1#!/usr/local/bin/perl
2
3# sedition-pp <keyword> <ppfile> <source file>
4#
5# Replaces occurrences of @<keyword>@ in the source file
6# with the text found in <ppfile>. <ppfile> may contain
7# multiple lines of text. In the <source file>, the @<keyword>@
8# must be on a line of its own - it may have leading and
9# trailing comment delimiters, but that's all. That's because these
10# delimiters will be replicated in the multiline substitution;
11# see below.
12#
13# Note that the <keyword> is surrounded by @@ in the text
14# where it's to be replaced. These delimiters do not appear in the command
15# line; this allows you to run sedition-pp on scripts and Makefiles
16# that themselves contain sedition-pp command lines, without clobbering
17# those commands.
18#
19# sedition-pp preserves and replicates leading and trailing context,
20# permitting language-independent substitution within comments.
21# For example,
22#     sedition-pp FOO foofile foo.c
23# finds in foo.c (C code) a line like
24#     * @FOO@
25# and replaces it with the text of "foofile", which might
26# result in:
27#     * An example license for foo.
28#     * Copyright (C) ...
29#
30# Whereas a (shell or Perl script) line like
31#     # @FOO@
32# would become
33#     # An example license for foo.
34#     # Copyright (C) ...
35#
36# And an HTML section like
37#   <!--
38#     -- @FOO@
39#     -->
40# is replaced with
41#     <!--
42#       -- An example license for foo.
43#       -- Copyright (C) ...
44#       -->
45#
46# modified from licenseadd.pl in ssdk; SRE, Mon Mar 31 19:39:50 2003
47# SVN $Id: sedition-pp 1531 2005-12-13 20:53:46Z eddy $
48#
49
50$keyword     = shift;
51$ppfile      = shift;
52$sourcefile  = shift;
53
54if (! -e $sourcefile) { die "no such file $sourcefile"; }
55($dev,$ino,$mode) = stat($sourcefile);
56
57open(PP,$ppfile) || die;
58$nlines = 0;
59while (<PP>)
60{
61    chomp;
62    $ppline[$nlines] = $_;
63    $nlines++;
64}
65close(PP);
66
67open(TMPFILE,">/tmp/tmp.pp.sedition") || die "Fatal: can't open /tmp/tmp.pp.sedition : $!\n";
68open(SOURCE,$sourcefile) || die;
69while (<SOURCE>)
70{
71    if (/^(.*)\@$keyword\@(.*)$/)
72    {
73	$start = $1;
74	$end   = $2;
75	foreach $line (@ppline)
76	{
77	    print TMPFILE "$start$line$end\n";
78	}
79    } else { print TMPFILE $_;}
80}
81close SOURCE;
82close TMPFILE;
83
84# Replace the original file with the new one, and restore the original
85# file's mode.
86#
87unlink $sourcefile;
88system("mv /tmp/tmp.pp.sedition $sourcefile");
89chmod $mode, $sourcefile;
90