Skip to content

Commit a42fa3c

Browse files
committed
fix(file): Preserve final line ending when rewriting JSON
1 parent 6371b8f commit a42fa3c

2 files changed

Lines changed: 15 additions & 1 deletion

File tree

src/file.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,10 @@ export async function withJsonFile<T = any>(
102102

103103
// set indentation based on the first indented line
104104
const indent = /^(\s+)/m.exec(rawContent)?.[1] || 0;
105-
const newContent = JSON.stringify(doc, null, indent);
105+
// preserve final line ending if present
106+
const ending = rawContent.endsWith('\n') ? '\n' : '';
107+
108+
const newContent = JSON.stringify(doc, null, indent) + ending;
106109
if (newContent !== rawContent) {
107110
await writeFile(path, newContent);
108111
}

tests/file.spec.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,17 @@ describe('withJsonFile', () => {
102102
expect(newContent).to.equal(JSON.stringify(EXPECTED_DATA, null, indentation));
103103
});
104104
});
105+
106+
it('should preserve final line ending', async () => {
107+
await writeFile(TEST_FILE, '{}\n');
108+
109+
await withJsonFile(TEST_FILE, (f) => {
110+
f.key = 'value';
111+
});
112+
113+
const newContent = (await readFile(TEST_FILE)).toString();
114+
expect(newContent).to.equal('{"key":"value"}\n');
115+
});
105116
});
106117

107118
describe('withYamlFile', () => {

0 commit comments

Comments
 (0)