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

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