mfgames-cil/examples/SampleTool/Commands/ConfigCommand.cs

79 lines
2.1 KiB
C#

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<ConfigCommand> logger;
private readonly ConfigToolService service;
private readonly Option<string> setOption;
/// <inheritdoc />
public ConfigCommand(ILoggerFactory loggerFactory, ConfigToolService service)
: base("config", "Sets and displays the configuration settings")
{
this.logger = loggerFactory.CreateLogger<ConfigCommand>();
this.service = service;
this.Handler = this;
this.setOption = new Option<string>("--set", "Sets the text value in the setting");
this.AddOption(this.setOption);
}
/// <inheritdoc />
public int Invoke(InvocationContext context)
{
return this.InvokeAsync(context).Result;
}
/// <inheritdoc />
public Task<int> InvokeAsync(InvocationContext context)
{
// Get the settings and report that it was being created.
ConfigCommandSettings settings =
this.service.ReadDefaultConfigFile<ConfigCommandSettings>();
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; }
}
}