Skip to content

Commit 22d00dc

Browse files
committed
Apply changes to fix python linting errors
1 parent 4b71d79 commit 22d00dc

File tree

22 files changed

+58
-49
lines changed

22 files changed

+58
-49
lines changed

compiler/rustc_codegen_gcc/tools/generate_intrinsics.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import re
44
import sys
55
import subprocess
6-
from os import walk
76

87

98
def run_command(command, cwd=None):
@@ -180,7 +179,7 @@ def update_intrinsics(llvm_path, llvmint, llvmint2):
180179
intrinsics[arch].sort(key=lambda x: (x[0], x[2]))
181180
out.write(' // {}\n'.format(arch))
182181
for entry in intrinsics[arch]:
183-
if entry[2] == True: # if it is a duplicate
182+
if entry[2] is True: # if it is a duplicate
184183
out.write(' // [DUPLICATE]: "{}" => "{}",\n'.format(entry[0], entry[1]))
185184
elif "_round_mask" in entry[1]:
186185
out.write(' // [INVALID CONVERSION]: "{}" => "{}",\n'.format(entry[0], entry[1]))

library/core/src/unicode/printable.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ def print_singletons(uppers, lowers, uppersname, lowersname):
119119
print("#[rustfmt::skip]")
120120
print("const {}: &[u8] = &[".format(lowersname))
121121
for i in range(0, len(lowers), 8):
122-
print(" {}".format(" ".join("{:#04x},".format(l) for l in lowers[i:i+8])))
122+
print(" {}".format(" ".join("{:#04x},".format(x) for x in lowers[i:i+8])))
123123
print("];")
124124

125125
def print_normal(normal, normalname):

src/bootstrap/bootstrap.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -620,7 +620,7 @@ def get_answer():
620620
# The latter one does not exist on NixOS when using tmpfs as root.
621621
try:
622622
with open("/etc/os-release", "r") as f:
623-
if not any(l.strip() in ("ID=nixos", "ID='nixos'", 'ID="nixos"') for l in f):
623+
if not any(ln.strip() in ("ID=nixos", "ID='nixos'", 'ID="nixos"') for ln in f):
624624
return False
625625
except FileNotFoundError:
626626
return False
@@ -872,7 +872,7 @@ def build_bootstrap(self, color, warnings, verbose_count):
872872
}
873873
for var_name, toml_key in var_data.items():
874874
toml_val = self.get_toml(toml_key, build_section)
875-
if toml_val != None:
875+
if toml_val is not None:
876876
env["{}_{}".format(var_name, host_triple_sanitized)] = toml_val
877877

878878
# preserve existing RUSTFLAGS

src/bootstrap/configure.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
rust_dir = os.path.dirname(rust_dir)
1010
rust_dir = os.path.dirname(rust_dir)
1111
sys.path.append(os.path.join(rust_dir, "src", "bootstrap"))
12-
import bootstrap
12+
import bootstrap # noqa: E402
1313

1414

1515
class Option(object):
@@ -319,7 +319,7 @@ def apply_args(known_args, option_checking, config):
319319
for key in known_args:
320320
# The `set` option is special and can be passed a bunch of times
321321
if key == 'set':
322-
for option, value in known_args[key]:
322+
for _option, value in known_args[key]:
323323
keyval = value.split('=', 1)
324324
if len(keyval) == 1 or keyval[1] == "true":
325325
value = True
@@ -401,7 +401,7 @@ def parse_example_config(known_args, config):
401401
top_level_keys = []
402402

403403
for line in open(rust_dir + '/config.example.toml').read().split("\n"):
404-
if cur_section == None:
404+
if cur_section is None:
405405
if line.count('=') == 1:
406406
top_level_key = line.split('=')[0]
407407
top_level_key = top_level_key.strip(' #')
@@ -523,8 +523,8 @@ def write_uncommented(target, f):
523523
block.append(line)
524524
if len(line) == 0:
525525
if not is_comment:
526-
for l in block:
527-
f.write(l + "\n")
526+
for ln in block:
527+
f.write(ln + "\n")
528528
block = []
529529
is_comment = True
530530
continue

src/ci/cpu-usage-over-time.py

100644100755
File mode changed.

src/ci/docker/host-x86_64/test-various/uefi_qemu_test/run.py

