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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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.concurrent.ConcurrentHashMap;
  49. import java.util.concurrent.ConcurrentMap;
  50. import org.eclipse.jgit.api.errors.GitAPIException;
  51. import org.eclipse.jgit.api.errors.JGitInternalException;
  52. import org.eclipse.jgit.internal.JGitText;
  53. import org.eclipse.jgit.lib.FileMode;
  54. import org.eclipse.jgit.lib.MutableObjectId;
  55. import org.eclipse.jgit.lib.ObjectId;
  56. import org.eclipse.jgit.lib.ObjectLoader;
  57. import org.eclipse.jgit.lib.ObjectReader;
  58. import org.eclipse.jgit.lib.Repository;
  59. import org.eclipse.jgit.revwalk.RevWalk;
  60. import org.eclipse.jgit.treewalk.TreeWalk;
  61. /**
  62. * Create an archive of files from a named tree.
  63. * <p>
  64. * Examples (<code>git</code> is a {@link Git} instance):
  65. * <p>
  66. * Create a tarball from HEAD:
  67. *
  68. * <pre>
  69. * ArchiveCommand.registerFormat("tar", new TarFormat());
  70. * try {
  71. * git.archive()
  72. * .setTree(db.resolve(&quot;HEAD&quot;))
  73. * .setOutputStream(out)
  74. * .call();
  75. * } finally {
  76. * ArchiveCommand.unregisterFormat("tar");
  77. * }
  78. * </pre>
  79. * <p>
  80. * Create a ZIP file from master:
  81. *
  82. * <pre>
  83. * ArchiveCommand.registerFormat("zip", new ZipFormat());
  84. * try {
  85. * git.archive().
  86. * .setTree(db.resolve(&quot;master&quot;))
  87. * .setFormat("zip")
  88. * .setOutputStream(out)
  89. * .call();
  90. * } finally {
  91. * ArchiveCommand.unregisterFormat("zip");
  92. * }
  93. * </pre>
  94. *
  95. * @see <a href="http://git-htmldocs.googlecode.com/git/git-archive.html" >Git
  96. * documentation about archive</a>
  97. *
  98. * @since 3.1
  99. */
  100. public class ArchiveCommand extends GitCommand<OutputStream> {
  101. /**
  102. * Archival format.
  103. *
  104. * Usage:
  105. * Repository repo = git.getRepository();
  106. * T out = format.createArchiveOutputStream(System.out);
  107. * try {
  108. * for (...) {
  109. * format.putEntry(out, path, mode, repo.open(objectId));
  110. * }
  111. * out.close();
  112. * }
  113. *
  114. * @param <T>
  115. * type representing an archive being created.
  116. */
  117. public static interface Format<T extends Closeable> {
  118. /**
  119. * Start a new archive. Entries can be included in the archive using the
  120. * putEntry method, and then the archive should be closed using its
  121. * close method.
  122. *
  123. * @param s
  124. * underlying output stream to which to write the archive.
  125. * @return new archive object for use in putEntry
  126. * @throws IOException
  127. * thrown by the underlying output stream for I/O errors
  128. */
  129. T createArchiveOutputStream(OutputStream s) throws IOException;
  130. /**
  131. * Write an entry to an archive.
  132. *
  133. * @param out
  134. * archive object from createArchiveOutputStream
  135. * @param path
  136. * full filename relative to the root of the archive
  137. * (with trailing '/' for directories)
  138. * @param mode
  139. * mode (for example FileMode.REGULAR_FILE or
  140. * FileMode.SYMLINK)
  141. * @param loader
  142. * blob object with data for this entry (null for
  143. * directories)
  144. * @throws IOException
  145. * thrown by the underlying output stream for I/O errors
  146. */
  147. void putEntry(T out, String path, FileMode mode,
  148. ObjectLoader loader) throws IOException;
  149. /**
  150. * Filename suffixes representing this format (e.g.,
  151. * { ".tar.gz", ".tgz" }).
  152. *
  153. * The behavior is undefined when suffixes overlap (if
  154. * one format claims suffix ".7z", no other format should
  155. * take ".tar.7z").
  156. *
  157. * @return this format's suffixes
  158. */
  159. Iterable<String> suffixes();
  160. }
  161. /**
  162. * Signals an attempt to use an archival format that ArchiveCommand
  163. * doesn't know about (for example due to a typo).
  164. */
  165. public static class UnsupportedFormatException extends GitAPIException {
  166. private static final long serialVersionUID = 1L;
  167. private final String format;
  168. /**
  169. * @param format the problematic format name
  170. */
  171. public UnsupportedFormatException(String format) {
  172. super(MessageFormat.format(JGitText.get().unsupportedArchiveFormat, format));
  173. this.format = format;
  174. }
  175. /**
  176. * @return the problematic format name
  177. */
  178. public String getFormat() {
  179. return format;
  180. }
  181. }
  182. /**
  183. * Available archival formats (corresponding to values for
  184. * the --format= option)
  185. */
  186. private static final ConcurrentMap<String, Format<?>> formats =
  187. new ConcurrentHashMap<String, Format<?>>();
  188. /**
  189. * Adds support for an additional archival format. To avoid
  190. * unnecessary dependencies, ArchiveCommand does not have support
  191. * for any formats built in; use this function to add them.
  192. *
  193. * OSGi plugins providing formats should call this function at
  194. * bundle activation time.
  195. *
  196. * @param name name of a format (e.g., "tar" or "zip").
  197. * @param fmt archiver for that format
  198. * @throws JGitInternalException
  199. * An archival format with that name was already registered.
  200. */
  201. public static void registerFormat(String name, Format<?> fmt) {
  202. // TODO(jrn): Check that suffixes don't overlap.
  203. if (formats.putIfAbsent(name, fmt) != null)
  204. throw new JGitInternalException(MessageFormat.format(
  205. JGitText.get().archiveFormatAlreadyRegistered,
  206. name));
  207. }
  208. /**
  209. * Removes support for an archival format so its Format can be
  210. * garbage collected.
  211. *
  212. * @param name name of format (e.g., "tar" or "zip").
  213. * @throws JGitInternalException
  214. * No such archival format was registered.
  215. */
  216. public static void unregisterFormat(String name) {
  217. if (formats.remove(name) == null)
  218. throw new JGitInternalException(MessageFormat.format(
  219. JGitText.get().archiveFormatAlreadyAbsent,
  220. name));
  221. }
  222. private static Format<?> formatBySuffix(String filenameSuffix)
  223. throws UnsupportedFormatException {
  224. if (filenameSuffix != null)
  225. for (Format<?> fmt : formats.values())
  226. for (String sfx : fmt.suffixes())
  227. if (filenameSuffix.endsWith(sfx))
  228. return fmt;
  229. return lookupFormat("tar"); //$NON-NLS-1$
  230. }
  231. private static Format<?> lookupFormat(String formatName) throws UnsupportedFormatException {
  232. Format<?> fmt = formats.get(formatName);
  233. if (fmt == null)
  234. throw new UnsupportedFormatException(formatName);
  235. return fmt;
  236. }
  237. private OutputStream out;
  238. private ObjectId tree;
  239. private String prefix;
  240. private String format;
  241. /** Filename suffix, for automatically choosing a format. */
  242. private String suffix;
  243. /**
  244. * @param repo
  245. */
  246. public ArchiveCommand(Repository repo) {
  247. super(repo);
  248. setCallable(false);
  249. }
  250. private <T extends Closeable> OutputStream writeArchive(Format<T> fmt) {
  251. final String pfx = prefix == null ? "" : prefix;
  252. final TreeWalk walk = new TreeWalk(repo);
  253. try {
  254. final T outa = fmt.createArchiveOutputStream(out);
  255. try {
  256. final MutableObjectId idBuf = new MutableObjectId();
  257. final ObjectReader reader = walk.getObjectReader();
  258. final RevWalk rw = new RevWalk(walk.getObjectReader());
  259. walk.reset(rw.parseTree(tree));
  260. while (walk.next()) {
  261. final String name = pfx + walk.getPathString();
  262. final FileMode mode = walk.getFileMode(0);
  263. if (walk.isSubtree()) {
  264. fmt.putEntry(outa, name + "/", mode, null);
  265. walk.enterSubtree();
  266. continue;
  267. }
  268. walk.getObjectId(idBuf, 0);
  269. fmt.putEntry(outa, name, mode, reader.open(idBuf));
  270. }
  271. outa.close();
  272. } finally {
  273. out.close();
  274. }
  275. return out;
  276. } catch (IOException e) {
  277. // TODO(jrn): Throw finer-grained errors.
  278. throw new JGitInternalException(
  279. JGitText.get().exceptionCaughtDuringExecutionOfArchiveCommand, e);
  280. } finally {
  281. walk.release();
  282. }
  283. }
  284. /**
  285. * @return the stream to which the archive has been written
  286. */
  287. @Override
  288. public OutputStream call() throws GitAPIException {
  289. checkCallable();
  290. final Format<?> fmt;
  291. if (format == null)
  292. fmt = formatBySuffix(suffix);
  293. else
  294. fmt = lookupFormat(format);
  295. return writeArchive(fmt);
  296. }
  297. /**
  298. * @param tree
  299. * the tag, commit, or tree object to produce an archive for
  300. * @return this
  301. */
  302. public ArchiveCommand setTree(ObjectId tree) {
  303. if (tree == null)
  304. throw new IllegalArgumentException();
  305. this.tree = tree;
  306. setCallable(true);
  307. return this;
  308. }
  309. /**
  310. * @param prefix
  311. * string prefixed to filenames in archive (e.g., "master/").
  312. * null means to not use any leading prefix.
  313. * @return this
  314. * @since 3.3
  315. */
  316. public ArchiveCommand setPrefix(String prefix) {
  317. this.prefix = prefix;
  318. return this;
  319. }
  320. /**
  321. * Set the intended filename for the produced archive. Currently the only
  322. * effect is to determine the default archive format when none is specified
  323. * with {@link #setFormat(String)}.
  324. *
  325. * @param filename
  326. * intended filename for the archive
  327. * @return this
  328. */
  329. public ArchiveCommand setFilename(String filename) {
  330. int slash = filename.lastIndexOf('/');
  331. int dot = filename.indexOf('.', slash + 1);
  332. if (dot == -1)
  333. this.suffix = ""; //$NON-NLS-1$
  334. else
  335. this.suffix = filename.substring(dot);
  336. return this;
  337. }
  338. /**
  339. * @param out
  340. * the stream to which to write the archive
  341. * @return this
  342. */
  343. public ArchiveCommand setOutputStream(OutputStream out) {
  344. this.out = out;
  345. return this;
  346. }
  347. /**
  348. * @param fmt
  349. * archive format (e.g., "tar" or "zip").
  350. * null means to choose automatically based on
  351. * the archive filename.
  352. * @return this
  353. */
  354. public ArchiveCommand setFormat(String fmt) {
  355. this.format = fmt;
  356. return this;
  357. }
  358. }