theme-utils.mjs 23 KB

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