62 lines
1.9 KiB
C#
62 lines
1.9 KiB
C#
|
using System;
|
||
|
using System.Collections.Generic;
|
||
|
using System.Text.RegularExpressions;
|
||
|
using Gallium;
|
||
|
using NodaTime;
|
||
|
using Zio;
|
||
|
|
||
|
namespace Nitride.Temporal
|
||
|
{
|
||
|
/// <summary>
|
||
|
/// Sets the instant in the file based on the path of the entity. This
|
||
|
/// defaults to a generous regular expression that handles most formats of
|
||
|
/// four digit year, a separator, two digit month, a separator, and a two
|
||
|
/// digit day of month.
|
||
|
/// </summary>
|
||
|
[WithProperties]
|
||
|
public partial class SetInstantFromPath : NitrideOperationBase
|
||
|
{
|
||
|
private readonly NitrideClock clock;
|
||
|
|
||
|
public SetInstantFromPath(NitrideClock clock)
|
||
|
{
|
||
|
this.clock = clock;
|
||
|
this.PathRegex = new Regex(
|
||
|
@"(?<year>\d{4})[/-](?<month>\d{2})[/-](?<day>\d{2})");
|
||
|
}
|
||
|
|
||
|
/// <summary>
|
||
|
/// Gets or sets a regular expression that has three named expressions:
|
||
|
/// year, month, and day.
|
||
|
/// </summary>
|
||
|
public Regex? PathRegex { get; set; }
|
||
|
|
||
|
/// <inheritdoc />
|
||
|
public override IEnumerable<Entity> Run(IEnumerable<Entity> input)
|
||
|
{
|
||
|
this.CheckNotNull(nameof(this.PathRegex), this.PathRegex);
|
||
|
|
||
|
return input.ForEachEntity<UPath>(this.Set);
|
||
|
}
|
||
|
|
||
|
private Entity Set(Entity entity, UPath path)
|
||
|
{
|
||
|
// See if the path matches the given expression.
|
||
|
Match match = this.PathRegex!.Match(path.ToString());
|
||
|
|
||
|
if (!match.Success)
|
||
|
{
|
||
|
return entity;
|
||
|
}
|
||
|
|
||
|
// Create an Instant from this.
|
||
|
Instant instant = this.clock.CreateInstant(
|
||
|
Convert.ToInt32(match.Groups["year"].Value),
|
||
|
Convert.ToInt32(match.Groups["month"].Value),
|
||
|
Convert.ToInt32(match.Groups["day"].Value));
|
||
|
|
||
|
return entity.Set(instant);
|
||
|
}
|
||
|
}
|
||
|
}
|