public bool IsGlobalDotNetCakeInstalled(IErrorsAndInfos errorsAndInfos) { vProcessRunner.RunProcess(DotNetExecutableFileName, DotNetToolListArguments, vWorkingFolder, errorsAndInfos); if (errorsAndInfos.AnyErrors()) { return(false); } var line = errorsAndInfos.Infos.FirstOrDefault(l => l.StartsWith(CakeToolId)); return(line?.Substring(CakeToolId.Length).TrimStart().StartsWith(PinnedCakeToolVersion) == true); }
/// <summary> /// Wraps the execution of the process described by <paramref name="startInfo"/> with an instance of <see cref="IConcurrencyService" />. /// </summary> /// <param name="startInfo">Contains the information about the process to start.</param> public async Task ExecuteProcess(ProcessStartInfo startInfo) { _ = startInfo ?? throw new ArgumentNullException(nameof(startInfo)); var token = _executionTokenGenerator.GenerateToken(startInfo); if (await _concurrencyService.TryAcquireLockAsync(token).ConfigureAwait(false)) { _logger.LogDebug("Lock on token {TOKEN} acquired", token); try { _logger.LogDebug("Starting: {FILENAME} {ARGS} with token: {TOKEN}", startInfo.FileName, startInfo.Arguments, token); var exitCode = _processRunner.RunProcess(startInfo); _logger.Log(GetLogLevelForExitCode(exitCode), "Exit code: {EXITCODE}", exitCode); } catch (Exception ex) { _logger.LogError(ex, "An error occurred while executing '{FILENAME} {ARGS}'", startInfo.FileName, startInfo.Arguments); throw; } finally { _logger.LogDebug("Releasing lock on token {TOKEN}", token); await _concurrencyService.ReleaseLockAsync(token).ConfigureAwait(false); _logger.LogDebug("Lock on token {TOKEN} released", token); } } }
public async Task Suspend() { logger.LogDebug("Running `psshutdown` to suspend."); var processRunResult = await processRunner.RunProcess( @"c:\Program Files\PSTools\psshutdown.exe", new[] { "-d", "-t", "5" }); logger.LogDebug($"`psshutdown` completed with exit code {processRunResult.ExitCode}."); if (processRunResult.ExitCode == 0) { return; } var logMessage = new StringBuilder() .AppendLine("Process run failed.") .AppendLine("Standard output:") .AppendLine(processRunResult.StandardOutput) .AppendLine("- - - - - -") .AppendLine("Standard error:") .AppendLine(processRunResult.StandardError) .ToString(); logger.LogError(logMessage); throw new InvalidOperationException($"Process run failed: {processRunResult.ExitCode}") { Data = { ["StandardOutput"] = processRunResult.StandardOutput, ["StandardError"] = processRunResult.StandardError, } }; }
public void Run(MsBuildProperties msBuildProperties) { var processProperties = new ProcessProperties() { Executable = "MSBuild.exe", Arguments = BuildArguments(msBuildProperties) }; _processRunner.RunProcess(processProperties); }
private async Task <bool> UpdateNugetPackagesForProjectAsync(string projectFileFullName, bool yesNo, IErrorsAndInfos errorsAndInfos) { using (SimpleLogger.BeginScope(SimpleLoggingScopeId.Create(nameof(UpdateNugetPackagesForProjectAsync), Guid.NewGuid().ToString()))) { SimpleLogger.LogInformation("Retrieving dependency ids and versions"); var dependencyErrorsAndInfos = new ErrorsAndInfos(); var dependencyIdsAndVersions = await PackageConfigsScanner.DependencyIdsAndVersionsAsync(projectFileFullName.Substring(0, projectFileFullName.LastIndexOf('\\')), true, true, dependencyErrorsAndInfos); SimpleLogger.LogInformation("Retrieving manually updated packages"); var secret = new SecretManuallyUpdatedPackages(); var manuallyUpdatedPackages = await SecretRepository.GetAsync(secret, errorsAndInfos); if (errorsAndInfos.AnyErrors()) { SimpleLogger.LogInformation("Returning false"); return(false); } foreach (var id in dependencyIdsAndVersions.Select(dependencyIdsAndVersion => dependencyIdsAndVersion.Key).Where(id => manuallyUpdatedPackages.All(p => p.Id != id))) { SimpleLogger.LogInformation($"Updating dependency {id}"); var projectFileFolder = new Folder(projectFileFullName.Substring(0, projectFileFullName.LastIndexOf('\\'))); ProcessRunner.RunProcess("dotnet", "remove " + projectFileFullName + " package " + id, projectFileFolder, errorsAndInfos); ProcessRunner.RunProcess("dotnet", "add " + projectFileFullName + " package " + id, projectFileFolder, errorsAndInfos); } SimpleLogger.LogInformation("Retrieving dependency ids and versions once more"); var dependencyIdsAndVersionsAfterUpdate = await PackageConfigsScanner.DependencyIdsAndVersionsAsync(projectFileFullName.Substring(0, projectFileFullName.LastIndexOf('\\')), true, true, dependencyErrorsAndInfos); SimpleLogger.LogInformation("Determining differences"); foreach (var dependencyIdsAndVersion in dependencyIdsAndVersionsAfterUpdate) { var id = dependencyIdsAndVersion.Key; var version = dependencyIdsAndVersion.Value; yesNo = yesNo || !dependencyIdsAndVersions.ContainsKey(id) || version != dependencyIdsAndVersions[id]; } SimpleLogger.LogInformation($"Returning {yesNo}"); return(yesNo); } }
public async Task Start(StartOptions options) { Status = TestStatus.Running; var arguments = new List <string>() { "test", Directory }; if (options.Filter != null) { arguments.Add($"--filter={options.Filter}"); } var processResult = await processRunner.RunProcess("dotnet", arguments); Status = processResult.ExitCode == 0 ? TestStatus.Succeeded : TestStatus.Failed; Output = processResult.Output; }
public void CallCake(string scriptFileFullName, string target, IErrorsAndInfos errorsAndInfos) { if (!File.Exists(scriptFileFullName)) { errorsAndInfos.Errors.Add(string.Format(Properties.Resources.FileNotFound, scriptFileFullName)); return; } var scriptFileFolder = new Folder(scriptFileFullName.Substring(0, scriptFileFullName.LastIndexOf('\\'))); var arguments = "cake \"" + scriptFileFullName + "\""; if (target != "") { arguments = arguments + " --target \"" + target + "\""; } vProcessRunner.RunProcess(DotNetExecutableFileName, arguments, scriptFileFolder, errorsAndInfos); }
public async Task <ValidationResponse> Validate(ValidationRequest validationRequest) { string inputFilePath = Path.Combine(_postedFilesDirectory, validationRequest.SavedFileName); string transformedFileName = Path.GetFileNameWithoutExtension(inputFilePath) + ".transformed.sarif"; string transformedFilePath = Path.Combine(_postedFilesDirectory, transformedFileName); string outputFileName = Path.GetFileNameWithoutExtension(validationRequest.PostedFileName) + ValidationLogSuffix; string outputFilePath = Path.Combine(_postedFilesDirectory, outputFileName); string arguments = $"validate --output \"{outputFilePath}\" --json-schema \"{_schemaFilePath}\" --force --pretty-print --rich-return-code \"{transformedFilePath}\""; ValidationResponse validationResponse; try { string inputText = File.ReadAllText(inputFilePath); string inputVersion = null; // Get the schema version of the unmodified input log using (StringReader reader = new StringReader(inputText)) { // Read the first 100 characters. This avoids the problem of reading a huge line from a minified log. char[] buffer = new char[100]; reader.ReadBlock(buffer, 0, buffer.Length); Match match = Regex.Match(inputText, VersionRegexPattern, RegexOptions.Compiled); if (match.Success) { inputVersion = match.Groups["version"].Value; } } string transformedText; string transformedVersion = null; PrereleaseCompatibilityTransformer.UpdateToCurrentVersion(inputText, Formatting.Indented, out transformedText); // Get the schema version of the transformed log using (StringReader reader = new StringReader(transformedText)) { // We know we have indent-formatted JSON, so read the third line which has the version property. string line = null; for (int i = 0; i < 3; i++) { line = reader.ReadLine(); } Match match = Regex.Match(line, VersionRegexPattern, RegexOptions.Compiled); if (match.Success) { transformedVersion = match.Groups["version"].Value; } } File.WriteAllText(transformedFilePath, transformedText); ProcessResult processResult = await _processRunner.RunProcess(_multitoolExePath, arguments); validationResponse = new ValidationResponse { Message = $"The SARIF validation service received a request to validate \"{validationRequest.PostedFileName}\".", Arguments = arguments, ExitCode = processResult.ExitCode, StandardError = processResult.StandardError, StandardOutput = processResult.StandardOutput, IsTransformed = inputVersion != transformedVersion, TransformedLogContents = transformedText, ResultsLogContents = _fileSystem.ReadAllText(outputFilePath) }; } catch (Exception ex) { validationResponse = new ValidationResponse { ExitCode = int.MaxValue, Message = $"Validation of file {validationRequest.PostedFileName} failed: {ex.Message}" }; } finally { if (_fileSystem.FileExists(outputFilePath)) { _fileSystem.DeleteFile(outputFilePath); } if (_fileSystem.FileExists(transformedFilePath)) { _fileSystem.DeleteFile(transformedFilePath); } } return(validationResponse); }