Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/quiet-pandas-read.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"pretty-quick": patch
---

Preserve non-ASCII characters, quotes, tabs and newlines in Git filenames when finding changed files.
18 changes: 13 additions & 5 deletions src/scms/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,16 @@ export const detect = (directory: string) => {
return found ? path.dirname(found) : null
}

const runGit = (directory: string, args: string[]) =>
const runGit = (directory: string, args: string[], throwOnError?: boolean) =>
exec('git', args, {
...(throwOnError ? { throwOnError } : {}),
nodeOptions: {
cwd: directory,
},
})

const getLines = (tinyexecOutput: Output) => tinyexecOutput.stdout.split('\n')
const getFilenames = (tinyexecOutput: Output) =>
tinyexecOutput.stdout.split('\0')

export const getSinceRevision = async (
directory: string,
Expand Down Expand Up @@ -62,25 +64,27 @@ export const getChangedFiles = async (
staged?: boolean | undefined,
) =>
[
...getLines(
...getFilenames(
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
await runGit(
directory,
[
'diff',
'--name-only',
staged ? '--cached' : null,
'--diff-filter=ACMRTUB',
'-z',
revision,
].filter(Boolean),
),
),
...(staged
? []
: getLines(
: getFilenames(
await runGit(directory, [
'ls-files',
'--others',
'--exclude-standard',
'-z',
]),
)),
].filter(Boolean)
Expand All @@ -103,6 +107,10 @@ export const stageFiles = async (directory: string, files: string[]) => {
}, [])

for (const batchedFiles of result) {
await runGit(directory, ['add', ...batchedFiles])
await runGit(
directory,
['--literal-pathspecs', 'add', '--', ...batchedFiles],
true,
)
}
}
2 changes: 1 addition & 1 deletion test/pattern.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ describe('match pattern', () => {
'/src/libs/hello/bar.js',
'/src/tools/hello/baz.js',
'/src/should-not-be-included/hello/zoo.js',
].join('\n'),
].join('\0'),
}
}
default: {
Expand Down
100 changes: 100 additions & 0 deletions test/scm-git-integration.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { execFileSync } from 'child_process'
import fs from 'fs'
import os from 'os'
import path from 'path'

let directory: string

// CI builds before testing. Run the built public API in Node so that Git,
// tinyexec and Prettier execute without Jest's manual module mocks.
const runPrettyQuick = (lockIndex = false) =>
JSON.parse(
execFileSync(
process.execPath,
[
'--input-type=module',
'--eval',
`import fs from 'node:fs';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
const { default: prettyQuick } = await import(pathToFileURL(process.argv[1]));
const directory = process.argv[2];
const result = await prettyQuick(directory, {
staged: true,
onStageFiles: process.argv[3] === 'true'
? () => fs.writeFileSync(path.join(directory, '.git', 'index.lock'), '')
: undefined,
});
process.stdout.write(JSON.stringify(result));`,
path.resolve(__dirname, '../lib/index.mjs'),
directory,
String(lockIndex),
],
{ encoding: 'utf8' },
),
)

const git = (...args: string[]) =>
// Resolve the same Git executable from PATH that pretty-quick uses.
// eslint-disable-next-line sonarjs/no-os-command-from-path
execFileSync('git', args, { cwd: directory, encoding: 'utf8' })

beforeEach(() => {
directory = fs.mkdtempSync(path.join(os.tmpdir(), 'pretty-quick-git-'))
git('init', '--quiet')
fs.writeFileSync(path.join(directory, '.prettierrc.json'), '{"semi":true}')
git('add', '--', '.prettierrc.json')
git(
'-c',
'user.name=Test',
'-c',
'user.email=test@example.com',
'-c',
'core.hooksPath=/dev/null',
'commit',
'--quiet',
'-m',
'Initial',
)
})

afterEach(() => {
fs.rmSync(directory, { recursive: true, force: true })
})

const testFilename = process.platform === 'win32' ? test.skip : test

testFilename.each([
['中文.js', 'other.js'],
['quote"name.js', 'other.js'],
['tab\tname.js', 'other.js'],
['line\nname.js', 'other.js'],
['*中文.js', 'other中文.js'],
['[文].js', '文.js'],
['-中文.js', 'other.js'],
[':(glob)*中文.js', 'other中文.js'],
])('restages only the literal file %j', (file, unrelated) => {
fs.writeFileSync(path.join(directory, file), 'example()')
fs.writeFileSync(path.join(directory, unrelated), 'unrelated()')
git('--literal-pathspecs', 'add', '--', file)

const result = runPrettyQuick()

expect(result).toEqual({ success: true, errors: [] })
expect(git('show', ':0:' + file)).toBe('example();\n')
expect(git('diff', '--cached', '--name-only', '-z')).toBe(file + '\0')
expect(git('ls-files', '--others', '--exclude-standard', '-z')).toBe(
unrelated + '\0',
)
expect(fs.readFileSync(path.join(directory, unrelated), 'utf8')).toBe(
'unrelated()',
)
})

test('reports a failed restage when Git cannot write the index', () => {
fs.writeFileSync(path.join(directory, 'example.js'), 'example()')
git('add', '--', 'example.js')
const result = runPrettyQuick(true)
expect(result).toEqual({ success: false, errors: ['STAGE_FAILED'] })
expect(git('show', ':0:example.js')).toBe('example()')
})
153 changes: 118 additions & 35 deletions test/scm-git.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@ const mockGitFs = (
}
case 'diff': {
return args[2] === '--cached'
? { stdout: './raz.js\n' }
: { stdout: './foo.js\n' + './bar.md\n' + additionalUnstaged }
? { stdout: './raz.js\0' }
: { stdout: './foo.js\0' + './bar.md\0' + additionalUnstaged }
}
case 'add': {
case '--literal-pathspecs': {
return { stdout: '' }
}
default: {
Expand Down Expand Up @@ -102,7 +102,7 @@ describe('with git', () => {

expect(tinyexec.exec).toHaveBeenCalledWith(
'git',
['diff', '--name-only', '--diff-filter=ACMRTUB'],
['diff', '--name-only', '--diff-filter=ACMRTUB', '-z'],
{ nodeOptions: { cwd: '/' } },
)
})
Expand All @@ -116,7 +116,7 @@ describe('with git', () => {

expect(tinyexec.exec).toHaveBeenCalledWith(
'git',
['diff', '--name-only', '--diff-filter=ACMRTUB', 'banana'],
['diff', '--name-only', '--diff-filter=ACMRTUB', '-z', 'banana'],
{ nodeOptions: { cwd: '/' } },
)
})
Expand All @@ -130,7 +130,7 @@ describe('with git', () => {

expect(tinyexec.exec).toHaveBeenCalledWith(
'git',
['ls-files', '--others', '--exclude-standard'],
['ls-files', '--others', '--exclude-standard', '-z'],
{ nodeOptions: { cwd: '/' } },
)
})
Expand All @@ -157,6 +157,44 @@ describe('with git', () => {
expect(onFoundChangedFiles).toHaveBeenCalledWith(['./foo.js', './bar.md'])
})

describe.each(['unstaged', 'staged', 'untracked'])('%s files', mode => {
test.each(['中文.js', 'quote"name.js', 'tab\tname.js', 'line\nname.js'])(
'formats %j without altering its name',
async file => {
const onWriteFile = jest.fn()
mock({ '/.git': {}, ['/' + file]: 'example()' })
const execSpy = jest.spyOn(tinyexec, 'exec') as jest.Mock
execSpy.mockImplementation((_command: string, args: string[]) => {
const diffMode = args.includes('--cached') ? 'staged' : 'unstaged'
const containsFile =
args[0] === 'ls-files'
? mode === 'untracked'
: args[0] === 'diff' && mode === diffMode
return { stdout: containsFile ? file + '\0' : '' }
})

await prettyQuick('root', {
since: 'banana',
staged: mode === 'staged',
onWriteFile,
})

expect(onWriteFile).toHaveBeenCalledWith(file)
expect(fs.readFileSync('/' + file, 'utf8')).toBe('formatted:example()')
if (mode === 'staged') {
expect(tinyexec.exec).toHaveBeenCalledWith(
'git',
['--literal-pathspecs', 'add', '--', file],
{
throwOnError: true,
nodeOptions: { cwd: '/' },
},
)
}
},
)
})

test('calls onWriteFile with changed files', async () => {
const onWriteFile = jest.fn()
mockGitFs()
Expand Down Expand Up @@ -229,42 +267,77 @@ describe('with git', () => {
test('with --staged stages fully-staged files', async () => {
mockGitFs()
await prettyQuick('root', { since: 'banana', staged: true })
expect(tinyexec.exec).toHaveBeenCalledWith('git', ['add', './raz.js'], {
nodeOptions: { cwd: '/' },
})
expect(tinyexec.exec).not.toHaveBeenCalledWith('git', ['add', './foo.js'], {
nodeOptions: { cwd: '/' },
})
expect(tinyexec.exec).not.toHaveBeenCalledWith('git', ['add', './bar.md'], {
nodeOptions: { cwd: '/' },
})
expect(tinyexec.exec).toHaveBeenCalledWith(
'git',
['--literal-pathspecs', 'add', '--', './raz.js'],
{
throwOnError: true,
nodeOptions: { cwd: '/' },
},
)
expect(tinyexec.exec).not.toHaveBeenCalledWith(
'git',
['--literal-pathspecs', 'add', '--', './foo.js'],
{
throwOnError: true,
nodeOptions: { cwd: '/' },
},
)
expect(tinyexec.exec).not.toHaveBeenCalledWith(
'git',
['--literal-pathspecs', 'add', '--', './bar.md'],
{
throwOnError: true,
nodeOptions: { cwd: '/' },
},
)
})

test('with --staged AND --no-restage does not re-stage any files', async () => {
mockGitFs()
await prettyQuick('root', { since: 'banana', staged: true, restage: false })
expect(tinyexec.exec).not.toHaveBeenCalledWith('git', ['add', './raz.js'], {
cwd: '/',
})
expect(tinyexec.exec).not.toHaveBeenCalledWith('git', ['add', './foo.js'], {
cwd: '/',
})
expect(tinyexec.exec).not.toHaveBeenCalledWith('git', ['add', './bar.md'], {
cwd: '/',
})
expect(tinyexec.exec).not.toHaveBeenCalledWith(
'git',
['--literal-pathspecs', 'add', '--', './raz.js'],
{
throwOnError: true,
nodeOptions: { cwd: '/' },
},
)
expect(tinyexec.exec).not.toHaveBeenCalledWith(
'git',
['--literal-pathspecs', 'add', '--', './foo.js'],
{
throwOnError: true,
nodeOptions: { cwd: '/' },
},
)
expect(tinyexec.exec).not.toHaveBeenCalledWith(
'git',
['--literal-pathspecs', 'add', '--', './bar.md'],
{
throwOnError: true,
nodeOptions: { cwd: '/' },
},
)
})

test('with --staged does not stage previously partially staged files AND aborts commit', async () => {
const additionalUnstaged = './raz.js\n' // raz.js is partly staged and partly not staged
const additionalUnstaged = './raz.js\0' // raz.js is partly staged and partly not staged
mockGitFs(additionalUnstaged)
await prettyQuick('root', { since: 'banana', staged: true })
expect(tinyexec.exec).not.toHaveBeenCalledWith('git', ['add', './raz.js'], {
cwd: '/',
})
expect(tinyexec.exec).not.toHaveBeenCalledWith(
'git',
['--literal-pathspecs', 'add', '--', './raz.js'],
{
throwOnError: true,
nodeOptions: { cwd: '/' },
},
)
})

test('with --staged returns false', async () => {
const additionalUnstaged = './raz.js\n' // raz.js is partly staged and partly not staged
const additionalUnstaged = './raz.js\0' // raz.js is partly staged and partly not staged
mockGitFs(additionalUnstaged)
const result = await prettyQuick('root', { since: 'banana', staged: true })
expect(result).toEqual({
Expand All @@ -276,12 +349,22 @@ describe('with git', () => {
test('without --staged does NOT stage changed files', async () => {
mockGitFs()
await prettyQuick('root', { since: 'banana' })
expect(tinyexec.exec).not.toHaveBeenCalledWith('git', ['add', './foo.js'], {
cwd: '/',
})
expect(tinyexec.exec).not.toHaveBeenCalledWith('git', ['add', './bar.md'], {
cwd: '/',
})
expect(tinyexec.exec).not.toHaveBeenCalledWith(
'git',
['--literal-pathspecs', 'add', '--', './foo.js'],
{
throwOnError: true,
nodeOptions: { cwd: '/' },
},
)
expect(tinyexec.exec).not.toHaveBeenCalledWith(
'git',
['--literal-pathspecs', 'add', '--', './bar.md'],
{
throwOnError: true,
nodeOptions: { cwd: '/' },
},
)
})

test('with --verbose calls onExamineFile', async () => {
Expand Down