-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathapi.js
More file actions
138 lines (111 loc) · 3.45 KB
/
api.js
File metadata and controls
138 lines (111 loc) · 3.45 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
import process from 'node:process';
import path from 'node:path';
import {promises as fs} from 'node:fs';
import normalizePath_ from 'normalize-path';
import writeFileAtomic from 'write-file-atomic';
import escapeStringRegexp from 'escape-string-regexp';
import {globby} from 'globby';
const normalizePath = process.platform === 'win32' ? normalizePath_ : x => x;
const toArray = value => {
if (value === undefined) {
return [];
}
return Array.isArray(value) ? value : [value];
};
const normalizeRegex = (pattern, forceIgnoreCase) => {
if (!(pattern instanceof RegExp)) {
throw new TypeError('Expected a RegExp');
}
const flags = new Set(pattern.flags);
flags.add('g');
// Override case handling
if (forceIgnoreCase) {
flags.add('i');
} else if (forceIgnoreCase === false) {
flags.delete('i');
}
return new RegExp(pattern.source, [...flags].join(''));
};
/**
Replace matching strings and regexes in files.
- If `find` is provided, `replacement` must be a string.
- If `transform` is provided, it runs after all find/replace operations.
- When `dryRun` is true, returns a list of proposed changes.
*/
export default async function replaceInFiles(
inputPaths,
{
find,
replacement,
ignoreCase = false,
glob = true,
dryRun = false,
transform,
} = {},
) {
const filePathPatterns = toArray(inputPaths);
if (transform !== undefined && typeof transform !== 'function') {
throw new TypeError('The `transform` option must be a function');
}
const hasFind = Array.isArray(find) && find.length > 0;
const hasTransform = typeof transform === 'function';
if (!hasFind && !hasTransform) {
throw new Error('Expected at least one `find` pattern or a `transform` function');
}
if (hasFind && typeof replacement !== 'string') {
throw new TypeError('Expected `replacement` to be a string when `find` is provided');
}
// Resolve file paths
let filePaths;
if (glob) {
const patterns = filePathPatterns.map(p => normalizePath(p));
// TODO: Look into using built-in glob when targeting Node.js 24.
filePaths = await globby(patterns, {dot: true, absolute: true, expandDirectories: false});
} else {
filePaths = filePathPatterns.map(p => path.resolve(String(p)));
}
// De-duplicate
filePaths = [...new Set(filePaths)];
// Replace escape sequences in replacement if we have find patterns
if (hasFind && typeof replacement === 'string') {
replacement = replacement
.replaceAll(String.raw`\n`, '\n')
.replaceAll(String.raw`\r`, '\r')
.replaceAll(String.raw`\t`, '\t');
}
// Prepare replacers
const replacers = hasFind
? toArray(find).map(pattern => {
if (typeof pattern === 'string') {
const flags = ignoreCase ? 'gi' : 'g';
return new RegExp(escapeStringRegexp(pattern), flags);
}
return normalizeRegex(pattern, ignoreCase);
})
: [];
const changes = [];
await Promise.all(filePaths.map(async filePath => {
const originalContent = await fs.readFile(filePath, 'utf8');
let nextContent = originalContent;
for (const rx of replacers) {
nextContent = nextContent.replace(rx, replacement);
}
if (hasTransform) {
nextContent = transform(nextContent, filePath);
if (typeof nextContent !== 'string') {
throw new TypeError('`transform` must return a string');
}
}
if (nextContent === originalContent) {
return;
}
if (dryRun) {
changes.push({filePath, originalContent, newContent: nextContent});
return;
}
await writeFileAtomic(filePath, nextContent);
}));
if (dryRun) {
return changes;
}
}