Treex/Block/Write/BaseWriter.pm

filter: Statementstmt 63.4% 78 / 123 Branchbran 31.8% 14 / 44 Conditioncond 30.3% 10 / 33 MC/DCmcdc 0.0% 0 / 17 Subroutinesub 75.0% 15 / 20 Podpod 0.0% 0 / 1 totaltotal 49.1% 117 / 238 CC 34 SCAR 26.6
CC
34
Cov
51%
_get_filename
36.6
BUILD
24.9
_open_file_handle
16.5
CRAP 14.3
« Treex/Block/Read/BaseSplitterRole.pm ↑ Summary Treex/Block/Write/Sentences.pm »
1 package Treex::Block::Write::BaseWriter;
2 6 $Treex::Block::Write::BaseWriter::VERSION = '2.20210102';
3 6 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 6 ▶use Treex::Core::Common;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 6 ▶use autodie; # die if the output file cannot be opened
Subroutine BEGIN: called CC=1 SCAR=0.0
6 6 ▶use File::Path;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 6 ▶use File::Basename;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 6 ▶use IO::Handle;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10  
11 6 extends 'Treex::Core::Block';
12  
13 6 has extension => (
14 isa => 'Str',
15 is => 'ro',
16 documentation => 'Default extension for the output file type.',
17 default => ''
18 );
19  
20 6 has compress => (
21 is => 'rw',
22 isa => 'Bool',
23 documentation => 'Compression to .gz. Defaults to document->compress, or 0.'
24 );
25  
26 6 has [qw(file_stem path)] => (
27 isa => 'Str',
28 is => 'rw',
29 documentation => 'These provide a possibility of creating output file names from input file names.',
30 );
31  
32 6 has stem_suffix => (
33 isa => 'Str',
34 is => 'ro',
35 documentation => 'A suffix to append after file_stem.',
36 );
37  
38 6 has to => (
39 isa => 'Str',
40 is => 'rw',
41 documentation => 'The destination filename ("-" means the standard output; '
42 . 'use "." for the filename inherited from upstream blocks).',
43 );
44  
45 # Experimental feature. TODO: reconsider the design and add tests
46 6 has substitute => (
47 isa => 'Str',
48 is => 'ro',
49 documentation => 'A file loaded from dir1 can be saved to dir2 by substitute={dir1}{dir2}. '
50 . 'You can use regex substituions, e.g. substitute={dir(\d+)/file(\d+).treex}{f\1-\2.streex}i',
51 );
52  
53  
54 6 has _filenames => (
55 isa => 'ArrayRef[Str]',
56 is => 'rw',
57 builder => '_build_filenames',
58 writer => '_set_filenames',
59 lazy_build => 1,
60 documentation => 'Array of filenames where to save the documents if using multiple files;'
61 . ' automatically initialized from the attribute "to".',
62 );
63  
64 6 has _file_handle => (
65 isa => 'Maybe[FileHandle]',
66 is => 'rw',
67 writer => '_set_file_handle',
68 documentation => 'The open output file handle.',
69 );
70  
71 6 has _last_filename => (
72 isa => 'Str',
73 is => 'rw',
74 writer => '_set_last_filename',
75 documentation => 'Last output filename, to keep stream open if unchanged.',
76 );
77  
78 0 ▶sub _build_filenames {
Subroutine _build_filenames: not called CC=2 SCAR=17.9
79 0 my $self = shift;
80 0 ▶ log_fatal "Parameter 'to' must be defined!" if !defined $self->to;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->to 0 0 0
81 0 return [ split /[ ,]+/, $self->to ];
82 }
83  
84 1 ▶sub BUILD {
Subroutine BUILD: called CC=7 SCAR=32.1
Pod undocumented
85 1 my ($self) = @_;
86 # fail soon if running under treex -p
87 1 ▶ if ($self->scenario && $self->scenario->runner && $self->scenario->runner->jobindex) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->scenario and $self->scenario->runner and $self->scenario->runner->jobindex) 0 1 1
Condition33%2/6
$self->scenario and $self->scenario->runner and $self->scenario->runner->jobindex
!ll&&!rl&&r
100
$self->scenario and $self->scenario->runner
!ll&&!rl&&r
010
MC/DC0%0/3
$self->scenario and $self->scenario->runner and $self->scenario->runner->jobindex
$self->scenario $self->scenario->runner $self->scenario->runner->jobindex
Truth table25%1/4
A and B and C
A= $self->scenarioB= $self->scenario->runnerC= $self->scenario->runner->jobindex
ABCresult
0XX0
10X0
1100
1111
88 # and if the output file is specified
89 0 ▶ if (defined $self->to and $self->to ne '-' and $self->to ne '.') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->to and $self->to ne "-" and $self->to ne ".") 0 0 0
Condition0%0/6
defined $self->to and $self->to ne "-" and $self->to ne "."
!ll&&!rl&&r
000
defined $self->to and $self->to ne "-"
!ll&&!rl&&r
000
MC/DC0%0/3
defined $self->to and $self->to ne "-" and $self->to ne "."
defined $self->to $self->to ne "-" $self->to ne "."
Truth table0%0/4
A and B and C
A= defined $self->toB= $self->to ne "-"C= $self->to ne "."
ABCresult
0XX0
10X0
1100
1111
90 0 log_fatal "Merging writer output with treex -p into file(s) (except for stdout) "
91 . "is not supported. to=" . $self->to;
92 }
93 }
94 1 return;
95 }
96  
97 # Return 1 if the document should be compressed (and '.gz' added to its extension).
98 1 ▶sub _compress_document {
Subroutine _compress_document: called CC=3 SCAR=12.7
99  
100 1 my ( $self, $document ) = @_;
101 1 my $compress = 0;
102  
103 1 ▶ if ( defined $self->compress ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $self->compress) { } 1 0 1
elsif (defined $document->compress) { } 0 0 0
104 1 $compress = $self->compress;
105 }
106 elsif ( defined $document->compress ) {
107 0 $compress = $document->compress;
108 }
109  
110 1 return $compress;
111 }
112  
113 # Return the correct extension for the given document, according to the default file extension
114 # for the format and the compression settings.
115 1 ▶sub _document_extension {
Subroutine _document_extension: called CC=2 SCAR=7.2
116 1 my ( $self, $document ) = @_;
117 1 ▶ return $self->extension . ( $self->_compress_document($document) ? '.gz' : '' );
Branch: 1 branch
BranchTrueFalseTotal
$self->_compress_document($document) ? : 0 1 1
118 }
119  
120 # This just returns the next filename from the list given in the 'to' parameter.
121 0 ▶sub _get_next_filename {
Subroutine _get_next_filename: not called CC=1 SCAR=6.9
122  
123 0 my ($self) = @_;
124  
125 0 my ( $next_filename, @rest_filenames ) = @{ $self->_filenames };
126 0 $self->_set_filenames( \@rest_filenames );
127 0 return $next_filename;
128 }
129  
130  
131 # This returns the correct file name for the next document, taking the path, file_stem,
132 # stem_suffix and to parameters into account.
133 1 ▶sub _get_filename {
Subroutine _get_filename: called CC=11 SCAR=36.0
134  
135 1 my ( $self, $document ) = @_;
136 1 my $filename = $document->full_filename . $self->_document_extension($document);
137  
138 1 ▶ if ( defined $self->path ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->path) 0 1 1
139 0 $document->set_path( $self->path );
140 0 $filename = $document->full_filename . $self->_document_extension($document);
141 }
142 1 ▶ if ( defined $self->file_stem ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->file_stem) 0 1 1
143 0 $document->set_file_stem( $self->file_stem );
144 0 $filename = $document->full_filename . $self->_document_extension($document);
145 }
146 1 ▶ if ( defined $self->stem_suffix ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->stem_suffix) 0 1 1
147 0 ▶ my $origstem = defined $self->file_stem
Branch: 1 branch
BranchTrueFalseTotal
defined $self->file_stem ? : 0 0 0
148 ? $self->file_stem : $document->file_stem;
149 0 $document->set_file_stem( $origstem . $self->stem_suffix );
150 0 $filename = $document->full_filename . $self->_document_extension($document);
151 }
152  
153 1 ▶ if ( defined( $self->to ) && ( $self->to ne '.' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->to and $self->to ne ".") 1 0 1
Condition33%1/3
defined $self->to and $self->to ne "."
!ll&&!rl&&r
001
MC/DC0%0/2
defined $self->to and $self->to ne "."
defined $self->to $self->to ne "."
Truth table33%1/3
A and B
A= defined $self->toB= $self->to ne "."
ABresult
0X0
100
111
154  
155 1 my $next_filename = $self->_get_next_filename();
156  
157 1 ▶ if ( !defined $next_filename ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $next_filename) { } 0 1 1
158 0 log_warn "There are more documents to save than filenames given ("
159 . $self->to . "). Falling back to the filename filled in by a DocumentReader ($filename).";
160 }
161 else {
162 1 ▶ $filename = ( defined $self->path ? $self->path : '' ) . $next_filename;
Branch: 1 branch
BranchTrueFalseTotal
defined $self->path ? : 0 1 1
163 }
164 }
165  
166 1 ▶ if (defined $self->substitute){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->substitute) 0 1 1
167 0 my $eval_string = '$filename =~ s' . $self->substitute . ';1;';
168 0 ▶ eval $eval_string or log_fatal "Failed to eval $eval_string"; ## no critic qw(BuiltinFunctions::ProhibitStringyEval)
Branch: 1 branch
BranchTrueFalseTotal
eval $eval_string or log_fatal("Failed to eval $eval_string") 0 0 0
169 # An alternative implementation without stringy eval is commented below (see r14228),
170 # but it cannot handle $1 in rexex, e.g.
171 # Write::Treex substitute='{(.+)-(.+)}{$2-$1}
172  
173 0 my ($fn, $directories) = fileparse($filename, $self->_document_extension($document));
174 0 $directories =~ s{/$}{};
175 0 $document->set_path($directories);
176 0 $document->set_file_stem($fn);
177 0 $document->set_file_number('');
178 }
179  
180 1 return $filename;
181 }
182  
183 # my $regex = $self->substitute;
184 # my $delimiter = ",";
185 # my $lc = ($regex =~ /i$/);
186 #
187 # # regex can have format {<old>}{<new>}
188 # if ( $regex =~ /^{(.*)}{(.*)}i?$/ ) {
189 # $regex =~ s/^{(.*)}{(.*)}i?$/$1,$2/;
190 # }
191 # # otherwise regex should have format /<original>/<replacement>/, where "/" is delimiter of a choice
192 # else {
193 # $delimiter = substr($regex, 0, 1);
194 # $regex =~ s/^\Q$delimiter\E(.*)\Q$delimiter\E$/$1/;
195 # }
196 #
197 # my @old_new_regex = split /\Q$delimiter\E/, $regex;
198 # log_fatal "Incorrect form of regex $self->substitute" if (scalar @old_new_regex != 2);
199 # $filename =~ s/$old_new_regex[0]/$old_new_regex[1]/i if $lc;
200 # $filename =~ s/$old_new_regex[0]/$old_new_regex[1]/ if !$lc;
201  
202  
203  
204 # Default process_document method for all Writer blocks.
205 1 ▶override 'process_document' => sub {
Subroutine __ANON__: called CC=4 SCAR=15.2
206 1 my ( $self, $document ) = @_;
207  
208 # set _file_handle properly (this MUST be called if process_document is overridden)
209 1 $self->_prepare_file_handle($document);
210  
211 1 $self->_do_before_process($document);
212  
213 # call the original process_document with _file_handle set
214 1 $self->_do_process_document($document);
215  
216 1 $self->_do_after_process($document);
217  
218 # This is not needed as the current file handle will be closed when opening the next file
219 # (in _prepare_file_handle) or at the end of the process.
220 # However, commenting the following line leads to undeterministic errors (e.g. in en2cs)
221 # UNFINISHED JOB e2c-news-dev2009-job001 PRODUCED EPILOG.
222 # On the other hand, always closing the handle prevents
223 # treex Read::Treex from=@my.list Write::Sentences to=out.txt
224 # As a workaround I decided to close the handle only in "treex -p".
225 # Martin Popel 2014
226 #$self->_close_file_handle() if $self->scenario->runner->jobindex;
227 ###
228 # For some reason the scenario->runner was not defined in some cases, so
229 # we test it too
230 # Dusan Varis 2014
231 # Also $self->scenario may not be defined if the writer is instantiated directly from Perl.
232 1 ▶ $self->_close_file_handle() if $self->scenario && $self->scenario->runner && $self->scenario->runner->jobindex;
Branch: 1 branch
BranchTrueFalseTotal
if $self->scenario and $self->scenario->runner and $self->scenario->runner->jobindex 0 1 1
Condition33%2/6
$self->scenario and $self->scenario->runner and $self->scenario->runner->jobindex
!ll&&!rl&&r
100
$self->scenario and $self->scenario->runner
!ll&&!rl&&r
010
MC/DC0%0/3
$self->scenario and $self->scenario->runner and $self->scenario->runner->jobindex
$self->scenario $self->scenario->runner $self->scenario->runner->jobindex
Truth table25%1/4
A and B and C
A= $self->scenarioB= $self->scenario->runnerC= $self->scenario->runner->jobindex
ABCresult
0XX0
10X0
1100
1111
233 # or if $self->scenario->runner->isa("Treex::Core::Parallel::Node")?
234  
235 1 return;
236 6 };
237  
238 sub _do_process_document
239 0 ▶{
Subroutine _do_process_document: not called CC=1 SCAR=6.9
240 0 my ($self, $document) = @_;
241  
242 0 $self->Treex::Core::Block::process_document($document);
243  
244 0 return;
245 }
246  
247 0 ▶sub _do_before_process {
Subroutine _do_before_process: not called CC=1 SCAR=6.9
248 0 my ($self, $document) = @_;
249  
250 0 return;
251 }
252  
253 0 ▶sub _do_after_process {
Subroutine _do_after_process: not called CC=1 SCAR=6.9
254 0 my ($self, $document) = @_;
255  
256 0 return;
257 }
258  
259 1 ▶override 'process_end' => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
260 1 my $self = shift;
261  
262 1 $self->_close_file_handle();
263  
264 1 return;
265 6 };
266  
267 sub _close_file_handle
268 2 ▶{
Subroutine _close_file_handle: called CC=4 SCAR=17.2
269 2 my $self = shift;
270  
271 #log_warn("CLOSE FH: " . $self->_file_handle . "; LAST: " . $self->_last_filename);
272  
273 # close the previous one (except if it's stdout)
274 2 ▶ if ( defined $self->_file_handle
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->_file_handle and !defined($self->_last_filename) || $self->_last_filename ne "-") 0 2 2
Condition50%3/6
defined $self->_file_handle and !defined($self->_last_filename) || $self->_last_filename ne "-"
!ll&&!rl&&r
110
not defined $self->_last_filename or $self->_last_filename ne "-"
l!l&&r!l&&!r
001
MC/DC0%0/3
defined $self->_file_handle and !defined($self->_last_filename) || $self->_last_filename ne "-"
defined $self->_file_handle not defined $self->_last_filename $self->_last_filename ne "-"
Truth table50%2/4
A and not(B) or C
A= defined $self->_file_handleB= not defined $self->_last_filenameC= $self->_last_filename ne "-"
ABCresult
0XX0
1000
11X1
1011
275 && ( !defined $self->_last_filename || $self->_last_filename ne "-" ) ) {
276 #log_warn("CLOSE - file handle - REAL");
277 0 close $self->_file_handle;
278 0 $self->_set_file_handle(undef);
279 }
280  
281 2 return;
282 }
283  
284 # Prepare the file handle for the next file to be processed.
285 # This MUST be called in all process_document overrides.
286 1 ▶sub _prepare_file_handle {
Subroutine _prepare_file_handle: called CC=4 SCAR=15.0
287 1 my ( $self, $document ) = @_;
288  
289 1 my $filename = $self->_get_filename($document);
290  
291 #log_warn("PREPARE FILENAME: $filename; LAST: " . $self->_last_filename);
292 #log_warn(int(defined $self->_last_filename) . " + " . int($filename eq $self->_last_filename) . " + " . $filename ne "__FAKE_OUTPUT__");
293  
294 1 ▶ if ( defined $self->_last_filename && $filename eq $self->_last_filename && $filename !~ "__FAKE_OUTPUT__") {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->_last_filename and $filename eq $self->_last_filename and not $filename =~ /__FAKE_OUTPUT__/) { } 0 1 1
Condition33%2/6
defined $self->_last_filename and $filename eq $self->_last_filename and not $filename =~ /__FAKE_OUTPUT__/
!ll&&!rl&&r
100
defined $self->_last_filename and $filename eq $self->_last_filename
!ll&&!rl&&r
100
MC/DC0%0/3
defined $self->_last_filename and $filename eq $self->_last_filename and not $filename =~ /__FAKE_OUTPUT__/
defined $self->_last_filename $filename eq $self->_last_filename not $filename =~ /__FAKE_OUTPUT__/
Truth table25%1/4
A and B and not(C)
A= defined $self->_last_filenameB= $filename eq $self->_last_filenameC= not $filename =~ /__FAKE_OUTPUT__/
ABCresult
0XX0
10X0
1100
1111
295  
296 # nothing to do, keep writing to the old filename
297 }
298 else {
299 # need to switch output stream
300  
301 1 $self->_close_file_handle();
302  
303 # open the new output stream
304 1 log_info "Saving to $filename";
305 1 $self->_set_file_handle( $self->_open_file_handle($filename) );
306 }
307  
308 # remember last used filename
309 1 $self->_set_last_filename($filename);
310 1 return;
311 }
312  
313 # Open the given file handle (including compressed variants and standard output).
314 1 ▶sub _open_file_handle {
Subroutine _open_file_handle: called CC=5 SCAR=28.1
315 1 my ( $self, $filename ) = @_;
316  
317 1 ▶ if ( $filename eq "-" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($filename eq "-") 1 0 1
318 1 STDOUT->autoflush(1);
319 1 return \*STDOUT;
320 }
321  
322 0 my $opn;
323 my $hdl;
324  
325 # file might not recognize some files!
326 0 ▶ if ( $filename =~ /\.gz$/ ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($filename =~ /\.gz$/) { } 0 0 0
elsif ($filename =~ /\.bz2$/) { } 0 0 0
327 0 $opn = "gzip -c > '$filename'";
328 }
329 elsif ( $filename =~ /\.bz2$/ ) {
330 0 $opn = "bzip2 > '$filename'";
331 }
332  
333 0 mkpath( dirname($filename) );
334 0 ▶ if ($opn) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opn) { } 0 0 0
335 0 open ( $hdl, '|-', $opn );
336 }
337 else {
338 0 open ( $hdl, '>', $filename );
339 }
340  
341 0 $hdl->autoflush(1);
342 0 return $hdl;
343 }
344  
345 6 1;
346  
347 __END__
« Treex/Block/Read/BaseSplitterRole.pm ↑ Summary Treex/Block/Write/Sentences.pm »