gitlog-to-changelog: VPATH build issues.
[gnulib.git] / build-aux / gitlog-to-changelog
1 eval '(exit $?0)' && eval 'exec perl -wS "$0" ${1+"$@"}'
2   & eval 'exec perl -wS "$0" $argv:q'
3     if 0;
4 # Convert git log output to ChangeLog format.
5
6 my $VERSION = '2012-07-16 18:34'; # UTC
7 # The definition above must lie within the first 8 lines in order
8 # for the Emacs time-stamp write hook (at end) to update it.
9 # If you change this file with Emacs, please let the write hook
10 # do its job.  Otherwise, update this string manually.
11
12 # Copyright (C) 2008-2012 Free Software Foundation, Inc.
13
14 # This program is free software: you can redistribute it and/or modify
15 # it under the terms of the GNU General Public License as published by
16 # the Free Software Foundation, either version 3 of the License, or
17 # (at your option) any later version.
18
19 # This program is distributed in the hope that it will be useful,
20 # but WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 # GNU General Public License for more details.
23
24 # You should have received a copy of the GNU General Public License
25 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
26
27 # Written by Jim Meyering
28
29 use strict;
30 use warnings;
31 use Getopt::Long;
32 use POSIX qw(strftime);
33
34 (my $ME = $0) =~ s|.*/||;
35
36 # use File::Coda; # http://meyering.net/code/Coda/
37 END {
38   defined fileno STDOUT or return;
39   close STDOUT and return;
40   warn "$ME: failed to close standard output: $!\n";
41   $? ||= 1;
42 }
43
44 sub usage ($)
45 {
46   my ($exit_code) = @_;
47   my $STREAM = ($exit_code == 0 ? *STDOUT : *STDERR);
48   if ($exit_code != 0)
49     {
50       print $STREAM "Try '$ME --help' for more information.\n";
51     }
52   else
53     {
54       print $STREAM <<EOF;
55 Usage: $ME [OPTIONS] [ARGS]
56
57 Convert git log output to ChangeLog format.  If present, any ARGS
58 are passed to "git log".  To avoid ARGS being parsed as options to
59 $ME, they may be preceded by '--'.
60
61 OPTIONS:
62
63    --amend=FILE FILE maps from an SHA1 to perl code (i.e., s/old/new/) that
64                   makes a change to SHA1's commit log text or metadata.
65    --append-dot append a dot to the first line of each commit message if
66                   there is no other punctuation or blank at the end.
67    --no-cluster never cluster commit messages under the same date/author
68                   header; the default is to cluster adjacent commit messages
69                   if their headers are the same and neither commit message
70                   contains multiple paragraphs.
71    --srcdir=DIR the root of the source tree, containing the '.git' directory.
72    --since=DATE convert only the logs since DATE;
73                   the default is to convert all log entries.
74    --format=FMT set format string for commit subject and body;
75                   see 'man git-log' for the list of format metacharacters;
76                   the default is '%s%n%b%n'
77    --strip-tab  remove one additional leading TAB from commit message lines.
78    --strip-cherry-pick  remove data inserted by "git cherry-pick";
79                   this includes the "cherry picked from commit ..." line,
80                   and the possible final "Conflicts:" paragraph.
81    --help       display this help and exit
82    --version    output version information and exit
83
84 EXAMPLE:
85
86   $ME --since=2008-01-01 > ChangeLog
87   $ME -- -n 5 foo > last-5-commits-to-branch-foo
88
89 SPECIAL SYNTAX:
90
91 The following types of strings are interpreted specially when they appear
92 at the beginning of a log message line.  They are not copied to the output.
93
94   Copyright-paperwork-exempt: Yes
95     Append the "(tiny change)" notation to the usual "date name email"
96     ChangeLog header to mark a change that does not require a copyright
97     assignment.
98   Co-authored-by: Joe User <user\@example.com>
99     List the specified name and email address on a second
100     ChangeLog header, denoting a co-author.
101   Signed-off-by: Joe User <user\@example.com>
102     These lines are simply elided.
103
104 In a FILE specified via --amend, comment lines (starting with "#") are ignored.
105 FILE must consist of <SHA,CODE+> pairs where SHA is a 40-byte SHA1 (alone on
106 a line) referring to a commit in the current project, and CODE refers to one
107 or more consecutive lines of Perl code.  Pairs must be separated by one or
108 more blank line.
109
110 Here is sample input for use with --amend=FILE, from coreutils:
111
112 3a169f4c5d9159283548178668d2fae6fced3030
113 # fix typo in title:
114 s/all tile types/all file types/
115
116 1379ed974f1fa39b12e2ffab18b3f7a607082202
117 # Due to a bug in vc-dwim, I mis-attributed a patch by Paul to myself.
118 # Change the author to be Paul.  Note the escaped "@":
119 s,Jim .*>,Paul Eggert <eggert\\\@cs.ucla.edu>,
120
121 EOF
122     }
123   exit $exit_code;
124 }
125
126 # If the string $S is a well-behaved file name, simply return it.
127 # If it contains white space, quotes, etc., quote it, and return the new string.
128 sub shell_quote($)
129 {
130   my ($s) = @_;
131   if ($s =~ m![^\w+/.,-]!)
132     {
133       # Convert each single quote to '\''
134       $s =~ s/\'/\'\\\'\'/g;
135       # Then single quote the string.
136       $s = "'$s'";
137     }
138   return $s;
139 }
140
141 sub quoted_cmd(@)
142 {
143   return join (' ', map {shell_quote $_} @_);
144 }
145
146 # Parse file F.
147 # Comment lines (starting with "#") are ignored.
148 # F must consist of <SHA,CODE+> pairs where SHA is a 40-byte SHA1
149 # (alone on a line) referring to a commit in the current project, and
150 # CODE refers to one or more consecutive lines of Perl code.
151 # Pairs must be separated by one or more blank line.
152 sub parse_amend_file($)
153 {
154   my ($f) = @_;
155
156   open F, '<', $f
157     or die "$ME: $f: failed to open for reading: $!\n";
158
159   my $fail;
160   my $h = {};
161   my $in_code = 0;
162   my $sha;
163   while (defined (my $line = <F>))
164     {
165       $line =~ /^\#/
166         and next;
167       chomp $line;
168       $line eq ''
169         and $in_code = 0, next;
170
171       if (!$in_code)
172         {
173           $line =~ /^([0-9a-fA-F]{40})$/
174             or (warn "$ME: $f:$.: invalid line; expected an SHA1\n"),
175               $fail = 1, next;
176           $sha = lc $1;
177           $in_code = 1;
178           exists $h->{$sha}
179             and (warn "$ME: $f:$.: duplicate SHA1\n"),
180               $fail = 1, next;
181         }
182       else
183         {
184           $h->{$sha} ||= '';
185           $h->{$sha} .= "$line\n";
186         }
187     }
188   close F;
189
190   $fail
191     and exit 1;
192
193   return $h;
194 }
195
196 {
197   my $since_date;
198   my $format_string = '%s%n%b%n';
199   my $amend_file;
200   my $append_dot = 0;
201   my $cluster = 1;
202   my $strip_tab = 0;
203   my $strip_cherry_pick = 0;
204   my $srcdir;
205   GetOptions
206     (
207      help => sub { usage 0 },
208      version => sub { print "$ME version $VERSION\n"; exit },
209      'since=s' => \$since_date,
210      'format=s' => \$format_string,
211      'amend=s' => \$amend_file,
212      'append-dot' => \$append_dot,
213      'cluster!' => \$cluster,
214      'strip-tab' => \$strip_tab,
215      'strip-cherry-pick' => \$strip_cherry_pick,
216      'srcdir=s' => \$srcdir,
217     ) or usage 1;
218
219   defined $since_date
220     and unshift @ARGV, "--since=$since_date";
221
222   # This is a hash that maps an SHA1 to perl code (i.e., s/old/new/)
223   # that makes a correction in the log or attribution of that commit.
224   my $amend_code = defined $amend_file ? parse_amend_file $amend_file : {};
225
226   my @cmd = ('git',
227              defined $srcdir ? ("--git-dir=$srcdir/.git") : (),
228              qw(log --log-size),
229              '--pretty=format:%H:%ct  %an  <%ae>%n%n'.$format_string, @ARGV);
230   open PIPE, '-|', @cmd
231     or die ("$ME: failed to run '". quoted_cmd (@cmd) ."': $!\n"
232             . "(Is your Git too old?  Version 1.5.1 or later is required.)\n");
233
234   my $prev_multi_paragraph;
235   my $prev_date_line = '';
236   my @prev_coauthors = ();
237   while (1)
238     {
239       defined (my $in = <PIPE>)
240         or last;
241       $in =~ /^log size (\d+)$/
242         or die "$ME:$.: Invalid line (expected log size):\n$in";
243       my $log_nbytes = $1;
244
245       my $log;
246       my $n_read = read PIPE, $log, $log_nbytes;
247       $n_read == $log_nbytes
248         or die "$ME:$.: unexpected EOF\n";
249
250       # Extract leading hash.
251       my ($sha, $rest) = split ':', $log, 2;
252       defined $sha
253         or die "$ME:$.: malformed log entry\n";
254       $sha =~ /^[0-9a-fA-F]{40}$/
255         or die "$ME:$.: invalid SHA1: $sha\n";
256
257       # If this commit's log requires any transformation, do it now.
258       my $code = $amend_code->{$sha};
259       if (defined $code)
260         {
261           eval 'use Safe';
262           my $s = new Safe;
263           # Put the unpreprocessed entry into "$_".
264           $_ = $rest;
265
266           # Let $code operate on it, safely.
267           my $r = $s->reval("$code")
268             or die "$ME:$.:$sha: failed to eval \"$code\":\n$@\n";
269
270           # Note that we've used this entry.
271           delete $amend_code->{$sha};
272
273           # Update $rest upon success.
274           $rest = $_;
275         }
276
277       # Remove lines inserted by "git cherry-pick".
278       if ($strip_cherry_pick)
279         {
280           $rest =~ s/^\s*Conflicts:\n.*//sm;
281           $rest =~ s/^\s*\(cherry picked from commit [\da-f]+\)\n//m;
282         }
283
284       my @line = split "\n", $rest;
285       my $author_line = shift @line;
286       defined $author_line
287         or die "$ME:$.: unexpected EOF\n";
288       $author_line =~ /^(\d+)  (.*>)$/
289         or die "$ME:$.: Invalid line "
290           . "(expected date/author/email):\n$author_line\n";
291
292       # Format 'Copyright-paperwork-exempt: Yes' as a standard ChangeLog
293       # `(tiny change)' annotation.
294       my $tiny = (grep (/^Copyright-paperwork-exempt:\s+[Yy]es$/, @line)
295                   ? '  (tiny change)' : '');
296
297       my $date_line = sprintf "%s  %s$tiny\n",
298         strftime ("%F", localtime ($1)), $2;
299
300       my @coauthors = grep /^Co-authored-by:.*$/, @line;
301       # Omit meta-data lines we've already interpreted.
302       @line = grep !/^(?:Signed-off-by:[ ].*>$
303                        |Co-authored-by:[ ]
304                        |Copyright-paperwork-exempt:[ ]
305                        )/x, @line;
306
307       # Remove leading and trailing blank lines.
308       if (@line)
309         {
310           while ($line[0] =~ /^\s*$/) { shift @line; }
311           while ($line[$#line] =~ /^\s*$/) { pop @line; }
312         }
313
314       # Record whether there are two or more paragraphs.
315       my $multi_paragraph = grep /^\s*$/, @line;
316
317       # Format 'Co-authored-by: A U Thor <email@example.com>' lines in
318       # standard multi-author ChangeLog format.
319       for (@coauthors)
320         {
321           s/^Co-authored-by:\s*/\t    /;
322           s/\s*</  </;
323
324           /<.*?@.*\..*>/
325             or warn "$ME: warning: missing email address for "
326               . substr ($_, 5) . "\n";
327         }
328
329       # If clustering of commit messages has been disabled, if this header
330       # would be different from the previous date/name/email/coauthors header,
331       # or if this or the previous entry consists of two or more paragraphs,
332       # then print the header.
333       if ( ! $cluster
334           || $date_line ne $prev_date_line
335           || "@coauthors" ne "@prev_coauthors"
336           || $multi_paragraph
337           || $prev_multi_paragraph)
338         {
339           $prev_date_line eq ''
340             or print "\n";
341           print $date_line;
342           @coauthors
343             and print join ("\n", @coauthors), "\n";
344         }
345       $prev_date_line = $date_line;
346       @prev_coauthors = @coauthors;
347       $prev_multi_paragraph = $multi_paragraph;
348
349       # If there were any lines
350       if (@line == 0)
351         {
352           warn "$ME: warning: empty commit message:\n  $date_line\n";
353         }
354       else
355         {
356           if ($append_dot)
357             {
358               # If the first line of the message has enough room, then
359               if (length $line[0] < 72)
360                 {
361                   # append a dot if there is no other punctuation or blank
362                   # at the end.
363                   $line[0] =~ /[[:punct:]\s]$/
364                     or $line[0] .= '.';
365                 }
366             }
367
368           # Remove one additional leading TAB from each line.
369           $strip_tab
370             and map { s/^\t// } @line;
371
372           # Prefix each non-empty line with a TAB.
373           @line = map { length $_ ? "\t$_" : '' } @line;
374
375           print "\n", join ("\n", @line), "\n";
376         }
377
378       defined ($in = <PIPE>)
379         or last;
380       $in ne "\n"
381         and die "$ME:$.: unexpected line:\n$in";
382     }
383
384   close PIPE
385     or die "$ME: error closing pipe from " . quoted_cmd (@cmd) . "\n";
386   # FIXME-someday: include $PROCESS_STATUS in the diagnostic
387
388   # Complain about any unused entry in the --amend=F specified file.
389   my $fail = 0;
390   foreach my $sha (keys %$amend_code)
391     {
392       warn "$ME:$amend_file: unused entry: $sha\n";
393       $fail = 1;
394     }
395
396   exit $fail;
397 }
398
399 # Local Variables:
400 # mode: perl
401 # indent-tabs-mode: nil
402 # eval: (add-hook 'write-file-hooks 'time-stamp)
403 # time-stamp-start: "my $VERSION = '"
404 # time-stamp-format: "%:y-%02m-%02d %02H:%02M"
405 # time-stamp-time-zone: "UTC"
406 # time-stamp-end: "'; # UTC"
407 # End: