View Javadoc
1   /*
2    * Copyright (C) 2011-2012, IBM Corporation and others.
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42   */
43  package org.eclipse.jgit.pgm;
44  
45  import static org.junit.Assert.assertNull;
46  
47  import java.io.ByteArrayOutputStream;
48  import java.io.File;
49  
50  import java.io.IOException;
51  import java.io.PrintWriter;
52  import java.util.ArrayList;
53  import java.util.List;
54  
55  import org.eclipse.jgit.internal.storage.file.FileRepository;
56  import org.eclipse.jgit.lib.Repository;
57  import org.eclipse.jgit.pgm.TextBuiltin.TerminatedByHelpException;
58  import org.eclipse.jgit.util.IO;
59  
60  public class CLIGitCommand extends Main {
61  
62  	private final Result result;
63  
64  	private final Repository db;
65  
66  	public CLIGitCommand(Repository db) {
67  		super();
68  		this.db = db;
69  		result = new Result();
70  	}
71  
72  	/**
73  	 * Executes git commands (with arguments) specified on the command line. The
74  	 * git repository (same for all commands) can be specified via system
75  	 * property "-Dgit_work_tree=path_to_work_tree". If the property is not set,
76  	 * current directory is used.
77  	 *
78  	 * @param args
79  	 *            each element in the array must be a valid git command line,
80  	 *            e.g. "git branch -h"
81  	 * @throws Exception
82  	 */
83  	public static void main(String[] args) throws Exception {
84  		String workDir = System.getProperty("git_work_tree");
85  		if (workDir == null) {
86  			workDir = ".";
87  			System.out.println(
88  					"System property 'git_work_tree' not specified, using current directory: "
89  							+ new File(workDir).getAbsolutePath());
90  		}
91  		try (Repository db = new FileRepository(workDir + "/.git")) {
92  			for (String cmd : args) {
93  				List<String> result = execute(cmd, db);
94  				for (String line : result) {
95  					System.out.println(line);
96  				}
97  			}
98  		}
99  	}
100 
101 	public static List<String> execute(String str, Repository db)
102 			throws Exception {
103 		Result result = executeRaw(str, db);
104 		return getOutput(result);
105 	}
106 
107 	public static Result executeRaw(String str, Repository db)
108 			throws Exception {
109 		CLIGitCommand cmd = new CLIGitCommand(db);
110 		cmd.run(str);
111 		return cmd.result;
112 	}
113 
114 	public static List<String> executeUnchecked(String str, Repository db)
115 			throws Exception {
116 		CLIGitCommand cmd = new CLIGitCommand(db);
117 		try {
118 			cmd.run(str);
119 			return getOutput(cmd.result);
120 		} catch (Throwable e) {
121 			return cmd.result.errLines();
122 		}
123 	}
124 
125 	private static List<String> getOutput(Result result) {
126 		if (result.ex instanceof TerminatedByHelpException) {
127 			return result.errLines();
128 		}
129 		return result.outLines();
130 	}
131 
132 	private void run(String commandLine) throws Exception {
133 		String[] argv = convertToMainArgs(commandLine);
134 		try {
135 			super.run(argv);
136 		} catch (TerminatedByHelpException e) {
137 			// this is not a failure, super called exit() on help
138 		} finally {
139 			writer.flush();
140 		}
141 	}
142 
143 	private static String[] convertToMainArgs(String str)
144 			throws Exception {
145 		String[] args = split(str);
146 		if (!args[0].equalsIgnoreCase("git") || args.length < 2) {
147 			throw new IllegalArgumentException(
148 					"Expected 'git <command> [<args>]', was:" + str);
149 		}
150 		String[] argv = new String[args.length - 1];
151 		System.arraycopy(args, 1, argv, 0, args.length - 1);
152 		return argv;
153 	}
154 
155 	@Override
156 	PrintWriter createErrorWriter() {
157 		return new PrintWriter(result.err);
158 	}
159 
160 	void init(final TextBuiltin cmd) throws IOException {
161 		cmd.outs = result.out;
162 		cmd.errs = result.err;
163 		super.init(cmd);
164 	}
165 
166 	@Override
167 	protected Repository openGitDir(String aGitdir) throws IOException {
168 		assertNull(aGitdir);
169 		return db;
170 	}
171 
172 	@Override
173 	void exit(int status, Exception t) throws Exception {
174 		if (t == null) {
175 			t = new IllegalStateException(Integer.toString(status));
176 		}
177 		result.ex = t;
178 		throw t;
179 	}
180 
181 	/**
182 	 * Split a command line into a string array.
183 	 *
184 	 * A copy of Gerrit's
185 	 * com.google.gerrit.sshd.CommandFactoryProvider#split(String)
186 	 *
187 	 * @param commandLine
188 	 *            a command line
189 	 * @return the array
190 	 */
191 	static String[] split(String commandLine) {
192 		final List<String> list = new ArrayList<String>();
193 		boolean inquote = false;
194 		boolean inDblQuote = false;
195 		StringBuilder r = new StringBuilder();
196 		for (int ip = 0; ip < commandLine.length();) {
197 			final char b = commandLine.charAt(ip++);
198 			switch (b) {
199 			case '\t':
200 			case ' ':
201 				if (inquote || inDblQuote)
202 					r.append(b);
203 				else if (r.length() > 0) {
204 					list.add(r.toString());
205 					r = new StringBuilder();
206 				}
207 				continue;
208 			case '\"':
209 				if (inquote)
210 					r.append(b);
211 				else
212 					inDblQuote = !inDblQuote;
213 				continue;
214 			case '\'':
215 				if (inDblQuote)
216 					r.append(b);
217 				else
218 					inquote = !inquote;
219 				continue;
220 			case '\\':
221 				if (inquote || ip == commandLine.length())
222 					r.append(b); // literal within a quote
223 				else
224 					r.append(commandLine.charAt(ip++));
225 				continue;
226 			default:
227 				r.append(b);
228 				continue;
229 			}
230 		}
231 		if (r.length() > 0)
232 			list.add(r.toString());
233 		return list.toArray(new String[list.size()]);
234 	}
235 
236 	public static class Result {
237 		public final ByteArrayOutputStream out = new ByteArrayOutputStream();
238 
239 		public final ByteArrayOutputStream err = new ByteArrayOutputStream();
240 
241 		public Exception ex;
242 
243 		public byte[] outBytes() {
244 			return out.toByteArray();
245 		}
246 
247 		public byte[] errBytes() {
248 			return err.toByteArray();
249 		}
250 
251 		public String outString() {
252 			return out.toString();
253 		}
254 
255 		public List<String> outLines() {
256 			return IO.readLines(out.toString());
257 		}
258 
259 		public String errString() {
260 			return err.toString();
261 		}
262 
263 		public List<String> errLines() {
264 			return IO.readLines(err.toString());
265 		}
266 	}
267 
268 }