public static IScriptServicesBuilder Create(Config config, string[] scriptArgs) { Guard.AgainstNullArgument("commandArgs", config); Guard.AgainstNullArgument("scriptArgs", scriptArgs); IConsole console = new ScriptConsole(); if (!string.IsNullOrWhiteSpace(config.OutputFile)) { console = new FileConsole(config.OutputFile, console); } var logProvider = new ColoredConsoleLogProvider(config.LogLevel, console); var initializationServices = new InitializationServices(logProvider); initializationServices.GetAppDomainAssemblyResolver().Initialize(); // NOTE (adamralph): this is a hideous assumption about what happens inside the CommandFactory. // It is a result of the ScriptServicesBuilderFactory also having to know what is going to happen inside the // Command Factory so that it builds the builder(:-p) correctly in advance. // This demonstrates the technical debt that exists with the ScriptServicesBuilderFactory and CommandFactory // in their current form. We have a separate refactoring task raised to address this. var repl = config.Repl || (!config.Clean && config.PackageName == null && !config.Save && config.ScriptName == null); var scriptServicesBuilder = new ScriptServicesBuilder(console, logProvider, null, null, initializationServices) .Cache(config.Cache) .Debug(config.Debug) .LogLevel(config.LogLevel) .ScriptName(config.ScriptName) .Repl(repl); return scriptServicesBuilder.LoadModules(Path.GetExtension(config.ScriptName) ?? ".csx", config.Modules); }
private static int Main(string[] args) { SetProfile(); ArgumentParseResult arguments; var console = new ScriptConsole(); try { var parser = new ArgumentHandler(new ArgumentParser(), new ConfigFileParser(console), new FileSystem()); arguments = parser.Parse(args); } catch(Exception ex) { console.WriteLine(ex.Message); var options = new ArgUsageOptions { ShowPosition = false, ShowType = false }; var usage = ArgUsage.GetUsage<ScriptCsArgs>(options: options); console.WriteLine(usage); return 1; } var scriptServicesBuilder = ScriptServicesBuilderFactory.Create(arguments.CommandArguments, arguments.ScriptArguments); var factory = new CommandFactory(scriptServicesBuilder); var command = factory.CreateCommand(arguments.CommandArguments, arguments.ScriptArguments); return (int)command.Execute(); }
public ScriptVariable Call(IList <ScriptVariable> args, ScriptConsole console) { if (args.Count != 2) { console.Warn("2 arguments required"); return(null); } return(new BooleanVariable(Object.ReferenceEquals(args[0], args[1]))); }
public ScriptVariable Call(IList <ScriptVariable> args, ScriptConsole console) { if (args == null) { throw new ArgumentNullException("args", "args cannot be null"); } return(this.Operation.Call(args, console.SequenceController)); }
public ScriptVariable Call(IList <ScriptVariable> args, ScriptConsole console) { if (args == null) { throw new ArgumentNullException("args", "args cannot be null"); } if (args.Count < 1) { throw new ArgumentException("args must have one or more elements", "args"); } if (args[0] == null) { throw new ArgumentException("first element of args cannot be null", "args"); } string viewerName = args[0].ToString(); SequenceView viewer = SequenceViewerController.Singleton.GetViewByTitle(viewerName); if (viewer == null) { throw new ArgumentException("first element of args must be resultSequence name : " + viewerName, "args"); } SequenceProcEnv env2 = new SequenceProcEnv(console.SequenceController, viewer.Sequence); IList <ProcParam <SequenceProcEnv> > parameters = this.Operation.GetParameters() ?? new ProcParam <SequenceProcEnv> [0]; if (args.Count != parameters.Count + 1) { throw new ArgumentException(string.Format(global::MotionDataHandler.Properties.Settings.Default.Msg_NumberOfArgumentsRequired, parameters.Count + 1)); } for (int i = 0; i < parameters.Count; i++) { string errorStr = ""; if (!parameters[i].FromScriptVariable(env2, args[i + 1], ref errorStr)) { throw new ArgumentException(string.Format(global::MotionDataHandler.Properties.Settings.Default.Msg_InvalidNthArgument + ": {1}", i + 1, errorStr ?? ""), "args"); } } SequenceData resultSequence = this.Operation.Operate(parameters, env2); ScriptVariable ret = null; if (resultSequence != null) { console.SequenceController.AddSequence(resultSequence, viewer.IsLocked); ret = new StringVariable(resultSequence.Title); } console.SequenceController.DoAllocationChanged(); if (this.Operation.ReplacesInternalData) { env2.SelectedSequence.IsDataChanged = true; } return(ret); }
private (ExecuteInteractiveCommand Command, ScriptConsole Console) GetExecuteInteractiveCommand(string[] commands) { var reader = new StringReader(string.Join(Environment.NewLine, commands)); var writer = new StringWriter(); var error = new StringWriter(); var console = new ScriptConsole(writer, reader, error); var logFactory = TestOutputHelper.CreateTestLogFactory(); return(new ExecuteInteractiveCommand(console, logFactory), console); }
private static Scaffolder CreateTestScaffolder(string installLocation) { var scriptEnvironment = (ScriptEnvironment)Activator.CreateInstance(typeof(ScriptEnvironment), nonPublic: true); var installLocationField = typeof(ScriptEnvironment).GetField("_installLocation", BindingFlags.NonPublic | BindingFlags.Instance); installLocationField.SetValue(scriptEnvironment, new Lazy <string>(() => installLocation)); var scriptConsole = new ScriptConsole(StringWriter.Null, StringReader.Null, StreamWriter.Null); var scaffolder = new Scaffolder(TestOutputHelper.CreateTestLogFactory(), scriptConsole, scriptEnvironment); return(scaffolder); }
public ScriptVariable Call(IList <ScriptVariable> args, ScriptConsole console) { if (console.ParentControl.InvokeRequired) { return((ScriptVariable)console.ParentControl.Invoke(new Func <IList <ScriptVariable>, ScriptConsole, ScriptVariable>(Call), args, console)); } SequenceViewerForm form = SequenceViewerForm.Singleton; form.Show(); return(null); }
public ScriptVariable Call(IList <ScriptVariable> args, ScriptConsole console) { if (args.Count == 0) { return(null); } if (args.Count == 1) { return(lengthOf(args[0])); } return(new ListVariable(args.Select(arg => lengthOf(arg)))); }
public ScriptVariable Call(IList <ScriptVariable> args, ScriptConsole console) { if (args.Count == 0 || args[0] == null || args[0].ToNumber() < 0) { System.Windows.Forms.MessageBox.Show("Sleeing...", typeof(SleepFunction).Name, System.Windows.Forms.MessageBoxButtons.OK); } else { System.Threading.Thread.Sleep((int)(args[0].ToNumber() * 1000M)); } return(null); }
public static IScriptServicesBuilder Create(ScriptCsArgs commandArgs, string[] scriptArgs) { Guard.AgainstNullArgument("commandArgs", commandArgs); Guard.AgainstNullArgument("scriptArgs", scriptArgs); IConsole console = new ScriptConsole(); if (!string.IsNullOrWhiteSpace(commandArgs.Output)) { console = new FileConsole(commandArgs.Output, console); } var configurator = new LoggerConfigurator(commandArgs.LogLevel); configurator.Configure(console); var logger = configurator.GetLogger(); var initializationServices = new InitializationServices(logger); initializationServices.GetAppDomainAssemblyResolver().Initialize(); var scriptServicesBuilder = new ScriptServicesBuilder(console, logger, null, null, initializationServices) .Cache(commandArgs.Cache) .Debug(commandArgs.Debug) .LogLevel(commandArgs.LogLevel) .ScriptName(commandArgs.ScriptName) .Repl(commandArgs.Repl); var modules = commandArgs.Modules == null ? new string[0] : commandArgs.Modules.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries); var extension = Path.GetExtension(commandArgs.ScriptName); if (string.IsNullOrWhiteSpace(extension) && !commandArgs.Repl) { // No extension was given, i.e we might have something like // "scriptcs foo" to deal with. We activate the default extension, // to make sure it's given to the LoadModules below. extension = ".csx"; if (!string.IsNullOrWhiteSpace(commandArgs.ScriptName)) { // If the was in fact a script specified, we'll extend it // with the default extension, assuming the user giving // "scriptcs foo" actually meant "scriptcs foo.csx". We // perform no validation here thought; let it be done by // the activated command. If the file don't exist, it's // up to the command to detect and report. commandArgs.ScriptName += extension; } } return scriptServicesBuilder.LoadModules(extension, modules); }
private static ArgumentParseResult ParseArguments(string[] args) { var console = new ScriptConsole(); try { var parser = new ArgumentHandler(new ArgumentParser(console), new ConfigFileParser(console), new FileSystem()); return parser.Parse(args); } finally { console.Exit(); } }
public MotionOperationExecution(IMotionOperationBase operation, ScriptConsole console) { if (operation == null) { throw new ArgumentNullException("operation", "'operation' cannot be null"); } if (console == null) { throw new ArgumentNullException("console", "'console' cannot be null"); } _operation = operation; _console = console; }
private ScriptServices CreateScriptServices(bool useLogging) { var console = new ScriptConsole(); var configurator = new LoggerConfigurator(useLogging ? LogLevel.Debug : LogLevel.Info); configurator.Configure(console); var logger = configurator.GetLogger(); var builder = new ScriptServicesBuilder(console, logger); builder.ScriptEngine<RoslynScriptEngine>(); return builder.Build(); }
public ScriptVariable Call(IList <ScriptVariable> args, ScriptConsole console) { ScriptVariable arg = null; if (args.Count >= 1) { arg = args[0]; } if (arg == null) { return(null); } return(new ListVariable(arg.ToList())); }
private static ArgumentParseResult ParseArguments(string[] args) { var console = new ScriptConsole(); try { var parser = new ArgumentHandler(new ArgumentParser(console), new ConfigFileParser(console), new FileSystem()); return(parser.Parse(args)); } finally { console.Exit(); } }
public async Task <T> Load(FileInfo file) { Console.Error.WriteLine($"Compiling {file.FullName}"); var console = new ScriptConsole(Console.Error, Console.In, Console.Error); var logger = LogHelper.CreateLogFactory(Verbose ? "debug" : "warning"); var manifestSource = File.ReadAllText(file.FullName); var command = new ExecuteCodeCommand(console, logger); var options = new ExecuteCodeCommandOptions(manifestSource, file.DirectoryName, new string[] { }, Microsoft.CodeAnalysis.OptimizationLevel.Debug, true, null); return(await command.Execute <T>(options)); }
private InteractiveTestContext GetRunner(params string[] commands) { var reader = new StringReader(string.Join(Environment.NewLine, commands)); var writer = new StringWriter(); var error = new StringWriter(); var console = new ScriptConsole(writer, reader, error); var logFactory = TestOutputHelper.CreateTestLogFactory(); var compiler = new ScriptCompiler(logFactory, useRestoreCache: false); var runner = new InteractiveRunner(compiler, logFactory, console, Array.Empty <string>()); return(new InteractiveTestContext(console, runner)); }
private static IArgumentHandler Setup(string fileContent, string fileName = "scriptcs.opts", bool fileExists = true) { const string currentDirectory = "C:\\test\\folder"; string filePath = currentDirectory + '\\' + fileName; var fs = new Mock <IFileSystem>(); fs.SetupGet(x => x.CurrentDirectory).Returns(currentDirectory); fs.Setup(x => x.FileExists(filePath)).Returns(fileExists); fs.Setup(x => x.ReadFile(filePath)).Returns(fileContent); var console = new ScriptConsole(); return(new ArgumentHandler(new ArgumentParser(console), new ConfigFileParser(console), fs.Object)); }
public DialogMotionOperation(ScriptConsole console, IMotionOperationBase operation) : this() { if (console == null) { throw new ArgumentNullException("console", "'console' cannot be null"); } if (operation == null) { throw new ArgumentNullException("operation", "'operation' cannot be null"); } _operation = operation; _console = console; _exec = new MotionOperationExecution(operation, _console); _targetInfoList = _console.MotionDataSet.GetSelectedObjectInfoList(info => _operation.FilterSelection(info)); }
public ScriptVariable Call(IList <ScriptVariable> args, ScriptConsole console) { if (args.Count < 1) { args = new ScriptVariable[] { new StringVariable("") }.ToList(); } List <ScriptVariable> msgs = new List <ScriptVariable>(); bool isList = args[0] is ListVariable; IList <ScriptVariable> firstArg = args[0].IsNull() ? new[] { new StringVariable("") } : args[0].ToList(); foreach (var arg in firstArg) { string name = arg.IsNull() ? "null" : arg.ToString(); try { msgs.Add(new StringVariable(name + " " + ScriptConsole.Singleton.GetUsage(name))); } catch (ArgumentException) { List <string> names = ScriptConsole.Singleton.GetFunctionNames(name); StringBuilder ret = new StringBuilder(); ret.AppendLine("subroutines starting with \"" + name + "\""); foreach (var n in names.Take(512)) { ret.AppendLine(" " + n); } if (names.Count > 512) { ret.Append("... "); } ret.AppendLine("(" + names.Count + " subroutines)"); msgs.Add(new StringVariable(ret.ToString())); } } if (args.Count >= 2 && !args[1].IsNull() && args[1].ToBoolean()) { if (isList) { return(new ListVariable(msgs)); } else { return(msgs[0]); } } return(ScriptConsole.Singleton.Invoke(new PrintFunction(), msgs)); }
public ScriptVariable Call(IList <ScriptVariable> args, ScriptConsole console) { StringWriter writer = new StringWriter(); foreach (var arg in args) { if (arg.IsNull()) { writer.Write("null"); } else { writer.Write(arg.ToString()); } } string str = writer.ToString(); console.Print(str); return(new NumberVariable(str.Length)); }
private static IArgumentHandler Setup(string fileContent, string fileName = Constants.ConfigFilename, bool fileExists = true, string globalFileContent = null) { const string currentDirectory = "C:\\test\\folder"; const string moduleDirectory = "C:\\test\\moduleFolder"; string filePath = currentDirectory + '\\' + fileName; string globalFilePath = moduleDirectory + "\\" + Constants.ConfigFilename; var fs = new Mock <IFileSystem>(); fs.SetupGet(x => x.CurrentDirectory).Returns(currentDirectory); fs.Setup(x => x.FileExists(filePath)).Returns(fileExists); fs.Setup(x => x.ReadFile(filePath)).Returns(fileContent); fs.SetupGet(x => x.GlobalFolder).Returns(moduleDirectory); fs.SetupGet(x => x.GlobalOptsFile).Returns(globalFilePath); fs.Setup(x => x.FileExists(globalFilePath)).Returns(globalFileContent != null); fs.Setup(x => x.ReadFile(globalFilePath)).Returns(globalFileContent); var console = new ScriptConsole(); return(new ArgumentHandler(new ArgumentParser(console), new ConfigFileParser(console), fs.Object)); }
public static IScriptServicesBuilder Create(Config config, string[] scriptArgs) { if (scriptArgs == null) { throw new ArgumentNullException(nameof(scriptArgs)); } IConsole console = new ScriptConsole(); if (!string.IsNullOrWhiteSpace(config.OutputFile)) { console = new FileConsole(config.OutputFile, console); } var logProvider = new ColoredConsoleLogProvider(config.LogLevel, console); var initializationServices = new InitializationServices(logProvider); //todo: maybe not needed at all? //initializationServices.GetAppDomainAssemblyResolver().Initialize(); // NOTE (adamralph): this is a hideous assumption about what happens inside the CommandFactory. // It is a result of the ScriptServicesBuilderFactory also having to know what is going to happen inside the // Command Factory so that it builds the builder(:-p) correctly in advance. // This demonstrates the technical debt that exists with the ScriptServicesBuilderFactory and CommandFactory // in their current form. We have a separate refactoring task raised to address this. var repl = config.Repl || (!config.Clean && config.PackageName == null && !config.Save && config.ScriptName == null); var scriptServicesBuilder = new ScriptServicesBuilder(console, logProvider, null, null, initializationServices) .Cache(config.Cache) .Debug(config.Debug) .LogLevel(config.LogLevel) .ScriptName(config.ScriptName) .Repl(repl); return(scriptServicesBuilder.LoadModules(Path.GetExtension(config.ScriptName) ?? ".csx", config.Modules)); }
private void scriptChecker_Tick(object sender, EventArgs e) { if (!scriptrunning) { labelScriptStatus.Text = "Script Status: Finished (or aborted)"; scriptChecker.Enabled = false; BUT_select_script.Enabled = true; BUT_run_script.Enabled = true; BUT_abort_script.Visible = false; BUT_edit_selected.Enabled = true; checkBoxRedirectOutput.Enabled = true; } else if ((script != null) && (checkBoxRedirectOutput.Checked) && (!outputwindowstarted)) { outputwindowstarted = true; ScriptConsole console = new ScriptConsole(); console.SetScript(script); ThemeManager.ApplyThemeTo(console); console.Show(); console.BringToFront(); components.Add(console); } }
public PublishCommand(ScriptConsole scriptConsole, LogFactory logFactory) { _scriptConsole = scriptConsole; _logFactory = logFactory; _logger = logFactory.CreateLogger <PublishCommand>(); }
public InteractiveTestContext(ScriptConsole console, InteractiveRunner runner) { Console = console; Runner = runner; }
public ExecuteCodeCommand(ScriptConsole scriptConsole, LogFactory logFactory) { _scriptConsole = scriptConsole; _logFactory = logFactory; }
public PublishCommand(ScriptConsole scriptConsole, LogFactory logFactory) { _scriptConsole = scriptConsole; _logFactory = logFactory; }
private bool RunScriptFile(string path) { string hash; using (var stream = File.OpenRead(path)) { hash = Encoding.UTF8.GetString(System.Security.Cryptography.MD5.Create().ComputeHash(stream)); } var scriptName = Path.GetFileNameWithoutExtension(path); string value; if (scriptName != null && scriptHashes.TryGetValue(scriptName, out value) && value == hash) { return(false); } using (StartScriptProcessingSession(new ScriptSource(scriptName, path))) { try { ParseScriptComments(path); } catch (Exception ex) { _logger.Warn(string.Format("Could not parse comments: {0}", ex.Message)); } var console = new ScriptConsole(); var scriptServicesBuilder = new ScriptServicesBuilder(console, _logger); scriptServicesBuilder.Cache(false); scriptServicesBuilder.LoadModules("csx"); var scriptServiceRoot = scriptServicesBuilder.Build(); var defaultReferences = ScriptExecutor.DefaultReferences.ToArray(); var fileSystem = new FileSystem(); //where clause hack using the exact same code that the hack in scriptCS sues to filter their list of assemblies in ShouldLoadAssembly in RuntimeServices.cs var packageReferences = scriptServiceRoot.PackageAssemblyResolver.GetAssemblyNames(Environment.CurrentDirectory).Where(fileSystem.IsPathRooted); scriptServiceRoot.Executor.AddReferences(defaultReferences.Concat(NuGetPackageAssemblyResolver.FilterAssembliesToMostRecent(packageReferences)).ToArray()); scriptServiceRoot.Executor.ImportNamespaces( ScriptExecutor.DefaultNamespaces.Concat(new[] { "MMBot", "Newtonsoft.Json", "Newtonsoft.Json.Linq", "HtmlAgilityPack", "System.Xml", "System.Net", "System.Net.Http" }).ToArray()); scriptServiceRoot.Executor.AddReference <Robot>(); scriptServiceRoot.Executor.AddReference <ILog>(); scriptServiceRoot.Executor.AddReference <JArray>(); scriptServiceRoot.Executor.AddReference <HtmlDocument>(); scriptServiceRoot.Executor.AddReference <HttpResponseMessage>(); scriptServiceRoot.Executor.AddReference <IScriptPackContext>(); scriptServiceRoot.Executor.AddReference <OwinContext>(); scriptServiceRoot.Executor.Initialize(new string[0], new IScriptPack[] { new MMBot2ScriptPackInternal(_robot), }); var result = scriptServiceRoot.Executor.Execute(path); if (!result.IsCompleteSubmission) { _logger.Error(string.Format("{0}: error compiling script - {1}", path, result.CompileExceptionInfo.SourceException.Message)); } if (result.CompileExceptionInfo != null) { _logger.Error(result.CompileExceptionInfo.SourceException.Message); _logger.Debug(result.CompileExceptionInfo.SourceException); } if (result.ExecuteExceptionInfo != null) { _logger.Error(result.ExecuteExceptionInfo.SourceException); } scriptHashes[CurrentScriptSource.Name] = hash; return(result.IsCompleteSubmission && result.CompileExceptionInfo == null && result.ExecuteExceptionInfo == null); } }
/// <summary> /// Initializes a new instance of the <see cref="EnvironmentReporter"/> class. /// </summary> /// <param name="versionProvider">The <see cref="IVersionProvider"/> that is /// responsible for providing the current and latest version.</param> /// <param name="scriptConsole">The <see cref="ScriptConsole"/> to write to.</param> /// <param name="scriptEnvironment">The <see cref="ScriptEnvironment"/> providing environmental information.</param> public EnvironmentReporter(IVersionProvider versionProvider, ScriptConsole scriptConsole, ScriptEnvironment scriptEnvironment) { _versionProvider = versionProvider; _scriptConsole = scriptConsole; _scriptEnvironment = scriptEnvironment; }
private bool RunScriptFile(string path) { using (StartScriptProcessingSession(new ScriptSource(Path.GetFileNameWithoutExtension(path), path))) { try { ParseScriptComments(path); } catch (Exception ex) { _logger.Warn(string.Format("Could not parse comments: {0}", ex.Message)); } var console = new ScriptConsole(); var scriptServicesBuilder = new ScriptServicesBuilder(console, _logger); scriptServicesBuilder.Cache(false); scriptServicesBuilder.LoadModules("csx", new string[0]); var scriptServiceRoot = scriptServicesBuilder.Build(); var defaultReferences = ScriptExecutor.DefaultReferences.ToArray(); var packageReferences = scriptServiceRoot.PackageAssemblyResolver.GetAssemblyNames(Environment.CurrentDirectory); scriptServiceRoot.Executor.AddReferences(defaultReferences.Concat(NuGetPackageAssemblyResolver.FilterAssembliesToMostRecent(packageReferences)).ToArray()); scriptServiceRoot.Executor.ImportNamespaces( ScriptExecutor.DefaultNamespaces.Concat(new[] { "MMBot", "Newtonsoft.Json", "Newtonsoft.Json.Linq", "HtmlAgilityPack", "System.Xml", "System.Net", "System.Net.Http" }).ToArray()); scriptServiceRoot.Executor.AddReference <Robot>(); scriptServiceRoot.Executor.AddReference <ILog>(); scriptServiceRoot.Executor.AddReference <JArray>(); scriptServiceRoot.Executor.AddReference <HtmlDocument>(); scriptServiceRoot.Executor.AddReference <HttpResponseMessage>(); scriptServiceRoot.Executor.AddReference <IScriptPackContext>(); scriptServiceRoot.Executor.AddReference <OwinContext>(); scriptServiceRoot.Executor.Initialize(new string[0], new IScriptPack[] { new MMBot2ScriptPackInternal(_robot), }); var result = scriptServiceRoot.Executor.Execute(path); if (result.CompileExceptionInfo != null) { _logger.Error(result.CompileExceptionInfo.SourceException.Message); _logger.Debug(result.CompileExceptionInfo.SourceException); } if (result.ExecuteExceptionInfo != null) { _logger.Error(result.ExecuteExceptionInfo.SourceException); } return(result.CompileExceptionInfo == null && result.ExecuteExceptionInfo == null); } }
private static IArgumentHandler Setup(string fileContent, string fileName = "scriptcs.opts", bool fileExists = true) { const string currentDirectory = "C:\\test\\folder"; string filePath = currentDirectory + '\\' + fileName; var fs = new Mock<IFileSystem>(); fs.SetupGet(x => x.CurrentDirectory).Returns(currentDirectory); fs.Setup(x => x.FileExists(filePath)).Returns(fileExists); fs.Setup(x => x.ReadFile(filePath)).Returns(fileContent); var console = new ScriptConsole(); return new ArgumentHandler(new ArgumentParser(console), new ConfigFileParser(console), fs.Object); }
public ExecuteScriptCommand(ScriptConsole scriptConsole, LogFactory logFactory) { _scriptConsole = scriptConsole; _logFactory = logFactory; _logger = logFactory.CreateLogger <ExecuteScriptCommand>(); }
private bool RunScriptFile(string path) { string hash; using (var stream = File.OpenRead(path)) { hash = Encoding.UTF8.GetString(System.Security.Cryptography.MD5.Create().ComputeHash(stream)); } var scriptName = Path.GetFileNameWithoutExtension(path); string value; if (scriptName != null && scriptHashes.TryGetValue(scriptName, out value) && value == hash) { return false; } using (StartScriptProcessingSession(new ScriptSource(scriptName, path))) { try { ParseScriptComments(path); } catch (Exception ex) { _logger.Warn(string.Format("Could not parse comments: {0}", ex.Message)); } var console = new ScriptConsole(); var scriptServicesBuilder = new ScriptServicesBuilder(console, _logger); scriptServicesBuilder.Cache(false); scriptServicesBuilder.LoadModules("csx"); var scriptServiceRoot = scriptServicesBuilder.Build(); var defaultReferences = ScriptExecutor.DefaultReferences.ToArray(); var fileSystem = new FileSystem(); //where clause hack using the exact same code that the hack in scriptCS sues to filter their list of assemblies in ShouldLoadAssembly in RuntimeServices.cs var packageReferences = scriptServiceRoot.PackageAssemblyResolver.GetAssemblyNames(Environment.CurrentDirectory).Where(fileSystem.IsPathRooted); scriptServiceRoot.Executor.AddReferences(defaultReferences.Concat(NuGetPackageAssemblyResolver.FilterAssembliesToMostRecent(packageReferences)).ToArray()); scriptServiceRoot.Executor.ImportNamespaces( ScriptExecutor.DefaultNamespaces.Concat(new[] { "MMBot", "Newtonsoft.Json", "Newtonsoft.Json.Linq", "HtmlAgilityPack", "System.Xml", "System.Net", "System.Net.Http" }).ToArray()); scriptServiceRoot.Executor.AddReference<Robot>(); scriptServiceRoot.Executor.AddReference<ILog>(); scriptServiceRoot.Executor.AddReference<JArray>(); scriptServiceRoot.Executor.AddReference<HtmlDocument>(); scriptServiceRoot.Executor.AddReference<HttpResponseMessage>(); scriptServiceRoot.Executor.AddReference<IScriptPackContext>(); scriptServiceRoot.Executor.AddReference<OwinContext>(); scriptServiceRoot.Executor.Initialize(new string[0], new IScriptPack[] { new MMBot2ScriptPackInternal(_robot), }); var result = scriptServiceRoot.Executor.Execute(path); if (!result.IsCompleteSubmission) { _logger.Error(string.Format("{0}: error compiling script - {1}", path, result.CompileExceptionInfo.SourceException.Message)); } if (result.CompileExceptionInfo != null) { _logger.Error(result.CompileExceptionInfo.SourceException.Message); _logger.Debug(result.CompileExceptionInfo.SourceException); } if (result.ExecuteExceptionInfo != null) { _logger.Error(result.ExecuteExceptionInfo.SourceException); } scriptHashes[CurrentScriptSource.Name] = hash; return result.IsCompleteSubmission && result.CompileExceptionInfo == null && result.ExecuteExceptionInfo == null; } }
public void TestJavaConsoleCommand() { ScriptConsole.Main(new string[] { "-l", "JAVASCRIPT", "-t", "2", "-f", "c:\\", "-s", "500" }); }
public MotionProcEnv(ScriptConsole console) { this.DataSet = console.MotionDataSet; this.SequenceController = console.SequenceController; }
public ScriptVariable Call(IList <ScriptVariable> args, ScriptConsole console) { _progress.Initialize(0, "Initializing..."); if (args == null) { throw new ArgumentNullException("args", "args cannot be null"); } if (args.Count < 1) { args = new List <ScriptVariable> { null } } ; if (args[0] == null) { args[0] = new ListVariable(); } IList <ScriptVariable> objectNamesVar = args[0].ToList(); if (objectNamesVar.Any(n => n.IsNull())) { throw new ArgumentException(global::MotionDataHandler.Properties.Settings.Default.Msg_ObjectNameCannotBeNull, "args"); } List <string> objectNames = objectNamesVar.Select(n => n.ToString()).ToList(); MotionDataSet dataSet = console.MotionDataSet; MotionProcEnv env2 = new MotionProcEnv(console); List <MotionObjectInfo> infoList = new List <MotionObjectInfo>(); foreach (string objectName in objectNames) { MotionObjectInfo info = dataSet.GetObjectInfoByName(objectName); if (info == null) { throw new ArgumentException(global::MotionDataHandler.Properties.Settings.Default.Msg_ObjectNotFound + ": " + objectName, "args"); } infoList.Add(info); } foreach (MotionObjectInfo info in infoList) { if (!_operation.FilterSelection(info)) { throw new ArgumentException(global::MotionDataHandler.Properties.Settings.Default.Msg_InvalidTargetObjectSpecified + ": " + info.Name, "args"); } } string errorMessage = ""; if (!_operation.ValidateSelection(infoList, ref errorMessage)) { if (errorMessage == null) { errorMessage = ""; } throw new ArgumentException(global::MotionDataHandler.Properties.Settings.Default.Msg_ImproperObjectSelection + ": " + errorMessage, "args"); } IList <ProcParam <MotionProcEnv> > parameters = _operation.GetParameters() ?? new ProcParam <MotionProcEnv> [0]; if (args.Count != parameters.Count + 1) { throw new ArgumentException(string.Format(global::MotionDataHandler.Properties.Settings.Default.Msg_NumberOfArgumentsRequired, parameters.Count + 1)); } for (int i = 0; i < parameters.Count; i++) { if (!parameters[i].FromScriptVariable(env2, args[i + 1], ref errorMessage)) { throw new ArgumentException(string.Format(global::MotionDataHandler.Properties.Settings.Default.Msg_InvalidNthArgument + ": {1}", i + 1, errorMessage ?? ""), "args"); } } if (!_operation.ValidateArguments(parameters, ref errorMessage)) { throw new ArgumentException(string.Format(global::MotionDataHandler.Properties.Settings.Default.Msg_InvalidArgument + ": {0}", errorMessage ?? ""), "args"); } IMotionOperationGeneral general = _operation as IMotionOperationGeneral; if (general != null) { _progress.Initialize(0, "Operation"); general.Operate(infoList, parameters, dataSet, _progress); return(new ListVariable(infoList.Select(info => new StringVariable(info.Name)))); } IMotionOperationEditObject edit = _operation as IMotionOperationEditObject; if (edit != null) { _progress.Initialize(dataSet.FrameLength, "Edit Object"); foreach (MotionFrame frame in dataSet.EnumerateFrame()) { IList <MotionObject> results = edit.EditObject(infoList, parameters, new ReadOnlyMotionFrame(frame), false); int count = Math.Min(results.Count, infoList.Count); for (int i = 0; i < count; i++) { frame[infoList[i]] = results[i]; } _progress.CurrentValue++; } dataSet.DoFrameListChanged(); return(new ListVariable(infoList.Select(info => new StringVariable(info.Name)))); } IMotionOperationOutputSequence output = _operation as IMotionOperationOutputSequence; if (output != null) { _progress.Initialize(0, "Output"); IList <Sequence.SequenceData> sequences = output.OutputSequence(infoList, parameters, dataSet.EnumerateFrame().Select(frame => new ReadOnlyMotionFrame(frame)), _progress); foreach (Sequence.SequenceData sequence in sequences) { console.SequenceController.AddSequence(sequence); } return(new ListVariable(sequences.Select(s => new StringVariable(s.Title)))); } IMotionOperationCreateObject create = _operation as IMotionOperationCreateObject; if (create != null) { _progress.Initialize(dataSet.FrameLength, "Create Object"); IList <MotionObjectInfo> newInfoList = create.GetNewObjectInfoList(infoList, parameters); MotionFrame firstFrame = dataSet.GetFrameByIndex(0); if (firstFrame != null) { IList <MotionObject> newObjects = create.CreateObjects(infoList, parameters, new ReadOnlyMotionFrame(firstFrame), false) ?? new MotionObject[0]; if (newObjects.Count != newInfoList.Count) { throw new InvalidOperationException(global::MotionDataHandler.Properties.Settings.Default.Msg_CreateObjectLengthMismatch); } } foreach (MotionObjectInfo newInfo in newInfoList) { dataSet.AddObject(newInfo); } foreach (MotionFrame frame in dataSet.EnumerateFrame()) { IList <MotionObject> newObjects = create.CreateObjects(infoList, parameters, new ReadOnlyMotionFrame(frame), false) ?? new MotionObject[0]; int count = Math.Min(newObjects.Count, newInfoList.Count); for (int i = 0; i < count; i++) { frame[newInfoList[i]] = newObjects[i]; } _progress.CurrentValue++; } dataSet.DoObjectInfoSetChanged(); dataSet.DoFrameListChanged(); return(new ListVariable(newInfoList.Select(info => new StringVariable(info.Name)))); } return(null); }