-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdownloadBin.js
94 lines (83 loc) · 2.72 KB
/
downloadBin.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
const fs = require("fs");
const path = require("path");
const mkdirp = require("mkdirp");
const { goPackageNames } = require("./packageNames");
const fetch = require("node-fetch");
module.exports = function(packageDirname, update) {
let binExists = true;
const binPath = path.join(packageDirname, "bin");
try {
binExists = binExists && fs.statSync(binPath).isDirectory();
binExists = binExists && fs.statSync(path.join(binPath, "blank-sr")).isFile();
binExists = binExists && fs.statSync(path.join(binPath, "blank-router")).isFile();
} catch (err) {
binExists = false;
}
if (binExists) {
return Promise.resolve();
}
console.log("Downloading packages...");
return new Promise((f, r) => {
mkdirp(binPath, f);
})
.then(() => {
const downloads = [];
if (!binExists || update) {
for (const packageName of goPackageNames) {
downloads.push(downloadPackage(binPath, packageName));
}
}
return Promise.all(downloads);
})
.then(() => {
console.log("All packages downloaded successfully");
});
};
function downloadPackage(binPath, name) {
if (process.arch !== "x64") {
throw new Error(`unsupported platform ${process.platform}/${process.arch}`);
}
const ext = process.platform === "win32" ? ".exe" : "";
return getLastVersionOfPackage(name)
.then(version => {
const downloadUrl = `https://github.com/getblank/${name}/releases/download/${version}/${name}-${
process.platform
}-amd64${ext}`;
console.info(downloadUrl);
return download(downloadUrl, path.join(binPath, `${name}${ext}`));
})
.then(() => {
console.log("Download complete:", `${name}${ext}`);
})
.catch(err => {
console.log("Download failed:", `${name}${ext}`, err);
});
}
function download(url, dest) {
return fetch(url)
.then(res => {
const file = fs.createWriteStream(dest, {
mode: 0o776,
});
return new Promise(resolve => {
res.body.on("end", resolve);
res.body.pipe(
file,
{ end: false }
);
});
})
.catch(err => {
fs.unlink(dest);
throw err;
});
}
function getLastVersionOfPackage(packageName) {
return fetch(`https://api.github.com/repos/getblank/${packageName}/releases/latest`)
.then(res => {
return res.json();
})
.then(json => {
return json.tag_name;
});
}