// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The instances `zfj` knows, kept in `$XDG_CONFIG_HOME/zfj/config.zon`, and //! the choice of which one a command reaches. //! //! The file holds tokens, so it is written readable by its owner alone, and //! written whole into a temporary file that then replaces it, so that an //! interrupted `zfj login` cannot leave half of one behind. const Config = @This(); const std = @import("std"); const builtin = @import("builtin"); const Allocator = std.mem.Allocator; const Io = std.Io; const git = @import("git.zig"); pub const Instance = struct { /// What the instance is called on the command line. name: []const u8, /// Where it is, without the API's path. url: []const u8, token: []const u8, /// How to clone from it, when `zfj login --protocol` said. protocol: ?Protocol = null, }; /// Which of a repository's URLs git is given: the one over HTTP(S), or the /// one over ssh. pub const Protocol = enum { https, ssh }; /// The name of the default instance. default: ?[]const u8 = null, instances: []const Instance = &.{}, /// Where the file is: `$XDG_CONFIG_HOME/zfj/config.zon`; else, on Windows, /// `%APPDATA%\zfj\config.zon`; else `$HOME/.config/zfj/config.zon`. pub fn path(arena: Allocator, environ: *const std.process.Environ.Map) error{ OutOfMemory, NoHome }![]const u8 { return pathFor(arena, environ, builtin.os.tag); } fn pathFor(arena: Allocator, environ: *const std.process.Environ.Map, os: std.Target.Os.Tag) error{ OutOfMemory, NoHome }![]const u8 { const separator: u8 = if (os == .windows) '\\' else '/'; if (nonEmpty(environ, "XDG_CONFIG_HOME")) |xdg| { return std.fmt.allocPrint(arena, "{s}{c}zfj{c}config.zon", .{ xdg, separator, separator }); } if (os == .windows) { if (nonEmpty(environ, "APPDATA")) |appdata| { return std.fmt.allocPrint(arena, "{s}\\zfj\\config.zon", .{appdata}); } } const home = nonEmpty(environ, "HOME") orelse return error.NoHome; return std.fmt.allocPrint(arena, "{s}{c}.config{c}zfj{c}config.zon", .{ home, separator, separator, separator }); } fn nonEmpty(environ: *const std.process.Environ.Map, name: []const u8) ?[]const u8 { const value = environ.get(name) orelse return null; return if (value.len == 0) null else value; } pub const LoadError = error{ OutOfMemory, Invalid, Unreadable }; /// Reads the file at `sub_path`, or nothing if there is none. On /// `error.Invalid` or `error.Unreadable`, `message` says what is wrong with it. pub fn load( gpa: Allocator, arena: Allocator, io: Io, dir: Io.Dir, sub_path: []const u8, message: *[]const u8, ) LoadError!Config { const source = dir.readFileAllocOptions(io, sub_path, arena, .limited(1 << 20), .of(u8), 0) catch |err| switch (err) { error.FileNotFound => return .{}, error.OutOfMemory => return error.OutOfMemory, else => { message.* = try std.fmt.allocPrint(arena, "cannot read {s}: {s}", .{ sub_path, @errorName(err) }); return error.Unreadable; }, }; var diagnostics: std.zon.parse.Diagnostics = undefined; return std.zon.parse.fromSlice(Config, .{ .gpa = gpa, .arena = arena, .source = source, .diagnostics = &diagnostics, }) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.ParseZon => { message.* = try std.fmt.allocPrint(arena, "{f}", .{diagnostics.fmt(sub_path)}); return error.Invalid; }, }; } pub fn save(config: Config, io: Io, dir: Io.Dir, sub_path: []const u8) !void { var file = try dir.createFileAtomic(io, sub_path, .{ .permissions = private, .make_path = true, .replace = true, }); defer file.deinit(io); var buffer: [4096]u8 = undefined; var writer = file.file.writer(io, &buffer); try writer.interface.writeAll( \\// The Forgejo instances zfj knows, written by `zfj login`. It holds \\// their tokens, so keep it readable by you alone. \\ ); try std.zon.stringify.serialize(config, .{}, &writer.interface); try writer.interface.writeByte('\n'); try writer.interface.flush(); try file.replace(io); } /// Readable and writable by the owner and nobody else. const private: Io.File.Permissions = if (@hasDecl(Io.File.Permissions, "fromMode")) .fromMode(0o600) else .default_file; pub fn find(config: Config, name: []const u8) ?Instance { for (config.instances) |instance| { if (std.mem.eql(u8, instance.name, name)) return instance; } return null; } /// The instance at `url`, ignoring a trailing slash on either. pub fn findUrl(config: Config, url: []const u8) ?Instance { for (config.instances) |instance| { if (std.mem.eql(u8, trimUrl(instance.url), trimUrl(url))) return instance; } return null; } fn trimUrl(url: []const u8) []const u8 { return std.mem.trimEnd(u8, url, "/"); } /// Adds `instance`, or replaces the one with its name. The first instance /// there is becomes the default. pub fn put(config: *Config, arena: Allocator, instance: Instance) Allocator.Error!void { var list: std.ArrayList(Instance) = .empty; var replaced = false; for (config.instances) |existing| { if (std.mem.eql(u8, existing.name, instance.name)) { try list.append(arena, instance); replaced = true; } else { try list.append(arena, existing); } } if (!replaced) try list.append(arena, instance); config.instances = list.items; if (config.default == null) config.default = instance.name; } /// Removes the instance called `name`, saying whether there was one. Removing /// the default leaves no default rather than guessing at another. pub fn remove(config: *Config, arena: Allocator, name: []const u8) Allocator.Error!bool { var list: std.ArrayList(Instance) = .empty; var removed = false; for (config.instances) |existing| { if (std.mem.eql(u8, existing.name, name)) { removed = true; } else { try list.append(arena, existing); } } config.instances = list.items; if (config.default) |d| { if (std.mem.eql(u8, d, name)) config.default = null; } return removed; } pub fn isUrl(text: []const u8) bool { return std.mem.startsWith(u8, text, "https://") or std.mem.startsWith(u8, text, "http://"); } /// The instance whose URL is on `host`. pub fn findHost(config: Config, host: []const u8) ?Instance { for (config.instances) |instance| { const instance_host = git.urlHost(instance.url) orelse continue; if (std.ascii.eqlIgnoreCase(instance_host, host)) return instance; } return null; } /// Where a command is going, and with what token. pub const Target = struct { url: []const u8, token: []const u8, /// The configured instance, if it is one. name: ?[]const u8, /// How to clone from it, if the configuration says. protocol: ?Protocol = null, /// How it was chosen. by: enum { choice, remote, default }, }; pub const SelectError = error{ UnknownInstance, NoInstance }; /// Chooses the instance a command reaches. `choice` is `--instance`, or /// failing that `ZFJ_INSTANCE`: a configured instance's name, or a URL, which /// need not be configured at all. Without one, it is the configured instance /// on `remote_host`, the host of the clone's git remote; and without that, /// the default instance. `env_token` is `FORGEJO_TOKEN`, which overrides /// whatever token the instance has. pub fn select(config: Config, choice: ?[]const u8, remote_host: ?[]const u8, env_token: ?[]const u8) SelectError!Target { if (choice) |c| { if (isUrl(c)) { const known = config.findUrl(c); return .{ .url = c, .token = env_token orelse if (known) |k| k.token else "", .name = if (known) |k| k.name else null, .protocol = if (known) |k| k.protocol else null, .by = .choice, }; } const instance = config.find(c) orelse return error.UnknownInstance; return target(instance, env_token, .choice); } if (remote_host) |host| { if (config.findHost(host)) |instance| return target(instance, env_token, .remote); } const name = config.default orelse return error.NoInstance; const instance = config.find(name) orelse return error.UnknownInstance; return target(instance, env_token, .default); } fn target(instance: Instance, env_token: ?[]const u8, by: @FieldType(Target, "by")) Target { return .{ .url = instance.url, .token = env_token orelse instance.token, .name = instance.name, .protocol = instance.protocol, .by = by }; } const testing = std.testing; const example: Config = .{ .default = "home", .instances = &.{ .{ .name = "home", .url = "https://git.example.org", .token = "home-token" }, .{ .name = "codeberg", .url = "https://codeberg.org/", .token = "codeberg-token", .protocol = .ssh }, }, }; test "the default instance is reached when nothing names one" { const t = try example.select(null, null, null); try testing.expectEqualStrings("https://git.example.org", t.url); try testing.expectEqualStrings("home-token", t.token); try testing.expectEqualStrings("home", t.name.?); } test "a name chooses a configured instance" { const t = try example.select("codeberg", null, null); try testing.expectEqualStrings("codeberg-token", t.token); try testing.expectError(error.UnknownInstance, example.select("nowhere", null, null)); } test "a URL needs no configuration, but takes a configured instance's token" { const unknown = try example.select("https://elsewhere.example", null, null); try testing.expectEqualStrings("", unknown.token); try testing.expect(unknown.name == null); const known = try example.select("https://codeberg.org", null, null); try testing.expectEqualStrings("codeberg-token", known.token); try testing.expectEqualStrings("codeberg", known.name.?); } test "FORGEJO_TOKEN overrides the instance's token" { const t = try example.select(null, null, "from-env"); try testing.expectEqualStrings("from-env", t.token); try testing.expectEqualStrings("https://git.example.org", t.url); } test "the git remote's host chooses an instance before the default does" { const t = try example.select(null, "codeberg.org", null); try testing.expectEqualStrings("codeberg", t.name.?); try testing.expectEqual(.remote, t.by); // A name or URL given outright still wins. try testing.expectEqualStrings("home", (try example.select("home", "codeberg.org", null)).name.?); // A remote on a host no instance is on leaves the default. try testing.expectEqualStrings("home", (try example.select(null, "github.com", null)).name.?); } test "with no default and nothing named, there is no instance" { const empty: Config = .{}; try testing.expectError(error.NoInstance, empty.select(null, null, null)); } test "putting an instance replaces one of the same name, and the first becomes the default" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var config: Config = .{}; try config.put(arena.allocator(), .{ .name = "a", .url = "https://a.example", .token = "1" }); try config.put(arena.allocator(), .{ .name = "b", .url = "https://b.example", .token = "2" }); try config.put(arena.allocator(), .{ .name = "a", .url = "https://a.example", .token = "3" }); try testing.expectEqual(@as(usize, 2), config.instances.len); try testing.expectEqualStrings("3", config.find("a").?.token); try testing.expectEqualStrings("a", config.default.?); } test "removing the default leaves no default" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var config = example; try testing.expect(try config.remove(arena.allocator(), "home")); try testing.expect(config.default == null); try testing.expect(!try config.remove(arena.allocator(), "home")); try testing.expectEqual(@as(usize, 1), config.instances.len); } test "the file is written privately, and reads back as it was" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); try example.save(testing.io, tmp.dir, "zfj/config.zon"); if (@hasDecl(Io.File.Permissions, "toMode")) { const stat = try tmp.dir.statFile(testing.io, "zfj/config.zon", .{}); try testing.expectEqual(@as(std.posix.mode_t, 0o600), stat.permissions.toMode() & 0o777); } var message: []const u8 = ""; const loaded = try load(testing.allocator, arena.allocator(), testing.io, tmp.dir, "zfj/config.zon", &message); try testing.expectEqualStrings("home", loaded.default.?); try testing.expectEqual(@as(usize, 2), loaded.instances.len); try testing.expectEqualStrings("codeberg-token", loaded.find("codeberg").?.token); try testing.expectEqual(.ssh, loaded.find("codeberg").?.protocol.?); try testing.expect(loaded.find("home").?.protocol == null); } test "a file from before instances had a protocol still reads" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(testing.io, .{ .sub_path = "config.zon", .data = ".{ .default = \"a\", .instances = .{ .{ .name = \"a\", .url = \"https://a.example\", .token = \"1\" } } }", }); var message: []const u8 = ""; const loaded = try load(testing.allocator, arena.allocator(), testing.io, tmp.dir, "config.zon", &message); try testing.expect(loaded.find("a").?.protocol == null); } test "an instance's protocol goes with it when it is chosen" { try testing.expectEqual(.ssh, (try example.select("codeberg", null, null)).protocol.?); try testing.expectEqual(.ssh, (try example.select("https://codeberg.org", null, null)).protocol.?); try testing.expect((try example.select(null, null, null)).protocol == null); } test "a missing file is no instances, and a broken one says where" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var message: []const u8 = ""; const none = try load(testing.allocator, arena.allocator(), testing.io, tmp.dir, "config.zon", &message); try testing.expectEqual(@as(usize, 0), none.instances.len); try tmp.dir.writeFile(testing.io, .{ .sub_path = "config.zon", .data = ".{ .instances = 7 }" }); try testing.expectError(error.Invalid, load(testing.allocator, arena.allocator(), testing.io, tmp.dir, "config.zon", &message)); try testing.expect(std.mem.startsWith(u8, message, "config.zon:1:")); } test "the file is found under XDG_CONFIG_HOME, or else HOME" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var environ: std.process.Environ.Map = .init(testing.allocator); defer environ.deinit(); try environ.put("HOME", "/home/someone"); try testing.expectEqualStrings("/home/someone/.config/zfj/config.zon", try pathFor(arena.allocator(), &environ, .linux)); try environ.put("XDG_CONFIG_HOME", "/elsewhere"); try testing.expectEqualStrings("/elsewhere/zfj/config.zon", try pathFor(arena.allocator(), &environ, .linux)); } test "on Windows the file is under APPDATA, unless XDG_CONFIG_HOME says otherwise" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var environ: std.process.Environ.Map = .init(testing.allocator); defer environ.deinit(); try testing.expectError(error.NoHome, pathFor(arena.allocator(), &environ, .windows)); try environ.put("APPDATA", "C:\\Users\\someone\\AppData\\Roaming"); try testing.expectEqualStrings("C:\\Users\\someone\\AppData\\Roaming\\zfj\\config.zon", try pathFor(arena.allocator(), &environ, .windows)); // APPDATA means nothing elsewhere. try testing.expectError(error.NoHome, pathFor(arena.allocator(), &environ, .linux)); try environ.put("XDG_CONFIG_HOME", "D:\\config"); try testing.expectEqualStrings("D:\\config\\zfj\\config.zon", try pathFor(arena.allocator(), &environ, .windows)); }