~gpanders/wk

ref: c0e190f572906dced35606b0d999d4390183c3c6 wk/src/cmd/open.zig -rw-r--r-- 2.0 KiB
c0e190f5 — Greg Anders Make patterns match on zettel contents 3 months ago
                                                                                
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
const std = @import("std");
const ascii = std.ascii;
const fmt = std.fmt;
const mem = std.mem;
const os = std.os;
const warn = std.debug.warn;

const Command = @import("../cmd.zig").Command;
const Zettel = @import("../zettel.zig").Zettel;
const getZettels = @import("../zettel.zig").getZettels;
const commit = @import("../util.zig").commit;

pub const cmd = Command{
    .name = "open",
    .aliases = &[_][]const u8{"o"},
    .usage = "o|open [NOTE [NOTE ...]]",
    .desc = "Open the given notes in your $EDITOR.",
    .run = run,
};

pub fn run(allocator: *mem.Allocator, args: ?[]const []const u8) Command.Error!void {
    const zettels = try getZettels(allocator);

    var argv = std.ArrayList([]const u8).init(allocator);
    try argv.append(os.getenv("EDITOR") orelse "vi");

    if (args) |patterns| {
        for (zettels) |zet| {
            if (zet.match(patterns)) try argv.append(zet.fname);
        }
    }

    var proc = try std.ChildProcess.init(argv.items, allocator);
    defer proc.deinit();

    const term = try proc.spawnAndWait();
    switch (term) {
        .Exited => {},
        else => {
            warn("The following command terminated unexpectedly:\n", .{});
            for (argv.items) |arg| warn("{} ", .{arg});
            return error.CommandFailed;
        },
    }

    var modified = std.ArrayList(*const Zettel).init(allocator);

    for (zettels) |*zet| {
        try zet.writeBacklinks();
        if (try zet.modified()) try modified.append(zet);
    }

    var lines = try std.ArrayList([]const u8).initCapacity(allocator, modified.items.len + 2);
    var files = try std.ArrayList([]const u8).initCapacity(allocator, modified.items.len);

    lines.appendAssumeCapacity(try fmt.allocPrint(allocator, "Updated {} files\n", .{modified.items.len}));
    for (modified.items) |mod| {
        lines.appendAssumeCapacity(try fmt.allocPrint(allocator, "- [[{}]] {}", .{ mod.id, mod.title }));
        files.appendAssumeCapacity(mod.fname);
    }

    const msg = try mem.join(allocator, "\n", lines.items);
    try commit(allocator, files.items, msg);
}