using System;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.Globalization;
using Nitride.Commands;
using NodaTime;
using NodaTime.Testing;
using Serilog;
namespace 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 Timekeeper timekeeper;
public DatePipelineCommandOption(ILogger logger, Timekeeper timekeeper)
{
this.logger = logger.ForContext();
this.timekeeper = timekeeper;
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.timekeeper.DateTimeZone);
var instant = zoned.ToInstant();
this.timekeeper.Clock = new FakeClock(instant);
}
// Report the date we are processing.
Instant now = this.timekeeper.Clock.GetCurrentInstant();
ZonedDateTime dateTime = now.InZone(this.timekeeper.DateTimeZone);
string formatted = dateTime.ToString("G", CultureInfo.InvariantCulture);
this.logger.Information("Setting date/time to {When:l}", formatted);
}
}