-
-
Notifications
You must be signed in to change notification settings - Fork 271
/
Copy pathArtifacts.jl
1028 lines (866 loc) · 37.5 KB
/
Artifacts.jl
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
module Artifacts
import Base: get, SHA1
import ..depots1, ..depots, ..set_readonly
import ..GitTools
using ..BinaryPlatforms
import ..TOML
import ..Types: parse_toml, write_env_usage
import ...Pkg: pkg_server
using ..PlatformEngines
using SHA
export create_artifact, artifact_exists, artifact_path, remove_artifact, verify_artifact,
artifact_meta, artifact_hash, bind_artifact!, unbind_artifact!, download_artifact,
find_artifacts_toml, ensure_artifact_installed, @artifact_str, archive_artifact
# keep in sync with Base.project_names and Base.manifest_names
const artifact_names = ("JuliaArtifacts.toml", "Artifacts.toml")
const ARTIFACTS_DIR_OVERRIDE = Ref{Union{String,Nothing}}(nothing)
"""
with_artifacts_directory(f::Function, artifacts_dir::String)
Helper function to allow temporarily changing the artifact installation and search
directory. When this is set, no other directory will be searched for artifacts, and new
artifacts will be installed within this directory. Similarly, removing an artifact will
only effect the given artifact directory. To layer artifact installation locations, use
the typical Julia depot path mechanism.
"""
function with_artifacts_directory(f::Function, artifacts_dir::String)
try
ARTIFACTS_DIR_OVERRIDE[] = artifacts_dir
f()
finally
ARTIFACTS_DIR_OVERRIDE[] = nothing
end
end
"""
artifacts_dirs(args...)
Return a list of paths joined into all possible artifacts directories, as dictated by the
current set of depot paths and the current artifact directory override via the method
`with_artifacts_dir()`.
"""
function artifacts_dirs(args...)
if ARTIFACTS_DIR_OVERRIDE[] === nothing
return [abspath(depot, "artifacts", args...) for depot in depots()]
else
# If we've been given an override, use _only_ that directory.
return [abspath(ARTIFACTS_DIR_OVERRIDE[], args...)]
end
end
"""
ARTIFACT_OVERRIDES
Artifact locations can be overridden by writing `Override.toml` files within the artifact
directories of Pkg depots. For example, in the default depot `~/.julia`, one may create
a `~/.julia/artifacts/Override.toml` file with the following contents:
78f35e74ff113f02274ce60dab6e92b4546ef806 = "/path/to/replacement"
c76f8cda85f83a06d17de6c57aabf9e294eb2537 = "fb886e813a4aed4147d5979fcdf27457d20aa35d"
[d57dbccd-ca19-4d82-b9b8-9d660942965b]
c_simple = "/path/to/c_simple_dir"
libfoo = "fb886e813a4aed4147d5979fcdf27457d20aa35d""
This file defines four overrides; two which override specific artifacts identified
through their content hashes, two which override artifacts based on their bound names
within a particular package's UUID. In both cases, there are two different targets of
the override: overriding to an on-disk location through an absolutet path, and
overriding to another artifact by its content-hash.
"""
const ARTIFACT_OVERRIDES = Ref{Union{Dict,Nothing}}(nothing)
function load_overrides(;force::Bool = false)
if ARTIFACT_OVERRIDES[] !== nothing && !force
return ARTIFACT_OVERRIDES[]
end
# We organize our artifact location overrides into two camps:
# - overrides per UUID with artifact names mapped to a new location
# - overrides per hash, mapped to a new location.
#
# Overrides per UUID/bound name are intercepted upon Artifacts.toml load, and new
# entries within the "hash" overrides are generated on-the-fly. Thus, all redirects
# mechanisticly happen through the "hash" overrides.
overrides = Dict(
# Overrides by UUID
:UUID => Dict{Base.UUID,Dict{String,Union{String,SHA1}}}(),
# Overrides by hash
:hash => Dict{SHA1,Union{String,SHA1}}(),
)
for override_file in reverse(artifacts_dirs("Overrides.toml"))
!isfile(override_file) && continue
# Load the toml file
depot_override_dict = parse_toml(override_file)
function parse_mapping(mapping::String, name::String)
if !isabspath(mapping) && !isempty(mapping)
try
mapping = Base.SHA1(mapping)
catch e
@error("Invalid override in '$(override_file)': entry '$(name)' must map to an absolute path or SHA1 hash!")
rethrow()
end
end
return mapping
end
function parse_mapping(mapping::Dict, name::String)
return Dict(k => parse_mapping(v, name) for (k, v) in mapping)
end
for (k, mapping) in depot_override_dict
# First, parse the mapping. Is it an absolute path, a valid SHA1-hash, or neither?
try
mapping = parse_mapping(mapping, k)
catch
@error("Invalid override in '$(override_file)': failed to parse entry `$(k)`")
continue
end
# Next, determine if this is a hash override or a UUID/name override
if isa(mapping, String) || isa(mapping, SHA1)
# if this mapping is a direct mapping (e.g. a String), store it as a hash override
hash = try
Base.SHA1(hex2bytes(k))
catch
@error("Invalid override in '$(override_file)': Invalid SHA1 hash '$(k)'")
continue
end
# If this mapping is the empty string, un-override it
if mapping == ""
delete!(overrides[:hash], hash)
else
overrides[:hash][hash] = mapping
end
elseif isa(mapping, Dict)
# Convert `k` into a uuid
uuid = try
Base.UUID(k)
catch
@error("Invalid override in '$(override_file)': Invalid UUID '$(k)'")
continue
end
# If this mapping is itself a dict, store it as a set of UUID/artifact name overrides
if !haskey(overrides[:UUID], uuid)
overrides[:UUID][uuid] = Dict{String,Union{String,SHA1}}()
end
# For each name in the mapping, update appropriately
for name in keys(mapping)
# If the mapping for this name is the empty string, un-override it
if mapping[name] == ""
delete!(overrides[:UUID][uuid], name)
else
# Otherwise, store it!
overrides[:UUID][uuid][name] = mapping[name]
end
end
end
end
end
ARTIFACT_OVERRIDES[] = overrides
end
# Helpers to map an override to an actual path
map_override_path(x::String) = x
map_override_path(x::SHA1) = artifact_path(x)
map_override_path(x::Nothing) = nothing
"""
query_override(hash::SHA1; overrides::Dict = load_overrides())
Query the loaded `<DEPOT>/artifacts/Overrides.toml` settings for artifacts that should be
redirected to a particular path or another content-hash.
"""
function query_override(hash::SHA1; overrides::Dict = load_overrides())
return map_override_path(get(overrides[:hash], hash, nothing))
end
function query_override(pkg::Base.UUID, artifact_name::String; overrides::Dict = load_overrides())
if haskey(overrides[:UUID], pkg)
return map_override_path(get(overrides[:UUID][pkg], artifact_name, nothing))
end
return nothing
end
"""
create_artifact(f::Function)
Creates a new artifact by running `f(artifact_path)`, hashing the result, and moving it
to the artifact store (`~/.julia/artifacts` on a typical installation). Returns the
identifying tree hash of this artifact.
!!! compat "Julia 1.3"
This function requires at least Julia 1.3.
"""
function create_artifact(f::Function)
# Ensure the `artifacts` directory exists in our default depot
artifacts_dir = first(artifacts_dirs())
mkpath(artifacts_dir)
# Temporary directory where we'll do our creation business
temp_dir = mktempdir(artifacts_dir)
try
# allow the user to do their work inside the temporary directory
f(temp_dir)
# Calculate the tree hash for this temporary directory
artifact_hash = SHA1(GitTools.tree_hash(temp_dir))
# If we created a dupe, just let the temp directory get destroyed. It's got the
# same contents as whatever already exists after all, so it doesn't matter. Only
# move its contents if it actually contains new contents. Note that we explicitly
# set `honor_overrides=false` here, as we wouldn't want to drop things into the
# system directory by accidentally creating something with the same content-hash
# as something that was foolishly overridden. This should be virtually impossible
# unless the user has been very unwise, but let's be cautious.
new_path = artifact_path(artifact_hash; honor_overrides=false)
if !isdir(new_path)
# Move this generated directory to its final destination, set it to read-only
mv(temp_dir, new_path)
set_readonly(new_path)
end
# Give the people what they want
return artifact_hash
finally
# Always attempt to cleanup
rm(temp_dir; recursive=true, force=true)
end
end
"""
artifact_paths(hash::SHA1; honor_overrides::Bool=true)
Return all possible paths for an artifact given the current list of depots as returned
by `Pkg.depots()`. All, some or none of these paths may exist on disk.
"""
function artifact_paths(hash::SHA1; honor_overrides::Bool=true)
# First, check to see if we've got an override:
if honor_overrides
override = query_override(hash)
if override !== nothing
return [override]
end
end
return artifacts_dirs(bytes2hex(hash.bytes))
end
"""
artifact_path(hash::SHA1; honor_overrides::Bool=true)
Given an artifact (identified by SHA1 git tree hash), return its installation path. If
the artifact does not exist, returns the location it would be installed to.
!!! compat "Julia 1.3"
This function requires at least Julia 1.3.
"""
function artifact_path(hash::SHA1; honor_overrides::Bool=true)
# Get all possible paths (rooted in all depots)
possible_paths = artifact_paths(hash; honor_overrides=honor_overrides)
# Find the first path that exists and return it
for p in possible_paths
if isdir(p)
return p
end
end
# If none exist, then just return the one that would exist within `depots1()`.
return first(possible_paths)
end
"""
artifact_exists(hash::SHA1; honor_overrides::Bool=true)
Returns whether or not the given artifact (identified by its sha1 git tree hash) exists
on-disk. Note that it is possible that the given artifact exists in multiple locations
(e.g. within multiple depots).
!!! compat "Julia 1.3"
This function requires at least Julia 1.3.
"""
function artifact_exists(hash::SHA1; honor_overrides::Bool=true)
return any(isdir.(artifact_paths(hash; honor_overrides=honor_overrides)))
end
"""
remove_artifact(hash::SHA1; honor_overrides::Bool=false)
Removes the given artifact (identified by its SHA1 git tree hash) from disk. Note that
if an artifact is installed in multiple depots, it will be removed from all of them. If
an overridden artifact is requested for removal, it will be silently ignored; this method
will never attempt to remove an overridden artifact.
In general, we recommend that you use `Pkg.gc()` to manage artifact installations and do
not use `remove_artifact()` directly, as it can be difficult to know if an artifact is
being used by another package.
!!! compat "Julia 1.3"
This function requires at least Julia 1.3.
"""
function remove_artifact(hash::SHA1)
if query_override(hash) !== nothing
# We never remove overridden artifacts.
return
end
# Get all possible paths (rooted in all depots)
possible_paths = artifacts_dirs(bytes2hex(hash.bytes))
for path in possible_paths
if isdir(path)
rm(path; recursive=true, force=true)
end
end
end
"""
verify_artifact(hash::SHA1; honor_overrides::Bool=false)
Verifies that the given artifact (identified by its SHA1 git tree hash) is installed on-
disk, and retains its integrity. If the given artifact is overridden, skips the
verification unless `honor_overrides` is set to `true`.
!!! compat "Julia 1.3"
This function requires at least Julia 1.3.
"""
function verify_artifact(hash::SHA1; honor_overrides::Bool=false)
# Silently skip overridden artifacts unless we really ask for it
if !honor_overrides
if query_override(hash) !== nothing
return true
end
end
# If it doesn't even exist, then skip out
if !artifact_exists(hash)
return false
end
# Otherwise actually run the verification
return hash.bytes == GitTools.tree_hash(artifact_path(hash))
end
"""
archive_artifact(hash::SHA1, tarball_path::String; honor_overrides::Bool=false)
Archive an artifact into a tarball stored at `tarball_path`, returns the SHA256 of the
resultant tarball as a hexidecimal string. Throws an error if the artifact does not
exist. If the artifact is overridden, throws an error unless `honor_overrides` is set.
!!! compat "Julia 1.3"
This function requires at least Julia 1.3.
"""
function archive_artifact(hash::SHA1, tarball_path::String; honor_overrides::Bool=false)
if !honor_overrides
if query_override(hash) !== nothing
error("Will not archive an overridden artifact unless `honor_overrides` is set!")
end
end
if !artifact_exists(hash)
error("Unable to archive artifact $(bytes2hex(hash.bytes)): does not exist!")
end
probe_platform_engines!()
# Package it up
package(artifact_path(hash), tarball_path)
# Calculate its sha256 and return that
return open(tarball_path, "r") do io
return bytes2hex(sha256(io))
end
end
"""
unpack_platform(entry::Dict, name::String, artifacts_toml::String)
Given an `entry` for the artifact named `name`, located within the file `artifacts_toml`,
returns the `Platform` object that this entry specifies. Returns `nothing` on error.
"""
function unpack_platform(entry::Dict, name::String, artifacts_toml::String)
if !haskey(entry, "os")
@error("Invalid artifacts file at '$(artifacts_toml)': platform-specific artifact entry '$name' missing 'os' key")
return nothing
end
if !haskey(entry, "arch")
@error("Invalid artifacts file at '$(artifacts_toml)': platform-specific artifact entrty '$name' missing 'arch' key")
return nothing
end
# Helpers to pull out `Symbol`s and `VersionNumber`s while preserving `nothing`.
nosym(x::Nothing) = nothing
nosym(x) = Symbol(lowercase(x))
nover(x::Nothing) = nothing
nover(x) = VersionNumber(x)
# First, extract OS; we need to build a mapping here
os_map = Dict(
"windows" => Windows,
"macos" => MacOS,
"freebsd" => FreeBSD,
"linux" => Linux,
)
P = get(os_map, lowercase(entry["os"]), UnknownPlatform)
# Next, architecture, libc, libgfortran version and cxxabi (if given)
arch = nosym(get(entry, "arch", nothing))
libc = nosym(get(entry, "libc", nothing))
libgfortran_version = nover(get(entry, "libgfortran_version", nothing))
libstdcxx_version = nover(get(entry, "libstdcxx_version", nothing))
cxxstring_abi = nosym(get(entry, "cxxstring_abi", nothing))
# Construct the actual Platform object
return P(arch;
libc=libc,
compiler_abi=CompilerABI(
libgfortran_version=libgfortran_version,
libstdcxx_version=libstdcxx_version,
cxxstring_abi=cxxstring_abi
),
)
end
function pack_platform!(meta::Dict, p::Platform)
os_map = Dict(
Windows => "windows",
MacOS => "macos",
FreeBSD => "freebsd",
Linux => "linux",
)
meta["os"] = os_map[typeof(p)]
meta["arch"] = string(arch(p))
if libc(p) !== nothing
meta["libc"] = string(libc(p))
end
if libgfortran_version(p) !== nothing
meta["libgfortran_version"] = string(libgfortran_version(p))
end
if libstdcxx_version(p) !== nothing
meta["libstdcxx_version"] = string(libstdcxx_version(p))
end
if cxxstring_abi(p) !== nothing
meta["cxxstring_abi"] = string(cxxstring_abi(p))
end
end
"""
load_artifacts_toml(artifacts_toml::String;
pkg_uuid::Union{UUID,Nothing}=nothing)
Loads an `(Julia)Artifacts.toml` file from disk. If `pkg_uuid` is set to the `UUID` of the
owning package, UUID/name overrides stored in a depot `Overrides.toml` will be resolved.
"""
function load_artifacts_toml(artifacts_toml::String;
pkg_uuid::Union{Base.UUID,Nothing} = nothing)
artifact_dict = parse_toml(artifacts_toml)
# Process overrides for this `pkg_uuid`
process_overrides(artifact_dict, pkg_uuid)
return artifact_dict
end
"""
process_overrides(artifact_dict::Dict, pkg_uuid::Base.UUID)
When loading an `Artifacts.toml` file, we must check `Override.toml` files to see if any
of the artifacts within it have been overridden by UUID. If they have, we honor the
overrides by inspecting the hashes of the targeted artifacts, then overriding them to
point to the given override, punting the actual redirection off to the hash-based
override system. This does not modify the `artifact_dict` object, it merely dynamically
adds more hash-based overrides as `Artifacts.toml` files that are overridden are loaded.
"""
function process_overrides(artifact_dict::Dict, pkg_uuid::Base.UUID)
# Insert just-in-time hash overrides by looking up the names of anything we need to
# override for this UUID, and inserting new overrides for those hashes.
overrides = load_overrides()
if haskey(overrides[:UUID], pkg_uuid)
pkg_overrides = overrides[:UUID][pkg_uuid]
for name in keys(artifact_dict)
# Skip names that we're not overriding
if !haskey(pkg_overrides, name)
continue
end
# If we've got a platform-specific friend, override all hashes:
if isa(artifact_dict[name], Array)
for entry in artifact_dict[name]
hash = SHA1(entry["git-tree-sha1"])
overrides[:hash][hash] = overrides[:UUID][pkg_uuid][name]
end
elseif isa(artifact_dict[name], Dict)
hash = SHA1(artifact_dict[name]["git-tree-sha1"])
overrides[:hash][hash] = overrides[:UUID][pkg_uuid][name]
end
end
end
return artifact_dict
end
# If someone tries to call process_overrides() with `nothing`, do exactly that
process_overrides(artifact_dict::Dict, pkg_uuid::Nothing) = nothing
"""
artifact_meta(name::String, artifacts_toml::String;
platform::Platform = platform_key_abi(),
pkg_uuid::Union{Base.UUID,Nothing}=nothing)
Get metadata about a given artifact (identified by name) stored within the given
`(Julia)Artifacts.toml` file. If the artifact is platform-specific, use `platform` to choose the
most appropriate mapping. If none is found, return `nothing`.
!!! compat "Julia 1.3"
This function requires at least Julia 1.3.
"""
function artifact_meta(name::String, artifacts_toml::String;
platform::Platform = platform_key_abi(),
pkg_uuid::Union{Base.UUID,Nothing}=nothing)
if !isfile(artifacts_toml)
return nothing
end
# Parse the toml of the artifacts_toml file
artifact_dict = load_artifacts_toml(artifacts_toml; pkg_uuid=pkg_uuid)
return artifact_meta(name, artifact_dict, artifacts_toml; platform=platform)
end
function artifact_meta(name::String, artifact_dict::Dict, artifacts_toml::String;
platform::Platform = platform_key_abi())
if !haskey(artifact_dict, name)
return nothing
end
meta = artifact_dict[name]
# If it's an array, find the entry that best matches our current platform
if isa(meta, Array)
dl_dict = Dict(unpack_platform(x, name, artifacts_toml) => x for x in meta)
meta = select_platform(dl_dict, platform)
# If it's NOT a dict, complain
elseif !isa(meta, Dict)
@error("Invalid artifacts file at $(artifacts_toml): artifact '$name' malformed, must be array or dict!")
return nothing
end
# This is such a no-no, we are going to call it out right here, right now.
if meta !== nothing && !haskey(meta, "git-tree-sha1")
@error("Invalid artifacts file at $(artifacts_toml): artifact '$name' contains no `git-tree-sha1`!")
return nothing
end
# Return the full meta-dict.
return meta
end
"""
artifact_hash(name::String, artifacts_toml::String; platform::Platform = platform_key_abi())
Thin wrapper around `artifact_meta()` to return the hash of the specified, platform-
collapsed artifact. Returns `nothing` if no mapping can be found.
!!! compat "Julia 1.3"
This function requires at least Julia 1.3.
"""
function artifact_hash(name::String, artifacts_toml::String;
platform::Platform = platform_key_abi(),
pkg_uuid::Union{Base.UUID,Nothing}=nothing)
meta = artifact_meta(name, artifacts_toml; platform=platform)
if meta === nothing
return nothing
end
return SHA1(meta["git-tree-sha1"])
end
"""
bind_artifact!(artifacts_toml::String, name::String, hash::SHA1;
platform::Union{Platform,Nothing} = nothing,
download_info::Union{Vector{Tuple},Nothing} = nothing,
lazy::Bool = false,
force::Bool = false)
Writes a mapping of `name` -> `hash` within the given `(Julia)Artifacts.toml` file. If
`platform` is not `nothing`, this artifact is marked as platform-specific, and will be
a multi-mapping. It is valid to bind multiple artifacts with the same name, but
different `platform`s and `hash`'es within the same `artifacts_toml`. If `force` is set
to `true`, this will overwrite a pre-existant mapping, otherwise an error is raised.
`download_info` is an optional tuple that contains a vector of URLs and a hash. These
URLs will be listed as possible locations where this artifact can be obtained. If `lazy`
is set to `true`, even if download information is available, this artifact will not be
downloaded until it is accessed via the `artifact"name"` syntax, or
`ensure_artifact_installed()` is called upon it.
!!! compat "Julia 1.3"
This function requires at least Julia 1.3.
"""
function bind_artifact!(artifacts_toml::String, name::String, hash::SHA1;
platform::Union{Platform,Nothing} = nothing,
download_info::Union{Vector{<:Tuple},Nothing} = nothing,
lazy::Bool = false,
force::Bool = false)
# First, check to see if this artifact is already bound:
if isfile(artifacts_toml)
artifact_dict = parse_toml(artifacts_toml)
if !force && haskey(artifact_dict, name)
meta = artifact_dict[name]
if !isa(meta, Array)
error("Mapping for '$name' within $(artifacts_toml) already exists!")
elseif any((unpack_platform(x, name, artifacts_toml) for x in meta) .== Ref(platform))
error("Mapping for '$name'/$(triplet(platform)) within $(artifacts_toml) already exists!")
end
end
else
artifact_dict = Dict()
end
# Otherwise, the new piece of data we're going to write out is this dict:
meta = Dict{String,Any}(
"git-tree-sha1" => bytes2hex(hash.bytes),
)
# If we're set to be lazy, then lazy we shall be
if lazy
meta["lazy"] = true
end
# Integrate download info, if it is given. We represent the download info as a
# vector of dicts, each with its own `url` and `sha256`, since different tarballs can
# expand to the same tree hash.
if download_info !== nothing
meta["download"] = [
Dict("url" => dl[1],
"sha256" => dl[2],
) for dl in download_info
]
end
if platform === nothing
artifact_dict[name] = meta
else
# Add platform-specific keys to our `meta` dict
pack_platform!(meta, platform)
# Insert this entry into the list of artifacts
if !haskey(artifact_dict, name)
artifact_dict[name] = [meta]
else
# Delete any entries that contain identical platforms
artifact_dict[name] = filter(
x -> unpack_platform(x, name, artifacts_toml) != platform,
artifact_dict[name]
)
push!(artifact_dict[name], meta)
end
end
# Spit it out onto disk
open(artifacts_toml, "w") do io
TOML.print(io, artifact_dict, sorted=true)
end
# Mark that we have used this Artifact.toml
write_env_usage(artifacts_toml, "artifact_usage.toml")
return
end
"""
unbind_artifact!(artifacts_toml::String, name::String; platform = nothing)
Unbind the given `name` from an `(Julia)Artifacts.toml` file.
Silently fails if no such binding exists within the file.
!!! compat "Julia 1.3"
This function requires at least Julia 1.3.
"""
function unbind_artifact!(artifacts_toml::String, name::String;
platform::Union{Platform,Nothing} = nothing)
artifact_dict = parse_toml(artifacts_toml)
if !haskey(artifact_dict, name)
return
end
if platform === nothing
delete!(artifact_dict, name)
else
artifact_dict[name] = filter(
x -> unpack_platform(x, name, artifacts_toml) != platform,
artifact_dict[name]
)
end
open(artifacts_toml, "w") do io
TOML.print(io, artifact_dict, sorted=true)
end
return
end
"""
download_artifact(tree_hash::SHA1, tarball_url::String, tarball_hash::String;
verbose::Bool = false)
Download/install an artifact into the artifact store. Returns `true` on success.
!!! compat "Julia 1.3"
This function requires at least Julia 1.3.
"""
function download_artifact(
tree_hash::SHA1,
tarball_url::String,
tarball_hash::Union{String, Nothing} = nothing;
verbose::Bool = false,
)
if artifact_exists(tree_hash)
return true
end
# Ensure that we're ready to download things
probe_platform_engines!()
if Sys.iswindows()
# The destination directory we're hoping to fill:
dest_dir = artifact_path(tree_hash; honor_overrides=false)
# On Windows, we have some issues around stat() and chmod() that make properly
# determining the git tree hash problematic; for this reason, we use the "unsafe"
# artifact unpacking method, which does not properly verify unpacked git tree
# hash. This will be fixed in a future Julia release which will properly interrogate
# the filesystem ACLs for executable permissions, which git tree hashes care about.
try
download_verify_unpack(tarball_url, tarball_hash, dest_dir, ignore_existence=true, verbose=verbose)
catch e
# Clean that destination directory out if something went wrong
rm(dest_dir; force=true, recursive=true)
if isa(e, InterruptException)
rethrow(e)
end
return false
end
else
# We download by using `create_artifact()`. We do this because the download may
# be corrupted or even malicious; we don't want to clobber someone else's artifact
# by trusting the tree hash that has been given to us; we will instead download it
# to a temporary directory, calculate the true tree hash, then move it to the proper
# location only after knowing what it is, and if something goes wrong in the process,
# everything should be cleaned up. Luckily, that is precisely what our
# `create_artifact()` wrapper does, so we use that here.
calc_hash = try
create_artifact() do dir
download_verify_unpack(tarball_url, tarball_hash, dir, ignore_existence=true, verbose=verbose)
end
catch e
if isa(e, InterruptException)
rethrow(e)
end
# If something went wrong during download, return false
return false
end
# Did we get what we expected? If not, freak out.
if calc_hash.bytes != tree_hash.bytes
msg = "Tree Hash Mismatch!\n"
msg *= " Expected git-tree-sha1: $(bytes2hex(tree_hash.bytes))\n"
msg *= " Calculated git-tree-sha1: $(bytes2hex(calc_hash.bytes))"
@error(msg)
return false
end
end
return true
end
"""
find_artifacts_toml(path::String)
Given the path to a `.jl` file, (such as the one returned by `__source__.file` in a macro
context), find the `(Julia)Artifacts.toml` that is contained within the containing project (if it
exists), otherwise return `nothing`.
!!! compat "Julia 1.3"
This function requires at least Julia 1.3.
"""
function find_artifacts_toml(path::String)
if !isdir(path)
path = dirname(path)
end
# Run until we hit the root directory.
while dirname(path) != path
for f in artifact_names
artifacts_toml_path = joinpath(path, f)
if isfile(artifacts_toml_path)
return abspath(artifacts_toml_path)
end
end
# Does a `(Julia)Project.toml` file exist here, in the absence of an Artifacts.toml?
# If so, stop the search as we've probably hit the top-level of this package,
# and we don't want to escape out into the larger filesystem.
for f in Base.project_names
if isfile(joinpath(path, f))
return nothing
end
end
# Move up a directory
path = dirname(path)
end
# We never found anything, just return `nothing`
return nothing
end
"""
ensure_artifact_installed(name::String, artifacts_toml::String;
platform::Platform = platform_key_abi(),
pkg_uuid::Union{Base.UUID,Nothing}=nothing)
Ensures an artifact is installed, downloading it via the download information stored in
`artifacts_toml` if necessary. Throws an error if unable to install.
!!! compat "Julia 1.3"
This function requires at least Julia 1.3.
"""
function ensure_artifact_installed(name::String, artifacts_toml::String;
platform::Platform = platform_key_abi(),
pkg_uuid::Union{Base.UUID,Nothing}=nothing,
verbose::Bool = false)
meta = artifact_meta(name, artifacts_toml; pkg_uuid=pkg_uuid, platform=platform)
if meta === nothing
error("Cannot locate artifact '$(name)' in '$(artifacts_toml)'")
end
return ensure_artifact_installed(name, meta, artifacts_toml; platform=platform, verbose=verbose)
end
function ensure_artifact_installed(name::String, meta::Dict, artifacts_toml::String;
platform::Platform = platform_key_abi(),
verbose::Bool = false)
hash = SHA1(meta["git-tree-sha1"])
if !artifact_exists(hash)
# first try downloading from Pkg server
# TODO: only do this if Pkg server knows about this package
if (server = pkg_server()) !== nothing
url = "$server/artifact/$hash"
if download_artifact(hash, url)
return artifact_path(hash)
end
end
# If this artifact does not exist on-disk already, ensure it has download
# information, then download it!
if !haskey(meta, "download")
error("Cannot automatically install '$(name)'; no download section in '$(artifacts_toml)'")
end
# Attempt to download from all sources
for entry in meta["download"]
url = entry["url"]
tarball_hash = entry["sha256"]
if download_artifact(hash, url, tarball_hash; verbose=verbose)
return artifact_path(hash)
end
end
error("Unable to automatically install '$(name)' from '$(artifacts_toml)'")
else
return artifact_path(hash)
end
end
"""
ensure_all_artifacts_installed(artifacts_toml::String;
platform = platform_key_abi(),
pkg_uuid = nothing,
include_lazy = false,
verbose = false)
Installs all non-lazy artifacts from a given `(Julia)Artifacts.toml` file. `package_uuid` must
be provided to properly support overrides from `Overrides.toml` entries in depots.
If `include_lazy` is set to `true`, then lazy packages will be installed as well.
!!! compat "Julia 1.3"
This function requires at least Julia 1.3.
"""
function ensure_all_artifacts_installed(artifacts_toml::String;
platform::Platform = platform_key_abi(),
pkg_uuid::Union{Nothing,Base.UUID} = nothing,
include_lazy::Bool = false,
verbose::Bool = false)
if !isfile(artifacts_toml)
return
end
artifact_dict = load_artifacts_toml(artifacts_toml; pkg_uuid=pkg_uuid)
for name in keys(artifact_dict)
# Get the metadata about this name for the requested platform
meta = artifact_meta(name, artifact_dict, artifacts_toml; platform=platform)
# If there are no instances of this name for the desired platform, skip it
meta === nothing && continue
# If this mapping doesn't have a `download` stanza or is lazy, skip it
if !haskey(meta, "download") || (get(meta, "lazy", false) && !include_lazy)
continue
end
# Otherwise, let's try and install it!
ensure_artifact_installed(name, meta, artifacts_toml; platform=platform, verbose=verbose)
end
end
"""
extract_all_hashes(artifacts_toml::String;
platform = platform_key_abi(),
pkg_uuid = nothing,
include_lazy = false)
Extract all hashes from a given `(Julia)Artifacts.toml` file. `package_uuid` must
be provided to properly support overrides from `Overrides.toml` entries in depots.
If `include_lazy` is set to `true`, then lazy packages will be installed as well.
"""
function extract_all_hashes(artifacts_toml::String;
platform::Platform = platform_key_abi(),
pkg_uuid::Union{Nothing,Base.UUID} = nothing,
include_lazy::Bool = false)
hashes = Base.SHA1[]
if !isfile(artifacts_toml)
return hashes
end
artifact_dict = load_artifacts_toml(artifacts_toml; pkg_uuid=pkg_uuid)
for name in keys(artifact_dict)
# Get the metadata about this name for the requested platform
meta = artifact_meta(name, artifact_dict, artifacts_toml; platform=platform)
# If there are no instances of this name for the desired platform, skip it
meta === nothing && continue
# If it's a lazy one and we aren't including lazy ones, skip
if get(meta, "lazy", false) && !include_lazy
continue
end
# Otherwise, add it to the list!
push!(hashes, Base.SHA1(meta["git-tree-sha1"]))
end
return hashes
end
function do_artifact_str(name, artifact_dict, artifacts_toml, __module__)
local pkg_uuid = nothing
if haskey(Base.module_keys, __module__)
# Process overrides for this UUID, if we know what it is
process_overrides(artifact_dict, Base.module_keys[__module__].uuid)
end
# Get platform once to avoid extra work
platform = platform_key_abi()
# Get the metadata about this name for the requested platform
meta = artifact_meta(name, artifact_dict, artifacts_toml; platform=platform)
if meta === nothing
error("Cannot locate artifact '$(name)' in '$(artifacts_toml)'")
end
# This is the resultant value at the end of all things
return ensure_artifact_installed(name, meta, artifacts_toml; platform=platform)
end
"""
macro artifact_str(name)
Macro that is used to automatically ensure an artifact is installed, and return its
location on-disk. Automatically looks the artifact up by name in the project's
`(Julia)Artifacts.toml` file. Throws an error on inability to install the requested artifact.
!!! compat "Julia 1.3"
This macro requires at least Julia 1.3.