c7580a25abc79fae6ace4573ca28ed966c9ad99c
[p5sagit/Config-Any.git] / lib / Config / Any.pm
1 package Config::Any;
2 # $Id: $
3 use warnings;
4 use strict;
5 use Carp;
6 use Module::Pluggable::Object ();
7 use English qw(-no_match_vars);
8
9 our $VERSION = (qw$Rev: $)[-1];
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.0.4
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( )
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 =cut
73
74 sub load_files {
75     my ($class, $args) = @_;
76     return unless defined $args;
77     unless (exists $args->{files}) {
78         warn "no files specified";
79         return;
80     }
81
82     my $files = [ grep { -f $_ } @{$args->{files}} ];
83     my $filter_cb = delete $args->{filter};
84     my $use_ext   = delete $args->{use_ext};
85     return $class->_load($files, $filter_cb, $use_ext);
86 }
87
88 =head2 load_stems( )
89
90     Config::Any->load_stems({stems => \@stems]});
91     Config::Any->load_stems({stems => \@stems, filter  => \&filter});
92     Config::Any->load_stems({stems => \@stems, use_ext => 1});
93
94 C<load_stems()> attempts to load configuration from a list of files which it generates
95 by combining the filename stems list passed in the C<stems> parameter with the 
96 potential filename extensions from each loader, which you can check with the
97 C<extensions()> classmethod described below. Once this list of possible filenames is
98 built it is treated exactly as in C<load_files()> above, as which it takes the same
99 parameters. Please read the C<load_files()> documentation before using this method.
100
101 =cut
102
103 sub load_stems {
104     my ($class, $args) = @_;
105     return unless defined $args;
106     unless (exists $args->{stems}) {
107         warn "no stems specified";
108         return;
109     }
110         
111     my $filter_cb = delete $args->{filter};
112     my $use_ext   = delete $args->{use_ext};
113     my $stems = $args->{stems};
114     my @files;
115     STEM:
116     for my $s (@$stems) {
117         EXT:
118         for my $ext ($class->extensions) {
119             my $file = "$s.$ext";
120             next EXT unless -f $file;
121             push @files, $file;
122             last EXT;
123         }
124     }
125     return $class->_load(\@files, $filter_cb, $use_ext);
126 }
127
128 # this is where we do the real work
129 # it's a private class-method because users should use the interface described
130 # in the POD.
131 sub _load {
132     my ($class, $files_ref, $filter_cb, $use_ext) = @_;
133     croak "_load requires a arrayref of file paths" unless defined $files_ref;
134
135     my $final_configs       = [];
136     my $originally_loaded   = {};
137
138     for my $loader ( $class->plugins ) {
139         my %ext = map { $_ => 1 } $loader->extensions;
140         FILE:
141         for my $filename (@$files_ref) {
142             if (defined $use_ext) {
143                 for my $e (keys %ext) {
144                     my ($fileext) = $filename =~ m{ \. $e \z }xms;
145                     next FILE unless exists $ext{$fileext};
146                 }
147             }
148
149             my $config;
150                         eval {
151                                 $config = $loader->load( $filename );
152                         };
153                         next if $EVAL_ERROR;
154             next if !$config;
155             $filter_cb->( $config ) if defined $filter_cb;
156             push @$final_configs, { $filename => $config };
157         }
158     }
159     $final_configs;
160 }
161
162 =head2 finder( )
163
164 The C<finder()> classmethod returns the 
165 L<Module::Pluggable::Object|Module::Pluggable::Object>
166 object which is used to load the plugins. See the documentation for that module for
167 more information.
168
169 =cut
170
171 sub finder {
172     my $class = shift;
173     my $finder = Module::Pluggable::Object->new(
174         search_path => [ __PACKAGE__ ],
175         require     => 1
176     );
177     $finder;
178 }
179
180 =head2 plugins( )
181
182 The C<plugins()> classmethod returns the names of configuration loading plugins as 
183 found by L<Module::Pluggable::Object|Module::Pluggable::Object>.
184
185 =cut
186
187 sub plugins {
188     my $class = shift;
189     return $class->finder->plugins;
190 }
191
192 =head2 extensions( )
193
194 The C<extensions()> classmethod returns the possible file extensions which can be loaded
195 by C<load_stems()> and C<load_files()>. This may be useful if you set the C<use_ext>
196 parameter to those methods.
197
198 =cut
199
200 sub extensions {
201     my $class = shift;
202     my @ext = map { $_->extensions } $class->plugins;
203         return wantarray ? @ext : [@ext];
204 }
205
206 =head1 DIAGNOSTICS
207
208 =over
209
210 =item C<no files specified> or C<no stems specified>
211
212 The C<load_files()> and C<load_stems()> methods will issue this warning if
213 called with an empty list of files/stems to load.
214
215 =item C<_load requires a arrayref of file paths>
216
217 This fatal error will be thrown by the internal C<_load> method. It should not occur
218 but is specified here for completeness. If your code dies with this error, please
219 email a failing test case to the authors below.
220
221 =back
222
223 =head1 CONFIGURATION AND ENVIRONMENT
224
225 Config::Any requires no configuration files or environment variables.
226
227 =head1 DEPENDENCIES
228
229 L<Module::Pluggable|Module::Pluggable>
230
231 And at least one of the following:
232 L<Config::General|Config::General>
233 L<Config::Tiny|Config::Tiny>
234 L<JSON|JSON>
235 L<YAML|YAML>
236 L<JSON::Syck|JSON::Syck>
237 L<YAML::Syck|YAML::Syck>
238 L<XML::Simple|XML::Simple>
239
240 =head1 INCOMPATIBILITIES
241
242 None reported.
243
244 =head1 BUGS AND LIMITATIONS
245
246 No bugs have been reported.
247
248 Please report any bugs or feature requests to
249 C<bug-config-any@rt.cpan.org>, or through the web interface at
250 L<http://rt.cpan.org>.
251
252 =head1 AUTHOR
253
254 Joel Bernstein  C<< <rataxis@cpan.org> >>
255
256 =head1 CONTRIBUTORS
257
258 This module was based on the original 
259 L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader>
260 module by Brian Cassidy C<< <bricas@cpan.org> >>.
261
262 With ideas and support from Matt S Trout C<< <mst@shadowcatsystems.co.uk> >>.
263
264 =head1 LICENCE AND COPYRIGHT
265
266 Copyright (c) 2006, Portugal Telecom C<< http://www.sapo.pt/ >>. All rights reserved.
267
268 This module is free software; you can redistribute it and/or
269 modify it under the same terms as Perl itself. See L<perlartistic>.
270
271 =head1 DISCLAIMER OF WARRANTY
272
273 BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
274 FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
275 OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
276 PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
277 EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
278 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
279 ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
280 YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
281 NECESSARY SERVICING, REPAIR, OR CORRECTION.
282
283 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
284 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
285 REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
286 LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
287 OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
288 THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
289 RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
290 FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
291 SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
292 SUCH DAMAGES.
293
294 =head1 SEE ALSO
295
296 L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader> 
297 -- now a wrapper around this module.
298
299 =cut
300
301 1; # Magic true value required at end of module
302