theme-utils.mjs 29 KB

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