-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcli.js
executable file
·212 lines (195 loc) · 5.52 KB
/
cli.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
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
#!/usr/bin/env node
const recursive = require("recursive-readdir")
const chalk = require("chalk")
const gitStatus = require("git-status")
const fs = require("fs")
const { execFileSync } = require("child_process")
const debug = require("debug")("app:kebab-ify")
const camelCaseToKebab = (myStr) => {
newStr = myStr.replace(/\s+/g, "-") // Replace spaces because we don't like them
return newStr.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase()
}
const splitpath = (filepath) => {
const parts = filepath.split(/\//)
const file = parts.pop()
const path = parts.join("/")
return [path, file]
}
const fixpath = (p) => {
const [path, file] = splitpath(p)
return `${path.toLowerCase()}/${file}`
}
const ABORT = (msg) => {
const BANG = "\n * * * * * * * FAILED * * * * * * * * *\n\n"
console.error(BANG + msg + "\n" + BANG)
process.exit(1)
}
const skipThese = ["setupTests.*"]
//
// Main line starts here
//
const paths = {}
const opts = {
git: true,
}
const fixedfiles = []
// Path renames we did already
const gitcommands = ["#!/bin/bash"]
const reg = new RegExp(/from\s+['"](.*)['"]/)
const [, , ...args] = process.argv
const target = args[0] || "src"
if (!fs.existsSync(target)) {
console.error(
`Directory ${chalk.bgRed.yellow.underline(target)} does not exist`
)
process.exit(1)
}
// Check on git status - can't proceed if we are dirty
gitStatus((err, data) => {
if (err) {
if (err.match(/not a git repository/i)) {
opts.git = false
} else {
ABORT(err)
}
}
// data contains an array of dirty files, we worry about Modified files only
// [ { x: ' ', y: 'M', to: 'example/index.js', from: null } ]
const dirty = []
if (data) {
data.forEach((row) => {
if (row.from || row.y === "M") {
dirty.push(row.to)
}
})
}
if (dirty.length) {
ABORT(
"Git is showing " +
dirty.length +
" dirty files, (" +
dirty.join(", ") +
") please fix and retry"
)
}
// Good to go...
pass1()
})
const pass1 = () => {
recursive(target, skipThese, function (err, files) {
// `files` is an array of file paths
debug({ files })
files.forEach((filename) => {
const [path, file] = splitpath(filename)
const dirs = path.split("/")
dirs.pop() // Lose the last one
let tp = ""
dirs.forEach((dir) => {
tp = `${tp}${dir}/`
if (dir.match(/[A-Z]/)) {
const trimtp = tp.replace(/\/$/, "")
if (!paths[trimtp]) {
paths[trimtp] = trimtp.toLowerCase()
gitcommands.push(`mv '${trimtp}' '${trimtp.toLowerCase()}'`)
}
}
})
const newpath = camelCaseToKebab(path)
console.log(`[${path}] [${newpath}]`)
if (path !== newpath && !paths[path]) {
paths[path] = newpath
if (!newpath.match(/\-/)) {
const tmppath = `${newpath}.temp-rename`
gitcommands.push(`mv '${fixpath(path)}' '${tmppath}'`)
gitcommands.push(`mv '${tmppath}' '${newpath}'`)
} else {
gitcommands.push(`mv '${fixpath(path)}' '${newpath}'`)
}
}
const newfile = camelCaseToKebab(file)
if (file !== newfile) {
if (!newfile.match(/\-/)) {
const tmpfile = `${newfile}.temp-rename`
gitcommands.push(`mv '${newpath}/${file}' '${newpath}/${tmpfile}'`)
gitcommands.push(`mv '${newpath}/${tmpfile}' '${newpath}/${newfile}'`)
} else {
gitcommands.push(`mv '${newpath}/${file}' '${newpath}/${newfile}'`)
}
}
})
//
// Do the first stage, rename the files
//
const cmdfile = `${process.cwd()}/git-rename-commands.sh`
// If there were any files or folders to rename, do it now
if (gitcommands.length > 1) {
fs.writeFileSync(
cmdfile,
gitcommands
.map((cmd) => {
return opts.git ? `git ${cmd}` : cmd
})
.join("\n"),
{
encoding: "utf8",
mode: 0o766,
}
)
const res = execFileSync(cmdfile, { cwd: process.cwd() })
} else {
console.error("No files or folders to rename")
process.exit(1)
}
//
// Make another pass, modifying the imports statements in each file
// according to the same renaming logic
//
recursive(target, skipThese, function (err, srcfiles) {
// `srcfiles` is an array of file paths
srcfiles.forEach((f) => {
const lines = fs.readFileSync(f, "utf8").split(/\n/)
let dirty = false
const newbuf = lines
.map((line) => {
let newline = line
const m = line.match(reg)
if (m) {
const newfile = camelCaseToKebab(m[1])
if (m[1] !== newfile) {
newline = line.replace(reg, `from '${newfile}'`)
dirty = true
}
}
return newline
})
.join("\n")
if (dirty) {
fixedfiles.push(f)
fs.writeFileSync(f, newbuf)
}
})
//
// Now is the moment to report on what we did
//
const reportfile = "kebab-ify.log"
const contents = `Kebab-ification report
File/folder renames:
${
Object.keys(paths).length
? Object.keys(paths)
.map((p) => ` * ${p} => ${paths[p]}`)
.join("\n")
: "(None)"
}
Files modified:
${
fixedfiles.length
? `${fixedfiles.map((f) => ` * ${f}`).join("\n")}`
: "(None)"
}
`
fs.writeFileSync(reportfile, contents)
console.log(chalk.bgGreen.black(" Done "))
})
})
}