コード例 #1
0
        private bool ReadActiveServices()
        {
            var useForDownload = AnsiConsole.Confirm("Do you want to use pdbMate to add downloads to your usenet client?");

            if (useForDownload)
            {
                var allowedQualities = AnsiConsole.Prompt(
                    new MultiSelectionPrompt <string>()
                    .Title("What [green]video quality[/] do you want to download?")
                    .InstructionsText(
                        "[grey](Press [blue]<space>[/] to toggle a quality, " +
                        "[green]<enter>[/] to accept)[/]")
                    .AddChoices(new[] {
                    "1080p", "2160p"
                }));

                var keepOnlyHighestQuality = AnsiConsole.Confirm("When downloading from usenet, only keep the highest quality of the same release?");
                var downloadFavoriteActors = AnsiConsole.Confirm("Add downloads based on your favorite actors?");
                var downloadFavoriteSites  = AnsiConsole.Confirm("Add downloads based on your favorite sites?");

                if (!downloadFavoriteActors && !downloadFavoriteSites)
                {
                    AnsiConsole.MarkupLine($"[red]You do not want to add downloads based on your [bold]favorite actors OR sites[/] - pdbMate would not add any downloads - let's start from the beginning.[/]");
                    ReadActiveServices();
                }

                appSettings.UsenetDownload.AllowedQualities       = allowedQualities;
                appSettings.UsenetDownload.KeepOnlyHighestQuality = keepOnlyHighestQuality;
                appSettings.UsenetDownload.DownloadFavoriteSites  = downloadFavoriteSites;
                appSettings.UsenetDownload.DownloadFavoriteActors = downloadFavoriteActors;
            }

            return(useForDownload);
        }
        public void Run()
        {
            Console.Clear();

            _context = new ScaffolderContext(_appSettings);

            foreach (var inputCollector in _inputCollectors)
            {
                inputCollector.CollectInput(_context);
            }

            var changes = _outputCollectors
                          .Select(x => x.CollectChanges(_context))
                          .SelectMany(x => x)
                          .Where(x => x != null)
                          .ToList();

            if (ConfirmChanges(changes))
            {
                ApplyChanges(changes);
                Console.WriteLine("Done.");
            }

            if (AnsiConsole.Confirm("Do you want to scaffold something else?", false))
            {
                Run();
            }

            SaveUserAppSettings();
        }
コード例 #3
0
        private void ReadSabnzbd()
        {
            var hostname = AnsiConsole.Prompt(
                new TextPrompt <string>($"Enter [green]hostname[/] for sabnzbd (e.g. localhost):")
                .PromptStyle("green")
                .ValidationErrorMessage("[red]That's not a valid hostname[/]")
                .Validate(hostname =>
            {
                if (hostname.Contains(':'))
                {
                    return(ValidationResult.Error("[red]Do not provide http or the port in the hostname[/]"));
                }

                return(ValidationResult.Success());
            }));

            var useSsl = AnsiConsole.Confirm("Using SSL to connect?");

            hostname = $"http{(useSsl ? "s" : "")}://" + hostname;

            var port = AnsiConsole.Prompt(
                new TextPrompt <int>($"Enter [green]port[/] for sabnzbd (e.g. 8080):")
                .PromptStyle("green")
                .ValidationErrorMessage("[red]That's not a valid port[/]")
                .Validate(port =>
            {
                if (port == 0)
                {
                    return(ValidationResult.Error("[red]Port 0 is not a valid port[/]"));
                }

                return(ValidationResult.Success());
            }));

            hostname = hostname + ":" + port + "/sabnzbd/api";

            var apikey = AnsiConsole.Prompt(
                new TextPrompt <string>($"Enter [green]apikey[/] for sabnzbd:")
                .PromptStyle("green")
                .ValidationErrorMessage("[red]That's not a valid apikey[/]")
                .Validate(apikey =>
            {
                if (apikey.Length != 32)
                {
                    return(ValidationResult.Error("[red]The apikey must be 32 characters long[/]"));
                }

                return(ValidationResult.Success());
            }));

            if (!IsConnectionSabnzbdSuccessful(hostname, apikey))
            {
                AnsiConsole.MarkupLine($"[red]Cound not connect to sabnzbd on url: {hostname} - let's start from the beginning.[/]");
                ReadDownloadClient();
            }

            appSettings.Sabnzbd.Url    = hostname;
            appSettings.Sabnzbd.ApiKey = apikey;
        }
コード例 #4
0
        private void ReadNzbget()
        {
            var hostname = AnsiConsole.Prompt(
                new TextPrompt <string>($"Enter [green]hostname[/] for nzbget (e.g. localhost):")
                .PromptStyle("green")
                .ValidationErrorMessage("[red]That's not a valid hostname[/]")
                .Validate(hostname =>
            {
                if (hostname.Contains(':'))
                {
                    return(ValidationResult.Error("[red]Do not provide http or the port in the hostname[/]"));
                }

                return(ValidationResult.Success());
            }));

            var useSsl = AnsiConsole.Confirm("Using SSL to connect?");

            var port = AnsiConsole.Prompt(
                new TextPrompt <int>($"Enter [green]port[/] for sabnzbd (e.g. 8080):")
                .PromptStyle("green")
                .ValidationErrorMessage("[red]That's not a valid port[/]")
                .Validate(port =>
            {
                if (port == 0)
                {
                    return(ValidationResult.Error("[red]Port 0 is not a valid port[/]"));
                }

                return(ValidationResult.Success());
            }));

            var useAuth = AnsiConsole.Confirm("Do you need to specify username and password for accessing nzbget?");

            var username = "";
            var password = "";

            if (useAuth)
            {
                username = AnsiConsole.Prompt(new TextPrompt <string>($"Enter [green]username[/] for nzbget:")
                                              .PromptStyle("green").AllowEmpty());

                password = AnsiConsole.Prompt(new TextPrompt <string>($"Enter [green]password[/] for nzbget:")
                                              .PromptStyle("green").AllowEmpty());
            }

            if (!IsConnectionNzbgetSuccessful(hostname, port, username, password, useSsl))
            {
                AnsiConsole.MarkupLine($"[red]Cound not connect to nzbget on url: {hostname} - let's start from the beginning.[/]");
                ReadDownloadClient();
            }

            appSettings.Nzbget.Username = username;
            appSettings.Nzbget.Password = password;
            appSettings.Nzbget.Hostname = hostname;
            appSettings.Nzbget.Port     = port;
            appSettings.Nzbget.UseHttps = useSsl;
        }
コード例 #5
0
        public static bool AskConfirmation()
        {
            if (!AnsiConsole.Confirm("Run prompt example?"))
            {
                AnsiConsole.MarkupLine("Ok... :(");
                return(false);
            }

            return(true);
        }
コード例 #6
0
        public void CollectInput(ScaffolderContext context)
        {
            var enableSoftDelete = AnsiConsole.Confirm("Enable soft delete");

            context.Variables.Set(Constants.EnableSoftDelete, enableSoftDelete);

            var enableAuditlogging = AnsiConsole.Confirm("Enable audit logging?");

            context.Variables.Set(Constants.EnableAuditlogging, enableAuditlogging);
        }
 private bool ConfirmChanges(IEnumerable <IChange> changes)
 {
     Console.WriteLine();
     Console.WriteLine("Pending changes:");
     Console.WriteLine();
     foreach (var change in changes
              .GroupBy(x => x.DirectoryAndFileName)
              .Select(x => x.First())
              .OrderBy(x => x.DirectoryAndFileName))
     {
         Console.WriteLine($" - {change.ModificationType}: {Path.GetRelativePath(_appSettings.PathToSolutionRootDirectory, change.DirectoryAndFileName)}");
     }
     Console.WriteLine();
     return(AnsiConsole.Confirm("Apply pending changes?"));
 }
