-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcreateEnv.mts
More file actions
205 lines (192 loc) · 5.97 KB
/
createEnv.mts
File metadata and controls
205 lines (192 loc) · 5.97 KB
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import { execSync } from "node:child_process";
import { appendFileSync, writeFileSync, readFileSync } from "node:fs";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import dotenv from "dotenv";
import { Vercel } from "@vercel/sdk";
// eslint-disable-next-line @typescript-eslint/naming-convention
const __dirname = dirname(fileURLToPath(import.meta.url));
const projectRoot = join(__dirname, "..");
const baseParams: Record<string, string> = {};
enum Variant {
local = "local",
branch = "branch",
production = "production",
all = "all",
none = "none",
}
// option to override in .env, but otherwise use our values
const projectIdOrName: string =
process.env["VERCEL_PROJECT_ID"] ||
process.env["VERCEL_PROJECT_NAME"] ||
"discourse-graph";
const getVercelToken = () => {
return process.env["VERCEL_TOKEN"];
};
const makeFnEnv = (envTxt: string): string => {
return envTxt
.split("\n")
.filter((l) => l.match(/^SUPABASE_\w+_KEY/))
.map((l) => l.replace("SUPABASE_", "SB_"))
.join("\n");
};
const makeLocalEnv = () => {
execSync("supabase start", {
cwd: projectRoot,
stdio: "inherit",
});
const stdout = execSync("supabase status -o env", {
encoding: "utf8",
});
const prefixed = stdout
.split("\n")
.filter((line) => line.length > 0)
.map((line) =>
/^API_URL=/.test(line)
? `SUPABASE_URL=${line.substring(8)}`
: `SUPABASE_${line}`,
)
.join("\n");
writeFileSync(
join(projectRoot, ".env.local"),
prefixed + '\nNEXT_API_ROOT="http://localhost:3000/api"\n',
);
writeFileSync(
join(projectRoot, "supabase/functions/.env"),
makeFnEnv(prefixed),
);
};
const makeBranchEnv = async (vercel: Vercel, vercelToken: string) => {
let branch: string;
if (process.env.SUPABASE_GIT_BRANCH) {
// allow to override current branch
// currently test with ENG-589-create-space-fn
branch = process.env.SUPABASE_GIT_BRANCH;
} else {
const stdout = execSync("git status -b -uno", { encoding: "utf8" });
const branchM = stdout.match(/On branch (.*)/)?.[1];
if (branchM) branch = branchM;
else throw new Error("Could not find the git branch");
}
if (!/^[-\w]+$/.test(branch))
throw new Error("Invalid branch name: " + branch);
const result = await vercel.deployments.getDeployments({
...baseParams,
projectId: projectIdOrName,
limit: 1,
branch,
state: "READY",
});
if (result.deployments.length === 0) {
console.warn("No deployment for branch " + branch);
return;
}
const url = result.deployments[0]!.url;
try {
execSync(
`vercel -t ${vercelToken} env pull --environment preview --git-branch ${branch} .env.branch`,
{ encoding: "utf8" },
);
} catch (err) {
console.error(err);
throw err;
}
appendFileSync(".env.branch", `NEXT_API_ROOT="https://${url}/api"\n`);
const fromVercel = readFileSync(".env.branch").toString();
writeFileSync(
join(projectRoot, "supabase/functions/.env"),
makeFnEnv(fromVercel),
);
};
const makeProductionEnv = async (vercel: Vercel, vercelToken: string) => {
const result = await vercel.deployments.getDeployments({
...baseParams,
projectId: projectIdOrName,
limit: 1,
target: "production",
state: "READY",
});
if (result.deployments.length == 0) {
throw new Error("No production deployment found");
}
const url = result.deployments[0]!.url;
execSync(
`vercel -t ${vercelToken} env pull --environment production .env.production`,
);
appendFileSync(".env.production", `NEXT_API_ROOT="https://${url}/api"\n`);
const fromVercel = readFileSync(".env.production").toString();
writeFileSync(
join(projectRoot, "supabase/functions/.env"),
makeFnEnv(fromVercel),
);
};
const main = async (variant: Variant) => {
if (process.env.ROAM_BUILD_SCRIPT) {
// special case: production build
try {
const response = execSync(
"curl https://discoursegraphs.com/api/supabase/env",
);
const asJson = JSON.parse(response.toString()) as Record<string, string>;
writeFileSync(
join(projectRoot, ".env"),
Object.entries(asJson)
.map(([k, v]) => `${k}=${v}`)
.join("\n"),
);
return;
} catch (e) {
if (process.env.SUPABASE_URL && process.env.SUPABASE_PUBLISHABLE_KEY)
return;
throw new Error("Could not get environment from site");
}
} else if (
process.env.HOME === "/vercel" ||
(process.env.GITHUB_ACTIONS !== undefined &&
process.env.GITHUB_TEST !== "test")
)
// Do not execute in deployment or github action.
return;
if (variant === Variant.none) return;
try {
if (variant === Variant.local || variant === Variant.all) {
makeLocalEnv();
if (variant === Variant.local) return;
}
const vercelToken = getVercelToken();
if (!vercelToken) {
throw Error("Missing VERCEL_TOKEN in .env");
}
// option to override in .env, but otherwise use our values
const teamId = process.env["VERCEL_TEAM_ID"];
const teamSlug = process.env["VERCEL_TEAM_SLUG"] || "discourse-graphs";
if (teamId) {
baseParams.teamId = teamId;
} else {
baseParams.slug = teamSlug;
}
const vercel = new Vercel({ bearerToken: vercelToken });
if (variant === Variant.branch || variant === Variant.all) {
await makeBranchEnv(vercel, vercelToken);
}
if (variant === Variant.production || variant === Variant.all) {
await makeProductionEnv(vercel, vercelToken);
}
} catch (err) {
console.error("variant ", variant, " error ", err);
throw err;
}
};
if (fileURLToPath(import.meta.url) === process.argv[1]) {
dotenv.config();
const variantS: string =
(process.argv.length === 3
? process.argv[2]
: process.env["SUPABASE_USE_DB"]) || "none";
const variant = (Variant as Record<string, Variant>)[variantS];
if (variant === undefined) {
throw Error("Invalid variant: " + variant);
}
console.log(variant);
await main(variant);
}