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

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