Skip to content

Commit 089c9c5

Browse files
VoltrexKeyvatargos
authored andcommittedMay 3, 2023
build: refactor configure.py
- Explicitly specify the encoding when opening files. - Use f-strings to format strings. - Use `isinstance()` for type checks instead of `type()`. - Use the `with` keyword for resource-allocating operations. - Avoid using multiple statements in a single line. - Remove unnecessary `else` clauses after `return`. - Iterate with the `items()` method of dictionaries when both the key and value are used. - Remove unnecessary parentheses. - Rename unused unpacked variables to `_`, `_1`, etc etc. - Rename the `list` variable to avoid conflict with the global `list()` function. PR-URL: #47667 Reviewed-By: Christian Clauss <[email protected]>
1 parent 6d87355 commit 089c9c5

File tree

1 file changed

+121
-125
lines changed

1 file changed

+121
-125
lines changed
 

‎configure.py

+121-125
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@
5353
valid_mips_fpu = ('fp32', 'fp64', 'fpxx')
5454
valid_mips_float_abi = ('soft', 'hard')
5555
valid_intl_modes = ('none', 'small-icu', 'full-icu', 'system-icu')
56-
with open ('tools/icu/icu_versions.json') as f:
56+
with open('tools/icu/icu_versions.json', encoding='utf-8') as f:
5757
icu_versions = json.load(f)
5858

5959
shareable_builtins = {'cjs_module_lexer/lexer': 'deps/cjs-module-lexer/lexer.js',
@@ -108,7 +108,7 @@
108108
action='store',
109109
dest='dest_cpu',
110110
choices=valid_arch,
111-
help='CPU architecture to build for ({0})'.format(', '.join(valid_arch)))
111+
help=f"CPU architecture to build for ({', '.join(valid_arch)})")
112112

113113
parser.add_argument('--cross-compiling',
114114
action='store_true',
@@ -125,7 +125,7 @@
125125
action='store',
126126
dest='dest_os',
127127
choices=valid_os,
128-
help='operating system to build for ({0})'.format(', '.join(valid_os)))
128+
help=f"operating system to build for ({', '.join(valid_os)})")
129129

130130
parser.add_argument('--error-on-warn',
131131
action='store_true',
@@ -510,39 +510,34 @@
510510
action='store',
511511
dest='arm_float_abi',
512512
choices=valid_arm_float_abi,
513-
help='specifies which floating-point ABI to use ({0}).'.format(
514-
', '.join(valid_arm_float_abi)))
513+
help=f"specifies which floating-point ABI to use ({', '.join(valid_arm_float_abi)}).")
515514

516515
parser.add_argument('--with-arm-fpu',
517516
action='store',
518517
dest='arm_fpu',
519518
choices=valid_arm_fpu,
520-
help='ARM FPU mode ({0}) [default: %(default)s]'.format(
521-
', '.join(valid_arm_fpu)))
519+
help=f"ARM FPU mode ({', '.join(valid_arm_fpu)}) [default: %(default)s]")
522520

523521
parser.add_argument('--with-mips-arch-variant',
524522
action='store',
525523
dest='mips_arch_variant',
526524
default='r2',
527525
choices=valid_mips_arch,
528-
help='MIPS arch variant ({0}) [default: %(default)s]'.format(
529-
', '.join(valid_mips_arch)))
526+
help=f"MIPS arch variant ({', '.join(valid_mips_arch)}) [default: %(default)s]")
530527

531528
parser.add_argument('--with-mips-fpu-mode',
532529
action='store',
533530
dest='mips_fpu_mode',
534531
default='fp32',
535532
choices=valid_mips_fpu,
536-
help='MIPS FPU mode ({0}) [default: %(default)s]'.format(
537-
', '.join(valid_mips_fpu)))
533+
help=f"MIPS FPU mode ({', '.join(valid_mips_fpu)}) [default: %(default)s]")
538534

539535
parser.add_argument('--with-mips-float-abi',
540536
action='store',
541537
dest='mips_float_abi',
542538
default='hard',
543539
choices=valid_mips_float_abi,
544-
help='MIPS floating-point ABI ({0}) [default: %(default)s]'.format(
545-
', '.join(valid_mips_float_abi)))
540+
help=f"MIPS floating-point ABI ({', '.join(valid_mips_float_abi)}) [default: %(default)s]")
546541

