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 java.io.ByteArrayOutputStream;
46  import java.text.MessageFormat;
47  import java.util.ArrayList;
48  import java.util.List;
49  
50  import org.eclipse.jgit.lib.Repository;
51  import org.eclipse.jgit.pgm.internal.CLIText;
52  import org.eclipse.jgit.pgm.opt.CmdLineParser;
53  import org.eclipse.jgit.pgm.opt.SubcommandHandler;
54  import org.eclipse.jgit.util.IO;
55  import org.kohsuke.args4j.Argument;
56  
57  public class CLIGitCommand {
58  	@Argument(index = 0, metaVar = "metaVar_command", required = true, handler = SubcommandHandler.class)
59  	private TextBuiltin subcommand;
60  
61  	@Argument(index = 1, metaVar = "metaVar_arg")
62  	private List<String> arguments = new ArrayList<String>();
63  
64  	public TextBuiltin getSubcommand() {
65  		return subcommand;
66  	}
67  
68  	public List<String> getArguments() {
69  		return arguments;
70  	}
71  
72  	public static List<String> execute(String str, Repository db)
73  			throws Exception {
74  		try {
75  			return IO.readLines(new String(rawExecute(str, db)));
76  		} catch (Die e) {
77  			return IO.readLines(MessageFormat.format(CLIText.get().fatalError,
78  					e.getMessage()));
79  		}
80  	}
81  
82  	public static byte[] rawExecute(String str, Repository db)
83  			throws Exception {
84  		String[] args = split(str);
85  		if (!args[0].equalsIgnoreCase("git") || args.length < 2)
86  			throw new IllegalArgumentException(
87  					"Expected 'git <command> [<args>]', was:" + str);
88  		String[] argv = new String[args.length - 1];
89  		System.arraycopy(args, 1, argv, 0, args.length - 1);
90  
91  		CLIGitCommand bean = new CLIGitCommand();
92  		final CmdLineParser clp = new CmdLineParser(bean);
93  		clp.parseArgument(argv);
94  
95  		final TextBuiltin cmd = bean.getSubcommand();
96  		ByteArrayOutputStream baos = new ByteArrayOutputStream();
97  		cmd.outs = baos;
98  		if (cmd.requiresRepository())
99  			cmd.init(db, null);
100 		else
101 			cmd.init(null, null);
102 		try {
103 			cmd.execute(bean.getArguments().toArray(
104 					new String[bean.getArguments().size()]));
105 		} finally {
106 			if (cmd.outw != null)
107 				cmd.outw.flush();
108 		}
109 		return baos.toByteArray();
110 	}
111 
112 	/**
113 	 * Split a command line into a string array.
114 	 *
115 	 * A copy of Gerrit's
116 	 * com.google.gerrit.sshd.CommandFactoryProvider#split(String)
117 	 *
118 	 * @param commandLine
119 	 *            a command line
120 	 * @return the array
121 	 */
122 	static String[] split(String commandLine) {
123 		final List<String> list = new ArrayList<String>();
124 		boolean inquote = false;
125 		boolean inDblQuote = false;
126 		StringBuilder r = new StringBuilder();
127 		for (int ip = 0; ip < commandLine.length();) {
128 			final char b = commandLine.charAt(ip++);
129 			switch (b) {
130 			case '\t':
131 			case ' ':
132 				if (inquote || inDblQuote)
133 					r.append(b);
134 				else if (r.length() > 0) {
135 					list.add(r.toString());
136 					r = new StringBuilder();
137 				}
138 				continue;
139 			case '\"':
140 				if (inquote)
141 					r.append(b);
142 				else
143 					inDblQuote = !inDblQuote;
144 				continue;
145 			case '\'':
146 				if (inDblQuote)
147 					r.append(b);
148 				else
149 					inquote = !inquote;
150 				continue;
151 			case '\\':
152 				if (inquote || ip == commandLine.length())
153 					r.append(b); // literal within a quote
154 				else
155 					r.append(commandLine.charAt(ip++));
156 				continue;
157 			default:
158 				r.append(b);
159 				continue;
160 			}
161 		}
162 		if (r.length() > 0)
163 			list.add(r.toString());
164 		return list.toArray(new String[list.size()]);
165 	}
166 
167 }