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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  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. public int compareTo(Project that) {
  280. return this.getPathWithSlash().compareTo(that.getPathWithSlash());
  281. }
  282. }
  283. private static class XmlManifest extends DefaultHandler {
  284. private final RepoCommand command;
  285. private final InputStream inputStream;
  286. private final String filename;
  287. private final String baseUrl;
  288. private final Map<String, String> remotes;
  289. private final Set<String> plusGroups;
  290. private final Set<String> minusGroups;
  291. private List<Project> projects;
  292. private String defaultRemote;
  293. private String defaultRevision;
  294. private Project currentProject;
  295. XmlManifest(RepoCommand command, InputStream inputStream,
  296. String filename, String baseUrl, String groups) {
  297. this.command = command;
  298. this.inputStream = inputStream;
  299. this.filename = filename;
  300. // Strip trailing /s to match repo behavior.
  301. int lastIndex = baseUrl.length() - 1;
  302. while (lastIndex >= 0 && baseUrl.charAt(lastIndex) == '/')
  303. lastIndex--;
  304. this.baseUrl = baseUrl.substring(0, lastIndex + 1);
  305. remotes = new HashMap<String, String>();
  306. projects = new ArrayList<Project>();
  307. plusGroups = new HashSet<String>();
  308. minusGroups = new HashSet<String>();
  309. if (groups == null || groups.length() == 0 || groups.equals("default")) { //$NON-NLS-1$
  310. // default means "all,-notdefault"
  311. minusGroups.add("notdefault"); //$NON-NLS-1$
  312. } else {
  313. for (String group : groups.split(",")) { //$NON-NLS-1$
  314. if (group.startsWith("-")) //$NON-NLS-1$
  315. minusGroups.add(group.substring(1));
  316. else
  317. plusGroups.add(group);
  318. }
  319. }
  320. }
  321. void read() throws IOException {
  322. final XMLReader xr;
  323. try {
  324. xr = XMLReaderFactory.createXMLReader();
  325. } catch (SAXException e) {
  326. throw new IOException(JGitText.get().noXMLParserAvailable);
  327. }
  328. xr.setContentHandler(this);
  329. try {
  330. xr.parse(new InputSource(inputStream));
  331. } catch (SAXException e) {
  332. IOException error = new IOException(
  333. RepoText.get().errorParsingManifestFile);
  334. error.initCause(e);
  335. throw error;
  336. }
  337. }
  338. @Override
  339. public void startElement(
  340. String uri,
  341. String localName,
  342. String qName,
  343. Attributes attributes) throws SAXException {
  344. if ("project".equals(qName)) { //$NON-NLS-1$
  345. currentProject = new Project(
  346. attributes.getValue("name"), //$NON-NLS-1$
  347. attributes.getValue("path"), //$NON-NLS-1$
  348. attributes.getValue("revision"), //$NON-NLS-1$
  349. attributes.getValue("groups")); //$NON-NLS-1$
  350. } else if ("remote".equals(qName)) { //$NON-NLS-1$
  351. remotes.put(attributes.getValue("name"), //$NON-NLS-1$
  352. attributes.getValue("fetch")); //$NON-NLS-1$
  353. } else if ("default".equals(qName)) { //$NON-NLS-1$
  354. defaultRemote = attributes.getValue("remote"); //$NON-NLS-1$
  355. defaultRevision = attributes.getValue("revision"); //$NON-NLS-1$
  356. if (defaultRevision == null)
  357. defaultRevision = command.branch;
  358. } else if ("copyfile".equals(qName)) { //$NON-NLS-1$
  359. if (currentProject == null)
  360. throw new SAXException(RepoText.get().invalidManifest);
  361. currentProject.addCopyFile(new CopyFile(
  362. command.repo,
  363. currentProject.path,
  364. attributes.getValue("src"), //$NON-NLS-1$
  365. attributes.getValue("dest"))); //$NON-NLS-1$
  366. }
  367. }
  368. @Override
  369. public void endElement(
  370. String uri,
  371. String localName,
  372. String qName) throws SAXException {
  373. if ("project".equals(qName)) { //$NON-NLS-1$
  374. projects.add(currentProject);
  375. currentProject = null;
  376. }
  377. }
  378. @Override
  379. public void endDocument() throws SAXException {
  380. if (defaultRemote == null) {
  381. if (filename != null)
  382. throw new SAXException(MessageFormat.format(
  383. RepoText.get().errorNoDefaultFilename, filename));
  384. else
  385. throw new SAXException(RepoText.get().errorNoDefault);
  386. }
  387. final String remoteUrl;
  388. try {
  389. URI uri = new URI(baseUrl);
  390. remoteUrl = uri.resolve(remotes.get(defaultRemote)).toString();
  391. } catch (URISyntaxException e) {
  392. throw new SAXException(e);
  393. }
  394. removeNotInGroup();
  395. removeOverlaps();
  396. for (Project proj : projects) {
  397. command.addSubmodule(remoteUrl + proj.name,
  398. proj.path,
  399. proj.revision == null
  400. ? defaultRevision : proj.revision,
  401. proj.copyfiles);
  402. }
  403. }
  404. /** Remove projects that are not in our desired groups. */
  405. void removeNotInGroup() {
  406. Iterator<Project> iter = projects.iterator();
  407. while (iter.hasNext())
  408. if (!inGroups(iter.next()))
  409. iter.remove();
  410. }
  411. /** Remove projects that sits in a subdirectory of any other project. */
  412. void removeOverlaps() {
  413. Collections.sort(projects);
  414. Iterator<Project> iter = projects.iterator();
  415. if (!iter.hasNext())
  416. return;
  417. Project last = iter.next();
  418. while (iter.hasNext()) {
  419. Project p = iter.next();
  420. if (last.isAncestorOf(p))
  421. iter.remove();
  422. else
  423. last = p;
  424. }
  425. }
  426. boolean inGroups(Project proj) {
  427. for (String group : minusGroups) {
  428. if (proj.groups.contains(group)) {
  429. // minus groups have highest priority.
  430. return false;
  431. }
  432. }
  433. if (plusGroups.isEmpty() || plusGroups.contains("all")) { //$NON-NLS-1$
  434. // empty plus groups means "all"
  435. return true;
  436. }
  437. for (String group : plusGroups) {
  438. if (proj.groups.contains(group))
  439. return true;
  440. }
  441. return false;
  442. }
  443. }
  444. private static class ManifestErrorException extends GitAPIException {
  445. ManifestErrorException(Throwable cause) {
  446. super(RepoText.get().invalidManifest, cause);
  447. }
  448. }
  449. private static class RemoteUnavailableException extends GitAPIException {
  450. RemoteUnavailableException(String uri) {
  451. super(MessageFormat.format(RepoText.get().errorRemoteUnavailable, uri));
  452. }
  453. }
  454. /**
  455. * @param repo
  456. */
  457. public RepoCommand(final Repository repo) {
  458. super(repo);
  459. }
  460. /**
  461. * Set path to the manifest XML file.
  462. *
  463. * Calling {@link #setInputStream} will ignore the path set here.
  464. *
  465. * @param path
  466. * (with <code>/</code> as separator)
  467. * @return this command
  468. */
  469. public RepoCommand setPath(final String path) {
  470. this.path = path;
  471. return this;
  472. }
  473. /**
  474. * Set the input stream to the manifest XML.
  475. *
  476. * Setting inputStream will ignore the path set. It will be closed in
  477. * {@link #call}.
  478. *
  479. * @param inputStream
  480. * @return this command
  481. * @since 3.5
  482. */
  483. public RepoCommand setInputStream(final InputStream inputStream) {
  484. this.inputStream = inputStream;
  485. return this;
  486. }
  487. /**
  488. * Set base URI of the pathes inside the XML
  489. *
  490. * @param uri
  491. * @return this command
  492. */
  493. public RepoCommand setURI(final String uri) {
  494. this.uri = uri;
  495. return this;
  496. }
  497. /**
  498. * Set groups to sync
  499. *
  500. * @param groups groups separated by comma, examples: default|all|G1,-G2,-G3
  501. * @return this command
  502. */
  503. public RepoCommand setGroups(final String groups) {
  504. this.groups = groups;
  505. return this;
  506. }
  507. /**
  508. * Set default branch.
  509. *
  510. * This is generally the name of the branch the manifest file was in. If
  511. * there's no default revision (branch) specified in manifest and no
  512. * revision specified in project, this branch will be used.
  513. *
  514. * @param branch
  515. * @return this command
  516. */
  517. public RepoCommand setBranch(final String branch) {
  518. this.branch = branch;
  519. return this;
  520. }
  521. /**
  522. * The progress monitor associated with the clone operation. By default,
  523. * this is set to <code>NullProgressMonitor</code>
  524. *
  525. * @see org.eclipse.jgit.lib.NullProgressMonitor
  526. * @param monitor
  527. * @return this command
  528. */
  529. public RepoCommand setProgressMonitor(final ProgressMonitor monitor) {
  530. this.monitor = monitor;
  531. return this;
  532. }
  533. /**
  534. * Set the author/committer for the bare repository commit.
  535. *
  536. * For non-bare repositories, the current user will be used and this will be
  537. * ignored.
  538. *
  539. * @param author
  540. * @return this command
  541. */
  542. public RepoCommand setAuthor(final PersonIdent author) {
  543. this.author = author;
  544. return this;
  545. }
  546. /**
  547. * Set the GetHeadFromUri callback.
  548. *
  549. * This is only used in bare repositories.
  550. *
  551. * @param callback
  552. * @return this command
  553. */
  554. public RepoCommand setRemoteReader(final RemoteReader callback) {
  555. this.callback = callback;
  556. return this;
  557. }
  558. @Override
  559. public RevCommit call() throws GitAPIException {
  560. try {
  561. checkCallable();
  562. if (uri == null || uri.length() == 0)
  563. throw new IllegalArgumentException(
  564. JGitText.get().uriNotConfigured);
  565. if (inputStream == null) {
  566. if (path == null || path.length() == 0)
  567. throw new IllegalArgumentException(
  568. JGitText.get().pathNotConfigured);
  569. try {
  570. inputStream = new FileInputStream(path);
  571. } catch (IOException e) {
  572. throw new IllegalArgumentException(
  573. JGitText.get().pathNotConfigured);
  574. }
  575. }
  576. if (repo.isBare()) {
  577. bareProjects = new ArrayList<Project>();
  578. if (author == null)
  579. author = new PersonIdent(repo);
  580. if (callback == null)
  581. callback = new DefaultRemoteReader();
  582. } else
  583. git = new Git(repo);
  584. XmlManifest manifest = new XmlManifest(
  585. this, inputStream, path, uri, groups);
  586. try {
  587. manifest.read();
  588. } catch (IOException e) {
  589. throw new ManifestErrorException(e);
  590. }
  591. } finally {
  592. try {
  593. if (inputStream != null)
  594. inputStream.close();
  595. } catch (IOException e) {
  596. // Just ignore it, it's not important.
  597. }
  598. }
  599. if (repo.isBare()) {
  600. DirCache index = DirCache.newInCore();
  601. DirCacheBuilder builder = index.builder();
  602. ObjectInserter inserter = repo.newObjectInserter();
  603. RevWalk rw = new RevWalk(repo);
  604. try {
  605. Config cfg = new Config();
  606. for (Project proj : bareProjects) {
  607. String name = proj.path;
  608. String uri = proj.name;
  609. cfg.setString("submodule", name, "path", name); //$NON-NLS-1$ //$NON-NLS-2$
  610. cfg.setString("submodule", name, "url", uri); //$NON-NLS-1$ //$NON-NLS-2$
  611. // create gitlink
  612. DirCacheEntry dcEntry = new DirCacheEntry(name);
  613. ObjectId objectId;
  614. if (ObjectId.isId(proj.revision))
  615. objectId = ObjectId.fromString(proj.revision);
  616. else {
  617. objectId = callback.sha1(uri, proj.revision);
  618. }
  619. if (objectId == null)
  620. throw new RemoteUnavailableException(uri);
  621. dcEntry.setObjectId(objectId);
  622. dcEntry.setFileMode(FileMode.GITLINK);
  623. builder.add(dcEntry);
  624. for (CopyFile copyfile : proj.copyfiles) {
  625. byte[] src = callback.readFile(
  626. uri, proj.revision, copyfile.src);
  627. objectId = inserter.insert(Constants.OBJ_BLOB, src);
  628. dcEntry = new DirCacheEntry(copyfile.dest);
  629. dcEntry.setObjectId(objectId);
  630. dcEntry.setFileMode(FileMode.REGULAR_FILE);
  631. builder.add(dcEntry);
  632. }
  633. }
  634. String content = cfg.toText();
  635. // create a new DirCacheEntry for .gitmodules file.
  636. final DirCacheEntry dcEntry = new DirCacheEntry(Constants.DOT_GIT_MODULES);
  637. ObjectId objectId = inserter.insert(Constants.OBJ_BLOB,
  638. content.getBytes(Constants.CHARACTER_ENCODING));
  639. dcEntry.setObjectId(objectId);
  640. dcEntry.setFileMode(FileMode.REGULAR_FILE);
  641. builder.add(dcEntry);
  642. builder.finish();
  643. ObjectId treeId = index.writeTree(inserter);
  644. // Create a Commit object, populate it and write it
  645. ObjectId headId = repo.resolve(Constants.HEAD + "^{commit}"); //$NON-NLS-1$
  646. CommitBuilder commit = new CommitBuilder();
  647. commit.setTreeId(treeId);
  648. if (headId != null)
  649. commit.setParentIds(headId);
  650. commit.setAuthor(author);
  651. commit.setCommitter(author);
  652. commit.setMessage(RepoText.get().repoCommitMessage);
  653. ObjectId commitId = inserter.insert(commit);
  654. inserter.flush();
  655. RefUpdate ru = repo.updateRef(Constants.HEAD);
  656. ru.setNewObjectId(commitId);
  657. ru.setExpectedOldObjectId(headId != null ? headId : ObjectId.zeroId());
  658. Result rc = ru.update(rw);
  659. switch (rc) {
  660. case NEW:
  661. case FORCED:
  662. case FAST_FORWARD:
  663. // Successful. Do nothing.
  664. break;
  665. case REJECTED:
  666. case LOCK_FAILURE:
  667. throw new ConcurrentRefUpdateException(
  668. JGitText.get().couldNotLockHEAD, ru.getRef(),
  669. rc);
  670. default:
  671. throw new JGitInternalException(MessageFormat.format(
  672. JGitText.get().updatingRefFailed,
  673. Constants.HEAD, commitId.name(), rc));
  674. }
  675. return rw.parseCommit(commitId);
  676. } catch (IOException e) {
  677. throw new ManifestErrorException(e);
  678. } finally {
  679. rw.release();
  680. }
  681. } else {
  682. return git
  683. .commit()
  684. .setMessage(RepoText.get().repoCommitMessage)
  685. .call();
  686. }
  687. }
  688. private void addSubmodule(String url, String name, String revision,
  689. List<CopyFile> copyfiles) throws SAXException {
  690. if (repo.isBare()) {
  691. Project proj = new Project(url, name, revision, null);
  692. proj.copyfiles.addAll(copyfiles);
  693. bareProjects.add(proj);
  694. } else {
  695. SubmoduleAddCommand add = git
  696. .submoduleAdd()
  697. .setPath(name)
  698. .setURI(url);
  699. if (monitor != null)
  700. add.setProgressMonitor(monitor);
  701. try {
  702. Repository subRepo = add.call();
  703. if (revision != null) {
  704. Git sub = new Git(subRepo);
  705. sub.checkout().setName(findRef(revision, subRepo)).call();
  706. git.add().addFilepattern(name).call();
  707. }
  708. for (CopyFile copyfile : copyfiles) {
  709. copyfile.copy();
  710. git.add().addFilepattern(copyfile.dest).call();
  711. }
  712. } catch (GitAPIException e) {
  713. throw new SAXException(e);
  714. } catch (IOException e) {
  715. throw new SAXException(e);
  716. }
  717. }
  718. }
  719. private static String findRef(String ref, Repository repo)
  720. throws IOException {
  721. if (!ObjectId.isId(ref)) {
  722. Ref r = repo.getRef(
  723. Constants.DEFAULT_REMOTE_NAME + "/" + ref);
  724. if (r != null)
  725. return r.getName();
  726. }
  727. return ref;
  728. }
  729. }