547542
parser.add_argument('--use-largepages',
548543
action='store_true',
@@ -569,8 +564,7 @@
569564
dest='with_intl',
570565
default='full-icu',
571566
choices=valid_intl_modes,
572-
help='Intl mode (valid choices: {0}) [default: %(default)s]'.format(
573-
', '.join(valid_intl_modes)))
567+
help=f"Intl mode (valid choices: {', '.join(valid_intl_modes)}) [default: %(default)s]")
574568

575569
intl_optgroup.add_argument('--without-intl',
576570
action='store_const',
@@ -597,7 +591,7 @@
597591
dest='with_icu_source',
598592
help='Intl mode: optional local path to icu/ dir, or path/URL of '
599593
'the icu4c source archive. '
600-
'v%d.x or later recommended.' % icu_versions['minimum_icu'])
594+
f"v{icu_versions['minimum_icu']}.x or later recommended.")
601595

602596
intl_optgroup.add_argument('--with-icu-default-data-dir',
603597
action='store',
@@ -853,25 +847,25 @@
853847

854848
def error(msg):
855849
prefix = '\033[1m\033[31mERROR\033[0m' if os.isatty(1) else 'ERROR'
856-
print('%s: %s' % (prefix, msg))
850+
print(f'{prefix}: {msg}')
857851
sys.exit(1)
858852

859853
def warn(msg):
860854
warn.warned = True
861855
prefix = '\033[1m\033[93mWARNING\033[0m' if os.isatty(1) else 'WARNING'
862-
print('%s: %s' % (prefix, msg))
856+
print(f'{prefix}: {msg}')
863857

864858
# track if warnings occurred
865859
warn.warned = False
866860

867861
def info(msg):
868862
prefix = '\033[1m\033[32mINFO\033[0m' if os.isatty(1) else 'INFO'
869-
print('%s: %s' % (prefix, msg))
863+
print(f'{prefix}: {msg}')
870864

871865
def print_verbose(x):
872866
if not options.verbose:
873867
return
874-
if type(x) is str:
868+
if isinstance(x, str):
875869
print(x)
876870
else:
877871
pprint.pprint(x, indent=2)
@@ -904,9 +898,11 @@ def pkg_config(pkg):
904898
try:
905899
proc = subprocess.Popen(shlex.split(pkg_config) + args,
906900
stdout=subprocess.PIPE)
907-
val = to_utf8(proc.communicate()[0]).strip()
901+
with proc:
902+
val = to_utf8(proc.communicate()[0]).strip()
908903
except OSError as e:
909-
if e.errno != errno.ENOENT: raise e # Unexpected error.
904+
if e.errno != errno.ENOENT:
905+
raise e # Unexpected error.
910906
return (None, None, None, None) # No pkg-config/pkgconf installed.
911907
retval.append(val)
912908
args = ['--silence-errors']
@@ -920,13 +916,14 @@ def try_check_compiler(cc, lang):
920916
except OSError:
921917
return (False, False, '', '')
922918

923-
proc.stdin.write(b'__clang__ __GNUC__ __GNUC_MINOR__ __GNUC_PATCHLEVEL__ '
924-
b'__clang_major__ __clang_minor__ __clang_patchlevel__')
919+
with proc:
920+
proc.stdin.write(b'__clang__ __GNUC__ __GNUC_MINOR__ __GNUC_PATCHLEVEL__ '
921+
b'__clang_major__ __clang_minor__ __clang_patchlevel__')
925922

926-
if sys.platform == 'zos':
927-
values = (to_utf8(proc.communicate()[0]).split('\n')[-2].split() + ['0'] * 7)[0:7]
928-
else:
929-
values = (to_utf8(proc.communicate()[0]).split() + ['0'] * 7)[0:7]
923+
if sys.platform == 'zos':
924+
values = (to_utf8(proc.communicate()[0]).split('\n')[-2].split() + ['0'] * 7)[0:7]
925+
else:
926+
values = (to_utf8(proc.communicate()[0]).split() + ['0'] * 7)[0:7]
930927

931928
is_clang = values[0] == '1'
932929
gcc_version = tuple(map(int, values[1:1+3]))
@@ -952,12 +949,10 @@ def get_version_helper(cc, regexp):
952949
consider adjusting the CC environment variable if you installed
953950
it in a non-standard prefix.''')
954951

955-
match = re.search(regexp, to_utf8(proc.communicate()[1]))
952+
with proc:
953+
match = re.search(regexp, to_utf8(proc.communicate()[1]))
956954

957-
if match:
958-
return match.group(2)
959-
else:
960-
return '0.0'
955+
return match.group(2) if match else '0.0'
961956

962957
def get_nasm_version(asm):
963958
try:
@@ -970,13 +965,11 @@ def get_nasm_version(asm):
970965
and refer BUILDING.md.''')
971966
return '0.0'
972967

