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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  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 IncludedFileReader includedReader;
  122. private List<Project> bareProjects;
  123. private Git git;
  124. private ProgressMonitor monitor;
  125. /**
  126. * A callback to get ref sha1 of a repository from its uri.
  127. *
  128. * We provided a default implementation {@link DefaultRemoteReader} to
  129. * use ls-remote command to read the sha1 from the repository and clone the
  130. * repository to read the file. Callers may have their own quicker
  131. * implementation.
  132. *
  133. * @since 3.4
  134. */
  135. public interface RemoteReader {
  136. /**
  137. * Read a remote ref sha1.
  138. *
  139. * @param uri
  140. * The URI of the remote repository
  141. * @param ref
  142. * The ref (branch/tag/etc.) to read
  143. * @return the sha1 of the remote repository
  144. * @throws GitAPIException
  145. */
  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. public ObjectId sha1(String uri, String ref) throws GitAPIException {
  167. Map<String, Ref> map = Git
  168. .lsRemoteRepository()
  169. .setRemote(uri)
  170. .callAsMap();
  171. Ref r = RefDatabase.findRef(map, ref);
  172. return r != null ? r.getObjectId() : null;
  173. }
  174. public byte[] readFile(String uri, String ref, String path)
  175. throws GitAPIException, IOException {
  176. File dir = FileUtils.createTempDir("jgit_", ".git", null); //$NON-NLS-1$ //$NON-NLS-2$
  177. Repository repo = Git
  178. .cloneRepository()
  179. .setBare(true)
  180. .setDirectory(dir)
  181. .setURI(uri)
  182. .call()
  183. .getRepository();
  184. try {
  185. return readFileFromRepo(repo, ref, path);
  186. } finally {
  187. repo.close();
  188. FileUtils.delete(dir, FileUtils.RECURSIVE);
  189. }
  190. }
  191. /**
  192. * Read a file from the repository
  193. *
  194. * @param repo
  195. * The repository containing the file
  196. * @param ref
  197. * The ref (branch/tag/etc.) to read
  198. * @param path
  199. * The relative path (inside the repo) to the file to read
  200. * @return the file's content
  201. * @throws GitAPIException
  202. * @throws IOException
  203. * @since 3.5
  204. */
  205. protected byte[] readFileFromRepo(Repository repo,
  206. String ref, String path) throws GitAPIException, IOException {
  207. ObjectReader reader = repo.newObjectReader();
  208. byte[] result;
  209. try {
  210. ObjectId oid = repo.resolve(ref + ":" + path); //$NON-NLS-1$
  211. result = reader.open(oid).getBytes(Integer.MAX_VALUE);
  212. } finally {
  213. reader.release();
  214. }
  215. return result;
  216. }
  217. }
  218. /**
  219. * A callback to read included xml files.
  220. *
  221. * @since 3.5
  222. */
  223. public interface IncludedFileReader {
  224. /**
  225. * Read a file from the same base dir of the manifest xml file.
  226. *
  227. * @param path
  228. * The relative path to the file to read
  229. * @return the {@code InputStream} of the file.
  230. * @throws GitAPIException
  231. * @throws IOException
  232. */
  233. public InputStream readIncludeFile(String path)
  234. throws GitAPIException, IOException;
  235. }
  236. private static class CopyFile {
  237. final Repository repo;
  238. final String path;
  239. final String src;
  240. final String dest;
  241. CopyFile(Repository repo, String path, String src, String dest) {
  242. this.repo = repo;
  243. this.path = path;
  244. this.src = src;
  245. this.dest = dest;
  246. }
  247. void copy() throws IOException {
  248. File srcFile = new File(repo.getWorkTree(),
  249. path + "/" + src); //$NON-NLS-1$
  250. File destFile = new File(repo.getWorkTree(), dest);
  251. FileInputStream input = new FileInputStream(srcFile);
  252. try {
  253. FileOutputStream output = new FileOutputStream(destFile);
  254. try {
  255. FileChannel channel = input.getChannel();
  256. output.getChannel().transferFrom(channel, 0, channel.size());
  257. } finally {
  258. output.close();
  259. }
  260. } finally {
  261. input.close();
  262. }
  263. }
  264. }
  265. private static class Project implements Comparable<Project> {
  266. final String name;
  267. final String path;
  268. final String revision;
  269. final String remote;
  270. final Set<String> groups;
  271. final List<CopyFile> copyfiles;
  272. Project(String name, String path, String revision,
  273. String remote, String groups) {
  274. this.name = name;
  275. if (path != null)
  276. this.path = path;
  277. else
  278. this.path = name;
  279. this.revision = revision;
  280. this.remote = remote;
  281. this.groups = new HashSet<String>();
  282. if (groups != null && groups.length() > 0)
  283. this.groups.addAll(Arrays.asList(groups.split(","))); //$NON-NLS-1$
  284. copyfiles = new ArrayList<CopyFile>();
  285. }
  286. void addCopyFile(CopyFile copyfile) {
  287. copyfiles.add(copyfile);
  288. }
  289. String getPathWithSlash() {
  290. if (path.endsWith("/")) //$NON-NLS-1$
  291. return path;
  292. else
  293. return path + "/"; //$NON-NLS-1$
  294. }
  295. boolean isAncestorOf(Project that) {
  296. return that.getPathWithSlash().startsWith(this.getPathWithSlash());
  297. }
  298. @Override
  299. public boolean equals(Object o) {
  300. if (o instanceof Project) {
  301. Project that = (Project) o;
  302. return this.getPathWithSlash().equals(that.getPathWithSlash());
  303. }
  304. return false;
  305. }
  306. @Override
  307. public int hashCode() {
  308. return this.getPathWithSlash().hashCode();
  309. }
  310. public int compareTo(Project that) {
  311. return this.getPathWithSlash().compareTo(that.getPathWithSlash());
  312. }
  313. }
  314. private static class XmlManifest extends DefaultHandler {
  315. private final RepoCommand command;
  316. private final String filename;
  317. private final String baseUrl;
  318. private final Map<String, String> remotes;
  319. private final Set<String> plusGroups;
  320. private final Set<String> minusGroups;
  321. private List<Project> projects;
  322. private String defaultRemote;
  323. private String defaultRevision;
  324. private IncludedFileReader includedReader;
  325. private int xmlInRead;
  326. private Project currentProject;
  327. XmlManifest(RepoCommand command, IncludedFileReader includedReader,
  328. String filename, String baseUrl, String groups) {
  329. this.command = command;
  330. this.includedReader = includedReader;
  331. this.filename = filename;
  332. // Strip trailing /s to match repo behavior.
  333. int lastIndex = baseUrl.length() - 1;
  334. while (lastIndex >= 0 && baseUrl.charAt(lastIndex) == '/')
  335. lastIndex--;
  336. this.baseUrl = baseUrl.substring(0, lastIndex + 1);
  337. remotes = new HashMap<String, String>();
  338. projects = new ArrayList<Project>();
  339. plusGroups = new HashSet<String>();
  340. minusGroups = new HashSet<String>();
  341. if (groups == null || groups.length() == 0 || groups.equals("default")) { //$NON-NLS-1$
  342. // default means "all,-notdefault"
  343. minusGroups.add("notdefault"); //$NON-NLS-1$
  344. } else {
  345. for (String group : groups.split(",")) { //$NON-NLS-1$
  346. if (group.startsWith("-")) //$NON-NLS-1$
  347. minusGroups.add(group.substring(1));
  348. else
  349. plusGroups.add(group);
  350. }
  351. }
  352. }
  353. void read(InputStream inputStream) throws IOException {
  354. xmlInRead++;
  355. final XMLReader xr;
  356. try {
  357. xr = XMLReaderFactory.createXMLReader();
  358. } catch (SAXException e) {
  359. throw new IOException(JGitText.get().noXMLParserAvailable);
  360. }
  361. xr.setContentHandler(this);
  362. try {
  363. xr.parse(new InputSource(inputStream));
  364. } catch (SAXException e) {
  365. IOException error = new IOException(
  366. RepoText.get().errorParsingManifestFile);
  367. error.initCause(e);
  368. throw error;
  369. }
  370. }
  371. @Override
  372. public void startElement(
  373. String uri,
  374. String localName,
  375. String qName,
  376. Attributes attributes) throws SAXException {
  377. if ("project".equals(qName)) { //$NON-NLS-1$
  378. currentProject = new Project(
  379. attributes.getValue("name"), //$NON-NLS-1$
  380. attributes.getValue("path"), //$NON-NLS-1$
  381. attributes.getValue("revision"), //$NON-NLS-1$
  382. attributes.getValue("remote"), //$NON-NLS-1$
  383. attributes.getValue("groups")); //$NON-NLS-1$
  384. } else if ("remote".equals(qName)) { //$NON-NLS-1$
  385. String alias = attributes.getValue("alias"); //$NON-NLS-1$
  386. String fetch = attributes.getValue("fetch"); //$NON-NLS-1$
  387. remotes.put(attributes.getValue("name"), fetch); //$NON-NLS-1$
  388. if (alias != null)
  389. remotes.put(alias, fetch);
  390. } else if ("default".equals(qName)) { //$NON-NLS-1$
  391. defaultRemote = attributes.getValue("remote"); //$NON-NLS-1$
  392. defaultRevision = attributes.getValue("revision"); //$NON-NLS-1$
  393. if (defaultRevision == null)
  394. defaultRevision = command.branch;
  395. } else if ("copyfile".equals(qName)) { //$NON-NLS-1$
  396. if (currentProject == null)
  397. throw new SAXException(RepoText.get().invalidManifest);
  398. currentProject.addCopyFile(new CopyFile(
  399. command.repo,
  400. currentProject.path,
  401. attributes.getValue("src"), //$NON-NLS-1$
  402. attributes.getValue("dest"))); //$NON-NLS-1$
  403. } else if ("include".equals(qName)) { //$NON-NLS-1$
  404. String name = attributes.getValue("name"); //$NON-NLS-1$
  405. InputStream is = null;
  406. if (includedReader != null) {
  407. try {
  408. is = includedReader.readIncludeFile(name);
  409. } catch (Exception e) {
  410. throw new SAXException(MessageFormat.format(
  411. RepoText.get().errorIncludeFile, name), e);
  412. }
  413. } else if (filename != null) {
  414. int index = filename.lastIndexOf('/');
  415. String path = filename.substring(0, index + 1) + name;
  416. try {
  417. is = new FileInputStream(path);
  418. } catch (IOException e) {
  419. throw new SAXException(MessageFormat.format(
  420. RepoText.get().errorIncludeFile, path), e);
  421. }
  422. }
  423. if (is == null) {
  424. throw new SAXException(
  425. RepoText.get().errorIncludeNotImplemented);
  426. }
  427. try {
  428. read(is);
  429. } catch (IOException e) {
  430. throw new SAXException(e);
  431. }
  432. }
  433. }
  434. @Override
  435. public void endElement(
  436. String uri,
  437. String localName,
  438. String qName) throws SAXException {
  439. if ("project".equals(qName)) { //$NON-NLS-1$
  440. projects.add(currentProject);
  441. currentProject = null;
  442. }
  443. }
  444. @Override
  445. public void endDocument() throws SAXException {
  446. xmlInRead--;
  447. if (xmlInRead != 0)
  448. return;
  449. // Only do the following after we finished reading everything.
  450. removeNotInGroup();
  451. removeOverlaps();
  452. Map<String, String> remoteUrls = new HashMap<String, String>();
  453. URI baseUri;
  454. try {
  455. baseUri = new URI(baseUrl);
  456. } catch (URISyntaxException e) {
  457. throw new SAXException(e);
  458. }
  459. for (Project proj : projects) {
  460. String remote = proj.remote;
  461. if (remote == null) {
  462. if (defaultRemote == null) {
  463. if (filename != null)
  464. throw new SAXException(MessageFormat.format(
  465. RepoText.get().errorNoDefaultFilename,
  466. filename));
  467. else
  468. throw new SAXException(
  469. RepoText.get().errorNoDefault);
  470. }
  471. remote = defaultRemote;
  472. }
  473. String remoteUrl = remoteUrls.get(remote);
  474. if (remoteUrl == null) {
  475. remoteUrl = baseUri.resolve(remotes.get(remote)).toString();
  476. if (!remoteUrl.endsWith("/")) //$NON-NLS-1$
  477. remoteUrl = remoteUrl + "/"; //$NON-NLS-1$
  478. remoteUrls.put(remote, remoteUrl);
  479. }
  480. command.addSubmodule(remoteUrl + proj.name,
  481. proj.path,
  482. proj.revision == null
  483. ? defaultRevision : proj.revision,
  484. proj.copyfiles);
  485. }
  486. }
  487. /** Remove projects that are not in our desired groups. */
  488. void removeNotInGroup() {
  489. Iterator<Project> iter = projects.iterator();
  490. while (iter.hasNext())
  491. if (!inGroups(iter.next()))
  492. iter.remove();
  493. }
  494. /** Remove projects that sits in a subdirectory of any other project. */
  495. void removeOverlaps() {
  496. Collections.sort(projects);
  497. Iterator<Project> iter = projects.iterator();
  498. if (!iter.hasNext())
  499. return;
  500. Project last = iter.next();
  501. while (iter.hasNext()) {
  502. Project p = iter.next();
  503. if (last.isAncestorOf(p))
  504. iter.remove();
  505. else
  506. last = p;
  507. }
  508. }
  509. boolean inGroups(Project proj) {
  510. for (String group : minusGroups) {
  511. if (proj.groups.contains(group)) {
  512. // minus groups have highest priority.
  513. return false;
  514. }
  515. }
  516. if (plusGroups.isEmpty() || plusGroups.contains("all")) { //$NON-NLS-1$
  517. // empty plus groups means "all"
  518. return true;
  519. }
  520. for (String group : plusGroups) {
  521. if (proj.groups.contains(group))
  522. return true;
  523. }
  524. return false;
  525. }
  526. }
  527. @SuppressWarnings("serial")
  528. private static class ManifestErrorException extends GitAPIException {
  529. ManifestErrorException(Throwable cause) {
  530. super(RepoText.get().invalidManifest, cause);
  531. }
  532. }
  533. @SuppressWarnings("serial")
  534. private static class RemoteUnavailableException extends GitAPIException {
  535. RemoteUnavailableException(String uri) {
  536. super(MessageFormat.format(RepoText.get().errorRemoteUnavailable, uri));
  537. }
  538. }
  539. /**
  540. * @param repo
  541. */
  542. public RepoCommand(final Repository repo) {
  543. super(repo);
  544. }
  545. /**
  546. * Set path to the manifest XML file.
  547. *
  548. * Calling {@link #setInputStream} will ignore the path set here.
  549. *
  550. * @param path
  551. * (with <code>/</code> as separator)
  552. * @return this command
  553. */
  554. public RepoCommand setPath(final String path) {
  555. this.path = path;
  556. return this;
  557. }
  558. /**
  559. * Set the input stream to the manifest XML.
  560. *
  561. * Setting inputStream will ignore the path set. It will be closed in
  562. * {@link #call}.
  563. *
  564. * @param inputStream
  565. * @return this command
  566. * @since 3.5
  567. */
  568. public RepoCommand setInputStream(final InputStream inputStream) {
  569. this.inputStream = inputStream;
  570. return this;
  571. }
  572. /**
  573. * Set base URI of the pathes inside the XML
  574. *
  575. * @param uri
  576. * @return this command
  577. */
  578. public RepoCommand setURI(final String uri) {
  579. this.uri = uri;
  580. return this;
  581. }
  582. /**
  583. * Set groups to sync
  584. *
  585. * @param groups groups separated by comma, examples: default|all|G1,-G2,-G3
  586. * @return this command
  587. */
  588. public RepoCommand setGroups(final String groups) {
  589. this.groups = groups;
  590. return this;
  591. }
  592. /**
  593. * Set default branch.
  594. *
  595. * This is generally the name of the branch the manifest file was in. If
  596. * there's no default revision (branch) specified in manifest and no
  597. * revision specified in project, this branch will be used.
  598. *
  599. * @param branch
  600. * @return this command
  601. */
  602. public RepoCommand setBranch(final String branch) {
  603. this.branch = branch;
  604. return this;
  605. }
  606. /**
  607. * The progress monitor associated with the clone operation. By default,
  608. * this is set to <code>NullProgressMonitor</code>
  609. *
  610. * @see org.eclipse.jgit.lib.NullProgressMonitor
  611. * @param monitor
  612. * @return this command
  613. */
  614. public RepoCommand setProgressMonitor(final ProgressMonitor monitor) {
  615. this.monitor = monitor;
  616. return this;
  617. }
  618. /**
  619. * Set the author/committer for the bare repository commit.
  620. *
  621. * For non-bare repositories, the current user will be used and this will be
  622. * ignored.
  623. *
  624. * @param author
  625. * @return this command
  626. */
  627. public RepoCommand setAuthor(final PersonIdent author) {
  628. this.author = author;
  629. return this;
  630. }
  631. /**
  632. * Set the GetHeadFromUri callback.
  633. *
  634. * This is only used in bare repositories.
  635. *
  636. * @param callback
  637. * @return this command
  638. */
  639. public RepoCommand setRemoteReader(final RemoteReader callback) {
  640. this.callback = callback;
  641. return this;
  642. }
  643. /**
  644. * Set the IncludedFileReader callback.
  645. *
  646. * @param reader
  647. * @return this command
  648. * @since 3.5
  649. */
  650. public RepoCommand setIncludedFileReader(IncludedFileReader reader) {
  651. this.includedReader = reader;
  652. return this;
  653. }
  654. @Override
  655. public RevCommit call() throws GitAPIException {
  656. try {
  657. checkCallable();
  658. if (uri == null || uri.length() == 0)
  659. throw new IllegalArgumentException(
  660. JGitText.get().uriNotConfigured);
  661. if (inputStream == null) {
  662. if (path == null || path.length() == 0)
  663. throw new IllegalArgumentException(
  664. JGitText.get().pathNotConfigured);
  665. try {
  666. inputStream = new FileInputStream(path);
  667. } catch (IOException e) {
  668. throw new IllegalArgumentException(
  669. JGitText.get().pathNotConfigured);
  670. }
  671. }
  672. if (repo.isBare()) {
  673. bareProjects = new ArrayList<Project>();
  674. if (author == null)
  675. author = new PersonIdent(repo);
  676. if (callback == null)
  677. callback = new DefaultRemoteReader();
  678. } else
  679. git = new Git(repo);
  680. XmlManifest manifest = new XmlManifest(
  681. this, includedReader, path, uri, groups);
  682. try {
  683. manifest.read(inputStream);
  684. } catch (IOException e) {
  685. throw new ManifestErrorException(e);
  686. }
  687. } finally {
  688. try {
  689. if (inputStream != null)
  690. inputStream.close();
  691. } catch (IOException e) {
  692. // Just ignore it, it's not important.
  693. }
  694. }
  695. if (repo.isBare()) {
  696. DirCache index = DirCache.newInCore();
  697. DirCacheBuilder builder = index.builder();
  698. ObjectInserter inserter = repo.newObjectInserter();
  699. RevWalk rw = new RevWalk(repo);
  700. try {
  701. Config cfg = new Config();
  702. for (Project proj : bareProjects) {
  703. String name = proj.path;
  704. String nameUri = proj.name;
  705. cfg.setString("submodule", name, "path", name); //$NON-NLS-1$ //$NON-NLS-2$
  706. cfg.setString("submodule", name, "url", nameUri); //$NON-NLS-1$ //$NON-NLS-2$
  707. // create gitlink
  708. DirCacheEntry dcEntry = new DirCacheEntry(name);
  709. ObjectId objectId;
  710. if (ObjectId.isId(proj.revision))
  711. objectId = ObjectId.fromString(proj.revision);
  712. else {
  713. objectId = callback.sha1(nameUri, proj.revision);
  714. }
  715. if (objectId == null)
  716. throw new RemoteUnavailableException(nameUri);
  717. dcEntry.setObjectId(objectId);
  718. dcEntry.setFileMode(FileMode.GITLINK);
  719. builder.add(dcEntry);
  720. for (CopyFile copyfile : proj.copyfiles) {
  721. byte[] src = callback.readFile(
  722. nameUri, proj.revision, copyfile.src);
  723. objectId = inserter.insert(Constants.OBJ_BLOB, src);
  724. dcEntry = new DirCacheEntry(copyfile.dest);
  725. dcEntry.setObjectId(objectId);
  726. dcEntry.setFileMode(FileMode.REGULAR_FILE);
  727. builder.add(dcEntry);
  728. }
  729. }
  730. String content = cfg.toText();
  731. // create a new DirCacheEntry for .gitmodules file.
  732. final DirCacheEntry dcEntry = new DirCacheEntry(Constants.DOT_GIT_MODULES);
  733. ObjectId objectId = inserter.insert(Constants.OBJ_BLOB,
  734. content.getBytes(Constants.CHARACTER_ENCODING));
  735. dcEntry.setObjectId(objectId);
  736. dcEntry.setFileMode(FileMode.REGULAR_FILE);
  737. builder.add(dcEntry);
  738. builder.finish();
  739. ObjectId treeId = index.writeTree(inserter);
  740. // Create a Commit object, populate it and write it
  741. ObjectId headId = repo.resolve(Constants.HEAD + "^{commit}"); //$NON-NLS-1$
  742. CommitBuilder commit = new CommitBuilder();
  743. commit.setTreeId(treeId);
  744. if (headId != null)
  745. commit.setParentIds(headId);
  746. commit.setAuthor(author);
  747. commit.setCommitter(author);
  748. commit.setMessage(RepoText.get().repoCommitMessage);
  749. ObjectId commitId = inserter.insert(commit);
  750. inserter.flush();
  751. RefUpdate ru = repo.updateRef(Constants.HEAD);
  752. ru.setNewObjectId(commitId);
  753. ru.setExpectedOldObjectId(headId != null ? headId : ObjectId.zeroId());
  754. Result rc = ru.update(rw);
  755. switch (rc) {
  756. case NEW:
  757. case FORCED:
  758. case FAST_FORWARD:
  759. // Successful. Do nothing.
  760. break;
  761. case REJECTED:
  762. case LOCK_FAILURE:
  763. throw new ConcurrentRefUpdateException(
  764. JGitText.get().couldNotLockHEAD, ru.getRef(),
  765. rc);
  766. default:
  767. throw new JGitInternalException(MessageFormat.format(
  768. JGitText.get().updatingRefFailed,
  769. Constants.HEAD, commitId.name(), rc));
  770. }
  771. return rw.parseCommit(commitId);
  772. } catch (IOException e) {
  773. throw new ManifestErrorException(e);
  774. } finally {
  775. rw.release();
  776. }
  777. } else {
  778. return git
  779. .commit()
  780. .setMessage(RepoText.get().repoCommitMessage)
  781. .call();
  782. }
  783. }
  784. private void addSubmodule(String url, String name, String revision,
  785. List<CopyFile> copyfiles) throws SAXException {
  786. if (repo.isBare()) {
  787. Project proj = new Project(url, name, revision, null, null);
  788. proj.copyfiles.addAll(copyfiles);
  789. bareProjects.add(proj);
  790. } else {
  791. SubmoduleAddCommand add = git
  792. .submoduleAdd()
  793. .setPath(name)
  794. .setURI(url);
  795. if (monitor != null)
  796. add.setProgressMonitor(monitor);
  797. try {
  798. Repository subRepo = add.call();
  799. if (revision != null) {
  800. Git sub = new Git(subRepo);
  801. sub.checkout().setName(findRef(revision, subRepo)).call();
  802. subRepo.close();
  803. git.add().addFilepattern(name).call();
  804. }
  805. for (CopyFile copyfile : copyfiles) {
  806. copyfile.copy();
  807. git.add().addFilepattern(copyfile.dest).call();
  808. }
  809. } catch (GitAPIException e) {
  810. throw new SAXException(e);
  811. } catch (IOException e) {
  812. throw new SAXException(e);
  813. }
  814. }
  815. }
  816. private static String findRef(String ref, Repository repo)
  817. throws IOException {
  818. if (!ObjectId.isId(ref)) {
  819. Ref r = repo.getRef(Constants.DEFAULT_REMOTE_NAME + "/" + ref); //$NON-NLS-1$
  820. if (r != null)
  821. return r.getName();
  822. }
  823. return ref;
  824. }
  825. }