From 1e364bd00c4b2e7a99f495a83df16e751ad34fac Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Fri, 5 Jan 2024 09:04:42 +0000 Subject: [PATCH] fix(@schematics/angular): retain existing EOL when updating JSON files This commit updates the JSON utility to retain the existing EOF when updating files. --- packages/schematics/angular/utility/eol.ts | 25 +++++++++++++++++++ .../schematics/angular/utility/json-file.ts | 10 +++++++- 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 packages/schematics/angular/utility/eol.ts diff --git a/packages/schematics/angular/utility/eol.ts b/packages/schematics/angular/utility/eol.ts new file mode 100644 index 000000000000..8e9de0b699d2 --- /dev/null +++ b/packages/schematics/angular/utility/eol.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import { EOL } from 'node:os'; + +const CRLF = '\r\n'; +const LF = '\n'; + +export function getEOL(content: string): string { + const newlines = content.match(/(?:\r?\n)/g); + + if (newlines?.length) { + const crlf = newlines.filter((l) => l === CRLF).length; + const lf = newlines.length - crlf; + + return crlf > lf ? CRLF : LF; + } + + return EOL; +} diff --git a/packages/schematics/angular/utility/json-file.ts b/packages/schematics/angular/utility/json-file.ts index 3aebc5d24dcc..18536abb57aa 100644 --- a/packages/schematics/angular/utility/json-file.ts +++ b/packages/schematics/angular/utility/json-file.ts @@ -18,6 +18,7 @@ import { parseTree, printParseErrorCode, } from 'jsonc-parser'; +import { getEOL } from './eol'; export type InsertionIndex = (properties: string[]) => number; export type JSONPath = (string | number)[]; @@ -25,9 +26,14 @@ export type JSONPath = (string | number)[]; /** @private */ export class JSONFile { content: string; + private eol: string; - constructor(private readonly host: Tree, private readonly path: string) { + constructor( + private readonly host: Tree, + private readonly path: string, + ) { this.content = this.host.readText(this.path); + this.eol = getEOL(this.content); } private _jsonAst: Node | undefined; @@ -81,7 +87,9 @@ export class JSONFile { const edits = modify(this.content, jsonPath, value, { getInsertionIndex, + formattingOptions: { + eol: this.eol, insertSpaces: true, tabSize: 2, },