Template/Utils.pm untested

filter: Statementstmt 0.0% 0 / 308 Branchbran 0.0% 0 / 92 Conditioncond 0.0% 0 / 54 MC/DCmcdc 0.0% 0 / 33 Subroutinesub 0.0% 0 / 43 Podpod 0.0% 0 / 24 totaltotal 0.0% 0 / 554 CC 47 SCAR 29.2
CC
47
Cov
0%
find_root_dir
56.0
filter_list
42.0
slurp_file
42.0
CRAP 18.6
1 package Autoconf::Template::Utils;
2  
3 use strict;
4 use warnings;
5  
6 use Autoconf::Template::Constants qw(:all);
7 use Carp;
8 use English qw(-no_match_vars);
9 use Data::Dumper;
10 use Date::Format qw(time2str);
11 use File::Basename qw(fileparse basename dirname);
12 use File::Path qw(make_path);
13 use File::Find;
14 use File::ShareDir qw(dist_dir);
15 use List::Util qw(any none pairs);
16 use Scalar::Util qw(reftype);
17 use Log::Log4perl qw(:easy);
18 use Log::Log4perl::Level;
19 use JSON;
20 use Template;
21 use YAML qw(Load LoadFile DumpFile);
22  
23 use parent qw(Exporter);
24  
25 our @EXPORT_OK = qw(
26 create_path
27 expand_filename
28 filter_list
29 find_files
30 find_files_of_type
31 find_module_filename
32 find_root_dir
33 flatten_filename
34 get_project_meta_data
35 get_subdirs
36 get_subdir_by_type
37 init_logger
38 is_exclude_dir
39 message
40 module_to_path
41 path_to_module
42 render_tt_template
43 save_project_meta_data
44 slurp_file
45 strip_in
46 timestamp
47 to_boolean
48 version
49 );
50  
51 our %EXPORT_TAGS = ( all => [@EXPORT_OK] );
52  
53 our %LOG4PERL_LEVELS = (
54 trace => $TRACE,
55 debug => $DEBUG,
56 info => $INFO,
57 warn => $WARN,
58 error => $ERROR,
59 );
60  
61 ########################################################################
62 sub version {
63 ########################################################################
64 my ($version) = @_;
65  
66 print basename($PROGRAM_NAME) . " v$version\n\n";
67 print $COPYRIGHT;
68  
69 return;
70 }
71  
72 ########################################################################
73 sub get_subdir_by_type {
74 ########################################################################
75 my ($file) = @_;
76  
77 $file =~ s/[.]in$//xsm;
78  
79 my ( $name, $path, $ext ) = fileparse( $file, qr/[.][^.]+$/xsm );
80  
81 return ( $SUBDIRS_BY_TYPE{$ext}, $ext );
82 }
83  
84 ########################################################################
85 sub remove_empty_dirs {
86 ########################################################################
87 my ($dirs) = @_;
88  
89 my @empty;
90  
91 $dirs //= {};
92  
93 foreach my $p ( pairs %{$dirs} ) {
94 my ( $path, $files ) = @{$p};
95 next if @{$files};
96  
97 if ( none { $path ne $_ && $_ =~ /^$path/xsm } keys %{$dirs} ) {
98 push @empty, $path;
99 }
100 }
101  
102 foreach (@empty) {
103 delete $dirs->{$_};
104 }
105  
106 return $dirs;
107 }
108  
109 ########################################################################
110 sub get_subdirs {
111 ########################################################################
112 my ( $path, $dirs ) = @_;
113  
114 $dirs //= {};
115  
116 opendir my $fh, "$path"
117 or croak "could not open directory: $OS_ERROR";
118  
119 while ( my $file = readdir $fh ) {
120  
121 next if $file =~ /^[t.][.]?$/xsm;
122  
123 if ( -d "$path/$file" ) {
124 $dirs->{"$path/$file"} = [];
125 $dirs = get_subdirs( "$path/$file", $dirs );
126 }
127 else {
128 if ( $file =~ /[.]pm[.]in$/xsm ) {
129 push @{ $dirs->{$path} }, $file;
130 }
131 }
132 }
133  
134 closedir $fh;
135  
136 return remove_empty_dirs($dirs);
137 }
138  
139 ########################################################################
140 sub filter_list {
141 ########################################################################
142 my ( $files, $srcdir, @filter ) = @_;
143  
144 TRACE Dumper( [ files => $files, filter => \@filter ] );
145  
146 my @filtered_list;
147  
148 foreach my $file ( @{$files} ) {
149  
150 my $dirname = dirname $file;
151 TRACE Dumper( [ dirname => $dirname, file => $file ] );
152  
153 $dirname = $dirname eq $DOT ? $EMPTY : "$dirname/";
154  
155 my $exclude;
156  
157 foreach my $f (@filter) {
158  
159 my $pattern = $f;
160  
161 if ( ref $pattern && reftype($pattern) eq 'REGEXP' ) {
162 TRACE Dumper( [ file => $file, regexp => $pattern ] );
163  
164 if ( $file =~ $pattern ) {
165 $exclude = $TRUE;
166 TRACE Dumper( [ excluding => $file ] );
167 last;
168 }
169 }
170 else {
171 TRACE Dumper( [ file => $file, pattern => $pattern ] );
172  
173 if ( $file eq $pattern ) {
174 TRACE Dumper( [ excluding => $file ] );
175  
176 $exclude = $TRUE;
177 last;
178 }
179 }
180  
181 }
182  
183 next if $exclude;
184  
185 push @filtered_list, $file;
186 }
187  
188 return @filtered_list;
189 }
190  
191 ########################################################################
192 sub flatten_filename {
193 ########################################################################
194 my ( $filename, $sep ) = @_;
195  
196 $sep //= $DASH;
197  
198 my $name;
199  
200 if ( $filename =~ /[.]pm/xsm ) {
201 $name = path_to_module($filename);
202 $name =~ s/::/$sep/gxsm;
203 }
204 else {
205 $name = basename $filename;
206 $name =~ s/[.].*$//xsm;
207 }
208  
209 return lc $name;
210 }
211  
212 ########################################################################
213 sub expand_filename {
214 ########################################################################
215 my ($file) = @_;
216  
217 if ( $file =~ /^[~]/xsm ) {
218 croak "no \$HOME environment variable set\n"
219 if !$ENV{HOME};
220  
221 $file =~ s/~/$ENV{HOME}/xsm;
222 }
223  
224 return $file;
225 }
226  
227 ########################################################################
228 sub strip_in {
229 ########################################################################
230 my ($arg) = @_;
231  
232 if ( ref $arg ) {
233 for ( @{$arg} ) {
234 s/[.]in$//xsm;
235 }
236 }
237 else {
238 $arg =~ s/[.]in$//xsm;
239 }
240  
241 TRACE Dumper( 'strip_in', $arg );
242  
243 return $arg;
244 }
245  
246 ########################################################################
247 sub find_files {
248 ########################################################################
249 my ( $path, $type, $strip_in ) = @_;
250 $type //= 'pm';
251  
252 return find_files_of_type(
253 path => $path,
254 type => $type,
255 ext => '.in',
256 strip => $strip_in
257 );
258 }
259  
260 ########################################################################
261 sub is_exclude_dir {
262 ########################################################################
263 my ( $name, $exclude_dirs ) = @_;
264  
265 foreach my $dir ( @{$exclude_dirs} ) {
266 if ( !ref $dir ) {
267 $dir = qr/^$dir/xsm;
268 }
269  
270 DEBUG Dumper(
271 [ reftype => reftype($dir),
272 dir => $dir,
273 name => $File::Find::name
274 ]
275 );
276  
277 return $TRUE
278 if $File::Find::name =~ $dir;
279 }
280  
281 return $FALSE;
282 }
283  
284 ########################################################################
285 sub find_files_of_type {
286 ########################################################################
287 my (%args) = @_;
288  
289 my ( $path, $type, $ext, $strip_in, $exclude_dirs )
290 = @args{qw(path type ext strip exclude_dirs)};
291  
292 return ()
293 if !-d $path;
294  
295 $ext //= $EMPTY;
296  
297 my @files;
298  
299 TRACE sprintf 'looking for files of type %s in %s', $type, $path;
300  
301 find(
302 sub {
303 return
304 if -d $_ || !/[.]$type$ext$/xsm;
305  
306 return
307 if is_exclude_dir( $File::Find::name, $exclude_dirs );
308  
309 my $name = $File::Find::name;
310  
311 if ($strip_in) {
312 $name = strip_in($name);
313 }
314  
315 push @files, $name;
316 },
317 $path
318 );
319  
320 TRACE 'found files: ', join "\n", @files;
321  
322 return @files;
323 }
324  
325 ########################################################################
326 sub path_to_module {
327 ########################################################################
328 my ($path) = @_;
329  
330 my $module = $path;
331  
332 $module =~ s/\//::/gxsm;
333 $module =~ s/[.]pm.*$//xsm;
334  
335 return $module;
336 }
337  
338 ########################################################################
339 sub module_to_path {
340 ########################################################################
341 my ($module) = @_;
342  
343 $module =~ s/::/\//gxsm;
344  
345 return "$module.pm";
346 }
347  
348 ########################################################################
349 sub timestamp {
350 ########################################################################
351 my @now = localtime;
352 $now[5] += 1900;
353 $now[4] += 1;
354  
355 my %timestamp;
356  
357 $timestamp{date} = {
358 year => $now[5],
359 month => $now[4],
360 day => $now[3],
361 };
362  
363 # Fri Feb 10 14:16:12 2023
364 $timestamp{timestamp} = time2str( '%a %b %e %H:%M:%S %Y', time );
365  
366 return %timestamp;
367 }
368  
369 # give an fqp to a Perl module, we just want the portion of the path
370 # that reflects the package name...so if Foo::Bar is found at
371 # '/tmp/foo/Foo/Bar.pm' we return: 'Foo/Bar.pm'
372 ########################################################################
373 sub find_module_filename {
374 ########################################################################
375 my ($file) = @_;
376  
377 # if file does not exist it should be listed in manifest as something
378 # like: Foo/Bar.pm but we'll create it later
379 return $file
380 if !-e $file;
381  
382 my $module = slurp_file($file);
383  
384 if ( $module =~ /package\s+([^;]+)/xsm ) {
385 return module_to_path($1);
386 }
387  
388 return;
389 }
390  
391 ########################################################################
392 sub slurp_file {
393 ########################################################################
394 my ( $file, %options ) = @_;
395  
396 my $type = lc( $options{type} // $EMPTY );
397  
398 if ( any { $type eq $_ } qw(json yaml dmp) ) {
399 $options{comments} = $FALSE;
400 }
401  
402 $options{comments} //= $TRUE; # leave comments
403  
404 local $RS = undef;
405  
406 open my $fh, '<', $file
407 or croak "could not open $file";
408  
409 my $content = <$fh>;
410  
411 close $fh;
412  
413 if ( !$options{comments} ) {
414 while ( $content =~ s/^[\#][^\n]*$//gxsm ) { }
415 }
416  
417 return decode_json($content)
418 if $type eq 'json';
419  
420 return Load($content)
421 if $type eq 'yaml';
422  
423 return eval "$content" ## no critic (ProhibitStringyEval)
424 if $type eq 'dmp';
425  
426 return $content;
427 }
428  
429 ########################################################################
430 sub render_tt_template {
431 ########################################################################
432 my (@in) = @_;
433  
434 my %args;
435  
436 if ( ref $in[0] && reftype( $in[0] ) eq 'HASH' ) {
437 %args = %{ $in[0] };
438 }
439 else {
440 @args{qw(template parameters outfile)} = @in;
441 }
442  
443 my ( $template, $parameters, $outfile )
444 = @args{qw( template parameters outfile)};
445  
446 my @cleanup = @{ $args{cleanup} || [] };
447  
448 TRACE Dumper(
449 [ 'rendering template:' => $template,
450 'to outfile:' => $outfile,
451 'cleanup:' => $args{cleanup},
452 'parameters:' => $parameters,
453 'INCLUDE_PATH:' => Dumper( [$INCLUDE_PATH] ),
454 ]
455 );
456  
457 my $tt = Template->new(
458 { INCLUDE_PATH => [ $INCLUDE_PATH, dist_dir('Autoconf-Template') ],
459 ABSOLUTE => $TRUE,
460 INTERPOLATE => $FALSE,
461 FILTERS => {
462 to_am_var => sub {
463 my $text = shift;
464 $text =~ s/\//_/xmsg;
465 return $text;
466 }
467 },
468  
469 }
470 );
471  
472 my $content = $EMPTY;
473  
474 croak sprintf "error rendering template: %s\n", $tt->error()
475 if !$tt->process( $template, $parameters, \$content );
476  
477 if ( any { $_ eq 'nl' } @cleanup ) {
478 TRACE 'cleaning up multiple new lines...';
479  
480 while ( $content =~ s/\n\n\n/\n/xsmg ) { }
481 }
482  
483 if ($outfile) {
484  
485 create_path($outfile);
486  
487 open my $fh, '>', $outfile
488 or croak sprintf 'could not open [%s] for writing: %s', $outfile,
489 $OS_ERROR;
490  
491 print {$fh} $content;
492  
493 close $fh;
494 }
495  
496 return $content;
497 }
498  
499 {
500 my $meta_data;
501  
502 ########################################################################
503 sub get_project_meta_data {
504 ########################################################################
505 my ($options) = @_;
506  
507 return %{$meta_data}
508 if $meta_data;
509  
510 my ( $project, $destdir ) = find_root_dir($options);
511  
512 my $meta_data_file;
513  
514 if ( $destdir && $project ) {
515 $meta_data_file = sprintf '%s/%s/project.yaml', $destdir, $project;
516 }
517 elsif ( $options->{'project-root'} ) {
518 $meta_data_file = sprintf '%s/project.yaml', $options->{'project-root'};
519 }
520  
521 $meta_data = eval { return LoadFile($meta_data_file) };
522  
523 return %{ $meta_data || {} };
524 }
525 }
526  
527 ########################################################################
528 sub to_boolean {
529 ########################################################################
530 my ($val) = @_;
531  
532 $val //= $EMPTY;
533  
534 return ( any { $val eq $_ } qw(true 1 on yes) ) ? $TRUE : $FALSE;
535 }
536  
537 ########################################################################
538 sub save_project_meta_data {
539 ########################################################################
540 my ( $options, $meta_data ) = @_;
541  
542 $meta_data->{updated_date} = scalar localtime;
543  
544 foreach ( keys %BOOLEAN_OPTIONS ) {
545 $meta_data->{$_} = to_boolean( $meta_data->{$_} ) ? 'true' : 'false';
546 }
547  
548 DumpFile( sprintf( '%s/project.yaml', $options->{root} ), $meta_data );
549  
550 return;
551 }
552  
553 ########################################################################
554 sub find_root_dir {
555 ########################################################################
556 my ($options) = @_;
557  
558 my ( $project, $destdir );
559  
560 # see if we can figure out what project we are in...
561 if ( $options->{'project-root'} ) {
562 my %meta_data = get_project_meta_data($options);
563  
564 if ( keys %meta_data ) {
565 $project = $meta_data{project};
566 $destdir = dirname $options->{'project-root'};
567 }
568 }
569 elsif ( -e 'Makefile' ) {
570 # PACKAGE_NAME is the project name, so if you are anywhere in the
571 # build tree and have a 'Makefile' there I can probably find
572 # the project name...
573 my $makefile = slurp_file('Makefile');
574  
575 if ( $makefile =~ /^PACKAGE_NAME\s=\s([^\n]+)$/xsm ) {
576 $project = $1;
577 }
578  
579 if ( $makefile =~ /^abs_top_srcdir\s=\s([^\n]+)$/xsm ) {
580 # init_parameters() will create destdir from project and
581 # destdir, so we want the the directory preceding the root of the
582 # project directory...
583 $destdir = dirname $1;
584 }
585 }
586  
587 croak
588 q{Unable to find the root of your project. Use --project-root option or run 'configure'}
589 if !$project || !$destdir;
590  
591 @{$options}{qw(destdir project)} = ( $destdir, $project );
592  
593 return ( $project, $destdir );
594 }
595  
596 ########################################################################
597 sub message {
598 ########################################################################
599 my ( $options, @message ) = @_;
600  
601 return if $options->{quiet};
602  
603 return print {*STDOUT} "@message\n";
604 }
605  
606 ########################################################################
607 sub init_logger {
608 ########################################################################
609 my ($level) = @_;
610  
611 $level //= 'info';
612  
613 $level = $LOG4PERL_LEVELS{$level} || $INFO;
614  
615 if ( $ENV{DEBUG} ) {
616 $level = $ENV{DEBUG} > 1 ? $TRACE : $DEBUG;
617 }
618  
619 Log::Log4perl->easy_init(
620 { level => $level,
621 file => '>>autoconf-template-perl.log',
622 layout => '%d (%r/%R) (%p) %l %m%n',
623 }
624 );
625  
626 return get_logger();
627 }
628  
629 ########################################################################
630 sub create_path {
631 ########################################################################
632 my ($file) = @_;
633  
634 my ( $name, $path, $ext ) = fileparse( $file, qr/[.][^.]+$/xsm );
635  
636 if ( !-d $path ) {
637 make_path($path);
638 }
639  
640 return -d $path;
641 }
642  
643 1;
644  
645 ## no critic (RequirePodSections)
646  
647 __END__