]> mj.ucw.cz Git - libucw.git/blob - build/genconf
5e2269b0a76f12a0a835982870239182c18e807e
[libucw.git] / build / genconf
1 #!/usr/bin/perl
2 # Configuration file and script preprocessor
3 # (c) 2004 Martin Mares <mj@ucw.cz>
4
5 use strict;
6 use warnings;
7
8 @ARGV == 3 or die "Usage: genconf <src> <dest> <config.mk>";
9
10 open CF, $ARGV[2] or die "Unable to open $ARGV[2]";
11 my %options = ();
12 while (<CF>) {
13         /^(CONFIG_\w+)=[^0]/ || next;
14         $options{$1} = 1;
15 }
16 close CF;
17
18 my $opt_regex = join("|", keys %options);
19 sub eval_expr { $_ = "@_"; s/\b($opt_regex)\b/ 1 /g if $opt_regex; s/\bCONFIG_\w+\b/ 0 /g; return eval $_; }
20
21 open IN, $ARGV[0] or die "Unable to open $ARGV[0]";
22 open OUT, ">$ARGV[1]" or die "Unable to create $ARGV[1]";
23 my @ifs = ();   # stack of conditions, 1=satisfied, -1=unsatisfied, 0=shadowed
24 my $empty = 0;  # last line was empty
25 while (<IN>) {
26         if (/^#ifdef\s+(\w+)/) {
27                 push @ifs, (@ifs && $ifs[$#ifs] <= 0) ? 0 : (defined $options{$1}) ? 1 : -1;
28         } elsif (/^#ifndef\s+(\w+)/) {
29                 push @ifs, (@ifs && $ifs[$#ifs] <= 0) ? 0 : (defined $options{$1}) ? -1 : 1;
30         } elsif (/^#if\s(.*)$/) {
31                 push @ifs, (@ifs && $ifs[$#ifs] <= 0) ? 0 : (eval_expr $1) ? 1 : -1;
32         } elsif (/^#endif/) {
33                 defined pop @ifs || die "Improper nesting of conditionals";
34         } elsif (/^#else/) {
35                 my $x = pop @ifs;
36                 defined $x || die "Improper nesting of conditionals";
37                 push @ifs, $x >= 0 ? 0 : 1;
38         } elsif (/^#elsif\s(.*)$/) {
39                 my $x = pop @ifs;
40                 defined $x || die "Improper nesting of conditionals";
41                 push @ifs, $x >= 0 ? 0 : (eval_expr $1) ? 1 : -1;
42         } else {
43                 @ifs && $ifs[$#ifs] <= 0 && next;
44                 if (/^$/) {
45                         $empty && next;
46                         $empty = 1;
47                 } else { $empty = 0; }
48                 if (/^#pipe\s+(.+)/) {
49                         my $cmd = $1;
50                         my $val = `$cmd`;
51                         die "Piped command '$cmd' failed" if $?;
52                         print OUT `$1`;
53                 } else {
54                         print OUT;
55                 }
56         }
57 }
58 @ifs && die "Unterminated #ifdef";
59 close IN;
60 close OUT;