708936aa14a106c16666d96f22232158ef6040bf
[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.09_01';
10
11 =head1 NAME
12
13 Config::Any - Load configuration from different file formats, transparently
14
15 =head1 VERSION
16
17 This document describes Config::Any version 0.09
18
19 =head1 SYNOPSIS
20
21     use Config::Any;
22
23     my $cfg = Config::Any->load_stems({stems => \@filepath_stems, ... });
24     # or
25     my $cfg = Config::Any->load_files({files => \@filepaths, ... });
26
27     for (@$cfg) {
28         my ($filename, $config) = each %$_;
29         $class->config($config);
30         warn "loaded config from file: $filename";
31     }
32
33 =head1 DESCRIPTION
34
35 L<Config::Any|Config::Any> provides a facility for Perl applications and libraries
36 to load configuration data from multiple different file formats. It supports XML, YAML,
37 JSON, Apache-style configuration, Windows INI files, and even Perl code.
38
39 The rationale for this module is as follows: Perl programs are deployed on many different
40 platforms and integrated with many different systems. Systems administrators and end 
41 users may prefer different configuration formats than the developers. The flexibility
42 inherent in a multiple format configuration loader allows different users to make 
43 different choices, without generating extra work for the developers. As a developer
44 you only need to learn a single interface to be able to use the power of different
45 configuration formats.
46
47 =head1 INTERFACE 
48
49 =cut
50
51 =head2 load_files( \%args )
52
53     Config::Any->load_files( { files => \@files } );
54     Config::Any->load_files( { files => \@files, filter  => \&filter } );
55     Config::Any->load_files( { files => \@files, use_ext => 1 } );
56
57 C<load_files()> attempts to load configuration from the list of files passed in
58 the C<files> parameter, if the file exists.
59
60 If the C<filter> parameter is set, it is used as a callback to modify the configuration 
61 data before it is returned. It will be passed a single hash-reference parameter which 
62 it should modify in-place.
63
64 If the C<use_ext> parameter is defined, the loader will attempt to parse the file
65 extension from each filename and will skip the file unless it matches a standard
66 extension for the loading plugins. Only plugins whose standard extensions match the
67 file extension will be used. For efficiency reasons, its use is encouraged, but
68 be aware that you will lose flexibility -- for example, a file called C<myapp.cfg> 
69 containing YAML data will not be offered to the YAML plugin, whereas C<myapp.yml>
70 or C<myapp.yaml> would be.
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
103 C<load_stems()> attempts to load configuration from a list of files which it generates
104 by combining the filename stems list passed in the C<stems> parameter with the 
105 potential filename extensions from each loader, which you can check with the
106 C<extensions()> classmethod described below. Once this list of possible filenames is
107 built it is treated exactly as in C<load_files()> above, as which it takes the same
108 parameters. Please read the C<load_files()> documentation before using this method.
109
110 =cut
111
112 sub load_stems {
113     my ( $class, $args ) = @_;
114
115     unless ( $args && exists $args->{ stems } ) {
116         warn "No stems specified!";
117         return;
118     }
119
120     my $stems = delete $args->{ stems };
121     my @files;
122     for my $s ( @$stems ) {
123         for my $ext ( $class->extensions ) {
124             push @files, "$s.$ext";
125         }
126     }
127
128     $args->{ files } = \@files;
129     return $class->_load( $args );
130 }
131
132 sub _load {
133     my ( $class, $args ) = @_;
134     croak "_load requires a arrayref of file paths" unless $args->{ files };
135
136     if( !defined $args->{ use_ext } ) {
137         warn "use_ext argument was not explicitly set, as of 0.09, this is true by default";
138         $args->{ use_ext } = 1;
139     }
140
141     # figure out what plugins we're using
142     my $force   = defined $args->{ force_plugins };
143     my @plugins = $force ? @{ $args->{ force_plugins } } : $class->plugins;
144
145     # map extensions if we have to
146     my( %extension_lut, $extension_re );
147     my $use_ext_lut = !$force && $args->{ use_ext };
148     if( $use_ext_lut ) {
149         for my $plugin ( @plugins ) {
150             $extension_lut{ $_ } = $plugin for $plugin->extensions;
151         }
152
153         $extension_re = join( '|', keys %extension_lut );
154     }
155
156     # map args to plugins
157     my $base_class = __PACKAGE__;
158     my %loader_args;
159     for my $plugin ( @plugins ) {
160         $plugin =~ m{^$base_class\::(.+)};
161         $loader_args{ $plugin } = $args->{ driver_args }->{ $1 } || {};
162     }
163
164     my @results;
165
166     for my $filename ( @{ $args->{ files } } ) {
167         # don't even bother if it's not there
168         next unless -f $filename;
169
170         my @try_plugins = @plugins;
171
172         if( $use_ext_lut ) {
173             $filename =~ m{\.($extension_re)\z};
174             next unless $1;
175             @try_plugins = $extension_lut{ $1 };
176         }
177
178         for my $loader ( @try_plugins ) {
179             my @configs = eval { $loader->load( $filename, $loader_args{ $loader } ); };
180
181             # fatal error if we used extension matching
182             croak "Error parsing file: $filename" if $@ and $use_ext_lut;
183             next if $@ or !@configs;
184
185             # post-process config with a filter callback
186             if ( $args->{ filter } ) {
187                 $args->{ filter }->( $_ ) for @configs;
188             }
189
190             push @results, { $filename => @configs == 1 ? $configs[ 0 ] : \@configs };
191             last;
192         }
193     }
194
195     return \@results;
196 }
197
198 =head2 finder( )
199
200 The C<finder()> classmethod returns the 
201 L<Module::Pluggable::Object|Module::Pluggable::Object>
202 object which is used to load the plugins. See the documentation for that module for
203 more information.
204
205 =cut
206
207 sub finder {
208     my $class  = shift;
209     my $finder = Module::Pluggable::Object->new(
210         search_path => [ __PACKAGE__ ],
211         require     => 1
212     );
213     return $finder;
214 }
215
216 =head2 plugins( )
217
218 The C<plugins()> classmethod returns the names of configuration loading plugins as 
219 found by L<Module::Pluggable::Object|Module::Pluggable::Object>.
220
221 =cut
222
223 sub plugins {
224     my $class = shift;
225     return $class->finder->plugins;
226 }
227
228 =head2 extensions( )
229
230 The C<extensions()> classmethod returns the possible file extensions which can be loaded
231 by C<load_stems()> and C<load_files()>. This may be useful if you set the C<use_ext>
232 parameter to those methods.
233
234 =cut
235
236 sub extensions {
237     my $class = shift;
238     my @ext = map { $_->extensions } $class->plugins;
239     return wantarray ? @ext : \@ext;
240 }
241
242 =head1 DIAGNOSTICS
243
244 =over
245
246 =item C<No files specified!> or C<No stems specified!>
247
248 The C<load_files()> and C<load_stems()> methods will issue this warning if
249 called with an empty list of files/stems to load.
250
251 =item C<_load requires a arrayref of file paths>
252
253 This fatal error will be thrown by the internal C<_load> method. It should not occur
254 but is specified here for completeness. If your code dies with this error, please
255 email a failing test case to the authors below.
256
257 =back
258
259 =head1 CONFIGURATION AND ENVIRONMENT
260
261 Config::Any requires no configuration files or environment variables.
262
263 =head1 DEPENDENCIES
264
265 L<Module::Pluggable|Module::Pluggable>
266
267 And at least one of the following:
268 L<Config::General|Config::General>
269 L<Config::Tiny|Config::Tiny>
270 L<JSON|JSON>
271 L<YAML|YAML>
272 L<JSON::Syck|JSON::Syck>
273 L<YAML::Syck|YAML::Syck>
274 L<XML::Simple|XML::Simple>
275
276 =head1 INCOMPATIBILITIES
277
278 None reported.
279
280 =head1 BUGS AND LIMITATIONS
281
282 No bugs have been reported.
283
284 Please report any bugs or feature requests to
285 C<bug-config-any@rt.cpan.org>, or through the web interface at
286 L<http://rt.cpan.org>.
287
288 =head1 AUTHOR
289
290 Joel Bernstein  E<lt>rataxis@cpan.orgE<gt>
291
292 =head1 CONTRIBUTORS
293
294 This module was based on the original 
295 L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader>
296 module by Brian Cassidy C<< <bricas@cpan.org> >>.
297
298 With ideas and support from Matt S Trout C<< <mst@shadowcatsystems.co.uk> >>.
299
300 Further enhancements suggested by Evan Kaufman C<< <evank@cpan.org> >>.
301
302 =head1 LICENCE AND COPYRIGHT
303
304 Copyright (c) 2006, Portugal Telecom C<< http://www.sapo.pt/ >>. All rights reserved.
305 Portions copyright 2007, Joel Bernstein C<< <rataxis@cpan.org> >>.
306
307 This module is free software; you can redistribute it and/or
308 modify it under the same terms as Perl itself. See L<perlartistic>.
309
310 =head1 DISCLAIMER OF WARRANTY
311
312 BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
313 FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
314 OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
315 PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
316 EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
317 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
318 ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
319 YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
320 NECESSARY SERVICING, REPAIR, OR CORRECTION.
321
322 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
323 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
324 REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
325 LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
326 OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
327 THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
328 RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
329 FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
330 SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
331 SUCH DAMAGES.
332
333 =head1 SEE ALSO
334
335 L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader> 
336 -- now a wrapper around this module.
337
338 =cut
339
340 "Drink more beer";