Skip to content

Commit 03d56ce

Browse files
authored
Add more ruff lint rules (#328)
```yaml lint.select = [ "A", # flake8-builtins "AIR", # Airflow "ASYNC", # flake8-async "B", # flake8-bugbear "BLE", # flake8-blind-except "C90", # McCabe cyclomatic complexity "DJ", # flake8-django "DTZ", # flake8-datetimez "E", # pycodestyle "EM", # flake8-errmsg "EXE", # flake8-executable "F", # Pyflakes "FA", # flake8-future-annotations "FAST", # FastAPI "FBT", # flake8-boolean-trap "FIX", # flake8-fixme "FLY", # flynt "FURB", # refurb "G", # flake8-logging-format "I", # isort "ICN", # flake8-import-conventions "INP", # flake8-no-pep420 "INT", # flake8-gettext "ISC", # flake8-implicit-str-concat "LOG", # flake8-logging "NPY", # NumPy-specific rules "PD", # pandas-vet "PERF", # Perflint "PGH", # pygrep-hooks "PIE", # flake8-pie "PLC", # Pylint conventions "PLE", # Pylint errors "PYI", # flake8-pyi "RET", # flake8-return "RSE", # flake8-raise "SLOT", # flake8-slots "T10", # flake8-debugger "TC", # flake8-type-checking "TID", # flake8-tidy-imports "TRY", # tryceratops "W", # pycodestyle "YTT", # flake8-2020 ] ```
1 parent 07aba9e commit 03d56ce

File tree

5 files changed

+140
-53
lines changed

5 files changed

+140
-53
lines changed

.pre-commit-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ repos:
1515
- tomli
1616

1717
- repo: https://github.com/astral-sh/ruff-pre-commit
18-
rev: v0.9.9
18+
rev: v0.9.10
1919
hooks:
2020
- id: ruff
2121

cpplint.py

Lines changed: 46 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1407,9 +1407,9 @@ def AddFilters(self, filters):
14071407
if clean_filt:
14081408
self.filters.append(clean_filt)
14091409
for filt in self.filters:
1410-
if not (filt.startswith('+') or filt.startswith('-')):
1411-
raise ValueError('Every filter in --filters must start with + or -'
1412-
f' ({filt} does not)')
1410+
if not filt.startswith(('+', '-')):
1411+
msg = f'Every filter in --filters must start with + or - ({filt} does not)'
1412+
raise ValueError(msg)
14131413

14141414
def BackupFilters(self):
14151415
""" Saves the current filter list to backup storage."""
@@ -1618,7 +1618,7 @@ def Check(self, error, filename, linenum):
16181618
trigger = base_trigger * 2**_VerboseLevel()
16191619

16201620
if self.lines_in_function > trigger:
1621-
error_level = int(math.log(self.lines_in_function / base_trigger, 2))
1621+
error_level = int(math.log2(self.lines_in_function / base_trigger))
16221622
# 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...
16231623
if error_level > 5:
16241624
error_level = 5
@@ -1769,7 +1769,9 @@ def _ShouldPrintError(category, confidence, filename, linenum):
17691769
if category_match and file_match and line_match:
17701770
is_filtered = False
17711771
else:
1772-
assert False # should have been checked for in SetFilter.
1772+
# should have been checked for in SetFilter.
1773+
msg = f'Invalid filter: {one_filter}'
1774+
raise ValueError(msg)
17731775
if is_filtered:
17741776
return False
17751777

@@ -2357,7 +2359,8 @@ def CheckForCopyright(filename, lines, error):
23572359
# We'll say it should occur by line 10. Don't forget there's a
23582360
# placeholder line at the front.
23592361
for line in range(1, min(len(lines), 11)):
2360-
if re.search(r'Copyright', lines[line], re.I): break
2362+
if re.search(r'Copyright', lines[line], re.IGNORECASE):
2363+
break
23612364
else: # means no copyright line was found
23622365
error(filename, 0, 'legal/copyright', 5,
23632366
'No copyright message found. '
@@ -2376,8 +2379,7 @@ def GetIndentLevel(line):
23762379
indent = re.match(r'^( *)\S', line)
23772380
if indent:
23782381
return len(indent.group(1))
2379-
else:
2380-
return 0
2382+
return 0
23812383

23822384
def PathSplitToList(path):
23832385
"""Returns the path split into a list by the separator.
@@ -3108,14 +3110,16 @@ def InTemplateArgumentList(self, clean_lines, linenum, pos):
31083110
# These things do not look like template argument list:
31093111
# class Suspect {
31103112
# class Suspect x; }
3111-
if token in ('{', '}', ';'): return False
3113+
if token in ('{', '}', ';'):
3114+
return False
31123115

31133116
# These things look like template argument list:
31143117
# template <class Suspect>
31153118
# template <class Suspect = default_value>
31163119
# template <class Suspect[]>
31173120
# template <class Suspect...>
3118-
if token in ('>', '=', '[', ']', '.'): return True
3121+
if token in ('>', '=', '[', ']', '.'):
3122+
return True
31193123

31203124
# Check if token is an unmatched '<'.
31213125
# If not, move on to the next character.
@@ -4912,8 +4916,7 @@ def GetLineWidth(line):
49124916

49134917
width += 1
49144918
return width
4915-
else:
4916-
return len(line)
4919+
return len(line)
49174920

49184921

49194922
def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,
@@ -4985,9 +4988,7 @@ def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,
49854988
# Check if the line is a header guard.
49864989
is_header_guard = False
49874990
if IsHeaderExtension(file_extension):
4988-
if (line.startswith(f'#ifndef {cppvar}') or
4989-
line.startswith(f'#define {cppvar}') or
4990-
line.startswith(f'#endif // {cppvar}')):
4991+
if line.startswith((f'#ifndef {cppvar}', f'#define {cppvar}', f'#endif // {cppvar}')):
49914992
is_header_guard = True
49924993
# #include lines and header guards can be long, since there's no clean way to
49934994
# split them.
@@ -5126,8 +5127,7 @@ def _ClassifyInclude(fileinfo, include, used_angle_brackets, include_order="defa
51265127
return _CPP_SYS_HEADER
51275128
if is_std_c_header:
51285129
return _C_SYS_HEADER
5129-
else:
5130-
return _OTHER_SYS_HEADER
5130+
return _OTHER_SYS_HEADER
51315131

51325132
# If the target file and the include we're checking share a
51335133
# basename when we drop common extensions, and the include
@@ -5277,7 +5277,7 @@ def _GetTextInside(text, start_pattern):
52775277
closing_punctuation = set(dict.values(matching_punctuation))
52785278

52795279
# Find the position to start extracting text.
5280-
match = re.search(start_pattern, text, re.M)
5280+
match = re.search(start_pattern, text, re.MULTILINE)
52815281
if not match: # start_pattern not found in text.
52825282
return None
52835283
start_position = match.end(0)
@@ -5422,7 +5422,7 @@ def CheckLanguage(filename, clean_lines, linenum, file_extension,
54225422
match = re.match(r'([\w.\->()]+)$', printf_args)
54235423
if match and match.group(1) != '__VA_ARGS__':
54245424
function_name = re.search(r'\b((?:string)?printf)\s*\(',
5425-
line, re.I).group(1)
5425+
line, re.IGNORECASE).group(1)
54265426
error(filename, linenum, 'runtime/printf', 4,
54275427
'Potential format string bug. Do'
54285428
f' {function_name}("%s", {match.group(1)}) instead.')
@@ -5458,17 +5458,25 @@ def CheckLanguage(filename, clean_lines, linenum, file_extension,
54585458
skip_next = False
54595459
continue
54605460

5461-
if re.search(r'sizeof\(.+\)', tok): continue
5462-
if re.search(r'arraysize\(\w+\)', tok): continue
5461+
if re.search(r'sizeof\(.+\)', tok):
5462+
continue
5463+
if re.search(r'arraysize\(\w+\)', tok):
5464+
continue
54635465

54645466
tok = tok.lstrip('(')
54655467
tok = tok.rstrip(')')
5466-
if not tok: continue
5467-
if re.match(r'\d+', tok): continue
5468-
if re.match(r'0[xX][0-9a-fA-F]+', tok): continue
5469-
if re.match(r'k[A-Z0-9]\w*', tok): continue
5470-
if re.match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
5471-
if re.match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
5468+
if not tok:
5469+
continue
5470+
if re.match(r'\d+', tok):
5471+
continue
5472+
if re.match(r'0[xX][0-9a-fA-F]+', tok):
5473+
continue
5474+
if re.match(r'k[A-Z0-9]\w*', tok):
5475+
continue
5476+
if re.match(r'(.+::)?k[A-Z0-9]\w*', tok):
5477+
continue
5478+
if re.match(r'(.+::)?[A-Z][A-Z0-9_]*', tok):
5479+
continue
54725480
# A catch all for tricky sizeof cases, including 'sizeof expression',
54735481
# 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
54745482
# requires skipping the next token because we split on ' ' and '*'.
@@ -5783,7 +5791,7 @@ def CheckForNonConstReference(filename, clean_lines, linenum,
57835791
r')\s*\(')
57845792
if re.search(allowed_functions, line):
57855793
return
5786-
elif not re.search(r'\S+\([^)]*$', line):
5794+
if not re.search(r'\S+\([^)]*$', line):
57875795
# Don't see an allowed function on this line. Actually we
57885796
# didn't see any function name on this line, so this is likely a
57895797
# multi-line parameter list. Try a bit harder to catch this case.
@@ -5955,8 +5963,7 @@ def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):
59555963
return False
59565964

59575965
# operator++(int) and operator--(int)
5958-
if (context.endswith(' operator++') or context.endswith(' operator--') or
5959-
context.endswith('::operator++') or context.endswith('::operator--')):
5966+
if context.endswith((' operator++', ' operator--', '::operator++', '::operator--')):
59605967
return False
59615968

59625969
# A single unnamed argument for a function tends to look like old style cast.
@@ -6273,7 +6280,8 @@ def CheckRedundantVirtual(filename, clean_lines, linenum, error):
62736280
# Look for "virtual" on current line.
62746281
line = clean_lines.elided[linenum]
62756282
virtual = re.match(r'^(.*)(\bvirtual\b)(.*)$', line)
6276-
if not virtual: return
6283+
if not virtual:
6284+
return
62776285

62786286
# Ignore "virtual" keywords that are near access-specifiers. These
62796287
# are only used in class base-specifier and do not apply to member
@@ -6285,7 +6293,8 @@ def CheckRedundantVirtual(filename, clean_lines, linenum, error):
62856293
# Ignore the "virtual" keyword from virtual base classes. Usually
62866294
# there is a column on the same line in these cases (virtual base
62876295
# classes are rare in google3 because multiple inheritance is rare).
6288-
if re.match(r'^.*[^:]:[^:].*$', line): return
6296+
if re.match(r'^.*[^:]:[^:].*$', line):
6297+
return
62896298

62906299
# Look for the next opening parenthesis. This is the start of the
62916300
# parameter list (possibly on the next line shortly after virtual).
@@ -6374,7 +6383,7 @@ def IsBlockInNameSpace(nesting_state, is_forward_declaration):
63746383
if len(nesting_state.stack) >= 1:
63756384
if isinstance(nesting_state.stack[-1], _NamespaceInfo):
63766385
return True
6377-
elif (len(nesting_state.stack) > 1 and
6386+
if (len(nesting_state.stack) > 1 and
63786387
isinstance(nesting_state.previous_stack_top, _NamespaceInfo) and
63796388
isinstance(nesting_state.stack[-2], _NamespaceInfo)):
63806389
return True
@@ -6453,7 +6462,8 @@ def ProcessLine(filename, file_extension, clean_lines, line,
64536462
nesting_state.Update(filename, clean_lines, line, error)
64546463
CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
64556464
error)
6456-
if nesting_state.InAsmBlock(): return
6465+
if nesting_state.InAsmBlock():
6466+
return
64576467
CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
64586468
CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
64596469
CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error, cppvar)
@@ -6895,9 +6905,8 @@ def _ParseFilterSelector(parameter):
68956905
second_colon_pos = parameter.find(":", colon_pos + 1)
68966906
if second_colon_pos == -1:
68976907
return category, parameter[colon_pos + 1:], -1
6898-
else:
6899-
return category, parameter[colon_pos + 1: second_colon_pos], \
6900-
int(parameter[second_colon_pos + 1:])
6908+
return category, parameter[colon_pos + 1: second_colon_pos], \
6909+
int(parameter[second_colon_pos + 1:])
69016910

69026911
def _ExpandDirectories(filenames):
69036912
"""Searches a list of filenames and replaces directories in the list with

cpplint_clitest.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,12 @@
3333

3434
import glob
3535
import os
36-
import sys
37-
import subprocess
38-
import unittest
3936
import shutil
37+
import subprocess
38+
import sys
4039
import tempfile
40+
import unittest
41+
4142
from pytest import mark
4243
from testfixtures import compare
4344

@@ -101,7 +102,7 @@ def setUpClass(cls):
101102
except Exception:
102103
try:
103104
cls.tearDownClass()
104-
except Exception:
105+
except Exception: # noqa: BLE001
105106
pass
106107
raise
107108

cpplint_unittest.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -43,16 +43,17 @@
4343
import sys
4444
import tempfile
4545
import unittest
46-
from parameterized import parameterized
46+
4747
import pytest
48+
from parameterized import parameterized
4849

4950
import cpplint
5051

52+
5153
def codecs_latin_encode(x):
5254
if sys.version_info < (3,):
5355
return x
54-
else:
55-
return codecs.latin_1_encode(x)[0]
56+
return codecs.latin_1_encode(x)[0]
5657

5758
# This class works as an error collector and replaces cpplint.Error
5859
# function for the unit tests. We also verify each category we see
@@ -80,8 +81,7 @@ def __call__(self, filename, linenum,
8081
def Results(self):
8182
if len(self._errors) < 2:
8283
return ''.join(self._errors) # Most tests expect to have a string.
83-
else:
84-
return self._errors # Let's give a list if there is more than one.
84+
return self._errors # Let's give a list if there is more than one.
8585

8686
def ResultList(self):
8787
return self._errors
@@ -115,7 +115,7 @@ class EnterableList(list):
115115
def __enter__(self):
116116
return self
117117

118-
def __exit__(self, type, value, tb):
118+
def __exit__(self, type, value, tb): # noqa: A002
119119
return self
120120
self.mock_file = EnterableList(mock_file)
121121

@@ -4283,8 +4283,8 @@ def testParseArguments(self):
42834283
self.assertEqual(set(['hpp', 'h', 'cpp']), cpplint.GetAllExtensions())
42844284

42854285
finally:
4286-
sys.stdout == sys.__stdout__
4287-
sys.stderr == sys.__stderr__
4286+
sys.stdout = sys.__stdout__
4287+
sys.stderr = sys.__stderr__
42884288
cpplint._cpplint_state.output_format = old_output_format
42894289
cpplint._cpplint_state.verbose_level = old_verbose_level
42904290
cpplint._cpplint_state.filters = old_filters
@@ -4657,6 +4657,7 @@ def GetBuildHeaderGuardPreprocessorSymbol(self, file_path):
46574657
error)
46584658
if matched is not None:
46594659
return matched.group(1)
4660+
return None
46604661

46614662
def testBuildHeaderGuard(self):
46624663
file_path = 'mydir/foo.h'
@@ -5276,7 +5277,7 @@ def testBuildStorageClass(self):
52765277
# Make sure that the declaration is logged if there's an error.
52775278
# Seed generator with an integer for absolute reproducibility.
52785279
random.seed(25)
5279-
for unused_i in range(10):
5280+
for _i in range(10):
52805281
# Build up random list of non-storage-class declaration specs.
52815282
other_decl_specs = [random.choice(qualifiers), random.choice(signs),
52825283
random.choice(types)]
@@ -5660,7 +5661,7 @@ def testRegression(self):
56605661
def Format(includes):
56615662
include_list = []
56625663
for item in includes:
5663-
if item.startswith('"') or item.startswith('<'):
5664+
if item.startswith(('"', '<')):
56645665
include_list.append('#include %s\n' % item)
56655666
else:
56665667
include_list.append(item + '\n')

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy