File Coverage

blib/lib/App/PTP/Commands.pm
Criterion Covered Total %
statement 441 483 91.3
branch 115 162 70.9
condition 14 18 77.7
subroutine 50 53 94.3
pod 0 34 0.0
total 620 750 82.6


line stmt bran cond sub pod time code
1             # This module contains the function that are pushed in the pipelines and which
2             # are operating on the input files.
3              
4             package App::PTP::Commands;
5              
6 23     23   347 use 5.022;
  23         64  
7 23     22   253 use strict;
  22         48  
  22         349  
8 22     19   217 use warnings;
  19         57  
  19         596  
9              
10 19     19   118 no warnings 'experimental::smartmatch';
  19         45  
  19         776  
11 19     19   118 use feature 'switch';
  19         53  
  19         2933  
12              
13 19     19   7584 use App::PTP::Files qw(write_side_output read_side_input write_handle);
  19         46  
  19         1146  
14 19     19   7294 use App::PTP::PerlEnv;
  19         41  
  19         740  
15 19     19   7259 use App::PTP::Util;
  19         43  
  19         559  
16 19     19   105 use Cwd qw(abs_path);
  19         36  
  19         732  
17 19     19   95 use Data::Dumper;
  19         35  
  19         639  
18 19     19   90 use Exporter 'import';
  19         32  
  19         488  
19 19     19   9824 use File::Spec::Functions qw(rel2abs);
  19         16197  
  19         4616  
20 19     19   122 use List::Util qw(min max);
  19         1597  
  19         7678  
21 19     19   17335 use Safe;
  19         623809  
  19         53646  
