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.annotations.Nullable;
51  import org.eclipse.jgit.api.MergeCommand.FastForwardMode;
52  import org.eclipse.jgit.api.MergeCommand.FastForwardMode.Merge;
53  import org.eclipse.jgit.api.RebaseCommand.Operation;
54  import org.eclipse.jgit.api.errors.CanceledException;
55  import org.eclipse.jgit.api.errors.GitAPIException;
56  import org.eclipse.jgit.api.errors.InvalidConfigurationException;
57  import org.eclipse.jgit.api.errors.InvalidRemoteException;
58  import org.eclipse.jgit.api.errors.JGitInternalException;
59  import org.eclipse.jgit.api.errors.NoHeadException;
60  import org.eclipse.jgit.api.errors.RefNotAdvertisedException;
61  import org.eclipse.jgit.api.errors.RefNotFoundException;
62  import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
63  import org.eclipse.jgit.internal.JGitText;
64  import org.eclipse.jgit.lib.AnyObjectId;
65  import org.eclipse.jgit.lib.BranchConfig.BranchRebaseMode;
66  import org.eclipse.jgit.lib.Config;
67  import org.eclipse.jgit.lib.ConfigConstants;
68  import org.eclipse.jgit.lib.Constants;
69  import org.eclipse.jgit.lib.NullProgressMonitor;
70  import org.eclipse.jgit.lib.ProgressMonitor;
71  import org.eclipse.jgit.lib.Ref;
72  import org.eclipse.jgit.lib.Repository;
73  import org.eclipse.jgit.lib.RepositoryState;
74  import org.eclipse.jgit.lib.SubmoduleConfig.FetchRecurseSubmodulesMode;
75  import org.eclipse.jgit.merge.MergeStrategy;
76  import org.eclipse.jgit.transport.FetchResult;
77  import org.eclipse.jgit.transport.TagOpt;
78  
79  /**
80   * The Pull command
81   *
82   * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-pull.html"
83   *      >Git documentation about Pull</a>
84   */
85  public class PullCommand extends TransportCommand<PullCommand, PullResult> {
86  
87  	private final static String DOT = "."; //$NON-NLS-1$
88  
89  	private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;
90  
91  	private BranchRebaseMode pullRebaseMode = null;
92  
93  	private String remote;
94  
95  	private String remoteBranchName;
96  
97  	private MergeStrategy strategy = MergeStrategy.RECURSIVE;
98  
99  	private TagOpt tagOption;
100 
101 	private FastForwardMode fastForwardMode;
102 
103 	private FetchRecurseSubmodulesMode submoduleRecurseMode = null;
104 
105 	/**
106 	 * Constructor for PullCommand.
107 	 *
108 	 * @param repo
109 	 *            the {@link org.eclipse.jgit.lib.Repository}
110 	 */
111 	protected PullCommand(Repository repo) {
112 		super(repo);
113 	}
114 
115 	/**
116 	 * Set progress monitor
117 	 *
118 	 * @param monitor
119 	 *            a progress monitor
120 	 * @return this instance
121 	 */
122 	public PullCommand setProgressMonitor(ProgressMonitor monitor) {
123 		if (monitor == null) {
124 			monitor = NullProgressMonitor.INSTANCE;
125 		}
126 		this.monitor = monitor;
127 		return this;
128 	}
129 
130 	/**
131 	 * Set if rebase should be used after fetching. If set to true, rebase is
132 	 * used instead of merge. This is equivalent to --rebase on the command
133 	 * line.
134 	 * <p>
135 	 * If set to false, merge is used after fetching, overriding the
136 	 * configuration file. This is equivalent to --no-rebase on the command
137 	 * line.
138 	 * <p>
139 	 * This setting overrides the settings in the configuration file. By
140 	 * default, the setting in the repository configuration file is used.
141 	 * <p>
142 	 * A branch can be configured to use rebase by default. See
143 	 * branch.[name].rebase and branch.autosetuprebase.
144 	 *
145 	 * @param useRebase
146 	 *            whether to use rebase after fetching
147 	 * @return {@code this}
148 	 */
149 	public PullCommand setRebase(boolean useRebase) {
150 		checkCallable();
151 		pullRebaseMode = useRebase ? BranchRebaseMode.REBASE
152 				: BranchRebaseMode.NONE;
153 		return this;
154 	}
155 
156 	/**
157 	 * Sets the {@link org.eclipse.jgit.lib.BranchConfig.BranchRebaseMode} to
158 	 * use after fetching.
159 	 *
160 	 * <dl>
161 	 * <dt>BranchRebaseMode.REBASE</dt>
162 	 * <dd>Equivalent to {@code --rebase} on the command line: use rebase
163 	 * instead of merge after fetching.</dd>
164 	 * <dt>BranchRebaseMode.PRESERVE</dt>
165 	 * <dd>Equivalent to {@code --preserve-merges} on the command line: rebase
166 	 * preserving local merge commits.</dd>
167 	 * <dt>BranchRebaseMode.INTERACTIVE</dt>
168 	 * <dd>Equivalent to {@code --interactive} on the command line: use
169 	 * interactive rebase.</dd>
170 	 * <dt>BranchRebaseMode.NONE</dt>
171 	 * <dd>Equivalent to {@code --no-rebase}: merge instead of rebasing.
172 	 * <dt>{@code null}</dt>
173 	 * <dd>Use the setting defined in the git configuration, either {@code
174 	 * branch.[name].rebase} or, if not set, {@code pull.rebase}</dd>
175 	 * </dl>
176 	 *
177 	 * This setting overrides the settings in the configuration file. By
178 	 * default, the setting in the repository configuration file is used.
179 	 * <p>
180 	 * A branch can be configured to use rebase by default. See
181 	 * {@code branch.[name].rebase}, {@code branch.autosetuprebase}, and
182 	 * {@code pull.rebase}.
183 	 *
184 	 * @param rebaseMode
185 	 *            the {@link org.eclipse.jgit.lib.BranchConfig.BranchRebaseMode}
186 	 *            to use
187 	 * @return {@code this}
188 	 * @since 4.5
189 	 */
190 	public PullCommand setRebase(BranchRebaseMode rebaseMode) {
191 		checkCallable();
192 		pullRebaseMode = rebaseMode;
193 		return this;
194 	}
195 
196 	/**
197 	 * {@inheritDoc}
198 	 * <p>
199 	 * Execute the {@code Pull} command with all the options and parameters
200 	 * collected by the setter methods (e.g.
201 	 * {@link #setProgressMonitor(ProgressMonitor)}) of this class. Each
202 	 * instance of this class should only be used for one invocation of the
203 	 * command. Don't call this method twice on an instance.
204 	 */
205 	@Override
206 	public PullResult call() throws GitAPIException,
207 			WrongRepositoryStateException, InvalidConfigurationException,
208 			InvalidRemoteException, CanceledException,
209 			RefNotFoundException, RefNotAdvertisedException, NoHeadException,
210 			org.eclipse.jgit.api.errors.TransportException {
211 		checkCallable();
212 
213 		monitor.beginTask(JGitText.get().pullTaskName, 2);
214 		Config repoConfig = repo.getConfig();
215 
216 		String branchName = null;
217 		try {
218 			String fullBranch = repo.getFullBranch();
219 			if (fullBranch != null
220 					&& fullBranch.startsWith(Constants.R_HEADS)) {
221 				branchName = fullBranch.substring(Constants.R_HEADS.length());
222 			}
223 		} catch (IOException e) {
224 			throw new JGitInternalException(
225 					JGitText.get().exceptionCaughtDuringExecutionOfPullCommand,
226 					e);
227 		}
228 		if (remoteBranchName == null && branchName != 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 		if (remoteBranchName == null) {
236 			remoteBranchName = branchName;
237 		}
238 		if (remoteBranchName == null) {
239 			throw new NoHeadException(
240 					JGitText.get().cannotCheckoutFromUnbornBranch);
241 		}
242 
243 		if (!repo.getRepositoryState().equals(RepositoryState.SAFE))
244 			throw new WrongRepositoryStateException(MessageFormat.format(
245 					JGitText.get().cannotPullOnARepoWithState, repo
246 							.getRepositoryState().name()));
247 
248 		if (remote == null && branchName != null) {
249 			// get the configured remote for the currently checked out branch
250 			// stored in configuration key branch.<branch name>.remote
251 			remote = repoConfig.getString(
252 					ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
253 					ConfigConstants.CONFIG_KEY_REMOTE);
254 		}
255 		if (remote == null) {
256 			// fall back to default remote
257 			remote = Constants.DEFAULT_REMOTE_NAME;
258 		}
259 
260 		// determines whether rebase should be used after fetching
261 		if (pullRebaseMode == null && branchName != null) {
262 			pullRebaseMode = getRebaseMode(branchName, repoConfig);
263 		}
264 
265 
266 		final boolean isRemote = !remote.equals("."); //$NON-NLS-1$
267 		String remoteUri;
268 		FetchResult fetchRes;
269 		if (isRemote) {
270 			remoteUri = repoConfig.getString(
271 					ConfigConstants.CONFIG_REMOTE_SECTION, remote,
272 					ConfigConstants.CONFIG_KEY_URL);
273 			if (remoteUri == null) {
274 				String missingKey = ConfigConstants.CONFIG_REMOTE_SECTION + DOT
275 						+ remote + DOT + ConfigConstants.CONFIG_KEY_URL;
276 				throw new InvalidConfigurationException(MessageFormat.format(
277 						JGitText.get().missingConfigurationForKey, missingKey));
278 			}
279 
280 			if (monitor.isCancelled())
281 				throw new CanceledException(MessageFormat.format(
282 						JGitText.get().operationCanceled,
283 						JGitText.get().pullTaskName));
284 
285 			FetchCommand fetch = new FetchCommand(repo).setRemote(remote)
286 					.setProgressMonitor(monitor).setTagOpt(tagOption)
287 					.setRecurseSubmodules(submoduleRecurseMode);
288 			configure(fetch);
289 
290 			fetchRes = fetch.call();
291 		} else {
292 			// we can skip the fetch altogether
293 			remoteUri = JGitText.get().localRepository;
294 			fetchRes = null;
295 		}
296 
297 		monitor.update(1);
298 
299 		if (monitor.isCancelled())
300 			throw new CanceledException(MessageFormat.format(
301 					JGitText.get().operationCanceled,
302 					JGitText.get().pullTaskName));
303 
304 		// we check the updates to see which of the updated branches
305 		// corresponds
306 		// to the remote branch name
307 		AnyObjectId commitToMerge;
308 		if (isRemote) {
309 			Ref r = null;
310 			if (fetchRes != null) {
311 				r = fetchRes.getAdvertisedRef(remoteBranchName);
312 				if (r == null)
313 					r = fetchRes.getAdvertisedRef(Constants.R_HEADS
314 							+ remoteBranchName);
315 			}
316 			if (r == null) {
317 				throw new RefNotAdvertisedException(MessageFormat.format(
318 						JGitText.get().couldNotGetAdvertisedRef, remote,
319 						remoteBranchName));
320 			} else {
321 				commitToMerge = r.getObjectId();
322 			}
323 		} else {
324 			try {
325 				commitToMerge = repo.resolve(remoteBranchName);
326 				if (commitToMerge == null)
327 					throw new RefNotFoundException(MessageFormat.format(
328 							JGitText.get().refNotResolved, remoteBranchName));
329 			} catch (IOException e) {
330 				throw new JGitInternalException(
331 						JGitText.get().exceptionCaughtDuringExecutionOfPullCommand,
332 						e);
333 			}
334 		}
335 
336 		String upstreamName = MessageFormat.format(
337 				JGitText.get().upstreamBranchName,
338 				Repository.shortenRefName(remoteBranchName), remoteUri);
339 
340 		PullResult result;
341 		if (pullRebaseMode != BranchRebaseMode.NONE) {
342 			RebaseCommand rebase = new RebaseCommand(repo);
343 			RebaseResult rebaseRes = rebase.setUpstream(commitToMerge)
344 					.setUpstreamName(upstreamName).setProgressMonitor(monitor)
345 					.setOperation(Operation.BEGIN).setStrategy(strategy)
346 					.setPreserveMerges(
347 							pullRebaseMode == BranchRebaseMode.PRESERVE)
348 					.call();
349 			result = new PullResult(fetchRes, remote, rebaseRes);
350 		} else {
351 			MergeCommand merge = new MergeCommand(repo);
352 			MergeResult mergeRes = merge.include(upstreamName, commitToMerge)
353 					.setStrategy(strategy).setProgressMonitor(monitor)
354 					.setFastForward(getFastForwardMode()).call();
355 			monitor.update(1);
356 			result = new PullResult(fetchRes, remote, mergeRes);
357 		}
358 		monitor.endTask();
359 		return result;
360 	}
361 
362 	/**
363 	 * The remote (uri or name) to be used for the pull operation. If no remote
364 	 * is set, the branch's configuration will be used. If the branch
365 	 * configuration is missing the default value of
366 	 * <code>Constants.DEFAULT_REMOTE_NAME</code> will be used.
367 	 *
368 	 * @see Constants#DEFAULT_REMOTE_NAME
369 	 * @param remote
370 	 *            name of the remote to pull from
371 	 * @return {@code this}
372 	 * @since 3.3
373 	 */
374 	public PullCommand setRemote(String remote) {
375 		checkCallable();
376 		this.remote = remote;
377 		return this;
378 	}
379 
380 	/**
381 	 * The remote branch name to be used for the pull operation. If no
382 	 * remoteBranchName is set, the branch's configuration will be used. If the
383 	 * branch configuration is missing the remote branch with the same name as
384 	 * the current branch is used.
385 	 *
386 	 * @param remoteBranchName
387 	 *            remote branch name to be used for pull operation
388 	 * @return {@code this}
389 	 * @since 3.3
390 	 */
391 	public PullCommand setRemoteBranchName(String remoteBranchName) {
392 		checkCallable();
393 		this.remoteBranchName = remoteBranchName;
394 		return this;
395 	}
396 
397 	/**
398 	 * Get the remote name used for pull operation
399 	 *
400 	 * @return the remote used for the pull operation if it was set explicitly
401 	 * @since 3.3
402 	 */
403 	public String getRemote() {
404 		return remote;
405 	}
406 
407 	/**
408 	 * Get the remote branch name for the pull operation
409 	 *
410 	 * @return the remote branch name used for the pull operation if it was set
411 	 *         explicitly
412 	 * @since 3.3
413 	 */
414 	public String getRemoteBranchName() {
415 		return remoteBranchName;
416 	}
417 
418 	/**
419 	 * Set the @{code MergeStrategy}
420 	 *
421 	 * @param strategy
422 	 *            The merge strategy to use during this pull operation.
423 	 * @return {@code this}
424 	 * @since 3.4
425 	 */
426 	public PullCommand setStrategy(MergeStrategy strategy) {
427 		this.strategy = strategy;
428 		return this;
429 	}
430 
431 	/**
432 	 * Set the specification of annotated tag behavior during fetch
433 	 *
434 	 * @param tagOpt
435 	 *            the {@link org.eclipse.jgit.transport.TagOpt}
436 	 * @return {@code this}
437 	 * @since 4.7
438 	 */
439 	public PullCommand setTagOpt(TagOpt tagOpt) {
440 		checkCallable();
441 		this.tagOption = tagOpt;
442 		return this;
443 	}
444 
445 	/**
446 	 * Set the fast forward mode. It is used if pull is configured to do a merge
447 	 * as opposed to rebase. If non-{@code null} takes precedence over the
448 	 * fast-forward mode configured in git config.
449 	 *
450 	 * @param fastForwardMode
451 	 *            corresponds to the --ff/--no-ff/--ff-only options. If
452 	 *            {@code null} use the value of {@code pull.ff} configured in
453 	 *            git config. If {@code pull.ff} is not configured fall back to
454 	 *            the value of {@code merge.ff}. If {@code merge.ff} is not
455 	 *            configured --ff is the built-in default.
456 	 * @return {@code this}
457 	 * @since 4.9
458 	 */
459 	public PullCommand setFastForward(
460 			@Nullable FastForwardMode fastForwardMode) {
461 		checkCallable();
462 		this.fastForwardMode = fastForwardMode;
463 		return this;
464 	}
465 
466 	/**
467 	 * Set the mode to be used for recursing into submodules.
468 	 *
469 	 * @param recurse
470 	 *            the
471 	 *            {@link org.eclipse.jgit.lib.SubmoduleConfig.FetchRecurseSubmodulesMode}
472 	 *            to be used for recursing into submodules
473 	 * @return {@code this}
474 	 * @since 4.7
475 	 * @see FetchCommand#setRecurseSubmodules(FetchRecurseSubmodulesMode)
476 	 */
477 	public PullCommand setRecurseSubmodules(
478 			@Nullable FetchRecurseSubmodulesMode recurse) {
479 		this.submoduleRecurseMode = recurse;
480 		return this;
481 	}
482 
483 	/**
484 	 * Reads the rebase mode to use for a pull command from the repository
485 	 * configuration. This is the value defined for the configurations
486 	 * {@code branch.[branchName].rebase}, or,if not set, {@code pull.rebase}.
487 	 * If neither is set, yields
488 	 * {@link org.eclipse.jgit.lib.BranchConfig.BranchRebaseMode#NONE}.
489 	 *
490 	 * @param branchName
491 	 *            name of the local branch
492 	 * @param config
493 	 *            the {@link org.eclipse.jgit.lib.Config} to read the value from
494 	 * @return the {@link org.eclipse.jgit.lib.BranchConfig.BranchRebaseMode}
495 	 * @since 4.5
496 	 */
497 	public static BranchRebaseMode getRebaseMode(String branchName,
498 			Config config) {
499 		BranchRebaseMode mode = config.getEnum(BranchRebaseMode.values(),
500 				ConfigConstants.CONFIG_BRANCH_SECTION,
501 				branchName, ConfigConstants.CONFIG_KEY_REBASE, null);
502 		if (mode == null) {
503 			mode = config.getEnum(BranchRebaseMode.values(),
504 					ConfigConstants.CONFIG_PULL_SECTION, null,
505 					ConfigConstants.CONFIG_KEY_REBASE, BranchRebaseMode.NONE);
506 		}
507 		return mode;
508 	}
509 
510 	private FastForwardMode getFastForwardMode() {
511 		if (fastForwardMode != null) {
512 			return fastForwardMode;
513 		}
514 		Config config = repo.getConfig();
515 		Merge ffMode = config.getEnum(Merge.values(),
516 				ConfigConstants.CONFIG_PULL_SECTION, null,
517 				ConfigConstants.CONFIG_KEY_FF, null);
518 		return ffMode != null ? FastForwardMode.valueOf(ffMode) : null;
519 	}
520 }