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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  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. JGitText.get().canOnlyCherryPickCommitsWithOneParent);
  506. cherryPickList.add(commit);
  507. }
  508. Collections.reverse(cherryPickList);
  509. // create the folder for the meta information
  510. FileUtils.mkdir(rebaseDir);
  511. createFile(repo.getDirectory(), Constants.ORIG_HEAD, headId.name());
  512. createFile(rebaseDir, REBASE_HEAD, headId.name());
  513. createFile(rebaseDir, HEAD_NAME, headName);
  514. createFile(rebaseDir, ONTO, upstreamCommit.name());
  515. createFile(rebaseDir, INTERACTIVE, "");
  516. BufferedWriter fw = new BufferedWriter(new OutputStreamWriter(
  517. new FileOutputStream(new File(rebaseDir, GIT_REBASE_TODO)),
  518. Constants.CHARACTER_ENCODING));
  519. fw.write("# Created by EGit: rebasing " + upstreamCommit.name()
  520. + " onto " + headId.name());
  521. fw.newLine();
  522. try {
  523. StringBuilder sb = new StringBuilder();
  524. ObjectReader reader = walk.getObjectReader();
  525. for (RevCommit commit : cherryPickList) {
  526. sb.setLength(0);
  527. sb.append(Action.PICK.toToken());
  528. sb.append(" ");
  529. sb.append(reader.abbreviate(commit).name());
  530. sb.append(" ");
  531. sb.append(commit.getShortMessage());
  532. fw.write(sb.toString());
  533. fw.newLine();
  534. }
  535. } finally {
  536. fw.close();
  537. }
  538. monitor.endTask();
  539. // we rewind to the upstream commit
  540. monitor.beginTask(MessageFormat.format(JGitText.get().rewinding,
  541. upstreamCommit.getShortMessage()), ProgressMonitor.UNKNOWN);
  542. boolean checkoutOk = false;
  543. try {
  544. checkoutOk = checkoutCommit(upstreamCommit);
  545. } finally {
  546. if (!checkoutOk)
  547. FileUtils.delete(rebaseDir, FileUtils.RECURSIVE);
  548. }
  549. monitor.endTask();
  550. return null;
  551. }
  552. /**
  553. * checks if we can fast-forward and returns the new head if it is possible
  554. *
  555. * @param newCommit
  556. * @return the new head, or null
  557. * @throws RefNotFoundException
  558. * @throws IOException
  559. */
  560. public RevCommit tryFastForward(RevCommit newCommit)
  561. throws RefNotFoundException, IOException {
  562. Ref head = repo.getRef(Constants.HEAD);
  563. if (head == null || head.getObjectId() == null)
  564. throw new RefNotFoundException(MessageFormat.format(
  565. JGitText.get().refNotResolved, Constants.HEAD));
  566. ObjectId headId = head.getObjectId();
  567. if (headId == null)
  568. throw new RefNotFoundException(MessageFormat.format(
  569. JGitText.get().refNotResolved, Constants.HEAD));
  570. RevCommit headCommit = walk.lookupCommit(headId);
  571. if (walk.isMergedInto(newCommit, headCommit))
  572. return newCommit;
  573. String headName;
  574. if (head.isSymbolic())
  575. headName = head.getTarget().getName();
  576. else
  577. headName = "detached HEAD";
  578. return tryFastForward(headName, headCommit, newCommit);
  579. }
  580. private RevCommit tryFastForward(String headName, RevCommit oldCommit,
  581. RevCommit newCommit) throws IOException, JGitInternalException {
  582. boolean tryRebase = false;
  583. for (RevCommit parentCommit : newCommit.getParents())
  584. if (parentCommit.equals(oldCommit))
  585. tryRebase = true;
  586. if (!tryRebase)
  587. return null;
  588. CheckoutCommand co = new CheckoutCommand(repo);
  589. try {
  590. co.setName(newCommit.name()).call();
  591. if (headName.startsWith(Constants.R_HEADS)) {
  592. RefUpdate rup = repo.updateRef(headName);
  593. rup.setExpectedOldObjectId(oldCommit);
  594. rup.setNewObjectId(newCommit);
  595. rup.setRefLogMessage("Fast-foward from " + oldCommit.name()
  596. + " to " + newCommit.name(), false);
  597. Result res = rup.update(walk);
  598. switch (res) {
  599. case FAST_FORWARD:
  600. case NO_CHANGE:
  601. case FORCED:
  602. break;
  603. default:
  604. throw new IOException("Could not fast-forward");
  605. }
  606. }
  607. return newCommit;
  608. } catch (RefAlreadyExistsException e) {
  609. throw new JGitInternalException(e.getMessage(), e);
  610. } catch (RefNotFoundException e) {
  611. throw new JGitInternalException(e.getMessage(), e);
  612. } catch (InvalidRefNameException e) {
  613. throw new JGitInternalException(e.getMessage(), e);
  614. }
  615. }
  616. private void checkParameters() throws WrongRepositoryStateException {
  617. if (this.operation != Operation.BEGIN) {
  618. // these operations are only possible while in a rebasing state
  619. switch (repo.getRepositoryState()) {
  620. case REBASING_INTERACTIVE:
  621. break;
  622. default:
  623. throw new WrongRepositoryStateException(MessageFormat.format(
  624. JGitText.get().wrongRepositoryState, repo
  625. .getRepositoryState().name()));
  626. }
  627. } else
  628. switch (repo.getRepositoryState()) {
  629. case SAFE:
  630. if (this.upstreamCommit == null)
  631. throw new JGitInternalException(MessageFormat
  632. .format(JGitText.get().missingRequiredParameter,
  633. "upstream"));
  634. return;
  635. default:
  636. throw new WrongRepositoryStateException(MessageFormat.format(
  637. JGitText.get().wrongRepositoryState, repo
  638. .getRepositoryState().name()));
  639. }
  640. }
  641. private void createFile(File parentDir, String name, String content)
  642. throws IOException {
  643. File file = new File(parentDir, name);
  644. FileOutputStream fos = new FileOutputStream(file);
  645. try {
  646. fos.write(content.getBytes(Constants.CHARACTER_ENCODING));
  647. fos.write('\n');
  648. } finally {
  649. fos.close();
  650. }
  651. }
  652. private RebaseResult abort(RebaseResult result) throws IOException {
  653. try {
  654. String commitId = readFile(repo.getDirectory(), Constants.ORIG_HEAD);
  655. monitor.beginTask(MessageFormat.format(
  656. JGitText.get().abortingRebase, commitId),
  657. ProgressMonitor.UNKNOWN);
  658. DirCacheCheckout dco;
  659. RevCommit commit = walk.parseCommit(repo.resolve(commitId));
  660. if (result.getStatus().equals(Status.FAILED)) {
  661. RevCommit head = walk.parseCommit(repo.resolve(Constants.HEAD));
  662. dco = new DirCacheCheckout(repo, head.getTree(),
  663. repo.lockDirCache(), commit.getTree());
  664. } else {
  665. dco = new DirCacheCheckout(repo, repo.lockDirCache(),
  666. commit.getTree());
  667. }
  668. dco.setFailOnConflict(false);
  669. dco.checkout();
  670. walk.release();
  671. } finally {
  672. monitor.endTask();
  673. }
  674. try {
  675. String headName = readFile(rebaseDir, HEAD_NAME);
  676. if (headName.startsWith(Constants.R_REFS)) {
  677. monitor.beginTask(MessageFormat.format(
  678. JGitText.get().resettingHead, headName),
  679. ProgressMonitor.UNKNOWN);
  680. // update the HEAD
  681. RefUpdate refUpdate = repo.updateRef(Constants.HEAD, false);
  682. Result res = refUpdate.link(headName);
  683. switch (res) {
  684. case FAST_FORWARD:
  685. case FORCED:
  686. case NO_CHANGE:
  687. break;
  688. default:
  689. throw new JGitInternalException(
  690. JGitText.get().abortingRebaseFailed);
  691. }
  692. }
  693. // cleanup the files
  694. FileUtils.delete(rebaseDir, FileUtils.RECURSIVE);
  695. repo.writeCherryPickHead(null);
  696. return result;
  697. } finally {
  698. monitor.endTask();
  699. }
  700. }
  701. private String readFile(File directory, String fileName) throws IOException {
  702. byte[] content = IO.readFully(new File(directory, fileName));
  703. // strip off the last LF
  704. int end = content.length;
  705. while (0 < end && content[end - 1] == '\n')
  706. end--;
  707. return RawParseUtils.decode(content, 0, end);
  708. }
  709. private boolean checkoutCommit(RevCommit commit) throws IOException {
  710. try {
  711. RevCommit head = walk.parseCommit(repo.resolve(Constants.HEAD));
  712. DirCacheCheckout dco = new DirCacheCheckout(repo, head.getTree(),
  713. repo.lockDirCache(), commit.getTree());
  714. dco.setFailOnConflict(true);
  715. dco.checkout();
  716. // update the HEAD
  717. RefUpdate refUpdate = repo.updateRef(Constants.HEAD, true);
  718. refUpdate.setExpectedOldObjectId(head);
  719. refUpdate.setNewObjectId(commit);
  720. Result res = refUpdate.forceUpdate();
  721. switch (res) {
  722. case FAST_FORWARD:
  723. case NO_CHANGE:
  724. case FORCED:
  725. break;
  726. default:
  727. throw new IOException("Could not rewind to upstream commit");
  728. }
  729. } finally {
  730. walk.release();
  731. monitor.endTask();
  732. }
  733. return true;
  734. }
  735. private List<Step> loadSteps() throws IOException {
  736. byte[] buf = IO.readFully(new File(rebaseDir, GIT_REBASE_TODO));
  737. int ptr = 0;
  738. int tokenBegin = 0;
  739. ArrayList<Step> r = new ArrayList<Step>();
  740. while (ptr < buf.length) {
  741. tokenBegin = ptr;
  742. ptr = RawParseUtils.nextLF(buf, ptr);
  743. int nextSpace = 0;
  744. int tokenCount = 0;
  745. Step current = null;
  746. while (tokenCount < 3 && nextSpace < ptr) {
  747. switch (tokenCount) {
  748. case 0:
  749. nextSpace = RawParseUtils.next(buf, tokenBegin, ' ');
  750. String actionToken = new String(buf, tokenBegin, nextSpace
  751. - tokenBegin - 1);
  752. tokenBegin = nextSpace;
  753. if (actionToken.charAt(0) == '#') {
  754. tokenCount = 3;
  755. break;
  756. }
  757. Action action = Action.parse(actionToken);
  758. if (action != null)
  759. current = new Step(Action.parse(actionToken));
  760. break;
  761. case 1:
  762. if (current == null)
  763. break;
  764. nextSpace = RawParseUtils.next(buf, tokenBegin, ' ');
  765. String commitToken = new String(buf, tokenBegin, nextSpace
  766. - tokenBegin - 1);
  767. tokenBegin = nextSpace;
  768. current.commit = AbbreviatedObjectId
  769. .fromString(commitToken);
  770. break;
  771. case 2:
  772. if (current == null)
  773. break;
  774. nextSpace = ptr;
  775. int length = ptr - tokenBegin;
  776. current.shortMessage = new byte[length];
  777. System.arraycopy(buf, tokenBegin, current.shortMessage, 0,
  778. length);
  779. r.add(current);
  780. break;
  781. }
  782. tokenCount++;
  783. }
  784. }
  785. return r;
  786. }
  787. /**
  788. * @param upstream
  789. * the upstream commit
  790. * @return {@code this}
  791. */
  792. public RebaseCommand setUpstream(RevCommit upstream) {
  793. this.upstreamCommit = upstream;
  794. return this;
  795. }
  796. /**
  797. * @param upstream
  798. * id of the upstream commit
  799. * @return {@code this}
  800. */
  801. public RebaseCommand setUpstream(AnyObjectId upstream) {
  802. try {
  803. this.upstreamCommit = walk.parseCommit(upstream);
  804. } catch (IOException e) {
  805. throw new JGitInternalException(MessageFormat.format(
  806. JGitText.get().couldNotReadObjectWhileParsingCommit,
  807. upstream.name()), e);
  808. }
  809. return this;
  810. }
  811. /**
  812. * @param upstream
  813. * the upstream branch
  814. * @return {@code this}
  815. * @throws RefNotFoundException
  816. */
  817. public RebaseCommand setUpstream(String upstream)
  818. throws RefNotFoundException {
  819. try {
  820. ObjectId upstreamId = repo.resolve(upstream);
  821. if (upstreamId == null)
  822. throw new RefNotFoundException(MessageFormat.format(JGitText
  823. .get().refNotResolved, upstream));
  824. upstreamCommit = walk.parseCommit(repo.resolve(upstream));
  825. return this;
  826. } catch (IOException ioe) {
  827. throw new JGitInternalException(ioe.getMessage(), ioe);
  828. }
  829. }
  830. /**
  831. * @param operation
  832. * the operation to perform
  833. * @return {@code this}
  834. */
  835. public RebaseCommand setOperation(Operation operation) {
  836. this.operation = operation;
  837. return this;
  838. }
  839. /**
  840. * @param monitor
  841. * a progress monitor
  842. * @return this instance
  843. */
  844. public RebaseCommand setProgressMonitor(ProgressMonitor monitor) {
  845. this.monitor = monitor;
  846. return this;
  847. }
  848. static enum Action {
  849. PICK("pick"); // later add SQUASH, EDIT, etc.
  850. private final String token;
  851. private Action(String token) {
  852. this.token = token;
  853. }
  854. public String toToken() {
  855. return this.token;
  856. }
  857. static Action parse(String token) {
  858. if (token.equals("pick") || token.equals("p"))
  859. return PICK;
  860. throw new JGitInternalException(
  861. MessageFormat
  862. .format(
  863. "Unknown or unsupported command \"{0}\", only \"pick\" is allowed",
  864. token));
  865. }
  866. }
  867. static class Step {
  868. Action action;
  869. AbbreviatedObjectId commit;
  870. byte[] shortMessage;
  871. Step(Action action) {
  872. this.action = action;
  873. }
  874. }
  875. PersonIdent parseAuthor(byte[] raw) {
  876. if (raw.length == 0)
  877. return null;
  878. Map<String, String> keyValueMap = new HashMap<String, String>();
  879. for (int p = 0; p < raw.length;) {
  880. int end = RawParseUtils.nextLF(raw, p);
  881. if (end == p)
  882. break;
  883. int equalsIndex = RawParseUtils.next(raw, p, '=');
  884. if (equalsIndex == end)
  885. break;
  886. String key = RawParseUtils.decode(raw, p, equalsIndex - 1);
  887. String value = RawParseUtils.decode(raw, equalsIndex + 1, end - 2);
  888. p = end;
  889. keyValueMap.put(key, value);
  890. }
  891. String name = keyValueMap.get(GIT_AUTHOR_NAME);
  892. String email = keyValueMap.get(GIT_AUTHOR_EMAIL);
  893. String time = keyValueMap.get(GIT_AUTHOR_DATE);
  894. // the time is saved as <seconds since 1970> <timezone offset>
  895. long when = Long.parseLong(time.substring(0, time.indexOf(' '))) * 1000;
  896. String tzOffsetString = time.substring(time.indexOf(' ') + 1);
  897. int multiplier = -1;
  898. if (tzOffsetString.charAt(0) == '+')
  899. multiplier = 1;
  900. int hours = Integer.parseInt(tzOffsetString.substring(1, 3));
  901. int minutes = Integer.parseInt(tzOffsetString.substring(3, 5));
  902. // this is in format (+/-)HHMM (hours and minutes)
  903. // we need to convert into minutes
  904. int tz = (hours * 60 + minutes) * multiplier;
  905. if (name != null && email != null)
  906. return new PersonIdent(name, email, when, tz);
  907. return null;
  908. }
  909. }