Skip to content

Commit

Permalink
Merge b1f6006 into d018e79
Browse files Browse the repository at this point in the history
  • Loading branch information
vpeil committed Nov 6, 2019
2 parents d018e79 + b1f6006 commit 1b7b756
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
58 changes: 58 additions & 0 deletions lib/Catmandu/Fix/env.pm
@@ -0,0 +1,58 @@
package Catmandu::Fix::env;

use Catmandu::Sane;

our $VERSION = '1.2008';

use Moo;
use Catmandu::Util::Path qw(as_path);
use namespace::clean;
use Catmandu::Fix::Has;

with 'Catmandu::Fix::Builder';

has path => (fix_arg => 1);
has value => (fix_arg => 1, default => sub {undef});

sub _build_fixer {
my ($self) = @_;
my $v = $ENV{$self->value};
as_path($self->path)->creator($v);
}

1;

__END__
=pod
=head1 NAME
Catmandu::Fix::env - add or change the value of a HASH key or ARRAY index via
environment variables
=head1 DESCRIPTION
The C<env> fix behaves the same way as the <add_field> fix. Intermediate structures
are created if they are missing.
=head1 SYNOPSIS
# on the command line
$ ENV_MYVAL=bar catmandu convert Null to YAML --fix "env(foo, ENV_MYVAL)"
# output
---
foo: bar
...
# Add a new field 'foo' with value from ENV_MYVAL
env(foo, ENV_MYVAL)
# Create a deeply nested key with value from ENV_MYVAL
add_field(my.deep.nested.key, ENV_MYVAL)
=head1 SEE ALSO
L<Catmandu::Fix>
=cut
31 changes: 31 additions & 0 deletions t/Catmandu-Fix-env.t
@@ -0,0 +1,31 @@
#!/usr/bin/env perl

use strict;
use warnings;
use Test::More;
use Test::Exception;

my $pkg;

BEGIN {
$ENV{ENVTEST} = "bar";
$pkg = 'Catmandu::Fix::env';
use_ok $pkg;
}

is_deeply $pkg->new('foo', 'ENVTEST')->fix({}), {foo => "bar"},
"add field at root";

is_deeply $pkg->new('deeply.nested.$append.job', 'ENVTEST')->fix({}),
{deeply => {nested => [{job => "bar"}]}},
"add field creates intermediate path";

is_deeply $pkg->new('deeply.nested.1.job', 'ENVTEST')->fix({}),
{deeply => {nested => [undef, {job => "bar"}]}},
"add field creates intermediate path";

is_deeply $pkg->new('deeply.nested.$append.job', 'ENVTEST')
->fix({deeply => {nested => {}}}), {deeply => {nested => {}}},
"only add field if the path matches";

done_testing;

0 comments on commit 1b7b756

Please sign in to comment.