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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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.util.ArrayList;
  46. import java.util.LinkedHashMap;
  47. import java.util.List;
  48. import java.util.Map;
  49. import java.util.Map.Entry;
  50. import org.kohsuke.args4j.Argument;
  51. import org.kohsuke.args4j.ExampleMode;
  52. import org.kohsuke.args4j.Option;
  53. import org.eclipse.jgit.lib.Constants;
  54. import org.eclipse.jgit.lib.ObjectId;
  55. import org.eclipse.jgit.lib.Ref;
  56. import org.eclipse.jgit.lib.RefComparator;
  57. import org.eclipse.jgit.lib.RefUpdate;
  58. import org.eclipse.jgit.lib.Repository;
  59. import org.eclipse.jgit.lib.RefUpdate.Result;
  60. import org.eclipse.jgit.pgm.opt.CmdLineParser;
  61. import org.eclipse.jgit.revwalk.RevWalk;
  62. @Command(common = true, usage = "List, create, or delete branches")
  63. class Branch extends TextBuiltin {
  64. @Option(name = "--remote", aliases = { "-r" }, usage = "act on remote-tracking branches")
  65. private boolean remote = false;
  66. @Option(name = "--all", aliases = { "-a" }, usage = "list both remote-tracking and local branches")
  67. private boolean all = false;
  68. @Option(name = "--delete", aliases = { "-d" }, usage = "delete fully merged branch")
  69. private boolean delete = false;
  70. @Option(name = "--delete-force", aliases = { "-D" }, usage = "delete branch (even if not merged)")
  71. private boolean deleteForce = false;
  72. @Option(name = "--create-force", aliases = { "-f" }, usage = "force create branch even exists")
  73. private boolean createForce = false;
  74. @Option(name = "--verbose", aliases = { "-v" }, usage = "be verbose")
  75. private boolean verbose = false;
  76. @Argument
  77. private List<String> branches = new ArrayList<String>();
  78. private final Map<String, Ref> printRefs = new LinkedHashMap<String, Ref>();
  79. /** Only set for verbose branch listing at-the-moment */
  80. private RevWalk rw;
  81. private int maxNameLength;
  82. @Override
  83. protected void run() throws Exception {
  84. if (delete || deleteForce)
  85. delete(deleteForce);
  86. else {
  87. if (branches.size() > 2)
  88. throw die("Too many refs given\n" + new CmdLineParser(this).printExample(ExampleMode.ALL));
  89. if (branches.size() > 0) {
  90. String newHead = branches.get(0);
  91. String startBranch;
  92. if (branches.size() == 2)
  93. startBranch = branches.get(1);
  94. else
  95. startBranch = Constants.HEAD;
  96. Ref startRef = db.getRef(startBranch);
  97. ObjectId startAt = db.resolve(startBranch + "^0");
  98. if (startRef != null)
  99. startBranch = startRef.getName();
  100. else
  101. startBranch = startAt.name();
  102. startBranch = db.shortenRefName(startBranch);
  103. String newRefName = newHead;
  104. if (!newRefName.startsWith(Constants.R_HEADS))
  105. newRefName = Constants.R_HEADS + newRefName;
  106. if (!Repository.isValidRefName(newRefName))
  107. throw die(String.format("%s is not a valid ref name", newRefName));
  108. if (!createForce && db.resolve(newRefName) != null)
  109. throw die(String.format("branch %s already exists", newHead));
  110. RefUpdate updateRef = db.updateRef(newRefName);
  111. updateRef.setNewObjectId(startAt);
  112. updateRef.setForceUpdate(createForce);
  113. updateRef.setRefLogMessage("branch: Created from " + startBranch, false);
  114. Result update = updateRef.update();
  115. if (update == Result.REJECTED)
  116. throw die(String.format("Could not create branch %s: %s", newHead, update.toString()));
  117. } else {
  118. if (verbose)
  119. rw = new RevWalk(db);
  120. list();
  121. }
  122. }
  123. }
  124. private void list() throws Exception {
  125. Map<String, Ref> refs = db.getAllRefs();
  126. Ref head = refs.get(Constants.HEAD);
  127. // This can happen if HEAD is stillborn
  128. if (head != null) {
  129. String current = head.getName();
  130. if (current.equals(Constants.HEAD))
  131. addRef("(no branch)", head);
  132. addRefs(refs, Constants.R_HEADS, !remote);
  133. addRefs(refs, Constants.R_REMOTES, remote);
  134. for (final Entry<String, Ref> e : printRefs.entrySet()) {
  135. final Ref ref = e.getValue();
  136. printHead(e.getKey(), current.equals(ref.getName()), ref);
  137. }
  138. }
  139. }
  140. private void addRefs(final Map<String, Ref> allRefs, final String prefix,
  141. final boolean add) {
  142. if (all || add) {
  143. for (final Ref ref : RefComparator.sort(allRefs.values())) {
  144. final String name = ref.getName();
  145. if (name.startsWith(prefix))
  146. addRef(name.substring(name.indexOf('/', 5) + 1), ref);
  147. }
  148. }
  149. }
  150. private void addRef(final String name, final Ref ref) {
  151. printRefs.put(name, ref);
  152. maxNameLength = Math.max(maxNameLength, name.length());
  153. }
  154. private void printHead(final String ref, final boolean isCurrent,
  155. final Ref refObj) throws Exception {
  156. out.print(isCurrent ? '*' : ' ');
  157. out.print(' ');
  158. out.print(ref);
  159. if (verbose) {
  160. final int spaces = maxNameLength - ref.length() + 1;
  161. out.print(String.format("%" + spaces + "s", ""));
  162. final ObjectId objectId = refObj.getObjectId();
  163. out.print(objectId.abbreviate(db).name());
  164. out.print(' ');
  165. out.print(rw.parseCommit(objectId).getShortMessage());
  166. }
  167. out.println();
  168. }
  169. private void delete(boolean force) throws IOException {
  170. String current = db.getBranch();
  171. ObjectId head = db.resolve(Constants.HEAD);
  172. for (String branch : branches) {
  173. if (current.equals(branch)) {
  174. String err = "Cannot delete the branch '%s' which you are currently on.";
  175. throw die(String.format(err, branch));
  176. }
  177. RefUpdate update = db.updateRef((remote ? Constants.R_REMOTES
  178. : Constants.R_HEADS)
  179. + branch);
  180. update.setNewObjectId(head);
  181. update.setForceUpdate(force || remote);
  182. Result result = update.delete();
  183. if (result == Result.REJECTED) {
  184. String err = "The branch '%s' is not an ancestor of your current HEAD.\n"
  185. + "If you are sure you want to delete it, run 'jgit branch -D %1$s'.";
  186. throw die(String.format(err, branch));
  187. } else if (result == Result.NEW)
  188. throw die(String.format("branch '%s' not found.", branch));
  189. if (remote)
  190. out.println(String.format("Deleted remote branch %s", branch));
  191. else if (verbose)
  192. out.println(String.format("Deleted branch %s", branch));
  193. }
  194. }
  195. }