theme-utils.mjs 37 KB

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