]> mj.ucw.cz Git - libucw.git/blob - build/genconf
The write_merged() hook is no longer required in simple cases.
[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 sub eval_expr {
24         $_ = shift @_;
25         s/\b(CONFIG_\w+)\b/defined($options{$1}) ? 1 : 0/ge;
26         return eval $_;
27 }
28
29 open IN, $ARGV[0] or die "Unable to open $ARGV[0]";
30 open OUT, ">$ARGV[1]" or die "Unable to create $ARGV[1]";
31 my @ifs = ();   # stack of conditions, 1=satisfied, -1=unsatisfied, 0=shadowed
32 my $empty = 0;  # last line was empty
33 while (<IN>) {
34         if (/^#ifdef\s+(\w+)/) {
35                 push @ifs, (@ifs && $ifs[$#ifs] <= 0) ? 0 : (defined $options{$1}) ? 1 : -1;
36         } elsif (/^#ifndef\s+(\w+)/) {
37                 push @ifs, (@ifs && $ifs[$#ifs] <= 0) ? 0 : (defined $options{$1}) ? -1 : 1;
38         } elsif (/^#if\s(.*)$/) {
39                 push @ifs, (@ifs && $ifs[$#ifs] <= 0) ? 0 : (eval_expr $1) ? 1 : -1;
40         } elsif (/^#endif/) {
41                 defined pop @ifs || die "Improper nesting of conditionals";
42         } elsif (/^#else/) {
43                 my $x = pop @ifs;
44                 defined $x || die "Improper nesting of conditionals";
45                 push @ifs, $x >= 0 ? 0 : 1;
46         } elsif (/^#elsif\s(.*)$/) {
47                 my $x = pop @ifs;
48                 defined $x || die "Improper nesting of conditionals";
49                 push @ifs, $x >= 0 ? 0 : (eval_expr $1) ? 1 : -1;
50         } else {
51                 @ifs && $ifs[$#ifs] <= 0 && next;
52                 if (/^$/) {
53                         $empty && next;
54                         $empty = 1;
55                 } else { $empty = 0; }
56                 if (/^#pipe\s+(.+)/) {
57                         my $cmd = $1;
58                         my $val = `$cmd`;
59                         die "Piped command '$cmd' failed" if $?;
60                         print OUT `$1`;
61                 } else {
62                         sub repl ($) {
63                                 my $v = shift @_;
64                                 exists $vars{$v} or die "Cannot substitute $v: variable not set";
65                                 return $vars{$v};
66                         }
67                         s/@(\w+)@/repl($1)/ge;
68                         print OUT;
69                 }
70         }
71 }
72 @ifs && die "Unterminated #ifdef";
73 close IN;
74 close OUT;