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.1KB

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