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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  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 org.eclipse.jgit.lib.Constants.DEFAULT_REMOTE_NAME;
  45. import static org.eclipse.jgit.lib.Constants.R_REMOTES;
  46. import java.io.File;
  47. import java.io.FileInputStream;
  48. import java.io.IOException;
  49. import java.io.InputStream;
  50. import java.net.URI;
  51. import java.text.MessageFormat;
  52. import java.util.ArrayList;
  53. import java.util.List;
  54. import java.util.Map;
  55. import java.util.Set;
  56. import java.util.StringJoiner;
  57. import org.eclipse.jgit.annotations.Nullable;
  58. import org.eclipse.jgit.api.Git;
  59. import org.eclipse.jgit.api.GitCommand;
  60. import org.eclipse.jgit.api.SubmoduleAddCommand;
  61. import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
  62. import org.eclipse.jgit.api.errors.GitAPIException;
  63. import org.eclipse.jgit.api.errors.JGitInternalException;
  64. import org.eclipse.jgit.dircache.DirCache;
  65. import org.eclipse.jgit.dircache.DirCacheBuilder;
  66. import org.eclipse.jgit.dircache.DirCacheEntry;
  67. import org.eclipse.jgit.gitrepo.ManifestParser.IncludedFileReader;
  68. import org.eclipse.jgit.gitrepo.RepoProject.CopyFile;
  69. import org.eclipse.jgit.gitrepo.internal.RepoText;
  70. import org.eclipse.jgit.internal.JGitText;
  71. import org.eclipse.jgit.lib.CommitBuilder;
  72. import org.eclipse.jgit.lib.Config;
  73. import org.eclipse.jgit.lib.Constants;
  74. import org.eclipse.jgit.lib.FileMode;
  75. import org.eclipse.jgit.lib.ObjectId;
  76. import org.eclipse.jgit.lib.ObjectInserter;
  77. import org.eclipse.jgit.lib.ObjectReader;
  78. import org.eclipse.jgit.lib.PersonIdent;
  79. import org.eclipse.jgit.lib.ProgressMonitor;
  80. import org.eclipse.jgit.lib.Ref;
  81. import org.eclipse.jgit.lib.RefDatabase;
  82. import org.eclipse.jgit.lib.RefUpdate;
  83. import org.eclipse.jgit.lib.RefUpdate.Result;
  84. import org.eclipse.jgit.lib.Repository;
  85. import org.eclipse.jgit.revwalk.RevCommit;
  86. import org.eclipse.jgit.revwalk.RevWalk;
  87. import org.eclipse.jgit.util.FileUtils;
  88. /**
  89. * A class used to execute a repo command.
  90. *
  91. * This will parse a repo XML manifest, convert it into .gitmodules file and the
  92. * repository config file.
  93. *
  94. * If called against a bare repository, it will replace all the existing content
  95. * of the repository with the contents populated from the manifest.
  96. *
  97. * repo manifest allows projects overlapping, e.g. one project's manifestPath is
  98. * "foo" and another project's manifestPath is "foo/bar". This won't
  99. * work in git submodule, so we'll skip all the sub projects
  100. * ("foo/bar" in the example) while converting.
  101. *
  102. * @see <a href="https://code.google.com/p/git-repo/">git-repo project page</a>
  103. * @since 3.4
  104. */
  105. public class RepoCommand extends GitCommand<RevCommit> {
  106. private String manifestPath;
  107. private String baseUri;
  108. private URI targetUri;
  109. private String groupsParam;
  110. private String branch;
  111. private String targetBranch = Constants.HEAD;
  112. private boolean recordRemoteBranch = false;
  113. private boolean recordSubmoduleLabels = false;
  114. private boolean recordShallowSubmodules = false;
  115. private PersonIdent author;
  116. private RemoteReader callback;
  117. private InputStream inputStream;
  118. private IncludedFileReader includedReader;
  119. private boolean ignoreRemoteFailures = false;
  120. private List<RepoProject> bareProjects;
  121. private Git git;
  122. private ProgressMonitor monitor;
  123. /**
  124. * A callback to get ref sha1 of a repository from its uri.
  125. *
  126. * We provided a default implementation {@link DefaultRemoteReader} to
  127. * use ls-remote command to read the sha1 from the repository and clone the
  128. * repository to read the file. Callers may have their own quicker
  129. * implementation.
  130. *
  131. * @since 3.4
  132. */
  133. public interface RemoteReader {
  134. /**
  135. * Read a remote ref sha1.
  136. *
  137. * @param uri
  138. * The URI of the remote repository
  139. * @param ref
  140. * The ref (branch/tag/etc.) to read
  141. * @return the sha1 of the remote repository, or null if the ref does
  142. * not exist.
  143. * @throws GitAPIException
  144. */
  145. @Nullable
  146. public ObjectId sha1(String uri, String ref) throws GitAPIException;
  147. /**
  148. * Read a file from a remote repository.
  149. *
  150. * @param uri
  151. * The URI of the remote repository
  152. * @param ref
  153. * The ref (branch/tag/etc.) to read
  154. * @param path
  155. * The relative path (inside the repo) to the file to read
  156. * @return the file content.
  157. * @throws GitAPIException
  158. * @throws IOException
  159. * @since 3.5
  160. */
  161. public byte[] readFile(String uri, String ref, String path)
  162. throws GitAPIException, IOException;
  163. }
  164. /** A default implementation of {@link RemoteReader} callback. */
  165. public static class DefaultRemoteReader implements RemoteReader {
  166. @Override
  167. public ObjectId sha1(String uri, String ref) throws GitAPIException {
  168. Map<String, Ref> map = Git
  169. .lsRemoteRepository()
  170. .setRemote(uri)
  171. .callAsMap();
  172. Ref r = RefDatabase.findRef(map, ref);
  173. return r != null ? r.getObjectId() : null;
  174. }
  175. @Override
  176. public byte[] readFile(String uri, String ref, String path)
  177. throws GitAPIException, IOException {
  178. File dir = FileUtils.createTempDir("jgit_", ".git", null); //$NON-NLS-1$ //$NON-NLS-2$
  179. try (Git git = Git.cloneRepository().setBare(true).setDirectory(dir)
  180. .setURI(uri).call()) {
  181. return readFileFromRepo(git.getRepository(), ref, path);
  182. } finally {
  183. FileUtils.delete(dir, FileUtils.RECURSIVE);
  184. }
  185. }
  186. /**
  187. * Read a file from the repository
  188. *
  189. * @param repo
  190. * The repository containing the file
  191. * @param ref
  192. * The ref (branch/tag/etc.) to read
  193. * @param path
  194. * The relative path (inside the repo) to the file to read
  195. * @return the file's content
  196. * @throws GitAPIException
  197. * @throws IOException
  198. * @since 3.5
  199. */
  200. protected byte[] readFileFromRepo(Repository repo,
  201. String ref, String path) throws GitAPIException, IOException {
  202. try (ObjectReader reader = repo.newObjectReader()) {
  203. ObjectId oid = repo.resolve(ref + ":" + path); //$NON-NLS-1$
  204. return reader.open(oid).getBytes(Integer.MAX_VALUE);
  205. }
  206. }
  207. }
  208. @SuppressWarnings("serial")
  209. private static class ManifestErrorException extends GitAPIException {
  210. ManifestErrorException(Throwable cause) {
  211. super(RepoText.get().invalidManifest, cause);
  212. }
  213. }
  214. @SuppressWarnings("serial")
  215. private static class RemoteUnavailableException extends GitAPIException {
  216. RemoteUnavailableException(String uri) {
  217. super(MessageFormat.format(RepoText.get().errorRemoteUnavailable, uri));
  218. }
  219. }
  220. /**
  221. * @param repo
  222. */
  223. public RepoCommand(Repository repo) {
  224. super(repo);
  225. }
  226. /**
  227. * Set path to the manifest XML file.
  228. * <p>
  229. * Calling {@link #setInputStream} will ignore the path set here.
  230. *
  231. * @param path
  232. * (with <code>/</code> as separator)
  233. * @return this command
  234. */
  235. public RepoCommand setPath(String path) {
  236. this.manifestPath = path;
  237. return this;
  238. }
  239. /**
  240. * Set the input stream to the manifest XML.
  241. * <p>
  242. * Setting inputStream will ignore the path set. It will be closed in
  243. * {@link #call}.
  244. *
  245. * @param inputStream
  246. * @return this command
  247. * @since 3.5
  248. */
  249. public RepoCommand setInputStream(InputStream inputStream) {
  250. this.inputStream = inputStream;
  251. return this;
  252. }
  253. /**
  254. * Set base URI of the paths inside the XML. This is typically the name of
  255. * the directory holding the manifest repository, eg. for
  256. * https://android.googlesource.com/platform/manifest, this should be
  257. * /platform (if you would run this on android.googlesource.com)
  258. * or https://android.googlesource.com/platform elsewhere.
  259. *
  260. * @param uri
  261. * @return this command
  262. */
  263. public RepoCommand setURI(String uri) {
  264. this.baseUri = uri;
  265. return this;
  266. }
  267. /**
  268. * Set the URI of the superproject (this repository), so the .gitmodules
  269. * file can specify the submodule URLs relative to the superproject.
  270. *
  271. * @param uri
  272. * the URI of the repository holding the superproject.
  273. * @return this command
  274. * @since 4.8
  275. */
  276. public RepoCommand setTargetURI(String uri) {
  277. // The repo name is interpreted as a directory, for example
  278. // Gerrit (http://gerrit.googlesource.com/gerrit) has a
  279. // .gitmodules referencing ../plugins/hooks, which is
  280. // on http://gerrit.googlesource.com/plugins/hooks,
  281. this.targetUri = URI.create(uri + "/"); //$NON-NLS-1$
  282. return this;
  283. }
  284. /**
  285. * Set groups to sync
  286. *
  287. * @param groups groups separated by comma, examples: default|all|G1,-G2,-G3
  288. * @return this command
  289. */
  290. public RepoCommand setGroups(String groups) {
  291. this.groupsParam = groups;
  292. return this;
  293. }
  294. /**
  295. * Set default branch.
  296. * <p>
  297. * This is generally the name of the branch the manifest file was in. If
  298. * there's no default revision (branch) specified in manifest and no
  299. * revision specified in project, this branch will be used.
  300. *
  301. * @param branch
  302. * @return this command
  303. */
  304. public RepoCommand setBranch(String branch) {
  305. this.branch = branch;
  306. return this;
  307. }
  308. /**
  309. * Set target branch.
  310. * <p>
  311. * This is the target branch of the super project to be updated. If not set,
  312. * default is HEAD.
  313. * <p>
  314. * For non-bare repositories, HEAD will always be used and this will be
  315. * ignored.
  316. *
  317. * @param branch
  318. * @return this command
  319. * @since 4.1
  320. */
  321. public RepoCommand setTargetBranch(String branch) {
  322. this.targetBranch = Constants.R_HEADS + branch;
  323. return this;
  324. }
  325. /**
  326. * Set whether the branch name should be recorded in .gitmodules.
  327. * <p>
  328. * Submodule entries in .gitmodules can include a "branch" field
  329. * to indicate what remote branch each submodule tracks.
  330. * <p>
  331. * That field is used by "git submodule update --remote" to update
  332. * to the tip of the tracked branch when asked and by Gerrit to
  333. * update the superproject when a change on that branch is merged.
  334. * <p>
  335. * Subprojects that request a specific commit or tag will not have
  336. * a branch name recorded.
  337. * <p>
  338. * Not implemented for non-bare repositories.
  339. *
  340. * @param enable Whether to record the branch name
  341. * @return this command
  342. * @since 4.2
  343. */
  344. public RepoCommand setRecordRemoteBranch(boolean enable) {
  345. this.recordRemoteBranch = enable;
  346. return this;
  347. }
  348. /**
  349. * Set whether the labels field should be recorded as a label in
  350. * .gitattributes.
  351. * <p>
  352. * Not implemented for non-bare repositories.
  353. *
  354. * @param enable Whether to record the labels in the .gitattributes
  355. * @return this command
  356. * @since 4.4
  357. */
  358. public RepoCommand setRecordSubmoduleLabels(boolean enable) {
  359. this.recordSubmoduleLabels = enable;
  360. return this;
  361. }
  362. /**
  363. * Set whether the clone-depth field should be recorded as a shallow
  364. * recommendation in .gitmodules.
  365. * <p>
  366. * Not implemented for non-bare repositories.
  367. *
  368. * @param enable Whether to record the shallow recommendation.
  369. * @return this command
  370. * @since 4.4
  371. */
  372. public RepoCommand setRecommendShallow(boolean enable) {
  373. this.recordShallowSubmodules = enable;
  374. return this;
  375. }
  376. /**
  377. * The progress monitor associated with the clone operation. By default,
  378. * this is set to <code>NullProgressMonitor</code>
  379. *
  380. * @see org.eclipse.jgit.lib.NullProgressMonitor
  381. * @param monitor
  382. * @return this command
  383. */
  384. public RepoCommand setProgressMonitor(final ProgressMonitor monitor) {
  385. this.monitor = monitor;
  386. return this;
  387. }
  388. /**
  389. * Set whether to skip projects whose commits don't exist remotely.
  390. * <p>
  391. * When set to true, we'll just skip the manifest entry and continue
  392. * on to the next one.
  393. * <p>
  394. * When set to false (default), we'll throw an error when remote
  395. * failures occur.
  396. * <p>
  397. * Not implemented for non-bare repositories.
  398. *
  399. * @param ignore Whether to ignore the remote failures.
  400. * @return this command
  401. * @since 4.3
  402. */
  403. public RepoCommand setIgnoreRemoteFailures(boolean ignore) {
  404. this.ignoreRemoteFailures = ignore;
  405. return this;
  406. }
  407. /**
  408. * Set the author/committer for the bare repository commit.
  409. * <p>
  410. * For non-bare repositories, the current user will be used and this will be
  411. * ignored.
  412. *
  413. * @param author
  414. * @return this command
  415. */
  416. public RepoCommand setAuthor(final PersonIdent author) {
  417. this.author = author;
  418. return this;
  419. }
  420. /**
  421. * Set the GetHeadFromUri callback.
  422. *
  423. * This is only used in bare repositories.
  424. *
  425. * @param callback
  426. * @return this command
  427. */
  428. public RepoCommand setRemoteReader(final RemoteReader callback) {
  429. this.callback = callback;
  430. return this;
  431. }
  432. /**
  433. * Set the IncludedFileReader callback.
  434. *
  435. * @param reader
  436. * @return this command
  437. * @since 4.0
  438. */
  439. public RepoCommand setIncludedFileReader(IncludedFileReader reader) {
  440. this.includedReader = reader;
  441. return this;
  442. }
  443. @Override
  444. public RevCommit call() throws GitAPIException {
  445. try {
  446. checkCallable();
  447. if (baseUri == null) {
  448. baseUri = ""; //$NON-NLS-1$
  449. }
  450. if (inputStream == null) {
  451. if (manifestPath == null || manifestPath.length() == 0)
  452. throw new IllegalArgumentException(
  453. JGitText.get().pathNotConfigured);
  454. try {
  455. inputStream = new FileInputStream(manifestPath);
  456. } catch (IOException e) {
  457. throw new IllegalArgumentException(
  458. JGitText.get().pathNotConfigured);
  459. }
  460. }
  461. if (repo.isBare()) {
  462. bareProjects = new ArrayList<>();
  463. if (author == null)
  464. author = new PersonIdent(repo);
  465. if (callback == null)
  466. callback = new DefaultRemoteReader();
  467. } else
  468. git = new Git(repo);
  469. ManifestParser parser = new ManifestParser(
  470. includedReader, manifestPath, branch, baseUri, groupsParam, repo);
  471. try {
  472. parser.read(inputStream);
  473. for (RepoProject proj : parser.getFilteredProjects()) {
  474. addSubmodule(proj.getUrl(),
  475. proj.getPath(),
  476. proj.getRevision(),
  477. proj.getCopyFiles(),
  478. proj.getGroups(),
  479. proj.getRecommendShallow());
  480. }
  481. } catch (GitAPIException | IOException e) {
  482. throw new ManifestErrorException(e);
  483. }
  484. } finally {
  485. try {
  486. if (inputStream != null)
  487. inputStream.close();
  488. } catch (IOException e) {
  489. // Just ignore it, it's not important.
  490. }
  491. }
  492. if (repo.isBare()) {
  493. DirCache index = DirCache.newInCore();
  494. DirCacheBuilder builder = index.builder();
  495. ObjectInserter inserter = repo.newObjectInserter();
  496. try (RevWalk rw = new RevWalk(repo)) {
  497. Config cfg = new Config();
  498. StringBuilder attributes = new StringBuilder();
  499. for (RepoProject proj : bareProjects) {
  500. String path = proj.getPath();
  501. String nameUri = proj.getName();
  502. ObjectId objectId;
  503. if (ObjectId.isId(proj.getRevision())
  504. && !ignoreRemoteFailures) {
  505. objectId = ObjectId.fromString(proj.getRevision());
  506. } else {
  507. objectId = callback.sha1(nameUri, proj.getRevision());
  508. if (objectId == null) {
  509. if (ignoreRemoteFailures) {
  510. continue;
  511. }
  512. throw new RemoteUnavailableException(nameUri);
  513. }
  514. if (recordRemoteBranch) {
  515. // can be branch or tag
  516. cfg.setString("submodule", path, "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", path, "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(nameUri);
  541. if (targetUri != null) {
  542. submodUrl = relativize(targetUri, submodUrl);
  543. }
  544. cfg.setString("submodule", path, "path", path); //$NON-NLS-1$ //$NON-NLS-2$
  545. cfg.setString("submodule", path, "url", submodUrl.toString()); //$NON-NLS-1$ //$NON-NLS-2$
  546. // create gitlink
  547. DirCacheEntry dcEntry = new DirCacheEntry(path);
  548. dcEntry.setObjectId(objectId);
  549. dcEntry.setFileMode(FileMode.GITLINK);
  550. builder.add(dcEntry);
  551. for (CopyFile copyfile : proj.getCopyFiles()) {
  552. byte[] src = callback.readFile(
  553. nameUri, proj.getRevision(), copyfile.src);
  554. objectId = inserter.insert(Constants.OBJ_BLOB, src);
  555. dcEntry = new DirCacheEntry(copyfile.dest);
  556. dcEntry.setObjectId(objectId);
  557. dcEntry.setFileMode(FileMode.REGULAR_FILE);
  558. builder.add(dcEntry);
  559. }
  560. }
  561. String content = cfg.toText();
  562. // create a new DirCacheEntry for .gitmodules file.
  563. final DirCacheEntry dcEntry = new DirCacheEntry(Constants.DOT_GIT_MODULES);
  564. ObjectId objectId = inserter.insert(Constants.OBJ_BLOB,
  565. content.getBytes(Constants.CHARACTER_ENCODING));
  566. dcEntry.setObjectId(objectId);
  567. dcEntry.setFileMode(FileMode.REGULAR_FILE);
  568. builder.add(dcEntry);
  569. if (recordSubmoduleLabels) {
  570. // create a new DirCacheEntry for .gitattributes file.
  571. final DirCacheEntry dcEntryAttr = new DirCacheEntry(Constants.DOT_GIT_ATTRIBUTES);
  572. ObjectId attrId = inserter.insert(Constants.OBJ_BLOB,
  573. attributes.toString().getBytes(Constants.CHARACTER_ENCODING));
  574. dcEntryAttr.setObjectId(attrId);
  575. dcEntryAttr.setFileMode(FileMode.REGULAR_FILE);
  576. builder.add(dcEntryAttr);
  577. }
  578. builder.finish();
  579. ObjectId treeId = index.writeTree(inserter);
  580. // Create a Commit object, populate it and write it
  581. ObjectId headId = repo.resolve(targetBranch + "^{commit}"); //$NON-NLS-1$
  582. CommitBuilder commit = new CommitBuilder();
  583. commit.setTreeId(treeId);
  584. if (headId != null)
  585. commit.setParentIds(headId);
  586. commit.setAuthor(author);
  587. commit.setCommitter(author);
  588. commit.setMessage(RepoText.get().repoCommitMessage);
  589. ObjectId commitId = inserter.insert(commit);
  590. inserter.flush();
  591. RefUpdate ru = repo.updateRef(targetBranch);
  592. ru.setNewObjectId(commitId);
  593. ru.setExpectedOldObjectId(headId != null ? headId : ObjectId.zeroId());
  594. Result rc = ru.update(rw);
  595. switch (rc) {
  596. case NEW:
  597. case FORCED:
  598. case FAST_FORWARD:
  599. // Successful. Do nothing.
  600. break;
  601. case REJECTED:
  602. case LOCK_FAILURE:
  603. throw new ConcurrentRefUpdateException(
  604. MessageFormat.format(
  605. JGitText.get().cannotLock, targetBranch),
  606. ru.getRef(),
  607. rc);
  608. default:
  609. throw new JGitInternalException(MessageFormat.format(
  610. JGitText.get().updatingRefFailed,
  611. targetBranch, commitId.name(), rc));
  612. }
  613. return rw.parseCommit(commitId);
  614. } catch (IOException e) {
  615. throw new ManifestErrorException(e);
  616. }
  617. } else {
  618. return git
  619. .commit()
  620. .setMessage(RepoText.get().repoCommitMessage)
  621. .call();
  622. }
  623. }
  624. private void addSubmodule(String url, String path, String revision,
  625. List<CopyFile> copyfiles, Set<String> groups, String recommendShallow)
  626. throws GitAPIException, IOException {
  627. if (repo.isBare()) {
  628. RepoProject proj = new RepoProject(url, path, revision, null, groups, recommendShallow);
  629. proj.addCopyFiles(copyfiles);
  630. bareProjects.add(proj);
  631. } else {
  632. SubmoduleAddCommand add = git
  633. .submoduleAdd()
  634. .setPath(path)
  635. .setURI(url);
  636. if (monitor != null)
  637. add.setProgressMonitor(monitor);
  638. Repository subRepo = add.call();
  639. if (revision != null) {
  640. try (Git sub = new Git(subRepo)) {
  641. sub.checkout().setName(findRef(revision, subRepo))
  642. .call();
  643. }
  644. subRepo.close();
  645. git.add().addFilepattern(path).call();
  646. }
  647. for (CopyFile copyfile : copyfiles) {
  648. copyfile.copy();
  649. git.add().addFilepattern(copyfile.dest).call();
  650. }
  651. }
  652. }
  653. /*
  654. * Assume we are document "a/b/index.html", what should we put in a href to get to "a/" ?
  655. * Returns the child if either base or child is not a bare path. This provides a missing feature in
  656. * java.net.URI (see http://bugs.java.com/view_bug.do?bug_id=6226081).
  657. */
  658. static URI relativize(URI current, URI target) {
  659. // We only handle bare paths for now.
  660. if (!target.toString().equals(target.getPath())) {
  661. return target;
  662. }
  663. if (!current.toString().equals(current.getPath())) {
  664. return target;
  665. }
  666. String cur = current.normalize().getPath();
  667. String dest = target.normalize().getPath();
  668. // TODO(hanwen): maybe (absolute, relative) should throw an exception.
  669. if (cur.startsWith("/") != dest.startsWith("/")) { //$NON-NLS-1$//$NON-NLS-2$
  670. return target;
  671. }
  672. while (cur.startsWith("/")) { //$NON-NLS-1$
  673. cur = cur.substring(1);
  674. }
  675. while (dest.startsWith("/")) { //$NON-NLS-1$
  676. dest = dest.substring(1);
  677. }
  678. if (!cur.endsWith("/")) { //$NON-NLS-1$
  679. // The current file doesn't matter.
  680. cur = cur.substring(0, cur.lastIndexOf('/'));
  681. }
  682. String destFile = ""; //$NON-NLS-1$
  683. if (!dest.endsWith("/")) { //$NON-NLS-1$
  684. // We always have to provide the destination file.
  685. destFile = dest.substring(dest.lastIndexOf('/') + 1, dest.length());
  686. dest = dest.substring(0, dest.lastIndexOf('/'));
  687. }
  688. String[] cs = cur.split("/"); //$NON-NLS-1$
  689. String[] ds = dest.split("/"); //$NON-NLS-1$
  690. int common = 0;
  691. while (common < cs.length && common < ds.length && cs[common].equals(ds[common])) {
  692. common++;
  693. }
  694. StringJoiner j = new StringJoiner("/"); //$NON-NLS-1$
  695. for (int i = common; i < cs.length; i++) {
  696. j.add(".."); //$NON-NLS-1$
  697. }
  698. for (int i = common; i < ds.length; i++) {
  699. j.add(ds[i]);
  700. }
  701. j.add(destFile);
  702. return URI.create(j.toString());
  703. }
  704. private static String findRef(String ref, Repository repo)
  705. throws IOException {
  706. if (!ObjectId.isId(ref)) {
  707. Ref r = repo.exactRef(R_REMOTES + DEFAULT_REMOTE_NAME + "/" + ref); //$NON-NLS-1$
  708. if (r != null)
  709. return r.getName();
  710. }
  711. return ref;
  712. }
  713. }