1+ const express = require ( 'express' )
2+ const bodyParser = require ( 'body-parser' )
3+ const GhApi = require ( 'github4' )
4+ const yaml = require ( 'yamljs' )
5+ const glob = require ( 'globule' )
6+ const createFilesChangedDeterminer = require ( './lib/files-changed-determiner' )
7+ const createParsedYamlRetriever = require ( './lib/parsed-yaml-retriever' )
8+ const isValidSig = require ( './lib/signature-validator' )
9+
10+ const githubToken = process . env . GITHUB_TOKEN
11+ const sharedKey = process . env . PLUGIN_SECRET
12+
13+ const gh = new GhApi ( { version : '3.0.0' } )
14+ gh . authenticate ( { type : 'oauth' , token : githubToken } )
15+
16+ const determineFilesChanged = createFilesChangedDeterminer ( gh )
17+ const getParsedYaml = createParsedYamlRetriever ( gh )
18+
19+ const nullYaml = 'kind: pipeline\nname: default\ntrigger:\n event:\n exclude: [ "*" ]'
20+
21+ const app = express ( )
22+ app . post ( '/' , bodyParser . json ( ) , async ( req , res ) => {
23+ console . log ( 'Processing...' )
24+ if ( ! req . headers . signature ) return res . status ( 400 ) . send ( 'Missing signature' )
25+ if ( ! isValidSig ( req , sharedKey ) ) return res . status ( 400 ) . send ( 'Invalid signature' )
26+ if ( ! req . body ) return res . sendStatus ( 400 )
27+ const data = req . body
28+
29+ let filesChanged = [ ]
30+ try {
31+ filesChanged = await determineFilesChanged ( data )
32+ } catch ( e ) {
33+ console . log ( 'ERROR:' , e )
34+ return res . sendStatus ( 500 )
35+ }
36+
37+ console . log ( 'Files changed:' , filesChanged )
38+
39+ let parsedYaml = null
40+ try {
41+ parsedYaml = await getParsedYaml ( data )
42+ } catch ( e ) {
43+ if ( e . code === 404 ) return res . sendStatus ( 204 )
44+ console . log ( 'ERROR:' , e )
45+ return res . sendStatus ( 500 )
46+ }
47+
48+ if ( parsedYaml . trigger && parsedYaml . trigger . changeset && parsedYaml . trigger . changeset . includes ) {
49+ const requiredFiles = parsedYaml . trigger . changeset . includes
50+ const matchedFiles = glob . match ( requiredFiles , filesChanged , { dot : true } )
51+ console . log ( 'Matched files for pipeline:' , matchedFiles . length , 'Allowed matches:' , requiredFiles )
52+ if ( ! matchedFiles . length ) return res . json ( { Data : nullYaml } )
53+ }
54+
55+ const trimmedSteps = parsedYaml . steps . filter ( s => {
56+ if ( ! s . when || ! s . when . changeset || ! s . when . changeset . includes ) return true
57+ const requiredFiles = s . when . changeset . includes
58+ const matchedFiles = glob . match ( requiredFiles , filesChanged , { dot : true } )
59+ console . log ( 'Matched files for step:' , matchedFiles . length , 'Allowed matches:' , requiredFiles )
60+ return matchedFiles . length
61+ } )
62+
63+ const returnYaml = trimmedSteps . length ? yaml . stringify ( { ...parsedYaml , steps : trimmedSteps } ) : nullYaml
64+
65+ res . json ( { Data : returnYaml } )
66+ } )
67+
68+ app . listen ( 3000 )
0 commit comments