summaryrefslogtreecommitdiffstats
path: root/src/build/tools/verify-commit
blob: 780726b3f0b1589c2d8973de504fddcc0204d589 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
#!/usr/bin/perl
# IBM_PROLOG_BEGIN_TAG
# This is an automatically generated prolog.
#
# $Source: src/build/tools/verify-commit $
#
# OpenPOWER HostBoot Project
#
# Contributors Listed Below - COPYRIGHT 2013,2018
# [+] International Business Machines Corp.
#
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing
# permissions and limitations under the License.
#
# IBM_PROLOG_END_TAG

use strict;
use Getopt::Long qw(:config pass_through);

my $issueFound = 0;
my $errorFound = 0;
my $warningCount = 0;
my $showAll = 0;

use constant MAX_WARNINGS => 5;
use constant MAX_CODE_LINE_LENGTH => 80;

my $projectName = $ENV{'PROJECT_NAME'};
# Relative path of import tree from project root
my $importPrefix = $ENV{'IMPORT_REL_PATH'}."/";

my $rtcNumber = rtc_workitem_num();
my $cqNumber = cq_workitem_num();

GetOptions("show-all" => \$showAll);

verifyPatchSet();       # Verify the patch contents.
verifyCommitMsg();      # Verify the commit message.
verifyTodoFixme();      # Make sure there are no TODO/FIXME
                        # associated with current RTC/CQ

# Finish out the divider.
if ($issueFound)
{
    print "------------------------------------------------------------\n";
    my $hiddenWarnings = $warningCount - MAX_WARNINGS;
    if ($hiddenWarnings > 0 && !$showAll)
    {
        print "    $hiddenWarnings Warning(s) Hidden\n";
        print "    Run 'verify-commit --show-all'\n";
        print "------------------------------------------------------------\n";
    }
}

# Return a bad RC if we found an error.  Let warnings pass.
exit ($errorFound ? -1 : 0);


########################### Subroutines ################################

# @sub verifyPatchSet
#
# Extract the contents (lines changed) from the patch set and verify.
#
sub verifyPatchSet
{
    # git-diff options:
    #   * Diff against the previous commit (HEAD~1)
    #   * Filter only added and modified files (AM).
    #   * Show only the lines changed, with no context (U0).
    # Grep only the lines marked with "+" (instead of "-") to find just the
    # actions done by this patchset and not the content removed.
    open PATCH_CONTENTS, "git diff HEAD~1 --diff-filter=AM -U0 | ".
                         "grep -e \"^+\" -e \"^@@.*+[0-9]\\+\" |";

    my %fileContents = ();

    my $lastFile = "";
    my $fileLines = ();
    my $lineCount = 0;
    while (my $line = <PATCH_CONTENTS>)
    {
        chomp $line;

        # Line starting with "+++ b/path/to/file" indicate a new file.
        if ($line =~ m/^\+\+\+ b\/(.*)/)
        {
            # Save previous file into the map.
            if ($lastFile ne "")
            {
                $fileContents{$lastFile} = $fileLines;
                $fileLines = ();
                $lineCount = 0;
            }
            $lastFile = $1;
        }
        # Lines starting with "@@" indicates a seek in the file, so update
        # line numbers.
        elsif ($line =~ m/^@@.*\+([0-9]+)/)
        {
            $lineCount = $1 - 1;
        }
        else
        {
            $line =~ s/^\+//; # filter off the leading + symbol.
            $lineCount++;
            push @{$fileLines}, [$line, $lineCount];
        }
    }
    if ($lastFile ne "") # Save last file into the map.
    {
        $fileContents{$lastFile} = $fileLines;
        $fileLines = ();
    }

    # Verify each line of each file.
    foreach my $file (sort keys %fileContents)
    {
        foreach my $line (@{$fileContents{$file}})
        {
            verifyFileLine($file, @{$line}[0], @{$line}[1]);
        }
    }
}

# @sub verifyFileLine
#
# Checks a particular line of the file for the following issues:
#     * Warning: Lines longer than MAX_CODE_LINE_LENGTH characters, except in trace statement.
#     * Warning: Trailing whitespace.
#     * Warning: Tab characters outside of makefiles.
#     * Warning: TODO or FIXME type tag without a corresponding RTC number.
#     * Warning: NOMERGE tag found.
#
sub verifyFileLine
{
    my ($file,$line,$count) = @_;

    # Check if file was mirrored
    my $mirror = 0;
    if ($file =~ m/^$importPrefix/)
    {
        $mirror = 1;
    }

    # Check line length.
    if (length($line) > MAX_CODE_LINE_LENGTH)
    {
        if (($line =~ m/TRAC[DSFU]/) ||
            ($line =~m/TS_FAIL/) ||
            ($line =~m/printk/) ||
            ($line =~m/displayf/) ||
            ($line =~ m/FAPI_(INF|IMP|ERR|DBG|SCAN)/) ||
            ($line =~ m/print/))
        {
        }
        else
        {
            warning($file,$line,$count,
                    (sprintf "Length is more than %d characters (%d).",
                     MAX_CODE_LINE_LENGTH, length($line))
                   );
        }
    }

    # Check trailing whitespace.
    if ($line =~ m/\s$/)
    {
        warning($file,$line,$count,
                "Trailing whitespace found.");
    }

    # Check tabs.
    if ($line =~ m/\t/)
    {
        # Makefiles are ok (require tabs).
        if (not (($file =~ m/makefile/) || ($file =~ m/Makefile/) ||
                ($file =~ m/\.mk/)))
        {
            warning($file,$line,$count,
                    "Tab character found.");
        }
    }

    # Check "TODO" or "FIXME" type comments.
    if (($line =~ m/TODO/i) || ($line =~ m/FIXME/i))
    {
        if ( (not ($line =~ m/RTC[\s:]\s*[0-9]+/)) &&
             (not ($line =~ m/CQ[\s:]\s*[A-Z][A-Z][0-9]+/)))
        {
            warning($file,$line,$count,
                    "TODO/FIXME tag without corresponding RTC or CQ number.");
        }
    }

    # Check "NOMERGE" type comment.
    if ($line =~ m/NOMERGE/i)
    {
        warning($file,$line,$count,
                "NOMERGE tag found.");
    }

    # Check for "Confidential", unless it's a mirrored commit
    if ($line =~ m/Confidential/i && $projectName =~ m/HostBoot/i && !$mirror)
    {
        unless (($file =~ m/verify-commit/) ||
                ($file =~ m/addCopyright/))
        {
            error($file,$line,$count,
                  "File contains 'Confidential'.");
        }
    }
}

