Skip to content

Commit aa437a8

Browse files
committed
python scripts: fix enough so that undefined variable analysis works (#14319)
Fix basic errors from linter and get undefined variable analysis working through the type-checker. This will detect common problems such as typos, instead of at runtime. The changes are straightforward: cleaning up imports, basic bad things.
1 parent 3c3174b commit aa437a8

10 files changed

+87
-105
lines changed

dev-tools/scripts/.editorconfig

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
root = true
2+
3+
[*.py]
4+
indent_style = space
5+
indent_size = 2
6+
end_of_line = lf
7+
charset = utf-8
8+
trim_trailing_whitespace = true
9+
insert_final_newline = true

dev-tools/scripts/addVersion.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,10 @@
1818
import os
1919
import sys
2020
sys.path.append(os.path.dirname(__file__))
21-
from scriptutil import *
22-
21+
from scriptutil import find_branch_type, find_current_version, run, update_file, Version
2322
import argparse
2423
import re
2524
from configparser import ConfigParser, ExtendedInterpolation
26-
from textwrap import dedent
2725

2826
def update_changes(filename, new_version, init_changes, headers):
2927
print(' adding new section to %s...' % filename, end='', flush=True)
@@ -55,7 +53,7 @@ def ensure_deprecated(buffer):
5553
if last.strip() != '@Deprecated':
5654
spaces = ' ' * (len(last) - len(last.lstrip()) - 1)
5755
del buffer[-1] # Remove comment closer line
58-
if (len(buffer) >= 4 and re.search('for Lucene.\s*$', buffer[-1]) != None):
56+
if (len(buffer) >= 4 and re.search('for Lucene.\s*$', buffer[-1]) is not None):
5957
del buffer[-3:] # drop the trailing lines '<p> / Use this to get the latest ... / ... for Lucene.'
6058
buffer.append(( '{0} * @deprecated ({1}) Use latest\n'
6159
+ '{0} */\n'

dev-tools/scripts/buildAndPushRelease.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,9 @@
2424
import subprocess
2525
from subprocess import TimeoutExpired
2626
import textwrap
27-
import urllib.request, urllib.error, urllib.parse
27+
import urllib.request
28+
import urllib.error
29+
import urllib.parse
2830
import xml.etree.ElementTree as ET
2931

3032
import scriptutil

dev-tools/scripts/githubPRs.py

+1-10
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,7 @@
2828
import re
2929
from github import Github
3030
from jira import JIRA
31-
from datetime import datetime
32-
from time import strftime
33-
try:
34-
from jinja2 import Environment, BaseLoader
35-
can_do_html = True
36-
except:
37-
can_do_html = False
31+
from jinja2 import Environment, BaseLoader
3832

3933
def read_config():
4034
parser = argparse.ArgumentParser(description='Find open Pull Requests that need attention')
@@ -51,9 +45,6 @@ def out(text):
5145
print(text)
5246

5347
def make_html(dict):
54-
if not can_do_html:
55-
print ("ERROR: Cannot generate HTML. Please install jinja2")
56-
sys.exit(1)
5748
global conf
5849
template = Environment(loader=BaseLoader).from_string("""
5950
<h1>Lucene Github PR report</h1>

dev-tools/scripts/pyproject.toml

+1-17
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ venvPath = "."
33
venv = ".venv"
44
# TODO: improve!
55
# typeCheckingMode = "strict"
6+
reportUnnecessaryTypeIgnoreComment = "error"
67
typeCheckingMode = "basic"
78
# TODO: we should fix these
89
reportArgumentType = "none"
@@ -13,7 +14,6 @@ reportOperatorIssue = "none"
1314
reportOptionalIterable = "none"
1415
reportOptionalMemberAccess = "none"
1516
reportOptionalSubscript = "none"
16-
reportUndefinedVariable = "none"
1717

1818
[tool.ruff]
1919
line-length = 200
@@ -25,22 +25,6 @@ indent-width = 2
2525

2626
# disabling/enabling of rules
2727
ignore = [
28-
# we should fix these
29-
"E401", # multiple imports on one line
30-
"E701", # multiple statements on one line
31-
"E711", # comparison should be "is not None"
32-
"E703", # unnecessary semicolon
33-
"E713", # test for membership should be "not in"
34-
"E714", # test for object identity should be "is not"
35-
"E722", # do not use bare except
36-
"E741", # ambiguous variable name
37-
"F401", # unused import
38-
"F403", # unable to detect undefined names due to star imports
39-
"F405", # undefined name or defined from star imports
40-
"F811", # redefinition of unused
41-
"F821", # undefined name
42-
"F841", # local variable assigned but never used
43-
4428
# These rules are always disabled: conflict with the formatter
4529
# don't enable! https://docs.astral.sh/ruff/formatter/#conflicting-lint-rules
4630
"W191", "E111", "E114", "E117", "D206", "D300", "Q000", "Q001",

dev-tools/scripts/releaseWizard.py

+28-34
Original file line numberDiff line numberDiff line change
@@ -51,15 +51,10 @@
5151
from datetime import timedelta
5252
from datetime import timezone
5353

54-
try:
55-
import holidays
56-
import yaml
57-
from ics import Calendar, Event
58-
from jinja2 import Environment
59-
except:
60-
print("You lack some of the module dependencies to run this script.")
61-
print("Please run 'pip3 install -r requirements.txt' and try again.")
62-
sys.exit(1)
54+
import holidays
55+
import yaml
56+
from ics import Calendar, Event
57+
from jinja2 import Environment
6358

6459
import scriptutil
6560
from consolemenu import ConsoleMenu
@@ -173,26 +168,26 @@ def check_prerequisites(todo=None):
173168
sys.exit("Script requires Python v3.4 or later")
174169
try:
175170
gpg_ver = run("gpg --version").splitlines()[0]
176-
except:
171+
except Exception:
177172
sys.exit("You will need gpg installed")
178-
if not 'GPG_TTY' in os.environ:
173+
if 'GPG_TTY' not in os.environ:
179174
print("WARNING: GPG_TTY environment variable is not set, GPG signing may not work correctly (try 'export GPG_TTY=$(tty)'")
180-
if not 'JAVA11_HOME' in os.environ:
175+
if 'JAVA11_HOME' not in os.environ:
181176
sys.exit("Please set environment variables JAVA11_HOME")
182177
try:
183178
asciidoc_ver = run("asciidoctor -V").splitlines()[0]
184-
except:
179+
except Exception:
185180
asciidoc_ver = ""
186181
print("WARNING: In order to export asciidoc version to HTML, you will need asciidoctor installed")
187182
try:
188183
git_ver = run("git --version").splitlines()[0]
189-
except:
184+
except Exception:
190185
sys.exit("You will need git installed")
191186
try:
192187
run("svn --version").splitlines()[0]
193-
except:
188+
except Exception:
194189
sys.exit("You will need svn installed")
195-
if not 'EDITOR' in os.environ:
190+
if 'EDITOR' not in os.environ:
196191
print("WARNING: Environment variable $EDITOR not set, using %s" % get_editor())
197192

198193
if todo:
@@ -285,7 +280,7 @@ def __init__(self, config_path, release_version, script_version):
285280
self.mirrored_versions = None
286281
try:
287282
self.script_branch_type = scriptutil.find_branch_type()
288-
except:
283+
except Exception:
289284
print("WARNING: This script shold (ideally) run from the release branch, not a feature branch (%s)" % self.script_branch)
290285
self.script_branch_type = 'feature'
291286
self.set_release_version(release_version)
@@ -510,7 +505,7 @@ def get_rc_number(self):
510505
def get_current_git_rev(self):
511506
try:
512507
return run("git rev-parse HEAD", cwd=self.get_git_checkout_folder()).strip()
513-
except:
508+
except Exception:
514509
return "<git-rev>"
515510

516511
def get_group_by_id(self, id):
@@ -717,7 +712,7 @@ def __init__(self, id, title, description=None, post_description=None, done=None
717712
if self.types:
718713
self.types = ensure_list(self.types)
719714
for t in self.types:
720-
if not t in ['minor', 'major', 'bugfix']:
715+
if t not in ['minor', 'major', 'bugfix']:
721716
sys.exit("Wrong Todo config for '%s'. Type needs to be either 'minor', 'major' or 'bugfix'" % self.id)
722717
if commands:
723718
self.commands.todo_id = self.id
@@ -867,7 +862,7 @@ def get_release_version():
867862
v = str(input("Which version are you releasing? (x.y.z) "))
868863
try:
869864
version = Version.parse(v)
870-
except:
865+
except Exception:
871866
print("Not a valid version %s" % v)
872867
return get_release_version()
873868

@@ -1011,8 +1006,8 @@ def generate_asciidoc():
10111006
fh.write("\n%s\n\n" % todo.get_post_description())
10121007
if todo.links:
10131008
fh.write("Links:\n\n")
1014-
for l in todo.links:
1015-
fh.write("* %s\n" % expand_jinja(l))
1009+
for link in todo.links:
1010+
fh.write("* %s\n" % expand_jinja(link))
10161011
fh.write("\n")
10171012

10181013
fh.close()
@@ -1031,7 +1026,7 @@ def load_rc():
10311026
try:
10321027
with open(lucenerc, 'r') as fp:
10331028
return json.load(fp)
1034-
except:
1029+
except Exception:
10351030
return None
10361031

10371032

@@ -1160,7 +1155,7 @@ def configure_pgp(gpg_todo):
11601155
print("Please either generate a strong key or reconfigure your client")
11611156
return False
11621157
print("Validated that your key is of type RSA and has a length >= 2048 (%s)" % length)
1163-
except:
1158+
except Exception:
11641159
print(textwrap.dedent("""\
11651160
Key not found on your private gpg keychain. In order to sign the release you'll
11661161
need to fix this, then try again"""))
@@ -1170,14 +1165,14 @@ def configure_pgp(gpg_todo):
11701165
sigs = 0
11711166
apache_sigs = 0
11721167
for line in lines:
1173-
if line.startswith("sig") and not gpg_id in line:
1168+
if line.startswith("sig") and gpg_id not in line:
11741169
sigs += 1
11751170
if '@apache.org' in line:
11761171
apache_sigs += 1
11771172
print("Your key has %s signatures, of which %s are by committers (@apache.org address)" % (sigs, apache_sigs))
11781173
if apache_sigs < 1:
11791174
print(textwrap.dedent("""\
1180-
Your key is not signed by any other committer.
1175+
Your key is not signed by any other committer.
11811176
Please review https://infra.apache.org/openpgp.html#apache-wot
11821177
and make sure to get your key signed until next time.
11831178
You may want to run 'gpg --refresh-keys' to refresh your keychain."""))
@@ -1220,7 +1215,7 @@ def configure_pgp(gpg_todo):
12201215
print(textwrap.dedent("""\
12211216
You need the passphrase to sign the release.
12221217
This script can prompt you securely for your passphrase (will not be stored) and pass it on to
1223-
buildAndPushRelease in a secure way. However, you can also configure your passphrase in advance
1218+
buildAndPushRelease in a secure way. However, you can also configure your passphrase in advance
12241219
and avoid having to type it in the terminal. This can be done with either a gpg-agent (for gpg tool)
12251220
or in gradle.properties or an ENV.var (for gradle), See ./gradlew helpPublishing for details."""))
12261221
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():
12511246

12521247
try:
12531248
ConsoleMenu(clear_screen=True)
1254-
except Exception as e:
1249+
except Exception:
12551250
sys.exit("You need to install 'consolemenu' package version 0.7.1 for the Wizard to function. Please run 'pip "
12561251
"install -r requirements.txt'")
12571252

@@ -1264,7 +1259,6 @@ def main():
12641259
release_root = os.path.expanduser("~/.lucene-releases")
12651260
if not load_rc() or c.init:
12661261
print("Initializing")
1267-
dir_ok = False
12681262
root = str(input("Choose root folder: [~/.lucene-releases] "))
12691263
if os.path.exists(root) and (not os.path.isdir(root) or not os.access(root, os.W_OK)):
12701264
sys.exit("Root %s exists but is not a directory or is not writable" % root)
@@ -1552,8 +1546,8 @@ def run(self): # pylint: disable=inconsistent-return-statements # TODO
15521546
for line in cmd.display_cmd():
15531547
print(" %s" % line)
15541548
print()
1555-
confirm_each = (not self.confirm_each_command is False) and len(commands) > 1
1556-
if not self.enable_execute is False:
1549+
confirm_each = (self.confirm_each_command is not False) and len(commands) > 1
1550+
if self.enable_execute is not False:
15571551
if self.run_text:
15581552
print("\n%s\n" % self.get_run_text())
15591553
if confirm_each:
@@ -1825,7 +1819,7 @@ def run(self, dict=None):
18251819
return result
18261820

18271821

1828-
def create_ical(todo): # pylint: disable=unused-argument
1822+
def create_ical(_todo): # pylint: disable=unused-argument
18291823
if ask_yes_no("Do you want to add a Calendar reminder for the close vote time?"):
18301824
c = Calendar()
18311825
e = Event()
@@ -1872,7 +1866,7 @@ def vote_close_72h_holidays():
18721866
return holidays if len(holidays) > 0 else None
18731867

18741868

1875-
def prepare_announce_lucene(todo): # pylint: disable=unused-argument
1869+
def prepare_announce_lucene(_todo): # pylint: disable=unused-argument
18761870
if not os.path.exists(lucene_news_file):
18771871
lucene_text = expand_jinja("(( template=announce_lucene ))")
18781872
with open(lucene_news_file, 'w') as fp:
@@ -1883,7 +1877,7 @@ def prepare_announce_lucene(todo): # pylint: disable=unused-argument
18831877
return True
18841878

18851879

1886-
def check_artifacts_available(todo): # pylint: disable=unused-argument
1880+
def check_artifacts_available(_todo): # pylint: disable=unused-argument
18871881
try:
18881882
cdnUrl = expand_jinja("https://dlcdn.apache.org/lucene/java/{{ release_version }}/lucene-{{ release_version }}-src.tgz.asc")
18891883
load(cdnUrl)

dev-tools/scripts/releasedJirasRegex.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
import sys
1919
import os
2020
sys.path.append(os.path.dirname(__file__))
21-
from scriptutil import *
21+
from scriptutil import Version
2222
import argparse
2323
import re
2424

0 commit comments

Comments
 (0)