973-
match = re.match(r"NASM version ([2-9]\.[0-9][0-9]+)",
974-
to_utf8(proc.communicate()[0]))
968+
with proc:
969+
match = re.match(r"NASM version ([2-9]\.[0-9][0-9]+)",
970+
to_utf8(proc.communicate()[0]))
975971

976-
if match:
977-
return match.group(1)
978-
else:
979-
return '0.0'
972+
return match.group(1) if match else '0.0'
980973

981974
def get_llvm_version(cc):
982975
return get_version_helper(
@@ -1002,14 +995,16 @@ def get_gas_version(cc):
1002995
consider adjusting the CC environment variable if you installed
1003996
it in a non-standard prefix.''')
1004997

1005-
gas_ret = to_utf8(proc.communicate()[1])
998+
with proc:
999+
gas_ret = to_utf8(proc.communicate()[1])
1000+
10061001
match = re.match(r"GNU assembler version ([2-9]\.[0-9]+)", gas_ret)
10071002

10081003
if match:
10091004
return match.group(1)
1010-
else:
1011-
warn('Could not recognize `gas`: ' + gas_ret)
1012-
return '0.0'
1005+
1006+
warn(f'Could not recognize `gas`: {gas_ret}')
1007+
return '0.0'
10131008

10141009
# Note: Apple clang self-reports as clang 4.2.0 and gcc 4.2.1. It passes
10151010
# the version check more by accident than anything else but a more rigorous
@@ -1027,26 +1022,22 @@ def check_compiler(o):
10271022

10281023
ok, is_clang, clang_version, gcc_version = try_check_compiler(CXX, 'c++')
10291024
version_str = ".".join(map(str, clang_version if is_clang else gcc_version))
1030-
print_verbose('Detected %sC++ compiler (CXX=%s) version: %s' %
1031-
('clang ' if is_clang else '', CXX, version_str))
1025+
print_verbose(f"Detected {'clang ' if is_clang else ''}C++ compiler (CXX={CXX}) version: {version_str}")
10321026
if not ok:
1033-
warn('failed to autodetect C++ compiler version (CXX=%s)' % CXX)
1027+
warn(f'failed to autodetect C++ compiler version (CXX={CXX})')
10341028
elif clang_version < (8, 0, 0) if is_clang else gcc_version < (10, 1, 0):
1035-
warn('C++ compiler (CXX=%s, %s) too old, need g++ 10.1.0 or clang++ 8.0.0' %
1036-
(CXX, version_str))
1029+
warn(f'C++ compiler (CXX={CXX}, {version_str}) too old, need g++ 10.1.0 or clang++ 8.0.0')
10371030

10381031
ok, is_clang, clang_version, gcc_version = try_check_compiler(CC, 'c')
10391032
version_str = ".".join(map(str, clang_version if is_clang else gcc_version))
1040-
print_verbose('Detected %sC compiler (CC=%s) version: %s' %
1041-
('clang ' if is_clang else '', CC, version_str))
1033+
print_verbose(f"Detected {'clang ' if is_clang else ''}C compiler (CC={CC}) version: {version_str}")
10421034
if not ok:
1043-
warn('failed to autodetect C compiler version (CC=%s)' % CC)
1035+
warn(f'failed to autodetect C compiler version (CC={CC})')
10441036
elif not is_clang and gcc_version < (4, 2, 0):
10451037
# clang 3.2 is a little white lie because any clang version will probably
10461038
# do for the C bits. However, we might as well encourage people to upgrade
10471039
# to a version that is not completely ancient.
1048-
warn('C compiler (CC=%s, %s) too old, need gcc 4.2 or clang 3.2' %
1049-
(CC, version_str))
1040+
warn(f'C compiler (CC={CC}, {version_str}) too old, need gcc 4.2 or clang 3.2')
10501041

10511042
o['variables']['llvm_version'] = get_llvm_version(CC) if is_clang else '0.0'
10521043

@@ -1076,8 +1067,9 @@ def cc_macros(cc=None):
10761067
consider adjusting the CC environment variable if you installed
10771068
it in a non-standard prefix.''')
10781069

