11import os
22import sys
3+ import re
34import subprocess
45from shutil import which
56from pathlib import Path
1011import jdk # requires install-jdk package
1112
1213
14+ mvn_repo : str
15+ homedir : Path
16+
17+
18+ def initialize_paths ():
19+ global mvn_repo , homedir
20+ homedir = Path .home ()
21+ mvn_repo = os .path .join (homedir , '.m2' , 'repository' , 'org' , 'antlr' , 'antlr4' )
22+
23+
1324def latest_version ():
14- with urlopen (f"https://search.maven.org/solrsearch/select?q=a:antlr4-master+g:org.antlr" ) as response :
15- s = response .read ().decode ("UTF-8" )
16- searchResult = json .loads (s )['response' ]
17- # searchResult = s.json()['response']
18- antlr_info = searchResult ['docs' ][0 ]
19- # print(json.dump(searchResult))
20- latest = antlr_info ['latestVersion' ]
21- return latest
25+ try :
26+ with urlopen (f"https://search.maven.org/solrsearch/select?q=a:antlr4-master+g:org.antlr" ) as response :
27+ s = response .read ().decode ("UTF-8" )
28+ searchResult = json .loads (s )['response' ]
29+ # searchResult = s.json()['response']
30+ antlr_info = searchResult ['docs' ][0 ]
31+ # print(json.dump(searchResult))
32+ latest = antlr_info ['latestVersion' ]
33+ return latest
34+ except error .URLError as e :
35+ print ("Could not get latest version number, attempting to fall back to latest downloaded version..." )
36+ version_dirs = list (filter (lambda directory : re .match (r"[0-9]+\.[0-9]+\.[0-9]+" , directory ), os .listdir (mvn_repo )))
37+ version_dirs .sort (reverse = True )
38+ if len (version_dirs ) == 0 :
39+ raise FileNotFoundError ("Could not find a previously downloaded antlr4 jar" )
40+ else :
41+ latest_version_dir = version_dirs .pop ()
42+ print (f"Found version '{ latest_version_dir } ', this version may be out of date" )
43+ return latest_version_dir
2244
2345def antlr4_jar (version ):
2446 jar = os .path .join (mvn_repo , version , f'antlr4-{ version } -complete.jar' )
@@ -77,10 +99,6 @@ def install_jre(java_version='11'):
7799
78100
79101def install_jre_and_antlr (version ):
80- global mvn_repo , homedir
81- homedir = Path .home ()
82- mvn_repo = os .path .join (homedir , '.m2' , 'repository' , 'org' , 'antlr' , 'antlr4' )
83-
84102 jar = antlr4_jar (version )
85103 java = which ("java" )
86104 if java is None :
@@ -108,6 +126,7 @@ def get_version_arg(args):
108126
109127def tool ():
110128 """Entry point to run antlr4 tool itself"""
129+ initialize_paths ()
111130 args = sys .argv [1 :]
112131 args , version = get_version_arg (args )
113132 jar , java = install_jre_and_antlr (version )
@@ -123,6 +142,7 @@ def tool():
123142
124143def interp ():
125144 """Entry point to run antlr4 profiling using grammar and input file"""
145+ initialize_paths ()
126146 args = sys .argv [1 :]
127147 args , version = get_version_arg (args )
128148 jar , java = install_jre_and_antlr (version )
0 commit comments