about summary refs log tree commit diff
diff options
context:
space:
mode:
authorTrevor Gross <tmgross@umich.edu>2023-06-10 12:06:17 -0400
committerTrevor Gross <tgross@intrepidcs.com>2023-06-16 20:56:01 -0400
commit22d00dcd47e0b8e18eb254966750fb523c726e4e (patch)
tree603ea4c342940caabe746bc86822350aa5d7f9f4
parent4b71d79c972a605959b0a7c82b323fbd8562f070 (diff)
downloadrust-22d00dcd47e0b8e18eb254966750fb523c726e4e.tar.gz
rust-22d00dcd47e0b8e18eb254966750fb523c726e4e.zip
Apply changes to fix python linting errors
-rw-r--r--compiler/rustc_codegen_gcc/tools/generate_intrinsics.py3
-rwxr-xr-xlibrary/core/src/unicode/printable.py2
-rw-r--r--src/bootstrap/bootstrap.py4
-rwxr-xr-xsrc/bootstrap/configure.py10
-rwxr-xr-x[-rw-r--r--]src/ci/cpu-usage-over-time.py0
-rwxr-xr-x[-rw-r--r--]src/ci/docker/host-x86_64/test-various/uefi_qemu_test/run.py0
-rwxr-xr-xsrc/ci/docker/scripts/android-sdk-manager.py17
-rwxr-xr-xsrc/ci/docker/scripts/fuchsia-test-runner.py4
-rwxr-xr-x[-rw-r--r--]src/ci/stage-build.py4
-rwxr-xr-x[-rw-r--r--]src/etc/dec2flt_table.py4
-rw-r--r--src/etc/gdb_load_rust_pretty_printers.py1
-rwxr-xr-xsrc/etc/generate-deriving-span-tests.py4
-rwxr-xr-x[-rw-r--r--]src/etc/htmldocck.py8
-rw-r--r--src/etc/lldb_batchmode.py2
-rw-r--r--src/etc/lldb_providers.py2
-rwxr-xr-x[-rw-r--r--]src/etc/test-float-parse/runtests.py0
-rwxr-xr-xsrc/tools/miri/test-cargo-miri/run-test.py20
-rwxr-xr-xsrc/tools/publish_toolstate.py16
-rwxr-xr-x[-rw-r--r--]tests/run-make/coverage-reports/sort_subviews.py0
-rwxr-xr-xtests/run-make/libtest-junit/validate_junit.py2
-rwxr-xr-xtests/run-make/rustdoc-map-file/validate_json.py2
-rw-r--r--tests/run-make/sysroot-crates-are-unstable/test.py2
22 files changed, 58 insertions, 49 deletions
diff --git a/compiler/rustc_codegen_gcc/tools/generate_intrinsics.py b/compiler/rustc_codegen_gcc/tools/generate_intrinsics.py
index 6188924b0d5..83abe145e64 100644
--- a/compiler/rustc_codegen_gcc/tools/generate_intrinsics.py
+++ b/compiler/rustc_codegen_gcc/tools/generate_intrinsics.py
@@ -3,7 +3,6 @@ import os
 import re
 import sys
 import subprocess
-from os import walk
 
 
 def run_command(command, cwd=None):
@@ -180,7 +179,7 @@ def update_intrinsics(llvm_path, llvmint, llvmint2):
             intrinsics[arch].sort(key=lambda x: (x[0], x[2]))
             out.write('    // {}\n'.format(arch))
             for entry in intrinsics[arch]:
-                if entry[2] == True: # if it is a duplicate
+                if entry[2] is True: # if it is a duplicate
                     out.write('    // [DUPLICATE]: "{}" => "{}",\n'.format(entry[0], entry[1]))
                 elif "_round_mask" in entry[1]:
                     out.write('    // [INVALID CONVERSION]: "{}" => "{}",\n'.format(entry[0], entry[1]))
