You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PullCommand.java 15KB

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