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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. @Override
  144. void init(final TextBuiltin cmd) throws IOException {
  145. cmd.outs = result.out;
  146. cmd.errs = result.err;
  147. super.init(cmd);
  148. }
  149. @Override
  150. protected Repository openGitDir(String aGitdir) throws IOException {
  151. assertNull(aGitdir);
  152. return db;
  153. }
  154. @Override
  155. void exit(int status, Exception t) throws Exception {
  156. if (t == null) {
  157. t = new IllegalStateException(Integer.toString(status));
  158. }
  159. result.ex = t;
  160. throw t;
  161. }
  162. /**
  163. * Split a command line into a string array.
  164. *
  165. * A copy of Gerrit's
  166. * com.google.gerrit.sshd.CommandFactoryProvider#split(String)
  167. *
  168. * @param commandLine
  169. * a command line
  170. * @return the array
  171. */
  172. static String[] split(String commandLine) {
  173. final List<String> list = new ArrayList<>();
  174. boolean inquote = false;
  175. boolean inDblQuote = false;
  176. StringBuilder r = new StringBuilder();
  177. for (int ip = 0; ip < commandLine.length();) {
  178. final char b = commandLine.charAt(ip++);
  179. switch (b) {
  180. case '\t':
  181. case ' ':
  182. if (inquote || inDblQuote)
  183. r.append(b);
  184. else if (r.length() > 0) {
  185. list.add(r.toString());
  186. r = new StringBuilder();
  187. }
  188. continue;
  189. case '\"':
  190. if (inquote)
  191. r.append(b);
  192. else
  193. inDblQuote = !inDblQuote;
  194. continue;
  195. case '\'':
  196. if (inDblQuote)
  197. r.append(b);
  198. else
  199. inquote = !inquote;
  200. continue;
  201. case '\\':
  202. if (inDblQuote || inquote || ip == commandLine.length())
  203. r.append(b); // literal within a quote
  204. else
  205. r.append(commandLine.charAt(ip++));
  206. continue;
  207. default:
  208. r.append(b);
  209. continue;
  210. }
  211. }
  212. if (r.length() > 0)
  213. list.add(r.toString());
  214. return list.toArray(new String[list.size()]);
  215. }
  216. public static class Result {
  217. public final ByteArrayOutputStream out = new ByteArrayOutputStream();
  218. public final ByteArrayOutputStream err = new ByteArrayOutputStream();
  219. public Exception ex;
  220. public byte[] outBytes() {
  221. return out.toByteArray();
  222. }
  223. public byte[] errBytes() {
  224. return err.toByteArray();
  225. }
  226. public String outString() {
  227. return out.toString();
  228. }
  229. public List<String> outLines() {
  230. return IO.readLines(out.toString());
  231. }
  232. public String errString() {
  233. return err.toString();
  234. }
  235. public List<String> errLines() {
  236. return IO.readLines(err.toString());
  237. }
  238. }
  239. }