/
gem.rb
398 lines (326 loc) · 11.8 KB
/
gem.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
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
# typed: strict
# frozen_string_literal: true
module Tapioca
module Commands
class Gem < Command
include SorbetHelper
include RBIHelper
sig do
params(
gem_names: T::Array[String],
exclude: T::Array[String],
prerequire: T.nilable(String),
postrequire: String,
typed_overrides: T::Hash[String, String],
outpath: Pathname,
file_header: T::Boolean,
doc: T::Boolean,
include_exported_rbis: T::Boolean,
number_of_workers: T.nilable(Integer),
auto_strictness: T::Boolean,
dsl_dir: String,
rbi_formatter: RBIFormatter
).void
end
def initialize(
gem_names:,
exclude:,
prerequire:,
postrequire:,
typed_overrides:,
outpath:,
file_header:,
doc:,
include_exported_rbis:,
number_of_workers: nil,
auto_strictness: true,
dsl_dir: DEFAULT_DSL_DIR,
rbi_formatter: DEFAULT_RBI_FORMATTER
)
@gem_names = gem_names
@exclude = exclude
@prerequire = prerequire
@postrequire = postrequire
@typed_overrides = typed_overrides
@outpath = outpath
@file_header = file_header
@number_of_workers = number_of_workers
@auto_strictness = auto_strictness
@dsl_dir = dsl_dir
@rbi_formatter = rbi_formatter
super()
@loader = T.let(nil, T.nilable(Runtime::Loader))
@bundle = T.let(nil, T.nilable(Gemfile))
@existing_rbis = T.let(nil, T.nilable(T::Hash[String, String]))
@expected_rbis = T.let(nil, T.nilable(T::Hash[String, String]))
@doc = T.let(doc, T::Boolean)
@include_exported_rbis = include_exported_rbis
end
sig { override.void }
def execute
require_gem_file
gem_queue = gems_to_generate(@gem_names).reject { |gem| @exclude.include?(gem.name) }
anything_done = [
perform_removals,
gem_queue.any?,
].any?
Executor.new(gem_queue, number_of_workers: @number_of_workers).run_in_parallel do |gem|
shell.indent do
compile_gem_rbi(gem)
puts
end
end
if anything_done
validate_rbi_files(
command: default_command(:gem, @gem_names.join(" ")),
gem_dir: @outpath.to_s,
dsl_dir: @dsl_dir,
auto_strictness: @auto_strictness,
gems: bundle.dependencies
)
say("All operations performed in working directory.", [:green, :bold])
say("Please review changes and commit them.", [:green, :bold])
else
say("No operations performed, all RBIs are up-to-date.", [:green, :bold])
end
end
sig { params(should_verify: T::Boolean).void }
def sync(should_verify: false)
if should_verify
say("Checking for out-of-date RBIs...")
say("")
perform_sync_verification
return
end
anything_done = [
perform_removals,
perform_additions,
].any?
if anything_done
validate_rbi_files(
command: default_command(:gem),
gem_dir: @outpath.to_s,
dsl_dir: @dsl_dir,
auto_strictness: @auto_strictness,
gems: bundle.dependencies
)
say("All operations performed in working directory.", [:green, :bold])
say("Please review changes and commit them.", [:green, :bold])
else
say("No operations performed, all RBIs are up-to-date.", [:green, :bold])
end
puts
end
private
sig { returns(Runtime::Loader) }
def loader
@loader ||= Runtime::Loader.new
end
sig { returns(Gemfile) }
def bundle
@bundle ||= Gemfile.new(@exclude)
end
sig { void }
def require_gem_file
say("Requiring all gems to prepare for compiling... ")
begin
loader.load_bundle(bundle, @prerequire, @postrequire)
rescue LoadError => e
explain_failed_require(@postrequire, e)
exit(1)
end
Runtime::Trackers::Autoload.eager_load_all!
say(" Done", :green)
unless bundle.missing_specs.empty?
say(" completed with missing specs: ")
say(bundle.missing_specs.join(", "), :yellow)
end
puts
end
sig { params(gem_names: T::Array[String]).returns(T::Array[Gemfile::GemSpec]) }
def gems_to_generate(gem_names)
return bundle.dependencies if gem_names.empty?
gem_names.map do |gem_name|
gem = bundle.gem(gem_name)
if gem.nil?
say("Error: Cannot find gem '#{gem_name}'", :red)
exit(1)
end
gem
end
end
sig { params(gem: Gemfile::GemSpec).void }
def compile_gem_rbi(gem)
gem_name = set_color(gem.name, :yellow, :bold)
rbi = RBI::File.new(strictness: @typed_overrides[gem.name] || "true")
@rbi_formatter.write_header!(rbi,
default_command(:gem, gem.name),
reason: "types exported from the `#{gem.name}` gem",) if @file_header
rbi.root = Tapioca::Gem::Pipeline.new(gem, include_doc: @doc).compile
merge_with_exported_rbi(gem, rbi) if @include_exported_rbis
if rbi.empty?
@rbi_formatter.write_empty_body_comment!(rbi)
say("Compiled #{gem_name} (empty output)", :yellow)
else
say("Compiled #{gem_name}", :green)
end
rbi_string = @rbi_formatter.print_file(rbi)
create_file(@outpath / gem.rbi_file_name, rbi_string)
T.unsafe(Pathname).glob((@outpath / "#{gem.name}@*.rbi").to_s) do |file|
remove_file(file) unless file.basename.to_s == gem.rbi_file_name
end
end
sig { void }
def perform_sync_verification
diff = {}
removed_rbis.each do |gem_name|
filename = existing_rbi(gem_name)
diff[filename] = :removed
end
added_rbis.each do |gem_name|
filename = expected_rbi(gem_name)
diff[filename] = gem_rbi_exists?(gem_name) ? :changed : :added
end
report_diff_and_exit_if_out_of_date(diff, :gem)
end
sig { void }
def perform_removals
say("Removing RBI files of gems that have been removed:", [:blue, :bold])
puts
anything_done = T.let(false, T::Boolean)
gems = removed_rbis
shell.indent do
if gems.empty?
say("Nothing to do.")
else
gems.each do |removed|
filename = existing_rbi(removed)
remove_file(filename)
end
anything_done = true
end
end
puts
anything_done
end
sig { void }
def perform_additions
say("Generating RBI files of gems that are added or updated:", [:blue, :bold])
puts
anything_done = T.let(false, T::Boolean)
gems = added_rbis
shell.indent do
if gems.empty?
say("Nothing to do.")
else
require_gem_file
Executor.new(gems, number_of_workers: @number_of_workers).run_in_parallel do |gem_name|
filename = expected_rbi(gem_name)
if gem_rbi_exists?(gem_name)
old_filename = existing_rbi(gem_name)
move(old_filename, filename) unless old_filename == filename
end
gem = T.must(bundle.gem(gem_name))
compile_gem_rbi(gem)
puts
end
end
anything_done = true
end
puts
anything_done
end
sig { params(file: String, error: LoadError).void }
def explain_failed_require(file, error)
say_error("\n\nLoadError: #{error}", :bold, :red)
say_error("\nTapioca could not load all the gems required by your application.", :yellow)
say_error("If you populated ", :yellow)
say_error("#{file} ", :bold, :blue)
say_error("with ", :yellow)
say_error("`#{default_command(:require)}`", :bold, :blue)
say_error("you should probably review it and remove the faulty line.", :yellow)
end
sig { returns(T::Array[String]) }
def removed_rbis
(existing_rbis.keys - expected_rbis.keys).sort
end
sig { params(gem_name: String).returns(Pathname) }
def existing_rbi(gem_name)
gem_rbi_filename(gem_name, T.must(existing_rbis[gem_name]))
end
sig { returns(T::Array[String]) }
def added_rbis
expected_rbis.select do |name, value|
existing_rbis[name] != value
end.keys.sort
end
sig { params(gem_name: String).returns(Pathname) }
def expected_rbi(gem_name)
gem_rbi_filename(gem_name, T.must(expected_rbis[gem_name]))
end
sig { params(gem_name: String).returns(T::Boolean) }
def gem_rbi_exists?(gem_name)
existing_rbis.key?(gem_name)
end
sig { params(diff: T::Hash[String, Symbol], command: Symbol).void }
def report_diff_and_exit_if_out_of_date(diff, command)
if diff.empty?
say("Nothing to do, all RBIs are up-to-date.")
else
say("RBI files are out-of-date. In your development environment, please run:", :green)
say(" `#{default_command(command)}`", [:green, :bold])
say("Once it is complete, be sure to commit and push any changes", :green)
say("")
say("Reason:", [:red])
diff.group_by(&:last).sort.each do |cause, diff_for_cause|
say(build_error_for_files(cause, diff_for_cause.map(&:first)))
end
exit(1)
end
end
sig { params(old_filename: Pathname, new_filename: Pathname).void }
def move(old_filename, new_filename)
say("-> Moving: #{old_filename} to #{new_filename}")
old_filename.rename(new_filename.to_s)
end
sig { returns(T::Hash[String, String]) }
def existing_rbis
@existing_rbis ||= Pathname.glob((@outpath / "*@*.rbi").to_s)
.to_h { |f| T.cast(f.basename(".*").to_s.split("@", 2), [String, String]) }
end
sig { returns(T::Hash[String, String]) }
def expected_rbis
@expected_rbis ||= bundle.dependencies
.reject { |gem| @exclude.include?(gem.name) }
.to_h { |gem| [gem.name, gem.version.to_s] }
end
sig { params(gem_name: String, version: String).returns(Pathname) }
def gem_rbi_filename(gem_name, version)
@outpath / "#{gem_name}@#{version}.rbi"
end
sig { params(cause: Symbol, files: T::Array[String]).returns(String) }
def build_error_for_files(cause, files)
" File(s) #{cause}:\n - #{files.join("\n - ")}"
end
sig { params(gem: Gemfile::GemSpec, file: RBI::File).void }
def merge_with_exported_rbi(gem, file)
return file unless gem.export_rbi_files?
tree = gem.exported_rbi_tree
unless tree.conflicts.empty?
say_error("\n\n RBIs exported by `#{gem.name}` contain conflicts and can't be used:", :yellow)
tree.conflicts.each do |conflict|
say_error("\n #{conflict}", :yellow)
say_error(" Found at:", :yellow)
say_error(" #{conflict.left.loc}", :yellow)
say_error(" #{conflict.right.loc}", :yellow)
end
return file
end
file.root = RBI::Rewriters::Merge.merge_trees(file.root, tree, keep: RBI::Rewriters::Merge::Keep::LEFT)
rescue RBI::ParseError => e
say_error("\n\n RBIs exported by `#{gem.name}` contain errors and can't be used:", :yellow)
say_error("Cause: #{e.message} (#{e.location})")
end
end
end
end