Skip to content
zit Artifact [86ff1b563c]
Login

Artifact [86ff1b563c]

Artifact 86ff1b563ca69bad16dc65335b667510ac498dc551f365773aa0f303e1d78c2a:


//! `zit timeline`: the one-line-per-check-in history listing.

const std = @import("std");
const zit = @import("zit");
const cli = @import("zit").cli;
const logstore = @import("zit").logstore;
const Repository = @import("zit").Repository;
const repostate = zit.repostate;
const artifact = zit.artifact;
const diagnostics = @import("../cli/diagnostics.zig");
const help_pages = @import("../cli/help.zig");
const stateOom = diagnostics.stateOom;
const repoReadFail = diagnostics.repoReadFail;
const openRepo = diagnostics.openRepo;
const timeline_help = help_pages.timeline_help;

// The PATH walk is the library core's, shared with the daemon's `log`.
const filelog = zit.filelog;
const LogWalkError = filelog.LogWalkError;
const LogPathFilter = filelog.LogPathFilter;
const PathProbe = filelog.PathProbe;
const pathStep = filelog.pathStep;

const checkin_display = @import("checkin_display.zig");
const firstCommentLine = checkin_display.firstCommentLine;
const sym_prefix = checkin_display.sym_prefix;
const timeline_hash_display = checkin_display.timeline_hash_display;

/// Whether the check-in `id` changes PATH per the B-log change definition: its
/// effective content (or presence) for PATH differs from its PRIMARY parent's
/// (§3.2 first-listed P-card parent). A root has no parent, so presence alone is
/// a change; a rename surfaces at both names as a presence flip. The literal
/// name only: `timeline -p` filters rows by it and follows nothing.
/// `manifest` is the already-parsed check-in the caller holds.
fn logChangesPath(
    gpa: std.mem.Allocator,
    repo: *Repository,
    probe: *PathProbe,
    id: []const u8,
    manifest: *const artifact.Manifest,
    path: []const u8,
) LogWalkError!bool {
    // §3.2: the primary parent is the first hash of the first P card.
    var primary: ?[]const u8 = null;
    for (manifest.p) |pc| {
        var hashes = pc.hashes();
        if (hashes.next()) |first| {
            primary = first;
            break;
        }
    }
    const filter: LogPathFilter = .{ .repo = repo, .path = path, .follow = false };
    const name = try probe.names.intern(gpa, path);
    const step = try pathStep(gpa, filter, probe, repo.lookup(id), if (primary) |p| repo.lookup(p) else null, name, false);
    return step.hit;
}

/// `zit timeline` — the global chronological history of every check-in
/// (repo-state §2/§8.3): one line per check-in, event.mtime descending, ties by
/// full artifact hash so the listing is byte-reproducible. Read-only: opens the
/// repository, enumerates through the single `checkinsByMtime` query, renders,
/// and mutates nothing. No positional, `-h`/`--help` only (the house
/// `parseNoPositionalArgs` grammar). (contracts/timeline.md B-timeline-1..13.)
pub fn runTimeline(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
) cli.Exit {
    const parsed = switch (cli.parseTimelineArgs(verb_args)) {
        .ok => |p| p,
        .unknown_option => |tok| return cli.usageError(streams, "timeline", .unknown_option, tok),
        .extra_argument => |tok| return cli.usageError(streams, "timeline", .extra_argument, tok),
        .bad_limit => |tok| return cli.usageError(streams, "timeline", .bad_limit, tok),
    };
    // --help wins over every effect (B-timeline-8).
    if (parsed.help) {
        streams.out.writeAll(timeline_help) catch {};
        return .ok;
    }

    // The image carries everything a row renders — adjacency for the §3.2
    // merge mark since layout 2, comment and login since layout 6 — so the
    // zero-parse path answers; a full derive replayed every record for one
    // row. Only `full`/`-v`/`-p` read manifests, through the facade.
    var repo: Repository = undefined;
    var root_dir: std.Io.Dir = undefined;
    const rc = openRepo(gpa, io, arena, streams, "timeline", amb.repo_override, false, true, &repo, &root_dir);
    if (rc != .ok) return rc;
    defer root_dir.close(io);
    defer repo.deinit(gpa);
    const exit = renderTimeline(gpa, &repo, streams, parsed);
    if (exit == .ok) cli.horizonHistoryNote(gpa, io, root_dir, streams, "timeline");
    return exit;
}

