diff --git a/src/helpers.js b/src/helpers.js index 1c705df..78379e1 100644 --- a/src/helpers.js +++ b/src/helpers.js @@ -1,4 +1,4 @@ -const { existsSync, mkdirSync, writeFileSync } = require('fs'); +const { existsSync, mkdirSync, writeFileSync, unlink } = require('fs'); const { join } = require('path'); const validateDir = (dir) => { @@ -45,6 +45,29 @@ const writeToFile = ({ dir, filename, content, isRequired, mode = '0644' }) => { } }; +const deleteFile = ({ dir, filename, isRequired }) => { + validateDir(dir); + const filePath = join(dir, filename); + + if (existsSync(filePath)) { + const message = `⚠️ [FILE] ${filePath} Required file exist.`; + handleError(message, isRequired); + return; + } + + try { + console.log(`[FILE] Deleting ${filePath} file ...`); + unlink(filePath, (error) => { + if (error) { + throw new Error(error); + } + }); + } catch (error) { + const message = `⚠️[FILE] Deleting file error. filePath: ${filePath}, message: ${error.message}`; + handleError(message, isRequired); + } +}; + const validateRequiredInputs = (inputs) => { const inputKeys = Object.keys(inputs); const validInputs = inputKeys.filter((inputKey) => { @@ -66,6 +89,7 @@ const snakeToCamel = (str) => str.replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.t module.exports = { writeToFile, + deleteFile, validateRequiredInputs, snakeToCamel }; diff --git a/src/remoteCmd.js b/src/remoteCmd.js index 3881b20..70f7656 100644 --- a/src/remoteCmd.js +++ b/src/remoteCmd.js @@ -1,7 +1,7 @@ const { exec } = require('child_process'); const crypto = require('crypto'); const { sshServer, githubWorkspace, remotePort } = require('./inputs'); -const { writeToFile } = require('./helpers'); +const { writeToFile, deleteFile } = require('./helpers'); const handleError = (message, isRequired, callback) => { if (isRequired) { @@ -30,6 +30,8 @@ const remoteCmd = async (content, privateKeyPath, isRequired, label) => new Prom } else { const limited = data.substring(0, dataLimit); console.log('✅ [CMD] Remote script executed. \n', limited, stderr); + deleteFile({ dir: githubWorkspace, filename }); + console.log('✅ [FILE] Script file deleted.'); resolve(limited); } }