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.

ArchiveCommand.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. /*
  2. * Copyright (C) 2012 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.api;
  44. import java.io.Closeable;
  45. import java.io.IOException;
  46. import java.io.OutputStream;
  47. import java.text.MessageFormat;
  48. import java.util.ArrayList;
  49. import java.util.Arrays;
  50. import java.util.HashMap;
  51. import java.util.List;
  52. import java.util.Map;
  53. import java.util.concurrent.ConcurrentHashMap;
  54. import java.util.concurrent.ConcurrentMap;
  55. import org.eclipse.jgit.api.errors.GitAPIException;
  56. import org.eclipse.jgit.api.errors.JGitInternalException;
  57. import org.eclipse.jgit.internal.JGitText;
  58. import org.eclipse.jgit.lib.FileMode;
  59. import org.eclipse.jgit.lib.MutableObjectId;
  60. import org.eclipse.jgit.lib.ObjectId;
  61. import org.eclipse.jgit.lib.ObjectLoader;
  62. import org.eclipse.jgit.lib.ObjectReader;
  63. import org.eclipse.jgit.lib.Repository;
  64. import org.eclipse.jgit.revwalk.RevWalk;
  65. import org.eclipse.jgit.treewalk.TreeWalk;
  66. import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
  67. /**
  68. * Create an archive of files from a named tree.
  69. * <p>
  70. * Examples (<code>git</code> is a {@link Git} instance):
  71. * <p>
  72. * Create a tarball from HEAD:
  73. *
  74. * <pre>
  75. * ArchiveCommand.registerFormat("tar", new TarFormat());
  76. * try {
  77. * git.archive()
  78. * .setTree(db.resolve(&quot;HEAD&quot;))
  79. * .setOutputStream(out)
  80. * .call();
  81. * } finally {
  82. * ArchiveCommand.unregisterFormat("tar");
  83. * }
  84. * </pre>
  85. * <p>
  86. * Create a ZIP file from master:
  87. *
  88. * <pre>
  89. * ArchiveCommand.registerFormat("zip", new ZipFormat());
  90. * try {
  91. * git.archive().
  92. * .setTree(db.resolve(&quot;master&quot;))
  93. * .setFormat("zip")
  94. * .setOutputStream(out)
  95. * .call();
  96. * } finally {
  97. * ArchiveCommand.unregisterFormat("zip");
  98. * }
  99. * </pre>
  100. *
  101. * @see <a href="http://git-htmldocs.googlecode.com/git/git-archive.html" >Git
  102. * documentation about archive</a>
  103. *
  104. * @since 3.1
  105. */
  106. public class ArchiveCommand extends GitCommand<OutputStream> {
  107. /**
  108. * Archival format.
  109. *
  110. * Usage:
  111. * Repository repo = git.getRepository();
  112. * T out = format.createArchiveOutputStream(System.out);
  113. * try {
  114. * for (...) {
  115. * format.putEntry(out, path, mode, repo.open(objectId));
  116. * }
  117. * out.close();
  118. * }
  119. *
  120. * @param <T>
  121. * type representing an archive being created.
  122. */
  123. public static interface Format<T extends Closeable> {
  124. /**
  125. * Start a new archive. Entries can be included in the archive using the
  126. * putEntry method, and then the archive should be closed using its
  127. * close method.
  128. *
  129. * @param s
  130. * underlying output stream to which to write the archive.
  131. * @return new archive object for use in putEntry
  132. * @throws IOException
  133. * thrown by the underlying output stream for I/O errors
  134. */
  135. T createArchiveOutputStream(OutputStream s) throws IOException;
  136. /**
  137. * Start a new archive. Entries can be included in the archive using the
  138. * putEntry method, and then the archive should be closed using its
  139. * close method. In addition options can be applied to the underlying
  140. * stream. E.g. compression level.
  141. *
  142. * @param s
  143. * underlying output stream to which to write the archive.
  144. * @param o
  145. * options to apply to the underlying output stream. Keys are
  146. * option names and values are option values.
  147. * @return new archive object for use in putEntry
  148. * @throws IOException
  149. * thrown by the underlying output stream for I/O errors
  150. * @since 4.0
  151. */
  152. T createArchiveOutputStream(OutputStream s, Map<String, Object> o)
  153. throws IOException;
  154. /**
  155. * Write an entry to an archive.
  156. *
  157. * @param out
  158. * archive object from createArchiveOutputStream
  159. * @param path
  160. * full filename relative to the root of the archive (with
  161. * trailing '/' for directories)
  162. * @param mode
  163. * mode (for example FileMode.REGULAR_FILE or
  164. * FileMode.SYMLINK)
  165. * @param loader
  166. * blob object with data for this entry (null for
  167. * directories)
  168. * @throws IOException
  169. * thrown by the underlying output stream for I/O errors
  170. * @deprecated use
  171. * {@link #putEntry(Closeable, ObjectId, String, FileMode, ObjectLoader)}
  172. * instead
  173. */
  174. @Deprecated
  175. void putEntry(T out, String path, FileMode mode,
  176. ObjectLoader loader) throws IOException;
  177. /**
  178. * Write an entry to an archive.
  179. *
  180. * @param out
  181. * archive object from createArchiveOutputStream
  182. * @param tree
  183. * the tag, commit, or tree object to produce an archive for
  184. * @param path
  185. * full filename relative to the root of the archive (with
  186. * trailing '/' for directories)
  187. * @param mode
  188. * mode (for example FileMode.REGULAR_FILE or
  189. * FileMode.SYMLINK)
  190. * @param loader
  191. * blob object with data for this entry (null for
  192. * directories)
  193. * @throws IOException
  194. * thrown by the underlying output stream for I/O errors
  195. * @since 4.7
  196. */
  197. void putEntry(T out, ObjectId tree, String path, FileMode mode,
  198. ObjectLoader loader) throws IOException;
  199. /**
  200. * Filename suffixes representing this format (e.g.,
  201. * { ".tar.gz", ".tgz" }).
  202. *
  203. * The behavior is undefined when suffixes overlap (if
  204. * one format claims suffix ".7z", no other format should
  205. * take ".tar.7z").
  206. *
  207. * @return this format's suffixes
  208. */
  209. Iterable<String> suffixes();
  210. }
  211. /**
  212. * Signals an attempt to use an archival format that ArchiveCommand
  213. * doesn't know about (for example due to a typo).
  214. */
  215. public static class UnsupportedFormatException extends GitAPIException {
  216. private static final long serialVersionUID = 1L;
  217. private final String format;
  218. /**
  219. * @param format the problematic format name
  220. */
  221. public UnsupportedFormatException(String format) {
  222. super(MessageFormat.format(JGitText.get().unsupportedArchiveFormat, format));
  223. this.format = format;
  224. }
  225. /**
  226. * @return the problematic format name
  227. */
  228. public String getFormat() {
  229. return format;
  230. }
  231. }
  232. private static class FormatEntry {
  233. final Format<?> format;
  234. /** Number of times this format has been registered. */
  235. final int refcnt;
  236. public FormatEntry(Format<?> format, int refcnt) {
  237. if (format == null)
  238. throw new NullPointerException();
  239. this.format = format;
  240. this.refcnt = refcnt;
  241. }
  242. }
  243. /**
  244. * Available archival formats (corresponding to values for
  245. * the --format= option)
  246. */
  247. private static final ConcurrentMap<String, FormatEntry> formats =
  248. new ConcurrentHashMap<String, FormatEntry>();
  249. /**
  250. * Replaces the entry for a key only if currently mapped to a given
  251. * value.
  252. *
  253. * @param map a map
  254. * @param key key with which the specified value is associated
  255. * @param oldValue expected value for the key (null if should be absent).
  256. * @param newValue value to be associated with the key (null to remove).
  257. * @return true if the value was replaced
  258. */
  259. private static <K, V> boolean replace(ConcurrentMap<K, V> map,
  260. K key, V oldValue, V newValue) {
  261. if (oldValue == null && newValue == null) // Nothing to do.
  262. return true;
  263. if (oldValue == null)
  264. return map.putIfAbsent(key, newValue) == null;
  265. else if (newValue == null)
  266. return map.remove(key, oldValue);
  267. else
  268. return map.replace(key, oldValue, newValue);
  269. }
  270. /**
  271. * Adds support for an additional archival format. To avoid
  272. * unnecessary dependencies, ArchiveCommand does not have support
  273. * for any formats built in; use this function to add them.
  274. * <p>
  275. * OSGi plugins providing formats should call this function at
  276. * bundle activation time.
  277. * <p>
  278. * It is okay to register the same archive format with the same
  279. * name multiple times, but don't forget to unregister it that
  280. * same number of times, too.
  281. * <p>
  282. * Registering multiple formats with different names and the
  283. * same or overlapping suffixes results in undefined behavior.
  284. * TODO: check that suffixes don't overlap.
  285. *
  286. * @param name name of a format (e.g., "tar" or "zip").
  287. * @param fmt archiver for that format
  288. * @throws JGitInternalException
  289. * A different archival format with that name was
  290. * already registered.
  291. */
  292. public static void registerFormat(String name, Format<?> fmt) {
  293. if (fmt == null)
  294. throw new NullPointerException();
  295. FormatEntry old, entry;
  296. do {
  297. old = formats.get(name);
  298. if (old == null) {
  299. entry = new FormatEntry(fmt, 1);
  300. continue;
  301. }
  302. if (!old.format.equals(fmt))
  303. throw new JGitInternalException(MessageFormat.format(
  304. JGitText.get().archiveFormatAlreadyRegistered,
  305. name));
  306. entry = new FormatEntry(old.format, old.refcnt + 1);
  307. } while (!replace(formats, name, old, entry));
  308. }
  309. /**
  310. * Marks support for an archival format as no longer needed so its
  311. * Format can be garbage collected if no one else is using it either.
  312. * <p>
  313. * In other words, this decrements the reference count for an
  314. * archival format. If the reference count becomes zero, removes
  315. * support for that format.
  316. *
  317. * @param name name of format (e.g., "tar" or "zip").
  318. * @throws JGitInternalException
  319. * No such archival format was registered.
  320. */
  321. public static void unregisterFormat(String name) {
  322. FormatEntry old, entry;
  323. do {
  324. old = formats.get(name);
  325. if (old == null)
  326. throw new JGitInternalException(MessageFormat.format(
  327. JGitText.get().archiveFormatAlreadyAbsent,
  328. name));
  329. if (old.refcnt == 1) {
  330. entry = null;
  331. continue;
  332. }
  333. entry = new FormatEntry(old.format, old.refcnt - 1);
  334. } while (!replace(formats, name, old, entry));
  335. }
  336. private static Format<?> formatBySuffix(String filenameSuffix)
  337. throws UnsupportedFormatException {
  338. if (filenameSuffix != null)
  339. for (FormatEntry entry : formats.values()) {
  340. Format<?> fmt = entry.format;
  341. for (String sfx : fmt.suffixes())
  342. if (filenameSuffix.endsWith(sfx))
  343. return fmt;
  344. }
  345. return lookupFormat("tar"); //$NON-NLS-1$
  346. }
  347. private static Format<?> lookupFormat(String formatName) throws UnsupportedFormatException {
  348. FormatEntry entry = formats.get(formatName);
  349. if (entry == null)
  350. throw new UnsupportedFormatException(formatName);
  351. return entry.format;
  352. }
  353. private OutputStream out;
  354. private ObjectId tree;
  355. private String prefix;
  356. private String format;
  357. private Map<String, Object> formatOptions = new HashMap<>();
  358. private List<String> paths = new ArrayList<String>();
  359. /** Filename suffix, for automatically choosing a format. */
  360. private String suffix;
  361. /**
  362. * @param repo
  363. */
  364. public ArchiveCommand(Repository repo) {
  365. super(repo);
  366. setCallable(false);
  367. }
  368. private <T extends Closeable> OutputStream writeArchive(Format<T> fmt) {
  369. try {
  370. try (TreeWalk walk = new TreeWalk(repo);
  371. RevWalk rw = new RevWalk(walk.getObjectReader())) {
  372. String pfx = prefix == null ? "" : prefix; //$NON-NLS-1$
  373. T outa = fmt.createArchiveOutputStream(out, formatOptions);
  374. MutableObjectId idBuf = new MutableObjectId();
  375. ObjectReader reader = walk.getObjectReader();
  376. walk.reset(rw.parseTree(tree));
  377. if (!paths.isEmpty())
  378. walk.setFilter(PathFilterGroup.createFromStrings(paths));
  379. while (walk.next()) {
  380. String name = pfx + walk.getPathString();
  381. FileMode mode = walk.getFileMode(0);
  382. if (walk.isSubtree())
  383. walk.enterSubtree();
  384. if (mode == FileMode.GITLINK)
  385. // TODO(jrn): Take a callback to recurse
  386. // into submodules.
  387. mode = FileMode.TREE;
  388. if (mode == FileMode.TREE) {
  389. fmt.putEntry(outa, tree, name + "/", mode, null); //$NON-NLS-1$
  390. continue;
  391. }
  392. walk.getObjectId(idBuf, 0);
  393. fmt.putEntry(outa, tree, name, mode, reader.open(idBuf));
  394. }
  395. outa.close();
  396. return out;
  397. } finally {
  398. out.close();
  399. }
  400. } catch (IOException e) {
  401. // TODO(jrn): Throw finer-grained errors.
  402. throw new JGitInternalException(
  403. JGitText.get().exceptionCaughtDuringExecutionOfArchiveCommand, e);
  404. }
  405. }
  406. /**
  407. * @return the stream to which the archive has been written
  408. */
  409. @Override
  410. public OutputStream call() throws GitAPIException {
  411. checkCallable();
  412. Format<?> fmt;
  413. if (format == null)
  414. fmt = formatBySuffix(suffix);
  415. else
  416. fmt = lookupFormat(format);
  417. return writeArchive(fmt);
  418. }
  419. /**
  420. * @param tree
  421. * the tag, commit, or tree object to produce an archive for
  422. * @return this
  423. */
  424. public ArchiveCommand setTree(ObjectId tree) {
  425. if (tree == null)
  426. throw new IllegalArgumentException();
  427. this.tree = tree;
  428. setCallable(true);
  429. return this;
  430. }
  431. /**
  432. * @param prefix
  433. * string prefixed to filenames in archive (e.g., "master/").
  434. * null means to not use any leading prefix.
  435. * @return this
  436. * @since 3.3
  437. */
  438. public ArchiveCommand setPrefix(String prefix) {
  439. this.prefix = prefix;
  440. return this;
  441. }
  442. /**
  443. * Set the intended filename for the produced archive. Currently the only
  444. * effect is to determine the default archive format when none is specified
  445. * with {@link #setFormat(String)}.
  446. *
  447. * @param filename
  448. * intended filename for the archive
  449. * @return this
  450. */
  451. public ArchiveCommand setFilename(String filename) {
  452. int slash = filename.lastIndexOf('/');
  453. int dot = filename.indexOf('.', slash + 1);
  454. if (dot == -1)
  455. this.suffix = ""; //$NON-NLS-1$
  456. else
  457. this.suffix = filename.substring(dot);
  458. return this;
  459. }
  460. /**
  461. * @param out
  462. * the stream to which to write the archive
  463. * @return this
  464. */
  465. public ArchiveCommand setOutputStream(OutputStream out) {
  466. this.out = out;
  467. return this;
  468. }
  469. /**
  470. * @param fmt
  471. * archive format (e.g., "tar" or "zip").
  472. * null means to choose automatically based on
  473. * the archive filename.
  474. * @return this
  475. */
  476. public ArchiveCommand setFormat(String fmt) {
  477. this.format = fmt;
  478. return this;
  479. }
  480. /**
  481. * @param options
  482. * archive format options (e.g., level=9 for zip compression).
  483. * @return this
  484. * @since 4.0
  485. */
  486. public ArchiveCommand setFormatOptions(Map<String, Object> options) {
  487. this.formatOptions = options;
  488. return this;
  489. }
  490. /**
  491. * Set an optional parameter path. without an optional path parameter, all
  492. * files and subdirectories of the current working directory are included in
  493. * the archive. If one or more paths are specified, only these are included.
  494. *
  495. * @param paths
  496. * file names (e.g <code>file1.c</code>) or directory names (e.g.
  497. * <code>dir</code> to add <code>dir/file1</code> and
  498. * <code>dir/file2</code>) can also be given to add all files in
  499. * the directory, recursively. Fileglobs (e.g. *.c) are not yet
  500. * supported.
  501. * @return this
  502. * @since 3.4
  503. */
  504. public ArchiveCommand setPaths(String... paths) {
  505. this.paths = Arrays.asList(paths);
  506. return this;
  507. }
  508. }