/// §3.2: a check-in that joins two or more lines of development — one carrying
/// at least one merge parent (a second-or-later P-card hash), i.e. more than one
/// distinct parent. The mainline (primary-only) check-in has exactly one.
fn timelineIsMerge(state: *const repostate.RepoState, rid: repostate.Rid) bool {
    return state.parentCount(rid) >= 2;
}

/// Renders the timeline to stdout: for each check-in in `checkinsByMtime` order,
/// one line `<mark><hash12>  <ISO>  <branch>  <first-comment-line>`. `<mark>` is
/// "M " for a merge check-in (§3.2) else "  ". Bounded by the enumeration size;
/// each row reads and frees exactly one manifest (no unbounded retention). An
/// empty repository prints nothing (B-timeline-7).
fn renderTimeline(gpa: std.mem.Allocator, repo: *Repository, streams: cli.Streams, a: cli.TimelineArgs) cli.Exit {
    // `-p PATH` runs the same predicate the log walk does, and paid
    // the same unmemoized reconstruction per row.
    var tl_plaintext: logstore.PlaintextCache = .{};
    defer tl_plaintext.deinit(gpa);
    var tl_probe = PathProbe.init(gpa, &tl_plaintext);
    defer tl_probe.deinit(gpa);
    const rids = repo.state().checkinsByMtime(gpa) catch return stateOom(streams, "timeline");
    defer gpa.free(rids);
    // `-c`: the checkout's branch, which needs a checkout.
    var current_branch_buf: []const u8 = "";
    if (a.current_branch) {
        const cur = repo.current_hint orelse {
            streams.err.writeAll("zit timeline: -c needs a checkout; name the branch with -b instead\n") catch {};
            return .failure;
        };
        current_branch_buf = repo.branchOf(cur);
    }
    const want_branch: ?[]const u8 = if (a.current_branch) current_branch_buf else a.branch;

    var last_day: [10]u8 = undefined;
    var have_day = false;
    var matched: usize = 0;
    var shown: usize = 0;
    var idx: usize = 0;
    if (a.format == .html) {
        // A static page — the same rows as -F medium, in a table.
        streams.out.writeAll("<!doctype html>\n<meta charset=\"utf-8\">\n<title>zit timeline</title>\n" ++
            "<style>body{font:14px/1.4 system-ui,sans-serif;margin:1.5em}table.timeline{border-collapse:collapse}" ++
            "table.timeline td{padding:.2em .6em;vertical-align:top;border-bottom:1px solid #ddd}" ++
            "td.h{font-family:ui-monospace,monospace}tr.current td{background:#fff6d6}</style>\n" ++
            "<table class=\"timeline\">\n<tr><th>check-in</th><th>when</th><th>branch</th><th>user</th><th>comment</th></tr>\n") catch {};
    }
    while (idx < rids.len) : (idx += 1) {
        const rid = if (a.reverse) rids[rids.len - 1 - idx] else rids[idx];
        if (a.limit) |n| if (n != 0 and shown >= n) break;
        const mtime = repo.state().mtimeOf(rid) orelse unreachable;
        const branch = repo.branchOf(rid); // §6.1, config main-branch fallback
        if (want_branch) |b| if (!std.mem.eql(u8, b, branch)) continue;

        // A manifest is read only for what the crosslinked state cannot
        // answer: the file lists `--verbose`, `full`, and a path filter need.
        // Comment and user come from the state — the image carries both since
        // So the default format reads no artifact at all. This
        // condition used to be `a.format != .oneline`, written when oneline
        // was the default; `medium` became the default and every row
        // began inflating a manifest for two strings the state already had.
        const need_manifest = a.path != null or a.verbose or a.format == .full;
        const state_comment = repo.state().commentOf(rid);
        const state_user = repo.state().userOf(rid);
        var maybe: ?Repository.OwnedManifest = null;
        defer if (maybe) |*m| m.deinit(gpa);
        if (need_manifest or state_comment == null or state_user == null) {
            maybe = repo.manifest(gpa, rid) catch |e| switch (e) {
                error.OutOfMemory => return stateOom(streams, "timeline"),
                error.NotARepo, error.CannotRead, error.Corrupt => return repoReadFail(streams, "timeline"),
                error.ImportPending => |oe| return diagnostics.repoOpenFail(streams, "timeline", oe),
            };
        }
        const user: []const u8 = if (state_user) |u|
            u
        else if (maybe) |m|
            (if (m.manifest.u) |u| u.login else "")
        else
            "";
        if (a.user) |u| if (!std.mem.eql(u8, u, user)) continue;
        if (a.path) |path| {
            const m = maybe orelse continue;
            const changes = logChangesPath(gpa, repo, &tl_probe, repo.hashOf(rid), &m.manifest, path) catch |e| switch (e) {
                error.OutOfMemory => return stateOom(streams, "timeline"),
                else => false,
            };
            if (!changes) continue;
        }
        matched += 1;
        if (a.offset) |off| if (matched <= off) continue;
        shown += 1;

        var iso_buf: [19]u8 = undefined;
        const iso = cli.formatWriterTimestamp(@intCast(mtime / 1000), &iso_buf);
        const mark = if (timelineIsMerge(repo.state(), rid)) "M " else "  ";
        const hash = repo.hashOf(rid);
        const short = hash[0..@min(hash.len, timeline_hash_display)];
        const manifest_comment: []const u8 = if (state_comment) |c|
            firstCommentLine(c)
        else if (maybe) |m|
            (if (m.manifest.c) |c| firstCommentLine(c.comment) else "")
        else
            "";
        const comment = repo.override(rid, .comment, manifest_comment);
        const is_current = if (repo.current_hint) |cur| cur == rid else false;

        switch (a.format) {
            .oneline => {
                if (a.weekday) {
                    const day = zit.repostate.weekdayName(zit.repostate.weekdayOf(mtime));
                    streams.out.print("{s}{s}  {s} {s}  {s}  {s}\n", .{ mark, short, day, iso, branch, comment }) catch {};
                } else {
                    streams.out.print("{s}{s}  {s}  {s}  {s}\n", .{ mark, short, iso, branch, comment }) catch {};
                }
            },
            .html => {
                var row: std.ArrayList(u8) = .empty;
                defer row.deinit(gpa);
                row.print(gpa, "<tr{s}><td class=\"h\">{s}</td><td>{s}</td><td>", .{ if (is_current) " class=\"current\"" else "", hash[0..@min(hash.len, 10)], iso }) catch return stateOom(streams, "timeline");
                zit.textdiff.htmlEscape(gpa, &row, branch) catch return stateOom(streams, "timeline");
                row.appendSlice(gpa, "</td><td>") catch return stateOom(streams, "timeline");
                zit.textdiff.htmlEscape(gpa, &row, user) catch return stateOom(streams, "timeline");
                row.appendSlice(gpa, "</td><td>") catch return stateOom(streams, "timeline");
                if (mark[0] == 'M') row.appendSlice(gpa, "<b>merge</b> ") catch return stateOom(streams, "timeline");
                zit.textdiff.htmlEscape(gpa, &row, comment) catch return stateOom(streams, "timeline");
                row.appendSlice(gpa, "</td></tr>\n") catch return stateOom(streams, "timeline");
                streams.out.writeAll(row.items) catch {};
            },
            .medium, .full => {
                // Fossil's shape: a date header once per day, then
                // `hh:mm:ss [hash] *CURRENT* comment (user: u tags: ...)`.
                const day = iso[0..10];
                if (!have_day or !std.mem.eql(u8, &last_day, day)) {
                    @memcpy(&last_day, day);
                    have_day = true;
                    streams.out.print("=== {s} {s} ===\n", .{ zit.repostate.weekdayName(zit.repostate.weekdayOf(mtime)), day }) catch {}; // weekday
                }
                streams.out.print("{s} [{s}] {s}{s}{s} (user: {s} tags: {s}", .{ iso[11..19], cli.shortHash(hash), if (is_current) "*CURRENT* " else "", if (mark[0] == 'M') "*MERGE* " else "", comment, user, branch }) catch {};
                const tags = repo.state().tagsOf(gpa, rid) catch return stateOom(streams, "timeline");
                defer gpa.free(tags);
                for (tags) |t| {
                    if (t.tagtype != .singleton or !std.mem.startsWith(u8, t.name, sym_prefix)) continue;
                    streams.out.print(", {s}", .{t.name[sym_prefix.len..]}) catch {};
                }
                streams.out.writeAll(")\n") catch {};
            },
        }
        if (a.format == .full or a.verbose) {
            if (maybe) |m| timelineFiles(gpa, repo, rid, &m.manifest, streams) catch return stateOom(streams, "timeline");
        }
    }
    if (a.format == .html) streams.out.writeAll("</table>\n") catch {};
    return .ok;
}

