]> mj.ucw.cz Git - libucw.git/blob - lib/perl/Config.pm
More bits of the sorter.
[libucw.git] / lib / perl / Config.pm
1 #       Perl module for parsing Sherlock configuration files (using the config utility)
2 #
3 #       (c) 2002--2005 Martin Mares <mj@ucw.cz>
4 #
5 #       This software may be freely distributed and used according to the terms
6 #       of the GNU Lesser General Public License.
7
8 package Sherlock::Config;
9
10 use strict;
11 use warnings;
12 use Getopt::Long;
13
14 our %Sections = ();
15
16 our $DefaultConfigFile = "";
17
18 sub Parse(@) {
19         my @options = @_;
20         my $defargs = "";
21         my $override_config = 0;
22         push @options, "config|C=s" => sub { my ($o,$a)=@_; $defargs .= " -C'$a'"; $override_config=1; };
23         push @options, "set|S=s" => sub { my ($o,$a)=@_; $defargs .= " -S'$a'"; };
24         Getopt::Long::Configure("bundling");
25         Getopt::Long::GetOptions(@options) or return 0;
26         if (!$override_config && $DefaultConfigFile) {
27                 $defargs = "-C'$DefaultConfigFile' $defargs";
28         }
29         foreach my $section (keys %Sections) {
30                 my $opts = $Sections{$section};
31                 my $optlist = join(";", keys %$opts);
32                 my %filtered_opts = map { my $t=$_; $t=~s/[#\$]+$//; $t => $$opts{$_} } keys %$opts;
33                 my @l = `bin/config $defargs "$section\{$optlist\}"`;
34                 $? && exit 1;
35                 foreach my $o (@l) {
36                         $o =~ /^CF_.*_([^=]+)='(.*)'\n$/ or die "Cannot parse bin/config output: $_";
37                         my $var = $filtered_opts{$1};
38                         my $val = $2;
39                         if (ref $var eq "SCALAR") {
40                                 $$var = $val;
41                         } elsif (ref $var eq "ARRAY") {
42                                 push @$var, $val;
43                         } elsif (ref $var) {
44                                 die ("Sherlock::Config::Parse: don't know how to set $o");
45                         }
46                 }
47         }
48         1;
49 }
50
51 1;  # OK