From fdc1b9a24d643825b02357de087b4101b7e19c3a Mon Sep 17 00:00:00 2001 From: Dragan Filipovic Date: Mon, 2 Jan 2023 12:57:35 +0100 Subject: [PATCH] Use promise --- dist/index.js | 2 +- src/index.js | 29 ++++++++------ src/remoteCmd.js | 24 +++++++---- src/rsyncCli.js | 102 ++++++++++++++++++++++------------------------- 4 files changed, 83 insertions(+), 74 deletions(-) diff --git a/dist/index.js b/dist/index.js index 9e898a6..37d75e2 100755 --- a/dist/index.js +++ b/dist/index.js @@ -1,2 +1,2 @@ #!/usr/bin/env node -(()=>{var e={898:(e,r,s)=>{"use strict";var t=s(81).spawn;var o=s(837);var escapeSpaces=function(e){if(typeof e==="string"){return e.replace(/\b\s/g,"\\ ")}else{return e}};var escapeSpacesInOptions=function(e){["src","dest","include","exclude","excludeFirst"].forEach((function(r){var s=e[r];if(typeof s==="string"){e[r]=escapeSpaces(s)}else if(Array.isArray(s)===true){e[r]=s.map(escapeSpaces)}}));return e};e.exports=function(e,r){e=e||{};e=o._extend({},e);e=escapeSpacesInOptions(e);var s=e.platform||process.platform;var n=s==="win32";if(typeof e.src==="undefined"){throw new Error("'src' directory is missing from options")}if(typeof e.dest==="undefined"){throw new Error("'dest' directory is missing from options")}var i=e.dest;if(typeof e.host!=="undefined"){i=e.host+":"+e.dest}if(!Array.isArray(e.src)){e.src=[e.src]}var c=[].concat(e.src);c.push(i);var a=(e.args||[]).find((function(e){return e.match(/--chmod=/)}));if(n&&!a){c.push("--chmod=ugo=rwX")}if(typeof e.host!=="undefined"||e.ssh){c.push("--rsh");var l="ssh";if(typeof e.port!=="undefined"){l+=" -p "+e.port}if(typeof e.privateKey!=="undefined"){l+=" -i "+e.privateKey}if(typeof e.sshCmdArgs!=="undefined"){l+=" "+e.sshCmdArgs.join(" ")}c.push(l)}if(e.recursive===true){c.push("--recursive")}if(e.times===true){c.push("--times")}if(e.syncDest===true||e.deleteAll===true){c.push("--delete");c.push("--delete-excluded")}if(e.syncDestIgnoreExcl===true||e.delete===true){c.push("--delete")}if(e.dryRun===true){c.push("--dry-run");c.push("--verbose")}if(typeof e.excludeFirst!=="undefined"&&o.isArray(e.excludeFirst)){e.excludeFirst.forEach((function(e,r){c.push("--exclude="+e)}))}if(typeof e.include!=="undefined"&&o.isArray(e.include)){e.include.forEach((function(e,r){c.push("--include="+e)}))}if(typeof e.exclude!=="undefined"&&o.isArray(e.exclude)){e.exclude.forEach((function(e,r){c.push("--exclude="+e)}))}switch(e.compareMode){case"sizeOnly":c.push("--size-only");break;case"checksum":c.push("--checksum");break}if(typeof e.args!=="undefined"&&o.isArray(e.args)){c=[...new Set([...c,...e.args])]}c=[...new Set(c)];var noop=function(){};var d=e.onStdout||noop;var u=e.onStderr||noop;var f="rsync ";c.forEach((function(e){if(e.substr(0,4)==="ssh "){e='"'+e+'"'}f+=e+" "}));f=f.trim();if(e.noExec){r(null,null,null,f);return}try{var p="";var h="";var y;if(n){y=t("cmd.exe",["/s","/c",'"'+f+'"'],{windowsVerbatimArguments:true,stdio:[process.stdin,"pipe","pipe"]})}else{y=t("/bin/sh",["-c",f])}y.stdout.on("data",(function(e){d(e);p+=e}));y.stderr.on("data",(function(e){u(e);h+=e}));y.on("exit",(function(e){var s=null;if(e!==0){s=new Error("rsync exited with code "+e);s.code=e}r(s,p,h,f)}))}catch(e){r(e,null,null,f)}}},505:(e,r,s)=>{const{existsSync:t,mkdirSync:o,writeFileSync:n}=s(147);const{join:i}=s(17);const validateDir=e=>{if(!e){console.log("[DIR] dir is not defined");return}if(t(e)){console.log(`[DIR] ${e} dir exist`);return}console.log(`[DIR] Creating ${e} dir in workspace root`);o(e);console.log("✅ [DIR] dir created.")};const writeToFile=({dir:e,filename:r,content:s,isRequired:o})=>{validateDir(e);const c=i(e,r);if(t(c)){console.log(`[FILE] ${c} file exist`);if(o){throw new Error(`⚠️ [FILE] ${c} Required file exist, aborting ...`)}return}try{console.log(`[FILE] writing ${c} file ...`,s.length);n(c,s,{encoding:"utf8",mode:384})}catch(e){throw new Error(`⚠️[FILE] Writing to file error. filePath: ${c}, message: ${e.message}`)}};const validateRequiredInputs=e=>{const r=Object.keys(e);const s=r.filter((r=>{const s=e[r];if(!s){console.error(`⚠️ [INPUTS] ${r} is mandatory`)}return s}));if(s.length!==r.length){throw new Error("⚠️ [INPUTS] Inputs not valid, aborting ...")}};const snakeToCamel=e=>e.replace(/[^a-zA-Z0-9]+(.)/g,((e,r)=>r.toUpperCase()));e.exports={writeToFile:writeToFile,validateRequiredInputs:validateRequiredInputs,snakeToCamel:snakeToCamel}},229:(e,r,s)=>{const{snakeToCamel:t}=s(505);const o=["REMOTE_HOST","REMOTE_USER","REMOTE_PORT","SSH_PRIVATE_KEY","DEPLOY_KEY_NAME","SOURCE","TARGET","ARGS","SSH_CMD_ARGS","EXCLUDE","SCRIPT_BEFORE","SCRIPT_AFTER"];const n=process.env.GITHUB_WORKSPACE;const i=process.env.REMOTE_USER;const c={source:"",target:`/home/${i}/`,exclude:"",args:"-rltgoDzvO",sshCmdArgs:"-o StrictHostKeyChecking=no",deployKeyName:"deploy_key"};const a={githubWorkspace:n};o.forEach((e=>{const r=t(e.toLowerCase());const s=process.env[e]||process.env[`INPUT_${e}`];const o=s===undefined?c[r]:s;let i=o;switch(r){case"source":i=`${n}/${o}`;break;case"exclude":case"args":case"sshCmdArgs":i=o.split(",").map((e=>e.trim()));break}a[r]=i}));a.sshServer=`${a.remoteUser}@${a.remoteHost}`;a.rsyncServer=`${a.remoteUser}@${a.remoteHost}:${a.target}`;e.exports=a},976:(e,r,s)=>{const{exec:t}=s(81);const{privateKey:o,sshServer:n,githubWorkspace:i}=s(229);const{writeToFile:c}=s(505);const remoteCmd=(e,r)=>{const s=`local_ssh_script-${r}.sh`;try{c({dir:i,filename:s,content:e});t(`ssh -i ${o} ${n} 'bash -s' < ${s}`,((e,r,s)=>{if(e){console.log("⚠️ [CMD] Remote script failed. ",e.message)}else{console.log("✅ [CMD] Remote script executed. \n",r,s)}}))}catch(e){console.log("⚠️ [CMD] Starting Remote script execution failed. ",e.message)}};e.exports={remoteCmdBefore:e=>remoteCmd(e,"before"),remoteCmdAfter:e=>remoteCmd(e,"after")}},447:(e,r,s)=>{const{execSync:t}=s(81);const o=s(898);const n=new Promise((async(e,r)=>{try{t("rsync --version",{stdio:"inherit"});console.log("⚠️ [CLI] Rsync exists");e();return}catch(e){console.log("⚠️ [CLI] Rsync doesn't exists",e)}console.log('⚠️ [CLI] Rsync doesn\'t exists. Start installation with "apt-get" \n');try{t("sudo DEBIAN_FRONTEND=noninteractive apt-get -y update && sudo DEBIAN_FRONTEND=noninteractive apt-get --no-install-recommends -y install rsync",{stdio:"inherit"});console.log("✅ [CLI] Rsync installed. \n");e()}catch(e){r(Error(`⚠️ [CLI] Rsync installation failed. Aborting ... error: ${e.message}`))}}));const rsyncCli=({source:e,rsyncServer:r,exclude:s,remotePort:t,privateKeyPath:n,args:i,sshCmdArgs:c,callback:a})=>{console.log(`[Rsync] Starting Rsync Action: ${e} to ${r}`);if(s)console.log(`[Rsync] excluding folders ${s}`);const l={ssh:true,recursive:true};try{o({...l,src:e,dest:r,excludeFirst:s,port:t,privateKey:n,args:i,sshCmdArgs:c},((e,r,s,t)=>{if(e){console.error("⚠️ [Rsync] error: ",e.message);console.log("⚠️ [Rsync] stderr: ",s);console.log("⚠️ [Rsync] stdout: ",r);console.log("⚠️ [Rsync] cmd: ",t)}else{console.log("✅ [Rsync] finished.",r)}a(e,r,s,t);if(e){process.abort()}}))}catch(e){console.error("⚠️ [Rsync] command error: ",e.message,e.stack);process.abort()}};const sshDeploy=e=>{n.then((()=>{rsyncCli(e)})).catch((e=>{throw e}))};e.exports={sshDeploy:sshDeploy}},822:(e,r,s)=>{const{join:t}=s(17);const{writeToFile:o}=s(505);const getPrivateKeyPath=e=>{const{HOME:r}=process.env;const s=t(r||__dirname,".ssh");return{dir:s,filename:e,path:t(s,e)}};const addSshKey=(e,r)=>{const{dir:s,filename:t}=getPrivateKeyPath(r);o({dir:s,filename:"known_hosts",content:""});console.log("✅ [SSH] known_hosts file ensured",s);o({dir:s,filename:t,content:e,isRequired:true});console.log("✅ [SSH] key added to `.ssh` dir ",s,t)};e.exports={getPrivateKeyPath:getPrivateKeyPath,addSshKey:addSshKey}},81:e=>{"use strict";e.exports=require("child_process")},147:e=>{"use strict";e.exports=require("fs")},17:e=>{"use strict";e.exports=require("path")},837:e=>{"use strict";e.exports=require("util")}};var r={};function __nccwpck_require__(s){var t=r[s];if(t!==undefined){return t.exports}var o=r[s]={exports:{}};var n=true;try{e[s](o,o.exports,__nccwpck_require__);n=false}finally{if(n)delete r[s]}return o.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var s={};(()=>{const{sshDeploy:e}=__nccwpck_require__(447);const{remoteCmdBefore:r,remoteCmdAfter:s}=__nccwpck_require__(976);const{addSshKey:t,getPrivateKeyPath:o}=__nccwpck_require__(822);const{validateRequiredInputs:n}=__nccwpck_require__(505);const i=__nccwpck_require__(229);const run=()=>{const{source:c,remoteUser:a,remoteHost:l,remotePort:d,deployKeyName:u,sshPrivateKey:f,args:p,exclude:h,sshCmdArgs:y,scriptBefore:m,scriptAfter:g,rsyncServer:_}=i;n({sshPrivateKey:f,remoteHost:l,remoteUser:a});t(f,u);const{path:v}=o(u);if(m){r(m)}let callback=()=>{};if(g){callback=(...e)=>{s(g,e)}}e({source:c,rsyncServer:_,exclude:h,remotePort:d,privateKeyPath:v,args:p,sshCmdArgs:y,callback:callback})};run()})();module.exports=s})(); \ No newline at end of file +(()=>{var e={898:(e,r,s)=>{"use strict";var t=s(81).spawn;var o=s(837);var escapeSpaces=function(e){if(typeof e==="string"){return e.replace(/\b\s/g,"\\ ")}else{return e}};var escapeSpacesInOptions=function(e){["src","dest","include","exclude","excludeFirst"].forEach((function(r){var s=e[r];if(typeof s==="string"){e[r]=escapeSpaces(s)}else if(Array.isArray(s)===true){e[r]=s.map(escapeSpaces)}}));return e};e.exports=function(e,r){e=e||{};e=o._extend({},e);e=escapeSpacesInOptions(e);var s=e.platform||process.platform;var n=s==="win32";if(typeof e.src==="undefined"){throw new Error("'src' directory is missing from options")}if(typeof e.dest==="undefined"){throw new Error("'dest' directory is missing from options")}var c=e.dest;if(typeof e.host!=="undefined"){c=e.host+":"+e.dest}if(!Array.isArray(e.src)){e.src=[e.src]}var i=[].concat(e.src);i.push(c);var a=(e.args||[]).find((function(e){return e.match(/--chmod=/)}));if(n&&!a){i.push("--chmod=ugo=rwX")}if(typeof e.host!=="undefined"||e.ssh){i.push("--rsh");var d="ssh";if(typeof e.port!=="undefined"){d+=" -p "+e.port}if(typeof e.privateKey!=="undefined"){d+=" -i "+e.privateKey}if(typeof e.sshCmdArgs!=="undefined"){d+=" "+e.sshCmdArgs.join(" ")}i.push(d)}if(e.recursive===true){i.push("--recursive")}if(e.times===true){i.push("--times")}if(e.syncDest===true||e.deleteAll===true){i.push("--delete");i.push("--delete-excluded")}if(e.syncDestIgnoreExcl===true||e.delete===true){i.push("--delete")}if(e.dryRun===true){i.push("--dry-run");i.push("--verbose")}if(typeof e.excludeFirst!=="undefined"&&o.isArray(e.excludeFirst)){e.excludeFirst.forEach((function(e,r){i.push("--exclude="+e)}))}if(typeof e.include!=="undefined"&&o.isArray(e.include)){e.include.forEach((function(e,r){i.push("--include="+e)}))}if(typeof e.exclude!=="undefined"&&o.isArray(e.exclude)){e.exclude.forEach((function(e,r){i.push("--exclude="+e)}))}switch(e.compareMode){case"sizeOnly":i.push("--size-only");break;case"checksum":i.push("--checksum");break}if(typeof e.args!=="undefined"&&o.isArray(e.args)){i=[...new Set([...i,...e.args])]}i=[...new Set(i)];var noop=function(){};var l=e.onStdout||noop;var u=e.onStderr||noop;var f="rsync ";i.forEach((function(e){if(e.substr(0,4)==="ssh "){e='"'+e+'"'}f+=e+" "}));f=f.trim();if(e.noExec){r(null,null,null,f);return}try{var p="";var h="";var y;if(n){y=t("cmd.exe",["/s","/c",'"'+f+'"'],{windowsVerbatimArguments:true,stdio:[process.stdin,"pipe","pipe"]})}else{y=t("/bin/sh",["-c",f])}y.stdout.on("data",(function(e){l(e);p+=e}));y.stderr.on("data",(function(e){u(e);h+=e}));y.on("exit",(function(e){var s=null;if(e!==0){s=new Error("rsync exited with code "+e);s.code=e}r(s,p,h,f)}))}catch(e){r(e,null,null,f)}}},505:(e,r,s)=>{const{existsSync:t,mkdirSync:o,writeFileSync:n}=s(147);const{join:c}=s(17);const validateDir=e=>{if(!e){console.log("[DIR] dir is not defined");return}if(t(e)){console.log(`[DIR] ${e} dir exist`);return}console.log(`[DIR] Creating ${e} dir in workspace root`);o(e);console.log("✅ [DIR] dir created.")};const writeToFile=({dir:e,filename:r,content:s,isRequired:o})=>{validateDir(e);const i=c(e,r);if(t(i)){console.log(`[FILE] ${i} file exist`);if(o){throw new Error(`⚠️ [FILE] ${i} Required file exist, aborting ...`)}return}try{console.log(`[FILE] writing ${i} file ...`,s.length);n(i,s,{encoding:"utf8",mode:384})}catch(e){throw new Error(`⚠️[FILE] Writing to file error. filePath: ${i}, message: ${e.message}`)}};const validateRequiredInputs=e=>{const r=Object.keys(e);const s=r.filter((r=>{const s=e[r];if(!s){console.error(`⚠️ [INPUTS] ${r} is mandatory`)}return s}));if(s.length!==r.length){throw new Error("⚠️ [INPUTS] Inputs not valid, aborting ...")}};const snakeToCamel=e=>e.replace(/[^a-zA-Z0-9]+(.)/g,((e,r)=>r.toUpperCase()));e.exports={writeToFile:writeToFile,validateRequiredInputs:validateRequiredInputs,snakeToCamel:snakeToCamel}},229:(e,r,s)=>{const{snakeToCamel:t}=s(505);const o=["REMOTE_HOST","REMOTE_USER","REMOTE_PORT","SSH_PRIVATE_KEY","DEPLOY_KEY_NAME","SOURCE","TARGET","ARGS","SSH_CMD_ARGS","EXCLUDE","SCRIPT_BEFORE","SCRIPT_AFTER"];const n=process.env.GITHUB_WORKSPACE;const c=process.env.REMOTE_USER;const i={source:"",target:`/home/${c}/`,exclude:"",args:"-rltgoDzvO",sshCmdArgs:"-o StrictHostKeyChecking=no",deployKeyName:"deploy_key"};const a={githubWorkspace:n};o.forEach((e=>{const r=t(e.toLowerCase());const s=process.env[e]||process.env[`INPUT_${e}`];const o=s===undefined?i[r]:s;let c=o;switch(r){case"source":c=`${n}/${o}`;break;case"exclude":case"args":case"sshCmdArgs":c=o.split(",").map((e=>e.trim()));break}a[r]=c}));a.sshServer=`${a.remoteUser}@${a.remoteHost}`;a.rsyncServer=`${a.remoteUser}@${a.remoteHost}:${a.target}`;e.exports=a},976:(e,r,s)=>{const{exec:t}=s(81);const{privateKey:o,sshServer:n,githubWorkspace:c}=s(229);const{writeToFile:i}=s(505);const handleError=(e,r,s)=>{const t=`⚠️ [CMD] Remote script failed: ${e}`;if(r){s(new Error(t))}else{console.log(t)}};const remoteCmd=async(e,r,s)=>new Promise(((a,d)=>{const l=`local_ssh_script-${r}.sh`;try{i({dir:c,filename:l,content:e});t(`ssh -i ${o} ${n} 'RSYNC_STDOUT=${process.env.RSYNC_STDOUT} bash -s' < ${l}`,((e,r,t)=>{if(e){handleError(e.message,s,d)}else{console.log("✅ [CMD] Remote script executed. \n",r,t);a(r)}}))}catch(e){handleError(e.message,s,d)}}));e.exports={remoteCmdBefore:async(e,r)=>remoteCmd(e,"before",r),remoteCmdAfter:async(e,r)=>remoteCmd(e,"after",r)}},447:(e,r,s)=>{const{execSync:t}=s(81);const o=s(898);const{writeToFile:n}=s(505);const nodeRsyncPromise=async e=>new Promise(((r,s)=>{try{o(e,((e,t,o,n)=>{if(e){console.log("⚠️ [Rsync] stderr: ",o);console.log("⚠️ [Rsync] stdout: ",t);console.log("⚠️ [Rsync] cmd: ",n);s(e)}else{r(t)}}))}catch(e){console.error("⚠️ [Rsync] command error: ",e.message,e.stack);s(e)}}));const validateRsync=async()=>{try{t("rsync --version",{stdio:"inherit"});console.log("⚠️ [CLI] Rsync exists");return}catch(e){console.log("⚠️ [CLI] Rsync doesn't exists",e)}console.log('⚠️ [CLI] Start rsync installation with "apt-get" \n');try{t("sudo DEBIAN_FRONTEND=noninteractive apt-get -y update && sudo DEBIAN_FRONTEND=noninteractive apt-get --no-install-recommends -y install rsync",{stdio:"inherit"});console.log("✅ [CLI] Rsync installed. \n")}catch(e){throw new Error(`⚠️ [CLI] Rsync installation failed. Aborting ... error: ${e.message}`)}};const rsyncCli=async({source:e,rsyncServer:r,exclude:s,remotePort:t,privateKeyPath:o,args:n,sshCmdArgs:c})=>{console.log(`[Rsync] Starting Rsync Action: ${e} to ${r}`);if(s)console.log(`[Rsync] excluding folders ${s}`);const i={ssh:true,recursive:true};return nodeRsyncPromise({...i,src:e,dest:r,excludeFirst:s,port:t,privateKey:o,args:n,sshCmdArgs:c})};const sshDeploy=async e=>{await validateRsync();const r=await rsyncCli(e);console.log("✅ [Rsync] finished.",r);process.env.RSYNC_STDOUT=r;return r};e.exports={sshDeploy:sshDeploy}},822:(e,r,s)=>{const{join:t}=s(17);const{writeToFile:o}=s(505);const getPrivateKeyPath=e=>{const{HOME:r}=process.env;const s=t(r||__dirname,".ssh");return{dir:s,filename:e,path:t(s,e)}};const addSshKey=(e,r)=>{const{dir:s,filename:t}=getPrivateKeyPath(r);o({dir:s,filename:"known_hosts",content:""});console.log("✅ [SSH] known_hosts file ensured",s);o({dir:s,filename:t,content:e,isRequired:true});console.log("✅ [SSH] key added to `.ssh` dir ",s,t)};e.exports={getPrivateKeyPath:getPrivateKeyPath,addSshKey:addSshKey}},81:e=>{"use strict";e.exports=require("child_process")},147:e=>{"use strict";e.exports=require("fs")},17:e=>{"use strict";e.exports=require("path")},837:e=>{"use strict";e.exports=require("util")}};var r={};function __nccwpck_require__(s){var t=r[s];if(t!==undefined){return t.exports}var o=r[s]={exports:{}};var n=true;try{e[s](o,o.exports,__nccwpck_require__);n=false}finally{if(n)delete r[s]}return o.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var s={};(()=>{const{sshDeploy:e}=__nccwpck_require__(447);const{remoteCmdBefore:r,remoteCmdAfter:s}=__nccwpck_require__(976);const{addSshKey:t,getPrivateKeyPath:o}=__nccwpck_require__(822);const{validateRequiredInputs:n}=__nccwpck_require__(505);const c=__nccwpck_require__(229);const run=async()=>{const{source:i,remoteUser:a,remoteHost:d,remotePort:l,deployKeyName:u,sshPrivateKey:f,args:p,exclude:h,sshCmdArgs:y,scriptBefore:m,scriptAfter:g,rsyncServer:_}=c;n({sshPrivateKey:f,remoteHost:d,remoteUser:a});t(f,u);const{path:v}=o(u);if(m){await r(m)}await e({source:i,rsyncServer:_,exclude:h,remotePort:l,privateKeyPath:v,args:p,sshCmdArgs:y});if(g){await s(g)}};run().then((()=>{console.log("DONE")})).catch((()=>{console.error("ERROR")}))})();module.exports=s})(); \ No newline at end of file diff --git a/src/index.js b/src/index.js index 6bb6ee2..4564505 100644 --- a/src/index.js +++ b/src/index.js @@ -5,7 +5,7 @@ const { addSshKey, getPrivateKeyPath } = require('./sshKey'); const { validateRequiredInputs } = require('./helpers'); const inputs = require('./inputs'); -const run = () => { +const run = async () => { const { source, remoteUser, remoteHost, remotePort, deployKeyName, sshPrivateKey, @@ -20,20 +20,25 @@ const run = () => { const { path: privateKeyPath } = getPrivateKeyPath(deployKeyName); // Check Script before if (scriptBefore) { - remoteCmdBefore(scriptBefore); - } - // Check script after - let callback = () => {}; - if (scriptAfter) { - callback = (...result) => { - remoteCmdAfter(scriptAfter, result); - }; + await remoteCmdBefore(scriptBefore); } + /* eslint-disable object-property-newline */ - sshDeploy({ + await sshDeploy({ source, rsyncServer, exclude, remotePort, - privateKeyPath, args, sshCmdArgs, callback + privateKeyPath, args, sshCmdArgs }); + + // Check script after + if (scriptAfter) { + await remoteCmdAfter(scriptAfter); + } }; -run(); +run() + .then(() => { + console.log('DONE'); + }) + .catch(() => { + console.error('ERROR'); + }); diff --git a/src/remoteCmd.js b/src/remoteCmd.js index 9e73140..1e01476 100644 --- a/src/remoteCmd.js +++ b/src/remoteCmd.js @@ -3,24 +3,34 @@ const { exec } = require('child_process'); const { privateKey, sshServer, githubWorkspace } = require('./inputs'); const { writeToFile } = require('./helpers'); -const remoteCmd = (content, label) => { +const handleError = (errorMessage, isRequired, callback) => { + const message = `⚠️ [CMD] Remote script failed: ${errorMessage}`; + if (isRequired) { + callback(new Error(message)); + } else { + console.log(message); + } +}; + +const remoteCmd = async (content, label, isRequired) => new Promise((resolve, reject) => { const filename = `local_ssh_script-${label}.sh`; try { writeToFile({ dir: githubWorkspace, filename, content }); - exec(`ssh -i ${privateKey} ${sshServer} 'bash -s' < ${filename}`, (err, data, stderr) => { + exec(`ssh -i ${privateKey} ${sshServer} 'RSYNC_STDOUT=${process.env.RSYNC_STDOUT} bash -s' < ${filename}`, (err, data, stderr) => { if (err) { - console.log('⚠️ [CMD] Remote script failed. ', err.message); + handleError(err.message, isRequired, reject); } else { console.log('✅ [CMD] Remote script executed. \n', data, stderr); + resolve(data); } }); } catch (err) { - console.log('⚠️ [CMD] Starting Remote script execution failed. ', err.message); + handleError(err.message, isRequired, reject); } -}; +}); module.exports = { - remoteCmdBefore: (cmd) => remoteCmd(cmd, 'before'), - remoteCmdAfter: (cmd) => remoteCmd(cmd, 'after') + remoteCmdBefore: async (cmd, isRequired) => remoteCmd(cmd, 'before', isRequired), + remoteCmdAfter: async (cmd, isRequired) => remoteCmd(cmd, 'after', isRequired) }; diff --git a/src/rsyncCli.js b/src/rsyncCli.js index e3db592..eb192cb 100644 --- a/src/rsyncCli.js +++ b/src/rsyncCli.js @@ -1,30 +1,46 @@ const { execSync } = require('child_process'); const nodeRsync = require('rsyncwrapper'); +const { writeToFile } = require('./helpers'); -// eslint-disable-next-line no-async-promise-executor -const validateRsync = new Promise(async (resolve, reject) => { +const nodeRsyncPromise = async (config) => new Promise((resolve, reject) => { try { - execSync('rsync --version', { stdio: 'inherit' }); - console.log('⚠️ [CLI] Rsync exists'); - resolve(); - return; - } catch (e) { - console.log('⚠️ [CLI] Rsync doesn\'t exists', e); - } - - console.log('⚠️ [CLI] Rsync doesn\'t exists. Start installation with "apt-get" \n'); - try { - execSync('sudo DEBIAN_FRONTEND=noninteractive apt-get -y update && sudo DEBIAN_FRONTEND=noninteractive apt-get --no-install-recommends -y install rsync', { stdio: 'inherit' }); - console.log('✅ [CLI] Rsync installed. \n'); - resolve(); - } catch (err) { - reject(Error(`⚠️ [CLI] Rsync installation failed. Aborting ... error: ${err.message}`)); + nodeRsync(config, (error, stdout, stderr, cmd) => { + if (error) { + console.log('⚠️ [Rsync] stderr: ', stderr); + console.log('⚠️ [Rsync] stdout: ', stdout); + console.log('⚠️ [Rsync] cmd: ', cmd); + reject(error); + } else { + resolve(stdout); + } + }); + } catch (error) { + console.error('⚠️ [Rsync] command error: ', error.message, error.stack); + reject(error); } }); -const rsyncCli = ({ +const validateRsync = async () => { + try { + execSync('rsync --version', { stdio: 'inherit' }); + console.log('⚠️ [CLI] Rsync exists'); + return; + } catch (error) { + console.log('⚠️ [CLI] Rsync doesn\'t exists', error); + } + + console.log('⚠️ [CLI] Start rsync installation with "apt-get" \n'); + try { + execSync('sudo DEBIAN_FRONTEND=noninteractive apt-get -y update && sudo DEBIAN_FRONTEND=noninteractive apt-get --no-install-recommends -y install rsync', { stdio: 'inherit' }); + console.log('✅ [CLI] Rsync installed. \n'); + } catch (error) { + throw new Error(`⚠️ [CLI] Rsync installation failed. Aborting ... error: ${error.message}`); + } +}; + +const rsyncCli = async ({ source, rsyncServer, exclude, remotePort, - privateKeyPath, args, sshCmdArgs, callback + privateKeyPath, args, sshCmdArgs }) => { console.log(`[Rsync] Starting Rsync Action: ${source} to ${rsyncServer}`); if (exclude) console.log(`[Rsync] excluding folders ${exclude}`); @@ -34,43 +50,21 @@ const rsyncCli = ({ recursive: true }; - try { - // RSYNC COMMAND - /* eslint-disable object-property-newline */ - nodeRsync({ - ...defaultOptions, - src: source, dest: rsyncServer, excludeFirst: exclude, port: remotePort, - privateKey: privateKeyPath, args, sshCmdArgs - }, (error, stdout, stderr, cmd) => { - if (error) { - console.error('⚠️ [Rsync] error: ', error.message); - console.log('⚠️ [Rsync] stderr: ', stderr); - console.log('⚠️ [Rsync] stdout: ', stdout); - console.log('⚠️ [Rsync] cmd: ', cmd); - } else { - console.log('✅ [Rsync] finished.', stdout); - } - - callback(error, stdout, stderr, cmd); - - if (error) { - process.abort(); - } - }); - } catch (err) { - console.error('⚠️ [Rsync] command error: ', err.message, err.stack); - process.abort(); - } + // RSYNC COMMAND + /* eslint-disable object-property-newline */ + return nodeRsyncPromise({ + ...defaultOptions, + src: source, dest: rsyncServer, excludeFirst: exclude, port: remotePort, + privateKey: privateKeyPath, args, sshCmdArgs + }); }; -const sshDeploy = (params) => { - validateRsync - .then(() => { - rsyncCli(params); - }) - .catch((err) => { - throw err; - }); +const sshDeploy = async (params) => { + await validateRsync(); + const stdout = await rsyncCli(params); + console.log('✅ [Rsync] finished.', stdout); + process.env.RSYNC_STDOUT = stdout; + return stdout; }; module.exports = {