1+ module . exports = async ( context , req ) => {
2+ const action = req . body . action
3+ const owner = req . body . repository . owner . login
4+ const repo = req . body . repository . name
5+ const sender = req . body . sender . login
6+
7+ const getToken = ( ( ) => {
8+ let token
9+
10+ const get = async ( ) => {
11+ const getInstallationIdForRepo = require ( './get-installation-id-for-repo' )
12+ const installationId = await getInstallationIdForRepo ( context , owner , repo )
13+ const getInstallationAccessToken = require ( './get-installation-access-token' )
14+ return await getInstallationAccessToken ( context , installationId )
15+ }
16+
17+ return async ( ) => token || ( token = await get ( ) )
18+ } ) ( )
19+
20+ const isAllowed = async ( login ) => {
21+ const getCollaboratorPermissions = require ( './get-collaborator-permissions' )
22+ const token = await getToken ( )
23+ const permission = await getCollaboratorPermissions ( context , token , owner , repo , login )
24+ return [ 'ADMIN' , 'MAINTAIN' , 'WRITE' ] . includes ( permission . toString ( ) )
25+ }
26+
27+ if ( ! isAllowed ( sender ) ) {
28+ if ( action !== 'completed' ) {
29+ // Cancel workflow run
30+ const { cancelWorkflowRun } = require ( './check-runs' )
31+ const token = await getToken ( )
32+ const workflowRunId = req . body . workflow_job . run_id
33+ await cancelWorkflowRun ( context , token , owner , repo , workflowRunId )
34+ }
35+ throw new Error ( `${ sender } is not allowed to do that` )
36+ }
37+
38+ if ( action === 'queued' ) {
39+ // Spin up a new runner
40+ const triggerWorkflowDispatch = require ( './trigger-workflow-dispatch' )
41+ const token = await getToken ( )
42+ const answer = await triggerWorkflowDispatch (
43+ context ,
44+ token ,
45+ 'git-for-windows' ,
46+ 'git-for-windows-automation' ,
47+ 'create-azure-self-hosted-runners.yml' ,
48+ 'main' , {
49+ runner_scope : 'repo-level'
50+ }
51+ )
52+
53+ return `The workflow run to create the self-hosted runner VM was started at ${ answer . html_url } `
54+ }
55+
56+ if ( action === 'completed' ) {
57+ // Delete the runner
58+ const triggerWorkflowDispatch = require ( './trigger-workflow-dispatch' )
59+ const token = await getToken ( )
60+ const vmName = req . body . workflow_job . runner_name
61+ const answer = await triggerWorkflowDispatch (
62+ context ,
63+ token ,
64+ 'git-for-windows' ,
65+ 'git-for-windows-automation' ,
66+ 'delete-self-hosted-runner.yml' ,
67+ 'main' , {
68+ runner_name : vmName
69+ }
70+ )
71+
72+ return `The workflow run to delete the self-hosted runner VM '${ vmName } ' was started at ${ answer . html_url } `
73+ }
74+
75+ return `Unhandled action: ${ action } `
76+ }
0 commit comments