From 7f3baf5628d729c1d6005f728e36cf1e685c8552 Mon Sep 17 00:00:00 2001 From: Borja LoFe Date: Thu, 26 Nov 2026 13:02:47 +0100 Subject: [PATCH] fix(push)!: publish the active branch to its configured upstream Resolve the push destination from the branch's own git configuration (branch..remote and branch..merge) and publish only that branch with an explicit refspec, instead of always running `git push origin HEAD`. The remote name and the remote branch name are never assumed; the push never forces and never changes git config. Skip with a clear warning, inventing no destination, on a detached HEAD, a branch with no configured upstream, a local tracking ref (remote=.), or a missing remote. The local commit is always preserved. Replace pushToOrigin with pushCurrentBranch; the success message is now `Committed and pushed to /: `. Add hermetic tests (local bare remotes, no network) and update README and CHANGELOG. BREAKING CHANGE: a branch with no configured upstream is no longer pushed to a remote named `origin`; it now resolves with a warning and a local commit. Configure an upstream (git push -u, or branch..merge) to publish. --- CHANGELOG.md | 13 ++++++ README.md | 54 ++++++++++++++++------ src/git-commit-action.ts | 6 +-- src/lib/git-push.ts | 97 ++++++++++++++++++++++++++++++++++++---- test/git-commit.test.ts | 93 +++++++++++++++++++++++++++++++++----- 5 files changed, 227 insertions(+), 36 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9dedf8f..c98bde3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Changed + +- `gitCommit` now publishes the active branch to the upstream configured for + that branch (`branch..remote` and `branch..merge`) instead of + always running `git push origin HEAD`. The remote name and the remote branch + name are read from git configuration, never assumed, and the branch is pushed + with an explicit single-ref refspec so no other references are published. The + push is skipped with a clear warning, and no destination is invented, on a + detached HEAD, a branch with no configured upstream, a local tracking ref + (`remote = .`), or a missing remote; the local commit is always preserved. + This stops the action from pushing to a wrong or invented `origin` when the + branch tracks a differently named remote or remote branch. + ## [0.1.1] - 2026-11-24 ### Security diff --git a/README.md b/README.md index 3188492..18f2db2 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # plop-pack-git-commit -PlopJS action pack that stages changes, creates a git commit, and pushes to `origin`. +PlopJS action pack that stages changes, creates a git commit, and publishes the active branch to its configured upstream. Inspired by [plop-pack-git-init](https://github.com/crutchcorn/plop-pack-git-init), but focused on committing existing or generated files in an already initialized repository. @@ -15,9 +15,9 @@ Inspired by [plop-pack-git-init](https://github.com/crutchcorn/plop-pack-git-ini ## Scope -**Includes:** Plop action `gitCommit` (stage specific files or `all`, commit, push `origin HEAD`), Zod schema export, CI + security release automation. +**Includes:** Plop action `gitCommit` (stage specific files or `all`, commit, publish the active branch to its configured upstream), Zod schema export, CI + security release automation. -**Does not include:** configurable remote/branch names today; fail-hard push; hosting-specific remotes (`forgejo` / `github` as remote names). +**Does not include:** fail-hard push; automatic upstream creation (the action never runs `push -u` or invents a destination); force push. ## How to run it @@ -95,14 +95,35 @@ Provide either `files` or `all: true`. They are mutually exclusive. ## Push behavior -After a successful commit, the action always runs: +After a successful commit, the action publishes only the active branch to the +upstream destination configured for that branch. It reads the destination from +git itself: ```bash -git push origin HEAD +remote=$(git config --get branch..remote) +merge=$(git config --get branch..merge) # e.g. refs/heads/ +git push "$remote" "refs/heads/:$merge" ``` -- If there was nothing to commit (`skipEmpty`), push is skipped. -- If `origin` is missing or push fails, the action resolves with a warning instead of failing the generator. The commit remains local. +The remote name and the remote branch name are never assumed: a branch that +tracks `upstream`, `forgejo`, or `github`, or whose remote branch has a +different name, is published to exactly that destination. The explicit +single-ref refspec means no other references are pushed regardless of your +`push.default`. The action never forces and never changes your git +configuration. + +The push is skipped with a clear warning, and no destination is invented, when: + +- there was nothing to commit (`skipEmpty`); +- `HEAD` is detached (no branch to publish); +- the active branch has no configured upstream (`branch..remote` / + `branch..merge`); +- the branch tracks a local ref (`remote = .`); +- the configured remote does not exist. + +If the push itself fails (network, rejection), the action resolves with a +warning instead of failing the generator. In every skip or failure case the +local commit is preserved. ## Schema export @@ -120,13 +141,18 @@ const result = gitCommitConfigSchema.safeParse({ - `git` available in `PATH` - Git user identity configured (`user.name`, `user.email`) -- Remote `origin` configured when you expect push to succeed +- The active branch has an upstream configured (`git push -u ` once, or `git branch --set-upstream-to`) when you expect push to succeed ## Decisions -**Why always `git push origin HEAD`?** +**Why publish to the configured upstream instead of `git push origin HEAD`?** -Keeps the action tiny and predictable for the common case (one remote named `origin`). Homelab clones that use remotes `forgejo` / `github` instead of `origin` will get a warning and a local commit — documented limitation, not a silent success. +The branch already records where it should go (`branch..remote` and +`branch..merge`). Honoring it works for clones whose remote is +`forgejo` / `github` or whose remote branch has a different name, and it avoids +pushing to a wrong or invented `origin/` destination. A branch with +no upstream gets a warning and a local commit, not a silent push to a guessed +remote. **Why `skipEmpty` default `true`?** @@ -140,7 +166,9 @@ Commit already happened. Aborting the generator after a network blip strands the ## Trade-offs and limitations -Hardcoded `origin` vs multi-remote homelab naming. Soft push failures vs strict CI. Package optimises interactive generators, not gatekeeping pipelines. +The branch must have an upstream configured for the push to run; the action +never creates one. Soft push failures vs strict CI. Package optimises +interactive generators, not gatekeeping pipelines. ## Evidence of quality @@ -157,9 +185,9 @@ Security-release automation (Dependabot → patch bump → changelog → publish ## Next steps -1. Optional `remote` / `ref` config for non-`origin` setups. +1. Optional explicit `remote` / `ref` config to override the branch upstream. 2. Optional `failOnPushError` for CI-strict consumers. -3. Document a vault Plop example that matches remotes `forgejo`/`github`. +3. Optional opt-in to create the upstream (`push -u`) when none is configured. ## Development diff --git a/src/git-commit-action.ts b/src/git-commit-action.ts index 9311290..21a6631 100644 --- a/src/git-commit-action.ts +++ b/src/git-commit-action.ts @@ -1,6 +1,6 @@ import { access } from "node:fs/promises"; import path from "node:path"; -import { pushToOrigin } from "./lib/git-push.js"; +import { pushCurrentBranch } from "./lib/git-push.js"; import { runGit } from "./lib/run-git.js"; import { type GitCommitActionConfig, gitCommitConfigSchema } from "./schemas/git-commit-config.js"; @@ -110,10 +110,10 @@ export async function gitCommitAction( await runGit(["commit", "-m", message], { cwd: repoPath, verbose }); - const pushResult = await pushToOrigin(repoPath, verbose); + const pushResult = await pushCurrentBranch(repoPath, verbose); if (pushResult.ok) { - return `Committed and pushed to origin: ${message}`; + return `Committed and pushed to ${pushResult.remote}/${pushResult.remoteBranch}: ${message}`; } if (verbose) { diff --git a/src/lib/git-push.ts b/src/lib/git-push.ts index 893bb43..8bd9452 100644 --- a/src/lib/git-push.ts +++ b/src/lib/git-push.ts @@ -1,27 +1,108 @@ import { runGit } from "./run-git.js"; -export type PushResult = { ok: true } | { ok: false; warning: string }; +export type PushResult = + | { ok: true; remote: string; remoteBranch: string } + | { ok: false; warning: string }; -async function hasOriginRemote(repoPath: string, verbose: boolean): Promise { +/** + * Current branch name, or null when HEAD is detached. + */ +async function currentBranch(repoPath: string, verbose: boolean): Promise { try { - await runGit(["remote", "get-url", "origin"], { cwd: repoPath, verbose }); + const { stdout } = await runGit(["symbolic-ref", "--quiet", "--short", "HEAD"], { + cwd: repoPath, + verbose, + }); + const name = stdout.trim(); + return name.length > 0 ? name : null; + } catch { + return null; + } +} + +/** + * Value of a git config key, or null when it is unset (git exits non-zero). + */ +async function gitConfigGet( + repoPath: string, + key: string, + verbose: boolean, +): Promise { + try { + const { stdout } = await runGit(["config", "--get", key], { cwd: repoPath, verbose }); + const value = stdout.trim(); + return value.length > 0 ? value : null; + } catch { + return null; + } +} + +async function remoteExists(repoPath: string, remote: string, verbose: boolean): Promise { + try { + await runGit(["remote", "get-url", remote], { cwd: repoPath, verbose }); return true; } catch { return false; } } -export async function pushToOrigin(repoPath: string, verbose = false): Promise { - if (!(await hasOriginRemote(repoPath, verbose))) { +function shortRemoteBranch(mergeRef: string): string { + const prefix = "refs/heads/"; + return mergeRef.startsWith(prefix) ? mergeRef.slice(prefix.length) : mergeRef; +} + +/** + * Publish only the active branch to its configured upstream destination. + * + * The destination is resolved from the branch's own git configuration + * (`branch..remote` and `branch..merge`); the remote name and the + * remote branch name are never assumed. The branch is published with an + * explicit single-ref refspec, so no other references are pushed regardless of + * `push.default`. The push never forces and never changes git configuration. + * + * On a detached HEAD, a missing upstream, a local-only tracking ref, or a + * missing remote, the push is skipped with a clear warning and no destination + * is invented. The local commit is always preserved. + */ +export async function pushCurrentBranch(repoPath: string, verbose = false): Promise { + const branch = await currentBranch(repoPath, verbose); + if (branch === null) { + return { + ok: false, + warning: "Committed; push skipped: HEAD is detached, no branch to publish", + }; + } + + const remote = await gitConfigGet(repoPath, `branch.${branch}.remote`, verbose); + const mergeRef = await gitConfigGet(repoPath, `branch.${branch}.merge`, verbose); + + if (remote === null || mergeRef === null) { + return { + ok: false, + warning: `Committed; push skipped: no upstream configured for branch ${branch}`, + }; + } + + if (remote === ".") { + return { + ok: false, + warning: `Committed; push skipped: branch ${branch} tracks a local ref, not a remote`, + }; + } + + if (!(await remoteExists(repoPath, remote, verbose))) { return { ok: false, - warning: "Committed; push skipped: remote origin is not configured", + warning: `Committed; push skipped: configured remote ${remote} for branch ${branch} does not exist`, }; } try { - await runGit(["push", "origin", "HEAD"], { cwd: repoPath, verbose }); - return { ok: true }; + await runGit(["push", remote, `refs/heads/${branch}:${mergeRef}`], { + cwd: repoPath, + verbose, + }); + return { ok: true, remote, remoteBranch: shortRemoteBranch(mergeRef) }; } catch (error) { const message = error instanceof Error ? error.message : String(error); return { diff --git a/test/git-commit.test.ts b/test/git-commit.test.ts index 14ce608..050b090 100644 --- a/test/git-commit.test.ts +++ b/test/git-commit.test.ts @@ -172,11 +172,22 @@ describe("gitCommitAction", () => { ).rejects.toThrow("Invalid gitCommit config"); }); - it("pushes to origin after a successful commit", async () => { + async function setUpstream( + repoPath: string, + branch: string, + remote: string, + mergeRef: string, + ): Promise { + await runGit(["config", `branch.${branch}.remote`, remote], { cwd: repoPath }); + await runGit(["config", `branch.${branch}.merge`, mergeRef], { cwd: repoPath }); + } + + it("publishes the active branch to its configured upstream, honoring a non-origin remote and a different remote branch name", async () => { const bareDir = await createBareRemote(); const repoPath = await createTempDir("plop-git-commit-repo-"); - await initGitRepo(repoPath); - await runGit(["remote", "add", "origin", bareDir], { cwd: repoPath }); + await initGitRepo(repoPath, "work"); + await runGit(["remote", "add", "upstream", bareDir], { cwd: repoPath }); + await setUpstream(repoPath, "work", "upstream", "refs/heads/published"); await writeFile(path.join(repoPath, "file.txt"), "content\n"); @@ -189,14 +200,24 @@ describe("gitCommitAction", () => { }, ); - expect(message).toContain("Committed and pushed to origin"); - const bareHead = await runGit(["show-ref", "--heads", "main"], { cwd: bareDir }); - expect(bareHead.stdout.trim()).not.toBe(""); + expect(message).toContain("Committed and pushed to upstream/published"); + + const published = await runGit(["log", "-1", "--pretty=format:%s", "published"], { + cwd: bareDir, + }); + expect(published.stdout.trim()).toBe("first commit"); + + await expect( + runGit(["rev-parse", "--verify", "refs/heads/work"], { cwd: bareDir }), + ).rejects.toThrow(); }); - it("warns but does not throw when origin is missing", async () => { + it("does not fall back to origin when the active branch has no configured upstream", async () => { + const bareDir = await createBareRemote(); const repoPath = await createTempDir("plop-git-commit-repo-"); await initGitRepo(repoPath); + await runGit(["remote", "add", "origin", bareDir], { cwd: repoPath }); + await writeFile(path.join(repoPath, "file.txt"), "content\n"); const message = await gitCommitAction( @@ -208,15 +229,63 @@ describe("gitCommitAction", () => { }, ); - expect(message).toContain("Committed; push skipped"); - const fileContents = await readFile(path.join(repoPath, "file.txt"), "utf8"); - expect(fileContents).toBe("content\n"); + expect(message).toContain("push skipped: no upstream configured"); + await expect( + runGit(["rev-parse", "--verify", "refs/heads/main"], { cwd: bareDir }), + ).rejects.toThrow(); + }); + + it("skips the push on a detached HEAD without inventing a destination", async () => { + const repoPath = await createTempDir("plop-git-commit-repo-"); + await initGitRepo(repoPath); + await writeFile(path.join(repoPath, "first.txt"), "one\n"); + await runGit(["add", "-A"], { cwd: repoPath }); + await runGit(["commit", "-m", "base"], { cwd: repoPath }); + const head = await runGit(["rev-parse", "HEAD"], { cwd: repoPath }); + await runGit(["checkout", head.stdout.trim()], { cwd: repoPath }); + + await writeFile(path.join(repoPath, "second.txt"), "two\n"); + + const message = await gitCommitAction( + {}, + { + path: repoPath, + message: "detached commit", + files: "second.txt", + }, + ); + + expect(message).toContain("push skipped: HEAD is detached"); + const log = await runGit(["log", "-1", "--pretty=format:%s"], { cwd: repoPath }); + expect(log.stdout.trim()).toBe("detached commit"); + }); + + it("skips the push when the configured remote does not exist", async () => { + const repoPath = await createTempDir("plop-git-commit-repo-"); + await initGitRepo(repoPath); + await setUpstream(repoPath, "main", "ghost", "refs/heads/main"); + await writeFile(path.join(repoPath, "file.txt"), "content\n"); + + const message = await gitCommitAction( + {}, + { + path: repoPath, + message: "missing remote", + files: "file.txt", + }, + ); + + expect(message).toContain("configured remote ghost"); + expect(message).toContain("does not exist"); + const log = await runGit(["log", "-1", "--pretty=format:%s"], { cwd: repoPath }); + expect(log.stdout.trim()).toBe("missing remote"); }); - it("warns but does not throw when push fails", async () => { + it("warns but does not throw when the push to the configured upstream fails", async () => { const repoPath = await createTempDir("plop-git-commit-repo-"); await initGitRepo(repoPath); - await runGit(["remote", "add", "origin", "/definitely/not/a/git/remote"], { cwd: repoPath }); + await runGit(["remote", "add", "backup", "/definitely/not/a/git/remote"], { cwd: repoPath }); + await setUpstream(repoPath, "main", "backup", "refs/heads/main"); await writeFile(path.join(repoPath, "file.txt"), "content\n"); const message = await gitCommitAction(