1079-
p.stdin.write(b'\n')
1080-
out = to_utf8(p.communicate()[0]).split('\n')
1070+
with p:
1071+
p.stdin.write(b'\n')
1072+
out = to_utf8(p.communicate()[0]).split('\n')
10811073

10821074
k = {}
10831075
for line in out:
@@ -1134,9 +1126,9 @@ def host_arch_cc():
11341126

11351127
rtn = 'ia32' # default
11361128

1137-
for i in matchup:
1138-
if i in k and k[i] != '0':
1139-
rtn = matchup[i]
1129+
for key, value in matchup.items():
1130+
if k.get(key, 0) and k[key] != '0':
1131+
rtn = value
11401132
break
11411133

11421134
if rtn == 'mipsel' and '_LP64' in k:
@@ -1195,7 +1187,7 @@ def configure_arm(o):
11951187

11961188

11971189
def configure_mips(o, target_arch):
1198-
can_use_fpu_instructions = (options.mips_float_abi != 'soft')
1190+
can_use_fpu_instructions = options.mips_float_abi != 'soft'
11991191
o['variables']['v8_can_use_fpu_instructions'] = b(can_use_fpu_instructions)
12001192
o['variables']['v8_use_mips_abi_hardfloat'] = b(can_use_fpu_instructions)
12011193
o['variables']['mips_arch_variant'] = options.mips_arch_variant
@@ -1214,16 +1206,18 @@ def configure_zos(o):
12141206

12151207
def clang_version_ge(version_checked):
12161208
for compiler in [(CC, 'c'), (CXX, 'c++')]:
1217-
ok, is_clang, clang_version, gcc_version = \
1209+
_, is_clang, clang_version, _1 = (
12181210
try_check_compiler(compiler[0], compiler[1])
1211+
)
12191212
if is_clang and clang_version >= version_checked:
12201213
return True
12211214
return False
12221215

12231216
def gcc_version_ge(version_checked):
12241217
for compiler in [(CC, 'c'), (CXX, 'c++')]:
1225-
ok, is_clang, clang_version, gcc_version = \
1218+
_, is_clang, _1, gcc_version = (
12261219
try_check_compiler(compiler[0], compiler[1])
1220+
)
12271221
if is_clang or gcc_version < version_checked:
12281222
return False
12291223
return True
@@ -1324,7 +1318,7 @@ def configure_node(o):
13241318
version_checked_str = ".".join(map(str, version_checked))
13251319
raise Exception(
13261320
'The options --enable-pgo-generate and --enable-pgo-use '
1327-
'are supported for gcc and gxx %s or newer only.' % (version_checked_str))
1321+
f'are supported for gcc and gxx {version_checked_str} or newer only.')
13281322

13291323
if options.enable_pgo_generate and options.enable_pgo_use:
13301324
raise Exception(
@@ -1347,8 +1341,8 @@ def configure_node(o):
13471341
gcc_version_checked_str = ".".join(map(str, gcc_version_checked))
13481342
clang_version_checked_str = ".".join(map(str, clang_version_checked))
13491343
raise Exception(
1350-
'The option --enable-lto is supported for gcc %s+'
1351-
'or clang %s+ only.' % (gcc_version_checked_str, clang_version_checked_str))
1344+
f'The option --enable-lto is supported for gcc {gcc_version_checked_str}+'
1345+
f'or clang {clang_version_checked_str}+ only.')
13521346

13531347
o['variables']['enable_lto'] = b(options.enable_lto)
13541348

@@ -1458,15 +1452,15 @@ def configure_library(lib, output, pkgname=None):
14581452
if 'msvs_settings' not in output:
14591453
output['msvs_settings'] = { 'VCLinkerTool': { 'AdditionalOptions': [] } }
14601454
output['msvs_settings']['VCLinkerTool']['AdditionalOptions'] += [
1461-
'/LIBPATH:%s' % options.__dict__[shared_lib + '_libpath']]
1455+
f"/LIBPATH:{options.__dict__[shared_lib + '_libpath']}"]
14621456
else:
14631457
output['libraries'] += [
1464-
'-L%s' % options.__dict__[shared_lib + '_libpath']]
1458+
f"-L{options.__dict__[shared_lib + '_libpath']}"]
14651459
elif pkg_libpath:
14661460
output['libraries'] += [pkg_libpath]
14671461

