Skip to content
zit Artifact [0bbe8a4e13]
Login

Artifact [0bbe8a4e13]

Artifact 0bbe8a4e13aa0a2c7763cd431fbc45bad9e569ac6f568b93691489dc4a2665fb:


//! Which of a Git source's refs an import takes, and the account of that
//! choice the import prints.
//!
//! Local branches and tags are the repository's own history; a
//! remote-tracking ref is a copy of someone else's, kept for fetching, and
//! can reach history no branch here does (an archived remote's binaries, a
//! stale side branch whose newer commits then outrank the main line). So by
//! default only `refs/heads/*` and `refs/tags/*` are taken, and every other
//! namespace comes in with `--all-refs`. A destination that already records a
//! ref keeps taking it: dropping it would cancel its name and orphan the
//! check-ins only it reached.

const std = @import("std");

/// The option that takes every namespace, as imports did before.
pub const all_refs_option = "--all-refs";

/// Names shown per namespace in the text account; the rest are counted.
pub const shown_per_namespace = 5;

pub const Verdict = enum {
    /// A local branch or tag, or any ref under `--all-refs`.
    take,
    /// Outside the default namespaces, taken because the destination's map
    /// already records it.
    recorded,
    /// A pull request head: kept in the capture only to pair a squash merge
    /// with the head it took, never published as a ref.
    internal,
    skip,
};

pub fn judge(name: []const u8, all_refs: bool, recorded: *const std.StringHashMapUnmanaged(void)) Verdict {
    if (std.mem.startsWith(u8, name, "refs/pull/")) return .internal;
    if (std.mem.startsWith(u8, name, "refs/heads/") or std.mem.startsWith(u8, name, "refs/tags/")) return .take;
    if (all_refs) return .take;
    if (recorded.contains(name)) return .recorded;
    return .skip;
}

/// `refs/heads/x/y` is in `refs/heads`; a ref with no namespace of its own
/// (`refs/stash`, `HEAD`) is its own.
pub fn namespaceOf(name: []const u8) []const u8 {
    const prefix = "refs/";
    if (!std.mem.startsWith(u8, name, prefix)) return name;
    const slash = std.mem.indexOfScalar(u8, name[prefix.len..], '/') orelse return name;
    return name[0 .. prefix.len + slash];
}

/// One namespace of the account, every name in full, sorted.
pub const Group = struct {
    namespace: []const u8,
    count: usize,
    names: []const []const u8,
};

/// A skipped namespace carries the option that would take it.
pub const SkippedGroup = struct {
    namespace: []const u8,
    count: usize,
    names: []const []const u8,
    option: []const u8 = all_refs_option,
};

/// The account in the shape `-F json` prints it.
pub const Report = struct {
    taken: []const Group,
    recorded: []const Group,
    skipped: []const SkippedGroup,
};

/// The refs a capture took and left, by verdict. `internal` refs are in
/// neither list: they are a means, not a ref the import publishes.
pub const Selection = struct {
    arena: std.heap.ArenaAllocator,
    taken: std.ArrayList([]const u8) = .empty,
    recorded: std.ArrayList([]const u8) = .empty,
    skipped: std.ArrayList([]const u8) = .empty,

    pub fn init(gpa: std.mem.Allocator) Selection {
        return .{ .arena = std.heap.ArenaAllocator.init(gpa) };
    }

    pub fn deinit(self: *Selection) void {
        self.arena.deinit();
        self.* = undefined;
    }

    /// Record `name` under its verdict; the name is copied.
    pub fn note(self: *Selection, name: []const u8, verdict: Verdict) !void {
        const list = switch (verdict) {
            .take => &self.taken,
            .recorded => &self.recorded,
            .skip => &self.skipped,
            .internal => return,
        };
        const a = self.arena.allocator();
        try list.append(a, try a.dupe(u8, name));
    }

    /// The account, allocated from `arena`, which the caller owns.
    pub fn report(self: *const Selection, arena: std.mem.Allocator) !Report {
        const skipped = try group(arena, self.skipped.items);
        const with_option = try arena.alloc(SkippedGroup, skipped.len);
        for (skipped, with_option) |g, *s| s.* = .{ .namespace = g.namespace, .count = g.count, .names = g.names };
        return .{
            .taken = try group(arena, self.taken.items),
            .recorded = try group(arena, self.recorded.items),
            .skipped = with_option,
        };
    }
};

fn lessThan(_: void, a: []const u8, b: []const u8) bool {
    return std.mem.lessThan(u8, a, b);
}