22              
23             # Every public function is exported by default.
24             my @all_cmd =
25             qw(prepare_perl_env do_grep do_substitute do_perl
26             do_execute do_load do_sort do_list_op do_tail do_head do_delete_marked
27             do_insert_marked do_set_markers do_number_lines do_file_name do_line_count
28             do_cut do_paste do_pivot do_tee do_shell do_eat);
29             our @EXPORT_OK = (@all_cmd, 'warn_or_die_if_needed');
30             our %EXPORT_TAGS = (CMD => \@all_cmd);
31              
32             our @markers; # The current marker array, not shared in the safe.
33             tie @App::PTP::PerlEnv::m, 'App::PTP::Util::MarkersArray';
34              
35             my $f_setter = tie $App::PTP::PerlEnv::f, 'App::PTP::Util::ReadOnlyVar';
36             my $F_setter = tie $App::PTP::PerlEnv::F, 'App::PTP::Util::ReadOnlyVar';
37             my $n_setter = tie $App::PTP::PerlEnv::n, 'App::PTP::Util::ReadOnlyVar';
38             my $N_setter = tie $App::PTP::PerlEnv::N, 'App::PTP::Util::ReadOnlyVar';
39             my $m_setter = tie $App::PTP::PerlEnv::m, 'App::PTP::Util::AliasVar';
40             # This variable is public because it is set in the App::PTP::process_all method.
41             our $I_setter = tie $App::PTP::PerlEnv::I, 'App::PTP::Util::ReadOnlyVar';
42              
43             # This 'safe' provides an isolated environment for all the regex and perl code
44             # execution provided by the user.
45             my $safe; # Sets to Safe->new() before each new file processed;
46              
47             # Prepare the $safe variable so that it can execute code with access to our
48             # PerlEnv.
49             sub new_safe {
50 31     31 0 81 my ($options) = @_;
51 31 100 100     109 if ($safe and $options->{preserve_perl_env} and
      66        
52             $safe->reval('$PerlEnv_LOADED')) {
53 2 50       1080 print "Skipping creation of new safe.\n" if $options->{debug_mode};
54 2         6 return;
55             }
56 29 50       96 print "Creating a new safe.\n" if $options->{debug_mode};
57 29         181 $safe = Safe->new();
58 29         31274 $safe->share_from('App::PTP::PerlEnv', \@App::PTP::PerlEnv::EXPORT_OK);
59 29 100       7157 if ($options->{use_safe} > 1) {
60 14         54 $safe->permit_only(qw(:base_core :base_mem :base_loop :base_math :base_orig
61             :load));
62 14         180 $safe->deny(qw(tie untie bless));
63             } else {
64 15         51 $safe->deny_only(qw(:subprocess :ownprocess :others :dangerous));
65             }
66 29 50       299 if ($@) {
67 0         0 chomp($@);
68 0         0 die "INTERNAL ERROR: cannot load the PerlEnv module: ${@}\n";
69             }
70             }
71              
72             # Prepare an App::PTP::SafeEnv package with access to the PerlEnv one and
73             # nothing else.
74             sub reset_safe_env {
75 117     117 0 205 my ($options) = @_;
76 117 50 66     298 if ($options->{preserve_perl_env} and $App::PTP::SafeEnv::PerlEnv_LOADED) {
77 2 50       19 print "Skipping reset of perl environment.\n" if $options->{debug_mode};
78 2         4 return;
79             }
80 115 50       360 print "Reseting the perl environment.\n" if $options->{debug_mode};
81             # We can't undef the hash, otherwise the code compiled in the eval below no
82             # longer refers to the same package (this would work however with a
83             # string-eval instead of a block-eval as the code would be compiled and
84             # create a new package hash).
85 115         313 %App::PTP::SafeEnv:: = ();
86 115         173 eval {
87             package App::PTP::SafeEnv;
88 115         14669 App::PTP::PerlEnv->import(':all');
89 115         339 our $PerlEnv_LOADED = 1; # For some reason the import does not work
90             };
91 115 50       433 if ($@) {
92 0         0 chomp($@);
93 0         0 die "INTERNAL ERROR: cannot prepare the SafeEnv package: ${@}\n";
94             }
95             }
96              
97             # Delete the PerlEnv (both the safe and the eval based one). This method is only
98             # meant to be called from tests.
99             sub delete_perl_env {
100 134     134 0 2462079 undef $safe;
101 134         4677 %App::PTP::SafeEnv:: = ();
102             }
103              
104             # Should be called for each new file so that the environment seen by the user
105             # supplied Perl code is empty.
106             sub prepare_perl_env {
107 148     148 0 318 my ($file_name, $options) = @_;
108 148 100       329 if (ref($file_name)) {
109 128         469 $f_setter->set('-');
110 128         275 $F_setter->set('-');
111             } else {
112 20         77 $f_setter->set($file_name);
113 20         544 $F_setter->set(abs_path($file_name));
114             }
115 148 100       422 if ($options->{use_safe} > 0) {
116 31         93 new_safe($options);
117             } else {
118 117         291 reset_safe_env($options);
119             }
120             }
121              
122             # process($file_name, \@pipeline, \%options, \@content, $missing_final_sep)
123             # Applies all the stage of the pipeline on the given content (which is modified
124             # in place).
125             sub process {
126 148     148 0 359 my ($file_name, $pipeline, $options, $content, $missing_final_separator) = @_;
127 148 50       392 if ($options->{debug_mode}) {
128             # For long files, we print only the first and last lines.
129 148         447 my @debug_content = @$content;
130 148         701 my $omit_msg = sprintf "... (%d lines omitted)", (@$content - 8);
131 148 100       387 splice @debug_content, 4, -4, $omit_msg if @$content > 10;
132 148 100       386 if (ref($file_name)) {
133 128         491 print "Processing $${file_name} with content: ".Dumper(\@debug_content);
134             } else {
135 20         98 print "Processing '${file_name}' with content: ".Dumper(\@debug_content);
136             }
137 148 100       8066 print "Has final separator: ".($missing_final_separator ? 'false' : 'true')."\n";
138             }
139 148         470 prepare_perl_env($file_name, $options);
140 148         482 @markers = (0) x scalar(@$content);
141 148         282 my $markers = \@markers;
142 148         317 for my $stage (@$pipeline) {
143 197         1427 my ($command, $code, $modes, @args) = @$stage;
144 197         812 $N_setter->set(scalar(@$content));
145 197         435 $modes->{missing_final_separator} = $missing_final_separator;
146 197         430 $modes->{file_name_ref} = \$_[0]; # this is an alias to the passed value.
147 197 50       613 if ($options->{debug_mode}) {
148 197         459 local $Data::Dumper::Indent = 0;
149             printf "Executing command: %s(%s).\n", $command,
150 197         502 join(', ', map { Dumper($_) } @args);
  296         5200  
151             }
152 197         7772 &$code($content, $markers, $modes, $options, @args);
153             }
154             }
155              
156             sub base_prepare_re {
157 12     12 0 22 my ($re, $modes) = @_;
158 12 50       35 if ($modes->{quote_regex}) {
159 0         0 $re = quotemeta($re);
160             }
161 12 50       35 if (not $modes->{case_sensitive}) {
162 0         0 $re = '(?i)'.$re;
163             }
164 12         24 return $re;
165             }
166              
167             # prepare_re('re', \%options)
168             # Applies the modal option on the given regex.
169             # This function is not exported.
170             sub prepare_re {
171 12     12 0 26 my ($re, $modes) = @_;
172 12         32 $re = base_prepare_re($re, $modes);
173 12         18 my $r;
174 12 50       45 if ($modes->{regex_engine} ne 'perl') {
175             # Some play to correctly escape whetever special characters might be in the
176             # regex while preserving its semantics. This relies on the fact that the
177             # 'Terse' option of Data::Dumper is set in the main program.
178             # The regex-engine variable has been validated in the Args module.
179 0         0 my $str_re = Dumper($re);
180 0         0 $r = eval "use re::engine::$modes->{regex_engine};
181             \$re = $str_re;
182             qr/\$re/s ";
183 0 0       0 if ($@) {
184 0         0 chomp($@);
185 0         0 die "FATAL: Cannot use the specified regex engine: ${@}\n";
186             }
187             } else {
188 12         182 $r = qr/$re/s;
189             }
190 12         35 return $r;
191             }
192              
193             sub quote_for_re {
194 75     75 0 136 my ($text, $modes) = @_;
195 75 100       169 if ($modes->{quote_regex}) {
196 7         19 return quotemeta($text);
197             } else {
198             # We quote just the '{' or '}' characters.
199 68         309 return $text =~ s/(\{|\})/\\$1/gr;
200             }
201             }
202              
203             sub prepare_re2 {
204 56     56 0 110 my ($re, $modes) = @_;
205 56         127 $re = quote_for_re($re, $modes);
206 56 100       160 if (not $modes->{case_sensitive}) {
207 1         3 $re = '(?i)'.$re;
208             }
209 56         94 my $use_statement = '';
210 56 50       146 if ($modes->{regex_engine} ne 'perl') {
211 0         0 $use_statement = "use re::engine::$modes->{regex_engine};";
212             }
213 56         224 return ($use_statement, "{${re}}");
214             }
215              
216             # This interpolate str in the Perl env (unless -Q is in effect).
217             sub maybe_interpolate {
218 12     12 0 25 my ($str, $modes, $options, $command) = @_;
219 12 100       31 if (not $modes->{quote_regex}) {
220 6         42 $str = eval_in_safe_env("<<\"PTP_EOF_WORD\"\n${str}\nPTP_EOF_WORD\n", $options);
221 6 50       22 die "FATAL: Cannot eval string for --${command}: ${@}\n" if $@;
222 6         17 chomp($str);
223             }
224 12         27 return $str;
225             }
226              
227             sub do_grep {
228 37     37 0 109 my ($content, $markers, $modes, $options, $re) = @_;
229 37         99 my ($use_stmt, $quoted_re) = prepare_re2($re, $modes);
230 37 50       148 print "\$re = ${quoted_re}\n" if $options->{debug_mode};
231 37         134 my $wrapped = get_code_in_safe_env(
232             "{; ${use_stmt} undef \$_ unless m ${quoted_re} }", $options, '--grep');
233 37         114 $. = 0;
234 37         77 map { $m_setter->set(\$markers->[$.]);
  218         15570  
235 218         675 $n_setter->set($.++);
236 218         2827 $wrapped->() } @$content;
237             # This code is duplicated from do_perl:
238 37         4923 for my $i (0 .. $#$content) {
239 218 100       452 if (not defined $content->[$i]) {
    50          
240 141         189 undef $markers->[$i];
241             } elsif (not defined $markers->[$i]) {
242 0         0 $markers->[$i] = ''; # We don't want undef here, as we will filter on it.
243             }
244             }
245 37         78 @$content = grep { defined } @$content;
  218         382  
246 37         65 @$markers = grep { defined } @$markers;
  218         674  
247             }
248              
249             sub do_substitute {
250 19     19 0 53 my ($content, $markers, $modes, $options, $re, $subst) = @_;
251 19 50       47 if ($options->{debug_mode}) {
252 19         55 print "Before: \$re = ${re}; \$subst = ${subst}\n";
253             }
254 19         46 my ($use_stmt, $quoted_re) = prepare_re2($re, $modes);
255 19         47 my $quoted_subst = quote_for_re($subst, $modes);
256 19 100       50 my $g = $modes->{global_match} ? 'g' : '';
257 19 50       42 if ($options->{debug_mode}) {
258 19         46 print "After: \$re = ${quoted_re}; \$subst = ${quoted_subst}\n";
259             }
260 19         69 my $wrapped = get_code_in_safe_env(
261             "; ${use_stmt} s ${quoted_re}{${quoted_subst}}${g}", $options,
262             '--substitute');
263 19         46 $. = 0;
264 19         42 map { $m_setter->set(\$markers->[$.]);
  73         4433  
265 73         225 $n_setter->set($.++);
266 73         958 $wrapped->() } @$content;
267             }
268              
269             sub warn_or_die_if_needed {
270 216     216 0 431 my ($text, $modes) = @_;
271 216 100       913 return 0 unless $@;
272 3         8 chomp($@);
273 3 50       9 if ($modes->{fatal_error}) {
274 0         0 die "FATAL: ${text}: ${@}\n";
275             } else {
276 3         17 print "WARNING: ${text}: ${@}\n";
277             }
278 3         8 return 1;
279             }
280              
281             sub eval_in_safe_env {
282 151     151 0 306 my ($code, $options) = @_;
283 151 50       389 if ($options->{debug_mode} > 1) {
284 0         0 print "Evaluating the following code: ${code}\n";
285             }
286 151 100       361 if ($options->{use_safe} > 0) {
287 61         202 return $safe->reval($code);
288             } else {
289 90     8   7523 return eval("package App::PTP::SafeEnv;
  8     7   55  
  8     7   15  
  8         229  
  8         44  
  8         14  
  8         551  
  8         62  
  8         18  
  8         234  
  8         45  
  8         16  
  8         524  
  7         56  
  7         19  
  7         188  
  7         41  
  7         13  
  7         413  
  7         55  
  7         18  
  7         182  
  7         39  
  7         14  
  7         522  
  4         28  
  4         7  
  4         98  
  4         20  
  4         10  
  4         303  
  4         29  
  4         9  
  4         175  
  4         21  
  4         8  
  4         244  
  4         26  
  4         9  
  4         160  
  4         21  
  4         38  
  4         387  
  4         64  
  4         11  
  4         100  
  4         22  
  4         7  
  4         272  
  4         28  
  4         8  
  4         99  
  4         18  
  4         8  
  4         279  
  4         27  
  4         17  
  4         94  
  4         21  
  4         6  
  4         261  
  4         38  
  4         9  
  4         113  
  4         21  
  4         9  
  4         259  
  3         21  
  3         6  
  3         73  
  3         13  
  3         8  
  3         131  
  3         17  
  3         7  
  3         63  
  3         13  
  3         6  
  3         198  
  8         62  
  8         19  
  8         219  
  8         80  
  8         20  
  8         438  
  1         7  
  1         2  
  1         23  
  1         5  
  1         2  
  1         94  
  1         7  
  1         2  
  1         28  
290             no strict;
291             no warnings;
292             ${code}");
293             }
294             }
295              
296             sub get_code_in_safe_env {
297 121     121 0 281 my ($code, $options, $cmd) = @_;
298 121         373 my $wrapped_code = eval_in_safe_env("sub { ${code} }", $options);
299 121 50       30089 die "FATAL: Cannot wrap code for ${cmd}: ${@}" if $@;
300 121         264 return $wrapped_code;
301             }
302              
303             sub do_perl {
304 60     60 0 174 my ($content, $markers, $modes, $options, $cmd, $code) = @_;
305 60         151 $. = 0;
306 60         314 my $scmd = '-'.($cmd =~ s/^(..)/-$1/r); # --perl or -n.
307 60         155 my $wrapped_code = get_code_in_safe_env($code, $options, $scmd);
308             my @result = map {
309 60         146 $m_setter->set(\$markers->[$.]);
  201         816  
310 201         638 $n_setter->set(++$.);
311 201         327 my $input = $_;
312             # Among other things, this ensures that the code is always executed in
313             # a scalar context.
314 201         283 my $r = eval { $wrapped_code->() };
  201         2365  
315             # We can't use return as we're not in a sub.
316 201 100       29085 if (warn_or_die_if_needed("Perl code failed in ${scmd}", $modes)) {
317 3         6 given ($cmd) {
318 3         10 1 when 'filter';
319 2         7 $input when 'n';
320 1         3 $markers[$.] when 'mark-line';
321             }
322             } else {
323 198         542 $r;
324             }
325             } @$content;
326              
327 60         208 $n_setter->set(undef);
328 60         175 $m_setter->set(\undef);
329              
330 60 100       278 if ($cmd eq 'perl') {
    100          
    100          
    50          
331             # Do nothing with the result.
332             } elsif ($cmd eq 'n') {
333 29         99 @$content = @result;
334             } elsif ($cmd eq 'filter') {
335 6         68 for my $i (0 .. $#$content) {
336 23 100 100     104 if (!$result[$i] xor $modes->{inverse_match}) {
337 12         28 undef $content->[$i];
338             }
339             }
340             } elsif ($cmd eq 'mark-line') {
341 7         27 @$markers = @result;
342             } else {
343 0         0 die "FATAL: Invalid command received for perl operation ($cmd).\n";
344             }
345              
346 60         208 for my $i (0 .. $#$content) {
347 201 100       522 if (not defined $content->[$i]) {
    100          
348 12         24 undef $markers->[$i];
349             } elsif (not defined $markers->[$i]) {
350 6         14 $markers->[$i] = ''; # We don't want undef here, as we will filter on it.
351             }
352             }
353 60         120 @$content = grep { defined } @$content;
  201         445  
354 60         118 @$markers = grep { defined } @$markers;
  201         1017  
355             }
356              
357             sub do_execute {
358 21     21 0 81 my ($content, $markers, $modes, $options, $cmd, $code) = @_;
359 21 100       69 $code = "use $code;" if $cmd eq 'M';
360 21         67 eval_in_safe_env($code, $options);
361 21 100       24548 if ($@) {
362 2         9 chomp($@);
363 2         22 my $scmd = '-'.($cmd =~ s/^(..)/-$1/r); # --execute or -M.
364 2         55 die "FATAL: Perl code failed in ${scmd}: ${@}\n";
365             }
366             }
367              
368             sub do_load {
369 3     3 0 13 my ($content, $markers, $modes, $options, $file) = @_;
370             # do can open relative paths, but in that case it looks them up in the @INC
371             # directory, which we want to avoid.
372             # We don't use abs_path here to not die (just yet) if the file does not exist.
373 3         15 my $abs_path = rel2abs($file);
374 3 50       240 print "Loading file: '$abs_path'\n" if $options->{debug_mode};
375 3 50       23 if (not defined eval_in_safe_env("do '${abs_path}';", $options)) {
376 0 0       0 if ($@) {
    0          
377 0         0 die "FATAL: Perl code failed in --load: ${@}\n";
378             } elsif ($!) {
379 0         0 die "FATAL: Cannot load file '$file' for --load: $!\n";
380             }
381             }
382             }
383              
384             sub do_sort {
385 9     9 0 57 my ($content, $markers, $modes, $options) = @_;
386 9 50       49 if (ref($modes->{comparator}) eq 'CODE') {
    100          
387             # This branch is no longer used.
388 0         0 @$content = sort { $modes->{comparator}() } @$content;
  0         0  
389             } elsif (ref($modes->{comparator}) eq 'SCALAR') {
390 7 100       10 if (${$modes->{comparator}} eq 'default') {
  7 100       26  
    50          
391 5         36 @$content = sort @$content;
392 2         9 } elsif (${$modes->{comparator}} eq 'numeric') {
393 19     19   196 no warnings "numeric";
  19         35  
  19         1551  
394 1         6 @$content = sort { $a <=> $b } @$content;
  5         16  
395 1         5 } elsif (${$modes->{comparator}} eq 'locale') {
396 19     19   8020 use locale;
  19         8892  
  19         103  
397 1         5 @$content = sort { $a cmp $b } @$content;
  21         26  
398             } else {
399             die sprintf "INTERNAL ERROR: Invalid comparator (%s)\n",
400 0         0 ${$modes->{comparator}};
  0         0  
401             }
402             } else {
403             die sprintf "INTERNAL ERROR: Invalid comparator type (%s)\n",
404 2 50       6 Dumper($modes->{comparator}) if ref $modes->{comparator};
405 2         5 my $cmp = $modes->{comparator};
406 2         7 my $sort = get_code_in_safe_env("sort { $cmp } \@_", $options,
407             'custom comparator');
408 2         44 @$content = $sort->(@$content);
409             }
410 9         43 @$markers = (0) x scalar(@$content);
411             }
412              
413             sub do_list_op {
414 2     2 0 7 my ($content, $markers, $modes, $options, $sub, $apply_on_markers) = @_;
415 2         10 @$content = &$sub(@$content);
416 2 50       7 if ($apply_on_markers) {
417 0         0 @$markers = &$sub(@$markers);
418             } else {
419 2         10 @$markers = (0) x scalar(@$content);
420             }
421             }
422              
423             sub do_tail {
424 4     4 0 8 my ($content, $markers, $modes, $options, $len) = @_;
425 4 100       11 $len = 10 unless $len;
426 4         10 splice @$content, 0, -$len;
427 4         15 splice @$markers, 0, -$len;
428             }
429              
430             sub do_head {
431 4     4 0 10 my ($content, $markers, $modes, $options, $len) = @_;
432 4 100       10 $len = 10 unless $len;
433 4 100       9 $len = -@$content if $len < -@$content;
434 4         15 splice @$content, $len;
435 4         15 splice @$markers, $len;
436             }
437              
438             sub do_delete_marked {
439             # negative offset if we're deleting a line before the marker.
440 3     3 0 17 my ($content, $markers, $modes, $options, $offset) = @_;
441 3         31 my $start = min(max(0, -$offset), $#$content);
442 3         23 my $end = max(min($#$content, $#$content + $offset), $#$content);
443 3         11 my @markers_temp = @$markers; # So that we can read it even after an undef.
444 3         13 for my $i ($start .. $end) {
445 12 100       31 if ($markers_temp[$i]) {
446 6         18 undef $content->[$i + $offset];
447 6         14 undef $markers->[$i + $offset];
448             }
449             }
450 3         10 @$content = grep { defined } @$content;
  12         32  
451 3         9 @$markers = grep { defined } @$markers;
  12         35  
452             }
453              
454             sub do_insert_marked {
455             # negative offset if we're inserting a line before the marker.
456 3     3 0 13 my ($content, $markers, $modes, $options, $offset, $line) = @_;
457 3         13 my @markers_temp = @$markers;
458 3         10 my @content_temp = @$content;
459 3         8 my $added = 0;
460 3         5 my $wrapped;
461 3 50       11 if (not $modes->{quote_regex}) {
462 3         15 $wrapped = get_code_in_safe_env("\"${line}\"", $options,
463             '--insert-marked');
464             }
465 3         14 for my $i (0 .. $#content_temp) {
466 12 100       74 next unless $markers_temp[$i];
467 6         10 my $r;
468 6 50       19 if ($modes->{quote_regex}) {
469 0         0 $r = $line;
470             } else {
471 6         11 $_ = $content_temp[$i];
472 6         23 $n_setter->set($i + 1);
473 6         22 $m_setter->set($markers_temp[$i]);
474 6         14 $line =~ s/(?:[^\\]|^)((:?\\\\)*")/\\$1/g;
475 6         13 $r = eval { $wrapped->() };
  6         51  
476 6 50       1226 next if warn_or_die_if_needed(
477             'String interpolation failed in --insert-marked', $modes);
478             # it should not be possible for the result to be undef...
479             }
480             # We never insert at a negative offset or before the previously added line.
481             # Offset = 0 means we're inserting after the current line.
482 6         15 my $target = $i + $offset + 1 + $added;
483 6 50       15 $target = $added if $target < $added;
484 6 50       14 $target = @$content if $target > @$content;
485 6         12 ++$added;
486 6         19 splice @$content, $target, 0, $r;
487 6         17 splice @$markers, $target, 0, 0;
488             }
489             }
490              
491             sub do_set_markers {
492 0     0 0 0 my ($content, $markers, $modes, $options, $value) = @_;
493 0         0 @$markers = ($value)x scalar(@$content);
494             }
495              
496             sub do_number_lines {
497 0     0 0 0 my ($content, $markers, $modes, $options) = @_;
498 0         0 my $line = 0;
499 0         0 my $n = int(log(@$content) / log(10)) + 1;
500 0         0 map { $_ = sprintf("%${n}d %s", ++$line, $_) } @$content;
  0         0  
501             }
502              
503             sub do_file_name {
504 5     5 0 13 my ($content, $markers, $modes, $options, $replace_all) = @_;
505 5         10 my $name;
506 5 100 33     27 if (ref($modes->{file_name_ref}) eq 'SCALAR') {
    50          
507 2         3 $name = ${$modes->{file_name_ref}};
  2         6  
508             } elsif (ref($modes->{file_name_ref}) eq 'REF' and
509 3         12 ref(${$modes->{file_name_ref}}) eq 'SCALAR') {
510 3         6 $name = $${$modes->{file_name_ref}};
  3         7  
511             } else {
512             die 'INTERNAL ERROR: Invalid input marker: '.Dumper($modes->{file_name_ref})
513 0         0 ."\n";
514             }
515 5 100       12 if ($replace_all) {
516             # Does nothing to empty file.
517 2 100       9 if (@$content) {
518 1         3 @$content = ($name);
519 1         6 @$markers = (0);
520             }
521             } else {
522 3         9 unshift @$content, $name;
523 3         10 unshift @$markers, 0;
524             }
525             }
526              
527             sub do_line_count {
528 2     2 0 6 my ($content, $markers, $modes, $options) = @_;
529 2         5 @$content = (scalar(@$content));
530 2         6 @$markers = (0);
531             }
532              
533             sub do_cut {
534 5     5 0 13 my ($content, $markers, $modes, $options, $spec) = @_;
535 5         14 my $re = prepare_re($modes->{input_field}, $modes);
536 5 50       15 if ($options->{debug_mode}) {
537 5         11 print "Examples of the --cut operation:\n";
538 5         34 my @debug = map { [split $re] } @$content[0..min(5, $#$content)];
  12         92  
539 5 100       12 map { for ((@$_)[@$spec]) { $_ = "-->${_}<--" if $_ } } @debug;
  12         28  
  24         61  
540 5         11 local $, = $modes->{output_field};
541 5         19 local $\ = $options->{output_separator};
542 5         9 map { print @$_ } @debug;
  12         41  
543             }
544             @$content =
545             map {
546 5 100       11 join $modes->{output_field}, map { $_ ? $_ : '' } (split $re)[@$spec]
  12         55  
  24         82  
547             } @$content;
548             }
549              
550             sub do_paste {
551 0     0 0 0 my ($content, $markers, $modes, $options, $file) = @_;
552 0         0 my ($side_content, undef) = read_side_input($file, $options);
553 0         0 for my $i (0 .. $#$side_content) {
554 0         0 $content->[$i] .= $modes->{output_field}.$side_content->[$i];
555             }
556 0         0 for my $i ($#$side_content + 1 .. $#$content) {
557 0         0 $content->[$i] .= $modes->{output_field};
558             }
559 0 0       0 if (@$content > @$markers) {
560 0         0 splice @$markers, scalar(@$markers), 0, (0) x (@$content - @$markers);
561             }
562             }
563              
564             sub do_pivot {
565 7     7 0 22 my ($content, $markers, $modes, $options, $action) = @_;
566 7         14 my $m = 0;
567             # This is unused by the 'pivot' action, but it's not a huge issue.
568 7         25 my $re = prepare_re($modes->{input_field}, $modes);
569 7 100       29 if ($action eq 'transpose') {
    100          
    50          
570 2         4 $m = 0;
571             my @lines =
572 2         4 map { my $r = [split $re]; $m = max($m, scalar(@$r)); $r } @$content;
  6         30  
  6         16  
  6         13  
573             @$content =
574             map {
575 2         6 my $c = $_;
  5         6  
576 5   100     9 join $modes->{output_field}, map { $_->[$c] // '' } @lines;
  15         41  
577             } 0..($m - 1);
578             } elsif ($action eq 'pivot') {
579 4         8 $m = 1;
580 4         24 @$content = (join $modes->{output_field}, @$content);
581             } elsif ($action eq 'anti-pivot') {
582 1         2 @$content = map { split $re } @$content;
  3         20  
583 1         3 $m = @$content;
584             } else {
585 0         0 die "INTERNAL ERROR: unknown action for the pivot method: ${action}\n";
586             }
587 7         40 @$markers = (0) x $m;
588             }
589              
590             sub do_tee {
591 6     6 0 14 my ($content, $markers, $modes, $options, $file_name) = @_;
592 6         12 $file_name = maybe_interpolate($file_name, $modes, $options, 'tee');
593             # This missing_final_separator is not really an option, it is added in the
594             # modes struct by the 'process' method, specifically for this function.
595             write_side_output($file_name, $content, $modes->{missing_final_separator},
596 6         17 $options);
597             }
598              
599             sub do_shell {
600 6     6 0 25 my ($content, $markers, $modes, $options, $command, $arg) = @_;
601 6 50       17 die "INTERNAL ERROR: Unexpected command in do_tee: ${command}\n" unless $command eq 'shell';
602 6         18 $arg = maybe_interpolate($arg, $modes, $options, $command);
603             {
604 6         11 local $SIG{PIPE} = "IGNORE";
  6         125  
605 6 50       15568 open(my $pipe, '|-', $arg) or die "FATAL: Cannot execute command given to --${command}: $!\n";
606 6         320 write_handle($pipe, $content, $modes->{missing_final_separator}, $options);
607             # When run by CPAN testers, this fails sometime for unknown reason. So this
608             # is only a warning and not a fatal error.
609 6 50       7392 close $pipe or print "WARNING: Cannot close pipe for command given to --${command}: $!\n";
610             }
611             }
612              
613             sub do_eat {
614 1     1 0 20 my ($content, $markers, $modes, $options) = @_;
615 1         24 @$content = ();
616 1         34 @$markers = ();
617             }
618              
619             1;