Newer
Older
dub_jkp / source / configy / Read.d
  1. /*******************************************************************************
  2.  
  3. Utilities to fill a struct representing the configuration with the content
  4. of a YAML document.
  5.  
  6. The main function of this module is `parseConfig`. Convenience functions
  7. `parseConfigString` and `parseConfigFile` are also available.
  8.  
  9. The type parameter to those three functions must be a struct and is used
  10. to drive the processing of the YAML node. When an error is encountered,
  11. an `Exception` will be thrown, with a descriptive message.
  12. The rules by which the struct is filled are designed to be
  13. as intuitive as possible, and are described below.
  14.  
  15. Optional_Fields:
  16. One of the major convenience offered by this utility is its handling
  17. of optional fields. A field is detected as optional if it has
  18. an initializer that is different from its type `init` value,
  19. for example `string field = "Something";` is an optional field,
  20. but `int count = 0;` is not.
  21. To mark a field as optional even with its default value,
  22. use the `Optional` UDA: `@Optional int count = 0;`.
  23.  
  24. Converter:
  25. Because config structs may contain complex types such as
  26. a Phobos type, a user-defined `Amount`, or Vibe.d's `URL`,
  27. one may need to apply a converter to a struct's field.
  28. Converters are functions that take a YAML `Node` as argument
  29. and return a type that is implicitly convertible to the field type
  30. (usually just the field type). They offer the most power to users,
  31. as they can inspect the YAML structure, but should be used as a last resort.
  32.  
  33. Composite_Types:
  34. Processing starts from a `struct` at the top level, and recurse into
  35. every fields individually. If a field is itself a struct,
  36. the filler will attempt the following, in order:
  37. - If the field has no value and is not optional, an Exception will
  38. be thrown with an error message detailing where the issue happened.
  39. - If the field has no value and is optional, the default value will
  40. be used.
  41. - If the field has a value, the filler will first check for a converter
  42. and use it if present.
  43. - If the type has a `static` method named `fromString` whose sole argument
  44. is a `string`, it will be used.
  45. - If the type has a constructor whose sole argument is a `string`,
  46. it will be used;
  47. - Finally, the filler will attempt to deserialize all struct members
  48. one by one and pass them to the default constructor, if there is any.
  49. - If none of the above succeeded, a `static assert` will trigger.
  50.  
  51. Alias_this:
  52. If a `struct` contains an `alias this`, the field that is aliased will be
  53. ignored, instead the config parser will parse nested fields as if they
  54. were part of the enclosing structure. This allow to re-use a single `struct`
  55. in multiple place without having to resort to a `mixin template`.
  56. Having an initializer will make all fields in the aliased struct optional.
  57. The aliased field cannot have attributes other than `@Optional`,
  58. which will then apply to all fields it exposes.
  59.  
  60. Duration_parsing:
  61. If the config field is of type `core.time.Duration`, special parsing rules
  62. will apply. There are two possible forms in which a Duration field may
  63. be expressed. In the first form, the YAML node should be a mapping,
  64. and it will be checked for fields matching the supported units
  65. in `core.time`: `weeks`, `days`, `hours`, `minutes`, `seconds`, `msecs`,
  66. `usecs`, `hnsecs`, `nsecs`. Strict parsing option will be respected.
  67. The values of the fields will then be added together, so the following
  68. YAML usages are equivalent:
  69. ---
  70. // sleepFor:
  71. // hours: 8
  72. // minutes: 30
  73. ---
  74. and:
  75. ---
  76. // sleepFor:
  77. // minutes: 510
  78. ---
  79. Provided that the definition of the field is:
  80. ---
  81. public Duration sleepFor;
  82. ---
  83.  
  84. In the second form, the field should have a suffix composed of an
  85. underscore ('_'), followed by a unit name as defined in `core.time`.
  86. This can be either the field name directly, or a name override.
  87. The latter is recommended to avoid confusion when using the field in code.
  88. In this form, the YAML node is expected to be a scalar.
  89. So the previous example, using this form, would be expressed as:
  90. ---
  91. sleepFor_minutes: 510
  92. ---
  93. and the field definition should be one of those two:
  94. ---
  95. public @Name("sleepFor_minutes") Duration sleepFor; /// Prefer this
  96. public Duration sleepFor_minutes; /// This works too
  97. ---
  98.  
  99. Those forms are mutually exclusive, so a field with a unit suffix
  100. will error out if a mapping is used. This prevents surprises and ensures
  101. that the error message, if any, is consistent accross user input.
  102.  
  103. To disable or change this behavior, one may use a `Converter` instead.
  104.  
  105. Strict_Parsing:
  106. When strict parsing is enabled, the config filler will also validate
  107. that the YAML nodes do not contains entry which are not present in the
  108. mapping (struct) being processed.
  109. This can be useful to catch typos or outdated configuration options.
  110.  
  111. Post_Validation:
  112. Some configuration will require validation accross multiple sections.
  113. For example, two sections may be mutually exclusive as a whole,
  114. or may have fields which are mutually exclusive with another section's
  115. field(s). This kind of dependence is hard to account for declaratively,
  116. and does not affect parsing. For this reason, the preferred way to
  117. handle those cases is to define a `validate` member method on the
  118. affected config struct(s), which will be called once
  119. parsing for that mapping is completed.
  120. If an error is detected, this method should throw an Exception.
  121.  
  122. Enabled_or_disabled_field:
  123. While most complex logic validation should be handled post-parsing,
  124. some section may be optional by default, but if provided, will have
  125. required fields. To support this use case, if a field with the name
  126. `enabled` is present in a struct, the parser will first process it.
  127. If it is `false`, the parser will not attempt to process the struct
  128. further, and the other fields will have their default value.
  129. Likewise, if a field named `disabled` exists, the struct will not
  130. be processed if it is set to `true`.
  131.  
  132. Copyright:
  133. Copyright (c) 2019-2022 BOSAGORA Foundation
  134. All rights reserved.
  135.  
  136. License:
  137. MIT License. See LICENSE for details.
  138.  
  139. *******************************************************************************/
  140.  
  141. module configy.Read;
  142.  
  143. public import configy.Attributes;
  144. public import configy.Exceptions : ConfigException;
  145. import configy.Exceptions;
  146. import configy.Utils;
  147.  
  148. import dyaml.exception;
  149. import dyaml.node;
  150. import dyaml.loader;
  151.  
  152. import std.algorithm;
  153. import std.conv;
  154. import std.datetime;
  155. import std.format;
  156. import std.getopt;
  157. import std.meta;
  158. import std.range;
  159. import std.traits;
  160. import std.typecons : Nullable, nullable, tuple;
  161.  
  162. static import core.time;
  163.  
  164. // Dub-specific adjustments for output
  165. import dub.internal.logging;
  166.  
  167. /// Command-line arguments
  168. public struct CLIArgs
  169. {
  170. /// Path to the config file
  171. public string config_path = "config.yaml";
  172.  
  173. /// Overrides for config options
  174. public string[][string] overrides;
  175.  
  176. /// Helper to add items to `overrides`
  177. public void overridesHandler (string, string value)
  178. {
  179. import std.string;
  180. const idx = value.indexOf('=');
  181. if (idx < 0) return;
  182. string k = value[0 .. idx], v = value[idx + 1 .. $];
  183. if (auto val = k in this.overrides)
  184. (*val) ~= v;
  185. else
  186. this.overrides[k] = [ v ];
  187. }
  188.  
  189. /***************************************************************************
  190.  
  191. Parses the base command line arguments
  192.  
  193. This can be composed with the program argument.
  194. For example, consider a program which wants to expose a `--version`
  195. switch, the definition could look like this:
  196. ---
  197. public struct ProgramCLIArgs
  198. {
  199. public CLIArgs base; // This struct
  200.  
  201. public alias base this; // For convenience
  202.  
  203. public bool version_; // Program-specific part
  204. }
  205. ---
  206. Then, an application-specific configuration routine would be:
  207. ---
  208. public GetoptResult parse (ref ProgramCLIArgs clargs, ref string[] args)
  209. {
  210. auto r = clargs.base.parse(args);
  211. if (r.helpWanted) return r;
  212. return getopt(
  213. args,
  214. "version", "Print the application version, &clargs.version_");
  215. }
  216. ---
  217.  
  218. Params:
  219. args = The command line args to parse (parsed options will be removed)
  220. passThrough = Whether to enable `config.passThrough` and
  221. `config.keepEndOfOptions`. `true` by default, to allow
  222. composability. If your program doesn't have other
  223. arguments, pass `false`.
  224.  
  225. Returns:
  226. The result of calling `getopt`
  227.  
  228. ***************************************************************************/
  229.  
  230. public GetoptResult parse (ref string[] args, bool passThrough = true)
  231. {
  232. return getopt(
  233. args,
  234. // `caseInsensistive` is the default, but we need something
  235. // with the same type for the ternary
  236. passThrough ? config.keepEndOfOptions : config.caseInsensitive,
  237. // Also the default, same reasoning
  238. passThrough ? config.passThrough : config.noPassThrough,
  239. "config|c",
  240. "Path to the config file. Defaults to: " ~ this.config_path,
  241. &this.config_path,
  242.  
  243. "override|O",
  244. "Override a config file value\n" ~
  245. "Example: -O foo.bar=true -o dns=1.1.1.1 -o dns=2.2.2.2\n" ~
  246. "Array values are additive, other items are set to the last override",
  247. &this.overridesHandler,
  248. );
  249. }
  250. }
  251.  
  252. /*******************************************************************************
  253.  
  254. Attempt to read and process the config file at `path`, print any error
  255.  
  256. This 'simple' overload of the more detailed `parseConfigFile` will attempt
  257. to read the file at `path`, and return a `Nullable` instance of it.
  258. If an error happens, either because the file isn't readable or
  259. the configuration has an issue, a message will be printed to `stderr`,
  260. with colors if the output is a TTY, and a `null` instance will be returned.
  261.  
  262. The calling code can hence just read a config file via:
  263. ```
  264. int main ()
  265. {
  266. auto configN = parseConfigFileSimple!Config("config.yaml");
  267. if (configN.isNull()) return 1; // Error path
  268. auto config = configN.get();
  269. // Rest of the program ...
  270. }
  271. ```
  272. An overload accepting `CLIArgs args` also exists.
  273.  
  274. Params:
  275. path = Path of the file to read from
  276. args = Command line arguments on which `parse` has been called
  277. strict = Whether the parsing should reject unknown keys in the
  278. document, warn, or ignore them (default: `StrictMode.Error`)
  279.  
  280. Returns:
  281. An initialized `Config` instance if reading/parsing was successful;
  282. a `null` instance otherwise.
  283.  
  284. *******************************************************************************/
  285.  
  286. public Nullable!T parseConfigFileSimple (T) (string path, StrictMode strict = StrictMode.Error)
  287. {
  288. return parseConfigFileSimple!(T)(CLIArgs(path), strict);
  289. }
  290.  
  291.  
  292. /// Ditto
  293. public Nullable!T parseConfigFileSimple (T) (in CLIArgs args, StrictMode strict = StrictMode.Error)
  294. {
  295. try
  296. {
  297. Node root = Loader.fromFile(args.config_path).load();
  298. return nullable(parseConfig!T(args, root, strict));
  299. }
  300. catch (ConfigException exc)
  301. {
  302. exc.printException();
  303. return typeof(return).init;
  304. }
  305. catch (Exception exc)
  306. {
  307. // Other Exception type may be thrown by D-YAML,
  308. // they won't include rich information.
  309. logWarn("%s", exc.message());
  310. return typeof(return).init;
  311. }
  312. }
  313.  
  314. /*******************************************************************************
  315.  
  316. Print an Exception, potentially with colors on
  317.  
  318. Trusted because of `stderr` usage.
  319.  
  320. *******************************************************************************/
  321.  
  322. private void printException (scope ConfigException exc) @trusted
  323. {
  324. import dub.internal.logging;
  325.  
  326. if (hasColors)
  327. logWarn("%S", exc);
  328. else
  329. logWarn("%s", exc.message());
  330. }
  331.  
  332. /*******************************************************************************
  333.  
  334. Parses the config file or string and returns a `Config` instance.
  335.  
  336. Params:
  337. cmdln = command-line arguments (containing the path to the config)
  338. path = When parsing a string, the path corresponding to it
  339. strict = Whether the parsing should reject unknown keys in the
  340. document, warn, or ignore them (default: `StrictMode.Error`)
  341.  
  342. Throws:
  343. `Exception` if parsing the config file failed.
  344.  
  345. Returns:
  346. `Config` instance
  347.  
  348. *******************************************************************************/
  349.  
  350. public T parseConfigFile (T) (in CLIArgs cmdln, StrictMode strict = StrictMode.Error)
  351. {
  352. Node root = Loader.fromFile(cmdln.config_path).load();
  353. return parseConfig!T(cmdln, root, strict);
  354. }
  355.  
  356. /// ditto
  357. public T parseConfigString (T) (string data, string path, StrictMode strict = StrictMode.Error)
  358. {
  359. CLIArgs cmdln = { config_path: path };
  360. auto loader = Loader.fromString(data);
  361. loader.name = path;
  362. Node root = loader.load();
  363. return parseConfig!T(cmdln, root, strict);
  364. }
  365.  
  366. /*******************************************************************************
  367.  
  368. Process the content of the YAML document described by `node` into an
  369. instance of the struct `T`.
  370.  
  371. See the module description for a complete overview of this function.
  372.  
  373. Params:
  374. T = Type of the config struct to fill
  375. cmdln = Command line arguments
  376. node = The root node matching `T`
  377. strict = Action to take when encountering unknown keys in the document
  378. initPath = Unused
  379.  
  380. Returns:
  381. An instance of `T` filled with the content of `node`
  382.  
  383. Throws:
  384. If the content of `node` cannot satisfy the requirements set by `T`,
  385. or if `node` contain extra fields and `strict` is `true`.
  386.  
  387. *******************************************************************************/
  388.  
  389. public T parseConfig (T) (
  390. in CLIArgs cmdln, Node node, StrictMode strict = StrictMode.Error, string initPath = null)
  391. {
  392. static assert(is(T == struct), "`" ~ __FUNCTION__ ~
  393. "` should only be called with a `struct` type as argument, not: `" ~
  394. fullyQualifiedName!T ~ "`");
  395.  
  396. final switch (node.nodeID)
  397. {
  398. case NodeID.mapping:
  399. dbgWrite("Parsing config '%s', strict: %s, initPath: %s",
  400. fullyQualifiedName!T,
  401. strict == StrictMode.Warn ?
  402. strict.paint(Yellow) : strict.paintIf(!!strict, Green, Red),
  403. initPath.length ? initPath : "(none)");
  404. return node.parseMapping!(StructFieldRef!T)(
  405. initPath, T.init, const(Context)(cmdln, strict), null);
  406. case NodeID.sequence:
  407. case NodeID.scalar:
  408. case NodeID.invalid:
  409. throw new TypeConfigException(node, "mapping (object)", "document root");
  410. }
  411. }
  412.  
  413. /*******************************************************************************
  414.  
  415. The behavior to have when encountering a field in YAML not present
  416. in the config definition.
  417.  
  418. *******************************************************************************/
  419.  
  420. public enum StrictMode
  421. {
  422. /// Issue an error by throwing an `UnknownKeyConfigException`
  423. Error = 0,
  424. /// Write a message to `stderr`, but continue processing the file
  425. Warn = 1,
  426. /// Be silent and do nothing
  427. Ignore = 2,
  428. }
  429.  
  430. /// Used to pass around configuration
  431. package struct Context
  432. {
  433. ///
  434. private CLIArgs cmdln;
  435.  
  436. ///
  437. private StrictMode strict;
  438. }
  439.  
  440. /// Helper template for `staticMap` used for strict mode
  441. private enum FieldRefToName (alias FR) = FR.Name;
  442.  
  443. private enum IsPattern (alias FR) = FR.Pattern;
  444.  
  445. /// Returns: An alias sequence of field names, taking UDAs (`@Name` et al) into account
  446. private alias FieldsName (T) = staticMap!(FieldRefToName, FieldRefTuple!T);
  447.  
  448. private alias Patterns (T) = staticMap!(FieldRefToName, Filter!(IsPattern, FieldRefTuple!T));
  449. /*******************************************************************************
  450.  
  451. Parse a mapping from `node` into an instance of `T`
  452.  
  453. Params:
  454. TLFR = Top level field reference for this mapping
  455. node = The YAML node object matching the struct being read
  456. path = The runtime path to this mapping, used for nested types
  457. defaultValue = The default value to use for `T`, which can be different
  458. from `T.init` when recursing into fields with initializers.
  459. ctx = A context where properties that need to be conserved during
  460. recursion are stored
  461. fieldDefaults = Default value for some fields, used for `Key` recursion
  462.  
  463. *******************************************************************************/
  464. /// Parse a single mapping, recurse as needed
  465. private TLFR.Type parseMapping (alias TLFR)
  466. (Node node, string path, auto ref TLFR.Type defaultValue,
  467. in Context ctx, in Node[string] fieldDefaults)
  468. {
  469. static assert(is(TLFR.Type == struct), "`parseMapping` called with wrong type (should be a `struct`)");
  470. assert(node.nodeID == NodeID.mapping, "Internal error: parseMapping shouldn't have been called");
  471.  
  472. dbgWrite("%s: `parseMapping` called for '%s' (node entries: %s)",
  473. TLFR.Type.stringof.paint(Cyan), path.paint(Cyan),
  474. node.length.paintIf(!!node.length, Green, Red));
  475.  
  476. static foreach (FR; FieldRefTuple!(TLFR.Type))
  477. {
  478. static if (FR.Name != FR.FieldName && hasMember!(TLFR.Type, FR.Name) &&
  479. !is(typeof(mixin("TLFR.Type.", FR.Name)) == function))
  480. static assert (FieldRef!(TLFR.Type, FR.Name).Name != FR.Name,
  481. "Field `" ~ FR.FieldName ~ "` `@Name` attribute shadows field `" ~
  482. FR.Name ~ "` in `" ~ TLFR.Type.stringof ~ "`: Add a `@Name` attribute to `" ~
  483. FR.Name ~ "` or change that of `" ~ FR.FieldName ~ "`");
  484. }
  485.  
  486. if (ctx.strict != StrictMode.Ignore)
  487. {
  488. /// First, check that all the sections found in the mapping are present in the type
  489. /// If not, the user might have made a typo.
  490. immutable string[] fieldNames = [ FieldsName!(TLFR.Type) ];
  491. immutable string[] patterns = [ Patterns!(TLFR.Type) ];
  492. FIELD: foreach (const ref Node key, const ref Node value; node)
  493. {
  494. const k = key.as!string;
  495. if (!fieldNames.canFind(k))
  496. {
  497. foreach (p; patterns)
  498. if (k.startsWith(p))
  499. // Require length because `0` would match `canFind`
  500. // and we don't want to allow `$PATTERN-`
  501. if (k[p.length .. $].length > 1 && k[p.length] == '-')
  502. continue FIELD;
  503.  
  504. if (ctx.strict == StrictMode.Warn)
  505. {
  506. scope exc = new UnknownKeyConfigException(
  507. path, key.as!string, fieldNames, key.startMark());
  508. exc.printException();
  509. }
  510. else
  511. throw new UnknownKeyConfigException(
  512. path, key.as!string, fieldNames, key.startMark());
  513. }
  514. }
  515. }
  516.  
  517. const enabledState = node.isMappingEnabled!(TLFR.Type)(defaultValue);
  518.  
  519. if (enabledState.field != EnabledState.Field.None)
  520. dbgWrite("%s: Mapping is enabled: %s", TLFR.Type.stringof.paint(Cyan), (!!enabledState).paintBool());
  521.  
  522. auto convertField (alias FR) ()
  523. {
  524. static if (FR.Name != FR.FieldName)
  525. dbgWrite("Field name `%s` will use YAML field `%s`",
  526. FR.FieldName.paint(Yellow), FR.Name.paint(Green));
  527. // Using exact type here matters: we could get a qualified type
  528. // (e.g. `immutable(string)`) if the field is qualified,
  529. // which causes problems.
  530. FR.Type default_ = __traits(getMember, defaultValue, FR.FieldName);
  531.  
  532. // If this struct is disabled, do not attempt to parse anything besides
  533. // the `enabled` / `disabled` field.
  534. if (!enabledState)
  535. {
  536. // Even this is too noisy
  537. version (none)
  538. dbgWrite("%s: %s field of disabled struct, default: %s",
  539. path.paint(Cyan), "Ignoring".paint(Yellow), default_);
  540.  
  541. static if (FR.Name == "enabled")
  542. return false;
  543. else static if (FR.Name == "disabled")
  544. return true;
  545. else
  546. return default_;
  547. }
  548.  
  549. if (auto ptr = FR.FieldName in fieldDefaults)
  550. {
  551. dbgWrite("Found %s (%s.%s) in `fieldDefaults`",
  552. FR.Name.paint(Cyan), path.paint(Cyan), FR.FieldName.paint(Cyan));
  553.  
  554. if (ctx.strict && FR.FieldName in node)
  555. throw new ConfigExceptionImpl("'Key' field is specified twice", path, FR.FieldName, node.startMark());
  556. return (*ptr).parseField!(FR)(path.addPath(FR.FieldName), default_, ctx)
  557. .dbgWriteRet("Using value '%s' from fieldDefaults for field '%s'",
  558. FR.FieldName.paint(Cyan));
  559. }
  560.  
  561. // This, `FR.Pattern`, and the field in `@Name` are special support for `dub`
  562. static if (FR.Pattern)
  563. {
  564. static if (is(FR.Type : V[K], K, V))
  565. {
  566. static struct AAFieldRef
  567. {
  568. ///
  569. private enum Ref = V.init;
  570. ///
  571. private alias Type = V;
  572. private enum Optional = FR.Optional;
  573. }
  574.  
  575. static assert(is(K : string), "Key type should be string-like");
  576. }
  577. else
  578. static assert(0, "Cannot have pattern on non-AA field");
  579.  
  580. AAFieldRef.Type[string] result;
  581. foreach (pair; node.mapping)
  582. {
  583. const key = pair.key.as!string;
  584. if (!key.startsWith(FR.Name))
  585. continue;
  586. string suffix = key[FR.Name.length .. $];
  587. if (suffix.length)
  588. {
  589. if (suffix[0] == '-') suffix = suffix[1 .. $];
  590. else continue;
  591. }
  592.  
  593. result[suffix] = pair.value.parseField!(AAFieldRef)(
  594. path.addPath(key), default_.get(key, AAFieldRef.Type.init), ctx);
  595. }
  596. bool hack = true;
  597. if (hack) return result;
  598. }
  599.  
  600. if (auto ptr = FR.Name in node)
  601. {
  602. dbgWrite("%s: YAML field is %s in node%s",
  603. FR.Name.paint(Cyan), "present".paint(Green),
  604. (FR.Name == FR.FieldName ? "" : " (note that field name is overriden)").paint(Yellow));
  605. return (*ptr).parseField!(FR)(path.addPath(FR.Name), default_, ctx)
  606. .dbgWriteRet("Using value '%s' from YAML document for field '%s'",
  607. FR.FieldName.paint(Cyan));
  608. }
  609.  
  610. dbgWrite("%s: Field is %s from node%s",
  611. FR.Name.paint(Cyan), "missing".paint(Red),
  612. (FR.Name == FR.FieldName ? "" : " (note that field name is overriden)").paint(Yellow));
  613.  
  614. // A field is considered optional if it has an initializer that is different
  615. // from its default value, or if it has the `Optional` UDA.
  616. // In that case, just return this value.
  617. static if (FR.Optional)
  618. return default_
  619. .dbgWriteRet("Using default value '%s' for optional field '%s'", FR.FieldName.paint(Cyan));
  620.  
  621. // The field is not present, but it could be because it is an optional section.
  622. // For example, the section could be defined as:
  623. // ---
  624. // struct RequestLimit { size_t reqs = 100; }
  625. // struct Config { RequestLimit limits; }
  626. // ---
  627. // In this case we need to recurse into `RequestLimit` to check if any
  628. // of its field is required.
  629. else static if (mightBeOptional!FR)
  630. {
  631. const npath = path.addPath(FR.Name);
  632. string[string] aa;
  633. return Node(aa).parseMapping!(FR)(npath, default_, ctx, null);
  634. }
  635. else
  636. throw new MissingKeyException(path, FR.Name, node.startMark());
  637. }
  638.  
  639. FR.Type convert (alias FR) ()
  640. {
  641. static if (__traits(getAliasThis, TLFR.Type).length == 1 &&
  642. __traits(getAliasThis, TLFR.Type)[0] == FR.FieldName)
  643. {
  644. static assert(FR.Name == FR.FieldName,
  645. "Field `" ~ fullyQualifiedName!(FR.Ref) ~
  646. "` is the target of an `alias this` and cannot have a `@Name` attribute");
  647. static assert(!hasConverter!(FR.Ref),
  648. "Field `" ~ fullyQualifiedName!(FR.Ref) ~
  649. "` is the target of an `alias this` and cannot have a `@Converter` attribute");
  650.  
  651. alias convertW(string FieldName) = convert!(FieldRef!(FR.Type, FieldName, FR.Optional));
  652. return FR.Type(staticMap!(convertW, FieldNameTuple!(FR.Type)));
  653. }
  654. else
  655. return convertField!(FR)();
  656. }
  657.  
  658. debug (ConfigFillerDebug)
  659. {
  660. indent++;
  661. scope (exit) indent--;
  662. }
  663.  
  664. TLFR.Type doValidation (TLFR.Type result)
  665. {
  666. static if (is(typeof(result.validate())))
  667. {
  668. if (enabledState)
  669. {
  670. dbgWrite("%s: Calling `%s` method",
  671. TLFR.Type.stringof.paint(Cyan), "validate()".paint(Green));
  672. result.validate();
  673. }
  674. else
  675. {
  676. dbgWrite("%s: Ignoring `%s` method on disabled mapping",
  677. TLFR.Type.stringof.paint(Cyan), "validate()".paint(Green));
  678. }
  679. }
  680. else if (enabledState)
  681. dbgWrite("%s: No `%s` method found",
  682. TLFR.Type.stringof.paint(Cyan), "validate()".paint(Yellow));
  683.  
  684. return result;
  685. }
  686.  
  687. // This might trigger things like "`this` is not accessible".
  688. // In this case, the user most likely needs to provide a converter.
  689. alias convertWrapper(string FieldName) = convert!(FieldRef!(TLFR.Type, FieldName));
  690. return doValidation(TLFR.Type(staticMap!(convertWrapper, FieldNameTuple!(TLFR.Type))));
  691. }
  692.  
  693. /*******************************************************************************
  694.  
  695. Parse a field, trying to match up the compile-time expectation with
  696. the run time value of the Node (`nodeID`).
  697.  
  698. This is the central point which does "type conversion", from the YAML node
  699. to the field type. Whenever adding support for a new type, things should
  700. happen here.
  701.  
  702. Because a `struct` can be filled from either a mapping or a scalar,
  703. this function will first try the converter / fromString / string ctor
  704. methods before defaulting to fieldwise construction.
  705.  
  706. Note that optional fields are checked before recursion happens,
  707. so this method does not do this check.
  708.  
  709. *******************************************************************************/
  710.  
  711. package FR.Type parseField (alias FR)
  712. (Node node, string path, auto ref FR.Type defaultValue, in Context ctx)
  713. {
  714. if (node.nodeID == NodeID.invalid)
  715. throw new TypeConfigException(node, "valid", path);
  716.  
  717. // If we reached this, it means the field is set, so just recurse
  718. // to peel the type
  719. static if (is(FR.Type : SetInfo!FT, FT))
  720. return FR.Type(
  721. parseField!(FieldRef!(FR.Type, "value"))(node, path, defaultValue, ctx),
  722. true);
  723.  
  724. else static if (hasConverter!(FR.Ref))
  725. return wrapException(node.viaConverter!(FR)(path, ctx), path, node.startMark());
  726.  
  727. else static if (hasFromYAML!(FR.Type))
  728. {
  729. scope impl = new ConfigParserImpl!(FR.Type)(node, path, ctx);
  730. return wrapException(FR.Type.fromYAML(impl), path, node.startMark());
  731. }
  732.  
  733. else static if (hasFromString!(FR.Type))
  734. return wrapException(FR.Type.fromString(node.as!string), path, node.startMark());
  735.  
  736. else static if (hasStringCtor!(FR.Type))
  737. return wrapException(FR.Type(node.as!string), path, node.startMark());
  738.  
  739. else static if (is(immutable(FR.Type) == immutable(core.time.Duration)))
  740. {
  741. if (node.nodeID != NodeID.mapping)
  742. throw new DurationTypeConfigException(node, path);
  743. return node.parseMapping!(StructFieldRef!DurationMapping)(
  744. path, DurationMapping.make(defaultValue), ctx, null).opCast!Duration;
  745. }
  746.  
  747. else static if (is(FR.Type == struct))
  748. {
  749. if (node.nodeID != NodeID.mapping)
  750. throw new TypeConfigException(node, "mapping (object)", path);
  751. return node.parseMapping!(FR)(path, defaultValue, ctx, null);
  752. }
  753.  
  754. // Handle string early as they match the sequence rule too
  755. else static if (isSomeString!(FR.Type))
  756. // Use `string` type explicitly because `Variant` thinks
  757. // `immutable(char)[]` (aka `string`) and `immutable(char[])`
  758. // (aka `immutable(string)`) are not compatible.
  759. return node.parseScalar!(string)(path);
  760. // Enum too, as their base type might be an array (including strings)
  761. else static if (is(FR.Type == enum))
  762. return node.parseScalar!(FR.Type)(path);
  763.  
  764. else static if (is(FR.Type : E[K], E, K))
  765. {
  766. if (node.nodeID != NodeID.mapping)
  767. throw new TypeConfigException(node, "mapping (associative array)", path);
  768.  
  769. static struct AAFieldRef
  770. {
  771. ///
  772. private enum Ref = E.init;
  773. ///
  774. private alias Type = E;
  775. }
  776.  
  777. // Note: As of June 2022 (DMD v2.100.0), associative arrays cannot
  778. // have initializers, hence their UX for config is less optimal.
  779. return node.mapping().map!(
  780. (Node.Pair pair) {
  781. return tuple(
  782. pair.key.get!K,
  783. pair.value.parseField!(AAFieldRef)(
  784. format("%s[%s]", path, pair.key.as!string), E.init, ctx));
  785. }).assocArray();
  786.  
  787. }
  788. else static if (is(FR.Type : E[], E))
  789. {
  790. static if (hasUDA!(FR.Ref, Key))
  791. {
  792. static assert(getUDAs!(FR.Ref, Key).length == 1,
  793. "`" ~ fullyQualifiedName!(FR.Ref) ~
  794. "` field shouldn't have more than one `Key` attribute");
  795. static assert(is(E == struct),
  796. "Field `" ~ fullyQualifiedName!(FR.Ref) ~
  797. "` has a `Key` attribute, but is a sequence of `" ~
  798. fullyQualifiedName!E ~ "`, not a sequence of `struct`");
  799.  
  800. string key = getUDAs!(FR.Ref, Key)[0].name;
  801.  
  802. if (node.nodeID != NodeID.mapping && node.nodeID != NodeID.sequence)
  803. throw new TypeConfigException(node, "mapping (object) or sequence", path);
  804.  
  805. if (node.nodeID == NodeID.mapping) return node.mapping().map!(
  806. (Node.Pair pair) {
  807. if (pair.value.nodeID != NodeID.mapping)
  808. throw new TypeConfigException(
  809. "sequence of " ~ pair.value.nodeTypeString(),
  810. "sequence of mapping (array of objects)",
  811. path, null, node.startMark());
  812.  
  813. return pair.value.parseMapping!(StructFieldRef!E)(
  814. path.addPath(pair.key.as!string),
  815. E.init, ctx, key.length ? [ key: pair.key ] : null);
  816. }).array();
  817. }
  818. if (node.nodeID != NodeID.sequence)
  819. throw new TypeConfigException(node, "sequence (array)", path);
  820.  
  821. // Only those two fields are used by `parseFieldImpl`
  822. static struct ArrayFieldRef
  823. {
  824. ///
  825. private enum Ref = E.init;
  826. ///
  827. private alias Type = E;
  828. }
  829.  
  830. // We pass `E.init` as default value as it is not going to be used:
  831. // Either there is something in the YAML document, and that will be
  832. // converted, or `sequence` will not iterate.
  833. return node.sequence.enumerate.map!(
  834. kv => kv.value.parseField!(ArrayFieldRef)(
  835. format("%s[%s]", path, kv.index), E.init, ctx))
  836. .array();
  837. }
  838. else
  839. {
  840. static assert (!is(FR.Type == union),
  841. "`union` are not supported. Use a converter instead");
  842. return node.parseScalar!(FR.Type)(path);
  843. }
  844. }
  845.  
  846. /// Parse a node as a scalar
  847. private T parseScalar (T) (Node node, string path)
  848. {
  849. if (node.nodeID != NodeID.scalar)
  850. throw new TypeConfigException(node, "scalar (value)", path);
  851.  
  852. static if (is(T == enum))
  853. return node.as!string.to!(T);
  854. else
  855. return node.as!(T);
  856. }
  857.  
  858. /*******************************************************************************
  859.  
  860. Write a potentially throwing user-provided expression in ConfigException
  861.  
  862. The user-provided hooks may throw (e.g. `fromString / the constructor),
  863. and the error may or may not be clear. We can't do anything about a bad
  864. message but we can wrap the thrown exception in a `ConfigException`
  865. to provide the location in the yaml file where the error happened.
  866.  
  867. Params:
  868. exp = The expression that may throw
  869. path = Path within the config file of the field
  870. position = Position of the node in the YAML file
  871. file = Call site file (otherwise the message would point to this function)
  872. line = Call site line (see `file` reasoning)
  873.  
  874. Returns:
  875. The result of `exp` evaluation.
  876.  
  877. *******************************************************************************/
  878.  
  879. private T wrapException (T) (lazy T exp, string path, Mark position,
  880. string file = __FILE__, size_t line = __LINE__)
  881. {
  882. try
  883. return exp;
  884. catch (Exception exc)
  885. throw new ConstructionException(exc, path, position, file, line);
  886. }
  887.  
  888. /// Allows us to reuse parseMapping and strict parsing
  889. private struct DurationMapping
  890. {
  891. public SetInfo!long weeks;
  892. public SetInfo!long days;
  893. public SetInfo!long hours;
  894. public SetInfo!long minutes;
  895. public SetInfo!long seconds;
  896. public SetInfo!long msecs;
  897. public SetInfo!long usecs;
  898. public SetInfo!long hnsecs;
  899. public SetInfo!long nsecs;
  900.  
  901. private static DurationMapping make (Duration def) @safe pure nothrow @nogc
  902. {
  903. typeof(return) result;
  904. auto fullSplit = def.split();
  905. result.weeks = SetInfo!long(fullSplit.weeks, fullSplit.weeks != 0);
  906. result.days = SetInfo!long(fullSplit.days, fullSplit.days != 0);
  907. result.hours = SetInfo!long(fullSplit.hours, fullSplit.hours != 0);
  908. result.minutes = SetInfo!long(fullSplit.minutes, fullSplit.minutes != 0);
  909. result.seconds = SetInfo!long(fullSplit.seconds, fullSplit.seconds != 0);
  910. result.msecs = SetInfo!long(fullSplit.msecs, fullSplit.msecs != 0);
  911. result.usecs = SetInfo!long(fullSplit.usecs, fullSplit.usecs != 0);
  912. result.hnsecs = SetInfo!long(fullSplit.hnsecs, fullSplit.hnsecs != 0);
  913. // nsecs is ignored by split as it's not representable in `Duration`
  914. return result;
  915. }
  916.  
  917. ///
  918. public void validate () const @safe
  919. {
  920. // That check should never fail, as the YAML parser would error out,
  921. // but better be safe than sorry.
  922. foreach (field; this.tupleof)
  923. if (field.set)
  924. return;
  925.  
  926. throw new Exception(
  927. "Expected at least one of the components (weeks, days, hours, " ~
  928. "minutes, seconds, msecs, usecs, hnsecs, nsecs) to be set");
  929. }
  930.  
  931. /// Allow conversion to a `Duration`
  932. public Duration opCast (T : Duration) () const scope @safe pure nothrow @nogc
  933. {
  934. return core.time.weeks(this.weeks) + core.time.days(this.days) +
  935. core.time.hours(this.hours) + core.time.minutes(this.minutes) +
  936. core.time.seconds(this.seconds) + core.time.msecs(this.msecs) +
  937. core.time.usecs(this.usecs) + core.time.hnsecs(this.hnsecs) +
  938. core.time.nsecs(this.nsecs);
  939. }
  940. }
  941.  
  942. /// Evaluates to `true` if we should recurse into the struct via `parseMapping`
  943. private enum mightBeOptional (alias FR) = is(FR.Type == struct) &&
  944. !is(immutable(FR.Type) == immutable(core.time.Duration)) &&
  945. !hasConverter!(FR.Ref) && !hasFromString!(FR.Type) &&
  946. !hasStringCtor!(FR.Type) && !hasFromYAML!(FR.Type);
  947.  
  948. /// Convenience template to check for the presence of converter(s)
  949. private enum hasConverter (alias Field) = hasUDA!(Field, Converter);
  950.  
  951. /// Provided a field reference `FR` which is known to have at least one converter,
  952. /// perform basic checks and return the value after applying the converter.
  953. private auto viaConverter (alias FR) (Node node, string path, in Context context)
  954. {
  955. enum Converters = getUDAs!(FR.Ref, Converter);
  956. static assert (Converters.length,
  957. "Internal error: `viaConverter` called on field `" ~
  958. FR.FieldName ~ "` with no converter");
  959.  
  960. static assert(Converters.length == 1,
  961. "Field `" ~ FR.FieldName ~ "` cannot have more than one `Converter`");
  962.  
  963. scope impl = new ConfigParserImpl!(FR.Type)(node, path, context);
  964. return Converters[0].converter(impl);
  965. }
  966.  
  967. private final class ConfigParserImpl (T) : ConfigParser!T
  968. {
  969. private Node node_;
  970. private string path_;
  971. private const(Context) context_;
  972.  
  973. /// Ctor
  974. public this (Node n, string p, const Context c) scope @safe pure nothrow @nogc
  975. {
  976. this.node_ = n;
  977. this.path_ = p;
  978. this.context_ = c;
  979. }
  980.  
  981. public final override inout(Node) node () inout @safe pure nothrow @nogc
  982. {
  983. return this.node_;
  984. }
  985.  
  986. public final override string path () const @safe pure nothrow @nogc
  987. {
  988. return this.path_;
  989. }
  990.  
  991. protected final override const(Context) context () const @safe pure nothrow @nogc
  992. {
  993. return this.context_;
  994. }
  995. }
  996.  
  997. /*******************************************************************************
  998.  
  999. A reference to a field in a `struct`
  1000.  
  1001. The compiler sometimes rejects passing fields by `alias`, or complains about
  1002. missing `this` (meaning it tries to evaluate the value). Sometimes, it also
  1003. discards the UDAs.
  1004.  
  1005. To prevent this from happening, we always pass around a `FieldRef`,
  1006. which wraps the parent struct type (`T`) and the name of the field (`name`).
  1007.  
  1008. To avoid any issue, eponymous usage is also avoided, hence the reference
  1009. needs to be accessed using `Ref`. A convenience `Type` alias is provided,
  1010. as well as `Default`.
  1011.  
  1012. *******************************************************************************/
  1013.  
  1014. package template FieldRef (alias T, string name, bool forceOptional = false)
  1015. {
  1016. // Renamed imports as the names exposed by this template clash
  1017. // with what we import.
  1018. import configy.Attributes : CAName = Name, CAOptional = Optional;
  1019.  
  1020. /// The reference to the field
  1021. public alias Ref = __traits(getMember, T, name);
  1022.  
  1023. /// Type of the field
  1024. public alias Type = typeof(Ref);
  1025.  
  1026. /// The name of the field in the struct itself
  1027. public alias FieldName = name;
  1028.  
  1029. /// The name used in the configuration field (taking `@Name` into account)
  1030. static if (hasUDA!(Ref, CAName))
  1031. {
  1032. static assert (getUDAs!(Ref, CAName).length == 1,
  1033. "Field `" ~ fullyQualifiedName!(Ref) ~
  1034. "` cannot have more than one `Name` attribute");
  1035.  
  1036. public immutable Name = getUDAs!(Ref, CAName)[0].name;
  1037.  
  1038. public immutable Pattern = getUDAs!(Ref, CAName)[0].startsWith;
  1039. }
  1040. else
  1041. {
  1042. public immutable Name = FieldName;
  1043. public immutable Pattern = false;
  1044. }
  1045.  
  1046. /// Default value of the field (may or may not be `Type.init`)
  1047. public enum Default = __traits(getMember, T.init, name);
  1048.  
  1049. /// Evaluates to `true` if this field is to be considered optional
  1050. /// (does not need to be present in the YAML document)
  1051. public enum Optional = forceOptional ||
  1052. hasUDA!(Ref, CAOptional) ||
  1053. is(immutable(Type) == immutable(bool)) ||
  1054. is(Type : SetInfo!FT, FT) ||
  1055. (Default != Type.init);
  1056. }
  1057.  
  1058. /// A pseudo `FieldRef` used for structs which are not fields (top-level)
  1059. private template StructFieldRef (ST)
  1060. {
  1061. ///
  1062. public alias Type = ST;
  1063.  
  1064. ///
  1065. public enum Default = ST.init;
  1066.  
  1067. ///
  1068. public enum Optional = false;
  1069. }
  1070.  
  1071. /// Get a tuple of `FieldRef` from a `struct`
  1072. private template FieldRefTuple (T)
  1073. {
  1074. static assert(is(T == struct),
  1075. "Argument " ~ T.stringof ~ " to `FieldRefTuple` should be a `struct`");
  1076.  
  1077. ///
  1078. static if (__traits(getAliasThis, T).length == 0)
  1079. public alias FieldRefTuple = staticMap!(Pred, FieldNameTuple!T);
  1080. else
  1081. {
  1082. /// Tuple of strings of aliased fields
  1083. /// As of DMD v2.100.0, only a single alias this is supported in D.
  1084. private immutable AliasedFieldNames = __traits(getAliasThis, T);
  1085. static assert(AliasedFieldNames.length == 1, "Multiple `alias this` are not supported");
  1086.  
  1087. // Ignore alias to functions (if it's a property we can't do anything)
  1088. static if (isSomeFunction!(__traits(getMember, T, AliasedFieldNames)))
  1089. public alias FieldRefTuple = staticMap!(Pred, FieldNameTuple!T);
  1090. else
  1091. {
  1092. /// "Base" field names minus aliased ones
  1093. private immutable BaseFields = Erase!(AliasedFieldNames, FieldNameTuple!T);
  1094. static assert(BaseFields.length == FieldNameTuple!(T).length - 1);
  1095.  
  1096. public alias FieldRefTuple = AliasSeq!(
  1097. staticMap!(Pred, BaseFields),
  1098. FieldRefTuple!(typeof(__traits(getMember, T, AliasedFieldNames))));
  1099. }
  1100. }
  1101.  
  1102. private alias Pred (string name) = FieldRef!(T, name);
  1103. }
  1104.  
  1105. /// Helper predicate
  1106. private template NameIs (string searching)
  1107. {
  1108. enum bool Pred (alias FR) = (searching == FR.Name);
  1109. }
  1110.  
  1111. /// Returns whether or not the field has a `enabled` / `disabled` field,
  1112. /// and its value. If it does not, returns `true`.
  1113. private EnabledState isMappingEnabled (M) (Node node, auto ref M default_)
  1114. {
  1115. import std.meta : Filter;
  1116.  
  1117. alias EMT = Filter!(NameIs!("enabled").Pred, FieldRefTuple!M);
  1118. alias DMT = Filter!(NameIs!("disabled").Pred, FieldRefTuple!M);
  1119.  
  1120. static if (EMT.length)
  1121. {
  1122. static assert (DMT.length == 0,
  1123. "`enabled` field `" ~ EMT[0].FieldName ~
  1124. "` conflicts with `disabled` field `" ~ DMT[0].FieldName ~ "`");
  1125.  
  1126. if (auto ptr = "enabled" in node)
  1127. return EnabledState(EnabledState.Field.Enabled, (*ptr).as!bool);
  1128. return EnabledState(EnabledState.Field.Enabled, __traits(getMember, default_, EMT[0].FieldName));
  1129. }
  1130. else static if (DMT.length)
  1131. {
  1132. if (auto ptr = "disabled" in node)
  1133. return EnabledState(EnabledState.Field.Disabled, (*ptr).as!bool);
  1134. return EnabledState(EnabledState.Field.Disabled, __traits(getMember, default_, DMT[0].FieldName));
  1135. }
  1136. else
  1137. {
  1138. return EnabledState(EnabledState.Field.None);
  1139. }
  1140. }
  1141.  
  1142. /// Retun value of `isMappingEnabled`
  1143. private struct EnabledState
  1144. {
  1145. /// Used to determine which field controls a mapping enabled state
  1146. private enum Field
  1147. {
  1148. /// No such field, the mapping is considered enabled
  1149. None,
  1150. /// The field is named 'enabled'
  1151. Enabled,
  1152. /// The field is named 'disabled'
  1153. Disabled,
  1154. }
  1155.  
  1156. /// Check if the mapping is considered enabled
  1157. public bool opCast () const scope @safe pure @nogc nothrow
  1158. {
  1159. return this.field == Field.None ||
  1160. (this.field == Field.Enabled && this.fieldValue) ||
  1161. (this.field == Field.Disabled && !this.fieldValue);
  1162. }
  1163.  
  1164. /// Type of field found
  1165. private Field field;
  1166.  
  1167. /// Value of the field, interpretation depends on `field`
  1168. private bool fieldValue;
  1169. }
  1170.  
  1171. unittest
  1172. {
  1173. static struct Config1
  1174. {
  1175. int integer2 = 42;
  1176. @Name("notStr2")
  1177. @(42) string str2;
  1178. }
  1179.  
  1180. static struct Config2
  1181. {
  1182. Config1 c1dup = { 42, "Hello World" };
  1183. string message = "Something";
  1184. }
  1185.  
  1186. static struct Config3
  1187. {
  1188. Config1 c1;
  1189. int integer;
  1190. string str;
  1191. Config2 c2 = { c1dup: { integer2: 69 } };
  1192. }
  1193.  
  1194. static assert(is(FieldRef!(Config3, "c2").Type == Config2));
  1195. static assert(FieldRef!(Config3, "c2").Default != Config2.init);
  1196. static assert(FieldRef!(Config2, "message").Default == Config2.init.message);
  1197. alias NFR1 = FieldRef!(Config3, "c2");
  1198. alias NFR2 = FieldRef!(NFR1.Ref, "c1dup");
  1199. alias NFR3 = FieldRef!(NFR2.Ref, "integer2");
  1200. alias NFR4 = FieldRef!(NFR2.Ref, "str2");
  1201. static assert(hasUDA!(NFR4.Ref, int));
  1202.  
  1203. static assert(FieldRefTuple!(Config3)[1].Name == "integer");
  1204. static assert(FieldRefTuple!(FieldRefTuple!(Config3)[0].Type)[1].Name == "notStr2");
  1205. }
  1206.  
  1207. /// Evaluates to `true` if `T` is a `struct` with a default ctor
  1208. private enum hasFieldwiseCtor (T) = (is(T == struct) && is(typeof(() => T(T.init.tupleof))));
  1209.  
  1210. /// Evaluates to `true` if `T` has a static method that is designed to work with this library
  1211. private enum hasFromYAML (T) = is(typeof(T.fromYAML(ConfigParser!(T).init)) : T);
  1212.  
  1213. /// Evaluates to `true` if `T` has a static method that accepts a `string` and returns a `T`
  1214. private enum hasFromString (T) = is(typeof(T.fromString(string.init)) : T);
  1215.  
  1216. /// Evaluates to `true` if `T` is a `struct` which accepts a single string as argument
  1217. private enum hasStringCtor (T) = (is(T == struct) && is(typeof(T.__ctor)) &&
  1218. Parameters!(T.__ctor).length == 1 &&
  1219. is(typeof(() => T(string.init))));
  1220.  
  1221. unittest
  1222. {
  1223. static struct Simple
  1224. {
  1225. int value;
  1226. string otherValue;
  1227. }
  1228.  
  1229. static assert( hasFieldwiseCtor!Simple);
  1230. static assert(!hasStringCtor!Simple);
  1231.  
  1232. static struct PubKey
  1233. {
  1234. ubyte[] data;
  1235.  
  1236. this (string hex) @safe pure nothrow @nogc{}
  1237. }
  1238.  
  1239. static assert(!hasFieldwiseCtor!PubKey);
  1240. static assert( hasStringCtor!PubKey);
  1241.  
  1242. static assert(!hasFieldwiseCtor!string);
  1243. static assert(!hasFieldwiseCtor!int);
  1244. static assert(!hasStringCtor!string);
  1245. static assert(!hasStringCtor!int);
  1246. }
  1247.  
  1248. /// Convenience function to extend a YAML path
  1249. private string addPath (string opath, string newPart)
  1250. in(newPart.length)
  1251. do {
  1252. return opath.length ? format("%s.%s", opath, newPart) : newPart;
  1253. }