more code updates, before i look in depth at the _load() routine
[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';
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 # this is where we do the real work
133 # it's a private class-method because users should use the interface described
134 # in the POD.
135 sub _load {
136     my ( $class, $args ) = @_;
137     my ( $files_ref, $filter_cb, $use_ext, $force_plugins_ref )
138         = @{ $args }{ qw(files filter use_ext force_plugins) };
139     croak "_load requires a arrayref of file paths" unless defined $files_ref;
140
141     my %files         = map { $_ => 1 } @$files_ref;
142     my %force_plugins = map { $_ => 1 } @$force_plugins_ref;
143     my $enforcing = keys %force_plugins ? 1 : 0;
144
145     my $final_configs     = [];
146     my $originally_loaded = {};
147
148     # perform a separate file loop for each loader
149     for my $loader ( $class->plugins ) {
150         next if $enforcing && not defined $force_plugins{ $loader };
151         last unless keys %files;
152         my %ext = map { $_ => 1 } $loader->extensions;
153
154         my ( $loader_class ) = $loader =~ /::([^:]+)$/;
155         my $driver_args = $args->{ driver_args }{ $loader_class } || {};
156
157     FILE:
158         for my $filename ( keys %files ) {
159             next unless -f $filename;
160
161        # use file extension to decide whether this loader should try this file
162        # use_ext => 1 hits this block
163             if ( defined $use_ext && !$enforcing ) {
164                 my $matched_ext = 0;
165             EXT:
166                 for my $e ( keys %ext ) {
167                     next EXT unless $filename =~ m{ \. $e \z }xms;
168                     next FILE unless exists $ext{ $e };
169                     $matched_ext = 1;
170                 }
171
172                 next FILE unless $matched_ext;
173             }
174
175             my $config;
176             eval { $config = $loader->load( $filename, $driver_args ); };
177
178             next if $@;         # if it croaked or warned, we can't use it
179             next if !$config;
180             delete $files{ $filename };
181
182             # post-process config with a filter callback, if we got one
183             $filter_cb->( $config ) if defined $filter_cb;
184
185             push @$final_configs, { $filename => $config };
186         }
187     }
188
189     return $final_configs;
190 }
191
192 =head2 finder( )
193
194 The C<finder()> classmethod returns the 
195 L<Module::Pluggable::Object|Module::Pluggable::Object>
196 object which is used to load the plugins. See the documentation for that module for
197 more information.
198
199 =cut
200
201 sub finder {
202     my $class  = shift;
203     my $finder = Module::Pluggable::Object->new(
204         search_path => [ __PACKAGE__ ],
205         require     => 1
206     );
207     return $finder;
208 }
209
210 =head2 plugins( )
211
212 The C<plugins()> classmethod returns the names of configuration loading plugins as 
213 found by L<Module::Pluggable::Object|Module::Pluggable::Object>.
214
215 =cut
216
217 sub plugins {
218     my $class = shift;
219     return $class->finder->plugins;
220 }
221
222 =head2 extensions( )
223
224 The C<extensions()> classmethod returns the possible file extensions which can be loaded
225 by C<load_stems()> and C<load_files()>. This may be useful if you set the C<use_ext>
226 parameter to those methods.
227
228 =cut
229
230 sub extensions {
231     my $class = shift;
232     my @ext = map { $_->extensions } $class->plugins;
233     return wantarray ? @ext : \@ext;
234 }
235
236 =head1 DIAGNOSTICS
237
238 =over
239
240 =item C<No files specified!> or C<No stems specified!>
241
242 The C<load_files()> and C<load_stems()> methods will issue this warning if
243 called with an empty list of files/stems to load.
244
245 =item C<_load requires a arrayref of file paths>
246
247 This fatal error will be thrown by the internal C<_load> method. It should not occur
248 but is specified here for completeness. If your code dies with this error, please
249 email a failing test case to the authors below.
250
251 =back
252
253 =head1 CONFIGURATION AND ENVIRONMENT
254
255 Config::Any requires no configuration files or environment variables.
256
257 =head1 DEPENDENCIES
258
259 L<Module::Pluggable|Module::Pluggable>
260
261 And at least one of the following:
262 L<Config::General|Config::General>
263 L<Config::Tiny|Config::Tiny>
264 L<JSON|JSON>
265 L<YAML|YAML>
266 L<JSON::Syck|JSON::Syck>
267 L<YAML::Syck|YAML::Syck>
268 L<XML::Simple|XML::Simple>
269
270 =head1 INCOMPATIBILITIES
271
272 None reported.
273
274 =head1 BUGS AND LIMITATIONS
275
276 No bugs have been reported.
277
278 Please report any bugs or feature requests to
279 C<bug-config-any@rt.cpan.org>, or through the web interface at
280 L<http://rt.cpan.org>.
281
282 =head1 AUTHOR
283
284 Joel Bernstein  E<lt>rataxis@cpan.orgE<gt>
285
286 =head1 CONTRIBUTORS
287
288 This module was based on the original 
289 L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader>
290 module by Brian Cassidy C<< <bricas@cpan.org> >>.
291
292 With ideas and support from Matt S Trout C<< <mst@shadowcatsystems.co.uk> >>.
293
294 Further enhancements suggested by Evan Kaufman C<< <evank@cpan.org> >>.
295
296 =head1 LICENCE AND COPYRIGHT
297
298 Copyright (c) 2006, Portugal Telecom C<< http://www.sapo.pt/ >>. All rights reserved.
299 Portions copyright 2007, Joel Bernstein C<< <rataxis@cpan.org> >>.
300
301 This module is free software; you can redistribute it and/or
302 modify it under the same terms as Perl itself. See L<perlartistic>.
303
304 =head1 DISCLAIMER OF WARRANTY
305
306 BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
307 FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
308 OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
309 PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
310 EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
311 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
312 ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
313 YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
314 NECESSARY SERVICING, REPAIR, OR CORRECTION.
315
316 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
317 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
318 REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
319 LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
320 OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
321 THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
322 RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
323 FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
324 SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
325 SUCH DAMAGES.
326
327 =head1 SEE ALSO
328
329 L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader> 
330 -- now a wrapper around this module.
331
332 =cut
333
334 "Drink more beer";