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.1KB

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