theme-utils.mjs 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132
  1. import { spawn } from 'child_process';
  2. import fs, { existsSync } 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. const coreThemes = ['twentyten', 'twentyeleven', 'twentytwelve', 'twentythirteen', 'twentyfourteen', 'twentyfifteen', 'twentysixteen', 'twentyseventeen', 'twentynineteen', 'twentytwenty', 'twentytwentyone', 'twentytwentytwo'];
  12. const commands = {
  13. "push-button-deploy": {
  14. helpText: `
  15. * Gets the last deployed hash from the sandbox
  16. * Version bump all themes that have changes since the last deployment
  17. * Commit the version bump change to github
  18. * Clean the sandbox and ensure it is up - to - date
  19. * Push all changed files(including removal of deleted files) since the last deployment
  20. * Update the 'last deployed' hash on the sandbox
  21. * Create a phabricator diff based on the changes since the last deployment.The description including the commit messages since the last deployment.
  22. * Open the Phabricator Diff in your browser
  23. * Create a tag in the github repository at this point of change which includes the phabricator link in the description
  24. * After pausing to allow testing, land and deploy the changes
  25. `,
  26. run: pushButtonDeploy
  27. },
  28. "clean-sandbox": {
  29. helpText: 'Perform a hard reset, checkout trunk, and pull on the public themes working copy on your sandbox.',
  30. run: cleanSandbox
  31. },
  32. "clean-premium-sandbox": {
  33. helpText: 'Perform a hard reset, checkout trunk, and pull on the premium themes working copy on your sandbox.',
  34. run: cleanPremiumSandbox
  35. },
  36. "clean-all-sandbox": {
  37. helpText: 'Perform a hard reset, checkout trunk, and pull on both the public and premium themes working copies on your sandbox.',
  38. run: cleanAllSandbox
  39. },
  40. "push-to-sandbox": {
  41. helpText: 'Uses rsync to copy all modified files for all themes from the local machine to your sandbox.',
  42. run: pushToSandbox
  43. },
  44. "push-changes-to-sandbox": {
  45. helpText: 'Uses rsync to copy all modified files for any modified themes from the local machine to your sandbox.',
  46. run: pushChangesToSandbox
  47. },
  48. "push-theme-to-sandbox": {
  49. helpText: 'Uses rsync to copy all modified files for the specified theme from the local machine to your sandbox.',
  50. additionalArgs: '<theme-slug>',
  51. run: (args) => pushThemeToSandbox(args?.[1])
  52. },
  53. "push-premium-to-sandbox": {
  54. helpText: 'Uses rsync to copy all modified files for all premium themes from the local machine to your sandbox. For the blockbase theme, all instances of the string "blockbase" are replaced with "blockbase-premium".',
  55. run: pushPremiumToSandbox
  56. },
  57. "version-bump-themes": {
  58. helpText: 'Bump the version of any theme that has had changes since the last deployment. This includes bumping the version of any parent themes and updating the changelog for the theme.',
  59. run: versionBumpThemes
  60. },
  61. "land-diff": {
  62. helpText: 'Run arc land to merge in the specified diff id.',
  63. additionalArgs: '<arc diff id>',
  64. run: (args) => landChanges(args?.[1])
  65. },
  66. "deploy-preview": {
  67. helpText: 'Display a list of the changes to be deployed.',
  68. run: deployPreview
  69. },
  70. "deploy-theme": {
  71. helpText: 'This runs "deploy pub <theme>" on the provided list of themes.',
  72. additionalArgs: '<array of theme slugs>',
  73. run: (args) => deployThemes([args?.[1]])
  74. },
  75. "build-com-zip": {
  76. helpText: 'Build the production zip file for the specified theme.',
  77. additionalArgs: '<theme-slug>',
  78. run: (args) => buildComZip([args?.[1]])
  79. },
  80. "pull-core-themes": {
  81. helpText: 'Use rsync to copy any changed public CORE theme files from your sandbox to your local machine. CORE themes are any of the Twenty<whatever> themes.',
  82. run: pullCoreThemes
  83. },
  84. "push-core-themes": {
  85. helpText: 'Use rsync to copy any changed public CORE theme files from your local machine to your sandbox. CORE themes are any of the Twenty<whatever> themes.',
  86. run: pushCoreThemes
  87. },
  88. "sync-core-theme": {
  89. helpText: 'Given a theme slug and SVN revision, sync the theme from the specified revision to the latest. This command is generally run by deploy-sync-core-theme and not by itself.',
  90. additionalArgs: '<theme-slug> <since-revision>',
  91. run: (args) => syncCoreTheme(args?.[1], args?.[2])
  92. },
  93. "deploy-sync-core-theme": {
  94. helpText: 'Given a theme slug and SVN revision, sync the theme from the specified revision to the latest. This command contains additional prompts and error checking not provided by sync-core-theme.',
  95. additionalArgs: '<theme-slug> <since-revision>',
  96. run: (args) => deploySyncCoreTheme(args?.[1], args?.[2])
  97. },
  98. "update-theme-changelog": {
  99. helpText: 'Use the commit log to build a list of recent changes and add them as a new changelog entry. If add-changes is true, the updated readme.txt will be staged.',
  100. additionalArgs: '<theme-slug> <add-changes, true/false>',
  101. run: (args) => updateThemeChangelog(args?.[1], false, args?.[2])
  102. },
  103. "rebuild-theme-changelog": {
  104. helpText: 'Rebuild the entire change long from the given starting hash.',
  105. additionalArgs: '<theme-slug> <since>',
  106. run: (args) => rebuildThemeChangelog(args?.[1], args?.[2])
  107. },
  108. "help": {
  109. helpText: 'Displays the main help message.',
  110. run: (args) => showHelp(args?.[1])
  111. },
  112. };
  113. (async function start() {
  114. let args = process.argv.slice(2);
  115. let command = args?.[0];
  116. if (!commands[command]) {
  117. return showHelp();
  118. }
  119. commands[command].run(args);
  120. })();
  121. function showHelp(command = '') {
  122. if (!command || !commands.hasOwnProperty(command)) {
  123. console.log(`
  124. node theme-utils.mjs [command]
  125. Available commands:
  126. _(theme-utils.mjs help [command] for more details)_
  127. \t${Object.keys(commands).join('\n\t')}
  128. `);
  129. return;
  130. }
  131. const { helpText, additionalArgs } = commands[command];
  132. console.log(`
  133. ${command} ${additionalArgs ?? ''}
  134. ${helpText}
  135. `);
  136. }
  137. /*
  138. Create list of changes from git logs
  139. Optionally pass in a deployed hash or default to calling getLastDeployedHash()
  140. Optionally pass in boolean bulletPoints to add bullet points to each commit log
  141. */
  142. async function getCommitLogs(hash, bulletPoints, theme) {
  143. if (!hash) {
  144. hash = await getLastDeployedHash();
  145. }
  146. let format = 'format:%s';
  147. let themeDir = '';
  148. if (bulletPoints) {
  149. format = 'format:"* %s"';
  150. }
  151. if (theme) {
  152. themeDir = `-- ./${theme}`;
  153. }
  154. let logs = await executeCommand(`git log --reverse --pretty=${format} ${hash}..HEAD ${themeDir}`);
  155. // Remove any double quotes from commit messages
  156. logs = logs.replace(/"/g, '');
  157. return logs;
  158. }
  159. /*
  160. Determine what changes would be deployed
  161. */
  162. async function deployPreview() {
  163. console.clear();
  164. console.log('To ensure accuracy clean your sandbox before previewing. (It is not automatically done).');
  165. let message = await checkForDeployability();
  166. if (message) {
  167. console.log(`\n${message}\n\n`);
  168. }
  169. let hash = await getLastDeployedHash();
  170. console.log(`Last deployed hash: ${hash}`);
  171. let changedThemes = await getChangedThemes(hash);
  172. console.log(`The following themes have changes:\n${changedThemes}`);
  173. let logs = await getCommitLogs(hash);
  174. console.log(`\n\nCommit log of changes to be deployed:\n\n${logs}\n\n`);
  175. }
  176. /*
  177. Execute the first phase of a deployment.
  178. * Gets the last deployed hash from the sandbox
  179. * Version bump all themes that have changes since the last deployment
  180. * Commit the version bump change to github
  181. * Clean the sandbox and ensure it is up-to-date
  182. * Push all changed files (including removal of deleted files) since the last deployment
  183. * Update the 'last deployed' hash on the sandbox
  184. * Create a phabricator diff based on the changes since the last deployment. The description including the commit messages since the last deployment.
  185. * Open the Phabricator Diff in your browser
  186. * Create a tag in the github repository at this point of change which includes the phabricator link in the description
  187. */
  188. async function pushButtonDeploy() {
  189. console.clear();
  190. let prompt = await inquirer.prompt([{
  191. type: 'confirm',
  192. message: 'You are about to deploy /trunk. Are you ready to continue?',
  193. name: "continue",
  194. default: false
  195. }]);
  196. if (!prompt.continue) {
  197. return;
  198. }
  199. let message = await checkForDeployability();
  200. if (message) {
  201. return console.log(`\n\n${message}\n\n`);
  202. }
  203. try {
  204. await cleanSandbox();
  205. //build variations
  206. console.log('Building Variations');
  207. await executeCommand(`node ./variations/build-variations.mjs git-add-changes`)
  208. prompt = await inquirer.prompt([{
  209. type: 'confirm',
  210. message: 'Are you good with any staged theme variations changes? Make any manual adjustments now if necessary.',
  211. name: "continue",
  212. default: false
  213. }]);
  214. if (!prompt.continue) {
  215. console.log(`Aborted Automated Deploy Process at variations building.`);
  216. return;
  217. }
  218. try {
  219. await executeCommand(`
  220. git commit -m "Building Variations"
  221. `);
  222. } catch (err) {
  223. // Most likely the error is that there are no variation changes to commit.
  224. // Just swallowing that error for now
  225. }
  226. let hash = await getLastDeployedHash();
  227. let thingsWentBump = await versionBumpThemes();
  228. if (thingsWentBump) {
  229. prompt = await inquirer.prompt([{
  230. type: 'confirm',
  231. message: 'Are you good with the version bump and changelog updates? Make any manual adjustments now if necessary.',
  232. name: "continue",
  233. default: false
  234. }]);
  235. if (!prompt.continue) {
  236. console.log(`Aborted Automated Deploy Process at version bump changes.`);
  237. return;
  238. }
  239. }
  240. let changedThemes = await getChangedThemes(hash);
  241. await pushChangesToSandbox();
  242. //push changes (from version bump)
  243. if (thingsWentBump) {
  244. prompt = await inquirer.prompt([{
  245. type: 'confirm',
  246. message: 'Are you ready to push this version bump change to the source repository (Github)?',
  247. name: "continue",
  248. default: false
  249. }]);
  250. if (!prompt.continue) {
  251. console.log(`Aborted Automated Deploy Process at version bump push change.`);
  252. return;
  253. }
  254. await executeCommand(`
  255. git commit -m "Version Bump";
  256. git push
  257. `, true);
  258. }
  259. await updateLastDeployedHash();
  260. let commitMessage = await buildPhabricatorCommitMessageSince(hash);
  261. let diffUrl = await createPhabricatorDiff(commitMessage);
  262. let diffId = diffUrl.split('a8c.com/')[1];
  263. await tagDeployment({
  264. hash: hash,
  265. diffId: diffId
  266. });
  267. 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`);
  268. prompt = await inquirer.prompt([{
  269. type: 'confirm',
  270. message: 'Are you ready to land these changes?',
  271. name: "continue",
  272. default: false
  273. }]);
  274. if (!prompt.continue) {
  275. 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}`);
  276. return;
  277. }
  278. await landChanges(diffId);
  279. let changedPublicThemes = changedThemes.filter(item => !premiumThemes.includes(item));
  280. try {
  281. await deployThemes(changedPublicThemes);
  282. }
  283. catch (err) {
  284. prompt = await inquirer.prompt([{
  285. type: 'confirm',
  286. message: `There was an error deploying themes. ${err} Do you wish to continue to the next step?`,
  287. name: "continue",
  288. default: false
  289. }]);
  290. if (!prompt.continue) {
  291. console.log(`Aborted Automated Deploy during deploy phase.`);
  292. return;
  293. }
  294. }
  295. await buildComZips(changedPublicThemes);
  296. console.log(`The following themes have changed:\n${changedThemes.join('\n')}`)
  297. console.log('\n\nAll Done!!\n\n');
  298. }
  299. catch (err) {
  300. console.log("ERROR with deploy script: ", err);
  301. }
  302. }
  303. async function deploySyncCoreTheme(theme, sinceRevision) {
  304. await cleanSandbox();
  305. let latestRevision = await syncCoreTheme(theme, sinceRevision);
  306. let prompt = await inquirer.prompt([{
  307. type: 'confirm',
  308. message: `Changes have been synced to your sandbox. Please resolve any conflicts (noted in .rej files). Are you ready to continue?`,
  309. name: "continue",
  310. default: false
  311. }]);
  312. if (!prompt.continue) {
  313. console.log(`Aborted Core Sync Deploy.`);
  314. return;
  315. }
  316. let logs = await executeCommand(`svn log https://core.svn.wordpress.org/trunk/wp-content/themes/${theme} -r${sinceRevision}:HEAD`)
  317. let commitMessage = `${theme}: Merge latest core changes up to [wp${latestRevision}]
  318. Summary:
  319. ${logs}
  320. Test Plan: Activate ${theme} and ensure nothing is broken
  321. Reviewers:
  322. #themes_team
  323. Subscribers:
  324. `;
  325. let diffUrl = await createPhabricatorDiff(commitMessage);
  326. let diffId = diffUrl.split('a8c.com/')[1];
  327. prompt = await inquirer.prompt([{
  328. type: 'confirm',
  329. message: 'Are you ready to land these changes?',
  330. name: "continue",
  331. default: false
  332. }]);
  333. if (!prompt.continue) {
  334. console.log(`Aborted Automated Deploy Sync Process Landing Phase\n\nYou will have to land these changes manually. The ID of the diff to land: ${diffId}`);
  335. return;
  336. }
  337. return;
  338. // await landChanges(diffId);
  339. // await deployThemes([theme]);
  340. // await buildComZips([theme]);
  341. }
  342. /*
  343. Build .zip file for .com
  344. */
  345. async function buildComZip(themeSlug) {
  346. console.log(`Building ${themeSlug} .zip`);
  347. let styleCss = fs.readFileSync(`${themeSlug}/style.css`, 'utf8');
  348. // Gets the theme version (Version:) and minimum WP version (Tested up to:) from the theme's style.css
  349. let themeVersion = getThemeMetadata(styleCss, 'Version');
  350. let wpVersionCompat = getThemeMetadata(styleCss, 'Requires at least');
  351. if (themeVersion && wpVersionCompat) {
  352. await executeOnSandbox(`php ${sandboxRootFolder}bin/themes/theme-downloads/build-theme-zip.php --stylesheet=pub/${themeSlug} --themeversion=${themeVersion} --wpversioncompat=${wpVersionCompat};`, true);
  353. }
  354. else {
  355. console.log('Unable to build theme .zip.');
  356. if (!themeVersion) {
  357. console.log('Could not find theme version (Version:) in the theme style.css.');
  358. }
  359. if (!wpVersionCompat) {
  360. console.log('Could not find WP compat version (Tested up to:) in the theme style.css.');
  361. }
  362. console.log('Please build the .zip file for the theme manually.', themeSlug);
  363. open('https://mc.a8c.com/themes/downloads/');
  364. }
  365. }
  366. async function buildComZips(themes) {
  367. for (let theme of themes) {
  368. try {
  369. await buildComZip(theme);
  370. } catch (err) {
  371. console.log(`There was an error building dotcom zip for ${theme}. ${err}`);
  372. }
  373. }
  374. }
  375. /*
  376. Check to ensure that:
  377. * The current branch is /trunk
  378. * That trunk is up-to-date with origin/trunk
  379. */
  380. async function checkForDeployability() {
  381. let branchName = await executeCommand('git symbolic-ref --short HEAD');
  382. if (branchName !== 'trunk') {
  383. return 'Only the /trunk branch can be deployed.';
  384. }
  385. await executeCommand('git remote update', true);
  386. let localMasterHash = await executeCommand('git rev-parse trunk')
  387. let remoteMasterHash = await executeCommand('git rev-parse origin/trunk')
  388. if (localMasterHash !== remoteMasterHash) {
  389. return 'Local /trunk is out-of-date. Pull changes to continue.'
  390. }
  391. return null;
  392. }
  393. /*
  394. Land the changes from the given diff ID. This is the "production merge".
  395. */
  396. async function landChanges(diffId) {
  397. return executeCommand(`ssh -tt -A ${remoteSSH} "cd ${sandboxPublicThemesFolder}; /usr/local/bin/arc patch ${diffId}; /usr/local/bin/arc land; exit;"`, true);
  398. }
  399. async function getChangedThemes(hash) {
  400. console.log('Determining all changed themes');
  401. let themes = await getActionableThemes();
  402. let changedThemes = [];
  403. for (let theme of themes) {
  404. let hasChanges = await checkThemeForChanges(theme, hash);
  405. if (hasChanges) {
  406. changedThemes.push(theme);
  407. }
  408. }
  409. return changedThemes;
  410. }
  411. /*
  412. Deploy a collection of themes.
  413. Part of the push-button-deploy process.
  414. Can also be triggered to deploy a single theme with the command:
  415. node ./theme-utils.mjs deploy-theme THEMENAME
  416. */
  417. async function deployThemes(themes) {
  418. let response;
  419. for (let theme of themes) {
  420. console.log(`Deploying ${theme}`);
  421. let deploySuccess = false;
  422. let attempt = 0;
  423. while (!deploySuccess && attempt <= 2) {
  424. attempt++;
  425. console.log(`\nattempt #${attempt}\n\n`);
  426. response = await executeOnSandbox(`deploy pub ${theme};exit;`, true, true);
  427. deploySuccess = response.includes('successfully deployed to');
  428. if (!deploySuccess) {
  429. console.log('Deploy was not successful. Trying again in 10 seconds...');
  430. await new Promise(resolve => setTimeout(resolve, 10000));
  431. }
  432. else {
  433. console.log("Deploy successful.");
  434. }
  435. }
  436. if (!deploySuccess) {
  437. await inquirer.prompt([{
  438. type: 'confirm',
  439. message: `${theme} was not sucessfully deployed and should be deployed manually.`,
  440. name: "continue",
  441. default: false
  442. }]);
  443. }
  444. }
  445. }
  446. /*
  447. Provide the hash of the last managed deployment.
  448. This hash is used to determine all the changes that have happened between that point and the current point.
  449. */
  450. async function getLastDeployedHash() {
  451. let result = await executeOnSandbox(`
  452. cat ${sandboxPublicThemesFolder}/.pub-git-hash
  453. `);
  454. return result;
  455. }
  456. /*
  457. Update the 'last deployed hash' on the server with the current hash.
  458. */
  459. async function updateLastDeployedHash() {
  460. let hash = await executeCommand(`git rev-parse HEAD`);
  461. await executeOnSandbox(`
  462. echo '${hash}' > ${sandboxPublicThemesFolder}/.pub-git-hash
  463. `);
  464. }
  465. /*
  466. Version bump (increment version patch) any theme project that has had changes since the last deployment.
  467. If a theme's version has already been changed since that last deployment then do not version bump it.
  468. If any theme projects have had a version bump also version bump the parent project.
  469. If a theme has changes also update its changelog.
  470. Commit the change.
  471. */
  472. async function versionBumpThemes() {
  473. console.log("Version Bumping");
  474. let themes = await getActionableThemes();
  475. let hash = await getLastDeployedHash();
  476. let changesWereMade = false;
  477. let versionBumpCount = 0;
  478. for (let theme of themes) {
  479. let hasChanges = await checkThemeForChanges(theme, hash);
  480. if (!hasChanges) {
  481. // console.log(`${theme} has no changes`);
  482. continue;
  483. }
  484. versionBumpCount++;
  485. let hasVersionBump = await checkThemeForVersionBump(theme, hash);
  486. if (hasVersionBump) {
  487. continue;
  488. }
  489. await versionBumpTheme(theme, true);
  490. await updateThemeChangelog(theme, true);
  491. changesWereMade = true;
  492. }
  493. //version bump the root project if there were changes to any of the themes
  494. let rootHasVersionBump = await checkProjectForVersionBump(hash);
  495. if (versionBumpCount > 0 && !rootHasVersionBump) {
  496. await executeCommand(`npm version patch --no-git-tag-version && git add package.json package-lock.json`);
  497. changesWereMade = true;
  498. }
  499. return changesWereMade;
  500. }
  501. export function getThemeMetadata(styleCss, attribute) {
  502. if (!styleCss || !attribute) {
  503. return null;
  504. }
  505. switch (attribute) {
  506. case 'Version':
  507. return styleCss
  508. .match(/(?<=Version:\s*).*?(?=\s*\r?\n|\rg)/gs)[0]
  509. .trim()
  510. .replace('-wpcom', '');
  511. case 'Requires at least':
  512. return styleCss
  513. .match(/(?<=Requires at least:\s*).*?(?=\s*\r?\n|\rg)/gs);
  514. }
  515. }
  516. /* Rebuild theme changelog from a given starting hash */
  517. async function rebuildThemeChangelog(theme, since) {
  518. console.log(`Rebuilding ${theme} changelog since ${since || 'forever'}`);
  519. if (since) {
  520. since = `${since}..HEAD`;
  521. } else {
  522. since = 'HEAD';
  523. }
  524. let hashes = await executeCommand(`git rev-list ${since} -- ./${theme}`);
  525. hashes = hashes.split('\n');
  526. let logs = '== Changelog ==\n';
  527. for (let hash of hashes) {
  528. let log = await executeCommand(`git log -n 1 --pretty=format:"* %s" ${hash}`);
  529. if (log.includes('Version Bump')) {
  530. let previousStyleString = await executeCommand(`git show ${hash}:${theme}/style.css 2>/dev/null`);
  531. let version = getThemeMetadata(previousStyleString, 'Version');
  532. logs += `\n= ${version} =\n`;
  533. } else {
  534. // Remove any double quotes from commit messages
  535. log = log.replace(/"/g, '');
  536. logs += log + '\n';
  537. }
  538. }
  539. // Get theme readme.txt
  540. let readmeFilePath = `${theme}/readme.txt`;
  541. // Update readme.txt
  542. fs.readFile(readmeFilePath, 'utf8', function (err, data) {
  543. let changelogSection = '== Changelog ==';
  544. let regex = new RegExp('^.*' + changelogSection + '.*$', 'gm');
  545. let formattedChangelog = data.replace(regex, logs);
  546. fs.writeFile(readmeFilePath, formattedChangelog, 'utf8', function (err) {
  547. if (err) return console.log(err);
  548. });
  549. });
  550. }
  551. /*
  552. Update theme changelog using current commit logs.
  553. Used by versionBumpThemes to update each theme changelog.
  554. */
  555. async function updateThemeChangelog(theme, addChanges) {
  556. console.log(`Updating ${theme} changelog`);
  557. // Get theme version
  558. let styleCss = fs.readFileSync(`${theme}/style.css`, 'utf8');
  559. let version = getThemeMetadata(styleCss, 'Version');
  560. // Get list of updates with bullet points
  561. let logs = await getCommitLogs('', true, theme);
  562. // Get theme readme.txt
  563. let readmeFilePath = `${theme}/readme.txt`;
  564. if (!existsSync(readmeFilePath)) {
  565. console.log(`Unable to find a readme.txt for ${theme}.`);
  566. return;
  567. }
  568. // Build changelog entry
  569. let newChangelogEntry = `== Changelog ==
  570. = ${version} =
  571. ${logs}`;
  572. // Update readme.txt
  573. fs.readFile(readmeFilePath, 'utf8', function (err, data) {
  574. let changelogSection = '== Changelog ==';
  575. let regex = new RegExp('^.*' + changelogSection + '.*$', 'gm');
  576. let formattedChangelog = data.replace(regex, newChangelogEntry);
  577. fs.writeFile(readmeFilePath, formattedChangelog, 'utf8', function (err) {
  578. if (err) return console.log(err);
  579. });
  580. });
  581. // Stage readme.txt
  582. if (addChanges) {
  583. await executeCommand(`git add ${readmeFilePath}`);
  584. }
  585. }
  586. /*
  587. Version Bump a Theme.
  588. Used by versionBumpThemes to do the work of version bumping.
  589. First increment the patch version in style.css
  590. Then update any of these files with the new version: [package.json, style.scss, style-child-theme.scss]
  591. */
  592. async function versionBumpTheme(theme, addChanges) {
  593. console.log(`${theme} needs a version bump`);
  594. await executeCommand(`perl -pi -e 's/Version: ((\\d+\\.)*)(\\d+)(.*)$/"Version: ".$1.($3+1).$4/ge' ${theme}/style.css`, true);
  595. await executeCommand(`git add ${theme}/style.css`);
  596. let styleCss = fs.readFileSync(`${theme}/style.css`, 'utf8');
  597. let currentVersion = getThemeMetadata(styleCss, 'Version');
  598. let filesToUpdate = await executeCommand(`find ${theme} -name package.json -o -name style.scss -o -name style-child-theme.scss -maxdepth 2`);
  599. filesToUpdate = filesToUpdate.split('\n').filter(item => item != '');
  600. for (let file of filesToUpdate) {
  601. await executeCommand(`perl -pi -e 's/Version: (.*)$/"Version: '${currentVersion}'"/ge' ${file}`);
  602. await executeCommand(`perl -pi -e 's/\\"version\\": (.*)$/"\\"version\\": \\"'${currentVersion}'\\","/ge' ${file}`);
  603. if (addChanges) {
  604. await executeCommand(`git add ${file}`);
  605. }
  606. }
  607. }
  608. /*
  609. Determine if a theme has had a version bump since a given hash.
  610. Used by versionBumpThemes
  611. Compares the value of 'version' in style.css between the hash and current value
  612. */
  613. async function checkThemeForVersionBump(theme, hash) {
  614. return executeCommand(`
  615. git show ${hash}:${theme}/style.css 2>/dev/null
  616. `)
  617. .catch((error) => {
  618. //This is a new theme, no need to bump versions so we'll just say we've already done it
  619. return true;
  620. })
  621. .then((previousStyleString) => {
  622. if (previousStyleString === true) {
  623. return previousStyleString;
  624. }
  625. let previousVersion = getThemeMetadata(previousStyleString, 'Version');
  626. let styleCss = fs.readFileSync(`${theme}/style.css`, 'utf8');
  627. let currentVersion = getThemeMetadata(styleCss, 'Version');
  628. return previousVersion != currentVersion;
  629. });
  630. }
  631. /*
  632. Determine if the project has had a version bump since a given hash.
  633. Used by versionBumpThemes
  634. Compares the value of 'version' in package.json between the hash and current value
  635. */
  636. async function checkProjectForVersionBump(hash) {
  637. let previousPackageString = await executeCommand(`
  638. git show ${hash}:./package.json 2>/dev/null
  639. `);
  640. let previousPackage = JSON.parse(previousPackageString);
  641. let currentPackage = JSON.parse(fs.readFileSync(`./package.json`))
  642. return previousPackage.version != currentPackage.version;
  643. }
  644. /*
  645. Determine if a theme has had changes since a given hash.
  646. Used by versionBumpThemes
  647. */
  648. async function checkThemeForChanges(theme, hash) {
  649. let comittedChanges = await executeCommand(`git diff --name-only ${hash} HEAD -- ${theme}`);
  650. return comittedChanges != '';
  651. }
  652. /*
  653. Provide a list of 'actionable' themes (those themes that have style.css files)
  654. */
  655. async function getActionableThemes() {
  656. let result = await executeCommand(`for d in */; do
  657. if test -f "./$d/style.css"; then
  658. echo $d;
  659. fi
  660. done`);
  661. return result
  662. .split('\n')
  663. .map(item => item.replace('/', ''));
  664. }
  665. /*
  666. Clean the theme sandbox.
  667. checkout origin/trunk and ensure it's up-to-date.
  668. Remove any other changes.
  669. */
  670. async function cleanSandbox() {
  671. console.log('Cleaning the Themes Sandbox');
  672. await executeOnSandbox(`
  673. cd ${sandboxPublicThemesFolder};
  674. git reset --hard HEAD;
  675. git clean -fd;
  676. git checkout trunk;
  677. git pull;
  678. echo;
  679. git status
  680. `, true);
  681. console.log('All done cleaning.');
  682. }
  683. /*
  684. Clean the premium theme sandbox.
  685. checkout origin/trunk and ensure it's up-to-date.
  686. Remove any other changes.
  687. */
  688. async function cleanPremiumSandbox() {
  689. console.log('Cleaning the Themes Sandbox');
  690. await executeOnSandbox(`
  691. cd ${sandboxPremiumThemesFolder};
  692. git reset --hard HEAD;
  693. git clean -fd;
  694. git checkout trunk;
  695. git pull;
  696. echo;
  697. git status
  698. `, true);
  699. console.log('All done cleaning.');
  700. }
  701. /*
  702. Clean the entire sandbox.
  703. checkout origin/trunk and ensure it's up-to-date.
  704. Remove any other changes.
  705. */
  706. async function cleanAllSandbox() {
  707. console.log('Cleaning the Entire Sandbox');
  708. let response = await executeOnSandbox(`
  709. cd ${sandboxRootFolder};
  710. git reset --hard HEAD;
  711. git clean -fd;
  712. git checkout trunk;
  713. git pull;
  714. echo;
  715. git status
  716. `, true);
  717. console.log('All done cleaning.');
  718. }
  719. /*
  720. Push exactly what is here (all files) up to the sandbox (with the exclusion of files noted in .sandbox-ignore)
  721. */
  722. async function pushToSandbox() {
  723. console.log("Pushing All Themes to Sandbox.");
  724. let allThemes = await getActionableThemes();
  725. allThemes = allThemes.filter(item => !premiumThemes.includes(item));
  726. console.log(`Syncing ${allThemes.length} themes`);
  727. for (let theme of allThemes) {
  728. await pushThemeToSandbox(theme);
  729. }
  730. }
  731. async function pushThemeToSandbox(theme) {
  732. console.log(`Syncing ${theme}`);
  733. return executeCommand(`
  734. rsync -avR --no-p --no-times --delete -m --exclude-from='.sandbox-ignore' ./${theme}/ wpcom-sandbox:${sandboxPublicThemesFolder}/
  735. `, true);
  736. }
  737. /*
  738. Push exactly what is here (all files) up to the sandbox (with the exclusion of files noted in .sandbox-ignore)
  739. This pushes only the folders noted as "premiumThemes" into the premium themes directory.
  740. This is the only part of the deploy process that is automated; the rest must be done manually including:
  741. * Creating a Phabricator Diff
  742. * Landing (comitting) the change
  743. * Deploying the theme
  744. * Triggering the .zip builds
  745. */
  746. async function pushPremiumToSandbox() {
  747. //TODO: It would be nice to determine this list programatically
  748. const filesToModify = [
  749. 'style.css',
  750. 'block-templates/404.html',
  751. 'block-template-parts/header.html',
  752. 'block-template-parts/footer.html'
  753. ];
  754. // Change 'blockbase' to 'blockbase-premium' in the files noted
  755. for (let theme of premiumThemes) {
  756. for (let file of filesToModify) {
  757. await executeCommand(`perl -pi -e 's/blockbase/blockbase-premium/' ${theme}/${file}`, true);
  758. }
  759. }
  760. // Push the changes in the premium themes to the sandbox
  761. await executeCommand(`
  762. rsync -avR --no-p --no-times --delete -m --exclude-from='.sandbox-ignore' --exclude='sass' ./${premiumThemes.join(' ./')} wpcom-sandbox:${sandboxPremiumThemesFolder}/
  763. `, true);
  764. // revert the local blockbase-premium changes
  765. for (let theme of premiumThemes) {
  766. for (let file of filesToModify) {
  767. await executeCommand(`
  768. git restore --source=HEAD --staged --worktree ./${theme}/${file}
  769. `);
  770. }
  771. }
  772. }
  773. /*
  774. Push only (and every) change since the point-of-diversion from /trunk
  775. Remove files from the sandbox that have been removed since the last deployed hash
  776. */
  777. async function pushChangesToSandbox() {
  778. console.log("Pushing Changed Themes to Sandbox.");
  779. let hash = await getLastDeployedHash();
  780. let changedThemes = await getChangedThemes(hash);
  781. changedThemes = changedThemes.filter(item => !premiumThemes.includes(item));
  782. console.log(`Syncing ${changedThemes.length} themes`);
  783. for (let theme of changedThemes) {
  784. await pushThemeToSandbox(theme);
  785. }
  786. }
  787. async function pullCoreThemes() {
  788. console.log("Pulling CORE themes from sandbox.");
  789. for (let theme of coreThemes) {
  790. await executeCommand(`
  791. rsync -avr --no-p --no-times --delete -m --exclude-from='.sandbox-ignore' wpcom-sandbox:${sandboxPublicThemesFolder}/${theme}/ ./${theme}/
  792. `, true);
  793. }
  794. }
  795. async function pushCoreThemes() {
  796. console.log("Pushing CORE themes to sandbox.");
  797. for (let theme of coreThemes) {
  798. await executeCommand(`
  799. rsync -avr --no-p --no-times --delete -m --exclude-from='.sandbox-ignore' ./${theme}/ wpcom-sandbox:${sandboxPublicThemesFolder}/${theme}/
  800. `, true);
  801. }
  802. }
  803. async function syncCoreTheme(theme, sinceRevision) {
  804. if (!theme) {
  805. console.log('Must supply theme to sync and revision to start from');
  806. return;
  807. }
  808. if (!sinceRevision) {
  809. sinceRevision = await executeOnSandbox(`cat ${sandboxPublicThemesFolder}/${theme}/.pub-svn-revision`);
  810. }
  811. let latestRevision = await executeCommand(`svn info -r HEAD https://core.svn.wordpress.org/trunk | grep Revision | egrep -o "[0-9]+"`);
  812. console.log(`syncing core theme ${theme} from ${sinceRevision} to ${latestRevision} on your sandbox`);
  813. try {
  814. await executeOnSandbox(`
  815. cd ${sandboxPublicThemesFolder};
  816. /usr/bin/svn diff --git -r ${sinceRevision}:HEAD https://core.svn.wordpress.org/trunk/wp-content/themes/${theme} | git apply --reject --ignore-space-change --ignore-whitespace -p4 --directory=${theme} -
  817. `, true);
  818. }
  819. catch (err) {
  820. console.log('Error merging:', err);
  821. }
  822. await executeOnSandbox(`
  823. echo '${latestRevision}' > ${sandboxPublicThemesFolder}/${theme}/.pub-svn-revision
  824. `);
  825. return latestRevision;
  826. }
  827. /*
  828. Build the Phabricator commit message.
  829. This message contains the logs from all of the commits since the given hash.
  830. Used by create*PhabricatorDiff
  831. */
  832. async function buildPhabricatorCommitMessageSince(hash) {
  833. let projectVersion = await executeCommand(`node -p "require('./package.json').version"`);
  834. let logs = await getCommitLogs(hash);
  835. return `Deploy Themes ${projectVersion} to wpcom
  836. Summary:
  837. ${logs}
  838. Test Plan: Execute Smoke Test
  839. Reviewers:
  840. Subscribers:
  841. `;
  842. }
  843. /*
  844. Create a Phabricator diff with the given message based on the contents currently in the sandbox.
  845. Open the phabricator diff in your browser.
  846. Provide the URL of the phabricator diff.
  847. */
  848. async function createPhabricatorDiff(commitMessage) {
  849. console.log('creating Phabricator Diff');
  850. let result = await executeOnSandbox(`
  851. cd ${sandboxPublicThemesFolder};
  852. git branch -D deploy
  853. git checkout -b deploy
  854. git add --all
  855. git commit -m "${commitMessage}"
  856. arc diff --create --verbatim
  857. `, true);
  858. let phabricatorUrl = getPhabricatorUrlFromResponse(result);
  859. console.log('Diff Created at: ', phabricatorUrl);
  860. if (phabricatorUrl) {
  861. open(phabricatorUrl);
  862. }
  863. return phabricatorUrl;
  864. }
  865. /*
  866. Utility to pull the Phabricator URL from the diff creation command.
  867. Used by createPhabricatorDiff
  868. */
  869. function getPhabricatorUrlFromResponse(response) {
  870. return response
  871. ?.split('\n')
  872. ?.find(item => {
  873. return item.includes('Revision URI: ');
  874. })
  875. ?.split("Revision URI: ")[1];
  876. }
  877. /*
  878. Create a git tag at the current hash.
  879. In the description include the commit logs since the given hash.
  880. Include the (cleansed) Phabricator link.
  881. */
  882. async function tagDeployment(options = {}) {
  883. console.log('tagging deployment');
  884. let hash = options.hash || await getLastDeployedHash();
  885. let workInTheOpenPhabricatorUrl = '';
  886. if (options.diffId) {
  887. workInTheOpenPhabricatorUrl = `Phabricator: ${options.diffId}-code`;
  888. }
  889. let projectVersion = await executeCommand(`node -p "require('./package.json').version"`);
  890. let logs = await getCommitLogs(hash);
  891. let tag = `v${projectVersion}`;
  892. let message = `Deploy Themes ${tag} to wpcom. \n\n${logs} \n\n${workInTheOpenPhabricatorUrl}`;
  893. await executeCommand(`
  894. git tag -a ${tag} -m "${message}"
  895. git push origin ${tag}
  896. `, true);
  897. }
  898. /*
  899. Execute a command on the sandbox.
  900. Expects the following to be configured in your ~/.ssh/config file:
  901. Host wpcom-sandbox
  902. User wpdev
  903. HostName SANDBOXURL.wordpress.com
  904. ForwardAgent yes
  905. */
  906. function executeOnSandbox(command, logResponse, enablePsudoterminal) {
  907. if (enablePsudoterminal) {
  908. return executeCommand(`ssh -tt -A ${remoteSSH} << EOF
  909. ${command}
  910. EOF`, logResponse);
  911. }
  912. return executeCommand(`ssh -TA ${remoteSSH} << EOF
  913. ${command}
  914. EOF`, logResponse);
  915. }
  916. /*
  917. Execute a command locally.
  918. */
  919. export async function executeCommand(command, logResponse) {
  920. return new Promise((resolove, reject) => {
  921. let child;
  922. let response = '';
  923. let errResponse = '';
  924. if (isWin) {
  925. child = spawn('cmd.exe', ['/s', '/c', '"' + command + '"'], {
  926. windowsVerbatimArguments: true,
  927. stdio: [process.stdin, 'pipe', 'pipe'],
  928. })
  929. } else {
  930. child = spawn(process.env.SHELL, ['-c', command], {
  931. stdio: [process.stdin, 'pipe', 'pipe'],
  932. });
  933. }
  934. child.stdout.on('data', (data) => {
  935. response += data;
  936. if (logResponse) {
  937. console.log(data.toString());
  938. }
  939. });
  940. child.stderr.on('data', (data) => {
  941. errResponse += data;
  942. if (logResponse) {
  943. console.log(data.toString());
  944. }
  945. });
  946. child.on('exit', (code) => {
  947. if (code !== 0) {
  948. reject(errResponse.trim());
  949. }
  950. resolove(response.trim());
  951. });
  952. });
  953. }