您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

Branch.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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.Collection;
  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.api.Git;
  52. import org.eclipse.jgit.api.ListBranchCommand;
  53. import org.eclipse.jgit.api.ListBranchCommand.ListMode;
  54. import org.eclipse.jgit.lib.Constants;
  55. import org.eclipse.jgit.lib.ObjectId;
  56. import org.eclipse.jgit.lib.ObjectReader;
  57. import org.eclipse.jgit.lib.Ref;
  58. import org.eclipse.jgit.lib.RefComparator;
  59. import org.eclipse.jgit.lib.RefRename;
  60. import org.eclipse.jgit.lib.RefUpdate;
  61. import org.eclipse.jgit.lib.RefUpdate.Result;
  62. import org.eclipse.jgit.lib.Repository;
  63. import org.eclipse.jgit.pgm.internal.CLIText;
  64. import org.eclipse.jgit.pgm.opt.OptionWithValuesListHandler;
  65. import org.eclipse.jgit.revwalk.RevWalk;
  66. import org.kohsuke.args4j.Argument;
  67. import org.kohsuke.args4j.Option;
  68. @Command(common = true, usage = "usage_listCreateOrDeleteBranches")
  69. class Branch extends TextBuiltin {
  70. private String otherBranch;
  71. private boolean createForce;
  72. private boolean rename;
  73. @Option(name = "--remote", aliases = { "-r" }, usage = "usage_actOnRemoteTrackingBranches")
  74. private boolean remote = false;
  75. @Option(name = "--all", aliases = { "-a" }, usage = "usage_listBothRemoteTrackingAndLocalBranches")
  76. private boolean all = false;
  77. @Option(name = "--contains", metaVar = "metaVar_commitish", usage = "usage_printOnlyBranchesThatContainTheCommit")
  78. private String containsCommitish;
  79. private List<String> delete;
  80. /**
  81. * Delete branches
  82. *
  83. * @param names
  84. * a {@link java.util.List} of branch names.
  85. */
  86. @Option(name = "--delete", aliases = {
  87. "-d" }, metaVar = "metaVar_branchNames", usage = "usage_deleteFullyMergedBranch", handler = OptionWithValuesListHandler.class)
  88. public void delete(List<String> names) {
  89. if (names.isEmpty()) {
  90. throw die(CLIText.get().branchNameRequired);
  91. }
  92. delete = names;
  93. }
  94. private List<String> deleteForce;
  95. /**
  96. * Forcefully delete branches
  97. *
  98. * @param names
  99. * a {@link java.util.List} of branch names.
  100. */
  101. @Option(name = "--delete-force", aliases = {
  102. "-D" }, metaVar = "metaVar_branchNames", usage = "usage_deleteBranchEvenIfNotMerged", handler = OptionWithValuesListHandler.class)
  103. public void deleteForce(List<String> names) {
  104. if (names.isEmpty()) {
  105. throw die(CLIText.get().branchNameRequired);
  106. }
  107. deleteForce = names;
  108. }
  109. /**
  110. * Forcefully create a list of branches
  111. *
  112. * @param branchAndStartPoint
  113. * a branch name and a start point
  114. */
  115. @Option(name = "--create-force", aliases = {
  116. "-f" }, metaVar = "metaVar_branchAndStartPoint", usage = "usage_forceCreateBranchEvenExists", handler = OptionWithValuesListHandler.class)
  117. public void createForce(List<String> branchAndStartPoint) {
  118. createForce = true;
  119. if (branchAndStartPoint.isEmpty()) {
  120. throw die(CLIText.get().branchNameRequired);
  121. }
  122. if (branchAndStartPoint.size() > 2) {
  123. throw die(CLIText.get().tooManyRefsGiven);
  124. }
  125. if (branchAndStartPoint.size() == 1) {
  126. branch = branchAndStartPoint.get(0);
  127. } else {
  128. branch = branchAndStartPoint.get(0);
  129. otherBranch = branchAndStartPoint.get(1);
  130. }
  131. }
  132. /**
  133. * Move or rename a branch
  134. *
  135. * @param currentAndNew
  136. * the current and the new branch name
  137. */
  138. @Option(name = "--move", aliases = {
  139. "-m" }, metaVar = "metaVar_oldNewBranchNames", usage = "usage_moveRenameABranch", handler = OptionWithValuesListHandler.class)
  140. public void moveRename(List<String> currentAndNew) {
  141. rename = true;
  142. if (currentAndNew.isEmpty()) {
  143. throw die(CLIText.get().branchNameRequired);
  144. }
  145. if (currentAndNew.size() > 2) {
  146. throw die(CLIText.get().tooManyRefsGiven);
  147. }
  148. if (currentAndNew.size() == 1) {
  149. branch = currentAndNew.get(0);
  150. } else {
  151. branch = currentAndNew.get(0);
  152. otherBranch = currentAndNew.get(1);
  153. }
  154. }
  155. @Option(name = "--verbose", aliases = { "-v" }, usage = "usage_beVerbose")
  156. private boolean verbose = false;
  157. @Argument(metaVar = "metaVar_name")
  158. private String branch;
  159. private final Map<String, Ref> printRefs = new LinkedHashMap<>();
  160. /** Only set for verbose branch listing at-the-moment */
  161. private RevWalk rw;
  162. private int maxNameLength;
  163. /** {@inheritDoc} */
  164. @Override
  165. protected void run() throws Exception {
  166. if (delete != null || deleteForce != null) {
  167. if (delete != null) {
  168. delete(delete, false);
  169. }
  170. if (deleteForce != null) {
  171. delete(deleteForce, true);
  172. }
  173. } else {
  174. if (rename) {
  175. String src, dst;
  176. if (otherBranch == null) {
  177. final Ref head = db.exactRef(Constants.HEAD);
  178. if (head != null && head.isSymbolic()) {
  179. src = head.getLeaf().getName();
  180. } else {
  181. throw die(CLIText.get().cannotRenameDetachedHEAD);
  182. }
  183. dst = branch;
  184. } else {
  185. src = branch;
  186. final Ref old = db.findRef(src);
  187. if (old == null)
  188. throw die(MessageFormat.format(CLIText.get().doesNotExist, src));
  189. if (!old.getName().startsWith(Constants.R_HEADS))
  190. throw die(MessageFormat.format(CLIText.get().notABranch, src));
  191. src = old.getName();
  192. dst = otherBranch;
  193. }
  194. if (!dst.startsWith(Constants.R_HEADS))
  195. dst = Constants.R_HEADS + dst;
  196. if (!Repository.isValidRefName(dst))
  197. throw die(MessageFormat.format(CLIText.get().notAValidRefName, dst));
  198. RefRename r = db.renameRef(src, dst);
  199. if (r.rename() != Result.RENAMED)
  200. throw die(MessageFormat.format(CLIText.get().cannotBeRenamed, src));
  201. } else if (createForce || branch != null) {
  202. String newHead = branch;
  203. String startBranch;
  204. if (createForce) {
  205. startBranch = otherBranch;
  206. } else {
  207. startBranch = Constants.HEAD;
  208. }
  209. Ref startRef = db.findRef(startBranch);
  210. ObjectId startAt = db.resolve(startBranch + "^0"); //$NON-NLS-1$
  211. if (startRef != null) {
  212. startBranch = startRef.getName();
  213. } else if (startAt != null) {
  214. startBranch = startAt.name();
  215. } else {
  216. throw die(MessageFormat.format(
  217. CLIText.get().notAValidCommitName, startBranch));
  218. }
  219. startBranch = Repository.shortenRefName(startBranch);
  220. String newRefName = newHead;
  221. if (!newRefName.startsWith(Constants.R_HEADS)) {
  222. newRefName = Constants.R_HEADS + newRefName;
  223. }
  224. if (!Repository.isValidRefName(newRefName)) {
  225. throw die(MessageFormat.format(CLIText.get().notAValidRefName, newRefName));
  226. }
  227. if (!createForce && db.resolve(newRefName) != null) {
  228. throw die(MessageFormat.format(CLIText.get().branchAlreadyExists, newHead));
  229. }
  230. RefUpdate updateRef = db.updateRef(newRefName);
  231. updateRef.setNewObjectId(startAt);
  232. updateRef.setForceUpdate(createForce);
  233. updateRef.setRefLogMessage(MessageFormat.format(CLIText.get().branchCreatedFrom, startBranch), false);
  234. Result update = updateRef.update();
  235. if (update == Result.REJECTED) {
  236. throw die(MessageFormat.format(CLIText.get().couldNotCreateBranch, newHead, update.toString()));
  237. }
  238. } else {
  239. if (verbose) {
  240. rw = new RevWalk(db);
  241. }
  242. list();
  243. }
  244. }
  245. }
  246. private void list() throws Exception {
  247. Ref head = db.exactRef(Constants.HEAD);
  248. // This can happen if HEAD is stillborn
  249. if (head != null) {
  250. String current = head.getLeaf().getName();
  251. try (Git git = new Git(db)) {
  252. ListBranchCommand command = git.branchList();
  253. if (all)
  254. command.setListMode(ListMode.ALL);
  255. else if (remote)
  256. command.setListMode(ListMode.REMOTE);
  257. if (containsCommitish != null)
  258. command.setContains(containsCommitish);
  259. List<Ref> refs = command.call();
  260. for (Ref ref : refs) {
  261. if (ref.getName().equals(Constants.HEAD))
  262. addRef("(no branch)", head); //$NON-NLS-1$
  263. }
  264. addRefs(refs, Constants.R_HEADS);
  265. addRefs(refs, Constants.R_REMOTES);
  266. try (ObjectReader reader = db.newObjectReader()) {
  267. for (Entry<String, Ref> e : printRefs.entrySet()) {
  268. final Ref ref = e.getValue();
  269. printHead(reader, e.getKey(),
  270. current.equals(ref.getName()), ref);
  271. }
  272. }
  273. }
  274. }
  275. }
  276. private void addRefs(Collection<Ref> refs, String prefix) {
  277. for (Ref ref : RefComparator.sort(refs)) {
  278. final String name = ref.getName();
  279. if (name.startsWith(prefix))
  280. addRef(name.substring(name.indexOf('/', 5) + 1), ref);
  281. }
  282. }
  283. private void addRef(String name, Ref ref) {
  284. printRefs.put(name, ref);
  285. maxNameLength = Math.max(maxNameLength, name.length());
  286. }
  287. private void printHead(final ObjectReader reader, final String ref,
  288. final boolean isCurrent, final Ref refObj) throws Exception {
  289. outw.print(isCurrent ? '*' : ' ');
  290. outw.print(' ');
  291. outw.print(ref);
  292. if (verbose) {
  293. final int spaces = maxNameLength - ref.length() + 1;
  294. outw.format("%" + spaces + "s", ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
  295. final ObjectId objectId = refObj.getObjectId();
  296. outw.print(reader.abbreviate(objectId).name());
  297. outw.print(' ');
  298. outw.print(rw.parseCommit(objectId).getShortMessage());
  299. }
  300. outw.println();
  301. }
  302. private void delete(List<String> branches, boolean force)
  303. throws IOException {
  304. String current = db.getBranch();
  305. ObjectId head = db.resolve(Constants.HEAD);
  306. for (String b : branches) {
  307. if (b.equals(current)) {
  308. throw die(MessageFormat.format(CLIText.get().cannotDeleteTheBranchWhichYouAreCurrentlyOn, b));
  309. }
  310. RefUpdate update = db.updateRef((remote ? Constants.R_REMOTES
  311. : Constants.R_HEADS)
  312. + b);
  313. update.setNewObjectId(head);
  314. update.setForceUpdate(force || remote);
  315. Result result = update.delete();
  316. if (result == Result.REJECTED) {
  317. throw die(MessageFormat.format(CLIText.get().branchIsNotAnAncestorOfYourCurrentHEAD, b));
  318. } else if (result == Result.NEW)
  319. throw die(MessageFormat.format(CLIText.get().branchNotFound, b));
  320. if (remote)
  321. outw.println(MessageFormat.format(CLIText.get().deletedRemoteBranch, b));
  322. else if (verbose)
  323. outw.println(MessageFormat.format(CLIText.get().deletedBranch, b));
  324. }
  325. }
  326. }