-
-
Notifications
You must be signed in to change notification settings - Fork 199
/
Copy pathnodeUtils.ts
46 lines (36 loc) · 972 Bytes
/
nodeUtils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import os from 'os';
export interface NodeError extends Error {
code: string;
}
function getEndOfLine(content: string) {
const matches = content.match(/\r?\n/g);
if (matches === null)
return os.EOL;
const crlf = matches.filter(nl => nl === `\r\n`).length;
const lf = matches.length - crlf;
return crlf > lf ? `\r\n` : `\n`;
}
export function normalizeLineEndings(originalContent: string, newContent: string) {
return newContent.replace(/\r?\n/g, getEndOfLine(originalContent));
}
function getIndent(content: string) {
const indentMatch = content.match(/^[ \t]+/m);
if (indentMatch) {
return indentMatch[0];
} else {
return ` `;
}
}
function stripBOM(content: string) {
if (content.charCodeAt(0) === 0xFEFF) {
return content.slice(1);
} else {
return content;
}
}
export function readPackageJson(content: string) {
return {
data: JSON.parse(stripBOM(content) || `{}`),
indent: getIndent(content),
};
}