Config-Std
view release on metacpan or search on metacpan
lib/Config/Std.pm view on Meta::CPAN
my ($hash_ref, $filename) = @_;
$hash_ref = ${$hash_ref} if ref $hash_ref eq 'REF';
$filename = $filename_for{$hash_ref} if @_<2;
croak "Missing filename for call to write_config()"
unless $filename;
my $caller = caller;
my $inter_gap
= exists $global_inter_gap{$caller} ? $global_inter_gap{$caller}
: 1;
my $post_gap
= $post_section_gap_for{$hash_ref}
|| (defined $global_inter_gap{$caller} ? $global_inter_gap{$caller}
: 1
);
# Update existing keyvals in each block...
my %updated;
for my $block ( @{$array_rep_for{$hash_ref}} ) {
my $block_name = $block->get_name();
$block->update($hash_ref->{$block_name}, $updated{$block_name}||={});
}
# Add new keyvals to the first section of block...
for my $block ( @{$array_rep_for{$hash_ref}} ) {
my $block_name = $block->get_name();
$block->extend($hash_ref->{$block_name}, $updated{$block_name},
$post_gap, $inter_gap
);
}
# Add new blocks at the end...
for my $block_name ( sort grep {!$updated{$_}} keys %{$hash_ref} ) {
my $block = Config::Std::Block->new({name=>$block_name});
my $subhash = $hash_ref->{$block_name};
my $first = 1;
# RT 85956
for my $key ( sort keys %{$subhash} ) {
if (!defined $subhash->{$key}) {
croak "Can't save undefined value for key {'$block_name'}{'$key'} (only scalars or array refs)";
}
my $value = $subhash->{$key};
my $separate = ref $value || $value =~ m/\n./xms;
$block->ensure_gap() if ($first ? $post_gap : $inter_gap)
|| $separate;
$block->add_keyval($key, undef, $value);
$block->add_gap() if $separate;
$first = 0;
}
$block->ensure_gap();
push @{$array_rep_for{$hash_ref}}, $block;
}
open my $fh, '>', $filename
or croak "Can't open config file '$filename' for writing (\L$!\E)";
flock($fh,LOCK_EX|LOCK_NB)
|| croak "Can't write to locked config file '$filename'"
if ! ref $filename;
my $first = 1;
for my $block ( @{$array_rep_for{$hash_ref}} ) {
print {$fh} $block->serialize($first, scalar caller, $post_gap);
$first = 0;
}
flock($fh,LOCK_UN) if ! ref $filename;
return 1;
}
sub read_config ($\[%$]) {
my ($filename, $var_ref, $opt_ref) = @_;
my $var_type = ref($var_ref) || q{};
my $hash_ref;
if ($var_type eq 'SCALAR' && !defined ${$var_ref} ) {
${$var_ref} = $hash_ref = {};
}
elsif ($var_type eq 'HASH') {
$hash_ref = $var_ref;
}
else {
croak q{Scalar second argument to 'read_config' must be empty};
}
bless $hash_ref, 'Config::Std::Hash';
my $blocks = $array_rep_for{$hash_ref}
= _load_config_for($filename, $hash_ref);
for my $block ( @{$blocks} ) {
$block->copy_to($hash_ref);
}
$filename_for{$hash_ref} = $filename;
# Remove initial empty section if no data...
if (!keys %{ $hash_ref->{q{}} }) {
delete $hash_ref->{q{}};
}
return 1;
}
sub _load_config_for {
my ($filename, $hash_ref) = @_;
open my $fh, '<', $filename
or croak "Can't open config file '$filename' (\L$!\E)";
flock($fh,LOCK_SH|LOCK_NB)
|| croak "Can't read from locked config file '$filename'"
if !ref $filename;
my $text = do{local $/; <$fh>};
flock($fh,LOCK_UN) if !ref $filename;
my @config_file = Config::Std::Block->new({ name=>q{}, first=>1 });
my $comment = q{};
my %seen;
# Start tracking whether section markers have gaps after them...
$post_section_gap_for{$hash_ref} = 0;
for ($text) {
pos = 0;
while (pos() < length() ) {
# Gap...
if (m/\G (?: [^\S\n]* (?:\n|\z)+)/gcxms) {
### Found gap
$config_file[-1]->add_comment($comment) if $comment;
$config_file[-1]->add_gap();
$comment = q{};
}
# Comment...
elsif (m/\G (\s* [#;] [^\n]* (?:\n|\z) )/gcxms) {
### Found comment: $1
$comment .= $1;
}
# Block...
elsif (m/\G ([^\S\n]*) [[] ( [^]\n]* ) []] ( ([^\S\n]*) [#;] [^\n]* )? [^\S\n]* (?:\n|\z)/gcxms) {
my ($pre, $name, $parcomm, $ws) = ($1, $2, $3, $4);
### Found block: $name
if ($parcomm) {
$pre = 2 + length($pre) + length($name) + length($ws);
if (m/\G ( (?: \n? [ ]{$pre,} [#] [^\n]* )+ )/gcxms) {
$parcomm .= "\n$1";
}
}
push @config_file,
Config::Std::Block->new({
name => $name,
precomm => $comment,
parcomm => $parcomm,
first => !$seen{$name}++,
});
$comment = q{};
# Check for trailing gap...
$post_section_gap_for{$hash_ref}
+= m/\G (?= [^\S\n]* (?:\n|\z) )/xms ? +1 : -1;
}
# Key/value...
elsif (m/\G [^\S\n]* ([^=:\n]+?) [^\S\n]* ([:=] [^\S\n]*) ([^\n]*) (?:\n|\z)/gcxms) {
my ($key, $sep, $val) = ($1, $2, $3);
my $pure_sep = $sep;
$pure_sep =~ s/\s*//g;
# Continuation lines...
lib/Config/Std.pm view on Meta::CPAN
The C<write_config()> subroutine takes two arguments: the hash or hash
reference containing the configuration data to be written out to disk,
and an optional filename specifying which file it is to be written to.
The data hash must conform to the two-level structure described earlier:
with top-level keys naming sections and their values being references to
second-level hashes that store the keys and values of the configuartion
variables. If the structure of the hash differs from this, an exception is
thrown.
If a filename is also specified, the subroutine opens that file
and writes to it. It no filename is specified, the subroutine uses the
name of the file from which the hash was originally loaded using
C<read_config()>. It no filename is specified and the hash I<wasn't>
originally loaded using C<read_config()>, an exception is thrown.
The subroutine returns true on success and throws and exception on failure.
=back
If necessary (typically to avoid conflicts with other modules), you can
have the module export its two subroutines with different names by
loading it with the appropriate options:
use Config::Std { read_config => 'get_ini', write_config => 'update_ini' };
# and later...
get_ini($filename => %config_hash);
# and later still...
update_ini(%config_hash);
You can also control how much spacing the module puts between single-
line values when they are first written to a file, by using the
C<def_gap> option:
# No empty line between single-line config values...
use Config::Std { def_gap => 0 };
# An empty line between all single-line config values...
use Config::Std { def_gap => 1 };
Regardless of the value passed for C<def_gap>, new multi-line values are
always written with an empty line above and below them. Likewise, values
that were previously read in from a file are always written back with
whatever spacing they originally had.
=head1 DIAGNOSTICS
=over
=item Can't open config file '%s' (%s)
You tried to read in a configuration file, but the file you specified
didn't exist. Perhaps the filepath you specified was wrong. Or maybe
your application didn't have permission to access the file you specified.
=item Can't read from locked config file '$filename'
You tried to read in a configuration file, but the file you specified
was being written by someone else (they had a file lock active on it).
Either try again later, or work out who else is using the file.
=item Scalar second argument to 'read_config' must be empty
You passed a scalar variable as the destination into C<read_config()>
was supposed to load a configuration file, but that variable already had
a defined value, so C<read_config()> couldn't autovivify a new hash for
you. Did you mean to pass the subroutine a hash instead of a scalar?
=item Can't save %s value for key '%s' (only scalars or array refs)
You called C<write_config> and passed it a hash containing a
configuration variable whose value wasn't a single string, or a list of
strings. The configuration file format supported by this module only
supports those two data types as values. If you really need to store
other kinds of data in a configuration file, you should consider using
C<Data::Dumper> or C<YAML> instead.
=item Missing filename in call to write_config()
You tried to calll C<write_config()> with only a configuration hash, but that
hash wasn't originally loaded using C<read_config()>, so C<write_config()> has
no idea where to write it to. Either make sure the hash you're trying to save
was originally loaded using C<read_config()>, or else provide an explicit
filename as the second argument to C<write_config()>.
=item Can't open config file '%s' for writing (%s)
You tried to update or create a configuration file, but the file you
specified could not be opened for writing (for the reason given in the
parentheses). This is often caused by incorrect filepaths or lack of
write permissions on a directory.
=item Can't write to locked config file '%s'
You tried to update or create a configuration file, but the file you
specified was being written at the time by someone else (they had a file
lock active on it). Either try again later, or work out who else is
using the file.
=back
=head1 CONFIGURATION AND ENVIRONMENT
Config::Std requires no configuration files or environment variables.
(To do so would be disturbingly recursive.)
=head1 DEPENDENCIES
This module requires the Class::Std module (available from the CPAN)
=head1 INCOMPATIBILITIES
Those variants of INI file dialect supporting partial-line comment are incompatible.
(This is the price of keeping comments when re-writing.)
=head1 BUGS AND LIMITATIONS
=over
=item Memory leak re-reading
A daemon re-reading its config file has reported a memory leak.
=item Parallel testing not safe
This is a config file module. Tests written before C<TAP> got parallel
testing are unsafe with parallel testing, surprise!
Settings are now included to force serial testing (until we refactor all tests
to use temp dirs?).
If using an older Perl < 5.21.1, and Module.PL, and getting out-of-sequence test failures installing this module, either
update Test::Harness~'>= 3.31'
or export HARNESS_OPTIONS=j1
(or force/no-test, or use Build.PL and/or perl-5.22.0 or newer instead).
=item Loading on demand
If you attempt to load C<read_config()> and C<write_config()>
at runtime with C<require>, you can not rely upon the prototype
to convert a regular hash to a reference. To work around this,
you must explicitly pass a reference to the config hash.
require Config::Std;
Config::Std->import;
my %config;
read_config($file, \%config);
write_config(\%config, $file);
( run in 0.676 second using v1.01-cache-2.11-cpan-39bf76dae61 )