Skip to content

Commit 4de7074

Browse files
msigwartsxzz
andauthored
fix(exports): use correct indentation for output (#599)
Co-authored-by: Kevin Deng <sxzz@sxzz.moe>
1 parent ca0d210 commit 4de7074

File tree

2 files changed

+41
-6
lines changed

2 files changed

+41
-6
lines changed

src/features/exports.test.ts

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import path from 'node:path'
22
import process from 'node:process'
33
import { describe, test } from 'vitest'
4-
import { generateExports } from './exports.ts'
4+
import { detectIndent, generateExports } from './exports.ts'
55
import type { OutputChunk } from 'rolldown'
66

77
const cwd = process.cwd()
@@ -402,6 +402,29 @@ describe.concurrent('generateExports', () => {
402402
})
403403
})
404404

405+
describe('detectIndent', () => {
406+
test('two spaces', ({ expect }) => {
407+
expect(detectIndent(stringifyJson(2))).toBe(2)
408+
})
409+
test('four spaces', ({ expect }) => {
410+
expect(detectIndent(stringifyJson(4))).toBe(4)
411+
})
412+
test('tab', ({ expect }) => {
413+
expect(detectIndent(stringifyJson('\t'))).toBe('\t')
414+
})
415+
test('empty', ({ expect }) => {
416+
expect(detectIndent('')).toBe(2)
417+
})
418+
test('empty line', ({ expect }) => {
419+
expect(detectIndent('{\n\n "foo": 42 }')).toBe(2)
420+
})
421+
})
422+
423+
function stringifyJson(indentation: string | number): string {
424+
const contents = JSON.stringify({ foo: 42 }, null, indentation)
425+
return contents
426+
}
427+
405428
function genChunk(fileName: string) {
406429
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
407430
return {

src/features/exports.ts

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -65,17 +65,29 @@ export async function writeExports(
6565
}
6666

6767
const original = await readFile(pkg.packageJsonPath, 'utf8')
68-
let contents = JSON.stringify(
69-
updatedPkg,
70-
null,
71-
original.includes('\t') ? '\t' : 2,
72-
)
68+
let contents = JSON.stringify(updatedPkg, null, detectIndent(original))
7369
if (original.endsWith('\n')) contents += '\n'
7470
if (contents !== original) {
7571
await writeFile(pkg.packageJsonPath, contents, 'utf8')
7672
}
7773
}
7874

75+
export function detectIndent(jsonText: string): string | number {
76+
const lines = jsonText.split(/\r?\n/)
77+
78+
for (const line of lines) {
79+
const match = line.match(/^(\s+)\S/)
80+
if (!match) continue
81+
82+
if (match[1].includes('\t')) {
83+
return '\t'
84+
}
85+
return match[1].length
86+
}
87+
88+
return 2
89+
}
90+
7991
type SubExport = Partial<Record<'cjs' | 'es' | 'src', string>>
8092

8193
export async function generateExports(

0 commit comments

Comments
 (0)