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

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