Skip to content

Commit bf441ed

Browse files
tiehuisandrewrk
authored andcommittedJul 14, 2018
Add --stdin option to zig fmt
·
0.15.10.3.0
1 parent ed3181f commit bf441ed

File tree

1 file changed

+40
-5
lines changed

1 file changed

+40
-5
lines changed
 

‎src-self-hosted/main.zig‎

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -527,6 +527,7 @@ const usage_fmt =
527527
\\Options:
528528
\\ --help Print this help and exit
529529
\\ --color [auto|off|on] Enable or disable colored error messages
530+
\\ --stdin Format code from stdin
530531
\\
531532
\\
532533
;
@@ -538,6 +539,7 @@ const args_fmt_spec = []Flag{
538539
"off",
539540
"on",
540541
}),
542+
Flag.Bool("--stdin"),
541543
};
542544

543545
const Fmt = struct {
@@ -579,11 +581,6 @@ fn cmdFmt(allocator: *Allocator, args: []const []const u8) !void {
579581
os.exit(0);
580582
}
581583

582-
if (flags.positionals.len == 0) {
583-
try stderr.write("expected at least one source file argument\n");
584-
os.exit(1);
585-
}
586-
587584
const color = blk: {
588585
if (flags.single("color")) |color_flag| {
589586
if (mem.eql(u8, color_flag, "auto")) {
@@ -598,6 +595,44 @@ fn cmdFmt(allocator: *Allocator, args: []const []const u8) !void {
598595
}
599596
};
600597

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+
601636
var fmt = Fmt{
602637
.seen = std.HashMap([]const u8, void, mem.hash_slice_u8, mem.eql_slice_u8).init(allocator),
603638
.queue = std.LinkedList([]const u8).init(),

0 commit comments

Comments
 (0)
Please sign in to comment.