script/update_config

filter: Statementstmt 87.9% 673 / 765 Branchbran 75.3% 336 / 446 Conditioncond 69.8% 188 / 269 MC/DCmcdc 55.1% 85 / 154 Subroutinesub 92.5% 99 / 107 Podpod n/a totaltotal 79.3% 1381 / 1741 CC 348 SCAR 34.3
CC
348
Cov
81%
export_fragments
306.0
install_module
240.0
load_module
123.7
CRAP 30.9
↑ Summary /usr/local/bin/perldoc »
1 #!/usr/bin/env perl
2  
3 157 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 157 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 157 ▶use 5.024;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 157 ▶use English;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 # Only modules that are in the standard distribution for 5.24. The rests should
9 # be in the INIT block below.
10 157 ▶use Config;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 157 ▶use Cwd ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 157 ▶use Digest::SHA 'sha1_hex';
Subroutine BEGIN: called CC=1 SCAR=0.0
13 157 ▶use File::Basename qw(basename dirname);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 157 ▶use File::Path 'make_path';
Subroutine BEGIN: called CC=1 SCAR=0.0
15 157 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 157 ▶use File::Spec::Functions 'catfile';
Subroutine BEGIN: called CC=1 SCAR=0.0
17 157 ▶use FindBin;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 157 ▶use Getopt::Long 'GetOptions';
Subroutine BEGIN: called CC=1 SCAR=0.0
19 157 ▶use List::Util qw(all any first);
Subroutine BEGIN: called CC=1 SCAR=0.0
20 157 ▶use Pod::Usage 'pod2usage';
Subroutine BEGIN: called CC=1 SCAR=0.0
21 157 ▶use Scalar::Util 'refaddr';
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 # This must be kept in sync with the version in lib/App/UpdateConfig.pm (the
24 # script cannot use that module as it must work as a standalone file).
25 154 our $VERSION = '1.07';
26  
27 # With --help, prints the entire documentation, through perldoc when available.
28 3 ▶sub print_usage {
Subroutine print_usage: called CC=4 SCAR=13.9
29 3 my ($is_help) = @_;
30 3 ▶ pod2usage({
Branch: 3 branches
BranchTrueFalseTotal
$is_help ? : 1 2 3
$is_help ? : 1 2 3
$is_help ? : 1 2 3
31 -msg => "update_config: Automatic updates of a linux configuration.\n",
32 -verbose => $is_help ? 2 : 0,
33 -exitval => $is_help ? 0 : 2,
34 -output => $is_help ? \*STDOUT : \*STDERR,
35 });
36 }
37  
38 154 my %flags;
39 my @orig_argv;
40  
41 157 ▶BEGIN {
Subroutine BEGIN: called CC=6 SCAR=18.6
42 157 @orig_argv = @ARGV;
43 157 ▶ GetOptions(
Branch: 1 branch
BranchTrueFalseTotal
&GetOptions(\%flags, "silent", "diff", "help", "test", "list", "root", "no-root", "export", "dir=s", "pack", "force") or print_usage(0) 156 1 157
44 \%flags, 'silent', 'diff', 'help', 'test', 'list',
45 'root', 'no-root', 'export', 'dir=s', 'pack', 'force'
46 ) or print_usage(0);
47 156 ▶ print_usage(1) if $flags{help};
Branch: 1 branch
BranchTrueFalseTotal
if $flags{"help"} 1 155 156
48 155 ▶ print_usage(0) if @ARGV;
Branch: 1 branch
BranchTrueFalseTotal
if @ARGV 1 154 155
49 154 ▶ if ($flags{pack} and $0 eq '-') {
Branch: 1 branch
BranchTrueFalseTotal
if ($flags{"pack"} and $0 eq "-") 0 154 154
Condition66%2/3
$flags{"pack"} and $0 eq "-"
!ll&&!rl&&r
14860
MC/DC0%0/2
$flags{"pack"} and $0 eq "-"
$flags{"pack"} $0 eq "-"
Truth table66%2/3
A and B
A= $flags{"pack"}B= $0 eq "-"
ABresult
0X0
100
111
50 0 print STDERR "Cannot use --pack if the script is read from the standard input\n";
51 0 exit 1;
52 }
53 }
54  
55 154 my $need_sudo = 0;
56  
57 806 ▶sub try_load {
Subroutine try_load: called CC=2 SCAR=7.0
58 806 my ($m, @args) = @_;
59 806 ▶ eval "require $m" or return 0; ## no critic (ProhibitStringyEval)
Branch: 1 branch
BranchTrueFalseTotal
eval "require $m" or return 0 806 0 806
60 806 $m->import(@args);
61 806 return 1;
62 }
63  
64 # Returns the full path of the given program if it is found in the PATH, or
65 # undef otherwise.
66 0 ▶sub find_program {
Subroutine find_program: not called CC=1 SCAR=6.9
67 0 my ($name) = @_;
68 0 ▶ return first { -f && -x } map { catfile($_, $name) } File::Spec->path();
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
-f $_ and -x $_ 0 0 0
69 }
70  
71 # Returns true if this script is installed in one of the bin directories of
72 # the Perl installation (e.g. with `sudo cpanm`), rather than with local::lib or
73 # as a standalone copy.
74 0 ▶sub is_installed_globally {
Subroutine is_installed_globally: not called CC=3 SCAR=24.8
75 0 ▶ return 0 if $0 eq '-';
Branch: 1 branch
BranchTrueFalseTotal
if $0 eq "-" 0 0 0
76 my @dirs =
77 0 ▶ grep { defined && $_ ne '' }
Condition0%0/3
defined $_ && $_ ne ''
!ll&&!rl&&r
000
MC/DC0%0/2
defined $_ && $_ ne ''
defined $_ $_ ne ''
Truth table0%0/3
A && B
A= defined $_B= $_ ne ''
ABresult
0X0
100
111
78 @Config{
79 0 qw(installbin installscript installsitebin installsitescript installvendorbin installvendorscript)
80 };
81 0 ▶ return any { (Cwd::realpath($_) // '') eq $FindBin::RealBin } @dirs;
Subroutine __ANON__: not called CC=2 SCAR=17.9
Condition0%0/2
Cwd::realpath($_) // ""
l!l
00
MC/DC0%0/1
Cwd::realpath($_) // ""
Cwd::realpath($_)
Truth table0%0/2
A
A= Cwd::realpath($_)
Aresult
11
00
82 }
83  
84 # Whether local::lib is loaded (undef until we try to load it).
85 154 my $has_local_lib;
86  
87 # Installs the given module with cpanm if it is available, or cpan otherwise.
88 # The module is installed in the local::lib directory if local::lib is loaded,
89 # or system-wide otherwise, using sudo when needed.
90 0 ▶sub install_module {
Subroutine install_module: not called CC=15 SCAR=54.8
91 0 my ($m) = @_;
92 0 local $ENV{PERL_MM_USE_DEFAULT} = 1; # Used so that cpan don’t ask questions.
93 0 my $cpanm = find_program('cpanm');
94 # When it can't write in the system directories, cpanm installs the modules
95 # in ~/perl5, where we would not find them without local::lib. And when we
96 # are installed globally, our modules must be installed globally too.
97 $need_sudo = 1
98 if ($cpanm or is_installed_globally())
99 and not $has_local_lib
100 and not -w $Config{installsitelib}
101 0 ▶ and $EUID != 0;
Branch: 1 branch
BranchTrueFalseTotal
if $cpanm || is_installed_globally() and not $has_local_lib and not -w $main::Config{"installsitelib"} and $main::EUID != 0 0 0 0
Condition0%0/12
$cpanm || is_installed_globally() and not $has_local_lib and not -w $main::Config{"installsitelib"} and $main::EUID != 0
!ll&&!rl&&r
000
$cpanm || is_installed_globally() and not $has_local_lib and not -w $main::Config{"installsitelib"}
!ll&&!rl&&r
000
$cpanm || is_installed_globally() and not $has_local_lib
!ll&&!rl&&r
000
$cpanm or is_installed_globally()
l!l&&r!l&&!r
000
MC/DC0%0/5
$cpanm || is_installed_globally() and not $has_local_lib and not -w $main::Config{"installsitelib"} and $main::EUID != 0
$cpanm is_installed_globally() not $has_local_lib not -w $main::Config{"installsitelib"} $main::EUID != 0
Truth table0%0/9
A or B and not(C) and not(D) and E
A= $cpanmB= is_installed_globally()C= not $has_local_libD= not -w $main::Config{"installsitelib"}E= $main::EUID != 0
ABCDEresult
00XXX0
1X0XX0
010XX0
1X10X0
0110X0
1X1100
011100
1X1111
011111
102 0 ▶ my @cmd = $cpanm ? ($cpanm) : ('cpan', ($has_local_lib ? '-I' : ()), '-i');
Branch: 2 branches
BranchTrueFalseTotal
$cpanm ? : 0 0 0
$has_local_lib ? : 0 0 0
103 0 ▶ my $name = $cpanm ? 'cpanm' : 'cpan';
Branch: 1 branch
BranchTrueFalseTotal
$cpanm ? : 0 0 0
104 0 ▶ if (!$need_sudo) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($need_sudo) 0 0 0
105 0 ▶ print "Installing module '${m}' with ${name}\n" unless $flags{silent};
Branch: 1 branch
BranchTrueFalseTotal
unless $flags{"silent"} 0 0 0
106 0 ▶ return if system(@cmd, $m) == 0;
Branch: 1 branch
BranchTrueFalseTotal
if system(@cmd, $m) == 0 0 0 0
107 0 $need_sudo = 1;
108 }
109 # sudo resets the environment, so the module is installed system-wide even
110 # if local::lib is loaded.
111 0 ▶ print "Installing module '${m}' with sudo ${name}\n" unless $flags{silent};
Branch: 1 branch
BranchTrueFalseTotal
unless $flags{"silent"} 0 0 0
112 0 ▶ system('sudo', ($cpanm ? $cpanm : qw(cpan -i)), $m) == 0
Branch: 2 branches
BranchTrueFalseTotal
system("sudo", $cpanm ? $cpanm : ("cpan", "-i"), $m) == 0 or die "Cannot install module '${m}'.\n" 0 0 0
$cpanm ? : 0 0 0
113 or die "Cannot install module '$m'.\n";
114 0 return;
115 }
116  
117 806 ▶sub load_module {
Subroutine load_module: called CC=12 SCAR=48.2
118 806 my ($m, @args) = @_;
119 806 ▶ return 1 if try_load($m, @args);
Branch: 1 branch
BranchTrueFalseTotal
if try_load($m, @args) 806 0 806
120  
121 # We try to load local::lib if we need to install a module (unless we are
122 # installed globally, in which case the modules are installed alongside us).
123 # If we don’t have local::lib, we won’t install it as that might require a
124 # sudo and, at that point, that defeats the points of using local::lib in the
125 # first place.
126 0 ▶ if (not defined $has_local_lib and is_installed_globally()) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $has_local_lib and is_installed_globally()) { } 0 0 0
elsif (not defined $has_local_lib) { } 0 0 0
Condition0%0/3
not defined $has_local_lib and is_installed_globally()
!ll&&!rl&&r
000
MC/DC0%0/2
not defined $has_local_lib and is_installed_globally()
not defined $has_local_lib is_installed_globally()
Truth table0%0/3
not(A) and B
A= not defined $has_local_libB= is_installed_globally()
ABresult
0X0
100
111
127 0 $has_local_lib = 0;
128 print "Installing modules globally, as update_config is installed globally\n"
129 0 ▶ unless $flags{silent};
Branch: 1 branch
BranchTrueFalseTotal
unless $flags{"silent"} 0 0 0
130 } elsif (!defined $has_local_lib) {
131 # local::lib prints some configuration and exit the program when $0 is '-' (meant for `perl -Mlocal::lib`).
132 0 ▶ local $0 = $0 eq '-' ? 'fakename.pl' : $0;
Branch: 1 branch
BranchTrueFalseTotal
$0 eq '-' ? : 0 0 0
133 0 $has_local_lib = try_load('local::lib');
134 0 ▶ if ($has_local_lib) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_local_lib) { } 0 0 0
135 0 ▶ print "Successfully loaded local::lib\n" unless $flags{silent};
Branch: 1 branch
BranchTrueFalseTotal
unless $flags{"silent"} 0 0 0
136 # We try to load the module again, in case it was already installed locally.
137 0 ▶ return 1 if try_load($m, @args);
Branch: 1 branch
BranchTrueFalseTotal
if try_load($m, @args) 0 0 0
138 } else {
139 0 ▶ print "Failed to load local::lib\n" unless $flags{silent};
Branch: 1 branch
BranchTrueFalseTotal
unless $flags{"silent"} 0 0 0
140 }
141 }
142  
143 0 install_module($m);
144 0 ▶ try_load($m, @args) or die "Cannot load module '$m'.\n";
Branch: 1 branch
BranchTrueFalseTotal
try_load($m, @args) or die "Cannot load module '${m}'.\n" 0 0 0
145 0 return 1;
146 }
147  
148 # We try to load and, if necessary, install non-standard modules.
149 154 ▶INIT {
Subroutine INIT: called CC=1 SCAR=0.0
150 154 load_module 'Data::Section::Simple', 'get_data_section';
151 154 load_module 'File::HomeDir';
152 154 load_module 'File::Slurp', 'read_file', 'write_file';
153 154 load_module 'Text::Diff', 'diff';
154 154 load_module 'File::Which'; # Loaded so that config fragments can REQUIRE which('program')
155 }
156  
157 154 ▶use constant DEFAULT_COMMENTS_CHAR => '#';
Subroutine BEGIN: called CC=1 SCAR=0.0
158 154 ▶use constant DEFAULT_GUARD_STRING => 'AUTO-CONFIG';
Subroutine BEGIN: called CC=1 SCAR=0.0
159 154 ▶use constant COMMENTS_CHAR_COUNT => 3; # In the guard markers.
Subroutine BEGIN: called CC=1 SCAR=0.0
160 154 ▶use constant ARRAYS_MARKER => 'update_config_arrays'; # In MERGE fragments.
Subroutine BEGIN: called CC=1 SCAR=0.0
161 154 ▶use constant STATE_HASH_LENGTH => 16; # Hex digits in the name of the saved states.
Subroutine BEGIN: called CC=1 SCAR=0.0
162 154 ▶use constant ENTIRE_FILE_STATE_HEADER => "ENTIRE FILE\n\n"; # In the ENTIRE FILE states.
Subroutine BEGIN: called CC=1 SCAR=0.0
163 154 ▶use constant DIR_CONF_NAME => '.update_config'; # The directives of a directory.
Subroutine BEGIN: called CC=1 SCAR=0.0
164  
165 606 ▶sub get_home_dir {
Subroutine get_home_dir: called CC=1 SCAR=0.0
166 606 return File::HomeDir->my_home
167 # return `echo -n ~`;
168 }
169  
170 # Returns the default directory of the configuration fragments: ~/.update_config
171 # if it exists, otherwise $XDG_CONFIG_HOME/update_config.
172 152 ▶sub get_config_dir {
Subroutine get_config_dir: called CC=3 SCAR=11.0
173 152 my $home_config = catfile(get_home_dir(), '.update_config');
174 152 ▶ return $home_config if -d $home_config;
Branch: 1 branch
BranchTrueFalseTotal
if -d $home_config 1 151 152
175 151 ▶ return catfile($ENV{XDG_CONFIG_HOME} || catfile(get_home_dir(), '.config'), 'update_config');
Condition66%2/3
$ENV{'XDG_CONFIG_HOME'} || catfile(get_home_dir(), '.config')
l!l&&r!l&&!r
21490
MC/DC0%0/2
$ENV{'XDG_CONFIG_HOME'} || catfile(get_home_dir(), '.config')
$ENV{'XDG_CONFIG_HOME'} catfile(get_home_dir(), '.config')
Truth table66%2/3
A || B
A= $ENV{'XDG_CONFIG_HOME'}B= catfile(get_home_dir(), '.config')
ABresult
1X1
011
000
176 }
177  
178 # Remove part of a file name that we are ignoring when creating the
179 # target file (for the moment, only a suffix within bracket).
180 422 ▶sub clean_output_path {
Subroutine clean_output_path: called CC=1 SCAR=0.0
181 422 my ($name) = @_;
182 422 return $name =~ s/\s*(?:\[.*\]\s*)$//r;
183 }
184  
185 # Returns the number of components in the given fragment name (its path relative
186 # to the configuration directory), which is the depth at which its own
187 # directives are set (see add_conf).
188 263 ▶sub get_name_depth {
Subroutine get_name_depth: called CC=1 SCAR=0.0
189 263 my ($name) = @_;
190 263 my @parts = split m{/}, $name;
191 263 return scalar @parts;
192 }
193  
194 # Returns the guard suffix of the fragment with the given name (its path
195 # relative to the configuration directory) and configuration (from
196 # parse_file_conf): its GUARD SUFFIX directive, if any, followed by the
197 # suffixes between brackets at the end of the names of the directories below
198 # the one where that directive is set and of the fragment itself (so all of
199 # them without the directive), joined with '-' and in upper case. Returns undef
200 # if there are no such suffixes.
201 244 ▶sub get_guard_suffix {
Subroutine get_guard_suffix: called CC=6 SCAR=17.9
202 244 my ($name, $conf) = @_;
203 244 my @parts = split m{/}, $name;
204 244 ▶ my $from = exists $conf->{guard_suffix} ? $conf->{depth}{guard_suffix} : 0;
Branch: 1 branch
BranchTrueFalseTotal
exists $conf->{'guard_suffix'} ? : 13 231 244
205 my @suffixes =
206 244 ▶ grep { defined && $_ ne '' } map { m/\s*\[(.*)\]\s*$/ ? $1 : undef } @parts[$from .. $#parts];
Branch: 1 branch
BranchTrueFalseTotal
/\s*\[(.*)\]\s*$/u ? : 46 299 345
Condition100%3/3
defined $_ && $_ ne ''
!ll&&!rl&&r
299145
MC/DC100%2/2
defined $_ && $_ ne ''
defined $_ $_ ne ''
Truth table100%3/3
A && B
A= defined $_B= $_ ne ''
ABresult
0X0
100
111
207 244 ▶ unshift @suffixes, $conf->{guard_suffix} if exists $conf->{guard_suffix};
Branch: 1 branch
BranchTrueFalseTotal
if exists $conf->{"guard_suffix"} 13 231 244
208 244 ▶ return @suffixes ? uc join('-', @suffixes) : undef;
Branch: 1 branch
BranchTrueFalseTotal
@suffixes ? : 53 191 244
209 }
210  
211 # parse_file_name($file_name)
212 # Returns a tuple (mode, input_spec, output_spec) where mode is one
213 # of 'file' or 'pipe' specifying if the input and output spec will
214 # be normal file name or a commands that should be executed.
215 # If the file has a prefix in bracket, then it is ignored.
216 221 ▶sub parse_file_name {
Subroutine parse_file_name: called CC=6 SCAR=18.0
217 # if more logic is added in this function, it may be needed to reverse
218 # it in the export block.
219 221 my ($raw_path) = @_;
220 221 $raw_path = clean_output_path($raw_path);
221 221 my @file_part = split /,/, $raw_path;
222 221 ▶ my $mode = @file_part == 1 ? 'file' : 'pipe';
Branch: 1 branch
BranchTrueFalseTotal
@file_part == 1 ? : 218 3 221
223 221 ▶ die "Invalid file specification: '$raw_path'.\n" if @file_part < 1 || @file_part > 2;
Branch: 1 branch
BranchTrueFalseTotal
if @file_part < 1 or @file_part > 2 0 221 221
Condition33%1/3
@file_part < 1 or @file_part > 2
l!l&&r!l&&!r
00221
MC/DC0%0/2
@file_part < 1 or @file_part > 2
@file_part < 1 @file_part > 2
Truth table33%1/3
A or B
A= @file_part < 1B= @file_part > 2
ABresult
1X1
011
000
224 221 ▶ if (@file_part == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@file_part == 1) { } 218 3 221
225 218 my $path;
226 218 ▶ if ($file_part[0] =~ m{^/}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($file_part[0] =~ m[^/]u) { } 6 212 218
227 6 $path = $file_part[0];
228 } else {
229 212 $path = catfile(get_home_dir(), $file_part[0]);
230 }
231 218 return ('file', $path, $path);
232 } else {
233 3 return ('pipe', @file_part);
234 }
235 }
236  
237 # Returns the current content of the target, split in three parts: the content
238 # before the guard markers, between them, and after them.
239 168 ▶sub read_content {
Subroutine read_content: called CC=12 SCAR=25.0
240 168 my ($mode, $file, $conf) = @_;
241 168 ▶ if ($mode eq 'file' and not -e $file) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mode eq "file" and not -e $file) 95 73 168
Condition100%3/3
$mode eq "file" and not -e $file
!ll&&!rl&&r
27195
MC/DC100%2/2
$mode eq "file" and not -e $file
$mode eq "file" not -e $file
Truth table100%3/3
A and not(B)
A= $mode eq "file"B= not -e $file
ABresult
0X0
100
111
242 95 return ('', '', '');
243 }
244 73 ▶ open(my $fh, ($mode eq 'file' ? '<' : '-|'), $file) or die "Cannot open '$file' for read: $!.\n";
Branch: 2 branches
BranchTrueFalseTotal
open my $fh, $mode eq "file" ? "<" : "-|", $file or die "Cannot open '${file}' for read: $!.\n" 73 0 73
$mode eq 'file' ? : 71 2 73
245 73 my @lines = <$fh>;
246 # Closing a pipe fails if the command fails, which is expected for some of
247 # them (e.g. `crontab -l` when there is no crontab yet).
248 73 ▶ close $fh or $mode eq 'pipe' or die "Cannot close '$file': $!.\n";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or $mode eq "pipe" or die "Cannot close '${file}': $!.\n" 73 0 73
Condition33%1/3
close $fh or $mode eq "pipe"
l!l&&r!l&&!r
7300
MC/DC0%0/2
close $fh or $mode eq "pipe"
close $fh $mode eq "pipe"
Truth table33%1/3
A or B
A= close $fhB= $mode eq "pipe"
ABresult
1X1
011
000
249  
250 73 ▶ return ('', join('', @lines), '') if $conf->{entire_file} or $conf->{merge};
Branch: 1 branch
BranchTrueFalseTotal
if $conf->{"entire_file"} or $conf->{"merge"} 46 27 73
Condition100%3/3
$conf->{"entire_file"} or $conf->{"merge"}
l!l&&r!l&&!r
172927
MC/DC100%2/2
$conf->{"entire_file"} or $conf->{"merge"}
$conf->{"entire_file"} $conf->{"merge"}
Truth table100%3/3
A or B
A= $conf->{"entire_file"}B= $conf->{"merge"}
ABresult
1X1
011
000
251 27 my ($start) = grep { $lines[$_] eq $conf->{start_marker} } 0 .. $#lines;
252 27 ▶ if (not defined $start) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $start) 7 20 27
253 7 ▶ return $conf->{is_prefix} ? ('', '', join('', @lines)) : (join('', @lines), '', '');
Branch: 1 branch
BranchTrueFalseTotal
$conf->{'is_prefix'} ? : 1 6 7
254 }
255 20 my ($end) = grep { $lines[$_] eq $conf->{end_marker} } $start + 1 .. $#lines;
256 20 ▶ die "Missing closing tag in '$file'.\n" if not defined $end;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $end 1 19 20
257 return (
258 19 join('', @lines[0 .. $start - 1]),
259 join('', @lines[$start + 1 .. $end - 1]),
260 join('', @lines[$end + 1 .. $#lines]));
261 }
262  
263 131 ▶sub write_content {
Subroutine write_content: called CC=9 SCAR=22.1
264 131 my ($mode, $file, $content, $conf) = @_;
265 131 ▶ if ($mode eq 'file') {
Branch: 1 branch
BranchTrueFalseTotal
if ($mode eq "file") 129 2 131
266 129 my $dir = dirname($file);
267 129 ▶ if (not -e $dir) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-e $dir) 24 105 129
268 24 ▶ make_path($dir) or die "Cannot create directory '$dir': $!.\n";
Branch: 1 branch
BranchTrueFalseTotal
make_path($dir) or die "Cannot create directory '${dir}': $!.\n" 24 0 24
269 }
270 }
271 131 ▶ open(my $fh, ($mode eq 'file' ? '>' : '|-'), $file) or die "Cannot open '$file' for write: $!\n";
Branch: 2 branches
BranchTrueFalseTotal
open my $fh, $mode eq "file" ? ">" : "|-", $file or die "Cannot open '${file}' for write: $!\n" 131 0 131
$mode eq 'file' ? : 129 2 131
272 131 print $fh $content;
273 131 ▶ if ($conf->{make_executable}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($conf->{"make_executable"}) 1 130 131
274 1 my $current_mode = (stat $fh)[2] & oct('7777');
275 1 chmod($current_mode | oct('111'), $fh);
276 }
277 131 ▶ close $fh or die "Error writing '$file': $!.\n";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or die "Error writing '${file}': $!.\n" 131 0 131
278 131 ▶ chmod oct($conf->{perm}), $file if need_perm_update($file, $mode, $conf);
Branch: 1 branch
BranchTrueFalseTotal
if need_perm_update($file, $mode, $conf) 8 123 131
279 131 return;
280 }
281  
282 # Returns a one-line description of what is at the given path, comparable to
283 # the description of the symbolic link that a SYMLINK fragment creates there
284 # (see get_contents): `-> destination` for a symbolic link, an empty string if
285 # nothing exists there, or the type of the file in parentheses otherwise.
286 9 ▶sub describe_symlink_target {
Subroutine describe_symlink_target: called CC=5 SCAR=16.1
287 9 my ($path) = @_;
288 9 ▶ if (-l $path) {
Branch: 1 branch
BranchTrueFalseTotal
if (-l $path) 4 5 9
289 4 ▶ my $dest = readlink($path) // die "Cannot read the symbolic link '${path}': $!.\n";
Condition50%1/2
readlink $path // die("Cannot read the symbolic link '${path}': $!.\n")
l!l
40
MC/DC0%0/1
readlink $path // die("Cannot read the symbolic link '${path}': $!.\n")
readlink $path
Truth table50%1/2
A
A= readlink $path
Aresult
11
00
290 4 return "-> ${dest}\n";
291 }
292 5 ▶ return '' if not -e $path;
Branch: 1 branch
BranchTrueFalseTotal
unless -e $path 2 3 5
293 3 ▶ return -d _ ? "(directory)\n" : "(file)\n";
Branch: 1 branch
BranchTrueFalseTotal
-d _ ? : 1 2 3
294 }
295  
296 # Creates a symbolic link at the given path, pointing to the given destination,
297 # replacing atomically what is at that path, unless it is a directory.
298 4 ▶sub write_symlink {
Subroutine write_symlink: called CC=5 SCAR=20.4
299 4 my ($path, $dest) = @_;
300 4 my $dir = dirname($path);
301 4 ▶ if (not -e $dir) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-e $dir) 0 4 4
302 0 ▶ make_path($dir) or die "Cannot create directory '$dir': $!.\n";
Branch: 1 branch
BranchTrueFalseTotal
make_path($dir) or die "Cannot create directory '${dir}': $!.\n" 0 0 0
303 }
304 4 my $tmp = "${path}.update_config-${PID}";
305 4 ▶ symlink($dest, $tmp) or die "Cannot create the symbolic link '${tmp}': $!.\n";
Branch: 1 branch
BranchTrueFalseTotal
symlink $dest, $tmp or die "Cannot create the symbolic link '${tmp}': $!.\n" 4 0 4
306 4 ▶ if (not rename($tmp, $path)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (rename $tmp, $path) 0 4 4
307 0 my $error = $!;
308 0 unlink $tmp;
309 0 die "Cannot replace '${path}' with a symbolic link: ${error}.\n";
310 }
311 4 return;
312 }
313  
314 157 ▶sub need_perm_update {
Subroutine need_perm_update: called CC=3 SCAR=11.0
315 157 my ($file, $mode, $conf) = @_;
316 157 ▶ return 0 if not exists $conf->{perm};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $conf->{"perm"} 148 9 157
317 9 ▶ return 0 if $mode ne 'file';
Branch: 1 branch
BranchTrueFalseTotal
if $mode ne "file" 0 9 9
318 9 my $current = (stat $file)[2] & oct('7777');
319 9 return $current != oct($conf->{perm});
320 }
321  
322 # The directives that can appear at the beginning of a fragment. Each entry
323 # gives the key of the fragment configuration where the directive is stored
324 # (if any) and how: `flag` directives take no value and set their key to their
325 # `value` (default to 1),
326 # `multiple` directives can be repeated and store their values in a list, the
327 # others store their value directly (an empty string for `optional` directives
328 # without a value).
329 154 my %DIRECTIVES = (
330 'APPEND' => {key => 'append', flag => 1},
331 'BASE' => {key => 'base', multiple => 1},
332 'COMMENTS CHAR' => {key => 'comments_char'},
333 'DIR' => {key => 'dir'},
334 'ENTIRE FILE' => {key => 'entire_file', flag => 1},
335 'FILENAME' => {key => 'filename'},
336 'GUARD SUFFIX' => {key => 'guard_suffix'},
337 'IS PREFIX' => {key => 'is_prefix', flag => 1},
338 'MAKE EXECUTABLE' => {key => 'make_executable', flag => 1},
339 'MERGE' => {key => 'merge', optional => 1},
340 'MERGE ARRAYS' => {key => 'merge_arrays'},
341 # Both MIRROR variants set the same key, so that the deepest one wins.
342 'MIRROR' => {key => 'mirror', flag => 1, value => 'dir'},
343 'MIRROR CONTENTS' => {key => 'mirror', flag => 1, value => 'contents'},
344 'NEED ROOT' => {key => 'need_root', flag => 1},
345 # TODO: validate that the mode is a correct octal value.
346 'PERM' => {key => 'perm'},
347 'POST UPDATE' => {key => 'post_update'},
348 'REM' => {},
349 'REQUIRE' => {key => 'require', multiple => 1},
350 'SYMLINK' => {key => 'symlink'},
351 );
352  
353 # For some directives, the directives that can't be used with them when they are
354 # set as deep (see add_conf). These directives are ignored when they are set in
355 # a parent directory of the one setting the key directive.
356 154 my %EXCLUDED_DIRECTIVES = (
357 'APPEND' => [
358 'COMMENTS CHAR',
359 'ENTIRE FILE',
360 'IS PREFIX',
361 'MAKE EXECUTABLE',
362 'MERGE',
363 'MERGE ARRAYS',
364 'NEED ROOT',
365 'PERM',
366 'POST UPDATE'
367 ],
368 'SYMLINK' => [
369 'APPEND',
370 'COMMENTS CHAR',
371 'ENTIRE FILE',
372 'IS PREFIX',
373 'MAKE EXECUTABLE',
374 'MERGE',
375 'MERGE ARRAYS',
376 'PERM'
377 ],
378 );
379 # Longest names first, so that a directive is not matched by its prefix (e.g.
380 # MERGE ARRAYS by MERGE).
381 154 my $DIRECTIVE_RE = join '|', map { quotemeta } sort { length $b <=> length $a } keys %DIRECTIVES;
382  
383 # Applies the directive in the given line to the fragment configuration.
384 # Returns false if the line is not a valid directive.
385 597 ▶sub parse_directive {
Subroutine parse_directive: called CC=10 SCAR=23.0
386 597 my ($line, $conf) = @_;
387 597 ▶ my ($name, $value) = $line =~ m/^(${DIRECTIVE_RE}) (?: \s+ (\S.*?) )? \s*$/x or return 0;
Branch: 1 branch
BranchTrueFalseTotal
() = $line =~ /^($DIRECTIVE_RE) (?: \s+ (\S.*?) )? \s*$/ux or return 0 347 250 597
388 347 my $directive = $DIRECTIVES{$name};
389 # Flag directives must not have a value and the other ones must have one
390 # (unless it is optional).
391 347 ▶ return 0 if $directive->{flag} ? defined $value : !defined $value && !$directive->{optional};
Branch: 2 branches
BranchTrueFalseTotal
if $directive->{"flag"} ? defined $value : !(defined $value || $directive->{"optional"}) 2 345 347
$directive->{'flag'} ? : 104 243 347
Condition100%3/3
defined $value || $directive->{'optional'}
l!l&&r!l&&!r
232101
MC/DC100%2/2
defined $value || $directive->{'optional'}
defined $value $directive->{'optional'}
Truth table100%3/3
A || B
A= defined $valueB= $directive->{'optional'}
ABresult
1X1
011
000
392 345 ▶ $value //= '';
Condition100%2/2
$value //= ""
l!l
232113
MC/DC100%1/1
$value //= ""
$value
Truth table100%2/2
A
A= $value
Aresult
11
00
393 345 my $key = $directive->{key};
394 345 ▶ if (not defined $key) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $key) { } 3 342 345
elsif ($directive->{'flag'}) { } 103 239 342
elsif ($directive->{'multiple'}) { } 27 212 239
395 # Nothing to do, this is a comment.
396 } elsif ($directive->{flag}) {
397 103 ▶ $conf->{$key} = $directive->{value} // 1;
Condition100%2/2
$directive->{"value"} // 1
l!l
1885
MC/DC100%1/1
$directive->{"value"} // 1
$directive->{"value"}
Truth table100%2/2
A
A= $directive->{"value"}
Aresult
11
00
398 } elsif ($directive->{multiple}) {
399 27 push @{$conf->{$key}}, $value;
400 } else {
401 212 $conf->{$key} = $value;
402 }
403 345 return 1;
404 }
405  
406 # Parses the directives at the beginning of the given fragment text. Returns a
407 # hash-ref with their values (see parse_directive), the rest of the text (the
408 # content of the fragment) and an array-ref of the lines of the directives.
409 275 ▶sub parse_directives {
Subroutine parse_directives: called CC=3 SCAR=11.0
410 275 my ($text) = @_;
411 275 my (%conf, @lines);
412 275 $text =~ s/\n{2,}$/\n/;
413 275 $text =~ s/^\n+//;
414 # Each directive is on its own line, they can be followed by empty lines.
415 275 ▶ while ($text =~ m/\A ([^\n]*) \n+/x) {
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ /\A ([^\n]*) \n+/ux) 540 24 564
416 540 my ($line, $end) = ($1, $LAST_MATCH_END[0]);
417 540 ▶ last if not parse_directive($line, \%conf);
Branch: 1 branch
BranchTrueFalseTotal
unless parse_directive($line, \%conf) 251 289 540
418 289 push @lines, $line;
419 289 substr $text, 0, $end, '';
420 }
421 275 return (\%conf, $text, \@lines);
422 }
423  
424 # Returns the directives of a DIR_CONF_NAME file with the given name (used in
425 # error messages), as a hash-ref (see parse_directive). Dies if the file
426 # contains anything else than directives and empty lines.
427 40 ▶sub parse_dir_conf {
Subroutine parse_dir_conf: called CC=5 SCAR=16.1
428 40 my ($name, $text) = @_;
429 40 my %conf;
430 40 for my $line (split /\n/, $text) {
431 58 ▶ next if $line !~ m/\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless $line =~ /\S/u 1 57 58
432 57 ▶ parse_directive($line, \%conf) or die "Invalid directive in '${name}': '${line}'.\n";
Branch: 1 branch
BranchTrueFalseTotal
parse_directive($line, \%conf) or die "Invalid directive in '${name}': '${line}'.\n" 56 1 57
433 }
434 39 check_dir_and_mirror(\%conf, $name);
435 37 ▶ die "SYMLINK cannot be used in '${name}'.\n" if exists $conf{symlink};
Branch: 1 branch
BranchTrueFalseTotal
if exists $conf{"symlink"} 1 36 37
436 36 return \%conf;
437 }
438  
439 # Dies if the given directives (from parse_directive) of the file with the
440 # given name contain both DIR and MIRROR.
441 314 ▶sub check_dir_and_mirror {
Subroutine check_dir_and_mirror: called CC=3 SCAR=11.0
442 314 my ($conf, $name) = @_;
443 die "DIR and MIRROR cannot be used together in '${name}'.\n"
444 314 ▶ if exists $conf->{dir} and exists $conf->{mirror};
Branch: 1 branch
BranchTrueFalseTotal
if exists $conf->{"dir"} and exists $conf->{"mirror"} 2 312 314
Condition100%3/3
exists $conf->{"dir"} and exists $conf->{"mirror"}
!ll&&!rl&&r
295172
MC/DC100%2/2
exists $conf->{"dir"} and exists $conf->{"mirror"}
exists $conf->{"dir"} exists $conf->{"mirror"}
Truth table100%3/3
A and B
A= exists $conf->{"dir"}B= exists $conf->{"mirror"}
ABresult
0X0
100
111
445 312 return;
446 }
447  
448 # Adds to the combined configuration $conf the directives of $new (from
449 # parse_directive), which are set at the given depth: the number of
450 # directories between the root of the configuration directory and the
451 # DIR_CONF_NAME file setting them (or get_name_depth for the own directives of
452 # a fragment). The repeatable directives are appended to the existing ones,
453 # the others replace them. The depth of each directive is stored in the
454 # `depth` hash-ref of $conf.
455 356 ▶sub add_conf {
Subroutine add_conf: called CC=5 SCAR=16.1
456 356 my ($conf, $new, $depth) = @_;
457 # DIR and MIRROR both set the directory of the target, the deepest one wins.
458 356 ▶ delete $conf->{mirror} if exists $new->{dir};
Branch: 1 branch
BranchTrueFalseTotal
if exists $new->{"dir"} 21 335 356
459 356 ▶ delete $conf->{dir} if exists $new->{mirror};
Branch: 1 branch
BranchTrueFalseTotal
if exists $new->{"mirror"} 33 323 356
460 356 for my $key (keys %{$new}) {
461 394 ▶ if (ref $new->{$key} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $new->{$key} eq 'ARRAY') { } 47 347 394
462 47 push @{$conf->{$key}}, @{$new->{$key}};
463 } else {
464 347 $conf->{$key} = $new->{$key};
465 }
466 394 $conf->{depth}{$key} = $depth;
467 }
468 356 return;
469 }
470  
471 # Returns the configuration that the fragment with the given name inherits
472 # from the DIR_CONF_NAME files of its directories (from $dir_confs, see
473 # split_config_files), combined from the outermost one with add_conf.
474 263 ▶sub get_inherited_conf {
Subroutine get_inherited_conf: called CC=3 SCAR=11.0
475 263 my ($name, $dir_confs) = @_;
476 263 my @dirs = split m{/}, $name;
477 263 pop @dirs;
478 263 my %conf = (depth => {});
479 263 for my $depth (0 .. @dirs) {
480 386 my $dir_conf = $dir_confs->{join '/', @dirs[0 .. $depth - 1]};
481 386 ▶ add_conf(\%conf, $dir_conf, $depth) if $dir_conf;
Branch: 1 branch
BranchTrueFalseTotal
if $dir_conf 81 305 386
482 }
483 263 return \%conf;
484 }
485  
486 # Returns the configuration of a fragment, as a hash with the values of its
487 # directives, its `content` and its guard markers. When the optional $name of
488 # the fragment is given, it is used for the defaults of some directives (see
489 # get_guard_suffix), and the fragment inherits the directives of its
490 # directories from the optional $dir_confs (see get_inherited_conf).
491 275 ▶sub parse_file_conf {
Subroutine parse_file_conf: called CC=22 SCAR=30.9
492 275 my ($file, $name, $dir_confs) = @_;
493 275 my ($own, $content) = parse_directives($file);
494 275 ▶ check_dir_and_mirror($own, $name // 'the fragment');
Condition100%2/2
$name // "the fragment"
l!l
26312
MC/DC100%1/1
$name // "the fragment"
$name
Truth table100%2/2
A
A= $name
Aresult
11
00
495 275 ▶ my %conf = defined $name ? %{get_inherited_conf($name, $dir_confs // {})} : (depth => {});
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 263 12 275
Condition50%1/2
$dir_confs // {}
l!l
2630
MC/DC0%0/1
$dir_confs // {}
$dir_confs
Truth table50%1/2
A
A= $dir_confs
Aresult
11
00
496 275 ▶ add_conf(\%conf, $own, defined $name ? get_name_depth($name) : 0);
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 263 12 275
497 275 ▶ validate_symlink_conf(\%conf, $content) if exists $conf{symlink};
Branch: 1 branch
BranchTrueFalseTotal
if exists $conf{"symlink"} 20 255 275
498 266 ▶ remove_excluded_directives(\%conf, 'APPEND') if exists $conf{append};
Branch: 1 branch
BranchTrueFalseTotal
if exists $conf{"append"} 29 237 266
499 # MERGE ARRAYS can be set in a directory for its fragments that use MERGE,
500 # and COMMENTS CHAR for its fragments that don't (unless it is set as deep
501 # as MERGE).
502 257 ▶ delete $conf{merge_arrays} if not exists $conf{merge} and not exists $own->{merge_arrays};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $conf{"merge"} or exists $own->{"merge_arrays"} 199 58 257
Condition100%3/3
exists $conf{"merge"} or exists $own->{"merge_arrays"}
l!l&&r!l&&!r
562199
MC/DC100%2/2
exists $conf{"merge"} or exists $own->{"merge_arrays"}
exists $conf{"merge"} exists $own->{"merge_arrays"}
Truth table100%3/3
A or B
A= exists $conf{"merge"}B= exists $own->{"merge_arrays"}
ABresult
1X1
011
000
503 delete $conf{comments_char}
504 if exists $conf{merge}
505 and exists $conf{comments_char}
506 257 ▶ and $conf{depth}{comments_char} < $conf{depth}{merge};
Branch: 1 branch
BranchTrueFalseTotal
if exists $conf{"merge"} and exists $conf{"comments_char"} and $conf{"depth"}{"comments_char"} < $conf{"depth"}{"merge"} 2 255 257
Condition100%6/6
exists $conf{"merge"} and exists $conf{"comments_char"} and $conf{"depth"}{"comments_char"} < $conf{"depth"}{"merge"}
!ll&&!rl&&r
25412
exists $conf{"merge"} and exists $conf{"comments_char"}
!ll&&!rl&&r
201533
MC/DC100%3/3
exists $conf{"merge"} and exists $conf{"comments_char"} and $conf{"depth"}{"comments_char"} < $conf{"depth"}{"merge"}
exists $conf{"merge"} exists $conf{"comments_char"} $conf{"depth"}{"comments_char"} < $conf{"depth"}{"merge"}
Truth table100%4/4
A and B and C
A= exists $conf{"merge"}B= exists $conf{"comments_char"}C= $conf{"depth"}{"comments_char"} < $conf{"depth"}{"merge"}
ABCresult
0XX0
10X0
1100
1111
507 257 ▶ if (defined $name and defined $conf{merge} and $conf{merge} eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $name and defined $conf{"merge"} and $conf{"merge"} eq "") 8 249 257
Condition100%6/6
defined $name and defined $conf{"merge"} and $conf{"merge"} eq ""
!ll&&!rl&&r
213368
defined $name and defined $conf{"merge"}
!ll&&!rl&&r
1220144
MC/DC100%3/3
defined $name and defined $conf{"merge"} and $conf{"merge"} eq ""
defined $name defined $conf{"merge"} $conf{"merge"} eq ""
Truth table100%4/4
A and B and C
A= defined $nameB= defined $conf{"merge"}C= $conf{"merge"} eq ""
ABCresult
0XX0
10X0
1100
1111
508 8 $conf{merge} = get_merge_format($name, get_target($name, \%conf));
509 }
510 256 ▶ if (defined $name) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $name) { } 244 12 256
elsif (exists $conf{'guard_suffix'}) { } 0 12 12
511 244 my $suffix = get_guard_suffix($name, \%conf);
512 244 ▶ $conf{guard_suffix} = $suffix if defined $suffix;
Branch: 1 branch
BranchTrueFalseTotal
if defined $suffix 53 191 244
513 } elsif (exists $conf{guard_suffix}) {
514 0 $conf{guard_suffix} = uc $conf{guard_suffix};
515 }
516 256 ▶ my $comments_decorator = ($conf{comments_char} // DEFAULT_COMMENTS_CHAR) x COMMENTS_CHAR_COUNT;
Condition100%2/2
$conf{"comments_char"} // "#"
l!l
6250
MC/DC100%1/1
$conf{"comments_char"} // "#"
$conf{"comments_char"}
Truth table100%2/2
A
A= $conf{"comments_char"}
Aresult
11
00
517 256 ▶ my $guard = DEFAULT_GUARD_STRING.(exists $conf{guard_suffix} ? ':'.$conf{guard_suffix} : '');
Branch: 1 branch
BranchTrueFalseTotal
exists $conf{'guard_suffix'} ? : 53 203 256
518 256 $conf{start_marker} = $comments_decorator.$guard.' START'.$comments_decorator."\n";
519 256 $conf{end_marker} = $comments_decorator.$guard.' END'.$comments_decorator."\n";
520 256 $conf{content} = $content;
521 256 ▶ validate_merge_conf(\%conf) if exists $conf{merge} or exists $conf{merge_arrays};
Branch: 1 branch
BranchTrueFalseTotal
if exists $conf{"merge"} or exists $conf{"merge_arrays"} 57 199 256
Condition100%3/3
exists $conf{"merge"} or exists $conf{"merge_arrays"}
l!l&&r!l&&!r
552199
MC/DC100%2/2
exists $conf{"merge"} or exists $conf{"merge_arrays"}
exists $conf{"merge"} exists $conf{"merge_arrays"}
Truth table100%3/3
A or B
A= exists $conf{"merge"}B= exists $conf{"merge_arrays"}
ABresult
1X1
011
000
522 251 return %conf;
523 }
524  
525 # Removes from the given fragment configuration (see parse_file_conf), which
526 # uses the given directive (a key of %EXCLUDED_DIRECTIVES), the directives that
527 # are excluded by it and set in a parent directory of the one setting it. Dies
528 # if one of these directives is set as deep as it, or deeper.
529 48 ▶sub remove_excluded_directives {
Subroutine remove_excluded_directives: called CC=4 SCAR=13.9
530 48 my ($conf, $directive) = @_;
531 48 my $depth = $conf->{depth}{$DIRECTIVES{$directive}{key}};
532 48 for my $d (@{$EXCLUDED_DIRECTIVES{$directive}}) {
533 349 my $key = $DIRECTIVES{$d}{key};
534 349 ▶ next if not exists $conf->{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $conf->{$key} 324 25 349
535 25 ▶ die "${directive} cannot be used with ${d}.\n" if $conf->{depth}{$key} >= $depth;
Branch: 1 branch
BranchTrueFalseTotal
if $conf->{"depth"}{$key} >= $depth 17 8 25
536 8 delete $conf->{$key};
537 }
538 31 return;
539 }
540  
541 # Dies if the given fragment configuration (with the SYMLINK directive, see
542 # parse_file_conf) and content are invalid for a symbolic link. Removes from the
543 # configuration the inherited directives that don't apply to symbolic links (see
544 # remove_excluded_directives), and expands a leading `~` in the destination of
545 # the link.
546 20 ▶sub validate_symlink_conf {
Subroutine validate_symlink_conf: called CC=2 SCAR=6.9
547 20 my ($conf, $content) = @_;
548 20 ▶ die "A SYMLINK fragment cannot have any content.\n" if $content =~ m/\S/;
Branch: 1 branch
BranchTrueFalseTotal
if $content =~ /\S/u 1 19 20
549 19 remove_excluded_directives($conf, 'SYMLINK');
550 11 $conf->{symlink} =~ s{^~(?=/|$)}{get_home_dir()}e;
551 11 return;
552 }
553  
554 # The formats supported by the MERGE directive. Each entry gives the module
555 # needed to handle the format (if any, it is loaded only when used), a `parse`
556 # function that takes a text and returns the corresponding data (dies on
557 # error), and a `serialize` function that takes a data hash-ref and returns its
558 # text representation (with sorted keys when possible).
559 my %MERGE_FORMATS = (
560 ini => {
561 module => 'Config::Tiny',
562 parse => \&parse_ini,
563 2 ▶ serialize => sub { Config::Tiny->new($_[0])->write_string },
Subroutine __ANON__: called CC=1 SCAR=0.0
564 },
565 json => {
566 module => 'JSON::PP',
567 51 ▶ parse => sub { $_[0] =~ m/\S/ ? JSON::PP->new->relaxed->decode($_[0]) : {} },
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$_[0] =~ /\S/u ? : 45 6 51
568 38 ▶ serialize => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
569 38 my $json = JSON::PP->new->canonical->indent;
570 38 $json->space_after->indent_length(2);
571 38 return $json->encode($_[0]);
572 },
573 },
574 toml => {
575 module => 'TOML::Tiny',
576 parse => \&parse_toml,
577 22 ▶ serialize => sub { my $t = TOML::Tiny::to_toml($_[0]); $t eq '' ? '' : "${t}\n" },
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
$t eq '' ? : 0 22 22
578 },
579 yaml => {
580 module => 'YAML::PP',
581 parse => \&parse_yaml,
582 4 ▶ serialize => sub { YAML::PP->new(boolean => 'JSON::PP', header => 0)->dump_string($_[0]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
583 },
584 154 );
585  
586 # The file extensions, other than the names of the MERGE formats, that are
587 # recognized by get_merge_format.
588 154 my %MERGE_EXTENSIONS = (yml => 'yaml');
589  
590 # Returns the MERGE format of the fragment with the given name, from the
591 # extension of its target (ignoring the suffix between brackets). Dies if that
592 # extension is not a known format.
593 8 ▶sub get_merge_format {
Subroutine get_merge_format: called CC=4 SCAR=14.0
594 8 my ($name, $target) = @_;
595 8 my ($extension) = clean_output_path($target) =~ m/[.](\w+)$/;
596 8 ▶ $extension = lc($extension // '');
Condition50%1/2
$extension // ""
l!l
80
MC/DC0%0/1
$extension // ""
$extension
Truth table50%1/2
A
A= $extension
Aresult
11
00
597 8 ▶ my $format = $MERGE_EXTENSIONS{$extension} // $extension;
Condition66%2/3
$MERGE_EXTENSIONS{$extension} // $extension
l!l&&r!l&&!r
170
MC/DC0%0/2
$MERGE_EXTENSIONS{$extension} // $extension
$MERGE_EXTENSIONS{$extension} $extension
Truth table66%2/3
A // B
A= $MERGE_EXTENSIONS{$extension}B= $extension
ABresult
1X1
011
000
598 die "Cannot find the MERGE format of '${name}' from the extension of '${target}'.\n"
599 8 ▶ if not exists $MERGE_FORMATS{$format};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $MERGE_FORMATS{$format} 1 7 8
600 7 return $format;
601 }
602  
603 # Dies if the MERGE directives of a fragment configuration are invalid and sets
604 # the default value of MERGE ARRAYS.
605 57 ▶sub validate_merge_conf {
Subroutine validate_merge_conf: called CC=8 SCAR=20.8
606 57 my ($conf) = @_;
607 57 ▶ die "MERGE ARRAYS requires the MERGE directive.\n" if not exists $conf->{merge};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $conf->{"merge"} 2 55 57
608 # Without a name, parse_file_conf does not know the target of the fragment,
609 # from which the format would be found.
610 die "Unsupported MERGE format: '$conf->{merge}'.\n"
611 55 ▶ if $conf->{merge} ne '' and not exists $MERGE_FORMATS{lc $conf->{merge}};
Branch: 1 branch
BranchTrueFalseTotal
if $conf->{"merge"} ne "" and not exists $MERGE_FORMATS{lc $conf->{"merge"}} 1 54 55
Condition66%2/3
$conf->{"merge"} ne "" and not exists $MERGE_FORMATS{lc $conf->{"merge"}}
!ll&&!rl&&r
0541
MC/DC50%1/2
$conf->{"merge"} ne "" and not exists $MERGE_FORMATS{lc $conf->{"merge"}}
$conf->{"merge"} ne "" not exists $MERGE_FORMATS{lc $conf->{"merge"}}
Truth table66%2/3
A and not(B)
A= $conf->{"merge"} ne ""B= not exists $MERGE_FORMATS{lc $conf->{"merge"}}
ABresult
0X0
100
111
612 54 $conf->{merge} = lc $conf->{merge};
613 54 ▶ $conf->{merge_arrays} //= 'auto';
Condition100%2/2
$conf->{"merge_arrays"} //= "auto"
l!l
450
MC/DC100%1/1
$conf->{"merge_arrays"} //= "auto"
$conf->{"merge_arrays"}
Truth table100%2/2
A
A= $conf->{"merge_arrays"}
Aresult
11
00
614 die "Invalid MERGE ARRAYS value: '$conf->{merge_arrays}'.\n"
615 54 ▶ if not any { $conf->{merge_arrays} eq $_ } qw(auto union replace);
Subroutine __ANON__: called CC=1 SCAR=0.2
Branch: 1 branch
BranchTrueFalseTotal
unless &any(sub { $conf->{"merge_arrays"} eq $_; } , "auto", "union", "replace") 0 54 54
616 54 for my $d ('COMMENTS CHAR', 'ENTIRE FILE', 'IS PREFIX') {
617 159 ▶ die "MERGE cannot be used with ${d}.\n" if exists $conf->{$DIRECTIVES{$d}{key}};
Branch: 1 branch
BranchTrueFalseTotal
if exists $$conf{$DIRECTIVES{$d}{"key"}} 2 157 159
618 }
619 52 return;
620 }
621  
622 26 ▶sub parse_toml {
Subroutine parse_toml: called CC=2 SCAR=7.0
623 26 my ($text) = @_;
624 26 my ($data, $error) = TOML::Tiny::from_toml($text);
625 26 ▶ die "${error}\n" if $error;
Branch: 1 branch
BranchTrueFalseTotal
if $error 0 26 26
626 26 return $data;
627 }
628  
629 4 ▶sub parse_yaml {
Subroutine parse_yaml: called CC=3 SCAR=11.0
630 4 my ($text) = @_;
631 4 my @docs = YAML::PP->new(boolean => 'JSON::PP')->load_string($text);
632 4 ▶ die "Multiple YAML documents are not supported.\n" if @docs > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @docs > 1 0 4 4
633 4 ▶ return $docs[0] // {};
Condition100%2/2
$docs[0] // {}
l!l
31
MC/DC100%1/1
$docs[0] // {}
$docs[0]
Truth table100%2/2
A
A= $docs[0]
Aresult
11
00
634 }
635  
636 # Returns the INI data as a plain hash-ref, where the keys outside of any
637 # section are in the `_` section.
638 2 ▶sub parse_ini {
Subroutine parse_ini: called CC=2 SCAR=7.0
639 2 my ($text) = @_;
640 2 ▶ my $config = Config::Tiny->read_string($text) // die Config::Tiny->errstr."\n";
Condition50%1/2
"Config::Tiny"->read_string($text) // die("Config::Tiny"->errstr . "\n")
l!l
20
MC/DC0%0/1
"Config::Tiny"->read_string($text) // die("Config::Tiny"->errstr . "\n")
"Config::Tiny"->read_string($text)
Truth table50%1/2
A
A= "Config::Tiny"->read_string($text)
Aresult
11
00
641 2 return {%{$config}};
642 }
643  
644 # Returns the hash-ref parsed from the given text in the given MERGE format.
645 # The $source is used in error messages.
646 83 ▶sub parse_merge_data {
Subroutine parse_merge_data: called CC=3 SCAR=11.4
647 83 my ($format, $text, $source) = @_;
648 83 my $data = eval { $MERGE_FORMATS{$format}{parse}->($text) };
649 83 ▶ if ($EVAL_ERROR) {
Branch: 1 branch
BranchTrueFalseTotal
if ($main::EVAL_ERROR) 0 83 83
650 0 my $error = $EVAL_ERROR =~ s/\s+\z//r;
651 0 die "Cannot parse ${source} as ${format}: ${error}\n";
652 }
653 83 ▶ die "The content of ${source} is not a ${format} table.\n" if ref $data ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $data ne "HASH" 1 82 83
654 82 return $data;
655 }
656  
657 # Returns true if the two given data structures are equal. Scalar values are
658 # compared as strings.
659 32 ▶sub data_equal {
Subroutine data_equal: called CC=8 SCAR=24.9
660 32 my ($x, $y) = @_;
661 32 ▶ return 0 if ref $x ne ref $y;
Branch: 1 branch
BranchTrueFalseTotal
if ref $x ne ref $y 0 32 32
662 32 ▶ if (ref $x eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $x eq "HASH") 9 23 32
663 9 ▶ return 0 if keys %{$x} != keys %{$y};
Branch: 1 branch
BranchTrueFalseTotal
if keys %{$x;} != keys %{$y;} 0 9 9
664 9 ▶ return all { exists $y->{$_} and data_equal($x->{$_}, $y->{$_}) } keys %{$x};
Subroutine __ANON__: called CC=2 SCAR=7.1
Branch: 1 branch
BranchTrueFalseTotal
exists $y->{$_} and data_equal($x->{$_}, $y->{$_}) 9 0 9
665 }
666 23 ▶ if (ref $x eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $x eq "ARRAY") 0 23 23
667 0 ▶ return 0 if @{$x} != @{$y};
Branch: 1 branch
BranchTrueFalseTotal
if @{$x;} != @{$y;} 0 0 0
668 0 ▶ return all { data_equal($x->[$_], $y->[$_]) } 0 .. $#{$x};
Subroutine __ANON__: not called CC=1 SCAR=6.9
669 }
670 23 ▶ return !defined $y if !defined $x;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $x 0 23 23
671 23 ▶ return defined $y && "$x" eq "$y";
Condition66%2/3
defined $y && "$x" eq "$y"
!ll&&!rl&&r
0815
MC/DC50%1/2
defined $y && "$x" eq "$y"
defined $y "$x" eq "$y"
Truth table66%2/3
A && B
A= defined $yB= "$x" eq "$y"
ABresult
0X0
100
111
672 }
673  
674 # Removes recursively the ARRAYS_MARKER entries from the given fragment data and
675 # records in %$modes the merge mode of the arrays that they name (see
676 # parse_array_mode), indexed by the address of these arrays.
677 184 ▶sub extract_array_modes {
Subroutine extract_array_modes: called CC=9 SCAR=22.0
678 184 my ($data, $modes) = @_;
679 184 ▶ if (ref $data eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $data eq 'HASH') { } 92 92 184
elsif (ref $data eq 'ARRAY') { } 15 77 92
680 92 ▶ my $marker = delete $data->{+ARRAYS_MARKER} // {};
Condition100%2/2
delete $data->{"update_config_arrays"} // {}
l!l
785
MC/DC100%1/1
delete $data->{"update_config_arrays"} // {}
delete $data->{"update_config_arrays"}
Truth table100%2/2
A
A= delete $data->{"update_config_arrays"}
Aresult
11
00
681 92 ▶ die ARRAYS_MARKER." must be a map.\n" if ref $marker ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $marker ne "HASH" 0 92 92
682 92 for my $k (keys %{$marker}) {
683 7 ▶ die ARRAYS_MARKER." names '${k}' which is not an array.\n" if ref $data->{$k} ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $data->{$k} ne "ARRAY" 1 6 7
684 6 $modes->{refaddr $data->{$k}} = parse_array_mode($marker->{$k});
685 }
686 90 extract_array_modes($_, $modes) for values %{$data};
687 } elsif (ref $data eq 'ARRAY') {
688 15 extract_array_modes($_, $modes) for @{$data};
689 }
690 182 return;
691 }
692  
693 # Returns the merge mode described by the given text: `union`, `replace` or
694 # an array-ref of the key fields given as `key:field1,field2`.
695 6 ▶sub parse_array_mode {
Subroutine parse_array_mode: called CC=4 SCAR=13.9
696 6 my ($text) = @_;
697 6 ▶ die "Invalid array merge mode: '${text}'.\n" if ref $text;
Branch: 1 branch
BranchTrueFalseTotal
if ref $text 0 6 6
698 6 ▶ return $text if any { $text eq $_ } qw(union replace);
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
if &any(sub { $text eq $_; } , "union", "replace") 1 5 6
699 5 ▶ if ($text =~ m/^key:(.+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ /^key:(.+)$/u) 4 1 5
700 4 return [split /,/, $1];
701 }
702 1 die "Invalid array merge mode: '${text}'.\n";
703 }
704  
705 # Returns the merge mode of the given fragment $array, to be merged into the
706 # $target array. Arrays without an explicit mode use the MERGE ARRAYS directive
707 # and, by default, are replaced if they contain only scalars.
708 11 ▶sub get_array_mode {
Subroutine get_array_mode: called CC=4 SCAR=13.9
709 11 my ($ctx, $array, $target) = @_;
710 11 ▶ my $mode = $ctx->{modes}{refaddr $array} // $ctx->{default};
Condition66%2/3
$ctx->{"modes"}{builtin::refaddr($array)} // $ctx->{"default"}
l!l&&r!l&&!r
470
MC/DC0%0/2
$ctx->{"modes"}{builtin::refaddr($array)} // $ctx->{"default"}
$ctx->{"modes"}{builtin::refaddr($array)} $ctx->{"default"}
Truth table66%2/3
A // B
A= $ctx->{"modes"}{builtin::refaddr($array)}B= $ctx->{"default"}
ABresult
1X1
011
000
711 11 ▶ return $mode if $mode ne 'auto';
Branch: 1 branch
BranchTrueFalseTotal
if $mode ne "auto" 7 4 11
712 4 ▶ return (any { ref } @{$array}, @{$target}) ? 'union' : 'replace';
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
&any(sub { ref $_; } , @{$array;}, @{$target;}) ? : 3 1 4
713 }
714  
715 # Merges in place the $new hash-ref (from a fragment) into the $target one
716 # (from the target file). $old is the data of the previous version of the
717 # fragment (or an empty hash-ref), its values that are no longer in $new are
718 # removed from $target, unless they were modified there. Nested hashes are
719 # merged recursively and arrays according to their mode (see get_array_mode).
720 # $ctx has the `modes` from extract_array_modes and the `default` mode.
721 45 ▶sub merge_hash {
Subroutine merge_hash: called CC=19 SCAR=31.1
722 45 my ($target, $old, $new, $ctx) = @_;
723 45 for my $k (keys %{$new}) {
724 58 my ($t, $o, $n) = ($target->{$k}, $old->{$k}, $new->{$k});
725 58 my $mode;
726 58 ▶ if (ref $n eq 'HASH' and ref $t eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $n eq 'HASH' and ref $t eq 'HASH') { } 6 52 58
elsif (ref $n eq 'ARRAY' and ref $t eq 'ARRAY' and ($mode = get_array_mode($ctx, $n, $t)) ne 'replace') { } 8 44 52
Condition100%3/3
ref $n eq "HASH" and ref $t eq "HASH"
!ll&&!rl&&r
5116
MC/DC100%2/2
ref $n eq "HASH" and ref $t eq "HASH"
ref $n eq "HASH" ref $t eq "HASH"
Truth table100%3/3
A and B
A= ref $n eq "HASH"B= ref $t eq "HASH"
ABresult
0X0
100
111
727 6 ▶ merge_hash($t, ref $o eq 'HASH' ? $o : {}, $n, $ctx);
Branch: 1 branch
BranchTrueFalseTotal
ref $o eq 'HASH' ? : 1 5 6
728 ▶ } elsif (ref $n eq 'ARRAY'
Condition100%6/6
ref $n eq "ARRAY" and ref $t eq "ARRAY" and ($mode = get_array_mode($ctx, $n, $t)) ne "replace"
!ll&&!rl&&r
4138
ref $n eq "ARRAY" and ref $t eq "ARRAY"
!ll&&!rl&&r
40111
MC/DC100%3/3
ref $n eq "ARRAY" and ref $t eq "ARRAY" and ($mode = get_array_mode($ctx, $n, $t)) ne "replace"
ref $n eq "ARRAY" ref $t eq "ARRAY" ($mode = get_array_mode($ctx, $n, $t)) ne "replace"
Truth table100%4/4
A and B and C
A= ref $n eq "ARRAY"B= ref $t eq "ARRAY"C= ($mode = get_array_mode($ctx, $n, $t)) ne "replace"
ABCresult
0XX0
10X0
1100
1111
729 and ref $t eq 'ARRAY'
730 and ($mode = get_array_mode($ctx, $n, $t)) ne 'replace') {
731 8 ▶ merge_array($t, ref $o eq 'ARRAY' ? $o : [], $n, $mode, $ctx);
Branch: 1 branch
BranchTrueFalseTotal
ref $o eq 'ARRAY' ? : 3 5 8
732 } else {
733 44 $target->{$k} = $n;
734 }
735 }
736 45 ▶ for my $k (grep { !exists $new->{$_} && exists $target->{$_} } keys %{$old}) {
Condition66%2/3
!exists $new->{$_} && exists $target->{$_}
!ll&&!rl&&r
12012
MC/DC50%1/2
!exists $new->{$_} && exists $target->{$_}
!exists $new->{$_} exists $target->{$_}
Truth table66%2/3
not(A) && B
A= !exists $new->{$_}B= exists $target->{$_}
ABresult
0X0
100
111
737 12 my ($t, $o) = ($target->{$k}, $old->{$k});
738 12 my $mode;
739 12 ▶ if (ref $o eq 'HASH' and ref $t eq 'HASH') {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $o eq 'HASH' and ref $t eq 'HASH') { } 1 11 12
elsif (ref $o eq 'ARRAY' and ref $t eq 'ARRAY' and ($mode = get_array_mode($ctx, $o, $t)) ne 'replace') { } 0 11 11
elsif (data_equal($t, $o)) { } 10 1 11
Condition66%2/3
ref $o eq "HASH" and ref $t eq "HASH"
!ll&&!rl&&r
1101
MC/DC50%1/2
ref $o eq "HASH" and ref $t eq "HASH"
ref $o eq "HASH" ref $t eq "HASH"
Truth table66%2/3
A and B
A= ref $o eq "HASH"B= ref $t eq "HASH"
ABresult
0X0
100
111
740 1 merge_hash($t, $o, {}, $ctx);
741 1 ▶ delete $target->{$k} if not %{$t};
Branch: 1 branch
BranchTrueFalseTotal
unless %{$t;} 1 0 1
742 ▶ } elsif (ref $o eq 'ARRAY'
Condition33%2/6
ref $o eq "ARRAY" and ref $t eq "ARRAY" and ($mode = get_array_mode($ctx, $o, $t)) ne "replace"
!ll&&!rl&&r
1100
ref $o eq "ARRAY" and ref $t eq "ARRAY"
!ll&&!rl&&r
1100
MC/DC0%0/3
ref $o eq "ARRAY" and ref $t eq "ARRAY" and ($mode = get_array_mode($ctx, $o, $t)) ne "replace"
ref $o eq "ARRAY" ref $t eq "ARRAY" ($mode = get_array_mode($ctx, $o, $t)) ne "replace"
Truth table25%1/4
A and B and C
A= ref $o eq "ARRAY"B= ref $t eq "ARRAY"C= ($mode = get_array_mode($ctx, $o, $t)) ne "replace"
ABCresult
0XX0
10X0
1100
1111
743 and ref $t eq 'ARRAY'
744 and ($mode = get_array_mode($ctx, $o, $t)) ne 'replace') {
745 0 merge_array($t, $o, [], $mode, $ctx);
746 0 ▶ delete $target->{$k} if not @{$t};
Branch: 1 branch
BranchTrueFalseTotal
unless @{$t;} 0 0 0
747 } elsif (data_equal($t, $o)) {
748 10 delete $target->{$k};
749 }
750 }
751 45 return;
752 }
753  
754 # Merges in place the $new array-ref into $target, with the given mode (`union`
755 # or the array-ref of key fields), see merge_hash.
756 8 ▶sub merge_array {
Subroutine merge_array: called CC=2 SCAR=6.9
757 8 my ($target, $old, $new, $mode, $ctx) = @_;
758 8 ▶ return merge_keyed_array($target, $old, $new, $mode, $ctx) if ref $mode;
Branch: 1 branch
BranchTrueFalseTotal
if ref $mode 3 5 8
759 my @removed = grep {
760 3 my $o = $_;
761 3 ▶ !any { data_equal($o, $_) } @{$new}
Subroutine __ANON__: called CC=1 SCAR=0.0
762 5 } @{$old};
763 5 @{$target} = grep {
764 8 my $t = $_;
765 2 ▶ !any { data_equal($t, $_) } @removed
Subroutine __ANON__: called CC=1 SCAR=0.0
766 5 } @{$target};
767 5 push @{$target}, grep {
768 5 my $n = $_;
769 5 ▶ !any { data_equal($n, $_) } @{$target}
Subroutine __ANON__: called CC=1 SCAR=0.0
770 5 } @{$new};
771 5 return;
772 }
773  
774 # Merges in place arrays of maps identified by the given key fields: the
775 # entries of $target with the same key as an entry of $new are merged with it
776 # (with merge_hash), the others from $new are appended. The values of the
777 # entries removed since $old are removed, as well as these entries if only
778 # their key remains.
779 3 ▶sub merge_keyed_array {
Subroutine merge_keyed_array: called CC=14 SCAR=27.2
780 3 my ($target, $old, $new, $fields, $ctx) = @_;
781 # Returns the key of an entry or undef if it does not have all the fields.
782 17 ▶ my $key_of = sub {
Subroutine __ANON__: called CC=3 SCAR=11.7
783 17 my ($e) = @_;
784 17 ▶ return if ref $e ne 'HASH' or any { !defined $e->{$_} || ref $e->{$_} } @{$fields};
Subroutine __ANON__: called CC=2 SCAR=8.1
Branch: 2 branches
BranchTrueFalseTotal
if ref $e ne "HASH" or &any(sub { not defined $e->{$_} or ref $e->{$_}; } , @{$fields;}) 0 17 17
not defined $e->{$_} or ref $e->{$_} 0 21 21
Condition33%1/3
ref $e ne "HASH" or &any(sub { not defined $e->{$_} or ref $e->{$_}; } , @{$fields;})
l!l&&r!l&&!r
0017
MC/DC0%0/2
ref $e ne "HASH" or &any(sub { not defined $e->{$_} or ref $e->{$_}; } , @{$fields;})
ref $e ne "HASH" &any(sub { not defined $e->{$_} or ref $e->{$_}; } , @{$fields;})
Truth table33%1/3
A or B
A= ref $e ne "HASH"B= &any(sub { not defined $e->{$_} or ref $e->{$_}; } , @{$fields;})
ABresult
1X1
011
000
785 17 return join "\0", map { $e->{$_} } @{$fields};
786 3 };
787 3 my (%new, %old, %seen);
788 3 for my $n (@{$new}) {
789 0 ▶ my $k = $key_of->($n) // die "An array entry is missing the key fields: @{$fields}.\n";
Condition50%1/2
&$key_of($n) // die("An array entry is missing the key fields: @{$fields;}.\n")
l!l
40
MC/DC0%0/1
&$key_of($n) // die("An array entry is missing the key fields: @{$fields;}.\n")
&$key_of($n)
Truth table50%1/2
A
A= &$key_of($n)
Aresult
11
00
790 0 ▶ die "Duplicate array entry for the key fields: @{$fields}.\n" if exists $new{$k};
Branch: 1 branch
BranchTrueFalseTotal
if exists $new{$k} 0 4 4
791 4 $new{$k} = $n;
792 }
793 3 for my $o (@{$old}) {
794 2 my $k = $key_of->($o);
795 2 ▶ $old{$k} = {%{$o}} if defined $k;
Branch: 1 branch
BranchTrueFalseTotal
if defined $k 2 0 2
796 2 ▶ delete @{$old{$k}}{@{$fields}} if defined $k;
Branch: 1 branch
BranchTrueFalseTotal
if defined $k 2 0 2
797 }
798 3 my @result;
799 3 for my $t (@{$target}) {
800 7 my $k = $key_of->($t);
801 7 ▶ if (defined $k and exists $new{$k}) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $k and exists $new{$k}) { } 3 4 7
elsif (defined $k and exists $old{$k}) { } 2 2 4
Condition66%2/3
defined $k and exists $new{$k}
!ll&&!rl&&r
043
MC/DC50%1/2
defined $k and exists $new{$k}
defined $k exists $new{$k}
Truth table66%2/3
A and B
A= defined $kB= exists $new{$k}
ABresult
0X0
100
111
802 3 ▶ merge_hash($t, $old{$k} // {}, $new{$k}, $ctx);
Condition50%1/2
$old{$k} // {}
l!l
03
MC/DC0%0/1
$old{$k} // {}
$old{$k}
Truth table50%1/2
A
A= $old{$k}
Aresult
11
00
803 3 $seen{$k} = 1;
804 ▶ } elsif (defined $k and exists $old{$k}) {
Condition66%2/3
defined $k and exists $old{$k}
!ll&&!rl&&r
022
MC/DC50%1/2
defined $k and exists $old{$k}
defined $k exists $old{$k}
Truth table66%2/3
A and B
A= defined $kB= exists $old{$k}
ABresult
0X0
100
111
805 2 merge_hash($t, $old{$k}, {}, $ctx);
806 2 ▶ next if keys %{$t} == @{$fields};
Branch: 1 branch
BranchTrueFalseTotal
if keys %{$t;} == @{$fields;} 1 1 2
807 }
808 6 push @result, $t;
809 }
810 3 push @result, grep { !$seen{$key_of->($_)} } @{$new};
811 3 @{$target} = @result;
812 3 return;
813 }
814  
815 # Returns the path of the file where the last applied version of the given
816 # MERGE or ENTIRE FILE fragment (from prepare_fragment) is saved, which is
817 # specific to the fragment (its path in the configuration directory) and to its
818 # target. The NEED ROOT fragments are saved in a system directory so that the
819 # state of the user is never written by root.
820 98 ▶sub get_state_path {
Subroutine get_state_path: called CC=4 SCAR=14.1
821 98 my ($fragment) = @_;
822 98 my ($name, $in_path, $conf) = @{$fragment}{qw(name in_path conf)};
823 98 my $dir;
824 98 ▶ if ($conf->{need_root}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($conf->{'need_root'}) { } 7 91 98
825 7 ▶ $dir = $ENV{UPDATE_CONFIG_ROOT_STATE_DIR} || '/var/lib/update_config';
Condition50%1/2
$ENV{'UPDATE_CONFIG_ROOT_STATE_DIR'} || '/var/lib/update_config'
l!l
70
MC/DC0%0/1
$ENV{'UPDATE_CONFIG_ROOT_STATE_DIR'} || '/var/lib/update_config'
$ENV{'UPDATE_CONFIG_ROOT_STATE_DIR'}
Truth table50%1/2
A
A= $ENV{'UPDATE_CONFIG_ROOT_STATE_DIR'}
Aresult
11
00
826 } else {
827 91 ▶ $dir = catfile($ENV{XDG_STATE_HOME} || catfile(get_home_dir(), '.local', 'state'),
Condition33%1/3
$ENV{'XDG_STATE_HOME'} || catfile(get_home_dir(), '.local', 'state')
l!l&&r!l&&!r
0910
MC/DC0%0/2
$ENV{'XDG_STATE_HOME'} || catfile(get_home_dir(), '.local', 'state')
$ENV{'XDG_STATE_HOME'} catfile(get_home_dir(), '.local', 'state')
Truth table33%1/3
A || B
A= $ENV{'XDG_STATE_HOME'}B= catfile(get_home_dir(), '.local', 'state')
ABresult
1X1
011
000
828 'update_config');
829 }
830 # The readable part of the name is not unique (in particular for commands),
831 # so we add a hash of the full target and of the name of the fragment.
832 98 my $readable = basename($in_path) =~ s/[^\w.]+/_/gr;
833 98 my $hash = substr sha1_hex(join "\0", $in_path, $name), 0, STATE_HASH_LENGTH;
834 98 return catfile($dir, "${readable}-${hash}");
835 }
836  
837 # Returns the data of the previous version of the given MERGE fragment (from
838 # prepare_fragment), if it was saved with the same format. Otherwise returns an
839 # empty hash-ref.
840 36 ▶sub read_merge_state {
Subroutine read_merge_state: called CC=4 SCAR=14.0
841 36 my ($fragment) = @_;
842 36 my $conf = $fragment->{conf};
843 36 my $path = get_state_path($fragment);
844 36 ▶ return {} if not -f $path;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $path 24 12 36
845 12 my %old = parse_file_conf(scalar read_file($path));
846 12 ▶ return {} if ($old{merge} // '') ne $conf->{merge};
Branch: 1 branch
BranchTrueFalseTotal
if ($old{"merge"} // "") ne $conf->{"merge"} 0 12 12
Condition50%1/2
$old{"merge"} // ""
l!l
120
MC/DC0%0/1
$old{"merge"} // ""
$old{"merge"}
Truth table50%1/2
A
A= $old{"merge"}
Aresult
11
00
847 12 return parse_merge_data($old{merge}, $old{content}, "the saved state '${path}'");
848 }
849  
850 # Returns the content of the given ENTIRE FILE fragment (from prepare_fragment)
851 # when it was last applied, or undef if it was not saved.
852 13 ▶sub read_entire_file_state {
Subroutine read_entire_file_state: called CC=3 SCAR=11.0
853 13 my ($fragment) = @_;
854 13 my $path = get_state_path($fragment);
855 13 ▶ return if not -f $path;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $path 2 11 13
856 11 my $content = read_file($path);
857 11 ▶ return if substr($content, 0, length ENTIRE_FILE_STATE_HEADER) ne ENTIRE_FILE_STATE_HEADER;
Branch: 1 branch
BranchTrueFalseTotal
if substr($content, 0, 13) ne "ENTIRE FILE\n\n" 0 11 11
858 11 return substr $content, length ENTIRE_FILE_STATE_HEADER;
859 }
860  
861 # Saves the content of the given MERGE (with its format) or ENTIRE FILE
862 # fragment (from prepare_fragment), so that it can be read by read_merge_state
863 # or read_entire_file_state on the next run.
864 49 ▶sub save_state {
Subroutine save_state: called CC=6 SCAR=17.9
865 49 my ($fragment) = @_;
866 49 my $conf = $fragment->{conf};
867 49 my $path = get_state_path($fragment);
868 49 ▶ my $header = $conf->{merge} ? "MERGE $conf->{merge}\n\n" : ENTIRE_FILE_STATE_HEADER;
Branch: 1 branch
BranchTrueFalseTotal
$conf->{'merge'} ? : 31 18 49
869 49 my $content = $header.$conf->{content};
870 49 ▶ return if -f $path and read_file($path) eq $content;
Branch: 1 branch
BranchTrueFalseTotal
if -f $path and read_file($path) eq $content 6 43 49
Condition100%3/3
-f $path and read_file($path) eq $content
!ll&&!rl&&r
27166
MC/DC100%2/2
-f $path and read_file($path) eq $content
-f $path read_file($path) eq $content
Truth table100%3/3
A and B
A= -f $pathB= read_file($path) eq $content
ABresult
0X0
100
111
871 43 my $dir = dirname($path);
872 43 ▶ make_path($dir) if not -d $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $dir 24 19 43
873 43 ▶ write_file($path, $content) or die "Cannot write '${path}': $!\n";
Branch: 1 branch
BranchTrueFalseTotal
write_file($path, $content) or die "Cannot write '${path}': $!\n" 43 0 43
874 43 return;
875 }
876  
877 # Returns the current content of a MERGE target, re-serialized in its format,
878 # and its content once the fragment is merged into it.
879 36 ▶sub merge_content {
Subroutine merge_content: called CC=2 SCAR=6.9
880 36 my ($mode, $file, $conf, $old) = @_;
881 36 my (undef, $text) = read_content($mode, $file, $conf);
882 36 my $data = parse_merge_data($conf->{merge}, $text, "'${file}'");
883 35 my $new = parse_merge_data($conf->{merge}, $conf->{content}, 'the fragment');
884 35 my $ctx = {modes => {}, default => $conf->{merge_arrays}};
885 35 extract_array_modes($_, $ctx->{modes}) for $new, $old;
886 33 my $serialize = $MERGE_FORMATS{$conf->{merge}}{serialize};
887 33 my $old_content = $serialize->($data);
888 33 merge_hash($data, $old, $new, $ctx);
889 33 return ($old_content, $serialize->($data));
890 }
891  
892 # Puts in %$content the content of the files in the given directory and all its
893 # subdirectories, indexed by their path relative to the given directory (the
894 # optional $prefix is added at the beginning of these paths). Ignores hidden files and
895 # directories, except for the DIR_CONF_NAME files.
896 244 ▶sub read_config_files {
Subroutine read_config_files: called CC=9 SCAR=22.0
897 244 my ($dir, $content, $prefix) = @_;
898 244 ▶ opendir(my $dh, $dir) or die "Can't open dir '$dir': $!\n";
Branch: 1 branch
BranchTrueFalseTotal
opendir my $dh, $dir or die "Can't open dir '${dir}': $!\n" 244 0 244
899 244 ▶ while (readdir $dh) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readdir $dh)) 913 244 1157
900 913 my $f = catfile($dir, $_);
901 913 ▶ next if m/^\./ and ($_ ne DIR_CONF_NAME or not -f $f);
Branch: 1 branch
BranchTrueFalseTotal
if /^\./u and $_ ne ".update_config" || !(-f $f) 490 423 913
Condition83%5/6
/^\./u and $_ ne ".update_config" || !(-f $f)
!ll&&!rl&&r
37944490
$_ ne ".update_config" or not -f $f
l!l&&r!l&&!r
490044
MC/DC66%2/3
/^\./u and $_ ne ".update_config" || !(-f $f)
/^\./u $_ ne ".update_config" not -f $f
Truth table75%3/4
A and B or not(C)
A= /^\./uB= $_ ne ".update_config"C= not -f $f
ABCresult
0XX0
1000
11X1
1011
902 423 ▶ my $name = defined $prefix ? "${prefix}/$_" : $_;
Branch: 1 branch
BranchTrueFalseTotal
defined $prefix ? : 167 256 423
903 423 ▶ read_config_files($f, $content, $name) if -d $f;
Branch: 1 branch
BranchTrueFalseTotal
if -d $f 91 332 423
904 423 ▶ $content->{$name} = read_file($f) if -f $f;
Branch: 1 branch
BranchTrueFalseTotal
if -f $f 332 91 423
905 }
906 244 closedir $dh;
907 244 return;
908 }
909  
910 # Splits the given configuration files (indexed by their path relative to the
911 # configuration directory) into the fragments, indexed the same way, and the
912 # directives of the DIR_CONF_NAME files (from parse_dir_conf), indexed by the
913 # path of their directory ('' for the root of the configuration directory).
914 148 ▶sub split_config_files {
Subroutine split_config_files: called CC=3 SCAR=11.0
915 148 my ($config_files) = @_;
916 148 my (%fragments, %dir_confs);
917 148 ▶ while (my ($name, $content) = each %{$config_files}) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %{$config_files;}) 310 144 454
918 310 ▶ if (basename($name) eq DIR_CONF_NAME) {
Branch: 1 branch
BranchTrueFalseTotal
if (basename($name) eq '.update_config') { } 40 270 310
919 40 $dir_confs{$name =~ s{/?[^/]+$}{}r} = parse_dir_conf($name, $content);
920 } else {
921 270 $fragments{$name} = $content;
922 }
923 }
924 144 return (\%fragments, \%dir_confs);
925 }
926  
927 # The keys of the directives that are replaced by a single FILENAME directive
928 # in the exported fragments.
929 154 my %TARGET_KEYS = map { $_ => 1 } qw(base dir filename mirror);
930  
931 # Returns the text of the given directive, with the given value.
932 0 ▶sub format_directive {
Subroutine format_directive: not called CC=3 SCAR=24.8
933 0 my ($directive, $value) = @_;
934 0 ▶ return $DIRECTIVES{$directive}{flag} || $value eq '' ? $directive : "${directive} ${value}";
Branch: 1 branch
BranchTrueFalseTotal
$DIRECTIVES{$directive}{'flag'} || $value eq '' ? : 0 0 0
Condition0%0/3
$DIRECTIVES{$directive}{"flag"} or $value eq ""
l!l&&r!l&&!r
000
MC/DC0%0/2
$DIRECTIVES{$directive}{"flag"} or $value eq ""
$DIRECTIVES{$directive}{"flag"} $value eq ""
Truth table0%0/3
A or B
A= $DIRECTIVES{$directive}{"flag"}B= $value eq ""
ABresult
1X1
011
000
935 }
936  
937 # Writes in the current directory the fragments embedded in the script. The
938 # exported files are not in their directories, so their target, their guard
939 # suffix and the directives inherited from their directories are written
940 # explicitly.
941 0 ▶sub export_fragments {
Subroutine export_fragments: not called CC=17 SCAR=57.2
942 0 my ($fragments, $dir_confs) = split_config_files(get_data_section());
943 0 for my $file (sort keys %{$fragments}) {
944 0 my %conf = parse_file_conf($fragments->{$file}, $file, $dir_confs);
945 0 my ($own, $content, $own_lines) = parse_directives($fragments->{$file});
946 0 my $inherited = get_inherited_conf($file, $dir_confs);
947 0 my @header = ('FILENAME '.get_target($file, \%conf));
948 push @header, "GUARD SUFFIX $conf{guard_suffix}"
949 0 ▶ if exists $conf{guard_suffix} and not exists $own->{guard_suffix};
Branch: 1 branch
BranchTrueFalseTotal
if exists $conf{"guard_suffix"} and not exists $own->{"guard_suffix"} 0 0 0
Condition0%0/3
exists $conf{"guard_suffix"} and not exists $own->{"guard_suffix"}
!ll&&!rl&&r
000
MC/DC0%0/2
exists $conf{"guard_suffix"} and not exists $own->{"guard_suffix"}
exists $conf{"guard_suffix"} not exists $own->{"guard_suffix"}
Truth table0%0/3
A and not(B)
A= exists $conf{"guard_suffix"}B= not exists $own->{"guard_suffix"}
ABresult
0X0
100
111
950 0 for my $d (sort keys %DIRECTIVES) {
951 0 my ($key, $multiple) = @{$DIRECTIVES{$d}}{qw(key multiple)};
952 0 ▶ next if not defined $key or $TARGET_KEYS{$key} or $key eq 'guard_suffix';
Branch: 1 branch
BranchTrueFalseTotal
if not defined $key or $TARGET_KEYS{$key} or $key eq "guard_suffix" 0 0 0
Condition0%0/6
not defined $key or $TARGET_KEYS{$key} or $key eq "guard_suffix"
l!l&&r!l&&!r
000
not defined $key or $TARGET_KEYS{$key}
l!l&&r!l&&!r
000
MC/DC0%0/3
not defined $key or $TARGET_KEYS{$key} or $key eq "guard_suffix"
not defined $key $TARGET_KEYS{$key} $key eq "guard_suffix"
Truth table0%0/4
not(A) or B or C
A= not defined $keyB= $TARGET_KEYS{$key}C= $key eq "guard_suffix"
ABCresult
1XX1
01X1
0011
0000
953 0 ▶ next if not exists $inherited->{$key} or not exists $conf{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $inherited->{$key} and exists $conf{$key} 0 0 0
Condition0%0/3
exists $inherited->{$key} and exists $conf{$key}
!ll&&!rl&&r
000
MC/DC0%0/2
exists $inherited->{$key} and exists $conf{$key}
exists $inherited->{$key} exists $conf{$key}
Truth table0%0/3
A and B
A= exists $inherited->{$key}B= exists $conf{$key}
ABresult
0X0
100
111
954 0 ▶ next if exists $own->{$key} and not $multiple;
Branch: 1 branch
BranchTrueFalseTotal
if exists $own->{$key} and not $multiple 0 0 0
Condition0%0/3
exists $own->{$key} and not $multiple
!ll&&!rl&&r
000
MC/DC0%0/2
exists $own->{$key} and not $multiple
exists $own->{$key} not $multiple
Truth table0%0/3
A and not(B)
A= exists $own->{$key}B= not $multiple
ABresult
0X0
100
111
955 push @header,
956 0 ▶ map { format_directive($d, $_) } $multiple ? @{$inherited->{$key}} : $inherited->{$key};
Branch: 1 branch
BranchTrueFalseTotal
$multiple ? : 0 0 0
957 }
958 0 for my $line (@{$own_lines}) {
959 0 my ($d) = $line =~ m/^(${DIRECTIVE_RE})/;
960 0 ▶ push @header, $line if not $TARGET_KEYS{$DIRECTIVES{$d}{key} // ''};
Branch: 1 branch
BranchTrueFalseTotal
unless $TARGET_KEYS{$DIRECTIVES{$d}{"key"} // ""} 0 0 0
Condition0%0/2
$DIRECTIVES{$d}{"key"} // ""
l!l
00
MC/DC0%0/1
$DIRECTIVES{$d}{"key"} // ""
$DIRECTIVES{$d}{"key"}
Truth table0%0/2
A
A= $DIRECTIVES{$d}{"key"}
Aresult
11
00
961 }
962 0 $content = join('', map { "${_}\n" } @header).$content;
963 0 $file =~ s/^\.//;
964 0 $file =~ s{/|,}{_}g;
965 0 print "Exporting: $file\n";
966 0 ▶ write_file($file, $content) or die "Cannot write file '$file': $!\n";
Branch: 1 branch
BranchTrueFalseTotal
write_file($file, $content) or die "Cannot write file '${file}': $!\n" 0 0 0
967 }
968 0 return;
969 }
970  
971 # Prints on STDOUT our own script, followed by all the given fragments, so that
972 # they are embedded in its __DATA__ section.
973 6 ▶sub pack_fragments {
Subroutine pack_fragments: called CC=4 SCAR=13.9
974 6 my ($config_files) = @_;
975 6 print read_file(catfile($FindBin::RealBin, $FindBin::RealScript));
976 6 for my $file (sort by_fragment_order keys %{$config_files}) {
977 20 my $content = $config_files->{$file};
978 # The next "@@" header must start on its own line.
979 20 ▶ $content .= "\n" if $content ne '' and $content !~ m/\n\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $content ne "" and not $content =~ /\n\z/u 1 19 20
Condition66%2/3
$content ne "" and not $content =~ /\n\z/u
!ll&&!rl&&r
0191
MC/DC50%1/2
$content ne "" and not $content =~ /\n\z/u
$content ne "" not $content =~ /\n\z/u
Truth table66%2/3
A and not(B)
A= $content ne ""B= not $content =~ /\n\z/u
ABresult
0X0
100
111
980 20 print "@@ ${file}\n${content}";
981 }
982 6 return;
983 }
984  
985 # Returns true if all the REQUIRE guards of the fragment are verified.
986 233 ▶sub check_requirements {
Subroutine check_requirements: called CC=6 SCAR=17.9
987 233 my ($conf, $display_name) = @_;
988 233 for my $r (@{$conf->{require}}) {
989 19 my ($expr, $reason) = split /\s*#\s*/, $r, 2;
990 19 ▶ next if eval $expr; ## no critic (ProhibitStringyEval)
Branch: 1 branch
BranchTrueFalseTotal
if eval $expr 7 12 19
991 12 ▶ die "Error while executing 'require' guard for ${display_name} '${expr}': $@.\n" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 11 12
992 printf "Skipping %s due to require guard%s\n", $display_name, ($reason ? ': '.$reason : '')
993 11 ▶ unless $flags{silent};
Branch: 2 branches
BranchTrueFalseTotal
unless $flags{"silent"} 11 0 11
$reason ? : 3 8 11
994 11 return 0;
995 }
996 221 return 1;
997 }
998  
999 # Writes the new content of the target file and executes the POST UPDATE
1000 # command if any.
1001 135 ▶sub update_target {
Subroutine update_target: called CC=5 SCAR=16.1
1002 135 my ($mode, $out_path, $before, $new_content, $after, $conf) = @_;
1003 135 ▶ if (exists $conf->{symlink}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $conf->{'symlink'}) { } 4 131 135
elsif ($conf->{'entire_file'} or $conf->{'merge'}) { } 41 90 131
1004 4 write_symlink($out_path, $conf->{symlink});
1005 ▶ } elsif ($conf->{entire_file} or $conf->{merge}) {
Condition100%3/3
$conf->{"entire_file"} or $conf->{"merge"}
l!l&&r!l&&!r
152690
MC/DC100%2/2
$conf->{"entire_file"} or $conf->{"merge"}
$conf->{"entire_file"} $conf->{"merge"}
Truth table100%3/3
A or B
A= $conf->{"entire_file"}B= $conf->{"merge"}
ABresult
1X1
011
000
1006 41 write_content($mode, $out_path, $new_content, $conf);
1007 } else {
1008 90 my $content = $before.$conf->{start_marker}.$new_content.$conf->{end_marker}.$after;
1009 90 write_content($mode, $out_path, $content, $conf);
1010 }
1011 135 ▶ if ($conf->{post_update}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($conf->{"post_update"}) 1 134 135
1012 1 my $cmd = $conf->{post_update} =~ s/\$@/$out_path/gr;
1013 1 system $cmd;
1014 }
1015 135 return;
1016 }
1017  
1018 # Returns the current content of the target of the given fragment (from
1019 # prepare_fragment), split in four parts: the content before the managed part,
1020 # the current and new versions of the managed part, and the content after it.
1021 177 ▶sub get_contents {
Subroutine get_contents: called CC=4 SCAR=13.9
1022 177 my ($fragment) = @_;
1023 177 my ($mode, $in_path, $conf) = @{$fragment}{qw(mode in_path conf)};
1024 return ('', describe_symlink_target($in_path), "-> $conf->{symlink}\n", '')
1025 177 ▶ if exists $conf->{symlink};
Branch: 1 branch
BranchTrueFalseTotal
if exists $conf->{"symlink"} 9 168 177
1026 168 ▶ if (not $conf->{merge}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($conf->{"merge"}) 132 36 168
1027 132 my ($before, $old_content, $after) = read_content($mode, $in_path, $conf);
1028 131 return ($before, $old_content, $conf->{content}, $after);
1029 }
1030 36 my $module = $MERGE_FORMATS{$conf->{merge}}{module};
1031 36 ▶ load_module($module) if $module;
Branch: 1 branch
BranchTrueFalseTotal
if $module 36 0 36
1032 36 my $old = read_merge_state($fragment);
1033 36 return ('', merge_content($mode, $in_path, $conf, $old), '');
1034 }
1035  
1036 # Returns the given $path resolved relative to the $base path. Both are relative
1037 # to the home directory (an empty $base is the home directory itself), unless
1038 # they are absolute. A $path starting with `~` is relative to the home
1039 # directory, whatever the $base.
1040 291 ▶sub resolve_path {
Subroutine resolve_path: called CC=5 SCAR=16.1
1041 291 my ($base, $path) = @_;
1042 291 ▶ return $path if $path =~ m{^/};
Branch: 1 branch
BranchTrueFalseTotal
if $path =~ m[^/]u 6 285 291
1043 285 ▶ if ($path =~ m{^~(?:/+(.*))?$}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ m[^~(?:/+(.*))?$]u) 4 281 285
1044 4 ▶ return $1 // '';
Condition100%2/2
$1 // ""
l!l
31
MC/DC100%1/1
$1 // ""
$1
Truth table100%2/2
A
A= $1
Aresult
11
00
1045 }
1046 281 ▶ return $path if $base eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $base eq "" 234 47 281
1047 47 return catfile($base, $path);
1048 }
1049  
1050 # Returns the given component of the name of a fragment (its base name or, with
1051 # the MIRROR directive, one of its directories), as it is used in its target:
1052 # without its suffix between brackets and with a `dot_` prefix replaced by a
1053 # dot (as hidden files are ignored in the configuration directory). $name is
1054 # the name of the fragment, used in error messages.
1055 193 ▶sub get_target_name {
Subroutine get_target_name: called CC=2 SCAR=6.9
1056 193 my ($name, $part) = @_;
1057 193 my $clean = clean_output_path($part);
1058 193 ▶ die "Cannot use '${part}' in the target of '${name}', its name is only a guard suffix.\n"
Branch: 1 branch
BranchTrueFalseTotal
if $clean eq "" 2 191 193
1059 if $clean eq '';
1060 191 return $clean =~ s/^dot_/./r;
1061 }
1062  
1063 # Returns the directory of the target of the fragment with the given name and
1064 # the MIRROR directive: the path of its directory relative to the parent of the
1065 # directory where MIRROR is set (the one containing the DIR_CONF_NAME file, or
1066 # the fragment itself), or relative to that directory with MIRROR CONTENTS. The
1067 # root of the configuration directory is never part of that path (see
1068 # get_target_name).
1069 18 ▶sub get_mirrored_dir {
Subroutine get_mirrored_dir: called CC=4 SCAR=13.9
1070 18 my ($name, $conf) = @_;
1071 18 my @dirs = split m{/}, $name;
1072 18 pop @dirs;
1073 # The own directives of a fragment are one level deeper than its directory.
1074 18 my $from = $conf->{depth}{mirror};
1075 18 ▶ $from = @dirs if $from > @dirs;
Branch: 1 branch
BranchTrueFalseTotal
if $from > @dirs 3 15 18
1076 18 ▶ $from-- if $conf->{mirror} eq 'dir' and $from > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $conf->{"mirror"} eq "dir" and $from > 0 11 7 18
Condition100%3/3
$conf->{"mirror"} eq "dir" and $from > 0
!ll&&!rl&&r
6111
MC/DC100%2/2
$conf->{"mirror"} eq "dir" and $from > 0
$conf->{"mirror"} eq "dir" $from > 0
Truth table100%3/3
A and B
A= $conf->{"mirror"} eq "dir"B= $from > 0
ABresult
0X0
100
111
1077 18 return join '/', map { get_target_name($name, $_) } @dirs[$from .. $#dirs];
1078 }
1079  
1080 # Returns the target of the given fragment, from its BASE, DIR (or MIRROR) and
1081 # FILENAME directives and from its name, in the format expected by
1082 # parse_file_name. An absolute FILENAME (or one starting with `~` or made of
1083 # commands) ignores the BASE, DIR and MIRROR directives set in a parent
1084 # directory. Dies if these directives are incompatible.
1085 247 ▶sub get_target {
Subroutine get_target: called CC=14 SCAR=26.4
1086 247 my ($name, $conf) = @_;
1087 247 ▶ my $file = $conf->{filename} // get_target_name($name, basename($name));
Condition66%2/3
$conf->{"filename"} // get_target_name($name, basename($name))
l!l&&r!l&&!r
751720
MC/DC0%0/2
$conf->{"filename"} // get_target_name($name, basename($name))
$conf->{"filename"} get_target_name($name, basename($name))
Truth table66%2/3
A // B
A= $conf->{"filename"}B= get_target_name($name, basename($name))
ABresult
1X1
011
000
1088 247 ▶ if ($file =~ m{^(?:/|~(?:/|$))} or $file =~ m/,/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($file =~ m[^(?:/|~(?:/|$))]u or $file =~ /,/u) 11 236 247
Condition100%3/3
$file =~ m[^(?:/|~(?:/|$))]u or $file =~ /,/u
l!l&&r!l&&!r
74236
MC/DC100%2/2
$file =~ m[^(?:/|~(?:/|$))]u or $file =~ /,/u
$file =~ m[^(?:/|~(?:/|$))]u $file =~ /,/u
Truth table100%3/3
A or B
A= $file =~ m[^(?:/|~(?:/|$))]uB= $file =~ /,/u
ABresult
1X1
011
000
1089 11 ▶ my $file_depth = exists $conf->{filename} ? $conf->{depth}{filename} : get_name_depth($name);
Branch: 1 branch
BranchTrueFalseTotal
exists $conf->{'filename'} ? : 11 0 11
1090 11 for my $d ('DIR', 'MIRROR') {
1091 19 my $key = $DIRECTIVES{$d}{key};
1092 19 ▶ next if not exists $conf->{$key} or $conf->{depth}{$key} < $file_depth;
Branch: 1 branch
BranchTrueFalseTotal
if not exists $conf->{$key} or $conf->{"depth"}{$key} < $file_depth 15 4 19
Condition100%3/3
not exists $conf->{$key} or $conf->{"depth"}{$key} < $file_depth
l!l&&r!l&&!r
1144
MC/DC100%2/2
not exists $conf->{$key} or $conf->{"depth"}{$key} < $file_depth
not exists $conf->{$key} $conf->{"depth"}{$key} < $file_depth
Truth table100%3/3
not(A) or B
A= not exists $conf->{$key}B= $conf->{"depth"}{$key} < $file_depth
ABresult
1X1
011
000
1093 4 ▶ die "${d} cannot be used with commands in '${name}'.\n" if $file =~ m/,/;
Branch: 1 branch
BranchTrueFalseTotal
if $file =~ /,/u 1 3 4
1094 3 die "FILENAME cannot be an absolute path with ${d} in '${name}'.\n";
1095 }
1096 7 ▶ return $file =~ m/,/ ? $file : resolve_path('', $file);
Branch: 1 branch
BranchTrueFalseTotal
$file =~ /,/u ? : 3 4 7
1097 }
1098 236 ▶ my $dir = exists $conf->{mirror} ? get_mirrored_dir($name, $conf) : $conf->{dir};
Branch: 1 branch
BranchTrueFalseTotal
exists $conf->{'mirror'} ? : 18 218 236
1099 234 my $target = '';
1100 $target = resolve_path($target, $_)
1101 234 ▶ for @{$conf->{base} // []}, grep { defined && $_ ne '' } $dir, $file;
Condition100%5/5
$conf->{"base"} // []
l!l
17217
defined $_ && $_ ne ''
!ll&&!rl&&r
2044260
MC/DC100%1/1
$conf->{"base"} // []
$conf->{"base"}
MC/DC100%2/2
defined $_ && $_ ne ''
defined $_ $_ ne ''
Truth table100%2/2
A
A= $conf->{"base"}
Aresult
11
00
Truth table100%3/3
A && B
A= defined $_B= $_ ne ''
ABresult
0X0
100
111
1102 234 return $target;
1103 }
1104  
1105 # Sorts the fragments by their base name and then by their path, ignoring case
1106 # (and then without ignoring it, so that the order is always the same).
1107 209 ▶sub by_fragment_order {
Subroutine by_fragment_order: called CC=3 SCAR=13.1
1108 209 ▶ return (lc basename($a) cmp lc basename($b)) || (lc $a cmp lc $b) || ($a cmp $b);
Condition50%3/6
lc basename($a) cmp lc basename($b) || lc $a cmp lc $b || $a cmp $b
l!l&&r!l&&!r
20900
lc basename($a) cmp lc basename($b) or lc $a cmp lc $b
l!l&&r!l&&!r
192170
MC/DC0%0/3
lc basename($a) cmp lc basename($b) || lc $a cmp lc $b || $a cmp $b
lc basename($a) cmp lc basename($b) lc $a cmp lc $b $a cmp $b
Truth table50%2/4
A or B || C
A= lc basename($a) cmp lc basename($b)B= lc $a cmp lc $bC= $a cmp $b
ABCresult
1XX1
01X1
0011
0000
1109 }
1110  
1111 # Returns the description of the given fragment (from its name and content, and
1112 # the directives of its directories, see parse_file_conf), as a hash-ref with
1113 # its name, `conf` (from parse_file_conf), `display_name`, and the `mode`,
1114 # `in_path` and `out_path` of its target (from parse_file_name). Returns undef
1115 # if its REQUIRE guards are not verified.
1116 263 ▶sub prepare_fragment {
Subroutine prepare_fragment: called CC=5 SCAR=16.1
1117 263 my ($name, $content, $dir_confs) = @_;
1118 263 my %conf = parse_file_conf($content, $name, $dir_confs);
1119 239 my $target = get_target($name, \%conf);
1120 233 ▶ my $display_name = $target.($conf{guard_suffix} ? ' ('.$conf{guard_suffix}.')' : '');
Branch: 1 branch
BranchTrueFalseTotal
$conf{'guard_suffix'} ? : 51 182 233
1121 233 ▶ return if not check_requirements(\%conf, $display_name);
Branch: 1 branch
BranchTrueFalseTotal
unless check_requirements(\%conf, $display_name) 11 221 232
1122 221 my %fragment = (name => $name, conf => \%conf, display_name => $display_name);
1123 221 @fragment{qw(mode in_path out_path)} = parse_file_name($target);
1124 die "SYMLINK cannot be used with commands in '${name}'.\n"
1125 221 ▶ if exists $conf{symlink} and $fragment{mode} eq 'pipe';
Branch: 1 branch
BranchTrueFalseTotal
if exists $conf{"symlink"} and $fragment{"mode"} eq "pipe" 1 220 221
Condition100%3/3
exists $conf{"symlink"} and $fragment{"mode"} eq "pipe"
!ll&&!rl&&r
210101
MC/DC100%2/2
exists $conf{"symlink"} and $fragment{"mode"} eq "pipe"
exists $conf{"symlink"} $fragment{"mode"} eq "pipe"
Truth table100%3/3
A and B
A= exists $conf{"symlink"}B= $fragment{"mode"} eq "pipe"
ABresult
0X0
100
111
1126 220 return \%fragment;
1127 }
1128  
1129 # Returns a key identifying the target of the given fragment (from
1130 # prepare_fragment).
1131 416 ▶sub get_target_key {
Subroutine get_target_key: called CC=1 SCAR=0.0
1132 416 my ($fragment) = @_;
1133 416 return "$fragment->{mode}\0$fragment->{in_path}";
1134 }
1135  
1136 # Dies if some of the given fragments (from prepare_fragment) can't be applied
1137 # to the same target: when they have the same guard suffix (unless they both
1138 # use MERGE), when one of them uses ENTIRE FILE or SYMLINK, or when only one of
1139 # them uses MERGE. The APPEND fragments are ignored (see append_fragments).
1140 111 ▶sub check_conflicts {
Subroutine check_conflicts: called CC=12 SCAR=24.9
1141 111 my (@fragments) = @_;
1142 111 my %by_target;
1143 111 for my $f (grep { !$_->{conf}{append} } @fragments) {
1144 190 my $c = $f->{conf};
1145 190 for my $other (@{$by_target{get_target_key($f)}}) {
1146 14 my $o = $other->{conf};
1147 next
1148 if !$c->{entire_file}
1149 && !$o->{entire_file}
1150 && !exists $c->{symlink}
1151 && !exists $o->{symlink}
1152 && !$c->{merge} == !$o->{merge}
1153 14 ▶ && ($c->{merge} || ($c->{guard_suffix} // "\0") ne ($o->{guard_suffix} // "\0"));
Branch: 1 branch
BranchTrueFalseTotal
if not $c->{"entire_file"} || $o->{"entire_file"} || exists $c->{"symlink"} || exists $o->{"symlink"} and !$c->{"merge"} == !$o->{"merge"} and $c->{"merge"} || ($c->{"guard_suffix"} // "\0") ne ($o->{"guard_suffix"} // "\0") 10 4 14
Condition90%20/22
not $c->{"entire_file"} || $o->{"entire_file"} || exists $c->{"symlink"} || exists $o->{"symlink"} and !$c->{"merge"} == !$o->{"merge"} and $c->{"merge"} || ($c->{"guard_suffix"} // "\0") ne ($o->{"guard_suffix"} // "\0")
!ll&&!rl&&r
3110
not $c->{"entire_file"} || $o->{"entire_file"} || exists $c->{"symlink"} || exists $o->{"symlink"} and !$c->{"merge"} == !$o->{"merge"}
!ll&&!rl&&r
2111
$c->{'entire_file'} || $o->{'entire_file'} || exists $c->{'symlink'} || exists $o->{'symlink'}
l!l&&r!l&&!r
1112
$c->{"entire_file"} or $o->{"entire_file"} or exists $c->{"symlink"}
l!l&&r!l&&!r
1013
$c->{"entire_file"} or $o->{"entire_file"}
l!l&&r!l&&!r
1013
$c->{"merge"} or ($c->{"guard_suffix"} // "\0") ne ($o->{"guard_suffix"} // "\0")
l!l&&r!l&&!r
731
$c->{"guard_suffix"} // "\0"
l!l
31
$o->{"guard_suffix"} // "\0"
l!l
22
MC/DC71%5/7
not $c->{"entire_file"} || $o->{"entire_file"} || exists $c->{"symlink"} || exists $o->{"symlink"} and !$c->{"merge"} == !$o->{"merge"} and $c->{"merge"} || ($c->{"guard_suffix"} // "\0") ne ($o->{"guard_suffix"} // "\0")
$c->{"entire_file"} $o->{"entire_file"} exists $c->{"symlink"} exists $o->{'symlink'} !$c->{"merge"} == !$o->{"merge"} $c->{"merge"} $c->{"guard_suffix"}
MC/DC100%1/1
$o->{"guard_suffix"} // "\0"
$o->{"guard_suffix"}
Truth table75%6/8
not(A or B or C || D) and not(E) and F or G
A= $c->{"entire_file"}B= $o->{"entire_file"}C= exists $c->{"symlink"}D= exists $o->{'symlink'}E= !$c->{"merge"} == !$o->{"merge"}F= $c->{"merge"}G= $c->{"guard_suffix"}
ABCDEFGresult
1XXXXXX0
01XXXXX0
001XXXX0
0001XXX0
00000XX0
00001000
000011X1
00001011
Truth table100%2/2
A
A= $o->{"guard_suffix"}
Aresult
11
00
1154 4 die "Fragments '$other->{name}' and '$f->{name}' can't both be applied to "
1155 ."'$f->{in_path}', use different GUARD SUFFIX directives.\n";
1156 }
1157 186 push @{$by_target{get_target_key($f)}}, $f;
1158 }
1159 107 return;
1160 }
1161  
1162 # Appends the content of each of the given APPEND fragments (from
1163 # prepare_fragment) to the content of the ENTIRE FILE fragment, among the given
1164 # fragments, that has the same target, in the order of the APPEND fragments,
1165 # separated by an empty line. Returns the other fragments. Dies if there is no
1166 # such ENTIRE FILE fragment. The fragments must have been validated by
1167 # check_conflicts.
1168 107 ▶sub append_fragments {
Subroutine append_fragments: called CC=6 SCAR=17.9
1169 107 my (@fragments) = @_;
1170 107 my %entire_files = map { (get_target_key($_) => $_) } grep { $_->{conf}{entire_file} } @fragments;
1171 107 for my $f (grep { $_->{conf}{append} } @fragments) {
1172 16 ▶ my $target = $entire_files{get_target_key($f)}
Condition100%2/2
$entire_files{get_target_key($f)} // die(qq[Fragment '$f->{"name"}' uses APPEND, but there is no ENTIRE FILE fragment applied ] . qq[to '$f->{"in_path"}'.\n])
l!l
133
MC/DC100%1/1
$entire_files{get_target_key($f)} // die(qq[Fragment '$f->{"name"}' uses APPEND, but there is no ENTIRE FILE fragment applied ] . qq[to '$f->{"in_path"}'.\n])
$entire_files{get_target_key($f)}
Truth table100%2/2
A
A= $entire_files{get_target_key($f)}
Aresult
11
00
1173 // die "Fragment '$f->{name}' uses APPEND, but there is no ENTIRE FILE fragment applied "
1174 ."to '$f->{in_path}'.\n";
1175 13 ▶ next if $f->{conf}{content} eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $f->{"conf"}{"content"} eq "" 3 10 13
1176 10 my $content = \$target->{conf}{content};
1177 10 ▶ if (${$content} ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if (${$content;} ne "") 9 1 10
1178 9 ▶ ${$content} .= "\n" if ${$content} !~ m/\n\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless ${$content;} =~ /\n\z/u 1 8 9
1179 9 ${$content} .= "\n";
1180 }
1181 10 ${$content} .= $f->{conf}{content};
1182 }
1183 104 return grep { !$_->{conf}{append} } @fragments;
1184 }
1185  
1186 # Returns the modifications made to the target of the given ENTIRE FILE fragment
1187 # (from prepare_fragment), whose current content is given, since the fragment
1188 # was last applied (according to its saved state), as a diff. Returns undef if
1189 # the target was not modified, or for the other fragments.
1190 136 ▶sub get_target_modifications {
Subroutine get_target_modifications: called CC=6 SCAR=17.9
1191 136 my ($fragment, $current) = @_;
1192 136 my ($conf, $mode, $in_path) = @{$fragment}{qw(conf mode in_path)};
1193 136 ▶ return if not $conf->{entire_file};
Branch: 1 branch
BranchTrueFalseTotal
unless $conf->{"entire_file"} 116 20 136
1194 20 ▶ return if $mode eq 'file' and not -e $in_path;
Branch: 1 branch
BranchTrueFalseTotal
if $mode eq "file" and not -e $in_path 7 13 20
Condition66%2/3
$mode eq "file" and not -e $in_path
!ll&&!rl&&r
0137
MC/DC50%1/2
$mode eq "file" and not -e $in_path
$mode eq "file" not -e $in_path
Truth table66%2/3
A and not(B)
A= $mode eq "file"B= not -e $in_path
ABresult
0X0
100
111
1195 13 ▶ my $saved = read_entire_file_state($fragment) // return;
Condition100%2/2
read_entire_file_state($fragment) // (return)
l!l
112
MC/DC100%1/1
read_entire_file_state($fragment) // (return)
read_entire_file_state($fragment)
Truth table100%2/2
A
A= read_entire_file_state($fragment)
Aresult
11
00
1196 11 ▶ return if $saved eq $current;
Branch: 1 branch
BranchTrueFalseTotal
if $saved eq $current 4 7 11
1197 7 return diff(\$saved, \$current, {CONTEXT => 0});
1198 }
1199  
1200 # Checks whether the target of the given fragment (from prepare_fragment), whose
1201 # current and new contents are given, can be overwritten: an ENTIRE FILE target
1202 # that was not modified (see get_target_modifications), or a SYMLINK target
1203 # that is a symbolic link or does not exist. Returns undef, after printing the
1204 # reason, if the fragment must be skipped (a SYMLINK target that is a directory
1205 # is always skipped). Otherwise, returns the text to add to the message
1206 # reporting the update: ' (forced)' if the target can't be overwritten but
1207 # --force is used, or an empty string.
1208 144 ▶sub check_target_modifications {
Subroutine check_target_modifications: called CC=9 SCAR=22.0
1209 144 my ($fragment, $current, $new) = @_;
1210 144 ▶ return '' if $current eq $new;
Branch: 1 branch
BranchTrueFalseTotal
if $current eq $new 1 143 144
1211 143 ▶ if (exists $fragment->{conf}{symlink}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $fragment->{"conf"}{"symlink"}) 7 136 143
1212 7 ▶ return '' if $current eq '' or $current =~ m/^->/;
Branch: 1 branch
BranchTrueFalseTotal
if $current eq "" or $current =~ /^->/u 4 3 7
Condition100%3/3
$current eq "" or $current =~ /^->/u
l!l&&r!l&&!r
223
MC/DC100%2/2
$current eq "" or $current =~ /^->/u
$current eq "" $current =~ /^->/u
Truth table100%3/3
A or B
A= $current eq ""B= $current =~ /^->/u
ABresult
1X1
011
000
1213 3 ▶ if ($current eq "(directory)\n") {
Branch: 1 branch
BranchTrueFalseTotal
if ($current eq "(directory)\n") 1 2 3
1214 1 print STDERR "Skipping $fragment->{display_name}, which is a directory\n";
1215 1 return;
1216 }
1217 2 ▶ return ' (forced)' if $flags{force};
Branch: 1 branch
BranchTrueFalseTotal
if $flags{"force"} 1 1 2
1218 1 print STDERR "Skipping $fragment->{display_name}, which is not a symbolic link "
1219 ."(use --force to overwrite it)\n";
1220 1 return;
1221 }
1222 136 ▶ my $modifications = get_target_modifications($fragment, $current) // return '';
Condition100%2/2
get_target_modifications($fragment, $current) // (return "")
l!l
7129
MC/DC100%1/1
get_target_modifications($fragment, $current) // (return "")
get_target_modifications($fragment, $current)
Truth table100%2/2
A
A= get_target_modifications($fragment, $current)
Aresult
11
00
1223 7 ▶ return ' (forced)' if $flags{force};
Branch: 1 branch
BranchTrueFalseTotal
if $flags{"force"} 3 4 7
1224 4 print STDERR "Skipping $fragment->{display_name}, which was modified since its last update "
1225 ."(use --force to overwrite it):\n${modifications}";
1226 4 return;
1227 }
1228  
1229 # Applies the given fragment (from prepare_fragment), depending on the command
1230 # line flags. Returns true if the fragment needs root and was not applied.
1231 177 ▶sub apply_fragment {
Subroutine apply_fragment: called CC=18 SCAR=28.9
1232 177 my ($fragment) = @_;
1233 177 my ($conf, $display_name) = @{$fragment}{qw(conf display_name)};
1234 177 my ($mode, $in_path, $out_path) = @{$fragment}{qw(mode in_path out_path)};
1235 177 my ($before, $old_content, $new_content, $after) = get_contents($fragment);
1236 # Whether this run is the one that writes this fragment (as root or not).
1237 173 ▶ my $can_write = !$flags{test} && !$conf->{need_root} == !$flags{root};
Condition100%3/3
!$flags{'test'} && !$conf->{'need_root'} == !$flags{'root'}
!ll&&!rl&&r
74162
MC/DC100%2/2
!$flags{'test'} && !$conf->{'need_root'} == !$flags{'root'}
!$flags{'test'} !$conf->{'need_root'} == !$flags{'root'}
Truth table100%3/3
not(A) && not(B)
A= !$flags{'test'}B= !$conf->{'need_root'} == !$flags{'root'}
ABresult
0X0
100
111
1238 173 ▶ if ($old_content eq $new_content and not need_perm_update($out_path, $mode, $conf)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($old_content eq $new_content and not need_perm_update($out_path, $mode, $conf)) 25 148 173
Condition100%3/3
$old_content eq $new_content and not need_perm_update($out_path, $mode, $conf)
!ll&&!rl&&r
147125
MC/DC100%2/2
$old_content eq $new_content and not need_perm_update($out_path, $mode, $conf)
$old_content eq $new_content not need_perm_update($out_path, $mode, $conf)
Truth table100%3/3
A and not(B)
A= $old_content eq $new_contentB= not need_perm_update($out_path, $mode, $conf)
ABresult
0X0
100
111
1239 25 ▶ print "Nothing to do for: $display_name\n" unless $flags{silent};
Branch: 1 branch
BranchTrueFalseTotal
unless $flags{"silent"} 23 2 25
1240 25 ▶ save_state($fragment) if ($conf->{merge} or $conf->{entire_file}) and $can_write;
Branch: 1 branch
BranchTrueFalseTotal
if $conf->{"merge"} || $conf->{"entire_file"} and $can_write 8 17 25
Condition100%6/6
$conf->{"merge"} || $conf->{"entire_file"} and $can_write
!ll&&!rl&&r
1618
$conf->{"merge"} or $conf->{"entire_file"}
l!l&&r!l&&!r
6316
MC/DC100%3/3
$conf->{"merge"} || $conf->{"entire_file"} and $can_write
$conf->{"merge"} $conf->{"entire_file"} $can_write
Truth table80%4/5
A or B and C
A= $conf->{"merge"}B= $conf->{"entire_file"}C= $can_write
ABCresult
00X0
1X00
0100
1X11
0111
1241 25 return 0;
1242 }
1243 148 ▶ if ($flags{diff}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($flags{"diff"}) 3 145 148
1244 3 my $diff = diff(\$old_content, \$new_content, {CONTEXT => 0});
1245 3 print "Diff for: $display_name\n$diff";
1246 }
1247 148 ▶ return 1 if $conf->{need_root} and not $flags{root};
Branch: 1 branch
BranchTrueFalseTotal
if $conf->{"need_root"} and not $flags{"root"} 3 145 148
Condition100%3/3
$conf->{"need_root"} and not $flags{"root"}
!ll&&!rl&&r
14053
MC/DC100%2/2
$conf->{"need_root"} and not $flags{"root"}
$conf->{"need_root"} not $flags{"root"}
Truth table100%3/3
A and not(B)
A= $conf->{"need_root"}B= not $flags{"root"}
ABresult
0X0
100
111
1248 145 ▶ return 0 if $flags{root} and not $conf->{need_root};
Branch: 1 branch
BranchTrueFalseTotal
if $flags{"root"} and not $conf->{"need_root"} 1 144 145
Condition100%3/3
$flags{"root"} and not $conf->{"need_root"}
!ll&&!rl&&r
13951
MC/DC100%2/2
$flags{"root"} and not $conf->{"need_root"}
$flags{"root"} not $conf->{"need_root"}
Truth table100%3/3
A and not(B)
A= $flags{"root"}B= not $conf->{"need_root"}
ABresult
0X0
100
111
1249 144 ▶ my $forced = check_target_modifications($fragment, $old_content, $new_content) // return 0;
Condition100%2/2
check_target_modifications($fragment, $old_content, $new_content) // (return 0)
l!l
1386
MC/DC100%1/1
check_target_modifications($fragment, $old_content, $new_content) // (return 0)
check_target_modifications($fragment, $old_content, $new_content)
Truth table100%2/2
A
A= check_target_modifications($fragment, $old_content, $new_content)
Aresult
11
00
1250 138 ▶ if ($can_write) {
Branch: 1 branch
BranchTrueFalseTotal
if ($can_write) 135 3 138
1251 135 update_target($mode, $out_path, $before, $new_content, $after, $conf);
1252 135 ▶ save_state($fragment) if $conf->{merge} or $conf->{entire_file};
Branch: 1 branch
BranchTrueFalseTotal
if $conf->{"merge"} or $conf->{"entire_file"} 41 94 135
Condition100%3/3
$conf->{"merge"} or $conf->{"entire_file"}
l!l&&r!l&&!r
261594
MC/DC100%2/2
$conf->{"merge"} or $conf->{"entire_file"}
$conf->{"merge"} $conf->{"entire_file"}
Truth table100%3/3
A or B
A= $conf->{"merge"}B= $conf->{"entire_file"}
ABresult
1X1
011
000
1253 }
1254 138 ▶ print "Updated: ${display_name}${forced}\n" unless $flags{silent};
Branch: 1 branch
BranchTrueFalseTotal
unless $flags{"silent"} 136 2 138
1255 138 return 0;
1256 }
1257  
1258 154 ▶sub main {
Subroutine main: called CC=16 SCAR=30.5
1259 154 ▶ if ($flags{export}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($flags{"export"}) 0 154 154
1260 0 export_fragments();
1261 0 return;
1262 }
1263  
1264 154 my $config_files = {};
1265 154 ▶ $config_files = get_data_section() unless $flags{pack}; # We don’t read __DATA__ if we’re packing content anyway.
Branch: 1 branch
BranchTrueFalseTotal
unless $flags{"pack"} 148 6 154
1266 154 ▶ my $config_dir = $flags{dir} // get_config_dir();
Condition66%2/3
$flags{"dir"} // get_config_dir()
l!l&&r!l&&!r
21520
MC/DC0%0/2
$flags{"dir"} // get_config_dir()
$flags{"dir"} get_config_dir()
Truth table66%2/3
A // B
A= $flags{"dir"}B= get_config_dir()
ABresult
1X1
011
000
1267 154 ▶ print "Reading configuration from: ${config_dir}\n" unless $flags{silent} or $flags{pack};
Branch: 1 branch
BranchTrueFalseTotal
unless $flags{"silent"} or $flags{"pack"} 144 10 154
Condition100%3/3
$flags{"silent"} or $flags{"pack"}
l!l&&r!l&&!r
46144
MC/DC100%2/2
$flags{"silent"} or $flags{"pack"}
$flags{"silent"} $flags{"pack"}
Truth table100%3/3
A or B
A= $flags{"silent"}B= $flags{"pack"}
ABresult
1X1
011
000
1268 154 ▶ read_config_files($config_dir, $config_files) if -d $config_dir;
Branch: 1 branch
BranchTrueFalseTotal
if -d $config_dir 153 1 154
1269  
1270 154 ▶ if ($flags{pack}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($flags{"pack"}) 6 148 154
1271 6 pack_fragments($config_files);
1272 6 return;
1273 }
1274  
1275 148 my ($fragment_files, $dir_confs) = split_config_files($config_files);
1276 263 my @fragments = map { prepare_fragment($_, $fragment_files->{$_}, $dir_confs) }
1277 144 sort by_fragment_order keys %{$fragment_files};
1278 112 ▶ if ($flags{list}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($flags{"list"}) 1 111 112
1279 1 print "$_->{in_path}\n" for @fragments;
1280 1 return;
1281 }
1282 111 check_conflicts(@fragments);
1283 107 @fragments = append_fragments(@fragments);
1284  
1285 104 my $need_root = 0;
1286 104 for my $f (@fragments) {
1287 177 ▶ $need_root = 1 if apply_fragment($f);
Branch: 1 branch
BranchTrueFalseTotal
if apply_fragment($f) 3 170 173
1288 }
1289  
1290 100 ▶ return if not $need_root or $flags{'no-root'};
Branch: 1 branch
BranchTrueFalseTotal
if not $need_root or $flags{"no-root"} 100 0 100
Condition66%2/3
not $need_root or $flags{"no-root"}
l!l&&r!l&&!r
9730
MC/DC0%0/2
not $need_root or $flags{"no-root"}
not $need_root $flags{"no-root"}
Truth table66%2/3
not(A) or B
A= not $need_rootB= $flags{"no-root"}
ABresult
1X1
011
000
1291 0 ▶ if ($0 eq '-') {
Branch: 1 branch
BranchTrueFalseTotal
if ($0 eq "-") 0 0 0
1292 0 ▶ print "Skipping NEED_ROOT fragments for an execution from stdin\n" unless $flags{silent};
Branch: 1 branch
BranchTrueFalseTotal
unless $flags{"silent"} 0 0 0
1293 0 return;
1294 }
1295 0 my $script = catfile(${FindBin::RealBin}, ${FindBin::RealScript});
1296 0 system('sudo', $script, @orig_argv, '--root');
1297 0 return;
1298 }
1299  
1300 154 main();
1301  
1302 =pod
1303  
1304 =encoding utf8
1305  
1306 =head1 NAME
1307  
1308 update_config - Deploy configuration fragments (dotfiles, etc.) locally or on
1309 remote hosts.
1310  
1311 =head1 SYNOPSIS
1312  
1313 update_config [--test] [--help] [--diff] [--silent] [--list] [--dir directory]
1314 [--root|--no-root] [--force] [--export] [--pack]
1315  
1316 =head1 DESCRIPTION
1317  
1318 The program reads configuration fragments from the F<~/.update_config>
1319 directory if it exists. Otherwise, it reads them from the
1320 F<$XDG_CONFIG_HOME/update_config> directory (F<~/.config/update_config> when
1321 C<XDG_CONFIG_HOME> is not set). In both cases, all the subdirectories are read
1322 too, as well as the fragments embedded in the script itself by the C<--pack>
1323 option. A directory can also contain a F<.update_config> file, with directives
1324 that apply to all its fragments (see L</Directory directives>). A fragment
1325 from the directory replaces an embedded fragment with the same name.
1326  
1327 The non-core modules used by the program are installed automatically when
1328 they are missing (some of them only when they are first needed), with
1329 C<cpanm> if it is available, or C<cpan> otherwise. If the program is installed
1330 in the directories of the Perl installation (e.g. with C<sudo cpanm>), the
1331 modules are installed there too, using C<sudo> if needed. Otherwise, they are
1332 installed with L<local::lib> if that module is available, or system-wide (using
1333 C<sudo> if needed).
1334  
1335 =head1 OPTIONS
1336  
1337 The available options for the program are the following. They can all be
1338 abbreviated down to a single character.
1339  
1340 --diff Print the difference between the current configuration and what
1341 will be written
1342  
1343 --silent Do not print the status of the configuration files (except for
1344 error messages).
1345  
1346 --test Do not modify the configuration files.
1347  
1348 --list Only print a list of the configuration files and exit.
1349  
1350 --root Install only the configuration fragments that are marked as
1351 'NEED ROOT'.
1352  
1353 --no-root Do not attempt to install the 'NEED ROOT' fragments.
1354  
1355 --force Overwrite the targets of the 'ENTIRE FILE' fragments even if they
1356 were modified since they were last written by the program, and
1357 the files that are not symbolic links at the targets of the
1358 'SYMLINK' fragments. These targets are then reported as
1359 "Updated: target (forced)".
1360  
1361 --export Export in the current directory all the files that are embedded
1362 in the script, with their target and the directives that they
1363 inherit from their directories written explicitly.
1364  
1365 --dir directory Process only the configuration files in the given
1366 directory and its subdirectories, instead of those from the
1367 default path.
1368  
1369 --pack Write on the standard output a version of the script where all the
1370 config fragments are embedded. To be used typically with:
1371 update_config --pack | ssh user@host perl -- - --no-root
1372 or just
1373 update_config --pack | ssh host perl
1374  
1375 --help Print this help message.
1376  
1377 =head1 FRAGMENT FILES
1378  
1379 Each fragment file describes a piece of content that should be present in a
1380 target file. By default, the target is a file directly in your home directory,
1381 with the same name as the fragment. However, hidden files are ignored when the
1382 fragments are read, so a C<dot_> prefix in the name of a fragment is replaced
1383 by a dot in its target (e.g. F<dot_bashrc> targets F<.bashrc>). The target can
1384 also be set explicitly with the C<FILENAME> directive described below.
1385  
1386 You can organize the fragments in sub-directories, but these are not part of
1387 the target path: only the base name of a fragment is used as its default
1388 target (unless the C<MIRROR> directive is used). A suffix between brackets in
1389 that name is not part of the target but it is the default guard suffix of the fragment (e.g. F<bashrc [linux]> and
1390 F<bashrc [macos]> both target F<.bashrc>, with the C<LINUX> and C<MACOS> guard
1391 suffixes, which are always in upper case). Several fragments can be applied to the same file only if they have
1392 different guard suffixes (see the C<GUARD SUFFIX> directive), if they all
1393 use C<MERGE>, or if all but one use C<APPEND>, otherwise the program fails
1394 without applying any fragment.
1395  
1396 Similarly, a suffix between brackets at the end of the name of a directory
1397 (e.g. F<[linux]> or F<work [linux]>) is the default guard suffix of all the
1398 fragments that it contains, including in its sub-directories. When several of
1399 these suffixes apply to a fragment (from its directories or its own name),
1400 they are joined with C<->, from the outermost one (e.g. the default guard
1401 suffix of F<[linux]/shell [work]/bashrc [prompt]> is C<LINUX-WORK-PROMPT>). Hidden
1402 directories are ignored too and fragments are processed in alphabetical order
1403 of their base name, ignoring case.
1404  
1405 Unless the C<MERGE> directive is used (see L</Merged files>), the content of the
1406 fragment is written in the target file between two guard lines, which look
1407 like C<###AUTO-CONFIG START###> and C<###AUTO-CONFIG END###>. Everything outside of these guards is left untouched, so you can still edit the
1408 rest of the file by hand. If the guards are not already present, the content is
1409 added at the end of the file, which is created if needed. When the guarded
1410 content is already up to date, the file is not modified at all.
1411  
1412 =head2 Directives
1413  
1414 A fragment can start with a few directives, one per line, that control how it
1415 is applied. The content of the fragment starts at the first line that is not a
1416 directive, and the empty lines following the directives are skipped. The
1417 supported directives are the following:
1418  
1419 =over 4
1420  
1421 =item C<FILENAME> I<path>
1422  
1423 Sets the target file, instead of using the name of the fragment. The path is
1424 relative to the directory given by C<DIR> or C<MIRROR> if any, itself relative
1425 to the base directory (your home directory, unless C<BASE> is used). An
1426 absolute path, or a path starting with C<~/> (relative to your home
1427 directory), ignores these directories. The path can
1428 also be made of two commands separated by a comma. In that case, the current
1429 content is read from the output of the first command and the new content is
1430 passed on the input of the second one (this is useful for C<crontab -l,
1431 crontab ->).
1432  
1433 =item C<DIR> I<path>
1434  
1435 Sets the directory of the target file, which keeps the name of the fragment
1436 (or the one given by C<FILENAME>, which must then be a relative path). The
1437 path is relative to the base directory (your home directory, unless C<BASE> is
1438 used), unless it is an absolute path or it starts with C<~> (for your home
1439 directory). This directive cannot be used when the target is made of two
1440 commands, nor with C<MIRROR>.
1441  
1442 =item C<BASE> I<path>
1443  
1444 Sets the base directory of the target, which is your home directory by
1445 default: the C<DIR> and C<FILENAME> paths and the directories given by
1446 C<MIRROR> are relative to it. A relative path is relative to the previous base
1447 directory, which is the one set by a C<BASE> directive in a parent directory
1448 (see L</Directory directives>), if any, or your home directory otherwise. The
1449 path can also be absolute, or start with C<~> for a path relative to your home
1450 directory.
1451  
1452 =item C<MIRROR>
1453  
1454 Uses the structure of the configuration directory for the target, which is
1455 mostly useful in a F<.update_config> file (see L</Directory directives>): the
1456 directory of the target is the path of the directory of the fragment, starting
1457 with the directory where C<MIRROR> is set (the one containing the
1458 F<.update_config> file, or the fragment itself), relative to the base directory
1459 (see C<BASE>). For example, with C<MIRROR> in F<dot_config/.update_config>, the
1460 fragment F<dot_config/fish/config.fish> targets F<~/.config/fish/config.fish>.
1461 The root of the configuration directory is never part of the mirrored path. As
1462 for the name of the fragment, the suffixes between brackets are removed from
1463 the names of the mirrored directories (a directory whose name is only such a
1464 suffix can't be mirrored) and a C<dot_> prefix is replaced by a dot (e.g.
1465 F<dot_config/app [work]/dot_rc> targets F<.config/app/.rc>). A C<DIR>
1466 directive set deeper than C<MIRROR> replaces the mirrored path (and the
1467 reverse), and C<FILENAME> replaces the name of the fragment.
1468  
1469 =item C<MIRROR CONTENTS>
1470  
1471 Like C<MIRROR>, but the directory where the directive is set is not part of the
1472 mirrored path, only the directories below it are (e.g. with C<MIRROR CONTENTS>
1473 in F<config/.update_config>, the fragment F<config/fish/config.fish> targets
1474 F<~/fish/config.fish>). The deepest of C<MIRROR> and C<MIRROR CONTENTS> wins.
1475  
1476 =item C<COMMENTS CHAR> I<char>
1477  
1478 Sets the character that starts a comment in the target file, which is used in
1479 the guard lines (it is repeated three times). The default is C<#>.
1480  
1481 =item C<GUARD SUFFIX> I<suffix>
1482  
1483 Adds a suffix to the guard lines, which then look like
1484 C<###AUTO-CONFIG:SUFFIX START###>. You need this if several fragments target
1485 the same file. By default, the suffixes between brackets at the end of the name
1486 of the fragment and of its directories are used, if any (see above). The suffix
1487 is always converted to upper case, whether it comes from this directive or from
1488 the names of the files. With C<MERGE>, there are no guard lines and the suffix
1489 is ignored.
1490  
1491 =item C<IS PREFIX>
1492  
1493 Adds the content at the beginning of the file instead of at the end, when the
1494 guards are not already present.
1495  
1496 =item C<ENTIRE FILE>
1497  
1498 Replaces the entire target file with the content of the fragment, without any
1499 guard lines. The last applied version of the fragment is saved (see
1500 L</Merged files>) and, if the target was modified since then, it is not
1501 overwritten: the program prints the modifications that would be lost, skips
1502 the fragment and continues with the other ones. The C<--force> option
1503 overwrites the target anyway, and reports it as C<Updated: target (forced)>. A
1504 target that does not exist is always written.
1505  
1506 =item C<APPEND>
1507  
1508 Appends the content of the fragment to the content of the C<ENTIRE FILE>
1509 fragment that has the same target, instead of applying it separately (e.g.
1510 F<AGENTS.md> with C<ENTIRE FILE>, and F<AGENTS.md [work]> with C<APPEND> and a
1511 C<REQUIRE> guard). Any number of C<APPEND> fragments can target the same file,
1512 in which case they are appended in the order in which the fragments are
1513 processed (see above), whatever their guard suffixes. The content of each
1514 fragment is separated from the previous one by an empty line (the fragments
1515 with no content are ignored). The program fails without
1516 applying any fragment if there is no C<ENTIRE FILE> fragment applied to the
1517 target (e.g. because of its C<REQUIRE> guards). This directive can be set in a
1518 F<.update_config> file for all the fragments of a directory. It cannot be used
1519 with C<COMMENTS CHAR>, C<ENTIRE FILE>, C<IS PREFIX>, C<MAKE EXECUTABLE>,
1520 C<MERGE>, C<MERGE ARRAYS>, C<NEED ROOT>, C<PERM> or C<POST UPDATE> (the
1521 directives of the C<ENTIRE FILE> fragment apply to the whole file, these
1522 directives are ignored when they are set in a parent directory of the one
1523 setting C<APPEND>).
1524  
1525 =item C<MAKE EXECUTABLE>
1526  
1527 Makes the target file executable.
1528  
1529 =item C<MERGE> [I<format>]
1530  
1531 Merges the data of the fragment into the target file instead of using guard
1532 lines, see L</Merged files> below. The format is one of C<json>, C<toml>,
1533 C<yaml> or C<ini> (case insensitive). Without a format, it is given by the
1534 extension of the target, which must be the last part of its name, ignoring
1535 the suffix between brackets (e.g. a fragment named F<config.toml [work]> is
1536 merged as C<toml>). The C<yml> extension is recognized too. This directive cannot be used with C<COMMENTS CHAR>,
1537 C<ENTIRE FILE> or C<IS PREFIX>.
1538  
1539 =item C<MERGE ARRAYS> I<mode>
1540  
1541 With C<MERGE>, sets how the arrays without an explicit mode are merged (see
1542 L</Merged files>): C<union> or C<replace> for all of them, or C<auto> (the
1543 default) to use C<replace> for the arrays that contain only scalars and
1544 C<union> for the others.
1545  
1546 =item C<SYMLINK> I<destination>
1547  
1548 Makes the target a symbolic link to the given destination, instead of writing
1549 the content of the fragment, which must be empty. A destination starting with
1550 C<~> is relative to your home directory, other relative destinations are
1551 relative to the directory of the link (as with C<ln -s>). An existing symbolic
1552 link at the target is replaced. Other files are not overwritten (the fragment
1553 is skipped, the program continues with the other ones), unless the C<--force>
1554 option is used. A directory is never replaced. The target can't be made of
1555 commands, and this directive can't be used in a F<.update_config> file, nor
1556 with C<APPEND>, C<COMMENTS CHAR>, C<ENTIRE FILE>, C<IS PREFIX>, C<MAKE EXECUTABLE>,
1557 C<MERGE>, C<MERGE ARRAYS> or C<PERM> (these directives are ignored when they
1558 are set in a parent directory).
1559  
1560 =item C<PERM> I<mode>
1561  
1562 Sets the permissions of the target file, given in octal (e.g. C<600>).
1563  
1564 =item C<NEED ROOT>
1565  
1566 Marks a fragment that must be written as root (typically a file under
1567 F</etc>). These fragments are applied at the end of the run, by executing the
1568 program again through C<sudo> with the C<--root> option.
1569  
1570 =item C<REQUIRE> I<expression> [C<#> I<reason>]
1571  
1572 Evaluates a Perl expression and skips the fragment if it is false. The optional
1573 reason is printed when the fragment is skipped. The expression can use the
1574 C<which> function from L<File::Which> as well as the variables from
1575 L<English>. This directive can be repeated, in which case all the expressions
1576 must be true.
1577  
1578 =item C<POST UPDATE> I<command>
1579  
1580 Executes a shell command after the target file has been updated. In the
1581 command, C<$@> is replaced by the path of the target file.
1582  
1583 =item C<REM> I<text>
1584  
1585 A comment, which is ignored.
1586  
1587 =back
1588  
1589 =head2 Directory directives
1590  
1591 A directory of fragments can contain a F<.update_config> file, with directives
1592 (and C<REM> comments) on each line, possibly separated by empty lines, but no
1593 content. These directives apply to all the fragments of the directory,
1594 including those in its sub-directories. If several of these files apply to a
1595 fragment (from its directory and its parent directories), their directives
1596 are combined, starting with the outermost directory and ending with the
1597 directives of the fragment itself:
1598  
1599 =over 4
1600  
1601 =item *
1602  
1603 The C<REQUIRE> directives are all evaluated, the fragment is skipped if any of
1604 them is false.
1605  
1606 =item *
1607  
1608 For the other directives, the value from the deepest file wins (so the
1609 directives of a fragment override those of its directories). Note that a
1610 directive without a value (e.g. C<ENTIRE FILE>) cannot be disabled once it is
1611 set in a directory.
1612  
1613 =item *
1614  
1615 A C<GUARD SUFFIX> directive in a F<.update_config> file replaces the suffixes
1616 between brackets of the names of its directory and of the directories above
1617 it, but the suffixes of the directories below it and of the fragment
1618 itself are still added after it (e.g. with a F<.update_config> file containing
1619 C<GUARD SUFFIX work> in F<dir [d]>, the guard suffix of F<dir [d]/sub [s]/file>
1620 is C<WORK-S>). A C<GUARD SUFFIX> directive in a fragment replaces all of these
1621 suffixes.
1622  
1623 =item *
1624  
1625 A C<COMMENTS CHAR> directive is ignored by the fragments using C<MERGE> when
1626 it is set in a parent directory of the one setting C<MERGE> (otherwise, they
1627 cannot be used together). Similarly, C<MERGE ARRAYS> can be set in a
1628 F<.update_config> file without C<MERGE>, it then only applies to the fragments
1629 that use C<MERGE>.
1630  
1631 =item *
1632  
1633 The C<BASE> directives are all applied, each relative to the previous one.
1634  
1635 =item *
1636  
1637 An absolute C<FILENAME> (or a pair of commands, or a path starting with C<~/>)
1638 ignores the C<BASE>, C<DIR>, C<MIRROR> and C<MIRROR CONTENTS> directives set
1639 in a parent directory.
1640  
1641 =back
1642  
1643 A C<FILENAME> directive in a F<.update_config> file sends all the fragments of
1644 the directory to the same target, which requires them to have different guard
1645 suffixes (e.g. from their names, like F<path [path]> and F<editor [editor]>).
1646  
1647 For example, with a F<dot_config/.update_config> file containing:
1648  
1649 MIRROR
1650  
1651 the fragment F<dot_config/fish/config.fish> targets
1652 F<~/.config/fish/config.fish>, F<dot_config/git [work]/config> targets
1653 F<~/.config/git/config> (with the C<WORK> guard suffix) and
1654 F<dot_config/app/settings.json> containing C<DIR .config/other> targets
1655 F<~/.config/other/settings.json>. The same targets are obtained with a
1656 F<config/.update_config> file containing:
1657  
1658 BASE .config
1659 MIRROR CONTENTS
1660  
1661 and C<DIR other> in F<config/app/settings.json>.
1662  
1663 =head2 Merged files
1664  
1665 Some programs rewrite their own configuration file (re-ordering its entries,
1666 removing its comments, etc.), which would break the guard lines. For these
1667 files, the C<MERGE> directive merges the data of the fragment, written in the
1668 same format as the target file, into the existing data of that file:
1669  
1670 =over 4
1671  
1672 =item *
1673  
1674 Maps (TOML tables, JSON objects, YAML mappings or INI sections), starting with
1675 the root of the file, are merged recursively: each key of the fragment is
1676 added to the existing map. For other values, the value from the fragment
1677 replaces the existing one.
1678  
1679 =item *
1680  
1681 Arrays are merged according to their mode, which is given by an
1682 C<update_config_arrays> map placed next to them in the fragment (that is, in
1683 the map containing the arrays). Each key of that map is the name of an array
1684 and its value is one of:
1685  
1686 =over 4
1687  
1688 =item C<replace>
1689  
1690 The array from the fragment replaces the existing one.
1691  
1692 =item C<union>
1693  
1694 The elements of the fragment (which can be whole maps, e.g. TOML C<[[array]]>
1695 entries) are appended to the existing array, unless an equal element is
1696 already present.
1697  
1698 =item C<key:>I<field>[C<,>I<field>...]
1699  
1700 For arrays of maps, the entries of the fragment are matched with the existing
1701 entries having the same value for all the given fields. A matching entry is
1702 merged like any other map (so values added there by the program are kept) and
1703 the entries without a match are appended.
1704  
1705 =back
1706  
1707 The C<update_config_arrays> maps are not written in the target file. The
1708 arrays not listed in such a map use the mode given by the C<MERGE ARRAYS>
1709 directive (by default, C<replace> for arrays of scalars and C<union> for the
1710 others).
1711  
1712 =item *
1713  
1714 The target file is entirely rewritten, with sorted keys and without its
1715 comments. But it is not modified at all if it already contains the data of the
1716 fragment, whatever its formatting.
1717  
1718 =item *
1719  
1720 The last applied version of each fragment (for each target) is saved in
1721 F<$XDG_STATE_HOME/update_config> (F<~/.local/state/update_config> by
1722 default), or in F</var/lib/update_config> for the C<NEED ROOT> fragments
1723 (this can be overridden with the C<UPDATE_CONFIG_ROOT_STATE_DIR> environment
1724 variable). On the next run, the values that were removed from the fragment are
1725 also removed from the target file, unless they were modified there. This also
1726 applies to the elements of arrays merged with C<union>, and to the values of
1727 the entries of arrays merged with a C<key> (such an entry is removed entirely
1728 if only its key fields remain). This is a best effort mechanism that does not
1729 cover the changes made before the state was saved, nor the fragments that were
1730 renamed or moved to another directory since then.
1731  
1732 =back
1733  
1734 The C<ini> format supports C<key = value> lines, optionally in C<[section]>
1735 blocks, and comment lines starting with C<;> or C<#>. The values are kept as
1736 raw text. The C<json> format accepts trailing commas and C<#> comments but not
1737 C<//> comments.
1738  
1739 =head2 Examples
1740  
1741 This fragment adds some content to your F<~/.bashrc> file, but only on WSL
1742 hosts. The guard suffix allows to have another fragment for the same file:
1743  
1744 FILENAME .bashrc
1745 GUARD SUFFIX WSL
1746 REQUIRE `uname -r` =~ /WSL/ # Not a WSL host
1747  
1748 export BROWSER=wslview
1749  
1750 This one installs a full script in a system directory, and needs root to do so:
1751  
1752 FILENAME /etc/network/if-pre-up.d/10-iptables-load
1753 REQUIRE -d '/etc/network/if-pre-up.d' # No if-pre-up.d directory
1754 NEED ROOT
1755 ENTIRE FILE
1756 MAKE EXECUTABLE
1757  
1758 #!/bin/sh
1759 iptables-restore < /etc/iptables.rules
1760  
1761 And this one updates a configuration file and then reloads it in the running
1762 program:
1763  
1764 FILENAME .tmux.conf
1765 REQUIRE which('tmux') # tmux is not installed
1766 POST UPDATE tmux source-file $@
1767  
1768 set -g prefix C-a
1769  
1770 The following fragments use the C<MERGE> directive, for files that are
1771 rewritten by their program. This one sets a theme and adds a server to a TOML
1772 file, while keeping the other servers configured there (by default, the
1773 C<[[server]]> entries are merged with C<union>):
1774  
1775 FILENAME .config/app/config.toml
1776 MERGE toml
1777  
1778 [ui]
1779 theme = "dark"
1780  
1781 [[server]]
1782 name = "home"
1783 url = "https://home.example.com"
1784  
1785 This one configures some languages in the Helix editor. The entries of the
1786 C<language> array are matched by their C<name>: if a C<rust> entry already
1787 exists, its C<indent> is updated and its other values are kept. The marker for
1788 an array at the root of the file must be placed before any table header:
1789  
1790 FILENAME .config/helix/languages.toml
1791 MERGE toml
1792  
1793 update_config_arrays = { language = "key:name" }
1794  
1795 [[language]]
1796 name = "rust"
1797 indent = { tab-width = 4, unit = " " }
1798  
1799 [[language]]
1800 name = "python"
1801 auto-format = true
1802  
1803 This one adds a key binding to Alacritty, where the bindings are identified by
1804 both their C<key> and C<mods> fields. As the C<bindings> array is in the
1805 C<keyboard> table, the marker is placed in that table:
1806  
1807 FILENAME .config/alacritty/alacritty.toml
1808 MERGE toml
1809  
1810 [keyboard]
1811 update_config_arrays = { bindings = "key:key,mods" }
1812  
1813 [[keyboard.bindings]]
1814 key = "N"
1815 mods = "Control|Shift"
1816 action = "CreateNewWindow"
1817  
1818 And this one adds a list of excluded paths in a JSON file, without removing the
1819 ones that were already present (the array contains only scalars, so it would
1820 be replaced by default):
1821  
1822 FILENAME .config/app/settings.json
1823 MERGE json
1824  
1825 {
1826 "update_config_arrays": {"exclude": "union"},
1827 "exclude": ["node_modules", ".cache"]
1828 }
1829  
1830 =cut
1831  
1832 __DATA__
↑ Summary /usr/local/bin/perldoc »