release date + misc.
[p5sagit/Config-Any.git] / lib / Config / Any.pm
1 package Config::Any;
2
3 use strict;
4 use warnings;
5
6 use Carp;
7 use Module::Pluggable::Object ();
8
9 our $VERSION = '0.13';
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<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.
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 =cut
46
47 =head2 load_files( \%args )
48
49     Config::Any->load_files( { files => \@files } );
50     Config::Any->load_files( { files => \@files, filter  => \&filter } );
51     Config::Any->load_files( { files => \@files, use_ext => 1 } );
52     Config::Any->load_files( { files => \@files, flatten_to_hash => 1 } );
53
54 C<load_files()> attempts to load configuration from the list of files passed in
55 the C<files> parameter, if the file exists.
56
57 If the C<filter> parameter is set, it is used as a callback to modify the configuration 
58 data before it is returned. It will be passed a single hash-reference parameter which 
59 it should modify in-place.
60
61 If the C<use_ext> parameter is defined, the loader will attempt to parse the file
62 extension from each filename and will skip the file unless it matches a standard
63 extension for the loading plugins. Only plugins whose standard extensions match the
64 file extension will be used. For efficiency reasons, its use is encouraged, but
65 be aware that you will lose flexibility -- for example, a file called C<myapp.cfg> 
66 containing YAML data will not be offered to the YAML plugin, whereas C<myapp.yml>
67 or C<myapp.yaml> would be.
68
69 When the C<flatten_to_hash> parameter is defined, the loader will return a hash
70 keyed on the file names, as opposed to the usual list of single-key hashes.
71
72 C<load_files()> also supports a 'force_plugins' parameter, whose value should be an
73 arrayref of plugin names like C<Config::Any::INI>. Its intended use is to allow the use 
74 of a non-standard file extension while forcing it to be offered to a particular parser.
75 It is not compatible with 'use_ext'. 
76
77 You can supply a C<driver_args> hashref to pass special options to a particular
78 parser object. Example:
79
80     Config::Any->load_files( { files => \@files, driver_args => {
81         General => { -LowerCaseNames => 1 }
82     } )
83
84 =cut
85
86 sub load_files {
87     my ( $class, $args ) = @_;
88
89     unless ( $args && exists $args->{ files } ) {
90         warn "No files specified!";
91         return;
92     }
93
94     return $class->_load( $args );
95 }
96
97 =head2 load_stems( \%args )
98
99     Config::Any->load_stems( { stems => \@stems } );
100     Config::Any->load_stems( { stems => \@stems, filter  => \&filter } );
101     Config::Any->load_stems( { stems => \@stems, use_ext => 1 } );
102     Config::Any->load_stems( { stems => \@stems, flatten_to_hash => 1 } );
103
104 C<load_stems()> attempts to load configuration from a list of files which it generates
105 by combining the filename stems list passed in the C<stems> parameter with the 
106 potential filename extensions from each loader, which you can check with the
107 C<extensions()> classmethod described below. Once this list of possible filenames is
108 built it is treated exactly as in C<load_files()> above, as which it takes the same
109 parameters. Please read the C<load_files()> documentation before using this method.
110
111 =cut
112
113 sub load_stems {
114     my ( $class, $args ) = @_;
115
116     unless ( $args && exists $args->{ stems } ) {
117         warn "No stems specified!";
118         return;
119     }
120
121     my $stems = delete $args->{ stems };
122     my @files;
123     for my $s ( @$stems ) {
124         for my $ext ( $class->extensions ) {
125             push @files, "$s.$ext";
126         }
127     }
128
129     $args->{ files } = \@files;
130     return $class->_load( $args );
131 }
132
133 sub _load {
134     my ( $class, $args ) = @_;
135     croak "_load requires a arrayref of file paths" unless $args->{ files };
136
137     my $force = defined $args->{ force_plugins };
138     if ( !$force and !defined $args->{ use_ext } ) {
139         warn
140             "use_ext argument was not explicitly set, as of 0.09, this is true by default";
141         $args->{ use_ext } = 1;
142     }
143
144     # figure out what plugins we're using
145     my @plugins = $force ? @{ $args->{ force_plugins } } : $class->plugins;
146
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             $extension_lut{ $_ } = $plugin for $plugin->extensions;
153         }
154
155         $extension_re = join( '|', keys %extension_lut );
156     }
157
158     # map args to plugins
159     my $base_class = __PACKAGE__;
160     my %loader_args;
161     for my $plugin ( @plugins ) {
162         $plugin =~ m{^$base_class\::(.+)};
163         $loader_args{ $plugin } = $args->{ driver_args }->{ $1 } || {};
164     }
165
166     my @results;
167
168     for my $filename ( @{ $args->{ files } } ) {
169
170         # don't even bother if it's not there
171         next unless -f $filename;
172
173         my @try_plugins = @plugins;
174
175         if ( $use_ext_lut ) {
176             $filename =~ m{\.($extension_re)\z};
177             next unless $1;
178             @try_plugins = $extension_lut{ $1 };
179         }
180
181         for my $loader ( @try_plugins ) {
182             next unless $loader->is_supported;
183             my @configs
184                 = eval { $loader->load( $filename, $loader_args{ $loader } ); };
185
186             # fatal error if we used extension matching
187             croak "Error parsing $filename: $@" if $@ and $use_ext_lut;
188             next if $@ or !@configs;
189
190             # post-process config with a filter callback
191             if ( $args->{ filter } ) {
192                 $args->{ filter }->( $_ ) for @configs;
193             }
194
195             push @results,
196                 { $filename => @configs == 1 ? $configs[ 0 ] : \@configs };
197             last;
198         }
199     }
200
201     if ( defined $args->{ flatten_to_hash } ) {
202         my %flattened = map { %$_ } @results;
203         return \%flattened;
204     }
205
206     return \@results;
207 }
208
209 =head2 finder( )
210
211 The C<finder()> classmethod returns the 
212 L<Module::Pluggable::Object|Module::Pluggable::Object>
213 object which is used to load the plugins. See the documentation for that module for
214 more information.
215
216 =cut
217
218 sub finder {
219     my $class  = shift;
220     my $finder = Module::Pluggable::Object->new(
221         search_path => [ __PACKAGE__ ],
222         require     => 1
223     );
224     return $finder;
225 }
226
227 =head2 plugins( )
228
229 The C<plugins()> classmethod returns the names of configuration loading plugins as 
230 found by L<Module::Pluggable::Object|Module::Pluggable::Object>.
231
232 =cut
233
234 sub plugins {
235     my $class = shift;
236     return $class->finder->plugins;
237 }
238
239 =head2 extensions( )
240
241 The C<extensions()> classmethod returns the possible file extensions which can be loaded
242 by C<load_stems()> and C<load_files()>. This may be useful if you set the C<use_ext>
243 parameter to those methods.
244
245 =cut
246
247 sub extensions {
248     my $class = shift;
249     my @ext = map { $_->extensions } $class->plugins;
250     return wantarray ? @ext : \@ext;
251 }
252
253 =head1 DIAGNOSTICS
254
255 =over
256
257 =item C<No files specified!> or C<No stems specified!>
258
259 The C<load_files()> and C<load_stems()> methods will issue this warning if
260 called with an empty list of files/stems to load.
261
262 =item C<_load requires a arrayref of file paths>
263
264 This fatal error will be thrown by the internal C<_load> method. It should not occur
265 but is specified here for completeness. If your code dies with this error, please
266 email a failing test case to the authors below.
267
268 =back
269
270 =head1 CONFIGURATION AND ENVIRONMENT
271
272 Config::Any requires no configuration files or environment variables.
273
274 =head1 DEPENDENCIES
275
276 L<Module::Pluggable|Module::Pluggable>
277
278 And at least one of the following:
279 L<Config::General|Config::General>
280 L<Config::Tiny|Config::Tiny>
281 L<JSON|JSON>
282 L<YAML|YAML>
283 L<JSON::Syck|JSON::Syck>
284 L<YAML::Syck|YAML::Syck>
285 L<XML::Simple|XML::Simple>
286
287 =head1 INCOMPATIBILITIES
288
289 None reported.
290
291 =head1 BUGS AND LIMITATIONS
292
293 No bugs have been reported.
294
295 Please report any bugs or feature requests to
296 C<bug-config-any@rt.cpan.org>, or through the web interface at
297 L<http://rt.cpan.org>.
298
299 =head1 AUTHOR
300
301 Joel Bernstein E<lt>rataxis@cpan.orgE<gt>
302
303 =head1 CONTRIBUTORS
304
305 This module was based on the original 
306 L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader>
307 module by Brian Cassidy C<< <bricas@cpan.org> >>.
308
309 With ideas and support from Matt S Trout C<< <mst@shadowcatsystems.co.uk> >>.
310
311 Further enhancements suggested by Evan Kaufman C<< <evank@cpan.org> >>.
312
313 =head1 LICENCE AND COPYRIGHT
314
315 Copyright (c) 2006, Portugal Telecom C<< http://www.sapo.pt/ >>. All rights reserved.
316 Portions copyright 2007, Joel Bernstein C<< <rataxis@cpan.org> >>.
317
318 This module is free software; you can redistribute it and/or
319 modify it under the same terms as Perl itself. See L<perlartistic>.
320
321 =head1 DISCLAIMER OF WARRANTY
322
323 BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
324 FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
325 OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
326 PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
327 EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
328 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
329 ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
330 YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
331 NECESSARY SERVICING, REPAIR, OR CORRECTION.
332
333 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
334 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
335 REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
336 LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
337 OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
338 THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
339 RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
340 FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
341 SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
342 SUCH DAMAGES.
343
344 =head1 SEE ALSO
345
346 L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader> 
347 -- now a wrapper around this module.
348
349 =cut
350
351 "Drink more beer";