theme-utils.mjs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. import { spawn } from 'child_process';
  2. import fs from 'fs';
  3. import open from 'open';
  4. import inquirer from 'inquirer';
  5. const remoteSSH = 'wpcom-sandbox';
  6. const sandboxPublicThemesFolder = '/home/wpdev/public_html/wp-content/themes/pub';
  7. const sandboxRootFolder = '/home/wpdev/public_html/';
  8. const isWin = process.platform === 'win32';
  9. (async function start() {
  10. let args = process.argv.slice(2);
  11. let command = args?.[0];
  12. switch (command) {
  13. case "push-button-deploy-git": return pushButtonDeploy('git');
  14. case "push-button-deploy-svn": return pushButtonDeploy('svn');
  15. case "clean-sandbox-git": return cleanSandboxGit();
  16. case "clean-sandbox-svn": return cleanSandboxSvn();
  17. case "clean-all-sandbox-git": return cleanAllSandboxGit();
  18. case "clean-all-sandbox-svn": return cleanAllSandboxSvn();
  19. case "push-to-sandbox": return pushToSandbox();
  20. case "push-changes-to-sandbox": return pushChangesToSandbox();
  21. case "version-bump-themes": return versionBumpThemes();
  22. case "land-diff-git": return landChangesGit(args?.[1]);
  23. case "land-diff-svn": return landChangesSvn(args?.[1]);
  24. case "deploy-preview": return deployPreview();
  25. }
  26. return showHelp();
  27. })();
  28. function showHelp(){
  29. // TODO: make this helpful
  30. console.log('Help info can go here');
  31. }
  32. /*
  33. Determine what changes would be deployed
  34. */
  35. async function deployPreview() {
  36. console.clear();
  37. console.log('To ensure accuracy clean your sandbox before previewing. (It is not automatically done).');
  38. console.log('npm run sandbox:clean:git OR npm run sandbox:clean:svn')
  39. let message = await checkForDeployability();
  40. if (message) {
  41. console.log(`\n${message}\n\n`);
  42. }
  43. let hash = await getLastDeployedHash();
  44. console.log(`Last deployed hash: ${hash}`);
  45. let changedThemes = await getChangedThemes(hash);
  46. console.log(`The following themes have changes:\n${changedThemes}`);
  47. let logs = await executeCommand(`git log --reverse --pretty=format:%s ${hash}..HEAD`);
  48. console.log(`\n\nCommit log of changes to be deployed:\n\n${logs}\n\n`);
  49. }
  50. /*
  51. Execute the first phase of a deployment.
  52. Leverages git on the sandbox.
  53. * Gets the last deployed hash from the sandbox
  54. * Version bump all themes have have changes since the last deployment
  55. * Commit the version bump change to github
  56. * Clean the sandbox and ensure it is up-to-date
  57. * Push all changed files (including removal of deleted files) since the last deployment
  58. * Update the 'last deployed' hash on the sandbox
  59. * Create a phabricator diff based on the changes since the last deployment. The description including the commit messages since the last deployment.
  60. * Open the Phabricator Diff in your browser
  61. * Create a tag in the github repository at this point of change which includes the phabricator link in the description
  62. */
  63. async function pushButtonDeploy(repoType) {
  64. if (repoType != 'svn' && repoType != 'git' ) {
  65. return console.log('Specify a repo type to use push-button deploy');
  66. }
  67. let message = await checkForDeployability();
  68. if (message) {
  69. return console.log(`\n\n${message}\n\n`);
  70. }
  71. try {
  72. console.clear();
  73. let prompt = await inquirer.prompt([{
  74. type: 'confirm',
  75. message: 'You are about to deploy /trunk. Are you ready to continue?',
  76. name: "continue",
  77. default: false
  78. }]);
  79. if(!prompt.continue){
  80. return;
  81. }
  82. let hash = await getLastDeployedHash();
  83. let diffUrl;
  84. await versionBumpThemes();
  85. let changedThemes = await getChangedThemes(hash);
  86. //TODO: Can these be automagically uploaded?
  87. //await buildChangedOrgZips();
  88. if (repoType === 'git' ) {
  89. await cleanSandboxGit();
  90. }
  91. else {
  92. await cleanSandboxSvn();
  93. }
  94. await pushChangesToSandbox();
  95. await updateLastDeployedHash();
  96. if (repoType === 'git' ) {
  97. diffUrl = await createGitPhabricatorDiff(hash);
  98. }
  99. else {
  100. diffUrl = await createSvnPhabricatorDiff(hash);
  101. }
  102. let diffId = diffUrl.split('a8c.com/')[1];
  103. //push changes (from version bump)
  104. await executeCommand('git push');
  105. await tagDeployment({
  106. hash: hash,
  107. diffId: diffId
  108. });
  109. console.log(`\n\nPhase One Complete\n\nYour sandbox has been updated and the diff is available for review.\nPlease give your sandbox a smoke test to determine that the changes work as expected.\nThe following themes have had changes: \n\n${changedThemes}\n\n\n`);
  110. prompt = await inquirer.prompt([{
  111. type: 'confirm',
  112. message: 'Are you ready to land these changes?',
  113. name: "continue",
  114. default: false
  115. }]);
  116. if(!prompt.continue){
  117. console.log(`Aborted Automated Deploy Process Landing Phase\n\nYou will have to land these changes manually. The ID of the diff to land: ${diffId}` );
  118. return;
  119. }
  120. if (repoType === 'git' ) {
  121. landChangesGit(diffId);
  122. }
  123. else {
  124. landChangesSvn(diffId);
  125. }
  126. prompt = await inquirer.prompt([{
  127. type: 'confirm',
  128. message: 'The changes have landed. Do you wish to deploy the changed themes now?',
  129. name: "continue",
  130. default: false
  131. }]);
  132. if(!prompt.continue){
  133. console.log(`Aborted Automated Deploy Process Deploy Phase. Please deploy the following themes manually:\n${changedThemes}` );
  134. return;
  135. }
  136. await deployThemes(changedThemes);
  137. //TODO: Can this be automated?
  138. open('https://mc.a8c.com/themes/downloads/');
  139. console.log('Please build the .zip files for the themes manually');
  140. console.log('\n\nAll Done!!\n\n');
  141. }
  142. catch (err) {
  143. console.log("ERROR with deply script: ", err);
  144. }
  145. }
  146. /*
  147. Check to ensure that:
  148. * The current branch is /trunk
  149. * That trunk is up-to-date with origin/trunk
  150. */
  151. async function checkForDeployability(){
  152. let branchName = await executeCommand('git symbolic-ref --short HEAD');
  153. if(branchName !== 'trunk' ) {
  154. return 'Only the /trunk branch can be deployed.';
  155. }
  156. await executeCommand('git remote update', true);
  157. let localMasterHash = await executeCommand('git rev-parse trunk')
  158. let remoteMasterHash = await executeCommand('git rev-parse origin/trunk')
  159. if(localMasterHash !== remoteMasterHash) {
  160. return 'Local /trunk is out-of-date. Pull changes to continue.'
  161. }
  162. return null;
  163. }
  164. /*
  165. Land the changes from the given diff ID. This is the "production merge".
  166. This is the git version of that action.
  167. */
  168. async function landChangesGit(diffId){
  169. return await executeOnSandbox(`
  170. cd ${sandboxPublicThemesFolder};
  171. arc patch ${diffId}
  172. arc land
  173. `, true);
  174. }
  175. /*
  176. Land the changes from the given diff ID. This is the "production merge".
  177. This is the svn version of that action.
  178. */
  179. async function landChangesSvn(diffId){
  180. return await executeOnSandbox(`
  181. cd ${sandboxPublicThemesFolder};
  182. svn ci -m ${diffId}
  183. `, true);
  184. }
  185. async function getChangedThemes(hash) {
  186. console.log('Determining all changed themes')
  187. let themes = await getActionableThemes();
  188. let changedThemes = [];
  189. for (let theme of themes) {
  190. let hasChanges = await checkThemeForChanges(theme, hash);
  191. if(hasChanges){
  192. changedThemes.push(theme.replace('./', ''));
  193. }
  194. }
  195. return changedThemes;
  196. }
  197. async function deployThemes(themes) {
  198. let response;
  199. for (let theme of themes ) {
  200. response = await executeOnSandbox(`deploy pub ${theme}`, true);
  201. //TODO: if the response wasn't happy then prompt to try again.
  202. }
  203. }
  204. /*
  205. Provide the hash of the last managed deployment.
  206. This hash is used to determine all the changes that have happened between that point and the current point.
  207. */
  208. async function getLastDeployedHash() {
  209. let result = await executeOnSandbox(`
  210. cat ${sandboxPublicThemesFolder}/.pub-git-hash
  211. `);
  212. return result;
  213. }
  214. /*
  215. Update the 'last deployed hash' on the server with the current hash.
  216. */
  217. async function updateLastDeployedHash() {
  218. let hash = await executeCommand(`git rev-parse HEAD`);
  219. await executeOnSandbox(`
  220. echo '${hash}' > ${sandboxPublicThemesFolder}/.pub-git-hash
  221. `);
  222. }
  223. /*
  224. Version bump (increment version patch) any theme project that has had changes since the last deployment.
  225. If a theme's version has already been changed since that last deployment then do not version bump it.
  226. If any theme projects have had a version bump also version bump the parent project.
  227. Commit the change.
  228. */
  229. async function versionBumpThemes() {
  230. console.log("Version Bumping");
  231. let themes = await getActionableThemes();
  232. let hash = await getLastDeployedHash();
  233. let versionBumpCount = 0;
  234. for (let theme of themes) {
  235. let hasChanges = await checkThemeForChanges(theme, hash);
  236. if( ! hasChanges){
  237. // console.log(`${theme} has no changes`);
  238. continue;
  239. }
  240. versionBumpCount++;
  241. let hasVersionBump = await checkThemeForVersionBump(theme, hash);
  242. if( hasVersionBump ){
  243. // console.log(`${theme} has already been version bumped`);
  244. continue;
  245. }
  246. await versionBumpTheme(theme);
  247. }
  248. //version bump the root project if there were changes to any of the themes
  249. let rootHasVersionBump = await checkThemeForVersionBump('.', hash);
  250. if ( versionBumpCount > 0 && ! rootHasVersionBump ) {
  251. await executeCommand(`npm version patch --no-git-tag-version`);
  252. }
  253. if (versionBumpCount > 0 && !rootHasVersionBump) {
  254. console.log('commiting version-bump');
  255. await executeCommand(`
  256. git commit -a -m "Version Bump";
  257. `, true);
  258. }
  259. }
  260. /*
  261. Version Bump a Theme.
  262. Used by versionBumpThemes to do the work of version bumping.
  263. First increment the patch version in package.json (the source of truth for versioning)
  264. Then update any of these files with the new version: [style.css, style.scss, style-child-theme.scss]
  265. */
  266. async function versionBumpTheme(theme){
  267. console.log(`${theme} needs a version bump`);
  268. await executeCommand(`npm --prefix ${theme} version patch --no-git-tag-version`);
  269. let currentPackage = JSON.parse(fs.readFileSync(`${theme}/package.json`))
  270. let currentVersion = currentPackage.version;
  271. let filesToUpdate = await executeCommand(`find ${theme} -name style.css -o -name style.scss -o -name style-child-theme.scss -maxdepth 2`);
  272. filesToUpdate = filesToUpdate.split('\n');
  273. for ( let file of filesToUpdate ) {
  274. console.log('updating file', file, currentVersion);
  275. //TODO: I'm sure we can use something other than perl for this but this was prior art...
  276. await executeCommand(`perl -pi -e 's/Version: (.*)$/"Version: '${currentVersion}'"/ge' ${file}`);
  277. }
  278. }
  279. /*
  280. Determine if a theme has had a version bump since a given hash.
  281. Used by versionBumpThemes
  282. Compares the value of 'version' in package.json between the hash and current value
  283. */
  284. async function checkThemeForVersionBump(theme, hash){
  285. let previousPackageString = await executeCommand(`
  286. git show ${hash}:${theme}/package.json 2>/dev/null
  287. `);
  288. let previousPackage = JSON.parse(previousPackageString);
  289. let currentPackage = JSON.parse(fs.readFileSync(`${theme}/package.json`))
  290. return previousPackage.version != currentPackage.version;
  291. }
  292. /*
  293. Determine if a theme has had changes since a given hash.
  294. Used by versionBumpThemes
  295. */
  296. async function checkThemeForChanges(theme, hash){
  297. let uncomittedChanges = await executeCommand(`git diff-index --name-only HEAD -- ${theme}`);
  298. let comittedChanges = await executeCommand(`git diff --name-only ${hash} HEAD -- ${theme}`);
  299. return uncomittedChanges != '' || comittedChanges != '';
  300. }
  301. /*
  302. Provide a list of 'actionable' themes (those themes that have package.json files)
  303. */
  304. async function getActionableThemes() {
  305. //TODO: This could be done more effeciently. It's very slow running.
  306. let result = await executeCommand(`find . -depth 2 -name package.json -print0 | xargs -0 -n1 dirname | sort --unique`);
  307. return result.split('\n');
  308. }
  309. async function buildChangedOrgZips() {
  310. console.log("Building .org Zip files");
  311. await executeCommand(`./theme-batch-utils.sh build-org-zip-if-changed`, true);
  312. }
  313. /*
  314. Clean the theme sandbox.
  315. Assumes sandbox is in 'git' mode
  316. checkout origin/develop and ensure it's up-to-date.
  317. Remove any other changes.
  318. */
  319. async function cleanSandboxGit() {
  320. console.log('Cleaning the Themes Sandbox');
  321. await executeOnSandbox(`
  322. cd ${sandboxPublicThemesFolder};
  323. git reset --hard HEAD;
  324. git clean -fd;
  325. git checkout develop;
  326. git pull;
  327. echo;
  328. git status
  329. `, true);
  330. console.log('All done cleaning.');
  331. }
  332. /*
  333. Clean the entire sandbox.
  334. Assumes sandbox is in 'git' mode
  335. checkout origin/develop and ensure it's up-to-date.
  336. Remove any other changes.
  337. */
  338. async function cleanAllSandboxGit() {
  339. console.log('Cleaning the Entire Sandbox');
  340. let response = await executeOnSandbox(`
  341. cd ${sandboxRootFolder};
  342. git reset --hard HEAD;
  343. git clean -fd;
  344. git checkout develop;
  345. git pull;
  346. echo;
  347. git status
  348. `, true);
  349. console.log('All done cleaning.');
  350. }
  351. /*
  352. Clean the theme sandbox.
  353. Assumes sandbox is in 'svn' mode
  354. ensure trunk is up-to-date
  355. Remove any other changes
  356. */
  357. async function cleanSandboxSvn() {
  358. console.log('Cleaning the theme sandbox');
  359. await executeOnSandbox(`
  360. cd ${sandboxPublicThemesFolder};
  361. svn revert -R .;
  362. svn cleanup --remove-unversioned;
  363. svn up;
  364. `, true);
  365. console.log('All done cleaning.');
  366. }
  367. /*
  368. Clean the entire sandbox.
  369. Assumes sandbox is in 'svn' mode
  370. ensure trunk is up-to-date
  371. Remove any other changes
  372. */
  373. async function cleanAllSandboxSvn() {
  374. console.log('Cleaning the entire sandbox');
  375. await executeOnSandbox(`
  376. cd ${sandboxRootFolder};
  377. svn revert -R .;
  378. svn cleanup --remove-unversioned;
  379. svn up .;
  380. `, true);
  381. console.log('All done cleaning.');
  382. }
  383. /*
  384. Push exactly what is here (all files) up to the sandbox (with the exclusion of files noted in .sandbox-ignore)
  385. */
  386. function pushToSandbox() {
  387. executeCommand(`
  388. rsync -av --no-p --no-times --exclude-from='.sandbox-ignore' ./ wpcom-sandbox:${sandboxPublicThemesFolder}/
  389. `);
  390. }
  391. /*
  392. Push only (and every) change since the point-of-diversion from /trunk
  393. Remove files from the sandbox that have been removed since the last deployed hash
  394. */
  395. async function pushChangesToSandbox() {
  396. console.log("Pushing Changes to Sandbox.");
  397. let hash = await getLastDeployedHash();
  398. let deletedFiles = await getDeletedFilesSince(hash);
  399. let changedFiles = await getComittedChangesSinceHash(hash);
  400. //remove deleted files from changed files
  401. changedFiles = changedFiles.filter( item => {
  402. return false === deletedFiles.includes(item);
  403. });
  404. if(deletedFiles.length > 0) {
  405. console.log('deleting from sandbox: ', deletedFiles);
  406. await executeOnSandbox(`
  407. cd ${sandboxPublicThemesFolder};
  408. rm -f ${deletedFiles.join(' ')}
  409. `, true);
  410. }
  411. if(changedFiles.length > 0) {
  412. console.log('pushing changed files to sandbox:', changedFiles);
  413. await executeCommand(`
  414. rsync -avR --no-p --no-times --exclude-from='.sandbox-ignore' ${changedFiles.join(' ')} wpcom-sandbox:${sandboxPublicThemesFolder}/
  415. `, true);
  416. }
  417. }
  418. /*
  419. Provide a collection of all files that have changed since the given hash.
  420. Used by pushChangesToSandbox
  421. */
  422. async function getComittedChangesSinceHash(hash) {
  423. let comittedChanges = await executeCommand(`git diff ${hash} HEAD --name-only`);
  424. comittedChanges = comittedChanges.replace(/\r?\n|\r/g, " ").split(" ");
  425. let uncomittedChanges = await executeCommand(`git diff HEAD --name-only`);
  426. uncomittedChanges = uncomittedChanges.replace(/\r?\n|\r/g, " ").split(" ");
  427. return comittedChanges.concat(uncomittedChanges);
  428. }
  429. /*
  430. Provide a collection of all files that have been deleted since the given hash.
  431. Used by pushChangesToSandbox
  432. */
  433. async function getDeletedFilesSince(hash){
  434. let deletedSinceHash = await executeCommand(`
  435. git log --format=format:"" --name-only -M100% --diff-filter=D ${hash}..HEAD
  436. `);
  437. deletedSinceHash = deletedSinceHash.replace(/\r?\n|\r/g, " ").trim().split(" ");
  438. let deletedAndUncomitted = await executeCommand(`
  439. git diff HEAD --name-only --diff-filter=D
  440. `);
  441. deletedAndUncomitted = deletedAndUncomitted.replace(/\r?\n|\r/g, " ").trim().split(" ");
  442. return deletedSinceHash.concat(deletedAndUncomitted).filter( item => {
  443. return item != '';
  444. });
  445. }
  446. /*
  447. Build the Phabricator commit message.
  448. This message contains the logs from all of the commits since the given hash.
  449. Used by create*PhabricatorDiff
  450. */
  451. async function buildPhabricatorCommitMessageSince(hash){
  452. let projectVersion = await executeCommand(`node -p "require('./package.json').version"`);
  453. let logs = await executeCommand(`git log --reverse --pretty=format:%s ${hash}..HEAD`);
  454. return `Deploy Themes ${projectVersion} to wpcom
  455. Summary:
  456. ${logs}
  457. Test Plan: Execute Smoke Test
  458. Reviewers:
  459. Subscribers:
  460. `;
  461. }
  462. /*
  463. Create a (git) Phabricator diff from a given hash.
  464. Open the phabricator diff in your browser.
  465. Provide the URL of the phabricator diff.
  466. */
  467. async function createGitPhabricatorDiff(hash) {
  468. console.log('creating Phabricator Diff');
  469. let commitMessage = await buildPhabricatorCommitMessageSince(hash);
  470. let result = await executeOnSandbox(`
  471. cd ${sandboxPublicThemesFolder};
  472. git branch -D deploy
  473. git checkout -b deploy
  474. git add --all
  475. git commit -m "${commitMessage}"
  476. arc diff --create --verbatim
  477. `, true);
  478. let phabricatorUrl = getPhabricatorUrlFromResponse(result);
  479. console.log('Diff Created at: ', phabricatorUrl);
  480. if(phabricatorUrl) {
  481. open(phabricatorUrl);
  482. }
  483. return phabricatorUrl;
  484. }
  485. /*
  486. Create a (svn) Phabricator diff from a given hash.
  487. Open the phabricator diff in your browser.
  488. Provide the URL of the phabricator diff.
  489. */
  490. async function createSvnPhabricatorDiff(hash) {
  491. console.log('creating Phabricator Diff');
  492. const commitTempFileLocation = '/tmp/theme-deploy-comment.txt';
  493. const commitMessage = await buildPhabricatorCommitMessageSince(hash);
  494. const result = await executeOnSandbox(`
  495. cd ${sandboxPublicThemesFolder};
  496. echo '${commitMessage}' > ${commitTempFileLocation}
  497. svn add --force * --auto-props --parents --depth infinity -q
  498. arc diff --create --message-file ${commitTempFileLocation}
  499. `, true);
  500. const phabricatorUrl = getPhabricatorUrlFromResponse(result);
  501. console.log('Diff Created at: ', phabricatorUrl);
  502. if(phabricatorUrl) {
  503. open(phabricatorUrl);
  504. }
  505. return phabricatorUrl;
  506. }
  507. /*
  508. Utility to pull the Phabricator URL from the diff creation command.
  509. Used by createGitPhabricatorDiff
  510. */
  511. function getPhabricatorUrlFromResponse(response){
  512. return response
  513. ?.split('\n')
  514. ?.find( item => {
  515. return item.includes('Revision URI: ');
  516. })
  517. ?.split("Revision URI: ")[1];
  518. }
  519. /*
  520. Create a git tag at the current hash.
  521. In the description include the commit logs since the given hash.
  522. Include the (cleansed) Phabricator link.
  523. */
  524. async function tagDeployment(options={}) {
  525. let hash = options.hash || await getLastDeployedHash();
  526. let workInTheOpenPhabricatorUrl = '';
  527. if (options.diffId) {
  528. workInTheOpenPhabricatorUrl = `Phabricator: ${options.diffId}-code`;
  529. }
  530. let projectVersion = await executeCommand(`node -p "require('./package.json').version"`);
  531. let logs = await executeCommand(`git log --reverse --pretty=format:%s ${hash}..HEAD`);
  532. let tag = `v${projectVersion}`;
  533. let message = `Deploy Themes ${tag} to wpcom. \n\n${logs} \n\n${workInTheOpenPhabricatorUrl}`;
  534. await executeCommand(`
  535. git tag -a ${tag} -m "${message}"
  536. git push origin ${tag}
  537. `);
  538. }
  539. /*
  540. Execute a command on the sandbox.
  541. Expects the following to be configured in your ~/.ssh/config file:
  542. Host wpcom-sandbox
  543. User wpdev
  544. HostName SANDBOXURL.wordpress.com
  545. ForwardAgent yes
  546. */
  547. function executeOnSandbox(command, logResponse){
  548. return executeCommand(`ssh -TA ${remoteSSH} << EOF
  549. ${command}
  550. EOF`, logResponse);
  551. }
  552. /*
  553. Execute a command locally.
  554. */
  555. async function executeCommand(command, logResponse) {
  556. return new Promise((resolove, reject) => {
  557. let child;
  558. let response = '';
  559. let errResponse = '';
  560. if (isWin) {
  561. child = spawn('cmd.exe', ['/s', '/c', '"' + command + '"'], {
  562. windowsVerbatimArguments: true,
  563. stdio: [process.stdin, 'pipe', 'pipe'],
  564. })
  565. } else {
  566. child = spawn(process.env.SHELL, ['-c', command]);
  567. }
  568. child.stdout.on('data', (data) => {
  569. response += data;
  570. if(logResponse){
  571. console.log(data.toString());
  572. }
  573. });
  574. child.stderr.on('data', (data) => {
  575. errResponse += data;
  576. if(logResponse){
  577. console.log(data.toString());
  578. }
  579. });
  580. child.on('exit', (code) => {
  581. if (code !== 0) {
  582. reject(errResponse.trim());
  583. }
  584. resolove(response.trim());
  585. });
  586. });
  587. }