theme-utils.mjs 22 KB

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