public void AddDirectory(string dir) { if (string.IsNullOrEmpty(dir)) { return; } dir = Path.GetFullPath(dir); if (!_dirs.Contains(dir)) { Console.WriteLine($"Directory '{dir.Bold()}' added to assembly search paths."); _dirs.Add(dir); } }
private string SelectCsProj() { var csprojFiles = FileSystem.Directory.GetFiles(".", "*.csproj"); if (csprojFiles.Length == 1) { return(csprojFiles.First()); } if (csprojFiles.Length == 0) { AnsiConsole.Write(new Markup($"[bold red]Can't find a project file in current directory![/]")); AnsiConsole.WriteLine(); AnsiConsole.Write(new Markup($"[bold red]Please run Sergen in a folder that contains the Asp.Net Core project.[/]")); AnsiConsole.WriteLine(); return(null); } AnsiConsole.WriteLine(); AnsiConsole.Write(new Spectre.Console.Rule($"[bold orange1]Please select an Asp.Net Core project file[/]") { Alignment = Justify.Left }); AnsiConsole.WriteLine(); var selections = new SelectionPrompt <string>() .PageSize(10) .MoreChoicesText("[grey](Move up and down to reveal more project files)[/]") .AddChoices(csprojFiles); return(AnsiConsole.Prompt(selections)); }
public static void Main() { // Render a bar chart AnsiConsole.WriteLine(); Render("Fruits per month", new BarChart() .Width(60) .Label("[green bold underline]Number of fruits[/]") .CenterLabel() .AddItem("Apple", 12, Color.Yellow) .AddItem("Orange", 54, Color.Green) .AddItem("Banana", 33, Color.Red)); // Render a breakdown chart AnsiConsole.WriteLine(); Render("Languages used", new BreakdownChart() .FullSize() .Width(60) .ShowPercentage() .AddItem("SCSS", 37, Color.Red) .AddItem("HTML", 28.3, Color.Blue) .AddItem("C#", 22.6, Color.Green) .AddItem("JavaScript", 6, Color.Yellow) .AddItem("Ruby", 6, Color.LightGreen) .AddItem("Shell", 0.1, Color.Aqua)); }
private static string AskFruit() { AnsiConsole.WriteLine(); AnsiConsole.Render(new Rule("[yellow]Lists[/]").RuleStyle("grey").LeftAligned()); var favorites = AnsiConsole.Prompt( new MultiSelectionPrompt <string>() .PageSize(10) .Title("What are your [green]favorite fruits[/]?") .AddChoices(new[] { "Apple", "Apricot", "Avocado", "Banana", "Blackcurrant", "Blueberry", "Cherry", "Cloudberry", "Cocunut", "Date", "Dragonfruit", "Durian", "Egg plant", "Elderberry", "Fig", "Grape", "Guava", "Honeyberry", "Jackfruit", "Jambul", "Kiwano", "Kiwifruit", "Lime", "Lylo", "Lychee", "Melon", "Mulberry", "Nectarine", "Orange", "Olive" })); var fruit = favorites.Count == 1 ? favorites[0] : null; if (string.IsNullOrWhiteSpace(fruit)) { fruit = AnsiConsole.Prompt( new SelectionPrompt <string>() .Title("Ok, but if you could only choose [green]one[/]?") .AddChoices(favorites)); } AnsiConsole.MarkupLine("Your selected: [yellow]{0}[/]", fruit); return(fruit); }
public override int Execute([NotNull] CommandContext context, [NotNull] Settings settings) { try { AnsiConsole.MarkupLine("[cyan]-=[[ EscapeFromTarkov-Trainer Universal Installer ]]=-[/]"); AnsiConsole.WriteLine(); var installation = Installation.GetTargetInstallation(settings.Path, "Please select from where to uninstall the trainer"); if (installation == null) { return((int)ExitCode.NoInstallationFound); } AnsiConsole.MarkupLine($"Target [green]EscapeFromTarkov ({installation.Version})[/] in [blue]{installation.Location}[/]."); if (!RemoveFile(Path.Combine(installation.Managed, "NLog.EFT.Trainer.dll"))) { return((int)ExitCode.RemoveDllFailed); } if (!RemoveFile(Path.Combine(installation.Data, "outline"))) { return((int)ExitCode.RemoveOutlineFailed); } RemoveOrPatchConfiguration(installation); } catch (Exception ex) { AnsiConsole.MarkupLine($"[red]Error: {ex.Message}. Please file an issue here : https://github.com/sailro/EscapeFromTarkov-Trainer/issues [/]"); return((int)ExitCode.Failure); } return((int)ExitCode.Success); }
private static void Render(IRenderable canvas, string title) { AnsiConsole.WriteLine(); AnsiConsole.Render(new Rule($"[yellow]{title}[/]").LeftAligned().RuleStyle("grey")); AnsiConsole.WriteLine(); AnsiConsole.Render(canvas); }
/// <summary> /// A main function can also take <see cref="CancellationToken"/> which is hooked up to support termination (e.g CTRL+C) /// </summary> /// <param name="branch">The stack's branch we are targeting the generation for</param> /// <param name="interactive">Run the generation interactively, this will ignore all flags</param> /// <param name="download">Whether to download the specs or use an already downloaded copy</param> /// <param name="includeHighLevel">Also generate the high level client (NEST)</param> /// <param name="skipGenerate">Only download the specs, skip all code generation</param> /// <param name="token"></param> /// <returns></returns> private static async Task <int> Main( string branch, bool interactive = false, bool download = false, bool includeHighLevel = false, bool skipGenerate = false , CancellationToken token = default) { Interactive = interactive; try { if (string.IsNullOrEmpty(branch)) { throw new ArgumentException("--branch can not be null"); } await Generate(download, branch, includeHighLevel, skipGenerate, token); } catch (OperationCanceledException) { AnsiConsole.WriteLine(); AnsiConsole.Render(new Rule("[b white on orange4_1] Cancelled [/]").LeftAligned()); AnsiConsole.WriteLine(); return(1); } catch (Exception ex) { AnsiConsole.WriteLine(); AnsiConsole.Render(new Rule("[b white on darkred] Exception [/]") { Alignment = Justify.Left, }); AnsiConsole.WriteLine(); AnsiConsole.WriteException(ex); return(1); } return(0); }
public static void Draw <T>(this T[,] array, Func <T, string> getDisplayText) { var borderLength = array.GetLength(0); var stringBuilder = new StringBuilder(); void DrawBorder() { stringBuilder.AppendLine(new string(Enumerable.Repeat('-', borderLength) .ToArray())); } DrawBorder(); for (var y = 0; y < array.GetLength(1); y++) { for (var x = 0; x < borderLength; x++) { stringBuilder.Append(getDisplayText(array[x, y])); } stringBuilder.Append(Environment.NewLine); } DrawBorder(); AnsiConsole.WriteLine(stringBuilder.ToString()); }
public void ListShards(IProjectionStore store) { var projections = store.Shards.Select(x => x.Source).Distinct(); if (projections.IsEmpty()) { AnsiConsole.Markup("[gray]No projections in this store.[/]"); AnsiConsole.WriteLine(); return; } var table = new Table(); table.AddColumn("Projection Name"); table.AddColumn("Class"); table.AddColumn("Shards"); table.AddColumn("Lifecycle"); foreach (var projection in projections) { var shards = store.Shards.Where(x => x.Source == projection).Select(x => x.Name.Identity).Join(", "); table.AddRow(projection.ProjectionName, projection.GetType().FullNameInCode(), shards, projection.Lifecycle.ToString()); } AnsiConsole.Render(table); AnsiConsole.WriteLine(); }
private static async Task Main(string[] args) { AnsiConsole.WriteLine(string.Join(", ", args)); const string parent = ".."; string production = Debugger.IsAttached ? Path.Combine(parent, parent, parent, parent, "F0.Talks.MutationTesting", "Mathematics", "Calculator.cs") : Path.Combine(parent, "F0.Talks.MutationTesting", "Mathematics", "Calculator.cs"); string test = Debugger.IsAttached ? Path.Combine(parent, parent, parent, parent, "F0.Talks.MutationTesting.Tests", "Mathematics", "CalculatorTests.cs") : Path.Combine(parent, "F0.Talks.MutationTesting.Tests", "Mathematics", "CalculatorTests.cs"); if (!File.Exists(production) || !File.Exists(test)) { production = Path.Combine(parent, "demo", "F0.Talks.MutationTesting", "Mathematics", "Calculator.cs"); test = Path.Combine(parent, "demo", "F0.Talks.MutationTesting.Tests", "Mathematics", "CalculatorTests.cs"); } Source source = await Source.CreateAsync(production, test); Compiler compiler = await Compiler.CreateAsync(source); await Runner.RunAsync(source, compiler); }
public async Task Run(string[] args) { AnsiConsoleHelper.TitleRule(Sayings.Affirmative().EscapeMarkup(), "gold3_1"); AnsiConsole.WriteLine(); await _rootCommand.InvokeAsync(args); }
public override int Execute([NotNull] CommandContext context, [NotNull] Settings settings) { AnsiConsole.WriteLine(nameof(RepeatedPrintCmd)); AnsiConsole.WriteLine($"Message: {settings.Message}"); AnsiConsole.WriteLine($"Repeat: {settings.Repeat}"); return(0); }
private void WriteLine(string message) { lock (_lockObj) { _console.WriteLine(message); } }
public static void Main() { var items = new[] { Create("Ascii", Border.Ascii), Create("Ascii2", Border.Ascii2), Create("AsciiDoubleHead", Border.AsciiDoubleHead), Create("Horizontal", Border.Horizontal), Create("Simple", Border.Simple), Create("SimpleHeavy", Border.SimpleHeavy), Create("Minimal", Border.Minimal), Create("MinimalHeavyHead", Border.MinimalHeavyHead), Create("MinimalDoubleHead", Border.MinimalDoubleHead), Create("Square", Border.Square), Create("Rounded", Border.Rounded), Create("Heavy", Border.Heavy), Create("HeavyEdge", Border.HeavyEdge), Create("HeavyHead", Border.HeavyHead), Create("Double", Border.Double), Create("DoubleEdge", Border.DoubleEdge), }; AnsiConsole.WriteLine(); AnsiConsole.Render(new Columns(items).Collapse()); }
private static void BasicExceptionWriting(Exception ex) { AnsiConsole.WriteLine(); AnsiConsole.MarkupLine("[underline green]Basic exception writing :[/]"); AnsiConsole.WriteException(ex); }
public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { if (IsEnabled(logLevel)) { _outConsole.WriteLine(string.Format("{0}: {1}", Caption(logLevel), formatter(state, exception))); } }
public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func <object, Exception, string> formatter) { if (IsEnabled(logLevel)) { _outConsole.WriteLine($"[{_loggerName}] {Caption(logLevel)}: {formatter(state, exception)}"); } }
public void DisplayRebuildIsComplete() { AnsiConsole.Markup("[green]Projection Rebuild complete![/]"); AnsiConsole.WriteLine(); AnsiConsole.WriteLine(); AnsiConsole.WriteLine(); }
public override int Execute(CommandContext context, ConfigureCiSettings settings) { var profilerEnvironmentVariables = Utils.GetProfilerEnvironmentVariables( ApplicationContext.RunnerFolder, ApplicationContext.Platform, settings); if (profilerEnvironmentVariables == null) { return(1); } // Enable CI Visibility mode profilerEnvironmentVariables[Configuration.ConfigurationKeys.CIVisibility.Enabled] = "1"; if (!TryExtractCiName(settings, out var ciName)) { return(1); } AnsiConsole.WriteLine("Setting up the environment variables."); if (!CIConfiguration.SetupCIEnvironmentVariables(profilerEnvironmentVariables, ciName)) { return(1); } return(0); }
static int RunListAndReturnExitCode(ListOptions options) { AnsiConsole.WriteLine("Fetching versions from builder.blender.org..."); AnsiConsole.WriteLine(); var client = new BlenderOrgClient(); var result = client.GetAvailableVersions().GetAwaiter().GetResult().ToList(); if (!string.IsNullOrEmpty(options.Branch)) { result = result.Where(x => x.Tag == options.Branch).ToList(); } if (!string.IsNullOrEmpty(options.OperatingSystem)) { result = result.Where(x => x.OperatingSystem == options.OperatingSystem).ToList(); } var table = new Table(); table.AddColumns("OS", "Variation", "Version", "Arch", "Size", "Built On"); foreach (var res in result) { AddVersionLine(table, res); } AnsiConsole.Render(table); return(0); }
private int List(Settings settings) { var examples = _finder.FindExamples(); if (examples.Count == 0) { AnsiConsole.Markup("[yellow]No examples could be found.[/]"); return(0); } AnsiConsole.WriteLine(); var rows = new Grid().Collapse(); rows.AddColumn(); foreach (var group in examples.GroupBy(ex => ex.Group)) { rows.AddRow(CreateTable(settings, group.Key, group)); rows.AddEmptyRow(); } AnsiConsole.Render(rows); AnsiConsole.MarkupLine("Type [blue]dotnet example --help[/] for help"); return(0); }
private static void PrintRoot(KnowledgeManagementContext db, Skill rootSkill) { List <int> childSkills = RecursiveSearch(db, new List <int> { rootSkill.Id }) .Select(s => s.Id) .ToList(); List <Profile> profiles = db.Competency .Include(c => c.OwnerEntity) .Where(c => childSkills.Contains(c.Skill)) .Select(c => c.OwnerEntity) .ToList() .DistinctBy(p => p.Id) .ToList(); AnsiConsole.WriteLine($"Second level skill: {rootSkill.Id}. {rootSkill.Name_RU}, Child skills: {childSkills.Count}, Child profiles: {profiles.Count}"); var table = new Table(); table.AddColumn(new TableColumn("[u]Id[/]")); table.AddColumn(new TableColumn("[u]Title[/]")); table.AddColumn(new TableColumn("[u]Price[/]")); foreach (Profile user in profiles) { table.AddRow(user.Id.ToString(), user.Title ?? user.Title_RU, user.Price.ToString()); } AnsiConsole.Render(table); }
public void WriteLine(string message) { lock (_lock) { _console.WriteLine(message); } }
private const int ResultsPerPage = 200; // chosen arbitrarily; higher numbers work too /// <summary> /// Get all projects from the ShapeYourCity API. /// </summary> /// <returns>An async enumerable of projects (because the API is paginated)</returns> public static async IAsyncEnumerable <Project> GetAllProjects(string jwt, bool useCache = false) { IAsyncPolicy <Projects> cachePolicy = useCache ? Policy.CacheAsync <Projects>(new CacheManager <Projects>(), TimeSpan.FromHours(1)) : Policy.NoOpAsync <Projects>(); var client = new HttpClient(); string startUrl = $"https://shapeyourcity.ca/api/v2/projects?per_page={ResultsPerPage}"; string?next = startUrl; int pageCount = 0; // loop over result pages while (next != null) { HttpRequestMessage message = new(HttpMethod.Get, next); message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwt); var deserializedResponse = await cachePolicy.ExecuteAsync(async context => { var response = await Policy.Handle <Exception>().RetryAsync(3).ExecuteAsync(async() => await client.SendAsync(message)); return(JsonSerializer.Deserialize <Projects>(await response.Content.ReadAsStringAsync()) ?? new Projects()); }, new Context(next)); if (deserializedResponse?.data is not null) { AnsiConsole.WriteLine($"Retrieved page {++pageCount} ({deserializedResponse.data.Count()} items)"); foreach (var item in deserializedResponse?.data ?? Enumerable.Empty <Project>()) { yield return(item); } next = deserializedResponse?.links?.next; } } }
static int Main(string[] args) { var rootCommand = new RootCommand("CLI for executing various actions against elmah.io") { new Option <bool>("--nologo", "Doesn't display the startup banner or the copyright message"), }; rootCommand.AddCommand(ClearCommand.Create()); rootCommand.AddCommand(DataloaderCommand.Create()); rootCommand.AddCommand(DeploymentCommand.Create()); rootCommand.AddCommand(ExportCommand.Create()); rootCommand.AddCommand(LogCommand.Create()); rootCommand.AddCommand(SourceMapCommand.Create()); rootCommand.AddCommand(TailCommand.Create()); if (args == null || args.All(arg => arg != "--nologo")) { AnsiConsole.Write(new FigletText("elmah.io") .LeftAligned() .Color(new Color(13, 165, 142))); AnsiConsole.MarkupLine("[yellow]Copyright (C)[/] [rgb(13,165,142)]elmah.io[/]. All rights reserved."); } args = args.Where(arg => arg != "--nologo").ToArray(); AnsiConsole.WriteLine(); return(rootCommand.InvokeAsync(args).Result); }
public bool List(ProjectInformation project) { var result = FindProgram(project); if (result == null) { return(false); } var lines = GetLines(result); var table = new Table { ShowHeaders = false, Border = TableBorder.Rounded }; table.AddColumn(new TableColumn(string.Empty) { NoWrap = true }); table.AddColumn(string.Empty); var lineNumber = 1; foreach (var line in lines) { table.AddRow($"[grey]{lineNumber}[/]", line); lineNumber++; } AnsiConsole.WriteLine(); AnsiConsole.Write(table); return(true); }
void DisplayTime(bool utc) { var now = utc ? DateTime.UtcNow : DateTime.Now; AnsiConsole.MarkupLine($":two_o_clock: [silver][[{now:yyyy-MM-dd.}[/][white]{now:HH:mm:ss.fffK}]][/]"); AnsiConsole.WriteLine(); }
void DisplayDate(bool utc) { var now = utc ? DateTime.UtcNow : DateTime.Now; AnsiConsole.MarkupLine($":tear_off_calendar: [silver][[{now:yyyy-MM-dd}]][/]"); AnsiConsole.WriteLine(); }
public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { if (IsEnabled(logLevel)) { _outConsole.WriteLine($"[{_loggerName}] {Caption(logLevel)}: {formatter(state, exception)}"); } }
private static async Task <int> RefactorCommand(IHost host, FileInfo solutionPath, string projectName) { return(await AnsiConsole.Progress().AutoClear(false) .Columns(new TaskDescriptionColumn(), new ProgressBarColumn(), new PercentageColumn(), new ElapsedTimeColumn()).StartAsync(async progressContext => { var logger = host.Services.GetRequiredService <ILogger <Program> >(); var progressSubscriber = new AnsiConsoleProgressSubscriber(progressContext); var workspace = CreateWorkspace(progressSubscriber, logger); var(solution, proj) = await OpenSolutionAndProject(solutionPath, projectName, workspace, progressSubscriber, logger); if (proj == null) { return -1; } progressSubscriber.Report( new FindInternalClassesProgress(FindInternalTypesStep.LoadSolution, 100)); var port = host.Services.GetRequiredService <IFindInternalTypesPort>(); var internalSymbols = await port.FindProjClassesWhichCanBeInternalAsync(solution, proj.Id, progressSubscriber, CancellationToken.None); AnsiConsole.WriteLine($"Found {internalSymbols.Count()} public types which can be made internal"); var fix = host.Services.GetRequiredService <IPublicToInternalFixPort>(); var newSolution = await fix.MakePublicTypesInternal(solution, internalSymbols); return workspace.TryApplyChanges(newSolution) ? 0 : -1; })); }