theme-utils.mjs 38 KB

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