Skip to content

Commit

Permalink
fix: hotfix preserve final newline
Browse files Browse the repository at this point in the history
  • Loading branch information
zardoy committed Nov 20, 2021
1 parent 259b051 commit 6e340ab
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ export const modifyJsonFile: ModifyJsonFileGenericFunction = async (path, modify
removeJsonc = false,
} = options
try {
let { json, indent } = await loadJsonFile(path, { encoding, tabSize, removeJsonc })
let { json, indent, hasFinalNewline } = await loadJsonFile(path, { encoding, tabSize, removeJsonc })
if (typeof modifyProperties === 'function') {
// TODO why arg is never
json = await (modifyProperties as any)(json)
Expand All @@ -120,7 +120,10 @@ export const modifyJsonFile: ModifyJsonFileGenericFunction = async (path, modify
}
}

await fs.promises.writeFile(path, JSON.stringify(json, undefined, indent))
// TODO don't use this fix
let string = JSON.stringify(json, undefined, indent)
if (hasFinalNewline) string += '\n'
await fs.promises.writeFile(path, string)
} catch (err) {
if (throws) throw err
}
Expand Down
1 change: 1 addition & 0 deletions src/loadJsonFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,6 @@ export const loadJsonFile = async (filePath: string, { encoding, tabSize, remove
return {
json: parseJson(contents, filePath) as JsonRoot,
indent: tabSize === 'preserve' ? detectIndent(contents).indent : tabSize === 'hard' ? '\t' : tabSize === null ? undefined : ' '.repeat(tabSize),
hasFinalNewline: contents.split('\n').slice(-1)[0]! === '',
}
}
41 changes: 41 additions & 0 deletions tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,47 @@ test("Don't throw error if option is provided on missing property in input", asy
)
})

test('Preserves empty newline', async () => {
expect.assertions(1)
prepare({
data: `
{
"author": "eldar",
"bin": "src/bin.ts",
"dependencies": {
"fdir": ">=2",
"type-fest": "*"
}
}
`,
json: false,
writeCallback(data) {
expect(data).toMatchInlineSnapshot(`
"{
\\"author\\": \\"eldar\\",
\\"bin\\": \\"build/bin.js\\",
\\"dependencies\\": {
\\"fdir\\": \\">=2\\",
\\"type-fest\\": \\"*\\"
},
\\"somethingWeird\\": \\"new-item\\"
}
"
`)
},
})
await modifyJsonFile(
'',
{
bin: 'build/bin.js',
somethingWeird: () => 'new-item',
},
{
ifPropertyIsMissingForSetter: 'pass',
},
)
})

test('loader removes comments and trailing commas', async () => {
const { json } = await loadJsonFile(join(__dirname, './tsconfig.fixture.json'), { encoding: 'utf-8', removeJsonc: true, tabSize: 'preserve' })
expect(json).toMatchInlineSnapshot(`
Expand Down

0 comments on commit 6e340ab

Please sign in to comment.