1 package Girocco
::ConfigUtil
;
10 use base
qw(Exporter);
11 our @EXPORT = qw(to_utf8 read_config_file read_config_file_hash git_bool);
16 $encoder = Encode
::find_encoding
('Windows-1252') ||
17 Encode
::find_encoding
('ISO-8859-1') or
18 die "failed to load ISO-8859-1 encoder\n";
22 my ($str, $encode) = @_;
23 return undef unless defined $str;
25 if (Encode
::is_utf8
($str) || utf8
::decode
($str)) {
28 $ans = $encoder->decode($str, Encode
::FB_DEFAULT
);
30 utf8
::encode
($ans) if $encode;
44 $_[0] =~ s/\\([btn\042\\])/$escvals{$1}/g;
49 # mimics Git's config.c git_parse_source function behavior
50 # returns array of arrayref of key and value
51 # except that valueless booleans have a value of undef
52 sub read_config_file
{
58 open my $fh, '<', $fn or
59 $warn && warn("could not open \"$fn\": $!\n"), return(undef);
63 warn "bad config line $li in file $fn\n" if $warn;
70 s/^\x{feff}// if $li == 1;
73 if (/\G([.a-zA-Z0-9-]+)\]/gc) {
74 $section = lc($1) . ".";
75 } elsif (/\G([.a-zA-Z0-9-]*)\s+"((?:[^\042\\\n]|\\.)*)"\]/gc) {
76 $section = lc($1) . "." .
77 &{sub{my $x=shift; $x =~ s/\\(.)/$1/g; $x}}($2) . ".";
83 next if /\G(?:[;#]|$)/;
84 if (/\G([a-zA-Z][a-zA-Z0-9-]*)[ \t]*/gc) {
85 my $k = $section . lc($1);
89 } elsif (/\G=\s*/gc) {
97 if (!$qt && /\G((?:[^"\\\n;#]|\\[btn"\\])+)/gc) {
104 $v .= &$cf_unesc($a);
105 } elsif ($qt && /\G((?:[^"\\\n]|\\[btn"\\])+)/gc) {
107 $v .= &$cf_unesc($a);
108 } elsif (/\G\042/gc) {
110 } elsif (!$qt && /\G[;#]/gc) {
118 /^\s+/gc unless $v ne "" || $qt;
130 push(@vals, [$k, $v]);
139 # Same as read_config_file except that a hashref is returned and
140 # subsequent same-key-name values replace earlier ones.
141 # Also valueless booleans are given the value 1
142 sub read_config_file_hash
{
143 my $result = read_config_file
(@_);
144 return undef unless defined($result);
145 my %config = map {($$_[0], defined($$_[1])?
$$_[1]:1)} @
$result;
149 # Returns 0 for false, 1 for true, undef for unrecognized or undef
150 # Unless the optional second argument is true in which case undef returns 1
152 defined($_[0]) or return $_[1] ?
1 : undef;
154 return 0 if $v eq 'false' || $v eq 'off' || $v eq 'no' || $v eq '' || $v =~ /^[-+]?0+$/;
155 return 1 if $v eq 'true' || $v eq 'on' || $v eq 'yes' || $v =~ /^[-+]?0*[1-9][0-9]*$/;