-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcore.ts
204 lines (170 loc) · 5.44 KB
/
core.ts
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
import assert from "assert"
import { botPullRequestCommentMention } from "./bot"
import { ExtendedOctokit, isOrganizationMember } from "./github"
import { Task } from "./task"
import { CommandExecutor, Context } from "./types"
export const defaultParseTryRuntimeBotCommandOptions = {
baseEnv: { RUST_LOG: "remote-ext=info" },
}
export const parsePullRequestBotCommand = (
commandLine: string,
{ baseEnv }: { baseEnv: Record<string, string> },
) => {
const allTokens = commandLine.split(" ").filter((value) => {
return !!value
})
const [firstToken, ...tokens] = allTokens
if (firstToken !== botPullRequestCommentMention) {
return
}
const args: string[] = []
const env: Record<string, string> = { ...baseEnv }
// envArgs are only collected at the start of the command line
let isCollectingEnvVars = true
for (const tok of tokens) {
if (isCollectingEnvVars) {
const matches = tok.match(/^([A-Za-z_]+)=(.*)/)
if (matches === null) {
isCollectingEnvVars = false
} else {
const [, name, value] = matches
assert(name)
env[name] = value
continue
}
}
args.push(tok)
}
return { args, env }
}
export const parsePullRequestBotCommandArgs = (
{ nodesAddresses }: Context,
args: string[],
) => {
// This expression catches the following forms: -foo=, --foo=
const commandOptionExpression = /^-[^=\s]+=/
// This expression catches the following forms: ws://foo, wss://foo, etc.
const uriPrefixExpression = /^ws\w*:\/\//
const nodeOptionsDisplay = `Available names are: ${Object.keys(
nodesAddresses,
).join(", ")}.`
const parsedArgs = []
for (const rawArg of args) {
const optionPrefix = commandOptionExpression.exec(rawArg)
const { argPrefix, arg } =
optionPrefix === null
? { argPrefix: "", arg: rawArg }
: {
argPrefix: optionPrefix[0],
arg: rawArg.slice(optionPrefix[0].length),
}
const uriPrefixMatch = uriPrefixExpression.exec(arg)
if (uriPrefixMatch === null) {
parsedArgs.push(rawArg)
continue
}
const [uriPrefix] = uriPrefixMatch
const invalidNodeAddressExplanation = `Argument "${arg}" started with ${uriPrefix} and therefore it was interpreted as a node address, but it is invalid`
const node = arg.slice(uriPrefix.length)
if (!node) {
return `${invalidNodeAddressExplanation}. Must specify one address in the form \`${uriPrefix}name\`. ${nodeOptionsDisplay}`
}
const nodeAddress = nodesAddresses[node]
if (!nodeAddress) {
return `${invalidNodeAddressExplanation}. Nodes are referred to by name. No node named "${node}" is available. ${nodeOptionsDisplay}`
}
parsedArgs.push(`${argPrefix}${nodeAddress}`)
}
return parsedArgs
}
export const getDeploymentsLogsMessage = ({ deployment }: Context) => {
return deployment === undefined
? ""
: `The logs for this command should be available on Grafana for the data source \`loki.${deployment.environment}\` and query \`{container=~"${deployment.container}"}\``
}
export const isRequesterAllowed = async (
ctx: Context,
octokit: ExtendedOctokit,
username: string,
) => {
const { allowedOrganizations } = ctx
for (const organizationId of allowedOrganizations) {
if (
await isOrganizationMember(ctx, { organizationId, username, octokit })
) {
return true
}
}
return false
}
export const prepareBranch = async function* (
{ repoPath, gitRef: { contributor, owner, repo, branch } }: Task,
{
run,
getFetchEndpoint,
}: {
run: CommandExecutor
getFetchEndpoint: () => Promise<{ token: string; url: string }>
},
) {
yield run("mkdir", ["-p", repoPath])
const { token, url } = await getFetchEndpoint()
const runInRepo = (...[execPath, args, options]: Parameters<typeof run>) => {
return run(execPath, args, {
...options,
secretsToHide: [token, ...(options?.secretsToHide ?? [])],
options: { cwd: repoPath, ...options?.options },
})
}
// Clone the repository if it does not exist
yield runInRepo(
"git",
["clone", "--quiet", `${url}/${owner}/${repo}`, repoPath],
{
testAllowedErrorMessage: (err) => {
return err.endsWith("already exists and is not an empty directory.")
},
},
)
// Clean up garbage files before checkout
yield runInRepo("git", ["add", "."])
yield runInRepo("git", ["reset", "--hard"])
// Check out to the detached head so that any branch can be deleted
const out = await runInRepo("git", ["rev-parse", "HEAD"], {
options: { cwd: repoPath },
})
if (out instanceof Error) {
return out
}
const detachedHead = out.trim()
yield runInRepo("git", ["checkout", "--quiet", detachedHead], {
testAllowedErrorMessage: (err) => {
// Why the hell is this not printed to stdout?
return err.startsWith("HEAD is now at")
},
})
const prRemote = "pr"
yield runInRepo("git", ["remote", "remove", prRemote], {
testAllowedErrorMessage: (err) => {
return err.includes("No such remote:")
},
})
yield runInRepo("git", [
"remote",
"add",
prRemote,
`${url}/${contributor}/${repo}.git`,
])
yield runInRepo("git", ["fetch", "--quiet", prRemote, branch])
yield runInRepo("git", ["branch", "-D", branch], {
testAllowedErrorMessage: (err) => {
return err.endsWith("not found.")
},
})
yield runInRepo("git", [
"checkout",
"--quiet",
"--track",
`${prRemote}/${branch}`,
])
}