56c7e4e3c1f48e85bd4e1a515d32320b77c085ba
[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 = '2011-11-02 07:53'; # 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-2011 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    --since=DATE convert only the logs since DATE;
68                   the default is to convert all log entries.
69    --format=FMT set format string for commit subject and body;
70                   see 'man git-log' for the list of format metacharacters;
71                   the default is '%s%n%b%n'
72
73    --help       display this help and exit
74    --version    output version information and exit
75
76 EXAMPLE:
77
78   $ME --since=2008-01-01 > ChangeLog
79   $ME -- -n 5 foo > last-5-commits-to-branch-foo
80
81 In a FILE specified via --amend, comment lines (starting with "#") are ignored.
82 FILE must consist of <SHA,CODE+> pairs where SHA is a 40-byte SHA1 (alone on
83 a line) referring to a commit in the current project, and CODE refers to one
84 or more consecutive lines of Perl code.  Pairs must be separated by one or
85 more blank line.
86
87 Here is sample input for use with --amend=FILE, from coreutils:
88
89 3a169f4c5d9159283548178668d2fae6fced3030
90 # fix typo in title:
91 s/all tile types/all file types/
92
93 1379ed974f1fa39b12e2ffab18b3f7a607082202
94 # Due to a bug in vc-dwim, I mis-attributed a patch by Paul to myself.
95 # Change the author to be Paul.  Note the escaped "@":
96 s,Jim .*>,Paul Eggert <eggert\@cs.ucla.edu>,
97
98 EOF
99     }
100   exit $exit_code;
101 }
102
103 # If the string $S is a well-behaved file name, simply return it.
104 # If it contains white space, quotes, etc., quote it, and return the new string.
105 sub shell_quote($)
106 {
107   my ($s) = @_;
108   if ($s =~ m![^\w+/.,-]!)
109     {
110       # Convert each single quote to '\''
111       $s =~ s/\'/\'\\\'\'/g;
112       # Then single quote the string.
113       $s = "'$s'";
114     }
115   return $s;
116 }
117
118 sub quoted_cmd(@)
119 {
120   return join (' ', map {shell_quote $_} @_);
121 }
122
123 # Parse file F.
124 # Comment lines (starting with "#") are ignored.
125 # F must consist of <SHA,CODE+> pairs where SHA is a 40-byte SHA1
126 # (alone on a line) referring to a commit in the current project, and
127 # CODE refers to one or more consecutive lines of Perl code.
128 # Pairs must be separated by one or more blank line.
129 sub parse_amend_file($)
130 {
131   my ($f) = @_;
132
133   open F, '<', $f
134     or die "$ME: $f: failed to open for reading: $!\n";
135
136   my $fail;
137   my $h = {};
138   my $in_code = 0;
139   my $sha;
140   while (defined (my $line = <F>))
141     {
142       $line =~ /^\#/
143         and next;
144       chomp $line;
145       $line eq ''
146         and $in_code = 0, next;
147
148       if (!$in_code)
149         {
150           $line =~ /^([0-9a-fA-F]{40})$/
151             or (warn "$ME: $f:$.: invalid line; expected an SHA1\n"),
152               $fail = 1, next;
153           $sha = lc $1;
154           $in_code = 1;
155           exists $h->{$sha}
156             and (warn "$ME: $f:$.: duplicate SHA1\n"),
157               $fail = 1, next;
158         }
159       else
160         {
161           $h->{$sha} ||= '';
162           $h->{$sha} .= "$line\n";
163         }
164     }
165   close F;
166
167   $fail
168     and exit 1;
169
170   return $h;
171 }
172
173 {
174   my $since_date;
175   my $format_string = '%s%n%b%n';
176   my $amend_file;
177   my $append_dot = 0;
178   GetOptions
179     (
180      help => sub { usage 0 },
181      version => sub { print "$ME version $VERSION\n"; exit },
182      'since=s' => \$since_date,
183      'format=s' => \$format_string,
184      'amend=s' => \$amend_file,
185      'append-dot' => \$append_dot,
186     ) or usage 1;
187
188
189   defined $since_date
190     and unshift @ARGV, "--since=$since_date";
191
192   # This is a hash that maps an SHA1 to perl code (i.e., s/old/new/)
193   # that makes a correction in the log or attribution of that commit.
194   my $amend_code = defined $amend_file ? parse_amend_file $amend_file : {};
195
196   my @cmd = (qw (git log --log-size),
197              '--pretty=format:%H:%ct  %an  <%ae>%n%n'.$format_string, @ARGV);
198   open PIPE, '-|', @cmd
199     or die ("$ME: failed to run `". quoted_cmd (@cmd) ."': $!\n"
200             . "(Is your Git too old?  Version 1.5.1 or later is required.)\n");
201
202   my $prev_date_line = '';
203   while (1)
204     {
205       defined (my $in = <PIPE>)
206         or last;
207       $in =~ /^log size (\d+)$/
208         or die "$ME:$.: Invalid line (expected log size):\n$in";
209       my $log_nbytes = $1;
210
211       my $log;
212       my $n_read = read PIPE, $log, $log_nbytes;
213       $n_read == $log_nbytes
214         or die "$ME:$.: unexpected EOF\n";
215
216       # Extract leading hash.
217       my ($sha, $rest) = split ':', $log, 2;
218       defined $sha
219         or die "$ME:$.: malformed log entry\n";
220       $sha =~ /^[0-9a-fA-F]{40}$/
221         or die "$ME:$.: invalid SHA1: $sha\n";
222
223       # If this commit's log requires any transformation, do it now.
224       my $code = $amend_code->{$sha};
225       if (defined $code)
226         {
227           eval 'use Safe';
228           my $s = new Safe;
229           # Put the unpreprocessed entry into "$_".
230           $_ = $rest;
231
232           # Let $code operate on it, safely.
233           my $r = $s->reval("$code")
234             or die "$ME:$.:$sha: failed to eval \"$code\":\n$@\n";
235
236           # Note that we've used this entry.
237           delete $amend_code->{$sha};
238
239           # Update $rest upon success.
240           $rest = $_;
241         }
242
243       my @line = split "\n", $rest;
244       my $author_line = shift @line;
245       defined $author_line
246         or die "$ME:$.: unexpected EOF\n";
247       $author_line =~ /^(\d+)  (.*>)$/
248         or die "$ME:$.: Invalid line "
249           . "(expected date/author/email):\n$author_line\n";
250
251       my $date_line = sprintf "%s  $2\n", strftime ("%F", localtime ($1));
252       # If this line would be the same as the previous date/name/email
253       # line, then arrange not to print it.
254       if ($date_line ne $prev_date_line)
255         {
256           $prev_date_line eq ''
257             or print "\n";
258           print $date_line;
259         }
260       $prev_date_line = $date_line;
261
262       # Omit "Signed-off-by..." lines.
263       @line = grep !/^Signed-off-by: .*>$/, @line;
264
265       # Remove leading and trailing blank lines.
266       if (@line)
267         {
268           while ($line[0] =~ /^\s*$/) { shift @line; }
269           while ($line[$#line] =~ /^\s*$/) { pop @line; }
270         }
271
272       # If there were any lines
273       if (@line == 0)
274         {
275           warn "$ME: warning: empty commit message:\n  $date_line\n";
276         }
277       else
278         {
279           if ($append_dot)
280             {
281               # If the first line of the message has enough room, then
282               if (length $line[0] < 72)
283                 {
284                   # append a dot if there is no other punctuation or blank
285                   # at the end.
286                   $line[0] =~ /[[:punct:]\s]$/
287                     or $line[0] .= '.';
288                 }
289             }
290
291           # Prefix each non-empty line with a TAB.
292           @line = map { length $_ ? "\t$_" : '' } @line;
293
294           print "\n", join ("\n", @line), "\n";
295         }
296
297       defined ($in = <PIPE>)
298         or last;
299       $in ne "\n"
300         and die "$ME:$.: unexpected line:\n$in";
301     }
302
303   close PIPE
304     or die "$ME: error closing pipe from " . quoted_cmd (@cmd) . "\n";
305   # FIXME-someday: include $PROCESS_STATUS in the diagnostic
306
307   # Complain about any unused entry in the --amend=F specified file.
308   my $fail = 0;
309   foreach my $sha (keys %$amend_code)
310     {
311       warn "$ME:$amend_file: unused entry: $sha\n";
312       $fail = 1;
313     }
314
315   exit $fail;
316 }
317
318 # Local Variables:
319 # mode: perl
320 # indent-tabs-mode: nil
321 # eval: (add-hook 'write-file-hooks 'time-stamp)
322 # time-stamp-start: "my $VERSION = '"
323 # time-stamp-format: "%:y-%02m-%02d %02H:%02M"
324 # time-stamp-time-zone: "UTC"
325 # time-stamp-end: "'; # UTC"
326 # End: