-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
441 lines (380 loc) · 11.8 KB
/
main.js
File metadata and controls
441 lines (380 loc) · 11.8 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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
#!/usr/bin/env node
import fs from "fs"
import _ from "colors"
import child_process from "child_process"
import util from "util"
import { resolve } from "path"
const execPromise = util.promisify(child_process.exec)
const usage = `usage: git-ls [options] [/path/to/parent1] [/path/to/parent2] [...]
options:
-h, --help Show this help message and exit
-o, --only-git Only show git repositories
-s, --short Use ⇣⇡↕!+? symbols for status
-i, --ignore Only repo with status flags
-q, --quiet Do not show progress
-v, --verbose Show verbose output
--update Upgrade git-ls with latest version
--upgrade Alias for --update
`
const isInteractive = process.stdout.isTTY
const descriptorsHashMap = {}
const options = {
onlyGit: false,
quiet: !isInteractive,
shortStatusDisplay: false,
onlyWithStatus: false,
verbose: false,
}
let longestFolderName = 0
const main = async () => {
const targets = []
const folders = []
const filteredFolders = []
const args = process.argv.slice(2)
// parse args. First parse options, then when first arg without - or -- is found, parse folders. Allow for multiple -oqetc to be combined
let parametersEnded = false
for (const arg of args) {
if (!parametersEnded && arg.startsWith("-")) {
if (arg === "-h" || arg === "--help") {
console.log(usage)
process.exit(0)
} else if (arg === "--") {
parametersEnded = true
} else if (arg.startsWith("--")) {
// Handle long options
if (arg === "--only-git") {
options.onlyGit = true
} else if (arg === "--quiet") {
options.quiet = true
} else if (arg === "--ignore") {
options.onlyWithStatus = true
} else if (arg === "--short") {
options.shortStatusDisplay = true
} else if (arg === "--verbose") {
options.verbose = true
} else if (arg === "--update" || arg === "--upgrade") {
await doUpdate()
process.exit(0)
} else {
console.error(`Unknown option: ${arg}`)
console.log(usage)
process.exit(1)
}
} else {
// Handle combined short options like -oq
const shortOptions = arg.slice(1).split("")
for (const opt of shortOptions) {
if (opt === "o") {
options.onlyGit = true
} else if (opt === "q") {
options.quiet = true
} else if (opt === "s") {
options.shortStatusDisplay = true
} else if (opt === "v") {
options.verbose = true
} else if (opt === "i") {
options.onlyWithStatus = true
} else {
console.error(`Unknown option: -${opt}`)
console.log(usage)
process.exit(1)
}
}
}
} else {
targets.push(arg)
}
}
if (targets.length === 0) {
targets.push(".")
}
// read folders in each target
for (const target of targets) {
const targetFolders = await fs.promises.readdir(target)
// filter out folders
const targetFilteredFolders = targetFolders
.filter((folder) => {
try {
return fs.lstatSync(`${target}/${folder}`).isDirectory()
} catch {
return false
}
})
.map((e) => {
if (target === ".") return e
else return `${target}/${e}`
})
folders.push(...targetFolders)
filteredFolders.push(...targetFilteredFolders)
}
longestFolderName =
filteredFolders.reduce((acc, folder) => {
return folder.length > acc.length ? folder : acc
}, "").length || 0
// if is interactive
const promises = []
let resolvedPromises = 0
const callback = (d) => {
resolvedPromises++
if (descriptorsHashMap[d.name]) return
descriptorsHashMap[d.name] = d
if (!options.quiet) {
process.stdout.write("\r" + " ".repeat(longestFolderName + 16) + "\r")
process.stdout.write(
`\r (${Object.keys(descriptorsHashMap).length}/${
filteredFolders.length
}) ${d.timeEnd - d.timeStart}ms ${d.name} \r`
)
}
}
for (let i = 0; i < filteredFolders.length; i++) {
promises.push(makeDescriptor(filteredFolders[i]).then(callback))
}
await new Promise((resolve) => setTimeout(resolve, 1000))
// reverse order
for (let i = filteredFolders.length - 1; i >= 0; i--) {
promises.push(makeDescriptor(filteredFolders[i]).then(callback))
}
// wait for all promises to resolve
while (Object.keys(descriptorsHashMap).length < filteredFolders.length) {
await new Promise((resolve) => setTimeout(resolve, 100))
}
const descriptors = Object.values(descriptorsHashMap).filter((e) => {
if (options.onlyWithStatus && e.stateDisplayParts?.length === 0)
return false
if (options.onlyGit && !e.isGit) return false
setLongestName("folder", e.name)
return true
})
// clearTimeout(showRemainingTimeout) // #remaining-timeout
if (!options.quiet)
process.stdout.write("\r" + " ".repeat(longestFolderName + 16) + "\r")
// sort (non-git, alphabetically)
descriptors.sort((a, b) => {
if (a.isGit && !b.isGit) return 1
if (!a.isGit && b.isGit) return -1
return String.prototype.localeCompare.call(a.name, b.name)
})
for (const descriptor of descriptors) {
console.log(descriptor.toString())
}
}
let longestName = {}
const setLongestName = (key, string) => {
if (!longestName[key]) {
longestName[key] = 0
}
if (string.length > longestName[key]) {
longestName[key] = string.length
}
}
const getLongestName = (key) => {
return longestName[key] || 0
}
const padEndName = (key, string, noPaddedStringModifier = (e) => e) => {
return noPaddedStringModifier(string).padEnd(getLongestName(key), " ")
}
const makeDescriptor = async (folder) => {
const d = {
timeStart: Date.now(),
name: folder,
toString() {
this.nameDisplay = padEndName("folder", this.name)
if (!d.isGit)
return (
this.nameDisplay.yellow.italic + " not-a-git-repository".yellow.italic
)
let namePart = this.nameDisplay
if (this.stateDisplayParts.length <= 0) {
namePart = namePart.blue
} else {
namePart = namePart.yellow.bold
}
let branchPart = padEndName("branch", this.branch)
if (this.stateDisplayParts.length > 0) {
branchPart = branchPart.yellow.bold
} else {
branchPart = branchPart.blue
}
let statePart = padEndName("stateDisplay", this.stateDisplay)
if (this.stateDisplay.length > 0) {
statePart = statePart.yellow.bold
}
let originPart = padEndName(
"remoteOriginUrl",
!this.remoteOriginUrl ? "no-remote" : this.remoteOriginUrl
)
if (!this.remoteOriginUrl) {
originPart = originPart.red
} else if (this.needsGitPull) {
originPart = originPart.yellow.bold
} else if (this.stateDisplayParts.length > 0) {
originPart = originPart.blue
} else {
originPart = originPart.blue
}
return `${namePart} ${branchPart} ${statePart} ${originPart}`
},
}
d.isGit = false
try {
await fs.promises.stat(`${folder}/.git`)
d.isGit = true
} catch {}
// if not git, return
if (!d.isGit) {
d.timeEnd = Date.now()
return d
}
d.branch = (
await execPromise(`git -C ${folder} branch --show-current`)
).stdout.trim()
setLongestName("branch", d.branch)
d.isDirty =
(await execPromise(`git -C ${folder} status --porcelain`)).stdout.trim()
.length > 0
try {
d.remoteOriginUrl = (
await execPromise(`git -C ${folder} remote get-url origin`)
).stdout.trim()
setLongestName("remoteOriginUrl", d.remoteOriginUrl)
} catch {}
d.hasUntracked = (
await execPromise(`git -C ${folder} ls-files --others --exclude-standard`)
).stdout.trim().length
d.hasPendingChangesFromTrackedFiles = false
try {
d.hasPendingChangesFromTrackedFiles =
(await execPromise(`git -C ${folder} diff --name-only`)).stdout.trim()
.length > 0
} catch {}
d.needsGitCommit = false
try {
d.needsGitCommit =
(
await execPromise(`git -C ${folder} diff --staged --name-only`)
).stdout.trim().length > 0
} catch {}
d.needsGitPush = false
try {
d.needsGitPush =
(await execPromise(`git -C ${folder} log @{u}..`)).stdout.trim().length >
0
} catch {}
d.needsGitPull = false
if (d.remoteOriginUrl) {
try {
const attemptsMax = 10
let attempts = attemptsMax
while (attempts > 0) {
if (descriptorsHashMap[folder]) throw new Error("cancelled")
try {
const result = await execPromise(
`git -C ${folder} fetch -q && git -C ${folder} log ..@{u}`,
{ timeout: 2000 + (attemptsMax - attempts) * 500 }
)
d.needsGitPull = result.stdout.trim().length > 0
break
} catch (err) {
attempts--
if (attempts === 0) throw err
await new Promise((resolve) => setTimeout(resolve, 500))
}
}
} catch {}
}
d.isInMergeState = false
try {
await fs.promises.stat(`${folder}/.git/MERGE_HEAD`)
d.isInMergeState = true
} catch {}
d.stateDisplayParts = []
// readability
const ds = d.stateDisplayParts
const s = stateDisplayMode[options.shortStatusDisplay ? "short" : "full"]
if (d.needsGitPull && d.needsGitPush) ds.push(s.needsGitPullAndPush)
else if (d.needsGitPush) ds.push(s.needsGitPush)
else if (d.needsGitPull) ds.push(s.needsGitPull)
if (d.hasPendingChangesFromTrackedFiles)
ds.push(s.hasPendingChangesFromTrackedFiles)
if (d.needsGitCommit) ds.push(s.needsGitCommit)
if (d.hasUntracked) ds.push(s.hasUntracked)
d.stateDisplay = ds.join(s.joiner)
if (d.stateDisplay.length > 0) d.stateDisplay = `[${d.stateDisplay}]`
setLongestName("stateDisplay", d.stateDisplay)
d.timeEnd = Date.now()
return d
}
// __dirname for ESM
const __dirname = new URL(".", import.meta.url).pathname
const doUpdate = async () => {
// fetch master from remote and count commits
try {
try {
await fetch("https://numbers.snwfdhmp.com/counter", {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
key: "counters.git-ls.update-requested",
}),
})
} catch {}
// get current ref
const currentRef = (
await execPromise(`git -C "${__dirname}" rev-parse HEAD`)
).stdout
.trim()
.slice(0, 7)
const pullResult = await execPromise(
`git -C "${__dirname}" pull origin master --ff-only`
)
console.log("git:", pullResult.stdout.trim())
try {
const npmResult = await execPromise(`npm install --no-audit`, {
cwd: __dirname,
})
console.log("npm:", npmResult.stdout.trim())
} catch (e) {
console.log("npm install failed with following message:")
console.error(e)
console.log(
`-----\n\nYou might want to run "npm install" manually (cd ${__dirname}; npm install)`
)
}
const getNewRef = (
await execPromise(`git -C "${__dirname}" rev-parse HEAD`)
).stdout
.trim()
.slice(0, 7)
if (currentRef !== getNewRef) {
console.log(`git-ls: updated from ${currentRef} to ${getNewRef}`.green)
}
return
} catch (e) {
console.log("Update failed with following message:".red)
console.error(e)
}
}
main()
const stateDisplayMode = {
short: {
needsGitPull: "⇣",
needsGitPush: "⇡",
needsGitPullAndPush: "↕",
hasPendingChangesFromTrackedFiles: "!",
needsGitCommit: "+",
hasUntracked: "?",
joiner: "",
},
full: {
needsGitPull: "pull",
needsGitPush: "push",
needsGitPullAndPush: "pull push",
hasPendingChangesFromTrackedFiles: "add",
needsGitCommit: "commit",
hasUntracked: "track",
joiner: " ",
},
}