forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lockfile.zig
4283 lines (3709 loc) · 174 KB
/
lockfile.zig
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
const std = @import("std");
const Allocator = std.mem.Allocator;
const bun = @import("root").bun;
const string = bun.string;
const Output = bun.Output;
const Global = bun.Global;
const Environment = bun.Environment;
const strings = bun.strings;
const MutableString = bun.MutableString;
const stringZ = bun.stringZ;
const default_allocator = bun.default_allocator;
const C = bun.C;
const JSAst = bun.JSAst;
const JSLexer = bun.js_lexer;
const logger = bun.logger;
const js_parser = bun.js_parser;
const Expr = @import("../js_ast.zig").Expr;
const json_parser = bun.JSON;
const JSPrinter = bun.js_printer;
const linker = @import("../linker.zig");
const sync = @import("../sync.zig");
const Api = @import("../api/schema.zig").Api;
const Path = @import("../resolver/resolve_path.zig");
const configureTransformOptionsForBun = @import("../bun.js/config.zig").configureTransformOptionsForBun;
const Command = @import("../cli.zig").Command;
const BunArguments = @import("../cli.zig").Arguments;
const bundler = bun.bundler;
const DotEnv = @import("../env_loader.zig");
const which = @import("../which.zig").which;
const Run = @import("../bun_js.zig").Run;
const HeaderBuilder = bun.HTTP.HeaderBuilder;
const Fs = @import("../fs.zig");
const FileSystem = Fs.FileSystem;
const Lock = @import("../lock.zig").Lock;
const URL = @import("../url.zig").URL;
const AsyncHTTP = bun.HTTP.AsyncHTTP;
const HTTPChannel = bun.HTTP.HTTPChannel;
const NetworkThread = bun.HTTP.NetworkThread;
const Integrity = @import("./integrity.zig").Integrity;
const clap = bun.clap;
const ExtractTarball = @import("./extract_tarball.zig");
const Npm = @import("./npm.zig");
const Bitset = bun.bit_set.DynamicBitSetUnmanaged;
const z_allocator = @import("../memory_allocator.zig").z_allocator;
const Lockfile = @This();
const IdentityContext = @import("../identity_context.zig").IdentityContext;
const ArrayIdentityContext = @import("../identity_context.zig").ArrayIdentityContext;
const Semver = @import("./semver.zig");
const ExternalString = Semver.ExternalString;
const String = Semver.String;
const GlobalStringBuilder = @import("../string_builder.zig");
const SlicedString = Semver.SlicedString;
const Repository = @import("./repository.zig").Repository;
const Bin = @import("./bin.zig").Bin;
const Dependency = @import("./dependency.zig");
const Behavior = Dependency.Behavior;
const FolderResolution = @import("./resolvers/folder_resolver.zig").FolderResolution;
const Install = @import("./install.zig");
const Aligner = Install.Aligner;
const alignment_bytes_to_repeat_buffer = Install.alignment_bytes_to_repeat_buffer;
const PackageManager = Install.PackageManager;
const DependencyID = Install.DependencyID;
const ExternalSlice = Install.ExternalSlice;
const ExternalSliceAligned = Install.ExternalSliceAligned;
const ExternalStringList = Install.ExternalStringList;
const ExternalStringMap = Install.ExternalStringMap;
const Features = Install.Features;
const initializeStore = Install.initializeStore;
const invalid_package_id = Install.invalid_package_id;
const Origin = Install.Origin;
const PackageID = Install.PackageID;
const PackageInstall = Install.PackageInstall;
const PackageNameHash = Install.PackageNameHash;
const Resolution = @import("./resolution.zig").Resolution;
const Crypto = @import("../sha.zig").Hashers;
const PackageJSON = @import("../resolver/package_json.zig").PackageJSON;
const MetaHash = [std.crypto.hash.sha2.Sha512256.digest_length]u8;
const zero_hash = std.mem.zeroes(MetaHash);
const NameHashMap = std.ArrayHashMapUnmanaged(u32, String, ArrayIdentityContext, false);
const NameHashSet = std.ArrayHashMapUnmanaged(u32, void, ArrayIdentityContext, false);
const VersionHashMap = std.ArrayHashMapUnmanaged(u32, Semver.Version, ArrayIdentityContext, false);
// Serialized data
/// The version of the lockfile format, intended to prevent data corruption for format changes.
format: FormatVersion = .v1,
meta_hash: MetaHash = zero_hash,
packages: Lockfile.Package.List = .{},
buffers: Buffers = .{},
/// name -> PackageID || [*]PackageID
/// Not for iterating.
package_index: PackageIndex.Map,
string_pool: StringPool,
allocator: Allocator,
scratch: Scratch = .{},
scripts: Scripts = .{},
trusted_dependencies: NameHashSet = .{},
workspace_paths: NameHashMap = .{},
workspace_versions: VersionHashMap = .{},
const Stream = std.io.FixedBufferStream([]u8);
pub const default_filename = "bun.lockb";
pub const Scripts = struct {
const Entry = struct {
cwd: string,
script: string,
};
const Entries = std.ArrayListUnmanaged(Entry);
const RunCommand = @import("../cli/run_command.zig").RunCommand;
preinstall: Entries = .{},
install: Entries = .{},
postinstall: Entries = .{},
preprepare: Entries = .{},
prepare: Entries = .{},
postprepare: Entries = .{},
pub fn hasAny(this: *Scripts) bool {
inline for (Package.Scripts.Hooks) |hook| {
if (@field(this, hook).items.len > 0) return true;
}
return false;
}
pub fn run(this: *Scripts, allocator: Allocator, env: *DotEnv.Loader, silent: bool, comptime hook: []const u8) !void {
for (@field(this, hook).items) |entry| {
if (comptime Environment.allow_assert) std.debug.assert(Fs.FileSystem.instance_loaded);
_ = try RunCommand.runPackageScript(allocator, entry.script, hook, entry.cwd, env, &.{}, silent);
}
}
pub fn deinit(this: *Scripts, allocator: Allocator) void {
inline for (Package.Scripts.Hooks) |hook| {
const list = &@field(this, hook);
for (list.items) |entry| {
allocator.free(entry.cwd);
allocator.free(entry.script);
}
list.deinit(allocator);
}
}
};
pub fn isEmpty(this: *const Lockfile) bool {
return this.packages.len == 0 or this.packages.len == 1 or this.packages.get(0).resolutions.len == 0;
}
pub const LoadFromDiskResult = union(Tag) {
not_found: void,
err: struct {
step: Step,
value: anyerror,
},
ok: *Lockfile,
pub const Step = enum { open_file, read_file, parse_file };
pub const Tag = enum {
not_found,
err,
ok,
};
};
pub fn loadFromDisk(this: *Lockfile, allocator: Allocator, log: *logger.Log, filename: stringZ) LoadFromDiskResult {
if (comptime Environment.allow_assert) std.debug.assert(FileSystem.instance_loaded);
var file = std.io.getStdIn();
if (filename.len > 0)
file = std.fs.cwd().openFileZ(filename, .{ .mode = .read_only }) catch |err| {
return switch (err) {
error.FileNotFound, error.AccessDenied, error.BadPathName => LoadFromDiskResult{ .not_found = {} },
else => LoadFromDiskResult{ .err = .{ .step = .open_file, .value = err } },
};
};
defer file.close();
var buf = file.readToEndAlloc(allocator, std.math.maxInt(usize)) catch |err| {
return LoadFromDiskResult{ .err = .{ .step = .read_file, .value = err } };
};
return this.loadFromBytes(buf, allocator, log);
}
pub fn loadFromBytes(this: *Lockfile, buf: []u8, allocator: Allocator, log: *logger.Log) LoadFromDiskResult {
var stream = Stream{ .buffer = buf, .pos = 0 };
this.format = FormatVersion.current;
this.scripts = .{};
this.trusted_dependencies = .{};
this.workspace_paths = .{};
this.workspace_versions = .{};
Lockfile.Serializer.load(this, &stream, allocator, log) catch |err| {
return LoadFromDiskResult{ .err = .{ .step = .parse_file, .value = err } };
};
return LoadFromDiskResult{ .ok = this };
}
pub const InstallResult = struct {
lockfile: *Lockfile,
summary: PackageInstall.Summary,
};
pub const Tree = struct {
id: Id = invalid_id,
dependency_id: DependencyID = invalid_package_id,
parent: Id = invalid_id,
dependencies: Lockfile.DependencyIDSlice = .{},
pub const external_size = @sizeOf(Id) + @sizeOf(PackageID) + @sizeOf(Id) + @sizeOf(Lockfile.DependencyIDSlice);
pub const External = [external_size]u8;
pub const Slice = ExternalSlice(Tree);
pub const List = std.ArrayListUnmanaged(Tree);
pub const Id = u32;
pub fn toExternal(this: Tree) External {
var out = External{};
out[0..4].* = @as(Id, @bitCast(this.id));
out[4..8].* = @as(Id, @bitCast(this.dependency_id));
out[8..12].* = @as(Id, @bitCast(this.parent));
out[12..16].* = @as(u32, @bitCast(this.dependencies.off));
out[16..20].* = @as(u32, @bitCast(this.dependencies.len));
if (out.len != 20) @compileError("Tree.External is not 20 bytes");
return out;
}
pub fn toTree(out: External) Tree {
return .{
.id = @as(Id, @bitCast(out[0..4].*)),
.dependency_id = @as(Id, @bitCast(out[4..8].*)),
.parent = @as(Id, @bitCast(out[8..12].*)),
.dependencies = .{
.off = @as(u32, @bitCast(out[12..16].*)),
.len = @as(u32, @bitCast(out[16..20].*)),
},
};
}
pub const root_dep_id: DependencyID = invalid_package_id - 1;
const invalid_id: Id = std.math.maxInt(Id);
const dependency_loop = invalid_id - 1;
const hoisted = invalid_id - 2;
const error_id = hoisted;
const SubtreeError = error{ OutOfMemory, DependencyLoop };
pub const NodeModulesFolder = struct {
relative_path: stringZ,
dependencies: []const DependencyID,
};
pub const Iterator = struct {
trees: []const Tree,
dependency_ids: []const DependencyID,
dependencies: []const Dependency,
resolutions: []const PackageID,
tree_id: Id = 0,
path_buf: [bun.MAX_PATH_BYTES]u8 = undefined,
path_buf_len: usize = 0,
last_parent: Id = invalid_id,
string_buf: string,
// max number of node_modules folders
depth_stack: [(bun.MAX_PATH_BYTES / "node_modules".len) + 1]Id = undefined,
pub fn init(lockfile: *const Lockfile) Iterator {
return .{
.trees = lockfile.buffers.trees.items,
.dependency_ids = lockfile.buffers.hoisted_dependencies.items,
.dependencies = lockfile.buffers.dependencies.items,
.resolutions = lockfile.buffers.resolutions.items,
.string_buf = lockfile.buffers.string_bytes.items,
};
}
pub fn nextNodeModulesFolder(this: *Iterator) ?NodeModulesFolder {
if (this.tree_id >= this.trees.len) return null;
while (this.trees[this.tree_id].dependencies.len == 0) {
this.tree_id += 1;
if (this.tree_id >= this.trees.len) return null;
}
const tree = this.trees[this.tree_id];
const string_buf = this.string_buf;
{
// For now, the dumb way
// (the smart way is avoiding this copy)
this.path_buf[0.."node_modules".len].* = "node_modules".*;
var parent_id = tree.id;
var path_written: usize = "node_modules".len;
this.depth_stack[0] = 0;
if (tree.id > 0) {
var depth_buf_len: usize = 1;
while (parent_id > 0 and parent_id < @as(Id, @intCast(this.trees.len))) {
this.depth_stack[depth_buf_len] = parent_id;
parent_id = this.trees[parent_id].parent;
depth_buf_len += 1;
}
depth_buf_len -= 1;
while (depth_buf_len > 0) : (depth_buf_len -= 1) {
this.path_buf[path_written] = std.fs.path.sep;
path_written += 1;
const tree_id = this.depth_stack[depth_buf_len];
const name = this.dependencies[this.trees[tree_id].dependency_id].name.slice(string_buf);
bun.copy(u8, this.path_buf[path_written..], name);
path_written += name.len;
this.path_buf[path_written..][0.."/node_modules".len].* = (std.fs.path.sep_str ++ "node_modules").*;
path_written += "/node_modules".len;
}
}
this.path_buf[path_written] = 0;
this.path_buf_len = path_written;
}
this.tree_id += 1;
var relative_path: [:0]u8 = this.path_buf[0..this.path_buf_len :0];
return .{
.relative_path = relative_path,
.dependencies = tree.dependencies.get(this.dependency_ids),
};
}
};
const Builder = struct {
allocator: Allocator,
name_hashes: []const PackageNameHash,
list: ArrayList = .{},
resolutions: []const PackageID,
dependencies: []const Dependency,
resolution_lists: []const Lockfile.DependencyIDSlice,
queue: Lockfile.TreeFiller,
log: *logger.Log,
old_lockfile: *Lockfile,
pub fn maybeReportError(this: *Builder, comptime fmt: string, args: anytype) void {
this.log.addErrorFmt(null, logger.Loc.Empty, this.allocator, fmt, args) catch {};
}
pub fn buf(this: *const Builder) []const u8 {
return this.old_lockfile.buffers.string_bytes.items;
}
pub fn packageName(this: *Builder, id: PackageID) String.Formatter {
return this.old_lockfile.packages.items(.name)[id].fmt(this.old_lockfile.buffers.string_bytes.items);
}
pub fn packageVersion(this: *Builder, id: PackageID) Resolution.Formatter {
return this.old_lockfile.packages.items(.resolution)[id].fmt(this.old_lockfile.buffers.string_bytes.items);
}
pub const Entry = struct {
tree: Tree,
dependencies: Lockfile.DependencyIDList,
};
pub const ArrayList = std.MultiArrayList(Entry);
/// Flatten the multi-dimensional ArrayList of package IDs into a single easily serializable array
pub fn clean(this: *Builder) !DependencyIDList {
const end = @as(Id, @truncate(this.list.len));
var i: Id = 0;
var total: u32 = 0;
var trees = this.list.items(.tree);
var dependencies = this.list.items(.dependencies);
while (i < end) : (i += 1) {
total += trees[i].dependencies.len;
}
var dependency_ids = try DependencyIDList.initCapacity(z_allocator, total);
var next = PackageIDSlice{};
for (trees, dependencies) |*tree, *child| {
if (tree.dependencies.len > 0) {
const len = @as(PackageID, @truncate(child.items.len));
next.off += next.len;
next.len = len;
tree.dependencies = next;
dependency_ids.appendSliceAssumeCapacity(child.items);
child.deinit(this.allocator);
}
}
this.queue.deinit();
return dependency_ids;
}
};
pub fn processSubtree(
this: *const Tree,
dependency_id: DependencyID,
builder: *Builder,
) SubtreeError!void {
const package_id = switch (dependency_id) {
root_dep_id => 0,
else => |id| builder.resolutions[id],
};
const resolution_list = builder.resolution_lists[package_id];
if (resolution_list.len == 0) return;
try builder.list.append(builder.allocator, .{
.tree = .{
.parent = this.id,
.id = @as(Id, @truncate(builder.list.len)),
.dependency_id = dependency_id,
},
.dependencies = .{},
});
const list_slice = builder.list.slice();
const trees = list_slice.items(.tree);
const dependency_lists = list_slice.items(.dependencies);
const next: *Tree = &trees[builder.list.len - 1];
const name_hashes: []const PackageNameHash = builder.name_hashes;
const max_package_id = @as(PackageID, @truncate(name_hashes.len));
var dep_id = resolution_list.off;
const end = dep_id + resolution_list.len;
while (dep_id < end) : (dep_id += 1) {
const pid = builder.resolutions[dep_id];
// Skip unresolved packages, e.g. "peerDependencies"
if (pid >= max_package_id) continue;
const dependency = builder.dependencies[dep_id];
// Do not hoist aliased packages
const destination = if (dependency.name_hash != name_hashes[pid])
next.id
else
next.hoistDependency(
true,
pid,
dep_id,
&dependency,
dependency_lists,
trees,
builder,
) catch |err| return err;
switch (destination) {
Tree.dependency_loop, Tree.hoisted => continue,
else => {
dependency_lists[destination].append(builder.allocator, dep_id) catch unreachable;
trees[destination].dependencies.len += 1;
if (builder.resolution_lists[pid].len > 0) {
try builder.queue.writeItem(.{
.tree_id = destination,
.dependency_id = dep_id,
});
}
},
}
}
if (next.dependencies.len == 0) {
if (comptime Environment.allow_assert) std.debug.assert(builder.list.len == next.id + 1);
_ = builder.list.pop();
}
}
// This function does one of three things:
// - de-duplicate (skip) the package
// - move the package to the top directory
// - leave the package at the same (relative) directory
fn hoistDependency(
this: *Tree,
comptime as_defined: bool,
package_id: PackageID,
dependency_id: DependencyID,
dependency: *const Dependency,
dependency_lists: []Lockfile.DependencyIDList,
trees: []Tree,
builder: *Builder,
) !Id {
const this_dependencies = this.dependencies.get(dependency_lists[this.id].items);
for (this_dependencies) |dep_id| {
const dep = builder.dependencies[dep_id];
if (dep.name_hash != dependency.name_hash) continue;
if (builder.resolutions[dep_id] != package_id) {
if (as_defined and !dep.behavior.isPeer()) {
builder.maybeReportError("Package \"{}@{}\" has a dependency loop\n Resolution: \"{}@{}\"\n Dependency: \"{}@{}\"", .{
builder.packageName(package_id),
builder.packageVersion(package_id),
builder.packageName(builder.resolutions[dep_id]),
builder.packageVersion(builder.resolutions[dep_id]),
dependency.name.fmt(builder.buf()),
dependency.version.literal.fmt(builder.buf()),
});
return error.DependencyLoop;
}
// ignore versioning conflicts caused by peer dependencies
return dependency_loop;
}
return hoisted;
}
if (this.parent < error_id) {
const id = trees[this.parent].hoistDependency(
false,
package_id,
dependency_id,
dependency,
dependency_lists,
trees,
builder,
) catch unreachable;
if (!as_defined or id != dependency_loop) return id;
}
return this.id;
}
};
/// This conditonally clones the lockfile with root packages marked as non-resolved
/// that do not satisfy `Features`. The package may still end up installed even
/// if it was e.g. in "devDependencies" and its a production install. In that case,
/// it would be installed because another dependency or transient dependency needed it.
///
/// Warning: This potentially modifies the existing lockfile in-place. That is
/// safe to do because at this stage, the lockfile has already been saved to disk.
/// Our in-memory representation is all that's left.
pub fn maybeCloneFilteringRootPackages(
old: *Lockfile,
features: Features,
exact_versions: bool,
) !*Lockfile {
const old_root_dependenices_list = old.packages.items(.dependencies)[0];
var old_root_resolutions = old.packages.items(.resolutions)[0];
const root_dependencies = old_root_dependenices_list.get(old.buffers.dependencies.items);
var resolutions = old_root_resolutions.mut(old.buffers.resolutions.items);
var any_changes = false;
const end = @as(PackageID, @truncate(old.packages.len));
for (root_dependencies, resolutions) |dependency, *resolution| {
if (!dependency.behavior.isEnabled(features) and resolution.* < end) {
resolution.* = invalid_package_id;
any_changes = true;
}
}
if (!any_changes) return old;
return try old.clean(&.{}, exact_versions);
}
fn preprocessUpdateRequests(old: *Lockfile, updates: []PackageManager.UpdateRequest, exact_versions: bool) !void {
const root_deps_list: Lockfile.DependencySlice = old.packages.items(.dependencies)[0];
if (@as(usize, root_deps_list.off) < old.buffers.dependencies.items.len) {
var string_builder = old.stringBuilder();
{
const root_deps: []const Dependency = root_deps_list.get(old.buffers.dependencies.items);
const old_resolutions_list = old.packages.items(.resolutions)[0];
const old_resolutions: []const PackageID = old_resolutions_list.get(old.buffers.resolutions.items);
const resolutions_of_yore: []const Resolution = old.packages.items(.resolution);
for (updates) |update| {
if (update.version.tag == .uninitialized) {
for (root_deps, old_resolutions) |dep, old_resolution| {
if (dep.name_hash == String.Builder.stringHash(update.name)) {
if (old_resolution > old.packages.len) continue;
const res = resolutions_of_yore[old_resolution];
const len = switch (exact_versions) {
false => std.fmt.count("^{}", .{res.value.npm.fmt(old.buffers.string_bytes.items)}),
true => std.fmt.count("{}", .{res.value.npm.fmt(old.buffers.string_bytes.items)}),
};
if (len >= String.max_inline_len) {
string_builder.cap += len;
}
}
}
}
}
}
try string_builder.allocate();
defer string_builder.clamp();
{
var temp_buf: [513]u8 = undefined;
var root_deps: []Dependency = root_deps_list.mut(old.buffers.dependencies.items);
const old_resolutions_list_lists = old.packages.items(.resolutions);
const old_resolutions_list = old_resolutions_list_lists[0];
const old_resolutions: []const PackageID = old_resolutions_list.get(old.buffers.resolutions.items);
const resolutions_of_yore: []const Resolution = old.packages.items(.resolution);
for (updates) |*update| {
if (update.version.tag == .uninitialized) {
for (root_deps, old_resolutions) |*dep, old_resolution| {
if (dep.name_hash == String.Builder.stringHash(update.name)) {
if (old_resolution > old.packages.len) continue;
const res = resolutions_of_yore[old_resolution];
var buf = switch (exact_versions) {
false => std.fmt.bufPrint(&temp_buf, "^{}", .{res.value.npm.fmt(old.buffers.string_bytes.items)}) catch break,
true => std.fmt.bufPrint(&temp_buf, "{}", .{res.value.npm.fmt(old.buffers.string_bytes.items)}) catch break,
};
const external_version = string_builder.append(ExternalString, buf);
const sliced = external_version.value.sliced(old.buffers.string_bytes.items);
dep.version = Dependency.parse(
old.allocator,
dep.name,
sliced.slice,
&sliced,
null,
) orelse Dependency.Version{};
}
}
}
update.e_string = null;
}
}
}
}
pub fn clean(
old: *Lockfile,
updates: []PackageManager.UpdateRequest,
exact_versions: bool,
) !*Lockfile {
// This is wasteful, but we rarely log anything so it's fine.
var log = logger.Log.init(bun.default_allocator);
defer {
for (log.msgs.items) |*item| {
item.deinit(bun.default_allocator);
}
log.deinit();
}
return old.cleanWithLogger(updates, &log, exact_versions);
}
pub fn cleanWithLogger(
old: *Lockfile,
updates: []PackageManager.UpdateRequest,
log: *logger.Log,
exact_versions: bool,
) !*Lockfile {
const old_trusted_dependencies = old.trusted_dependencies;
const old_scripts = old.scripts;
// We will only shrink the number of packages here.
// never grow
if (updates.len > 0) {
try old.preprocessUpdateRequests(updates, exact_versions);
}
// Deduplication works like this
// Go through *already* resolved package versions
// Ask, do any of those versions happen to match a lower version?
// If yes, choose that version instead.
// Why lower?
//
// Normally, the problem is looks like this:
// Package A: "react@^17"
// Package B: "[email protected]
//
// Now you have two copies of React.
// When you really only wanted one.
// Since _typically_ the issue is that Semver ranges with "^" or "~" say "choose latest", we end up with latest
// if (options.enable.deduplicate_packages) {
// var resolutions: []PackageID = old.buffers.resolutions.items;
// const dependencies: []const Dependency = old.buffers.dependencies.items;
// const package_resolutions: []const Resolution = old.packages.items(.resolution);
// const string_buf = old.buffers.string_bytes.items;
// const root_resolution = @as(usize, old.packages.items(.resolutions)[0].len);
// const DedupeMap = std.ArrayHashMap(PackageNameHash, std.ArrayListUnmanaged([2]PackageID), ArrayIdentityContext(PackageNameHash), false);
// var dedupe_map = DedupeMap.initContext(allocator, .{});
// try dedupe_map.ensureTotalCapacity(old.unique_packages.count());
// for (resolutions) |resolved_package_id, dep_i| {
// if (resolved_package_id < max_package_id and !old.unique_packages.isSet(resolved_package_id)) {
// const dependency = dependencies[dep_i];
// if (dependency.version.tag == .npm) {
// var dedupe_entry = try dedupe_map.getOrPut(dependency.name_hash);
// if (!dedupe_entry.found_existing) dedupe_entry.value_ptr.* = .{};
// try dedupe_entry.value_ptr.append(allocator, [2]PackageID{ dep_i, resolved_package_id });
// }
// }
// }
// }
var new = try old.allocator.create(Lockfile);
try new.initEmpty(
old.allocator,
);
try new.string_pool.ensureTotalCapacity(old.string_pool.capacity());
try new.package_index.ensureTotalCapacity(old.package_index.capacity());
try new.packages.ensureTotalCapacity(old.allocator, old.packages.len);
try new.buffers.preallocate(old.buffers, old.allocator);
old.scratch.dependency_list_queue.head = 0;
// Step 1. Recreate the lockfile with only the packages that are still alive
const root = old.rootPackage() orelse return error.NoPackage;
var package_id_mapping = try old.allocator.alloc(PackageID, old.packages.len);
@memset(
package_id_mapping,
invalid_package_id,
);
var clone_queue_ = PendingResolutions.init(old.allocator);
var cloner = Cloner{
.old = old,
.lockfile = new,
.mapping = package_id_mapping,
.clone_queue = clone_queue_,
.log = log,
};
// try clone_queue.ensureUnusedCapacity(root.dependencies.len);
_ = try root.clone(old, new, package_id_mapping, &cloner);
// When you run `"bun add react"
// This is where we update it in the lockfile from "latest" to "^17.0.2"
try cloner.flush();
// Don't allow invalid memory to happen
if (updates.len > 0) {
const slice = new.packages.slice();
const names = slice.items(.name);
const resolutions = slice.items(.resolution);
const dep_list = slice.items(.dependencies)[0];
const res_list = slice.items(.resolutions)[0];
const root_deps: []const Dependency = dep_list.get(new.buffers.dependencies.items);
const resolved_ids: []const PackageID = res_list.get(new.buffers.resolutions.items);
const string_buf = new.buffers.string_bytes.items;
for (updates) |*update| {
if (update.resolution.tag == .uninitialized) {
for (root_deps, resolved_ids) |dep, package_id| {
if (update.matches(dep, string_buf)) {
if (package_id > new.packages.len) continue;
update.version_buf = string_buf;
update.version = dep.version;
update.resolution = resolutions[package_id];
update.resolved_name = names[package_id];
}
}
}
}
}
new.trusted_dependencies = old_trusted_dependencies;
new.scripts = old_scripts;
return new;
}
pub const MetaHashFormatter = struct {
meta_hash: *const MetaHash,
pub fn format(this: MetaHashFormatter, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
var remain: []const u8 = this.meta_hash[0..];
try std.fmt.format(
writer,
"{}-{}-{}-{}",
.{
std.fmt.fmtSliceHexUpper(remain[0..8]),
std.fmt.fmtSliceHexLower(remain[8..16]),
std.fmt.fmtSliceHexUpper(remain[16..24]),
std.fmt.fmtSliceHexLower(remain[24..32]),
},
);
}
};
pub fn fmtMetaHash(this: *const Lockfile) MetaHashFormatter {
return .{
.meta_hash = &this.meta_hash,
};
}
pub const FillItem = struct {
tree_id: Tree.Id,
dependency_id: DependencyID,
};
pub const TreeFiller = std.fifo.LinearFifo(FillItem, .Dynamic);
const Cloner = struct {
clone_queue: PendingResolutions,
lockfile: *Lockfile,
old: *Lockfile,
mapping: []PackageID,
trees: Tree.List = Tree.List{},
trees_count: u32 = 1,
log: *logger.Log,
pub fn flush(this: *Cloner) anyerror!void {
const max_package_id = this.old.packages.len;
while (this.clone_queue.popOrNull()) |to_clone_| {
const to_clone: PendingResolution = to_clone_;
const mapping = this.mapping[to_clone.old_resolution];
if (mapping < max_package_id) {
this.lockfile.buffers.resolutions.items[to_clone.resolve_id] = mapping;
continue;
}
const old_package = this.old.packages.get(to_clone.old_resolution);
this.lockfile.buffers.resolutions.items[to_clone.resolve_id] = try old_package.clone(
this.old,
this.lockfile,
this.mapping,
this,
);
}
if (this.lockfile.buffers.dependencies.items.len > 0)
try this.hoist();
// capacity is used for calculating byte size
// so we need to make sure it's exact
if (this.lockfile.packages.capacity != this.lockfile.packages.len and this.lockfile.packages.len > 0)
this.lockfile.packages.shrinkAndFree(this.lockfile.allocator, this.lockfile.packages.len);
}
fn hoist(this: *Cloner) anyerror!void {
if (this.lockfile.packages.len == 0) return;
var allocator = this.lockfile.allocator;
var slice = this.lockfile.packages.slice();
var builder = Tree.Builder{
.name_hashes = slice.items(.name_hash),
.queue = TreeFiller.init(allocator),
.resolution_lists = slice.items(.resolutions),
.resolutions = this.lockfile.buffers.resolutions.items,
.allocator = allocator,
.dependencies = this.lockfile.buffers.dependencies.items,
.log = this.log,
.old_lockfile = this.old,
};
try (Tree{}).processSubtree(Tree.root_dep_id, &builder);
// This goes breadth-first
while (builder.queue.readItem()) |item| {
try builder.list.items(.tree)[item.tree_id].processSubtree(item.dependency_id, &builder);
}
this.lockfile.buffers.hoisted_dependencies = try builder.clean();
{
const final = builder.list.items(.tree);
this.lockfile.buffers.trees = .{
.items = final,
.capacity = final.len,
};
}
}
};
const PendingResolution = struct {
old_resolution: PackageID,
resolve_id: PackageID,
parent: PackageID,
};
const PendingResolutions = std.ArrayList(PendingResolution);
pub const Printer = struct {
lockfile: *Lockfile,
options: PackageManager.Options,
successfully_installed: ?Bitset = null,
updates: []const PackageManager.UpdateRequest = &[_]PackageManager.UpdateRequest{},
pub const Format = enum { yarn };
pub fn print(
allocator: Allocator,
log: *logger.Log,
input_lockfile_path: string,
format: Format,
) !void {
@setCold(true);
// We truncate longer than allowed paths. We should probably throw an error instead.
var path = input_lockfile_path[0..@min(input_lockfile_path.len, bun.MAX_PATH_BYTES)];
var lockfile_path_buf1: [bun.MAX_PATH_BYTES]u8 = undefined;
var lockfile_path_buf2: [bun.MAX_PATH_BYTES]u8 = undefined;
var lockfile_path: stringZ = "";
if (!std.fs.path.isAbsolute(path)) {
var cwd = try std.os.getcwd(&lockfile_path_buf1);
var parts = [_]string{path};
var lockfile_path__ = Path.joinAbsStringBuf(cwd, &lockfile_path_buf2, &parts, .auto);
lockfile_path_buf2[lockfile_path__.len] = 0;
lockfile_path = lockfile_path_buf2[0..lockfile_path__.len :0];
} else if (path.len > 0) {
@memcpy(lockfile_path_buf1[0..path.len], path);
lockfile_path_buf1[path.len] = 0;
lockfile_path = lockfile_path_buf1[0..path.len :0];
}
if (lockfile_path.len > 0 and lockfile_path[0] == std.fs.path.sep)
std.os.chdir(std.fs.path.dirname(lockfile_path) orelse "/") catch {};
_ = try FileSystem.init(null);
var lockfile = try allocator.create(Lockfile);
const load_from_disk = lockfile.loadFromDisk(allocator, log, lockfile_path);
switch (load_from_disk) {
.err => |cause| {
switch (cause.step) {
.open_file => Output.prettyErrorln("<r><red>error<r> opening lockfile:<r> {s}.", .{
@errorName(cause.value),
}),
.parse_file => Output.prettyErrorln("<r><red>error<r> parsing lockfile:<r> {s}", .{
@errorName(cause.value),
}),
.read_file => Output.prettyErrorln("<r><red>error<r> reading lockfile:<r> {s}", .{
@errorName(cause.value),
}),
}
if (log.errors > 0) {
switch (Output.enable_ansi_colors) {
inline else => |enable_ansi_colors| {
try log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), enable_ansi_colors);
},
}
}
Global.crash();
},
.not_found => {
Output.prettyErrorln("<r><red>lockfile not found:<r> {}", .{
strings.QuotedFormatter{ .text = std.mem.sliceAsBytes(lockfile_path) },
});
Global.crash();
},
.ok => {},
}
var writer = Output.writer();
try printWithLockfile(allocator, lockfile, format, @TypeOf(writer), writer);
Output.flush();
}
pub fn printWithLockfile(
allocator: Allocator,
lockfile: *Lockfile,
format: Format,
comptime Writer: type,
writer: Writer,
) !void {
var fs = &FileSystem.instance;
var options = PackageManager.Options{};
var entries_option = try fs.fs.readDirectory(fs.top_level_dir, null, 0, true);
var env_loader: *DotEnv.Loader = brk: {
var map = try allocator.create(DotEnv.Map);
map.* = DotEnv.Map.init(allocator);
var loader = try allocator.create(DotEnv.Loader);
loader.* = DotEnv.Loader.init(map, allocator);
break :brk loader;
};
env_loader.loadProcess();
try env_loader.load(&fs.fs, entries_option.entries, .production);
var log = logger.Log.init(allocator);
try options.load(
allocator,
&log,
env_loader,
null,
null,
);
var printer = Printer{
.lockfile = lockfile,
.options = options,
};
switch (format) {
.yarn => {