Skip to content

Commit 9041457

Browse files
committed
Add IJsonFileSaveOptions.updateExistingFile
1 parent bebd6da commit 9041457

3 files changed

Lines changed: 75 additions & 22 deletions

File tree

‎common/reviews/api/node-core-library.api.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,11 +90,13 @@ interface IFileWriterFlags {
9090
interface IJsonFileSaveOptions extends IJsonFileStringifyOptions {
9191
ensureFolderExists?: boolean;
9292
onlyIfChanged?: boolean;
93+
updateExistingFile?: boolean;
9394
}
9495

9596
// @public
9697
interface IJsonFileStringifyOptions {
9798
newlineConversion?: NewlineKind;
99+
prettyFormatting?: boolean;
98100
}
99101

100102
// @public
@@ -202,6 +204,7 @@ class JsonFile {
202204
static loadAndValidateWithCallback(jsonFilename: string, jsonSchema: JsonSchema, errorCallback: (errorInfo: IJsonSchemaErrorInfo) => void): any;
203205
static save(jsonObject: Object, jsonFilename: string, options?: IJsonFileSaveOptions): boolean;
204206
static stringify(jsonObject: Object, options?: IJsonFileStringifyOptions): string;
207+
static updateString(previousJson: string, newJsonObject: Object, options?: IJsonFileStringifyOptions): string;
205208
static validateNoUndefinedMembers(jsonObject: Object): void;
206209
}
207210

@@ -297,6 +300,7 @@ class ProtectableMap<K, V> {
297300
class Text {
298301
static convertToCrLf(input: string): string;
299302
static convertToLf(input: string): string;
303+
static ensureTrailingNewline(s: string, newlineKind?: NewlineKind): string;
300304
static padEnd(s: string, minimumLength: number): string;
301305
static replaceAll(input: string, searchValue: string, replaceValue: string): string;
302306
static truncateWithEllipsis(s: string, maximumLength: number): string;

‎libraries/node-core-library/src/JsonFile.ts‎

Lines changed: 65 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ import * as os from 'os';
55
import * as jju from 'jju';
66

77
import { JsonSchema, IJsonSchemaErrorInfo, IJsonSchemaValidateOptions } from './JsonSchema';
8-
import { Text } from './Text';
9-
import { FileSystem, NewlineKind } from './FileSystem';
8+
import { Text, NewlineKind } from './Text';
9+
import { FileSystem } from './FileSystem';
1010

1111
/**
1212
* Options for JsonFile.stringify()
@@ -20,7 +20,7 @@ export interface IJsonFileStringifyOptions {
2020
newlineConversion?: NewlineKind;
2121

2222
/**
23-
* If true, then the JJU library will be used to improve the text formatting.
23+
* If true, then the "jju" library will be used to improve the text formatting.
2424
* Note that this is slightly slower than the native JSON.stringify() implementation.
2525
*/
2626
prettyFormatting?: boolean;
@@ -43,6 +43,14 @@ export interface IJsonFileSaveOptions extends IJsonFileStringifyOptions {
4343
* Defaults to false.
4444
*/
4545
ensureFolderExists?: boolean;
46+
47+
/**
48+
* If true, use the "jju" library to preserve the existing JSON formatting: The file will be loaded
49+
* from the target filename, the new content will be merged in (preserving whitespace and comments),
50+
* and then the file will be overwritten with the merged contents. If the target file does not exist,
51+
* then the file is saved normally.
52+
*/
53+
updateExistingFile?: boolean;
4654
}
4755

4856
/**
@@ -99,19 +107,42 @@ export class JsonFile {
99107
* @returns a JSON string, with newlines, and indented with two spaces
100108
*/
101109
public static stringify(jsonObject: Object, options?: IJsonFileStringifyOptions): string {
102-
JsonFile.validateNoUndefinedMembers(jsonObject);
110+
return JsonFile.updateString('', jsonObject, options);
111+
}
112+
113+
/**
114+
* Serializes the specified JSON object to a string buffer.
115+
* @param jsonObject - the object to be serialized
116+
* @param options - other settings that control serialization
117+
* @returns a JSON string, with newlines, and indented with two spaces
118+
*/
119+
public static updateString(previousJson: string, newJsonObject: Object,
120+
options?: IJsonFileStringifyOptions): string {
121+
if (!options) {
122+
options = { };
123+
}
124+
125+
JsonFile.validateNoUndefinedMembers(newJsonObject);
103126

104127
let stringified: string;
105128

106-
if (options && options.prettyFormatting) {
107-
stringified = jju.stringify(jsonObject, {
129+
if (previousJson !== '') {
130+
stringified = jju.update(previousJson, newJsonObject, {
131+
mode: 'json',
132+
indent: 2
133+
});
134+
} else if (options.prettyFormatting) {
135+
stringified = jju.stringify(newJsonObject, {
108136
mode: 'json',
109137
indent: 2
110-
}) + '\n';
138+
});
111139
} else {
112-
stringified = JSON.stringify(jsonObject, undefined, 2) + '\n';
140+
stringified = JSON.stringify(newJsonObject, undefined, 2);
113141
}
114142

143+
// Add the trailing newline
144+
stringified = Text.ensureTrailingNewline(stringified);
145+
115146
if (options && options.newlineConversion) {
116147
switch (options.newlineConversion) {
117148
case NewlineKind.CrLf:
@@ -131,28 +162,42 @@ export class JsonFile {
131162
* @param options - other settings that control how the file is saved
132163
* @returns false if ISaveJsonFileOptions.onlyIfChanged didn't save anything; true otherwise
133164
*/
134-
public static save(jsonObject: Object, jsonFilename: string, options: IJsonFileSaveOptions = {}): boolean {
135-
const normalized: string = JsonFile.stringify(jsonObject, options);
136-
137-
const buffer: Buffer = new Buffer(normalized); // utf8 encoding happens here
165+
public static save(jsonObject: Object, jsonFilename: string, options?: IJsonFileSaveOptions): boolean {
166+
if (!options) {
167+
options = { };
168+
}
138169

139-
if (options.onlyIfChanged) {
140-
// Has the file changed?
170+
// Do we need to read the previous file contents?
171+
let oldBuffer: Buffer | undefined = undefined;
172+
if (options.updateExistingFile || options.onlyIfChanged) {
141173
if (FileSystem.exists(jsonFilename)) {
142174
try {
143-
const oldBuffer: Buffer = FileSystem.readFileToBuffer(jsonFilename);
144-
if (Buffer.compare(buffer, oldBuffer) === 0) {
145-
// Nothing has changed, so don't touch the file
146-
return false;
147-
}
175+
oldBuffer = FileSystem.readFileToBuffer(jsonFilename);
148176
} catch (error) {
149177
// Ignore this error, and try writing a new file. If that fails, then we should report that
150178
// error instead.
151179
}
152180
}
153181
}
154182

155-
FileSystem.writeFile(jsonFilename, buffer.toString(), {
183+
let jsonToUpdate: string = '';
184+
if (options.updateExistingFile && oldBuffer) {
185+
jsonToUpdate = oldBuffer.toString();
186+
}
187+
188+
const newJson: string = JsonFile.updateString(jsonToUpdate, jsonObject, options);
189+
190+
const newBuffer: Buffer = new Buffer(newJson); // utf8 encoding happens here
191+
192+
if (options.onlyIfChanged) {
193+
// Has the file changed?
194+
if (oldBuffer && Buffer.compare(newBuffer, oldBuffer) === 0) {
195+
// Nothing has changed, so don't touch the file
196+
return false;
197+
}
198+
}
199+
200+
FileSystem.writeFile(jsonFilename, newBuffer.toString(), {
156201
ensureFolderExists: options.ensureFolderExists
157202
});
158203

‎libraries/node-core-library/typings/jju/jju.d.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ interface IJjuParseOptions {
66
reserved_keys? : 'ignore' | 'throw' | 'replace';
77
null_prototype?: boolean;
88
reviver?: (key: any, value: any) => any;
9-
mode?: 'json';
9+
mode?: 'json' | 'json5' | undefined;
1010
}
1111

1212
interface IJjuStringifyOptions {
@@ -16,10 +16,14 @@ interface IJjuStringifyOptions {
1616
sort_keys?: boolean;
1717
replacer?: (key: string, value: any) => any;
1818
no_trailing_comma?: boolean;
19-
mode?: string | 'json';
19+
mode?: 'json' | 'json5' | undefined;
20+
}
21+
22+
interface IJjuUpdateOptions extends IJjuParseOptions, IJjuStringifyOptions {
2023
}
2124

2225
declare module 'jju' {
2326
export function parse(text: string, options?: IJjuParseOptions): any;
2427
export function stringify(value: any, options?: IJjuStringifyOptions): string;
28+
export function update(text: string, new_value: any, options: IJjuUpdateOptions): string;
2529
}

0 commit comments

Comments
 (0)