theme-utils.mjs 22 KB

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