Skip to content

Commit a0136a5

Browse files
Implement LOG015 and G ruff ruleset recommendations in scripts/ (project-chip#42062)
* Implement LOG015 and G ruff ruleset recommendations in scripts/ - created per-file logger as LOG015 recommends - updated log messages to not use lazy formatting instead of f-strings, .format() and % - %s -> '%s' where applicable in log messages to better indicate empty strings - log.error -> log.exception in exception handlers - used logging.getLevelNamesMapping() instead of magic dicts Signed-off-by: Maciej Grela <[email protected]> * Restyled by isort * Implement copilot review changes Signed-off-by: Maciej Grela <[email protected]> * Fix two missed LOGGER instances Signed-off-by: Maciej Grela <[email protected]> --------- Signed-off-by: Maciej Grela <[email protected]> Co-authored-by: Restyled.io <[email protected]>
1 parent 81af9a6 commit a0136a5

File tree

84 files changed

+883
-873
lines changed

Some content is hidden

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

84 files changed

+883
-873
lines changed

scripts/checkout_submodules.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222
import subprocess
2323
from collections import namedtuple
2424

25+
log = logging.getLogger(__name__)
26+
2527
CHIP_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
2628

2729
ALL_PLATFORMS = {
@@ -102,15 +104,14 @@ def make_chip_root_safe_directory() -> None:
102104
config.check_returncode()
103105
existing = config.stdout.split('\0')
104106
if CHIP_ROOT not in existing:
105-
logging.info(
106-
"Adding CHIP_ROOT to global git safe.directory configuration")
107+
log.info("Adding CHIP_ROOT to global git safe.directory configuration")
107108
subprocess.check_call(
108109
['git', 'config', '--global', '--add', 'safe.directory', CHIP_ROOT])
109110

110111

111112
def checkout_modules(modules: list, shallow: bool, force: bool, recursive: bool, jobs: int) -> None:
112113
names = ', '.join([module.name for module in modules])
113-
logging.info(f'Checking out: {names}')
114+
log.info("Checking out '%s'", names)
114115

115116
cmd = ['git', '-c', 'core.symlinks=true', '-C', CHIP_ROOT]
116117
cmd += ['submodule', '--quiet', 'update', '--init']
@@ -137,7 +138,7 @@ def checkout_modules(modules: list, shallow: bool, force: bool, recursive: bool,
137138

138139
def deinit_modules(modules: list, force: bool) -> None:
139140
names = ', '.join([module.name for module in modules])
140-
logging.info(f'Deinitializing: {names}')
141+
log.info("Deinitializing: '%s'", names)
141142

142143
cmd = ['git', '-C', CHIP_ROOT, 'submodule', '--quiet', 'deinit']
143144
cmd += ['--force'] if force else []

scripts/codegen.py

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@
4141
except ImportError:
4242
_has_coloredlogs = False
4343

44+
log = logging.getLogger(__name__)
45+
4446

4547
class ListGeneratedFilesStorage(GeneratorStorage):
4648
"""
@@ -59,12 +61,7 @@ def write_new_data(self, relative_path: str, content: str):
5961

6062
# Supported log levels, mapping string values required for argument
6163
# parsing into logging constants
62-
__LOG_LEVELS__ = {
63-
'debug': logging.DEBUG,
64-
'info': logging.INFO,
65-
'warn': logging.WARNING,
66-
'fatal': logging.FATAL,
67-
}
64+
__LOG_LEVELS__ = logging.getLevelNamesMapping()
6865

6966

7067
@click.command()
@@ -111,9 +108,9 @@ def main(log_level, generator, option, output_dir, dry_run, name_only, expected_
111108

112109
def formatKotlinFiles(paths):
113110
try:
114-
logging.info("Prettifying %d kotlin files:", len(paths))
111+
log.info("Prettifying %d kotlin files:", len(paths))
115112
for name in paths:
116-
logging.info(" %s" % name)
113+
log.info(" '%s'", name)
117114

118115
VERSION = "0.58"
119116
JAR_NAME = f"ktfmt-{VERSION}-with-dependencies.jar"
@@ -148,31 +145,31 @@ def formatKotlinFiles(paths):
148145
else:
149146
storage = FileSystemGeneratorStorage(output_dir)
150147

151-
logging.info("Parsing idl from %s" % idl_path)
148+
log.info("Parsing idl from '%s'", idl_path)
152149
idl_tree = CreateParser().parse(open(idl_path, "rt").read(), file_name=idl_path)
153150

154151
plugin_module = None
155152
if generator.startswith('custom:'):
156153
# check that the plugin path is provided
157154
custom_params = generator.split(':')
158155
if len(custom_params) != 3:
159-
logging.fatal("Custom generator format not valid. Please use --generator custom:<path>:<module>")
156+
log.fatal("Custom generator format not valid. Please use --generator custom:<path>:<module>")
160157
sys.exit(1)
161158
(generator, plugin_path, plugin_module) = custom_params
162159

163-
logging.info("Using CustomGenerator at plugin path %s.%s" % (plugin_path, plugin_module))
160+
log.info("Using CustomGenerator at plugin path '%s.%s'", plugin_path, plugin_module)
164161
sys.path.append(plugin_path)
165162
generator = 'CUSTOM'
166163

167164
extra_args = {}
168165
for o in option:
169166
if ':' not in o:
170-
logging.fatal("Please specify options as '<key>:<value>'. %r is not valid. " % o)
167+
log.fatal("Please specify options as '<key>:<value>'. %r is not valid. ", o)
171168
sys.exit(1)
172169
key, value = o.split(':')
173170
extra_args[key] = value
174171

175-
logging.info("Running code generator %s" % generator)
172+
log.info("Running code generator '%s'", generator)
176173
generator = CodeGenerator.FromString(generator).Create(storage, idl=idl_tree, plugin_module=plugin_module, **extra_args)
177174
generator.render(dry_run)
178175

@@ -186,7 +183,7 @@ def formatKotlinFiles(paths):
186183

187184
if name_dict.get('.kt', []):
188185
try:
189-
logging.debug("Formatting kt_files: %s" % name_dict['.kt'])
186+
log.debug("Formatting kt_files: '%s'", name_dict['.kt'])
190187
except Exception:
191188
traceback.print_exc()
192189
formatKotlinFiles(name_dict['.kt'])
@@ -196,7 +193,7 @@ def formatKotlinFiles(paths):
196193
cpp_files.extend(name_dict.get(ext, []))
197194
if cpp_files:
198195
try:
199-
logging.debug("Formatting cpp_files: %s", cpp_files)
196+
log.debug("Formatting cpp_files: '%s'", cpp_files)
200197
subprocess.check_call([getClangFormatBinary(), "-i"] + cpp_files)
201198
except Exception:
202199
traceback.print_exc()
@@ -210,20 +207,20 @@ def formatKotlinFiles(paths):
210207
expected.add(expanded_path)
211208

212209
if expected != storage.generated_paths:
213-
logging.fatal("expected and generated files do not match.")
210+
log.fatal("expected and generated files do not match.")
214211

215212
extra = storage.generated_paths - expected
216213
missing = expected - storage.generated_paths
217214

218215
for name in extra:
219-
logging.fatal(" '%s' was generated but not expected" % name)
216+
log.fatal(" '%s' was generated but not expected", name)
220217

221218
for name in missing:
222-
logging.fatal(" '%s' was expected but not generated" % name)
219+
log.fatal(" '%s' was expected but not generated", name)
223220

224221
sys.exit(1)
225222

226-
logging.info("Done")
223+
log.info("Done")
227224

228225

229226
if __name__ == '__main__':

scripts/codepregen.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -37,14 +37,11 @@
3737
except ImportError:
3838
_has_coloredlogs = False
3939

40+
log = logging.getLogger(__name__)
41+
4042
# Supported log levels, mapping string values required for argument
4143
# parsing into logging constants
42-
__LOG_LEVELS__ = {
43-
'debug': logging.DEBUG,
44-
'info': logging.INFO,
45-
'warn': logging.WARNING,
46-
'fatal': logging.FATAL,
47-
}
44+
__LOG_LEVELS__ = logging.getLevelNamesMapping()
4845

4946

5047
def _ParallelGenerateOne(arg):
@@ -111,7 +108,7 @@ def main(log_level, parallel, dry_run, generator, input_glob, sdk_root, external
111108

112109
output_dir = os.path.abspath(output_dir)
113110

114-
logging.info(f"Pre-generating {sdk_root} data into {output_dir}")
111+
log.info("Pre-generating '%s' data into '%s'", sdk_root, output_dir)
115112

116113
if not dry_run:
117114
runner = ShellRunner()
@@ -137,7 +134,7 @@ def main(log_level, parallel, dry_run, generator, input_glob, sdk_root, external
137134
for target in targets:
138135
target.Generate(output_dir)
139136

140-
logging.info("Done")
137+
log.info("Done")
141138

142139

143140
if __name__ == '__main__':

scripts/copyfiles.py

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -26,14 +26,11 @@
2626
except ImportError:
2727
_has_coloredlogs = False
2828

29+
log = logging.getLogger(__name__)
30+
2931
# Supported log levels, mapping string values required for argument
3032
# parsing into logging constants
31-
__LOG_LEVELS__ = {
32-
'debug': logging.DEBUG,
33-
'info': logging.INFO,
34-
'warn': logging.WARNING,
35-
'fatal': logging.FATAL,
36-
}
33+
__LOG_LEVELS__ = logging.getLevelNamesMapping()
3734

3835

3936
@click.command()
@@ -72,7 +69,7 @@ def main(log_level, source_dir: str, target_dir: str, filenames: list[str]):
7269

7370
# We are copying to target ...
7471
if not os.path.exists(target_dir):
75-
logging.info("Creating output directory %s", target_dir)
72+
log.info("Creating output directory '%s'", target_dir)
7673
os.makedirs(target_dir)
7774

7875
for filename in filenames:
@@ -88,7 +85,7 @@ def main(log_level, source_dir: str, target_dir: str, filenames: list[str]):
8885
filename = os.path.abspath(filename)
8986
relative_path = os.path.relpath(filename, source_dir)
9087
if not filename.endswith(relative_path):
91-
logging.error("%s does not seem to be a child of %s: relative path is %s", filename, source_dir, relative_path)
88+
log.error("'%s' does not seem to be a child of '%s': relative path is '%s'", filename, source_dir, relative_path)
9289
sys.exit(1)
9390

9491
# Prepend the destination directory to relative path. So that if we have:
@@ -105,10 +102,10 @@ def main(log_level, source_dir: str, target_dir: str, filenames: list[str]):
105102

106103
destination_dir = os.path.dirname(destination)
107104
if not os.path.exists(destination_dir):
108-
logging.info("Creating output directory %s", destination_dir)
105+
log.info("Creating output directory '%s'", destination_dir)
109106
os.makedirs(destination_dir)
110107

111-
logging.info("Copying %s into %s", filename, destination)
108+
log.info("Copying '%s' into '%s'", filename, destination)
112109
shutil.copyfile(filename, destination)
113110

114111

scripts/examples/tests/test.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323

2424
import coloredlogs
2525

26+
log = logging.getLogger(__name__)
27+
2628
SCRIPT_ROOT = os.path.dirname(__file__)
2729

2830

@@ -60,9 +62,9 @@ def main():
6062
diffs = list(difflib.unified_diff(expected, actual))
6163

6264
if diffs:
63-
logging.error("DIFFERENCE between expected and generated output")
65+
log.error("DIFFERENCE between expected and generated output")
6466
for line in diffs:
65-
logging.warning(" " + line.strip())
67+
log.warning(" %s", line.strip())
6668
sys.exit(1)
6769

6870

scripts/flashing/bouffalolab_firmware_utils.py

Lines changed: 24 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import pathlib
2121
import platform
2222
import re
23+
import shlex
2324
import shutil
2425
import subprocess
2526
import sys
@@ -31,6 +32,8 @@
3132

3233
coloredlogs.install(level='DEBUG')
3334

35+
log = logging.getLogger(__name__)
36+
3437
# Additional options that can be use to configure an `Flasher`
3538
# object (as dictionary keys) and/or passed as command line options.
3639

@@ -359,14 +362,14 @@ def get_tools():
359362
raise Exception("Do NOT support {} operating system to program firmware.".format(sys.platform))
360363

361364
if not os.path.exists(flashtool_exe):
362-
logging.fatal('*' * 80)
363-
logging.error('Flashtool is not installed, or environment variable BOUFFALOLAB_SDK_ROOT is not exported.')
364-
logging.fatal('\tPlease make sure Bouffalo Lab SDK installs as below:')
365-
logging.fatal('\t\t./third_party/bouffalolab/env-setup.sh')
366-
367-
logging.fatal('\tPlease make sure BOUFFALOLAB_SDK_ROOT exports before building as below:')
368-
logging.fatal('\t\texport BOUFFALOLAB_SDK_ROOT="your install path"')
369-
logging.fatal('*' * 80)
365+
log.fatal("*" * 80)
366+
log.error("Flashtool is not installed, or environment variable BOUFFALOLAB_SDK_ROOT is not exported.")
367+
log.fatal("\tPlease make sure Bouffalo Lab SDK installs as below:")
368+
log.fatal("\t\t./third_party/bouffalolab/env-setup.sh")
369+
370+
log.fatal("\tPlease make sure BOUFFALOLAB_SDK_ROOT exports before building as below:")
371+
log.fatal("\t\texport BOUFFALOLAB_SDK_ROOT='your install path'")
372+
log.fatal("*" * 80)
370373
raise Exception("Flash tool is not installed.")
371374

372375
return flashtool_path, flashtool_exe
@@ -428,12 +431,12 @@ def exe_gen_ota_image_cmd(flashtool_exe):
428431
if self.args["sk"]:
429432
gen_ota_img_cmd += ["--sk", self.args["sk"]]
430433

431-
logging.info("ota image generating: {}".format(" ".join(gen_ota_img_cmd)))
434+
log.info("ota image generating: %s", shlex.join(gen_ota_img_cmd))
432435
process = subprocess.Popen(gen_ota_img_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
433436
while process.poll() is None:
434437
line = process.stdout.readline().decode('utf-8').rstrip()
435438
if line:
436-
logging.info(line)
439+
log.info(line)
437440

438441
fw_ota_images = self.find_file(self.work_dir, r'^FW_OTA.+\.hash$')
439442
if not fw_ota_images or 0 == len(fw_ota_images):
@@ -542,7 +545,7 @@ def exe_prog_cmd(flashtool_exe, mfd_addr, flashtool_path):
542545

543546
if mfd_addr and self.args["mfd_str"]:
544547
if self.args["key"] and not self.args["iv"]:
545-
logging.warning("mfd file has no iv, do NOT program mfd key.")
548+
log.warning("mfd file has no iv, do NOT program mfd key.")
546549
else:
547550
prog_cmd += ["--dac_key", self.args["key"]]
548551
prog_cmd += ["--dac_iv", self.args["iv"]]
@@ -552,12 +555,12 @@ def exe_prog_cmd(flashtool_exe, mfd_addr, flashtool_path):
552555
if self.option.erase:
553556
prog_cmd += ["--erase"]
554557

555-
logging.info("firmware programming: {}".format(" ".join(prog_cmd)))
558+
log.info("firmware programming: %s", shlex.join(prog_cmd))
556559
process = subprocess.Popen(prog_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
557560
while process.poll() is None:
558561
line = process.stdout.readline().decode('utf-8').rstrip()
559562
if line:
560-
logging.info(line)
563+
log.info(line)
561564

562565
flashtool_path, flashtool_exe = get_tools()
563566
self.args["pt"] = os.path.join(os.getcwd(), str(self.args["pt"]))
@@ -595,10 +598,10 @@ def get_tools():
595598
raise Exception("Do NOT support {} operating system to program firmware.".format(sys.platform))
596599

597600
if not os.path.exists(flashtool_exe) or not os.path.exists(fw_proc_exe):
598-
logging.fatal('*' * 80)
599-
logging.error("Expecting tools as below:")
600-
logging.error(fw_proc_exe)
601-
logging.error(flashtool_exe)
601+
log.fatal("*" * 80)
602+
log.error("Expecting tools as below:")
603+
log.error(fw_proc_exe)
604+
log.error(flashtool_exe)
602605
raise Exception("Flashtool or fw tool doesn't contain in SDK")
603606

604607
return fw_proc_exe, flashtool_exe
@@ -670,12 +673,12 @@ def exe_proc_cmd(fw_proc_exe):
670673
"--edata", "0x80,{};0x7c,{};0xfc,{}".format(self.args["key"], lock0, lock1)
671674
]
672675

673-
logging.info("firmware process command: {}".format(" ".join(fw_proc_cmd)))
676+
log.info("firmware process command: %s", shlex.join(fw_proc_cmd))
674677
process = subprocess.Popen(fw_proc_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
675678
while process.poll() is None:
676679
line = process.stdout.readline().decode('utf-8').rstrip()
677680
if line:
678-
logging.info(line)
681+
log.info(line)
679682

680683
os.system("mkdir -p {}/ota_images".format(self.work_dir))
681684
os.system("mv {}/*.ota {}/ota_images/".format(self.work_dir, self.work_dir))
@@ -701,12 +704,12 @@ def exe_prog_cmd(flashtool_exe):
701704
"--port", self.args["port"],
702705
]
703706

704-
logging.info("firwmare programming: {}".format(" ".join(prog_cmd)))
707+
log.info("firwmare programming: %s", shlex.join(prog_cmd))
705708
process = subprocess.Popen(prog_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
706709
while process.poll() is None:
707710
line = process.stdout.readline().decode('utf-8').rstrip()
708711
if line:
709-
logging.info(line)
712+
log.info(line)
710713

711714
fw_proc_exe, flashtool_exe = get_tools()
712715
os.chdir(self.work_dir)

0 commit comments

Comments
 (0)