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 7.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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 static org.junit.Assert.assertNull;
  45. import java.io.ByteArrayOutputStream;
  46. import java.io.File;
  47. import java.io.IOException;
  48. import java.io.PrintWriter;
  49. import java.util.ArrayList;
  50. import java.util.List;
  51. import org.eclipse.jgit.internal.storage.file.FileRepository;
  52. import org.eclipse.jgit.lib.Repository;
  53. import org.eclipse.jgit.pgm.TextBuiltin.TerminatedByHelpException;
  54. import org.eclipse.jgit.util.IO;
  55. public class CLIGitCommand extends Main {
  56. private final Result result;
  57. private final Repository db;
  58. public CLIGitCommand(Repository db) {
  59. super();
  60. this.db = db;
  61. result = new Result();
  62. }
  63. /**
  64. * Executes git commands (with arguments) specified on the command line. The
  65. * git repository (same for all commands) can be specified via system
  66. * property "-Dgit_work_tree=path_to_work_tree". If the property is not set,
  67. * current directory is used.
  68. *
  69. * @param args
  70. * each element in the array must be a valid git command line,
  71. * e.g. "git branch -h"
  72. * @throws Exception
  73. */
  74. public static void main(String[] args) throws Exception {
  75. String workDir = System.getProperty("git_work_tree");
  76. if (workDir == null) {
  77. workDir = ".";
  78. System.out.println(
  79. "System property 'git_work_tree' not specified, using current directory: "
  80. + new File(workDir).getAbsolutePath());
  81. }
  82. try (Repository db = new FileRepository(workDir + "/.git")) {
  83. for (String cmd : args) {
  84. List<String> result = execute(cmd, db);
  85. for (String line : result) {
  86. System.out.println(line);
  87. }
  88. }
  89. }
  90. }
  91. public static List<String> execute(String str, Repository db)
  92. throws Exception {
  93. Result result = executeRaw(str, db);
  94. return getOutput(result);
  95. }
  96. public static Result executeRaw(String str, Repository db)
  97. throws Exception {
  98. CLIGitCommand cmd = new CLIGitCommand(db);
  99. cmd.run(str);
  100. return cmd.result;
  101. }
  102. public static List<String> executeUnchecked(String str, Repository db)
  103. throws Exception {
  104. CLIGitCommand cmd = new CLIGitCommand(db);
  105. try {
  106. cmd.run(str);
  107. return getOutput(cmd.result);
  108. } catch (Throwable e) {
  109. return cmd.result.errLines();
  110. }
  111. }
  112. private static List<String> getOutput(Result result) {
  113. if (result.ex instanceof TerminatedByHelpException) {
  114. return result.errLines();
  115. }
  116. return result.outLines();
  117. }
  118. private void run(String commandLine) throws Exception {
  119. String[] argv = convertToMainArgs(commandLine);
  120. try {
  121. super.run(argv);
  122. } catch (TerminatedByHelpException e) {
  123. // this is not a failure, super called exit() on help
  124. } finally {
  125. writer.flush();
  126. }
  127. }
  128. private static String[] convertToMainArgs(String str)
  129. throws Exception {
  130. String[] args = split(str);
  131. if (!args[0].equalsIgnoreCase("git") || args.length < 2) {
  132. throw new IllegalArgumentException(
  133. "Expected 'git <command> [<args>]', was:" + str);
  134. }
  135. String[] argv = new String[args.length - 1];
  136. System.arraycopy(args, 1, argv, 0, args.length - 1);
  137. return argv;
  138. }
  139. @Override
  140. PrintWriter createErrorWriter() {
  141. return new PrintWriter(result.err);
  142. }
  143. void init(final TextBuiltin cmd) throws IOException {
  144. cmd.outs = result.out;
  145. cmd.errs = result.err;
  146. super.init(cmd);
  147. }
  148. @Override
  149. protected Repository openGitDir(String aGitdir) throws IOException {
  150. assertNull(aGitdir);
  151. return db;
  152. }
  153. @Override
  154. void exit(int status, Exception t) throws Exception {
  155. if (t == null) {
  156. t = new IllegalStateException(Integer.toString(status));
  157. }
  158. result.ex = t;
  159. throw t;
  160. }
  161. /**
  162. * Split a command line into a string array.
  163. *
  164. * A copy of Gerrit's
  165. * com.google.gerrit.sshd.CommandFactoryProvider#split(String)
  166. *
  167. * @param commandLine
  168. * a command line
  169. * @return the array
  170. */
  171. static String[] split(String commandLine) {
  172. final List<String> list = new ArrayList<String>();
  173. boolean inquote = false;
  174. boolean inDblQuote = false;
  175. StringBuilder r = new StringBuilder();
  176. for (int ip = 0; ip < commandLine.length();) {
  177. final char b = commandLine.charAt(ip++);
  178. switch (b) {
  179. case '\t':
  180. case ' ':
  181. if (inquote || inDblQuote)
  182. r.append(b);
  183. else if (r.length() > 0) {
  184. list.add(r.toString());
  185. r = new StringBuilder();
  186. }
  187. continue;
  188. case '\"':
  189. if (inquote)
  190. r.append(b);
  191. else
  192. inDblQuote = !inDblQuote;
  193. continue;
  194. case '\'':
  195. if (inDblQuote)
  196. r.append(b);
  197. else
  198. inquote = !inquote;
  199. continue;
  200. case '\\':
  201. if (inDblQuote || inquote || ip == commandLine.length())
  202. r.append(b); // literal within a quote
  203. else
  204. r.append(commandLine.charAt(ip++));
  205. continue;
  206. default:
  207. r.append(b);
  208. continue;
  209. }
  210. }
  211. if (r.length() > 0)
  212. list.add(r.toString());
  213. return list.toArray(new String[list.size()]);
  214. }
  215. public static class Result {
  216. public final ByteArrayOutputStream out = new ByteArrayOutputStream();
  217. public final ByteArrayOutputStream err = new ByteArrayOutputStream();
  218. public Exception ex;
  219. public byte[] outBytes() {
  220. return out.toByteArray();
  221. }
  222. public byte[] errBytes() {
  223. return err.toByteArray();
  224. }
  225. public String outString() {
  226. return out.toString();
  227. }
  228. public List<String> outLines() {
  229. return IO.readLines(out.toString());
  230. }
  231. public String errString() {
  232. return err.toString();
  233. }
  234. public List<String> errLines() {
  235. return IO.readLines(err.toString());
  236. }
  237. }
  238. }