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

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