diff --git a/library/core/src/unicode/printable.py b/library/core/src/unicode/printable.py
index 7c37f5f099c..4d39ace066c 100755
--- a/library/core/src/unicode/printable.py
+++ b/library/core/src/unicode/printable.py
@@ -119,7 +119,7 @@ def print_singletons(uppers, lowers, uppersname, lowersname):
     print("#[rustfmt::skip]")
     print("const {}: &[u8] = &[".format(lowersname))
     for i in range(0, len(lowers), 8):
-        print("    {}".format(" ".join("{:#04x},".format(l) for l in lowers[i:i+8])))
+        print("    {}".format(" ".join("{:#04x},".format(x) for x in lowers[i:i+8])))
     print("];")
 
 def print_normal(normal, normalname):
diff --git a/src/bootstrap/bootstrap.py b/src/bootstrap/bootstrap.py
index 473fdbe1edc..5714613cdf5 100644
--- a/src/bootstrap/bootstrap.py
+++ b/src/bootstrap/bootstrap.py
@@ -620,7 +620,7 @@ class RustBuild(object):
             # The latter one does not exist on NixOS when using tmpfs as root.
             try:
                 with open("/etc/os-release", "r") as f:
-                    if not any(l.strip() in ("ID=nixos", "ID='nixos'", 'ID="nixos"') for l in f):
+                    if not any(ln.strip() in ("ID=nixos", "ID='nixos'", 'ID="nixos"') for ln in f):
                         return False
             except FileNotFoundError:
                 return False
@@ -872,7 +872,7 @@ class RustBuild(object):
         }
         for var_name, toml_key in var_data.items():
             toml_val = self.get_toml(toml_key, build_section)
-            if toml_val != None:
+            if toml_val is not None:
                 env["{}_{}".format(var_name, host_triple_sanitized)] = toml_val
 
         # preserve existing RUSTFLAGS
diff --git a/src/bootstrap/configure.py b/src/bootstrap/configure.py
index 4481e1668b6..a16f77317c8 100755
--- a/src/bootstrap/configure.py
+++ b/src/bootstrap/configure.py
@@ -9,7 +9,7 @@ rust_dir = os.path.dirname(os.path.abspath(__file__))
 rust_dir = os.path.dirname(rust_dir)
 rust_dir = os.path.dirname(rust_dir)
 sys.path.append(os.path.join(rust_dir, "src", "bootstrap"))
-import bootstrap
+import bootstrap # noqa: E402
 
 
 class Option(object):
@@ -319,7 +319,7 @@ def apply_args(known_args, option_checking, config):
     for key in known_args:
         # The `set` option is special and can be passed a bunch of times
         if key == 'set':
-            for option, value in known_args[key]:
+            for _option, value in known_args[key]:
                 keyval = value.split('=', 1)
                 if len(keyval) == 1 or keyval[1] == "true":
                     value = True
@@ -401,7 +401,7 @@ def parse_example_config(known_args, config):
     top_level_keys = []
 
     for line in open(rust_dir + '/config.example.toml').read().split("\n"):
-        if cur_section == None:
+        if cur_section is None:
             if line.count('=') == 1:
                 top_level_key = line.split('=')[0]
                 top_level_key = top_level_key.strip(' #')
@@ -523,8 +523,8 @@ def write_uncommented(target, f):
         block.append(line)
         if len(line) == 0:
             if not is_comment:
-                for l in block:
-                    f.write(l + "\n")
+                for ln in block:
+                    f.write(ln + "\n")
             block = []
             is_comment = True
             continue
diff --git a/src/ci/cpu-usage-over-time.py b/src/ci/cpu-usage-over-time.py
index adfd895ead0..adfd895ead0 100644..100755
--- a/src/ci/cpu-usage-over-time.py
+++ b/src/ci/cpu-usage-over-time.py
diff --git a/src/ci/docker/host-x86_64/test-various/uefi_qemu_test/run.py b/src/ci/docker/host-x86_64/test-various/uefi_qemu_test/run.py
index ffae7b0d4ac..ffae7b0d4ac 100644..100755
--- a/src/ci/docker/host-x86_64/test-various/uefi_qemu_test/run.py
+++ b/src/ci/docker/host-x86_64/test-various/uefi_qemu_test/run.py
diff --git a/src/ci/docker/scripts/android-sdk-manager.py b/src/ci/docker/scripts/android-sdk-manager.py
index c9e2961f6eb..66cba58427b 100755
--- a/src/ci/docker/scripts/android-sdk-manager.py
+++ b/src/ci/docker/scripts/android-sdk-manager.py
@@ -2,6 +2,14 @@
 # Simpler reimplementation of Android's sdkmanager
 # Extra features of this implementation are pinning and mirroring
 
