-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathartefact.ex
More file actions
292 lines (237 loc) · 8.34 KB
/
artefact.ex
File metadata and controls
292 lines (237 loc) · 8.34 KB
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
defmodule ElixirMake.Artefact do
@moduledoc false
alias ElixirMake.Artefact
@checksum_algo :sha256
defstruct [:basename, :checksum, :checksum_algo]
@doc """
Returns user cache directory.
"""
def cache_dir() do
cache_opts = if System.get_env("MIX_XDG"), do: %{os: :linux}, else: %{}
cache_dir =
Path.expand(
System.get_env("ELIXIR_MAKE_CACHE_DIR") ||
:filename.basedir(:user_cache, "elixir_make", cache_opts)
)
File.mkdir_p!(cache_dir)
cache_dir
end
@doc """
Returns the checksum algorithm
"""
def checksum_algo do
@checksum_algo
end
@doc """
Computes the checksum and artefact for the given contents.
"""
def checksum(basename, contents) do
hash = :crypto.hash(checksum_algo(), contents)
checksum = Base.encode16(hash, case: :lower)
%Artefact{basename: basename, checksum: checksum, checksum_algo: checksum_algo()}
end
@doc """
Writes checksum for the target to disk.
"""
def write_checksum_for_target!(%Artefact{
basename: basename,
checksum: checksum,
checksum_algo: checksum_algo
}) do
cache_dir = Artefact.cache_dir()
file = Path.join(cache_dir, "#{basename}.#{Atom.to_string(checksum_algo)}")
File.write!(file, [checksum, " ", basename, "\n"])
end
@doc """
Writes checksums to disk.
"""
def write_checksums!(checksums) do
file = checksum_file()
pairs =
Enum.map(checksums, fn
%Artefact{basename: basename, checksum: checksum, checksum_algo: algo} ->
{basename, "#{algo}:#{checksum}"}
end)
lines =
for {filename, checksum} <- Enum.sort(pairs) do
~s( "#{filename}" => "#{checksum}",\n)
end
File.write!(file, ["%{\n", lines, "}\n"])
end
defp checksum_file() do
Path.join(File.cwd!(), "checksum.exs")
end
## Archive handling
@doc """
Returns the full path to the precompiled archive.
"""
def archive_path(config, target, nif_version) do
Path.join(cache_dir(), archive_filename(config, target, nif_version))
end
defp archive_filename(config, target, nif_version) do
case config[:make_precompiler] do
{:nif, _} ->
"#{config[:app]}-nif-#{nif_version}-#{target}-#{config[:version]}.tar.gz"
{type, _} ->
"#{config[:app]}-#{type}-#{target}-#{config[:version]}.tar.gz"
end
end
@doc """
Compresses the given files and computes its checksum and artefact.
"""
def compress(archive_path, paths) do
:ok = :erl_tar.create(archive_path, paths, [:compressed])
checksum(Path.basename(archive_path), File.read!(archive_path))
end
@doc """
Verifies and decompresses the given `archive_path` at `app_priv`.
"""
def verify_and_decompress(archive_path, app_priv) do
basename = Path.basename(archive_path)
case File.read(archive_path) do
{:ok, contents} ->
verify_and_decompress(basename, archive_path, contents, app_priv)
{:error, reason} ->
{:error,
"precompiled #{inspect(basename)} does not exist or cannot download: #{inspect(reason)}"}
end
end
defp verify_and_decompress(basename, archive_path, contents, app_priv) do
checksum_file()
|> read_map_from_file()
|> case do
%{^basename => algo_with_checksum} ->
[algo, checksum] = String.split(algo_with_checksum, ":")
algo = String.to_existing_atom(algo)
case checksum(basename, contents) do
%Artefact{checksum: ^checksum, checksum_algo: ^algo} ->
case :erl_tar.extract({:binary, contents}, [:compressed, {:cwd, app_priv}]) do
:ok ->
:ok
{:error, term} ->
{:error,
"cannot decompress precompiled #{inspect(archive_path)}: #{inspect(term)}"}
end
_ ->
{:error, "precompiled #{inspect(basename)} does not match its checksum"}
end
checksum when checksum == %{} ->
{:error, "missing checksum.exs file"}
_checksum ->
{:error, "precompiled #{inspect(basename)} does not exist in checksum.exs"}
end
end
defp read_map_from_file(file) do
with {:ok, contents} <- File.read(file),
{%{} = contents, _} <- Code.eval_string(contents) do
contents
else
_ -> %{}
end
end
## Archive/NIF urls
defp nif_version_to_tuple(nif_version) do
[major, minor | _] = String.split(nif_version, ".")
{String.to_integer(major), String.to_integer(minor)}
end
defp fallback_version(opts) do
current_nif_version = "#{:erlang.system_info(:nif_version)}"
{major, minor} = nif_version_to_tuple(current_nif_version)
# Get all matching major versions, earlier than the current version
# and their distance. We want the closest (smallest distance).
candidates =
for version <- opts.versions,
{^major, candidate_minor} <- [nif_version_to_tuple(version)],
candidate_minor <= minor,
do: {minor - candidate_minor, version}
case Enum.sort(candidates) do
[{_, version} | _] -> version
_ -> current_nif_version
end
end
defp get_versions_for_target(versions, current_target) do
case versions do
version_list when is_list(version_list) ->
version_list
version_func when is_function(version_func, 1) ->
version_func.(%{target: current_target})
end
end
@doc """
Returns all available {{target, nif_version}, url} pairs available.
"""
def available_target_urls(config, precompiler) do
targets = precompiler.all_supported_targets(:fetch)
url_template =
config[:make_precompiler_url] ||
Mix.raise("`make_precompiler_url` is not specified in `project`")
current_nif_version = "#{:erlang.system_info(:nif_version)}"
nif_versions =
config[:make_precompiler_nif_versions] ||
[versions: [current_nif_version]]
Enum.reduce(targets, [], fn target, archives ->
versions = get_versions_for_target(nif_versions[:versions], target)
archive_filenames =
Enum.reduce(versions, [], fn nif_version_for_target, acc ->
availability = nif_versions[:availability]
available? =
if is_function(availability, 2) do
IO.warn(
":availability key in elixir_make is deprecated, pass a function as :versions instead"
)
availability.(target, nif_version_for_target)
else
true
end
if available? do
archive_filename = archive_filename(config, target, nif_version_for_target)
[
{{target, nif_version_for_target},
String.replace(url_template, "@{artefact_filename}", archive_filename)}
| acc
]
else
acc
end
end)
archive_filenames ++ archives
end)
end
@doc """
Returns the url for the current target.
"""
def current_target_url(config, precompiler, current_nif_version) do
case precompiler.current_target() do
{:ok, current_target} ->
nif_versions =
config[:make_precompiler_nif_versions] ||
[versions: []]
versions = get_versions_for_target(nif_versions[:versions], current_target)
nif_version_to_use =
if current_nif_version in versions do
current_nif_version
else
fallback_version = nif_versions[:fallback_version] || (&fallback_version/1)
opts = %{target: current_target, versions: versions}
fallback_version.(opts)
end
available_urls = available_target_urls(config, precompiler)
target_at_nif_version = {current_target, nif_version_to_use}
case List.keyfind(available_urls, target_at_nif_version, 0) do
{^target_at_nif_version, download_url} ->
{:ok, current_target, nif_version_to_use, download_url}
nil ->
available_targets = Enum.map(available_urls, fn {target, _url} -> target end)
{:error,
{:unavailable_target, current_target,
"cannot find download url for current target `#{inspect(current_target)}`. Available targets are: #{inspect(available_targets)}"}}
end
{:error, msg} ->
{:error, msg}
end
end
def download(config, url) do
downloader = config[:make_precompiler_downloader] || ElixirMake.Downloader.Httpc
downloader.download(url)
end
end