You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RebaseCommand.java 55KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722
  1. /*
  2. * Copyright (C) 2010, 2013 Mathias Kinzler <mathias.kinzler@sap.com>
  3. * Copyright (C) 2016, Laurent Delaigue <laurent.delaigue@obeo.fr>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.api;
  45. import java.io.ByteArrayOutputStream;
  46. import java.io.File;
  47. import java.io.FileNotFoundException;
  48. import java.io.FileOutputStream;
  49. import java.io.IOException;
  50. import java.text.MessageFormat;
  51. import java.util.ArrayList;
  52. import java.util.Collection;
  53. import java.util.Collections;
  54. import java.util.HashMap;
  55. import java.util.Iterator;
  56. import java.util.LinkedList;
  57. import java.util.List;
  58. import java.util.Map;
  59. import java.util.regex.Matcher;
  60. import java.util.regex.Pattern;
  61. import org.eclipse.jgit.api.RebaseResult.Status;
  62. import org.eclipse.jgit.api.ResetCommand.ResetType;
  63. import org.eclipse.jgit.api.errors.CheckoutConflictException;
  64. import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
  65. import org.eclipse.jgit.api.errors.GitAPIException;
  66. import org.eclipse.jgit.api.errors.InvalidRebaseStepException;
  67. import org.eclipse.jgit.api.errors.InvalidRefNameException;
  68. import org.eclipse.jgit.api.errors.JGitInternalException;
  69. import org.eclipse.jgit.api.errors.NoHeadException;
  70. import org.eclipse.jgit.api.errors.NoMessageException;
  71. import org.eclipse.jgit.api.errors.RefAlreadyExistsException;
  72. import org.eclipse.jgit.api.errors.RefNotFoundException;
  73. import org.eclipse.jgit.api.errors.StashApplyFailureException;
  74. import org.eclipse.jgit.api.errors.UnmergedPathsException;
  75. import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
  76. import org.eclipse.jgit.diff.DiffFormatter;
  77. import org.eclipse.jgit.dircache.DirCache;
  78. import org.eclipse.jgit.dircache.DirCacheCheckout;
  79. import org.eclipse.jgit.dircache.DirCacheIterator;
  80. import org.eclipse.jgit.errors.RevisionSyntaxException;
  81. import org.eclipse.jgit.internal.JGitText;
  82. import org.eclipse.jgit.lib.AbbreviatedObjectId;
  83. import org.eclipse.jgit.lib.AnyObjectId;
  84. import org.eclipse.jgit.lib.ConfigConstants;
  85. import org.eclipse.jgit.lib.Constants;
  86. import org.eclipse.jgit.lib.NullProgressMonitor;
  87. import org.eclipse.jgit.lib.ObjectId;
  88. import org.eclipse.jgit.lib.ObjectReader;
  89. import org.eclipse.jgit.lib.PersonIdent;
  90. import org.eclipse.jgit.lib.ProgressMonitor;
  91. import org.eclipse.jgit.lib.RebaseTodoLine;
  92. import org.eclipse.jgit.lib.RebaseTodoLine.Action;
  93. import org.eclipse.jgit.lib.Ref;
  94. import org.eclipse.jgit.lib.RefUpdate;
  95. import org.eclipse.jgit.lib.RefUpdate.Result;
  96. import org.eclipse.jgit.lib.Repository;
  97. import org.eclipse.jgit.merge.MergeStrategy;
  98. import org.eclipse.jgit.revwalk.RevCommit;
  99. import org.eclipse.jgit.revwalk.RevWalk;
  100. import org.eclipse.jgit.revwalk.filter.RevFilter;
  101. import org.eclipse.jgit.submodule.SubmoduleWalk.IgnoreSubmoduleMode;
  102. import org.eclipse.jgit.treewalk.TreeWalk;
  103. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  104. import org.eclipse.jgit.util.FileUtils;
  105. import org.eclipse.jgit.util.IO;
  106. import org.eclipse.jgit.util.RawParseUtils;
  107. /**
  108. * A class used to execute a {@code Rebase} command. It has setters for all
  109. * supported options and arguments of this command and a {@link #call()} method
  110. * to finally execute the command. Each instance of this class should only be
  111. * used for one invocation of the command (means: one call to {@link #call()})
  112. * <p>
  113. *
  114. * @see <a
  115. * href="http://www.kernel.org/pub/software/scm/git/docs/git-rebase.html"
  116. * >Git documentation about Rebase</a>
  117. */
  118. public class RebaseCommand extends GitCommand<RebaseResult> {
  119. /**
  120. * The name of the "rebase-merge" folder for interactive rebases.
  121. */
  122. public static final String REBASE_MERGE = "rebase-merge"; //$NON-NLS-1$
  123. /**
  124. * The name of the "rebase-apply" folder for non-interactive rebases.
  125. */
  126. private static final String REBASE_APPLY = "rebase-apply"; //$NON-NLS-1$
  127. /**
  128. * The name of the "stopped-sha" file
  129. */
  130. public static final String STOPPED_SHA = "stopped-sha"; //$NON-NLS-1$
  131. private static final String AUTHOR_SCRIPT = "author-script"; //$NON-NLS-1$
  132. private static final String DONE = "done"; //$NON-NLS-1$
  133. private static final String GIT_AUTHOR_DATE = "GIT_AUTHOR_DATE"; //$NON-NLS-1$
  134. private static final String GIT_AUTHOR_EMAIL = "GIT_AUTHOR_EMAIL"; //$NON-NLS-1$
  135. private static final String GIT_AUTHOR_NAME = "GIT_AUTHOR_NAME"; //$NON-NLS-1$
  136. private static final String GIT_REBASE_TODO = "git-rebase-todo"; //$NON-NLS-1$
  137. private static final String HEAD_NAME = "head-name"; //$NON-NLS-1$
  138. private static final String INTERACTIVE = "interactive"; //$NON-NLS-1$
  139. private static final String QUIET = "quiet"; //$NON-NLS-1$
  140. private static final String MESSAGE = "message"; //$NON-NLS-1$
  141. private static final String ONTO = "onto"; //$NON-NLS-1$
  142. private static final String ONTO_NAME = "onto-name"; //$NON-NLS-1$
  143. private static final String PATCH = "patch"; //$NON-NLS-1$
  144. private static final String REBASE_HEAD = "head"; //$NON-NLS-1$
  145. private static final String AMEND = "amend"; //$NON-NLS-1$
  146. private static final String MESSAGE_FIXUP = "message-fixup"; //$NON-NLS-1$
  147. private static final String MESSAGE_SQUASH = "message-squash"; //$NON-NLS-1$
  148. private static final String AUTOSTASH = "autostash"; //$NON-NLS-1$
  149. private static final String AUTOSTASH_MSG = "On {0}: autostash"; //$NON-NLS-1$
  150. /**
  151. * The folder containing the hashes of (potentially) rewritten commits when
  152. * --preserve-merges is used.
  153. */
  154. private static final String REWRITTEN = "rewritten"; //$NON-NLS-1$
  155. /**
  156. * File containing the current commit(s) to cherry pick when --preserve-merges
  157. * is used.
  158. */
  159. private static final String CURRENT_COMMIT = "current-commit"; //$NON-NLS-1$
  160. private static final String REFLOG_PREFIX = "rebase:"; //$NON-NLS-1$
  161. /**
  162. * The available operations
  163. */
  164. public enum Operation {
  165. /**
  166. * Initiates rebase
  167. */
  168. BEGIN,
  169. /**
  170. * Continues after a conflict resolution
  171. */
  172. CONTINUE,
  173. /**
  174. * Skips the "current" commit
  175. */
  176. SKIP,
  177. /**
  178. * Aborts and resets the current rebase
  179. */
  180. ABORT,
  181. /**
  182. * Starts processing steps
  183. * @since 3.2
  184. */
  185. PROCESS_STEPS;
  186. }
  187. private Operation operation = Operation.BEGIN;
  188. private RevCommit upstreamCommit;
  189. private String upstreamCommitName;
  190. private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;
  191. private final RevWalk walk;
  192. private final RebaseState rebaseState;
  193. private InteractiveHandler interactiveHandler;
  194. private boolean stopAfterInitialization = false;
  195. private RevCommit newHead;
  196. private boolean lastStepWasForward;
  197. private MergeStrategy strategy = MergeStrategy.RECURSIVE;
  198. private boolean preserveMerges = false;
  199. /**
  200. * @param repo
  201. */
  202. protected RebaseCommand(Repository repo) {
  203. super(repo);
  204. walk = new RevWalk(repo);
  205. rebaseState = new RebaseState(repo.getDirectory());
  206. }
  207. /**
  208. * Executes the {@code Rebase} command with all the options and parameters
  209. * collected by the setter methods of this class. Each instance of this
  210. * class should only be used for one invocation of the command. Don't call
  211. * this method twice on an instance.
  212. *
  213. * @return an object describing the result of this command
  214. * @throws GitAPIException
  215. * @throws WrongRepositoryStateException
  216. * @throws NoHeadException
  217. * @throws RefNotFoundException
  218. */
  219. public RebaseResult call() throws GitAPIException, NoHeadException,
  220. RefNotFoundException, WrongRepositoryStateException {
  221. newHead = null;
  222. lastStepWasForward = false;
  223. checkCallable();
  224. checkParameters();
  225. try {
  226. switch (operation) {
  227. case ABORT:
  228. try {
  229. return abort(RebaseResult.ABORTED_RESULT);
  230. } catch (IOException ioe) {
  231. throw new JGitInternalException(ioe.getMessage(), ioe);
  232. }
  233. case PROCESS_STEPS:
  234. // fall through
  235. case SKIP:
  236. // fall through
  237. case CONTINUE:
  238. String upstreamCommitId = rebaseState.readFile(ONTO);
  239. try {
  240. upstreamCommitName = rebaseState.readFile(ONTO_NAME);
  241. } catch (FileNotFoundException e) {
  242. // Fall back to commit ID if file doesn't exist (e.g. rebase
  243. // was started by C Git)
  244. upstreamCommitName = upstreamCommitId;
  245. }
  246. this.upstreamCommit = walk.parseCommit(repo
  247. .resolve(upstreamCommitId));
  248. preserveMerges = rebaseState.getRewrittenDir().exists();
  249. break;
  250. case BEGIN:
  251. autoStash();
  252. if (stopAfterInitialization
  253. || !walk.isMergedInto(
  254. walk.parseCommit(repo.resolve(Constants.HEAD)),
  255. upstreamCommit)) {
  256. org.eclipse.jgit.api.Status status = Git.wrap(repo)
  257. .status().setIgnoreSubmodules(IgnoreSubmoduleMode.ALL).call();
  258. if (status.hasUncommittedChanges()) {
  259. List<String> list = new ArrayList<String>();
  260. list.addAll(status.getUncommittedChanges());
  261. return RebaseResult.uncommittedChanges(list);
  262. }
  263. }
  264. RebaseResult res = initFilesAndRewind();
  265. if (stopAfterInitialization)
  266. return RebaseResult.INTERACTIVE_PREPARED_RESULT;
  267. if (res != null) {
  268. autoStashApply();
  269. if (rebaseState.getDir().exists())
  270. FileUtils.delete(rebaseState.getDir(),
  271. FileUtils.RECURSIVE);
  272. return res;
  273. }
  274. }
  275. if (monitor.isCancelled())
  276. return abort(RebaseResult.ABORTED_RESULT);
  277. if (operation == Operation.CONTINUE) {
  278. newHead = continueRebase();
  279. List<RebaseTodoLine> doneLines = repo.readRebaseTodo(
  280. rebaseState.getPath(DONE), true);
  281. RebaseTodoLine step = doneLines.get(doneLines.size() - 1);
  282. if (newHead != null
  283. && step.getAction() != Action.PICK) {
  284. RebaseTodoLine newStep = new RebaseTodoLine(
  285. step.getAction(),
  286. AbbreviatedObjectId.fromObjectId(newHead),
  287. step.getShortMessage());
  288. RebaseResult result = processStep(newStep, false);
  289. if (result != null)
  290. return result;
  291. }
  292. File amendFile = rebaseState.getFile(AMEND);
  293. boolean amendExists = amendFile.exists();
  294. if (amendExists) {
  295. FileUtils.delete(amendFile);
  296. }
  297. if (newHead == null && !amendExists) {
  298. // continueRebase() returns null only if no commit was
  299. // neccessary. This means that no changes where left over
  300. // after resolving all conflicts. In this case, cgit stops
  301. // and displays a nice message to the user, telling him to
  302. // either do changes or skip the commit instead of continue.
  303. return RebaseResult.NOTHING_TO_COMMIT_RESULT;
  304. }
  305. }
  306. if (operation == Operation.SKIP)
  307. newHead = checkoutCurrentHead();
  308. List<RebaseTodoLine> steps = repo.readRebaseTodo(
  309. rebaseState.getPath(GIT_REBASE_TODO), false);
  310. if (steps.size() == 0) {
  311. return finishRebase(walk.parseCommit(repo.resolve(Constants.HEAD)), false);
  312. }
  313. if (isInteractive()) {
  314. interactiveHandler.prepareSteps(steps);
  315. repo.writeRebaseTodoFile(rebaseState.getPath(GIT_REBASE_TODO),
  316. steps, false);
  317. }
  318. checkSteps(steps);
  319. for (int i = 0; i < steps.size(); i++) {
  320. RebaseTodoLine step = steps.get(i);
  321. popSteps(1);
  322. RebaseResult result = processStep(step, true);
  323. if (result != null) {
  324. return result;
  325. }
  326. }
  327. return finishRebase(newHead, lastStepWasForward);
  328. } catch (CheckoutConflictException cce) {
  329. return RebaseResult.conflicts(cce.getConflictingPaths());
  330. } catch (IOException ioe) {
  331. throw new JGitInternalException(ioe.getMessage(), ioe);
  332. }
  333. }
  334. private void autoStash() throws GitAPIException, IOException {
  335. if (repo.getConfig().getBoolean(ConfigConstants.CONFIG_REBASE_SECTION,
  336. ConfigConstants.CONFIG_KEY_AUTOSTASH, false)) {
  337. String message = MessageFormat.format(
  338. AUTOSTASH_MSG,
  339. Repository
  340. .shortenRefName(getHeadName(getHead())));
  341. RevCommit stashCommit = Git.wrap(repo).stashCreate().setRef(null)
  342. .setWorkingDirectoryMessage(
  343. message)
  344. .call();
  345. if (stashCommit != null) {
  346. FileUtils.mkdir(rebaseState.getDir());
  347. rebaseState.createFile(AUTOSTASH, stashCommit.getName());
  348. }
  349. }
  350. }
  351. private boolean autoStashApply() throws IOException, GitAPIException {
  352. boolean conflicts = false;
  353. if (rebaseState.getFile(AUTOSTASH).exists()) {
  354. String stash = rebaseState.readFile(AUTOSTASH);
  355. try {
  356. Git.wrap(repo).stashApply().setStashRef(stash)
  357. .ignoreRepositoryState(true).setStrategy(strategy)
  358. .call();
  359. } catch (StashApplyFailureException e) {
  360. conflicts = true;
  361. try (RevWalk rw = new RevWalk(repo)) {
  362. ObjectId stashId = repo.resolve(stash);
  363. RevCommit commit = rw.parseCommit(stashId);
  364. updateStashRef(commit, commit.getAuthorIdent(),
  365. commit.getShortMessage());
  366. }
  367. }
  368. }
  369. return conflicts;
  370. }
  371. private void updateStashRef(ObjectId commitId, PersonIdent refLogIdent,
  372. String refLogMessage) throws IOException {
  373. Ref currentRef = repo.exactRef(Constants.R_STASH);
  374. RefUpdate refUpdate = repo.updateRef(Constants.R_STASH);
  375. refUpdate.setNewObjectId(commitId);
  376. refUpdate.setRefLogIdent(refLogIdent);
  377. refUpdate.setRefLogMessage(refLogMessage, false);
  378. if (currentRef != null)
  379. refUpdate.setExpectedOldObjectId(currentRef.getObjectId());
  380. else
  381. refUpdate.setExpectedOldObjectId(ObjectId.zeroId());
  382. refUpdate.forceUpdate();
  383. }
  384. private RebaseResult processStep(RebaseTodoLine step, boolean shouldPick)
  385. throws IOException, GitAPIException {
  386. if (Action.COMMENT.equals(step.getAction()))
  387. return null;
  388. if (preserveMerges
  389. && shouldPick
  390. && (Action.EDIT.equals(step.getAction()) || Action.PICK
  391. .equals(step.getAction()))) {
  392. writeRewrittenHashes();
  393. }
  394. ObjectReader or = repo.newObjectReader();
  395. Collection<ObjectId> ids = or.resolve(step.getCommit());
  396. if (ids.size() != 1)
  397. throw new JGitInternalException(
  398. JGitText.get().cannotResolveUniquelyAbbrevObjectId);
  399. RevCommit commitToPick = walk.parseCommit(ids.iterator().next());
  400. if (shouldPick) {
  401. if (monitor.isCancelled())
  402. return RebaseResult.result(Status.STOPPED, commitToPick);
  403. RebaseResult result = cherryPickCommit(commitToPick);
  404. if (result != null)
  405. return result;
  406. }
  407. boolean isSquash = false;
  408. switch (step.getAction()) {
  409. case PICK:
  410. return null; // continue rebase process on pick command
  411. case REWORD:
  412. String oldMessage = commitToPick.getFullMessage();
  413. String newMessage = interactiveHandler
  414. .modifyCommitMessage(oldMessage);
  415. newHead = new Git(repo).commit().setMessage(newMessage)
  416. .setAmend(true).setNoVerify(true).call();
  417. return null;
  418. case EDIT:
  419. rebaseState.createFile(AMEND, commitToPick.name());
  420. return stop(commitToPick, Status.EDIT);
  421. case COMMENT:
  422. break;
  423. case SQUASH:
  424. isSquash = true;
  425. //$FALL-THROUGH$
  426. case FIXUP:
  427. resetSoftToParent();
  428. List<RebaseTodoLine> steps = repo.readRebaseTodo(
  429. rebaseState.getPath(GIT_REBASE_TODO), false);
  430. RebaseTodoLine nextStep = steps.size() > 0 ? steps.get(0) : null;
  431. File messageFixupFile = rebaseState.getFile(MESSAGE_FIXUP);
  432. File messageSquashFile = rebaseState.getFile(MESSAGE_SQUASH);
  433. if (isSquash && messageFixupFile.exists())
  434. messageFixupFile.delete();
  435. newHead = doSquashFixup(isSquash, commitToPick, nextStep,
  436. messageFixupFile, messageSquashFile);
  437. }
  438. return null;
  439. }
  440. private RebaseResult cherryPickCommit(RevCommit commitToPick)
  441. throws IOException, GitAPIException, NoMessageException,
  442. UnmergedPathsException, ConcurrentRefUpdateException,
  443. WrongRepositoryStateException, NoHeadException {
  444. try {
  445. monitor.beginTask(MessageFormat.format(
  446. JGitText.get().applyingCommit,
  447. commitToPick.getShortMessage()), ProgressMonitor.UNKNOWN);
  448. if (preserveMerges)
  449. return cherryPickCommitPreservingMerges(commitToPick);
  450. else
  451. return cherryPickCommitFlattening(commitToPick);
  452. } finally {
  453. monitor.endTask();
  454. }
  455. }
  456. private RebaseResult cherryPickCommitFlattening(RevCommit commitToPick)
  457. throws IOException, GitAPIException, NoMessageException,
  458. UnmergedPathsException, ConcurrentRefUpdateException,
  459. WrongRepositoryStateException, NoHeadException {
  460. // If the first parent of commitToPick is the current HEAD,
  461. // we do a fast-forward instead of cherry-pick to avoid
  462. // unnecessary object rewriting
  463. newHead = tryFastForward(commitToPick);
  464. lastStepWasForward = newHead != null;
  465. if (!lastStepWasForward) {
  466. // TODO if the content of this commit is already merged
  467. // here we should skip this step in order to avoid
  468. // confusing pseudo-changed
  469. String ourCommitName = getOurCommitName();
  470. try (Git git = new Git(repo)) {
  471. CherryPickResult cherryPickResult = git.cherryPick()
  472. .include(commitToPick).setOurCommitName(ourCommitName)
  473. .setReflogPrefix(REFLOG_PREFIX).setStrategy(strategy)
  474. .call();
  475. switch (cherryPickResult.getStatus()) {
  476. case FAILED:
  477. if (operation == Operation.BEGIN)
  478. return abort(RebaseResult
  479. .failed(cherryPickResult.getFailingPaths()));
  480. else
  481. return stop(commitToPick, Status.STOPPED);
  482. case CONFLICTING:
  483. return stop(commitToPick, Status.STOPPED);
  484. case OK:
  485. newHead = cherryPickResult.getNewHead();
  486. }
  487. }
  488. }
  489. return null;
  490. }
  491. private RebaseResult cherryPickCommitPreservingMerges(RevCommit commitToPick)
  492. throws IOException, GitAPIException, NoMessageException,
  493. UnmergedPathsException, ConcurrentRefUpdateException,
  494. WrongRepositoryStateException, NoHeadException {
  495. writeCurrentCommit(commitToPick);
  496. List<RevCommit> newParents = getNewParents(commitToPick);
  497. boolean otherParentsUnchanged = true;
  498. for (int i = 1; i < commitToPick.getParentCount(); i++)
  499. otherParentsUnchanged &= newParents.get(i).equals(
  500. commitToPick.getParent(i));
  501. // If the first parent of commitToPick is the current HEAD,
  502. // we do a fast-forward instead of cherry-pick to avoid
  503. // unnecessary object rewriting
  504. newHead = otherParentsUnchanged ? tryFastForward(commitToPick) : null;
  505. lastStepWasForward = newHead != null;
  506. if (!lastStepWasForward) {
  507. ObjectId headId = getHead().getObjectId();
  508. // getHead() checks for null
  509. assert headId != null;
  510. if (!AnyObjectId.equals(headId, newParents.get(0)))
  511. checkoutCommit(headId.getName(), newParents.get(0));
  512. // Use the cherry-pick strategy if all non-first parents did not
  513. // change. This is different from C Git, which always uses the merge
  514. // strategy (see below).
  515. try (Git git = new Git(repo)) {
  516. if (otherParentsUnchanged) {
  517. boolean isMerge = commitToPick.getParentCount() > 1;
  518. String ourCommitName = getOurCommitName();
  519. CherryPickCommand pickCommand = git.cherryPick()
  520. .include(commitToPick)
  521. .setOurCommitName(ourCommitName)
  522. .setReflogPrefix(REFLOG_PREFIX)
  523. .setStrategy(strategy);
  524. if (isMerge) {
  525. pickCommand.setMainlineParentNumber(1);
  526. // We write a MERGE_HEAD and later commit explicitly
  527. pickCommand.setNoCommit(true);
  528. writeMergeInfo(commitToPick, newParents);
  529. }
  530. CherryPickResult cherryPickResult = pickCommand.call();
  531. switch (cherryPickResult.getStatus()) {
  532. case FAILED:
  533. if (operation == Operation.BEGIN)
  534. return abort(RebaseResult.failed(
  535. cherryPickResult.getFailingPaths()));
  536. else
  537. return stop(commitToPick, Status.STOPPED);
  538. case CONFLICTING:
  539. return stop(commitToPick, Status.STOPPED);
  540. case OK:
  541. if (isMerge) {
  542. // Commit the merge (setup above using
  543. // writeMergeInfo())
  544. CommitCommand commit = git.commit();
  545. commit.setAuthor(commitToPick.getAuthorIdent());
  546. commit.setReflogComment(REFLOG_PREFIX + " " //$NON-NLS-1$
  547. + commitToPick.getShortMessage());
  548. newHead = commit.call();
  549. } else
  550. newHead = cherryPickResult.getNewHead();
  551. break;
  552. }
  553. } else {
  554. // Use the merge strategy to redo merges, which had some of
  555. // their non-first parents rewritten
  556. MergeCommand merge = git.merge()
  557. .setFastForward(MergeCommand.FastForwardMode.NO_FF)
  558. .setProgressMonitor(monitor)
  559. .setCommit(false);
  560. for (int i = 1; i < commitToPick.getParentCount(); i++)
  561. merge.include(newParents.get(i));
  562. MergeResult mergeResult = merge.call();
  563. if (mergeResult.getMergeStatus().isSuccessful()) {
  564. CommitCommand commit = git.commit();
  565. commit.setAuthor(commitToPick.getAuthorIdent());
  566. commit.setMessage(commitToPick.getFullMessage());
  567. commit.setReflogComment(REFLOG_PREFIX + " " //$NON-NLS-1$
  568. + commitToPick.getShortMessage());
  569. newHead = commit.call();
  570. } else {
  571. if (operation == Operation.BEGIN && mergeResult
  572. .getMergeStatus() == MergeResult.MergeStatus.FAILED)
  573. return abort(RebaseResult
  574. .failed(mergeResult.getFailingPaths()));
  575. return stop(commitToPick, Status.STOPPED);
  576. }
  577. }
  578. }
  579. }
  580. return null;
  581. }
  582. // Prepare MERGE_HEAD and message for the next commit
  583. private void writeMergeInfo(RevCommit commitToPick,
  584. List<RevCommit> newParents) throws IOException {
  585. repo.writeMergeHeads(newParents.subList(1, newParents.size()));
  586. repo.writeMergeCommitMsg(commitToPick.getFullMessage());
  587. }
  588. // Get the rewritten equivalents for the parents of the given commit
  589. private List<RevCommit> getNewParents(RevCommit commitToPick)
  590. throws IOException {
  591. List<RevCommit> newParents = new ArrayList<RevCommit>();
  592. for (int p = 0; p < commitToPick.getParentCount(); p++) {
  593. String parentHash = commitToPick.getParent(p).getName();
  594. if (!new File(rebaseState.getRewrittenDir(), parentHash).exists())
  595. newParents.add(commitToPick.getParent(p));
  596. else {
  597. String newParent = RebaseState.readFile(
  598. rebaseState.getRewrittenDir(), parentHash);
  599. if (newParent.length() == 0)
  600. newParents.add(walk.parseCommit(repo
  601. .resolve(Constants.HEAD)));
  602. else
  603. newParents.add(walk.parseCommit(ObjectId
  604. .fromString(newParent)));
  605. }
  606. }
  607. return newParents;
  608. }
  609. private void writeCurrentCommit(RevCommit commit) throws IOException {
  610. RebaseState.appendToFile(rebaseState.getFile(CURRENT_COMMIT),
  611. commit.name());
  612. }
  613. private void writeRewrittenHashes() throws RevisionSyntaxException,
  614. IOException, RefNotFoundException {
  615. File currentCommitFile = rebaseState.getFile(CURRENT_COMMIT);
  616. if (!currentCommitFile.exists())
  617. return;
  618. ObjectId headId = getHead().getObjectId();
  619. // getHead() checks for null
  620. assert headId != null;
  621. String head = headId.getName();
  622. String currentCommits = rebaseState.readFile(CURRENT_COMMIT);
  623. for (String current : currentCommits.split("\n")) //$NON-NLS-1$
  624. RebaseState
  625. .createFile(rebaseState.getRewrittenDir(), current, head);
  626. FileUtils.delete(currentCommitFile);
  627. }
  628. private RebaseResult finishRebase(RevCommit finalHead,
  629. boolean lastStepIsForward) throws IOException, GitAPIException {
  630. String headName = rebaseState.readFile(HEAD_NAME);
  631. updateHead(headName, finalHead, upstreamCommit);
  632. boolean stashConflicts = autoStashApply();
  633. FileUtils.delete(rebaseState.getDir(), FileUtils.RECURSIVE);
  634. if (stashConflicts)
  635. return RebaseResult.STASH_APPLY_CONFLICTS_RESULT;
  636. if (lastStepIsForward || finalHead == null)
  637. return RebaseResult.FAST_FORWARD_RESULT;
  638. return RebaseResult.OK_RESULT;
  639. }
  640. private void checkSteps(List<RebaseTodoLine> steps)
  641. throws InvalidRebaseStepException, IOException {
  642. if (steps.isEmpty())
  643. return;
  644. if (RebaseTodoLine.Action.SQUASH.equals(steps.get(0).getAction())
  645. || RebaseTodoLine.Action.FIXUP.equals(steps.get(0).getAction())) {
  646. if (!rebaseState.getFile(DONE).exists()
  647. || rebaseState.readFile(DONE).trim().length() == 0) {
  648. throw new InvalidRebaseStepException(MessageFormat.format(
  649. JGitText.get().cannotSquashFixupWithoutPreviousCommit,
  650. steps.get(0).getAction().name()));
  651. }
  652. }
  653. }
  654. private RevCommit doSquashFixup(boolean isSquash, RevCommit commitToPick,
  655. RebaseTodoLine nextStep, File messageFixup, File messageSquash)
  656. throws IOException, GitAPIException {
  657. if (!messageSquash.exists()) {
  658. // init squash/fixup sequence
  659. ObjectId headId = repo.resolve(Constants.HEAD);
  660. RevCommit previousCommit = walk.parseCommit(headId);
  661. initializeSquashFixupFile(MESSAGE_SQUASH,
  662. previousCommit.getFullMessage());
  663. if (!isSquash)
  664. initializeSquashFixupFile(MESSAGE_FIXUP,
  665. previousCommit.getFullMessage());
  666. }
  667. String currSquashMessage = rebaseState
  668. .readFile(MESSAGE_SQUASH);
  669. int count = parseSquashFixupSequenceCount(currSquashMessage) + 1;
  670. String content = composeSquashMessage(isSquash,
  671. commitToPick, currSquashMessage, count);
  672. rebaseState.createFile(MESSAGE_SQUASH, content);
  673. if (messageFixup.exists())
  674. rebaseState.createFile(MESSAGE_FIXUP, content);
  675. return squashIntoPrevious(
  676. !messageFixup.exists(),
  677. nextStep);
  678. }
  679. private void resetSoftToParent() throws IOException,
  680. GitAPIException, CheckoutConflictException {
  681. Ref ref = repo.exactRef(Constants.ORIG_HEAD);
  682. ObjectId orig_head = ref == null ? null : ref.getObjectId();
  683. try {
  684. // we have already commited the cherry-picked commit.
  685. // what we need is to have changes introduced by this
  686. // commit to be on the index
  687. // resetting is a workaround
  688. Git.wrap(repo).reset().setMode(ResetType.SOFT)
  689. .setRef("HEAD~1").call(); //$NON-NLS-1$
  690. } finally {
  691. // set ORIG_HEAD back to where we started because soft
  692. // reset moved it
  693. repo.writeOrigHead(orig_head);
  694. }
  695. }
  696. private RevCommit squashIntoPrevious(boolean sequenceContainsSquash,
  697. RebaseTodoLine nextStep)
  698. throws IOException, GitAPIException {
  699. RevCommit retNewHead;
  700. String commitMessage = rebaseState
  701. .readFile(MESSAGE_SQUASH);
  702. try (Git git = new Git(repo)) {
  703. if (nextStep == null || ((nextStep.getAction() != Action.FIXUP)
  704. && (nextStep.getAction() != Action.SQUASH))) {
  705. // this is the last step in this sequence
  706. if (sequenceContainsSquash) {
  707. commitMessage = interactiveHandler
  708. .modifyCommitMessage(commitMessage);
  709. }
  710. retNewHead = git.commit()
  711. .setMessage(stripCommentLines(commitMessage))
  712. .setAmend(true).setNoVerify(true).call();
  713. rebaseState.getFile(MESSAGE_SQUASH).delete();
  714. rebaseState.getFile(MESSAGE_FIXUP).delete();
  715. } else {
  716. // Next step is either Squash or Fixup
  717. retNewHead = git.commit().setMessage(commitMessage)
  718. .setAmend(true).setNoVerify(true).call();
  719. }
  720. }
  721. return retNewHead;
  722. }
  723. private static String stripCommentLines(String commitMessage) {
  724. StringBuilder result = new StringBuilder();
  725. for (String line : commitMessage.split("\n")) { //$NON-NLS-1$
  726. if (!line.trim().startsWith("#")) //$NON-NLS-1$
  727. result.append(line).append("\n"); //$NON-NLS-1$
  728. }
  729. if (!commitMessage.endsWith("\n")) //$NON-NLS-1$
  730. result.deleteCharAt(result.length() - 1);
  731. return result.toString();
  732. }
  733. @SuppressWarnings("nls")
  734. private static String composeSquashMessage(boolean isSquash,
  735. RevCommit commitToPick, String currSquashMessage, int count) {
  736. StringBuilder sb = new StringBuilder();
  737. String ordinal = getOrdinal(count);
  738. sb.setLength(0);
  739. sb.append("# This is a combination of ").append(count)
  740. .append(" commits.\n");
  741. // Add the previous message without header (i.e first line)
  742. sb.append(currSquashMessage.substring(currSquashMessage.indexOf("\n") + 1));
  743. sb.append("\n");
  744. if (isSquash) {
  745. sb.append("# This is the ").append(count).append(ordinal)
  746. .append(" commit message:\n");
  747. sb.append(commitToPick.getFullMessage());
  748. } else {
  749. sb.append("# The ").append(count).append(ordinal)
  750. .append(" commit message will be skipped:\n# ");
  751. sb.append(commitToPick.getFullMessage().replaceAll("([\n\r])",
  752. "$1# "));
  753. }
  754. return sb.toString();
  755. }
  756. private static String getOrdinal(int count) {
  757. switch (count % 10) {
  758. case 1:
  759. return "st"; //$NON-NLS-1$
  760. case 2:
  761. return "nd"; //$NON-NLS-1$
  762. case 3:
  763. return "rd"; //$NON-NLS-1$
  764. default:
  765. return "th"; //$NON-NLS-1$
  766. }
  767. }
  768. /**
  769. * Parse the count from squashed commit messages
  770. *
  771. * @param currSquashMessage
  772. * the squashed commit message to be parsed
  773. * @return the count of squashed messages in the given string
  774. */
  775. static int parseSquashFixupSequenceCount(String currSquashMessage) {
  776. String regex = "This is a combination of (.*) commits"; //$NON-NLS-1$
  777. String firstLine = currSquashMessage.substring(0,
  778. currSquashMessage.indexOf("\n")); //$NON-NLS-1$
  779. Pattern pattern = Pattern.compile(regex);
  780. Matcher matcher = pattern.matcher(firstLine);
  781. if (!matcher.find())
  782. throw new IllegalArgumentException();
  783. return Integer.parseInt(matcher.group(1));
  784. }
  785. private void initializeSquashFixupFile(String messageFile,
  786. String fullMessage) throws IOException {
  787. rebaseState
  788. .createFile(
  789. messageFile,
  790. "# This is a combination of 1 commits.\n# The first commit's message is:\n" + fullMessage); //$NON-NLS-1$);
  791. }
  792. private String getOurCommitName() {
  793. // If onto is different from upstream, this should say "onto", but
  794. // RebaseCommand doesn't support a different "onto" at the moment.
  795. String ourCommitName = "Upstream, based on " //$NON-NLS-1$
  796. + Repository.shortenRefName(upstreamCommitName);
  797. return ourCommitName;
  798. }
  799. private void updateHead(String headName, RevCommit aNewHead, RevCommit onto)
  800. throws IOException {
  801. // point the previous head (if any) to the new commit
  802. if (headName.startsWith(Constants.R_REFS)) {
  803. RefUpdate rup = repo.updateRef(headName);
  804. rup.setNewObjectId(aNewHead);
  805. rup.setRefLogMessage("rebase finished: " + headName + " onto " //$NON-NLS-1$ //$NON-NLS-2$
  806. + onto.getName(), false);
  807. Result res = rup.forceUpdate();
  808. switch (res) {
  809. case FAST_FORWARD:
  810. case FORCED:
  811. case NO_CHANGE:
  812. break;
  813. default:
  814. throw new JGitInternalException(
  815. JGitText.get().updatingHeadFailed);
  816. }
  817. rup = repo.updateRef(Constants.HEAD);
  818. rup.setRefLogMessage("rebase finished: returning to " + headName, //$NON-NLS-1$
  819. false);
  820. res = rup.link(headName);
  821. switch (res) {
  822. case FAST_FORWARD:
  823. case FORCED:
  824. case NO_CHANGE:
  825. break;
  826. default:
  827. throw new JGitInternalException(
  828. JGitText.get().updatingHeadFailed);
  829. }
  830. }
  831. }
  832. private RevCommit checkoutCurrentHead() throws IOException, NoHeadException {
  833. ObjectId headTree = repo.resolve(Constants.HEAD + "^{tree}"); //$NON-NLS-1$
  834. if (headTree == null)
  835. throw new NoHeadException(
  836. JGitText.get().cannotRebaseWithoutCurrentHead);
  837. DirCache dc = repo.lockDirCache();
  838. try {
  839. DirCacheCheckout dco = new DirCacheCheckout(repo, dc, headTree);
  840. dco.setFailOnConflict(false);
  841. boolean needsDeleteFiles = dco.checkout();
  842. if (needsDeleteFiles) {
  843. List<String> fileList = dco.getToBeDeleted();
  844. for (String filePath : fileList) {
  845. File fileToDelete = new File(repo.getWorkTree(), filePath);
  846. if (repo.getFS().exists(fileToDelete))
  847. FileUtils.delete(fileToDelete, FileUtils.RECURSIVE
  848. | FileUtils.RETRY);
  849. }
  850. }
  851. } finally {
  852. dc.unlock();
  853. }
  854. try (RevWalk rw = new RevWalk(repo)) {
  855. RevCommit commit = rw.parseCommit(repo.resolve(Constants.HEAD));
  856. return commit;
  857. }
  858. }
  859. /**
  860. * @return the commit if we had to do a commit, otherwise null
  861. * @throws GitAPIException
  862. * @throws IOException
  863. */
  864. private RevCommit continueRebase() throws GitAPIException, IOException {
  865. // if there are still conflicts, we throw a specific Exception
  866. DirCache dc = repo.readDirCache();
  867. boolean hasUnmergedPaths = dc.hasUnmergedPaths();
  868. if (hasUnmergedPaths)
  869. throw new UnmergedPathsException();
  870. // determine whether we need to commit
  871. boolean needsCommit;
  872. try (TreeWalk treeWalk = new TreeWalk(repo)) {
  873. treeWalk.reset();
  874. treeWalk.setRecursive(true);
  875. treeWalk.addTree(new DirCacheIterator(dc));
  876. ObjectId id = repo.resolve(Constants.HEAD + "^{tree}"); //$NON-NLS-1$
  877. if (id == null)
  878. throw new NoHeadException(
  879. JGitText.get().cannotRebaseWithoutCurrentHead);
  880. treeWalk.addTree(id);
  881. treeWalk.setFilter(TreeFilter.ANY_DIFF);
  882. needsCommit = treeWalk.next();
  883. }
  884. if (needsCommit) {
  885. try (Git git = new Git(repo)) {
  886. CommitCommand commit = git.commit();
  887. commit.setMessage(rebaseState.readFile(MESSAGE));
  888. commit.setAuthor(parseAuthor());
  889. return commit.call();
  890. }
  891. }
  892. return null;
  893. }
  894. private PersonIdent parseAuthor() throws IOException {
  895. File authorScriptFile = rebaseState.getFile(AUTHOR_SCRIPT);
  896. byte[] raw;
  897. try {
  898. raw = IO.readFully(authorScriptFile);
  899. } catch (FileNotFoundException notFound) {
  900. if (authorScriptFile.exists()) {
  901. throw notFound;
  902. }
  903. return null;
  904. }
  905. return parseAuthor(raw);
  906. }
  907. private RebaseResult stop(RevCommit commitToPick, RebaseResult.Status status)
  908. throws IOException {
  909. PersonIdent author = commitToPick.getAuthorIdent();
  910. String authorScript = toAuthorScript(author);
  911. rebaseState.createFile(AUTHOR_SCRIPT, authorScript);
  912. rebaseState.createFile(MESSAGE, commitToPick.getFullMessage());
  913. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  914. try (DiffFormatter df = new DiffFormatter(bos)) {
  915. df.setRepository(repo);
  916. df.format(commitToPick.getParent(0), commitToPick);
  917. }
  918. rebaseState.createFile(PATCH, new String(bos.toByteArray(),
  919. Constants.CHARACTER_ENCODING));
  920. rebaseState.createFile(STOPPED_SHA,
  921. repo.newObjectReader()
  922. .abbreviate(
  923. commitToPick).name());
  924. // Remove cherry pick state file created by CherryPickCommand, it's not
  925. // needed for rebase
  926. repo.writeCherryPickHead(null);
  927. return RebaseResult.result(status, commitToPick);
  928. }
  929. String toAuthorScript(PersonIdent author) {
  930. StringBuilder sb = new StringBuilder(100);
  931. sb.append(GIT_AUTHOR_NAME);
  932. sb.append("='"); //$NON-NLS-1$
  933. sb.append(author.getName());
  934. sb.append("'\n"); //$NON-NLS-1$
  935. sb.append(GIT_AUTHOR_EMAIL);
  936. sb.append("='"); //$NON-NLS-1$
  937. sb.append(author.getEmailAddress());
  938. sb.append("'\n"); //$NON-NLS-1$
  939. // the command line uses the "external String"
  940. // representation for date and timezone
  941. sb.append(GIT_AUTHOR_DATE);
  942. sb.append("='"); //$NON-NLS-1$
  943. sb.append("@"); // @ for time in seconds since 1970 //$NON-NLS-1$
  944. String externalString = author.toExternalString();
  945. sb
  946. .append(externalString.substring(externalString
  947. .lastIndexOf('>') + 2));
  948. sb.append("'\n"); //$NON-NLS-1$
  949. return sb.toString();
  950. }
  951. /**
  952. * Removes the number of lines given in the parameter from the
  953. * <code>git-rebase-todo</code> file but preserves comments and other lines
  954. * that can not be parsed as steps
  955. *
  956. * @param numSteps
  957. * @throws IOException
  958. */
  959. private void popSteps(int numSteps) throws IOException {
  960. if (numSteps == 0)
  961. return;
  962. List<RebaseTodoLine> todoLines = new LinkedList<RebaseTodoLine>();
  963. List<RebaseTodoLine> poppedLines = new LinkedList<RebaseTodoLine>();
  964. for (RebaseTodoLine line : repo.readRebaseTodo(
  965. rebaseState.getPath(GIT_REBASE_TODO), true)) {
  966. if (poppedLines.size() >= numSteps
  967. || RebaseTodoLine.Action.COMMENT.equals(line.getAction()))
  968. todoLines.add(line);
  969. else
  970. poppedLines.add(line);
  971. }
  972. repo.writeRebaseTodoFile(rebaseState.getPath(GIT_REBASE_TODO),
  973. todoLines, false);
  974. if (poppedLines.size() > 0) {
  975. repo.writeRebaseTodoFile(rebaseState.getPath(DONE), poppedLines,
  976. true);
  977. }
  978. }
  979. private RebaseResult initFilesAndRewind() throws IOException,
  980. GitAPIException {
  981. // we need to store everything into files so that we can implement
  982. // --skip, --continue, and --abort
  983. Ref head = getHead();
  984. ObjectId headId = head.getObjectId();
  985. if (headId == null) {
  986. throw new RefNotFoundException(MessageFormat.format(
  987. JGitText.get().refNotResolved, Constants.HEAD));
  988. }
  989. String headName = getHeadName(head);
  990. RevCommit headCommit = walk.lookupCommit(headId);
  991. RevCommit upstream = walk.lookupCommit(upstreamCommit.getId());
  992. if (!isInteractive() && walk.isMergedInto(upstream, headCommit))
  993. return RebaseResult.UP_TO_DATE_RESULT;
  994. else if (!isInteractive() && walk.isMergedInto(headCommit, upstream)) {
  995. // head is already merged into upstream, fast-foward
  996. monitor.beginTask(MessageFormat.format(
  997. JGitText.get().resettingHead,
  998. upstreamCommit.getShortMessage()), ProgressMonitor.UNKNOWN);
  999. checkoutCommit(headName, upstreamCommit);
  1000. monitor.endTask();
  1001. updateHead(headName, upstreamCommit, upstream);
  1002. return RebaseResult.FAST_FORWARD_RESULT;
  1003. }
  1004. monitor.beginTask(JGitText.get().obtainingCommitsForCherryPick,
  1005. ProgressMonitor.UNKNOWN);
  1006. // create the folder for the meta information
  1007. FileUtils.mkdir(rebaseState.getDir(), true);
  1008. repo.writeOrigHead(headId);
  1009. rebaseState.createFile(REBASE_HEAD, headId.name());
  1010. rebaseState.createFile(HEAD_NAME, headName);
  1011. rebaseState.createFile(ONTO, upstreamCommit.name());
  1012. rebaseState.createFile(ONTO_NAME, upstreamCommitName);
  1013. if (isInteractive()) {
  1014. rebaseState.createFile(INTERACTIVE, ""); //$NON-NLS-1$
  1015. }
  1016. rebaseState.createFile(QUIET, ""); //$NON-NLS-1$
  1017. ArrayList<RebaseTodoLine> toDoSteps = new ArrayList<RebaseTodoLine>();
  1018. toDoSteps.add(new RebaseTodoLine("# Created by EGit: rebasing " + headId.name() //$NON-NLS-1$
  1019. + " onto " + upstreamCommit.name())); //$NON-NLS-1$
  1020. // determine the commits to be applied
  1021. List<RevCommit> cherryPickList = calculatePickList(headCommit);
  1022. ObjectReader reader = walk.getObjectReader();
  1023. for (RevCommit commit : cherryPickList)
  1024. toDoSteps.add(new RebaseTodoLine(Action.PICK, reader
  1025. .abbreviate(commit), commit.getShortMessage()));
  1026. repo.writeRebaseTodoFile(rebaseState.getPath(GIT_REBASE_TODO),
  1027. toDoSteps, false);
  1028. monitor.endTask();
  1029. // we rewind to the upstream commit
  1030. monitor.beginTask(MessageFormat.format(JGitText.get().rewinding,
  1031. upstreamCommit.getShortMessage()), ProgressMonitor.UNKNOWN);
  1032. boolean checkoutOk = false;
  1033. try {
  1034. checkoutOk = checkoutCommit(headName, upstreamCommit);
  1035. } finally {
  1036. if (!checkoutOk)
  1037. FileUtils.delete(rebaseState.getDir(), FileUtils.RECURSIVE);
  1038. }
  1039. monitor.endTask();
  1040. return null;
  1041. }
  1042. private List<RevCommit> calculatePickList(RevCommit headCommit)
  1043. throws GitAPIException, NoHeadException, IOException {
  1044. Iterable<RevCommit> commitsToUse;
  1045. try (Git git = new Git(repo)) {
  1046. LogCommand cmd = git.log().addRange(upstreamCommit, headCommit);
  1047. commitsToUse = cmd.call();
  1048. }
  1049. List<RevCommit> cherryPickList = new ArrayList<RevCommit>();
  1050. for (RevCommit commit : commitsToUse) {
  1051. if (preserveMerges || commit.getParentCount() == 1)
  1052. cherryPickList.add(commit);
  1053. }
  1054. Collections.reverse(cherryPickList);
  1055. if (preserveMerges) {
  1056. // When preserving merges we only rewrite commits which have at
  1057. // least one parent that is itself rewritten (or a merge base)
  1058. File rewrittenDir = rebaseState.getRewrittenDir();
  1059. FileUtils.mkdir(rewrittenDir, false);
  1060. walk.reset();
  1061. walk.setRevFilter(RevFilter.MERGE_BASE);
  1062. walk.markStart(upstreamCommit);
  1063. walk.markStart(headCommit);
  1064. RevCommit base;
  1065. while ((base = walk.next()) != null)
  1066. RebaseState.createFile(rewrittenDir, base.getName(),
  1067. upstreamCommit.getName());
  1068. Iterator<RevCommit> iterator = cherryPickList.iterator();
  1069. pickLoop: while(iterator.hasNext()){
  1070. RevCommit commit = iterator.next();
  1071. for (int i = 0; i < commit.getParentCount(); i++) {
  1072. boolean parentRewritten = new File(rewrittenDir, commit
  1073. .getParent(i).getName()).exists();
  1074. if (parentRewritten) {
  1075. new File(rewrittenDir, commit.getName()).createNewFile();
  1076. continue pickLoop;
  1077. }
  1078. }
  1079. // commit is only merged in, needs not be rewritten
  1080. iterator.remove();
  1081. }
  1082. }
  1083. return cherryPickList;
  1084. }
  1085. private static String getHeadName(Ref head) {
  1086. String headName;
  1087. if (head.isSymbolic()) {
  1088. headName = head.getTarget().getName();
  1089. } else {
  1090. ObjectId headId = head.getObjectId();
  1091. // the callers are checking this already
  1092. assert headId != null;
  1093. headName = headId.getName();
  1094. }
  1095. return headName;
  1096. }
  1097. private Ref getHead() throws IOException, RefNotFoundException {
  1098. Ref head = repo.exactRef(Constants.HEAD);
  1099. if (head == null || head.getObjectId() == null)
  1100. throw new RefNotFoundException(MessageFormat.format(
  1101. JGitText.get().refNotResolved, Constants.HEAD));
  1102. return head;
  1103. }
  1104. private boolean isInteractive() {
  1105. return interactiveHandler != null;
  1106. }
  1107. /**
  1108. * checks if we can fast-forward and returns the new head if it is possible
  1109. *
  1110. * @param newCommit
  1111. * @return the new head, or null
  1112. * @throws IOException
  1113. * @throws GitAPIException
  1114. */
  1115. public RevCommit tryFastForward(RevCommit newCommit) throws IOException,
  1116. GitAPIException {
  1117. Ref head = getHead();
  1118. ObjectId headId = head.getObjectId();
  1119. if (headId == null)
  1120. throw new RefNotFoundException(MessageFormat.format(
  1121. JGitText.get().refNotResolved, Constants.HEAD));
  1122. RevCommit headCommit = walk.lookupCommit(headId);
  1123. if (walk.isMergedInto(newCommit, headCommit))
  1124. return newCommit;
  1125. String headName = getHeadName(head);
  1126. return tryFastForward(headName, headCommit, newCommit);
  1127. }
  1128. private RevCommit tryFastForward(String headName, RevCommit oldCommit,
  1129. RevCommit newCommit) throws IOException, GitAPIException {
  1130. boolean tryRebase = false;
  1131. for (RevCommit parentCommit : newCommit.getParents())
  1132. if (parentCommit.equals(oldCommit))
  1133. tryRebase = true;
  1134. if (!tryRebase)
  1135. return null;
  1136. CheckoutCommand co = new CheckoutCommand(repo);
  1137. try {
  1138. co.setName(newCommit.name()).call();
  1139. if (headName.startsWith(Constants.R_HEADS)) {
  1140. RefUpdate rup = repo.updateRef(headName);
  1141. rup.setExpectedOldObjectId(oldCommit);
  1142. rup.setNewObjectId(newCommit);
  1143. rup.setRefLogMessage("Fast-forward from " + oldCommit.name() //$NON-NLS-1$
  1144. + " to " + newCommit.name(), false); //$NON-NLS-1$
  1145. Result res = rup.update(walk);
  1146. switch (res) {
  1147. case FAST_FORWARD:
  1148. case NO_CHANGE:
  1149. case FORCED:
  1150. break;
  1151. default:
  1152. throw new IOException("Could not fast-forward"); //$NON-NLS-1$
  1153. }
  1154. }
  1155. return newCommit;
  1156. } catch (RefAlreadyExistsException e) {
  1157. throw new JGitInternalException(e.getMessage(), e);
  1158. } catch (RefNotFoundException e) {
  1159. throw new JGitInternalException(e.getMessage(), e);
  1160. } catch (InvalidRefNameException e) {
  1161. throw new JGitInternalException(e.getMessage(), e);
  1162. } catch (CheckoutConflictException e) {
  1163. throw new JGitInternalException(e.getMessage(), e);
  1164. }
  1165. }
  1166. private void checkParameters() throws WrongRepositoryStateException {
  1167. if (this.operation == Operation.PROCESS_STEPS) {
  1168. if (rebaseState.getFile(DONE).exists())
  1169. throw new WrongRepositoryStateException(MessageFormat.format(
  1170. JGitText.get().wrongRepositoryState, repo
  1171. .getRepositoryState().name()));
  1172. }
  1173. if (this.operation != Operation.BEGIN) {
  1174. // these operations are only possible while in a rebasing state
  1175. switch (repo.getRepositoryState()) {
  1176. case REBASING_INTERACTIVE:
  1177. case REBASING:
  1178. case REBASING_REBASING:
  1179. case REBASING_MERGE:
  1180. break;
  1181. default:
  1182. throw new WrongRepositoryStateException(MessageFormat.format(
  1183. JGitText.get().wrongRepositoryState, repo
  1184. .getRepositoryState().name()));
  1185. }
  1186. } else
  1187. switch (repo.getRepositoryState()) {
  1188. case SAFE:
  1189. if (this.upstreamCommit == null)
  1190. throw new JGitInternalException(MessageFormat
  1191. .format(JGitText.get().missingRequiredParameter,
  1192. "upstream")); //$NON-NLS-1$
  1193. return;
  1194. default:
  1195. throw new WrongRepositoryStateException(MessageFormat.format(
  1196. JGitText.get().wrongRepositoryState, repo
  1197. .getRepositoryState().name()));
  1198. }
  1199. }
  1200. private RebaseResult abort(RebaseResult result) throws IOException,
  1201. GitAPIException {
  1202. try {
  1203. ObjectId origHead = repo.readOrigHead();
  1204. String commitId = origHead != null ? origHead.name() : null;
  1205. monitor.beginTask(MessageFormat.format(
  1206. JGitText.get().abortingRebase, commitId),
  1207. ProgressMonitor.UNKNOWN);
  1208. DirCacheCheckout dco;
  1209. if (commitId == null)
  1210. throw new JGitInternalException(
  1211. JGitText.get().abortingRebaseFailedNoOrigHead);
  1212. ObjectId id = repo.resolve(commitId);
  1213. RevCommit commit = walk.parseCommit(id);
  1214. if (result.getStatus().equals(Status.FAILED)) {
  1215. RevCommit head = walk.parseCommit(repo.resolve(Constants.HEAD));
  1216. dco = new DirCacheCheckout(repo, head.getTree(),
  1217. repo.lockDirCache(), commit.getTree());
  1218. } else {
  1219. dco = new DirCacheCheckout(repo, repo.lockDirCache(),
  1220. commit.getTree());
  1221. }
  1222. dco.setFailOnConflict(false);
  1223. dco.checkout();
  1224. walk.close();
  1225. } finally {
  1226. monitor.endTask();
  1227. }
  1228. try {
  1229. String headName = rebaseState.readFile(HEAD_NAME);
  1230. monitor.beginTask(MessageFormat.format(
  1231. JGitText.get().resettingHead, headName),
  1232. ProgressMonitor.UNKNOWN);
  1233. Result res = null;
  1234. RefUpdate refUpdate = repo.updateRef(Constants.HEAD, false);
  1235. refUpdate.setRefLogMessage("rebase: aborting", false); //$NON-NLS-1$
  1236. if (headName.startsWith(Constants.R_REFS)) {
  1237. // update the HEAD
  1238. res = refUpdate.link(headName);
  1239. } else {
  1240. refUpdate.setNewObjectId(repo.readOrigHead());
  1241. res = refUpdate.forceUpdate();
  1242. }
  1243. switch (res) {
  1244. case FAST_FORWARD:
  1245. case FORCED:
  1246. case NO_CHANGE:
  1247. break;
  1248. default:
  1249. throw new JGitInternalException(
  1250. JGitText.get().abortingRebaseFailed);
  1251. }
  1252. boolean stashConflicts = autoStashApply();
  1253. // cleanup the files
  1254. FileUtils.delete(rebaseState.getDir(), FileUtils.RECURSIVE);
  1255. repo.writeCherryPickHead(null);
  1256. repo.writeMergeHeads(null);
  1257. if (stashConflicts)
  1258. return RebaseResult.STASH_APPLY_CONFLICTS_RESULT;
  1259. return result;
  1260. } finally {
  1261. monitor.endTask();
  1262. }
  1263. }
  1264. private boolean checkoutCommit(String headName, RevCommit commit)
  1265. throws IOException,
  1266. CheckoutConflictException {
  1267. try {
  1268. RevCommit head = walk.parseCommit(repo.resolve(Constants.HEAD));
  1269. DirCacheCheckout dco = new DirCacheCheckout(repo, head.getTree(),
  1270. repo.lockDirCache(), commit.getTree());
  1271. dco.setFailOnConflict(true);
  1272. try {
  1273. dco.checkout();
  1274. } catch (org.eclipse.jgit.errors.CheckoutConflictException cce) {
  1275. throw new CheckoutConflictException(dco.getConflicts(), cce);
  1276. }
  1277. // update the HEAD
  1278. RefUpdate refUpdate = repo.updateRef(Constants.HEAD, true);
  1279. refUpdate.setExpectedOldObjectId(head);
  1280. refUpdate.setNewObjectId(commit);
  1281. refUpdate.setRefLogMessage(
  1282. "checkout: moving from " //$NON-NLS-1$
  1283. + Repository.shortenRefName(headName)
  1284. + " to " + commit.getName(), false); //$NON-NLS-1$
  1285. Result res = refUpdate.forceUpdate();
  1286. switch (res) {
  1287. case FAST_FORWARD:
  1288. case NO_CHANGE:
  1289. case FORCED:
  1290. break;
  1291. default:
  1292. throw new IOException(
  1293. JGitText.get().couldNotRewindToUpstreamCommit);
  1294. }
  1295. } finally {
  1296. walk.close();
  1297. monitor.endTask();
  1298. }
  1299. return true;
  1300. }
  1301. /**
  1302. * @param upstream
  1303. * the upstream commit
  1304. * @return {@code this}
  1305. */
  1306. public RebaseCommand setUpstream(RevCommit upstream) {
  1307. this.upstreamCommit = upstream;
  1308. this.upstreamCommitName = upstream.name();
  1309. return this;
  1310. }
  1311. /**
  1312. * @param upstream
  1313. * id of the upstream commit
  1314. * @return {@code this}
  1315. */
  1316. public RebaseCommand setUpstream(AnyObjectId upstream) {
  1317. try {
  1318. this.upstreamCommit = walk.parseCommit(upstream);
  1319. this.upstreamCommitName = upstream.name();
  1320. } catch (IOException e) {
  1321. throw new JGitInternalException(MessageFormat.format(
  1322. JGitText.get().couldNotReadObjectWhileParsingCommit,
  1323. upstream.name()), e);
  1324. }
  1325. return this;
  1326. }
  1327. /**
  1328. * @param upstream
  1329. * the upstream branch
  1330. * @return {@code this}
  1331. * @throws RefNotFoundException
  1332. */
  1333. public RebaseCommand setUpstream(String upstream)
  1334. throws RefNotFoundException {
  1335. try {
  1336. ObjectId upstreamId = repo.resolve(upstream);
  1337. if (upstreamId == null)
  1338. throw new RefNotFoundException(MessageFormat.format(JGitText
  1339. .get().refNotResolved, upstream));
  1340. upstreamCommit = walk.parseCommit(repo.resolve(upstream));
  1341. upstreamCommitName = upstream;
  1342. return this;
  1343. } catch (IOException ioe) {
  1344. throw new JGitInternalException(ioe.getMessage(), ioe);
  1345. }
  1346. }
  1347. /**
  1348. * Optionally override the name of the upstream. If this is used, it has to
  1349. * come after any {@link #setUpstream} call.
  1350. *
  1351. * @param upstreamName
  1352. * the name which will be used to refer to upstream in conflicts
  1353. * @return {@code this}
  1354. */
  1355. public RebaseCommand setUpstreamName(String upstreamName) {
  1356. if (upstreamCommit == null) {
  1357. throw new IllegalStateException(
  1358. "setUpstreamName must be called after setUpstream."); //$NON-NLS-1$
  1359. }
  1360. this.upstreamCommitName = upstreamName;
  1361. return this;
  1362. }
  1363. /**
  1364. * @param operation
  1365. * the operation to perform
  1366. * @return {@code this}
  1367. */
  1368. public RebaseCommand setOperation(Operation operation) {
  1369. this.operation = operation;
  1370. return this;
  1371. }
  1372. /**
  1373. * @param monitor
  1374. * a progress monitor
  1375. * @return this instance
  1376. */
  1377. public RebaseCommand setProgressMonitor(ProgressMonitor monitor) {
  1378. if (monitor == null) {
  1379. monitor = NullProgressMonitor.INSTANCE;
  1380. }
  1381. this.monitor = monitor;
  1382. return this;
  1383. }
  1384. /**
  1385. * Enables interactive rebase
  1386. * <p>
  1387. * Does not stop after initialization of interactive rebase. This is
  1388. * equivalent to
  1389. * {@link RebaseCommand#runInteractively(InteractiveHandler, boolean)
  1390. * runInteractively(handler, false)};
  1391. * </p>
  1392. *
  1393. * @param handler
  1394. * @return this
  1395. */
  1396. public RebaseCommand runInteractively(InteractiveHandler handler) {
  1397. return runInteractively(handler, false);
  1398. }
  1399. /**
  1400. * Enables interactive rebase
  1401. * <p>
  1402. * If stopAfterRebaseInteractiveInitialization is {@code true} the rebase
  1403. * stops after initialization of interactive rebase returning
  1404. * {@link RebaseResult#INTERACTIVE_PREPARED_RESULT}
  1405. * </p>
  1406. *
  1407. * @param handler
  1408. * @param stopAfterRebaseInteractiveInitialization
  1409. * if {@code true} the rebase stops after initialization
  1410. * @return this instance
  1411. * @since 3.2
  1412. */
  1413. public RebaseCommand runInteractively(InteractiveHandler handler,
  1414. final boolean stopAfterRebaseInteractiveInitialization) {
  1415. this.stopAfterInitialization = stopAfterRebaseInteractiveInitialization;
  1416. this.interactiveHandler = handler;
  1417. return this;
  1418. }
  1419. /**
  1420. * @param strategy
  1421. * The merge strategy to use during this rebase operation.
  1422. * @return {@code this}
  1423. * @since 3.4
  1424. */
  1425. public RebaseCommand setStrategy(MergeStrategy strategy) {
  1426. this.strategy = strategy;
  1427. return this;
  1428. }
  1429. /**
  1430. * @param preserve
  1431. * True to re-create merges during rebase. Defaults to false, a
  1432. * flattening rebase.
  1433. * @return {@code this}
  1434. * @since 3.5
  1435. */
  1436. public RebaseCommand setPreserveMerges(boolean preserve) {
  1437. this.preserveMerges = preserve;
  1438. return this;
  1439. }
  1440. /**
  1441. * Allows configure rebase interactive process and modify commit message
  1442. */
  1443. public interface InteractiveHandler {
  1444. /**
  1445. * Given list of {@code steps} should be modified according to user
  1446. * rebase configuration
  1447. * @param steps
  1448. * initial configuration of rebase interactive
  1449. */
  1450. void prepareSteps(List<RebaseTodoLine> steps);
  1451. /**
  1452. * Used for editing commit message on REWORD
  1453. *
  1454. * @param commit
  1455. * @return new commit message
  1456. */
  1457. String modifyCommitMessage(String commit);
  1458. }
  1459. PersonIdent parseAuthor(byte[] raw) {
  1460. if (raw.length == 0)
  1461. return null;
  1462. Map<String, String> keyValueMap = new HashMap<String, String>();
  1463. for (int p = 0; p < raw.length;) {
  1464. int end = RawParseUtils.nextLF(raw, p);
  1465. if (end == p)
  1466. break;
  1467. int equalsIndex = RawParseUtils.next(raw, p, '=');
  1468. if (equalsIndex == end)
  1469. break;
  1470. String key = RawParseUtils.decode(raw, p, equalsIndex - 1);
  1471. String value = RawParseUtils.decode(raw, equalsIndex + 1, end - 2);
  1472. p = end;
  1473. keyValueMap.put(key, value);
  1474. }
  1475. String name = keyValueMap.get(GIT_AUTHOR_NAME);
  1476. String email = keyValueMap.get(GIT_AUTHOR_EMAIL);
  1477. String time = keyValueMap.get(GIT_AUTHOR_DATE);
  1478. // the time is saved as <seconds since 1970> <timezone offset>
  1479. int timeStart = 0;
  1480. if (time.startsWith("@")) //$NON-NLS-1$
  1481. timeStart = 1;
  1482. else
  1483. timeStart = 0;
  1484. long when = Long
  1485. .parseLong(time.substring(timeStart, time.indexOf(' '))) * 1000;
  1486. String tzOffsetString = time.substring(time.indexOf(' ') + 1);
  1487. int multiplier = -1;
  1488. if (tzOffsetString.charAt(0) == '+')
  1489. multiplier = 1;
  1490. int hours = Integer.parseInt(tzOffsetString.substring(1, 3));
  1491. int minutes = Integer.parseInt(tzOffsetString.substring(3, 5));
  1492. // this is in format (+/-)HHMM (hours and minutes)
  1493. // we need to convert into minutes
  1494. int tz = (hours * 60 + minutes) * multiplier;
  1495. if (name != null && email != null)
  1496. return new PersonIdent(name, email, when, tz);
  1497. return null;
  1498. }
  1499. private static class RebaseState {
  1500. private final File repoDirectory;
  1501. private File dir;
  1502. public RebaseState(File repoDirectory) {
  1503. this.repoDirectory = repoDirectory;
  1504. }
  1505. public File getDir() {
  1506. if (dir == null) {
  1507. File rebaseApply = new File(repoDirectory, REBASE_APPLY);
  1508. if (rebaseApply.exists()) {
  1509. dir = rebaseApply;
  1510. } else {
  1511. File rebaseMerge = new File(repoDirectory, REBASE_MERGE);
  1512. dir = rebaseMerge;
  1513. }
  1514. }
  1515. return dir;
  1516. }
  1517. /**
  1518. * @return Directory with rewritten commit hashes, usually exists if
  1519. * {@link RebaseCommand#preserveMerges} is true
  1520. **/
  1521. public File getRewrittenDir() {
  1522. return new File(getDir(), REWRITTEN);
  1523. }
  1524. public String readFile(String name) throws IOException {
  1525. return readFile(getDir(), name);
  1526. }
  1527. public void createFile(String name, String content) throws IOException {
  1528. createFile(getDir(), name, content);
  1529. }
  1530. public File getFile(String name) {
  1531. return new File(getDir(), name);
  1532. }
  1533. public String getPath(String name) {
  1534. return (getDir().getName() + "/" + name); //$NON-NLS-1$
  1535. }
  1536. private static String readFile(File directory, String fileName)
  1537. throws IOException {
  1538. byte[] content = IO.readFully(new File(directory, fileName));
  1539. // strip off the last LF
  1540. int end = RawParseUtils.prevLF(content, content.length);
  1541. return RawParseUtils.decode(content, 0, end + 1);
  1542. }
  1543. private static void createFile(File parentDir, String name,
  1544. String content)
  1545. throws IOException {
  1546. File file = new File(parentDir, name);
  1547. FileOutputStream fos = new FileOutputStream(file);
  1548. try {
  1549. fos.write(content.getBytes(Constants.CHARACTER_ENCODING));
  1550. fos.write('\n');
  1551. } finally {
  1552. fos.close();
  1553. }
  1554. }
  1555. private static void appendToFile(File file, String content)
  1556. throws IOException {
  1557. FileOutputStream fos = new FileOutputStream(file, true);
  1558. try {
  1559. fos.write(content.getBytes(Constants.CHARACTER_ENCODING));
  1560. fos.write('\n');
  1561. } finally {
  1562. fos.close();
  1563. }
  1564. }
  1565. }
  1566. }