選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

ScriptCommand.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. /*
  2. * Copyright (c) 2006-2015 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. package com.dmdirc.addons.scriptplugin;
  23. import com.dmdirc.ClientModule.GlobalConfig;
  24. import com.dmdirc.commandline.CommandLineOptionsModule.Directory;
  25. import com.dmdirc.commandparser.BaseCommandInfo;
  26. import com.dmdirc.commandparser.CommandArguments;
  27. import com.dmdirc.commandparser.CommandInfo;
  28. import com.dmdirc.commandparser.CommandType;
  29. import com.dmdirc.commandparser.commands.Command;
  30. import com.dmdirc.commandparser.commands.IntelligentCommand;
  31. import com.dmdirc.commandparser.commands.context.CommandContext;
  32. import com.dmdirc.interfaces.CommandController;
  33. import com.dmdirc.interfaces.WindowModel;
  34. import com.dmdirc.interfaces.config.AggregateConfigProvider;
  35. import com.dmdirc.plugins.PluginDomain;
  36. import com.dmdirc.ui.input.AdditionalTabTargets;
  37. import java.io.File;
  38. import java.io.FileWriter;
  39. import java.io.IOException;
  40. import java.util.Map;
  41. import java.util.stream.Collectors;
  42. import javax.annotation.Nonnull;
  43. import javax.inject.Inject;
  44. import javax.script.ScriptEngineManager;
  45. import javax.script.ScriptException;
  46. /**
  47. * The Script Command allows controlling of the script plugin.
  48. */
  49. public class ScriptCommand extends Command implements IntelligentCommand {
  50. /** A command info object for this command. */
  51. public static final CommandInfo INFO = new BaseCommandInfo("script",
  52. "script - Allows controlling the script plugin", CommandType.TYPE_GLOBAL);
  53. /** Global config to read settings from. */
  54. private final AggregateConfigProvider globalConfig;
  55. /** Plugin settings domain. */
  56. private final String domain;
  57. /** Manager used to retrieve script engines. */
  58. private final ScriptEngineManager scriptEngineManager;
  59. /** Script directory. */
  60. private final String scriptDirectory;
  61. /** Script manager to handle scripts. */
  62. private final ScriptManager scriptManager;
  63. /**
  64. * Creates a new instance of this command.
  65. *
  66. * @param scriptManager Used to manage scripts
  67. * @param globalConfig Global config
  68. * @param commandController The controller to use for command information.
  69. * @param domain This plugin's settings domain
  70. * @param scriptEngineManager Manager used to get script engines
  71. * @param scriptDirectory Directory to store scripts
  72. */
  73. @Inject
  74. public ScriptCommand(final ScriptManager scriptManager,
  75. @Directory(ScriptModule.SCRIPTS) final String scriptDirectory,
  76. @GlobalConfig final AggregateConfigProvider globalConfig,
  77. final CommandController commandController,
  78. @PluginDomain(ScriptPlugin.class) final String domain,
  79. final ScriptEngineManager scriptEngineManager) {
  80. super(commandController);
  81. this.globalConfig = globalConfig;
  82. this.domain = domain;
  83. this.scriptEngineManager = scriptEngineManager;
  84. this.scriptDirectory = scriptDirectory;
  85. this.scriptManager = scriptManager;
  86. }
  87. @Override
  88. public void execute(@Nonnull final WindowModel origin, final CommandArguments args,
  89. final CommandContext context) {
  90. final String[] sargs = args.getArguments();
  91. if (sargs.length > 0 && ("rehash".equalsIgnoreCase(sargs[0]) ||
  92. "reload".equalsIgnoreCase(sargs[0]))) {
  93. showOutput(origin, args.isSilent(), "Reloading scripts");
  94. scriptManager.rehash();
  95. } else if (sargs.length > 0 && "load".equalsIgnoreCase(sargs[0])) {
  96. if (sargs.length > 1) {
  97. final String filename = args.getArgumentsAsString(1);
  98. showOutput(origin, args.isSilent(), "Loading: " + filename + " ["
  99. + scriptManager.loadScript(scriptDirectory + filename) + ']');
  100. } else {
  101. showError(origin, args.isSilent(), "You must specify a script to load");
  102. }
  103. } else if (sargs.length > 0 && "unload".equalsIgnoreCase(sargs[0])) {
  104. if (sargs.length > 1) {
  105. final String filename = args.getArgumentsAsString(1);
  106. showOutput(origin, args.isSilent(), "Unloading: " + filename + " ["
  107. + scriptManager.loadScript(scriptDirectory + filename) + ']');
  108. } else {
  109. showError(origin, args.isSilent(), "You must specify a script to unload");
  110. }
  111. } else if (sargs.length > 0 && "eval".equalsIgnoreCase(sargs[0])) {
  112. if (sargs.length > 1) {
  113. final String script = args.getArgumentsAsString(1);
  114. showOutput(origin, args.isSilent(), "Evaluating: " + script);
  115. try {
  116. final ScriptEngineWrapper wrapper;
  117. if (globalConfig.hasOptionString(domain, "eval.baseFile")) {
  118. final String baseFile = scriptDirectory + '/'
  119. + globalConfig.getOption(domain, "eval.baseFile");
  120. if (new File(baseFile).exists()) {
  121. wrapper = new ScriptEngineWrapper(scriptEngineManager, baseFile);
  122. } else {
  123. wrapper = new ScriptEngineWrapper(scriptEngineManager, null);
  124. }
  125. } else {
  126. wrapper = new ScriptEngineWrapper(scriptEngineManager, null);
  127. }
  128. wrapper.getScriptEngine().put("cmd_origin", origin);
  129. wrapper.getScriptEngine().put("cmd_isSilent", args.isSilent());
  130. wrapper.getScriptEngine().put("cmd_args", sargs);
  131. showOutput(origin, args.isSilent(), "Result: "
  132. + wrapper.getScriptEngine().eval(script));
  133. } catch (ScriptException e) {
  134. showOutput(origin, args.isSilent(), "Exception: " + e + " -> "
  135. + e.getMessage());
  136. if (globalConfig.getOptionBool(domain, "eval.showStackTrace")) {
  137. final String[] stacktrace = getTrace(e);
  138. for (String line : stacktrace) {
  139. showOutput(origin, args.isSilent(), "Stack trace: " + line);
  140. }
  141. }
  142. }
  143. } else {
  144. showError(origin, args.isSilent(), "You must specify some script to eval.");
  145. }
  146. } else if (sargs.length > 0 && "savetobasefile".equalsIgnoreCase(sargs[0])) {
  147. if (sargs.length > 2) {
  148. final String[] bits = sargs[1].split("/");
  149. final String functionName = bits[0];
  150. final String script = args.getArgumentsAsString(2);
  151. showOutput(origin, args.isSilent(), "Saving as '" + functionName
  152. + "': " + script);
  153. if (globalConfig.hasOptionString(domain, "eval.baseFile")) {
  154. try {
  155. final String baseFile = scriptDirectory + '/'
  156. + globalConfig.getOption(domain, "eval.baseFile");
  157. try (FileWriter writer = new FileWriter(baseFile, true)) {
  158. writer.write("function ");
  159. writer.write(functionName);
  160. writer.write("(");
  161. for (int i = 1; i < bits.length; i++) {
  162. writer.write(bits[i]);
  163. writer.write(" ");
  164. }
  165. writer.write(") {\n");
  166. writer.write(script);
  167. writer.write("\n}\n");
  168. writer.flush();
  169. }
  170. } catch (IOException ioe) {
  171. showError(origin, args.isSilent(), "IOException: " + ioe.getMessage());
  172. }
  173. } else {
  174. showError(origin, args.isSilent(),
  175. "No baseFile specified, please /set " + domain
  176. + " eval.baseFile filename (stored in scripts dir of profile)");
  177. }
  178. } else if (sargs.length > 1) {
  179. showError(origin, args.isSilent(), "You must specify some script to save.");
  180. } else {
  181. showError(origin, args.isSilent(),
  182. "You must specify a function name and some script to save.");
  183. }
  184. } else if (sargs.length > 0 && "help".equalsIgnoreCase(sargs[0])) {
  185. showOutput(origin, args.isSilent(),
  186. "This command allows you to interact with the script plugin");
  187. showOutput(origin, args.isSilent(), "-------------------");
  188. showOutput(origin, args.isSilent(),
  189. "reload/rehash - Reload all loaded scripts");
  190. showOutput(origin, args.isSilent(),
  191. "load <script> - load scripts/<script> (file name relative to scripts dir)");
  192. showOutput(origin, args.isSilent(),
  193. "unload <script> - unload <script> (full file name)");
  194. showOutput(origin, args.isSilent(),
  195. "eval <script> - evaluate the code <script> and return the result");
  196. showOutput(origin, args.isSilent(),
  197. "savetobasefile <name> <script> - save the code <script> to the eval basefile ("
  198. + domain + ".eval.basefile)");
  199. showOutput(origin, args.isSilent(),
  200. " as the function <name> (name/foo/bar will save it as 'name' with foo and");
  201. showOutput(origin, args.isSilent(),
  202. " bar as arguments.");
  203. showOutput(origin, args.isSilent(), "-------------------");
  204. } else {
  205. showError(origin, args.isSilent(), "Unknown subcommand.");
  206. }
  207. }
  208. @Override
  209. public AdditionalTabTargets getSuggestions(final int arg,
  210. final IntelligentCommandContext context) {
  211. final AdditionalTabTargets res = new AdditionalTabTargets();
  212. res.excludeAll();
  213. if (arg == 0) {
  214. res.add("help");
  215. res.add("rehash");
  216. res.add("reload");
  217. res.add("load");
  218. res.add("unload");
  219. res.add("eval");
  220. res.add("savetobasefile");
  221. } else if (arg == 1) {
  222. final Map<String, ScriptEngineWrapper> scripts = scriptManager.getScripts();
  223. if ("load".equalsIgnoreCase(context.getPreviousArgs().get(0))) {
  224. res.addAll(scriptManager.getPossibleScripts().stream()
  225. .collect(Collectors.toList()));
  226. } else if ("unload".equalsIgnoreCase(context.getPreviousArgs().get(0))) {
  227. res.addAll(scripts.keySet().stream().collect(Collectors.toList()));
  228. }
  229. }
  230. return res;
  231. }
  232. /**
  233. * Converts an exception into a string array.
  234. *
  235. * @param throwable Exception to convert
  236. *
  237. * @return Exception string array
  238. */
  239. private static String[] getTrace(final Throwable throwable) {
  240. String[] trace;
  241. if (throwable == null) {
  242. trace = new String[0];
  243. } else {
  244. final StackTraceElement[] traceElements = throwable.getStackTrace();
  245. trace = new String[traceElements.length + 1];
  246. trace[0] = throwable.toString();
  247. for (int i = 0; i < traceElements.length; i++) {
  248. trace[i + 1] = traceElements[i].toString();
  249. }
  250. if (throwable.getCause() != null) {
  251. final String[] causeTrace = getTrace(throwable.getCause());
  252. final String[] newTrace = new String[trace.length + causeTrace.length];
  253. trace[0] = "\nWhich caused: " + trace[0];
  254. System.arraycopy(causeTrace, 0, newTrace, 0, causeTrace.length);
  255. System.arraycopy(trace, 0, newTrace, causeTrace.length, trace.length);
  256. trace = newTrace;
  257. }
  258. }
  259. return trace;
  260. }
  261. }