Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

CreateBranchCommand.java 12KB

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