diff --git a/kernel_config_merger.pl b/kernel_config_merger.pl new file mode 100644 index 0000000..627ea7b --- /dev/null +++ b/kernel_config_merger.pl @@ -0,0 +1,91 @@ +use strict; +use warnings; + +package Kernel::Config { + sub new { + my $class = shift; + my %params = @_; + my $self = bless {}, $class; + my $file = $params{file}; + $self->_checkIsPlainFileAndReadable( file => $file ); + $self->_readConfigFile( file => $file ); + $self; + } + + sub _checkIsPlainFileAndReadable { + my $self = shift; + my %params = @_; + my $file = $params{file}; + die "No file param" unless defined $file; + die "No such file $file" unless -e $file; + die "No plain file $file" unless -f $file; + die "Cannot read $file" unless -r $file; + } + + sub _readConfigFile { + my $self = shift; + my %params = @_; + my $file = $params{file}; + open my $fh, '<', $file or die "Cannot open $file for read"; + my $lines = [ <$fh> ]; + $lines = [ grep { !(/#/ || /^\s*$/) } @$lines]; + my $hash_config = $self->_parseConfigLinesToHash( lines => $lines ); + $self->{hash_config} = $hash_config; + } + + sub _parseConfigLinesToHash { + my $self = shift; + my %params = @_; + my $lines = $params{lines}; + my $hash_config = { map { chomp; split qr/=/ } @$lines }; + return $hash_config; + } + + sub hashConfig { + my $self = shift; + $self->{hash_config} = $_[1] if defined $_[1]; + return $self->{hash_config}; + } + + sub merge { + my $self = shift; + my %params = @_; + my $remote_kernel_config = $params{kernel_config}; + my $remote_hash_config = $remote_kernel_config->hashConfig; + my $hash_config = $self->hashConfig; + my $keys = [ keys %$hash_config, keys %$remote_hash_config ]; + my $new_hash_config = { + map { + $self->_optionSelectorMergerConfigFirst( + key => $_, + hash_config => $hash_config, + remote_hash_config => $remote_hash_config + ) + } @$keys + }; + $self->hashConfig( $new_hash_config ); + $self; + } + + sub _optionSelectorMergerConfigFirst { + my $self = shift; + my %params = @_; + my $key = $params{key}; + my $hash_config = $params{hash_config}; + my $remote_hash_config = $params{remote_hash_config}; + if ( defined $hash_config->{$key} && $hash_config->{$key} !~ /^\s*$/ ) { + return ( $key => $hash_config->{$key} ) + } else { + return ( $key => ($remote_hash_config->{$key} // "")); + } + } + + sub plainConfig { + my $self = shift; + my $hash_config = $self->hashConfig; + my $plain_config = join( "\n", ( map { "$_=$hash_config->{$_}" } keys %$hash_config ) ); + $plain_config .= "\n"; + return $plain_config; + } +} +print Kernel::Config->new( file => $ARGV[0] )->merge( kernel_config => Kernel::Config->new( file => $ARGV[1] ))->plainConfig;