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

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