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

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