1
0
Fork 0
mirror of https://github.com/anrieff/libcpuid synced 2025-06-07 00:51:40 +00:00

Use f-strings in Python scripts

This commit is contained in:
The Tumultuous Unicorn Of Darkness 2025-04-28 21:08:24 +02:00
parent c818294b89
commit aeb788c723
No known key found for this signature in database
GPG key ID: 1E55EE2EFF18BC1A
3 changed files with 30 additions and 30 deletions

View file

@ -9,7 +9,7 @@ git_root_dir = os.popen("git rev-parse --show-toplevel").read().splitlines()
err = 0
def getEnumElements(enumName):
f = open("%s/libcpuid.h" % args.root_dir, "r")
f = open(f"{args.root_dir}/libcpuid.h", "r")
l = []
on = False
rexp = re.compile(r'^\s*([A-Z0-9_]+)(\s*=\s*[A-Z0-9_]+)?\s*,.*$')
@ -28,7 +28,7 @@ def getEnumElements(enumName):
return []
def getConstant(constantName):
f = open("%s/libcpuid_constants.h" % args.root_dir, "r")
f = open(f"{args.root_dir}/libcpuid_constants.h", "r")
value = 0
for line in f:
items = line.strip().split()
@ -38,10 +38,10 @@ def getConstant(constantName):
return value
def checkEnumSize(enumName, constantName):
print("Checking enum `%s':" % enumName, end=' ')
print(f"Checking enum `{enumName}':", end=' ')
count = len(getEnumElements(enumName)) - 1
themax = getConstant(constantName)
print("%d elements; max size (%s=%d)..." % (count, constantName, themax), end=' ')
print(f"{count} elements; max size ({constantName}={themax})...", end=' ')
if count > themax:
err += 1
print("FAILED")
@ -70,7 +70,7 @@ checkEnumSize("cpu_sgx_feature_t", "SGX_FLAGS_MAX")
rexp = re.compile('.*{ CPU_FEATURE_([^,]+), "([^"]+)".*}.*')
print("Finding features:")
for fn in glob.glob("%s/*.c" % args.root_dir):
for fn in glob.glob(f"{args.root_dir}/*.c"):
f = open(fn, "rt")
line = 1
nfeat = 0
@ -81,16 +81,16 @@ for fn in glob.glob("%s/*.c" % args.root_dir):
assert len(res) == 1, "Too many matches"
if res[0][0].lower() != res[0][1]:
err += 1
print("..Mismatch - %s:%d - `%s' vs `%s'" % (os.path.basename(fn), line, res[0][0], res[0][1]))
print(f"..Mismatch - {os.path.basename(fn)}:{line} - `{res[0][0]}' vs `{res[0][1]}'")
line += 1
if nfeat:
print(" %s: %d features described" % (os.path.basename(fn), nfeat))
print(f" {os.path.basename(fn)}: {nfeat} features described")
f.close()
# Check whether all features are converted by cpu_feature_str():
allf = []
f = open("%s/libcpuid.h" % args.root_dir, "rt")
f = open(f"{args.root_dir}/libcpuid.h", "rt")
rexp = re.compile('\t(CPU_FEATURE_[^, ]+).*')
for s in f.readlines():
if rexp.match(s):
@ -100,22 +100,22 @@ f.close()
impf = []
rexp = re.compile('\t+{ (CPU_FEATURE_[^,]+).*')
f = open("%s/cpuid_main.c" % args.root_dir, "rt")
f = open(f"{args.root_dir}/cpuid_main.c", "rt")
for s in f.readlines():
if rexp.match(s):
entry = rexp.findall(s)[0]
if entry in impf:
err += 1
print("cpu_feature_str(): duplicate entry: %s" % entry)
print(f"cpu_feature_str(): duplicate entry: {entry}")
impf.append(entry)
f.close()
print("Found %d total features and %d named features" % (len(allf), len(impf)))
print(f"Found {len(allf)} total features and {len(impf)} named features")
for feature in allf:
if not feature in impf:
err += 1
print("cpu_feature_str(): don't have entry for %s" % feature)
print(f"cpu_feature_str(): don't have entry for {feature}")
# Check whether all features have detection code:
print("Checking whether all features have detection code...", end=' ')
@ -127,7 +127,7 @@ rexp1 = re.compile(r'.*\[(CPU_FEATURE_[^ \]]+)\]\s*=\s*{.*') # e.g. "[CPU_FEATUR
rexp2 = re.compile(r'.*(CPU_FEATURE_[^ ,]+),\s*FEATURE_LEVEL_ARM_.*') # e.g. "set_feature_status(data, ext_status, (mte_frac == 0b0000), CPU_FEATURE_MTE_ASYNC, FEATURE_LEVEL_ARM_V8_5_A, -1);"
rexp3 = re.compile(r'.*(CPU_FEATURE_[^ }]+).*') # e.g. "{ 28, CPU_FEATURE_HT },"
for fn in glob.glob("%s/*.c" % args.root_dir):
for fn in glob.glob(f"{args.root_dir}/*.c"):
f = open(fn, "rt")
files_code[fn] = []
for s in f.readlines():
@ -157,13 +157,13 @@ for feature in allf:
print("FAILED:")
firstError = False
err += 1
print("..No detection code for %s" % feature)
print(f"..No detection code for {feature}")
if len(matching_files) > 1 and feature not in features_whitelist:
if firstError:
print("FAILED:")
firstError = False
err += 1
print("..Conflicting detection code for %s in files %s" % (feature, " and ".join(matching_files)))
print(f"..Conflicting detection code for {feature} in files {' and '.join(matching_files)}")
if firstError:
print("All OK.")
@ -178,7 +178,7 @@ definitions = 0
match_entry_fields = 11 # this number needs to change if the definition of match_entry_t ever changes
codename_str_max = 64-1 # this number needs to change if the value of CODENAME_STR_MAX ever changes
common_cache_sizes = ["8", "16", "32", "64", "128", "256", "512", "1024", "2048", "3072", "4096", "6144", "8192", "12288", "16384"]
for fn in glob.glob("%s/*.c" % args.root_dir):
for fn in glob.glob(f"{args.root_dir}/*.c"):
bfn = os.path.basename(fn)
nline = 0
f = open(fn, "rt")
@ -202,23 +202,23 @@ for fn in glob.glob("%s/*.c" % args.root_dir):
s = parts[match_entry_fields-1].strip()
if s[0] != '"' or s[-1] != '"':
err += 1
print("..Warning, %s:%d - cannot correctly handle the cpu codename" % (bfn, nline))
print(f"..Warning, {bfn}:{nline} - cannot correctly handle the cpu codename")
allok = False
continue
s = s[1:-1]
if len(s) > codename_str_max:
err += 1
print("..%s:%d - codename (%s) is longer than %d characters!" % (bfn, nline, s, codename_str_max))
print(f"..{bfn}:{nline} - codename ({s}) is longer than {codename_str_max} characters!")
allok = False
if cache_exp.match(s):
cache_size = cache_exp.findall(s)[0][1:-1]
if not cache_size in common_cache_sizes:
err += 1
print("..Warning, %s:%d - suspicious cache size in codename [%s] (%s)" % (bfn, nline, s, cache_size))
print(f"..Warning, {bfn}:{nline} - suspicious cache size in codename [{s}] ({cache_size})")
allok = False
if cdefs:
definitions += 1
print(" %s: %d processor definitions," % (bfn, cdefs), end=' ')
print(f" {bfn}: {cdefs} processor definitions,", end=' ')
if allok:
print("all OK")
else:

