-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
224 lines (198 loc) · 5.87 KB
/
index.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
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
/// Replacer
const replace = require("replace-in-file");
const util = require("util");
const { promises: fs } = require("fs");
const path = require("path");
interface myArgs {
h: boolean | undefined;
dir: string | undefined;
in: string | undefined;
all: boolean | undefined;
ext: string | undefined;
notext: string | undefined;
d: boolean | undefined;
dry: boolean | undefined;
}
interface replaced {
file: string;
numMatches: number;
numReplacements: number;
hasChanged: boolean;
}
/// Recursively finds all files in a directory.
const walk = async (
dir: string,
showHidden: boolean,
allowedExtensions: string[],
disallowedExtensions: string[]
) => {
let entries = await fs.readdir(dir);
if (showHidden) {
/// Removes hidden files / folders
entries = entries.filter((item) => !/(^|\/)\.[^\/\.]/g.test(item));
}
let ret: string[] = [];
/// Loop through all items found in current dir
for (const entry of entries) {
const fullpath: string = path.resolve(dir, entry);
const info = await fs.stat(fullpath);
if (info.isDirectory()) {
/// If item is directory, recurse.
ret = [
...ret,
...(await walk(
fullpath,
showHidden,
allowedExtensions,
disallowedExtensions
)),
];
} else if (
checkExtAllowed(fullpath, allowedExtensions) &&
checkExtDisallowed(fullpath, disallowedExtensions)
) {
/// Checks if file name is allowed (or not disallowed)
ret = [...ret, fullpath];
}
}
return ret;
};
/// True if file extension is on allowed list, or if list is empty.
const checkExtAllowed = (name: string, extensions: string[]): boolean => {
const ext: string = path.extname(name).substring(1);
return extensions.includes(ext) || extensions.length == 0;
};
/// True if file extension is not on disallowed list, or if list is empty.
const checkExtDisallowed = (name: string, extensions: string[]): boolean => {
const ext = path.extname(name).substring(1);
return !extensions.includes(ext) || extensions.length == 0;
};
/// Runs replacement.
const runReplacer = async (
dir: string,
from: RegExp[],
to: string[],
showHidden: boolean,
allowedExtensions: string[],
disallowedExtensions: string[],
dry: boolean
) => {
/// Recursive function to find all files to be searched.
const allFiles = await walk(
dir,
showHidden,
allowedExtensions,
disallowedExtensions
);
/// Config object for replace-in-file.
const options = {
files: allFiles,
from: from,
to: to,
countMatches: true,
dry: dry,
};
/// Make the replacements.
const x: replaced[] = replace.sync(options);
/// Changed file counter.
let count = 0;
/// Format string output
const output: string = x
.map((e: replaced) => {
const str = e.hasChanged
? `\n${e.file.split("/").at(-1)}: ${e.numReplacements} replacements`
: undefined;
if (str) count++;
return str;
})
.join("");
process.stdout.write(output);
if (dry) {
process.stdout.write(`\n\n${count} files to be changed\n\n`);
} else {
process.stdout.write(`\n\n${count} files changed\n\n`);
}
};
/// Prints helps to console.
const showHelp = () => {
process.stdout.write("\n\nreplacer \n \n\n");
process.stdout.write("params: \n \n\n");
process.stdout.write("--dir directory for replacements \n");
process.stdout.write(
"--in json of replacement key value pairs. either direct json or path to file\n"
);
process.stdout.write(
"--a search all, including hidden files and folders\n"
);
process.stdout.write(
"--ext comma seperated list of allowed extensions\n"
);
process.stdout.write(
"--notext comma seperated list of disallowed extensions\n"
);
process.stdout.write("--dry perform a dry-run\n");
process.stdout.write("--d run in debug mode\n");
process.stdout.write(
"--h show this small and not very useful help screen \n"
);
process.stdout.write("\n\n\n\n");
};
// ------------------------------------------------------------
/// Load cmd line args.
const argv: myArgs = require("minimist")(process.argv.slice(2));
if (argv.h) {
showHelp();
} else {
/// Load variables
const dir: string = argv.dir ?? ".";
const showHidden: boolean = argv.all ?? false;
let allowedExtensions: string[];
let disallowedExtensions: string[];
let from: RegExp[];
let to: string[];
try {
allowedExtensions = argv.ext != undefined ? argv.ext.split(",") : [];
} catch (err) {
process.stdout.write("Error: allowed extensions bad format");
if (argv.d) process.stdout.write(`\n\n${err}`);
}
try {
disallowedExtensions =
argv.notext != undefined ? argv.notext.split(",") : [];
} catch (err) {
process.stdout.write("Error: disallowed extensions bad format");
if (argv.d) process.stdout.write(`\n\n${err}`);
}
if (argv.in != undefined && argv.in.includes(".json")) {
try {
const variables = require(argv.in);
from = Object.keys(variables).map((w) => {
w = w.replaceAll("(", "\\(");
w = w.replaceAll(")", "\\)");
w = w.replaceAll("[", "\\[");
w = w.replaceAll("]", "\\]");
return RegExp(w, "g");
});
to = Object.values(variables);
} catch (err) {
process.stdout.write("Error: Input file error");
if (argv.d) process.stdout.write(`\n\n${err}`);
}
if (argv.d) {
process.stdout.write(
`\n\ndirectory: ${dir}\n\nshowHidden: ${showHidden}\n\nextensions: ${allowedExtensions}\n\ndisallowed extensions: ${disallowedExtensions}\n\nparams from: ${from}\n\nparams to: ${to}`
);
}
runReplacer(
dir,
from,
to,
showHidden,
allowedExtensions,
disallowedExtensions,
argv.dry ?? false
);
} else {
process.stdout.write("Error: Input file error");
}
}