blib/lib/Evented/Configuration.pm untested

filter: Statementstmt 0.0% 0 / 128 Branchbran 0.0% 0 / 46 Conditioncond 0.0% 0 / 32 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 16 totaltotal 0.0% 0 / 244 CC 24 SCAR 40.3
CC
24
Cov
0%
parse_config
182.0
_value_to_perl
12.0
new
6.0
CRAP 56.3
1 # Copyright (c) 2016, Mitchell Cooper
2 #
3 # Evented::Configuration:
4 #
5 # a configuration file parser and event-driven configuration class.
6 # Evented::Configuration is based on UICd::Configuration, the class of the UIC daemon.
7 # UICd's parser was based on juno5's parser, which evolved from juno4, juno3, and juno2.
8 # Early versions of Evented::Configuration were also found in several IRC bots, including
9 # foxy-java. Evented::Configuration provides several convenience fetching methods.
10 #
11 # Events:
12 #
13 # each time a configuration value changes, change:blocktype/blockname:key is fired. For unnamed
14 # blocks, the block type is omitted. For example, a block named 'chocolate' of type
15 # 'cookies' would fire the event 'change:cookies/chocolate:favorite' when its 'favorite' key
16 # is changed. An unnamed block of type 'fudge' would fire the event 'change:fudge:peanutbutter'
17 # when its 'peanutbutter' key is changed.
18 #
19 # If a value never existed, new values fire change events as well. If you want your
20 # listeners to respond to certain values even when the configuration is first loaded,
21 # simply add the listeners before calling parse_config(). If you wish for the opposite
22 # behavior, do the opposite: apply the handlers after calling parse_config().
23 #
24 # All events are fired with:
25 # $old - first argument, the former value of this configuration key.
26 # $new - second argument, the new value of this configuration key.
27 #
28 # The easiest way to attach configuration change events is with the on_change() method.
29 # It is also the safest way because event names could possibly change in the future.
30 # For example:
31 #
32 # $conf->on_change(['someBlockType', 'someBlockName'], 'key', sub {
33 # my ($event, $old, $new) = @_;
34 # ...
35 # });
36 #
37 # You can also add additional hash arguments for ->register_event() to the end.
38 #
39  
40 package Evented::Configuration;
41  
42 use warnings;
43 use strict;
44 use utf8;
45 use 5.010;
46 use parent 'Evented::Object';
47 use Scalar::Util qw(blessed);
48  
49 our $VERSION = '4.00';
50  
51 my ($true, $false) = (1, 0);
52 sub on () { state $on = bless \$true, 'Evented::Configuration::Boolean' }
53 sub off () { state $off = bless \$false, 'Evented::Configuration::Boolean' }
54  
55 # create a new configuration instance.
56 sub new {
57 my ($class, %opts) = (shift, @_);
58  
59 # if we have no defined conffile, we must give up now.
60 return if !defined $opts{conffile};
61  
62 # if 'hashref' is provided, use it.
63 $opts{conf} = $opts{hashref} || $opts{conf} || {};
64  
65 # return the new configuration object.
66 return bless \%opts, $class;
67  
68 }
69  
70 # parse the configuration file.
71 sub parse_config {
72 my ($conf) = @_;
73 my $file = $conf->{conffile};
74  
75 # open for reading
76 my $fh;
77 if (not open $fh, '<', $file) {
78 my $msg = "$file: Failed to open for reading: $!";
79 return (undef, $msg);
80 }
81  
82 my ($block, $name, @new_conf);
83 my $err = sub {
84 my ($i, $msg) = @_;
85 $msg = "$file:$i: $msg; parsing aborted";
86 close $fh;
87 return wantarray ? (undef, $msg) : undef;
88 };
89  
90 while (<$fh>) {
91 my ($key, $val, $val_changed_maybe);
92  
93 # remove comments and excess whitespace.
94 chomp;
95 s/^\s*//;
96 s/\s*(#.*)$//;
97 next unless length;
98  
99 # a block with a name.
100 if (m/^\[(.+?):(.+)\]$/) {
101 $block = trim($1);
102 $name = trim($2);
103 }
104  
105 # a nameless block.
106 elsif (m/^\[(.+)\]$/) {
107 $block = 'section';
108 $name = trim($1);
109 }
110  
111 # a boolean key.
112 elsif (m/^([\w:]+)$/) {
113 $key = trim($1);
114 $val = on;
115 $val_changed_maybe++;
116  
117 # no block is set
118 return $err->($., "Stray key '$key'")
119 if !length $block;
120 }
121  
122 # a key and value.
123 elsif (m/^([\w:]+)\s*[:=]+(.+)$/) {
124 $key = trim($1);
125 my $val_str = trim($2);
126 $val_changed_maybe++;
127  
128 # no block is set
129 return $err->($., "Stray pair '$key = $val_str'")
130 if !length $block;
131  
132 $val = eval $val_str;
133  
134 # error occured in eval
135 return $err->($., "Invalid value '$val_str': $@")
136 if $@;
137 }
138  
139 # I don't know how to handle this.
140 else {
141 return $err->($., "Syntax error: '$_'");
142 }
143  
144 # something may have changed.
145 next unless $val_changed_maybe;
146  
147 # fetch the old value and set the new value.
148 my $old = $conf->{conf}{$block}{$name}{$key};
149  
150 # push the events.
151 push @new_conf, $block, $name, $key, $old, $val;
152 }
153  
154 # we parsed the entire file successfully, so commit the changes.
155 my @new_events;
156 while (my @set = splice @new_conf, 0, 5) {
157 push @new_events, $conf->_get_events(@set);
158 $conf->{conf}{ $set[0] }{ $set[1] }{ $set[2] } = $set[4];
159 }
160  
161 # now fire change events.
162 $conf->fire_events_together(@new_events) if @new_events;
163  
164 close $fh;
165 return 1;
166 }
167  
168 # returns true if the block is found.
169 # supports unnamed blocks by get(block, key)
170 # supports named blocks by get([block type, block name], key)
171 sub has_block {
172 my ($conf, $block) = @_;
173 my ($block_type, $block_name) = _block_parts($block);
174 return 1 if $conf->{conf}{$block_type}{$block_name};
175 }
176  
177 # returns a list of all the names of a block type.
178 # for example, names_of_block('listen') might return ('0.0.0.0', '127.0.0.1')
179 sub names_of_block {
180 my ($conf, $block_type) = @_;
181 return keys %{ $conf->{conf}{$block_type} };
182 }
183  
184 # returns a list of all the keys in a block.
185 # for example, keys_of_block('modules') would return an array of every module.
186 # accepts block type or [block type, block name] as well.
187 sub keys_of_block {
188 my ($conf, $block) = @_;
189 my ($block_type, $block_name) = _block_parts($block);
190  
191 # not a hashref. return empty list.
192 my $hashref = $conf->{conf}{$block_type}{$block_name};
193 if (!$hashref || !ref $hashref || ref $hashref ne 'HASH') {
194 return;
195 }
196  
197 return keys %$hashref;
198 }
199  
200 # returns a list of all the values in a block.
201 # accepts block type or [block type, block name] as well.
202 sub values_of_block {
203 my ($conf, $block) = @_;
204 my ($block_type, $block_name) = _block_parts($block);
205  
206 # not a hashref. return empty list.
207 my $hashref = $conf->{conf}{$block_type}{$block_name};
208 if (!$hashref || !ref $hashref || ref $hashref ne 'HASH') {
209 return;
210 }
211  
212 return map _value_to_perl($_), values %$hashref;
213 }
214  
215 # returns the key:value hash of a block.
216 # accepts block type or [block type, block name] as well.
217 sub hash_of_block {
218 my ($conf, $block) = @_;
219 my ($block_type, $block_name) = _block_parts($block);
220  
221 # not a hashref. return empty list.
222 my $hashref = $conf->{conf}{$block_type}{$block_name};
223 if (!$hashref || !ref $hashref || ref $hashref ne 'HASH') {
224 return;
225 }
226  
227 return map { $_ => _value_to_perl($hashref->{$_}) } keys %$hashref;
228 }
229  
230 # get a configuration value.
231 # supports unnamed blocks by get(block, key)
232 # supports named blocks by get([block type, block name], key)
233 sub get { _get(shift, 0, @_) }
234 sub _get {
235 my ($conf, $bool_objs, $block, $key) = @_;
236 my ($block_type, $block_name) = _block_parts($block);
237 my $res = $conf->{conf}{$block_type}{$block_name}{$key};
238 return $bool_objs ? $res : _value_to_perl($res);
239 }
240  
241 # remove leading and trailing whitespace.
242 sub trim {
243 my $string = shift;
244 $string =~ s/\s+$//;
245 $string =~ s/^\s+//;
246 return $string;
247 }
248  
249 # convert stored value to Perl representation.
250 sub _value_to_perl {
251 my ($val) = @_;
252 if (blessed $val && $val->isa('Evented::Configuration::Boolean')) {
253 return $$val ? 1 : undef;
254 }
255 return $val;
256 }
257  
258 # attach a configuration change listener.
259 # see notes at top of file for usage.
260 sub on_change {
261 my ($conf, $block, $key, $code, %opts) = @_;
262 my ($block_type, $block_name) = _block_parts($block);
263  
264 # determine the name of the event.
265 $block = $block_type eq 'section' ? $block_name : $block_type.q(/).$block_name;
266 my $event_name = "change:$block:$key";
267  
268 # register the event.
269 return $conf->register_event($event_name => $code, %opts);
270 }
271  
272 # get events for a change.
273 sub _get_events {
274 my ($conf, $block, $name, $key, $old, $val) = @_;
275 $old = _value_to_perl($old);
276 $val = _value_to_perl($val);
277  
278 # determine the name of the event.
279 my $eblock = $block eq 'section' ? $name : $block.q(/).$name;
280  
281 # return the events.
282 return (
283  
284 # change => sub { my ($blockref, $key, $old, $new) }
285 # change:namelessblock => sub { my ($key, $old, $new) }
286 # change:named/theName => sub { my ($key, $old, $new) }
287 # change:section:__ANY__ => sub { my ($the_type, $key, $old, $new) }
288 # change:named:__ANY__ => sub { my ($the_name, $key, $old, $new) }
289 # change:namelessblock:someKey => sub { my ($old, $new) }
290 # change:named/theName:someKey => sub { my ($old, $new) }
291  
292 [ change => [ $block, $name ], $key, $old, $val ],
293 [ "change:$eblock" => $key, $old, $val ],
294 [ "change:$block:__ANY__" => $name, $key, $old, $val ],
295 [ "change:$eblock:$key" => $old, $val ]
296  
297 );
298 }
299  
300 # handle 'unamed block' or [ 'block type', 'named block' ]
301 # returns a list (block type, block name)
302 sub _block_parts {
303 my $block = shift;
304 if (ref $block && ref $block eq 'ARRAY' && @$block >= 2) {
305 return @$block;
306 }
307 return ('section', $block);
308 }
309  
310 1;
311  
312 =head1 NAME
313  
314 B<Evented::Configuration> - an event-driven objective configuration class and parser for
315 Perl software built upon L<Evented::Object>.
316  
317 =head1 SYNOPSIS
318  
319 =head2 Example usage
320  
321 # create a new configuration instance.
322 my $conf = Evented::Configuration->new(conffile => 'etc/some.conf');
323  
324 # attach a callback to respond to changes of the user:age key.
325 $conf->on_change('user', 'name', sub {
326 my ($event, $old, $new) = @_;
327 say 'The user\'s age changed from ', $old || '(not born)', "to $new";
328 });
329  
330 # parse the configuration file.
331 $conf->parse_config();
332  
333 =head2 Example configuration file
334  
335 # some.conf file
336  
337 # Comments
338  
339 # Hello, I am a comment.
340 # I am also a comment.
341  
342 # Unnamed blocks
343  
344 [ someBlock ]
345  
346 someKey = "some string"
347 otherKey = 12
348 another = ['hello', 'there']
349 evenMore = ['a'..'z']
350  
351 # Named blocks
352  
353 [ cookies: sugar ]
354  
355 favorites = ['sugar cookie', 'snickerdoodle']
356  
357 [ cookies: chocolate ]
358  
359 favorites = ['chocolate macadamia nut', 'chocolate chip']
360  
361 =head1 DESCRIPTION
362  
363 As the name suggests, event firing is what makes Evented::Configuration unique in
364 comparison to other configuration classes.
365  
366 =head2 Blocks
367  
368 Evented::Configuration's configuration is block-styled, with all keys and values
369 associated with a block. Blocks can be "named," meaning there are several blocks of one
370 type with different names, or they can be "unnamed," meaning there is only one block of
371 that type.
372  
373 =head2 Objective
374  
375 Evented::Configuration's objective interface allows you to store nothing more than the
376 configuration object. Then, make the object accessible where you need it.
377  
378 =head2 Event-driven
379  
380 Evented::Configuration is based upon the Evented::Object framework, firing events each time
381 a configuration changes. This allows software to respond immediately to changes of user
382 settings, etc.
383  
384 =head2 Convenience
385  
386 Most configuration parsers spit out nothing more than a hash reference of keys and values.
387 Evented::Configuration instead supplies several convenient methods for fetching
388 configuration data.
389  
390 =head1 METHODS
391  
392 Evented::Configuration provides several convenient methods for fetching configuration
393 values.
394  
395 =head2 Evented::Configuration->new(%options)
396  
397 Creates a new instance of Evented::Configuration.
398  
399 my $conf = Evented::Configuration->new(conffile => 'etc/some.conf');
400  
401 B<Parameters>
402  
403 =over 4
404  
405 =item *
406  
407 B<options>: a hash of constructor options.
408  
409 =back
410  
411 B<%options - constructor options>
412  
413 =over 4
414  
415 =item *
416  
417 * B<conffile>: file location of a configuration file.
418  
419 =item *
420  
421 * B<hashref>: I<optional>, a hash ref to store configuration values in.
422  
423 =back
424  
425 =head2 $conf->parse_config()
426  
427 Parses the configuration file. Used also to rehash configuration.
428  
429 $conf->parse_config();
430  
431 =head2 $conf->get($block, $key)
432  
433 Fetches a single configuration value.
434  
435 my $value = $conf->get('unnamedBlock', 'someKey');
436 my $other = $conf->get(['blockType', 'namedBlock'], 'someKey');
437  
438 B<Parameters>
439  
440 =over 4
441  
442 =item *
443  
444 B<block>: for unnamed blocks, should be the string block type. for named blocks, should be
445 an array reference in the form of C<[block type, block name]>.
446  
447 =item *
448  
449 B<key>: the key of the configuration value being fetched.
450  
451 =back
452  
453 =head2 $conf->names_of_block($block_type)
454  
455 Returns an array of the names of all blocks of the specified type.
456  
457 foreach my $block_name ($conf->names_of_block('cookies')) {
458 print "name of this cookie block: $block_name\n";
459 }
460  
461 B<Parameters>
462  
463 =over 4
464  
465 =item *
466  
467 B<block_type>: the type of the named block.
468  
469 =back
470  
471 =head2 $conf->keys_of_block($block)
472  
473 Returns an array of all the keys in the specified block.
474  
475 foreach my $key ($conf->keys_of_block('someUnnamedBlock')) {
476 print "someUnnamedBlock unnamed block has key: $key\n";
477 }
478  
479 foreach my $key ($conf->keys_of_block('someNamedBlock', 'someName')) {
480 print "someNamedBlock:someName named block has key: $key\n";
481 }
482  
483 B<Parameters>
484  
485 =over 4
486  
487 =item *
488  
489 B<block>: for unnamed blocks, should be the string block type. for named blocks, should be
490 an array reference in the form of C<[block type, block name]>.
491  
492 =back
493  
494 =head2 $conf->on_change($block, $key, $code, %opts)
495  
496 Attaches an event listener for the configuration change event. This event will be fired
497 even if the value never existed. If you want a listener to be called the first time the
498 configuration is parsed, simply add the listener before calling C<-E<gt>parse_config()>.
499 Otherwise, add listeners later.
500  
501 # an example with an unnamed block
502 $conf->on_change('myUnnamedBlock', 'myKey', sub {
503 my ($event, $old, $new) = @_;
504 ...
505 });
506  
507 # an example with a name block.
508 $conf->on_change(['myNamedBlockType', 'myBlockName'], 'someKey', sub {
509 my ($event, $old, $new) = @_;
510 ...
511 });
512  
513 # an example with an unnamed block and ->register_event() options.
514 $conf->on_change('myUnnamedBlock', 'myKey', sub {
515 my ($event, $old, $new) = @_;
516 ...
517 }, priority => 100, name => 'myCallback');
518  
519 B<Parameters>
520  
521 =over 4
522  
523 =item *
524  
525 B<block>: for unnamed blocks, should be the string block type. for named blocks, should be
526 an array reference in the form of C<[block type, block name]>.
527  
528 =item *
529  
530 B<key>: the key of the configuration value being listened for.
531  
532 =item *
533  
534 B<code>: a code reference to be called when the value is changed.
535  
536 =item *
537  
538 B<opts>: I<optional>, a hash of any other options to be passed to Evented::Object's
539 C<-E<gt>register_event()>.
540  
541 =back
542  
543 =head1 EVENTS
544  
545 Evented::Configuration fires events when configuration values are changed.
546  
547 In any case, events are fired with arguments C<(old value, new value)>.
548  
549 Say you have an unnamed block of type C<myBlock>. If you changed the key C<myKey> in
550 C<myBlock>, Evented::Configuration would fire the event
551 C<change:myBlock:myKey>.
552  
553 Now assume you have a named block of type C<myBlock> with name C<myName>. If you changed
554 the key C<myKey> in C<myBlock:myName>, Evented::Configuration would fire event
555 C<change:myBlock/myName:myKey>.
556  
557 However, it is recommended that you use the C<-E<gt>on_change()> method rather than
558 directly attaching event callbacks. This will insure compatibility for later versions that
559 could possibly change the way events are fired.
560  
561 =head1 SEE ALSO
562  
563 =over 4
564  
565 =item *
566  
567 L<Evented::Object> - the event class that powers Evented::Configuration.
568  
569 =back
570  
571 =head1 AUTHOR
572  
573 L<Mitchell Cooper|https://github.com/cooper> <cooper@cpan.org>
574  
575 Copyright E<copy> 2014. Released under BSD license.
576  
577 =over 4
578  
579 =item *
580  
581 B<IRC channel>: L<irc.notroll.net #k|irc://irc.notroll.net/k>
582  
583 =item *
584  
585 B<Email>: cooper@cpan.org
586  
587 =item *
588  
589 B<CPAN>: L<COOPER|http://search.cpan.org/~cooper/>
590  
591 =item *
592  
593 B<GitHub>: L<cooper|https://github.com/cooper>
594  
595 =back
596  
597 Comments, complaints, and recommendations are accepted. IRC is my preferred communication
598 medium. Bugs may be reported on
599 L<RT|https://rt.cpan.org/Public/Dist/Display.html?Name=Evented-Configuration>.