-
Notifications
You must be signed in to change notification settings - Fork 179
/
pre-build.js
113 lines (107 loc) · 3.19 KB
/
pre-build.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
const https = require('https')
const path = require('path')
const fs = require('fs')
const request = require('request')
const zlib = require('zlib')
const AdmZip = require('adm-zip');
const prefix = 'https://github.com/Dreamacro/clash/releases/download'
const version = 'v0.15.0'
const binary_name = 'clash'
async function downloadClashBinary() {
let platform = ''
let arch = ''
let ext = ''
let url = ''
let fileName = ''
switch(process.platform) {
case 'darwin':
platform = 'darwin'
arch='amd64'
ext = '.gz'
break
case 'win32':
platform = 'windows'
if (process.arch === 'x64') {
arch = 'amd64'
ext = '.zip'
} else {
arch = '386'
ext = '.zip'
}
break
case 'linux':
platform = 'linux'
if (process.arch === 'x64') {
arch = 'amd64'
ext = '.gz'
} else {
arch = '386'
ext = '.gz'
}
break
default:
break
}
url = `${prefix}/${version}/${binary_name}-${platform}-${arch}-${version}${ext}`
fileName = `clash-${platform}-${arch}${platform === 'windows' ? '.exe' : ''}`
const filePath = path.join('.', 'clash-binaries', fileName + ext)
if (fs.existsSync(filePath)) {
console.log(`Clash binary exists for Platform: ${platform}, Arch: ${arch}`)
return Promise.resolve(filePath)
}
const fos = fs.createWriteStream(filePath)
return new Promise((resolve, reject) => {
console.log(`Prepare to download Clash binary for Platform ${platform}, Arch: ${arch}`)
const stream = request.get(url)
.pipe(fos)
stream.on('finish', () => {
resolve(filePath)
})
.on('error', () => {
reject()
})
})
}
function unZipGzFile(filePath) {
return new Promise((resolve, reject) => {
console.log(filePath)
const fileContents = fs.createReadStream(filePath);
const writeStream = fs.createWriteStream(filePath.slice(0, -3));
const unzip = zlib.createGunzip();
fileContents.pipe(unzip).pipe(writeStream).on('finish', err => {
if (err) {
reject(err)
return
}
fs.unlinkSync(filePath)
fs.chmodSync(filePath.slice(0, -3), 0o755)
resolve()
})
})
}
function unZipZipFile(filePath) {
return new Promise((resolve, reject) => {
const zip = new AdmZip(filePath)
zip.extractAllToAsync(path.join('.', 'clash-binaries'), true, err => {
if (err) {
reject(err)
return
}
fs.unlinkSync(filePath)
resolve()
})
})
}
downloadClashBinary().then((filePath) => {
console.log('Clash binary downloaded.')
console.log('Extracting...')
if (process.platform === 'win32') {
return unZipZipFile(filePath)
} else {
return unZipGzFile(filePath)
}
}).then(() => {
console.log('Done.')
}).catch(e => {
console.error(e)
})