View Javadoc
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 	 * Initializes the command to work with a repository, including setting the
143 	 * output and error streams.
144 	 *
145 	 * @param repository
146 	 *            the opened repository that the command should work on.
147 	 * @param gitDir
148 	 *            value of the {@code --git-dir} command line option, if
149 	 *            {@code repository} is null.
150 	 * @param input
151 	 *            input stream from which input will be read
152 	 * @param output
153 	 *            output stream to which output will be written
154 	 * @param error
155 	 *            error stream to which errors will be written
156 	 * @since 4.9
157 	 */
158 	public void initRaw(final Repository repository, final String gitDir,
159 			InputStream input, OutputStream output, OutputStream error) {
160 		this.ins = input;
161 		this.outs = output;
162 		this.errs = error;
163 		init(repository, gitDir);
164 	}
165 
166 	/**
167 	 * Initialize the command to work with a repository.
168 	 *
169 	 * @param repository
170 	 *            the opened repository that the command should work on.
171 	 * @param gitDir
172 	 *            value of the {@code --git-dir} command line option, if
173 	 *            {@code repository} is null.
174 	 */
175 	protected void init(final Repository repository, final String gitDir) {
176 		try {
177 			final String outputEncoding = repository != null ? repository
178 					.getConfig().getString("i18n", null, "logOutputEncoding") : null; //$NON-NLS-1$ //$NON-NLS-2$
179 			if (ins == null)
180 				ins = new FileInputStream(FileDescriptor.in);
181 			if (outs == null)
182 				outs = new FileOutputStream(FileDescriptor.out);
183 			if (errs == null)
184 				errs = new FileOutputStream(FileDescriptor.err);
185 			BufferedWriter outbufw;
186 			if (outputEncoding != null)
187 				outbufw = new BufferedWriter(new OutputStreamWriter(outs,
188 						outputEncoding));
189 			else
190 				outbufw = new BufferedWriter(new OutputStreamWriter(outs));
191 			outw = new ThrowingPrintWriter(outbufw);
192 			BufferedWriter errbufw;
193 			if (outputEncoding != null)
194 				errbufw = new BufferedWriter(new OutputStreamWriter(errs,
195 						outputEncoding));
196 			else
197 				errbufw = new BufferedWriter(new OutputStreamWriter(errs));
198 			errw = new ThrowingPrintWriter(errbufw);
199 		} catch (IOException e) {
200 			throw die(CLIText.get().cannotCreateOutputStream);
201 		}
202 
203 		if (repository != null && repository.getDirectory() != null) {
204 			db = repository;
205 			gitdir = repository.getDirectory().getAbsolutePath();
206 		} else {
207 			db = repository;
208 			gitdir = gitDir;
209 		}
210 	}
211 
212 	/**
213 	 * Parse arguments and run this command.
214 	 *
215 	 * @param args
216 	 *            command line arguments passed after the command name.
217 	 * @throws Exception
218 	 *             an error occurred while processing the command. The main
219 	 *             framework will catch the exception and print a message on
220 	 *             standard error.
221 	 */
222 	public final void execute(String[] args) throws Exception {
223 		parseArguments(args);
224 		run();
225 	}
226 
227 	/**
228 	 * Parses the command line arguments prior to running.
229 	 * <p>
230 	 * This method should only be invoked by {@link #execute(String[])}, prior
231 	 * to calling {@link #run()}. The default implementation parses all
232 	 * arguments into this object's instance fields.
233 	 *
234 	 * @param args
235 	 *            the arguments supplied on the command line, if any.
236 	 * @throws IOException
237 	 */
238 	protected void parseArguments(final String[] args) throws IOException {
239 		final CmdLineParser clp = new CmdLineParser(this);
240 		help = containsHelp(args);
241 		try {
242 			clp.parseArgument(args);
243 		} catch (CmdLineException err) {
244 			this.errw.println(CLIText.fatalError(err.getMessage()));
245 			if (help) {
246 				printUsage("", clp); //$NON-NLS-1$
247 			}
248 			throw die(true, err);
249 		}
250 
251 		if (help) {
252 			printUsage("", clp); //$NON-NLS-1$
253 			throw new TerminatedByHelpException();
254 		}
255 
256 		argWalk = clp.getRevWalkGently();
257 	}
258 
259 	/**
260 	 * Print the usage line
261 	 *
262 	 * @param clp
263 	 * @throws IOException
264 	 */
265 	public void printUsageAndExit(final CmdLineParser clp) throws IOException {
266 		printUsageAndExit("", clp); //$NON-NLS-1$
267 	}
268 
269 	/**
270 	 * Print an error message and the usage line
271 	 *
272 	 * @param message
273 	 * @param clp
274 	 * @throws IOException
275 	 */
276 	public void printUsageAndExit(final String message, final CmdLineParser clp) throws IOException {
277 		printUsage(message, clp);
278 		throw die(true);
279 	}
280 
281 	/**
282 	 * @param message
283 	 *            non null
284 	 * @param clp
285 	 *            parser used to print options
286 	 * @throws IOException
287 	 * @since 4.2
288 	 */
289 	protected void printUsage(final String message, final CmdLineParser clp)
290 			throws IOException {
291 		errw.println(message);
292 		errw.print("jgit "); //$NON-NLS-1$
293 		errw.print(commandName);
294 		clp.printSingleLineUsage(errw, getResourceBundle());
295 		errw.println();
296 
297 		errw.println();
298 		clp.printUsage(errw, getResourceBundle());
299 		errw.println();
300 
301 		errw.flush();
302 	}
303 
304 	/**
305 	 * @return error writer, typically this is standard error.
306 	 * @since 4.2
307 	 */
308 	public ThrowingPrintWriter getErrorWriter() {
309 		return errw;
310 	}
311 
312 	/**
313 	 * @return output writer, typically this is standard output.
314 	 * @since 4.9
315 	 */
316 	public ThrowingPrintWriter getOutputWriter() {
317 		return outw;
318 	}
319 
320 	/**
321 	 * @return the resource bundle that will be passed to args4j for purpose of
322 	 *         string localization
323 	 */
324 	protected ResourceBundle getResourceBundle() {
325 		return CLIText.get().resourceBundle();
326 	}
327 
328 	/**
329 	 * Perform the actions of this command.
330 	 * <p>
331 	 * This method should only be invoked by {@link #execute(String[])}.
332 	 *
333 	 * @throws Exception
334 	 *             an error occurred while processing the command. The main
335 	 *             framework will catch the exception and print a message on
336 	 *             standard error.
337 	 */
338 	protected abstract void run() throws Exception;
339 
340 	/**
341 	 * @return the repository this command accesses.
342 	 */
343 	public Repository getRepository() {
344 		return db;
345 	}
346 
347 	ObjectId resolve(final String s) throws IOException {
348 		final ObjectId r = db.resolve(s);
349 		if (r == null)
350 			throw die(MessageFormat.format(CLIText.get().notARevision, s));
351 		return r;
352 	}
353 
354 	/**
355 	 * @param why
356 	 *            textual explanation
357 	 * @return a runtime exception the caller is expected to throw
358 	 */
359 	protected static Die die(final String why) {
360 		return new Die(why);
361 	}
362 
363 	/**
364 	 * @param why
365 	 *            textual explanation
366 	 * @param cause
367 	 *            why the command has failed.
368 	 * @return a runtime exception the caller is expected to throw
369 	 */
370 	protected static Die die(final String why, final Throwable cause) {
371 		return new Die(why, cause);
372 	}
373 
374 	/**
375 	 * @param aborted
376 	 *            boolean indicating that the execution has been aborted before running
377 	 * @return a runtime exception the caller is expected to throw
378 	 * @since 3.4
379 	 */
380 	protected static Die die(boolean aborted) {
381 		return new Die(aborted);
382 	}
383 
384 	/**
385 	 * @param aborted
386 	 *            boolean indicating that the execution has been aborted before
387 	 *            running
388 	 * @param cause
389 	 *            why the command has failed.
390 	 * @return a runtime exception the caller is expected to throw
391 	 * @since 4.2
392 	 */
393 	protected static Die die(boolean aborted, final Throwable cause) {
394 		return new Die(aborted, cause);
395 	}
396 
397 	String abbreviateRef(String dst, boolean abbreviateRemote) {
398 		if (dst.startsWith(R_HEADS))
399 			dst = dst.substring(R_HEADS.length());
400 		else if (dst.startsWith(R_TAGS))
401 			dst = dst.substring(R_TAGS.length());
402 		else if (abbreviateRemote && dst.startsWith(R_REMOTES))
403 			dst = dst.substring(R_REMOTES.length());
404 		return dst;
405 	}
406 
407 	/**
408 	 * @param args
409 	 *            non null
410 	 * @return true if the given array contains help option
411 	 * @since 4.2
412 	 */
413 	public static boolean containsHelp(String[] args) {
414 		for (String str : args) {
415 			if (str.equals("-h") || str.equals("--help")) { //$NON-NLS-1$ //$NON-NLS-2$
416 				return true;
417 			}
418 		}
419 		return false;
420 	}
421 
422 	/**
423 	 * Exception thrown by {@link TextBuiltin} if it proceeds 'help' option
424 	 *
425 	 * @since 4.2
426 	 */
427 	public static class TerminatedByHelpException extends Die {
428 		private static final long serialVersionUID = 1L;
429 
430 		/**
431 		 * Default constructor
432 		 */
433 		public TerminatedByHelpException() {
434 			super(true);
435 		}
436 
437 	}
438 }