Page MenuHomePhabricator

D13201.diff
No OneTemporary

D13201.diff

diff --git a/cmake/utils/gen-ninja-deps.py b/cmake/utils/gen-ninja-deps.py
--- a/cmake/utils/gen-ninja-deps.py
+++ b/cmake/utils/gen-ninja-deps.py
@@ -164,7 +164,7 @@
if len(d) == 0:
continue
- str = t.decode() + ": \\\n "
+ str = f"{t.decode()}: \\\n "
str += " \\\n ".join(sorted(map((lambda x: x.decode()), d)))
print(str)
diff --git a/cmake/utils/junit-reports-merge.py b/cmake/utils/junit-reports-merge.py
--- a/cmake/utils/junit-reports-merge.py
+++ b/cmake/utils/junit-reports-merge.py
@@ -14,7 +14,7 @@
def __init__(self, name, report_dir):
self.name = name
self.test_cases = {}
- self.report_file = os.path.join(report_dir, '{}.xml'.format(self.name))
+ self.report_file = os.path.join(report_dir, f'{self.name}.xml')
def add_test_case(self, test_case):
self.test_cases[test_case.test_id] = test_case
@@ -69,14 +69,14 @@
def __getattr__(self, attribute):
if attribute == 'test_id':
- return self.classname + '/' + self.name
+ return f"{self.classname}/{self.name}"
return self.node.attrib[attribute]
class Lock:
def __init__(self, suite, lock_dir):
- self.lock_file = os.path.join(lock_dir, '{}.lock'.format(suite))
+ self.lock_file = os.path.join(lock_dir, f'{suite}.lock')
def __enter__(self):
os.makedirs(os.path.dirname(self.lock_file), exist_ok=True)
@@ -89,7 +89,7 @@
def main(report_dir, lock_dir, suite, test):
- junit = '{}-{}.xml'.format(suite, test)
+ junit = f'{suite}-{test}.xml'
if not os.path.isfile(junit):
return 0
diff --git a/share/qt/extract_strings_qt.py b/share/qt/extract_strings_qt.py
--- a/share/qt/extract_strings_qt.py
+++ b/share/qt/extract_strings_qt.py
@@ -71,7 +71,7 @@
f = open(OUT_CPP, 'w', encoding="utf8")
f.write('#include <QtGlobal>\n')
-f.write('// Automatically @{} by extract_strings_qt.py\n'.format('generated'))
+f.write("// Automatically @generated by extract_strings_qt.py\n")
f.write("""
#ifdef __GNUC__
#define UNUSED __attribute__((unused))
@@ -80,7 +80,7 @@
#endif
""")
f.write('static const char UNUSED *bitcoin_strings[] = {\n')
-f.write('QT_TRANSLATE_NOOP("bitcoin-abc", "{}"),\n'.format(os.getenv('COPYRIGHT_HOLDERS'),))
+f.write(f"QT_TRANSLATE_NOOP(\"bitcoin-abc\", \"{os.getenv('COPYRIGHT_HOLDERS')}\"),\n")
messages.sort(key=operator.itemgetter(0))
for (msgid, msgstr) in messages:
if msgid != EMPTY:
diff --git a/share/rpcauth/rpcauth.py b/share/rpcauth/rpcauth.py
--- a/share/rpcauth/rpcauth.py
+++ b/share/rpcauth/rpcauth.py
@@ -45,8 +45,8 @@
password_hmac = password_to_hmac(salt, args.password)
print('String to be appended to bitcoin.conf:')
- print('rpcauth={0}:{1}${2}'.format(args.username, salt, password_hmac))
- print('Your password:\n{0}'.format(args.password))
+ print(f'rpcauth={args.username}:{salt}${password_hmac}')
+ print(f'Your password:\n{args.password}')
if __name__ == '__main__':
diff --git a/src/bench/data/convert-raw-to-header.py b/src/bench/data/convert-raw-to-header.py
--- a/src/bench/data/convert-raw-to-header.py
+++ b/src/bench/data/convert-raw-to-header.py
@@ -8,8 +8,8 @@
with open(input_file, "rb") as f:
contents = f.read()
- print("static unsigned const char {}_raw[] = {{".format(test_name))
- print(", ".join(map(lambda x: "0x{:02x}".format(x), contents)))
+ print(f"static unsigned const char {test_name}_raw[] = {{")
+ print(", ".join(map(lambda x: f"0x{x:02x}", contents)))
print("};")
diff --git a/src/test/data/generate_asmap.py b/src/test/data/generate_asmap.py
--- a/src/test/data/generate_asmap.py
+++ b/src/test/data/generate_asmap.py
@@ -11,9 +11,8 @@
with open(output_file, "w", encoding="utf-8") as f:
f.write(
- "static unsigned const char {}_raw[] = {{\n".format(
- Path(input_file).stem))
- f.write(", ".join(map(lambda x: "0x{:02x}".format(x), contents)))
+ f"static unsigned const char {Path(input_file).stem}_raw[] = {{\n")
+ f.write(", ".join(map(lambda x: f"0x{x:02x}", contents)))
f.write("\n};\n")
diff --git a/src/test/data/generate_header.py b/src/test/data/generate_header.py
--- a/src/test/data/generate_header.py
+++ b/src/test/data/generate_header.py
@@ -10,8 +10,8 @@
print("#include <cstdint>\n")
print("namespace json_tests {")
- print("static const uint8_t {}[] = {{".format(test_name))
- print(", ".join(map(lambda x: "0x{:02x}".format(x), contents)))
+ print(f"static const uint8_t {test_name}[] = {{")
+ print(", ".join(map(lambda x: f"0x{x:02x}", contents)))
print("};")
print("};")
diff --git a/test/fuzz/test_runner.py b/test/fuzz/test_runner.py
--- a/test/fuzz/test_runner.py
+++ b/test/fuzz/test_runner.py
@@ -76,7 +76,7 @@
# Read config generated by configure.
config = configparser.ConfigParser()
- configfile = os.path.abspath(os.path.dirname(__file__)) + "/../config.ini"
+ configfile = f"{os.path.abspath(os.path.dirname(__file__))}/../config.ini"
config.read_file(open(configfile, encoding="utf8"))
if not config["components"].getboolean("ENABLE_FUZZ"):
@@ -96,16 +96,14 @@
sys.exit(1)
logging.debug(
- "{} fuzz target(s) found: {}".format(
- len(test_list_all), " ".join(
- sorted(test_list_all))))
+ f"{len(test_list_all)} fuzz target(s) found: {' '.join(sorted(test_list_all))}")
# By default run all
args.target = args.target or test_list_all
test_list_error = list(set(args.target).difference(set(test_list_all)))
if test_list_error:
logging.error(
- "Unknown fuzz targets selected: {}".format(test_list_error))
+ f"Unknown fuzz targets selected: {test_list_error}")
test_list_selection = list(
set(test_list_all).intersection(set(args.target)))
if not test_list_selection:
@@ -114,7 +112,7 @@
for excluded_target in args.exclude.split(","):
if excluded_target not in test_list_selection:
logging.error(
- "Target \"{}\" not found in current target list.".format(excluded_target))
+ f"Target \"{excluded_target}\" not found in current target list.")
continue
test_list_selection.remove(excluded_target)
test_list_selection.sort()
@@ -195,10 +193,10 @@
Run {targets} without input, and outputs the generated corpus seeds to
{seed_dir}.
"""
- logging.info("Generating corpus seeds to {}".format(seed_dir))
+ logging.info(f"Generating corpus seeds to {seed_dir}")
def job(command):
- logging.debug("Running '{}'\n".format(" ".join(command)))
+ logging.debug(f"Running '{' '.join(command)}'\n")
logging.debug("Command '{}' output:\n'{}'\n".format(
' '.join(command),
subprocess.run(command, check=True, stderr=subprocess.PIPE,
@@ -222,7 +220,7 @@
def merge_inputs(*, fuzz_pool, corpus, test_list, test_dir, merge_dir):
logging.info(
- "Merge the inputs in the passed dir into the seed_dir. Passed dir {}".format(merge_dir))
+ f"Merge the inputs in the passed dir into the seed_dir. Passed dir {merge_dir}")
jobs = []
for t in test_list:
args = [
@@ -238,7 +236,7 @@
os.makedirs(os.path.join(merge_dir, t), exist_ok=True)
def job(t, args):
- output = 'Run {} with args {}\n'.format(t, " ".join(args))
+ output = f"Run {t} with args {' '.join(args)}\n"
output += subprocess.run(args,
check=True,
stderr=subprocess.PIPE,
@@ -268,7 +266,7 @@
'--error-exitcode=1'] + args
def job(t, args):
- output = 'Run {} with args {}'.format(t, args)
+ output = f'Run {t} with args {args}'
result = subprocess.run(
args,
stderr=subprocess.PIPE,
diff --git a/test/lint/check-doc.py b/test/lint/check-doc.py
--- a/test/lint/check-doc.py
+++ b/test/lint/check-doc.py
@@ -91,11 +91,11 @@
args_unknown = args_docd - args_used
pp = PrettyPrinter()
- print("Args used : {}".format(len(args_used)))
- print("Args documented : {}".format(len(args_docd)))
- print("Args undocumented: {}".format(len(args_need_doc)))
+ print(f"Args used : {len(args_used)}")
+ print(f"Args documented : {len(args_docd)}")
+ print(f"Args undocumented: {len(args_need_doc)}")
pp.pprint(args_need_doc)
- print("Args unknown : {}".format(len(args_unknown)))
+ print(f"Args unknown : {len(args_unknown)}")
pp.pprint(args_unknown)
diff --git a/test/lint/lint-format-strings.py b/test/lint/lint-format-strings.py
--- a/test/lint/lint-format-strings.py
+++ b/test/lint/lint-format-strings.py
@@ -72,7 +72,7 @@
for line in source_code.split("\n")
if not line.strip().startswith("#")]
return re.findall(
- r"[^a-zA-Z_](?=({}\(.*).*)".format(function_name), " " + " ".join(lines))
+ r"[^a-zA-Z_](?=({}\(.*).*)".format(function_name), f" {' '.join(lines)}")
def normalize(s):
@@ -183,7 +183,7 @@
assert isinstance(function_name, str) and isinstance(
function_call, str) and function_name
remaining = normalize(escape(function_call))
- expected_function_call = "{}(".format(function_name)
+ expected_function_call = f"{function_name}("
assert remaining.startswith(expected_function_call)
parts = [expected_function_call]
remaining = remaining[len(expected_function_call):]
diff --git a/test/lint/lint-python-format.py b/test/lint/lint-python-format.py
--- a/test/lint/lint-python-format.py
+++ b/test/lint/lint-python-format.py
@@ -106,9 +106,9 @@
elif specifier == "r":
return "{!r}"
elif specifier.startswith("-"):
- return "{:" + specifier[1:] + "}"
+ return f"{{:{specifier[1:]}}}"
specifier = specifier.replace("i", "d")
- return "{:" + specifier + "}"
+ return f"{{:{specifier}}}"
(replacement, count) = re.subn(
r"%([.-]?[0-9]*[a-zA-Z])", specifier_sub, replacement, flags=re.MULTILINE)
@@ -117,7 +117,7 @@
# E.g % 42 => .format(42)
# E.g. % (42, "my_string") => .format(42, "my_string")
def single_qualifier_sub(match):
- qualifier = ".format(" + match.group(1).strip()
+ qualifier = f".format({match.group(1).strip()}"
# Where to close the parenthesis if there is a single specifier ?
# It is whether at the end or before the first ',', ']', '}' (if
# enclosed in a function call, a list or a dictionary).
@@ -133,12 +133,12 @@
if c == "]" and opening_count > 0:
opening_count -= 1
continue
- return qualifier[:i] + ")" + qualifier[i:]
- return qualifier + ")"
+ return f"{qualifier[:i]}){qualifier[i:]}"
+ return f"{qualifier})"
def multi_qualifier_sub(match):
# The closing parenthesis is already there as we are replacing a tuple
- qualifier = ".format(" + match.group(1).strip()
+ qualifier = f".format({match.group(1).strip()}"
return qualifier
# There are 2 possible way to write the qualifier:
@@ -273,8 +273,8 @@
for line_number, error in sorted(errors.items(),
key=lambda pair: int(pair[0])):
replacement = build_replacement(error)
- print("({}) {}".format(line_number, error.rstrip()))
- print("=> " + replacement)
+ print(f"({line_number}) {error.rstrip()}")
+ print(f"=> {replacement}")
if __name__ == "__main__":
diff --git a/test/util/bitcoin-util-test.py b/test/util/bitcoin-util-test.py
--- a/test/util/bitcoin-util-test.py
+++ b/test/util/bitcoin-util-test.py
@@ -54,10 +54,10 @@
try:
bctest(testDir, testObj, buildenv)
except Exception:
- logging.info("FAILED: " + testObj["description"])
+ logging.info(f"FAILED: {testObj['description']}")
failed_testcases.append(testObj["description"])
else:
- logging.info("PASSED: " + testObj["description"])
+ logging.info(f"PASSED: {testObj['description']}")
if failed_testcases:
error_message = "FAILED_TESTCASES:\n"
@@ -102,14 +102,14 @@
outputData = open(os.path.join(testDir, outputFn),
encoding="utf8").read()
except OSError:
- logging.error("Output file " + outputFn + " can not be opened")
+ logging.error(f"Output file {outputFn} can not be opened")
raise
if not outputData:
- logging.error("Output data missing for " + outputFn)
+ logging.error(f"Output data missing for {outputFn}")
raise Exception
if not outputType:
logging.error(
- "Output file {} does not have a file extension".format(outputFn))
+ f"Output file {outputFn} does not have a file extension")
raise Exception
# Run the test
@@ -118,7 +118,7 @@
try:
outs = proc.communicate(input=inputData)
except OSError:
- logging.error("OSError, Failed to execute " + execprog)
+ logging.error(f"OSError, Failed to execute {execprog}")
raise
if outputData:
@@ -128,7 +128,7 @@
a_parsed = parse_output(outs[0], outputType)
except Exception as e:
logging.error(
- 'Error parsing command output as {}: {}'.format(outputType, e))
+ f'Error parsing command output as {outputType}: {e}')
raise
try:
b_parsed = parse_output(outputData, outputType)
@@ -138,12 +138,11 @@
raise
# Compare data
if a_parsed != b_parsed:
- logging.error("Output data mismatch for " +
- outputFn + " (format " + outputType + ")")
+ logging.error(f"Output data mismatch for {outputFn} (format {outputType})")
data_mismatch = True
# Compare formatting
if outs[0] != outputData:
- error_message = "Output formatting mismatch for " + outputFn + ":\n"
+ error_message = f"Output formatting mismatch for {outputFn}:\n"
error_message += "".join(difflib.context_diff(outputData.splitlines(True),
outs[0].splitlines(
True),
@@ -159,7 +158,7 @@
if "return_code" in testObj:
wantRC = testObj['return_code']
if proc.returncode != wantRC:
- logging.error("Return code mismatch for " + outputFn)
+ logging.error(f"Return code mismatch for {outputFn}")
raise Exception
if "error_txt" in testObj:
@@ -185,7 +184,7 @@
elif fmt == 'hex': # hex: parse and compare binary data
return bytes.fromhex(a.strip())
else:
- raise NotImplementedError("Don't know how to compare {}".format(fmt))
+ raise NotImplementedError(f"Don't know how to compare {fmt}")
if __name__ == '__main__':

File Metadata

Mime Type
text/plain
Expires
Sat, Apr 26, 11:35 (6 h, 19 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
5573417
Default Alt Text
D13201.diff (15 KB)

Event Timeline