xref: /openbsd-src/gnu/usr.bin/perl/regen/tidy_embed.pl (revision f2a19305cfc49ea4d1a5feb55cd6c283c6f1e031)
1use lib "regen";
2use HeaderParser;
3use strict;
4use warnings;
5
6my $parser= HeaderParser->new(
7        pre_process_content => sub {
8            my ($self,$line_data)= @_;
9            $self->tidy_embed_fnc_entry($line_data);
10            my $embed= $line_data->{embed}
11                or return;
12        },
13        post_process_grouped_content => sub {
14            my ($self, $group_ary)= @_;
15            my $last=chr(0x10FFFF);
16            for(my $i= $#$group_ary; $i>=0; $i--) {
17                my $entry= $group_ary->[$i];
18                if ($entry->{embed}) {
19                    $last = $entry->{embed}{name};
20                }
21                $entry->{sort}{klc}= lc($last)=~s/[^a-z]+//gr;
22                $entry->{sort}{key}= $last;
23                $entry->{sort}{idx}= $i;
24            }
25            @{$group_ary}=
26                sort {
27                    $a->{sort}{klc} cmp $b->{sort}{klc} ||
28                    $a->{sort}{key} cmp $b->{sort}{key} ||
29                    $a->{sort}{idx} <=> $b->{sort}{idx}
30                } @{$group_ary};
31            delete $_->{sort} for @$group_ary;
32        },
33    );
34my $tap;
35if (@ARGV and $ARGV[0] eq "--tap") {
36    $tap = shift @ARGV;
37}
38my $file= "embed.fnc";
39if (@ARGV) {
40    $file= shift @ARGV;
41}
42my $new= "$file.new";
43my $bak= "$file.bak";
44$parser->read_file($file);
45my $lines= $parser->lines;
46my (@head, @tail);
47# strip off comments at the start of the file
48while ($lines->[0]{type} eq "content" and !$lines->[0]{embed}) {
49    push @head, shift @$lines;
50}
51
52# strip off comments at the bottom of the file
53while ($lines->[-1]{type} eq "content" and !$lines->[-1]{embed})
54{
55    unshift @tail, pop @$lines;
56}
57
58my $grouped_content_ary= $parser->group_content();
59my $grouped_content_txt= $parser->lines_as_str(
60    [ @head, @$grouped_content_ary, @tail ]);
61if ($grouped_content_txt ne $parser->{orig_content}) {
62    if ($tap) {
63        print "not ok - $0 $file\n";
64    } elsif (-t) {
65        print "Updating $file\n";
66    }
67    open my $fh,">",$new
68        or die "Failed to open '$new' for write: $!";
69    print $fh $grouped_content_txt
70        or die "Failed to print to '$new': $!";
71    close $fh
72        or die "Failed to close '$new': $!";
73    rename $file, $bak
74        or die "Couldn't move '$file' to '$bak': $!";
75    rename $new, $file
76        or die "Couldn't move embed.fnc.new to embed.fnc: $!";
77} elsif ($tap) {
78    print "ok - $0 $file\n";
79}
80