using System; using System.CommandLine; using System.CommandLine.Invocation; using System.Threading.Tasks; using MfGames.ToolBuilder; using MfGames.ToolBuilder.Config; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace SampleTool.Commands; public class ConfigCommand : Command, ICommandHandler, ITopCommand { private readonly ILogger logger; private readonly ConfigToolService service; private readonly Option setOption; /// public ConfigCommand(ILoggerFactory loggerFactory, ConfigToolService service) : base("config", "Sets and displays the configuration settings") { this.logger = loggerFactory.CreateLogger(); this.service = service; this.Handler = this; this.setOption = new Option("--set", "Sets the text value in the setting"); this.AddOption(this.setOption); } /// public int Invoke(InvocationContext context) { return this.InvokeAsync(context).Result; } /// public Task InvokeAsync(InvocationContext context) { // Get the settings and report that it was being created. ConfigCommandSettings settings = this.service.ReadDefaultConfigFile(); if (settings == null) { this.logger.LogInformation("Creating configuration file"); settings = new ConfigCommandSettings(); } // If we have a set command, then provide it. string value = context.ParseResult.GetValueForOption(this.setOption); if (value != null) { settings.Value = value; } // Increment the counter. settings.TimesRead++; // Report the values. Console.WriteLine(JsonConvert.SerializeObject(settings, Formatting.Indented)); // Write out the settings. this.service.WriteDefaultConfigFile(settings); return Task.FromResult(0); } private class ConfigCommandSettings { public int TimesRead { get; set; } public string Value { get; set; } } }