/
another-elm
executable file
·268 lines (209 loc) · 7.82 KB
/
another-elm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
#! /usr/bin/env python3
import contextlib
import json
import os
import random
import shutil
import string
import subprocess
import sys
from pathlib import Path
another_elm_version = None # REPLACE ME
assert isinstance(another_elm_version, str)
random_suffix = None # REPLACE ME
assert isinstance(random_suffix, str)
xdg_data_home = os.environ.get(
"XDG_DATA_HOME",
Path.home() / ".local" / "share",
)
customised_dir = xdg_data_home / "another-elm" / "packages"
stub_packages = {
'bytes',
'file',
'http',
'parser',
'random',
'regex',
'time',
'url',
'virtual-dom',
}
def replace_with_stub(packages_root, author, package):
versions_dir = packages_root / author / package
try:
dirs = os.listdir(versions_dir)
except FileNotFoundError:
return
for v in dirs:
package_root = versions_dir / v
src_dir = package_root / "src"
stub_file = package_root / "stub"
elm_json_path = package_root / "elm.json"
dummy_module = "P{}".format(''.join(
[random.choice(string.ascii_letters) for n in range(32)]))
dummy_path = (src_dir / dummy_module).with_suffix(".elm")
shutil.rmtree(package_root)
os.makedirs(src_dir)
with open(stub_file, 'w'):
pass
with open(dummy_path, 'w') as f:
f.write("""module {} exposing (..)
a = 2
""".format(dummy_module))
with open(elm_json_path, 'w') as f:
json.dump(
{
"type": "package",
"name": "{}/{}".format(author, package),
"summary": "Encode and decode JSON values",
"license": "BSD-3-Clause",
"version": str(v),
"exposed-modules": [dummy_module],
"elm-version": "0.19.0 <= v < 0.20.0",
"dependencies": {
"elm/core": "1.0.0 <= v < 2.0.0"
},
"test-dependencies": {}
},
f,
indent=4)
def customize(packages_root, author, package):
versions_dir = packages_root / author / package
custom_package_dir = customised_dir / author / package
custom_src_dir = custom_package_dir / "src"
custom_json_file = custom_package_dir / "elm.json"
return customize_help(versions_dir, custom_src_dir, custom_json_file)
def customize_help(versions_dir, custom_src_dir, custom_json_file):
try:
dirs = os.listdir(versions_dir)
except FileNotFoundError:
dirs = []
any_modified = False
for v in dirs:
package_root = versions_dir / v
if not (package_root / 'custom').exists():
any_modified = True
shutil.rmtree(package_root)
package_root.mkdir()
shutil.copytree(custom_src_dir, package_root / "src")
shutil.copy(custom_json_file, package_root / "elm.json")
with open(package_root / 'custom', 'w'):
pass
return any_modified
class ElmStuff(contextlib.AbstractContextManager):
"""Move the elm-stuff/{version}/ into a temperory directory and move
elm-stuff/another/{version} to elm-stuff/{version}
When the context manager exits it will move elm-stuff/{version}/ back to
its original location (in the another sub directory) and restore the
original contents of elm-stuff/{version}/.
Elm does not allow configuration of the elm-stuff directories location, so
we resort to this hack to get a separate directory for another-elm compiler
runs.
"""
def __init__(self, version, pkg_marker):
self.elm_stuff = Path('elm-stuff')
self.workdir = self.elm_stuff / version
self.marker = self.workdir / ".marker"
another_stuff = self.elm_stuff / 'another'
self.tempdir = None
self.another_workdir = another_stuff / version
another_stuff.mkdir(exist_ok=True, parents=True)
try:
self.tempdir = self.workdir.rename(another_stuff / "tmp")
except FileNotFoundError:
pass
try:
self.another_workdir.rename(self.workdir)
except FileNotFoundError:
pass
self.__clear_if_stale(pkg_marker)
def __clear_if_stale(self, pkg_marker):
try:
stuff_mtime = self.marker.stat().st_mtime
pkg_mtime = pkg_marker.stat().st_mtime
if stuff_mtime < pkg_mtime:
self.clear()
except FileNotFoundError:
self.clear()
def __exit__(self, _0, _1, _2):
try:
self.workdir.rename(self.another_workdir)
except FileNotFoundError:
pass
if self.tempdir is not None:
self.tempdir.rename(self.workdir)
def mark(self):
try:
self.marker.touch(exist_ok=True)
except FileNotFoundError:
self.clear()
def clear(self):
try:
shutil.rmtree(self.workdir)
except FileNotFoundError:
pass
def run_elm(elm, args):
if "--stdlib-variant" in args:
print(f"another-elm {another_elm_version}")
return 0
suffix_opt = "--print-random-suffix"
if suffix_opt in args:
arg_index = args.index(suffix_opt)
if arg_index > 0 and args[arg_index - 1] == "-Z":
print(random_suffix)
return 0
else:
print(
"--print-random-suffix in an unstable option.",
file=sys.stderr,
)
print(
f"Please opt in to unstable features with -Z {suffix_opt}",
file=sys.stderr,
)
return 1
elm_home_dir = os.getenv('ELM_HOME', default=Path.home() / '.elm')
another_elm_home_dir = Path(elm_home_dir) / 'another'
custom_env = os.environ.copy()
custom_env["ELM_HOME"] = another_elm_home_dir
elm_version = subprocess.run([elm, "--version"],
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
check=True).stdout.decode("utf-8").strip()
packages_root = another_elm_home_dir / elm_version / 'packages'
packages_marker = packages_root / ".marker"
def run_compiler(**kwargs):
return subprocess.run([elm] + args, env=custom_env,
**kwargs).returncode
with ElmStuff(elm_version, packages_marker) as elm_stuff:
run_compiler(stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
another_elm_home_dir.mkdir(exist_ok=True, parents=True)
for stub_package in stub_packages:
replace_with_stub(packages_root, 'elm', stub_package)
any_customized = False
for (author, pkg) in [('elm', 'core'), ('elm', 'json'),
('elm', 'browser'), ('elm', 'html'),
('elm', 'svg'), ('elm-explorations', 'test'),
('elm-explorations', 'markdown')]:
if customize(packages_root, author, pkg):
elm_stuff.clear()
(packages_root / "registry.dat").unlink(missing_ok=True)
run_compiler(stderr=subprocess.DEVNULL,
stdout=subprocess.DEVNULL)
for author in os.scandir(packages_root):
if (author.name != "elm"
and author.name != "elm-explorations"
and author.is_dir()):
shutil.rmtree(author.path)
any_customized = True
if any_customized:
packages_marker.touch(exist_ok=True)
ret = run_compiler()
elm_stuff.mark()
return ret
if __name__ == '__main__':
args = []
if len(sys.argv) > 1:
args = sys.argv[1:]
elm = os.getenv('ELM', 'elm')
exit(run_elm(elm, args))