Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions packages/cli/src/commands/commit.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import type { CommandModule, ArgumentsCamelCase } from "yargs";
import {
getCommandOutput,
getCurrentBranch,
getErrorMessage,
isProtectedBranch,
runCommitWorkflow,
} from "@stackcode/core";
import { t } from "@stackcode/i18n";
Expand Down Expand Up @@ -30,6 +32,19 @@ export const getCommitCommand = (): CommandModule<object, CommitArgs> => ({
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({
Expand Down
67 changes: 67 additions & 0 deletions packages/cli/test/commands/commit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand All @@ -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(() => {});
});
Expand Down Expand Up @@ -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();
});
});
40 changes: 40 additions & 0 deletions packages/core/src/branches.ts
Original file line number Diff line number Diff line change
@@ -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<string | null> {
try {
const branch = await getCommandOutput("git", ["branch", "--show-current"], {
cwd,
});
return branch || null;
} catch {
return null;
}
}
5 changes: 5 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
61 changes: 61 additions & 0 deletions packages/core/test/branches.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
7 changes: 6 additions & 1 deletion packages/i18n/src/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
7 changes: 6 additions & 1 deletion packages/i18n/src/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
7 changes: 6 additions & 1 deletion packages/i18n/src/locales/pt.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
49 changes: 49 additions & 0 deletions packages/vscode-extension/src/commands/CommitCommand.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import * as vscode from "vscode";
import {
getCurrentBranch,
isProtectedBranch,
runCommitWorkflow,
runIssuesWorkflow,
type CommitWorkflowStep,
Expand Down Expand Up @@ -50,6 +52,10 @@ export class CommitCommand extends BaseCommand {
return;
}

if (!(await this.confirmBranch(workspaceFolder.uri.fsPath))) {
return;
}

// Ensure authenticated for commit workflow
const authResult = await this.authFlowManager.ensureAuthenticated(
"To create commits with issue linking, StackCode needs GitHub access.\n\n" +
Expand Down Expand Up @@ -416,6 +422,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<boolean> {
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.
*/
Expand Down
11 changes: 11 additions & 0 deletions packages/vscode-extension/src/test/__mocks__/core-workflows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,17 @@ export const validateCommitMessage = jest.fn(
},
);

/**
* Mock implementations of the branch helpers
*/
export const getCurrentBranch = jest.fn(
async (): Promise<string | null> => "feature/mock",
);

export const isProtectedBranch = jest.fn((branch: string | null) =>
["main", "master", "develop"].includes(branch ?? ""),
);

/**
* Mock implementation of clearRepositoryCache
*/
Expand Down
Loading
Loading