Skip to content

Commit dd2d2d8

Browse files
committed
Add a git branch detection test
1 parent f8321f1 commit dd2d2d8

File tree

3 files changed

+58
-7
lines changed

3 files changed

+58
-7
lines changed

src/extension.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,17 @@ export async function activate(context: vscode.ExtensionContext) {
8585
null,
8686
context.subscriptions,
8787
);
88+
89+
const api = {
90+
/**
91+
* Exposed for testing purposes.
92+
*/
93+
get gitBranch() {
94+
return gitBranch;
95+
},
96+
};
97+
98+
return api;
8899
}
89100

90101
// This method is called when your extension is deactivated

src/getgitbranch.ts

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -68,13 +68,9 @@ async function getCurrentGitBranchFromGit(
6868
const docDirectory = utils.dirname(docWithAbsolutePath);
6969

7070
try {
71-
const { stdout } = await execFile(
72-
"git",
73-
["rev-parse", "--abbrev-ref", "HEAD"],
74-
{
75-
cwd: docDirectory,
76-
},
77-
);
71+
const { stdout } = await execFile("git", ["branch", "--show-current"], {
72+
cwd: docDirectory,
73+
});
7874

7975
const branchName = stdout.trim();
8076
if (!branchName) {
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import * as assert from "assert";
2+
import * as vscode from "vscode";
3+
import * as path from "path";
4+
import * as fs from "fs";
5+
import * as os from "os";
6+
7+
import { execSync } from "child_process";
8+
9+
suite("Extension Integration", () => {
10+
test("Git branch detected in not-in-workspace file", async () => {
11+
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "git-commit-test-"));
12+
const commitMessage = path.join(tmpDir, "COMMIT_EDITMSG");
13+
fs.writeFileSync(commitMessage, "Initial commit\n\nDetails here.\n");
14+
15+
// Create a repo and a branch that we can detect
16+
execSync("git init", { cwd: tmpDir });
17+
execSync("git checkout -b test-branch", { cwd: tmpDir });
18+
19+
// Open the file in an editor
20+
const doc = await vscode.workspace.openTextDocument(
21+
vscode.Uri.file(commitMessage),
22+
);
23+
await vscode.window.showTextDocument(doc);
24+
25+
// Wait for extension activation to complete
26+
const ext = vscode.extensions.getExtension(
27+
"walles.git-commit-message-plus",
28+
)!;
29+
await ext.activate();
30+
31+
// Wait (up to ~2s) for async branch detection to populate gitBranch
32+
const deadline = Date.now() + 2000;
33+
let actualBranch: string | undefined = ext.exports.gitBranch;
34+
while (!actualBranch && Date.now() < deadline) {
35+
await new Promise((r) => globalThis.setTimeout(r, 50));
36+
actualBranch = ext.exports.gitBranch;
37+
}
38+
39+
assert.strictEqual(actualBranch, "test-branch");
40+
41+
// Clean up
42+
fs.rmSync(tmpDir, { recursive: true, force: true });
43+
});
44+
});

0 commit comments

Comments
 (0)