14681462
default_libs = getattr(options, shared_lib + '_libname')
1469-
default_libs = ['-l{0}'.format(l) for l in default_libs.split(',')]
1463+
default_libs = [f'-l{l}' for l in default_libs.split(',')]
14701464

14711465
if default_libs:
14721466
output['libraries'] += default_libs
@@ -1528,7 +1522,7 @@ def configure_openssl(o):
15281522

15291523
if options.without_ssl:
15301524
def without_ssl_error(option):
1531-
error('--without-ssl is incompatible with %s' % option)
1525+
error(f'--without-ssl is incompatible with {option}')
15321526
if options.shared_openssl:
15331527
without_ssl_error('--shared-openssl')
15341528
if options.openssl_no_asm:
@@ -1608,35 +1602,35 @@ def configure_static(o):
16081602

16091603

16101604
def write(filename, data):
1611-
print_verbose('creating %s' % filename)
1612-
with open(filename, 'w+') as f:
1605+
print_verbose(f'creating {filename}')
1606+
with open(filename, 'w+', encoding='utf-8') as f:
16131607
f.write(data)
16141608

16151609
do_not_edit = '# Do not edit. Generated by the configure script.\n'
16161610

16171611
def glob_to_var(dir_base, dir_sub, patch_dir):
1618-
list = []
1619-
dir_all = '%s/%s' % (dir_base, dir_sub)
1612+
file_list = []
1613+
dir_all = f'{dir_base}/{dir_sub}'
16201614
files = os.walk(dir_all)
16211615
for ent in files:
1622-
(path, dirs, files) = ent
1616+
(_, _1, files) = ent
16231617
for file in files:
16241618
if file.endswith(('.cpp', '.c', '.h')):
16251619
# srcfile uses "slash" as dir separator as its output is consumed by gyp
1626-
srcfile = '%s/%s' % (dir_sub, file)
1620+
srcfile = f'{dir_sub}/{file}'
16271621
if patch_dir:
1628-
patchfile = '%s/%s/%s' % (dir_base, patch_dir, file)
1622+
patchfile = f'{dir_base}{patch_dir}{file}'
16291623
if os.path.isfile(patchfile):
1630-
srcfile = '%s/%s' % (patch_dir, file)
1631-
info('Using floating patch "%s" from "%s"' % (patchfile, dir_base))
1632-
list.append(srcfile)
1624+
srcfile = f'{patch_dir}/{file}'
1625+
info(f'Using floating patch "{patchfile}" from "{dir_base}"')
1626+
file_list.append(srcfile)
16331627
break
1634-
return list
1628+
return file_list
16351629

