scripts/get_maintainer.pl: add default --git-fallback, remove default --git
[pandora-kernel.git] / scripts / get_maintainer.pl
1 #!/usr/bin/perl -w
2 # (c) 2007, Joe Perches <joe@perches.com>
3 #           created from checkpatch.pl
4 #
5 # Print selected MAINTAINERS information for
6 # the files modified in a patch or for a file
7 #
8 # usage: perl scripts/get_maintainer.pl [OPTIONS] <patch>
9 #        perl scripts/get_maintainer.pl [OPTIONS] -f <file>
10 #
11 # Licensed under the terms of the GNU GPL License version 2
12
13 use strict;
14
15 my $P = $0;
16 my $V = '0.25';
17
18 use Getopt::Long qw(:config no_auto_abbrev);
19
20 my $lk_path = "./";
21 my $email = 1;
22 my $email_usename = 1;
23 my $email_maintainer = 1;
24 my $email_list = 1;
25 my $email_subscriber_list = 0;
26 my $email_git_penguin_chiefs = 0;
27 my $email_git = 0;
28 my $email_git_all_signature_types = 0;
29 my $email_git_blame = 0;
30 my $email_git_fallback = 1;
31 my $email_git_min_signatures = 1;
32 my $email_git_max_maintainers = 5;
33 my $email_git_min_percent = 5;
34 my $email_git_since = "1-year-ago";
35 my $email_hg_since = "-365";
36 my $email_remove_duplicates = 1;
37 my $output_multiline = 1;
38 my $output_separator = ", ";
39 my $output_roles = 0;
40 my $output_rolestats = 0;
41 my $scm = 0;
42 my $web = 0;
43 my $subsystem = 0;
44 my $status = 0;
45 my $keywords = 1;
46 my $sections = 0;
47 my $file_emails = 0;
48 my $from_filename = 0;
49 my $pattern_depth = 0;
50 my $version = 0;
51 my $help = 0;
52
53 my $exit = 0;
54
55 my @penguin_chief = ();
56 push(@penguin_chief, "Linus Torvalds:torvalds\@linux-foundation.org");
57 #Andrew wants in on most everything - 2009/01/14
58 #push(@penguin_chief, "Andrew Morton:akpm\@linux-foundation.org");
59
60 my @penguin_chief_names = ();
61 foreach my $chief (@penguin_chief) {
62     if ($chief =~ m/^(.*):(.*)/) {
63         my $chief_name = $1;
64         my $chief_addr = $2;
65         push(@penguin_chief_names, $chief_name);
66     }
67 }
68 my $penguin_chiefs = "\(" . join("|", @penguin_chief_names) . "\)";
69
70 # Signature types of people who are either
71 #       a) responsible for the code in question, or
72 #       b) familiar enough with it to give relevant feedback
73 my @signature_tags = ();
74 push(@signature_tags, "Signed-off-by:");
75 push(@signature_tags, "Reviewed-by:");
76 push(@signature_tags, "Acked-by:");
77 my $signaturePattern = "\(" . join("|", @signature_tags) . "\)";
78
79 # rfc822 email address - preloaded methods go here.
80 my $rfc822_lwsp = "(?:(?:\\r\\n)?[ \\t])";
81 my $rfc822_char = '[\\000-\\377]';
82
83 # VCS command support: class-like functions and strings
84
85 my %VCS_cmds;
86
87 my %VCS_cmds_git = (
88     "execute_cmd" => \&git_execute_cmd,
89     "available" => '(which("git") ne "") && (-d ".git")',
90     "find_signers_cmd" => "git log --no-color --since=\$email_git_since -- \$file",
91     "find_commit_signers_cmd" => "git log --no-color -1 \$commit",
92     "find_commit_author_cmd" => "git log -1 --format=\"%an <%ae>\" \$commit",
93     "blame_range_cmd" => "git blame -l -L \$diff_start,+\$diff_length \$file",
94     "blame_file_cmd" => "git blame -l \$file",
95     "commit_pattern" => "^commit [0-9a-f]{40,40}",
96     "blame_commit_pattern" => "^([0-9a-f]+) "
97 );
98
99 my %VCS_cmds_hg = (
100     "execute_cmd" => \&hg_execute_cmd,
101     "available" => '(which("hg") ne "") && (-d ".hg")',
102     "find_signers_cmd" =>
103         "hg log --date=\$email_hg_since" .
104                 " --template='commit {node}\\n{desc}\\n' -- \$file",
105     "find_commit_signers_cmd" => "hg log --template='{desc}\\n' -r \$commit",
106     "find_commit_author_cmd" => "hg log -l 1 --template='{author}\\n' -r \$commit",
107     "blame_range_cmd" => "",            # not supported
108     "blame_file_cmd" => "hg blame -c \$file",
109     "commit_pattern" => "^commit [0-9a-f]{40,40}",
110     "blame_commit_pattern" => "^([0-9a-f]+):"
111 );
112
113 if (-f "${lk_path}.get_maintainer.conf") {
114     my @conf_args;
115     open(my $conffile, '<', "${lk_path}.get_maintainer.conf")
116         or warn "$P: Can't open .get_maintainer.conf: $!\n";
117     while (<$conffile>) {
118         my $line = $_;
119
120         $line =~ s/\s*\n?$//g;
121         $line =~ s/^\s*//g;
122         $line =~ s/\s+/ /g;
123
124         next if ($line =~ m/^\s*#/);
125         next if ($line =~ m/^\s*$/);
126
127         my @words = split(" ", $line);
128         foreach my $word (@words) {
129             last if ($word =~ m/^#/);
130             push (@conf_args, $word);
131         }
132     }
133     close($conffile);
134     unshift(@ARGV, @conf_args) if @conf_args;
135 }
136
137 if (!GetOptions(
138                 'email!' => \$email,
139                 'git!' => \$email_git,
140                 'git-all-signature-types!' => \$email_git_all_signature_types,
141                 'git-blame!' => \$email_git_blame,
142                 'git-fallback!' => \$email_git_fallback,
143                 'git-chief-penguins!' => \$email_git_penguin_chiefs,
144                 'git-min-signatures=i' => \$email_git_min_signatures,
145                 'git-max-maintainers=i' => \$email_git_max_maintainers,
146                 'git-min-percent=i' => \$email_git_min_percent,
147                 'git-since=s' => \$email_git_since,
148                 'hg-since=s' => \$email_hg_since,
149                 'remove-duplicates!' => \$email_remove_duplicates,
150                 'm!' => \$email_maintainer,
151                 'n!' => \$email_usename,
152                 'l!' => \$email_list,
153                 's!' => \$email_subscriber_list,
154                 'multiline!' => \$output_multiline,
155                 'roles!' => \$output_roles,
156                 'rolestats!' => \$output_rolestats,
157                 'separator=s' => \$output_separator,
158                 'subsystem!' => \$subsystem,
159                 'status!' => \$status,
160                 'scm!' => \$scm,
161                 'web!' => \$web,
162                 'pattern-depth=i' => \$pattern_depth,
163                 'k|keywords!' => \$keywords,
164                 'sections!' => \$sections,
165                 'fe|file-emails!' => \$file_emails,
166                 'f|file' => \$from_filename,
167                 'v|version' => \$version,
168                 'h|help|usage' => \$help,
169                 )) {
170     die "$P: invalid argument - use --help if necessary\n";
171 }
172
173 if ($help != 0) {
174     usage();
175     exit 0;
176 }
177
178 if ($version != 0) {
179     print("${P} ${V}\n");
180     exit 0;
181 }
182
183 if (-t STDIN && !@ARGV) {
184     # We're talking to a terminal, but have no command line arguments.
185     die "$P: missing patchfile or -f file - use --help if necessary\n";
186 }
187
188 if ($output_separator ne ", ") {
189     $output_multiline = 0;
190 }
191
192 if ($output_rolestats) {
193     $output_roles = 1;
194 }
195
196 if ($sections) {
197     $email = 0;
198     $email_list = 0;
199     $scm = 0;
200     $status = 0;
201     $subsystem = 0;
202     $web = 0;
203     $keywords = 0;
204 } else {
205     my $selections = $email + $scm + $status + $subsystem + $web;
206     if ($selections == 0) {
207         die "$P:  Missing required option: email, scm, status, subsystem or web\n";
208     }
209 }
210
211 if ($email &&
212     ($email_maintainer + $email_list + $email_subscriber_list +
213      $email_git + $email_git_penguin_chiefs + $email_git_blame) == 0) {
214     die "$P: Please select at least 1 email option\n";
215 }
216
217 if (!top_of_kernel_tree($lk_path)) {
218     die "$P: The current directory does not appear to be "
219         . "a linux kernel source tree.\n";
220 }
221
222 if ($email_git_all_signature_types) {
223     $signaturePattern = "(.+?)[Bb][Yy]:";
224 }
225
226 ## Read MAINTAINERS for type/value pairs
227
228 my @typevalue = ();
229 my %keyword_hash;
230
231 open (my $maint, '<', "${lk_path}MAINTAINERS")
232     or die "$P: Can't open MAINTAINERS: $!\n";
233 while (<$maint>) {
234     my $line = $_;
235
236     if ($line =~ m/^(\C):\s*(.*)/) {
237         my $type = $1;
238         my $value = $2;
239
240         ##Filename pattern matching
241         if ($type eq "F" || $type eq "X") {
242             $value =~ s@\.@\\\.@g;       ##Convert . to \.
243             $value =~ s/\*/\.\*/g;       ##Convert * to .*
244             $value =~ s/\?/\./g;         ##Convert ? to .
245             ##if pattern is a directory and it lacks a trailing slash, add one
246             if ((-d $value)) {
247                 $value =~ s@([^/])$@$1/@;
248             }
249         } elsif ($type eq "K") {
250             $keyword_hash{@typevalue} = $value;
251         }
252         push(@typevalue, "$type:$value");
253     } elsif (!/^(\s)*$/) {
254         $line =~ s/\n$//g;
255         push(@typevalue, $line);
256     }
257 }
258 close($maint);
259
260 my %mailmap;
261
262 if ($email_remove_duplicates) {
263     open(my $mailmap, '<', "${lk_path}.mailmap")
264         or warn "$P: Can't open .mailmap: $!\n";
265     while (<$mailmap>) {
266         my $line = $_;
267
268         next if ($line =~ m/^\s*#/);
269         next if ($line =~ m/^\s*$/);
270
271         my ($name, $address) = parse_email($line);
272         $line = format_email($name, $address, $email_usename);
273
274         next if ($line =~ m/^\s*$/);
275
276         if (exists($mailmap{$name})) {
277             my $obj = $mailmap{$name};
278             push(@$obj, $address);
279         } else {
280             my @arr = ($address);
281             $mailmap{$name} = \@arr;
282         }
283     }
284     close($mailmap);
285 }
286
287 ## use the filenames on the command line or find the filenames in the patchfiles
288
289 my @files = ();
290 my @range = ();
291 my @keyword_tvi = ();
292 my @file_emails = ();
293
294 if (!@ARGV) {
295     push(@ARGV, "&STDIN");
296 }
297
298 foreach my $file (@ARGV) {
299     if ($file ne "&STDIN") {
300         ##if $file is a directory and it lacks a trailing slash, add one
301         if ((-d $file)) {
302             $file =~ s@([^/])$@$1/@;
303         } elsif (!(-f $file)) {
304             die "$P: file '${file}' not found\n";
305         }
306     }
307     if ($from_filename) {
308         push(@files, $file);
309         if ($file ne "MAINTAINERS" && -f $file && ($keywords || $file_emails)) {
310             open(my $f, '<', $file)
311                 or die "$P: Can't open $file: $!\n";
312             my $text = do { local($/) ; <$f> };
313             close($f);
314             if ($keywords) {
315                 foreach my $line (keys %keyword_hash) {
316                     if ($text =~ m/$keyword_hash{$line}/x) {
317                         push(@keyword_tvi, $line);
318                     }
319                 }
320             }
321             if ($file_emails) {
322                 my @poss_addr = $text =~ m$[A-Za-zÀ-ÿ\"\' \,\.\+-]*\s*[\,]*\s*[\(\<\{]{0,1}[A-Za-z0-9_\.\+-]+\@[A-Za-z0-9\.-]+\.[A-Za-z0-9]+[\)\>\}]{0,1}$g;
323                 push(@file_emails, clean_file_emails(@poss_addr));
324             }
325         }
326     } else {
327         my $file_cnt = @files;
328         my $lastfile;
329
330         open(my $patch, "< $file")
331             or die "$P: Can't open $file: $!\n";
332         while (<$patch>) {
333             my $patch_line = $_;
334             if (m/^\+\+\+\s+(\S+)/) {
335                 my $filename = $1;
336                 $filename =~ s@^[^/]*/@@;
337                 $filename =~ s@\n@@;
338                 $lastfile = $filename;
339                 push(@files, $filename);
340             } elsif (m/^\@\@ -(\d+),(\d+)/) {
341                 if ($email_git_blame) {
342                     push(@range, "$lastfile:$1:$2");
343                 }
344             } elsif ($keywords) {
345                 foreach my $line (keys %keyword_hash) {
346                     if ($patch_line =~ m/^[+-].*$keyword_hash{$line}/x) {
347                         push(@keyword_tvi, $line);
348                     }
349                 }
350             }
351         }
352         close($patch);
353
354         if ($file_cnt == @files) {
355             warn "$P: file '${file}' doesn't appear to be a patch.  "
356                 . "Add -f to options?\n";
357         }
358         @files = sort_and_uniq(@files);
359     }
360 }
361
362 @file_emails = uniq(@file_emails);
363
364 my @email_to = ();
365 my @list_to = ();
366 my @scm = ();
367 my @web = ();
368 my @subsystem = ();
369 my @status = ();
370
371 # Find responsible parties
372
373 foreach my $file (@files) {
374
375     my %hash;
376     my $exact_pattern_match = 0;
377     my $tvi = find_first_section();
378     while ($tvi < @typevalue) {
379         my $start = find_starting_index($tvi);
380         my $end = find_ending_index($tvi);
381         my $exclude = 0;
382         my $i;
383
384         #Do not match excluded file patterns
385
386         for ($i = $start; $i < $end; $i++) {
387             my $line = $typevalue[$i];
388             if ($line =~ m/^(\C):\s*(.*)/) {
389                 my $type = $1;
390                 my $value = $2;
391                 if ($type eq 'X') {
392                     if (file_match_pattern($file, $value)) {
393                         $exclude = 1;
394                         last;
395                     }
396                 }
397             }
398         }
399
400         if (!$exclude) {
401             for ($i = $start; $i < $end; $i++) {
402                 my $line = $typevalue[$i];
403                 if ($line =~ m/^(\C):\s*(.*)/) {
404                     my $type = $1;
405                     my $value = $2;
406                     if ($type eq 'F') {
407                         if (file_match_pattern($file, $value)) {
408                             my $value_pd = ($value =~ tr@/@@);
409                             my $file_pd = ($file  =~ tr@/@@);
410                             $value_pd++ if (substr($value,-1,1) ne "/");
411                             $value_pd = -1 if ($value =~ /^\.\*/);
412                             $exact_pattern_match = 1 if ($value_pd >= $file_pd);
413                             if ($pattern_depth == 0 ||
414                                 (($file_pd - $value_pd) < $pattern_depth)) {
415                                 $hash{$tvi} = $value_pd;
416                             }
417                         }
418                     }
419                 }
420             }
421         }
422
423         $tvi = $end + 1;
424     }
425
426     foreach my $line (sort {$hash{$b} <=> $hash{$a}} keys %hash) {
427         add_categories($line);
428         if ($sections) {
429             my $i;
430             my $start = find_starting_index($line);
431             my $end = find_ending_index($line);
432             for ($i = $start; $i < $end; $i++) {
433                 my $line = $typevalue[$i];
434                 if ($line =~ /^[FX]:/) {                ##Restore file patterns
435                     $line =~ s/([^\\])\.([^\*])/$1\?$2/g;
436                     $line =~ s/([^\\])\.$/$1\?/g;       ##Convert . back to ?
437                     $line =~ s/\\\./\./g;               ##Convert \. to .
438                     $line =~ s/\.\*/\*/g;               ##Convert .* to *
439                 }
440                 $line =~ s/^([A-Z]):/$1:\t/g;
441                 print("$line\n");
442             }
443             print("\n");
444         }
445     }
446
447     if ($email &&
448         ($email_git || ($email_git_fallback && !$exact_pattern_match))) {
449         vcs_file_signoffs($file);
450     }
451
452     if ($email && $email_git_blame) {
453         vcs_file_blame($file);
454     }
455 }
456
457 if ($keywords) {
458     @keyword_tvi = sort_and_uniq(@keyword_tvi);
459     foreach my $line (@keyword_tvi) {
460         add_categories($line);
461     }
462 }
463
464 if ($email) {
465     foreach my $chief (@penguin_chief) {
466         if ($chief =~ m/^(.*):(.*)/) {
467             my $email_address;
468
469             $email_address = format_email($1, $2, $email_usename);
470             if ($email_git_penguin_chiefs) {
471                 push(@email_to, [$email_address, 'chief penguin']);
472             } else {
473                 @email_to = grep($_->[0] !~ /${email_address}/, @email_to);
474             }
475         }
476     }
477
478     foreach my $email (@file_emails) {
479         my ($name, $address) = parse_email($email);
480
481         my $tmp_email = format_email($name, $address, $email_usename);
482         push_email_address($tmp_email, '');
483         add_role($tmp_email, 'in file');
484     }
485 }
486
487 if ($email || $email_list) {
488     my @to = ();
489     if ($email) {
490         @to = (@to, @email_to);
491     }
492     if ($email_list) {
493         @to = (@to, @list_to);
494     }
495     output(merge_email(@to));
496 }
497
498 if ($scm) {
499     @scm = uniq(@scm);
500     output(@scm);
501 }
502
503 if ($status) {
504     @status = uniq(@status);
505     output(@status);
506 }
507
508 if ($subsystem) {
509     @subsystem = uniq(@subsystem);
510     output(@subsystem);
511 }
512
513 if ($web) {
514     @web = uniq(@web);
515     output(@web);
516 }
517
518 exit($exit);
519
520 sub file_match_pattern {
521     my ($file, $pattern) = @_;
522     if (substr($pattern, -1) eq "/") {
523         if ($file =~ m@^$pattern@) {
524             return 1;
525         }
526     } else {
527         if ($file =~ m@^$pattern@) {
528             my $s1 = ($file =~ tr@/@@);
529             my $s2 = ($pattern =~ tr@/@@);
530             if ($s1 == $s2) {
531                 return 1;
532             }
533         }
534     }
535     return 0;
536 }
537
538 sub usage {
539     print <<EOT;
540 usage: $P [options] patchfile
541        $P [options] -f file|directory
542 version: $V
543
544 MAINTAINER field selection options:
545   --email => print email address(es) if any
546     --git => include recent git \*-by: signers
547     --git-all-signature-types => include signers regardless of signature type
548         or use only ${signaturePattern} signers (default: $email_git_all_signature_types)
549     --git-fallback => use git when no exact MAINTAINERS pattern (default: $email_git_fallback)
550     --git-chief-penguins => include ${penguin_chiefs}
551     --git-min-signatures => number of signatures required (default: $email_git_min_signatures)
552     --git-max-maintainers => maximum maintainers to add (default: $email_git_max_maintainers)
553     --git-min-percent => minimum percentage of commits required (default: $email_git_min_percent)
554     --git-blame => use git blame to find modified commits for patch or file
555     --git-since => git history to use (default: $email_git_since)
556     --hg-since => hg history to use (default: $email_hg_since)
557     --m => include maintainer(s) if any
558     --n => include name 'Full Name <addr\@domain.tld>'
559     --l => include list(s) if any
560     --s => include subscriber only list(s) if any
561     --remove-duplicates => minimize duplicate email names/addresses
562     --roles => show roles (status:subsystem, git-signer, list, etc...)
563     --rolestats => show roles and statistics (commits/total_commits, %)
564     --file-emails => add email addresses found in -f file (default: 0 (off))
565   --scm => print SCM tree(s) if any
566   --status => print status if any
567   --subsystem => print subsystem name if any
568   --web => print website(s) if any
569
570 Output type options:
571   --separator [, ] => separator for multiple entries on 1 line
572     using --separator also sets --nomultiline if --separator is not [, ]
573   --multiline => print 1 entry per line
574
575 Other options:
576   --pattern-depth => Number of pattern directory traversals (default: 0 (all))
577   --keywords => scan patch for keywords (default: 1 (on))
578   --sections => print the entire subsystem sections with pattern matches
579   --version => show version
580   --help => show this help information
581
582 Default options:
583   [--email --git --m --n --l --multiline --pattern-depth=0 --remove-duplicates]
584
585 Notes:
586   Using "-f directory" may give unexpected results:
587       Used with "--git", git signators for _all_ files in and below
588           directory are examined as git recurses directories.
589           Any specified X: (exclude) pattern matches are _not_ ignored.
590       Used with "--nogit", directory is used as a pattern match,
591           no individual file within the directory or subdirectory
592           is matched.
593       Used with "--git-blame", does not iterate all files in directory
594   Using "--git-blame" is slow and may add old committers and authors
595       that are no longer active maintainers to the output.
596   Using "--roles" or "--rolestats" with git send-email --cc-cmd or any
597       other automated tools that expect only ["name"] <email address>
598       may not work because of additional output after <email address>.
599   Using "--rolestats" and "--git-blame" shows the #/total=% commits,
600       not the percentage of the entire file authored.  # of commits is
601       not a good measure of amount of code authored.  1 major commit may
602       contain a thousand lines, 5 trivial commits may modify a single line.
603   If git is not installed, but mercurial (hg) is installed and an .hg
604       repository exists, the following options apply to mercurial:
605           --git,
606           --git-min-signatures, --git-max-maintainers, --git-min-percent, and
607           --git-blame
608       Use --hg-since not --git-since to control date selection
609   File ".get_maintainer.conf", if it exists in the linux kernel source root
610       directory, can change whatever get_maintainer defaults are desired.
611       Entries in this file can be any command line argument.
612       This file is prepended to any additional command line arguments.
613       Multiple lines and # comments are allowed.
614 EOT
615 }
616
617 sub top_of_kernel_tree {
618         my ($lk_path) = @_;
619
620         if ($lk_path ne "" && substr($lk_path,length($lk_path)-1,1) ne "/") {
621             $lk_path .= "/";
622         }
623         if (   (-f "${lk_path}COPYING")
624             && (-f "${lk_path}CREDITS")
625             && (-f "${lk_path}Kbuild")
626             && (-f "${lk_path}MAINTAINERS")
627             && (-f "${lk_path}Makefile")
628             && (-f "${lk_path}README")
629             && (-d "${lk_path}Documentation")
630             && (-d "${lk_path}arch")
631             && (-d "${lk_path}include")
632             && (-d "${lk_path}drivers")
633             && (-d "${lk_path}fs")
634             && (-d "${lk_path}init")
635             && (-d "${lk_path}ipc")
636             && (-d "${lk_path}kernel")
637             && (-d "${lk_path}lib")
638             && (-d "${lk_path}scripts")) {
639                 return 1;
640         }
641         return 0;
642 }
643
644 sub parse_email {
645     my ($formatted_email) = @_;
646
647     my $name = "";
648     my $address = "";
649
650     if ($formatted_email =~ /^([^<]+)<(.+\@.*)>.*$/) {
651         $name = $1;
652         $address = $2;
653     } elsif ($formatted_email =~ /^\s*<(.+\@\S*)>.*$/) {
654         $address = $1;
655     } elsif ($formatted_email =~ /^(.+\@\S*).*$/) {
656         $address = $1;
657     }
658
659     $name =~ s/^\s+|\s+$//g;
660     $name =~ s/^\"|\"$//g;
661     $address =~ s/^\s+|\s+$//g;
662
663     if ($name =~ /[^\w \-]/i) {          ##has "must quote" chars
664         $name =~ s/(?<!\\)"/\\"/g;       ##escape quotes
665         $name = "\"$name\"";
666     }
667
668     return ($name, $address);
669 }
670
671 sub format_email {
672     my ($name, $address, $usename) = @_;
673
674     my $formatted_email;
675
676     $name =~ s/^\s+|\s+$//g;
677     $name =~ s/^\"|\"$//g;
678     $address =~ s/^\s+|\s+$//g;
679
680     if ($name =~ /[^\w \-]/i) {          ##has "must quote" chars
681         $name =~ s/(?<!\\)"/\\"/g;       ##escape quotes
682         $name = "\"$name\"";
683     }
684
685     if ($usename) {
686         if ("$name" eq "") {
687             $formatted_email = "$address";
688         } else {
689             $formatted_email = "$name <$address>";
690         }
691     } else {
692         $formatted_email = $address;
693     }
694
695     return $formatted_email;
696 }
697
698 sub find_first_section {
699     my $index = 0;
700
701     while ($index < @typevalue) {
702         my $tv = $typevalue[$index];
703         if (($tv =~ m/^(\C):\s*(.*)/)) {
704             last;
705         }
706         $index++;
707     }
708
709     return $index;
710 }
711
712 sub find_starting_index {
713     my ($index) = @_;
714
715     while ($index > 0) {
716         my $tv = $typevalue[$index];
717         if (!($tv =~ m/^(\C):\s*(.*)/)) {
718             last;
719         }
720         $index--;
721     }
722
723     return $index;
724 }
725
726 sub find_ending_index {
727     my ($index) = @_;
728
729     while ($index < @typevalue) {
730         my $tv = $typevalue[$index];
731         if (!($tv =~ m/^(\C):\s*(.*)/)) {
732             last;
733         }
734         $index++;
735     }
736
737     return $index;
738 }
739
740 sub get_maintainer_role {
741     my ($index) = @_;
742
743     my $i;
744     my $start = find_starting_index($index);
745     my $end = find_ending_index($index);
746
747     my $role;
748     my $subsystem = $typevalue[$start];
749     if (length($subsystem) > 20) {
750         $subsystem = substr($subsystem, 0, 17);
751         $subsystem =~ s/\s*$//;
752         $subsystem = $subsystem . "...";
753     }
754
755     for ($i = $start + 1; $i < $end; $i++) {
756         my $tv = $typevalue[$i];
757         if ($tv =~ m/^(\C):\s*(.*)/) {
758             my $ptype = $1;
759             my $pvalue = $2;
760             if ($ptype eq "S") {
761                 $role = $pvalue;
762             }
763         }
764     }
765
766     $role = lc($role);
767     if      ($role eq "supported") {
768         $role = "supporter";
769     } elsif ($role eq "maintained") {
770         $role = "maintainer";
771     } elsif ($role eq "odd fixes") {
772         $role = "odd fixer";
773     } elsif ($role eq "orphan") {
774         $role = "orphan minder";
775     } elsif ($role eq "obsolete") {
776         $role = "obsolete minder";
777     } elsif ($role eq "buried alive in reporters") {
778         $role = "chief penguin";
779     }
780
781     return $role . ":" . $subsystem;
782 }
783
784 sub get_list_role {
785     my ($index) = @_;
786
787     my $i;
788     my $start = find_starting_index($index);
789     my $end = find_ending_index($index);
790
791     my $subsystem = $typevalue[$start];
792     if (length($subsystem) > 20) {
793         $subsystem = substr($subsystem, 0, 17);
794         $subsystem =~ s/\s*$//;
795         $subsystem = $subsystem . "...";
796     }
797
798     if ($subsystem eq "THE REST") {
799         $subsystem = "";
800     }
801
802     return $subsystem;
803 }
804
805 sub add_categories {
806     my ($index) = @_;
807
808     my $i;
809     my $start = find_starting_index($index);
810     my $end = find_ending_index($index);
811
812     push(@subsystem, $typevalue[$start]);
813
814     for ($i = $start + 1; $i < $end; $i++) {
815         my $tv = $typevalue[$i];
816         if ($tv =~ m/^(\C):\s*(.*)/) {
817             my $ptype = $1;
818             my $pvalue = $2;
819             if ($ptype eq "L") {
820                 my $list_address = $pvalue;
821                 my $list_additional = "";
822                 my $list_role = get_list_role($i);
823
824                 if ($list_role ne "") {
825                     $list_role = ":" . $list_role;
826                 }
827                 if ($list_address =~ m/([^\s]+)\s+(.*)$/) {
828                     $list_address = $1;
829                     $list_additional = $2;
830                 }
831                 if ($list_additional =~ m/subscribers-only/) {
832                     if ($email_subscriber_list) {
833                         push(@list_to, [$list_address, "subscriber list${list_role}"]);
834                     }
835                 } else {
836                     if ($email_list) {
837                         push(@list_to, [$list_address, "open list${list_role}"]);
838                     }
839                 }
840             } elsif ($ptype eq "M") {
841                 my ($name, $address) = parse_email($pvalue);
842                 if ($name eq "") {
843                     if ($i > 0) {
844                         my $tv = $typevalue[$i - 1];
845                         if ($tv =~ m/^(\C):\s*(.*)/) {
846                             if ($1 eq "P") {
847                                 $name = $2;
848                                 $pvalue = format_email($name, $address, $email_usename);
849                             }
850                         }
851                     }
852                 }
853                 if ($email_maintainer) {
854                     my $role = get_maintainer_role($i);
855                     push_email_addresses($pvalue, $role);
856                 }
857             } elsif ($ptype eq "T") {
858                 push(@scm, $pvalue);
859             } elsif ($ptype eq "W") {
860                 push(@web, $pvalue);
861             } elsif ($ptype eq "S") {
862                 push(@status, $pvalue);
863             }
864         }
865     }
866 }
867
868 my %email_hash_name;
869 my %email_hash_address;
870
871 sub email_inuse {
872     my ($name, $address) = @_;
873
874     return 1 if (($name eq "") && ($address eq ""));
875     return 1 if (($name ne "") && exists($email_hash_name{$name}));
876     return 1 if (($address ne "") && exists($email_hash_address{$address}));
877
878     return 0;
879 }
880
881 sub push_email_address {
882     my ($line, $role) = @_;
883
884     my ($name, $address) = parse_email($line);
885
886     if ($address eq "") {
887         return 0;
888     }
889
890     if (!$email_remove_duplicates) {
891         push(@email_to, [format_email($name, $address, $email_usename), $role]);
892     } elsif (!email_inuse($name, $address)) {
893         push(@email_to, [format_email($name, $address, $email_usename), $role]);
894         $email_hash_name{$name}++;
895         $email_hash_address{$address}++;
896     }
897
898     return 1;
899 }
900
901 sub push_email_addresses {
902     my ($address, $role) = @_;
903
904     my @address_list = ();
905
906     if (rfc822_valid($address)) {
907         push_email_address($address, $role);
908     } elsif (@address_list = rfc822_validlist($address)) {
909         my $array_count = shift(@address_list);
910         while (my $entry = shift(@address_list)) {
911             push_email_address($entry, $role);
912         }
913     } else {
914         if (!push_email_address($address, $role)) {
915             warn("Invalid MAINTAINERS address: '" . $address . "'\n");
916         }
917     }
918 }
919
920 sub add_role {
921     my ($line, $role) = @_;
922
923     my ($name, $address) = parse_email($line);
924     my $email = format_email($name, $address, $email_usename);
925
926     foreach my $entry (@email_to) {
927         if ($email_remove_duplicates) {
928             my ($entry_name, $entry_address) = parse_email($entry->[0]);
929             if (($name eq $entry_name || $address eq $entry_address)
930                 && ($role eq "" || !($entry->[1] =~ m/$role/))
931             ) {
932                 if ($entry->[1] eq "") {
933                     $entry->[1] = "$role";
934                 } else {
935                     $entry->[1] = "$entry->[1],$role";
936                 }
937             }
938         } else {
939             if ($email eq $entry->[0]
940                 && ($role eq "" || !($entry->[1] =~ m/$role/))
941             ) {
942                 if ($entry->[1] eq "") {
943                     $entry->[1] = "$role";
944                 } else {
945                     $entry->[1] = "$entry->[1],$role";
946                 }
947             }
948         }
949     }
950 }
951
952 sub which {
953     my ($bin) = @_;
954
955     foreach my $path (split(/:/, $ENV{PATH})) {
956         if (-e "$path/$bin") {
957             return "$path/$bin";
958         }
959     }
960
961     return "";
962 }
963
964 sub mailmap {
965     my (@lines) = @_;
966     my %hash;
967
968     foreach my $line (@lines) {
969         my ($name, $address) = parse_email($line);
970         if (!exists($hash{$name})) {
971             $hash{$name} = $address;
972         } elsif ($address ne $hash{$name}) {
973             $address = $hash{$name};
974             $line = format_email($name, $address, $email_usename);
975         }
976         if (exists($mailmap{$name})) {
977             my $obj = $mailmap{$name};
978             foreach my $map_address (@$obj) {
979                 if (($map_address eq $address) &&
980                     ($map_address ne $hash{$name})) {
981                     $line = format_email($name, $hash{$name}, $email_usename);
982                 }
983             }
984         }
985     }
986
987     return @lines;
988 }
989
990 sub git_execute_cmd {
991     my ($cmd) = @_;
992     my @lines = ();
993
994     my $output = `$cmd`;
995     $output =~ s/^\s*//gm;
996     @lines = split("\n", $output);
997
998     return @lines;
999 }
1000
1001 sub hg_execute_cmd {
1002     my ($cmd) = @_;
1003     my @lines = ();
1004
1005     my $output = `$cmd`;
1006     @lines = split("\n", $output);
1007
1008     return @lines;
1009 }
1010
1011 sub vcs_find_signers {
1012     my ($cmd) = @_;
1013     my @lines = ();
1014     my $commits;
1015
1016     @lines = &{$VCS_cmds{"execute_cmd"}}($cmd);
1017
1018     my $pattern = $VCS_cmds{"commit_pattern"};
1019
1020     $commits = grep(/$pattern/, @lines);        # of commits
1021
1022     @lines = grep(/^[ \t]*${signaturePattern}.*\@.*$/, @lines);
1023     if (!$email_git_penguin_chiefs) {
1024         @lines = grep(!/${penguin_chiefs}/i, @lines);
1025     }
1026
1027     return (0, @lines) if !@lines;
1028
1029     # cut -f2- -d":"
1030     s/.*:\s*(.+)\s*/$1/ for (@lines);
1031
1032 ## Reformat email addresses (with names) to avoid badly written signatures
1033
1034     foreach my $line (@lines) {
1035         my ($name, $address) = parse_email($line);
1036         $line = format_email($name, $address, 1);
1037     }
1038
1039     return ($commits, @lines);
1040 }
1041
1042 sub vcs_find_author {
1043     my ($cmd) = @_;
1044     my @lines = ();
1045
1046     @lines = &{$VCS_cmds{"execute_cmd"}}($cmd);
1047
1048     if (!$email_git_penguin_chiefs) {
1049         @lines = grep(!/${penguin_chiefs}/i, @lines);
1050     }
1051
1052     return @lines if !@lines;
1053
1054 ## Reformat email addresses (with names) to avoid badly written signatures
1055
1056     foreach my $line (@lines) {
1057         my ($name, $address) = parse_email($line);
1058         $line = format_email($name, $address, 1);
1059     }
1060
1061     return @lines;
1062 }
1063
1064 sub vcs_save_commits {
1065     my ($cmd) = @_;
1066     my @lines = ();
1067     my @commits = ();
1068
1069     @lines = &{$VCS_cmds{"execute_cmd"}}($cmd);
1070
1071     foreach my $line (@lines) {
1072         if ($line =~ m/$VCS_cmds{"blame_commit_pattern"}/) {
1073             push(@commits, $1);
1074         }
1075     }
1076
1077     return @commits;
1078 }
1079
1080 sub vcs_blame {
1081     my ($file) = @_;
1082     my $cmd;
1083     my @commits = ();
1084
1085     return @commits if (!(-f $file));
1086
1087     if (@range && $VCS_cmds{"blame_range_cmd"} eq "") {
1088         my @all_commits = ();
1089
1090         $cmd = $VCS_cmds{"blame_file_cmd"};
1091         $cmd =~ s/(\$\w+)/$1/eeg;               #interpolate $cmd
1092         @all_commits = vcs_save_commits($cmd);
1093
1094         foreach my $file_range_diff (@range) {
1095             next if (!($file_range_diff =~ m/(.+):(.+):(.+)/));
1096             my $diff_file = $1;
1097             my $diff_start = $2;
1098             my $diff_length = $3;
1099             next if ("$file" ne "$diff_file");
1100             for (my $i = $diff_start; $i < $diff_start + $diff_length; $i++) {
1101                 push(@commits, $all_commits[$i]);
1102             }
1103         }
1104     } elsif (@range) {
1105         foreach my $file_range_diff (@range) {
1106             next if (!($file_range_diff =~ m/(.+):(.+):(.+)/));
1107             my $diff_file = $1;
1108             my $diff_start = $2;
1109             my $diff_length = $3;
1110             next if ("$file" ne "$diff_file");
1111             $cmd = $VCS_cmds{"blame_range_cmd"};
1112             $cmd =~ s/(\$\w+)/$1/eeg;           #interpolate $cmd
1113             push(@commits, vcs_save_commits($cmd));
1114         }
1115     } else {
1116         $cmd = $VCS_cmds{"blame_file_cmd"};
1117         $cmd =~ s/(\$\w+)/$1/eeg;               #interpolate $cmd
1118         @commits = vcs_save_commits($cmd);
1119     }
1120
1121     foreach my $commit (@commits) {
1122         $commit =~ s/^\^//g;
1123     }
1124
1125     return @commits;
1126 }
1127
1128 my $printed_novcs = 0;
1129 sub vcs_exists {
1130     %VCS_cmds = %VCS_cmds_git;
1131     return 1 if eval $VCS_cmds{"available"};
1132     %VCS_cmds = %VCS_cmds_hg;
1133     return 1 if eval $VCS_cmds{"available"};
1134     %VCS_cmds = ();
1135     if (!$printed_novcs) {
1136         warn("$P: No supported VCS found.  Add --nogit to options?\n");
1137         warn("Using a git repository produces better results.\n");
1138         warn("Try Linus Torvalds' latest git repository using:\n");
1139         warn("git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git\n");
1140         $printed_novcs = 1;
1141     }
1142     return 0;
1143 }
1144
1145 sub vcs_assign {
1146     my ($role, $divisor, @lines) = @_;
1147
1148     my %hash;
1149     my $count = 0;
1150
1151     return if (@lines <= 0);
1152
1153     if ($divisor <= 0) {
1154         warn("Bad divisor in " . (caller(0))[3] . ": $divisor\n");
1155         $divisor = 1;
1156     }
1157
1158     if ($email_remove_duplicates) {
1159         @lines = mailmap(@lines);
1160     }
1161
1162     return if (@lines <= 0);
1163
1164     @lines = sort(@lines);
1165
1166     # uniq -c
1167     $hash{$_}++ for @lines;
1168
1169     # sort -rn
1170     foreach my $line (sort {$hash{$b} <=> $hash{$a}} keys %hash) {
1171         my $sign_offs = $hash{$line};
1172         my $percent = $sign_offs * 100 / $divisor;
1173
1174         $percent = 100 if ($percent > 100);
1175         $count++;
1176         last if ($sign_offs < $email_git_min_signatures ||
1177                  $count > $email_git_max_maintainers ||
1178                  $percent < $email_git_min_percent);
1179         push_email_address($line, '');
1180         if ($output_rolestats) {
1181             my $fmt_percent = sprintf("%.0f", $percent);
1182             add_role($line, "$role:$sign_offs/$divisor=$fmt_percent%");
1183         } else {
1184             add_role($line, $role);
1185         }
1186     }
1187 }
1188
1189 sub vcs_file_signoffs {
1190     my ($file) = @_;
1191
1192     my @signers = ();
1193     my $commits;
1194
1195     return if (!vcs_exists());
1196
1197     my $cmd = $VCS_cmds{"find_signers_cmd"};
1198     $cmd =~ s/(\$\w+)/$1/eeg;           # interpolate $cmd
1199
1200     ($commits, @signers) = vcs_find_signers($cmd);
1201     vcs_assign("commit_signer", $commits, @signers);
1202 }
1203
1204 sub vcs_file_blame {
1205     my ($file) = @_;
1206
1207     my @signers = ();
1208     my @all_commits = ();
1209     my @commits = ();
1210     my $total_commits;
1211     my $total_lines;
1212
1213     return if (!vcs_exists());
1214
1215     @all_commits = vcs_blame($file);
1216     @commits = uniq(@all_commits);
1217     $total_commits = @commits;
1218     $total_lines = @all_commits;
1219
1220     foreach my $commit (@commits) {
1221         my $commit_count;
1222         my @commit_signers = ();
1223
1224         my $cmd = $VCS_cmds{"find_commit_signers_cmd"};
1225         $cmd =~ s/(\$\w+)/$1/eeg;       #interpolate $cmd
1226
1227         ($commit_count, @commit_signers) = vcs_find_signers($cmd);
1228
1229         push(@signers, @commit_signers);
1230     }
1231
1232     if ($from_filename) {
1233         if ($output_rolestats) {
1234             my @blame_signers;
1235             foreach my $commit (@commits) {
1236                 my $i;
1237                 my $cmd = $VCS_cmds{"find_commit_author_cmd"};
1238                 $cmd =~ s/(\$\w+)/$1/eeg;       #interpolate $cmd
1239                 my @author = vcs_find_author($cmd);
1240                 next if !@author;
1241                 my $count = grep(/$commit/, @all_commits);
1242                 for ($i = 0; $i < $count ; $i++) {
1243                     push(@blame_signers, $author[0]);
1244                 }
1245             }
1246             if (@blame_signers) {
1247                 vcs_assign("authored lines", $total_lines, @blame_signers);
1248             }
1249         }
1250         vcs_assign("commits", $total_commits, @signers);
1251     } else {
1252         vcs_assign("modified commits", $total_commits, @signers);
1253     }
1254 }
1255
1256 sub uniq {
1257     my (@parms) = @_;
1258
1259     my %saw;
1260     @parms = grep(!$saw{$_}++, @parms);
1261     return @parms;
1262 }
1263
1264 sub sort_and_uniq {
1265     my (@parms) = @_;
1266
1267     my %saw;
1268     @parms = sort @parms;
1269     @parms = grep(!$saw{$_}++, @parms);
1270     return @parms;
1271 }
1272
1273 sub clean_file_emails {
1274     my (@file_emails) = @_;
1275     my @fmt_emails = ();
1276
1277     foreach my $email (@file_emails) {
1278         $email =~ s/[\(\<\{]{0,1}([A-Za-z0-9_\.\+-]+\@[A-Za-z0-9\.-]+)[\)\>\}]{0,1}/\<$1\>/g;
1279         my ($name, $address) = parse_email($email);
1280         if ($name eq '"[,\.]"') {
1281             $name = "";
1282         }
1283
1284         my @nw = split(/[^A-Za-zÀ-ÿ\'\,\.\+-]/, $name);
1285         if (@nw > 2) {
1286             my $first = $nw[@nw - 3];
1287             my $middle = $nw[@nw - 2];
1288             my $last = $nw[@nw - 1];
1289
1290             if (((length($first) == 1 && $first =~ m/[A-Za-z]/) ||
1291                  (length($first) == 2 && substr($first, -1) eq ".")) ||
1292                 (length($middle) == 1 ||
1293                  (length($middle) == 2 && substr($middle, -1) eq "."))) {
1294                 $name = "$first $middle $last";
1295             } else {
1296                 $name = "$middle $last";
1297             }
1298         }
1299
1300         if (substr($name, -1) =~ /[,\.]/) {
1301             $name = substr($name, 0, length($name) - 1);
1302         } elsif (substr($name, -2) =~ /[,\.]"/) {
1303             $name = substr($name, 0, length($name) - 2) . '"';
1304         }
1305
1306         if (substr($name, 0, 1) =~ /[,\.]/) {
1307             $name = substr($name, 1, length($name) - 1);
1308         } elsif (substr($name, 0, 2) =~ /"[,\.]/) {
1309             $name = '"' . substr($name, 2, length($name) - 2);
1310         }
1311
1312         my $fmt_email = format_email($name, $address, $email_usename);
1313         push(@fmt_emails, $fmt_email);
1314     }
1315     return @fmt_emails;
1316 }
1317
1318 sub merge_email {
1319     my @lines;
1320     my %saw;
1321
1322     for (@_) {
1323         my ($address, $role) = @$_;
1324         if (!$saw{$address}) {
1325             if ($output_roles) {
1326                 push(@lines, "$address ($role)");
1327             } else {
1328                 push(@lines, $address);
1329             }
1330             $saw{$address} = 1;
1331         }
1332     }
1333
1334     return @lines;
1335 }
1336
1337 sub output {
1338     my (@parms) = @_;
1339
1340     if ($output_multiline) {
1341         foreach my $line (@parms) {
1342             print("${line}\n");
1343         }
1344     } else {
1345         print(join($output_separator, @parms));
1346         print("\n");
1347     }
1348 }
1349
1350 my $rfc822re;
1351
1352 sub make_rfc822re {
1353 #   Basic lexical tokens are specials, domain_literal, quoted_string, atom, and
1354 #   comment.  We must allow for rfc822_lwsp (or comments) after each of these.
1355 #   This regexp will only work on addresses which have had comments stripped
1356 #   and replaced with rfc822_lwsp.
1357
1358     my $specials = '()<>@,;:\\\\".\\[\\]';
1359     my $controls = '\\000-\\037\\177';
1360
1361     my $dtext = "[^\\[\\]\\r\\\\]";
1362     my $domain_literal = "\\[(?:$dtext|\\\\.)*\\]$rfc822_lwsp*";
1363
1364     my $quoted_string = "\"(?:[^\\\"\\r\\\\]|\\\\.|$rfc822_lwsp)*\"$rfc822_lwsp*";
1365
1366 #   Use zero-width assertion to spot the limit of an atom.  A simple
1367 #   $rfc822_lwsp* causes the regexp engine to hang occasionally.
1368     my $atom = "[^$specials $controls]+(?:$rfc822_lwsp+|\\Z|(?=[\\[\"$specials]))";
1369     my $word = "(?:$atom|$quoted_string)";
1370     my $localpart = "$word(?:\\.$rfc822_lwsp*$word)*";
1371
1372     my $sub_domain = "(?:$atom|$domain_literal)";
1373     my $domain = "$sub_domain(?:\\.$rfc822_lwsp*$sub_domain)*";
1374
1375     my $addr_spec = "$localpart\@$rfc822_lwsp*$domain";
1376
1377     my $phrase = "$word*";
1378     my $route = "(?:\@$domain(?:,\@$rfc822_lwsp*$domain)*:$rfc822_lwsp*)";
1379     my $route_addr = "\\<$rfc822_lwsp*$route?$addr_spec\\>$rfc822_lwsp*";
1380     my $mailbox = "(?:$addr_spec|$phrase$route_addr)";
1381
1382     my $group = "$phrase:$rfc822_lwsp*(?:$mailbox(?:,\\s*$mailbox)*)?;\\s*";
1383     my $address = "(?:$mailbox|$group)";
1384
1385     return "$rfc822_lwsp*$address";
1386 }
1387
1388 sub rfc822_strip_comments {
1389     my $s = shift;
1390 #   Recursively remove comments, and replace with a single space.  The simpler
1391 #   regexps in the Email Addressing FAQ are imperfect - they will miss escaped
1392 #   chars in atoms, for example.
1393
1394     while ($s =~ s/^((?:[^"\\]|\\.)*
1395                     (?:"(?:[^"\\]|\\.)*"(?:[^"\\]|\\.)*)*)
1396                     \((?:[^()\\]|\\.)*\)/$1 /osx) {}
1397     return $s;
1398 }
1399
1400 #   valid: returns true if the parameter is an RFC822 valid address
1401 #
1402 sub rfc822_valid {
1403     my $s = rfc822_strip_comments(shift);
1404
1405     if (!$rfc822re) {
1406         $rfc822re = make_rfc822re();
1407     }
1408
1409     return $s =~ m/^$rfc822re$/so && $s =~ m/^$rfc822_char*$/;
1410 }
1411
1412 #   validlist: In scalar context, returns true if the parameter is an RFC822
1413 #              valid list of addresses.
1414 #
1415 #              In list context, returns an empty list on failure (an invalid
1416 #              address was found); otherwise a list whose first element is the
1417 #              number of addresses found and whose remaining elements are the
1418 #              addresses.  This is needed to disambiguate failure (invalid)
1419 #              from success with no addresses found, because an empty string is
1420 #              a valid list.
1421
1422 sub rfc822_validlist {
1423     my $s = rfc822_strip_comments(shift);
1424
1425     if (!$rfc822re) {
1426         $rfc822re = make_rfc822re();
1427     }
1428     # * null list items are valid according to the RFC
1429     # * the '1' business is to aid in distinguishing failure from no results
1430
1431     my @r;
1432     if ($s =~ m/^(?:$rfc822re)?(?:,(?:$rfc822re)?)*$/so &&
1433         $s =~ m/^$rfc822_char*$/) {
1434         while ($s =~ m/(?:^|,$rfc822_lwsp*)($rfc822re)/gos) {
1435             push(@r, $1);
1436         }
1437         return wantarray ? (scalar(@r), @r) : 1;
1438     }
1439     return wantarray ? () : 0;
1440 }