// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! `zfj pr ...`: opening a pull request, and reading them -- one with its //! thread, a list of them, and the diff one proposes. //! //! Flags are spelled as `fj pr`'s are. Commenting on, labelling and closing //! a pull request are the `issue` commands, which take a pull request's //! number: Forgejo numbers the two from one sequence. //! //! A pull request's state is shown as `merged` when it was, although //! Forgejo's own `state` says `closed` for both a merged one and one closed //! unmerged. const std = @import("std"); const Io = std.Io; const zfj = @import("zfj"); const args = @import("args.zig"); const call = @import("call.zig"); const Context = @import("Context.zig"); const git = @import("git.zig"); const text = @import("text.zig"); const Exit = Context.Exit; const porcelain = @import("porcelain.zig"); const Runner = porcelain.Runner; const place = porcelain.place; const collect = porcelain.collect; const writeJson = porcelain.writeJson; const Style = porcelain.Style; const repo_note = porcelain.repo_note; const json_note = porcelain.json_note; const oneLine = porcelain.oneLine; const splitCommas = porcelain.splitCommas; const writeLabels = porcelain.writeLabels; const login = porcelain.login; const day = porcelain.day; pub const commands = [_]porcelain.Command{ Runner("pr", Create).command("create", "open a pull request from a pushed branch"), Runner("pr", View).command("view", "show a pull request, and with --comments its thread"), Runner("pr", List).command("list", "list a repository's pull requests"), Runner("pr", Diff).command("diff", "show the diff a pull request proposes"), }; pub fn main(ctx: *Context, words: []const []const u8) !Exit { return porcelain.dispatch(ctx, "pr", &commands, words); } const Create = struct { repo: ?[]const u8 = null, title: []const u8, body: ?[]const u8 = null, @"body-file": ?[]const u8 = null, base: ?[]const u8 = null, head: ?[]const u8 = null, label: ?[]const []const u8 = null, assignee: ?[]const []const u8 = null, json: bool = false, pub const short = .{ .R = "repo", .t = "title", .b = "body", .F = "body-file", .B = "base", .H = "head", .l = "label", .a = "assignee" }; pub const usage = "create -t [-b <text> | -F <file>] [-B <branch>] [-H <branch>] [-l <label>]... [-a <user>]..."; pub const about = "Opens a pull request from a branch already pushed. Without -b or -F, and on a terminal, $EDITOR is opened for the description."; pub const notes = [_]args.Note{ repo_note, .{ .description = "the pull request's title" }, .{ .description = "the description, or - to read it from stdin" }, .{ .description = "read the description from a file, or - for stdin", .complete = .files }, .{ .description = "the branch to merge into (default: the repository's default branch)" }, .{ .description = "the branch to merge from, as <branch> or a fork's <owner>:<branch> (default: the branch checked out, as <owner>:<branch> when the origin remote is a fork)" }, .{ .description = "a label to give it, by name; commas separate several" }, .{ .description = "a user to assign it to; commas separate several" }, json_note, }; pub fn run(ctx: *Context, o: Create) !Exit { const at = place(ctx, o.repo) catch |e| return Context.exitFor(e); const head = o.head orelse try defaultHead(ctx, at) orelse return ctx.usage("no branch is checked out to open a pull request from; name one with -H", .{}); const body = text.body(ctx, .{ .body = o.body, .body_file = o.@"body-file" }, .optional, "pull request description") catch |e| switch (e) { error.OutOfMemory => return e, else => |f| return Context.exitFor(f), }; const names = try splitCommas(ctx, o.label); const labels = if (names.len == 0) null else switch (try labelIds(ctx, at, names)) { .ok => |ids| ids, .failed => |exit| return exit, }; const assignees = try splitCommas(ctx, o.assignee); // Forgejo wants a base, and has no default for one of its own. var repository: ?zfj.Owned(zfj.Repository) = null; defer if (repository) |*r| r.deinit(); const base = o.base orelse base: { repository = switch (call.result(ctx, "repoGet", zfj.repoGetResult(at.client, .{ .owner = at.owner, .repo = at.repo }))) { .ok => |ok| ok, .failed => |exit| return exit, }; break :base repository.?.value().default_branch orelse return ctx.environment("Forgejo gave no default branch for {s}/{s}; name one with -B", .{ at.owner, at.repo }); }; var created = switch (call.result(ctx, "repoCreatePullRequest", zfj.repoCreatePullRequestResult(at.client, .{ .owner = at.owner, .repo = at.repo }, .{ .title = o.title, .body = body, .head = head, .base = base, .labels = labels, .assignees = if (assignees.len == 0) null else assignees, }))) { .ok => |ok| ok, .failed => |exit| return exit, }; defer created.deinit(); if (o.json) return writeJson(ctx, created.body); try ctx.stdout.print("{s}\n", .{created.value().html_url orelse ""}); return .ok; } }; /// The branch checked out, as `<owner>:<branch>` when the clone's origin is /// a fork of the repository on the same instance -- where a branch pushed /// to origin is -- or null when no branch is checked out. fn defaultHead(ctx: *Context, at: porcelain.Place) !?[]const u8 { const name = git.currentBranch(ctx.arena, ctx.io) orelse return null; const origin = git.remoteLocation(ctx.arena, ctx.io, "origin") orelse return name; const t = ctx.target() catch return name; const host = git.urlHost(t.url) orelse return name; if (!std.ascii.eqlIgnoreCase(host, origin.host)) return name; if (std.mem.eql(u8, origin.owner, at.owner)) return name; return try std.fmt.allocPrint(ctx.arena, "{s}:{s}", .{ origin.owner, name }); } const View = struct { number: i64, repo: ?[]const u8 = null, comments: bool = false, json: bool = false, web: bool = false, pub const short = .{ .R = "repo", .w = "web" }; pub const positional: []const []const u8 = &.{"number"}; pub const usage = "view <number> [--comments] [--json | --web]"; pub const about = "Shows a pull request: its branches, its size, whether it can be merged, and its description; with --comments, its conversation too."; pub const notes = [_]args.Note{ .{ .description = "the pull request's number" }, repo_note, .{ .description = "show the conversation too" }, .{ .description = "write Forgejo's JSON for the pull request, with its conversation as a \"comments\" list when --comments is given" }, .{ .description = "open the pull request in the browser instead: $BROWSER, else the system's" }, }; pub fn run(ctx: *Context, o: View) !Exit { if (o.web and (o.json or o.comments)) return ctx.usage("--web opens the pull request in the browser, and takes neither --json nor --comments", .{}); const at = place(ctx, o.repo) catch |e| return Context.exitFor(e); var pull = switch (call.result(ctx, "repoGetPullRequest", zfj.repoGetPullRequestResult(at.client, .{ .owner = at.owner, .repo = at.repo, .index = o.number }))) { .ok => |ok| ok, .failed => |exit| return exit, }; defer pull.deinit(); if (o.web) { const url = pull.value().html_url orelse return ctx.environment("Forgejo gave no web address for #{d}", .{o.number}); return porcelain.openInBrowser(ctx, url); } // The conversation on a pull request is its issue's comments; what // is said on lines of the diff belongs to reviews, which this does // not show. var comments: ?zfj.Owned([]const zfj.Comment) = null; defer if (comments) |*c| c.deinit(); if (o.comments) { comments = switch (call.result(ctx, "issueGetComments", zfj.issueGetCommentsResult(at.client, .{ .owner = at.owner, .repo = at.repo, .index = o.number }))) { .ok => |ok| ok, .failed => |exit| return exit, }; } if (o.json) return porcelain.writeJsonWithComments(ctx, pull.body, if (comments) |c| c.body else null); var out: Io.Writer.Allocating = .init(ctx.arena); const style = Style.of(ctx); try renderPull(&out.writer, style, pull.value().*); if (comments) |*c| try porcelain.renderComments(&out.writer, style, c.value().*); try ctx.page(out.written()); return .ok; } }; const List = struct { repo: ?[]const u8 = null, state: []const u8 = "open", label: ?[]const []const u8 = null, author: ?[]const u8 = null, base: ?[]const u8 = null, head: ?[]const u8 = null, limit: i64 = 30, page: ?i64 = null, json: bool = false, pub const short = .{ .R = "repo", .s = "state", .l = "label", .A = "author", .B = "base", .H = "head", .L = "limit" }; pub const usage = "list [--state open|closed|all] [-l <label>]... [-A <user>] [-B <branch>] [-H <branch>] [--json]"; pub const about = "Lists a repository's pull requests, newest first. The global --paginate fetches every page."; pub const notes = [_]args.Note{ repo_note, .{ .description = "which pull requests: open, closed (merged or not) or all", .allowed = &.{ "open", "closed", "all" } }, .{ .description = "only pull requests with this label; given more than once, those with any of them" }, .{ .description = "only pull requests this user opened" }, .{ .description = "only pull requests into this branch" }, .{ .description = "only pull requests from this branch" }, .{ .description = "how many to a page (the instance may give fewer)" }, .{ .description = "which page" }, json_note, }; pub fn run(ctx: *Context, o: List) !Exit { const at = place(ctx, o.repo) catch |e| return Context.exitFor(e); const names = try splitCommas(ctx, o.label); var params: zfj.RepoListPullRequestsParams = .{ .owner = at.owner, .repo = at.repo, .state = o.state, .labels = if (names.len == 0) null else switch (try labelIds(ctx, at, names)) { .ok => |ids| ids, .failed => |exit| return exit, }, .poster = o.author, .base = o.base, .head = o.head, .limit = o.limit, .page = o.page, }; const joined = switch (try collect(ctx, "repoListPullRequests", zfj.repoListPullRequestsRaw, at.client, ¶ms)) { .ok => |ok| ok, .failed => |exit| return exit, }; if (o.json) return writeJson(ctx, joined); return writePullList(ctx, joined); } }; const Diff = struct { number: i64, repo: ?[]const u8 = null, patch: bool = false, pub const short = .{ .R = "repo" }; pub const positional: []const []const u8 = &.{"number"}; pub const usage = "diff <number> [--patch]"; pub const about = "Writes the unified diff a pull request proposes, or with --patch its commits as a patch series for `git am`."; pub const notes = [_]args.Note{ .{ .description = "the pull request's number" }, repo_note, .{ .description = "write the commits in `git format-patch` form rather than one diff" }, }; pub fn run(ctx: *Context, o: Diff) !Exit { const at = place(ctx, o.repo) catch |e| return Context.exitFor(e); var response = zfj.repoDownloadPullDiffOrPatchRaw(at.client, .{ .owner = at.owner, .repo = at.repo, .index = o.number, .diffType = if (o.patch) "patch" else "diff", }) catch |err| return ctx.transport("repoDownloadPullDiffOrPatch", err); defer response.deinit(); if (response.status.class() != .success) return ctx.apiError("repoDownloadPullDiffOrPatch", response.status, response.body); try ctx.page(response.body); return .ok; } }; /// The ids of labels named by the user, which is how Forgejo's list of pull /// requests wants them: an unknown name is a usage error rather than a /// filter that silently matches nothing. fn labelIds(ctx: *Context, at: porcelain.Place, names: []const []const u8) !porcelain.Got([]const i64) { var params: zfj.IssueListLabelsParams = .{ .owner = at.owner, .repo = at.repo }; const joined = switch (try porcelain.collectAll(ctx, "issueListLabels", zfj.issueListLabelsRaw, at.client, ¶ms)) { .ok => |ok| ok, .failed => |exit| return .{ .failed = exit }, }; const parsed = std.json.parseFromSlice([]const zfj.Label, ctx.gpa, joined, .{ .ignore_unknown_fields = true }) catch |err| { _ = ctx.parseFailure("the list", "a list of Label", @errorName(err)); return .{ .failed = .response_mismatch }; }; defer parsed.deinit(); const ids = try ctx.arena.alloc(i64, names.len); for (names, ids) |name, *id| { id.* = for (parsed.value) |label| { if (std.mem.eql(u8, label.name orelse continue, name)) break label.id orelse continue; } else return .{ .failed = ctx.usage("{s} has no label '{s}'; `zfj label list` lists them", .{ at.repo, name }) }; } return .{ .ok = ids }; } /// `merged` for a pull request that was, which Forgejo calls `closed`. fn stateOf(pull: zfj.PullRequest) []const u8 { if (pull.merged orelse false) return "merged"; return pull.state orelse ""; } fn branch(info: ?zfj.PRBranchInfo) []const u8 { const b = info orelse return "?"; return b.label orelse b.ref orelse "?"; } fn renderPull(writer: *Io.Writer, style: Style, pull: zfj.PullRequest) !void { const state = stateOf(pull); try writer.print("{s}{s}{s} #{d}\n", .{ style.bold, pull.title orelse "", style.reset, pull.number orelse 0 }); try writer.print("{s}{s}{s}{s} · {s} · {s} → {s}\n", .{ style.stateColor(state), state, if (pull.draft orelse false) " (draft)" else "", style.reset, login(pull.user), branch(pull.head), branch(pull.base), }); try writer.print("Opened {s}", .{day(pull.created_at)}); if (pull.merged orelse false) { try writer.print(" · merged {s} by {s}", .{ day(pull.merged_at), login(pull.merged_by) }); } else if (pull.closed_at) |closed| { try writer.print(" · closed {s}", .{day(closed)}); } if (pull.comments) |count| try writer.print(" · {d} comment{s}", .{ count, if (count == 1) "" else "s" }); try writer.writeByte('\n'); if (pull.changed_files) |files| { try writer.print("{d} file{s} changed, {s}+{d}{s} {s}-{d}{s}", .{ files, if (files == 1) "" else "s", style.green, pull.additions orelse 0, style.reset, style.red, pull.deletions orelse 0, style.reset, }); if (std.mem.eql(u8, state, "open")) try writer.writeAll(if (pull.mergeable orelse false) " · can be merged" else " · cannot be merged cleanly"); try writer.writeByte('\n'); } if (pull.labels) |labels| if (labels.len != 0) { try writer.writeAll("Labels: "); try writeLabels(writer, labels, ", "); try writer.writeByte('\n'); }; if (pull.assignees) |users| if (users.len != 0) { try writer.writeAll("Assignees: "); for (users, 0..) |user, i| try writer.print("{s}{s}", .{ if (i == 0) "" else ", ", user.login orelse "" }); try writer.writeByte('\n'); }; if (pull.requested_reviewers) |users| if (users.len != 0) { try writer.writeAll("Reviewers requested: "); for (users, 0..) |user, i| try writer.print("{s}{s}", .{ if (i == 0) "" else ", ", user.login orelse "" }); try writer.writeByte('\n'); }; if (pull.milestone) |milestone| try writer.print("Milestone: {s}\n", .{milestone.title orelse ""}); if (pull.html_url) |url| try writer.print("{s}{s}{s}\n", .{ style.dim, url, style.reset }); const body = std.mem.trim(u8, pull.body orelse "", " \t\r\n"); if (body.len != 0) try writer.print("\n{s}\n", .{body}); } /// A list of pull requests: columns on a terminal, and otherwise one to a /// line with its number, state, title, head and base branches, and labels /// separated by tabs. fn writePullList(ctx: *Context, json: []const u8) !Exit { const parsed = std.json.parseFromSlice([]const zfj.PullRequest, ctx.gpa, json, .{ .ignore_unknown_fields = true }) catch |err| { _ = ctx.parseFailure("the list", "a list of PullRequest", @errorName(err)); return .response_mismatch; }; defer parsed.deinit(); const pulls = parsed.value; var out: Io.Writer.Allocating = .init(ctx.arena); if (!ctx.stdoutIsTty()) { for (pulls) |pull| { try out.writer.print("{d}\t{s}\t{s}\t{s}\t{s}\t", .{ pull.number orelse 0, stateOf(pull), oneLine(pull.title orelse ""), branch(pull.head), branch(pull.base), }); try writeLabels(&out.writer, pull.labels, ","); try out.writer.writeByte('\n'); } try ctx.stdout.writeAll(out.written()); try ctx.stdout.flush(); return .ok; } if (pulls.len == 0) { try ctx.stdout.writeAll("No pull requests.\n"); try ctx.stdout.flush(); return .ok; } const style = Style.of(ctx); var number_width: usize = 0; for (pulls) |pull| number_width = @max(number_width, std.fmt.count("{d}", .{pull.number orelse 0})); for (pulls) |pull| { const number = pull.number orelse 0; try out.writer.splatByteAll(' ', number_width - std.fmt.count("{d}", .{number})); const state = stateOf(pull); try out.writer.print("{s}#{d}{s} {s}{s: <6}{s} {s} {s}{s} → {s}{s}", .{ style.bold, number, style.reset, style.stateColor(state), state, style.reset, oneLine(pull.title orelse ""), style.dim, branch(pull.head), branch(pull.base), style.reset, }); if (pull.labels) |labels| if (labels.len != 0) { try out.writer.print(" {s}", .{style.dim}); try writeLabels(&out.writer, labels, ", "); try out.writer.writeAll(style.reset); }; try out.writer.writeByte('\n'); } try ctx.page(out.written()); return .ok; } const testing = std.testing; test "every command compiles" { // They are reached only through `commands`' function pointers, which a // test build would otherwise leave unanalyzed. for (commands) |command| _ = command.run; } test "every command's notes cover its options" { inline for (.{ Create, View, List, Diff }) |Options| { try testing.expectEqual(@typeInfo(Options).@"struct".field_names.len, Options.notes.len); } }