Skip to content

Commit

Permalink
feat(tools): Enforce utf-8 encoding with open() function
Browse files Browse the repository at this point in the history
  • Loading branch information
Marek Fiala authored and espressif-bot committed Dec 27, 2024
1 parent 305f1c1 commit 2c814ef
Show file tree
Hide file tree
Showing 40 changed files with 115 additions and 124 deletions.
10 changes: 5 additions & 5 deletions components/efuse/efuse_table_gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,13 +126,13 @@ def verify_duplicate_name(self):
field_name = p.field_name + p.group
if field_name != '' and len(duplicates.intersection([field_name])) != 0:
fl_error = True
print('Field at %s, %s, %s, %s have dublicate field_name' %
print('Field at %s, %s, %s, %s have duplicate field_name' %
(p.field_name, p.efuse_block, p.bit_start, p.bit_count))
if fl_error is True:
raise InputError('Field names must be unique')

def check_struct_field_name(self):
# check that stuctured fields have a root field
# check that structured fields have a root field
for p in self:
if '.' in p.field_name:
name = ''
Expand Down Expand Up @@ -454,7 +454,7 @@ def process_input_file(file, type_table):

def ckeck_md5_in_file(md5, filename):
if os.path.exists(filename):
with open(filename, 'r') as f:
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
if md5 in line:
return True
Expand All @@ -478,12 +478,12 @@ def create_output_files(name, output_table, debug):
if ckeck_md5_in_file(output_table.md5_digest_table, file_c_path) is False:
status('Creating efuse *.h file ' + file_h_path + ' ...')
output = output_table.to_header(file_name)
with open(file_h_path, 'w') as f:
with open(file_h_path, 'w', encoding='utf-8') as f:
f.write(output)

status('Creating efuse *.c file ' + file_c_path + ' ...')
output = output_table.to_c_file(file_name, debug)
with open(file_c_path, 'w') as f:
with open(file_c_path, 'w', encoding='utf-8') as f:
f.write(output)
else:
print('Source files do not require updating correspond to csv file.')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def generate_tests_cases(target): # type: (str) -> None

messages = [random.randrange(0, 1 << max_key_size) for x in range(NUM_MESSAGES)]

with open('digital_signature_test_cases.h', 'w') as f:
with open('digital_signature_test_cases.h', 'w', encoding='utf-8') as f:
f.write('/*\n')
year = datetime.datetime.now().year
f.write(' * SPDX-FileCopyrightText: {year} Espressif Systems (Shanghai) CO LTD\n'.format(year=year))
Expand Down
4 changes: 2 additions & 2 deletions components/esp_system/check_system_init_priorities.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def main() -> None:
glob_iter = glob.glob(os.path.join(idf_path, 'components', '**', f'*.{extension}'), recursive=True)
source_files_iters.append(glob_iter)
for filename in itertools.chain(*source_files_iters):
with open(filename, 'r') as f_obj:
with open(filename, 'r', encoding='utf-8') as f_obj:
file_contents = f_obj.read()
if ESP_SYSTEM_INIT_FN_STR not in file_contents:
continue
Expand Down Expand Up @@ -88,7 +88,7 @@ def sort_key(entry: StartupEntry) -> typing.Tuple[str, int, str]:
# 3. Load startup entries list from STARTUP_ENTRIES_FILE, removing comments and empty lines
#
startup_entries_expected_lines = []
with open(os.path.join(idf_path, STARTUP_ENTRIES_FILE), 'r') as startup_entries_expected_file:
with open(os.path.join(idf_path, STARTUP_ENTRIES_FILE), 'r', encoding='utf-8') as startup_entries_expected_file:
for line in startup_entries_expected_file:
if line.startswith('#') or len(line.strip()) == 0:
continue
Expand Down
3 changes: 1 addition & 2 deletions components/espcoredump/espcoredump.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
#
# SPDX-License-Identifier: Apache-2.0
#

import json
import logging
import os.path
Expand All @@ -26,7 +25,7 @@ def get_prefix_map_gdbinit_path(prog_path): # type: (str) -> Any
logging.warning('%s does not exist. Please build the app with "idf.py build"', desc_path)
return ''

with open(desc_path, 'r') as f:
with open(desc_path, 'r', encoding='utf-8') as f:
project_desc = json.load(f)

return project_desc.get('debug_prefix_map_gdbinit')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ def write_to_c_header(init_key: bytes, k1: bytes, k2_info: bytes, k1_encrypted_3
test_data_xts_aes_128: list, k1_encrypted_64: list,
xts_test_data_xts_aes_256: list, pubx: bytes,
puby: bytes, k1_G_0: bytes, k1_G_1: bytes) -> None:
with open('key_manager_test_cases.h', 'w') as file:
with open('key_manager_test_cases.h', 'w', encoding='utf-8') as file:
header_content = """#include <stdint.h>
#define TEST_COUNT 5
Expand Down
2 changes: 1 addition & 1 deletion components/partition_table/gen_esp32part.py
Original file line number Diff line number Diff line change
Expand Up @@ -676,7 +676,7 @@ def main():

if input_is_binary:
output = table.to_csv()
with sys.stdout if args.output == '-' else open(args.output, 'w') as f:
with sys.stdout if args.output == '-' else open(args.output, 'w', encoding='utf-8') as f:
f.write(output)
else:
output = table.to_binary()
Expand Down
3 changes: 1 addition & 2 deletions components/partition_table/gen_extra_subtypes_inc.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
#!/usr/bin/env python
# SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
# SPDX-License-Identifier: Apache-2.0

import argparse


def gen_header_file(path: str, subtypes: str) -> None:
HDR_MESSAGE = '/* Automatically generated file. DO NOT EDIT. */\n\n'
PARTTOOL_USAGE = 'If you want to use parttool.py manually, please use the following as an extra argument:'
with open(path, 'w') as f:
with open(path, 'w', encoding='utf-8') as f:
f.write(HDR_MESSAGE)
if subtypes:
f.write('/*\n\t' + PARTTOOL_USAGE + '\n\t')
Expand Down
2 changes: 1 addition & 1 deletion components/partition_table/parttool.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def parse_esptool_args(esptool_args):
partition_table = gen.PartitionTable.from_binary(f.read())

if partition_table is None:
with open(partition_table_file, 'r') as f:
with open(partition_table_file, 'r', encoding='utf-8') as f:
f.seek(0)
partition_table = gen.PartitionTable.from_csv(f.read())
else:
Expand Down
8 changes: 4 additions & 4 deletions components/ulp/esp32ulp_mapgen.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
#!/usr/bin/env python
# esp32ulp_mapgen utility converts a symbol list provided by nm into an export script
# for the linker and a header file.
#
# SPDX-FileCopyrightText: 2016-2024 Espressif Systems (Shanghai) CO LTD
# SPDX-License-Identifier: Apache-2.0
#
# esp32ulp_mapgen utility converts a symbol list provided by nm into an export script
# for the linker and a header file.
import argparse
import os
import textwrap
Expand Down Expand Up @@ -64,7 +64,7 @@ def main() -> None:

args = parser.parse_args()

with open(args.outputfile + '.h', 'w') as f_h, open(args.outputfile + '.ld', 'w') as f_ld:
with open(args.outputfile + '.h', 'w', encoding='utf-8') as f_h, open(args.outputfile + '.ld', 'w', encoding='utf-8') as f_ld:
gen_ld_h_from_sym(args.symfile, f_ld, f_h, int(args.base_addr, 0))


Expand Down
2 changes: 1 addition & 1 deletion conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ def real_func(item: str, value: float, target: str) -> None:
"""

def _find_perf_item(operator: str, path: str) -> float:
with open(path) as f:
with open(path, encoding='utf-8') as f:
data = f.read()
match = re.search(fr'#define\s+IDF_PERFORMANCE_{operator}_{item.upper()}\s+([\d.]+)', data)
return float(match.group(1)) # type: ignore
Expand Down
3 changes: 1 addition & 2 deletions examples/protocols/esp_local_ctrl/pytest_esp_local_ctrl.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# SPDX-FileCopyrightText: 2022-2023 Espressif Systems (Shanghai) CO LTD
# SPDX-License-Identifier: Unlicense OR CC0-1.0

import logging
import os
import re
Expand All @@ -22,7 +21,7 @@ def get_sdk_path() -> str:
class CustomProcess(object):
def __init__(self, cmd: str, logfile: str, verbose:bool =True) -> None:
self.verbose = verbose
self.f = open(logfile, 'w')
self.f = open(logfile, 'w', encoding='utf-8')
if self.verbose:
logging.info('Starting {} > {}'.format(cmd, self.f.name))
self.pexpect_proc = pexpect.spawn(cmd, timeout=60, logfile=self.f, encoding='utf-8', codec_errors='ignore')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def test_examples_protocol_https_server_simple(dut: Dut) -> None:
ssl_context.check_hostname = False
ssl_context.load_verify_locations(cadata=server_cert_pem)

with open(CLIENT_CERT_FILE, 'w') as cert, open(CLIENT_KEY_FILE, 'w') as key:
with open(CLIENT_CERT_FILE, 'w', encoding='utf-8') as cert, open(CLIENT_KEY_FILE, 'w', encoding='utf-8') as key:
cert.write(client_cert_pem)
key.write(client_key_pem)

Expand Down
7 changes: 4 additions & 3 deletions examples/protocols/mqtt/ssl/pytest_mqtt_ssl.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
# SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
# SPDX-FileCopyrightText: 2022-2024 Espressif Systems (Shanghai) CO LTD
# SPDX-License-Identifier: Unlicense OR CC0-1.0
import logging
import os
import re
import ssl
import sys
from threading import Event, Thread
from threading import Event
from threading import Thread

import paho.mqtt.client as mqtt
import pexpect
Expand Down Expand Up @@ -47,7 +48,7 @@ def on_message(client, userdata, msg): # type: (mqtt.Client, tuple, mqtt.client
event_client_received_binary.set()
return
recv_binary = binary + '.received'
with open(recv_binary, 'w') as fw:
with open(recv_binary, 'w', encoding='utf-8') as fw:
fw.write(msg.payload)
raise ValueError('Received binary (saved as: {}) does not match the original file: {}'.format(recv_binary, binary))

Expand Down
2 changes: 1 addition & 1 deletion examples/security/hmac_soft_jtag/jtag_example_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def generate_token_data(hmac_key_file: str, output_file: Optional[str] = None) -
with open(output_file, 'wb') as out_file:
out_file.write(token_data)
elif output_file.endswith('.hex'):
with open(output_file, 'w') as out_file:
with open(output_file, 'w', encoding='utf-8') as out_file:
out_file.write(token_hex)
else:
print(f'Unsupported file format for output file: {output_file}')
Expand Down
2 changes: 1 addition & 1 deletion examples/security/hmac_soft_jtag/pytest_jtag_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@


def run_gdb_test(dut: IdfDut) -> None:
with open(os.path.join(dut.logdir, 'ocd.txt'), 'w') as ocd_log, \
with open(os.path.join(dut.logdir, 'ocd.txt'), 'w', encoding='utf-8') as ocd_log, \
pexpect.spawn(f'openocd -f board/esp32c6-builtin.cfg',
timeout=60,
logfile=ocd_log,
Expand Down
4 changes: 2 additions & 2 deletions examples/storage/semihost_vfs/pytest_semihost_vfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,15 @@ def test_semihost_vfs(dut: IdfDut) -> None:
dut.expect_exact('example: Wrote 2776 bytes')
dut.expect_exact('====================== HOST DATA START =========================')

with open(HOST_FILE_PATH) as f:
with open(HOST_FILE_PATH, encoding='utf-8') as f:
for line in f:
if line.strip():
dut.expect_exact(line.strip())

dut.expect_exact('====================== HOST DATA END =========================')
dut.expect_exact('example: Read 6121 bytes')

with open(os.path.join(TEMP_DIR, 'esp32_stdout.txt')) as f:
with open(os.path.join(TEMP_DIR, 'esp32_stdout.txt'), encoding='utf-8') as f:

def expected_content() -> t.Iterator[str]:
yield 'example: Switched to semihosted stdout'
Expand Down
2 changes: 1 addition & 1 deletion examples/storage/spiffsgen/pytest_spiffsgen_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def test_spiffsgen_example(dut: Dut) -> None:
base_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'spiffs_image')

# Expect hello.txt is read successfully
with open(os.path.join(base_dir, 'hello.txt'), 'r') as hello_txt:
with open(os.path.join(base_dir, 'hello.txt'), 'r', encoding='utf-8') as hello_txt:
dut.expect('Read from hello.txt: ' + hello_txt.read().rstrip())

# Expect alice.txt MD5 hash is computed accurately
Expand Down
4 changes: 2 additions & 2 deletions examples/system/app_trace_basic/pytest_app_trace_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def test_examples_app_trace_basic(dut: IdfDut, openocd: OpenOcd) -> None:
assert 'Targets connected.' in dut.openocd.write('esp apptrace start file://apptrace.log 0 2000 3 0 0')
apptrace_wait_stop(dut.openocd)

with open(openocd._logfile) as oocd_log: # pylint: disable=protected-access
with open(openocd._logfile, encoding='utf-8') as oocd_log: # pylint: disable=protected-access
cores = 1 if dut.app.sdkconfig.get('ESP_SYSTEM_SINGLE_CORE_MODE') is True else 2
params_str = 'App trace params: from {} cores,'.format(cores)
found = False
Expand All @@ -59,7 +59,7 @@ def test_examples_app_trace_basic(dut: IdfDut, openocd: OpenOcd) -> None:
'"{}" could not be found in {}'.format(params_str, openocd._logfile) # pylint: disable=protected-access
)

