private static async Task <bool> IsInsideGitWorkTreeAsync(DirectoryInfo outputDirectory) { var gitDiff = new ProcessStartInfo("git") { Arguments = ArgumentEscaper.EscapeAndConcatenate(new[] { "rev-parse", "--is-inside-work-tree" }), WorkingDirectory = outputDirectory.FullName }; using var stdout = new StringWriter(); int exitCode = await gitDiff.GetExitCodeAsync(stdout, stdErr : TextWriter.Null); return(exitCode == 0); }
private void StartProcess(string directory) { const string exeName = "ワガママハイスペック.exe"; this._process = Process.Start( "wine", ArgumentEscaper.EscapeAndConcatenate(new[] { JoinPathInWindows(directory, exeName), "-forcelog=clear" })); var logFilePath = Path.Combine(ToUnixPath(directory), "savedata", "krkr.console.log"); // プロセス開始から 5 秒間はログファイルにアクセスさせない var allowedToAccessAt = DateTime.UtcNow.AddTicks(5 * TimeSpan.TicksPerSecond); var logObservable = Observable.Create <string>(async(observer, cancellationToken) => { var now = DateTime.UtcNow; if (now < allowedToAccessAt) { await Task.Delay(allowedToAccessAt - now, cancellationToken).ConfigureAwait(false); } using (var reader = new LogFileReader(logFilePath)) { reader.SeekToLastLine(); while (true) { while (reader.Read() is string log) { observer.OnNext(log); } await Task.Delay(500, cancellationToken).ConfigureAwait(false); } } }) .Merge( Observable.FromEventPattern( x => this._process.Exited += x, x => { if (this._process != null) { this._process.Exited -= x; } } ) .SelectMany(_ => s_processExitedObservable) ); this._logStream = Observable.Create <string>(observer => (this._process.HasExited ? s_processExitedObservable : logObservable).Subscribe(observer)); }
public Task <CommandResult> ExecuteAsync(bool throwOnFailure = false) { var tcs = new TaskCompletionSource <CommandResult>(); var exeName = Path.GetFileNameWithoutExtension(ExecutablePath); var formattedArgs = ArgumentEscaper.EscapeAndConcatenate(Arguments); var process = new Process() { StartInfo = new ProcessStartInfo() { FileName = ExecutablePath, Arguments = formattedArgs, WorkingDirectory = WorkingDirectory, RedirectStandardError = true, RedirectStandardOutput = true, } }; process.EnableRaisingEvents = true; var stdout = new StringBuilder(); var stderr = new StringBuilder(); process.ErrorDataReceived += (sender, a) => ProcessDataReceived(a, stderr, _standardErrorHandler); process.OutputDataReceived += (sender, a) => ProcessDataReceived(a, stdout, _standardOutputHandler); process.Exited += (sender, a) => { _logger.LogDebug("'{Command} {Arguments}' exited with code {ExitCode}", exeName, formattedArgs, process.ExitCode); if (process.ExitCode != 0 && throwOnFailure) { tcs.TrySetException(new CommandLineException($"Command '{exeName} {formattedArgs}' failed with exit code {process.ExitCode}!")); } else { tcs.TrySetResult(new CommandResult(process.ExitCode, stdout.ToString(), stderr.ToString())); } }; _logger.LogInformation("Running '{Command} {Arguments}'", exeName, formattedArgs); process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); return(tcs.Task); void ProcessDataReceived(DataReceivedEventArgs args, StringBuilder buffer, Action <string> handler) { buffer.AppendLine(args.Data); handler?.Invoke(args.Data); _logger.LogDebug(args.Data); } }
public override bool Execute() { if (string.IsNullOrEmpty(RuleFile) || !File.Exists(RuleFile)) { Log.LogError($"RuleFile '{RuleFile}' does not exist"); return(false); } if (ArtifactDirectory == null || ArtifactDirectory.Length == 0) { Log.LogError($"At least one ArtifactDirectory must exist."); return(false); } var taskAssemblyFolder = Path.GetDirectoryName(GetType().GetTypeInfo().Assembly.Location); var toolPath = Path.Combine(taskAssemblyFolder, "..", "..", ConsoleAppExe); if (!File.Exists(toolPath)) { toolPath = Path.Combine(taskAssemblyFolder, ConsoleAppExe); } var dotnetMuxer = DotNetMuxer.MuxerPathOrDefault(); var arguments = new List <string> { toolPath, "--rule-file", RuleFile, }; foreach (var rule in ExcludedRules ?? Enumerable.Empty <string>()) { arguments.Add("--excluded-rule"); arguments.Add(rule); } arguments.AddRange(ArtifactDirectory); var psi = new ProcessStartInfo { FileName = dotnetMuxer, Arguments = ArgumentEscaper.EscapeAndConcatenate(arguments), }; Log.LogCommandLine($"Executing '{psi.FileName} {psi.Arguments}'"); var process = Process.Start(psi); process.WaitForExit(); return(process.ExitCode == 0); }
public static int Run( string executable, IReadOnlyList <string> args, IReporter reporter, string workingDirectory = null, bool interceptOutput = false) { var arguments = ArgumentEscaper.EscapeAndConcatenate(args); reporter.WriteVerbose(executable + " " + arguments); var startInfo = new ProcessStartInfo { FileName = executable, Arguments = arguments, UseShellExecute = false, RedirectStandardOutput = interceptOutput }; if (workingDirectory != null) { startInfo.WorkingDirectory = workingDirectory; } using var process = Process.Start(startInfo); if (interceptOutput) { string line; while ((line = process.StandardOutput.ReadLine()) != null) { reporter.WriteVerbose(line); } } // Follow precedent set in Razor integration tests and ensure process events and output are complete. // https://github.com/aspnet/Razor/blob/d719920fdcc7d1db3a6f74cd5404d66fa098f057/test/Microsoft.NET.Sdk.Razor.Test/IntegrationTests/MSBuildProcessManager.cs#L91-L102 // Timeout is double how long the inside man waits for the IDocumentProcessor to wrap up. if (!process.WaitForExit((int)(TimeSpan.FromMinutes(2).TotalMilliseconds))) { process.Kill(); // Should be unreachable in almost every case. throw new TimeoutException($"Process {executable} timed out after 2 minutes."); } process.WaitForExit(); return(process.ExitCode); }
private ICommand GetRunCommand() { var globalProperties = new Dictionary <string, string> { { Constants.MSBuildExtensionsPath, AppContext.BaseDirectory } }; if (!string.IsNullOrWhiteSpace(Configuration)) { globalProperties.Add("Configuration", Configuration); } if (!string.IsNullOrWhiteSpace(Framework)) { globalProperties.Add("TargetFramework", Framework); } ProjectInstance projectInstance = new ProjectInstance(Project, globalProperties, null); string runProgram = projectInstance.GetPropertyValue("RunCommand"); if (string.IsNullOrEmpty(runProgram)) { string outputType = projectInstance.GetPropertyValue("OutputType"); throw new GracefulException( string.Format( LocalizableStrings.RunCommandExceptionUnableToRun, "dotnet run", "OutputType", outputType)); } string runArguments = projectInstance.GetPropertyValue("RunArguments"); string runWorkingDirectory = projectInstance.GetPropertyValue("RunWorkingDirectory"); string fullArguments = runArguments; if (_args.Any()) { fullArguments += " " + ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(_args); } CommandSpec commandSpec = new CommandSpec(runProgram, fullArguments, CommandResolutionStrategy.None); return(Command.Create(commandSpec) .WorkingDirectory(runWorkingDirectory)); }
private CommandResult RunProcess(string executable, string[] args, StreamForwarder stdOut, StreamForwarder stdErr) { var psi = new ProcessStartInfo { FileName = executable, Arguments = ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(args), RedirectStandardError = true, RedirectStandardOutput = true }; Log("Executing: ".Bold().Blue() + $"{psi.FileName} {psi.Arguments}"); foreach (var item in Environment) { psi.Environment[item.Key] = item.Value; } if (!string.IsNullOrWhiteSpace(WorkingDirectory)) { psi.WorkingDirectory = WorkingDirectory; Log($"Working directory: {WorkingDirectory}"); } var process = new Process { StartInfo = psi, EnableRaisingEvents = true }; using (process) { process.Start(); var threadOut = stdOut.BeginRead(process.StandardOutput); var threadErr = stdErr.BeginRead(process.StandardError); process.WaitForExit(); Task.WaitAll(threadOut, threadErr); var result = new CommandResult( process.StartInfo, process.ExitCode, stdOut.CapturedOutput, stdErr.CapturedOutput); return(result); } }
private static async Task <string?> GetLatestMsBuildExePathAsync() { var vsWhereExe = Environment.ExpandEnvironmentVariables(@"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe"); var args = new[] { "-latest", "-prerelease", "-products", "*", "-requires", "Microsoft.Component.MSBuild", "-version", "[16.0,]", "-find", @"MSBuild\**\Bin\MSBuild.exe" }; var(exitCode, stdOut, _) = await new ProcessStartInfo(vsWhereExe) { Arguments = ArgumentEscaper.EscapeAndConcatenate(args) }.GetOutputAsync(); if (exitCode == 0 && !string.IsNullOrWhiteSpace(stdOut)) { return(stdOut); } return(null); }
private Process StartLauncher(params string[] args) { var startInfo = new ProcessStartInfo { Arguments = ArgumentEscaper.Escape(args), FileName = "Launcher.exe", RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false }; var proc = Process.Start(startInfo); proc.should_not_be_null(); proc.WaitForExit(); return(proc); }
public CommandSpec Resolve(CommandResolverArguments commandResolverArguments) { if (commandResolverArguments.CommandName == null) { return(null); } if (Path.IsPathRooted(commandResolverArguments.CommandName)) { var escapedArgs = ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart( commandResolverArguments.CommandArguments.OrEmptyIfNull()); return(new CommandSpec(commandResolverArguments.CommandName, escapedArgs)); } return(null); }
private static Command CreateCommand(string path, IEnumerable <string> args) { var psi = new ProcessStartInfo { FileName = path, Arguments = ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(args), UseShellExecute = false }; var _process = new Process { StartInfo = psi }; return(new Command(_process)); }
private ICommand GetRunCommand() { Dictionary <string, string> globalProperties = new Dictionary <string, string>() { { "MSBuildExtensionsPath", AppContext.BaseDirectory } }; if (!string.IsNullOrWhiteSpace(Configuration)) { globalProperties.Add("Configuration", Configuration); } if (!string.IsNullOrWhiteSpace(Framework)) { globalProperties.Add("TargetFramework", Framework); } ProjectInstance projectInstance = new ProjectInstance(Project, globalProperties, null); string runProgram = projectInstance.GetPropertyValue("RunCommand"); if (string.IsNullOrEmpty(runProgram)) { string outputType = projectInstance.GetPropertyValue("OutputType"); throw new GracefulException(string.Join(Environment.NewLine, "Unable to run your project.", "Please ensure you have a runnable project type and ensure 'dotnet run' supports this project.", $"The current OutputType is '{outputType}'.")); } string runArguments = projectInstance.GetPropertyValue("RunArguments"); string runWorkingDirectory = projectInstance.GetPropertyValue("RunWorkingDirectory"); string fullArguments = runArguments; if (_args.Any()) { fullArguments += " " + ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(_args); } CommandSpec commandSpec = new CommandSpec(runProgram, fullArguments, CommandResolutionStrategy.None); return(Command.Create(commandSpec) .WorkingDirectory(runWorkingDirectory)); }
private static async Task <bool> IsGitDiffEmptyAsync(DirectoryInfo outputDirectory) { var gitDiff = new ProcessStartInfo("git") { Arguments = ArgumentEscaper.EscapeAndConcatenate(new[] { "diff", "--exit-code", "--relative", "--summary", "--diff-filter=ACMRTUXB*" }), WorkingDirectory = outputDirectory.FullName }; using var stdout = new StringWriter(); int exitCode = await gitDiff.GetExitCodeAsync(stdout); if (exitCode == 1) { Console.WriteLine(stdout.ToString()); } return(exitCode == 0); }
private ICommand GetRunCommand() { Dictionary <string, string> globalProperties = new Dictionary <string, string>() { { LocalizableStrings.RunCommandMSBuildExtensionsPath, AppContext.BaseDirectory } }; if (!string.IsNullOrWhiteSpace(Configuration)) { globalProperties.Add(LocalizableStrings.RunCommandConfiguration, Configuration); } if (!string.IsNullOrWhiteSpace(Framework)) { globalProperties.Add(LocalizableStrings.RunCommandTargetFramework, Framework); } ProjectInstance projectInstance = new ProjectInstance(Project, globalProperties, null); string runProgram = projectInstance.GetPropertyValue(LocalizableStrings.RunCommandProjectInstance); if (string.IsNullOrEmpty(runProgram)) { string outputType = projectInstance.GetPropertyValue(LocalizableStrings.RunCommandOutputType); throw new GracefulException(string.Join(Environment.NewLine, LocalizableStrings.RunCommandExceptionUnableToRun1, LocalizableStrings.RunCommandExceptionUnableToRun2, $"{LocalizableStrings.RunCommandExceptionUnableToRun3} '{outputType}'.")); } string runArguments = projectInstance.GetPropertyValue(LocalizableStrings.RunCommandRunArguments); string runWorkingDirectory = projectInstance.GetPropertyValue(LocalizableStrings.RunCommandRunWorkingDirectory); string fullArguments = runArguments; if (_args.Any()) { fullArguments += " " + ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(_args); } CommandSpec commandSpec = new CommandSpec(runProgram, fullArguments, CommandResolutionStrategy.None); return(Command.Create(commandSpec) .WorkingDirectory(runWorkingDirectory)); }
public int Execute(bool redirectOutput) { var arguments = ArgumentEscaper.EscapeAndConcatenate(_arguments); var processStartInfo = new ProcessStartInfo { UseShellExecute = false, FileName = _processPath, Arguments = arguments, RedirectStandardOutput = redirectOutput, RedirectStandardError = redirectOutput, }; Log.Debug($"Executing {_processPath}"); Log.Debug($"Arguments: {arguments}"); var process = new Process { StartInfo = processStartInfo }; try { process.Start(); process.WaitForExit(); } catch (Exception e) { Log.Debug(e.ToString()); Log.Error(e.Message); Log.Fatal($"Error executing process {_processPath}"); } if (process.ExitCode == 0) { RedirectOutput(redirectOutput, process, false, _isGenerator, _receiveOutput); } else { RedirectOutput(redirectOutput, process, true, _isGenerator, _receiveOutput); } return(process.ExitCode); }
private int ExecuteScript(ITestOutputHelper output, string script, string[] koreBuildArgs, params string[] commandArgs) { output.WriteLine("Starting in " + WorkingDirectory); var arguments = new List <string>(); string cmd; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { cmd = "cmd.exe"; arguments.Add("/C"); arguments.Add($@".\{script}.cmd"); } else { cmd = "bash"; arguments.Add($"./{script}.sh"); } arguments.AddRange(koreBuildArgs); arguments.AddRange(new[] { "-ToolsSource", _toolsSource, "-Reinstall", }); arguments.AddRange(commandArgs); arguments.Add("/bl:" + _logFile); var psi = new ProcessStartInfo { FileName = cmd, Arguments = ArgumentEscaper.EscapeAndConcatenate(arguments), RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false, WorkingDirectory = WorkingDirectory, }; return(Run(output, psi)); }
public ProcessStartInfo GetProcessStartInfo() { var processInfo = new ProcessStartInfo { FileName = GetHostExeName(), Arguments = ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(_allArgs), UseShellExecute = false }; if (_environmentVariables != null) { foreach (var entry in _environmentVariables) { processInfo.Environment[entry.Key] = entry.Value; } } return(processInfo); }
private async Task Nuget(params string[] args) { var pInfo = new ProcessStartInfo { Arguments = ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(args), FileName = await GetNugetExePath() }; Console.WriteLine("command: ".Bold().Blue() + pInfo.FileName); Console.WriteLine("arguments: ".Bold().Blue() + pInfo.Arguments); var p = Process.Start(pInfo); p.WaitForExit(); if (p.ExitCode != 0) { throw new InvalidOperationException("nuget.exe command returned non-zero exit code: " + p.ExitCode); } }
private static VsInstallation[] GetInstallations(List <string> args, TaskLoggingHelper log) { args.Add("-format"); args.Add("json"); var vswhere = GetVsWherePath(); var process = new Process { StartInfo = { FileName = vswhere, Arguments = ArgumentEscaper.EscapeAndConcatenate(args), RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true, } }; log.LogCommandLine(process.StartInfo.FileName + " " + process.StartInfo.Arguments); try { process.Start(); process.WaitForExit(); } catch (Exception ex) { log.LogError("vswhere failed." + ex.Message); return(Array.Empty <VsInstallation>()); } var output = process.StandardOutput.ReadToEnd(); if (process.ExitCode != 0) { log.LogMessage(MessageImportance.Low, "vswhere output = " + output); log.LogError("vswhere failed."); return(Array.Empty <VsInstallation>()); } return(JsonConvert.DeserializeObject <VsInstallation[]>(output)); }
void ExecuteDeploymentProvider(IConsole console) { var providerToExecute = Path.Combine( ToolsDirectory, string.Concat("dotnet-deploy-", Provider) ); var psi = new ProcessStartInfo { FileName = providerToExecute, Arguments = ArgumentEscaper.EscapeAndConcatenate(RemainingArgs), RedirectStandardOutput = true, RedirectStandardError = true, }; var process = Process.Start(psi); process.WaitForExit(); console.Out.WriteLine(process.StandardOutput.ReadToEnd()); }
private ICommand GetRunCommand() { var globalProperties = new Dictionary <string, string> { { Constants.MSBuildExtensionsPath, AppContext.BaseDirectory } }; if (!string.IsNullOrWhiteSpace(Configuration)) { globalProperties.Add("Configuration", Configuration); } if (!string.IsNullOrWhiteSpace(Framework)) { globalProperties.Add("TargetFramework", Framework); } Project project = new Project(Project, globalProperties, null); string runProgram = project.GetPropertyValue("RunCommand"); if (string.IsNullOrEmpty(runProgram)) { ThrowUnableToRunError(project); } string runArguments = project.GetPropertyValue("RunArguments"); string runWorkingDirectory = project.GetPropertyValue("RunWorkingDirectory"); string fullArguments = runArguments; if (_args.Any()) { fullArguments += " " + ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(_args); } CommandSpec commandSpec = new CommandSpec(runProgram, fullArguments, CommandResolutionStrategy.None); return(Command.Create(commandSpec) .WorkingDirectory(runWorkingDirectory)); }
public void Start() { if (_process != null) { throw new InvalidOperationException("Already started"); } _process = new Process { EnableRaisingEvents = true, StartInfo = new ProcessStartInfo { UseShellExecute = false, FileName = _spec.Executable, WorkingDirectory = _spec.WorkingDirectory, Arguments = ArgumentEscaper.EscapeAndConcatenate(_spec.Arguments), RedirectStandardOutput = true, RedirectStandardError = true, Environment = { ["DOTNET_SKIP_FIRST_TIME_EXPERIENCE"] = "true" } } }; foreach (var env in _spec.EnvironmentVariables) { _process.StartInfo.EnvironmentVariables[env.Key] = env.Value; } _process.OutputDataReceived += OnData; _process.ErrorDataReceived += OnData; _process.Exited += OnExit; WriteTestOutput($"{DateTime.Now}: starting process: '{_process.StartInfo.FileName} {_process.StartInfo.Arguments}'"); _process.Start(); _started = true; _process.BeginErrorReadLine(); _process.BeginOutputReadLine(); WriteTestOutput($"{DateTime.Now}: process started: '{_process.StartInfo.FileName} {_process.StartInfo.Arguments}'"); }
public static int Main(string[] args) { var app = new CommandLineApplication { AllowArgumentSeparator = true, UnrecognizedArgumentHandling = UnrecognizedArgumentHandling.StopParsingAndCollect, }; var showMilliseconds = app.Option <int>("-m", "Show time in milliseconds", CommandOptionType.NoValue); app.OnExecute(() => { var timer = Stopwatch.StartNew(); if (app.RemainingArguments != null && app.RemainingArguments.Count > 0) { var process = new Process { StartInfo = { FileName = app.RemainingArguments[0], Arguments = ArgumentEscaper.EscapeAndConcatenate(app.RemainingArguments.Skip(1)), } }; process.Start(); process.WaitForExit(); } timer.Stop(); if (showMilliseconds.HasValue()) { Console.WriteLine($"Time = {timer.Elapsed.TotalMilliseconds} ms"); } else { Console.WriteLine($"Time = {timer.Elapsed.TotalSeconds}s"); } }); return(app.Execute(args)); }
public static string StartServerIfNotStarted(IConsole console, string ffmpegPath = null, string ffprobePath = null) { if (WebServerUtils.IsServerAlive()) { console.WriteLine("Server is alive, getting its port..."); var port = WebServerUtils.GetServerPort(); if (port.HasValue) { return(WebServerUtils.GetWebServerIpAddress(port.Value)); } console.WriteLine("Couldn't retrieve the server port"); return(null); } var dir = Directory.GetCurrentDirectory(); var path = Path.Combine(dir, "Server", WebServerUtils.ServerProcessName); console.WriteLine($"Trying to start process located in = {path}"); //#if DEBUG // path = "E:\\Proyectos\\CastIt\\CastIt.Server\\bin\\Debug\\net5.0\\CastIt.Server.exe"; //#endif console.WriteLine("Web server is not running, starting it..."); var openPort = WebServerUtils.GetOpenPort(); var args = new[] { AppWebServerConstants.PortArgument, $"{openPort}", AppWebServerConstants.FFmpegPathArgument, ffmpegPath, AppWebServerConstants.FFprobePathArgument, ffprobePath }; var escapedArgs = ArgumentEscaper.EscapeAndConcatenate(args); bool started = WebServerUtils.StartServer(escapedArgs, path); if (started) { return(WebServerUtils.GetWebServerIpAddress(openPort)); } console.WriteLine("Couldn't start the web server"); return(null); }
public static int Main(string[] args) { var processInfo = new ProcessStartInfo() { FileName = Path.Combine(Path.GetDirectoryName(typeof(Program).GetTypeInfo().Assembly.Location), "tool", "package_tool"), Arguments = ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(args), UseShellExecute = false }; Console.WriteLine($"dotnet-deb-tool: executing - {processInfo.FileName} {processInfo.Arguments}"); var process = new Process() { StartInfo = processInfo }; process.Start(); process.WaitForExit(); return(process.ExitCode); }