Treex/Block/Write/BaseWriter.pm

filter: Statementstmt 63.5% 75 / 118 Branchbran 32.5% 13 / 40 Conditioncond 38.8% 7 / 18 MC/DCmcdc 0.0% 0 / 10 Subroutinesub 73.6% 14 / 19 Podpod n/a totaltotal 53.1% 109 / 205 CC 27 SCAR 25.5
CC
27
Cov
54%
_get_filename
36.6
_open_file_handle
16.5
_build_filenames
6.0
CRAP 12.8
« Treex/Core/DocumentReader.pm ↑ Summary Treex/Block/Read/BaseReader.pm »
1 package Treex::Block::Write::BaseWriter;
2 6 $Treex::Block::Write::BaseWriter::VERSION = '2.20151210';
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 (default is "-" meaning 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 sub _build_filenames {
79 0 ▶ my $self = shift;
Subroutine _build_filenames: not called CC=2 SCAR=17.9
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 # Return 1 if the document should be compressed (and '.gz' added to its extension).
85 sub _compress_document {
86  
87 1 ▶ my ( $self, $document ) = @_;
Subroutine _compress_document: called CC=3 SCAR=12.7
88 1 my $compress = 0;
89  
90 1 ▶ if ( defined $self->compress ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $self->compress) { } 1 0 1
elsif (defined $document->compress) { } 0 0 0
91 1 $compress = $self->compress;
92 }
93 elsif ( defined $document->compress ) {
94 0 $compress = $document->compress;
95 }
96  
97 1 return $compress;
98 }
99  
100 # Return the correct extension for the given document, according to the default file extension
101 # for the format and the compression settings.
102 sub _document_extension {
103 1 ▶ my ( $self, $document ) = @_;
Subroutine _document_extension: called CC=2 SCAR=7.2
104 1 ▶ return $self->extension . ( $self->_compress_document($document) ? '.gz' : '' );
Branch: 1 branch
BranchTrueFalseTotal
$self->_compress_document($document) ? : 0 1 1
105 }
106  
107 # This just returns the next filename from the list given in the 'to' parameter.
108 sub _get_next_filename {
109
110 0 ▶ my ($self) = @_;
Subroutine _get_next_filename: not called CC=1 SCAR=6.9
111
112 0 my ( $next_filename, @rest_filenames ) = @{ $self->_filenames };
113 0 $self->_set_filenames( \@rest_filenames );
114 0 return $next_filename;
115 }
116  
117  
118 # This returns the correct file name for the next document, taking the path, file_stem,
119 # stem_suffix and to parameters into account.
120 sub _get_filename {
121  
122 1 ▶ my ( $self, $document ) = @_;
Subroutine _get_filename: called CC=11 SCAR=36.0
123 1 my $filename = $document->full_filename . $self->_document_extension($document);
124  
125 1 ▶ if ( defined $self->path ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->path) 0 1 1
126 0 $document->set_path( $self->path );
127 0 $filename = $document->full_filename . $self->_document_extension($document);
128 }
129 1 ▶ if ( defined $self->file_stem ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->file_stem) 0 1 1
130 0 $document->set_file_stem( $self->file_stem );
131 0 $filename = $document->full_filename . $self->_document_extension($document);
132 }
133 1 ▶ if ( defined $self->stem_suffix ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->stem_suffix) 0 1 1
134 0 ▶ my $origstem = defined $self->file_stem
Branch: 1 branch
BranchTrueFalseTotal
defined $self->file_stem ? : 0 0 0
135 ? $self->file_stem : $document->file_stem;
136 0 $document->set_file_stem( $origstem . $self->stem_suffix );
137 0 $filename = $document->full_filename . $self->_document_extension($document);
138 }
139  
140 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
141  
142 1 my $next_filename = $self->_get_next_filename();
143  
144 1 ▶ if ( !defined $next_filename ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $next_filename) { } 0 1 1
145 0 log_warn "There are more documents to save than filenames given ("
146 . $self->to . "). Falling back to the filename filled in by a DocumentReader ($filename).";
147 }
148 else {
149 1 ▶ $filename = ( defined $self->path ? $self->path : '' ) . $next_filename;
Branch: 1 branch
BranchTrueFalseTotal
defined $self->path ? : 0 1 1
150 }
151 }
152
153 1 ▶ if (defined $self->substitute){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->substitute) 0 1 1
154 0 my $eval_string = '$filename =~ s' . $self->substitute . ';1;';
155 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
156 # An alternative implementation without stringy eval is commented below (see r14228),
157 # but it cannot handle $1 in rexex, e.g.
158 # Write::Treex substitute='{(.+)-(.+)}{$2-$1}
159  
160 0 my ($fn, $directories) = fileparse($filename, $self->_document_extension($document));
161 0 $directories =~ s{/$}{};
162 0 $document->set_path($directories);
163 0 $document->set_file_stem($fn);
164 0 $document->set_file_number('');
165 }
166  
167 1 return $filename;
168 }
169  
170 # my $regex = $self->substitute;
171 # my $delimiter = ",";
172 # my $lc = ($regex =~ /i$/);
173 #
174 # # regex can have format {<old>}{<new>}
175 # if ( $regex =~ /^{(.*)}{(.*)}i?$/ ) {
176 # $regex =~ s/^{(.*)}{(.*)}i?$/$1,$2/;
177 # }
178 # # otherwise regex should have format /<original>/<replacement>/, where "/" is delimiter of a choice
179 # else {
180 # $delimiter = substr($regex, 0, 1);
181 # $regex =~ s/^\Q$delimiter\E(.*)\Q$delimiter\E$/$1/;
182 # }
183 #
184 # my @old_new_regex = split /\Q$delimiter\E/, $regex;
185 # log_fatal "Incorrect form of regex $self->substitute" if (scalar @old_new_regex != 2);
186 # $filename =~ s/$old_new_regex[0]/$old_new_regex[1]/i if $lc;
187 # $filename =~ s/$old_new_regex[0]/$old_new_regex[1]/ if !$lc;
188  
189  
190  
191 # Default process_document method for all Writer blocks.
192 override 'process_document' => sub {
193 1 ▶ my ( $self, $document ) = @_;
Subroutine __ANON__: called CC=3 SCAR=11.4
194  
195 # set _file_handle properly (this MUST be called if process_document is overridden)
196 1 $self->_prepare_file_handle($document);
197
198 1 $self->_do_before_process($document);
199  
200 # call the original process_document with _file_handle set
201 1 $self->_do_process_document($document);
202  
203 1 $self->_do_after_process($document);
204
205 # This is not needed as the current file handle will be closed when opening the next file
206 # (in _prepare_file_handle) or at the end of the process.
207 # However, commenting the following line leads to undeterministic errors (e.g. in en2cs)
208 # UNFINISHED JOB e2c-news-dev2009-job001 PRODUCED EPILOG.
209 # On the other hand, always closing the handle prevents
210 # treex Read::Treex from=@my.list Write::Sentences to=out.txt
211 # As a workaround I decided to close the handle only in "treex -p".
212 # Martin Popel 2014
213 #$self->_close_file_handle() if $self->scenario->runner->jobindex;
214 ###
215 # For some reason the scenario->runner was not defined in some cases, so
216 # we test it too
217 # Dusan Varis 2014
218 1 ▶ $self->_close_file_handle() if ($self->scenario->runner && $self->scenario->runner->jobindex);
Branch: 1 branch
BranchTrueFalseTotal
if $self->scenario->runner and $self->scenario->runner->jobindex 0 1 1
Condition33%1/3
$self->scenario->runner and $self->scenario->runner->jobindex
!ll&&!rl&&r
100
MC/DC0%0/2
$self->scenario->runner and $self->scenario->runner->jobindex
$self->scenario->runner $self->scenario->runner->jobindex
Truth table33%1/3
A and B
A= $self->scenario->runnerB= $self->scenario->runner->jobindex
ABresult
0X0
100
111
219 # or if $self->scenario->runner->isa("Treex::Core::Parallel::Node")?
220  
221 1 return;
222 6 };
223  
224 sub _do_process_document
225 {
226 0 ▶ my ($self, $document) = @_;
Subroutine _do_process_document: not called CC=1 SCAR=6.9
227  
228 0 $self->Treex::Core::Block::process_document($document);
229  
230 0 return;
231 }
232  
233 sub _do_before_process {
234 0 ▶ my ($self, $document) = @_;
Subroutine _do_before_process: not called CC=1 SCAR=6.9
235  
236 0 return;
237 }
238  
239 sub _do_after_process {
240 0 ▶ my ($self, $document) = @_;
Subroutine _do_after_process: not called CC=1 SCAR=6.9
241  
242 0 return;
243 }
244  
245 override 'process_end' => sub {
246 1 ▶ my $self = shift;
Subroutine __ANON__: called CC=1 SCAR=0.0
247  
248 1 $self->_close_file_handle();
249  
250 1 return;
251 6 };
252  
253 sub _close_file_handle
254 {
255 2 ▶ my $self = shift;
Subroutine _close_file_handle: called CC=4 SCAR=17.2
256  
257 #log_warn("CLOSE FH: " . $self->_file_handle . "; LAST: " . $self->_last_filename);
258  
259 # close the previous one (except if it's stdout)
260 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
261 && ( !defined $self->_last_filename || $self->_last_filename ne "-" ) ) {
262 #log_warn("CLOSE - file handle - REAL");
263 0 close $self->_file_handle;
264 0 $self->_set_file_handle(undef);
265 }
266  
267 2 return;
268 }
269  
270 # Prepare the file handle for the next file to be processed.
271 # This MUST be called in all process_document overrides.
272 sub _prepare_file_handle {
273 1 ▶ my ( $self, $document ) = @_;
Subroutine _prepare_file_handle: called CC=4 SCAR=15.0
274  
275 1 my $filename = $self->_get_filename($document);
276
277 #log_warn("PREPARE FILENAME: $filename; LAST: " . $self->_last_filename);
278 #log_warn(int(defined $self->_last_filename) . " + " . int($filename eq $self->_last_filename) . " + " . $filename ne "__FAKE_OUTPUT__");
279  
280 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
281  
282 # nothing to do, keep writing to the old filename
283 }
284 else {
285 # need to switch output stream
286  
287 1 $self->_close_file_handle();
288  
289 # open the new output stream
290 1 log_info "Saving to $filename";
291 1 $self->_set_file_handle( $self->_open_file_handle($filename) );
292 }
293  
294 # remember last used filename
295 1 $self->_set_last_filename($filename);
296 1 return;
297 }
298  
299 # Open the given file handle (including compressed variants and standard output).
300 sub _open_file_handle {
301 1 ▶ my ( $self, $filename ) = @_;
Subroutine _open_file_handle: called CC=5 SCAR=28.1
302  
303 1 ▶ if ( $filename eq "-" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($filename eq "-") 1 0 1
304 1 STDOUT->autoflush(1);
305 1 return \*STDOUT;
306 }
307  
308 0 my $opn;
309 my $hdl;
310  
311 # file might not recognize some files!
312 0 ▶ if ( $filename =~ /\.gz$/ ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($filename =~ /\.gz$/) { } 0 0 0
elsif ($filename =~ /\.bz2$/) { } 0 0 0
313 0 $opn = "gzip -c > '$filename'";
314 }
315 elsif ( $filename =~ /\.bz2$/ ) {
316 0 $opn = "bzip2 > '$filename'";
317 }
318  
319 0 mkpath( dirname($filename) );
320 0 ▶ if ($opn) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opn) { } 0 0 0
321 0 open ( $hdl, '|-', $opn );
322 }
323 else {
324 0 open ( $hdl, '>', $filename );
325 }
326
327 0 $hdl->autoflush(1);
328 0 return $hdl;
329 }
330  
331 6 1;
332  
333 __END__
334  
335 =encoding utf-8
336  
337 =head1 NAME
338  
339 Treex::Block::Write::BaseWriter
340  
341 =head1 VERSION
342  
343 version 2.20151210
344  
345 =head1 DESCRIPTION
346  
347 This is the base class for document writer blocks in Treex.
348  
349 It handles selecting and opening the output files, allowing for output of one-file per document.
350 The output file name(s) may be set in several ways (standard output may also be used as a file
351 with the name '-'); GZip file compression is supported.
352  
353 Other features, such as writing all documents to one file or setting character encoding,
354 are enabled in L<Treex::Block::Write::BaseTextWriter>.
355  
356 =head1 PARAMETERS
357  
358 =over
359  
360 =item C<to>
361  
362 Space-or-comma-separated list of output file names.
363  
364 =item C<file_stem>, C<path>
365  
366 These override the respective attributes in documents
367 (filled in by a L<DocumentReader|Treex::Core::DocumentReader>),
368 which are used for generating output file names.
369  
370 =item C<stem_suffix>
371  
372 A string to append after C<file_stem>.
373  
374 =item C<compress>
375  
376 If set to 1, the output files are compressed using GZip (if C<to> is used to set
377 file names, the names must also contain the ".gz" suffix).
378  
379 =item C<clobber>
380  
381 If set to 1, existing destination files will be overwritten.
382  
383 =back
384  
385 =head1 DERIVED CLASSES
386  
387 The derived classes should just use C<print { $self->_file_handle } "output text">, the
388 base class will take care of opening the proper file.
389  
390 All derived classes that override the C<process_document> method directly must call
391 the C<_prepare_file_handle> method to gain access to the correct file handle.
392  
393 The C<extension> parameter should be overriden with the default file extension
394 for the given file type.
395  
396 =head1 TODO
397  
398 =over
399  
400 =item *
401  
402 Set C<compress> if file name contains .gz or .bz2? Add .gz to extension to even for file names set with
403 the C<to> parameter if C<compress> is set to true?
404  
405 =item *
406  
407 Possibly rearrange somehow so that the C<_prepare_file_handle> method is not needed. The problem is that
408 if this was a Moose role, it would have to be applied only after an override to C<process_document>. The
409 Moose C<inner> and C<augment> operators are a possibility, but would not remove a need for a somewhat
410 non-standard behavior in derived classes (one could not just override C<process_document>, but would
411 have to C<augment> it).
412  
413 =back
414
415 =head1 AUTHORS
416  
417 Ondřej Dušek <odusek@ufal.mff.cuni.cz>
418  
419 Martin Popel <popel@ufal.mff.cuni.cz>
420  
421 Ondřej Bojar <bojar@ufal.mff.cuni.cz>
422  
423 =head1 COPYRIGHT AND LICENSE
424  
425 Copyright © 2011-2012 by Institute of Formal and Applied Linguistics, Charles University in Prague
426  
427 This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
« Treex/Core/DocumentReader.pm ↑ Summary Treex/Block/Read/BaseReader.pm »