using System; using System.CommandLine; using System.CommandLine.Invocation; using System.Globalization; using MfGames.Nitride.Commands; using NodaTime; using NodaTime.Testing; using Serilog; namespace MfGames.Nitride.Temporal.Cli; /// /// A factory to inject the "--date=XXXX-XX-XX" argument into the build /// and other pipeline commands. /// public class DatePipelineCommandOption : IPipelineCommandOption { private readonly ILogger logger; private readonly TimeService timeService; public DatePipelineCommandOption( ILogger logger, TimeService timeService) { this.logger = logger.ForContext(); this.timeService = timeService; this.Option = new Option("--date") { Description = "Sets the date to something other than now", ArgumentHelpName = "DATE", }; } /// public Option Option { get; } /// public void Handle(InvocationContext context) { // If we got a date, then use NodaTime's fake clock to set it so // everything will use that. var value = (DateTime?)context.ParseResult.GetValueForOption(this.Option); if (value.HasValue && value.Value != DateTime.MinValue) { // We have a date, so we need to create a fake clock that has this // date for the entire run. var local = LocalDateTime.FromDateTime(value.Value); ZonedDateTime zoned = local.InZoneStrictly(this.timeService.DateTimeZone); var instant = zoned.ToInstant(); this.timeService.Clock = new FakeClock(instant); } // Report the date we are processing. Instant now = this.timeService.Clock.GetCurrentInstant(); ZonedDateTime dateTime = now.InZone(this.timeService.DateTimeZone); string formatted = dateTime.ToString("G", CultureInfo.InvariantCulture); this.logger.Information("Setting date/time to {When:l}", formatted); } }