Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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