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

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