Files
git-worktree/test/worktree.test.mjs
T

64 lines
2.1 KiB
JavaScript

import test from 'node:test'
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import os from 'node:os'
import {
parseWorktreePorcelain,
gitExec,
getGitRoot,
} from '../index.js'
test('parseWorktreePorcelain parses git porcelain worktree format', () => {
const sample = `worktree /home/user/project
HEAD 1234567890abcdef
branch refs/heads/main
worktree /home/user/project/.worktrees/feature-a
HEAD fedcba0987654321
branch refs/heads/feature-a
worktree /home/user/project/.worktrees/detached-run
HEAD aaaaaaa000000000
detached
`
const res = parseWorktreePorcelain(sample)
assert.equal(res.length, 3)
assert.equal(res[0].path, '/home/user/project')
assert.equal(res[0].branch, 'main')
assert.equal(res[0].commit, '1234567890abcdef')
assert.equal(res[1].branch, 'feature-a')
assert.equal(res[2].detached, true)
})
test('gitExec and getGitRoot inside real git repo', async () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'git-wt-test-'))
await gitExec(tmp, ['init', '-b', 'main'])
await gitExec(tmp, ['config', 'user.name', 'Test Agent'])
await gitExec(tmp, ['config', 'user.email', 'test@example.com'])
fs.writeFileSync(path.join(tmp, 'hello.txt'), 'hello world')
await gitExec(tmp, ['add', 'hello.txt'])
await gitExec(tmp, ['commit', '-m', 'initial commit'])
const root = await getGitRoot(tmp)
// Resolve symlinks if any on temporary dirs
assert.equal(fs.realpathSync(root), fs.realpathSync(tmp))
// Create worktree
const wtDir = path.join(tmp, '.worktrees', 'test-wt')
const addRes = await gitExec(tmp, ['worktree', 'add', '-b', 'feature-test', wtDir])
assert.equal(addRes.code, 0)
// Verify list
const listRes = await gitExec(tmp, ['worktree', 'list', '--porcelain'])
const parsed = parseWorktreePorcelain(listRes.stdout)
assert.equal(parsed.length, 2)
assert.ok(parsed.some((w) => w.branch === 'feature-test'))
// Remove worktree
const rmRes = await gitExec(tmp, ['worktree', 'remove', wtDir])
assert.equal(rmRes.code, 0)
fs.rmSync(tmp, { recursive: true, force: true })
})