100644100755
File mode changed.

src/ci/docker/scripts/android-sdk-manager.py

+8-9
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,14 @@
22
# Simpler reimplementation of Android's sdkmanager
33
# Extra features of this implementation are pinning and mirroring
44

5+
import argparse
6+
import hashlib
7+
import os
8+
import subprocess
9+
import tempfile
10+
import urllib.request
11+
import xml.etree.ElementTree as ET
12+
513
# These URLs are the Google repositories containing the list of available
614
# packages and their versions. The list has been generated by listing the URLs
715
# fetched while executing `tools/bin/sdkmanager --list`
@@ -27,15 +35,6 @@
2735
MIRROR_BUCKET_REGION = "us-west-1"
2836
MIRROR_BASE_DIR = "rustc/android/"
2937

30-
import argparse
31-
import hashlib
32-
import os
33-
import subprocess
34-
import sys
35-
import tempfile
36-
import urllib.request
37-
import xml.etree.ElementTree as ET
38-
3938
class Package:
4039
def __init__(self, path, url, sha1, deps=None):
4140
if deps is None:

src/ci/docker/scripts/fuchsia-test-runner.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -568,8 +568,8 @@ def log(msg):
568568
env_vars += f'\n "{var_name}={var_value}",'
569569

570570
# Default to no backtrace for test suite
571-
if os.getenv("RUST_BACKTRACE") == None:
572-
env_vars += f'\n "RUST_BACKTRACE=0",'
571+
if os.getenv("RUST_BACKTRACE") is None:
572+
env_vars += '\n "RUST_BACKTRACE=0",'
573573

