~gpanders/wk

ref: c0e190f572906dced35606b0d999d4390183c3c6 wk/src/cmd/show.zig -rw-r--r-- 1.5 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
const std = @import("std");
const ChildProcess = std.ChildProcess;
const fs = std.fs;
const mem = std.mem;

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

pub const cmd = Command{
    .name = "show",
    .aliases = &[_][]const u8{"s"},
    .usage = "s|show <NOTE> [NOTE ...]",
    .desc = "Display contents of notes to stdout.",
    .run = run,
};

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

            const writer = ColorWriter.new(std.io.getStdOut());

            writer.setColor(.Blue).print("{}\n", .{zet.fname});
            writer.setColor(.Yellow).print("{}", .{zet.contents[0..3]});

            const metadata_end = blk: {
                if (mem.indexOfPos(u8, zet.contents, 3, "...")) |i| {
                    break :blk i;
                } else if (mem.indexOfPos(u8, zet.contents, 3, "---")) |i| {
                    break :blk i;
                } else unreachable;
            };

            writer.print("{}", .{zet.contents[3..metadata_end]});

            writer.setColor(.Yellow).print("{}", .{zet.contents[metadata_end .. metadata_end + 3]});
            writer.print("{}\n", .{zet.contents[metadata_end + 3 ..]});
        }
    } else {
        return error.MissingRequiredArgument;
    }
}