您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

RebaseCommand.java 55KB

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