# zfj Zig bindings for the [Forgejo](https://forgejo.org/) API. All 506 operations and 246 models of Forgejo v16.0.3, typed, with the response of every call parsed into the model the API documentation names for it — and `zfj`, a command-line tool built on them that can perform any of those operations. Requires Zig 0.17. The last release for Zig 0.16 is `v0.1.0`, and the `zig-0.16` branch carries it. ## The bindings are generated, not written This repository holds the API *description* — `api/swagger.v1.json`, taken from the Forgejo v16.0.3 release — and a small program that turns it into Zig. The build runs that program and compiles what it prints; no generated source is checked in, so the bindings cannot drift from the specification they came from. Updating to a new Forgejo release is therefore a matter of replacing one file. See [Updating the specification](#updating-the-specification). `zig build` leaves the generated source at `zig-out/api.zig`, which is the reference for what the library actually exposes. `zig build docs` renders the same thing as browsable documentation. ## Using it Add the dependency: ```console zig fetch --save https://git.jcollie.dev/jeff/zfj/archive/main.tar.gz ``` then wire the module up in `build.zig`: ```zig const zfj = b.dependency("zfj", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("zfj", zfj.module("zfj")); ``` Operations are grouped the way the Forgejo API documentation groups them, one client per tag — `IssueClient`, `RepositoryClient`, `UserClient`, `OrganizationClient`, `AdminClient`, `NotificationClient`, `PackageClient`, `SettingsClient`, `MiscellaneousClient`, `ActivitypubClient`: ```zig const std = @import("std"); const zfj = @import("zfj"); pub fn main(init: std.process.Init) !u8 { const allocator = init.gpa; var client = zfj.Client.init(allocator, init.io, init.environ_map.get("FORGEJO_TOKEN").?); defer client.deinit(); client.withBaseUrl("https://codeberg.org/api/v1"); var issues = zfj.IssueClient.init(&client); var issue = try issues.issueGetIssue(.{ .owner = "forgejo", .repo = "forgejo", .index = 42, }); defer issue.deinit(); std.debug.print("{s}\n", .{issue.value().title.?}); return 0; } ``` Every operation is also a plain function taking the client as its first argument, so the call above can equally be written `zfj.issueGetIssue(&client, .{ ... })`. The tag clients are a grouping over those functions and nothing more. Three forms of each operation are generated: | Form | Returns | For | | --- | --- | --- | | `issueGetIssue` | `Owned(Issue)` | the usual case: a parsed model, or `error.ResponseError` | | `issueGetIssueResult` | `ApiResult(Issue)` | when the failing status code matters | | `issueGetIssueRaw` | `RawResponse` | when the bytes matter | `Owned(T)` owns both the response body and the parsed model; `deinit()` frees both, and `value()` borrows the model out of it. Model fields are optional and default to null, because the API omits rather than nulls what it has no value for. An operation's path and query values are passed as one struct, its params, whose type is named after the operation: `issueGetIssue` takes an `IssueGetIssueParams`. An operation that sends a body takes it as a separate argument, typed as the model the API documentation names for it. Many of those are Forgejo's own `…Option` models, such as `CreateIssueOption`, and are never params. Operation names are Forgejo's operationIds with the first letter lowercased, so they can be looked up in the API documentation as they are. The one exception is `renderRawMarkdown`, Forgejo's `renderMarkdownRaw`, whose id is already the name of `renderMarkdown`'s raw form. Operations whose only successful response is empty — the deletes, mostly — return `!void`. `RawResponse` and `Owned(T)` both keep the response's headers, and `header(name)` finds one regardless of case — which is how Forgejo says how many results there are (`X-Total-Count`) and where the next page is (`Link`). The specification's summaries and descriptions are doc comments on the operations, their params and the models, so they appear in `zig build docs` and in an editor. The same text is also available while a program runs: `zfj.operation_info.` is an `OperationInfo` holding the operation's method, path and summary, and for each of its params the location, description and allowed values. ### Authentication The token passed to `Client.init` is sent as `Authorization: Bearer `. Forgejo accepts that spelling as well as the `token ` its documentation describes; both are read by the same code path. Pass an empty string to make requests unauthenticated. ## The command-line tool `zig build` also builds `zig-out/bin/zfj`. Every operation the bindings export is a command of its own, named after the operation: ```console $ zfj login codeberg https://codeberg.org Token for https://codeberg.org (made under Settings, Applications): Logged in to codeberg (https://codeberg.org) as someone. codeberg is the default instance. $ zfj op issueGetIssue --owner forgejo --repo forgejo --index 42 ``` `zfj op` alone lists the operations, and `zfj op --help` says what an operation does, the request it makes, and each of its params with its description and, where the API documentation gives them, the values it accepts. The flags after an operation's name are exactly its params, spelled as the API documentation spells them — `--page`, `--type`, `--color` and all. The tool's own options, such as `--instance`, `--debug` and `--color` for the terminal, go *before* the command and nowhere else, so the two can never be confused. An operation that sends a request body reads it from stdin as JSON, and the JSON is checked against the request body's model before anything is sent, so a misspelled field is caught locally: ```console $ echo '{"title": "It broke"}' | zfj op issueCreateIssue --owner me --repo thing ``` An operation that uploads a file takes it as a path, and sends it under the path's own name; `-` reads it from stdin instead, named by `--name`: ```console $ zfj op issueCreateIssueAttachment --owner me --repo thing --index 42 --attachment crash.log ``` A list operation returns one page at a time. With `--paginate`, `zfj` follows the `Link` header Forgejo sends from page to page and writes every page's items as one JSON array: ```console $ zfj --paginate op issueListIssues --owner forgejo --repo forgejo --state all ``` A successful response is written to stdout exactly as Forgejo sent it. It is also parsed into the model the API documentation names for it; if that fails, `zfj` warns on stderr, and with `--strict` it fails instead. An error response goes to stderr, so stdout only ever holds a successful one. | Exit status | Meaning | | --- | --- | | 0 | success | | 1 | the instance answered with an error status | | 2 | a usage error: an unknown option, a missing param, a request body that does not parse | | 3 | no instance to reach, the configuration file cannot be read, or the request got no answer | | 4 | with `--strict`, a successful response that does not parse into its model | | 5 | with `--exit-status`, a run that did not succeed | A reader that stops early, such as `head` in `zfj run view 12 --log | head`, is not an error: `zfj` stops writing and exits 0, saying nothing on stderr. ### Working with issues `zfj issue` holds commands shaped around tasks rather than single operations, spelled as `fj`'s are: ```console $ zfj issue list --state all -l bug $ zfj issue view 42 --comments $ zfj issue view 42 --web $ zfj issue create -t "It broke" -F report.md -l bug $ zfj issue comment 42 -b "Fixed in 1a2b3c4." $ zfj issue edit 42 --add-label needs-info --add-assignee someone $ zfj issue close 42 -c "Fixed in 1a2b3c4." $ zfj issue reopen 42 -c "Still happens on Windows." $ zfj issue block 42 --by 41 $ zfj issue blockers 42 ``` The repository is named with `-R /`. Without it, it is read off the clone's `upstream` remote, or failing that its `origin`, and the remote has to be on the instance being reached — which, unless `--instance` or `ZFJ_INSTANCE` names another, is the configured instance on the remote's host. Without `-b` or `-F`, and on a terminal, `create` and `comment` open `$EDITOR` for the text. `close` and `reopen` take a comment with `-c` or `-F`, post it before changing the issue's state, and without either leave no comment. `view --web` opens the issue in `$BROWSER` when that is set, and otherwise in the user's chosen browser, through [zig-openuri](https://git.jcollie.dev/jeff/zig-openuri): the desktop portal on Linux, falling back to `xdg-open` where there is no portal (over ssh, say), and `ShellExecuteExW` on Windows. On macOS it runs `open`. On a terminal, lists are columns and an issue is shown with its body as Markdown, through `$ZFJ_PAGER`, `$PAGER` or `less` (on Windows, only `$ZFJ_PAGER`). The editor is `$VISUAL` or `$EDITOR`, else `vi` (`notepad` on Windows). Piped elsewhere, a list is one issue to a line with its number, state, title and labels separated by tabs. `--json` writes Forgejo's own JSON instead; `view --comments --json` adds the comment thread to the issue as a `comments` list, and `list --json` honors `--paginate`. `zfj issue --help` says what each takes. ### Pull requests `zfj pr` opens them and reads them: ```console $ git push origin my-branch $ zfj pr create -t "Fix the thing" -b "It was broken." -l bug $ zfj pr list --state all -B main $ zfj pr view 42 --comments $ zfj pr diff 42 $ zfj pr diff 42 --patch | git am ``` `create` opens a pull request from a branch already pushed. The head is the branch checked out unless `-H` names another, and the base is the repository's default branch unless `-B` names another. In a clone of a fork, where `origin` is the fork and `upstream` the repository it came from, the pull request goes to `upstream` from the branch on `origin`. Without `-b` or `-F`, and on a terminal, `$EDITOR` is opened for the description. `list` filters by `-l