7 use Module::Pluggable::Object ();
13 Config::Any - Load configuration from different file formats, transparently
19 my $cfg = Config::Any->load_stems({stems => \@filepath_stems, ... });
21 my $cfg = Config::Any->load_files({files => \@filepaths, ... });
24 my ($filename, $config) = %$_;
25 $class->config($config);
26 warn "loaded config from file: $filename";
31 L<Config::Any|Config::Any> 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.
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.
45 =head2 load_files( \%args )
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 } );
52 C<load_files()> attempts to load configuration from the list of files passed in
53 the C<files> parameter, if the file exists.
55 If the C<filter> 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.
59 If the C<use_ext> 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<myapp.cfg>
64 containing YAML data will not be offered to the YAML plugin, whereas C<myapp.yml>
65 or C<myapp.yaml> would be.
67 When the C<flatten_to_hash> 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.
70 C<load_files()> also supports a 'force_plugins' parameter, whose value should be an
71 arrayref of plugin names like C<Config::Any::INI>. 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'.
75 You can supply a C<driver_args> hashref to pass special options to a particular
76 parser object. Example:
78 Config::Any->load_files( { files => \@files, driver_args => {
79 General => { -LowerCaseNames => 1 }
85 my ( $class, $args ) = @_;
87 unless ( $args && exists $args->{ files } ) {
88 warn "No files specified!";
92 return $class->_load( $args );
95 =head2 load_stems( \%args )
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 } );
102 C<load_stems()> attempts to load configuration from a list of files which it generates
103 by combining the filename stems list passed in the C<stems> parameter with the
104 potential filename extensions from each loader, which you can check with the
105 C<extensions()> classmethod described below. Once this list of possible filenames is
106 built it is treated exactly as in C<load_files()> above, as which it takes the same
107 parameters. Please read the C<load_files()> documentation before using this method.
112 my ( $class, $args ) = @_;
114 unless ( $args && exists $args->{ stems } ) {
115 warn "No stems specified!";
119 my $stems = delete $args->{ stems };
121 for my $s ( @$stems ) {
122 for my $ext ( $class->extensions ) {
123 push @files, "$s.$ext";
127 $args->{ files } = \@files;
128 return $class->_load( $args );
132 my ( $class, $args ) = @_;
133 croak "_load requires a arrayref of file paths" unless $args->{ files };
135 my $force = defined $args->{ force_plugins };
136 if ( !$force and !defined $args->{ use_ext } ) {
138 "use_ext argument was not explicitly set, as of 0.09, this is true by default";
139 $args->{ use_ext } = 1;
142 # figure out what plugins we're using
144 ? map { eval "require $_;"; $_; } @{ $args->{ force_plugins } }
147 # map extensions if we have to
148 my ( %extension_lut, $extension_re );
149 my $use_ext_lut = !$force && $args->{ use_ext };
150 if ( $use_ext_lut ) {
151 for my $plugin ( @plugins ) {
152 for ( $plugin->extensions ) {
153 $extension_lut{ $_ } ||= [];
154 push @{ $extension_lut{ $_ } }, $plugin;
158 $extension_re = join( '|', keys %extension_lut );
161 # map args to plugins
162 my $base_class = __PACKAGE__;
164 for my $plugin ( @plugins ) {
165 $plugin =~ m{^$base_class\::(.+)};
166 $loader_args{ $plugin } = $args->{ driver_args }->{ $1 } || {};
171 for my $filename ( @{ $args->{ files } } ) {
173 # don't even bother if it's not there
174 next unless -f $filename;
176 my @try_plugins = @plugins;
178 if ( $use_ext_lut ) {
179 $filename =~ m{\.($extension_re)\z};
182 $filename =~ m{\.([^.]+)\z};
183 croak "There are no loaders available for .${1} files";
186 @try_plugins = @{ $extension_lut{ $1 } };
189 # not using use_ext means we try all plugins anyway, so we'll
190 # ignore it for the "unsupported" error
191 my $supported = $use_ext_lut ? 0 : 1;
192 for my $loader ( @try_plugins ) {
193 next unless $loader->is_supported;
198 @configs = eval { $loader->load( $filename, $loader_args{ $loader } ); };
202 # fatal error if we used extension matching
203 croak "Error parsing $filename: $err" if $err and $use_ext_lut;
204 next if $err or !@configs;
206 # post-process config with a filter callback
207 if ( $args->{ filter } ) {
208 $args->{ filter }->( $_ ) for @configs;
212 { $filename => @configs == 1 ? $configs[ 0 ] : \@configs };
218 "Cannot load $filename: required support modules are not available.\nPlease install "
219 . join( " OR ", map { _support_error( $_ ) } @try_plugins );
223 if ( defined $args->{ flatten_to_hash } ) {
224 my %flattened = map { %$_ } @results;
233 if ( $module->can( 'requires_all_of' ) ) {
234 return join( ' and ',
235 map { ref $_ ? join( ' ', @$_ ) : $_ } $module->requires_all_of );
237 if ( $module->can( 'requires_any_of' ) ) {
240 map { ref $_ ? join( ' ', @$_ ) : $_ } $module->requires_any_of );
246 The C<finder()> classmethod returns the
247 L<Module::Pluggable::Object|Module::Pluggable::Object>
248 object which is used to load the plugins. See the documentation for that module for
255 my $finder = Module::Pluggable::Object->new(
256 search_path => [ __PACKAGE__ ],
257 except => [ __PACKAGE__ . '::Base' ],
265 The C<plugins()> classmethod returns the names of configuration loading plugins as
266 found by L<Module::Pluggable::Object|Module::Pluggable::Object>.
273 # filter out things that don't look like our plugins
274 return grep { $_->isa( 'Config::Any::Base' ) } $class->finder->plugins;
279 The C<extensions()> classmethod returns the possible file extensions which can be loaded
280 by C<load_stems()> and C<load_files()>. This may be useful if you set the C<use_ext>
281 parameter to those methods.
288 = map { $_->extensions } $class->plugins;
289 return wantarray ? @ext : \@ext;
296 =item C<No files specified!> or C<No stems specified!>
298 The C<load_files()> and C<load_stems()> methods will issue this warning if
299 called with an empty list of files/stems to load.
301 =item C<_load requires a arrayref of file paths>
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.
309 =head1 CONFIGURATION AND ENVIRONMENT
311 Config::Any requires no configuration files or environment variables.
315 L<Module::Pluggable::Object|Module::Pluggable::Object>
317 And at least one of the following:
318 L<Config::General|Config::General>
319 L<Config::Tiny|Config::Tiny>
322 L<JSON::Syck|JSON::Syck>
323 L<YAML::Syck|YAML::Syck>
324 L<XML::Simple|XML::Simple>
326 =head1 INCOMPATIBILITIES
330 =head1 BUGS AND LIMITATIONS
332 No bugs have been reported.
334 Please report any bugs or feature requests to
335 C<bug-config-any@rt.cpan.org>, or through the web interface at
336 L<https://rt.cpan.org/Public/Dist/Display.html?Name=Config-Any>.
340 Joel Bernstein <rataxis@cpan.org>
344 This module was based on the original
345 L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader>
346 module by Brian Cassidy C<< <bricas@cpan.org> >>.
348 With ideas and support from Matt S Trout C<< <mst@shadowcatsystems.co.uk> >>.
350 Further enhancements suggested by Evan Kaufman C<< <evank@cpan.org> >>.
352 =head1 LICENCE AND COPYRIGHT
354 Copyright (c) 2006, Portugal Telecom C<< http://www.sapo.pt/ >>. All rights reserved.
355 Portions copyright 2007, Joel Bernstein C<< <rataxis@cpan.org> >>.
357 This module is free software; you can redistribute it and/or
358 modify it under the same terms as Perl itself. See L<perlartistic>.
360 =head1 DISCLAIMER OF WARRANTY
362 BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
363 FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
364 OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
365 PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
366 EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
367 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
368 ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
369 YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
370 NECESSARY SERVICING, REPAIR, OR CORRECTION.
372 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
373 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
374 REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
375 LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
376 OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
377 THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
378 RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
379 FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
380 SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
385 L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader>
386 -- now a wrapper around this module.