1Config::Model::Value(3)User Contributed Perl DocumentatioCnonfig::Model::Value(3)
2
3
4
6 Config::Model::Value - Strongly typed configuration value
7
9 version 2.129
10
12 use Config::Model;
13
14 # define configuration tree object
15 my $model = Config::Model->new;
16 $model ->create_config_class (
17 name => "MyClass",
18
19 element => [
20
21 [qw/foo bar/] => {
22 type => 'leaf',
23 value_type => 'string',
24 description => 'foobar',
25 }
26 ,
27 country => {
28 type => 'leaf',
29 value_type => 'enum',
30 choice => [qw/France US/],
31 description => 'big countries',
32 }
33 ,
34 ],
35 ) ;
36
37 my $inst = $model->instance(root_class_name => 'MyClass' );
38
39 my $root = $inst->config_root ;
40
41 # put data
42 $root->load( steps => 'foo=FOO country=US' );
43
44 print $root->report ;
45 # foo = FOO
46 # DESCRIPTION: foobar
47 #
48 # country = US
49 # DESCRIPTION: big countries
50
52 This class provides a way to specify configuration value with the
53 following properties:
54
55 · Strongly typed scalar: the value can either be an enumerated type,
56 a boolean, a number, an integer or a string
57
58 · default parameter: a value can have a default value specified
59 during the construction. This default value is written in the
60 target configuration file. ("default" parameter)
61
62 · upstream default parameter: specifies a default value that is used
63 by the application when no information is provided in the
64 configuration file. This upstream_default value is not written in
65 the configuration files. Only the "fetch_standard" method returns
66 the builtin value. This parameter was previously referred as
67 "built_in" value. This may be used for audit purpose.
68 ("upstream_default" parameter)
69
70 · mandatory value: reading a mandatory value raises an exception if
71 the value is not specified and has no default value.
72
73 · dynamic change of property: A slave value can be registered to
74 another master value so that the properties of the slave value can
75 change according to the value of the master value. For instance,
76 paper size value can be 'letter' for country 'US' and 'A4' for
77 country 'France'.
78
79 · A reference to the Id of a hash of list element. In other word, the
80 value is an enumerated type where the possible values (choice) is
81 defined by the existing keys of a has element somewhere in the
82 tree. See "Value Reference".
83
85 There are several kind of default values. They depend on where these
86 values are defined (or found).
87
88 From the lowest default level to the "highest":
89
90 · "upstream_default": The value is known in the application, but is
91 not written in the configuration file.
92
93 · "layered": The value is known by the application through another
94 mean (e.g. an included configuration file), but is not written in
95 the configuration file.
96
97 · "default": The value is known by the model, but not by the
98 application. This value must be written in the configuration file.
99
100 · "computed": The value is computed from other configuration
101 elements. This value must be written in the configuration file.
102
103 · "preset": The value is not known by the model or by the
104 application. But it can be found by an automatic program and stored
105 while the configuration Config::Model::Instance is in preset mode
106
107 Then there is the value entered by the user. This overrides all kind of
108 "default" value.
109
110 The fetch_standard function returns the "highest" level of default
111 value, but does not return a custom value, i.e. a value entered by the
112 user.
113
115 Value object should not be created directly.
116
118 A leaf element must be declared with the following parameters:
119
120 value_type
121 Either "boolean", "enum", "integer", "number", "uniline", "string",
122 "file", "dir". Mandatory. See "Value types".
123
124 default
125 Specify the default value (optional)
126
127 upstream_default
128 Specify a built in default value (optional). I.e a value known by
129 the application which does not need to be written in the
130 configuration file.
131
132 write_as
133 Array ref. Reserved for boolean value. Specify how to write a
134 boolean value. Default is "[0,1]" which may not be the most
135 readable. "write_as" can be specified as "['false','true']" or
136 "['no','yes']".
137
138 compute
139 Computes a value according to a formula and other values. By
140 default a computed value cannot be set. See
141 Config::Model::ValueComputer for computed value declaration.
142
143 migrate_from
144 This is a special parameter to cater for smooth configuration
145 upgrade. This parameter can be used to copy the value of a
146 deprecated parameter to its replacement. See "Upgrade" for details.
147
148 convert => [uc | lc ]
149 When stored, the value is converted to uppercase (uc) or lowercase
150 (lc).
151
152 min Specify the minimum value (optional, only for integer, number)
153
154 max Specify the maximum value (optional, only for integer, number)
155
156 mandatory
157 Set to 1 if the configuration value must be set by the
158 configuration user (default: 0)
159
160 choice
161 Array ref of the possible value of an enum. Example :
162
163 choice => [ qw/foo bar/]
164
165 match
166 Perl regular expression. The value is matched with the regex to
167 assert its validity. Example "match => '^foo'" means that the
168 parameter value must begin with "foo". Valid only for "string" or
169 "uniline" values.
170
171 warn_if_match
172 Hash ref. Keys are made of Perl regular expression. The value can
173 specify a warning message (leave empty or undefined for a default
174 warning message) and instructions to fix the value. A warning is
175 issued when the value matches the passed regular expression. Valid
176 only for "string" or "uniline" values. The fix instructions is
177 evaluated when apply_fixes is called. $_ contains the value to fix.
178 $_ is stored as the new value once the instructions are done.
179 $self contains the value object. Use with care.
180
181 In the example below, any value matching 'foo' is converted in
182 uppercase:
183
184 warn_if_match => {
185 'foo' => {
186 fix => 'uc;',
187 msg => 'value $_ contains foo'
188 },
189 'BAR' => {
190 fix =>'lc;',
191 msg => 'value $_ contains BAR'
192 }
193 },
194
195 The tests are done in alphabetical order. In the example above,
196 "BAR" test is done before "foo" test.
197
198 $_ is substituted with the bad value when the message is generated.
199 $std_value is substituted with the standard value (i.e the preset,
200 computed or default value).
201
202 warn_unless_match
203 Hash ref like above. A warning is issued when the value does not
204 match the passed regular expression. Valid only for "string" or
205 "uniline" values.
206
207 warn
208 String. Issue a warning to user with the specified string any time
209 a value is set or read.
210
211 warn_if
212 A bit like "warn_if_match". The hash key is not a regexp but a
213 label to help users. The hash ref contains some Perl code that is
214 evaluated to perform the test. A warning is issued if the given
215 code returns true.
216
217 $_ contains the value to check. $self contains the
218 "Config::Model::Value" object (use with care).
219
220 The example below warns if value contaims a number:
221
222 warn_if => {
223 warn_test => {
224 code => 'defined $_ && /\d/;',
225 msg => 'value $_ should not have numbers',
226 fix => 's/\d//g;'
227 }
228 },
229
230 Any operation or check on file must be done with "file" sub
231 (otherwise tests will break). This sub returns a Path::Tiny object
232 that can be used to perform checks. For instance:
233
234 warn_if => {
235 warn_test => {
236 code => 'not file($_)->exists',
237 msg => 'file $_ should exist'
238 }
239
240 warn_unless
241 Like "warn_if", but issue a warning when the given "code" returns
242 false.
243
244 The example below warns unless the value points to an existing
245 directory:
246
247 warn_unless => {
248 'dir' => {
249 code => '-d',
250 msg => 'missing dir',
251 fix => "system(mkdir $_);" }
252 }
253
254 assert
255 Like "warn_if". Except that returned value triggers an error when
256 the given code returns false:
257
258 assert => {
259 test_nb => {
260 code => 'defined $_ && /\d/;',
261 msg => 'should not have numbers',
262 fix => 's/\d//g;'
263 }
264 },
265
266 grammar
267 Setup a Parse::RecDescent grammar to perform validation.
268
269 If the grammar does not start with a "check" rule (i.e does not
270 start with "check: "), the first line of the grammar is modified to
271 add "check" rule and this rules is set up so the entire value must
272 match the passed grammar.
273
274 I.e. the grammar:
275
276 token (oper token)(s?)
277 oper: 'and' | 'or'
278 token: 'Apache' | 'CC-BY' | 'Perl'
279
280 is changed to
281
282 check: token (oper token)(s?) /^\Z/ {$return = 1;}
283 oper: 'and' | 'or'
284 token: 'Apache' | 'CC-BY' | 'Perl'
285
286 The rule is called with Value object and a string reference. So, in
287 the actions you may need to define, you can call the value object
288 as $arg[0], store error message in "${$arg[1]}}" and store warnings
289 in "${$arg[2]}}".
290
291 replace
292 Hash ref. Used for enum to substitute one value with another. This
293 parameter must be used to enable user to upgrade a configuration
294 with obsolete values. For instance, if the value "foo" is obsolete
295 and replaced by "foo_better", you must declare:
296
297 replace => { foo => 'foo_better' }
298
299 The hash key can also be a regular expression for wider range
300 replacement. The regexp must match the whole value:
301
302 replace => ( 'foo.*' => 'better_foo' }
303
304 In this case, a value is replaced by "better_foo" when the
305 "/^foo.*$/" regexp matches.
306
307 replace_follow
308 Path specifying a hash of value element in the configuration tree.
309 The hash if used in a way similar to the "replace" parameter. In
310 this case, the replacement is not coded in the model but specified
311 by the configuration.
312
313 refer_to
314 Specify a path to an id element used as a reference. See Value
315 Reference for details.
316
317 computed_refer_to
318 Specify a path to an id element used as a computed reference. See
319 "Value Reference" for details.
320
321 warp
322 See section below: "Warp: dynamic value configuration".
323
324 help
325 You may provide detailed description on possible values with a hash
326 ref. Example:
327
328 help => { oui => "French for 'yes'", non => "French for 'no'"}
329
330 The key of help is used as a regular expression to find the help
331 text applicable to a value. These regexp are tried from the longest
332 to the shortest and are matched from the beginning of the string.
333 The key ""."" or "".*"" are fallback used last.
334
335 For instance:
336
337 help => {
338 'foobar' => 'help for values matching /^foobar/',
339 'foo' => 'help for values matching /^foo/ but not /^foobar/ (used above)',
340 '.' => 'help for all other values'
341 }
342
343 Value types
344 This modules can check several value types:
345
346 "boolean"
347 Accepts values 1 or 0, "yes" or "no", "true" or "false", and empty
348 string. The value read back is always 1 or 0.
349
350 "enum"
351 Enum choices must be specified by the "choice" parameter.
352
353 "integer"
354 Enable positive or negative integer
355
356 "number"
357 The value can be a decimal number
358
359 "uniline"
360 A one line string. I.e without "\n" in it.
361
362 "string"
363 Actually, no check is performed with this type.
364
365 "reference"
366 Like an "enum" where the possible values (aka choice) is defined by
367 another location if the configuration tree. See "Value Reference".
368
369 "file"
370 A file name or path. A warning is issued if the file does not
371 exists (or is a directory)
372
373 "dir"
374 A directory name or path. A warning is issued if the directory does
375 not exists (or is a plain file)
376
378 The Warp functionality enable a "Value" object to change its properties
379 (i.e. default value or its type) dynamically according to the value of
380 another "Value" object locate elsewhere in the configuration tree. (See
381 Config::Model::Warper for an explanation on warp mechanism).
382
383 For instance if you declare 2 "Value" element this way:
384
385 $model ->create_config_class (
386 name => "TV_config_class",
387 element => [
388 country => {
389 type => 'leaf',
390 value_type => 'enum',
391 choice => [qw/US Europe Japan/]
392 } ,
393 tv_standard => { # this example is getting old...
394 type => 'leaf',
395 value_type => 'enum',
396 choice => [ qw/PAL NTSC SECAM/ ]
397 warp => {
398 follow => {
399 # this points to the warp master
400 c => '- country'
401 },
402 rules => {
403 '$c eq "US"' => {
404 default => 'NTSC'
405 },
406 '$c eq "France"' => {
407 default => 'SECAM'
408 },
409 '$c eq "Japan"' => {
410 default => 'NTSC'
411 },
412 '$c eq "Europe"' => {
413 default => 'PAL'
414 },
415 }
416 }
417 } ,
418 ]
419 );
420
421 Setting "country" element to "US" means that "tv_standard" has a
422 default value set to "NTSC" by the warp mechanism.
423
424 Likewise, the warp mechanism enables you to dynamically change the
425 possible values of an enum element:
426
427 state => {
428 type => 'leaf',
429 value_type => 'enum', # example is admittedly silly
430 warp => {
431 follow => {
432 c => '- country'
433 },
434 rules => {
435 '$c eq "US"' => {
436 choice => ['Kansas', 'Texas' ]
437 },
438 '$c eq "Europe"' => {
439 choice => ['France', 'Spain' ]
440 },
441 '$c eq "Japan"' => {
442 choice => ['Honshu', 'Hokkaido' ]
443 }
444 }
445 }
446 }
447
448 Cascaded warping
449 Warping value can be cascaded: "A" can be warped by "B" which can be
450 warped by "C". But this feature should be avoided since it can lead to
451 a model very hard to debug. Bear in mind that:
452
453 · Warp loops are not detected and end up in "deep recursion
454 subroutine" failures.
455
456 · avoid "diamond" shaped warp dependencies: the results depends on
457 the order of the warp algorithm which can be unpredictable in this
458 case
459
460 · The keys declared in the warp rules ("US", "Europe" and "Japan" in
461 the example above) cannot be checked at start time against the warp
462 master "Value". So a wrong warp rule key is silently ignored during
463 start up and fails at run time.
464
466 To set up an enumerated value where the possible choice depends on the
467 key of a Config::Model::AnyId object, you must:
468
469 · Set "value_type" to "reference".
470
471 · Specify the "refer_to" or "computed_refer_to" parameter. See
472 refer_to parameter.
473
474 In this case, a "IdElementReference" object is created to handle the
475 relation between this value object and the referred Id. See
476 Config::Model::IdElementReference for details.
477
479 The following methods returns the current value of the parameter of the
480 value object (as declared in the model unless they were warped):
481
482 min
483 max
484 mandatory
485 choice
486 convert
487 value_type
488 default
489 upstream_default
490 index_value
491 element_name
492
493 name
494 Returns the object name.
495
496 get_type
497 Returns "leaf".
498
499 can_store
500 Returns true if the value object can be assigned to. Return 0 for a
501 read-only value (i.e. a computed value with no override allowed).
502
503 get_choice
504 Query legal values (only for enum types). Return an array (possibly
505 empty).
506
507 get_help
508 With a parameter, returns the help string applicable to the passed
509 value or undef.
510
511 Without parameter returns a hash ref that contains all the help
512 strings.
513
514 error_msg
515 Returns the error messages of this object (if any)
516
517 warning_msg
518 Returns warning concerning this value. Returns a list in list context
519 and a string in scalar context.
520
521 check_value
522 Parameters: "( value )"
523
524 Check the consistency of the value.
525
526 "check_value" also accepts named parameters:
527
528 value
529 quiet
530 When non null, check does not try to get extra information from the
531 tree. This is required in some cases to avoid loops in check,
532 get_info, get_warp_info, re-check ...
533
534 In scalar context, return 0 or 1.
535
536 In array context, return an empty array when no error was found. In
537 case of errors, returns an array of error strings that should be shown
538 to the user.
539
540 has_fixes
541 Returns the number of fixes that can be applied to the current value.
542
543 apply_fixes
544 Applies the fixes to suppress the current warnings.
545
546 check
547 Parameters: "( [ value => foo ] )"
548
549 Like "check_value".
550
551 Also displays warnings on STDOUT unless "silent" parameter is set to 1.
552 In this case,user is expected to retrieve them with "warning_msg".
553
554 Without "value" argument, this method checks the value currently
555 stored.
556
558 store
559 Parameters: "( $value )" or "value => ..., check => yes|no|skip ),
560 silent => 0|1"
561
562 Store value in leaf element. "check" parameter can be used to skip
563 validation check (default ies 'yes'). "silent" cane be used to
564 suppress warnings.
565
566 Optional "callback" is now deprecated.
567
568 clear
569 Clear the stored value. Further read returns the default value (or
570 computed or migrated value).
571
572 load_data
573 Parameters: "( $value )"
574
575 Load scalar data. Data is forwarded to "store".
576
577 Called with "load_data" or "load_data" or with the same parameters are
578 "store" method.
579
580 fetch_custom
581 Returns the stored value if this value is different from a standard
582 setting or built in setting. In other words, returns undef if the
583 stored value is identical to the default value or the computed value or
584 the built in value.
585
586 fetch_standard
587 Returns the standard value as defined by the configuration model. The
588 standard value can be either a preset value, a layered value, a
589 computed value, a default value or a built-in default value.
590
591 has_data
592 Return true if the value contains information different from default or
593 upstream default value.
594
595 fetch
596 Check and fetch value from leaf element. The method can have one
597 parameter (the fetch mode) or several pairs:
598
599 mode
600 Whether to fetch default, custom, etc value. See below for details
601
602 check
603 Whether to check if the value is valid or not before returning it.
604 Default is 'yes'. Possible value are
605
606 yes Perform check and raise an exception for bad values
607
608 skip
609 Perform check and return undef for bad values. A warning is
610 issued when a bad value is skipped. Set "check" to "no" to
611 avoid warnings.
612
613 no Do not check and return values even if bad
614
615 silent
616 When set to 1, warning are not displayed on STDOUT. User is
617 expected to read warnings with warning_msg method.
618
619 According to the "mode" parameter, this method returns either:
620
621 empty mode parameter (default)
622 Value entered by user or default value if the value is different
623 from upstream_default or layered value. Typically this value is
624 written in a configuration file.
625
626 backend
627 Alias for default mode.
628
629 custom
630 The value entered by the user (if different from built in, preset,
631 computed or default value)
632
633 user
634 The value most useful to user: the value that is used by the
635 application.
636
637 preset
638 The value entered in preset mode
639
640 standard
641 The preset or computed or default or built in value.
642
643 default
644 The default value (defined by the configuration model)
645
646 layered
647 The value found in included files (treated in layered mode: values
648 specified there are handled as upstream default values). E.g. like
649 in multistrap config.
650
651 upstream_default
652 The upstream_default value. (defined by the configuration model)
653
654 non_upstream_default
655 The custom or preset or computed or default value. Returns undef if
656 either of this value is identical to the upstream_default value.
657 This feature is useful to reduce data to write in configuration
658 file.
659
660 allow_undef
661 With this mode, "fetch()" returns undef for mandatory values.
662 Normally, trying to fetch an undefined mandatory value leads to an
663 exception.
664
665 user_value
666 Returns the value entered by the user. Does not use the default or
667 computed value. Returns undef unless a value was actually stored.
668
669 fetch_preset
670 Returns the value entered in preset mode. Does not use the default or
671 computed value. Returns undef unless a value was actually stored in
672 preset mode.
673
674 clear_preset
675 Delete the preset value. (Even out of preset mode). Returns true if
676 other data are still stored in the value (layered or user data).
677 Returns false otherwise.
678
679 fetch_layered
680 Returns the value entered in layered mode. Does not use the default or
681 computed value. Returns undef unless a value was actually stored in
682 layered mode.
683
684 clear_layered
685 Delete the layered value. (Even out of layered mode). Returns true if
686 other data are still stored in the value (layered or user data).
687 Returns false otherwise.
688
689 get( path => ..., mode => ... , check => ... )
690 Get a value from a directory like path.
691
692 set( path , value )
693 Set a value from a directory like path.
694
696 Number with min and max values
697 bounded_number => {
698 type => 'leaf',
699 value_type => 'number',
700 min => 1,
701 max => 4,
702 },
703
704 Mandatory value
705 mandatory_string => {
706 type => 'leaf',
707 value_type => 'string',
708 mandatory => 1,
709 },
710
711 mandatory_boolean => {
712 type => 'leaf',
713 value_type => 'boolean',
714 mandatory => 1,
715 },
716
717 Enum with help associated with each value
718 Note that the help specification is optional.
719
720 enum_with_help => {
721 type => 'leaf',
722 value_type => 'enum',
723 choice => [qw/a b c/],
724 help => {
725 a => 'a help'
726 }
727 },
728
729 Migrate old obsolete enum value
730 Legacy values "a1", "c1" and "foo/.*" are replaced with "a", "c" and
731 "foo/".
732
733 with_replace => {
734 type => 'leaf',
735 value_type => 'enum',
736 choice => [qw/a b c/],
737 replace => {
738 a1 => 'a',
739 c1 => 'c',
740 'foo/.*' => 'foo',
741 },
742 },
743
744 Enforce value to match a regexp
745 An exception is triggered when the value does not match the "match"
746 regular expression.
747
748 match => {
749 type => 'leaf',
750 value_type => 'string',
751 match => '^foo\d{2}$',
752 },
753
754 Enforce value to match a Parse::RecDescent grammar
755 match_with_parse_recdescent => {
756 type => 'leaf',
757 value_type => 'string',
758 grammar => q{
759 token (oper token)(s?)
760 oper: 'and' | 'or'
761 token: 'Apache' | 'CC-BY' | 'Perl'
762 },
763 },
764
765 Issue a warning if a value matches a regexp
766 Issue a warning if the string contains upper case letters. Propose a
767 fix that translate all capital letters to lower case.
768
769 warn_if_capital => {
770 type => 'leaf',
771 value_type => 'string',
772 warn_if_match => {
773 '/A-Z/' => {
774 fix => '$_ = lc;'
775 }
776 },
777 },
778
779 A specific warning can be specified:
780
781 warn_if_capital => {
782 type => 'leaf',
783 value_type => 'string',
784 warn_if_match => {
785 '/A-Z/' => {
786 fix => '$_ = lc;',
787 mesg => 'NO UPPER CASE PLEASE'
788 }
789 },
790 },
791
792 Issue a warning if a value does NOT match a regexp
793 warn_unless => {
794 type => 'leaf',
795 value_type => 'string',
796 warn_unless_match => {
797 foo => {
798 msg => '',
799 fix => '$_ = "foo".$_;'
800 }
801 },
802 },
803
804 Always issue a warning
805 always_warn => {
806 type => 'leaf',
807 value_type => 'string',
808 warn => 'Always warn whenever used',
809 },
810
811 Computed values
812 See "Examples" in Config::Model::ValueComputer.
813
815 Upgrade is a special case when the configuration of an application has
816 changed. Some parameters can be removed and replaced by another one. To
817 avoid trouble on the application user side, Config::Model offers a
818 possibility to handle the migration of configuration data through a
819 special declaration in the configuration model.
820
821 This declaration must:
822
823 · Declare the deprecated parameter with a "status" set to
824 "deprecated"
825
826 · Declare the new parameter with the instructions to load the
827 semantic content from the deprecated parameter. These instructions
828 are declared in the "migrate_from" parameters (which is similar to
829 the "compute" parameter)
830
831 Here an example where a URL parameter is changed to a set of 2
832 parameters (host and path):
833
834 'old_url' => {
835 type => 'leaf',
836 value_type => 'uniline',
837 status => 'deprecated',
838 },
839 'host' => {
840 type => 'leaf',
841 value_type => 'uniline',
842
843 # the formula must end with '$1' so the result of the capture is used
844 # as the host value
845 migrate_from => {
846 formula => '$old =~ m!http://([\w\.]+)!; $1 ;',
847 variables => {
848 old => '- old_url'
849 },
850 use_eval => 1,
851 },
852 },
853 'path' => {
854 type => 'leaf',
855 value_type => 'uniline',
856 migrate_from => {
857 formula => '$old =~ m!http://[\w\.]+(/.*)!; $1 ;',
858 variables => {
859 old => '- old_url'
860 },
861 use_eval => 1,
862 },
863 },
864
866 When an error is encountered, this module may throw the following
867 exceptions:
868
869 Config::Model::Exception::Model Config::Model::Exception::Formula
870 Config::Model::Exception::WrongValue
871 Config::Model::Exception::WarpError
872
873 See Config::Model::Exception for more details.
874
876 Dominique Dumont, (ddumont at cpan dot org)
877
879 Config::Model, Config::Model::Node, Config::Model::AnyId,
880 Config::Model::Warper, Config::Model::Exception
881 Config::Model::ValueComputer,
882
884 Dominique Dumont
885
887 This software is Copyright (c) 2005-2018 by Dominique Dumont.
888
889 This is free software, licensed under:
890
891 The GNU Lesser General Public License, Version 2.1, February 1999
892
893
894
895perl v5.28.1 2018-12-07 Config::Model::Value(3)