Skip to content

Commit 1e364bd

Browse files
committed
fix(@schematics/angular): retain existing EOL when updating JSON files
This commit updates the JSON utility to retain the existing EOF when updating files.
1 parent 640a76a commit 1e364bd

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.io/license
7+
*/
8+
9+
import { EOL } from 'node:os';
10+
11+
const CRLF = '\r\n';
12+
const LF = '\n';
13+
14+
export function getEOL(content: string): string {
15+
const newlines = content.match(/(?:\r?\n)/g);
16+
17+
if (newlines?.length) {
18+
const crlf = newlines.filter((l) => l === CRLF).length;
19+
const lf = newlines.length - crlf;
20+
21+
return crlf > lf ? CRLF : LF;
22+
}
23+
24+
return EOL;
25+
}

packages/schematics/angular/utility/json-file.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,22 @@ import {
1818
parseTree,
1919
printParseErrorCode,
2020
} from 'jsonc-parser';
21+
import { getEOL } from './eol';
2122

2223
export type InsertionIndex = (properties: string[]) => number;
2324
export type JSONPath = (string | number)[];
2425

2526
/** @private */
2627
export class JSONFile {
2728
content: string;
29+
private eol: string;
2830

29-
constructor(private readonly host: Tree, private readonly path: string) {
31+
constructor(
32+
private readonly host: Tree,
33+
private readonly path: string,
34+
) {
3035
this.content = this.host.readText(this.path);
36+
this.eol = getEOL(this.content);
3137
}
3238

3339
private _jsonAst: Node | undefined;
@@ -81,7 +87,9 @@ export class JSONFile {
8187

8288
const edits = modify(this.content, jsonPath, value, {
8389
getInsertionIndex,
90+
8491
formattingOptions: {
92+
eol: this.eol,
8593
insertSpaces: true,
8694
tabSize: 2,
8795
},

0 commit comments

Comments
 (0)