private void HandleStrykerRunResult(IStrykerInputs inputs, StrykerRunResult result) { var logger = ApplicationLogging.LoggerFactory.CreateLogger <StrykerCli>(); if (double.IsNaN(result.MutationScore)) { logger.LogInformation("Stryker was unable to calculate a mutation score"); } else { logger.LogInformation("The final mutation score is {MutationScore:P2}", result.MutationScore); } if (result.ScoreIsLowerThanThresholdBreak()) { var thresholdBreak = (double)inputs.ValidateAll().Thresholds.Break / 100; logger.LogWarning("Final mutation score is below threshold break. Crashing..."); _console.WriteLine(); _console.MarkupLine($"[Red]The mutation score is lower than the configured break threshold of {thresholdBreak:P0}.[/]"); _console.MarkupLine(" [Red]Looks like you've got some work to do :smiling_face_with_halo:[/]"); ExitCode = ExitCodes.BreakThresholdViolated; } }
public void OnAllMutantsTested(IReadOnlyProjectComponent reportComponent) { var files = reportComponent.GetAllFiles(); if (files.Any()) { // print empty line for readability _console.WriteLine(); _console.WriteLine(); _console.WriteLine("All mutants have been tested, and your mutation score has been calculated"); var table = new Table() .RoundedBorder() .AddColumn("File", c => c.NoWrap()) .AddColumn("% score", c => c.Alignment(Justify.Right).NoWrap()) .AddColumn("# killed", c => c.Alignment(Justify.Right).NoWrap()) .AddColumn("# timeout", c => c.Alignment(Justify.Right).NoWrap()) .AddColumn("# survived", c => c.Alignment(Justify.Right).NoWrap()) .AddColumn("# no cov", c => c.Alignment(Justify.Right).NoWrap()) .AddColumn("# error", c => c.Alignment(Justify.Right).NoWrap()); DisplayComponent(reportComponent, table); foreach (var file in files) { DisplayComponent(file, table); } _console.Write(table); } }
public void OnAllMutantsTested(IReadOnlyProjectComponent reportComponent) { Tree root = null; var stack = new Stack <IHasTreeNodes>(); // setup display handlers reportComponent.DisplayFolder = (IReadOnlyProjectComponent current) => { var name = Path.GetFileName(current.RelativePath); if (root is null) { root = new Tree("All files" + DisplayComponent(current)); stack.Push(root); } else if (!string.IsNullOrWhiteSpace(name)) { stack.Push(stack.Peek().AddNode(name + DisplayComponent(current))); } }; reportComponent.DisplayFile = (IReadOnlyProjectComponent current) => { var name = Path.GetFileName(current.RelativePath); var fileNode = stack.Peek().AddNode(name + DisplayComponent(current)); if (current.FullPath == current.Parent.Children.Last().FullPath) { stack.Pop(); } var totalMutants = current.TotalMutants(); foreach (var mutant in totalMutants) { var status = mutant.ResultStatus switch { MutantStatus.Killed or MutantStatus.Timeout => $"[Green][[{mutant.ResultStatus}]][/]", MutantStatus.NoCoverage => $"[Yellow][[{mutant.ResultStatus}]][/]", _ => $"[Red][[{mutant.ResultStatus}]][/]", }; var mutantNode = fileNode.AddNode(status + $" {mutant.Mutation.DisplayName} on line {mutant.Line}"); mutantNode.AddNode(Markup.Escape($"[-] {mutant.Mutation.OriginalNode}")); mutantNode.AddNode(Markup.Escape($"[+] {mutant.Mutation.ReplacementNode}")); } }; // print empty line for readability _console.WriteLine(); _console.WriteLine(); _console.WriteLine("All mutants have been tested, and your mutation score has been calculated"); // start recursive invocation of handlers reportComponent.Display(); _console.Write(root); }
private static string AskName(IAnsiConsole console) { console.WriteLine(); console.Write(new Rule("[yellow]Strings[/]").RuleStyle("grey").LeftAligned()); var name = console.Ask <string>("What's your [green]name[/]?"); return(name); }
/// <summary> /// Writes the text representation of the specified 32-bit unsigned integer value, /// followed by the current line terminator, to the console. /// </summary> /// <param name="console">The console to write to.</param> /// <param name="provider">An object that supplies culture-specific formatting information.</param> /// <param name="value">The value to write.</param> public static void WriteLine(this IAnsiConsole console, IFormatProvider provider, uint value) { if (console is null) { throw new ArgumentNullException(nameof(console)); } console.WriteLine(value.ToString(provider)); }
public override int Execute([NotNull] CommandContext context, [NotNull] Settings settings) { var projectsToAnalyze = PathUtility.GetProjectPaths(settings.ProjectOrSolutionPath, out var entry); // Remove all projects that we want to skip. projectsToAnalyze.RemoveAll(p => { var projectName = Path.GetFileNameWithoutExtension(p); return(settings.Skip?.Contains(projectName, StringComparer.OrdinalIgnoreCase) ?? false); }); var targetFramework = settings.TargetFramework; var analyzerResults = new List <ProjectAnalyzerResult>(); var projectCache = new HashSet <Project>(new ProjectComparer()); _console.WriteLine(); return(_console.Status().Start($"Analyzing...", ctx => { ctx.Refresh(); _console.MarkupLine($"Analyzing [yellow]{Path.GetFileName(entry)}[/]"); foreach (var projectToAnalyze in projectsToAnalyze) { // Perform a design time build of the project. var buildResult = _builder.Build( projectToAnalyze, targetFramework, settings.Skip, projectCache); // Update the cache of built projects. projectCache.Add(buildResult.Project); foreach (var item in buildResult.Dependencies) { projectCache.Add(item); } // Analyze the project. var analyzeResult = _analyzer.Analyze(buildResult.Project); if (settings.Exclude?.Length > 0) { // Filter packages that should be excluded. analyzeResult = analyzeResult.Filter(settings.Exclude); } analyzerResults.Add(analyzeResult); } // Write the rport to the console _reporter.WriteToConsole(analyzerResults); // Return the correct exit code. return GetExitCode(settings, analyzerResults); })); }
/// <summary> /// Writes the specified string value, followed by the current line terminator, to the console. /// </summary> /// <param name="console">The console to write to.</param> /// <param name="text">The text to write.</param> /// <param name="style">The text style.</param> public static void WriteLine(this IAnsiConsole console, string text, Style style) { if (console is null) { throw new ArgumentNullException(nameof(console)); } console.Write(text, style); console.WriteLine(); }
public void Choose(IAnsiConsole console, int pageSize = 5) { var prompt = new SelectionPrompt <string> { Title = "What is your favorite color?", PageSize = pageSize }.AddChoices("blue", "purple", "red", "orange", "yellow", "green"); var answer = console.Prompt(prompt); console.WriteLine(answer); }
public void ReportFinalState() { _progressBar.Tick(string.Format(LoggingFormat, _numberOfMutantsRan, _mutantsToBeTested, _mutantsKilledCount, _mutantsSurvivedCount, _mutantsTimeoutCount, RemainingTime())); Dispose(); var length = _mutantsToBeTested.ToString().Length; _console.WriteLine(); _console.MarkupLine($"Killed: [Magenta]{_mutantsKilledCount.ToString().PadLeft(length)}[/]"); _console.MarkupLine($"Survived: [Magenta]{_mutantsSurvivedCount.ToString().PadLeft(length)}[/]"); _console.MarkupLine($"Timeout: [Magenta]{_mutantsTimeoutCount.ToString().PadLeft(length)}[/]"); }
public void OnAllMutantsTested(IReadOnlyProjectComponent reportComponent) { var mutationReport = JsonReport.Build(_options, reportComponent); var reportUri = _dashboardClient.PublishReport(mutationReport, _options.ProjectVersion).Result; if (reportUri != null) { if (_options.ReportTypeToOpen == Options.Inputs.ReportType.Dashboard) { _processWrapper.Open(reportUri); } else { _console.Write("[Cyan]Hint: by passing \"--open-report:dashboard or -o:dashboard\" the report will open automatically once Stryker is done.[/]"); } _console.WriteLine(); _console.MarkupLine("[Green]Your report has been uploaded at:[/]"); if (_console.Profile.Capabilities.Links) { // We must print the report path as the link text because on some terminals links might be supported but not actually clickable: https://github.com/spectreconsole/spectre.console/issues/764 _console.MarkupLine($"[Green][link={reportUri}]{reportUri}[/][/]"); } else { _console.MarkupLine($"[Green]{reportUri}[/]"); } _console.MarkupLine("[Green]You can open it in your browser of choice.[/]"); } else { _logger.LogError("Uploading to stryker dashboard failed..."); } _console.WriteLine(); _console.WriteLine(); }
public override int Execute([NotNull] CommandContext context, [NotNull] EmptyCommandSettings settings) { if (context.Remaining.Raw.Count > 0) { _console.WriteLine("# Raw"); foreach (var item in context.Remaining.Raw) { _console.WriteLine(item); } } if (context.Remaining.Parsed.Count > 0) { _console.WriteLine("# Parsed"); foreach (var item in context.Remaining.Parsed) { _console.WriteLine(string.Format("{0}={1}", item.Key, string.Join(",", item.Select(x => x)))); } } return(0); }
private static string AskSport(IAnsiConsole console) { console.WriteLine(); console.Write(new Rule("[yellow]Choices[/]").RuleStyle("grey").LeftAligned()); return(console.Prompt( new TextPrompt <string>("What's your [green]favorite sport[/]?") .InvalidChoiceMessage("[red]That's not a sport![/]") .DefaultValue("Sport?") .AddChoice("Soccer") .AddChoice("Hockey") .AddChoice("Basketball"))); }
/// <summary> /// Writes the specified string value, followed by the /// current line terminator, to the console. /// </summary> /// <param name="console">The console to write to.</param> /// <param name="value">The value to write.</param> public static void WriteLine(this IAnsiConsole console, string value) { if (console is null) { throw new ArgumentNullException(nameof(console)); } if (value != null) { console.Write(value); } console.WriteLine(); }
public void Pull( IAnsiConsole console, CancellationToken cancellationToken, ProjOrRepoKeys projOrRepoKeys, DryRunArgs dryRunArgs, [Option] string?branch, [Option] bool prune = false) { using var repositories = _gitService.GetLocalRepos(projOrRepoKeys); if (dryRunArgs.IsDryRun) { console.WriteLine(); console.WriteLine("dryrun: the following repositories would be pulled"); var records = repositories.OrderBy(r => r.Name); PrintReposTable(AnsiConsole.Console, records); } else { repositories.SafelyForEach( r => _gitService.PullLatest(r, prune, branch), cancellationToken, summarizeErrors: true); } }
public override void Completed(bool clear) { lock (_lock) { if (clear) { _console.Render(_live.RestoreCursor()); } else { _console.WriteLine(); } _console.Cursor.Show(); } }
private string GenerateReport(string template, LibraryDrop libraryDrop) { var inputProcessor = new InputProcessingService(_inputs); TestRunDrop run; try { run = inputProcessor.Process(); } catch (InvalidDataException e) { _errorConsole.WriteLine(e.Message); return(null); } string report = null; _standardConsole.WriteLine(); _standardConsole.MarkupLine("Generating report"); try { var reportGenerator = new ReportGenerator(new LibraryTestRun { Run = run, Library = libraryDrop }); report = reportGenerator.GenerateReport(template ?? Templates.MdMultiReport, out var errors); foreach (var error in errors) { _standardConsole.MarkupLine($"[orange1]{error.Message}[/]"); } _standardConsole.WriteLine(); _standardConsole.MarkupLine("Finished generating report"); } catch (SyntaxException e) { _errorConsole.WriteLine(e.Message); } catch (Exception e) { _errorConsole.WriteLine($"Unexpected error occurred while generating report {e.Message}"); } return(report); }
private static int AskAge(IAnsiConsole console) { console.WriteLine(); console.Write(new Rule("[yellow]Integers[/]").RuleStyle("grey").LeftAligned()); return(console.Prompt( new TextPrompt <int>("How [green]old[/] are you?") .PromptStyle("green") .ValidationErrorMessage("[red]That's not a valid age[/]") .Validate(age => { return age switch { <= 0 => ValidationResult.Error("[red]You must at least be 1 years old[/]"), >= 123 => ValidationResult.Error("[red]You must be younger than the oldest person alive[/]"), _ => ValidationResult.Success(), };
public override async Task <int> ExecuteAsync(CommandContext context, TorrentOptions request) { var cancellationToken = CancellationToken.None; var outputPath = request.Output; if (string.IsNullOrWhiteSpace(outputPath)) { outputPath = _fileSystem.Directory.GetCurrentDirectory(); } if (!_fileSystem.Directory.Exists(outputPath)) { throw new SoddiException($"Output path {outputPath} not found"); } _console.WriteLine("Finding archive files..."); var archiveUrls = await _availableArchiveParser.FindOrPickArchive(request.Archive, request.Pick, cancellationToken); var potentialArchives = new List <string>(); foreach (var archiveUrl in archiveUrls) { potentialArchives.AddRange(new[] { archiveUrl.LongName + ".7z", $"{archiveUrl.LongName}-Badges.7z", $"{archiveUrl.LongName}-Comments.7z", $"{archiveUrl.LongName}-PostHistory.7z", $"{archiveUrl.LongName}-PostLinks.7z", $"{archiveUrl.LongName}-Posts.7z", $"{archiveUrl.LongName}-Tags.7z", $"{archiveUrl.LongName}-Users.7z", $"{archiveUrl.LongName}-Votes.7z" }); } const string Url = "https://archive.org/download/stackexchange/stackexchange_archive.torrent"; await _torrentDownloader.Download(Url, potentialArchives, request.EnablePortForwarding, outputPath, cancellationToken); return(await Task.FromResult(0)); }
/// <inheritdoc /> public async Task WriteOutputAsync(Stream content, IOutputFormatterOptions?options = null, CancellationToken cancellationToken = default) { using var reader = new StreamReader(content); const int BUFFER_LENGTH = 4096; var charsReceived = 0; do { var buffer = new char[BUFFER_LENGTH]; charsReceived = await reader.ReadAsync(buffer.AsMemory(0, buffer.Length), cancellationToken); if (charsReceived == 0) { break; } _ansiConsole.Write(new string(buffer, 0, charsReceived)); } while(charsReceived == BUFFER_LENGTH); _ansiConsole.WriteLine(); }
/// <summary> /// Writes the specified array of Unicode characters, followed by the current /// line terminator, value to the console. /// </summary> /// <param name="console">The console to write to.</param> /// <param name="provider">An object that supplies culture-specific formatting information.</param> /// <param name="value">The value to write.</param> public static void WriteLine(this IAnsiConsole console, IFormatProvider provider, char[] value) { if (console is null) { throw new ArgumentNullException(nameof(console)); } if (value is null) { throw new ArgumentNullException(nameof(value)); } for (var index = 0; index < value.Length; index++) { console.Write(value[index].ToString(provider)); } console.WriteLine(); }
private List <string> MultiPrompt(IAnsiConsole ansiConsole, string prompt) { var answers = new List <string>(); ansiConsole.WriteLine(prompt); while (true) { var textPrompt = new TextPrompt <string>("> ") { AllowEmpty = true }; var answer = ansiConsole.Prompt(textPrompt); if (string.IsNullOrEmpty(answer)) { return(answers); } answers.Add(answer); } }
public void OnAllMutantsTested(IReadOnlyProjectComponent reportComponent) { var mutationReport = JsonReport.Build(_options, reportComponent); var filename = _options.ReportFileName + ".json"; var reportPath = Path.Combine(_options.OutputPath, "reports", filename); var reportUri = "file://" + reportPath.Replace("\\", "/"); WriteReportToJsonFile(reportPath, mutationReport); _console.WriteLine(); _console.MarkupLine("[Green]Your json report has been generated at:[/]"); if (_console.Profile.Capabilities.Links) { // We must print the report path as the link text because on some terminals links might be supported but not actually clickable: https://github.com/spectreconsole/spectre.console/issues/764 _console.MarkupLine($"[Green][link={reportUri}]{reportPath}[/][/]"); } else { _console.MarkupLine($"[Green]{reportUri}[/]"); } }
internal void Run(string title, string template) { WriteHeader(title); WriteInputTable(); var report = GenerateReport(template, GenerateLibraryParameters(title)); if (string.IsNullOrEmpty(report)) { _errorConsole.WriteLine("Error, report generated no content"); Environment.Exit((int)ExitCodes.ReportGenerationError); } var saved = SaveReport(report); if (!saved) { _errorConsole.WriteLine("Error, report unable to be saved"); Environment.Exit((int)ExitCodes.ReportSaveError); } }
public override void Completed(bool clear) { lock (_lock) { if (clear) { _console.Write(_live.RestoreCursor()); } else { if (_live.HasRenderable && _live.DidOverflow) { // Redraw the whole live renderable _console.Write(_live.RestoreCursor()); _live.Overflow = VerticalOverflow.Visible; _console.Write(_live.Target); } _console.WriteLine(); } _console.Cursor.Show(); } }
public void OnAllMutantsTested(IReadOnlyProjectComponent reportComponent) { var mutationReport = JsonReport.Build(_options, reportComponent); var filename = _options.ReportFileName + ".html"; var reportPath = Path.Combine(_options.OutputPath, "reports", filename); reportPath = FilePathUtils.NormalizePathSeparators(reportPath); WriteHtmlReport(reportPath, mutationReport.ToJsonHtmlSafe()); var reportUri = "file://" + reportPath.Replace("\\", "/"); if (_options.ReportTypeToOpen == Options.Inputs.ReportType.Html) { _processWrapper.Open(reportUri); } else { _console.MarkupLine("[Cyan]Hint: by passing \"--open-report or -o\" the report will open automatically once Stryker is done.[/]"); } _console.WriteLine(); _console.MarkupLine("[Green]Your html report has been generated at:[/]"); if (_console.Profile.Capabilities.Links) { // We must print the report path as the link text because on some terminals links might be supported but not actually clickable: https://github.com/spectreconsole/spectre.console/issues/764 _console.MarkupLine($"[Green][link={reportUri}]{reportPath}[/][/]"); } else { _console.MarkupLine($"[Green]{reportUri}[/]"); } _console.MarkupLine("[Green]You can open it in your browser of choice.[/]"); }
public async Task <int> RunAll(IRemainingArguments remaining) { var examples = _finder.FindExamples(); foreach (var(_, first, _, example) in examples.Enumerate()) { if (!first) { _console.WriteLine(); } _console.Write(new Rule($"Example: [silver]{example.Name}[/]").LeftAligned().RuleStyle("grey")); var exitCode = await Run(example.Name, remaining).ConfigureAwait(false); if (exitCode != 0) { _console.MarkupLine($"[red]Error:[/] Example [u]{example.Name}[/] did not return a successful exit code."); return(exitCode); } } return(0); }
public void List() { var examples = _finder.FindExamples(); if (examples.Count == 0) { _console.Markup("[yellow]No examples could be found.[/]"); return; } _console.WriteLine(); var rows = new Grid().Collapse(); rows.AddColumn(); foreach (var group in examples.GroupBy(ex => ex.Group)) { rows.AddRow(CreateTable(group.Key, group)); rows.AddEmptyRow(); } _console.Write(rows); _console.MarkupLine("Type [blue]dotnet example --help[/] for help"); }
private static void WriteError(string message) => StdErr.WriteLine(message, s_ErrorStyle);
private static void WriteMessage(string message) => StdOut.WriteLine(message, s_MessageStyle);
/// <summary> /// Writes the specified markup, followed by the current line terminator, to the console. /// </summary> /// <param name="console">The console to write to.</param> /// <param name="provider">An object that supplies culture-specific formatting information.</param> /// <param name="format">A composite format string.</param> /// <param name="args">An array of objects to write.</param> public static void MarkupLine(this IAnsiConsole console, IFormatProvider provider, string format, params object[] args) { Markup(console, provider, format, args); console.WriteLine(); }