with open('apptrace.log') as apptrace_log:
with open('apptrace.log', encoding='utf-8') as apptrace_log:
for sample_num in range(1, 51):
log_str = 'Apptrace test data[{}]:{}'.format(sample_num, sample_num * sample_num)
found = False
Expand Down
14 changes: 7 additions & 7 deletions examples/system/app_trace_to_plot/read_trace.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# SPDX-FileCopyrightText: 2023 Espressif Systems (Shanghai) CO LTD
# SPDX-FileCopyrightText: 2023-2024 Espressif Systems (Shanghai) CO LTD
# SPDX-License-Identifier: Apache-2.0

import argparse
import datetime
import json
Expand All @@ -9,7 +8,8 @@
import sys
from enum import Enum
from functools import partial
from typing import Any, List
from typing import Any
from typing import List

try:
import espytrace.apptrace
Expand Down Expand Up @@ -47,7 +47,7 @@ class States(Enum):
html.Div([
html.H2('Telemetry Data'),
html.Div(id='live-update-data'),
dcc.Graph(id='live-update-graph', style={'height': 800}), # Height of the plotting area setted to 800px
dcc.Graph(id='live-update-graph', style={'height': 800}), # Height of the plotting area set to 800px
dcc.Interval(
id='interval-component',
interval=5 * 100, # Graph will be updated every 500 ms
Expand All @@ -57,7 +57,7 @@ class States(Enum):
)


# Multiple components can update everytime interval gets fired.
# Multiple components can update every time interval gets fired.
@app.callback(Output('live-update-graph', 'figure'),
Input('interval-component', 'n_intervals'))
def update_graph_live(_n: Any) -> Any: # pylint: disable=undefined-argument
Expand Down Expand Up @@ -162,13 +162,13 @@ def handle(self) -> None:


def read_json(file_path: str) -> Any:
with open(file_path, 'r') as f:
with open(file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
return data


def save_data(file_path: str) -> None:
with open(file_path, 'w') as f:
with open(file_path, 'w', encoding='utf-8') as f:
f.writelines(output_lines)


Expand Down
2 changes: 1 addition & 1 deletion examples/system/efuse/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def get_efuse_offset(self, efuse_name: str) -> Any:
with tempfile.NamedTemporaryFile(suffix='.json') as temp_file:
temp_file_path = temp_file.name
espefuse.main(f'--virt -c {self.target} summary --format json --file {temp_file_path}'.split())
with open(temp_file_path, 'r') as file:
with open(temp_file_path, 'r', encoding='utf-8') as file:
efuse_summary = json.load(file)
if efuse_name in efuse_summary:
data = efuse_summary[efuse_name]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@


def create_file(server_file: str, file_data: str) -> None:
with open(server_file, 'w+') as file:
with open(server_file, 'w+', encoding='utf-8') as file:
file.write(file_data)


Expand Down
4 changes: 2 additions & 2 deletions examples/system/ota/partitions_ota/pytest_partitions_ota.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,13 +151,13 @@ def start_https_server(ota_image_dir: str, server_ip: str, server_port: int, ser

if server_file is None:
server_file = os.path.join(ota_image_dir, 'server_cert.pem')
cert_file_handle = open(server_file, 'w+')
cert_file_handle = open(server_file, 'w+', encoding='utf-8')
cert_file_handle.write(server_cert)
cert_file_handle.close()

if key_file is None:
key_file = os.path.join(ota_image_dir, 'server_key.pem')
key_file_handle = open('server_key.pem', 'w+')
key_file_handle = open('server_key.pem', 'w+', encoding='utf-8')
key_file_handle.write(server_key)
key_file_handle.close()

Expand Down
8 changes: 4 additions & 4 deletions examples/system/ota/simple_ota_example/pytest_simple_ota.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,13 +80,13 @@ def start_https_server(ota_image_dir: str, server_ip: str, server_port: int, ser

if server_file is None:
server_file = os.path.join(ota_image_dir, 'server_cert.pem')
cert_file_handle = open(server_file, 'w+')
cert_file_handle = open(server_file, 'w+', encoding='utf-8')
cert_file_handle.write(server_cert)
cert_file_handle.close()

if key_file is None:
key_file = os.path.join(ota_image_dir, 'server_key.pem')
key_file_handle = open('server_key.pem', 'w+')
key_file_handle = open('server_key.pem', 'w+', encoding='utf-8')
key_file_handle.write(server_key)
key_file_handle.close()

Expand All @@ -102,12 +102,12 @@ def start_https_server(ota_image_dir: str, server_ip: str, server_port: int, ser
def start_tls1_3_server(ota_image_dir: str, server_port: int) -> subprocess.Popen:
os.chdir(ota_image_dir)
server_file = os.path.join(ota_image_dir, 'server_cert.pem')
cert_file_handle = open(server_file, 'w+')
cert_file_handle = open(server_file, 'w+', encoding='utf-8')
cert_file_handle.write(server_cert)
cert_file_handle.close()

key_file = os.path.join(ota_image_dir, 'server_key.pem')
key_file_handle = open('server_key.pem', 'w+')
key_file_handle = open('server_key.pem', 'w+', encoding='utf-8')
key_file_handle.write(server_key)
key_file_handle.close()

Expand Down
2 changes: 1 addition & 1 deletion examples/system/sysview_tracing/pytest_sysview_tracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def dut_expect_task_event() -> None:

dut.gdb.write('c', non_blocking=True)
time.sleep(1) # to avoid EOF file error
with open(dut.gdb._logfile) as fr: # pylint: disable=protected-access
with open(dut.gdb._logfile, encoding='utf-8') as fr: # pylint: disable=protected-access
gdb_pexpect_proc = pexpect.fdpexpect.fdspawn(fr.fileno())
gdb_pexpect_proc.expect('Thread 2 "main" hit Breakpoint 1, app_main ()')

Expand Down
Loading

0 comments on commit 2c814ef

Please sign in to comment.