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.

CreateBranchCommand.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. /*
  2. * Copyright (C) 2010, Mathias Kinzler <mathias.kinzler@sap.com>
  3. * Copyright (C) 2010, Chris Aniszczyk <caniszczyk@gmail.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.IOException;
  46. import java.text.MessageFormat;
  47. import org.eclipse.jgit.api.errors.GitAPIException;
  48. import org.eclipse.jgit.api.errors.InvalidRefNameException;
  49. import org.eclipse.jgit.api.errors.JGitInternalException;
  50. import org.eclipse.jgit.api.errors.RefAlreadyExistsException;
  51. import org.eclipse.jgit.api.errors.RefNotFoundException;
  52. import org.eclipse.jgit.errors.AmbiguousObjectException;
  53. import org.eclipse.jgit.internal.JGitText;
  54. import org.eclipse.jgit.lib.ConfigConstants;
  55. import org.eclipse.jgit.lib.Constants;
  56. import org.eclipse.jgit.lib.ObjectId;
  57. import org.eclipse.jgit.lib.Ref;
  58. import org.eclipse.jgit.lib.RefUpdate;
  59. import org.eclipse.jgit.lib.RefUpdate.Result;
  60. import org.eclipse.jgit.lib.Repository;
  61. import org.eclipse.jgit.lib.StoredConfig;
  62. import org.eclipse.jgit.revwalk.RevCommit;
  63. import org.eclipse.jgit.revwalk.RevWalk;
  64. /**
  65. * Used to create a local branch.
  66. *
  67. * @see <a
  68. * href="http://www.kernel.org/pub/software/scm/git/docs/git-branch.html"
  69. * >Git documentation about Branch</a>
  70. */
  71. public class CreateBranchCommand extends GitCommand<Ref> {
  72. private String name;
  73. private boolean force = false;
  74. private SetupUpstreamMode upstreamMode;
  75. private String startPoint = Constants.HEAD;
  76. private RevCommit startCommit;
  77. /**
  78. * The modes available for setting up the upstream configuration
  79. * (corresponding to the --set-upstream, --track, --no-track options
  80. *
  81. */
  82. public enum SetupUpstreamMode {
  83. /**
  84. * Corresponds to the --track option
  85. */
  86. TRACK,
  87. /**
  88. * Corresponds to the --no-track option
  89. */
  90. NOTRACK,
  91. /**
  92. * Corresponds to the --set-upstream option
  93. */
  94. SET_UPSTREAM;
  95. }
  96. /**
  97. * @param repo
  98. */
  99. protected CreateBranchCommand(Repository repo) {
  100. super(repo);
  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 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 GitAPIException, RefAlreadyExistsException,
  114. RefNotFoundException, InvalidRefNameException {
  115. checkCallable();
  116. processOptions();
  117. RevWalk revWalk = new RevWalk(repo);
  118. try {
  119. Ref refToCheck = repo.getRef(name);
  120. boolean exists = refToCheck != null
  121. && refToCheck.getName().startsWith(Constants.R_HEADS);
  122. if (!force && exists)
  123. throw new RefAlreadyExistsException(MessageFormat.format(
  124. JGitText.get().refAlreadyExists1, name));
  125. ObjectId startAt = getStartPoint();
  126. String startPointFullName = null;
  127. if (startPoint != null) {
  128. Ref baseRef = repo.getRef(startPoint);
  129. if (baseRef != null)
  130. startPointFullName = baseRef.getName();
  131. }
  132. // determine whether we are based on a commit,
  133. // a branch, or a tag and compose the reflog message
  134. String refLogMessage;
  135. String baseBranch = ""; //$NON-NLS-1$
  136. if (startPointFullName == null) {
  137. String baseCommit;
  138. if (startCommit != null)
  139. baseCommit = startCommit.getShortMessage();
  140. else {
  141. RevCommit commit = revWalk.parseCommit(repo
  142. .resolve(startPoint));
  143. baseCommit = commit.getShortMessage();
  144. }
  145. if (exists)
  146. refLogMessage = "branch: Reset start-point to commit " //$NON-NLS-1$
  147. + baseCommit;
  148. else
  149. refLogMessage = "branch: Created from commit " + baseCommit; //$NON-NLS-1$
  150. } else if (startPointFullName.startsWith(Constants.R_HEADS)
  151. || startPointFullName.startsWith(Constants.R_REMOTES)) {
  152. baseBranch = startPointFullName;
  153. if (exists)
  154. refLogMessage = "branch: Reset start-point to branch " //$NON-NLS-1$
  155. + startPointFullName; // TODO
  156. else
  157. refLogMessage = "branch: Created from branch " + baseBranch; //$NON-NLS-1$
  158. } else {
  159. startAt = revWalk.peel(revWalk.parseAny(startAt));
  160. if (exists)
  161. refLogMessage = "branch: Reset start-point to tag " //$NON-NLS-1$
  162. + startPointFullName;
  163. else
  164. refLogMessage = "branch: Created from tag " //$NON-NLS-1$
  165. + startPointFullName;
  166. }
  167. RefUpdate updateRef = repo.updateRef(Constants.R_HEADS + name);
  168. updateRef.setNewObjectId(startAt);
  169. updateRef.setRefLogMessage(refLogMessage, false);
  170. Result updateResult;
  171. if (exists && force)
  172. updateResult = updateRef.forceUpdate();
  173. else
  174. updateResult = updateRef.update();
  175. setCallable(false);
  176. boolean ok = false;
  177. switch (updateResult) {
  178. case NEW:
  179. ok = !exists;
  180. break;
  181. case NO_CHANGE:
  182. case FAST_FORWARD:
  183. case FORCED:
  184. ok = exists;
  185. break;
  186. default:
  187. break;
  188. }
  189. if (!ok)
  190. throw new JGitInternalException(MessageFormat.format(JGitText
  191. .get().createBranchUnexpectedResult, updateResult
  192. .name()));
  193. Ref result = repo.getRef(name);
  194. if (result == null)
  195. throw new JGitInternalException(
  196. JGitText.get().createBranchFailedUnknownReason);
  197. if (baseBranch.length() == 0) {
  198. return result;
  199. }
  200. // if we are based on another branch, see
  201. // if we need to configure upstream configuration: first check
  202. // whether the setting was done explicitly
  203. boolean doConfigure;
  204. if (upstreamMode == SetupUpstreamMode.SET_UPSTREAM
  205. || upstreamMode == SetupUpstreamMode.TRACK)
  206. // explicitly set to configure
  207. doConfigure = true;
  208. else if (upstreamMode == SetupUpstreamMode.NOTRACK)
  209. // explicitly set to not configure
  210. doConfigure = false;
  211. else {
  212. // if there was no explicit setting, check the configuration
  213. String autosetupflag = repo.getConfig().getString(
  214. ConfigConstants.CONFIG_BRANCH_SECTION, null,
  215. ConfigConstants.CONFIG_KEY_AUTOSETUPMERGE);
  216. if ("false".equals(autosetupflag)) { //$NON-NLS-1$
  217. doConfigure = false;
  218. } else if ("always".equals(autosetupflag)) { //$NON-NLS-1$
  219. doConfigure = true;
  220. } else {
  221. // in this case, the default is to configure
  222. // only in case the base branch was a remote branch
  223. doConfigure = baseBranch.startsWith(Constants.R_REMOTES);
  224. }
  225. }
  226. if (doConfigure) {
  227. StoredConfig config = repo.getConfig();
  228. String[] tokens = baseBranch.split("/", 4); //$NON-NLS-1$
  229. boolean isRemote = tokens[1].equals("remotes"); //$NON-NLS-1$
  230. if (isRemote) {
  231. // refs/remotes/<remote name>/<branch>
  232. String remoteName = tokens[2];
  233. String branchName = tokens[3];
  234. config
  235. .setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  236. name, ConfigConstants.CONFIG_KEY_REMOTE,
  237. remoteName);
  238. config.setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  239. name, ConfigConstants.CONFIG_KEY_MERGE,
  240. Constants.R_HEADS + branchName);
  241. } else {
  242. // set "." as remote
  243. config.setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  244. name, ConfigConstants.CONFIG_KEY_REMOTE, "."); //$NON-NLS-1$
  245. config.setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  246. name, ConfigConstants.CONFIG_KEY_MERGE, baseBranch);
  247. }
  248. config.save();
  249. }
  250. return result;
  251. } catch (IOException ioe) {
  252. throw new JGitInternalException(ioe.getMessage(), ioe);
  253. } finally {
  254. revWalk.release();
  255. }
  256. }
  257. private ObjectId getStartPoint() throws AmbiguousObjectException,
  258. RefNotFoundException, IOException {
  259. if (startCommit != null)
  260. return startCommit.getId();
  261. ObjectId result = null;
  262. try {
  263. result = repo.resolve((startPoint == null) ? Constants.HEAD
  264. : startPoint);
  265. } catch (AmbiguousObjectException e) {
  266. throw e;
  267. }
  268. if (result == null)
  269. throw new RefNotFoundException(MessageFormat.format(
  270. JGitText.get().refNotResolved,
  271. startPoint != null ? startPoint : Constants.HEAD));
  272. return result;
  273. }
  274. private void processOptions() throws InvalidRefNameException {
  275. if (name == null
  276. || !Repository.isValidRefName(Constants.R_HEADS + name))
  277. throw new InvalidRefNameException(MessageFormat.format(JGitText
  278. .get().branchNameInvalid, name == null ? "<null>" : name)); //$NON-NLS-1$
  279. }
  280. /**
  281. * @param name
  282. * the name of the new branch
  283. * @return this instance
  284. */
  285. public CreateBranchCommand setName(String name) {
  286. checkCallable();
  287. this.name = name;
  288. return this;
  289. }
  290. /**
  291. * @param force
  292. * if <code>true</code> and the branch with the given name
  293. * already exists, the start-point of an existing branch will be
  294. * set to a new start-point; if false, the existing branch will
  295. * not be changed
  296. * @return this instance
  297. */
  298. public CreateBranchCommand setForce(boolean force) {
  299. checkCallable();
  300. this.force = force;
  301. return this;
  302. }
  303. /**
  304. * @param startPoint
  305. * corresponds to the start-point option; if <code>null</code>,
  306. * the current HEAD will be used
  307. * @return this instance
  308. */
  309. public CreateBranchCommand setStartPoint(String startPoint) {
  310. checkCallable();
  311. this.startPoint = startPoint;
  312. this.startCommit = null;
  313. return this;
  314. }
  315. /**
  316. * @param startPoint
  317. * corresponds to the start-point option; if <code>null</code>,
  318. * the current HEAD will be used
  319. * @return this instance
  320. */
  321. public CreateBranchCommand setStartPoint(RevCommit startPoint) {
  322. checkCallable();
  323. this.startCommit = startPoint;
  324. this.startPoint = null;
  325. return this;
  326. }
  327. /**
  328. * @param mode
  329. * corresponds to the --track/--no-track/--set-upstream options;
  330. * may be <code>null</code>
  331. * @return this instance
  332. */
  333. public CreateBranchCommand setUpstreamMode(SetupUpstreamMode mode) {
  334. checkCallable();
  335. this.upstreamMode = mode;
  336. return this;
  337. }
  338. }