// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The commands that manage the instances `zfj` knows: `login`, `logout`, //! `instances` and `default`. They are the tool's own business rather than //! Forgejo's, so they are top-level words of their own. const std = @import("std"); const builtin = @import("builtin"); const Io = std.Io; const zfj = @import("zfj"); const args = @import("args.zig"); const Config = @import("Config.zig"); const Context = @import("Context.zig"); const Exit = Context.Exit; const Login = struct { name: []const u8, url: []const u8, protocol: ?Config.Protocol = null, pub const positional: []const []const u8 = &.{ "name", "url" }; pub const notes = [_]args.Note{ .{ .description = "what to call the instance, a short word such as the host's" }, .{ .description = "where it is, as an http:// or https:// URL" }, .{ .description = "how `zfj repo clone` clones from it; without it, as before, and at first https" }, }; }; /// What `login` takes, for completing it. pub const login_spec = args.spec(Login, &Login.notes); /// What `logout` and `default` take: the name of an instance. const Named = struct { name: []const u8, pub const positional: []const []const u8 = &.{"name"}; pub const notes = [_]args.Note{.{ .description = "the instance", .complete = .instances }}; }; pub const named_spec = args.spec(Named, &Named.notes); /// `zfj login `: asks for a token (or reads it from stdin when /// that is not a terminal), checks it by asking the instance who it belongs /// to, and saves it. The first instance logged in to becomes the default. pub fn login(ctx: *Context, words: []const []const u8) !Exit { if (wantsHelp(words)) { try ctx.stdout.writeAll("usage: zfj login [--protocol https|ssh]\n\n"); try args.writeHelp(Login, ctx.stdout, &Login.notes); return .ok; } var diagnostic: args.Diagnostic = .{}; const o = (args.parse(Login, ctx.arena, words, .all, &diagnostic) catch |err| switch (err) { error.Usage => return ctx.usage("login takes a name and a URL: {s}", .{diagnostic.message()}), else => |e| return e, }).value; const name = o.name; const url = std.mem.trimEnd(u8, o.url, "/"); if (name.len == 0 or Config.isUrl(name) or std.mem.findAny(u8, name, " \t/") != null) return ctx.usage("'{s}' cannot name an instance; use a short word, such as the host's", .{name}); if (!Config.isUrl(url)) return ctx.usage("'{s}' is not an http:// or https:// URL", .{url}); const token = try readToken(ctx, url) orelse { const stdin: Io.File = .stdin(); if (stdin.isTty(ctx.io) catch false) return ctx.usage("no token was given", .{}); return ctx.usage("no token on stdin; with no terminal to ask at, the token is read from stdin: `zfj login {s} {s} < token-file`", .{ name, url }); }; const client = ctx.makeClient(url, token) catch return .environment; var result = zfj.userGetCurrentResult(client) catch |err| return ctx.transport("userGetCurrent", err); defer result.deinit(); const user = switch (result) { .ok => |*ok| ok.value().login orelse "an unnamed user", .api_error => |raw| return ctx.apiError("userGetCurrent", raw.status, raw.body), .parse_error => |e| blk: { const exit = ctx.parseFailure("userGetCurrent", "User", e.error_name); if (exit != .ok) return exit; break :blk "a user zfj could not read"; }, }; const config = ctx.config() catch return .environment; // Logging in again for a new token keeps the protocol chosen before. const protocol = o.protocol orelse if (config.find(name)) |known| known.protocol else null; try config.put(ctx.arena, .{ .name = name, .url = url, .token = token, .protocol = protocol }); ctx.saveConfig() catch return .environment; try ctx.stdout.print("Logged in to {s} ({s}) as {s}.\n", .{ name, url, user }); if (std.mem.eql(u8, config.default.?, name)) try ctx.stdout.print("{s} is the default instance.\n", .{name}); return .ok; } /// `zfj logout `: forgets an instance and its token. The token itself /// is not revoked; that is done on the instance, under Settings. pub fn logout(ctx: *Context, words: []const []const u8) !Exit { if (wantsHelp(words)) { try ctx.stdout.writeAll("usage: zfj logout \n"); return .ok; } if (words.len != 1) return ctx.usage("logout takes the name of an instance", .{}); const config = ctx.config() catch return .environment; const was_default = if (config.default) |d| std.mem.eql(u8, d, words[0]) else false; if (!try config.remove(ctx.arena, words[0])) return ctx.usage("no instance named '{s}'; `zfj instances` lists them", .{words[0]}); ctx.saveConfig() catch return .environment; try ctx.stdout.print("Logged out of {s}.\n", .{words[0]}); if (was_default) try ctx.stdout.writeAll("There is no default instance now; `zfj default ` sets one.\n"); return .ok; } /// `zfj instances`: the instances, one to a line, the default marked with /// `*`. Tokens are never shown. pub fn instances(ctx: *Context, words: []const []const u8) !Exit { if (wantsHelp(words)) { try ctx.stdout.writeAll("usage: zfj instances\n"); return .ok; } if (words.len != 0) return ctx.usage("instances takes no arguments", .{}); const config = ctx.config() catch return .environment; var width: usize = 0; for (config.instances) |instance| width = @max(width, instance.name.len); for (config.instances) |instance| { const is_default = if (config.default) |d| std.mem.eql(u8, d, instance.name) else false; try ctx.stdout.print("{s} {s}", .{ if (is_default) "*" else " ", instance.name }); try ctx.stdout.splatByteAll(' ', width - instance.name.len + 2); try ctx.stdout.print("{s}\n", .{instance.url}); } return .ok; } /// `zfj default `: the instance reached when nothing names one. pub fn default(ctx: *Context, words: []const []const u8) !Exit { if (wantsHelp(words)) { try ctx.stdout.writeAll("usage: zfj default \n"); return .ok; } if (words.len != 1) return ctx.usage("default takes the name of an instance", .{}); const config = ctx.config() catch return .environment; const instance = config.find(words[0]) orelse return ctx.usage("no instance named '{s}'; `zfj instances` lists them", .{words[0]}); config.default = instance.name; ctx.saveConfig() catch return .environment; try ctx.stdout.print("{s} is the default instance.\n", .{instance.name}); return .ok; } fn wantsHelp(words: []const []const u8) bool { for (words) |word| if (std.mem.eql(u8, word, "--help")) return true; return false; } /// A token typed at a prompt with echo off, or all of stdin when that is not /// a terminal. Null when it is empty. fn readToken(ctx: *Context, url: []const u8) !?[]const u8 { const stdin: Io.File = .stdin(); var buffer: [1024]u8 = undefined; var reader = stdin.reader(ctx.io, &buffer); const text = if (try stdin.isTty(ctx.io)) blk: { try ctx.stderr.print("Token for {s} (made under Settings, Applications): ", .{url}); try ctx.stderr.flush(); const echo = Echo.off(stdin); defer echo.restore(stdin); const line = try reader.interface.takeDelimiter('\n') orelse ""; try ctx.stderr.writeByte('\n'); try ctx.stderr.flush(); break :blk try ctx.arena.dupe(u8, line); } else try reader.interface.allocRemaining(ctx.arena, .limited(64 * 1024)); const token = std.mem.trim(u8, text, " \t\r\n"); return if (token.len == 0) null else token; } /// The terminal's echo, turned off while a token is typed: through termios, /// or on Windows through the console's mode. const Echo = struct { saved: if (builtin.os.tag == .windows) ?u32 else ?std.posix.termios, fn off(file: Io.File) Echo { if (builtin.os.tag == .windows) { var mode: u32 = undefined; if (GetConsoleMode(file.handle, &mode) == .FALSE) return .{ .saved = null }; if (SetConsoleMode(file.handle, mode & ~enable_echo_input) == .FALSE) return .{ .saved = null }; return .{ .saved = mode }; } const saved = std.posix.tcgetattr(file.handle) catch return .{ .saved = null }; var quiet = saved; quiet.lflag.ECHO = false; std.posix.tcsetattr(file.handle, .FLUSH, quiet) catch return .{ .saved = null }; return .{ .saved = saved }; } fn restore(echo: Echo, file: Io.File) void { const saved = echo.saved orelse return; if (builtin.os.tag == .windows) { _ = SetConsoleMode(file.handle, saved); return; } std.posix.tcsetattr(file.handle, .FLUSH, saved) catch {}; } // Not in the standard library's Windows bindings. const windows = std.os.windows; const enable_echo_input: u32 = 0x0004; extern "kernel32" fn GetConsoleMode(console: windows.HANDLE, mode: *u32) callconv(.winapi) windows.BOOL; extern "kernel32" fn SetConsoleMode(console: windows.HANDLE, mode: u32) callconv(.winapi) windows.BOOL; };