-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathdev.js
158 lines (150 loc) · 4.61 KB
/
dev.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
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
require('dotenv').config()
if (!process.env.GOOGLE_CLOUD_PROJECT)
throw new Error('Missing GOOGLE_CLOUD_PROJECT environment variable.')
const fs = require('fs')
const ora = require('ora')()
const FormData = require('form-data')
const axios = require('axios').default
const bucketName = `${process.env.GOOGLE_CLOUD_PROJECT}-evalaas`
const { Storage } = require('@google-cloud/storage')
const gcs = new Storage()
let pushing = false
let pending = false
let latestResult
const { GoogleAuth } = require('google-auth-library')
const auth = new GoogleAuth()
require('yargs')
.command(
'$0',
'Watches for file change and uploads automatron code.',
{},
async (args) => {
ora.info('Running bundler.')
const ncc = require('@vercel/ncc')(require.resolve('./src/bot.ts'), {
externals: [
'@google-cloud/firestore',
'@google-cloud/storage',
'@google-cloud/trace-agent',
'@google-cloud/vision',
'mongodb',
'google-auth-library',
],
sourceMap: true,
sourceMapRegister: false,
watch: true,
})
ncc.handler((result) => {
if (result.err) {
console.error(result.err)
return
}
let code = result.code
const expectedFooter = '//# sourceMappingURL=index.js.map'
const mapBase64 = Buffer.from(result.map).toString('base64')
const mapComment = `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${mapBase64}`
if (code.endsWith(expectedFooter)) {
code = code.slice(0, -expectedFooter.length) + mapComment
} else {
code += '\n' + mapComment
}
const codeBuffer = Buffer.from(code)
const gzippedBuffer = require('zlib').gzipSync(codeBuffer)
console.log(
'Compiled / Code %skb (%skb gzipped)',
(codeBuffer.length / 1024).toFixed(1),
(gzippedBuffer.length / 1024).toFixed(1)
)
require('fs').writeFileSync('automatron.js.gz', gzippedBuffer)
// https://github.com/zeit/ncc/pull/516#issuecomment-601708133
require('fs').writeFileSync(
'webpack.stats.json',
JSON.stringify(result.stats.toJson())
)
push()
})
ncc.rebuild(() => {
console.log('Rebuilding...')
})
ora.info('Watching for file changes.')
}
)
.command('id-token', 'Prints ID token', {}, async () => {
const jwt = await getJwt()
console.log(jwt)
})
.command('download-env', 'Downloads environment file', {}, async () => {
await gcs
.bucket(bucketName)
.file('evalaas/automatron.env')
.download({ destination: 'automatron.env' })
})
.command('upload-env', 'Uploads environment file', {}, async () => {
await gcs
.bucket(bucketName)
.file('evalaas/automatron.env')
.save(fs.readFileSync('automatron.env'))
})
.command(
'set-up-codespaces',
'Downloads Google Cloud service account file for usage in GitHub Codespaces',
{},
async () => {
const encrypted = require('@dtinth/encrypted')(
process.env.SERVICE_ACCOUNT_ENCRYPTION_KEY
)
const encryptedServiceAccount = require('child_process')
.execSync('curl $SERVICE_ACCOUNT_URL')
.toString()
.trim()
const decryptedServiceAccount = encrypted(encryptedServiceAccount)
const serviceAccountPath =
process.env.HOME + '/.google-cloud-service-account.json'
fs.writeFileSync(
serviceAccountPath,
JSON.stringify(decryptedServiceAccount, null, 2)
)
console.log('Written service account file to', serviceAccountPath)
}
)
.strict()
.help()
.parse()
async function getJwt() {
const audience = 'https://github.com/dtinth/automatron'
const client = await auth.getIdTokenClient(audience)
const jwt = await client.idTokenProvider.fetchIdToken(audience)
return jwt
}
async function push() {
if (pushing) {
pending = true
return
}
pushing = true
ora.start('Uploading code...')
try {
const jwt = await getJwt()
const form = new FormData()
const buffer = fs.readFileSync('automatron.js.gz')
form.append('file', buffer, 'file')
await axios.put(
`${process.env.EVALAAS_URL}/admin/endpoints/automatron`,
form.getBuffer(),
{
headers: Object.assign({}, form.getHeaders(), {
Authorization: `Bearer ${jwt}`,
}),
}
)
ora.succeed('Done! Code updated at ' + new Date().toString())
} catch (error) {
ora.fail('Failed: ' + error)
} finally {
ora.stop()
pushing = false
if (pending) {
pending = false
push()
}
}
}