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.

RepoCommand.java 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. /*
  2. * Copyright (C) 2014, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.gitrepo;
  44. import static java.nio.charset.StandardCharsets.UTF_8;
  45. import static org.eclipse.jgit.lib.Constants.DEFAULT_REMOTE_NAME;
  46. import static org.eclipse.jgit.lib.Constants.R_REMOTES;
  47. import java.io.File;
  48. import java.io.FileInputStream;
  49. import java.io.IOException;
  50. import java.io.InputStream;
  51. import java.net.URI;
  52. import java.text.MessageFormat;
  53. import java.util.ArrayList;
  54. import java.util.List;
  55. import java.util.Map;
  56. import java.util.Objects;
  57. import java.util.StringJoiner;
  58. import java.util.TreeMap;
  59. import org.eclipse.jgit.annotations.Nullable;
  60. import org.eclipse.jgit.api.Git;
  61. import org.eclipse.jgit.api.GitCommand;
  62. import org.eclipse.jgit.api.SubmoduleAddCommand;
  63. import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
  64. import org.eclipse.jgit.api.errors.GitAPIException;
  65. import org.eclipse.jgit.api.errors.JGitInternalException;
  66. import org.eclipse.jgit.dircache.DirCache;
  67. import org.eclipse.jgit.dircache.DirCacheBuilder;
  68. import org.eclipse.jgit.dircache.DirCacheEntry;
  69. import org.eclipse.jgit.gitrepo.ManifestParser.IncludedFileReader;
  70. import org.eclipse.jgit.gitrepo.RepoProject.CopyFile;
  71. import org.eclipse.jgit.gitrepo.RepoProject.LinkFile;
  72. import org.eclipse.jgit.gitrepo.internal.RepoText;
  73. import org.eclipse.jgit.internal.JGitText;
  74. import org.eclipse.jgit.lib.CommitBuilder;
  75. import org.eclipse.jgit.lib.Config;
  76. import org.eclipse.jgit.lib.Constants;
  77. import org.eclipse.jgit.lib.FileMode;
  78. import org.eclipse.jgit.lib.ObjectId;
  79. import org.eclipse.jgit.lib.ObjectInserter;
  80. import org.eclipse.jgit.lib.ObjectReader;
  81. import org.eclipse.jgit.lib.PersonIdent;
  82. import org.eclipse.jgit.lib.ProgressMonitor;
  83. import org.eclipse.jgit.lib.Ref;
  84. import org.eclipse.jgit.lib.RefDatabase;
  85. import org.eclipse.jgit.lib.RefUpdate;
  86. import org.eclipse.jgit.lib.RefUpdate.Result;
  87. import org.eclipse.jgit.lib.Repository;
  88. import org.eclipse.jgit.revwalk.RevCommit;
  89. import org.eclipse.jgit.revwalk.RevWalk;
  90. import org.eclipse.jgit.util.FileUtils;
  91. /**
  92. * A class used to execute a repo command.
  93. *
  94. * This will parse a repo XML manifest, convert it into .gitmodules file and the
  95. * repository config file.
  96. *
  97. * If called against a bare repository, it will replace all the existing content
  98. * of the repository with the contents populated from the manifest.
  99. *
  100. * repo manifest allows projects overlapping, e.g. one project's manifestPath is
  101. * "foo" and another project's manifestPath is "foo/bar". This won't
  102. * work in git submodule, so we'll skip all the sub projects
  103. * ("foo/bar" in the example) while converting.
  104. *
  105. * @see <a href="https://code.google.com/p/git-repo/">git-repo project page</a>
  106. * @since 3.4
  107. */
  108. public class RepoCommand extends GitCommand<RevCommit> {
  109. private String manifestPath;
  110. private String baseUri;
  111. private URI targetUri;
  112. private String groupsParam;
  113. private String branch;
  114. private String targetBranch = Constants.HEAD;
  115. private boolean recordRemoteBranch = true;
  116. private boolean recordSubmoduleLabels = true;
  117. private boolean recordShallowSubmodules = true;
  118. private PersonIdent author;
  119. private RemoteReader callback;
  120. private InputStream inputStream;
  121. private IncludedFileReader includedReader;
  122. private boolean ignoreRemoteFailures = false;
  123. private ProgressMonitor monitor;
  124. /**
  125. * A callback to get ref sha1 of a repository from its uri.
  126. *
  127. * We provided a default implementation {@link DefaultRemoteReader} to
  128. * use ls-remote command to read the sha1 from the repository and clone the
  129. * repository to read the file. Callers may have their own quicker
  130. * implementation.
  131. *
  132. * @since 3.4
  133. */
  134. public interface RemoteReader {
  135. /**
  136. * Read a remote ref sha1.
  137. *
  138. * @param uri
  139. * The URI of the remote repository
  140. * @param ref
  141. * The ref (branch/tag/etc.) to read
  142. * @return the sha1 of the remote repository, or null if the ref does
  143. * not exist.
  144. * @throws GitAPIException
  145. */
  146. @Nullable
  147. public ObjectId sha1(String uri, String ref) throws GitAPIException;
  148. /**
  149. * Read a file from a remote repository.
  150. *
  151. * @param uri
  152. * The URI of the remote repository
  153. * @param ref
  154. * The ref (branch/tag/etc.) to read
  155. * @param path
  156. * The relative path (inside the repo) to the file to read
  157. * @return the file content.
  158. * @throws GitAPIException
  159. * @throws IOException
  160. * @since 3.5
  161. */
  162. public byte[] readFile(String uri, String ref, String path)
  163. throws GitAPIException, IOException;
  164. }
  165. /** A default implementation of {@link RemoteReader} callback. */
  166. public static class DefaultRemoteReader implements RemoteReader {
  167. @Override
  168. public ObjectId sha1(String uri, String ref) throws GitAPIException {
  169. Map<String, Ref> map = Git
  170. .lsRemoteRepository()
  171. .setRemote(uri)
  172. .callAsMap();
  173. Ref r = RefDatabase.findRef(map, ref);
  174. return r != null ? r.getObjectId() : null;
  175. }
  176. @Override
  177. public byte[] readFile(String uri, String ref, String path)
  178. throws GitAPIException, IOException {
  179. File dir = FileUtils.createTempDir("jgit_", ".git", null); //$NON-NLS-1$ //$NON-NLS-2$
  180. try (Git git = Git.cloneRepository().setBare(true).setDirectory(dir)
  181. .setURI(uri).call()) {
  182. return readFileFromRepo(git.getRepository(), ref, path);
  183. } finally {
  184. FileUtils.delete(dir, FileUtils.RECURSIVE);
  185. }
  186. }
  187. /**
  188. * Read a file from the repository
  189. *
  190. * @param repo
  191. * The repository containing the file
  192. * @param ref
  193. * The ref (branch/tag/etc.) to read
  194. * @param path
  195. * The relative path (inside the repo) to the file to read
  196. * @return the file's content
  197. * @throws GitAPIException
  198. * @throws IOException
  199. * @since 3.5
  200. */
  201. protected byte[] readFileFromRepo(Repository repo,
  202. String ref, String path) throws GitAPIException, IOException {
  203. try (ObjectReader reader = repo.newObjectReader()) {
  204. ObjectId oid = repo.resolve(ref + ":" + path); //$NON-NLS-1$
  205. return reader.open(oid).getBytes(Integer.MAX_VALUE);
  206. }
  207. }
  208. }
  209. @SuppressWarnings("serial")
  210. private static class ManifestErrorException extends GitAPIException {
  211. ManifestErrorException(Throwable cause) {
  212. super(RepoText.get().invalidManifest, cause);
  213. }
  214. }
  215. @SuppressWarnings("serial")
  216. private static class RemoteUnavailableException extends GitAPIException {
  217. RemoteUnavailableException(String uri) {
  218. super(MessageFormat.format(RepoText.get().errorRemoteUnavailable, uri));
  219. }
  220. }
  221. /**
  222. * Constructor for RepoCommand
  223. *
  224. * @param repo
  225. * the {@link org.eclipse.jgit.lib.Repository}
  226. */
  227. public RepoCommand(Repository repo) {
  228. super(repo);
  229. }
  230. /**
  231. * Set path to the manifest XML file.
  232. * <p>
  233. * Calling {@link #setInputStream} will ignore the path set here.
  234. *
  235. * @param path
  236. * (with <code>/</code> as separator)
  237. * @return this command
  238. */
  239. public RepoCommand setPath(String path) {
  240. this.manifestPath = path;
  241. return this;
  242. }
  243. /**
  244. * Set the input stream to the manifest XML.
  245. * <p>
  246. * Setting inputStream will ignore the path set. It will be closed in
  247. * {@link #call}.
  248. *
  249. * @param inputStream a {@link java.io.InputStream} object.
  250. * @return this command
  251. * @since 3.5
  252. */
  253. public RepoCommand setInputStream(InputStream inputStream) {
  254. this.inputStream = inputStream;
  255. return this;
  256. }
  257. /**
  258. * Set base URI of the paths inside the XML. This is typically the name of
  259. * the directory holding the manifest repository, eg. for
  260. * https://android.googlesource.com/platform/manifest, this should be
  261. * /platform (if you would run this on android.googlesource.com) or
  262. * https://android.googlesource.com/platform elsewhere.
  263. *
  264. * @param uri
  265. * the base URI
  266. * @return this command
  267. */
  268. public RepoCommand setURI(String uri) {
  269. this.baseUri = uri;
  270. return this;
  271. }
  272. /**
  273. * Set the URI of the superproject (this repository), so the .gitmodules
  274. * file can specify the submodule URLs relative to the superproject.
  275. *
  276. * @param uri
  277. * the URI of the repository holding the superproject.
  278. * @return this command
  279. * @since 4.8
  280. */
  281. public RepoCommand setTargetURI(String uri) {
  282. // The repo name is interpreted as a directory, for example
  283. // Gerrit (http://gerrit.googlesource.com/gerrit) has a
  284. // .gitmodules referencing ../plugins/hooks, which is
  285. // on http://gerrit.googlesource.com/plugins/hooks,
  286. this.targetUri = URI.create(uri + "/"); //$NON-NLS-1$
  287. return this;
  288. }
  289. /**
  290. * Set groups to sync
  291. *
  292. * @param groups groups separated by comma, examples: default|all|G1,-G2,-G3
  293. * @return this command
  294. */
  295. public RepoCommand setGroups(String groups) {
  296. this.groupsParam = groups;
  297. return this;
  298. }
  299. /**
  300. * Set default branch.
  301. * <p>
  302. * This is generally the name of the branch the manifest file was in. If
  303. * there's no default revision (branch) specified in manifest and no
  304. * revision specified in project, this branch will be used.
  305. *
  306. * @param branch
  307. * a branch name
  308. * @return this command
  309. */
  310. public RepoCommand setBranch(String branch) {
  311. this.branch = branch;
  312. return this;
  313. }
  314. /**
  315. * Set target branch.
  316. * <p>
  317. * This is the target branch of the super project to be updated. If not set,
  318. * default is HEAD.
  319. * <p>
  320. * For non-bare repositories, HEAD will always be used and this will be
  321. * ignored.
  322. *
  323. * @param branch
  324. * branch name
  325. * @return this command
  326. * @since 4.1
  327. */
  328. public RepoCommand setTargetBranch(String branch) {
  329. this.targetBranch = Constants.R_HEADS + branch;
  330. return this;
  331. }
  332. /**
  333. * Set whether the branch name should be recorded in .gitmodules.
  334. * <p>
  335. * Submodule entries in .gitmodules can include a "branch" field
  336. * to indicate what remote branch each submodule tracks.
  337. * <p>
  338. * That field is used by "git submodule update --remote" to update
  339. * to the tip of the tracked branch when asked and by Gerrit to
  340. * update the superproject when a change on that branch is merged.
  341. * <p>
  342. * Subprojects that request a specific commit or tag will not have
  343. * a branch name recorded.
  344. * <p>
  345. * Not implemented for non-bare repositories.
  346. *
  347. * @param enable Whether to record the branch name
  348. * @return this command
  349. * @since 4.2
  350. */
  351. public RepoCommand setRecordRemoteBranch(boolean enable) {
  352. this.recordRemoteBranch = enable;
  353. return this;
  354. }
  355. /**
  356. * Set whether the labels field should be recorded as a label in
  357. * .gitattributes.
  358. * <p>
  359. * Not implemented for non-bare repositories.
  360. *
  361. * @param enable Whether to record the labels in the .gitattributes
  362. * @return this command
  363. * @since 4.4
  364. */
  365. public RepoCommand setRecordSubmoduleLabels(boolean enable) {
  366. this.recordSubmoduleLabels = enable;
  367. return this;
  368. }
  369. /**
  370. * Set whether the clone-depth field should be recorded as a shallow
  371. * recommendation in .gitmodules.
  372. * <p>
  373. * Not implemented for non-bare repositories.
  374. *
  375. * @param enable Whether to record the shallow recommendation.
  376. * @return this command
  377. * @since 4.4
  378. */
  379. public RepoCommand setRecommendShallow(boolean enable) {
  380. this.recordShallowSubmodules = enable;
  381. return this;
  382. }
  383. /**
  384. * The progress monitor associated with the clone operation. By default,
  385. * this is set to <code>NullProgressMonitor</code>
  386. *
  387. * @see org.eclipse.jgit.lib.NullProgressMonitor
  388. * @param monitor
  389. * a {@link org.eclipse.jgit.lib.ProgressMonitor}
  390. * @return this command
  391. */
  392. public RepoCommand setProgressMonitor(ProgressMonitor monitor) {
  393. this.monitor = monitor;
  394. return this;
  395. }
  396. /**
  397. * Set whether to skip projects whose commits don't exist remotely.
  398. * <p>
  399. * When set to true, we'll just skip the manifest entry and continue
  400. * on to the next one.
  401. * <p>
  402. * When set to false (default), we'll throw an error when remote
  403. * failures occur.
  404. * <p>
  405. * Not implemented for non-bare repositories.
  406. *
  407. * @param ignore Whether to ignore the remote failures.
  408. * @return this command
  409. * @since 4.3
  410. */
  411. public RepoCommand setIgnoreRemoteFailures(boolean ignore) {
  412. this.ignoreRemoteFailures = ignore;
  413. return this;
  414. }
  415. /**
  416. * Set the author/committer for the bare repository commit.
  417. * <p>
  418. * For non-bare repositories, the current user will be used and this will be
  419. * ignored.
  420. *
  421. * @param author
  422. * the author's {@link org.eclipse.jgit.lib.PersonIdent}
  423. * @return this command
  424. */
  425. public RepoCommand setAuthor(PersonIdent author) {
  426. this.author = author;
  427. return this;
  428. }
  429. /**
  430. * Set the GetHeadFromUri callback.
  431. *
  432. * This is only used in bare repositories.
  433. *
  434. * @param callback
  435. * a {@link org.eclipse.jgit.gitrepo.RepoCommand.RemoteReader}
  436. * object.
  437. * @return this command
  438. */
  439. public RepoCommand setRemoteReader(RemoteReader callback) {
  440. this.callback = callback;
  441. return this;
  442. }
  443. /**
  444. * Set the IncludedFileReader callback.
  445. *
  446. * @param reader
  447. * a
  448. * {@link org.eclipse.jgit.gitrepo.ManifestParser.IncludedFileReader}
  449. * object.
  450. * @return this command
  451. * @since 4.0
  452. */
  453. public RepoCommand setIncludedFileReader(IncludedFileReader reader) {
  454. this.includedReader = reader;
  455. return this;
  456. }
  457. /** {@inheritDoc} */
  458. @Override
  459. public RevCommit call() throws GitAPIException {
  460. checkCallable();
  461. if (baseUri == null) {
  462. baseUri = ""; //$NON-NLS-1$
  463. }
  464. if (inputStream == null) {
  465. if (manifestPath == null || manifestPath.length() == 0)
  466. throw new IllegalArgumentException(
  467. JGitText.get().pathNotConfigured);
  468. try {
  469. inputStream = new FileInputStream(manifestPath);
  470. } catch (IOException e) {
  471. throw new IllegalArgumentException(
  472. JGitText.get().pathNotConfigured);
  473. }
  474. }
  475. List<RepoProject> filteredProjects;
  476. try {
  477. ManifestParser parser = new ManifestParser(includedReader,
  478. manifestPath, branch, baseUri, groupsParam, repo);
  479. parser.read(inputStream);
  480. filteredProjects = parser.getFilteredProjects();
  481. } catch (IOException e) {
  482. throw new ManifestErrorException(e);
  483. } finally {
  484. try {
  485. inputStream.close();
  486. } catch (IOException e) {
  487. // Just ignore it, it's not important.
  488. }
  489. }
  490. if (repo.isBare()) {
  491. if (author == null)
  492. author = new PersonIdent(repo);
  493. if (callback == null)
  494. callback = new DefaultRemoteReader();
  495. List<RepoProject> renamedProjects = renameProjects(filteredProjects);
  496. DirCache index = DirCache.newInCore();
  497. DirCacheBuilder builder = index.builder();
  498. ObjectInserter inserter = repo.newObjectInserter();
  499. try (RevWalk rw = new RevWalk(repo)) {
  500. Config cfg = new Config();
  501. StringBuilder attributes = new StringBuilder();
  502. for (RepoProject proj : renamedProjects) {
  503. String name = proj.getName();
  504. String path = proj.getPath();
  505. String url = proj.getUrl();
  506. ObjectId objectId;
  507. if (ObjectId.isId(proj.getRevision())) {
  508. objectId = ObjectId.fromString(proj.getRevision());
  509. } else {
  510. objectId = callback.sha1(url, proj.getRevision());
  511. if (objectId == null && !ignoreRemoteFailures) {
  512. throw new RemoteUnavailableException(url);
  513. }
  514. if (recordRemoteBranch) {
  515. // can be branch or tag
  516. cfg.setString("submodule", name, "branch", //$NON-NLS-1$ //$NON-NLS-2$
  517. proj.getRevision());
  518. }
  519. if (recordShallowSubmodules && proj.getRecommendShallow() != null) {
  520. // The shallow recommendation is losing information.
  521. // As the repo manifests stores the recommended
  522. // depth in the 'clone-depth' field, while
  523. // git core only uses a binary 'shallow = true/false'
  524. // hint, we'll map any depth to 'shallow = true'
  525. cfg.setBoolean("submodule", name, "shallow", //$NON-NLS-1$ //$NON-NLS-2$
  526. true);
  527. }
  528. }
  529. if (recordSubmoduleLabels) {
  530. StringBuilder rec = new StringBuilder();
  531. rec.append("/"); //$NON-NLS-1$
  532. rec.append(path);
  533. for (String group : proj.getGroups()) {
  534. rec.append(" "); //$NON-NLS-1$
  535. rec.append(group);
  536. }
  537. rec.append("\n"); //$NON-NLS-1$
  538. attributes.append(rec.toString());
  539. }
  540. URI submodUrl = URI.create(url);
  541. if (targetUri != null) {
  542. submodUrl = relativize(targetUri, submodUrl);
  543. }
  544. cfg.setString("submodule", name, "path", path); //$NON-NLS-1$ //$NON-NLS-2$
  545. cfg.setString("submodule", name, "url", //$NON-NLS-1$ //$NON-NLS-2$
  546. submodUrl.toString());
  547. // create gitlink
  548. if (objectId != null) {
  549. DirCacheEntry dcEntry = new DirCacheEntry(path);
  550. dcEntry.setObjectId(objectId);
  551. dcEntry.setFileMode(FileMode.GITLINK);
  552. builder.add(dcEntry);
  553. for (CopyFile copyfile : proj.getCopyFiles()) {
  554. byte[] src = callback.readFile(
  555. url, proj.getRevision(), copyfile.src);
  556. objectId = inserter.insert(Constants.OBJ_BLOB, src);
  557. dcEntry = new DirCacheEntry(copyfile.dest);
  558. dcEntry.setObjectId(objectId);
  559. dcEntry.setFileMode(FileMode.REGULAR_FILE);
  560. builder.add(dcEntry);
  561. }
  562. for (LinkFile linkfile : proj.getLinkFiles()) {
  563. String link;
  564. if (linkfile.dest.contains("/")) { //$NON-NLS-1$
  565. link = FileUtils.relativizeGitPath(
  566. linkfile.dest.substring(0,
  567. linkfile.dest.lastIndexOf('/')),
  568. proj.getPath() + "/" + linkfile.src); //$NON-NLS-1$
  569. } else {
  570. link = proj.getPath() + "/" + linkfile.src; //$NON-NLS-1$
  571. }
  572. objectId = inserter.insert(Constants.OBJ_BLOB,
  573. link.getBytes(UTF_8));
  574. dcEntry = new DirCacheEntry(linkfile.dest);
  575. dcEntry.setObjectId(objectId);
  576. dcEntry.setFileMode(FileMode.SYMLINK);
  577. builder.add(dcEntry);
  578. }
  579. }
  580. }
  581. String content = cfg.toText();
  582. // create a new DirCacheEntry for .gitmodules file.
  583. final DirCacheEntry dcEntry = new DirCacheEntry(Constants.DOT_GIT_MODULES);
  584. ObjectId objectId = inserter.insert(Constants.OBJ_BLOB,
  585. content.getBytes(UTF_8));
  586. dcEntry.setObjectId(objectId);
  587. dcEntry.setFileMode(FileMode.REGULAR_FILE);
  588. builder.add(dcEntry);
  589. if (recordSubmoduleLabels) {
  590. // create a new DirCacheEntry for .gitattributes file.
  591. final DirCacheEntry dcEntryAttr = new DirCacheEntry(Constants.DOT_GIT_ATTRIBUTES);
  592. ObjectId attrId = inserter.insert(Constants.OBJ_BLOB,
  593. attributes.toString().getBytes(UTF_8));
  594. dcEntryAttr.setObjectId(attrId);
  595. dcEntryAttr.setFileMode(FileMode.REGULAR_FILE);
  596. builder.add(dcEntryAttr);
  597. }
  598. builder.finish();
  599. ObjectId treeId = index.writeTree(inserter);
  600. // Create a Commit object, populate it and write it
  601. ObjectId headId = repo.resolve(targetBranch + "^{commit}"); //$NON-NLS-1$
  602. if (headId != null && rw.parseCommit(headId).getTree().getId().equals(treeId)) {
  603. // No change. Do nothing.
  604. return rw.parseCommit(headId);
  605. }
  606. CommitBuilder commit = new CommitBuilder();
  607. commit.setTreeId(treeId);
  608. if (headId != null)
  609. commit.setParentIds(headId);
  610. commit.setAuthor(author);
  611. commit.setCommitter(author);
  612. commit.setMessage(RepoText.get().repoCommitMessage);
  613. ObjectId commitId = inserter.insert(commit);
  614. inserter.flush();
  615. RefUpdate ru = repo.updateRef(targetBranch);
  616. ru.setNewObjectId(commitId);
  617. ru.setExpectedOldObjectId(headId != null ? headId : ObjectId.zeroId());
  618. Result rc = ru.update(rw);
  619. switch (rc) {
  620. case NEW:
  621. case FORCED:
  622. case FAST_FORWARD:
  623. // Successful. Do nothing.
  624. break;
  625. case REJECTED:
  626. case LOCK_FAILURE:
  627. throw new ConcurrentRefUpdateException(
  628. MessageFormat.format(
  629. JGitText.get().cannotLock, targetBranch),
  630. ru.getRef(),
  631. rc);
  632. default:
  633. throw new JGitInternalException(MessageFormat.format(
  634. JGitText.get().updatingRefFailed,
  635. targetBranch, commitId.name(), rc));
  636. }
  637. return rw.parseCommit(commitId);
  638. } catch (GitAPIException | IOException e) {
  639. throw new ManifestErrorException(e);
  640. }
  641. } else {
  642. try (Git git = new Git(repo)) {
  643. for (RepoProject proj : filteredProjects) {
  644. addSubmodule(proj.getName(), proj.getUrl(), proj.getPath(),
  645. proj.getRevision(), proj.getCopyFiles(),
  646. proj.getLinkFiles(), git);
  647. }
  648. return git.commit().setMessage(RepoText.get().repoCommitMessage)
  649. .call();
  650. } catch (GitAPIException | IOException e) {
  651. throw new ManifestErrorException(e);
  652. }
  653. }
  654. }
  655. private void addSubmodule(String name, String url, String path,
  656. String revision, List<CopyFile> copyfiles, List<LinkFile> linkfiles,
  657. Git git) throws GitAPIException, IOException {
  658. assert (!repo.isBare());
  659. assert (git != null);
  660. if (!linkfiles.isEmpty()) {
  661. throw new UnsupportedOperationException(
  662. JGitText.get().nonBareLinkFilesNotSupported);
  663. }
  664. SubmoduleAddCommand add = git.submoduleAdd().setName(name).setPath(path)
  665. .setURI(url);
  666. if (monitor != null)
  667. add.setProgressMonitor(monitor);
  668. Repository subRepo = add.call();
  669. if (revision != null) {
  670. try (Git sub = new Git(subRepo)) {
  671. sub.checkout().setName(findRef(revision, subRepo)).call();
  672. }
  673. subRepo.close();
  674. git.add().addFilepattern(path).call();
  675. }
  676. for (CopyFile copyfile : copyfiles) {
  677. copyfile.copy();
  678. git.add().addFilepattern(copyfile.dest).call();
  679. }
  680. }
  681. /**
  682. * Rename the projects if there's a conflict when converted to submodules.
  683. *
  684. * @param projects
  685. * parsed projects
  686. * @return projects that are renamed if necessary
  687. */
  688. private List<RepoProject> renameProjects(List<RepoProject> projects) {
  689. Map<String, List<RepoProject>> m = new TreeMap<>();
  690. for (RepoProject proj : projects) {
  691. List<RepoProject> l = m.get(proj.getName());
  692. if (l == null) {
  693. l = new ArrayList<>();
  694. m.put(proj.getName(), l);
  695. }
  696. l.add(proj);
  697. }
  698. List<RepoProject> ret = new ArrayList<>();
  699. for (List<RepoProject> ps : m.values()) {
  700. boolean nameConflict = ps.size() != 1;
  701. for (RepoProject proj : ps) {
  702. String name = proj.getName();
  703. if (nameConflict) {
  704. name += SLASH + proj.getPath();
  705. }
  706. RepoProject p = new RepoProject(name,
  707. proj.getPath(), proj.getRevision(), null,
  708. proj.getGroups(), proj.getRecommendShallow());
  709. p.setUrl(proj.getUrl());
  710. p.addCopyFiles(proj.getCopyFiles());
  711. p.addLinkFiles(proj.getLinkFiles());
  712. ret.add(p);
  713. }
  714. }
  715. return ret;
  716. }
  717. /*
  718. * Assume we are document "a/b/index.html", what should we put in a href to get to "a/" ?
  719. * Returns the child if either base or child is not a bare path. This provides a missing feature in
  720. * java.net.URI (see http://bugs.java.com/view_bug.do?bug_id=6226081).
  721. */
  722. private static final String SLASH = "/"; //$NON-NLS-1$
  723. static URI relativize(URI current, URI target) {
  724. if (!Objects.equals(current.getHost(), target.getHost())) {
  725. return target;
  726. }
  727. String cur = current.normalize().getPath();
  728. String dest = target.normalize().getPath();
  729. // TODO(hanwen): maybe (absolute, relative) should throw an exception.
  730. if (cur.startsWith(SLASH) != dest.startsWith(SLASH)) {
  731. return target;
  732. }
  733. while (cur.startsWith(SLASH)) {
  734. cur = cur.substring(1);
  735. }
  736. while (dest.startsWith(SLASH)) {
  737. dest = dest.substring(1);
  738. }
  739. if (cur.indexOf('/') == -1 || dest.indexOf('/') == -1) {
  740. // Avoid having to special-casing in the next two ifs.
  741. String prefix = "prefix/"; //$NON-NLS-1$
  742. cur = prefix + cur;
  743. dest = prefix + dest;
  744. }
  745. if (!cur.endsWith(SLASH)) {
  746. // The current file doesn't matter.
  747. int lastSlash = cur.lastIndexOf('/');
  748. cur = cur.substring(0, lastSlash);
  749. }
  750. String destFile = ""; //$NON-NLS-1$
  751. if (!dest.endsWith(SLASH)) {
  752. // We always have to provide the destination file.
  753. int lastSlash = dest.lastIndexOf('/');
  754. destFile = dest.substring(lastSlash + 1, dest.length());
  755. dest = dest.substring(0, dest.lastIndexOf('/'));
  756. }
  757. String[] cs = cur.split(SLASH);
  758. String[] ds = dest.split(SLASH);
  759. int common = 0;
  760. while (common < cs.length && common < ds.length && cs[common].equals(ds[common])) {
  761. common++;
  762. }
  763. StringJoiner j = new StringJoiner(SLASH);
  764. for (int i = common; i < cs.length; i++) {
  765. j.add(".."); //$NON-NLS-1$
  766. }
  767. for (int i = common; i < ds.length; i++) {
  768. j.add(ds[i]);
  769. }
  770. j.add(destFile);
  771. return URI.create(j.toString());
  772. }
  773. private static String findRef(String ref, Repository repo)
  774. throws IOException {
  775. if (!ObjectId.isId(ref)) {
  776. Ref r = repo.exactRef(R_REMOTES + DEFAULT_REMOTE_NAME + "/" + ref); //$NON-NLS-1$
  777. if (r != null)
  778. return r.getName();
  779. }
  780. return ref;
  781. }
  782. }