From 0119b8c22e42bf726bd0739e78ba1510d6a90535 Mon Sep 17 00:00:00 2001 From: Yago Borba <140000816+YagoBorba@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:50:49 -0300 Subject: [PATCH] feat: warn before committing directly on main, master or develop Closes #30. In GitFlow those branches receive changes through pull requests. stc commit now warns, suggests starting a branch with stc git start and asks for confirmation (default no). The VS Code commit command shows the same warning with Start a new branch and Commit anyway. @stackcode/core exports getCurrentBranch, isProtectedBranch and DEFAULT_PROTECTED_BRANCHES, tested against a real repository. Messages are available in English, Portuguese and Spanish. --- packages/cli/src/commands/commit.ts | 15 ++++ packages/cli/test/commands/commit.test.ts | 67 +++++++++++++++++ packages/core/src/branches.ts | 40 +++++++++++ packages/core/src/index.ts | 5 ++ packages/core/test/branches.test.ts | 61 ++++++++++++++++ packages/i18n/src/locales/en.json | 7 +- packages/i18n/src/locales/es.json | 7 +- packages/i18n/src/locales/pt.json | 7 +- .../src/commands/CommitCommand.ts | 49 +++++++++++++ .../src/test/__mocks__/core-workflows.ts | 11 +++ .../CommitCommand.integration.test.ts | 71 ++++++++++++++++++- 11 files changed, 336 insertions(+), 4 deletions(-) create mode 100644 packages/core/src/branches.ts create mode 100644 packages/core/test/branches.test.ts diff --git a/packages/cli/src/commands/commit.ts b/packages/cli/src/commands/commit.ts index 4208c63..05c2df9 100644 --- a/packages/cli/src/commands/commit.ts +++ b/packages/cli/src/commands/commit.ts @@ -1,7 +1,9 @@ import type { CommandModule, ArgumentsCamelCase } from "yargs"; import { getCommandOutput, + getCurrentBranch, getErrorMessage, + isProtectedBranch, runCommitWorkflow, } from "@stackcode/core"; import { t } from "@stackcode/i18n"; @@ -30,6 +32,19 @@ export const getCommitCommand = (): CommandModule => ({ return; } + const branch = await getCurrentBranch(process.cwd()); + if (branch && isProtectedBranch(branch)) { + ui.log.warning(t("commit.protected_branch_warning", { branch })); + ui.log.info(t("commit.protected_branch_suggestion", { branch })); + const proceed = await ui.promptForConfirmation( + t("commit.protected_branch_confirm", { branch }), + false, + ); + if (!proceed) { + return; + } + } + const answers = await ui.promptForCommitAnswers(); const result = await runCommitWorkflow({ diff --git a/packages/cli/test/commands/commit.test.ts b/packages/cli/test/commands/commit.test.ts index 1f74bab..26fdd01 100644 --- a/packages/cli/test/commands/commit.test.ts +++ b/packages/cli/test/commands/commit.test.ts @@ -5,6 +5,10 @@ import * as ui from "../../src/commands/ui"; vi.mock("@stackcode/core", () => ({ getCommandOutput: vi.fn(), + getCurrentBranch: vi.fn(), + isProtectedBranch: vi.fn((branch: string | null) => + ["main", "master", "develop"].includes(branch ?? ""), + ), runCommitWorkflow: vi.fn(), getErrorMessage: vi.fn((error: unknown) => error instanceof Error ? error.message : String(error ?? "error"), @@ -17,6 +21,7 @@ describe("Commit Command Handler", () => { beforeEach(() => { vi.clearAllMocks(); + vi.mocked(core.getCurrentBranch).mockResolvedValue("feature/login"); vi.spyOn(console, "log").mockImplementation(() => {}); vi.spyOn(console, "error").mockImplementation(() => {}); }); @@ -90,4 +95,66 @@ describe("Commit Command Handler", () => { }), ); }); + + describe("on a protected branch", () => { + beforeEach(() => { + vi.mocked(core.getCommandOutput).mockResolvedValue("M src/index.ts"); + vi.mocked(core.getCurrentBranch).mockResolvedValue("develop"); + vi.mocked(ui.promptForCommitAnswers).mockResolvedValue({ + type: "fix", + scope: "", + shortDescription: "handle empty config", + longDescription: "", + breakingChanges: "", + affectedIssues: "", + }); + vi.mocked(core.runCommitWorkflow).mockResolvedValue({ + status: "committed", + message: "fix: handle empty config", + }); + }); + + it("warns and stops when the user does not confirm", async () => { + vi.mocked(ui.promptForConfirmation).mockResolvedValue(false); + + await handler({ _: [], $0: "stc" }); + + expect(ui.log.warning).toHaveBeenCalled(); + expect(ui.promptForConfirmation).toHaveBeenCalledWith( + expect.any(String), + false, + ); + expect(ui.promptForCommitAnswers).not.toHaveBeenCalled(); + expect(core.runCommitWorkflow).not.toHaveBeenCalled(); + }); + + it("commits when the user confirms", async () => { + vi.mocked(ui.promptForConfirmation).mockResolvedValue(true); + + await handler({ _: [], $0: "stc" }); + + expect(core.runCommitWorkflow).toHaveBeenCalled(); + }); + }); + + it("does not ask for confirmation on a feature branch", async () => { + vi.mocked(core.getCommandOutput).mockResolvedValue("M src/index.ts"); + vi.mocked(ui.promptForCommitAnswers).mockResolvedValue({ + type: "feat", + scope: "", + shortDescription: "add login", + longDescription: "", + breakingChanges: "", + affectedIssues: "", + }); + vi.mocked(core.runCommitWorkflow).mockResolvedValue({ + status: "committed", + message: "feat: add login", + }); + + await handler({ _: [], $0: "stc" }); + + expect(ui.promptForConfirmation).not.toHaveBeenCalled(); + expect(core.runCommitWorkflow).toHaveBeenCalled(); + }); }); diff --git a/packages/core/src/branches.ts b/packages/core/src/branches.ts new file mode 100644 index 0000000..72b7563 --- /dev/null +++ b/packages/core/src/branches.ts @@ -0,0 +1,40 @@ +/** + * @fileoverview Helpers to detect work happening directly on long-lived + * GitFlow branches, where commits should arrive through pull requests. + */ +import { getCommandOutput } from "./utils.js"; + +/** Branches that should only receive changes through pull requests. */ +export const DEFAULT_PROTECTED_BRANCHES: readonly string[] = [ + "main", + "master", + "develop", +]; + +/** + * Tells whether a branch is one of the protected GitFlow branches. + * @param branch - Branch name, or null/undefined when unknown (detached HEAD). + * @param protectedBranches - Branch names to protect. + */ +export function isProtectedBranch( + branch: string | null | undefined, + protectedBranches: readonly string[] = DEFAULT_PROTECTED_BRANCHES, +): boolean { + return Boolean(branch) && protectedBranches.includes(branch as string); +} + +/** + * Returns the checked-out branch, or null outside a repository or on a + * detached HEAD. + * @param cwd - Directory inside the repository. + */ +export async function getCurrentBranch(cwd: string): Promise { + try { + const branch = await getCommandOutput("git", ["branch", "--show-current"], { + cwd, + }); + return branch || null; + } catch { + return null; + } +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 000e6e8..60bf784 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -19,6 +19,11 @@ export { } from "./generators.js"; export { scaffoldProject, setupHusky } from "./scaffold.js"; export { validateCommitMessage } from "./validator.js"; +export { + DEFAULT_PROTECTED_BRANCHES, + getCurrentBranch, + isProtectedBranch, +} from "./branches.js"; export * from "./github.js"; export * from "./types.js"; diff --git a/packages/core/test/branches.test.ts b/packages/core/test/branches.test.ts new file mode 100644 index 0000000..6960b84 --- /dev/null +++ b/packages/core/test/branches.test.ts @@ -0,0 +1,61 @@ +import { execFileSync } from "child_process"; +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { + DEFAULT_PROTECTED_BRANCHES, + getCurrentBranch, + isProtectedBranch, +} from "../src/branches.js"; + +describe("isProtectedBranch", () => { + it("protects main, master and develop by default", () => { + expect(DEFAULT_PROTECTED_BRANCHES).toEqual(["main", "master", "develop"]); + for (const branch of DEFAULT_PROTECTED_BRANCHES) { + expect(isProtectedBranch(branch)).toBe(true); + } + }); + + it("does not protect work branches or unknown branches", () => { + expect(isProtectedBranch("feature/login")).toBe(false); + expect(isProtectedBranch("release/1.2.0")).toBe(false); + expect(isProtectedBranch(null)).toBe(false); + expect(isProtectedBranch(undefined)).toBe(false); + }); + + it("accepts a custom list", () => { + expect(isProtectedBranch("trunk", ["trunk"])).toBe(true); + expect(isProtectedBranch("main", ["trunk"])).toBe(false); + }); +}); + +describe("getCurrentBranch", () => { + let dir: string; + + beforeEach(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), "stackcode-branch-")); + }); + + afterEach(() => { + fs.rmSync(dir, { recursive: true, force: true }); + }); + + it("returns the checked-out branch", async () => { + execFileSync("git", ["init", "-b", "develop"], { + cwd: dir, + stdio: "ignore", + }); + expect(await getCurrentBranch(dir)).toBe("develop"); + + execFileSync("git", ["checkout", "-b", "feature/x"], { + cwd: dir, + stdio: "ignore", + }); + expect(await getCurrentBranch(dir)).toBe("feature/x"); + }); + + it("returns null outside a repository", async () => { + expect(await getCurrentBranch(dir)).toBeNull(); + }); +}); diff --git a/packages/i18n/src/locales/en.json b/packages/i18n/src/locales/en.json index 75b7963..49b18c5 100644 --- a/packages/i18n/src/locales/en.json +++ b/packages/i18n/src/locales/en.json @@ -114,7 +114,12 @@ "test": "test: Adding missing tests or correcting existing tests", "chore": "chore: Changes to the build process or auxiliary tools", "revert": "revert: Reverts a previous commit" - } + }, + "protected_branch_warning": "You are about to commit directly on \"{branch}\".", + "protected_branch_suggestion": "In GitFlow, \"{branch}\" receives changes through pull requests. Start a branch with \"stc git start\" and commit there.", + "protected_branch_confirm": "Commit on \"{branch}\" anyway?", + "protected_branch_continue": "Commit anyway", + "protected_branch_new_branch": "Start a new branch" }, "config": { "command_description": "Manage StackCode global and local configuration.", diff --git a/packages/i18n/src/locales/es.json b/packages/i18n/src/locales/es.json index 07b9d5c..4d90eb6 100644 --- a/packages/i18n/src/locales/es.json +++ b/packages/i18n/src/locales/es.json @@ -114,7 +114,12 @@ "test": "test: Agregando tests faltantes o corrigiendo tests existentes", "chore": "chore: Cambios en el proceso de build o herramientas auxiliares", "revert": "revert: Revierte un commit previo" - } + }, + "protected_branch_warning": "Estás a punto de hacer commit directamente en \"{branch}\".", + "protected_branch_suggestion": "En GitFlow, \"{branch}\" recibe cambios mediante pull requests. Crea una rama con \"stc git start\" y haz el commit allí.", + "protected_branch_confirm": "¿Hacer el commit en \"{branch}\" de todos modos?", + "protected_branch_continue": "Hacer commit de todos modos", + "protected_branch_new_branch": "Crear una nueva rama" }, "config": { "command_description": "Gestionar configuración global y local de StackCode.", diff --git a/packages/i18n/src/locales/pt.json b/packages/i18n/src/locales/pt.json index 3b280e1..9c49272 100644 --- a/packages/i18n/src/locales/pt.json +++ b/packages/i18n/src/locales/pt.json @@ -135,7 +135,12 @@ "test": "test: Adicionando ou corrigindo testes", "chore": "chore: Mudanças no processo de build ou ferramentas auxiliares", "revert": "revert: Reverte um commit anterior" - } + }, + "protected_branch_warning": "Você está prestes a fazer commit direto na \"{branch}\".", + "protected_branch_suggestion": "No GitFlow, a \"{branch}\" recebe mudanças por pull request. Crie uma branch com \"stc git start\" e faça o commit nela.", + "protected_branch_confirm": "Fazer o commit na \"{branch}\" mesmo assim?", + "protected_branch_continue": "Fazer commit mesmo assim", + "protected_branch_new_branch": "Criar uma nova branch" }, "config": { "command_description": "Gerencia as configurações locais e globais do StackCode.", diff --git a/packages/vscode-extension/src/commands/CommitCommand.ts b/packages/vscode-extension/src/commands/CommitCommand.ts index 4552908..764b956 100644 --- a/packages/vscode-extension/src/commands/CommitCommand.ts +++ b/packages/vscode-extension/src/commands/CommitCommand.ts @@ -1,5 +1,7 @@ import * as vscode from "vscode"; import { + getCurrentBranch, + isProtectedBranch, runCommitWorkflow, runIssuesWorkflow, type CommitWorkflowStep, @@ -44,6 +46,10 @@ export class CommitCommand extends BaseCommand { return; } + if (!(await this.confirmBranch(workspaceFolder.uri.fsPath))) { + return; + } + const commitType = await this.selectCommitType(); if (!commitType) { return; @@ -386,6 +392,49 @@ export class CommitCommand extends BaseCommand { return this.outputChannel; } + /** + * Warns before committing directly on main, master or develop and offers + * to start a new branch instead. Returns true when the commit should go on. + */ + private async confirmBranch(cwd: string): Promise { + const branch = await getCurrentBranch(cwd); + if (!branch || !isProtectedBranch(branch)) { + return true; + } + + const startBranch = this.translate( + "commit.protected_branch_new_branch", + "Start a new branch", + ); + const commitAnyway = this.translate( + "commit.protected_branch_continue", + "Commit anyway", + ); + const choice = await vscode.window.showWarningMessage( + this.translate( + "commit.protected_branch_warning", + 'You are about to commit directly on "{branch}".', + { branch }, + ), + { + modal: true, + detail: this.translate( + "commit.protected_branch_suggestion", + 'In GitFlow, "{branch}" receives changes through pull requests. Start a branch and commit there.', + { branch }, + ), + }, + startBranch, + commitAnyway, + ); + + if (choice === startBranch) { + await vscode.commands.executeCommand("stackcode.git.start"); + return false; + } + return choice === commitAnyway; + } + /** * Safely translates a key using i18n with a fallback string. */ diff --git a/packages/vscode-extension/src/test/__mocks__/core-workflows.ts b/packages/vscode-extension/src/test/__mocks__/core-workflows.ts index a192c80..bc8a649 100644 --- a/packages/vscode-extension/src/test/__mocks__/core-workflows.ts +++ b/packages/vscode-extension/src/test/__mocks__/core-workflows.ts @@ -240,6 +240,17 @@ export const validateCommitMessage = jest.fn( }, ); +/** + * Mock implementations of the branch helpers + */ +export const getCurrentBranch = jest.fn( + async (): Promise => "feature/mock", +); + +export const isProtectedBranch = jest.fn((branch: string | null) => + ["main", "master", "develop"].includes(branch ?? ""), +); + /** * Mock implementation of clearRepositoryCache */ diff --git a/packages/vscode-extension/src/test/integration/CommitCommand.integration.test.ts b/packages/vscode-extension/src/test/integration/CommitCommand.integration.test.ts index 6baa983..f51c0ef 100644 --- a/packages/vscode-extension/src/test/integration/CommitCommand.integration.test.ts +++ b/packages/vscode-extension/src/test/integration/CommitCommand.integration.test.ts @@ -10,7 +10,7 @@ import { CommitCommand } from "../../commands/CommitCommand"; import { GitHubAuthService } from "../../services/GitHubAuthService"; import { GitMonitor } from "../../monitors/GitMonitor"; import { ProgressManager } from "../../services/ProgressManager"; -import { runCommitWorkflow } from "@stackcode/core"; +import { getCurrentBranch, runCommitWorkflow } from "@stackcode/core"; jest.mock("vscode", () => { const mockQuickPick = { @@ -27,9 +27,13 @@ jest.mock("vscode", () => { showInputBox: jest.fn(), showInformationMessage: jest.fn(), showErrorMessage: jest.fn(), + showWarningMessage: jest.fn(), withProgress: jest.fn((_, callback) => callback({ report: jest.fn() })), createQuickPick: jest.fn(() => mockQuickPick), }, + commands: { + executeCommand: jest.fn(), + }, workspace: { workspaceFolders: [ { @@ -56,6 +60,10 @@ jest.mock("vscode", () => { jest.mock("@stackcode/core", () => ({ runCommitWorkflow: jest.fn(), + getCurrentBranch: jest.fn(), + isProtectedBranch: jest.fn((branch: string | null) => + ["main", "master", "develop"].includes(branch ?? ""), + ), })); jest.mock("@stackcode/i18n", () => ({ @@ -100,6 +108,9 @@ describe("CommitCommand Integration Tests", () => { (vscode.window.showInformationMessage as jest.Mock).mockClear(); (vscode.window.showErrorMessage as jest.Mock).mockClear(); (runCommitWorkflow as jest.Mock).mockClear(); + (vscode.window.showWarningMessage as jest.Mock).mockReset(); + (vscode.commands.executeCommand as jest.Mock).mockClear(); + (getCurrentBranch as jest.Mock).mockResolvedValue("feature/test"); }); describe("execute()", () => { @@ -258,4 +269,62 @@ describe("CommitCommand Integration Tests", () => { ).toHaveBeenCalled(); }); }); + + describe("on a protected branch", () => { + beforeEach(() => { + (getCurrentBranch as jest.Mock).mockResolvedValue("develop"); + }); + + it("starts a new branch instead of committing when asked", async () => { + (vscode.window.showWarningMessage as jest.Mock).mockResolvedValueOnce( + "commit.protected_branch_new_branch", + ); + + await commitCommand.execute(); + + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "stackcode.git.start", + ); + expect(vscode.window.showQuickPick).not.toHaveBeenCalled(); + expect(runCommitWorkflow).not.toHaveBeenCalled(); + }); + + it("stops when the warning is dismissed", async () => { + (vscode.window.showWarningMessage as jest.Mock).mockResolvedValueOnce( + undefined, + ); + + await commitCommand.execute(); + + expect(vscode.window.showQuickPick).not.toHaveBeenCalled(); + expect(runCommitWorkflow).not.toHaveBeenCalled(); + }); + + it("commits when the user chooses to commit anyway", async () => { + (vscode.window.showWarningMessage as jest.Mock).mockResolvedValueOnce( + "commit.protected_branch_continue", + ); + (vscode.window.showQuickPick as jest.Mock).mockResolvedValueOnce({ + label: "fix", + value: "fix", + }); + (vscode.window.showInputBox as jest.Mock) + .mockResolvedValueOnce("") + .mockResolvedValueOnce("Fix crash") + .mockResolvedValueOnce("") + .mockResolvedValueOnce("") + .mockResolvedValueOnce(""); + (runCommitWorkflow as jest.Mock).mockResolvedValue({ + status: "committed", + message: "fix: Fix crash", + }); + + await commitCommand.execute(); + + expect(runCommitWorkflow).toHaveBeenCalledWith( + expect.objectContaining({ type: "fix", shortDescription: "Fix crash" }), + expect.anything(), + ); + }); + }); });