// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! `zfj repo ...`: repositories themselves, rather than what is in them. //! //! The repository is the thing each command acts on, so it is named as an //! argument rather than with `-R`: `/`, a bare `` for //! the authenticated user's, or nothing for the one the clone's remote //! names (docs/adr/0006-repo-commands-name-the-repository-positionally.md). const std = @import("std"); const Io = std.Io; const zfj = @import("zfj"); const args = @import("args.zig"); const call = @import("call.zig"); const Config = @import("Config.zig"); const Context = @import("Context.zig"); const git = @import("git.zig"); const Exit = Context.Exit; const porcelain = @import("porcelain.zig"); const Runner = porcelain.Runner; const Place = porcelain.Place; const writeJson = porcelain.writeJson; const Style = porcelain.Style; const json_note = porcelain.json_note; const oneLine = porcelain.oneLine; pub const commands = [_]porcelain.Command{ Runner("repo", View).command("view", "show a repository"), Runner("repo", List).command("list", "list your repositories, or an owner's"), Runner("repo", Clone).command("clone", "clone a repository, and a fork's parent as upstream"), Runner("repo", Create).command("create", "create a repository, yours or an organization's"), Runner("repo", Fork).command("fork", "fork a repository, or find the fork already made"), Runner("repo", Edit).command("edit", "change a repository's name, description, visibility or units"), Runner("repo", Delete).command("delete", "delete a repository, once its name is typed back"), }; pub fn main(ctx: *Context, words: []const []const u8) !Exit { return porcelain.dispatch(ctx, "repo", &commands, words); } const repository_note: args.Note = .{ .description = "/, or for one of your own; without it, the clone's upstream or origin remote" }; /// The repository `given` names, and the client to reach it with: see the /// top of this file. A bare name costs a request, to ask whose the token is. fn locate(ctx: *Context, given: ?[]const u8) !call.Got(Place) { return locateAs(ctx, given, .mine); } /// What a bare `` names: one of the authenticated user's own, or -- /// for a command that changes a repository -- nothing, so that the owner is /// never guessed at. const Bare = enum { mine, refused }; fn locateAs(ctx: *Context, given: ?[]const u8, bare: Bare) !call.Got(Place) { const text = given orelse { const named = ctx.remoteRepository(.argument) catch |e| return .{ .failed = Context.exitFor(e) }; const client = ctx.client() catch return .{ .failed = .environment }; return .{ .ok = .{ .client = client, .owner = named.owner, .repo = named.name } }; }; if (std.mem.findScalar(u8, text, '/') != null) { const named = Context.parseRepository(text) orelse return .{ .failed = ctx.usage("a repository is / or , not '{s}'", .{text}) }; const client = ctx.client() catch return .{ .failed = .environment }; return .{ .ok = .{ .client = client, .owner = named.owner, .repo = named.name } }; } if (text.len == 0) return .{ .failed = ctx.usage("a repository needs a name", .{}) }; if (bare == .refused) return .{ .failed = ctx.usage("name the repository as /{s}", .{text}) }; const client = ctx.client() catch return .{ .failed = .environment }; const owner = switch (try currentLogin(ctx, client)) { .ok => |ok| ok, .failed => |exit| return .{ .failed = exit }, }; return .{ .ok = .{ .client = client, .owner = owner, .repo = text } }; } /// The login of the user the token belongs to. fn currentLogin(ctx: *Context, client: *zfj.Client) !call.Got([]const u8) { var user = switch (call.result(ctx, "userGetCurrent", zfj.userGetCurrentResult(client))) { .ok => |ok| ok, .failed => |exit| return .{ .failed = exit }, }; defer user.deinit(); const login = user.value().login orelse return .{ .failed = ctx.environment("Forgejo did not say whose the token is; name the owner outright", .{}) }; return .{ .ok = try ctx.arena.dupe(u8, login) }; } const View = struct { repository: ?[]const u8 = null, json: bool = false, web: bool = false, pub const short = .{ .w = "web" }; pub const positional: []const []const u8 = &.{"repository"}; pub const usage = "view [/] [--json | --web]"; pub const about = "Shows a repository: what it is, where to clone it from, and how much is in it."; pub const notes = [_]args.Note{ repository_note, json_note, .{ .description = "open the repository in the browser instead: $BROWSER, else the system's" }, }; pub fn run(ctx: *Context, o: View) !Exit { if (o.web and o.json) return ctx.usage("--web opens the repository in the browser, and does not take --json", .{}); const at = switch (try locate(ctx, o.repository)) { .ok => |ok| ok, .failed => |exit| return exit, }; var repository = switch (call.result(ctx, "repoGet", zfj.repoGetResult(at.client, .{ .owner = at.owner, .repo = at.repo }))) { .ok => |ok| ok, .failed => |exit| return exit, }; defer repository.deinit(); if (o.json) return writeJson(ctx, repository.body); if (o.web) { const url = repository.value().html_url orelse return ctx.environment("Forgejo gave no web address for {s}/{s}", .{ at.owner, at.repo }); return porcelain.openInBrowser(ctx, url); } var out: Io.Writer.Allocating = .init(ctx.arena); try renderRepository(&out.writer, Style.of(ctx), repository.value().*); try ctx.page(out.written()); return .ok; } }; const List = struct { owner: ?[]const u8 = null, limit: i64 = 30, page: ?i64 = null, json: bool = false, pub const short = .{ .L = "limit" }; pub const positional: []const []const u8 = &.{"owner"}; pub const usage = "list [] [--json]"; pub const about = "Lists your repositories and those of the organizations you belong to, or with an owner, that user's or organization's. The global --paginate fetches every page."; pub const notes = [_]args.Note{ .{ .description = "the user or organization whose repositories to list" }, .{ .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 client = ctx.client() catch return .environment; // Forgejo answers for an organization here as for a user. const joined = switch (if (o.owner) |owner| blk: { var params: zfj.UserListReposParams = .{ .username = owner, .limit = o.limit, .page = o.page }; break :blk try porcelain.collect(ctx, "userListRepos", zfj.userListReposRaw, client, ¶ms); } else blk: { var params: zfj.UserCurrentListReposParams = .{ .limit = o.limit, .page = o.page }; break :blk try porcelain.collect(ctx, "userCurrentListRepos", zfj.userCurrentListReposRaw, client, ¶ms); }) { .ok => |ok| ok, .failed => |exit| return exit, }; if (o.json) return writeJson(ctx, joined); const parsed = std.json.parseFromSlice([]const zfj.Repository, ctx.gpa, joined, .{ .ignore_unknown_fields = true }) catch |err| { _ = ctx.parseFailure("the list", "a list of Repository", @errorName(err)); return .response_mismatch; }; defer parsed.deinit(); return writeRepositoryList(ctx, parsed.value); } }; const Clone = struct { repository: []const u8, directory: ?[]const u8 = null, protocol: ?Config.Protocol = null, @"git-args": []const []const u8 = &.{}, pub const short = .{ .p = "protocol" }; pub const positional: []const []const u8 = &.{ "repository", "directory" }; pub const rest = "git-args"; pub const usage = "clone [] [--protocol https|ssh] [-- ]"; pub const about = "Clones a repository with git. A fork's clone is given its parent as the upstream remote, which is where zfj's issue and pull request commands then go."; pub const notes = [_]args.Note{ .{ .description = "/, or for one of your own" }, .{ .description = "where to clone it; without it, a directory named for the repository", .complete = .dirs }, protocol_note, .{ .description = "options for git clone itself, such as --depth 1" }, }; pub fn run(ctx: *Context, o: Clone) !Exit { const at = switch (try locate(ctx, o.repository)) { .ok => |ok| ok, .failed => |exit| return exit, }; var repository = switch (call.result(ctx, "repoGet", zfj.repoGetResult(at.client, .{ .owner = at.owner, .repo = at.repo }))) { .ok => |ok| ok, .failed => |exit| return exit, }; defer repository.deinit(); const protocol = protocolFor(ctx, o.protocol) catch return .environment; return cloneRepository(ctx, repository.value().*, o.directory, protocol, o.@"git-args"); } }; const Create = struct { repository: []const u8, description: ?[]const u8 = null, private: bool = false, @"default-branch": ?[]const u8 = null, template: bool = false, init: bool = false, readme: ?[]const u8 = null, license: ?[]const u8 = null, gitignore: ?[]const []const u8 = null, @"label-set": ?[]const u8 = null, clone: bool = false, remote: bool = false, protocol: ?Config.Protocol = null, json: bool = false, pub const short = .{ .d = "description", .p = "protocol" }; pub const positional: []const []const u8 = &.{"repository"}; pub const usage = "create [/] [-d ] [--private] [--init] [--clone | --remote] [--json]"; pub const about = "Creates a repository: one of your own, or with / in front, that organization's. It prints the new repository's address. Nothing local is touched unless --clone or --remote asks."; pub const notes = [_]args.Note{ .{ .description = "the new repository's name, or / to create it in an organization" }, .{ .description = "what the repository is" }, .{ .description = "make it private" }, .{ .description = "the default branch's name, when --init makes one" }, .{ .description = "make it a template, for creating others from" }, .{ .description = "make a first commit, with a README; --readme, --license and --gitignore imply it" }, .{ .description = "the README template to start from, such as Default" }, .{ .description = "the license to start with, such as MIT" }, .{ .description = "a .gitignore template to start with, such as Zig; commas separate several" }, .{ .description = "the set of issue labels to start with, such as Default" }, .{ .description = "clone it afterwards, as `zfj repo clone` does" }, .{ .description = "add it to the clone in the working directory as the origin remote" }, protocol_note, json_note, }; pub fn run(ctx: *Context, o: Create) !Exit { if (o.clone and o.remote) return ctx.usage("--clone makes a new clone and --remote adds to this one; give one of them", .{}); if (o.json and (o.clone or o.remote)) return ctx.usage("--json writes the new repository's JSON, and takes neither --clone nor --remote", .{}); const named: Context.Repository = if (std.mem.findScalar(u8, o.repository, '/') != null) Context.parseRepository(o.repository) orelse return ctx.usage("a new repository is or /, not '{s}'", .{o.repository}) else .{ .owner = "", .name = o.repository }; if (named.name.len == 0) return ctx.usage("a repository needs a name", .{}); const client = ctx.client() catch return .environment; // One's own repositories are created by one operation and an // organization's by another, and / should mean the same // as . const mine = named.owner.len == 0 or blk: { const login = switch (try currentLogin(ctx, client)) { .ok => |ok| ok, .failed => |exit| return exit, }; break :blk std.ascii.eqlIgnoreCase(login, named.owner); }; const gitignores = try porcelain.splitCommas(ctx, o.gitignore); const body: zfj.CreateRepoOption = .{ .name = named.name, .description = o.description, .private = o.private, .default_branch = o.@"default-branch", .template = o.template, .auto_init = o.init or o.readme != null or o.license != null or gitignores.len != 0, .readme = o.readme, .license = o.license, .gitignores = if (gitignores.len == 0) null else try std.mem.join(ctx.arena, ",", gitignores), .issue_labels = o.@"label-set", }; var created = switch (if (mine) call.result(ctx, "createCurrentUserRepo", zfj.createCurrentUserRepoResult(client, body)) else call.result(ctx, "createOrgRepo", zfj.createOrgRepoResult(client, .{ .org = named.owner }, body))) { .ok => |ok| ok, .failed => |exit| return exit, }; defer created.deinit(); if (o.json) return writeJson(ctx, created.body); const repository = created.value().*; try ctx.stdout.print("{s}\n", .{repository.html_url orelse repository.full_name orelse named.name}); if (o.clone) { const protocol = protocolFor(ctx, o.protocol) catch return .environment; return cloneRepository(ctx, repository, null, protocol, &.{}); } if (o.remote) { const protocol = protocolFor(ctx, o.protocol) catch return .environment; const url = cloneUrl(repository, protocol) orelse return ctx.environment("Forgejo gave no {t} URL for {s}, so it is not a remote", .{ protocol, repository.full_name orelse named.name }); try ctx.stdout.flush(); const added = git.runShown(ctx.io, &.{ "git", "remote", "add", "origin", url }) catch |err| return ctx.environment("cannot run git: {s}", .{@errorName(err)}); if (!added) return ctx.environment("the repository is created, but could not be added as the origin remote", .{}); try ctx.stderr.print("Added {s} as the origin remote.\n", .{url}); try ctx.stderr.flush(); } return .ok; } }; const Fork = struct { repository: ?[]const u8 = null, org: ?[]const u8 = null, name: ?[]const u8 = null, remote: bool = false, clone: bool = false, protocol: ?Config.Protocol = null, json: bool = false, pub const short = .{ .p = "protocol" }; pub const positional: []const []const u8 = &.{"repository"}; pub const usage = "fork [/] [--org ] [--name ] [--remote | --clone] [--json]"; pub const about = "Forks a repository, and prints the fork's address. A fork already there is no failure: it is found and used instead, so that forking twice is the same as forking once. Nothing local is touched unless --remote or --clone asks."; pub const notes = [_]args.Note{ repository_note, .{ .description = "fork into this organization rather than to your own" }, .{ .description = "name the fork this, rather than as the repository is named" }, .{ .description = "in a clone of the repository: rename its origin remote to upstream, and add the fork as origin" }, .{ .description = "clone the fork, as `zfj repo clone` does, with the repository as upstream" }, protocol_note, .{ .description = "write Forgejo's JSON for the fork rather than its address" }, }; pub fn run(ctx: *Context, o: Fork) !Exit { if (o.clone and o.remote) return ctx.usage("--clone makes a new clone and --remote changes this one; give one of them", .{}); if (o.json and (o.clone or o.remote)) return ctx.usage("--json writes the fork's JSON, and takes neither --clone nor --remote", .{}); const at = switch (try locate(ctx, o.repository)) { .ok => |ok| ok, .failed => |exit| return exit, }; // Checked before forking, so that a clone which cannot take the // remotes is said to be so before anything is made. if (o.remote) if (checkRemotes(ctx, at)) |exit| return exit; var response = zfj.createForkRaw(at.client, .{ .owner = at.owner, .repo = at.repo }, .{ .organization = o.org, .name = o.name, }) catch |err| return ctx.transport("createFork", err); defer response.deinit(); const fork_owner, const fork_name = switch (response.status) { .conflict => switch (try findFork(ctx, at, o.org)) { .ok => |ok| ok, .failed => |exit| return exit, }, else => found: { if (response.status.class() != .success) return ctx.apiError("createFork", response.status, response.body); const made = std.json.parseFromSlice(zfj.Repository, ctx.gpa, response.body, .{ .ignore_unknown_fields = true }) catch |err| { _ = ctx.parseFailure("createFork", "Repository", @errorName(err)); return .response_mismatch; }; defer made.deinit(); const owner = if (made.value.owner) |user| user.login else null; break :found .{ try ctx.arena.dupe(u8, owner orelse return ctx.environment("Forgejo did not say whose the fork is", .{})), try ctx.arena.dupe(u8, made.value.name orelse return ctx.environment("Forgejo did not say what the fork is called", .{})), }; }, }; // Read back whole, with its parent, whichever way it was come by. var fork = switch (call.result(ctx, "repoGet", zfj.repoGetResult(at.client, .{ .owner = fork_owner, .repo = fork_name }))) { .ok => |ok| ok, .failed => |exit| return exit, }; defer fork.deinit(); if (o.json) return writeJson(ctx, fork.body); const repository = fork.value().*; if (response.status == .conflict) { try ctx.stderr.print("{s}/{s} already has a fork at {s}/{s}.\n", .{ at.owner, at.repo, fork_owner, fork_name }); try ctx.stderr.flush(); } try ctx.stdout.print("{s}\n", .{repository.html_url orelse repository.full_name orelse fork_name}); if (o.clone) { const protocol = protocolFor(ctx, o.protocol) catch return .environment; return cloneRepository(ctx, repository, null, protocol, &.{}); } if (o.remote) { const protocol = protocolFor(ctx, o.protocol) catch return .environment; const url = cloneUrl(repository, protocol) orelse return ctx.environment("Forgejo gave no {t} URL for {s}/{s}, so it is not a remote", .{ protocol, fork_owner, fork_name }); try ctx.stdout.flush(); if (!(git.runShown(ctx.io, &.{ "git", "remote", "rename", "origin", "upstream" }) catch |err| return ctx.environment("cannot run git: {s}", .{@errorName(err)}))) return ctx.environment("the fork is made, but the origin remote could not be renamed to upstream", .{}); if (!(git.runShown(ctx.io, &.{ "git", "remote", "add", "origin", url }) catch |err| return ctx.environment("cannot run git: {s}", .{@errorName(err)}))) return ctx.environment("the fork is made and origin is now upstream, but the fork could not be added as origin", .{}); try ctx.stderr.print("Renamed origin to upstream, and added {s} as origin.\n", .{url}); try ctx.stderr.flush(); } return .ok; } }; /// Null when the clone here can take a fork's remotes: an origin that is /// the repository being forked, and no upstream yet. fn checkRemotes(ctx: *Context, at: Place) ?Exit { const origin = git.remoteLocation(ctx.arena, ctx.io, "origin") orelse return ctx.usage("--remote changes the clone here, and it has no origin remote", .{}); if (!std.ascii.eqlIgnoreCase(origin.owner, at.owner) or !std.ascii.eqlIgnoreCase(origin.repo, at.repo)) return ctx.usage("--remote changes a clone of {s}/{s}, and origin here is {s}/{s}", .{ at.owner, at.repo, origin.owner, origin.repo }); if (git.remoteLocation(ctx.arena, ctx.io, "upstream") != null) return ctx.usage("--remote would rename origin to upstream, and the clone here already has an upstream remote", .{}); return null; } /// The fork of the repository at `at` that `org`, or else the /// authenticated user, already has: which may be named otherwise. fn findFork(ctx: *Context, at: Place, org: ?[]const u8) !call.Got(struct { []const u8, []const u8 }) { const owner = org orelse switch (try currentLogin(ctx, at.client)) { .ok => |ok| ok, .failed => |exit| return .{ .failed = exit }, }; var params: zfj.ListForksParams = .{ .owner = at.owner, .repo = at.repo }; const joined = switch (try porcelain.collectAll(ctx, "listForks", zfj.listForksRaw, at.client, ¶ms)) { .ok => |ok| ok, .failed => |exit| return .{ .failed = exit }, }; const forks = std.json.parseFromSliceLeaky([]const zfj.Repository, ctx.arena, joined, .{ .ignore_unknown_fields = true }) catch |err| { _ = ctx.parseFailure("listForks", "a list of Repository", @errorName(err)); return .{ .failed = .response_mismatch }; }; for (forks) |fork| { const login = (fork.owner orelse continue).login orelse continue; if (std.ascii.eqlIgnoreCase(login, owner)) return .{ .ok = .{ login, fork.name orelse continue } }; } return .{ .failed = ctx.environment("Forgejo says {s} already has a fork of {s}/{s}, and lists none", .{ owner, at.owner, at.repo }) }; } const Edit = struct { repository: ?[]const u8 = null, name: ?[]const u8 = null, description: ?[]const u8 = null, website: ?[]const u8 = null, @"default-branch": ?[]const u8 = null, private: bool = false, public: bool = false, archive: bool = false, unarchive: bool = false, template: bool = false, @"no-template": bool = false, enable: ?[]const []const u8 = null, disable: ?[]const []const u8 = null, json: bool = false, pub const short = .{ .d = "description" }; pub const positional: []const []const u8 = &.{"repository"}; pub const usage = "edit [/] [--name ] [-d ] [--private | --public] [--archive | --unarchive] [--enable ] [--disable ] [--json]"; pub const about = "Changes a repository. Only what is given changes; the merge settings and the rest are `zfj op repoEdit`'s."; pub const notes = [_]args.Note{ .{ .description = "/; without it, the clone's upstream or origin remote" }, .{ .description = "rename it; the old name goes on redirecting to the new" }, .{ .description = "what the repository is" }, .{ .description = "the repository's website" }, .{ .description = "the branch pull requests go to and clones check out" }, .{ .description = "make it private" }, .{ .description = "make it public" }, .{ .description = "archive it, leaving it to be read and not changed" }, .{ .description = "take it out of the archive" }, .{ .description = "make it a template, for creating others from" }, .{ .description = "make it no longer a template" }, .{ .description = "turn a unit on: " ++ unit_names ++ "; commas separate several" }, .{ .description = "turn a unit off, as for --enable" }, .{ .description = "write Forgejo's JSON for the repository as changed" }, }; pub fn run(ctx: *Context, o: Edit) !Exit { if (o.private and o.public) return ctx.usage("give --private or --public, not both", .{}); if (o.archive and o.unarchive) return ctx.usage("give --archive or --unarchive, not both", .{}); if (o.template and o.@"no-template") return ctx.usage("give --template or --no-template, not both", .{}); var body: zfj.EditRepoOption = .{ .name = o.name, .description = o.description, .website = o.website, .default_branch = o.@"default-branch", .private = either(o.private, o.public), .archived = either(o.archive, o.unarchive), .template = either(o.template, o.@"no-template"), }; for ([_]struct { []const []const u8, bool }{ .{ try porcelain.splitCommas(ctx, o.enable), true }, .{ try porcelain.splitCommas(ctx, o.disable), false } }) |entry| { const names, const on = entry; for (names) |unit_name| { const unit = std.meta.stringToEnum(Unit, unit_name) orelse return ctx.usage("'{s}' is not a unit; the units are " ++ unit_names, .{unit_name}); const field = unitField(&body, unit); if (field.* != null and field.* != on) return ctx.usage("{s} cannot be both enabled and disabled", .{unit_name}); field.* = on; } } if (std.meta.eql(body, .{})) return ctx.usage("nothing to change; `zfj repo edit --help` says what can be", .{}); const at = switch (try locateAs(ctx, o.repository, .refused)) { .ok => |ok| ok, .failed => |exit| return exit, }; var edited = switch (call.result(ctx, "repoEdit", zfj.repoEditResult(at.client, .{ .owner = at.owner, .repo = at.repo }, body))) { .ok => |ok| ok, .failed => |exit| return exit, }; defer edited.deinit(); if (o.json) { const exit = try writeJson(ctx, edited.body); if (o.name != null) try noteRemotes(ctx, at, edited.value().*); return exit; } try ctx.stdout.print("Edited {s}\n", .{edited.value().full_name orelse at.repo}); if (o.name != null) try noteRemotes(ctx, at, edited.value().*); return .ok; } }; /// The units of a repository that `repo edit` turns on and off. const Unit = enum { issues, wiki, @"pull-requests", projects, releases, packages, actions }; const unit_names = "issues, wiki, pull-requests, projects, releases, packages, actions"; comptime { var names: []const u8 = ""; for (@typeInfo(Unit).@"enum".field_names, 0..) |name, i| names = names ++ (if (i == 0) "" else ", ") ++ name; if (!std.mem.eql(u8, names, unit_names)) @compileError("unit_names does not list Unit"); } fn unitField(body: *zfj.EditRepoOption, unit: Unit) *?bool { return switch (unit) { .issues => &body.has_issues, .wiki => &body.has_wiki, .@"pull-requests" => &body.has_pull_requests, .projects => &body.has_projects, .releases => &body.has_releases, .packages => &body.has_packages, .actions => &body.has_actions, }; } /// A pair of flags, one meaning true and the other false: null for neither. fn either(yes: bool, no: bool) ?bool { if (yes) return true; if (no) return false; return null; } /// After a rename, the commands that would point the clone's remotes at the /// new name. Forgejo redirects the old one, so nothing has to change, and /// nothing is changed. fn noteRemotes(ctx: *Context, at: Place, renamed: zfj.Repository) !void { for (git.remote_names) |remote| { const url = git.remoteUrl(ctx.arena, ctx.io, remote) orelse continue; const location = git.parseUrl(url) orelse continue; if (!std.ascii.eqlIgnoreCase(location.owner, at.owner) or !std.ascii.eqlIgnoreCase(location.repo, at.repo)) continue; const over_http = std.mem.startsWith(u8, url, "http://") or std.mem.startsWith(u8, url, "https://"); const new_url = (if (over_http) renamed.clone_url else renamed.ssh_url) orelse continue; try ctx.stderr.print("The {s} remote still names the old repository, which redirects; to point it at the new one:\n git remote set-url {s} {s}\n", .{ remote, remote, new_url }); } try ctx.stderr.flush(); } const Delete = struct { repository: []const u8, yes: bool = false, pub const short = .{ .y = "yes" }; pub const positional: []const []const u8 = &.{"repository"}; pub const usage = "delete / [--yes]"; pub const about = "Deletes a repository, with its issues, pull requests, wiki and releases, for good. On a terminal it asks for the repository's name to be typed back first; anywhere else it deletes nothing without --yes."; pub const notes = [_]args.Note{ .{ .description = "/, always in full: never a bare name, and never the clone's remote" }, .{ .description = "delete it without asking" }, }; pub fn run(ctx: *Context, o: Delete) !Exit { const named = Context.parseRepository(o.repository) orelse return ctx.usage("delete takes the repository in full, as /, not '{s}'", .{o.repository}); const client = ctx.client() catch return .environment; // Looked up first, so that a mistyped name is a 404 rather than a // question about a repository that is not there. var repository = switch (call.result(ctx, "repoGet", zfj.repoGetResult(client, .{ .owner = named.owner, .repo = named.name }))) { .ok => |ok| ok, .failed => |exit| return exit, }; defer repository.deinit(); const full_name = try ctx.arena.dupe(u8, repository.value().full_name orelse o.repository); if (!o.yes) { const stdin: Io.File = .stdin(); const stderr: Io.File = .stderr(); if (!(stdin.isTty(ctx.io) catch false) or !(stderr.isTty(ctx.io) catch false)) return ctx.usage("nothing was deleted: with no terminal to ask at, --yes says to delete {s}", .{full_name}); try ctx.stderr.print( "This deletes {s}, with its issues, pull requests, wiki and releases, and cannot be undone.\nType {s} to delete it: ", .{ full_name, full_name }, ); try ctx.stderr.flush(); var buffer: [512]u8 = undefined; var reader = stdin.reader(ctx.io, &buffer); const line = reader.interface.takeDelimiterInclusive('\n') catch ""; if (!std.mem.eql(u8, std.mem.trim(u8, line, " \t\r\n"), full_name)) return ctx.usage("that is not {s}, so nothing was deleted", .{full_name}); } if (call.done(ctx, "repoDelete", zfj.repoDeleteRaw(client, .{ .owner = named.owner, .repo = named.name }))) |exit| return exit; try ctx.stdout.print("Deleted {s}\n", .{full_name}); return .ok; } }; const protocol_note: args.Note = .{ .description = "clone over https or ssh; without it, as `zfj login --protocol` chose for the instance, else https" }; /// `--protocol`, else the instance's, else https. fn protocolFor(ctx: *Context, given: ?Config.Protocol) error{Reported}!Config.Protocol { if (given) |protocol| return protocol; return (try ctx.target()).protocol orelse .https; } fn cloneUrl(repository: zfj.Repository, protocol: Config.Protocol) ?[]const u8 { return switch (protocol) { .https => repository.clone_url, .ssh => repository.ssh_url, }; } /// `git clone`s `repository` into `directory`, and when it is a fork, adds /// its parent as the `upstream` remote. fn cloneRepository( ctx: *Context, repository: zfj.Repository, directory: ?[]const u8, protocol: Config.Protocol, git_args: []const []const u8, ) !Exit { const full_name = repository.full_name orelse "the repository"; const url = cloneUrl(repository, protocol) orelse return ctx.environment("Forgejo gave no {t} URL to clone {s} from", .{ protocol, full_name }); // Where git will put it: named for the repository, as git would name it // from the URL, so that the remote can be added there afterwards. const into = directory orelse repository.name orelse return ctx.environment("Forgejo gave no name for {s}; say where to clone it", .{full_name}); try ctx.stdout.flush(); try ctx.stderr.flush(); const clone_argv = try std.mem.concat(ctx.arena, []const u8, &.{ &.{ "git", "clone" }, git_args, &.{ "--", url, into } }); const cloned = git.runShown(ctx.io, clone_argv) catch |err| return ctx.environment("cannot run git: {s}", .{@errorName(err)}); if (!cloned) return ctx.environment("git clone did not succeed", .{}); if (repository.fork orelse false) { const parent = repository.parent orelse return .ok; const parent_url = cloneUrl(parent.*, protocol) orelse return ctx.environment("Forgejo gave no {t} URL for {s}'s parent, so it has no upstream remote", .{ protocol, full_name }); const added = git.runShown(ctx.io, &.{ "git", "-C", into, "remote", "add", "upstream", parent_url }) catch |err| return ctx.environment("cannot run git: {s}", .{@errorName(err)}); if (!added) return ctx.environment("the clone is made, but its upstream remote could not be added", .{}); try ctx.stderr.print("Added {s} as the upstream remote.\n", .{parent.full_name orelse parent_url}); try ctx.stderr.flush(); } return .ok; } /// Columns on a terminal -- name, what kind of repository, description -- /// and otherwise one repository to a line with those separated by tabs. fn writeRepositoryList(ctx: *Context, repositories: []const zfj.Repository) !Exit { var out: Io.Writer.Allocating = .init(ctx.arena); if (!ctx.stdoutIsTty()) { for (repositories) |repository| { try out.writer.print("{s}\t{s}\t", .{ repository.full_name orelse "", visibility(repository) }); try writeKinds(&out.writer, repository, ",", .between); try out.writer.print("\t{s}\n", .{oneLine(repository.description orelse "")}); } try ctx.stdout.writeAll(out.written()); try ctx.stdout.flush(); return .ok; } if (repositories.len == 0) { try ctx.stdout.writeAll("No repositories.\n"); try ctx.stdout.flush(); return .ok; } const style = Style.of(ctx); var name_width: usize = 0; var kind_width: usize = 0; for (repositories) |repository| { name_width = @max(name_width, @as([]const u8, repository.full_name orelse "").len); kind_width = @max(kind_width, kindLength(repository)); } for (repositories) |repository| { const name = repository.full_name orelse ""; try out.writer.print("{s}{s}{s}", .{ style.bold, name, style.reset }); try out.writer.splatByteAll(' ', name_width - name.len); try out.writer.print(" {s}", .{visibility(repository)}); try writeKinds(&out.writer, repository, ", ", .before); const description = oneLine(repository.description orelse ""); if (description.len != 0) { try out.writer.splatByteAll(' ', kind_width - kindLength(repository)); try out.writer.print(" {s}{s}{s}", .{ style.dim, description, style.reset }); } try out.writer.writeByte('\n'); } try ctx.page(out.written()); return .ok; } fn visibility(repository: zfj.Repository) []const u8 { if (repository.private orelse false) return "private"; if (repository.internal orelse false) return "internal"; return "public"; } /// What a repository is besides its visibility -- fork, mirror, template, /// archived -- each after `separator`, or with `.between` only between them. fn writeKinds(writer: *Io.Writer, repository: zfj.Repository, separator: []const u8, placing: enum { before, between }) !void { var first = true; for (kinds(repository)) |kind| if (kind) |k| { if (!first or placing == .before) try writer.writeAll(separator); try writer.writeAll(k); first = false; }; } fn kinds(repository: zfj.Repository) [4]?[]const u8 { return .{ if (repository.fork orelse false) "fork" else null, if (repository.mirror orelse false) "mirror" else null, if (repository.template orelse false) "template" else null, if (repository.archived orelse false) "archived" else null, }; } /// How wide the visibility and kinds are in the terminal's columns. fn kindLength(repository: zfj.Repository) usize { var length = visibility(repository).len; for (kinds(repository)) |kind| if (kind) |k| { length += ", ".len + k.len; }; return length; } fn renderRepository(writer: *Io.Writer, style: Style, repository: zfj.Repository) !void { try writer.print("{s}{s}{s}\n", .{ style.bold, repository.full_name orelse "", style.reset }); try writer.writeAll(visibility(repository)); if (repository.fork orelse false) { try writer.writeAll(" · fork"); if (repository.parent) |parent| try writer.print(" of {s}", .{parent.full_name orelse ""}); } if (repository.mirror orelse false) try writer.writeAll(" · mirror"); if (repository.template orelse false) try writer.writeAll(" · template"); if (repository.archived orelse false) try writer.print(" · {s}archived{s}", .{ style.yellow, style.reset }); if (repository.empty orelse false) try writer.writeAll(" · empty"); try writer.writeByte('\n'); const description = std.mem.trim(u8, repository.description orelse "", " \t\r\n"); if (description.len != 0) try writer.print("{s}\n", .{description}); try writer.writeByte('\n'); if (repository.default_branch) |branch| if (branch.len != 0) try writer.print("Default branch: {s}\n", .{branch}); if (repository.website) |website| if (website.len != 0) try writer.print("Website: {s}\n", .{website}); try writeCount(writer, repository.stars_count, "star", "stars", ""); try writeCount(writer, repository.forks_count, "fork", "forks", " · "); try writeCount(writer, repository.open_issues_count, "open issue", "open issues", " · "); try writeCount(writer, repository.open_pr_counter, "open pull request", "open pull requests", " · "); try writer.writeByte('\n'); if (repository.clone_url) |url| try writer.print("Clone: {s}\n", .{url}); if (repository.ssh_url) |url| try writer.print("{s}{s}\n", .{ if (repository.clone_url == null) "Clone: " else " ", url }); if (repository.html_url) |url| try writer.print("{s}{s}{s}\n", .{ style.dim, url, style.reset }); } fn writeCount(writer: *Io.Writer, count: ?i64, comptime one: []const u8, comptime many: []const u8, comptime separator: []const u8) !void { const n = count orelse 0; try writer.print(separator ++ "{d} {s}", .{ n, if (n == 1) one else many }); } const testing = std.testing; test "a repository is shown with its state, its counts and where to clone it" { const parent: zfj.Repository = .{ .full_name = "alice/thing" }; var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try renderRepository(&out.writer, .{}, .{ .full_name = "team/thing", .description = "A thing.\n", .fork = true, .parent = &parent, .archived = true, .default_branch = "main", .stars_count = 1, .forks_count = 0, .open_issues_count = 2, .open_pr_counter = 1, .clone_url = "https://example.org/team/thing.git", .ssh_url = "ssh://git@example.org/team/thing.git", .html_url = "https://example.org/team/thing", }); try testing.expectEqualStrings( \\team/thing \\public · fork of alice/thing · archived \\A thing. \\ \\Default branch: main \\1 star · 0 forks · 2 open issues · 1 open pull request \\Clone: https://example.org/team/thing.git \\ ssh://git@example.org/team/thing.git \\https://example.org/team/thing \\ , out.written()); } test "a private repository says so before anything else about it" { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try renderRepository(&out.writer, .{}, .{ .full_name = "me/secret", .private = true, .internal = true, .empty = true }); try testing.expect(std.mem.startsWith(u8, out.written(), "me/secret\nprivate · empty\n")); } test "a repository's kinds follow its visibility, in the order a list shows them" { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); const repository: zfj.Repository = .{ .private = true, .fork = true, .archived = true }; try out.writer.writeAll(visibility(repository)); try writeKinds(&out.writer, repository, ", ", .before); try testing.expectEqualStrings("private, fork, archived", out.written()); try testing.expectEqual(out.written().len, kindLength(repository)); out.clearRetainingCapacity(); try writeKinds(&out.writer, repository, ",", .between); try testing.expectEqualStrings("fork,archived", out.written()); } test "each unit is a field of the edit's body" { var body: zfj.EditRepoOption = .{}; unitField(&body, .@"pull-requests").* = false; unitField(&body, .actions).* = true; try testing.expectEqual(false, body.has_pull_requests.?); try testing.expectEqual(true, body.has_actions.?); try testing.expect(body.has_wiki == null); } test "every command compiles" { for (commands) |command| _ = command.run; } test "every command's notes cover its options" { inline for (.{ View, List, Clone, Create, Fork, Edit, Delete }) |Options| { try testing.expectEqual(@typeInfo(Options).@"struct".field_names.len, Options.notes.len); } }