forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.zig
2091 lines (1851 loc) · 91.4 KB
/
cli.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 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 constStrToU8 = bun.constStrToU8;
const FeatureFlags = bun.FeatureFlags;
const C = bun.C;
const root = @import("root");
const std = @import("std");
const lex = bun.js_lexer;
const logger = @import("root").bun.logger;
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 RegularExpression = bun.RegularExpression;
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 clap = @import("root").bun.clap;
const BunJS = @import("./bun_js.zig");
const Install = @import("./install/install.zig");
const bundler = bun.bundler;
const DotEnv = @import("./env_loader.zig");
const RunCommand_ = @import("./cli/run_command.zig").RunCommand;
const CreateCommand_ = @import("./cli/create_command.zig").CreateCommand;
const fs = @import("fs.zig");
const Router = @import("./router.zig");
const MacroMap = @import("./resolver/package_json.zig").MacroMap;
const TestCommand = @import("./cli/test_command.zig").TestCommand;
const Reporter = @import("./report.zig");
pub var start_time: i128 = undefined;
const Bunfig = @import("./bunfig.zig").Bunfig;
pub const Cli = struct {
var wait_group: sync.WaitGroup = undefined;
var log_: logger.Log = undefined;
pub fn startTransform(_: std.mem.Allocator, _: Api.TransformOptions, _: *logger.Log) anyerror!void {}
pub fn start(allocator: std.mem.Allocator, _: anytype, _: anytype, comptime MainPanicHandler: type) void {
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| {
switch (err) {
else => {
if (Output.enable_ansi_colors_stderr) {
log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), true) catch {};
} else {
log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), false) catch {};
}
Reporter.globalError(err, @errorReturnTrace());
},
}
};
}
pub var cmd: ?Command.Tag = null;
};
const LoaderMatcher = strings.ExactSizeMatcher(4);
const ColonListType = @import("./cli/colon_list_type.zig").ColonListType;
pub const LoaderColonList = ColonListType(Api.Loader, Arguments.loader_resolver);
pub const DefineColonList = ColonListType(string, Arguments.noop_resolver);
fn invalidTarget(diag: *clap.Diagnostic, _target: []const u8) noreturn {
@setCold(true);
diag.name.long = "--target";
diag.arg = _target;
diag.report(Output.errorWriter(), error.InvalidTarget) catch {};
std.process.exit(1);
}
pub const Arguments = struct {
pub fn loader_resolver(in: string) !Api.Loader {
const option_loader = options.Loader.fromString(in) orelse return error.InvalidLoader;
return option_loader.toAPI();
}
pub fn noop_resolver(in: string) !string {
return in;
}
pub fn fileReadError(err: anyerror, stderr: anytype, filename: string, kind: string) noreturn {
stderr.writer().print("Error reading file \"{s}\" for {s}: {s}", .{ filename, kind, @errorName(err) }) catch {};
std.process.exit(1);
}
pub fn readFile(
allocator: std.mem.Allocator,
cwd: string,
filename: string,
) ![]u8 {
var paths = [_]string{ cwd, filename };
const outpath = try std.fs.path.resolve(allocator, &paths);
defer allocator.free(outpath);
var file = try bun.openFileZ(&try std.os.toPosixPath(outpath), std.fs.File.OpenFlags{ .mode = .read_only });
defer file.close();
const size = try file.getEndPos();
return try file.readToEndAlloc(allocator, size);
}
pub fn resolve_jsx_runtime(str: string) !Api.JsxRuntime {
if (strings.eqlComptime(str, "automatic")) {
return Api.JsxRuntime.automatic;
} else if (strings.eqlComptime(str, "fallback") or strings.eqlComptime(str, "classic")) {
return Api.JsxRuntime.classic;
} else if (strings.eqlComptime(str, "solid")) {
return Api.JsxRuntime.solid;
} else {
return error.InvalidJSXRuntime;
}
}
pub const ParamType = clap.Param(clap.Help);
const base_params_ = [_]ParamType{
clap.parseParam("--env-file <STR>... Load environment variables from the specified file(s)") catch unreachable,
clap.parseParam("--cwd <STR> Absolute path to resolve files & entry points from. This just changes the process' cwd.") catch unreachable,
clap.parseParam("-c, --config <PATH>? Specify path to Bun config file. Default <d>$cwd<r>/bunfig.toml") catch unreachable,
clap.parseParam("-h, --help Display this menu and exit") catch unreachable,
clap.parseParam("<POS>...") catch unreachable,
};
const transpiler_params_ = [_]ParamType{
clap.parseParam("--main-fields <STR>... Main fields to lookup in package.json. Defaults to --target dependent") catch unreachable,
clap.parseParam("--extension-order <STR>... Defaults to: .tsx,.ts,.jsx,.js,.json ") catch unreachable,
clap.parseParam("--tsconfig-override <STR> Specify custom tsconfig.json. Default <d>$cwd<r>/tsconfig.json") catch unreachable,
clap.parseParam("-d, --define <STR>... Substitute K:V while parsing, e.g. --define process.env.NODE_ENV:\"development\". Values are parsed as JSON.") catch unreachable,
clap.parseParam("-l, --loader <STR>... Parse files with .ext:loader, e.g. --loader .js:jsx. Valid loaders: js, jsx, ts, tsx, json, toml, text, file, wasm, napi") catch unreachable,
clap.parseParam("--no-macros Disable macros from being executed in the bundler, transpiler and runtime") catch unreachable,
clap.parseParam("--jsx-factory <STR> Changes the function called when compiling JSX elements using the classic JSX runtime") catch unreachable,
clap.parseParam("--jsx-fragment <STR> Changes the function called when compiling JSX fragments") catch unreachable,
clap.parseParam("--jsx-import-source <STR> Declares the module specifier to be used for importing the jsx and jsxs factory functions. Default: \"react\"") catch unreachable,
clap.parseParam("--jsx-runtime <STR> \"automatic\" (default) or \"classic\"") catch unreachable,
};
const runtime_params_ = [_]ParamType{
clap.parseParam("--watch Automatically restart the process on file change") catch unreachable,
clap.parseParam("--hot Enable auto reload in the Bun runtime, test runner, or bundler") catch unreachable,
clap.parseParam("--smol Use less memory, but run garbage collection more often") catch unreachable,
clap.parseParam("-r, --preload <STR>... Import a module before other modules are loaded") catch unreachable,
clap.parseParam("--inspect <STR>? Activate Bun's debugger") catch unreachable,
clap.parseParam("--inspect-wait <STR>? Activate Bun's debugger, wait for a connection before executing") catch unreachable,
clap.parseParam("--inspect-brk <STR>? Activate Bun's debugger, set breakpoint on first line of code and wait") catch unreachable,
clap.parseParam("--if-present Exit without an error if the entrypoint does not exist") catch unreachable,
clap.parseParam("--no-install Disable auto install in the Bun runtime") catch unreachable,
clap.parseParam("--install <STR> Configure auto-install behavior. One of \"auto\" (default, auto-installs when no node_modules), \"fallback\" (missing packages only), \"force\" (always).") catch unreachable,
clap.parseParam("-i Auto-install dependencies during execution. Equivalent to --install=fallback.") catch unreachable,
clap.parseParam("-e, --eval <STR> Evaluate argument as a script") catch unreachable,
clap.parseParam("--prefer-offline Skip staleness checks for packages in the Bun runtime and resolve from disk") catch unreachable,
clap.parseParam("--prefer-latest Use the latest matching versions of packages in the Bun runtime, always checking npm") catch unreachable,
clap.parseParam("-p, --port <STR> Set the default port for Bun.serve") catch unreachable,
clap.parseParam("-u, --origin <STR>") catch unreachable,
};
const auto_only_params = [_]ParamType{
// clap.parseParam("--all") catch unreachable,
clap.parseParam("-b, --bun Force a script or package to use Bun's runtime instead of Node.js (via symlinking node)") catch unreachable,
clap.parseParam("--silent Don't print the script command") catch unreachable,
clap.parseParam("-v, --version Print version and exit") catch unreachable,
clap.parseParam("--revision Print version with revision and exit") catch unreachable,
};
const auto_params = auto_only_params ++ runtime_params_ ++ transpiler_params_ ++ base_params_;
const run_only_params = [_]ParamType{
clap.parseParam("--silent Don't print the script command") catch unreachable,
clap.parseParam("-b, --bun Force a script or package to use Bun's runtime instead of Node.js (via symlinking node)") catch unreachable,
};
pub const run_params = run_only_params ++ runtime_params_ ++ transpiler_params_ ++ base_params_;
const bunx_commands = [_]ParamType{
clap.parseParam("--silent Don't print the script command") catch unreachable,
clap.parseParam("-b, --bun Force a script or package to use Bun's runtime instead of Node.js (via symlinking node)") catch unreachable,
};
const build_only_params = [_]ParamType{
clap.parseParam("--compile Generate a standalone Bun executable containing your bundled code") catch unreachable,
clap.parseParam("--watch Automatically restart the process on file change") catch unreachable,
clap.parseParam("--target <STR> The intended execution environment for the bundle. \"browser\", \"bun\" or \"node\"") catch unreachable,
clap.parseParam("--outdir <STR> Default to \"dist\" if multiple files") catch unreachable,
clap.parseParam("--outfile <STR> Write to a file") catch unreachable,
clap.parseParam("--sourcemap <STR>? Build with sourcemaps - 'inline', 'external', or 'none'") catch unreachable,
clap.parseParam("--format <STR> Specifies the module format to build to. Only \"esm\" is supported.") catch unreachable,
clap.parseParam("--root <STR> Root directory used for multiple entry points") catch unreachable,
clap.parseParam("--splitting Enable code splitting") catch unreachable,
clap.parseParam("--public-path <STR> A prefix to be appended to any import paths in bundled code") catch unreachable,
clap.parseParam("-e, --external <STR>... Exclude module from transpilation (can use * wildcards). ex: -e react") catch unreachable,
clap.parseParam("--entry-naming <STR> Customize entry point filenames. Defaults to \"[dir]/[name].[ext]\"") catch unreachable,
clap.parseParam("--chunk-naming <STR> Customize chunk filenames. Defaults to \"[name]-[hash].[ext]\"") catch unreachable,
clap.parseParam("--asset-naming <STR> Customize asset filenames. Defaults to \"[name]-[hash].[ext]\"") catch unreachable,
clap.parseParam("--server-components Enable React Server Components (experimental)") catch unreachable,
clap.parseParam("--no-bundle Transpile file only, do not bundle") catch unreachable,
clap.parseParam("--minify Enable all minification flags") catch unreachable,
clap.parseParam("--minify-syntax Minify syntax and inline data") catch unreachable,
clap.parseParam("--minify-whitespace Minify whitespace") catch unreachable,
clap.parseParam("--minify-identifiers Minify identifiers") catch unreachable,
clap.parseParam("--dump-environment-variables") catch unreachable,
};
pub const build_params = build_only_params ++ transpiler_params_ ++ base_params_;
// TODO: update test completions
const test_only_params = [_]ParamType{
clap.parseParam("--timeout <NUMBER> Set the per-test timeout in milliseconds, default is 5000.") catch unreachable,
clap.parseParam("--update-snapshots Update snapshot files") catch unreachable,
clap.parseParam("--rerun-each <NUMBER> Re-run each test file <NUMBER> times, helps catch certain bugs") catch unreachable,
clap.parseParam("--only Only run tests that are marked with \"test.only()\"") catch unreachable,
clap.parseParam("--todo Include tests that are marked with \"test.todo()\"") catch unreachable,
clap.parseParam("--coverage Generate a coverage profile") catch unreachable,
clap.parseParam("--bail <NUMBER>? Exit the test suite after <NUMBER> failures. If you do not specify a number, it defaults to 1.") catch unreachable,
clap.parseParam("-t, --test-name-pattern <STR> Run only tests with a name that matches the given regex.") catch unreachable,
};
pub const test_params = test_only_params ++ runtime_params_ ++ transpiler_params_ ++ base_params_;
fn printVersionAndExit() noreturn {
@setCold(true);
Output.writer().writeAll(Global.package_json_version ++ "\n") catch {};
Global.exit(0);
}
fn printRevisionAndExit() noreturn {
@setCold(true);
Output.writer().writeAll(Global.package_json_version_with_revision ++ "\n") catch {};
Global.exit(0);
}
pub fn loadConfigPath(allocator: std.mem.Allocator, auto_loaded: bool, config_path: [:0]const u8, ctx: *Command.Context, comptime cmd: Command.Tag) !void {
var config_file = switch (bun.sys.openA(config_path, std.os.O.RDONLY, 0)) {
.result => |fd| std.fs.File{ .handle = bun.fdcast(fd) },
.err => |err| {
if (auto_loaded) return;
Output.prettyErrorln("{}\nwhile opening config \"{s}\"", .{
err,
config_path,
});
Global.exit(1);
},
};
defer config_file.close();
var contents = config_file.readToEndAlloc(allocator, std.math.maxInt(usize)) catch |err| {
if (auto_loaded) return;
Output.prettyErrorln("<r><red>error<r>: {s} reading config \"{s}\"", .{
@errorName(err),
config_path,
});
Global.exit(1);
};
js_ast.Stmt.Data.Store.create(allocator);
js_ast.Expr.Data.Store.create(allocator);
defer {
js_ast.Stmt.Data.Store.reset();
js_ast.Expr.Data.Store.reset();
}
var original_level = ctx.log.level;
defer {
ctx.log.level = original_level;
}
ctx.log.level = logger.Log.Level.warn;
try Bunfig.parse(allocator, logger.Source.initPathString(bun.asByteSlice(config_path), contents), ctx, cmd);
}
fn getHomeConfigPath(buf: *[bun.MAX_PATH_BYTES]u8) ?[:0]const u8 {
if (bun.getenvZ("XDG_CONFIG_HOME") orelse bun.getenvZ(bun.DotEnv.home_env)) |data_dir| {
var paths = [_]string{".bunfig.toml"};
return resolve_path.joinAbsStringBufZ(data_dir, buf, &paths, .auto);
}
return null;
}
pub fn loadConfig(allocator: std.mem.Allocator, user_config_path_: ?string, ctx: *Command.Context, comptime cmd: Command.Tag) !void {
var config_buf: [bun.MAX_PATH_BYTES]u8 = undefined;
if (comptime cmd.readGlobalConfig()) {
if (!ctx.has_loaded_global_config) {
ctx.has_loaded_global_config = true;
if (getHomeConfigPath(&config_buf)) |path| {
try loadConfigPath(allocator, true, path, ctx, comptime cmd);
}
}
}
var config_path_: []const u8 = user_config_path_ orelse "";
var auto_loaded: bool = false;
if (config_path_.len == 0 and (user_config_path_ != null or
Command.Tag.always_loads_config.get(cmd) or
(cmd == .AutoCommand and
// "bun"
(ctx.positionals.len == 0 or
// "bun file.js"
ctx.positionals.len > 0 and options.defaultLoaders.has(std.fs.path.extension(ctx.positionals[0]))))))
{
config_path_ = "bunfig.toml";
auto_loaded = true;
}
if (config_path_.len == 0) {
return;
}
defer ctx.debug.loaded_bunfig = true;
var config_path: [:0]u8 = undefined;
if (config_path_[0] == '/') {
@memcpy(config_buf[0..config_path_.len], config_path_);
config_buf[config_path_.len] = 0;
config_path = config_buf[0..config_path_.len :0];
} else {
if (ctx.args.absolute_working_dir == null) {
var secondbuf: [bun.MAX_PATH_BYTES]u8 = undefined;
var cwd = bun.getcwd(&secondbuf) catch return;
ctx.args.absolute_working_dir = try allocator.dupe(u8, cwd);
}
var parts = [_]string{ ctx.args.absolute_working_dir.?, config_path_ };
config_path_ = resolve_path.joinAbsStringBuf(
ctx.args.absolute_working_dir.?,
&config_buf,
&parts,
.auto,
);
config_buf[config_path_.len] = 0;
config_path = config_buf[0..config_path_.len :0];
}
try loadConfigPath(allocator, auto_loaded, config_path, ctx, comptime cmd);
}
pub fn loadConfigWithCmdArgs(
comptime cmd: Command.Tag,
allocator: std.mem.Allocator,
args: clap.Args(clap.Help, cmd.params()),
ctx: *Command.Context,
) !void {
return try loadConfig(allocator, args.option("--config"), ctx, comptime cmd);
}
pub fn parse(allocator: std.mem.Allocator, ctx: *Command.Context, comptime cmd: Command.Tag) !Api.TransformOptions {
var diag = clap.Diagnostic{};
const params_to_parse = comptime cmd.params();
var args = clap.parse(clap.Help, params_to_parse, .{
.diagnostic = &diag,
.allocator = allocator,
.stop_after_positional_at = switch (cmd) {
.RunCommand => 2,
.AutoCommand => 1,
else => 0,
},
}) catch |err| {
// Report useful error and exit
diag.report(Output.errorWriter(), err) catch {};
cmd.printHelp(false);
Global.exit(1);
};
const print_help = args.flag("--help");
if (print_help) {
cmd.printHelp(true);
Output.flush();
Global.exit(0);
}
if (cmd == .AutoCommand) {
if (args.flag("--version")) {
printVersionAndExit();
}
if (args.flag("--revision")) {
printRevisionAndExit();
}
}
var cwd: []u8 = undefined;
if (args.option("--cwd")) |cwd_| {
cwd = brk: {
var outbuf: [bun.MAX_PATH_BYTES]u8 = undefined;
const out = std.os.realpath(cwd_, &outbuf) catch |err| {
Output.prettyErrorln("error resolving --cwd: {s}", .{@errorName(err)});
Global.exit(1);
};
break :brk try allocator.dupe(u8, out);
};
} else {
cwd = try bun.getcwdAlloc(allocator);
}
if (cmd == .TestCommand) {
if (args.option("--timeout")) |timeout_ms| {
if (timeout_ms.len > 0) {
ctx.test_options.default_timeout_ms = std.fmt.parseInt(u32, timeout_ms, 10) catch {
Output.prettyErrorln("<r><red>error<r>: Invalid timeout: \"{s}\"", .{timeout_ms});
Global.exit(1);
};
}
}
if (!ctx.test_options.coverage.enabled) {
ctx.test_options.coverage.enabled = args.flag("--coverage");
}
if (args.option("--bail")) |bail| {
if (bail.len > 0) {
ctx.test_options.bail = std.fmt.parseInt(u32, bail, 10) catch |e| {
Output.prettyErrorln("<r><red>error<r>: --bail expects a number: {s}", .{@errorName(e)});
Global.exit(1);
};
if (ctx.test_options.bail == 0) {
Output.prettyErrorln("<r><red>error<r>: --bail expects a number greater than 0", .{});
Global.exit(1);
}
} else {
ctx.test_options.bail = 1;
}
}
if (args.option("--rerun-each")) |repeat_count| {
if (repeat_count.len > 0) {
ctx.test_options.repeat_count = std.fmt.parseInt(u32, repeat_count, 10) catch |e| {
Output.prettyErrorln("<r><red>error<r>: --rerun-each expects a number: {s}", .{@errorName(e)});
Global.exit(1);
};
}
}
if (args.option("--test-name-pattern")) |namePattern| {
const regex = RegularExpression.init(bun.String.fromBytes(namePattern), RegularExpression.Flags.none) catch {
Output.prettyErrorln(
"<r><red>error<r>: --test-name-pattern expects a valid regular expression but received {}",
.{
strings.QuotedFormatter{
.text = namePattern,
},
},
);
Global.exit(1);
};
ctx.test_options.test_filter_regex = regex;
}
ctx.test_options.update_snapshots = args.flag("--update-snapshots");
ctx.test_options.run_todo = args.flag("--todo");
ctx.test_options.only = args.flag("--only");
}
ctx.args.absolute_working_dir = cwd;
ctx.positionals = args.positionals();
if (comptime Command.Tag.loads_config.get(cmd)) {
try loadConfigWithCmdArgs(cmd, allocator, args, ctx);
}
var opts: Api.TransformOptions = ctx.args;
var defines_tuple = try DefineColonList.resolve(allocator, args.options("--define"));
if (defines_tuple.keys.len > 0) {
opts.define = .{
.keys = defines_tuple.keys,
.values = defines_tuple.values,
};
}
var loader_tuple = try LoaderColonList.resolve(allocator, args.options("--loader"));
if (loader_tuple.keys.len > 0) {
opts.loaders = .{
.extensions = loader_tuple.keys,
.loaders = loader_tuple.values,
};
}
opts.tsconfig_override = if (args.option("--tsconfig-override")) |ts|
(Arguments.readFile(allocator, cwd, ts) catch |err| fileReadError(err, Output.errorStream(), ts, "tsconfig.json"))
else
null;
opts.serve = false; // TODO
opts.main_fields = args.options("--main-fields");
// we never actually supported inject.
// opts.inject = args.options("--inject");
opts.env_files = args.options("--env-file");
opts.extension_order = args.options("--extension-order");
ctx.passthrough = args.remaining();
// runtime commands
if (cmd == .AutoCommand or cmd == .RunCommand or cmd == .TestCommand) {
const preloads = args.options("--preload");
if (args.flag("--hot")) {
ctx.debug.hot_reload = .hot;
} else if (args.flag("--watch")) {
ctx.debug.hot_reload = .watch;
bun.auto_reload_on_crash = true;
}
if (args.option("--origin")) |origin| {
opts.origin = origin;
}
if (args.option("--port")) |port_str| {
opts.port = std.fmt.parseInt(u16, port_str, 10) catch return error.InvalidPort;
}
ctx.debug.offline_mode_setting = if (args.flag("--prefer-offline"))
Bunfig.OfflineMode.offline
else if (args.flag("--prefer-latest"))
Bunfig.OfflineMode.latest
else
Bunfig.OfflineMode.online;
if (args.flag("--no-install")) {
ctx.debug.global_cache = .disable;
} else if (args.flag("-i")) {
ctx.debug.global_cache = .fallback;
} else if (args.option("--install")) |enum_value| {
// -i=auto --install=force, --install=disable
if (options.GlobalCache.Map.get(enum_value)) |result| {
ctx.debug.global_cache = result;
// -i, --install
} else if (enum_value.len == 0) {
ctx.debug.global_cache = options.GlobalCache.force;
} else {
Output.prettyErrorln("Invalid value for --install: \"{s}\". Must be either \"auto\", \"fallback\", \"force\", or \"disable\"\n", .{enum_value});
Global.exit(1);
}
}
if (ctx.preloads.len > 0 and preloads.len > 0) {
var all = std.ArrayList(string).initCapacity(ctx.allocator, ctx.preloads.len + preloads.len) catch unreachable;
all.appendSliceAssumeCapacity(ctx.preloads);
all.appendSliceAssumeCapacity(preloads);
ctx.preloads = all.items;
} else if (preloads.len > 0) {
ctx.preloads = preloads;
}
ctx.runtime_options.eval_script = args.option("--eval") orelse "";
ctx.runtime_options.if_present = args.flag("--if-present");
ctx.runtime_options.smol = args.flag("--smol");
if (args.option("--inspect")) |inspect_flag| {
ctx.runtime_options.debugger = if (inspect_flag.len == 0)
Command.Debugger{ .enable = .{} }
else
Command.Debugger{ .enable = .{
.path_or_port = inspect_flag,
} };
} else if (args.option("--inspect-wait")) |inspect_flag| {
ctx.runtime_options.debugger = if (inspect_flag.len == 0)
Command.Debugger{ .enable = .{
.wait_for_connection = true,
} }
else
Command.Debugger{ .enable = .{
.path_or_port = inspect_flag,
.wait_for_connection = true,
} };
} else if (args.option("--inspect-brk")) |inspect_flag| {
ctx.runtime_options.debugger = if (inspect_flag.len == 0)
Command.Debugger{ .enable = .{
.wait_for_connection = true,
.set_breakpoint_on_first_line = true,
} }
else
Command.Debugger{ .enable = .{
.path_or_port = inspect_flag,
.wait_for_connection = true,
.set_breakpoint_on_first_line = true,
} };
}
}
if (opts.port != null and opts.origin == null) {
opts.origin = try std.fmt.allocPrint(allocator, "http://localhost:{d}/", .{opts.port.?});
}
var output_dir: ?string = null;
var output_file: ?string = null;
if (cmd == .BuildCommand) {
ctx.bundler_options.transform_only = args.flag("--no-bundle");
const minify_flag = args.flag("--minify");
ctx.bundler_options.minify_syntax = minify_flag or args.flag("--minify-syntax");
ctx.bundler_options.minify_whitespace = minify_flag or args.flag("--minify-whitespace");
ctx.bundler_options.minify_identifiers = minify_flag or args.flag("--minify-identifiers");
if (args.options("--external").len > 0) {
var externals = try allocator.alloc([]u8, args.options("--external").len);
for (args.options("--external"), 0..) |external, i| {
externals[i] = constStrToU8(external);
}
opts.external = externals;
}
const TargetMatcher = strings.ExactSizeMatcher(8);
if (args.option("--target")) |_target| {
opts.target = opts.target orelse switch (TargetMatcher.match(_target)) {
TargetMatcher.case("browser") => Api.Target.browser,
TargetMatcher.case("node") => Api.Target.node,
TargetMatcher.case("macro") => if (cmd == .BuildCommand) Api.Target.bun_macro else Api.Target.bun,
TargetMatcher.case("bun") => Api.Target.bun,
else => invalidTarget(&diag, _target),
};
ctx.debug.run_in_bun = opts.target.? == .bun;
}
if (args.flag("--watch")) {
ctx.debug.hot_reload = .watch;
bun.auto_reload_on_crash = true;
}
if (args.flag("--compile")) {
ctx.bundler_options.compile = true;
}
if (args.option("--outdir")) |outdir| {
if (outdir.len > 0) {
ctx.bundler_options.outdir = outdir;
}
} else if (args.option("--outfile")) |outfile| {
if (outfile.len > 0) {
ctx.bundler_options.outfile = outfile;
}
}
if (args.option("--root")) |root_dir| {
if (root_dir.len > 0) {
ctx.bundler_options.root_dir = root_dir;
}
}
if (args.option("--format")) |format_str| {
const format = options.Format.fromString(format_str) orelse {
Output.prettyErrorln("<r><red>error<r>: Invalid format - must be esm, cjs, or iife", .{});
Global.crash();
};
switch (format) {
.esm => {},
else => {
Output.prettyErrorln("<r><red>error<r>: Formats besides 'esm' are not implemented", .{});
Global.crash();
},
}
}
if (args.flag("--splitting")) {
ctx.bundler_options.code_splitting = true;
}
if (args.option("--entry-naming")) |entry_naming| {
ctx.bundler_options.entry_naming = try strings.concat(allocator, &.{ "./", entry_naming });
}
if (args.option("--chunk-naming")) |chunk_naming| {
ctx.bundler_options.chunk_naming = try strings.concat(allocator, &.{ "./", chunk_naming });
}
if (args.option("--asset-naming")) |asset_naming| {
ctx.bundler_options.asset_naming = try strings.concat(allocator, &.{ "./", asset_naming });
}
if (comptime FeatureFlags.react_server_components) {
if (args.flag("--server-components")) {
ctx.bundler_options.react_server_components = true;
}
}
if (args.option("--sourcemap")) |setting| {
if (setting.len == 0 or strings.eqlComptime(setting, "inline")) {
opts.source_map = Api.SourceMapMode.inline_into_file;
} else if (strings.eqlComptime(setting, "none")) {
opts.source_map = Api.SourceMapMode._none;
} else if (strings.eqlComptime(setting, "external")) {
opts.source_map = Api.SourceMapMode.external;
} else {
Output.prettyErrorln("<r><red>error<r>: Invalid sourcemap setting: \"{s}\"", .{setting});
Global.crash();
}
}
}
if (opts.entry_points.len == 0) {
var entry_points = ctx.positionals;
switch (comptime cmd) {
.BuildCommand => {
if (entry_points.len > 0 and (strings.eqlComptime(
entry_points[0],
"build",
) or strings.eqlComptime(entry_points[0], "bun"))) {
var out_entry = entry_points[1..];
for (entry_points, 0..) |entry, i| {
if (entry.len > 0) {
out_entry = out_entry[i..];
break;
}
}
entry_points = out_entry;
}
},
.RunCommand => {
if (entry_points.len > 0 and (strings.eqlComptime(
entry_points[0],
"run",
) or strings.eqlComptime(
entry_points[0],
"r",
))) {
entry_points = entry_points[1..];
}
},
else => {},
}
opts.entry_points = entry_points;
}
var jsx_factory = args.option("--jsx-factory");
var jsx_fragment = args.option("--jsx-fragment");
var jsx_import_source = args.option("--jsx-import-source");
var jsx_runtime = args.option("--jsx-runtime");
const react_fast_refresh = true;
if (cmd == .AutoCommand or cmd == .RunCommand) {
ctx.debug.silent = args.flag("--silent");
ctx.debug.run_in_bun = args.flag("--bun") or ctx.debug.run_in_bun;
}
opts.resolve = Api.ResolveMode.lazy;
if (jsx_factory != null or
jsx_fragment != null or
jsx_import_source != null or
jsx_runtime != null or
!react_fast_refresh)
{
var default_factory = "".*;
var default_fragment = "".*;
var default_import_source = "".*;
if (opts.jsx == null) {
opts.jsx = Api.Jsx{
.factory = constStrToU8(jsx_factory orelse &default_factory),
.fragment = constStrToU8(jsx_fragment orelse &default_fragment),
.import_source = constStrToU8(jsx_import_source orelse &default_import_source),
.runtime = if (jsx_runtime) |runtime| try resolve_jsx_runtime(runtime) else Api.JsxRuntime.automatic,
.development = false,
.react_fast_refresh = react_fast_refresh,
};
} else {
opts.jsx = Api.Jsx{
.factory = constStrToU8(jsx_factory orelse opts.jsx.?.factory),
.fragment = constStrToU8(jsx_fragment orelse opts.jsx.?.fragment),
.import_source = constStrToU8(jsx_import_source orelse opts.jsx.?.import_source),
.runtime = if (jsx_runtime) |runtime| try resolve_jsx_runtime(runtime) else opts.jsx.?.runtime,
.development = false,
.react_fast_refresh = react_fast_refresh,
};
}
}
if (cmd == .BuildCommand) {
if (opts.entry_points.len == 0 and opts.framework == null) {
Output.prettyErrorln("<r><b>bun build <r><d>v" ++ Global.package_json_version_with_sha ++ "<r>", .{});
Output.prettyError("<r><red>error: Missing entrypoints. What would you like to bundle?<r>\n\n", .{});
Output.flush();
Output.pretty("Usage:\n <d>$<r> <b><green>bun build<r> \\<entrypoint\\> [...\\<entrypoints\\>] <cyan>[...flags]<r> \n", .{});
Output.pretty("\nTo see full documentation:\n <d>$<r> <b><green>bun build<r> --help\n", .{});
Output.flush();
Global.exit(1);
}
}
if (opts.log_level) |log_level| {
logger.Log.default_log_level = switch (log_level) {
.debug => logger.Log.Level.debug,
.err => logger.Log.Level.err,
.warn => logger.Log.Level.warn,
else => logger.Log.Level.err,
};
ctx.log.level = logger.Log.default_log_level;
}
if (args.flag("--no-macros")) {
ctx.debug.macros = .{ .disable = {} };
}
opts.output_dir = output_dir;
if (output_file != null)
ctx.debug.output_file = output_file.?;
return opts;
}
};
const AutoCommand = struct {
pub fn exec(allocator: std.mem.Allocator) !void {
try HelpCommand.execWithReason(allocator, .invalid_command);
}
};
const InitCommand = @import("./cli/init_command.zig").InitCommand;
pub const HelpCommand = struct {
pub fn exec(allocator: std.mem.Allocator) !void {
@setCold(true);
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><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>link<r> <d>[\<package\>]<r> Register or link a local npm package
\\ <b><blue>unlink<r> Unregister a local npm package
\\ <b><blue>pm <d>\<subcommand\><r> Additional package management utilities
\\
\\ <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 blank 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.
\\ <d>\<command\><r> <b><cyan>--help<r> Print help text for command.
\\
;
const cli_helptext_footer =
\\
\\Learn more about Bun: <magenta>https://bun.sh/docs<r>
\\Join our Discord community: <blue>https://bun.sh/discord<r>
\\
;
pub fn printWithReason(comptime reason: Reason, show_all_flags: bool) void {
var rand_state = std.rand.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_create_filler[package_create_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],
};
switch (reason) {
.explicit => {
Output.pretty(
"<r><b><magenta>Bun<r> is a fast JavaScript runtime, package manager, bundler, and test runner. <d>(" ++
Global.package_json_version_with_sha ++
")<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 {
@setCold(true);
printWithReason(reason, false);
if (reason == .invalid_command) {
std.process.exit(1);
}
}
};
pub const ReservedCommand = struct {
pub fn exec(_: std.mem.Allocator) !void {
@setCold(true);
const command_name = 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);
}
};
const AddCompletions = @import("./cli/add_completions.zig");
pub const Command = struct {
var script_name_buf: [bun.MAX_PATH_BYTES]u8 = undefined;
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,
// 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 = "",
};