Skip to content

A Swiss Army knife for developers.

Ported Cron parser tool to DevToys 2.0 (#1066)

Etienne Baudoux46a3a5447e86
diff --git a/src/Directory.Packages.props b/src/Directory.Packages.props
index 8a6d4d6ae..743fd1433 100644
--- a/src/Directory.Packages.props
+++ b/src/Directory.Packages.props
@@ -11,6 +11,8 @@
<PackageVersion Include="CommunityToolkit.Mvvm" Version="$(CommunityToolkitVersion)" />
<PackageVersion Include="CommunityToolkit.Maui" Version="5.2.0" />
<PackageVersion Include="coverlet.collector" Version="6.0.0" />
+ <PackageVersion Include="CronExpressionDescriptor" Version="2.32.0" />
+ <PackageVersion Include="Cronos" Version="0.8.3" />
<PackageVersion Include="FluentAssertions" Version="6.11.0" />
<PackageVersion Include="FuzzySharp" Version="2.0.2" />
<PackageVersion Include="GirCore.Adw-1" Version="$(GirCore)" />
diff --git a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj b/src/app/dev/DevToys.Tools/DevToys.Tools.csproj
index b89648cf1..f76f47641 100644
--- a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj
+++ b/src/app/dev/DevToys.Tools/DevToys.Tools.csproj
@@ -38,6 +38,11 @@
<AutoGen>True</AutoGen>
<DependentUpon>GlobalStrings.resx</DependentUpon>
</Compile>
+ <Compile Update="Tools\Converters\Cron\CronParser.Designer.cs">
+ <DesignTime>True</DesignTime>
+ <AutoGen>True</AutoGen>
+ <DependentUpon>CronParser.resx</DependentUpon>
+ </Compile>
<Compile Update="Tools\EncodersDecoders\Certificate\CertificateDecoder.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
@@ -204,6 +209,10 @@
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>GlobalStrings.Designer.cs</LastGenOutput>
</EmbeddedResource>
+ <EmbeddedResource Update="Tools\Converters\Cron\CronParser.resx">
+ <Generator>ResXFileCodeGenerator</Generator>
+ <LastGenOutput>CronParser.Designer.cs</LastGenOutput>
+ </EmbeddedResource>
<EmbeddedResource Update="Tools\Converters\JsonTable\JsonTableConverter.resx">
<LastGenOutput>JsonTableConverter.Designer.cs</LastGenOutput>
<Generator>ResXFileCodeGenerator</Generator>
@@ -353,6 +362,8 @@
</ItemGroup>
<ItemGroup>
+ <PackageReference Include="CronExpressionDescriptor" />
+ <PackageReference Include="Cronos" />
<PackageReference Include="Newtonsoft.Json" />
<PackageReference Include="YamlDotNet" />
<PackageReference Include="Markdig" />
diff --git a/src/app/dev/DevToys.Tools/Helpers/CronHelper.cs b/src/app/dev/DevToys.Tools/Helpers/CronHelper.cs
new file mode 100644
index 000000000..af4fe2f08
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Helpers/CronHelper.cs
@@ -0,0 +1,85 @@
+using System.Globalization;
+using CronExpressionDescriptor;
+using Cronos;
+using DevToys.Tools.Tools.Converters.Cron;
+
+namespace DevToys.Tools.Helpers;
+
+internal static class CronHelper
+{
+ internal static bool TryGenerateNextSchedulesAndDescription(
+ string cronExpression,
+ string dateFormat,
+ bool includeSeconds,
+ int maxScheduleCount,
+ out string schedule,
+ out string description,
+ out string error)
+ {
+ if (string.IsNullOrEmpty(cronExpression))
+ {
+ schedule = string.Empty;
+ description = string.Empty;
+ error = string.Empty;
+ return true;
+ }
+
+ // Validate date format
+ if (!ValidateDateTimeFormat(dateFormat))
+ {
+ schedule = string.Empty;
+ description = string.Empty;
+ error = CronParser.OutputFormatErrorMessage;
+ return false;
+ }
+
+ try
+ {
+ // Attempt to generate a description
+ description = ExpressionDescriptor.GetDescription(cronExpression);
+
+ var expression
+ = CronExpression.Parse(
+ cronExpression,
+ includeSeconds ? CronFormat.IncludeSeconds : CronFormat.Standard);
+
+ Guard.IsNotNull(expression, nameof(expression));
+
+ // Attempt to generate next schedules
+ DateTimeOffset? nextOccurrence = expression.GetNextOccurrence(DateTimeOffset.Now, TimeZoneInfo.Local, true);
+ var output = new List<string>();
+ int i = 0;
+ while (i < maxScheduleCount && nextOccurrence.HasValue)
+ {
+ output.Add(nextOccurrence.Value.ToString(dateFormat));
+ nextOccurrence = expression.GetNextOccurrence(nextOccurrence.Value, TimeZoneInfo.Local, false);
+ i++;
+ }
+
+ schedule = string.Join(Environment.NewLine, output);
+ error = string.Empty;
+ return true;
+ }
+ catch
+ {
+ schedule = string.Empty;
+ description = string.Empty;
+ error = CronParser.CronErrorMessage;
+ return false;
+ }
+ }
+
+ private static bool ValidateDateTimeFormat(string dateFormat)
+ {
+ try
+ {
+ string s = DateTime.Now.ToString(dateFormat, CultureInfo.InvariantCulture);
+ DateTime.Parse(s, CultureInfo.InvariantCulture);
+ return true;
+ }
+ catch
+ {
+ return false;
+ }
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Models/CronScheduleCount.cs b/src/app/dev/DevToys.Tools/Models/CronScheduleCount.cs
new file mode 100644
index 000000000..41e4075fd
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Models/CronScheduleCount.cs
@@ -0,0 +1,10 @@
+namespace DevToys.Tools.Models;
+
+internal enum CronScheduleCount
+{
+ Five,
+ Ten,
+ TwentyFive,
+ Fifty,
+ OneHundred
+}
diff --git a/src/app/dev/DevToys.Tools/Tools/Converters/Cron/CronParser.Designer.cs b/src/app/dev/DevToys.Tools/Tools/Converters/Cron/CronParser.Designer.cs
new file mode 100644
index 000000000..c88275c01
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Tools/Converters/Cron/CronParser.Designer.cs
@@ -0,0 +1,243 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace DevToys.Tools.Tools.Converters.Cron {
+ using System;
+
+
+ /// <summary>
+ /// A strongly-typed resource class, for looking up localized strings, etc.
+ /// </summary>
+ // This class was auto-generated by the StronglyTypedResourceBuilder
+ // class via a tool like ResGen or Visual Studio.
+ // To add or remove a member, edit your .ResX file then rerun ResGen
+ // with the /str option, or rebuild your VS project.
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class CronParser {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal CronParser() {
+ }
+
+ /// <summary>
+ /// Returns the cached ResourceManager instance used by this class.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager {
+ get {
+ if (object.ReferenceEquals(resourceMan, null)) {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DevToys.Tools.Tools.Converters.Cron.CronParser", typeof(CronParser).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ /// <summary>
+ /// Overrides the current thread's CurrentUICulture property for all
+ /// resource lookups using this strongly typed resource class.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture {
+ get {
+ return resourceCulture;
+ }
+ set {
+ resourceCulture = value;
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Cron parsing tool.
+ /// </summary>
+ internal static string AccessibleName {
+ get {
+ return ResourceManager.GetString("AccessibleName", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Configuration.
+ /// </summary>
+ internal static string ConfigurationTitle {
+ get {
+ return ResourceManager.GetString("ConfigurationTitle", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Cron description.
+ /// </summary>
+ internal static string CronDescriptionTitle {
+ get {
+ return ResourceManager.GetString("CronDescriptionTitle", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Cron expression is not valid.
+ /// </summary>
+ internal static string CronErrorMessage {
+ get {
+ return ResourceManager.GetString("CronErrorMessage", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to The Cron expression to parse.
+ /// </summary>
+ internal static string CronExpressionOptionDescription {
+ get {
+ return ResourceManager.GetString("CronExpressionOptionDescription", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Date time fomat of generated scheduled dates.
+ /// </summary>
+ internal static string DateFormatOptionDescription {
+ get {
+ return ResourceManager.GetString("DateFormatOptionDescription", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Parse Cron expression to get scheduled dates.
+ /// </summary>
+ internal static string Description {
+ get {
+ return ResourceManager.GetString("Description", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Whether the Cron expression includes seconds in its definition.
+ /// </summary>
+ internal static string IncludeSecondsOptionDescription {
+ get {
+ return ResourceManager.GetString("IncludeSecondsOptionDescription", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Cron expression to parse.
+ /// </summary>
+ internal static string InputTitle {
+ get {
+ return ResourceManager.GetString("InputTitle", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Cron expression parser.
+ /// </summary>
+ internal static string LongDisplayTitle {
+ get {
+ return ResourceManager.GetString("LongDisplayTitle", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Number of schedules to be generated.
+ /// </summary>
+ internal static string MaxScheduleCountOptionDescription {
+ get {
+ return ResourceManager.GetString("MaxScheduleCountOptionDescription", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to How many scheduled dates needs to be generated.
+ /// </summary>
+ internal static string OutputCountDescription {
+ get {
+ return ResourceManager.GetString("OutputCountDescription", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Next scheduled dates.
+ /// </summary>
+ internal static string OutputCountTitle {
+ get {
+ return ResourceManager.GetString("OutputCountTitle", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Date time fomat of upcoming dates.
+ /// </summary>
+ internal static string OutputFormatDescription {
+ get {
+ return ResourceManager.GetString("OutputFormatDescription", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Output date time format is not valid.
+ /// </summary>
+ internal static string OutputFormatErrorMessage {
+ get {
+ return ResourceManager.GetString("OutputFormatErrorMessage", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Output format.
+ /// </summary>
+ internal static string OutputFormatTitle {
+ get {
+ return ResourceManager.GetString("OutputFormatTitle", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Next scheduled dates.
+ /// </summary>
+ internal static string OutputScheduleTitle {
+ get {
+ return ResourceManager.GetString("OutputScheduleTitle", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Cron parser.
+ /// </summary>
+ internal static string ShortDisplayTitle {
+ get {
+ return ResourceManager.GetString("ShortDisplayTitle", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Whether the Cron expression should include seconds in its definition.
+ /// </summary>
+ internal static string UseSecondsDescription {
+ get {
+ return ResourceManager.GetString("UseSecondsDescription", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Include seconds.
+ /// </summary>
+ internal static string UseSecondsTitle {
+ get {
+ return ResourceManager.GetString("UseSecondsTitle", resourceCulture);
+ }
+ }
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Tools/Converters/Cron/CronParser.resx b/src/app/dev/DevToys.Tools/Tools/Converters/Cron/CronParser.resx
new file mode 100644
index 000000000..72a8c8171
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Tools/Converters/Cron/CronParser.resx
@@ -0,0 +1,180 @@
+<?xml version="1.0" encoding="utf-8"?>
+<root>
+ <!--
+ Microsoft ResX Schema
+
+ Version 2.0
+
+ The primary goals of this format is to allow a simple XML format
+ that is mostly human readable. The generation and parsing of the
+ various data types are done through the TypeConverter classes
+ associated with the data types.
+
+ Example:
+
+ ... ado.net/XML headers & schema ...
+ <resheader name="resmimetype">text/microsoft-resx</resheader>
+ <resheader name="version">2.0</resheader>
+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+ <value>[base64 mime encoded serialized .NET Framework object]</value>
+ </data>
+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+ <comment>This is a comment</comment>
+ </data>
+
+ There are any number of "resheader" rows that contain simple
+ name/value pairs.
+
+ Each data row contains a name, and value. The row also contains a
+ type or mimetype. Type corresponds to a .NET class that support
+ text/value conversion through the TypeConverter architecture.
+ Classes that don't support this are serialized and stored with the
+ mimetype set.
+
+ The mimetype is used for serialized objects, and tells the
+ ResXResourceReader how to depersist the object. This is currently not
+ extensible. For a given mimetype the value must be set accordingly:
+
+ Note - application/x-microsoft.net.object.binary.base64 is the format
+ that the ResXResourceWriter will generate, however the reader can
+ read any of the formats listed below.
+
+ mimetype: application/x-microsoft.net.object.binary.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.soap.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.bytearray.base64
+ value : The object must be serialized into a byte array
+ : using a System.ComponentModel.TypeConverter
+ : and then encoded with base64 encoding.
+ -->
+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
+ <xsd:element name="root" msdata:IsDataSet="true">
+ <xsd:complexType>
+ <xsd:choice maxOccurs="unbounded">
+ <xsd:element name="metadata">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" />
+ </xsd:sequence>
+ <xsd:attribute name="name" use="required" type="xsd:string" />
+ <xsd:attribute name="type" type="xsd:string" />
+ <xsd:attribute name="mimetype" type="xsd:string" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="assembly">
+ <xsd:complexType>
+ <xsd:attribute name="alias" type="xsd:string" />
+ <xsd:attribute name="name" type="xsd:string" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="data">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="resheader">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" />
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:choice>
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:schema>
+ <resheader name="resmimetype">
+ <value>text/microsoft-resx</value>
+ </resheader>
+ <resheader name="version">
+ <value>2.0</value>
+ </resheader>
+ <resheader name="reader">
+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <resheader name="writer">
+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <data name="AccessibleName" xml:space="preserve">
+ <value>Cron parsing tool</value>
+ </data>
+ <data name="ConfigurationTitle" xml:space="preserve">
+ <value>Configuration</value>
+ </data>
+ <data name="CronDescriptionTitle" xml:space="preserve">
+ <value>Cron description</value>
+ </data>
+ <data name="CronErrorMessage" xml:space="preserve">
+ <value>Cron expression is not valid</value>
+ </data>
+ <data name="CronExpressionOptionDescription" xml:space="preserve">
+ <value>The Cron expression to parse</value>
+ </data>
+ <data name="DateFormatOptionDescription" xml:space="preserve">
+ <value>Date time fomat of generated scheduled dates</value>
+ </data>
+ <data name="Description" xml:space="preserve">
+ <value>Parse Cron expression to get scheduled dates</value>
+ </data>
+ <data name="IncludeSecondsOptionDescription" xml:space="preserve">
+ <value>Whether the Cron expression includes seconds in its definition</value>
+ </data>
+ <data name="InputTitle" xml:space="preserve">
+ <value>Cron expression to parse</value>
+ </data>
+ <data name="LongDisplayTitle" xml:space="preserve">
+ <value>Cron expression parser</value>
+ </data>
+ <data name="MaxScheduleCountOptionDescription" xml:space="preserve">
+ <value>Number of schedules to be generated</value>
+ </data>
+ <data name="OutputCountDescription" xml:space="preserve">
+ <value>How many scheduled dates needs to be generated</value>
+ </data>
+ <data name="OutputCountTitle" xml:space="preserve">
+ <value>Next scheduled dates</value>
+ </data>
+ <data name="OutputFormatDescription" xml:space="preserve">
+ <value>Date time fomat of upcoming dates</value>
+ </data>
+ <data name="OutputFormatErrorMessage" xml:space="preserve">
+ <value>Output date time format is not valid</value>
+ </data>
+ <data name="OutputFormatTitle" xml:space="preserve">
+ <value>Output format</value>
+ </data>
+ <data name="OutputScheduleTitle" xml:space="preserve">
+ <value>Next scheduled dates</value>
+ </data>
+ <data name="ShortDisplayTitle" xml:space="preserve">
+ <value>Cron parser</value>
+ </data>
+ <data name="UseSecondsDescription" xml:space="preserve">
+ <value>Whether the Cron expression should include seconds in its definition</value>
+ </data>
+ <data name="UseSecondsTitle" xml:space="preserve">
+ <value>Include seconds</value>
+ </data>
+</root>
\ No newline at end of file
diff --git a/src/app/dev/DevToys.Tools/Tools/Converters/Cron/CronParserCommandLineTool.cs b/src/app/dev/DevToys.Tools/Tools/Converters/Cron/CronParserCommandLineTool.cs
new file mode 100644
index 000000000..f7fa673d7
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Tools/Converters/Cron/CronParserCommandLineTool.cs
@@ -0,0 +1,72 @@
+using DevToys.Tools.Helpers;
+using Microsoft.Extensions.Logging;
+
+namespace DevToys.Tools.Tools.Converters.Cron;
+
+[Export(typeof(ICommandLineTool))]
+[Name("CronParser")]
+[CommandName(
+ Name = "cronparser",
+ Alias = "cron",
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Converters.Cron.CronParser",
+ DescriptionResourceName = nameof(CronParser.Description))]
+internal sealed class CronParserCommandLineTool : ICommandLineTool
+{
+ [CommandLineOption(
+ Name = "seconds",
+ Alias = "s",
+ DescriptionResourceName = nameof(CronParser.IncludeSecondsOptionDescription))]
+ internal bool IncludeSeconds { get; set; } = true;
+
+ [CommandLineOption(
+ Name = "scheduleCount",
+ Alias = "c",
+ DescriptionResourceName = nameof(CronParser.MaxScheduleCountOptionDescription))]
+ internal int MaxScheduleCount { get; set; } = 5;
+
+ [CommandLineOption(
+ Name = "dateFormat",
+ Alias = "d",
+ DescriptionResourceName = nameof(CronParser.DateFormatOptionDescription))]
+ internal string DateFormat { get; set; } = "yyyy-MM-dd ddd HH:mm:ss";
+
+ [CommandLineOption(
+ Name = "expression",
+ Alias = "e",
+ IsRequired = true,
+ DescriptionResourceName = nameof(CronParser.CronExpressionOptionDescription))]
+ internal string CronExpression { get; set; } = string.Empty;
+
+ public ValueTask<int> InvokeAsync(ILogger logger, CancellationToken cancellationToken)
+ {
+ bool succeeded
+ = CronHelper.TryGenerateNextSchedulesAndDescription(
+ CronExpression,
+ DateFormat,
+ IncludeSeconds,
+ MaxScheduleCount,
+ out string schedule,
+ out string description,
+ out string error);
+
+ if (!string.IsNullOrEmpty(description))
+ {
+ Console.WriteLine(description);
+ }
+
+ if (!string.IsNullOrEmpty(schedule))
+ {
+ Console.WriteLine(schedule);
+ }
+
+ if (succeeded)
+ {
+ return ValueTask.FromResult(0);
+ }
+ else
+ {
+ Console.Error.WriteLine(error);
+ return ValueTask.FromResult(-1);
+ }
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Tools/Converters/Cron/CronParserGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/Converters/Cron/CronParserGuiTool.cs
new file mode 100644
index 000000000..92746caae
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Tools/Converters/Cron/CronParserGuiTool.cs
@@ -0,0 +1,224 @@
+using DevToys.Tools.Helpers;
+using DevToys.Tools.Models;
+
+namespace DevToys.Tools.Tools.Converters.Cron;
+
+[Export(typeof(IGuiTool))]
+[Name("CronParser")]
+[ToolDisplayInformation(
+ IconFontName = "DevToys-Tools-Icons",
+ IconGlyph = '\u0104',
+ GroupName = PredefinedCommonToolGroupNames.Converters,
+ ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Converters.Cron.CronParser",
+ ShortDisplayTitleResourceName = nameof(CronParser.ShortDisplayTitle),
+ LongDisplayTitleResourceName = nameof(CronParser.LongDisplayTitle),
+ DescriptionResourceName = nameof(CronParser.Description),
+ AccessibleNameResourceName = nameof(CronParser.AccessibleName))]
+internal sealed class CronParserGuiTool : IGuiTool
+{
+ private const string DefaultCronWithSeconds = "* * * * * *";
+ private const string DefaultCronWithoutSeconds = "* * * * *";
+
+ /// <summary>
+ /// Whether the tool should include seconds in Cron definition
+ /// </summary>
+ internal static readonly SettingDefinition<bool> includeSeconds
+ = new(
+ name: $"{nameof(CronParserGuiTool)}.{nameof(includeSeconds)}",
+ defaultValue: true);
+
+ /// <summary>
+ /// How many lines of next occurrences the tool should generate
+ /// </summary>
+ private static readonly SettingDefinition<CronScheduleCount> outputCount
+ = new(
+ name: $"{nameof(CronParserGuiTool)}.{nameof(outputCount)}",
+ defaultValue: CronScheduleCount.Five);
+
+ private enum GridColumn
+ {
+ Stretch
+ }
+
+ private enum GridRow
+ {
+ Settings,
+ Results
+ }
+
+ private readonly ISettingsProvider _settingsProvider;
+ private readonly IUISingleLineTextInput _dateFormatText = SingleLineTextInput("cron-parser-date-format");
+ private readonly IUISingleLineTextInput _cronExpressionText = SingleLineTextInput("cron-parser-cron-expression");
+ private readonly IUISingleLineTextInput _outputCronDescriptionText = SingleLineTextInput("cron-parser-output-description");
+ private readonly IUIMultiLineTextInput _outputScheduleText = MultilineTextInput("cron-parser-output-schedule");
+ private readonly IUIInfoBar _infoBar = InfoBar("cron-parser-info-bar");
+
+ [ImportingConstructor]
+ public CronParserGuiTool(ISettingsProvider settingsProvider)
+ {
+ _settingsProvider = settingsProvider;
+
+ if (_settingsProvider.GetSetting(includeSeconds))
+ {
+ _cronExpressionText.Text(DefaultCronWithSeconds);
+ }
+ else
+ {
+ _cronExpressionText.Text(DefaultCronWithoutSeconds);
+ }
+
+ _dateFormatText.Text("yyyy-MM-dd ddd HH:mm:ss");
+
+ ParseCronExpression();
+ }
+
+ public UIToolView View
+ => new(
+ isScrollable: true,
+ Grid()
+ .ColumnLargeSpacing()
+ .RowLargeSpacing()
+ .Rows(
+ (GridRow.Settings, Auto),
+ (GridRow.Results, new UIGridLength(1, UIGridUnitType.Fraction)))
+ .Columns(
+ (GridColumn.Stretch, new UIGridLength(1, UIGridUnitType.Fraction)))
+
+ .Cells(
+ Cell(
+ GridRow.Settings,
+ GridColumn.Stretch,
+ Stack()
+ .Vertical()
+ .LargeSpacing()
+ .WithChildren(
+
+ Stack()
+ .Vertical()
+ .WithChildren(
+
+ Label().Text(CronParser.ConfigurationTitle),
+
+ Setting()
+ .Icon("FluentSystemIcons", '\uF18D')
+ .Title(CronParser.UseSecondsTitle)
+ .Description(CronParser.UseSecondsDescription)
+ .Handle(
+ _settingsProvider,
+ includeSeconds,
+ OnSettingChanged),
+
+ Setting()
+ .Icon("FluentSystemIcons", '\uf7ed')
+ .Title(CronParser.OutputCountTitle)
+ .Description(CronParser.OutputCountDescription)
+ .Handle(
+ _settingsProvider,
+ outputCount,
+ OnSettingChanged,
+ Item("5", CronScheduleCount.Five),
+ Item("10", CronScheduleCount.Ten),
+ Item("25", CronScheduleCount.TwentyFive),
+ Item("50", CronScheduleCount.Fifty),
+ Item("100", CronScheduleCount.OneHundred)),
+
+ Setting()
+ .Icon("FluentSystemIcons", '\uF7E4')
+ .Title(CronParser.OutputFormatTitle)
+ .Description(CronParser.OutputFormatDescription)
+ .InteractiveElement(
+ _dateFormatText
+ .HideCommandBar()
+ .OnTextChanged(OnCronExpressionOrDateFormatChanged))),
+
+ _cronExpressionText
+ .Title(CronParser.InputTitle)
+ .CanCopyWhenEditable()
+ .OnTextChanged(OnCronExpressionOrDateFormatChanged),
+
+ _infoBar
+ .NonClosable()
+ .Warning()
+ .Close(),
+
+ _outputCronDescriptionText
+ .Title(CronParser.CronDescriptionTitle)
+ .ReadOnly())),
+
+ Cell(
+ GridRow.Results,
+ GridColumn.Stretch,
+
+ _outputScheduleText
+ .Title(CronParser.OutputScheduleTitle)
+ .ReadOnly())));
+
+ public void OnDataReceived(string dataTypeName, object? parsedData)
+ {
+ }
+
+ private void OnSettingChanged(bool _)
+ {
+ OnSettingChanged();
+ }
+
+ private void OnSettingChanged(CronScheduleCount value)
+ {
+ OnSettingChanged();
+ }
+
+ private void OnCronExpressionOrDateFormatChanged(string _)
+ {
+ OnSettingChanged();
+ }
+
+ private void OnSettingChanged()
+ {
+ ParseCronExpression();
+ }
+
+ private void ParseCronExpression()
+ {
+ string cronExpression = _cronExpressionText.Text;
+ string dateFormat = _dateFormatText.Text;
+ bool seconds = _settingsProvider.GetSetting(includeSeconds);
+ int maxScheduleCount = GetOutputCount();
+
+ bool succeeded
+ = CronHelper.TryGenerateNextSchedulesAndDescription(
+ cronExpression,
+ dateFormat,
+ seconds,
+ maxScheduleCount,
+ out string schedule,
+ out string description,
+ out string error);
+
+ _outputCronDescriptionText.Text(description);
+ _outputScheduleText.Text(schedule);
+
+ if (succeeded)
+ {
+ _infoBar.Close();
+ }
+ else
+ {
+ _infoBar.Title(error);
+ _infoBar.Open();
+ }
+ }
+
+ private int GetOutputCount()
+ {
+ return _settingsProvider.GetSetting(outputCount) switch
+ {
+ CronScheduleCount.Five => 5,
+ CronScheduleCount.Ten => 10,
+ CronScheduleCount.TwentyFive => 25,
+ CronScheduleCount.Fifty => 50,
+ CronScheduleCount.OneHundred => 100,
+ _ => throw new NotSupportedException(),
+ };
+ }
+}
diff --git a/src/app/tests/DevToys.UnitTests/Tools/Converters/CronParserCommandLineToolTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Converters/CronParserCommandLineToolTests.cs
new file mode 100644
index 000000000..76dcb64ed
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/Converters/CronParserCommandLineToolTests.cs
@@ -0,0 +1,71 @@
+using System.IO;
+using System.Threading.Tasks;
+using DevToys.CLI;
+using DevToys.Tools.Tools.Converters.Cron;
+using Microsoft.Extensions.Logging;
+
+namespace DevToys.UnitTests.Tools.Converters;
+
+[Collection(nameof(TestParallelizationDisabled))]
+public sealed class CronParserCommandLineToolTests : MefBasedTest
+{
+ private readonly StringWriter _consoleWriter = new();
+ private readonly StringWriter _consoleErrorWriter = new();
+ private readonly CronParserCommandLineTool _tool;
+ private readonly Mock<ILogger> _loggerMock;
+
+ public CronParserCommandLineToolTests()
+ : base(typeof(CronParserCommandLineTool).Assembly)
+ {
+ _tool = (CronParserCommandLineTool)MefProvider.ImportMany<ICommandLineTool, CommandLineToolMetadata>()
+ .Single(t => t.Metadata.InternalComponentName == "CronParser").Value;
+
+ _loggerMock = new Mock<ILogger>();
+ Console.SetOut(_consoleWriter);
+ Console.SetError(_consoleErrorWriter);
+ }
+
+ [Theory(DisplayName = "Invalid cron expression")]
+ [InlineData("*")]
+ [InlineData("* * * * * * * * *")]
+ public async Task InvalidCronExpression(string input)
+ {
+ _tool.CronExpression = input;
+
+ int result = await _tool.InvokeAsync(_loggerMock.Object, default);
+ result.Should().Be(-1);
+ string consoleOutput = _consoleWriter.ToString().Trim();
+ consoleOutput.Should().Be("");
+ string consoleErrorOutput = _consoleErrorWriter.ToString().Trim();
+ consoleErrorOutput.Should().NotBe("");
+ }
+
+ [Theory(DisplayName = "Invalid date format")]
+ [InlineData("hello")]
+ public async Task InvalidDateFormat(string input)
+ {
+ _tool.CronExpression = "* * * * *";
+ _tool.DateFormat = input;
+
+ int result = await _tool.InvokeAsync(_loggerMock.Object, default);
+ result.Should().Be(-1);
+ string consoleOutput = _consoleWriter.ToString().Trim();
+ consoleOutput.Should().Be("");
+ string consoleErrorOutput = _consoleErrorWriter.ToString().Trim();
+ consoleErrorOutput.Should().NotBe("");
+ }
+
+ [Theory(DisplayName = "Parse cron correctly")]
+ [InlineData("* * * * * *", true, "Every second")]
+ [InlineData("* * * * *", false, "Every minute")]
+ public async Task ParseCron(string input, bool includeSeconds, string expectedResult)
+ {
+ _tool.CronExpression = input;
+ _tool.IncludeSeconds = includeSeconds;
+
+ int result = await _tool.InvokeAsync(_loggerMock.Object, default);
+ result.Should().Be(0);
+ string consoleOutput = _consoleWriter.ToString().Trim();
+ consoleOutput.Should().StartWith(expectedResult);
+ }
+}
diff --git a/src/app/tests/DevToys.UnitTests/Tools/Converters/CronParserGuiToolTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Converters/CronParserGuiToolTests.cs
new file mode 100644
index 000000000..613c17dd3
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/Converters/CronParserGuiToolTests.cs
@@ -0,0 +1,64 @@
+using DevToys.Core.Tools.Metadata;
+using DevToys.Tools.Tools.Converters.Cron;
+
+namespace DevToys.UnitTests.Tools.Converters;
+
+public sealed class CronParserGuiToolTests : MefBasedTest
+{
+ private readonly ISettingsProvider _settingsProvider;
+ private readonly UIToolView _toolView;
+ private readonly CronParserGuiTool _tool;
+ private readonly IUISingleLineTextInput _dateFormatText;
+ private readonly IUISingleLineTextInput _cronExpressionText;
+ private readonly IUISingleLineTextInput _outputCronDescriptionText;
+ private readonly IUIInfoBar _infoBar;
+
+ public CronParserGuiToolTests()
+ : base(typeof(CronParserGuiTool).Assembly)
+ {
+ _settingsProvider = MefProvider.Import<ISettingsProvider>();
+ _tool = (CronParserGuiTool)MefProvider.ImportMany<IGuiTool, GuiToolMetadata>()
+ .Single(t => t.Metadata.InternalComponentName == "CronParser")
+ .Value;
+
+ _toolView = _tool.View;
+
+ _dateFormatText = (IUISingleLineTextInput)_toolView.GetChildElementById("cron-parser-date-format");
+ _cronExpressionText = (IUISingleLineTextInput)_toolView.GetChildElementById("cron-parser-cron-expression");
+ _outputCronDescriptionText = (IUISingleLineTextInput)_toolView.GetChildElementById("cron-parser-output-description");
+ _infoBar = (IUIInfoBar)_toolView.GetChildElementById("cron-parser-info-bar");
+
+ _settingsProvider.SetSetting(CronParserGuiTool.includeSeconds, true);
+ }
+
+ [Theory(DisplayName = "Invalid cron expression")]
+ [InlineData("*")]
+ [InlineData("* * * * * * * * *")]
+ public void InvalidCronExpression(string input)
+ {
+ _infoBar.IsOpened.Should().BeFalse();
+ _cronExpressionText.Text(input);
+ _infoBar.IsOpened.Should().BeTrue();
+ }
+
+ [Theory(DisplayName = "Invalid date format")]
+ [InlineData("hello")]
+ public void InvalidDateFormat(string input)
+ {
+ _infoBar.IsOpened.Should().BeFalse();
+ _dateFormatText.Text(input);
+ _infoBar.IsOpened.Should().BeTrue();
+ }
+
+ [Theory(DisplayName = "Parse cron correctly")]
+ [InlineData("* * * * * *", true, "Every second")]
+ [InlineData("* * * * *", false, "Every minute")]
+ public void ParseCron(string input, bool includeSeconds, string expectedResult)
+ {
+ _settingsProvider.SetSetting(CronParserGuiTool.includeSeconds, includeSeconds);
+ _cronExpressionText.Text(input);
+
+ _infoBar.IsOpened.Should().BeFalse();
+ _outputCronDescriptionText.Text.Should().Be(expectedResult);
+ }
+}