import type { 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 { AddCreateDateOptions } from '../../src/node/helper/addCreateDate.js' import type { AutoFrontmatterContext } from '../../src/node/types.js' interface ExecFileSyncOptions { cwd: string encoding: string timeout: number stdio: string[] } type ExecFileSyncMock = ( file: string, args: string[], options: ExecFileSyncOptions, ) => string const execFileSyncMock = vi.hoisted(() => vi.fn()) vi.mock( import('node:child_process'), () => ({ execFileSync: execFileSyncMock, }) as unknown as Partial<{ execFileSync: typeof execFileSync }>, ) const GIT_TIMESTAMP = 1_700_000_000 const GIT_DATE = new Date(GIT_TIMESTAMP * 1000) const pad = (value: number): string => String(value).padStart(2, '0') const EXPECTED_DATE = getDateString(GIT_DATE) const EXPECTED_TIME = `${pad(GIT_DATE.getHours())}:${pad(GIT_DATE.getMinutes())}:${pad(GIT_DATE.getSeconds())}` const FORMAT_CASES: [ format: NonNullable, expected: string, pattern: RegExp, ][] = [ ['date', EXPECTED_DATE, /^\d{4}-\d{2}-\d{2}$/u], [ 'full', `${EXPECTED_DATE} ${EXPECTED_TIME}`, /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/u, ], ['time', EXPECTED_TIME, /^\d{2}:\d{2}:\d{2}$/u], ] const GIT_INVALID_OUTPUTS: [name: string, output: string][] = [ ['empty', ''], ['whitespace', ' \n'], ['non-numeric', 'not-a-timestamp\n'], ['partially numeric', '1700000000abc\n'], ['zero', '0\n'], ['negative', '-1700000000\n'], ['float', '1700000000.5\n'], ['multiple lines', '1700000000\n1600000000\n'], ] const createContext = (filepath: string): AutoFrontmatterContext => ({ filepath, relativePath: path.basename(filepath), content: '', }) const fileSystemDate = (filepath: string): string => { const stats = fs.statSync(filepath) return getDateString( stats.birthtime.getFullYear() === 1970 ? stats.atime : stats.birthtime, ) } /** * Run a test against a real file in a temporary directory, and clean it up * afterwards. The mocked git call never touches the file itself. * * @param filename - File name to create in the temporary directory / 在临时目录中 * 创建的文件名 * @param run - Test body that receives the file path / 接收文件路径的测试主体 */ const withTempFile = ( filename: string, run: (filepath: string, relativePath: string) => void, ): void => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'auto-frontmatter-date-')) const filepath = path.join(dir, filename) fs.writeFileSync(filepath, '# Content') execFileSyncMock.mockReset() try { run(filepath, path.relative(process.cwd(), filepath)) } finally { fs.rmSync(dir, { recursive: true, force: true }) } } describe('addCreateDate git creation date', () => { it('should pass the git arguments as an array and keep the path a single argument', () => { const filename = 'note with space; $(id) `whoami`.md' withTempFile(filename, (filepath, relativePath) => { execFileSyncMock.mockReturnValue(`${GIT_TIMESTAMP}\n`) const data: Record = {} addCreateDate(data, createContext(filepath)) expect(execFileSyncMock).toHaveBeenCalledTimes(1) const [[command, args, options]] = execFileSyncMock.mock.calls expect(command).toBe('git') expect(args).toStrictEqual([ '--no-pager', '--literal-pathspecs', 'log', '--follow', '--diff-filter=A', '--format=%at', '--', relativePath, ]) expect(args.at(-1)).toBe(relativePath) expect(options).toStrictEqual({ cwd: process.cwd(), encoding: 'utf-8', timeout: 5000, stdio: ['pipe', 'pipe', 'ignore'], }) expect(data.date).toBe(EXPECTED_DATE) }) }) it('should keep a path that starts with a dash after the `--` separator', () => { const filename = '--force.md' withTempFile(filename, (filepath, relativePath) => { execFileSyncMock.mockReturnValue(`${GIT_TIMESTAMP}\n`) addCreateDate({}, createContext(filepath)) const [[, args]] = execFileSyncMock.mock.calls expect(args.at(-2)).toBe('--') expect(args.at(-1)).toBe(relativePath) expect(relativePath.endsWith(filename)).toBe(true) }) }) it('should keep a file name with a line break a single argument', () => { const filename = 'line\nbreak.md' withTempFile(filename, (filepath, relativePath) => { execFileSyncMock.mockReturnValue(`${GIT_TIMESTAMP}\n`) const data: Record = {} addCreateDate(data, createContext(filepath)) const [[, args]] = execFileSyncMock.mock.calls // A shell would split this name into two commands, an argument array // keeps it whole. expect(args).toHaveLength(8) expect(args.at(-1)).toBe(relativePath) expect(relativePath).toContain('\n') expect(data.date).toBe(EXPECTED_DATE) }) }) it('should disable pathspec magic so a file name cannot change what git reads', () => { const filename = ':(exclude)*.md' withTempFile(filename, (filepath, relativePath) => { execFileSyncMock.mockReturnValue(`${GIT_TIMESTAMP}\n`) const data: Record = {} addCreateDate(data, createContext(filepath)) const [[, args]] = execFileSyncMock.mock.calls expect(args.indexOf('--literal-pathspecs')).toBeGreaterThanOrEqual(0) expect(args.indexOf('--literal-pathspecs')).toBeLessThan( args.indexOf('log'), ) expect(args.at(-1)).toBe(relativePath) expect(data.date).toBe(EXPECTED_DATE) }) }) it('should use the git timestamp as the creation date', () => { withTempFile('valid.md', (filepath) => { execFileSyncMock.mockReturnValue(`${GIT_TIMESTAMP}\n`) const data: Record = {} addCreateDate(data, createContext(filepath)) expect(data.date).toBe(EXPECTED_DATE) }) }) it.each(FORMAT_CASES)( 'should format the creation date as %s', (format, expected, pattern) => { withTempFile('formatted.md', (filepath) => { execFileSyncMock.mockReturnValue(`${GIT_TIMESTAMP}\n`) const data: Record = {} addCreateDate(data, createContext(filepath), { format }) expect(data.date).toBe(expected) expect(data.date).toMatch(pattern) }) }, ) it.each(GIT_INVALID_OUTPUTS)( 'should fall back to the file date when git outputs a %s value', (_name, output) => { withTempFile('invalid.md', (filepath) => { execFileSyncMock.mockReturnValue(output) const data: Record = {} addCreateDate(data, createContext(filepath)) expect(data.date).not.toBe('1970-01-01') expect(data.date).toBe(fileSystemDate(filepath)) }) }, ) it('should fall back to the file date when git cannot run', () => { withTempFile('no-git.md', (filepath) => { execFileSyncMock.mockImplementation(() => { throw new Error('spawnSync git ENOENT') }) const data: Record = {} addCreateDate(data, createContext(filepath)) expect(data.date).not.toBe('1970-01-01') expect(data.date).toBe(fileSystemDate(filepath)) }) }) })