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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  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. repo.writeOrigHead(headId);
  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. ObjectId origHead = repo.readOrigHead();
  669. String commitId = origHead != null ? origHead.name() : null;
  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(MessageFormat.format(
  876. JGitText.get().unknownOrUnsupportedCommand, token,
  877. PICK.toToken()));
  878. }
  879. }
  880. static class Step {
  881. Action action;
  882. AbbreviatedObjectId commit;
  883. byte[] shortMessage;
  884. Step(Action action) {
  885. this.action = action;
  886. }
  887. }
  888. PersonIdent parseAuthor(byte[] raw) {
  889. if (raw.length == 0)
  890. return null;
  891. Map<String, String> keyValueMap = new HashMap<String, String>();
  892. for (int p = 0; p < raw.length;) {
  893. int end = RawParseUtils.nextLF(raw, p);
  894. if (end == p)
  895. break;
  896. int equalsIndex = RawParseUtils.next(raw, p, '=');
  897. if (equalsIndex == end)
  898. break;
  899. String key = RawParseUtils.decode(raw, p, equalsIndex - 1);
  900. String value = RawParseUtils.decode(raw, equalsIndex + 1, end - 2);
  901. p = end;
  902. keyValueMap.put(key, value);
  903. }
  904. String name = keyValueMap.get(GIT_AUTHOR_NAME);
  905. String email = keyValueMap.get(GIT_AUTHOR_EMAIL);
  906. String time = keyValueMap.get(GIT_AUTHOR_DATE);
  907. // the time is saved as <seconds since 1970> <timezone offset>
  908. long when = Long.parseLong(time.substring(0, time.indexOf(' '))) * 1000;
  909. String tzOffsetString = time.substring(time.indexOf(' ') + 1);
  910. int multiplier = -1;
  911. if (tzOffsetString.charAt(0) == '+')
  912. multiplier = 1;
  913. int hours = Integer.parseInt(tzOffsetString.substring(1, 3));
  914. int minutes = Integer.parseInt(tzOffsetString.substring(3, 5));
  915. // this is in format (+/-)HHMM (hours and minutes)
  916. // we need to convert into minutes
  917. int tz = (hours * 60 + minutes) * multiplier;
  918. if (name != null && email != null)
  919. return new PersonIdent(name, email, when, tz);
  920. return null;
  921. }
  922. }