-
-
Notifications
You must be signed in to change notification settings - Fork 269
/
Copy pathOperations.jl
1376 lines (1264 loc) · 51.8 KB
/
Operations.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
# This file is a part of Julia. License is MIT: https://julialang.org/license
module Operations
using UUIDs
using Random: randstring
import LibGit2
import REPL
using REPL.TerminalMenus
using ..Types, ..GraphType, ..Resolve, ..Pkg2, ..PlatformEngines, ..GitTools, ..Display
import ..depots, ..depots1, ..devdir, ..Types.uuid_julia, ..Types.PackageEntry
import ..Artifacts: ensure_all_artifacts_installed, artifact_names, extract_all_hashes, artifact_exists
using ..BinaryPlatforms
import ..Pkg
#########
# Utils #
#########
function find_installed(name::String, uuid::UUID, sha1::SHA1)
slug_default = Base.version_slug(uuid, sha1)
# 4 used to be the default so look there first
for slug in (Base.version_slug(uuid, sha1, 4), slug_default)
for depot in depots()
path = abspath(depot, "packages", name, slug)
ispath(path) && return path
end
end
return abspath(depots1(), "packages", name, slug_default)
end
# more accurate name is `should_be_tracking_registered_version`
# the only way to know for sure is to key into the registries
tracking_registered_version(pkg) =
!is_stdlib(pkg.uuid) && pkg.path === nothing && pkg.repo.url === nothing
function source_path(pkg::PackageSpec)
return is_stdlib(pkg.uuid) ? Types.stdlib_path(pkg.name) :
pkg.path !== nothing ? pkg.path :
pkg.repo.url !== nothing ? find_installed(pkg.name, pkg.uuid, pkg.tree_hash) :
pkg.tree_hash !== nothing ? find_installed(pkg.name, pkg.uuid, pkg.tree_hash) :
nothing
end
is_dep(env::EnvCache, pkg::PackageSpec) =
any(uuid -> uuid == pkg.uuid, [uuid for (name, uuid) in env.project.deps])
function load_direct_deps!(ctx::Context, pkgs::Vector{PackageSpec}; version::Bool=true)
# load rest of deps normally
for (name::String, uuid::UUID) in ctx.env.project.deps
pkgs[uuid] === nothing || continue # dont duplicate packages
entry = manifest_info(ctx.env, uuid)
push!(pkgs, entry === nothing ?
PackageSpec(;uuid=uuid, name=name) :
PackageSpec(;
uuid = uuid,
name = name,
path = entry.path,
repo = entry.repo,
tree_hash = entry.tree_hash,
pinned = entry.pinned,
version = version ? something(entry.version, VersionSpec()) : VersionSpec()))
end
end
function load_all_deps!(ctx::Context, pkgs::Vector{PackageSpec}; version::Bool=true)
for (uuid, entry) in ctx.env.manifest
push!(pkgs, PackageSpec(name=entry.name, uuid=uuid, path=entry.path,
version = version ? something(entry.version, VersionSpec()) : VersionSpec(),
repo=entry.repo, tree_hash=entry.tree_hash))
end
load_direct_deps!(ctx, pkgs; version=version)
end
function is_instantiated(ctx::Context)::Bool
# Load everything
pkgs = PackageSpec[]
Operations.load_all_deps!(ctx, pkgs)
# Make sure all paths exist
for pkg in pkgs
sourcepath = Operations.source_path(pkg)
isdir(sourcepath) || return false
check_artifacts_downloaded(sourcepath) || return false
end
return true
end
function update_manifest!(ctx::Context, pkgs::Vector{PackageSpec})
manifest = ctx.env.manifest
empty!(manifest)
#find_registered!(ctx.env, [pkg.uuid for pkg in pkgs]) # Is this necessary? its for `load_deps`...
for pkg in pkgs
entry = PackageEntry(;name = pkg.name, version = pkg.version, pinned = pkg.pinned,
tree_hash = pkg.tree_hash, path = pkg.path, repo = pkg.repo)
is_stdlib(pkg.uuid) && (entry.version = nothing) # do not set version for stdlibs
entry.deps = load_deps(ctx, pkg)
ctx.env.manifest[pkg.uuid] = entry
end
end
####################
# Registry Loading #
####################
function load_package_data(f::Base.Callable, path::String, versions)
toml = parse_toml(path, fakeit=true)
data = Dict{VersionNumber,Dict{String,Any}}()
for ver in versions
ver::VersionNumber
for (v, d) in toml, (key, value) in d
vr = VersionRange(v)
ver in vr || continue
dict = get!(data, ver, Dict{String,Any}())
haskey(dict, key) && pkgerror("$ver/$key is duplicated in $path")
dict[key] = f(value)
end
end
return data
end
load_package_data(f::Base.Callable, path::String, version::VersionNumber) =
get(load_package_data(f, path, [version]), version, nothing)
function load_package_data_raw(T::Type, path::String)
toml = parse_toml(path, fakeit=true)
data = Dict{VersionRange,Dict{String,T}}()
for (v, d) in toml, (key, value) in d
vr = VersionRange(v)
dict = get!(data, vr, Dict{String,T}())
haskey(dict, key) && pkgerror("$vr/$key is duplicated in $path")
dict[key] = T(value)
end
return data
end
function load_versions(path::String; include_yanked = false)
toml = parse_toml(path, "Versions.toml"; fakeit=true)
return Dict{VersionNumber, SHA1}(
VersionNumber(ver) => SHA1(info["git-tree-sha1"]) for (ver, info) in toml
if !get(info, "yanked", false) || include_yanked)
end
function load_tree_hash(ctx::Context, pkg::PackageSpec)
hashes = SHA1[]
for path in registered_paths(ctx.env, pkg.uuid)
vers = load_versions(path; include_yanked = true)
hash = get(vers, pkg.version, nothing)
hash !== nothing && push!(hashes, hash)
end
isempty(hashes) && return nothing
length(unique!(hashes)) == 1 || pkgerror("hash mismatch")
return hashes[1]
end
function load_tree_hashes!(ctx::Context, pkgs::Vector{PackageSpec})
for pkg in pkgs
tracking_registered_version(pkg) || continue
pkg.tree_hash = load_tree_hash(ctx, pkg)
end
end
#######################################
# Dependency gathering and resolution #
#######################################
include("backwards_compatible_isolation.jl")
function set_maximum_version_registry!(env::EnvCache, pkg::PackageSpec)
pkgversions = Set{VersionNumber}()
for path in registered_paths(env, pkg.uuid)
pathvers = keys(load_versions(path; include_yanked = false))
union!(pkgversions, pathvers)
end
if length(pkgversions) == 0
pkg.version = VersionNumber(0)
else
max_version = maximum(pkgversions)
pkg.version = VersionNumber(max_version.major, max_version.minor, max_version.patch, max_version.prerelease, ("",))
end
end
function load_deps(ctx::Context, pkg::PackageSpec)::Dict{String,UUID}
if tracking_registered_version(pkg)
for path in registered_paths(ctx.env, pkg.uuid)
data = load_package_data(UUID, joinpath(path, "Deps.toml"), pkg.version)
data !== nothing && return data
end
return Dict{String,UUID}()
else
path = project_rel_path(ctx, source_path(pkg))
project_file = projectfile_path(path; strict=true)
if project_file !== nothing
project = read_project(project_file)
return project.deps
else
# Check in REQUIRE file
# Remove when packages uses Project files properly
deps = Dict{String,UUID}()
dep_pkgs = PackageSpec[]
stdlib_deps = find_stdlib_deps(ctx, path)
for (uuid, name) in stdlib_deps
push!(dep_pkgs, PackageSpec(name, uuid))
end
reqfile = joinpath(path, "REQUIRE")
if isfile(reqfile)
for r in Pkg2.Reqs.read(reqfile)
r isa Pkg2.Reqs.Requirement || continue
push!(dep_pkgs, PackageSpec(name=r.package))
end
registry_resolve!(ctx.env, dep_pkgs)
project_deps_resolve!(ctx.env, dep_pkgs)
ensure_resolved(ctx.env, dep_pkgs; registry=true)
end
for dep_pkg in dep_pkgs
dep_pkg.name == "julia" && continue
deps[dep_pkg.name] = dep_pkg.uuid
end
end
return deps
end
end
function collect_project!(ctx::Context, pkg::PackageSpec, path::String, fix_deps_map::Dict{UUID,Vector{PackageSpec}})
fix_deps_map[pkg.uuid] = valtype(fix_deps_map)()
project_file = projectfile_path(path; strict=true)
(project_file === nothing) && return false
project = read_package(project_file)
compat = project.compat
if haskey(compat, "julia") && !(VERSION in Types.semver_spec(compat["julia"]))
@warn("julia version requirement for package $(pkg.name) not satisfied")
end
for (deppkg_name, uuid) in project.deps
vspec = haskey(compat, deppkg_name) ? Types.semver_spec(compat[deppkg_name]) : VersionSpec()
deppkg = PackageSpec(deppkg_name, uuid, vspec)
push!(fix_deps_map[pkg.uuid], deppkg)
end
if project.version !== nothing
pkg.version = project.version
else
# @warn "project file for $(pkg.name) is missing a `version` entry"
set_maximum_version_registry!(ctx.env, pkg)
end
return true
end
is_fixed(pkg::PackageSpec) = pkg.path !== nothing || pkg.repo.url !== nothing
function collect_fixed!(ctx::Context, pkgs::Vector{PackageSpec}, names::Dict{UUID, String})
fix_deps_map = Dict{UUID,Vector{PackageSpec}}()
for pkg in pkgs
path = project_rel_path(ctx, source_path(pkg))
if !isdir(path)
pkgerror("path $(path) for package $(pkg.name) no longer exists. Remove the package or `develop` it at a new path")
end
found_project = collect_project!(ctx, pkg, path, fix_deps_map)
if !found_project
collect_require!(ctx, pkg, path, fix_deps_map)
end
end
fixed = Dict{UUID,Fixed}()
# Collect the dependencies for the fixed packages
for (uuid, deps) in fix_deps_map
fix_pkg = pkgs[uuid]
q = Dict{UUID, VersionSpec}()
for dep in deps
names[dep.uuid] = dep.name
q[dep.uuid] = dep.version
end
fixed[uuid] = Fixed(fix_pkg.version, q)
end
return fixed
end
# Resolve a set of versions given package version specs
# looks at uuid, version, repo/path,
# sets version to a VersionNumber
# adds any other packages which may be in the dependency graph
# all versioned packges should have a `tree_hash`
function resolve_versions!(ctx::Context, pkgs::Vector{PackageSpec})
printpkgstyle(ctx, :Resolving, "package versions...")
# compatibility
proj_compat = Types.project_compatibility(ctx, "julia")
v = intersect(VERSION, proj_compat)
if isempty(v)
@warn "julia version requirement for project not satisfied" _module=nothing _file=nothing
end
# anything not mentioned is fixed
names = Dict{UUID, String}(uuid => stdlib for (uuid, stdlib) in ctx.stdlibs)
names[uuid_julia] = "julia"
# construct data structures for resolver and call it
# this also sets pkg.version for fixed packages
fixed = collect_fixed!(ctx, filter(is_fixed, pkgs), names)
# non fixed packages are `add`ed by version: their version is either restricted or free
# fixed packages are `dev`ed or `add`ed by repo
# at this point, fixed packages have a version and `deps`
# check compat
for pkg in pkgs
proj_compat = Types.project_compatibility(ctx, pkg.name)
v = intersect(pkg.version, proj_compat)
if isempty(v)
pkgerror(string("empty intersection between $(pkg.name)@$(pkg.version) and project ",
"compatibility $(proj_compat)"))
end
# Work around not clobbering 0.x.y+ for checked out old type of packages
if !(pkg.version isa VersionNumber)
pkg.version = v
end
end
for pkg in pkgs
names[pkg.uuid] = pkg.name
end
reqs = Requires(pkg.uuid => VersionSpec(pkg.version) for pkg in pkgs if pkg.uuid ≠ uuid_julia)
fixed[uuid_julia] = Fixed(VERSION)
graph = deps_graph(ctx, names, reqs, fixed)
simplify_graph!(graph)
vers = resolve(graph)
find_registered!(ctx.env, collect(keys(vers)))
# update vector of package versions
for (uuid, ver) in vers
pkg = pkgs[uuid]
if pkg !== nothing
# Fixed packages are not returned by resolve (they already have their version set)
pkg.version = vers[pkg.uuid]
else
name = (uuid in keys(ctx.stdlibs)) ? ctx.stdlibs[uuid] : registered_name(ctx.env, uuid)
push!(pkgs, PackageSpec(;name=name, uuid=uuid, version=ver))
end
end
load_tree_hashes!(ctx, pkgs)
end
include("require.jl")
get_or_make(::Type{T}, d::Dict{K}, k::K) where {T,K} = haskey(d, k) ? convert(T, d[k]) : T()
get_or_make!(d::Dict{K,V}, k::K) where {K,V} = get!(d, k) do; V() end
function deps_graph(ctx::Context, uuid_to_name::Dict{UUID,String}, reqs::Requires, fixed::Dict{UUID,Fixed})
uuids = collect(union(keys(reqs), keys(fixed), map(fx->keys(fx.requires), values(fixed))...))
seen = UUID[]
all_versions = Dict{UUID,Set{VersionNumber}}()
all_deps = Dict{UUID,Dict{VersionRange,Dict{String,UUID}}}()
all_compat = Dict{UUID,Dict{VersionRange,Dict{String,VersionSpec}}}()
for (fp, fx) in fixed
all_versions[fp] = Set([fx.version])
all_deps[fp] = Dict(VersionRange(fx.version) => Dict())
all_compat[fp] = Dict(VersionRange(fx.version) => Dict())
end
while true
unseen = setdiff(uuids, seen)
isempty(unseen) && break
for uuid in unseen
push!(seen, uuid)
uuid in keys(fixed) && continue
all_versions_u = get_or_make!(all_versions, uuid)
all_deps_u = get_or_make!(all_deps, uuid)
all_compat_u = get_or_make!(all_compat, uuid)
# make sure all versions of all packages know about julia uuid
if uuid ≠ uuid_julia
deps_u_allvers = get_or_make!(all_deps_u, VersionRange())
deps_u_allvers["julia"] = uuid_julia
end
# Collect deps + compat for stdlib
if uuid in keys(ctx.stdlibs)
path = Types.stdlib_path(ctx.stdlibs[uuid])
proj_file = projectfile_path(path; strict=true)
@assert proj_file != nothing
proj = Types.read_package(proj_file)
v = something(proj.version, VERSION)
push!(all_versions_u, v)
vr = VersionRange(v)
all_deps_u_vr = get_or_make!(all_deps_u, vr)
for (name, other_uuid) in proj.deps
all_deps_u_vr[name] = other_uuid
other_uuid in uuids || push!(uuids, other_uuid)
end
# TODO look at compat section for stdlibs?
all_compat_u_vr = get_or_make!(all_compat_u, vr)
for (name, other_uuid) in proj.deps
all_compat_u_vr[name] = VersionSpec()
end
else
for path in registered_paths(ctx.env, uuid)
version_info = load_versions(path; include_yanked = false)
versions = sort!(collect(keys(version_info)))
deps_data = load_package_data_raw(UUID, joinpath(path, "Deps.toml"))
compat_data = load_package_data_raw(VersionSpec, joinpath(path, "Compat.toml"))
union!(all_versions_u, versions)
for (vr, dd) in deps_data
all_deps_u_vr = get_or_make!(all_deps_u, vr)
for (name,other_uuid) in dd
# check conflicts??
all_deps_u_vr[name] = other_uuid
other_uuid in uuids || push!(uuids, other_uuid)
end
end
for (vr, cd) in compat_data
all_compat_u_vr = get_or_make!(all_compat_u, vr)
for (name,vs) in cd
# check conflicts??
all_compat_u_vr[name] = vs
end
end
end
end
end
find_registered!(ctx.env, uuids)
end
for uuid in uuids
uuid == uuid_julia && continue
if !haskey(uuid_to_name, uuid)
name = registered_name(ctx.env, uuid)
name === nothing && pkgerror("cannot find name corresponding to UUID $(uuid) in a registry")
uuid_to_name[uuid] = name
entry = manifest_info(ctx.env, uuid)
entry ≡ nothing && continue
uuid_to_name[uuid] = entry.name
end
end
return Graph(all_versions, all_deps, all_compat, uuid_to_name, reqs, fixed, #=verbose=# ctx.graph_verbose)
end
function load_urls(ctx::Context, pkgs::Vector{PackageSpec})
urls = Dict{UUID,Vector{String}}()
for pkg in pkgs
uuid = pkg.uuid
ver = pkg.version::VersionNumber
urls[uuid] = String[]
for path in registered_paths(ctx.env, uuid)
info = parse_toml(path, "Package.toml")
repo = info["repo"]
repo in urls[uuid] || push!(urls[uuid], repo)
end
end
foreach(sort!, values(urls))
return urls
end
########################
# Package installation #
########################
function get_archive_url_for_version(url::String, ref)
if (m = match(r"https://github.com/(.*?)/(.*?).git", url)) != nothing
return "https://api.github.com/repos/$(m.captures[1])/$(m.captures[2])/tarball/$(ref)"
end
return nothing
end
# Returns if archive successfully installed
function install_archive(
urls::Vector{String},
hash::SHA1,
version_path::String
)::Bool
tmp_objects = String[]
url_success = false
for url in urls
archive_url = get_archive_url_for_version(url, hash)
archive_url !== nothing || continue
path = tempname() * randstring(6) * ".tar.gz"
push!(tmp_objects, path) # for cleanup
url_success = true
try
PlatformEngines.download(archive_url, path; verbose=false)
catch e
e isa InterruptException && rethrow()
url_success = false
end
url_success || continue
dir = joinpath(tempdir(), randstring(12))
push!(tmp_objects, dir) # for cleanup
# Might fail to extract an archive (Pkg#190)
try
unpack(path, dir; verbose=false)
catch e
e isa InterruptException && rethrow()
@warn "failed to extract archive downloaded from $(archive_url)"
url_success = false
end
url_success || continue
dirs = readdir(dir)
# 7z on Win might create this spurious file
filter!(x -> x != "pax_global_header", dirs)
@assert length(dirs) == 1
!isdir(version_path) && mkpath(version_path)
mv(joinpath(dir, dirs[1]), version_path; force=true)
break # successful install
end
# Clean up and exit
foreach(x -> Base.rm(x; force=true, recursive=true), tmp_objects)
return url_success
end
const refspecs = ["+refs/*:refs/remotes/cache/*"]
function install_git(
ctx::Context,
uuid::UUID,
name::String,
hash::SHA1,
urls::Vector{String},
version::Union{VersionNumber,Nothing},
version_path::String
)::Nothing
repo = nothing
tree = nothing
try
repo, git_hash = Base.shred!(LibGit2.CachedCredentials()) do creds
clones_dir = joinpath(depots1(), "clones")
ispath(clones_dir) || mkpath(clones_dir)
repo_path = joinpath(clones_dir, string(uuid))
repo = GitTools.ensure_clone(repo_path, urls[1]; isbare=true,
header = "[$uuid] $name from $(urls[1])",
credentials=creds)
git_hash = LibGit2.GitHash(hash.bytes)
for url in urls
try LibGit2.with(LibGit2.GitObject, repo, git_hash) do g
end
break # object was found, we can stop
catch err
err isa LibGit2.GitError && err.code == LibGit2.Error.ENOTFOUND || rethrow()
end
GitTools.fetch(repo, url, refspecs=refspecs, credentials=creds)
end
return repo, git_hash
end
tree = try
LibGit2.GitObject(repo, git_hash)
catch err
err isa LibGit2.GitError && err.code == LibGit2.Error.ENOTFOUND || rethrow()
error("$name: git object $(string(hash)) could not be found")
end
tree isa LibGit2.GitTree ||
error("$name: git object $(string(hash)) should be a tree, not $(typeof(tree))")
mkpath(version_path)
GC.@preserve version_path begin
opts = LibGit2.CheckoutOptions(
checkout_strategy = LibGit2.Consts.CHECKOUT_FORCE,
target_directory = Base.unsafe_convert(Cstring, version_path)
)
LibGit2.checkout_tree(repo, tree, options=opts)
end
return
finally
repo !== nothing && LibGit2.close(repo)
tree !== nothing && LibGit2.close(tree)
end
end
function download_artifacts(pkgs::Vector{PackageSpec}; platform::Platform=platform_key_abi(),
verbose::Bool=false)
# Filter out packages that have no source_path()
pkg_roots = String[p for p in source_path.(pkgs) if p != nothing]
return download_artifacts(pkg_roots; platform=platform, verbose=verbose)
end
function download_artifacts(pkg_roots::Vector{String}; platform::Platform=platform_key_abi(),
verbose::Bool=false)
for path in pkg_roots
# Check to see if this package has an (Julia)Artifacts.toml
for f in artifact_names
artifacts_toml = joinpath(path, f)
if isfile(artifacts_toml)
ensure_all_artifacts_installed(artifacts_toml; platform=platform, verbose=verbose)
write_env_usage(artifacts_toml, "artifact_usage.toml")
break
end
end
end
end
function check_artifacts_downloaded(pkg_root::String; platform::Platform=platform_key_abi())
for f in artifact_names
artifacts_toml = joinpath(pkg_root, f)
if isfile(artifacts_toml)
hashes = extract_all_hashes(artifacts_toml)
if !all(artifact_exists.(hashes))
return false
end
break
end
end
return true
end
# install & update manifest
function download_source(ctx::Context, pkgs::Vector{PackageSpec}; readonly=true)
pkgs = filter(tracking_registered_version, pkgs)
urls = load_urls(ctx, pkgs)
return download_source(ctx, pkgs, urls; readonly=readonly)
end
function download_source(ctx::Context, pkgs::Vector{PackageSpec},
urls::Dict{UUID, Vector{String}}; readonly=true)
probe_platform_engines!()
new_pkgs = PackageSpec[]
pkgs_to_install = Tuple{PackageSpec, String}[]
for pkg in pkgs
path = source_path(pkg)
ispath(path) && continue
push!(pkgs_to_install, (pkg, path))
push!(new_pkgs, pkg)
end
widths = [textwidth(pkg.name) for (pkg, _) in pkgs_to_install]
max_name = length(widths) == 0 ? 0 : maximum(widths)
########################################
# Install from archives asynchronously #
########################################
jobs = Channel(ctx.num_concurrent_downloads);
results = Channel(ctx.num_concurrent_downloads);
@async begin
for pkg in pkgs_to_install
put!(jobs, pkg)
end
end
for i in 1:ctx.num_concurrent_downloads
@async begin
for (pkg, path) in jobs
if ctx.preview
put!(results, (pkg, true, path))
continue
end
if ctx.use_libgit2_for_all_downloads
put!(results, (pkg, false, path))
continue
end
try
success = install_archive(urls[pkg.uuid], pkg.tree_hash, path)
if success && readonly
set_readonly(path) # In add mode, files should be read-only
end
if ctx.use_only_tarballs_for_downloads && !success
pkgerror("failed to get tarball from $(urls[pkg.uuid])")
end
put!(results, (pkg, success, path))
catch err
put!(results, (pkg, err, catch_backtrace()))
end
end
end
end
missed_packages = Tuple{PackageSpec, String}[]
for i in 1:length(pkgs_to_install)
pkg, exc_or_success, bt_or_path = take!(results)
exc_or_success isa Exception && pkgerror("Error when installing package $(pkg.name):\n",
sprint(Base.showerror, exc_or_success, bt_or_path))
success, path = exc_or_success, bt_or_path
if success
vstr = pkg.version != nothing ? "v$(pkg.version)" : "[$h]"
printpkgstyle(ctx, :Installed, string(rpad(pkg.name * " ", max_name + 2, "─"), " ", vstr))
else
push!(missed_packages, (pkg, path))
end
end
##################################################
# Use LibGit2 to download any remaining packages #
##################################################
for (pkg, path) in missed_packages
uuid = pkg.uuid
if !ctx.preview
install_git(ctx, pkg.uuid, pkg.name, pkg.tree_hash, urls[uuid], pkg.version::VersionNumber, path)
readonly && set_readonly(path)
end
vstr = pkg.version != nothing ? "v$(pkg.version)" : "[$h]"
printpkgstyle(ctx, :Installed, string(rpad(pkg.name * " ", max_name + 2, "─"), " ", vstr))
end
return new_pkgs
end
################################
# Manifest update and pruning #
################################
project_rel_path(ctx::Context, path::String) =
normpath(joinpath(dirname(ctx.env.project_file), path))
function prune_manifest(env::EnvCache)
keep = collect(values(env.project.deps))
env.manifest = prune_manifest!(env.manifest, keep)
end
function prune_manifest!(manifest::Dict, keep::Vector{UUID})
while !isempty(keep)
clean = true
for (uuid, entry) in manifest
uuid in keep || continue
for dep in values(entry.deps)
dep in keep && continue
push!(keep, dep)
clean = false
end
end
clean && break
end
return Dict(uuid => entry for (uuid, entry) in manifest if uuid in keep)
end
function any_package_not_installed(ctx)
for (uuid, entry) in ctx.env.manifest
if Base.locate_package(Base.PkgId(uuid, entry.name)) === nothing
return true
end
end
return false
end
#########
# Build #
#########
function _get_deps!(ctx::Context, pkgs::Vector{PackageSpec}, uuids::Vector{UUID})
for pkg in pkgs
pkg.uuid in keys(ctx.stdlibs) && continue
pkg.uuid in uuids && continue
push!(uuids, pkg.uuid)
if Types.is_project(ctx.env, pkg)
pkgs = [PackageSpec(name, uuid) for (name, uuid) in ctx.env.project.deps]
else
info = manifest_info(ctx.env, pkg.uuid)
if info === nothing
pkgerror("could not find manifest info for package with uuid: $(pkg.uuid)")
end
pkgs = [PackageSpec(name, uuid) for (name, uuid) in info.deps]
end
_get_deps!(ctx, pkgs, uuids)
end
return
end
function build(ctx::Context, pkgs::Vector{PackageSpec}, verbose::Bool)
if !ctx.preview && (any_package_not_installed(ctx) || !isfile(ctx.env.manifest_file))
Pkg.instantiate(ctx)
end
uuids = UUID[]
_get_deps!(ctx, pkgs, uuids)
length(uuids) == 0 && (@info("no packages to build"); return)
build_versions(ctx, uuids; might_need_to_resolve=true, verbose=verbose)
ctx.preview && preview_info()
end
function dependency_order_uuids(ctx::Context, uuids::Vector{UUID})::Dict{UUID,Int}
order = Dict{UUID,Int}()
seen = UUID[]
k = 0
function visit(uuid::UUID)
uuid in keys(ctx.stdlibs) && return
uuid in seen &&
return @warn("Dependency graph not a DAG, linearizing anyway")
haskey(order, uuid) && return
push!(seen, uuid)
if Types.is_project_uuid(ctx.env, uuid)
deps = values(ctx.env.project.deps)
else
entry = manifest_info(ctx.env, uuid)
deps = values(entry.deps)
end
foreach(visit, deps)
pop!(seen)
order[uuid] = k += 1
end
visit(uuid::String) = visit(UUID(uuid))
foreach(visit, uuids)
return order
end
function gen_build_code(build_file::String)
code = """
$(Base.load_path_setup_code(false))
cd($(repr(dirname(build_file))))
include($(repr(build_file)))
"""
return ```
$(Base.julia_cmd()) -O0 --color=no --history-file=no
--startup-file=$(Base.JLOptions().startupfile == 1 ? "yes" : "no")
--compiled-modules=$(Bool(Base.JLOptions().use_compiled_modules) ? "yes" : "no")
--eval $code
```
end
builddir(source_path::String) = joinpath(source_path, "deps")
buildfile(source_path::String) = joinpath(builddir(source_path), "build.jl")
function build_versions(ctx::Context, uuids::Vector{UUID}; might_need_to_resolve=false, verbose=false)
# collect builds for UUIDs with `deps/build.jl` files
ctx.preview && (printpkgstyle(ctx, :Building, "skipping building in preview mode"); return)
builds = Tuple{UUID,String,String,VersionNumber}[]
for uuid in uuids
uuid in keys(ctx.stdlibs) && continue
if Types.is_project_uuid(ctx.env, uuid)
path = dirname(ctx.env.project_file)
name = ctx.env.pkg.name
version = ctx.env.pkg.version
else
entry = manifest_info(ctx.env, uuid)
name = entry.name
if entry.tree_hash !== nothing
path = find_installed(name, uuid, entry.tree_hash)
elseif entry.path !== nothing
path = project_rel_path(ctx, entry.path)
else
pkgerror("Could not find either `git-tree-sha1` or `path` for package $name")
end
version = v"0.0"
end
ispath(path) || error("Build path for $name does not exist: $path")
ispath(buildfile(path)) && push!(builds, (uuid, name, path, version))
end
# toposort builds by dependencies
order = dependency_order_uuids(ctx, map(first, builds))
sort!(builds, by = build -> order[first(build)])
max_name = isempty(builds) ? 0 : maximum(textwidth.([build[2] for build in builds]))
# build each package versions in a child process
for (uuid, name, source_path, version) in builds
pkg = PackageSpec(;uuid=uuid, name=name, version=version)
build_file = buildfile(source_path)
if !isfile(projectfile_path(builddir(source_path)))
backwards_compat_for_build(ctx, pkg, build_file,
verbose, might_need_to_resolve, max_name)
continue
end
log_file = splitext(build_file)[1] * ".log"
printpkgstyle(ctx, :Building,
rpad(name * " ", max_name + 1, "─") * "→ " * Types.pathrepr(log_file))
sandbox(ctx, pkg, source_path, builddir(source_path)) do
ok = open(log_file, "w") do log
success(pipeline(gen_build_code(buildfile(source_path)),
stdout = verbose ? stdout : log,
stderr = verbose ? stderr : log))
end
ok && return
n_lines = isinteractive() ? 100 : 5000
# TODO: Extract last n lines more efficiently
log_lines = readlines(log_file)
log_show = join(log_lines[max(1, length(log_lines) - n_lines):end], '\n')
full_log_at, last_lines =
if length(log_lines) > n_lines
"\n\nFull log at $log_file",
", showing the last $n_lines of log"
else
"", ""
end
@error "Error building `$(pkg.name)`$last_lines: \n$log_show$full_log_at"
end
end
return
end
##############
# Operations #
##############
function rm(ctx::Context, pkgs::Vector{PackageSpec})
drop = UUID[]
# find manifest-mode drops
for pkg in pkgs
pkg.mode == PKGMODE_MANIFEST || continue
info = manifest_info(ctx.env, pkg.uuid)
if info !== nothing
pkg.uuid in drop || push!(drop, pkg.uuid)
else
str = has_name(pkg) ? pkg.name : string(pkg.uuid)
@warn("`$str` not in manifest, ignoring")
end
end
# drop reverse dependencies
while !isempty(drop)
clean = true
for (uuid, entry) in ctx.env.manifest
deps = values(entry.deps)
isempty(drop ∩ deps) && continue
uuid ∉ drop || continue
push!(drop, uuid)
clean = false
end
clean && break
end
# find project-mode drops
for pkg in pkgs
pkg.mode == PKGMODE_PROJECT || continue
found = false
for (name::String, uuid::UUID) in ctx.env.project.deps
pkg.name == name || pkg.uuid == uuid || continue
pkg.name == name ||
error("project file name mismatch for `$uuid`: $(pkg.name) ≠ $name")
pkg.uuid == uuid ||
error("project file UUID mismatch for `$name`: $(pkg.uuid) ≠ $uuid")
uuid in drop || push!(drop, uuid)
found = true
break
end
found && continue
str = has_name(pkg) ? pkg.name : string(pkg.uuid)
@warn("`$str` not in project, ignoring")
end
# delete drops from project
n = length(ctx.env.project.deps)
filter!(ctx.env.project.deps) do (_, uuid)
uuid ∉ drop
end
if length(ctx.env.project.deps) == n
@info "No changes"
return
end
# only declare `compat` for direct dependencies
# `julia` is always an implicit direct dependency
filter!(ctx.env.project.compat) do (name, _)
name == "julia" || name in keys(ctx.env.project.deps)
end
deps_names = append!(collect(keys(ctx.env.project.deps)),
collect(keys(ctx.env.project.extras)))
filter!(ctx.env.project.targets) do (target, deps)
!isempty(filter!(in(deps_names), deps))
end
# only keep reachable manifest entires
prune_manifest(ctx.env)
# update project & manifest
write_env(ctx)
end
update_package_add(pkg::PackageSpec, ::Nothing, is_dep::Bool) = pkg
function update_package_add(pkg::PackageSpec, entry::PackageEntry, is_dep::Bool)
if entry.pinned
pkg.version == VersionSpec() ||
@warn "`$(pkg.name)` is pinned at `v$(entry.version)`. Maintaining pinned version."
return PackageSpec(; uuid=pkg.uuid, name=pkg.name, pinned=true,
version=entry.version, tree_hash=entry.tree_hash)
end
if entry.path !== nothing || entry.repo.url !== nothing || pkg.repo.url !== nothing
return pkg # overwrite everything, nothing to copy over
end
if is_stdlib(pkg.uuid)
return pkg # stdlibs are not versioned like other packages
elseif is_dep && ((isa(pkg.version, VersionNumber) && entry.version == pkg.version) ||
(!isa(pkg.version, VersionNumber) && entry.version ∈ pkg.version))
# leave the package as is at the installed version
return PackageSpec(; uuid=pkg.uuid, name=pkg.name, version=entry.version,
tree_hash=entry.tree_hash)
end
# adding a new version not compatible with the old version, so we just overwrite
return pkg
end
function check_registered(ctx::Context, pkgs::Vector{PackageSpec})
pkgs = filter(tracking_registered_version, pkgs)
find_registered!(ctx.env, UUID[pkg.uuid for pkg in pkgs])
for pkg in pkgs
isempty(registered_paths(ctx.env, pkg.uuid)) || continue
pkgerror("Package $(pkg.name) [$(pkg.uuid)] not found in a registry.")
end
end
# Check if the package can be added without colliding/overwriting things
function assert_can_add(ctx::Context, pkgs::Vector{PackageSpec})
for pkg in pkgs
@assert pkg.name !== nothing && pkg.uuid !== nothing
# package with the same name exist in the project: assert that they have the same uuid
get(ctx.env.project.deps, pkg.name, pkg.uuid) == pkg.uuid ||
pkgerror("cannot add package `$(pkg.name) = \"$(pkg.uuid)\"` ",
"since package `$(pkg.name) = \"$(get(ctx.env.project.deps, pkg.name, pkg.uuid))\"` ",
"already exists as a direct dependency.")
# package with the same uuid exist in the project: assert they have the same name
name = findfirst(==(pkg.uuid), ctx.env.project.deps)
(name === nothing || name == pkg.name) ||
pkgerror("cannot add package `$(pkg.name) = \"$(pkg.uuid)\"` ",
"since package `$(pkg.name) = \"$(ctx.env.project.deps[name])\"` ",
"already exists as a direct dependency.")
# package with the same uuid exist in the manifest: assert they have the same name
haskey(ctx.env.manifest, pkg.uuid) && (ctx.env.manifest[pkg.uuid].name != pkg.name) &&
pkgerror("cannot add package `$(pkg.name) = \"$(pkg.uuid)\"` ",
"since package `$(ctx.env.manifest[pkg.uuid].name) = \"$(pkg.uuid)\"` ",
"already exists in the manifest.")
end
end
function add(ctx::Context, pkgs::Vector{PackageSpec}, new_git=UUID[];
strict::Bool=false, platform::Platform=platform_key_abi())
assert_can_add(ctx, pkgs)