This repository has been archived by the owner on Nov 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
prebuild.mjs
57 lines (43 loc) · 1.68 KB
/
prebuild.mjs
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
// the .mjs file extention is only there so we can use nicer imports. The code is still normal JavaScript
import {exec} from 'child_process';
import {promisify} from 'util';
import {writeFile} from 'fs/promises';
// attempt to find an existing deploy for the given branch
const getDeployUrl = async (branch) => {
const {stdout} = await promisify(exec)(`firebase hosting:channel:list --json`);
const {result} = JSON.parse(stdout);
return result.channels.find(deploy => deploy.name.split('/').pop() === branch)?.url;
};
// create a new hosting preview channel without deploying and return its' url
const generateBranchDeployUrl = async (branch) => {
const {stdout} = await promisify(exec)(`firebase hosting:channel:create ${branch} --json`);
const {result} = JSON.parse(stdout);
return result.url;
};
// set the preview url in the CI env so future stages can use it
const setEnv = async (url) => {
const envs = {
// this is the name of the variable that we'll be able to use through the rest of the CI process
// you can add more variables here if you need them
MY_DEPLOYED_URL: url,
};
const stringified = Object.entries(envs)
.reduce((prev, [key, value]) => `${prev}${key}=${value}\n`, '');
await writeFile('build.env', stringified);
};
// ensure that there is a preview channel ready for our deploy, and put its' url in the env
const prepare = async (branch) => {
let url = await getDeployUrl(branch);
if (!url) {
url = await generateBranchDeployUrl(branch);
}
await setEnv(url);
console.log(`preparation complete: ${url}`);
};
prepare(
process.argv[2] || process.env.CI_COMMIT_REF_SLUG,
)
.catch(e => {
console.error(e);
process.exit(1);
});