diff --git a/packages/config/README.md b/packages/config/README.md
index 4837be9..b784874 100644
--- a/packages/config/README.md
+++ b/packages/config/README.md
@@ -237,9 +237,10 @@ 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 |
+| 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/example/main.dart b/packages/config/example/main.dart
index bd4c732..2872700 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/command/usage/options_usage.dart b/packages/config/lib/src/command/usage/options_usage.dart
index c918b7f..c791fa1 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 4139782..0b27c3e 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,9 +166,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, usageOnly: usageOnly),
hide: opt.hide,
splitCommas: opt.multiParser.separator == ',',
aliases: opt.argAliases ?? const [],
@@ -165,10 +180,80 @@ 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, usageOnly: usageOnly),
mandatory: opt.mandatory,
hide: opt.hide,
aliases: opt.argAliases ?? const [],
);
}
}
+
+/// 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 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]: 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 (usageOnly &&
+ !marksAllowed &&
+ help != null &&
+ opt.defaultValue() != null) {
+ return [help];
+ }
+ return opt.defaultValue()?.map(opt.multiParser.elementParser.format);
+}
diff --git a/packages/config/lib/src/config/config.dart b/packages/config/lib/src/config/config.dart
index b30c7ef..42e84f3 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/configuration.dart b/packages/config/lib/src/config/configuration.dart
index 8674d8d..9098d65 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
new file mode 100644
index 0000000..11c5316
--- /dev/null
+++ b/packages/config/lib/src/config/date_time_options.dart
@@ -0,0 +1,515 @@
+import 'exceptions.dart';
+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. 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;
+
+ 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 (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;
+ }
+
+ 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 is local
+/// 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
+/// 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;
+
+ 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.defaultValueHelp,
+ 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'),
+ );
+
+ /// 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
+ void validateValue(final DateTime value) {
+ if (!dateOnly) {
+ super.validateValue(value);
+ return;
+ }
+ final local = _localCalendarDate(value);
+ final allowed = allowedValues;
+ 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)})',
+ );
+ }
+ }
+
+ /// A date-only value is stored as local midnight on its calendar date.
+ @override
+ DateTime valueToStore(final DateTime value) {
+ if (!dateOnly) return value;
+ return _localCalendarDate(value);
+ }
+
+ /// Local midnight on [value]'s calendar date.
+ ///
+ /// 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 (!_sameCalendarDate(local, value)) {
+ throw FormatException(
+ '${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].
+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.defaultValueHelp,
+ 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.defaultValueHelp,
+ 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/file_system_options.dart b/packages/config/lib/src/config/file_system_options.dart
index 93ffd81..1df4043 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 b83d847..b1f43f3 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,
@@ -28,6 +34,7 @@ class StringOption extends ConfigOptionBase {
super.fromCustom,
super.fromDefault,
super.defaultsTo,
+ super.defaultValueHelp,
super.helpText,
super.valueHelp,
super.allowedHelp,
@@ -36,9 +43,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.
@@ -54,6 +72,7 @@ class MultiStringOption extends MultiOption {
super.fromCustom,
super.fromDefault,
super.defaultsTo,
+ super.defaultValueHelp,
super.helpText,
super.valueHelp,
super.allowedHelp,
@@ -77,6 +96,7 @@ class MultiStringOption extends MultiOption {
super.fromCustom,
super.fromDefault,
super.defaultsTo,
+ super.defaultValueHelp,
super.helpText,
super.valueHelp,
super.allowedHelp,
@@ -144,6 +164,7 @@ class EnumOption extends ConfigOptionBase {
super.fromCustom,
super.fromDefault,
super.defaultsTo,
+ super.defaultValueHelp,
super.helpText,
super.valueHelp,
super.allowedHelp,
@@ -192,6 +213,7 @@ class ComparableValueOption extends ConfigOptionBase {
super.fromCustom,
super.fromDefault,
super.defaultsTo,
+ super.defaultValueHelp,
super.helpText,
super.valueHelp,
super.allowedHelp,
@@ -210,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 {
@@ -250,6 +283,7 @@ class IntOption extends ComparableValueOption {
super.fromCustom,
super.fromDefault,
super.defaultsTo,
+ super.defaultValueHelp,
super.helpText,
super.valueHelp = 'integer',
super.allowedHelp,
@@ -263,34 +297,25 @@ class IntOption extends ComparableValueOption {
}) : super(valueParser: const IntParser());
}
-/// Parses a date string into a [DateTime] object.
-/// Throws [FormatException] if parsing failed.
-///
-/// 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\].
-class DateTimeParser extends ValueParser {
- const DateTimeParser();
+class DoubleParser extends ValueParser {
+ const DoubleParser();
@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)}',
- );
- if (val != null) return val;
- }
- throw FormatException('Invalid date-time "$value"');
+ double parse(final String value) {
+ return double.parse(value);
}
}
-/// Date-time value configuration option.
+/// Floating-point value configuration option.
///
/// Supports minimum and maximum range checking.
-class DateTimeOption extends ComparableValueOption {
- const DateTimeOption({
+/// 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,
super.argAliases,
super.argAbbrev,
@@ -301,8 +326,9 @@ class DateTimeOption extends ComparableValueOption {
super.fromCustom,
super.fromDefault,
super.defaultsTo,
+ super.defaultValueHelp,
super.helpText,
- super.valueHelp = 'YYYY-MM-DDtHH:MM:SSz',
+ super.valueHelp = 'number',
super.allowedHelp,
super.group,
super.allowedValues,
@@ -311,150 +337,28 @@ class DateTimeOption extends ComparableValueOption {
super.hide,
super.min,
super.max,
- }) : super(valueParser: const DateTimeParser());
-}
-
-/// 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});
+ }) : super(valueParser: const DoubleParser());
+ /// JSON and YAML store whole numbers as integers.
@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".'),
- );
+ double? valueFromConfig(final Object value) {
+ if (value is int) return value.toDouble();
+ return super.valueFromConfig(value);
}
@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' : '';
+ void validateValue(final double value) {
+ if (value.isNaN && (min != null || max != null)) {
+ throw FormatException(
+ '${valueParser.format(value)} is not a valid number',
+ );
}
- return absValue % mod > 0 ? '${absValue.remainder(mod)}$unit' : '';
+ super.validateValue(value);
}
-}
-/// 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());
+ @override
+ bool valueIsBelow(final double value, final double limit) => value < limit;
- /// 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);
+ @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 17edd9f..a54eee3 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,
@@ -339,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;
@@ -486,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;
}
@@ -550,6 +578,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,
@@ -570,9 +609,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,
);
}
@@ -666,6 +706,7 @@ class FlagOption extends ConfigOptionBase {
super.fromCustom,
super.fromDefault,
super.defaultsTo,
+ super.defaultValueHelp,
super.helpText,
super.valueHelp,
super.group,
@@ -757,6 +798,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 2c99a6f..6785d3c 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/arg_parser/scan_and_parse_args_test.dart b/packages/config/test/config/arg_parser/scan_and_parse_args_test.dart
index dcd8d5a..4728112 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/completion_test.dart b/packages/config/test/config/completion_test.dart
index b247fc7..3083d02 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/configuration_test.dart b/packages/config/test/config/configuration_test.dart
index 64978e6..65d495d 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';
@@ -214,6 +215,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',
@@ -278,6 +365,161 @@ 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');
+ });
+
+ 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', () {
+ 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")'),
+ );
+ });
+
+ 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', () {
const projectIdOpt = StringOption(
configKeys: ['primary:/projectId', 'fallback:/projectId'],
diff --git a/packages/config/test/config/configuration_type_test.dart b/packages/config/test/config/configuration_type_test.dart
index 611e62d..079f9d4 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',
@@ -206,6 +331,274 @@ 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 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',
diff --git a/packages/config/test/config/date_parsing_test.dart b/packages/config/test/config/date_parsing_test.dart
index 41d5235..30e6e04 100644
--- a/packages/config/test/config/date_parsing_test.dart
+++ b/packages/config/test/config/date_parsing_test.dart
@@ -3,126 +3,504 @@ 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.',
- () {
+ 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),
+ };
+
+ for (final entry in cases.entries) {
+ test('then ${entry.key} is that DateTime', () {
+ expect(parser.parse(entry.key), entry.value);
+ });
+ }
+
+ 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('then Z is UTC', () {
+ final parsed = parser.parse('2026-08-01T00:00:00Z');
+ expect(parsed, DateTime.utc(2026, 8, 1));
+ expect(parsed.isUtc, isTrue);
+ });
+ });
+
+ 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',
+ };
+
+ 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}',
+ ),
+ ),
+ );
+ });
+ }
+ });
+
+ 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(''),
- throwsA(isA()),
+ parser.format(parser.parse('2020-01-01T12:20:40.001Z')),
+ '2020-01-01T12:20:40.001Z',
);
- },
- );
-
- 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)),
+ parser.format(parser.parse('2020-01-01T12:20:40.1Z')),
+ '2020-01-01T12:20:40.1Z',
);
- },
- );
-
- test(
- 'When calling parseDate() with 20200101 then it successfully returns a DateTime.',
- () {
expect(
- dateTimeParser.parse('20200101'),
- equals(DateTime(2020, 1, 1)),
+ 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');
+ });
test(
- 'When calling parseDate() with 2020-01-01 12:20:40 then it successfully returns a DateTime.',
+ '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(
- dateTimeParser.parse('2020-01-01 12:20:40'),
- equals(DateTime(2020, 1, 1, 12, 20, 40)),
+ () => 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',
+ ),
+ ),
);
},
);
+ });
- 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('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-01T12:20:40.001z then it successfully returns a DateTime.',
+ 'when passed a calendar date then it resolves to local midnight',
() {
- expect(
- dateTimeParser.parse('2020-01-01T12:20:40.001z'),
- equals(DateTime.utc(2020, 1, 1, 12, 20, 40, 1)),
+ 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-01t12: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-01t12: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-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)),
- );
- },
+ 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)',
+ ]);
+ });
+ });
+
+ 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 calling parseDate() with 2020-01-01:12:20:40 then it successfully returns a DateTime.',
+ 'when the default has a time then the value is that calendar date',
() {
- expect(
- dateTimeParser.parse('2020-01-01:12:20:40'),
- equals(DateTime(2020, 1, 1, 12, 20, 40)),
+ final config = Configuration.resolve(
+ options: [on],
+ args: const [],
);
+ expect(config.value(on), DateTime(2026, 8, 1));
},
);
+ 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 calling parseDate() with 2020-01-01_12:20:40 then it successfully returns a DateTime.',
+ 'when the default is local midnight then the value is that midnight',
() {
- expect(
- dateTimeParser.parse('2020-01-01_12:20:40'),
- equals(DateTime(2020, 1, 1, 12, 20, 40)),
+ 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 calling parseDate() with 2020-01-01/12:20:40 then it successfully returns a DateTime.',
+ 'when the default calendar date does not exist locally '
+ 'then it is rejected',
() {
- expect(
- dateTimeParser.parse('2020-01-01/12:20:40'),
- equals(DateTime(2020, 1, 1, 12, 20, 40)),
+ // 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 calling parseDate() with 2020-01-01x12:20:40 then it throws FormatException.',
+ 'when passed the calendar date of a UTC entry then it is accepted',
() {
- expect(
- () => dateTimeParser.parse('2020-01-01x12:20:40'),
- throwsA(isA()),
+ 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`',
+ ]);
+ });
});
}