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.

ScriptCommand.java 13KB

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