View Javadoc
1   /*
2    * Copyright (C) 2010, Mathias Kinzler <mathias.kinzler@sap.com>
3    * Copyright (C) 2010, Chris Aniszczyk <caniszczyk@gmail.com>
4    * and other copyright owners as documented in the project's IP log.
5    *
6    * This program and the accompanying materials are made available
7    * under the terms of the Eclipse Distribution License v1.0 which
8    * accompanies this distribution, is reproduced below, and is
9    * available at http://www.eclipse.org/org/documents/edl-v10.php
10   *
11   * All rights reserved.
12   *
13   * Redistribution and use in source and binary forms, with or
14   * without modification, are permitted provided that the following
15   * conditions are met:
16   *
17   * - Redistributions of source code must retain the above copyright
18   *   notice, this list of conditions and the following disclaimer.
19   *
20   * - Redistributions in binary form must reproduce the above
21   *   copyright notice, this list of conditions and the following
22   *   disclaimer in the documentation and/or other materials provided
23   *   with the distribution.
24   *
25   * - Neither the name of the Eclipse Foundation, Inc. nor the
26   *   names of its contributors may be used to endorse or promote
27   *   products derived from this software without specific prior
28   *   written permission.
29   *
30   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
31   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
32   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
35   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
37   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
38   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
39   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
40   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
41   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
42   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43   */
44  package org.eclipse.jgit.api;
45  
46  import java.io.IOException;
47  import java.text.MessageFormat;
48  import java.util.ArrayList;
49  import java.util.HashSet;
50  import java.util.List;
51  import java.util.Set;
52  
53  import org.eclipse.jgit.api.errors.CannotDeleteCurrentBranchException;
54  import org.eclipse.jgit.api.errors.GitAPIException;
55  import org.eclipse.jgit.api.errors.JGitInternalException;
56  import org.eclipse.jgit.api.errors.NotMergedException;
57  import org.eclipse.jgit.internal.JGitText;
58  import org.eclipse.jgit.lib.ConfigConstants;
59  import org.eclipse.jgit.lib.Constants;
60  import org.eclipse.jgit.lib.Ref;
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.lib.StoredConfig;
65  import org.eclipse.jgit.revwalk.RevCommit;
66  import org.eclipse.jgit.revwalk.RevWalk;
67  
68  /**
69   * Used to delete one or several branches.
70   *
71   * The result of {@link #call()} is a list with the (full) names of the deleted
72   * branches.
73   *
74   * Note that we don't have a setter corresponding to the -r option; remote
75   * tracking branches are simply deleted just like local branches.
76   *
77   * @see <a
78   *      href="http://www.kernel.org/pub/software/scm/git/docs/git-branch.html"
79   *      >Git documentation about Branch</a>
80   */
81  public class DeleteBranchCommand extends GitCommand<List<String>> {
82  	private final Set<String> branchNames = new HashSet<>();
83  
84  	private boolean force;
85  
86  	/**
87  	 * @param repo
88  	 */
89  	protected DeleteBranchCommand(Repository repo) {
90  		super(repo);
91  	}
92  
93  	/**
94  	 * @throws NotMergedException
95  	 *             when trying to delete a branch which has not been merged into
96  	 *             the currently checked out branch without force
97  	 * @throws CannotDeleteCurrentBranchException
98  	 * @return the list with the (full) names of the deleted branches
99  	 */
100 	@Override
101 	public List<String> call() throws GitAPIException,
102 			NotMergedException, CannotDeleteCurrentBranchException {
103 		checkCallable();
104 		List<String> result = new ArrayList<>();
105 		if (branchNames.isEmpty())
106 			return result;
107 		try {
108 			String currentBranch = repo.getFullBranch();
109 			if (!force) {
110 				// check if the branches to be deleted
111 				// are all merged into the current branch
112 				try (RevWalk walk = new RevWalk(repo)) {
113 					RevCommit tip = walk
114 							.parseCommit(repo.resolve(Constants.HEAD));
115 					for (String branchName : branchNames) {
116 						if (branchName == null)
117 							continue;
118 						Ref currentRef = repo.findRef(branchName);
119 						if (currentRef == null)
120 							continue;
121 
122 						RevCommit base = walk
123 								.parseCommit(repo.resolve(branchName));
124 						if (!walk.isMergedInto(base, tip)) {
125 							throw new NotMergedException();
126 						}
127 					}
128 				}
129 			}
130 			setCallable(false);
131 			for (String branchName : branchNames) {
132 				if (branchName == null)
133 					continue;
134 				Ref currentRef = repo.findRef(branchName);
135 				if (currentRef == null)
136 					continue;
137 				String fullName = currentRef.getName();
138 				if (fullName.equals(currentBranch))
139 					throw new CannotDeleteCurrentBranchException(
140 							MessageFormat
141 									.format(
142 											JGitText.get().cannotDeleteCheckedOutBranch,
143 											branchName));
144 				RefUpdate update = repo.updateRef(fullName);
145 				update.setRefLogMessage("branch deleted", false); //$NON-NLS-1$
146 				update.setForceUpdate(true);
147 				Result deleteResult = update.delete();
148 
149 				boolean ok = true;
150 				switch (deleteResult) {
151 				case IO_FAILURE:
152 				case LOCK_FAILURE:
153 				case REJECTED:
154 					ok = false;
155 					break;
156 				default:
157 					break;
158 				}
159 
160 				if (ok) {
161 					result.add(fullName);
162 					if (fullName.startsWith(Constants.R_HEADS)) {
163 						String shortenedName = fullName
164 								.substring(Constants.R_HEADS.length());
165 						// remove upstream configuration if any
166 						final StoredConfig cfg = repo.getConfig();
167 						cfg.unsetSection(
168 								ConfigConstants.CONFIG_BRANCH_SECTION,
169 								shortenedName);
170 						cfg.save();
171 					}
172 				} else
173 					throw new JGitInternalException(MessageFormat.format(
174 							JGitText.get().deleteBranchUnexpectedResult,
175 							deleteResult.name()));
176 			}
177 			return result;
178 		} catch (IOException ioe) {
179 			throw new JGitInternalException(ioe.getMessage(), ioe);
180 		}
181 	}
182 
183 	/**
184 	 * @param branchnames
185 	 *            the names of the branches to delete; if not set, this will do
186 	 *            nothing; invalid branch names will simply be ignored
187 	 * @return this instance
188 	 */
189 	public DeleteBranchCommand setBranchNames(String... branchnames) {
190 		checkCallable();
191 		this.branchNames.clear();
192 		for (String branch : branchnames)
193 			this.branchNames.add(branch);
194 		return this;
195 	}
196 
197 	/**
198 	 * @param force
199 	 *            <code>true</code> corresponds to the -D option,
200 	 *            <code>false</code> to the -d option (default) <br>
201 	 *            if <code>false</code> a check will be performed whether the
202 	 *            branch to be deleted is already merged into the current branch
203 	 *            and deletion will be refused in this case
204 	 * @return this instance
205 	 */
206 	public DeleteBranchCommand setForce(boolean force) {
207 		checkCallable();
208 		this.force = force;
209 		return this;
210 	}
211 }