Debian Codegraph @

tools/parse_olson

raw
1 #!/usr/bin/env perl
2
3 use strict;
4 use warnings;
5
6 use lib './lib';
7
8 use Data::Dumper;
9 use DateTime;
10 use DateTime::TimeZone::OlsonDB;
11 use File::Copy;
12 use File::Find::Rule;
13 use File::Path;
14 use File::Spec;
15 use Getopt::Long;
16 use List::Util qw( max );
17 use Locale::Country 3.11 qw( code2country );
18 use Parallel::ForkManager;
19
20 $Data::Dumper::Indent = 1;
21 $Data::Dumper::Sortkeys = 1;
22 $Data::Dumper::Terse = 1;
23
24 my $VERSION = '0.08';
25
26 my $INFINITY = 100**100**100;
27
28 my %opts;
29 GetOptions(
30 'dir:s' => \$opts{dir},
31 'clean' => \$opts{clean},
32 'version:s' => \$opts{version},
33 'jobs:i' => \$opts{jobs},
34 'old' => \$opts{old},
35 'file:s' => \$opts{file},
36 'name:s' => \$opts{name},
37 'debug' => \$opts{debug},
38 'help' => \$opts{help},
39 );
40
41 $opts{help} = 1
42 unless defined $opts{dir} && -d $opts{dir};
43
44 $opts{help} = 1
45 unless defined $opts{version} || $opts{file} || $opts{name};
46
47 $opts{version} ||= 'test';
48
49 $opts{jobs} ||= 12;
50
51 if ( $opts{help} ) {
52 print <<'EOF';
53
54 This script parses the Olson time zone database files and turns them into a
55 set of Perl modules. It also generates the DateTime::TimeZone::Catalog
56 module, which contains a list of all the available time zone names.
57
58 By default, it looks for files named africa, antarctica, asia, australasia,
59 europe, northamerica, southamerica, and backward. All other files are ignored.
60
61 It takes the following arguments:
62
63 --dir A directory containing Olson db files.
64
65 --version The version of the Olson data files being used.
66 Required unless one of the debugging options is given.
67
68 --clean Remove old generated modules (which may not be valid with
69 the latest Olson database)
70
71 --jobs Number of parallel jobs to run. Defaults to 4.
72
73 --file Parse just the file with the given name. For debugging.
74
75 --name Only create the specified time zone. For debugging.
76
77 --old Also look for files named etcetera and systemv
78
79 --debug Turn on debugging in Olson parser
80
81 --help What you are reading
82
83 If the --file or --name options are specified, the DateTime::TimeZone::Catalog
84 module will not be generated.
85
86 EOF
87
88 exit;
89 }
90
91 clean() if $opts{clean};
92
93 my @files;
94
95 if ( $opts{file} ) {
96 @files = $opts{file};
97 }
98 else {
99 @files = qw(
100 africa
101 antarctica
102 asia
103 australasia
104 europe
105 northamerica
106 southamerica
107 backward
108 );
109
110 push @files, qw( etcetera )
111 if $opts{old};
112 }
113
114 my $autogen_warning = <<"EOF";
115 # This file is auto-generated by the Perl DateTime Suite time zone
116 # code generator ($VERSION) This code generator comes with the
117 # DateTime::TimeZone module distribution in the tools/ directory
118 EOF
119
120 my $dt_tz_version = DateTime::TimeZone::OlsonDB->VERSION;
121
122 my $pm = Parallel::ForkManager->new( $opts{jobs} );
123
124 my ( @zones, %categories, %links );
125 $pm->run_on_finish(
126 sub {
127 my ( $exit_code, $data ) = @_[ 1, 5 ];
128 die "Bad exit: $exit_code" if $exit_code;
129
130 push @zones, @{ $data->{zones} };
131 $links{$_} = $data->{links}{$_} for keys %{ $data->{links} };
132 for my $category ( keys %{ $data->{categories} } ) {
133 push @{ $categories{$category} },
134 @{ $data->{categories}{$category} };
135 }
136 }
137 );
138
139 for my $file ( sort @files ) {
140 $pm->start() and next;
141
142 $pm->finish( 0, parse_file($file) );
143 }
144
145 $pm->wait_all_children();
146
147 exit if $opts{name};
148
149 clean_links();
150
151 make_catalog_pm();
152
153 sub clean {
154 for my $f (
155 File::Find::Rule->file->name('*.pm')
156 ->grep('This file is auto-generated')->in('lib'),
157 File::Find::Rule->file->name('zd*.t')->in('t')
158 ) {
159 unlink $f or die "Cannot unlink $f: $!";
160 }
161 }
162
163 sub parse_file {
164 my $file = File::Spec->catfile( $opts{dir}, shift );
165
166 die "No such file $file\n" unless -e $file;
167
168 print "Now parsing $file\n";
169
170 $DateTime::TimeZone::OlsonDB::DEBUG = 1
171 if $opts{debug};
172
173 my $odb = DateTime::TimeZone::OlsonDB->new;
174
175 $odb->parse_file($file);
176
177 my @zones;
178 my %categories;
179 foreach my $zone_name ( sort $odb->zone_names ) {
180 if ( $opts{name} ) {
181 next unless $zone_name eq $opts{name};
182 }
183 print " creating zone $zone_name\n";
184
185 push @zones, $zone_name;
186
187 my $name;
188 my @dir;
189 if ( $zone_name =~ m{/} ) {
190 my $category;
191 ( $category, $name ) = split /\//, $zone_name, 2;
192 push @{ $categories{$category} }, $name;
193
194 ( $dir[0] = $category ) =~ tr/-/_/;
195 }
196 else {
197 $name = $zone_name;
198 }
199
200 my $outfile1 = $name;
201 $outfile1 =~ s/-(\d)/_Minus$1/;
202 $outfile1 =~ s/\+/_Plus/;
203 $outfile1 =~ s/-/_/g;
204
205 ( my $mod_name = $zone_name ) =~ s/\//::/g;
206 $mod_name =~ s/-(\d)/_Minus$1/;
207 $mod_name =~ s/\+/_Plus/;
208 $mod_name =~ s/-/_/g;
209
210 my $zone = $odb->zone($zone_name);
211 my $max_year = max(
212 (localtime)[5] + 1910,
213 $zone->last_rules_year($odb),
214 );
215
216 $zone = $odb->expanded_zone(
217 name => $zone_name,
218 expand_to_year => $max_year,
219 );
220
221 my $spans = serialize_spans( zone_as_spans($zone) );
222
223 $spans =~ s/-inf(inity)?/DateTime::TimeZone::NEG_INFINITY/gi;
224 $spans =~ s/\binf(inity)?/DateTime::TimeZone::INFINITY/gi;
225
226 $spans =~ s/('(?:start|end)_date'\s+=>\s+)'(\d+)'/$1$2/g;
227
228 my $generator = zone_generator($zone);
229
230 my $has_dst_changes = grep { $_->is_dst } $zone->sorted_changes;
231
232 my $from = "Generated from $file.";
233 $from .= " Olson data version $opts{version}"
234 if defined $opts{version};
235
236 # Helps avoid mis indexing on (meta)cpan
237 my $keyword = 'package';
238 my $pkg = "$keyword DateTime::TimeZone::$mod_name";
239
240 my $body = <<"EOF";
241 $autogen_warning
242 #
243 # $from
244 #
245 # Do not edit this file directly.
246 #
247 $pkg;
248
249 use strict;
250 use warnings;
251 use namespace::autoclean;
252
253 our \$VERSION = '$dt_tz_version';
254
255 use Class::Singleton 1.03;
256 use DateTime::TimeZone;
257 use DateTime::TimeZone::OlsonDB;
258
259 \@DateTime::TimeZone::${mod_name}::ISA = ( 'Class::Singleton', 'DateTime::TimeZone' );
260
261 my \$spans =
262 $spans;
263
264 sub olson_version {'$opts{version}'}
265
266 sub has_dst_changes {$has_dst_changes}
267
268 sub _max_year {$max_year}
269
270 sub _new_instance {
271 return shift->_init( \@_, spans => \$spans );
272 }
273
274 $generator
275
276 1;
277
278 EOF
279
280 my @name_pieces = split /\//, $outfile1;
281 my $filename = ( pop @name_pieces ) . '.pm';
282
283 my $outdir = File::Spec->catdir(
284 qw( lib DateTime TimeZone ),
285 @dir, @name_pieces
286 );
287
288 mkpath( $outdir, 1, 0755 );
289
290 my $outfile2 = File::Spec->catfile( $outdir, $filename );
291
292 open my $fh, ">$outfile2" or die "Cannot write to $outfile2: $!";
293 print $fh $body or die "Cannot write to $outfile2: $!";
294 close $fh or die "Cannot write to $outfile2: $!";
295 }
296
297 return {
298 links => { $odb->links() },
299 categories => \%categories,
300 zones => \@zones,
301 };
302 }
303
304 sub zone_as_spans {
305 my $zone = shift;
306
307 my @spans;
308
309 my @changes = $zone->sorted_changes;
310
311 for ( my $x = 1; $x < @changes; $x++ ) {
312 my $last_total_offset
313 = $x > 1 ? $changes[ $x - 2 ]->total_offset : undef;
314
315 my $span = DateTime::TimeZone::OlsonDB::Change::two_changes_as_span(
316 @changes[ $x - 1, $x ], $last_total_offset );
317
318 push @spans, $span;
319
320 if ( @spans > 2 ) {
321 die "Gap in UTC end/start datetime for " . $zone->name
322 unless $spans[-2]{utc_end} == $spans[-1]{utc_start};
323 }
324 }
325
326 unless ( $zone->infinite_rules ) {
327 my $last_change = $changes[-1];
328
329 my $last_observance = $last_change->observance;
330
331 if ( $last_change->utc_start_datetime ) {
332 push @spans, {
333 utc_start =>
334 $last_change->utc_start_datetime->utc_rd_as_seconds,
335 utc_end => $INFINITY,
336 local_start =>
337 $last_change->local_start_datetime->utc_rd_as_seconds,
338 local_end => $INFINITY,
339 short_name => $last_change->short_name,
340 offset => $last_change->total_offset,
341 is_dst => $last_change->is_dst,
342 };
343 }
344
345 # This happens with zones that have only one rule and no real changes (Pacific/Johnston)
346 else {
347 my $utc_start = @spans ? $spans[-1]{utc_end} : -1 * $INFINITY;
348
349 push @spans, {
350 utc_start => $utc_start,
351 utc_end => $INFINITY,
352 local_start => $utc_start - $last_observance->total_offset,
353 local_end => $INFINITY,
354 short_name => $last_observance->formatted_short_name(q{}),
355 offset => $last_observance->total_offset,
356 is_dst => 0,
357 };
358 }
359 }
360
361 return \@spans;
362 }
363
364 sub serialize_spans {
365 my $spans = shift;
366
367 my $string = "[\n";
368 $string .= join "\n", map { serialize_span($_) } @$spans;
369 $string .= "\n]";
370
371 return $string;
372 }
373
374 sub serialize_span {
375 my $span = shift;
376
377 # must correspond to constants in DT::TZ, and short_name is always last
378 my $string = " [\n";
379 for my $key (qw( utc_start utc_end local_start local_end )) {
380 my $comment
381 = sprintf( '# %12s %s', $key, _num_as_datetime( $span->{$key} ) );
382 $comment =~ s/\s+$//;
383 $string .= "$span->{$key}, $comment\n";
384 }
385
386 for my $key (qw( offset is_dst )) {
387 $string .= "$span->{$key},\n";
388 }
389
390 $string .= "'$span->{short_name}',";
391 $string .= "\n ],";
392
393 return $string;
394 }
395
396 {
397 {
398
399 package FakeCal;
400
401 sub utc_rd_values {
402 return @{ $_[0] };
403 }
404 }
405
406 sub _num_as_datetime {
407 my $num = shift;
408
409 return q{} unless $num =~ /^\d+$/;
410
411 my $days = do { use integer; $num / 86400 };
412 my $secs = $num % 86400;
413
414 my $obj = bless [ $days, $secs, 0 ], 'FakeCal';
415
416 my $dt = DateTime->from_object( object => $obj );
417
418 return $dt->strftime('%Y-%m-%d %H:%M:%S (%a)');
419 }
420 }
421
422 sub zone_generator {
423 my $zone = shift;
424
425 return '' unless $zone->infinite_rules;
426
427 my $generator = <<'EOF';
428 sub _last_offset { !OFFSET }
429
430 my $last_observance = !LAST_OBSERVANCE;
431 sub _last_observance { $last_observance }
432
433 my $rules = !RULES;
434 sub _rules { $rules }
435 EOF
436
437 my $last_observance = ( $zone->sorted_changes )[-1]->observance;
438
439 # hack to trim size of dumped object
440 delete $last_observance->{utc_start_datetime}{locale};
441 delete $last_observance->{local_start_datetime}{locale};
442 delete $last_observance->{utc_start_datetime}{local_c};
443 delete $last_observance->{local_start_datetime}{local_c};
444 delete $last_observance->{rules};
445 delete $last_observance->{first_rule};
446
447 # This assumes that there is only one observance from end of
448 # changes til end of time, which should be guaranteed by code in
449 # OlsonDB module.
450 my $offset = $last_observance->total_offset;
451
452 my @rules = $zone->infinite_rules;
453
454 # This is cleaner than making the above a double-quoted string
455 $generator =~ s/!RULES/Dumper \@rules/eg;
456 $generator =~ s/!LAST_OBSERVANCE/Dumper $last_observance/eg;
457 $generator =~ s/\$VAR1->\{'local_start_datetime'\}\{'tz'\}/bless( {
458 'name' => 'floating',
459 'offset' => 0
460 }, 'DateTime::TimeZone::Floating' )/;
461 $generator =~ s/\$VAR1->\{'utc_start_datetime'\}\{'tz'\}/bless( {
462 'name' => 'floating',
463 'offset' => 0
464 }, 'DateTime::TimeZone::Floating' )/;
465 $generator =~ s/!OFFSET/$offset/g;
466
467 return $generator;
468 }
469
470 sub clean_links {
471
472 # override some links and add others
473 %links = (
474 %links,
475 'Etc/GMT' => 'UTC',
476 'Etc/GMT+0' => 'UTC',
477 'Etc/Universal' => 'UTC',
478 'Etc/UCT' => 'UTC',
479 'Etc/UTC' => 'UTC',
480 'Etc/Zulu' => 'UTC',
481 'GMT0' => 'UTC',
482 'GMT' => 'UTC',
483 'AKST9AKDT' => 'America/Anchorage',
484 'JST-9' => 'Asia/Tokyo',
485 );
486
487 delete $links{UTC};
488
489 # Some links resolve to other links - chase them down until they point
490 # to a real zone.
491 while ( my @k = grep { $links{ $links{$_} } } keys %links ) {
492 for my $k (@k) {
493 $links{$k} = $links{ $links{$k} };
494 }
495 }
496 }
497
498 sub make_catalog_pm {
499 my $links = Dumper \%links;
500 $links =~ s/{/(/;
501 $links =~ s/}/)/;
502
503 my $zones = join "\n", map {" $_"} sort @zones, 'UTC';
504 my $cat_names = join "\n", map {" $_"} sort keys %categories;
505 my $cat = '';
506 foreach my $c ( sort keys %categories ) {
507 $cat .= qq| '$c' => [ qw(\n|;
508 $cat .= join "\n", map {" $_"} sort @{ $categories{$c} };
509 $cat .= "\n) ],\n";
510 }
511
512 my %countries = parse_zone_tab();
513
514 # hard-code this alias per request of David Cantrell on the list.
515 $countries{UK} = $countries{GB};
516
517 my $countries = '';
518 for my $c ( sort keys %countries ) {
519 $countries .= qq| '\L$c' => [ qw(\n|;
520
521 # We explicitly do not sort these because the order in
522 # zones.tab is already in a sane sort order.
523 $countries .= join "\n",
524 map {" $_"} map { $_->[0] } @{ $countries{$c} };
525 $countries .= "\n) ],\n";
526 }
527
528 # Helps avoid mis indexing on (meta)cpan
529 my $keyword = 'package';
530 my $pkg = "$keyword DateTime::TimeZone::Catalog";
531
532 # The leading spaces are to make sure that none of the pod gets indexed by
533 # MetaCPAN.
534 my $zonecatalog = <<"EOF";
535 $autogen_warning
536 #
537 # Do not edit this file directly.
538
539 $pkg;
540
541 use strict;
542 use warnings;
543 use namespace::autoclean;
544
545 our \$VERSION = '$dt_tz_version';
546
547 our \@ALL =
548 qw(
549 $zones
550 );
551
552 our \@CATEGORY_NAMES =
553 qw(
554 $cat_names
555 );
556
557 our \%CATEGORIES =
558 (
559 $cat
560 );
561
562 our \%ZONES_BY_COUNTRY =
563 (
564 $countries
565 );
566
567 our \%LINKS =
568 $links
569 ;
570
571 sub OlsonVersion { '$opts{version}' }
572
573
574 1;
575
576 __END__
577
578 =pod
579
580 =head1 NAME
581
582 DateTime::TimeZone::Catalog - Provides a list of all valid time zone names
583
584 =head1 DESCRIPTION
585
586 This module contains an enumerated list of all known system timezones,
587 so that applications can easily present a list of timezones.
588
589 =head1 AVAILABLE ZONES
590
591 =head2 Zones by Continent/Region
592
593 EOF
594
595 $zonecatalog =~ s/^\ //mg;
596
597 for my $category ( sort keys %categories ) {
598 $zonecatalog .= "=head3 $category\n\n";
599
600 for my $zone ( @{ $categories{$category} } ) {
601 $zonecatalog .= " $category/$zone\n";
602 }
603
604 $zonecatalog .= "\n";
605 }
606
607 $zonecatalog .= <<'EOF';
608 =head2 Zones by Country
609
610 EOF
611
612 for my $country (
613 sort { lc $a->[0] cmp lc $b->[0] }
614 map {
615 my $country = my_code2country($_);
616 warn "no country for $_\n" unless defined $country;
617 [ $country, $_ ];
618 } grep { $_ ne 'UK' } keys %countries
619 ) {
620
621 $zonecatalog .= "=head3 $country->[0] ($country->[1])\n\n";
622
623 for my $zone ( @{ $countries{ $country->[1] } } ) {
624 my $line = join ' - ', grep {defined} @{$zone};
625 $zonecatalog .= " $line\n";
626 }
627
628 $zonecatalog .= "\n";
629 }
630
631 $zonecatalog .= <<'EOF';
632 =head2 Linked Zones
633
634 A linked zone is an alias from one name to another.
635
636 EOF
637
638 for my $from ( sort keys %links ) {
639 $zonecatalog .= " $from => $links{$from}\n";
640 }
641
642 $zonecatalog .= "\n";
643
644 $zonecatalog .= "=cut\n";
645
646 open my $fh, ">lib/DateTime/TimeZone/Catalog.pm" or die $!;
647 print $fh $zonecatalog or die $!;
648 close $fh or die $!;
649 }
650
651 sub parse_zone_tab {
652 my $file = File::Spec->catfile( $opts{dir}, 'zone.tab' );
653
654 open my $fh, "<$file" or die "Cannot read $file: $!";
655
656 my %countries;
657 while (<$fh>) {
658 next if /^\#/;
659 chomp;
660
661 my ( $cc, undef, $tz, $desc ) = split /\t+/, $_;
662
663 push @{ $countries{$cc} }, [ $tz, $desc ];
664 }
665
666 return %countries;
667 }
668
669 sub my_code2country {
670 my $code = shift;
671
672 return 'South Sudan' if $code eq 'SS';
673
674 return code2country($code);
675 }