選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

RebaseCommand.java 55KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720
  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. // getHead() checks for null
  508. assert headId != null;
  509. if (!AnyObjectId.equals(headId, newParents.get(0)))
  510. checkoutCommit(headId.getName(), newParents.get(0));
  511. // Use the cherry-pick strategy if all non-first parents did not
  512. // change. This is different from C Git, which always uses the merge
  513. // strategy (see below).
  514. try (Git git = new Git(repo)) {
  515. if (otherParentsUnchanged) {
  516. boolean isMerge = commitToPick.getParentCount() > 1;
  517. String ourCommitName = getOurCommitName();
  518. CherryPickCommand pickCommand = git.cherryPick()
  519. .include(commitToPick)
  520. .setOurCommitName(ourCommitName)
  521. .setReflogPrefix(REFLOG_PREFIX)
  522. .setStrategy(strategy);
  523. if (isMerge) {
  524. pickCommand.setMainlineParentNumber(1);
  525. // We write a MERGE_HEAD and later commit explicitly
  526. pickCommand.setNoCommit(true);
  527. writeMergeInfo(commitToPick, newParents);
  528. }
  529. CherryPickResult cherryPickResult = pickCommand.call();
  530. switch (cherryPickResult.getStatus()) {
  531. case FAILED:
  532. if (operation == Operation.BEGIN)
  533. return abort(RebaseResult.failed(
  534. cherryPickResult.getFailingPaths()));
  535. else
  536. return stop(commitToPick, Status.STOPPED);
  537. case CONFLICTING:
  538. return stop(commitToPick, Status.STOPPED);
  539. case OK:
  540. if (isMerge) {
  541. // Commit the merge (setup above using
  542. // writeMergeInfo())
  543. CommitCommand commit = git.commit();
  544. commit.setAuthor(commitToPick.getAuthorIdent());
  545. commit.setReflogComment(REFLOG_PREFIX + " " //$NON-NLS-1$
  546. + commitToPick.getShortMessage());
  547. newHead = commit.call();
  548. } else
  549. newHead = cherryPickResult.getNewHead();
  550. break;
  551. }
  552. } else {
  553. // Use the merge strategy to redo merges, which had some of
  554. // their non-first parents rewritten
  555. MergeCommand merge = git.merge()
  556. .setFastForward(MergeCommand.FastForwardMode.NO_FF)
  557. .setCommit(false);
  558. for (int i = 1; i < commitToPick.getParentCount(); i++)
  559. merge.include(newParents.get(i));
  560. MergeResult mergeResult = merge.call();
  561. if (mergeResult.getMergeStatus().isSuccessful()) {
  562. CommitCommand commit = git.commit();
  563. commit.setAuthor(commitToPick.getAuthorIdent());
  564. commit.setMessage(commitToPick.getFullMessage());
  565. commit.setReflogComment(REFLOG_PREFIX + " " //$NON-NLS-1$
  566. + commitToPick.getShortMessage());
  567. newHead = commit.call();
  568. } else {
  569. if (operation == Operation.BEGIN && mergeResult
  570. .getMergeStatus() == MergeResult.MergeStatus.FAILED)
  571. return abort(RebaseResult
  572. .failed(mergeResult.getFailingPaths()));
  573. return stop(commitToPick, Status.STOPPED);
  574. }
  575. }
  576. }
  577. }
  578. return null;
  579. }
  580. // Prepare MERGE_HEAD and message for the next commit
  581. private void writeMergeInfo(RevCommit commitToPick,
  582. List<RevCommit> newParents) throws IOException {
  583. repo.writeMergeHeads(newParents.subList(1, newParents.size()));
  584. repo.writeMergeCommitMsg(commitToPick.getFullMessage());
  585. }
  586. // Get the rewritten equivalents for the parents of the given commit
  587. private List<RevCommit> getNewParents(RevCommit commitToPick)
  588. throws IOException {
  589. List<RevCommit> newParents = new ArrayList<RevCommit>();
  590. for (int p = 0; p < commitToPick.getParentCount(); p++) {
  591. String parentHash = commitToPick.getParent(p).getName();
  592. if (!new File(rebaseState.getRewrittenDir(), parentHash).exists())
  593. newParents.add(commitToPick.getParent(p));
  594. else {
  595. String newParent = RebaseState.readFile(
  596. rebaseState.getRewrittenDir(), parentHash);
  597. if (newParent.length() == 0)
  598. newParents.add(walk.parseCommit(repo
  599. .resolve(Constants.HEAD)));
  600. else
  601. newParents.add(walk.parseCommit(ObjectId
  602. .fromString(newParent)));
  603. }
  604. }
  605. return newParents;
  606. }
  607. private void writeCurrentCommit(RevCommit commit) throws IOException {
  608. RebaseState.appendToFile(rebaseState.getFile(CURRENT_COMMIT),
  609. commit.name());
  610. }
  611. private void writeRewrittenHashes() throws RevisionSyntaxException,
  612. IOException, RefNotFoundException {
  613. File currentCommitFile = rebaseState.getFile(CURRENT_COMMIT);
  614. if (!currentCommitFile.exists())
  615. return;
  616. ObjectId headId = getHead().getObjectId();
  617. // getHead() checks for null
  618. assert headId != null;
  619. String head = headId.getName();
  620. String currentCommits = rebaseState.readFile(CURRENT_COMMIT);
  621. for (String current : currentCommits.split("\n")) //$NON-NLS-1$
  622. RebaseState
  623. .createFile(rebaseState.getRewrittenDir(), current, head);
  624. FileUtils.delete(currentCommitFile);
  625. }
  626. private RebaseResult finishRebase(RevCommit finalHead,
  627. boolean lastStepIsForward) throws IOException, GitAPIException {
  628. String headName = rebaseState.readFile(HEAD_NAME);
  629. updateHead(headName, finalHead, upstreamCommit);
  630. boolean stashConflicts = autoStashApply();
  631. FileUtils.delete(rebaseState.getDir(), FileUtils.RECURSIVE);
  632. if (stashConflicts)
  633. return RebaseResult.STASH_APPLY_CONFLICTS_RESULT;
  634. if (lastStepIsForward || finalHead == null)
  635. return RebaseResult.FAST_FORWARD_RESULT;
  636. return RebaseResult.OK_RESULT;
  637. }
  638. private void checkSteps(List<RebaseTodoLine> steps)
  639. throws InvalidRebaseStepException, IOException {
  640. if (steps.isEmpty())
  641. return;
  642. if (RebaseTodoLine.Action.SQUASH.equals(steps.get(0).getAction())
  643. || RebaseTodoLine.Action.FIXUP.equals(steps.get(0).getAction())) {
  644. if (!rebaseState.getFile(DONE).exists()
  645. || rebaseState.readFile(DONE).trim().length() == 0) {
  646. throw new InvalidRebaseStepException(MessageFormat.format(
  647. JGitText.get().cannotSquashFixupWithoutPreviousCommit,
  648. steps.get(0).getAction().name()));
  649. }
  650. }
  651. }
  652. private RevCommit doSquashFixup(boolean isSquash, RevCommit commitToPick,
  653. RebaseTodoLine nextStep, File messageFixup, File messageSquash)
  654. throws IOException, GitAPIException {
  655. if (!messageSquash.exists()) {
  656. // init squash/fixup sequence
  657. ObjectId headId = repo.resolve(Constants.HEAD);
  658. RevCommit previousCommit = walk.parseCommit(headId);
  659. initializeSquashFixupFile(MESSAGE_SQUASH,
  660. previousCommit.getFullMessage());
  661. if (!isSquash)
  662. initializeSquashFixupFile(MESSAGE_FIXUP,
  663. previousCommit.getFullMessage());
  664. }
  665. String currSquashMessage = rebaseState
  666. .readFile(MESSAGE_SQUASH);
  667. int count = parseSquashFixupSequenceCount(currSquashMessage) + 1;
  668. String content = composeSquashMessage(isSquash,
  669. commitToPick, currSquashMessage, count);
  670. rebaseState.createFile(MESSAGE_SQUASH, content);
  671. if (messageFixup.exists())
  672. rebaseState.createFile(MESSAGE_FIXUP, content);
  673. return squashIntoPrevious(
  674. !messageFixup.exists(),
  675. nextStep);
  676. }
  677. private void resetSoftToParent() throws IOException,
  678. GitAPIException, CheckoutConflictException {
  679. Ref ref = repo.getRef(Constants.ORIG_HEAD);
  680. ObjectId orig_head = ref == null ? null : ref.getObjectId();
  681. try {
  682. // we have already commited the cherry-picked commit.
  683. // what we need is to have changes introduced by this
  684. // commit to be on the index
  685. // resetting is a workaround
  686. Git.wrap(repo).reset().setMode(ResetType.SOFT)
  687. .setRef("HEAD~1").call(); //$NON-NLS-1$
  688. } finally {
  689. // set ORIG_HEAD back to where we started because soft
  690. // reset moved it
  691. repo.writeOrigHead(orig_head);
  692. }
  693. }
  694. private RevCommit squashIntoPrevious(boolean sequenceContainsSquash,
  695. RebaseTodoLine nextStep)
  696. throws IOException, GitAPIException {
  697. RevCommit retNewHead;
  698. String commitMessage = rebaseState
  699. .readFile(MESSAGE_SQUASH);
  700. try (Git git = new Git(repo)) {
  701. if (nextStep == null || ((nextStep.getAction() != Action.FIXUP)
  702. && (nextStep.getAction() != Action.SQUASH))) {
  703. // this is the last step in this sequence
  704. if (sequenceContainsSquash) {
  705. commitMessage = interactiveHandler
  706. .modifyCommitMessage(commitMessage);
  707. }
  708. retNewHead = git.commit()
  709. .setMessage(stripCommentLines(commitMessage))
  710. .setAmend(true).setNoVerify(true).call();
  711. rebaseState.getFile(MESSAGE_SQUASH).delete();
  712. rebaseState.getFile(MESSAGE_FIXUP).delete();
  713. } else {
  714. // Next step is either Squash or Fixup
  715. retNewHead = git.commit().setMessage(commitMessage)
  716. .setAmend(true).setNoVerify(true).call();
  717. }
  718. }
  719. return retNewHead;
  720. }
  721. private static String stripCommentLines(String commitMessage) {
  722. StringBuilder result = new StringBuilder();
  723. for (String line : commitMessage.split("\n")) { //$NON-NLS-1$
  724. if (!line.trim().startsWith("#")) //$NON-NLS-1$
  725. result.append(line).append("\n"); //$NON-NLS-1$
  726. }
  727. if (!commitMessage.endsWith("\n")) //$NON-NLS-1$
  728. result.deleteCharAt(result.length() - 1);
  729. return result.toString();
  730. }
  731. @SuppressWarnings("nls")
  732. private static String composeSquashMessage(boolean isSquash,
  733. RevCommit commitToPick, String currSquashMessage, int count) {
  734. StringBuilder sb = new StringBuilder();
  735. String ordinal = getOrdinal(count);
  736. sb.setLength(0);
  737. sb.append("# This is a combination of ").append(count)
  738. .append(" commits.\n");
  739. // Add the previous message without header (i.e first line)
  740. sb.append(currSquashMessage.substring(currSquashMessage.indexOf("\n") + 1));
  741. sb.append("\n");
  742. if (isSquash) {
  743. sb.append("# This is the ").append(count).append(ordinal)
  744. .append(" commit message:\n");
  745. sb.append(commitToPick.getFullMessage());
  746. } else {
  747. sb.append("# The ").append(count).append(ordinal)
  748. .append(" commit message will be skipped:\n# ");
  749. sb.append(commitToPick.getFullMessage().replaceAll("([\n\r])",
  750. "$1# "));
  751. }
  752. return sb.toString();
  753. }
  754. private static String getOrdinal(int count) {
  755. switch (count % 10) {
  756. case 1:
  757. return "st"; //$NON-NLS-1$
  758. case 2:
  759. return "nd"; //$NON-NLS-1$
  760. case 3:
  761. return "rd"; //$NON-NLS-1$
  762. default:
  763. return "th"; //$NON-NLS-1$
  764. }
  765. }
  766. /**
  767. * Parse the count from squashed commit messages
  768. *
  769. * @param currSquashMessage
  770. * the squashed commit message to be parsed
  771. * @return the count of squashed messages in the given string
  772. */
  773. static int parseSquashFixupSequenceCount(String currSquashMessage) {
  774. String regex = "This is a combination of (.*) commits"; //$NON-NLS-1$
  775. String firstLine = currSquashMessage.substring(0,
  776. currSquashMessage.indexOf("\n")); //$NON-NLS-1$
  777. Pattern pattern = Pattern.compile(regex);
  778. Matcher matcher = pattern.matcher(firstLine);
  779. if (!matcher.find())
  780. throw new IllegalArgumentException();
  781. return Integer.parseInt(matcher.group(1));
  782. }
  783. private void initializeSquashFixupFile(String messageFile,
  784. String fullMessage) throws IOException {
  785. rebaseState
  786. .createFile(
  787. messageFile,
  788. "# This is a combination of 1 commits.\n# The first commit's message is:\n" + fullMessage); //$NON-NLS-1$);
  789. }
  790. private String getOurCommitName() {
  791. // If onto is different from upstream, this should say "onto", but
  792. // RebaseCommand doesn't support a different "onto" at the moment.
  793. String ourCommitName = "Upstream, based on " //$NON-NLS-1$
  794. + Repository.shortenRefName(upstreamCommitName);
  795. return ourCommitName;
  796. }
  797. private void updateHead(String headName, RevCommit aNewHead, RevCommit onto)
  798. throws IOException {
  799. // point the previous head (if any) to the new commit
  800. if (headName.startsWith(Constants.R_REFS)) {
  801. RefUpdate rup = repo.updateRef(headName);
  802. rup.setNewObjectId(aNewHead);
  803. rup.setRefLogMessage("rebase finished: " + headName + " onto " //$NON-NLS-1$ //$NON-NLS-2$
  804. + onto.getName(), false);
  805. Result res = rup.forceUpdate();
  806. switch (res) {
  807. case FAST_FORWARD:
  808. case FORCED:
  809. case NO_CHANGE:
  810. break;
  811. default:
  812. throw new JGitInternalException(
  813. JGitText.get().updatingHeadFailed);
  814. }
  815. rup = repo.updateRef(Constants.HEAD);
  816. rup.setRefLogMessage("rebase finished: returning to " + headName, //$NON-NLS-1$
  817. false);
  818. res = rup.link(headName);
  819. switch (res) {
  820. case FAST_FORWARD:
  821. case FORCED:
  822. case NO_CHANGE:
  823. break;
  824. default:
  825. throw new JGitInternalException(
  826. JGitText.get().updatingHeadFailed);
  827. }
  828. }
  829. }
  830. private RevCommit checkoutCurrentHead() throws IOException, NoHeadException {
  831. ObjectId headTree = repo.resolve(Constants.HEAD + "^{tree}"); //$NON-NLS-1$
  832. if (headTree == null)
  833. throw new NoHeadException(
  834. JGitText.get().cannotRebaseWithoutCurrentHead);
  835. DirCache dc = repo.lockDirCache();
  836. try {
  837. DirCacheCheckout dco = new DirCacheCheckout(repo, dc, headTree);
  838. dco.setFailOnConflict(false);
  839. boolean needsDeleteFiles = dco.checkout();
  840. if (needsDeleteFiles) {
  841. List<String> fileList = dco.getToBeDeleted();
  842. for (String filePath : fileList) {
  843. File fileToDelete = new File(repo.getWorkTree(), filePath);
  844. if (repo.getFS().exists(fileToDelete))
  845. FileUtils.delete(fileToDelete, FileUtils.RECURSIVE
  846. | FileUtils.RETRY);
  847. }
  848. }
  849. } finally {
  850. dc.unlock();
  851. }
  852. try (RevWalk rw = new RevWalk(repo)) {
  853. RevCommit commit = rw.parseCommit(repo.resolve(Constants.HEAD));
  854. return commit;
  855. }
  856. }
  857. /**
  858. * @return the commit if we had to do a commit, otherwise null
  859. * @throws GitAPIException
  860. * @throws IOException
  861. */
  862. private RevCommit continueRebase() throws GitAPIException, IOException {
  863. // if there are still conflicts, we throw a specific Exception
  864. DirCache dc = repo.readDirCache();
  865. boolean hasUnmergedPaths = dc.hasUnmergedPaths();
  866. if (hasUnmergedPaths)
  867. throw new UnmergedPathsException();
  868. // determine whether we need to commit
  869. boolean needsCommit;
  870. try (TreeWalk treeWalk = new TreeWalk(repo)) {
  871. treeWalk.reset();
  872. treeWalk.setRecursive(true);
  873. treeWalk.addTree(new DirCacheIterator(dc));
  874. ObjectId id = repo.resolve(Constants.HEAD + "^{tree}"); //$NON-NLS-1$
  875. if (id == null)
  876. throw new NoHeadException(
  877. JGitText.get().cannotRebaseWithoutCurrentHead);
  878. treeWalk.addTree(id);
  879. treeWalk.setFilter(TreeFilter.ANY_DIFF);
  880. needsCommit = treeWalk.next();
  881. }
  882. if (needsCommit) {
  883. try (Git git = new Git(repo)) {
  884. CommitCommand commit = git.commit();
  885. commit.setMessage(rebaseState.readFile(MESSAGE));
  886. commit.setAuthor(parseAuthor());
  887. return commit.call();
  888. }
  889. }
  890. return null;
  891. }
  892. private PersonIdent parseAuthor() throws IOException {
  893. File authorScriptFile = rebaseState.getFile(AUTHOR_SCRIPT);
  894. byte[] raw;
  895. try {
  896. raw = IO.readFully(authorScriptFile);
  897. } catch (FileNotFoundException notFound) {
  898. if (authorScriptFile.exists()) {
  899. throw notFound;
  900. }
  901. return null;
  902. }
  903. return parseAuthor(raw);
  904. }
  905. private RebaseResult stop(RevCommit commitToPick, RebaseResult.Status status)
  906. throws IOException {
  907. PersonIdent author = commitToPick.getAuthorIdent();
  908. String authorScript = toAuthorScript(author);
  909. rebaseState.createFile(AUTHOR_SCRIPT, authorScript);
  910. rebaseState.createFile(MESSAGE, commitToPick.getFullMessage());
  911. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  912. try (DiffFormatter df = new DiffFormatter(bos)) {
  913. df.setRepository(repo);
  914. df.format(commitToPick.getParent(0), commitToPick);
  915. }
  916. rebaseState.createFile(PATCH, new String(bos.toByteArray(),
  917. Constants.CHARACTER_ENCODING));
  918. rebaseState.createFile(STOPPED_SHA,
  919. repo.newObjectReader()
  920. .abbreviate(
  921. commitToPick).name());
  922. // Remove cherry pick state file created by CherryPickCommand, it's not
  923. // needed for rebase
  924. repo.writeCherryPickHead(null);
  925. return RebaseResult.result(status, commitToPick);
  926. }
  927. String toAuthorScript(PersonIdent author) {
  928. StringBuilder sb = new StringBuilder(100);
  929. sb.append(GIT_AUTHOR_NAME);
  930. sb.append("='"); //$NON-NLS-1$
  931. sb.append(author.getName());
  932. sb.append("'\n"); //$NON-NLS-1$
  933. sb.append(GIT_AUTHOR_EMAIL);
  934. sb.append("='"); //$NON-NLS-1$
  935. sb.append(author.getEmailAddress());
  936. sb.append("'\n"); //$NON-NLS-1$
  937. // the command line uses the "external String"
  938. // representation for date and timezone
  939. sb.append(GIT_AUTHOR_DATE);
  940. sb.append("='"); //$NON-NLS-1$
  941. sb.append("@"); // @ for time in seconds since 1970 //$NON-NLS-1$
  942. String externalString = author.toExternalString();
  943. sb
  944. .append(externalString.substring(externalString
  945. .lastIndexOf('>') + 2));
  946. sb.append("'\n"); //$NON-NLS-1$
  947. return sb.toString();
  948. }
  949. /**
  950. * Removes the number of lines given in the parameter from the
  951. * <code>git-rebase-todo</code> file but preserves comments and other lines
  952. * that can not be parsed as steps
  953. *
  954. * @param numSteps
  955. * @throws IOException
  956. */
  957. private void popSteps(int numSteps) throws IOException {
  958. if (numSteps == 0)
  959. return;
  960. List<RebaseTodoLine> todoLines = new LinkedList<RebaseTodoLine>();
  961. List<RebaseTodoLine> poppedLines = new LinkedList<RebaseTodoLine>();
  962. for (RebaseTodoLine line : repo.readRebaseTodo(
  963. rebaseState.getPath(GIT_REBASE_TODO), true)) {
  964. if (poppedLines.size() >= numSteps
  965. || RebaseTodoLine.Action.COMMENT.equals(line.getAction()))
  966. todoLines.add(line);
  967. else
  968. poppedLines.add(line);
  969. }
  970. repo.writeRebaseTodoFile(rebaseState.getPath(GIT_REBASE_TODO),
  971. todoLines, false);
  972. if (poppedLines.size() > 0) {
  973. repo.writeRebaseTodoFile(rebaseState.getPath(DONE), poppedLines,
  974. true);
  975. }
  976. }
  977. private RebaseResult initFilesAndRewind() throws IOException,
  978. GitAPIException {
  979. // we need to store everything into files so that we can implement
  980. // --skip, --continue, and --abort
  981. Ref head = getHead();
  982. ObjectId headId = head.getObjectId();
  983. if (headId == null) {
  984. throw new RefNotFoundException(MessageFormat.format(
  985. JGitText.get().refNotResolved, Constants.HEAD));
  986. }
  987. String headName = getHeadName(head);
  988. RevCommit headCommit = walk.lookupCommit(headId);
  989. RevCommit upstream = walk.lookupCommit(upstreamCommit.getId());
  990. if (!isInteractive() && walk.isMergedInto(upstream, headCommit))
  991. return RebaseResult.UP_TO_DATE_RESULT;
  992. else if (!isInteractive() && walk.isMergedInto(headCommit, upstream)) {
  993. // head is already merged into upstream, fast-foward
  994. monitor.beginTask(MessageFormat.format(
  995. JGitText.get().resettingHead,
  996. upstreamCommit.getShortMessage()), ProgressMonitor.UNKNOWN);
  997. checkoutCommit(headName, upstreamCommit);
  998. monitor.endTask();
  999. updateHead(headName, upstreamCommit, upstream);
  1000. return RebaseResult.FAST_FORWARD_RESULT;
  1001. }
  1002. monitor.beginTask(JGitText.get().obtainingCommitsForCherryPick,
  1003. ProgressMonitor.UNKNOWN);
  1004. // create the folder for the meta information
  1005. FileUtils.mkdir(rebaseState.getDir(), true);
  1006. repo.writeOrigHead(headId);
  1007. rebaseState.createFile(REBASE_HEAD, headId.name());
  1008. rebaseState.createFile(HEAD_NAME, headName);
  1009. rebaseState.createFile(ONTO, upstreamCommit.name());
  1010. rebaseState.createFile(ONTO_NAME, upstreamCommitName);
  1011. if (isInteractive()) {
  1012. rebaseState.createFile(INTERACTIVE, ""); //$NON-NLS-1$
  1013. }
  1014. rebaseState.createFile(QUIET, ""); //$NON-NLS-1$
  1015. ArrayList<RebaseTodoLine> toDoSteps = new ArrayList<RebaseTodoLine>();
  1016. toDoSteps.add(new RebaseTodoLine("# Created by EGit: rebasing " + headId.name() //$NON-NLS-1$
  1017. + " onto " + upstreamCommit.name())); //$NON-NLS-1$
  1018. // determine the commits to be applied
  1019. List<RevCommit> cherryPickList = calculatePickList(headCommit);
  1020. ObjectReader reader = walk.getObjectReader();
  1021. for (RevCommit commit : cherryPickList)
  1022. toDoSteps.add(new RebaseTodoLine(Action.PICK, reader
  1023. .abbreviate(commit), commit.getShortMessage()));
  1024. repo.writeRebaseTodoFile(rebaseState.getPath(GIT_REBASE_TODO),
  1025. toDoSteps, false);
  1026. monitor.endTask();
  1027. // we rewind to the upstream commit
  1028. monitor.beginTask(MessageFormat.format(JGitText.get().rewinding,
  1029. upstreamCommit.getShortMessage()), ProgressMonitor.UNKNOWN);
  1030. boolean checkoutOk = false;
  1031. try {
  1032. checkoutOk = checkoutCommit(headName, upstreamCommit);
  1033. } finally {
  1034. if (!checkoutOk)
  1035. FileUtils.delete(rebaseState.getDir(), FileUtils.RECURSIVE);
  1036. }
  1037. monitor.endTask();
  1038. return null;
  1039. }
  1040. private List<RevCommit> calculatePickList(RevCommit headCommit)
  1041. throws GitAPIException, NoHeadException, IOException {
  1042. Iterable<RevCommit> commitsToUse;
  1043. try (Git git = new Git(repo)) {
  1044. LogCommand cmd = git.log().addRange(upstreamCommit, headCommit);
  1045. commitsToUse = cmd.call();
  1046. }
  1047. List<RevCommit> cherryPickList = new ArrayList<RevCommit>();
  1048. for (RevCommit commit : commitsToUse) {
  1049. if (preserveMerges || commit.getParentCount() == 1)
  1050. cherryPickList.add(commit);
  1051. }
  1052. Collections.reverse(cherryPickList);
  1053. if (preserveMerges) {
  1054. // When preserving merges we only rewrite commits which have at
  1055. // least one parent that is itself rewritten (or a merge base)
  1056. File rewrittenDir = rebaseState.getRewrittenDir();
  1057. FileUtils.mkdir(rewrittenDir, false);
  1058. walk.reset();
  1059. walk.setRevFilter(RevFilter.MERGE_BASE);
  1060. walk.markStart(upstreamCommit);
  1061. walk.markStart(headCommit);
  1062. RevCommit base;
  1063. while ((base = walk.next()) != null)
  1064. RebaseState.createFile(rewrittenDir, base.getName(),
  1065. upstreamCommit.getName());
  1066. Iterator<RevCommit> iterator = cherryPickList.iterator();
  1067. pickLoop: while(iterator.hasNext()){
  1068. RevCommit commit = iterator.next();
  1069. for (int i = 0; i < commit.getParentCount(); i++) {
  1070. boolean parentRewritten = new File(rewrittenDir, commit
  1071. .getParent(i).getName()).exists();
  1072. if (parentRewritten) {
  1073. new File(rewrittenDir, commit.getName()).createNewFile();
  1074. continue pickLoop;
  1075. }
  1076. }
  1077. // commit is only merged in, needs not be rewritten
  1078. iterator.remove();
  1079. }
  1080. }
  1081. return cherryPickList;
  1082. }
  1083. private static String getHeadName(Ref head) {
  1084. String headName;
  1085. if (head.isSymbolic()) {
  1086. headName = head.getTarget().getName();
  1087. } else {
  1088. ObjectId headId = head.getObjectId();
  1089. // the callers are checking this already
  1090. assert headId != null;
  1091. headName = headId.getName();
  1092. }
  1093. return headName;
  1094. }
  1095. private Ref getHead() throws IOException, RefNotFoundException {
  1096. Ref head = repo.getRef(Constants.HEAD);
  1097. if (head == null || head.getObjectId() == null)
  1098. throw new RefNotFoundException(MessageFormat.format(
  1099. JGitText.get().refNotResolved, Constants.HEAD));
  1100. return head;
  1101. }
  1102. private boolean isInteractive() {
  1103. return interactiveHandler != null;
  1104. }
  1105. /**
  1106. * checks if we can fast-forward and returns the new head if it is possible
  1107. *
  1108. * @param newCommit
  1109. * @return the new head, or null
  1110. * @throws IOException
  1111. * @throws GitAPIException
  1112. */
  1113. public RevCommit tryFastForward(RevCommit newCommit) throws IOException,
  1114. GitAPIException {
  1115. Ref head = getHead();
  1116. ObjectId headId = head.getObjectId();
  1117. if (headId == null)
  1118. throw new RefNotFoundException(MessageFormat.format(
  1119. JGitText.get().refNotResolved, Constants.HEAD));
  1120. RevCommit headCommit = walk.lookupCommit(headId);
  1121. if (walk.isMergedInto(newCommit, headCommit))
  1122. return newCommit;
  1123. String headName = getHeadName(head);
  1124. return tryFastForward(headName, headCommit, newCommit);
  1125. }
  1126. private RevCommit tryFastForward(String headName, RevCommit oldCommit,
  1127. RevCommit newCommit) throws IOException, GitAPIException {
  1128. boolean tryRebase = false;
  1129. for (RevCommit parentCommit : newCommit.getParents())
  1130. if (parentCommit.equals(oldCommit))
  1131. tryRebase = true;
  1132. if (!tryRebase)
  1133. return null;
  1134. CheckoutCommand co = new CheckoutCommand(repo);
  1135. try {
  1136. co.setName(newCommit.name()).call();
  1137. if (headName.startsWith(Constants.R_HEADS)) {
  1138. RefUpdate rup = repo.updateRef(headName);
  1139. rup.setExpectedOldObjectId(oldCommit);
  1140. rup.setNewObjectId(newCommit);
  1141. rup.setRefLogMessage("Fast-forward from " + oldCommit.name() //$NON-NLS-1$
  1142. + " to " + newCommit.name(), false); //$NON-NLS-1$
  1143. Result res = rup.update(walk);
  1144. switch (res) {
  1145. case FAST_FORWARD:
  1146. case NO_CHANGE:
  1147. case FORCED:
  1148. break;
  1149. default:
  1150. throw new IOException("Could not fast-forward"); //$NON-NLS-1$
  1151. }
  1152. }
  1153. return newCommit;
  1154. } catch (RefAlreadyExistsException e) {
  1155. throw new JGitInternalException(e.getMessage(), e);
  1156. } catch (RefNotFoundException e) {
  1157. throw new JGitInternalException(e.getMessage(), e);
  1158. } catch (InvalidRefNameException e) {
  1159. throw new JGitInternalException(e.getMessage(), e);
  1160. } catch (CheckoutConflictException e) {
  1161. throw new JGitInternalException(e.getMessage(), e);
  1162. }
  1163. }
  1164. private void checkParameters() throws WrongRepositoryStateException {
  1165. if (this.operation == Operation.PROCESS_STEPS) {
  1166. if (rebaseState.getFile(DONE).exists())
  1167. throw new WrongRepositoryStateException(MessageFormat.format(
  1168. JGitText.get().wrongRepositoryState, repo
  1169. .getRepositoryState().name()));
  1170. }
  1171. if (this.operation != Operation.BEGIN) {
  1172. // these operations are only possible while in a rebasing state
  1173. switch (repo.getRepositoryState()) {
  1174. case REBASING_INTERACTIVE:
  1175. case REBASING:
  1176. case REBASING_REBASING:
  1177. case REBASING_MERGE:
  1178. break;
  1179. default:
  1180. throw new WrongRepositoryStateException(MessageFormat.format(
  1181. JGitText.get().wrongRepositoryState, repo
  1182. .getRepositoryState().name()));
  1183. }
  1184. } else
  1185. switch (repo.getRepositoryState()) {
  1186. case SAFE:
  1187. if (this.upstreamCommit == null)
  1188. throw new JGitInternalException(MessageFormat
  1189. .format(JGitText.get().missingRequiredParameter,
  1190. "upstream")); //$NON-NLS-1$
  1191. return;
  1192. default:
  1193. throw new WrongRepositoryStateException(MessageFormat.format(
  1194. JGitText.get().wrongRepositoryState, repo
  1195. .getRepositoryState().name()));
  1196. }
  1197. }
  1198. private RebaseResult abort(RebaseResult result) throws IOException,
  1199. GitAPIException {
  1200. try {
  1201. ObjectId origHead = repo.readOrigHead();
  1202. String commitId = origHead != null ? origHead.name() : null;
  1203. monitor.beginTask(MessageFormat.format(
  1204. JGitText.get().abortingRebase, commitId),
  1205. ProgressMonitor.UNKNOWN);
  1206. DirCacheCheckout dco;
  1207. if (commitId == null)
  1208. throw new JGitInternalException(
  1209. JGitText.get().abortingRebaseFailedNoOrigHead);
  1210. ObjectId id = repo.resolve(commitId);
  1211. RevCommit commit = walk.parseCommit(id);
  1212. if (result.getStatus().equals(Status.FAILED)) {
  1213. RevCommit head = walk.parseCommit(repo.resolve(Constants.HEAD));
  1214. dco = new DirCacheCheckout(repo, head.getTree(),
  1215. repo.lockDirCache(), commit.getTree());
  1216. } else {
  1217. dco = new DirCacheCheckout(repo, repo.lockDirCache(),
  1218. commit.getTree());
  1219. }
  1220. dco.setFailOnConflict(false);
  1221. dco.checkout();
  1222. walk.close();
  1223. } finally {
  1224. monitor.endTask();
  1225. }
  1226. try {
  1227. String headName = rebaseState.readFile(HEAD_NAME);
  1228. monitor.beginTask(MessageFormat.format(
  1229. JGitText.get().resettingHead, headName),
  1230. ProgressMonitor.UNKNOWN);
  1231. Result res = null;
  1232. RefUpdate refUpdate = repo.updateRef(Constants.HEAD, false);
  1233. refUpdate.setRefLogMessage("rebase: aborting", false); //$NON-NLS-1$
  1234. if (headName.startsWith(Constants.R_REFS)) {
  1235. // update the HEAD
  1236. res = refUpdate.link(headName);
  1237. } else {
  1238. refUpdate.setNewObjectId(repo.readOrigHead());
  1239. res = refUpdate.forceUpdate();
  1240. }
  1241. switch (res) {
  1242. case FAST_FORWARD:
  1243. case FORCED:
  1244. case NO_CHANGE:
  1245. break;
  1246. default:
  1247. throw new JGitInternalException(
  1248. JGitText.get().abortingRebaseFailed);
  1249. }
  1250. boolean stashConflicts = autoStashApply();
  1251. // cleanup the files
  1252. FileUtils.delete(rebaseState.getDir(), FileUtils.RECURSIVE);
  1253. repo.writeCherryPickHead(null);
  1254. repo.writeMergeHeads(null);
  1255. if (stashConflicts)
  1256. return RebaseResult.STASH_APPLY_CONFLICTS_RESULT;
  1257. return result;
  1258. } finally {
  1259. monitor.endTask();
  1260. }
  1261. }
  1262. private boolean checkoutCommit(String headName, RevCommit commit)
  1263. throws IOException,
  1264. CheckoutConflictException {
  1265. try {
  1266. RevCommit head = walk.parseCommit(repo.resolve(Constants.HEAD));
  1267. DirCacheCheckout dco = new DirCacheCheckout(repo, head.getTree(),
  1268. repo.lockDirCache(), commit.getTree());
  1269. dco.setFailOnConflict(true);
  1270. try {
  1271. dco.checkout();
  1272. } catch (org.eclipse.jgit.errors.CheckoutConflictException cce) {
  1273. throw new CheckoutConflictException(dco.getConflicts(), cce);
  1274. }
  1275. // update the HEAD
  1276. RefUpdate refUpdate = repo.updateRef(Constants.HEAD, true);
  1277. refUpdate.setExpectedOldObjectId(head);
  1278. refUpdate.setNewObjectId(commit);
  1279. refUpdate.setRefLogMessage(
  1280. "checkout: moving from " //$NON-NLS-1$
  1281. + Repository.shortenRefName(headName)
  1282. + " to " + commit.getName(), false); //$NON-NLS-1$
  1283. Result res = refUpdate.forceUpdate();
  1284. switch (res) {
  1285. case FAST_FORWARD:
  1286. case NO_CHANGE:
  1287. case FORCED:
  1288. break;
  1289. default:
  1290. throw new IOException(
  1291. JGitText.get().couldNotRewindToUpstreamCommit);
  1292. }
  1293. } finally {
  1294. walk.close();
  1295. monitor.endTask();
  1296. }
  1297. return true;
  1298. }
  1299. /**
  1300. * @param upstream
  1301. * the upstream commit
  1302. * @return {@code this}
  1303. */
  1304. public RebaseCommand setUpstream(RevCommit upstream) {
  1305. this.upstreamCommit = upstream;
  1306. this.upstreamCommitName = upstream.name();
  1307. return this;
  1308. }
  1309. /**
  1310. * @param upstream
  1311. * id of the upstream commit
  1312. * @return {@code this}
  1313. */
  1314. public RebaseCommand setUpstream(AnyObjectId upstream) {
  1315. try {
  1316. this.upstreamCommit = walk.parseCommit(upstream);
  1317. this.upstreamCommitName = upstream.name();
  1318. } catch (IOException e) {
  1319. throw new JGitInternalException(MessageFormat.format(
  1320. JGitText.get().couldNotReadObjectWhileParsingCommit,
  1321. upstream.name()), e);
  1322. }
  1323. return this;
  1324. }
  1325. /**
  1326. * @param upstream
  1327. * the upstream branch
  1328. * @return {@code this}
  1329. * @throws RefNotFoundException
  1330. */
  1331. public RebaseCommand setUpstream(String upstream)
  1332. throws RefNotFoundException {
  1333. try {
  1334. ObjectId upstreamId = repo.resolve(upstream);
  1335. if (upstreamId == null)
  1336. throw new RefNotFoundException(MessageFormat.format(JGitText
  1337. .get().refNotResolved, upstream));
  1338. upstreamCommit = walk.parseCommit(repo.resolve(upstream));
  1339. upstreamCommitName = upstream;
  1340. return this;
  1341. } catch (IOException ioe) {
  1342. throw new JGitInternalException(ioe.getMessage(), ioe);
  1343. }
  1344. }
  1345. /**
  1346. * Optionally override the name of the upstream. If this is used, it has to
  1347. * come after any {@link #setUpstream} call.
  1348. *
  1349. * @param upstreamName
  1350. * the name which will be used to refer to upstream in conflicts
  1351. * @return {@code this}
  1352. */
  1353. public RebaseCommand setUpstreamName(String upstreamName) {
  1354. if (upstreamCommit == null) {
  1355. throw new IllegalStateException(
  1356. "setUpstreamName must be called after setUpstream."); //$NON-NLS-1$
  1357. }
  1358. this.upstreamCommitName = upstreamName;
  1359. return this;
  1360. }
  1361. /**
  1362. * @param operation
  1363. * the operation to perform
  1364. * @return {@code this}
  1365. */
  1366. public RebaseCommand setOperation(Operation operation) {
  1367. this.operation = operation;
  1368. return this;
  1369. }
  1370. /**
  1371. * @param monitor
  1372. * a progress monitor
  1373. * @return this instance
  1374. */
  1375. public RebaseCommand setProgressMonitor(ProgressMonitor monitor) {
  1376. if (monitor == null) {
  1377. monitor = NullProgressMonitor.INSTANCE;
  1378. }
  1379. this.monitor = monitor;
  1380. return this;
  1381. }
  1382. /**
  1383. * Enables interactive rebase
  1384. * <p>
  1385. * Does not stop after initialization of interactive rebase. This is
  1386. * equivalent to
  1387. * {@link RebaseCommand#runInteractively(InteractiveHandler, boolean)
  1388. * runInteractively(handler, false)};
  1389. * </p>
  1390. *
  1391. * @param handler
  1392. * @return this
  1393. */
  1394. public RebaseCommand runInteractively(InteractiveHandler handler) {
  1395. return runInteractively(handler, false);
  1396. }
  1397. /**
  1398. * Enables interactive rebase
  1399. * <p>
  1400. * If stopAfterRebaseInteractiveInitialization is {@code true} the rebase
  1401. * stops after initialization of interactive rebase returning
  1402. * {@link RebaseResult#INTERACTIVE_PREPARED_RESULT}
  1403. * </p>
  1404. *
  1405. * @param handler
  1406. * @param stopAfterRebaseInteractiveInitialization
  1407. * if {@code true} the rebase stops after initialization
  1408. * @return this instance
  1409. * @since 3.2
  1410. */
  1411. public RebaseCommand runInteractively(InteractiveHandler handler,
  1412. final boolean stopAfterRebaseInteractiveInitialization) {
  1413. this.stopAfterInitialization = stopAfterRebaseInteractiveInitialization;
  1414. this.interactiveHandler = handler;
  1415. return this;
  1416. }
  1417. /**
  1418. * @param strategy
  1419. * The merge strategy to use during this rebase operation.
  1420. * @return {@code this}
  1421. * @since 3.4
  1422. */
  1423. public RebaseCommand setStrategy(MergeStrategy strategy) {
  1424. this.strategy = strategy;
  1425. return this;
  1426. }
  1427. /**
  1428. * @param preserve
  1429. * True to re-create merges during rebase. Defaults to false, a
  1430. * flattening rebase.
  1431. * @return {@code this}
  1432. * @since 3.5
  1433. */
  1434. public RebaseCommand setPreserveMerges(boolean preserve) {
  1435. this.preserveMerges = preserve;
  1436. return this;
  1437. }
  1438. /**
  1439. * Allows configure rebase interactive process and modify commit message
  1440. */
  1441. public interface InteractiveHandler {
  1442. /**
  1443. * Given list of {@code steps} should be modified according to user
  1444. * rebase configuration
  1445. * @param steps
  1446. * initial configuration of rebase interactive
  1447. */
  1448. void prepareSteps(List<RebaseTodoLine> steps);
  1449. /**
  1450. * Used for editing commit message on REWORD
  1451. *
  1452. * @param commit
  1453. * @return new commit message
  1454. */
  1455. String modifyCommitMessage(String commit);
  1456. }
  1457. PersonIdent parseAuthor(byte[] raw) {
  1458. if (raw.length == 0)
  1459. return null;
  1460. Map<String, String> keyValueMap = new HashMap<String, String>();
  1461. for (int p = 0; p < raw.length;) {
  1462. int end = RawParseUtils.nextLF(raw, p);
  1463. if (end == p)
  1464. break;
  1465. int equalsIndex = RawParseUtils.next(raw, p, '=');
  1466. if (equalsIndex == end)
  1467. break;
  1468. String key = RawParseUtils.decode(raw, p, equalsIndex - 1);
  1469. String value = RawParseUtils.decode(raw, equalsIndex + 1, end - 2);
  1470. p = end;
  1471. keyValueMap.put(key, value);
  1472. }
  1473. String name = keyValueMap.get(GIT_AUTHOR_NAME);
  1474. String email = keyValueMap.get(GIT_AUTHOR_EMAIL);
  1475. String time = keyValueMap.get(GIT_AUTHOR_DATE);
  1476. // the time is saved as <seconds since 1970> <timezone offset>
  1477. int timeStart = 0;
  1478. if (time.startsWith("@")) //$NON-NLS-1$
  1479. timeStart = 1;
  1480. else
  1481. timeStart = 0;
  1482. long when = Long
  1483. .parseLong(time.substring(timeStart, time.indexOf(' '))) * 1000;
  1484. String tzOffsetString = time.substring(time.indexOf(' ') + 1);
  1485. int multiplier = -1;
  1486. if (tzOffsetString.charAt(0) == '+')
  1487. multiplier = 1;
  1488. int hours = Integer.parseInt(tzOffsetString.substring(1, 3));
  1489. int minutes = Integer.parseInt(tzOffsetString.substring(3, 5));
  1490. // this is in format (+/-)HHMM (hours and minutes)
  1491. // we need to convert into minutes
  1492. int tz = (hours * 60 + minutes) * multiplier;
  1493. if (name != null && email != null)
  1494. return new PersonIdent(name, email, when, tz);
  1495. return null;
  1496. }
  1497. private static class RebaseState {
  1498. private final File repoDirectory;
  1499. private File dir;
  1500. public RebaseState(File repoDirectory) {
  1501. this.repoDirectory = repoDirectory;
  1502. }
  1503. public File getDir() {
  1504. if (dir == null) {
  1505. File rebaseApply = new File(repoDirectory, REBASE_APPLY);
  1506. if (rebaseApply.exists()) {
  1507. dir = rebaseApply;
  1508. } else {
  1509. File rebaseMerge = new File(repoDirectory, REBASE_MERGE);
  1510. dir = rebaseMerge;
  1511. }
  1512. }
  1513. return dir;
  1514. }
  1515. /**
  1516. * @return Directory with rewritten commit hashes, usually exists if
  1517. * {@link RebaseCommand#preserveMerges} is true
  1518. **/
  1519. public File getRewrittenDir() {
  1520. return new File(getDir(), REWRITTEN);
  1521. }
  1522. public String readFile(String name) throws IOException {
  1523. return readFile(getDir(), name);
  1524. }
  1525. public void createFile(String name, String content) throws IOException {
  1526. createFile(getDir(), name, content);
  1527. }
  1528. public File getFile(String name) {
  1529. return new File(getDir(), name);
  1530. }
  1531. public String getPath(String name) {
  1532. return (getDir().getName() + "/" + name); //$NON-NLS-1$
  1533. }
  1534. private static String readFile(File directory, String fileName)
  1535. throws IOException {
  1536. byte[] content = IO.readFully(new File(directory, fileName));
  1537. // strip off the last LF
  1538. int end = RawParseUtils.prevLF(content, content.length);
  1539. return RawParseUtils.decode(content, 0, end + 1);
  1540. }
  1541. private static void createFile(File parentDir, String name,
  1542. String content)
  1543. throws IOException {
  1544. File file = new File(parentDir, name);
  1545. FileOutputStream fos = new FileOutputStream(file);
  1546. try {
  1547. fos.write(content.getBytes(Constants.CHARACTER_ENCODING));
  1548. fos.write('\n');
  1549. } finally {
  1550. fos.close();
  1551. }
  1552. }
  1553. private static void appendToFile(File file, String content)
  1554. throws IOException {
  1555. FileOutputStream fos = new FileOutputStream(file, true);
  1556. try {
  1557. fos.write(content.getBytes(Constants.CHARACTER_ENCODING));
  1558. fos.write('\n');
  1559. } finally {
  1560. fos.close();
  1561. }
  1562. }
  1563. }
  1564. }