]> mj.ucw.cz Git - libucw.git/blob - build/genconf
29565a9c48a9d3bc2e34c442cbd3b8b9c457b690
[libucw.git] / build / genconf
1 #!/usr/bin/perl
2 # Configuration file and script preprocessor
3 # (c) 2004--2007 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 my %vars = ();
13 while (<CF>) {
14         chomp;
15         if (my ($k,$v) = /^(\w+)=(.*)/) {
16                 $v =~ s/\s+$//;
17                 $vars{$k} = $v;
18                 $options{$k} = 1 if ($k =~ /^CONFIG_/);
19         }
20 }
21 close CF;
22
23 my $opt_regex = join("|", keys %options);
24 sub eval_expr { $_ = "@_"; s/\b($opt_regex)\b/ 1 /g if $opt_regex; s/\bCONFIG_\w+\b/ 0 /g; return eval $_; }
25
26 open IN, $ARGV[0] or die "Unable to open $ARGV[0]";
27 open OUT, ">$ARGV[1]" or die "Unable to create $ARGV[1]";
28 my @ifs = ();   # stack of conditions, 1=satisfied, -1=unsatisfied, 0=shadowed
29 my $empty = 0;  # last line was empty
30 while (<IN>) {
31         if (/^#ifdef\s+(\w+)/) {
32                 push @ifs, (@ifs && $ifs[$#ifs] <= 0) ? 0 : (defined $options{$1}) ? 1 : -1;
33         } elsif (/^#ifndef\s+(\w+)/) {
34                 push @ifs, (@ifs && $ifs[$#ifs] <= 0) ? 0 : (defined $options{$1}) ? -1 : 1;
35         } elsif (/^#if\s(.*)$/) {
36                 push @ifs, (@ifs && $ifs[$#ifs] <= 0) ? 0 : (eval_expr $1) ? 1 : -1;
37         } elsif (/^#endif/) {
38                 defined pop @ifs || die "Improper nesting of conditionals";
39         } elsif (/^#else/) {
40                 my $x = pop @ifs;
41                 defined $x || die "Improper nesting of conditionals";
42                 push @ifs, $x >= 0 ? 0 : 1;
43         } elsif (/^#elsif\s(.*)$/) {
44                 my $x = pop @ifs;
45                 defined $x || die "Improper nesting of conditionals";
46                 push @ifs, $x >= 0 ? 0 : (eval_expr $1) ? 1 : -1;
47         } else {
48                 @ifs && $ifs[$#ifs] <= 0 && next;
49                 if (/^$/) {
50                         $empty && next;
51                         $empty = 1;
52                 } else { $empty = 0; }
53                 if (/^#pipe\s+(.+)/) {
54                         my $cmd = $1;
55                         my $val = `$cmd`;
56                         die "Piped command '$cmd' failed" if $?;
57                         print OUT `$1`;
58                 } else {
59                         sub repl ($) {
60                                 my $v = shift @_;
61                                 exists $vars{$v} or die "Cannot substitute $v: variable not set";
62                                 return $vars{$v};
63                         }
64                         s/@(\w+)@/repl($1)/ge;
65                         print OUT;
66                 }
67         }
68 }
69 @ifs && die "Unterminated #ifdef";
70 close IN;
71 close OUT;