574574
cml.write(
575575
self.CML_TEMPLATE.format(env_vars=env_vars, exe_name=exe_name)

src/ci/stage-build.py

100644100755
+2-2
Original file line numberDiff line numberDiff line change
@@ -440,7 +440,7 @@ def retry_action(action, name: str, max_fails: int = 5):
440440
try:
441441
action()
442442
return
443-
except:
443+
except BaseException: # also catch ctrl+c/sysexit
444444
LOGGER.error(f"Action `{name}` has failed\n{traceback.format_exc()}")
445445

446446
raise Exception(f"Action `{name}` has failed after {max_fails} attempts")
@@ -818,7 +818,7 @@ def extract_dist_dir(name: str) -> Path:
818818
# Extract rustc, libstd, cargo and src archives to create the optimized sysroot
819819
rustc_dir = extract_dist_dir(f"rustc-nightly-{PGO_HOST}") / "rustc"
820820
libstd_dir = extract_dist_dir(f"rust-std-nightly-{PGO_HOST}") / f"rust-std-{PGO_HOST}"
821-
cargo_dir = extract_dist_dir(f"cargo-nightly-{PGO_HOST}") / f"cargo"
821+
cargo_dir = extract_dist_dir(f"cargo-nightly-{PGO_HOST}") / "cargo"
822822
extracted_src_dir = extract_dist_dir("rust-src-nightly") / "rust-src"
823823

824824
# We need to manually copy libstd to the extracted rustc sysroot

src/etc/dec2flt_table.py

100644100755
+1-3
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,7 @@
1414
available here: <https://github.com/fastfloat/fast_float/blob/main/script/table_generation.py>.
1515
"""
1616
from __future__ import print_function
17-
from math import ceil, floor, log, log2
18-
from fractions import Fraction
17+
from math import ceil, floor, log
1918
from collections import deque
2019

2120
HEADER = """
@@ -97,7 +96,6 @@ def print_proper_powers(min_exp, max_exp, bias):
9796
print('#[rustfmt::skip]')
9897
typ = '[(u64, u64); N_POWERS_OF_FIVE]'
9998
print('pub static POWER_OF_FIVE_128: {} = ['.format(typ))
100-
lo_mask = (1 << 64) - 1
10199
for c, exp in powers:
102100
hi = '0x{:x}'.format(c // (1 << 64))
103101
lo = '0x{:x}'.format(c % (1 << 64))

src/etc/gdb_load_rust_pretty_printers.py

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
self_dir = path.dirname(path.realpath(__file__))
55
sys.path.append(self_dir)
66

7+
# ruff: noqa: E402
78
import gdb
89
import gdb_lookup
910

src/etc/generate-deriving-span-tests.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,9 @@ def write_file(name, string):
102102
traits[trait] = (ALL, supers, errs)
103103

104104
for (trait, (types, super_traits, error_count)) in traits.items():
105-
mk = lambda ty: create_test_case(ty, trait, super_traits, error_count)
105+
def mk(ty, t=trait, st=super_traits, ec=error_count):
106+
return create_test_case(ty, t, st, ec)
107+
106108
if types & ENUM:
107109
write_file(trait + '-enum', mk(ENUM_TUPLE))
108110
write_file(trait + '-enum-struct-variant', mk(ENUM_STRUCT))

src/etc/htmldocck.py

100644100755
+5-3
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@
144144

145145
# Python 2 -> 3 compatibility
146146
try:
147-
unichr
147+
unichr # noqa: B018 FIXME: py2
148148
except NameError:
149149
unichr = chr
150150

@@ -348,7 +348,9 @@ def get_tree(self, path):
348348
try:
349349
tree = ET.fromstringlist(f.readlines(), CustomHTMLParser())
350350
except Exception as e:
351-
raise RuntimeError('Cannot parse an HTML file {!r}: {}'.format(path, e))
351+
raise RuntimeError( # noqa: B904 FIXME: py2
352+
'Cannot parse an HTML file {!r}: {}'.format(path, e)
353+
)
352354
self.trees[path] = tree
353355
return self.trees[path]
354356

@@ -422,7 +424,7 @@ def check_snapshot(snapshot_name, actual_tree, normalize_to_text):
422424
if bless:
423425
expected_str = None
424426
else:
425-
raise FailedCheck('No saved snapshot value')
427+
raise FailedCheck('No saved snapshot value') # noqa: B904 FIXME: py2
426428

427429
if not normalize_to_text:
428430
actual_str = ET.tostring(actual_tree).decode('utf-8')

src/etc/lldb_batchmode.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ def listen():
124124
breakpoint = lldb.SBBreakpoint.GetBreakpointFromEvent(event)
125125
print_debug("breakpoint added, id = " + str(breakpoint.id))
126126
new_breakpoints.append(breakpoint.id)
127-
except:
127+
except BaseException: # explicitly catch ctrl+c/sysexit
128128
print_debug("breakpoint listener shutting down")
129129

130130
# Start the listener and let it run as a daemon

src/etc/lldb_providers.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import sys
22

3-
from lldb import SBValue, SBData, SBError, eBasicTypeLong, eBasicTypeUnsignedLong, \
3+
from lldb import SBData, SBError, eBasicTypeLong, eBasicTypeUnsignedLong, \
44
eBasicTypeUnsignedChar
55

66
# from lldb.formatters import Logger

src/etc/test-float-parse/runtests.py

100644100755
File mode changed.

src/tools/miri/test-cargo-miri/run-test.py

+14-6
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,11 @@
55
and the working directory to contain the cargo-miri-test project.
66
'''
77

8-
import sys, subprocess, os, re, difflib
8+
import difflib
9+
import os
10+
import re
11+
import sys
12+
import subprocess
913

1014
CGREEN = '\33[32m'
1115
CBOLD = '\33[1m'
@@ -46,7 +50,9 @@ def check_output(actual, path, name):
4650
print(f"--- END diff {name} ---")
4751
return False
4852

49-
def test(name, cmd, stdout_ref, stderr_ref, stdin=b'', env={}):
53+
def test(name, cmd, stdout_ref, stderr_ref, stdin=b'', env=None):
54+
if env is None:
55+
env = {}
5056
print("Testing {}...".format(name))
5157
## Call `cargo miri`, capture all output
5258
p_env = os.environ.copy()
@@ -64,13 +70,15 @@ def test(name, cmd, stdout_ref, stderr_ref, stdin=b'', env={}):
6470

6571
stdout_matches = check_output(stdout, stdout_ref, "stdout")
6672
stderr_matches = check_output(stderr, stderr_ref, "stderr")
67-
73+
6874
if p.returncode == 0 and stdout_matches and stderr_matches:
6975
# All good!
7076
return
7177
fail("exit code was {}".format(p.returncode))
7278

73-
def test_no_rebuild(name, cmd, env={}):
79+
def test_no_rebuild(name, cmd, env=None):
80+
if env is None:
81+
env = {}
7482
print("Testing {}...".format(name))
7583
p_env = os.environ.copy()
7684
p_env.update(env)
@@ -84,13 +92,13 @@ def test_no_rebuild(name, cmd, env={}):
8492
stdout = stdout.decode("UTF-8")
8593
stderr = stderr.decode("UTF-8")
8694
if p.returncode != 0:
87-
fail("rebuild failed");
95+
fail("rebuild failed")
8896
# Also check for 'Running' as a sanity check.
8997
if stderr.count(" Compiling ") > 0 or stderr.count(" Running ") == 0:
9098
print("--- BEGIN stderr ---")
9199
print(stderr, end="")
92100
print("--- END stderr ---")
93-
fail("Something was being rebuilt when it should not be (or we got no output)");
101+
fail("Something was being rebuilt when it should not be (or we got no output)")
94102

95103
def test_cargo_miri_run():
96104
test("`cargo miri run` (no isolation)",

src/tools/publish_toolstate.py

+8-8
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
import urllib.request as urllib2
2323
from urllib.error import HTTPError
2424
try:
25-
import typing
25+
import typing # noqa: F401 FIXME: py2
2626
except ImportError:
2727
pass
2828

@@ -152,8 +152,8 @@ def update_latest(
152152
latest = json.load(f, object_pairs_hook=collections.OrderedDict)
153153

154154
current_status = {
155-
os: read_current_status(current_commit, 'history/' + os + '.tsv')
156-
for os in ['windows', 'linux']
155+
os_: read_current_status(current_commit, 'history/' + os_ + '.tsv')
156+
for os_ in ['windows', 'linux']
157157
}
158158

159159
slug = 'rust-lang/rust'
@@ -170,23 +170,23 @@ def update_latest(
170170
changed = False
171171
create_issue_for_status = None # set to the status that caused the issue
172172

173-
for os, s in current_status.items():
174-
old = status[os]
173+
for os_, s in current_status.items():
174+
old = status[os_]
175175
new = s.get(tool, old)
176-
status[os] = new
176+
status[os_] = new
177177
maintainers = ' '.join('@'+name for name in MAINTAINERS.get(tool, ()))
178178
# comparing the strings, but they are ordered appropriately:
179179
# "test-pass" > "test-fail" > "build-fail"
180180
if new > old:
181181
# things got fixed or at least the status quo improved
182182
changed = True
183183
message += '🎉 {} on {}: {} → {} (cc {}).\n' \
184-
.format(tool, os, old, new, maintainers)
184+
.format(tool, os_, old, new, maintainers)
185185
elif new < old:
186186
# tests or builds are failing and were not failing before
187187
changed = True
188188
title = '💔 {} on {}: {} → {}' \
189-
.format(tool, os, old, new)
189+
.format(tool, os_, old, new)
190190
message += '{} (cc {}).\n' \
191191
.format(title, maintainers)
192192
# See if we need to create an issue.

tests/run-make/coverage-reports/sort_subviews.py

100644100755
File mode changed.

tests/run-make/libtest-junit/validate_junit.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,6 @@
77
for line in sys.stdin:
88
try:
99
ET.fromstring(line)
10-
except ET.ParseError as pe:
10+
except ET.ParseError:
1111
print("Invalid xml: %r" % line)
1212
raise

tests/run-make/rustdoc-map-file/validate_json.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77

88
def find_redirect_map_file(folder, errors):
9-
for root, dirs, files in os.walk(folder):
9+
for root, _dirs, files in os.walk(folder):
1010
for name in files:
1111
if not name.endswith("redirect-map.json"):
1212
continue

tests/run-make/sysroot-crates-are-unstable/test.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def check_lib(lib):
4646
'--target', os.environ['TARGET'],
4747
'--extern', '{}={}'.format(lib['name'], lib['path'])],
4848
to_input=('extern crate {};'.format(lib['name'])).encode('utf-8'))
49-
if not 'use of unstable library feature' in '{}{}'.format(stdout, stderr):
49+
if 'use of unstable library feature' not in '{}{}'.format(stdout, stderr):
5050
print('crate {} "{}" is not unstable'.format(lib['name'], lib['path']))
5151
print('{}{}'.format(stdout, stderr))
5252
print('')

0 commit comments

Comments
 (0)