@@ -527,6 +527,7 @@ const usage_fmt =
527
527
\\Options:
528
528
\\ --help Print this help and exit
529
529
\\ --color [auto|off|on] Enable or disable colored error messages
530
+ \\ --stdin Format code from stdin
530
531
\\
531
532
\\
532
533
;
@@ -538,6 +539,7 @@ const args_fmt_spec = []Flag{
538
539
"off" ,
539
540
"on" ,
540
541
}),
542
+ Flag .Bool ("--stdin" ),
541
543
};
542
544
543
545
const Fmt = struct {
@@ -579,11 +581,6 @@ fn cmdFmt(allocator: *Allocator, args: []const []const u8) !void {
579
581
os .exit (0 );
580
582
}
581
583
582
- if (flags .positionals .len == 0 ) {
583
- try stderr .write ("expected at least one source file argument\n " );
584
- os .exit (1 );
585
- }
586
-
587
584
const color = blk : {
588
585
if (flags .single ("color" )) | color_flag | {
589
586
if (mem .eql (u8 , color_flag , "auto" )) {
@@ -598,6 +595,44 @@ fn cmdFmt(allocator: *Allocator, args: []const []const u8) !void {
598
595
}
599
596
};
600
597
598
+ if (flags .present ("stdin" )) {
599
+ if (flags .positionals .len != 0 ) {
600
+ try stderr .write ("cannot use --stdin with positional arguments\n " );
601
+ os .exit (1 );
602
+ }
603
+
604
+ var stdin_file = try io .getStdIn ();
605
+ var stdin = io .FileInStream .init (& stdin_file );
606
+
607
+ const source_code = try stdin .stream .readAllAlloc (allocator , @maxValue (usize ));
608
+ defer allocator .free (source_code );
609
+
610
+ var tree = std .zig .parse (allocator , source_code ) catch | err | {
611
+ try stderr .print ("error parsing stdin: {}\n " , err );
612
+ os .exit (1 );
613
+ };
614
+ defer tree .deinit ();
615
+
616
+ var error_it = tree .errors .iterator (0 );
617
+ while (error_it .next ()) | parse_error | {
618
+ const msg = try errmsg .createFromParseError (allocator , parse_error , & tree , "<stdin>" );
619
+ defer allocator .destroy (msg );
620
+
621
+ try errmsg .printToFile (& stderr_file , msg , color );
622
+ }
623
+ if (tree .errors .len != 0 ) {
624
+ os .exit (1 );
625
+ }
626
+
627
+ _ = try std .zig .render (allocator , stdout , & tree );
628
+ return ;
629
+ }
630
+
631
+ if (flags .positionals .len == 0 ) {
632
+ try stderr .write ("expected at least one source file argument\n " );
633
+ os .exit (1 );
634
+ }
635
+
601
636
var fmt = Fmt {
602
637
.seen = std .HashMap ([]const u8 , void , mem .hash_slice_u8 , mem .eql_slice_u8 ).init (allocator ),
603
638
.queue = std .LinkedList ([]const u8 ).init (),
0 commit comments