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.

Branch.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. /*
  2. * Copyright (C) 2007-2008, Charles O'Farrell <charleso@charleso.org>
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.pgm;
  44. import java.io.IOException;
  45. import java.text.MessageFormat;
  46. import java.util.Collection;
  47. import java.util.LinkedHashMap;
  48. import java.util.List;
  49. import java.util.Map;
  50. import java.util.Map.Entry;
  51. import org.eclipse.jgit.api.Git;
  52. import org.eclipse.jgit.api.ListBranchCommand;
  53. import org.eclipse.jgit.api.ListBranchCommand.ListMode;
  54. import org.eclipse.jgit.lib.Constants;
  55. import org.eclipse.jgit.lib.ObjectId;
  56. import org.eclipse.jgit.lib.ObjectReader;
  57. import org.eclipse.jgit.lib.Ref;
  58. import org.eclipse.jgit.lib.RefComparator;
  59. import org.eclipse.jgit.lib.RefRename;
  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.pgm.internal.CLIText;
  64. import org.eclipse.jgit.pgm.opt.OptionWithValuesListHandler;
  65. import org.eclipse.jgit.revwalk.RevWalk;
  66. import org.kohsuke.args4j.Argument;
  67. import org.kohsuke.args4j.Option;
  68. @Command(common = true, usage = "usage_listCreateOrDeleteBranches")
  69. class Branch extends TextBuiltin {
  70. private String otherBranch;
  71. private boolean createForce;
  72. private boolean rename;
  73. @Option(name = "--remote", aliases = { "-r" }, usage = "usage_actOnRemoteTrackingBranches")
  74. private boolean remote = false;
  75. @Option(name = "--all", aliases = { "-a" }, usage = "usage_listBothRemoteTrackingAndLocalBranches")
  76. private boolean all = false;
  77. @Option(name = "--contains", metaVar = "metaVar_commitish", usage = "usage_printOnlyBranchesThatContainTheCommit")
  78. private String containsCommitish;
  79. private List<String> delete;
  80. @Option(name = "--delete", aliases = {
  81. "-d" }, metaVar = "metaVar_branchNames", usage = "usage_deleteFullyMergedBranch", handler = OptionWithValuesListHandler.class)
  82. public void delete(List<String> names) {
  83. if (names.isEmpty()) {
  84. throw die(CLIText.get().branchNameRequired);
  85. }
  86. delete = names;
  87. }
  88. private List<String> deleteForce;
  89. @Option(name = "--delete-force", aliases = {
  90. "-D" }, metaVar = "metaVar_branchNames", usage = "usage_deleteBranchEvenIfNotMerged", handler = OptionWithValuesListHandler.class)
  91. public void deleteForce(List<String> names) {
  92. if (names.isEmpty()) {
  93. throw die(CLIText.get().branchNameRequired);
  94. }
  95. deleteForce = names;
  96. }
  97. @Option(name = "--create-force", aliases = {
  98. "-f" }, metaVar = "metaVar_branchAndStartPoint", usage = "usage_forceCreateBranchEvenExists", handler = OptionWithValuesListHandler.class)
  99. public void createForce(List<String> branchAndStartPoint) {
  100. createForce = true;
  101. if (branchAndStartPoint.isEmpty()) {
  102. throw die(CLIText.get().branchNameRequired);
  103. }
  104. if (branchAndStartPoint.size() > 2) {
  105. throw die(CLIText.get().tooManyRefsGiven);
  106. }
  107. if (branchAndStartPoint.size() == 1) {
  108. branch = branchAndStartPoint.get(0);
  109. } else {
  110. branch = branchAndStartPoint.get(0);
  111. otherBranch = branchAndStartPoint.get(1);
  112. }
  113. }
  114. @Option(name = "--move", aliases = {
  115. "-m" }, metaVar = "metaVar_oldNewBranchNames", usage = "usage_moveRenameABranch", handler = OptionWithValuesListHandler.class)
  116. public void moveRename(List<String> currentAndNew) {
  117. rename = true;
  118. if (currentAndNew.isEmpty()) {
  119. throw die(CLIText.get().branchNameRequired);
  120. }
  121. if (currentAndNew.size() > 2) {
  122. throw die(CLIText.get().tooManyRefsGiven);
  123. }
  124. if (currentAndNew.size() == 1) {
  125. branch = currentAndNew.get(0);
  126. } else {
  127. branch = currentAndNew.get(0);
  128. otherBranch = currentAndNew.get(1);
  129. }
  130. }
  131. @Option(name = "--verbose", aliases = { "-v" }, usage = "usage_beVerbose")
  132. private boolean verbose = false;
  133. @Argument(metaVar = "metaVar_name")
  134. private String branch;
  135. private final Map<String, Ref> printRefs = new LinkedHashMap<>();
  136. /** Only set for verbose branch listing at-the-moment */
  137. private RevWalk rw;
  138. private int maxNameLength;
  139. @Override
  140. protected void run() throws Exception {
  141. if (delete != null || deleteForce != null) {
  142. if (delete != null) {
  143. delete(delete, false);
  144. }
  145. if (deleteForce != null) {
  146. delete(deleteForce, true);
  147. }
  148. } else {
  149. if (rename) {
  150. String src, dst;
  151. if (otherBranch == null) {
  152. final Ref head = db.exactRef(Constants.HEAD);
  153. if (head != null && head.isSymbolic()) {
  154. src = head.getLeaf().getName();
  155. } else {
  156. throw die(CLIText.get().cannotRenameDetachedHEAD);
  157. }
  158. dst = branch;
  159. } else {
  160. src = branch;
  161. final Ref old = db.findRef(src);
  162. if (old == null)
  163. throw die(MessageFormat.format(CLIText.get().doesNotExist, src));
  164. if (!old.getName().startsWith(Constants.R_HEADS))
  165. throw die(MessageFormat.format(CLIText.get().notABranch, src));
  166. src = old.getName();
  167. dst = otherBranch;
  168. }
  169. if (!dst.startsWith(Constants.R_HEADS))
  170. dst = Constants.R_HEADS + dst;
  171. if (!Repository.isValidRefName(dst))
  172. throw die(MessageFormat.format(CLIText.get().notAValidRefName, dst));
  173. RefRename r = db.renameRef(src, dst);
  174. if (r.rename() != Result.RENAMED)
  175. throw die(MessageFormat.format(CLIText.get().cannotBeRenamed, src));
  176. } else if (createForce || branch != null) {
  177. String newHead = branch;
  178. String startBranch;
  179. if (createForce) {
  180. startBranch = otherBranch;
  181. } else {
  182. startBranch = Constants.HEAD;
  183. }
  184. Ref startRef = db.findRef(startBranch);
  185. ObjectId startAt = db.resolve(startBranch + "^0"); //$NON-NLS-1$
  186. if (startRef != null) {
  187. startBranch = startRef.getName();
  188. } else if (startAt != null) {
  189. startBranch = startAt.name();
  190. } else {
  191. throw die(MessageFormat.format(
  192. CLIText.get().notAValidCommitName, startBranch));
  193. }
  194. startBranch = Repository.shortenRefName(startBranch);
  195. String newRefName = newHead;
  196. if (!newRefName.startsWith(Constants.R_HEADS)) {
  197. newRefName = Constants.R_HEADS + newRefName;
  198. }
  199. if (!Repository.isValidRefName(newRefName)) {
  200. throw die(MessageFormat.format(CLIText.get().notAValidRefName, newRefName));
  201. }
  202. if (!createForce && db.resolve(newRefName) != null) {
  203. throw die(MessageFormat.format(CLIText.get().branchAlreadyExists, newHead));
  204. }
  205. RefUpdate updateRef = db.updateRef(newRefName);
  206. updateRef.setNewObjectId(startAt);
  207. updateRef.setForceUpdate(createForce);
  208. updateRef.setRefLogMessage(MessageFormat.format(CLIText.get().branchCreatedFrom, startBranch), false);
  209. Result update = updateRef.update();
  210. if (update == Result.REJECTED) {
  211. throw die(MessageFormat.format(CLIText.get().couldNotCreateBranch, newHead, update.toString()));
  212. }
  213. } else {
  214. if (verbose) {
  215. rw = new RevWalk(db);
  216. }
  217. list();
  218. }
  219. }
  220. }
  221. private void list() throws Exception {
  222. Ref head = db.exactRef(Constants.HEAD);
  223. // This can happen if HEAD is stillborn
  224. if (head != null) {
  225. String current = head.getLeaf().getName();
  226. try (Git git = new Git(db)) {
  227. ListBranchCommand command = git.branchList();
  228. if (all)
  229. command.setListMode(ListMode.ALL);
  230. else if (remote)
  231. command.setListMode(ListMode.REMOTE);
  232. if (containsCommitish != null)
  233. command.setContains(containsCommitish);
  234. List<Ref> refs = command.call();
  235. for (Ref ref : refs) {
  236. if (ref.getName().equals(Constants.HEAD))
  237. addRef("(no branch)", head); //$NON-NLS-1$
  238. }
  239. addRefs(refs, Constants.R_HEADS);
  240. addRefs(refs, Constants.R_REMOTES);
  241. try (ObjectReader reader = db.newObjectReader()) {
  242. for (final Entry<String, Ref> e : printRefs.entrySet()) {
  243. final Ref ref = e.getValue();
  244. printHead(reader, e.getKey(),
  245. current.equals(ref.getName()), ref);
  246. }
  247. }
  248. }
  249. }
  250. }
  251. private void addRefs(final Collection<Ref> refs, final String prefix) {
  252. for (final Ref ref : RefComparator.sort(refs)) {
  253. final String name = ref.getName();
  254. if (name.startsWith(prefix))
  255. addRef(name.substring(name.indexOf('/', 5) + 1), ref);
  256. }
  257. }
  258. private void addRef(final String name, final Ref ref) {
  259. printRefs.put(name, ref);
  260. maxNameLength = Math.max(maxNameLength, name.length());
  261. }
  262. private void printHead(final ObjectReader reader, final String ref,
  263. final boolean isCurrent, final Ref refObj) throws Exception {
  264. outw.print(isCurrent ? '*' : ' ');
  265. outw.print(' ');
  266. outw.print(ref);
  267. if (verbose) {
  268. final int spaces = maxNameLength - ref.length() + 1;
  269. outw.format("%" + spaces + "s", ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
  270. final ObjectId objectId = refObj.getObjectId();
  271. outw.print(reader.abbreviate(objectId).name());
  272. outw.print(' ');
  273. outw.print(rw.parseCommit(objectId).getShortMessage());
  274. }
  275. outw.println();
  276. }
  277. private void delete(List<String> branches, boolean force)
  278. throws IOException {
  279. String current = db.getBranch();
  280. ObjectId head = db.resolve(Constants.HEAD);
  281. for (String b : branches) {
  282. if (b.equals(current)) {
  283. throw die(MessageFormat.format(CLIText.get().cannotDeleteTheBranchWhichYouAreCurrentlyOn, b));
  284. }
  285. RefUpdate update = db.updateRef((remote ? Constants.R_REMOTES
  286. : Constants.R_HEADS)
  287. + b);
  288. update.setNewObjectId(head);
  289. update.setForceUpdate(force || remote);
  290. Result result = update.delete();
  291. if (result == Result.REJECTED) {
  292. throw die(MessageFormat.format(CLIText.get().branchIsNotAnAncestorOfYourCurrentHEAD, b));
  293. } else if (result == Result.NEW)
  294. throw die(MessageFormat.format(CLIText.get().branchNotFound, b));
  295. if (remote)
  296. outw.println(MessageFormat.format(CLIText.get().deletedRemoteBranch, b));
  297. else if (verbose)
  298. outw.println(MessageFormat.format(CLIText.get().deletedBranch, b));
  299. }
  300. }
  301. }