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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  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";
  111. /**
  112. * The name of the "stopped-sha" file
  113. */
  114. public static final String STOPPED_SHA = "stopped-sha";
  115. private static final String AUTHOR_SCRIPT = "author-script";
  116. private static final String DONE = "done";
  117. private static final String GIT_AUTHOR_DATE = "GIT_AUTHOR_DATE";
  118. private static final String GIT_AUTHOR_EMAIL = "GIT_AUTHOR_EMAIL";
  119. private static final String GIT_AUTHOR_NAME = "GIT_AUTHOR_NAME";
  120. private static final String GIT_REBASE_TODO = "git-rebase-todo";
  121. private static final String HEAD_NAME = "head-name";
  122. private static final String INTERACTIVE = "interactive";
  123. private static final String MESSAGE = "message";
  124. private static final String ONTO = "onto";
  125. private static final String ONTO_NAME = "onto-name";
  126. private static final String PATCH = "patch";
  127. private static final String REBASE_HEAD = "head";
  128. private static final String AMEND = "amend";
  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(" ");
  245. sb.append(step.commit.name());
  246. sb.append(" ");
  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}");
  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}");
  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("='");
  453. sb.append(author.getName());
  454. sb.append("'\n");
  455. sb.append(GIT_AUTHOR_EMAIL);
  456. sb.append("='");
  457. sb.append(author.getEmailAddress());
  458. sb.append("'\n");
  459. // the command line uses the "external String"
  460. // representation for date and timezone
  461. sb.append(GIT_AUTHOR_DATE);
  462. sb.append("='");
  463. sb.append("@"); // @ for time in seconds since 1970
  464. String externalString = author.toExternalString();
  465. sb
  466. .append(externalString.substring(externalString
  467. .lastIndexOf('>') + 2));
  468. sb.append("'\n");
  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, "");
  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(" ");
  612. sb.append(reader.abbreviate(commit).name());
  613. sb.append(" ");
  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()
  682. + " to " + newCommit.name(), false);
  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");
  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"),
  997. /** Use commit, but edit the commit message */
  998. REWORD("reword", "r"),
  999. /** Use commit, but stop for amending */
  1000. EDIT("edit", "e"); // later add SQUASH, FIXUP, etc.
  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. @Override
  1014. public String toString() {
  1015. return "Action[" + token + "]";
  1016. }
  1017. static Action parse(String token) {
  1018. for (Action action : Action.values()) {
  1019. if (action.token.equals(token)
  1020. || action.shortToken.equals(token))
  1021. return action;
  1022. }
  1023. throw new JGitInternalException(MessageFormat.format(
  1024. JGitText.get().unknownOrUnsupportedCommand, token,
  1025. Action.values()));
  1026. }
  1027. }
  1028. /**
  1029. * Describes single rebase step
  1030. */
  1031. public static class Step {
  1032. Action action;
  1033. AbbreviatedObjectId commit;
  1034. byte[] shortMessage;
  1035. Step(Action action) {
  1036. this.action = action;
  1037. }
  1038. /**
  1039. * @return rebase action type
  1040. */
  1041. public Action getAction() {
  1042. return action;
  1043. }
  1044. /**
  1045. * @param action
  1046. */
  1047. public void setAction(Action action) {
  1048. this.action = action;
  1049. }
  1050. /**
  1051. * @return abbreviated commit SHA-1 of commit that action will be
  1052. * performed on
  1053. */
  1054. public AbbreviatedObjectId getCommit() {
  1055. return commit;
  1056. }
  1057. /**
  1058. * @return short message commit of commit that action will be performed
  1059. * on
  1060. */
  1061. public byte[] getShortMessage() {
  1062. return shortMessage;
  1063. }
  1064. @Override
  1065. public String toString() {
  1066. return "Step[" + action + ", "
  1067. + ((commit == null) ? "null" : commit)
  1068. + ", "
  1069. + ((shortMessage == null) ? "null" : new String(
  1070. shortMessage)) + "]";
  1071. }
  1072. }
  1073. PersonIdent parseAuthor(byte[] raw) {
  1074. if (raw.length == 0)
  1075. return null;
  1076. Map<String, String> keyValueMap = new HashMap<String, String>();
  1077. for (int p = 0; p < raw.length;) {
  1078. int end = RawParseUtils.nextLF(raw, p);
  1079. if (end == p)
  1080. break;
  1081. int equalsIndex = RawParseUtils.next(raw, p, '=');
  1082. if (equalsIndex == end)
  1083. break;
  1084. String key = RawParseUtils.decode(raw, p, equalsIndex - 1);
  1085. String value = RawParseUtils.decode(raw, equalsIndex + 1, end - 2);
  1086. p = end;
  1087. keyValueMap.put(key, value);
  1088. }
  1089. String name = keyValueMap.get(GIT_AUTHOR_NAME);
  1090. String email = keyValueMap.get(GIT_AUTHOR_EMAIL);
  1091. String time = keyValueMap.get(GIT_AUTHOR_DATE);
  1092. // the time is saved as <seconds since 1970> <timezone offset>
  1093. int timeStart = 0;
  1094. if (time.startsWith("@"))
  1095. timeStart = 1;
  1096. else
  1097. timeStart = 0;
  1098. long when = Long
  1099. .parseLong(time.substring(timeStart, time.indexOf(' '))) * 1000;
  1100. String tzOffsetString = time.substring(time.indexOf(' ') + 1);
  1101. int multiplier = -1;
  1102. if (tzOffsetString.charAt(0) == '+')
  1103. multiplier = 1;
  1104. int hours = Integer.parseInt(tzOffsetString.substring(1, 3));
  1105. int minutes = Integer.parseInt(tzOffsetString.substring(3, 5));
  1106. // this is in format (+/-)HHMM (hours and minutes)
  1107. // we need to convert into minutes
  1108. int tz = (hours * 60 + minutes) * multiplier;
  1109. if (name != null && email != null)
  1110. return new PersonIdent(name, email, when, tz);
  1111. return null;
  1112. }
  1113. }