This repository has been archived on 2023-02-02. You can view files and clone it, but cannot push or open issues or pull requests.
mfgames-nitride-cil/src/MfGames.Nitride.Temporal/Cli/DatePipelineCommandOption.cs

70 lines
2.0 KiB
C#

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;
/// <summary>
/// A factory to inject the "--date=XXXX-XX-XX" argument into the build
/// and other pipeline commands.
/// </summary>
public class DatePipelineCommandOption : IPipelineCommandOption
{
private readonly ILogger logger;
private readonly TimeService timeService;
public DatePipelineCommandOption(
ILogger logger,
TimeService timeService)
{
this.logger = logger.ForContext<Instant>();
this.timeService = timeService;
this.Option = new Option<DateTime>("--date")
{
Description = "Sets the date to something other than now",
ArgumentHelpName = "DATE",
};
}
/// <inheritdoc />
public Option Option { get; }
/// <inheritdoc />
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);
}
}