Created
July 23, 2019 12:01
-
-
Save Platane/469d58e0fde4413689074914cea7fcda to your computer and use it in GitHub Desktop.
Set the env var in circle project from a .env file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require("fs"); | |
const https = require("https"); | |
/** | |
* | |
* Set the env var in circle project from a .env file | |
* | |
* usage: | |
* | |
* ```bash | |
* node setEnv.js --project js13kGames/bot --token xxxx .env | |
* | |
* node setEnv.js --vcsType bb --project js13kGames/bot --token xxxx .env | |
* | |
* node setEnv.js --vcsType bb --username js13kGames --project bot --token xxxx .env | |
* | |
* ``` | |
*/ | |
// make the http call to set an env var in circle | |
const setEnvVar = (vcsType, username, project, token) => (name, value) => | |
new Promise((resolve, reject) => { | |
const req = https.request( | |
`https://circleci.com/api/v1.1/project/${vcsType}/${username}/${project}/envvar?circle-token=${token}`, | |
{ method: "POST", headers: { "content-type": "application/json" } }, | |
res => { | |
if (res.statusCode.toString()[0] === "2") resolve(); | |
let b = ""; | |
res.on("data", c => (b += c.toString())); | |
res.on("error", reject); | |
res.on("end", () => reject(b)); | |
} | |
); | |
req.write(JSON.stringify({ name, value })); | |
req.end(); | |
}); | |
// match all regexp | |
const matchAll = (text, re) => { | |
const matches = []; | |
re.lastIndex = -1; | |
let m; | |
while ((m = re.exec(text))) { | |
matches.push(m); | |
} | |
return matches; | |
}; | |
// read env var from file | |
const readEnv = filename => | |
matchAll( | |
fs.readFileSync(filename).toString(), | |
/^ *([^#\s=]+) *=([^\n]*)$/gm | |
).map(([, name, value]) => ({ name, value: value.trim() })); | |
// read and arg | |
const readNamedArg = name => { | |
const i = process.argv.findIndex( | |
x => x === `--${name}` || x === `-${name[0]}` | |
); | |
return i === -1 ? undefined : process.argv[i + 1]; | |
}; | |
// | |
// | |
const run = async () => { | |
// parse args | |
const token = readNamedArg("token"); | |
const envFilename = process.argv.slice(-1)[0]; | |
const v = readNamedArg("vcsType"); | |
const u = readNamedArg("username"); | |
const p = readNamedArg("project"); | |
const s = p.split("/"); | |
const vcsType = (s.length === 3 && s[0]) || v || "gh"; | |
const username = (s.length === 3 && s[1]) || (s.length === 2 && s[0]) || u; | |
const project = s.slice(-1)[0]; | |
// loop over env and set | |
for (const { name, value } of readEnv(envFilename)) { | |
console.log(name); | |
await setEnvVar(vcsType, username, project, token)(name, value); | |
} | |
}; | |
run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment