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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. try (RevWalk revWalk = new RevWalk(repo)) {
  118. Ref refToCheck = repo.findRef(name);
  119. boolean exists = refToCheck != null
  120. && refToCheck.getName().startsWith(Constants.R_HEADS);
  121. if (!force && exists)
  122. throw new RefAlreadyExistsException(MessageFormat.format(
  123. JGitText.get().refAlreadyExists1, name));
  124. ObjectId startAt = getStartPointObjectId();
  125. String startPointFullName = null;
  126. if (startPoint != null) {
  127. Ref baseRef = repo.findRef(startPoint);
  128. if (baseRef != null)
  129. startPointFullName = baseRef.getName();
  130. }
  131. // determine whether we are based on a commit,
  132. // a branch, or a tag and compose the reflog message
  133. String refLogMessage;
  134. String baseBranch = ""; //$NON-NLS-1$
  135. if (startPointFullName == null) {
  136. String baseCommit;
  137. if (startCommit != null)
  138. baseCommit = startCommit.getShortMessage();
  139. else {
  140. RevCommit commit = revWalk.parseCommit(repo
  141. .resolve(getStartPointOrHead()));
  142. baseCommit = commit.getShortMessage();
  143. }
  144. if (exists)
  145. refLogMessage = "branch: Reset start-point to commit " //$NON-NLS-1$
  146. + baseCommit;
  147. else
  148. refLogMessage = "branch: Created from commit " + baseCommit; //$NON-NLS-1$
  149. } else if (startPointFullName.startsWith(Constants.R_HEADS)
  150. || startPointFullName.startsWith(Constants.R_REMOTES)) {
  151. baseBranch = startPointFullName;
  152. if (exists)
  153. refLogMessage = "branch: Reset start-point to branch " //$NON-NLS-1$
  154. + startPointFullName; // TODO
  155. else
  156. refLogMessage = "branch: Created from branch " + baseBranch; //$NON-NLS-1$
  157. } else {
  158. startAt = revWalk.peel(revWalk.parseAny(startAt));
  159. if (exists)
  160. refLogMessage = "branch: Reset start-point to tag " //$NON-NLS-1$
  161. + startPointFullName;
  162. else
  163. refLogMessage = "branch: Created from tag " //$NON-NLS-1$
  164. + startPointFullName;
  165. }
  166. RefUpdate updateRef = repo.updateRef(Constants.R_HEADS + name);
  167. updateRef.setNewObjectId(startAt);
  168. updateRef.setRefLogMessage(refLogMessage, false);
  169. Result updateResult;
  170. if (exists && force)
  171. updateResult = updateRef.forceUpdate();
  172. else
  173. updateResult = updateRef.update();
  174. setCallable(false);
  175. boolean ok = false;
  176. switch (updateResult) {
  177. case NEW:
  178. ok = !exists;
  179. break;
  180. case NO_CHANGE:
  181. case FAST_FORWARD:
  182. case FORCED:
  183. ok = exists;
  184. break;
  185. default:
  186. break;
  187. }
  188. if (!ok)
  189. throw new JGitInternalException(MessageFormat.format(JGitText
  190. .get().createBranchUnexpectedResult, updateResult
  191. .name()));
  192. Ref result = repo.findRef(name);
  193. if (result == null)
  194. throw new JGitInternalException(
  195. JGitText.get().createBranchFailedUnknownReason);
  196. if (baseBranch.length() == 0) {
  197. return result;
  198. }
  199. // if we are based on another branch, see
  200. // if we need to configure upstream configuration: first check
  201. // whether the setting was done explicitly
  202. boolean doConfigure;
  203. if (upstreamMode == SetupUpstreamMode.SET_UPSTREAM
  204. || upstreamMode == SetupUpstreamMode.TRACK)
  205. // explicitly set to configure
  206. doConfigure = true;
  207. else if (upstreamMode == SetupUpstreamMode.NOTRACK)
  208. // explicitly set to not configure
  209. doConfigure = false;
  210. else {
  211. // if there was no explicit setting, check the configuration
  212. String autosetupflag = repo.getConfig().getString(
  213. ConfigConstants.CONFIG_BRANCH_SECTION, null,
  214. ConfigConstants.CONFIG_KEY_AUTOSETUPMERGE);
  215. if ("false".equals(autosetupflag)) { //$NON-NLS-1$
  216. doConfigure = false;
  217. } else if ("always".equals(autosetupflag)) { //$NON-NLS-1$
  218. doConfigure = true;
  219. } else {
  220. // in this case, the default is to configure
  221. // only in case the base branch was a remote branch
  222. doConfigure = baseBranch.startsWith(Constants.R_REMOTES);
  223. }
  224. }
  225. if (doConfigure) {
  226. StoredConfig config = repo.getConfig();
  227. String remoteName = repo.getRemoteName(baseBranch);
  228. if (remoteName != null) {
  229. String branchName = repo
  230. .shortenRemoteBranchName(baseBranch);
  231. config
  232. .setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  233. name, ConfigConstants.CONFIG_KEY_REMOTE,
  234. remoteName);
  235. config.setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  236. name, ConfigConstants.CONFIG_KEY_MERGE,
  237. Constants.R_HEADS + branchName);
  238. } else {
  239. // set "." as remote
  240. config.setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  241. name, ConfigConstants.CONFIG_KEY_REMOTE, "."); //$NON-NLS-1$
  242. config.setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  243. name, ConfigConstants.CONFIG_KEY_MERGE, baseBranch);
  244. }
  245. config.save();
  246. }
  247. return result;
  248. } catch (IOException ioe) {
  249. throw new JGitInternalException(ioe.getMessage(), ioe);
  250. }
  251. }
  252. private ObjectId getStartPointObjectId() throws AmbiguousObjectException,
  253. RefNotFoundException, IOException {
  254. if (startCommit != null)
  255. return startCommit.getId();
  256. String startPointOrHead = getStartPointOrHead();
  257. ObjectId result = repo.resolve(startPointOrHead);
  258. if (result == null)
  259. throw new RefNotFoundException(MessageFormat.format(
  260. JGitText.get().refNotResolved, startPointOrHead));
  261. return result;
  262. }
  263. private String getStartPointOrHead() {
  264. return startPoint != null ? startPoint : Constants.HEAD;
  265. }
  266. private void processOptions() throws InvalidRefNameException {
  267. if (name == null
  268. || !Repository.isValidRefName(Constants.R_HEADS + name))
  269. throw new InvalidRefNameException(MessageFormat.format(JGitText
  270. .get().branchNameInvalid, name == null ? "<null>" : name)); //$NON-NLS-1$
  271. }
  272. /**
  273. * @param name
  274. * the name of the new branch
  275. * @return this instance
  276. */
  277. public CreateBranchCommand setName(String name) {
  278. checkCallable();
  279. this.name = name;
  280. return this;
  281. }
  282. /**
  283. * @param force
  284. * if <code>true</code> and the branch with the given name
  285. * already exists, the start-point of an existing branch will be
  286. * set to a new start-point; if false, the existing branch will
  287. * not be changed
  288. * @return this instance
  289. */
  290. public CreateBranchCommand setForce(boolean force) {
  291. checkCallable();
  292. this.force = force;
  293. return this;
  294. }
  295. /**
  296. * @param startPoint
  297. * corresponds to the start-point option; if <code>null</code>,
  298. * the current HEAD will be used
  299. * @return this instance
  300. */
  301. public CreateBranchCommand setStartPoint(String startPoint) {
  302. checkCallable();
  303. this.startPoint = startPoint;
  304. this.startCommit = null;
  305. return this;
  306. }
  307. /**
  308. * @param startPoint
  309. * corresponds to the start-point option; if <code>null</code>,
  310. * the current HEAD will be used
  311. * @return this instance
  312. */
  313. public CreateBranchCommand setStartPoint(RevCommit startPoint) {
  314. checkCallable();
  315. this.startCommit = startPoint;
  316. this.startPoint = null;
  317. return this;
  318. }
  319. /**
  320. * @param mode
  321. * corresponds to the --track/--no-track/--set-upstream options;
  322. * may be <code>null</code>
  323. * @return this instance
  324. */
  325. public CreateBranchCommand setUpstreamMode(SetupUpstreamMode mode) {
  326. checkCallable();
  327. this.upstreamMode = mode;
  328. return this;
  329. }
  330. }