-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsync-apps.js
72 lines (65 loc) · 2.13 KB
/
sync-apps.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
const https = require("https");
const tar = require("tar");
const fs = require("fs-extra");
const path = require("path");
const appBuilds = require("./app-builds");
const downloadAndExtract = (key, url, tag) => {
const finalUrl = url.replace("{{tag}}", tag);
console.log(`Downloading ${key} from ${finalUrl}`);
const appPath = path.join(__dirname, "apps", key);
// Create the folder if it doesn't exist
fs.mkdirSync(appPath, { recursive: true });
const downloadFile = (url, redirections = 5) => {
return new Promise((resolve, reject) => {
if (redirections < 1) {
reject(new Error("Too many redirections"));
}
const request = https.get(url, (response) => {
if (response.statusCode === 200) {
resolve(response);
} else if (response.statusCode === 302 || response.statusCode === 301) {
console.log(`Redirecting to ${response.headers.location}`);
downloadFile(response.headers.location, redirections - 1)
.then(resolve)
.catch(reject);
} else {
reject(
new Error(
`Failed to download file, status code: ${response.statusCode}`
)
);
}
});
request.on("error", reject);
});
};
downloadFile(finalUrl)
.then((response) => {
const extraction = tar.x({ cwd: appPath });
response.pipe(extraction);
return new Promise((resolve, reject) => {
extraction.on("finish", resolve);
extraction.on("error", reject);
});
})
.then(() => {
const buildPath = path.join(appPath, "build");
if (fs.existsSync(buildPath)) {
return fs
.copy(buildPath, appPath)
.then(() => fs.remove(buildPath))
.then(() =>
console.log(`Moved files from ${buildPath} to ${appPath}`)
);
} else {
console.log(`No build directory in ${appPath}`);
}
})
.catch((error) => {
console.error(`Failed to download and extract ${key}: ${error.message}`);
});
};
for (const key in appBuilds) {
const { tag, url } = appBuilds[key];
downloadAndExtract(key, url, tag);
}