44
55import glob
66import os
7+ import re
78import shutil
9+ import subprocess
810import sys
911
1012from contextlib import closing
13+ from distutils .spawn import find_executable
1114from tempfile import TemporaryFile
15+ from warnings import warn
1216from zipfile import ZipFile
1317
1418try :
3034
3135
3236BASE_URL = 'https://www.languagetool.org/download/'
33- FILENAME = 'LanguageTool-2.2 .zip'
37+ FILENAME = 'LanguageTool-{version} .zip'
3438PACKAGE_PATH = 'language_check'
3539
3640
@@ -53,6 +57,35 @@ class Version(LooseVersion):
5357 pass
5458
5559
60+ class InstallationError (Exception ):
61+ pass
62+
63+
64+ def get_newest_possible_languagetool_version ():
65+ java_path = find_executable ('java' )
66+ if not java_path :
67+ raise InstallationError ('Could not find Java.' )
68+
69+ output = subprocess .check_output ([java_path , '-version' ],
70+ stderr = subprocess .STDOUT ,
71+ universal_newlines = True )
72+ # http://www.oracle.com/technetwork/java/javase/versioning-naming-139433.html
73+ regex = r'^java version "(?P<major1>\d+)\.(?P<major2>\d+)\.[^"]+"$'
74+ match = re .search (regex , output , re .MULTILINE )
75+ if not match :
76+ raise InstallationError ('Could not parse Java version from """{}""".' .format (output ))
77+
78+ java_version = int (match .group ('major1' )) * 1000 + int (match .group ('major2' ))
79+ if java_version >= 1007 :
80+ return '2.7'
81+ elif java_version >= 1006 :
82+ warn ('language-check would be able to use a newer version of LanguageTool '
83+ 'if you had Java 7 or newer installed.' )
84+ return '2.2'
85+ else :
86+ raise InstallationError ('You need at least Java 6 to use language-check.' )
87+
88+
5689def get_common_prefix (z ):
5790 """Get common directory in a zip file if any."""
5891 l = z .namelist ()
@@ -72,8 +105,10 @@ def download_lt(update=False):
72105 if old_path_list and not update :
73106 return
74107
75- url = urljoin (BASE_URL , FILENAME )
76- dirname = os .path .splitext (FILENAME )[0 ]
108+ version = get_newest_possible_languagetool_version ()
109+ filename = FILENAME .format (version = version )
110+ url = urljoin (BASE_URL , filename )
111+ dirname = os .path .splitext (filename )[0 ]
77112 extract_path = os .path .join (PACKAGE_PATH , dirname )
78113
79114 if extract_path in old_path_list :
@@ -85,7 +120,7 @@ def download_lt(update=False):
85120 content_len = int (u .headers ['Content-Length' ])
86121 sys .stdout .write (
87122 'Downloading {!r} ({:.1f} MiB)...\n '
88- .format (FILENAME , content_len / 1048576. )
123+ .format (filename , content_len / 1048576. )
89124 )
90125 sys .stdout .flush ()
91126 chunk_len = content_len // 100
0 commit comments