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 13KB

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