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 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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.ArrayList;
  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.lib.Constants;
  52. import org.eclipse.jgit.lib.ObjectId;
  53. import org.eclipse.jgit.lib.Ref;
  54. import org.eclipse.jgit.lib.RefComparator;
  55. import org.eclipse.jgit.lib.RefRename;
  56. import org.eclipse.jgit.lib.RefUpdate;
  57. import org.eclipse.jgit.lib.Repository;
  58. import org.eclipse.jgit.lib.RefUpdate.Result;
  59. import org.eclipse.jgit.pgm.opt.CmdLineParser;
  60. import org.eclipse.jgit.revwalk.RevWalk;
  61. import org.kohsuke.args4j.Argument;
  62. import org.kohsuke.args4j.ExampleMode;
  63. import org.kohsuke.args4j.Option;
  64. @Command(common = true, usage = "usage_listCreateOrDeleteBranches")
  65. class Branch extends TextBuiltin {
  66. @Option(name = "--remote", aliases = { "-r" }, usage = "usage_actOnRemoteTrackingBranches")
  67. private boolean remote = false;
  68. @Option(name = "--all", aliases = { "-a" }, usage = "usage_listBothRemoteTrackingAndLocalBranches")
  69. private boolean all = false;
  70. @Option(name = "--delete", aliases = { "-d" }, usage = "usage_deleteFullyMergedBranch")
  71. private boolean delete = false;
  72. @Option(name = "--delete-force", aliases = { "-D" }, usage = "usage_deleteBranchEvenIfNotMerged")
  73. private boolean deleteForce = false;
  74. @Option(name = "--create-force", aliases = { "-f" }, usage = "usage_forceCreateBranchEvenExists")
  75. private boolean createForce = false;
  76. @Option(name = "-m", usage = "usage_moveRenameABranch")
  77. private boolean rename = false;
  78. @Option(name = "--verbose", aliases = { "-v" }, usage = "usage_beVerbose")
  79. private boolean verbose = false;
  80. @Argument
  81. private List<String> branches = new ArrayList<String>();
  82. private final Map<String, Ref> printRefs = new LinkedHashMap<String, Ref>();
  83. /** Only set for verbose branch listing at-the-moment */
  84. private RevWalk rw;
  85. private int maxNameLength;
  86. @Override
  87. protected void run() throws Exception {
  88. if (delete || deleteForce)
  89. delete(deleteForce);
  90. else {
  91. if (branches.size() > 2)
  92. throw die(CLIText.get().tooManyRefsGiven + new CmdLineParser(this).printExample(ExampleMode.ALL));
  93. if (rename) {
  94. String src, dst;
  95. if (branches.size() == 1) {
  96. final Ref head = db.getRef(Constants.HEAD);
  97. if (head != null && head.isSymbolic())
  98. src = head.getLeaf().getName();
  99. else
  100. throw die(CLIText.get().cannotRenameDetachedHEAD);
  101. dst = branches.get(0);
  102. } else {
  103. src = branches.get(0);
  104. final Ref old = db.getRef(src);
  105. if (old == null)
  106. throw die(MessageFormat.format(CLIText.get().doesNotExist, src));
  107. if (!old.getName().startsWith(Constants.R_HEADS))
  108. throw die(MessageFormat.format(CLIText.get().notABranch, src));
  109. src = old.getName();
  110. dst = branches.get(1);
  111. }
  112. if (!dst.startsWith(Constants.R_HEADS))
  113. dst = Constants.R_HEADS + dst;
  114. if (!Repository.isValidRefName(dst))
  115. throw die(MessageFormat.format(CLIText.get().notAValidRefName, dst));
  116. RefRename r = db.renameRef(src, dst);
  117. if (r.rename() != Result.RENAMED)
  118. throw die(MessageFormat.format(CLIText.get().cannotBeRenamed, src));
  119. } else if (branches.size() > 0) {
  120. String newHead = branches.get(0);
  121. String startBranch;
  122. if (branches.size() == 2)
  123. startBranch = branches.get(1);
  124. else
  125. startBranch = Constants.HEAD;
  126. Ref startRef = db.getRef(startBranch);
  127. ObjectId startAt = db.resolve(startBranch + "^0");
  128. if (startRef != null)
  129. startBranch = startRef.getName();
  130. else
  131. startBranch = startAt.name();
  132. startBranch = db.shortenRefName(startBranch);
  133. String newRefName = newHead;
  134. if (!newRefName.startsWith(Constants.R_HEADS))
  135. newRefName = Constants.R_HEADS + newRefName;
  136. if (!Repository.isValidRefName(newRefName))
  137. throw die(MessageFormat.format(CLIText.get().notAValidRefName, newRefName));
  138. if (!createForce && db.resolve(newRefName) != null)
  139. throw die(MessageFormat.format(CLIText.get().branchAlreadyExists, newHead));
  140. RefUpdate updateRef = db.updateRef(newRefName);
  141. updateRef.setNewObjectId(startAt);
  142. updateRef.setForceUpdate(createForce);
  143. updateRef.setRefLogMessage(MessageFormat.format(CLIText.get().branchCreatedFrom, startBranch), false);
  144. Result update = updateRef.update();
  145. if (update == Result.REJECTED)
  146. throw die(MessageFormat.format(CLIText.get().couldNotCreateBranch, newHead, update.toString()));
  147. } else {
  148. if (verbose)
  149. rw = new RevWalk(db);
  150. list();
  151. }
  152. }
  153. }
  154. private void list() throws Exception {
  155. Map<String, Ref> refs = db.getAllRefs();
  156. Ref head = refs.get(Constants.HEAD);
  157. // This can happen if HEAD is stillborn
  158. if (head != null) {
  159. String current = head.getLeaf().getName();
  160. if (current.equals(Constants.HEAD))
  161. addRef("(no branch)", head);
  162. addRefs(refs, Constants.R_HEADS, !remote);
  163. addRefs(refs, Constants.R_REMOTES, remote);
  164. for (final Entry<String, Ref> e : printRefs.entrySet()) {
  165. final Ref ref = e.getValue();
  166. printHead(e.getKey(), current.equals(ref.getName()), ref);
  167. }
  168. }
  169. }
  170. private void addRefs(final Map<String, Ref> allRefs, final String prefix,
  171. final boolean add) {
  172. if (all || add) {
  173. for (final Ref ref : RefComparator.sort(allRefs.values())) {
  174. final String name = ref.getName();
  175. if (name.startsWith(prefix))
  176. addRef(name.substring(name.indexOf('/', 5) + 1), ref);
  177. }
  178. }
  179. }
  180. private void addRef(final String name, final Ref ref) {
  181. printRefs.put(name, ref);
  182. maxNameLength = Math.max(maxNameLength, name.length());
  183. }
  184. private void printHead(final String ref, final boolean isCurrent,
  185. final Ref refObj) throws Exception {
  186. out.print(isCurrent ? '*' : ' ');
  187. out.print(' ');
  188. out.print(ref);
  189. if (verbose) {
  190. final int spaces = maxNameLength - ref.length() + 1;
  191. out.format("%" + spaces + "s", "");
  192. final ObjectId objectId = refObj.getObjectId();
  193. out.print(objectId.abbreviate(db).name());
  194. out.print(' ');
  195. out.print(rw.parseCommit(objectId).getShortMessage());
  196. }
  197. out.println();
  198. }
  199. private void delete(boolean force) throws IOException {
  200. String current = db.getBranch();
  201. ObjectId head = db.resolve(Constants.HEAD);
  202. for (String branch : branches) {
  203. if (current.equals(branch)) {
  204. throw die(MessageFormat.format(CLIText.get().cannotDeleteTheBranchWhichYouAreCurrentlyOn, branch));
  205. }
  206. RefUpdate update = db.updateRef((remote ? Constants.R_REMOTES
  207. : Constants.R_HEADS)
  208. + branch);
  209. update.setNewObjectId(head);
  210. update.setForceUpdate(force || remote);
  211. Result result = update.delete();
  212. if (result == Result.REJECTED) {
  213. throw die(MessageFormat.format(CLIText.get().branchIsNotAnAncestorOfYourCurrentHEAD, branch));
  214. } else if (result == Result.NEW)
  215. throw die(MessageFormat.format(CLIText.get().branchNotFound, branch));
  216. if (remote)
  217. out.println(MessageFormat.format(CLIText.get().deletedRemoteBranch, branch));
  218. else if (verbose)
  219. out.println(MessageFormat.format(CLIText.get().deletedBranch, branch));
  220. }
  221. }
  222. }