コード例 #8
0
        private static void JournalStart()
        {
            if (!string.IsNullOrWhiteSpace(trackId))
            {
                AnsiConsole.MarkupLine($"You are alredy tracking your journal with the ID '{trackId}'");
                if (!AnsiConsole.Confirm("Do you want to overwrite it?"))
                {
                    return;
                }
            }

            trackId = AnsiConsole.Ask <string>("Please enter your journal id: ");

            HttpClient.DefaultRequestHeaders.Remove(TRACKID_HEADER);
            HttpClient.DefaultRequestHeaders.Add(TRACKID_HEADER, trackId);
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: gmomartins/spectre.console
        public static void Main(string[] args)
        {
            // Check if we can accept key strokes
            if (!AnsiConsole.Capabilities.SupportsInteraction)
            {
                AnsiConsole.MarkupLine("[red]Environment does not support interaction.[/]");
                return;
            }

            // Confirmation
            if (!AnsiConsole.Confirm("Run prompt example?"))
            {
                AnsiConsole.MarkupLine("Ok... :(");
                return;
            }

            // String
            AnsiConsole.WriteLine();
            AnsiConsole.Render(new Rule("[yellow]Strings[/]").RuleStyle("grey").LeftAligned());
            var name = AnsiConsole.Ask <string>("What's your [green]name[/]?");

            // String with choices
            AnsiConsole.WriteLine();
            AnsiConsole.Render(new Rule("[yellow]Choices[/]").RuleStyle("grey").LeftAligned());
            var fruit = AnsiConsole.Prompt(
                new TextPrompt <string>("What's your [green]favorite fruit[/]?")
                .InvalidChoiceMessage("[red]That's not a valid fruit[/]")
                .DefaultValue("Orange")
                .AddChoice("Apple")
                .AddChoice("Banana")
                .AddChoice("Orange"));

            // Integer
            AnsiConsole.WriteLine();
            AnsiConsole.Render(new Rule("[yellow]Integers[/]").RuleStyle("grey").LeftAligned());
            var age = AnsiConsole.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(),
                });
コード例 #10
0
        public List <Player> GetPlayerParticipation(List <Player> players, int blindPrice)
        {
            var smallBlindPrice      = _bettingService.DetermineSmallBlindPrice(blindPrice);
            var participatingPlayers = new List <Player>();

            Console.WriteLine($"Big Blind: {blindPrice} chips");
            Console.WriteLine($"Small Blind: {smallBlindPrice} chips");

            foreach (var player in players)
            {
                if (AnsiConsole.Confirm($"{player.Name} do you want to participate"))
                {
                    participatingPlayers.Add(player);
                }
            }

            return(participatingPlayers);
        }
コード例 #11
0
        public static void CreateNewConfiguration()
        {
            if (ConfigAccess.ReadConfiguration() is not null)
            {
                ShowConfiguration();
                var option = AnsiConsole.Confirm("Desea eliminar la configuración?");
                if (option) ConfigAccess.DeleteConfiguration();
            }
            else
            {
                var color1 = AnsiConsole.Prompt(new SelectionPrompt<string>().Title("Color 1, row 1 table?").AddChoices(Colors));
                var color2 = AnsiConsole.Prompt(new SelectionPrompt<string>().Title("Color 2, row 2 table?").AddChoices(Colors));
                var color3 = AnsiConsole.Prompt(new SelectionPrompt<string>().Title("Color 3, header table?").AddChoices(Colors));
                var salary = AnsiConsole.Ask<int>("Salario minimo");

                ConfigAccess.CreateConfigurations(color1, color2, color3, salary);
            }
        }
コード例 #12
0
        public static Installation?GetTargetInstallation(string?path, string promptTitle)
        {
            var installations = new List <Installation>();

            AnsiConsole
            .Status()
            .Start("Discovering [green]Escape From Tarkov[/] installations...", _ =>
            {
                installations = Installation
                                .DiscoverInstallations()
                                .Distinct()
                                .ToList();
            });

            if (path is not null && Installation.TryDiscoverInstallation(path, out var installation))
            {
                installations.Add(installation);
            }

            installations = installations
                            .Distinct()
                            .OrderBy(i => i.Location)
                            .ToList();

            switch (installations.Count)
            {
            case 0:
                AnsiConsole.MarkupLine("[yellow]No [green]EscapeFromTarkov[/] installation found, please re-run this installer, passing the installation path as argument.[/]");
                return(null);

            case 1:
                var first = installations.First();
                return(AnsiConsole.Confirm($"Continue with [green]EscapeFromTarkov ({first.Version})[/] in [blue]{first.Location}[/] ?") ? first : null);

            default:
                var prompt = new SelectionPrompt <Installation>
                {
                    Converter = i => i.Location,
                    Title     = promptTitle
                };
                prompt.AddChoices(installations);
                return(AnsiConsole.Prompt(prompt));
            }
        }
コード例 #13
0
        public static bool Validate(Manifest.Manifest manifest)
        {
            var toolVersion = manifest?.Check?.ToolVersion ?? "0.1.0";

            Util.Log($"Required Version: {toolVersion}");

            var fileVersion = NuGetVersion.Parse(FileVersionInfo.GetVersionInfo(typeof(ToolInfo).Assembly.Location).FileVersion);

            Util.Log($"Current Version: {fileVersion}");

            if (string.IsNullOrEmpty(toolVersion) || !NuGetVersion.TryParse(toolVersion, out var toolVer) || fileVersion < toolVer)
            {
                Console.WriteLine();
                AnsiConsole.MarkupLine($"[bold red]{Icon.Error} Updating to version {toolVersion} or newer is required:[/]");
                AnsiConsole.MarkupLine($"[blue]  dotnet tool update --global {ToolPackageId}[/]");

                if (Debugger.IsAttached)
                {
                    if (AnsiConsole.Confirm("Mismatched version, continue debugging anyway?"))
                    {
                        return(true);
                    }
                }

                return(false);
            }

            var minSupportedDotNetSdkVersion = Manifest.DotNetSdk.Version6Preview5;

            // Check that we aren't on a manifest that wants too old of dotnet6
            if (manifest?.Check?.DotNet?.Sdks?.Any(dnsdk =>
                                                   NuGetVersion.TryParse(dnsdk.Version, out var dnsdkVersion) && dnsdkVersion < minSupportedDotNetSdkVersion) ?? false)
            {
                Console.WriteLine();
                AnsiConsole.MarkupLine($"[bold red]{Icon.Error} This version of the tool is incompatible with installing an older version of .NET 6[/]");
                return(false);
            }

            return(true);
        }
コード例 #14
0
        private static async Task JournalSee()
        {
            Console.Clear();

            if (string.IsNullOrWhiteSpace(trackId))
            {
                AnsiConsole.MarkupLine("You are not tracking your journal");
                if (AnsiConsole.Confirm("Would you like to start tracking it?"))
                {
                    JournalStart();
                }
                else
                {
                    return;
                }
            }

            var journalRequest = new JournalRequest {
                Id = trackId
            };
            var response = await CalculatorServiceClient.QueryAsync(journalRequest);

            AnsiConsole.MarkupLine($"Operations for the tracking id '{trackId}':");

            var table = new Table();

            table.AddColumn("Operation");
            table.AddColumn("Calculation");
            table.AddColumn("Date");

            foreach (var operation in response.Operations)
            {
                table.AddRow(operation.Operation, operation.Calculation, operation.Date.ToString());
            }

            AnsiConsole.Render(table);
            AnsiConsole.MarkupLine("Press any key to exit");
            Console.ReadKey();
            Console.Clear();
        }
