-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathcli.js
executable file
·331 lines (308 loc) · 9.75 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
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
#!/usr/bin/env node
const defaults = require('./src/defaults')
const figma = require('./src/figma-client')
const fs = require('fs')
const path = require('path')
const ora = require('ora')
const chalk = require('chalk')
const ui = require('cliui')({ width: 80 })
const axios = require('axios')
const prompts = require('prompts')
const promptsList = require('./src/prompts')
const mkdirp = require('mkdirp')
const argv = require('minimist')(process.argv.slice(2))
let config = {}
let figmaClient
const spinner = ora()
function deleteConfig () {
const configFile = path.resolve(defaults.configFileName)
if (fs.existsSync(configFile)) {
fs.unlinkSync(configFile)
console.log(chalk.cyan.bold('Deleted previous config'))
}
}
function updateGitIgnore () {
const ignorePath = '.gitignore'
const configPath = argv.config || defaults.configFileName
const ignoreCompletePath = path.resolve(ignorePath)
if (fs.existsSync(configPath)) {
const ignoreContent = `\n#figma-export-icons\n${configPath}`
const ignore = fs.existsSync(ignoreCompletePath)
? fs.readFileSync(ignoreCompletePath, 'utf-8')
: ''
if(!ignore.includes(ignoreContent)) {
fs.writeFileSync(ignoreCompletePath, ignore + ignoreContent)
console.log(`Updated ${ignorePath} : ${ignoreContent}`)
}
}
}
function getConfig () {
return new Promise((resolve) => {
const configFile = path.resolve(argv.config || defaults.configFileName)
if (fs.existsSync(configFile)) {
config = JSON.parse(fs.readFileSync(configFile, 'utf-8'))
const missingConfig = promptsList.filter((q) => !config[q.name])
if (missingConfig.length > 0) getPromptData(missingConfig).then(() => resolve())
else resolve()
} else {
getPromptData().then(() => resolve())
}
})
}
async function getPromptData ( list = promptsList ) {
const onCancel = prompt => {
process.exit(1)
}
const response = await prompts(list, { onCancel })
config = Object.assign(config, response)
fs.writeFileSync('icons-config.json', JSON.stringify(config, null, 2))
}
function createOutputDirectory () {
return new Promise((resolve) => {
const directory = path.resolve(config.iconsPath)
if (!fs.existsSync(directory)) {
console.log(`Directory ${config.iconsPath} does not exist`)
if (mkdirp.sync(directory)) {
console.log(`Created directory ${config.iconsPath}`)
resolve()
}
} else {
resolve()
}
})
}
function deleteIcon (iconPath) {
return new Promise((resolve) => {
fs.unlink(iconPath, (err) => {
if (err) throw err
// if no error, file has been deleted successfully
resolve()
})
})
}
function deleteDirectory (directory) {
return new Promise((resolve) => {
fs.rmdir(directory, (err) => {
if (err) throw err
resolve()
})
})
}
function deleteIcons () {
return new Promise((resolve) => {
const directory = path.resolve(config.iconsPath)
// read icons directory files
fs.readdir(directory, (err, files) => {
if (err) throw err
spinner.start('Deleting directory contents')
let filesToDelete = []
let subdirectories = []
files.forEach((file) => {
const hasSubdirectory = fs.lstatSync(path.join(directory, file)).isDirectory()
if (hasSubdirectory) {
const subdirectory = path.join(directory, file)
subdirectories.push(subdirectory)
// read subdirectory
fs.readdir(subdirectory, (err, files) => {
if (err) throw err
files.forEach(file => filesToDelete.push(deleteIcon(path.join(subdirectory, file))))
})
} else {
if (file !== 'README.md') {
filesToDelete.push(deleteIcon(path.join(directory, file)))
}
}
})
Promise.all(filesToDelete).then(() => {
const directoriesToDelete = subdirectories.map(subdirectory => deleteDirectory(subdirectory))
Promise.all(directoriesToDelete).then(() => {
spinner.succeed()
resolve()
})
})
})
})
}
function findDuplicates (propertyName, arr) {
return arr.reduce((acc, current) => {
const x = acc.find(item => item[propertyName] === current[propertyName])
if (x) {
spinner.fail(chalk.bgRed.bold(`Duplicate icon name: ${x[propertyName]}. Please fix figma file`))
current[propertyName] = current[propertyName] + '-duplicate-name'
}
return acc.concat([current])
}, [])
}
function getPathToFrame(root, current) {
if(!current.length) return root
const path = [...current]
const name = path.shift()
const foundChild = root.children.find(c => c.name === name)
if (!foundChild) return root;
return getPathToFrame(foundChild, path)
}
function getFigmaFile () {
return new Promise((resolve) => {
spinner.start('Fetching Figma file (this might take a while depending on the figma file size)')
figmaClient.get(`/files/${config.fileId}`)
.then((res) => {
const endTime = new Date().getTime()
spinner.succeed()
console.log(chalk.cyan.bold(`Finished in ${(endTime - res.config.startTime) / 1000}s\n`))
const page = res.data.document.children.find(c => c.name === config.page)
if (!page) {
console.log(chalk.red.bold('Cannot find Icons Page, check your settings'))
return
}
const shouldGetFrame = isNaN(config.frame) && parseInt(config.frame) !== -1
let iconsArray = page.children
if (shouldGetFrame) {
const frameNameArr = config.frame.split('/').filter(Boolean)
const frameName = frameNameArr.pop()
const frameRoot = getPathToFrame(page, frameNameArr)
if (!frameRoot.children.find(c => c.name === frameName)) {
console.log(chalk.red.bold('Cannot find', chalk.white.bgRed(frameName), 'Frame in this Page, check your settings'))
return
}
iconsArray = frameRoot.children.find(c => c.name === frameName).children
}
let icons = iconsArray.map((icon) => {
return { id: icon.id, name: icon.name }
})
icons = findDuplicates('name', icons)
resolve(icons)
})
.catch((err) => {
spinner.fail()
if (err.response) {
console.log(chalk.red.bold(`Cannot get Figma file: ${err.response.data.status} ${err.response.data.err}`))
} else {
console.log(err)
}
process.exit(1)
})
})
}
function getImages (icons) {
return new Promise((resolve) => {
spinner.start('Fetching icon urls')
const iconIds = icons.map(icon => icon.id).join(',')
figmaClient.get(`/images/${config.fileId}?ids=${iconIds}&format=svg`)
.then((res) => {
spinner.succeed()
const images = res.data.images
icons.forEach((icon) => {
icon.image = images[icon.id]
})
resolve(icons)
})
.catch((err) => {
console.log('Cannot get icons: ', err)
process.exit(1)
})
})
}
function downloadImage (url, name) {
let nameClean = name
let directory = config.iconsPath
const idx = name.lastIndexOf('/')
if (idx !== -1) {
directory = directory + '/' + name.substring(0, idx)
nameClean = name.substring(idx + 1)
if (!fs.existsSync(directory)) {
if (mkdirp.sync(directory)) {
console.log(`\nCreated sub directory ${directory}`)
iconPath = directory
} else {
console.log('Cannot create directories')
process.exit(1)
}
}
}
const imagePath = path.resolve(directory, `${nameClean}.svg`)
const writer = fs.createWriteStream(imagePath)
axios.get(url, {responseType: 'stream'})
.then((res) => {
res.data.pipe(writer)
})
.catch((err) => {
spinner.fail()
console.log(name)
console.log(err.message)
console.log(err.config.url)
console.log(chalk.red.bold('Something went wrong fetching the image from S3, please try again'),)
process.exit(1)
})
return new Promise((resolve, reject) => {
writer.on('finish', () => {
// console.log(`Saved ${name}.svg`, fs.statSync(imagePath).size)
resolve({
name: `${name}.svg`,
size: fs.statSync(imagePath).size
})
})
writer.on('error', (err) => {
console.log('error writting file', err)
reject(err)
})
})
}
function makeRow (a, b) {
return ` ${a}\t ${b}\t`
}
function formatSize (size) {
return (size / 1024).toFixed(2) + ' KiB'
}
function makeResultsTable (results) {
ui.div(
makeRow(
chalk.cyan.bold(`File`),
chalk.cyan.bold(`Size`),
) + `\n\n` +
results.map(asset => makeRow(
asset.name.includes('-duplicate-name')
? chalk.red.bold(asset.name)
: chalk.green(asset.name),
formatSize(asset.size)
)).join(`\n`)
)
return ui.toString()
}
function removeFromName(name) {
return name.replace(config.removeFromName, '')
}
function exportIcons () {
getFigmaFile()
.then((res) => {
getImages(res)
.then((icons) => {
console.log(`Api returned ${icons.length} icons\n`)
createOutputDirectory()
.then(() => {
deleteIcons().then(() => {
spinner.start('Downloading')
const AllIcons = icons.map(icon => downloadImage(icon.image, removeFromName(icon.name)))
// const AllIcons = []
Promise.all(AllIcons).then((res) => {
spinner.succeed(chalk.cyan.bold('Download Finished!\n'))
console.log(`${makeResultsTable(res)}\n`)
})
})
})
})
.catch((err) => {
console.log(chalk.red(err))
})
})
}
function run () {
updateGitIgnore()
if (argv.c) {
deleteConfig()
}
getConfig().then(() => {
figmaClient = figma(config.figmaPersonalToken)
exportIcons()
})
}
run()