theme-utils.mjs 22 KB

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