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

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