~gpanders/wk

d89283e0aaf59f39d8b6dce223473d68dfe480be — Greg Anders 8 months ago 6e91c77
Read arguments from stdin if stdin is not a TTY

This means commands can be composed using

    zet tag TAG | zet open

With fish, the former method still works too:

    zet open (zet tag TAG)

fish handles spaces and line separators in command output much better
than bash.
1 files changed, 25 insertions(+), 16 deletions(-)

M src/main.zig
M src/main.zig => src/main.zig +25 -16
@@ 32,22 32,10 @@ pub fn main() anyerror!void {
    try std.process.changeCurDir(dir);

    const command = arglist[1];
    var args: ?[][]const u8 = if (arglist.len > 2) arglist[2..] else null;

    // If first arg is a newline delimited string, split it into separate
    // lines. This can happen when the result of one zet command is used as the
    // argument to another zet command
    if (args != null and std.mem.indexOf(u8, args.?[0], "\n") != null) {
        var lines = std.ArrayList([]const u8).init(allocator);
        defer lines.deinit();

        var it = std.mem.split(args.?[0], "\n");
        while (it.next()) |line| {
            try lines.append(line);
        }

        args = lines.toOwnedSlice();
    }
    var args: ?[][]const u8 = if (arglist.len > 2 and !std.mem.eql(u8, arglist[2], "-"))
        arglist[2..]
    else
        try readFromStdin(allocator);

    cmd.handleCommand(allocator, command, args) catch |err| return switch (err) {
        error.UnknownCommand => {


@@ 70,3 58,24 @@ pub fn main() anyerror!void {
        else => return err,
    };
}

fn readFromStdin(allocator: *std.mem.Allocator) !?[][]const u8 {
    if (std.io.getStdIn().isTty()) {
        return null;
    }

    var input = try std.io.getStdIn().inStream().readAllAlloc(allocator, 1 * 1024 * 1024);
    defer allocator.free(input);

    var args = std.ArrayList([]const u8).init(allocator);
    defer args.deinit();

    var it = std.mem.split(input, "\n");
    while (it.next()) |line| {
        if (line.len == 0) continue;
        const arg = try std.mem.dupe(allocator, u8, line);
        try args.append(arg);
    }

    return args.toOwnedSlice();
}