public static async System.Threading.Tasks.Task RundotNetScript(string[] args, IStaticSite ctx) { var logger = new ScriptLogger(ScriptConsole.Default.Out, true); var dependencyResolver = new RuntimeDependencyResolver(type => ((level, message) => { if (level == LogLevel.Debug) { logger.Verbose(message); } if (level == LogLevel.Info) { logger.Log(message); } })); var code = Microsoft.CodeAnalysis.Text.SourceText.From(File.ReadAllText("FlipLeaf.csx")); var scriptContext = new ScriptContext(code, Environment.CurrentDirectory ?? Directory.GetCurrentDirectory(), args, scriptMode: Dotnet.Script.DependencyModel.Context.ScriptMode.REPL); var compiler = new ScriptCompiler(logger, dependencyResolver); var runner = new ScriptRunner(compiler, logger, ScriptConsole.Default); await runner.Execute <int>(scriptContext); }
private InteractiveTestContext GetRunner(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 logger = new ScriptLogger(console.Error, true); var runtimeDependencyResolver = new RuntimeDependencyResolver(type => ((level, message) => { if (level == LogLevel.Debug) { logger.Verbose(message); } if (level == LogLevel.Info) { logger.Log(message); } })); var compiler = new ScriptCompiler(logger, runtimeDependencyResolver); var runner = new InteractiveRunner(compiler, logger, console); return(new InteractiveTestContext(console, runner)); }
private LogFactory GetLogFactory() { var logger = new ScriptLogger(ScriptConsole.Default.Error, true); return(type => ((level, message) => { if (level == LogLevel.Debug) { logger.Verbose(message); } if (level == LogLevel.Info) { logger.Log(message); } })); }
/// <inheritdoc /> public string Execute(string commandPath, string arguments) { _lastStandardErrorOutput.Clear(); _logger.Verbose($"Executing {commandPath} {arguments}"); var startInformation = CreateProcessStartInfo(commandPath, arguments); var process = CreateProcess(startInformation); RunAndWait(process); _logger.Verbose(_lastProcessOutput.ToString()); if (process.ExitCode != 0) { _logger.Log(_lastStandardErrorOutput.ToString()); throw new InvalidOperationException($"The command {commandPath} {arguments} failed to execute"); } return(_lastProcessOutput.ToString()); }
private static ScriptCompiler GetScriptCompiler(bool debugMode) { var logger = new ScriptLogger(ScriptConsole.Default.Error, debugMode); var runtimeDependencyResolver = new RuntimeDependencyResolver(type => ((level, message) => { if (level == LogLevel.Debug) { logger.Verbose(message); } if (level == LogLevel.Info) { logger.Log(message); } })); var compiler = new ScriptCompiler(logger, runtimeDependencyResolver); return(compiler); }
private ScriptCompiler GetScriptCompiler() { var logger = new ScriptLogger(ScriptConsole.Default.Error, LogVerbosityDebug); var runtimeDependencyResolver = new RuntimeDependencyResolver(type => ((level, message) => { switch (level) { case LogLevel.Debug: logger.Verbose(message); break; case LogLevel.Info: logger.Log(message); break; } })); var compiler = new ScriptCompiler(logger, runtimeDependencyResolver); return(compiler); }
private static int Wain(string[] args) { var app = new CommandLineApplication(throwOnUnexpectedArg: false) { ExtendedHelpText = "Starting without a path to a CSX file or a command, starts the REPL (interactive) mode." }; var file = app.Argument("script", "Path to CSX script"); var interactive = app.Option("-i | --interactive", "Execute a script and drop into the interactive mode afterwards.", CommandOptionType.NoValue); var configuration = app.Option("-c | --configuration <configuration>", "Configuration to use for running the script [Release/Debug] Default is \"Debug\"", CommandOptionType.SingleValue); var packageSources = app.Option("-s | --sources <SOURCE>", "Specifies a NuGet package source to use when resolving NuGet packages.", CommandOptionType.MultipleValue); var debugMode = app.Option(DebugFlagShort + " | " + DebugFlagLong, "Enables debug output.", CommandOptionType.NoValue); var argsBeforeDoubleHyphen = args.TakeWhile(a => a != "--").ToArray(); var argsAfterDoubleHypen = args.SkipWhile(a => a != "--").Skip(1).ToArray(); app.HelpOption("-? | -h | --help"); app.VersionOption("-v | --version", GetVersion); var infoOption = app.Option("--info", "Displays environmental information", CommandOptionType.NoValue); app.Command("eval", c => { c.Description = "Execute CSX code."; var code = c.Argument("code", "Code to execute."); var cwd = c.Option("-cwd |--workingdirectory <currentworkingdirectory>", "Working directory for the code compiler. Defaults to current directory.", CommandOptionType.SingleValue); c.OnExecute(async() => { int exitCode = 0; if (!string.IsNullOrWhiteSpace(code.Value)) { var optimizationLevel = OptimizationLevel.Debug; if (configuration.HasValue() && configuration.Value().ToLower() == "release") { optimizationLevel = OptimizationLevel.Release; } exitCode = await RunCode(code.Value, debugMode.HasValue(), optimizationLevel, app.RemainingArguments.Concat(argsAfterDoubleHypen), cwd.Value(), packageSources.Values?.ToArray()); } return(exitCode); }); }); app.Command("init", c => { c.Description = "Creates a sample script along with the launch.json file needed to launch and debug the script."; var fileName = c.Argument("filename", "(Optional) The name of the sample script file to be created during initialization. Defaults to 'main.csx'"); var cwd = c.Option("-cwd |--workingdirectory <currentworkingdirectory>", "Working directory for initialization. Defaults to current directory.", CommandOptionType.SingleValue); c.OnExecute(() => { var scaffolder = new Scaffolder(new ScriptLogger(ScriptConsole.Default.Error, debugMode.HasValue())); scaffolder.InitializerFolder(fileName.Value, cwd.Value() ?? Directory.GetCurrentDirectory()); return(0); }); }); app.Command("new", c => { c.Description = "Creates a new script file"; var fileNameArgument = c.Argument("filename", "The script file name"); var cwd = c.Option("-cwd |--workingdirectory <currentworkingdirectory>", "Working directory the new script file to be created. Defaults to current directory.", CommandOptionType.SingleValue); c.OnExecute(() => { var scaffolder = new Scaffolder(new ScriptLogger(ScriptConsole.Default.Error, debugMode.HasValue())); if (fileNameArgument.Value == null) { c.ShowHelp(); return(0); } scaffolder.CreateNewScriptFile(fileNameArgument.Value, cwd.Value() ?? Directory.GetCurrentDirectory()); return(0); }); }); app.Command("publish", c => { c.Description = "Creates a self contained executable or DLL from a script"; var fileNameArgument = c.Argument("filename", "The script file name"); var publishDirectoryOption = c.Option("-o |--output", "Directory where the published executable should be placed. Defaults to a 'publish' folder in the current directory.", CommandOptionType.SingleValue); var dllName = c.Option("-n |--name", "The name for the generated DLL (executable not supported at this time). Defaults to the name of the script.", CommandOptionType.SingleValue); var dllOption = c.Option("--dll", "Publish to a .dll instead of an executable.", CommandOptionType.NoValue); var commandConfig = c.Option("-c | --configuration <configuration>", "Configuration to use for publishing the script [Release/Debug]. Default is \"Debug\"", CommandOptionType.SingleValue); var publishDebugMode = c.Option(DebugFlagShort + " | " + DebugFlagLong, "Enables debug output.", CommandOptionType.NoValue); var runtime = c.Option("-r |--runtime", "The runtime used when publishing the self contained executable. Defaults to your current runtime.", CommandOptionType.SingleValue); c.OnExecute(() => { if (fileNameArgument.Value == null) { c.ShowHelp(); return(0); } var optimizationLevel = OptimizationLevel.Debug; if (commandConfig.HasValue() && commandConfig.Value().ToLower() == "release") { optimizationLevel = OptimizationLevel.Release; } var runtimeIdentifier = runtime.Value() ?? ScriptEnvironment.Default.RuntimeIdentifier; var absoluteFilePath = Path.IsPathRooted(fileNameArgument.Value) ? fileNameArgument.Value : Path.Combine(Directory.GetCurrentDirectory(), fileNameArgument.Value); // if a publish directory has been specified, then it is used directly, otherwise: // -- for EXE {current dir}/publish/{runtime ID} // -- for DLL {current dir}/publish var publishDirectory = publishDirectoryOption.Value() ?? (dllOption.HasValue() ? Path.Combine(Path.GetDirectoryName(absoluteFilePath), "publish") : Path.Combine(Path.GetDirectoryName(absoluteFilePath), "publish", runtimeIdentifier)); var absolutePublishDirectory = Path.IsPathRooted(publishDirectory) ? publishDirectory : Path.Combine(Directory.GetCurrentDirectory(), publishDirectory); var logFactory = GetLogFactory(); var compiler = GetScriptCompiler(publishDebugMode.HasValue()); var scriptEmmiter = new ScriptEmitter(ScriptConsole.Default, compiler); var publisher = new ScriptPublisher(logFactory, scriptEmmiter); var code = SourceText.From(File.ReadAllText(absoluteFilePath)); var context = new ScriptContext(code, absolutePublishDirectory, Enumerable.Empty <string>(), absoluteFilePath, optimizationLevel); if (dllOption.HasValue()) { publisher.CreateAssembly <int, CommandLineScriptGlobals>(context, logFactory, dllName.Value()); } else { publisher.CreateExecutable <int, CommandLineScriptGlobals>(context, logFactory, runtimeIdentifier); } return(0); LogFactory GetLogFactory() { var logger = new ScriptLogger(ScriptConsole.Default.Error, publishDebugMode.HasValue()); return(type => ((level, message) => { if (level == LogLevel.Debug) { logger.Verbose(message); } if (level == LogLevel.Info) { logger.Log(message); } })); } }); }); app.Command("exec", c => { c.Description = "Run a script from a DLL."; var dllPath = c.Argument("dll", "Path to DLL based script"); var commandDebugMode = c.Option(DebugFlagShort + " | " + DebugFlagLong, "Enables debug output.", CommandOptionType.NoValue); c.OnExecute(async() => { int exitCode = 0; if (!string.IsNullOrWhiteSpace(dllPath.Value)) { if (!File.Exists(dllPath.Value)) { throw new Exception($"Couldn't find file '{dllPath.Value}'"); } var absoluteFilePath = Path.IsPathRooted(dllPath.Value) ? dllPath.Value : Path.Combine(Directory.GetCurrentDirectory(), dllPath.Value); var compiler = GetScriptCompiler(commandDebugMode.HasValue()); var runner = new ScriptRunner(compiler, compiler.Logger, ScriptConsole.Default); var result = await runner.Execute <int>(absoluteFilePath); return(result); } return(exitCode); }); }); app.OnExecute(async() => { int exitCode = 0; if (infoOption.HasValue()) { Console.Write(GetEnvironmentInfo()); return(0); } if (!string.IsNullOrWhiteSpace(file.Value)) { var optimizationLevel = OptimizationLevel.Debug; if (configuration.HasValue() && configuration.Value().ToLower() == "release") { optimizationLevel = OptimizationLevel.Release; } exitCode = await RunScript(file.Value, debugMode.HasValue(), optimizationLevel, app.RemainingArguments.Concat(argsAfterDoubleHypen), interactive.HasValue(), packageSources.Values?.ToArray()); } else { await RunInteractive(debugMode.HasValue(), packageSources.Values?.ToArray()); } return(exitCode); }); return(app.Execute(argsBeforeDoubleHyphen)); }