-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·91 lines (75 loc) · 2.39 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
#!/usr/bin/env node
// @ts-check
const path = require('path')
const fs = require('fs')
const minimist = require('minimist')
const prompts = require('prompts')
const { red } = require('kolorist')
const { getFilePath } = require('./utils/getFilePath')
const { readFile } = require('./utils/readFile')
const { parse } = require('./utils/parse')
const { downLoadImageToLocal, createRootDir } = require('./utils/generate')
const { isFileLegal } = require('./utils/checkFile')
function canSafelyOverwrite(dir) {
return !fs.existsSync(dir) || fs.readdirSync(dir).length === 0
}
async function init() {
const cwd = process.cwd()
let originFilePath
const argv = minimist(process.argv.slice(2), {
alias: { 'file-path': ['path', 'p'] }
})
if (argv.p) {
originFilePath = getFilePath(argv.p, cwd)
}
let targetDir = argv._[0]
const defaultProjectName = !targetDir ? 'images' : targetDir
let result = {}
try {
result = await prompts([
{
name: 'filePath',
type: originFilePath ? null : 'text',
message: 'Parsed file path:',
validate: (value) => isFileLegal(value)
},
{
name: 'targetDirName',
type: targetDir ? null : 'text',
message: 'Target directory name:',
initial: defaultProjectName,
onState: (state) => (targetDir = String(state.value).trim() || defaultProjectName)
},
{
name: 'shouldOverwrite',
type: () => (canSafelyOverwrite(targetDir) ? null : 'confirm'),
message: () => {
const dirForPrompt =
targetDir === '.' ? 'Current directory' : `Target directory "${targetDir}"`
return `${dirForPrompt} is not empty. Remove existing files and continue?`
}
},
{
name: 'overwriteChecker',
type: (prev, values = {}) => {
if (values.shouldOverwrite === false) {
throw new Error(red('✖') + ' Operation cancelled')
}
return null
}
}
])
} catch (cancelled) {
console.log(cancelled.message)
process.exit(1)
}
const { filePath = originFilePath, targetDirName, shouldOverwrite } = result
const root = path.resolve(cwd, targetDirName)
const content = readFile(filePath)
const images = parse(content)
await createRootDir(root, shouldOverwrite)
await downLoadImageToLocal(images, root)
}
init().catch((error) => {
console.log(error)
})