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

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