|
| 1 | +import { test, expect } from "vitest"; |
| 2 | +import fs from "fs/promises"; |
| 3 | +import path from "node:path"; |
| 4 | +import os from "node:os"; |
| 5 | +import { git } from "@commitlint/test"; |
| 6 | + |
| 7 | +import toplevel from "./index.js"; |
| 8 | + |
| 9 | +test("should find git toplevel from repo root", async () => { |
| 10 | + const cwd = await git.bootstrap(); |
| 11 | + const result = await toplevel(cwd); |
| 12 | + expect(result).toBe(cwd); |
| 13 | +}); |
| 14 | + |
| 15 | +test("should find git toplevel from subdirectory", async () => { |
| 16 | + const cwd = await git.bootstrap(); |
| 17 | + const subdir = path.join(cwd, "subdir"); |
| 18 | + await fs.mkdir(subdir); |
| 19 | + |
| 20 | + const result = await toplevel(subdir); |
| 21 | + expect(result).toBe(cwd); |
| 22 | +}); |
| 23 | + |
| 24 | +test("should prefer closer .git directory over farther .git file", async () => { |
| 25 | + // Create a parent directory with a .git file (simulating dotfiles bare repo) |
| 26 | + const parentDir = await fs.mkdtemp(path.join(os.tmpdir(), "parent-")); |
| 27 | + const gitFileContent = `gitdir: ${path.join(parentDir, ".rcfiles")}`; |
| 28 | + await fs.writeFile(path.join(parentDir, ".git"), gitFileContent); |
| 29 | + await fs.mkdir(path.join(parentDir, ".rcfiles")); |
| 30 | + |
| 31 | + // Create a child git repo inside the parent |
| 32 | + const childDir = path.join(parentDir, "child-repo"); |
| 33 | + await fs.mkdir(childDir); |
| 34 | + await fs.mkdir(path.join(childDir, ".git")); |
| 35 | + |
| 36 | + // The toplevel should be the child repo, not the parent |
| 37 | + const result = await toplevel(childDir); |
| 38 | + expect(result).toBe(childDir); |
| 39 | + |
| 40 | + // Cleanup |
| 41 | + await fs.rm(parentDir, { recursive: true }); |
| 42 | +}); |
| 43 | + |
| 44 | +test("should handle .git file (submodule) correctly", async () => { |
| 45 | + const cwd = await git.bootstrap(); |
| 46 | + |
| 47 | + // Create a submodule-like structure with a .git file |
| 48 | + const submoduleDir = path.join(cwd, "submodule"); |
| 49 | + await fs.mkdir(submoduleDir); |
| 50 | + const gitFileContent = `gitdir: ${path.join(cwd, ".git", "modules", "submodule")}`; |
| 51 | + await fs.writeFile(path.join(submoduleDir, ".git"), gitFileContent); |
| 52 | + |
| 53 | + const result = await toplevel(submoduleDir); |
| 54 | + expect(result).toBe(submoduleDir); |
| 55 | +}); |
| 56 | + |
| 57 | +test("should return undefined when no .git found", async () => { |
| 58 | + const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "no-git-")); |
| 59 | + |
| 60 | + const result = await toplevel(tmpDir); |
| 61 | + expect(result).toBeUndefined(); |
| 62 | + |
| 63 | + await fs.rm(tmpDir, { recursive: true }); |
| 64 | +}); |
0 commit comments