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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  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 java.io.File;
  45. import java.io.FileInputStream;
  46. import java.io.FileOutputStream;
  47. import java.io.IOException;
  48. import java.io.InputStream;
  49. import java.net.URI;
  50. import java.net.URISyntaxException;
  51. import java.nio.channels.FileChannel;
  52. import java.text.MessageFormat;
  53. import java.util.ArrayList;
  54. import java.util.Arrays;
  55. import java.util.Collections;
  56. import java.util.HashMap;
  57. import java.util.HashSet;
  58. import java.util.Iterator;
  59. import java.util.List;
  60. import java.util.Map;
  61. import java.util.Set;
  62. import org.eclipse.jgit.api.Git;
  63. import org.eclipse.jgit.api.GitCommand;
  64. import org.eclipse.jgit.api.SubmoduleAddCommand;
  65. import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
  66. import org.eclipse.jgit.api.errors.GitAPIException;
  67. import org.eclipse.jgit.api.errors.JGitInternalException;
  68. import org.eclipse.jgit.dircache.DirCache;
  69. import org.eclipse.jgit.dircache.DirCacheBuilder;
  70. import org.eclipse.jgit.dircache.DirCacheEntry;
  71. import org.eclipse.jgit.gitrepo.internal.RepoText;
  72. import org.eclipse.jgit.internal.JGitText;
  73. import org.eclipse.jgit.lib.CommitBuilder;
  74. import org.eclipse.jgit.lib.Config;
  75. import org.eclipse.jgit.lib.Constants;
  76. import org.eclipse.jgit.lib.FileMode;
  77. import org.eclipse.jgit.lib.ObjectId;
  78. import org.eclipse.jgit.lib.ObjectInserter;
  79. import org.eclipse.jgit.lib.ObjectReader;
  80. import org.eclipse.jgit.lib.PersonIdent;
  81. import org.eclipse.jgit.lib.ProgressMonitor;
  82. import org.eclipse.jgit.lib.Ref;
  83. import org.eclipse.jgit.lib.RefDatabase;
  84. import org.eclipse.jgit.lib.RefUpdate;
  85. import org.eclipse.jgit.lib.RefUpdate.Result;
  86. import org.eclipse.jgit.lib.Repository;
  87. import org.eclipse.jgit.revwalk.RevCommit;
  88. import org.eclipse.jgit.revwalk.RevWalk;
  89. import org.eclipse.jgit.util.FileUtils;
  90. import org.xml.sax.Attributes;
  91. import org.xml.sax.InputSource;
  92. import org.xml.sax.SAXException;
  93. import org.xml.sax.XMLReader;
  94. import org.xml.sax.helpers.DefaultHandler;
  95. import org.xml.sax.helpers.XMLReaderFactory;
  96. /**
  97. * A class used to execute a repo command.
  98. *
  99. * This will parse a repo XML manifest, convert it into .gitmodules file and the
  100. * repository config file.
  101. *
  102. * If called against a bare repository, it will replace all the existing content
  103. * of the repository with the contents populated from the manifest.
  104. *
  105. * repo manifest allows projects overlapping, e.g. one project's path is
  106. * "foo" and another project's path is "foo/bar". This won't
  107. * work in git submodule, so we'll skip all the sub projects
  108. * ("foo/bar" in the example) while converting.
  109. *
  110. * @see <a href="https://code.google.com/p/git-repo/">git-repo project page</a>
  111. * @since 3.4
  112. */
  113. public class RepoCommand extends GitCommand<RevCommit> {
  114. private String path;
  115. private String uri;
  116. private String groups;
  117. private String branch;
  118. private PersonIdent author;
  119. private RemoteReader callback;
  120. private InputStream inputStream;
  121. private List<Project> bareProjects;
  122. private Git git;
  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
  143. * @throws GitAPIException
  144. */
  145. public ObjectId sha1(String uri, String ref) throws GitAPIException;
  146. /**
  147. * Read a file from a remote repository.
  148. *
  149. * @param uri
  150. * The URI of the remote repository
  151. * @param ref
  152. * The ref (branch/tag/etc.) to read
  153. * @param path
  154. * The relative path (inside the repo) to the file to read
  155. * @return the file content.
  156. * @throws GitAPIException
  157. * @throws IOException
  158. */
  159. public byte[] readFile(String uri, String ref, String path)
  160. throws GitAPIException, IOException;
  161. }
  162. /** A default implementation of {@link RemoteReader} callback. */
  163. public static class DefaultRemoteReader implements RemoteReader {
  164. public ObjectId sha1(String uri, String ref) throws GitAPIException {
  165. Map<String, Ref> map = Git
  166. .lsRemoteRepository()
  167. .setRemote(uri)
  168. .callAsMap();
  169. Ref r = RefDatabase.findRef(map, ref);
  170. return r != null ? r.getObjectId() : null;
  171. }
  172. public byte[] readFile(String uri, String ref, String path)
  173. throws GitAPIException, IOException {
  174. File dir = FileUtils.createTempDir("jgit_", ".git", null); //$NON-NLS-1$ //$NON-NLS-2$
  175. Repository repo = Git
  176. .cloneRepository()
  177. .setBare(true)
  178. .setDirectory(dir)
  179. .setURI(uri)
  180. .call()
  181. .getRepository();
  182. try {
  183. return readFileFromRepo(repo, ref, path);
  184. } finally {
  185. FileUtils.delete(dir, FileUtils.RECURSIVE);
  186. }
  187. }
  188. /**
  189. * Read a file from the repository
  190. *
  191. * @param repo
  192. * The repository containing the file
  193. * @param ref
  194. * The ref (branch/tag/etc.) to read
  195. * @param path
  196. * The relative path (inside the repo) to the file to read
  197. * @return the file's content
  198. * @throws GitAPIException
  199. * @throws IOException
  200. * @since 3.5
  201. */
  202. protected byte[] readFileFromRepo(Repository repo,
  203. String ref, String path) throws GitAPIException, IOException {
  204. ObjectReader reader = repo.newObjectReader();
  205. byte[] result;
  206. try {
  207. ObjectId oid = repo.resolve(ref + ":" + path); //$NON-NLS-1$
  208. result = reader.open(oid).getBytes(Integer.MAX_VALUE);
  209. } finally {
  210. reader.release();
  211. }
  212. return result;
  213. }
  214. }
  215. private static class CopyFile {
  216. final Repository repo;
  217. final String path;
  218. final String src;
  219. final String dest;
  220. CopyFile(Repository repo, String path, String src, String dest) {
  221. this.repo = repo;
  222. this.path = path;
  223. this.src = src;
  224. this.dest = dest;
  225. }
  226. void copy() throws IOException {
  227. File srcFile = new File(repo.getWorkTree(),
  228. path + "/" + src); //$NON-NLS-1$
  229. File destFile = new File(repo.getWorkTree(), dest);
  230. FileInputStream input = new FileInputStream(srcFile);
  231. try {
  232. FileOutputStream output = new FileOutputStream(destFile);
  233. try {
  234. FileChannel channel = input.getChannel();
  235. output.getChannel().transferFrom(channel, 0, channel.size());
  236. } finally {
  237. output.close();
  238. }
  239. } finally {
  240. input.close();
  241. }
  242. }
  243. }
  244. private static class Project implements Comparable<Project> {
  245. final String name;
  246. final String path;
  247. final String revision;
  248. final Set<String> groups;
  249. final List<CopyFile> copyfiles;
  250. Project(String name, String path, String revision, String groups) {
  251. this.name = name;
  252. this.path = path;
  253. this.revision = revision;
  254. this.groups = new HashSet<String>();
  255. if (groups != null && groups.length() > 0)
  256. this.groups.addAll(Arrays.asList(groups.split(","))); //$NON-NLS-1$
  257. copyfiles = new ArrayList<CopyFile>();
  258. }
  259. void addCopyFile(CopyFile copyfile) {
  260. copyfiles.add(copyfile);
  261. }
  262. String getPathWithSlash() {
  263. if (path.endsWith("/")) //$NON-NLS-1$
  264. return path;
  265. else
  266. return path + "/"; //$NON-NLS-1$
  267. }
  268. boolean isAncestorOf(Project that) {
  269. return that.getPathWithSlash().startsWith(this.getPathWithSlash());
  270. }
  271. @Override
  272. public boolean equals(Object o) {
  273. if (o instanceof Project) {
  274. Project that = (Project) o;
  275. return this.getPathWithSlash().equals(that.getPathWithSlash());
  276. }
  277. return false;
  278. }
  279. @Override
  280. public int hashCode() {
  281. return this.getPathWithSlash().hashCode();
  282. }
  283. public int compareTo(Project that) {
  284. return this.getPathWithSlash().compareTo(that.getPathWithSlash());
  285. }
  286. }
  287. private static class XmlManifest extends DefaultHandler {
  288. private final RepoCommand command;
  289. private final InputStream inputStream;
  290. private final String filename;
  291. private final String baseUrl;
  292. private final Map<String, String> remotes;
  293. private final Set<String> plusGroups;
  294. private final Set<String> minusGroups;
  295. private List<Project> projects;
  296. private String defaultRemote;
  297. private String defaultRevision;
  298. private Project currentProject;
  299. XmlManifest(RepoCommand command, InputStream inputStream,
  300. String filename, String baseUrl, String groups) {
  301. this.command = command;
  302. this.inputStream = inputStream;
  303. this.filename = filename;
  304. // Strip trailing /s to match repo behavior.
  305. int lastIndex = baseUrl.length() - 1;
  306. while (lastIndex >= 0 && baseUrl.charAt(lastIndex) == '/')
  307. lastIndex--;
  308. this.baseUrl = baseUrl.substring(0, lastIndex + 1);
  309. remotes = new HashMap<String, String>();
  310. projects = new ArrayList<Project>();
  311. plusGroups = new HashSet<String>();
  312. minusGroups = new HashSet<String>();
  313. if (groups == null || groups.length() == 0 || groups.equals("default")) { //$NON-NLS-1$
  314. // default means "all,-notdefault"
  315. minusGroups.add("notdefault"); //$NON-NLS-1$
  316. } else {
  317. for (String group : groups.split(",")) { //$NON-NLS-1$
  318. if (group.startsWith("-")) //$NON-NLS-1$
  319. minusGroups.add(group.substring(1));
  320. else
  321. plusGroups.add(group);
  322. }
  323. }
  324. }
  325. void read() throws IOException {
  326. final XMLReader xr;
  327. try {
  328. xr = XMLReaderFactory.createXMLReader();
  329. } catch (SAXException e) {
  330. throw new IOException(JGitText.get().noXMLParserAvailable);
  331. }
  332. xr.setContentHandler(this);
  333. try {
  334. xr.parse(new InputSource(inputStream));
  335. } catch (SAXException e) {
  336. IOException error = new IOException(
  337. RepoText.get().errorParsingManifestFile);
  338. error.initCause(e);
  339. throw error;
  340. }
  341. }
  342. @Override
  343. public void startElement(
  344. String uri,
  345. String localName,
  346. String qName,
  347. Attributes attributes) throws SAXException {
  348. if ("project".equals(qName)) { //$NON-NLS-1$
  349. currentProject = new Project(
  350. attributes.getValue("name"), //$NON-NLS-1$
  351. attributes.getValue("path"), //$NON-NLS-1$
  352. attributes.getValue("revision"), //$NON-NLS-1$
  353. attributes.getValue("groups")); //$NON-NLS-1$
  354. } else if ("remote".equals(qName)) { //$NON-NLS-1$
  355. remotes.put(attributes.getValue("name"), //$NON-NLS-1$
  356. attributes.getValue("fetch")); //$NON-NLS-1$
  357. } else if ("default".equals(qName)) { //$NON-NLS-1$
  358. defaultRemote = attributes.getValue("remote"); //$NON-NLS-1$
  359. defaultRevision = attributes.getValue("revision"); //$NON-NLS-1$
  360. if (defaultRevision == null)
  361. defaultRevision = command.branch;
  362. } else if ("copyfile".equals(qName)) { //$NON-NLS-1$
  363. if (currentProject == null)
  364. throw new SAXException(RepoText.get().invalidManifest);
  365. currentProject.addCopyFile(new CopyFile(
  366. command.repo,
  367. currentProject.path,
  368. attributes.getValue("src"), //$NON-NLS-1$
  369. attributes.getValue("dest"))); //$NON-NLS-1$
  370. }
  371. }
  372. @Override
  373. public void endElement(
  374. String uri,
  375. String localName,
  376. String qName) throws SAXException {
  377. if ("project".equals(qName)) { //$NON-NLS-1$
  378. projects.add(currentProject);
  379. currentProject = null;
  380. }
  381. }
  382. @Override
  383. public void endDocument() throws SAXException {
  384. if (defaultRemote == null) {
  385. if (filename != null)
  386. throw new SAXException(MessageFormat.format(
  387. RepoText.get().errorNoDefaultFilename, filename));
  388. else
  389. throw new SAXException(RepoText.get().errorNoDefault);
  390. }
  391. final String remoteUrl;
  392. try {
  393. URI uri = new URI(baseUrl);
  394. remoteUrl = uri.resolve(remotes.get(defaultRemote)).toString();
  395. } catch (URISyntaxException e) {
  396. throw new SAXException(e);
  397. }
  398. removeNotInGroup();
  399. removeOverlaps();
  400. for (Project proj : projects) {
  401. command.addSubmodule(remoteUrl + proj.name,
  402. proj.path,
  403. proj.revision == null
  404. ? defaultRevision : proj.revision,
  405. proj.copyfiles);
  406. }
  407. }
  408. /** Remove projects that are not in our desired groups. */
  409. void removeNotInGroup() {
  410. Iterator<Project> iter = projects.iterator();
  411. while (iter.hasNext())
  412. if (!inGroups(iter.next()))
  413. iter.remove();
  414. }
  415. /** Remove projects that sits in a subdirectory of any other project. */
  416. void removeOverlaps() {
  417. Collections.sort(projects);
  418. Iterator<Project> iter = projects.iterator();
  419. if (!iter.hasNext())
  420. return;
  421. Project last = iter.next();
  422. while (iter.hasNext()) {
  423. Project p = iter.next();
  424. if (last.isAncestorOf(p))
  425. iter.remove();
  426. else
  427. last = p;
  428. }
  429. }
  430. boolean inGroups(Project proj) {
  431. for (String group : minusGroups) {
  432. if (proj.groups.contains(group)) {
  433. // minus groups have highest priority.
  434. return false;
  435. }
  436. }
  437. if (plusGroups.isEmpty() || plusGroups.contains("all")) { //$NON-NLS-1$
  438. // empty plus groups means "all"
  439. return true;
  440. }
  441. for (String group : plusGroups) {
  442. if (proj.groups.contains(group))
  443. return true;
  444. }
  445. return false;
  446. }
  447. }
  448. private static class ManifestErrorException extends GitAPIException {
  449. ManifestErrorException(Throwable cause) {
  450. super(RepoText.get().invalidManifest, cause);
  451. }
  452. }
  453. private static class RemoteUnavailableException extends GitAPIException {
  454. RemoteUnavailableException(String uri) {
  455. super(MessageFormat.format(RepoText.get().errorRemoteUnavailable, uri));
  456. }
  457. }
  458. /**
  459. * @param repo
  460. */
  461. public RepoCommand(final Repository repo) {
  462. super(repo);
  463. }
  464. /**
  465. * Set path to the manifest XML file.
  466. *
  467. * Calling {@link #setInputStream} will ignore the path set here.
  468. *
  469. * @param path
  470. * (with <code>/</code> as separator)
  471. * @return this command
  472. */
  473. public RepoCommand setPath(final String path) {
  474. this.path = path;
  475. return this;
  476. }
  477. /**
  478. * Set the input stream to the manifest XML.
  479. *
  480. * Setting inputStream will ignore the path set. It will be closed in
  481. * {@link #call}.
  482. *
  483. * @param inputStream
  484. * @return this command
  485. * @since 3.5
  486. */
  487. public RepoCommand setInputStream(final InputStream inputStream) {
  488. this.inputStream = inputStream;
  489. return this;
  490. }
  491. /**
  492. * Set base URI of the pathes inside the XML
  493. *
  494. * @param uri
  495. * @return this command
  496. */
  497. public RepoCommand setURI(final String uri) {
  498. this.uri = uri;
  499. return this;
  500. }
  501. /**
  502. * Set groups to sync
  503. *
  504. * @param groups groups separated by comma, examples: default|all|G1,-G2,-G3
  505. * @return this command
  506. */
  507. public RepoCommand setGroups(final String groups) {
  508. this.groups = groups;
  509. return this;
  510. }
  511. /**
  512. * Set default branch.
  513. *
  514. * This is generally the name of the branch the manifest file was in. If
  515. * there's no default revision (branch) specified in manifest and no
  516. * revision specified in project, this branch will be used.
  517. *
  518. * @param branch
  519. * @return this command
  520. */
  521. public RepoCommand setBranch(final String branch) {
  522. this.branch = branch;
  523. return this;
  524. }
  525. /**
  526. * The progress monitor associated with the clone operation. By default,
  527. * this is set to <code>NullProgressMonitor</code>
  528. *
  529. * @see org.eclipse.jgit.lib.NullProgressMonitor
  530. * @param monitor
  531. * @return this command
  532. */
  533. public RepoCommand setProgressMonitor(final ProgressMonitor monitor) {
  534. this.monitor = monitor;
  535. return this;
  536. }
  537. /**
  538. * Set the author/committer for the bare repository commit.
  539. *
  540. * For non-bare repositories, the current user will be used and this will be
  541. * ignored.
  542. *
  543. * @param author
  544. * @return this command
  545. */
  546. public RepoCommand setAuthor(final PersonIdent author) {
  547. this.author = author;
  548. return this;
  549. }
  550. /**
  551. * Set the GetHeadFromUri callback.
  552. *
  553. * This is only used in bare repositories.
  554. *
  555. * @param callback
  556. * @return this command
  557. */
  558. public RepoCommand setRemoteReader(final RemoteReader callback) {
  559. this.callback = callback;
  560. return this;
  561. }
  562. @Override
  563. public RevCommit call() throws GitAPIException {
  564. try {
  565. checkCallable();
  566. if (uri == null || uri.length() == 0)
  567. throw new IllegalArgumentException(
  568. JGitText.get().uriNotConfigured);
  569. if (inputStream == null) {
  570. if (path == null || path.length() == 0)
  571. throw new IllegalArgumentException(
  572. JGitText.get().pathNotConfigured);
  573. try {
  574. inputStream = new FileInputStream(path);
  575. } catch (IOException e) {
  576. throw new IllegalArgumentException(
  577. JGitText.get().pathNotConfigured);
  578. }
  579. }
  580. if (repo.isBare()) {
  581. bareProjects = new ArrayList<Project>();
  582. if (author == null)
  583. author = new PersonIdent(repo);
  584. if (callback == null)
  585. callback = new DefaultRemoteReader();
  586. } else
  587. git = new Git(repo);
  588. XmlManifest manifest = new XmlManifest(
  589. this, inputStream, path, uri, groups);
  590. try {
  591. manifest.read();
  592. } catch (IOException e) {
  593. throw new ManifestErrorException(e);
  594. }
  595. } finally {
  596. try {
  597. if (inputStream != null)
  598. inputStream.close();
  599. } catch (IOException e) {
  600. // Just ignore it, it's not important.
  601. }
  602. }
  603. if (repo.isBare()) {
  604. DirCache index = DirCache.newInCore();
  605. DirCacheBuilder builder = index.builder();
  606. ObjectInserter inserter = repo.newObjectInserter();
  607. RevWalk rw = new RevWalk(repo);
  608. try {
  609. Config cfg = new Config();
  610. for (Project proj : bareProjects) {
  611. String name = proj.path;
  612. String uri = proj.name;
  613. cfg.setString("submodule", name, "path", name); //$NON-NLS-1$ //$NON-NLS-2$
  614. cfg.setString("submodule", name, "url", uri); //$NON-NLS-1$ //$NON-NLS-2$
  615. // create gitlink
  616. DirCacheEntry dcEntry = new DirCacheEntry(name);
  617. ObjectId objectId;
  618. if (ObjectId.isId(proj.revision))
  619. objectId = ObjectId.fromString(proj.revision);
  620. else {
  621. objectId = callback.sha1(uri, proj.revision);
  622. }
  623. if (objectId == null)
  624. throw new RemoteUnavailableException(uri);
  625. dcEntry.setObjectId(objectId);
  626. dcEntry.setFileMode(FileMode.GITLINK);
  627. builder.add(dcEntry);
  628. for (CopyFile copyfile : proj.copyfiles) {
  629. byte[] src = callback.readFile(
  630. uri, proj.revision, copyfile.src);
  631. objectId = inserter.insert(Constants.OBJ_BLOB, src);
  632. dcEntry = new DirCacheEntry(copyfile.dest);
  633. dcEntry.setObjectId(objectId);
  634. dcEntry.setFileMode(FileMode.REGULAR_FILE);
  635. builder.add(dcEntry);
  636. }
  637. }
  638. String content = cfg.toText();
  639. // create a new DirCacheEntry for .gitmodules file.
  640. final DirCacheEntry dcEntry = new DirCacheEntry(Constants.DOT_GIT_MODULES);
  641. ObjectId objectId = inserter.insert(Constants.OBJ_BLOB,
  642. content.getBytes(Constants.CHARACTER_ENCODING));
  643. dcEntry.setObjectId(objectId);
  644. dcEntry.setFileMode(FileMode.REGULAR_FILE);
  645. builder.add(dcEntry);
  646. builder.finish();
  647. ObjectId treeId = index.writeTree(inserter);
  648. // Create a Commit object, populate it and write it
  649. ObjectId headId = repo.resolve(Constants.HEAD + "^{commit}"); //$NON-NLS-1$
  650. CommitBuilder commit = new CommitBuilder();
  651. commit.setTreeId(treeId);
  652. if (headId != null)
  653. commit.setParentIds(headId);
  654. commit.setAuthor(author);
  655. commit.setCommitter(author);
  656. commit.setMessage(RepoText.get().repoCommitMessage);
  657. ObjectId commitId = inserter.insert(commit);
  658. inserter.flush();
  659. RefUpdate ru = repo.updateRef(Constants.HEAD);
  660. ru.setNewObjectId(commitId);
  661. ru.setExpectedOldObjectId(headId != null ? headId : ObjectId.zeroId());
  662. Result rc = ru.update(rw);
  663. switch (rc) {
  664. case NEW:
  665. case FORCED:
  666. case FAST_FORWARD:
  667. // Successful. Do nothing.
  668. break;
  669. case REJECTED:
  670. case LOCK_FAILURE:
  671. throw new ConcurrentRefUpdateException(
  672. JGitText.get().couldNotLockHEAD, ru.getRef(),
  673. rc);
  674. default:
  675. throw new JGitInternalException(MessageFormat.format(
  676. JGitText.get().updatingRefFailed,
  677. Constants.HEAD, commitId.name(), rc));
  678. }
  679. return rw.parseCommit(commitId);
  680. } catch (IOException e) {
  681. throw new ManifestErrorException(e);
  682. } finally {
  683. rw.release();
  684. }
  685. } else {
  686. return git
  687. .commit()
  688. .setMessage(RepoText.get().repoCommitMessage)
  689. .call();
  690. }
  691. }
  692. private void addSubmodule(String url, String name, String revision,
  693. List<CopyFile> copyfiles) throws SAXException {
  694. if (repo.isBare()) {
  695. Project proj = new Project(url, name, revision, null);
  696. proj.copyfiles.addAll(copyfiles);
  697. bareProjects.add(proj);
  698. } else {
  699. SubmoduleAddCommand add = git
  700. .submoduleAdd()
  701. .setPath(name)
  702. .setURI(url);
  703. if (monitor != null)
  704. add.setProgressMonitor(monitor);
  705. try {
  706. Repository subRepo = add.call();
  707. if (revision != null) {
  708. Git sub = new Git(subRepo);
  709. sub.checkout().setName(findRef(revision, subRepo)).call();
  710. git.add().addFilepattern(name).call();
  711. }
  712. for (CopyFile copyfile : copyfiles) {
  713. copyfile.copy();
  714. git.add().addFilepattern(copyfile.dest).call();
  715. }
  716. } catch (GitAPIException e) {
  717. throw new SAXException(e);
  718. } catch (IOException e) {
  719. throw new SAXException(e);
  720. }
  721. }
  722. }
  723. private static String findRef(String ref, Repository repo)
  724. throws IOException {
  725. if (!ObjectId.isId(ref)) {
  726. Ref r = repo.getRef(
  727. Constants.DEFAULT_REMOTE_NAME + "/" + ref);
  728. if (r != null)
  729. return r.getName();
  730. }
  731. return ref;
  732. }
  733. }