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

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