Skip to content
zit Artifact [cb071dc59d]
Login

Artifact [cb071dc59d]

Artifact cb071dc59d7bc7ddc9ad76c6da43dea617eb8e9510baac1c7e943a7804baa077:


//! `zit ticket show` / `zit ticket list` — read a ticket back.
//!
//! The store keeps a ticket as a run of change artifacts (a K card naming the
//! ticket, J cards setting fields). The ticket as people see it is those
//! changes replayed in time order, as Fossil's ticket rebuild does: a J
//! field replaces the value, a `+field` appends to it. There is no ticket
//! index, so every read scans the store for ticket artifacts — the same
//! full-store read `ticket set` already pays to check its id.
//!
//! The comment fields (`comment`, `icomment`) are a history, not a value:
//! each change that sets one contributes a comment with that change's author
//! and time, and they are left out of the field list.

const std = @import("std");
const zit = @import("zit");
const cli = @import("zit").cli;
const artifact = @import("zit").artifact;
const logstore = @import("zit").logstore;
const storage = @import("zit").storage;

const diagnostics = @import("../cli/diagnostics.zig");
const help_pages = @import("../cli/help.zig");
const stateOom = diagnostics.stateOom;

/// The shortest ticket id prefix `set` and `show` expand, as Fossil's name
/// resolution does for a check-in.
pub const min_prefix = 4;

/// The most candidates an ambiguous prefix names.
const max_candidates = 8;

/// The shortest id `list` prints.
const short_id_len = 10;

pub fn isLowerHex(s: []const u8) bool {
    for (s) |c| {
        const ok = (c >= '0' and c <= '9') or (c >= 'a' and c <= 'f');
        if (!ok) return false;
    }
    return true;
}

const Change = struct {
    rid: u64,
    id: []const u8,
    time: []const u8,
    user: []const u8,
    fields: []const artifact.JCard,
};

const Field = struct { name: []const u8, value: []const u8 };

const Comment = struct { time: []const u8, user: []const u8, text: []const u8 };

const Ticket = struct {
    id: []const u8,
    created: []const u8,
    changed: []const u8,
    fields: []const Field,
    comments: []const Comment,

    fn get(t: Ticket, name: []const u8) ?[]const u8 {
        for (t.fields) |f| if (std.mem.eql(u8, f.name, name)) return f.value;
        return null;
    }
};

fn changeLess(_: void, a: Change, b: Change) bool {
    return switch (std.mem.order(u8, a.time, b.time)) {
        .lt => true,
        .gt => false,
        .eq => a.rid < b.rid,
    };
}

fn fieldLess(_: void, a: Field, b: Field) bool {
    return std.mem.lessThan(u8, a.name, b.name);
}

fn isCommentField(name: []const u8) bool {
    return std.mem.eql(u8, name, "comment") or std.mem.eql(u8, name, "icomment");
}

/// Replay `changes` (all of one ticket) into the ticket. Sorts them in place.
fn replay(arena: std.mem.Allocator, id: []const u8, changes: []Change) error{OutOfMemory}!Ticket {
    std.mem.sort(Change, changes, {}, changeLess);
    var fields: std.ArrayList(Field) = .empty;
    var comments: std.ArrayList(Comment) = .empty;
    for (changes) |ch| {
        for (ch.fields) |j| {
            const append = j.field.len > 1 and j.field[0] == '+';
            const name = if (append) j.field[1..] else j.field;
            if (isCommentField(name)) {
                if (j.value.len != 0) try comments.append(arena, .{ .time = ch.time, .user = ch.user, .text = j.value });
                continue;
            }
            var slot: ?*Field = null;
            for (fields.items) |*f| {
                if (std.mem.eql(u8, f.name, name)) slot = f;
            }
            if (slot) |f| {
                f.value = if (append) try std.mem.concat(arena, u8, &.{ f.value, j.value }) else j.value;
            } else {
                try fields.append(arena, .{ .name = name, .value = j.value });
            }
        }
    }
    std.mem.sort(Field, fields.items, {}, fieldLess);
    return .{
        .id = id,
        .created = changes[0].time,
        .changed = changes[changes.len - 1].time,
        .fields = fields.items,
        .comments = comments.items,
    };
}

