/
kernel_require.rb
90 lines (81 loc) · 2.77 KB
/
kernel_require.rb
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
# frozen_string_literal: true
module Bootsnap
module LoadPathCache
module CoreExt
def self.make_load_error(path)
err = LoadError.new(+"cannot load such file -- #{path}")
err.instance_variable_set(Bootsnap::LoadPathCache::ERROR_TAG_IVAR, true)
err.define_singleton_method(:path) { path }
err
end
end
end
end
module Kernel
module_function # rubocop:disable Style/ModuleFunction
alias_method(:require_without_bootsnap, :require)
# Note that require registers to $LOADED_FEATURES while load does not.
def require_with_bootsnap_lfi(path, resolved = nil)
Bootsnap::LoadPathCache.loaded_features_index.register(path, resolved) do
require_without_bootsnap(resolved || path)
end
end
def require(path)
return false if Bootsnap::LoadPathCache.loaded_features_index.key?(path)
if (resolved = Bootsnap::LoadPathCache.load_path_cache.find(path))
return require_with_bootsnap_lfi(path, resolved)
end
raise(Bootsnap::LoadPathCache::CoreExt.make_load_error(path))
rescue LoadError => e
e.instance_variable_set(Bootsnap::LoadPathCache::ERROR_TAG_IVAR, true)
raise(e)
rescue Bootsnap::LoadPathCache::ReturnFalse
false
rescue Bootsnap::LoadPathCache::FallbackScan
fallback = true
ensure
if fallback
require_with_bootsnap_lfi(path)
end
end
alias_method(:require_relative_without_bootsnap, :require_relative)
def require_relative(path)
location = caller_locations(1..1).first
realpath = Bootsnap::LoadPathCache.realpath_cache.call(
location.absolute_path || location.path, path
)
require(realpath)
end
alias_method(:load_without_bootsnap, :load)
def load(path, wrap = false)
if (resolved = Bootsnap::LoadPathCache.load_path_cache.find(path, try_extensions: false))
load_without_bootsnap(resolved, wrap)
else
load_without_bootsnap(path, wrap)
end
end
end
class Module
alias_method(:autoload_without_bootsnap, :autoload)
def autoload(const, path)
# NOTE: This may defeat LoadedFeaturesIndex, but it's not immediately
# obvious how to make it work. This feels like a pretty niche case, unclear
# if it will ever burn anyone.
#
# The challenge is that we don't control the point at which the entry gets
# added to $LOADED_FEATURES and won't be able to hook that modification
# since it's done in C-land.
autoload_without_bootsnap(const, Bootsnap::LoadPathCache.load_path_cache.find(path) || path)
rescue LoadError => e
e.instance_variable_set(Bootsnap::LoadPathCache::ERROR_TAG_IVAR, true)
raise(e)
rescue Bootsnap::LoadPathCache::ReturnFalse
false
rescue Bootsnap::LoadPathCache::FallbackScan
fallback = true
ensure
if fallback
autoload_without_bootsnap(const, path)
end
end
end