/// The files a check-in changes against its primary parent, one
/// indented line each in Fossil's words.
fn timelineFiles(gpa: std.mem.Allocator, repo: *Repository, rid: repostate.Rid, manifest: *const artifact.Manifest, streams: cli.Streams) error{OutOfMemory}!void {
    var primary: ?repostate.Rid = null;
    for (manifest.p) |pc| {
        var hashes = pc.hashes();
        if (hashes.next()) |first| {
            primary = repo.lookup(first);
            break;
        }
    }
    // Read in proportion to what the check-in changed; the two whole lists
    // below answer when that read does not settle it.
    if (primary) |p| if (try repo.changesBetween(gpa, p, rid)) |found| {
        var changes = found;
        defer changes.deinit();
        for (changes.rows) |row| switch (row.state) {
            .added => streams.out.print("   ADDED {s}\n", .{row.name}) catch {},
            .removed => streams.out.print("   DELETED {s}\n", .{row.name}) catch {},
            // A mode change alone is not an edit here.
            .modified => if (!std.mem.eql(u8, row.parent.?, row.to_card.?.hash.?)) {
                streams.out.print("   EDITED {s}\n", .{row.name}) catch {};
            },
        };
        return;
    };
    var here = (repo.files(gpa, rid) catch return) orelse return;
    defer here.deinit(gpa);
    var parent_list: ?Repository.FileList = if (primary) |p| (repo.files(gpa, p) catch null) else null;
    defer if (parent_list) |*pl| pl.deinit(gpa);
    var hit = here.iterator();
    var pit_opt: ?Repository.EffectiveFiles = if (parent_list) |*pl| pl.iterator() else null;
    var pcur: ?artifact.FCard = if (pit_opt) |*pit| pit.next() else null;
    var hcur: ?artifact.FCard = hit.next();
    while (hcur != null or pcur != null) {
        if (pcur == null or (hcur != null and std.mem.order(u8, hcur.?.filename, pcur.?.filename) == .lt)) {
            streams.out.print("   ADDED {s}\n", .{hcur.?.filename}) catch {};
            hcur = hit.next();
        } else if (hcur == null or std.mem.order(u8, hcur.?.filename, pcur.?.filename) == .gt) {
            streams.out.print("   DELETED {s}\n", .{pcur.?.filename}) catch {};
            pcur = pit_opt.?.next();
        } else {
            if (!std.mem.eql(u8, hcur.?.hash orelse "", pcur.?.hash orelse "")) {
                streams.out.print("   EDITED {s}\n", .{hcur.?.filename}) catch {};
            }
            hcur = hit.next();
            pcur = pit_opt.?.next();
        }
    }
}