File Coverage

blib/lib/Config/Any.pm
Criterion Covered Total %
statement 97 105 92.3
branch 33 44 75.0
condition 18 22 81.8
subroutine 11 11 100.0
pod 5 5 100.0
total 164 187 87.7


line stmt bran cond sub pod time code
1             package Config::Any;
2              
3 14     14   975861 use strict;
  14         137  
  14         400  
4 14     14   66 use warnings;
  14         33  
  14         353  
5              
6 14     14   73 use Carp;
  14         27  
  14         858  
7 14     14   6962 use Module::Pluggable::Object ();
  14         141551  
  14         16223  
8              
9             our $VERSION = '0.33';
10              
11             =head1 NAME
12              
13             Config::Any - Load configuration from different file formats, transparently
14              
15             =head1 SYNOPSIS
16              
17             use Config::Any;
18              
19             my $cfg = Config::Any->load_stems({stems => \@filepath_stems, ... });
20             # or
21             my $cfg = Config::Any->load_files({files => \@filepaths, ... });
22              
23             for (@$cfg) {
24             my ($filename, $config) = %$_;
25             $class->config($config);
26             warn "loaded config from file: $filename";
27             }
28              
29             =head1 DESCRIPTION
30              
31             L provides a facility for Perl applications and libraries
32             to load configuration data from multiple different file formats. It supports XML, YAML,
33             JSON, Apache-style configuration, Windows INI files, and even Perl code.
34              
35             The rationale for this module is as follows: Perl programs are deployed on many different
36             platforms and integrated with many different systems. Systems administrators and end
37             users may prefer different configuration formats than the developers. The flexibility
38             inherent in a multiple format configuration loader allows different users to make
39             different choices, without generating extra work for the developers. As a developer
40             you only need to learn a single interface to be able to use the power of different
41             configuration formats.
42              
43             =head1 INTERFACE
44              
45             =head2 load_files( \%args )
46              
47             Config::Any->load_files( { files => \@files } );
48             Config::Any->load_files( { files => \@files, filter => \&filter } );
49             Config::Any->load_files( { files => \@files, use_ext => 1 } );
50             Config::Any->load_files( { files => \@files, flatten_to_hash => 1 } );
51              
52             C attempts to load configuration from the list of files passed in
53             the C parameter, if the file exists.
54              
55             If the C parameter is set, it is used as a callback to modify the configuration
56             data before it is returned. It will be passed a single hash-reference parameter which
57             it should modify in-place.
58              
59             If the C parameter is defined, the loader will attempt to parse the file
60             extension from each filename and will skip the file unless it matches a standard
61             extension for the loading plugins. Only plugins whose standard extensions match the
62             file extension will be used. For efficiency reasons, its use is encouraged, but
63             be aware that you will lose flexibility -- for example, a file called C
64             containing YAML data will not be offered to the YAML plugin, whereas C
65             or C would be.
66              
67             When the C parameter is defined, the loader will return a hash
68             keyed on the file names, as opposed to the usual list of single-key hashes.
69              
70             C also supports a 'force_plugins' parameter, whose value should be an
71             arrayref of plugin names like C. Its intended use is to allow the use
72             of a non-standard file extension while forcing it to be offered to a particular parser.
73             It is not compatible with 'use_ext'.
74              
75             You can supply a C hashref to pass special options to a particular
76             parser object. Example:
77              
78             Config::Any->load_files( { files => \@files, driver_args => {
79             General => { -LowerCaseNames => 1 }
80             } )
81              
82             =cut
83              
84             sub load_files {
85 12     12 1 2878 my ( $class, $args ) = @_;
86              
87 12 100 100     108 unless ( $args && exists $args->{ files } ) {
88 2         27 warn "No files specified!";
89 2         29 return;
90             }
91              
92 10         62 return $class->_load( $args );
93             }
94              
95             =head2 load_stems( \%args )
96              
97             Config::Any->load_stems( { stems => \@stems } );
98             Config::Any->load_stems( { stems => \@stems, filter => \&filter } );
99             Config::Any->load_stems( { stems => \@stems, use_ext => 1 } );
100             Config::Any->load_stems( { stems => \@stems, flatten_to_hash => 1 } );
101              
102             C attempts to load configuration from a list of files which it generates
103             by combining the filename stems list passed in the C parameter with the
104             potential filename extensions from each loader, which you can check with the
105             C classmethod described below. Once this list of possible filenames is
106             built it is treated exactly as in C above, as which it takes the same
107             parameters. Please read the C documentation before using this method.
108              
109             =cut
110              
111             sub load_stems {
112 3     3 1 2441 my ( $class, $args ) = @_;
113              
114 3 100 100     29 unless ( $args && exists $args->{ stems } ) {
115 2         21 warn "No stems specified!";
116 2         13 return;
117             }
118              
119 1         15 my $stems = delete $args->{ stems };
120 1         6 my @files;
121 1         7 for my $s ( @$stems ) {
122 1         13 for my $ext ( $class->extensions ) {
123 10         22 push @files, "$s.$ext";
124             }
125             }
126              
127 1         4 $args->{ files } = \@files;
128 1         13 return $class->_load( $args );
129             }
130              
131             sub _load {
132 11     11   30 my ( $class, $args ) = @_;
133 11 50       37 croak "_load requires a arrayref of file paths" unless $args->{ files };
134              
135 11         29 my $force = defined $args->{ force_plugins };
136 11 50 66     73 if ( !$force and !defined $args->{ use_ext } ) {
137 0         0 warn
138             "use_ext argument was not explicitly set, as of 0.09, this is true by default";
139 0         0 $args->{ use_ext } = 1;
140             }
141              
142             # figure out what plugins we're using
143             my @plugins = $force
144 11 100       56 ? map { eval "require $_;"; $_; } @{ $args->{ force_plugins } }
  1         47  
  1         6  
  1         3  
145             : $class->plugins;
146              
147             # map extensions if we have to
148 11         147 my ( %extension_lut, $extension_re );
149 11   100     97 my $use_ext_lut = !$force && $args->{ use_ext };
150 11 100       39 if ( $use_ext_lut ) {
151 9         23 for my $plugin ( @plugins ) {
152 55         209 for ( $plugin->extensions ) {
153 91   50     382 $extension_lut{ $_ } ||= [];
154 91         120 push @{ $extension_lut{ $_ } }, $plugin;
  91         188  
155             }
156             }
157              
158 9         43 $extension_re = join( '|', keys %extension_lut );
159             }
160              
161             # map args to plugins
162 11         31 my $base_class = __PACKAGE__;
163 11         19 my %loader_args;
164 11         22 for my $plugin ( @plugins ) {
165 62         302 $plugin =~ m{^$base_class\::(.+)};
166 62   50     315 $loader_args{ $plugin } = $args->{ driver_args }->{ $1 } || {};
167             }
168              
169 11         28 my @results;
170              
171 11         24 for my $filename ( @{ $args->{ files } } ) {
  11         32  
172              
173             # don't even bother if it's not there
174 20 100       370 next unless -f $filename;
175              
176 11         64 my @try_plugins = @plugins;
177              
178 11 100       29 if ( $use_ext_lut ) {
179 9         383 $filename =~ m{\.($extension_re)\z};
180              
181 9 100       45 if ( !$1 ) {
182 1         5 $filename =~ m{\.([^.]+)\z};
183 1         204 croak "There are no loaders available for .${1} files";
184             }
185              
186 8         53 @try_plugins = @{ $extension_lut{ $1 } };
  8         39  
187             }
188              
189             # not using use_ext means we try all plugins anyway, so we'll
190             # ignore it for the "unsupported" error
191 10 100       36 my $supported = $use_ext_lut ? 0 : 1;
192 10         25 for my $loader ( @try_plugins ) {
193 13 100       88 next unless $loader->is_supported;
194 10         27 $supported = 1;
195 10         20 my @configs;
196 10         32 my $err = do {
197 10         18 local $@;
198 10         23 @configs = eval { $loader->load( $filename, $loader_args{ $loader } ); };
  10         41  
199 10         64 $@;
200             };
201              
202             # fatal error if we used extension matching
203 10 100 100     304 croak "Error parsing $filename: $err" if $err and $use_ext_lut;
204 9 100 66     106 next if $err or !@configs;
205              
206             # post-process config with a filter callback
207 8 100       46 if ( $args->{ filter } ) {
208 2         37 $args->{ filter }->( $_ ) for @configs;
209             }
210              
211 7 50       82 push @results,
212             { $filename => @configs == 1 ? $configs[ 0 ] : \@configs };
213 7         51 last;
214             }
215              
216 8 100       90 if ( !$supported ) {
217             croak
218             "Cannot load $filename: required support modules are not available.\nPlease install "
219 1         4 . join( " OR ", map { _support_error( $_ ) } @try_plugins );
  1         87  
220             }
221             }
222              
223 7 50       36 if ( defined $args->{ flatten_to_hash } ) {
224 0         0 my %flattened = map { %$_ } @results;
  0         0  
225 0         0 return \%flattened;
226             }
227              
228 7         417 return \@results;
229             }
230              
231             sub _support_error {
232 1     1   4 my $module = shift;
233 1 50       7 if ( $module->can( 'requires_all_of' ) ) {
234             return join( ' and ',
235 1 50       38 map { ref $_ ? join( ' ', @$_ ) : $_ } $module->requires_all_of );
  1         215  
236             }
237 0 0       0 if ( $module->can( 'requires_any_of' ) ) {
238             return 'one of '
239             . join( ' or ',
240 0 0       0 map { ref $_ ? join( ' ', @$_ ) : $_ } $module->requires_any_of );
  0         0  
241             }
242             }
243              
244             =head2 finder( )
245              
246             The C classmethod returns the
247             L
248             object which is used to load the plugins. See the documentation for that module for
249             more information.
250              
251             =cut
252              
253             sub finder {
254 11     11 1 20 my $class = shift;
255 11         135 my $finder = Module::Pluggable::Object->new(
256             search_path => [ __PACKAGE__ ],
257             except => [ __PACKAGE__ . '::Base' ],
258             require => 1
259             );
260 11         240 return $finder;
261             }
262              
263             =head2 plugins( )
264              
265             The C classmethod returns the names of configuration loading plugins as
266             found by L.
267              
268             =cut
269              
270             sub plugins {
271 11     11 1 23 my $class = shift;
272              
273             # filter out things that don't look like our plugins
274 11         46 return grep { $_->isa( 'Config::Any::Base' ) } $class->finder->plugins;
  67         98922  
275             }
276              
277             =head2 extensions( )
278              
279             The C classmethod returns the possible file extensions which can be loaded
280             by C and C. This may be useful if you set the C
281             parameter to those methods.
282              
283             =cut
284              
285             sub extensions {
286 1     1 1 5 my $class = shift;
287             my @ext
288 1         7 = map { $_->extensions } $class->plugins;
  6         25  
289 1 50       35 return wantarray ? @ext : \@ext;
290             }
291              
292             =head1 DIAGNOSTICS
293              
294             =over
295              
296             =item C or C
297              
298             The C and C methods will issue this warning if
299             called with an empty list of files/stems to load.
300              
301             =item C<_load requires a arrayref of file paths>
302              
303             This fatal error will be thrown by the internal C<_load> method. It should not occur
304             but is specified here for completeness. If your code dies with this error, please
305             email a failing test case to the authors below.
306              
307             =back
308              
309             =head1 CONFIGURATION AND ENVIRONMENT
310              
311             Config::Any requires no configuration files or environment variables.
312              
313             =head1 DEPENDENCIES
314              
315             L
316              
317             And at least one of the following for each file type to be supported:
318              
319             =over 4
320              
321             =item *
322              
323             For C<.cnf>, C<.conf> files: L
324              
325             =item *
326              
327             For C<.ini> files: L
328              
329             =item *
330              
331             For C<.json>, C<.jsn> files: L, L, L, L, L, L, L
332              
333             =item *
334              
335             For C<.pl>, C<.perl> files: no additional requirements
336              
337             =item *
338              
339             For C<.xml> files: L
340              
341             =item *
342              
343             For C<.yml>, C<.yaml> files: L, L, L
344              
345             =back
346              
347             Additionally, other file types are supported by third-party plugins in the C
348             namespace, installed separately.
349              
350             =head1 BUGS AND LIMITATIONS
351              
352             Please report any bugs or feature requests to
353             C, or through the web interface at
354             L.
355              
356             =head1 AUTHOR
357              
358             Joel Bernstein
359              
360             =head1 CONTRIBUTORS
361              
362             This module was based on the original
363             L
364             module by Brian Cassidy C<< >>.
365              
366             With ideas and support from Matt S Trout C<< >>.
367              
368             Further enhancements suggested by Evan Kaufman C<< >>.
369              
370             =head1 LICENCE AND COPYRIGHT
371              
372             Copyright (c) 2006, Portugal Telecom C<< http://www.sapo.pt/ >>. All rights reserved.
373             Portions copyright 2007, Joel Bernstein C<< >>.
374              
375             This module is free software; you can redistribute it and/or
376             modify it under the same terms as Perl itself. See L.
377              
378             =head1 DISCLAIMER OF WARRANTY
379              
380             BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
381             FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
382             OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
383             PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
384             EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
385             WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
386             ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
387             YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
388             NECESSARY SERVICING, REPAIR, OR CORRECTION.
389              
390             IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
391             WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
392             REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
393             LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
394             OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
395             THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
396             RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
397             FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
398             SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
399             SUCH DAMAGES.
400              
401             =head1 SEE ALSO
402              
403             L
404             -- now a wrapper around this module.
405              
406             =cut
407              
408             "Drink more beer";