View Javadoc
1   /*
2    * Copyright (C) 2012 Google Inc. 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  
11  package org.eclipse.jgit.pgm;
12  
13  import java.io.FileNotFoundException;
14  import java.io.FileOutputStream;
15  import java.io.OutputStream;
16  
17  import org.eclipse.jgit.api.ArchiveCommand;
18  import org.eclipse.jgit.api.Git;
19  import org.eclipse.jgit.api.errors.GitAPIException;
20  import org.eclipse.jgit.archive.ArchiveFormats;
21  import org.eclipse.jgit.lib.ObjectId;
22  import org.eclipse.jgit.pgm.internal.CLIText;
23  import org.kohsuke.args4j.Argument;
24  import org.kohsuke.args4j.Option;
25  
26  @Command(common = true, usage = "usage_archive")
27  class Archive extends TextBuiltin {
28  	static {
29  		ArchiveFormats.registerAll();
30  	}
31  
32  	@Argument(index = 0, metaVar = "metaVar_treeish")
33  	private ObjectId tree;
34  
35  	@Option(name = "--format", metaVar = "metaVar_archiveFormat", usage = "usage_archiveFormat")
36  	private String format;
37  
38  	@Option(name = "--prefix", metaVar = "metaVar_archivePrefix", usage = "usage_archivePrefix")
39  	private String prefix;
40  
41  	@Option(name = "--output", aliases = { "-o" }, metaVar = "metaVar_file", usage = "usage_archiveOutput")
42  	private String output;
43  
44  	/** {@inheritDoc} */
45  	@Override
46  	protected void run() throws Exception {
47  		if (tree == null)
48  			throw die(CLIText.get().treeIsRequired);
49  
50  		OutputStream stream = null;
51  		try {
52  			if (output != null)
53  				stream = new FileOutputStream(output);
54  			else
55  				stream = outs;
56  
57  			try (Git git = new Git(db)) {
58  				ArchiveCommand cmd = git.archive()
59  					.setTree(tree)
60  					.setFormat(format)
61  					.setPrefix(prefix)
62  					.setOutputStream(stream);
63  				if (output != null)
64  					cmd.setFilename(output);
65  				cmd.call();
66  			} catch (GitAPIException e) {
67  				throw die(e.getMessage(), e);
68  			}
69  		} catch (FileNotFoundException e) {
70  			throw die(e.getMessage(), e);
71  		} finally {
72  			if (output != null && stream != null)
73  				stream.close();
74  		}
75  	}
76  }