Apache Lucene open-source search software
reformat the python code with 'make reformat' and enable format in CI check
Robert Muirec75fcad5a42
diff --git a/dev-tools/scripts/Makefile b/dev-tools/scripts/Makefileindex 97295299f1a..97ed7aaed24 100644--- a/dev-tools/scripts/Makefile+++ b/dev-tools/scripts/Makefile@@ -23,9 +23,7 @@ VENV=${PWD}/.venvSOURCES=$(wildcard *.py)# check formatting, linting, and types-# TODO: enable this when we're ready to reformat all code-# lint: format ruff pyright-lint: ruff pyright+lint: format ruff pyright# check all formattingformat: envdiff --git a/dev-tools/scripts/addBackcompatIndexes.py b/dev-tools/scripts/addBackcompatIndexes.pyindex e508ae0c8da..3ae0ea62d4c 100755--- a/dev-tools/scripts/addBackcompatIndexes.py+++ b/dev-tools/scripts/addBackcompatIndexes.py@@ -23,119 +23,109 @@import osimport sys-sys.path.append(os.path.dirname(__file__))-import scriptutil+sys.path.append(os.path.dirname(__file__))import argparse-import urllib.error-import urllib.requestimport reimport shutil+import urllib.error+import urllib.request++import scriptutil+def create_and_add_index(source, indextype, index_version, current_version, temp_dir):if not current_version.is_back_compat_with(index_version):- prefix = 'unsupported'+ prefix = "unsupported"else:- prefix = {- 'cfs': 'index',- 'nocfs': 'index',- 'sorted': 'sorted',- 'int7_hnsw': 'int7_hnsw',- 'moreterms': 'moreterms',- 'dvupdates': 'dvupdates',- 'emptyIndex': 'empty'- }[indextype]- if indextype in ('cfs', 'nocfs'):- filename = '%s.%s-%s.zip' % (prefix, index_version, indextype)+ prefix = {"cfs": "index", "nocfs": "index", "sorted": "sorted", "int7_hnsw": "int7_hnsw", "moreterms": "moreterms", "dvupdates": "dvupdates", "emptyIndex": "empty"}[indextype]+ if indextype in ("cfs", "nocfs"):+ filename = "%s.%s-%s.zip" % (prefix, index_version, indextype)else:- filename = '%s.%s.zip' % (prefix, index_version)+ filename = "%s.%s.zip" % (prefix, index_version)- print(' creating %s...' % filename, end='', flush=True)- module = 'backward-codecs'- index_dir = os.path.join('lucene', module, 'src/test/org/apache/lucene/backward_index')+ print(" creating %s..." % filename, end="", flush=True)+ module = "backward-codecs"+ index_dir = os.path.join("lucene", module, "src/test/org/apache/lucene/backward_index")if os.path.exists(os.path.join(index_dir, filename)):- print('uptodate')+ print("uptodate")returntest = {- 'cfs': 'testCreateCFS',- 'nocfs': 'testCreateNoCFS',- 'sorted': 'testCreateSortedIndex',- 'int7_hnsw': 'testCreateInt7HNSWIndices',- 'moreterms': 'testCreateMoreTermsIndex',- 'dvupdates': 'testCreateIndexWithDocValuesUpdates',- 'emptyIndex': 'testCreateEmptyIndex'+ "cfs": "testCreateCFS",+ "nocfs": "testCreateNoCFS",+ "sorted": "testCreateSortedIndex",+ "int7_hnsw": "testCreateInt7HNSWIndices",+ "moreterms": "testCreateMoreTermsIndex",+ "dvupdates": "testCreateIndexWithDocValuesUpdates",+ "emptyIndex": "testCreateEmptyIndex",}[indextype]- gradle_args = ' '.join([- '-Ptests.useSecurityManager=false',- '-p lucene/%s' % module,- 'test',- '--tests TestGenerateBwcIndices.%s' % test,- '-Dtests.bwcdir=%s' % temp_dir,- '-Dtests.codec=default'- ])+ gradle_args = " ".join(["-Ptests.useSecurityManager=false", "-p lucene/%s" % module, "test", "--tests TestGenerateBwcIndices.%s" % test, "-Dtests.bwcdir=%s" % temp_dir, "-Dtests.codec=default"])base_dir = os.getcwd()bc_index_file = os.path.join(temp_dir, filename)if os.path.exists(bc_index_file):- print('alreadyexists')+ print("alreadyexists")else:os.chdir(source)- scriptutil.run('./gradlew %s' % gradle_args)+ scriptutil.run("./gradlew %s" % gradle_args)if not os.path.exists(bc_index_file):- raise Exception("Expected file can't be found: %s" %bc_index_file)- print('done')+ raise Exception("Expected file can't be found: %s" % bc_index_file)+ print("done")- print(' adding %s...' % filename, end='', flush=True)- scriptutil.run('cp %s %s' % (bc_index_file, os.path.join(base_dir, index_dir)))+ print(" adding %s..." % filename, end="", flush=True)+ scriptutil.run("cp %s %s" % (bc_index_file, os.path.join(base_dir, index_dir)))os.chdir(base_dir)- print('done')+ print("done")+def update_backcompat_tests(index_version, current_version):- print(' adding new indexes to backcompat tests...', end='', flush=True)- module = 'lucene/backward-codecs'+ print(" adding new indexes to backcompat tests...", end="", flush=True)+ module = "lucene/backward-codecs"filename = Noneif not current_version.is_back_compat_with(index_version):- filename = '%s/src/test/org/apache/lucene/backward_index/unsupported_versions.txt' % module+ filename = "%s/src/test/org/apache/lucene/backward_index/unsupported_versions.txt" % moduleelse:- filename = '%s/src/test/org/apache/lucene/backward_index/versions.txt' % module+ filename = "%s/src/test/org/apache/lucene/backward_index/versions.txt" % module- strip_dash_suffix_re = re.compile(r'-.*')+ strip_dash_suffix_re = re.compile(r"-.*")def find_version(x):x = x.strip()- x = re.sub(strip_dash_suffix_re, '', x) # remove the -suffix if any+ x = re.sub(strip_dash_suffix_re, "", x) # remove the -suffix if anyreturn scriptutil.Version.parse(x)def edit(buffer, match, line):v = find_version(line)changed = Falseif v.on_or_after(index_version):- if not index_version.on_or_after(v):- buffer.append(('%s\n') % index_version)- changed = True+ if not index_version.on_or_after(v):+ buffer.append(("%s\n") % index_version)+ changed = Truebuffer.append(line)return changeddef append(buffer, changed):if changed:return changed- if not buffer[len(buffer)-1].endswith('\n'):- buffer.append('\n')- buffer.append(('%s\n') % index_version)+ if not buffer[len(buffer) - 1].endswith("\n"):+ buffer.append("\n")+ buffer.append(("%s\n") % index_version)return True- changed = scriptutil.update_file(filename, re.compile(r'.*'), edit, append)- print('done' if changed else 'uptodate')+ changed = scriptutil.update_file(filename, re.compile(r".*"), edit, append)+ print("done" if changed else "uptodate")+def check_backcompat_tests():- print(' checking backcompat tests...', end='', flush=True)- scriptutil.run('./gradlew -p lucene/backward-codecs test --tests TestGenerateBwcIndices')- print('ok')+ print(" checking backcompat tests...", end="", flush=True)+ scriptutil.run("./gradlew -p lucene/backward-codecs test --tests TestGenerateBwcIndices")+ print("ok")+def download_from_cdn(version, remotename, localname):- url = 'http://dlcdn.apache.org/lucene/java/%s/%s' % (version, remotename)+ url = "http://dlcdn.apache.org/lucene/java/%s/%s" % (version, remotename)try:urllib.request.urlretrieve(url, localname)return True@@ -144,8 +134,9 @@ def download_from_cdn(version, remotename, localname):return Falseraise e+def download_from_archives(version, remotename, localname):- url = 'http://archive.apache.org/dist/lucene/java/%s/%s' % (version, remotename)+ url = "http://archive.apache.org/dist/lucene/java/%s/%s" % (version, remotename)try:urllib.request.urlretrieve(url, localname)return True@@ -154,86 +145,84 @@ def download_from_archives(version, remotename, localname):return Falseraise e+def download_release(version, temp_dir, force):- print(' downloading %s source release...' % version, end='', flush=True)- source = os.path.join(temp_dir, 'lucene-%s' % version)+ print(" downloading %s source release..." % version, end="", flush=True)+ source = os.path.join(temp_dir, "lucene-%s" % version)if os.path.exists(source):if force:shutil.rmtree(source)else:- print('uptodate')+ print("uptodate")return source- filename = 'lucene-%s-src.tgz' % version+ filename = "lucene-%s-src.tgz" % versionsource_tgz = os.path.join(temp_dir, filename)- if not download_from_cdn(version, filename, source_tgz) and \- not download_from_archives(version, filename, source_tgz):- raise Exception('Could not find version %s in apache CDN or archives' % version)+ if not download_from_cdn(version, filename, source_tgz) and not download_from_archives(version, filename, source_tgz):+ raise Exception("Could not find version %s in apache CDN or archives" % version)olddir = os.getcwd()os.chdir(temp_dir)- scriptutil.run('tar -xvzf %s' % source_tgz)+ scriptutil.run("tar -xvzf %s" % source_tgz)os.chdir(olddir)- print('done')+ print("done")return source+def read_config():- parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,- description='''\+ parser = argparse.ArgumentParser(+ formatter_class=argparse.RawDescriptionHelpFormatter,+ description="""\Add backcompat index and test for new version. See:http://wiki.apache.org/lucene-java/ReleaseTodo#Generate_Backcompat_Indexes-''')- parser.add_argument('--force', action='store_true', default=False,- help='Redownload the version and rebuild, even if it already exists')- parser.add_argument('--no-cleanup', dest='cleanup', action='store_false', default=True,- help='Do not cleanup the built indexes, so that they can be reused ' +- 'for adding to another branch')- parser.add_argument('--temp-dir', metavar='DIR', default='/tmp/lucenebwc',- help='Temp directory to build backcompat indexes within')- parser.add_argument('version', type=scriptutil.Version.parse,- help='Version to add, of the form X.Y.Z')+""",+ )+ parser.add_argument("--force", action="store_true", default=False, help="Redownload the version and rebuild, even if it already exists")+ parser.add_argument("--no-cleanup", dest="cleanup", action="store_false", default=True, help="Do not cleanup the built indexes, so that they can be reused " + "for adding to another branch")+ parser.add_argument("--temp-dir", metavar="DIR", default="/tmp/lucenebwc", help="Temp directory to build backcompat indexes within")+ parser.add_argument("version", type=scriptutil.Version.parse, help="Version to add, of the form X.Y.Z")c = parser.parse_args()return c+def main():c = read_config()if not os.path.exists(c.temp_dir):os.makedirs(c.temp_dir)- print('\nCreating backwards compatibility indexes')+ print("\nCreating backwards compatibility indexes")source = download_release(c.version, c.temp_dir, c.force)current_version = scriptutil.Version.parse(scriptutil.find_current_version())- create_and_add_index(source, 'cfs', c.version, current_version, c.temp_dir)- create_and_add_index(source, 'nocfs', c.version, current_version, c.temp_dir)- create_and_add_index(source, 'int7_hnsw', c.version, current_version, c.temp_dir)- should_make_sorted = current_version.is_back_compat_with(c.version) \- and (c.version.major > 6 or (c.version.major == 6 and c.version.minor >= 2))+ create_and_add_index(source, "cfs", c.version, current_version, c.temp_dir)+ create_and_add_index(source, "nocfs", c.version, current_version, c.temp_dir)+ create_and_add_index(source, "int7_hnsw", c.version, current_version, c.temp_dir)+ should_make_sorted = current_version.is_back_compat_with(c.version) and (c.version.major > 6 or (c.version.major == 6 and c.version.minor >= 2))if should_make_sorted:- create_and_add_index(source, 'sorted', c.version, current_version, c.temp_dir)+ create_and_add_index(source, "sorted", c.version, current_version, c.temp_dir)if c.version.minor == 0 and c.version.bugfix == 0 and current_version.is_back_compat_with(c.version):- create_and_add_index(source, 'moreterms', c.version, current_version, c.temp_dir)- create_and_add_index(source, 'dvupdates', c.version, current_version, c.temp_dir)- create_and_add_index(source, 'emptyIndex', c.version, current_version, c.temp_dir)- print ('\nMANUAL UPDATE REQUIRED: edit TestGenerateBwcIndices to enable moreterms, dvupdates, and empty index testing')+ create_and_add_index(source, "moreterms", c.version, current_version, c.temp_dir)+ create_and_add_index(source, "dvupdates", c.version, current_version, c.temp_dir)+ create_and_add_index(source, "emptyIndex", c.version, current_version, c.temp_dir)+ print("\nMANUAL UPDATE REQUIRED: edit TestGenerateBwcIndices to enable moreterms, dvupdates, and empty index testing")- print('\nAdding backwards compatibility tests')+ print("\nAdding backwards compatibility tests")update_backcompat_tests(c.version, current_version)-- print('\nTesting changes')+ print("\nTesting changes")check_backcompat_tests()if c.cleanup:- print('\nCleaning up')- print(' deleting %s...' % c.temp_dir, end='', flush=True)+ print("\nCleaning up")+ print(" deleting %s..." % c.temp_dir, end="", flush=True)shutil.rmtree(c.temp_dir)- print('done')+ print("done")print()-if __name__ == '__main__':++if __name__ == "__main__":try:main()except KeyboardInterrupt:- print('\nRecieved Ctrl-C, exiting early')+ print("\nRecieved Ctrl-C, exiting early")diff --git a/dev-tools/scripts/addVersion.py b/dev-tools/scripts/addVersion.pyindex bc692825458..75632d6a6dd 100755--- a/dev-tools/scripts/addVersion.py+++ b/dev-tools/scripts/addVersion.py@@ -17,15 +17,19 @@import osimport sys+sys.path.append(os.path.dirname(__file__))-from scriptutil import find_branch_type, find_current_version, run, update_file, Versionimport argparseimport refrom configparser import ConfigParser, ExtendedInterpolation+from scriptutil import Version, find_branch_type, find_current_version, run, update_file++def update_changes(filename, new_version, init_changes, headers):- print(' adding new section to %s...' % filename, end='', flush=True)- matcher = re.compile(r'\d+\.\d+\.\d+\s+===')+ print(" adding new section to %s..." % filename, end="", flush=True)+ matcher = re.compile(r"\d+\.\d+\.\d+\s+===")+def edit(buffer, match, line):if new_version.dot in line:return None@@ -34,63 +38,60 @@ def update_changes(filename, new_version, init_changes, headers):buffer.append(line.replace(match.group(0), new_version.dot))buffer.append(init_changes)for header in headers:- buffer.append('%s\n---------------------\n(No changes)\n\n' % header)+ buffer.append("%s\n---------------------\n(No changes)\n\n" % header)buffer.append(line)return match is not Nonechanged = update_file(filename, matcher, edit)- print('done' if changed else 'uptodate')+ print("done" if changed else "uptodate")+def add_constant(new_version, deprecate):- filename = 'lucene/core/src/java/org/apache/lucene/util/Version.java'- print(' adding constant %s...' % new_version.constant, end='', flush=True)- constant_prefix = 'public static final Version LUCENE_'+ filename = "lucene/core/src/java/org/apache/lucene/util/Version.java"+ print(" adding constant %s..." % new_version.constant, end="", flush=True)+ constant_prefix = "public static final Version LUCENE_"matcher = re.compile(constant_prefix)- prev_matcher = new_version.make_previous_matcher(prefix=constant_prefix, sep='_')+ prev_matcher = new_version.make_previous_matcher(prefix=constant_prefix, sep="_")def ensure_deprecated(buffer):last = buffer[-1]- 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(r'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'- + '{0}@Deprecated\n').format(spaces, new_version))+ 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(r"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" + "{0}@Deprecated\n").format(spaces, new_version))def buffer_constant(buffer, line):- spaces = ' ' * (len(line) - len(line.lstrip()))- buffer.append(( '\n{0}/**\n'- + '{0} * Match settings and bugs in Lucene\'s {1} release.\n')- .format(spaces, new_version))+ spaces = " " * (len(line) - len(line.lstrip()))+ buffer.append(("\n{0}/**\n" + "{0} * Match settings and bugs in Lucene's {1} release.\n").format(spaces, new_version))if deprecate:- buffer.append('%s * @deprecated Use latest\n' % spaces)+ buffer.append("%s * @deprecated Use latest\n" % spaces)else:- buffer.append(( '{0} * <p>Use this to get the latest & greatest settings, bug fixes, etc, for Lucene.\n').format(spaces))- buffer.append('%s */\n' % spaces)+ buffer.append(("{0} * <p>Use this to get the latest & greatest settings, bug fixes, etc, for Lucene.\n").format(spaces))+ buffer.append("%s */\n" % spaces)if deprecate:- buffer.append('%s@Deprecated\n' % spaces)- buffer.append('{0}public static final Version {1} = new Version({2}, {3}, {4});\n'.format- (spaces, new_version.constant, new_version.major, new_version.minor, new_version.bugfix))+ buffer.append("%s@Deprecated\n" % spaces)+ buffer.append("{0}public static final Version {1} = new Version({2}, {3}, {4});\n".format(spaces, new_version.constant, new_version.major, new_version.minor, new_version.bugfix))class Edit(object):found = -1+def __call__(self, buffer, match, line):if new_version.constant in line:- return None # constant already exists+ return None # constant already exists# outer match is just to find lines declaring version constantsmatch = prev_matcher.search(line)if match is not None:- ensure_deprecated(buffer) # old version should be deprecated- self.found = len(buffer) + 1 # extra 1 for buffering current line below+ ensure_deprecated(buffer) # old version should be deprecated+ self.found = len(buffer) + 1 # extra 1 for buffering current line belowelif self.found != -1:# we didn't match, but we previously had a match, so insert new version here# first find where to insert (first empty line before current constant)c = []buffer_constant(c, line)- tmp = buffer[self.found:]- buffer[self.found:] = c+ tmp = buffer[self.found :]+ buffer[self.found :] = cbuffer.extend(tmp)buffer.append(line)return True@@ -99,97 +100,105 @@ def add_constant(new_version, deprecate):return Falsechanged = update_file(filename, matcher, Edit())- print('done' if changed else 'uptodate')+ print("done" if changed else "uptodate")+def update_build_version(new_version):- print(' changing baseVersion...', end='', flush=True)- filename = 'build.gradle'+ print(" changing baseVersion...", end="", flush=True)+ filename = "build.gradle"+def edit(buffer, _, line):if new_version.dot in line:return None- buffer.append(' String baseVersion = \'' + new_version.dot + '\'\n')+ buffer.append(" String baseVersion = '" + new_version.dot + "'\n")return Trueversion_prop_re = re.compile(r'baseVersion\s*=\s*([\'"])(.*)\1')changed = update_file(filename, version_prop_re, edit)- print('done' if changed else 'uptodate')+ print("done" if changed else "uptodate")+def update_latest_constant(new_version):- print(' changing Version.LATEST to %s...' % new_version.constant, end='', flush=True)- filename = 'lucene/core/src/java/org/apache/lucene/util/Version.java'- matcher = re.compile('public static final Version LATEST')+ print(" changing Version.LATEST to %s..." % new_version.constant, end="", flush=True)+ filename = "lucene/core/src/java/org/apache/lucene/util/Version.java"+ matcher = re.compile("public static final Version LATEST")+def edit(buffer, _, line):if new_version.constant in line:return None- buffer.append(line.rpartition('=')[0] + ('= %s;\n' % new_version.constant))+ buffer.append(line.rpartition("=")[0] + ("= %s;\n" % new_version.constant))return Truechanged = update_file(filename, matcher, edit)- print('done' if changed else 'uptodate')+ print("done" if changed else "uptodate")+def onerror(x):raise x+def check_lucene_version_tests():- print(' checking lucene version tests...', end='', flush=True)- run('./gradlew -p lucene/core test --tests TestVersion')- print('ok')+ print(" checking lucene version tests...", end="", flush=True)+ run("./gradlew -p lucene/core test --tests TestVersion")+ print("ok")+def read_config(current_version):- parser = argparse.ArgumentParser(description='Add a new version to CHANGES, to Version.java and build.gradle files')- parser.add_argument('version', type=Version.parse)+ parser = argparse.ArgumentParser(description="Add a new version to CHANGES, to Version.java and build.gradle files")+ parser.add_argument("version", type=Version.parse)newconf = parser.parse_args()newconf.branch_type = find_branch_type()newconf.is_latest_version = newconf.version.on_or_after(current_version)- print ("branch_type is %s " % newconf.branch_type)+ print("branch_type is %s " % newconf.branch_type)return newconf+# Hack ConfigParser, designed to parse INI files, to parse & interpolate Java .properties filesdef parse_properties_file(filename):- contents = open(filename, encoding='ISO-8859-1').read().replace('%', '%%') # Escape interpolation metachar- parser = ConfigParser(interpolation=ExtendedInterpolation()) # Handle ${property-name} interpolation- parser.read_string("[DUMMY_SECTION]\n" + contents) # Add required section- return dict(parser.items('DUMMY_SECTION'))+ contents = open(filename, encoding="ISO-8859-1").read().replace("%", "%%") # Escape interpolation metachar+ parser = ConfigParser(interpolation=ExtendedInterpolation()) # Handle ${property-name} interpolation+ parser.read_string("[DUMMY_SECTION]\n" + contents) # Add required section+ return dict(parser.items("DUMMY_SECTION"))def main():- if not os.path.exists('build.gradle'):+ if not os.path.exists("build.gradle"):sys.exit("Tool must be run from the root of a source checkout.")current_version = Version.parse(find_current_version())newconf = read_config(current_version)is_bugfix = newconf.version.is_bugfix_release()- print('\nAdding new version %s' % newconf.version)+ print("\nAdding new version %s" % newconf.version)# See LUCENE-8883 for some thoughts on which categories to use- update_changes('lucene/CHANGES.txt', newconf.version, '\n',- ['Bug Fixes'] if is_bugfix else ['API Changes', 'New Features', 'Improvements', 'Optimizations', 'Bug Fixes', 'Other'])+ update_changes("lucene/CHANGES.txt", newconf.version, "\n", ["Bug Fixes"] if is_bugfix else ["API Changes", "New Features", "Improvements", "Optimizations", "Bug Fixes", "Other"])latest_or_backcompat = newconf.is_latest_version or current_version.is_back_compat_with(newconf.version)if latest_or_backcompat:add_constant(newconf.version, not newconf.is_latest_version)else:- print('\nNot adding constant for version %s because it is no longer supported' % newconf.version)+ print("\nNot adding constant for version %s because it is no longer supported" % newconf.version)if newconf.is_latest_version:- print('\nUpdating latest version')+ print("\nUpdating latest version")update_build_version(newconf.version)update_latest_constant(newconf.version)if newconf.version.is_major_release():- print('\nTODO: ')- print(' - Move backcompat oldIndexes to unsupportedIndexes in TestBackwardsCompatibility')- print(' - Update IndexFormatTooOldException throw cases')+ print("\nTODO: ")+ print(" - Move backcompat oldIndexes to unsupportedIndexes in TestBackwardsCompatibility")+ print(" - Update IndexFormatTooOldException throw cases")elif latest_or_backcompat:- print('\nTesting changes')+ print("\nTesting changes")check_lucene_version_tests()print()-if __name__ == '__main__':++if __name__ == "__main__":try:main()except KeyboardInterrupt:- print('\nReceived Ctrl-C, exiting early')+ print("\nReceived Ctrl-C, exiting early")diff --git a/dev-tools/scripts/buildAndPushRelease.py b/dev-tools/scripts/buildAndPushRelease.pyindex 3e41c1a9bbd..85952be2dd0 100755--- a/dev-tools/scripts/buildAndPushRelease.py+++ b/dev-tools/scripts/buildAndPushRelease.py@@ -17,39 +17,41 @@import argparseimport datetime-import re-import timeimport os-import sys+import reimport subprocess-from subprocess import TimeoutExpired+import sysimport textwrap-import urllib.request+import timeimport urllib.errorimport urllib.parse+import urllib.requestimport xml.etree.ElementTree as ET+from subprocess import TimeoutExpiredimport scriptutil-LOG = '/tmp/release.log'+LOG = "/tmp/release.log"dev_mode = False+def log(msg):- f = open(LOG, mode='ab')- f.write(msg.encode('utf-8'))+ f = open(LOG, mode="ab")+ f.write(msg.encode("utf-8"))f.close()+def run(command):- log('\n\n%s: RUN: %s\n' % (datetime.datetime.now(), command))- if os.system('%s >> %s 2>&1' % (command, LOG)):- msg = ' FAILED: %s [see log %s]' % (command, LOG)+ log("\n\n%s: RUN: %s\n" % (datetime.datetime.now(), command))+ if os.system("%s >> %s 2>&1" % (command, LOG)):+ msg = " FAILED: %s [see log %s]" % (command, LOG)print(msg)raise RuntimeError(msg)def runAndSendGPGPassword(command, password):p = subprocess.Popen(command, shell=True, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)- f = open(LOG, 'ab')+ f = open(LOG, "ab")while True:assert p.stdoutassert p.stdin@@ -58,89 +60,90 @@ def runAndSendGPGPassword(command, password):if len(line) == 0:breakf.write(line)- if line.find(b'Enter GPG keystore password:') != -1:+ if line.find(b"Enter GPG keystore password:") != -1:time.sleep(1.0)- p.stdin.write((password + '\n').encode('UTF-8'))- p.stdin.write('\n'.encode('UTF-8'))+ p.stdin.write((password + "\n").encode("UTF-8"))+ p.stdin.write("\n".encode("UTF-8"))try:result = p.wait(timeout=120)if result != 0:- msg = ' FAILED: %s [see log %s]' % (command, LOG)+ msg = " FAILED: %s [see log %s]" % (command, LOG)print(msg)raise RuntimeError(msg)except TimeoutExpired:- msg = ' FAILED: %s [timed out after 2 minutes; see log %s]' % (command, LOG)+ msg = " FAILED: %s [timed out after 2 minutes; see log %s]" % (command, LOG)print(msg)raise RuntimeError(msg)+def load(urlString, encoding="utf-8"):try:content = urllib.request.urlopen(urlString).read().decode(encoding)except Exception as e:- print('Retrying download of url %s after exception: %s' % (urlString, e))+ print("Retrying download of url %s after exception: %s" % (urlString, e))content = urllib.request.urlopen(urlString).read().decode(encoding)return content+def getGitRev():if not dev_mode:- status = os.popen('git status').read().strip()- if 'nothing to commit, working directory clean' not in status and 'nothing to commit, working tree clean' not in status:- raise RuntimeError('git clone is dirty:\n\n%s' % status)- if 'Your branch is ahead of' in status:- raise RuntimeError('Your local branch is ahead of the remote? git status says:\n%s' % status)- print(' git clone is clean')+ status = os.popen("git status").read().strip()+ if "nothing to commit, working directory clean" not in status and "nothing to commit, working tree clean" not in status:+ raise RuntimeError("git clone is dirty:\n\n%s" % status)+ if "Your branch is ahead of" in status:+ raise RuntimeError("Your local branch is ahead of the remote? git status says:\n%s" % status)+ print(" git clone is clean")else:- print(' Ignoring dirty git clone due to dev-mode')- return os.popen('git rev-parse HEAD').read().strip()+ print(" Ignoring dirty git clone due to dev-mode")+ return os.popen("git rev-parse HEAD").read().strip()def prepare(root, version, pause_before_sign, gpg_key_id, gpg_password, gpg_home=None, sign_gradle=False):print()- print('Prepare release...')+ print("Prepare release...")if os.path.exists(LOG):os.remove(LOG)if not dev_mode:os.chdir(root)- print(' git pull...')- run('git pull')+ print(" git pull...")+ run("git pull")else:- print(' Development mode, not running git pull')+ print(" Development mode, not running git pull")rev = getGitRev()- print(' git rev: %s' % rev)- log('\nGIT rev: %s\n' % rev)+ print(" git rev: %s" % rev)+ log("\nGIT rev: %s\n" % rev)- print(' Check DOAP files')+ print(" Check DOAP files")checkDOAPfiles(version)if not dev_mode:- print(' ./gradlew --stacktrace --no-daemon clean')- run('./gradlew --stacktrace --no-daemon clean')- print(' ./gradlew --stacktrace --no-daemon check')- run('./gradlew --stacktrace --no-daemon check')+ print(" ./gradlew --stacktrace --no-daemon clean")+ run("./gradlew --stacktrace --no-daemon clean")+ print(" ./gradlew --stacktrace --no-daemon check")+ run("./gradlew --stacktrace --no-daemon check")else:- print(' skipping precommit check due to dev-mode')+ print(" skipping precommit check due to dev-mode")if pause_before_sign:input("Tests complete! Please press ENTER to proceed to assembleRelease: ")- print(' prepare-release')- cmd = './gradlew --stacktrace --no-daemon assembleRelease' \- ' -Dversion.release=%s' % version+ print(" prepare-release")+ cmd = "./gradlew --stacktrace --no-daemon assembleRelease -Dversion.release=%s" % versionif dev_mode:- cmd += ' -Pvalidation.git.failOnModified=false'+ cmd += " -Pvalidation.git.failOnModified=false"if gpg_key_id is not None:- cmd += ' -Psign --max-workers 2'+ cmd += " -Psign --max-workers 2"if sign_gradle:print(" Signing method is gradle java-plugin")cmd += ' -Psigning.keyId="%s"' % gpg_key_idif gpg_home is not None:- cmd += ' -Psigning.secretKeyRingFile="%s"' % os.path.join(gpg_home, 'secring.gpg')+ cmd += ' -Psigning.secretKeyRingFile="%s"' % os.path.join(gpg_home, "secring.gpg")if gpg_password is not None:# Pass gpg passphrase as env.var to gradle rather than as plaintext argument- os.environ['ORG_GRADLE_PROJECT_signingPassword'] = gpg_password+ os.environ["ORG_GRADLE_PROJECT_signingPassword"] = gpg_passwordelse:print(" Signing method is gpg tool")cmd += ' -PuseGpg -Psigning.gnupg.keyName="%s"' % gpg_key_id@@ -153,88 +156,91 @@ def prepare(root, version, pause_before_sign, gpg_key_id, gpg_password, gpg_homeelse:run(cmd)- print(' done!')+ print(" done!")print()return rev-reVersion1 = re.compile(r'\>(\d+)\.(\d+)\.(\d+)(-alpha|-beta)?/\<', re.IGNORECASE)-reVersion2 = re.compile(r'-(\d+)\.(\d+)\.(\d+)(-alpha|-beta)?\.zip<', re.IGNORECASE)-reDoapRevision = re.compile(r'(\d+)\.(\d+)(?:\.(\d+))?(-alpha|-beta)?', re.IGNORECASE)++reVersion1 = re.compile(r"\>(\d+)\.(\d+)\.(\d+)(-alpha|-beta)?/\<", re.IGNORECASE)+reVersion2 = re.compile(r"-(\d+)\.(\d+)\.(\d+)(-alpha|-beta)?\.zip<", re.IGNORECASE)+reDoapRevision = re.compile(r"(\d+)\.(\d+)(?:\.(\d+))?(-alpha|-beta)?", re.IGNORECASE)++def checkDOAPfiles(version):# In Lucene DOAP file, verify presence of all releases less than the one being produced.errorMessages = []- for product in ['lucene']:- url = 'https://archive.apache.org/dist/lucene/%s' % ('java' if product == 'lucene' else product)+ for product in ["lucene"]:+ url = "https://archive.apache.org/dist/lucene/%s" % ("java" if product == "lucene" else product)distpage = load(url)releases = set()for regex in reVersion1, reVersion2:for tup in regex.findall(distpage):- if tup[0] in ('1', '2'): # Ignore 1.X and 2.X releases+ if tup[0] in ("1", "2"): # Ignore 1.X and 2.X releasescontinuereleases.add(normalizeVersion(tup))- doapNS = '{http://usefulinc.com/ns/doap#}'- xpathRevision = '{0}Project/{0}release/{0}Version/{0}revision'.format(doapNS)+ doapNS = "{http://usefulinc.com/ns/doap#}"+ xpathRevision = "{0}Project/{0}release/{0}Version/{0}revision".format(doapNS)doapFile = "dev-tools/doap/%s.rdf" % producttreeRoot = ET.parse(doapFile).getroot()doapRevisions = set()for revision in treeRoot.findall(xpathRevision):- if (revision.text and (match := reDoapRevision.match(revision.text))):- if (match.group(1) not in ('0', '1', '2')): # Ignore 0.X, 1.X and 2.X revisions+ if revision.text and (match := reDoapRevision.match(revision.text)):+ if match.group(1) not in ("0", "1", "2"): # Ignore 0.X, 1.X and 2.X revisionsdoapRevisions.add(normalizeVersion(match.groups()))else:- errorMessages.append('ERROR: Failed to parse revision: %s in %s' % (revision.text, doapFile))+ errorMessages.append("ERROR: Failed to parse revision: %s in %s" % (revision.text, doapFile))missingDoapRevisions = set()for release in releases:- if release not in doapRevisions and release < version: # Ignore releases greater than the one being produced+ if release not in doapRevisions and release < version: # Ignore releases greater than the one being producedmissingDoapRevisions.add(release)if len(missingDoapRevisions) > 0:- errorMessages.append('ERROR: Missing revision(s) in %s: %s' % (doapFile, ', '.join(sorted(missingDoapRevisions))))- if (len(errorMessages) > 0):- raise RuntimeError('\n%s\n(Hint: copy/paste from the stable branch version of the file(s).)'- % '\n'.join(errorMessages))+ errorMessages.append("ERROR: Missing revision(s) in %s: %s" % (doapFile, ", ".join(sorted(missingDoapRevisions))))+ if len(errorMessages) > 0:+ raise RuntimeError("\n%s\n(Hint: copy/paste from the stable branch version of the file(s).)" % "\n".join(errorMessages))+def normalizeVersion(tup):- suffix = ''- if tup[-1] is not None and tup[-1].lower() == '-alpha':- tup = tup[:(len(tup) - 1)]- suffix = '-ALPHA'- elif tup[-1] is not None and tup[-1].lower() == '-beta':- tup = tup[:(len(tup) - 1)]- suffix = '-BETA'- while tup[-1] in ('', None):- tup = tup[:(len(tup) - 1)]+ suffix = ""+ if tup[-1] is not None and tup[-1].lower() == "-alpha":+ tup = tup[: (len(tup) - 1)]+ suffix = "-ALPHA"+ elif tup[-1] is not None and tup[-1].lower() == "-beta":+ tup = tup[: (len(tup) - 1)]+ suffix = "-BETA"+ while tup[-1] in ("", None):+ tup = tup[: (len(tup) - 1)]while len(tup) < 3:- tup = tup + ('0',)- return '.'.join(tup) + suffix+ tup = tup + ("0",)+ return ".".join(tup) + suffixdef pushLocal(version, root, rcNum, localDir):- print('Push local [%s]...' % localDir)+ print("Push local [%s]..." % localDir)os.makedirs(localDir)- lucene_dist_dir = '%s/lucene/distribution/build/release' % root- rev = open('%s/lucene/distribution/build/release/.gitrev' % root, encoding='UTF-8').read()+ lucene_dist_dir = "%s/lucene/distribution/build/release" % root+ rev = open("%s/lucene/distribution/build/release/.gitrev" % root, encoding="UTF-8").read()- dir = 'lucene-%s-RC%d-rev-%s' % (version, rcNum, rev)- os.makedirs('%s/%s/lucene' % (localDir, dir))- print(' Lucene')+ dir = "lucene-%s-RC%d-rev-%s" % (version, rcNum, rev)+ os.makedirs("%s/%s/lucene" % (localDir, dir))+ print(" Lucene")os.chdir(lucene_dist_dir)- print(' archive...')- if os.path.exists('lucene.tar'):- os.remove('lucene.tar')- run('tar cf lucene.tar *')+ print(" archive...")+ if os.path.exists("lucene.tar"):+ os.remove("lucene.tar")+ run("tar cf lucene.tar *")- os.chdir('%s/%s/lucene' % (localDir, dir))- print(' extract...')+ os.chdir("%s/%s/lucene" % (localDir, dir))+ print(" extract...")run('tar xf "%s/lucene.tar"' % lucene_dist_dir)- os.remove('%s/lucene.tar' % lucene_dist_dir)- os.chdir('..')+ os.remove("%s/lucene.tar" % lucene_dist_dir)+ os.chdir("..")- print(' chmod...')- run('chmod -R a+rX-w .')+ print(" chmod...")+ run("chmod -R a+rX-w .")- print(' done!')- return 'file://%s/%s' % (os.path.abspath(localDir), dir)+ print(" done!")+ return "file://%s/%s" % (os.path.abspath(localDir), dir)def read_version(path):@@ -242,63 +248,60 @@ def read_version(path):def parse_config():- epilogue = textwrap.dedent('''+ epilogue = textwrap.dedent("""Example usage for a Release Manager:python3 -u dev-tools/scripts/buildAndPushRelease.py --push-local /tmp/releases/6.0.1 --sign 6E68DA61 --rc-num 1- ''')- description = 'Utility to build, push, and test a release.'- parser = argparse.ArgumentParser(description=description, epilog=epilogue,- formatter_class=argparse.RawDescriptionHelpFormatter)- parser.add_argument('--no-prepare', dest='prepare', default=True, action='store_false',- help='Use the already built release in the provided checkout')- parser.add_argument('--local-keys', metavar='PATH',- help='Uses local KEYS file to validate presence of RM\'s gpg key')- parser.add_argument('--push-local', metavar='PATH',- help='Push the release to the local path')- parser.add_argument('--pause-before-sign', default=False, action='store_true',- help='Pause for user confirmation before the assembleRelease step (to prevent timeout on gpg pinentry')- parser.add_argument('--sign', metavar='KEYID',- help='Sign the release with the given gpg key')- parser.add_argument('--sign-method-gradle', dest='sign_method_gradle', default=False, action='store_true',- help='Use Gradle built-in GPG signing instead of gpg command for signing artifacts. '- ' This may require --gpg-secring argument if your keychain cannot be resolved automatically.')- parser.add_argument('--gpg-pass-noprompt', dest='gpg_pass_noprompt', default=False, action='store_true',- help='Do not prompt for gpg passphrase. For the default gnupg method, this means your gpg-agent'- ' needs a non-TTY pin-entry program. For gradle signing method, passphrase must be provided'- ' in gradle.properties or by env.var/sysprop. See ./gradlew helpPublishing for more info')- parser.add_argument('--gpg-home', metavar='PATH',- help='Path to gpg home containing your secring.gpg'- ' Optional, will use $HOME/.gnupg/secring.gpg by default')- parser.add_argument('--rc-num', metavar='NUM', type=int, default=1,- help='Release Candidate number. Default: 1')- parser.add_argument('--root', metavar='PATH', default='.',- help='Root of Git working tree for lucene. Default: "." (the current directory)')- parser.add_argument('--logfile', metavar='PATH',- help='Specify log file path (default /tmp/release.log)')- parser.add_argument('--dev-mode', default=False, action='store_true',- help='Enable development mode, which disables some strict checks')+ """)+ description = "Utility to build, push, and test a release."+ parser = argparse.ArgumentParser(description=description, epilog=epilogue, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--no-prepare", dest="prepare", default=True, action="store_false", help="Use the already built release in the provided checkout")+ parser.add_argument("--local-keys", metavar="PATH", help="Uses local KEYS file to validate presence of RM's gpg key")+ parser.add_argument("--push-local", metavar="PATH", help="Push the release to the local path")+ parser.add_argument("--pause-before-sign", default=False, action="store_true", help="Pause for user confirmation before the assembleRelease step (to prevent timeout on gpg pinentry")+ parser.add_argument("--sign", metavar="KEYID", help="Sign the release with the given gpg key")+ parser.add_argument(+ "--sign-method-gradle",+ dest="sign_method_gradle",+ default=False,+ action="store_true",+ help="Use Gradle built-in GPG signing instead of gpg command for signing artifacts. This may require --gpg-secring argument if your keychain cannot be resolved automatically.",+ )+ parser.add_argument(+ "--gpg-pass-noprompt",+ dest="gpg_pass_noprompt",+ default=False,+ action="store_true",+ help="Do not prompt for gpg passphrase. For the default gnupg method, this means your gpg-agent"+ " needs a non-TTY pin-entry program. For gradle signing method, passphrase must be provided"+ " in gradle.properties or by env.var/sysprop. See ./gradlew helpPublishing for more info",+ )+ parser.add_argument("--gpg-home", metavar="PATH", help="Path to gpg home containing your secring.gpg Optional, will use $HOME/.gnupg/secring.gpg by default")+ parser.add_argument("--rc-num", metavar="NUM", type=int, default=1, help="Release Candidate number. Default: 1")+ parser.add_argument("--root", metavar="PATH", default=".", help='Root of Git working tree for lucene. Default: "." (the current directory)')+ parser.add_argument("--logfile", metavar="PATH", help="Specify log file path (default /tmp/release.log)")+ parser.add_argument("--dev-mode", default=False, action="store_true", help="Enable development mode, which disables some strict checks")config = parser.parse_args()if not config.prepare and config.sign:- parser.error('Cannot sign already built release')+ parser.error("Cannot sign already built release")if config.push_local is not None and os.path.exists(config.push_local):- parser.error('Cannot push to local path that already exists')+ parser.error("Cannot push to local path that already exists")if config.rc_num <= 0:- parser.error('Release Candidate number must be a positive integer')+ parser.error("Release Candidate number must be a positive integer")if not os.path.isdir(config.root):parser.error('Root path "%s" is not a directory' % config.root)if config.local_keys is not None and not os.path.exists(config.local_keys):parser.error('Local KEYS file "%s" not found' % config.local_keys)- if config.gpg_home and not os.path.exists(os.path.join(config.gpg_home, 'secring.gpg')):- parser.error('Specified gpg home %s does not exist or does not contain a secring.gpg' % config.gpg_home)+ if config.gpg_home and not os.path.exists(os.path.join(config.gpg_home, "secring.gpg")):+ parser.error("Specified gpg home %s does not exist or does not contain a secring.gpg" % config.gpg_home)global dev_modeif config.dev_mode:print("Enabling development mode - DO NOT USE FOR ACTUAL RELEASE!")dev_mode = Truecwd = os.getcwd()os.chdir(config.root)- config.root = os.getcwd() # Absolutize root dir- if os.system('git rev-parse') or 2 != len([d for d in ('dev-tools','lucene') if os.path.isdir(d)]):+ config.root = os.getcwd() # Absolutize root dir+ if os.system("git rev-parse") or 2 != len([d for d in ("dev-tools", "lucene") if os.path.isdir(d)]):parser.error('Root path "%s" is not a valid lucene checkout' % config.root)os.chdir(cwd)global LOG@@ -307,27 +310,29 @@ def parse_config():print("Logfile is: %s" % LOG)config.version = read_version(config.root)- print('Building version: %s' % config.version)+ print("Building version: %s" % config.version)return config+def check_cmdline_tools(): # Fail fast if there are cmdline tool problems- if os.system('git --version >/dev/null 2>/dev/null'):+ if os.system("git --version >/dev/null 2>/dev/null"):raise RuntimeError('"git --version" returned a non-zero exit code.')+def check_key_in_keys(gpgKeyID, local_keys):if gpgKeyID is not None:- print(' Verify your gpg key is in the main KEYS file')+ print(" Verify your gpg key is in the main KEYS file")if local_keys is not None:print(" Using local KEYS file %s" % local_keys)- keysFileText = open(local_keys, encoding='iso-8859-1').read()+ keysFileText = open(local_keys, encoding="iso-8859-1").read()keysFileLocation = local_keyselse:keysFileURL = "https://archive.apache.org/dist/lucene/KEYS"keysFileLocation = keysFileURLprint(" Using online KEYS file %s" % keysFileURL)- keysFileText = load(keysFileURL, encoding='iso-8859-1')- if len(gpgKeyID) > 2 and gpgKeyID[0:2] == '0x':+ keysFileText = load(keysFileURL, encoding="iso-8859-1")+ if len(gpgKeyID) > 2 and gpgKeyID[0:2] == "0x":gpgKeyID = gpgKeyID[2:]if len(gpgKeyID) > 40:gpgKeyID = gpgKeyID.replace(" ", "")@@ -335,31 +340,40 @@ def check_key_in_keys(gpgKeyID, local_keys):gpgKeyID8Char = "%s %s" % (gpgKeyID[0:4], gpgKeyID[4:8])re_to_match = r"^pub .*\n\s+(\w{4} \w{4} \w{4} \w{4} \w{4} \w{4} \w{4} \w{4} %s|\w{32}%s)" % (gpgKeyID8Char, gpgKeyID)elif len(gpgKeyID) == 40:- gpgKeyID40Char = "%s %s %s %s %s %s %s %s %s %s" % \- (gpgKeyID[0:4], gpgKeyID[4:8], gpgKeyID[8:12], gpgKeyID[12:16], gpgKeyID[16:20],- gpgKeyID[20:24], gpgKeyID[24:28], gpgKeyID[28:32], gpgKeyID[32:36], gpgKeyID[36:])+ gpgKeyID40Char = "%s %s %s %s %s %s %s %s %s %s" % (+ gpgKeyID[0:4],+ gpgKeyID[4:8],+ gpgKeyID[8:12],+ gpgKeyID[12:16],+ gpgKeyID[16:20],+ gpgKeyID[20:24],+ gpgKeyID[24:28],+ gpgKeyID[28:32],+ gpgKeyID[32:36],+ gpgKeyID[36:],+ )re_to_match = r"^pub .*\n\s+(%s|%s)" % (gpgKeyID40Char, gpgKeyID)else:- print('Invalid gpg key id format [%s]. Must be 8 byte short ID or 40 byte fingerprint, with or without 0x prefix, no spaces.' % gpgKeyID)+ print("Invalid gpg key id format [%s]. Must be 8 byte short ID or 40 byte fingerprint, with or without 0x prefix, no spaces." % gpgKeyID)exit(2)if re.search(re_to_match, keysFileText, re.MULTILINE):- print(' Found key %s in KEYS file at %s' % (gpgKeyID, keysFileLocation))+ print(" Found key %s in KEYS file at %s" % (gpgKeyID, keysFileLocation))else:- print(' ERROR: Did not find your key %s in KEYS file at %s. Please add it and try again.' % (gpgKeyID, keysFileLocation))+ print(" ERROR: Did not find your key %s in KEYS file at %s. Please add it and try again." % (gpgKeyID, keysFileLocation))if local_keys is not None:- print(' You are using a local KEYS file. Make sure it is up to date or validate against the online version')+ print(" You are using a local KEYS file. Make sure it is up to date or validate against the online version")exit(2)def resolve_gpghome():for p in [# Linux, macos- os.path.join(os.path.expanduser("~"), '.gnupg'),+ os.path.join(os.path.expanduser("~"), ".gnupg"),# Windows 10- os.path.expandvars(r'%APPDATA%\GnuPG')+ os.path.expandvars(r"%APPDATA%\GnuPG"),# TODO: Should we support Cygwin?]:- if os.path.exists(os.path.join(p, 'secring.gpg')):+ if os.path.exists(os.path.join(p, "secring.gpg")):return preturn None@@ -393,7 +407,8 @@ def main():c.key_password = Noneelse:import getpass- c.key_password = getpass.getpass('Enter GPG keystore password: ')++ c.key_password = getpass.getpass("Enter GPG keystore password: ")else:c.key_id = Nonec.key_password = None@@ -409,8 +424,8 @@ def main():url = Noneif url is not None:- print(' URL: %s' % url)- print('Next run the smoker tester:')+ print(" URL: %s" % url)+ print("Next run the smoker tester:")p = re.compile(".*/")m = p.match(sys.argv[0])assert m@@ -418,11 +433,11 @@ def main():signed = "--not-signed"else:signed = ""- print('%s -u %ssmokeTestRelease.py %s %s' % (sys.executable, m.group(), signed, url))+ print("%s -u %ssmokeTestRelease.py %s %s" % (sys.executable, m.group(), signed, url))-if __name__ == '__main__':++if __name__ == "__main__":try:main()except KeyboardInterrupt:- print('Keyboard interrupt...exiting')-+ print("Keyboard interrupt...exiting")diff --git a/dev-tools/scripts/create_line_file_docs.py b/dev-tools/scripts/create_line_file_docs.pyindex 9fe53cdda4b..9c753f22f79 100644--- a/dev-tools/scripts/create_line_file_docs.py+++ b/dev-tools/scripts/create_line_file_docs.py@@ -15,22 +15,22 @@# See the License for the specific language governing permissions and# limitations under the License.-import osimport gzip-import time+import osimport randomimport re-import urllib.request+import shutilimport subprocessimport tempfile-import shutil+import time+import urllib.requestDEBUG = FalseTARGET_DOC_CHARS = 1024-def compress_with_seek_points(file_name_in, file_name_out, num_seek_points):+def compress_with_seek_points(file_name_in, file_name_out, num_seek_points):bytes_per_chunk = os.path.getsize(file_name_in) / num_seek_pointsseek_points = []@@ -38,8 +38,7 @@ def compress_with_seek_points(file_name_in, file_name_out, num_seek_points):if os.path.exists(file_name_out):os.remove(file_name_out)- with open(file_name_in, 'rb') as f_in:-+ with open(file_name_in, "rb") as f_in:f_out = Nonebytes_in_chunk = 0@@ -50,10 +49,10 @@ def compress_with_seek_points(file_name_in, file_name_out, num_seek_points):if f_out is None:if os.path.exists(file_name_out):seek_points.append(os.path.getsize(file_name_out))- print(' create chunk %s at pos=%s' % (chunk_count, seek_points[-1]))+ print(" create chunk %s at pos=%s" % (chunk_count, seek_points[-1]))else:- print(' create chunk %s at pos=0' % chunk_count)- f_out = gzip.open(file_name_out, 'ab')+ print(" create chunk %s at pos=0" % chunk_count)+ f_out = gzip.open(file_name_out, "ab")chunk_count += 1line = f_in.readline()@@ -61,35 +60,36 @@ def compress_with_seek_points(file_name_in, file_name_out, num_seek_points):breakbytes_in_chunk += len(line)- f_out.write(line) # false positive in python's crazy typing # pyright: ignore[reportArgumentType]+ f_out.write(line) # false positive in python's crazy typing # pyright: ignore[reportArgumentType]if bytes_in_chunk > bytes_per_chunk and chunk_count < num_seek_points:f_out.close()f_out = Nonebytes_in_chunk = 0- with open(file_name_out[:-3] + '.seek', 'w') as f_out:+ with open(file_name_out[:-3] + ".seek", "w") as f_out:for seek_point in seek_points:- f_out.write('%d\n' % seek_point)+ f_out.write("%d\n" % seek_point)+-re_tag = re.compile(r'<[^>]+?>')-re_newlines = re.compile(r'\n+')-re_space = re.compile(r'\s')+re_tag = re.compile(r"<[^>]+?>")+re_newlines = re.compile(r"\n+")+re_space = re.compile(r"\s")# used to find word break, for splitting docs into ~1 KB sized smaller docs:-re_next_non_word_character = re.compile(r'\W', re.U)+re_next_non_word_character = re.compile(r"\W", re.U)-EUROPARL_V7_URL = 'https://www.statmt.org/europarl/v7/europarl.tgz'+EUROPARL_V7_URL = "https://www.statmt.org/europarl/v7/europarl.tgz"-def split_docs(all_out, title_string, date_string, body_string):- '''+def split_docs(all_out, title_string, date_string, body_string):+ """Splits docs into smallish (~1 KB) sized docs, repeating same title and date- '''+ """doc_count = 0while len(body_string) > 0:- char_count = int(random.gauss(TARGET_DOC_CHARS, TARGET_DOC_CHARS/4))+ char_count = int(random.gauss(TARGET_DOC_CHARS, TARGET_DOC_CHARS / 4))if char_count < 64:# trimmed normal?continue@@ -102,75 +102,75 @@ def split_docs(all_out, title_string, date_string, body_string):body_string_fragment = body_string[:char_count].strip()- #print('write title %d, body %d' % (len(title_string), len(body_string_fragment)))- all_out.write('%s\t%s\t%s\n' % (title_string, date_string, body_string_fragment))+ # print('write title %d, body %d' % (len(title_string), len(body_string_fragment)))+ all_out.write("%s\t%s\t%s\n" % (title_string, date_string, body_string_fragment))body_string = body_string[char_count:]doc_count += 1return doc_count-def sample_europarl():+def sample_europarl():# download europarl.tgz v7, if not already here (in cwd):- file_name = 'europarl.tgz'+ file_name = "europarl.tgz"if not os.path.exists(file_name):- print('Download %s to %s...' % (EUROPARL_V7_URL, file_name))- urllib.request.urlretrieve(EUROPARL_V7_URL, file_name + '.tmp')- os.rename(file_name + '.tmp', file_name)+ print("Download %s to %s..." % (EUROPARL_V7_URL, file_name))+ urllib.request.urlretrieve(EUROPARL_V7_URL, file_name + ".tmp")+ os.rename(file_name + ".tmp", file_name)else:- print('%s already here; skipping download...' % file_name)+ print("%s already here; skipping download..." % file_name)if not DEBUG:tmp_dir_path = tempfile.mkdtemp()else:- tmp_dir_path = '/tmp/tmp31ekzg75'+ tmp_dir_path = "/tmp/tmp31ekzg75"print('Using tmp dir "%s"...' % tmp_dir_path)try:if not DEBUG:- cmd = 'tar xzf %s -C %s' % (file_name, tmp_dir_path)- print('Run: %s' % cmd)+ cmd = "tar xzf %s -C %s" % (file_name, tmp_dir_path)+ print("Run: %s" % cmd)subprocess.run(cmd, shell=True)doc_count = 0skip_count = 0file_count = 0- all_txt_file_name = '%s/all.txt' % tmp_dir_path+ all_txt_file_name = "%s/all.txt" % tmp_dir_path- print('Extract text...')+ print("Extract text...")start_time = time.time()next_print_time = start_time + 3# normalize text a bit and concatenate all lines into single file, counting total lines/bytes- with open(all_txt_file_name, 'w', encoding='utf-8') as all_out:- for dir_path, _, file_names in os.walk('%s/txt' % tmp_dir_path):+ with open(all_txt_file_name, "w", encoding="utf-8") as all_out:+ for dir_path, _, file_names in os.walk("%s/txt" % tmp_dir_path):for file_name in file_names:- if file_name.endswith('.txt'):+ if file_name.endswith(".txt"):file_count += 1- year, month, day = (int(x) for x in file_name[3:-4].split('-')[:3])+ year, month, day = (int(x) for x in file_name[3:-4].split("-")[:3])if year >= 50:year = 1900 + yearelse:year = 2000 + year- date_string = '%04d-%02d-%02d' % (year, month, day)+ date_string = "%04d-%02d-%02d" % (year, month, day)# unfortunately we need errors='ignore' since in Europarl v7, one file (pl/ep-09-10-22-009.txt) has invalid utf-8:chapter_count = 0- with open('%s/%s' % (dir_path, file_name), 'r', encoding='utf-8', errors='ignore') as f_in:+ with open("%s/%s" % (dir_path, file_name), "r", encoding="utf-8", errors="ignore") as f_in:last_text = []last_title = Nonewhile True:line = f_in.readline()- if line == '':+ if line == "":breakline = line.strip()- if line.startswith('<CHAPTER '):+ if line.startswith("<CHAPTER "):if last_title is not None:- s = ' '.join(last_text)- s = re_tag.sub(' ', s)- s = re_newlines.sub(' ', s)+ s = " ".join(last_text)+ s = re_tag.sub(" ", s)+ s = re_newlines.sub(" ", s)s = s.strip()if len(s) > 0:doc_count += split_docs(all_out, last_title, date_string, s)@@ -181,10 +181,10 @@ def sample_europarl():chapter_count += 1while True:last_title = f_in.readline()- if last_title == '':+ if last_title == "":last_title = Nonebreak- last_title = re_tag.sub(' ', last_title).strip()+ last_title = re_tag.sub(" ", last_title).strip()if len(last_title) > 0:breakcontinue@@ -192,9 +192,9 @@ def sample_europarl():last_text.append(line)if last_title is not None:- s = ' '.join(last_text)- s = re_tag.sub(' ', s)- s = re_newlines.sub(' ', s)+ s = " ".join(last_text)+ s = re_tag.sub(" ", s)+ s = re_newlines.sub(" ", s)s = s.strip()if len(s) > 0:doc_count += split_docs(all_out, last_title, date_string, s)@@ -205,37 +205,42 @@ def sample_europarl():skip_count += 1if chapter_count > 0:- #print('%s/%s: %d chapters' % (dir_path, file_name, chapter_count))+ # print('%s/%s: %d chapters' % (dir_path, file_name, chapter_count))passnow = time.time()if now > next_print_time:- print('%4.1fs: keep %.2f K of %.2f K files (%.1f%%), %.2f M docs, %.2f GB...' % \- (now - start_time, (file_count - skip_count) / 1000, file_count / 1000,- 100 * (file_count - skip_count) / file_count,- doc_count / 1000000, all_out.tell() / 1024/1024/1024))+ print(+ "%4.1fs: keep %.2f K of %.2f K files (%.1f%%), %.2f M docs, %.2f GB..."+ % (now - start_time, (file_count - skip_count) / 1000, file_count / 1000, 100 * (file_count - skip_count) / file_count, doc_count / 1000000, all_out.tell() / 1024 / 1024 / 1024)+ )while next_print_time < now:next_print_time += 3- total_mb = os.path.getsize(all_txt_file_name)/1024/1024+ total_mb = os.path.getsize(all_txt_file_name) / 1024 / 1024now = time.time()- print('%4.1fs (done): keep %.2f K of %.2f K files (%.1f%%), %.2f M docs, %.2f GB...' % \- (now - start_time, (file_count - skip_count) / 1000, file_count / 1000,- 100 * (file_count - skip_count) / file_count,- doc_count / 1000000, os.path.getsize(all_txt_file_name) / 1024/1024/1024))-- print('Shuffle...')- subprocess.run('shuf %s > %s.shuffled' % (all_txt_file_name, all_txt_file_name), shell=True)+ print(+ "%4.1fs (done): keep %.2f K of %.2f K files (%.1f%%), %.2f M docs, %.2f GB..."+ % (+ now - start_time,+ (file_count - skip_count) / 1000,+ file_count / 1000,+ 100 * (file_count - skip_count) / file_count,+ doc_count / 1000000,+ os.path.getsize(all_txt_file_name) / 1024 / 1024 / 1024,+ )+ )++ print("Shuffle...")+ subprocess.run("shuf %s > %s.shuffled" % (all_txt_file_name, all_txt_file_name), shell=True)for mb in (20, 200, 2000):- print('Sample %d MB file...' % mb)- file_name_out = '%dmb.txt' % mb- with open(file_name_out, 'w', encoding='utf-8') as f_out:-+ print("Sample %d MB file..." % mb)+ file_name_out = "%dmb.txt" % mb+ with open(file_name_out, "w", encoding="utf-8") as f_out:chance = mb / total_mb- with open(all_txt_file_name + '.shuffled', 'r', encoding='utf-8') as f:-+ with open(all_txt_file_name + ".shuffled", "r", encoding="utf-8") as f:while True:line = f.readline()if len(line) == 0:@@ -243,22 +248,19 @@ def sample_europarl():if random.random() <= chance:f_out.write(line)- print(' got %.2f MB' % (os.path.getsize(file_name_out)/1024/1024))+ print(" got %.2f MB" % (os.path.getsize(file_name_out) / 1024 / 1024))- compress_with_seek_points(file_name_out,- file_name_out + '.gz',- mb)+ compress_with_seek_points(file_name_out, file_name_out + ".gz", mb)finally:print('Removing tmp dir "%s"...' % tmp_dir_path)if not DEBUG:shutil.rmtree(tmp_dir_path)- print('\nWARNING: left ./europarl.tgz, which you should delete if you do not want it!\n')+ print("\nWARNING: left ./europarl.tgz, which you should delete if you do not want it!\n")+if False:- compress_with_seek_points('/x/tmp/europarl.lines.txt',- '/x/tmp/foo.txt.gz',- 16)+ compress_with_seek_points("/x/tmp/europarl.lines.txt", "/x/tmp/foo.txt.gz", 16)else:sample_europarl()diff --git a/dev-tools/scripts/diff_lucene_changes.py b/dev-tools/scripts/diff_lucene_changes.pyindex b6a3f6870b7..d443ff32bce 100644--- a/dev-tools/scripts/diff_lucene_changes.py+++ b/dev-tools/scripts/diff_lucene_changes.py@@ -22,34 +22,36 @@ import sysimport tempfileimport urllib.request-'''+"""A simple tool to see diffs between main's version of CHANGES.txt entries fora given release vs the stable branch's version. It's best to keep these 1)identical and 2) matching what changes were actually backported to be honestto users and avoid future annoying conflicts on backport.-'''+"""# e.g. python3 -u diff_lucene_changes.py branch_9_9 main 9.9.0#+def get_changes_url(branch_name):if os.path.isdir(branch_name):- url = f'file://{branch_name}/lucene/CHANGES.txt'+ url = f"file://{branch_name}/lucene/CHANGES.txt"else:- url = f'https://raw.githubusercontent.com/apache/lucene/{branch_name}/lucene/CHANGES.txt'- print(f'NOTE: resolving {branch_name} --> {url}')+ url = f"https://raw.githubusercontent.com/apache/lucene/{branch_name}/lucene/CHANGES.txt"+ print(f"NOTE: resolving {branch_name} --> {url}")return url+def extract_release_section(changes_txt, release_name):- match = re.search(f'=======+ Lucene {re.escape(release_name)} =======+(.*?)=======+ Lucene .*? =======+$',- changes_txt.decode('utf-8'), re.MULTILINE | re.DOTALL)+ match = re.search(f"=======+ Lucene {re.escape(release_name)} =======+(.*?)=======+ Lucene .*? =======+$", changes_txt.decode("utf-8"), re.MULTILINE | re.DOTALL)assert match- return match.group(1).encode('utf-8')+ return match.group(1).encode("utf-8")+def main():if len(sys.argv) < 3 or len(sys.argv) > 5:- print('\nUsage: python3 -u dev-tools/scripts/diff_lucene_changes.py <branch1-or-local-clone> <branch2-or-local-clone> <release-name> [diff-commandline-extras]\n')+ print("\nUsage: python3 -u dev-tools/scripts/diff_lucene_changes.py <branch1-or-local-clone> <branch2-or-local-clone> <release-name> [diff-commandline-extras]\n")print(' e.g.: python3 -u dev-tools/scripts/diff_lucene_changes.py branch_9_9 /l/trunk 9.9.0 "-w"\n')sys.exit(1)@@ -62,19 +64,18 @@ def main():else:diff_cl_extras = []- branch1_changes = extract_release_section(urllib.request.urlopen(get_changes_url(branch1)).read(),- release_name)- branch2_changes = extract_release_section(urllib.request.urlopen(get_changes_url(branch2)).read(),- release_name)+ branch1_changes = extract_release_section(urllib.request.urlopen(get_changes_url(branch1)).read(), release_name)+ branch2_changes = extract_release_section(urllib.request.urlopen(get_changes_url(branch2)).read(), release_name)with tempfile.NamedTemporaryFile() as f1, tempfile.NamedTemporaryFile() as f2:f1.write(branch1_changes)f2.write(branch2_changes)- command = ['diff'] + diff_cl_extras + [f1.name, f2.name]+ command = ["diff"] + diff_cl_extras + [f1.name, f2.name]# diff returns non-zero exit status when there are diffs, so don't pass check=True- print(subprocess.run(command, check=False, capture_output=True).stdout.decode('utf-8'))+ print(subprocess.run(command, check=False, capture_output=True).stdout.decode("utf-8"))+-if __name__ == '__main__':+if __name__ == "__main__":main()diff --git a/dev-tools/scripts/githubPRs.py b/dev-tools/scripts/githubPRs.pyindex 9390e947048..335c05e6aa7 100755--- a/dev-tools/scripts/githubPRs.py+++ b/dev-tools/scripts/githubPRs.py@@ -22,21 +22,24 @@ issue number in title, and the ones where the linked JIRA is already closedimport osimport sys+sys.path.append(os.path.dirname(__file__))import argparseimport jsonimport refrom typing import cast+from github import Github+from jinja2 import BaseLoader, Environmentfrom jira import JIRA, Issuefrom jira.client import ResultList-from jinja2 import Environment, BaseLoader+def read_config():- parser = argparse.ArgumentParser(description='Find open Pull Requests that need attention')- parser.add_argument('--json', action='store_true', default=False, help='Output as json')- parser.add_argument('--html', action='store_true', default=False, help='Output as html')- parser.add_argument('--token', help='Github access token in case you query too often anonymously')+ parser = argparse.ArgumentParser(description="Find open Pull Requests that need attention")+ parser.add_argument("--json", action="store_true", default=False, help="Output as json")+ parser.add_argument("--html", action="store_true", default=False, help="Output as html")+ parser.add_argument("--token", help="Github access token in case you query too often anonymously")newconf = parser.parse_args()return newconf@@ -46,6 +49,7 @@ def out(text):if not (conf.json or conf.html):print(text)+def make_html(dict):global conftemplate = Environment(loader=BaseLoader()).from_string("""@@ -69,6 +73,7 @@ def make_html(dict):""")return template.render(dict)+def main():global confconf = read_config()@@ -77,32 +82,32 @@ def main():gh = Github(token)else:gh = Github()- jira = JIRA('https://issues.apache.org/jira') # this ctor has broken types in jira library. # pyright: ignore[reportArgumentType]+ jira = JIRA("https://issues.apache.org/jira") # this ctor has broken types in jira library. # pyright: ignore[reportArgumentType]result = {}- repo = gh.get_repo('apache/lucene')- open_prs = repo.get_pulls(state='open')+ repo = gh.get_repo("apache/lucene")+ open_prs = repo.get_pulls(state="open")out("Lucene Github PR report")out("============================")out("Number of open Pull Requests: %s" % open_prs.totalCount)- result['open_count'] = open_prs.totalCount+ result["open_count"] = open_prs.totalCount- lack_jira = list(filter(lambda x: not re.match(r'.*\b(LUCENE)-\d{3,6}\b', x.title), open_prs))- result['no_jira_count'] = len(lack_jira)+ lack_jira = list(filter(lambda x: not re.match(r".*\b(LUCENE)-\d{3,6}\b", x.title), open_prs))+ result["no_jira_count"] = len(lack_jira)lack_jira_list = []for pr in lack_jira:- lack_jira_list.append({'title': pr.title, 'number': pr.number, 'user': pr.user.login, 'created': pr.created_at.strftime("%Y-%m-%d")})- result['no_jira'] = lack_jira_list+ lack_jira_list.append({"title": pr.title, "number": pr.number, "user": pr.user.login, "created": pr.created_at.strftime("%Y-%m-%d")})+ result["no_jira"] = lack_jira_listout("\nPRs lacking JIRA reference in title")for pr in lack_jira_list:- out(" #%s: %s %s (%s)" % (pr['number'], pr['created'], pr['title'], pr['user'] ))+ out(" #%s: %s %s (%s)" % (pr["number"], pr["created"], pr["title"], pr["user"]))out("\nOpen PRs with a resolved JIRA")- has_jira = list(filter(lambda x: re.match(r'.*\b(LUCENE)-\d{3,6}\b', x.title), open_prs))+ has_jira = list(filter(lambda x: re.match(r".*\b(LUCENE)-\d{3,6}\b", x.title), open_prs))issue_ids = []issue_to_pr = {}for pr in has_jira:- match = re.match(r'.*\b((LUCENE)-\d{3,6})\b', pr.title)+ match = re.match(r".*\b((LUCENE)-\d{3,6})\b", pr.title)assert matchjira_issue_str = match.group(1)issue_ids.append(jira_issue_str)@@ -115,26 +120,24 @@ def main():pr_number = issue_to_pr[issue.key].numberassignee = issue.fields.assignee.name if issue.fields.assignee else Noneresolution = issue.fields.resolution.name if issue.fields.resolution else None- closed_jiras.append({ 'issue_key': issue.key,- 'status': issue.fields.status.name,- 'resolution': resolution,- 'resolution_date': issue.fields.resolutiondate[:10],- 'pr_number': pr_number,- 'pr_title': pr_title,- 'issue_summary': issue.fields.summary,- 'assignee': assignee})-- closed_jiras.sort(key=lambda r: r['pr_number'], reverse=True)+ closed_jiras.append(+ {+ "issue_key": issue.key,+ "status": issue.fields.status.name,+ "resolution": resolution,+ "resolution_date": issue.fields.resolutiondate[:10],+ "pr_number": pr_number,+ "pr_title": pr_title,+ "issue_summary": issue.fields.summary,+ "assignee": assignee,+ }+ )++ closed_jiras.sort(key=lambda r: r["pr_number"], reverse=True)for issue in closed_jiras:- out(" #%s: %s %s %s: %s (%s)" % (issue['pr_number'],- issue['status'],- issue['resolution_date'],- issue['issue_key'],- issue['issue_summary'],- issue['assignee'])- )- result['closed_jira_count'] = len(resolved_jiras)- result['closed_jira'] = closed_jiras+ out(" #%s: %s %s %s: %s (%s)" % (issue["pr_number"], issue["status"], issue["resolution_date"], issue["issue_key"], issue["issue_summary"], issue["assignee"]))+ result["closed_jira_count"] = len(resolved_jiras)+ result["closed_jira"] = closed_jirasif conf.json:print(json.dumps(result, indent=4))@@ -142,8 +145,9 @@ def main():if conf.html:print(make_html(result))-if __name__ == '__main__':++if __name__ == "__main__":try:main()except KeyboardInterrupt:- print('\nReceived Ctrl-C, exiting early')+ print("\nReceived Ctrl-C, exiting early")diff --git a/dev-tools/scripts/releaseWizard.py b/dev-tools/scripts/releaseWizard.pyindex 3a7a8c1abac..fa64491d77a 100755--- a/dev-tools/scripts/releaseWizard.py+++ b/dev-tools/scripts/releaseWizard.py@@ -47,1849 +47,1878 @@ import textwrapimport timeimport urllib.requestfrom collections import OrderedDict-from datetime import datetime-from datetime import timedelta-from datetime import timezone+from datetime import datetime, timedelta, timezonefrom typing import cast-from holidays import country_holidaysimport yaml+from consolemenu import ConsoleMenu+from consolemenu.items import ExitItem, FunctionItem, SubmenuItem+from holidays import country_holidaysfrom ics import Calendar, Eventfrom jinja2 import Environmentimport scriptutil-from consolemenu import ConsoleMenu-from consolemenu.items import FunctionItem, SubmenuItem, ExitItemfrom scriptutil import BranchType, Version, download, run# Lucene-to-Java version mappingjava_versions = {6: 8, 7: 8, 8: 8, 9: 11, 10: 21, 11: 23}editor = None+# Edit this to add other global jinja2 variables or filtersdef expand_jinja(text, vars=None):- global_vars = OrderedDict({- 'script_version': state.script_version,- 'release_version': state.release_version,- 'release_version_underscore': state.release_version.replace('.', '_'),- 'release_date': state.get_release_date(),- 'ivy2_folder': os.path.expanduser("~/.ivy2/"),- 'config_path': state.config_path,- 'rc_number': state.rc_number,- 'script_branch': state.script_branch,- 'release_folder': state.get_release_folder(),- 'git_checkout_folder': state.get_git_checkout_folder(),- 'git_website_folder': state.get_website_git_folder(),- 'dist_url_base': 'https://dist.apache.org/repos/dist/dev/lucene',- 'm2_repository_url': 'https://repository.apache.org/service/local/staging/deploy/maven2',- 'dist_file_path': state.get_dist_folder(),- 'rc_folder': state.get_rc_folder(),- 'base_branch': state.get_base_branch_name(),- 'release_branch': state.release_branch,- 'stable_branch': state.get_stable_branch_name(),- 'minor_branch': state.get_minor_branch_name(),- 'release_type': state.release_type,- 'is_feature_release': state.release_type in ['minor', 'major'],- 'release_version_major': state.release_version_major,- 'release_version_minor': state.release_version_minor,- 'release_version_bugfix': state.release_version_bugfix,- 'state': state,- 'gpg_key' : state.get_gpg_key(),- 'gradle_cmd' : 'gradlew.bat' if is_windows() else './gradlew',- 'epoch': unix_time_millis(datetime.now(tz=timezone.utc)),- 'get_next_version': state.get_next_version(),- 'current_git_rev': state.get_current_git_rev(),- 'keys_downloaded': keys_downloaded(),- 'editor': get_editor(),- 'rename_cmd': 'ren' if is_windows() else 'mv',- 'vote_close_72h': vote_close_72h_date().strftime("%Y-%m-%d %H:00 UTC"),- 'vote_close_72h_epoch': unix_time_millis(vote_close_72h_date()),- 'vote_close_72h_holidays': vote_close_72h_holidays(),- 'lucene_news_file': lucene_news_file,- 'load_lines': load_lines,- 'set_java_home': set_java_home,- 'latest_version': state.get_latest_version(),- 'latest_lts_version': state.get_latest_lts_version(),- 'main_version': state.get_main_version(),- 'mirrored_versions': state.get_mirrored_versions(),- 'mirrored_versions_to_delete': state.get_mirrored_versions_to_delete(),- 'home': os.path.expanduser("~")- })- global_vars.update(state.get_todo_states())- if vars:- global_vars.update(vars)-- filled = replace_templates(text)+ global_vars = OrderedDict(+ {+ "script_version": state.script_version,+ "release_version": state.release_version,+ "release_version_underscore": state.release_version.replace(".", "_"),+ "release_date": state.get_release_date(),+ "ivy2_folder": os.path.expanduser("~/.ivy2/"),+ "config_path": state.config_path,+ "rc_number": state.rc_number,+ "script_branch": state.script_branch,+ "release_folder": state.get_release_folder(),+ "git_checkout_folder": state.get_git_checkout_folder(),+ "git_website_folder": state.get_website_git_folder(),+ "dist_url_base": "https://dist.apache.org/repos/dist/dev/lucene",+ "m2_repository_url": "https://repository.apache.org/service/local/staging/deploy/maven2",+ "dist_file_path": state.get_dist_folder(),+ "rc_folder": state.get_rc_folder(),+ "base_branch": state.get_base_branch_name(),+ "release_branch": state.release_branch,+ "stable_branch": state.get_stable_branch_name(),+ "minor_branch": state.get_minor_branch_name(),+ "release_type": state.release_type,+ "is_feature_release": state.release_type in ["minor", "major"],+ "release_version_major": state.release_version_major,+ "release_version_minor": state.release_version_minor,+ "release_version_bugfix": state.release_version_bugfix,+ "state": state,+ "gpg_key": state.get_gpg_key(),+ "gradle_cmd": "gradlew.bat" if is_windows() else "./gradlew",+ "epoch": unix_time_millis(datetime.now(tz=timezone.utc)),+ "get_next_version": state.get_next_version(),+ "current_git_rev": state.get_current_git_rev(),+ "keys_downloaded": keys_downloaded(),+ "editor": get_editor(),+ "rename_cmd": "ren" if is_windows() else "mv",+ "vote_close_72h": vote_close_72h_date().strftime("%Y-%m-%d %H:00 UTC"),+ "vote_close_72h_epoch": unix_time_millis(vote_close_72h_date()),+ "vote_close_72h_holidays": vote_close_72h_holidays(),+ "lucene_news_file": lucene_news_file,+ "load_lines": load_lines,+ "set_java_home": set_java_home,+ "latest_version": state.get_latest_version(),+ "latest_lts_version": state.get_latest_lts_version(),+ "main_version": state.get_main_version(),+ "mirrored_versions": state.get_mirrored_versions(),+ "mirrored_versions_to_delete": state.get_mirrored_versions_to_delete(),+ "home": os.path.expanduser("~"),+ }+ )+ global_vars.update(state.get_todo_states())+ if vars:+ global_vars.update(vars)++ filled = replace_templates(text)- try:- env = Environment(lstrip_blocks=True, keep_trailing_newline=False, trim_blocks=True)- env.filters['path_join'] = lambda paths: os.path.join(*paths)- env.filters['expanduser'] = lambda path: os.path.expanduser(path)- env.filters['formatdate'] = lambda date: (datetime.strftime(date, "%-d %B %Y") if date else "<date>" )- template = env.from_string(str(filled), globals=global_vars)- filled = template.render()- except Exception as e:- print("Exception while rendering jinja template %s: %s" % (str(filled)[:10], e))- return filled+ try:+ env = Environment(lstrip_blocks=True, keep_trailing_newline=False, trim_blocks=True)+ env.filters["path_join"] = lambda paths: os.path.join(*paths)+ env.filters["expanduser"] = lambda path: os.path.expanduser(path)+ env.filters["formatdate"] = lambda date: (datetime.strftime(date, "%-d %B %Y") if date else "<date>")+ template = env.from_string(str(filled), globals=global_vars)+ filled = template.render()+ except Exception as e:+ print("Exception while rendering jinja template %s: %s" % (str(filled)[:10], e))+ return filleddef replace_templates(text):- tpl_lines = []- for line in text.splitlines():- if match := re.search(r"^\(\( template=(.+?) \)\)", line):- name = match.group(1)- tpl_lines.append(replace_templates(templates[name].strip()))- else:- tpl_lines.append(line)- return "\n".join(tpl_lines)+ tpl_lines = []+ for line in text.splitlines():+ if match := re.search(r"^\(\( template=(.+?) \)\)", line):+ name = match.group(1)+ tpl_lines.append(replace_templates(templates[name].strip()))+ else:+ tpl_lines.append(line)+ return "\n".join(tpl_lines)+def getScriptVersion():- return scriptutil.find_current_version()+ return scriptutil.find_current_version()def get_editor():- global editor- if editor is None:- if 'EDITOR' in os.environ:- if os.environ['EDITOR'] in ['vi', 'vim', 'nano', 'pico', 'emacs']:- print("WARNING: You have EDITOR set to %s, which will not work when launched from this tool. Please use an editor that launches a separate window/process" % os.environ['EDITOR'])- editor = os.environ['EDITOR']- elif is_windows():- editor = 'notepad.exe'- elif is_mac():- editor = 'open -a TextEdit'- else:- sys.exit("On Linux you have to set EDITOR variable to a command that will start an editor in its own window")- return editor+ global editor+ if editor is None:+ if "EDITOR" in os.environ:+ if os.environ["EDITOR"] in ["vi", "vim", "nano", "pico", "emacs"]:+ print("WARNING: You have EDITOR set to %s, which will not work when launched from this tool. Please use an editor that launches a separate window/process" % os.environ["EDITOR"])+ editor = os.environ["EDITOR"]+ elif is_windows():+ editor = "notepad.exe"+ elif is_mac():+ editor = "open -a TextEdit"+ else:+ sys.exit("On Linux you have to set EDITOR variable to a command that will start an editor in its own window")+ return editordef check_prerequisites(todo=None):- if sys.version_info < (3, 4):- sys.exit("Script requires Python v3.4 or later")- try:- gpg_ver = run("gpg --version").splitlines()[0]- except Exception:- sys.exit("You will need gpg installed")- 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 'JAVA11_HOME' not in os.environ:- sys.exit("Please set environment variables JAVA11_HOME")- try:- asciidoc_ver = run("asciidoctor -V").splitlines()[0]- 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 Exception:- sys.exit("You will need git installed")- try:- run("svn --version").splitlines()[0]- except Exception:- sys.exit("You will need svn installed")- if 'EDITOR' not in os.environ:- print("WARNING: Environment variable $EDITOR not set, using %s" % get_editor())-- if todo:- print("%s\n%s\n%s\n" % (gpg_ver, asciidoc_ver, git_ver))- return True+ if sys.version_info < (3, 4):+ sys.exit("Script requires Python v3.4 or later")+ try:+ gpg_ver = run("gpg --version").splitlines()[0]+ except Exception:+ sys.exit("You will need gpg installed")+ 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 "JAVA11_HOME" not in os.environ:+ sys.exit("Please set environment variables JAVA11_HOME")+ try:+ asciidoc_ver = run("asciidoctor -V").splitlines()[0]+ 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 Exception:+ sys.exit("You will need git installed")+ try:+ run("svn --version").splitlines()[0]+ except Exception:+ sys.exit("You will need svn installed")+ if "EDITOR" not in os.environ:+ print("WARNING: Environment variable $EDITOR not set, using %s" % get_editor())++ if todo:+ print("%s\n%s\n%s\n" % (gpg_ver, asciidoc_ver, git_ver))+ return Trueepoch = datetime.fromtimestamp(timestamp=0, tz=timezone.utc)def unix_time_millis(dt):- return int((dt - epoch).total_seconds() * 1000.0)+ return int((dt - epoch).total_seconds() * 1000.0)def bootstrap_todos(todo_list):- # Establish links from commands to to_do for finding todo vars- for tg in todo_list:+ # Establish links from commands to to_do for finding todo vars+ for tg in todo_list:+ if dry_run:+ print("Group %s" % tg.id)+ for td in tg.get_todos():+ if dry_run:+ print(" Todo %s" % td.id)+ cmds = td.commands+ if cmds:if dry_run:- print("Group %s" % tg.id)- for td in tg.get_todos():- if dry_run:- print(" Todo %s" % td.id)- cmds = td.commands- if cmds:- if dry_run:- print(" Commands")- cmds.todo_id = td.id- for cmd in cmds.commands:- if dry_run:- print(" Command %s" % cmd.cmd)- cmd.todo_id = td.id-- print("Loaded TODO definitions from releaseWizard.yaml")- return todo_list+ print(" Commands")+ cmds.todo_id = td.id+ for cmd in cmds.commands:+ if dry_run:+ print(" Command %s" % cmd.cmd)+ cmd.todo_id = td.id++ print("Loaded TODO definitions from releaseWizard.yaml")+ return todo_listdef maybe_remove_rc_from_svn():- todo = state.get_todo_by_id('import_svn')- if todo and todo.is_done():- print("import_svn done")- Commands(state.get_git_checkout_folder(),- """Looks like you uploaded artifacts for {{ build_rc.git_rev | default("<git_rev>", True) }} to svn which needs to be removed.""",- [Command(- """svn -m "Remove cancelled Lucene {{ release_version }} RC{{ rc_number }}" rm {{ dist_url }}""",- logfile="svn_rm.log",- tee=True,- vars={- 'dist_folder': """lucene-{{ release_version }}-RC{{ rc_number }}-rev-{{ build_rc.git_rev | default("<git_rev>", True) }}""",- 'dist_url': "{{ dist_url_base }}/{{ dist_folder }}"- }- )],- enable_execute=True, confirm_each_command=False).run()+ todo = state.get_todo_by_id("import_svn")+ if todo and todo.is_done():+ print("import_svn done")+ Commands(+ state.get_git_checkout_folder(),+ """Looks like you uploaded artifacts for {{ build_rc.git_rev | default("<git_rev>", True) }} to svn which needs to be removed.""",+ [+ Command(+ """svn -m "Remove cancelled Lucene {{ release_version }} RC{{ rc_number }}" rm {{ dist_url }}""",+ logfile="svn_rm.log",+ tee=True,+ vars={"dist_folder": """lucene-{{ release_version }}-RC{{ rc_number }}-rev-{{ build_rc.git_rev | default("<git_rev>", True) }}""", "dist_url": "{{ dist_url_base }}/{{ dist_folder }}"},+ )+ ],+ enable_execute=True,+ confirm_each_command=False,+ ).run()# To be able to hide fields when dumping Yamlclass SecretYamlObject(yaml.YAMLObject):- hidden_fields = []- @classmethod- def to_yaml(cls,dumper,data):- print("Dumping object %s" % type(data))-- new_data = copy.deepcopy(data)- for item in cls.hidden_fields:- if item in new_data.__dict__:- del new_data.__dict__[item]- for item in data.__dict__:- if item in new_data.__dict__ and new_data.__dict__[item] is None:- del new_data.__dict__[item]- return dumper.represent_yaml_object(cls.yaml_tag, new_data, cls,- flow_style=cls.yaml_flow_style)+ hidden_fields = []++ @classmethod+ def to_yaml(cls, dumper, data):+ print("Dumping object %s" % type(data))++ new_data = copy.deepcopy(data)+ for item in cls.hidden_fields:+ if item in new_data.__dict__:+ del new_data.__dict__[item]+ for item in data.__dict__:+ if item in new_data.__dict__ and new_data.__dict__[item] is None:+ del new_data.__dict__[item]+ return dumper.represent_yaml_object(cls.yaml_tag, new_data, cls, flow_style=cls.yaml_flow_style)def str_presenter(dumper, data):- if len(data.split('\n')) > 1: # check for multiline string- return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')- return dumper.represent_scalar('tag:yaml.org,2002:str', data)+ if len(data.split("\n")) > 1: # check for multiline string+ return dumper.represent_scalar("tag:yaml.org,2002:str", data, style="|")+ return dumper.represent_scalar("tag:yaml.org,2002:str", data)class ReleaseState:- def __init__(self, config_path, release_version, script_version):- self.script_version = script_version- self.config_path = config_path- self.todo_groups: list[TodoGroup] = []- self.todos: dict[str,Todo] = {}- self.latest_version = None- self.previous_rcs = {}- self.rc_number = 1- self.start_date = unix_time_millis(datetime.now(tz=timezone.utc))- self.script_branch = run("git rev-parse --abbrev-ref HEAD").strip()- self.mirrored_versions = None- try:- self.script_branch_type = scriptutil.find_branch_type()- 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)-- def set_release_version(self, version):- self.validate_release_version(self.script_branch_type, self.script_branch, version)- self.release_version = version- v = Version.parse(version)- self.release_version_major = v.major- self.release_version_minor = v.minor- self.release_version_bugfix = v.bugfix- self.release_branch = "branch_%s_%s" % (v.major, v.minor)- if v.is_major_release():- self.release_type = 'major'- elif v.is_minor_release():- self.release_type = 'minor'- else:- self.release_type = 'bugfix'-- def is_released(self):- todo = self.get_todo_by_id('announce_lucene')- assert todo- return todo.is_done()-- def get_gpg_key(self):- gpg_task = self.get_todo_by_id('gpg')- assert gpg_task- if gpg_task.is_done():- return gpg_task.get_state()['gpg_key']- else:- return None+ def __init__(self, config_path, release_version, script_version):+ self.script_version = script_version+ self.config_path = config_path+ self.todo_groups: list[TodoGroup] = []+ self.todos: dict[str, Todo] = {}+ self.latest_version = None+ self.previous_rcs = {}+ self.rc_number = 1+ self.start_date = unix_time_millis(datetime.now(tz=timezone.utc))+ self.script_branch = run("git rev-parse --abbrev-ref HEAD").strip()+ self.mirrored_versions = None+ try:+ self.script_branch_type = scriptutil.find_branch_type()+ 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)++ def set_release_version(self, version):+ self.validate_release_version(self.script_branch_type, self.script_branch, version)+ self.release_version = version+ v = Version.parse(version)+ self.release_version_major = v.major+ self.release_version_minor = v.minor+ self.release_version_bugfix = v.bugfix+ self.release_branch = "branch_%s_%s" % (v.major, v.minor)+ if v.is_major_release():+ self.release_type = "major"+ elif v.is_minor_release():+ self.release_type = "minor"+ else:+ self.release_type = "bugfix"++ def is_released(self):+ todo = self.get_todo_by_id("announce_lucene")+ assert todo+ return todo.is_done()++ def get_gpg_key(self):+ gpg_task = self.get_todo_by_id("gpg")+ assert gpg_task+ if gpg_task.is_done():+ return gpg_task.get_state()["gpg_key"]+ else:+ return None- def get_release_date(self):- publish_task = self.get_todo_by_id('publish_maven')- assert publish_task- if publish_task.is_done():- return unix_to_datetime(publish_task.get_state()['done_date'])- else:- return None+ def get_release_date(self):+ publish_task = self.get_todo_by_id("publish_maven")+ assert publish_task+ if publish_task.is_done():+ return unix_to_datetime(publish_task.get_state()["done_date"])+ else:+ return None- def get_release_date_iso(self):- release_date = self.get_release_date()- if release_date is None:- return "yyyy-mm-dd"- else:- return release_date.isoformat()[:10]-- def get_latest_version(self):- if self.latest_version is None:- versions = self.get_mirrored_versions()- latest = versions[0]- for ver in versions:- if Version.parse(ver).gt(Version.parse(latest)):- latest = ver- self.latest_version = latest- self.save()- return state.latest_version-- def get_mirrored_versions(self):- if state.mirrored_versions is None:- releases_str = load("https://projects.apache.org/json/foundation/releases.json", "utf-8")- releases = json.loads(releases_str)['lucene']- state.mirrored_versions = [ r for r in list(map(lambda y: y[7:], filter(lambda x: x.startswith('lucene-'), list(releases.keys())))) ]- return state.mirrored_versions-- def get_mirrored_versions_to_delete(self):- versions = self.get_mirrored_versions()- to_keep = versions- if state.release_type == 'major':- to_keep = [self.release_version, self.get_latest_version()]- if state.release_type == 'minor':- to_keep = [self.release_version, self.get_latest_lts_version()]- if state.release_type == 'bugfix':- if Version.parse(state.release_version).major == Version.parse(state.get_latest_version()).major:- to_keep = [self.release_version, self.get_latest_lts_version()]- elif Version.parse(state.release_version).major == Version.parse(state.get_latest_lts_version()).major:- to_keep = [self.get_latest_version(), self.release_version]- else:- raise Exception("Release version %s must have same major version as current minor or lts release")- return [ver for ver in versions if ver not in to_keep]-- def get_main_version(self):- v = Version.parse(self.get_latest_version())- return "%s.%s.%s" % (v.major + 1, 0, 0)-- def get_latest_lts_version(self):- versions = self.get_mirrored_versions()- latest = self.get_latest_version()- lts_prefix = "%s." % (Version.parse(latest).major - 1)- lts_versions = list(filter(lambda x: x.startswith(lts_prefix), versions))- latest_lts = lts_versions[0]- for ver in lts_versions:- if Version.parse(ver).gt(Version.parse(latest_lts)):- latest_lts = ver- return latest_lts-- def validate_release_version(self, branch_type, branch, release_version):- ver = Version.parse(release_version)- # print("release_version=%s, ver=%s" % (release_version, ver))- if branch_type == BranchType.release:- if not branch.startswith('branch_'):- sys.exit("Incompatible branch and branch_type")- if not ver.is_bugfix_release():- sys.exit("You can only release bugfix releases from an existing release branch")- elif branch_type == BranchType.stable:- if not branch.startswith('branch_') and branch.endswith('x'):- sys.exit("Incompatible branch and branch_type")- if not ver.is_minor_release():- sys.exit("You can only release minor releases from an existing stable branch")- elif branch_type == BranchType.unstable:- if not branch == 'main':- sys.exit("Incompatible branch and branch_type")- if not ver.is_major_release():- sys.exit("You can only release a new major version from main branch")- if not getScriptVersion() == release_version:- print("WARNING: Expected release version %s when on branch %s, but got %s" % (- getScriptVersion(), branch, release_version))-- def get_base_branch_name(self):- v = Version.parse(self.release_version)- if v.is_major_release():- return 'main'- elif v.is_minor_release():- return self.get_stable_branch_name()- elif v.major == Version.parse(self.get_latest_version()).major:- return self.get_minor_branch_name()- else:- return self.release_branch-- def clear_rc(self):- if ask_yes_no("Are you sure? This will clear and restart RC%s" % self.rc_number):- maybe_remove_rc_from_svn()- for g in list(filter(lambda x: x.in_rc_loop(), self.todo_groups)):- for t in g.get_todos():- t.clear()- print("Cleared RC TODO state")- try:- shutil.rmtree(self.get_rc_folder())- print("Cleared folder %s" % self.get_rc_folder())- except Exception:- print("WARN: Failed to clear %s, please do it manually with higher privileges" % self.get_rc_folder())- self.save()-- def new_rc(self):- if ask_yes_no("Are you sure? This will abort current RC"):- maybe_remove_rc_from_svn()- dict = {}- for g in list(filter(lambda x: x.in_rc_loop(), self.todo_groups)):- for t in g.get_todos():- if t.applies(self.release_type):- dict[t.id] = copy.deepcopy(t.state)- t.clear()- self.previous_rcs["RC%d" % self.rc_number] = dict- self.rc_number += 1- self.save()-- def to_dict(self):- tmp_todos = {}- for todo_id in self.todos:- t = self.todos[todo_id]- tmp_todos[todo_id] = copy.deepcopy(t.state)- dict = {- 'script_version': self.script_version,- 'release_version': self.release_version,- 'start_date': self.start_date,- 'rc_number': self.rc_number,- 'script_branch': self.script_branch,- 'todos': tmp_todos,- 'previous_rcs': self.previous_rcs- }- if self.latest_version:- dict['latest_version'] = self.latest_version- return dict-- def restore_from_dict(self, dict):- self.script_version = dict['script_version']- assert dict['release_version'] == self.release_version- if 'start_date' in dict:- self.start_date = dict['start_date']- if 'latest_version' in dict:- self.latest_version = dict['latest_version']- else:- self.latest_version = None- self.rc_number = dict['rc_number']- self.script_branch = dict['script_branch']- self.previous_rcs = copy.deepcopy(dict['previous_rcs'])- for todo_id in dict['todos']:- if todo_id in self.todos:- t = self.todos[todo_id]- for k in dict['todos'][todo_id]:- t.state[k] = dict['todos'][todo_id][k]- else:- print("Warning: Could not restore state for %s, Todo definition not found" % todo_id)-- def load(self):- if os.path.exists(os.path.join(self.config_path, self.release_version, 'state.yaml')):- state_file = os.path.join(self.config_path, self.release_version, 'state.yaml')- with open(state_file, 'r') as fp:- try:- dict = yaml.load(fp, Loader=yaml.Loader)- self.restore_from_dict(dict)- print("Loaded state from %s" % state_file)- except Exception as e:- print("Failed to load state from %s: %s" % (state_file, e))-- def save(self):- print("Saving")- if not os.path.exists(os.path.join(self.config_path, self.release_version)):- print("Creating folder %s" % os.path.join(self.config_path, self.release_version))- os.makedirs(os.path.join(self.config_path, self.release_version))-- with open(os.path.join(self.config_path, self.release_version, 'state.yaml'), 'w') as fp:- yaml.dump(self.to_dict(), fp, sort_keys=False, default_flow_style=False)-- def clear(self):- self.previous_rcs = {}- self.rc_number = 1- for t_id in self.todos:- t = self.todos[t_id]- t.state = {}- self.save()-- def get_rc_number(self):- return self.rc_number-- def get_current_git_rev(self):+ def get_release_date_iso(self):+ release_date = self.get_release_date()+ if release_date is None:+ return "yyyy-mm-dd"+ else:+ return release_date.isoformat()[:10]++ def get_latest_version(self):+ if self.latest_version is None:+ versions = self.get_mirrored_versions()+ latest = versions[0]+ for ver in versions:+ if Version.parse(ver).gt(Version.parse(latest)):+ latest = ver+ self.latest_version = latest+ self.save()+ return state.latest_version++ def get_mirrored_versions(self):+ if state.mirrored_versions is None:+ releases_str = load("https://projects.apache.org/json/foundation/releases.json", "utf-8")+ releases = json.loads(releases_str)["lucene"]+ state.mirrored_versions = [r for r in list(map(lambda y: y[7:], filter(lambda x: x.startswith("lucene-"), list(releases.keys()))))]+ return state.mirrored_versions++ def get_mirrored_versions_to_delete(self):+ versions = self.get_mirrored_versions()+ to_keep = versions+ if state.release_type == "major":+ to_keep = [self.release_version, self.get_latest_version()]+ if state.release_type == "minor":+ to_keep = [self.release_version, self.get_latest_lts_version()]+ if state.release_type == "bugfix":+ if Version.parse(state.release_version).major == Version.parse(state.get_latest_version()).major:+ to_keep = [self.release_version, self.get_latest_lts_version()]+ elif Version.parse(state.release_version).major == Version.parse(state.get_latest_lts_version()).major:+ to_keep = [self.get_latest_version(), self.release_version]+ else:+ raise Exception("Release version %s must have same major version as current minor or lts release")+ return [ver for ver in versions if ver not in to_keep]++ def get_main_version(self):+ v = Version.parse(self.get_latest_version())+ return "%s.%s.%s" % (v.major + 1, 0, 0)++ def get_latest_lts_version(self):+ versions = self.get_mirrored_versions()+ latest = self.get_latest_version()+ lts_prefix = "%s." % (Version.parse(latest).major - 1)+ lts_versions = list(filter(lambda x: x.startswith(lts_prefix), versions))+ latest_lts = lts_versions[0]+ for ver in lts_versions:+ if Version.parse(ver).gt(Version.parse(latest_lts)):+ latest_lts = ver+ return latest_lts++ def validate_release_version(self, branch_type, branch, release_version):+ ver = Version.parse(release_version)+ # print("release_version=%s, ver=%s" % (release_version, ver))+ if branch_type == BranchType.release:+ if not branch.startswith("branch_"):+ sys.exit("Incompatible branch and branch_type")+ if not ver.is_bugfix_release():+ sys.exit("You can only release bugfix releases from an existing release branch")+ elif branch_type == BranchType.stable:+ if not branch.startswith("branch_") and branch.endswith("x"):+ sys.exit("Incompatible branch and branch_type")+ if not ver.is_minor_release():+ sys.exit("You can only release minor releases from an existing stable branch")+ elif branch_type == BranchType.unstable:+ if not branch == "main":+ sys.exit("Incompatible branch and branch_type")+ if not ver.is_major_release():+ sys.exit("You can only release a new major version from main branch")+ if not getScriptVersion() == release_version:+ print("WARNING: Expected release version %s when on branch %s, but got %s" % (getScriptVersion(), branch, release_version))++ def get_base_branch_name(self):+ v = Version.parse(self.release_version)+ if v.is_major_release():+ return "main"+ elif v.is_minor_release():+ return self.get_stable_branch_name()+ elif v.major == Version.parse(self.get_latest_version()).major:+ return self.get_minor_branch_name()+ else:+ return self.release_branch++ def clear_rc(self):+ if ask_yes_no("Are you sure? This will clear and restart RC%s" % self.rc_number):+ maybe_remove_rc_from_svn()+ for g in list(filter(lambda x: x.in_rc_loop(), self.todo_groups)):+ for t in g.get_todos():+ t.clear()+ print("Cleared RC TODO state")+ try:+ shutil.rmtree(self.get_rc_folder())+ print("Cleared folder %s" % self.get_rc_folder())+ except Exception:+ print("WARN: Failed to clear %s, please do it manually with higher privileges" % self.get_rc_folder())+ self.save()++ def new_rc(self):+ if ask_yes_no("Are you sure? This will abort current RC"):+ maybe_remove_rc_from_svn()+ dict = {}+ for g in list(filter(lambda x: x.in_rc_loop(), self.todo_groups)):+ for t in g.get_todos():+ if t.applies(self.release_type):+ dict[t.id] = copy.deepcopy(t.state)+ t.clear()+ self.previous_rcs["RC%d" % self.rc_number] = dict+ self.rc_number += 1+ self.save()++ def to_dict(self):+ tmp_todos = {}+ for todo_id in self.todos:+ t = self.todos[todo_id]+ tmp_todos[todo_id] = copy.deepcopy(t.state)+ dict = {+ "script_version": self.script_version,+ "release_version": self.release_version,+ "start_date": self.start_date,+ "rc_number": self.rc_number,+ "script_branch": self.script_branch,+ "todos": tmp_todos,+ "previous_rcs": self.previous_rcs,+ }+ if self.latest_version:+ dict["latest_version"] = self.latest_version+ return dict++ def restore_from_dict(self, dict):+ self.script_version = dict["script_version"]+ assert dict["release_version"] == self.release_version+ if "start_date" in dict:+ self.start_date = dict["start_date"]+ if "latest_version" in dict:+ self.latest_version = dict["latest_version"]+ else:+ self.latest_version = None+ self.rc_number = dict["rc_number"]+ self.script_branch = dict["script_branch"]+ self.previous_rcs = copy.deepcopy(dict["previous_rcs"])+ for todo_id in dict["todos"]:+ if todo_id in self.todos:+ t = self.todos[todo_id]+ for k in dict["todos"][todo_id]:+ t.state[k] = dict["todos"][todo_id][k]+ else:+ print("Warning: Could not restore state for %s, Todo definition not found" % todo_id)++ def load(self):+ if os.path.exists(os.path.join(self.config_path, self.release_version, "state.yaml")):+ state_file = os.path.join(self.config_path, self.release_version, "state.yaml")+ with open(state_file, "r") as fp:try:- return run("git rev-parse HEAD", cwd=self.get_git_checkout_folder()).strip()- except Exception:- return "<git-rev>"-- def get_group_by_id(self, id):- lst = list(filter(lambda x: x.id == id, self.todo_groups))- if len(lst) == 1:- return lst[0]- else:- return None+ dict = yaml.load(fp, Loader=yaml.Loader)+ self.restore_from_dict(dict)+ print("Loaded state from %s" % state_file)+ except Exception as e:+ print("Failed to load state from %s: %s" % (state_file, e))- def get_todo_by_id(self, id):- lst = list(filter(lambda x: x.id == id, self.todos.values()))- if len(lst) == 1:- return lst[0]- else:- return None+ def save(self):+ print("Saving")+ if not os.path.exists(os.path.join(self.config_path, self.release_version)):+ print("Creating folder %s" % os.path.join(self.config_path, self.release_version))+ os.makedirs(os.path.join(self.config_path, self.release_version))- def get_todo_state_by_id(self, id):- lst = list(filter(lambda x: x.id == id, self.todos.values()))- if len(lst) == 1:- return lst[0].state- else:- return {}-- def get_release_folder(self):- folder = os.path.join(self.config_path, self.release_version)- if not os.path.exists(folder):- print("Creating folder %s" % folder)- os.makedirs(folder)- return folder-- def get_rc_folder(self):- folder = os.path.join(self.get_release_folder(), "RC%d" % self.rc_number)- if not os.path.exists(folder):- print("Creating folder %s" % folder)- os.makedirs(folder)- return folder-- def get_dist_folder(self):- folder = os.path.join(self.get_rc_folder(), "dist")- return folder-- def get_git_checkout_folder(self):- folder = os.path.join(self.get_release_folder(), "lucene")- return folder-- def get_website_git_folder(self):- folder = os.path.join(self.get_release_folder(), "lucene-site")- return folder-- def get_minor_branch_name(self):- latest = state.get_latest_version()- if latest is not None:- v = Version.parse(latest)- return "branch_%s_%s" % (v.major, v.minor)- else:- raise Exception("Cannot find latest version")+ with open(os.path.join(self.config_path, self.release_version, "state.yaml"), "w") as fp:+ yaml.dump(self.to_dict(), fp, sort_keys=False, default_flow_style=False)- def get_stable_branch_name(self):- if self.release_type == 'major':- v = Version.parse(self.get_main_version())- else:- v = Version.parse(self.get_latest_version())- return "branch_%sx" % v.major-- def get_next_version(self):- if self.release_type == 'major':- return "%s.0.0" % (self.release_version_major + 1)- if self.release_type == 'minor':- return "%s.%s.0" % (self.release_version_major, self.release_version_minor + 1)- if self.release_type == 'bugfix':- return "%s.%s.%s" % (self.release_version_major, self.release_version_minor, self.release_version_bugfix + 1)- return None-- def get_java_home(self):- return self.get_java_home_for_version(self.release_version)-- def get_java_home_for_version(self, version):- v = Version.parse(version)- java_ver = java_versions[v.major]- java_home_var = "JAVA%s_HOME" % java_ver- if java_home_var in os.environ:- return os.environ[java_home_var]- else:- raise Exception("Script needs environment variable %s" % java_home_var )+ def clear(self):+ self.previous_rcs = {}+ self.rc_number = 1+ for t_id in self.todos:+ t = self.todos[t_id]+ t.state = {}+ self.save()++ def get_rc_number(self):+ return self.rc_number++ def get_current_git_rev(self):+ try:+ return run("git rev-parse HEAD", cwd=self.get_git_checkout_folder()).strip()+ except Exception:+ return "<git-rev>"++ def get_group_by_id(self, id):+ lst = list(filter(lambda x: x.id == id, self.todo_groups))+ if len(lst) == 1:+ return lst[0]+ else:+ return None++ def get_todo_by_id(self, id):+ lst = list(filter(lambda x: x.id == id, self.todos.values()))+ if len(lst) == 1:+ return lst[0]+ else:+ return None++ def get_todo_state_by_id(self, id):+ lst = list(filter(lambda x: x.id == id, self.todos.values()))+ if len(lst) == 1:+ return lst[0].state+ else:+ return {}++ def get_release_folder(self):+ folder = os.path.join(self.config_path, self.release_version)+ if not os.path.exists(folder):+ print("Creating folder %s" % folder)+ os.makedirs(folder)+ return folder++ def get_rc_folder(self):+ folder = os.path.join(self.get_release_folder(), "RC%d" % self.rc_number)+ if not os.path.exists(folder):+ print("Creating folder %s" % folder)+ os.makedirs(folder)+ return folder++ def get_dist_folder(self):+ folder = os.path.join(self.get_rc_folder(), "dist")+ return folder++ def get_git_checkout_folder(self):+ folder = os.path.join(self.get_release_folder(), "lucene")+ return folder++ def get_website_git_folder(self):+ folder = os.path.join(self.get_release_folder(), "lucene-site")+ return folder++ def get_minor_branch_name(self):+ latest = state.get_latest_version()+ if latest is not None:+ v = Version.parse(latest)+ return "branch_%s_%s" % (v.major, v.minor)+ else:+ raise Exception("Cannot find latest version")++ def get_stable_branch_name(self):+ if self.release_type == "major":+ v = Version.parse(self.get_main_version())+ else:+ v = Version.parse(self.get_latest_version())+ return "branch_%sx" % v.major++ def get_next_version(self):+ if self.release_type == "major":+ return "%s.0.0" % (self.release_version_major + 1)+ if self.release_type == "minor":+ return "%s.%s.0" % (self.release_version_major, self.release_version_minor + 1)+ if self.release_type == "bugfix":+ return "%s.%s.%s" % (self.release_version_major, self.release_version_minor, self.release_version_bugfix + 1)+ return None++ def get_java_home(self):+ return self.get_java_home_for_version(self.release_version)++ def get_java_home_for_version(self, version):+ v = Version.parse(version)+ java_ver = java_versions[v.major]+ java_home_var = "JAVA%s_HOME" % java_ver+ if java_home_var in os.environ:+ return os.environ[java_home_var]+ else:+ raise Exception("Script needs environment variable %s" % java_home_var)- def get_java_cmd_for_version(self, version):- return os.path.join(self.get_java_home_for_version(version), "bin", "java")+ def get_java_cmd_for_version(self, version):+ return os.path.join(self.get_java_home_for_version(version), "bin", "java")- def get_java_cmd(self):- return os.path.join(self.get_java_home(), "bin", "java")+ def get_java_cmd(self):+ return os.path.join(self.get_java_home(), "bin", "java")- def get_todo_states(self):- states = {}- if self.todos:- for todo_id in self.todos:- t = self.todos[todo_id]- states[todo_id] = copy.deepcopy(t.state)- return states+ def get_todo_states(self):+ states = {}+ if self.todos:+ for todo_id in self.todos:+ t = self.todos[todo_id]+ states[todo_id] = copy.deepcopy(t.state)+ return states- def init_todos(self, groups):- self.todo_groups = groups- self.todos = {}- for g in self.todo_groups:- for t in g.get_todos():- self.todos[t.id] = t+ def init_todos(self, groups):+ self.todo_groups = groups+ self.todos = {}+ for g in self.todo_groups:+ for t in g.get_todos():+ self.todos[t.id] = tclass TodoGroup(SecretYamlObject):- yaml_tag = u'!TodoGroup'- hidden_fields = []- def __init__(self, id, title, description, todos, is_in_rc_loop=None, depends=None):- self.id = id- self.title = title- self.description = description- self.depends = depends- self.is_in_rc_loop = is_in_rc_loop- self.todos = todos-- @classmethod- def from_yaml(cls, loader, node):- fields = loader.construct_mapping(node, deep = True)- return TodoGroup(**fields)-- def num_done(self):- return sum(1 for x in self.todos if x.is_done() > 0)-- def num_applies(self):- count = sum(1 for x in self.todos if x.applies(state.release_type))- # print("num_applies=%s" % count)- return count-- def is_done(self):- # print("Done=%s, applies=%s" % (self.num_done(), self.num_applies()))- return self.num_done() >= self.num_applies()-- def get_title(self):- # print("get_title: %s" % self.is_done())- prefix = ""- if self.is_done():- prefix = "✓ "- return "%s%s (%d/%d)" % (prefix, self.title, self.num_done(), self.num_applies())-- def get_submenu(self):- menu = ConsoleMenu(title=self.title, subtitle=self.get_subtitle, prologue_text=self.get_description(),- clear_screen=False)- menu.exit_item = CustomExitItem("Return")- for todo in self.get_todos():- if todo.applies(state.release_type):- menu.append_item(todo.get_menu_item())- return menu-- def get_menu_item(self):- item = SubmenuItem(self.get_title, self.get_submenu())- return item-- def get_todos(self):- return self.todos-- def in_rc_loop(self):- return self.is_in_rc_loop is True-- def get_description(self):- desc = self.description- if desc:- return expand_jinja(desc)- else:- return None+ yaml_tag = "!TodoGroup"+ hidden_fields = []++ def __init__(self, id, title, description, todos, is_in_rc_loop=None, depends=None):+ self.id = id+ self.title = title+ self.description = description+ self.depends = depends+ self.is_in_rc_loop = is_in_rc_loop+ self.todos = todos++ @classmethod+ def from_yaml(cls, loader, node):+ fields = loader.construct_mapping(node, deep=True)+ return TodoGroup(**fields)++ def num_done(self):+ return sum(1 for x in self.todos if x.is_done() > 0)++ def num_applies(self):+ count = sum(1 for x in self.todos if x.applies(state.release_type))+ # print("num_applies=%s" % count)+ return count++ def is_done(self):+ # print("Done=%s, applies=%s" % (self.num_done(), self.num_applies()))+ return self.num_done() >= self.num_applies()++ def get_title(self):+ # print("get_title: %s" % self.is_done())+ prefix = ""+ if self.is_done():+ prefix = "✓ "+ return "%s%s (%d/%d)" % (prefix, self.title, self.num_done(), self.num_applies())++ def get_submenu(self):+ menu = ConsoleMenu(title=self.title, subtitle=self.get_subtitle, prologue_text=self.get_description(), clear_screen=False)+ menu.exit_item = CustomExitItem("Return")+ for todo in self.get_todos():+ if todo.applies(state.release_type):+ menu.append_item(todo.get_menu_item())+ return menu++ def get_menu_item(self):+ item = SubmenuItem(self.get_title, self.get_submenu())+ return item++ def get_todos(self):+ return self.todos++ def in_rc_loop(self):+ return self.is_in_rc_loop is True++ def get_description(self):+ desc = self.description+ if desc:+ return expand_jinja(desc)+ else:+ return None- def get_subtitle(self) -> str:- if self.depends:- ret_str = ""- for dep in ensure_list(self.depends):- g = state.get_group_by_id(dep)- if not g:- g = state.get_todo_by_id(dep)- if g and not g.is_done():- ret_str += "NOTE: Please first complete '%s'\n" % g.title- return ret_str.strip()- return ""+ def get_subtitle(self) -> str:+ if self.depends:+ ret_str = ""+ for dep in ensure_list(self.depends):+ g = state.get_group_by_id(dep)+ if not g:+ g = state.get_todo_by_id(dep)+ if g and not g.is_done():+ ret_str += "NOTE: Please first complete '%s'\n" % g.title+ return ret_str.strip()+ return ""class Todo(SecretYamlObject):- yaml_tag = u'!Todo'- hidden_fields = ['state']- def __init__(self, id, title, description=None, post_description=None, done=None, types=None, links=None,- commands=None, user_input=None, depends=None, vars=None, asciidoc=None, persist_vars=None,- function=None):- self.id = id- self.title = title- self.description = description- self.asciidoc = asciidoc- self.types = types- self.depends = depends- self.vars = vars- self.persist_vars = persist_vars- self.function = function- self.user_input = user_input- self.commands = commands- self.post_description = post_description- self.links = links- self.state = {}-- self.set_done(done)- if self.types:- self.types = ensure_list(self.types)- for t in self.types:- 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 self.commands:- self.commands.todo_id = self.id- for c in self.commands.commands:- c.todo_id = self.id-- @classmethod- def from_yaml(cls, loader, node):- fields = loader.construct_mapping(node, deep = True)- return Todo(**fields)-- def get_vars(self):- myvars = {}- if self.vars:- for k in self.vars:- val = self.vars[k]- if callable(val):- myvars[k] = expand_jinja(val(), vars=myvars)- else:- myvars[k] = expand_jinja(val, vars=myvars)- return myvars-- def set_done(self, is_done):- if is_done:- self.state['done_date'] = unix_time_millis(datetime.now(tz=timezone.utc))- if self.persist_vars:- for k in self.persist_vars:- self.state[k] = self.get_vars()[k]+ yaml_tag = "!Todo"+ hidden_fields = ["state"]++ def __init__(+ self,+ id,+ title,+ description=None,+ post_description=None,+ done=None,+ types=None,+ links=None,+ commands=None,+ user_input=None,+ depends=None,+ vars=None,+ asciidoc=None,+ persist_vars=None,+ function=None,+ ):+ self.id = id+ self.title = title+ self.description = description+ self.asciidoc = asciidoc+ self.types = types+ self.depends = depends+ self.vars = vars+ self.persist_vars = persist_vars+ self.function = function+ self.user_input = user_input+ self.commands = commands+ self.post_description = post_description+ self.links = links+ self.state = {}++ self.set_done(done)+ if self.types:+ self.types = ensure_list(self.types)+ for t in self.types:+ 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 self.commands:+ self.commands.todo_id = self.id+ for c in self.commands.commands:+ c.todo_id = self.id++ @classmethod+ def from_yaml(cls, loader, node):+ fields = loader.construct_mapping(node, deep=True)+ return Todo(**fields)++ def get_vars(self):+ myvars = {}+ if self.vars:+ for k in self.vars:+ val = self.vars[k]+ if callable(val):+ myvars[k] = expand_jinja(val(), vars=myvars)else:- self.state.clear()- self.state['done'] = is_done+ myvars[k] = expand_jinja(val, vars=myvars)+ return myvars++ def set_done(self, is_done):+ if is_done:+ self.state["done_date"] = unix_time_millis(datetime.now(tz=timezone.utc))+ if self.persist_vars:+ for k in self.persist_vars:+ self.state[k] = self.get_vars()[k]+ else:+ self.state.clear()+ self.state["done"] = is_done- def applies(self, type):- if self.types:- return type in self.types- return True+ def applies(self, type):+ if self.types:+ return type in self.types+ return True- def is_done(self):- return 'done' in self.state and self.state['done'] is True+ def is_done(self):+ return "done" in self.state and self.state["done"] is True- def get_title(self):- prefix = ""- if self.is_done():- prefix = "✓ "- return expand_jinja("%s%s" % (prefix, self.title), self.get_vars_and_state())+ def get_title(self):+ prefix = ""+ if self.is_done():+ prefix = "✓ "+ return expand_jinja("%s%s" % (prefix, self.title), self.get_vars_and_state())- def display_and_confirm(self):- try:- if self.depends:- for dep in ensure_list(self.depends):- g = state.get_group_by_id(dep)- if not g:- g = state.get_todo_by_id(dep)- assert g- if not g.is_done():- print("This step depends on '%s'. Please complete that first\n" % g.title)- return- desc = self.get_description()- if desc:- print("%s" % desc)- try:- if self.function and not self.is_done():- if not eval(self.function)(self):- return- except Exception as e:- print("Function call to %s for todo %s failed: %s" % (self.function, self.id, e))- raise e- if self.user_input and not self.is_done():- ui_list = ensure_list(self.user_input)- for ui in ui_list:- ui.run(self.state)- print()- if self.links:- print("\nLinks:\n")- for link in self.links:- print("- %s" % expand_jinja(link, self.get_vars_and_state()))- print()- cmds = self.get_commands()- if cmds:- if not self.is_done():- if not cmds.logs_prefix:- cmds.logs_prefix = self.id- cmds.run()- else:- print("This step is already completed. You have to first set it to 'not completed' in order to execute commands again.")- print()- if self.post_description:- print("%s" % self.get_post_description())- todostate = self.get_state()- if self.is_done() and len(todostate) > 2:- print("Variables registered\n")- for k in todostate:- if k == 'done' or k == 'done_date':- continue- print("* %s = %s" % (k, todostate[k]))- print()- completed = ask_yes_no("Mark task '%s' as completed?" % self.get_title())- self.set_done(completed)- state.save()- except Exception as e:- print("ERROR while executing todo %s (%s)" % (self.get_title(), e))+ def display_and_confirm(self):+ try:+ if self.depends:+ for dep in ensure_list(self.depends):+ g = state.get_group_by_id(dep)+ if not g:+ g = state.get_todo_by_id(dep)+ assert g+ if not g.is_done():+ print("This step depends on '%s'. Please complete that first\n" % g.title)+ return+ desc = self.get_description()+ if desc:+ print("%s" % desc)+ try:+ if self.function and not self.is_done():+ if not eval(self.function)(self):+ return+ except Exception as e:+ print("Function call to %s for todo %s failed: %s" % (self.function, self.id, e))+ raise e+ if self.user_input and not self.is_done():+ ui_list = ensure_list(self.user_input)+ for ui in ui_list:+ ui.run(self.state)+ print()+ if self.links:+ print("\nLinks:\n")+ for link in self.links:+ print("- %s" % expand_jinja(link, self.get_vars_and_state()))+ print()+ cmds = self.get_commands()+ if cmds:+ if not self.is_done():+ if not cmds.logs_prefix:+ cmds.logs_prefix = self.id+ cmds.run()+ else:+ print("This step is already completed. You have to first set it to 'not completed' in order to execute commands again.")+ print()+ if self.post_description:+ print("%s" % self.get_post_description())+ todostate = self.get_state()+ if self.is_done() and len(todostate) > 2:+ print("Variables registered\n")+ for k in todostate:+ if k == "done" or k == "done_date":+ continue+ print("* %s = %s" % (k, todostate[k]))+ print()+ completed = ask_yes_no("Mark task '%s' as completed?" % self.get_title())+ self.set_done(completed)+ state.save()+ except Exception as e:+ print("ERROR while executing todo %s (%s)" % (self.get_title(), e))- def get_menu_item(self):- return FunctionItem(self.get_title(), self.display_and_confirm)+ def get_menu_item(self):+ return FunctionItem(self.get_title(), self.display_and_confirm)- def clone(self):- clone = Todo(self.id, self.title, description=self.description)- clone.state = copy.deepcopy(self.state)- return clone+ def clone(self):+ clone = Todo(self.id, self.title, description=self.description)+ clone.state = copy.deepcopy(self.state)+ return clone- def clear(self):- self.state.clear()- self.set_done(False)+ def clear(self):+ self.state.clear()+ self.set_done(False)- def get_state(self):- return self.state+ def get_state(self):+ return self.state- def get_description(self):- desc = self.description- if desc:- return expand_jinja(desc, vars=self.get_vars_and_state())- else:- return None+ def get_description(self):+ desc = self.description+ if desc:+ return expand_jinja(desc, vars=self.get_vars_and_state())+ else:+ return None- def get_post_description(self):- if self.post_description:- return expand_jinja(self.post_description, vars=self.get_vars_and_state())- else:- return None+ def get_post_description(self):+ if self.post_description:+ return expand_jinja(self.post_description, vars=self.get_vars_and_state())+ else:+ return None- def get_commands(self):- cmds = self.commands- return cmds+ def get_commands(self):+ cmds = self.commands+ return cmds- def get_asciidoc(self):- if self.asciidoc:- return expand_jinja(self.asciidoc, vars=self.get_vars_and_state())- else:- return None+ def get_asciidoc(self):+ if self.asciidoc:+ return expand_jinja(self.asciidoc, vars=self.get_vars_and_state())+ else:+ return None- def get_vars_and_state(self):- d = self.get_vars().copy()- d.update(self.get_state())- return d+ def get_vars_and_state(self):+ d = self.get_vars().copy()+ d.update(self.get_state())+ return ddef get_release_version():- v = str(input("Which version are you releasing? (x.y.z) "))- try:- version = Version.parse(v)- except Exception:- print("Not a valid version %s" % v)- return get_release_version()+ v = str(input("Which version are you releasing? (x.y.z) "))+ try:+ version = Version.parse(v)+ except Exception:+ print("Not a valid version %s" % v)+ return get_release_version()- return str(version)+ return str(version)def get_subtitle():- applying_groups = list(filter(lambda x: x.num_applies() > 0, state.todo_groups))- done_groups = sum(1 for x in applying_groups if x.is_done())- return "Please complete the below checklist (Complete: %s/%s)" % (done_groups, len(applying_groups))+ applying_groups = list(filter(lambda x: x.num_applies() > 0, state.todo_groups))+ done_groups = sum(1 for x in applying_groups if x.is_done())+ return "Please complete the below checklist (Complete: %s/%s)" % (done_groups, len(applying_groups))def get_todo_menuitem_title():- return "Go to checklist (RC%d)" % (state.rc_number)+ return "Go to checklist (RC%d)" % (state.rc_number)def get_releasing_text():- return "Releasing Lucene %s RC%d" % (state.release_version, state.rc_number)+ return "Releasing Lucene %s RC%d" % (state.release_version, state.rc_number)def get_start_new_rc_menu_title():- return "Abort RC%d and start a new RC%d" % (state.rc_number, state.rc_number + 1)+ return "Abort RC%d and start a new RC%d" % (state.rc_number, state.rc_number + 1)def start_new_rc():- state.new_rc()- print("Started RC%d" % state.rc_number)+ state.new_rc()+ print("Started RC%d" % state.rc_number)def reset_state():- global state- if ask_yes_no("Are you sure? This will erase all current progress"):- maybe_remove_rc_from_svn()- shutil.rmtree(os.path.join(state.config_path, state.release_version))- state.clear()+ global state+ if ask_yes_no("Are you sure? This will erase all current progress"):+ maybe_remove_rc_from_svn()+ shutil.rmtree(os.path.join(state.config_path, state.release_version))+ state.clear()def template(name, vars=None):- return expand_jinja(templates[name], vars=vars)+ return expand_jinja(templates[name], vars=vars)def help():- print(template('help'))- pause()+ print(template("help"))+ pause()def ensure_list(o):- if o is None:- return []- if not isinstance(o, list):- return [o]- else:- return o+ if o is None:+ return []+ if not isinstance(o, list):+ return [o]+ else:+ return odef open_file(filename):- print("Opening file %s" % filename)- if platform.system().startswith("Win"):- run("start %s" % filename)- else:- run("open %s" % filename)+ print("Opening file %s" % filename)+ if platform.system().startswith("Win"):+ run("start %s" % filename)+ else:+ run("open %s" % filename)def expand_multiline(cmd_txt, indent=0):- return re.sub(r' +', " %s\n %s" % (Commands.cmd_continuation_char, " "*indent), cmd_txt)+ return re.sub(r" +", " %s\n %s" % (Commands.cmd_continuation_char, " " * indent), cmd_txt)def unix_to_datetime(unix_stamp):- return datetime.fromtimestamp(timestamp=unix_stamp / 1000, tz=timezone.utc)+ return datetime.fromtimestamp(timestamp=unix_stamp / 1000, tz=timezone.utc)def generate_asciidoc():- base_filename = os.path.join(state.get_release_folder(),- "lucene_release_%s"- % (state.release_version.replace(r"\.", "_")))-- filename_adoc = "%s.adoc" % base_filename- filename_html = "%s.html" % base_filename- fh = open(filename_adoc, "w")-- fh.write("= Lucene Release %s\n\n" % state.release_version)- fh.write("(_Generated by releaseWizard.py v%s at %s_)\n\n"- % (getScriptVersion(), datetime.now(tz=timezone.utc).strftime("%Y-%m-%d %H:%M UTC")))- fh.write(":numbered:\n\n")- fh.write("%s\n\n" % template('help'))- for group in state.todo_groups:- if group.num_applies() == 0:- continue- fh.write("== %s\n\n" % group.get_title())- fh.write("%s\n\n" % group.get_description())- for todo in group.get_todos():- if not todo.applies(state.release_type):- continue- fh.write("=== %s\n\n" % todo.get_title())- if todo.is_done():- fh.write("_Completed %s_\n\n" % unix_to_datetime(todo.state['done_date']).strftime(- "%Y-%m-%d %H:%M UTC"))- if todo.get_asciidoc():- fh.write("%s\n\n" % todo.get_asciidoc())+ base_filename = os.path.join(state.get_release_folder(), "lucene_release_%s" % (state.release_version.replace(r"\.", "_")))++ filename_adoc = "%s.adoc" % base_filename+ filename_html = "%s.html" % base_filename+ fh = open(filename_adoc, "w")++ fh.write("= Lucene Release %s\n\n" % state.release_version)+ fh.write("(_Generated by releaseWizard.py v%s at %s_)\n\n" % (getScriptVersion(), datetime.now(tz=timezone.utc).strftime("%Y-%m-%d %H:%M UTC")))+ fh.write(":numbered:\n\n")+ fh.write("%s\n\n" % template("help"))+ for group in state.todo_groups:+ if group.num_applies() == 0:+ continue+ fh.write("== %s\n\n" % group.get_title())+ fh.write("%s\n\n" % group.get_description())+ for todo in group.get_todos():+ if not todo.applies(state.release_type):+ continue+ fh.write("=== %s\n\n" % todo.get_title())+ if todo.is_done():+ fh.write("_Completed %s_\n\n" % unix_to_datetime(todo.state["done_date"]).strftime("%Y-%m-%d %H:%M UTC"))+ if todo.get_asciidoc():+ fh.write("%s\n\n" % todo.get_asciidoc())+ else:+ desc = todo.get_description()+ if desc:+ fh.write("%s\n\n" % desc)+ state_copy = copy.deepcopy(todo.state)+ state_copy.pop("done", None)+ state_copy.pop("done_date", None)+ if len(state_copy) > 0 or todo.user_input is not None:+ fh.write(".Variables collected in this step\n")+ fh.write("|===\n")+ fh.write("|Variable |Value\n")+ mykeys = set()+ for e in ensure_list(todo.user_input):+ mykeys.add(e.name)+ for e in state_copy.keys():+ mykeys.add(e)+ for key in mykeys:+ val = "(not set)"+ if key in state_copy:+ val = state_copy[key]+ fh.write("\n|%s\n|%s\n" % (key, val))+ fh.write("|===\n\n")+ cmds = todo.get_commands()+ if cmds:+ if cmds.commands_text:+ fh.write("%s\n\n" % cmds.get_commands_text())+ fh.write("[source,sh]\n----\n")+ if cmds.env:+ for key in cmds.env:+ val = cmds.env[key]+ if is_windows():+ fh.write("SET %s=%s\n" % (key, val))else:- desc = todo.get_description()- if desc:- fh.write("%s\n\n" % desc)- state_copy = copy.deepcopy(todo.state)- state_copy.pop('done', None)- state_copy.pop('done_date', None)- if len(state_copy) > 0 or todo.user_input is not None:- fh.write(".Variables collected in this step\n")- fh.write("|===\n")- fh.write("|Variable |Value\n")- mykeys = set()- for e in ensure_list(todo.user_input):- mykeys.add(e.name)- for e in state_copy.keys():- mykeys.add(e)- for key in mykeys:- val = "(not set)"- if key in state_copy:- val = state_copy[key]- fh.write("\n|%s\n|%s\n" % (key, val))- fh.write("|===\n\n")- cmds = todo.get_commands()- if cmds:- if cmds.commands_text:- fh.write("%s\n\n" % cmds.get_commands_text())- fh.write("[source,sh]\n----\n")- if cmds.env:- for key in cmds.env:- val = cmds.env[key]- if is_windows():- fh.write("SET %s=%s\n" % (key, val))- else:- fh.write("export %s=%s\n" % (key, val))- fh.write(abbreviate_homedir("cd %s\n" % cmds.get_root_folder()))- cmds2 = ensure_list(cmds.commands)- for c in cmds2:- for line in c.display_cmd():- fh.write("%s\n" % line)- fh.write("----\n\n")- if todo.post_description and not todo.get_asciidoc():- fh.write("\n%s\n\n" % todo.get_post_description())- if todo.links:- fh.write("Links:\n\n")- for link in todo.links:- fh.write("* %s\n" % expand_jinja(link))- fh.write("\n")-- fh.close()- print("Wrote file %s" % os.path.join(state.get_release_folder(), filename_adoc))- print("Running command 'asciidoctor %s'" % filename_adoc)- run_follow("asciidoctor %s" % filename_adoc)- if os.path.exists(filename_html):- open_file(filename_html)- else:- print("Failed generating HTML version, please install asciidoctor")- pause()+ fh.write("export %s=%s\n" % (key, val))+ fh.write(abbreviate_homedir("cd %s\n" % cmds.get_root_folder()))+ cmds2 = ensure_list(cmds.commands)+ for c in cmds2:+ for line in c.display_cmd():+ fh.write("%s\n" % line)+ fh.write("----\n\n")+ if todo.post_description and not todo.get_asciidoc():+ fh.write("\n%s\n\n" % todo.get_post_description())+ if todo.links:+ fh.write("Links:\n\n")+ for link in todo.links:+ fh.write("* %s\n" % expand_jinja(link))+ fh.write("\n")++ fh.close()+ print("Wrote file %s" % os.path.join(state.get_release_folder(), filename_adoc))+ print("Running command 'asciidoctor %s'" % filename_adoc)+ run_follow("asciidoctor %s" % filename_adoc)+ if os.path.exists(filename_html):+ open_file(filename_html)+ else:+ print("Failed generating HTML version, please install asciidoctor")+ pause()def load_rc():- lucenerc = os.path.expanduser("~/.lucenerc")- try:- with open(lucenerc, 'r') as fp:- return json.load(fp)- except Exception:- return {}+ lucenerc = os.path.expanduser("~/.lucenerc")+ try:+ with open(lucenerc, "r") as fp:+ return json.load(fp)+ except Exception:+ return {}def store_rc(release_root, release_version=None):- lucenerc = os.path.expanduser("~/.lucenerc")- dict = {}- dict['root'] = release_root- if release_version:- dict['release_version'] = release_version- with open(lucenerc, "w") as fp:- json.dump(dict, fp, indent=2)+ lucenerc = os.path.expanduser("~/.lucenerc")+ dict = {}+ dict["root"] = release_root+ if release_version:+ dict["release_version"] = release_version+ with open(lucenerc, "w") as fp:+ json.dump(dict, fp, indent=2)def release_other_version():- if not state.is_released():- maybe_remove_rc_from_svn()- store_rc(state.config_path, None)- print("Please restart the wizard")- sys.exit(0)+ if not state.is_released():+ maybe_remove_rc_from_svn()+ store_rc(state.config_path, None)+ print("Please restart the wizard")+ sys.exit(0)+def file_to_string(filename):- with open(filename, encoding='utf8') as f:- return f.read().strip()+ with open(filename, encoding="utf8") as f:+ return f.read().strip()+def download_keys():- download('KEYS', "https://archive.apache.org/dist/lucene/KEYS", state.config_path)+ download("KEYS", "https://archive.apache.org/dist/lucene/KEYS", state.config_path)+def keys_downloaded():- return os.path.exists(os.path.join(state.config_path, "KEYS"))+ return os.path.exists(os.path.join(state.config_path, "KEYS"))def dump_yaml():- file = open(os.path.join(script_path, "releaseWizard.yaml"), "w")- yaml.add_representer(str, str_presenter)- yaml.Dumper.ignore_aliases = lambda self, data : True- dump_obj = {'templates': templates,- 'groups': state.todo_groups}- yaml.dump(dump_obj, width=180, stream=file, sort_keys=False, default_flow_style=False)+ file = open(os.path.join(script_path, "releaseWizard.yaml"), "w")+ yaml.add_representer(str, str_presenter)+ yaml.Dumper.ignore_aliases = lambda self, data: True+ dump_obj = {"templates": templates, "groups": state.todo_groups}+ yaml.dump(dump_obj, width=180, stream=file, sort_keys=False, default_flow_style=False)def parse_config():- description = 'Script to guide a RM through the whole release process'- parser = argparse.ArgumentParser(description=description, epilog="Go push that release!",- formatter_class=argparse.RawDescriptionHelpFormatter)- parser.add_argument('--dry-run', dest='dry', action='store_true', default=False,- help='Do not execute any commands, but echo them instead. Display extra debug info')- parser.add_argument('--init', action='store_true', default=False,- help='Re-initialize root and version')- config = parser.parse_args()+ description = "Script to guide a RM through the whole release process"+ parser = argparse.ArgumentParser(description=description, epilog="Go push that release!", formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--dry-run", dest="dry", action="store_true", default=False, help="Do not execute any commands, but echo them instead. Display extra debug info")+ parser.add_argument("--init", action="store_true", default=False, help="Re-initialize root and version")+ config = parser.parse_args()- return config+ return configdef load(urlString, encoding="utf-8"):- try:- content = urllib.request.urlopen(urlString).read().decode(encoding)- except Exception as e:- print('Retrying download of url %s after exception: %s' % (urlString, e))- content = urllib.request.urlopen(urlString).read().decode(encoding)- return content+ try:+ content = urllib.request.urlopen(urlString).read().decode(encoding)+ except Exception as e:+ print("Retrying download of url %s after exception: %s" % (urlString, e))+ content = urllib.request.urlopen(urlString).read().decode(encoding)+ return contentdef configure_pgp(gpg_todo):- print("Based on your Apache ID we'll lookup your key online\n"- "and through this complete the 'gpg' prerequisite task.\n")- gpg_state = gpg_todo.get_state()- id = str(input("Please enter your Apache id: (ENTER=skip) "))- if id.strip() == '':- return False- key_url = "https://home.apache.org/keys/committer/%s.asc" % id.strip()- committer_key = load(key_url)- lines = committer_key.splitlines()- keyid_linenum = None- for idx, line in enumerate(lines):- if line == 'ASF ID: %s' % id:- keyid_linenum = idx+1- break- if keyid_linenum:- keyid_line = lines[keyid_linenum]- assert keyid_line.startswith('LDAP PGP key: ')- gpg_fingerprint = keyid_line[14:].replace(" ", "")- gpg_id = gpg_fingerprint[-8:]- print("Found gpg key id %s on file at Apache (%s)" % (gpg_id, key_url))- else:- print(textwrap.dedent("""\+ print("Based on your Apache ID we'll lookup your key online\nand through this complete the 'gpg' prerequisite task.\n")+ gpg_state = gpg_todo.get_state()+ id = str(input("Please enter your Apache id: (ENTER=skip) "))+ if id.strip() == "":+ return False+ key_url = "https://home.apache.org/keys/committer/%s.asc" % id.strip()+ committer_key = load(key_url)+ lines = committer_key.splitlines()+ keyid_linenum = None+ for idx, line in enumerate(lines):+ if line == "ASF ID: %s" % id:+ keyid_linenum = idx + 1+ break+ if keyid_linenum:+ keyid_line = lines[keyid_linenum]+ assert keyid_line.startswith("LDAP PGP key: ")+ gpg_fingerprint = keyid_line[14:].replace(" ", "")+ gpg_id = gpg_fingerprint[-8:]+ print("Found gpg key id %s on file at Apache (%s)" % (gpg_id, key_url))+ else:+ print(+ textwrap.dedent("""\Could not find your GPG key from Apache servers.Please make sure you have registered your key ID in- id.apache.org, see links for more info."""))- gpg_fingerprint = str(input("Enter your key fingerprint manually, all 40 characters (ENTER=skip): "))- if gpg_fingerprint.strip() == '':- return False- elif len(gpg_fingerprint) != 40:- print("gpg fingerprint must be 40 characters long, do not just input the last 8")- gpg_fingerprint = gpg_fingerprint.upper()- gpg_id = gpg_fingerprint[-8:]- try:- res = run("gpg --list-secret-keys %s" % gpg_fingerprint)- print("Found key %s on your private gpg keychain" % gpg_id)- # Check rsa and key length >= 4096- match = re.search(r'^sec#? +((rsa|dsa)(\d{4})) ', res)- type = "(unknown)"- length = -1- if match:- type = match.group(2)- length = int(match.group(3))- else:- match = re.search(r'^sec#? +((\d{4})([DR])/.*?) ', res)- if match:- type = 'rsa' if match.group(3) == 'R' else 'dsa'- length = int(match.group(2))- else:- print("Could not determine type and key size for your key")- print("%s" % res)- if not ask_yes_no("Is your key of type RSA and size >= 2048 (ideally 4096)? "):- print("Sorry, please generate a new key, add to KEYS and register with id.apache.org")- return False- if not type == 'rsa':- print("We strongly recommend RSA type key, your is '%s'. Consider generating a new key." % type.upper())- if length < 2048:- print("Your key has key length of %s. Cannot use < 2048, please generate a new key before doing the release" % length)- return False- if length < 4096:- print("Your key length is < 4096, Please generate a stronger key.")- print("Alternatively, follow instructions in https://infra.apache.org/release-signing.html#note")- if not ask_yes_no("Have you configured your gpg to avoid SHA-1?"):- print("Please either generate a strong key or reconfigure your client")- return False- print("Validated that your key is of type RSA and has a length >= 2048 (%s)" % length)- except Exception:- print(textwrap.dedent("""\- Key not found on your private gpg keychain. In order to sign the release you'll- need to fix this, then try again"""))+ id.apache.org, see links for more info.""")+ )+ gpg_fingerprint = str(input("Enter your key fingerprint manually, all 40 characters (ENTER=skip): "))+ if gpg_fingerprint.strip() == "":+ return False+ elif len(gpg_fingerprint) != 40:+ print("gpg fingerprint must be 40 characters long, do not just input the last 8")+ gpg_fingerprint = gpg_fingerprint.upper()+ gpg_id = gpg_fingerprint[-8:]+ try:+ res = run("gpg --list-secret-keys %s" % gpg_fingerprint)+ print("Found key %s on your private gpg keychain" % gpg_id)+ # Check rsa and key length >= 4096+ match = re.search(r"^sec#? +((rsa|dsa)(\d{4})) ", res)+ type = "(unknown)"+ length = -1+ if match:+ type = match.group(2)+ length = int(match.group(3))+ else:+ match = re.search(r"^sec#? +((\d{4})([DR])/.*?) ", res)+ if match:+ type = "rsa" if match.group(3) == "R" else "dsa"+ length = int(match.group(2))+ else:+ print("Could not determine type and key size for your key")+ print("%s" % res)+ if not ask_yes_no("Is your key of type RSA and size >= 2048 (ideally 4096)? "):+ print("Sorry, please generate a new key, add to KEYS and register with id.apache.org")+ return False+ if not type == "rsa":+ print("We strongly recommend RSA type key, your is '%s'. Consider generating a new key." % type.upper())+ if length < 2048:+ print("Your key has key length of %s. Cannot use < 2048, please generate a new key before doing the release" % length)+ return False+ if length < 4096:+ print("Your key length is < 4096, Please generate a stronger key.")+ print("Alternatively, follow instructions in https://infra.apache.org/release-signing.html#note")+ if not ask_yes_no("Have you configured your gpg to avoid SHA-1?"):+ print("Please either generate a strong key or reconfigure your client")return False- try:- lines = run("gpg --check-signatures %s" % gpg_fingerprint).splitlines()- sigs = 0- apache_sigs = 0- for line in lines:- if line.startswith("sig") and gpg_id not in line:- sigs += 1- if '@apache.org' in line:- apache_sigs += 1- print("Your key has %s signatures, of which %s are by committers (@apache.org address)" % (sigs, apache_sigs))- if apache_sigs < 1:- print(textwrap.dedent("""\+ print("Validated that your key is of type RSA and has a length >= 2048 (%s)" % length)+ except Exception:+ print(+ textwrap.dedent("""\+ Key not found on your private gpg keychain. In order to sign the release you'll+ need to fix this, then try again""")+ )+ return False+ try:+ lines = run("gpg --check-signatures %s" % gpg_fingerprint).splitlines()+ sigs = 0+ apache_sigs = 0+ for line in lines:+ if line.startswith("sig") and gpg_id not in line:+ sigs += 1+ if "@apache.org" in line:+ apache_sigs += 1+ print("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.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."""))- uses_apacheid = is_code_signing_key = False- for line in lines:- if line.startswith("uid") and "%s@apache" % id in line:- uses_apacheid = True- if 'CODE SIGNING KEY' in line.upper():- is_code_signing_key = True- if not uses_apacheid:- print("WARNING: Your key should use your apache-id email address, see https://infra.apache.org/release-signing.html#user-id")- if not is_code_signing_key:- print("WARNING: You code signing key should be labeled 'CODE SIGNING KEY', see https://infra.apache.org/release-signing.html#key-comment")- except Exception as e:- print("Could not check signatures of your key: %s" % e)-- download_keys()- keys_text = file_to_string(os.path.join(state.config_path, "KEYS"))- if gpg_id in keys_text or "%s %s" % (gpg_id[:4], gpg_id[-4:]) in keys_text:- print("Found your key ID in official KEYS file. KEYS file is not cached locally.")- else:- print(textwrap.dedent("""\+ You may want to run 'gpg --refresh-keys' to refresh your keychain.""")+ )+ uses_apacheid = is_code_signing_key = False+ for line in lines:+ if line.startswith("uid") and "%s@apache" % id in line:+ uses_apacheid = True+ if "CODE SIGNING KEY" in line.upper():+ is_code_signing_key = True+ if not uses_apacheid:+ print("WARNING: Your key should use your apache-id email address, see https://infra.apache.org/release-signing.html#user-id")+ if not is_code_signing_key:+ print("WARNING: You code signing key should be labeled 'CODE SIGNING KEY', see https://infra.apache.org/release-signing.html#key-comment")+ except Exception as e:+ print("Could not check signatures of your key: %s" % e)++ download_keys()+ keys_text = file_to_string(os.path.join(state.config_path, "KEYS"))+ if gpg_id in keys_text or "%s %s" % (gpg_id[:4], gpg_id[-4:]) in keys_text:+ print("Found your key ID in official KEYS file. KEYS file is not cached locally.")+ else:+ print(+ textwrap.dedent("""\Could not find your key ID in official KEYS file.Please make sure it is added to https://dist.apache.org/repos/dist/release/lucene/KEYS- and committed to svn. Then re-try this initialization"""))- if not ask_yes_no("Do you want to continue without fixing KEYS file? (not recommended) "):- return False+ and committed to svn. Then re-try this initialization""")+ )+ if not ask_yes_no("Do you want to continue without fixing KEYS file? (not recommended) "):+ return False- gpg_state['apache_id'] = id- gpg_state['gpg_key'] = gpg_id- gpg_state['gpg_fingerprint'] = gpg_fingerprint+ gpg_state["apache_id"] = id+ gpg_state["gpg_key"] = gpg_id+ gpg_state["gpg_fingerprint"] = gpg_fingerprint- print(textwrap.dedent("""\+ print(+ textwrap.dedent("""\You can choose between signing the release with the gpg program or withthe gradle signing plugin. Read about the difference by running- ./gradlew helpPublishing"""))+ ./gradlew helpPublishing""")+ )- gpg_state['use_gradle'] = ask_yes_no("Do you want to sign the release with gradle plugin? No means gpg")+ gpg_state["use_gradle"] = ask_yes_no("Do you want to sign the release with gradle plugin? No means gpg")- print(textwrap.dedent("""\+ 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 tobuildAndPushRelease 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? ")+ 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? ")- return True+ return Truedef pause(fun=None):- if fun:- fun()- input("\nPress ENTER to continue...")+ if fun:+ fun()+ input("\nPress ENTER to continue...")class CustomExitItem(ExitItem):- def show(self, index, available_width=None):- return super(CustomExitItem, self).show(index)+ def show(self, index, available_width=None):+ return super(CustomExitItem, self).show(index)- def get_return(self):- return ""+ def get_return(self):+ return ""def main():- global state- global dry_run- global templates+ global state+ global dry_run+ global templates- print("Lucene releaseWizard v%s" % getScriptVersion())+ print("Lucene releaseWizard v%s" % getScriptVersion())- try:- ConsoleMenu(clear_screen=True)- 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'")-- c = parse_config()-- if c.dry:- print("Entering dry-run mode where all commands will be echoed instead of executed")- dry_run = True-- release_root = os.path.expanduser("~/.lucene-releases")- if not load_rc() or c.init:- print("Initializing")- root = 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)- if not root == '':- if root.startswith("~/"):- release_root = os.path.expanduser(root)- else:- release_root = os.path.abspath(root)- if not os.path.exists(release_root):- try:- print("Creating release root %s" % release_root)- os.makedirs(release_root)- except Exception as e:- sys.exit("Error while creating %s: %s" % (release_root, e))- release_version = get_release_version()+ try:+ ConsoleMenu(clear_screen=True)+ 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'")++ c = parse_config()++ if c.dry:+ print("Entering dry-run mode where all commands will be echoed instead of executed")+ dry_run = True++ release_root = os.path.expanduser("~/.lucene-releases")+ if not load_rc() or c.init:+ print("Initializing")+ root = 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)+ if not root == "":+ if root.startswith("~/"):+ release_root = os.path.expanduser(root)+ else:+ release_root = os.path.abspath(root)+ if not os.path.exists(release_root):+ try:+ print("Creating release root %s" % release_root)+ os.makedirs(release_root)+ except Exception as e:+ sys.exit("Error while creating %s: %s" % (release_root, e))+ release_version = get_release_version()+ else:+ conf = load_rc()+ release_root = conf["root"]+ if conf and "release_version" in conf:+ release_version = conf["release_version"]else:- conf = load_rc()- release_root = conf['root']- if conf and 'release_version' in conf:- release_version = conf['release_version']- else:- release_version = get_release_version()- store_rc(release_root, release_version)+ release_version = get_release_version()+ store_rc(release_root, release_version)- check_prerequisites()+ check_prerequisites()- try:- y = yaml.load(open(os.path.join(script_path, "releaseWizard.yaml"), "r"), Loader=yaml.Loader)- templates = y.get('templates')- todo_list = y.get('groups')- state = ReleaseState(release_root, release_version, getScriptVersion())- state.init_todos(bootstrap_todos(todo_list))- state.load()- except Exception as e:- sys.exit("Failed initializing. %s" % e)-- state.save()-- # Smoketester requires JAVA11_HOME to point to Java11- os.environ['JAVA_HOME'] = state.get_java_home()- os.environ['JAVACMD'] = state.get_java_cmd()-- global lucene_news_file- lucene_news_file = os.path.join(state.get_website_git_folder(), 'content', 'core', 'core_news',- "%s-%s-available.md" % (state.get_release_date_iso(), state.release_version.replace(".", "-")))-- main_menu = ConsoleMenu(title="Lucene ReleaseWizard",- subtitle=get_releasing_text,- prologue_text="Welcome to the release wizard. From here you can manage the process including creating new RCs. "- "All changes are persisted, so you can exit any time and continue later. Make sure to read the Help section.",- epilogue_text="® 2022 The Lucene project. Licensed under the Apache License 2.0\nScript version v%s)" % getScriptVersion(),- clear_screen=False)-- todo_menu = ConsoleMenu(title=get_releasing_text,- subtitle=get_subtitle,- prologue_text=None,- epilogue_text=None,- clear_screen=False)- todo_menu.exit_item = CustomExitItem("Return")-- for todo_group in state.todo_groups:- if todo_group.num_applies() >= 0:- menu_item = todo_group.get_menu_item()- menu_item.set_menu(todo_menu)- todo_menu.append_item(menu_item)-- main_menu.append_item(SubmenuItem(get_todo_menuitem_title, todo_menu, menu=main_menu))- main_menu.append_item(FunctionItem(get_start_new_rc_menu_title(), start_new_rc))- main_menu.append_item(FunctionItem('Clear and restart current RC', state.clear_rc))- main_menu.append_item(FunctionItem("Clear all state, restart the %s release" % state.release_version, reset_state))- main_menu.append_item(FunctionItem('Start release for a different version', release_other_version))- main_menu.append_item(FunctionItem('Generate Asciidoc guide for this release', generate_asciidoc))- # main_menu.append_item(FunctionItem('Dump YAML', dump_yaml))- main_menu.append_item(FunctionItem('Help', help))-- main_menu.show()+ try:+ y = yaml.load(open(os.path.join(script_path, "releaseWizard.yaml"), "r"), Loader=yaml.Loader)+ templates = y.get("templates")+ todo_list = y.get("groups")+ state = ReleaseState(release_root, release_version, getScriptVersion())+ state.init_todos(bootstrap_todos(todo_list))+ state.load()+ except Exception as e:+ sys.exit("Failed initializing. %s" % e)++ state.save()++ # Smoketester requires JAVA11_HOME to point to Java11+ os.environ["JAVA_HOME"] = state.get_java_home()+ os.environ["JAVACMD"] = state.get_java_cmd()++ global lucene_news_file+ lucene_news_file = os.path.join(state.get_website_git_folder(), "content", "core", "core_news", "%s-%s-available.md" % (state.get_release_date_iso(), state.release_version.replace(".", "-")))++ main_menu = ConsoleMenu(+ title="Lucene ReleaseWizard",+ subtitle=get_releasing_text,+ prologue_text="Welcome to the release wizard. From here you can manage the process including creating new RCs. "+ "All changes are persisted, so you can exit any time and continue later. Make sure to read the Help section.",+ epilogue_text="® 2022 The Lucene project. Licensed under the Apache License 2.0\nScript version v%s)" % getScriptVersion(),+ clear_screen=False,+ )++ todo_menu = ConsoleMenu(title=get_releasing_text, subtitle=get_subtitle, prologue_text=None, epilogue_text=None, clear_screen=False)+ todo_menu.exit_item = CustomExitItem("Return")++ for todo_group in state.todo_groups:+ if todo_group.num_applies() >= 0:+ menu_item = todo_group.get_menu_item()+ menu_item.set_menu(todo_menu)+ todo_menu.append_item(menu_item)++ main_menu.append_item(SubmenuItem(get_todo_menuitem_title, todo_menu, menu=main_menu))+ main_menu.append_item(FunctionItem(get_start_new_rc_menu_title(), start_new_rc))+ main_menu.append_item(FunctionItem("Clear and restart current RC", state.clear_rc))+ main_menu.append_item(FunctionItem("Clear all state, restart the %s release" % state.release_version, reset_state))+ main_menu.append_item(FunctionItem("Start release for a different version", release_other_version))+ main_menu.append_item(FunctionItem("Generate Asciidoc guide for this release", generate_asciidoc))+ # main_menu.append_item(FunctionItem('Dump YAML', dump_yaml))+ main_menu.append_item(FunctionItem("Help", help))++ main_menu.show()sys.path.append(os.path.dirname(__file__))-current_git_root = os.path.abspath(- os.path.join(os.path.abspath(os.path.dirname(__file__)), os.path.pardir, os.path.pardir))+current_git_root = os.path.abspath(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.path.pardir, os.path.pardir))dry_run = False-major_minor = ['major', 'minor']+major_minor = ["major", "minor"]script_path = os.path.dirname(os.path.realpath(__file__))os.chdir(script_path)def git_checkout_folder():- return state.get_git_checkout_folder()+ return state.get_git_checkout_folder()def tail_file(file, lines):- bufsize = 8192- fsize = os.stat(file).st_size- with open(file) as f:- if bufsize >= fsize:- bufsize = fsize- idx = 0- while True:- idx += 1- seek_pos = fsize - bufsize * idx- if seek_pos < 0:- seek_pos = 0- f.seek(seek_pos)- data = []- data.extend(f.readlines())- if len(data) >= lines or f.tell() == 0 or seek_pos == 0:- if not seek_pos == 0:- print("Tailing last %d lines of file %s" % (lines, file))- print(''.join(data[-lines:]))- break+ bufsize = 8192+ fsize = os.stat(file).st_size+ with open(file) as f:+ if bufsize >= fsize:+ bufsize = fsize+ idx = 0+ while True:+ idx += 1+ seek_pos = fsize - bufsize * idx+ if seek_pos < 0:+ seek_pos = 0+ f.seek(seek_pos)+ data = []+ data.extend(f.readlines())+ if len(data) >= lines or f.tell() == 0 or seek_pos == 0:+ if not seek_pos == 0:+ print("Tailing last %d lines of file %s" % (lines, file))+ print("".join(data[-lines:]))+ breakdef run_with_log_tail(command, cwd, logfile=None, tail_lines=10, tee=False, live=False, shell=None):- fh = sys.stdout- if logfile:- logdir = os.path.dirname(logfile)- if not os.path.exists(logdir):- os.makedirs(logdir)- fh = open(logfile, 'w')- rc = run_follow(command, cwd, fh=fh, tee=tee, live=live, shell=shell)- if logfile:- fh.close()- if not tee and tail_lines and tail_lines > 0:- tail_file(logfile, tail_lines)- return rc+ fh = sys.stdout+ if logfile:+ logdir = os.path.dirname(logfile)+ if not os.path.exists(logdir):+ os.makedirs(logdir)+ fh = open(logfile, "w")+ rc = run_follow(command, cwd, fh=fh, tee=tee, live=live, shell=shell)+ if logfile:+ fh.close()+ if not tee and tail_lines and tail_lines > 0:+ tail_file(logfile, tail_lines)+ return rcdef ask_yes_no(text):- answer = None- while answer not in ['y', 'n']:- answer = str(input("\nQ: %s (y/n): " % text))- print("\n")- return answer == 'y'+ answer = None+ while answer not in ["y", "n"]:+ answer = str(input("\nQ: %s (y/n): " % text))+ print("\n")+ return answer == "y"def abbreviate_line(line, width):- line = line.rstrip()- if len(line) > width:- line = "%s.....%s" % (line[:(width / 2 - 5)], line[-(width / 2):])- else:- line = "%s%s" % (line, " " * (width - len(line) + 2))- return line+ line = line.rstrip()+ if len(line) > width:+ line = "%s.....%s" % (line[: (width / 2 - 5)], line[-(width / 2) :])+ else:+ line = "%s%s" % (line, " " * (width - len(line) + 2))+ return linedef print_line_cr(line, linenum, stdout=True, tee=False):- if not tee:- if not stdout:- print("[line %s] %s" % (linenum, abbreviate_line(line, 80)), end='\r')+ if not tee:+ if not stdout:+ print("[line %s] %s" % (linenum, abbreviate_line(line, 80)), end="\r")+ else:+ if line.endswith("\r"):+ print(line.rstrip(), end="\r")else:- if line.endswith("\r"):- print(line.rstrip(), end='\r')- else:- print(line.rstrip())+ print(line.rstrip())def run_follow(command, cwd=None, fh=sys.stdout, tee=False, live=False, shell=None):- doShell = '&&' in command or '&' in command or shell is not None- if not doShell and not isinstance(command, list):- command = shlex.split(command)- process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd,- universal_newlines=True, bufsize=0, close_fds=True, shell=doShell)- lines_written = 0-- assert process.stdout- fl = fcntl.fcntl(process.stdout, fcntl.F_GETFL)- fcntl.fcntl(process.stdout, fcntl.F_SETFL, fl | os.O_NONBLOCK)-- assert process.stderr- flerr = fcntl.fcntl(process.stderr, fcntl.F_GETFL)- fcntl.fcntl(process.stderr, fcntl.F_SETFL, flerr | os.O_NONBLOCK)-- endstdout = endstderr = False- errlines = []- while not (endstderr and endstdout):- lines_before = lines_written- if not endstdout:- try:- if live:- chars = process.stdout.read()- if chars == '' and process.poll() is not None:- endstdout = True- else:- fh.write(chars)- fh.flush()- if '\n' in chars:- lines_written += 1- else:- line = process.stdout.readline()- if line == '' and process.poll() is not None:- endstdout = True- else:- fh.write("%s\n" % line.rstrip())- fh.flush()- lines_written += 1- print_line_cr(line, lines_written, stdout=(fh == sys.stdout), tee=tee)-- except Exception:- pass- if not endstderr:- try:- if live:- chars = process.stderr.read()- if chars == '' and process.poll() is not None:- endstderr = True- else:- fh.write(chars)- fh.flush()- if '\n' in chars:- lines_written += 1- else:- line = process.stderr.readline()- if line == '' and process.poll() is not None:- endstderr = True- else:- errlines.append("%s\n" % line.rstrip())- lines_written += 1- print_line_cr(line, lines_written, stdout=(fh == sys.stdout), tee=tee)- except Exception:- pass-- if not lines_written > lines_before:- # if no output then sleep a bit before checking again- time.sleep(0.1)-- print(" " * 80)- rc = process.poll()- if len(errlines) > 0:- for line in errlines:+ doShell = "&&" in command or "&" in command or shell is not None+ if not doShell and not isinstance(command, list):+ command = shlex.split(command)+ process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, universal_newlines=True, bufsize=0, close_fds=True, shell=doShell)+ lines_written = 0++ assert process.stdout+ fl = fcntl.fcntl(process.stdout, fcntl.F_GETFL)+ fcntl.fcntl(process.stdout, fcntl.F_SETFL, fl | os.O_NONBLOCK)++ assert process.stderr+ flerr = fcntl.fcntl(process.stderr, fcntl.F_GETFL)+ fcntl.fcntl(process.stderr, fcntl.F_SETFL, flerr | os.O_NONBLOCK)++ endstdout = endstderr = False+ errlines = []+ while not (endstderr and endstdout):+ lines_before = lines_written+ if not endstdout:+ try:+ if live:+ chars = process.stdout.read()+ if chars == "" and process.poll() is not None:+ endstdout = True+ else:+ fh.write(chars)+ fh.flush()+ if "\n" in chars:+ lines_written += 1+ else:+ line = process.stdout.readline()+ if line == "" and process.poll() is not None:+ endstdout = True+ else:fh.write("%s\n" % line.rstrip())fh.flush()- return rc+ lines_written += 1+ print_line_cr(line, lines_written, stdout=(fh == sys.stdout), tee=tee)++ except Exception:+ pass+ if not endstderr:+ try:+ if live:+ chars = process.stderr.read()+ if chars == "" and process.poll() is not None:+ endstderr = True+ else:+ fh.write(chars)+ fh.flush()+ if "\n" in chars:+ lines_written += 1+ else:+ line = process.stderr.readline()+ if line == "" and process.poll() is not None:+ endstderr = True+ else:+ errlines.append("%s\n" % line.rstrip())+ lines_written += 1+ print_line_cr(line, lines_written, stdout=(fh == sys.stdout), tee=tee)+ except Exception:+ pass++ if not lines_written > lines_before:+ # if no output then sleep a bit before checking again+ time.sleep(0.1)++ print(" " * 80)+ rc = process.poll()+ if len(errlines) > 0:+ for line in errlines:+ fh.write("%s\n" % line.rstrip())+ fh.flush()+ return rcdef is_windows():- return platform.system().startswith("Win")+ return platform.system().startswith("Win")+def is_mac():- return platform.system().startswith("Darwin")+ return platform.system().startswith("Darwin")+def is_linux():- return platform.system().startswith("Linux")+ return platform.system().startswith("Linux")+class Commands(SecretYamlObject):- yaml_tag = u'!Commands'- hidden_fields = ['todo_id']- cmd_continuation_char = "^" if is_windows() else "\\"- def __init__(self, root_folder, commands_text=None, commands=[], logs_prefix=None, run_text=None, enable_execute=None,- confirm_each_command=None, env=None, vars=None, todo_id=None, remove_files=None):- self.root_folder = root_folder- self.commands_text = commands_text- self.vars = vars- self.env = env- self.run_text = run_text- self.remove_files = remove_files- self.todo_id = todo_id- self.logs_prefix = logs_prefix- self.enable_execute = enable_execute- self.confirm_each_command = confirm_each_command- self.commands = commands- for c in self.commands:- c.todo_id = todo_id-- @classmethod- def from_yaml(cls, loader, node):- fields = loader.construct_mapping(node, deep = True)- return Commands(**fields)-- def run(self): # pylint: disable=inconsistent-return-statements # TODO- root = self.get_root_folder()-- if self.commands_text:- print(self.get_commands_text())- if self.env:- for key in self.env:- val = self.jinjaify(self.env[key])- os.environ[key] = str(val)- if is_windows():- print("\n SET %s=%s" % (key, val))+ yaml_tag = "!Commands"+ hidden_fields = ["todo_id"]+ cmd_continuation_char = "^" if is_windows() else "\\"++ def __init__(+ self, root_folder, commands_text=None, commands=[], logs_prefix=None, run_text=None, enable_execute=None, confirm_each_command=None, env=None, vars=None, todo_id=None, remove_files=None+ ):+ self.root_folder = root_folder+ self.commands_text = commands_text+ self.vars = vars+ self.env = env+ self.run_text = run_text+ self.remove_files = remove_files+ self.todo_id = todo_id+ self.logs_prefix = logs_prefix+ self.enable_execute = enable_execute+ self.confirm_each_command = confirm_each_command+ self.commands = commands+ for c in self.commands:+ c.todo_id = todo_id++ @classmethod+ def from_yaml(cls, loader, node):+ fields = loader.construct_mapping(node, deep=True)+ return Commands(**fields)++ def run(self): # pylint: disable=inconsistent-return-statements # TODO+ root = self.get_root_folder()++ if self.commands_text:+ print(self.get_commands_text())+ if self.env:+ for key in self.env:+ val = self.jinjaify(self.env[key])+ os.environ[key] = str(val)+ if is_windows():+ print("\n SET %s=%s" % (key, val))+ else:+ print("\n export %s=%s" % (key, val))+ print(abbreviate_homedir("\n cd %s" % root))+ commands = ensure_list(self.commands)+ for cmd in commands:+ for line in cmd.display_cmd():+ print(" %s" % line)+ print()+ 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:+ print("You will get prompted before running each individual command.")+ else:+ print("You will not be prompted for each command but will see the output of each. If one command fails the execution will stop.")+ success = True+ if ask_yes_no("Do you want me to run these commands now?"):+ if self.remove_files:+ for _f in ensure_list(self.get_remove_files()):+ f = os.path.join(root, _f)+ if os.path.exists(f):+ filefolder = "File" if os.path.isfile(f) else "Folder"+ if ask_yes_no("%s %s already exists. Shall I remove it now?" % (filefolder, f)) and not dry_run:+ if os.path.isdir(f):+ shutil.rmtree(f)else:- print("\n export %s=%s" % (key, val))- print(abbreviate_homedir("\n cd %s" % root))- commands = ensure_list(self.commands)+ os.remove(f)+ index = 0+ log_folder = self.logs_prefix if len(commands) > 1 else Nonefor cmd in commands:- for line in cmd.display_cmd():- print(" %s" % line)- print()- 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:- print("You will get prompted before running each individual command.")+ index += 1+ if len(commands) > 1:+ log_prefix = "%02d_" % index+ else:+ log_prefix = self.logs_prefix if self.logs_prefix else ""+ if not log_prefix[-1:] == "_":+ log_prefix += "_"+ cwd = root+ if cmd.cwd:+ cwd = os.path.join(root, cmd.cwd)+ folder_prefix = ""+ if cmd.cwd:+ folder_prefix = cmd.cwd + "_"+ if confirm_each and cmd.comment:+ print("# %s\n" % cmd.get_comment())+ if not confirm_each or ask_yes_no("Shall I run '%s' in folder '%s'" % (cmd, cwd)):+ if not confirm_each:+ print("------------\nRunning '%s' in folder '%s'" % (cmd, cwd))+ logfilename = cmd.logfile+ logfile = None+ cmd_to_run = "%s%s" % ("echo Dry run, command is: " if dry_run else "", cmd.get_cmd())+ if cmd.redirect:+ try:+ out = run(cmd_to_run, cwd=cwd)+ mode = "a" if cmd.redirect_append is True else "w"+ with open(os.path.join(root, cwd, cmd.get_redirect()), mode) as outfile:+ outfile.write(out)+ outfile.flush()+ print("Wrote %s bytes to redirect file %s" % (len(out), cmd.get_redirect()))+ except Exception as e:+ print("Command %s failed: %s" % (cmd_to_run, e))+ success = False+ breakelse:- print(- "You will not be prompted for each command but will see the output of each. If one command fails the execution will stop.")- success = True- if ask_yes_no("Do you want me to run these commands now?"):- if self.remove_files:- for _f in ensure_list(self.get_remove_files()):- f = os.path.join(root, _f)- if os.path.exists(f):- filefolder = "File" if os.path.isfile(f) else "Folder"- if ask_yes_no("%s %s already exists. Shall I remove it now?" % (filefolder, f)) and not dry_run:- if os.path.isdir(f):- shutil.rmtree(f)- else:- os.remove(f)- index = 0- log_folder = self.logs_prefix if len(commands) > 1 else None- for cmd in commands:- index += 1- if len(commands) > 1:- log_prefix = "%02d_" % index- else:- log_prefix = self.logs_prefix if self.logs_prefix else ''- if not log_prefix[-1:] == '_':- log_prefix += "_"- cwd = root- if cmd.cwd:- cwd = os.path.join(root, cmd.cwd)- folder_prefix = ''- if cmd.cwd:- folder_prefix = cmd.cwd + "_"- if confirm_each and cmd.comment:- print("# %s\n" % cmd.get_comment())- if not confirm_each or ask_yes_no("Shall I run '%s' in folder '%s'" % (cmd, cwd)):- if not confirm_each:- print("------------\nRunning '%s' in folder '%s'" % (cmd, cwd))- logfilename = cmd.logfile- logfile = None- cmd_to_run = "%s%s" % ("echo Dry run, command is: " if dry_run else "", cmd.get_cmd())- if cmd.redirect:- try:- out = run(cmd_to_run, cwd=cwd)- mode = 'a' if cmd.redirect_append is True else 'w'- with open(os.path.join(root, cwd, cmd.get_redirect()), mode) as outfile:- outfile.write(out)- outfile.flush()- print("Wrote %s bytes to redirect file %s" % (len(out), cmd.get_redirect()))- except Exception as e:- print("Command %s failed: %s" % (cmd_to_run, e))- success = False- break- else:- if not cmd.stdout:- if not log_folder:- log_folder = os.path.join(state.get_rc_folder(), "logs")- elif not os.path.isabs(log_folder):- log_folder = os.path.join(state.get_rc_folder(), "logs", log_folder)- if not logfilename:- logfilename = "%s.log" % re.sub(r"\W", "_", cmd.get_cmd())- logfile = os.path.join(log_folder, "%s%s%s" % (log_prefix, folder_prefix, logfilename))- if cmd.tee:- print("Output of command will be printed (logfile=%s)" % logfile)- elif cmd.live:- print("Output will be shown live byte by byte")- logfile = None- else:- print("Wait until command completes... Full log in %s\n" % logfile)- if cmd.comment:- print("# %s\n" % cmd.get_comment())- start_time = time.time()- returncode = run_with_log_tail(cmd_to_run, cwd, logfile=logfile, tee=cmd.tee, tail_lines=25,- live=cmd.live, shell=cmd.shell)- elapsed = time.time() - start_time- if not returncode == 0:- if cmd.should_fail:- print("Command failed, which was expected")- success = True- else:- print("WARN: Command %s returned with error" % cmd.get_cmd())- success = False- break- else:- if cmd.should_fail and not dry_run:- print("Expected command to fail, but it succeeded.")- success = False- break- else:- if elapsed > 30:- print("Command completed in %s seconds" % elapsed)- if not success:- print("WARNING: One or more commands failed, you may want to check the logs")- return success-- def get_root_folder(self):- return cast(str, self.jinjaify(self.root_folder))-- def get_commands_text(self):- return self.jinjaify(self.commands_text)-- def get_run_text(self):- return self.jinjaify(self.run_text)-- def get_remove_files(self):- return self.jinjaify(self.remove_files)-- def get_vars(self):- myvars = {}- if self.vars:- for k in self.vars:- val = self.vars[k]- if callable(val):- myvars[k] = expand_jinja(val(), vars=myvars)+ if not cmd.stdout:+ if not log_folder:+ log_folder = os.path.join(state.get_rc_folder(), "logs")+ elif not os.path.isabs(log_folder):+ log_folder = os.path.join(state.get_rc_folder(), "logs", log_folder)+ if not logfilename:+ logfilename = "%s.log" % re.sub(r"\W", "_", cmd.get_cmd())+ logfile = os.path.join(log_folder, "%s%s%s" % (log_prefix, folder_prefix, logfilename))+ if cmd.tee:+ print("Output of command will be printed (logfile=%s)" % logfile)+ elif cmd.live:+ print("Output will be shown live byte by byte")+ logfile = Noneelse:- myvars[k] = expand_jinja(val, vars=myvars)- return myvars-- def jinjaify(self, data, join=False):- if not data:- return None- v = self.get_vars()- if self.todo_id:- todo = state.get_todo_by_id(self.todo_id)- assert todo- v.update(todo.get_vars())- if isinstance(data, list):- if join:- return expand_jinja(" ".join(data), v)- else:- res = []- for rf in data:- res.append(expand_jinja(rf, v))- return res+ print("Wait until command completes... Full log in %s\n" % logfile)+ if cmd.comment:+ print("# %s\n" % cmd.get_comment())+ start_time = time.time()+ returncode = run_with_log_tail(cmd_to_run, cwd, logfile=logfile, tee=cmd.tee, tail_lines=25, live=cmd.live, shell=cmd.shell)+ elapsed = time.time() - start_time+ if not returncode == 0:+ if cmd.should_fail:+ print("Command failed, which was expected")+ success = True+ else:+ print("WARN: Command %s returned with error" % cmd.get_cmd())+ success = False+ break+ else:+ if cmd.should_fail and not dry_run:+ print("Expected command to fail, but it succeeded.")+ success = False+ break+ else:+ if elapsed > 30:+ print("Command completed in %s seconds" % elapsed)+ if not success:+ print("WARNING: One or more commands failed, you may want to check the logs")+ return success++ def get_root_folder(self):+ return cast(str, self.jinjaify(self.root_folder))++ def get_commands_text(self):+ return self.jinjaify(self.commands_text)++ def get_run_text(self):+ return self.jinjaify(self.run_text)++ def get_remove_files(self):+ return self.jinjaify(self.remove_files)++ def get_vars(self):+ myvars = {}+ if self.vars:+ for k in self.vars:+ val = self.vars[k]+ if callable(val):+ myvars[k] = expand_jinja(val(), vars=myvars)else:- return expand_jinja(data, v)+ myvars[k] = expand_jinja(val, vars=myvars)+ return myvars++ def jinjaify(self, data, join=False):+ if not data:+ return None+ v = self.get_vars()+ if self.todo_id:+ todo = state.get_todo_by_id(self.todo_id)+ assert todo+ v.update(todo.get_vars())+ if isinstance(data, list):+ if join:+ return expand_jinja(" ".join(data), v)+ else:+ res = []+ for rf in data:+ res.append(expand_jinja(rf, v))+ return res+ else:+ return expand_jinja(data, v)def abbreviate_homedir(line):- if is_windows():- if 'HOME' in os.environ:- return re.sub(r'([^/]|\b)%s' % os.path.expanduser('~'), "\\1%HOME%", line)- elif 'USERPROFILE' in os.environ:- return re.sub(r'([^/]|\b)%s' % os.path.expanduser('~'), "\\1%USERPROFILE%", line)- else:- return line+ if is_windows():+ if "HOME" in os.environ:+ return re.sub(r"([^/]|\b)%s" % os.path.expanduser("~"), "\\1%HOME%", line)+ elif "USERPROFILE" in os.environ:+ return re.sub(r"([^/]|\b)%s" % os.path.expanduser("~"), "\\1%USERPROFILE%", line)else:- return re.sub(r'([^/]|\b)%s' % os.path.expanduser('~'), "\\1~", line)+ return line+ else:+ return re.sub(r"([^/]|\b)%s" % os.path.expanduser("~"), "\\1~", line)class Command(SecretYamlObject):- yaml_tag = u'!Command'- hidden_fields = ['todo_id']- def __init__(self, cmd, cwd=None, stdout=None, logfile=None, tee=None, live=None, comment=None, vars=None,- todo_id=None, should_fail=None, redirect=None, redirect_append=None, shell=None):- self.cmd = cmd- self.cwd = cwd- self.comment = comment- self.logfile = logfile- self.vars = vars- self.tee = tee- self.live = live- self.stdout = stdout- self.should_fail = should_fail- self.shell = shell- self.todo_id = todo_id- self.redirect_append = redirect_append- self.redirect = redirect- if tee and stdout:- self.stdout = None- print("Command %s specifies 'tee' and 'stdout', using only 'tee'" % self.cmd)- if live and stdout:- self.stdout = None- print("Command %s specifies 'live' and 'stdout', using only 'live'" % self.cmd)- if live and tee:- self.tee = None- print("Command %s specifies 'tee' and 'live', using only 'live'" % self.cmd)- if redirect and (tee or stdout or live):- self.tee = self.stdout = self.live = None- print("Command %s specifies 'redirect' and other out options at the same time. Using redirect only" % self.cmd)-- @classmethod- def from_yaml(cls, loader, node):- fields = loader.construct_mapping(node, deep = True)- return Command(**fields)-- def get_comment(self):- return self.jinjaify(self.comment)-- def get_redirect(self):- return self.jinjaify(self.redirect)-- def get_cmd(self):- return cast(str, self.jinjaify(self.cmd, join=True))-- def get_vars(self):- myvars = {}- if self.vars:- for k in self.vars:- val = self.vars[k]- if callable(val):- myvars[k] = expand_jinja(val(), vars=myvars)- else:- myvars[k] = expand_jinja(val, vars=myvars)- return myvars-- def __str__(self):- return self.get_cmd()-- def jinjaify(self, data, join=False):- v = self.get_vars()- if self.todo_id:- todo = state.get_todo_by_id(self.todo_id)- assert todo- v.update(todo.get_vars())- if isinstance(data, list):- if join:- return expand_jinja(" ".join(data), v)- else:- res = []- for rf in data:- res.append(expand_jinja(rf, v))- return res+ yaml_tag = "!Command"+ hidden_fields = ["todo_id"]++ def __init__(self, cmd, cwd=None, stdout=None, logfile=None, tee=None, live=None, comment=None, vars=None, todo_id=None, should_fail=None, redirect=None, redirect_append=None, shell=None):+ self.cmd = cmd+ self.cwd = cwd+ self.comment = comment+ self.logfile = logfile+ self.vars = vars+ self.tee = tee+ self.live = live+ self.stdout = stdout+ self.should_fail = should_fail+ self.shell = shell+ self.todo_id = todo_id+ self.redirect_append = redirect_append+ self.redirect = redirect+ if tee and stdout:+ self.stdout = None+ print("Command %s specifies 'tee' and 'stdout', using only 'tee'" % self.cmd)+ if live and stdout:+ self.stdout = None+ print("Command %s specifies 'live' and 'stdout', using only 'live'" % self.cmd)+ if live and tee:+ self.tee = None+ print("Command %s specifies 'tee' and 'live', using only 'live'" % self.cmd)+ if redirect and (tee or stdout or live):+ self.tee = self.stdout = self.live = None+ print("Command %s specifies 'redirect' and other out options at the same time. Using redirect only" % self.cmd)++ @classmethod+ def from_yaml(cls, loader, node):+ fields = loader.construct_mapping(node, deep=True)+ return Command(**fields)++ def get_comment(self):+ return self.jinjaify(self.comment)++ def get_redirect(self):+ return self.jinjaify(self.redirect)++ def get_cmd(self):+ return cast(str, self.jinjaify(self.cmd, join=True))++ def get_vars(self):+ myvars = {}+ if self.vars:+ for k in self.vars:+ val = self.vars[k]+ if callable(val):+ myvars[k] = expand_jinja(val(), vars=myvars)else:- return expand_jinja(data, v)+ myvars[k] = expand_jinja(val, vars=myvars)+ return myvars++ def __str__(self):+ return self.get_cmd()++ def jinjaify(self, data, join=False):+ v = self.get_vars()+ if self.todo_id:+ todo = state.get_todo_by_id(self.todo_id)+ assert todo+ v.update(todo.get_vars())+ if isinstance(data, list):+ if join:+ return expand_jinja(" ".join(data), v)+ else:+ res = []+ for rf in data:+ res.append(expand_jinja(rf, v))+ return res+ else:+ return expand_jinja(data, v)++ def display_cmd(self):+ lines = []+ if self.comment:+ if is_windows():+ lines.append("REM %s" % self.get_comment())+ else:+ lines.append("# %s" % self.get_comment())+ if self.cwd:+ lines.append("pushd %s" % self.cwd)+ redir = "" if self.redirect is None else " %s %s" % (">" if self.redirect_append is None else ">>", self.get_redirect())+ line = "%s%s" % (expand_multiline(self.get_cmd(), indent=2), redir)+ # Print ~ or %HOME% rather than the full expanded homedir path+ line = abbreviate_homedir(line)+ lines.append(line)+ if self.cwd:+ lines.append("popd")+ return lines- def display_cmd(self):- lines = []- if self.comment:- if is_windows():- lines.append("REM %s" % self.get_comment())- else:- lines.append("# %s" % self.get_comment())- if self.cwd:- lines.append("pushd %s" % self.cwd)- redir = "" if self.redirect is None else " %s %s" % (">" if self.redirect_append is None else ">>" , self.get_redirect())- line = "%s%s" % (expand_multiline(self.get_cmd(), indent=2), redir)- # Print ~ or %HOME% rather than the full expanded homedir path- line = abbreviate_homedir(line)- lines.append(line)- if self.cwd:- lines.append("popd")- return linesclass UserInput(SecretYamlObject):- yaml_tag = u'!UserInput'-- def __init__(self, name, prompt, type=None):- self.type = type- self.prompt = prompt- self.name = name-- @classmethod- def from_yaml(cls, loader, node):- fields = loader.construct_mapping(node, deep = True)- return UserInput(**fields)-- def run(self, dict=None):- correct = False- while not correct:- try:- result = str(input("%s : " % self.prompt))- if self.type and self.type == 'int':- result = int(result)- correct = True- except Exception as e:- print("Incorrect input: %s, try again" % e)- continue- if dict:- dict[self.name] = result- return result---def create_ical(_todo): # pylint: disable=unused-argument- if ask_yes_no("Do you want to add a Calendar reminder for the close vote time?"):- # TODO: this library has broken typing and seems unmaintained, replace?- c = Calendar() # pyright: ignore[reportArgumentType]- e = Event() # pyright: ignore[reportArgumentType]- e.name = "Lucene %s vote ends" % state.release_version- e.begin = vote_close_72h_date()- e.description = "Remember to sum up votes and continue release :)"- c.events.add(e)- ics_file = os.path.join(state.get_rc_folder(), 'vote_end.ics')- with open(ics_file, 'w') as my_file:- my_file.writelines(c) # pyright: ignore[reportArgumentType]- open_file(ics_file)- return True+ yaml_tag = "!UserInput"++ def __init__(self, name, prompt, type=None):+ self.type = type+ self.prompt = prompt+ self.name = name++ @classmethod+ def from_yaml(cls, loader, node):+ fields = loader.construct_mapping(node, deep=True)+ return UserInput(**fields)++ def run(self, dict=None):+ correct = False+ while not correct:+ try:+ result = str(input("%s : " % self.prompt))+ if self.type and self.type == "int":+ result = int(result)+ correct = True+ except Exception as e:+ print("Incorrect input: %s, try again" % e)+ continue+ if dict:+ dict[self.name] = result+ return result+++def create_ical(_todo): # pylint: disable=unused-argument+ if ask_yes_no("Do you want to add a Calendar reminder for the close vote time?"):+ # TODO: this library has broken typing and seems unmaintained, replace?+ c = Calendar() # pyright: ignore[reportArgumentType]+ e = Event() # pyright: ignore[reportArgumentType]+ e.name = "Lucene %s vote ends" % state.release_version+ e.begin = vote_close_72h_date()+ e.description = "Remember to sum up votes and continue release :)"+ c.events.add(e)+ ics_file = os.path.join(state.get_rc_folder(), "vote_end.ics")+ with open(ics_file, "w") as my_file:+ my_file.writelines(c) # pyright: ignore[reportArgumentType]+ open_file(ics_file)+ return Truetoday = datetime.now(tz=timezone.utc).date()-sundays = {(today + timedelta(days=x)): 'Sunday' for x in range(10) if (today + timedelta(days=x)).weekday() == 6}+sundays = {(today + timedelta(days=x)): "Sunday" for x in range(10) if (today + timedelta(days=x)).weekday() == 6}y = datetime.now(tz=timezone.utc).year-years = [y, y+1]-non_working = country_holidays('CA', years=years) + country_holidays('US', years=years) + country_holidays('UK', years=years) \- + country_holidays('DE', years=years) + country_holidays('NO', years=years) + country_holidays('IN', years=years) + country_holidays('RU', years=years)+years = [y, y + 1]+non_working = (+ country_holidays("CA", years=years)+ + country_holidays("US", years=years)+ + country_holidays("UK", years=years)+ + country_holidays("DE", years=years)+ + country_holidays("NO", years=years)+ + country_holidays("IN", years=years)+ + country_holidays("RU", years=years)+)def vote_close_72h_date():- # Voting open at least 72 hours according to ASF policy- return datetime.now(tz=timezone.utc) + timedelta(hours=73)+ # Voting open at least 72 hours according to ASF policy+ return datetime.now(tz=timezone.utc) + timedelta(hours=73)def vote_close_72h_holidays():- days = 0- day_offset = -1- holidays = []- # Warn RM about major holidays coming up that should perhaps extend the voting deadline- # Warning will be given for Sunday or a public holiday observed by 3 or more [CA, US, EN, DE, NO, IND, RU]- while days < 3:- day_offset += 1- d = today + timedelta(days=day_offset)- if not (d in sundays or (d in non_working and len(non_working[d]) >= 2)):- days += 1- else:- if d in sundays:- holidays.append("%s (Sunday)" % d)- else:- holidays.append("%s (%s)" % (d, non_working[d]))- return holidays if len(holidays) > 0 else None---def prepare_announce_lucene(_todo): # pylint: disable=unused-argument- if not os.path.exists(lucene_news_file):- lucene_text = expand_jinja("(( template=announce_lucene ))")- with open(lucene_news_file, 'w') as fp:- fp.write(lucene_text)- # print("Wrote Lucene announce draft to %s" % lucene_news_file)+ days = 0+ day_offset = -1+ holidays = []+ # Warn RM about major holidays coming up that should perhaps extend the voting deadline+ # Warning will be given for Sunday or a public holiday observed by 3 or more [CA, US, EN, DE, NO, IND, RU]+ while days < 3:+ day_offset += 1+ d = today + timedelta(days=day_offset)+ if not (d in sundays or (d in non_working and len(non_working[d]) >= 2)):+ days += 1else:- print("Draft already exist, not re-generating")- return True+ if d in sundays:+ holidays.append("%s (Sunday)" % d)+ else:+ holidays.append("%s (%s)" % (d, non_working[d]))+ return holidays if len(holidays) > 0 else None+++def prepare_announce_lucene(_todo): # pylint: disable=unused-argument+ if not os.path.exists(lucene_news_file):+ lucene_text = expand_jinja("(( template=announce_lucene ))")+ with open(lucene_news_file, "w") as fp:+ fp.write(lucene_text)+ # print("Wrote Lucene announce draft to %s" % lucene_news_file)+ else:+ print("Draft already exist, not re-generating")+ return True-def check_artifacts_available(_todo): # pylint: disable=unused-argument+def check_artifacts_available(_todo): # pylint: disable=unused-argumentcdnUrl = expand_jinja("https://dlcdn.apache.org/lucene/java/{{ release_version }}/lucene-{{ release_version }}-src.tgz.asc")try:load(cdnUrl)@@ -1908,21 +1937,22 @@ def check_artifacts_available(_todo): # pylint: disable=unused-argumentreturn True+def set_java_home(version):- os.environ['JAVA_HOME'] = state.get_java_home_for_version(version)- os.environ['JAVACMD'] = state.get_java_cmd_for_version(version)+ os.environ["JAVA_HOME"] = state.get_java_home_for_version(version)+ os.environ["JAVACMD"] = state.get_java_cmd_for_version(version)def load_lines(file, from_line=0):- if os.path.exists(file):- with open(file, 'r') as fp:- return fp.readlines()[from_line:]- else:- return ["<Please paste the announcement text here>\n"]+ if os.path.exists(file):+ with open(file, "r") as fp:+ return fp.readlines()[from_line:]+ else:+ return ["<Please paste the announcement text here>\n"]-if __name__ == '__main__':- try:- main()- except KeyboardInterrupt:- print('Keyboard interrupt...exiting')+if __name__ == "__main__":+ try:+ main()+ except KeyboardInterrupt:+ print("Keyboard interrupt...exiting")diff --git a/dev-tools/scripts/releasedJirasRegex.py b/dev-tools/scripts/releasedJirasRegex.pyindex 5934344bce2..f6887bc9923 100755--- a/dev-tools/scripts/releasedJirasRegex.py+++ b/dev-tools/scripts/releasedJirasRegex.py@@ -15,13 +15,16 @@# See the License for the specific language governing permissions and# limitations under the License.-import sysimport os+import sys+sys.path.append(os.path.dirname(__file__))-from scriptutil import Versionimport argparseimport re+from scriptutil import Version++# Pulls out all JIRAs mentioned at the beginning of bullet items# under the given version in the given CHANGES.txt file# and prints a regular expression that will match all of them@@ -31,27 +34,27 @@ import re# bullets or numbered entries.#def print_released_jiras_regex(version, filename):- release_boundary_re = re.compile(r'\s*====*\s+(.*)\s+===')- version_re = re.compile(r'%s(?:$|[^-])' % version)- bullet_re = re.compile(r'\s*(?:[-*]|\d+\.(?=(?:\s|(?:LUCENE)-)))(.*)')- jira_ptn = r'(?:LUCENE)-\d+'+ release_boundary_re = re.compile(r"\s*====*\s+(.*)\s+===")+ version_re = re.compile(r"%s(?:$|[^-])" % version)+ bullet_re = re.compile(r"\s*(?:[-*]|\d+\.(?=(?:\s|(?:LUCENE)-)))(.*)")+ jira_ptn = r"(?:LUCENE)-\d+"jira_re = re.compile(jira_ptn)- jira_list_ptn = r'(?:[:,/()\s]*(?:%s))+' % jira_ptn+ jira_list_ptn = r"(?:[:,/()\s]*(?:%s))+" % jira_ptnjira_list_re = re.compile(jira_list_ptn)- more_jiras_on_next_line_re = re.compile(r'%s\s*,\s*$' % jira_list_ptn) # JIRA list with trailing comma+ more_jiras_on_next_line_re = re.compile(r"%s\s*,\s*$" % jira_list_ptn) # JIRA list with trailing commaunder_requested_version = Falserequested_version_found = Falsemore_jiras_on_next_line = Falselucene_jiras = []- with open(filename, 'r') as changes:+ with open(filename, "r") as changes:for line in changes:version_boundary = release_boundary_re.match(line)if version_boundary is not None:if under_requested_version:- break # No longer under the requested version - stop looking for JIRAs+ break # No longer under the requested version - stop looking for JIRAselse:if version_re.search(version_boundary.group(1)):- under_requested_version = True # Start looking for JIRAs+ under_requested_version = True # Start looking for JIRAsrequested_version_found = Trueelse:if under_requested_version:@@ -62,30 +65,32 @@ def print_released_jiras_regex(version, filename):if jira_list_match is not None:jira_match = jira_re.findall(jira_list_match.group(0))for jira in jira_match:- lucene_jiras.append(jira.rsplit('-', 1)[-1])+ lucene_jiras.append(jira.rsplit("-", 1)[-1])more_jiras_on_next_line = more_jiras_on_next_line_re.match(content)if not requested_version_found:- raise Exception('Could not find %s in %s' % (version, filename))+ raise Exception("Could not find %s in %s" % (version, filename))print()- if (len(lucene_jiras) == 0):- print('(No JIRAs => no regex)', end='')+ if len(lucene_jiras) == 0:+ print("(No JIRAs => no regex)", end="")else:- print(r'LUCENE-(?:%s)\b' % '|'.join(lucene_jiras), end='')+ print(r"LUCENE-(?:%s)\b" % "|".join(lucene_jiras), end="")print()+def read_config():- parser = argparse.ArgumentParser(- description='Prints a regex matching JIRAs fixed in the given version by parsing the given CHANGES.txt file')- parser.add_argument('version', type=Version.parse, help='Version of the form X.Y.Z')- parser.add_argument('changes', help='CHANGES.txt file to parse')+ parser = argparse.ArgumentParser(description="Prints a regex matching JIRAs fixed in the given version by parsing the given CHANGES.txt file")+ parser.add_argument("version", type=Version.parse, help="Version of the form X.Y.Z")+ parser.add_argument("changes", help="CHANGES.txt file to parse")return parser.parse_args()+def main():config = read_config()print_released_jiras_regex(config.version, config.changes)-if __name__ == '__main__':++if __name__ == "__main__":try:main()except KeyboardInterrupt:- print('\nReceived Ctrl-C, exiting early')+ print("\nReceived Ctrl-C, exiting early")diff --git a/dev-tools/scripts/reproduceJenkinsFailures.py b/dev-tools/scripts/reproduceJenkinsFailures.pyindex 95fb35d33f3..372091869ef 100644--- a/dev-tools/scripts/reproduceJenkinsFailures.py+++ b/dev-tools/scripts/reproduceJenkinsFailures.py@@ -28,37 +28,37 @@ import urllib.requestfrom textwrap import dedent# Example: Checking out Revision e441a99009a557f82ea17ee9f9c3e9b89c75cee6 (refs/remotes/origin/master)-reGitRev = re.compile(r'Checking out Revision (\S+)\s+\(refs/remotes/origin/([^)]+)')+reGitRev = re.compile(r"Checking out Revision (\S+)\s+\(refs/remotes/origin/([^)]+)")# Policeman Jenkins example: [Lucene-Solr-7.x-Linux] $ /var/lib/jenkins/tools/hudson.tasks.Ant_AntInstallation/ANT_1.8.2/bin/ant "-Dargs=-XX:-UseCompressedOops -XX:+UseConcMarkSweepGC" jenkins-hourly# Policeman Jenkins Windows example: [Lucene-Solr-master-Windows] $ cmd.exe /C "C:\Users\jenkins\tools\hudson.tasks.Ant_AntInstallation\ANT_1.8.2\bin\ant.bat '"-Dargs=-client -XX:+UseConcMarkSweepGC"' jenkins-hourly && exit %%ERRORLEVEL%%"# ASF Jenkins example: [Lucene-Solr-Tests-master] $ /home/jenkins/tools/ant/apache-ant-1.8.4/bin/ant jenkins-hourly# ASF Jenkins nightly example: [checkout] $ /home/jenkins/tools/ant/apache-ant-1.8.4/bin/ant -file build.xml -Dtests.multiplier=2 -Dtests.linedocsfile=/home/jenkins/jenkins-slave/workspace/Lucene-Solr-NightlyTests-master/test-data/enwiki.random.lines.txt jenkins-nightly# ASF Jenkins smoker example: [Lucene-Solr-SmokeRelease-master] $ /home/jenkins/tools/ant/apache-ant-1.8.4/bin/ant nightly-smoke-reAntInvocation = re.compile(r'\bant(?:\.bat)?\s+.*(?:jenkins-(?:hourly|nightly)|nightly-smoke)')+reAntInvocation = re.compile(r"\bant(?:\.bat)?\s+.*(?:jenkins-(?:hourly|nightly)|nightly-smoke)")reAntSysprops = re.compile(r'"-D[^"]+"|-D[^=]+="[^"]*"|-D\S+')# Method example: NOTE: reproduce with: ant test -Dtestcase=ZkSolrClientTest -Dtests.method=testMultipleWatchesAsync -Dtests.seed=6EF5AB70F0032849 -Dtests.locale=he-IL -Dtests.timezone=NST -Dtests.asserts=true -Dtests.file.encoding=UTF-8# Suite example: NOTE: reproduce with: ant test -Dtestcase=CloudSolrClientTest -Dtests.seed=DB2DF2D8228BAF27 -Dtests.multiplier=3 -Dtests.locale=es-AR -Dtests.timezone=America/Argentina/Cordoba -Dtests.asserts=true -Dtests.file.encoding=US-ASCII-reReproLine = re.compile(r'NOTE:\s+reproduce\s+with:(\s+ant\s+test\s+-Dtestcase=(\S+)\s+(?:-Dtests.method=\S+\s+)?(.*))')-reTestsSeed = re.compile(r'-Dtests.seed=\S+\s*')+reReproLine = re.compile(r"NOTE:\s+reproduce\s+with:(\s+ant\s+test\s+-Dtestcase=(\S+)\s+(?:-Dtests.method=\S+\s+)?(.*))")+reTestsSeed = re.compile(r"-Dtests.seed=\S+\s*")# Example: https://jenkins.thetaphi.de/job/Lucene-Solr-master-Linux/21108/-reJenkinsURLWithoutConsoleText = re.compile(r'https?://.*/\d+/?\Z', re.IGNORECASE)+reJenkinsURLWithoutConsoleText = re.compile(r"https?://.*/\d+/?\Z", re.IGNORECASE)-reJavaFile = re.compile(r'(.*)\.java\Z')-reModule = re.compile(r'\.[\\/](.*)[\\/]src[\\/]')-reTestOutputFile = re.compile(r'TEST-(.*\.([^-.]+))(?:-\d+)?\.xml\Z')+reJavaFile = re.compile(r"(.*)\.java\Z")+reModule = re.compile(r"\.[\\/](.*)[\\/]src[\\/]")+reTestOutputFile = re.compile(r"TEST-(.*\.([^-.]+))(?:-\d+)?\.xml\Z")reErrorFailure = re.compile(r'(?:errors|failures)="[^0]')-reGitMainBranch = re.compile(r'^(?:master|branch_[x_\d]+)$')+reGitMainBranch = re.compile(r"^(?:master|branch_[x_\d]+)$")# consoleText from Policeman Jenkins's Windows jobs fails to decode as UTF-8-encoding = 'iso-8859-1'+encoding = "iso-8859-1"lastFailureCode = 0gitCheckoutSucceeded = False-description = dedent('''\+description = dedent("""\Must be run from a Lucene/Solr git workspace. Downloads the Jenkinslog pointed to by the given URL, parses it for Git revision and failedLucene/Solr tests, checks out the Git revision in the local workspace,@@ -67,46 +67,45 @@ description = dedent('''\in each module of interest, failing at the end if any of the runs fails.To control the maximum number of concurrent JVMs used for each module'stest run, set 'tests.jvms', e.g. in ~/lucene.build.properties- ''')+ """)defaultIters = 5+def readConfig():- parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,- description=description)- parser.add_argument('url', metavar='URL',- help='Points to the Jenkins log to parse')- parser.add_argument('--no-git', dest='useGit', action='store_false', default=True,- help='Do not run "git" at all')- parser.add_argument('--iters', dest='testIters', type=int, default=defaultIters, metavar='N',- help='Number of iterations per test suite (default: %d)' % defaultIters)+ parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=description)+ parser.add_argument("url", metavar="URL", help="Points to the Jenkins log to parse")+ parser.add_argument("--no-git", dest="useGit", action="store_false", default=True, help='Do not run "git" at all')+ parser.add_argument("--iters", dest="testIters", type=int, default=defaultIters, metavar="N", help="Number of iterations per test suite (default: %d)" % defaultIters)return parser.parse_args()+def runOutput(cmd):- print('[repro] %s' % cmd)+ print("[repro] %s" % cmd)try:- return subprocess.check_output(cmd.split(' '), universal_newlines=True).strip()+ return subprocess.check_output(cmd.split(" "), universal_newlines=True).strip()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))+ 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==Falsedef run(cmd, rememberFailure=True):global lastFailureCode- print('[repro] %s' % cmd)+ print("[repro] %s" % cmd)code = os.system(cmd)if 0 != code and rememberFailure:- print('\n[repro] Setting last failure code to %d\n' % code)+ print("\n[repro] Setting last failure code to %d\n" % code)lastFailureCode = codereturn code+def fetchAndParseJenkinsLog(url, numRetries):global revisionFromLogglobal branchFromLogglobal antOptionsrevisionFromLog = None- antOptions = ''+ antOptions = ""tests = {}- print('[repro] Jenkins log URL: %s\n' % url)+ print("[repro] Jenkins log URL: %s\n" % url)try:# HTTPS fails at certificate validation, see LUCENE-9412, PEP-476context = ssl._create_unverified_context()@@ -117,53 +116,54 @@ def fetchAndParseJenkinsLog(url, numRetries):if match is not None:revisionFromLog = match.group(1)branchFromLog = match.group(2)- print('[repro] Revision: %s\n' % revisionFromLog)+ print("[repro] Revision: %s\n" % revisionFromLog)else:match = reReproLine.search(line)if match is not None:- print('[repro] Repro line: %s\n' % match.group(1))+ print("[repro] Repro line: %s\n" % match.group(1))testcase = match.group(2)reproLineWithoutMethod = match.group(3).strip()tests[testcase] = reproLineWithoutMethodelse:match = reAntInvocation.search(line)if match is not None:- antOptions = ' '.join(reAntSysprops.findall(line))+ antOptions = " ".join(reAntSysprops.findall(line))if len(antOptions) > 0:- print('[repro] Ant options: %s' % antOptions)+ print("[repro] Ant options: %s" % antOptions)except urllib.error.URLError as e:- raise RuntimeError('ERROR: fetching %s : %s' % (url, e))+ raise RuntimeError("ERROR: fetching %s : %s" % (url, e))except http.client.IncompleteRead as e:if numRetries > 0:- print('[repro] Encountered IncompleteRead exception, pausing and then retrying...')- time.sleep(2) # pause for 2 seconds+ print("[repro] Encountered IncompleteRead exception, pausing and then retrying...")+ time.sleep(2) # pause for 2 secondsreturn fetchAndParseJenkinsLog(url, numRetries - 1)else:- print('[repro] Encountered IncompleteRead exception, aborting after too many retries.')- raise RuntimeError('ERROR: fetching %s : %s' % (url, e))+ print("[repro] Encountered IncompleteRead exception, aborting after too many retries.")+ raise RuntimeError("ERROR: fetching %s : %s" % (url, e))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)+ raise RuntimeError("ERROR: %s does not appear to be a Jenkins log." % url)if 0 == len(tests):print('[repro] No "reproduce with" lines found; exiting.')sys.exit(0)return tests+def prepareWorkspace(useGit, gitRef):global gitCheckoutSucceededif useGit:- code = run('git fetch')+ code = run("git fetch")if 0 != code:raise RuntimeError('ERROR: "git fetch" failed. See above.')- checkoutCmd = 'git checkout %s' % gitRef+ checkoutCmd = "git checkout %s" % gitRefcode = run(checkoutCmd)if 0 != code:addWantedBranchCmd = "git remote set-branches --add origin %s" % gitRef- checkoutBranchCmd = 'git checkout -t -b %s origin/%s' % (gitRef, gitRef) # Checkout remote branch as new local branch+ checkoutBranchCmd = "git checkout -t -b %s origin/%s" % (gitRef, gitRef) # Checkout remote branch as new local branchprint('"%s" failed. Trying "%s" and "%s".' % (checkoutCmd, addWantedBranchCmd, checkoutBranchCmd))code = run(addWantedBranchCmd)if 0 != code:@@ -172,15 +172,16 @@ def prepareWorkspace(useGit, gitRef):if 0 != code:raise RuntimeError('ERROR: "%s" failed. See above.' % checkoutBranchCmd)gitCheckoutSucceeded = True- run('git merge --ff-only', rememberFailure=False) # Ignore failure on non-branch ref+ run("git merge --ff-only", rememberFailure=False) # Ignore failure on non-branch ref- code = run('ant clean')+ code = run("ant clean")if 0 != code:raise RuntimeError('ERROR: "ant clean" failed. See above.')+def groupTestsByModule(tests):modules = {}- for (dir, _, files) in os.walk('.'):+ for dir, _, files in os.walk("."):for file in files:match = reJavaFile.search(file)if match is not None:@@ -192,23 +193,24 @@ def groupTestsByModule(tests):if module not in modules:modules[module] = set()modules[module].add(test)- print('[repro] Test suites by module:')+ print("[repro] Test suites by module:")for module in modules:- print('[repro] %s' % module)+ print("[repro] %s" % module)for test in modules[module]:- print('[repro] %s' % test)+ print("[repro] %s" % test)return modules+def runTests(testIters, modules, tests):cwd = os.getcwd()testCmdline = 'ant test-nocompile -Dtests.dups=%d -Dtests.maxfailures=%d -Dtests.class="%s" -Dtests.showOutput=onerror %s %s'for module in modules:moduleTests = list(modules[module])- testList = '|'.join(map(lambda t: '*.%s' % t, moduleTests))+ testList = "|".join(map(lambda t: "*.%s" % t, moduleTests))numTests = len(moduleTests)- params = tests[moduleTests[0]] # Assumption: all tests in this module have the same cmdline params+ params = tests[moduleTests[0]] # Assumption: all tests in this module have the same cmdline paramsos.chdir(module)- code = run('ant compile-test')+ code = run("ant compile-test")try:if 0 != code:raise RuntimeError("ERROR: Compile failed in %s/ with code %d. See above." % (module, code))@@ -216,10 +218,11 @@ def runTests(testIters, modules, tests):finally:os.chdir(cwd)+def printAndMoveReports(testIters, newSubDir, location):failures = {}- for start in ('lucene/build', 'solr/build'):- for (dir, _, files) in os.walk(start):+ for start in ("lucene/build", "solr/build"):+ for dir, _, files in os.walk(start):for file in files:testOutputFileMatch = reTestOutputFile.search(file)if testOutputFileMatch is not None:@@ -227,90 +230,89 @@ def printAndMoveReports(testIters, newSubDir, location):if testcase not in failures:failures[testcase] = 0filePath = os.path.join(dir, file)- with open(filePath, encoding='UTF-8') as testOutputFile:+ with open(filePath, encoding="UTF-8") as testOutputFile:for line in testOutputFile:errorFailureMatch = reErrorFailure.search(line)if errorFailureMatch is not None:failures[testcase] += 1break# have to play nice with 'ant clean'...- newDirPath = os.path.join('repro-reports', newSubDir, dir)+ newDirPath = os.path.join("repro-reports", newSubDir, dir)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+def getLocalGitBranch():- origGitBranch = runOutput('git rev-parse --abbrev-ref HEAD')- if origGitBranch == 'HEAD': # In detached HEAD state- origGitBranch = runOutput('git rev-parse HEAD') # Use the SHA when not on a branch- print('[repro] Initial local git branch/revision: %s' % origGitBranch)+ origGitBranch = runOutput("git rev-parse --abbrev-ref HEAD")+ if origGitBranch == "HEAD": # In detached HEAD state+ origGitBranch = runOutput("git rev-parse HEAD") # Use the SHA when not on a branch+ print("[repro] Initial local git branch/revision: %s" % origGitBranch)return origGitBranch+def main():config = readConfig()- tests = fetchAndParseJenkinsLog(config.url, numRetries = 2)+ tests = fetchAndParseJenkinsLog(config.url, numRetries=2)localGitBranch = Noneif config.useGit:localGitBranch = getLocalGitBranch()try:# 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')- shutil.rmtree('repro-reports')+ 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")+ 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 ''))-+ 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 = teststests = {}for fullClass in failures:- testcase = fullClass[(fullClass.rindex('.') + 1):]+ testcase = fullClass[(fullClass.rindex(".") + 1) :]if failures[fullClass] == config.testIters:tests[testcase] = oldTests[testcase]if len(tests) > 0:- print('\n[repro] Re-testing 100%% failures at the tip of %s' % branchFromLog)+ print("\n[repro] Re-testing 100%% failures at the tip of %s" % branchFromLog)prepareWorkspace(True, branchFromLog)modules = groupTestsByModule(tests)runTests(config.testIters, modules, tests)- failures = printAndMoveReports(config.testIters, 'branch-tip',- ' original seeds at the tip of %s' % branchFromLog)+ failures = printAndMoveReports(config.testIters, "branch-tip", " original seeds at the tip of %s" % branchFromLog)# Retest 100% tip-of-branch failures without a seedoldTests = teststests = {}for fullClass in failures:- testcase = fullClass[(fullClass.rindex('.') + 1):]+ testcase = fullClass[(fullClass.rindex(".") + 1) :]if failures[fullClass] == config.testIters:- tests[testcase] = re.sub(reTestsSeed, '', oldTests[testcase])+ tests[testcase] = re.sub(reTestsSeed, "", oldTests[testcase])if len(tests) > 0:- print('\n[repro] Re-testing 100%% failures at the tip of %s without a seed' % branchFromLog)+ print("\n[repro] Re-testing 100%% failures at the tip of %s without a seed" % branchFromLog)prepareWorkspace(False, branchFromLog)modules = groupTestsByModule(tests)runTests(config.testIters, modules, tests)- printAndMoveReports(config.testIters, 'branch-tip-no-seed',- ' at the tip of %s without a seed' % branchFromLog)+ printAndMoveReports(config.testIters, "branch-tip-no-seed", " at the tip of %s without a seed" % branchFromLog)except Exception:- print('[repro] %s' % traceback.format_exc())+ print("[repro] %s" % traceback.format_exc())sys.exit(1)finally:if config.useGit and gitCheckoutSucceeded:- run('git checkout %s' % localGitBranch, rememberFailure=False) # Restore original git branch/sha+ run("git checkout %s" % localGitBranch, rememberFailure=False) # Restore original git branch/sha- print('[repro] Exiting with code %d' % lastFailureCode)+ print("[repro] Exiting with code %d" % lastFailureCode)sys.exit(lastFailureCode)-if __name__ == '__main__':++if __name__ == "__main__":try:main()except KeyboardInterrupt:- print('[repro] Keyboard interrupt...exiting')+ print("[repro] Keyboard interrupt...exiting")diff --git a/dev-tools/scripts/scriptutil.py b/dev-tools/scripts/scriptutil.pyindex 5bc5c56de29..4b054dfaa0c 100644--- a/dev-tools/scripts/scriptutil.py+++ b/dev-tools/scripts/scriptutil.py@@ -14,15 +14,16 @@# limitations under the License.import argparse+import osimport reimport subprocessimport sys-import os-from enum import Enumimport time-import urllib.requestimport urllib.errorimport urllib.parse+import urllib.request+from enum import Enum+class Version(object):def __init__(self, major, minor, bugfix, prerelease):@@ -31,30 +32,30 @@ class Version(object):self.bugfix = bugfixself.prerelease = prereleaseself.previous_dot_matcher = self.make_previous_matcher()- self.dot = '%d.%d.%d' % (self.major, self.minor, self.bugfix)- self.constant = 'LUCENE_%d_%d_%d' % (self.major, self.minor, self.bugfix)+ self.dot = "%d.%d.%d" % (self.major, self.minor, self.bugfix)+ self.constant = "LUCENE_%d_%d_%d" % (self.major, self.minor, self.bugfix)@classmethoddef parse(cls, value):- match = re.search(r'(\d+)\.(\d+).(\d+)(.1|.2)?', value)+ match = re.search(r"(\d+)\.(\d+).(\d+)(.1|.2)?", value)if match is None:- raise argparse.ArgumentTypeError('Version argument must be of format x.y.z(.1|.2)?')+ raise argparse.ArgumentTypeError("Version argument must be of format x.y.z(.1|.2)?")parts = [int(v) for v in match.groups()[:-1]]- parts.append({ None: 0, '.1': 1, '.2': 2 }[match.groups()[-1]])+ parts.append({None: 0, ".1": 1, ".2": 2}[match.groups()[-1]])return Version(*parts)def __str__(self):return self.dot- def make_previous_matcher(self, prefix='', suffix='', sep='\\.'):+ def make_previous_matcher(self, prefix="", suffix="", sep="\\."):if self.is_bugfix_release():- pattern = '%s%s%s%s%d' % (self.major, sep, self.minor, sep, self.bugfix - 1)+ pattern = "%s%s%s%s%d" % (self.major, sep, self.minor, sep, self.bugfix - 1)elif self.is_minor_release():- pattern = '%s%s%d%s\\d+' % (self.major, sep, self.minor - 1, sep)+ pattern = "%s%s%d%s\\d+" % (self.major, sep, self.minor - 1, sep)else:- pattern = '%d%s\\d+%s\\d+' % (self.major - 1, sep, sep)+ pattern = "%d%s\\d+%s\\d+" % (self.major - 1, sep, sep)- return re.compile(prefix + '(' + pattern + ')' + suffix)+ return re.compile(prefix + "(" + pattern + ")" + suffix)def is_bugfix_release(self):return self.bugfix != 0@@ -66,31 +67,32 @@ class Version(object):return self.bugfix == 0 and self.minor == 0def on_or_after(self, other):- return (self.major > other.major or self.major == other.major and- (self.minor > other.minor or self.minor == other.minor and- (self.bugfix > other.bugfix or self.bugfix == other.bugfix and- self.prerelease >= other.prerelease)))+ return (+ self.major > other.major+ or self.major == other.major+ and (self.minor > other.minor or self.minor == other.minor and (self.bugfix > other.bugfix or self.bugfix == other.bugfix and self.prerelease >= other.prerelease))+ )def gt(self, other):- return (self.major > other.major or- (self.major == other.major and self.minor > other.minor) or- (self.major == other.major and self.minor == other.minor and self.bugfix > other.bugfix))+ return self.major > other.major or (self.major == other.major and self.minor > other.minor) or (self.major == other.major and self.minor == other.minor and self.bugfix > other.bugfix)def is_back_compat_with(self, other):if not self.on_or_after(other):- raise Exception('Back compat check disallowed for newer version: %s < %s' % (self, other))+ raise Exception("Back compat check disallowed for newer version: %s < %s" % (self, other))return other.major + 1 >= self.major+def run(cmd, cwd=None):try:output = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT, cwd=cwd)except subprocess.CalledProcessError as e:- print(e.output.decode('utf-8'))+ print(e.output.decode("utf-8"))raise e- return output.decode('utf-8')+ return output.decode("utf-8")+def update_file(filename, line_re, edit, append=None):- infile = open(filename, 'r')+ infile = open(filename, "r")buffer = []changed = False@@ -104,69 +106,70 @@ def update_file(filename, line_re, edit, append=None):continuebuffer.append(line)if append:- changed = append(buffer, changed) # in the case did not change in edit but have an append function+ changed = append(buffer, changed) # in the case did not change in edit but have an append functionif not changed:- raise Exception('Could not find %s in %s' % (line_re, filename))- with open(filename, 'w') as f:- f.write(''.join(buffer))+ raise Exception("Could not find %s in %s" % (line_re, filename))+ with open(filename, "w") as f:+ f.write("".join(buffer))return True# branch types are "release", "stable" and "unstable"class BranchType(Enum):unstable = 1- stable = 2- release = 3+ stable = 2+ release = 3+def find_branch_type():- output = subprocess.check_output('git status', shell=True)- for line in output.split(b'\n'):- if line.startswith(b'On branch '):- branchName = line.split(b' ')[-1]+ output = subprocess.check_output("git status", shell=True)+ for line in output.split(b"\n"):+ if line.startswith(b"On branch "):+ branchName = line.split(b" ")[-1]breakelse:- raise Exception('git status missing branch name')+ raise Exception("git status missing branch name")- if branchName == b'main':+ if branchName == b"main":return BranchType.unstable- if re.match(r'branch_(\d+)x', branchName.decode('UTF-8')):+ if re.match(r"branch_(\d+)x", branchName.decode("UTF-8")):return BranchType.stable- if re.match(r'branch_(\d+)_(\d+)', branchName.decode('UTF-8')):+ if re.match(r"branch_(\d+)_(\d+)", branchName.decode("UTF-8")):return BranchType.release- raise Exception('Cannot run %s on feature branch' % sys.argv[0].rsplit('/', 1)[-1])+ raise Exception("Cannot run %s on feature branch" % sys.argv[0].rsplit("/", 1)[-1])def download(name, urlString, tmpDir, quiet=False, force_clean=True):if not quiet:- print("Downloading %s" % urlString)+ print("Downloading %s" % urlString)startTime = time.time()- fileName = '%s/%s' % (tmpDir, name)+ fileName = "%s/%s" % (tmpDir, name)if not force_clean and os.path.exists(fileName):- if not quiet and fileName.find('.asc') == -1:- print(' already done: %.1f MB' % (os.path.getsize(fileName)/1024./1024.))+ if not quiet and fileName.find(".asc") == -1:+ print(" already done: %.1f MB" % (os.path.getsize(fileName) / 1024.0 / 1024.0))returntry:attemptDownload(urlString, fileName)except Exception as e:- print('Retrying download of url %s after exception: %s' % (urlString, e))+ print("Retrying download of url %s after exception: %s" % (urlString, e))try:attemptDownload(urlString, fileName)except Exception as e:raise RuntimeError('failed to download url "%s"' % urlString) from e- if not quiet and fileName.find('.asc') == -1:- t = time.time()-startTime- sizeMB = os.path.getsize(fileName)/1024./1024.- print(' %.1f MB in %.2f sec (%.1f MB/sec)' % (sizeMB, t, sizeMB/t))+ if not quiet and fileName.find(".asc") == -1:+ t = time.time() - startTime+ sizeMB = os.path.getsize(fileName) / 1024.0 / 1024.0+ print(" %.1f MB in %.2f sec (%.1f MB/sec)" % (sizeMB, t, sizeMB / t))def attemptDownload(urlString, fileName):fIn = urllib.request.urlopen(urlString)- fOut = open(fileName, 'wb')+ fOut = open(fileName, "wb")success = Falsetry:while True:s = fIn.read(65536)- if s == b'':+ if s == b"":breakfOut.write(s)fOut.close()@@ -178,14 +181,18 @@ def attemptDownload(urlString, fileName):if not success:os.remove(fileName)+version_prop_re = re.compile(r'baseVersion\s*=\s*([\'"])(.*)\1')++def find_current_version():script_path = os.path.dirname(os.path.realpath(__file__))top_level_dir = os.path.join(os.path.abspath("%s/" % script_path), os.path.pardir, os.path.pardir)- match = version_prop_re.search(open('%s/build.gradle' % top_level_dir).read())+ match = version_prop_re.search(open("%s/build.gradle" % top_level_dir).read())assert matchreturn match.group(2).strip()-if __name__ == '__main__':- print('This is only a support module, it cannot be run')++if __name__ == "__main__":+ print("This is only a support module, it cannot be run")sys.exit(1)diff --git a/dev-tools/scripts/smokeTestRelease.py b/dev-tools/scripts/smokeTestRelease.pyindex 5d93f00146a..e29d95ca4ab 100755--- a/dev-tools/scripts/smokeTestRelease.py+++ b/dev-tools/scripts/smokeTestRelease.py@@ -36,6 +36,7 @@ import urllib.requestimport xml.etree.ElementTree as ETimport zipfilefrom collections import namedtuple+import scriptutilBASE_JAVA_VERSION = "23"@@ -44,20 +45,21 @@ BASE_JAVA_VERSION = "23"# must have a working gpg, tar, unzip in your path. This has been# tested on Linux and on Cygwin under Windows 7.-cygwin = platform.system().lower().startswith('cygwin')-cygwinWindowsRoot = os.popen('cygpath -w /').read().strip().replace('\\','/') if cygwin else ''+cygwin = platform.system().lower().startswith("cygwin")+cygwinWindowsRoot = os.popen("cygpath -w /").read().strip().replace("\\", "/") if cygwin else ""def unshortenURL(url):parsed = urllib.parse.urlparse(url)- if parsed[0] in ('http', 'https'):+ if parsed[0] in ("http", "https"):h = http.client.HTTPConnection(parsed.netloc)- h.request('HEAD', parsed.path)+ h.request("HEAD", parsed.path)response = h.getresponse()- if int(response.status/100) == 3 and response.getheader('Location'):- return response.getheader('Location')+ if int(response.status / 100) == 3 and response.getheader("Location"):+ return response.getheader("Location")return url+# TODO# - make sure jars exist inside bin release# - make sure docs exist@@ -69,7 +71,6 @@ FORCE_CLEAN = Truedef getHREFs(urlString):-# Deref any redirectswhile True:url = urllib.parse.urlparse(urlString)@@ -79,9 +80,9 @@ def getHREFs(urlString):h = http.client.HTTPSConnection(url.netloc)else:raise RuntimeError("Unknown protocol: %s" % url.scheme)- h.request('HEAD', url.path)+ h.request("HEAD", url.path)r = h.getresponse()- newLoc = r.getheader('location')+ newLoc = r.getheader("location")if newLoc is not None:urlString = newLocelse:@@ -91,7 +92,7 @@ def getHREFs(urlString):try:html = load(urlString)except:- print('\nFAILED to open url %s' % urlString)+ print("\nFAILED to open url %s" % urlString)traceback.print_exc()raise@@ -103,53 +104,53 @@ def getHREFs(urlString):def load(urlString):try:- content = urllib.request.urlopen(urlString).read().decode('utf-8')+ content = urllib.request.urlopen(urlString).read().decode("utf-8")except Exception as e:- print('Retrying download of url %s after exception: %s' % (urlString, e))- content = urllib.request.urlopen(urlString).read().decode('utf-8')+ print("Retrying download of url %s after exception: %s" % (urlString, e))+ content = urllib.request.urlopen(urlString).read().decode("utf-8")return contentdef noJavaPackageClasses(desc, file):with zipfile.ZipFile(file) as z2:for name2 in z2.namelist():- if name2.endswith('.class') and (name2.startswith('java/') or name2.startswith('javax/')):+ if name2.endswith(".class") and (name2.startswith("java/") or name2.startswith("javax/")):raise RuntimeError('%s contains sheisty class "%s"' % (desc, name2))def decodeUTF8(bytes):- return codecs.getdecoder('UTF-8')(bytes)[0]+ return codecs.getdecoder("UTF-8")(bytes)[0]-MANIFEST_FILE_NAME = 'META-INF/MANIFEST.MF'-NOTICE_FILE_NAME = 'META-INF/NOTICE.txt'-LICENSE_FILE_NAME = 'META-INF/LICENSE.txt'+MANIFEST_FILE_NAME = "META-INF/MANIFEST.MF"+NOTICE_FILE_NAME = "META-INF/NOTICE.txt"+LICENSE_FILE_NAME = "META-INF/LICENSE.txt"def checkJARMetaData(desc, jarFile, gitRevision, version):-- with zipfile.ZipFile(jarFile, 'r') as z:+ with zipfile.ZipFile(jarFile, "r") as z:for name in (MANIFEST_FILE_NAME, NOTICE_FILE_NAME, LICENSE_FILE_NAME):try:# The Python docs state a KeyError is raised ... so this None# check is just defensive:if z.getinfo(name) is None:- raise RuntimeError('%s is missing %s' % (desc, name))+ raise RuntimeError("%s is missing %s" % (desc, name))except KeyError:- raise RuntimeError('%s is missing %s' % (desc, name))+ raise RuntimeError("%s is missing %s" % (desc, name))s = decodeUTF8(z.read(MANIFEST_FILE_NAME))for verify in (- 'Specification-Vendor: The Apache Software Foundation',- 'Implementation-Vendor: The Apache Software Foundation',- 'Specification-Title: Lucene Search Engine:',- 'Implementation-Title: org.apache.lucene',- 'X-Compile-Source-JDK: %s' % BASE_JAVA_VERSION,- 'X-Compile-Target-JDK: %s' % BASE_JAVA_VERSION,- 'Specification-Version: %s' % version,- 'X-Build-JDK: %s.' % BASE_JAVA_VERSION,- 'Extension-Name: org.apache.lucene'):+ "Specification-Vendor: The Apache Software Foundation",+ "Implementation-Vendor: The Apache Software Foundation",+ "Specification-Title: Lucene Search Engine:",+ "Implementation-Title: org.apache.lucene",+ "X-Compile-Source-JDK: %s" % BASE_JAVA_VERSION,+ "X-Compile-Target-JDK: %s" % BASE_JAVA_VERSION,+ "Specification-Version: %s" % version,+ "X-Build-JDK: %s." % BASE_JAVA_VERSION,+ "Extension-Name: org.apache.lucene",+ ):if type(verify) is not tuple:verify = (verify,)for x in verify:@@ -161,55 +162,51 @@ def checkJARMetaData(desc, jarFile, gitRevision, version):else:raise RuntimeError('%s is missing one of "%s" inside its META-INF/MANIFEST.MF: %s' % (desc, verify, s))- if gitRevision != 'skip':+ if gitRevision != "skip":# Make sure this matches the version and git revision we think we are releasing:match = re.search("Implementation-Version: (.+\r\n .+)", s, re.MULTILINE)if match:implLine = match.group(1).replace("\r\n ", "")- verifyRevision = '%s %s' % (version, gitRevision)+ verifyRevision = "%s %s" % (version, gitRevision)if implLine.find(verifyRevision) == -1:- raise RuntimeError('%s is missing "%s" inside its META-INF/MANIFEST.MF (wrong git revision?)' % \- (desc, verifyRevision))+ raise RuntimeError('%s is missing "%s" inside its META-INF/MANIFEST.MF (wrong git revision?)' % (desc, verifyRevision))else:- raise RuntimeError('%s is missing Implementation-Version inside its META-INF/MANIFEST.MF' % desc)+ raise RuntimeError("%s is missing Implementation-Version inside its META-INF/MANIFEST.MF" % desc)notice = decodeUTF8(z.read(NOTICE_FILE_NAME))lucene_license = decodeUTF8(z.read(LICENSE_FILE_NAME))if LUCENE_LICENSE is None:- raise RuntimeError('BUG in smokeTestRelease!')+ raise RuntimeError("BUG in smokeTestRelease!")if LUCENE_NOTICE is None:- raise RuntimeError('BUG in smokeTestRelease!')+ raise RuntimeError("BUG in smokeTestRelease!")if notice != LUCENE_NOTICE:- raise RuntimeError('%s: %s contents doesn\'t match main NOTICE.txt' % \- (desc, NOTICE_FILE_NAME))+ raise RuntimeError("%s: %s contents doesn't match main NOTICE.txt" % (desc, NOTICE_FILE_NAME))if lucene_license != LUCENE_LICENSE:- raise RuntimeError('%s: %s contents doesn\'t match main LICENSE.txt' % \- (desc, LICENSE_FILE_NAME))+ raise RuntimeError("%s: %s contents doesn't match main LICENSE.txt" % (desc, LICENSE_FILE_NAME))def normSlashes(path):- return path.replace(os.sep, '/')+ return path.replace(os.sep, "/")def checkAllJARs(topDir, gitRevision, version):- print(' verify JAR metadata/identity/no javax.* or java.* classes...')+ print(" verify JAR metadata/identity/no javax.* or java.* classes...")for root, _, files in os.walk(topDir):-normRoot = normSlashes(root)for file in files:- if file.lower().endswith('.jar'):- if normRoot.endswith('/replicator/lib') and file.startswith('javax.servlet'):+ if file.lower().endswith(".jar"):+ if normRoot.endswith("/replicator/lib") and file.startswith("javax.servlet"):continue- fullPath = '%s/%s' % (root, file)+ fullPath = "%s/%s" % (root, file)noJavaPackageClasses('JAR file "%s"' % fullPath, fullPath)- if file.lower().find('lucene') != -1:+ if file.lower().find("lucene") != -1:checkJARMetaData('JAR file "%s"' % fullPath, fullPath, gitRevision, version)def checkSigs(urlString, version, tmpDir, isSigned, keysFile):- print(' test basics...')+ print(" test basics...")ents = getDirEntries(urlString)artifact = NonechangesURL = None@@ -217,32 +214,32 @@ def checkSigs(urlString, version, tmpDir, isSigned, keysFile):artifactURL = NoneexpectedSigs = []if isSigned:- expectedSigs.append('asc')- expectedSigs.extend(['sha512'])+ expectedSigs.append("asc")+ expectedSigs.extend(["sha512"])sigs = []artifacts = []for text, subURL in ents:- if text == 'KEYS':- raise RuntimeError('lucene: release dir should not contain a KEYS file - only toplevel /dist/lucene/KEYS is used')- elif text == 'maven/':+ if text == "KEYS":+ raise RuntimeError("lucene: release dir should not contain a KEYS file - only toplevel /dist/lucene/KEYS is used")+ elif text == "maven/":mavenURL = subURL- elif text.startswith('changes'):- if text not in ('changes/', 'changes-%s/' % version):- raise RuntimeError('lucene: found %s vs expected changes-%s/' % (text, version))+ elif text.startswith("changes"):+ if text not in ("changes/", "changes-%s/" % version):+ raise RuntimeError("lucene: found %s vs expected changes-%s/" % (text, version))changesURL = subURLelif artifact is None:artifact = textartifactURL = subURL- expected = 'lucene-%s' % version+ expected = "lucene-%s" % versionif not artifact.startswith(expected):- raise RuntimeError('lucene: unknown artifact %s: expected prefix %s' % (text, expected))+ raise RuntimeError("lucene: unknown artifact %s: expected prefix %s" % (text, expected))sigs = []- elif text.startswith(artifact + '.'):- sigs.append(text[len(artifact)+1:])+ elif text.startswith(artifact + "."):+ sigs.append(text[len(artifact) + 1 :])else:if sigs != expectedSigs:- raise RuntimeError('lucene: artifact %s has wrong sigs: expected %s but got %s' % (artifact, expectedSigs, sigs))+ raise RuntimeError("lucene: artifact %s has wrong sigs: expected %s but got %s" % (artifact, expectedSigs, sigs))artifacts.append((artifact, artifactURL))artifact = textartifactURL = subURL@@ -251,74 +248,69 @@ def checkSigs(urlString, version, tmpDir, isSigned, keysFile):if sigs != []:artifacts.append((artifact, artifactURL))if sigs != expectedSigs:- raise RuntimeError('lucene: artifact %s has wrong sigs: expected %s but got %s' % (artifact, expectedSigs, sigs))+ raise RuntimeError("lucene: artifact %s has wrong sigs: expected %s but got %s" % (artifact, expectedSigs, sigs))- expected = ['lucene-%s-src.tgz' % version,- 'lucene-%s.tgz' % version]+ expected = ["lucene-%s-src.tgz" % version, "lucene-%s.tgz" % version]actual = [x[0] for x in artifacts]if expected != actual:- raise RuntimeError('lucene: wrong artifacts: expected %s but got %s' % (expected, actual))+ raise RuntimeError("lucene: wrong artifacts: expected %s but got %s" % (expected, actual))# Set up clean gpg world; import keys file:- gpgHomeDir = '%s/lucene.gpg' % tmpDir+ gpgHomeDir = "%s/lucene.gpg" % tmpDirif os.path.exists(gpgHomeDir):shutil.rmtree(gpgHomeDir)os.makedirs(gpgHomeDir, 0o700)- run('gpg --homedir %s --import %s' % (gpgHomeDir, keysFile),- '%s/lucene.gpg.import.log' % tmpDir)+ run("gpg --homedir %s --import %s" % (gpgHomeDir, keysFile), "%s/lucene.gpg.import.log" % tmpDir)if mavenURL is None:- raise RuntimeError('lucene is missing maven')+ raise RuntimeError("lucene is missing maven")if changesURL is None:- raise RuntimeError('lucene is missing changes-%s' % version)+ raise RuntimeError("lucene is missing changes-%s" % version)testChanges(version, changesURL)for artifact, urlString in artifacts:- print(' download %s...' % artifact)+ print(" download %s..." % artifact)scriptutil.download(artifact, urlString, tmpDir, force_clean=FORCE_CLEAN)verifyDigests(artifact, urlString, tmpDir)if isSigned:- print(' verify sig')+ print(" verify sig")# Test sig (this is done with a clean brand-new GPG world)- scriptutil.download(artifact + '.asc', urlString + '.asc', tmpDir, force_clean=FORCE_CLEAN)- sigFile = '%s/%s.asc' % (tmpDir, artifact)- artifactFile = '%s/%s' % (tmpDir, artifact)- logFile = '%s/lucene.%s.gpg.verify.log' % (tmpDir, artifact)- run('gpg --homedir %s --display-charset utf-8 --verify %s %s' % (gpgHomeDir, sigFile, artifactFile),- logFile)+ scriptutil.download(artifact + ".asc", urlString + ".asc", tmpDir, force_clean=FORCE_CLEAN)+ sigFile = "%s/%s.asc" % (tmpDir, artifact)+ artifactFile = "%s/%s" % (tmpDir, artifact)+ logFile = "%s/lucene.%s.gpg.verify.log" % (tmpDir, artifact)+ run("gpg --homedir %s --display-charset utf-8 --verify %s %s" % (gpgHomeDir, sigFile, artifactFile), logFile)# Forward any GPG warnings, except the expected one (since it's a clean world)with open(logFile) as f:print("File: %s" % logFile)for line in f.readlines():- if line.lower().find('warning') != -1 \- and line.find('WARNING: This key is not certified with a trusted signature') == -1:- print(' GPG: %s' % line.strip())+ if line.lower().find("warning") != -1 and line.find("WARNING: This key is not certified with a trusted signature") == -1:+ print(" GPG: %s" % line.strip())# Test trust (this is done with the real users config)- run('gpg --import %s' % (keysFile),- '%s/lucene.gpg.trust.import.log' % tmpDir)- print(' verify trust')- logFile = '%s/lucene.%s.gpg.trust.log' % (tmpDir, artifact)- run('gpg --display-charset utf-8 --verify %s %s' % (sigFile, artifactFile), logFile)+ run("gpg --import %s" % (keysFile), "%s/lucene.gpg.trust.import.log" % tmpDir)+ print(" verify trust")+ logFile = "%s/lucene.%s.gpg.trust.log" % (tmpDir, artifact)+ run("gpg --display-charset utf-8 --verify %s %s" % (sigFile, artifactFile), logFile)# Forward any GPG warnings:with open(logFile) as f:for line in f.readlines():- if line.lower().find('warning') != -1:- print(' GPG: %s' % line.strip())+ if line.lower().find("warning") != -1:+ print(" GPG: %s" % line.strip())def testChanges(version, changesURLString):- print(' check changes HTML...')+ print(" check changes HTML...")changesURL = Nonefor text, subURL in getDirEntries(changesURLString):- if text == 'Changes.html':+ if text == "Changes.html":changesURL = subURLif changesURL is None:- raise RuntimeError('did not see Changes.html link from %s' % changesURLString)+ raise RuntimeError("did not see Changes.html link from %s" % changesURLString)s = load(changesURL)checkChangesContent(s, version, changesURL, True)@@ -327,22 +319,22 @@ def testChanges(version, changesURLString):def testChangesText(dir, version):"Checks all CHANGES.txt under this dir."for root, _, files in os.walk(dir):-# NOTE: O(N) but N should be smallish:- if 'CHANGES.txt' in files:- fullPath = '%s/CHANGES.txt' % root- #print 'CHECK %s' % fullPath- checkChangesContent(open(fullPath, encoding='UTF-8').read(), version, fullPath, False)+ if "CHANGES.txt" in files:+ fullPath = "%s/CHANGES.txt" % root+ # print 'CHECK %s' % fullPath+ checkChangesContent(open(fullPath, encoding="UTF-8").read(), version, fullPath, False)+reChangesSectionHREF = re.compile('<a id="(.*?)".*?>(.*?)</a>', re.IGNORECASE)-reUnderbarNotDashHTML = re.compile(r'<li>(\s*(LUCENE)_\d\d\d\d+)')-reUnderbarNotDashTXT = re.compile(r'\s+((LUCENE)_\d\d\d\d+)', re.MULTILINE)+reUnderbarNotDashHTML = re.compile(r"<li>(\s*(LUCENE)_\d\d\d\d+)")+reUnderbarNotDashTXT = re.compile(r"\s+((LUCENE)_\d\d\d\d+)", re.MULTILINE)def checkChangesContent(s, version, name, isHTML):currentVersionTuple = versionToTuple(version, name)- if isHTML and s.find('Release %s' % version) == -1:+ if isHTML and s.find("Release %s" % version) == -1:raise RuntimeError('did not see "Release %s" in %s' % (version, name))if isHTML:@@ -352,16 +344,16 @@ def checkChangesContent(s, version, name, isHTML):m = r.search(s)if m is not None:- raise RuntimeError('incorrect issue (_ instead of -) in %s: %s' % (name, m.group(1)))+ raise RuntimeError("incorrect issue (_ instead of -) in %s: %s" % (name, m.group(1)))- if s.lower().find('not yet released') != -1:+ if s.lower().find("not yet released") != -1:raise RuntimeError('saw "not yet released" in %s' % name)if not isHTML:- sub = 'Lucene %s' % version+ sub = "Lucene %s" % versionif s.find(sub) == -1:# benchmark never seems to include release info:- if name.find('/benchmark/') == -1:+ if name.find("/benchmark/") == -1:raise RuntimeError('did not see "%s" in %s' % (sub, name))if isHTML:@@ -372,12 +364,12 @@ def checkChangesContent(s, version, name, isHTML):release = Nonefor id, text in reChangesSectionHREF.findall(s):- if text.lower().startswith('release '):+ if text.lower().startswith("release "):release = text[8:].strip()seenText.clear()releaseTuple = versionToTuple(release, name)if releaseTuple > currentVersionTuple:- raise RuntimeError('Future release %s is greater than %s in %s' % (release, version, name))+ raise RuntimeError("Future release %s is greater than %s in %s" % (release, version, name))if id in seenIDs:raise RuntimeError('%s has duplicate section "%s" under release "%s"' % (name, text, release))seenIDs.add(id)@@ -386,31 +378,28 @@ def checkChangesContent(s, version, name, isHTML):seenText.add(text)-reVersion = re.compile(r'(\d+)\.(\d+)(?:\.(\d+))?\s*(-alpha|-beta|final|RC\d+)?\s*(?:\[.*\])?', re.IGNORECASE)+reVersion = re.compile(r"(\d+)\.(\d+)(?:\.(\d+))?\s*(-alpha|-beta|final|RC\d+)?\s*(?:\[.*\])?", re.IGNORECASE)def versionToTuple(version, name):versionMatch = reVersion.match(version)if versionMatch is None:- raise RuntimeError('Version %s in %s cannot be parsed' % (version, name))+ raise RuntimeError("Version %s in %s cannot be parsed" % (version, name))versionTuple = versionMatch.groups()- while versionTuple[-1] is None or versionTuple[-1] == '':+ while versionTuple[-1] is None or versionTuple[-1] == "":versionTuple = versionTuple[:-1]- if versionTuple[-1].lower() == '-alpha':- versionTuple = versionTuple[:-1] + ('0',)- elif versionTuple[-1].lower() == '-beta':- versionTuple = versionTuple[:-1] + ('1',)- elif versionTuple[-1].lower() == 'final':- versionTuple = versionTuple[:-2] + ('100',)- elif versionTuple[-1].lower()[:2] == 'rc':+ if versionTuple[-1].lower() == "-alpha":+ versionTuple = versionTuple[:-1] + ("0",)+ elif versionTuple[-1].lower() == "-beta":+ versionTuple = versionTuple[:-1] + ("1",)+ elif versionTuple[-1].lower() == "final":+ versionTuple = versionTuple[:-2] + ("100",)+ elif versionTuple[-1].lower()[:2] == "rc":versionTuple = versionTuple[:-2] + (versionTuple[-1][2:],)return tuple(int(x) if x is not None and x.isnumeric() else x for x in versionTuple)-reUnixPath = re.compile(r'\b[a-zA-Z_]+=(?:"(?:\\"|[^"])*"' + '|(?:\\\\.|[^"\'\\s])*' + r"|'(?:\\'|[^'])*')" \- + r'|(/(?:\\.|[^"\'\s])*)' \- + r'|("/(?:\\.|[^"])*")' \- + r"|('/(?:\\.|[^'])*')")+reUnixPath = re.compile(r'\b[a-zA-Z_]+=(?:"(?:\\"|[^"])*"' + "|(?:\\\\.|[^\"'\\s])*" + r"|'(?:\\'|[^'])*')" + r'|(/(?:\\.|[^"\'\s])*)' + r'|("/(?:\\.|[^"])*")' + r"|('/(?:\\.|[^'])*')")def unix2win(matchobj):@@ -429,22 +418,21 @@ 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:+ if "; gradlew " in command:command = reUnixPath.sub(unix2win, command)return commanddef printFileContents(fileName):-# Assume log file was written in system's default encoding, but# even if we are wrong, we replace errors ... the ASCII chars# (which is what we mostly care about eg for the test seed) should# still survive:- txt = codecs.open(fileName, 'r', encoding=sys.getdefaultencoding(), errors='replace').read()+ txt = codecs.open(fileName, "r", encoding=sys.getdefaultencoding(), errors="replace").read()# Encode to our output encoding (likely also system's default# encoding):- bytes = txt.encode(sys.stdout.encoding, errors='replace')+ bytes = txt.encode(sys.stdout.encoding, errors="replace")# Decode back to string and print... we should hit no exception here# since all errors have been replaced:@@ -455,7 +443,7 @@ def printFileContents(fileName):def run(command, logFile):if cygwin:command = cygwinifyPaths(command)- if os.system('%s > %s 2>&1' % (command, logFile)):+ if os.system("%s > %s 2>&1" % (command, logFile)):logPath = os.path.abspath(logFile)print('\ncommand "%s" failed:' % command)printFileContents(logFile)@@ -463,13 +451,13 @@ def run(command, logFile):def verifyDigests(artifact, urlString, tmpDir):- print(' verify sha512 digest')- sha512Expected, t = load(urlString + '.sha512').strip().split()- if t != '*'+artifact:- raise RuntimeError('SHA512 %s.sha512 lists artifact %s but expected *%s' % (urlString, t, artifact))+ print(" verify sha512 digest")+ sha512Expected, t = load(urlString + ".sha512").strip().split()+ if t != "*" + artifact:+ raise RuntimeError("SHA512 %s.sha512 lists artifact %s but expected *%s" % (urlString, t, artifact))s512 = hashlib.sha512()- f = open('%s/%s' % (tmpDir, artifact), 'rb')+ f = open("%s/%s" % (tmpDir, artifact), "rb")while True:x = f.read(65536)if len(x) == 0:@@ -478,69 +466,70 @@ def verifyDigests(artifact, urlString, tmpDir):f.close()sha512Actual = s512.hexdigest()if sha512Actual != sha512Expected:- raise RuntimeError('SHA512 digest mismatch for %s: expected %s but got %s' % (artifact, sha512Expected, sha512Actual))+ raise RuntimeError("SHA512 digest mismatch for %s: expected %s but got %s" % (artifact, sha512Expected, sha512Actual))def getDirEntries(urlString):- if urlString.startswith('file:/') and not urlString.startswith('file://'):+ if urlString.startswith("file:/") and not urlString.startswith("file://"):# stupid bogus ant URIurlString = "file:///" + urlString[6:]- if urlString.startswith('file://'):+ if urlString.startswith("file://"):path = urlString[7:]- if path.endswith('/'):+ if path.endswith("/"):path = path[:-1]- if cygwin: # Convert Windows path to Cygwin path- path = re.sub(r'^/([A-Za-z]):/', r'/cygdrive/\1/', path)+ if cygwin: # Convert Windows path to Cygwin path+ path = re.sub(r"^/([A-Za-z]):/", r"/cygdrive/\1/", path)files = []for ent in os.listdir(path):- entPath = '%s/%s' % (path, ent)+ entPath = "%s/%s" % (path, ent)if os.path.isdir(entPath):- entPath += '/'- ent += '/'- files.append((ent, 'file://%s' % entPath))+ entPath += "/"+ ent += "/"+ files.append((ent, "file://%s" % entPath))files.sort()return fileselse:links = getHREFs(urlString)for i, (text, _) in enumerate(links):- if text == 'Parent Directory' or text == '..':- return links[(i+1):]- raise RuntimeError('could not enumerate %s' % (urlString))+ if text == "Parent Directory" or text == "..":+ return links[(i + 1) :]+ raise RuntimeError("could not enumerate %s" % (urlString))def unpackAndVerify(java, tmpDir, artifact, gitRevision, version, testArgs):- destDir = '%s/unpack' % tmpDir+ destDir = "%s/unpack" % tmpDirif os.path.exists(destDir):shutil.rmtree(destDir)os.makedirs(destDir)os.chdir(destDir)- print(' unpack %s...' % artifact)- unpackLogFile = '%s/lucene-unpack-%s.log' % (tmpDir, artifact)- if artifact.endswith('.tar.gz') or artifact.endswith('.tgz'):- run('tar xzf %s/%s' % (tmpDir, artifact), unpackLogFile)- elif artifact.endswith('.zip'):- run('unzip %s/%s' % (tmpDir, artifact), unpackLogFile)+ print(" unpack %s..." % artifact)+ unpackLogFile = "%s/lucene-unpack-%s.log" % (tmpDir, artifact)+ if artifact.endswith(".tar.gz") or artifact.endswith(".tgz"):+ run("tar xzf %s/%s" % (tmpDir, artifact), unpackLogFile)+ elif artifact.endswith(".zip"):+ run("unzip %s/%s" % (tmpDir, artifact), unpackLogFile)# make sure it unpacks to proper subdirfiles = os.listdir(destDir)- expected = 'lucene-%s' % version+ expected = "lucene-%s" % versionif files != [expected]:- raise RuntimeError('unpack produced entries %s; expected only %s' % (files, expected))+ raise RuntimeError("unpack produced entries %s; expected only %s" % (files, expected))- unpackPath = '%s/%s' % (destDir, expected)+ unpackPath = "%s/%s" % (destDir, expected)verifyUnpacked(java, artifact, unpackPath, gitRevision, version, testArgs)return unpackPath+LUCENE_NOTICE = NoneLUCENE_LICENSE = Nonedef is_in_list(in_folder, files, indent=4):for fileName in files:- print("%sChecking %s" % (" "*indent, fileName))+ print("%sChecking %s" % (" " * indent, fileName))found = False- for f in [fileName, fileName + '.txt', fileName + '.md']:+ for f in [fileName, fileName + ".txt", fileName + ".md"]:if f in in_folder:in_folder.remove(f)found = True@@ -553,24 +542,23 @@ def verifyUnpacked(java, artifact, unpackPath, gitRevision, version, testArgs):global LUCENE_LICENSEos.chdir(unpackPath)- isSrc = artifact.find('-src') != -1+ isSrc = artifact.find("-src") != -1# Check text files in releaseprint(" %s" % artifact)- in_root_folder = list(filter(lambda x: x[0] != '.', os.listdir(unpackPath)))+ in_root_folder = list(filter(lambda x: x[0] != ".", os.listdir(unpackPath)))in_lucene_folder = []if isSrc:- in_lucene_folder.extend(os.listdir(os.path.join(unpackPath, 'lucene')))- is_in_list(in_root_folder, ['LICENSE', 'NOTICE', 'README'])- is_in_list(in_lucene_folder, ['JRE_VERSION_MIGRATION', 'CHANGES', 'MIGRATE', 'SYSTEM_REQUIREMENTS'])+ in_lucene_folder.extend(os.listdir(os.path.join(unpackPath, "lucene")))+ is_in_list(in_root_folder, ["LICENSE", "NOTICE", "README"])+ is_in_list(in_lucene_folder, ["JRE_VERSION_MIGRATION", "CHANGES", "MIGRATE", "SYSTEM_REQUIREMENTS"])else:- is_in_list(in_root_folder, ['LICENSE', 'NOTICE', 'README', 'JRE_VERSION_MIGRATION', 'CHANGES',- 'MIGRATE', 'SYSTEM_REQUIREMENTS'])+ is_in_list(in_root_folder, ["LICENSE", "NOTICE", "README", "JRE_VERSION_MIGRATION", "CHANGES", "MIGRATE", "SYSTEM_REQUIREMENTS"])if LUCENE_NOTICE is None:- LUCENE_NOTICE = open('%s/NOTICE.txt' % unpackPath, encoding='UTF-8').read()+ LUCENE_NOTICE = open("%s/NOTICE.txt" % unpackPath, encoding="UTF-8").read()if LUCENE_LICENSE is None:- LUCENE_LICENSE = open('%s/LICENSE.txt' % unpackPath, encoding='UTF-8').read()+ LUCENE_LICENSE = open("%s/LICENSE.txt" % unpackPath, encoding="UTF-8").read()# if not isSrc:# # TODO: we should add verifyModule/verifySubmodule (e.g. analysis) here and recurse through@@ -582,63 +570,103 @@ def verifyUnpacked(java, artifact, unpackPath, gitRevision, version, testArgs):# raise RuntimeError('lucene: file "%s" is missing from artifact %s' % (fileName, artifact))# in_root_folder.remove(fileName)- expected_folders = ['analysis', 'analysis.tests', 'backward-codecs', 'benchmark', 'benchmark-jmh', 'classification', 'codecs', 'core', 'core.tests',- 'distribution.tests', 'demo', 'expressions', 'facet', 'grouping', 'highlighter', 'join',- 'luke', 'memory', 'misc', 'monitor', 'queries', 'queryparser', 'replicator',- 'sandbox', 'spatial-extras', 'spatial-test-fixtures', 'spatial3d', 'suggest', 'test-framework', 'licenses']+ expected_folders = [+ "analysis",+ "analysis.tests",+ "backward-codecs",+ "benchmark",+ "benchmark-jmh",+ "classification",+ "codecs",+ "core",+ "core.tests",+ "distribution.tests",+ "demo",+ "expressions",+ "facet",+ "grouping",+ "highlighter",+ "join",+ "luke",+ "memory",+ "misc",+ "monitor",+ "queries",+ "queryparser",+ "replicator",+ "sandbox",+ "spatial-extras",+ "spatial-test-fixtures",+ "spatial3d",+ "suggest",+ "test-framework",+ "licenses",+ ]if isSrc:- expected_src_root_files = ['build.gradle', 'build-tools', 'CONTRIBUTING.md', 'dev-docs', 'dev-tools', 'gradle', 'gradlew',- 'gradlew.bat', 'help', 'lucene', 'settings.gradle', 'versions.lock', 'versions.toml']- expected_src_lucene_files = ['build.gradle', 'documentation', 'distribution', 'dev-docs']+ expected_src_root_files = [+ "build.gradle",+ "build-tools",+ "CONTRIBUTING.md",+ "dev-docs",+ "dev-tools",+ "gradle",+ "gradlew",+ "gradlew.bat",+ "help",+ "lucene",+ "settings.gradle",+ "versions.lock",+ "versions.toml",+ ]+ expected_src_lucene_files = ["build.gradle", "documentation", "distribution", "dev-docs"]is_in_list(in_root_folder, expected_src_root_files)is_in_list(in_lucene_folder, expected_folders)is_in_list(in_lucene_folder, expected_src_lucene_files)if len(in_lucene_folder) > 0:- raise RuntimeError('lucene: unexpected files/dirs in artifact %s lucene/ folder: %s' % (artifact, in_lucene_folder))+ raise RuntimeError("lucene: unexpected files/dirs in artifact %s lucene/ folder: %s" % (artifact, in_lucene_folder))else:- is_in_list(in_root_folder, ['bin', 'docs', 'licenses', 'modules', 'modules-thirdparty', 'modules-test-framework'])+ is_in_list(in_root_folder, ["bin", "docs", "licenses", "modules", "modules-thirdparty", "modules-test-framework"])if len(in_root_folder) > 0:- raise RuntimeError('lucene: unexpected files/dirs in artifact %s: %s' % (artifact, in_root_folder))+ raise RuntimeError("lucene: unexpected files/dirs in artifact %s: %s" % (artifact, in_root_folder))if isSrc:- print(' make sure no JARs/WARs in src dist...')- lines = os.popen('find . -name \\*.jar').readlines()+ print(" make sure no JARs/WARs in src dist...")+ lines = os.popen("find . -name \\*.jar").readlines()if len(lines) != 0:- print(' FAILED:')+ print(" FAILED:")for line in lines:- print(' %s' % line.strip())- raise RuntimeError('source release has JARs...')- lines = os.popen('find . -name \\*.war').readlines()+ print(" %s" % line.strip())+ raise RuntimeError("source release has JARs...")+ lines = os.popen("find . -name \\*.war").readlines()if len(lines) != 0:- print(' FAILED:')+ print(" FAILED:")for line in lines:- print(' %s' % line.strip())- raise RuntimeError('source release has WARs...')+ print(" %s" % line.strip())+ raise RuntimeError("source release has WARs...")- validateCmd = './gradlew --no-daemon check -p lucene/documentation'+ validateCmd = "./gradlew --no-daemon check -p lucene/documentation"print(' run "%s"' % validateCmd)- java.run_java(validateCmd, '%s/validate.log' % unpackPath)+ java.run_java(validateCmd, "%s/validate.log" % unpackPath)print(" run tests w/ Java %s and testArgs='%s'..." % (BASE_JAVA_VERSION, testArgs))- java.run_java('./gradlew --no-daemon test %s' % testArgs, '%s/test.log' % unpackPath)+ java.run_java("./gradlew --no-daemon test %s" % testArgs, "%s/test.log" % unpackPath)print(" compile jars w/ Java %s" % BASE_JAVA_VERSION)- java.run_java('./gradlew --no-daemon jar -Dversion.release=%s' % version, '%s/compile.log' % unpackPath)+ java.run_java("./gradlew --no-daemon jar -Dversion.release=%s" % version, "%s/compile.log" % unpackPath)testDemo(java.run_java, isSrc, version, BASE_JAVA_VERSION)if java.run_alt_javas:for run_alt_java, alt_java_version in zip(java.run_alt_javas, java.alt_java_versions):print(" run tests w/ Java %s and testArgs='%s'..." % (alt_java_version, testArgs))- run_alt_java('./gradlew --no-daemon test %s' % testArgs, '%s/test.log' % unpackPath)+ run_alt_java("./gradlew --no-daemon test %s" % testArgs, "%s/test.log" % unpackPath)print(" compile jars w/ Java %s" % alt_java_version)- run_alt_java('./gradlew --no-daemon jar -Dversion.release=%s' % version, '%s/compile.log' % unpackPath)+ run_alt_java("./gradlew --no-daemon jar -Dversion.release=%s" % version, "%s/compile.log" % unpackPath)testDemo(run_alt_java, isSrc, version, alt_java_version)- print(' confirm all releases have coverage in TestBackwardsCompatibility')+ print(" confirm all releases have coverage in TestBackwardsCompatibility")confirmAllReleasesAreTestedForBackCompat(version, unpackPath)else:-checkAllJARs(os.getcwd(), gitRevision, version)testDemo(java.run_java, isSrc, version, BASE_JAVA_VERSION)@@ -646,66 +674,68 @@ def verifyUnpacked(java, artifact, unpackPath, gitRevision, version, testArgs):for run_alt_java, alt_java_version in zip(java.run_alt_javas, java.alt_java_versions):testDemo(run_alt_java, isSrc, version, alt_java_version)- testChangesText('.', version)+ testChangesText(".", version)def testDemo(run_java, isSrc, version, jdk):- if os.path.exists('index'):- shutil.rmtree('index') # nuke any index from any previous iteration+ if os.path.exists("index"):+ shutil.rmtree("index") # nuke any index from any previous iteration- print(' test demo with %s...' % jdk)- sep = ';' if cygwin else ':'+ print(" test demo with %s..." % jdk)+ sep = ";" if cygwin else ":"if isSrc:# For source release, use the classpath for each module.- classPath = ['lucene/core/build/libs/lucene-core-%s.jar' % version,- 'lucene/demo/build/libs/lucene-demo-%s.jar' % version,- 'lucene/analysis/common/build/libs/lucene-analyzers-common-%s.jar' % version,- 'lucene/queryparser/build/libs/lucene-queryparser-%s.jar' % version]+ classPath = [+ "lucene/core/build/libs/lucene-core-%s.jar" % version,+ "lucene/demo/build/libs/lucene-demo-%s.jar" % version,+ "lucene/analysis/common/build/libs/lucene-analyzers-common-%s.jar" % version,+ "lucene/queryparser/build/libs/lucene-queryparser-%s.jar" % version,+ ]cp = sep.join(classPath)- docsDir = 'lucene/core/src'+ docsDir = "lucene/core/src"checkIndexCmd = 'java -ea -cp "%s" org.apache.lucene.index.CheckIndex index' % cpindexFilesCmd = 'java -cp "%s" -Dsmoketester=true org.apache.lucene.demo.IndexFiles -index index -docs %s' % (cp, docsDir)searchFilesCmd = 'java -cp "%s" org.apache.lucene.demo.SearchFiles -index index -query lucene' % cpelse:# For binary release, set up module path.cp = "--module-path %s" % (sep.join(["modules", "modules-thirdparty"]))- docsDir = 'docs'- checkIndexCmd = 'java -ea %s --module org.apache.lucene.core/org.apache.lucene.index.CheckIndex index' % cp- indexFilesCmd = 'java -Dsmoketester=true %s --module org.apache.lucene.demo/org.apache.lucene.demo.IndexFiles -index index -docs %s' % (cp, docsDir)- searchFilesCmd = 'java %s --module org.apache.lucene.demo/org.apache.lucene.demo.SearchFiles -index index -query lucene' % cp-- run_java(indexFilesCmd, 'index.log')- run_java(searchFilesCmd, 'search.log')- reMatchingDocs = re.compile(r'(\d+) total matching documents')- m = reMatchingDocs.search(open('search.log', encoding='UTF-8').read())+ docsDir = "docs"+ checkIndexCmd = "java -ea %s --module org.apache.lucene.core/org.apache.lucene.index.CheckIndex index" % cp+ indexFilesCmd = "java -Dsmoketester=true %s --module org.apache.lucene.demo/org.apache.lucene.demo.IndexFiles -index index -docs %s" % (cp, docsDir)+ searchFilesCmd = "java %s --module org.apache.lucene.demo/org.apache.lucene.demo.SearchFiles -index index -query lucene" % cp++ run_java(indexFilesCmd, "index.log")+ run_java(searchFilesCmd, "search.log")+ reMatchingDocs = re.compile(r"(\d+) total matching documents")+ m = reMatchingDocs.search(open("search.log", encoding="UTF-8").read())if m is None:- raise RuntimeError('lucene demo\'s SearchFiles found no results')+ raise RuntimeError("lucene demo's SearchFiles found no results")else:numHits = int(m.group(1))if numHits < 100:- raise RuntimeError('lucene demo\'s SearchFiles found too few results: %s' % numHits)+ raise RuntimeError("lucene demo's SearchFiles found too few results: %s" % numHits)print(' got %d hits for query "lucene"' % numHits)- print(' checkindex with %s...' % jdk)- run_java(checkIndexCmd, 'checkindex.log')- s = open('checkindex.log').read()- m = re.search(r'^\s+version=(.*?)$', s, re.MULTILINE)+ print(" checkindex with %s..." % jdk)+ run_java(checkIndexCmd, "checkindex.log")+ s = open("checkindex.log").read()+ m = re.search(r"^\s+version=(.*?)$", s, re.MULTILINE)if m is None:- raise RuntimeError('unable to locate version=NNN output from CheckIndex; see checkindex.log')+ raise RuntimeError("unable to locate version=NNN output from CheckIndex; see checkindex.log")actualVersion = m.group(1)if removeTrailingZeros(actualVersion) != removeTrailingZeros(version):raise RuntimeError('wrong version from CheckIndex: got "%s" but expected "%s"' % (actualVersion, version))def removeTrailingZeros(version):- return re.sub(r'(\.0)*$', '', version)+ return re.sub(r"(\.0)*$", "", version)def checkMaven(baseURL, tmpDir, gitRevision, version, isSigned, keysFile):- print(' download artifacts')+ print(" download artifacts")artifacts = []- artifactsURL = '%s/lucene/maven/org/apache/lucene/' % baseURL- targetDir = '%s/maven/org/apache/lucene' % tmpDir+ artifactsURL = "%s/lucene/maven/org/apache/lucene/" % baseURL+ targetDir = "%s/maven/org/apache/lucene" % tmpDirif not os.path.exists(targetDir):os.makedirs(targetDir)crawl(artifacts, artifactsURL, targetDir)@@ -720,23 +750,23 @@ def checkMaven(baseURL, tmpDir, gitRevision, version, isSigned, keysFile):distFiles = getBinaryDistFiles(tmpDir, version, baseURL)checkIdenticalMavenArtifacts(distFiles, artifacts, version)- checkAllJARs('%s/maven/org/apache/lucene' % tmpDir, gitRevision, version)+ checkAllJARs("%s/maven/org/apache/lucene" % tmpDir, gitRevision, version)def getBinaryDistFiles(tmpDir, version, baseURL):- distribution = 'lucene-%s.tgz' % version- if not os.path.exists('%s/%s' % (tmpDir, distribution)):- distURL = '%s/lucene/%s' % (baseURL, distribution)- print(' download %s...' % distribution, end=' ')+ distribution = "lucene-%s.tgz" % version+ if not os.path.exists("%s/%s" % (tmpDir, distribution)):+ distURL = "%s/lucene/%s" % (baseURL, distribution)+ print(" download %s..." % distribution, end=" ")scriptutil.download(distribution, distURL, tmpDir, force_clean=FORCE_CLEAN)- destDir = '%s/unpack-lucene-getBinaryDistFiles' % tmpDir+ destDir = "%s/unpack-lucene-getBinaryDistFiles" % tmpDirif os.path.exists(destDir):shutil.rmtree(destDir)os.makedirs(destDir)os.chdir(destDir)- print(' unpack %s...' % distribution)- unpackLogFile = '%s/unpack-%s-getBinaryDistFiles.log' % (tmpDir, distribution)- run('tar xzf %s/%s' % (tmpDir, distribution), unpackLogFile)+ print(" unpack %s..." % distribution)+ unpackLogFile = "%s/unpack-%s-getBinaryDistFiles.log" % (tmpDir, distribution)+ run("tar xzf %s/%s" % (tmpDir, distribution), unpackLogFile)distributionFiles = []for root, _, files in os.walk(destDir):distributionFiles.extend([os.path.join(root, file) for file in files])@@ -744,15 +774,15 @@ def getBinaryDistFiles(tmpDir, version, baseURL):def checkJavadocAndSourceArtifacts(artifacts, version):- print(' check for javadoc and sources artifacts...')+ print(" check for javadoc and sources artifacts...")for artifact in artifacts:- if artifact.endswith(version + '.jar'):- javadocJar = artifact[:-4] + '-javadoc.jar'+ if artifact.endswith(version + ".jar"):+ javadocJar = artifact[:-4] + "-javadoc.jar"if javadocJar not in artifacts:- raise RuntimeError('missing: %s' % javadocJar)- sourcesJar = artifact[:-4] + '-sources.jar'+ raise RuntimeError("missing: %s" % javadocJar)+ sourcesJar = artifact[:-4] + "-sources.jar"if sourcesJar not in artifacts:- raise RuntimeError('missing: %s' % sourcesJar)+ raise RuntimeError("missing: %s" % sourcesJar)def getZipFileEntries(fileName):@@ -766,8 +796,8 @@ def getZipFileEntries(fileName):def checkIdenticalMavenArtifacts(distFiles, artifacts, version):- print(' verify that Maven artifacts are same as in the binary distribution...')- reJarWar = re.compile(r'%s\.[wj]ar$' % version) # exclude *-javadoc.jar and *-sources.jar+ print(" verify that Maven artifacts are same as in the binary distribution...")+ reJarWar = re.compile(r"%s\.[wj]ar$" % version) # exclude *-javadoc.jar and *-sources.jardistFilenames = dict()for file in distFiles:baseName = os.path.basename(file)@@ -776,29 +806,28 @@ def checkIdenticalMavenArtifacts(distFiles, artifacts, version):if reJarWar.search(artifact):artifactFilename = os.path.basename(artifact)if artifactFilename not in distFilenames:- raise RuntimeError('Maven artifact %s is not present in lucene binary distribution' % artifact)+ raise RuntimeError("Maven artifact %s is not present in lucene binary distribution" % artifact)else:identical = filecmp.cmp(artifact, distFilenames[artifactFilename], shallow=False)if not identical:- raise RuntimeError('Maven artifact %s is not identical to %s in lucene binary distribution'- % (artifact, distFilenames[artifactFilename]))+ raise RuntimeError("Maven artifact %s is not identical to %s in lucene binary distribution" % (artifact, distFilenames[artifactFilename]))def verifyMavenDigests(artifacts):print(" verify Maven artifacts' md5/sha1 digests...")- reJarWarPom = re.compile(r'\.(?:[wj]ar|pom)$')+ reJarWarPom = re.compile(r"\.(?:[wj]ar|pom)$")for artifactFile in [a for a in artifacts if reJarWarPom.search(a)]:- if artifactFile + '.md5' not in artifacts:- raise RuntimeError('missing: MD5 digest for %s' % artifactFile)- if artifactFile + '.sha1' not in artifacts:- raise RuntimeError('missing: SHA1 digest for %s' % artifactFile)- with open(artifactFile + '.md5', encoding='UTF-8') as md5File:+ if artifactFile + ".md5" not in artifacts:+ raise RuntimeError("missing: MD5 digest for %s" % artifactFile)+ if artifactFile + ".sha1" not in artifacts:+ raise RuntimeError("missing: SHA1 digest for %s" % artifactFile)+ with open(artifactFile + ".md5", encoding="UTF-8") as md5File:md5Expected = md5File.read().strip()- with open(artifactFile + '.sha1', encoding='UTF-8') as sha1File:+ with open(artifactFile + ".sha1", encoding="UTF-8") as sha1File:sha1Expected = sha1File.read().strip()md5 = hashlib.md5()sha1 = hashlib.sha1()- inputFile = open(artifactFile, 'rb')+ inputFile = open(artifactFile, "rb")while True:bytes = inputFile.read(65536)if len(bytes) == 0:@@ -809,80 +838,73 @@ def verifyMavenDigests(artifacts):md5Actual = md5.hexdigest()sha1Actual = sha1.hexdigest()if md5Actual != md5Expected:- raise RuntimeError('MD5 digest mismatch for %s: expected %s but got %s'- % (artifactFile, md5Expected, md5Actual))+ raise RuntimeError("MD5 digest mismatch for %s: expected %s but got %s" % (artifactFile, md5Expected, md5Actual))if sha1Actual != sha1Expected:- raise RuntimeError('SHA1 digest mismatch for %s: expected %s but got %s'- % (artifactFile, sha1Expected, sha1Actual))+ raise RuntimeError("SHA1 digest mismatch for %s: expected %s but got %s" % (artifactFile, sha1Expected, sha1Actual))def getPOMcoordinate(treeRoot):- namespace = '{http://maven.apache.org/POM/4.0.0}'- groupId = treeRoot.find('%sgroupId' % namespace)+ namespace = "{http://maven.apache.org/POM/4.0.0}"+ groupId = treeRoot.find("%sgroupId" % namespace)if groupId is None:- groupId = treeRoot.find('{0}parent/{0}groupId'.format(namespace))+ groupId = treeRoot.find("{0}parent/{0}groupId".format(namespace))groupId = groupId.text.strip()- artifactId = treeRoot.find('%sartifactId' % namespace).text.strip()- version = treeRoot.find('%sversion' % namespace)+ artifactId = treeRoot.find("%sartifactId" % namespace).text.strip()+ version = treeRoot.find("%sversion" % namespace)if version is None:- version = treeRoot.find('{0}parent/{0}version'.format(namespace))+ version = treeRoot.find("{0}parent/{0}version".format(namespace))version = version.text.strip()- packaging = treeRoot.find('%spackaging' % namespace)- packaging = 'jar' if packaging is None else packaging.text.strip()+ packaging = treeRoot.find("%spackaging" % namespace)+ packaging = "jar" if packaging is None else packaging.text.strip()return groupId, artifactId, packaging, versiondef verifyMavenSigs(tmpDir, artifacts, keysFile):- print(' verify maven artifact sigs', end=' ')+ print(" verify maven artifact sigs", end=" ")# Set up clean gpg world; import keys file:- gpgHomeDir = '%s/lucene.gpg' % tmpDir+ gpgHomeDir = "%s/lucene.gpg" % tmpDirif os.path.exists(gpgHomeDir):shutil.rmtree(gpgHomeDir)os.makedirs(gpgHomeDir, 0o700)- run('gpg --homedir %s --import %s' % (gpgHomeDir, keysFile),- '%s/lucene.gpg.import.log' % tmpDir)+ run("gpg --homedir %s --import %s" % (gpgHomeDir, keysFile), "%s/lucene.gpg.import.log" % tmpDir)- reArtifacts = re.compile(r'\.(?:pom|[jw]ar)$')+ reArtifacts = re.compile(r"\.(?:pom|[jw]ar)$")for artifactFile in [a for a in artifacts if reArtifacts.search(a)]:artifact = os.path.basename(artifactFile)- sigFile = '%s.asc' % artifactFile+ sigFile = "%s.asc" % artifactFile# Test sig (this is done with a clean brand-new GPG world)- logFile = '%s/lucene.%s.gpg.verify.log' % (tmpDir, artifact)- run('gpg --display-charset utf-8 --homedir %s --verify %s %s' % (gpgHomeDir, sigFile, artifactFile),- logFile)+ logFile = "%s/lucene.%s.gpg.verify.log" % (tmpDir, artifact)+ run("gpg --display-charset utf-8 --homedir %s --verify %s %s" % (gpgHomeDir, sigFile, artifactFile), logFile)# Forward any GPG warnings, except the expected one (since it's a clean world)print_warnings_in_file(logFile)# Test trust (this is done with the real users config)- run('gpg --import %s' % keysFile,- '%s/lucene.gpg.trust.import.log' % tmpDir)- logFile = '%s/lucene.%s.gpg.trust.log' % (tmpDir, artifact)- run('gpg --display-charset utf-8 --verify %s %s' % (sigFile, artifactFile), logFile)+ run("gpg --import %s" % keysFile, "%s/lucene.gpg.trust.import.log" % tmpDir)+ logFile = "%s/lucene.%s.gpg.trust.log" % (tmpDir, artifact)+ run("gpg --display-charset utf-8 --verify %s %s" % (sigFile, artifactFile), logFile)# Forward any GPG warnings:print_warnings_in_file(logFile)- sys.stdout.write('.')+ sys.stdout.write(".")print()def print_warnings_in_file(file):with open(file) as f:for line in f.readlines():- if line.lower().find('warning') != -1 \- and line.find('WARNING: This key is not certified with a trusted signature') == -1 \- and line.find('WARNING: using insecure memory') == -1:- print(' GPG: %s' % line.strip())+ if line.lower().find("warning") != -1 and line.find("WARNING: This key is not certified with a trusted signature") == -1 and line.find("WARNING: using insecure memory") == -1:+ print(" GPG: %s" % line.strip())def verifyPOMperBinaryArtifact(artifacts, version):- print(' verify that each binary artifact has a deployed POM...')- reBinaryJarWar = re.compile(r'%s\.[jw]ar$' % re.escape(version))+ print(" verify that each binary artifact has a deployed POM...")+ reBinaryJarWar = re.compile(r"%s\.[jw]ar$" % re.escape(version))for artifact in [a for a in artifacts if reBinaryJarWar.search(a)]:- POM = artifact[:-4] + '.pom'+ POM = artifact[:-4] + ".pom"if POM not in artifacts:- raise RuntimeError('missing: POM for %s' % artifact)+ raise RuntimeError("missing: POM for %s" % artifact)def verifyDeployedPOMsCoordinates(artifacts, version):@@ -891,25 +913,23 @@ def verifyDeployedPOMsCoordinates(artifacts, version):its filepath, and verify that the corresponding artifact exists."""print(" verify deployed POMs' coordinates...")- for POM in [a for a in artifacts if a.endswith('.pom')]:+ for POM in [a for a in artifacts if a.endswith(".pom")]:treeRoot = ET.parse(POM).getroot()groupId, artifactId, packaging, POMversion = getPOMcoordinate(treeRoot)- POMpath = '%s/%s/%s/%s-%s.pom' \- % (groupId.replace('.', '/'), artifactId, version, artifactId, version)+ POMpath = "%s/%s/%s/%s-%s.pom" % (groupId.replace(".", "/"), artifactId, version, artifactId, version)if not POM.endswith(POMpath):- raise RuntimeError("Mismatch between POM coordinate %s:%s:%s and filepath: %s"- % (groupId, artifactId, POMversion, POM))+ raise RuntimeError("Mismatch between POM coordinate %s:%s:%s and filepath: %s" % (groupId, artifactId, POMversion, POM))# Verify that the corresponding artifact existsartifact = POM[:-3] + packagingif artifact not in artifacts:- raise RuntimeError('Missing corresponding .%s artifact for POM %s' % (packaging, POM))+ raise RuntimeError("Missing corresponding .%s artifact for POM %s" % (packaging, POM))def crawl(downloadedFiles, urlString, targetDir, exclusions=set()):for text, subURL in getDirEntries(urlString):if text not in exclusions:path = os.path.join(targetDir, text)- if text.endswith('/'):+ if text.endswith("/"):if not os.path.exists(path):os.makedirs(path)crawl(downloadedFiles, subURL, path, exclusions)@@ -917,39 +937,37 @@ def crawl(downloadedFiles, urlString, targetDir, exclusions=set()):if not os.path.exists(path) or FORCE_CLEAN:scriptutil.download(text, subURL, targetDir, quiet=True, force_clean=FORCE_CLEAN)downloadedFiles.append(path)- sys.stdout.write('.')+ sys.stdout.write(".")def make_java_config(parser, alt_java_homes):def _make_runner(java_home, is_base_version=False):if cygwin:- java_home = subprocess.check_output('cygpath -u "%s"' % java_home, shell=True).decode('utf-8').strip()- cmd_prefix = 'export JAVA_HOME="%s" PATH="%s/bin:$PATH" JAVACMD="%s/bin/java"' % \- (java_home, java_home, java_home)- s = subprocess.check_output('%s; java -version' % cmd_prefix,- shell=True, stderr=subprocess.STDOUT).decode('utf-8')+ java_home = subprocess.check_output('cygpath -u "%s"' % java_home, shell=True).decode("utf-8").strip()+ cmd_prefix = 'export JAVA_HOME="%s" PATH="%s/bin:$PATH" JAVACMD="%s/bin/java"' % (java_home, java_home, java_home)+ s = subprocess.check_output("%s; java -version" % cmd_prefix, shell=True, stderr=subprocess.STDOUT).decode("utf-8")match = re.search(r'version "([1-9][0-9]*)', s)assert matchactual_version = match.group(1)- print('Java %s JAVA_HOME=%s' % (actual_version, java_home))+ print("Java %s JAVA_HOME=%s" % (actual_version, java_home))# validate Java versionif is_base_version:if BASE_JAVA_VERSION != actual_version:- parser.error('got wrong base version for java %s:\n%s' % (BASE_JAVA_VERSION, s))+ parser.error("got wrong base version for java %s:\n%s" % (BASE_JAVA_VERSION, s))else:if int(actual_version) < int(BASE_JAVA_VERSION):- parser.error('got wrong version for java %s, less than base version %s:\n%s' % (actual_version, BASE_JAVA_VERSION, s))+ parser.error("got wrong version for java %s, less than base version %s:\n%s" % (actual_version, BASE_JAVA_VERSION, s))def run_java(cmd, logfile):- run('%s; %s' % (cmd_prefix, cmd), logfile)+ run("%s; %s" % (cmd_prefix, cmd), logfile)return run_java, actual_version- java_home = os.environ.get('JAVA_HOME')+ java_home = os.environ.get("JAVA_HOME")if java_home is None:- parser.error('JAVA_HOME must be set')+ parser.error("JAVA_HOME must be set")run_java, _ = _make_runner(java_home, True)run_alt_javas = []alt_java_versions = []@@ -959,37 +977,30 @@ def make_java_config(parser, alt_java_homes):run_alt_javas.append(run_alt_java)alt_java_versions.append(version)- jc = namedtuple('JavaConfig', 'run_java java_home run_alt_javas alt_java_homes alt_java_versions')+ jc = namedtuple("JavaConfig", "run_java java_home run_alt_javas alt_java_homes alt_java_versions")return jc(run_java, java_home, run_alt_javas, alt_java_homes, alt_java_versions)-version_re = re.compile(r'(\d+\.\d+\.\d+(-ALPHA|-BETA)?)')-revision_re = re.compile(r'rev-([a-f\d]+)')++version_re = re.compile(r"(\d+\.\d+\.\d+(-ALPHA|-BETA)?)")+revision_re = re.compile(r"rev-([a-f\d]+)")+def parse_config():- epilogue = textwrap.dedent('''+ epilogue = textwrap.dedent("""Example usage:python3 -u dev-tools/scripts/smokeTestRelease.py https://dist.apache.org/repos/dist/dev/lucene/lucene-9.0.0-RC1-rev-c7510a0...- ''')- description = 'Utility to test a release.'- parser = argparse.ArgumentParser(description=description, epilog=epilogue,- formatter_class=argparse.RawDescriptionHelpFormatter)- parser.add_argument('--tmp-dir', metavar='PATH',- help='Temporary directory to test inside, defaults to /tmp/smoke_lucene_$version_$revision')- parser.add_argument('--not-signed', dest='is_signed', action='store_false', default=True,- help='Indicates the release is not signed')- parser.add_argument('--local-keys', metavar='PATH',- help='Uses local KEYS file instead of fetching from https://archive.apache.org/dist/lucene/KEYS')- parser.add_argument('--revision',- help='GIT revision number that release was built with, defaults to that in URL')- parser.add_argument('--version', metavar='X.Y.Z(-ALPHA|-BETA)?',- help='Version of the release, defaults to that in URL')- parser.add_argument('--test-alternative-java', action='append',- help='Path to alternative Java home directory, to run tests with if specified')- parser.add_argument('--download-only', action='store_true', default=False,- help='Only perform download and sha hash check steps')- parser.add_argument('url', help='Url pointing to release to test')- parser.add_argument('test_args', nargs=argparse.REMAINDER,- help='Arguments to pass to gradle for testing, e.g. -Dwhat=ever.')+ """)+ description = "Utility to test a release."+ parser = argparse.ArgumentParser(description=description, epilog=epilogue, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--tmp-dir", metavar="PATH", help="Temporary directory to test inside, defaults to /tmp/smoke_lucene_$version_$revision")+ parser.add_argument("--not-signed", dest="is_signed", action="store_false", default=True, help="Indicates the release is not signed")+ parser.add_argument("--local-keys", metavar="PATH", help="Uses local KEYS file instead of fetching from https://archive.apache.org/dist/lucene/KEYS")+ parser.add_argument("--revision", help="GIT revision number that release was built with, defaults to that in URL")+ parser.add_argument("--version", metavar="X.Y.Z(-ALPHA|-BETA)?", help="Version of the release, defaults to that in URL")+ parser.add_argument("--test-alternative-java", action="append", help="Path to alternative Java home directory, to run tests with if specified")+ parser.add_argument("--download-only", action="store_true", default=False, help="Only perform download and sha hash check steps")+ parser.add_argument("url", help="Url pointing to release to test")+ parser.add_argument("test_args", nargs=argparse.REMAINDER, help="Arguments to pass to gradle for testing, e.g. -Dwhat=ever.")c = parser.parse_args()if c.version is not None:@@ -998,15 +1009,15 @@ def parse_config():else:version_match = version_re.search(c.url)if version_match is None:- parser.error('Could not find version in URL')+ parser.error("Could not find version in URL")c.version = version_match.group(1)if c.revision is None:revision_match = revision_re.search(c.url)if revision_match is None:- parser.error('Could not find revision in URL')+ parser.error("Could not find revision in URL")c.revision = revision_match.group(1)- print('Revision: %s' % c.revision)+ print("Revision: %s" % c.revision)if c.local_keys is not None and not os.path.exists(c.local_keys):parser.error('Local KEYS file "%s" not found' % c.local_keys)@@ -1016,32 +1027,34 @@ def parse_config():if c.tmp_dir:c.tmp_dir = os.path.abspath(c.tmp_dir)else:- tmp = '/tmp/smoke_lucene_%s_%s' % (c.version, c.revision)+ tmp = "/tmp/smoke_lucene_%s_%s" % (c.version, c.revision)c.tmp_dir = tmpi = 1while os.path.exists(c.tmp_dir):- c.tmp_dir = tmp + '_%d' % i+ c.tmp_dir = tmp + "_%d" % ii += 1return c-reVersion1 = re.compile(r'\>(\d+)\.(\d+)\.(\d+)(-alpha|-beta)?/\<', re.IGNORECASE)-reVersion2 = re.compile(r'-(\d+)\.(\d+)\.(\d+)(-alpha|-beta)?\.', re.IGNORECASE)++reVersion1 = re.compile(r"\>(\d+)\.(\d+)\.(\d+)(-alpha|-beta)?/\<", re.IGNORECASE)+reVersion2 = re.compile(r"-(\d+)\.(\d+)\.(\d+)(-alpha|-beta)?\.", re.IGNORECASE)+def getAllLuceneReleases():- s = load('https://archive.apache.org/dist/lucene/java')+ s = load("https://archive.apache.org/dist/lucene/java")releases = set()for r in reVersion1, reVersion2:for tup in r.findall(s):- if tup[-1].lower() == '-alpha':- tup = tup[:3] + ('0',)- elif tup[-1].lower() == '-beta':- tup = tup[:3] + ('1',)- elif tup[-1] == '':+ if tup[-1].lower() == "-alpha":+ tup = tup[:3] + ("0",)+ elif tup[-1].lower() == "-beta":+ tup = tup[:3] + ("1",)+ elif tup[-1] == "":tup = tup[:3]else:- raise RuntimeError('failed to parse version: %s' % tup[-1])+ raise RuntimeError("failed to parse version: %s" % tup[-1])releases.add(tuple(int(x) for x in tup))releaseList = list(releases)@@ -1050,39 +1063,38 @@ def getAllLuceneReleases():def confirmAllReleasesAreTestedForBackCompat(smokeVersion, unpackPath):-- print(' find all past Lucene releases...')+ print(" find all past Lucene releases...")allReleases = getAllLuceneReleases()- #for tup in allReleases:+ # for tup in allReleases:# print(' %s' % '.'.join(str(x) for x in tup))- testedIndicesPaths = glob.glob('%s/lucene/backward-codecs/src/test/org/apache/lucene/backward_index/*-cfs.zip' % unpackPath)+ testedIndicesPaths = glob.glob("%s/lucene/backward-codecs/src/test/org/apache/lucene/backward_index/*-cfs.zip" % unpackPath)testedIndices = set()- reIndexName = re.compile(r'^[^.]*.(.*?)-cfs.zip')+ reIndexName = re.compile(r"^[^.]*.(.*?)-cfs.zip")for name in testedIndicesPaths:basename = os.path.basename(name)match = reIndexName.fullmatch(basename)assert matchversion = match.group(1)- tup = tuple(version.split('.'))+ tup = tuple(version.split("."))if len(tup) == 3:# oktup = tuple(int(x) for x in tup)- elif tup == ('4', '0', '0', '1'):+ elif tup == ("4", "0", "0", "1"):# CONFUSING: this is the 4.0.0-alpha index??tup = 4, 0, 0, 0- elif tup == ('4', '0', '0', '2'):+ elif tup == ("4", "0", "0", "2"):# CONFUSING: this is the 4.0.0-beta index??tup = 4, 0, 0, 1- elif basename == 'unsupported.5x-with-4x-segments-cfs.zip':+ elif basename == "unsupported.5x-with-4x-segments-cfs.zip":# Mixed version test case; ignore it for our purposes because we only# tally up the "tests single Lucene version" indicescontinue- elif basename == 'unsupported.5.0.0.singlesegment-cfs.zip':+ elif basename == "unsupported.5.0.0.singlesegment-cfs.zip":tup = 5, 0, 0else:- raise RuntimeError('could not parse version %s' % name)+ raise RuntimeError("could not parse version %s" % name)testedIndices.add(tup)@@ -1090,7 +1102,7 @@ def confirmAllReleasesAreTestedForBackCompat(smokeVersion, unpackPath):indexList = list(testedIndices)indexList.sort()for release in indexList:- print(' %s' % '.'.join(str(x) for x in release))+ print(" %s" % ".".join(str(x) for x in release))allReleases = set(allReleases)@@ -1098,45 +1110,43 @@ def confirmAllReleasesAreTestedForBackCompat(smokeVersion, unpackPath):if x not in allReleases:# Curious: we test 1.9.0 index but it's not in the releases (I think it was pulled because of nasty bug?)if x != (1, 9, 0):- raise RuntimeError('tested version=%s but it was not released?' % '.'.join(str(y) for y in x))+ raise RuntimeError("tested version=%s but it was not released?" % ".".join(str(y) for y in x))notTested = []for x in allReleases:if x not in testedIndices:- releaseVersion = '.'.join(str(y) for y in x)- if releaseVersion in ('1.4.3', '1.9.1', '2.3.1', '2.3.2'):+ releaseVersion = ".".join(str(y) for y in x)+ if releaseVersion in ("1.4.3", "1.9.1", "2.3.1", "2.3.2"):# Exempt the dark ages indicescontinue- if x >= tuple(int(y) for y in smokeVersion.split('.')):+ if x >= tuple(int(y) for y in smokeVersion.split(".")):# Exempt versions not less than the one being smoke tested- print(' Backcompat testing not required for release %s because it\'s not less than %s'- % (releaseVersion, smokeVersion))+ print(" Backcompat testing not required for release %s because it's not less than %s" % (releaseVersion, smokeVersion))continuenotTested.append(x)if len(notTested) > 0:notTested.sort()- print('Releases that don\'t seem to be tested:')+ print("Releases that don't seem to be tested:")for x in notTested:- print(' %s' % '.'.join(str(y) for y in x))- raise RuntimeError('some releases are not tested by TestBackwardsCompatibility?')+ print(" %s" % ".".join(str(y) for y in x))+ raise RuntimeError("some releases are not tested by TestBackwardsCompatibility?")else:- print(' success!')+ print(" success!")def main():c = parse_config()# Pick <major>.<minor> part of version and require script to be from same branch- match = re.search(r'((\d+).(\d+)).(\d+)', scriptutil.find_current_version())+ match = re.search(r"((\d+).(\d+)).(\d+)", scriptutil.find_current_version())assert matchscriptVersion = match.group(1).strip()- if not c.version.startswith(scriptVersion + '.'):- raise RuntimeError('smokeTestRelease.py for %s.X is incompatible with a %s release.' % (scriptVersion, c.version))+ if not c.version.startswith(scriptVersion + "."):+ raise RuntimeError("smokeTestRelease.py for %s.X is incompatible with a %s release." % (scriptVersion, c.version))- print('NOTE: output encoding is %s' % sys.stdout.encoding)- smokeTest(c.java, c.url, c.revision, c.version, c.tmp_dir, c.is_signed, c.local_keys, ' '.join(c.test_args),- downloadOnly=c.download_only)+ print("NOTE: output encoding is %s" % sys.stdout.encoding)+ smokeTest(c.java, c.url, c.revision, c.version, c.tmp_dir, c.is_signed, c.local_keys, " ".join(c.test_args), downloadOnly=c.download_only)def smokeTest(java, baseURL, gitRevision, version, tmpDir, isSigned, local_keys, testArgs, downloadOnly=False):@@ -1146,14 +1156,14 @@ def smokeTest(java, baseURL, gitRevision, version, tmpDir, isSigned, local_keys,# important code paths. They're disabled by default to preserve a good# developer experience, but we enable them for smoke tests where we want good# coverage.- testArgs = '-Dtests.nightly=true %s' % testArgs+ testArgs = "-Dtests.nightly=true %s" % testArgs# We also enable GUI tests in smoke tests (LUCENE-10531)- testArgs = '-Dtests.gui=true %s' % testArgs+ testArgs = "-Dtests.gui=true %s" % testArgsif FORCE_CLEAN:if os.path.exists(tmpDir):- raise RuntimeError('temp dir %s exists; please remove first' % tmpDir)+ raise RuntimeError("temp dir %s exists; please remove first" % tmpDir)if not os.path.exists(tmpDir):os.makedirs(tmpDir)@@ -1163,45 +1173,44 @@ def smokeTest(java, baseURL, gitRevision, version, tmpDir, isSigned, local_keys,print('Load release URL "%s"...' % baseURL)newBaseURL = unshortenURL(baseURL)if newBaseURL != baseURL:- print(' unshortened: %s' % newBaseURL)+ print(" unshortened: %s" % newBaseURL)baseURL = newBaseURLfor text, subURL in getDirEntries(baseURL):- if text.lower().find('lucene') != -1:+ if text.lower().find("lucene") != -1:lucenePath = subURLif lucenePath is None:- raise RuntimeError('could not find lucene subdir')+ raise RuntimeError("could not find lucene subdir")print()- print('Get KEYS...')+ print("Get KEYS...")if local_keys is not None:print(" Using local KEYS file %s" % local_keys)keysFile = local_keyselse:keysFileURL = "https://archive.apache.org/dist/lucene/KEYS"print(" Downloading online KEYS file %s" % keysFileURL)- scriptutil.download('KEYS', keysFileURL, tmpDir, force_clean=FORCE_CLEAN)- keysFile = '%s/KEYS' % (tmpDir)+ scriptutil.download("KEYS", keysFileURL, tmpDir, force_clean=FORCE_CLEAN)+ keysFile = "%s/KEYS" % (tmpDir)print()- print('Test Lucene...')+ print("Test Lucene...")checkSigs(lucenePath, version, tmpDir, isSigned, keysFile)if not downloadOnly:- unpackAndVerify(java, tmpDir, 'lucene-%s.tgz' % version, gitRevision, version, testArgs)- unpackAndVerify(java, tmpDir, 'lucene-%s-src.tgz' % version, gitRevision, version, testArgs)+ unpackAndVerify(java, tmpDir, "lucene-%s.tgz" % version, gitRevision, version, testArgs)+ unpackAndVerify(java, tmpDir, "lucene-%s-src.tgz" % version, gitRevision, version, testArgs)print()- print('Test Maven artifacts...')+ print("Test Maven artifacts...")checkMaven(baseURL, tmpDir, gitRevision, version, isSigned, keysFile)else:print("\nLucene test done (--download-only specified)")- print('\nSUCCESS! [%s]\n' % (datetime.datetime.now() - startTime))+ print("\nSUCCESS! [%s]\n" % (datetime.datetime.now() - startTime))-if __name__ == '__main__':+if __name__ == "__main__":try:main()except KeyboardInterrupt:- print('Keyboard interrupt...exiting')-+ print("Keyboard interrupt...exiting")