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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  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(remotes.get(defaultRemote));
  394. if (uri.getHost() != null) {
  395. // This is not relative path, no need for baseUrl.
  396. remoteUrl = uri.toString();
  397. } else {
  398. uri = new URI(baseUrl);
  399. remoteUrl = uri.resolve(
  400. remotes.get(defaultRemote)).toString();
  401. }
  402. } catch (URISyntaxException e) {
  403. throw new SAXException(e);
  404. }
  405. removeNotInGroup();
  406. removeOverlaps();
  407. for (Project proj : projects) {
  408. command.addSubmodule(remoteUrl + "/" + proj.name,
  409. proj.path,
  410. proj.revision == null
  411. ? defaultRevision : proj.revision,
  412. proj.copyfiles);
  413. }
  414. }
  415. /** Remove projects that are not in our desired groups. */
  416. void removeNotInGroup() {
  417. Iterator<Project> iter = projects.iterator();
  418. while (iter.hasNext())
  419. if (!inGroups(iter.next()))
  420. iter.remove();
  421. }
  422. /** Remove projects that sits in a subdirectory of any other project. */
  423. void removeOverlaps() {
  424. Collections.sort(projects);
  425. Iterator<Project> iter = projects.iterator();
  426. if (!iter.hasNext())
  427. return;
  428. Project last = iter.next();
  429. while (iter.hasNext()) {
  430. Project p = iter.next();
  431. if (last.isAncestorOf(p))
  432. iter.remove();
  433. else
  434. last = p;
  435. }
  436. }
  437. boolean inGroups(Project proj) {
  438. for (String group : minusGroups) {
  439. if (proj.groups.contains(group)) {
  440. // minus groups have highest priority.
  441. return false;
  442. }
  443. }
  444. if (plusGroups.isEmpty() || plusGroups.contains("all")) { //$NON-NLS-1$
  445. // empty plus groups means "all"
  446. return true;
  447. }
  448. for (String group : plusGroups) {
  449. if (proj.groups.contains(group))
  450. return true;
  451. }
  452. return false;
  453. }
  454. }
  455. private static class ManifestErrorException extends GitAPIException {
  456. ManifestErrorException(Throwable cause) {
  457. super(RepoText.get().invalidManifest, cause);
  458. }
  459. }
  460. private static class RemoteUnavailableException extends GitAPIException {
  461. RemoteUnavailableException(String uri) {
  462. super(MessageFormat.format(RepoText.get().errorRemoteUnavailable, uri));
  463. }
  464. }
  465. /**
  466. * @param repo
  467. */
  468. public RepoCommand(final Repository repo) {
  469. super(repo);
  470. }
  471. /**
  472. * Set path to the manifest XML file.
  473. *
  474. * Calling {@link #setInputStream} will ignore the path set here.
  475. *
  476. * @param path
  477. * (with <code>/</code> as separator)
  478. * @return this command
  479. */
  480. public RepoCommand setPath(final String path) {
  481. this.path = path;
  482. return this;
  483. }
  484. /**
  485. * Set the input stream to the manifest XML.
  486. *
  487. * Setting inputStream will ignore the path set. It will be closed in
  488. * {@link #call}.
  489. *
  490. * @param inputStream
  491. * @return this command
  492. * @since 3.5
  493. */
  494. public RepoCommand setInputStream(final InputStream inputStream) {
  495. this.inputStream = inputStream;
  496. return this;
  497. }
  498. /**
  499. * Set base URI of the pathes inside the XML
  500. *
  501. * @param uri
  502. * @return this command
  503. */
  504. public RepoCommand setURI(final String uri) {
  505. this.uri = uri;
  506. return this;
  507. }
  508. /**
  509. * Set groups to sync
  510. *
  511. * @param groups groups separated by comma, examples: default|all|G1,-G2,-G3
  512. * @return this command
  513. */
  514. public RepoCommand setGroups(final String groups) {
  515. this.groups = groups;
  516. return this;
  517. }
  518. /**
  519. * Set default branch.
  520. *
  521. * This is generally the name of the branch the manifest file was in. If
  522. * there's no default revision (branch) specified in manifest and no
  523. * revision specified in project, this branch will be used.
  524. *
  525. * @param branch
  526. * @return this command
  527. */
  528. public RepoCommand setBranch(final String branch) {
  529. this.branch = branch;
  530. return this;
  531. }
  532. /**
  533. * The progress monitor associated with the clone operation. By default,
  534. * this is set to <code>NullProgressMonitor</code>
  535. *
  536. * @see org.eclipse.jgit.lib.NullProgressMonitor
  537. * @param monitor
  538. * @return this command
  539. */
  540. public RepoCommand setProgressMonitor(final ProgressMonitor monitor) {
  541. this.monitor = monitor;
  542. return this;
  543. }
  544. /**
  545. * Set the author/committer for the bare repository commit.
  546. *
  547. * For non-bare repositories, the current user will be used and this will be
  548. * ignored.
  549. *
  550. * @param author
  551. * @return this command
  552. */
  553. public RepoCommand setAuthor(final PersonIdent author) {
  554. this.author = author;
  555. return this;
  556. }
  557. /**
  558. * Set the GetHeadFromUri callback.
  559. *
  560. * This is only used in bare repositories.
  561. *
  562. * @param callback
  563. * @return this command
  564. */
  565. public RepoCommand setRemoteReader(final RemoteReader callback) {
  566. this.callback = callback;
  567. return this;
  568. }
  569. @Override
  570. public RevCommit call() throws GitAPIException {
  571. try {
  572. checkCallable();
  573. if (uri == null || uri.length() == 0)
  574. throw new IllegalArgumentException(
  575. JGitText.get().uriNotConfigured);
  576. if (inputStream == null) {
  577. if (path == null || path.length() == 0)
  578. throw new IllegalArgumentException(
  579. JGitText.get().pathNotConfigured);
  580. try {
  581. inputStream = new FileInputStream(path);
  582. } catch (IOException e) {
  583. throw new IllegalArgumentException(
  584. JGitText.get().pathNotConfigured);
  585. }
  586. }
  587. if (repo.isBare()) {
  588. bareProjects = new ArrayList<Project>();
  589. if (author == null)
  590. author = new PersonIdent(repo);
  591. if (callback == null)
  592. callback = new DefaultRemoteReader();
  593. } else
  594. git = new Git(repo);
  595. XmlManifest manifest = new XmlManifest(
  596. this, inputStream, path, uri, groups);
  597. try {
  598. manifest.read();
  599. } catch (IOException e) {
  600. throw new ManifestErrorException(e);
  601. }
  602. } finally {
  603. try {
  604. if (inputStream != null)
  605. inputStream.close();
  606. } catch (IOException e) {
  607. // Just ignore it, it's not important.
  608. }
  609. }
  610. if (repo.isBare()) {
  611. DirCache index = DirCache.newInCore();
  612. DirCacheBuilder builder = index.builder();
  613. ObjectInserter inserter = repo.newObjectInserter();
  614. RevWalk rw = new RevWalk(repo);
  615. try {
  616. Config cfg = new Config();
  617. for (Project proj : bareProjects) {
  618. String name = proj.path;
  619. String uri = proj.name;
  620. cfg.setString("submodule", name, "path", name); //$NON-NLS-1$ //$NON-NLS-2$
  621. cfg.setString("submodule", name, "url", uri); //$NON-NLS-1$ //$NON-NLS-2$
  622. // create gitlink
  623. DirCacheEntry dcEntry = new DirCacheEntry(name);
  624. ObjectId objectId;
  625. if (ObjectId.isId(proj.revision))
  626. objectId = ObjectId.fromString(proj.revision);
  627. else {
  628. objectId = callback.sha1(uri, proj.revision);
  629. }
  630. if (objectId == null)
  631. throw new RemoteUnavailableException(uri);
  632. dcEntry.setObjectId(objectId);
  633. dcEntry.setFileMode(FileMode.GITLINK);
  634. builder.add(dcEntry);
  635. for (CopyFile copyfile : proj.copyfiles) {
  636. byte[] src = callback.readFile(
  637. uri, proj.revision, copyfile.src);
  638. objectId = inserter.insert(Constants.OBJ_BLOB, src);
  639. dcEntry = new DirCacheEntry(copyfile.dest);
  640. dcEntry.setObjectId(objectId);
  641. dcEntry.setFileMode(FileMode.REGULAR_FILE);
  642. builder.add(dcEntry);
  643. }
  644. }
  645. String content = cfg.toText();
  646. // create a new DirCacheEntry for .gitmodules file.
  647. final DirCacheEntry dcEntry = new DirCacheEntry(Constants.DOT_GIT_MODULES);
  648. ObjectId objectId = inserter.insert(Constants.OBJ_BLOB,
  649. content.getBytes(Constants.CHARACTER_ENCODING));
  650. dcEntry.setObjectId(objectId);
  651. dcEntry.setFileMode(FileMode.REGULAR_FILE);
  652. builder.add(dcEntry);
  653. builder.finish();
  654. ObjectId treeId = index.writeTree(inserter);
  655. // Create a Commit object, populate it and write it
  656. ObjectId headId = repo.resolve(Constants.HEAD + "^{commit}"); //$NON-NLS-1$
  657. CommitBuilder commit = new CommitBuilder();
  658. commit.setTreeId(treeId);
  659. if (headId != null)
  660. commit.setParentIds(headId);
  661. commit.setAuthor(author);
  662. commit.setCommitter(author);
  663. commit.setMessage(RepoText.get().repoCommitMessage);
  664. ObjectId commitId = inserter.insert(commit);
  665. inserter.flush();
  666. RefUpdate ru = repo.updateRef(Constants.HEAD);
  667. ru.setNewObjectId(commitId);
  668. ru.setExpectedOldObjectId(headId != null ? headId : ObjectId.zeroId());
  669. Result rc = ru.update(rw);
  670. switch (rc) {
  671. case NEW:
  672. case FORCED:
  673. case FAST_FORWARD:
  674. // Successful. Do nothing.
  675. break;
  676. case REJECTED:
  677. case LOCK_FAILURE:
  678. throw new ConcurrentRefUpdateException(
  679. JGitText.get().couldNotLockHEAD, ru.getRef(),
  680. rc);
  681. default:
  682. throw new JGitInternalException(MessageFormat.format(
  683. JGitText.get().updatingRefFailed,
  684. Constants.HEAD, commitId.name(), rc));
  685. }
  686. return rw.parseCommit(commitId);
  687. } catch (IOException e) {
  688. throw new ManifestErrorException(e);
  689. } finally {
  690. rw.release();
  691. }
  692. } else {
  693. return git
  694. .commit()
  695. .setMessage(RepoText.get().repoCommitMessage)
  696. .call();
  697. }
  698. }
  699. private void addSubmodule(String url, String name, String revision,
  700. List<CopyFile> copyfiles) throws SAXException {
  701. if (repo.isBare()) {
  702. Project proj = new Project(url, name, revision, null);
  703. proj.copyfiles.addAll(copyfiles);
  704. bareProjects.add(proj);
  705. } else {
  706. SubmoduleAddCommand add = git
  707. .submoduleAdd()
  708. .setPath(name)
  709. .setURI(url);
  710. if (monitor != null)
  711. add.setProgressMonitor(monitor);
  712. try {
  713. Repository subRepo = add.call();
  714. if (revision != null) {
  715. Git sub = new Git(subRepo);
  716. sub.checkout().setName(findRef(revision, subRepo)).call();
  717. git.add().addFilepattern(name).call();
  718. }
  719. for (CopyFile copyfile : copyfiles) {
  720. copyfile.copy();
  721. git.add().addFilepattern(copyfile.dest).call();
  722. }
  723. } catch (GitAPIException e) {
  724. throw new SAXException(e);
  725. } catch (IOException e) {
  726. throw new SAXException(e);
  727. }
  728. }
  729. }
  730. private static String findRef(String ref, Repository repo)
  731. throws IOException {
  732. if (!ObjectId.isId(ref)) {
  733. Ref r = repo.getRef(
  734. Constants.DEFAULT_REMOTE_NAME + "/" + ref);
  735. if (r != null)
  736. return r.getName();
  737. }
  738. return ref;
  739. }
  740. }