-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
82 lines (66 loc) · 1.96 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
import Path from 'path'
import fs from 'fs-extra'
import glob from 'glob'
import checkin from 'checkin'
import './utils/progress'
import apikey from './apikey'
import taida from './taida'
import { lint } from './lint'
import emitter from './utils/emitter'
export default function (opt) {
let options = null
try {
options = checkin(opt, lint)
} catch (e) {
return Promise.reject(e)
}
const { pattern, alternate, apikeys, dest } = options
apikey.config({ alternate, apikeys })
const isBitmap = p => /\.(jpg|jpeg|png)$/.test(p)
const resources = Array.from(new Set(
[].concat(pattern)
.map(f => glob.sync(f))
.reduce((ret, arr) => ret.concat(arr), [])
.filter(isBitmap)
))
if (!resources.length) {
return Promise.reject(new Error('exit for no matched bitmaps'))
}
if (options.progress) emitter.emit('bar.init', resources.length)
const readFile = path => fs.readFileSync(path)
const writeFile = (path, buffer) => fs.outputFileSync(path, buffer, { encoding: 'binary' })
const wrapImg = path => ({ path, buffer: readFile(path) })
const compressP = function (img) {
const key = apikey.get()
const buffer = img.buffer
const fallback = () => {
apikey.depress(key)
return taida(apikey.get(), buffer, fallback)
}
return taida(key, buffer, fallback)
.then(
ret => Promise.resolve(Object.assign({}, img, ret))
)
.catch(
error => Promise.resolve({
...img,
error
})
)
}
const outputP = function (outputDir, img) {
emitter.emit('bar.progress')
if (img.error) {
return Promise.resolve(img)
}
const { path, buffer } = img
const output = outputDir ? Path.join(outputDir, Path.basename(path)) : path
writeFile(output, buffer)
return Promise.resolve(img)
}
const resourcesP = resources
.map(wrapImg)
.map(img => compressP(img).then(outputP.bind(null, dest)))
return Promise
.all(resourcesP)
}