theme-utils.mjs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  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 sandboxPremiumThemesFolder = '/home/wpdev/public_html/wp-content/themes/premium';
  8. const sandboxRootFolder = '/home/wpdev/public_html/';
  9. const isWin = process.platform === 'win32';
  10. const premiumThemes = [ 'videomaker', 'videomaker-white' ];
  11. (async function start() {
  12. let args = process.argv.slice(2);
  13. let command = args?.[0];
  14. switch (command) {
  15. case "push-button-deploy": return pushButtonDeploy();
  16. case "clean-sandbox": return cleanSandbox();
  17. case "clean-premium-sandbox": return cleanPremiumSandbox();
  18. case "clean-all-sandbox": return cleanAllSandbox();
  19. case "push-to-sandbox": return pushToSandbox();
  20. case "push-changes-to-sandbox": return pushChangesToSandbox();
  21. case "push-premium-to-sandbox": return pushPremiumToSandbox();
  22. case "version-bump-themes": return versionBumpThemes();
  23. case "land-diff": return landChanges(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. 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. * 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() {
  64. console.clear();
  65. let prompt = await inquirer.prompt([{
  66. type: 'confirm',
  67. message: 'You are about to deploy /trunk. Are you ready to continue?',
  68. name: "continue",
  69. default: false
  70. }]);
  71. if(!prompt.continue){
  72. return;
  73. }
  74. let message = await checkForDeployability();
  75. if (message) {
  76. return console.log(`\n\n${message}\n\n`);
  77. }
  78. try {
  79. await cleanSandbox();
  80. //build variations
  81. console.log('Building Variations');
  82. await executeCommand(`node ./variations/build-variations.mjs git-add-changes`)
  83. prompt = await inquirer.prompt([{
  84. type: 'confirm',
  85. message: 'Are you good with any staged theme variations changes? Make any manual adjustments now if necessary.',
  86. name: "continue",
  87. default: false
  88. }]);
  89. if(!prompt.continue){
  90. console.log(`Aborted Automated Deploy Process at variations building.` );
  91. return;
  92. }
  93. try {
  94. await executeCommand(`
  95. git commit -m "Building Variations"
  96. `);
  97. } catch (err) {
  98. // Most likely the error is that there are no variation changes to commit.
  99. // Just swallowing that error for now
  100. }
  101. let hash = await getLastDeployedHash();
  102. let thingsWentBump = await versionBumpThemes();
  103. if( thingsWentBump ){
  104. prompt = await inquirer.prompt([{
  105. type: 'confirm',
  106. message: 'Are you good with the version bump changes? Make any manual adjustments now if necessary.',
  107. name: "continue",
  108. default: false
  109. }]);
  110. if(!prompt.continue){
  111. console.log(`Aborted Automated Deploy Process at version bump changes.` );
  112. return;
  113. }
  114. }
  115. let changedThemes = await getChangedThemes(hash);
  116. await pushChangesToSandbox();
  117. //push changes (from version bump)
  118. if( thingsWentBump ){
  119. prompt = await inquirer.prompt([{
  120. type: 'confirm',
  121. message: 'Are you ready to push this version bump change to the source repository (Github)?',
  122. name: "continue",
  123. default: false
  124. }]);
  125. if(!prompt.continue){
  126. console.log(`Aborted Automated Deploy Process at version bump push change.` );
  127. return;
  128. }
  129. await executeCommand(`
  130. git commit -m "Version Bump";
  131. git push
  132. `, true);
  133. }
  134. await updateLastDeployedHash();
  135. let diffUrl = await createPhabricatorDiff(hash);
  136. let diffId = diffUrl.split('a8c.com/')[1];
  137. await tagDeployment({
  138. hash: hash,
  139. diffId: diffId
  140. });
  141. 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`);
  142. prompt = await inquirer.prompt([{
  143. type: 'confirm',
  144. message: 'Are you ready to land these changes?',
  145. name: "continue",
  146. default: false
  147. }]);
  148. if(!prompt.continue){
  149. 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}` );
  150. return;
  151. }
  152. await landChanges(diffId);
  153. let changedPublicThemes = changedThemes.filter( item=> ! premiumThemes.includes( item ) );
  154. try {
  155. await deployThemes(changedPublicThemes);
  156. }
  157. catch (err) {
  158. prompt = await inquirer.prompt([{
  159. type: 'confirm',
  160. message: `There was an error deploying themes. ${err} Do you wish to continue to the next step?`,
  161. name: "continue",
  162. default: false
  163. }]);
  164. if(!prompt.continue){
  165. console.log(`Aborted Automated Deploy during deploy phase.` );
  166. return;
  167. }
  168. }
  169. await buildComZips(changedPublicThemes);
  170. console.log(`The following themes have changed:\n${changedThemes.join('\n')}`)
  171. console.log('\n\nAll Done!!\n\n');
  172. }
  173. catch (err) {
  174. console.log("ERROR with deploy script: ", err);
  175. }
  176. }
  177. /*
  178. Build .zip file for .com
  179. */
  180. async function buildComZip(themeSlug) {
  181. console.log( `Building ${themeSlug} .zip` );
  182. let styleCss = fs.readFileSync(`${themeSlug}/style.css`, 'utf8');
  183. // Gets the theme version (Version:) and minimum WP version (Tested up to:) from the theme's style.css
  184. let themeVersion = getThemeMetadata(styleCss, 'Version');
  185. let wpVersionCompat = getThemeMetadata(styleCss, 'Requires at least');
  186. if (themeVersion && wpVersionCompat) {
  187. await executeOnSandbox(`php ${sandboxRootFolder}bin/themes/theme-downloads/build-theme-zip.php --stylesheet=pub/${themeSlug} --themeversion=${themeVersion} --wpversioncompat=${wpVersionCompat};`, true);
  188. }
  189. else {
  190. console.log('Unable to build theme .zip.');
  191. if (!themeVersion) {
  192. console.log('Could not find theme version (Version:) in the theme style.css.');
  193. }
  194. if (!wpVersionCompat) {
  195. console.log('Could not find WP compat version (Tested up to:) in the theme style.css.');
  196. }
  197. console.log('Please build the .zip file for the theme manually.', themeSlug);
  198. open('https://mc.a8c.com/themes/downloads/');
  199. }
  200. }
  201. async function buildComZips(themes) {
  202. for ( let theme of themes ) {
  203. try {
  204. await buildComZip(theme);
  205. } catch (err) {
  206. console.log(`There was an error building dotcom zip for ${theme}. ${err}`);
  207. }
  208. }
  209. }
  210. /*
  211. Check to ensure that:
  212. * The current branch is /trunk
  213. * That trunk is up-to-date with origin/trunk
  214. */
  215. async function checkForDeployability(){
  216. let branchName = await executeCommand('git symbolic-ref --short HEAD');
  217. if(branchName !== 'trunk' ) {
  218. return 'Only the /trunk branch can be deployed.';
  219. }
  220. await executeCommand('git remote update', true);
  221. let localMasterHash = await executeCommand('git rev-parse trunk')
  222. let remoteMasterHash = await executeCommand('git rev-parse origin/trunk')
  223. if(localMasterHash !== remoteMasterHash) {
  224. return 'Local /trunk is out-of-date. Pull changes to continue.'
  225. }
  226. return null;
  227. }
  228. /*
  229. Land the changes from the given diff ID. This is the "production merge".
  230. */
  231. async function landChanges(diffId){
  232. return executeCommand(`ssh -tt -A ${remoteSSH} "cd ${sandboxPublicThemesFolder}; /usr/local/bin/arc patch ${diffId}; /usr/local/bin/arc land; exit;"`, true);
  233. }
  234. async function getChangedThemes(hash) {
  235. console.log('Determining all changed themes');
  236. let themes = await getActionableThemes();
  237. let changedThemes = [];
  238. for (let theme of themes) {
  239. let hasChanges = await checkThemeForChanges(theme, hash);
  240. if(hasChanges){
  241. changedThemes.push(theme);
  242. }
  243. }
  244. return changedThemes;
  245. }
  246. /*
  247. Deploy a collection of themes.
  248. Part of the push-button-deploy process.
  249. Can also be triggered to deploy a single theme with the command:
  250. node ./theme-utils.mjs deploy-theme THEMENAME
  251. */
  252. async function deployThemes( themes ) {
  253. let response;
  254. for ( let theme of themes ) {
  255. console.log( `Deploying ${theme}` );
  256. let deploySuccess = false;
  257. let attempt = 0;
  258. while ( ! deploySuccess && attempt <= 2 ) {
  259. attempt++;
  260. console.log(`\nattempt #${attempt}\n\n`);
  261. response = await executeOnSandbox( `deploy pub ${theme};exit;`, true, true );
  262. deploySuccess = response.includes( 'successfully deployed to' );
  263. if( ! deploySuccess ) {
  264. console.log( 'Deploy was not successful. Trying again in 10 seconds...' );
  265. await new Promise(resolve => setTimeout(resolve, 10000));
  266. }
  267. else {
  268. console.log( "Deploy successful." );
  269. }
  270. }
  271. if ( ! deploySuccess ) {
  272. await inquirer.prompt([{
  273. type: 'confirm',
  274. message: `${theme} was not sucessfully deployed and should be deployed manually.`,
  275. name: "continue",
  276. default: false
  277. }]);
  278. }
  279. }
  280. }
  281. /*
  282. Provide the hash of the last managed deployment.
  283. This hash is used to determine all the changes that have happened between that point and the current point.
  284. */
  285. async function getLastDeployedHash() {
  286. let result = await executeOnSandbox(`
  287. cat ${sandboxPublicThemesFolder}/.pub-git-hash
  288. `);
  289. return result;
  290. }
  291. /*
  292. Update the 'last deployed hash' on the server with the current hash.
  293. */
  294. async function updateLastDeployedHash() {
  295. let hash = await executeCommand(`git rev-parse HEAD`);
  296. await executeOnSandbox(`
  297. echo '${hash}' > ${sandboxPublicThemesFolder}/.pub-git-hash
  298. `);
  299. }
  300. /*
  301. Version bump (increment version patch) any theme project that has had changes since the last deployment.
  302. If a theme's version has already been changed since that last deployment then do not version bump it.
  303. If any theme projects have had a version bump also version bump the parent project.
  304. Commit the change.
  305. */
  306. async function versionBumpThemes() {
  307. console.log("Version Bumping");
  308. let themes = await getActionableThemes();
  309. let hash = await getLastDeployedHash();
  310. let changesWereMade = false;
  311. let versionBumpCount = 0;
  312. for (let theme of themes) {
  313. let hasChanges = await checkThemeForChanges(theme, hash);
  314. if( ! hasChanges){
  315. // console.log(`${theme} has no changes`);
  316. continue;
  317. }
  318. versionBumpCount++;
  319. let hasVersionBump = await checkThemeForVersionBump(theme, hash);
  320. if( hasVersionBump ){
  321. continue;
  322. }
  323. await versionBumpTheme(theme, true);
  324. changesWereMade = true;
  325. }
  326. //version bump the root project if there were changes to any of the themes
  327. let rootHasVersionBump = await checkProjectForVersionBump(hash);
  328. if ( versionBumpCount > 0 && ! rootHasVersionBump ) {
  329. await executeCommand(`npm version patch --no-git-tag-version && git add package.json package-lock.json`);
  330. changesWereMade = true;
  331. }
  332. return changesWereMade;
  333. }
  334. export function getThemeMetadata(styleCss, attribute) {
  335. if ( !styleCss || !attribute ) {
  336. return null;
  337. }
  338. switch ( attribute ) {
  339. case 'Version':
  340. return styleCss
  341. .match(/(?<=Version:\s*).*?(?=\s*\r?\n|\rg)/gs)[0]
  342. .trim()
  343. .replace('-wpcom', '');
  344. case 'Requires at least':
  345. return styleCss
  346. .match(/(?<=Requires at least:\s*).*?(?=\s*\r?\n|\rg)/gs);
  347. }
  348. }
  349. /*
  350. Version Bump a Theme.
  351. Used by versionBumpThemes to do the work of version bumping.
  352. First increment the patch version in style.css
  353. Then update any of these files with the new version: [package.json, style.scss, style-child-theme.scss]
  354. */
  355. async function versionBumpTheme(theme, addChanges){
  356. console.log(`${theme} needs a version bump`);
  357. await executeCommand(`perl -pi -e 's/Version: ((\\d+\\.)*)(\\d+)(.*)$/"Version: ".$1.($3+1).$4/ge' ${theme}/style.css`, true);
  358. await executeCommand(`git add ${theme}/style.css`);
  359. let styleCss = fs.readFileSync(`${theme}/style.css`, 'utf8');
  360. let currentVersion = getThemeMetadata(styleCss, 'Version');
  361. let filesToUpdate = await executeCommand(`find ${theme} -name package.json -o -name style.scss -o -name style-child-theme.scss -maxdepth 2`);
  362. filesToUpdate = filesToUpdate.split('\n').filter(item => item != '');
  363. for ( let file of filesToUpdate ) {
  364. await executeCommand(`perl -pi -e 's/Version: (.*)$/"Version: '${currentVersion}'"/ge' ${file}`);
  365. await executeCommand(`perl -pi -e 's/\\"version\\": (.*)$/"\\"version\\": \\"'${currentVersion}'\\","/ge' ${file}`);
  366. if (addChanges){
  367. await executeCommand(`git add ${file}`);
  368. }
  369. }
  370. }
  371. /*
  372. Determine if a theme has had a version bump since a given hash.
  373. Used by versionBumpThemes
  374. Compares the value of 'version' in style.css between the hash and current value
  375. */
  376. async function checkThemeForVersionBump(theme, hash){
  377. return executeCommand(`
  378. git show ${hash}:${theme}/style.css 2>/dev/null
  379. `)
  380. .catch( ( error ) => {
  381. //This is a new theme, no need to bump versions so we'll just say we've already done it
  382. return true;
  383. } )
  384. .then( ( previousStyleString ) => {
  385. if( previousStyleString === true) {
  386. return previousStyleString;
  387. }
  388. let previousVersion = getThemeMetadata(previousStyleString, 'Version');
  389. let styleCss = fs.readFileSync(`${theme}/style.css`, 'utf8');
  390. let currentVersion = getThemeMetadata(styleCss, 'Version');
  391. return previousVersion != currentVersion;
  392. });
  393. }
  394. /*
  395. Determine if the project has had a version bump since a given hash.
  396. Used by versionBumpThemes
  397. Compares the value of 'version' in package.json between the hash and current value
  398. */
  399. async function checkProjectForVersionBump(hash){
  400. let previousPackageString = await executeCommand(`
  401. git show ${hash}:./package.json 2>/dev/null
  402. `);
  403. let previousPackage = JSON.parse(previousPackageString);
  404. let currentPackage = JSON.parse(fs.readFileSync(`./package.json`))
  405. return previousPackage.version != currentPackage.version;
  406. }
  407. /*
  408. Determine if a theme has had changes since a given hash.
  409. Used by versionBumpThemes
  410. */
  411. async function checkThemeForChanges(theme, hash){
  412. let comittedChanges = await executeCommand(`git diff --name-only ${hash} HEAD -- ${theme}`);
  413. return comittedChanges != '';
  414. }
  415. /*
  416. Provide a list of 'actionable' themes (those themes that have style.css files)
  417. */
  418. async function getActionableThemes() {
  419. let result = await executeCommand(`for d in */; do
  420. if test -f "./$d/style.css"; then
  421. echo $d;
  422. fi
  423. done`);
  424. return result
  425. .split('\n')
  426. .map(item=>item.replace('/', ''));
  427. }
  428. /*
  429. Clean the theme sandbox.
  430. checkout origin/trunk and ensure it's up-to-date.
  431. Remove any other changes.
  432. */
  433. async function cleanSandbox() {
  434. console.log('Cleaning the Themes Sandbox');
  435. await executeOnSandbox(`
  436. cd ${sandboxPublicThemesFolder};
  437. git reset --hard HEAD;
  438. git clean -fd;
  439. git checkout trunk;
  440. git pull;
  441. echo;
  442. git status
  443. `, true);
  444. console.log('All done cleaning.');
  445. }
  446. /*
  447. Clean the premium theme sandbox.
  448. checkout origin/trunk and ensure it's up-to-date.
  449. Remove any other changes.
  450. */
  451. async function cleanPremiumSandbox() {
  452. console.log('Cleaning the Themes Sandbox');
  453. await executeOnSandbox(`
  454. cd ${sandboxPremiumThemesFolder};
  455. git reset --hard HEAD;
  456. git clean -fd;
  457. git checkout trunk;
  458. git pull;
  459. echo;
  460. git status
  461. `, true);
  462. console.log('All done cleaning.');
  463. }
  464. /*
  465. Clean the entire sandbox.
  466. checkout origin/trunk and ensure it's up-to-date.
  467. Remove any other changes.
  468. */
  469. async function cleanAllSandbox() {
  470. console.log('Cleaning the Entire Sandbox');
  471. let response = await executeOnSandbox(`
  472. cd ${sandboxRootFolder};
  473. git reset --hard HEAD;
  474. git clean -fd;
  475. git checkout trunk;
  476. git pull;
  477. echo;
  478. git status
  479. `, true);
  480. console.log('All done cleaning.');
  481. }
  482. /*
  483. Push exactly what is here (all files) up to the sandbox (with the exclusion of files noted in .sandbox-ignore)
  484. */
  485. async function pushToSandbox() {
  486. console.log("Pushing All Themes to Sandbox.");
  487. let allThemes = await getActionableThemes();
  488. allThemes = allThemes.filter( item=> ! premiumThemes.includes( item ) );
  489. console.log(`Syncing ${allThemes.length} themes`);
  490. for ( let theme of allThemes ) {
  491. await pushThemeToSandbox(theme);
  492. }
  493. }
  494. async function pushThemeToSandbox(theme) {
  495. console.log( `Syncing ${theme}` );
  496. return executeCommand(`
  497. rsync -avR --no-p --no-times --delete -m --exclude-from='.sandbox-ignore' ./${theme}/ wpcom-sandbox:${sandboxPublicThemesFolder}/
  498. `, true);
  499. }
  500. /*
  501. Push exactly what is here (all files) up to the sandbox (with the exclusion of files noted in .sandbox-ignore)
  502. This pushes only the folders noted as "premiumThemes" into the premium themes directory.
  503. This is the only part of the deploy process that is automated; the rest must be done manually including:
  504. * Creating a Phabricator Diff
  505. * Landing (comitting) the change
  506. * Deploying the theme
  507. * Triggering the .zip builds
  508. */
  509. async function pushPremiumToSandbox() {
  510. //TODO: It would be nice to determine this list programatically
  511. const filesToModify = [
  512. 'style.css',
  513. 'block-templates/404.html',
  514. 'block-template-parts/header.html',
  515. 'block-template-parts/footer.html'
  516. ];
  517. // Change 'blockbase' to 'blockbase-premium' in the files noted
  518. for ( let theme of premiumThemes ) {
  519. for ( let file of filesToModify ) {
  520. await executeCommand(`perl -pi -e 's/blockbase/blockbase-premium/' ${theme}/${file}`, true);
  521. }
  522. }
  523. // Push the changes in the premium themes to the sandbox
  524. await executeCommand(`
  525. rsync -avR --no-p --no-times --delete -m --exclude-from='.sandbox-ignore' --exclude='sass' ./${premiumThemes.join(' ./')} wpcom-sandbox:${sandboxPremiumThemesFolder}/
  526. `, true);
  527. // revert the local blockbase-premium changes
  528. for ( let theme of premiumThemes ) {
  529. for ( let file of filesToModify ) {
  530. await executeCommand(`
  531. git restore --source=HEAD --staged --worktree ./${theme}/${file}
  532. `);
  533. }
  534. }
  535. }
  536. /*
  537. Push only (and every) change since the point-of-diversion from /trunk
  538. Remove files from the sandbox that have been removed since the last deployed hash
  539. */
  540. async function pushChangesToSandbox() {
  541. console.log("Pushing Changed Themes to Sandbox.");
  542. let hash = await getLastDeployedHash();
  543. let changedThemes = await getChangedThemes(hash);
  544. changedThemes = changedThemes.filter( item=> ! premiumThemes.includes( item ) );
  545. console.log(`Syncing ${changedThemes.length} themes`);
  546. for ( let theme of changedThemes ) {
  547. pushThemeToSandbox(theme);
  548. }
  549. }
  550. /*
  551. Build the Phabricator commit message.
  552. This message contains the logs from all of the commits since the given hash.
  553. Used by create*PhabricatorDiff
  554. */
  555. async function buildPhabricatorCommitMessageSince(hash){
  556. let projectVersion = await executeCommand(`node -p "require('./package.json').version"`);
  557. let logs = await executeCommand(`git log --reverse --pretty=format:%s ${hash}..HEAD`);
  558. // Remove any double quotes from commit messages
  559. logs.replace(/"/g, '');
  560. return `Deploy Themes ${projectVersion} to wpcom
  561. Summary:
  562. ${logs}
  563. Test Plan: Execute Smoke Test
  564. Reviewers:
  565. Subscribers:
  566. `;
  567. }
  568. /*
  569. Create a Phabricator diff from a given hash.
  570. Open the phabricator diff in your browser.
  571. Provide the URL of the phabricator diff.
  572. */
  573. async function createPhabricatorDiff(hash) {
  574. console.log('creating Phabricator Diff');
  575. let commitMessage = await buildPhabricatorCommitMessageSince(hash);
  576. let result = await executeOnSandbox(`
  577. cd ${sandboxPublicThemesFolder};
  578. git branch -D deploy
  579. git checkout -b deploy
  580. git add --all
  581. git commit -m "${commitMessage}"
  582. arc diff --create --verbatim
  583. `, true);
  584. let phabricatorUrl = getPhabricatorUrlFromResponse(result);
  585. console.log('Diff Created at: ', phabricatorUrl);
  586. if(phabricatorUrl) {
  587. open(phabricatorUrl);
  588. }
  589. return phabricatorUrl;
  590. }
  591. /*
  592. Utility to pull the Phabricator URL from the diff creation command.
  593. Used by createPhabricatorDiff
  594. */
  595. function getPhabricatorUrlFromResponse(response){
  596. return response
  597. ?.split('\n')
  598. ?.find( item => {
  599. return item.includes('Revision URI: ');
  600. })
  601. ?.split("Revision URI: ")[1];
  602. }
  603. /*
  604. Create a git tag at the current hash.
  605. In the description include the commit logs since the given hash.
  606. Include the (cleansed) Phabricator link.
  607. */
  608. async function tagDeployment(options={}) {
  609. console.log('tagging deployment');
  610. let hash = options.hash || await getLastDeployedHash();
  611. let workInTheOpenPhabricatorUrl = '';
  612. if (options.diffId) {
  613. workInTheOpenPhabricatorUrl = `Phabricator: ${options.diffId}-code`;
  614. }
  615. let projectVersion = await executeCommand(`node -p "require('./package.json').version"`);
  616. let logs = await executeCommand(`git log --reverse --pretty=format:%s ${hash}..HEAD`);
  617. // Remove any double quotes from commit messages
  618. logs.replace(/"/g, '');
  619. let tag = `v${projectVersion}`;
  620. let message = `Deploy Themes ${tag} to wpcom. \n\n${logs} \n\n${workInTheOpenPhabricatorUrl}`;
  621. await executeCommand(`
  622. git tag -a ${tag} -m "${message}"
  623. git push origin ${tag}
  624. `, true);
  625. }
  626. /*
  627. Execute a command on the sandbox.
  628. Expects the following to be configured in your ~/.ssh/config file:
  629. Host wpcom-sandbox
  630. User wpdev
  631. HostName SANDBOXURL.wordpress.com
  632. ForwardAgent yes
  633. */
  634. function executeOnSandbox(command, logResponse, enablePsudoterminal){
  635. if(enablePsudoterminal){
  636. return executeCommand(`ssh -tt -A ${remoteSSH} << EOF
  637. ${command}
  638. EOF`, logResponse);
  639. }
  640. return executeCommand(`ssh -TA ${remoteSSH} << EOF
  641. ${command}
  642. EOF`, logResponse);
  643. }
  644. /*
  645. Execute a command locally.
  646. */
  647. export async function executeCommand(command, logResponse) {
  648. return new Promise((resolove, reject) => {
  649. let child;
  650. let response = '';
  651. let errResponse = '';
  652. if (isWin) {
  653. child = spawn('cmd.exe', ['/s', '/c', '"' + command + '"'], {
  654. windowsVerbatimArguments: true,
  655. stdio: [process.stdin, 'pipe', 'pipe'],
  656. })
  657. } else {
  658. child = spawn(process.env.SHELL, ['-c', command], {
  659. stdio: [process.stdin, 'pipe', 'pipe'],
  660. });
  661. }
  662. child.stdout.on('data', (data) => {
  663. response += data;
  664. if(logResponse){
  665. console.log(data.toString());
  666. }
  667. });
  668. child.stderr.on('data', (data) => {
  669. errResponse += data;
  670. if(logResponse){
  671. console.log(data.toString());
  672. }
  673. });
  674. child.on('exit', (code) => {
  675. if (code !== 0) {
  676. reject(errResponse.trim());
  677. }
  678. resolove(response.trim());
  679. });
  680. });
  681. }