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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  1. /*
  2. * Copyright (C) 2010, Mathias Kinzler <mathias.kinzler@sap.com>
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.api;
  44. import java.io.BufferedReader;
  45. import java.io.BufferedWriter;
  46. import java.io.ByteArrayOutputStream;
  47. import java.io.File;
  48. import java.io.FileInputStream;
  49. import java.io.FileNotFoundException;
  50. import java.io.FileOutputStream;
  51. import java.io.IOException;
  52. import java.io.InputStreamReader;
  53. import java.io.OutputStreamWriter;
  54. import java.text.MessageFormat;
  55. import java.util.ArrayList;
  56. import java.util.Collection;
  57. import java.util.Collections;
  58. import java.util.HashMap;
  59. import java.util.List;
  60. import java.util.Map;
  61. import org.eclipse.jgit.api.RebaseResult.Status;
  62. import org.eclipse.jgit.api.errors.CheckoutConflictException;
  63. import org.eclipse.jgit.api.errors.GitAPIException;
  64. import org.eclipse.jgit.api.errors.InvalidRefNameException;
  65. import org.eclipse.jgit.api.errors.JGitInternalException;
  66. import org.eclipse.jgit.api.errors.NoHeadException;
  67. import org.eclipse.jgit.api.errors.RefAlreadyExistsException;
  68. import org.eclipse.jgit.api.errors.RefNotFoundException;
  69. import org.eclipse.jgit.api.errors.UnmergedPathsException;
  70. import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
  71. import org.eclipse.jgit.diff.DiffFormatter;
  72. import org.eclipse.jgit.dircache.DirCache;
  73. import org.eclipse.jgit.dircache.DirCacheCheckout;
  74. import org.eclipse.jgit.dircache.DirCacheIterator;
  75. import org.eclipse.jgit.internal.JGitText;
  76. import org.eclipse.jgit.lib.AbbreviatedObjectId;
  77. import org.eclipse.jgit.lib.AnyObjectId;
  78. import org.eclipse.jgit.lib.Constants;
  79. import org.eclipse.jgit.lib.NullProgressMonitor;
  80. import org.eclipse.jgit.lib.ObjectId;
  81. import org.eclipse.jgit.lib.ObjectReader;
  82. import org.eclipse.jgit.lib.PersonIdent;
  83. import org.eclipse.jgit.lib.ProgressMonitor;
  84. import org.eclipse.jgit.lib.Ref;
  85. import org.eclipse.jgit.lib.RefUpdate;
  86. import org.eclipse.jgit.lib.RefUpdate.Result;
  87. import org.eclipse.jgit.lib.Repository;
  88. import org.eclipse.jgit.revwalk.RevCommit;
  89. import org.eclipse.jgit.revwalk.RevWalk;
  90. import org.eclipse.jgit.treewalk.TreeWalk;
  91. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  92. import org.eclipse.jgit.util.FileUtils;
  93. import org.eclipse.jgit.util.IO;
  94. import org.eclipse.jgit.util.RawParseUtils;
  95. /**
  96. * A class used to execute a {@code Rebase} command. It has setters for all
  97. * supported options and arguments of this command and a {@link #call()} method
  98. * to finally execute the command. Each instance of this class should only be
  99. * used for one invocation of the command (means: one call to {@link #call()})
  100. * <p>
  101. *
  102. * @see <a
  103. * href="http://www.kernel.org/pub/software/scm/git/docs/git-rebase.html"
  104. * >Git documentation about Rebase</a>
  105. */
  106. public class RebaseCommand extends GitCommand<RebaseResult> {
  107. /**
  108. * The name of the "rebase-merge" folder
  109. */
  110. public static final String REBASE_MERGE = "rebase-merge"; //$NON-NLS-1$
  111. /**
  112. * The name of the "stopped-sha" file
  113. */
  114. public static final String STOPPED_SHA = "stopped-sha"; //$NON-NLS-1$
  115. private static final String AUTHOR_SCRIPT = "author-script"; //$NON-NLS-1$
  116. private static final String DONE = "done"; //$NON-NLS-1$
  117. private static final String GIT_AUTHOR_DATE = "GIT_AUTHOR_DATE"; //$NON-NLS-1$
  118. private static final String GIT_AUTHOR_EMAIL = "GIT_AUTHOR_EMAIL"; //$NON-NLS-1$
  119. private static final String GIT_AUTHOR_NAME = "GIT_AUTHOR_NAME"; //$NON-NLS-1$
  120. private static final String GIT_REBASE_TODO = "git-rebase-todo"; //$NON-NLS-1$
  121. private static final String HEAD_NAME = "head-name"; //$NON-NLS-1$
  122. private static final String INTERACTIVE = "interactive"; //$NON-NLS-1$
  123. private static final String MESSAGE = "message"; //$NON-NLS-1$
  124. private static final String ONTO = "onto"; //$NON-NLS-1$
  125. private static final String ONTO_NAME = "onto-name"; //$NON-NLS-1$
  126. private static final String PATCH = "patch"; //$NON-NLS-1$
  127. private static final String REBASE_HEAD = "head"; //$NON-NLS-1$
  128. private static final String AMEND = "amend"; //$NON-NLS-1$
  129. /**
  130. * The available operations
  131. */
  132. public enum Operation {
  133. /**
  134. * Initiates rebase
  135. */
  136. BEGIN,
  137. /**
  138. * Continues after a conflict resolution
  139. */
  140. CONTINUE,
  141. /**
  142. * Skips the "current" commit
  143. */
  144. SKIP,
  145. /**
  146. * Aborts and resets the current rebase
  147. */
  148. ABORT;
  149. }
  150. private Operation operation = Operation.BEGIN;
  151. private RevCommit upstreamCommit;
  152. private String upstreamCommitName;
  153. private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;
  154. private final RevWalk walk;
  155. private final File rebaseDir;
  156. private InteractiveHandler interactiveHandler;
  157. /**
  158. * @param repo
  159. */
  160. protected RebaseCommand(Repository repo) {
  161. super(repo);
  162. walk = new RevWalk(repo);
  163. rebaseDir = new File(repo.getDirectory(), REBASE_MERGE);
  164. }
  165. /**
  166. * Executes the {@code Rebase} command with all the options and parameters
  167. * collected by the setter methods of this class. Each instance of this
  168. * class should only be used for one invocation of the command. Don't call
  169. * this method twice on an instance.
  170. *
  171. * @return an object describing the result of this command
  172. * @throws GitAPIException
  173. * @throws WrongRepositoryStateException
  174. * @throws NoHeadException
  175. * @throws RefNotFoundException
  176. */
  177. public RebaseResult call() throws GitAPIException, NoHeadException,
  178. RefNotFoundException, WrongRepositoryStateException {
  179. RevCommit newHead = null;
  180. boolean lastStepWasForward = false;
  181. checkCallable();
  182. checkParameters();
  183. try {
  184. switch (operation) {
  185. case ABORT:
  186. try {
  187. return abort(RebaseResult.ABORTED_RESULT);
  188. } catch (IOException ioe) {
  189. throw new JGitInternalException(ioe.getMessage(), ioe);
  190. }
  191. case SKIP:
  192. // fall through
  193. case CONTINUE:
  194. String upstreamCommitId = readFile(rebaseDir, ONTO);
  195. try {
  196. upstreamCommitName = readFile(rebaseDir, ONTO_NAME);
  197. } catch (FileNotFoundException e) {
  198. // Fall back to commit ID if file doesn't exist (e.g. rebase
  199. // was started by C Git)
  200. upstreamCommitName = upstreamCommitId;
  201. }
  202. this.upstreamCommit = walk.parseCommit(repo
  203. .resolve(upstreamCommitId));
  204. break;
  205. case BEGIN:
  206. RebaseResult res = initFilesAndRewind();
  207. if (res != null)
  208. return res;
  209. }
  210. if (monitor.isCancelled())
  211. return abort(RebaseResult.ABORTED_RESULT);
  212. if (operation == Operation.CONTINUE) {
  213. newHead = continueRebase();
  214. File amendFile = new File(rebaseDir, AMEND);
  215. boolean amendExists = amendFile.exists();
  216. if (amendExists) {
  217. FileUtils.delete(amendFile);
  218. }
  219. if (newHead == null && !amendExists) {
  220. // continueRebase() returns null only if no commit was
  221. // neccessary. This means that no changes where left over
  222. // after resolving all conflicts. In this case, cgit stops
  223. // and displays a nice message to the user, telling him to
  224. // either do changes or skip the commit instead of continue.
  225. return RebaseResult.NOTHING_TO_COMMIT_RESULT;
  226. }
  227. }
  228. if (operation == Operation.SKIP)
  229. newHead = checkoutCurrentHead();
  230. ObjectReader or = repo.newObjectReader();
  231. List<Step> steps = loadSteps();
  232. if (isInteractive()) {
  233. interactiveHandler.prepareSteps(steps);
  234. BufferedWriter fw = new BufferedWriter(
  235. new OutputStreamWriter(new FileOutputStream(new File(
  236. rebaseDir, GIT_REBASE_TODO)),
  237. Constants.CHARACTER_ENCODING));
  238. fw.newLine();
  239. try {
  240. StringBuilder sb = new StringBuilder();
  241. for (Step step : steps) {
  242. sb.setLength(0);
  243. sb.append(step.action.token);
  244. sb.append(" "); //$NON-NLS-1$
  245. sb.append(step.commit.name());
  246. sb.append(" "); //$NON-NLS-1$
  247. sb.append(RawParseUtils.decode(step.shortMessage)
  248. .trim());
  249. fw.write(sb.toString());
  250. fw.newLine();
  251. }
  252. } finally {
  253. fw.close();
  254. }
  255. }
  256. for (Step step : steps) {
  257. popSteps(1);
  258. Collection<ObjectId> ids = or.resolve(step.commit);
  259. if (ids.size() != 1)
  260. throw new JGitInternalException(
  261. "Could not resolve uniquely the abbreviated object ID");
  262. RevCommit commitToPick = walk
  263. .parseCommit(ids.iterator().next());
  264. if (monitor.isCancelled())
  265. return new RebaseResult(commitToPick);
  266. try {
  267. monitor.beginTask(MessageFormat.format(
  268. JGitText.get().applyingCommit,
  269. commitToPick.getShortMessage()),
  270. ProgressMonitor.UNKNOWN);
  271. // if the first parent of commitToPick is the current HEAD,
  272. // we do a fast-forward instead of cherry-pick to avoid
  273. // unnecessary object rewriting
  274. newHead = tryFastForward(commitToPick);
  275. lastStepWasForward = newHead != null;
  276. if (!lastStepWasForward) {
  277. // TODO if the content of this commit is already merged
  278. // here we should skip this step in order to avoid
  279. // confusing pseudo-changed
  280. String ourCommitName = getOurCommitName();
  281. CherryPickResult cherryPickResult = new Git(repo)
  282. .cherryPick().include(commitToPick)
  283. .setOurCommitName(ourCommitName).call();
  284. switch (cherryPickResult.getStatus()) {
  285. case FAILED:
  286. if (operation == Operation.BEGIN)
  287. return abort(new RebaseResult(
  288. cherryPickResult.getFailingPaths()));
  289. else
  290. return stop(commitToPick);
  291. case CONFLICTING:
  292. return stop(commitToPick);
  293. case OK:
  294. newHead = cherryPickResult.getNewHead();
  295. }
  296. }
  297. switch (step.action) {
  298. case PICK:
  299. continue; // continue rebase process on pick command
  300. case REWORD:
  301. String oldMessage = commitToPick.getFullMessage();
  302. String newMessage = interactiveHandler
  303. .modifyCommitMessage(oldMessage);
  304. newHead = new Git(repo).commit().setMessage(newMessage)
  305. .setAmend(true).call();
  306. continue;
  307. case EDIT:
  308. createFile(rebaseDir, AMEND, commitToPick.name());
  309. return stop(commitToPick);
  310. }
  311. } finally {
  312. monitor.endTask();
  313. }
  314. }
  315. if (newHead != null) {
  316. String headName = readFile(rebaseDir, HEAD_NAME);
  317. updateHead(headName, newHead);
  318. FileUtils.delete(rebaseDir, FileUtils.RECURSIVE);
  319. if (lastStepWasForward)
  320. return RebaseResult.FAST_FORWARD_RESULT;
  321. return RebaseResult.OK_RESULT;
  322. }
  323. return RebaseResult.FAST_FORWARD_RESULT;
  324. } catch (IOException ioe) {
  325. throw new JGitInternalException(ioe.getMessage(), ioe);
  326. }
  327. }
  328. private String getOurCommitName() {
  329. // If onto is different from upstream, this should say "onto", but
  330. // RebaseCommand doesn't support a different "onto" at the moment.
  331. String ourCommitName = "Upstream, based on "
  332. + Repository.shortenRefName(upstreamCommitName);
  333. return ourCommitName;
  334. }
  335. private void updateHead(String headName, RevCommit newHead)
  336. throws IOException {
  337. // point the previous head (if any) to the new commit
  338. if (headName.startsWith(Constants.R_REFS)) {
  339. RefUpdate rup = repo.updateRef(headName);
  340. rup.setNewObjectId(newHead);
  341. Result res = rup.forceUpdate();
  342. switch (res) {
  343. case FAST_FORWARD:
  344. case FORCED:
  345. case NO_CHANGE:
  346. break;
  347. default:
  348. throw new JGitInternalException("Updating HEAD failed");
  349. }
  350. rup = repo.updateRef(Constants.HEAD);
  351. res = rup.link(headName);
  352. switch (res) {
  353. case FAST_FORWARD:
  354. case FORCED:
  355. case NO_CHANGE:
  356. break;
  357. default:
  358. throw new JGitInternalException("Updating HEAD failed");
  359. }
  360. }
  361. }
  362. private RevCommit checkoutCurrentHead() throws IOException, NoHeadException {
  363. ObjectId headTree = repo.resolve(Constants.HEAD + "^{tree}"); //$NON-NLS-1$
  364. if (headTree == null)
  365. throw new NoHeadException(
  366. JGitText.get().cannotRebaseWithoutCurrentHead);
  367. DirCache dc = repo.lockDirCache();
  368. try {
  369. DirCacheCheckout dco = new DirCacheCheckout(repo, dc, headTree);
  370. dco.setFailOnConflict(false);
  371. boolean needsDeleteFiles = dco.checkout();
  372. if (needsDeleteFiles) {
  373. List<String> fileList = dco.getToBeDeleted();
  374. for (String filePath : fileList) {
  375. File fileToDelete = new File(repo.getWorkTree(), filePath);
  376. if (fileToDelete.exists())
  377. FileUtils.delete(fileToDelete, FileUtils.RECURSIVE
  378. | FileUtils.RETRY);
  379. }
  380. }
  381. } finally {
  382. dc.unlock();
  383. }
  384. RevWalk rw = new RevWalk(repo);
  385. RevCommit commit = rw.parseCommit(repo.resolve(Constants.HEAD));
  386. rw.release();
  387. return commit;
  388. }
  389. /**
  390. * @return the commit if we had to do a commit, otherwise null
  391. * @throws GitAPIException
  392. * @throws IOException
  393. */
  394. private RevCommit continueRebase() throws GitAPIException, IOException {
  395. // if there are still conflicts, we throw a specific Exception
  396. DirCache dc = repo.readDirCache();
  397. boolean hasUnmergedPaths = dc.hasUnmergedPaths();
  398. if (hasUnmergedPaths)
  399. throw new UnmergedPathsException();
  400. // determine whether we need to commit
  401. TreeWalk treeWalk = new TreeWalk(repo);
  402. treeWalk.reset();
  403. treeWalk.setRecursive(true);
  404. treeWalk.addTree(new DirCacheIterator(dc));
  405. ObjectId id = repo.resolve(Constants.HEAD + "^{tree}"); //$NON-NLS-1$
  406. if (id == null)
  407. throw new NoHeadException(
  408. JGitText.get().cannotRebaseWithoutCurrentHead);
  409. treeWalk.addTree(id);
  410. treeWalk.setFilter(TreeFilter.ANY_DIFF);
  411. boolean needsCommit = treeWalk.next();
  412. treeWalk.release();
  413. if (needsCommit) {
  414. CommitCommand commit = new Git(repo).commit();
  415. commit.setMessage(readFile(rebaseDir, MESSAGE));
  416. commit.setAuthor(parseAuthor());
  417. return commit.call();
  418. }
  419. return null;
  420. }
  421. private PersonIdent parseAuthor() throws IOException {
  422. File authorScriptFile = new File(rebaseDir, AUTHOR_SCRIPT);
  423. byte[] raw;
  424. try {
  425. raw = IO.readFully(authorScriptFile);
  426. } catch (FileNotFoundException notFound) {
  427. return null;
  428. }
  429. return parseAuthor(raw);
  430. }
  431. private RebaseResult stop(RevCommit commitToPick) throws IOException {
  432. PersonIdent author = commitToPick.getAuthorIdent();
  433. String authorScript = toAuthorScript(author);
  434. createFile(rebaseDir, AUTHOR_SCRIPT, authorScript);
  435. createFile(rebaseDir, MESSAGE, commitToPick.getFullMessage());
  436. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  437. DiffFormatter df = new DiffFormatter(bos);
  438. df.setRepository(repo);
  439. df.format(commitToPick.getParent(0), commitToPick);
  440. createFile(rebaseDir, PATCH, new String(bos.toByteArray(),
  441. Constants.CHARACTER_ENCODING));
  442. createFile(rebaseDir, STOPPED_SHA, repo.newObjectReader().abbreviate(
  443. commitToPick).name());
  444. // Remove cherry pick state file created by CherryPickCommand, it's not
  445. // needed for rebase
  446. repo.writeCherryPickHead(null);
  447. return new RebaseResult(commitToPick);
  448. }
  449. String toAuthorScript(PersonIdent author) {
  450. StringBuilder sb = new StringBuilder(100);
  451. sb.append(GIT_AUTHOR_NAME);
  452. sb.append("='"); //$NON-NLS-1$
  453. sb.append(author.getName());
  454. sb.append("'\n"); //$NON-NLS-1$
  455. sb.append(GIT_AUTHOR_EMAIL);
  456. sb.append("='"); //$NON-NLS-1$
  457. sb.append(author.getEmailAddress());
  458. sb.append("'\n"); //$NON-NLS-1$
  459. // the command line uses the "external String"
  460. // representation for date and timezone
  461. sb.append(GIT_AUTHOR_DATE);
  462. sb.append("='"); //$NON-NLS-1$
  463. sb.append("@"); // @ for time in seconds since 1970 //$NON-NLS-1$
  464. String externalString = author.toExternalString();
  465. sb
  466. .append(externalString.substring(externalString
  467. .lastIndexOf('>') + 2));
  468. sb.append("'\n"); //$NON-NLS-1$
  469. return sb.toString();
  470. }
  471. /**
  472. * Removes the number of lines given in the parameter from the
  473. * <code>git-rebase-todo</code> file but preserves comments and other lines
  474. * that can not be parsed as steps
  475. *
  476. * @param numSteps
  477. * @throws IOException
  478. */
  479. private void popSteps(int numSteps) throws IOException {
  480. if (numSteps == 0)
  481. return;
  482. List<String> todoLines = new ArrayList<String>();
  483. List<String> poppedLines = new ArrayList<String>();
  484. File todoFile = new File(rebaseDir, GIT_REBASE_TODO);
  485. File doneFile = new File(rebaseDir, DONE);
  486. BufferedReader br = new BufferedReader(new InputStreamReader(
  487. new FileInputStream(todoFile), Constants.CHARACTER_ENCODING));
  488. try {
  489. // check if the line starts with a action tag (pick, skip...)
  490. while (poppedLines.size() < numSteps) {
  491. String popCandidate = br.readLine();
  492. if (popCandidate == null)
  493. break;
  494. if (popCandidate.length() == 0)
  495. continue;
  496. if (popCandidate.charAt(0) == '#')
  497. continue;
  498. int spaceIndex = popCandidate.indexOf(' ');
  499. boolean pop = false;
  500. if (spaceIndex >= 0) {
  501. String actionToken = popCandidate.substring(0, spaceIndex);
  502. pop = Action.parse(actionToken) != null;
  503. }
  504. if (pop)
  505. poppedLines.add(popCandidate);
  506. else
  507. todoLines.add(popCandidate);
  508. }
  509. String readLine = br.readLine();
  510. while (readLine != null) {
  511. todoLines.add(readLine);
  512. readLine = br.readLine();
  513. }
  514. } finally {
  515. br.close();
  516. }
  517. BufferedWriter todoWriter = new BufferedWriter(new OutputStreamWriter(
  518. new FileOutputStream(todoFile), Constants.CHARACTER_ENCODING));
  519. try {
  520. for (String writeLine : todoLines) {
  521. todoWriter.write(writeLine);
  522. todoWriter.newLine();
  523. }
  524. } finally {
  525. todoWriter.close();
  526. }
  527. if (poppedLines.size() > 0) {
  528. // append here
  529. BufferedWriter doneWriter = new BufferedWriter(
  530. new OutputStreamWriter(
  531. new FileOutputStream(doneFile, true),
  532. Constants.CHARACTER_ENCODING));
  533. try {
  534. for (String writeLine : poppedLines) {
  535. doneWriter.write(writeLine);
  536. doneWriter.newLine();
  537. }
  538. } finally {
  539. doneWriter.close();
  540. }
  541. }
  542. }
  543. private RebaseResult initFilesAndRewind() throws IOException,
  544. GitAPIException {
  545. // we need to store everything into files so that we can implement
  546. // --skip, --continue, and --abort
  547. Ref head = repo.getRef(Constants.HEAD);
  548. if (head == null || head.getObjectId() == null)
  549. throw new RefNotFoundException(MessageFormat.format(
  550. JGitText.get().refNotResolved, Constants.HEAD));
  551. String headName;
  552. if (head.isSymbolic())
  553. headName = head.getTarget().getName();
  554. else
  555. headName = "detached HEAD";
  556. ObjectId headId = head.getObjectId();
  557. if (headId == null)
  558. throw new RefNotFoundException(MessageFormat.format(
  559. JGitText.get().refNotResolved, Constants.HEAD));
  560. RevCommit headCommit = walk.lookupCommit(headId);
  561. RevCommit upstream = walk.lookupCommit(upstreamCommit.getId());
  562. if (!isInteractive() && walk.isMergedInto(upstream, headCommit))
  563. return RebaseResult.UP_TO_DATE_RESULT;
  564. else if (!isInteractive() && walk.isMergedInto(headCommit, upstream)) {
  565. // head is already merged into upstream, fast-foward
  566. monitor.beginTask(MessageFormat.format(
  567. JGitText.get().resettingHead,
  568. upstreamCommit.getShortMessage()), ProgressMonitor.UNKNOWN);
  569. checkoutCommit(upstreamCommit);
  570. monitor.endTask();
  571. updateHead(headName, upstreamCommit);
  572. return RebaseResult.FAST_FORWARD_RESULT;
  573. }
  574. monitor.beginTask(JGitText.get().obtainingCommitsForCherryPick,
  575. ProgressMonitor.UNKNOWN);
  576. // determine the commits to be applied
  577. LogCommand cmd = new Git(repo).log().addRange(upstreamCommit,
  578. headCommit);
  579. Iterable<RevCommit> commitsToUse = cmd.call();
  580. List<RevCommit> cherryPickList = new ArrayList<RevCommit>();
  581. for (RevCommit commit : commitsToUse) {
  582. if (commit.getParentCount() != 1)
  583. throw new JGitInternalException(
  584. MessageFormat.format(
  585. JGitText.get().canOnlyCherryPickCommitsWithOneParent,
  586. commit.name(),
  587. Integer.valueOf(commit.getParentCount())));
  588. cherryPickList.add(commit);
  589. }
  590. Collections.reverse(cherryPickList);
  591. // create the folder for the meta information
  592. FileUtils.mkdir(rebaseDir);
  593. repo.writeOrigHead(headId);
  594. createFile(rebaseDir, REBASE_HEAD, headId.name());
  595. createFile(rebaseDir, HEAD_NAME, headName);
  596. createFile(rebaseDir, ONTO, upstreamCommit.name());
  597. createFile(rebaseDir, ONTO_NAME, upstreamCommitName);
  598. createFile(rebaseDir, INTERACTIVE, ""); //$NON-NLS-1$
  599. BufferedWriter fw = new BufferedWriter(new OutputStreamWriter(
  600. new FileOutputStream(new File(rebaseDir, GIT_REBASE_TODO)),
  601. Constants.CHARACTER_ENCODING));
  602. fw.write("# Created by EGit: rebasing " + upstreamCommit.name()
  603. + " onto " + headId.name());
  604. fw.newLine();
  605. try {
  606. StringBuilder sb = new StringBuilder();
  607. ObjectReader reader = walk.getObjectReader();
  608. for (RevCommit commit : cherryPickList) {
  609. sb.setLength(0);
  610. sb.append(Action.PICK.toToken());
  611. sb.append(" "); //$NON-NLS-1$
  612. sb.append(reader.abbreviate(commit).name());
  613. sb.append(" "); //$NON-NLS-1$
  614. sb.append(commit.getShortMessage());
  615. fw.write(sb.toString());
  616. fw.newLine();
  617. }
  618. } finally {
  619. fw.close();
  620. }
  621. monitor.endTask();
  622. // we rewind to the upstream commit
  623. monitor.beginTask(MessageFormat.format(JGitText.get().rewinding,
  624. upstreamCommit.getShortMessage()), ProgressMonitor.UNKNOWN);
  625. boolean checkoutOk = false;
  626. try {
  627. checkoutOk = checkoutCommit(upstreamCommit);
  628. } finally {
  629. if (!checkoutOk)
  630. FileUtils.delete(rebaseDir, FileUtils.RECURSIVE);
  631. }
  632. monitor.endTask();
  633. return null;
  634. }
  635. private boolean isInteractive() {
  636. return interactiveHandler != null;
  637. }
  638. /**
  639. * checks if we can fast-forward and returns the new head if it is possible
  640. *
  641. * @param newCommit
  642. * @return the new head, or null
  643. * @throws IOException
  644. * @throws GitAPIException
  645. */
  646. public RevCommit tryFastForward(RevCommit newCommit) throws IOException,
  647. GitAPIException {
  648. Ref head = repo.getRef(Constants.HEAD);
  649. if (head == null || head.getObjectId() == null)
  650. throw new RefNotFoundException(MessageFormat.format(
  651. JGitText.get().refNotResolved, Constants.HEAD));
  652. ObjectId headId = head.getObjectId();
  653. if (headId == null)
  654. throw new RefNotFoundException(MessageFormat.format(
  655. JGitText.get().refNotResolved, Constants.HEAD));
  656. RevCommit headCommit = walk.lookupCommit(headId);
  657. if (walk.isMergedInto(newCommit, headCommit))
  658. return newCommit;
  659. String headName;
  660. if (head.isSymbolic())
  661. headName = head.getTarget().getName();
  662. else
  663. headName = "detached HEAD";
  664. return tryFastForward(headName, headCommit, newCommit);
  665. }
  666. private RevCommit tryFastForward(String headName, RevCommit oldCommit,
  667. RevCommit newCommit) throws IOException, GitAPIException {
  668. boolean tryRebase = false;
  669. for (RevCommit parentCommit : newCommit.getParents())
  670. if (parentCommit.equals(oldCommit))
  671. tryRebase = true;
  672. if (!tryRebase)
  673. return null;
  674. CheckoutCommand co = new CheckoutCommand(repo);
  675. try {
  676. co.setName(newCommit.name()).call();
  677. if (headName.startsWith(Constants.R_HEADS)) {
  678. RefUpdate rup = repo.updateRef(headName);
  679. rup.setExpectedOldObjectId(oldCommit);
  680. rup.setNewObjectId(newCommit);
  681. rup.setRefLogMessage("Fast-foward from " + oldCommit.name() //$NON-NLS-1$
  682. + " to " + newCommit.name(), false); //$NON-NLS-1$
  683. Result res = rup.update(walk);
  684. switch (res) {
  685. case FAST_FORWARD:
  686. case NO_CHANGE:
  687. case FORCED:
  688. break;
  689. default:
  690. throw new IOException("Could not fast-forward"); //$NON-NLS-1$
  691. }
  692. }
  693. return newCommit;
  694. } catch (RefAlreadyExistsException e) {
  695. throw new JGitInternalException(e.getMessage(), e);
  696. } catch (RefNotFoundException e) {
  697. throw new JGitInternalException(e.getMessage(), e);
  698. } catch (InvalidRefNameException e) {
  699. throw new JGitInternalException(e.getMessage(), e);
  700. } catch (CheckoutConflictException e) {
  701. throw new JGitInternalException(e.getMessage(), e);
  702. }
  703. }
  704. private void checkParameters() throws WrongRepositoryStateException {
  705. if (this.operation != Operation.BEGIN) {
  706. // these operations are only possible while in a rebasing state
  707. switch (repo.getRepositoryState()) {
  708. case REBASING_INTERACTIVE:
  709. case REBASING:
  710. case REBASING_REBASING:
  711. case REBASING_MERGE:
  712. break;
  713. default:
  714. throw new WrongRepositoryStateException(MessageFormat.format(
  715. JGitText.get().wrongRepositoryState, repo
  716. .getRepositoryState().name()));
  717. }
  718. } else
  719. switch (repo.getRepositoryState()) {
  720. case SAFE:
  721. if (this.upstreamCommit == null)
  722. throw new JGitInternalException(MessageFormat
  723. .format(JGitText.get().missingRequiredParameter,
  724. "upstream"));
  725. return;
  726. default:
  727. throw new WrongRepositoryStateException(MessageFormat.format(
  728. JGitText.get().wrongRepositoryState, repo
  729. .getRepositoryState().name()));
  730. }
  731. }
  732. private void createFile(File parentDir, String name, String content)
  733. throws IOException {
  734. File file = new File(parentDir, name);
  735. FileOutputStream fos = new FileOutputStream(file);
  736. try {
  737. fos.write(content.getBytes(Constants.CHARACTER_ENCODING));
  738. fos.write('\n');
  739. } finally {
  740. fos.close();
  741. }
  742. }
  743. private RebaseResult abort(RebaseResult result) throws IOException {
  744. try {
  745. ObjectId origHead = repo.readOrigHead();
  746. String commitId = origHead != null ? origHead.name() : null;
  747. monitor.beginTask(MessageFormat.format(
  748. JGitText.get().abortingRebase, commitId),
  749. ProgressMonitor.UNKNOWN);
  750. DirCacheCheckout dco;
  751. if (commitId == null)
  752. throw new JGitInternalException(
  753. JGitText.get().abortingRebaseFailedNoOrigHead);
  754. ObjectId id = repo.resolve(commitId);
  755. RevCommit commit = walk.parseCommit(id);
  756. if (result.getStatus().equals(Status.FAILED)) {
  757. RevCommit head = walk.parseCommit(repo.resolve(Constants.HEAD));
  758. dco = new DirCacheCheckout(repo, head.getTree(),
  759. repo.lockDirCache(), commit.getTree());
  760. } else {
  761. dco = new DirCacheCheckout(repo, repo.lockDirCache(),
  762. commit.getTree());
  763. }
  764. dco.setFailOnConflict(false);
  765. dco.checkout();
  766. walk.release();
  767. } finally {
  768. monitor.endTask();
  769. }
  770. try {
  771. String headName = readFile(rebaseDir, HEAD_NAME);
  772. if (headName.startsWith(Constants.R_REFS)) {
  773. monitor.beginTask(MessageFormat.format(
  774. JGitText.get().resettingHead, headName),
  775. ProgressMonitor.UNKNOWN);
  776. // update the HEAD
  777. RefUpdate refUpdate = repo.updateRef(Constants.HEAD, false);
  778. Result res = refUpdate.link(headName);
  779. switch (res) {
  780. case FAST_FORWARD:
  781. case FORCED:
  782. case NO_CHANGE:
  783. break;
  784. default:
  785. throw new JGitInternalException(
  786. JGitText.get().abortingRebaseFailed);
  787. }
  788. }
  789. // cleanup the files
  790. FileUtils.delete(rebaseDir, FileUtils.RECURSIVE);
  791. repo.writeCherryPickHead(null);
  792. return result;
  793. } finally {
  794. monitor.endTask();
  795. }
  796. }
  797. private String readFile(File directory, String fileName) throws IOException {
  798. byte[] content = IO.readFully(new File(directory, fileName));
  799. // strip off the last LF
  800. int end = content.length;
  801. while (0 < end && content[end - 1] == '\n')
  802. end--;
  803. return RawParseUtils.decode(content, 0, end);
  804. }
  805. private boolean checkoutCommit(RevCommit commit) throws IOException {
  806. try {
  807. RevCommit head = walk.parseCommit(repo.resolve(Constants.HEAD));
  808. DirCacheCheckout dco = new DirCacheCheckout(repo, head.getTree(),
  809. repo.lockDirCache(), commit.getTree());
  810. dco.setFailOnConflict(true);
  811. dco.checkout();
  812. // update the HEAD
  813. RefUpdate refUpdate = repo.updateRef(Constants.HEAD, true);
  814. refUpdate.setExpectedOldObjectId(head);
  815. refUpdate.setNewObjectId(commit);
  816. Result res = refUpdate.forceUpdate();
  817. switch (res) {
  818. case FAST_FORWARD:
  819. case NO_CHANGE:
  820. case FORCED:
  821. break;
  822. default:
  823. throw new IOException("Could not rewind to upstream commit");
  824. }
  825. } finally {
  826. walk.release();
  827. monitor.endTask();
  828. }
  829. return true;
  830. }
  831. List<Step> loadSteps() throws IOException {
  832. byte[] buf = IO.readFully(new File(rebaseDir, GIT_REBASE_TODO));
  833. int ptr = 0;
  834. int tokenBegin = 0;
  835. ArrayList<Step> r = new ArrayList<Step>();
  836. while (ptr < buf.length) {
  837. tokenBegin = ptr;
  838. ptr = RawParseUtils.nextLF(buf, ptr);
  839. int nextSpace = RawParseUtils.next(buf, tokenBegin, ' ');
  840. int tokenCount = 0;
  841. Step current = null;
  842. while (tokenCount < 3 && nextSpace < ptr) {
  843. switch (tokenCount) {
  844. case 0:
  845. String actionToken = new String(buf, tokenBegin, nextSpace
  846. - tokenBegin - 1);
  847. tokenBegin = nextSpace;
  848. if (actionToken.charAt(0) == '#') {
  849. tokenCount = 3;
  850. break;
  851. }
  852. Action action = Action.parse(actionToken);
  853. if (action != null)
  854. current = new Step(Action.parse(actionToken));
  855. break;
  856. case 1:
  857. if (current == null)
  858. break;
  859. nextSpace = RawParseUtils.next(buf, tokenBegin, ' ');
  860. String commitToken = new String(buf, tokenBegin, nextSpace
  861. - tokenBegin - 1);
  862. tokenBegin = nextSpace;
  863. current.commit = AbbreviatedObjectId
  864. .fromString(commitToken);
  865. break;
  866. case 2:
  867. if (current == null)
  868. break;
  869. nextSpace = ptr;
  870. int length = ptr - tokenBegin;
  871. current.shortMessage = new byte[length];
  872. System.arraycopy(buf, tokenBegin, current.shortMessage, 0,
  873. length);
  874. r.add(current);
  875. break;
  876. }
  877. tokenCount++;
  878. }
  879. }
  880. return r;
  881. }
  882. /**
  883. * @param upstream
  884. * the upstream commit
  885. * @return {@code this}
  886. */
  887. public RebaseCommand setUpstream(RevCommit upstream) {
  888. this.upstreamCommit = upstream;
  889. this.upstreamCommitName = upstream.name();
  890. return this;
  891. }
  892. /**
  893. * @param upstream
  894. * id of the upstream commit
  895. * @return {@code this}
  896. */
  897. public RebaseCommand setUpstream(AnyObjectId upstream) {
  898. try {
  899. this.upstreamCommit = walk.parseCommit(upstream);
  900. this.upstreamCommitName = upstream.name();
  901. } catch (IOException e) {
  902. throw new JGitInternalException(MessageFormat.format(
  903. JGitText.get().couldNotReadObjectWhileParsingCommit,
  904. upstream.name()), e);
  905. }
  906. return this;
  907. }
  908. /**
  909. * @param upstream
  910. * the upstream branch
  911. * @return {@code this}
  912. * @throws RefNotFoundException
  913. */
  914. public RebaseCommand setUpstream(String upstream)
  915. throws RefNotFoundException {
  916. try {
  917. ObjectId upstreamId = repo.resolve(upstream);
  918. if (upstreamId == null)
  919. throw new RefNotFoundException(MessageFormat.format(JGitText
  920. .get().refNotResolved, upstream));
  921. upstreamCommit = walk.parseCommit(repo.resolve(upstream));
  922. upstreamCommitName = upstream;
  923. return this;
  924. } catch (IOException ioe) {
  925. throw new JGitInternalException(ioe.getMessage(), ioe);
  926. }
  927. }
  928. /**
  929. * Optionally override the name of the upstream. If this is used, it has to
  930. * come after any {@link #setUpstream} call.
  931. *
  932. * @param upstreamName
  933. * the name which will be used to refer to upstream in conflicts
  934. * @return {@code this}
  935. */
  936. public RebaseCommand setUpstreamName(String upstreamName) {
  937. if (upstreamCommit == null) {
  938. throw new IllegalStateException(
  939. "setUpstreamName must be called after setUpstream.");
  940. }
  941. this.upstreamCommitName = upstreamName;
  942. return this;
  943. }
  944. /**
  945. * @param operation
  946. * the operation to perform
  947. * @return {@code this}
  948. */
  949. public RebaseCommand setOperation(Operation operation) {
  950. this.operation = operation;
  951. return this;
  952. }
  953. /**
  954. * @param monitor
  955. * a progress monitor
  956. * @return this instance
  957. */
  958. public RebaseCommand setProgressMonitor(ProgressMonitor monitor) {
  959. this.monitor = monitor;
  960. return this;
  961. }
  962. /**
  963. * Enables interactive rebase
  964. *
  965. * @param handler
  966. * @return this
  967. */
  968. public RebaseCommand runInteractively(InteractiveHandler handler) {
  969. this.interactiveHandler = handler;
  970. return this;
  971. }
  972. /**
  973. * Allows configure rebase interactive process and modify commit message
  974. */
  975. public interface InteractiveHandler {
  976. /**
  977. * Given list of {@code steps} should be modified according to user
  978. * rebase configuration
  979. * @param steps
  980. * initial configuration of rebase interactive
  981. */
  982. void prepareSteps(List<Step> steps);
  983. /**
  984. * Used for editing commit message on REWORD
  985. *
  986. * @param commit
  987. * @return new commit message
  988. */
  989. String modifyCommitMessage(String commit);
  990. }
  991. /**
  992. * Describes rebase actions
  993. */
  994. public static enum Action {
  995. /** Use commit */
  996. PICK("pick", "p"), //$NON-NLS-1$ //$NON-NLS-2$
  997. /** Use commit, but edit the commit message */
  998. REWORD("reword", "r"), //$NON-NLS-1$ //$NON-NLS-2$
  999. /** Use commit, but stop for amending */
  1000. EDIT("edit", "e"); // later add SQUASH, FIXUP, etc. //$NON-NLS-1$ //$NON-NLS-2$
  1001. private final String token;
  1002. private final String shortToken;
  1003. private Action(String token, String shortToken) {
  1004. this.token = token;
  1005. this.shortToken = shortToken;
  1006. }
  1007. /**
  1008. * @return full action token name
  1009. */
  1010. public String toToken() {
  1011. return this.token;
  1012. }
  1013. @SuppressWarnings("nls")
  1014. @Override
  1015. public String toString() {
  1016. return "Action[" + token + "]";
  1017. }
  1018. static Action parse(String token) {
  1019. for (Action action : Action.values()) {
  1020. if (action.token.equals(token)
  1021. || action.shortToken.equals(token))
  1022. return action;
  1023. }
  1024. throw new JGitInternalException(MessageFormat.format(
  1025. JGitText.get().unknownOrUnsupportedCommand, token,
  1026. Action.values()));
  1027. }
  1028. }
  1029. /**
  1030. * Describes single rebase step
  1031. */
  1032. public static class Step {
  1033. Action action;
  1034. AbbreviatedObjectId commit;
  1035. byte[] shortMessage;
  1036. Step(Action action) {
  1037. this.action = action;
  1038. }
  1039. /**
  1040. * @return rebase action type
  1041. */
  1042. public Action getAction() {
  1043. return action;
  1044. }
  1045. /**
  1046. * @param action
  1047. */
  1048. public void setAction(Action action) {
  1049. this.action = action;
  1050. }
  1051. /**
  1052. * @return abbreviated commit SHA-1 of commit that action will be
  1053. * performed on
  1054. */
  1055. public AbbreviatedObjectId getCommit() {
  1056. return commit;
  1057. }
  1058. /**
  1059. * @return short message commit of commit that action will be performed
  1060. * on
  1061. */
  1062. public byte[] getShortMessage() {
  1063. return shortMessage;
  1064. }
  1065. @SuppressWarnings("nls")
  1066. @Override
  1067. public String toString() {
  1068. return "Step["
  1069. + action
  1070. + ", "
  1071. + ((commit == null) ? "null" : commit)
  1072. + ", "
  1073. + ((shortMessage == null) ? "null" : new String(
  1074. shortMessage)) + "]";
  1075. }
  1076. }
  1077. PersonIdent parseAuthor(byte[] raw) {
  1078. if (raw.length == 0)
  1079. return null;
  1080. Map<String, String> keyValueMap = new HashMap<String, String>();
  1081. for (int p = 0; p < raw.length;) {
  1082. int end = RawParseUtils.nextLF(raw, p);
  1083. if (end == p)
  1084. break;
  1085. int equalsIndex = RawParseUtils.next(raw, p, '=');
  1086. if (equalsIndex == end)
  1087. break;
  1088. String key = RawParseUtils.decode(raw, p, equalsIndex - 1);
  1089. String value = RawParseUtils.decode(raw, equalsIndex + 1, end - 2);
  1090. p = end;
  1091. keyValueMap.put(key, value);
  1092. }
  1093. String name = keyValueMap.get(GIT_AUTHOR_NAME);
  1094. String email = keyValueMap.get(GIT_AUTHOR_EMAIL);
  1095. String time = keyValueMap.get(GIT_AUTHOR_DATE);
  1096. // the time is saved as <seconds since 1970> <timezone offset>
  1097. int timeStart = 0;
  1098. if (time.startsWith("@")) //$NON-NLS-1$
  1099. timeStart = 1;
  1100. else
  1101. timeStart = 0;
  1102. long when = Long
  1103. .parseLong(time.substring(timeStart, time.indexOf(' '))) * 1000;
  1104. String tzOffsetString = time.substring(time.indexOf(' ') + 1);
  1105. int multiplier = -1;
  1106. if (tzOffsetString.charAt(0) == '+')
  1107. multiplier = 1;
  1108. int hours = Integer.parseInt(tzOffsetString.substring(1, 3));
  1109. int minutes = Integer.parseInt(tzOffsetString.substring(3, 5));
  1110. // this is in format (+/-)HHMM (hours and minutes)
  1111. // we need to convert into minutes
  1112. int tz = (hours * 60 + minutes) * multiplier;
  1113. if (name != null && email != null)
  1114. return new PersonIdent(name, email, when, tz);
  1115. return null;
  1116. }
  1117. }