File Coverage

blib/lib/Banal/Config.pm
Criterion Covered Total %
statement 25 27 92.5
branch n/a
condition n/a
subroutine 9 9 100.0
pod n/a
total 34 36 94.4


line stmt bran cond sub pod time code
1             package Banal::Config;
2              
3 1     1   27773 use 5.006;
  1         4  
  1         50  
4 1     1   6 use strict;
  1         2  
  1         39  
5 1     1   6 use warnings;
  1         6  
  1         40  
6 1     1   5 no warnings qw(uninitialized);
  1         2  
  1         39  
7              
8             our $VERSION = '0.11';
9              
10 1     1   6 use File::Spec;
  1         2  
  1         24  
11              
12 1     1   653 use Banal::Config::General;
  1         3  
  1         72  
13 1     1   652 use Banal::Config::General::Extended;
  1         3  
  1         53  
14 1     1   1161 use Banal::Utils::Data qw(banal_get_data);
  1         13172  
  1         58  
15              
16              
17 1     1   417 use Moose;
  0            
  0            
18              
19             has 'verbose' => (is => 'rw', lazy_build=>1);
20             has 'debug' => (is => 'rw', lazy_build=>1);
21             has 'switches' => (is => 'rw', isa => 'HashRef', default=>sub{{}}); # Typically contains command line switches as produced by Getopt::Long or Getopt::Descriptive, or something that resembles it.
22             has 'options' => (is => 'rw', isa => 'HashRef', default=>sub{{}}); # The hash that gets passed to "new" for the actual configuration object (xcfg). The 'ConfigFile' option will default to the value of 'source' property.
23             has 'source' => (is => 'rw', isa => 'Str', lazy_build=>1); # The path to the configuration file. If it's not set, it will be guessed based on the name of the running process ($0). Note that this may be overriden by the "-ConfigFile" option.
24             has 'xcfg_class' => (is => 'rw', isa => 'Str', default=>'Banal::Config::General::Extended' );
25             has 'xcfg' => (
26             is => 'rw',
27             isa => 'Banal::Config::General::Extended',
28             lazy_build => 1,
29             handles => [qw (obj value hash array is_hash is_array is_scalar exists keys delete configfile find)],
30             );
31            
32            
33             has 'cfg_hash' => (is => 'rw', lazy_build=>1);
34              
35             has 'cfg_context' => (is => 'rw', lazy_build=>1); # If you do not set this, you can also provide it with the 'cfg_context' switch or the '-Banal_ConfigContext' option. Otherwise, it will take upon the value given by 'cfg_context_default'
36             has 'cfg_context_default' => (is => 'rw', lazy_build=>1); # You may wish to override this, if needed.
37              
38             has 'default_options_for_banal_get_data' => (is => 'rw', default=>sub {
39             {
40             search_upwards_while_not_defined => 1,
41             use_path_semantics => 1,
42             path_separator => '/',
43             remove_extra_separators => 1,
44             remove_leading_separator => 0,
45             remove_trailing_separator => 1,
46             remove_empty_segments => 1,
47             try_avoiding_repeated_segments => 1,
48             lower_case => 1,
49             trim => 1,
50             }
51             }
52             );
53              
54              
55              
56             #-----------------------------------------------
57             sub load {
58             my $self = shift;
59            
60             return $self->reload();
61             }
62              
63             #-----------------------------------------------
64             sub reload {
65             my $self = shift;
66             my $cc = $self->xcfg_class;
67             my $opts = $self->options;
68            
69             eval {
70             require $cc;
71             };
72             my $c = $cc->new(-ConfigFile=>$self->source, %$opts); # source can be overriden with the options.
73            
74             return $self->xcfg($c);
75             }
76            
77            
78             #
79             #-----------------------------------------------
80             sub get_cfg {
81             my $self = shift;
82             return $self->grab_cfg(key=>[@_]);
83             }
84              
85              
86             #-----------------------------------------------
87             sub grab_cfg {
88             my $self = shift;
89             my $args = {@_};
90            
91             $args->{data} ||= $self->cfg_hash();
92            
93             unless (defined($args->{context})) {
94             $args->{context} = $self->cfg_context();
95             }
96            
97             unless (defined($args->{options})) {
98             # get a copy.
99             my $opts = $self->default_options_for_banal_get_data();
100             $args->{options} = {%$opts};
101             }
102            
103              
104             return banal_get_data(%$args);
105             }
106              
107              
108             #***************************************************
109             # Possible Overrides
110             #***************************************************
111             #-----------------------------------------------
112             sub get_default_config_term {
113             my $self = shift;
114            
115             my ($prg_volume, $prg_dirs, $prg_name) = File::Spec->splitpath( $0 );
116            
117             return $prg_name;
118             }
119              
120             #-----------------------------------------------
121             sub get_default_config_file_base_name {
122             my $self = shift;
123            
124             return $self->get_default_config_term();
125             }
126              
127              
128             #***************************************************
129             # Less likely overrides
130             #***************************************************
131             #-----------------------------------------------
132             sub guess_config_file_path {
133             my $self = shift;
134             my $args = $self->switches;
135             $args = {%$args, @_}; # swicth overrides are possible by passing arguments to the function.
136            
137             # If we have an explicit argument for the config file path, return that.
138             foreach my $opt ($self->get_possible_option_names_for_config_file_path(@_)) {
139             my $p = $args->{$opt};
140             return $p if ($p);
141             }
142            
143             # Or else, if we have a defined ENVIRONMENT variable that contains a value, return that.
144             foreach my $v ($self->get_possible_environment_variable_names_for_config_file_path(@_)) {
145             my $p = $ENV{$v};
146             return $p if ($p);
147             }
148            
149             # Otherwise, return the first config file that exists in a list of possible file paths (normally based on the program name).
150             foreach my $p ($self->get_possible_config_file_paths(@_)) {
151             return $p if ($p and (-e $p));
152             }
153            
154            
155             # Too bad. We've got nothing.
156            
157             warn "No config file can be accessed. Does it exist?!\n" if $self->verbose > 7; # DEBUG
158             return;
159             }
160              
161            
162             #-----------------------------------------------
163             sub get_possible_option_names_for_config_file_path {
164             my $self = shift;
165             my @possibilities;
166            
167             my $term = $self->get_default_config_term();
168            
169             @possibilities = (
170             $term . "_cfg",
171             "cfg_" . $term,
172             "cfg",
173             );
174             return @possibilities;
175             }
176              
177             #-----------------------------------------------
178             sub get_possible_environment_variable_names_for_config_file_path {
179             my $self = shift;
180             my @possibilities;
181            
182             my $term = $self->get_default_config_term();
183            
184             @possibilities = (
185             uc($term . "_CFG"),
186             uc("CFG_" . $term),
187             );
188             return @possibilities;
189             }
190              
191             #-----------------------------------------------
192             sub get_possible_config_file_paths {
193             my $self = shift;
194             my @possibilities;
195              
196             my $base_name = $self->get_default_config_file_base_name();
197            
198             @possibilities = (
199             "./test/etc/" . $base_name . ".conf", # this one is for testing purposes during "make test"
200             "~/." . $base_name . ".conf",
201             "/etc/" . $base_name . ".conf",
202             "." . $base_name . ".conf",
203             );
204             return @possibilities;
205             }
206              
207              
208              
209              
210              
211             #**********************************************
212             # BUILDERS
213             #**********************************************
214             #--------------------------------------
215             sub _build_verbose {
216             my $self = shift;
217            
218             return $self->switches->verbose;
219             }
220              
221             #--------------------------------------
222             sub _build_debug {
223             my $self = shift;
224            
225             return ($self->verbose >= 7);
226             }
227              
228             #--------------------------------------
229             sub _build_source {
230             my $self = shift;
231             return $self->guess_config_file_path();
232             }
233              
234             #--------------------------------------
235             sub _build_xcfg {
236             my $self = shift;
237             return $self->load();
238             }
239              
240             #--------------------------------------
241             sub _build_cfg_hash {
242             my $self = shift;
243             return $self->xcfg()->config;
244             }
245              
246              
247             #--------------------------------------
248             sub _build_cfg_context {
249             my $self = shift;
250             my $ctx = $self->switches->{cfg_context} || $self->options->{-Banal_ConfigContext} || $self->cfg_context_default;
251             return $ctx;
252             }
253              
254             #--------------------------------------
255             sub _build_cfg_context_default {
256             my $self = shift;
257             my $ctx = $self->get_default_config_term();
258             return $ctx;
259             }
260              
261              
262              
263             no Moose;
264             __PACKAGE__->meta->make_immutable;
265              
266             1;
267              
268              
269              
270              
271              
272             __END__
273              
274             =head1 NAME
275              
276             Banal::Config - A convenient wrapper around Config::General
277              
278              
279             =head1 SYNOPSIS
280              
281             Quick summary of what the module does.
282              
283             Perhaps a little code snippet.
284              
285             use Banal::Config;
286              
287             my $foo = Banal::Config->new(options=>{...}, switches=>{...});
288             ...
289              
290             =head1 EXPORT
291              
292             None.
293              
294             =head1 EXPORT_OK
295              
296             None.
297              
298             =head1 CLASS METHODS
299              
300             =head2 get_default_config_term()
301              
302             This "term" is in several places, such as :
303             - for generating the name of the default command line switch possibly holding the config file path (used when no explicit config file path is given)
304             - for generating the name of the default environment variable possibly holding the config file path (used when no explicit config file path is given)
305             - for generating the default base name of the config file, which in turn is searched in several places (used when no explicit config file path is given)
306             - for generating the default configuration context within the config file.
307            
308            
309             By default, returns the base name of the main program (script).
310              
311             Can be overridden.
312              
313              
314             =head2 get_default_config_file_base_name()
315              
316             The default base name of the configuration file, which will be searched in several places when trying to "guess" the config file path.
317             This would only be needed when there is no explicit config file path given.
318              
319             By default, simply calls "get_default_config_term()".
320              
321              
322             =head2 guess_config_file_path()
323              
324             A call to this class method is made in order to build the default value of the "source" attribute, which will be used as the source path for the config file UNLESS one is explicetly given in the options argument to new().
325              
326             The current implementation goes as follows:
327             - It will first try suitable "switches". If one that designates the config fie path is defined, the that one will be return. By default, here are those switches that will be checked for definedness:
328             cfg_[%TERM%] [%TERM%]_cfg cfg
329            
330             where TERM is obtained by a call to get_default_config_term()
331            
332             - Then, we will see if there is an ENVIRONMENT variable,
333             [%TERM%]_CFG
334             CFG_[%TERM%]
335            
336             - or else, we will use as config, the first file that exists in the following list:
337              
338             "./test/etc/" . $base_name . ".conf", # this one is for testing purposes during "make test"
339             "~/." . $base_name . ".conf",
340             "/etc/" . $base_name . ".conf",
341             "." . $base_name . ".conf",
342              
343             where $base_name is obtained by a call to get_default_config_file_base_name()
344            
345            
346             =head2 get_possible_option_names_for_config_file_path
347              
348             Used by guess_config_file_path() to check for command line switches.
349              
350             Currently returns the list: cfg_[%TERM%] [%TERM%]_cfg cfg
351             where TERM is obtained by a call to get_default_config_term()
352            
353            
354             =head2 get_possible_environment_variable_names_for_config_file_path
355              
356             Used by guess_config_file_path() to check for ENVIRONMENT variables.
357              
358             Currently returns the list: [%TERM%]_CFG CFG_[%TERM%]
359              
360             where TERM is obtained by a call to get_default_config_term()
361            
362              
363             =head2 get_possible_config_file_paths()
364              
365             Used by guess_config_file_path() after trying command line swictches and ENV variables.
366             At this point (when everything else is exhausted), the first file that exists in the list returned by this function will be used as the config file.
367              
368             Currently returns the list:
369              
370             "./test/etc/" . $base_name . ".conf", # this one is for testing purposes during "make test"
371             "~/." . $base_name . ".conf",
372             "/etc/" . $base_name . ".conf",
373             "." . $base_name . ".conf",
374              
375             where $base_name is obtained by a call to get_default_config_file_base_name()
376            
377            
378             =head1 METHODS
379              
380             =head2 get_cfg()
381              
382             Return the configuration value given by key (which may also be an ARRAY of path segments, or one long config key in path notation, or a mix).
383              
384             If the value for the given key is not defined, it will be tried in outer contexts (in concentric circles) until it is found.
385             This way, it is possible to set a value in an outer configuration context, and use it within.
386              
387             A simple call to:
388              
389             $self->grab_cfg(key=>[@_]);
390              
391             =head2 grab_cfg()
392              
393             Return the configuration value given by key (which may also be an ARRAY of path segments, or one long config key in path notation, or a mix).
394              
395             If the value for the given key is not defined, it will be tried in outer contexts (in concentric circles) until it is found.
396             This way, it is possible to set a value in an outer configuration context, and use it within.
397              
398             $value = $c->grab_cfg(key => {..}, options => {..}, context=>{..})
399              
400              
401             By default:
402             options : $self->default_options_for_banal_get_data()
403             context : $self->cfg_context();
404            
405              
406             =head2 reload()
407              
408             Reload the configuratoin file from disk.
409              
410              
411             =head2 load()
412              
413             Reload the configuratoin file from disk (when the first such call needs to be distinguished, as opposed to reload().)
414              
415              
416              
417             =head1 AUTHOR
418              
419             "aulusoy", C<< <"dev (at) ulusoy.name"> >>
420              
421             =head1 BUGS
422              
423             Please report any bugs or feature requests to C<bug-banal-config at rt.cpan.org>, or through
424             the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Banal-Config>. I will be notified, and then you'll
425             automatically be notified of progress on your bug as I make changes.
426              
427              
428              
429             =head1 SUPPORT
430              
431             You can find documentation for this module with the perldoc command.
432              
433             perldoc Banal::Config
434              
435              
436             You can also look for information at:
437              
438             =over 4
439              
440             =item * RT: CPAN's request tracker (report bugs here)
441              
442             L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Banal-Config>
443              
444             =item * AnnoCPAN: Annotated CPAN documentation
445              
446             L<http://annocpan.org/dist/Banal-Config>
447              
448             =item * CPAN Ratings
449              
450             L<http://cpanratings.perl.org/d/Banal-Config>
451              
452             =item * Search CPAN
453              
454             L<http://search.cpan.org/dist/Banal-Config/>
455              
456             =back
457              
458              
459             =head1 ACKNOWLEDGEMENTS
460              
461              
462             =head1 LICENSE AND COPYRIGHT
463              
464             Copyright 2014 "aulusoy".
465              
466             This program is free software; you can redistribute it and/or modify it
467             under the terms of the the Artistic License (2.0). You may obtain a
468             copy of the full license at:
469              
470             L<http://www.perlfoundation.org/artistic_license_2_0>
471              
472             Any use, modification, and distribution of the Standard or Modified
473             Versions is governed by this Artistic License. By using, modifying or
474             distributing the Package, you accept this license. Do not use, modify,
475             or distribute the Package, if you do not accept this license.
476              
477             If your Modified Version has been derived from a Modified Version made
478             by someone other than you, you are nevertheless required to ensure that
479             your Modified Version complies with the requirements of this license.
480              
481             This license does not grant you the right to use any trademark, service
482             mark, tradename, or logo of the Copyright Holder.
483              
484             This license includes the non-exclusive, worldwide, free-of-charge
485             patent license to make, have made, use, offer to sell, sell, import and
486             otherwise transfer the Package with respect to any patent claims
487             licensable by the Copyright Holder that are necessarily infringed by the
488             Package. If you institute patent litigation (including a cross-claim or
489             counterclaim) against any party alleging that the Package constitutes
490             direct or contributory patent infringement, then this Artistic License
491             to you shall terminate on the date that such litigation is filed.
492              
493             Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
494             AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
495             THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
496             PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
497             YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
498             CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
499             CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
500             EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
501              
502              
503             =cut
504              
505             1; # End of Banal::Config