-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
loading.jl
4207 lines (3840 loc) · 167 KB
/
loading.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
# Base.require is the implementation for the `import` statement
const require_lock = ReentrantLock()
# Cross-platform case-sensitive path canonicalization
if Sys.isunix() && !Sys.isapple()
# assume case-sensitive filesystems, don't have to do anything
isfile_casesensitive(path) = isaccessiblefile(path)
elseif Sys.iswindows()
# GetLongPathName Win32 function returns the case-preserved filename on NTFS.
function isfile_casesensitive(path)
isaccessiblefile(path) || return false # Fail fast
basename(Filesystem.longpath(path)) == basename(path)
end
elseif Sys.isapple()
# HFS+ filesystem is case-preserving. The getattrlist API returns
# a case-preserved filename. In the rare event that HFS+ is operating
# in case-sensitive mode, this will still work but will be redundant.
# Constants from <sys/attr.h>
const ATRATTR_BIT_MAP_COUNT = 5
const ATTR_CMN_NAME = 1
const BITMAPCOUNT = 1
const COMMONATTR = 5
const FSOPT_NOFOLLOW = 1 # Don't follow symbolic links
const attr_list = zeros(UInt8, 24)
attr_list[BITMAPCOUNT] = ATRATTR_BIT_MAP_COUNT
attr_list[COMMONATTR] = ATTR_CMN_NAME
# This essentially corresponds to the following C code:
# attrlist attr_list;
# memset(&attr_list, 0, sizeof(attr_list));
# attr_list.bitmapcount = ATTR_BIT_MAP_COUNT;
# attr_list.commonattr = ATTR_CMN_NAME;
# struct Buffer {
# u_int32_t total_length;
# u_int32_t filename_offset;
# u_int32_t filename_length;
# char filename[max_filename_length];
# };
# Buffer buf;
# getattrpath(path, &attr_list, &buf, sizeof(buf), FSOPT_NOFOLLOW);
function isfile_casesensitive(path)
isaccessiblefile(path) || return false
path_basename = String(basename(path))
local casepreserved_basename
header_size = 12
buf = Vector{UInt8}(undef, length(path_basename) + header_size + 1)
while true
ret = ccall(:getattrlist, Cint,
(Cstring, Ptr{Cvoid}, Ptr{Cvoid}, Csize_t, Culong),
path, attr_list, buf, sizeof(buf), FSOPT_NOFOLLOW)
systemerror(:getattrlist, ret ≠ 0)
filename_length = GC.@preserve buf unsafe_load(
convert(Ptr{UInt32}, pointer(buf) + 8))
if (filename_length + header_size) > length(buf)
resize!(buf, filename_length + header_size)
continue
end
casepreserved_basename =
view(buf, (header_size+1):(header_size+filename_length-1))
break
end
# Hack to compensate for inability to create a string from a subarray with no allocations.
codeunits(path_basename) == casepreserved_basename && return true
# If there is no match, it's possible that the file does exist but HFS+
# performed unicode normalization. See https://developer.apple.com/library/mac/qa/qa1235/_index.html.
isascii(path_basename) && return false
codeunits(Unicode.normalize(path_basename, :NFD)) == casepreserved_basename
end
else
# Generic fallback that performs a slow directory listing.
function isfile_casesensitive(path)
isaccessiblefile(path) || return false
dir, filename = splitdir(path)
any(readdir(dir) .== filename)
end
end
# Check if the file is accessible. If stat fails return `false`
function isaccessibledir(dir)
return try
isdir(dir)
catch err
err isa IOError || rethrow()
false
end
end
function isaccessiblefile(file)
return try
isfile(file)
catch err
err isa IOError || rethrow()
false
end
end
function isaccessiblepath(path)
return try
ispath(path)
catch err
err isa IOError || rethrow()
false
end
end
## SHA1 ##
struct SHA1
bytes::NTuple{20, UInt8}
end
function SHA1(bytes::Vector{UInt8})
length(bytes) == 20 ||
throw(ArgumentError("wrong number of bytes for SHA1 hash: $(length(bytes))"))
return SHA1(ntuple(i->bytes[i], Val(20)))
end
SHA1(s::AbstractString) = SHA1(hex2bytes(s))
parse(::Type{SHA1}, s::AbstractString) = SHA1(s)
function tryparse(::Type{SHA1}, s::AbstractString)
try
return parse(SHA1, s)
catch e
if isa(e, ArgumentError)
return nothing
end
rethrow(e)
end
end
string(hash::SHA1) = bytes2hex(hash.bytes)
print(io::IO, hash::SHA1) = bytes2hex(io, hash.bytes)
show(io::IO, hash::SHA1) = print(io, "SHA1(\"", hash, "\")")
isless(a::SHA1, b::SHA1) = isless(a.bytes, b.bytes)
hash(a::SHA1, h::UInt) = hash((SHA1, a.bytes), h)
==(a::SHA1, b::SHA1) = a.bytes == b.bytes
# fake uuid5 function (for self-assigned UUIDs)
# TODO: delete and use real uuid5 once it's in stdlib
function uuid5(namespace::UUID, key::String)
u::UInt128 = 0
h = hash(namespace)
for _ = 1:sizeof(u)÷sizeof(h)
u <<= sizeof(h) << 3
u |= (h = hash(key, h))
end
u &= 0xffffffffffff0fff3fffffffffffffff
u |= 0x00000000000050008000000000000000
return UUID(u)
end
const ns_dummy_uuid = UUID("fe0723d6-3a44-4c41-8065-ee0f42c8ceab")
function dummy_uuid(project_file::String)
@lock require_lock begin
cache = LOADING_CACHE[]
if cache !== nothing
uuid = get(cache.dummy_uuid, project_file, nothing)
uuid === nothing || return uuid
end
project_path = try
realpath(project_file)
catch ex
ex isa IOError || rethrow()
project_file
end
uuid = uuid5(ns_dummy_uuid, project_path)
if cache !== nothing
cache.dummy_uuid[project_file] = uuid
end
return uuid
end
end
## package path slugs: turning UUID + SHA1 into a pair of 4-byte "slugs" ##
const slug_chars = String(['A':'Z'; 'a':'z'; '0':'9'])
function slug(x::UInt32, p::Int)
y::UInt32 = x
sprint(sizehint=p) do io
n = length(slug_chars)
for i = 1:p
y, d = divrem(y, n)
write(io, slug_chars[1+d])
end
end
end
function package_slug(uuid::UUID, p::Int=5)
crc = _crc32c(uuid)
return slug(crc, p)
end
function version_slug(uuid::UUID, sha1::SHA1, p::Int=5)
crc = _crc32c(uuid)
crc = _crc32c(sha1.bytes, crc)
return slug(crc, p)
end
mutable struct CachedTOMLDict
path::String
inode::UInt64
mtime::Float64
size::Int64
hash::UInt32
d::Dict{String, Any}
end
function CachedTOMLDict(p::TOML.Parser, path::String)
s = stat(path)
content = read(path)
crc32 = _crc32c(content)
TOML.reinit!(p, String(content); filepath=path)
d = TOML.parse(p)
return CachedTOMLDict(
path,
s.inode,
s.mtime,
s.size,
crc32,
d,
)
end
function get_updated_dict(p::TOML.Parser, f::CachedTOMLDict)
s = stat(f.path)
# note, this might miss very rapid in-place updates, such that mtime is
# identical but that is solvable by not doing in-place updates, and not
# rapidly changing these files
if s.inode != f.inode || s.mtime != f.mtime || f.size != s.size
content = read(f.path)
new_hash = _crc32c(content)
if new_hash != f.hash
f.inode = s.inode
f.mtime = s.mtime
f.size = s.size
f.hash = new_hash
TOML.reinit!(p, String(content); filepath=f.path)
return f.d = TOML.parse(p)
end
end
return f.d
end
struct LoadingCache
load_path::Vector{String}
dummy_uuid::Dict{String, UUID}
env_project_file::Dict{String, Union{Bool, String}}
project_file_manifest_path::Dict{String, Union{Nothing, String}}
require_parsed::Set{String}
identified_where::Dict{Tuple{PkgId, String}, Union{Nothing, Tuple{PkgId, String}}}
identified::Dict{String, Union{Nothing, Tuple{PkgId, String}}}
located::Dict{Tuple{PkgId, Union{String, Nothing}}, Union{Tuple{String, String}, Nothing}}
end
const LOADING_CACHE = Ref{Union{LoadingCache, Nothing}}(nothing)
LoadingCache() = LoadingCache(load_path(), Dict(), Dict(), Dict(), Set(), Dict(), Dict(), Dict())
struct TOMLCache{Dates}
p::TOML.Parser{Dates}
d::Dict{String, CachedTOMLDict}
end
TOMLCache(p::TOML.Parser) = TOMLCache(p, Dict{String, CachedTOMLDict}())
TOMLCache(p::TOML.Parser, d::Dict{String, Dict{String, Any}}) = TOMLCache(p, convert(Dict{String, CachedTOMLDict}, d))
const TOML_CACHE = TOMLCache(TOML.Parser{nothing}())
parsed_toml(project_file::AbstractString) = parsed_toml(project_file, TOML_CACHE, require_lock)
function parsed_toml(project_file::AbstractString, toml_cache::TOMLCache, toml_lock::ReentrantLock)
lock(toml_lock) do
cache = LOADING_CACHE[]
dd = if !haskey(toml_cache.d, project_file)
d = CachedTOMLDict(toml_cache.p, project_file)
toml_cache.d[project_file] = d
d.d
else
d = toml_cache.d[project_file]
# We are in a require call and have already parsed this TOML file
# assume that it is unchanged to avoid hitting disk
if cache !== nothing && project_file in cache.require_parsed
d.d
else
get_updated_dict(toml_cache.p, d)
end
end
if cache !== nothing
push!(cache.require_parsed, project_file)
end
return dd
end
end
## package identification: determine unique identity of package to be loaded ##
# Used by Pkg but not used in loading itself
function find_package(arg) # ::Union{Nothing,String}
pkgenv = identify_package_env(arg)
pkgenv === nothing && return nothing
pkg, env = pkgenv
return locate_package(pkg, env)
end
# is there a better/faster ground truth?
function is_stdlib(pkgid::PkgId)
pkgid.name in readdir(Sys.STDLIB) || return false
stdlib_root = joinpath(Sys.STDLIB, pkgid.name)
project_file = locate_project_file(stdlib_root)
if project_file isa String
d = parsed_toml(project_file)
uuid = get(d, "uuid", nothing)
if uuid !== nothing
return UUID(uuid) == pkgid.uuid
end
end
return false
end
"""
Base.identify_package_env(name::String)::Union{Tuple{PkgId, String}, Nothing}
Base.identify_package_env(where::Union{Module,PkgId}, name::String)::Union{Tuple{PkgId, Union{String, Nothing}}, Nothing}
Same as [`Base.identify_package`](@ref) except that the path to the environment where the package is identified
is also returned, except when the identity is not identified.
"""
identify_package_env(where::Module, name::String) = identify_package_env(PkgId(where), name)
function identify_package_env(where::PkgId, name::String)
cache = LOADING_CACHE[]
if cache !== nothing
pkg_env = get(cache.identified_where, (where, name), missing)
pkg_env === missing || return pkg_env
end
pkg_env = nothing
if where.name === name
return (where, nothing)
elseif where.uuid === nothing
pkg_env = identify_package_env(name) # ignore `where`
else
for env in load_path()
pkgid = manifest_deps_get(env, where, name)
pkgid === nothing && continue # not found--keep looking
if pkgid.uuid !== nothing
pkg_env = pkgid, env # found in explicit environment--use it
end
break # found in implicit environment--return "not found"
end
if pkg_env === nothing && is_stdlib(where)
# if not found it could be that manifests are from a different julia version/commit
# where stdlib dependencies have changed, so look up deps based on the stdlib Project.toml
# as a fallback
pkg_env = identify_stdlib_project_dep(where, name)
end
end
if cache !== nothing
cache.identified_where[(where, name)] = pkg_env
end
return pkg_env
end
function identify_package_env(name::String)
cache = LOADING_CACHE[]
if cache !== nothing
pkg_env = get(cache.identified, name, missing)
pkg_env === missing || return pkg_env
end
pkg_env = nothing
for env in load_path()
pkg = project_deps_get(env, name)
if pkg !== nothing
pkg_env = pkg, env # found--return it
break
end
end
if cache !== nothing
cache.identified[name] = pkg_env
end
return pkg_env
end
function identify_stdlib_project_dep(stdlib::PkgId, depname::String)
@debug """
Stdlib $(repr("text/plain", stdlib)) is trying to load `$depname`
which is not listed as a dep in the load path manifests, so resorting to search
in the stdlib Project.tomls for true deps"""
stdlib_projfile = locate_project_file(joinpath(Sys.STDLIB, stdlib.name))
stdlib_projfile === nothing && return nothing
found = explicit_project_deps_get(stdlib_projfile, depname)
if found !== nothing
@debug "$(repr("text/plain", stdlib)) indeed depends on $depname in project $stdlib_projfile"
pkgid = PkgId(found, depname)
return pkgid, stdlib_projfile
end
return nothing
end
_nothing_or_first(x) = x === nothing ? nothing : first(x)
"""
Base.identify_package(name::String)::Union{PkgId, Nothing}
Base.identify_package(where::Union{Module,PkgId}, name::String)::Union{PkgId, Nothing}
Identify the package by its name from the current environment stack, returning
its `PkgId`, or `nothing` if it cannot be found.
If only the `name` argument is provided, it searches each environment in the
stack and its named direct dependencies.
The `where` argument provides the context from where to search for the
package: in this case it first checks if the name matches the context itself,
otherwise it searches all recursive dependencies (from the resolved manifest of
each environment) until it locates the context `where`, and from there
identifies the dependency with the corresponding name.
```julia-repl
julia> Base.identify_package("Pkg") # Pkg is a dependency of the default environment
Pkg [44cfe95a-1eb2-52ea-b672-e2afdf69b78f]
julia> using LinearAlgebra
julia> Base.identify_package(LinearAlgebra, "Pkg") # Pkg is not a dependency of LinearAlgebra
```
"""
identify_package(where::Module, name::String) = _nothing_or_first(identify_package_env(where, name))
identify_package(where::PkgId, name::String) = _nothing_or_first(identify_package_env(where, name))
identify_package(name::String) = _nothing_or_first(identify_package_env(name))
function locate_package_env(pkg::PkgId, stopenv::Union{String, Nothing}=nothing)::Union{Nothing,Tuple{String,String}}
cache = LOADING_CACHE[]
if cache !== nothing
pathenv = get(cache.located, (pkg, stopenv), missing)
pathenv === missing || return pathenv
end
path = nothing
env′ = nothing
if pkg.uuid === nothing
for env in load_path()
# look for the toplevel pkg `pkg.name` in this entry
found = project_deps_get(env, pkg.name)
if found !== nothing
@assert found.name == pkg.name
if found.uuid === nothing
# pkg.name is present in this directory or project file,
# return the path the entry point for the code, if it could be found
# otherwise, signal failure
path = implicit_manifest_uuid_path(env, pkg)
env′ = env
@goto done
end
end
if !(loading_extension || precompiling_extension)
stopenv == env && @goto done
end
end
else
for env in load_path()
path = manifest_uuid_path(env, pkg)
# missing is used as a sentinel to stop looking further down in envs
if path === missing
path = nothing
@goto done
end
if path !== nothing
env′ = env
@goto done
end
if !(loading_extension || precompiling_extension)
stopenv == env && break
end
end
# Allow loading of stdlibs if the name/uuid are given
# e.g. if they have been explicitly added to the project/manifest
mbypath = manifest_uuid_path(Sys.STDLIB, pkg)
if mbypath isa String
path = mbypath
env′ = Sys.STDLIB
@goto done
end
end
@label done
if path !== nothing && !isfile_casesensitive(path)
path = nothing
end
if cache !== nothing
cache.located[(pkg, stopenv)] = path === nothing ? nothing : (path, something(env′))
end
path === nothing && return nothing
return path, something(env′)
end
"""
Base.locate_package(pkg::PkgId)::Union{String, Nothing}
The path to the entry-point file for the package corresponding to the identifier
`pkg`, or `nothing` if not found. See also [`identify_package`](@ref).
```julia-repl
julia> pkg = Base.identify_package("Pkg")
Pkg [44cfe95a-1eb2-52ea-b672-e2afdf69b78f]
julia> Base.locate_package(pkg)
"/path/to/julia/stdlib/v$(VERSION.major).$(VERSION.minor)/Pkg/src/Pkg.jl"
```
"""
function locate_package(pkg::PkgId, stopenv::Union{String, Nothing}=nothing)::Union{Nothing,String}
_nothing_or_first(locate_package_env(pkg, stopenv))
end
"""
pathof(m::Module)
Return the path of the `m.jl` file that was used to `import` module `m`,
or `nothing` if `m` was not imported from a package.
Use [`dirname`](@ref) to get the directory part and [`basename`](@ref)
to get the file name part of the path.
See also [`pkgdir`](@ref).
"""
function pathof(m::Module)
@lock require_lock begin
pkgid = get(module_keys, m, nothing)
pkgid === nothing && return nothing
origin = get(pkgorigins, pkgid, nothing)
origin === nothing && return nothing
path = origin.path
path === nothing && return nothing
return fixup_stdlib_path(path)
end
end
"""
pkgdir(m::Module[, paths::String...])
Return the root directory of the package that declared module `m`,
or `nothing` if `m` was not declared in a package. Optionally further
path component strings can be provided to construct a path within the
package root.
To get the root directory of the package that implements the current module
the form `pkgdir(@__MODULE__)` can be used.
If an extension module is given, the root of the parent package is returned.
```julia-repl
julia> pkgdir(Foo)
"/path/to/Foo.jl"
julia> pkgdir(Foo, "src", "file.jl")
"/path/to/Foo.jl/src/file.jl"
```
See also [`pathof`](@ref).
!!! compat "Julia 1.7"
The optional argument `paths` requires at least Julia 1.7.
"""
function pkgdir(m::Module, paths::String...)
rootmodule = moduleroot(m)
path = pathof(rootmodule)
path === nothing && return nothing
original = path
path, base = splitdir(dirname(path))
if base == "src"
# package source in `../src/Foo.jl`
elseif base == "ext"
# extension source in `../ext/FooExt.jl`
elseif basename(path) == "ext"
# extension source in `../ext/FooExt/FooExt.jl`
path = dirname(path)
else
error("Unexpected path structure for module source: $original")
end
return joinpath(path, paths...)
end
function get_pkgversion_from_path(path)
project_file = locate_project_file(path)
if project_file isa String
d = parsed_toml(project_file)
v = get(d, "version", nothing)
if v !== nothing
return VersionNumber(v::String)
end
end
return nothing
end
"""
pkgversion(m::Module)
Return the version of the package that imported module `m`,
or `nothing` if `m` was not imported from a package, or imported
from a package without a version field set.
The version is read from the package's Project.toml during package
load.
To get the version of the package that imported the current module
the form `pkgversion(@__MODULE__)` can be used.
!!! compat "Julia 1.9"
This function was introduced in Julia 1.9.
"""
function pkgversion(m::Module)
path = pkgdir(m)
path === nothing && return nothing
@lock require_lock begin
v = get_pkgversion_from_path(path)
pkgorigin = get(pkgorigins, PkgId(moduleroot(m)), nothing)
# Cache the version
if pkgorigin !== nothing && pkgorigin.version === nothing
pkgorigin.version = v
end
return v
end
end
## generic project & manifest API ##
const project_names = ("JuliaProject.toml", "Project.toml")
const manifest_names = (
"JuliaManifest-v$(VERSION.major).$(VERSION.minor).toml",
"Manifest-v$(VERSION.major).$(VERSION.minor).toml",
"JuliaManifest.toml",
"Manifest.toml",
)
const preferences_names = ("JuliaLocalPreferences.toml", "LocalPreferences.toml")
function locate_project_file(env::String)
for proj in project_names
project_file = joinpath(env, proj)
if isfile_casesensitive(project_file)
return project_file
end
end
return true
end
# classify the LOAD_PATH entry to be one of:
# - `false`: nonexistent / nothing to see here
# - `true`: `env` is an implicit environment
# - `path`: the path of an explicit project file
function env_project_file(env::String)::Union{Bool,String}
@lock require_lock begin
cache = LOADING_CACHE[]
if cache !== nothing
project_file = get(cache.env_project_file, env, nothing)
project_file === nothing || return project_file
end
if isdir(env)
project_file = locate_project_file(env)
elseif basename(env) in project_names && isfile_casesensitive(env)
project_file = env
else
project_file = false
end
if cache !== nothing
cache.env_project_file[env] = project_file
end
return project_file
end
end
function base_project(project_file)
base_dir = abspath(joinpath(dirname(project_file), ".."))
base_project_file = env_project_file(base_dir)
base_project_file isa String || return nothing
d = parsed_toml(base_project_file)
workspace = get(d, "workspace", nothing)::Union{Dict{String, Any}, Nothing}
if workspace === nothing
return nothing
end
projects = get(workspace, "projects", nothing)::Union{Vector{String}, Nothing, String}
projects === nothing && return nothing
if projects isa Vector && basename(dirname(project_file)) in projects
return base_project_file
end
return nothing
end
function project_deps_get(env::String, name::String)::Union{Nothing,PkgId}
project_file = env_project_file(env)
if project_file isa String
pkg_uuid = explicit_project_deps_get(project_file, name)
pkg_uuid === nothing || return PkgId(pkg_uuid, name)
elseif project_file
return implicit_project_deps_get(env, name)
end
return nothing
end
function package_get(project_file, where::PkgId, name::String)
proj = project_file_name_uuid(project_file, where.name)
if proj == where
# if `where` matches the project, use [deps] section as manifest, and stop searching
pkg_uuid = explicit_project_deps_get(project_file, name)
return PkgId(pkg_uuid, name)
end
return nothing
end
function manifest_deps_get(env::String, where::PkgId, name::String)::Union{Nothing,PkgId}
uuid = where.uuid
@assert uuid !== nothing
project_file = env_project_file(env)
if project_file isa String
pkg = package_get(project_file, where, name)
pkg === nothing || return pkg
d = parsed_toml(project_file)
exts = get(d, "extensions", nothing)::Union{Dict{String, Any}, Nothing}
if exts !== nothing
proj = project_file_name_uuid(project_file, where.name)
# Check if `where` is an extension of the project
if where.name in keys(exts) && where.uuid == uuid5(proj.uuid::UUID, where.name)
# Extensions can load weak deps...
weakdeps = get(d, "weakdeps", nothing)::Union{Dict{String, Any}, Nothing}
if weakdeps !== nothing
wuuid = get(weakdeps, name, nothing)::Union{String, Nothing}
if wuuid !== nothing
return PkgId(UUID(wuuid), name)
end
end
# ... and they can load same deps as the project itself
mby_uuid = explicit_project_deps_get(project_file, name)
mby_uuid === nothing || return PkgId(mby_uuid, name)
end
end
# look for manifest file and `where` stanza
return explicit_manifest_deps_get(project_file, where, name)
elseif project_file
# if env names a directory, search it
return implicit_manifest_deps_get(env, where, name)
end
return nothing
end
function manifest_uuid_path(env::String, pkg::PkgId)::Union{Nothing,String,Missing}
project_file = env_project_file(env)
if project_file isa String
proj = project_file_name_uuid(project_file, pkg.name)
if proj == pkg
# if `pkg` matches the project, return the project itself
return project_file_path(project_file, pkg.name)
end
mby_ext = project_file_ext_path(project_file, pkg)
mby_ext === nothing || return mby_ext
# look for manifest file and `where` stanza
return explicit_manifest_uuid_path(project_file, pkg)
elseif project_file
# if env names a directory, search it
proj = implicit_manifest_uuid_path(env, pkg)
proj === nothing || return proj
# if not found
parentid = get(EXT_PRIMED, pkg, nothing)
if parentid !== nothing
_, parent_project_file = entry_point_and_project_file(env, parentid.name)
if parent_project_file !== nothing
parentproj = project_file_name_uuid(parent_project_file, parentid.name)
if parentproj == parentid
mby_ext = project_file_ext_path(parent_project_file, pkg)
mby_ext === nothing || return mby_ext
end
end
end
end
return nothing
end
function find_ext_path(project_path::String, extname::String)
extfiledir = joinpath(project_path, "ext", extname, extname * ".jl")
isfile(extfiledir) && return extfiledir
return joinpath(project_path, "ext", extname * ".jl")
end
function project_file_ext_path(project_file::String, ext::PkgId)
d = parsed_toml(project_file)
p = dirname(project_file)
exts = get(d, "extensions", nothing)::Union{Dict{String, Any}, Nothing}
if exts !== nothing
if ext.name in keys(exts) && ext.uuid == uuid5(UUID(d["uuid"]::String), ext.name)
return find_ext_path(p, ext.name)
end
end
return nothing
end
# find project file's top-level UUID entry (or nothing)
function project_file_name_uuid(project_file::String, name::String)::PkgId
d = parsed_toml(project_file)
uuid′ = get(d, "uuid", nothing)::Union{String, Nothing}
uuid = uuid′ === nothing ? dummy_uuid(project_file) : UUID(uuid′)
name = get(d, "name", name)::String
return PkgId(uuid, name)
end
function project_file_path(project_file::String, name::String)
d = parsed_toml(project_file)
entryfile = get(d, "path", nothing)::Union{String, Nothing}
# "path" entry in project file is soft deprecated
if entryfile === nothing
entryfile = get(d, "entryfile", nothing)::Union{String, Nothing}
end
return entry_path(dirname(project_file), name, entryfile)
end
function workspace_manifest(project_file)
base = base_project(project_file)
if base !== nothing
return project_file_manifest_path(base)
end
return nothing
end
# find project file's corresponding manifest file
function project_file_manifest_path(project_file::String)::Union{Nothing,String}
@lock require_lock begin
cache = LOADING_CACHE[]
if cache !== nothing
manifest_path = get(cache.project_file_manifest_path, project_file, missing)
manifest_path === missing || return manifest_path
end
dir = abspath(dirname(project_file))
d = parsed_toml(project_file)
base_manifest = workspace_manifest(project_file)
if base_manifest !== nothing
return base_manifest
end
explicit_manifest = get(d, "manifest", nothing)::Union{String, Nothing}
manifest_path = nothing
if explicit_manifest !== nothing
manifest_file = normpath(joinpath(dir, explicit_manifest))
if isfile_casesensitive(manifest_file)
manifest_path = manifest_file
end
end
if manifest_path === nothing
for mfst in manifest_names
manifest_file = joinpath(dir, mfst)
if isfile_casesensitive(manifest_file)
manifest_path = manifest_file
break
end
end
end
if cache !== nothing
cache.project_file_manifest_path[project_file] = manifest_path
end
return manifest_path
end
end
# given a directory (implicit env from LOAD_PATH) and a name,
# check if it is an implicit package
function entry_point_and_project_file_inside(dir::String, name::String)::Union{Tuple{Nothing,Nothing},Tuple{String,Nothing},Tuple{String,String}}
path = normpath(joinpath(dir, "src", "$name.jl"))
isfile_casesensitive(path) || return nothing, nothing
for proj in project_names
project_file = normpath(joinpath(dir, proj))
isfile_casesensitive(project_file) || continue
return path, project_file
end
return path, nothing
end
# given a project directory (implicit env from LOAD_PATH) and a name,
# find an entry point for `name`, and see if it has an associated project file
function entry_point_and_project_file(dir::String, name::String)::Union{Tuple{Nothing,Nothing},Tuple{String,Nothing},Tuple{String,String}}
dir_name = joinpath(dir, name)
path, project_file = entry_point_and_project_file_inside(dir_name, name)
path === nothing || return path, project_file
dir_jl = dir_name * ".jl"
path, project_file = entry_point_and_project_file_inside(dir_jl, name)
path === nothing || return path, project_file
# check for less likely case with a bare file and no src directory last to minimize stat calls
path = normpath(joinpath(dir, "$name.jl"))
isfile_casesensitive(path) && return path, nothing
return nothing, nothing
end
# Find the project file for the extension `ext` in the implicit env `dir``
function implicit_env_project_file_extension(dir::String, ext::PkgId)
for pkg in readdir(dir; join=true)
project_file = env_project_file(pkg)
project_file isa String || continue
path = project_file_ext_path(project_file, ext)
if path !== nothing
return path, project_file
end
end
return nothing, nothing
end
# given a path, name, and possibly an entryfile, return the entry point
function entry_path(path::String, name::String, entryfile::Union{Nothing,String})::String
isfile_casesensitive(path) && return normpath(path)
entrypoint = entryfile === nothing ? joinpath("src", "$name.jl") : entryfile
return normpath(joinpath(path, entrypoint))
end
## explicit project & manifest API ##
# find project file root or deps `name => uuid` mapping
# `ext` is the name of the extension if `name` is loaded from one
# return `nothing` if `name` is not found
function explicit_project_deps_get(project_file::String, name::String, ext::Union{String,Nothing}=nothing)::Union{Nothing,UUID}
d = parsed_toml(project_file)
if get(d, "name", nothing)::Union{String, Nothing} === name
root_uuid = dummy_uuid(project_file)
uuid = get(d, "uuid", nothing)::Union{String, Nothing}
return uuid === nothing ? root_uuid : UUID(uuid)
end
deps = get(d, "deps", nothing)::Union{Dict{String, Any}, Nothing}
if deps !== nothing
uuid = get(deps, name, nothing)::Union{String, Nothing}
uuid === nothing || return UUID(uuid)
end
if ext !== nothing
extensions = get(d, "extensions", nothing)
extensions === nothing && return nothing
ext_data = get(extensions, ext, nothing)
ext_data === nothing && return nothing
if (ext_data isa String && name == ext_data) || (ext_data isa Vector{String} && name in ext_data)
weakdeps = get(d, "weakdeps", nothing)::Union{Dict{String, Any}, Nothing}
weakdeps === nothing && return nothing
wuuid = get(weakdeps, name, nothing)::Union{String, Nothing}
wuuid === nothing && return nothing
return UUID(wuuid)
end
end
return nothing
end
function is_v1_format_manifest(raw_manifest::Dict{String})
if haskey(raw_manifest, "manifest_format")
mf = raw_manifest["manifest_format"]
if mf isa Dict{String} && haskey(mf, "uuid")
# the off-chance where an old format manifest has a dep called "manifest_format"
return true
end
return false
else
return true
end
end
# returns a deps list for both old and new manifest formats
function get_deps(raw_manifest::Dict)
if is_v1_format_manifest(raw_manifest)
return raw_manifest
else
# if the manifest has no deps, there won't be a `deps` field
return get(Dict{String, Any}, raw_manifest, "deps")::Dict{String, Any}
end
end
# find `where` stanza and return the PkgId for `name`
# return `nothing` if it did not find `where` (indicating caller should continue searching)
function explicit_manifest_deps_get(project_file::String, where::PkgId, name::String)::Union{Nothing,PkgId}
manifest_file = project_file_manifest_path(project_file)
manifest_file === nothing && return nothing # manifest not found--keep searching LOAD_PATH
d = get_deps(parsed_toml(manifest_file))
found_where = false
found_name = false
for (dep_name, entries) in d
entries::Vector{Any}
for entry in entries
entry = entry::Dict{String, Any}
uuid = get(entry, "uuid", nothing)::Union{String, Nothing}
uuid === nothing && continue
# deps is either a list of names (deps = ["DepA", "DepB"]) or
# a table of entries (deps = {"DepA" = "6ea...", "DepB" = "55d..."}
deps = get(entry, "deps", nothing)::Union{Vector{String}, Dict{String, Any}, Nothing}
if UUID(uuid) === where.uuid
found_where = true
if deps isa Vector{String}
found_name = name in deps
found_name && @goto done
elseif deps isa Dict{String, Any}
deps = deps::Dict{String, Any}
for (dep, uuid) in deps
uuid::String
if dep === name
return PkgId(UUID(uuid), name)
end
end
end
else # Check for extensions
extensions = get(entry, "extensions", nothing)
if extensions !== nothing
if haskey(extensions, where.name) && where.uuid == uuid5(UUID(uuid), where.name)
found_where = true
if name == dep_name
return PkgId(UUID(uuid), name)