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 54KB

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