Imported Upstream version 1.5
[debian/gzip] / 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-05-22 09:40'; # 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    --since=DATE convert only the logs since DATE;
72                   the default is to convert all log entries.
73    --format=FMT set format string for commit subject and body;
74                   see 'man git-log' for the list of format metacharacters;
75                   the default is '%s%n%b%n'
76    --strip-tab  remove one additional leading TAB from commit message lines.
77    --strip-cherry-pick  remove data inserted by "git cherry-pick";
78                   this includes the "cherry picked from commit ..." line,
79                   and the possible final "Conflicts:" paragraph.
80    --help       display this help and exit
81    --version    output version information and exit
82
83 EXAMPLE:
84
85   $ME --since=2008-01-01 > ChangeLog
86   $ME -- -n 5 foo > last-5-commits-to-branch-foo
87
88 SPECIAL SYNTAX:
89
90 The following types of strings are interpreted specially when they appear
91 at the beginning of a log message line.  They are not copied to the output.
92
93   Copyright-paperwork-exempt: Yes
94     Append the "(tiny change)" notation to the usual "date name email"
95     ChangeLog header to mark a change that does not require a copyright
96     assignment.
97   Co-authored-by: Joe User <user\@example.com>
98     List the specified name and email address on a second
99     ChangeLog header, denoting a co-author.
100   Signed-off-by: Joe User <user\@example.com>
101     These lines are simply elided.
102
103 In a FILE specified via --amend, comment lines (starting with "#") are ignored.
104 FILE must consist of <SHA,CODE+> pairs where SHA is a 40-byte SHA1 (alone on
105 a line) referring to a commit in the current project, and CODE refers to one
106 or more consecutive lines of Perl code.  Pairs must be separated by one or
107 more blank line.
108
109 Here is sample input for use with --amend=FILE, from coreutils:
110
111 3a169f4c5d9159283548178668d2fae6fced3030
112 # fix typo in title:
113 s/all tile types/all file types/
114
115 1379ed974f1fa39b12e2ffab18b3f7a607082202
116 # Due to a bug in vc-dwim, I mis-attributed a patch by Paul to myself.
117 # Change the author to be Paul.  Note the escaped "@":
118 s,Jim .*>,Paul Eggert <eggert\\\@cs.ucla.edu>,
119
120 EOF
121     }
122   exit $exit_code;
123 }
124
125 # If the string $S is a well-behaved file name, simply return it.
126 # If it contains white space, quotes, etc., quote it, and return the new string.
127 sub shell_quote($)
128 {
129   my ($s) = @_;
130   if ($s =~ m![^\w+/.,-]!)
131     {
132       # Convert each single quote to '\''
133       $s =~ s/\'/\'\\\'\'/g;
134       # Then single quote the string.
135       $s = "'$s'";
136     }
137   return $s;
138 }
139
140 sub quoted_cmd(@)
141 {
142   return join (' ', map {shell_quote $_} @_);
143 }
144
145 # Parse file F.
146 # Comment lines (starting with "#") are ignored.
147 # F must consist of <SHA,CODE+> pairs where SHA is a 40-byte SHA1
148 # (alone on a line) referring to a commit in the current project, and
149 # CODE refers to one or more consecutive lines of Perl code.
150 # Pairs must be separated by one or more blank line.
151 sub parse_amend_file($)
152 {
153   my ($f) = @_;
154
155   open F, '<', $f
156     or die "$ME: $f: failed to open for reading: $!\n";
157
158   my $fail;
159   my $h = {};
160   my $in_code = 0;
161   my $sha;
162   while (defined (my $line = <F>))
163     {
164       $line =~ /^\#/
165         and next;
166       chomp $line;
167       $line eq ''
168         and $in_code = 0, next;
169
170       if (!$in_code)
171         {
172           $line =~ /^([0-9a-fA-F]{40})$/
173             or (warn "$ME: $f:$.: invalid line; expected an SHA1\n"),
174               $fail = 1, next;
175           $sha = lc $1;
176           $in_code = 1;
177           exists $h->{$sha}
178             and (warn "$ME: $f:$.: duplicate SHA1\n"),
179               $fail = 1, next;
180         }
181       else
182         {
183           $h->{$sha} ||= '';
184           $h->{$sha} .= "$line\n";
185         }
186     }
187   close F;
188
189   $fail
190     and exit 1;
191
192   return $h;
193 }
194
195 {
196   my $since_date;
197   my $format_string = '%s%n%b%n';
198   my $amend_file;
199   my $append_dot = 0;
200   my $cluster = 1;
201   my $strip_tab = 0;
202   my $strip_cherry_pick = 0;
203   GetOptions
204     (
205      help => sub { usage 0 },
206      version => sub { print "$ME version $VERSION\n"; exit },
207      'since=s' => \$since_date,
208      'format=s' => \$format_string,
209      'amend=s' => \$amend_file,
210      'append-dot' => \$append_dot,
211      'cluster!' => \$cluster,
212      'strip-tab' => \$strip_tab,
213      'strip-cherry-pick' => \$strip_cherry_pick,
214     ) or usage 1;
215
216
217   defined $since_date
218     and unshift @ARGV, "--since=$since_date";
219
220   # This is a hash that maps an SHA1 to perl code (i.e., s/old/new/)
221   # that makes a correction in the log or attribution of that commit.
222   my $amend_code = defined $amend_file ? parse_amend_file $amend_file : {};
223
224   my @cmd = (qw (git log --log-size),
225              '--pretty=format:%H:%ct  %an  <%ae>%n%n'.$format_string, @ARGV);
226   open PIPE, '-|', @cmd
227     or die ("$ME: failed to run '". quoted_cmd (@cmd) ."': $!\n"
228             . "(Is your Git too old?  Version 1.5.1 or later is required.)\n");
229
230   my $prev_multi_paragraph;
231   my $prev_date_line = '';
232   my @prev_coauthors = ();
233   while (1)
234     {
235       defined (my $in = <PIPE>)
236         or last;
237       $in =~ /^log size (\d+)$/
238         or die "$ME:$.: Invalid line (expected log size):\n$in";
239       my $log_nbytes = $1;
240
241       my $log;
242       my $n_read = read PIPE, $log, $log_nbytes;
243       $n_read == $log_nbytes
244         or die "$ME:$.: unexpected EOF\n";
245
246       # Extract leading hash.
247       my ($sha, $rest) = split ':', $log, 2;
248       defined $sha
249         or die "$ME:$.: malformed log entry\n";
250       $sha =~ /^[0-9a-fA-F]{40}$/
251         or die "$ME:$.: invalid SHA1: $sha\n";
252
253       # If this commit's log requires any transformation, do it now.
254       my $code = $amend_code->{$sha};
255       if (defined $code)
256         {
257           eval 'use Safe';
258           my $s = new Safe;
259           # Put the unpreprocessed entry into "$_".
260           $_ = $rest;
261
262           # Let $code operate on it, safely.
263           my $r = $s->reval("$code")
264             or die "$ME:$.:$sha: failed to eval \"$code\":\n$@\n";
265
266           # Note that we've used this entry.
267           delete $amend_code->{$sha};
268
269           # Update $rest upon success.
270           $rest = $_;
271         }
272
273       # Remove lines inserted by "git cherry-pick".
274       if ($strip_cherry_pick)
275         {
276           $rest =~ s/^\s*Conflicts:\n.*//sm;
277           $rest =~ s/^\s*\(cherry picked from commit [\da-f]+\)\n//m;
278         }
279
280       my @line = split "\n", $rest;
281       my $author_line = shift @line;
282       defined $author_line
283         or die "$ME:$.: unexpected EOF\n";
284       $author_line =~ /^(\d+)  (.*>)$/
285         or die "$ME:$.: Invalid line "
286           . "(expected date/author/email):\n$author_line\n";
287
288       # Format 'Copyright-paperwork-exempt: Yes' as a standard ChangeLog
289       # `(tiny change)' annotation.
290       my $tiny = (grep (/^Copyright-paperwork-exempt:\s+[Yy]es$/, @line)
291                   ? '  (tiny change)' : '');
292
293       my $date_line = sprintf "%s  %s$tiny\n",
294         strftime ("%F", localtime ($1)), $2;
295
296       my @coauthors = grep /^Co-authored-by:.*$/, @line;
297       # Omit meta-data lines we've already interpreted.
298       @line = grep !/^(?:Signed-off-by:[ ].*>$
299                        |Co-authored-by:[ ]
300                        |Copyright-paperwork-exempt:[ ]
301                        )/x, @line;
302
303       # Remove leading and trailing blank lines.
304       if (@line)
305         {
306           while ($line[0] =~ /^\s*$/) { shift @line; }
307           while ($line[$#line] =~ /^\s*$/) { pop @line; }
308         }
309
310       # Record whether there are two or more paragraphs.
311       my $multi_paragraph = grep /^\s*$/, @line;
312
313       # Format 'Co-authored-by: A U Thor <email@example.com>' lines in
314       # standard multi-author ChangeLog format.
315       for (@coauthors)
316         {
317           s/^Co-authored-by:\s*/\t    /;
318           s/\s*</  </;
319
320           /<.*?@.*\..*>/
321             or warn "$ME: warning: missing email address for "
322               . substr ($_, 5) . "\n";
323         }
324
325       # If clustering of commit messages has been disabled, if this header
326       # would be different from the previous date/name/email/coauthors header,
327       # or if this or the previous entry consists of two or more paragraphs,
328       # then print the header.
329       if ( ! $cluster
330           || $date_line ne $prev_date_line
331           || "@coauthors" ne "@prev_coauthors"
332           || $multi_paragraph
333           || $prev_multi_paragraph)
334         {
335           $prev_date_line eq ''
336             or print "\n";
337           print $date_line;
338           @coauthors
339             and print join ("\n", @coauthors), "\n";
340         }
341       $prev_date_line = $date_line;
342       @prev_coauthors = @coauthors;
343       $prev_multi_paragraph = $multi_paragraph;
344
345       # If there were any lines
346       if (@line == 0)
347         {
348           warn "$ME: warning: empty commit message:\n  $date_line\n";
349         }
350       else
351         {
352           if ($append_dot)
353             {
354               # If the first line of the message has enough room, then
355               if (length $line[0] < 72)
356                 {
357                   # append a dot if there is no other punctuation or blank
358                   # at the end.
359                   $line[0] =~ /[[:punct:]\s]$/
360                     or $line[0] .= '.';
361                 }
362             }
363
364           # Remove one additional leading TAB from each line.
365           $strip_tab
366             and map { s/^\t// } @line;
367
368           # Prefix each non-empty line with a TAB.
369           @line = map { length $_ ? "\t$_" : '' } @line;
370
371           print "\n", join ("\n", @line), "\n";
372         }
373
374       defined ($in = <PIPE>)
375         or last;
376       $in ne "\n"
377         and die "$ME:$.: unexpected line:\n$in";
378     }
379
380   close PIPE
381     or die "$ME: error closing pipe from " . quoted_cmd (@cmd) . "\n";
382   # FIXME-someday: include $PROCESS_STATUS in the diagnostic
383
384   # Complain about any unused entry in the --amend=F specified file.
385   my $fail = 0;
386   foreach my $sha (keys %$amend_code)
387     {
388       warn "$ME:$amend_file: unused entry: $sha\n";
389       $fail = 1;
390     }
391
392   exit $fail;
393 }
394
395 # Local Variables:
396 # mode: perl
397 # indent-tabs-mode: nil
398 # eval: (add-hook 'write-file-hooks 'time-stamp)
399 # time-stamp-start: "my $VERSION = '"
400 # time-stamp-format: "%:y-%02m-%02d %02H:%02M"
401 # time-stamp-time-zone: "UTC"
402 # time-stamp-end: "'; # UTC"
403 # End: