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

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