Debian Codegraph @

examples/csv-check

raw
1 #!/pro/bin/perl
2
3 # csv-check: Check validity of CSV file and report
4 # (m)'20 [21 May 2020] Copyright H.M.Brand 2007-2026
5
6 # This code requires the defined-or feature and PerlIO
7
8 use 5.012000;
9 use warnings;
10
11 use Data::Peek;
12 use Encode qw( decode encode );
13
14 our $VERSION = "2.06"; # 2025-01-03
15 my $cmd = $0; $cmd =~ s{.*/}{};
16
17 sub usage {
18 my $err = shift and select STDERR;
19 print <<"EOU";
20 usage: $cmd [-s <sep>] [-q <quot>] [-e <esc>] [-u] [--pp] [file.csv]
21 -s S --sep=S use S as seperator char. Auto-detect, default = ','
22 the string "tab" is allowed.
23 -q Q --quo=Q use Q as quote char. Auto-detect, default = '"'
24 the string "undef" will disable quotation.
25 -e E --esc=E use E as escape char. Auto-detect, default = '"'
26 the string "undef" will disable escapes.
27 -N --nl force EOL to \\n
28 -C --cr force EOL to \\r
29 -M --crnl force EOL to \\r\\n
30 -u --utf-8 check if all fields are valid unicode
31 -E E --enc=E open file with encoding E
32 -h --hdr check with header (implies BOM)
33 -b --bom check with BOM (no header)
34 -f --skip-formula do not check formula's
35
36 --pp use Text::CSV_PP instead (cross-check)
37
38 -A a --attr=at:val pass attributes to parser
39 --at=val is also supported for know attributes
40 -L --list-attr list supported CSV attributes
41 -X --list-changes list attributes that changed from default
42 EOU
43 exit $err;
44 } # usage
45
46 use Getopt::Long qw(:config bundling passthrough);
47 my $eol;
48 GetOptions (
49 "help|?" => sub { usage (0); },
50 "V|version" => sub { say "$cmd [$VERSION]"; exit 0; },
51
52 "c|s|sep=s" => \(my $sep = ""),
53 "q|quo|quote=s" => \(my $quo = '"'),
54 "e|esc|escape=s" => \(my $esc = '"'),
55 "N|nl!" => sub { $eol = "\n"; },
56 "C|cr!" => sub { $eol = "\r"; },
57 "M|crnl!" => sub { $eol = "\r\n"; },
58 "B|binary!" => \(my $bin = 1),
59
60 "u|utf|utf8|utf-8!" => \(my $opt_u = 0),
61 "E|enc|encoding=s" => \(my $enc),
62 "h|hdr|header!" => \(my $opt_h = 0),
63 "b|bom!" => \(my $opt_b = 0),
64 "f|skip-formula!" => \(my $opt_f = 0),
65
66 "A|attr=s" => \ my @opt_A,
67 "L|list-attr!" => \ my $opt_L,
68 "X|list-changes!" => \ my $opt_X,
69
70 "pp!" => \(my $opt_p = 0),
71
72 "v|verbose:1" => \(my $opt_v = 0),
73 ) or usage (1);
74 $opt_X and $opt_L++;
75
76 my $csvmod = "Text::CSV_XS";
77 if ($opt_p) {
78 require Text::CSV_PP;
79 $csvmod = "Text::CSV_PP";
80 }
81 else {
82 require Text::CSV_XS;
83 }
84 $csvmod->import ();
85
86 binmode STDOUT, ":encoding(utf-8)";
87 binmode STDERR, ":encoding(utf-8)";
88
89 my $fn = $ARGV[0] // "-";
90 my @warn;
91
92 my %csvarg = (
93 sep_char => $sep eq "tab" ? "\t" : $sep,
94 quote_char => $quo eq "undef" ? undef : $quo,
95 escape_char => $esc eq "undef" ? undef : $esc,
96 eol => $eol,
97 strict_eol => 1,
98 binary => $bin,
99 keep_meta_info => 1,
100 auto_diag => 1,
101 formula => $opt_f ? "none" : "diag",
102 );
103 { my $p = $csvmod->new;
104 my %ka = map { $_ => $p->{$_} } grep m/^[a-z]/ => $p->known_attributes;
105 foreach my $i (reverse 0 .. $#ARGV) {
106 if ($ARGV[$i] =~ m/^--(no[-_])?+([-\w]+)(?:=(.*))?$/) {
107 my ($attr, $val) = (lc $2 =~ tr/-/_/r, $3 // ($1 ? 0 : 1));
108 if (exists $ka{$attr}) {
109 unshift @opt_A, "$attr:$val";
110 splice @ARGV, $i, 1;
111 }
112 }
113 }
114 for (@opt_A) {
115 m/^([-\w]+)(?:[:=](.*))?/ or next;
116 my ($attr, $val) = (lc $1 =~ tr/-/_/r, $2 // 1);
117 exists $ka{$attr} or next;
118 $val eq "undef" || !length $val and $val = undef; # -A escape_char:
119 $csvarg{$attr} = $val;
120 }
121 if ($opt_L) {
122 $csvarg{sep_char} ||= $ka{sep_char};
123 foreach my $attr (sort keys %ka) {
124 $ka{$attr} //= "(undef)";
125 $csvarg{$attr} //= $ka{$attr};
126 $opt_X and $csvarg{$attr} eq $ka{$attr} and next;
127 printf " %-21s : %s\n", $attr, $csvarg{$attr};
128 }
129 exit 0;
130 }
131 }
132 $opt_v > 1 and DDumper \%csvarg;
133
134 my $data = do { local $/; <> } or die "No data to analyze\n";
135
136 my ($rows, %cols, $s_eol) = (0);
137 unless ($sep) { # No sep char passed, try to auto-detect;
138 my ($first_line) = ($data =~ m/\A(.*?)(?:\r\n|\n|\r)/);
139 $first_line ||= $data; # if no EOL at all, use whole set
140 $sep = $first_line =~ m/["\d],["\d,]/ ? "," :
141 $first_line =~ m/["\d];["\d;]/ ? ";" :
142 $first_line =~ m/["\d]\t["\d]/ ? "\t" :
143 # If neither, then for unquoted strings
144 $first_line =~ m/\w,[\w,]/ ? "," :
145 $first_line =~ m/\w;[\w;]/ ? ";" :
146 $first_line =~ m/\w\t[\w]/ ? "\t" : ",";
147 $data =~ m/([\r\n]+)\Z/ and $s_eol = DDisplay "$1";
148 $csvarg{sep_char} = $sep;
149 }
150
151 my $csv = $csvmod->new (\%csvarg);
152 $opt_v > 8 and DDumper $csv;
153
154 $bin = 0; # Assume ASCII only
155
156 sub done {
157 my $file = $ARGV // "STDIN";
158 (my $pv = "$]0000000") =~ s{^([0-9]+)\.([0-9]{3})([0-9]{3})[0-9]*}
159 {sprintf "%d.%d.%d",$1,$2,$3}e;
160 my $uv = eval {
161 no warnings;
162 (my $cv = $]) =~ s/0+$//;
163 eval { require Unicode::UCD; Unicode::UCD::UnicodeVersion () } ||
164 eval { require Module::CoreList; $Module::CoreList::version{$cv}{Unicode} };
165 } || "unknown";
166 say "Checked $file with $cmd $VERSION\nusing $csvmod @{[$csvmod->VERSION]} with perl $pv and Unicode $uv";
167 my @diag = $csv->error_diag;
168 my $line = $. // $csv->record_number // "?";
169 if ($diag[0] == 2012 && $csv->eof) {
170 my @coll = sort { $a <=> $b } keys %cols;
171 local $" = ", ";
172 my $cols = @coll == 1 ? $coll[0] : "(@coll)";
173 $s_eol //= $csv->eol || "--unknown--";
174 $s_eol =~ m/[\x00-\x1f]/ and $s_eol = DDisplay $s_eol;
175 say "OK: rows: $rows, columns: $cols";
176 say " sep = <$sep>, quo = <$quo>, bin = <$bin>, eol = <$s_eol>";
177 say " encoding = $csv->{ENCODING}" if $csv->{ENCODING};
178 if (@coll > 1) {
179 say "multiple column lengths:";
180 printf " %6d line%s with %4d field%s\n",
181 $cols{$_}, $cols{$_} == 1 ? " " : "s",
182 $_, $_ == 1 ? "" : "s"
183 for @coll;
184 }
185 $diag[0] = 0;
186 }
187 elsif ($diag[2]) {
188 say "$ARGV record $diag[3] at line $line/$diag[2] - $diag[0] - $diag[1]";
189 my $ep = $diag[2] - 1; # diag[2] is 1-based
190 my $ei = $csv->error_input;
191 if (defined $ei) {
192 my $l = 0;
193 my $s = "";
194 eval { my $u = decode ("utf-8", $ei); $ei = $u };
195 for (split m/([^ -~])/ => $ei) {
196 if (m/^[ -~]+$/) {
197 $s .= $_;
198 $l += length;
199 next;
200 }
201 if ($_ eq "\t") {
202 $s .= "\\t";
203 $ep > $l and $ep++;
204 $l += 2;
205 next;
206 }
207 if ($_ eq "\n") {
208 $s .= "\\n";
209 $ep > $l and $ep++;
210 $l += 2;
211 next;
212 }
213 if ($_ eq "\r") {
214 $s .= "\\r";
215 $ep > $l and $ep++;
216 $l += 2;
217 next;
218 }
219 $s .= sprintf "\\x{%05x}", ord;
220 $ep > $l and $ep += 9 - length encode "utf-8", $_;
221 $l += 9;
222 }
223
224 say " |$s|"; # 2b06
225 say " |", " " x $ep, "\x{25b2}", " " x (length ($s) - $ep - 1), "|";
226 }
227 }
228 else {
229 say "$ARGV line $line - $diag[1]";
230 }
231 print for @warn;
232 exit $diag[0];
233 } # done
234
235 sub show {
236 say STDERR join ", " => map { "\x{231e}$_\x{231d}" } @_;
237 } # show
238
239 sub stats {
240 my $r = shift;
241 $cols{scalar @$r}++;
242 grep { $_ & 0x0002 } $csv->meta_info and $bin = 1;
243 $opt_v > 2 and show (@$r);
244 if ($opt_u) {
245 my @r = @$r;
246 foreach my $x (0 .. $#r) {
247 utf8::is_utf8 ($r[$x]) and next;
248
249 local $SIG{__WARN__} = sub {
250 (my $msg = shift) =~ s{ at /\S+Encode.pm.*}{};
251 my @h = $csv->column_names;
252 push @warn, sprintf "Field %d%s in record %d - '%s'\t- %s",
253 $x + 1, @h ? " (column: '$h[$x]')" : "", $rows,
254 DPeek ($r[$x]), $msg;
255 };
256 my $oct = decode ("utf-8", $r[$x], Encode::FB_WARN);
257 }
258 }
259 } # stats
260
261 my $mode = $enc ? "<:encoding($enc)" : "<";
262 open my $fh, $mode, \$data or die "$fn: $!\n";
263 if ($opt_h) {
264 $csv->header ($fh);
265 }
266 elsif ($opt_b) {
267 my @hdr = $csv->header ($fh, { detect_bom => 1, set_column_names => 0 });
268 stats \@hdr;
269 }
270
271 local $SIG{__WARN__} = sub { push @warn, @_; };
272 while (my $row = $csv->getline ($fh)) {
273 $rows++;
274 stats $row;
275 }
276 done;