+import argparse
+import hashlib
+import os
+import subprocess
+import tempfile
+import urllib.request
+import xml.etree.ElementTree as ET
+
 # These URLs are the Google repositories containing the list of available
 # packages and their versions. The list has been generated by listing the URLs
 # fetched while executing `tools/bin/sdkmanager --list`
@@ -27,15 +35,6 @@ MIRROR_BUCKET = "rust-lang-ci-mirrors"
 MIRROR_BUCKET_REGION = "us-west-1"
 MIRROR_BASE_DIR = "rustc/android/"
 
-import argparse
-import hashlib
-import os
-import subprocess
-import sys
-import tempfile
-import urllib.request
-import xml.etree.ElementTree as ET
-
 class Package:
     def __init__(self, path, url, sha1, deps=None):
         if deps is None:
diff --git a/src/ci/docker/scripts/fuchsia-test-runner.py b/src/ci/docker/scripts/fuchsia-test-runner.py
index ecef56f56f1..77144b74996 100755
--- a/src/ci/docker/scripts/fuchsia-test-runner.py
+++ b/src/ci/docker/scripts/fuchsia-test-runner.py
@@ -568,8 +568,8 @@ class TestEnvironment:
                         env_vars += f'\n            "{var_name}={var_value}",'
 
                 # Default to no backtrace for test suite
