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));
            }
Exemplo n.º 3
0
        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));
        }
Exemplo n.º 4
0
        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);
        }
Exemplo n.º 5
0
        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);
        }
Exemplo n.º 6
0
 private static void Render(IRenderable canvas, string title)
 {
     AnsiConsole.WriteLine();
     AnsiConsole.Render(new Rule($"[yellow]{title}[/]").LeftAligned().RuleStyle("grey"));
     AnsiConsole.WriteLine();
     AnsiConsole.Render(canvas);
 }
Exemplo n.º 7
0
 /// <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());
        }
Exemplo n.º 9
0
        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();
        }
Exemplo n.º 10
0
        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);
        }
Exemplo n.º 11
0
        public async Task Run(string[] args)
        {
            AnsiConsoleHelper.TitleRule(Sayings.Affirmative().EscapeMarkup(), "gold3_1");
            AnsiConsole.WriteLine();

            await _rootCommand.InvokeAsync(args);
        }
Exemplo n.º 12
0
 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);
 }
Exemplo n.º 13
0
 private void WriteLine(string message)
 {
     lock (_lockObj)
     {
         _console.WriteLine(message);
     }
 }
Exemplo n.º 14
0
        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());
        }
Exemplo n.º 15
0
        private static void BasicExceptionWriting(Exception ex)
        {
            AnsiConsole.WriteLine();

            AnsiConsole.MarkupLine("[underline green]Basic exception writing :[/]");
            AnsiConsole.WriteException(ex);
        }
Exemplo n.º 16
0
 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)));
     }
 }
Exemplo n.º 17
0
 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)}");
     }
 }
Exemplo n.º 18
0
 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);
        }
Exemplo n.º 20
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);
        }
Exemplo n.º 21
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);
        }
Exemplo n.º 22
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);
        }
Exemplo n.º 23
0
 public void WriteLine(string message)
 {
     lock (_lock)
     {
         _console.WriteLine(message);
     }
 }
Exemplo n.º 24
0
    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;
            }
        }
    }
Exemplo n.º 25
0
        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);
        }
Exemplo n.º 26
0
    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);
    }
Exemplo n.º 27
0
        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();
        }
Exemplo n.º 28
0
        void DisplayDate(bool utc)
        {
            var now = utc ? DateTime.UtcNow : DateTime.Now;

            AnsiConsole.MarkupLine($":tear_off_calendar: [silver][[{now:yyyy-MM-dd}]][/]");
            AnsiConsole.WriteLine();
        }
Exemplo n.º 29
0
 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)}");
     }
 }
Exemplo n.º 30
0
        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;
            }));
        }