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.

CheckoutCommand.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. /*
  2. * Copyright (C) 2010, Chris Aniszczyk <caniszczyk@gmail.com>
  3. * Copyright (C) 2011, Matthias Sohn <matthias.sohn@sap.com>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.api;
  45. import java.io.File;
  46. import java.io.IOException;
  47. import java.text.MessageFormat;
  48. import java.util.LinkedList;
  49. import java.util.List;
  50. import org.eclipse.jgit.api.CheckoutResult.Status;
  51. import org.eclipse.jgit.api.errors.CheckoutConflictException;
  52. import org.eclipse.jgit.api.errors.InvalidRefNameException;
  53. import org.eclipse.jgit.api.errors.JGitInternalException;
  54. import org.eclipse.jgit.api.errors.RefAlreadyExistsException;
  55. import org.eclipse.jgit.api.errors.RefNotFoundException;
  56. import org.eclipse.jgit.dircache.DirCache;
  57. import org.eclipse.jgit.dircache.DirCacheCheckout;
  58. import org.eclipse.jgit.dircache.DirCacheEditor;
  59. import org.eclipse.jgit.dircache.DirCacheEditor.PathEdit;
  60. import org.eclipse.jgit.dircache.DirCacheEntry;
  61. import org.eclipse.jgit.dircache.DirCacheIterator;
  62. import org.eclipse.jgit.errors.AmbiguousObjectException;
  63. import org.eclipse.jgit.internal.JGitText;
  64. import org.eclipse.jgit.lib.AnyObjectId;
  65. import org.eclipse.jgit.lib.Constants;
  66. import org.eclipse.jgit.lib.FileMode;
  67. import org.eclipse.jgit.lib.ObjectId;
  68. import org.eclipse.jgit.lib.ObjectReader;
  69. import org.eclipse.jgit.lib.Ref;
  70. import org.eclipse.jgit.lib.RefUpdate;
  71. import org.eclipse.jgit.lib.RefUpdate.Result;
  72. import org.eclipse.jgit.lib.Repository;
  73. import org.eclipse.jgit.revwalk.RevCommit;
  74. import org.eclipse.jgit.revwalk.RevTree;
  75. import org.eclipse.jgit.revwalk.RevWalk;
  76. import org.eclipse.jgit.treewalk.TreeWalk;
  77. import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
  78. /**
  79. * Checkout a branch to the working tree
  80. *
  81. * @see <a
  82. * href="http://www.kernel.org/pub/software/scm/git/docs/git-checkout.html"
  83. * >Git documentation about Checkout</a>
  84. */
  85. public class CheckoutCommand extends GitCommand<Ref> {
  86. private String name;
  87. private boolean force = false;
  88. private boolean createBranch = false;
  89. private CreateBranchCommand.SetupUpstreamMode upstreamMode;
  90. private String startPoint = null;
  91. private RevCommit startCommit;
  92. private CheckoutResult status;
  93. private List<String> paths;
  94. private boolean checkoutAllPaths;
  95. /**
  96. * @param repo
  97. */
  98. protected CheckoutCommand(Repository repo) {
  99. super(repo);
  100. this.paths = new LinkedList<String>();
  101. }
  102. /**
  103. * @throws RefAlreadyExistsException
  104. * when trying to create (without force) a branch with a name
  105. * that already exists
  106. * @throws RefNotFoundException
  107. * if the start point or branch can not be found
  108. * @throws InvalidRefNameException
  109. * if the provided name is <code>null</code> or otherwise
  110. * invalid
  111. * @return the newly created branch
  112. */
  113. public Ref call() throws JGitInternalException, RefAlreadyExistsException,
  114. RefNotFoundException, InvalidRefNameException,
  115. CheckoutConflictException {
  116. checkCallable();
  117. processOptions();
  118. try {
  119. if (checkoutAllPaths || !paths.isEmpty()) {
  120. checkoutPaths();
  121. status = CheckoutResult.OK_RESULT;
  122. setCallable(false);
  123. return null;
  124. }
  125. if (createBranch) {
  126. Git git = new Git(repo);
  127. CreateBranchCommand command = git.branchCreate();
  128. command.setName(name);
  129. command.setStartPoint(getStartPoint().name());
  130. if (upstreamMode != null)
  131. command.setUpstreamMode(upstreamMode);
  132. command.call();
  133. }
  134. Ref headRef = repo.getRef(Constants.HEAD);
  135. String shortHeadRef = getShortBranchName(headRef);
  136. String refLogMessage = "checkout: moving from " + shortHeadRef;
  137. ObjectId branch = repo.resolve(name);
  138. if (branch == null)
  139. throw new RefNotFoundException(MessageFormat.format(JGitText
  140. .get().refNotResolved, name));
  141. RevWalk revWalk = new RevWalk(repo);
  142. AnyObjectId headId = headRef.getObjectId();
  143. RevCommit headCommit = headId == null ? null : revWalk
  144. .parseCommit(headId);
  145. RevCommit newCommit = revWalk.parseCommit(branch);
  146. RevTree headTree = headCommit == null ? null : headCommit.getTree();
  147. DirCacheCheckout dco;
  148. DirCache dc = repo.lockDirCache();
  149. try {
  150. dco = new DirCacheCheckout(repo, headTree, dc,
  151. newCommit.getTree());
  152. dco.setFailOnConflict(true);
  153. try {
  154. dco.checkout();
  155. } catch (org.eclipse.jgit.errors.CheckoutConflictException e) {
  156. status = new CheckoutResult(Status.CONFLICTS,
  157. dco.getConflicts());
  158. throw new CheckoutConflictException(dco.getConflicts(), e);
  159. }
  160. } finally {
  161. dc.unlock();
  162. }
  163. Ref ref = repo.getRef(name);
  164. if (ref != null && !ref.getName().startsWith(Constants.R_HEADS))
  165. ref = null;
  166. String toName = Repository.shortenRefName(name);
  167. RefUpdate refUpdate = repo.updateRef(Constants.HEAD, ref == null);
  168. refUpdate.setForceUpdate(force);
  169. refUpdate.setRefLogMessage(refLogMessage + " to " + toName, false);
  170. Result updateResult;
  171. if (ref != null)
  172. updateResult = refUpdate.link(ref.getName());
  173. else {
  174. refUpdate.setNewObjectId(newCommit);
  175. updateResult = refUpdate.forceUpdate();
  176. }
  177. setCallable(false);
  178. boolean ok = false;
  179. switch (updateResult) {
  180. case NEW:
  181. ok = true;
  182. break;
  183. case NO_CHANGE:
  184. case FAST_FORWARD:
  185. case FORCED:
  186. ok = true;
  187. break;
  188. default:
  189. break;
  190. }
  191. if (!ok)
  192. throw new JGitInternalException(MessageFormat.format(JGitText
  193. .get().checkoutUnexpectedResult, updateResult.name()));
  194. if (!dco.getToBeDeleted().isEmpty()) {
  195. status = new CheckoutResult(Status.NONDELETED, dco
  196. .getToBeDeleted());
  197. }
  198. else
  199. status = CheckoutResult.OK_RESULT;
  200. return ref;
  201. } catch (IOException ioe) {
  202. throw new JGitInternalException(ioe.getMessage(), ioe);
  203. } finally {
  204. if (status == null)
  205. status = CheckoutResult.ERROR_RESULT;
  206. }
  207. }
  208. private String getShortBranchName(Ref headRef) {
  209. if (headRef.getTarget().getName().equals(headRef.getName()))
  210. return headRef.getTarget().getObjectId().getName();
  211. return Repository.shortenRefName(headRef.getTarget().getName());
  212. }
  213. /**
  214. * @param path
  215. * Path to update in the working tree and index.
  216. * @return {@code this}
  217. */
  218. public CheckoutCommand addPath(String path) {
  219. checkCallable();
  220. this.paths.add(path);
  221. return this;
  222. }
  223. /**
  224. * Set whether to checkout all paths
  225. * <p>
  226. * This options should be used when you want to do a path checkout on the
  227. * entire repository and so calling {@link #addPath(String)} is not possible
  228. * since empty paths are not allowed.
  229. *
  230. * @param all
  231. * true to checkout all paths, false otherwise
  232. * @return {@code this}
  233. * @since 2.0
  234. */
  235. public CheckoutCommand setAllPaths(boolean all) {
  236. checkoutAllPaths = all;
  237. return this;
  238. }
  239. /**
  240. * Checkout paths into index and working directory
  241. *
  242. * @return this instance
  243. * @throws IOException
  244. * @throws RefNotFoundException
  245. */
  246. protected CheckoutCommand checkoutPaths() throws IOException,
  247. RefNotFoundException {
  248. RevWalk revWalk = new RevWalk(repo);
  249. DirCache dc = repo.lockDirCache();
  250. try {
  251. DirCacheEditor editor = dc.editor();
  252. TreeWalk startWalk = new TreeWalk(revWalk.getObjectReader());
  253. startWalk.setRecursive(true);
  254. if (!checkoutAllPaths)
  255. startWalk.setFilter(PathFilterGroup.createFromStrings(paths));
  256. boolean checkoutIndex = startCommit == null && startPoint == null;
  257. if (!checkoutIndex)
  258. startWalk.addTree(revWalk.parseCommit(getStartPoint())
  259. .getTree());
  260. else
  261. startWalk.addTree(new DirCacheIterator(dc));
  262. final File workTree = repo.getWorkTree();
  263. final ObjectReader r = repo.getObjectDatabase().newReader();
  264. try {
  265. while (startWalk.next()) {
  266. final ObjectId blobId = startWalk.getObjectId(0);
  267. final FileMode mode = startWalk.getFileMode(0);
  268. editor.add(new PathEdit(startWalk.getPathString()) {
  269. public void apply(DirCacheEntry ent) {
  270. ent.setObjectId(blobId);
  271. ent.setFileMode(mode);
  272. try {
  273. DirCacheCheckout.checkoutEntry(repo, new File(
  274. workTree, ent.getPathString()), ent, r);
  275. } catch (IOException e) {
  276. throw new JGitInternalException(
  277. MessageFormat.format(
  278. JGitText.get().checkoutConflictWithFile,
  279. ent.getPathString()), e);
  280. }
  281. }
  282. });
  283. }
  284. editor.commit();
  285. } finally {
  286. startWalk.release();
  287. r.release();
  288. }
  289. } finally {
  290. dc.unlock();
  291. revWalk.release();
  292. }
  293. return this;
  294. }
  295. private ObjectId getStartPoint() throws AmbiguousObjectException,
  296. RefNotFoundException, IOException {
  297. if (startCommit != null)
  298. return startCommit.getId();
  299. ObjectId result = null;
  300. try {
  301. result = repo.resolve((startPoint == null) ? Constants.HEAD
  302. : startPoint);
  303. } catch (AmbiguousObjectException e) {
  304. throw e;
  305. }
  306. if (result == null)
  307. throw new RefNotFoundException(MessageFormat.format(
  308. JGitText.get().refNotResolved,
  309. startPoint != null ? startPoint : Constants.HEAD));
  310. return result;
  311. }
  312. private void processOptions() throws InvalidRefNameException {
  313. if ((!checkoutAllPaths && paths.isEmpty())
  314. && (name == null || !Repository
  315. .isValidRefName(Constants.R_HEADS + name)))
  316. throw new InvalidRefNameException(MessageFormat.format(JGitText
  317. .get().branchNameInvalid, name == null ? "<null>" : name));
  318. }
  319. /**
  320. * @param name
  321. * the name of the new branch
  322. * @return this instance
  323. */
  324. public CheckoutCommand setName(String name) {
  325. checkCallable();
  326. this.name = name;
  327. return this;
  328. }
  329. /**
  330. * @param createBranch
  331. * if <code>true</code> a branch will be created as part of the
  332. * checkout and set to the specified start point
  333. * @return this instance
  334. */
  335. public CheckoutCommand setCreateBranch(boolean createBranch) {
  336. checkCallable();
  337. this.createBranch = createBranch;
  338. return this;
  339. }
  340. /**
  341. * @param force
  342. * if <code>true</code> and the branch with the given name
  343. * already exists, the start-point of an existing branch will be
  344. * set to a new start-point; if false, the existing branch will
  345. * not be changed
  346. * @return this instance
  347. */
  348. public CheckoutCommand setForce(boolean force) {
  349. checkCallable();
  350. this.force = force;
  351. return this;
  352. }
  353. /**
  354. * @param startPoint
  355. * corresponds to the start-point option; if <code>null</code>,
  356. * the current HEAD will be used
  357. * @return this instance
  358. */
  359. public CheckoutCommand setStartPoint(String startPoint) {
  360. checkCallable();
  361. this.startPoint = startPoint;
  362. this.startCommit = null;
  363. return this;
  364. }
  365. /**
  366. * @param startCommit
  367. * corresponds to the start-point option; if <code>null</code>,
  368. * the current HEAD will be used
  369. * @return this instance
  370. */
  371. public CheckoutCommand setStartPoint(RevCommit startCommit) {
  372. checkCallable();
  373. this.startCommit = startCommit;
  374. this.startPoint = null;
  375. return this;
  376. }
  377. /**
  378. * @param mode
  379. * corresponds to the --track/--no-track options; may be
  380. * <code>null</code>
  381. * @return this instance
  382. */
  383. public CheckoutCommand setUpstreamMode(
  384. CreateBranchCommand.SetupUpstreamMode mode) {
  385. checkCallable();
  386. this.upstreamMode = mode;
  387. return this;
  388. }
  389. /**
  390. * @return the result
  391. */
  392. public CheckoutResult getResult() {
  393. if (status == null)
  394. return CheckoutResult.NOT_TRIED_RESULT;
  395. return status;
  396. }
  397. }