/
apply.pm
128 lines (102 loc) · 2.47 KB
/
apply.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
use v5.14;
use warnings;
package Pantry::App::Command::apply;
# ABSTRACT: Implements pantry apply subcommand
# VERSION
use Pantry::App -command;
use autodie;
use JSON;
use namespace::clean;
sub abstract {
return 'Apply recipes or attributes to a node or role'
}
sub command_type {
return 'TARGET';
}
sub options {
my ($self) = @_;
return $self->data_options;
}
sub valid_types {
return qw/node role/
}
sub _apply_node {
my ($self, $opt, $name) = @_;
$self->_apply_obj($opt, 'node', $name);
}
sub _apply_role {
my ($self, $opt, $name) = @_;
$self->_apply_obj($opt, 'role', $name);
}
my %setters = (
node => {
default => 'set_attribute',
override => undef,
},
role => {
default => 'set_default_attribute',
override => 'set_override_attribute',
},
);
sub _apply_obj {
my ($self, $opt, $type, $name) = @_;
my $obj = $self->_check_name($type, $name);
$self->_apply_runlist($obj, $opt);
for my $k ( sort keys %{$setters{$type}} ) {
if ( my $method = $setters{$type}{$k} ) {
$self->_set_attributes($obj, $opt, $k, $method);
}
elsif ( $opt->{$k} ) {
$k = ucfirst $k;
warn "$k attributes do not apply to $type objects. Skipping them.\n";
}
}
$obj->save;
return;
}
sub _apply_runlist {
my ($self, $obj, $opt) = @_;
if ($opt->{role}) {
$obj->append_to_run_list(map { "role[$_]" } @{$opt->{role}});
}
if ($opt->{recipe}) {
$obj->append_to_run_list(map { "recipe[$_]" } @{$opt->{recipe}});
}
return;
}
sub _set_attributes {
my ($self, $obj, $opt, $which, $method) = @_;
if ($opt->{$which}) {
for my $attr ( @{ $opt->{$which} } ) {
my ($key, $value) = split /=/, $attr, 2; # split on first '='
if ( $value =~ /(?<!\\),/ ) {
# split on unescaped commas, then unescape escaped commas
$value = [ map { $self->_boolify($_) } map { s/\\,/,/gr } split /(?<!\\),/, $value ];
}
else {
$value = $self->_boolify($value);
}
$obj->$method($key, $value);
}
}
return;
}
sub _boolify {
my ($self, $value) = @_;
if ($value eq 'false') {
$value = JSON::false;
}
elsif ( $value eq 'true' ) {
$value = JSON::true;
}
return $value;
}
1;
=for Pod::Coverage options validate
=head1 SYNOPSIS
$ pantry apply node foo.example.com --recipe nginx --default nginx.port=8080
=head1 DESCRIPTION
This class implements the C<pantry apply> command, which is used to apply recipes or attributes
to a node.
=cut
# vim: ts=2 sts=2 sw=2 et: