-
Notifications
You must be signed in to change notification settings - Fork 4.3k
Expand file tree
/
Copy pathcli.zig
More file actions
1827 lines (1635 loc) · 74.5 KB
/
cli.zig
File metadata and controls
1827 lines (1635 loc) · 74.5 KB
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 debug = Output.scoped(.CLI, .hidden);
pub var start_time: i128 = undefined;
pub var Bun__Node__ProcessTitle: ?string = null;
pub const Cli = struct {
pub const CompileTarget = @import("./compile_target.zig");
pub var log_: logger.Log = undefined;
pub fn startTransform(_: std.mem.Allocator, _: api.TransformOptions, _: *logger.Log) anyerror!void {}
pub fn start(allocator: std.mem.Allocator) void {
is_main_thread = true;
start_time = std.time.nanoTimestamp();
log_ = logger.Log.init(allocator);
var log = &log_;
// var panicker = MainPanicHandler.init(log);
// MainPanicHandler.Singleton = &panicker;
Command.start(allocator, log) catch |err| {
log.print(Output.errorWriter()) catch {};
bun.crash_handler.handleRootError(err, @errorReturnTrace());
};
}
pub var cmd: ?Command.Tag = null;
pub threadlocal var is_main_thread: bool = false;
};
pub const debug_flags = if (Environment.show_crash_trace) struct {
pub var resolve_breakpoints: []const []const u8 = &.{};
pub var print_breakpoints: []const []const u8 = &.{};
pub fn hasResolveBreakpoint(str: []const u8) bool {
for (resolve_breakpoints) |bp| {
if (strings.contains(str, bp)) {
return true;
}
}
return false;
}
pub fn hasPrintBreakpoint(path: fs.Path) bool {
for (print_breakpoints) |bp| {
if (strings.contains(path.pretty, bp)) {
return true;
}
if (strings.contains(path.text, bp)) {
return true;
}
}
return false;
}
} else @compileError("Do not access this namespace in a release build");
pub const LoaderColonList = ColonListType(api.Loader, Arguments.loader_resolver);
pub const DefineColonList = ColonListType(string, Arguments.noop_resolver);
pub fn invalidTarget(diag: *clap.Diagnostic, _target: []const u8) noreturn {
@branchHint(.cold);
diag.name.long = "target";
diag.arg = _target;
diag.report(Output.errorWriter(), error.InvalidTarget) catch {};
std.process.exit(1);
}
pub const BuildCommand = @import("./cli/build_command.zig").BuildCommand;
pub const AddCommand = @import("./cli/add_command.zig").AddCommand;
pub const CreateCommand = @import("./cli/create_command.zig").CreateCommand;
pub const CreateCommandExample = @import("./cli/create_command.zig").Example;
pub const CreateListExamplesCommand = @import("./cli/create_command.zig").CreateListExamplesCommand;
pub const DiscordCommand = @import("./cli/discord_command.zig").DiscordCommand;
pub const InstallCommand = @import("./cli/install_command.zig").InstallCommand;
pub const LinkCommand = @import("./cli/link_command.zig").LinkCommand;
pub const UnlinkCommand = @import("./cli/unlink_command.zig").UnlinkCommand;
pub const InstallCompletionsCommand = @import("./cli/install_completions_command.zig").InstallCompletionsCommand;
pub const PackageManagerCommand = @import("./cli/package_manager_command.zig").PackageManagerCommand;
pub const RemoveCommand = @import("./cli/remove_command.zig").RemoveCommand;
pub const RunCommand = @import("./cli/run_command.zig").RunCommand;
pub const ShellCompletions = @import("./cli/shell_completions.zig");
pub const UpdateCommand = @import("./cli/update_command.zig").UpdateCommand;
pub const UpgradeCommand = @import("./cli/upgrade_command.zig").UpgradeCommand;
pub const BunxCommand = @import("./cli/bunx_command.zig").BunxCommand;
pub const ExecCommand = @import("./cli/exec_command.zig").ExecCommand;
pub const PatchCommand = @import("./cli/patch_command.zig").PatchCommand;
pub const PatchCommitCommand = @import("./cli/patch_commit_command.zig").PatchCommitCommand;
pub const OutdatedCommand = @import("./cli/outdated_command.zig").OutdatedCommand;
pub const UpdateInteractiveCommand = @import("./cli/update_interactive_command.zig").UpdateInteractiveCommand;
pub const PublishCommand = @import("./cli/publish_command.zig").PublishCommand;
pub const PackCommand = @import("./cli/pack_command.zig").PackCommand;
pub const AuditCommand = @import("./cli/audit_command.zig").AuditCommand;
pub const InitCommand = @import("./cli/init_command.zig").InitCommand;
pub const WhyCommand = @import("./cli/why_command.zig").WhyCommand;
pub const FuzzilliCommand = @import("./cli/fuzzilli_command.zig").FuzzilliCommand;
pub const ReplCommand = @import("./cli/repl_command.zig").ReplCommand;
pub const Arguments = @import("./cli/Arguments.zig");
const AutoCommand = struct {
pub fn exec(allocator: std.mem.Allocator) !void {
try HelpCommand.execWithReason(allocator, .invalid_command);
}
};
pub const HelpCommand = struct {
pub fn exec(allocator: std.mem.Allocator) !void {
@branchHint(.cold);
execWithReason(allocator, .explicit);
}
pub const Reason = enum {
explicit,
invalid_command,
};
// someone will get mad at me for this
pub const packages_to_remove_filler = [_]string{
"moment",
"underscore",
"jquery",
"backbone",
"redux",
"browserify",
"webpack",
"left-pad",
"is-array",
"babel-core",
"@parcel/core",
};
pub const packages_to_add_filler = [_]string{
"elysia",
"@shumai/shumai",
"hono",
"react",
"lyra",
"@remix-run/dev",
"@evan/duckdb",
"@zarfjs/zarf",
"zod",
"tailwindcss",
};
pub const packages_to_x_filler = [_]string{
"bun-repl",
"next",
"vite",
"prisma",
"nuxi",
"prettier",
"eslint",
};
pub const packages_to_create_filler = [_]string{
"next-app",
"vite",
"astro",
"svelte",
"elysia",
};
// the spacing between commands here is intentional
pub const cli_helptext_fmt =
\\<b>Usage:<r> <b>bun \<command\> <cyan>[...flags]<r> <b>[...args]<r>
\\
\\<b>Commands:<r>
\\ <b><magenta>run<r> <d>./my-script.ts<r> Execute a file with Bun
\\ <d>lint<r> Run a package.json script
\\ <b><magenta>test<r> Run unit tests with Bun
\\ <b><magenta>x<r> <d>{s:<16}<r> Execute a package binary (CLI), installing if needed <d>(bunx)<r>
\\ <b><magenta>repl<r> Start a REPL session with Bun
\\ <b><magenta>exec<r> Run a shell script directly with Bun
\\
\\ <b><blue>install<r> Install dependencies for a package.json <d>(bun i)<r>
\\ <b><blue>add<r> <d>{s:<16}<r> Add a dependency to package.json <d>(bun a)<r>
\\ <b><blue>remove<r> <d>{s:<16}<r> Remove a dependency from package.json <d>(bun rm)<r>
\\ <b><blue>update<r> <d>{s:<16}<r> Update outdated dependencies
\\ <b><blue>audit<r> Check installed packages for vulnerabilities
\\ <b><blue>outdated<r> Display latest versions of outdated dependencies
\\ <b><blue>link<r> <d>[\<package\>]<r> Register or link a local npm package
\\ <b><blue>unlink<r> Unregister a local npm package
\\ <b><blue>publish<r> Publish a package to the npm registry
\\ <b><blue>patch <d>\<pkg\><r> Prepare a package for patching
\\ <b><blue>pm <d>\<subcommand\><r> Additional package management utilities
\\ <b><blue>info<r> <d>{s:<16}<r> Display package metadata from the registry
\\ <b><blue>why<r> <d>{s:<16}<r> Explain why a package is installed
\\
\\ <b><yellow>build<r> <d>./a.ts ./b.jsx<r> Bundle TypeScript & JavaScript into a single file
\\
\\ <b><cyan>init<r> Start an empty Bun project from a built-in template
\\ <b><cyan>create<r> <d>{s:<16}<r> Create a new project from a template <d>(bun c)<r>
\\ <b><cyan>upgrade<r> Upgrade to latest version of Bun.
\\ <b><cyan>feedback<r> <d>./file1 ./file2<r> Provide feedback to the Bun team.
\\
\\ <d>\<command\><r> <b><cyan>--help<r> Print help text for command.
\\
;
const cli_helptext_footer =
\\
\\Learn more about Bun: <magenta>https://bun.com/docs<r>
\\Join our Discord community: <blue>https://bun.com/discord<r>
\\
;
pub fn printWithReason(comptime reason: Reason, show_all_flags: bool) void {
var rand_state = std.Random.DefaultPrng.init(@as(u64, @intCast(@max(std.time.milliTimestamp(), 0))));
const rand = rand_state.random();
const package_x_i = rand.uintAtMost(usize, packages_to_x_filler.len - 1);
const package_add_i = rand.uintAtMost(usize, packages_to_add_filler.len - 1);
const package_remove_i = rand.uintAtMost(usize, packages_to_remove_filler.len - 1);
const package_create_i = rand.uintAtMost(usize, packages_to_create_filler.len - 1);
const args = .{
packages_to_x_filler[package_x_i],
packages_to_add_filler[package_add_i],
packages_to_remove_filler[package_remove_i],
packages_to_add_filler[(package_add_i + 1) % packages_to_add_filler.len],
packages_to_add_filler[(package_add_i + 2) % packages_to_add_filler.len],
packages_to_add_filler[(package_add_i + 3) % packages_to_add_filler.len],
packages_to_create_filler[package_create_i],
};
switch (reason) {
.explicit => {
if (comptime Environment.isDebug) {
if (bun.argv.len == 1) {
if (bun.Output.isAIAgent()) {
if (bun.env_var.npm_lifecycle_event.get()) |event| {
if (bun.strings.hasPrefixComptime(event, "bd")) {
// claude gets very confused by the help menu
// let's give claude some self confidence.
Output.println("BUN COMPILED SUCCESSFULLY! 🎉", .{});
Global.exit(0);
}
}
}
}
}
Output.pretty(
"<r><b><magenta>Bun<r> is a fast JavaScript runtime, package manager, bundler, and test runner. <d>(" ++
Global.package_json_version_with_revision ++
")<r>\n\n" ++
cli_helptext_fmt,
args,
);
if (show_all_flags) {
Output.pretty("\n<b>Flags:<r>", .{});
const flags = Arguments.runtime_params_ ++ Arguments.auto_only_params ++ Arguments.base_params_;
clap.simpleHelpBunTopLevel(comptime &flags);
Output.pretty("\n\n(more flags in <b>bun install --help<r>, <b>bun test --help<r>, and <b>bun build --help<r>)\n", .{});
}
Output.pretty(cli_helptext_footer, .{});
},
.invalid_command => Output.prettyError(
"<r><red>Uh-oh<r> not sure what to do with that command.\n\n" ++ cli_helptext_fmt,
args,
),
}
Output.flush();
}
pub fn execWithReason(_: std.mem.Allocator, comptime reason: Reason) void {
@branchHint(.cold);
printWithReason(reason, false);
if (reason == .invalid_command) {
Global.exit(1);
}
Global.exit(0);
}
};
pub const ReservedCommand = struct {
pub fn exec(_: std.mem.Allocator) !void {
@branchHint(.cold);
const command_name = for (bun.argv[1..]) |arg| {
if (arg.len > 1 and arg[0] == '-') continue;
break arg;
} else bun.argv[1];
Output.prettyError(
\\<r><red>Uh-oh<r>. <b><yellow>bun {s}<r> is a subcommand reserved for future use by Bun.
\\
\\If you were trying to run a package.json script called {s}, use <b><magenta>bun run {s}<r>.
\\
, .{ command_name, command_name, command_name });
Output.flush();
std.process.exit(1);
}
};
/// This is set `true` during `Command.which()` if argv0 is "node", in which the CLI is going
/// to pretend to be node.js by always choosing RunCommand with a relative filepath.
///
/// Examples of how this differs from bun alone:
/// - `node build` -> `bun run ./build`
/// - `node scripts/postinstall` -> `bun run ./scripts/postinstall`
pub var pretend_to_be_node = false;
/// This is set `true` during `Command.which()` if argv0 is "bunx"
pub var is_bunx_exe = false;
pub const Command = struct {
pub fn get() Context {
return global_cli_ctx;
}
pub const DebugOptions = struct {
dump_environment_variables: bool = false,
dump_limits: bool = false,
fallback_only: bool = false,
silent: bool = false,
hot_reload: HotReload = HotReload.none,
global_cache: options.GlobalCache = .auto,
offline_mode_setting: ?Bunfig.OfflineMode = null,
run_in_bun: bool = false,
loaded_bunfig: bool = false,
/// Disables using bun.shell.Interpreter for `bun run`, instead spawning cmd.exe
use_system_shell: bool = !bun.Environment.isWindows,
// technical debt
macros: MacroOptions = MacroOptions.unspecified,
editor: string = "",
package_bundle_map: bun.StringArrayHashMapUnmanaged(options.BundlePackage) = bun.StringArrayHashMapUnmanaged(options.BundlePackage){},
test_directory: []const u8 = "",
output_file: []const u8 = "",
};
pub const MacroOptions = union(enum) { unspecified: void, disable: void, map: MacroMap };
pub const HotReload = enum {
none,
hot,
watch,
};
pub const TestOptions = struct {
default_timeout_ms: u32 = 5 * std.time.ms_per_s,
update_snapshots: bool = false,
repeat_count: u32 = 0,
retry: u32 = 0,
run_todo: bool = false,
only: bool = false,
pass_with_no_tests: bool = false,
concurrent: bool = false,
randomize: bool = false,
seed: ?u32 = null,
concurrent_test_glob: ?[]const []const u8 = null,
bail: u32 = 0,
coverage: TestCommand.CodeCoverageOptions = .{},
path_ignore_patterns: []const []const u8 = &.{},
path_ignore_patterns_from_cli: bool = false,
test_filter_pattern: ?[]const u8 = null,
test_filter_regex: ?*RegularExpression = null,
max_concurrency: u32 = 20,
file_parallelism: u32 = 1,
reporters: struct {
dots: bool = false,
only_failures: bool = false,
junit: bool = false,
} = .{},
reporter_outfile: ?[]const u8 = null,
};
pub const Debugger = union(enum) {
unspecified: void,
enable: struct {
path_or_port: []const u8 = "",
wait_for_connection: bool = false,
set_breakpoint_on_first_line: bool = false,
},
};
pub const RuntimeOptions = struct {
smol: bool = false,
debugger: Debugger = .{ .unspecified = {} },
if_present: bool = false,
redis_preconnect: bool = false,
sql_preconnect: bool = false,
eval: struct {
script: []const u8 = "",
eval_and_print: bool = false,
} = .{},
preconnect: []const []const u8 = &[_][]const u8{},
dns_result_order: []const u8 = "verbatim",
/// `--expose-gc` makes `globalThis.gc()` available. Added for Node
/// compatibility.
expose_gc: bool = false,
preserve_symlinks_main: bool = false,
console_depth: ?u16 = null,
cron_title: []const u8 = "",
cron_period: []const u8 = "",
cpu_prof: struct {
enabled: bool = false,
name: []const u8 = "",
dir: []const u8 = "",
interval: u32 = 1000,
md_format: bool = false,
json_format: bool = false,
} = .{},
heap_prof: struct {
enabled: bool = false,
text_format: bool = false,
name: []const u8 = "",
dir: []const u8 = "",
} = .{},
};
var global_cli_ctx: Context = undefined;
var context_data: ContextData = undefined;
pub const init = ContextData.create;
pub const ContextData = struct {
start_time: i128,
args: api.TransformOptions,
log: *logger.Log,
allocator: std.mem.Allocator,
positionals: []const string = &.{},
passthrough: []const string = &.{},
install: ?*api.BunInstall = null,
debug: DebugOptions = .{},
test_options: TestOptions = .{},
bundler_options: BundlerOptions = .{},
runtime_options: RuntimeOptions = .{},
filters: []const []const u8 = &.{},
workspaces: bool = false,
if_present: bool = false,
parallel: bool = false,
sequential: bool = false,
no_exit_on_error: bool = false,
preloads: []const string = &.{},
has_loaded_global_config: bool = false,
pub const BundlerOptions = struct {
outdir: []const u8 = "",
outfile: []const u8 = "",
metafile: [:0]const u8 = "",
metafile_md: [:0]const u8 = "",
root_dir: []const u8 = "",
public_path: []const u8 = "",
entry_naming: []const u8 = "[dir]/[name].[ext]",
chunk_naming: []const u8 = "./[name]-[hash].[ext]",
asset_naming: []const u8 = "./[name]-[hash].[ext]",
server_components: bool = false,
react_fast_refresh: bool = false,
code_splitting: bool = false,
transform_only: bool = false,
inline_entrypoint_import_meta_main: bool = false,
minify_syntax: bool = false,
minify_whitespace: bool = false,
minify_identifiers: bool = false,
keep_names: bool = false,
ignore_dce_annotations: bool = false,
emit_dce_annotations: bool = true,
output_format: options.Format = .esm,
bytecode: bool = false,
banner: []const u8 = "",
footer: []const u8 = "",
css_chunking: bool = false,
bake: bool = false,
bake_debug_dump_server: bool = false,
bake_debug_disable_minify: bool = false,
production: bool = false,
env_behavior: api.DotEnvBehavior = .disable,
env_prefix: []const u8 = "",
elide_lines: ?usize = null,
// Compile options
compile: bool = false,
compile_target: Cli.CompileTarget = .{},
compile_exec_argv: ?[]const u8 = null,
compile_autoload_dotenv: bool = true,
compile_autoload_bunfig: bool = true,
compile_autoload_tsconfig: bool = false,
compile_autoload_package_json: bool = false,
compile_executable_path: ?[]const u8 = null,
windows: options.WindowsOptions = .{},
allow_unresolved: ?[]const []const u8 = null,
};
pub fn create(allocator: std.mem.Allocator, log: *logger.Log, comptime command: Command.Tag) anyerror!Context {
Cli.cmd = command;
context_data = .{
.args = std.mem.zeroes(api.TransformOptions),
.log = log,
.start_time = start_time,
.allocator = allocator,
};
global_cli_ctx = &context_data;
if (comptime Command.Tag.uses_global_options.get(command)) {
global_cli_ctx.args = try Arguments.parse(allocator, global_cli_ctx, command);
}
if (comptime Environment.isWindows) {
if (global_cli_ctx.debug.hot_reload == .watch) {
if (!bun.windows.isWatcherChild()) {
// this is noreturn
bun.windows.becomeWatcherManager(allocator);
} else {
bun.auto_reload_on_crash = true;
}
}
}
return global_cli_ctx;
}
};
pub const Context = *ContextData;
// std.process.args allocates!
const ArgsIterator = struct {
buf: [][:0]const u8,
i: u32 = 0,
pub fn next(this: *ArgsIterator) ?[]const u8 {
if (this.buf.len <= this.i) {
return null;
}
const i = this.i;
this.i += 1;
return this.buf[i];
}
pub fn skip(this: *ArgsIterator) bool {
return this.next() != null;
}
};
pub fn isBunX(argv0: []const u8) bool {
if (Environment.isWindows) {
return strings.endsWithComptime(argv0, "bunx.exe") or strings.endsWithComptime(argv0, "bunx");
}
return strings.endsWithComptime(argv0, "bunx");
}
pub fn isNode(argv0: []const u8) bool {
if (Environment.isWindows) {
return strings.endsWithComptime(argv0, "node.exe") or strings.endsWithComptime(argv0, "node");
}
return strings.endsWithComptime(argv0, "node");
}
pub fn which() Tag {
var args_iter = ArgsIterator{ .buf = bun.argv };
const argv0 = args_iter.next() orelse return .HelpCommand;
if (isBunX(argv0)) {
// if we are bunx, but NOT a symlink to bun. when we run `<self> install`, we dont
// want to recursively run bunx. so this check lets us peek back into bun install.
if (args_iter.next()) |next| {
if (bun.strings.eqlComptime(next, "add") and bun.feature_flag.BUN_INTERNAL_BUNX_INSTALL.get()) {
return .AddCommand;
} else if (bun.strings.eqlComptime(next, "exec") and bun.feature_flag.BUN_INTERNAL_BUNX_INSTALL.get()) {
return .ExecCommand;
}
}
is_bunx_exe = true;
return .BunxCommand;
}
if (isNode(argv0)) {
@import("./deps/zig-clap/clap/streaming.zig").warn_on_unrecognized_flag = false;
pretend_to_be_node = true;
return .RunAsNodeCommand;
}
var next_arg = ((args_iter.next()) orelse return .AutoCommand);
while (next_arg.len > 0 and next_arg[0] == '-' and !(next_arg.len > 1 and next_arg[1] == 'e')) {
next_arg = ((args_iter.next()) orelse return .AutoCommand);
}
const first_arg_name = next_arg;
const RootCommandMatcher = strings.ExactSizeMatcher(12);
return switch (RootCommandMatcher.match(first_arg_name)) {
RootCommandMatcher.case("init") => .InitCommand,
RootCommandMatcher.case("build"), RootCommandMatcher.case("bun") => .BuildCommand,
RootCommandMatcher.case("discord") => .DiscordCommand,
RootCommandMatcher.case("upgrade") => .UpgradeCommand,
RootCommandMatcher.case("completions") => .InstallCompletionsCommand,
RootCommandMatcher.case("getcompletes") => .GetCompletionsCommand,
RootCommandMatcher.case("link") => .LinkCommand,
RootCommandMatcher.case("unlink") => .UnlinkCommand,
RootCommandMatcher.case("x") => .BunxCommand,
RootCommandMatcher.case("repl") => .ReplCommand,
RootCommandMatcher.case("i"),
RootCommandMatcher.case("install"),
=> brk: {
for (args_iter.buf) |arg| {
if (arg.len > 0 and (strings.eqlComptime(arg, "-g") or strings.eqlComptime(arg, "--global"))) {
break :brk .AddCommand;
}
}
break :brk .InstallCommand;
},
RootCommandMatcher.case("ci") => .InstallCommand,
RootCommandMatcher.case("c"), RootCommandMatcher.case("create") => .CreateCommand,
RootCommandMatcher.case("test") => .TestCommand,
RootCommandMatcher.case("pm") => .PackageManagerCommand,
RootCommandMatcher.case("add"), RootCommandMatcher.case("a") => .AddCommand,
RootCommandMatcher.case("update") => .UpdateCommand,
RootCommandMatcher.case("patch") => .PatchCommand,
RootCommandMatcher.case("patch-commit") => .PatchCommitCommand,
RootCommandMatcher.case("r"),
RootCommandMatcher.case("remove"),
RootCommandMatcher.case("rm"),
RootCommandMatcher.case("uninstall"),
=> .RemoveCommand,
RootCommandMatcher.case("run") => .RunCommand,
RootCommandMatcher.case("help") => .HelpCommand,
RootCommandMatcher.case("exec") => .ExecCommand,
RootCommandMatcher.case("outdated") => .OutdatedCommand,
RootCommandMatcher.case("publish") => .PublishCommand,
RootCommandMatcher.case("audit") => .AuditCommand,
RootCommandMatcher.case("info") => .InfoCommand,
// These are reserved for future use by Bun, so that someone
// doing `bun deploy` to run a script doesn't accidentally break
// when we add our actual command
RootCommandMatcher.case("deploy") => .ReservedCommand,
RootCommandMatcher.case("cloud") => .ReservedCommand,
RootCommandMatcher.case("config") => .ReservedCommand,
RootCommandMatcher.case("use") => .ReservedCommand,
RootCommandMatcher.case("auth") => .ReservedCommand,
RootCommandMatcher.case("login") => .ReservedCommand,
RootCommandMatcher.case("logout") => .ReservedCommand,
RootCommandMatcher.case("whoami") => .PackageManagerCommand,
RootCommandMatcher.case("prune") => .ReservedCommand,
RootCommandMatcher.case("list") => .PackageManagerCommand,
RootCommandMatcher.case("why") => .WhyCommand,
RootCommandMatcher.case("fuzzilli") => if (bun.Environment.enable_fuzzilli)
.FuzzilliCommand
else
.AutoCommand,
RootCommandMatcher.case("-e") => .AutoCommand,
else => .AutoCommand,
};
}
const default_completions_list = [_]string{
"build",
"install",
"add",
"run",
"update",
"link",
"unlink",
"remove",
"create",
"bun",
"upgrade",
"discord",
"test",
"pm",
"x",
"repl",
"info",
};
const reject_list = default_completions_list ++ [_]string{
"build",
"completions",
"help",
};
/// Keep the stack space usage of this function small. This function is
/// kept alive for the entire duration of the process
///
/// So do not add any path buffers or anything that is large in this
/// function or that stack space is used up forever.
pub fn start(allocator: std.mem.Allocator, log: *logger.Log) !void {
if (comptime Environment.allow_assert) {
if (!bun.env_var.MI_VERBOSE.get()) {
bun.mimalloc.mi_option_set_enabled(.verbose, false);
}
}
// WebView host subprocess entry. Must be before StandaloneModuleGraph,
// before JSC init, before anything that touches a JS engine. The child
// runs CFRunLoopRun() as its real main loop — no Bun runtime past this.
if (comptime Environment.isMac) {
if (bun.env_var.BUN_INTERNAL_WEBVIEW_HOST.get()) |fd_str| {
const fd = std.fmt.parseInt(u31, fd_str, 10) catch {
Output.panic("Invalid BUN_INTERNAL_WEBVIEW_HOST fd: {s}", .{fd_str});
};
const hostMain = @extern(
*const fn (i32) callconv(.c) noreturn,
.{ .name = "Bun__WebView__hostMain" },
);
hostMain(fd);
}
}
// bun build --compile entry point
if (!bun.feature_flag.BUN_BE_BUN.get()) {
if (try bun.StandaloneModuleGraph.fromExecutable(bun.default_allocator)) |graph| {
var offset_for_passthrough: usize = 0;
const ctx: *ContextData = brk: {
if (graph.compile_exec_argv.len > 0 or bun.bun_options_argc > 0) {
const original_argv_len = bun.argv.len;
var argv_list = std.array_list.Managed([:0]const u8).fromOwnedSlice(bun.default_allocator, bun.argv);
if (graph.compile_exec_argv.len > 0) {
try bun.appendOptionsEnv(graph.compile_exec_argv, [:0]const u8, &argv_list);
}
// Store the full argv including user arguments
const full_argv = argv_list.items;
const num_exec_argv_options = full_argv.len -| original_argv_len;
// Calculate offset: skip executable name + all exec argv options + BUN_OPTIONS args
const num_parsed_options = num_exec_argv_options + bun.bun_options_argc;
offset_for_passthrough = if (full_argv.len > 1) 1 + num_parsed_options else 0;
// Temporarily set bun.argv to only include executable name + exec_argv options + BUN_OPTIONS args.
// This prevents user arguments like --version/--help from being intercepted
// by Bun's argument parser (they should be passed through to user code).
bun.argv = full_argv[0..@min(1 + num_parsed_options, full_argv.len)];
// Handle actual options to parse.
const result = try Command.init(allocator, log, .AutoCommand);
// Restore full argv so passthrough calculation works correctly
bun.argv = full_argv;
break :brk result;
}
context_data = .{
.args = std.mem.zeroes(api.TransformOptions),
.log = log,
.start_time = start_time,
.allocator = bun.default_allocator,
};
global_cli_ctx = &context_data;
// If no compile_exec_argv, skip executable name if present
offset_for_passthrough = @min(1, bun.argv.len);
break :brk global_cli_ctx;
};
ctx.args.target = .bun;
if (ctx.debug.global_cache == .auto)
ctx.debug.global_cache = .disable;
ctx.passthrough = bun.argv[offset_for_passthrough..];
try bun_js.Run.bootStandalone(
ctx,
graph.entryPoint().name,
graph,
);
return;
}
}
debug("argv: [{f}]", .{bun.fmt.fmtSlice(bun.argv, ", ")});
const tag = which();
switch (tag) {
.DiscordCommand => return try DiscordCommand.exec(allocator),
.HelpCommand => return try HelpCommand.exec(allocator),
.ReservedCommand => return try ReservedCommand.exec(allocator),
.InitCommand => return try InitCommand.exec(allocator, bun.argv[@min(2, bun.argv.len)..]),
.InfoCommand => {
try @"bun info"(allocator, log);
return;
},
.BuildCommand => {
const ctx = try Command.init(allocator, log, .BuildCommand);
try BuildCommand.exec(ctx, null);
},
.InstallCompletionsCommand => {
try InstallCompletionsCommand.exec(allocator);
return;
},
.InstallCommand => {
const ctx = try Command.init(allocator, log, .InstallCommand);
try InstallCommand.exec(ctx);
return;
},
.AddCommand => {
const ctx = try Command.init(allocator, log, .AddCommand);
try AddCommand.exec(ctx);
return;
},
.UpdateCommand => {
const ctx = try Command.init(allocator, log, .UpdateCommand);
try UpdateCommand.exec(ctx);
return;
},
.PatchCommand => {
const ctx = try Command.init(allocator, log, .PatchCommand);
try PatchCommand.exec(ctx);
return;
},
.PatchCommitCommand => {
const ctx = try Command.init(allocator, log, .PatchCommitCommand);
try PatchCommitCommand.exec(ctx);
return;
},
.OutdatedCommand => {
const ctx = try Command.init(allocator, log, .OutdatedCommand);
try OutdatedCommand.exec(ctx);
return;
},
.UpdateInteractiveCommand => {
const ctx = try Command.init(allocator, log, .UpdateInteractiveCommand);
try UpdateInteractiveCommand.exec(ctx);
return;
},
.PublishCommand => {
const ctx = try Command.init(allocator, log, .PublishCommand);
try PublishCommand.exec(ctx);
return;
},
.AuditCommand => {
const ctx = try Command.init(allocator, log, .AuditCommand);
try AuditCommand.exec(ctx);
},
.WhyCommand => {
const ctx = try Command.init(allocator, log, .WhyCommand);
try WhyCommand.exec(ctx);
return;
},
.BunxCommand => {
const ctx = try Command.init(allocator, log, .BunxCommand);
try BunxCommand.exec(ctx, bun.argv[if (is_bunx_exe) 0 else 1..]);
return;
},
.ReplCommand => {
const ctx = try Command.init(allocator, log, .RunCommand);
try ReplCommand.exec(ctx);
return;
},
.RemoveCommand => {
const ctx = try Command.init(allocator, log, .RemoveCommand);
try RemoveCommand.exec(ctx);
return;
},
.LinkCommand => {
const ctx = try Command.init(allocator, log, .LinkCommand);
try LinkCommand.exec(ctx);
return;
},
.UnlinkCommand => {
const ctx = try Command.init(allocator, log, .UnlinkCommand);
try UnlinkCommand.exec(ctx);
return;
},
.PackageManagerCommand => {
const ctx = try Command.init(allocator, log, .PackageManagerCommand);
try PackageManagerCommand.exec(ctx);
return;
},
.TestCommand => {
const ctx = try Command.init(allocator, log, .TestCommand);
try TestCommand.exec(ctx);
return;
},
.GetCompletionsCommand => {
try @"bun getcompletes"(allocator, log);
return;
},
.CreateCommand => {
try @"bun create"(allocator, log);
return;
},
.RunCommand => {
const ctx = try Command.init(allocator, log, .RunCommand);
ctx.args.target = .bun;
if (ctx.parallel or ctx.sequential) {
MultiRun.run(ctx) catch |err| {
Output.prettyErrorln("<r><red>error<r>: {s}", .{@errorName(err)});
Global.exit(1);
};
}
if (ctx.filters.len > 0 or ctx.workspaces) {
FilterRun.runScriptsWithFilter(ctx) catch |err| {
Output.prettyErrorln("<r><red>error<r>: {s}", .{@errorName(err)});
Global.exit(1);
};
}
if (ctx.positionals.len > 0) {
if (try RunCommand.exec(ctx, .{ .bin_dirs_only = false, .log_errors = true, .allow_fast_run_for_extensions = false })) {
return;
}
Global.exit(1);
}
},
.RunAsNodeCommand => {
const ctx = try Command.init(allocator, log, .RunAsNodeCommand);
bun.assert(pretend_to_be_node);
try RunCommand.execAsIfNode(ctx);
},
.UpgradeCommand => {
const ctx = try Command.init(allocator, log, .UpgradeCommand);
try UpgradeCommand.exec(ctx);
return;
},
.AutoCommand => {
const ctx = Command.init(allocator, log, .AutoCommand) catch |e| {
switch (e) {
error.MissingEntryPoint => {
HelpCommand.execWithReason(allocator, .explicit);
return;
},
else => {
return e;
},
}
};
ctx.args.target = .bun;
if (ctx.parallel or ctx.sequential) {
MultiRun.run(ctx) catch |err| {
Output.prettyErrorln("<r><red>error<r>: {s}", .{@errorName(err)});
Global.exit(1);
};
}
if (ctx.filters.len > 0 or ctx.workspaces) {
FilterRun.runScriptsWithFilter(ctx) catch |err| {
Output.prettyErrorln("<r><red>error<r>: {s}", .{@errorName(err)});
Global.exit(1);
};
}
if (ctx.runtime_options.eval.script.len > 0) {
return try @"bun --eval --print"(ctx);
}
const extension: []const u8 = if (ctx.args.entry_points.len > 0)
std.fs.path.extension(ctx.args.entry_points[0])
else
@as([]const u8, "");
// KEYWORDS: open file argv argv0
if (ctx.args.entry_points.len == 1) {
if (strings.eqlComptime(extension, ".lockb")) {
return try @"bun ./bun.lockb"(ctx);
}
}
if (ctx.positionals.len > 0) {
if (ctx.filters.len > 0) {
Output.prettyln("<r><yellow>warn<r>: Filters are ignored for auto command", .{});
}
if (try RunCommand.exec(ctx, .{ .bin_dirs_only = true, .log_errors = !ctx.runtime_options.if_present, .allow_fast_run_for_extensions = true })) {
return;
}
return;
}
Output.flush();
try HelpCommand.exec(allocator);