theme-utils.mjs 22 KB

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