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