-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeeper.js
executable file
·288 lines (246 loc) · 8.33 KB
/
deeper.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
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
#!/usr/bin/env node
const fs = require("fs")
const path = require("path")
const child_process = require("child_process")
const yargs = require("yargs/yargs")
const { hideBin } = require("yargs/helpers")
const moment = require("moment")
const cwd = process.cwd()
const readline = require("readline")
const rimraf = require("rimraf")
const storage = require("node-persist")
async function exec(...args) {
const chalk = (await import("chalk")).default
console.log(chalk.gray(`> ${args[0]}`))
child_process.execSync(...args)
}
function addToGitignore(file) {
const gitignorePath = path.join(cwd, ".gitignore")
if (fs.existsSync(gitignorePath)) {
const gitignore = fs.readFileSync(gitignorePath, "utf8")
if (!gitignore.includes(file)) {
fs.appendFileSync(gitignorePath, `\n${file}`)
}
} else {
fs.writeFileSync(gitignorePath, `${file}\n`)
}
}
// Function to prompt the user
function promptUser(prompt) {
return new Promise((resolve) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
rl.question(prompt, (answer) => {
rl.close()
resolve(answer.toLowerCase() === "y")
})
})
}
async function isHuskyInstalled() {
try {
// Attempt to list the version of husky
// If husky is not installed, this command will throw an error
await exec("npx --no husky -v", { stdio: "ignore" })
return true
} catch {
// If the command throws an error, husky is not installed
return false
}
}
async function main() {
const chalk = (await import("chalk")).default
const argv = yargs(hideBin(process.argv))
.command(
"<npm-dependency>",
"replace a package with a symlink to a git repo",
)
.command("sync", "build and sync all packages in .deeper to this project")
.command("clean", "clean out all cloned deeper packages in node_modules")
.help().argv
const deeperDir = path.join(cwd, ".deeper")
await storage.init({ dir: path.join(deeperDir, ".config") })
const nodeModulesDir = path.join(cwd, "node_modules")
if (!fs.existsSync(deeperDir)) {
console.log(
chalk.yellow(
"No .deeper directory, this may be your first time running deeper in this project",
),
)
if (!(await isHuskyInstalled())) {
if (
await promptUser(
"Husky is not installed globally. Would you like to make sure this project does not get yalc links accidentally committed and install husky? (y/n) ",
)
) {
await exec("npx husky install")
}
}
if (!fs.existsSync(path.join(cwd, ".husky"))) {
if (await promptUser(`Install the "yalc check" precommit hook?`)) {
await exec(`npx husky add .husky/pre-commit "yalc check"`)
await exec(`git add .husky/pre-commit`)
await exec(`git commit -m "added husky to check for yalc issues"`)
}
}
fs.mkdirSync(deeperDir, { recursive: true })
}
const dep = argv._[0]
const syncList = (await storage.getItem("synclist")) ?? []
if (dep === "sync") {
console.log(
chalk.green(
`Syncing ${syncList
.map((s) => `.deeper/${s}`)
.join(",")} to this project...`,
),
)
if (!fs.existsSync(deeperDir)) {
console.log(chalk.red("No .deeper directory found"))
process.exit(1)
}
if (syncList.length === 0) {
console.log(
chalk.red(
`Sync list is empty (try "deeper <package>" to add to the sync list)`,
),
)
process.exit(1)
}
const deeperDirFiles = fs.readdirSync(deeperDir)
const scopedPackageFiles = []
for (const fileOrDir of deeperDirFiles) {
if (fileOrDir === ".config") continue
const deeperPackageJson = path.join(fileOrDir, "package.json")
if (!fs.existsSync(deeperPackageJson)) {
scopedPackageFiles.push(
...fs
.readdirSync(path.join(deeperDir, fileOrDir))
.map((p) => path.join(fileOrDir, p)),
)
}
}
deeperDirFiles.push(...scopedPackageFiles)
for (const file of deeperDirFiles) {
const deeperPackageDir = path.join(deeperDir, file)
const deeperPackageJson = path.join(deeperPackageDir, "package.json")
if (fs.existsSync(deeperPackageJson)) {
if (!syncList.includes(file)) {
console.log(chalk.gray(`Skipping ${file} (not in synclist)`))
continue
}
console.log(chalk.green(`Syncing ${file}`))
const pkg = require(deeperPackageJson)
console.log(chalk.green(`Installing ${file}`))
await exec(`cd ${deeperPackageDir} && npm install`)
if (pkg.scripts?.build) {
console.log(chalk.green(`Building ${file}`))
await exec(`cd ${deeperPackageDir} && npm run build`)
}
console.log(
chalk.gray(`Adding the "${file}" to this project via yalc...`),
)
await exec(`cd ${deeperPackageDir} && yalc publish`)
await exec(`yalc add ${file}`)
console.log(chalk.green(`Done syncing ${file}!`))
}
}
return
} else if (dep === "clean") {
console.log(
chalk.green(`Cleaning out all cloned deeper packages in node_modules...`),
)
child_process.execSync("yalc remove --all")
await storage.removeItem("synclist")
console.log(
chalk.green(`Running npm install to restore original packages...`),
)
child_process.execSync("npm install")
console.log(chalk.green(`Done!`))
return
}
if (!dep) {
console.log(chalk.red("Please provide a valid npm dependency"))
process.exit(1)
}
addToGitignore(".deeper")
addToGitignore(".yalc")
addToGitignore("yalc.lock")
const nodeModulePath = path.join(nodeModulesDir, dep)
const pkgPath = path.join(nodeModulePath, "package.json")
const gitPath = path.join(deeperDir, dep)
if (!fs.existsSync(pkgPath)) {
console.log(chalk.red(`Could not find ${dep} in node_modules`))
process.exit(1)
}
const pkg = require(pkgPath)
if (!pkg.repository) {
console.log(chalk.red(`Could not find repository url for ${dep}`))
process.exit(1)
}
if (typeof pkg.repository === "string") {
pkg.repository = { url: pkg.repository }
}
let gitUrl = pkg.repository.url
// If the repository url is just "<org>/<repo>", make it a proper github url
if (gitUrl.match(/^[^/]+\/[^/]+$/)) {
gitUrl = `[email protected]:${gitUrl}`
}
if (gitUrl.startsWith("https://github.com")) {
gitUrl = gitUrl.replace("https://github.com/", "[email protected]:")
}
console.log(chalk.green(`Found repository url for ${dep}: ${gitUrl}`))
if (!fs.existsSync(gitPath)) {
console.log(chalk.green(`Cloning ${gitUrl} to ${gitPath}`))
child_process.execSync(`git clone ${gitUrl} ${gitPath}`)
} else {
console.log(
chalk.yellow(`Repository for ${dep} already exists at ${gitPath}`),
)
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
const answer = await new Promise((resolve) =>
rl.question(
`Would you like to update it, stashing old changes? (default: no)\n`,
(answer) => resolve(answer),
),
)
if (answer.toLowerCase().startsWith("y")) {
const timestamp = moment().format("YYYY-MM-DD-hh-mm")
const stashName = `deeper-stash-${timestamp}`
console.log(
chalk.green(`Stashing changes to "${stashName}" and updating ${dep}`),
)
console.log(
chalk.gray(
`Restore previous changes with 'git stash apply "${stashName}"'`,
),
)
await exec(`cd ${gitPath} && git stash save "${stashName}"`)
// TODO get the remote head with: git remote show origin | grep 'HEAD branch'
await exec(`cd ${gitPath} && git fetch && git checkout origin/main`)
}
rl.close()
}
console.log(chalk.green(`Installing ${dep}`))
await exec(`cd ${gitPath} && npm install`)
if (pkg.scripts?.build) {
console.log(chalk.green(`Building ${dep}`))
await exec(`cd ${gitPath} && npm run build`)
}
console.log(chalk.gray(`Adding the "${dep}" to this project via yalc...`))
await exec(`cd ${gitPath} && yalc publish`)
await exec(`yalc add ${dep}`)
if (!syncList.includes(dep))
await storage.setItem("synclist", [...syncList, dep])
console.log(chalk.green(`Done!`))
console.log(
chalk.green(
`\nRun "deeper sync" to sync your packages!\nEdit the package in ".deeper/${dep}"\n`,
),
)
}
main()