From 2d37cbf411d45d6d40f0eed6640e36aad5c37109 Mon Sep 17 00:00:00 2001 From: Christer Date: Thu, 19 Nov 2026 13:46:29 +0100 Subject: [PATCH 01/11] feat(config): New setting 'requireNonEmpty' for StringOption --- packages/config/README.md | 2 +- .../config/lib/src/config/option_types.dart | 17 +++ .../test/config/configuration_type_test.dart | 125 ++++++++++++++++++ 3 files changed, 143 insertions(+), 1 deletion(-) diff --git a/packages/config/README.md b/packages/config/README.md index 4837be96..6158075d 100644 --- a/packages/config/README.md +++ b/packages/config/README.md @@ -237,7 +237,7 @@ The library provides a rich set of typed options out of the box. All option type | Value Type | Option Class | Additional Settings | Description | |------|-------|---------------------|-------------| -| String | `StringOption` | None | String values | +| String | `StringOption` | `requireNonEmpty` | Whether a non-empty string is required | | Boolean | `FlagOption` | `negatable` | Whether the flag can be negated | | Integer | `IntOption` | `min`
`max` | Minimum allowed value
Maximum allowed value | | DateTime | `DateTimeOption` | `min`
`max` | Minimum allowed date/time
Maximum allowed date/time | diff --git a/packages/config/lib/src/config/option_types.dart b/packages/config/lib/src/config/option_types.dart index b83d8470..98b1b862 100644 --- a/packages/config/lib/src/config/option_types.dart +++ b/packages/config/lib/src/config/option_types.dart @@ -16,7 +16,13 @@ class StringParser extends ValueParser { } /// String value configuration option. +/// +/// If [requireNonEmpty] is true and the input is an empty string, +/// the validation throws a [FormatException]. class StringOption extends ConfigOptionBase { + /// When true, an empty string is rejected as an invalid value. + final bool requireNonEmpty; + const StringOption({ super.argName, super.argAliases, @@ -36,9 +42,20 @@ class StringOption extends ConfigOptionBase { super.customValidator, super.mandatory, super.hide, + this.requireNonEmpty = false, }) : super( valueParser: const StringParser(), ); + + @override + @mustCallSuper + void validateValue(final String value) { + super.validateValue(value); + + if (requireNonEmpty && value.isEmpty) { + throw const FormatException('Value must not be empty'); + } + } } /// Convenience class for multi-value configuration option for strings. diff --git a/packages/config/test/config/configuration_type_test.dart b/packages/config/test/config/configuration_type_test.dart index 611e62de..4eb8bb80 100644 --- a/packages/config/test/config/configuration_type_test.dart +++ b/packages/config/test/config/configuration_type_test.dart @@ -8,6 +8,131 @@ enum AnimalEnum { } void main() async { + group('Given a StringOption', () { + const typedOpt = StringOption(argName: 'name'); + + test('when passed an empty argument then it is parsed correctly', () async { + final config = Configuration.resolveNoExcept( + options: [typedOpt], + args: ['--name', ''], + ); + expect(config.optionalValue(typedOpt), equals('')); + }); + }); + + group('Given a StringOption that rejects empty strings', () { + const typedOpt = StringOption( + argName: 'name', + envName: 'NAME', + configKey: 'name', + requireNonEmpty: true, + ); + + test( + 'when passed a non-empty value then it is parsed correctly', + () async { + final config = Configuration.resolveNoExcept( + options: [typedOpt], + args: ['--name', 'alice'], + ); + expect(config.optionalValue(typedOpt), equals('alice')); + }, + ); + + test('when passed an empty argument then it reports an error', () async { + final config = Configuration.resolveNoExcept( + options: [typedOpt], + args: ['--name', ''], + ); + + expect(config.errors, hasLength(1)); + expect( + config.errors.single, + equals('Invalid value for option `name`: Value must not be empty'), + ); + }); + + test('when passed an empty env var then it reports an error', () async { + final config = Configuration.resolveNoExcept( + options: [typedOpt], + env: {'NAME': ''}, + ); + + expect(config.errors, hasLength(1)); + expect( + config.errors.single, + equals('Invalid value for option `name`: Value must not be empty'), + ); + }); + + test( + 'when passed an empty config value then it reports an error', + () async { + final config = Configuration.resolveNoExcept( + options: [typedOpt], + configBroker: _TestConfigBroker({'name': ''}), + ); + + expect(config.errors, hasLength(1)); + expect( + config.errors.single, + equals('Invalid value for option `name`: Value must not be empty'), + ); + }, + ); + + test( + 'when passed a whitespace value then it is parsed correctly', + () async { + final config = Configuration.resolveNoExcept( + options: [typedOpt], + args: ['--name', ' '], + ); + expect(config.optionalValue(typedOpt), equals(' ')); + }, + ); + + test('when passed no value then it stays unset', () async { + final config = Configuration.resolveNoExcept( + options: [typedOpt], + args: [], + ); + expect(config.errors, isEmpty); + expect(config.optionalValue(typedOpt), isNull); + }); + + test('when the default is empty then it reports an error', () async { + const option = StringOption( + argName: 'name', + defaultsTo: '', + requireNonEmpty: true, + ); + final config = Configuration.resolveNoExcept( + options: [option], + args: [], + ); + + expect(config.errors, hasLength(1)); + expect( + config.errors.single, + equals('Invalid value for option `name`: Value must not be empty'), + ); + }); + + test('when the default is non-empty then it is used', () async { + const option = StringOption( + argName: 'name', + defaultsTo: 'fallback', + requireNonEmpty: true, + ); + final config = Configuration.resolveNoExcept( + options: [option], + args: [], + ); + expect(config.optionalValue(option), equals('fallback')); + }); + }); + group('Given an EnumOption', () { const typedOpt = EnumOption( argName: 'animal', From 29e076a12b2fcf621085cb8ed3060a657fa083e4 Mon Sep 17 00:00:00 2001 From: Christer Date: Thu, 19 Nov 2026 14:16:17 +0100 Subject: [PATCH 02/11] feat(config): Rewrite DateTimeParser to avoid pitfalls of builtin parser DateTimeParser no longer accepts an impossible date or time and rolls it into the next valid one. 2026-02-31, hour 24, minute 60, and second 60 all fail. A fraction longer than 6 digits fails instead of being cut off. dateOnly: true accepts only a calendar date (YYYY-MM-DD or YYYYMMDD) and rejects a time. The value help is YYYY-MM-DD in that mode, and YYYY-MM-DDTHH:MM:SSZ otherwise. --- packages/config/example/main.dart | 4 +- .../config/lib/src/config/option_types.dart | 271 +++++++++++- .../config/test/config/date_parsing_test.dart | 398 ++++++++++++++---- 3 files changed, 562 insertions(+), 111 deletions(-) diff --git a/packages/config/example/main.dart b/packages/config/example/main.dart index bd4c732c..28727006 100644 --- a/packages/config/example/main.dart +++ b/packages/config/example/main.dart @@ -15,8 +15,8 @@ import 'package:config/config.dart'; /// /// Command line usage: /// ```sh -/// --until= The end timestamp of the series -/// (defaults to "2025-08-08 12:06:49.611906") +/// --until= The end timestamp of the series +/// (defaults to "2025-08-08T12:06:49.611906") /// -l, --length= The number of elements in the series /// -i, --interval= The interval between the series elements /// ``` diff --git a/packages/config/lib/src/config/option_types.dart b/packages/config/lib/src/config/option_types.dart index 98b1b862..d7219cf5 100644 --- a/packages/config/lib/src/config/option_types.dart +++ b/packages/config/lib/src/config/option_types.dart @@ -280,34 +280,267 @@ class IntOption extends ComparableValueOption { }) : super(valueParser: const IntParser()); } -/// Parses a date string into a [DateTime] object. -/// Throws [FormatException] if parsing failed. +/// Parses a calendar date or a date-time into a [DateTime]. +/// +/// Throws [FormatException] if [value] is not a valid date or date-time. +/// +/// A calendar date is `YYYY-MM-DD` or the compact form `YYYYMMDD` +/// (four-digit year, optional `+` or `-` sign). A date-time adds a +/// time, separated by `T`, a space, or one of `-_/:t`. The time is +/// `HH[:MM[:SS[(.|,)fraction]]]`, then an optional `Z` or numeric offset +/// (`±HH`, `±HHMM`, or `±HH:MM`). +/// +/// Components must be in range. `2026-02-31` does not roll into March, +/// and hour `24`, minute `60`, and second `60` are rejected. Fractional +/// seconds longer than 6 digits are rejected instead of being truncated. +/// +/// The zone follows [DateTime.parse]: a value with no offset is local, +/// and `Z` or a numeric offset is UTC. A numeric offset is converted to +/// UTC. /// -/// This implementation is more forgiving than [DateTime.parse]. -/// In addition to the standard T and space separators between -/// date and time it also allows \[-_/:t\]. +/// When [dateOnly] is true, a time part is rejected. The result is local +/// midnight on that calendar date. class DateTimeParser extends ValueParser { - const DateTimeParser(); + /// When true, only a calendar date is accepted. + final bool dateOnly; + + const DateTimeParser({this.dateOnly = false}); + + /// Date or date-time grammar, plus `-_/:t` as date/time separators. + /// The year is exactly four digits. + /// + /// Groups: year, dash, month, dash, day, hour, minute, second, + /// fraction, zone, zone sign, zone hour, zone minute. + /// The two date dashes are both present (`YYYY-MM-DD`) or both absent + /// (`YYYYMMDD`), so a longer year is not read as a four-digit year. + static final RegExp _pattern = RegExp( + r'^([+-]?\d{4})(-)?(\d\d)(-)?(\d\d)' + r'(?:[ T_/:t-](\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d+))?)?)?' + r'( ?[zZ]| ?([-+])(\d\d)(?::?(\d\d))?)?)?$', + ); @override DateTime parse(final String value) { - final val = DateTime.tryParse(value); - if (val != null) return val; - if (value.length >= 11 && '-_/:t'.contains(value[10])) { - final val = DateTime.tryParse( - '${value.substring(0, 10)}T${value.substring(11)}', + final match = _pattern.firstMatch(value); + if (match == null) { + throw FormatException(_invalid(value)); + } + + final year = int.parse(match[1]!); + final month = int.parse(match[3]!); + final day = int.parse(match[5]!); + if ((match[2] == null) != (match[4] == null)) { + throw FormatException(_invalid(value)); + } + final hourText = match[6]; + if (dateOnly && hourText != null) { + throw FormatException(_invalid(value, 'a time is not allowed')); + } + + final hour = hourText == null ? 0 : int.parse(hourText); + final minute = _number(match[7]); + final second = _number(match[8]); + final fraction = match[9]; + _validateDate(value, year, month, day); + if (hourText != null) { + _validateTime(value, hour, minute, second); + } + + final hasZone = match[10] != null; + final zoneSign = match[11]; + final zoneHour = zoneSign == null ? 0 : int.parse(match[12]!); + final zoneMinute = zoneSign == null ? 0 : _number(match[13]); + if (zoneSign != null) { + _validateOffset(value, zoneHour, zoneMinute); + } + + final fractionMicros = fraction == null + ? 0 + : _fractionMicros(value, fraction); + final millisecond = fractionMicros ~/ Duration.microsecondsPerMillisecond; + final microsecond = fractionMicros.remainder( + Duration.microsecondsPerMillisecond, + ); + final parsed = hasZone + ? DateTime.utc( + year, + month, + day, + hour, + minute, + second, + millisecond, + microsecond, + ) + : DateTime( + year, + month, + day, + hour, + minute, + second, + millisecond, + microsecond, + ); + if (!hasZone || zoneSign == null || (zoneHour == 0 && zoneMinute == 0)) { + return parsed; + } + + final offset = Duration(hours: zoneHour, minutes: zoneMinute); + return zoneSign == '-' ? parsed.add(offset) : parsed.subtract(offset); + } + + /// Formats [value] as text that [parse] accepts. + /// + /// A local date-time has no zone suffix. A UTC date-time ends in `Z`. + /// A calendar date is `YYYY-MM-DD` from [value]'s year, month, and day. + @override + String format(final DateTime value) { + if (dateOnly) return _calendarDate(value); + final zone = value.isUtc ? 'Z' : ''; + return '${_calendarDate(value)}${_timeOfDay(value)}$zone'; + } + + String _invalid(final String value, [final String? detail]) { + final kind = dateOnly ? 'date' : 'date-time'; + if (detail == null) return 'Invalid $kind "$value"'; + return 'Invalid $kind "$value": $detail'; + } + + void _validateDate( + final String value, + final int year, + final int month, + final int day, + ) { + if (month < 1 || month > 12) { + throw FormatException(_invalid(value, 'month must be between 1 and 12')); + } + final maxDay = _daysInMonth(year, month); + if (day < 1 || day > maxDay) { + throw FormatException( + _invalid(value, 'day must be between 1 and $maxDay'), + ); + } + } + + void _validateTime( + final String value, + final int hour, + final int minute, + final int second, + ) { + if (hour < 0 || hour > 23) { + throw FormatException(_invalid(value, 'hour must be between 0 and 23')); + } + if (minute < 0 || minute > 59) { + throw FormatException( + _invalid(value, 'minute must be between 0 and 59'), + ); + } + if (second < 0 || second > 59) { + throw FormatException( + _invalid(value, 'second must be between 0 and 59'), ); - if (val != null) return val; } - throw FormatException('Invalid date-time "$value"'); } + + void _validateOffset( + final String value, + final int hour, + final int minute, + ) { + if (hour < 0 || hour > 23) { + throw FormatException( + _invalid(value, 'time-zone hour must be between 0 and 23'), + ); + } + if (minute < 0 || minute > 59) { + throw FormatException( + _invalid(value, 'time-zone minute must be between 0 and 59'), + ); + } + } + + int _fractionMicros(final String value, final String digits) { + if (digits.length > 6) { + throw FormatException( + _invalid(value, 'fractional seconds must have at most 6 digits'), + ); + } + var result = 0; + for (var i = 0; i < 6; i++) { + result *= 10; + if (i < digits.length) { + result += digits.codeUnitAt(i) - 0x30; + } + } + return result; + } + + static int _number(final String? text) => text == null ? 0 : int.parse(text); + + static int _daysInMonth(final int year, final int month) { + switch (month) { + case 2: + return _isLeapYear(year) ? 29 : 28; + case 4: + case 6: + case 9: + case 11: + return 30; + default: + return 31; + } + } + + /// Proleptic Gregorian leap rule, including year 0 and negative years. + static bool _isLeapYear(final int year) { + if (year % 4 != 0) return false; + if (year % 100 != 0) return true; + return year % 400 == 0; + } + + static String _calendarDate(final DateTime value) { + final year = value.year.abs().toString().padLeft(4, '0'); + final sign = value.year < 0 ? '-' : ''; + return '$sign$year-${_two(value.month)}-${_two(value.day)}'; + } + + static String _timeOfDay(final DateTime value) { + final fraction = value.millisecond * 1000 + value.microsecond; + return 'T${_two(value.hour)}:${_two(value.minute)}:${_two(value.second)}' + '${_fraction(fraction)}'; + } + + static String _fraction(final int microseconds) { + if (microseconds == 0) return ''; + final digits = microseconds.toString().padLeft(6, '0'); + var end = digits.length; + while (end > 0 && digits[end - 1] == '0') { + end--; + } + return '.${digits.substring(0, end)}'; + } + + static String _two(final int value) => value.toString().padLeft(2, '0'); } /// Date-time value configuration option. /// -/// Supports minimum and maximum range checking. +/// Supports minimum and maximum range checking. Limits are compared as +/// instants. A parsed value with no offset is local, and one with `Z` or +/// a numeric offset is UTC. +/// +/// Set [dateOnly] to accept only a calendar date. The value help then +/// describes that date (`YYYY-MM-DD`) instead of a timestamp. class DateTimeOption extends ComparableValueOption { + /// When true, only a calendar date (`YYYY-MM-DD`) is accepted. + final bool dateOnly; + const DateTimeOption({ + final bool dateOnly = false, + final String? valueHelp, super.argName, super.argAliases, super.argAbbrev, @@ -319,7 +552,6 @@ class DateTimeOption extends ComparableValueOption { super.fromDefault, super.defaultsTo, super.helpText, - super.valueHelp = 'YYYY-MM-DDtHH:MM:SSz', super.allowedHelp, super.group, super.allowedValues, @@ -328,7 +560,14 @@ class DateTimeOption extends ComparableValueOption { super.hide, super.min, super.max, - }) : super(valueParser: const DateTimeParser()); + }) : dateOnly = dateOnly, + super( + valueParser: dateOnly + ? const DateTimeParser(dateOnly: true) + : const DateTimeParser(), + valueHelp: + valueHelp ?? (dateOnly ? 'YYYY-MM-DD' : 'YYYY-MM-DDTHH:MM:SSZ'), + ); } /// The time units supported by the [DurationParser]. diff --git a/packages/config/test/config/date_parsing_test.dart b/packages/config/test/config/date_parsing_test.dart index 41d5235c..1f9e81e7 100644 --- a/packages/config/test/config/date_parsing_test.dart +++ b/packages/config/test/config/date_parsing_test.dart @@ -3,126 +3,338 @@ import 'package:test/test.dart'; void main() { group('Given a DateTimeParser', () { - const dateTimeParser = DateTimeParser(); + const parser = DateTimeParser(); - test( - 'When calling parseDate() with empty string then it throws FormatException.', - () { - expect( - () => dateTimeParser.parse(''), - throwsA(isA()), - ); - }, - ); + group('when parsing a valid value', () { + final cases = { + '2020-01-01': DateTime(2020), + '20200101': DateTime(2020), + '+2020-01-01': DateTime(2020), + '0000-02-29': DateTime(0, 2, 29), + '-0004-02-29': DateTime(-4, 2, 29), + '2024-02-29': DateTime(2024, 2, 29), + '2000-02-29': DateTime(2000, 2, 29), + '2020-01-01 12:20:40': DateTime(2020, 1, 1, 12, 20, 40), + '2020-01-01T12:20:40Z': DateTime.utc(2020, 1, 1, 12, 20, 40), + '2020-01-01T12:20:40z': DateTime.utc(2020, 1, 1, 12, 20, 40), + '2020-01-01T12:20:40.001z': DateTime.utc(2020, 1, 1, 12, 20, 40, 1), + '2020-01-01T12:20:40.1': DateTime(2020, 1, 1, 12, 20, 40, 100), + '2020-01-01T12:20:40,123': DateTime(2020, 1, 1, 12, 20, 40, 123), + '2020-01-01T12:20:40.123456': DateTime( + 2020, + 1, + 1, + 12, + 20, + 40, + 123, + 456, + ), + '2020-01-01t12:20:40': DateTime(2020, 1, 1, 12, 20, 40), + '2020-01-01-12:20:40': DateTime(2020, 1, 1, 12, 20, 40), + '2020-01-01:12:20:40': DateTime(2020, 1, 1, 12, 20, 40), + '2020-01-01_12:20:40': DateTime(2020, 1, 1, 12, 20, 40), + '2020-01-01/12:20:40': DateTime(2020, 1, 1, 12, 20, 40), + '2020-01-01-05:00': DateTime(2020, 1, 1, 5), + '2020-01-01T12': DateTime(2020, 1, 1, 12), + '2020-01-01T12:20': DateTime(2020, 1, 1, 12, 20), + '20200101T122040Z': DateTime.utc(2020, 1, 1, 12, 20, 40), + '2020-01-01 12:20:40 Z': DateTime.utc(2020, 1, 1, 12, 20, 40), + '9999-12-31': DateTime(9999, 12, 31), + '2026-08-01T12:00:00+02:00': DateTime.utc(2026, 8, 1, 10), + '2026-08-01T12:00:00+02': DateTime.utc(2026, 8, 1, 10), + '2026-08-01T12:00:00+0200': DateTime.utc(2026, 8, 1, 10), + '2026-08-01T12:00:00-05:00': DateTime.utc(2026, 8, 1, 17), + '2026-08-01T00:30:00+02:00': DateTime.utc(2026, 7, 31, 22, 30), + '2020-01-01T12:20:40+05:30': DateTime.utc(2020, 1, 1, 6, 50, 40), + }; - test( - 'When calling parseDate() with 2020-01-01 then it successfully returns a DateTime.', - () { - expect( - dateTimeParser.parse('2020-01-01'), - equals(DateTime(2020, 1, 1)), - ); - }, - ); + for (final entry in cases.entries) { + test('then ${entry.key} is that DateTime', () { + expect(parser.parse(entry.key), entry.value); + }); + } - test( - 'When calling parseDate() with 20200101 then it successfully returns a DateTime.', - () { - expect( - dateTimeParser.parse('20200101'), - equals(DateTime(2020, 1, 1)), - ); - }, - ); + test('then a value without an offset is local', () { + final parsed = parser.parse('2026-08-01'); + expect(parsed, DateTime(2026, 8, 1)); + expect(parsed.isUtc, isFalse); + }); - test( - 'When calling parseDate() with 2020-01-01 12:20:40 then it successfully returns a DateTime.', - () { - expect( - dateTimeParser.parse('2020-01-01 12:20:40'), - equals(DateTime(2020, 1, 1, 12, 20, 40)), - ); - }, - ); + test('then Z is UTC', () { + final parsed = parser.parse('2026-08-01T00:00:00Z'); + expect(parsed, DateTime.utc(2026, 8, 1)); + expect(parsed.isUtc, isTrue); + }); + }); - test( - 'When calling parseDate() with 2020-01-01T12:20:40Z then it successfully returns a DateTime.', - () { - expect( - dateTimeParser.parse('2020-01-01T12:20:40Z'), - equals(DateTime.utc(2020, 1, 1, 12, 20, 40)), - ); - }, - ); + group('when a component is out of range', () { + final cases = { + '2026-02-31': 'day must be between 1 and 28', + '2026-02-29': 'day must be between 1 and 28', + '2026-02-30': 'day must be between 1 and 28', + '2100-02-29': 'day must be between 1 and 28', + '1900-02-29': 'day must be between 1 and 28', + '-0003-02-29': 'day must be between 1 and 28', + '2026-02-31T12:00:00Z': 'day must be between 1 and 28', + '2026-13-01': 'month must be between 1 and 12', + '2026-00-01': 'month must be between 1 and 12', + '2026-01-00': 'day must be between 1 and 31', + '2026-01-32': 'day must be between 1 and 31', + '2026-04-31': 'day must be between 1 and 30', + '2026-11-31': 'day must be between 1 and 30', + '2026-01-01T24:00:00': 'hour must be between 0 and 23', + '2026-01-01T24:00:00Z': 'hour must be between 0 and 23', + '2026-01-01T25:00:00': 'hour must be between 0 and 23', + '2026-01-01T00:60:00': 'minute must be between 0 and 59', + '2026-01-01T00:00:60': 'second must be between 0 and 59', + '2026-01-01T23:59:60Z': 'second must be between 0 and 59', + '2026-01-01T12:00:00.0000001': + 'fractional seconds must have at most 6 digits', + '2026-01-01T12:00:00.1234567': + 'fractional seconds must have at most 6 digits', + '2026-01-01T12:00:00+24:00': 'time-zone hour must be between 0 and 23', + '2026-01-01T12:00:00+05:60': + 'time-zone minute must be between 0 and 59', + }; - test( - 'When calling parseDate() with 2020-01-01T12:20:40.001z then it successfully returns a DateTime.', - () { - expect( - dateTimeParser.parse('2020-01-01T12:20:40.001z'), - equals(DateTime.utc(2020, 1, 1, 12, 20, 40, 1)), - ); - }, - ); + for (final entry in cases.entries) { + test('then ${entry.key} is rejected', () { + expect( + () => parser.parse(entry.key), + throwsA( + isA().having( + (final e) => e.message, + 'message', + 'Invalid date-time "${entry.key}": ${entry.value}', + ), + ), + ); + }); + } + }); - test( - 'When calling parseDate() with 2020-01-01t12:20:40 then it successfully returns a DateTime.', - () { + group('when the text is not a date-time', () { + for (final input in [ + '', + '2020-01-01x12:20:40', + '2020-01-01Z', + ' 2020-01-01', + '2020-01-01 ', + '2020-1-1', + '2020-01-01T12:20:40+5:00', + '2020-01-01T12:20:40+00:00:00', + '2020-01-01T', + '10000-01-01', + '10000-01-01t12:30:00', + '999999-01-01', + ]) { + test('then $input is rejected', () { + expect( + () => parser.parse(input), + throwsA( + isA().having( + (final e) => e.message, + 'message', + 'Invalid date-time "$input"', + ), + ), + ); + }); + } + }); + + group('when formatting', () { + test('then an offset value is written as UTC and round-trips', () { + final parsed = parser.parse('2026-08-01T00:30:00+02:00'); + expect(parser.format(parsed), '2026-07-31T22:30:00Z'); + expect(parser.parse(parser.format(parsed)), parsed); + }); + + test('then fractional seconds round-trip without extra zeros', () { expect( - dateTimeParser.parse('2020-01-01t12:20:40'), - equals(DateTime(2020, 1, 1, 12, 20, 40)), + parser.format(parser.parse('2020-01-01T12:20:40.001Z')), + '2020-01-01T12:20:40.001Z', ); - }, - ); - - test( - 'When calling parseDate() with 2020-01-01-12:20:40 then it successfully returns a DateTime.', - () { expect( - dateTimeParser.parse('2020-01-01-12:20:40'), - equals(DateTime(2020, 1, 1, 12, 20, 40)), + parser.format(parser.parse('2020-01-01T12:20:40.1Z')), + '2020-01-01T12:20:40.1Z', ); - }, - ); - - test( - 'When calling parseDate() with 2020-01-01:12:20:40 then it successfully returns a DateTime.', - () { expect( - dateTimeParser.parse('2020-01-01:12:20:40'), - equals(DateTime(2020, 1, 1, 12, 20, 40)), + parser.format(parser.parse('2020-01-01T12:20:40.000001Z')), + '2020-01-01T12:20:40.000001Z', ); - }, + }); + + test('then a local value is written without Z and round-trips', () { + final local = DateTime(2026, 8, 1, 12); + expect(parser.format(local), '2026-08-01T12:00:00'); + expect(parser.parse(parser.format(local)), local); + }); + + test('then a UTC value is written with Z and round-trips', () { + final utc = DateTime.utc(2026, 8, 1, 12); + expect(parser.format(utc), '2026-08-01T12:00:00Z'); + expect(parser.parse(parser.format(utc)), utc); + }); + }); + }); + + group('Given a date-only DateTimeParser', () { + const parser = DateTimeParser(dateOnly: true); + + test('when parsing YYYY-MM-DD then it is local midnight', () { + expect(parser.parse('2026-08-01'), DateTime(2026, 8, 1)); + }); + + test('when parsing a compact date then it is local midnight', () { + expect(parser.parse('20260801'), DateTime(2026, 8, 1)); + }); + + test('when parsing an impossible date then it is rejected', () { + expect( + () => parser.parse('2026-02-31'), + throwsA( + isA().having( + (final e) => e.message, + 'message', + 'Invalid date "2026-02-31": day must be between 1 and 28', + ), + ), + ); + }); + + test('when parsing a timestamp then a time is not allowed', () { + expect( + () => parser.parse('2026-08-01T00:00:00Z'), + throwsA( + isA().having( + (final e) => e.message, + 'message', + 'Invalid date "2026-08-01T00:00:00Z": a time is not allowed', + ), + ), + ); + }); + + test('when parsing a date with Z then it is rejected', () { + expect( + () => parser.parse('2026-08-01Z'), + throwsA( + isA().having( + (final e) => e.message, + 'message', + 'Invalid date "2026-08-01Z"', + ), + ), + ); + }); + + test('when formatting then only the calendar date is shown', () { + expect(parser.format(DateTime.utc(2026, 8, 1, 15)), '2026-08-01'); + }); + }); + + group('Given a DateTimeOption', () { + const timestamp = DateTimeOption(argName: 'before', mandatory: true); + const calendar = DateTimeOption( + argName: 'on', + dateOnly: true, + mandatory: true, ); + test('then the value help describes a timestamp', () { + expect(timestamp.valueHelp, 'YYYY-MM-DDTHH:MM:SSZ'); + expect(timestamp.dateOnly, isFalse); + }); + + test('then a date-only option describes a calendar date', () { + expect(calendar.valueHelp, 'YYYY-MM-DD'); + expect(calendar.dateOnly, isTrue); + expect( + calendar.valueParser, + isA().having( + (final parser) => parser.dateOnly, + 'dateOnly', + isTrue, + ), + ); + }); + + test('then an explicit value help is kept', () { + expect( + const DateTimeOption(valueHelp: 'when').valueHelp, + 'when', + ); + expect( + const DateTimeOption(dateOnly: true, valueHelp: 'when').valueHelp, + 'when', + ); + }); + test( - 'When calling parseDate() with 2020-01-01_12:20:40 then it successfully returns a DateTime.', + 'when passed a calendar date then it resolves to local midnight', () { - expect( - dateTimeParser.parse('2020-01-01_12:20:40'), - equals(DateTime(2020, 1, 1, 12, 20, 40)), + final config = Configuration.resolveNoExcept( + options: [timestamp], + args: ['--before', '2026-08-01'], ); + expect(config.errors, isEmpty); + expect(config.value(timestamp), DateTime(2026, 8, 1)); }, ); + test('when passed an impossible date then the error names the range', () { + final config = Configuration.resolveNoExcept( + options: [timestamp], + args: ['--before', '2026-02-31'], + ); + expect(config.errors, [ + 'Invalid value for option `before` : ' + 'Invalid date-time "2026-02-31": day must be between 1 and 28', + ]); + }); + test( - 'When calling parseDate() with 2020-01-01/12:20:40 then it successfully returns a DateTime.', + 'when a date-only option is passed a timestamp then it is rejected', () { - expect( - dateTimeParser.parse('2020-01-01/12:20:40'), - equals(DateTime(2020, 1, 1, 12, 20, 40)), + final config = Configuration.resolveNoExcept( + options: [calendar], + args: ['--on', '2026-08-01T00:00:00Z'], ); + expect(config.errors, [ + 'Invalid value for option `on` : ' + 'Invalid date "2026-08-01T00:00:00Z": a time is not allowed', + ]); }, ); + }); - test( - 'When calling parseDate() with 2020-01-01x12:20:40 then it throws FormatException.', - () { - expect( - () => dateTimeParser.parse('2020-01-01x12:20:40'), - throwsA(isA()), - ); - }, + group('Given a DateTimeOption with a maximum instant', () { + final option = DateTimeOption( + argName: 'before', + mandatory: true, + max: DateTime.utc(2026, 8, 1), ); + + test('when the value equals the maximum then it is accepted', () { + final config = Configuration.resolveNoExcept( + options: [option], + args: ['--before', '2026-08-01T00:00:00Z'], + ); + expect(config.value(option), DateTime.utc(2026, 8, 1)); + }); + + test('when the value is later than the maximum then it is rejected', () { + final config = Configuration.resolveNoExcept( + options: [option], + args: ['--before', '2026-08-02'], + ); + expect(config.errors, [ + 'Invalid value for option `before` : ' + '2026-08-02T00:00:00 is above the maximum ' + '(2026-08-01T00:00:00Z)', + ]); + }); }); } From 988fa490476e1b487f9194582f779ec2e6a7e61a Mon Sep 17 00:00:00 2001 From: Christer Date: Thu, 19 Nov 2026 14:19:34 +0100 Subject: [PATCH 03/11] refactor(config): Moved DateTimeOption & DurationOption to own file --- packages/config/lib/src/config/config.dart | 1 + .../lib/src/config/date_time_options.dart | 436 ++++++++++++++++++ .../config/lib/src/config/option_types.dart | 435 ----------------- 3 files changed, 437 insertions(+), 435 deletions(-) create mode 100644 packages/config/lib/src/config/date_time_options.dart diff --git a/packages/config/lib/src/config/config.dart b/packages/config/lib/src/config/config.dart index b30c7ef1..42e84f30 100644 --- a/packages/config/lib/src/config/config.dart +++ b/packages/config/lib/src/config/config.dart @@ -16,6 +16,7 @@ export 'config_source_provider.dart'; export 'configuration.dart'; export 'configuration_broker.dart'; export 'configuration_parser.dart'; +export 'date_time_options.dart'; export 'exceptions.dart'; export 'file_system_options.dart'; export 'multi_config_source.dart'; diff --git a/packages/config/lib/src/config/date_time_options.dart b/packages/config/lib/src/config/date_time_options.dart new file mode 100644 index 00000000..9269e577 --- /dev/null +++ b/packages/config/lib/src/config/date_time_options.dart @@ -0,0 +1,436 @@ +import 'option_types.dart'; +import 'options.dart'; + +/// Parses a calendar date or a date-time into a [DateTime]. +/// +/// Throws [FormatException] if [value] is not a valid date or date-time. +/// +/// A calendar date is `YYYY-MM-DD` or the compact form `YYYYMMDD` +/// (four-digit year, optional `+` or `-` sign). A date-time adds a +/// time, separated by `T`, a space, or one of `-_/:t`. The time is +/// `HH[:MM[:SS[(.|,)fraction]]]`, then an optional `Z` or numeric offset +/// (`±HH`, `±HHMM`, or `±HH:MM`). +/// +/// Components must be in range. `2026-02-31` does not roll into March, +/// and hour `24`, minute `60`, and second `60` are rejected. Fractional +/// seconds longer than 6 digits are rejected instead of being truncated. +/// +/// The zone follows [DateTime.parse]: a value with no offset is local, +/// and `Z` or a numeric offset is UTC. A numeric offset is converted to +/// UTC. +/// +/// When [dateOnly] is true, a time part is rejected. The result is local +/// midnight on that calendar date. +class DateTimeParser extends ValueParser { + /// When true, only a calendar date is accepted. + final bool dateOnly; + + const DateTimeParser({this.dateOnly = false}); + + /// Date or date-time grammar, plus `-_/:t` as date/time separators. + /// The year is exactly four digits. + /// + /// Groups: year, dash, month, dash, day, hour, minute, second, + /// fraction, zone, zone sign, zone hour, zone minute. + /// The two date dashes are both present (`YYYY-MM-DD`) or both absent + /// (`YYYYMMDD`), so a longer year is not read as a four-digit year. + static final RegExp _pattern = RegExp( + r'^([+-]?\d{4})(-)?(\d\d)(-)?(\d\d)' + r'(?:[ T_/:t-](\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d+))?)?)?' + r'( ?[zZ]| ?([-+])(\d\d)(?::?(\d\d))?)?)?$', + ); + + @override + DateTime parse(final String value) { + final match = _pattern.firstMatch(value); + if (match == null) { + throw FormatException(_invalid(value)); + } + + final year = int.parse(match[1]!); + final month = int.parse(match[3]!); + final day = int.parse(match[5]!); + if ((match[2] == null) != (match[4] == null)) { + throw FormatException(_invalid(value)); + } + final hourText = match[6]; + if (dateOnly && hourText != null) { + throw FormatException(_invalid(value, 'a time is not allowed')); + } + + final hour = hourText == null ? 0 : int.parse(hourText); + final minute = _number(match[7]); + final second = _number(match[8]); + final fraction = match[9]; + _validateDate(value, year, month, day); + if (hourText != null) { + _validateTime(value, hour, minute, second); + } + + final hasZone = match[10] != null; + final zoneSign = match[11]; + final zoneHour = zoneSign == null ? 0 : int.parse(match[12]!); + final zoneMinute = zoneSign == null ? 0 : _number(match[13]); + if (zoneSign != null) { + _validateOffset(value, zoneHour, zoneMinute); + } + + final fractionMicros = fraction == null + ? 0 + : _fractionMicros(value, fraction); + final millisecond = fractionMicros ~/ Duration.microsecondsPerMillisecond; + final microsecond = fractionMicros.remainder( + Duration.microsecondsPerMillisecond, + ); + final parsed = hasZone + ? DateTime.utc( + year, + month, + day, + hour, + minute, + second, + millisecond, + microsecond, + ) + : DateTime( + year, + month, + day, + hour, + minute, + second, + millisecond, + microsecond, + ); + if (!hasZone || zoneSign == null || (zoneHour == 0 && zoneMinute == 0)) { + return parsed; + } + + final offset = Duration(hours: zoneHour, minutes: zoneMinute); + return zoneSign == '-' ? parsed.add(offset) : parsed.subtract(offset); + } + + /// Formats [value] as text that [parse] accepts. + /// + /// A local date-time has no zone suffix. A UTC date-time ends in `Z`. + /// A calendar date is `YYYY-MM-DD` from [value]'s year, month, and day. + @override + String format(final DateTime value) { + if (dateOnly) return _calendarDate(value); + final zone = value.isUtc ? 'Z' : ''; + return '${_calendarDate(value)}${_timeOfDay(value)}$zone'; + } + + String _invalid(final String value, [final String? detail]) { + final kind = dateOnly ? 'date' : 'date-time'; + if (detail == null) return 'Invalid $kind "$value"'; + return 'Invalid $kind "$value": $detail'; + } + + void _validateDate( + final String value, + final int year, + final int month, + final int day, + ) { + if (month < 1 || month > 12) { + throw FormatException(_invalid(value, 'month must be between 1 and 12')); + } + final maxDay = _daysInMonth(year, month); + if (day < 1 || day > maxDay) { + throw FormatException( + _invalid(value, 'day must be between 1 and $maxDay'), + ); + } + } + + void _validateTime( + final String value, + final int hour, + final int minute, + final int second, + ) { + if (hour < 0 || hour > 23) { + throw FormatException(_invalid(value, 'hour must be between 0 and 23')); + } + if (minute < 0 || minute > 59) { + throw FormatException( + _invalid(value, 'minute must be between 0 and 59'), + ); + } + if (second < 0 || second > 59) { + throw FormatException( + _invalid(value, 'second must be between 0 and 59'), + ); + } + } + + void _validateOffset( + final String value, + final int hour, + final int minute, + ) { + if (hour < 0 || hour > 23) { + throw FormatException( + _invalid(value, 'time-zone hour must be between 0 and 23'), + ); + } + if (minute < 0 || minute > 59) { + throw FormatException( + _invalid(value, 'time-zone minute must be between 0 and 59'), + ); + } + } + + int _fractionMicros(final String value, final String digits) { + if (digits.length > 6) { + throw FormatException( + _invalid(value, 'fractional seconds must have at most 6 digits'), + ); + } + var result = 0; + for (var i = 0; i < 6; i++) { + result *= 10; + if (i < digits.length) { + result += digits.codeUnitAt(i) - 0x30; + } + } + return result; + } + + static int _number(final String? text) => text == null ? 0 : int.parse(text); + + static int _daysInMonth(final int year, final int month) { + switch (month) { + case 2: + return _isLeapYear(year) ? 29 : 28; + case 4: + case 6: + case 9: + case 11: + return 30; + default: + return 31; + } + } + + /// Proleptic Gregorian leap rule, including year 0 and negative years. + static bool _isLeapYear(final int year) { + if (year % 4 != 0) return false; + if (year % 100 != 0) return true; + return year % 400 == 0; + } + + static String _calendarDate(final DateTime value) { + final year = value.year.abs().toString().padLeft(4, '0'); + final sign = value.year < 0 ? '-' : ''; + return '$sign$year-${_two(value.month)}-${_two(value.day)}'; + } + + static String _timeOfDay(final DateTime value) { + final fraction = value.millisecond * 1000 + value.microsecond; + return 'T${_two(value.hour)}:${_two(value.minute)}:${_two(value.second)}' + '${_fraction(fraction)}'; + } + + static String _fraction(final int microseconds) { + if (microseconds == 0) return ''; + final digits = microseconds.toString().padLeft(6, '0'); + var end = digits.length; + while (end > 0 && digits[end - 1] == '0') { + end--; + } + return '.${digits.substring(0, end)}'; + } + + static String _two(final int value) => value.toString().padLeft(2, '0'); +} + +/// Date-time value configuration option. +/// +/// Supports minimum and maximum range checking. Limits are compared as +/// instants. A parsed value with no offset is local, and one with `Z` or +/// a numeric offset is UTC. +/// +/// Set [dateOnly] to accept only a calendar date. The value help then +/// describes that date (`YYYY-MM-DD`) instead of a timestamp. +class DateTimeOption extends ComparableValueOption { + /// When true, only a calendar date (`YYYY-MM-DD`) is accepted. + final bool dateOnly; + + const DateTimeOption({ + this.dateOnly = false, + final String? valueHelp, + super.argName, + super.argAliases, + super.argAbbrev, + super.argPos, + super.envName, + super.configKey, + super.configKeys, + super.fromCustom, + super.fromDefault, + super.defaultsTo, + super.helpText, + super.allowedHelp, + super.group, + super.allowedValues, + super.customValidator, + super.mandatory, + super.hide, + super.min, + super.max, + }) : super( + valueParser: dateOnly + ? const DateTimeParser(dateOnly: true) + : const DateTimeParser(), + valueHelp: + valueHelp ?? (dateOnly ? 'YYYY-MM-DD' : 'YYYY-MM-DDTHH:MM:SSZ'), + ); +} + +/// The time units supported by the [DurationParser]. +enum DurationUnit { + microseconds('us'), + milliseconds('ms'), + seconds('s'), + minutes('m'), + hours('h'), + days('d'); + + final String suffix; + + const DurationUnit(this.suffix); +} + +/// Parses a duration string into a [Duration] object. +/// +/// The input string must be a number followed by an optional unit +/// which is one of: seconds (s), minutes (m), hours (h), days (d), +/// milliseconds (ms), or microseconds (us). +/// If no unit is specified, the [defaultUnit] is assumed, which is in +/// seconds if not specified otherwise. +/// Examples: +/// - `10`, equivalent to `10s` +/// - `10m` +/// - `10h` +/// - `10d` +/// - `10ms` +/// - `10us` +/// +/// Throws [FormatException] if parsing failed. +class DurationParser extends ValueParser { + final DurationUnit defaultUnit; + + const DurationParser({this.defaultUnit = DurationUnit.seconds}); + + @override + Duration parse(final String value) { + // integer followed by an optional unit (s, m, h, d, ms, us) + const pattern = r'^(-?\d+)(ms|us|[smhd])?$'; + final regex = RegExp(pattern); + final match = regex.firstMatch(value); + + if (match == null || match.groupCount != 2) { + throw FormatException('Invalid duration value "$value"'); + } + final valueStr = match.group(1); + final unit = _determineUnit(match.group(2)); + final val = int.parse(valueStr ?? ''); + return switch (unit) { + DurationUnit.seconds => Duration(seconds: val), + DurationUnit.minutes => Duration(minutes: val), + DurationUnit.hours => Duration(hours: val), + DurationUnit.days => Duration(days: val), + DurationUnit.milliseconds => Duration(milliseconds: val), + DurationUnit.microseconds => Duration(microseconds: val), + }; + } + + DurationUnit _determineUnit(final String? suffix) { + if (suffix == null) return defaultUnit; + + return DurationUnit.values.firstWhere( + (final unit) => unit.suffix == suffix, + orElse: () => throw FormatException('Invalid duration unit "$suffix".'), + ); + } + + @override + String format(final Duration value) { + if (value == Duration.zero) return '0s'; + + final sign = value.isNegative ? '-' : ''; + final d = _unitStr(value.inDays, null, 'd'); + final h = _unitStr(value.inHours, 24, 'h'); + final m = _unitStr(value.inMinutes, 60, 'm'); + final s = _unitStr(value.inSeconds, 60, 's'); + final ms = _unitStr(value.inMilliseconds, 1000, 'ms'); + final us = _unitStr(value.inMicroseconds, 1000, 'us'); + + return '$sign$d$h$m$s$ms$us'; + } + + static String _unitStr(final int value, final int? mod, final String unit) { + final absValue = value.abs(); + if (mod == null) { + return absValue > 0 ? '$absValue$unit' : ''; + } + return absValue % mod > 0 ? '${absValue.remainder(mod)}$unit' : ''; + } +} + +/// Duration value configuration option. +/// +/// Supports minimum and maximum range checking. +class DurationOption extends ComparableValueOption { + const DurationOption({ + super.argName, + super.argAliases, + super.argAbbrev, + super.argPos, + super.envName, + super.configKey, + super.configKeys, + super.fromCustom, + super.fromDefault, + super.defaultsTo, + super.helpText, + super.valueHelp = 'integer[us|ms|s|m|h|d]', + super.allowedHelp, + super.group, + super.allowedValues, + super.customValidator, + super.mandatory, + super.hide, + super.min, + super.max, + }) : super(valueParser: const DurationParser()); + + /// Creates a DurationOption with a custom duration parser, + /// e.g. with a specific default unit. + const DurationOption.custom({ + required final DurationParser parser, + super.argName, + super.argAliases, + super.argAbbrev, + super.argPos, + super.envName, + super.configKey, + super.configKeys, + super.fromCustom, + super.fromDefault, + super.defaultsTo, + super.helpText, + super.valueHelp = 'integer[us|ms|s|m|h|d]', + super.allowedHelp, + super.group, + super.allowedValues, + super.customValidator, + super.mandatory, + super.hide, + super.min, + super.max, + }) : super(valueParser: parser); +} diff --git a/packages/config/lib/src/config/option_types.dart b/packages/config/lib/src/config/option_types.dart index d7219cf5..26b19ce2 100644 --- a/packages/config/lib/src/config/option_types.dart +++ b/packages/config/lib/src/config/option_types.dart @@ -279,438 +279,3 @@ class IntOption extends ComparableValueOption { super.max, }) : super(valueParser: const IntParser()); } - -/// Parses a calendar date or a date-time into a [DateTime]. -/// -/// Throws [FormatException] if [value] is not a valid date or date-time. -/// -/// A calendar date is `YYYY-MM-DD` or the compact form `YYYYMMDD` -/// (four-digit year, optional `+` or `-` sign). A date-time adds a -/// time, separated by `T`, a space, or one of `-_/:t`. The time is -/// `HH[:MM[:SS[(.|,)fraction]]]`, then an optional `Z` or numeric offset -/// (`±HH`, `±HHMM`, or `±HH:MM`). -/// -/// Components must be in range. `2026-02-31` does not roll into March, -/// and hour `24`, minute `60`, and second `60` are rejected. Fractional -/// seconds longer than 6 digits are rejected instead of being truncated. -/// -/// The zone follows [DateTime.parse]: a value with no offset is local, -/// and `Z` or a numeric offset is UTC. A numeric offset is converted to -/// UTC. -/// -/// When [dateOnly] is true, a time part is rejected. The result is local -/// midnight on that calendar date. -class DateTimeParser extends ValueParser { - /// When true, only a calendar date is accepted. - final bool dateOnly; - - const DateTimeParser({this.dateOnly = false}); - - /// Date or date-time grammar, plus `-_/:t` as date/time separators. - /// The year is exactly four digits. - /// - /// Groups: year, dash, month, dash, day, hour, minute, second, - /// fraction, zone, zone sign, zone hour, zone minute. - /// The two date dashes are both present (`YYYY-MM-DD`) or both absent - /// (`YYYYMMDD`), so a longer year is not read as a four-digit year. - static final RegExp _pattern = RegExp( - r'^([+-]?\d{4})(-)?(\d\d)(-)?(\d\d)' - r'(?:[ T_/:t-](\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d+))?)?)?' - r'( ?[zZ]| ?([-+])(\d\d)(?::?(\d\d))?)?)?$', - ); - - @override - DateTime parse(final String value) { - final match = _pattern.firstMatch(value); - if (match == null) { - throw FormatException(_invalid(value)); - } - - final year = int.parse(match[1]!); - final month = int.parse(match[3]!); - final day = int.parse(match[5]!); - if ((match[2] == null) != (match[4] == null)) { - throw FormatException(_invalid(value)); - } - final hourText = match[6]; - if (dateOnly && hourText != null) { - throw FormatException(_invalid(value, 'a time is not allowed')); - } - - final hour = hourText == null ? 0 : int.parse(hourText); - final minute = _number(match[7]); - final second = _number(match[8]); - final fraction = match[9]; - _validateDate(value, year, month, day); - if (hourText != null) { - _validateTime(value, hour, minute, second); - } - - final hasZone = match[10] != null; - final zoneSign = match[11]; - final zoneHour = zoneSign == null ? 0 : int.parse(match[12]!); - final zoneMinute = zoneSign == null ? 0 : _number(match[13]); - if (zoneSign != null) { - _validateOffset(value, zoneHour, zoneMinute); - } - - final fractionMicros = fraction == null - ? 0 - : _fractionMicros(value, fraction); - final millisecond = fractionMicros ~/ Duration.microsecondsPerMillisecond; - final microsecond = fractionMicros.remainder( - Duration.microsecondsPerMillisecond, - ); - final parsed = hasZone - ? DateTime.utc( - year, - month, - day, - hour, - minute, - second, - millisecond, - microsecond, - ) - : DateTime( - year, - month, - day, - hour, - minute, - second, - millisecond, - microsecond, - ); - if (!hasZone || zoneSign == null || (zoneHour == 0 && zoneMinute == 0)) { - return parsed; - } - - final offset = Duration(hours: zoneHour, minutes: zoneMinute); - return zoneSign == '-' ? parsed.add(offset) : parsed.subtract(offset); - } - - /// Formats [value] as text that [parse] accepts. - /// - /// A local date-time has no zone suffix. A UTC date-time ends in `Z`. - /// A calendar date is `YYYY-MM-DD` from [value]'s year, month, and day. - @override - String format(final DateTime value) { - if (dateOnly) return _calendarDate(value); - final zone = value.isUtc ? 'Z' : ''; - return '${_calendarDate(value)}${_timeOfDay(value)}$zone'; - } - - String _invalid(final String value, [final String? detail]) { - final kind = dateOnly ? 'date' : 'date-time'; - if (detail == null) return 'Invalid $kind "$value"'; - return 'Invalid $kind "$value": $detail'; - } - - void _validateDate( - final String value, - final int year, - final int month, - final int day, - ) { - if (month < 1 || month > 12) { - throw FormatException(_invalid(value, 'month must be between 1 and 12')); - } - final maxDay = _daysInMonth(year, month); - if (day < 1 || day > maxDay) { - throw FormatException( - _invalid(value, 'day must be between 1 and $maxDay'), - ); - } - } - - void _validateTime( - final String value, - final int hour, - final int minute, - final int second, - ) { - if (hour < 0 || hour > 23) { - throw FormatException(_invalid(value, 'hour must be between 0 and 23')); - } - if (minute < 0 || minute > 59) { - throw FormatException( - _invalid(value, 'minute must be between 0 and 59'), - ); - } - if (second < 0 || second > 59) { - throw FormatException( - _invalid(value, 'second must be between 0 and 59'), - ); - } - } - - void _validateOffset( - final String value, - final int hour, - final int minute, - ) { - if (hour < 0 || hour > 23) { - throw FormatException( - _invalid(value, 'time-zone hour must be between 0 and 23'), - ); - } - if (minute < 0 || minute > 59) { - throw FormatException( - _invalid(value, 'time-zone minute must be between 0 and 59'), - ); - } - } - - int _fractionMicros(final String value, final String digits) { - if (digits.length > 6) { - throw FormatException( - _invalid(value, 'fractional seconds must have at most 6 digits'), - ); - } - var result = 0; - for (var i = 0; i < 6; i++) { - result *= 10; - if (i < digits.length) { - result += digits.codeUnitAt(i) - 0x30; - } - } - return result; - } - - static int _number(final String? text) => text == null ? 0 : int.parse(text); - - static int _daysInMonth(final int year, final int month) { - switch (month) { - case 2: - return _isLeapYear(year) ? 29 : 28; - case 4: - case 6: - case 9: - case 11: - return 30; - default: - return 31; - } - } - - /// Proleptic Gregorian leap rule, including year 0 and negative years. - static bool _isLeapYear(final int year) { - if (year % 4 != 0) return false; - if (year % 100 != 0) return true; - return year % 400 == 0; - } - - static String _calendarDate(final DateTime value) { - final year = value.year.abs().toString().padLeft(4, '0'); - final sign = value.year < 0 ? '-' : ''; - return '$sign$year-${_two(value.month)}-${_two(value.day)}'; - } - - static String _timeOfDay(final DateTime value) { - final fraction = value.millisecond * 1000 + value.microsecond; - return 'T${_two(value.hour)}:${_two(value.minute)}:${_two(value.second)}' - '${_fraction(fraction)}'; - } - - static String _fraction(final int microseconds) { - if (microseconds == 0) return ''; - final digits = microseconds.toString().padLeft(6, '0'); - var end = digits.length; - while (end > 0 && digits[end - 1] == '0') { - end--; - } - return '.${digits.substring(0, end)}'; - } - - static String _two(final int value) => value.toString().padLeft(2, '0'); -} - -/// Date-time value configuration option. -/// -/// Supports minimum and maximum range checking. Limits are compared as -/// instants. A parsed value with no offset is local, and one with `Z` or -/// a numeric offset is UTC. -/// -/// Set [dateOnly] to accept only a calendar date. The value help then -/// describes that date (`YYYY-MM-DD`) instead of a timestamp. -class DateTimeOption extends ComparableValueOption { - /// When true, only a calendar date (`YYYY-MM-DD`) is accepted. - final bool dateOnly; - - const DateTimeOption({ - final bool dateOnly = false, - final String? valueHelp, - super.argName, - super.argAliases, - super.argAbbrev, - super.argPos, - super.envName, - super.configKey, - super.configKeys, - super.fromCustom, - super.fromDefault, - super.defaultsTo, - super.helpText, - super.allowedHelp, - super.group, - super.allowedValues, - super.customValidator, - super.mandatory, - super.hide, - super.min, - super.max, - }) : dateOnly = dateOnly, - super( - valueParser: dateOnly - ? const DateTimeParser(dateOnly: true) - : const DateTimeParser(), - valueHelp: - valueHelp ?? (dateOnly ? 'YYYY-MM-DD' : 'YYYY-MM-DDTHH:MM:SSZ'), - ); -} - -/// The time units supported by the [DurationParser]. -enum DurationUnit { - microseconds('us'), - milliseconds('ms'), - seconds('s'), - minutes('m'), - hours('h'), - days('d'); - - final String suffix; - - const DurationUnit(this.suffix); -} - -/// Parses a duration string into a [Duration] object. -/// -/// The input string must be a number followed by an optional unit -/// which is one of: seconds (s), minutes (m), hours (h), days (d), -/// milliseconds (ms), or microseconds (us). -/// If no unit is specified, the [defaultUnit] is assumed, which is in -/// seconds if not specified otherwise. -/// Examples: -/// - `10`, equivalent to `10s` -/// - `10m` -/// - `10h` -/// - `10d` -/// - `10ms` -/// - `10us` -/// -/// Throws [FormatException] if parsing failed. -class DurationParser extends ValueParser { - final DurationUnit defaultUnit; - - const DurationParser({this.defaultUnit = DurationUnit.seconds}); - - @override - Duration parse(final String value) { - // integer followed by an optional unit (s, m, h, d, ms, us) - const pattern = r'^(-?\d+)(ms|us|[smhd])?$'; - final regex = RegExp(pattern); - final match = regex.firstMatch(value); - - if (match == null || match.groupCount != 2) { - throw FormatException('Invalid duration value "$value"'); - } - final valueStr = match.group(1); - final unit = _determineUnit(match.group(2)); - final val = int.parse(valueStr ?? ''); - return switch (unit) { - DurationUnit.seconds => Duration(seconds: val), - DurationUnit.minutes => Duration(minutes: val), - DurationUnit.hours => Duration(hours: val), - DurationUnit.days => Duration(days: val), - DurationUnit.milliseconds => Duration(milliseconds: val), - DurationUnit.microseconds => Duration(microseconds: val), - }; - } - - DurationUnit _determineUnit(final String? suffix) { - if (suffix == null) return defaultUnit; - - return DurationUnit.values.firstWhere( - (final unit) => unit.suffix == suffix, - orElse: () => throw FormatException('Invalid duration unit "$suffix".'), - ); - } - - @override - String format(final Duration value) { - if (value == Duration.zero) return '0s'; - - final sign = value.isNegative ? '-' : ''; - final d = _unitStr(value.inDays, null, 'd'); - final h = _unitStr(value.inHours, 24, 'h'); - final m = _unitStr(value.inMinutes, 60, 'm'); - final s = _unitStr(value.inSeconds, 60, 's'); - final ms = _unitStr(value.inMilliseconds, 1000, 'ms'); - final us = _unitStr(value.inMicroseconds, 1000, 'us'); - - return '$sign$d$h$m$s$ms$us'; - } - - static String _unitStr(final int value, final int? mod, final String unit) { - final absValue = value.abs(); - if (mod == null) { - return absValue > 0 ? '$absValue$unit' : ''; - } - return absValue % mod > 0 ? '${absValue.remainder(mod)}$unit' : ''; - } -} - -/// Duration value configuration option. -/// -/// Supports minimum and maximum range checking. -class DurationOption extends ComparableValueOption { - const DurationOption({ - super.argName, - super.argAliases, - super.argAbbrev, - super.argPos, - super.envName, - super.configKey, - super.configKeys, - super.fromCustom, - super.fromDefault, - super.defaultsTo, - super.helpText, - super.valueHelp = 'integer[us|ms|s|m|h|d]', - super.allowedHelp, - super.group, - super.allowedValues, - super.customValidator, - super.mandatory, - super.hide, - super.min, - super.max, - }) : super(valueParser: const DurationParser()); - - /// Creates a DurationOption with a custom duration parser, - /// e.g. with a specific default unit. - const DurationOption.custom({ - required final DurationParser parser, - super.argName, - super.argAliases, - super.argAbbrev, - super.argPos, - super.envName, - super.configKey, - super.configKeys, - super.fromCustom, - super.fromDefault, - super.defaultsTo, - super.helpText, - super.valueHelp = 'integer[us|ms|s|m|h|d]', - super.allowedHelp, - super.group, - super.allowedValues, - super.customValidator, - super.mandatory, - super.hide, - super.min, - super.max, - }) : super(valueParser: parser); -} From a7dc7117760e0dbff557a9c034c53480c88df5bb Mon Sep 17 00:00:00 2001 From: Christer Date: Thu, 19 Nov 2026 14:26:31 +0100 Subject: [PATCH 04/11] test(config): Verifiy that several appearances of single option are rejected Closes Configuration.resolve accepts multiple appearances of an option that is not a multi-option Fixes #137 --- .../arg_parser/scan_and_parse_args_test.dart | 32 +++++++ .../test/config/configuration_test.dart | 86 +++++++++++++++++++ 2 files changed, 118 insertions(+) diff --git a/packages/config/test/config/arg_parser/scan_and_parse_args_test.dart b/packages/config/test/config/arg_parser/scan_and_parse_args_test.dart index dcd8d5ad..47281120 100644 --- a/packages/config/test/config/arg_parser/scan_and_parse_args_test.dart +++ b/packages/config/test/config/arg_parser/scan_and_parse_args_test.dart @@ -596,6 +596,38 @@ void main() { ); }); + test('when it is specified twice with attached values ' + 'then the error is recorded', () { + expect( + parse(['--name=ada', '--name=grace']).errors, + ['Option --name cannot be specified more than once'], + ); + }); + + test('when it is specified twice with attached values ' + 'then the first value is kept', () { + expect( + parse(['--name=ada', '--name=grace']).regularOptions[name], + 'ada', + ); + }); + + test('when a separate value is followed by an attached value ' + 'then the error is recorded', () { + expect( + parse(['--name', 'ada', '--name=grace']).errors, + ['Option --name cannot be specified more than once'], + ); + }); + + test('when a separate value is followed by an attached value ' + 'then the first value is kept', () { + expect( + parse(['--name', 'ada', '--name=grace']).regularOptions[name], + 'ada', + ); + }); + test('when the name and an alias are both passed ' 'then the error is recorded', () { expect( diff --git a/packages/config/test/config/configuration_test.dart b/packages/config/test/config/configuration_test.dart index 64978e65..3ae94a69 100644 --- a/packages/config/test/config/configuration_test.dart +++ b/packages/config/test/config/configuration_test.dart @@ -214,6 +214,92 @@ void main() async { ); }); + group('Given a single-value date option', () { + const from = DateTimeOption( + argName: 'from', + dateOnly: true, + mandatory: true, + ); + + test( + 'when --from value is repeated ' + 'then it reports that the option cannot be specified more than once', + () { + expect( + () => Configuration.resolve( + options: [from], + args: ['--from', '2026-01-01', '--from', '2026-02-01'], + ), + throwsA( + isA().having( + (final e) => e.message, + 'message', + 'Option --from cannot be specified more than once.', + ), + ), + ); + }, + ); + + test( + 'when --from=value is repeated ' + 'then it reports that the option cannot be specified more than once', + () { + expect( + () => Configuration.resolve( + options: [from], + args: ['--from=2026-01-01', '--from=2026-02-01'], + ), + throwsA( + isA().having( + (final e) => e.message, + 'message', + 'Option --from cannot be specified more than once.', + ), + ), + ); + }, + ); + + test( + 'when a separate value is followed by an attached value ' + 'then it reports that the option cannot be specified more than once', + () { + expect( + () => Configuration.resolve( + options: [from], + args: ['--from', '2026-01-01', '--from=2026-02-01'], + ), + throwsA( + isA().having( + (final e) => e.message, + 'message', + 'Option --from cannot be specified more than once.', + ), + ), + ); + }, + ); + + test('when --from value appears once then that date is used', () { + final config = Configuration.resolve( + options: [from], + args: ['--from', '2026-01-01'], + ); + + expect(config.value(from), DateTime(2026, 1, 1)); + }); + + test('when --from=value appears once then that date is used', () { + final config = Configuration.resolve( + options: [from], + args: ['--from=2026-02-01'], + ); + + expect(config.value(from), DateTime(2026, 2, 1)); + }); + }); + group('Given a configuration option with a defaultsTo value', () { const projectIdOpt = StringOption( argName: 'project', From 8ad46bcaaff0cc4e61449e2e507fd92012c93bf9 Mon Sep 17 00:00:00 2001 From: Christer Date: Thu, 19 Nov 2026 14:55:05 +0100 Subject: [PATCH 05/11] feat(config): Option definer can control default value formatting Give the command option definer more control over the formatting of the default value help text Fixes #80 --- .../lib/src/command/usage/options_usage.dart | 2 +- .../lib/src/config/arg_parser_bridge.dart | 34 ++++- .../lib/src/config/date_time_options.dart | 3 + .../lib/src/config/file_system_options.dart | 2 + .../config/lib/src/config/option_types.dart | 6 + packages/config/lib/src/config/options.dart | 20 ++- .../test/command/usage_formatting_test.dart | 138 ++++++++++++++++++ .../test/config/configuration_test.dart | 83 +++++++++++ 8 files changed, 282 insertions(+), 6 deletions(-) diff --git a/packages/config/lib/src/command/usage/options_usage.dart b/packages/config/lib/src/command/usage/options_usage.dart index c918b7f3..c791fa1e 100644 --- a/packages/config/lib/src/command/usage/options_usage.dart +++ b/packages/config/lib/src/command/usage/options_usage.dart @@ -265,7 +265,7 @@ class OptionsUsageGenerator { final format = option.multiParser.elementParser.format; return def.any((final element) => format(element) == value); } - return option.defaultValueString() == value; + return option.valueParser.format(def) == value; } } diff --git a/packages/config/lib/src/config/arg_parser_bridge.dart b/packages/config/lib/src/config/arg_parser_bridge.dart index 4139782c..061275ee 100644 --- a/packages/config/lib/src/config/arg_parser_bridge.dart +++ b/packages/config/lib/src/config/arg_parser_bridge.dart @@ -149,9 +149,7 @@ void _addToArgParser(final OptionDefinition option, final ArgParser argParser) { opt.multiParser.elementParser.format, ), allowedHelp: opt.allowedHelp, - defaultsTo: opt.defaultValue()?.map( - opt.multiParser.elementParser.format, - ), + defaultsTo: _legacyMultiDefaults(opt), hide: opt.hide, splitCommas: opt.multiParser.separator == ',', aliases: opt.argAliases ?? const [], @@ -165,10 +163,38 @@ void _addToArgParser(final OptionDefinition option, final ArgParser argParser) { valueHelp: opt.valueHelpString(), allowed: opt.allowedValues?.map(opt.valueParser.format), allowedHelp: opt.allowedHelp, - defaultsTo: opt.defaultValueString(), + defaultsTo: _legacyDefaultString(opt), mandatory: opt.mandatory, hide: opt.hide, aliases: opt.argAliases ?? const [], ); } } + +/// Default string stored on the legacy parser. +/// +/// Allowed values are matched against the formatted default to mark it, +/// so [ConfigOptionBase.defaultValueString] is used only when there is +/// nothing to match. +String? _legacyDefaultString(final ConfigOptionBase opt) { + if (opt.allowedValues != null || opt.allowedHelp != null) { + final value = opt.defaultValue(); + if (value == null) return null; + return opt.valueParser.format(value); + } + return opt.defaultValueString(); +} + +/// Default list stored on the legacy parser for a [MultiOption]. +/// +/// Same rule as [_legacyDefaultString]: a custom help string replaces the +/// formatted defaults only when no allowed value would be marked from them. +Iterable? _legacyMultiDefaults(final MultiOption opt) { + final marksAllowed = + opt.allowedElementValues != null || opt.allowedHelp != null; + final help = opt.defaultValueHelp; + if (!marksAllowed && help != null && opt.defaultValue() != null) { + return [help]; + } + return opt.defaultValue()?.map(opt.multiParser.elementParser.format); +} diff --git a/packages/config/lib/src/config/date_time_options.dart b/packages/config/lib/src/config/date_time_options.dart index 9269e577..bf83b397 100644 --- a/packages/config/lib/src/config/date_time_options.dart +++ b/packages/config/lib/src/config/date_time_options.dart @@ -272,6 +272,7 @@ class DateTimeOption extends ComparableValueOption { super.fromCustom, super.fromDefault, super.defaultsTo, + super.defaultValueHelp, super.helpText, super.allowedHelp, super.group, @@ -396,6 +397,7 @@ class DurationOption extends ComparableValueOption { super.fromCustom, super.fromDefault, super.defaultsTo, + super.defaultValueHelp, super.helpText, super.valueHelp = 'integer[us|ms|s|m|h|d]', super.allowedHelp, @@ -422,6 +424,7 @@ class DurationOption extends ComparableValueOption { super.fromCustom, super.fromDefault, super.defaultsTo, + super.defaultValueHelp, super.helpText, super.valueHelp = 'integer[us|ms|s|m|h|d]', super.allowedHelp, diff --git a/packages/config/lib/src/config/file_system_options.dart b/packages/config/lib/src/config/file_system_options.dart index 93ffd810..1df40434 100644 --- a/packages/config/lib/src/config/file_system_options.dart +++ b/packages/config/lib/src/config/file_system_options.dart @@ -46,6 +46,7 @@ class DirOption extends ConfigOptionBase { super.fromCustom, super.fromDefault, super.defaultsTo, + super.defaultValueHelp, super.helpText, super.valueHelp, super.group, @@ -128,6 +129,7 @@ class FileOption extends ConfigOptionBase { super.fromCustom, super.fromDefault, super.defaultsTo, + super.defaultValueHelp, super.helpText, super.valueHelp, super.group, diff --git a/packages/config/lib/src/config/option_types.dart b/packages/config/lib/src/config/option_types.dart index 26b19ce2..08374a24 100644 --- a/packages/config/lib/src/config/option_types.dart +++ b/packages/config/lib/src/config/option_types.dart @@ -34,6 +34,7 @@ class StringOption extends ConfigOptionBase { super.fromCustom, super.fromDefault, super.defaultsTo, + super.defaultValueHelp, super.helpText, super.valueHelp, super.allowedHelp, @@ -71,6 +72,7 @@ class MultiStringOption extends MultiOption { super.fromCustom, super.fromDefault, super.defaultsTo, + super.defaultValueHelp, super.helpText, super.valueHelp, super.allowedHelp, @@ -94,6 +96,7 @@ class MultiStringOption extends MultiOption { super.fromCustom, super.fromDefault, super.defaultsTo, + super.defaultValueHelp, super.helpText, super.valueHelp, super.allowedHelp, @@ -161,6 +164,7 @@ class EnumOption extends ConfigOptionBase { super.fromCustom, super.fromDefault, super.defaultsTo, + super.defaultValueHelp, super.helpText, super.valueHelp, super.allowedHelp, @@ -209,6 +213,7 @@ class ComparableValueOption extends ConfigOptionBase { super.fromCustom, super.fromDefault, super.defaultsTo, + super.defaultValueHelp, super.helpText, super.valueHelp, super.allowedHelp, @@ -267,6 +272,7 @@ class IntOption extends ComparableValueOption { super.fromCustom, super.fromDefault, super.defaultsTo, + super.defaultValueHelp, super.helpText, super.valueHelp = 'integer', super.allowedHelp, diff --git a/packages/config/lib/src/config/options.dart b/packages/config/lib/src/config/options.dart index 17edd9f3..642dbba7 100644 --- a/packages/config/lib/src/config/options.dart +++ b/packages/config/lib/src/config/options.dart @@ -206,6 +206,12 @@ abstract class ConfigOptionBase implements OptionDefinition { final V Function()? fromDefault; final V? defaultsTo; + /// Usage text for the default, shown instead of the formatted actual default value. + /// Set this when the actual default value is not what users should read. + /// For example, a computed directory can be shown as `/lib/` rather + /// than its absolute path. + final String? defaultValueHelp; + final String? helpText; final String? valueHelp; final Map? allowedHelp; @@ -228,6 +234,7 @@ abstract class ConfigOptionBase implements OptionDefinition { this.fromCustom, this.fromDefault, this.defaultsTo, + this.defaultValueHelp, this.helpText, this.valueHelp, this.allowedHelp, @@ -252,10 +259,13 @@ abstract class ConfigOptionBase implements OptionDefinition { return (df != null ? df() : defaultsTo); } + /// The default value as shown in usage. + /// [defaultValueHelp] when set, otherwise the formatted [defaultValue]. + /// Returns null when the option has no default. String? defaultValueString() { final defValue = defaultValue(); if (defValue == null) return null; - return valueParser.format(defValue); + return defaultValueHelp ?? valueParser.format(defValue); } String? valueHelpString() { @@ -320,6 +330,12 @@ abstract class ConfigOptionBase implements OptionDefinition { "Mandatory options can't have default values", ); } + if (defaultValueHelp != null && fromDefault == null && defaultsTo == null) { + throw OptionDefinitionError( + this, + 'defaultValueHelp requires defaultsTo or fromDefault', + ); + } } /// Validates the parsed value, @@ -666,6 +682,7 @@ class FlagOption extends ConfigOptionBase { super.fromCustom, super.fromDefault, super.defaultsTo, + super.defaultValueHelp, super.helpText, super.valueHelp, super.group, @@ -757,6 +774,7 @@ class MultiOption extends ConfigOptionBase> { super.fromCustom, super.fromDefault, super.defaultsTo, + super.defaultValueHelp, super.helpText, super.valueHelp, super.allowedHelp, diff --git a/packages/config/test/command/usage_formatting_test.dart b/packages/config/test/command/usage_formatting_test.dart index 2c99a6f4..6785d3c3 100644 --- a/packages/config/test/command/usage_formatting_test.dart +++ b/packages/config/test/command/usage_formatting_test.dart @@ -1,3 +1,5 @@ +import 'dart:io'; + import 'package:config/command.dart'; import 'package:config/config.dart'; import 'package:test/test.dart'; @@ -1105,6 +1107,142 @@ void main() { ); }); + group('Given an option with custom default help text', () { + late Command command; + + setUp(() { + command = _command( + name: 'write', + description: 'Write output', + options: const [ + StringOption( + argName: 'output-dir', + argAbbrev: 'd', + helpText: 'Override the directory to write the Dart source file to', + defaultsTo: '/Users/myself/dev/cli_tools/packages/cli_tools', + defaultValueHelp: '/packages/cli_tools/', + ), + ], + ); + _runner(subcommands: [command]); + }); + + test('when reading usage then the custom text is shown', () { + expect( + command.usage, + _usage(const [ + 'Write output', + '', + 'Usage: tool write [--output-dir=]', + '', + 'Options:', + '-d, --output-dir ' + 'Override the directory to write the Dart source file to', + ' (defaults to /packages/cli_tools/)', + '', + 'Run "tool help" to see global options.', + ]), + ); + }); + }); + + group('Given a directory option with custom default help text', () { + late DirOption option; + + setUp(() { + option = DirOption( + argName: 'output-dir', + defaultsTo: Directory('/tmp/generated'), + defaultValueHelp: '/lib/', + ); + }); + + test('when reading usage then the path description is shown', () { + final command = _command( + name: 'write', + description: 'Write output', + options: [option], + ); + _runner(subcommands: [command]); + + expect(command.usage, contains('(defaults to /lib/)')); + expect(command.usage, isNot(contains('/tmp/generated'))); + }); + + test( + 'when resolving with no arguments then the directory is unchanged', + () { + final config = Configuration.resolve( + options: [option], + args: const [], + ); + + expect(config.value(option).path, '/tmp/generated'); + }, + ); + }); + + group('Given a ranged option with custom default help text', () { + late Command command; + + setUp(() { + command = _command( + name: 'play', + description: 'Play a card', + options: const [ + IntOption( + argName: 'count', + helpText: 'How many', + defaultsTo: 2, + min: 1, + max: 10, + defaultValueHelp: 'a pair', + ), + ], + ); + _runner(subcommands: [command]); + }); + + test('when reading usage then the range uses the custom text', () { + expect( + command.usage, + contains('values: [1 - 10] (defaults to a pair)'), + ); + }); + }); + + group('Given allowed values and custom default help text', () { + late Command command; + + setUp(() { + command = _command( + name: 'play', + description: 'Play a card', + options: const [ + StringOption( + argName: 'suit', + helpText: 'Like in cards', + defaultsTo: 'clubs', + defaultValueHelp: 'the black suit', + allowedValues: ['spades', 'clubs', 'hearts', 'diamonds'], + ), + ], + ); + _runner(subcommands: [command]); + }); + + test( + 'when reading usage then the formatted default stays marked in the list', + () { + expect( + command.usage, + contains('values: [spades, clubs (default), hearts, diamonds]'), + ); + expect(command.usage, isNot(contains('the black suit'))); + }, + ); + }); + group('Given an option with a range and a default', () { late Command command; diff --git a/packages/config/test/config/configuration_test.dart b/packages/config/test/config/configuration_test.dart index 3ae94a69..7827a5aa 100644 --- a/packages/config/test/config/configuration_test.dart +++ b/packages/config/test/config/configuration_test.dart @@ -364,6 +364,89 @@ void main() async { }); }); + group('Given an option with defaultValueHelp', () { + const projectIdOpt = StringOption( + argName: 'project', + defaultsTo: 'constDefaultValue', + defaultValueHelp: '', + ); + + test('then the usage text replaces the formatted default', () { + expect(projectIdOpt.defaultValueString(), ''); + }); + + test('when getting the usage then the custom text is shown', () { + expect( + [projectIdOpt].usage, + equals('--project (defaults to "")'), + ); + }); + + test('when resolving with no arguments then the value is unchanged', () { + final config = Configuration.resolve( + options: [projectIdOpt], + args: const [], + ); + + expect(config.value(projectIdOpt), 'constDefaultValue'); + }); + }); + + group('Given defaultValueHelp and allowed values', () { + const suit = StringOption( + argName: 'suit', + helpText: 'Like in cards', + defaultsTo: 'clubs', + defaultValueHelp: 'the black suit', + allowedValues: ['spades', 'clubs', 'hearts', 'diamonds'], + ); + + test('when getting the usage then the formatted default stays marked', () { + expect( + [suit].usage, + equals( + '--suit Like in cards\n' + ' [spades, clubs (default), hearts, diamonds]', + ), + ); + }); + }); + + group('Given defaultValueHelp without a default value', () { + const option = StringOption( + argName: 'name', + defaultValueHelp: '', + ); + + test('when validating the definition then it throws', () { + expect( + () => validateOptions([option]), + throwsA( + isA().having( + (final e) => e.message, + 'message', + 'defaultValueHelp requires defaultsTo or fromDefault', + ), + ), + ); + }); + }); + + group('Given a multi option with defaultValueHelp', () { + const suits = MultiStringOption( + argName: 'suit', + defaultsTo: ['clubs', 'hearts'], + defaultValueHelp: 'the red and black suits', + ); + + test('when getting the usage then the custom text is shown', () { + expect( + [suits].usage, + equals('--suit (defaults to "the red and black suits")'), + ); + }); + }); + group('Given a configuration option with multiple configKeys', () { const projectIdOpt = StringOption( configKeys: ['primary:/projectId', 'fallback:/projectId'], From e6e3c5cd75df3beb69a4d703de93724ae10ab2e3 Mon Sep 17 00:00:00 2001 From: Christer Date: Thu, 19 Nov 2026 15:11:02 +0100 Subject: [PATCH 06/11] feat(config): DoubleOption added --- packages/config/README.md | 1 + .../config/lib/src/config/option_types.dart | 39 ++++++ .../test/config/configuration_type_test.dart | 117 ++++++++++++++++++ 3 files changed, 157 insertions(+) diff --git a/packages/config/README.md b/packages/config/README.md index 6158075d..b7848745 100644 --- a/packages/config/README.md +++ b/packages/config/README.md @@ -240,6 +240,7 @@ The library provides a rich set of typed options out of the box. All option type | String | `StringOption` | `requireNonEmpty` | Whether a non-empty string is required | | Boolean | `FlagOption` | `negatable` | Whether the flag can be negated | | Integer | `IntOption` | `min`
`max` | Minimum allowed value
Maximum allowed value | +| Double | `DoubleOption` | `min`
`max` | Minimum allowed value
Maximum allowed value | | DateTime | `DateTimeOption` | `min`
`max` | Minimum allowed date/time
Maximum allowed date/time | | Duration | `DurationOption` | `min`
`max` | Minimum allowed duration
Maximum allowed duration | | Any Enum | `EnumOption` | None | Typed enum values | diff --git a/packages/config/lib/src/config/option_types.dart b/packages/config/lib/src/config/option_types.dart index 08374a24..0b45a5b3 100644 --- a/packages/config/lib/src/config/option_types.dart +++ b/packages/config/lib/src/config/option_types.dart @@ -285,3 +285,42 @@ class IntOption extends ComparableValueOption { super.max, }) : super(valueParser: const IntParser()); } + +class DoubleParser extends ValueParser { + const DoubleParser(); + + @override + double parse(final String value) { + return double.parse(value); + } +} + +/// Floating-point value configuration option. +/// +/// Supports minimum and maximum range checking. +/// An integer string such as `1` is parsed as `1.0`. +class DoubleOption extends ComparableValueOption { + const DoubleOption({ + super.argName, + super.argAliases, + super.argAbbrev, + super.argPos, + super.envName, + super.configKey, + super.configKeys, + super.fromCustom, + super.fromDefault, + super.defaultsTo, + super.defaultValueHelp, + super.helpText, + super.valueHelp = 'number', + super.allowedHelp, + super.group, + super.allowedValues, + super.customValidator, + super.mandatory, + super.hide, + super.min, + super.max, + }) : super(valueParser: const DoubleParser()); +} diff --git a/packages/config/test/config/configuration_type_test.dart b/packages/config/test/config/configuration_type_test.dart index 4eb8bb80..b5e41e44 100644 --- a/packages/config/test/config/configuration_type_test.dart +++ b/packages/config/test/config/configuration_type_test.dart @@ -331,6 +331,123 @@ void main() async { ); }); + group('Given a DoubleOption', () { + const typedOpt = DoubleOption( + argName: 'number', + mandatory: true, + ); + + test( + 'when passed a fractional value then it is parsed correctly', + () async { + final config = Configuration.resolveNoExcept( + options: [typedOpt], + args: ['--number', '1.5'], + env: {}, + ); + expect(config.value(typedOpt), equals(1.5)); + }, + ); + + test( + 'when passed an integer value then it is parsed as a double', + () async { + final config = Configuration.resolveNoExcept( + options: [typedOpt], + args: ['--number', '2'], + env: {}, + ); + final value = config.value(typedOpt); + expect(value, equals(2.0)); + expect(value, isA()); + }, + ); + + test( + 'when passed a valid negative value then it is parsed correctly', + () async { + final config = Configuration.resolveNoExcept( + options: [typedOpt], + args: ['--number', '-1.25'], + env: {}, + ); + expect(config.value(typedOpt), equals(-1.25)); + }, + ); + + test('when passed a non-number value then it reports an error', () async { + final config = Configuration.resolveNoExcept( + options: [typedOpt], + args: ['--number', 'unicorn'], + env: {}, + ); + + expect(config.errors, hasLength(1)); + expect( + config.errors.single, + contains('Invalid value for option `number` '), + ); + }); + }); + + group('Given a ranged DoubleOption', () { + const typedOpt = DoubleOption( + argName: 'number', + mandatory: true, + min: 0.5, + max: 1.5, + ); + + test('when passed a valid value then it is parsed correctly', () async { + final config = Configuration.resolveNoExcept( + options: [typedOpt], + args: ['--number', '1.0'], + env: {}, + ); + expect(config.value(typedOpt), equals(1.0)); + }); + + test( + 'when passed a value less than the range then it reports an error', + () async { + final config = Configuration.resolveNoExcept( + options: [typedOpt], + args: ['--number', '0.4'], + env: {}, + ); + + expect(config.errors, hasLength(1)); + expect( + config.errors.single, + equals( + 'Invalid value for option `number` : ' + '0.4 is below the minimum (0.5)', + ), + ); + }, + ); + + test( + 'when passed a value greater than the range then it reports an error', + () async { + final config = Configuration.resolveNoExcept( + options: [typedOpt], + args: ['--number', '1.6'], + env: {}, + ); + + expect(config.errors, hasLength(1)); + expect( + config.errors.single, + equals( + 'Invalid value for option `number` : ' + '1.6 is above the maximum (1.5)', + ), + ); + }, + ); + }); + group('Given a ranged DurationOption', () { const typedOpt = DurationOption( argName: 'duration', From 4e0ae45601f34fd13a1ff3d38e975c28ed55b3c6 Mon Sep 17 00:00:00 2001 From: Christer Date: Thu, 19 Nov 2026 15:43:10 +0100 Subject: [PATCH 07/11] fix(config): Keep default help text out of parsed values Custom default text is for usage. Parsers that read arguments keep the configured default, and flag usage can show that text without changing the boolean result. Co-authored-by: Cursor --- .../lib/src/config/arg_parser_bridge.dart | 91 +++++++++++++++---- .../test/config/configuration_test.dart | 73 +++++++++++++++ 2 files changed, 148 insertions(+), 16 deletions(-) diff --git a/packages/config/lib/src/config/arg_parser_bridge.dart b/packages/config/lib/src/config/arg_parser_bridge.dart index 061275ee..0b27c3ee 100644 --- a/packages/config/lib/src/config/arg_parser_bridge.dart +++ b/packages/config/lib/src/config/arg_parser_bridge.dart @@ -86,7 +86,12 @@ class OldParsedArgs implements ParsedArgs { String oldUsage(final Iterable options) { final parser = ArgParser(); final argOptions = options.where((final o) => o.option.argName != null); - addOptionsToParser(argOptions, parser, addGroupSeparators: true); + addOptionsToParser( + argOptions, + parser, + addGroupSeparators: true, + usageOnly: true, + ); return parser.usage; } @@ -94,8 +99,12 @@ void addOptionsToParser( final Iterable argNameOpts, final ArgParser argParser, { final bool addGroupSeparators = false, + final bool usageOnly = false, }) { - final receiver = _ArgParserOptionCollection(argParser); + final receiver = _ArgParserOptionCollection( + argParser, + usageOnly: usageOnly, + ); addOptionsToReceiver( argNameOpts, receiver, @@ -105,8 +114,12 @@ void addOptionsToParser( class _ArgParserOptionCollection implements OptionReceiver { final ArgParser argParser; + final bool usageOnly; - _ArgParserOptionCollection(this.argParser); + _ArgParserOptionCollection( + this.argParser, { + required this.usageOnly, + }); @override void addSeparator(final String separator) { @@ -115,11 +128,15 @@ class _ArgParserOptionCollection implements OptionReceiver { @override void addOption(final OptionDefinition option) { - _addToArgParser(option, argParser); + _addToArgParser(option, argParser, usageOnly: usageOnly); } } -void _addToArgParser(final OptionDefinition option, final ArgParser argParser) { +void _addToArgParser( + final OptionDefinition option, + final ArgParser argParser, { + required final bool usageOnly, +}) { final opt = option.option; final argName = opt.argName; if (argName == null) { @@ -131,8 +148,8 @@ void _addToArgParser(final OptionDefinition option, final ArgParser argParser) { argParser.addFlag( argName, abbr: opt.argAbbrev, - help: opt.helpText, - defaultsTo: opt.defaultValue(), + help: _flagHelp(opt, usageOnly: usageOnly), + defaultsTo: _flagDefault(opt, usageOnly: usageOnly), negatable: opt.negatable, hideNegatedUsage: opt.hideNegatedUsage, hide: opt.hide, @@ -149,7 +166,7 @@ void _addToArgParser(final OptionDefinition option, final ArgParser argParser) { opt.multiParser.elementParser.format, ), allowedHelp: opt.allowedHelp, - defaultsTo: _legacyMultiDefaults(opt), + defaultsTo: _legacyMultiDefaults(opt, usageOnly: usageOnly), hide: opt.hide, splitCommas: opt.multiParser.separator == ',', aliases: opt.argAliases ?? const [], @@ -163,7 +180,7 @@ void _addToArgParser(final OptionDefinition option, final ArgParser argParser) { valueHelp: opt.valueHelpString(), allowed: opt.allowedValues?.map(opt.valueParser.format), allowedHelp: opt.allowedHelp, - defaultsTo: _legacyDefaultString(opt), + defaultsTo: _legacyDefaultString(opt, usageOnly: usageOnly), mandatory: opt.mandatory, hide: opt.hide, aliases: opt.argAliases ?? const [], @@ -171,29 +188,71 @@ void _addToArgParser(final OptionDefinition option, final ArgParser argParser) { } } +/// Help text for a flag on the legacy parser. +/// +/// [package:args] prints `(defaults to on)` from the boolean default and has +/// no slot for custom default text. Usage-only parsers put +/// [FlagOption.defaultValueHelp] in the help and omit that boolean line. +/// Parsers used to parse arguments keep [FlagOption.helpText] unchanged. +String? _flagHelp(final FlagOption opt, {required final bool usageOnly}) { + final help = opt.helpText; + if (!usageOnly) return help; + final custom = opt.defaultValueHelp; + if (custom == null) return help; + final line = '(defaults to $custom)'; + if (help == null || help.isEmpty) return line; + return '$help\n$line'; +} + +/// Boolean default stored on the legacy parser. +/// +/// A usage-only parser passes null when custom default text is shown, so +/// [package:args] does not also print `(defaults to on)`. A parser that +/// reads arguments keeps the real boolean. +bool? _flagDefault(final FlagOption opt, {required final bool usageOnly}) { + if (usageOnly && opt.defaultValueHelp != null) return null; + return opt.defaultValue(); +} + /// Default string stored on the legacy parser. /// /// Allowed values are matched against the formatted default to mark it, -/// so [ConfigOptionBase.defaultValueString] is used only when there is -/// nothing to match. -String? _legacyDefaultString(final ConfigOptionBase opt) { +/// so a custom help string is used only when there is nothing to match. +/// That help string is usage text: parsers that read arguments store the +/// formatted value instead, so an omitted option does not come back as the +/// help text. +String? _legacyDefaultString( + final ConfigOptionBase opt, { + required final bool usageOnly, +}) { if (opt.allowedValues != null || opt.allowedHelp != null) { final value = opt.defaultValue(); if (value == null) return null; return opt.valueParser.format(value); } + if (!usageOnly) { + final value = opt.defaultValue(); + if (value == null) return null; + return opt.valueParser.format(value); + } return opt.defaultValueString(); } /// Default list stored on the legacy parser for a [MultiOption]. /// -/// Same rule as [_legacyDefaultString]: a custom help string replaces the -/// formatted defaults only when no allowed value would be marked from them. -Iterable? _legacyMultiDefaults(final MultiOption opt) { +/// Same rule as [_legacyDefaultString]: custom help text is only stored on +/// a parser that exists to render usage. +Iterable? _legacyMultiDefaults( + final MultiOption opt, { + required final bool usageOnly, +}) { final marksAllowed = opt.allowedElementValues != null || opt.allowedHelp != null; final help = opt.defaultValueHelp; - if (!marksAllowed && help != null && opt.defaultValue() != null) { + if (usageOnly && + !marksAllowed && + help != null && + opt.defaultValue() != null) { return [help]; } return opt.defaultValue()?.map(opt.multiParser.elementParser.format); diff --git a/packages/config/test/config/configuration_test.dart b/packages/config/test/config/configuration_test.dart index 7827a5aa..65d495db 100644 --- a/packages/config/test/config/configuration_test.dart +++ b/packages/config/test/config/configuration_test.dart @@ -1,3 +1,4 @@ +import 'package:args/args.dart'; import 'package:config/config.dart'; import 'package:test/test.dart'; @@ -390,6 +391,17 @@ void main() async { expect(config.value(projectIdOpt), 'constDefaultValue'); }); + + test( + 'when the legacy parser reads no arguments ' + 'then the result is the configured default', + () { + final parser = ArgParser(); + prepareOptionsForParsing([projectIdOpt], parser); + + expect(parser.parse(const []).option('project'), 'constDefaultValue'); + }, + ); }); group('Given defaultValueHelp and allowed values', () { @@ -445,6 +457,67 @@ void main() async { equals('--suit (defaults to "the red and black suits")'), ); }); + + test( + 'when the legacy parser reads no arguments ' + 'then the result is the configured defaults', + () { + final parser = ArgParser(); + prepareOptionsForParsing([suits], parser); + + expect( + parser.parse(const []).multiOption('suit'), + ['clubs', 'hearts'], + ); + }, + ); + }); + + group('Given a flag with defaultValueHelp', () { + const color = FlagOption( + argName: 'color', + helpText: 'Colorize output', + defaultsTo: true, + defaultValueHelp: 'when stdout is a terminal', + ); + + test('when getting the usage then the custom text is shown', () { + expect( + [color].usage, + equals( + '--[no-]color Colorize output\n' + ' (defaults to when stdout is a terminal)', + ), + ); + }); + + test( + 'when the legacy parser reads no arguments then the flag stays on', + () { + final parser = ArgParser(); + prepareOptionsForParsing([color], parser); + + expect(parser.parse(const []).flag('color'), isTrue); + }, + ); + }); + + group('Given a flag without defaultValueHelp', () { + const verbose = FlagOption( + argName: 'verbose', + helpText: 'Emit more logs', + defaultsTo: true, + ); + + test('when getting the usage then the boolean default is shown', () { + expect( + [verbose].usage, + equals( + '--[no-]verbose Emit more logs\n' + ' (defaults to on)', + ), + ); + }); }); group('Given a configuration option with multiple configKeys', () { From f31773e95bf0736ee433f7e521aea7a564c36ea3 Mon Sep 17 00:00:00 2001 From: Christer Date: Thu, 19 Nov 2026 15:43:54 +0100 Subject: [PATCH 08/11] fix(config): Treat whole numbers and signed zero as doubles Configuration files store 2 as an integer, which is the same value as 2.0. Bounds also reject NaN and accept -0.0 at a zero limit. Co-authored-by: Cursor --- .../config/lib/src/config/option_types.dart | 44 ++++- packages/config/lib/src/config/options.dart | 16 +- .../test/config/configuration_type_test.dart | 151 ++++++++++++++++++ 3 files changed, 206 insertions(+), 5 deletions(-) diff --git a/packages/config/lib/src/config/option_types.dart b/packages/config/lib/src/config/option_types.dart index 0b45a5b3..b1f43f3e 100644 --- a/packages/config/lib/src/config/option_types.dart +++ b/packages/config/lib/src/config/option_types.dart @@ -232,20 +232,31 @@ class ComparableValueOption extends ConfigOptionBase { super.validateValue(value); final mininum = min; - if (mininum != null && value.compareTo(mininum) < 0) { + if (mininum != null && valueIsBelow(value, mininum)) { throw FormatException( '${valueParser.format(value)} is below the minimum ' '(${valueParser.format(mininum)})', ); } final maximum = max; - if (maximum != null && value.compareTo(maximum) > 0) { + if (maximum != null && valueIsAbove(value, maximum)) { throw FormatException( '${valueParser.format(value)} is above the maximum ' '(${valueParser.format(maximum)})', ); } } + + /// Whether [value] is ordered before [limit]. + /// + /// [DoubleOption] uses numeric comparison so that `-0.0` and `0.0`, + /// which compare equal, are both inside a bound of zero. + @protected + bool valueIsBelow(final V value, final V limit) => value.compareTo(limit) < 0; + + /// Whether [value] is ordered after [limit]. + @protected + bool valueIsAbove(final V value, final V limit) => value.compareTo(limit) > 0; } class IntParser extends ValueParser { @@ -298,7 +309,11 @@ class DoubleParser extends ValueParser { /// Floating-point value configuration option. /// /// Supports minimum and maximum range checking. -/// An integer string such as `1` is parsed as `1.0`. +/// An integer string such as `1` is parsed as `1.0`. A whole number stored +/// as an integer by a configuration file is the same value. +/// +/// `NaN` is rejected when [min] or [max] is set, because it is not ordered +/// relative to a bound. `-0.0` is inside a bound of `0.0`. class DoubleOption extends ComparableValueOption { const DoubleOption({ super.argName, @@ -323,4 +338,27 @@ class DoubleOption extends ComparableValueOption { super.min, super.max, }) : super(valueParser: const DoubleParser()); + + /// JSON and YAML store whole numbers as integers. + @override + double? valueFromConfig(final Object value) { + if (value is int) return value.toDouble(); + return super.valueFromConfig(value); + } + + @override + void validateValue(final double value) { + if (value.isNaN && (min != null || max != null)) { + throw FormatException( + '${valueParser.format(value)} is not a valid number', + ); + } + super.validateValue(value); + } + + @override + bool valueIsBelow(final double value, final double limit) => value < limit; + + @override + bool valueIsAbove(final double value, final double limit) => value > limit; } diff --git a/packages/config/lib/src/config/options.dart b/packages/config/lib/src/config/options.dart index 642dbba7..8f5dcd59 100644 --- a/packages/config/lib/src/config/options.dart +++ b/packages/config/lib/src/config/options.dart @@ -566,6 +566,17 @@ abstract class ConfigOptionBase implements OptionDefinition { ); } + /// A configuration value that is already a [V], or null when it is not. + /// + /// String values are parsed separately. Subclasses may accept other native + /// values that mean the same thing, such as an integer for a double option. + /// A null return is reported as a type error. + @protected + V? valueFromConfig(final Object value) { + if (value is V) return value as V; + return null; + } + OptionResolutionImpl? _resolveConfigValue( final Configuration cfg, final ConfigurationBroker? configBroker, @@ -586,9 +597,10 @@ abstract class ConfigOptionBase implements OptionDefinition { source: ValueSourceType.config, ); } - if (value is V) { + final native = valueFromConfig(value); + if (native != null) { return OptionResolutionImpl( - value: value as V, + value: native, source: ValueSourceType.config, ); } diff --git a/packages/config/test/config/configuration_type_test.dart b/packages/config/test/config/configuration_type_test.dart index b5e41e44..079f9d48 100644 --- a/packages/config/test/config/configuration_type_test.dart +++ b/packages/config/test/config/configuration_type_test.dart @@ -448,6 +448,157 @@ void main() async { ); }); + group('Given a DoubleOption read from configuration', () { + const typedOpt = DoubleOption( + argName: 'number', + configKey: 'number', + mandatory: true, + ); + + test('when the value is an integer then it resolves as a double', () { + final config = Configuration.resolveNoExcept( + options: [typedOpt], + configBroker: _TestConfigBroker({'number': 2}), + ); + + final value = config.value(typedOpt); + expect(value, equals(2.0)); + expect(value, isA()); + }); + + test('when the value is a double then it resolves as that double', () { + final config = Configuration.resolveNoExcept( + options: [typedOpt], + configBroker: _TestConfigBroker({'number': 1.5}), + ); + + expect(config.value(typedOpt), equals(1.5)); + }); + + test('when the value is a string integer then it resolves as a double', () { + final config = Configuration.resolveNoExcept( + options: [typedOpt], + configBroker: _TestConfigBroker({'number': '2'}), + ); + + expect(config.value(typedOpt), equals(2.0)); + }); + + test('when the value is not a number then it reports a type error', () { + final config = Configuration.resolveNoExcept( + options: [typedOpt], + configBroker: _TestConfigBroker({'number': true}), + ); + + expect(config.errors, [ + 'option `number` value true is of type bool, not double.', + ]); + }); + }); + + group('Given a DoubleOption with only a minimum', () { + const typedOpt = DoubleOption( + argName: 'number', + mandatory: true, + min: 0.0, + ); + + test('when passed negative zero then it is accepted', () { + final config = Configuration.resolveNoExcept( + options: [typedOpt], + args: ['--number', '-0.0'], + ); + + expect(config.errors, isEmpty); + expect(config.value(typedOpt), equals(0.0)); + }); + + test('when passed positive zero then it is accepted', () { + final config = Configuration.resolveNoExcept( + options: [typedOpt], + args: ['--number', '0.0'], + ); + + expect(config.value(typedOpt), equals(0.0)); + }); + + test('when passed a negative value then it is below the minimum', () { + final config = Configuration.resolveNoExcept( + options: [typedOpt], + args: ['--number', '-0.1'], + ); + + expect(config.errors, [ + 'Invalid value for option `number` : ' + '-0.1 is below the minimum (0.0)', + ]); + }); + + test('when passed NaN then it is rejected', () { + final config = Configuration.resolveNoExcept( + options: [typedOpt], + args: ['--number', 'NaN'], + ); + + expect(config.errors, [ + 'Invalid value for option `number` : ' + 'NaN is not a valid number', + ]); + }); + + test('when the default is NaN then it is rejected', () { + const nanDefault = DoubleOption( + argName: 'number', + defaultsTo: double.nan, + min: 0.0, + ); + final config = Configuration.resolveNoExcept( + options: [nanDefault], + args: const [], + ); + + expect(config.errors, [ + 'Invalid value for option `number` : ' + 'NaN is not a valid number', + ]); + }); + }); + + group('Given a DoubleOption with only a maximum of zero', () { + const typedOpt = DoubleOption( + argName: 'number', + mandatory: true, + max: 0.0, + ); + + test('when passed negative zero then it is accepted', () { + final config = Configuration.resolveNoExcept( + options: [typedOpt], + args: ['--number', '-0.0'], + ); + + expect(config.errors, isEmpty); + expect(config.value(typedOpt), equals(0.0)); + }); + }); + + group('Given a DoubleOption with no numeric bounds', () { + const typedOpt = DoubleOption( + argName: 'number', + mandatory: true, + ); + + test('when passed NaN then it is accepted', () { + final config = Configuration.resolveNoExcept( + options: [typedOpt], + args: ['--number', 'NaN'], + ); + + expect(config.errors, isEmpty); + expect(config.value(typedOpt).isNaN, isTrue); + }); + }); + group('Given a ranged DurationOption', () { const typedOpt = DurationOption( argName: 'duration', From ff6b43aa2285644e00633d0002bc43b50f4dd29e Mon Sep 17 00:00:00 2001 From: Christer Date: Thu, 19 Nov 2026 15:45:00 +0100 Subject: [PATCH 09/11] fix(config): Keep date-only values on their calendar date A date-only option is the calendar date at local midnight. Allowed values match that date, including a UTC date offered by completion, and a local midnight that would fall on another day is rejected. Co-authored-by: Cursor --- .../lib/src/config/date_time_options.dart | 54 ++++++- packages/config/lib/src/config/options.dart | 34 +++- .../config/test/config/completion_test.dart | 13 ++ .../config/test/config/date_parsing_test.dart | 146 ++++++++++++++++++ 4 files changed, 243 insertions(+), 4 deletions(-) diff --git a/packages/config/lib/src/config/date_time_options.dart b/packages/config/lib/src/config/date_time_options.dart index bf83b397..7c4b4555 100644 --- a/packages/config/lib/src/config/date_time_options.dart +++ b/packages/config/lib/src/config/date_time_options.dart @@ -20,7 +20,8 @@ import 'options.dart'; /// UTC. /// /// When [dateOnly] is true, a time part is rejected. The result is local -/// midnight on that calendar date. +/// midnight on that calendar date. A local midnight that falls on a different +/// calendar day, which can happen when a time zone skips that day, is rejected. class DateTimeParser extends ValueParser { /// When true, only a calendar date is accepted. final bool dateOnly; @@ -103,6 +104,15 @@ class DateTimeParser extends ValueParser { millisecond, microsecond, ); + if (dateOnly && + (parsed.year != year || parsed.month != month || parsed.day != day)) { + throw FormatException( + _invalid( + value, + 'that calendar date does not exist in the local time zone', + ), + ); + } if (!hasZone || zoneSign == null || (zoneHour == 0 && zoneMinute == 0)) { return parsed; } @@ -253,8 +263,12 @@ class DateTimeParser extends ValueParser { /// instants. A parsed value with no offset is local, and one with `Z` or /// a numeric offset is UTC. /// -/// Set [dateOnly] to accept only a calendar date. The value help then -/// describes that date (`YYYY-MM-DD`) instead of a timestamp. +/// Set [dateOnly] to accept only a calendar date. The value is local +/// midnight on that date, including a typed default or configuration value: +/// its year, month, and day are kept and the time of day is not part of the +/// value. Allowed values match on that calendar date, so a UTC date and a +/// local date on the same day are the same choice. The value help then +/// describes the date (`YYYY-MM-DD`) instead of a timestamp. class DateTimeOption extends ComparableValueOption { /// When true, only a calendar date (`YYYY-MM-DD`) is accepted. final bool dateOnly; @@ -289,6 +303,40 @@ class DateTimeOption extends ComparableValueOption { valueHelp: valueHelp ?? (dateOnly ? 'YYYY-MM-DD' : 'YYYY-MM-DDTHH:MM:SSZ'), ); + + /// Date-only allowed values are calendar dates. A UTC midnight and the + /// local midnight of the same day are the same choice, which is also what + /// completion offers. + @override + bool allowsValue(final DateTime value) { + if (!dateOnly) return super.allowsValue(value); + final allowed = allowedValues; + if (allowed == null) return true; + return allowed.any( + (final candidate) => + candidate.year == value.year && + candidate.month == value.month && + candidate.day == value.day, + ); + } + + /// A date-only value is local midnight on its calendar date. + /// + /// Throws [FormatException] when that local midnight would fall on a + /// different day. + @override + DateTime canonicalize(final DateTime value) { + if (!dateOnly) return value; + final local = DateTime(value.year, value.month, value.day); + if (local.year != value.year || + local.month != value.month || + local.day != value.day) { + throw FormatException( + '${valueParser.format(value)} does not exist in the local time zone', + ); + } + return local; + } } /// The time units supported by the [DurationParser]. diff --git a/packages/config/lib/src/config/options.dart b/packages/config/lib/src/config/options.dart index 8f5dcd59..47949889 100644 --- a/packages/config/lib/src/config/options.dart +++ b/packages/config/lib/src/config/options.dart @@ -338,6 +338,24 @@ abstract class ConfigOptionBase implements OptionDefinition { } } + /// Whether [value] is one of [allowedValues]. + /// + /// True when [allowedValues] is not set. Subclasses may match by a + /// coarser rule than [Object.==], for example a calendar date. + @protected + bool allowsValue(final V value) { + final allowed = allowedValues; + if (allowed == null) return true; + return allowed.contains(value); + } + + /// The value used for validation and for the resolved result. + /// + /// The default returns [value]. A subclass can map a typed value onto the + /// same form as a parsed string, and throw [FormatException] when it cannot. + @protected + V canonicalize(final V value) => value; + /// Validates the parsed value, /// throwing a [FormatException] if the value is invalid, /// or a [InvalidValueException] if the value is invalid for other reasons. @@ -346,7 +364,7 @@ abstract class ConfigOptionBase implements OptionDefinition { /// If they do, they must also call the super implementation. @mustCallSuper void validateValue(final V value) { - if (allowedValues?.contains(value) == false) { + if (!allowsValue(value)) { throw InvalidValueException( '`$value` is not an allowed value for ${qualifiedString()}', ); @@ -499,6 +517,20 @@ abstract class ConfigOptionBase implements OptionDefinition { } } + final parsed = res.value; + if (parsed != null) { + try { + final canonical = canonicalize(parsed); + if (canonical != parsed) { + res = res.copyWithValue(canonical); + } + } on FormatException catch (e) { + return res.copyWithError( + _makeFormatErrorMessage(e), + ); + } + } + final error = validateOptionValue(res.value); if (error != null) return res.copyWithError(error); diff --git a/packages/config/test/config/completion_test.dart b/packages/config/test/config/completion_test.dart index b247fc70..3083d029 100644 --- a/packages/config/test/config/completion_test.dart +++ b/packages/config/test/config/completion_test.dart @@ -53,6 +53,19 @@ Future complete(final OptionDefinition option) async { } void main() { + group('Given a date-only option with a UTC allowed value', () { + final option = DateTimeOption( + argName: 'on', + dateOnly: true, + allowedValues: [DateTime.utc(2026, 8, 1)], + ); + + test('when completing then the calendar date is offered', () async { + final result = await complete(option); + expect(result.candidates, [const CompletionCandidate('2026-08-01')]); + }); + }); + group('Given a StringOption without allowed values', () { const option = StringOption(argName: 'name'); diff --git a/packages/config/test/config/date_parsing_test.dart b/packages/config/test/config/date_parsing_test.dart index 1f9e81e7..90c186df 100644 --- a/packages/config/test/config/date_parsing_test.dart +++ b/packages/config/test/config/date_parsing_test.dart @@ -233,6 +233,32 @@ void main() { test('when formatting then only the calendar date is shown', () { expect(parser.format(DateTime.utc(2026, 8, 1, 15)), '2026-08-01'); }); + + test( + 'when local midnight falls on another day then the date is rejected', + () { + // Samoa skipped 2011-12-30. Other zones still have that midnight. + const input = '2011-12-30'; + final local = DateTime(2011, 12, 30); + final shifted = + local.year != 2011 || local.month != 12 || local.day != 30; + if (!shifted) { + expect(parser.parse(input), local); + return; + } + expect( + () => parser.parse(input), + throwsA( + isA().having( + (final e) => e.message, + 'message', + 'Invalid date "$input": ' + 'that calendar date does not exist in the local time zone', + ), + ), + ); + }, + ); }); group('Given a DateTimeOption', () { @@ -337,4 +363,124 @@ void main() { ]); }); }); + + group('Given a timestamp option with a default time', () { + final option = DateTimeOption( + argName: 'before', + defaultsTo: DateTime.utc(2026, 8, 1, 15), + ); + + test('when resolving with no arguments then the time is kept', () { + final config = Configuration.resolve( + options: [option], + args: const [], + ); + expect(config.value(option), DateTime.utc(2026, 8, 1, 15)); + }); + }); + + group('Given a date-only option', () { + final on = DateTimeOption( + argName: 'on', + dateOnly: true, + defaultsTo: DateTime.utc(2026, 8, 1, 15), + ); + + test( + 'when the default has a time then the value is that calendar date', + () { + final config = Configuration.resolve( + options: [on], + args: const [], + ); + expect(config.value(on), DateTime(2026, 8, 1)); + }, + ); + + test( + 'when the default is local midnight then the value is that midnight', + () { + final option = DateTimeOption( + argName: 'on', + dateOnly: true, + defaultsTo: DateTime(2026, 8, 1), + ); + final config = Configuration.resolve( + options: [option], + args: const [], + ); + expect(config.value(option), DateTime(2026, 8, 1)); + }, + ); + + test( + 'when the default calendar date does not exist locally ' + 'then it is rejected', + () { + // Samoa skipped 2011-12-30. Other zones still have that midnight. + final local = DateTime(2011, 12, 30); + final shifted = + local.year != 2011 || local.month != 12 || local.day != 30; + final option = DateTimeOption( + argName: 'on', + dateOnly: true, + defaultsTo: DateTime.utc(2011, 12, 30), + ); + final config = Configuration.resolveNoExcept( + options: [option], + args: const [], + ); + if (!shifted) { + expect(config.value(option), DateTime(2011, 12, 30)); + return; + } + expect(config.errors, [ + 'Invalid value for option `on` : ' + '2011-12-30 does not exist in the local time zone', + ]); + }, + ); + }); + + group('Given a date-only option with allowed dates', () { + final on = DateTimeOption( + argName: 'on', + dateOnly: true, + mandatory: true, + allowedValues: [ + DateTime.utc(2026, 8, 1), + DateTime(2026, 9, 1), + ], + ); + + test( + 'when passed the calendar date of a UTC entry then it is accepted', + () { + final config = Configuration.resolve( + options: [on], + args: ['--on', '2026-08-01'], + ); + expect(config.value(on), DateTime(2026, 8, 1)); + }, + ); + + test('when passed a local-midnight entry then it is accepted', () { + final config = Configuration.resolve( + options: [on], + args: ['--on', '2026-09-01'], + ); + expect(config.value(on), DateTime(2026, 9, 1)); + }); + + test('when passed another calendar date then it is rejected', () { + final config = Configuration.resolveNoExcept( + options: [on], + args: ['--on', '2026-10-01'], + ); + expect(config.errors, [ + 'Invalid value for option `on` : ' + '`2026-10-01 00:00:00.000` is not an allowed value for option `on`', + ]); + }); + }); } From dfbda11dadf382047690c3247a838bd8a4ccfc2b Mon Sep 17 00:00:00 2001 From: Christer Date: Thu, 19 Nov 2026 16:08:37 +0100 Subject: [PATCH 10/11] fix(config): Keep date-only calendar checks on DateTimeOption Co-authored-by: Cursor --- .../lib/src/config/date_time_options.dart | 89 ++++++++++++++----- packages/config/lib/src/config/options.dart | 34 +------ 2 files changed, 69 insertions(+), 54 deletions(-) diff --git a/packages/config/lib/src/config/date_time_options.dart b/packages/config/lib/src/config/date_time_options.dart index 7c4b4555..375d56da 100644 --- a/packages/config/lib/src/config/date_time_options.dart +++ b/packages/config/lib/src/config/date_time_options.dart @@ -1,3 +1,8 @@ +import 'arg_parser_facade.dart' show ParsedArgs; +import 'configuration.dart' show Configuration; +import 'configuration_broker.dart'; +import 'exceptions.dart'; +import 'option_resolution_impl.dart'; import 'option_types.dart'; import 'options.dart'; @@ -304,39 +309,81 @@ class DateTimeOption extends ComparableValueOption { valueHelp ?? (dateOnly ? 'YYYY-MM-DD' : 'YYYY-MM-DDTHH:MM:SSZ'), ); - /// Date-only allowed values are calendar dates. A UTC midnight and the - /// local midnight of the same day are the same choice, which is also what - /// completion offers. + /// A date-only value is checked and stored as local midnight on its + /// calendar date. Allowed values match that date, so a UTC date and a + /// local date on the same day are the same choice. @override - bool allowsValue(final DateTime value) { - if (!dateOnly) return super.allowsValue(value); + void validateValue(final DateTime value) { + if (!dateOnly) { + super.validateValue(value); + return; + } + final local = _localCalendarDate(value); final allowed = allowedValues; - if (allowed == null) return true; - return allowed.any( - (final candidate) => - candidate.year == value.year && - candidate.month == value.month && - candidate.day == value.day, + if (allowed != null && + !allowed.any( + (final candidate) => _sameCalendarDate(candidate, local), + )) { + throw InvalidValueException( + '`$local` is not an allowed value for ${qualifiedString()}', + ); + } + customValidator?.call(local); + final minimum = min; + if (minimum != null && local.compareTo(minimum) < 0) { + throw FormatException( + '${valueParser.format(local)} is below the minimum ' + '(${valueParser.format(minimum)})', + ); + } + final maximum = max; + if (maximum != null && local.compareTo(maximum) > 0) { + throw FormatException( + '${valueParser.format(local)} is above the maximum ' + '(${valueParser.format(maximum)})', + ); + } + } + + @override + OptionResolutionImpl resolveValue( + final Configuration cfg, { + final ParsedArgs? args, + final Iterator? posArgs, + final Map? env, + final ConfigurationBroker? configBroker, + }) { + final resolved = super.resolveValue( + cfg, + args: args, + posArgs: posArgs, + env: env, + configBroker: configBroker, ); + if (!dateOnly || resolved.error != null) return resolved; + final value = resolved.value; + if (value == null) return resolved; + final local = _localCalendarDate(value); + if (local == value) return resolved; + return resolved.copyWithValue(local); } - /// A date-only value is local midnight on its calendar date. + /// Local midnight on [value]'s calendar date. /// - /// Throws [FormatException] when that local midnight would fall on a - /// different day. - @override - DateTime canonicalize(final DateTime value) { - if (!dateOnly) return value; + /// Throws [FormatException] when that midnight would fall on another day. + static DateTime _localCalendarDate(final DateTime value) { final local = DateTime(value.year, value.month, value.day); - if (local.year != value.year || - local.month != value.month || - local.day != value.day) { + if (!_sameCalendarDate(local, value)) { throw FormatException( - '${valueParser.format(value)} does not exist in the local time zone', + '${DateTimeParser._calendarDate(value)} does not exist ' + 'in the local time zone', ); } return local; } + + static bool _sameCalendarDate(final DateTime a, final DateTime b) => + a.year == b.year && a.month == b.month && a.day == b.day; } /// The time units supported by the [DurationParser]. diff --git a/packages/config/lib/src/config/options.dart b/packages/config/lib/src/config/options.dart index 47949889..8f5dcd59 100644 --- a/packages/config/lib/src/config/options.dart +++ b/packages/config/lib/src/config/options.dart @@ -338,24 +338,6 @@ abstract class ConfigOptionBase implements OptionDefinition { } } - /// Whether [value] is one of [allowedValues]. - /// - /// True when [allowedValues] is not set. Subclasses may match by a - /// coarser rule than [Object.==], for example a calendar date. - @protected - bool allowsValue(final V value) { - final allowed = allowedValues; - if (allowed == null) return true; - return allowed.contains(value); - } - - /// The value used for validation and for the resolved result. - /// - /// The default returns [value]. A subclass can map a typed value onto the - /// same form as a parsed string, and throw [FormatException] when it cannot. - @protected - V canonicalize(final V value) => value; - /// Validates the parsed value, /// throwing a [FormatException] if the value is invalid, /// or a [InvalidValueException] if the value is invalid for other reasons. @@ -364,7 +346,7 @@ abstract class ConfigOptionBase implements OptionDefinition { /// If they do, they must also call the super implementation. @mustCallSuper void validateValue(final V value) { - if (!allowsValue(value)) { + if (allowedValues?.contains(value) == false) { throw InvalidValueException( '`$value` is not an allowed value for ${qualifiedString()}', ); @@ -517,20 +499,6 @@ abstract class ConfigOptionBase implements OptionDefinition { } } - final parsed = res.value; - if (parsed != null) { - try { - final canonical = canonicalize(parsed); - if (canonical != parsed) { - res = res.copyWithValue(canonical); - } - } on FormatException catch (e) { - return res.copyWithError( - _makeFormatErrorMessage(e), - ); - } - } - final error = validateOptionValue(res.value); if (error != null) return res.copyWithError(error); From 8bc01cdabfed99c5d1904e8bfe01c0e91e499974 Mon Sep 17 00:00:00 2001 From: Christer Date: Thu, 19 Nov 2026 16:37:27 +0100 Subject: [PATCH 11/11] fix(config): Store date-only presets as local midnight Presets skipped the calendar-date normalization already applied to arguments and defaults. Co-authored-by: Cursor --- .../config/lib/src/config/configuration.dart | 6 +++- .../lib/src/config/date_time_options.dart | 31 ++++--------------- packages/config/lib/src/config/options.dart | 12 +++++++ .../config/test/config/date_parsing_test.dart | 20 ++++++++++++ 4 files changed, 43 insertions(+), 26 deletions(-) diff --git a/packages/config/lib/src/config/configuration.dart b/packages/config/lib/src/config/configuration.dart index 8674d8d8..9098d65f 100644 --- a/packages/config/lib/src/config/configuration.dart +++ b/packages/config/lib/src/config/configuration.dart @@ -376,7 +376,11 @@ class Configuration { final error = option.option.validateOptionValue(value); if (error != null) return resolution.copyWithError(error); - return resolution; + if (value == null) return resolution; + + final stored = option.option.valueToStore(value); + if (stored == value) return resolution; + return resolution.copyWithValue(stored); } void _validateGroups( diff --git a/packages/config/lib/src/config/date_time_options.dart b/packages/config/lib/src/config/date_time_options.dart index 375d56da..11c5316c 100644 --- a/packages/config/lib/src/config/date_time_options.dart +++ b/packages/config/lib/src/config/date_time_options.dart @@ -1,8 +1,4 @@ -import 'arg_parser_facade.dart' show ParsedArgs; -import 'configuration.dart' show Configuration; -import 'configuration_broker.dart'; import 'exceptions.dart'; -import 'option_resolution_impl.dart'; import 'option_types.dart'; import 'options.dart'; @@ -269,7 +265,8 @@ class DateTimeParser extends ValueParser { /// a numeric offset is UTC. /// /// Set [dateOnly] to accept only a calendar date. The value is local -/// midnight on that date, including a typed default or configuration value: +/// midnight on that date, including a typed default, preset, or configuration +/// value: /// its year, month, and day are kept and the time of day is not part of the /// value. Allowed values match on that calendar date, so a UTC date and a /// local date on the same day are the same choice. The value help then @@ -345,27 +342,11 @@ class DateTimeOption extends ComparableValueOption { } } + /// A date-only value is stored as local midnight on its calendar date. @override - OptionResolutionImpl resolveValue( - final Configuration cfg, { - final ParsedArgs? args, - final Iterator? posArgs, - final Map? env, - final ConfigurationBroker? configBroker, - }) { - final resolved = super.resolveValue( - cfg, - args: args, - posArgs: posArgs, - env: env, - configBroker: configBroker, - ); - if (!dateOnly || resolved.error != null) return resolved; - final value = resolved.value; - if (value == null) return resolved; - final local = _localCalendarDate(value); - if (local == value) return resolved; - return resolved.copyWithValue(local); + DateTime valueToStore(final DateTime value) { + if (!dateOnly) return value; + return _localCalendarDate(value); } /// Local midnight on [value]'s calendar date. diff --git a/packages/config/lib/src/config/options.dart b/packages/config/lib/src/config/options.dart index 8f5dcd59..a54eee35 100644 --- a/packages/config/lib/src/config/options.dart +++ b/packages/config/lib/src/config/options.dart @@ -355,6 +355,13 @@ abstract class ConfigOptionBase implements OptionDefinition { customValidator?.call(value); } + /// The value stored after [validateValue] has accepted [value]. + /// + /// The default returns [value]. A date-only option maps the value onto + /// local midnight on the same calendar date. + @internal + V valueToStore(final V value) => value; + /// Returns self. @override ConfigOptionBase get option => this; @@ -502,6 +509,11 @@ abstract class ConfigOptionBase implements OptionDefinition { final error = validateOptionValue(res.value); if (error != null) return res.copyWithError(error); + final accepted = res.value; + if (accepted != null) { + final stored = valueToStore(accepted); + if (stored != accepted) return res.copyWithValue(stored); + } return res; } diff --git a/packages/config/test/config/date_parsing_test.dart b/packages/config/test/config/date_parsing_test.dart index 90c186df..30e6e040 100644 --- a/packages/config/test/config/date_parsing_test.dart +++ b/packages/config/test/config/date_parsing_test.dart @@ -397,6 +397,26 @@ void main() { }, ); + test('when a preset has a time then the value is that calendar date', () { + const option = DateTimeOption(argName: 'on', dateOnly: true); + final config = Configuration.fromValues( + values: {option: DateTime.utc(2026, 8, 1, 15)}, + ); + + expect(config.errors, isEmpty); + expect(config.optionalValue(option), DateTime(2026, 8, 1)); + }); + + test('when a timestamp preset has a time then that time is kept', () { + const option = DateTimeOption(argName: 'before'); + final instant = DateTime.utc(2026, 8, 1, 15); + final config = Configuration.fromValues( + values: {option: instant}, + ); + + expect(config.optionalValue(option), instant); + }); + test( 'when the default is local midnight then the value is that midnight', () {