コード例 #15
0
 public Program()
 {
     _client = new HttpClient
     {
         BaseAddress = new Uri("https://www.affirmations.dev/")
     };
     while (true)
     {
         if (!AnsiConsole.Confirm("Need some [bold green]Affirmation[/]?"))
         {
             if (AnsiConsole.Confirm("Do you want to [bold red]quit[/] already?"))
             {
                 return;
             }
             else
             {
                 continue;
             }
         }
         var jsonObject = JsonSerializer.Deserialize <Model>(_client.GetStringAsync("").Result);
         AnsiConsole.Render(new Markup($"[bold red]{jsonObject.affirmation}\n[/]"));
     }
 }
コード例 #16
0
        public static void Main(string[] args)
        {
            // Check if we can accept key strokes
            if (!AnsiConsole.Profile.Capabilities.Interactive)
            {
                AnsiConsole.MarkupLine("[red]Environment does not support interaction.[/]");
                return;
            }

            // Confirmation
            if (!AnsiConsole.Confirm("Run prompt example?"))
            {
                AnsiConsole.MarkupLine("Ok... :(");
                return;
            }

            // Ask the user for some different things
            var name     = AskName();
            var fruit    = AskFruit();
            var sport    = AskSport();
            var age      = AskAge();
            var password = AskPassword();
            var color    = AskColor();

            // Summary
            AnsiConsole.WriteLine();
            AnsiConsole.Render(new Rule("[yellow]Results[/]").RuleStyle("grey").LeftAligned());
            AnsiConsole.Render(new Table().AddColumns("[grey]Question[/]", "[grey]Answer[/]")
                               .RoundedBorder()
                               .BorderColor(Color.Grey)
                               .AddRow("[grey]Name[/]", name)
                               .AddRow("[grey]Favorite fruit[/]", fruit)
                               .AddRow("[grey]Favorite sport[/]", sport)
                               .AddRow("[grey]Age[/]", age.ToString())
                               .AddRow("[grey]Password[/]", password)
                               .AddRow("[grey]Favorite color[/]", string.IsNullOrEmpty(color) ? "Unknown" : color));
        }
コード例 #17
0
        public override async Task <int> ExecuteAsync(CommandContext context, Settings settings)
        {
            try
            {
                AnsiConsole.MarkupLine("[cyan]-=[[ EscapeFromTarkov-Trainer Universal Installer ]]=-[/]");
                AnsiConsole.WriteLine();

                var installation = Installation.GetTargetInstallation(settings.Path, "Please select where to install the trainer");
                if (installation == null)
                {
                    return((int)ExitCode.NoInstallationFound);
                }

                AnsiConsole.MarkupLine($"Target [green]EscapeFromTarkov ({installation.Version})[/] in [blue]{installation.Location}[/].");

                var(compilation, archive) = await GetCompilationAsync(installation, "master");

                if (compilation == null)
                {
                    var branch = settings.Branch ?? installation.Version.ToString();
                    if (!branch.StartsWith("dev-"))
                    {
                        branch = "dev-" + branch;
                    }

                    (compilation, archive) = await GetCompilationAsync(installation, branch);
                }

                if (compilation == null)
                {
                    AnsiConsole.MarkupLine($"[red]Unable to compile trainer for version {installation.Version}. Please file an issue here : https://github.com/sailro/EscapeFromTarkov-Trainer/issues [/]");
                    return((int)ExitCode.CompilationFailed);
                }

                if (installation.UsingSptAki)
                {
                    AnsiConsole.MarkupLine("[yellow]SPT-AKI detected. Please make sure you have run the game at least once before installing the trainer.[/]");
                    AnsiConsole.MarkupLine("[yellow]SPT-AKI is patching binaries during the first run, and we [underline]need[/] to compile against those patched binaries.[/]");
                    AnsiConsole.MarkupLine("[yellow]If you install this trainer on stock binaries, the game will freeze at the startup screen.[/]");

                    if (!AnsiConsole.Confirm("Continue installation (yes I have run the game at least once) ?"))
                    {
                        return((int)ExitCode.Canceled);
                    }
                }

                if (!CreateDll(installation, compilation))
                {
                    return((int)ExitCode.CreateDllFailed);
                }

                if (!CreateOutline(installation, archive !))
                {
                    return((int)ExitCode.CreateOutlineFailed);
                }

                CreateOrPatchConfiguration(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);
        }
コード例 #18
0
 private static bool PromptForConfirmation(string question)
 {
     return(AnsiConsole.Confirm(question));
 }
コード例 #19
0
    private static async Task Main(string[] args)
    {
        // First configure the HttpClient
        // There are many ways to do this, but this sample takes a minimalistic approach.
        // This is just the minimal setup to get things going without exceptions under normal conditions.
        // In a real application, you would use Polly and IHttpClientFactory to add resiliency etc.
        using var http = new HttpClient();

        // From here on out, you can create GW2SDK services, pass the HttpClient and a JSON reader object.
        // The default JSON reader should work fine, but can be replaced with a custom implementation.
        var meta = new MetaQuery(http);

        var build = await AnsiConsole.Status()
                    .StartAsync(
            "Retrieving the current game version...",
            async ctx => await meta.GetBuild()
            );

        AnsiConsole.MarkupLine($"Gw2: [white on dodgerblue2]{build.Value.Id}[/]");

        var metadata = await AnsiConsole.Status()
                       .StartAsync(
            "Retrieving API endpoints...",
            async ctx =>
        {
            var v1 = await meta.GetApiVersion("v1");
            var v2 = await meta.GetApiVersion();
            return(v1: v1.Value, v2: v2.Value);
        }
            );

        var showDisabled = AnsiConsole.Confirm("Show disabled routes?", false);

        var showAuthorized = AnsiConsole.Confirm("Show routes that require an account?");

        var routes = new Table().MinimalBorder()
                     .AddColumn("Route")
                     .AddColumn("Authorization")
                     .AddColumn("Localization");

        foreach (var route in metadata.v1.Routes)
        {
            var pathTemplate = route.Active switch
            {
                false => ":no_entry: [dim bold]{0}[/]",
                true when Routes.IsSupported(route) => ":rocket: [bold blue]{0}[/]",
                _ => ":construction: {0}"
            };

            if (route.Active || showDisabled)
            {
                routes.AddRow(
                    string.Format(pathTemplate, route.Path.EscapeMarkup()),
                    "⸻",
                    route.Multilingual ? string.Join(", ", metadata.v1.Languages) : "⸻"
                    );
            }
        }

        foreach (var route in metadata.v2.Routes)
        {
            if (!showAuthorized && route.RequiresAuthorization)
            {
                continue;
            }

            var pathTemplate = route.Active switch
            {
                false => ":no_entry: [dim]{0}[/]",
                true when Routes.IsSupported(route) => ":rocket: [bold blue]{0}[/]",
                _ => ":construction: {0}"
            };

            if (route.Active || showDisabled)
            {
                routes.AddRow(
                    string.Format(pathTemplate, route.Path.EscapeMarkup()),
                    route.RequiresAuthorization ? "Access token" : "⸻",
                    route.Multilingual ? string.Join(", ", metadata.v2.Languages) : "⸻"
                    );
            }
        }

        var changes = new Table().MinimalBorder().AddColumn("Change").AddColumn("Description");

        foreach (var schema in metadata.v2.SchemaVersions)
        {
            var formatted = DateTimeOffset.Parse(schema.Version).ToString("D");
            changes.AddRow(formatted.EscapeMarkup(), schema.Description.EscapeMarkup());
        }

        AnsiConsole.WriteLine(
            "Highlighted routes are supported by GW2SDK. Dim routes are disabled."
            );
        AnsiConsole.Write(routes);
        AnsiConsole.Write(new Rule("Notable changes").LeftAligned());
        AnsiConsole.Write(changes);
    }
}
コード例 #20
0
ファイル: Program.cs プロジェクト: pdbme/pdbMate
        private static string[] GetArgsByInteractiveMode()
        {
            var argList = new List <string>();

            var action = AnsiConsole.Prompt(
                new SelectionPrompt <string>()
                .Title("Which [green]action[/] do you want to execute?")
                .AddChoices(new[] {
                "rename", "download", "autopilot", "setup", "backfilling"
            }));

            argList.Add(action);

            var isVerbose = AnsiConsole.Confirm("Run action in debug logging mode?");

            if (isVerbose)
            {
                argList.Add("--loglevel");
                argList.Add("d");
            }

            if (action == "rename" || action == "download" || action == "autopilot" || action == "backfilling")
            {
                var isDryRun = AnsiConsole.Confirm("Execute action as dryrun (does not modify anything on disk)?");
                if (isDryRun)
                {
                    argList.Add("--dryrun");
                }
            }

            if (action == "backfilling")
            {
                var doBackfillingForActors = AnsiConsole.Confirm("Do backfilling for all your favorite actors?");
                if (doBackfillingForActors)
                {
                    argList.Add("--actor");
                    argList.Add("0");
                }

                var doBackfillingForSites = AnsiConsole.Confirm("Do backfilling for all your favorite sites?");
                if (doBackfillingForSites)
                {
                    argList.Add("--site");
                    argList.Add("0");
                }

                var daysBack = AnsiConsole.Prompt(
                    new TextPrompt <int>($"Enter the maximum [green]number of days[/] you want to go back and backfill:")
                    .PromptStyle("green")
                    .ValidationErrorMessage("[red]That's not a valid number of days[/]")
                    .Validate(id =>
                {
                    if (id == 0)
                    {
                        return(ValidationResult.Error($"[red]Number of days should be more than 0[/]"));
                    }

                    if (id > 1800)
                    {
                        return(ValidationResult.Error($"[red]Number of days should be less than 1800[/]"));
                    }

                    return(ValidationResult.Success());
                }));
                argList.Add("--daysback");
                argList.Add(daysBack.ToString());

                if (!doBackfillingForActors && !doBackfillingForSites)
                {
                    var siteId = AnsiConsole.Prompt(
                        new TextPrompt <int>($"Enter [green]site id[/] you want to backfill (enter 0 to skip and continue with an actor id):")
                        .PromptStyle("green")
                        .ValidationErrorMessage("[red]That's not a valid site id[/]")
                        .Validate(id =>
                    {
                        if (id < 0)
                        {
                            return(ValidationResult.Error($"[red]Id {id} is not known[/]"));
                        }

                        return(ValidationResult.Success());
                    }));
                    if (siteId > 0)
                    {
                        argList.Add("--site");
                        argList.Add(siteId.ToString());
                    }
                    else
                    {
                        var actorId = AnsiConsole.Prompt(
                            new TextPrompt <int>($"Enter [green]actor id[/] you want to backfill:")
                            .PromptStyle("green")
                            .ValidationErrorMessage("[red]That's not a valid actor id[/]")
                            .Validate(id =>
                        {
                            if (id == 0)
                            {
                                return(ValidationResult.Error($"[red]Id {id} is not known[/]"));
                            }

                            return(ValidationResult.Success());
                        }));
                        argList.Add("--actor");
                        argList.Add(actorId.ToString());
                    }
                }
            }

            return(argList.ToArray());
        }
