Skip to content

Commit 437a798

Browse files
committed
fix: drop the OpenPGP UID comment from the GPG signer author name
parseSignerUid() now strips the parenthesised OpenPGP user-ID comment that ends the name part of a signer UID, so "Nate Corcoran (2023 PC) <email>" yields the author name "Nate Corcoran" (and "Nate Corcoran <CLDMV>" with company: "CLDMV"). Nested and backslash-escaped parentheses in the comment are handled; parentheses elsewhere in the name are kept, and a UID that is only a comment keeps its raw name. parseSignerUid is exported for unit tests. Fixes #61
1 parent 0de081f commit 437a798

6 files changed

Lines changed: 265 additions & 7 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ Common CLI options:
5555
- `--sample-output`
5656
- `--force-author-update`
5757
- `--force-last-modified-author-update`
58-
- `--use-gpg-signer-author`
58+
- `--use-gpg-signer-author` (signer UID name, with the OpenPGP UID comment dropped)
5959
- `--cwd <path>`
6060
- `--input <path>`
6161
- `--include-folder <path>` (repeatable)
@@ -105,7 +105,7 @@ Important options:
105105
- `company?: string` - appends to `@Author` as `Name <Company>`
106106
- `forceAuthorUpdate?: boolean` - force update `@Author`/`@Email` to detected or overridden current values
107107
- `forceLastModifiedAuthorUpdate?: boolean` - force update `@Last modified by` to detected or overridden current values. Without this, an existing header's recorded `@Last modified by` identity is preserved and does not by itself trigger an update just because the running author differs (e.g. a different `git config user.name` than whoever last touched the file)
108-
- `useGpgSignerAuthor?: boolean` - use signed-commit UID (`%GS`) for detected `@Author` (includes signer comment when present)
108+
- `useGpgSignerAuthor?: boolean` - use the last commit's signer UID (`%GS`) for the detected `@Author` name. The OpenPGP UID comment is dropped, so `Nate Corcoran (2023 PC) <[email protected]>` becomes `Nate Corcoran` (with `company: "CLDMV"`: `Nate Corcoran <CLDMV>`). An unsigned commit falls back to `git config user.name`, then the last commit's author
109109
- `companyName?: string` (default: `Catalyzed Motivation Inc.`)
110110
- `copyrightStartYear?: number` (default: current year)
111111

‎src/utils/git.mjs‎

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,20 +37,67 @@ export async function runGit(cwd, args) {
3737
}
3838
}
3939

