Skip to content

Commit bc5e8e3

Browse files
authored
Enforce return code style check in Python code (project-chip#41842)
* Post merge review updates * Add ruff rule to check for return value correctness * Apply ruff automatic fixes * Apply ruff rewrite fixes * Cleanup dead code * Apply restyle fixes * Simplify if else logic by inlining return
1 parent 076b40e commit bc5e8e3

File tree

281 files changed

+1038
-1687
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

281 files changed

+1038
-1687
lines changed

config/esp32/components/chip/create_args_gn.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,7 @@
4545

4646
def get_compile_flags(src_file):
4747
compile_command = [
48-
res["command"]
49-
for res in filter(lambda cmd: cmd["file"] == src_file, compile_commands)
48+
res["command"] for res in compile_commands if res["file"] == src_file
5049
]
5150

5251
if len(compile_command) != 1:

credentials/fetch_paa_certs_from_dcl.py

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -73,14 +73,13 @@ def parse_paa_root_certs(cmdpipe, paa_list):
7373
line = cmdpipe.stdout.readline()
7474
if not line:
7575
break
76-
else:
77-
if b': ' in line:
78-
key, value = line.split(b': ')
79-
result[key.strip(b' -').decode("utf-8")
80-
] = value.strip().decode("utf-8")
81-
parse_paa_root_certs.counter += 1
82-
if parse_paa_root_certs.counter % 2 == 0:
83-
paa_list.append(copy.deepcopy(result))
76+
if b': ' in line:
77+
key, value = line.split(b': ')
78+
result[key.strip(b' -').decode("utf-8")
79+
] = value.strip().decode("utf-8")
80+
parse_paa_root_certs.counter += 1
81+
if parse_paa_root_certs.counter % 2 == 0:
82+
paa_list.append(copy.deepcopy(result))
8483

8584

8685
def write_cert(certificate, subject):
@@ -109,16 +108,15 @@ def parse_paa_root_cert_from_dcld(cmdpipe):
109108
line = cmdpipe.stdout.readline()
110109
if not line:
111110
break
112-
else:
113-
if b'pemCert: |' in line:
114-
while True:
115-
line = cmdpipe.stdout.readline()
116-
certificate += line.strip(b' \t').decode("utf-8")
117-
if b'-----END CERTIFICATE-----' in line:
118-
break
119-
if b'subjectAsText:' in line:
120-
subject = line.split(b': ')[1].strip().decode("utf-8")
121-
break
111+
if b'pemCert: |' in line:
112+
while True:
113+
line = cmdpipe.stdout.readline()
114+
certificate += line.strip(b' \t').decode("utf-8")
115+
if b'-----END CERTIFICATE-----' in line:
116+
break
117+
if b'subjectAsText:' in line:
118+
subject = line.split(b': ')[1].strip().decode("utf-8")
119+
break
122120

123121
return (certificate, subject)
124122

credentials/generate_revocation_set.py

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -178,9 +178,8 @@ def is_self_signed_certificate(cert: x509.Certificate) -> bool:
178178
result = verify_cert(cert, cert)
179179
if result == CertVerificationResult.SUCCESS:
180180
return True
181-
else:
182-
logging.debug(
183-
f"Certificate with subject: {cert.subject.rfc4514_string()} is not a valid self-signed certificate. Result: {result.name}")
181+
logging.debug(
182+
f"Certificate with subject: {cert.subject.rfc4514_string()} is not a valid self-signed certificate. Result: {result.name}")
184183
return False
185184

186185

@@ -207,13 +206,12 @@ def validate_cert_chain(crl_signer: x509.Certificate, crl_signer_delegator: x509
207206
f"Cannot verify certificate subject: {crl_signer_delegator.subject.rfc4514_string()} issued by certificate subject: {paa.subject.rfc4514_string()}. Result: {result_delegator.name}")
208207
return False
209208
return True
210-
else:
211-
result = verify_cert(crl_signer, paa)
212-
if not result == CertVerificationResult.SUCCESS:
213-
logging.debug(
214-
f"Cannot verify certificate subject: {crl_signer.subject.rfc4514_string()} issued by certificate subject: {paa.subject.rfc4514_string()}. Result: {result.name}")
215-
return False
216-
return True
209+
result = verify_cert(crl_signer, paa)
210+
if not result == CertVerificationResult.SUCCESS:
211+
logging.debug(
212+
f"Cannot verify certificate subject: {crl_signer.subject.rfc4514_string()} issued by certificate subject: {paa.subject.rfc4514_string()}. Result: {result.name}")
213+
return False
214+
return True
217215

218216

219217
def validate_vid_pid(revocation_point: RevocationPoint, crl_signer_certificate: x509.Certificate, crl_signer_delegator_certificate: x509.Certificate) -> bool:
@@ -371,8 +369,7 @@ def send_get_request(self, url: str) -> dict:
371369
Send a GET request for a json object.
372370
'''
373371
try:
374-
response = requests.get(url).json()
375-
return response
372+
return requests.get(url).json()
376373
except Exception as e:
377374
logging.error(f"Failed to fetch {url}: {e}")
378375
return None
@@ -430,7 +427,7 @@ def get_paa_cert(self, initial_cert: x509.Certificate) -> Optional[x509.Certific
430427
akid = get_akid(initial_cert)
431428
except ExtensionNotFound:
432429
logging.warning('Certificate AKID not found.')
433-
return
430+
return None
434431
paa_certificate = None
435432
while not paa_certificate:
436433
try:
@@ -441,7 +438,7 @@ def get_paa_cert(self, initial_cert: x509.Certificate) -> Optional[x509.Certific
441438

442439
except Exception as e:
443440
logging.error('Failed to get PAA certificate', e)
444-
return
441+
return None
445442
logging.debug(f"issuer_name: {issuer_certificate.subject.rfc4514_string()}")
446443
issuer_name = issuer_certificate.issuer
447444
try:

examples/chef/chef.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -120,8 +120,7 @@ def check_python_version() -> None:
120120

121121
def load_cicd_config() -> Dict[str, Any]:
122122
with open(_CICD_CONFIG_FILE_NAME) as config_file:
123-
config = json.loads(config_file.read())
124-
return config
123+
return json.loads(config_file.read())
125124

126125

127126
def flush_print(
@@ -470,7 +469,7 @@ def main() -> int:
470469
archive_name = f"{label}-{device_name}"
471470
if options.build_exclude and re.search(options.build_exclude, archive_name):
472471
continue
473-
elif options.build_include and not re.search(options.build_include, archive_name):
472+
if options.build_include and not re.search(options.build_include, archive_name):
474473
continue
475474
if options.dry_run:
476475
flush_print(archive_name)

examples/chef/stateful_shell.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,3 +159,4 @@ def run_cmd(
159159
)
160160

161161
return output
162+
return None

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ select = [
3333
# Consistent commas
3434
"COM",
3535
# Simplify the code if possible
36-
"C4",
36+
"C4", "RET",
3737
# Ensure that scripts are executable
3838
"EXE",
3939
# Check for common logging issues

scripts/build/builders/android.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -53,14 +53,10 @@ def AbiName(self):
5353
raise Exception("Unknown board type: %r" % self)
5454

5555
def IsIde(self):
56-
if (
57-
self == AndroidBoard.AndroidStudio_ARM
58-
or self == AndroidBoard.AndroidStudio_ARM64
59-
or self == AndroidBoard.AndroidStudio_X64
60-
or self == AndroidBoard.AndroidStudio_X86
61-
):
62-
return True
63-
return False
56+
return (self == AndroidBoard.AndroidStudio_ARM
57+
or self == AndroidBoard.AndroidStudio_ARM64
58+
or self == AndroidBoard.AndroidStudio_X64
59+
or self == AndroidBoard.AndroidStudio_X86)
6460

6561

6662
class AndroidApp(Enum):

scripts/py_matter_idl/matter/idl/data_model_xml/handlers/handlers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -468,7 +468,7 @@ def __init__(self, context: Context, cluster: Cluster, attrs: AttributesImpl):
468468
is_command = False # response
469469
else:
470470
log.warning("Could not clearly determine command direction: %s",
471-
list(attrs.items()))
471+
attrs.items())
472472
# Do a best-guess. However we should NOT need to guess once
473473
# we have a good data set
474474
is_command = not attrs["name"].endswith("Response")

scripts/py_matter_idl/matter/idl/data_model_xml/handlers/parsing.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,7 @@ def AttributesToEvent(attrs: AttributesImpl) -> Event:
268268
elif attrs["priority"] == "debug":
269269
priority = EventPriority.DEBUG
270270
elif attrs["priority"] == "desc":
271-
log.warning("Found an event with 'desc' priority: '%s'", list(attrs.items()))
271+
log.warning("Found an event with 'desc' priority: '%s'", attrs.items())
272272
priority = EventPriority.CRITICAL
273273
else:
274274
raise Exception("UNKNOWN event priority: %r" % attrs["priority"])

scripts/py_matter_idl/matter/idl/generators/cpp/tlvmeta/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ def GenerateTables(self) -> Generator[Table, None, None]:
171171
)
172172
for e in self.cluster.events if e.fields
173173
])
174-
cluster_entries.extend(list(self.CommandEntries()))
174+
cluster_entries.extend(self.CommandEntries())
175175

176176
yield Table(
177177
full_name=self.cluster.name,
@@ -239,7 +239,7 @@ def GenerateTables(self) -> Generator[Table, None, None]:
239239
def CreateTables(idl: Idl) -> List[Table]:
240240
result = []
241241
for cluster in idl.clusters:
242-
result.extend(list(ClusterTablesGenerator(cluster).GenerateTables()))
242+
result.extend(ClusterTablesGenerator(cluster).GenerateTables())
243243
return result
244244

245245

0 commit comments

Comments
 (0)