/// `names` grouped by namespace, namespaces and names sorted. The groups
/// and the name lists are allocated from `arena`; the names are copied.
fn group(arena: std.mem.Allocator, names: []const []const u8) ![]const Group {
    const sorted = try arena.alloc([]const u8, names.len);
    for (names, sorted) |n, *s| s.* = try arena.dupe(u8, n);
    // Sorted by full name, a namespace's refs are contiguous only when no
    // other namespace sorts between them, so sort by namespace first.
    std.mem.sort([]const u8, sorted, {}, struct {
        fn less(_: void, a: []const u8, b: []const u8) bool {
            const na = namespaceOf(a);
            const nb = namespaceOf(b);
            if (!std.mem.eql(u8, na, nb)) return std.mem.lessThan(u8, na, nb);
            return std.mem.lessThan(u8, a, b);
        }
    }.less);
    var groups: std.ArrayList(Group) = .empty;
    var start: usize = 0;
    while (start < sorted.len) {
        const ns = namespaceOf(sorted[start]);
        var end = start + 1;
        while (end < sorted.len and std.mem.eql(u8, namespaceOf(sorted[end]), ns)) end += 1;
        try groups.append(arena, .{ .namespace = ns, .count = end - start, .names = sorted[start..end] });
        start = end;
    }
    return groups.toOwnedSlice(arena);
}

fn total(groups: anytype) usize {
    var n: usize = 0;
    for (groups) |g| n += g.count;
    return n;
}

fn plural(n: usize) []const u8 {
    return if (n == 1) "" else "s";
}

/// `refs/heads 2 (main, topic)`: the namespace, its count, and its first
/// names without the namespace, the rest counted.
fn writeGroups(out: *std.Io.Writer, groups: anytype) !void {
    for (groups, 0..) |g, i| {
        if (i != 0) try out.writeAll(", ");
        try out.print("{s} {d}", .{ g.namespace, g.count });
        const short = g.names[0].len > g.namespace.len;
        if (!short) continue;
        try out.writeAll(" (");
        const shown = @min(g.names.len, shown_per_namespace);
        for (g.names[0..shown], 0..) |name, k| {
            if (k != 0) try out.writeAll(", ");
            try out.writeAll(name[g.namespace.len + 1 ..]);
        }
        if (g.names.len > shown) try out.print(" and {d} more", .{g.names.len - shown});
        try out.writeAll(")");
    }
}

/// The text account, one line per kind present; nothing for an empty kind.
pub fn writeText(out: *std.Io.Writer, r: Report, destination: []const u8) !void {
    const taken = total(r.taken);
    try out.print("import-git: took {d} ref{s}", .{ taken, plural(taken) });
    if (taken != 0) {
        try out.writeAll(": ");
        try writeGroups(out, r.taken);
    }
    try out.writeAll("\n");
    const recorded = total(r.recorded);
    if (recorded != 0) {
        try out.print("import-git: kept {d} ref{s} outside refs/heads and refs/tags because '{s}' already records {s}: ", .{ recorded, plural(recorded), destination, if (recorded == 1) "it" else "them" });
        try writeGroups(out, r.recorded);
        try out.writeAll("\n");
    }
    const skipped = total(r.skipped);
    if (skipped != 0) {
        try out.print("import-git: skipped {d} ref{s}: ", .{ skipped, plural(skipped) });
        try writeGroups(out, r.skipped);
        try out.print("; {s} takes {s}\n", .{ all_refs_option, if (skipped == 1) "it" else "them" });
    }
}

test "judge: branches and tags by default, the rest with --all-refs or a record; pull heads stay internal" {
    var none: std.StringHashMapUnmanaged(void) = .empty;
    try std.testing.expectEqual(Verdict.take, judge("refs/heads/main", false, &none));
    try std.testing.expectEqual(Verdict.take, judge("refs/tags/v1", false, &none));
    try std.testing.expectEqual(Verdict.skip, judge("refs/remotes/origin/main", false, &none));
    try std.testing.expectEqual(Verdict.skip, judge("refs/notes/commits", false, &none));
    try std.testing.expectEqual(Verdict.skip, judge("refs/stash", false, &none));
    try std.testing.expectEqual(Verdict.internal, judge("refs/pull/7/head", false, &none));
    try std.testing.expectEqual(Verdict.take, judge("refs/remotes/origin/main", true, &none));
    try std.testing.expectEqual(Verdict.take, judge("refs/stash", true, &none));
    try std.testing.expectEqual(Verdict.internal, judge("refs/pull/7/head", true, &none));
    // `refs/headsx` is not a branch.
    try std.testing.expectEqual(Verdict.skip, judge("refs/headsx/a", false, &none));

    var recorded: std.StringHashMapUnmanaged(void) = .empty;
    defer recorded.deinit(std.testing.allocator);
    try recorded.put(std.testing.allocator, "refs/remotes/origin/old", {});
    try std.testing.expectEqual(Verdict.recorded, judge("refs/remotes/origin/old", false, &recorded));
    try std.testing.expectEqual(Verdict.skip, judge("refs/remotes/origin/new", false, &recorded));
    try std.testing.expectEqual(Verdict.take, judge("refs/remotes/origin/old", true, &recorded));
}

test "namespaceOf: the first two components, or the whole name" {
    try std.testing.expectEqualStrings("refs/heads", namespaceOf("refs/heads/a/b"));
    try std.testing.expectEqualStrings("refs/remotes", namespaceOf("refs/remotes/origin/main"));
    try std.testing.expectEqualStrings("refs/stash", namespaceOf("refs/stash"));
    try std.testing.expectEqualStrings("HEAD", namespaceOf("HEAD"));
}

test "writeText: counts per namespace, the first names, and the option for what was skipped" {
    const gpa = std.testing.allocator;
    var sel = Selection.init(gpa);
    defer sel.deinit();
    var none: std.StringHashMapUnmanaged(void) = .empty;
    for ([_][]const u8{ "refs/tags/v2", "refs/heads/main", "refs/remotes/origin/main", "refs/heads/feature", "refs/tags/v1", "refs/pull/3/head", "refs/stash", "refs/remotes/archive/bin" }) |name| {
        try sel.note(name, judge(name, false, &none));
    }
    var arena = std.heap.ArenaAllocator.init(gpa);
    defer arena.deinit();
    const r = try sel.report(arena.allocator());
    var buf: std.Io.Writer.Allocating = .init(gpa);
    defer buf.deinit();
    try writeText(&buf.writer, r, "dest.zit");
    try std.testing.expectEqualStrings(
        "import-git: took 4 refs: refs/heads 2 (feature, main), refs/tags 2 (v1, v2)\n" ++
            "import-git: skipped 3 refs: refs/remotes 2 (archive/bin, origin/main), refs/stash 1; --all-refs takes them\n",
        buf.written(),
    );
}

test "writeText: thousands of tags read as a count and the first few" {
    const gpa = std.testing.allocator;
    var sel = Selection.init(gpa);
    defer sel.deinit();
    try sel.note("refs/heads/main", .take);
    var name_buf: [32]u8 = undefined;
    for (0..2500) |i| try sel.note(try std.fmt.bufPrint(&name_buf, "refs/tags/t{d:0>4}", .{i}), .take);
    try sel.note("refs/remotes/origin/old", .recorded);
    var arena = std.heap.ArenaAllocator.init(gpa);
    defer arena.deinit();
    const r = try sel.report(arena.allocator());
    var buf: std.Io.Writer.Allocating = .init(gpa);
    defer buf.deinit();
    try writeText(&buf.writer, r, "d");
    try std.testing.expectEqualStrings(
        "import-git: took 2501 refs: refs/heads 1 (main), refs/tags 2500 (t0000, t0001, t0002, t0003, t0004 and 2495 more)\n" ++
            "import-git: kept 1 ref outside refs/heads and refs/tags because 'd' already records it: refs/remotes 1 (origin/old)\n",
        buf.written(),
    );
    try std.testing.expectEqual(@as(usize, 2500), r.taken[1].names.len);
}

test "report: -F json carries every name, by namespace, and the option on what was skipped" {
    const gpa = std.testing.allocator;
    var sel = Selection.init(gpa);
    defer sel.deinit();
    try sel.note("refs/heads/main", .take);
    try sel.note("refs/remotes/origin/main", .skip);
    var arena = std.heap.ArenaAllocator.init(gpa);
    defer arena.deinit();
    const r = try sel.report(arena.allocator());
    var buf: std.Io.Writer.Allocating = .init(gpa);
    defer buf.deinit();
    try std.json.Stringify.value(r, .{}, &buf.writer);
    try std.testing.expectEqualStrings(
        "{\"taken\":[{\"namespace\":\"refs/heads\",\"count\":1,\"names\":[\"refs/heads/main\"]}]," ++
            "\"recorded\":[]," ++
            "\"skipped\":[{\"namespace\":\"refs/remotes\",\"count\":1,\"names\":[\"refs/remotes/origin/main\"],\"option\":\"--all-refs\"}]}",
        buf.written(),
    );
}