File Coverage

blib/lib/App/PTP/Commands.pm
Criterion Covered Total %
statement 435 482 90.2
branch 110 160 68.7
condition 13 18 72.2
subroutine 50 53 94.3
pod 0 34 0.0
total 608 747 81.3


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 21     21   299 use 5.022;
  21         71  
7 21     20   263 use strict;
  20         55  
  20         378  
8 20     17   241 use warnings;
  17         35  
  17         638  
9              
10 17     17   115 no warnings 'experimental::smartmatch';
  17         64  
  17         781  
11 17     17   117 use feature 'switch';
  17         50  
  17         2805  
12              
13 17     17   7665 use App::PTP::Files qw(write_side_output read_side_input write_handle);
  17         46  
  17         1124  
14 17     17   7273 use App::PTP::PerlEnv;
  17         41  
  17         727  
15 17     17   7185 use App::PTP::Util;
  17         41  
  17         571  
16 17     17   120 use Cwd qw(abs_path);
  17         33  
  17         781  
17 17     17   96 use Data::Dumper;
  17         43  
  17         658  
18 17     17   91 use Exporter 'import';
  17         28  
  17         458  
19 17     17   8018 use File::Spec::Functions qw(rel2abs);
  17         16623  
  17         3015  
20 17     17   1921 use List::Util qw(min max);
  17         1828  
  17         8829  
