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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  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.JGitText;
  62. import org.eclipse.jgit.api.RebaseResult.Status;
  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.lib.AbbreviatedObjectId;
  76. import org.eclipse.jgit.lib.AnyObjectId;
  77. import org.eclipse.jgit.lib.Constants;
  78. import org.eclipse.jgit.lib.NullProgressMonitor;
  79. import org.eclipse.jgit.lib.ObjectId;
  80. import org.eclipse.jgit.lib.ObjectReader;
  81. import org.eclipse.jgit.lib.PersonIdent;
  82. import org.eclipse.jgit.lib.ProgressMonitor;
  83. import org.eclipse.jgit.lib.Ref;
  84. import org.eclipse.jgit.lib.RefUpdate;
  85. import org.eclipse.jgit.lib.RefUpdate.Result;
  86. import org.eclipse.jgit.lib.Repository;
  87. import org.eclipse.jgit.revwalk.RevCommit;
  88. import org.eclipse.jgit.revwalk.RevWalk;
  89. import org.eclipse.jgit.treewalk.TreeWalk;
  90. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  91. import org.eclipse.jgit.util.FileUtils;
  92. import org.eclipse.jgit.util.IO;
  93. import org.eclipse.jgit.util.RawParseUtils;
  94. /**
  95. * A class used to execute a {@code Rebase} command. It has setters for all
  96. * supported options and arguments of this command and a {@link #call()} method
  97. * to finally execute the command. Each instance of this class should only be
  98. * used for one invocation of the command (means: one call to {@link #call()})
  99. * <p>
  100. *
  101. * @see <a
  102. * href="http://www.kernel.org/pub/software/scm/git/docs/git-rebase.html"
  103. * >Git documentation about Rebase</a>
  104. */
  105. public class RebaseCommand extends GitCommand<RebaseResult> {
  106. /**
  107. * The name of the "rebase-merge" folder
  108. */
  109. public static final String REBASE_MERGE = "rebase-merge";
  110. /**
  111. * The name of the "stopped-sha" file
  112. */
  113. public static final String STOPPED_SHA = "stopped-sha";
  114. private static final String AUTHOR_SCRIPT = "author-script";
  115. private static final String DONE = "done";
  116. private static final String GIT_AUTHOR_DATE = "GIT_AUTHOR_DATE";
  117. private static final String GIT_AUTHOR_EMAIL = "GIT_AUTHOR_EMAIL";
  118. private static final String GIT_AUTHOR_NAME = "GIT_AUTHOR_NAME";
  119. private static final String GIT_REBASE_TODO = "git-rebase-todo";
  120. private static final String HEAD_NAME = "head-name";
  121. private static final String INTERACTIVE = "interactive";
  122. private static final String MESSAGE = "message";
  123. private static final String ONTO = "onto";
  124. private static final String PATCH = "patch";
  125. private static final String REBASE_HEAD = "head";
  126. /**
  127. * The available operations
  128. */
  129. public enum Operation {
  130. /**
  131. * Initiates rebase
  132. */
  133. BEGIN,
  134. /**
  135. * Continues after a conflict resolution
  136. */
  137. CONTINUE,
  138. /**
  139. * Skips the "current" commit
  140. */
  141. SKIP,
  142. /**
  143. * Aborts and resets the current rebase
  144. */
  145. ABORT;
  146. }
  147. private Operation operation = Operation.BEGIN;
  148. private RevCommit upstreamCommit;
  149. private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;
  150. private final RevWalk walk;
  151. private final File rebaseDir;
  152. /**
  153. * @param repo
  154. */
  155. protected RebaseCommand(Repository repo) {
  156. super(repo);
  157. walk = new RevWalk(repo);
  158. rebaseDir = new File(repo.getDirectory(), REBASE_MERGE);
  159. }
  160. /**
  161. * Executes the {@code Rebase} command with all the options and parameters
  162. * collected by the setter methods of this class. Each instance of this
  163. * class should only be used for one invocation of the command. Don't call
  164. * this method twice on an instance.
  165. *
  166. * @return an object describing the result of this command
  167. */
  168. public RebaseResult call() throws NoHeadException, RefNotFoundException,
  169. JGitInternalException, GitAPIException {
  170. RevCommit newHead = null;
  171. boolean lastStepWasForward = false;
  172. checkCallable();
  173. checkParameters();
  174. try {
  175. switch (operation) {
  176. case ABORT:
  177. try {
  178. return abort(RebaseResult.ABORTED_RESULT);
  179. } catch (IOException ioe) {
  180. throw new JGitInternalException(ioe.getMessage(), ioe);
  181. }
  182. case SKIP:
  183. // fall through
  184. case CONTINUE:
  185. String upstreamCommitName = readFile(rebaseDir, ONTO);
  186. this.upstreamCommit = walk.parseCommit(repo
  187. .resolve(upstreamCommitName));
  188. break;
  189. case BEGIN:
  190. RebaseResult res = initFilesAndRewind();
  191. if (res != null)
  192. return res;
  193. }
  194. if (monitor.isCancelled())
  195. return abort(RebaseResult.ABORTED_RESULT);
  196. if (operation == Operation.CONTINUE)
  197. newHead = continueRebase();
  198. if (operation == Operation.SKIP)
  199. newHead = checkoutCurrentHead();
  200. ObjectReader or = repo.newObjectReader();
  201. List<Step> steps = loadSteps();
  202. for (Step step : steps) {
  203. popSteps(1);
  204. Collection<ObjectId> ids = or.resolve(step.commit);
  205. if (ids.size() != 1)
  206. throw new JGitInternalException(
  207. "Could not resolve uniquely the abbreviated object ID");
  208. RevCommit commitToPick = walk
  209. .parseCommit(ids.iterator().next());
  210. if (monitor.isCancelled())
  211. return new RebaseResult(commitToPick);
  212. try {
  213. monitor.beginTask(MessageFormat.format(
  214. JGitText.get().applyingCommit,
  215. commitToPick.getShortMessage()),
  216. ProgressMonitor.UNKNOWN);
  217. // if the first parent of commitToPick is the current HEAD,
  218. // we do a fast-forward instead of cherry-pick to avoid
  219. // unnecessary object rewriting
  220. newHead = tryFastForward(commitToPick);
  221. lastStepWasForward = newHead != null;
  222. if (!lastStepWasForward) {
  223. // TODO if the content of this commit is already merged
  224. // here we should skip this step in order to avoid
  225. // confusing pseudo-changed
  226. CherryPickResult cherryPickResult = new Git(repo)
  227. .cherryPick().include(commitToPick).call();
  228. switch (cherryPickResult.getStatus()) {
  229. case FAILED:
  230. if (operation == Operation.BEGIN)
  231. return abort(new RebaseResult(
  232. cherryPickResult.getFailingPaths()));
  233. else
  234. return stop(commitToPick);
  235. case CONFLICTING:
  236. return stop(commitToPick);
  237. case OK:
  238. newHead = cherryPickResult.getNewHead();
  239. }
  240. }
  241. } finally {
  242. monitor.endTask();
  243. }
  244. }
  245. if (newHead != null) {
  246. String headName = readFile(rebaseDir, HEAD_NAME);
  247. updateHead(headName, newHead);
  248. FileUtils.delete(rebaseDir, FileUtils.RECURSIVE);
  249. if (lastStepWasForward)
  250. return RebaseResult.FAST_FORWARD_RESULT;
  251. return RebaseResult.OK_RESULT;
  252. }
  253. return RebaseResult.FAST_FORWARD_RESULT;
  254. } catch (IOException ioe) {
  255. throw new JGitInternalException(ioe.getMessage(), ioe);
  256. }
  257. }
  258. private void updateHead(String headName, RevCommit newHead)
  259. throws IOException {
  260. // point the previous head (if any) to the new commit
  261. if (headName.startsWith(Constants.R_REFS)) {
  262. RefUpdate rup = repo.updateRef(headName);
  263. rup.setNewObjectId(newHead);
  264. Result res = rup.forceUpdate();
  265. switch (res) {
  266. case FAST_FORWARD:
  267. case FORCED:
  268. case NO_CHANGE:
  269. break;
  270. default:
  271. throw new JGitInternalException("Updating HEAD failed");
  272. }
  273. rup = repo.updateRef(Constants.HEAD);
  274. res = rup.link(headName);
  275. switch (res) {
  276. case FAST_FORWARD:
  277. case FORCED:
  278. case NO_CHANGE:
  279. break;
  280. default:
  281. throw new JGitInternalException("Updating HEAD failed");
  282. }
  283. }
  284. }
  285. private RevCommit checkoutCurrentHead() throws IOException,
  286. NoHeadException, JGitInternalException {
  287. ObjectId headTree = repo.resolve(Constants.HEAD + "^{tree}");
  288. if (headTree == null)
  289. throw new NoHeadException(
  290. JGitText.get().cannotRebaseWithoutCurrentHead);
  291. DirCache dc = repo.lockDirCache();
  292. try {
  293. DirCacheCheckout dco = new DirCacheCheckout(repo, dc, headTree);
  294. dco.setFailOnConflict(false);
  295. boolean needsDeleteFiles = dco.checkout();
  296. if (needsDeleteFiles) {
  297. List<String> fileList = dco.getToBeDeleted();
  298. for (String filePath : fileList) {
  299. File fileToDelete = new File(repo.getWorkTree(), filePath);
  300. if (fileToDelete.exists())
  301. FileUtils.delete(fileToDelete, FileUtils.RECURSIVE
  302. | FileUtils.RETRY);
  303. }
  304. }
  305. } finally {
  306. dc.unlock();
  307. }
  308. RevWalk rw = new RevWalk(repo);
  309. RevCommit commit = rw.parseCommit(repo.resolve(Constants.HEAD));
  310. rw.release();
  311. return commit;
  312. }
  313. /**
  314. * @return the commit if we had to do a commit, otherwise null
  315. * @throws GitAPIException
  316. * @throws IOException
  317. */
  318. private RevCommit continueRebase() throws GitAPIException, IOException {
  319. // if there are still conflicts, we throw a specific Exception
  320. DirCache dc = repo.readDirCache();
  321. boolean hasUnmergedPaths = dc.hasUnmergedPaths();
  322. if (hasUnmergedPaths)
  323. throw new UnmergedPathsException();
  324. // determine whether we need to commit
  325. TreeWalk treeWalk = new TreeWalk(repo);
  326. treeWalk.reset();
  327. treeWalk.setRecursive(true);
  328. treeWalk.addTree(new DirCacheIterator(dc));
  329. ObjectId id = repo.resolve(Constants.HEAD + "^{tree}");
  330. if (id == null)
  331. throw new NoHeadException(
  332. JGitText.get().cannotRebaseWithoutCurrentHead);
  333. treeWalk.addTree(id);
  334. treeWalk.setFilter(TreeFilter.ANY_DIFF);
  335. boolean needsCommit = treeWalk.next();
  336. treeWalk.release();
  337. if (needsCommit) {
  338. CommitCommand commit = new Git(repo).commit();
  339. commit.setMessage(readFile(rebaseDir, MESSAGE));
  340. commit.setAuthor(parseAuthor());
  341. return commit.call();
  342. }
  343. return null;
  344. }
  345. private PersonIdent parseAuthor() throws IOException {
  346. File authorScriptFile = new File(rebaseDir, AUTHOR_SCRIPT);
  347. byte[] raw;
  348. try {
  349. raw = IO.readFully(authorScriptFile);
  350. } catch (FileNotFoundException notFound) {
  351. return null;
  352. }
  353. return parseAuthor(raw);
  354. }
  355. private RebaseResult stop(RevCommit commitToPick) throws IOException {
  356. PersonIdent author = commitToPick.getAuthorIdent();
  357. String authorScript = toAuthorScript(author);
  358. createFile(rebaseDir, AUTHOR_SCRIPT, authorScript);
  359. createFile(rebaseDir, MESSAGE, commitToPick.getFullMessage());
  360. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  361. DiffFormatter df = new DiffFormatter(bos);
  362. df.setRepository(repo);
  363. df.format(commitToPick.getParent(0), commitToPick);
  364. createFile(rebaseDir, PATCH, new String(bos.toByteArray(),
  365. Constants.CHARACTER_ENCODING));
  366. createFile(rebaseDir, STOPPED_SHA, repo.newObjectReader().abbreviate(
  367. commitToPick).name());
  368. // Remove cherry pick state file created by CherryPickCommand, it's not
  369. // needed for rebase
  370. repo.writeCherryPickHead(null);
  371. return new RebaseResult(commitToPick);
  372. }
  373. String toAuthorScript(PersonIdent author) {
  374. StringBuilder sb = new StringBuilder(100);
  375. sb.append(GIT_AUTHOR_NAME);
  376. sb.append("='");
  377. sb.append(author.getName());
  378. sb.append("'\n");
  379. sb.append(GIT_AUTHOR_EMAIL);
  380. sb.append("='");
  381. sb.append(author.getEmailAddress());
  382. sb.append("'\n");
  383. // the command line uses the "external String"
  384. // representation for date and timezone
  385. sb.append(GIT_AUTHOR_DATE);
  386. sb.append("='");
  387. String externalString = author.toExternalString();
  388. sb
  389. .append(externalString.substring(externalString
  390. .lastIndexOf('>') + 2));
  391. sb.append("'\n");
  392. return sb.toString();
  393. }
  394. /**
  395. * Removes the number of lines given in the parameter from the
  396. * <code>git-rebase-todo</code> file but preserves comments and other lines
  397. * that can not be parsed as steps
  398. *
  399. * @param numSteps
  400. * @throws IOException
  401. */
  402. private void popSteps(int numSteps) throws IOException {
  403. if (numSteps == 0)
  404. return;
  405. List<String> todoLines = new ArrayList<String>();
  406. List<String> poppedLines = new ArrayList<String>();
  407. File todoFile = new File(rebaseDir, GIT_REBASE_TODO);
  408. File doneFile = new File(rebaseDir, DONE);
  409. BufferedReader br = new BufferedReader(new InputStreamReader(
  410. new FileInputStream(todoFile), Constants.CHARACTER_ENCODING));
  411. try {
  412. // check if the line starts with a action tag (pick, skip...)
  413. while (poppedLines.size() < numSteps) {
  414. String popCandidate = br.readLine();
  415. if (popCandidate == null)
  416. break;
  417. if (popCandidate.charAt(0) == '#')
  418. continue;
  419. int spaceIndex = popCandidate.indexOf(' ');
  420. boolean pop = false;
  421. if (spaceIndex >= 0) {
  422. String actionToken = popCandidate.substring(0, spaceIndex);
  423. pop = Action.parse(actionToken) != null;
  424. }
  425. if (pop)
  426. poppedLines.add(popCandidate);
  427. else
  428. todoLines.add(popCandidate);
  429. }
  430. String readLine = br.readLine();
  431. while (readLine != null) {
  432. todoLines.add(readLine);
  433. readLine = br.readLine();
  434. }
  435. } finally {
  436. br.close();
  437. }
  438. BufferedWriter todoWriter = new BufferedWriter(new OutputStreamWriter(
  439. new FileOutputStream(todoFile), Constants.CHARACTER_ENCODING));
  440. try {
  441. for (String writeLine : todoLines) {
  442. todoWriter.write(writeLine);
  443. todoWriter.newLine();
  444. }
  445. } finally {
  446. todoWriter.close();
  447. }
  448. if (poppedLines.size() > 0) {
  449. // append here
  450. BufferedWriter doneWriter = new BufferedWriter(
  451. new OutputStreamWriter(
  452. new FileOutputStream(doneFile, true),
  453. Constants.CHARACTER_ENCODING));
  454. try {
  455. for (String writeLine : poppedLines) {
  456. doneWriter.write(writeLine);
  457. doneWriter.newLine();
  458. }
  459. } finally {
  460. doneWriter.close();
  461. }
  462. }
  463. }
  464. private RebaseResult initFilesAndRewind() throws RefNotFoundException,
  465. IOException, NoHeadException, JGitInternalException {
  466. // we need to store everything into files so that we can implement
  467. // --skip, --continue, and --abort
  468. Ref head = repo.getRef(Constants.HEAD);
  469. if (head == null || head.getObjectId() == null)
  470. throw new RefNotFoundException(MessageFormat.format(
  471. JGitText.get().refNotResolved, Constants.HEAD));
  472. String headName;
  473. if (head.isSymbolic())
  474. headName = head.getTarget().getName();
  475. else
  476. headName = "detached HEAD";
  477. ObjectId headId = head.getObjectId();
  478. if (headId == null)
  479. throw new RefNotFoundException(MessageFormat.format(
  480. JGitText.get().refNotResolved, Constants.HEAD));
  481. RevCommit headCommit = walk.lookupCommit(headId);
  482. RevCommit upstream = walk.lookupCommit(upstreamCommit.getId());
  483. if (walk.isMergedInto(upstream, headCommit))
  484. return RebaseResult.UP_TO_DATE_RESULT;
  485. else if (walk.isMergedInto(headCommit, upstream)) {
  486. // head is already merged into upstream, fast-foward
  487. monitor.beginTask(MessageFormat.format(
  488. JGitText.get().resettingHead,
  489. upstreamCommit.getShortMessage()), ProgressMonitor.UNKNOWN);
  490. checkoutCommit(upstreamCommit);
  491. monitor.endTask();
  492. updateHead(headName, upstreamCommit);
  493. return RebaseResult.FAST_FORWARD_RESULT;
  494. }
  495. monitor.beginTask(JGitText.get().obtainingCommitsForCherryPick,
  496. ProgressMonitor.UNKNOWN);
  497. // determine the commits to be applied
  498. LogCommand cmd = new Git(repo).log().addRange(upstreamCommit,
  499. headCommit);
  500. Iterable<RevCommit> commitsToUse = cmd.call();
  501. List<RevCommit> cherryPickList = new ArrayList<RevCommit>();
  502. for (RevCommit commit : commitsToUse) {
  503. if (commit.getParentCount() != 1)
  504. throw new JGitInternalException(
  505. MessageFormat.format(
  506. JGitText.get().canOnlyCherryPickCommitsWithOneParent,
  507. commit.name(),
  508. Integer.valueOf(commit.getParentCount())));
  509. cherryPickList.add(commit);
  510. }
  511. Collections.reverse(cherryPickList);
  512. // create the folder for the meta information
  513. FileUtils.mkdir(rebaseDir);
  514. createFile(repo.getDirectory(), Constants.ORIG_HEAD, headId.name());
  515. createFile(rebaseDir, REBASE_HEAD, headId.name());
  516. createFile(rebaseDir, HEAD_NAME, headName);
  517. createFile(rebaseDir, ONTO, upstreamCommit.name());
  518. createFile(rebaseDir, INTERACTIVE, "");
  519. BufferedWriter fw = new BufferedWriter(new OutputStreamWriter(
  520. new FileOutputStream(new File(rebaseDir, GIT_REBASE_TODO)),
  521. Constants.CHARACTER_ENCODING));
  522. fw.write("# Created by EGit: rebasing " + upstreamCommit.name()
  523. + " onto " + headId.name());
  524. fw.newLine();
  525. try {
  526. StringBuilder sb = new StringBuilder();
  527. ObjectReader reader = walk.getObjectReader();
  528. for (RevCommit commit : cherryPickList) {
  529. sb.setLength(0);
  530. sb.append(Action.PICK.toToken());
  531. sb.append(" ");
  532. sb.append(reader.abbreviate(commit).name());
  533. sb.append(" ");
  534. sb.append(commit.getShortMessage());
  535. fw.write(sb.toString());
  536. fw.newLine();
  537. }
  538. } finally {
  539. fw.close();
  540. }
  541. monitor.endTask();
  542. // we rewind to the upstream commit
  543. monitor.beginTask(MessageFormat.format(JGitText.get().rewinding,
  544. upstreamCommit.getShortMessage()), ProgressMonitor.UNKNOWN);
  545. boolean checkoutOk = false;
  546. try {
  547. checkoutOk = checkoutCommit(upstreamCommit);
  548. } finally {
  549. if (!checkoutOk)
  550. FileUtils.delete(rebaseDir, FileUtils.RECURSIVE);
  551. }
  552. monitor.endTask();
  553. return null;
  554. }
  555. /**
  556. * checks if we can fast-forward and returns the new head if it is possible
  557. *
  558. * @param newCommit
  559. * @return the new head, or null
  560. * @throws RefNotFoundException
  561. * @throws IOException
  562. */
  563. public RevCommit tryFastForward(RevCommit newCommit)
  564. throws RefNotFoundException, IOException {
  565. Ref head = repo.getRef(Constants.HEAD);
  566. if (head == null || head.getObjectId() == null)
  567. throw new RefNotFoundException(MessageFormat.format(
  568. JGitText.get().refNotResolved, Constants.HEAD));
  569. ObjectId headId = head.getObjectId();
  570. if (headId == null)
  571. throw new RefNotFoundException(MessageFormat.format(
  572. JGitText.get().refNotResolved, Constants.HEAD));
  573. RevCommit headCommit = walk.lookupCommit(headId);
  574. if (walk.isMergedInto(newCommit, headCommit))
  575. return newCommit;
  576. String headName;
  577. if (head.isSymbolic())
  578. headName = head.getTarget().getName();
  579. else
  580. headName = "detached HEAD";
  581. return tryFastForward(headName, headCommit, newCommit);
  582. }
  583. private RevCommit tryFastForward(String headName, RevCommit oldCommit,
  584. RevCommit newCommit) throws IOException, JGitInternalException {
  585. boolean tryRebase = false;
  586. for (RevCommit parentCommit : newCommit.getParents())
  587. if (parentCommit.equals(oldCommit))
  588. tryRebase = true;
  589. if (!tryRebase)
  590. return null;
  591. CheckoutCommand co = new CheckoutCommand(repo);
  592. try {
  593. co.setName(newCommit.name()).call();
  594. if (headName.startsWith(Constants.R_HEADS)) {
  595. RefUpdate rup = repo.updateRef(headName);
  596. rup.setExpectedOldObjectId(oldCommit);
  597. rup.setNewObjectId(newCommit);
  598. rup.setRefLogMessage("Fast-foward from " + oldCommit.name()
  599. + " to " + newCommit.name(), false);
  600. Result res = rup.update(walk);
  601. switch (res) {
  602. case FAST_FORWARD:
  603. case NO_CHANGE:
  604. case FORCED:
  605. break;
  606. default:
  607. throw new IOException("Could not fast-forward");
  608. }
  609. }
  610. return newCommit;
  611. } catch (RefAlreadyExistsException e) {
  612. throw new JGitInternalException(e.getMessage(), e);
  613. } catch (RefNotFoundException e) {
  614. throw new JGitInternalException(e.getMessage(), e);
  615. } catch (InvalidRefNameException e) {
  616. throw new JGitInternalException(e.getMessage(), e);
  617. }
  618. }
  619. private void checkParameters() throws WrongRepositoryStateException {
  620. if (this.operation != Operation.BEGIN) {
  621. // these operations are only possible while in a rebasing state
  622. switch (repo.getRepositoryState()) {
  623. case REBASING_INTERACTIVE:
  624. break;
  625. default:
  626. throw new WrongRepositoryStateException(MessageFormat.format(
  627. JGitText.get().wrongRepositoryState, repo
  628. .getRepositoryState().name()));
  629. }
  630. } else
  631. switch (repo.getRepositoryState()) {
  632. case SAFE:
  633. if (this.upstreamCommit == null)
  634. throw new JGitInternalException(MessageFormat
  635. .format(JGitText.get().missingRequiredParameter,
  636. "upstream"));
  637. return;
  638. default:
  639. throw new WrongRepositoryStateException(MessageFormat.format(
  640. JGitText.get().wrongRepositoryState, repo
  641. .getRepositoryState().name()));
  642. }
  643. }
  644. private void createFile(File parentDir, String name, String content)
  645. throws IOException {
  646. File file = new File(parentDir, name);
  647. FileOutputStream fos = new FileOutputStream(file);
  648. try {
  649. fos.write(content.getBytes(Constants.CHARACTER_ENCODING));
  650. fos.write('\n');
  651. } finally {
  652. fos.close();
  653. }
  654. }
  655. private RebaseResult abort(RebaseResult result) throws IOException {
  656. try {
  657. String commitId = readFile(repo.getDirectory(), Constants.ORIG_HEAD);
  658. monitor.beginTask(MessageFormat.format(
  659. JGitText.get().abortingRebase, commitId),
  660. ProgressMonitor.UNKNOWN);
  661. DirCacheCheckout dco;
  662. RevCommit commit = walk.parseCommit(repo.resolve(commitId));
  663. if (result.getStatus().equals(Status.FAILED)) {
  664. RevCommit head = walk.parseCommit(repo.resolve(Constants.HEAD));
  665. dco = new DirCacheCheckout(repo, head.getTree(),
  666. repo.lockDirCache(), commit.getTree());
  667. } else {
  668. dco = new DirCacheCheckout(repo, repo.lockDirCache(),
  669. commit.getTree());
  670. }
  671. dco.setFailOnConflict(false);
  672. dco.checkout();
  673. walk.release();
  674. } finally {
  675. monitor.endTask();
  676. }
  677. try {
  678. String headName = readFile(rebaseDir, HEAD_NAME);
  679. if (headName.startsWith(Constants.R_REFS)) {
  680. monitor.beginTask(MessageFormat.format(
  681. JGitText.get().resettingHead, headName),
  682. ProgressMonitor.UNKNOWN);
  683. // update the HEAD
  684. RefUpdate refUpdate = repo.updateRef(Constants.HEAD, false);
  685. Result res = refUpdate.link(headName);
  686. switch (res) {
  687. case FAST_FORWARD:
  688. case FORCED:
  689. case NO_CHANGE:
  690. break;
  691. default:
  692. throw new JGitInternalException(
  693. JGitText.get().abortingRebaseFailed);
  694. }
  695. }
  696. // cleanup the files
  697. FileUtils.delete(rebaseDir, FileUtils.RECURSIVE);
  698. repo.writeCherryPickHead(null);
  699. return result;
  700. } finally {
  701. monitor.endTask();
  702. }
  703. }
  704. private String readFile(File directory, String fileName) throws IOException {
  705. byte[] content = IO.readFully(new File(directory, fileName));
  706. // strip off the last LF
  707. int end = content.length;
  708. while (0 < end && content[end - 1] == '\n')
  709. end--;
  710. return RawParseUtils.decode(content, 0, end);
  711. }
  712. private boolean checkoutCommit(RevCommit commit) throws IOException {
  713. try {
  714. RevCommit head = walk.parseCommit(repo.resolve(Constants.HEAD));
  715. DirCacheCheckout dco = new DirCacheCheckout(repo, head.getTree(),
  716. repo.lockDirCache(), commit.getTree());
  717. dco.setFailOnConflict(true);
  718. dco.checkout();
  719. // update the HEAD
  720. RefUpdate refUpdate = repo.updateRef(Constants.HEAD, true);
  721. refUpdate.setExpectedOldObjectId(head);
  722. refUpdate.setNewObjectId(commit);
  723. Result res = refUpdate.forceUpdate();
  724. switch (res) {
  725. case FAST_FORWARD:
  726. case NO_CHANGE:
  727. case FORCED:
  728. break;
  729. default:
  730. throw new IOException("Could not rewind to upstream commit");
  731. }
  732. } finally {
  733. walk.release();
  734. monitor.endTask();
  735. }
  736. return true;
  737. }
  738. private List<Step> loadSteps() throws IOException {
  739. byte[] buf = IO.readFully(new File(rebaseDir, GIT_REBASE_TODO));
  740. int ptr = 0;
  741. int tokenBegin = 0;
  742. ArrayList<Step> r = new ArrayList<Step>();
  743. while (ptr < buf.length) {
  744. tokenBegin = ptr;
  745. ptr = RawParseUtils.nextLF(buf, ptr);
  746. int nextSpace = 0;
  747. int tokenCount = 0;
  748. Step current = null;
  749. while (tokenCount < 3 && nextSpace < ptr) {
  750. switch (tokenCount) {
  751. case 0:
  752. nextSpace = RawParseUtils.next(buf, tokenBegin, ' ');
  753. String actionToken = new String(buf, tokenBegin, nextSpace
  754. - tokenBegin - 1);
  755. tokenBegin = nextSpace;
  756. if (actionToken.charAt(0) == '#') {
  757. tokenCount = 3;
  758. break;
  759. }
  760. Action action = Action.parse(actionToken);
  761. if (action != null)
  762. current = new Step(Action.parse(actionToken));
  763. break;
  764. case 1:
  765. if (current == null)
  766. break;
  767. nextSpace = RawParseUtils.next(buf, tokenBegin, ' ');
  768. String commitToken = new String(buf, tokenBegin, nextSpace
  769. - tokenBegin - 1);
  770. tokenBegin = nextSpace;
  771. current.commit = AbbreviatedObjectId
  772. .fromString(commitToken);
  773. break;
  774. case 2:
  775. if (current == null)
  776. break;
  777. nextSpace = ptr;
  778. int length = ptr - tokenBegin;
  779. current.shortMessage = new byte[length];
  780. System.arraycopy(buf, tokenBegin, current.shortMessage, 0,
  781. length);
  782. r.add(current);
  783. break;
  784. }
  785. tokenCount++;
  786. }
  787. }
  788. return r;
  789. }
  790. /**
  791. * @param upstream
  792. * the upstream commit
  793. * @return {@code this}
  794. */
  795. public RebaseCommand setUpstream(RevCommit upstream) {
  796. this.upstreamCommit = upstream;
  797. return this;
  798. }
  799. /**
  800. * @param upstream
  801. * id of the upstream commit
  802. * @return {@code this}
  803. */
  804. public RebaseCommand setUpstream(AnyObjectId upstream) {
  805. try {
  806. this.upstreamCommit = walk.parseCommit(upstream);
  807. } catch (IOException e) {
  808. throw new JGitInternalException(MessageFormat.format(
  809. JGitText.get().couldNotReadObjectWhileParsingCommit,
  810. upstream.name()), e);
  811. }
  812. return this;
  813. }
  814. /**
  815. * @param upstream
  816. * the upstream branch
  817. * @return {@code this}
  818. * @throws RefNotFoundException
  819. */
  820. public RebaseCommand setUpstream(String upstream)
  821. throws RefNotFoundException {
  822. try {
  823. ObjectId upstreamId = repo.resolve(upstream);
  824. if (upstreamId == null)
  825. throw new RefNotFoundException(MessageFormat.format(JGitText
  826. .get().refNotResolved, upstream));
  827. upstreamCommit = walk.parseCommit(repo.resolve(upstream));
  828. return this;
  829. } catch (IOException ioe) {
  830. throw new JGitInternalException(ioe.getMessage(), ioe);
  831. }
  832. }
  833. /**
  834. * @param operation
  835. * the operation to perform
  836. * @return {@code this}
  837. */
  838. public RebaseCommand setOperation(Operation operation) {
  839. this.operation = operation;
  840. return this;
  841. }
  842. /**
  843. * @param monitor
  844. * a progress monitor
  845. * @return this instance
  846. */
  847. public RebaseCommand setProgressMonitor(ProgressMonitor monitor) {
  848. this.monitor = monitor;
  849. return this;
  850. }
  851. static enum Action {
  852. PICK("pick"); // later add SQUASH, EDIT, etc.
  853. private final String token;
  854. private Action(String token) {
  855. this.token = token;
  856. }
  857. public String toToken() {
  858. return this.token;
  859. }
  860. static Action parse(String token) {
  861. if (token.equals("pick") || token.equals("p"))
  862. return PICK;
  863. throw new JGitInternalException(
  864. MessageFormat
  865. .format(
  866. "Unknown or unsupported command \"{0}\", only \"pick\" is allowed",
  867. token));
  868. }
  869. }
  870. static class Step {
  871. Action action;
  872. AbbreviatedObjectId commit;
  873. byte[] shortMessage;
  874. Step(Action action) {
  875. this.action = action;
  876. }
  877. }
  878. PersonIdent parseAuthor(byte[] raw) {
  879. if (raw.length == 0)
  880. return null;
  881. Map<String, String> keyValueMap = new HashMap<String, String>();
  882. for (int p = 0; p < raw.length;) {
  883. int end = RawParseUtils.nextLF(raw, p);
  884. if (end == p)
  885. break;
  886. int equalsIndex = RawParseUtils.next(raw, p, '=');
  887. if (equalsIndex == end)
  888. break;
  889. String key = RawParseUtils.decode(raw, p, equalsIndex - 1);
  890. String value = RawParseUtils.decode(raw, equalsIndex + 1, end - 2);
  891. p = end;
  892. keyValueMap.put(key, value);
  893. }
  894. String name = keyValueMap.get(GIT_AUTHOR_NAME);
  895. String email = keyValueMap.get(GIT_AUTHOR_EMAIL);
  896. String time = keyValueMap.get(GIT_AUTHOR_DATE);
  897. // the time is saved as <seconds since 1970> <timezone offset>
  898. long when = Long.parseLong(time.substring(0, time.indexOf(' '))) * 1000;
  899. String tzOffsetString = time.substring(time.indexOf(' ') + 1);
  900. int multiplier = -1;
  901. if (tzOffsetString.charAt(0) == '+')
  902. multiplier = 1;
  903. int hours = Integer.parseInt(tzOffsetString.substring(1, 3));
  904. int minutes = Integer.parseInt(tzOffsetString.substring(3, 5));
  905. // this is in format (+/-)HHMM (hours and minutes)
  906. // we need to convert into minutes
  907. int tz = (hours * 60 + minutes) * multiplier;
  908. if (name != null && email != null)
  909. return new PersonIdent(name, email, when, tz);
  910. return null;
  911. }
  912. }