-                if os.getenv("RUST_BACKTRACE") == None:
-                    env_vars += f'\n            "RUST_BACKTRACE=0",'
+                if os.getenv("RUST_BACKTRACE") is None:
+                    env_vars += '\n            "RUST_BACKTRACE=0",'
 
                 cml.write(
                     self.CML_TEMPLATE.format(env_vars=env_vars, exe_name=exe_name)
diff --git a/src/ci/stage-build.py b/src/ci/stage-build.py
index febc0492b94..3f30b69e8f4 100644..100755
--- a/src/ci/stage-build.py
+++ b/src/ci/stage-build.py
@@ -440,7 +440,7 @@ def retry_action(action, name: str, max_fails: int = 5):
         try:
             action()
             return
-        except:
+        except BaseException: # also catch ctrl+c/sysexit
             LOGGER.error(f"Action `{name}` has failed\n{traceback.format_exc()}")
 
     raise Exception(f"Action `{name}` has failed after {max_fails} attempts")
@@ -818,7 +818,7 @@ def run_tests(pipeline: Pipeline):
     # Extract rustc, libstd, cargo and src archives to create the optimized sysroot
     rustc_dir = extract_dist_dir(f"rustc-nightly-{PGO_HOST}") / "rustc"
     libstd_dir = extract_dist_dir(f"rust-std-nightly-{PGO_HOST}") / f"rust-std-{PGO_HOST}"
-    cargo_dir = extract_dist_dir(f"cargo-nightly-{PGO_HOST}") / f"cargo"
+    cargo_dir = extract_dist_dir(f"cargo-nightly-{PGO_HOST}") / "cargo"
     extracted_src_dir = extract_dist_dir("rust-src-nightly") / "rust-src"
 
     # We need to manually copy libstd to the extracted rustc sysroot
diff --git a/src/etc/dec2flt_table.py b/src/etc/dec2flt_table.py
index aa5188d96c3..9264a8439bb 100644..100755
--- a/src/etc/dec2flt_table.py
+++ b/src/etc/dec2flt_table.py
@@ -14,8 +14,7 @@ Adapted from Daniel Lemire's fast_float ``table_generation.py``,
 available here: <https://github.com/fastfloat/fast_float/blob/main/script/table_generation.py>.
 """
 from __future__ import print_function
-from math import ceil, floor, log, log2
-from fractions import Fraction
+from math import ceil, floor, log
 from collections import deque
 
 HEADER = """
@@ -97,7 +96,6 @@ def print_proper_powers(min_exp, max_exp, bias):
     print('#[rustfmt::skip]')
     typ = '[(u64, u64); N_POWERS_OF_FIVE]'
     print('pub static POWER_OF_FIVE_128: {} = ['.format(typ))
-    lo_mask = (1 << 64) - 1
     for c, exp in powers:
         hi = '0x{:x}'.format(c // (1 << 64))
         lo = '0x{:x}'.format(c % (1 << 64))
diff --git a/src/etc/gdb_load_rust_pretty_printers.py b/src/etc/gdb_load_rust_pretty_printers.py
index 491b6ba9e9e..e05039ce474 100644
--- a/src/etc/gdb_load_rust_pretty_printers.py
+++ b/src/etc/gdb_load_rust_pretty_printers.py
@@ -4,6 +4,7 @@ from os import path
 self_dir = path.dirname(path.realpath(__file__))
 sys.path.append(self_dir)
 
+# ruff: noqa: E402
 import gdb
 import gdb_lookup
 
diff --git a/src/etc/generate-deriving-span-tests.py b/src/etc/generate-deriving-span-tests.py
index d38f5add747..d61693460bc 100755
--- a/src/etc/generate-deriving-span-tests.py
+++ b/src/etc/generate-deriving-span-tests.py
@@ -102,7 +102,9 @@ for (trait, supers, errs) in [('Clone', [], 1),
     traits[trait] = (ALL, supers, errs)
 
 for (trait, (types, super_traits, error_count)) in traits.items():
-    mk = lambda ty: create_test_case(ty, trait, super_traits, error_count)
+    def mk(ty, t=trait, st=super_traits, ec=error_count):
+        return create_test_case(ty, t, st, ec)
+
     if types & ENUM:
         write_file(trait + '-enum', mk(ENUM_TUPLE))
         write_file(trait + '-enum-struct-variant', mk(ENUM_STRUCT))
diff --git a/src/etc/htmldocck.py b/src/etc/htmldocck.py
index c97fb4b8054..eade9e04559 100644..100755
--- a/src/etc/htmldocck.py
+++ b/src/etc/htmldocck.py
@@ -144,7 +144,7 @@ VOID_ELEMENTS = {'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'ke
 
 # Python 2 -> 3 compatibility
 try:
-    unichr
+    unichr # noqa: B018 FIXME: py2
 except NameError:
     unichr = chr
 
@@ -348,7 +348,9 @@ class CachedFiles(object):
             try:
                 tree = ET.fromstringlist(f.readlines(), CustomHTMLParser())
             except Exception as e:
-                raise RuntimeError('Cannot parse an HTML file {!r}: {}'.format(path, e))
+                raise RuntimeError( # noqa: B904 FIXME: py2
+                    'Cannot parse an HTML file {!r}: {}'.format(path, e)
+                )
             self.trees[path] = tree
             return self.trees[path]
 
@@ -422,7 +424,7 @@ def check_snapshot(snapshot_name, actual_tree, normalize_to_text):
         if bless:
             expected_str = None
         else:
-            raise FailedCheck('No saved snapshot value')
+            raise FailedCheck('No saved snapshot value') # noqa: B904 FIXME: py2
 
     if not normalize_to_text:
         actual_str = ET.tostring(actual_tree).decode('utf-8')
diff --git a/src/etc/lldb_batchmode.py b/src/etc/lldb_batchmode.py
index fc355c87b52..db1e0035ea0 100644
--- a/src/etc/lldb_batchmode.py
+++ b/src/etc/lldb_batchmode.py
@@ -124,7 +124,7 @@ def start_breakpoint_listener(target):
                         breakpoint = lldb.SBBreakpoint.GetBreakpointFromEvent(event)
                         print_debug("breakpoint added, id = " + str(breakpoint.id))
                         new_breakpoints.append(breakpoint.id)
-        except:
+        except BaseException: # explicitly catch ctrl+c/sysexit
             print_debug("breakpoint listener shutting down")
 
     # Start the listener and let it run as a daemon
diff --git a/src/etc/lldb_providers.py b/src/etc/lldb_providers.py
index c4381e202b9..4c86b214646 100644
--- a/src/etc/lldb_providers.py
+++ b/src/etc/lldb_providers.py
@@ -1,6 +1,6 @@
 import sys
 
-from lldb import SBValue, SBData, SBError, eBasicTypeLong, eBasicTypeUnsignedLong, \
+from lldb import SBData, SBError, eBasicTypeLong, eBasicTypeUnsignedLong, \
     eBasicTypeUnsignedChar
 
 # from lldb.formatters import Logger
diff --git a/src/etc/test-float-parse/runtests.py b/src/etc/test-float-parse/runtests.py
index cf7279534dc..cf7279534dc 100644..100755
--- a/src/etc/test-float-parse/runtests.py
+++ b/src/etc/test-float-parse/runtests.py
diff --git a/src/tools/miri/test-cargo-miri/run-test.py b/src/tools/miri/test-cargo-miri/run-test.py
index 9df90c725e4..f022c51e59f 100755
--- a/src/tools/miri/test-cargo-miri/run-test.py
+++ b/src/tools/miri/test-cargo-miri/run-test.py
@@ -5,7 +5,11 @@ Assumes the `MIRI_SYSROOT` env var to be set appropriately,
 and the working directory to contain the cargo-miri-test project.
 '''
 
-import sys, subprocess, os, re, difflib
+import difflib
+import os
+import re
+import sys
+import subprocess
 
 CGREEN  = '\33[32m'
 CBOLD   = '\33[1m'
@@ -46,7 +50,9 @@ def check_output(actual, path, name):
     print(f"--- END diff {name} ---")
     return False
 
-def test(name, cmd, stdout_ref, stderr_ref, stdin=b'', env={}):
+def test(name, cmd, stdout_ref, stderr_ref, stdin=b'', env=None):
+    if env is None:
+        env = {}
     print("Testing {}...".format(name))
     ## Call `cargo miri`, capture all output
     p_env = os.environ.copy()
@@ -64,13 +70,15 @@ def test(name, cmd, stdout_ref, stderr_ref, stdin=b'', env={}):
 
     stdout_matches = check_output(stdout, stdout_ref, "stdout")
     stderr_matches = check_output(stderr, stderr_ref, "stderr")
-    
+
     if p.returncode == 0 and stdout_matches and stderr_matches:
         # All good!
         return
     fail("exit code was {}".format(p.returncode))
 
-def test_no_rebuild(name, cmd, env={}):
+def test_no_rebuild(name, cmd, env=None):
+    if env is None:
+        env = {}
     print("Testing {}...".format(name))
     p_env = os.environ.copy()
     p_env.update(env)
@@ -84,13 +92,13 @@ def test_no_rebuild(name, cmd, env={}):
     stdout = stdout.decode("UTF-8")
     stderr = stderr.decode("UTF-8")
     if p.returncode != 0:
-        fail("rebuild failed");
+        fail("rebuild failed")
     # Also check for 'Running' as a sanity check.
     if stderr.count(" Compiling ") > 0 or stderr.count(" Running ") == 0:
         print("--- BEGIN stderr ---")
         print(stderr, end="")
         print("--- END stderr ---")
-        fail("Something was being rebuilt when it should not be (or we got no output)");
+        fail("Something was being rebuilt when it should not be (or we got no output)")
 
 def test_cargo_miri_run():
     test("`cargo miri run` (no isolation)",
diff --git a/src/tools/publish_toolstate.py b/src/tools/publish_toolstate.py
index 2018c239ba0..f9421117eaa 100755
--- a/src/tools/publish_toolstate.py
+++ b/src/tools/publish_toolstate.py
@@ -22,7 +22,7 @@ except ImportError:
     import urllib.request as urllib2
     from urllib.error import HTTPError
 try:
-    import typing
+    import typing # noqa: F401 FIXME: py2
 except ImportError:
     pass
 
@@ -152,8 +152,8 @@ def update_latest(
         latest = json.load(f, object_pairs_hook=collections.OrderedDict)
 
         current_status = {
-            os: read_current_status(current_commit, 'history/' + os + '.tsv')
-            for os in ['windows', 'linux']
+            os_: read_current_status(current_commit, 'history/' + os_ + '.tsv')
+            for os_ in ['windows', 'linux']
         }
 
         slug = 'rust-lang/rust'
@@ -170,10 +170,10 @@ def update_latest(
             changed = False
             create_issue_for_status = None  # set to the status that caused the issue
 
-            for os, s in current_status.items():
-                old = status[os]
+            for os_, s in current_status.items():
+                old = status[os_]
                 new = s.get(tool, old)
-                status[os] = new
+                status[os_] = new
                 maintainers = ' '.join('@'+name for name in MAINTAINERS.get(tool, ()))
                 # comparing the strings, but they are ordered appropriately:
                 # "test-pass" > "test-fail" > "build-fail"
@@ -181,12 +181,12 @@ def update_latest(
                     # things got fixed or at least the status quo improved
                     changed = True
                     message += '🎉 {} on {}: {} → {} (cc {}).\n' \
-                        .format(tool, os, old, new, maintainers)
+                        .format(tool, os_, old, new, maintainers)
                 elif new < old:
                     # tests or builds are failing and were not failing before
                     changed = True
                     title = '💔 {} on {}: {} → {}' \
-                        .format(tool, os, old, new)
+                        .format(tool, os_, old, new)
                     message += '{} (cc {}).\n' \
                         .format(title, maintainers)
                     # See if we need to create an issue.
diff --git a/tests/run-make/coverage-reports/sort_subviews.py b/tests/run-make/coverage-reports/sort_subviews.py
index 10cfc51d447..10cfc51d447 100644..100755
--- a/tests/run-make/coverage-reports/sort_subviews.py
+++ b/tests/run-make/coverage-reports/sort_subviews.py
diff --git a/tests/run-make/libtest-junit/validate_junit.py b/tests/run-make/libtest-junit/validate_junit.py
index 47a8e70ccc3..0d9b34a3cf7 100755
--- a/tests/run-make/libtest-junit/validate_junit.py
+++ b/tests/run-make/libtest-junit/validate_junit.py
@@ -7,6 +7,6 @@ import xml.etree.ElementTree as ET
 for line in sys.stdin:
     try:
         ET.fromstring(line)
-    except ET.ParseError as pe:
+    except ET.ParseError:
         print("Invalid xml: %r" % line)
         raise
diff --git a/tests/run-make/rustdoc-map-file/validate_json.py b/tests/run-make/rustdoc-map-file/validate_json.py
index 5c14c90b70d..912dea3791b 100755
--- a/tests/run-make/rustdoc-map-file/validate_json.py
+++ b/tests/run-make/rustdoc-map-file/validate_json.py
@@ -6,7 +6,7 @@ import json
 
 
 def find_redirect_map_file(folder, errors):
-    for root, dirs, files in os.walk(folder):
+    for root, _dirs, files in os.walk(folder):
         for name in files:
             if not name.endswith("redirect-map.json"):
                 continue
diff --git a/tests/run-make/sysroot-crates-are-unstable/test.py b/tests/run-make/sysroot-crates-are-unstable/test.py
index cab4faa4e64..45cfdd195b4 100644
--- a/tests/run-make/sysroot-crates-are-unstable/test.py
+++ b/tests/run-make/sysroot-crates-are-unstable/test.py
@@ -46,7 +46,7 @@ def check_lib(lib):
                                    '--target', os.environ['TARGET'],
                                    '--extern', '{}={}'.format(lib['name'], lib['path'])],
                                   to_input=('extern crate {};'.format(lib['name'])).encode('utf-8'))
-    if not 'use of unstable library feature' in '{}{}'.format(stdout, stderr):
+    if 'use of unstable library feature' not in '{}{}'.format(stdout, stderr):
         print('crate {} "{}" is not unstable'.format(lib['name'], lib['path']))
         print('{}{}'.format(stdout, stderr))
         print('')