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

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