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  import java.io.IOException;
50  import java.io.PrintWriter;
51  import java.util.ArrayList;
52  import java.util.List;
53  
54  import org.eclipse.jgit.internal.storage.file.FileRepository;
55  import org.eclipse.jgit.lib.Repository;
56  import org.eclipse.jgit.pgm.TextBuiltin.TerminatedByHelpException;
57  import org.eclipse.jgit.util.IO;
58  
59  public class CLIGitCommand extends Main {
60  
61  	private final Result result;
62  
63  	private final Repository db;
64  
65  	public CLIGitCommand(Repository db) {
66  		super();
67  		this.db = db;
68  		result = new Result();
69  	}
70  
71  	/**
72  	 * Executes git commands (with arguments) specified on the command line. The
73  	 * git repository (same for all commands) can be specified via system
74  	 * property "-Dgit_work_tree=path_to_work_tree". If the property is not set,
75  	 * current directory is used.
76  	 *
77  	 * @param args
78  	 *            each element in the array must be a valid git command line,
79  	 *            e.g. "git branch -h"
80  	 * @throws Exception
81  	 */
82  	public static void main(String[] args) throws Exception {
83  		String workDir = System.getProperty("git_work_tree");
84  		if (workDir == null) {
85  			workDir = ".";
86  			System.out.println(
87  					"System property 'git_work_tree' not specified, using current directory: "
88  							+ new File(workDir).getAbsolutePath());
89  		}
90  		try (Repository db = new FileRepository(workDir + "/.git")) {
91  			for (String cmd : args) {
92  				List<String> result = execute(cmd, db);
93  				for (String line : result) {
94  					System.out.println(line);
95  				}
96  			}
97  		}
98  	}
99  
100 	public static List<String> execute(String str, Repository db)
101 			throws Exception {
102 		Result result = executeRaw(str, db);
103 		return getOutput(result);
104 	}
105 
106 	public static Result executeRaw(String str, Repository db)
107 			throws Exception {
108 		CLIGitCommand cmd = new CLIGitCommand(db);
109 		cmd.run(str);
110 		return cmd.result;
111 	}
112 
113 	public static List<String> executeUnchecked(String str, Repository db)
114 			throws Exception {
115 		CLIGitCommand cmd = new CLIGitCommand(db);
116 		try {
117 			cmd.run(str);
118 			return getOutput(cmd.result);
119 		} catch (Throwable e) {
120 			return cmd.result.errLines();
121 		}
122 	}
123 
124 	private static List<String> getOutput(Result result) {
125 		if (result.ex instanceof TerminatedByHelpException) {
126 			return result.errLines();
127 		}
128 		return result.outLines();
129 	}
130 
131 	private void run(String commandLine) throws Exception {
132 		String[] argv = convertToMainArgs(commandLine);
133 		try {
134 			super.run(argv);
135 		} catch (TerminatedByHelpException e) {
136 			// this is not a failure, super called exit() on help
137 		} finally {
138 			writer.flush();
139 		}
140 	}
141 
142 	private static String[] convertToMainArgs(String str)
143 			throws Exception {
144 		String[] args = split(str);
145 		if (!args[0].equalsIgnoreCase("git") || args.length < 2) {
146 			throw new IllegalArgumentException(
147 					"Expected 'git <command> [<args>]', was:" + str);
148 		}
149 		String[] argv = new String[args.length - 1];
150 		System.arraycopy(args, 1, argv, 0, args.length - 1);
151 		return argv;
152 	}
153 
154 	@Override
155 	PrintWriter createErrorWriter() {
156 		return new PrintWriter(result.err);
157 	}
158 
159 	@Override
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<>();
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 (inDblQuote || 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 }