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

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