Apache Lucene open-source search software
python scripts: fix enough so that undefined variable analysis works (#14319)
Robert Muirdfa4494fe179
diff --git a/dev-tools/scripts/.editorconfig b/dev-tools/scripts/.editorconfignew file mode 100644index 00000000000..c99e8999717--- /dev/null+++ b/dev-tools/scripts/.editorconfig@@ -0,0 +1,9 @@+root = true++[*.py]+indent_style = space+indent_size = 2+end_of_line = lf+charset = utf-8+trim_trailing_whitespace = true+insert_final_newline = truediff --git a/dev-tools/scripts/addVersion.py b/dev-tools/scripts/addVersion.pyindex 95c8c3c7353..41ef19e0107 100755--- a/dev-tools/scripts/addVersion.py+++ b/dev-tools/scripts/addVersion.py@@ -18,12 +18,10 @@import osimport syssys.path.append(os.path.dirname(__file__))-from scriptutil import *-+from scriptutil import find_branch_type, find_current_version, run, update_file, Versionimport argparseimport refrom configparser import ConfigParser, ExtendedInterpolation-from textwrap import dedentdef update_changes(filename, new_version, init_changes, headers):print(' adding new section to %s...' % filename, end='', flush=True)@@ -55,7 +53,7 @@ def add_constant(new_version, deprecate):if last.strip() != '@Deprecated':spaces = ' ' * (len(last) - len(last.lstrip()) - 1)del buffer[-1] # Remove comment closer line- if (len(buffer) >= 4 and re.search('for Lucene.\s*$', buffer[-1]) != None):+ if (len(buffer) >= 4 and re.search('for Lucene.\s*$', buffer[-1]) is not None):del buffer[-3:] # drop the trailing lines '<p> / Use this to get the latest ... / ... for Lucene.'buffer.append(( '{0} * @deprecated ({1}) Use latest\n'+ '{0} */\n'diff --git a/dev-tools/scripts/buildAndPushRelease.py b/dev-tools/scripts/buildAndPushRelease.pyindex 8985d77cec2..50050800cfc 100755--- a/dev-tools/scripts/buildAndPushRelease.py+++ b/dev-tools/scripts/buildAndPushRelease.py@@ -24,7 +24,9 @@ import sysimport subprocessfrom subprocess import TimeoutExpiredimport textwrap-import urllib.request, urllib.error, urllib.parse+import urllib.request+import urllib.error+import urllib.parseimport xml.etree.ElementTree as ETimport scriptutildiff --git a/dev-tools/scripts/githubPRs.py b/dev-tools/scripts/githubPRs.pyindex 38e8c6be6b7..d55f916d00a 100755--- a/dev-tools/scripts/githubPRs.py+++ b/dev-tools/scripts/githubPRs.py@@ -28,13 +28,7 @@ import jsonimport refrom github import Githubfrom jira import JIRA-from datetime import datetime-from time import strftime-try:- from jinja2 import Environment, BaseLoader- can_do_html = True-except:- can_do_html = False+from jinja2 import Environment, BaseLoaderdef read_config():parser = argparse.ArgumentParser(description='Find open Pull Requests that need attention')@@ -51,9 +45,6 @@ def out(text):print(text)def make_html(dict):- if not can_do_html:- print ("ERROR: Cannot generate HTML. Please install jinja2")- sys.exit(1)global conftemplate = Environment(loader=BaseLoader).from_string("""<h1>Lucene Github PR report</h1>diff --git a/dev-tools/scripts/pyproject.toml b/dev-tools/scripts/pyproject.tomlindex 64ef5ef4408..2349f77d09b 100644--- a/dev-tools/scripts/pyproject.toml+++ b/dev-tools/scripts/pyproject.toml@@ -3,6 +3,7 @@ venvPath = "."venv = ".venv"# TODO: improve!# typeCheckingMode = "strict"+reportUnnecessaryTypeIgnoreComment = "error"typeCheckingMode = "basic"# TODO: we should fix thesereportArgumentType = "none"@@ -13,7 +14,6 @@ reportOperatorIssue = "none"reportOptionalIterable = "none"reportOptionalMemberAccess = "none"reportOptionalSubscript = "none"-reportUndefinedVariable = "none"[tool.ruff]line-length = 200@@ -25,22 +25,6 @@ indent-width = 2# disabling/enabling of rulesignore = [- # we should fix these- "E401", # multiple imports on one line- "E701", # multiple statements on one line- "E711", # comparison should be "is not None"- "E703", # unnecessary semicolon- "E713", # test for membership should be "not in"- "E714", # test for object identity should be "is not"- "E722", # do not use bare except- "E741", # ambiguous variable name- "F401", # unused import- "F403", # unable to detect undefined names due to star imports- "F405", # undefined name or defined from star imports- "F811", # redefinition of unused- "F821", # undefined name- "F841", # local variable assigned but never used-# These rules are always disabled: conflict with the formatter# don't enable! https://docs.astral.sh/ruff/formatter/#conflicting-lint-rules"W191", "E111", "E114", "E117", "D206", "D300", "Q000", "Q001",diff --git a/dev-tools/scripts/releaseWizard.py b/dev-tools/scripts/releaseWizard.pyindex a2bcb062175..cb75ca8bff7 100755--- a/dev-tools/scripts/releaseWizard.py+++ b/dev-tools/scripts/releaseWizard.py@@ -51,15 +51,10 @@ from datetime import datetimefrom datetime import timedeltafrom datetime import timezone-try:- import holidays- import yaml- from ics import Calendar, Event- from jinja2 import Environment-except:- print("You lack some of the module dependencies to run this script.")- print("Please run 'pip3 install -r requirements.txt' and try again.")- sys.exit(1)+import holidays+import yaml+from ics import Calendar, Event+from jinja2 import Environmentimport scriptutilfrom consolemenu import ConsoleMenu@@ -173,26 +168,26 @@ def check_prerequisites(todo=None):sys.exit("Script requires Python v3.4 or later")try:gpg_ver = run("gpg --version").splitlines()[0]- except:+ except Exception:sys.exit("You will need gpg installed")- if not 'GPG_TTY' in os.environ:+ if 'GPG_TTY' not in os.environ:print("WARNING: GPG_TTY environment variable is not set, GPG signing may not work correctly (try 'export GPG_TTY=$(tty)'")- if not 'JAVA11_HOME' in os.environ:+ if 'JAVA11_HOME' not in os.environ:sys.exit("Please set environment variables JAVA11_HOME")try:asciidoc_ver = run("asciidoctor -V").splitlines()[0]- except:+ except Exception:asciidoc_ver = ""print("WARNING: In order to export asciidoc version to HTML, you will need asciidoctor installed")try:git_ver = run("git --version").splitlines()[0]- except:+ except Exception:sys.exit("You will need git installed")try:run("svn --version").splitlines()[0]- except:+ except Exception:sys.exit("You will need svn installed")- if not 'EDITOR' in os.environ:+ if 'EDITOR' not in os.environ:print("WARNING: Environment variable $EDITOR not set, using %s" % get_editor())if todo:@@ -285,7 +280,7 @@ class ReleaseState:self.mirrored_versions = Nonetry:self.script_branch_type = scriptutil.find_branch_type()- except:+ except Exception:print("WARNING: This script shold (ideally) run from the release branch, not a feature branch (%s)" % self.script_branch)self.script_branch_type = 'feature'self.set_release_version(release_version)@@ -510,7 +505,7 @@ class ReleaseState:def get_current_git_rev(self):try:return run("git rev-parse HEAD", cwd=self.get_git_checkout_folder()).strip()- except:+ except Exception:return "<git-rev>"def get_group_by_id(self, id):@@ -717,7 +712,7 @@ class Todo(SecretYamlObject):if self.types:self.types = ensure_list(self.types)for t in self.types:- if not t in ['minor', 'major', 'bugfix']:+ if t not in ['minor', 'major', 'bugfix']:sys.exit("Wrong Todo config for '%s'. Type needs to be either 'minor', 'major' or 'bugfix'" % self.id)if commands:self.commands.todo_id = self.id@@ -867,7 +862,7 @@ def get_release_version():v = str(input("Which version are you releasing? (x.y.z) "))try:version = Version.parse(v)- except:+ except Exception:print("Not a valid version %s" % v)return get_release_version()@@ -1011,8 +1006,8 @@ def generate_asciidoc():fh.write("\n%s\n\n" % todo.get_post_description())if todo.links:fh.write("Links:\n\n")- for l in todo.links:- fh.write("* %s\n" % expand_jinja(l))+ for link in todo.links:+ fh.write("* %s\n" % expand_jinja(link))fh.write("\n")fh.close()@@ -1031,7 +1026,7 @@ def load_rc():try:with open(lucenerc, 'r') as fp:return json.load(fp)- except:+ except Exception:return None@@ -1160,7 +1155,7 @@ def configure_pgp(gpg_todo):print("Please either generate a strong key or reconfigure your client")return Falseprint("Validated that your key is of type RSA and has a length >= 2048 (%s)" % length)- except:+ except Exception:print(textwrap.dedent("""\Key not found on your private gpg keychain. In order to sign the release you'llneed to fix this, then try again"""))@@ -1170,14 +1165,14 @@ def configure_pgp(gpg_todo):sigs = 0apache_sigs = 0for line in lines:- if line.startswith("sig") and not gpg_id in line:+ if line.startswith("sig") and gpg_id not in line:sigs += 1if '@apache.org' in line:apache_sigs += 1print("Your key has %s signatures, of which %s are by committers (@apache.org address)" % (sigs, apache_sigs))if apache_sigs < 1:print(textwrap.dedent("""\- Your key is not signed by any other committer.+ Your key is not signed by any other committer.Please review https://infra.apache.org/openpgp.html#apache-wotand make sure to get your key signed until next time.You may want to run 'gpg --refresh-keys' to refresh your keychain."""))@@ -1220,7 +1215,7 @@ def configure_pgp(gpg_todo):print(textwrap.dedent("""\You need the passphrase to sign the release.This script can prompt you securely for your passphrase (will not be stored) and pass it on to- buildAndPushRelease in a secure way. However, you can also configure your passphrase in advance+ buildAndPushRelease in a secure way. However, you can also configure your passphrase in advanceand avoid having to type it in the terminal. This can be done with either a gpg-agent (for gpg tool)or in gradle.properties or an ENV.var (for gradle), See ./gradlew helpPublishing for details."""))gpg_state['prompt_pass'] = ask_yes_no("Do you want this wizard to prompt you for your gpg password? ")@@ -1251,7 +1246,7 @@ def main():try:ConsoleMenu(clear_screen=True)- except Exception as e:+ except Exception:sys.exit("You need to install 'consolemenu' package version 0.7.1 for the Wizard to function. Please run 'pip ""install -r requirements.txt'")@@ -1264,7 +1259,6 @@ def main():release_root = os.path.expanduser("~/.lucene-releases")if not load_rc() or c.init:print("Initializing")- dir_ok = Falseroot = str(input("Choose root folder: [~/.lucene-releases] "))if os.path.exists(root) and (not os.path.isdir(root) or not os.access(root, os.W_OK)):sys.exit("Root %s exists but is not a directory or is not writable" % root)@@ -1552,8 +1546,8 @@ class Commands(SecretYamlObject):for line in cmd.display_cmd():print(" %s" % line)print()- confirm_each = (not self.confirm_each_command is False) and len(commands) > 1- if not self.enable_execute is False:+ confirm_each = (self.confirm_each_command is not False) and len(commands) > 1+ if self.enable_execute is not False:if self.run_text:print("\n%s\n" % self.get_run_text())if confirm_each:@@ -1825,7 +1819,7 @@ class UserInput(SecretYamlObject):return result-def create_ical(todo): # pylint: disable=unused-argument+def create_ical(_todo): # pylint: disable=unused-argumentif ask_yes_no("Do you want to add a Calendar reminder for the close vote time?"):c = Calendar()e = Event()@@ -1872,7 +1866,7 @@ def vote_close_72h_holidays():return holidays if len(holidays) > 0 else None-def prepare_announce_lucene(todo): # pylint: disable=unused-argument+def prepare_announce_lucene(_todo): # pylint: disable=unused-argumentif not os.path.exists(lucene_news_file):lucene_text = expand_jinja("(( template=announce_lucene ))")with open(lucene_news_file, 'w') as fp:@@ -1883,7 +1877,7 @@ def prepare_announce_lucene(todo): # pylint: disable=unused-argumentreturn True-def check_artifacts_available(todo): # pylint: disable=unused-argument+def check_artifacts_available(_todo): # pylint: disable=unused-argumenttry:cdnUrl = expand_jinja("https://dlcdn.apache.org/lucene/java/{{ release_version }}/lucene-{{ release_version }}-src.tgz.asc")load(cdnUrl)diff --git a/dev-tools/scripts/releasedJirasRegex.py b/dev-tools/scripts/releasedJirasRegex.pyindex 1ec80fd155f..5934344bce2 100755--- a/dev-tools/scripts/releasedJirasRegex.py+++ b/dev-tools/scripts/releasedJirasRegex.py@@ -18,7 +18,7 @@import sysimport ossys.path.append(os.path.dirname(__file__))-from scriptutil import *+from scriptutil import Versionimport argparseimport rediff --git a/dev-tools/scripts/reproduceJenkinsFailures.py b/dev-tools/scripts/reproduceJenkinsFailures.pyindex e28ef3aa67c..f6994c0813f 100644--- a/dev-tools/scripts/reproduceJenkinsFailures.py+++ b/dev-tools/scripts/reproduceJenkinsFailures.py@@ -85,8 +85,8 @@ def runOutput(cmd):print('[repro] %s' % cmd)try:return subprocess.check_output(cmd.split(' '), universal_newlines=True).strip()- except CalledProcessError as e:- raise RuntimeError("ERROR: Cmd '%s' failed with exit code %d and the following output:\n%s"+ except subprocess.CalledProcessError as e:+ raise RuntimeError("ERROR: Cmd '%s' failed with exit code %d and the following output:\n%s"% (cmd, e.returncode, e.output))# Remembers non-zero exit code in lastFailureCode unless rememberFailure==False@@ -142,10 +142,10 @@ def fetchAndParseJenkinsLog(url, numRetries):print('[repro] Encountered IncompleteRead exception, aborting after too many retries.')raise RuntimeError('ERROR: fetching %s : %s' % (url, e))- if revisionFromLog == None:+ if revisionFromLog is None:if reJenkinsURLWithoutConsoleText.match(url):print('[repro] Not a Jenkins log. Appending "/consoleText" and retrying ...\n')- return fetchAndParseJenkinsLog(url + '/consoleText', numRetries)+ return fetchAndParseJenkinsLog(url + '/consoleText', numRetries)else:raise RuntimeError('ERROR: %s does not appear to be a Jenkins log.' % url)if 0 == len(tests):@@ -173,7 +173,7 @@ def prepareWorkspace(useGit, gitRef):raise RuntimeError('ERROR: "%s" failed. See above.' % checkoutBranchCmd)gitCheckoutSucceeded = Truerun('git merge --ff-only', rememberFailure=False) # Ignore failure on non-branch ref-+code = run('ant clean')if 0 != code:raise RuntimeError('ERROR: "ant clean" failed. See above.')@@ -204,7 +204,7 @@ def runTests(testIters, modules, tests):for module in modules:moduleTests = list(modules[module])testList = '|'.join(map(lambda t: '*.%s' % t, moduleTests))- numTests = len(moduleTests)+ numTests = len(moduleTests)params = tests[moduleTests[0]] # Assumption: all tests in this module have the same cmdline paramsos.chdir(module)code = run('ant compile-test')@@ -214,7 +214,7 @@ def runTests(testIters, modules, tests):run(testCmdline % (testIters, testIters * numTests, testList, antOptions, params))finally:os.chdir(cwd)-+def printAndMoveReports(testIters, newSubDir, location):failures = {}for start in ('lucene/build', 'solr/build'):@@ -237,7 +237,7 @@ def printAndMoveReports(testIters, newSubDir, location):os.makedirs(newDirPath, exist_ok=True)os.rename(filePath, os.path.join(newDirPath, file))print("[repro] Failures%s:" % location)- for testcase in sorted(failures, key=lambda t: (failures[t],t)): # sort by failure count, then by testcase+ for testcase in sorted(failures, key=lambda t: (failures[t],t)): # sort by failure count, then by testcaseprint("[repro] %d/%d failed: %s" % (failures[testcase], testIters, testcase))return failures@@ -258,15 +258,15 @@ def main():# have to play nice with ant clean, so printAndMoveReports will move all the junit XML files here...print('[repro] JUnit rest result XML files will be moved to: ./repro-reports')if os.path.isdir('repro-reports'):- print('[repro] Deleting old ./repro-reports');+ print('[repro] Deleting old ./repro-reports')shutil.rmtree('repro-reports')prepareWorkspace(config.useGit, revisionFromLog)modules = groupTestsByModule(tests)runTests(config.testIters, modules, tests)failures = printAndMoveReports(config.testIters, 'orig',' w/original seeds' + (' at %s' % revisionFromLog if config.useGit else ''))--++if config.useGit:# Retest 100% failures at the tip of the brancholdTests = tests@@ -282,7 +282,7 @@ def main():runTests(config.testIters, modules, tests)failures = printAndMoveReports(config.testIters, 'branch-tip',' original seeds at the tip of %s' % branchFromLog)-+# Retest 100% tip-of-branch failures without a seedoldTests = teststests = {}@@ -297,7 +297,7 @@ def main():runTests(config.testIters, modules, tests)printAndMoveReports(config.testIters, 'branch-tip-no-seed',' at the tip of %s without a seed' % branchFromLog)- except Exception as e:+ except Exception:print('[repro] %s' % traceback.format_exc())sys.exit(1)finally:diff --git a/dev-tools/scripts/scriptutil.py b/dev-tools/scripts/scriptutil.pyindex e1c9288770a..3995050ca55 100644--- a/dev-tools/scripts/scriptutil.py+++ b/dev-tools/scripts/scriptutil.py@@ -20,7 +20,8 @@ import sysimport osfrom enum import Enumimport time-import urllib.request, urllib.error, urllib.parse+import urllib.request+import urllib.errorimport urllib.parseclass Version(object):diff --git a/dev-tools/scripts/smokeTestRelease.py b/dev-tools/scripts/smokeTestRelease.pyindex da3c001162e..5bcc87a99c5 100755--- a/dev-tools/scripts/smokeTestRelease.py+++ b/dev-tools/scripts/smokeTestRelease.py@@ -32,7 +32,6 @@ import textwrapimport tracebackimport urllib.errorimport urllib.parse-import urllib.parseimport urllib.requestimport xml.etree.ElementTree as ETimport zipfile@@ -195,7 +194,7 @@ def normSlashes(path):def checkAllJARs(topDir, gitRevision, version):print(' verify JAR metadata/identity/no javax.* or java.* classes...')- for root, dirs, files in os.walk(topDir):+ for root, _, files in os.walk(topDir):normRoot = normSlashes(root)@@ -327,7 +326,7 @@ def testChanges(version, changesURLString):def testChangesText(dir, version):"Checks all CHANGES.txt under this dir."- for root, dirs, files in os.walk(dir):+ for root, _, files in os.walk(dir):# NOTE: O(N) but N should be smallish:if 'CHANGES.txt' in files:@@ -415,9 +414,12 @@ reUnixPath = re.compile(r'\b[a-zA-Z_]+=(?:"(?:\\"|[^"])*"' + '|(?:\\\\.|[^"\'\\sdef unix2win(matchobj):- if matchobj.group(1) is not None: return cygwinWindowsRoot + matchobj.group()- if matchobj.group(2) is not None: return '"%s%s' % (cygwinWindowsRoot, matchobj.group().lstrip('"'))- if matchobj.group(3) is not None: return "'%s%s" % (cygwinWindowsRoot, matchobj.group().lstrip("'"))+ if matchobj.group(1) is not None:+ return cygwinWindowsRoot + matchobj.group()+ if matchobj.group(2) is not None:+ return '"%s%s' % (cygwinWindowsRoot, matchobj.group().lstrip('"'))+ if matchobj.group(3) is not None:+ return "'%s%s" % (cygwinWindowsRoot, matchobj.group().lstrip("'"))return matchobj.group()@@ -427,7 +429,8 @@ def cygwinifyPaths(command):# values are automatically converted, so only paths outside of# environment variable values should be converted to Windows paths.# Assumption: all paths will be absolute.- if '; gradlew ' in command: command = reUnixPath.sub(unix2win, command)+ if '; gradlew ' in command:+ command = reUnixPath.sub(unix2win, command)return command@@ -450,7 +453,8 @@ def printFileContents(fileName):def run(command, logFile):- if cygwin: command = cygwinifyPaths(command)+ if cygwin:+ command = cygwinifyPaths(command)if os.system('%s > %s 2>&1' % (command, logFile)):logPath = os.path.abspath(logFile)print('\ncommand "%s" failed:' % command)@@ -488,18 +492,18 @@ def getDirEntries(urlString):path = path[:-1]if cygwin: # Convert Windows path to Cygwin pathpath = re.sub(r'^/([A-Za-z]):/', r'/cygdrive/\1/', path)- l = []+ files = []for ent in os.listdir(path):entPath = '%s/%s' % (path, ent)if os.path.isdir(entPath):entPath += '/'ent += '/'- l.append((ent, 'file://%s' % entPath))- l.sort()- return l+ files.append((ent, 'file://%s' % entPath))+ files.sort()+ return fileselse:links = getHREFs(urlString)- for i, (text, subURL) in enumerate(links):+ for i, (text, _) in enumerate(links):if text == 'Parent Directory' or text == '..':return links[(i+1):]@@ -518,10 +522,10 @@ def unpackAndVerify(java, tmpDir, artifact, gitRevision, version, testArgs):run('unzip %s/%s' % (tmpDir, artifact), unpackLogFile)# make sure it unpacks to proper subdir- l = os.listdir(destDir)+ files = os.listdir(destDir)expected = 'lucene-%s' % version- if l != [expected]:- raise RuntimeError('unpack produced entries %s; expected only %s' % (l, expected))+ if files != [expected]:+ raise RuntimeError('unpack produced entries %s; expected only %s' % (files, expected))unpackPath = '%s/%s' % (destDir, expected)verifyUnpacked(java, artifact, unpackPath, gitRevision, version, testArgs)@@ -733,7 +737,7 @@ def getBinaryDistFiles(tmpDir, version, baseURL):unpackLogFile = '%s/unpack-%s-getBinaryDistFiles.log' % (tmpDir, distribution)run('tar xzf %s/%s' % (tmpDir, distribution), unpackLogFile)distributionFiles = []- for root, dirs, files in os.walk(destDir):+ for root, _, files in os.walk(destDir):distributionFiles.extend([os.path.join(root, file) for file in files])return distributionFiles@@ -1037,9 +1041,9 @@ def getAllLuceneReleases():raise RuntimeError('failed to parse version: %s' % tup[-1])releases.add(tuple(int(x) for x in tup))- l = list(releases)- l.sort()- return l+ releaseList = list(releases)+ releaseList.sort()+ return releaseListdef confirmAllReleasesAreTestedForBackCompat(smokeVersion, unpackPath):@@ -1077,10 +1081,10 @@ def confirmAllReleasesAreTestedForBackCompat(smokeVersion, unpackPath):testedIndices.add(tup)- l = list(testedIndices)- l.sort()if False:- for release in l:+ indexList = list(testedIndices)+ indexList.sort()+ for release in indexList:print(' %s' % '.'.join(str(x) for x in release))allReleases = set(allReleases)@@ -1108,7 +1112,6 @@ def confirmAllReleasesAreTestedForBackCompat(smokeVersion, unpackPath):if len(notTested) > 0:notTested.sort()print('Releases that don\'t seem to be tested:')- failed = Truefor x in notTested:print(' %s' % '.'.join(str(y) for y in x))raise RuntimeError('some releases are not tested by TestBackwardsCompatibility?')