Commit | Line | Data |
---|---|---|
ec15bdbc LM |
1 | #!/usr/bin/perl |
2 | ||
3 | use strict; | |
4 | ||
5 | # default value | |
6 | my $format = "%"; | |
7 | my $pattern = ""; | |
8 | ||
9 | # help message | |
10 | sub usage() { | |
11 | ||
12 | print <<EOF; | |
13 | usage: getcomments [-f string] [-h] [-p regex] file... | |
14 | -f|--format string: format string for output printing [%] | |
15 | -h|--help: help message | |
16 | -p|--pattern regex: pattern matching on block [] | |
17 | ||
18 | Extract C/C++ block of comments | |
19 | ||
20 | Example: getcomments.pl -p='test:\\s' -f='./%' random.c | |
21 | EOF | |
22 | ||
23 | exit 1; | |
24 | } | |
25 | ||
26 | usage() if ($#ARGV < 0); | |
27 | ||
28 | # process argument | |
29 | foreach my $arg (@ARGV) { | |
30 | use vars qw/$caif $caip $naif $naip/; | |
31 | ||
32 | # analyse format argument | |
33 | ($caif, $_) = ($arg =~ /^(-f|--format)=(.*)/); | |
34 | ($caif, $_) = (1, $arg) if ($naif); | |
35 | next if ($naif = ($arg =~ /^(-f|--format)$/)); | |
36 | if ($caif) { $format = $_; next } | |
37 | ||
38 | # check for help message | |
39 | usage() if ($arg =~ /^(-h|--help)$/); | |
40 | ||
41 | # analyse pattern argument | |
42 | ($caip, $_) = ($arg =~ /^(-p|--pattern)=(.*)/); | |
43 | ($caip, $_) = (1, $arg) if ($naip); | |
44 | next if ($naip = ($arg =~ /^(-p|--pattern)$/)); | |
45 | if ($caip) { $pattern = $_; next } | |
46 | ||
47 | # no more argument, only file | |
48 | my $filename = $arg; | |
49 | ||
50 | # open file | |
51 | if (!open (IN, "<", $filename)) { | |
52 | print "Can not open $filename\n"; | |
53 | } | |
54 | ||
55 | # init table of comments | |
56 | my @comments; | |
57 | $#comments = -1; | |
58 | ||
59 | # read all the file | |
60 | while ($_ .= <IN>) { | |
61 | my $cmt; | |
62 | ||
63 | # process c++ comments | |
64 | ($cmt, $_) = m{//\s*(.*?)\s*$()} if (m{//} && !m{/\*.*//}); | |
65 | ||
66 | # process standard c comments | |
67 | ($cmt, $_) = m{^.*?/\*\s*(.*?)\s*\*/(.*)}s if (m{/\*.*\*/}s); | |
68 | ||
69 | push(@comments, $cmt) if ($cmt); | |
70 | ||
71 | # empty buffer if no comment is present | |
72 | undef($_) if (!m{/[/*]}); | |
73 | } | |
74 | ||
75 | # close file | |
76 | close (IN); | |
77 | ||
78 | # display comment blocks | |
79 | foreach my $block (@comments) { | |
80 | if (($block) = ($block =~ /$pattern(.*)/s)) { | |
81 | ($_ = $format) =~ s/%/$block/gs; | |
82 | print "$_\n"; | |
83 | } | |
84 | } | |
85 | } |