16361630
def configure_intl(o):
16371631
def icu_download(path):
16381632
depFile = 'tools/icu/current_ver.dep'
1639-
with open(depFile) as f:
1633+
with open(depFile, encoding='utf-8') as f:
16401634
icus = json.load(f)
16411635
# download ICU, if needed
16421636
if not os.access(options.download_path, os.W_OK):
@@ -1647,26 +1641,26 @@ def icu_download(path):
16471641
url = icu['url']
16481642
(expectHash, hashAlgo, allAlgos) = nodedownload.findHash(icu)
16491643
if not expectHash:
1650-
error('''Could not find a hash to verify ICU download.
1651-
%s may be incorrect.
1652-
For the entry %s,
1653-
Expected one of these keys: %s''' % (depFile, url, ' '.join(allAlgos)))
1644+
error(f'''Could not find a hash to verify ICU download.
1645+
{depFile} may be incorrect.
1646+
For the entry {url},
1647+
Expected one of these keys: {' '.join(allAlgos)}''')
16541648
local = url.split('/')[-1]
16551649
targetfile = os.path.join(options.download_path, local)
16561650
if not os.path.isfile(targetfile):
16571651
if attemptdownload:
16581652
nodedownload.retrievefile(url, targetfile)
16591653
else:
1660-
print('Re-using existing %s' % targetfile)
1654+
print(f'Re-using existing {targetfile}')
16611655
if os.path.isfile(targetfile):
1662-
print('Checking file integrity with %s:\r' % hashAlgo)
1656+
print(f'Checking file integrity with {hashAlgo}:\r')
16631657
gotHash = nodedownload.checkHash(targetfile, hashAlgo)
1664-
print('%s: %s %s' % (hashAlgo, gotHash, targetfile))
1665-
if (expectHash == gotHash):
1658+
print(f'{hashAlgo}: {gotHash} {targetfile}')
1659+
if expectHash == gotHash:
16661660
return targetfile
1667-
else:
1668-
warn('Expected: %s *MISMATCH*' % expectHash)
1669-
warn('\n ** Corrupted ZIP? Delete %s to retry download.\n' % targetfile)
1661+
1662+
warn(f'Expected: {expectHash} *MISMATCH*')
1663+
warn(f'\n ** Corrupted ZIP? Delete {targetfile} to retry download.\n')
16701664
return None
16711665
icu_config = {
16721666
'variables': {}
@@ -1694,12 +1688,14 @@ def icu_download(path):
16941688
# use the .gyp given
16951689
o['variables']['icu_gyp_path'] = options.with_icu_path
16961690
return
1691+
16971692
# --with-intl=<with_intl>
16981693
# set the default
16991694
if with_intl in (None, 'none'):
17001695
o['variables']['v8_enable_i18n_support'] = 0
17011696
return # no Intl
1702-
elif with_intl == 'small-icu':
1697+
1698+
if with_intl == 'small-icu':
17031699
# small ICU (English only)
17041700
o['variables']['v8_enable_i18n_support'] = 1
17051701
o['variables']['icu_small'] = b(True)
@@ -1722,8 +1718,7 @@ def icu_download(path):
17221718
icu_ver_major = icuversion.split('.')[0]
17231719
o['variables']['icu_ver_major'] = icu_ver_major
17241720
if int(icu_ver_major) < icu_versions['minimum_icu']:
1725-
error('icu4c v%s is too old, v%d.x or later is required.' %
1726-
(icuversion, icu_versions['minimum_icu']))
1721+
error(f"icu4c v{icuversion} is too old, v{icu_versions['minimum_icu']}.x or later is required.")
17271722
# libpath provides linker path which may contain spaces
17281723
if libpath:
17291724
o['libraries'] += [libpath]
@@ -1753,7 +1748,7 @@ def icu_download(path):
17531748
canned_is_full = os.path.isfile(os.path.join(canned_icu_dir, 'README-FULL-ICU.txt'))
17541749
canned_is_small = os.path.isfile(os.path.join(canned_icu_dir, 'README-SMALL-ICU.txt'))
17551750
if canned_is_small:
1756-
warn('Ignoring %s - in-repo small icu is no longer supported.' % canned_icu_dir)
1751+
warn(f'Ignoring {canned_icu_dir} - in-repo small icu is no longer supported.')
17571752

17581753
# We can use 'deps/icu-small' - pre-canned ICU *iff*
17591754
# - canned_is_full AND
@@ -1772,17 +1767,17 @@ def icu_download(path):
17721767
# --with-icu-source processing
17731768
# now, check that they didn't pass --with-icu-source=deps/icu
17741769
elif with_icu_source and os.path.abspath(icu_full_path) == os.path.abspath(with_icu_source):
1775-
warn('Ignoring redundant --with-icu-source=%s' % with_icu_source)
1770+
warn(f'Ignoring redundant --with-icu-source={with_icu_source}')
17761771
with_icu_source = None
17771772
# if with_icu_source is still set, try to use it.
17781773
if with_icu_source:
17791774
if os.path.isdir(icu_full_path):
1780-
print('Deleting old ICU source: %s' % icu_full_path)
1775+
print(f'Deleting old ICU source: {icu_full_path}')
17811776
shutil.rmtree(icu_full_path)
17821777
# now, what path was given?
17831778
if os.path.isdir(with_icu_source):
17841779
# it's a path. Copy it.
1785-
print('%s -> %s' % (with_icu_source, icu_full_path))
1780+
print(f'{with_icu_source} -> {icu_full_path}')
17861781
shutil.copytree(with_icu_source, icu_full_path)
17871782
else:
17881783
# could be file or URL.
@@ -1807,8 +1802,7 @@ def icu_download(path):
18071802
shutil.rmtree(icu_tmp_path)
18081803
else:
18091804
shutil.rmtree(icu_tmp_path)
1810-
error('--with-icu-source=%s did not result in an "icu" dir.' % \
1811-
with_icu_source)
1805+
error(f'--with-icu-source={with_icu_source} did not result in an "icu" dir.')
18121806

18131807
# ICU mode. (icu-generic.gyp)
18141808
o['variables']['icu_gyp_path'] = 'tools/icu/icu-generic.gyp'
@@ -1820,17 +1814,17 @@ def icu_download(path):
18201814
if localzip:
18211815
nodedownload.unpack(localzip, icu_parent_path)
18221816
else:
1823-
warn('* ECMA-402 (Intl) support didn\'t find ICU in %s..' % icu_full_path)
1817+
warn("* ECMA-402 (Intl) support didn't find ICU in {icu_full_path}..")
18241818
if not os.path.isdir(icu_full_path):
1825-
error('''Cannot build Intl without ICU in %s.
1826-
Fix, or disable with "--with-intl=none"''' % icu_full_path)
1819+
error(f'''Cannot build Intl without ICU in {icu_full_path}.
1820+
Fix, or disable with "--with-intl=none"''')
18271821
else:
1828-
print_verbose('* Using ICU in %s' % icu_full_path)
1822+
print_verbose(f'* Using ICU in {icu_full_path}')
18291823
# Now, what version of ICU is it? We just need the "major", such as 54.
18301824
# uvernum.h contains it as a #define.
18311825
uvernum_h = os.path.join(icu_full_path, 'source/common/unicode/uvernum.h')
18321826
if not os.path.isfile(uvernum_h):
1833-
error('Could not load %s - is ICU installed?' % uvernum_h)
1827+
error(f'Could not load {uvernum_h} - is ICU installed?')
18341828
icu_ver_major = None
18351829
matchVerExp = r'^\s*#define\s+U_ICU_VERSION_SHORT\s+"([^"]*)".*'
18361830
match_version = re.compile(matchVerExp)
@@ -1840,20 +1834,19 @@ def icu_download(path):
18401834
if m:
18411835
icu_ver_major = str(m.group(1))
18421836
if not icu_ver_major:
1843-
error('Could not read U_ICU_VERSION_SHORT version from %s' % uvernum_h)
1837+
error(f'Could not read U_ICU_VERSION_SHORT version from {uvernum_h}')
18441838
elif int(icu_ver_major) < icu_versions['minimum_icu']:
1845-
error('icu4c v%s.x is too old, v%d.x or later is required.' %
1846-
(icu_ver_major, icu_versions['minimum_icu']))
1839+
error(f"icu4c v{icu_ver_major}.x is too old, v{icu_versions['minimum_icu']}.x or later is required.")
18471840
icu_endianness = sys.byteorder[0]
18481841
o['variables']['icu_ver_major'] = icu_ver_major
18491842
o['variables']['icu_endianness'] = icu_endianness
1850-
icu_data_file_l = 'icudt%s%s.dat' % (icu_ver_major, 'l') # LE filename
1851-
icu_data_file = 'icudt%s%s.dat' % (icu_ver_major, icu_endianness)
1843+
icu_data_file_l = f'icudt{icu_ver_major}l.dat' # LE filename
1844+
icu_data_file = f'icudt{icu_ver_major}{icu_endianness}.dat'
18521845
# relative to configure
18531846
icu_data_path = os.path.join(icu_full_path,
18541847
'source/data/in',
18551848
icu_data_file_l) # LE
1856-
compressed_data = '%s.bz2' % (icu_data_path)
1849+
compressed_data = f'{icu_data_path}.bz2'
18571850
if not os.path.isfile(icu_data_path) and os.path.isfile(compressed_data):
18581851
# unpack. deps/icu is a temporary path
18591852
if os.path.isdir(icu_tmp_path):
@@ -1869,16 +1862,16 @@ def icu_download(path):
18691862
# Now, proceed..
18701863

18711864
# relative to dep..
1872-
icu_data_in = os.path.join('..','..', icu_data_path)
1865+
icu_data_in = os.path.join('..', '..', icu_data_path)
18731866
if not os.path.isfile(icu_data_path) and icu_endianness != 'l':
18741867
# use host endianness
18751868
icu_data_path = os.path.join(icu_full_path,
18761869
'source/data/in',
18771870
icu_data_file) # will be generated
18781871
if not os.path.isfile(icu_data_path):
18791872
# .. and we're not about to build it from .gyp!
1880-
error('''ICU prebuilt data file %s does not exist.
1881-
See the README.md.''' % icu_data_path)
1873+
error(f'''ICU prebuilt data file {icu_data_path} does not exist.
1874+
See the README.md.''')
18821875

18831876
# this is the input '.dat' file to use .. icudt*.dat
18841877
# may be little-endian if from a icu-project.org tarball
@@ -1896,10 +1889,10 @@ def icu_download(path):
18961889
}
18971890
# this creates a variable icu_src_XXX for each of the subdirs
18981891
# with a list of the src files to use
1899-
for i in icu_src:
1900-
var = 'icu_src_%s' % i
1901-
path = '../../%s/source/%s' % (icu_full_path, icu_src[i])
1902-
icu_config['variables'][var] = glob_to_var('tools/icu', path, 'patches/%s/source/%s' % (icu_ver_major, icu_src[i]) )
1892+
for key, value in icu_src.items():
1893+
var = f'icu_src_{key}'
1894+
path = f'../../{icu_full_path}/source/{value}'
1895+
icu_config['variables'][var] = glob_to_var('tools/icu', path, f'patches/{icu_ver_major}/source/{value}')
19031896
# calculate platform-specific genccode args
19041897
# print("platform %s, flavor %s" % (sys.platform, flavor))
19051898
# if sys.platform == 'darwin':
@@ -1950,8 +1943,9 @@ def configure_section_file(o):
19501943
warn('''No acceptable ld.gold linker found!''')
19511944
return 0
19521945

