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