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