Skip to content

Commit 305b786

Browse files
committed
Handle common directory prefix in the LanguageTool stand-alone distribution.
Also, support downloading from alternate locations (none for now).
1 parent 20c296e commit 305b786

1 file changed

Lines changed: 34 additions & 11 deletions

File tree

‎download_lt.py‎

Lines changed: 34 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
NormalizedVersion = None
3131

3232

33-
BASE_URL = "http://www.languagetool.org/download/"
33+
BASE_URLS = ["http://www.languagetool.org/download/"]
3434
PACKAGE_PATH = "language_tool"
3535

3636

@@ -52,6 +52,15 @@ class Version(LooseVersion):
5252
pass
5353

5454

55+
def get_common_prefix(z):
56+
"""Get common directory in a zip file if any.
57+
"""
58+
l = z.namelist()
59+
if l and all(n.startswith(l[0]) for n in l[1:]):
60+
return l[0]
61+
return None
62+
63+
5564
def download_lt(update=False):
5665
assert os.path.isdir(PACKAGE_PATH)
5766
old_path_list = [
@@ -65,28 +74,36 @@ def download_lt(update=False):
6574

6675
contents = ""
6776

68-
with closing(urlopen(BASE_URL)) as u:
69-
while True:
70-
data = u.read()
71-
if not data:
72-
break
73-
contents += data.decode()
77+
for n, base_url in enumerate(BASE_URLS):
78+
try:
79+
with closing(urlopen(base_url)) as u:
80+
while True:
81+
data = u.read()
82+
if not data:
83+
break
84+
contents += data.decode()
85+
break
86+
except IOError as e:
87+
if n == len(BASE_URLS) - 1:
88+
raise
89+
else:
90+
print("{}: {}".format(base_url, e), file=sys.stderr)
7491

7592
href_format = r'<a href="(LanguageTool-(\d+.*?)\.{})">'
7693

7794
matches = [
7895
(m.group(1), Version(m.group(2))) for m in
79-
re.finditer(href_format.format("zip"), contents)
96+
re.finditer(href_format.format("zip"), contents, re.I)
8097
]
8198

8299
if not matches:
83100
matches = [
84101
(m.group(1), Version(m.group(2))) for m in
85-
re.finditer(href_format.format("oxt"), contents)
102+
re.finditer(href_format.format("oxt"), contents, re.I)
86103
]
87104

88105
filename, version = matches[-1]
89-
url = urljoin(BASE_URL, filename)
106+
url = urljoin(base_url, filename)
90107
dirname = os.path.splitext(filename)[0]
91108
extract_path = os.path.join(PACKAGE_PATH, dirname)
92109

@@ -134,7 +151,13 @@ def download_lt(update=False):
134151
if os.path.isdir(old_path):
135152
shutil.rmtree(old_path)
136153
with closing(ZipFile(t)) as z:
137-
z.extractall(extract_path)
154+
prefix = get_common_prefix(z)
155+
if prefix:
156+
z.extractall(PACKAGE_PATH)
157+
os.rename(os.path.join(PACKAGE_PATH, prefix),
158+
os.path.join(PACKAGE_PATH, dirname))
159+
else:
160+
z.extractall(extract_path)
138161

139162

140163
if __name__ == "__main__":

0 commit comments

Comments
 (0)