-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathpresubmit_canned_checks.py
2101 lines (1789 loc) · 77.3 KB
/
presubmit_canned_checks.py
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Generic presubmit checks that can be reused by other presubmit checks."""
from __future__ import print_function
import io as _io
import os as _os
from warnings import warn
_HERE = _os.path.dirname(_os.path.abspath(__file__))
# These filters will be disabled if callers do not explicitly supply a
# (possibly-empty) list. Ideally over time this list could be driven to zero.
# TODO(pkasting): If some of these look like "should never enable", move them
# to OFF_UNLESS_MANUALLY_ENABLED_LINT_FILTERS.
#
# Justifications for each filter:
#
# - build/include : Too many; fix in the future
# TODO(pkasting): Try enabling subcategories
# - build/include_order : Not happening; #ifdefed includes
# - build/namespaces : TODO(pkasting): Try re-enabling
# - readability/casting : Mistakes a whole bunch of function pointers
# - runtime/int : Can be fixed long term; volume of errors too high
# - whitespace/braces : We have a lot of explicit scoping in chrome code
OFF_BY_DEFAULT_LINT_FILTERS = [
'-build/include',
'-build/include_order',
'-build/namespaces',
'-readability/casting',
'-runtime/int',
'-whitespace/braces',
]
# These filters will be disabled unless callers explicitly enable them, because
# they are undesirable in some way.
#
# Justifications for each filter:
# - build/c++11 : Include file and feature blocklists are
# google3-specific
# - build/header_guard : Checked by CheckForIncludeGuards
# - readability/todo : Chromium puts bug links, not usernames, in TODOs
# - runtime/references : No longer banned by Google style guide
# - whitespace/... : Most whitespace issues handled by clang-format
OFF_UNLESS_MANUALLY_ENABLED_LINT_FILTERS = [
'-build/c++11',
'-build/header_guard',
'-readability/todo',
'-runtime/references',
'-whitespace/braces',
'-whitespace/comma',
'-whitespace/end_of_line',
'-whitespace/forcolon',
'-whitespace/indent',
'-whitespace/line_length',
'-whitespace/newline',
'-whitespace/operators',
'-whitespace/parens',
'-whitespace/semicolon',
'-whitespace/tab',
]
_CORP_LINK_KEYWORD = '.corp.google'
### Description checks
def CheckChangeHasBugField(input_api, output_api):
"""Requires that the changelist have a Bug: field."""
bugs = input_api.change.BugsFromDescription()
if bugs:
if any(b.startswith('b/') for b in bugs):
return [
output_api.PresubmitNotifyResult(
'Buganizer bugs should be prefixed with b:, not b/.')
]
return []
return [output_api.PresubmitNotifyResult(
'If this change has an associated bug, add Bug: [bug number].')]
def CheckChangeHasNoUnwantedTags(input_api, output_api):
UNWANTED_TAGS = {
'FIXED': {
'why': 'is not supported',
'instead': 'Use "Fixed:" instead.'
},
# TODO: BUG, ISSUE
}
errors = []
for tag, desc in UNWANTED_TAGS.items():
if tag in input_api.change.tags:
subs = tag, desc['why'], desc.get('instead', '')
errors.append(('%s= %s. %s' % subs).rstrip())
return [output_api.PresubmitError('\n'.join(errors))] if errors else []
def CheckDoNotSubmitInDescription(input_api, output_api):
"""Checks that the user didn't add 'DO NOT ''SUBMIT' to the CL description.
"""
# Keyword is concatenated to avoid presubmit check rejecting the CL.
keyword = 'DO NOT ' + 'SUBMIT'
if keyword in input_api.change.DescriptionText():
return [output_api.PresubmitError(
keyword + ' is present in the changelist description.')]
return []
def CheckCorpLinksInDescription(input_api, output_api):
"""Checks that the description doesn't contain corp links."""
if _CORP_LINK_KEYWORD in input_api.change.DescriptionText():
return [
output_api.PresubmitPromptWarning(
'Corp link is present in the changelist description.')
]
return []
def CheckChangeHasDescription(input_api, output_api):
"""Checks the CL description is not empty."""
text = input_api.change.DescriptionText()
if text.strip() == '':
if input_api.is_committing and not input_api.no_diffs:
return [output_api.PresubmitError('Add a description to the CL.')]
return [output_api.PresubmitNotifyResult('Add a description to the CL.')]
return []
def CheckChangeWasUploaded(input_api, output_api):
"""Checks that the issue was uploaded before committing."""
if input_api.is_committing and not input_api.change.issue:
message = 'Issue wasn\'t uploaded. Please upload first.'
if input_api.no_diffs:
# Make this just a message with presubmit --all and --files
return [output_api.PresubmitNotifyResult(message)]
return [output_api.PresubmitError(message)]
return []
def CheckDescriptionUsesColonInsteadOfEquals(input_api, output_api):
"""Checks that the CL description uses a colon after 'Bug' and 'Fixed' tags
instead of equals.
crbug.com only interprets the lines "Bug: xyz" and "Fixed: xyz" but not
"Bug=xyz" or "Fixed=xyz".
"""
text = input_api.change.DescriptionText()
if input_api.re.search(r'^(Bug|Fixed)=',
text,
flags=input_api.re.IGNORECASE
| input_api.re.MULTILINE):
return [output_api.PresubmitError('Use Bug:/Fixed: instead of Bug=/Fixed=')]
return []
### Content checks
def CheckAuthorizedAuthor(input_api, output_api, bot_allowlist=None):
"""For non-googler/chromites committers, verify the author's email address is
in AUTHORS.
"""
if input_api.is_committing or input_api.no_diffs:
error_type = output_api.PresubmitError
else:
error_type = output_api.PresubmitPromptWarning
author = input_api.change.author_email
if not author:
input_api.logging.info('No author, skipping AUTHOR check')
return []
# This is used for CLs created by trusted robot accounts.
if bot_allowlist and author in bot_allowlist:
return []
authors_path = input_api.os_path.join(
input_api.PresubmitLocalPath(), 'AUTHORS')
author_re = input_api.re.compile(r'[^#]+\s+\<(.+?)\>\s*$')
valid_authors = []
with _io.open(authors_path, encoding='utf-8') as fp:
for line in fp:
m = author_re.match(line)
if m:
valid_authors.append(m.group(1).lower())
if not any(input_api.fnmatch.fnmatch(author.lower(), valid)
for valid in valid_authors):
input_api.logging.info('Valid authors are %s', ', '.join(valid_authors))
return [
error_type((
# pylint: disable=line-too-long
'%s is not in AUTHORS file. If you are a new contributor, please visit\n'
'https://chromium.googlesource.com/chromium/src/+/refs/heads/main/docs/contributing.md#Legal-stuff\n'
# pylint: enable=line-too-long
'and read the "Legal stuff" section\n'
'If you are a chromite, verify that the contributor signed the CLA.') %
author)
]
return []
def CheckDoNotSubmitInFiles(input_api, output_api):
"""Checks that the user didn't add 'DO NOT ''SUBMIT' to any files."""
# We want to check every text file, not just source files.
file_filter = lambda x : x
# Keyword is concatenated to avoid presubmit check rejecting the CL.
keyword = 'DO NOT ' + 'SUBMIT'
def DoNotSubmitRule(extension, line):
try:
return keyword not in line
# Fallback to True for non-text content
except UnicodeDecodeError:
return True
errors = _FindNewViolationsOfRule(DoNotSubmitRule, input_api, file_filter)
text = '\n'.join('Found %s in %s' % (keyword, loc) for loc in errors)
if text:
return [output_api.PresubmitError(text)]
return []
def CheckCorpLinksInFiles(input_api, output_api, source_file_filter=None):
"""Checks that files do not contain a corp link."""
errors = _FindNewViolationsOfRule(
lambda _, line: _CORP_LINK_KEYWORD not in line, input_api,
source_file_filter)
text = '\n'.join('Found corp link in %s' % loc for loc in errors)
if text:
return [output_api.PresubmitPromptWarning(text)]
return []
def GetCppLintFilters(lint_filters=None):
filters = OFF_UNLESS_MANUALLY_ENABLED_LINT_FILTERS[:]
if lint_filters is None:
lint_filters = OFF_BY_DEFAULT_LINT_FILTERS
filters.extend(lint_filters)
return filters
def CheckChangeLintsClean(input_api, output_api, source_file_filter=None,
lint_filters=None, verbose_level=None):
"""Checks that all '.cc' and '.h' files pass cpplint.py."""
_RE_IS_TEST = input_api.re.compile(r'.*tests?.(cc|h)$')
result = []
cpplint = input_api.cpplint
# Access to a protected member _XX of a client class
# pylint: disable=protected-access
cpplint._cpplint_state.ResetErrorCounts()
cpplint._SetFilters(','.join(GetCppLintFilters(lint_filters)))
# Use VS error format on Windows to make it easier to step through the
# results.
if input_api.platform == 'win32':
cpplint._SetOutputFormat('vs7')
if source_file_filter == None:
# The only valid extensions for cpplint are .cc, .h, .cpp, .cu, and .ch.
# Only process those extensions which are used in Chromium.
INCLUDE_CPP_FILES_ONLY = (r'.*\.(cc|h|cpp)$', )
source_file_filter = lambda x: input_api.FilterSourceFile(
x,
files_to_check=INCLUDE_CPP_FILES_ONLY,
files_to_skip=input_api.DEFAULT_FILES_TO_SKIP)
# We currently are more strict with normal code than unit tests; 4 and 5 are
# the verbosity level that would normally be passed to cpplint.py through
# --verbose=#. Hopefully, in the future, we can be more verbose.
files = [f.AbsoluteLocalPath() for f in
input_api.AffectedSourceFiles(source_file_filter)]
for file_name in files:
if _RE_IS_TEST.match(file_name):
level = 5
else:
level = 4
verbose_level = verbose_level or level
cpplint.ProcessFile(file_name, verbose_level)
if cpplint._cpplint_state.error_count > 0:
# cpplint errors currently cannot be counted as errors during upload
# presubmits because some directories only run cpplint during upload and
# therefore are far from cpplint clean.
if input_api.is_committing:
res_type = output_api.PresubmitError
else:
res_type = output_api.PresubmitPromptWarning
result = [
res_type('Changelist failed cpplint.py check. '
'Search the output for "(cpplint)"')
]
return result
def CheckChangeHasNoCR(input_api, output_api, source_file_filter=None):
"""Checks no '\r' (CR) character is in any source files."""
cr_files = []
for f in input_api.AffectedSourceFiles(source_file_filter):
if '\r' in input_api.ReadFile(f, 'rb'):
cr_files.append(f.LocalPath())
if cr_files:
return [output_api.PresubmitPromptWarning(
'Found a CR character in these files:', items=cr_files)]
return []
def CheckChangeHasOnlyOneEol(input_api, output_api, source_file_filter=None):
"""Checks the files ends with one and only one \n (LF)."""
eof_files = []
for f in input_api.AffectedSourceFiles(source_file_filter):
contents = input_api.ReadFile(f, 'rb')
# Check that the file ends in one and only one newline character.
if len(contents) > 1 and (contents[-1:] != '\n' or contents[-2:-1] == '\n'):
eof_files.append(f.LocalPath())
if eof_files:
return [output_api.PresubmitPromptWarning(
'These files should end in one (and only one) newline character:',
items=eof_files)]
return []
def CheckChangeHasNoCrAndHasOnlyOneEol(input_api, output_api,
source_file_filter=None):
"""Runs both CheckChangeHasNoCR and CheckChangeHasOnlyOneEOL in one pass.
It is faster because it is reading the file only once.
"""
cr_files = []
eof_files = []
for f in input_api.AffectedSourceFiles(source_file_filter):
contents = input_api.ReadFile(f, 'rb')
if '\r' in contents:
cr_files.append(f.LocalPath())
# Check that the file ends in one and only one newline character.
if len(contents) > 1 and (contents[-1:] != '\n' or contents[-2:-1] == '\n'):
eof_files.append(f.LocalPath())
outputs = []
if cr_files:
outputs.append(output_api.PresubmitPromptWarning(
'Found a CR character in these files:', items=cr_files))
if eof_files:
outputs.append(output_api.PresubmitPromptWarning(
'These files should end in one (and only one) newline character:',
items=eof_files))
return outputs
def CheckGenderNeutral(input_api, output_api, source_file_filter=None):
"""Checks that there are no gendered pronouns in any of the text files to be
submitted.
"""
if input_api.no_diffs:
return []
gendered_re = input_api.re.compile(
r'(^|\s|\(|\[)([Hh]e|[Hh]is|[Hh]ers?|[Hh]im|[Ss]he|[Gg]uys?)\\b')
errors = []
for f in input_api.AffectedFiles(include_deletes=False,
file_filter=source_file_filter):
for line_num, line in f.ChangedContents():
if gendered_re.search(line):
errors.append('%s (%d): %s' % (f.LocalPath(), line_num, line))
if errors:
return [output_api.PresubmitPromptWarning('Found a gendered pronoun in:',
long_text='\n'.join(errors))]
return []
def _ReportErrorFileAndLine(filename, line_num, dummy_line):
"""Default error formatter for _FindNewViolationsOfRule."""
return '%s:%s' % (filename, line_num)
def _GenerateAffectedFileExtList(input_api, source_file_filter):
"""Generate a list of (file, extension) tuples from affected files.
The result can be fed to _FindNewViolationsOfRule() directly, or
could be filtered before doing that.
Args:
input_api: object to enumerate the affected files.
source_file_filter: a filter to be passed to the input api.
Yields:
A list of (file, extension) tuples, where |file| is an affected
file, and |extension| its file path extension.
"""
for f in input_api.AffectedFiles(
include_deletes=False, file_filter=source_file_filter):
extension = str(f.LocalPath()).rsplit('.', 1)[-1]
yield (f, extension)
def _FindNewViolationsOfRuleForList(callable_rule,
file_ext_list,
error_formatter=_ReportErrorFileAndLine):
"""Find all newly introduced violations of a per-line rule (a callable).
Prefer calling _FindNewViolationsOfRule() instead of this function, unless
the list of affected files need to be filtered in a special way.
Arguments:
callable_rule: a callable taking a file extension and line of input and
returning True if the rule is satisfied and False if there was a problem.
file_ext_list: a list of input (file, extension) tuples, as returned by
_GenerateAffectedFileExtList().
error_formatter: a callable taking (filename, line_number, line) and
returning a formatted error string.
Returns:
A list of the newly-introduced violations reported by the rule.
"""
errors = []
for f, extension in file_ext_list:
# For speed, we do two passes, checking first the full file. Shelling out
# to the SCM to determine the changed region can be quite expensive on
# Win32. Assuming that most files will be kept problem-free, we can
# skip the SCM operations most of the time.
if all(callable_rule(extension, line) for line in f.NewContents()):
continue # No violation found in full text: can skip considering diff.
for line_num, line in f.ChangedContents():
if not callable_rule(extension, line):
errors.append(error_formatter(f.LocalPath(), line_num, line))
return errors
def _FindNewViolationsOfRule(callable_rule,
input_api,
source_file_filter=None,
error_formatter=_ReportErrorFileAndLine):
"""Find all newly introduced violations of a per-line rule (a callable).
Arguments:
callable_rule: a callable taking a file extension and line of input and
returning True if the rule is satisfied and False if there was a problem.
input_api: object to enumerate the affected files.
source_file_filter: a filter to be passed to the input api.
error_formatter: a callable taking (filename, line_number, line) and
returning a formatted error string.
Returns:
A list of the newly-introduced violations reported by the rule.
"""
if input_api.no_diffs:
return []
return _FindNewViolationsOfRuleForList(
callable_rule, _GenerateAffectedFileExtList(
input_api, source_file_filter), error_formatter)
def CheckChangeHasNoTabs(input_api, output_api, source_file_filter=None):
"""Checks that there are no tab characters in any of the text files to be
submitted.
"""
# In addition to the filter, make sure that makefiles are skipped.
if not source_file_filter:
# It's the default filter.
source_file_filter = input_api.FilterSourceFile
def filter_more(affected_file):
basename = input_api.os_path.basename(affected_file.LocalPath())
return (not (basename in ('Makefile', 'makefile') or
basename.endswith('.mk')) and
source_file_filter(affected_file))
tabs = _FindNewViolationsOfRule(lambda _, line : '\t' not in line,
input_api, filter_more)
if tabs:
return [output_api.PresubmitPromptWarning('Found a tab character in:',
long_text='\n'.join(tabs))]
return []
def CheckChangeTodoHasOwner(input_api, output_api, source_file_filter=None):
"""Checks that the user didn't add TODO(name) without an owner."""
unowned_todo = input_api.re.compile('TO''DO[^(]')
errors = _FindNewViolationsOfRule(lambda _, x : not unowned_todo.search(x),
input_api, source_file_filter)
errors = ['Found TO''DO with no owner in ' + x for x in errors]
if errors:
return [output_api.PresubmitPromptWarning('\n'.join(errors))]
return []
def CheckChangeHasNoStrayWhitespace(input_api, output_api,
source_file_filter=None):
"""Checks that there is no stray whitespace at source lines end."""
errors = _FindNewViolationsOfRule(lambda _, line : line.rstrip() == line,
input_api, source_file_filter)
if errors:
return [output_api.PresubmitPromptWarning(
'Found line ending with white spaces in:',
long_text='\n'.join(errors))]
return []
def CheckLongLines(input_api, output_api, maxlen, source_file_filter=None):
"""Checks that there aren't any lines longer than maxlen characters in any of
the text files to be submitted.
"""
if input_api.no_diffs:
return []
maxlens = {
'java': 100,
# This is specifically for Android's handwritten makefiles (Android.mk).
'mk': 200,
'': maxlen,
}
# Language specific exceptions to max line length.
# '.h' is considered an obj-c file extension, since OBJC_EXCEPTIONS are a
# superset of CPP_EXCEPTIONS.
CPP_FILE_EXTS = ('c', 'cc')
CPP_EXCEPTIONS = ('#define', '#endif', '#if', '#include', '#pragma')
HTML_FILE_EXTS = ('html',)
HTML_EXCEPTIONS = ('<g ', '<link ', '<path ',)
JAVA_FILE_EXTS = ('java',)
JAVA_EXCEPTIONS = ('import ', 'package ')
JS_FILE_EXTS = ('js',)
JS_EXCEPTIONS = ("GEN('#include", 'import ')
TS_FILE_EXTS = ('ts',)
TS_EXCEPTIONS = ('import ')
OBJC_FILE_EXTS = ('h', 'm', 'mm')
OBJC_EXCEPTIONS = ('#define', '#endif', '#if', '#import', '#include',
'#pragma')
PY_FILE_EXTS = ('py',)
PY_EXCEPTIONS = ('import', 'from')
LANGUAGE_EXCEPTIONS = [
(CPP_FILE_EXTS, CPP_EXCEPTIONS),
(HTML_FILE_EXTS, HTML_EXCEPTIONS),
(JAVA_FILE_EXTS, JAVA_EXCEPTIONS),
(JS_FILE_EXTS, JS_EXCEPTIONS),
(TS_FILE_EXTS, TS_EXCEPTIONS),
(OBJC_FILE_EXTS, OBJC_EXCEPTIONS),
(PY_FILE_EXTS, PY_EXCEPTIONS),
]
def no_long_lines(file_extension, line):
"""Returns True if the line length is okay."""
# Check for language specific exceptions.
if any(file_extension in exts and line.lstrip().startswith(exceptions)
for exts, exceptions in LANGUAGE_EXCEPTIONS):
return True
file_maxlen = maxlens.get(file_extension, maxlens[''])
# Stupidly long symbols that needs to be worked around if takes 66% of line.
long_symbol = file_maxlen * 2 / 3
# Hard line length limit at 50% more.
extra_maxlen = file_maxlen * 3 / 2
line_len = len(line)
if line_len <= file_maxlen:
return True
# Allow long URLs of any length.
if any((url in line) for url in ('file://', 'http://', 'https://')):
return True
if 'presubmit: ignore-long-line' in line:
return True
if line_len > extra_maxlen:
return False
if 'url(' in line and file_extension == 'css':
return True
if '<include' in line and file_extension in ('css', 'html', 'js'):
return True
return input_api.re.match(
r'.*[A-Za-z][A-Za-z_0-9]{%d,}.*' % long_symbol, line)
def is_global_pylint_directive(line, pos):
"""True iff the pylint directive starting at line[pos] is global."""
# Any character before |pos| that is not whitespace or '#' indidcates
# this is a local directive.
return not any(c not in " \t#" for c in line[:pos])
def check_python_long_lines(affected_files, error_formatter):
errors = []
global_check_enabled = True
for f in affected_files:
file_path = f.LocalPath()
for idx, line in enumerate(f.NewContents()):
line_num = idx + 1
line_is_short = no_long_lines(PY_FILE_EXTS[0], line)
pos = line.find('pylint: disable=line-too-long')
if pos >= 0:
if is_global_pylint_directive(line, pos):
global_check_enabled = False # Global disable
else:
continue # Local disable.
do_check = global_check_enabled
pos = line.find('pylint: enable=line-too-long')
if pos >= 0:
if is_global_pylint_directive(line, pos):
global_check_enabled = True # Global enable
do_check = True # Ensure it applies to current line as well.
else:
do_check = True # Local enable
if do_check and not line_is_short:
errors.append(error_formatter(file_path, line_num, line))
return errors
def format_error(filename, line_num, line):
return '%s, line %s, %s chars' % (filename, line_num, len(line))
file_ext_list = list(
_GenerateAffectedFileExtList(input_api, source_file_filter))
errors = []
# For non-Python files, a simple line-based rule check is enough.
non_py_file_ext_list = [x for x in file_ext_list if x[1] not in PY_FILE_EXTS]
if non_py_file_ext_list:
errors += _FindNewViolationsOfRuleForList(
no_long_lines, non_py_file_ext_list, error_formatter=format_error)
# However, Python files need more sophisticated checks that need parsing
# the whole source file.
py_file_list = [x[0] for x in file_ext_list if x[1] in PY_FILE_EXTS]
if py_file_list:
errors += check_python_long_lines(
py_file_list, error_formatter=format_error)
if errors:
msg = 'Found %d lines longer than %s characters (first 5 shown).' % (
len(errors), maxlen)
return [output_api.PresubmitPromptWarning(msg, items=errors[:5])]
return []
def CheckLicense(input_api, output_api, license_re_param=None,
project_name=None, source_file_filter=None, accept_empty_files=True):
"""Verifies the license header.
"""
# Early-out if the license_re is guaranteed to match everything.
if license_re_param and license_re_param == '.*':
return []
current_year = int(input_api.time.strftime('%Y'))
if license_re_param:
new_license_re = license_re = license_re_param
else:
project_name = project_name or 'Chromium'
# Accept any year number from 2006 to the current year, or the special
# 2006-20xx string used on the oldest files. 2006-20xx is deprecated, but
# tolerated on old files. On new files the current year must be specified.
allowed_years = (str(s) for s in reversed(range(2006, current_year + 1)))
years_re = '(' + '|'.join(allowed_years) + '|2006-2008|2006-2009|2006-2010)'
# Reduce duplication between the two regex expressions.
key_line = ('Use of this source code is governed by a BSD-style license '
'that can be')
# The (c) is deprecated, but tolerate it until it's removed from all files.
# "All rights reserved" is also deprecated, but tolerate it until it's
# removed from all files.
license_re = (r'.*? Copyright (\(c\) )?%(year)s The %(project)s Authors'
r'(\. All rights reserved\.)?\n'
r'.*? %(key_line)s\n'
r'.*? found in the LICENSE file\.(?: \*/)?\n') % {
'year': years_re,
'project': project_name,
'key_line': key_line,
}
# On new files don't tolerate any digression from the ideal.
new_license_re = (r'.*? Copyright %(year)s The %(project)s Authors\n'
r'.*? %(key_line)s\n'
r'.*? found in the LICENSE file\.(?: \*/)?\n') % {
'year': years_re,
'project': project_name,
'key_line': key_line,
}
license_re = input_api.re.compile(license_re, input_api.re.MULTILINE)
new_license_re = input_api.re.compile(new_license_re, input_api.re.MULTILINE)
bad_files = []
wrong_year_new_files = []
bad_new_files = []
for f in input_api.AffectedSourceFiles(source_file_filter):
# Only examine the first 1,000 bytes of the file to avoid expensive and
# fruitless regex searches over long files with no license.
# re.match would also avoid this but can't be used because some files have
# a shebang line ahead of the license.
# The \r\n fixup is because it is possible on Windows to copy/paste the
# license in such a way that \r\n line endings are inserted. This leads to
# confusing license error messages - it's better to let the separate \r\n
# check handle those.
contents = input_api.ReadFile(f, 'r')[:1000].replace('\r\n', '\n')
if accept_empty_files and not contents:
continue
if f.Action() == 'A':
# Stricter checking for new files (but might actually be moved).
match = new_license_re.search(contents)
if not match:
# License is totally wrong.
bad_new_files.append(f.LocalPath())
elif not license_re_param and match.groups()[0] != str(current_year):
# If we're using the built-in license_re on a new file then make sure
# the year is correct.
wrong_year_new_files.append(f.LocalPath())
elif not license_re.search(contents):
bad_files.append(f.LocalPath())
results = []
if bad_new_files:
if license_re_param:
error_message = ('License on new files must match:\n\n%s\n' %
license_re_param)
else:
# Verbatim text that can be copy-pasted into new files (possibly adjusting
# the leading comment delimiter).
new_license_text = ('// Copyright %(year)s The %(project)s Authors\n'
'// %(key_line)s\n'
'// found in the LICENSE file.\n') % {
'year': current_year,
'project': project_name,
'key_line': key_line,
}
error_message = (
'License on new files must be:\n\n%s\n' % new_license_text +
'(adjusting the comment delimiter accordingly).\n\n')
error_message += 'Found a bad license header in these new files:'
results.append(output_api.PresubmitError(error_message,
items=bad_new_files))
if wrong_year_new_files:
# We can't distinguish between new and moved files, so this has to be a
# warning rather than an error.
results.append(
output_api.PresubmitPromptWarning(
'License doesn\'t list the current year. If this is a new file, '
'use the current year. If this is a moved file then ignore this '
'warning.',
items=wrong_year_new_files))
if bad_files:
results.append(
output_api.PresubmitPromptWarning(
'License must match:\n%s\n' % license_re.pattern +
'Found a bad license header in these files:',
items=bad_files))
return results
### Other checks
def CheckDoNotSubmit(input_api, output_api):
return (
CheckDoNotSubmitInDescription(input_api, output_api) +
CheckDoNotSubmitInFiles(input_api, output_api)
)
def CheckTreeIsOpen(input_api, output_api,
url=None, closed=None, json_url=None):
"""Check whether to allow commit without prompt.
Supports two styles:
1. Checks that an url's content doesn't match a regexp that would mean that
the tree is closed. (old)
2. Check the json_url to decide whether to allow commit without prompt.
Args:
input_api: input related apis.
output_api: output related apis.
url: url to use for regex based tree status.
closed: regex to match for closed status.
json_url: url to download json style status.
"""
if not input_api.is_committing or \
'PRESUBMIT_SKIP_NETWORK' in _os.environ:
return []
try:
if json_url:
connection = input_api.urllib_request.urlopen(json_url)
status = input_api.json.loads(connection.read())
connection.close()
if not status['can_commit_freely']:
short_text = 'Tree state is: ' + status['general_state']
long_text = status['message'] + '\n' + json_url
if input_api.no_diffs:
return [
output_api.PresubmitPromptWarning(short_text, long_text=long_text)
]
return [output_api.PresubmitError(short_text, long_text=long_text)]
else:
# TODO(bradnelson): drop this once all users are gone.
connection = input_api.urllib_request.urlopen(url)
status = connection.read()
connection.close()
if input_api.re.match(closed, status):
long_text = status + '\n' + url
return [output_api.PresubmitError('The tree is closed.',
long_text=long_text)]
except IOError as e:
return [output_api.PresubmitError('Error fetching tree status.',
long_text=str(e))]
return []
def GetUnitTestsInDirectory(input_api,
output_api,
directory,
files_to_check=None,
files_to_skip=None,
env=None,
run_on_python2=True,
run_on_python3=True,
skip_shebang_check=False,
allowlist=None,
blocklist=None):
"""Lists all files in a directory and runs them. Doesn't recurse.
It's mainly a wrapper for RunUnitTests. Use allowlist and blocklist to filter
tests accordingly.
"""
unit_tests = []
test_path = input_api.os_path.abspath(
input_api.os_path.join(input_api.PresubmitLocalPath(), directory))
def check(filename, filters):
return any(True for i in filters if input_api.re.match(i, filename))
to_run = found = 0
for filename in input_api.os_listdir(test_path):
found += 1
fullpath = input_api.os_path.join(test_path, filename)
if not input_api.os_path.isfile(fullpath):
continue
if files_to_check and not check(filename, files_to_check):
continue
if files_to_skip and check(filename, files_to_skip):
continue
unit_tests.append(input_api.os_path.join(directory, filename))
to_run += 1
input_api.logging.debug('Found %d files, running %d unit tests'
% (found, to_run))
if not to_run:
return [
output_api.PresubmitPromptWarning(
'Out of %d files, found none that matched c=%r, s=%r in directory %s'
% (found, files_to_check, files_to_skip, directory))
]
return GetUnitTests(input_api, output_api, unit_tests, env, run_on_python2,
run_on_python3, skip_shebang_check)
def GetUnitTests(input_api,
output_api,
unit_tests,
env=None,
run_on_python2=True,
run_on_python3=True,
skip_shebang_check=False):
"""Runs all unit tests in a directory.
On Windows, sys.executable is used for unit tests ending with ".py".
"""
assert run_on_python3 or run_on_python2, (
'At least one of "run_on_python2" or "run_on_python3" must be set.')
def has_py3_shebang(test):
with _io.open(test, encoding='utf-8') as f:
maybe_shebang = f.readline()
return maybe_shebang.startswith('#!') and 'python3' in maybe_shebang
# We don't want to hinder users from uploading incomplete patches, but we do
# want to report errors as errors when doing presubmit --all testing.
if input_api.is_committing or input_api.no_diffs:
message_type = output_api.PresubmitError
else:
message_type = output_api.PresubmitPromptWarning
results = []
for unit_test in unit_tests:
cmd = [unit_test]
if input_api.verbose:
cmd.append('--verbose')
kwargs = {'cwd': input_api.PresubmitLocalPath()}
if env:
kwargs['env'] = env
if not unit_test.endswith('.py'):
results.append(input_api.Command(
name=unit_test,
cmd=cmd,
kwargs=kwargs,
message=message_type))
else:
test_run = False
# TODO(crbug.com/1223478): The intent for this line was to run the test
# on python3 if the file has a shebang OR if it was explicitly requested
# to run on python3. Since tests have been broken since this landed, we
# introduced the |skip_shebang_check| argument to work around the issue
# until every caller in Chromium has been fixed.
if (skip_shebang_check or has_py3_shebang(unit_test)) and run_on_python3:
results.append(input_api.Command(
name=unit_test,
cmd=cmd,
kwargs=kwargs,
message=message_type,
python3=True))
test_run = True
if run_on_python2:
results.append(input_api.Command(
name=unit_test,
cmd=cmd,
kwargs=kwargs,
message=message_type))
test_run = True
if not test_run:
results.append(output_api.PresubmitError(
"The %s test was not run. You may need to add\n"
"skip_shebang_check=True for python3 tests." % unit_test))
return results
def GetUnitTestsRecursively(input_api,
output_api,
directory,
files_to_check,
files_to_skip,
run_on_python2=True,
run_on_python3=True,
skip_shebang_check=False):
"""Gets all files in the directory tree (git repo) that match files_to_check.
Restricts itself to only find files within the Change's source repo, not
dependencies.
"""
def check(filename):
return (any(input_api.re.match(f, filename) for f in files_to_check) and
not any(input_api.re.match(f, filename) for f in files_to_skip))
tests = []
to_run = found = 0
for filepath in input_api.change.AllFiles(directory):
found += 1
if check(filepath):
to_run += 1
tests.append(filepath)
input_api.logging.debug('Found %d files, running %d' % (found, to_run))
if not to_run:
return [
output_api.PresubmitPromptWarning(
'Out of %d files, found none that matched c=%r, s=%r in directory %s'
% (found, files_to_check, files_to_skip, directory))
]
return GetUnitTests(input_api,
output_api,
tests,
run_on_python2=run_on_python2,
run_on_python3=run_on_python3,
skip_shebang_check=skip_shebang_check)
def GetPythonUnitTests(input_api, output_api, unit_tests, python3=False):
"""Run the unit tests out of process, capture the output and use the result
code to determine success.
DEPRECATED.
"""
# We don't want to hinder users from uploading incomplete patches.
if input_api.is_committing or input_api.no_diffs:
message_type = output_api.PresubmitError
else:
message_type = output_api.PresubmitNotifyResult
results = []
for unit_test in unit_tests:
# Run the unit tests out of process. This is because some unit tests
# stub out base libraries and don't clean up their mess. It's too easy to
# get subtle bugs.
cwd = None
env = None
unit_test_name = unit_test
# 'python -m test.unit_test' doesn't work. We need to change to the right
# directory instead.