# @sub verifyCommitMsg
#
# Looks at the commit message to verify the following items:
#    * Topic is exactly 1 line long.
#    * Lines are less than 80 characters.
#    * No trailing whitespace.
#    * Tags, such as 'RTC:', are only found in the footer.
#    * Untagged lines are not found in the footer.
#    * RTC tag is formatted correctly.
#    * Warning for lacking RTC tag.
#
sub verifyCommitMsg
{
    open COMMIT_CONTENTS, "git log -n1 --pretty=format:%B |";
    my $lineCount = 0;
    my $rtcTag = "";
    my $cqTag = "";
    my $githubTag = "";
    my $changeId = "";
    my $taggedLine = "";
    my $untaggedLine = "";

    while (my $line = <COMMIT_CONTENTS>)
    {
        $lineCount++;
        chomp $line;

        # Check line length over 80 characters.
        if (length($line) > 80)
        {
            error("Commit Message",$line,$lineCount,
                    (sprintf "Length is more than 80 characters (%d).",
                     length($line))
                 );
        }

        # Check trailing whitespace.
        if ($line =~ m/[^\s]+\s$/)
        {
            error("Commit Message",$line,$lineCount,
                  "Trailing whitespace found.");
        }

        # Blank line indicates a new "section".
        if ($line =~ m/^$/)
        {
            # Check for tags outside of the footer.
            # (new section implies previous section was not a footer)
            if ("" ne $taggedLine)
            {
                error("Commit Message",$taggedLine,$lineCount,
                      "Tagged line found outside commit-msg footer.");
            }

            $rtcTag = "";
            $cqTag = "";
            $githubTag = "";
            $untaggedLine = "";
            $taggedLine = "";
        }
        else
        {
            # Check for multi-line topic.
            if ($lineCount == 2)
            {
                error("Commit Message",$line,$lineCount,
                      "Topic must be only one line long.");
            }
        }

        # Verify format of RTC message. "RTC: 123456"
        if ($line =~ m/^\s*RTC:\s*[0-9]+(.*)/)
        {
            $rtcTag = $line;
            if ("" ne $1)
            {
                error("Commit Message",$line,$lineCount,
                        (sprintf "RTC tag format incorrect (%s).", $1));
            }
        }

        # Verify format of CQ message. "CQ: 123456"
        if ($line =~ m/^\s*CQ:\s*[A-Z][A-Z][0-9]+(.*)/)
        {
            $cqTag = $line;
            if ("" ne $1)
            {
                error("Commit Message",$line,$lineCount,
                        (sprintf "CQ tag format incorrect (%s).", $1));
            }
        }

        # Verify format of Github message. "Resolves somerepo/#12345"
        #  See https://help.github.com/articles/closing-issues-via-commit-messages
        if ($line =~ m/^\s*Resolves \s*.*#[0-9]+(.*)/)
        {
            $githubTag = $line;
            if ("" ne $1)
            {
                error("Commit Message",$line,$lineCount,
                        (sprintf "Github tag format incorrect (%s).", $1));
            }
        }

        if ($line =~ m/^\s*Change-Id:\s*[I][\w]+(.*)/)
        {
            if ("" ne $changeId)
            {
                error("Commit Message",$line,$lineCount,
                      "Mulitple Change-Id's found.");
            }

            $changeId = $line;
            if ("" ne $1)
            {
                error("Commit Message",$line,$lineCount,
                        (sprintf "Change-Id format incorrect (%s).", $1));
            }
        }

        # Identify if this is a tagged line or a non-tagged line and store
        # away.
        if ( (($line =~ m/^\s*[A-Za-z0-9\-_]+:[^:]/)
              && !($line =~ m/http/)) ||
              (($line =~ m/http/) && ($line =~ m/Reviewed-on:/)) ||
              ($line =~ "Resolves") )
        {
            # We allow lines that look like tags in the topic like...
            # "FOO: Adding support for BAR."
            # Unless the Change-Id is in the topic
            if ($lineCount > 1 || ($line =~ m/Change-Id/))
            {
                $taggedLine = $line;
            }
        }
        else
        {
            $untaggedLine = $line;
        }
    }

    # Warn for missing RTC tag.
    if (("" eq $rtcTag) && ("" eq $cqTag) && ("" eq $githubTag))
    {
        warning("Commit Message","<end-of-file>",$lineCount,
                "Neither RTC nor CQ nor Github tag found.");
    }

    # Error for missing Change-Id.
    if ("" eq $changeId)
    {
        error("Commit Message","<end-of-file>",$lineCount,
                "Change-Id not found.");
    }

    # Error for a mix of tag / untagged in the last section (ie. untagged
    # lines in the footer).
    if (("" ne $untaggedLine) && ("" ne $taggedLine))
    {
        error("Commit Message",$untaggedLine,$lineCount,
                "Untagged line found in footer.");
    }
}

# sub verifyTodoFixme
#
# Verifies that there are no Todo or Fixme
# tags in the code with the current commit's
# RTC or CQ number.
#
sub verifyTodoFixme
{
    my $file;
    my $commentText;
    my $lineNumber;
    # Get the list of TODO/FIXME lines in src/
    open TODO_LIST, "egrep -rn '(TODO.*(CQ|RTC).*)|(FIXME.*(CQ|RTC).*)' src/* |"
        or die "Cannot get the list of TODO/FIXME lines.\n";

    while(my $line = <TODO_LIST>)
    {
        chomp $line;
        if(check_rtc_todo_fixme($line))
        {
            ($file, $commentText, $lineNumber) = parse_todo_fixme_line($line);
            strong_warning($file, $commentText, $lineNumber,
             "TODO/FIXME tag with the same RTC number as in the current commit message.");
        }
        elsif(check_cq_todo_fixme($line))
        {
            ($file, $commentText, $lineNumber) = parse_todo_fixme_line($line);
            strong_warning($file, $commentText, $lineNumber,
              "TODO/FIXME tag with the same CQ number as in the current commit message.");
        }
    }
}

sub parse_todo_fixme_line
{
    my $line = shift;
    my ($file, $lineNumber, $commentText) = split(/:/, $line, 3);
    return ($file, $commentText, $lineNumber);
}

sub check_rtc_todo_fixme
{
    my $line = shift;
    if($line =~ m/RTC\s*:*\s*([0-9]+)/ &&
           $1 eq $rtcNumber && $rtcNumber ne "")
    {
        return 1;
    }

    return 0;
}

sub check_cq_todo_fixme
{
    my $line = shift;
    if($line =~ m/CQ\s*:*\s*([A-Z][A-Z][0-9]+)/ &&
          $1 eq $cqNumber && $cqNumber ne "")
    {
        return 1;
    }

    return 0;
}

sub warning
{
    my ($file, $line, $count, $statement) = @_;

    if ($warningCount < MAX_WARNINGS || $showAll)
    {
        print "------------------------------------------------------------\n";
        print "WARNING: $statement\n";
        print "  $file:$count\n";
        print "    $line\n";
    }

    $issueFound = 1;
    $warningCount++;
}

sub strong_warning
{
    my ($file, $line, $count, $statement) = @_;

    # Always show strong warnings
    print "------------------------------------------------------------\n";
    print "***WARNING: $statement\n";
    print "  $file:$count\n";
    print "    $line\n";

    $issueFound = 1;
    $warningCount++;
}

sub error
{
    my ($file, $line, $count, $statement) = @_;
    print "------------------------------------------------------------\n";
    print "ERROR: $statement\n";
    print "  $file:$count\n";
    print "    $line\n";

    $issueFound = 1;
    $errorFound = 1;
}

# sub rtc_workitem_num
#
#  Determines the RTC WorkItem associated with a git commit.
#
#  @param[in] commit - The git commit, or no parameter for last commit
#
#  @return string - RTC WorkItem number (or "").
#
sub rtc_workitem_num
{
    my $commit = shift;
    my $message;

    if(defined($commit))
    {
        $message = git_commit_msg($commit);
    }
    else
    {
        $message = git_commit_msg("");
    }

    if ($message =~ m/RTC:\s*([0-9]+)/)
    {
        return $1;
    }
    else
    {
        return "";
    }
}


# sub cq_workitem_num
#
# Determines the CQ WorkItem associated with a git commit.
#
# @param[in] commit - The git commit, or no parameter for last commit
#
# @return string - CQ WorkItem number (or "").
#
sub cq_workitem_num
{
    my $commit = shift;
    my $message;

    if(defined($commit))
    {
        $message = git_commit_msg($commit);
    }
    else
    {
        $message = git_commit_msg("");
    }

    if ($message =~ m/CQ:\s*([A-Z][A-Z][0-9]+)/)
    {
        return $1;
    }
    else
    {
        return "";
    }
}

# sub git_commit_msg
#
# Get the entire commit message associated with a commit.
#
# @param[in] commit - The commit to examine.
# @return string - The commit message.
#
sub git_commit_msg
{
    my $commit = shift;
    open COMMAND, "git log -n1 --pretty=%B $commit |";
    my $message = "";
    while (my $line = <COMMAND>)
    {
        $message = $message.$line;
    }
    close COMMAND;

    return $message;
}

OpenPOWER on IntegriCloud