21 17     17   16002 use Safe;
  17         650335  
  17         55200  
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 57 my ($options) = @_;
51 31 100 100     100 if ($safe and $options->{preserve_perl_env} and
      66        
52             $safe->reval('$PerlEnv_LOADED')) {
53 2 50       1070 print "Skipping creation of new safe.\n" if $options->{debug_mode};
54 2         6 return;
55             }
56 29 50       90 print "Creating a new safe.\n" if $options->{debug_mode};
57 29         191 $safe = Safe->new();
58 29         29784 $safe->share_from('App::PTP::PerlEnv', \@App::PTP::PerlEnv::EXPORT_OK);
59 29 100       6652 if ($options->{use_safe} > 1) {
60 14         56 $safe->permit_only(qw(:base_core :base_mem :base_loop :base_math :base_orig
61             :load));
62 14         144 $safe->deny(qw(tie untie bless));
63             } else {
64 15         45 $safe->deny_only(qw(:subprocess :ownprocess :others :dangerous));
65             }
66 29 50       259 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 112     112 0 224 my ($options) = @_;
76 112 50 66     309 if ($options->{preserve_perl_env} and $App::PTP::SafeEnv::PerlEnv_LOADED) {
77 2 50       8 print "Skipping reset of perl environment.\n" if $options->{debug_mode};
78 2         5 return;
79             }
80 110 50       365 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 110         298 %App::PTP::SafeEnv:: = ();
86 110         201 eval {
87             package App::PTP::SafeEnv;
88 110         15345 App::PTP::PerlEnv->import(':all');
89 110         413 our $PerlEnv_LOADED = 1; # For some reason the import does not work
90             };
91 110 50       421 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 129     129 0 2490291 undef $safe;
101 129         4711 %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 143     143 0 329 my ($file_name, $options) = @_;
108 143 100       331 if (ref($file_name)) {
109 123         450 $f_setter->set('-');
110 123         320 $F_setter->set('-');
111             } else {
112 20         75 $f_setter->set($file_name);
113 20         600 $F_setter->set(abs_path($file_name));
114             }
115 143 100       408 if ($options->{use_safe} > 0) {
116 31         87 new_safe($options);
117             } else {
118 112         298 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 143     143 0 355 my ($file_name, $pipeline, $options, $content, $missing_final_separator) = @_;
127 143 50       441 if ($options->{debug_mode}) {
128             # For long files, we print only the first and last lines.
129 143         441 my @debug_content = @$content;
130 143         713 my $omit_msg = sprintf "... (%d lines omitted)", (@$content - 8);
131 143 100       382 splice @debug_content, 4, -4, $omit_msg if @$content > 10;
132 143 100       359 if (ref($file_name)) {
133 123         482 print "Processing $${file_name} with content: ".Dumper(\@debug_content);
134             } else {
135 20         93 print "Processing '${file_name}' with content: ".Dumper(\@debug_content);
136             }
137 143 100       8690 print "Has final separator: ".($missing_final_separator ? 'false' : 'true')."\n";
138             }
139 143         489 prepare_perl_env($file_name, $options);
140 143         515 @markers = (0) x scalar(@$content);
141 143         275 my $markers = \@markers;
142 143         379 for my $stage (@$pipeline) {
143 192         1429 my ($command, $code, $modes, @args) = @$stage;
144 192         814 $N_setter->set(scalar(@$content));
145 192         457 $modes->{missing_final_separator} = $missing_final_separator;
146 192         420 $modes->{file_name_ref} = \$_[0]; # this is an alias to the passed value.
147 192 50       528 if ($options->{debug_mode}) {
148 192         415 local $Data::Dumper::Indent = 0;
149             printf "Executing command: %s(%s).\n", $command,
150 192         434 join(', ', map { Dumper($_) } @args);
  291         5696  
151             }
152 192         8085 &$code($content, $markers, $modes, $options, @args);
153             }
154             }
155              
156             sub base_prepare_re {
157 12     12 0 24 my ($re, $modes) = @_;
158 12 50       39 if ($modes->{quote_regex}) {
159 0         0 $re = quotemeta($re);
160             }
161 12 50       36 if (not $modes->{case_sensitive}) {
162 0         0 $re = '(?i)'.$re;
163             }
164 12         28 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 29 my ($re, $modes) = @_;
172 12         35 $re = base_prepare_re($re, $modes);
173 12         21 my $r;
174 12 50       47 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         227 $r = qr/$re/s;
189             }
190 12         44 return $r;
191             }
192              
193             sub quote_for_re {
194 75     75 0 130 my ($text, $modes) = @_;
195 75 100       174 if ($modes->{quote_regex}) {
196 7         20 return quotemeta($text);
197             } else {
198             # We quote just the '{' or '}' characters.
199 68         316 return $text =~ s/(\{|\})/\\$1/gr;
200             }
201             }
202              
203             sub prepare_re2 {
204 56     56 0 120 my ($re, $modes) = @_;
205 56         139 $re = quote_for_re($re, $modes);
206 56 100       165 if (not $modes->{case_sensitive}) {
207 1         4 $re = '(?i)'.$re;
208             }
209 56         93 my $use_statement = '';
210 56 50       153 if ($modes->{regex_engine} ne 'perl') {
211 0         0 $use_statement = "use re::engine::$modes->{regex_engine};";
212             }
213 56         209 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 51 my ($str, $modes, $options, $command) = @_;
219 12 100       39 if (not $modes->{quote_regex}) {
220 6         62 $str = eval_in_safe_env("<<~\"PTP_EOF_WORD\"\n${str}\nPTP_EOF_WORD\n", $options);
221 6 50       28 die "FATAL: Cannot eval string for --${command}: ${@}\n" if $@;
222 6         18 chomp($str);
223             }
224 12         32 return $str;
225             }
226              
227             sub do_grep {
228 37     37 0 126 my ($content, $markers, $modes, $options, $re) = @_;
229 37         94 my ($use_stmt, $quoted_re) = prepare_re2($re, $modes);
230 37 50       133 print "\$re = ${quoted_re}\n" if $options->{debug_mode};
231 37         137 my $wrapped = get_code_in_safe_env(
232             "{; ${use_stmt} undef \$_ unless m ${quoted_re} }", $options, '--grep');
233 37         105 $. = 0;
234 37         85 map { $m_setter->set(\$markers->[$.]);
  218         15369  
235 218         704 $n_setter->set($.++);
236 218         3075 $wrapped->() } @$content;
237             # This code is duplicated from do_perl:
238 37         4795 for my $i (0 .. $#$content) {
239 218 100       466 if (not defined $content->[$i]) {
    50          
240 141         216 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         433  
246 37         75 @$markers = grep { defined } @$markers;
  218         695  
247             }
248              
249             sub do_substitute {
250 19     19 0 53 my ($content, $markers, $modes, $options, $re, $subst) = @_;
251 19 50       66 if ($options->{debug_mode}) {
252 19         66 print "Before: \$re = ${re}; \$subst = ${subst}\n";
253             }
254 19         50 my ($use_stmt, $quoted_re) = prepare_re2($re, $modes);
255 19         52 my $quoted_subst = quote_for_re($subst, $modes);
256 19 100       53 my $g = $modes->{global_match} ? 'g' : '';
257 19 50       54 if ($options->{debug_mode}) {
258 19         59 print "After: \$re = ${quoted_re}; \$subst = ${quoted_subst}\n";
259             }
260 19         74 my $wrapped = get_code_in_safe_env(
261             "; ${use_stmt} s ${quoted_re}{${quoted_subst}}${g}", $options,
262             '--substitute');
263 19         48 $. = 0;
264 19         48 map { $m_setter->set(\$markers->[$.]);
  73         4349  
265 73         258 $n_setter->set($.++);
266 73         1104 $wrapped->() } @$content;
267             }
268              
269             sub warn_or_die_if_needed {
270 216     216 0 422 my ($text, $modes) = @_;
271 216 100       956 return 0 unless $@;
272 3         7 chomp($@);
273 3 50       10 if ($modes->{fatal_error}) {
274 0         0 die "FATAL: ${text}: ${@}\n";
275             } else {
276 3         17 print "WARNING: ${text}: ${@}\n";
277             }
278 3         7 return 1;
279             }
280              
281             sub eval_in_safe_env {
282 151     151 0 315 my ($code, $options) = @_;
283 151 50       377 if ($options->{debug_mode} > 1) {
284 0         0 print "Evaluating the following code: ${code}\n";
285             }
286 151 100       376 if ($options->{use_safe} > 0) {
287 61         202 return $safe->reval($code);
288             } else {
289 90     8   8526 return eval("package App::PTP::SafeEnv;
  8     7   59  
  8     7   32  
  8         269  
  8         52  
  8         23  
  8         628  
  8         65  
  8         22  
  8         225  
  8         43  
  8         19  
  8         619  
  7         62  
  7         18  
  7         201  
  7         37  
  7         22  
  7         442  
  7         56  
  7         17  
  7         192  
  7         38  
  7         14  
  7         570  
  4         31  
  4         15  
  4         103  
  4         24  
  4         8  
  4         322  
  4         36  
  4         8  
  4         163  
  4         23  
  4         7  
  4         264  
  4         28  
  4         9  
  4         167  
  4         25  
  4         55  
  4         359  
  4         68  
  4         14  
  4         111  
  4         21  
  4         9  
  4         292  
  4         28  
  4         10  
  4         109  
  4         21  
  4         8  
  4         301  
  4         33  
  4         9  
  4         108  
  4         19  
  4         9  
  4         299  
  4         28  
  4         7  
  4         109  
  4         21  
  4         8  
  4         285  
  3         21  
  3         9  
  3         78  
  3         16  
  3         6  
  3         184  
  3         27  
  3         9  
  3         79  
  3         17  
  3         27  
  3         284  
  8         99  
  8         19  
  8         247  
  8         112  
  8         24  
  8         556  
  1         7  
  1         2  
  1         39  
  1         7  
  1         2  
  1         86  
  1         7  
  1         2  
  1         25  
290             no strict;
291             no warnings;
292             ${code}");
293             }
294             }
295              
296             sub get_code_in_safe_env {
297 121     121 0 270 my ($code, $options, $cmd) = @_;
298 121         315 my $wrapped_code = eval_in_safe_env("sub { ${code} }", $options);
299 121 50       28699 die "FATAL: Cannot wrap code for ${cmd}: ${@}" if $@;
300 121         281 return $wrapped_code;
301             }
302              
303             sub do_perl {
304 60     60 0 183 my ($content, $markers, $modes, $options, $cmd, $code) = @_;
305 60         144 $. = 0;
306 60         303 my $scmd = '-'.($cmd =~ s/^(..)/-$1/r); # --perl or -n.
307 60         180 my $wrapped_code = get_code_in_safe_env($code, $options, $scmd);
308             my @result = map {
309 60         171 $m_setter->set(\$markers->[$.]);
  201         816  
310 201         649 $n_setter->set(++$.);
311 201         350 my $input = $_;
312             # Among other things, this ensures that the code is always executed in
313             # a scalar context.
314 201         266 my $r = eval { $wrapped_code->() };
  201         2371  
315             # We can't use return as we're not in a sub.
316 201 100       28372 if (warn_or_die_if_needed("Perl code failed in ${scmd}", $modes)) {
317 3         5 given ($cmd) {
318 3         11 1 when 'filter';
319 2         6 $input when 'n';
320 1         5 $markers[$.] when 'mark-line';
321             }
322             } else {
323 198         541 $r;
324             }
325             } @$content;
326              
327 60         209 $n_setter->set(undef);
328 60         171 $m_setter->set(\undef);
329              
330 60 100       214 if ($cmd eq 'perl') {
    100          
    100          
    50          
331             # Do nothing with the result.
332             } elsif ($cmd eq 'n') {
333 29         89 @$content = @result;
334             } elsif ($cmd eq 'filter') {
335 6         64 for my $i (0 .. $#$content) {
336 23 100 100     100 if (!$result[$i] xor $modes->{inverse_match}) {
337 12         25 undef $content->[$i];
338             }
339             }
340             } elsif ($cmd eq 'mark-line') {
341 7         22 @$markers = @result;
342             } else {
343 0         0 die "FATAL: Invalid command received for perl operation ($cmd).\n";
344             }
345              
346 60         192 for my $i (0 .. $#$content) {
347 201 100       509 if (not defined $content->[$i]) {
    100          
348 12         22 undef $markers->[$i];
349             } elsif (not defined $markers->[$i]) {
350 6         18 $markers->[$i] = ''; # We don't want undef here, as we will filter on it.
351             }
352             }
353 60         116 @$content = grep { defined } @$content;
  201         422  
354 60         119 @$markers = grep { defined } @$markers;
  201         1015  
355             }
356              
357             sub do_execute {
358 21     21 0 93 my ($content, $markers, $modes, $options, $cmd, $code) = @_;
359 21 100       82 $code = "use $code;" if $cmd eq 'M';
360 21         92 eval_in_safe_env($code, $options);
361 21 100       23116 if ($@) {
362 2         6 chomp($@);
363 2         20 my $scmd = '-'.($cmd =~ s/^(..)/-$1/r); # --execute or -M.
364 2         45 die "FATAL: Perl code failed in ${scmd}: ${@}\n";
365             }
366             }
367              
368             sub do_load {
369 3     3 0 28 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         19 my $abs_path = rel2abs($file);
374 3 50       204 print "Loading file: '$abs_path'\n" if $options->{debug_mode};
375 3 50       20 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 8     8 0 68 my ($content, $markers, $modes, $options) = @_;
386 8 50       41 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 6 100       9 if (${$modes->{comparator}} eq 'default') {
  6 100       23  
    50          
391 4         26 @$content = sort @$content;
392 2         12 } elsif (${$modes->{comparator}} eq 'numeric') {
393 17     17   194 no warnings "numeric";
  17         37  
  17         1489  
394 1         6 @$content = sort { $a <=> $b } @$content;
  5         18  
395 1         5 } elsif (${$modes->{comparator}} eq 'locale') {
396 17     17   8234 use locale;
  17         8864  
  17         103  
397 1         7 @$content = sort { $a cmp $b } @$content;
  21         31  
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       7 Dumper($modes->{comparator}) if ref $modes->{comparator};
405 2         4 my $cmp = $modes->{comparator};
406 2         10 my $sort = get_code_in_safe_env("sort { $cmp } \@_", $options,
407             'custom comparator');
408 2         54 @$content = $sort->(@$content);
409             }
410 8         44 @$markers = (0) x scalar(@$content);
411             }
412              
413             sub do_list_op {
414 1     1 0 7 my ($content, $markers, $modes, $options, $sub, $apply_on_markers) = @_;
415 1         5 @$content = &$sub(@$content);
416 1 50       5 if ($apply_on_markers) {
417 0         0 @$markers = &$sub(@$markers);
418             } else {
419 1         6 @$markers = (0) x scalar(@$content);
420             }
421             }
422              
423             sub do_tail {
424 4     4 0 19 my ($content, $markers, $modes, $options, $len) = @_;
425 4 100       12 $len = 10 unless $len;
426 4         13 splice @$content, 0, -$len;
427 4         18 splice @$markers, 0, -$len;
428             }
429              
430             sub do_head {
431 4     4 0 9 my ($content, $markers, $modes, $options, $len) = @_;
432 4 100       11 $len = 10 unless $len;
433 4 100       21 $len = -@$content if $len < -@$content;
434 4         13 splice @$content, $len;
435 4         17 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 15 my ($content, $markers, $modes, $options, $offset) = @_;
441 3         30 my $start = min(max(0, -$offset), $#$content);
442 3         20 my $end = max(min($#$content, $#$content + $offset), $#$content);
443 3         10 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         15 undef $content->[$i + $offset];
447 6         12 undef $markers->[$i + $offset];
448             }
449             }
450 3         10 @$content = grep { defined } @$content;
  12         28  
451 3         8 @$markers = grep { defined } @$markers;
  12         33  
452             }
453              
454             sub do_insert_marked {
455             # negative offset if we're inserting a line before the marker.
456 3     3 0 21 my ($content, $markers, $modes, $options, $offset, $line) = @_;
457 3         23 my @markers_temp = @$markers;
458 3         12 my @content_temp = @$content;
459 3         8 my $added = 0;
460 3         6 my $wrapped;
461 3 50       11 if (not $modes->{quote_regex}) {
462 3         14 $wrapped = get_code_in_safe_env("\"${line}\"", $options,
463             '--insert-marked');
464             }
465 3         33 for my $i (0 .. $#content_temp) {
466 12 100       74 next unless $markers_temp[$i];
467 6         11 my $r;
468 6 50       16 if ($modes->{quote_regex}) {
469 0         0 $r = $line;
470             } else {
471 6         14 $_ = $content_temp[$i];
472 6         23 $n_setter->set($i + 1);
473 6         24 $m_setter->set($markers_temp[$i]);
474 6         17 $line =~ s/(?:[^\\]|^)((:?\\\\)*")/\\$1/g;
475 6         14 $r = eval { $wrapped->() };
  6         51  
476 6 50       1307 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         21 my $target = $i + $offset + 1 + $added;
483 6 50       14 $target = $added if $target < $added;
484 6 50       15 $target = @$content if $target > @$content;
485 6         10 ++$added;
486 6         18 splice @$content, $target, 0, $r;
487 6         15 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 2     2 0 6 my ($content, $markers, $modes, $options, $replace_all) = @_;
505 2         4 my $name;
506 2 50 0     7 if (ref($modes->{file_name_ref}) eq 'SCALAR') {
    0          
507 2         5 $name = ${$modes->{file_name_ref}};
  2         5  
508             } elsif (ref($modes->{file_name_ref}) eq 'REF' and
509 0         0 ref(${$modes->{file_name_ref}}) eq 'SCALAR') {
510 0         0 $name = $${$modes->{file_name_ref}};
  0         0  
511             } else {
512             die 'INTERNAL ERROR: Invalid input marker: '.Dumper($modes->{file_name_ref})
513 0         0 ."\n";
514             }
515 2 50       6 if ($replace_all) {
516 0         0 @$content = ($name);
517 0         0 @$markers = (0);
518             } else {
519 2         5 unshift @$content, $name;
520 2         7 unshift @$markers, 0;
521             }
522             }
523              
524             sub do_line_count {
525 2     2 0 8 my ($content, $markers, $modes, $options) = @_;
526 2         6 @$content = (scalar(@$content));
527 2         5 @$markers = (0);
528             }
529              
530             sub do_cut {
531 5     5 0 15 my ($content, $markers, $modes, $options, $spec) = @_;
532 5         19 my $re = prepare_re($modes->{input_field}, $modes);
533 5 50       17 if ($options->{debug_mode}) {
534 5         15 print "Examples of the --cut operation:\n";
535 5         44 my @debug = map { [split $re] } @$content[0..min(5, $#$content)];
  12         99  
536 5 100       12 map { for ((@$_)[@$spec]) { $_ = "-->${_}<--" if $_ } } @debug;
  12         32  
  24         74  
537 5         11 local $, = $modes->{output_field};
538 5         23 local $\ = $options->{output_separator};
539 5         11 map { print @$_ } @debug;
  12         48  
540             }
541             @$content =
542             map {
543 5 100       16 join $modes->{output_field}, map { $_ ? $_ : '' } (split $re)[@$spec]
  12         68  
  24         114  
544             } @$content;
545             }
546              
547             sub do_paste {
548 0     0 0 0 my ($content, $markers, $modes, $options, $file) = @_;
549 0         0 my ($side_content, undef) = read_side_input($file, $options);
550 0         0 for my $i (0 .. $#$side_content) {
551 0         0 $content->[$i] .= $modes->{output_field}.$side_content->[$i];
552             }
553 0         0 for my $i ($#$side_content + 1 .. $#$content) {
554 0         0 $content->[$i] .= $modes->{output_field};
555             }
556 0 0       0 if (@$content > @$markers) {
557 0         0 splice @$markers, scalar(@$markers), 0, (0) x (@$content - @$markers);
558             }
559             }
560              
561             sub do_pivot {
562 7     7 0 31 my ($content, $markers, $modes, $options, $action) = @_;
563 7         14 my $m = 0;
564             # This is unused by the 'pivot' action, but it's not a huge issue.
565 7         25 my $re = prepare_re($modes->{input_field}, $modes);
566 7 100       34 if ($action eq 'transpose') {
    100          
    50          
567 2         5 $m = 0;
568             my @lines =
569 2         5 map { my $r = [split $re]; $m = max($m, scalar(@$r)); $r } @$content;
  6         34  
  6         20  
  6         14  
570             @$content =
571             map {
572 2         7 my $c = $_;
  5         8  
573 5   100     9 join $modes->{output_field}, map { $_->[$c] // '' } @lines;
  15         50  
574             } 0..($m - 1);
575             } elsif ($action eq 'pivot') {
576 4         10 $m = 1;
577 4         24 @$content = (join $modes->{output_field}, @$content);
578             } elsif ($action eq 'anti-pivot') {
579 1         3 @$content = map { split $re } @$content;
  3         23  
580 1         6 $m = @$content;
581             } else {
582 0         0 die "INTERNAL ERROR: unknown action for the pivot method: ${action}\n";
583             }
584 7         48 @$markers = (0) x $m;
585             }
586              
587             sub do_tee {
588 6     6 0 15 my ($content, $markers, $modes, $options, $file_name) = @_;
589 6         18 $file_name = maybe_interpolate($file_name, $modes, $options, 'tee');
590             # This missing_final_separator is not really an option, it is added in the
591             # modes struct by the 'process' method, specifically for this function.
592             write_side_output($file_name, $content, $modes->{missing_final_separator},
593 6         29 $options);
594             }
595              
596             sub do_shell {
597 6     6 0 22 my ($content, $markers, $modes, $options, $command, $arg) = @_;
598 6 50       20 die "INTERNAL ERROR: Unexpected command in do_tee: ${command}\n" unless $command eq 'shell';
599 6         22 $arg = maybe_interpolate($arg, $modes, $options, $command);
600             {
601 6         13 local $SIG{PIPE} = "IGNORE";
  6         136  
602 6 50       13413 open(my $pipe, '|-', $arg) or die "FATAL: Cannot execute command given to --${command}: $!\n";
603 6         310 write_handle($pipe, $content, $modes->{missing_final_separator}, $options);
604 6 50       9356 close $pipe or die "FATAL: Cannot close pipe for command given to --${command}: $!\n";
605             }
606             }
607              
608             sub do_eat {
609 1     1 0 19 my ($content, $markers, $modes, $options) = @_;
610 1         14 @$content = ();
611 1         31 @$markers = ();
612             }
613              
614             1;