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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. RevWalk revWalk = new RevWalk(repo);
  117. try {
  118. Ref refToCheck = repo.getRef(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().refAlreadyExists, name));
  124. ObjectId startAt = getStartPoint();
  125. String startPointFullName = null;
  126. if (startPoint != null) {
  127. Ref baseRef = repo.getRef(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 = "";
  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(startPoint));
  142. baseCommit = commit.getShortMessage();
  143. }
  144. if (exists)
  145. refLogMessage = "branch: Reset start-point to commit "
  146. + baseCommit;
  147. else
  148. refLogMessage = "branch: Created from commit " + baseCommit;
  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 "
  154. + startPointFullName; // TODO
  155. else
  156. refLogMessage = "branch: Created from branch " + baseBranch;
  157. } else {
  158. startAt = revWalk.peel(revWalk.parseAny(startAt));
  159. if (exists)
  160. refLogMessage = "branch: Reset start-point to tag "
  161. + startPointFullName;
  162. else
  163. refLogMessage = "branch: Created from tag "
  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.getRef(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)) {
  216. doConfigure = false;
  217. } else if ("always".equals(autosetupflag)) {
  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[] tokens = baseBranch.split("/", 4);
  228. boolean isRemote = tokens[1].equals("remotes");
  229. if (isRemote) {
  230. // refs/remotes/<remote name>/<branch>
  231. String remoteName = tokens[2];
  232. String branchName = tokens[3];
  233. config
  234. .setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  235. name, ConfigConstants.CONFIG_KEY_REMOTE,
  236. remoteName);
  237. config.setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  238. name, ConfigConstants.CONFIG_KEY_MERGE,
  239. Constants.R_HEADS + branchName);
  240. } else {
  241. // set "." as remote
  242. config.setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  243. name, ConfigConstants.CONFIG_KEY_REMOTE, ".");
  244. config.setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  245. name, ConfigConstants.CONFIG_KEY_MERGE, baseBranch);
  246. }
  247. config.save();
  248. }
  249. return result;
  250. } catch (IOException ioe) {
  251. throw new JGitInternalException(ioe.getMessage(), ioe);
  252. } finally {
  253. revWalk.release();
  254. }
  255. }
  256. private ObjectId getStartPoint() throws AmbiguousObjectException,
  257. RefNotFoundException, IOException {
  258. if (startCommit != null)
  259. return startCommit.getId();
  260. ObjectId result = null;
  261. try {
  262. result = repo.resolve((startPoint == null) ? Constants.HEAD
  263. : startPoint);
  264. } catch (AmbiguousObjectException e) {
  265. throw e;
  266. }
  267. if (result == null)
  268. throw new RefNotFoundException(MessageFormat.format(
  269. JGitText.get().refNotResolved,
  270. startPoint != null ? startPoint : Constants.HEAD));
  271. return result;
  272. }
  273. private void processOptions() throws InvalidRefNameException {
  274. if (name == null
  275. || !Repository.isValidRefName(Constants.R_HEADS + name))
  276. throw new InvalidRefNameException(MessageFormat.format(JGitText
  277. .get().branchNameInvalid, name == null ? "<null>" : name));
  278. }
  279. /**
  280. * @param name
  281. * the name of the new branch
  282. * @return this instance
  283. */
  284. public CreateBranchCommand setName(String name) {
  285. checkCallable();
  286. this.name = name;
  287. return this;
  288. }
  289. /**
  290. * @param force
  291. * if <code>true</code> and the branch with the given name
  292. * already exists, the start-point of an existing branch will be
  293. * set to a new start-point; if false, the existing branch will
  294. * not be changed
  295. * @return this instance
  296. */
  297. public CreateBranchCommand setForce(boolean force) {
  298. checkCallable();
  299. this.force = force;
  300. return this;
  301. }
  302. /**
  303. * @param startPoint
  304. * corresponds to the start-point option; if <code>null</code>,
  305. * the current HEAD will be used
  306. * @return this instance
  307. */
  308. public CreateBranchCommand setStartPoint(String startPoint) {
  309. checkCallable();
  310. this.startPoint = startPoint;
  311. this.startCommit = null;
  312. return this;
  313. }
  314. /**
  315. * @param startPoint
  316. * corresponds to the start-point option; if <code>null</code>,
  317. * the current HEAD will be used
  318. * @return this instance
  319. */
  320. public CreateBranchCommand setStartPoint(RevCommit startPoint) {
  321. checkCallable();
  322. this.startCommit = startPoint;
  323. this.startPoint = null;
  324. return this;
  325. }
  326. /**
  327. * @param mode
  328. * corresponds to the --track/--no-track/--set-upstream options;
  329. * may be <code>null</code>
  330. * @return this instance
  331. */
  332. public CreateBranchCommand setUpstreamMode(SetupUpstreamMode mode) {
  333. checkCallable();
  334. this.upstreamMode = mode;
  335. return this;
  336. }
  337. }