-
Notifications
You must be signed in to change notification settings - Fork 30
fix(code): pre-configure worktree with GitHub noreply email #2342
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lost-particles
wants to merge
1
commit into
PostHog:main
Choose a base branch
from
lost-particles:fix/preconfigure-noreply-identity-2156
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+316
−0
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
171 changes: 171 additions & 0 deletions
171
apps/code/src/main/services/workspace/githubIdentity.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,171 @@ | ||
| import { execFile } from "node:child_process"; | ||
| import * as fs from "node:fs/promises"; | ||
| import * as os from "node:os"; | ||
| import * as path from "node:path"; | ||
| import { promisify } from "node:util"; | ||
| import { makeLoggerMock } from "@test/loggerMock"; | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; | ||
|
|
||
| vi.mock("../../utils/logger.js", () => makeLoggerMock()); | ||
|
|
||
| import { | ||
| applyWorktreeIdentity, | ||
| computeNoreplyIdentity, | ||
| fetchGitHubUserInfo, | ||
| } from "./githubIdentity"; | ||
|
|
||
| const execFileAsync = promisify(execFile); | ||
|
|
||
| describe("computeNoreplyIdentity", () => { | ||
| it("returns noreply identity when GitHub user has email privacy enabled", () => { | ||
| expect( | ||
| computeNoreplyIdentity({ | ||
| id: 12345, | ||
| login: "octocat", | ||
| name: "Octo Cat", | ||
| email: null, | ||
| }), | ||
| ).toEqual({ | ||
| name: "Octo Cat", | ||
| email: "12345+octocat@users.noreply.github.com", | ||
| }); | ||
| }); | ||
|
|
||
| it("falls back to login when name is missing", () => { | ||
| expect( | ||
| computeNoreplyIdentity({ id: 12345, login: "octocat", email: null }), | ||
| ).toEqual({ | ||
| name: "octocat", | ||
| email: "12345+octocat@users.noreply.github.com", | ||
| }); | ||
| }); | ||
|
|
||
| it("returns null when GitHub user has a public email", () => { | ||
| expect( | ||
| computeNoreplyIdentity({ | ||
| id: 12345, | ||
| login: "octocat", | ||
| email: "octo@example.com", | ||
| }), | ||
| ).toBeNull(); | ||
| }); | ||
|
|
||
| it("returns null when id or login is missing", () => { | ||
| expect( | ||
| computeNoreplyIdentity({ | ||
| id: 0, | ||
| login: "octocat", | ||
| email: null, | ||
| }), | ||
| ).toBeNull(); | ||
| expect( | ||
| computeNoreplyIdentity({ | ||
| id: 12345, | ||
| login: "", | ||
| email: null, | ||
| }), | ||
| ).toBeNull(); | ||
| }); | ||
| }); | ||
|
|
||
| describe("fetchGitHubUserInfo", () => { | ||
| it("returns parsed user info when gh api user succeeds", async () => { | ||
| const runGh = vi | ||
| .fn() | ||
| .mockResolvedValue( | ||
| '{"id":12345,"login":"octocat","name":"Octo Cat","email":null}', | ||
| ); | ||
| const result = await fetchGitHubUserInfo({ runGh }); | ||
| expect(result).toEqual({ | ||
| id: 12345, | ||
| login: "octocat", | ||
| name: "Octo Cat", | ||
| email: null, | ||
| }); | ||
| expect(runGh).toHaveBeenCalledWith(["api", "user"]); | ||
| }); | ||
|
|
||
| it("returns null when gh fails (not installed / not authenticated)", async () => { | ||
| const runGh = vi.fn().mockRejectedValue(new Error("gh: command not found")); | ||
| expect(await fetchGitHubUserInfo({ runGh })).toBeNull(); | ||
| }); | ||
|
|
||
| it("returns null when response is malformed JSON", async () => { | ||
| const runGh = vi.fn().mockResolvedValue("not json"); | ||
| expect(await fetchGitHubUserInfo({ runGh })).toBeNull(); | ||
| }); | ||
|
|
||
| it("returns null when required fields are missing", async () => { | ||
| const runGh = vi.fn().mockResolvedValue('{"login":"octocat"}'); | ||
| expect(await fetchGitHubUserInfo({ runGh })).toBeNull(); | ||
| }); | ||
| }); | ||
|
|
||
| describe("applyWorktreeIdentity (integration)", () => { | ||
| let mainRepo: string; | ||
| let worktreePath: string; | ||
|
|
||
| beforeEach(async () => { | ||
| mainRepo = await fs.mkdtemp(path.join(os.tmpdir(), "posthog-id-main-")); | ||
| await execFileAsync("git", ["init", "-q"], { cwd: mainRepo }); | ||
| await execFileAsync( | ||
| "git", | ||
| ["config", "user.email", "private@example.com"], | ||
| { cwd: mainRepo }, | ||
| ); | ||
| await execFileAsync("git", ["config", "user.name", "Real Name"], { | ||
| cwd: mainRepo, | ||
| }); | ||
| await execFileAsync("git", ["commit", "--allow-empty", "-m", "init"], { | ||
| cwd: mainRepo, | ||
| }); | ||
|
|
||
| const worktreeBase = await fs.mkdtemp( | ||
| path.join(os.tmpdir(), "posthog-id-wt-"), | ||
| ); | ||
| worktreePath = path.join(worktreeBase, "wt"); | ||
| await execFileAsync("git", ["worktree", "add", "--detach", worktreePath], { | ||
| cwd: mainRepo, | ||
| }); | ||
| }); | ||
|
|
||
| afterEach(async () => { | ||
| await fs.rm(mainRepo, { recursive: true, force: true }); | ||
| await fs.rm(path.dirname(worktreePath), { recursive: true, force: true }); | ||
| }); | ||
|
|
||
| it("sets user.email and user.name only in the worktree, not the main repo", async () => { | ||
| await applyWorktreeIdentity(worktreePath, { | ||
| name: "Octo Cat", | ||
| email: "12345+octocat@users.noreply.github.com", | ||
| }); | ||
|
|
||
| const { stdout: worktreeEmail } = await execFileAsync( | ||
| "git", | ||
| ["config", "user.email"], | ||
| { cwd: worktreePath }, | ||
| ); | ||
| expect(worktreeEmail.trim()).toBe("12345+octocat@users.noreply.github.com"); | ||
|
|
||
| const { stdout: worktreeName } = await execFileAsync( | ||
| "git", | ||
| ["config", "user.name"], | ||
| { cwd: worktreePath }, | ||
| ); | ||
| expect(worktreeName.trim()).toBe("Octo Cat"); | ||
|
|
||
| // Main repo must retain its original identity. | ||
| const { stdout: mainEmail } = await execFileAsync( | ||
| "git", | ||
| ["config", "--local", "user.email"], | ||
| { cwd: mainRepo }, | ||
| ); | ||
| expect(mainEmail.trim()).toBe("private@example.com"); | ||
| const { stdout: mainName } = await execFileAsync( | ||
| "git", | ||
| ["config", "--local", "user.name"], | ||
| { cwd: mainRepo }, | ||
| ); | ||
| expect(mainName.trim()).toBe("Real Name"); | ||
| }); | ||
| }); | ||
113 changes: 113 additions & 0 deletions
113
apps/code/src/main/services/workspace/githubIdentity.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| import { execFile } from "node:child_process"; | ||
| import { promisify } from "node:util"; | ||
| import { logger } from "../../utils/logger"; | ||
|
|
||
| const log = logger.scope("workspace-github-identity"); | ||
|
|
||
| const execFileAsync = promisify(execFile); | ||
|
|
||
| export interface GitHubUserInfo { | ||
| id: number; | ||
| login: string; | ||
| name?: string | null; | ||
| email?: string | null; | ||
| } | ||
|
|
||
| export interface WorktreeIdentity { | ||
| name: string; | ||
| email: string; | ||
| } | ||
|
|
||
| /** | ||
| * Resolve a `<id>+<login>@users.noreply.github.com` identity for the user, | ||
| * but only when GitHub reports their email as private. When the user has a | ||
| * public email there is no GH007 push rejection to avoid, so we leave the | ||
| * worktree using whatever email the user has configured. | ||
| */ | ||
| export function computeNoreplyIdentity( | ||
| user: GitHubUserInfo, | ||
| ): WorktreeIdentity | null { | ||
| if (!user.id || !user.login) return null; | ||
| if (user.email) return null; | ||
| return { | ||
| name: user.name?.trim() || user.login, | ||
| email: `${user.id}+${user.login}@users.noreply.github.com`, | ||
| }; | ||
| } | ||
|
|
||
| export interface FetchGitHubUserInfoOptions { | ||
| /** Override for tests; defaults to invoking the local `gh` CLI. */ | ||
| runGh?: (args: string[]) => Promise<string>; | ||
| } | ||
|
|
||
| const GH_API_TIMEOUT_MS = 5_000; | ||
|
|
||
| async function defaultRunGh(args: string[]): Promise<string> { | ||
| const { stdout } = await execFileAsync("gh", args, { | ||
| timeout: GH_API_TIMEOUT_MS, | ||
| }); | ||
| return stdout; | ||
| } | ||
|
|
||
| /** | ||
| * Fetch the authenticated GitHub user via the user's `gh` CLI. Returns null | ||
| * if `gh` is not installed, not authenticated, or returns an unexpected | ||
| * shape — pre-configuring the noreply is a best-effort optimization and | ||
| * must not fail workspace creation. | ||
| */ | ||
| export async function fetchGitHubUserInfo( | ||
| options: FetchGitHubUserInfoOptions = {}, | ||
| ): Promise<GitHubUserInfo | null> { | ||
| const runGh = options.runGh ?? defaultRunGh; | ||
| let stdout: string; | ||
| try { | ||
| stdout = await runGh(["api", "user"]); | ||
| } catch (error) { | ||
| log.debug("gh api user failed; skipping noreply pre-configuration", { | ||
| error: error instanceof Error ? error.message : String(error), | ||
| }); | ||
| return null; | ||
| } | ||
| try { | ||
| const parsed = JSON.parse(stdout) as Record<string, unknown>; | ||
| if (typeof parsed.id !== "number" || typeof parsed.login !== "string") { | ||
| return null; | ||
| } | ||
| return { | ||
| id: parsed.id, | ||
| login: parsed.login, | ||
| name: typeof parsed.name === "string" ? parsed.name : null, | ||
| email: typeof parsed.email === "string" ? parsed.email : null, | ||
| }; | ||
| } catch { | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Set `user.name` and `user.email` on a worktree without affecting the main | ||
| * repo. Uses `git config --worktree`, which requires the repo extension | ||
| * `extensions.worktreeConfig` to be enabled — we toggle it here. The flag | ||
| * is purely an opt-in to per-worktree config storage and has no effect on | ||
| * any existing setting. | ||
| */ | ||
| export async function applyWorktreeIdentity( | ||
| worktreePath: string, | ||
| identity: WorktreeIdentity, | ||
| ): Promise<void> { | ||
| await execFileAsync( | ||
| "git", | ||
| ["config", "--local", "extensions.worktreeConfig", "true"], | ||
| { cwd: worktreePath }, | ||
| ); | ||
| await execFileAsync( | ||
| "git", | ||
| ["config", "--worktree", "user.email", identity.email], | ||
| { cwd: worktreePath }, | ||
| ); | ||
| await execFileAsync( | ||
| "git", | ||
| ["config", "--worktree", "user.name", identity.name], | ||
| { cwd: worktreePath }, | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
computeNoreplyIdentityandfetchGitHubUserInfosuites each have four independentit()cases that vary only in input/output — these are a natural fit forit.eachtables. Parameterised tests are the convention in this codebase and keep the intent easier to scan as the number of cases grows.Prompt To Fix With AI
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!