1953-
match = re.match(r"^GNU gold.*([0-9]+)\.([0-9]+)$",
1954-
proc.communicate()[0].decode("utf-8"))
1946+
with proc:
1947+
match = re.match(r"^GNU gold.*([0-9]+)\.([0-9]+)$",
1948+
proc.communicate()[0].decode("utf-8"))
19551949

19561950
if match:
19571951
gold_major_version = match.group(1)
@@ -1983,13 +1977,15 @@ def make_bin_override():
19831977
try:
19841978
os.makedirs(bin_override)
19851979
except OSError as e:
1986-
if e.errno != errno.EEXIST: raise e
1980+
if e.errno != errno.EEXIST:
1981+
raise e
19871982

19881983
python_link = os.path.join(bin_override, 'python')
19891984
try:
19901985
os.unlink(python_link)
19911986
except OSError as e:
1992-
if e.errno != errno.ENOENT: raise e
1987+
if e.errno != errno.ENOENT:
1988+
raise e
19931989
os.symlink(sys.executable, python_link)
19941990

19951991
# We need to set the environment right now so that when gyp (in run_gyp)
@@ -2013,7 +2009,7 @@ def make_bin_override():
20132009
# determine the "flavor" (operating system) we're building for,
20142010
# leveraging gyp's GetFlavor function
20152011
flavor_params = {}
2016-
if (options.dest_os):
2012+
if options.dest_os:
20172013
flavor_params['flavor'] = options.dest_os
20182014
flavor = GetFlavor(flavor_params)
20192015

@@ -2037,12 +2033,12 @@ def make_bin_override():
20372033

20382034
# configure shareable builtins
20392035
output['variables']['node_builtin_shareable_builtins'] = []
2040-
for builtin in shareable_builtins:
2036+
for builtin, value in shareable_builtins.items():
20412037
builtin_id = 'node_shared_builtin_' + builtin.replace('/', '_') + '_path'
20422038
if getattr(options, builtin_id):
20432039
output['defines'] += [builtin_id.upper() + '=' + getattr(options, builtin_id)]
20442040
else:
2045-
output['variables']['node_builtin_shareable_builtins'] += [shareable_builtins[builtin]]
2041+
output['variables']['node_builtin_shareable_builtins'] += [value]
20462042

20472043
# Forward OSS-Fuzz settings
20482044
output['variables']['ossfuzz'] = b(options.ossfuzz)

0 commit comments

Comments
 (0)
Please sign in to comment.