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

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