Something went wrong. Try again.
Sign git commits and tags with an OpenPGP key kept in Bitwarden.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! `bwgpg git-setup`: point git at bwgpg for signing.//!//! It sets, for one repository or with `--global` for every one://!//! | setting | value |//! |---|---|//! | `gpg.format` | `openpgp` |//! | `gpg.program` | bwgpg |//! | `user.signingkey` | the key's fingerprint |//! | `commit.gpgSign` | `true` |//! | `tag.gpgSign` | `true` |//!//! The last two can be left alone with `--no-sign-by-default`.//!//! The key is resolved by the agent before anything is written, which may//! mean asking for the master password. That is the point: a selector that//! matches nothing in the vault is refused here, rather than at the first//! commit. Whatever the selector was, it is the fingerprint that is written,//! so that git names exactly one key however the vault changes.//!//! `gpg.program` is plain `bwgpg` when that is what `PATH` finds, so that an//! upgrade that moves the executable does not strand the setting. Otherwise//! it is the absolute path of this executable.
const std = @import("std");const builtin = @import("builtin");const Allocator = std.mem.Allocator;const Io = std.Io;const Environ = std.process.Environ;const testing = std.testing;
const client = @import("agent/client.zig");const platform = @import("platform.zig");
pub const usage = \\usage: bwgpg git-setup [--global | --repo DIR] [--key SELECTOR] \\ [--no-sign-by-default] [--dry-run] \\ \\Configures git to sign with bwgpg: in the repository containing DIR (by \\default the current directory), or with --global for every repository. \\ \\ --key SELECTOR the key, as gpg -u takes it; by default the \\ config's default_key, or the vault's only key \\ --no-sign-by-default leave commit.gpgSign and tag.gpgSign alone \\ --dry-run say what would be set, and set nothing \\;
pub const Options = struct { global: bool = false, repo: ?[]const u8 = null, key: ?[]const u8 = null, sign_by_default: bool = true, dry_run: bool = false,};
pub const ParseError = error{ UnknownArgument, MissingValue, ConflictingScope };
pub fn parseArgs(args: []const []const u8) ParseError!Options { var o: Options = .{}; var i: usize = 0; while (i < args.len) : (i += 1) { const a = args[i]; const eql = std.mem.eql; if (eql(u8, a, "--global")) { o.global = true; } else if (eql(u8, a, "--repo") or eql(u8, a, "--key")) { i += 1; if (i >= args.len) return error.MissingValue; if (eql(u8, a, "--repo")) o.repo = args[i] else o.key = args[i]; } else if (eql(u8, a, "--no-sign-by-default")) { o.sign_by_default = false; } else if (eql(u8, a, "--dry-run")) { o.dry_run = true; } else { return error.UnknownArgument; } } if (o.global and o.repo != null) return error.ConflictingScope; return o;}
pub const Setting = struct { name: []const u8, value: []const u8,};
/// What to write, in the order it is written.pub fn settings(buf: *[5]Setting, program: []const u8, fingerprint: []const u8, sign_by_default: bool) []const Setting { buf[0] = .{ .name = "gpg.format", .value = "openpgp" }; buf[1] = .{ .name = "gpg.program", .value = program }; buf[2] = .{ .name = "user.signingkey", .value = fingerprint }; if (!sign_by_default) return buf[0..3]; buf[3] = .{ .name = "commit.gpgSign", .value = "true" }; buf[4] = .{ .name = "tag.gpgSign", .value = "true" }; return buf[0..5];}
fn say(io: Io, comptime fmt: []const u8, args: anytype) void { var buf: [1024]u8 = undefined; var w = Io.File.stdout().writer(io, &buf); w.interface.print(fmt, args) catch {}; w.interface.flush() catch {};}
fn complain(io: Io, comptime fmt: []const u8, args: anytype) void { var buf: [1024]u8 = undefined; var w = Io.File.stderr().writer(io, &buf); w.interface.print("bwgpg git-setup: " ++ fmt ++ "\n", args) catch {}; w.interface.flush() catch {};}
/// Runs `git` with `args`, in `repo` when given. Returns its standard output/// on success; reports its standard error and returns null otherwise.fn git(gpa: Allocator, io: Io, repo: ?[]const u8, args: []const []const u8) !?[]u8 { var argv: std.ArrayList([]const u8) = .empty; defer argv.deinit(gpa); try argv.append(gpa, "git"); if (repo) |r| try argv.appendSlice(gpa, &.{ "-C", r }); try argv.appendSlice(gpa, args);
const result = std.process.run(gpa, io, .{ .argv = argv.items }) catch |err| { complain(io, "cannot run git: {t}", .{err}); return null; }; defer gpa.free(result.stderr); const ok = switch (result.term) { .exited => |code| code == 0, else => false, }; if (!ok) { gpa.free(result.stdout); const msg = std.mem.trim(u8, result.stderr, " \t\r\n"); complain(io, "git {s}: {s}", .{ args[0], msg }); return null; } return result.stdout;}
/// The value for `gpg.program`: `bwgpg` if that is what PATH would find,/// else this executable's absolute path.fn programName(gpa: Allocator, io: Io, env: *const Environ.Map) ![]u8 { // Copied out of the sentinel-terminated slice it comes as, so that the // caller frees what it was given at the length it was allocated. const self_z = try std.process.executablePathAlloc(io, gpa); defer gpa.free(self_z); const self = try gpa.dupe(u8, self_z); errdefer gpa.free(self); const name = if (platform.is_windows) "bwgpg.exe" else "bwgpg"; const found = try platform.findProgram(gpa, io, env, name) orelse return self; defer gpa.free(found); const real = Io.Dir.cwd().realPathFileAlloc(io, found, gpa) catch return self; defer gpa.free(real); if (!std.mem.eql(u8, real, self)) return self; gpa.free(self); return gpa.dupe(u8, "bwgpg");}
pub fn run(gpa: Allocator, io: Io, env: *const Environ.Map, args: []const []const u8) !u8 { const o = parseArgs(args) catch |err| { complain(io, "{s}", .{switch (err) { error.UnknownArgument => "unknown argument", error.MissingValue => "--repo and --key take a value", error.ConflictingScope => "--global and --repo are exclusive", }}); var buf: [1024]u8 = undefined; var w = Io.File.stderr().writer(io, &buf); w.interface.writeAll(usage) catch {}; w.interface.flush() catch {}; return 2; };
// A repository scope needs a repository, and git's own answer to where // it is. var top: ?[]u8 = null; defer if (top) |t| gpa.free(t); if (!o.global) { const out = try git(gpa, io, o.repo, &.{ "rev-parse", "--show-toplevel" }) orelse return 1; defer gpa.free(out); top = try gpa.dupe(u8, std.mem.trim(u8, out, " \t\r\n")); }
const res = client.call(gpa, io, env, .{ .op = "describe", .key = o.key }, true) catch |err| { complain(io, "cannot reach the agent: {t}", .{err}); return 1; }; defer res.deinit(); if (!res.value.ok) { complain(io, "{s}", .{res.value.message orelse res.value.@"error" orelse "the agent refused"}); return 1; } const fingerprint = res.value.fingerprint orelse { complain(io, "the agent named no key", .{}); return 1; };
const program = try programName(gpa, io, env); defer gpa.free(program);
var buf: [5]Setting = undefined; const list = settings(&buf, program, fingerprint, o.sign_by_default);
const scope = if (o.global) "--global" else "--local"; if (o.global) { say(io, "{s} git's global config:\n", .{if (o.dry_run) "Would set in" else "Setting in"}); } else { say(io, "{s} {s}:\n", .{ if (o.dry_run) "Would set in" else "Setting in", top.? }); } for (list) |s| { say(io, " {s} = {s}\n", .{ s.name, s.value }); if (o.dry_run) continue; const out = try git(gpa, io, top, &.{ "config", scope, s.name, s.value }) orelse return 1; gpa.free(out); } return 0;}
test "arguments" { const a = try parseArgs(&.{}); try testing.expect(!a.global and a.sign_by_default and !a.dry_run); try testing.expectEqual(@as(?[]const u8, null), a.key);
const b = try parseArgs(&.{ "--global", "--key", "ABCD", "--no-sign-by-default", "--dry-run" }); try testing.expect(b.global and !b.sign_by_default and b.dry_run); try testing.expectEqualStrings("ABCD", b.key.?);
const c = try parseArgs(&.{ "--repo", "/src/thing" }); try testing.expectEqualStrings("/src/thing", c.repo.?);
try testing.expectError(error.MissingValue, parseArgs(&.{"--key"})); try testing.expectError(error.UnknownArgument, parseArgs(&.{"--bogus"})); try testing.expectError(error.ConflictingScope, parseArgs(&.{ "--global", "--repo", "." }));}
test "settings, with and without signing by default" { var buf: [5]Setting = undefined; const all = settings(&buf, "bwgpg", "FPR", true); try testing.expectEqual(@as(usize, 5), all.len); try testing.expectEqualStrings("gpg.program", all[1].name); try testing.expectEqualStrings("bwgpg", all[1].value); try testing.expectEqualStrings("FPR", all[2].value); try testing.expectEqualStrings("tag.gpgSign", all[4].name);
const some = settings(&buf, "bwgpg", "FPR", false); try testing.expectEqual(@as(usize, 3), some.len);}