|
| 1 | +const fs = require('fs'); |
| 2 | +const path = require('path'); |
| 3 | +const Step = require('../../actions').Step; |
| 4 | +const { spawnSync } = require('child_process'); |
| 5 | + |
| 6 | +const sanitizeInput = (req, action) => { |
| 7 | + return `${action.oldCommit} ${action.newCommit} ${action.ref}\n`; |
| 8 | +}; |
| 9 | + |
| 10 | +const exec = async (req, action, hookFilePath = './hooks/pre-receive.sh') => { |
| 11 | + const step = new Step('executeExternalPreReceiveHook'); |
| 12 | + |
| 13 | + try { |
| 14 | + const resolvedPath = path.resolve(hookFilePath); |
| 15 | + |
| 16 | + if (!fs.existsSync(resolvedPath)) { |
| 17 | + throw new Error(`Hook file not found: ${resolvedPath}`); |
| 18 | + } |
| 19 | + |
| 20 | + console.log(`Executing pre-receive hook from: ${resolvedPath}`); |
| 21 | + |
| 22 | + const sanitizedInput = sanitizeInput(req, action); |
| 23 | + |
| 24 | + const hookProcess = spawnSync(resolvedPath, [], { |
| 25 | + input: JSON.stringify(sanitizedInput), |
| 26 | + encoding: 'utf-8', |
| 27 | + }); |
| 28 | + |
| 29 | + const { stdout, stderr, status } = hookProcess; |
| 30 | + |
| 31 | + if (status !== 0) { |
| 32 | + console.error(`Pre-receive hook failed with exit code ${status}`); |
| 33 | + step.error = true; |
| 34 | + step.log(`Hook stderr: ${stderr.trim()}`); |
| 35 | + step.setError(stdout.trim()); |
| 36 | + action.addStep(step); |
| 37 | + return action; |
| 38 | + } |
| 39 | + |
| 40 | + console.log('Pre-receive hook executed successfully'); |
| 41 | + console.log(`Hook stdout: ${stdout.trim()}`); |
| 42 | + step.log('Pre-receive hook executed successfully'); |
| 43 | + action.addStep(step); |
| 44 | + return action; |
| 45 | + } catch (error) { |
| 46 | + console.error('Error during pre-receive hook execution:', error); |
| 47 | + step.error = true; |
| 48 | + step.setError(`Hook execution error: ${error.message}`); |
| 49 | + action.addStep(step); |
| 50 | + return action; |
| 51 | + } |
| 52 | +}; |
| 53 | + |
| 54 | +exec.displayName = 'executeExternalPreReceiveHook.exec'; |
| 55 | +exports.exec = exec; |
0 commit comments