Debian Codegraph @

src/pl/plperl/text2macro.pl

raw
1
2 # Copyright (c) 2021-2025, PostgreSQL Global Development Group
3
4 # src/pl/plperl/text2macro.pl
5
6 =head1 NAME
7
8 text2macro.pl - convert text files into C string-literal macro definitions
9
10 =head1 SYNOPSIS
11
12 text2macro [options] file ... > output.h
13
14 Options:
15
16 --prefix=S - add prefix S to the names of the macros
17 --name=S - use S as the macro name (assumes only one file)
18
19 =head1 DESCRIPTION
20
21 Reads one or more text files and outputs a corresponding series of C
22 pre-processor macro definitions. Each macro defines a string literal that
23 contains the contents of the corresponding text file. The basename of the text
24 file is capitalized and used as the name of the macro, along with an optional prefix.
25
26 =cut
27
28 use strict;
29 use warnings FATAL => 'all';
30
31 use Getopt::Long;
32
33 GetOptions(
34 'prefix=s' => \my $opt_prefix,
35 'name=s' => \my $opt_name,
36 'selftest!' => sub { exit selftest() },) or exit 1;
37
38 # This was once a command-line option, but meson is obstreperous
39 # about passing backslashes through custom targets.
40 my $opt_strip = '^(#.*|\s*)$';
41
42 die "No text files specified"
43 unless @ARGV;
44
45 print qq{
46 /*
47 * DO NOT EDIT - THIS FILE IS AUTOGENERATED - CHANGES WILL BE LOST
48 * Generated by src/pl/plperl/text2macro.pl
49 */
50 };
51
52 for my $src_file (@ARGV)
53 {
54
55 (my $macro = $src_file) =~ s/ .*? (\w+) (?:\.\w+) $/$1/x;
56
57 open my $src_fh, '<', $src_file
58 or die "Can't open $src_file: $!";
59
60 printf qq{#define %s%s \\\n},
61 $opt_prefix || '',
62 ($opt_name) ? $opt_name : uc $macro;
63 while (<$src_fh>)
64 {
65 chomp;
66
67 next if $opt_strip and m/$opt_strip/o;
68
69 # escape the text to suite C string literal rules
70 s/\\/\\\\/g;
71 s/"/\\"/g;
72
73 printf qq{"%s\\n" \\\n}, $_;
74 }
75 print qq{""\n\n};
76 }
77
78 print "/* end */\n";
79
80 exit 0;
81
82
83 sub selftest
84 {
85 my $tmp = "text2macro_tmp";
86 my $string = q{a '' '\\'' "" "\\"" "\\\\" "\\\\n" b};
87
88 open my $fh, '>', "$tmp.pl" or die;
89 print $fh $string;
90 close $fh;
91
92 system("perl $0 --name=X $tmp.pl > $tmp.c") == 0 or die;
93 open $fh, '>>', "$tmp.c" or die;
94 print $fh "#include <stdio.h>\n";
95 print $fh "int main() { puts(X); return 0; }\n";
96 close $fh;
97 system("cat -n $tmp.c") == 0 or die;
98
99 system("make $tmp") == 0 or die;
100 open $fh, '<', "./$tmp |" or die;
101 my $result = <$fh>;
102 unlink <$tmp.*>;
103
104 warn "Test string: $string\n";
105 warn "Result : $result";
106 die "Failed!" if $result ne "$string\n";
107 return;
108 }