コード例 #21
0
        public override async Task <int> ExecuteAsync(CommandContext context, CheckSettings settings)
        {
            Util.Verbose = settings.Verbose;
            Util.CI      = settings.CI;
            if (settings.CI)
            {
                settings.NonInteractive = true;
            }

            Console.Title = ToolInfo.ToolName;

            AnsiConsole.Render(
                new FigletText(".NET MAUI").LeftAligned().Color(Color.Green));

            AnsiConsole.MarkupLine($"[underline bold green]{Icon.Ambulance} {ToolInfo.ToolName} {Icon.Recommend}[/]");
            AnsiConsole.Render(new Rule());

            AnsiConsole.MarkupLine("This tool will attempt to evaluate your .NET MAUI development environment.");
            AnsiConsole.MarkupLine("If problems are detected, this tool may offer the option to try and fix them for you, or suggest a way to fix them yourself.");
            AnsiConsole.WriteLine();
            AnsiConsole.MarkupLine("Thanks for choosing .NET MAUI!");
            AnsiConsole.Render(new Rule());

            if (!Util.IsAdmin() && Util.IsWindows)
            {
                var suTxt = Util.IsWindows ? "Administrator" : "Superuser (su)";

                AnsiConsole.MarkupLine($"[bold red]{Icon.Bell} {suTxt} is required to fix most issues.  Consider exiting and running the tool with {suTxt} permissions.[/]");

                AnsiConsole.Render(new Rule());

                if (!settings.NonInteractive)
                {
                    if (!AnsiConsole.Confirm("Would you still like to continue?", false))
                    {
                        return(1);
                    }
                }
            }

            var cts = new System.Threading.CancellationTokenSource();

            var checkupStatus = new Dictionary <string, Models.Status>();
            var sharedState   = new SharedState();

            var results       = new Dictionary <string, DiagnosticResult>();
            var consoleStatus = AnsiConsole.Status();

            var skippedChecks = new List <string>();

            AnsiConsole.Markup($"[bold blue]{Icon.Thinking} Synchronizing configuration...[/]");

            var manifest = await ToolInfo.LoadManifest(settings.Manifest, settings.Dev);

            if (!ToolInfo.Validate(manifest))
            {
                ToolInfo.ExitPrompt(settings.NonInteractive);
                return(-1);
            }

            AnsiConsole.MarkupLine(" ok");
            AnsiConsole.Markup($"[bold blue]{Icon.Thinking} Scheduling appointments...[/]");

            if (!string.IsNullOrEmpty(settings.DotNetSdkRoot))
            {
                sharedState.SetEnvironmentVariable("DOTNET_ROOT", settings.DotNetSdkRoot);
            }

            var checkups = CheckupManager.BuildCheckupGraph(manifest, sharedState);

            AnsiConsole.MarkupLine(" ok");

            var checkupId = string.Empty;

            for (int i = 0; i < checkups.Count(); i++)
            {
                var checkup = checkups.ElementAt(i);

                // Set the manifest
                checkup.Manifest = manifest;

                // If the ID is the same, it's a retry
                var isRetry = checkupId == checkup.Id;

                // Track the last used id so we can detect retry
                checkupId = checkup.Id;

                if (!checkup.ShouldExamine(sharedState))
                {
                    checkupStatus[checkup.Id] = Models.Status.Ok;
                    continue;
                }

                var skipCheckup = false;

                var dependencies = checkup.DeclareDependencies(checkups.Select(c => c.Id));

                // Make sure our dependencies succeeded first
                if (dependencies?.Any() ?? false)
                {
                    foreach (var dep in dependencies)
                    {
                        var depCheckup = checkups.FirstOrDefault(c => c.Id.StartsWith(dep.CheckupId, StringComparison.OrdinalIgnoreCase));

                        if (depCheckup != null && depCheckup.IsPlatformSupported(Util.Platform))
                        {
                            if (!checkupStatus.TryGetValue(dep.CheckupId, out var depStatus) || depStatus == Models.Status.Error)
                            {
                                skipCheckup = dep.IsRequired;
                                break;
                            }
                        }
                    }
                }

                // See if --skip was specified
                if (settings.Skip?.Any(s => s.Equals(checkup.Id, StringComparison.OrdinalIgnoreCase) ||
                                       s.Equals(checkup.GetType().Name, StringComparison.OrdinalIgnoreCase)) ?? false)
                {
                    skipCheckup = true;
                }

                if (skipCheckup)
                {
                    skippedChecks.Add(checkup.Id);
                    checkupStatus[checkup.Id] = Models.Status.Error;
                    AnsiConsole.WriteLine();
                    AnsiConsole.MarkupLine($"[bold red]{Icon.Error} Skipped: " + checkup.Title + "[/]");
                    continue;
                }

                checkup.OnStatusUpdated += checkupStatusUpdated;

                AnsiConsole.WriteLine();
                AnsiConsole.MarkupLine($"[bold]{Icon.Checking} " + checkup.Title + " Checkup[/]...");
                Console.Title = checkup.Title;

                DiagnosticResult diagnosis = null;

                try
                {
                    diagnosis = await checkup.Examine(sharedState);
                }
                catch (Exception ex)
                {
                    Util.Exception(ex);
                    diagnosis = new DiagnosticResult(Models.Status.Error, checkup, ex.Message);
                }

                results[checkup.Id] = diagnosis;

                // Cache the status for dependencies
                checkupStatus[checkup.Id] = diagnosis.Status;

                if (diagnosis.Status == Models.Status.Ok)
                {
                    continue;
                }

                var statusEmoji = diagnosis.Status == Models.Status.Error ? Icon.Error : Icon.Warning;
                var statusColor = diagnosis.Status == Models.Status.Error ? "red" : "darkorange3_1";

                var msg = !string.IsNullOrEmpty(diagnosis.Message) ? " - " + diagnosis.Message : string.Empty;

                if (diagnosis.HasSuggestion)
                {
                    Console.WriteLine();
                    AnsiConsole.Render(new Rule());
                    AnsiConsole.MarkupLine($"[bold blue]{Icon.Recommend} Recommendation:[/][blue] {diagnosis.Suggestion.Name}[/]");

                    if (!string.IsNullOrEmpty(diagnosis.Suggestion.Description))
                    {
                        AnsiConsole.MarkupLine("" + diagnosis.Suggestion.Description + "");
                    }

                    AnsiConsole.Render(new Rule());
                    Console.WriteLine();

                    // See if we should fix
                    // needs to have a remedy available to even bother asking/trying
                    var doFix = diagnosis.Suggestion.HasSolution &&
                                (
                        // --fix + --non-interactive == auto fix, no prompt
                        (settings.NonInteractive && settings.Fix)
                        // interactive (default) + prompt/confirm they want to fix
                        || (!settings.NonInteractive && AnsiConsole.Confirm($"[bold]{Icon.Bell} Attempt to fix?[/]"))
                                );

                    if (doFix && !isRetry)
                    {
                        var isAdmin = Util.IsAdmin();

                        var adminMsg = Util.IsWindows ?
                                       $"{Icon.Bell} [red]Administrator Permissions Required.  Try opening a new console as Administrator and running this tool again.[/]"
                                                        : $"{Icon.Bell} [red]Super User Permissions Required.  Try running this tool again with 'sudo'.[/]";

                        var didFix = false;

                        foreach (var remedy in diagnosis.Suggestion.Solutions)
                        {
                            try
                            {
                                remedy.OnStatusUpdated += remedyStatusUpdated;

                                AnsiConsole.MarkupLine($"{Icon.Thinking} Attempting to fix: " + checkup.Title);

                                await remedy.Implement(sharedState, cts.Token);

                                didFix = true;
                                AnsiConsole.MarkupLine($"[bold]Fix applied.  Checking again...[/]");
                            }
                            catch (Exception x) when(x is AccessViolationException || x is UnauthorizedAccessException)
                            {
                                Util.Exception(x);
                                AnsiConsole.Markup(adminMsg);
                            }
                            catch (Exception ex)
                            {
                                Util.Exception(ex);
                                AnsiConsole.MarkupLine("[bold red]Fix failed - " + ex.Message + "[/]");
                            }
                            finally
                            {
                                remedy.OnStatusUpdated -= remedyStatusUpdated;
                            }
                        }

                        // RETRY The check again
                        if (didFix)
                        {
                            i--;
                        }
                    }
                }

                checkup.OnStatusUpdated -= checkupStatusUpdated;
            }

            AnsiConsole.Render(new Rule());
            AnsiConsole.WriteLine();

            var erroredChecks = results.Values.Where(d => d.Status == Models.Status.Error && !skippedChecks.Contains(d.Checkup.Id));

            foreach (var ec in erroredChecks)
            {
                Util.Log($"Checkup had Error status: {ec.Checkup.Id}");
            }

            var hasErrors = erroredChecks.Any();

            if (hasErrors)
            {
                AnsiConsole.MarkupLine($"[bold red]{Icon.Bell} There were one or more problems detected.[/]");
                AnsiConsole.MarkupLine($"[bold red]Please review the errors and correct them and run {ToolInfo.ToolCommand} again.[/]");
            }
            else
            {
                AnsiConsole.MarkupLine($"[bold blue]{Icon.Success} Congratulations, everything looks great![/]");
            }

            Console.Title = ToolInfo.ToolName;

            ToolInfo.ExitPrompt(settings.NonInteractive);

            Util.Log($"Has Errors? {hasErrors}");
            var exitCode = hasErrors ? 1 : 0;

            Environment.ExitCode = exitCode;

            return(exitCode);
        }
