theme-utils.mjs 20 KB

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