You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CLIGitCommand.java 6.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. import java.io.ByteArrayOutputStream;
  45. import java.io.File;
  46. import java.text.MessageFormat;
  47. import java.util.ArrayList;
  48. import java.util.List;
  49. import org.eclipse.jgit.internal.storage.file.FileRepository;
  50. import org.eclipse.jgit.lib.Repository;
  51. import org.eclipse.jgit.pgm.TextBuiltin.TerminatedByHelpException;
  52. import org.eclipse.jgit.pgm.internal.CLIText;
  53. import org.eclipse.jgit.pgm.opt.CmdLineParser;
  54. import org.eclipse.jgit.pgm.opt.SubcommandHandler;
  55. import org.eclipse.jgit.util.IO;
  56. import org.kohsuke.args4j.Argument;
  57. public class CLIGitCommand {
  58. @Argument(index = 0, metaVar = "metaVar_command", required = true, handler = SubcommandHandler.class)
  59. private TextBuiltin subcommand;
  60. @Argument(index = 1, metaVar = "metaVar_arg")
  61. private List<String> arguments = new ArrayList<String>();
  62. public TextBuiltin getSubcommand() {
  63. return subcommand;
  64. }
  65. public List<String> getArguments() {
  66. return arguments;
  67. }
  68. /**
  69. * Executes git commands (with arguments) specified on the command line. The
  70. * git repository (same for all commands) can be specified via system
  71. * property "-Dgit_work_tree=path_to_work_tree". If the property is not set,
  72. * current directory is used.
  73. *
  74. * @param args
  75. * each element in the array must be a valid git command line,
  76. * e.g. "git branch -h"
  77. * @throws Exception
  78. */
  79. public static void main(String[] args) throws Exception {
  80. String workDir = System.getProperty("git_work_tree");
  81. if (workDir == null) {
  82. workDir = ".";
  83. System.out.println(
  84. "System property 'git_work_tree' not specified, using current directory: "
  85. + new File(workDir).getAbsolutePath());
  86. }
  87. try (Repository db = new FileRepository(workDir + "/.git")) {
  88. for (String cmd : args) {
  89. List<String> result = execute(cmd, db);
  90. for (String line : result) {
  91. System.out.println(line);
  92. }
  93. }
  94. }
  95. }
  96. public static List<String> execute(String str, Repository db)
  97. throws Exception {
  98. try {
  99. return IO.readLines(new String(rawExecute(str, db)));
  100. } catch (Die e) {
  101. return IO.readLines(MessageFormat.format(CLIText.get().fatalError,
  102. e.getMessage()));
  103. }
  104. }
  105. public static byte[] rawExecute(String str, Repository db)
  106. throws Exception {
  107. String[] args = split(str);
  108. if (!args[0].equalsIgnoreCase("git") || args.length < 2)
  109. throw new IllegalArgumentException(
  110. "Expected 'git <command> [<args>]', was:" + str);
  111. String[] argv = new String[args.length - 1];
  112. System.arraycopy(args, 1, argv, 0, args.length - 1);
  113. CLIGitCommand bean = new CLIGitCommand();
  114. final CmdLineParser clp = new TestCmdLineParser(bean);
  115. clp.parseArgument(argv);
  116. final TextBuiltin cmd = bean.getSubcommand();
  117. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  118. cmd.outs = baos;
  119. ByteArrayOutputStream errs = new ByteArrayOutputStream();
  120. cmd.errs = errs;
  121. boolean seenHelp = TextBuiltin.containsHelp(argv);
  122. if (cmd.requiresRepository())
  123. cmd.init(db, null);
  124. else
  125. cmd.init(null, null);
  126. try {
  127. cmd.execute(bean.getArguments().toArray(
  128. new String[bean.getArguments().size()]));
  129. } catch (TerminatedByHelpException e) {
  130. seenHelp = true;
  131. // this is not a failure, command execution should just not happen
  132. } finally {
  133. if (cmd.outw != null) {
  134. cmd.outw.flush();
  135. }
  136. if (cmd.errw != null) {
  137. cmd.errw.flush();
  138. }
  139. if (seenHelp) {
  140. return errs.toByteArray();
  141. } else if (errs.size() > 0) {
  142. // forward the errors to the standard err
  143. System.err.print(errs.toString());
  144. }
  145. }
  146. return baos.toByteArray();
  147. }
  148. /**
  149. * Split a command line into a string array.
  150. *
  151. * A copy of Gerrit's
  152. * com.google.gerrit.sshd.CommandFactoryProvider#split(String)
  153. *
  154. * @param commandLine
  155. * a command line
  156. * @return the array
  157. */
  158. static String[] split(String commandLine) {
  159. final List<String> list = new ArrayList<String>();
  160. boolean inquote = false;
  161. boolean inDblQuote = false;
  162. StringBuilder r = new StringBuilder();
  163. for (int ip = 0; ip < commandLine.length();) {
  164. final char b = commandLine.charAt(ip++);
  165. switch (b) {
  166. case '\t':
  167. case ' ':
  168. if (inquote || inDblQuote)
  169. r.append(b);
  170. else if (r.length() > 0) {
  171. list.add(r.toString());
  172. r = new StringBuilder();
  173. }
  174. continue;
  175. case '\"':
  176. if (inquote)
  177. r.append(b);
  178. else
  179. inDblQuote = !inDblQuote;
  180. continue;
  181. case '\'':
  182. if (inDblQuote)
  183. r.append(b);
  184. else
  185. inquote = !inquote;
  186. continue;
  187. case '\\':
  188. if (inquote || ip == commandLine.length())
  189. r.append(b); // literal within a quote
  190. else
  191. r.append(commandLine.charAt(ip++));
  192. continue;
  193. default:
  194. r.append(b);
  195. continue;
  196. }
  197. }
  198. if (r.length() > 0)
  199. list.add(r.toString());
  200. return list.toArray(new String[list.size()]);
  201. }
  202. static class TestCmdLineParser extends CmdLineParser {
  203. public TestCmdLineParser(Object bean) {
  204. super(bean);
  205. }
  206. @Override
  207. protected boolean containsHelp(String... args) {
  208. return false;
  209. }
  210. }
  211. }