mklog revision 1.6
1#!/usr/bin/perl
2# Copyright (C) 2012-2014 Free Software Foundation, Inc.
3#
4# This file is part of GCC.
5#
6# GCC is free software; you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation; either version 3, or (at your option)
9# any later version.
10#
11# GCC is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with GCC; see the file COPYING.  If not, write to
18# the Free Software Foundation, 51 Franklin Street, Fifth Floor,
19# Boston, MA 02110-1301, USA.
20
21# This script parses a .diff file generated with 'diff -up' or 'diff -cp'
22# and adds a skeleton ChangeLog file to the file. It does not try to be
23# very smart when parsing function names, but it produces a reasonable
24# approximation.
25#
26# Author: Diego Novillo <dnovillo@google.com> and
27#         Cary Coutant <ccoutant@google.com>
28
29use File::Temp;
30use File::Copy qw(cp mv);
31
32$date = `date +%Y-%m-%d`; chop ($date);
33
34$dot_mklog_format_msg =
35    "The .mklog format is:\n"
36    . "NAME = ...\n"
37    . "EMAIL = ...\n";
38
39# Create a .mklog to reflect your profile, if necessary.
40my $conf = "$ENV{HOME}/.mklog";
41if (-f "$conf") {
42    open (CONF, "$conf")
43	or die "Could not open file '$conf' for reading: $!\n";
44    while (<CONF>) {
45	if (m/^\s*NAME\s*=\s*(.*?)\s*$/) {
46	    $name = $1;
47	} elsif (m/^\s*EMAIL\s*=\s*(.*?)\s*$/) {
48	    $addr = $1;
49	}
50    }
51    if (!($name && $addr)) {
52	die "Could not read .mklog settings.\n"
53	    . $dot_mklog_format_msg;
54    }
55} else {
56    $name = `git config user.name`;
57    chomp($name);
58    $addr = `git config user.email`;
59    chomp($addr);
60
61    if (!($name && $addr)) {
62	die "Could not read git user.name and user.email settings.\n"
63	    . "Please add missing git settings, or create a .mklog file in"
64	    . " $ENV{HOME}.\n"
65	    . $dot_mklog_format_msg;
66    }
67}
68
69$gcc_root = $0;
70$gcc_root =~ s/[^\\\/]+$/../;
71
72#-----------------------------------------------------------------------------
73# Program starts here. You should not need to edit anything below this
74# line.
75#-----------------------------------------------------------------------------
76$inline = 0;
77if ($#ARGV == 1 && ("$ARGV[0]" eq "-i" || "$ARGV[0]" eq "--inline")) {
78	shift;
79	$inline = 1;
80} elsif ($#ARGV != 0) {
81    $prog = `basename $0`; chop ($prog);
82    print <<EOF;
83usage: $prog [ -i | --inline ] file.diff
84
85Generate ChangeLog template for file.diff.
86It assumes that patch has been created with -up or -cp.
87When -i is used, the ChangeLog template is followed by the contents of
88file.diff.
89When file.diff is -, read standard input.
90When -i is used and file.diff is not -, it writes to file.diff, otherwise it
91writes to stdout.
92EOF
93    exit 1;
94}
95
96$diff = $ARGV[0];
97$dir = `dirname $diff`; chop ($dir);
98$basename = `basename $diff`; chop ($basename);
99$hdrline = "$date  $name  <$addr>";
100
101sub get_clname ($) {
102	return ('ChangeLog', $_[0]) if ($_[0] !~ /[\/\\]/);
103
104	my $dirname = $_[0];
105	while ($dirname) {
106		my $clname = "$dirname/ChangeLog";
107		if (-f "$gcc_root/$clname" || -f "$clname") {
108			my $relname = substr ($_[0], length ($dirname) + 1);
109			return ($clname, $relname);
110		} else {
111			$dirname =~ s/[\/\\]?[^\/\\]*$//;
112		} 
113	}
114
115	return ('Unknown ChangeLog', $_[0]);
116}
117
118sub remove_suffixes ($) {
119	my $filename = $_[0];
120	$filename =~ s/^[ab]\///;
121	$filename =~ s/\.jj$//;
122	return $filename;
123}
124
125sub is_context_hunk_start {
126	return @_[0] =~ /^\*\*\*\*\*\** ([a-zA-Z0-9_].*)/;
127}
128
129sub is_unified_hunk_start {
130	return @_[0] =~ /^@@ .* @@ ([a-zA-Z0-9_].*)/;
131}
132
133# Check if line is a top-level declaration.
134sub is_top_level {
135	my ($function, $is_context_diff) = (@_);
136	if (is_unified_hunk_start ($function)
137	    || is_context_hunk_start ($function)) {
138	    return 1;
139	}
140	if ($is_context_diff) {
141		$function =~ s/^..//;
142	} else {
143		$function =~ s/^.//;
144	}
145	return $function && $function !~ /^[\s{#]/;
146}
147
148# Read contents of .diff file
149open (DFILE, $diff) or die "Could not open file $diff for reading";
150chomp (my @diff_lines = <DFILE>);
151close (DFILE);
152
153# Array diff_lines is modified by the log generation, so save a copy in
154# orig_diff_lines if needed.
155if ($inline) {
156    @orig_diff_lines = @diff_lines;
157}
158
159# For every file in the .diff print all the function names in ChangeLog
160# format.
161%cl_entries = ();
162$change_msg = undef;
163$look_for_funs = 0;
164$clname = get_clname('');
165$line_idx = 0;
166foreach (@diff_lines) {
167    # Stop processing functions if we found a new file.
168	# Remember both left and right names because one may be /dev/null.
169    # Don't be fooled by line markers in case of context diff.
170    if (!/\*\*\*$/ && /^[+*][+*][+*] +(\S+)/) {
171		$left = remove_suffixes ($1);
172		$look_for_funs = 0;
173	}
174    if (!/---$/ && /^--- +(\S+)?/) {
175		$right = remove_suffixes ($1);
176		$look_for_funs = 0;
177	}
178
179	# Check if the body of diff started.
180	# We should now have both left and right name,
181	# so we can decide filename.
182
183    if ($left && (/^\*{15}/ || /^@@ /)) {
184	# If we have not seen any function names in the previous file (ie,
185	# $change_msg is empty), we just write out a ':' before starting the next
186	# file.
187	if ($clname) {
188		$cl_entries{$clname} .= $change_msg ? "$change_msg" : ":\n";
189	}
190
191	if ($left eq $right) {
192		$filename = $left;
193	} elsif($left eq '/dev/null') {
194		$filename = $right;
195	} elsif($right eq '/dev/null') {
196		$filename = $left;
197	} else {
198		print STDERR "Error: failed to parse diff for $left and $right\n";
199		exit 1;
200	}
201	$left = $right = undef;
202	($clname, $relname) = get_clname ($filename);
203	$cl_entries{$clname} .= "\t* $relname";
204	$change_msg = '';
205	$look_for_funs = $filename =~ '\.(c|cpp|C|cc|h|inc|def)$';
206    }
207
208    # Context diffs have extra whitespace after first char;
209    # remove it to make matching easier.
210    if ($is_context_diff) {
211      s/^([-+! ]) /\1/;
212    }
213
214    # Remember the last line in a diff block that might start
215    # a new function.
216    if (/^[-+! ]([a-zA-Z0-9_].*)/) {
217        $save_fn = $1;
218    }
219
220    # Check if file is newly added.
221    # Two patterns: for context and unified diff.
222    if (/^\*\*\* 0 \*\*\*\*/
223        || /^@@ -0,0 \+1.* @@/) {
224        $change_msg = $filename =~ /testsuite.*(?<!\.exp)$/ ? ": New test.\n" : ": New file.\n";
225        $look_for_funs = 0;
226    }
227
228    # Check if file was removed.
229    # Two patterns: for context and unified diff.
230    if (/^--- 0 ----/
231        || /^@@ -1.* \+0,0 @@/) {
232        $change_msg = ": Remove.\n";
233        $look_for_funs = 0;
234    }
235
236    if (is_unified_hunk_start ($diff_lines[$line_idx])) {
237        $is_context_diff = 0;
238    }
239    elsif (is_context_hunk_start ($diff_lines[$line_idx])) {
240	    $is_context_diff = 1;
241    }
242
243    # If we find a new function, print it in brackets.  Special case if
244    # this is the first function in a file.  
245    #
246    # Note that we don't try too hard to find good matches.  This should
247    # return a superset of the actual set of functions in the .diff file.
248    #
249    # The first pattern works with context diff files (diff -c). The
250    # second pattern works with unified diff files (diff -u).
251    #
252    # The third pattern looks for the starts of functions or classes
253    # within a diff block both for context and unified diff files.
254    if ($look_for_funs
255        && (/^\*\*\*\*\*\** ([a-zA-Z0-9_].*)/
256	|| /^@@ .* @@ ([a-zA-Z0-9_].*)/
257	|| /^[-+! ](\{)/))
258      {
259	$_ = $1;
260	my $fn;
261	if (/^\{/) {
262	    # Beginning of a new function.
263	    $_ = $save_fn;
264	} else {
265	    $save_fn = "";
266	}
267	if (/;$/) {
268	    # No usable function name found.
269	} elsif (/^((class|struct|union|enum) [a-zA-Z0-9_]+)/) {
270	    # Discard stuff after the class/struct/etc. tag.
271	    $fn = $1;
272	} elsif (/([a-zA-Z0-9_][^(]*)\(/) {
273	    # Discard template and function parameters.
274	    $fn = $1;
275	    1 while ($fn =~ s/<[^<>]*>//);
276	    $fn =~ s/[ \t]*$//;
277	}
278	# Check is function really modified
279	$no_real_change = 0;
280	$idx = $line_idx;
281	# Skip line info in context diffs.
282	while ($idx <= $#diff_lines && $is_context_diff
283               && $diff_lines[$idx + 1] =~ /^[-\*]{3} [0-9]/) {
284		++$idx;
285	}
286	# Check all lines till the first change
287	# for the presence of really changed function
288	do {
289		++$idx;
290		$no_real_change = $idx > $#diff_lines
291				  || is_top_level ($diff_lines[$idx], $is_context_diff);
292	} while (!$no_real_change && ($diff_lines[$idx] !~ /^[-+!]/));
293	if ($fn && !$seen_names{$fn} && !$no_real_change) {
294	    # If this is the first function in the file, we display it next
295	    # to the filename, so we need an extra space before the opening
296	    # brace.
297	    if (!$change_msg) {
298		$change_msg .= " ";
299	    } else {
300		$change_msg .= "\t";
301	    }
302
303		$change_msg .= "($fn):\n";
304	    $seen_names{$fn} = 1;
305	}
306    }
307	$line_idx++;
308}
309
310# If we have not seen any function names (ie, $change_msg is empty), we just
311# write out a ':'. This happens when there is only one file with no
312# functions.
313$cl_entries{$clname} .= $change_msg ? "$change_msg\n" : ":\n";
314
315if ($inline && $diff ne "-") {
316	# Get a temp filename, rather than an open filehandle, because we use
317	# the open to truncate.
318	$tmp = mktemp("tmp.XXXXXXXX") or die "Could not create temp file: $!";
319
320	# Copy the permissions to the temp file (in File::Copy module version
321	# 2.15 and later).
322	cp $diff, $tmp or die "Could not copy patch file to temp file: $!";
323
324	# Open the temp file, clearing contents.
325	open (OUTPUTFILE, '>', $tmp) or die "Could not open temp file: $!";
326} else {
327	*OUTPUTFILE = STDOUT;
328}
329
330# Print the log
331foreach my $clname (keys %cl_entries) {
332	print OUTPUTFILE "$clname:\n\n$hdrline\n\n$cl_entries{$clname}\n";
333}
334
335if ($inline) {
336	# Append the patch to the log
337	foreach (@orig_diff_lines) {
338		print OUTPUTFILE "$_\n";
339	}
340}
341
342if ($inline && $diff ne "-") {
343	# Close $tmp
344	close(OUTPUTFILE);
345
346	# Write new contents to $diff atomically
347	mv $tmp, $diff or die "Could not move temp file to patch file: $!";
348}
349
350exit 0;
351