theme-utils.mjs 23 KB

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