Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for specifying separator between units when using TimeFormatter #459

Merged
merged 2 commits into from
Jan 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 29 additions & 17 deletions src/SmartFormat.Extensions.Time/TimeFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
// Licensed under the MIT license.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using SmartFormat.Core.Extensions;
using SmartFormat.Core.Formatting;
using SmartFormat.Extensions.Time.Utilities;
Expand Down Expand Up @@ -119,50 +121,60 @@
public bool TryEvaluateFormat(IFormattingInfo formattingInfo)
{
var format = formattingInfo.Format;
var formatterName = formattingInfo.Placeholder?.FormatterName ?? string.Empty;
var current = formattingInfo.CurrentValue;

// Check whether arguments can be handled by this formatter
if (format is {HasNested: true})
// Now we have to check for a nested format.
// That is the one needed for the ListFormatter
var timeParts = GetTimeParts(formattingInfo);
if (timeParts is null) return false;

if (format is { Length: > 0, HasNested: true })
{
// Auto detection calls just return a failure to evaluate
if(formatterName == string.Empty)
return false;

// throw, if the formatter has been called explicitly
throw new FormatException($"Formatter named '{formatterName}' cannot handle nested formats.");
current = timeParts; // must be an IList to work with ListFormatter

format.Items.RemoveAt(0); // That's the format for the TimeFormatter
formattingInfo.FormatAsChild(format, current);
return true;
}


formattingInfo.Write(string.Join(" ", timeParts));
return true;
}

private IList<string>? GetTimeParts(IFormattingInfo formattingInfo)
{
var format = formattingInfo.Format;
var formatterName = formattingInfo.Placeholder?.FormatterName ?? string.Empty;
var current = formattingInfo.CurrentValue;

var options = formattingInfo.FormatterOptions.Trim();
var formatText = format?.RawText.Trim() ?? string.Empty;

// Not clear, whether we can process this format
if (formatterName == string.Empty && options == string.Empty && formatText == string.Empty) return false;
if (formatterName == string.Empty && options == string.Empty && formatText == string.Empty) return null;

// In SmartFormat 2.x, the format could be included in options, with empty format.
// Using compatibility with v2, there is no reliable way to set a language as an option
var v2Compatibility = options != string.Empty && formatText == string.Empty;
var formattingOptions = v2Compatibility ? options : formatText;

var fromTime = GetFromTime(current, formattingOptions);

if (fromTime is null)
{
// Auto detection calls just return a failure to evaluate
if (formatterName == string.Empty)
return false;
return null;

Check warning on line 167 in src/SmartFormat.Extensions.Time/TimeFormatter.cs

View check run for this annotation

Codecov / codecov/patch

src/SmartFormat.Extensions.Time/TimeFormatter.cs#L167

Added line #L167 was not covered by tests

// throw, if the formatter has been called explicitly
throw new FormatException(
$"Formatter named '{formatterName}' can only process types of {nameof(TimeSpan)}, {nameof(DateTime)}, {nameof(DateTimeOffset)}");
}

var timeTextInfo = GetTimeTextInfo(formattingInfo, v2Compatibility);

var timeSpanFormatOptions = TimeSpanFormatOptionsConverter.Parse(v2Compatibility ? options : formatText);
var timeString = fromTime.Value.ToTimeString(timeSpanFormatOptions, timeTextInfo);
formattingInfo.Write(timeString);
return true;
return fromTime.Value.ToTimeParts(timeSpanFormatOptions, timeTextInfo);
}

private static TimeSpan? GetFromTime(object? current, string? formattingOptions)
Expand Down
39 changes: 27 additions & 12 deletions src/SmartFormat.Extensions.Time/Utilities/TimeSpanUtility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// Licensed under the MIT license.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

Expand Down Expand Up @@ -47,11 +48,28 @@
/// <param name="timeTextInfo">An object that supplies the text to use for output</param>
public static string ToTimeString(this TimeSpan fromTime, TimeSpanFormatOptions options,
TimeTextInfo timeTextInfo)
{
return string.Join(" ", fromTime.ToTimeParts(options, timeTextInfo));

Check warning on line 52 in src/SmartFormat.Extensions.Time/Utilities/TimeSpanUtility.cs

View check run for this annotation

Codecov / codecov/patch

src/SmartFormat.Extensions.Time/Utilities/TimeSpanUtility.cs#L52

Added line #L52 was not covered by tests
}

