forked from OKEAMAH/prettier
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.js
More file actions
120 lines (106 loc) · 2.37 KB
/
Copy pathutils.js
File metadata and controls
120 lines (106 loc) · 2.37 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import fs from "node:fs/promises";
import path from "node:path";
import sdbm from "sdbm";
// @ts-expect-error
import { __internal as sharedWithCli } from "../index.js";
// eslint-disable-next-line no-console
const printToScreen = console.log.bind(console);
/**
* @template Obj
* @template Key
* @param {Array<Obj>} array
* @param {(value: Obj) => Key} iteratee
* @returns {{[p in Key]: T}}
*/
function groupBy(array, iteratee) {
const result = Object.create(null);
for (const value of array) {
const key = iteratee(value);
if (Array.isArray(result[key])) {
result[key].push(value);
} else {
result[key] = [value];
}
}
return result;
}
/**
* @template Obj
* @template {keyof Obj} Keys
* @param {Obj} object
* @param {Array<Keys>} keys
* @returns {{[key in Keys]: Obj[key]}}
*/
function pick(object, keys) {
const entries = keys.map((key) => [key, object[key]]);
return Object.fromEntries(entries);
}
/**
* @param {string} source
* @returns {string}
*/
function createHash(source) {
return String(sdbm(source));
}
/**
* Get stats of a given path.
* @param {string} filePath The path to target file.
* @returns {Promise<import('fs').Stats | undefined>} The stats.
*/
async function statSafe(filePath) {
try {
return await fs.stat(filePath);
} catch (/** @type {any} */ error) {
/* c8 ignore next 3 */
if (error.code !== "ENOENT") {
throw error;
}
}
}
/**
* Get stats of a given path without following symbolic links.
* @param {string} filePath The path to target file.
* @returns {Promise<import('fs').Stats | undefined>} The stats.
*/
async function lstatSafe(filePath) {
try {
return await fs.lstat(filePath);
} catch (/** @type {any} */ error) {
/* c8 ignore next 3 */
if (error.code !== "ENOENT") {
throw error;
}
}
}
/**
* @param {string} value
* @returns {boolean}
*/
function isJson(value) {
try {
JSON.parse(value);
return true;
} catch {
return false;
}
}
/**
* Replace `\` with `/` on Windows
* @param {string} filepath
* @returns {string}
*/
const normalizeToPosix =
path.sep === "\\"
? (filepath) => filepath.replaceAll("\\", "/")
: (filepath) => filepath;
export const { isNonEmptyArray, partition, omit } = sharedWithCli.utils;
export {
createHash,
groupBy,
isJson,
lstatSafe,
normalizeToPosix,
pick,
printToScreen,
statSafe,
};