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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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. if (monitor == null) {
  116. monitor = NullProgressMonitor.INSTANCE;
  117. }
  118. this.monitor = monitor;
  119. return this;
  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 ? PullRebaseMode.REBASE : PullRebaseMode.NO_REBASE;
  142. return this;
  143. }
  144. /**
  145. * Executes the {@code Pull} command with all the options and parameters
  146. * collected by the setter methods (e.g.
  147. * {@link #setProgressMonitor(ProgressMonitor)}) of this class. Each
  148. * instance of this class should only be used for one invocation of the
  149. * command. Don't call this method twice on an instance.
  150. *
  151. * @return the result of the pull
  152. * @throws WrongRepositoryStateException
  153. * @throws InvalidConfigurationException
  154. * @throws DetachedHeadException
  155. * @throws InvalidRemoteException
  156. * @throws CanceledException
  157. * @throws RefNotFoundException
  158. * @throws RefNotAdvertisedException
  159. * @throws NoHeadException
  160. * @throws org.eclipse.jgit.api.errors.TransportException
  161. * @throws GitAPIException
  162. */
  163. public PullResult call() throws GitAPIException,
  164. WrongRepositoryStateException, InvalidConfigurationException,
  165. DetachedHeadException, InvalidRemoteException, CanceledException,
  166. RefNotFoundException, RefNotAdvertisedException, NoHeadException,
  167. org.eclipse.jgit.api.errors.TransportException {
  168. checkCallable();
  169. monitor.beginTask(JGitText.get().pullTaskName, 2);
  170. String branchName;
  171. try {
  172. String fullBranch = repo.getFullBranch();
  173. if (fullBranch == null)
  174. throw new NoHeadException(
  175. JGitText.get().pullOnRepoWithoutHEADCurrentlyNotSupported);
  176. if (!fullBranch.startsWith(Constants.R_HEADS)) {
  177. // we can not pull if HEAD is detached and branch is not
  178. // specified explicitly
  179. throw new DetachedHeadException();
  180. }
  181. branchName = fullBranch.substring(Constants.R_HEADS.length());
  182. } catch (IOException e) {
  183. throw new JGitInternalException(
  184. JGitText.get().exceptionCaughtDuringExecutionOfPullCommand,
  185. e);
  186. }
  187. if (!repo.getRepositoryState().equals(RepositoryState.SAFE))
  188. throw new WrongRepositoryStateException(MessageFormat.format(
  189. JGitText.get().cannotPullOnARepoWithState, repo
  190. .getRepositoryState().name()));
  191. Config repoConfig = repo.getConfig();
  192. if (remote == null) {
  193. // get the configured remote for the currently checked out branch
  194. // stored in configuration key branch.<branch name>.remote
  195. remote = repoConfig.getString(
  196. ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
  197. ConfigConstants.CONFIG_KEY_REMOTE);
  198. }
  199. if (remote == null)
  200. // fall back to default remote
  201. remote = Constants.DEFAULT_REMOTE_NAME;
  202. if (remoteBranchName == null)
  203. // get the name of the branch in the remote repository
  204. // stored in configuration key branch.<branch name>.merge
  205. remoteBranchName = repoConfig.getString(
  206. ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
  207. ConfigConstants.CONFIG_KEY_MERGE);
  208. // determines whether rebase should be used after fetching
  209. if (pullRebaseMode == null) {
  210. pullRebaseMode = getRebaseMode(branchName, repoConfig);
  211. }
  212. if (remoteBranchName == null)
  213. remoteBranchName = branchName;
  214. final boolean isRemote = !remote.equals("."); //$NON-NLS-1$
  215. String remoteUri;
  216. FetchResult fetchRes;
  217. if (isRemote) {
  218. remoteUri = repoConfig.getString(
  219. ConfigConstants.CONFIG_REMOTE_SECTION, remote,
  220. ConfigConstants.CONFIG_KEY_URL);
  221. if (remoteUri == null) {
  222. String missingKey = ConfigConstants.CONFIG_REMOTE_SECTION + DOT
  223. + remote + DOT + ConfigConstants.CONFIG_KEY_URL;
  224. throw new InvalidConfigurationException(MessageFormat.format(
  225. JGitText.get().missingConfigurationForKey, missingKey));
  226. }
  227. if (monitor.isCancelled())
  228. throw new CanceledException(MessageFormat.format(
  229. JGitText.get().operationCanceled,
  230. JGitText.get().pullTaskName));
  231. FetchCommand fetch = new FetchCommand(repo);
  232. fetch.setRemote(remote);
  233. fetch.setProgressMonitor(monitor);
  234. configure(fetch);
  235. fetchRes = fetch.call();
  236. } else {
  237. // we can skip the fetch altogether
  238. remoteUri = JGitText.get().localRepository;
  239. fetchRes = null;
  240. }
  241. monitor.update(1);
  242. if (monitor.isCancelled())
  243. throw new CanceledException(MessageFormat.format(
  244. JGitText.get().operationCanceled,
  245. JGitText.get().pullTaskName));
  246. // we check the updates to see which of the updated branches
  247. // corresponds
  248. // to the remote branch name
  249. AnyObjectId commitToMerge;
  250. if (isRemote) {
  251. Ref r = null;
  252. if (fetchRes != null) {
  253. r = fetchRes.getAdvertisedRef(remoteBranchName);
  254. if (r == null)
  255. r = fetchRes.getAdvertisedRef(Constants.R_HEADS
  256. + remoteBranchName);
  257. }
  258. if (r == null) {
  259. throw new RefNotAdvertisedException(MessageFormat.format(
  260. JGitText.get().couldNotGetAdvertisedRef, remote,
  261. remoteBranchName));
  262. } else {
  263. commitToMerge = r.getObjectId();
  264. }
  265. } else {
  266. try {
  267. commitToMerge = repo.resolve(remoteBranchName);
  268. if (commitToMerge == null)
  269. throw new RefNotFoundException(MessageFormat.format(
  270. JGitText.get().refNotResolved, remoteBranchName));
  271. } catch (IOException e) {
  272. throw new JGitInternalException(
  273. JGitText.get().exceptionCaughtDuringExecutionOfPullCommand,
  274. e);
  275. }
  276. }
  277. String upstreamName = MessageFormat.format(
  278. JGitText.get().upstreamBranchName,
  279. Repository.shortenRefName(remoteBranchName), remoteUri);
  280. PullResult result;
  281. if (pullRebaseMode.rebase) {
  282. RebaseCommand rebase = new RebaseCommand(repo);
  283. RebaseResult rebaseRes = rebase.setUpstream(commitToMerge)
  284. .setUpstreamName(upstreamName).setProgressMonitor(monitor)
  285. .setOperation(Operation.BEGIN).setStrategy(strategy)
  286. .setPreserveMerges(pullRebaseMode.preserveMerges)
  287. .call();
  288. result = new PullResult(fetchRes, remote, rebaseRes);
  289. } else {
  290. MergeCommand merge = new MergeCommand(repo);
  291. merge.include(upstreamName, commitToMerge);
  292. merge.setStrategy(strategy);
  293. MergeResult mergeRes = merge.call();
  294. monitor.update(1);
  295. result = new PullResult(fetchRes, remote, mergeRes);
  296. }
  297. monitor.endTask();
  298. return result;
  299. }
  300. /**
  301. * The remote (uri or name) to be used for the pull operation. If no remote
  302. * is set, the branch's configuration will be used. If the branch
  303. * configuration is missing the default value of
  304. * <code>Constants.DEFAULT_REMOTE_NAME</code> will be used.
  305. *
  306. * @see Constants#DEFAULT_REMOTE_NAME
  307. * @param remote
  308. * @return {@code this}
  309. * @since 3.3
  310. */
  311. public PullCommand setRemote(String remote) {
  312. checkCallable();
  313. this.remote = remote;
  314. return this;
  315. }
  316. /**
  317. * The remote branch name to be used for the pull operation. If no
  318. * remoteBranchName is set, the branch's configuration will be used. If the
  319. * branch configuration is missing the remote branch with the same name as
  320. * the current branch is used.
  321. *
  322. * @param remoteBranchName
  323. * @return {@code this}
  324. * @since 3.3
  325. */
  326. public PullCommand setRemoteBranchName(String remoteBranchName) {
  327. checkCallable();
  328. this.remoteBranchName = remoteBranchName;
  329. return this;
  330. }
  331. /**
  332. * @return the remote used for the pull operation if it was set explicitly
  333. * @since 3.3
  334. */
  335. public String getRemote() {
  336. return remote;
  337. }
  338. /**
  339. * @return the remote branch name used for the pull operation if it was set
  340. * explicitly
  341. * @since 3.3
  342. */
  343. public String getRemoteBranchName() {
  344. return remoteBranchName;
  345. }
  346. /**
  347. * @param strategy
  348. * The merge strategy to use during this pull operation.
  349. * @return {@code this}
  350. * @since 3.4
  351. */
  352. public PullCommand setStrategy(MergeStrategy strategy) {
  353. this.strategy = strategy;
  354. return this;
  355. }
  356. private static PullRebaseMode getRebaseMode(String branchName, Config config) {
  357. PullRebaseMode mode = config.getEnum(PullRebaseMode.values(),
  358. ConfigConstants.CONFIG_PULL_SECTION, null,
  359. ConfigConstants.CONFIG_KEY_REBASE, PullRebaseMode.NO_REBASE);
  360. mode = config.getEnum(PullRebaseMode.values(),
  361. ConfigConstants.CONFIG_BRANCH_SECTION,
  362. branchName, ConfigConstants.CONFIG_KEY_REBASE, mode);
  363. return mode;
  364. }
  365. }