-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.ts
More file actions
308 lines (263 loc) · 8.58 KB
/
index.ts
File metadata and controls
308 lines (263 loc) · 8.58 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
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
/*
* MIT License
*
* Copyright (c) 2023-2025 Falcion
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Any code and/or API associated with OBSIDIAN behaves as stated in their distribution policy.
*/
import * as os from 'os'
import * as path from 'path'
import * as fs from 'fs-extra'
import * as readline from 'readline'
import chalk from 'chalk'
import { WriteStream, readFileSync, createWriteStream } from 'fs'
/*
* Declaring unsupport for macOS, iOS and any related types of platforms.
*/
if (os.type() === 'Darwin') process.abort()
/**
* @class
* Represents a logger utility for logging messages with different severity levels and chalk.
*/
export class LOCALE_LOGGER {
/**
* A process ID which represents session of localized logger instance.
* @type {number}
*/
private readonly session_id: number = process.ppid
/**
* Logs the info message.
* @param {...unknown} data - The data to be logged.
*/
public info(...data: unknown[]): void {
console.info(chalk.blue(this.parseData(data)))
}
/**
* Logs the warn message.
* @param {...unknown} data - The data to be logged.
*/
public warn(...data: unknown[]): void {
console.warn(chalk.yellow(this.parseData(data)))
}
/**
* Logs the error message.
* @param {...unknown} data - The data to be logged.
*/
public error(...data: unknown[]): void {
console.error(chalk.bgRed(chalk.white(this.parseData(data))))
}
/**
* Logs the success message.
* @param {...unknown} data - The data to be logged.
*/
public success(...data: unknown[]): void {
console.log(chalk.green(this.parseData(data)))
}
/**
* Logs the message with custom color.
* @param {(str: string) => string} color - The color function.
* @param {...unknown} data - The data to be logged.
*/
public raw(color: (str: string) => string, ...data: unknown[]): void {
console.debug(color(this.parseData(data)))
}
/**
* Formats a message with custom color.
* @param {(str: string) => string} color - The color function.
* @param {string} message - The message to be formatted.
* @returns {string} The formatted message.
*/
public msg(color: (str: string) => string, message: string): string {
return color(message)
}
private parseData(...data: unknown[]): string {
const ctx = data
.map((item) => (typeof item === 'object' ? JSON.stringify(item, null, 2) : String(item)))
.join(' ')
return `[${new Date().toLocaleString()}] < ${this.session_id} > \t - ${ctx}`
}
}
/**
* @class
* Represents a module for searching and updating files.
*/
export default class LOCALE_MODULE {
/**
* The root directory of the module.
* @type {string}
*/
public ROOT_DIRECTORY: string = __dirname
/**
* Directories to be excluded from traversal.
* @type {string[]}
*/
private EXCLUDING_FOLDERS: string[] = [
'node_modules',
'dist',
'venv',
'.git',
'$git',
'$',
'out',
'bin'
]
/**
* Values to be excluded from file content search.
* @type {string[]}
*/
private readonly EXCLUDING_VALUES: string[] = [
'FALCION',
'PATTERNU',
'PATTERNUGIT',
'PATTERNUGIT.NET'
]
public readonly LOGGER: LOCALE_LOGGER = new LOCALE_LOGGER()
/** **THIS IS A MAIN CONFIG FOR THIS SCRIPT
* ONLY EDIT THIS VALUES.**
**/
public CONFIG = {
USE_GITIGNORE: true,
/**
* Path to your gitignore from the root, relative to
* the script's directory.
*/
GITIGNORE_PATH: './.gitignore',
/**
* Path to the future logs of the locale module: by default is static of
* config's value.
*/
LOGS_FILE: `preparations-${new Date().toLocaleDateString()}.logs`
}
constructor(
path: string = this.CONFIG.LOGS_FILE,
ignoreUse: boolean = this.CONFIG.USE_GITIGNORE,
ignorePath: string = this.CONFIG.GITIGNORE_PATH
) {
this.CONFIG.LOGS_FILE = path
this.CONFIG.USE_GITIGNORE = ignoreUse
this.CONFIG.GITIGNORE_PATH = ignorePath
}
/**
* Updates the exclusion settings based on user input.
* @param {string[]} entries - Entries to be added to the exclusion list.
* @param {string} actions - User action (Y or N).
*/
public update(entries: string[], actions: string): void {
if (actions.length > 1) {
throw new RangeError('Action input must be a char.')
}
if (actions === 'Y') {
for (const entry of entries) {
this.EXCLUDING_VALUES.push(entry)
}
}
if (actions === 'N') {
this.EXCLUDING_FOLDERS = entries
}
if (this.CONFIG.USE_GITIGNORE) {
const gitignore = readFileSync('.gitignore').toString().split('\n')
gitignore.forEach((line) => {
if (line[0] !== '#' && line[0] !== '!') {
this.EXCLUDING_FOLDERS.push(line)
}
})
}
fs.ensureFileSync(this.CONFIG.LOGS_FILE)
}
/**
* Searches for specified words in file contents.
* @param {string} filepath - The path of the file to search.
* @param {string[]} data - Words to search for.
* @returns {Promise<void>} A promise representing the search operation.
*/
public async search(filepath: string, data: string[]): Promise<void> {
const buffer: string = await fs.readFile(filepath, { encoding: 'utf-8' })
const stream: WriteStream = createWriteStream(this.CONFIG.LOGS_FILE, { flags: 'a' })
const contents: string[] = buffer.split(os.EOL)
for (let i = 0; i < contents.length; i++) {
const line = contents[i].toUpperCase()
for (const target of data) {
if (line.includes(target)) {
this.LOGGER.raw(chalk.green, `Found "${target}" in L#${i} of: `)
this.LOGGER.raw(chalk.cyan, filepath)
stream.write(`Found "${target}" in L#${i} of:` + os.EOL)
stream.write(`\t${filepath}` + os.EOL)
}
}
}
stream.end()
}
/**
* Traverses directories and searches files for specified words.
* @param {string} directory - The directory to start traversal from.
* @returns {Promise<void>} A promise representing the traversal operation.
*/
public async traverse(directory: string = __dirname): Promise<void> {
try {
const items: string[] = await fs.readdir(directory)
for (const item of items) {
const itempath = path.join(directory, item)
const itemstats = await fs.stat(itempath)
if (itemstats.isDirectory()) {
if (!this.EXCLUDING_FOLDERS.includes(item)) {
await this.traverse(itempath)
}
} else if (itemstats.isFile()) {
await this.search(itempath, this.EXCLUDING_VALUES)
} else {
continue
}
}
} catch (err: unknown) {
this.LOGGER.error(err)
}
}
}
export const ask = async (rl: readline.Interface, question: string): Promise<string> => {
return await new Promise((resolve) => {
rl.question(question, resolve)
})
}
void (async () => {
const RL = readline.createInterface({
input: process.stdin,
output: process.stdout
})
void (async () => { })
try {
const finder = new LOCALE_MODULE()
const mode = await ask(RL, chalk.bgBlue(chalk.yellow('Add custom entries (Y/N/IGNORE): ')))
if (mode.toUpperCase() === 'Y') {
const params = await ask(RL, 'Enter parameters (comma-separated): ')
const diction = params.split(',').map((str) => str.trim())
finder.update(diction, mode.toUpperCase())
await finder.traverse()
} else if (mode.toUpperCase() === 'N') {
await finder.traverse()
}
} catch (error) {
console.error(
chalk.red(typeof error === 'object' ? JSON.stringify(error, null, 2) : String(error))
)
} finally {
RL.close()
}
})()