-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
163 lines (137 loc) · 4.88 KB
/
index.js
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
import inquirer from 'inquirer'
import program from 'commander'
import colors from 'colors'
import path from 'path'
import { reader, parser, replacer, outputer } from './lib'
let excludePaths = []
let excludePatterns = []
const collectExcludePaths = (value) => excludePaths = [...excludePaths, value]
const collectExcludePatterns = (value) => excludePatterns = [...excludePatterns, value]
program
.version('1.0.0')
.option('--cwd, --workingDir <workingDir>', 'Current working directory (where your files are).')
.option('--e, --excludePaths [excludePaths]', 'One or many paths (or globs) you want to exclude, i.e. `-e "prefix-*"`. Can be applied multiple times: `-e "one" -e "two"`.', collectExcludePaths)
.option('--o, --outputDir <outputDir>', 'The output directory.')
.option('--s, --search <search>', 'The string you want to search for, i.e. "../"')
.option('--r, --replace <replace>', 'The string you want to replace each occurrence of the search string with.')
.option('--ep, --excludePatterns <excludePatterns>', 'One or many regular expressions that you want to exclude from each matched search item, i.e. `-ep "iron.*"`. Can be applied multiple times: `-ep "one" -ep "two"`.', collectExcludePatterns)
.parse(process.argv)
async function runtime () {
const { workingDir, excludePaths, outputDir, search, replace, excludePatterns} = program
const fileList = await reader({ workingDir, excludePaths })
const parseResults = await parser({
workingDir,
fileList,
search,
replace,
excludePatterns
})
const allQuestions = parseResults.reduce((acc, cur) => {
const resultQuestion = cur.matches.map((r, i) => {
return {
type: 'confirm',
name: cur.path.replace('.html', `:${i}`), // NB: Dot ('.') will nest the result, avoid it in path.
message: `
Confirm change in ${cur.path}:
${colors.red(`- ${r.line}`)}
${colors.green(`+ ${r.suggestion}`)} \n \n`,
default: true
}
})
return [...acc, ...resultQuestion]
}, [])
const parseAnswers = (answers) => {
const mapAnswerIndexes = (flag) => {
// This method makes it possible to handle true / false values of answers[cur] (flag), without writing the same logic twice.
return (acc, cur) => {
const path = cur.substring(0, cur.lastIndexOf(':')) + '.html'
const index = parseInt(cur.substring(cur.lastIndexOf(':') + 1))
const valid = flag ? answers[cur] : !answers[cur]
if (valid) {
if (!acc[path]) {
acc[path] = [index]
} else {
acc[path] = [...acc[path], index]
}
}
return acc
}
}
/**
* Workflow
* 1. Categorize answers.
* 2. Map categorized answers with their matches.
* 3. Make replaced content & output to file.
*/
const denied = Object
.keys(answers)
.reduce(mapAnswerIndexes(false), {})
const accepted = Object
.keys(answers)
.reduce(mapAnswerIndexes(true), {})
const mapPathToAnswers = (subject) => {
return (item) => {
const matchList = subject[item]
const matches = parseResults
.find((m) => m.path === item)
.matches
.filter((m, i) => matchList.indexOf(i) !== -1)
return {
path: item,
matches
}
}
}
const deniedWithMatches = Object
.keys(denied)
.map(mapPathToAnswers(denied))
const acceptedWithMatches = Object
.keys(accepted)
.map(mapPathToAnswers(accepted))
return Promise
.all(
acceptedWithMatches
.map(async (item) => {
const fullPath = outputDir ? path.join(outputDir, item.path) : item.path
const content = await replacer({
path: item.path,
lines: item.matches
})
return outputer({ content, outputFile: fullPath})
})
)
.then(() => {
if (deniedWithMatches.length) {
console.log(`
⚠️ Some lines were skipped, you might want to check them:
--------------------------------------------------------
`)
deniedWithMatches.forEach((item) => {
console.log(`
File: ${colors.green(item.path)}
Lines:
`)
item.matches.map((m) => console.log(`- ${colors.yellow(m.line)}`))
})
}
const totalReplaced = acceptedWithMatches.reduce((acc, cur) => {
acc += cur.matches.length
return acc
}, 0)
console.log(`
----------------------------------------
✅ aaaaaand done.
Replaced ${colors.blue(totalReplaced)} occurrences of ${colors.red(search)} with ${colors.green(replace)}.`)
})
.catch((e) => console.error(`💥 Failed misserably. \n`, e))
}
return inquirer
.prompt(allQuestions)
.then(parseAnswers)
}
try {
runtime()
} catch (e) {
console.error(e)
console.error('Importer failed misserably ☹. ')
}