1 /*
2 * Copyright (C) 2007, Robin Rosenberg <robin.rosenberg@dewire.com>
3 * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
4 * and other copyright owners as documented in the project's IP log.
5 *
6 * This program and the accompanying materials are made available
7 * under the terms of the Eclipse Distribution License v1.0 which
8 * accompanies this distribution, is reproduced below, and is
9 * available at http://www.eclipse.org/org/documents/edl-v10.php
10 *
11 * All rights reserved.
12 *
13 * Redistribution and use in source and binary forms, with or
14 * without modification, are permitted provided that the following
15 * conditions are met:
16 *
17 * - Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 *
20 * - Redistributions in binary form must reproduce the above
21 * copyright notice, this list of conditions and the following
22 * disclaimer in the documentation and/or other materials provided
23 * with the distribution.
24 *
25 * - Neither the name of the Eclipse Foundation, Inc. nor the
26 * names of its contributors may be used to endorse or promote
27 * products derived from this software without specific prior
28 * written permission.
29 *
30 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
31 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
32 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
35 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
37 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
38 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
39 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
40 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
41 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
42 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43 */
44
45 package org.eclipse.jgit.pgm;
46
47 import static org.eclipse.jgit.lib.Constants.R_HEADS;
48 import static org.eclipse.jgit.lib.Constants.R_REMOTES;
49 import static org.eclipse.jgit.lib.Constants.R_TAGS;
50
51 import java.io.BufferedWriter;
52 import java.io.FileDescriptor;
53 import java.io.FileInputStream;
54 import java.io.FileOutputStream;
55 import java.io.IOException;
56 import java.io.InputStream;
57 import java.io.OutputStream;
58 import java.io.OutputStreamWriter;
59 import java.text.MessageFormat;
60 import java.util.ResourceBundle;
61
62 import org.eclipse.jgit.lib.ObjectId;
63 import org.eclipse.jgit.lib.Repository;
64 import org.eclipse.jgit.pgm.internal.CLIText;
65 import org.eclipse.jgit.pgm.opt.CmdLineParser;
66 import org.eclipse.jgit.revwalk.RevWalk;
67 import org.eclipse.jgit.util.io.ThrowingPrintWriter;
68 import org.kohsuke.args4j.CmdLineException;
69 import org.kohsuke.args4j.Option;
70
71 /**
72 * Abstract command which can be invoked from the command line.
73 * <p>
74 * Commands are configured with a single "current" repository and then the
75 * {@link #execute(String[])} method is invoked with the arguments that appear
76 * on the command line after the command name.
77 * <p>
78 * Command constructors should perform as little work as possible as they may be
79 * invoked very early during process loading, and the command may not execute
80 * even though it was constructed.
81 */
82 public abstract class TextBuiltin {
83 private String commandName;
84
85 @Option(name = "--help", usage = "usage_displayThisHelpText", aliases = { "-h" })
86 private boolean help;
87
88 /**
89 * Input stream, typically this is standard input.
90 *
91 * @since 3.4
92 */
93 protected InputStream ins;
94
95 /**
96 * Writer to output to, typically this is standard output.
97 *
98 * @since 2.2
99 */
100 protected ThrowingPrintWriter outw;
101
102 /**
103 * Stream to output to, typically this is standard output.
104 *
105 * @since 2.2
106 */
107 protected OutputStream outs;
108
109 /**
110 * Error writer, typically this is standard error.
111 *
112 * @since 3.4
113 */
114 protected ThrowingPrintWriter errw;
115
116 /**
117 * Error output stream, typically this is standard error.
118 *
119 * @since 3.4
120 */
121 protected OutputStream errs;
122
123 /** Git repository the command was invoked within. */
124 protected Repository db;
125
126 /** Directory supplied via --git-dir command line option. */
127 protected String gitdir;
128
129 /** RevWalk used during command line parsing, if it was required. */
130 protected RevWalk argWalk;
131
132 final void setCommandName(final String name) {
133 commandName = name;
134 }
135
136 /** @return true if {@link #db}/{@link #getRepository()} is required. */
137 protected boolean requiresRepository() {
138 return true;
139 }
140
141 /**
142 * Initialize the command to work with a repository.
143 *
144 * @param repository
145 * the opened repository that the command should work on.
146 * @param gitDir
147 * value of the {@code --git-dir} command line option, if
148 * {@code repository} is null.
149 */
150 protected void init(final Repository repository, final String gitDir) {
151 try {
152 final String outputEncoding = repository != null ? repository
153 .getConfig().getString("i18n", null, "logOutputEncoding") : null; //$NON-NLS-1$ //$NON-NLS-2$
154 if (ins == null)
155 ins = new FileInputStream(FileDescriptor.in);
156 if (outs == null)
157 outs = new FileOutputStream(FileDescriptor.out);
158 if (errs == null)
159 errs = new FileOutputStream(FileDescriptor.err);
160 BufferedWriter outbufw;
161 if (outputEncoding != null)
162 outbufw = new BufferedWriter(new OutputStreamWriter(outs,
163 outputEncoding));
164 else
165 outbufw = new BufferedWriter(new OutputStreamWriter(outs));
166 outw = new ThrowingPrintWriter(outbufw);
167 BufferedWriter errbufw;
168 if (outputEncoding != null)
169 errbufw = new BufferedWriter(new OutputStreamWriter(errs,
170 outputEncoding));
171 else
172 errbufw = new BufferedWriter(new OutputStreamWriter(errs));
173 errw = new ThrowingPrintWriter(errbufw);
174 } catch (IOException e) {
175 throw die(CLIText.get().cannotCreateOutputStream);
176 }
177
178 if (repository != null && repository.getDirectory() != null) {
179 db = repository;
180 gitdir = repository.getDirectory().getAbsolutePath();
181 } else {
182 db = repository;
183 gitdir = gitDir;
184 }
185 }
186
187 /**
188 * Parse arguments and run this command.
189 *
190 * @param args
191 * command line arguments passed after the command name.
192 * @throws Exception
193 * an error occurred while processing the command. The main
194 * framework will catch the exception and print a message on
195 * standard error.
196 */
197 public final void execute(String[] args) throws Exception {
198 parseArguments(args);
199 run();
200 }
201
202 /**
203 * Parses the command line arguments prior to running.
204 * <p>
205 * This method should only be invoked by {@link #execute(String[])}, prior
206 * to calling {@link #run()}. The default implementation parses all
207 * arguments into this object's instance fields.
208 *
209 * @param args
210 * the arguments supplied on the command line, if any.
211 * @throws IOException
212 */
213 protected void parseArguments(final String[] args) throws IOException {
214 final CmdLineParser clp = new CmdLineParser(this);
215 try {
216 clp.parseArgument(args);
217 } catch (CmdLineException err) {
218 if (!help) {
219 this.errw.println(MessageFormat.format(CLIText.get().fatalError, err.getMessage()));
220 throw die(true);
221 }
222 }
223
224 if (help) {
225 printUsageAndExit(clp);
226 }
227
228 argWalk = clp.getRevWalkGently();
229 }
230
231 /**
232 * Print the usage line
233 *
234 * @param clp
235 * @throws IOException
236 */
237 public void printUsageAndExit(final CmdLineParser clp) throws IOException {
238 printUsageAndExit("", clp); //$NON-NLS-1$
239 }
240
241 /**
242 * Print an error message and the usage line
243 *
244 * @param message
245 * @param clp
246 * @throws IOException
247 */
248 public void printUsageAndExit(final String message, final CmdLineParser clp) throws IOException {
249 errw.println(message);
250 errw.print("jgit "); //$NON-NLS-1$
251 errw.print(commandName);
252 clp.printSingleLineUsage(errw, getResourceBundle());
253 errw.println();
254
255 errw.println();
256 clp.printUsage(errw, getResourceBundle());
257 errw.println();
258
259 errw.flush();
260 throw die(true);
261 }
262
263 /**
264 * @return the resource bundle that will be passed to args4j for purpose
265 * of string localization
266 */
267 protected ResourceBundle getResourceBundle() {
268 return CLIText.get().resourceBundle();
269 }
270
271 /**
272 * Perform the actions of this command.
273 * <p>
274 * This method should only be invoked by {@link #execute(String[])}.
275 *
276 * @throws Exception
277 * an error occurred while processing the command. The main
278 * framework will catch the exception and print a message on
279 * standard error.
280 */
281 protected abstract void run() throws Exception;
282
283 /**
284 * @return the repository this command accesses.
285 */
286 public Repository getRepository() {
287 return db;
288 }
289
290 ObjectId resolve(final String s) throws IOException {
291 final ObjectId r = db.resolve(s);
292 if (r == null)
293 throw die(MessageFormat.format(CLIText.get().notARevision, s));
294 return r;
295 }
296
297 /**
298 * @param why
299 * textual explanation
300 * @return a runtime exception the caller is expected to throw
301 */
302 protected static Die die(final String why) {
303 return new Die(why);
304 }
305
306 /**
307 * @param why
308 * textual explanation
309 * @param cause
310 * why the command has failed.
311 * @return a runtime exception the caller is expected to throw
312 */
313 protected static Die die(final String why, final Throwable cause) {
314 return new Die(why, cause);
315 }
316
317 /**
318 * @param aborted
319 * boolean indicating that the execution has been aborted before running
320 * @return a runtime exception the caller is expected to throw
321 * @since 3.4
322 */
323 protected static Die die(boolean aborted) {
324 return new Die(aborted);
325 }
326
327 String abbreviateRef(String dst, boolean abbreviateRemote) {
328 if (dst.startsWith(R_HEADS))
329 dst = dst.substring(R_HEADS.length());
330 else if (dst.startsWith(R_TAGS))
331 dst = dst.substring(R_TAGS.length());
332 else if (abbreviateRemote && dst.startsWith(R_REMOTES))
333 dst = dst.substring(R_REMOTES.length());
334 return dst;
335 }
336 }