-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
run_command.zig
1837 lines (1567 loc) · 76.1 KB
/
run_command.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 bun = @import("root").bun;
const Async = bun.Async;
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 std = @import("std");
const uws = bun.uws;
const JSC = bun.JSC;
const WaiterThread = JSC.Subprocess.WaiterThread;
const lex = bun.js_lexer;
const logger = bun.logger;
const clap = bun.clap;
const CLI = bun.CLI;
const Arguments = CLI.Arguments;
const Command = CLI.Command;
const options = @import("../options.zig");
const js_parser = bun.js_parser;
const json_parser = bun.JSON;
const js_printer = bun.js_printer;
const js_ast = bun.JSAst;
const linker = @import("../linker.zig");
const sync = @import("../sync.zig");
const Api = @import("../api/schema.zig").Api;
const resolve_path = @import("../resolver/resolve_path.zig");
const configureTransformOptionsForBun = @import("../bun.js/config.zig").configureTransformOptionsForBun;
const bundler = bun.bundler;
const DotEnv = @import("../env_loader.zig");
const which = @import("../which.zig").which;
const Run = @import("../bun_js.zig").Run;
var path_buf: [bun.MAX_PATH_BYTES]u8 = undefined;
var path_buf2: [bun.MAX_PATH_BYTES]u8 = undefined;
const NpmArgs = struct {
// https://github.com/npm/rfcs/blob/main/implemented/0021-reduce-lifecycle-script-environment.md#detailed-explanation
pub const package_name: string = "npm_package_name";
pub const package_version: string = "npm_package_version";
};
const PackageJSON = @import("../resolver/package_json.zig").PackageJSON;
const yarn_commands: []u64 = @import("./list-of-yarn-commands.zig").all_yarn_commands;
const ShellCompletions = @import("./shell_completions.zig");
const PosixSpawn = bun.posix.spawn;
const PackageManager = @import("../install/install.zig").PackageManager;
const Lockfile = @import("../install/lockfile.zig");
const LifecycleScriptSubprocess = bun.install.LifecycleScriptSubprocess;
const windows = std.os.windows;
pub const RunCommand = struct {
const shells_to_search = &[_]string{
"bash",
"sh",
"zsh",
};
fn findShellImpl(PATH: string, cwd: string) ?stringZ {
if (comptime Environment.isWindows) {
return "C:\\Windows\\System32\\cmd.exe";
}
inline for (shells_to_search) |shell| {
if (which(&path_buf, PATH, cwd, shell)) |shell_| {
return shell_;
}
}
const Try = struct {
pub fn shell(str: stringZ) bool {
return bun.sys.isExecutableFilePath(str);
}
};
const hardcoded_popular_ones = [_]stringZ{
"/bin/bash",
"/usr/bin/bash",
"/usr/local/bin/bash", // don't think this is a real one
"/bin/sh",
"/usr/bin/sh", // don't think this is a real one
"/usr/bin/zsh",
"/usr/local/bin/zsh",
};
inline for (hardcoded_popular_ones) |shell| {
if (Try.shell(shell)) {
return shell;
}
}
return null;
}
/// Find the "best" shell to use
/// Cached to only run once
pub fn findShell(PATH: string, cwd: string) ?stringZ {
const bufs = struct {
pub var shell_buf_once: [bun.MAX_PATH_BYTES]u8 = undefined;
pub var found_shell: [:0]const u8 = "";
};
if (bufs.found_shell.len > 0) {
return bufs.found_shell;
}
if (findShellImpl(PATH, cwd)) |found| {
if (found.len < bufs.shell_buf_once.len) {
@memcpy(bufs.shell_buf_once[0..found.len], found);
bufs.shell_buf_once[found.len] = 0;
bufs.found_shell = bufs.shell_buf_once[0..found.len :0];
return bufs.found_shell;
}
return found;
}
return null;
}
const BUN_BIN_NAME = if (Environment.isDebug) "bun-debug" else "bun";
const BUN_RUN = std.fmt.comptimePrint("{s} run", .{BUN_BIN_NAME});
const BUN_RUN_USING_BUN = std.fmt.comptimePrint("{s} --bun run", .{BUN_BIN_NAME});
// Look for invocations of any:
// - yarn run
// - yarn $cmdName
// - pnpm run
// - npm run
// Replace them with "bun run"
pub inline fn replacePackageManagerRun(
copy_script: *std.ArrayList(u8),
script: string,
) !void {
var entry_i: usize = 0;
var delimiter: u8 = ' ';
while (entry_i < script.len) {
const start = entry_i;
switch (script[entry_i]) {
'y' => {
if (delimiter > 0) {
const remainder = script[start..];
if (strings.hasPrefixComptime(remainder, "yarn ")) {
const next = remainder["yarn ".len..];
// We have yarn
// Find the next space
if (strings.indexOfChar(next, ' ')) |space| {
const yarn_cmd = next[0..space];
if (strings.eqlComptime(yarn_cmd, "run")) {
try copy_script.appendSlice(BUN_RUN);
entry_i += "yarn run".len;
continue;
}
// yarn npm is a yarn 2 subcommand
if (strings.eqlComptime(yarn_cmd, "npm")) {
entry_i += "yarn npm ".len;
try copy_script.appendSlice("yarn npm ");
continue;
}
if (strings.startsWith(yarn_cmd, "-")) {
// Skip the rest of the command
entry_i += "yarn ".len + yarn_cmd.len;
try copy_script.appendSlice("yarn ");
try copy_script.appendSlice(yarn_cmd);
continue;
}
// implicit yarn commands
if (std.mem.indexOfScalar(u64, yarn_commands, bun.hash(yarn_cmd)) == null) {
try copy_script.appendSlice(BUN_RUN);
try copy_script.append(' ');
try copy_script.appendSlice(yarn_cmd);
entry_i += "yarn ".len + yarn_cmd.len;
delimiter = 0;
continue;
}
}
}
}
delimiter = 0;
},
// do we need to escape?
' ' => {
delimiter = ' ';
},
'"' => {
delimiter = '"';
},
'\'' => {
delimiter = '\'';
},
'n' => {
if (delimiter > 0) {
if (strings.hasPrefixComptime(script[start..], "npm run ")) {
try copy_script.appendSlice(BUN_RUN ++ " ");
entry_i += "npm run ".len;
delimiter = 0;
continue;
}
if (strings.hasPrefixComptime(script[start..], "npx ")) {
try copy_script.appendSlice(BUN_BIN_NAME ++ " x ");
entry_i += "npx ".len;
delimiter = 0;
continue;
}
}
delimiter = 0;
},
'p' => {
if (delimiter > 0) {
if (strings.hasPrefixComptime(script[start..], "pnpm run ")) {
try copy_script.appendSlice(BUN_RUN ++ " ");
entry_i += "pnpm run ".len;
delimiter = 0;
continue;
}
}
delimiter = 0;
},
// TODO: handle escape sequences properly
// https://github.com/oven-sh/bun/issues/53
'\\' => {
delimiter = 0;
if (entry_i + 1 < script.len) {
switch (script[entry_i + 1]) {
'"', '\'' => {
entry_i += 1;
continue;
},
'\\' => {
entry_i += 1;
},
else => {},
}
}
},
else => {
delimiter = 0;
},
}
try copy_script.append(script[entry_i]);
entry_i += 1;
}
}
const log = Output.scoped(.RUN, false);
fn runPackageScriptForeground(
allocator: std.mem.Allocator,
original_script: string,
name: string,
cwd: string,
env: *DotEnv.Loader,
passthrough: []const string,
silent: bool,
use_system_shell: bool,
) !bool {
const shell_bin = findShell(env.get("PATH") orelse "", cwd) orelse return error.MissingShell;
const script = original_script;
var copy_script = try std.ArrayList(u8).initCapacity(allocator, script.len);
// We're going to do this slowly.
// Find exact matches of yarn, pnpm, npm
try replacePackageManagerRun(©_script, script);
var combined_script: []u8 = copy_script.items;
log("Script: \"{s}\"", .{combined_script});
if (passthrough.len > 0) {
var combined_script_len = script.len;
for (passthrough) |p| {
combined_script_len += p.len + 1;
}
var combined_script_buf = try allocator.alloc(u8, combined_script_len);
bun.copy(u8, combined_script_buf, script);
var remaining_script_buf = combined_script_buf[script.len..];
for (passthrough) |part| {
const p = part;
remaining_script_buf[0] = ' ';
bun.copy(u8, remaining_script_buf[1..], p);
remaining_script_buf = remaining_script_buf[p.len + 1 ..];
}
combined_script = combined_script_buf;
}
if (!use_system_shell) {
if (!silent) {
if (Environment.isDebug) {
Output.prettyError("[bun shell] ", .{});
}
Output.prettyErrorln("<r><d><magenta>$<r> <d><b>{s}<r>", .{combined_script});
Output.flush();
}
const mini = bun.JSC.MiniEventLoop.initGlobal(env);
const code = bun.shell.Interpreter.initAndRunFromSource(mini, name, combined_script) catch |err| {
if (!silent) {
Output.prettyErrorln("<r><red>error<r>: Failed to run script <b>{s}<r> due to error <b>{s}<r>", .{ name, @errorName(err) });
}
Global.exit(1);
};
if (code > 0) {
if (code != 2 and !silent) {
Output.prettyErrorln("<r><red>error<r><d>:<r> script <b>\"{s}\"<r> exited with code {d}<r>", .{ name, code });
Output.flush();
}
Global.exitWide(code);
}
return true;
}
const argv = [_]string{
shell_bin,
if (Environment.isWindows) "/c" else "-c",
combined_script,
};
if (!silent) {
Output.prettyErrorln("<r><d><magenta>$<r> <d><b>{s}<r>", .{combined_script});
Output.flush();
}
const spawn_result = switch ((bun.spawnSync(&.{
.argv = &argv,
.argv0 = shell_bin.ptr,
// TODO: remember to free this when we add --filter or --concurrent
// in the meantime we don't need to free it.
.envp = try env.map.createNullDelimitedEnvMap(bun.default_allocator),
.cwd = cwd,
.stderr = .inherit,
.stdout = .inherit,
.stdin = .inherit,
.windows = if (Environment.isWindows) .{
.loop = JSC.EventLoopHandle.init(JSC.MiniEventLoop.initGlobal(env)),
} else {},
}) catch |err| {
if (!silent) {
Output.prettyErrorln("<r><red>error<r>: Failed to run script <b>{s}<r> due to error <b>{s}<r>", .{ name, @errorName(err) });
}
Output.flush();
return true;
})) {
.err => |err| {
if (!silent) {
Output.prettyErrorln("<r><red>error<r>: Failed to run script <b>{s}<r> due to error:\n{}", .{ name, err });
}
Output.flush();
return true;
},
.result => |result| result,
};
switch (spawn_result.status) {
.exited => |exit_code| {
if (exit_code.signal.valid() and exit_code.signal != .SIGINT and !silent) {
Output.prettyErrorln("<r><red>error<r><d>:<r> script <b>\"{s}\"<r> was terminated by signal {}<r>", .{ name, exit_code.signal.fmt(Output.enable_ansi_colors_stderr) });
Output.flush();
Global.raiseIgnoringPanicHandler(exit_code.signal);
}
if (exit_code.code != 0) {
if (exit_code.code != 2 and !silent) {
Output.prettyErrorln("<r><red>error<r><d>:<r> script <b>\"{s}\"<r> exited with code {d}<r>", .{ name, exit_code.code });
Output.flush();
}
Global.exit(exit_code.code);
}
},
.signaled => |signal| {
if (signal.valid() and signal != .SIGINT and !silent) {
Output.prettyErrorln("<r><red>error<r><d>:<r> script <b>\"{s}\"<r> was terminated by signal {}<r>", .{ name, signal.fmt(Output.enable_ansi_colors_stderr) });
Output.flush();
Global.raiseIgnoringPanicHandler(signal);
}
},
.err => |err| {
if (!silent) {
Output.prettyErrorln("<r><red>error<r>: Failed to run script <b>{s}<r> due to error:\n{}", .{ name, err });
}
Output.flush();
return true;
},
else => {},
}
return true;
}
/// When printing error messages from 'bun run', attribute bun overridden node.js to bun
/// This prevents '"node" exited with ...' when it was actually bun.
/// As of writing this is only used for 'runBinary'
fn basenameOrBun(str: []const u8) []const u8 {
// The full path is not used here, because on windows it is dependant on the
// username. Before windows we checked bun_node_dir, but this is not allowed on Windows.
if (strings.hasSuffixComptime(str, "/bun-node/node" ++ bun.exe_suffix) or (Environment.isWindows and strings.hasSuffixComptime(str, "\\bun-node\\node" ++ bun.exe_suffix))) {
return "bun";
}
return std.fs.path.basename(str);
}
/// On windows, this checks for a `.bunx` file in the same directory as the
/// script If it exists, it will be run instead of the script which is
/// assumed to `bun_shim_impl.exe`
///
/// This function only returns if an error starting the process is
/// encountered, most other errors are handled by printing and exiting.
pub fn runBinary(
ctx: Command.Context,
executable: []const u8,
executableZ: [:0]const u8,
cwd: string,
env: *DotEnv.Loader,
passthrough: []const string,
original_script_for_bun_run: ?[]const u8,
) !noreturn {
// Attempt to find a ".bunx" file on disk, and run it, skipping the
// wrapper exe. we build the full exe path even though we could do
// a relative lookup, because in the case we do find it, we have to
// generate this full path anyways.
if (Environment.isWindows and bun.FeatureFlags.windows_bunx_fast_path and bun.strings.hasSuffixComptime(executable, ".exe")) {
std.debug.assert(std.fs.path.isAbsolute(executable));
// Using @constCast is safe because we know that
// `direct_launch_buffer` is the data destination that assumption is
// backed by the immediate assertion.
var wpath = @constCast(bun.strings.toNTPath(&BunXFastPath.direct_launch_buffer, executable));
std.debug.assert(bun.isSliceInBufferT(u16, wpath, &BunXFastPath.direct_launch_buffer));
std.debug.assert(wpath.len > bun.windows.nt_object_prefix.len + ".exe".len);
wpath.len += ".bunx".len - ".exe".len;
@memcpy(wpath[wpath.len - "bunx".len ..], comptime bun.strings.w("bunx"));
BunXFastPath.tryLaunch(ctx, wpath, env, passthrough);
}
try runBinaryWithoutBunxPath(
ctx,
executable,
executableZ,
cwd,
env,
passthrough,
original_script_for_bun_run,
);
}
fn runBinaryGenericError(executable: []const u8, silent: bool, err: bun.sys.Error) noreturn {
if (!silent) {
Output.prettyErrorln("<r><red>error<r>: Failed to run \"<b>{s}<r>\" due to:\n{}", .{ basenameOrBun(executable), err.withPath(executable) });
if (@errorReturnTrace()) |trace| {
std.debug.dumpStackTrace(trace.*);
}
}
Global.exit(1);
}
fn runBinaryWithoutBunxPath(
ctx: Command.Context,
executable: []const u8,
executableZ: [*:0]const u8,
cwd: string,
env: *DotEnv.Loader,
passthrough: []const string,
original_script_for_bun_run: ?[]const u8,
) !noreturn {
var argv_ = [_]string{executable};
var argv: []const string = &argv_;
if (passthrough.len > 0) {
var array_list = std.ArrayList(string).init(ctx.allocator);
try array_list.append(executable);
try array_list.appendSlice(passthrough);
argv = try array_list.toOwnedSlice();
}
const silent = ctx.debug.silent;
const spawn_result = bun.spawnSync(&.{
.argv = argv,
.argv0 = executableZ,
// TODO: remember to free this when we add --filter or --concurrent
// in the meantime we don't need to free it.
.envp = try env.map.createNullDelimitedEnvMap(bun.default_allocator),
.cwd = cwd,
.stderr = .inherit,
.stdout = .inherit,
.stdin = .inherit,
.use_execve_on_macos = silent,
.windows = if (Environment.isWindows) .{
.loop = JSC.EventLoopHandle.init(JSC.MiniEventLoop.initGlobal(env)),
} else {},
}) catch |err| {
// an error occurred before the process was spawned
print_error: {
if (!silent) {
if (comptime Environment.isPosix) {
switch (bun.sys.stat(executable[0.. :0])) {
.result => |stat| {
if (bun.S.ISDIR(stat.mode)) {
Output.prettyErrorln("<r><red>error<r>: Failed to run directory \"<b>{s}<r>\"\n", .{basenameOrBun(executable)});
break :print_error;
}
},
.err => |err2| {
switch (err2.getErrno()) {
.NOENT, .PERM, .NOTDIR => {
Output.prettyErrorln("<r><red>error<r>: Failed to run \"<b>{s}<r>\" due to error:\n{}", .{ basenameOrBun(executable), err2 });
break :print_error;
},
else => {},
}
},
}
}
Output.prettyErrorln("<r><red>error<r>: Failed to run \"<b>{s}<r>\" due to <r><red>{s}<r>", .{ basenameOrBun(executable), @errorName(err) });
if (@errorReturnTrace()) |trace| {
std.debug.dumpStackTrace(trace.*);
}
}
}
Global.exit(1);
};
switch (spawn_result) {
.err => |err| {
// an error occurred while spawning the process
runBinaryGenericError(executable, silent, err);
},
.result => |result| {
switch (result.status) {
// An error occurred after the process was spawned.
.err => |err| {
runBinaryGenericError(executable, silent, err);
},
.signaled => |signal| {
if (!silent) {
Output.prettyErrorln("<r><red>error<r>: Failed to run \"<b>{s}<r>\" due to signal <b>{s}<r>", .{
basenameOrBun(executable),
signal.name() orelse "unknown",
});
if (@errorReturnTrace()) |trace| {
std.debug.dumpStackTrace(trace.*);
}
}
Output.flush();
Global.raiseIgnoringPanicHandler(@intFromEnum(signal));
},
.exited => |exit_code| {
// A process can be both signaled and exited
if (exit_code.signal.valid()) {
if (!silent) {
Output.prettyErrorln("<r><red>error<r>: \"<b>{s}<r>\" exited with signal <b>{s}<r>", .{
basenameOrBun(executable),
exit_code.signal.name() orelse "unknown",
});
if (@errorReturnTrace()) |trace| {
std.debug.dumpStackTrace(trace.*);
}
}
Output.flush();
Global.raiseIgnoringPanicHandler(@intFromEnum(exit_code.signal));
}
const code = exit_code.code;
if (code != 0) {
if (!silent) {
const is_probably_trying_to_run_a_pkg_script =
original_script_for_bun_run != null and
((code == 1 and bun.strings.eqlComptime(original_script_for_bun_run.?, "test")) or
(code == 2 and bun.strings.eqlAnyComptime(original_script_for_bun_run.?, &.{
"install",
"kill",
"link",
}) and ctx.positionals.len == 1));
if (is_probably_trying_to_run_a_pkg_script) {
// if you run something like `bun run test`, you get a confusing message because
// you don't usually think about your global path, let alone "/bin/test"
//
// test exits with code 1, the other ones i listed exit with code 2
//
// so for these script names, print the entire exe name.
Output.errGeneric("\"<b>{s}<r>\" exited with code {d}", .{ executable, code });
Output.note("a package.json script \"{s}\" was not found", .{original_script_for_bun_run.?});
}
// 128 + 2 is the exit code of a process killed by SIGINT, which is caused by CTRL + C
else if (code > 0 and code != 130) {
Output.errGeneric("\"<b>{s}<r>\" exited with code {d}", .{ basenameOrBun(executable), code });
} else {
Output.prettyErrorln("<r><red>error<r>: Failed to run \"<b>{s}<r>\" due to exit code <b>{d}<r>", .{
basenameOrBun(executable),
code,
});
}
if (@errorReturnTrace()) |trace| {
std.debug.dumpStackTrace(trace.*);
}
}
}
Global.exit(code);
},
.running => @panic("Unexpected state: process is running"),
}
},
}
}
pub fn ls(ctx: Command.Context) !void {
const args = ctx.args;
var this_bundler = try bundler.Bundler.init(ctx.allocator, ctx.log, args, null);
this_bundler.options.env.behavior = Api.DotEnvBehavior.load_all;
this_bundler.options.env.prefix = "";
this_bundler.resolver.care_about_bin_folder = true;
this_bundler.resolver.care_about_scripts = true;
this_bundler.configureLinker();
}
pub const bun_node_dir = switch (Environment.os) {
// This path is almost always a path to a user directory. So it cannot be inlined like
// our uses of /tmp. You can use one of these functions instead:
// - bun.windows.GetTempPathW (native)
// - bun.fs.FileSystem.RealFS.platformTempDir (any platform)
.windows => @compileError("Do not use RunCommand.bun_node_dir on Windows"),
.mac => "/private/tmp",
else => "/tmp",
} ++ if (!Environment.isDebug)
"/bun-node" ++ if (Environment.git_sha_short.len > 0) "-" ++ Environment.git_sha_short else ""
else
"/bun-node-debug";
pub fn bunNodeFileUtf8(allocator: std.mem.Allocator) ![:0]const u8 {
if (!Environment.isWindows) return bun_node_dir;
var temp_path_buffer: bun.WPathBuffer = undefined;
var target_path_buffer: bun.PathBuffer = undefined;
const len = bun.windows.GetTempPathW(
temp_path_buffer.len,
@ptrCast(&temp_path_buffer),
);
if (len == 0) {
return error.FailedToGetTempPath;
}
const converted = try bun.strings.convertUTF16toUTF8InBuffer(
&target_path_buffer,
temp_path_buffer[0..len],
);
const dir_name = "bun-node" ++ if (Environment.git_sha_short.len > 0) "-" ++ Environment.git_sha_short else "";
const file_name = dir_name ++ "\\node.exe";
@memcpy(target_path_buffer[converted.len..][0..file_name.len], file_name);
target_path_buffer[converted.len + file_name.len] = 0;
return try allocator.dupeZ(u8, target_path_buffer[0 .. converted.len + file_name.len :0]);
}
pub fn createFakeTemporaryNodeExecutable(PATH: *std.ArrayList(u8), optional_bun_path: *string) !void {
// If we are already running as "node", the path should exist
if (CLI.pretend_to_be_node) return;
if (Environment.isPosix) {
var argv0 = @as([*:0]const u8, @ptrCast(optional_bun_path.ptr));
// if we are already an absolute path, use that
// if the user started the application via a shebang, it's likely that the path is absolute already
if (bun.argv()[0][0] == '/') {
optional_bun_path.* = bun.argv()[0];
argv0 = bun.argv()[0];
} else if (optional_bun_path.len == 0) {
// otherwise, ask the OS for the absolute path
const self = try bun.selfExePath();
if (self.len > 0) {
argv0 = self.ptr;
optional_bun_path.* = self;
}
}
if (optional_bun_path.len == 0) {
argv0 = bun.argv()[0];
}
if (Environment.isDebug) {
std.fs.deleteTreeAbsolute(bun_node_dir) catch {};
}
const paths = .{ bun_node_dir ++ "/node", bun_node_dir ++ "/bun" };
inline for (paths) |path| {
var retried = false;
while (true) {
inner: {
std.os.symlinkZ(argv0, path) catch |err| {
if (err == error.PathAlreadyExists) break :inner;
if (retried)
return;
std.fs.makeDirAbsoluteZ(bun_node_dir) catch {};
retried = true;
continue;
};
}
break;
}
}
if (PATH.items.len > 0 and PATH.items[PATH.items.len - 1] != std.fs.path.delimiter) {
try PATH.append(std.fs.path.delimiter);
}
// The reason for the extra delim is because we are going to append the system PATH
// later on. this is done by the caller, and explains why we are adding bun_node_dir
// to the end of the path slice rather than the start.
try PATH.appendSlice(bun_node_dir ++ .{std.fs.path.delimiter});
} else if (Environment.isWindows) {
var target_path_buffer: bun.WPathBuffer = undefined;
const prefix = comptime bun.strings.w("\\??\\");
const len = bun.windows.GetTempPathW(
target_path_buffer.len - prefix.len,
@ptrCast(&target_path_buffer[prefix.len]),
);
if (len == 0) {
Output.debug("Failed to create temporary node dir: {s}", .{@tagName(std.os.windows.kernel32.GetLastError())});
return;
}
@memcpy(target_path_buffer[0..prefix.len], prefix);
const dir_name = "bun-node" ++ if (Environment.isDebug)
"-debug"
else if (Environment.git_sha_short.len > 0)
"-" ++ Environment.git_sha_short
else
"";
@memcpy(target_path_buffer[prefix.len..][len..].ptr, comptime bun.strings.w(dir_name));
const dir_slice = target_path_buffer[0 .. prefix.len + len + dir_name.len];
if (Environment.isDebug) {
const dir_slice_u8 = std.unicode.utf16leToUtf8Alloc(bun.default_allocator, dir_slice) catch @panic("oom");
defer bun.default_allocator.free(dir_slice_u8);
std.fs.deleteTreeAbsolute(dir_slice_u8) catch {};
std.fs.makeDirAbsolute(dir_slice_u8) catch @panic("huh?");
}
const image_path = bun.windows.exePathW();
inline for (.{ "node.exe", "bun.exe" }) |name| {
const file_name = dir_name ++ "\\" ++ name ++ "\x00";
@memcpy(target_path_buffer[len + prefix.len ..][0..file_name.len], comptime bun.strings.w(file_name));
const file_slice = target_path_buffer[0 .. prefix.len + len + file_name.len - "\x00".len];
if (bun.windows.CreateHardLinkW(@ptrCast(file_slice.ptr), image_path.ptr, null) == 0) {
switch (std.os.windows.kernel32.GetLastError()) {
.ALREADY_EXISTS => {},
else => {
{
std.debug.assert(target_path_buffer[dir_slice.len] == '\\');
target_path_buffer[dir_slice.len] = 0;
std.os.mkdirW(target_path_buffer[0..dir_slice.len :0], 0) catch {};
target_path_buffer[dir_slice.len] = '\\';
}
if (bun.windows.CreateHardLinkW(@ptrCast(file_slice.ptr), image_path.ptr, null) == 0) {
return;
}
},
}
}
}
if (PATH.items.len > 0 and PATH.items[PATH.items.len - 1] != std.fs.path.delimiter) {
try PATH.append(std.fs.path.delimiter);
}
// The reason for the extra delim is because we are going to append the system PATH
// later on. this is done by the caller, and explains why we are adding bun_node_dir
// to the end of the path slice rather than the start.
try bun.strings.toUTF8AppendToList(PATH, dir_slice[prefix.len..]);
try PATH.append(std.fs.path.delimiter);
}
}
pub const Filter = enum { script, bin, all, bun_js, all_plus_bun_js, script_and_descriptions, script_exclude };
const DirInfo = @import("../resolver/dir_info.zig");
pub fn configureEnvForRun(
ctx: Command.Context,
this_bundler: *bundler.Bundler,
env: ?*DotEnv.Loader,
log_errors: bool,
store_root_fd: bool,
) !*DirInfo {
const args = ctx.args;
this_bundler.* = try bundler.Bundler.init(ctx.allocator, ctx.log, args, env);
this_bundler.options.env.behavior = Api.DotEnvBehavior.load_all;
this_bundler.env.quiet = true;
this_bundler.options.env.prefix = "";
this_bundler.resolver.care_about_bin_folder = true;
this_bundler.resolver.care_about_scripts = true;
this_bundler.resolver.store_fd = store_root_fd;
this_bundler.resolver.opts.load_tsconfig_json = false;
this_bundler.options.load_tsconfig_json = false;
this_bundler.configureLinker();
const root_dir_info = this_bundler.resolver.readDirInfo(this_bundler.fs.top_level_dir) catch |err| {
if (!log_errors) return error.CouldntReadCurrentDirectory;
if (Output.enable_ansi_colors) {
ctx.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), true) catch {};
} else {
ctx.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), false) catch {};
}
Output.prettyErrorln("<r><red>error<r><d>:<r> <b>{s}<r> loading directory {}", .{ @errorName(err), bun.fmt.QuotedFormatter{ .text = this_bundler.fs.top_level_dir } });
Output.flush();
return err;
} orelse {
if (Output.enable_ansi_colors) {
ctx.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), true) catch {};
} else {
ctx.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), false) catch {};
}
Output.prettyErrorln("error loading current directory", .{});
Output.flush();
return error.CouldntReadCurrentDirectory;
};
this_bundler.resolver.store_fd = false;
if (env == null) {
this_bundler.env.loadProcess();
if (this_bundler.env.get("NODE_ENV")) |node_env| {
if (strings.eqlComptime(node_env, "production")) {
this_bundler.options.production = true;
}
}
this_bundler.runEnvLoader(true) catch {};
}
this_bundler.env.map.putDefault("npm_config_local_prefix", this_bundler.fs.top_level_dir) catch unreachable;
// we have no way of knowing what version they're expecting without running the node executable
// running the node executable is too slow
// so we will just hardcode it to LTS
this_bundler.env.map.putDefault(
"npm_config_user_agent",
// the use of npm/? is copying yarn
// e.g.
// > "yarn/1.22.4 npm/? node/v12.16.3 darwin x64",
"bun/" ++ Global.package_json_version ++ " npm/? node/v21.6.0 " ++ Global.os_name ++ " " ++ Global.arch_name,
) catch unreachable;
if (this_bundler.env.get("npm_execpath") == null) {
// we don't care if this fails
if (bun.selfExePath()) |self_exe_path| {
this_bundler.env.map.putDefault("npm_execpath", self_exe_path) catch unreachable;
} else |_| {}
}
if (root_dir_info.enclosing_package_json) |package_json| {
if (package_json.name.len > 0) {
if (this_bundler.env.map.get(NpmArgs.package_name) == null) {
this_bundler.env.map.put(NpmArgs.package_name, package_json.name) catch unreachable;
}
}
this_bundler.env.map.putDefault("npm_package_json", package_json.source.path.text) catch unreachable;
if (package_json.version.len > 0) {
if (this_bundler.env.map.get(NpmArgs.package_version) == null) {
this_bundler.env.map.put(NpmArgs.package_version, package_json.version) catch unreachable;
}
}
}
return root_dir_info;
}
pub fn configurePathForRun(
ctx: Command.Context,
root_dir_info: *DirInfo,
this_bundler: *bundler.Bundler,
ORIGINAL_PATH: ?*string,
cwd: string,
force_using_bun: bool,
) !void {
var package_json_dir: string = "";
if (root_dir_info.enclosing_package_json) |package_json| {
if (root_dir_info.package_json == null) {
// no trailing slash
package_json_dir = std.mem.trimRight(u8, package_json.source.path.name.dir, "/");
}
}
const PATH = this_bundler.env.get("PATH") orelse "";
if (ORIGINAL_PATH) |original_path| {
original_path.* = PATH;
}
const bun_node_exe = try bunNodeFileUtf8(ctx.allocator);
const bun_node_dir_win = bun.Dirname.dirname(u8, bun_node_exe) orelse return error.FailedToGetTempPath;
const found_node = this_bundler.env.loadNodeJSConfig(
this_bundler.fs,
if (force_using_bun) bun_node_exe else "",
) catch false;
var needs_to_force_bun = force_using_bun or !found_node;
var optional_bun_self_path: string = "";
var new_path_len: usize = PATH.len + 2;
if (package_json_dir.len > 0) {
new_path_len += package_json_dir.len + 1;
}
{
var remain = cwd;
while (strings.lastIndexOfChar(remain, std.fs.path.sep)) |i| {
new_path_len += strings.withoutTrailingSlash(remain).len + "node_modules.bin".len + 1 + 2; // +2 for path separators, +1 for path delimiter
remain = remain[0..i];
} else {
new_path_len += strings.withoutTrailingSlash(remain).len + "node_modules.bin".len + 1 + 2; // +2 for path separators, +1 for path delimiter
}
}
if (needs_to_force_bun) {
new_path_len += bun_node_dir_win.len + 1;
}
var new_path = try std.ArrayList(u8).initCapacity(ctx.allocator, new_path_len);
if (needs_to_force_bun) {
createFakeTemporaryNodeExecutable(&new_path, &optional_bun_self_path) catch bun.outOfMemory();
if (!force_using_bun) {
this_bundler.env.map.put("NODE", bun_node_exe) catch bun.outOfMemory();
this_bundler.env.map.put("npm_node_execpath", bun_node_exe) catch bun.outOfMemory();
this_bundler.env.map.put("npm_execpath", optional_bun_self_path) catch bun.outOfMemory();
}
needs_to_force_bun = false;
}
{
if (package_json_dir.len > 0) {
try new_path.appendSlice(package_json_dir);
try new_path.append(std.fs.path.delimiter);
}