theme-utils.mjs 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223
  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. let hash = await getLastDeployedHash();
  212. let thingsWentBump = await versionBumpThemes();
  213. if (thingsWentBump) {
  214. prompt = await inquirer.prompt([{
  215. type: 'confirm',
  216. message: 'Are you good with the version bump and changelog updates? 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 version bump changes.`);
  222. return;
  223. }
  224. }
  225. let changedThemes = await getChangedThemes(hash);
  226. await pushChangesToSandbox();
  227. //push changes (from version bump)
  228. if (thingsWentBump) {
  229. prompt = await inquirer.prompt([{
  230. type: 'confirm',
  231. message: 'Are you ready to push this version bump change to the source repository (Github)?',
  232. name: "continue",
  233. default: false
  234. }]);
  235. if (!prompt.continue) {
  236. console.log(`Aborted Automated Deploy Process at version bump push change.`);
  237. return;
  238. }
  239. await executeCommand(`
  240. git commit -m "Version Bump";
  241. git push
  242. `, true);
  243. }
  244. await updateLastDeployedHash();
  245. let commitMessage = await buildPhabricatorCommitMessageSince(hash);
  246. let diffUrl = await createPhabricatorDiff(commitMessage);
  247. let diffId = diffUrl.split('a8c.com/')[1];
  248. await tagDeployment({
  249. hash: hash,
  250. diffId: diffId
  251. });
  252. 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`);
  253. prompt = await inquirer.prompt([{
  254. type: 'confirm',
  255. message: 'Are you ready to land these changes?',
  256. name: "continue",
  257. default: false
  258. }]);
  259. if (!prompt.continue) {
  260. 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}`);
  261. return;
  262. }
  263. await landChanges(diffId);
  264. let changedPublicThemes = changedThemes.filter(item => !premiumThemes.includes(item));
  265. try {
  266. await deployThemes(changedPublicThemes);
  267. }
  268. catch (err) {
  269. prompt = await inquirer.prompt([{
  270. type: 'confirm',
  271. message: `There was an error deploying themes. ${err} Do you wish to continue to the next step?`,
  272. name: "continue",
  273. default: false
  274. }]);
  275. if (!prompt.continue) {
  276. console.log(`Aborted Automated Deploy during deploy phase.`);
  277. return;
  278. }
  279. }
  280. await buildComZips(changedPublicThemes);
  281. console.log(`The following themes have changed:\n${changedThemes.join('\n')}`)
  282. console.log('\n\nAll Done!!\n\n');
  283. }
  284. catch (err) {
  285. console.log("ERROR with deploy script: ", err);
  286. }
  287. }
  288. async function deploySyncCoreTheme(theme, sinceRevision) {
  289. await cleanSandbox();
  290. let latestRevision = await syncCoreTheme(theme, sinceRevision);
  291. let prompt = await inquirer.prompt([{
  292. type: 'confirm',
  293. message: `Changes have been synced to your sandbox. Please resolve any conflicts (noted in .rej files). Are you ready to continue?`,
  294. name: "continue",
  295. default: false
  296. }]);
  297. if (!prompt.continue) {
  298. console.log(`Aborted Core Sync Deploy.`);
  299. return;
  300. }
  301. let logs = await executeCommand(`svn log https://core.svn.wordpress.org/trunk/wp-content/themes/${theme} -r${sinceRevision}:HEAD`)
  302. let commitMessage = `${theme}: Merge latest core changes up to [wp${latestRevision}]
  303. Summary:
  304. ${logs}
  305. Test Plan: Activate ${theme} and ensure nothing is broken
  306. Reviewers:
  307. #themes_team
  308. Subscribers:
  309. `;
  310. let diffUrl = await createPhabricatorDiff(commitMessage);
  311. let diffId = diffUrl.split('a8c.com/')[1];
  312. prompt = await inquirer.prompt([{
  313. type: 'confirm',
  314. message: 'Are you ready to land these changes?',
  315. name: "continue",
  316. default: false
  317. }]);
  318. if (!prompt.continue) {
  319. 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}`);
  320. return;
  321. }
  322. return;
  323. // await landChanges(diffId);
  324. // await deployThemes([theme]);
  325. // await buildComZips([theme]);
  326. }
  327. /*
  328. Build .zip file for .com
  329. */
  330. async function buildComZip(themeSlug) {
  331. console.log(`Building ${themeSlug} .zip`);
  332. let styleCss = fs.readFileSync(`${themeSlug}/style.css`, 'utf8');
  333. // Gets the theme version (Version:) and minimum WP version (Tested up to:) from the theme's style.css
  334. let themeVersion = getThemeMetadata(styleCss, 'Version');
  335. let wpVersionCompat = getThemeMetadata(styleCss, 'Requires at least');
  336. if (themeVersion && wpVersionCompat) {
  337. await executeOnSandbox(`php ${sandboxRootFolder}bin/themes/theme-downloads/build-theme-zip.php --stylesheet=pub/${themeSlug} --themeversion=${themeVersion} --wpversioncompat=${wpVersionCompat};`, true);
  338. }
  339. else {
  340. console.log('Unable to build theme .zip.');
  341. if (!themeVersion) {
  342. console.log('Could not find theme version (Version:) in the theme style.css.');
  343. }
  344. if (!wpVersionCompat) {
  345. console.log('Could not find WP compat version (Tested up to:) in the theme style.css.');
  346. }
  347. console.log('Please build the .zip file for the theme manually.', themeSlug);
  348. open('https://mc.a8c.com/themes/downloads/');
  349. }
  350. }
  351. async function buildComZips(themes) {
  352. for (let theme of themes) {
  353. try {
  354. await buildComZip(theme);
  355. } catch (err) {
  356. console.log(`There was an error building dotcom zip for ${theme}. ${err}`);
  357. }
  358. }
  359. }
  360. /*
  361. Check to ensure that:
  362. * The current branch is /trunk
  363. * That trunk is up-to-date with origin/trunk
  364. */
  365. async function checkForDeployability() {
  366. let branchName = await executeCommand('git symbolic-ref --short HEAD');
  367. if (branchName !== 'trunk') {
  368. return 'Only the /trunk branch can be deployed.';
  369. }
  370. await executeCommand('git remote update', true);
  371. let localMasterHash = await executeCommand('git rev-parse trunk')
  372. let remoteMasterHash = await executeCommand('git rev-parse origin/trunk')
  373. if (localMasterHash !== remoteMasterHash) {
  374. return 'Local /trunk is out-of-date. Pull changes to continue.'
  375. }
  376. return null;
  377. }
  378. /*
  379. Land the changes from the given diff ID. This is the "production merge".
  380. */
  381. async function landChanges(diffId) {
  382. return executeCommand(`ssh -tt -A ${remoteSSH} "cd ${sandboxPublicThemesFolder}; /usr/local/bin/arc patch ${diffId}; /usr/local/bin/arc land; exit;"`, true);
  383. }
  384. async function getChangedThemes(hash) {
  385. console.log('Determining all changed themes');
  386. let themes = await getActionableThemes();
  387. let changedThemes = [];
  388. for (let theme of themes) {
  389. let hasChanges = await checkThemeForChanges(theme, hash);
  390. if (hasChanges) {
  391. changedThemes.push(theme);
  392. }
  393. }
  394. return changedThemes;
  395. }
  396. /*
  397. Deploy a collection of themes.
  398. Part of the push-button-deploy process.
  399. Can also be triggered to deploy a single theme with the command:
  400. node ./theme-utils.mjs deploy-theme THEMENAME
  401. */
  402. async function deployThemes(themes) {
  403. let response;
  404. for (let theme of themes) {
  405. console.log(`Deploying ${theme}`);
  406. let deploySuccess = false;
  407. let attempt = 0;
  408. while (!deploySuccess && attempt <= 2) {
  409. attempt++;
  410. console.log(`\nattempt #${attempt}\n\n`);
  411. response = await executeOnSandbox(`deploy pub ${theme};exit;`, true, true);
  412. deploySuccess = response.includes('successfully deployed to');
  413. if (!deploySuccess) {
  414. console.log('Deploy was not successful. Trying again in 10 seconds...');
  415. await new Promise(resolve => setTimeout(resolve, 10000));
  416. }
  417. else {
  418. console.log("Deploy successful.");
  419. }
  420. }
  421. if (!deploySuccess) {
  422. await inquirer.prompt([{
  423. type: 'confirm',
  424. message: `${theme} was not sucessfully deployed and should be deployed manually.`,
  425. name: "continue",
  426. default: false
  427. }]);
  428. }
  429. }
  430. }
  431. /*
  432. Provide the hash of the last managed deployment.
  433. This hash is used to determine all the changes that have happened between that point and the current point.
  434. */
  435. async function getLastDeployedHash() {
  436. let result = await executeOnSandbox(`
  437. cat ${sandboxPublicThemesFolder}/.pub-git-hash
  438. `);
  439. return result;
  440. }
  441. /*
  442. Update the 'last deployed hash' on the server with the current hash.
  443. */
  444. async function updateLastDeployedHash() {
  445. let hash = await executeCommand(`git rev-parse HEAD`);
  446. await executeOnSandbox(`
  447. echo '${hash}' > ${sandboxPublicThemesFolder}/.pub-git-hash
  448. `);
  449. }
  450. /*
  451. Version bump (increment version patch) any theme project that has had changes since the last deployment.
  452. If a theme's version has already been changed since that last deployment then do not version bump it.
  453. If any theme projects have had a version bump also version bump the parent project.
  454. If a theme has changes also update its changelog.
  455. Commit the change.
  456. */
  457. async function versionBumpThemes() {
  458. console.log("Version Bumping");
  459. let themes = await getActionableThemes();
  460. let hash = await getLastDeployedHash();
  461. let changesWereMade = false;
  462. let versionBumpCount = 0;
  463. for (let theme of themes) {
  464. let hasChanges = await checkThemeForChanges(theme, hash);
  465. if (!hasChanges) {
  466. // console.log(`${theme} has no changes`);
  467. continue;
  468. }
  469. versionBumpCount++;
  470. let hasVersionBump = await checkThemeForVersionBump(theme, hash);
  471. if (hasVersionBump) {
  472. continue;
  473. }
  474. await versionBumpTheme(theme, true);
  475. await updateThemeChangelog(theme, true);
  476. changesWereMade = true;
  477. }
  478. //version bump the root project if there were changes to any of the themes
  479. let rootHasVersionBump = await checkProjectForVersionBump(hash);
  480. if (versionBumpCount > 0 && !rootHasVersionBump) {
  481. await executeCommand(`npm version patch --no-git-tag-version && git add package.json package-lock.json`);
  482. changesWereMade = true;
  483. }
  484. return changesWereMade;
  485. }
  486. export function getThemeMetadata(styleCss, attribute) {
  487. if (!styleCss || !attribute) {
  488. return null;
  489. }
  490. switch (attribute) {
  491. case 'Version':
  492. return styleCss
  493. .match(/(?<=Version:\s*).*?(?=\s*\r?\n|\rg)/gs)[0]
  494. .trim()
  495. .replace('-wpcom', '');
  496. case 'Requires at least':
  497. return styleCss
  498. .match(/(?<=Requires at least:\s*).*?(?=\s*\r?\n|\rg)/gs);
  499. }
  500. }
  501. /* Rebuild theme changelog from a given starting hash */
  502. async function rebuildThemeChangelog(theme, since) {
  503. console.log(`Rebuilding ${theme} changelog since ${since || 'forever'}`);
  504. if (since) {
  505. since = `${since}..HEAD`;
  506. } else {
  507. since = 'HEAD';
  508. }
  509. let hashes = await executeCommand(`git rev-list ${since} -- ./${theme}`);
  510. hashes = hashes.split('\n');
  511. let logs = '== Changelog ==\n';
  512. for (let hash of hashes) {
  513. let log = await executeCommand(`git log -n 1 --pretty=format:"* %s" ${hash}`);
  514. if (log.includes('Version Bump')) {
  515. let previousStyleString = await executeCommand(`git show ${hash}:${theme}/style.css 2>/dev/null`);
  516. let version = getThemeMetadata(previousStyleString, 'Version');
  517. logs += `\n= ${version} =\n`;
  518. } else {
  519. // Remove any double quotes from commit messages
  520. log = log.replace(/"/g, '');
  521. logs += log + '\n';
  522. }
  523. }
  524. // Get theme readme.txt
  525. let readmeFilePath = `${theme}/readme.txt`;
  526. // Update readme.txt
  527. fs.readFile(readmeFilePath, 'utf8', function (err, data) {
  528. let changelogSection = '== Changelog ==';
  529. let regex = new RegExp('^.*' + changelogSection + '.*$', 'gm');
  530. let formattedChangelog = data.replace(regex, logs);
  531. fs.writeFile(readmeFilePath, formattedChangelog, 'utf8', function (err) {
  532. if (err) return console.log(err);
  533. });
  534. });
  535. }
  536. /*
  537. Update theme changelog using current commit logs.
  538. Used by versionBumpThemes to update each theme changelog.
  539. */
  540. async function updateThemeChangelog(theme, addChanges) {
  541. console.log(`Updating ${theme} changelog`);
  542. // Get theme version
  543. let styleCss = fs.readFileSync(`${theme}/style.css`, 'utf8');
  544. let version = getThemeMetadata(styleCss, 'Version');
  545. // Get list of updates with bullet points
  546. let logs = await getCommitLogs('', true, theme);
  547. // Get theme readme.txt
  548. let readmeFilePath = `${theme}/readme.txt`;
  549. if (!existsSync(readmeFilePath)) {
  550. console.log(`Unable to find a readme.txt for ${theme}.`);
  551. return;
  552. }
  553. // Build changelog entry
  554. let newChangelogEntry = `== Changelog ==
  555. = ${version} =
  556. ${logs}`;
  557. // Update readme.txt
  558. fs.readFile(readmeFilePath, 'utf8', function (err, data) {
  559. let changelogSection = '== Changelog ==';
  560. let regex = new RegExp('^.*' + changelogSection + '.*$', 'gm');
  561. let formattedChangelog = data.replace(regex, newChangelogEntry);
  562. fs.writeFile(readmeFilePath, formattedChangelog, 'utf8', function (err) {
  563. if (err) return console.log(err);
  564. });
  565. });
  566. // Stage readme.txt
  567. if (addChanges) {
  568. await executeCommand(`git add ${readmeFilePath}`);
  569. }
  570. }
  571. /*
  572. Version Bump a Theme.
  573. Used by versionBumpThemes to do the work of version bumping.
  574. First increment the patch version in style.css
  575. Then update any of these files with the new version: [package.json, style.scss, style-child-theme.scss]
  576. */
  577. async function versionBumpTheme(theme, addChanges) {
  578. console.log(`${theme} needs a version bump`);
  579. await executeCommand(`perl -pi -e 's/Version: ((\\d+\\.)*)(\\d+)(.*)$/"Version: ".$1.($3+1).$4/ge' ${theme}/style.css`, true);
  580. await executeCommand(`git add ${theme}/style.css`);
  581. let styleCss = fs.readFileSync(`${theme}/style.css`, 'utf8');
  582. let currentVersion = getThemeMetadata(styleCss, 'Version');
  583. let filesToUpdate = await executeCommand(`find ${theme} -not \\( -path "*/node_modules/*" -prune \\) -and \\( -name package.json -or -name style.scss -or -name style-child-theme.scss \\) -maxdepth 3`);
  584. filesToUpdate = filesToUpdate.split('\n').filter(item => item != '');
  585. for (let file of filesToUpdate) {
  586. await executeCommand(`perl -pi -e 's/Version: (.*)$/"Version: '${currentVersion}'"/ge' ${file}`);
  587. await executeCommand(`perl -pi -e 's/\\"version\\": (.*)$/"\\"version\\": \\"'${currentVersion}'\\","/ge' ${file}`);
  588. if (addChanges) {
  589. await executeCommand(`git add ${file}`);
  590. }
  591. }
  592. }
  593. /*
  594. Determine if a theme has had a version bump since a given hash.
  595. Used by versionBumpThemes
  596. Compares the value of 'version' in style.css between the hash and current value
  597. */
  598. async function checkThemeForVersionBump(theme, hash) {
  599. return executeCommand(`
  600. git show ${hash}:${theme}/style.css 2>/dev/null
  601. `)
  602. .catch((error) => {
  603. //This is a new theme, no need to bump versions so we'll just say we've already done it
  604. return true;
  605. })
  606. .then((previousStyleString) => {
  607. if (previousStyleString === true) {
  608. return previousStyleString;
  609. }
  610. let previousVersion = getThemeMetadata(previousStyleString, 'Version');
  611. let styleCss = fs.readFileSync(`${theme}/style.css`, 'utf8');
  612. let currentVersion = getThemeMetadata(styleCss, 'Version');
  613. return previousVersion != currentVersion;
  614. });
  615. }
  616. /*
  617. Determine if the project has had a version bump since a given hash.
  618. Used by versionBumpThemes
  619. Compares the value of 'version' in package.json between the hash and current value
  620. */
  621. async function checkProjectForVersionBump(hash) {
  622. let previousPackageString = await executeCommand(`
  623. git show ${hash}:./package.json 2>/dev/null
  624. `);
  625. let previousPackage = JSON.parse(previousPackageString);
  626. let currentPackage = JSON.parse(fs.readFileSync(`./package.json`))
  627. return previousPackage.version != currentPackage.version;
  628. }
  629. /*
  630. Determine if a theme has had changes since a given hash.
  631. Used by versionBumpThemes
  632. */
  633. async function checkThemeForChanges(theme, hash) {
  634. let comittedChanges = await executeCommand(`git diff --name-only ${hash} HEAD -- ${theme}`);
  635. return comittedChanges != '';
  636. }
  637. /*
  638. Provide a list of 'actionable' themes (those themes that have style.css files)
  639. */
  640. async function getActionableThemes() {
  641. let result = await executeCommand(`for d in */; do
  642. if test -f "./$d/style.css"; then
  643. echo $d;
  644. fi
  645. done`);
  646. return result
  647. .split('\n')
  648. .map(item => item.replace('/', ''));
  649. }
  650. /*
  651. Clean the theme sandbox.
  652. checkout origin/trunk and ensure it's up-to-date.
  653. Remove any other changes.
  654. */
  655. async function cleanSandbox() {
  656. console.log('Cleaning the Themes Sandbox');
  657. await executeOnSandbox(`
  658. cd ${sandboxPublicThemesFolder};
  659. git reset --hard HEAD;
  660. git clean -fd;
  661. git checkout trunk;
  662. git pull;
  663. echo;
  664. git status
  665. `, true);
  666. console.log('All done cleaning.');
  667. }
  668. /*
  669. Clean the premium theme sandbox.
  670. checkout origin/trunk and ensure it's up-to-date.
  671. Remove any other changes.
  672. */
  673. async function cleanPremiumSandbox() {
  674. console.log('Cleaning the Themes Sandbox');
  675. await executeOnSandbox(`
  676. cd ${sandboxPremiumThemesFolder};
  677. git reset --hard HEAD;
  678. git clean -fd;
  679. git checkout trunk;
  680. git pull;
  681. echo;
  682. git status
  683. `, true);
  684. console.log('All done cleaning.');
  685. }
  686. /*
  687. Clean the entire sandbox.
  688. checkout origin/trunk and ensure it's up-to-date.
  689. Remove any other changes.
  690. */
  691. async function cleanAllSandbox() {
  692. console.log('Cleaning the Entire Sandbox');
  693. let response = await executeOnSandbox(`
  694. cd ${sandboxRootFolder};
  695. git reset --hard HEAD;
  696. git clean -fd;
  697. git checkout trunk;
  698. git pull;
  699. echo;
  700. git status
  701. `, true);
  702. console.log('All done cleaning.');
  703. }
  704. /*
  705. Push exactly what is here (all files) up to the sandbox (with the exclusion of files noted in .sandbox-ignore)
  706. */
  707. async function pushToSandbox() {
  708. console.log("Pushing All Themes to Sandbox.");
  709. let allThemes = await getActionableThemes();
  710. allThemes = allThemes.filter(item => !premiumThemes.includes(item));
  711. console.log(`Syncing ${allThemes.length} themes`);
  712. for (let theme of allThemes) {
  713. await pushThemeToSandbox(theme);
  714. }
  715. }
  716. async function pushThemeToSandbox(theme) {
  717. console.log(`Syncing ${theme}`);
  718. return executeCommand(`
  719. rsync -avR --no-p --no-times --delete -m --exclude-from='.sandbox-ignore' ./${theme}/ wpcom-sandbox:${sandboxPublicThemesFolder}/
  720. `, true);
  721. }
  722. /*
  723. Push exactly what is here (all files) up to the sandbox (with the exclusion of files noted in .sandbox-ignore)
  724. This pushes only the folders noted as "premiumThemes" into the premium themes directory.
  725. This is the only part of the deploy process that is automated; the rest must be done manually including:
  726. * Creating a Phabricator Diff
  727. * Landing (comitting) the change
  728. * Deploying the theme
  729. * Triggering the .zip builds
  730. */
  731. async function pushPremiumToSandbox() {
  732. //TODO: It would be nice to determine this list programatically
  733. const filesToModify = [
  734. 'style.css',
  735. 'block-templates/404.html',
  736. 'block-template-parts/header.html',
  737. 'block-template-parts/footer.html'
  738. ];
  739. // Change 'blockbase' to 'blockbase-premium' in the files noted
  740. for (let theme of premiumThemes) {
  741. for (let file of filesToModify) {
  742. await executeCommand(`perl -pi -e 's/blockbase/blockbase-premium/' ${theme}/${file}`, true);
  743. }
  744. }
  745. // Push the changes in the premium themes to the sandbox
  746. await executeCommand(`
  747. rsync -avR --no-p --no-times --delete -m --exclude-from='.sandbox-ignore' --exclude='sass' ./${premiumThemes.join(' ./')} wpcom-sandbox:${sandboxPremiumThemesFolder}/
  748. `, true);
  749. // revert the local blockbase-premium changes
  750. for (let theme of premiumThemes) {
  751. for (let file of filesToModify) {
  752. await executeCommand(`
  753. git restore --source=HEAD --staged --worktree ./${theme}/${file}
  754. `);
  755. }
  756. }
  757. }
  758. /*
  759. Push only (and every) change since the point-of-diversion from /trunk
  760. Remove files from the sandbox that have been removed since the last deployed hash
  761. */
  762. async function pushChangesToSandbox() {
  763. console.log("Pushing Changed Themes to Sandbox.");
  764. let hash = await getLastDeployedHash();
  765. let changedThemes = await getChangedThemes(hash);
  766. changedThemes = changedThemes.filter(item => !premiumThemes.includes(item));
  767. console.log(`Syncing ${changedThemes.length} themes`);
  768. for (let theme of changedThemes) {
  769. await pushThemeToSandbox(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 executeOnSandbox(`cat ${sandboxPublicThemesFolder}/${theme}/.pub-svn-revision`);
  795. }
  796. let latestRevision = await executeCommand(`svn info -r HEAD https://core.svn.wordpress.org/trunk | grep Revision | egrep -o "[0-9]+"`);
  797. console.log(`syncing core theme ${theme} from ${sinceRevision} to ${latestRevision} on your sandbox`);
  798. try {
  799. await executeOnSandbox(`
  800. cd ${sandboxPublicThemesFolder};
  801. /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} -
  802. `, true);
  803. }
  804. catch (err) {
  805. console.log('Error merging:', err);
  806. }
  807. await executeOnSandbox(`
  808. echo '${latestRevision}' > ${sandboxPublicThemesFolder}/${theme}/.pub-svn-revision
  809. `);
  810. return latestRevision;
  811. }
  812. /*
  813. Build the Phabricator commit message.
  814. This message contains the logs from all of the commits since the given hash.
  815. Used by create*PhabricatorDiff
  816. */
  817. async function buildPhabricatorCommitMessageSince(hash) {
  818. let projectVersion = await executeCommand(`node -p "require('./package.json').version"`);
  819. let logs = await getCommitLogs(hash);
  820. return `Deploy Themes ${projectVersion} to wpcom
  821. Summary:
  822. ${logs}
  823. Test Plan: Execute Smoke Test
  824. Reviewers:
  825. Subscribers:
  826. `;
  827. }
  828. /*
  829. Create a Phabricator diff with the given message based on the contents currently in the sandbox.
  830. Open the phabricator diff in your browser.
  831. Provide the URL of the phabricator diff.
  832. */
  833. async function createPhabricatorDiff(commitMessage) {
  834. console.log('creating Phabricator Diff');
  835. let result = await executeOnSandbox(`
  836. cd ${sandboxPublicThemesFolder};
  837. git branch -D deploy
  838. git checkout -b deploy
  839. git add --all
  840. git commit -m "${commitMessage}"
  841. arc diff --create --verbatim
  842. `, true);
  843. let phabricatorUrl = getPhabricatorUrlFromResponse(result);
  844. console.log('Diff Created at: ', phabricatorUrl);
  845. if (phabricatorUrl) {
  846. open(phabricatorUrl);
  847. }
  848. return phabricatorUrl;
  849. }
  850. /*
  851. Utility to pull the Phabricator URL from the diff creation command.
  852. Used by createPhabricatorDiff
  853. */
  854. function getPhabricatorUrlFromResponse(response) {
  855. return response
  856. ?.split('\n')
  857. ?.find(item => {
  858. return item.includes('Revision URI: ');
  859. })
  860. ?.split("Revision URI: ")[1];
  861. }
  862. /*
  863. Create a git tag at the current hash.
  864. In the description include the commit logs since the given hash.
  865. Include the (cleansed) Phabricator link.
  866. */
  867. async function tagDeployment(options = {}) {
  868. console.log('tagging deployment');
  869. let hash = options.hash || await getLastDeployedHash();
  870. let workInTheOpenPhabricatorUrl = '';
  871. if (options.diffId) {
  872. workInTheOpenPhabricatorUrl = `Phabricator: ${options.diffId}-code`;
  873. }
  874. let projectVersion = await executeCommand(`node -p "require('./package.json').version"`);
  875. let logs = await getCommitLogs(hash);
  876. let tag = `v${projectVersion}`;
  877. let message = `Deploy Themes ${tag} to wpcom. \n\n${logs} \n\n${workInTheOpenPhabricatorUrl}`;
  878. await executeCommand(`
  879. git tag -a ${tag} -m "${message}"
  880. git push origin ${tag}
  881. `, true);
  882. }
  883. /*
  884. Execute a command on the sandbox.
  885. Expects the following to be configured in your ~/.ssh/config file:
  886. Host wpcom-sandbox
  887. User wpdev
  888. HostName SANDBOXURL.wordpress.com
  889. ForwardAgent yes
  890. */
  891. function executeOnSandbox(command, logResponse, enablePsudoterminal) {
  892. if (enablePsudoterminal) {
  893. return executeCommand(`ssh -tt -A ${remoteSSH} << EOF
  894. ${command}
  895. EOF`, logResponse);
  896. }
  897. return executeCommand(`ssh -TA ${remoteSSH} << EOF
  898. ${command}
  899. EOF`, logResponse);
  900. }
  901. /*
  902. Execute a command locally.
  903. */
  904. export async function executeCommand(command, logResponse) {
  905. return new Promise((resolove, reject) => {
  906. let child;
  907. let response = '';
  908. let errResponse = '';
  909. if (isWin) {
  910. child = spawn('cmd.exe', ['/s', '/c', '"' + command + '"'], {
  911. windowsVerbatimArguments: true,
  912. stdio: [process.stdin, 'pipe', 'pipe'],
  913. })
  914. } else {
  915. child = spawn(process.env.SHELL, ['-c', command], {
  916. stdio: [process.stdin, 'pipe', 'pipe'],
  917. });
  918. }
  919. child.stdout.on('data', (data) => {
  920. response += data;
  921. if (logResponse) {
  922. console.log(data.toString());
  923. }
  924. });
  925. child.stderr.on('data', (data) => {
  926. errResponse += data;
  927. if (logResponse) {
  928. console.log(data.toString());
  929. }
  930. });
  931. child.on('exit', (code) => {
  932. if (code !== 0) {
  933. reject(errResponse.trim());
  934. }
  935. resolove(response.trim());
  936. });
  937. });
  938. }
  939. async function escapePatterns() {
  940. // get staged files
  941. const staged = (await executeCommand(`git diff --cached --name-only`)).split('\n');
  942. // get unstaged, untracked files
  943. const unstaged = (await executeCommand(`git ls-files -m -o --exclude-standard`)).split('\n');
  944. // avoid duplicates and filter pattern files
  945. const patterns = [...new Set([...staged, ...unstaged])].filter(file => file.match(/.*\/patterns\/.*.php/g));
  946. // arrange patterns by theme
  947. const themePatterns = patterns.reduce((acc, file) => {
  948. const themeSlug = file.split('/').shift();
  949. return {
  950. ...acc,
  951. [themeSlug]: (acc[themeSlug] || []).concat(file)
  952. };
  953. }, {});
  954. Object.entries(themePatterns).forEach(async ([themeSlug, patterns]) => {
  955. console.log(getPatternTable(themeSlug, patterns));
  956. const prompt = await inquirer.prompt([{
  957. type: 'input',
  958. message: 'Verify the theme slug',
  959. name: "themeSlug",
  960. default: themeSlug
  961. }]);
  962. if (!prompt.themeSlug) {
  963. return;
  964. }
  965. const rewriter = getReWriter(prompt.themeSlug);
  966. patterns.forEach(file => {
  967. const tmpFile = `${file}-tmp`;
  968. const rstream = fs.createReadStream( file, { encoding: 'UTF-8' } );
  969. const wstream = fs.createWriteStream( tmpFile, { encoding: 'UTF-8' } );
  970. wstream.on('finish', () => {
  971. fs.renameSync(tmpFile, file);
  972. });
  973. rstream.pipe(rewriter).pipe(wstream);
  974. });
  975. });
  976. // Helper functions
  977. function getReWriter(themeSlug) {
  978. const rewriter = new RewritingStream();
  979. rewriter.on('text', (_, raw) => {
  980. rewriter.emitRaw(escapeText(raw, themeSlug));
  981. });
  982. rewriter.on('startTag', (startTag, rawHtml) => {
  983. if (startTag.tagName === 'img') {
  984. const attrs = startTag.attrs.filter(attr => ['src', 'alt'].includes(attr.name));
  985. attrs.forEach(attr => {
  986. if (attr.name === 'src') {
  987. attr.value = escapeImagePath(attr.value);
  988. } else if (attr.name === 'alt') {
  989. attr.value = escapeText(attr.value, themeSlug, true);
  990. }
  991. });
  992. }
  993. if (startTag.tagName === 'p') {
  994. console.log({tag: startTag, rawHtml})
  995. }
  996. rewriter.emitStartTag(startTag);
  997. });
  998. return rewriter;
  999. }
  1000. function escapeText(text, themeSlug, isAttr = false) {
  1001. const trimmedText = text && text.trim();
  1002. if (!themeSlug || !trimmedText || trimmedText.startsWith(`<?php`)) return text;
  1003. const escFunction = isAttr ? 'esc_attr__' : 'esc_html__';
  1004. const spaceChar = text.startsWith(' ') ? '&nbsp;' : ''
  1005. const resultText = text.replace('\'', '\\\'').trim();
  1006. return `${spaceChar}<?php echo ${escFunction}( '${resultText}', '${themeSlug}' ); ?>`;
  1007. }
  1008. function escapeImagePath(src) {
  1009. if (!src || src.trim().startsWith('<?php')) return src;
  1010. const assetsDir = 'assets';
  1011. const parts = src.split('/');
  1012. const resultSrc = parts.slice(parts.indexOf(assetsDir)).join('/');
  1013. return `<?php echo esc_url( get_template_directory_uri() ); ?>/${resultSrc}`;
  1014. }
  1015. function getPatternTable(themeSlug, patterns) {
  1016. const tableConfig = {
  1017. columnDefault: {
  1018. width: 80,
  1019. },
  1020. header: {
  1021. alignment: 'center',
  1022. content: `THEME: ${themeSlug}\n\n Following patterns may get updated with escaped strings and/or image paths`,
  1023. }
  1024. };
  1025. return table([patterns], tableConfig);
  1026. }
  1027. }