blib/script/perl_types_refactor_headers.pl untested

filter: Statementstmt 0.0% 0 / 81 Branchbran 0.0% 0 / 26 Conditioncond 0.0% 0 / 15 MC/DCmcdc 0.0% 0 / 10 Subroutinesub 0.0% 0 / 3 Podpod n/a totaltotal 0.0% 0 / 135 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 #!/usr/bin/env perl
2 use strict;
3 use warnings;
4 use File::Find;
5  
6 my $current_file_count = 0;
7 my @perl_files;
8 find(sub {
9 return unless -f;
10  
11 # select files whose name contains .pm or .pl
12 if ($_ =~ /\.(?:pm|pl)/) {
13 push @perl_files, $File::Find::name;
14 }
15 }, 't/lib');
16  
17 for my $file (@perl_files) {
18 $current_file_count++;
19 print "\nProcessing file #$current_file_count: $file\n";
20 open my $fh, '<', $file or do {
21 print " Cannot open file: $!\n";
22 next;
23 };
24 my @lines = <$fh>;
25 close $fh;
26  
27 my $modified = 0;
28 for (my $i = 0; $i <= $#lines; ) {
29 if ($lines[$i] =~ /^\s*($|#)/) { $i++; next }
30 if ($lines[$i] =~ /^\s*use\s+(?:Perl::Types|perltypes)\s*;/) {
31 print " Found old-style header at line " . ($i+1) . "\n";
32 splice @lines, $i, 1;
33 $modified = 1;
34 my $ver_i;
35 for my $j ($i .. $#lines) {
36 if ($lines[$j] =~ /^\s*our\s+\$VERSION\b/) { $ver_i = $j; last }
37 }
38 my $insert_idx;
39 for my $j ($i .. ($ver_i // $#lines)) {
40 if ($lines[$j] =~ /^\s*use\s+warnings\s*;/) {
41 $insert_idx = $j + 1;
42 last;
43 }
44 }
45 $insert_idx //= $i;
46 splice @lines, $insert_idx, 0, "use types;\n";
47 print " Inserted 'use types;' at line " . ($insert_idx+1) . "\n";
48 $i = ($ver_i // $insert_idx) + 1;
49 next;
50 }
51 elsif ($lines[$i] =~ /^\s*package\b/) {
52 print " Found new-style header at line " . ($i+1) . "\n";
53 my $ver_i;
54 for my $j ($i+1 .. $#lines) {
55 if ($lines[$j] =~ /^\s*our\s+\$VERSION\b/) { $ver_i = $j; last }
56 }
57 unless (defined $ver_i) {
58 print " No version line after package at line " . ($i+1) . ", skipping header\n";
59 $i++;
60 next;
61 }
62 my $found_type = 0;
63 for my $j ($i+1 .. $ver_i-1) {
64 if ($lines[$j] =~ /^\s*use\s+(?:Perl::Types|perltypes)\s*;/) {
65 print " Normalizing type use at line " . ($j+1) . " to 'use types;'\n";
66 $lines[$j] = "use types;\n";
67 $modified = 1;
68 $found_type = 1;
69 }
70 elsif ($lines[$j] =~ /^\s*use\s+types\s*;/) {
71 $found_type = 1;
72 }
73 }
74 unless ($found_type) {
75 print " Unrecognized header: no type use before version in block starting at line " . ($i+1) . "\n";
76 }
77 $i = $ver_i + 1;
78 next;
79 }
80 else {
81 $i++;
82 }
83 }
84 if ($modified) {
85 open my $out, '>', $file or do {
86 print " Cannot write file: $!\n";
87 next;
88 };
89 print $out @lines;
90 close $out;
91 print " File modified and saved.\n";
92 } else {
93 print " No changes needed.\n";
94 }
95  
96 # limit to the first few files for debugging
97 # if ($current_file_count >= 10) {
98 # die 'TMP DEBUG';
99 # }
100 }