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.Arrays;
49  
50  import org.eclipse.jgit.api.errors.DetachedHeadException;
51  import org.eclipse.jgit.api.errors.GitAPIException;
52  import org.eclipse.jgit.api.errors.InvalidRefNameException;
53  import org.eclipse.jgit.api.errors.JGitInternalException;
54  import org.eclipse.jgit.api.errors.NoHeadException;
55  import org.eclipse.jgit.api.errors.RefAlreadyExistsException;
56  import org.eclipse.jgit.api.errors.RefNotFoundException;
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.ObjectId;
61  import org.eclipse.jgit.lib.Ref;
62  import org.eclipse.jgit.lib.RefRename;
63  import org.eclipse.jgit.lib.RefUpdate.Result;
64  import org.eclipse.jgit.lib.Repository;
65  import org.eclipse.jgit.lib.StoredConfig;
66  
67  /**
68   * Used to rename branches.
69   *
70   * @see <a
71   *      href="http://www.kernel.org/pub/software/scm/git/docs/git-branch.html"
72   *      >Git documentation about Branch</a>
73   */
74  public class RenameBranchCommand extends GitCommand<Ref> {
75  	private String oldName;
76  
77  	private String newName;
78  
79  	/**
80  	 * <p>
81  	 * Constructor for RenameBranchCommand.
82  	 * </p>
83  	 *
84  	 * @param repo
85  	 *            the {@link org.eclipse.jgit.lib.Repository}
86  	 */
87  	protected RenameBranchCommand(Repository repo) {
88  		super(repo);
89  	}
90  
91  	/** {@inheritDoc} */
92  	@Override
93  	public Ref call() throws GitAPIException, RefNotFoundException, InvalidRefNameException,
94  			RefAlreadyExistsException, DetachedHeadException {
95  		checkCallable();
96  
97  		if (newName == null)
98  			throw new InvalidRefNameException(MessageFormat.format(JGitText
99  					.get().branchNameInvalid, "<null>")); //$NON-NLS-1$
100 
101 		try {
102 			String fullOldName;
103 			String fullNewName;
104 			if (repo.findRef(newName) != null)
105 				throw new RefAlreadyExistsException(MessageFormat.format(
106 						JGitText.get().refAlreadyExists1, newName));
107 			if (oldName != null) {
108 				Ref ref = repo.findRef(oldName);
109 				if (ref == null)
110 					throw new RefNotFoundException(MessageFormat.format(
111 							JGitText.get().refNotResolved, oldName));
112 				if (ref.getName().startsWith(Constants.R_TAGS))
113 					throw new RefNotFoundException(MessageFormat.format(
114 							JGitText.get().renameBranchFailedBecauseTag,
115 							oldName));
116 				fullOldName = ref.getName();
117 			} else {
118 				fullOldName = repo.getFullBranch();
119 				if (fullOldName == null) {
120 					throw new NoHeadException(
121 							JGitText.get().invalidRepositoryStateNoHead);
122 				}
123 				if (ObjectId.isId(fullOldName))
124 					throw new DetachedHeadException();
125 			}
126 
127 			if (fullOldName.startsWith(Constants.R_REMOTES))
128 				fullNewName = Constants.R_REMOTES + newName;
129 			else {
130 				fullNewName = Constants.R_HEADS + newName;
131 			}
132 
133 			if (!Repository.isValidRefName(fullNewName))
134 				throw new InvalidRefNameException(MessageFormat.format(JGitText
135 						.get().branchNameInvalid, fullNewName));
136 
137 			RefRename rename = repo.renameRef(fullOldName, fullNewName);
138 			Result renameResult = rename.rename();
139 
140 			setCallable(false);
141 
142 			if (Result.RENAMED != renameResult)
143 				throw new JGitInternalException(MessageFormat.format(JGitText
144 						.get().renameBranchUnexpectedResult, renameResult
145 						.name()));
146 
147 			if (fullNewName.startsWith(Constants.R_HEADS)) {
148 				String shortOldName = fullOldName.substring(Constants.R_HEADS
149 						.length());
150 				final StoredConfig repoConfig = repo.getConfig();
151 				// Copy all configuration values over to the new branch
152 				for (String name : repoConfig.getNames(
153 						ConfigConstants.CONFIG_BRANCH_SECTION, shortOldName)) {
154 					String[] values = repoConfig.getStringList(
155 							ConfigConstants.CONFIG_BRANCH_SECTION,
156 							shortOldName, name);
157 					if (values.length == 0)
158 						continue;
159 					// Keep any existing values already configured for the
160 					// new branch name
161 					String[] existing = repoConfig.getStringList(
162 							ConfigConstants.CONFIG_BRANCH_SECTION, newName,
163 							name);
164 					if (existing.length > 0) {
165 						String[] newValues = new String[values.length
166 								+ existing.length];
167 						System.arraycopy(existing, 0, newValues, 0,
168 								existing.length);
169 						System.arraycopy(values, 0, newValues, existing.length,
170 								values.length);
171 						values = newValues;
172 					}
173 
174 					repoConfig.setStringList(
175 							ConfigConstants.CONFIG_BRANCH_SECTION, newName,
176 							name, Arrays.asList(values));
177 				}
178 				repoConfig.unsetSection(ConfigConstants.CONFIG_BRANCH_SECTION,
179 						shortOldName);
180 				repoConfig.save();
181 			}
182 
183 			Ref resultRef = repo.findRef(newName);
184 			if (resultRef == null)
185 				throw new JGitInternalException(
186 						JGitText.get().renameBranchFailedUnknownReason);
187 			return resultRef;
188 		} catch (IOException ioe) {
189 			throw new JGitInternalException(ioe.getMessage(), ioe);
190 		}
191 	}
192 
193 	/**
194 	 * Set the new name of the branch
195 	 *
196 	 * @param newName
197 	 *            the new name
198 	 * @return this instance
199 	 */
200 	public RenameBranchCommand setNewName(String newName) {
201 		checkCallable();
202 		this.newName = newName;
203 		return this;
204 	}
205 
206 	/**
207 	 * Set the old name of the branch
208 	 *
209 	 * @param oldName
210 	 *            the name of the branch to rename; if not set, the currently
211 	 *            checked out branch (if any) will be renamed
212 	 * @return this instance
213 	 */
214 	public RenameBranchCommand setOldName(String oldName) {
215 		checkCallable();
216 		this.oldName = oldName;
217 		return this;
218 	}
219 }