View file

@ -49,7 +49,7 @@ def readResultFile():
if field in numeric:
value = s[s.find(":")+1:].strip()
if not rexp.match(value):
raise "Bad format of value: [%s]" % s
raise f"Bad format of value: [{s}]"
repdata.append(rexp.findall(value)[0])
if "CPU Info for type" in field:
repdata.append(delimiter)

View file

@ -34,8 +34,8 @@ def make_tempname(prefix):
return prefix
def fmt_error(err):
pfix = " %s: " % err[0]
return "%sexpected `%s'\n%sgot `%s'" % (pfix, err[1], " "*len(pfix), err[2])
pfix = f" {err[0]}: "
return "{} expected `{}'\n{} got `{}'".format(pfix, err[1], ' '*len(pfix), err[2])
def fixFile(filename, input_lines, output_lines):
f = open(filename, "wt")
@ -50,14 +50,14 @@ def do_test(inp, expected_out, binary, test_file_name, num_cpu_type):
f = open(fninp, "wt")
f.writelines([s + "\n" for s in inp])
f.close()
architecture = os.popen("%s --load=%s --architecture" % (binary, fninp)).read().splitlines()[-1]
architecture = os.popen(f"{binary} --load={fninp} --architecture").read().splitlines()[-1]
if architecture == "x86":
fields = fields_x86
elif architecture == "ARM":
fields = fields_arm
else:
fields = []
cmd = "%s --load=%s --outfile=%s %s" % (binary, fninp, fnoutp, " ".join(["--" + s for s in fields]))
cmd = f"{binary} --load={fninp} --outfile={fnoutp} {' '.join(['--' + s for s in fields])}"
os.system(cmd)
os.unlink(fninp)
real_out = []
@ -77,7 +77,7 @@ def do_test(inp, expected_out, binary, test_file_name, num_cpu_type):
fixFile(test_file_name, inp, real_out_delim)
return "Number of records, fixed."
else:
return "Unexpected number of records returned\n - expected length %d\n - real length %d\n - %d fields" % (len(expected_out), len(real_out), len(fields) * num_cpu_type)
return "Unexpected number of records returned\n - expected length {}\n - real length {}\n - {} fields".format(len(expected_out), len(real_out), len(fields) * num_cpu_type)
err_fields = []
for i in range(len(real_out)):
if real_out[i] != expected_out[i]:
@ -89,7 +89,7 @@ def do_test(inp, expected_out, binary, test_file_name, num_cpu_type):
fixFile(test_file_name, inp, real_out_delim)
return "Mismatch, fixed."
else:
return "Mismatch in fields:\n%s" % "\n".join([fmt_error(err) for err in err_fields])
return "Mismatch in fields:\n{}".format('\n'.join([fmt_error(err) for err in err_fields]))
def is_regular_file(filename):
try:
@ -142,7 +142,7 @@ filelist = []
for input_test_file in args.input_test_files:
if Path(input_test_file).is_dir():
# gather all *.test files from subdirs amd, intel and cie:
for dirpath, dirnames, filenames in Path(input_test_file).walk():
for dirpath, dirnames, filenames in os.walk(input_test_file):
filelist += [PurePath(dirpath).joinpath(fn) for fn in filenames if Path(fn).suffixes[0] == ".test"]
else:
filelist.append(input_test_file)
@ -161,7 +161,7 @@ for test_file_name_raw in filelist:
if test_file_name.suffixes[1] == ".xz":
f = lzma.open(test_file_name, "rt")
else:
print("Test [%s]: skipped because %s is not supported" % (test_file_name.name, "".join(test_file_name.suffixes[1:])))
print(f"Test [{test_file_name.name}]: skipped because {''.join(test_file_name.suffixes[1:])} is not supported")
continue
else:
# Plain text file
@ -180,7 +180,7 @@ for test_file_name_raw in filelist:
f.close()
#codename = current_output[len(current_output) - 2]
result = do_test(current_input, current_output, args.cpuid_tool, test_file_name, num_cpu_type)
print("Test [%s]: %s" % (test_file_name.name, result))
print(f"Test [{test_file_name.name}]: {result}")
if result != "OK":
errors = True
build_output = False