/// One ticket-change artifact's content as a Change, or null when the bytes
/// are not one. Strings are copied into `arena`.
fn changeOf(gpa: std.mem.Allocator, arena: std.mem.Allocator, rid: u64, bytes: []const u8) error{OutOfMemory}!?Change {
    // A ticket change starts with its D card and carries a K card; anything
    // else cannot be one, so most of the store is skipped without a parse.
    if (!std.mem.startsWith(u8, bytes, "D ")) return null;
    if (std.mem.indexOf(u8, bytes, "\nK ") == null) return null;
    var m = artifact.parse(gpa, bytes) catch return null;
    defer m.deinit();
    if (m.kind != .ticket) return null;
    const k = m.k orelse return null;
    const d = m.d orelse return null;
    const fields = try arena.alloc(artifact.JCard, m.j.len);
    for (m.j, fields) |src, *dst| {
        dst.* = .{ .field = try arena.dupe(u8, src.field), .value = try arena.dupe(u8, src.value) };
    }
    return .{
        .rid = rid,
        .id = try arena.dupe(u8, k.ticket_id),
        .time = try arena.dupe(u8, d.timestamp),
        .user = try arena.dupe(u8, if (m.u) |u| u.login else ""),
        .fields = fields,
    };
}

/// `D` timestamps are `YYYY-MM-DDTHH:MM:SS[.fff]`; show `YYYY-MM-DD HH:MM:SS`.
fn displayTime(arena: std.mem.Allocator, ts: []const u8) error{OutOfMemory}![]const u8 {
    const cut = @min(ts.len, 19);
    const out = try arena.dupe(u8, ts[0..cut]);
    if (out.len > 10 and out[10] == 'T') out[10] = ' ';
    return out;
}

fn writeIndented(out: *std.Io.Writer, text: []const u8, indent: []const u8) !void {
    var it = std.mem.splitScalar(u8, std.mem.trimEnd(u8, text, "\r\n"), '\n');
    while (it.next()) |line| {
        try out.writeAll(indent);
        try out.writeAll(std.mem.trimEnd(u8, line, "\r"));
        try out.writeByte('\n');
    }
}

fn oneLine(arena: std.mem.Allocator, s: []const u8) error{OutOfMemory}![]const u8 {
    const out = try arena.dupe(u8, s);
    for (out) |*c| if (c.* == '\n' or c.* == '\r' or c.* == '\t') {
        c.* = ' ';
    };
    return out;
}

fn printShow(arena: std.mem.Allocator, streams: cli.Streams, t: Ticket) error{OutOfMemory}!void {
    const out = streams.out;
    out.print("tkt_uuid: {s}\n", .{t.id}) catch {};
    out.print("tkt_ctime: {s}\n", .{try displayTime(arena, t.created)}) catch {};
    out.print("tkt_mtime: {s}\n", .{try displayTime(arena, t.changed)}) catch {};
    for (t.fields) |f| {
        if (std.mem.indexOfScalar(u8, f.value, '\n') == null) {
            out.print("{s}: {s}\n", .{ f.name, f.value }) catch {};
        } else {
            out.print("{s}:\n", .{f.name}) catch {};
            writeIndented(out, f.value, "  ") catch {};
        }
    }
    for (t.comments) |c| {
        out.print("\ncomment by {s} at {s}\n", .{ c.user, try displayTime(arena, c.time) }) catch {};
        writeIndented(out, c.text, "  ") catch {};
    }
}

fn writeTicketJson(jw: *std.json.Stringify, arena: std.mem.Allocator, t: Ticket, with_detail: bool) !void {
    try jw.beginObject();
    try jw.objectField("tkt_uuid");
    try jw.write(t.id);
    try jw.objectField("tkt_ctime");
    try jw.write(try displayTime(arena, t.created));
    try jw.objectField("tkt_mtime");
    try jw.write(try displayTime(arena, t.changed));
    if (with_detail) {
        try jw.objectField("fields");
        try jw.beginObject();
        for (t.fields) |f| {
            try jw.objectField(f.name);
            try jw.write(f.value);
        }
        try jw.endObject();
        try jw.objectField("comments");
        try jw.beginArray();
        for (t.comments) |c| {
            try jw.beginObject();
            try jw.objectField("time");
            try jw.write(try displayTime(arena, c.time));
            try jw.objectField("user");
            try jw.write(c.user);
            try jw.objectField("text");
            try jw.write(c.text);
            try jw.endObject();
        }
        try jw.endArray();
    } else {
        inline for (.{ "status", "type", "title" }) |name| {
            try jw.objectField(name);
            try jw.write(t.get(name));
        }
    }
    try jw.endObject();
}

