| 1 | package Jifty::Plugin::Config::Action::AddConfig; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | use base 'Jifty::Action'; | ||
| 5 | |||
| 6 | use Hash::Merge 'merge'; | ||
| 7 | |||
| 8 | use Jifty::Param::Schema; | ||
| 9 | use Jifty::Action schema { | ||
| 10 | param field => | ||
| 11 | is mandatory, | ||
| 12 | type is 'text'; | ||
| 13 | |||
| 14 | param value => | ||
| 15 | type is 'text'; | ||
| 16 | |||
| 17 | param context => | ||
| 18 | default is '/', | ||
| 19 | type is 'text', | ||
| 20 | hints are 'Example: /framework/Web/MasonConfig'; | ||
| 21 | |||
| 22 | param target_file => | ||
| 23 | default is 'etc/site_config.yml', | ||
| 24 | type is 'text'; | ||
| 25 | |||
| 26 | param empty_is_undef => | ||
| 27 | default is 0, | ||
| 28 | type is 'bool'; | ||
| 29 | |||
| 30 | param message => | ||
| 31 | type is 'text'; | ||
| 32 | }; | ||
| 33 | |||
| 34 | sub contextualize { | ||
| 35 | my $self = shift; | ||
| 36 | my $context = shift; | ||
| 37 | |||
| 38 | my $top = {}; | ||
| 39 | my @fragments = grep { length } split '/', $context; | ||
| 40 | |||
| 41 | my $pointer = $top; | ||
| 42 | for my $fragment (@fragments) { | ||
| 43 | $pointer = $pointer->{$fragment} ||= {}; | ||
| 44 | } | ||
| 45 | |||
| 46 | return ($top, $pointer); | ||
| 47 | } | ||
| 48 | |||
| 49 | sub write_new_config { | ||
| 50 | my $self = shift; | ||
| 51 | my $new_config = shift; | ||
| 52 | |||
| 53 | my $file = Jifty::Util->app_root | ||
| 54 | . '/' | ||
| 55 | . $self->argument_value('target_file'); | ||
| 56 | |||
| 57 | my $existing_config = -r $file ? Jifty::YAML::LoadFile($file) : {}; | ||
| 58 | |||
| 59 | Hash::Merge::set_behavior('RIGHT_PRECEDENT'); | ||
| 60 | my $combined_config = merge($existing_config, $new_config); | ||
| 61 | |||
| 62 | Jifty::YAML::DumpFile($file, $combined_config); | ||
| 63 | |||
| 64 | if (length $self->argument_value('message')) { | ||
| 65 | $self->result->message($self->argument_value('message')); | ||
| 66 | } | ||
| 67 | } | ||
| 68 | |||
| 69 | sub take_action { | ||
| 70 | my $self = shift; | ||
| 71 | |||
| 72 | my $context = $self->argument_value('context'); | ||
| 73 | my $field = $self->argument_value('field'); | ||
| 74 | my $value = $self->argument_value('value'); | ||
| 75 | |||
| 76 | my ($new_config, $pointer) = $self->contextualize($context); | ||
| 77 | |||
| 78 | undef $value if $self->argument_value('empty_is_undef') && $value eq ''; | ||
| 79 | |||
| 80 | my $display_value = defined($value) ? $value : "(undef)"; | ||
| 81 | $self->log->info("Changing config $field (in context $context) to $display_value"); | ||
| 82 | |||
| 83 | $pointer->{$field} = $value; | ||
| 84 | |||
| 85 | $self->write_new_config($new_config); | ||
| 86 | |||
| 87 | Jifty->config->load; | ||
| 88 | } | ||
| 89 | |||
| 90 | 1; | ||
| 91 | |||
| 92 | __END__ |