View Javadoc
1   /*
2    * Copyright (C) 2010, Christian Halstrick <christian.halstrick@sap.com>
3    * Copyright (C) 2010, Mathias Kinzler <mathias.kinzler@sap.com>
4    * Copyright (C) 2016, Laurent Delaigue <laurent.delaigue@obeo.fr>
5    * and other copyright owners as documented in the project's IP log.
6    *
7    * This program and the accompanying materials are made available
8    * under the terms of the Eclipse Distribution License v1.0 which
9    * accompanies this distribution, is reproduced below, and is
10   * available at http://www.eclipse.org/org/documents/edl-v10.php
11   *
12   * All rights reserved.
13   *
14   * Redistribution and use in source and binary forms, with or
15   * without modification, are permitted provided that the following
16   * conditions are met:
17   *
18   * - Redistributions of source code must retain the above copyright
19   *   notice, this list of conditions and the following disclaimer.
20   *
21   * - Redistributions in binary form must reproduce the above
22   *   copyright notice, this list of conditions and the following
23   *   disclaimer in the documentation and/or other materials provided
24   *   with the distribution.
25   *
26   * - Neither the name of the Eclipse Foundation, Inc. nor the
27   *   names of its contributors may be used to endorse or promote
28   *   products derived from this software without specific prior
29   *   written permission.
30   *
31   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
32   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
33   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
34   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
36   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
37   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
39   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
40   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
41   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
42   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
43   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44   */
45  package org.eclipse.jgit.api;
46  
47  import java.io.IOException;
48  import java.text.MessageFormat;
49  
50  import org.eclipse.jgit.api.RebaseCommand.Operation;
51  import org.eclipse.jgit.api.errors.CanceledException;
52  import org.eclipse.jgit.api.errors.DetachedHeadException;
53  import org.eclipse.jgit.api.errors.GitAPIException;
54  import org.eclipse.jgit.api.errors.InvalidConfigurationException;
55  import org.eclipse.jgit.api.errors.InvalidRemoteException;
56  import org.eclipse.jgit.api.errors.JGitInternalException;
57  import org.eclipse.jgit.api.errors.NoHeadException;
58  import org.eclipse.jgit.api.errors.RefNotAdvertisedException;
59  import org.eclipse.jgit.api.errors.RefNotFoundException;
60  import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
61  import org.eclipse.jgit.internal.JGitText;
62  import org.eclipse.jgit.lib.AnyObjectId;
63  import org.eclipse.jgit.lib.Config;
64  import org.eclipse.jgit.lib.ConfigConstants;
65  import org.eclipse.jgit.lib.Constants;
66  import org.eclipse.jgit.lib.NullProgressMonitor;
67  import org.eclipse.jgit.lib.ProgressMonitor;
68  import org.eclipse.jgit.lib.Ref;
69  import org.eclipse.jgit.lib.Repository;
70  import org.eclipse.jgit.lib.RepositoryState;
71  import org.eclipse.jgit.merge.MergeStrategy;
72  import org.eclipse.jgit.transport.FetchResult;
73  
74  /**
75   * The Pull command
76   *
77   * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-pull.html"
78   *      >Git documentation about Pull</a>
79   */
80  public class PullCommand extends TransportCommand<PullCommand, PullResult> {
81  
82  	private final static String DOT = "."; //$NON-NLS-1$
83  
84  	private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;
85  
86  	private PullRebaseMode pullRebaseMode = null;
87  
88  	private String remote;
89  
90  	private String remoteBranchName;
91  
92  	private MergeStrategy strategy = MergeStrategy.RECURSIVE;
93  
94  	private enum PullRebaseMode implements Config.ConfigEnum {
95  		REBASE_PRESERVE("preserve", true, true), //$NON-NLS-1$
96  		REBASE("true", true, false), //$NON-NLS-1$
97  		NO_REBASE("false", false, false); //$NON-NLS-1$
98  
99  		private final String configValue;
100 
101 		private final boolean rebase;
102 
103 		private final boolean preserveMerges;
104 
105 		PullRebaseMode(String configValue, boolean rebase,
106 				boolean preserveMerges) {
107 			this.configValue = configValue;
108 			this.rebase = rebase;
109 			this.preserveMerges = preserveMerges;
110 		}
111 
112 		public String toConfigValue() {
113 			return configValue;
114 		}
115 
116 		public boolean matchConfigValue(String in) {
117 			return in.equals(configValue);
118 		}
119 	}
120 
121 	/**
122 	 * @param repo
123 	 */
124 	protected PullCommand(Repository repo) {
125 		super(repo);
126 	}
127 
128 	/**
129 	 * @param monitor
130 	 *            a progress monitor
131 	 * @return this instance
132 	 */
133 	public PullCommand setProgressMonitor(ProgressMonitor monitor) {
134 		if (monitor == null) {
135 			monitor = NullProgressMonitor.INSTANCE;
136 		}
137 		this.monitor = monitor;
138 		return this;
139 	}
140 
141 	/**
142 	 * Set if rebase should be used after fetching. If set to true, rebase is
143 	 * used instead of merge. This is equivalent to --rebase on the command
144 	 * line.
145 	 * <p>
146 	 * If set to false, merge is used after fetching, overriding the
147 	 * configuration file. This is equivalent to --no-rebase on the command
148 	 * line.
149 	 * <p>
150 	 * This setting overrides the settings in the configuration file. By
151 	 * default, the setting in the repository configuration file is used.
152 	 * <p>
153 	 * A branch can be configured to use rebase by default. See
154 	 * branch.[name].rebase and branch.autosetuprebase.
155 	 *
156 	 * @param useRebase
157 	 * @return {@code this}
158 	 */
159 	public PullCommand setRebase(boolean useRebase) {
160 		checkCallable();
161 		pullRebaseMode = useRebase ? PullRebaseMode.REBASE : PullRebaseMode.NO_REBASE;
162 		return this;
163 	}
164 
165 	/**
166 	 * Executes the {@code Pull} command with all the options and parameters
167 	 * collected by the setter methods (e.g.
168 	 * {@link #setProgressMonitor(ProgressMonitor)}) of this class. Each
169 	 * instance of this class should only be used for one invocation of the
170 	 * command. Don't call this method twice on an instance.
171 	 *
172 	 * @return the result of the pull
173 	 * @throws WrongRepositoryStateException
174 	 * @throws InvalidConfigurationException
175 	 * @throws DetachedHeadException
176 	 * @throws InvalidRemoteException
177 	 * @throws CanceledException
178 	 * @throws RefNotFoundException
179 	 * @throws RefNotAdvertisedException
180 	 * @throws NoHeadException
181 	 * @throws org.eclipse.jgit.api.errors.TransportException
182 	 * @throws GitAPIException
183 	 */
184 	public PullResult call() throws GitAPIException,
185 			WrongRepositoryStateException, InvalidConfigurationException,
186 			DetachedHeadException, InvalidRemoteException, CanceledException,
187 			RefNotFoundException, RefNotAdvertisedException, NoHeadException,
188 			org.eclipse.jgit.api.errors.TransportException {
189 		checkCallable();
190 
191 		monitor.beginTask(JGitText.get().pullTaskName, 2);
192 
193 		String branchName;
194 		try {
195 			String fullBranch = repo.getFullBranch();
196 			if (fullBranch == null)
197 				throw new NoHeadException(
198 						JGitText.get().pullOnRepoWithoutHEADCurrentlyNotSupported);
199 			if (!fullBranch.startsWith(Constants.R_HEADS)) {
200 				// we can not pull if HEAD is detached and branch is not
201 				// specified explicitly
202 				throw new DetachedHeadException();
203 			}
204 			branchName = fullBranch.substring(Constants.R_HEADS.length());
205 		} catch (IOException e) {
206 			throw new JGitInternalException(
207 					JGitText.get().exceptionCaughtDuringExecutionOfPullCommand,
208 					e);
209 		}
210 
211 		if (!repo.getRepositoryState().equals(RepositoryState.SAFE))
212 			throw new WrongRepositoryStateException(MessageFormat.format(
213 					JGitText.get().cannotPullOnARepoWithState, repo
214 							.getRepositoryState().name()));
215 
216 		Config repoConfig = repo.getConfig();
217 		if (remote == null) {
218 			// get the configured remote for the currently checked out branch
219 			// stored in configuration key branch.<branch name>.remote
220 			remote = repoConfig.getString(
221 					ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
222 					ConfigConstants.CONFIG_KEY_REMOTE);
223 		}
224 		if (remote == null)
225 			// fall back to default remote
226 			remote = Constants.DEFAULT_REMOTE_NAME;
227 
228 		if (remoteBranchName == null)
229 			// get the name of the branch in the remote repository
230 			// stored in configuration key branch.<branch name>.merge
231 			remoteBranchName = repoConfig.getString(
232 					ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
233 					ConfigConstants.CONFIG_KEY_MERGE);
234 
235 		// determines whether rebase should be used after fetching
236 		if (pullRebaseMode == null) {
237 			pullRebaseMode = getRebaseMode(branchName, repoConfig);
238 		}
239 
240 		if (remoteBranchName == null)
241 			remoteBranchName = branchName;
242 
243 		final boolean isRemote = !remote.equals("."); //$NON-NLS-1$
244 		String remoteUri;
245 		FetchResult fetchRes;
246 		if (isRemote) {
247 			remoteUri = repoConfig.getString(
248 					ConfigConstants.CONFIG_REMOTE_SECTION, remote,
249 					ConfigConstants.CONFIG_KEY_URL);
250 			if (remoteUri == null) {
251 				String missingKey = ConfigConstants.CONFIG_REMOTE_SECTION + DOT
252 						+ remote + DOT + ConfigConstants.CONFIG_KEY_URL;
253 				throw new InvalidConfigurationException(MessageFormat.format(
254 						JGitText.get().missingConfigurationForKey, missingKey));
255 			}
256 
257 			if (monitor.isCancelled())
258 				throw new CanceledException(MessageFormat.format(
259 						JGitText.get().operationCanceled,
260 						JGitText.get().pullTaskName));
261 
262 			FetchCommand fetch = new FetchCommand(repo);
263 			fetch.setRemote(remote);
264 			fetch.setProgressMonitor(monitor);
265 			configure(fetch);
266 
267 			fetchRes = fetch.call();
268 		} else {
269 			// we can skip the fetch altogether
270 			remoteUri = JGitText.get().localRepository;
271 			fetchRes = null;
272 		}
273 
274 		monitor.update(1);
275 
276 		if (monitor.isCancelled())
277 			throw new CanceledException(MessageFormat.format(
278 					JGitText.get().operationCanceled,
279 					JGitText.get().pullTaskName));
280 
281 		// we check the updates to see which of the updated branches
282 		// corresponds
283 		// to the remote branch name
284 		AnyObjectId commitToMerge;
285 		if (isRemote) {
286 			Ref r = null;
287 			if (fetchRes != null) {
288 				r = fetchRes.getAdvertisedRef(remoteBranchName);
289 				if (r == null)
290 					r = fetchRes.getAdvertisedRef(Constants.R_HEADS
291 							+ remoteBranchName);
292 			}
293 			if (r == null) {
294 				throw new RefNotAdvertisedException(MessageFormat.format(
295 						JGitText.get().couldNotGetAdvertisedRef, remote,
296 						remoteBranchName));
297 			} else {
298 				commitToMerge = r.getObjectId();
299 			}
300 		} else {
301 			try {
302 				commitToMerge = repo.resolve(remoteBranchName);
303 				if (commitToMerge == null)
304 					throw new RefNotFoundException(MessageFormat.format(
305 							JGitText.get().refNotResolved, remoteBranchName));
306 			} catch (IOException e) {
307 				throw new JGitInternalException(
308 						JGitText.get().exceptionCaughtDuringExecutionOfPullCommand,
309 						e);
310 			}
311 		}
312 
313 		String upstreamName = MessageFormat.format(
314 				JGitText.get().upstreamBranchName,
315 				Repository.shortenRefName(remoteBranchName), remoteUri);
316 
317 		PullResult result;
318 		if (pullRebaseMode.rebase) {
319 			RebaseCommand rebase = new RebaseCommand(repo);
320 			RebaseResult rebaseRes = rebase.setUpstream(commitToMerge)
321 					.setUpstreamName(upstreamName).setProgressMonitor(monitor)
322 					.setOperation(Operation.BEGIN).setStrategy(strategy)
323 					.setPreserveMerges(pullRebaseMode.preserveMerges)
324 					.call();
325 			result = new PullResult(fetchRes, remote, rebaseRes);
326 		} else {
327 			MergeCommand merge = new MergeCommand(repo);
328 			merge.include(upstreamName, commitToMerge);
329 			merge.setStrategy(strategy);
330 			merge.setProgressMonitor(monitor);
331 			MergeResult mergeRes = merge.call();
332 			monitor.update(1);
333 			result = new PullResult(fetchRes, remote, mergeRes);
334 		}
335 		monitor.endTask();
336 		return result;
337 	}
338 
339 	/**
340 	 * The remote (uri or name) to be used for the pull operation. If no remote
341 	 * is set, the branch's configuration will be used. If the branch
342 	 * configuration is missing the default value of
343 	 * <code>Constants.DEFAULT_REMOTE_NAME</code> will be used.
344 	 *
345 	 * @see Constants#DEFAULT_REMOTE_NAME
346 	 * @param remote
347 	 * @return {@code this}
348 	 * @since 3.3
349 	 */
350 	public PullCommand setRemote(String remote) {
351 		checkCallable();
352 		this.remote = remote;
353 		return this;
354 	}
355 
356 	/**
357 	 * The remote branch name to be used for the pull operation. If no
358 	 * remoteBranchName is set, the branch's configuration will be used. If the
359 	 * branch configuration is missing the remote branch with the same name as
360 	 * the current branch is used.
361 	 *
362 	 * @param remoteBranchName
363 	 * @return {@code this}
364 	 * @since 3.3
365 	 */
366 	public PullCommand setRemoteBranchName(String remoteBranchName) {
367 		checkCallable();
368 		this.remoteBranchName = remoteBranchName;
369 		return this;
370 	}
371 
372 	/**
373 	 * @return the remote used for the pull operation if it was set explicitly
374 	 * @since 3.3
375 	 */
376 	public String getRemote() {
377 		return remote;
378 	}
379 
380 	/**
381 	 * @return the remote branch name used for the pull operation if it was set
382 	 *         explicitly
383 	 * @since 3.3
384 	 */
385 	public String getRemoteBranchName() {
386 		return remoteBranchName;
387 	}
388 
389 	/**
390 	 * @param strategy
391 	 *            The merge strategy to use during this pull operation.
392 	 * @return {@code this}
393 	 * @since 3.4
394 	 */
395 	public PullCommand setStrategy(MergeStrategy strategy) {
396 		this.strategy = strategy;
397 		return this;
398 	}
399 
400 	private static PullRebaseMode getRebaseMode(String branchName, Config config) {
401 		PullRebaseMode mode = config.getEnum(PullRebaseMode.values(),
402 				ConfigConstants.CONFIG_PULL_SECTION, null,
403 				ConfigConstants.CONFIG_KEY_REBASE, PullRebaseMode.NO_REBASE);
404 		mode = config.getEnum(PullRebaseMode.values(),
405 				ConfigConstants.CONFIG_BRANCH_SECTION,
406 				branchName, ConfigConstants.CONFIG_KEY_REBASE, mode);
407 		return mode;
408 	}
409 }