const Options = struct {
    json: bool = false,
    status: ?[]const u8 = null,
    id: ?[]const u8 = null,
};

/// Entry for `zit ticket show|list`; `args` follow the verb word.
pub fn run(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    is_list: bool,
    args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
) cli.Exit {
    var opt: Options = .{};
    var i: usize = 0;
    while (i < args.len) : (i += 1) {
        const tok = args[i];
        if (std.mem.eql(u8, tok, "-h") or std.mem.eql(u8, tok, "--help")) {
            streams.out.writeAll(help_pages.ticket_help) catch {};
            return .ok;
        } else if (std.mem.eql(u8, tok, "--json")) {
            opt.json = true;
        } else if (is_list and std.mem.eql(u8, tok, "--status")) {
            i += 1;
            if (i >= args.len) return cli.usageError(streams, "ticket", .unknown_option, "--status");
            opt.status = args[i];
        } else if (tok.len > 1 and tok[0] == '-') {
            return cli.usageError(streams, "ticket", .unknown_option, tok);
        } else if (!is_list and opt.id == null) {
            opt.id = tok;
        } else {
            return cli.usageError(streams, "ticket", .extra_argument, tok);
        }
    }
    if (!is_list) {
        const id = opt.id orelse {
            streams.err.writeAll("zit ticket: show needs a <ticket-id>\n") catch {};
            return .usage;
        };
        if (id.len < min_prefix or id.len > 40 or !isLowerHex(id)) {
            streams.err.print("zit ticket: '{s}' is not a ticket id ({d} to 40 lowercase hex)\n", .{ id, min_prefix }) catch {};
            return .failure;
        }
    }

    const root = (cli.resolveRoot(arena, io, amb.repo_override) catch return stateOom(streams, "ticket")) orelse {
        diagnostics.reportNoRoot(streams, io, "ticket", amb.repo_override);
        return .failure;
    };
    var root_dir = root.dir;
    defer root_dir.close(io);
    var file = cli.openStoreRead(io, root_dir) catch |e| {
        streams.err.print("zit ticket: cannot read the repository: {s}\n", .{diagnostics.reasonOf(e)}) catch {};
        return .failure;
    };
    defer file.close(io);
    const st = file.stat(io) catch {
        streams.err.writeAll("zit ticket: cannot read the repository\n") catch {};
        return .failure;
    };
    var fs = storage.FileStorage.init(io, file, st.size);
    var log = logstore.LogStore.openReadOnly(gpa, fs.storageFile()) catch |e| switch (e) {
        error.OutOfMemory => return stateOom(streams, "ticket"),
        else => {
            streams.err.writeAll("zit ticket: cannot read the repository\n") catch {};
            return .failure;
        },
    };
    defer log.deinit(gpa);

    var changes: std.ArrayList(Change) = .empty;
    const count: u64 = log.entryCount();
    var rid: u64 = 1;
    while (rid <= count) : (rid += 1) {
        const bytes = (log.content(gpa, rid) catch |e| switch (e) {
            error.OutOfMemory => return stateOom(streams, "ticket"),
            // A damaged or phantom entry cannot be a ticket; verify owns
            // damage reports.
            else => continue,
        }) orelse continue;
        defer gpa.free(bytes);
        const ch = (changeOf(gpa, arena, rid, bytes) catch return stateOom(streams, "ticket")) orelse continue;
        if (opt.id) |prefix| {
            if (!std.mem.startsWith(u8, ch.id, prefix)) continue;
        }
        changes.append(arena, ch) catch return stateOom(streams, "ticket");
    }

    // Group the changes by ticket id.
    var tickets: std.ArrayList(Ticket) = .empty;
    std.mem.sort(Change, changes.items, {}, struct {
        fn lt(_: void, a: Change, b: Change) bool {
            return switch (std.mem.order(u8, a.id, b.id)) {
                .lt => true,
                .gt => false,
                .eq => changeLess({}, a, b),
            };
        }
    }.lt);
    var start: usize = 0;
    while (start < changes.items.len) {
        var end = start + 1;
        while (end < changes.items.len and std.mem.eql(u8, changes.items[end].id, changes.items[start].id)) end += 1;
        const t = replay(arena, changes.items[start].id, changes.items[start..end]) catch return stateOom(streams, "ticket");
        tickets.append(arena, t) catch return stateOom(streams, "ticket");
        start = end;
    }

    if (!is_list) {
        const prefix = opt.id.?;
        if (tickets.items.len == 0) {
            streams.err.print("zit ticket: unknown ticket '{s}'\n", .{prefix}) catch {};
            return .failure;
        }
        if (tickets.items.len > 1) {
            streams.err.print("zit ticket: '{s}' is ambiguous; it matches:\n", .{prefix}) catch {};
            for (tickets.items[0..@min(tickets.items.len, max_candidates)]) |t| streams.err.print("  {s}\n", .{t.id}) catch {};
            if (tickets.items.len > max_candidates) streams.err.writeAll("  ...\n") catch {};
            return .failure;
        }
        const t = tickets.items[0];
        if (opt.json) return writeJsonDoc(gpa, arena, streams, &.{t}, true, false);
        printShow(arena, streams, t) catch return stateOom(streams, "ticket");
        return .ok;
    }

    // list: newest change first, then by id.
    var shown: std.ArrayList(Ticket) = .empty;
    for (tickets.items) |t| {
        if (opt.status) |want| {
            const have = t.get("status") orelse continue;
            if (!std.ascii.eqlIgnoreCase(have, want)) continue;
        }
        shown.append(arena, t) catch return stateOom(streams, "ticket");
    }
    std.mem.sort(Ticket, shown.items, {}, struct {
        fn lt(_: void, a: Ticket, b: Ticket) bool {
            return switch (std.mem.order(u8, a.changed, b.changed)) {
                .gt => true,
                .lt => false,
                .eq => std.mem.lessThan(u8, a.id, b.id),
            };
        }
    }.lt);
    if (opt.json) return writeJsonDoc(gpa, arena, streams, shown.items, false, true);

    var status_w: usize = 0;
    var type_w: usize = 0;
    for (shown.items) |t| {
        const status: []const u8 = t.get("status") orelse "-";
        status_w = @max(status_w, status.len);
        const kind: []const u8 = t.get("type") orelse "-";
        type_w = @max(type_w, kind.len);
    }
    for (shown.items) |t| {
        const status: []const u8 = t.get("status") orelse "-";
        const kind: []const u8 = t.get("type") orelse "-";
        const title = oneLine(arena, t.get("title") orelse "") catch return stateOom(streams, "ticket");
        streams.out.print("{s}  {s}", .{ t.id[0..short_id_len], status }) catch {};
        streams.out.splatByteAll(' ', status_w - status.len + 2) catch {};
        streams.out.writeAll(kind) catch {};
        streams.out.splatByteAll(' ', type_w - kind.len + 2) catch {};
        streams.out.print("{s}\n", .{title}) catch {};
    }
    return .ok;
}

/// One JSON document on one line: the single ticket, or an array of them.
fn writeJsonDoc(
    gpa: std.mem.Allocator,
    arena: std.mem.Allocator,
    streams: cli.Streams,
    tickets: []const Ticket,
    with_detail: bool,
    as_array: bool,
) cli.Exit {
    var aw: std.Io.Writer.Allocating = .init(gpa);
    defer aw.deinit();
    var jw: std.json.Stringify = .{ .writer = &aw.writer };
    // An Allocating writer fails only on OOM, so every error here is one.
    if (as_array) jw.beginArray() catch return stateOom(streams, "ticket");
    for (tickets) |t| writeTicketJson(&jw, arena, t, with_detail) catch return stateOom(streams, "ticket");
    if (as_array) jw.endArray() catch return stateOom(streams, "ticket");
    aw.writer.writeByte('\n') catch return stateOom(streams, "ticket");
    streams.out.writeAll(aw.written()) catch {};
    return .ok;
}