theme-utils.mjs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. import { spawn } from 'child_process';
  2. import fs from 'fs';
  3. import open from 'open';
  4. import inquirer from 'inquirer';
  5. import replace from 'replace-in-file';
  6. const remoteSSH = 'wpcom-sandbox';
  7. const sandboxPublicThemesFolder = '/home/wpdev/public_html/wp-content/themes/pub';
  8. const sandboxRootFolder = '/home/wpdev/public_html/';
  9. const isWin = process.platform === 'win32';
  10. (async function start() {
  11. let args = process.argv.slice(2);
  12. let command = args?.[0];
  13. switch (command) {
  14. case "push-button-deploy-git": return pushButtonDeploy('git');
  15. case "push-button-deploy-svn": return pushButtonDeploy('svn');
  16. case "clean-sandbox-git": return cleanSandboxGit();
  17. case "clean-sandbox-svn": return cleanSandboxSvn();
  18. case "clean-all-sandbox-git": return cleanAllSandboxGit();
  19. case "clean-all-sandbox-svn": return cleanAllSandboxSvn();
  20. case "push-to-sandbox": return pushToSandbox();
  21. case "push-changes-to-sandbox": return pushChangesToSandbox();
  22. case "version-bump-themes": return versionBumpThemes();
  23. case "land-diff-git": return landChangesGit(args?.[1]);
  24. case "land-diff-svn": return landChangesSvn(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 "lerna-update-stylecss": return lernaUpdateStyleCss();
  29. }
  30. return showHelp();
  31. })();
  32. function showHelp(){
  33. // TODO: make this helpful
  34. console.log('Help info can go here');
  35. }
  36. /*
  37. Update version number in style.css and style-child-theme.css for each theme
  38. after version bump from conventional commits (via Lerna)
  39. */
  40. async function lernaUpdateStyleCss() {
  41. let newVersion = await executeCommand(`node -p "require('./package.json').version"`);
  42. let styleCss = fs.existsSync('./style.css') ? './style.css' : '';
  43. let styleChildThemeCss = fs.existsSync('./style-child-theme.css') ? './style-child-theme.css' : '';
  44. let files = [styleCss, styleChildThemeCss].filter(Boolean);
  45. console.log({files})
  46. await replace({
  47. files,
  48. from: /(?<=Version:\s*).*?(?=\s*\r?\n|\rg)/gs,
  49. to: ` ${newVersion}`,
  50. });
  51. }
  52. /*
  53. Determine what changes would be deployed
  54. */
  55. async function deployPreview() {
  56. console.clear();
  57. console.log('To ensure accuracy clean your sandbox before previewing. (It is not automatically done).');
  58. console.log('npm run sandbox:clean:git OR npm run sandbox:clean:svn')
  59. let message = await checkForDeployability();
  60. if (message) {
  61. console.log(`\n${message}\n\n`);
  62. }
  63. let hash = await getLastDeployedHash();
  64. console.log(`Last deployed hash: ${hash}`);
  65. let changedThemes = await getChangedThemes(hash);
  66. console.log(`The following themes have changes:\n${changedThemes}`);
  67. let logs = await executeCommand(`git log --reverse --pretty=format:%s ${hash}..HEAD`);
  68. console.log(`\n\nCommit log of changes to be deployed:\n\n${logs}\n\n`);
  69. }
  70. /*
  71. Execute the first phase of a deployment.
  72. Leverages git on the sandbox.
  73. * Gets the last deployed hash from the sandbox
  74. * Version bump all themes have have changes since the last deployment
  75. * Commit the version bump change to github
  76. * Clean the sandbox and ensure it is up-to-date
  77. * Push all changed files (including removal of deleted files) since the last deployment
  78. * Update the 'last deployed' hash on the sandbox
  79. * Create a phabricator diff based on the changes since the last deployment. The description including the commit messages since the last deployment.
  80. * Open the Phabricator Diff in your browser
  81. * Create a tag in the github repository at this point of change which includes the phabricator link in the description
  82. */
  83. async function pushButtonDeploy(repoType) {
  84. console.clear();
  85. let prompt = await inquirer.prompt([{
  86. type: 'confirm',
  87. message: 'You are about to deploy /trunk. Are you ready to continue?',
  88. name: "continue",
  89. default: false
  90. }]);
  91. if(!prompt.continue){
  92. return;
  93. }
  94. if (repoType != 'svn' && repoType != 'git' ) {
  95. return console.log('Specify a repo type to use push-button deploy');
  96. }
  97. let message = await checkForDeployability();
  98. if (message) {
  99. return console.log(`\n\n${message}\n\n`);
  100. }
  101. try {
  102. if (repoType === 'git' ) {
  103. await cleanSandboxGit();
  104. }
  105. else {
  106. await cleanSandboxSvn();
  107. }
  108. let hash = await getLastDeployedHash();
  109. let diffUrl;
  110. await versionBumpThemes();
  111. let changedThemes = await getChangedThemes(hash);
  112. await pushChangesToSandbox();
  113. await updateLastDeployedHash();
  114. if (repoType === 'git' ) {
  115. diffUrl = await createGitPhabricatorDiff(hash);
  116. }
  117. else {
  118. diffUrl = await createSvnPhabricatorDiff(hash);
  119. }
  120. let diffId = diffUrl.split('a8c.com/')[1];
  121. //push changes (from version bump)
  122. await executeCommand('git push');
  123. await tagDeployment({
  124. hash: hash,
  125. diffId: diffId
  126. });
  127. 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`);
  128. prompt = await inquirer.prompt([{
  129. type: 'confirm',
  130. message: 'Are you ready to land these changes?',
  131. name: "continue",
  132. default: false
  133. }]);
  134. if(!prompt.continue){
  135. 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}` );
  136. return;
  137. }
  138. if (repoType === 'git' ) {
  139. await landChangesGit(diffId);
  140. }
  141. else {
  142. await landChangesSvn(diffId);
  143. }
  144. await deployThemes(changedThemes);
  145. await buildComZips(changedThemes);
  146. console.log(`The following themes have changed:\n${changedThemes.join('\n')}`)
  147. console.log('\n\nAll Done!!\n\n');
  148. }
  149. catch (err) {
  150. console.log("ERROR with deply script: ", err);
  151. }
  152. }
  153. /*
  154. Build .zip file for .com
  155. */
  156. async function buildComZip(themeSlug) {
  157. console.log( `Building ${themeSlug} .zip` );
  158. let styleCss = fs.readFileSync(`${themeSlug}/style.css`, 'utf8');
  159. // Gets the theme version (Version:) and minimum WP version (Tested up to:) from the theme's style.css
  160. let themeVersion = getThemeMetadata(styleCss, 'Version');
  161. let wpVersionCompat = getThemeMetadata(styleCss, 'Tested up to');
  162. if (themeVersion && wpVersionCompat) {
  163. await executeOnSandbox(`php ${sandboxRootFolder}bin/themes/theme-downloads/build-theme-zip.php --stylesheet=pub/${themeSlug} --themeversion=${themeVersion} --wpversioncompat=${wpVersionCompat}`, true);
  164. }
  165. else {
  166. console.log('Unable to build theme .zip.');
  167. if (!themeVersion) {
  168. console.log('Could not find theme version (Version:) in the theme style.css.');
  169. }
  170. if (!wpVersionCompat) {
  171. console.log('Could not find WP compat version (Tested up to:) in the theme style.css.');
  172. }
  173. console.log('Please build the .zip file for the theme manually.', themeSlug);
  174. open('https://mc.a8c.com/themes/downloads/');
  175. }
  176. }
  177. async function buildComZips(themes) {
  178. for ( let theme of themes ) {
  179. await buildComZip(theme);
  180. }
  181. }
  182. /*
  183. Check to ensure that:
  184. * The current branch is /trunk
  185. * That trunk is up-to-date with origin/trunk
  186. */
  187. async function checkForDeployability(){
  188. let branchName = await executeCommand('git symbolic-ref --short HEAD');
  189. if(branchName !== 'trunk' ) {
  190. return 'Only the /trunk branch can be deployed.';
  191. }
  192. await executeCommand('git remote update', true);
  193. let localMasterHash = await executeCommand('git rev-parse trunk')
  194. let remoteMasterHash = await executeCommand('git rev-parse origin/trunk')
  195. if(localMasterHash !== remoteMasterHash) {
  196. return 'Local /trunk is out-of-date. Pull changes to continue.'
  197. }
  198. return null;
  199. }
  200. /*
  201. Land the changes from the given diff ID. This is the "production merge".
  202. This is the git version of that action.
  203. */
  204. async function landChangesGit(diffId){
  205. return await executeOnSandbox(`cd ${sandboxPublicThemesFolder};arc patch ${diffId};arc land;exit;`, true, true);
  206. }
  207. /*
  208. Land the changes from the given diff ID. This is the "production merge".
  209. This is the svn version of that action.
  210. */
  211. async function landChangesSvn(diffId){
  212. return await executeOnSandbox(`
  213. cd ${sandboxPublicThemesFolder};
  214. svn ci -m ${diffId}
  215. `, true );
  216. }
  217. async function getChangedThemes(hash) {
  218. console.log('Determining all changed themes');
  219. let themes = await getActionableThemes();
  220. let changedThemes = [];
  221. for (let theme of themes) {
  222. let hasChanges = await checkThemeForChanges(theme, hash);
  223. if(hasChanges){
  224. changedThemes.push(theme);
  225. }
  226. }
  227. return changedThemes;
  228. }
  229. /*
  230. Deploy a collection of themes.
  231. Part of the push-button-deploy process.
  232. Can also be triggered to deploy a single theme with the command:
  233. node ./theme-utils.mjs deploy-theme THEMENAME
  234. */
  235. async function deployThemes( themes ) {
  236. let response;
  237. for ( let theme of themes ) {
  238. console.log( `Deploying ${theme}` );
  239. let deploySuccess = false;
  240. let attempt = 0;
  241. while ( ! deploySuccess) {
  242. attempt++;
  243. console.log(`\nattempt #${attempt}\n\n`);
  244. response = await executeOnSandbox( `deploy pub ${theme};exit;`, true, true );
  245. deploySuccess = response.includes( 'successfully deployed to' );
  246. if( ! deploySuccess ) {
  247. console.log( 'Deploy was not successful. Trying again in 10 seconds...' );
  248. await new Promise(resolve => setTimeout(resolve, 10000));
  249. }
  250. else {
  251. console.log( "Deploy successful." );
  252. }
  253. }
  254. }
  255. }
  256. /*
  257. Provide the hash of the last managed deployment.
  258. This hash is used to determine all the changes that have happened between that point and the current point.
  259. */
  260. async function getLastDeployedHash() {
  261. let result = await executeOnSandbox(`
  262. cat ${sandboxPublicThemesFolder}/.pub-git-hash
  263. `);
  264. return result;
  265. }
  266. /*
  267. Update the 'last deployed hash' on the server with the current hash.
  268. */
  269. async function updateLastDeployedHash() {
  270. let hash = await executeCommand(`git rev-parse HEAD`);
  271. await executeOnSandbox(`
  272. echo '${hash}' > ${sandboxPublicThemesFolder}/.pub-git-hash
  273. `);
  274. }
  275. /*
  276. Version bump (increment version patch) any theme project that has had changes since the last deployment.
  277. If a theme's version has already been changed since that last deployment then do not version bump it.
  278. If any theme projects have had a version bump also version bump the parent project.
  279. Commit the change.
  280. */
  281. async function versionBumpThemes() {
  282. console.log("Version Bumping");
  283. let themes = await getActionableThemes();
  284. let hash = await getLastDeployedHash();
  285. let versionBumpCount = 0;
  286. for (let theme of themes) {
  287. let hasChanges = await checkThemeForChanges(theme, hash);
  288. if( ! hasChanges){
  289. // console.log(`${theme} has no changes`);
  290. continue;
  291. }
  292. versionBumpCount++;
  293. let hasVersionBump = await checkThemeForVersionBump(theme, hash);
  294. if( hasVersionBump ){
  295. continue;
  296. }
  297. await versionBumpTheme(theme);
  298. }
  299. //version bump the root project if there were changes to any of the themes
  300. let rootHasVersionBump = await checkThemeForVersionBump('.', hash);
  301. if ( versionBumpCount > 0 && ! rootHasVersionBump ) {
  302. await executeCommand(`npm version patch --no-git-tag-version`);
  303. }
  304. if (versionBumpCount > 0) {
  305. console.log('commiting version-bump');
  306. await executeCommand(`
  307. git commit -a -m "Version Bump";
  308. `, true);
  309. }
  310. }
  311. function getThemeMetadata(styleCss, attribute) {
  312. if ( !styleCss || !attribute ) {
  313. return null;
  314. }
  315. switch ( attribute ) {
  316. case 'Version':
  317. return styleCss
  318. .match(/(?<=Version:\s*).*?(?=\s*\r?\n|\rg)/gs)[0]
  319. .trim()
  320. .replace('-wpcom', '');
  321. case 'Tested up to':
  322. return styleCss
  323. .match(/(?<=Tested up to:\s*).*?(?=\s*\r?\n|\rg)/gs);
  324. }
  325. }
  326. /*
  327. Version Bump a Theme.
  328. Used by versionBumpThemes to do the work of version bumping.
  329. First increment the patch version in style.css
  330. Then update any of these files with the new version: [package.json, style.scss, style-child-theme.scss]
  331. */
  332. async function versionBumpTheme(theme){
  333. console.log(`${theme} needs a version bump`);
  334. await executeCommand(`perl -pi -e 's/Version: ((\\d+\\.)*)(\\d+)(.*)$/"Version: ".$1.($3+1).$4/ge' ${theme}/style.css`, true);
  335. let styleCss = fs.readFileSync(`${theme}/style.css`, 'utf8');
  336. let currentVersion = getThemeMetadata(styleCss, 'Version');
  337. let filesToUpdate = await executeCommand(`find ${theme} -name package.json -o -name style.scss -o -name style-child-theme.scss -maxdepth 2`);
  338. filesToUpdate = filesToUpdate.split('\n').filter(item => item != '');
  339. for ( let file of filesToUpdate ) {
  340. await executeCommand(`perl -pi -e 's/Version: (.*)$/"Version: '${currentVersion}'"/ge' ${file}`);
  341. await executeCommand(`perl -pi -e 's/\\"version\\": (.*)$/"\\"version\\": \\"'${currentVersion}'\\","/ge' ${file}`);
  342. }
  343. }
  344. /*
  345. Determine if a theme has had a version bump since a given hash.
  346. Used by versionBumpThemes
  347. Compares the value of 'version' in style.css between the hash and current value
  348. */
  349. async function checkThemeForVersionBump(theme, hash){
  350. return executeCommand(`
  351. git show ${hash}:${theme}/style.css 2>/dev/null
  352. `)
  353. .catch( ( error ) => {
  354. //This is a new theme, no need to bump versions so we'll just say we've already done it
  355. return true;
  356. } )
  357. .then( ( previousStyleString ) => {
  358. if( previousStyleString === true) {
  359. return previousStyleString;
  360. }
  361. let previousVersion = getThemeMetadata(previousStyleString, 'Version');
  362. let styleCss = fs.readFileSync(`${theme}/style.css`, 'utf8');
  363. let currentVersion = getThemeMetadata(styleCss, 'Version');
  364. return previousVersion != currentVersion;
  365. });
  366. }
  367. /*
  368. Determine if a theme has had changes since a given hash.
  369. Used by versionBumpThemes
  370. */
  371. async function checkThemeForChanges(theme, hash){
  372. let uncomittedChanges = await executeCommand(`git diff-index --name-only HEAD -- ${theme}`);
  373. let comittedChanges = await executeCommand(`git diff --name-only ${hash} HEAD -- ${theme}`);
  374. return uncomittedChanges != '' || comittedChanges != '';
  375. }
  376. /*
  377. Provide a list of 'actionable' themes (those themes that have style.css files)
  378. */
  379. async function getActionableThemes() {
  380. let result = await executeCommand(`for d in */; do
  381. if test -f "./$d/style.css"; then
  382. echo $d;
  383. fi
  384. done`);
  385. return result
  386. .split('\n')
  387. .map(item=>item.replace('/', ''));
  388. }
  389. /*
  390. Clean the theme sandbox.
  391. Assumes sandbox is in 'git' mode
  392. checkout origin/develop and ensure it's up-to-date.
  393. Remove any other changes.
  394. */
  395. async function cleanSandboxGit() {
  396. console.log('Cleaning the Themes Sandbox');
  397. await executeOnSandbox(`
  398. cd ${sandboxPublicThemesFolder};
  399. git reset --hard HEAD;
  400. git clean -fd;
  401. git checkout develop;
  402. git pull;
  403. echo;
  404. git status
  405. `, true);
  406. console.log('All done cleaning.');
  407. }
  408. /*
  409. Clean the entire sandbox.
  410. Assumes sandbox is in 'git' mode
  411. checkout origin/develop and ensure it's up-to-date.
  412. Remove any other changes.
  413. */
  414. async function cleanAllSandboxGit() {
  415. console.log('Cleaning the Entire Sandbox');
  416. let response = await executeOnSandbox(`
  417. cd ${sandboxRootFolder};
  418. git reset --hard HEAD;
  419. git clean -fd;
  420. git checkout develop;
  421. git pull;
  422. echo;
  423. git status
  424. `, true);
  425. console.log('All done cleaning.');
  426. }
  427. /*
  428. Clean the theme sandbox.
  429. Assumes sandbox is in 'svn' mode
  430. ensure trunk is up-to-date
  431. Remove any other changes
  432. */
  433. async function cleanSandboxSvn() {
  434. console.log('Cleaning the theme sandbox');
  435. await executeOnSandbox(`
  436. cd ${sandboxPublicThemesFolder};
  437. svn revert -R .;
  438. svn cleanup --remove-unversioned;
  439. svn up;
  440. `, true);
  441. console.log('All done cleaning.');
  442. }
  443. /*
  444. Clean the entire sandbox.
  445. Assumes sandbox is in 'svn' mode
  446. ensure trunk is up-to-date
  447. Remove any other changes
  448. */
  449. async function cleanAllSandboxSvn() {
  450. console.log('Cleaning the entire sandbox');
  451. await executeOnSandbox(`
  452. cd ${sandboxRootFolder};
  453. svn revert -R .;
  454. svn cleanup --remove-unversioned;
  455. svn up .;
  456. `, true);
  457. console.log('All done cleaning.');
  458. }
  459. /*
  460. Push exactly what is here (all files) up to the sandbox (with the exclusion of files noted in .sandbox-ignore)
  461. */
  462. function pushToSandbox() {
  463. executeCommand(`
  464. rsync -av --no-p --no-times --exclude-from='.sandbox-ignore' ./ wpcom-sandbox:${sandboxPublicThemesFolder}/
  465. `);
  466. }
  467. /*
  468. Push only (and every) change since the point-of-diversion from /trunk
  469. Remove files from the sandbox that have been removed since the last deployed hash
  470. */
  471. async function pushChangesToSandbox() {
  472. console.log("Pushing Changes to Sandbox.");
  473. let hash = await getLastDeployedHash();
  474. let deletedFiles = await getDeletedFilesSince(hash);
  475. let changedFiles = await getComittedChangesSinceHash(hash);
  476. //remove deleted files from changed files
  477. changedFiles = changedFiles.filter( item => {
  478. return false === deletedFiles.includes(item);
  479. });
  480. if(deletedFiles.length > 0) {
  481. console.log('deleting from sandbox: ', deletedFiles);
  482. await executeOnSandbox(`
  483. cd ${sandboxPublicThemesFolder};
  484. rm -f ${deletedFiles.join(' ')}
  485. `, true);
  486. }
  487. if(changedFiles.length > 0) {
  488. console.log('pushing changed files to sandbox:', changedFiles);
  489. await executeCommand(`
  490. rsync -avR --no-p --no-times --exclude-from='.sandbox-ignore' ${changedFiles.join(' ')} wpcom-sandbox:${sandboxPublicThemesFolder}/
  491. `, true);
  492. }
  493. }
  494. /*
  495. Provide a collection of all files that have changed since the given hash.
  496. Used by pushChangesToSandbox
  497. */
  498. async function getComittedChangesSinceHash(hash) {
  499. let comittedChanges = await executeCommand(`git diff ${hash} HEAD --name-only`);
  500. comittedChanges = comittedChanges.replace(/\r?\n|\r/g, " ").split(" ");
  501. let uncomittedChanges = await executeCommand(`git diff HEAD --name-only`);
  502. uncomittedChanges = uncomittedChanges.replace(/\r?\n|\r/g, " ").split(" ");
  503. return comittedChanges.concat(uncomittedChanges);
  504. }
  505. /*
  506. Provide a collection of all files that have been deleted since the given hash.
  507. Used by pushChangesToSandbox
  508. */
  509. async function getDeletedFilesSince(hash){
  510. let deletedSinceHash = await executeCommand(`
  511. git log --format=format:"" --name-only -M100% --diff-filter=D ${hash}..HEAD
  512. `);
  513. deletedSinceHash = deletedSinceHash.replace(/\r?\n|\r/g, " ").trim().split(" ");
  514. let deletedAndUncomitted = await executeCommand(`
  515. git diff HEAD --name-only --diff-filter=D
  516. `);
  517. deletedAndUncomitted = deletedAndUncomitted.replace(/\r?\n|\r/g, " ").trim().split(" ");
  518. return deletedSinceHash.concat(deletedAndUncomitted).filter( item => {
  519. return item != '';
  520. });
  521. }
  522. /*
  523. Build the Phabricator commit message.
  524. This message contains the logs from all of the commits since the given hash.
  525. Used by create*PhabricatorDiff
  526. */
  527. async function buildPhabricatorCommitMessageSince(hash){
  528. let projectVersion = await executeCommand(`node -p "require('./package.json').version"`);
  529. let logs = await executeCommand(`git log --reverse --pretty=format:%s ${hash}..HEAD`);
  530. return `Deploy Themes ${projectVersion} to wpcom
  531. Summary:
  532. ${logs}
  533. Test Plan: Execute Smoke Test
  534. Reviewers:
  535. Subscribers:
  536. `;
  537. }
  538. /*
  539. Create a (git) Phabricator diff from a given hash.
  540. Open the phabricator diff in your browser.
  541. Provide the URL of the phabricator diff.
  542. */
  543. async function createGitPhabricatorDiff(hash) {
  544. console.log('creating Phabricator Diff');
  545. let commitMessage = await buildPhabricatorCommitMessageSince(hash);
  546. let result = await executeOnSandbox(`
  547. cd ${sandboxPublicThemesFolder};
  548. git branch -D deploy
  549. git checkout -b deploy
  550. git add --all
  551. git commit -m "${commitMessage}"
  552. arc diff --create --verbatim
  553. `, true);
  554. let phabricatorUrl = getPhabricatorUrlFromResponse(result);
  555. console.log('Diff Created at: ', phabricatorUrl);
  556. if(phabricatorUrl) {
  557. open(phabricatorUrl);
  558. }
  559. return phabricatorUrl;
  560. }
  561. /*
  562. Create a (svn) Phabricator diff from a given hash.
  563. Open the phabricator diff in your browser.
  564. Provide the URL of the phabricator diff.
  565. */
  566. async function createSvnPhabricatorDiff(hash) {
  567. console.log('creating Phabricator Diff');
  568. const commitTempFileLocation = '/tmp/theme-deploy-comment.txt';
  569. const commitMessage = await buildPhabricatorCommitMessageSince(hash);
  570. console.log(commitMessage);
  571. const result = await executeOnSandbox(`
  572. cd ${sandboxPublicThemesFolder};
  573. echo "${commitMessage}" > ${commitTempFileLocation};
  574. svn add --force * --auto-props --parents --depth infinity -q;
  575. svn status | grep "^\!" | sed 's/^\! *//g' | xargs svn rm;
  576. arc diff --create --message-file ${commitTempFileLocation}
  577. `, true);
  578. const phabricatorUrl = getPhabricatorUrlFromResponse(result);
  579. console.log('Diff Created at: ', phabricatorUrl);
  580. if(phabricatorUrl) {
  581. open(phabricatorUrl);
  582. }
  583. return phabricatorUrl;
  584. }
  585. /*
  586. Utility to pull the Phabricator URL from the diff creation command.
  587. Used by createGitPhabricatorDiff
  588. */
  589. function getPhabricatorUrlFromResponse(response){
  590. return response
  591. ?.split('\n')
  592. ?.find( item => {
  593. return item.includes('Revision URI: ');
  594. })
  595. ?.split("Revision URI: ")[1];
  596. }
  597. /*
  598. Create a git tag at the current hash.
  599. In the description include the commit logs since the given hash.
  600. Include the (cleansed) Phabricator link.
  601. */
  602. async function tagDeployment(options={}) {
  603. let hash = options.hash || await getLastDeployedHash();
  604. let workInTheOpenPhabricatorUrl = '';
  605. if (options.diffId) {
  606. workInTheOpenPhabricatorUrl = `Phabricator: ${options.diffId}-code`;
  607. }
  608. let projectVersion = await executeCommand(`node -p "require('./package.json').version"`);
  609. let logs = await executeCommand(`git log --reverse --pretty=format:%s ${hash}..HEAD`);
  610. let tag = `v${projectVersion}`;
  611. let message = `Deploy Themes ${tag} to wpcom. \n\n${logs} \n\n${workInTheOpenPhabricatorUrl}`;
  612. await executeCommand(`
  613. git tag -a ${tag} -m "${message}"
  614. git push origin ${tag}
  615. `);
  616. }
  617. /*
  618. Execute a command on the sandbox.
  619. Expects the following to be configured in your ~/.ssh/config file:
  620. Host wpcom-sandbox
  621. User wpdev
  622. HostName SANDBOXURL.wordpress.com
  623. ForwardAgent yes
  624. */
  625. function executeOnSandbox(command, logResponse, enablePsudoterminal){
  626. if(enablePsudoterminal){
  627. return executeCommand(`ssh -tt -A ${remoteSSH} << EOF
  628. ${command}
  629. EOF`, logResponse);
  630. }
  631. return executeCommand(`ssh -TA ${remoteSSH} << EOF
  632. ${command}
  633. EOF`, logResponse);
  634. }
  635. /*
  636. Execute a command locally.
  637. */
  638. async function executeCommand(command, logResponse) {
  639. return new Promise((resolove, reject) => {
  640. let child;
  641. let response = '';
  642. let errResponse = '';
  643. if (isWin) {
  644. child = spawn('cmd.exe', ['/s', '/c', '"' + command + '"'], {
  645. windowsVerbatimArguments: true,
  646. stdio: [process.stdin, 'pipe', 'pipe'],
  647. })
  648. } else {
  649. child = spawn(process.env.SHELL, ['-c', command]);
  650. }
  651. child.stdout.on('data', (data) => {
  652. response += data;
  653. if(logResponse){
  654. console.log(data.toString());
  655. }
  656. });
  657. child.stderr.on('data', (data) => {
  658. errResponse += data;
  659. if(logResponse){
  660. console.log(data.toString());
  661. }
  662. });
  663. child.on('exit', (code) => {
  664. if (code !== 0) {
  665. reject(errResponse.trim());
  666. }
  667. resolove(response.trim());
  668. });
  669. });
  670. }