Support automatic command line parsing for TextBuiltin subclasses
[egit/florian.git] / org.spearce.jgit.pgm / src / org / spearce / jgit / pgm / TextBuiltin.java
blob4c466ac2f6a3e84df8579bb77ccd37e7287eda31
1 /*
2 * Copyright (C) 2007, Robin Rosenberg <robin.rosenberg@dewire.com>
3 * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
5 * All rights reserved.
7 * Redistribution and use in source and binary forms, with or
8 * without modification, are permitted provided that the following
9 * conditions are met:
11 * - Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * - Redistributions in binary form must reproduce the above
15 * copyright notice, this list of conditions and the following
16 * disclaimer in the documentation and/or other materials provided
17 * with the distribution.
19 * - Neither the name of the Git Development Community nor the
20 * names of its contributors may be used to endorse or promote
21 * products derived from this software without specific prior
22 * written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
25 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
26 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
29 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
32 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
34 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 package org.spearce.jgit.pgm;
41 import java.io.BufferedWriter;
42 import java.io.IOException;
43 import java.io.OutputStreamWriter;
44 import java.io.PrintWriter;
46 import org.kohsuke.args4j.CmdLineException;
47 import org.kohsuke.args4j.Option;
48 import org.spearce.jgit.lib.Constants;
49 import org.spearce.jgit.lib.ObjectId;
50 import org.spearce.jgit.lib.Repository;
51 import org.spearce.jgit.pgm.opt.CmdLineParser;
52 import org.spearce.jgit.revwalk.RevWalk;
54 /**
55 * Abstract command which can be invoked from the command line.
56 * <p>
57 * Commands are configured with a single "current" repository and then the
58 * {@link #execute(String[])} method is invoked with the arguments that appear
59 * on the command line after the command name.
60 * <p>
61 * Command constructors should perform as little work as possible as they may be
62 * invoked very early during process loading, and the command may not execute
63 * even though it was constructed.
65 public abstract class TextBuiltin {
66 protected static final String REFS_HEADS = Constants.HEADS_PREFIX + "/";
68 protected static final String REFS_REMOTES = Constants.REMOTES_PREFIX + "/";
70 protected static final String REFS_TAGS = Constants.TAGS_PREFIX + "/";
72 private String commandName;
74 @Option(name = "--help", usage = "display this help text", aliases = { "-h" })
75 private boolean help;
77 /** Stream to output to, typically this is standard output. */
78 protected PrintWriter out;
80 /** Git repository the command was invoked within. */
81 protected Repository db;
83 /** RevWalk used during command line parsing, if it was required. */
84 protected RevWalk argWalk;
86 /**
87 * Set the name this command can be invoked as on the command line.
89 * @param name
90 * the name of the command.
92 public void setCommandName(final String name) {
93 commandName = name;
96 void init(final Repository repo) {
97 try {
98 out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
99 System.out, "UTF-8")));
100 } catch (IOException e) {
101 throw die("cannot create output stream");
103 db = repo;
107 * Parse arguments and run this command.
109 * @param args
110 * command line arguments passed after the command name.
111 * @throws Exception
112 * an error occurred while processing the command. The main
113 * framework will catch the exception and print a message on
114 * standard error.
116 public void execute(String[] args) throws Exception {
117 parseArguments(args);
118 run();
122 * Parses the command line arguments prior to running.
123 * <p>
124 * This method should only be invoked by {@link #execute(String[])}, prior
125 * to calling {@link #run()}. The default implementation parses all
126 * arguments into this object's instance fields.
128 * @param args
129 * the arguments supplied on the command line, if any.
131 protected void parseArguments(final String[] args) {
132 final CmdLineParser clp = new CmdLineParser(this);
133 try {
134 clp.parseArgument(args);
135 } catch (CmdLineException err) {
136 if (!help) {
137 System.err.println("fatal: " + err.getMessage());
138 System.exit(1);
142 if (help) {
143 System.err.print("jgit ");
144 System.err.print(commandName);
145 clp.printSingleLineUsage(System.err);
146 System.err.println();
148 System.err.println();
150 clp.printUsage(System.err);
151 System.err.println();
153 System.exit(1);
156 argWalk = clp.getRevWalkGently();
160 * Perform the actions of this command.
161 * <p>
162 * This method should only be invoked by {@link #execute(String[])}.
164 * @throws Exception
165 * an error occurred while processing the command. The main
166 * framework will catch the exception and print a message on
167 * standard error.
169 protected void run() throws Exception {
170 throw die("Override either execute (legacy) or run (new style).");
174 * @return the repository this command accesses.
176 public Repository getRepository() {
177 return db;
180 protected ObjectId resolve(final String s) throws IOException {
181 final ObjectId r = db.resolve(s);
182 if (r == null)
183 throw die("Not a revision: " + s);
184 return r;
187 protected static Die die(final String why) {
188 return new Die(why);
191 protected static String abbreviateObject(final ObjectId id) {
192 return id.toString().substring(0, 7);
195 protected String abbreviateRef(String dst, boolean abbreviateRemote) {
196 if (dst.startsWith(REFS_HEADS))
197 dst = dst.substring(REFS_HEADS.length());
198 else if (dst.startsWith(REFS_TAGS))
199 dst = dst.substring(REFS_TAGS.length());
200 else if (abbreviateRemote && dst.startsWith(REFS_REMOTES))
201 dst = dst.substring(REFS_REMOTES.length());
202 return dst;