Skip to content

Commit f40e04c

Browse files
committed
Fixed file modification calculator handling of an empty file '[]'. Added tests for auto-import
1 parent cbe9334 commit f40e04c

File tree

3 files changed

+346
-164
lines changed

3 files changed

+346
-164
lines changed

src/generators/file-modification-calculator.ts

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,10 @@ export class FileModificationCalculator {
3535
this.validate(modifications);
3636

3737
let newFile = this.existingFile!.contents.trimEnd();
38+
if (newFile === '[]') {
39+
newFile = '[\n]'
40+
}
41+
3842
const updateCache = [...modifications];
3943

4044
// Reverse the traversal order so we edit from the back. This way the line numbers won't be messed up with new edits.
@@ -128,19 +132,22 @@ export class FileModificationCalculator {
128132
let result = file;
129133

130134
const fileStyle = jju.analyze(file);
135+
const indent = file === '[\n]' ? 2 : fileStyle.indent;
131136

132137
for (const newResource of resources.reverse()) {
133138
const sortedResource = { ...newResource.core(true), ...this.sortKeys(newResource.parameters) }
134139
let content = jju.stringify(sortedResource, {
135-
indent: fileStyle.indent,
140+
indent,
136141
no_trailing_comma: true,
137142
quote: '"',
138143
quote_keys: fileStyle.quote_keys,
139144
mode: this.fileTypeString(fileType),
140145
});
141146

142-
content = content.split(/\n/).map((l) => `${this.indentString}${l}`).join('\n')
143-
content = `,\n${content}`;
147+
const indentString = file === '[\n]' ? ' ' : this.indentString;
148+
149+
content = content.split(/\n/).map((l) => `${indentString}${l}`).join('\n')
150+
content = file === '[\n]' ? `\n${content}` : `,\n${content}`;
144151

145152
result = this.splice(result, position, 0, content)
146153
}

0 commit comments

Comments
 (0)