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

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