import { execFileSync } from 'node:child_process' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' import { describe, expect, it, vi } from 'vitest' import { addCreateDate, getDateString, } from '../../src/node/helper/addCreateDate.js' import type { AutoFrontmatterContext } from '../../src/node/types.js' const GIT_TIMESTAMP = 1_700_000_000 const GIT_DATE = new Date(GIT_TIMESTAMP * 1000) const hasGit = (): boolean => { try { execFileSync('git', ['--version'], { stdio: 'ignore' }) return true } catch { return false } } const git = (cwd: string, args: string[]): void => { execFileSync('git', args, { cwd, stdio: 'ignore', env: { ...process.env, GIT_AUTHOR_NAME: 'test', GIT_AUTHOR_EMAIL: 'test@example.com', GIT_COMMITTER_NAME: 'test', GIT_COMMITTER_EMAIL: 'test@example.com', GIT_AUTHOR_DATE: `${GIT_TIMESTAMP} +0000`, GIT_COMMITTER_DATE: `${GIT_TIMESTAMP} +0000`, }, }) } const getCreateDate = (dir: string, filename: string): unknown => { const data: Record = {} vi.spyOn(process, 'cwd').mockReturnValueOnce(dir) addCreateDate(data, { filepath: path.join(dir, filename), relativePath: filename, content: '', } satisfies AutoFrontmatterContext) return data.date } /** * Create a temporary repository with one commit, run `run` with its path, and * remove the repository afterwards. * * @param filenames - File names to create and commit / 要创建并提交的文件名 * @param run - Test body that receives the repository path / 接收仓库路径的测试主体 */ const withRepository = ( filenames: string[], run: (dir: string) => void, ): void => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'auto-frontmatter-git-')) try { git(dir, ['init', '-q']) for (const filename of filenames) fs.writeFileSync(path.join(dir, filename), '# Content') git(dir, ['add', '-A']) git(dir, ['commit', '-qm', 'init']) run(dir) } finally { fs.rmSync(dir, { recursive: true, force: true }) vi.restoreAllMocks() } } describe.skipIf(!hasGit())('addCreateDate with a real git repository', () => { it('should read the creation date of a file name that looks like pathspec magic', () => { withRepository([':(exclude)magic.md', 'plain.md'], (dir) => { // Without `--literal-pathspecs` git rejects this name, and the plugin // falls back to the file system date, which is the current date. expect(getCreateDate(dir, ':(exclude)magic.md')).toBe( getDateString(GIT_DATE), ) }) }) it('should read the creation date of a file name with a line break', () => { withRepository(['line\nbreak.md'], (dir) => { expect(getCreateDate(dir, 'line\nbreak.md')).toBe(getDateString(GIT_DATE)) }) }) it('should fall back to the file date for a file that is not committed', () => { withRepository(['tracked.md'], (dir) => { const untracked = 'untracked.md' fs.writeFileSync(path.join(dir, untracked), '# Content') expect(getCreateDate(dir, untracked)).toBe( getDateString( new Date(fs.statSync(path.join(dir, untracked)).birthtime), ), ) }) }) })