/// <summary>
/// <para>Turns a TimeSpan into a list of human-readable text parts.</para>
/// <para>Uses the specified timeSpanFormatOptions.</para>
/// <para>For example: "31.23:59:00.555" = "31 days 23 hours 59 minutes 0 seconds 555 milliseconds"</para>
/// </summary>
/// <param name="fromTime"></param>
/// <param name="options">
/// <para>A combination of flags that determine the formatting options.</para>
/// <para>These will be combined with the default timeSpanFormatOptions.</para>
/// </param>
/// <param name="timeTextInfo">An object that supplies the text to use for output</param>
public static IList<string> ToTimeParts(this TimeSpan fromTime, TimeSpanFormatOptions options,
TimeTextInfo timeTextInfo)
{
// If there are any missing options, merge with the defaults:
// Also, as a safeguard against missing DefaultFormatOptions, let's also merge with the AbsoluteDefaults:
options = options.Merge(DefaultFormatOptions).Merge(AbsoluteDefaults);

// Extract the individual options:
var rangeMax = options.Mask(TimeSpanFormatOptionsPresets.Range).AllFlags().Last();
_rangeMin = options.Mask(TimeSpanFormatOptionsPresets.Range).AllFlags().First();
Expand Down Expand Up @@ -84,8 +102,7 @@
}

// Create our result:
var textStarted = false;
var result = new StringBuilder();
var result = new List<string>();
for (var i = rangeMax; i >= _rangeMin; i = (TimeSpanFormatOptions) ((int) i >> 1))
{
// Determine the value and title:
Expand Down Expand Up @@ -122,21 +139,19 @@
}

//Determine whether to display this value
if (!ShouldTruncate(value, textStarted, out var displayThisValue)) continue;
if (!ShouldTruncate(value, result.Any(), out var displayThisValue)) continue;

PrepareOutput(value, i == _rangeMin, textStarted, result, ref displayThisValue);
PrepareOutput(value, i == _rangeMin, result.Any(), result, ref displayThisValue);

// Output the value:
if (displayThisValue)
{
if (textStarted) result.Append(' ');
var unitTitle = _timeTextInfo.GetUnitText(i, value, _abbreviate);
result.Append(unitTitle);
textStarted = true;
if (!string.IsNullOrEmpty(unitTitle)) result.Add(unitTitle);
}
}

return result.ToString();
return result;
}

private static bool ShouldTruncate(int value, bool textStarted, out bool displayThisValue)
Expand All @@ -163,7 +178,7 @@
return false;
}

private static void PrepareOutput(int value, bool isRangeMin, bool hasTextStarted, StringBuilder result, ref bool displayThisValue)
private static void PrepareOutput(int value, bool isRangeMin, bool hasTextStarted, List<string> result, ref bool displayThisValue)
{
// we need to display SOMETHING (even if it's zero)
if (isRangeMin && !hasTextStarted)
Expand All @@ -173,7 +188,7 @@
{
// Output the "less than 1 unit" text:
var unitTitle = _timeTextInfo!.GetUnitText(_rangeMin, 1, _abbreviate);
result.Append(_timeTextInfo.GetLessThanText(unitTitle));
result.Add(_timeTextInfo.GetLessThanText(unitTitle));
displayThisValue = false;
}
}
Expand Down Expand Up @@ -212,4 +227,4 @@
}

#endregion
}
}
2 changes: 1 addition & 1 deletion src/SmartFormat.Extensions.Time/Utilities/TimeTextInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,4 +128,4 @@ public virtual string GetUnitText(TimeSpanFormatOptions unit, int value, bool ab
_ => string.Empty
};
}
}
}
16 changes: 12 additions & 4 deletions src/SmartFormat.Tests/Extensions.Time/TimeFormatterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using SmartFormat.Core.Settings;
using SmartFormat.Extensions;
using SmartFormat.Extensions.Time.Utilities;
using SmartFormat.Tests.TestUtils;
using SmartFormat.Utilities;

namespace SmartFormat.Tests.Extensions;
Expand Down Expand Up @@ -102,11 +103,18 @@ public void Explicit_Formatter_With_Unsupported_ArgType_Should_Throw()
Assert.That(() => smart.Format("{0:time:}", DateTime.UtcNow), Throws.Exception.TypeOf<FormattingException>());
}

[Test]
public void Formatter_With_NestedFormat_Should_Throw()
[TestCase("{0:time: {:list:|, | and }}", "en", "less than 1 second")]
[TestCase("{1:time: {:list:|, | and }}", "en", "1 day, 1 hour, 1 minute and 1 second")]
[TestCase("{2:time: {:list:|, | and }}", "en", "2 hours and 2 seconds")]
[TestCase("{3:time: {:list:|, | and }}", "en", "3 days and 3 seconds")]
[TestCase("{4:time: {:list:|, | and }}", "en", "less than 1 second")]
[TestCase("{5:time: {:list:|, | and }}", "en", "5 days")]
public void NestedListFormatTest(string format, string language, string expected)
{
var args = GetArgs();
var smart = GetFormatter();
Assert.That(() => smart.Format("{0:time:{}}", DateTime.UtcNow), Throws.Exception.TypeOf<FormattingException>());
var actual = smart.Format(CultureInfo.GetCultureInfo(language), format, args);
Assert.That(actual, Is.EqualTo(expected));
}

[Test]
Expand Down Expand Up @@ -223,4 +231,4 @@ public void TimeSpanOffsetFromGivenTimeToCurrentTime(int diffHours)

SystemTime.ResetDateTime();
}
}
}