~gpanders/wk

ref: 2b92540a79bcc7513853514ee61bc4126e5e8f04 wk/src/cmd/new.zig -rw-r--r-- 1.7 KiB
2b92540a — Greg Anders Print new Zettel name when stdout is not a tty 2 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
const std = @import("std");
const io = std.io;
const fmt = std.fmt;
const mem = std.mem;
const stdout = std.io.getStdOut().outStream();

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

pub const cmd = Command{
    .name = "new",
    .aliases = &[_][]const u8{"n"},
    .usage = "n|new <TITLE>",
    .desc = "Create a new note with the given title.",
    .run = run,
};

pub fn run(allocator: *mem.Allocator, args: ?[]const []const u8) Command.Error!void {
    if (args) |_| {
        const title = args.?[0];
        var new_zettel = try Zettel.new(allocator, title);

        if (!io.getStdOut().isTty()) {
            stdout.print("{}\n", .{new_zettel.fname}) catch {};
            return;
        }

        try openZettels(allocator, &[_]Zettel{new_zettel});

        new_zettel.contents = try new_zettel.read();

        const zettels = try getZettels(allocator);
        const links = try new_zettel.links();
        for (links) |link| {
            for (zettels) |*zet| {
                if (mem.eql(u8, link, zet.id)) try zet.backlinks.append(&new_zettel);
            }
        }

        var modified = std.ArrayList([]const u8).init(allocator);
        try modified.append(new_zettel.fname);

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

        const msg = try fmt.allocPrint(allocator, "New note: {}", .{title});
        try commit(allocator, modified.items, msg);
    } else {
        return error.MissingRequiredArgument;
    }
}