Skip to content

Commit

Permalink
Add support for stdin input with the - filename
Browse files Browse the repository at this point in the history
  • Loading branch information
Arnau478 committed Jul 7, 2024
1 parent bc01fda commit e31c09b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
2 changes: 1 addition & 1 deletion src/argparse.zig
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ pub fn parse(args: []const []const u8) ParseResult {
continue;
}

if (arg[0] == '-') {
if (arg[0] == '-' and arg.len > 1) {
if (arg.len <= 1) {
main.fail("expected flag", .{});
}
Expand Down
20 changes: 13 additions & 7 deletions src/main.zig
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,19 @@ pub fn main() void {
else => fail("{s}", .{@errorName(err)}),
};
} else {
if (parsed_args.filename) |filename| {
const file = std.fs.cwd().openFile(filename, .{}) catch |err| switch (err) {
error.FileNotFound => fail("{s} not found", .{filename}),
error.IsDir => fail("{s} is a directory", .{filename}),
else => fail("{s} could not be opened", .{filename}),
};
defer file.close();
if (parsed_args.filename) |true_filename| {
const is_stdin = std.mem.eql(u8, true_filename, "-");
const filename = if (is_stdin) "<stdin>" else true_filename;

const file = if (is_stdin)
std.io.getStdIn()
else
std.fs.cwd().openFile(filename, .{}) catch |err| switch (err) {
error.FileNotFound => fail("{s} not found", .{filename}),
error.IsDir => fail("{s} is a directory", .{filename}),
else => fail("{s} could not be opened", .{filename}),
};
defer if (!is_stdin) file.close();

const data = file.readToEndAlloc(allocator, std.math.maxInt(usize)) catch |err| switch (err) {
error.OutOfMemory => fail("Out of memory", .{}),
Expand Down

0 comments on commit e31c09b

Please sign in to comment.