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.

ArchiveCommandTest.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. /*
  2. * Copyright (C) 2014, Shaul Zorea <shaulzorea@gmail.com> and others
  3. *
  4. * This program and the accompanying materials are made available under the
  5. * terms of the Eclipse Distribution License v. 1.0 which is available at
  6. * https://www.eclipse.org/org/documents/edl-v10.php.
  7. *
  8. * SPDX-License-Identifier: BSD-3-Clause
  9. */
  10. package org.eclipse.jgit.api;
  11. import static java.nio.charset.StandardCharsets.UTF_8;
  12. import static org.junit.Assert.assertEquals;
  13. import static org.junit.Assert.assertNull;
  14. import static org.junit.Assert.assertTrue;
  15. import java.beans.Statement;
  16. import java.io.BufferedInputStream;
  17. import java.io.File;
  18. import java.io.FileNotFoundException;
  19. import java.io.FileOutputStream;
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import java.io.OutputStream;
  23. import java.nio.file.Files;
  24. import java.util.Arrays;
  25. import java.util.Collections;
  26. import java.util.HashMap;
  27. import java.util.List;
  28. import java.util.Map;
  29. import java.util.Random;
  30. import org.apache.commons.compress.archivers.ArchiveEntry;
  31. import org.apache.commons.compress.archivers.ArchiveInputStream;
  32. import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
  33. import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
  34. import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
  35. import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
  36. import org.apache.commons.compress.compressors.xz.XZCompressorInputStream;
  37. import org.eclipse.jgit.api.errors.AbortedByHookException;
  38. import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
  39. import org.eclipse.jgit.api.errors.GitAPIException;
  40. import org.eclipse.jgit.api.errors.NoFilepatternException;
  41. import org.eclipse.jgit.api.errors.NoHeadException;
  42. import org.eclipse.jgit.api.errors.NoMessageException;
  43. import org.eclipse.jgit.api.errors.UnmergedPathsException;
  44. import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
  45. import org.eclipse.jgit.archive.ArchiveFormats;
  46. import org.eclipse.jgit.errors.AmbiguousObjectException;
  47. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  48. import org.eclipse.jgit.junit.RepositoryTestCase;
  49. import org.eclipse.jgit.lib.FileMode;
  50. import org.eclipse.jgit.lib.ObjectId;
  51. import org.eclipse.jgit.lib.ObjectLoader;
  52. import org.eclipse.jgit.revwalk.RevCommit;
  53. import org.eclipse.jgit.util.IO;
  54. import org.eclipse.jgit.util.StringUtils;
  55. import org.junit.After;
  56. import org.junit.Before;
  57. import org.junit.Ignore;
  58. import org.junit.Test;
  59. public class ArchiveCommandTest extends RepositoryTestCase {
  60. // archives store timestamp with 1 second resolution
  61. private static final int WAIT = 2000;
  62. private static final String UNEXPECTED_ARCHIVE_SIZE = "Unexpected archive size";
  63. private static final String UNEXPECTED_FILE_CONTENTS = "Unexpected file contents";
  64. private static final String UNEXPECTED_TREE_CONTENTS = "Unexpected tree contents";
  65. private static final String UNEXPECTED_LAST_MODIFIED =
  66. "Unexpected lastModified mocked by MockSystemReader, truncated to 1 second";
  67. private static final String UNEXPECTED_DIFFERENT_HASH = "Unexpected different hash";
  68. private MockFormat format = null;
  69. @Before
  70. public void setup() {
  71. format = new MockFormat();
  72. ArchiveCommand.registerFormat(format.SUFFIXES.get(0), format);
  73. ArchiveFormats.registerAll();
  74. }
  75. @Override
  76. @After
  77. public void tearDown() {
  78. ArchiveCommand.unregisterFormat(format.SUFFIXES.get(0));
  79. ArchiveFormats.unregisterAll();
  80. }
  81. @Test
  82. public void archiveHeadAllFiles() throws IOException, GitAPIException {
  83. try (Git git = new Git(db)) {
  84. createTestContent(git);
  85. git.archive().setOutputStream(new MockOutputStream())
  86. .setFormat(format.SUFFIXES.get(0))
  87. .setTree(git.getRepository().resolve("HEAD")).call();
  88. assertEquals(UNEXPECTED_ARCHIVE_SIZE, 2, format.size());
  89. assertEquals(UNEXPECTED_FILE_CONTENTS, "content_1_2", format.getByPath("file_1.txt"));
  90. assertEquals(UNEXPECTED_FILE_CONTENTS, "content_2_2", format.getByPath("file_2.txt"));
  91. }
  92. }
  93. @Test
  94. public void archiveHeadSpecificPath() throws IOException, GitAPIException {
  95. try (Git git = new Git(db)) {
  96. writeTrashFile("file_1.txt", "content_1_1");
  97. git.add().addFilepattern("file_1.txt").call();
  98. git.commit().setMessage("create file").call();
  99. writeTrashFile("file_1.txt", "content_1_2");
  100. String expectedFilePath = "some_directory/file_2.txt";
  101. writeTrashFile(expectedFilePath, "content_2_2");
  102. git.add().addFilepattern(".").call();
  103. git.commit().setMessage("updated file").call();
  104. git.archive().setOutputStream(new MockOutputStream())
  105. .setFormat(format.SUFFIXES.get(0))
  106. .setTree(git.getRepository().resolve("HEAD"))
  107. .setPaths(expectedFilePath).call();
  108. assertEquals(UNEXPECTED_ARCHIVE_SIZE, 2, format.size());
  109. assertEquals(UNEXPECTED_FILE_CONTENTS, "content_2_2", format.getByPath(expectedFilePath));
  110. assertNull(UNEXPECTED_TREE_CONTENTS, format.getByPath("some_directory"));
  111. }
  112. }
  113. @Test
  114. public void archiveByIdSpecificFile() throws IOException, GitAPIException {
  115. try (Git git = new Git(db)) {
  116. writeTrashFile("file_1.txt", "content_1_1");
  117. git.add().addFilepattern("file_1.txt").call();
  118. RevCommit first = git.commit().setMessage("create file").call();
  119. writeTrashFile("file_1.txt", "content_1_2");
  120. String expectedFilePath = "some_directory/file_2.txt";
  121. writeTrashFile(expectedFilePath, "content_2_2");
  122. git.add().addFilepattern(".").call();
  123. git.commit().setMessage("updated file").call();
  124. Map<String, Object> options = new HashMap<>();
  125. Integer opt = Integer.valueOf(42);
  126. options.put("foo", opt);
  127. MockOutputStream out = new MockOutputStream();
  128. git.archive().setOutputStream(out)
  129. .setFormat(format.SUFFIXES.get(0))
  130. .setFormatOptions(options)
  131. .setTree(first)
  132. .setPaths("file_1.txt").call();
  133. assertEquals(opt.intValue(), out.getFoo());
  134. assertEquals(UNEXPECTED_ARCHIVE_SIZE, 1, format.size());
  135. assertEquals(UNEXPECTED_FILE_CONTENTS, "content_1_1", format.getByPath("file_1.txt"));
  136. }
  137. }
  138. @Test
  139. public void archiveByDirectoryPath() throws GitAPIException, IOException {
  140. try (Git git = new Git(db)) {
  141. writeTrashFile("file_0.txt", "content_0_1");
  142. git.add().addFilepattern("file_0.txt").call();
  143. git.commit().setMessage("commit_1").call();
  144. writeTrashFile("file_0.txt", "content_0_2");
  145. String expectedFilePath1 = "some_directory/file_1.txt";
  146. writeTrashFile(expectedFilePath1, "content_1_2");
  147. String expectedFilePath2 = "some_directory/file_2.txt";
  148. writeTrashFile(expectedFilePath2, "content_2_2");
  149. String expectedFilePath3 = "some_directory/nested_directory/file_3.txt";
  150. writeTrashFile(expectedFilePath3, "content_3_2");
  151. git.add().addFilepattern(".").call();
  152. git.commit().setMessage("commit_2").call();
  153. git.archive().setOutputStream(new MockOutputStream())
  154. .setFormat(format.SUFFIXES.get(0))
  155. .setTree(git.getRepository().resolve("HEAD"))
  156. .setPaths("some_directory/").call();
  157. assertEquals(UNEXPECTED_ARCHIVE_SIZE, 5, format.size());
  158. assertEquals(UNEXPECTED_FILE_CONTENTS, "content_1_2", format.getByPath(expectedFilePath1));
  159. assertEquals(UNEXPECTED_FILE_CONTENTS, "content_2_2", format.getByPath(expectedFilePath2));
  160. assertEquals(UNEXPECTED_FILE_CONTENTS, "content_3_2", format.getByPath(expectedFilePath3));
  161. assertNull(UNEXPECTED_TREE_CONTENTS, format.getByPath("some_directory"));
  162. assertNull(UNEXPECTED_TREE_CONTENTS, format.getByPath("some_directory/nested_directory"));
  163. }
  164. }
  165. @Test
  166. public void archiveHeadAllFilesTarTimestamps() throws Exception {
  167. archiveHeadAllFiles("tar");
  168. }
  169. @Test
  170. public void archiveHeadAllFilesTgzTimestamps() throws Exception {
  171. archiveHeadAllFiles("tgz");
  172. }
  173. @Test
  174. public void archiveHeadAllFilesTbz2Timestamps() throws Exception {
  175. archiveHeadAllFiles("tbz2");
  176. }
  177. @Test
  178. public void archiveHeadAllFilesTxzTimestamps() throws Exception {
  179. archiveHeadAllFiles("txz");
  180. }
  181. @Test
  182. public void archiveHeadAllFilesZipTimestamps() throws Exception {
  183. archiveHeadAllFiles("zip");
  184. }
  185. @Test
  186. public void archiveHeadAllFilesTgzWithCompressionReducesArchiveSize() throws Exception {
  187. archiveHeadAllFilesWithCompression("tgz");
  188. }
  189. @Test
  190. public void archiveHeadAllFilesTbz2WithCompressionReducesArchiveSize() throws Exception {
  191. archiveHeadAllFilesWithCompression("tbz2");
  192. }
  193. @Test
  194. @Ignore
  195. public void archiveHeadAllFilesTxzWithCompressionReducesArchiveSize() throws Exception {
  196. // We ignore this test because the txz format consumes a lot of memory for high level
  197. // compressions.
  198. archiveHeadAllFilesWithCompression("txz");
  199. }
  200. @Test
  201. public void archiveHeadAllFilesZipWithCompressionReducesArchiveSize() throws Exception {
  202. archiveHeadAllFilesWithCompression("zip");
  203. }
  204. private void archiveHeadAllFiles(String fmt) throws Exception {
  205. try (Git git = new Git(db)) {
  206. createTestContent(git);
  207. File archive = new File(getTemporaryDirectory(),
  208. "archive." + format);
  209. archive(git, archive, fmt);
  210. ObjectId hash1 = ObjectId.fromRaw(IO.readFully(archive));
  211. try (InputStream fi = Files.newInputStream(archive.toPath());
  212. InputStream bi = new BufferedInputStream(fi);
  213. ArchiveInputStream o = createArchiveInputStream(fmt, bi)) {
  214. assertEntries(o);
  215. }
  216. Thread.sleep(WAIT);
  217. archive(git, archive, fmt);
  218. assertEquals(UNEXPECTED_DIFFERENT_HASH, hash1,
  219. ObjectId.fromRaw(IO.readFully(archive)));
  220. }
  221. }
  222. @SuppressWarnings({ "serial", "boxing" })
  223. private void archiveHeadAllFilesWithCompression(String fmt) throws Exception {
  224. try (Git git = new Git(db)) {
  225. createLargeTestContent(git);
  226. File archive = new File(getTemporaryDirectory(),
  227. "archive." + format);
  228. archive(git, archive, fmt, new HashMap<String, Object>() {{
  229. put("compression-level", 1);
  230. }});
  231. int sizeCompression1 = getNumBytes(archive);
  232. archive(git, archive, fmt, new HashMap<String, Object>() {{
  233. put("compression-level", 9);
  234. }});
  235. int sizeCompression9 = getNumBytes(archive);
  236. assertTrue(sizeCompression1 > sizeCompression9);
  237. }
  238. }
  239. private static ArchiveInputStream createArchiveInputStream (String fmt, InputStream bi)
  240. throws IOException {
  241. switch (fmt) {
  242. case "tar":
  243. return new TarArchiveInputStream(bi);
  244. case "tgz":
  245. return new TarArchiveInputStream(new GzipCompressorInputStream(bi));
  246. case "tbz2":
  247. return new TarArchiveInputStream(new BZip2CompressorInputStream(bi));
  248. case "txz":
  249. return new TarArchiveInputStream(new XZCompressorInputStream(bi));
  250. case "zip":
  251. return new ZipArchiveInputStream(new BufferedInputStream(bi));
  252. }
  253. throw new IllegalArgumentException("Format " + fmt + " is not supported.");
  254. }
  255. private void createTestContent(Git git) throws IOException, GitAPIException,
  256. NoFilepatternException, NoHeadException, NoMessageException,
  257. UnmergedPathsException, ConcurrentRefUpdateException,
  258. WrongRepositoryStateException, AbortedByHookException {
  259. writeTrashFile("file_1.txt", "content_1_1");
  260. git.add().addFilepattern("file_1.txt").call();
  261. git.commit().setMessage("create file").call();
  262. writeTrashFile("file_1.txt", "content_1_2");
  263. writeTrashFile("file_2.txt", "content_2_2");
  264. git.add().addFilepattern(".").call();
  265. git.commit().setMessage("updated file").call();
  266. }
  267. private void createLargeTestContent(Git git) throws IOException, GitAPIException,
  268. NoFilepatternException, NoHeadException, NoMessageException,
  269. UnmergedPathsException, ConcurrentRefUpdateException,
  270. WrongRepositoryStateException, AbortedByHookException {
  271. StringBuilder largeContent = new StringBuilder();
  272. Random r = new Random();
  273. for (int i = 0; i < 2000; i++) {
  274. for (int j = 0; j < 80; j++) {
  275. largeContent.append((char)(r.nextInt(26) + 'a'));
  276. }
  277. largeContent.append("\n");
  278. }
  279. writeTrashFile("large_file.txt", largeContent.toString());
  280. git.add().addFilepattern("large_file.txt").call();
  281. git.commit().setMessage("create file").call();
  282. }
  283. private static void archive(Git git, File archive, String fmt)
  284. throws GitAPIException,
  285. FileNotFoundException, AmbiguousObjectException,
  286. IncorrectObjectTypeException, IOException {
  287. archive(git, archive, fmt, new HashMap<>());
  288. }
  289. private static void archive(Git git, File archive, String fmt, Map<String,
  290. Object> options)
  291. throws GitAPIException,
  292. FileNotFoundException, AmbiguousObjectException,
  293. IncorrectObjectTypeException, IOException {
  294. git.archive().setOutputStream(new FileOutputStream(archive))
  295. .setFormat(fmt)
  296. .setTree(git.getRepository().resolve("HEAD"))
  297. .setFormatOptions(options)
  298. .call();
  299. }
  300. private static void assertEntries(ArchiveInputStream o) throws IOException {
  301. ArchiveEntry e;
  302. int n = 0;
  303. while ((e = o.getNextEntry()) != null) {
  304. n++;
  305. assertEquals(UNEXPECTED_LAST_MODIFIED,
  306. (1250379778668L / 1000L) * 1000L,
  307. e.getLastModifiedDate().getTime());
  308. }
  309. assertEquals(UNEXPECTED_ARCHIVE_SIZE, 2, n);
  310. }
  311. private static int getNumBytes(File archive) throws Exception {
  312. try (InputStream fi = Files.newInputStream(archive.toPath());
  313. InputStream bi = new BufferedInputStream(fi)) {
  314. return bi.available();
  315. }
  316. }
  317. private static class MockFormat
  318. implements ArchiveCommand.Format<MockOutputStream> {
  319. private Map<String, String> entries = new HashMap<>();
  320. private int size() {
  321. return entries.size();
  322. }
  323. private String getByPath(String path) {
  324. return entries.get(path);
  325. }
  326. private final List<String> SUFFIXES = Collections
  327. .unmodifiableList(Arrays.asList(".mck"));
  328. @Override
  329. public MockOutputStream createArchiveOutputStream(OutputStream s)
  330. throws IOException {
  331. return createArchiveOutputStream(s,
  332. Collections.<String, Object> emptyMap());
  333. }
  334. @Override
  335. public MockOutputStream createArchiveOutputStream(OutputStream s,
  336. Map<String, Object> o) throws IOException {
  337. for (Map.Entry<String, Object> p : o.entrySet()) {
  338. try {
  339. String methodName = "set"
  340. + StringUtils.capitalize(p.getKey());
  341. new Statement(s, methodName, new Object[] { p.getValue() })
  342. .execute();
  343. } catch (Exception e) {
  344. throw new IOException("cannot set option: " + p.getKey(), e);
  345. }
  346. }
  347. return new MockOutputStream();
  348. }
  349. @Override
  350. public void putEntry(MockOutputStream out, ObjectId tree, String path, FileMode mode, ObjectLoader loader) {
  351. String content = mode != FileMode.TREE
  352. ? new String(loader.getBytes(), UTF_8)
  353. : null;
  354. entries.put(path, content);
  355. }
  356. @Override
  357. public Iterable<String> suffixes() {
  358. return SUFFIXES;
  359. }
  360. }
  361. public static class MockOutputStream extends OutputStream {
  362. private int foo;
  363. public void setFoo(int foo) {
  364. this.foo = foo;
  365. }
  366. public int getFoo() {
  367. return foo;
  368. }
  369. @Override
  370. public void write(int b) throws IOException {
  371. // Do nothing. for testing purposes.
  372. }
  373. }
  374. }