theme-utils.mjs 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366
  1. import { execSync, spawn } from 'child_process';
  2. import fs, { existsSync } from 'fs';
  3. import open from 'open';
  4. import inquirer from 'inquirer';
  5. import { RewritingStream } from 'parse5-html-rewriting-stream';
  6. import { table } from 'table';
  7. import progressbar from 'string-progressbar';
  8. import semver from 'semver';
  9. const remoteSSH = 'wpcom-sandbox';
  10. const sandboxPublicThemesFolder = '/home/wpcom/public_html/wp-content/themes/pub';
  11. const sandboxRootFolder = '/home/wpcom/public_html/';
  12. const glotPressScript = '~/public_html/bin/i18n/create-glotpress-project-for-theme.php';
  13. const isWin = process.platform === 'win32';
  14. const coreThemes = ['twentyten', 'twentyeleven', 'twentytwelve', 'twentythirteen', 'twentyfourteen', 'twentyfifteen', 'twentysixteen', 'twentyseventeen', 'twentynineteen', 'twentytwenty', 'twentytwentyone', 'twentytwentytwo', 'twentytwentythree', 'twentytwentyfour'];
  15. const commands = {
  16. "push-button-deploy": {
  17. helpText: `
  18. * Gets the last deployed hash from the sandbox
  19. * Version bump all themes that have changes since the last deployment
  20. * Commit the version bump change to github
  21. * Clean the sandbox and ensure it is up - to - date
  22. * Push all changed files(including removal of deleted files) since the last deployment
  23. * Update the 'last deployed' hash on the sandbox
  24. * Create a GitHub pull request based on the changes since the last deployment. The description including the commit messages since the last deployment.
  25. * Open the GitHub pull request in your browser
  26. * Create a tag in the github repository at this point of change which includes the GitHub pull request link in the description
  27. * After pausing to allow testing, merge and deploy the changes
  28. `,
  29. run: pushButtonDeploy
  30. },
  31. "clean-sandbox": {
  32. helpText: 'Perform a hard reset, checkout trunk, and pull on the public themes working copy on your sandbox.',
  33. run: cleanSandbox
  34. },
  35. "push-to-sandbox": {
  36. helpText: 'Uses rsync to copy all modified files for all themes from the local machine to your sandbox.',
  37. run: pushToSandbox
  38. },
  39. "push-changes-to-sandbox": {
  40. helpText: 'Uses rsync to copy all modified files for any modified themes from the local machine to your sandbox.',
  41. run: pushChangesToSandbox
  42. },
  43. "push-theme-to-sandbox": {
  44. helpText: 'Uses rsync to copy all modified files for the specified theme from the local machine to your sandbox.',
  45. additionalArgs: '<theme-slug>',
  46. run: (args) => pushThemeToSandbox(args?.[1])
  47. },
  48. "version-bump-themes": {
  49. 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.',
  50. run: versionBumpThemes
  51. },
  52. "land-diff": {
  53. helpText: 'Run gh pr merge to merge in the specified pull request id.',
  54. additionalArgs: '<gh pr id>',
  55. run: (args) => landChanges(args?.[1])
  56. },
  57. "deploy-preview": {
  58. helpText: 'Display a list of the changes to be deployed.',
  59. run: deployPreview
  60. },
  61. "deploy-theme": {
  62. helpText: 'This runs "deploy pub <theme>" on the provided list of themes.',
  63. additionalArgs: '<array of theme slugs>',
  64. run: (args) => deployThemes(args?.[1].split(/[ ,]+/))
  65. },
  66. "add-strict-typing": {
  67. helpText: 'Adds strict typing to any changed themes.',
  68. run: () => addStrictTypesToChangedThemes()
  69. },
  70. "build-com-zip": {
  71. helpText: 'Build the production zip file for the specified theme.',
  72. additionalArgs: '<theme-slug>',
  73. run: (args) => buildComZips(args?.[1].split(/[ ,]+/))
  74. },
  75. "checkout-core-theme": {
  76. helpText: 'Use SVN to checkout the given core themes from the wpcom SVN repository.',
  77. additionalArgs: '<theme-slug>',
  78. run: (args) => checkoutCoreTheme(args?.[1])
  79. },
  80. "pull-all-themes": {
  81. helpText: 'Use rsync to copy all public theme files from your sandbox to your local machine.',
  82. run: pullAllThemes
  83. },
  84. "pull-core-themes": {
  85. helpText: 'Use rsync to copy all public CORE theme files from your sandbox to your local machine. CORE themes are any of the Twenty<whatever> themes.',
  86. run: pullCoreThemes
  87. },
  88. "push-core-themes": {
  89. helpText: 'Use rsync to copy all public CORE theme files from your local machine to your sandbox. CORE themes are any of the Twenty<whatever> themes.',
  90. run: pushCoreThemes
  91. },
  92. "sync-core-theme": {
  93. helpText: 'Given a theme slug and SVN revision, sync the theme from the specified revision to the latest. This requires the core theme to be currently checked out from the wpcom svn repository.',
  94. additionalArgs: '<theme-slug> <since-revision>',
  95. run: (args) => syncCoreTheme(args?.[1], args?.[2])
  96. },
  97. "deploy-sync-core-theme": {
  98. 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.',
  99. additionalArgs: '<theme-slug> <since-revision>',
  100. run: (args) => deploySyncCoreTheme(args?.[1], args?.[2])
  101. },
  102. "create-core-github-pr": {
  103. helpText: 'Given a theme slug and specific revision create a GitHub pull request from the resources currently on the sandbox.',
  104. additionalArgs: '<theme-slug> <since-revision>',
  105. run: (args) => createCoreGithubPR(args?.[1], args?.[2])
  106. },
  107. "update-theme-changelog": {
  108. 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.',
  109. additionalArgs: '<theme-slug> <add-changes, true/false>',
  110. run: (args) => updateThemeChangelog(args?.[1], false, args?.[2])
  111. },
  112. "rebuild-theme-changelog": {
  113. helpText: 'Rebuild the entire change long from the given starting hash.',
  114. additionalArgs: '<theme-slug> <since>',
  115. run: (args) => rebuildThemeChangelog(args?.[1], args?.[2])
  116. },
  117. "escape-patterns": {
  118. helpText: 'Escapes block patterns for pattern files that have changes (staged or unstaged).',
  119. run: () => escapePatterns()
  120. },
  121. "help": {
  122. helpText: 'Displays the main help message.',
  123. run: (args) => showHelp(args?.[1])
  124. },
  125. };
  126. (async function start() {
  127. let args = process.argv.slice(2);
  128. let command = args?.[0];
  129. if (!commands[command]) {
  130. return showHelp();
  131. }
  132. commands[command].run(args);
  133. })();
  134. function showHelp(command = '') {
  135. if (!command || !commands.hasOwnProperty(command)) {
  136. console.log(`
  137. node theme-utils.mjs [command]
  138. Available commands:
  139. _(theme-utils.mjs help [command] for more details)_
  140. \t${Object.keys(commands).join('\n\t')}
  141. `);
  142. return;
  143. }
  144. const { helpText, additionalArgs } = commands[command];
  145. console.log(`
  146. ${command} ${additionalArgs ?? ''}
  147. ${helpText}
  148. `);
  149. }
  150. /*
  151. Create list of changes from git logs
  152. Optionally pass in a deployed hash or default to calling getLastDeployedHash()
  153. Optionally pass in boolean bulletPoints to add bullet points to each commit log
  154. */
  155. async function getCommitLogs(hash, bulletPoints, theme) {
  156. if (!hash) {
  157. hash = await getLastDeployedHash();
  158. }
  159. let format = 'format:%s';
  160. let themeDir = '';
  161. if (bulletPoints) {
  162. format = 'format:"* %s"';
  163. }
  164. if (theme) {
  165. themeDir = `-- ./${theme}`;
  166. }
  167. let logs = await executeCommand(`git log --reverse --pretty=${format} ${hash}..HEAD ${themeDir}`);
  168. // Remove any double quotes from commit messages
  169. logs = logs.replace(/"/g, '');
  170. return logs;
  171. }
  172. /*
  173. Determine what changes would be deployed
  174. */
  175. async function deployPreview() {
  176. console.clear();
  177. console.log('To ensure accuracy clean your sandbox before previewing. (It is not automatically done).');
  178. let message = await checkForDeployability();
  179. if (message) {
  180. console.log(`\n${message}\n\n`);
  181. }
  182. let hash = await getLastDeployedHash();
  183. console.log(`Last deployed hash: ${hash}`);
  184. let changedThemes = await getChangedThemes(hash);
  185. console.log(`The following themes have changes:\n${changedThemes}`);
  186. let logs = await getCommitLogs(hash);
  187. console.log(`\n\nCommit log of changes to be deployed:\n\n${logs}\n\n`);
  188. }
  189. async function addStrictTypesToChangedThemes() {
  190. let hash = await getLastDeployedHash();
  191. const changedThemes = await getChangedThemes(hash);
  192. for (let theme of changedThemes) {
  193. await executeCommand(`
  194. bash -c "./add-strict-types.sh ${theme}"
  195. `, true)
  196. .catch((err) => {
  197. console.log(`Error adding strict types to ${theme}: ${err}`);
  198. });
  199. }
  200. }
  201. /*
  202. Execute the first phase of a deployment.
  203. * Gets the last deployed hash from the sandbox
  204. * Version bump all themes that have changes since the last deployment
  205. * Commit the version bump change to github
  206. * Clean the sandbox and ensure it is up-to-date
  207. * Push all changed files (including removal of deleted files) since the last deployment
  208. * Update the 'last deployed' hash on the sandbox
  209. * Create a GitHub pull request based on the changes since the last deployment. The description including the commit messages since the last deployment.
  210. * Open the GitHub pull request in your browser
  211. * Create a tag in the github repository at this point of change which includes the GitHub pull request link in the description
  212. */
  213. async function pushButtonDeploy() {
  214. console.clear();
  215. let prompt = await inquirer.prompt([{
  216. type: 'confirm',
  217. message: 'You are about to deploy /trunk. Are you ready to continue?',
  218. name: "continue",
  219. default: false
  220. }]);
  221. if (!prompt.continue) {
  222. return;
  223. }
  224. let message = await checkForDeployability();
  225. if (message) {
  226. return console.log(`\n\n${message}\n\n`);
  227. }
  228. try {
  229. await cleanSandbox();
  230. const hash = await getLastDeployedHash();
  231. await addStrictTypesToChangedThemes();
  232. const thingsWentBump = await versionBumpThemes();
  233. if (thingsWentBump) {
  234. prompt = await inquirer.prompt([{
  235. type: 'confirm',
  236. message: 'Are you good with the version bump and changelog updates? Make any manual adjustments now if necessary.',
  237. name: "continue",
  238. default: false
  239. }]);
  240. if (!prompt.continue) {
  241. console.log(`Aborted Automated Deploy Process at version bump changes.`);
  242. return;
  243. }
  244. }
  245. const changedThemes = await getChangedThemes(hash);
  246. if (!changedThemes.length) {
  247. console.log(`\n\nEverything is upto date. Nothing new to deploy.\n\n`);
  248. return;
  249. }
  250. await pushChangesToSandbox();
  251. await createGlotPressProject(changedThemes);
  252. //push changes (from version bump)
  253. if (thingsWentBump) {
  254. prompt = await inquirer.prompt([{
  255. type: 'confirm',
  256. message: 'Are you ready to push this version bump change to the source repository (GitHub.com)?',
  257. name: "continue",
  258. default: false
  259. }]);
  260. if (!prompt.continue) {
  261. console.log(`Aborted Automated Deploy Process at version bump push change.`);
  262. return;
  263. }
  264. await executeCommand(`
  265. git commit -m "Version Bump";
  266. git push --set-upstream origin trunk
  267. `, true);
  268. }
  269. await updateLastDeployedHash();
  270. let commitMessage = await buildGithubCommitMessageSince(hash);
  271. // Make sure the themes/pub repo in sandbox is ready to create a PR to the A8C GitHub Host
  272. prompt = await inquirer.prompt([{
  273. type: 'confirm',
  274. message: 'Before you can create the GitHub PR, login in A8C GitHub Enterprise Server from the themes/pub repo in your sandbox with the command "gh auth login" and using your SSH key.\nAre you logged in?',
  275. name: "continue",
  276. default: false
  277. }]);
  278. if (!prompt.continue) {
  279. console.log(`Aborted Automated Deploy Process at require to login in into A8C GitHub Enterprise Server in sandbox.`);
  280. return;
  281. }
  282. let prUrl = await createGithubPR(commitMessage);
  283. let prId = prUrl.split('pull/')[1];
  284. await tagDeployment({
  285. hash: hash,
  286. prId: prId
  287. });
  288. console.log(`\n\nPhase One Complete\n\nYour sandbox has been updated and the PR 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`);
  289. prompt = await inquirer.prompt([{
  290. type: 'confirm',
  291. message: 'Are you ready to land these changes?',
  292. name: "continue",
  293. default: false
  294. }]);
  295. if (!prompt.continue) {
  296. console.log(`Aborted Automated Deploy Process Landing Phase\n\nYou will have to land these changes manually. The ID of the PR to land: ${prId}`);
  297. return;
  298. }
  299. await landChanges(prId);
  300. try {
  301. await deployThemes(changedThemes);
  302. }
  303. catch (err) {
  304. prompt = await inquirer.prompt([{
  305. type: 'confirm',
  306. message: `There was an error deploying themes. ${err} Do you wish to continue to the next step?`,
  307. name: "continue",
  308. default: false
  309. }]);
  310. if (!prompt.continue) {
  311. console.log(`Aborted Automated Deploy during deploy phase.`);
  312. return;
  313. }
  314. }
  315. await buildComZips(changedThemes);
  316. console.log(`The following themes have changed:\n${changedThemes.join('\n')}`)
  317. console.log('\n\nAll Done!!\n\n');
  318. }
  319. catch (err) {
  320. console.log("ERROR with deploy script: ", err);
  321. }
  322. }
  323. async function deploySyncCoreTheme(theme, sinceRevision) {
  324. if (!theme) {
  325. console.log('Must supply theme to sync and revision to start from');
  326. return;
  327. }
  328. await cleanSandbox();
  329. await checkoutCoreTheme(theme);
  330. await syncCoreTheme(theme, sinceRevision);
  331. let prompt = await inquirer.prompt([{
  332. type: 'confirm',
  333. message: `Changes have been synced locally. Please resolve any conflicts now. Are you ready to continue?`,
  334. name: "continue",
  335. default: false
  336. }]);
  337. if (!prompt.continue) {
  338. console.log(`Aborted Core Sync Deploy.`);
  339. return;
  340. }
  341. await pushThemeToSandbox(theme);
  342. let prId = await createCoreGithubPR(theme, sinceRevision);
  343. prompt = await inquirer.prompt([{
  344. type: 'confirm',
  345. message: 'Are you ready to land these changes?',
  346. name: "continue",
  347. default: false
  348. }]);
  349. if (!prompt.continue) {
  350. console.log(`Aborted Automated Deploy Sync Process Landing Phase\n\nYou will have to land these changes manually. The ID of the PR to land: ${prId}`);
  351. return;
  352. }
  353. await landChanges(prId);
  354. await deployThemes([theme]);
  355. await buildComZips([theme]);
  356. return;
  357. }
  358. async function buildCoreGithubCommitMessageSince(theme, sinceRevision){
  359. let latestRevision = await executeCommand(`svn info -r HEAD https://develop.svn.wordpress.org/trunk | grep Revision | egrep -o "[0-9]+"`);
  360. let logs = await executeCommand(`svn log https://core.svn.wordpress.org/trunk/wp-content/themes/${theme} -r${sinceRevision}:HEAD`)
  361. // Remove any double or back quotes from commit messages
  362. logs = logs.replace(/"/g, '');
  363. logs = logs.replace(/`/g, "'");
  364. logs = logs.replace(/\$/g, "%24");
  365. return `${theme}: Merge latest core changes up to [wp${latestRevision}]
  366. Summary:
  367. ${logs}
  368. Test Plan: Activate ${theme} and ensure nothing is broken
  369. Reviewers:
  370. #themes_team
  371. Subscribers:
  372. `;
  373. }
  374. /**
  375. * Deploys the localy copy of a core theme to wpcom.
  376. */
  377. async function createCoreGithubPR(theme, sinceRevision) {
  378. let commitMessage = await buildCoreGithubCommitMessageSince(theme, sinceRevision);
  379. let prUrl = await createGithubPR(commitMessage);
  380. let prId = prUrl.split('pull/')[1];
  381. return prId;
  382. }
  383. /*
  384. Build .zip file for .com
  385. */
  386. async function buildComZip(themeSlug) {
  387. console.log(`Building ${themeSlug} .zip`);
  388. let styleCss = fs.readFileSync(`${themeSlug}/style.css`, 'utf8');
  389. // Gets the theme version (Version:) and minimum WP version (Tested up to:) from the theme's style.css
  390. let themeVersion = getThemeMetadata(styleCss, 'Version');
  391. let wpVersionCompat = getThemeMetadata(styleCss, 'Requires at least');
  392. if (themeVersion && wpVersionCompat) {
  393. await executeOnSandbox(`php ${sandboxRootFolder}bin/themes/theme-downloads/build-theme-zip.php --stylesheet=pub/${themeSlug} --themeversion=${themeVersion} --wpversioncompat=${wpVersionCompat};`, true);
  394. }
  395. else {
  396. console.log('Unable to build theme .zip.');
  397. if (!themeVersion) {
  398. console.log('Could not find theme version (Version:) in the theme style.css.');
  399. }
  400. if (!wpVersionCompat) {
  401. console.log('Could not find WP compat version (Tested up to:) in the theme style.css.');
  402. }
  403. console.log('Please build the .zip file for the theme manually.', themeSlug);
  404. open('https://mc.a8c.com/themes/downloads/');
  405. }
  406. }
  407. async function buildComZips(themes) {
  408. console.log(`Building dotcom .zip files`);
  409. const progress = startProgress(themes.length);
  410. const failedThemes = []
  411. for (let theme of themes) {
  412. try {
  413. await buildComZip(theme);
  414. } catch (err) {
  415. console.log(`There was an error building dotcom zip for ${theme}. ${err}`);
  416. failedThemes.push(theme);
  417. }
  418. progress.increment();
  419. }
  420. if (failedThemes.length) {
  421. const tableConfig = {
  422. columnDefault: {
  423. width: 40,
  424. },
  425. header: {
  426. alignment: 'center',
  427. content: `There was an error building dotcom zip for following themes.`,
  428. }
  429. };
  430. console.log(table(failedThemes.map(t => [t]), tableConfig));
  431. }
  432. }
  433. /*
  434. Check to ensure that:
  435. * The current branch is /trunk
  436. * That trunk is up-to-date with origin/trunk
  437. */
  438. async function checkForDeployability() {
  439. let branchName = await executeCommand('git symbolic-ref --short HEAD');
  440. if (branchName !== 'trunk') {
  441. return 'Only the /trunk branch can be deployed.';
  442. }
  443. await executeCommand('git remote update', true);
  444. let localMasterHash = await executeCommand('git rev-parse trunk')
  445. let remoteMasterHash = await executeCommand('git rev-parse origin/trunk')
  446. if (localMasterHash !== remoteMasterHash) {
  447. return 'Local /trunk is out-of-date. Pull changes to continue.'
  448. }
  449. return null;
  450. }
  451. /*
  452. Land the changes from the given PR ID. This is the "production merge".
  453. */
  454. async function landChanges(prId) {
  455. return executeCommand(`ssh -tt -A ${remoteSSH} "cd ${sandboxPublicThemesFolder} && gh pr merge ${prId} --squash; exit;"`, true);
  456. }
  457. async function getChangedThemes(hash) {
  458. console.log('Determining all changed themes');
  459. let themes = await getActionableThemes();
  460. let changedThemes = [];
  461. for (let theme of themes) {
  462. let hasChanges = await checkThemeForChanges(theme, hash);
  463. if (hasChanges) {
  464. changedThemes.push(theme);
  465. }
  466. }
  467. return changedThemes;
  468. }
  469. /*
  470. Deploy a collection of themes.
  471. Part of the push-button-deploy process.
  472. Can also be triggered to deploy a single theme with the command:
  473. node ./theme-utils.mjs deploy-theme THEMENAME
  474. */
  475. async function deployThemes(themes) {
  476. let response;
  477. const failedThemes = [];
  478. const progress = startProgress(themes.length);
  479. for (let theme of themes) {
  480. console.log(`Deploying ${theme}`);
  481. let deploySuccess = false;
  482. let attempt = 0;
  483. while (!deploySuccess && attempt <= 2) {
  484. attempt++;
  485. console.log(`\nattempt #${attempt}\n\n`);
  486. try {
  487. response = await executeOnSandbox(`deploy pub ${theme};exit;`, true, true);
  488. deploySuccess = response.includes('successfully deployed to');
  489. } catch (error) {
  490. deploySuccess = false
  491. }
  492. if (!deploySuccess) {
  493. console.log('Deploy was not successful. Trying again in 10 seconds...');
  494. await new Promise(resolve => setTimeout(resolve, 10000));
  495. }
  496. else {
  497. console.log("Deploy successful.");
  498. }
  499. }
  500. if (!deploySuccess) {
  501. console.log(`${theme} was not sucessfully deployed and should be deployed manually.`);
  502. failedThemes.push(theme);
  503. }
  504. progress.increment();
  505. }
  506. if (failedThemes.length) {
  507. const tableConfig = {
  508. columnDefault: {
  509. width: 40,
  510. },
  511. header: {
  512. alignment: 'center',
  513. content: `Following themes are not deployed.`,
  514. }
  515. };
  516. console.log(table(failedThemes.map(t => [t]), tableConfig));
  517. }
  518. }
  519. /*
  520. Provide the hash of the last managed deployment.
  521. This hash is used to determine all the changes that have happened between that point and the current point.
  522. */
  523. async function getLastDeployedHash() {
  524. let result = await executeOnSandbox(`
  525. cat ${sandboxPublicThemesFolder}/.pub-git-hash
  526. `);
  527. return result;
  528. }
  529. /*
  530. Update the 'last deployed hash' on the server with the current hash.
  531. */
  532. async function updateLastDeployedHash() {
  533. let hash = await executeCommand(`git rev-parse HEAD`);
  534. await executeOnSandbox(`
  535. echo '${hash}' > ${sandboxPublicThemesFolder}/.pub-git-hash
  536. `);
  537. }
  538. /*
  539. Version bump (increment version patch) any theme project that has had changes since the last deployment.
  540. If a theme's version has already been changed since that last deployment then do not version bump it.
  541. If any theme projects have had a version bump also version bump the parent project.
  542. If a theme has changes also update its changelog.
  543. Commit the change.
  544. */
  545. async function versionBumpThemes() {
  546. console.log("Version Bumping");
  547. const themes = await getActionableThemes();
  548. const latestTag = execSync('git describe --tags --abbrev=0').toString().trim();
  549. // Get the hash for the latest tag.
  550. const hash = execSync(`git rev-parse ${latestTag}`).toString().trim();
  551. let versionBumpCount = 0;
  552. let changesWereMade = false;
  553. for (let theme of themes) {
  554. const hasChanges = await checkThemeForChanges(theme, hash);
  555. if (!hasChanges) {
  556. continue;
  557. }
  558. versionBumpCount++;
  559. const hasVersionBump = await checkThemeForVersionBump(theme, hash);
  560. if (hasVersionBump) {
  561. continue;
  562. }
  563. await versionBumpTheme(theme, true);
  564. await updateThemeChangelog(theme, true);
  565. changesWereMade = true;
  566. }
  567. //version bump the root project if there were changes to any of the themes
  568. const rootHasVersionBump = await checkProjectForVersionBump(hash);
  569. if (versionBumpCount === 0) {
  570. console.log('No changes detected; Root package version bump not required');
  571. } else if (!rootHasVersionBump) {
  572. await executeCommand(`npm version patch --no-git-tag-version && git add package.json package-lock.json`);
  573. changesWereMade = true;
  574. }
  575. return changesWereMade;
  576. }
  577. export function getThemeMetadata(styleCss, attribute, trimWPCom = true) {
  578. if (!styleCss || !attribute) {
  579. return null;
  580. }
  581. switch (attribute) {
  582. case 'Version':
  583. const version = styleCss
  584. .match(/(?<=Version:\s*).*?(?=\s*\r?\n|\rg)/gs)[0]
  585. .trim();
  586. return trimWPCom ? version.replace('-wpcom', '') : version;
  587. case 'Requires at least':
  588. return styleCss
  589. .match(/(?<=Requires at least:\s*).*?(?=\s*\r?\n|\rg)/gs);
  590. }
  591. }
  592. /* Rebuild theme changelog from a given starting hash */
  593. async function rebuildThemeChangelog(theme, since) {
  594. console.log(`Rebuilding ${theme} changelog since ${since || 'forever'}`);
  595. if (since) {
  596. since = `${since}..HEAD`;
  597. } else {
  598. since = 'HEAD';
  599. }
  600. let hashes = await executeCommand(`git rev-list ${since} -- ./${theme}`);
  601. hashes = hashes.split('\n');
  602. let logs = '== Changelog ==\n';
  603. for (let hash of hashes) {
  604. let log = await executeCommand(`git log -n 1 --pretty=format:"* %s" ${hash}`);
  605. if (log.includes('Version Bump')) {
  606. let previousStyleString = await executeCommand(`git show ${hash}:${theme}/style.css 2>/dev/null`);
  607. let version = getThemeMetadata(previousStyleString, 'Version');
  608. logs += `\n= ${version} =\n`;
  609. } else {
  610. // Remove any double quotes from commit messages
  611. log = log.replace(/"/g, '');
  612. logs += log + '\n';
  613. }
  614. }
  615. // Get theme readme.txt
  616. let readmeFilePath = `${theme}/readme.txt`;
  617. // Update readme.txt
  618. fs.readFile(readmeFilePath, 'utf8', function (err, data) {
  619. let changelogSection = '== Changelog ==';
  620. let regex = new RegExp('^.*' + changelogSection + '.*$', 'gm');
  621. let formattedChangelog = data.replace(regex, logs);
  622. fs.writeFile(readmeFilePath, formattedChangelog, 'utf8', function (err) {
  623. if (err) return console.log(err);
  624. });
  625. });
  626. }
  627. /*
  628. Update theme changelog using current commit logs.
  629. Used by versionBumpThemes to update each theme changelog.
  630. */
  631. async function updateThemeChangelog(theme, addChanges) {
  632. console.log(`Updating ${theme} changelog`);
  633. // Get theme version
  634. let styleCss = fs.readFileSync(`${theme}/style.css`, 'utf8');
  635. let version = getThemeMetadata(styleCss, 'Version');
  636. // Get list of updates with bullet points
  637. const lastestTagHash = execSync('git describe --tags --abbrev=0').toString().trim();
  638. let logs = await getCommitLogs(lastestTagHash, true, theme);
  639. // Get theme readme.txt
  640. let readmeFilePath = `${theme}/readme.txt`;
  641. if (!existsSync(readmeFilePath)) {
  642. console.log(`Unable to find a readme.txt for ${theme}.`);
  643. return;
  644. }
  645. // Build changelog entry
  646. let newChangelogEntry = `== Changelog ==
  647. = ${version} =
  648. ${logs}`;
  649. // Update readme.txt
  650. fs.readFile(readmeFilePath, 'utf8', function (err, data) {
  651. let changelogSection = '== Changelog ==';
  652. let regex = new RegExp('^.*' + changelogSection + '.*$', 'gm');
  653. let formattedChangelog = data.replace(regex, newChangelogEntry);
  654. fs.writeFile(readmeFilePath, formattedChangelog, 'utf8', function (err) {
  655. if (err) return console.log(err);
  656. });
  657. });
  658. // Stage readme.txt
  659. if (addChanges) {
  660. await executeCommand(`git add ${readmeFilePath}`);
  661. }
  662. }
  663. /*
  664. Version Bump a Theme.
  665. Used by versionBumpThemes to do the work of version bumping.
  666. First increment the patch version in style.css
  667. Then update any of these files with the new version: [package.json, style.scss, style-child-theme.scss]
  668. */
  669. async function versionBumpTheme(theme, addChanges) {
  670. console.log(`${theme} needs a version bump`);
  671. await executeCommand(`perl -pi -e 's/Version: ((\\d+\\.)*)(\\d+)(.*)$/"Version: ".$1.($3+1).$4/ge' ${theme}/style.css`, true);
  672. await executeCommand(`git add ${theme}/style.css`);
  673. let styleCss = fs.readFileSync(`${theme}/style.css`, 'utf8');
  674. let currentVersion = getThemeMetadata(styleCss, 'Version', false);
  675. let filesToUpdate = await executeCommand(`find ${theme} -not \\( -path "*/node_modules/*" -prune \\) -and \\( -name package.json -or -name style.scss -or -name style-rtl.css -or -name style-child-theme.scss \\) -maxdepth 3`);
  676. filesToUpdate = filesToUpdate.split('\n').filter(item => item != '');
  677. for (let file of filesToUpdate) {
  678. const isPackageJson = file === `${theme}/package.json`;
  679. if (isPackageJson) {
  680. // update theme/package.json and package-lock.json
  681. await executeCommand(`npm version ${currentVersion.replace('-wpcom', '')} --workspace=${theme}`);
  682. } else {
  683. await executeCommand(`perl -pi -e 's/Version: (.*)$/"Version: '${currentVersion}'"/ge' ${file}`);
  684. }
  685. if (addChanges) {
  686. await executeCommand(`git add ${file}`);
  687. }
  688. }
  689. }
  690. /*
  691. Determine if a theme has had a version bump since a given hash.
  692. Used by versionBumpThemes
  693. Compares the value of 'version' in style.css between the hash and current value
  694. */
  695. async function checkThemeForVersionBump(theme, hash) {
  696. return executeCommand(`
  697. git show ${hash}:${theme}/style.css 2>/dev/null
  698. `)
  699. .catch((error) => {
  700. //This is a new theme, no need to bump versions so we'll just say we've already done it
  701. return true;
  702. })
  703. .then((previousStyleString) => {
  704. if (previousStyleString === true) {
  705. return previousStyleString;
  706. }
  707. let previousVersion = getThemeMetadata(previousStyleString, 'Version');
  708. let styleCss = fs.readFileSync(`${theme}/style.css`, 'utf8');
  709. let currentVersion = getThemeMetadata(styleCss, 'Version');
  710. return previousVersion != currentVersion;
  711. });
  712. }
  713. /*
  714. Determine if the project has had a version bump since a given hash.
  715. Used by versionBumpThemes
  716. Compares the value of 'version' in package.json between the hash and current value
  717. */
  718. async function checkProjectForVersionBump(hash) {
  719. let previousPackageString = await executeCommand(`
  720. git show ${hash}:./package.json 2>/dev/null
  721. `);
  722. let previousPackage = JSON.parse(previousPackageString);
  723. let currentPackage = JSON.parse(fs.readFileSync(`./package.json`))
  724. return previousPackage.version != currentPackage.version;
  725. }
  726. /*
  727. Determine if a theme has had changes since a given hash.
  728. Used by versionBumpThemes
  729. */
  730. async function checkThemeForChanges(theme, hash) {
  731. let comittedChanges = await executeCommand(`git diff --name-only ${hash} HEAD -- ${theme}`);
  732. return comittedChanges != '';
  733. }
  734. /*
  735. Provide a list of 'actionable' themes (those themes that have style.css files)
  736. */
  737. async function getActionableThemes() {
  738. let result = await executeCommand(`for d in */; do
  739. if test -f "./$d/style.css"; then
  740. echo $d;
  741. fi
  742. done`);
  743. return result
  744. .split('\n')
  745. .map(item => item.replace('/', ''));
  746. }
  747. /*
  748. Clean the theme sandbox.
  749. checkout origin/trunk and ensure it's up-to-date.
  750. Remove any other changes.
  751. */
  752. async function cleanSandbox() {
  753. console.log('Cleaning the Themes Sandbox');
  754. await executeOnSandbox(`
  755. cd ${sandboxPublicThemesFolder};
  756. git reset --hard HEAD;
  757. git clean -fd;
  758. git checkout trunk;
  759. git pull;
  760. echo;
  761. git status
  762. `, true);
  763. console.log('All done cleaning.');
  764. }
  765. /*
  766. Push exactly what is here (all files) up to the sandbox (with the exclusion of files noted in .sandbox-ignore)
  767. */
  768. async function pushToSandbox() {
  769. console.log("Pushing All Themes to Sandbox.");
  770. let allThemes = await getActionableThemes();
  771. console.log(`Syncing ${allThemes.length} themes`);
  772. for (let theme of allThemes) {
  773. await pushThemeToSandbox(theme);
  774. }
  775. }
  776. async function pushThemeToSandbox(theme) {
  777. console.log(`Syncing ${theme}`);
  778. return executeCommand(`
  779. rsync -avR --no-p --no-times --delete -m --exclude-from='.sandbox-ignore' ./${theme}/ wpcom-sandbox:${sandboxPublicThemesFolder}/
  780. `, true);
  781. }
  782. /*
  783. Push only (and every) change since the point-of-diversion from /trunk
  784. Remove files from the sandbox that have been removed since the last deployed hash
  785. */
  786. async function pushChangesToSandbox() {
  787. console.log("Pushing Changed Themes to Sandbox.");
  788. let hash = await getLastDeployedHash();
  789. let changedThemes = await getChangedThemes(hash);
  790. console.log(`Syncing ${changedThemes.length} themes`);
  791. for (let theme of changedThemes) {
  792. await pushThemeToSandbox(theme);
  793. }
  794. }
  795. async function checkoutCoreTheme(theme) {
  796. if (!theme) {
  797. console.log('Must supply theme to sync and revision to start from');
  798. return;
  799. }
  800. return executeCommand(`
  801. rm -rf ./${theme}
  802. svn checkout https://wpcom-themes.svn.automattic.com/${theme} ./${theme}
  803. `);
  804. }
  805. async function pullAllThemes() {
  806. console.log("Pulling ALL themes from sandbox.");
  807. let allThemes = await getActionableThemes();
  808. for (let theme of allThemes) {
  809. try {
  810. await executeCommand(`
  811. rsync -avr --no-p --no-times --delete -m --exclude-from='.sandbox-ignore' wpcom-sandbox:${sandboxPublicThemesFolder}/${theme}/ ./${theme}/
  812. `, true);
  813. }
  814. catch (err) {
  815. console.log('Error pulling:', err);
  816. }
  817. }
  818. }
  819. async function pullCoreThemes() {
  820. console.log("Pulling CORE themes from sandbox.");
  821. for (let theme of coreThemes) {
  822. await executeCommand(`
  823. rsync -avr --no-p --no-times --delete -m --exclude-from='.sandbox-ignore' wpcom-sandbox:${sandboxPublicThemesFolder}/${theme}/ ./${theme}/
  824. `, true);
  825. }
  826. }
  827. async function pushCoreThemes() {
  828. console.log("Pushing CORE themes to sandbox.");
  829. for (let theme of coreThemes) {
  830. await executeCommand(`
  831. rsync -avr --no-p --no-times --delete -m --exclude-from='.sandbox-ignore' ./${theme}/ wpcom-sandbox:${sandboxPublicThemesFolder}/${theme}/
  832. `, true);
  833. }
  834. }
  835. async function syncCoreTheme(theme, sinceRevision) {
  836. if (!theme) {
  837. console.log('Must supply theme to sync and revision to start from');
  838. return;
  839. }
  840. if (!sinceRevision) {
  841. sinceRevision = await executeCommand(`cat ./${theme}/.pub-svn-revision`);
  842. }
  843. let latestRevision = await executeCommand(`svn info -r HEAD https://develop.svn.wordpress.org/trunk | grep Revision | egrep -o "[0-9]+"`);
  844. console.log(`syncing core theme ${theme} from ${sinceRevision} to ${latestRevision}`);
  845. try {
  846. await executeCommand(`
  847. svn merge --accept postpone http://develop.svn.wordpress.org/trunk/src/wp-content/themes/${theme} ./${theme} -r${sinceRevision}:HEAD
  848. echo '${latestRevision}' > ./${theme}/.pub-svn-revision
  849. `, true);
  850. }
  851. catch (err) {
  852. console.log('Error merging:', err);
  853. }
  854. return latestRevision;
  855. }
  856. /*
  857. Build the GitHub commit message.
  858. This message contains the logs from all of the commits since the given hash.
  859. Used by create*GithubPR
  860. */
  861. async function buildGithubCommitMessageSince(hash) {
  862. let projectVersion = await executeCommand(`node -p "require('./package.json').version"`);
  863. let logs = await getCommitLogs(hash);
  864. return `Deploy Themes ${projectVersion} to wpcom
  865. Summary:
  866. ${logs}
  867. Test Plan: Execute Smoke Test
  868. `;
  869. }
  870. /*
  871. Create a GitHub pull request with the given message based on the contents currently in the sandbox.
  872. Open the GitHub pull request in your browser.
  873. Provide the URL of the GitHub pull request.
  874. */
  875. async function createGithubPR(commitMessage) {
  876. console.log('Creating GitHub Pull Request');
  877. let result = await executeOnSandbox(`
  878. cd ${sandboxPublicThemesFolder};
  879. git branch -D deploy
  880. git checkout -b deploy
  881. git add --all
  882. git commit -m "${commitMessage}"
  883. git push origin deploy
  884. gh pr create --fill --head deploy
  885. `, true);
  886. let githubUrl = getGithubUrlFromResponse(result);
  887. console.log('PR Created at: ', githubUrl);
  888. if (githubUrl) {
  889. open(githubUrl);
  890. }
  891. return githubUrl;
  892. }
  893. /*
  894. Utility to pull the GitHub URL from the PR creation command.
  895. Used by createGithubPR
  896. */
  897. function getGithubUrlFromResponse(response) {
  898. return response
  899. ?.split('\n')
  900. ?.filter(item => item.includes('http')) // filter out lines that include 'http'
  901. ?.pop(); // get the last URL
  902. }
  903. /*
  904. Create a git tag at the current hash.
  905. In the description include the commit logs since the given hash.
  906. Include the (cleansed) GitHub PR link.
  907. */
  908. async function tagDeployment(options = {}) {
  909. console.log('tagging deployment');
  910. let hash = options.hash || await getLastDeployedHash();
  911. let workInTheOpenGithubUrl = '';
  912. if (options.prId) {
  913. workInTheOpenGithubUrl = `GitHub: ${options.prId}`;
  914. }
  915. let projectVersion = await executeCommand(`node -p "require('./package.json').version"`);
  916. let logs = await getCommitLogs(hash);
  917. let tag = `v${projectVersion}`;
  918. let message = `Deploy Themes ${tag} to wpcom. \n\n${logs} \n\n${workInTheOpenGithubUrl}`;
  919. await executeCommand(`
  920. git tag -a ${tag} -m "${message}"
  921. git push origin ${tag}
  922. `, true);
  923. }
  924. async function createGlotPressProject(changedThemes) {
  925. for (const themeSlug of changedThemes) {
  926. let styleCss = fs.readFileSync(`${themeSlug}/style.css`, 'utf8');
  927. let themeVersion = getThemeMetadata(styleCss, 'Version');
  928. // Check if theme version is correctly formatted. Temporarily coerce the value to a parseable semver version if it's not.
  929. if (!semver.valid(themeVersion)) {
  930. console.log(`\n[WARN] Invalid version in style.css for ${themeSlug}: ${themeVersion}\n`);
  931. themeVersion = semver.coerce(themeVersion);
  932. }
  933. if (semver.gte(themeVersion, '1.0.0')) {
  934. console.log(`\nCreating GlotPress project for ${themeSlug}\n`);
  935. await executeOnSandbox(`
  936. cd ${sandboxPublicThemesFolder};
  937. php ${glotPressScript} ${sandboxPublicThemesFolder}/${themeSlug};
  938. `, true);
  939. } else {
  940. console.log(`\nSkipped GlotPress project creation for ${themeSlug}.\nVersion bump to a major release to create GlotPress project.\n`);
  941. }
  942. }
  943. }
  944. /*
  945. Execute a command on the sandbox.
  946. Expects the following to be configured in your ~/.ssh/config file:
  947. Host wpcom-sandbox
  948. User wpdev
  949. HostName SANDBOXURL.wordpress.com
  950. ForwardAgent yes
  951. */
  952. function executeOnSandbox(command, logResponse, enablePsudoterminal) {
  953. if (enablePsudoterminal) {
  954. return executeCommand(`ssh -tt -A ${remoteSSH} << EOF
  955. ${command}
  956. EOF`, logResponse);
  957. }
  958. return executeCommand(`ssh -TA ${remoteSSH} << EOF
  959. ${command}
  960. EOF`, logResponse);
  961. }
  962. /*
  963. Execute a command locally.
  964. */
  965. export async function executeCommand(command, logResponse) {
  966. const timeout = 2*60*1000; // 2 min
  967. return new Promise((resolove, reject) => {
  968. let child;
  969. let response = '';
  970. let errResponse = '';
  971. if (isWin) {
  972. child = spawn('cmd.exe', ['/s', '/c', '"' + command + '"'], {
  973. windowsVerbatimArguments: true,
  974. stdio: [process.stdin, 'pipe', 'pipe'],
  975. detached: true,
  976. })
  977. } else {
  978. /*
  979. * Determines the shell to execute the command.
  980. * - Prioritizes using the user's default shell unless it's fish, a known problematic shell.
  981. * - In this case, falls back to `/bin/bash` for better syntax compatibility.
  982. */
  983. let shellPath = process.env.SHELL || '/bin/bash';
  984. if (shellPath.includes('fish') && fs.existsSync('/bin/bash')) {
  985. shellPath = '/bin/bash';
  986. }
  987. child = spawn(shellPath, ['-c', command], {
  988. stdio: [process.stdin, 'pipe', 'pipe'],
  989. detached: true,
  990. });
  991. }
  992. var timer = setTimeout(() => {
  993. try {
  994. process.kill(-child.pid, 'SIGKILL');
  995. } catch (e) {
  996. console.log('Cannot kill process');
  997. }
  998. }, timeout);
  999. child.stdout.on('data', (data) => {
  1000. response += data;
  1001. if (logResponse) {
  1002. console.log(data.toString());
  1003. }
  1004. });
  1005. child.stderr.on('data', (data) => {
  1006. errResponse += data;
  1007. if (logResponse) {
  1008. console.log(data.toString());
  1009. }
  1010. });
  1011. child.on('exit', (code) => {
  1012. clearTimeout(timer)
  1013. if (code !== 0) {
  1014. reject(errResponse.trim());
  1015. }
  1016. resolove(response.trim());
  1017. });
  1018. });
  1019. }
  1020. async function escapePatterns() {
  1021. // get staged files
  1022. const staged = (await executeCommand(`git diff --cached --name-only`)).split('\n');
  1023. // get unstaged, untracked files
  1024. const unstaged = (await executeCommand(`git ls-files -m -o --exclude-standard`)).split('\n');
  1025. // avoid duplicates and filter pattern files
  1026. const patterns = [...new Set([...staged, ...unstaged])].filter(file => file.match(/.*\/patterns\/.*.php/g));
  1027. // arrange patterns by theme
  1028. const themePatterns = patterns.reduce((acc, file) => {
  1029. const themeSlug = file.split('/').shift();
  1030. return {
  1031. ...acc,
  1032. [themeSlug]: (acc[themeSlug] || []).concat(file)
  1033. };
  1034. }, {});
  1035. Object.entries(themePatterns).forEach(async ([themeSlug, patterns]) => {
  1036. console.log(getPatternTable(themeSlug, patterns));
  1037. const prompt = await inquirer.prompt([{
  1038. type: 'input',
  1039. message: 'Verify the theme slug',
  1040. name: "themeSlug",
  1041. default: themeSlug
  1042. }]);
  1043. if (!prompt.themeSlug) {
  1044. return;
  1045. }
  1046. patterns.forEach(file => {
  1047. const rewriter = getReWriter(prompt.themeSlug);
  1048. const tmpFile = `${file}-tmp`;
  1049. const readStream = fs.createReadStream( file, { encoding: 'UTF-8' } );
  1050. const writeStream = fs.createWriteStream( tmpFile, { encoding: 'UTF-8' } );
  1051. writeStream.on('finish', () => {
  1052. fs.renameSync(tmpFile, file);
  1053. });
  1054. readStream.pipe(rewriter).pipe(writeStream);
  1055. });
  1056. });
  1057. // Helper functions
  1058. function getReWriter(themeSlug) {
  1059. const rewriter = new RewritingStream();
  1060. rewriter.on('text', (_, raw) => {
  1061. rewriter.emitRaw(escapeText(raw, themeSlug));
  1062. });
  1063. rewriter.on('startTag', (startTag, rawHtml) => {
  1064. if (startTag.tagName === 'img') {
  1065. const attrs = startTag.attrs.filter(attr => ['src', 'alt'].includes(attr.name));
  1066. attrs.forEach(attr => {
  1067. if (attr.name === 'src') {
  1068. attr.value = escapeImagePath(attr.value);
  1069. } else if (attr.name === 'alt') {
  1070. attr.value = escapeText(attr.value, themeSlug, true);
  1071. }
  1072. });
  1073. }
  1074. rewriter.emitStartTag(startTag);
  1075. });
  1076. rewriter.on('comment', (comment, rawHtml) => {
  1077. if (comment.text.startsWith('?php')) {
  1078. rewriter.emitRaw(rawHtml);
  1079. return;
  1080. }
  1081. // escape the strings in block config (blocks that are represented as comments)
  1082. // ex: <!-- wp:search {label: "Search"} /-->
  1083. const block = escapeBlockAttrs(comment.text, themeSlug)
  1084. rewriter.emitComment({...comment, text: block})
  1085. });
  1086. return rewriter;
  1087. }
  1088. function escapeBlockAttrs(block, themeSlug) {
  1089. // Set isAttr to true if it is an attribute in the result HTML
  1090. // If set to true, it generates esc_attr_, otherwise it generates esc_html_
  1091. const allowedAttrs=[
  1092. { name: 'label' },
  1093. { name: 'placeholder', isAttr: true },
  1094. { name: 'buttonText' },
  1095. { name: 'content' }
  1096. ];
  1097. const start = block.indexOf('{');
  1098. const end = block.lastIndexOf('}');
  1099. const configPrefix = block.slice(0, start);
  1100. const config = block.slice(start, end+1);
  1101. const configSuffix = block.slice(end+1);
  1102. try {
  1103. const configJson = JSON.parse(config);
  1104. allowedAttrs.forEach((attr) => {
  1105. if (!configJson[attr.name]) return;
  1106. configJson[attr.name] = escapeText(configJson[attr.name], themeSlug, attr.isAttr)
  1107. })
  1108. return configPrefix + JSON.stringify(configJson) + configSuffix;
  1109. } catch (error) {
  1110. // do nothing
  1111. return block
  1112. }
  1113. }
  1114. function escapeText(text, themeSlug, isAttr = false) {
  1115. const trimmedText = text && text.trim();
  1116. if (!themeSlug || !trimmedText || trimmedText.startsWith(`<?php`)) return text;
  1117. const escFunction = isAttr ? 'esc_attr__' : 'esc_html__';
  1118. const spaceChar = text.startsWith(' ') ? '&nbsp;' : ''
  1119. const resultText = text.replace('\'', '\\\'').trim();
  1120. return `${spaceChar}<?php echo ${escFunction}( '${resultText}', '${themeSlug}' ); ?>`;
  1121. }
  1122. function escapeImagePath(src) {
  1123. if (!src || src.trim().startsWith('<?php')) return src;
  1124. const assetsDir = 'assets';
  1125. const parts = src.split('/');
  1126. const resultSrc = parts.slice(parts.indexOf(assetsDir)).join('/');
  1127. return `<?php echo esc_url( get_template_directory_uri() ); ?>/${resultSrc}`;
  1128. }
  1129. function getPatternTable(themeSlug, patterns) {
  1130. const tableConfig = {
  1131. columnDefault: {
  1132. width: 40,
  1133. },
  1134. header: {
  1135. alignment: 'center',
  1136. content: `THEME: ${themeSlug}\n\n Following patterns may get updated with escaped strings and/or image paths`,
  1137. }
  1138. };
  1139. return table(patterns.map(p => [p]), tableConfig);
  1140. }
  1141. }
  1142. function startProgress(length) {
  1143. let current = 0;
  1144. function render() {
  1145. const [progress, percentage] = progressbar.filledBar(length, current);
  1146. console.log('\nProgress:', [progress, Math.round(percentage*100)/100], `${current}/${length}\n`);
  1147. }
  1148. render();
  1149. return {
  1150. increment() {
  1151. current++;
  1152. render();
  1153. }
  1154. };
  1155. }