40+
/**
41+
* Checks whether the character at an index is escaped by an odd run of preceding backslashes.
42+
* @param {string} text - Source text.
43+
* @param {number} index - Index of the character to check.
44+
* @returns {boolean} True when the character is backslash-escaped.
45+
*/
46+
function isEscaped(text, index) {
47+
let backslashes = 0;
48+
for (let cursor = index - 1; cursor >= 0 && text[cursor] === "\\"; cursor--) {
49+
backslashes++;
50+
}
51+
return backslashes % 2 === 1;
52+
}
53+
54+
/**
55+
* Removes a trailing OpenPGP user-ID comment from the name part of a UID.
56+
* A UID has the form `Name (Comment) <email>`; the comment is the parenthesised
57+
* group that ends the name part. Nested parentheses are balanced and
58+
* backslash-escaped parentheses (RFC 2822 quoted-pair) are treated as literal
59+
* text. Parentheses anywhere else in the name are kept.
60+
* @param {string} namePart - UID text before the `<email>` (or the whole UID when there is no email).
61+
* @returns {string} Name with the trailing comment removed, or the input unchanged when there is none.
62+
*/
63+
function stripUidComment(namePart) {
64+
const text = namePart.trim();
65+
if (!text.endsWith(")") || isEscaped(text, text.length - 1)) {
66+
return text;
67+
}
68+
69+
let depth = 0;
70+
for (let index = text.length - 1; index >= 0; index--) {
71+
const character = text[index];
72+
if ((character !== "(" && character !== ")") || isEscaped(text, index)) {
73+
continue;
74+
}
75+
depth += character === ")" ? 1 : -1;
76+
if (depth === 0) {
77+
return text.slice(0, index).trim();
78+
}
79+
}
80+
81+
return text;
82+
}
83+
4084
/**
4185
* Parses a signer UID string into author name and optional email.
86+
* The OpenPGP UID comment (`Name (Comment) <email>`) is dropped from the name;
87+
* when the UID is only a comment, the raw name is kept.
4288
* @param {string} signerUid - Raw signer UID (for example: "Name (Comment) <[email protected]>").
4389
* @returns {{authorName: string | null, authorEmail: string | null}} Parsed signer identity.
4490
*/
45-
function parseSignerUid(signerUid) {
91+
export function parseSignerUid(signerUid) {
4692
const trimmed = signerUid.trim();
4793
if (trimmed.length === 0) {
4894
return { authorName: null, authorEmail: null };
4995
}
5096

5197
const emailMatch = trimmed.match(/<([^>\n]+)>\s*$/);
5298
const authorEmail = emailMatch?.[1]?.trim() || null;
53-
const authorName = (emailMatch ? trimmed.slice(0, emailMatch.index) : trimmed).trim() || null;
99+
const rawName = (emailMatch ? trimmed.slice(0, emailMatch.index) : trimmed).trim();
100+
const authorName = stripUidComment(rawName) || rawName || null;
54101

55102
return { authorName, authorEmail };
56103
}

‎tests/git-edge.test.vitest.mjs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ describe("git edge parsing", () => {
152152

153153
const { detectGitAuthor } = await import("../src/utils/git.mjs");
154154
const author = await detectGitAuthor(workspace, { useGpgSignerAuthor: true });
155-
expect(author.authorName).toBe("Signer Name (Laptop)");
155+
expect(author.authorName).toBe("Signer Name");
156156
expect(author.authorEmail).toBe("[email protected]");
157157
} finally {
158158
process.env.PATH = previousPath;
@@ -212,7 +212,7 @@ describe("git edge parsing", () => {
212212

213213
const { detectGitAuthor } = await import("../src/utils/git.mjs");
214214
const author = await detectGitAuthor(workspace, { useGpgSignerAuthor: true });
215-
expect(author.authorName).toBe("Signer Name (Desktop)");
215+
expect(author.authorName).toBe("Signer Name");
216216
expect(author.authorEmail).toBe("[email protected]");
217217
} finally {
218218
process.env.PATH = previousPath;
Lines changed: 200 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,200 @@
1+
/**
2+
* @Project: @cldmv/fix-headers
3+
* @Filename: /tests/gpg-signer-uid.test.vitest.mjs
4+
* @Date: 2026-09-27T23:43:47-07:00 (1790577827)
5+
* @Author: Nate Corcoran <CLDMV>
6+
* @Email: <[email protected]>
7+
* -----
8+
* @Last modified by: Nate Corcoran <CLDMV> ([email protected])
9+
* @Last modified time: 2026-09-27T23:43:47-07:00 (1790577827)
10+
* -----
11+
* @Copyright: Copyright (c) 2026-2026 Catalyzed Motivation Inc. All rights reserved.
12+
*/
13+
14+
import { execFile } from "node:child_process";
15+
import { chmod, writeFile } from "node:fs/promises";
16+
import { promisify } from "node:util";
17+
import { join } from "node:path";
18+
import { describe, expect, it } from "vitest";
19+
import { fixHeaders } from "../src/fix-header.mjs";
20+
import { detectGitAuthor, parseSignerUid } from "../src/utils/git.mjs";
21+
import { cleanupWorkspace, createWorkspace, writeWorkspaceFile } from "./helpers/workspace.mjs";
22+
23+
const execFileAsync = promisify(execFile);
24+
25+
/**
26+
* Builds a bash git shim that answers the listed argument patterns and delegates everything else to the real git.
27+
* @param {Array<{match: string, output: string | null}>} rules - `$*` substring to match and the line to print (null prints nothing).
28+
* @returns {string} Shim script source.
29+
*/
30+
function buildGitShim(rules) {
31+
const branches = rules
32+
.map(({ match, output }) => {
33+
const body = output === null ? "" : ` printf '%s\\n' ${JSON.stringify(output)}\n`;
34+
return `if [[ "$*" == *${JSON.stringify(match)}* ]]; then\n${body} exit 0\nfi\n`;
35+
})
36+
.join("");
37+
return `#!/usr/bin/env bash\nset -e\n${branches}exec /usr/bin/git "$@"\n`;
38+
}
39+
40+
/**
41+
* Creates a committed git workspace and puts a git shim first on PATH.
42+
* @param {string} name - Workspace name suffix.
43+
* @param {Array<{match: string, output: string | null}>} rules - Shim rules passed to {@link buildGitShim}.
44+
* @returns {Promise<{workspace: string, restore: () => Promise<void>}>} Workspace path and a restore callback.
45+
*/
46+
async function createShimmedWorkspace(name, rules) {
47+
const workspace = await createWorkspace(name);
48+
const previousPath = process.env.PATH;
49+
await writeWorkspaceFile(join(workspace, "package.json"), JSON.stringify({ name }, null, 2));
50+
await writeWorkspaceFile(join(workspace, "src", "main.mjs"), "export const x = true;\n");
51+
await execFileAsync("git", ["init"], { cwd: workspace });
52+
await execFileAsync("git", ["config", "user.name", "Configured Name"], { cwd: workspace });
53+
await execFileAsync("git", ["config", "user.email", "[email protected]"], { cwd: workspace });
54+
await execFileAsync("git", ["add", "."], { cwd: workspace });
55+
await execFileAsync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "init"], { cwd: workspace });
56+
57+
const shimPath = join(workspace, "git");
58+
await writeFile(shimPath, buildGitShim(rules));
59+
await chmod(shimPath, 0o755);
60+
process.env.PATH = `${workspace}:${previousPath}`;
61+
62+
return {
63+
workspace,
64+
restore: async () => {
65+
process.env.PATH = previousPath;
66+
await cleanupWorkspace(workspace);
67+
}
68+
};
69+
}
70+
71+
describe("parseSignerUid", () => {
72+
it("drops the OpenPGP UID comment before the email", () => {
73+
expect(parseSignerUid("Nate Corcoran (2023 PC) <[email protected]>")).toEqual({
74+
authorName: "Nate Corcoran",
75+
authorEmail: "[email protected]"
76+
});
77+
});
78+
79+
it("parses a UID without a comment unchanged", () => {
80+
expect(parseSignerUid("Nate Corcoran <[email protected]>")).toEqual({
81+
authorName: "Nate Corcoran",
82+
authorEmail: "[email protected]"
83+
});
84+
});
85+
86+
it("parses an email-only UID with no name", () => {
87+
expect(parseSignerUid("<[email protected]>")).toEqual({ authorName: null, authorEmail: "[email protected]" });
88+
});
89+
90+
it("parses a name-only UID", () => {
91+
expect(parseSignerUid("Signer Name")).toEqual({ authorName: "Signer Name", authorEmail: null });
92+
});
93+
94+
it("drops a trailing comment from a name-only UID", () => {
95+
expect(parseSignerUid("Signer Name (Desktop)")).toEqual({ authorName: "Signer Name", authorEmail: null });
96+
});
97+
98+
it("keeps parentheses that sit inside the name rather than at its end", () => {
99+
expect(parseSignerUid("Jane (JJ) Doe <[email protected]>")).toEqual({ authorName: "Jane (JJ) Doe", authorEmail: "[email protected]" });
100+
expect(parseSignerUid("Jane (JJ) Doe (Work) <[email protected]>").authorName).toBe("Jane (JJ) Doe");
101+
});
102+
103+
it("drops a comment that contains nested parentheses", () => {
104+
expect(parseSignerUid("Signer Name (Home (old box)) <[email protected]>").authorName).toBe("Signer Name");
105+
});
106+
107+
it("only drops the last of several trailing comments", () => {
108+
expect(parseSignerUid("Signer Name (A) (B) <[email protected]>").authorName).toBe("Signer Name (A)");
109+
});
110+
111+
it("treats backslash-escaped parentheses as literal comment text", () => {
112+
expect(parseSignerUid(String.raw`Signer Name (a \) b \( c) <[email protected]>`).authorName).toBe("Signer Name");
113+
expect(parseSignerUid(String.raw`Signer Name (a \\) <[email protected]>`).authorName).toBe("Signer Name");
114+
});
115+
116+
it("keeps a name ending in an escaped parenthesis", () => {
117+
expect(parseSignerUid(String.raw`Signer Name \)`).authorName).toBe(String.raw`Signer Name \)`);
118+
});
119+
120+
it("keeps a name whose trailing parenthesis is unbalanced", () => {
121+
expect(parseSignerUid("Signer Name) <[email protected]>").authorName).toBe("Signer Name)");
122+
});
123+
124+
it("falls back to the raw name when the UID is only a comment", () => {
125+
expect(parseSignerUid("(Laptop) <[email protected]>")).toEqual({ authorName: "(Laptop)", authorEmail: "[email protected]" });
126+
expect(parseSignerUid("(Laptop)")).toEqual({ authorName: "(Laptop)", authorEmail: null });
127+
});
128+
129+
it("returns nulls for an empty or whitespace-only UID", () => {
130+
expect(parseSignerUid("")).toEqual({ authorName: null, authorEmail: null });
131+
expect(parseSignerUid(" ")).toEqual({ authorName: null, authorEmail: null });
132+
});
133+
});
134+
135+
describe("detectGitAuthor with useGpgSignerAuthor", () => {
136+
it("uses the signer name without its UID comment", async () => {
137+
const { workspace, restore } = await createShimmedWorkspace("gpg-uid-comment", [
138+
{ match: "log -1 --format=%GS", output: "Nate Corcoran (2023 PC) <[email protected]>" }
139+
]);
140+
try {
141+
const author = await detectGitAuthor(workspace, { useGpgSignerAuthor: true });
142+
expect(author.authorName).toBe("Nate Corcoran");
143+
expect(author.authorEmail).toBe("[email protected]");
144+
} finally {
145+
await restore();
146+
}
147+
});
148+
149+
it("falls back to user.name when the last commit is unsigned", async () => {
150+
const { workspace, restore } = await createShimmedWorkspace("gpg-uid-unsigned", [{ match: "log -1 --format=%GS", output: null }]);
151+
try {
152+
const author = await detectGitAuthor(workspace, { useGpgSignerAuthor: true });
153+
expect(author.authorName).toBe("Configured Name");
154+
expect(author.authorEmail).toBe("[email protected]");
155+
} finally {
156+
await restore();
157+
}
158+
});
159+
160+
it("falls back to the log author when the commit is unsigned and user.name is unset", async () => {
161+
const { workspace, restore } = await createShimmedWorkspace("gpg-uid-unsigned-no-config", [
162+
{ match: "config --get user.name", output: null },
163+
{ match: "config --get user.email", output: null },
164+
{ match: "log -1 --format=%GS", output: null },
165+
{ match: "log -1 --format=%an|%ae", output: "Log Author|[email protected]" }
166+
]);
167+
try {
168+
const author = await detectGitAuthor(workspace, { useGpgSignerAuthor: true });
169+
expect(author.authorName).toBe("Log Author");
170+
expect(author.authorEmail).toBe("[email protected]");
171+
} finally {
172+
await restore();
173+
}
174+
});
175+
});
176+
177+
describe("fixHeaders with useGpgSignerAuthor and company", () => {
178+
it("writes the signer name without its UID comment and with the company suffix", async () => {
179+
const { workspace, restore } = await createShimmedWorkspace("gpg-uid-fix-headers", [
180+
{ match: "log -1 --format=%GS", output: "Nate Corcoran (2023 PC) <[email protected]>" }
181+
]);
182+
try {
183+
const result = await fixHeaders({
184+
cwd: workspace,
185+
input: "src/main.mjs",
186+
useGpgSignerAuthor: true,
187+
company: "CLDMV",
188+
sampleOutput: true,
189+
dryRun: true
190+
});
191+
192+
expect(result.filesScanned).toBe(1);
193+
const header = result.changes[0]?.sample?.newValue;
194+
expect(header).toContain("@Author: Nate Corcoran <CLDMV>");
195+
expect(header).not.toContain("2023 PC");
196+
} finally {
197+
await restore();
198+
}
199+
});
200+
});

‎tests/project-metadata-edge.test.vitest.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,7 @@ describe("project metadata edge branches", () => {
262262
useGpgSignerAuthor: true
263263
});
264264

265-
expect(metadata.authorName).toBe("Signer Name (2026 Laptop)");
265+
expect(metadata.authorName).toBe("Signer Name");
266266
expect(metadata.authorEmail).toBe("[email protected]");
267267
} finally {
268268
process.env.PATH = previousPath;

‎types/src/utils/git.d.mts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,17 @@
2121
* @returns {Promise<string | null>} Trimmed stdout or null on failure.
2222
*/
2323
export declare function runGit(cwd: string, args: string[]): Promise<string | null>;
24+
/**
25+
* Parses a signer UID string into author name and optional email.
26+
* The OpenPGP UID comment (`Name (Comment) <email>`) is dropped from the name;
27+
* when the UID is only a comment, the raw name is kept.
28+
* @param {string} signerUid - Raw signer UID (for example: "Name (Comment) <[email protected]>").
29+
* @returns {{authorName: string | null, authorEmail: string | null}} Parsed signer identity.
30+
*/
31+
export declare function parseSignerUid(signerUid: string): {
32+
authorName: string | null;
33+
authorEmail: string | null;
34+
};
2435
/**
2536
* Detects git author name and email from config or commit history.
2637
* @param {string} cwd - Project directory.

0 commit comments

Comments
 (0)