DBBrowser/GetContent/Parse.pm untested

filter: Statementstmt 0.0% 0 / 315 Branchbran 0.0% 0 / 64 Conditioncond 0.0% 0 / 22 MC/DCmcdc 0.0% 0 / 14 Subroutinesub 0.0% 0 / 23 Podpod 0.0% 0 / 7 totaltotal 0.0% 0 / 445 CC 33 SCAR 47.0
CC
33
Cov
0%
parse_with_template
272.0
parse_with_Spreadsheet_Read
132.0
parse_with_split
30.0
CRAP 109.8
1 package # hide from PAUSE
2 App::DBBrowser::GetContent::Parse;
3  
4 use warnings;
5 use strict;
6 use 5.016;
7  
8 use Encode qw( decode );
9  
10 use Encode::Locale qw();
11 #use Spreadsheet::Read qw( ReadData rows ); # required
12 #use String::Unescape qw( unescape ); # required
13 #use Text::CSV_XS qw(); # required
14  
15 use Term::Choose qw();
16 use Term::Choose::LineFold qw( line_fold );
17 use Term::Choose::Screen qw( clear_screen );
18 use Term::Choose::Util qw( get_term_size unicode_sprintf insert_sep );
19 use Term::Form qw();
20  
21 use App::DBBrowser::Options;
22 use App::DBBrowser::Options::ReadWrite;
23  
24  
25 sub new {
26 my ( $class, $info, $options, $d ) = @_;
27 my $sf = {
28 i => $info,
29 o => $options,
30 d => $d
31 };
32 bless $sf, $class;
33 }
34  
35  
36 sub __print_waiting_str {
37 my ( $sf ) = @_;
38 print clear_screen;
39 print 'Parsing file ... ' . "\r";
40 }
41  
42  
43 sub parse_with_Text_CSV {
44 my ( $sf, $sql, $fh ) = @_;
45 my $ax = App::DBBrowser::Auxil->new( $sf->{i}, $sf->{o}, $sf->{d} );
46 my $tc = Term::Choose->new( $sf->{i}{tc_default} );
47 $sf->__print_waiting_str;
48 seek $fh, 0, 0;
49 require String::Unescape;
50 my $options = {
51 map { $_ => String::Unescape::unescape( $sf->{o}{csv_in}{$_} ) }
52 # grep length: keep the default value if the option is set to ''
53 grep { length $sf->{o}{csv_in}{$_} }
54 keys %{$sf->{o}{csv_in}}
55 };
56 require Text::CSV_XS;
57 my $csv = Text::CSV_XS->new( $options ) or die Text::CSV_XS->error_diag();
58 $csv->callbacks( error => sub {
59 my ( $code, $str, $pos, $rec, $fld ) = @_;
60 if ( $code == 2012 ) {
61 # no warnings for end of data.
62 # 2012 "EOF - End of data in parsing input stream"
63 }
64 else {
65 my $error_input = $csv->error_input() // 'No Error Input defined.';
66 my $prompt = "Error Input:";
67 $error_input =~ s/\R/ /g;
68 my $info = "Close with ENTER\nText::CSV_XS\n$code $str\nrecord:$rec field:$fld position:$pos\n";
69 $tc->choose(
70 [ line_fold( $error_input, { join => 0 } ) ],
71 { info => $info, prompt => $prompt }
72 );
73 $ax->print_sql_info( $info );
74 return;
75 }
76 } );
77 my $rows_of_cols = $csv->getline_all( $fh );
78 $sql->{insert_args} = $rows_of_cols;
79 return 1;
80 }
81  
82  
83 sub parse_with_split {
84 my ( $sf, $sql, $fh ) = @_;
85 $sf->__print_waiting_str;
86 my $rows_of_cols = [];
87 local $/;
88 seek $fh, 0, 0;
89 my $record_lead = $sf->{o}{split}{record_l_trim};
90 my $record_trail = $sf->{o}{split}{record_r_trim};
91 my $field_lead = $sf->{o}{split}{field_l_trim};
92 my $field_trail = $sf->{o}{split}{field_r_trim};
93 for my $row ( split /$sf->{o}{split}{record_sep}/, <$fh> ) {
94 $row =~ s/^$record_lead// if length $record_lead;
95 $row =~ s/$record_trail\z// if length $record_trail;
96 push @$rows_of_cols, [
97 map {
98 s/^$field_lead// if length $field_lead;
99 s/$field_trail\z// if length $field_trail;
100 $_
101 } split /$sf->{o}{split}{field_sep}/, $row, -1 ]; # negative LIMIT (-1) to preserve trailing empty fields
102 }
103 $sql->{insert_args} = $rows_of_cols;
104 return 1;
105 }
106  
107  
108 sub __print_template_info {
109 my ( $sf, $rows, $occupied_term_h ) = @_;
110 my ( $term_w, $term_h ) = get_term_size();
111 my $ten_steps = '';
112 for my $count ( 1 .. int( $term_w / 10 ) ) {
113 $ten_steps .= ( ' ' x ( 10 - length $count ) ) . $count;
114 }
115 my $tapeline = '123456789*';
116 my $ruler = '';
117 $ruler .= $tapeline x int( $term_w / 10 );
118 $ruler .= substr( $tapeline, 0, ( $term_w % 10 ) );
119 my $info = $ten_steps . "\n" . $ruler;
120 my $avail_h = $term_h - $occupied_term_h;
121 if ( $avail_h < 5 ) { ##
122 $avail_h = 5;
123 }
124 my $first_part_end = int( $avail_h / 1.5 );
125 my $second_part_begin = $avail_h - $first_part_end;
126 $first_part_end--;
127 $second_part_begin--;
128 my $end_idx = $#{$rows};
129 if ( @$rows > $avail_h ) {
130 for my $row ( @{$rows}[ 0 .. $first_part_end ] ) {
131 $info .= "\n" . unicode_sprintf( $row, $term_w, { suffix_on_truncate => $sf->{i}{dots} } );
132 }
133 $info .= "\n[...]";
134 for my $row ( @{$rows}[ $end_idx - $second_part_begin .. $end_idx ] ) {
135 $info .= "\n" . unicode_sprintf( $row, $term_w, { suffix_on_truncate => $sf->{i}{dots} } );
136 }
137 my $row_count = scalar( @$rows );
138 $info .= "\n" . unicode_sprintf( '[' . insert_sep( $row_count, $sf->{i}{info_thsd_sep} ) . ' rows]', $term_w, { suffix_on_truncate => $sf->{i}{dots} } );
139 }
140 else {
141 for my $row ( @$rows ) {
142 $info .= "\n" . unicode_sprintf( $row, $term_w, { suffix_on_truncate => $sf->{i}{dots} } );
143 }
144 }
145 $info .= "\n";
146 return $info;
147 }
148  
149  
150 sub parse_with_template {
151 my ( $sf, $sql, $fh ) = @_;
152 my $ax = App::DBBrowser::Auxil->new( $sf->{i}, $sf->{o}, $sf->{d} );
153 my $tf = Term::Form->new( $sf->{i}{tf_default} );
154 my $tc = Term::Choose->new( $sf->{i}{tc_default} );
155 my $old_idx = 0;
156  
157 IRS: while ( 1 ) {
158 my $prompt = 'Choose the input record separator:';
159 my @irs = ( "\\n", "\\r", "\\r\\n" );
160 my $reparse = ' Reparse';
161 my @pre = ( undef );
162 my $menu = [ @pre, map( ' "' . $_ . '"', @irs ), $reparse ];
163 my $info = "Parse mode: Template\n";
164 # Choose
165 my $idx = $tc->choose(
166 $menu,
167 { prompt => $prompt, index => 1, default => $old_idx, layout => 2, undef => ' <=', clear_screen => 1, info => $info }
168 );
169 $ax->print_sql_info( $info );
170 if ( ! $idx ) {
171 return;
172 }
173 if ( $sf->{o}{G}{menu_memory} ) {
174 if ( $old_idx == $idx && ! $ENV{TC_RESET_AUTO_UP} ) {
175 $old_idx = 0;
176 next IRS;
177 }
178 $old_idx = $idx;
179 }
180 if ( $menu->[$idx] eq $reparse ) {
181 my $op = App::DBBrowser::Options->new( $sf->{i}, $sf->{o} );
182 my $op_rw = App::DBBrowser::Options::ReadWrite->new( $sf->{i}, $sf->{o} );
183 $op->config_groups( [ { name => 'group_import', text => "- Import" } ], $sf->{i}{plugin} );
184 $op_rw->read_config_file( $sf->{i}{driver}, $sf->{i}{plugin} );
185 return -1;
186 }
187 require String::Unescape;
188 $/ = String::Unescape::unescape( $irs[$idx-@pre] );
189 $sf->__print_waiting_str;
190 seek $fh, 0, 0;
191 my @rows = grep { ! /^\s+\z/ } <$fh>;
192 chomp @rows;
193 my $fields_set = [ [ 'Col count', ], [ 'Sep width', ], ];
194  
195 SETTINGS: while ( 1 ) {
196 my $info = $sf->__print_template_info( \@rows, 7 + @$fields_set );
197 # Fill_form
198 my $form_set = $tf->fill_form(
199 $fields_set,
200 { info => $info, prompt => 'Settings:', confirm => $sf->{i}{confirm}, back => $sf->{i}{back} . ' ' }
201 );
202 $ax->print_sql_info( $info );
203 if ( ! $form_set ) {
204 next IRS;
205 }
206 my $number_of_columns = $form_set->[0];
207 my $separator_width = $form_set->[1];
208 my $prompt;
209 if ( ! defined $number_of_columns->[1] || $number_of_columns->[1] !~ /^[1-9][0-9]*\z/ ) { ## defined
210 $prompt = "'$number_of_columns->[0]' requires a value of 1 or greater!";
211 }
212 if ( ! length $separator_width->[1] ) {
213 $separator_width->[1] = 0;
214 }
215 if ( $separator_width->[1] !~ /^(?:0|[1-9][0-9]*)\z/ ) {
216 $prompt = "'$separator_width->[0]' requires a value of 0 or greater!";
217 }
218 if ( $prompt ) {
219 my $info = $sf->__print_template_info( \@rows, 6 );
220 $tc->choose(
221 [ 'Press ENTER' ],
222 { info => $info, prompt => $prompt }
223 );
224 $ax->print_sql_info( $info );
225 @$fields_set = @$form_set;
226 next SETTINGS;
227 }
228 my $col_count = $number_of_columns->[1];
229 my $col_sep_w = $separator_width->[1];
230 my $col_names = [ map { 'c' . $_ } 1 .. $col_count ];
231 my $fields = [ map { [ $_, ] } @$col_names ];
232 $fields->[-1][1] = '*';
233  
234 COL_WIDTHS: while ( 1 ) {
235 my $info = $sf->__print_template_info( \@rows, 7 + $col_count );
236 my $prompt = 'Separator width: ' . $col_sep_w;
237 $prompt .= "\n". 'Column widths:';
238 # Fill_form
239 my $form = $tf->fill_form(
240 $fields,
241 { info => $info, prompt => $prompt, confirm => $sf->{i}{_confirm}, back => $sf->{i}{_back} . ' ' }
242 );
243 $ax->print_sql_info( $info );
244 if ( ! $form ) {
245 @$fields_set = @$form_set;
246 next SETTINGS;
247 }
248 my @values;
249 for my $field ( @$form ) {
250 my ( $field_name, $field_value ) = @$field;
251 my ( $valid_regex, $error_message );
252 if ( $field_name eq $form->[-1][0] ) {
253 $valid_regex = qr/^(?:\*|[1-9][0-9]*)\z/;
254 $error_message = " requires * or a value of 1 or greater!";
255 }
256 else {
257 $valid_regex = qr/^[1-9][0-9]*\z/;
258 $error_message = " requires a value of 1 or greater!";
259 }
260 if ( ! defined $field_value || $field_value !~ $valid_regex ) { ## defined
261 $prompt = "'$field_name' " . $error_message;
262 my $info = $sf->__print_template_info( \@rows, 6 );
263 $tc->choose(
264 [ 'Press ENTER' ],
265 { info => $info, prompt => $prompt, info => $info }
266 );
267 $ax->print_sql_info( $info );
268 @$fields = @$form;
269 next COL_WIDTHS;
270 }
271 push @values, $field_value;
272 }
273 $prompt = 'Remove leading spaces?';
274 my ( $no, $yes ) = ( '- NO', '- YES' );
275 $info = $sf->__print_template_info( \@rows, 8 );
276 # Choose
277 my $remove_leading_spaces = $tc->choose(
278 [ undef, $no, $yes ],
279 { info => $info, prompt => $prompt, undef => $sf->{i}{_back}, layout => 2 }
280 );
281 $ax->print_sql_info( $info );
282 if ( ! defined $remove_leading_spaces ) {
283 next COL_WIDTHS;
284 }
285 my $template = join( 'x' x $col_sep_w, map { 'A' . $_ } @values );
286 my $rows_of_cols = [];
287 if ( ! eval {
288 seek $fh, 0, 0;
289 if ( $remove_leading_spaces eq $yes ) {
290 while ( my $row = <$fh> ) {
291 push @$rows_of_cols, [ map { s/^\s+//; $_ } unpack( $template, $row ) ];
292 }
293 }
294 else {
295 while ( my $row = <$fh> ) {
296 push @$rows_of_cols, [ unpack( $template, $row ) ];
297 }
298 }
299 1 }
300 ) {
301 $ax->print_error_message( $@ );
302 @$fields = @$form;
303 next COL_WIDTHS;
304 }
305 $sql->{insert_args} = $rows_of_cols;
306 return 1;
307 }
308 }
309 }
310 }
311  
312  
313 sub parse_with_Spreadsheet_Read {
314 my ( $sf, $sql, $source, $file_fs ) = @_;
315 my $tc = Term::Choose->new( { %{$sf->{i}{tc_default}}, clear_screen => 1 } );
316 $sf->__print_waiting_str;
317 require Spreadsheet::Read;
318 my $book = delete $source->{saved_book};
319 if ( ! defined $book ) {
320 if ( ! eval {
321 $book = Spreadsheet::Read::ReadData( $file_fs, cells => 0, attr => 0, rc => 1, strip => 0 );
322 1 }
323 ) {
324 die "Spreadsheet::Read: $@";
325 }
326 if ( ! defined $book ) {
327 $tc->choose(
328 [ 'Press ENTER' ],
329 { prompt => 'No Book in ' . decode( 'locale_fs', $file_fs ) . '!' }
330 );
331 return;
332 }
333 }
334 my $sheet_count = @$book - 1; # first sheet in $book contains meta info
335 if ( $sheet_count == 0 ) {
336 $tc->choose(
337 [ 'Press ENTER' ],
338 { prompt => 'No Sheets in ' . decode( 'locale_fs', $file_fs ) . '!' }
339 );
340 return;
341 }
342 my $sheet_idx;
343 if ( $sheet_count == 1 ) {
344 $sheet_idx = 1;
345 }
346 else {
347 $source->{saved_book} = $book; # save book if more than one sheet
348 my @sheets = map { '- ' . ( length $book->[$_]{label} ? $book->[$_]{label} : 'sheet_' . $_ ) } 1 .. $#$book;
349 my @pre = ( undef );
350 my $menu = [ @pre, @sheets ];
351  
352 SHEET: while ( 1 ) {
353 # Choose
354 my $idx = $tc->choose(
355 $menu,
356 { %{$sf->{i}{lyt_v}}, prompt => 'Choose a sheet', index => 1, default => $source->{old_idx_sheet},
357 undef => ' <=' }
358 );
359 if ( ! defined $idx || ! defined $menu->[$idx] ) {
360 return;
361 }
362 if ( $sf->{o}{G}{menu_memory} ) {
363 if ( $source->{old_idx_sheet} == $idx && ! $ENV{TC_RESET_AUTO_UP} ) {
364 $source->{old_idx_sheet} = 0;
365 next SHEET;
366 }
367 $source->{old_idx_sheet} = $idx;
368 }
369 $sheet_idx = $idx - @pre + 1;
370 last SHEET;
371 }
372 }
373 # if ( $book->[$sheet_idx]{maxrow} == 0 ) { # works for some file formats; catch empty sheets later ##
374 # my $sheet = length $book->[$sheet_idx]{label} ? $book->[$sheet_idx]{label} : 'sheet_' . $_;
375 # $tc->choose(
376 # [ 'Press ENTER' ],
377 # { prompt => $sheet . ': Empty Sheet!' }
378 # );
379 # return 1;
380 # }
381 $sql->{insert_args} = [ Spreadsheet::Read::rows( $book->[$sheet_idx] ) ];
382 if ( ! -T $file_fs && length $book->[$sheet_idx]{label} ) {
383 $source->{sheet_name} = $book->[$sheet_idx]{label};
384 }
385 return 1;
386 }
387  
388  
389  
390  
391 1;
392  
393  
394 __END__