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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  1. /*
  2. * Copyright (C) 2010, Mathias Kinzler <mathias.kinzler@sap.com>
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.api;
  44. import java.io.BufferedReader;
  45. import java.io.BufferedWriter;
  46. import java.io.ByteArrayOutputStream;
  47. import java.io.File;
  48. import java.io.FileInputStream;
  49. import java.io.FileNotFoundException;
  50. import java.io.FileOutputStream;
  51. import java.io.IOException;
  52. import java.io.InputStreamReader;
  53. import java.io.OutputStreamWriter;
  54. import java.text.MessageFormat;
  55. import java.util.ArrayList;
  56. import java.util.Collection;
  57. import java.util.Collections;
  58. import java.util.HashMap;
  59. import java.util.List;
  60. import java.util.Map;
  61. import org.eclipse.jgit.api.RebaseResult.Status;
  62. import org.eclipse.jgit.api.errors.CheckoutConflictException;
  63. import org.eclipse.jgit.api.errors.GitAPIException;
  64. import org.eclipse.jgit.api.errors.InvalidRefNameException;
  65. import org.eclipse.jgit.api.errors.JGitInternalException;
  66. import org.eclipse.jgit.api.errors.NoHeadException;
  67. import org.eclipse.jgit.api.errors.RefAlreadyExistsException;
  68. import org.eclipse.jgit.api.errors.RefNotFoundException;
  69. import org.eclipse.jgit.api.errors.UnmergedPathsException;
  70. import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
  71. import org.eclipse.jgit.diff.DiffFormatter;
  72. import org.eclipse.jgit.dircache.DirCache;
  73. import org.eclipse.jgit.dircache.DirCacheCheckout;
  74. import org.eclipse.jgit.dircache.DirCacheIterator;
  75. import org.eclipse.jgit.internal.JGitText;
  76. import org.eclipse.jgit.lib.AbbreviatedObjectId;
  77. import org.eclipse.jgit.lib.AnyObjectId;
  78. import org.eclipse.jgit.lib.Constants;
  79. import org.eclipse.jgit.lib.NullProgressMonitor;
  80. import org.eclipse.jgit.lib.ObjectId;
  81. import org.eclipse.jgit.lib.ObjectReader;
  82. import org.eclipse.jgit.lib.PersonIdent;
  83. import org.eclipse.jgit.lib.ProgressMonitor;
  84. import org.eclipse.jgit.lib.Ref;
  85. import org.eclipse.jgit.lib.RefUpdate;
  86. import org.eclipse.jgit.lib.RefUpdate.Result;
  87. import org.eclipse.jgit.lib.Repository;
  88. import org.eclipse.jgit.revwalk.RevCommit;
  89. import org.eclipse.jgit.revwalk.RevWalk;
  90. import org.eclipse.jgit.treewalk.TreeWalk;
  91. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  92. import org.eclipse.jgit.util.FileUtils;
  93. import org.eclipse.jgit.util.IO;
  94. import org.eclipse.jgit.util.RawParseUtils;
  95. /**
  96. * A class used to execute a {@code Rebase} command. It has setters for all
  97. * supported options and arguments of this command and a {@link #call()} method
  98. * to finally execute the command. Each instance of this class should only be
  99. * used for one invocation of the command (means: one call to {@link #call()})
  100. * <p>
  101. *
  102. * @see <a
  103. * href="http://www.kernel.org/pub/software/scm/git/docs/git-rebase.html"
  104. * >Git documentation about Rebase</a>
  105. */
  106. public class RebaseCommand extends GitCommand<RebaseResult> {
  107. /**
  108. * The name of the "rebase-merge" folder
  109. */
  110. public static final String REBASE_MERGE = "rebase-merge";
  111. /**
  112. * The name of the "stopped-sha" file
  113. */
  114. public static final String STOPPED_SHA = "stopped-sha";
  115. private static final String AUTHOR_SCRIPT = "author-script";
  116. private static final String DONE = "done";
  117. private static final String GIT_AUTHOR_DATE = "GIT_AUTHOR_DATE";
  118. private static final String GIT_AUTHOR_EMAIL = "GIT_AUTHOR_EMAIL";
  119. private static final String GIT_AUTHOR_NAME = "GIT_AUTHOR_NAME";
  120. private static final String GIT_REBASE_TODO = "git-rebase-todo";
  121. private static final String HEAD_NAME = "head-name";
  122. private static final String INTERACTIVE = "interactive";
  123. private static final String MESSAGE = "message";
  124. private static final String ONTO = "onto";
  125. private static final String 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 GitAPIException, NoHeadException,
  170. RefNotFoundException {
  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, NoHeadException {
  296. ObjectId headTree = repo.resolve(Constants.HEAD + "^{tree}");
  297. if (headTree == null)
  298. throw new NoHeadException(
  299. JGitText.get().cannotRebaseWithoutCurrentHead);
  300. DirCache dc = repo.lockDirCache();
  301. try {
  302. DirCacheCheckout dco = new DirCacheCheckout(repo, dc, headTree);
  303. dco.setFailOnConflict(false);
  304. boolean needsDeleteFiles = dco.checkout();
  305. if (needsDeleteFiles) {
  306. List<String> fileList = dco.getToBeDeleted();
  307. for (String filePath : fileList) {
  308. File fileToDelete = new File(repo.getWorkTree(), filePath);
  309. if (fileToDelete.exists())
  310. FileUtils.delete(fileToDelete, FileUtils.RECURSIVE
  311. | FileUtils.RETRY);
  312. }
  313. }
  314. } finally {
  315. dc.unlock();
  316. }
  317. RevWalk rw = new RevWalk(repo);
  318. RevCommit commit = rw.parseCommit(repo.resolve(Constants.HEAD));
  319. rw.release();
  320. return commit;
  321. }
  322. /**
  323. * @return the commit if we had to do a commit, otherwise null
  324. * @throws GitAPIException
  325. * @throws IOException
  326. */
  327. private RevCommit continueRebase() throws GitAPIException, IOException {
  328. // if there are still conflicts, we throw a specific Exception
  329. DirCache dc = repo.readDirCache();
  330. boolean hasUnmergedPaths = dc.hasUnmergedPaths();
  331. if (hasUnmergedPaths)
  332. throw new UnmergedPathsException();
  333. // determine whether we need to commit
  334. TreeWalk treeWalk = new TreeWalk(repo);
  335. treeWalk.reset();
  336. treeWalk.setRecursive(true);
  337. treeWalk.addTree(new DirCacheIterator(dc));
  338. ObjectId id = repo.resolve(Constants.HEAD + "^{tree}");
  339. if (id == null)
  340. throw new NoHeadException(
  341. JGitText.get().cannotRebaseWithoutCurrentHead);
  342. treeWalk.addTree(id);
  343. treeWalk.setFilter(TreeFilter.ANY_DIFF);
  344. boolean needsCommit = treeWalk.next();
  345. treeWalk.release();
  346. if (needsCommit) {
  347. CommitCommand commit = new Git(repo).commit();
  348. commit.setMessage(readFile(rebaseDir, MESSAGE));
  349. commit.setAuthor(parseAuthor());
  350. return commit.call();
  351. }
  352. return null;
  353. }
  354. private PersonIdent parseAuthor() throws IOException {
  355. File authorScriptFile = new File(rebaseDir, AUTHOR_SCRIPT);
  356. byte[] raw;
  357. try {
  358. raw = IO.readFully(authorScriptFile);
  359. } catch (FileNotFoundException notFound) {
  360. return null;
  361. }
  362. return parseAuthor(raw);
  363. }
  364. private RebaseResult stop(RevCommit commitToPick) throws IOException {
  365. PersonIdent author = commitToPick.getAuthorIdent();
  366. String authorScript = toAuthorScript(author);
  367. createFile(rebaseDir, AUTHOR_SCRIPT, authorScript);
  368. createFile(rebaseDir, MESSAGE, commitToPick.getFullMessage());
  369. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  370. DiffFormatter df = new DiffFormatter(bos);
  371. df.setRepository(repo);
  372. df.format(commitToPick.getParent(0), commitToPick);
  373. createFile(rebaseDir, PATCH, new String(bos.toByteArray(),
  374. Constants.CHARACTER_ENCODING));
  375. createFile(rebaseDir, STOPPED_SHA, repo.newObjectReader().abbreviate(
  376. commitToPick).name());
  377. // Remove cherry pick state file created by CherryPickCommand, it's not
  378. // needed for rebase
  379. repo.writeCherryPickHead(null);
  380. return new RebaseResult(commitToPick);
  381. }
  382. String toAuthorScript(PersonIdent author) {
  383. StringBuilder sb = new StringBuilder(100);
  384. sb.append(GIT_AUTHOR_NAME);
  385. sb.append("='");
  386. sb.append(author.getName());
  387. sb.append("'\n");
  388. sb.append(GIT_AUTHOR_EMAIL);
  389. sb.append("='");
  390. sb.append(author.getEmailAddress());
  391. sb.append("'\n");
  392. // the command line uses the "external String"
  393. // representation for date and timezone
  394. sb.append(GIT_AUTHOR_DATE);
  395. sb.append("='");
  396. String externalString = author.toExternalString();
  397. sb
  398. .append(externalString.substring(externalString
  399. .lastIndexOf('>') + 2));
  400. sb.append("'\n");
  401. return sb.toString();
  402. }
  403. /**
  404. * Removes the number of lines given in the parameter from the
  405. * <code>git-rebase-todo</code> file but preserves comments and other lines
  406. * that can not be parsed as steps
  407. *
  408. * @param numSteps
  409. * @throws IOException
  410. */
  411. private void popSteps(int numSteps) throws IOException {
  412. if (numSteps == 0)
  413. return;
  414. List<String> todoLines = new ArrayList<String>();
  415. List<String> poppedLines = new ArrayList<String>();
  416. File todoFile = new File(rebaseDir, GIT_REBASE_TODO);
  417. File doneFile = new File(rebaseDir, DONE);
  418. BufferedReader br = new BufferedReader(new InputStreamReader(
  419. new FileInputStream(todoFile), Constants.CHARACTER_ENCODING));
  420. try {
  421. // check if the line starts with a action tag (pick, skip...)
  422. while (poppedLines.size() < numSteps) {
  423. String popCandidate = br.readLine();
  424. if (popCandidate == null)
  425. break;
  426. if (popCandidate.charAt(0) == '#')
  427. continue;
  428. int spaceIndex = popCandidate.indexOf(' ');
  429. boolean pop = false;
  430. if (spaceIndex >= 0) {
  431. String actionToken = popCandidate.substring(0, spaceIndex);
  432. pop = Action.parse(actionToken) != null;
  433. }
  434. if (pop)
  435. poppedLines.add(popCandidate);
  436. else
  437. todoLines.add(popCandidate);
  438. }
  439. String readLine = br.readLine();
  440. while (readLine != null) {
  441. todoLines.add(readLine);
  442. readLine = br.readLine();
  443. }
  444. } finally {
  445. br.close();
  446. }
  447. BufferedWriter todoWriter = new BufferedWriter(new OutputStreamWriter(
  448. new FileOutputStream(todoFile), Constants.CHARACTER_ENCODING));
  449. try {
  450. for (String writeLine : todoLines) {
  451. todoWriter.write(writeLine);
  452. todoWriter.newLine();
  453. }
  454. } finally {
  455. todoWriter.close();
  456. }
  457. if (poppedLines.size() > 0) {
  458. // append here
  459. BufferedWriter doneWriter = new BufferedWriter(
  460. new OutputStreamWriter(
  461. new FileOutputStream(doneFile, true),
  462. Constants.CHARACTER_ENCODING));
  463. try {
  464. for (String writeLine : poppedLines) {
  465. doneWriter.write(writeLine);
  466. doneWriter.newLine();
  467. }
  468. } finally {
  469. doneWriter.close();
  470. }
  471. }
  472. }
  473. private RebaseResult initFilesAndRewind() throws IOException,
  474. GitAPIException {
  475. // we need to store everything into files so that we can implement
  476. // --skip, --continue, and --abort
  477. Ref head = repo.getRef(Constants.HEAD);
  478. if (head == null || head.getObjectId() == null)
  479. throw new RefNotFoundException(MessageFormat.format(
  480. JGitText.get().refNotResolved, Constants.HEAD));
  481. String headName;
  482. if (head.isSymbolic())
  483. headName = head.getTarget().getName();
  484. else
  485. headName = "detached HEAD";
  486. ObjectId headId = head.getObjectId();
  487. if (headId == null)
  488. throw new RefNotFoundException(MessageFormat.format(
  489. JGitText.get().refNotResolved, Constants.HEAD));
  490. RevCommit headCommit = walk.lookupCommit(headId);
  491. RevCommit upstream = walk.lookupCommit(upstreamCommit.getId());
  492. if (walk.isMergedInto(upstream, headCommit))
  493. return RebaseResult.UP_TO_DATE_RESULT;
  494. else if (walk.isMergedInto(headCommit, upstream)) {
  495. // head is already merged into upstream, fast-foward
  496. monitor.beginTask(MessageFormat.format(
  497. JGitText.get().resettingHead,
  498. upstreamCommit.getShortMessage()), ProgressMonitor.UNKNOWN);
  499. checkoutCommit(upstreamCommit);
  500. monitor.endTask();
  501. updateHead(headName, upstreamCommit);
  502. return RebaseResult.FAST_FORWARD_RESULT;
  503. }
  504. monitor.beginTask(JGitText.get().obtainingCommitsForCherryPick,
  505. ProgressMonitor.UNKNOWN);
  506. // determine the commits to be applied
  507. LogCommand cmd = new Git(repo).log().addRange(upstreamCommit,
  508. headCommit);
  509. Iterable<RevCommit> commitsToUse = cmd.call();
  510. List<RevCommit> cherryPickList = new ArrayList<RevCommit>();
  511. for (RevCommit commit : commitsToUse) {
  512. if (commit.getParentCount() != 1)
  513. throw new JGitInternalException(
  514. MessageFormat.format(
  515. JGitText.get().canOnlyCherryPickCommitsWithOneParent,
  516. commit.name(),
  517. Integer.valueOf(commit.getParentCount())));
  518. cherryPickList.add(commit);
  519. }
  520. Collections.reverse(cherryPickList);
  521. // create the folder for the meta information
  522. FileUtils.mkdir(rebaseDir);
  523. createFile(repo.getDirectory(), Constants.ORIG_HEAD, headId.name());
  524. createFile(rebaseDir, REBASE_HEAD, headId.name());
  525. createFile(rebaseDir, HEAD_NAME, headName);
  526. createFile(rebaseDir, ONTO, upstreamCommit.name());
  527. createFile(rebaseDir, INTERACTIVE, "");
  528. BufferedWriter fw = new BufferedWriter(new OutputStreamWriter(
  529. new FileOutputStream(new File(rebaseDir, GIT_REBASE_TODO)),
  530. Constants.CHARACTER_ENCODING));
  531. fw.write("# Created by EGit: rebasing " + upstreamCommit.name()
  532. + " onto " + headId.name());
  533. fw.newLine();
  534. try {
  535. StringBuilder sb = new StringBuilder();
  536. ObjectReader reader = walk.getObjectReader();
  537. for (RevCommit commit : cherryPickList) {
  538. sb.setLength(0);
  539. sb.append(Action.PICK.toToken());
  540. sb.append(" ");
  541. sb.append(reader.abbreviate(commit).name());
  542. sb.append(" ");
  543. sb.append(commit.getShortMessage());
  544. fw.write(sb.toString());
  545. fw.newLine();
  546. }
  547. } finally {
  548. fw.close();
  549. }
  550. monitor.endTask();
  551. // we rewind to the upstream commit
  552. monitor.beginTask(MessageFormat.format(JGitText.get().rewinding,
  553. upstreamCommit.getShortMessage()), ProgressMonitor.UNKNOWN);
  554. boolean checkoutOk = false;
  555. try {
  556. checkoutOk = checkoutCommit(upstreamCommit);
  557. } finally {
  558. if (!checkoutOk)
  559. FileUtils.delete(rebaseDir, FileUtils.RECURSIVE);
  560. }
  561. monitor.endTask();
  562. return null;
  563. }
  564. /**
  565. * checks if we can fast-forward and returns the new head if it is possible
  566. *
  567. * @param newCommit
  568. * @return the new head, or null
  569. * @throws IOException
  570. * @throws GitAPIException
  571. */
  572. public RevCommit tryFastForward(RevCommit newCommit) throws IOException,
  573. GitAPIException {
  574. Ref head = repo.getRef(Constants.HEAD);
  575. if (head == null || head.getObjectId() == null)
  576. throw new RefNotFoundException(MessageFormat.format(
  577. JGitText.get().refNotResolved, Constants.HEAD));
  578. ObjectId headId = head.getObjectId();
  579. if (headId == null)
  580. throw new RefNotFoundException(MessageFormat.format(
  581. JGitText.get().refNotResolved, Constants.HEAD));
  582. RevCommit headCommit = walk.lookupCommit(headId);
  583. if (walk.isMergedInto(newCommit, headCommit))
  584. return newCommit;
  585. String headName;
  586. if (head.isSymbolic())
  587. headName = head.getTarget().getName();
  588. else
  589. headName = "detached HEAD";
  590. return tryFastForward(headName, headCommit, newCommit);
  591. }
  592. private RevCommit tryFastForward(String headName, RevCommit oldCommit,
  593. RevCommit newCommit) throws IOException, GitAPIException {
  594. boolean tryRebase = false;
  595. for (RevCommit parentCommit : newCommit.getParents())
  596. if (parentCommit.equals(oldCommit))
  597. tryRebase = true;
  598. if (!tryRebase)
  599. return null;
  600. CheckoutCommand co = new CheckoutCommand(repo);
  601. try {
  602. co.setName(newCommit.name()).call();
  603. if (headName.startsWith(Constants.R_HEADS)) {
  604. RefUpdate rup = repo.updateRef(headName);
  605. rup.setExpectedOldObjectId(oldCommit);
  606. rup.setNewObjectId(newCommit);
  607. rup.setRefLogMessage("Fast-foward from " + oldCommit.name()
  608. + " to " + newCommit.name(), false);
  609. Result res = rup.update(walk);
  610. switch (res) {
  611. case FAST_FORWARD:
  612. case NO_CHANGE:
  613. case FORCED:
  614. break;
  615. default:
  616. throw new IOException("Could not fast-forward");
  617. }
  618. }
  619. return newCommit;
  620. } catch (RefAlreadyExistsException e) {
  621. throw new JGitInternalException(e.getMessage(), e);
  622. } catch (RefNotFoundException e) {
  623. throw new JGitInternalException(e.getMessage(), e);
  624. } catch (InvalidRefNameException e) {
  625. throw new JGitInternalException(e.getMessage(), e);
  626. } catch (CheckoutConflictException e) {
  627. throw new JGitInternalException(e.getMessage(), e);
  628. }
  629. }
  630. private void checkParameters() throws WrongRepositoryStateException {
  631. if (this.operation != Operation.BEGIN) {
  632. // these operations are only possible while in a rebasing state
  633. switch (repo.getRepositoryState()) {
  634. case REBASING_INTERACTIVE:
  635. break;
  636. default:
  637. throw new WrongRepositoryStateException(MessageFormat.format(
  638. JGitText.get().wrongRepositoryState, repo
  639. .getRepositoryState().name()));
  640. }
  641. } else
  642. switch (repo.getRepositoryState()) {
  643. case SAFE:
  644. if (this.upstreamCommit == null)
  645. throw new JGitInternalException(MessageFormat
  646. .format(JGitText.get().missingRequiredParameter,
  647. "upstream"));
  648. return;
  649. default:
  650. throw new WrongRepositoryStateException(MessageFormat.format(
  651. JGitText.get().wrongRepositoryState, repo
  652. .getRepositoryState().name()));
  653. }
  654. }
  655. private void createFile(File parentDir, String name, String content)
  656. throws IOException {
  657. File file = new File(parentDir, name);
  658. FileOutputStream fos = new FileOutputStream(file);
  659. try {
  660. fos.write(content.getBytes(Constants.CHARACTER_ENCODING));
  661. fos.write('\n');
  662. } finally {
  663. fos.close();
  664. }
  665. }
  666. private RebaseResult abort(RebaseResult result) throws IOException {
  667. try {
  668. String commitId = readFile(repo.getDirectory(), Constants.ORIG_HEAD);
  669. monitor.beginTask(MessageFormat.format(
  670. JGitText.get().abortingRebase, commitId),
  671. ProgressMonitor.UNKNOWN);
  672. DirCacheCheckout dco;
  673. RevCommit commit = walk.parseCommit(repo.resolve(commitId));
  674. if (result.getStatus().equals(Status.FAILED)) {
  675. RevCommit head = walk.parseCommit(repo.resolve(Constants.HEAD));
  676. dco = new DirCacheCheckout(repo, head.getTree(),
  677. repo.lockDirCache(), commit.getTree());
  678. } else {
  679. dco = new DirCacheCheckout(repo, repo.lockDirCache(),
  680. commit.getTree());
  681. }
  682. dco.setFailOnConflict(false);
  683. dco.checkout();
  684. walk.release();
  685. } finally {
  686. monitor.endTask();
  687. }
  688. try {
  689. String headName = readFile(rebaseDir, HEAD_NAME);
  690. if (headName.startsWith(Constants.R_REFS)) {
  691. monitor.beginTask(MessageFormat.format(
  692. JGitText.get().resettingHead, headName),
  693. ProgressMonitor.UNKNOWN);
  694. // update the HEAD
  695. RefUpdate refUpdate = repo.updateRef(Constants.HEAD, false);
  696. Result res = refUpdate.link(headName);
  697. switch (res) {
  698. case FAST_FORWARD:
  699. case FORCED:
  700. case NO_CHANGE:
  701. break;
  702. default:
  703. throw new JGitInternalException(
  704. JGitText.get().abortingRebaseFailed);
  705. }
  706. }
  707. // cleanup the files
  708. FileUtils.delete(rebaseDir, FileUtils.RECURSIVE);
  709. repo.writeCherryPickHead(null);
  710. return result;
  711. } finally {
  712. monitor.endTask();
  713. }
  714. }
  715. private String readFile(File directory, String fileName) throws IOException {
  716. byte[] content = IO.readFully(new File(directory, fileName));
  717. // strip off the last LF
  718. int end = content.length;
  719. while (0 < end && content[end - 1] == '\n')
  720. end--;
  721. return RawParseUtils.decode(content, 0, end);
  722. }
  723. private boolean checkoutCommit(RevCommit commit) throws IOException {
  724. try {
  725. RevCommit head = walk.parseCommit(repo.resolve(Constants.HEAD));
  726. DirCacheCheckout dco = new DirCacheCheckout(repo, head.getTree(),
  727. repo.lockDirCache(), commit.getTree());
  728. dco.setFailOnConflict(true);
  729. dco.checkout();
  730. // update the HEAD
  731. RefUpdate refUpdate = repo.updateRef(Constants.HEAD, true);
  732. refUpdate.setExpectedOldObjectId(head);
  733. refUpdate.setNewObjectId(commit);
  734. Result res = refUpdate.forceUpdate();
  735. switch (res) {
  736. case FAST_FORWARD:
  737. case NO_CHANGE:
  738. case FORCED:
  739. break;
  740. default:
  741. throw new IOException("Could not rewind to upstream commit");
  742. }
  743. } finally {
  744. walk.release();
  745. monitor.endTask();
  746. }
  747. return true;
  748. }
  749. private List<Step> loadSteps() throws IOException {
  750. byte[] buf = IO.readFully(new File(rebaseDir, GIT_REBASE_TODO));
  751. int ptr = 0;
  752. int tokenBegin = 0;
  753. ArrayList<Step> r = new ArrayList<Step>();
  754. while (ptr < buf.length) {
  755. tokenBegin = ptr;
  756. ptr = RawParseUtils.nextLF(buf, ptr);
  757. int nextSpace = 0;
  758. int tokenCount = 0;
  759. Step current = null;
  760. while (tokenCount < 3 && nextSpace < ptr) {
  761. switch (tokenCount) {
  762. case 0:
  763. nextSpace = RawParseUtils.next(buf, tokenBegin, ' ');
  764. String actionToken = new String(buf, tokenBegin, nextSpace
  765. - tokenBegin - 1);
  766. tokenBegin = nextSpace;
  767. if (actionToken.charAt(0) == '#') {
  768. tokenCount = 3;
  769. break;
  770. }
  771. Action action = Action.parse(actionToken);
  772. if (action != null)
  773. current = new Step(Action.parse(actionToken));
  774. break;
  775. case 1:
  776. if (current == null)
  777. break;
  778. nextSpace = RawParseUtils.next(buf, tokenBegin, ' ');
  779. String commitToken = new String(buf, tokenBegin, nextSpace
  780. - tokenBegin - 1);
  781. tokenBegin = nextSpace;
  782. current.commit = AbbreviatedObjectId
  783. .fromString(commitToken);
  784. break;
  785. case 2:
  786. if (current == null)
  787. break;
  788. nextSpace = ptr;
  789. int length = ptr - tokenBegin;
  790. current.shortMessage = new byte[length];
  791. System.arraycopy(buf, tokenBegin, current.shortMessage, 0,
  792. length);
  793. r.add(current);
  794. break;
  795. }
  796. tokenCount++;
  797. }
  798. }
  799. return r;
  800. }
  801. /**
  802. * @param upstream
  803. * the upstream commit
  804. * @return {@code this}
  805. */
  806. public RebaseCommand setUpstream(RevCommit upstream) {
  807. this.upstreamCommit = upstream;
  808. return this;
  809. }
  810. /**
  811. * @param upstream
  812. * id of the upstream commit
  813. * @return {@code this}
  814. */
  815. public RebaseCommand setUpstream(AnyObjectId upstream) {
  816. try {
  817. this.upstreamCommit = walk.parseCommit(upstream);
  818. } catch (IOException e) {
  819. throw new JGitInternalException(MessageFormat.format(
  820. JGitText.get().couldNotReadObjectWhileParsingCommit,
  821. upstream.name()), e);
  822. }
  823. return this;
  824. }
  825. /**
  826. * @param upstream
  827. * the upstream branch
  828. * @return {@code this}
  829. * @throws RefNotFoundException
  830. */
  831. public RebaseCommand setUpstream(String upstream)
  832. throws RefNotFoundException {
  833. try {
  834. ObjectId upstreamId = repo.resolve(upstream);
  835. if (upstreamId == null)
  836. throw new RefNotFoundException(MessageFormat.format(JGitText
  837. .get().refNotResolved, upstream));
  838. upstreamCommit = walk.parseCommit(repo.resolve(upstream));
  839. return this;
  840. } catch (IOException ioe) {
  841. throw new JGitInternalException(ioe.getMessage(), ioe);
  842. }
  843. }
  844. /**
  845. * @param operation
  846. * the operation to perform
  847. * @return {@code this}
  848. */
  849. public RebaseCommand setOperation(Operation operation) {
  850. this.operation = operation;
  851. return this;
  852. }
  853. /**
  854. * @param monitor
  855. * a progress monitor
  856. * @return this instance
  857. */
  858. public RebaseCommand setProgressMonitor(ProgressMonitor monitor) {
  859. this.monitor = monitor;
  860. return this;
  861. }
  862. static enum Action {
  863. PICK("pick"); // later add SQUASH, EDIT, etc.
  864. private final String token;
  865. private Action(String token) {
  866. this.token = token;
  867. }
  868. public String toToken() {
  869. return this.token;
  870. }
  871. static Action parse(String token) {
  872. if (token.equals("pick") || token.equals("p"))
  873. return PICK;
  874. throw new JGitInternalException(MessageFormat.format(
  875. JGitText.get().unknownOrUnsupportedCommand, token,
  876. PICK.toToken()));
  877. }
  878. }
  879. static class Step {
  880. Action action;
  881. AbbreviatedObjectId commit;
  882. byte[] shortMessage;
  883. Step(Action action) {
  884. this.action = action;
  885. }
  886. }
  887. PersonIdent parseAuthor(byte[] raw) {
  888. if (raw.length == 0)
  889. return null;
  890. Map<String, String> keyValueMap = new HashMap<String, String>();
  891. for (int p = 0; p < raw.length;) {
  892. int end = RawParseUtils.nextLF(raw, p);
  893. if (end == p)
  894. break;
  895. int equalsIndex = RawParseUtils.next(raw, p, '=');
  896. if (equalsIndex == end)
  897. break;
  898. String key = RawParseUtils.decode(raw, p, equalsIndex - 1);
  899. String value = RawParseUtils.decode(raw, equalsIndex + 1, end - 2);
  900. p = end;
  901. keyValueMap.put(key, value);
  902. }
  903. String name = keyValueMap.get(GIT_AUTHOR_NAME);
  904. String email = keyValueMap.get(GIT_AUTHOR_EMAIL);
  905. String time = keyValueMap.get(GIT_AUTHOR_DATE);
  906. // the time is saved as <seconds since 1970> <timezone offset>
  907. long when = Long.parseLong(time.substring(0, time.indexOf(' '))) * 1000;
  908. String tzOffsetString = time.substring(time.indexOf(' ') + 1);
  909. int multiplier = -1;
  910. if (tzOffsetString.charAt(0) == '+')
  911. multiplier = 1;
  912. int hours = Integer.parseInt(tzOffsetString.substring(1, 3));
  913. int minutes = Integer.parseInt(tzOffsetString.substring(3, 5));
  914. // this is in format (+/-)HHMM (hours and minutes)
  915. // we need to convert into minutes
  916. int tz = (hours * 60 + minutes) * multiplier;
  917. if (name != null && email != null)
  918. return new PersonIdent(name, email, when, tz);
  919. return null;
  920. }
  921. }