コード例 #22
0
    private static async Task Main(string[] args)
    {
        using var http = new HttpClient();
        var gw2 = new Gw2Client(http);

        var(ingredients, recipes) = await Progress()
                                    .StartAsync(
            async ctx =>
        {
            var recipesProgress = ctx.AddTask(
                "Fetching recipes",
                new ProgressTaskSettings {
                AutoStart = false
            }
                );
            var ingredientsProgress = ctx.AddTask(
                "Fetching ingredients",
                new ProgressTaskSettings {
                AutoStart = false
            }
                );

            var craftingRecipes = await GetRecipes(gw2.Crafting, recipesProgress);

            var groupedByIngredient = craftingRecipes
                                      .SelectMany(
                recipe => recipe.Ingredients
                .Where(ingredient => ingredient.Kind == IngredientKind.Item)
                .Select(ingredient => (Ingredient: ingredient.Id, Recipe: recipe))
                )
                                      .ToLookup(grouping => grouping.Ingredient, grouping => grouping.Recipe);

            var ingredientIndex = groupedByIngredient.Select(grouping => grouping.Key)
                                  .ToHashSet();

            var craftingIngredients = await GetItems(
                ingredientIndex,
                gw2.Items,
                ingredientsProgress
                );

            var ingredientsById = craftingIngredients.ToDictionary(item => item.Id);

            var mostCommon = groupedByIngredient
                             .OrderByDescending(grouping => grouping.Count())
                             .Select(grouping => ingredientsById[grouping.Key])
                             .ToList();

            return(Ingredients: mostCommon, Craftable: groupedByIngredient);
        }
            );

        do
        {
            AnsiConsole.Clear();

            var choice = AnsiConsole.Prompt(
                new SelectionPrompt <Item>().Title("Pick an ingredient to see the available recipes")
                .MoreChoicesText("Scroll down for less commonly used ingredients")
                .AddChoices(ingredients)
                .UseConverter(item => item.Name)
                .PageSize(20)
                );

            await using var ingredientIcon = await http.GetStreamAsync(choice.Icon !);

            var choiceTable = new Table().AddColumn("Icon")
                              .AddColumn("Ingredient")
                              .AddColumn("Description");

            choiceTable.AddRow(
                new CanvasImage(ingredientIcon).MaxWidth(32),
                new Markup(choice.Name.EscapeMarkup()),
                new Markup(choice.Description.EscapeMarkup())
                );

            AnsiConsole.Write(choiceTable);

            var outputs = await Progress()
                          .StartAsync(
                async ctx =>
            {
                var itemIds = recipes[choice.Id]
                              .Select(recipe => recipe.OutputItemId)
                              .ToHashSet();
                return(await GetItems(
                           itemIds,
                           gw2.Items,
                           ctx.AddTask("Fetching output items")
                           ));
            }
                );

            var recipesTable = new Table().AddColumn("Recipe").AddColumn("Description");

            foreach (var recipe in outputs)
            {
                recipesTable.AddRow(recipe.Name.EscapeMarkup(), recipe.Description.EscapeMarkup());
            }

            AnsiConsole.Write(recipesTable);
        } while (AnsiConsole.Confirm("Do you want to choose again?"));
    }
コード例 #23
0
        public override async Task <int> ExecuteAsync(CommandContext context, Settings settings)
        {
            try
            {
                AnsiConsole.MarkupLine("-=[[ [cyan]EscapeFromTarkov-Trainer Universal Installer[/] - [blue]https://github.com/sailro [/]]]=-");
                AnsiConsole.WriteLine();

                var installation = Installation.GetTargetInstallation(settings.Path, "Please select where to install the trainer");
                if (installation == null)
                {
                    return((int)ExitCode.NoInstallationFound);
                }

                AnsiConsole.MarkupLine($"Target [green]EscapeFromTarkov ({installation.Version})[/] in [blue]{installation.Location.EscapeMarkup()}[/].");

                // Try first to compile against master
                var @try = 0;
                var(compilation, archive, errors) = await GetCompilationAsync(++@try, installation, "master");

                var files = errors
                            .Select(d => d.Location.SourceTree?.FilePath)
                            .Where(s => s is not null)
                            .Distinct()
                            .ToArray();

                if (compilation == null)
                {
                    // Failure, so try with a dedicated branch if exists
                    var branch = settings.Branch ?? installation.Version.ToString();
                    if (!branch.StartsWith("dev-"))
                    {
                        branch = "dev-" + branch;
                    }

                    (compilation, archive, _) = await GetCompilationAsync(++@try, installation, branch);
                }

                if (compilation == null && files.Any() && files.All(f => f !.StartsWith("Features")))
                {
                    // Failure, retry by removing faulting features if possible
                    AnsiConsole.MarkupLine($"[yellow]Trying to disable faulting feature(s): [red]{string.Join(", ", files.Select(Path.GetFileNameWithoutExtension))}[/].[/]");
                    (compilation, archive, errors) = await GetCompilationAsync(++@try, installation, "master", files !);

                    if (!errors.Any())
                    {
                        AnsiConsole.MarkupLine("[yellow]We found a fallback! But please file an issue here : https://github.com/sailro/EscapeFromTarkov-Trainer/issues [/]");
                    }
                }

                if (compilation == null)
                {
                    // Failure
                    AnsiConsole.MarkupLine($"[red]Unable to compile trainer for version {installation.Version}. Please file an issue here : https://github.com/sailro/EscapeFromTarkov-Trainer/issues [/]");
                    return((int)ExitCode.CompilationFailed);
                }

                if (installation.UsingSptAki)
                {
                    AnsiConsole.MarkupLine("[yellow]SPT-AKI detected. Please make sure you have run the game at least once before installing the trainer.[/]");
                    AnsiConsole.MarkupLine("[yellow]SPT-AKI is patching binaries during the first run, and we [underline]need[/] to compile against those patched binaries.[/]");
                    AnsiConsole.MarkupLine("[yellow]If you install this trainer on stock binaries, the game will freeze at the startup screen.[/]");

                    if (!AnsiConsole.Confirm("Continue installation (yes I have run the game at least once) ?"))
                    {
                        return((int)ExitCode.Canceled);
                    }
                }

                if (!CreateDll(installation, "NLog.EFT.Trainer.dll", (dllPath) => compilation.Emit(dllPath)))
                {
                    return((int)ExitCode.CreateDllFailed);
                }

                if (!CreateDll(installation, "0Harmony.dll", (dllPath) => File.WriteAllBytes(dllPath, Resources._0Harmony), false))
                {
                    return((int)ExitCode.CreateHarmonyDllFailed);
                }

                if (!CreateOutline(installation, archive !))
                {
                    return((int)ExitCode.CreateOutlineFailed);
                }

                CreateOrPatchConfiguration(installation);
            }
            catch (Exception ex)
            {
                AnsiConsole.MarkupLine($"[red]Error: {ex.Message.EscapeMarkup()}. Please file an issue here : https://github.com/sailro/EscapeFromTarkov-Trainer/issues [/]");
                return((int)ExitCode.Failure);
            }

            return((int)ExitCode.Success);
        }
コード例 #24
0
        static async Task Main(string[] args)
        {
            string name, surname;
            int    birthday;

            List <Person> personsList = new List <Person> ();

            do
            {
                Console.WriteLine("1- Para agregar persona\n2- Para mostrar información");
                var option = int.Parse(Console.ReadLine());
                switch (option)
                {
                case 1:

                    name     = AnsiConsole.Ask <string> ("Cual es tu [blue]nombre[/]?");
                    surname  = AnsiConsole.Ask <string> ("Cual es tu  [blue]apellido[/]?");
                    birthday = AnsiConsole.Ask <int> ("Cual es tu [green]año de nacimiento[/]?");
                    Person persona = new Person(name, surname, birthday);
                    personsList.Add(persona);
                    AnsiConsole.Status()
                    .Start("Guardando...", ctx => {
                        Thread.Sleep(1000);
                        // Update the status and spinner
                        ctx.Status("Finalizado");
                        ctx.Spinner(Spinner.Known.Star);
                        ctx.SpinnerStyle(Style.Parse("green"));
                        Thread.Sleep(1000);
                    });
                    Console.Clear();
                    break;

                case 2:

                    var saveTable = AnsiConsole.Confirm("Guardar tabla?");
                    AnsiConsole.Record();
                    Table table = new Table();

                    table.AddColumn("Nombre");
                    table.AddColumn("Apellido");
                    table.AddColumn("Edad");
                    table.AddColumn("Pais");
                    table.AddColumn("Ciudad");
                    table.AddColumn("Idioma");
                    table.AddColumn("Cordenadas");

                    foreach (var item in personsList)
                    {
                        table.AddRow(item.Name, item.Surname, item.Birthday.ToString(), item.Country, item.City, item.Language, item.Cordinates);
                    }

                    var title = new TableTitle("Empleado", Style.WithDecoration(Decoration.Bold));
                    table.Title = title;

                    table.Border(TableBorder.Rounded);
                    table.BorderColor <Table> (Color.Blue);
                    AnsiConsole.Render(table);

                    if (saveTable)
                    {
                        string html = AnsiConsole.ExportHtml();
                        Directory.CreateDirectory("../Employes");
                        File.WriteAllText("../Employes/index.html", html);

                        Console.ForegroundColor = Color.Green;
                        Console.WriteLine("Guardado Exitosamente");
                        Console.ForegroundColor = Color.White;
                    }

                    break;

                default:
                    break;
                }
            } while (true);
        }
コード例 #25
0
        public override async Task <int> ExecuteAsync(CommandContext context, DoctorSettings settings)
        {
            Console.Title = ToolName;

            AnsiConsole.MarkupLine($"[underline bold green]{Icon.Ambulance} {ToolName} {Icon.Recommend}[/]");
            AnsiConsole.Render(new Rule());

            AnsiConsole.MarkupLine("This tool will attempt to evaluate your .NET MAUI development environment.");
            AnsiConsole.MarkupLine("If problems are detected, this tool may offer the option to try and fix them for you, or suggest a way to fix them yourself.");
            AnsiConsole.WriteLine();
            AnsiConsole.MarkupLine("Thanks for choosing .NET MAUI!");

            AnsiConsole.WriteLine();

            if (!settings.NonInteractive)
            {
                AnsiConsole.Markup("Press any key to start...");
                Console.ReadKey();
                AnsiConsole.WriteLine();
            }

            AnsiConsole.Render(new Rule());

            var clinic = new Clinic();
            var cts    = new System.Threading.CancellationTokenSource();

            var checkupStatus  = new Dictionary <string, Doctoring.Status>();
            var patientHistory = new PatientHistory();

            var diagnoses     = new List <Diagonosis>();
            var consoleStatus = AnsiConsole.Status();

            AnsiConsole.Markup($"[bold blue]{Icon.Thinking} Synchronizing configuration...[/]");

            var chart = await Manifest.Chart.FromFileOrUrl(settings.Manifest);

            var toolVersion = chart?.Doctor?.ToolVersion;

            var fileVersion = NuGetVersion.Parse(FileVersionInfo.GetVersionInfo(this.GetType().Assembly.Location).FileVersion);

            if (string.IsNullOrEmpty(toolVersion) || !NuGetVersion.TryParse(toolVersion, out var toolVer) || fileVersion < toolVer)
            {
                Console.WriteLine();
                AnsiConsole.MarkupLine($"[bold red]{Icon.Error} Updating to version {toolVersion} or newer is required:[/]");
                AnsiConsole.MarkupLine($"[red]Update with the following:[/]");

                var installCmdVer = string.IsNullOrEmpty(toolVersion) ? "" : $" --version {toolVersion}";
                AnsiConsole.Markup($"  dotnet tool install --global {ToolPackageId}{installCmdVer}");

                return(-1);
            }

            AnsiConsole.MarkupLine(" ok");
            AnsiConsole.Markup($"[bold blue]{Icon.Thinking} Scheduling appointments...[/]");

            if (chart.Doctor.OpenJdk != null)
            {
                clinic.OfferService(new OpenJdkCheckup(chart.Doctor.OpenJdk.MinimumVersion, chart.Doctor.OpenJdk.ExactVersion));
            }

            if (chart.Doctor.Android != null)
            {
                clinic.OfferService(new AndroidSdkManagerCheckup());
                clinic.OfferService(new AndroidSdkPackagesCheckup(chart.Doctor.Android.Packages.ToArray()));
                clinic.OfferService(new AndroidSdkLicensesCheckup());
            }

            if (chart.Doctor.XCode != null)
            {
                clinic.OfferService(new XCodeCheckup(chart.Doctor.XCode.MinimumVersion, chart.Doctor.XCode.ExactVersion));
            }

            if (chart.Doctor.VSMac != null && !string.IsNullOrEmpty(chart.Doctor.VSMac.MinimumVersion))
            {
                clinic.OfferService(new VisualStudioMacCheckup(chart.Doctor.VSMac.MinimumVersion, chart.Doctor.VSMac.ExactVersion));
            }

            if (chart.Doctor.VSWin != null && !string.IsNullOrEmpty(chart.Doctor.VSWin.MinimumVersion))
            {
                clinic.OfferService(new VisualStudioWindowsCheckup(chart.Doctor.VSWin.MinimumVersion, chart.Doctor.VSWin.ExactVersion));
            }


            if (chart.Doctor.DotNet?.Sdks?.Any() ?? false)
            {
                clinic.OfferService(new DotNetCheckup(chart.Doctor.DotNet.Sdks.ToArray()));

                foreach (var sdk in chart.Doctor.DotNet.Sdks)
                {
                    clinic.OfferService(new DotNetWorkloadsCheckup(sdk.Version, sdk.Workloads.ToArray(), sdk.PackageSources.ToArray()));

                    // Always run the packs checkup even if manifest is empty, since the workloads may resolve some required packs dynamically that aren't from the manifest
                    clinic.OfferService(new DotNetPacksCheckup(sdk.Version, sdk.Packs?.ToArray() ?? Array.Empty <Manifest.NuGetPackage>(), sdk.PackageSources.ToArray()));
                }
            }


            var checkups = clinic.ScheduleCheckups();

            AnsiConsole.MarkupLine(" ok");

            foreach (var checkup in checkups)
            {
                var skipCheckup = false;

                // Make sure our dependencies succeeded first
                if (checkup.Dependencies?.Any() ?? false)
                {
                    foreach (var dep in checkup.Dependencies)
                    {
                        if (!checkupStatus.TryGetValue(dep.CheckupId, out var depStatus) || depStatus != Doctoring.Status.Ok)
                        {
                            skipCheckup = dep.IsRequired;
                            break;
                        }
                    }
                }

                if (skipCheckup)
                {
                    checkupStatus.Add(checkup.Id, Doctoring.Status.Error);
                    AnsiConsole.WriteLine();
                    AnsiConsole.MarkupLine($"[bold red]{Icon.Error} Skipped: " + checkup.Title + "[/]");
                    continue;
                }

                checkup.OnStatusUpdated += (s, e) =>
                {
                    var msg = "";
                    if (e.Status == Doctoring.Status.Error)
                    {
                        msg = $"[red]{Icon.Error} {e.Message}[/]";
                    }
                    else if (e.Status == Doctoring.Status.Warning)
                    {
                        msg = $"[red]{Icon.Error} {e.Message}[/]";
                    }
                    else if (e.Status == Doctoring.Status.Ok)
                    {
                        msg = $"[green]{Icon.Success} {e.Message}[/]";
                    }
                    else
                    {
                        msg = $"{Icon.ListItem} {e.Message}";
                    }

                    AnsiConsole.MarkupLine("  " + msg);
                };

                AnsiConsole.WriteLine();
                AnsiConsole.MarkupLine($"[bold]{Icon.Checking} " + checkup.Title + " Checkup[/]...");
                Console.Title = checkup.Title;

                Diagonosis diagnosis = null;

                try
                {
                    diagnosis = await checkup.Examine(patientHistory);
                }
                catch (Exception ex)
                {
                    diagnosis = new Diagonosis(Doctoring.Status.Error, checkup, ex.Message);
                }

                diagnoses.Add(diagnosis);

                // Cache the status for dependencies
                checkupStatus.Add(checkup.Id, diagnosis.Status);

                if (diagnosis.Status == Doctoring.Status.Ok)
                {
                    continue;
                }

                var statusEmoji = diagnosis.Status == Doctoring.Status.Error ? Icon.Error : Icon.Warning;
                var statusColor = diagnosis.Status == Doctoring.Status.Error ? "red" : "orange3";

                var msg = !string.IsNullOrEmpty(diagnosis.Message) ? " - " + diagnosis.Message : string.Empty;

                //AnsiConsole.MarkupLine($"[{statusColor}]{statusEmoji} {checkup.Title}{msg}[/]");

                if (diagnosis.HasPrescription)
                {
                    AnsiConsole.MarkupLine($"  [bold blue]{Icon.Recommend} Recommendation:[/] {diagnosis.Prescription.Name}");

                    if (!string.IsNullOrEmpty(diagnosis.Prescription.Description))
                    {
                        AnsiConsole.MarkupLine("  " + diagnosis.Prescription.Description);
                    }

                    // See if we should fix
                    // needs to have a remedy available to even bother asking/trying
                    var doFix = diagnosis.Prescription.HasRemedy &&
                                (
                        // --fix + --non-interactive == auto fix, no prompt
                        (settings.NonInteractive && settings.Fix)
                        // interactive (default) + prompt/confirm they want to fix
                        || (!settings.NonInteractive && AnsiConsole.Confirm($"    [bold]{Icon.Bell} Attempt to fix?[/]"))
                                );

                    if (doFix)
                    {
                        var isAdmin = Util.IsAdmin();

                        foreach (var remedy in diagnosis.Prescription.Remedies)
                        {
                            if (!remedy.HasPrivilegesToRun(isAdmin, Util.Platform))
                            {
                                AnsiConsole.Markup("Fix requires running with adminstrator privileges.  Try opening a terminal as administrator and running maui-doctor again.");
                                continue;
                            }
                            try
                            {
                                remedy.OnStatusUpdated += (s, e) =>
                                {
                                    AnsiConsole.MarkupLine("  " + e.Message);
                                };

                                AnsiConsole.MarkupLine($"{Icon.Thinking} Attempting to fix: " + checkup.Title);

                                await remedy.Cure(cts.Token);

                                AnsiConsole.MarkupLine("  Fix applied.  Run doctor again to verify.");
                            }
                            catch (Exception ex)
                            {
                                AnsiConsole.MarkupLine("  Fix failed - " + ex.Message);
                            }
                        }
                    }
                }
            }

            AnsiConsole.Render(new Rule());
            AnsiConsole.WriteLine();


            if (diagnoses.Any(d => d.Status == Doctoring.Status.Error))
            {
                AnsiConsole.MarkupLine($"[bold red]{Icon.Bell} There were one or more problems detected.[/]");
                AnsiConsole.MarkupLine($"[bold red]Please review the errors and correct them and run maui-doctor again.[/]");
            }
            else
            {
                AnsiConsole.MarkupLine($"[bold blue]{Icon.Success} Congratulations, everything looks great![/]");
            }

            Console.Title = ToolName;

            return(0);
        }
コード例 #26
0
        private void ReadRenaming()
        {
            var useForRenaming = AnsiConsole.Confirm("Do you want to use pdbMate to rename your downloads (sort them into folders based on sitename and rename files into a humanfriendly format - very useful for media players like plex)?");

            if (!useForRenaming)
            {
                return;
            }

            var useStandardFormat = AnsiConsole.Confirm("Use default format for folder and filename renaming (Folder: {Video.Site.Sitename} File: {Video.ReleasedateShort} - {Video.Title} - {VideoQuality.SimplifiedName} - {PdbId}{FileExtension})?");

            if (!useStandardFormat)
            {
                appSettings.Rename.FilenameTemplate = AnsiConsole.Prompt(
                    new TextPrompt <string>($"Enter your desired [green]filename template[/] for renaming:")
                    .PromptStyle("green")
                    .ValidationErrorMessage("[red]That's not a valid filename template[/]")
                    .Validate(filenameTemplate =>
                {
                    if (!filenameTemplate.Contains("{FileExtension}"))
                    {
                        return(ValidationResult.Error("[red]Please include at least the {FileExtension}[/]"));
                    }

                    return(ValidationResult.Success());
                }));
                appSettings.Rename.FolderTemplate = AnsiConsole.Prompt(
                    new TextPrompt <string>($"Enter your desired [green]folder template[/] for renaming:")
                    .PromptStyle("green"));
            }

            bool doYouWantToAddAnother = false;

            do
            {
                var sourceFolder = AnsiConsole.Prompt(
                    new TextPrompt <string>($"Add [green]folderpath[/] as source for renaming:")
                    .PromptStyle("green")
                    .ValidationErrorMessage("[red]That's not a valid folderpath[/]")
                    .Validate(folderpath =>
                {
                    if (!Directory.Exists(folderpath))
                    {
                        return(ValidationResult.Error("[red]This directory does not exist[/]"));
                    }

                    return(ValidationResult.Success());
                }));

                appSettings.Rename.SourceFolders.Add(sourceFolder);
                doYouWantToAddAnother = AnsiConsole.Confirm("Do you want to add another source folder for renaming?");
            }while (doYouWantToAddAnother);

            appSettings.Rename.TargetFolder = AnsiConsole.Prompt(
                new TextPrompt <string>($"In which [green]target path[/] should renamed files be moved (every site will become its own subfolder if the default folder template setting wasn't changed):")
                .PromptStyle("green")
                .ValidationErrorMessage("[red]That's not a valid target path[/]")
                .Validate(targetFolder =>
            {
                if (!Directory.Exists(targetFolder))
                {
                    return(ValidationResult.Error("[red]This directory does not exist[/]"));
                }

                return(ValidationResult.Success());
            }));
        }
コード例 #27
0
 public static void DeleteConfiguration()
 {
     ShowConfiguration();
     var option = AnsiConsole.Confirm("Desea eliminar la configuración?");
     if (option) ConfigAccess.DeleteConfiguration();
 }
コード例 #28
0
ファイル: Program.cs プロジェクト: Bia10/ArcNET
        private static void Main()
        {
            Terminal.RenderLogo();

            var choice = Terminal.GetMainMenuChoice();

            ConsoleExtensions.Log($"Selected choice: {choice}", "info");
            switch (choice)
            {
            case "Extract game data":
                ConsoleExtensions.Log($"Choice: {choice} is currently unsupported!", "error");
                break;

            case "Parse extracted game data":
                Parser.ParseExtractedData();
                break;

            case "Install High-Res patch":
                var pathToHighResDir = GetHighResDir();
                var files            = Directory.EnumerateFiles(
                    pathToHighResDir, "*.*", SearchOption.AllDirectories).ToList();

                if (files.Count == 0)
                {
                    ConsoleExtensions.Log("HighResFolder empty proceeding to clone latest version", "info");
                    GitHub.CloneHighResPatch(pathToHighResDir);
                }

                var configPath = Path.Combine(pathToHighResDir + "\\config.ini");
                if (!File.Exists(configPath))
                {
                    throw new InvalidOperationException($"Config file not found at path: {configPath}");
                }

                ConsoleExtensions.Log("Gathering environment info", "info");
                var envInfo = new EnvironmentInfo();
                envInfo.Print();

                ConsoleExtensions.Log("Auto-config according to environment info", "info");
                HighResConfig.AutoConfigure(envInfo);

                ConsoleExtensions.Log("Summary of config.ini:", "info");
                AnsiConsole.Render(Terminal.ConfigTable());

                if (AnsiConsole.Confirm("Would you like to change config?"))
                {
                    AnsiConsole.WriteException(new NotImplementedException());
                    return;
                }

                HighResConfig.Write(configPath);
                LaunchWeidu(CmdArgs.Weidu.InstallHighResPatch, pathToHighResDir);
                break;

            case "Uninstall High-Res patch":
                LaunchWeidu(CmdArgs.Weidu.UninstallHighResPatch);
                break;

            default:
                ConsoleExtensions.Log($"Choice: {choice} is currently unsupported!", "error");
                break;
            }
        }