-
Notifications
You must be signed in to change notification settings - Fork 357
/
theme-utils.mjs
2401 lines (2165 loc) · 64.7 KB
/
theme-utils.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { execSync, spawn } from 'child_process';
import fs, { existsSync } from 'fs';
import util from 'util';
import open from 'open';
import process from 'process';
import inquirer from 'inquirer';
import { RewritingStream } from 'parse5-html-rewriting-stream';
import { table, getBorderCharacters } from 'table';
import progressbar from 'string-progressbar';
import semver from 'semver';
import Ajv from 'ajv';
import AjvDraft04 from 'ajv-draft-04';
import glob from 'fast-glob';
import chalk, { Chalk } from 'chalk';
const remoteSSH = 'wpcom-sandbox';
const sandboxPublicThemesFolder =
'/home/wpcom/public_html/wp-content/themes/pub';
const sandboxRootFolder = '/home/wpcom/public_html/';
const glotPressScript =
'~/public_html/bin/i18n/create-glotpress-project-for-theme.php';
const isWin = process.platform === 'win32';
const coreThemes = [
'twentyten',
'twentyeleven',
'twentytwelve',
'twentythirteen',
'twentyfourteen',
'twentyfifteen',
'twentysixteen',
'twentyseventeen',
'twentynineteen',
'twentytwenty',
'twentytwentyone',
'twentytwentytwo',
'twentytwentythree',
'twentytwentyfour',
];
const commands = {
'push-button-deploy': {
helpText: `
* Gets the last deployed hash from the sandbox
* Version bump all themes that have changes since the last deployment
* Commit the version bump change to github
* Clean the sandbox and ensure it is up - to - date
* Push all changed files (including removal of deleted files) since the last deployment
* Update the 'last deployed' hash on the sandbox
* Create a GitHub pull request based on the changes since the last deployment. The description including the commit messages since the last deployment.
* Open the GitHub pull request in your browser
* Create a tag in the github repository at this point of change which includes the GitHub pull request link in the description
* After pausing to allow testing, merge and deploy the changes
`,
run: pushButtonDeploy,
},
'clean-sandbox': {
helpText:
'Perform a hard reset, checkout trunk, and pull on the public themes working copy on your sandbox.',
run: cleanSandbox,
},
'push-to-sandbox': {
helpText:
'Uses rsync to copy all modified files for all themes from the local machine to your sandbox.',
run: pushToSandbox,
},
'push-changes-to-sandbox': {
helpText:
'Uses rsync to copy all modified files for any modified themes from the local machine to your sandbox.',
run: pushChangesToSandbox,
},
'push-theme-to-sandbox': {
helpText:
'Uses rsync to copy all modified files for the specified theme from the local machine to your sandbox.',
additionalArgs: '<theme-slug>',
run: ( args ) => pushThemeToSandbox( args?.[ 1 ] ),
},
'version-bump-themes': {
helpText:
'Bump the version of any theme that has had changes since the last deployment. This includes bumping the version of any parent themes and updating the changelog for the theme. Optionally specify a single theme to version bump.',
run: ( args ) => versionBumpThemes( args?.[ 1 ]?.split( /[ ,]+/ ) ),
},
'land-diff': {
helpText: 'Run gh pr merge to merge in the specified pull request id.',
additionalArgs: '<gh pr id>',
run: ( args ) => landChanges( args?.[ 1 ] ),
},
'deploy-preview': {
helpText: 'Display a list of the changes to be deployed.',
run: deployPreview,
},
'deploy-theme': {
helpText:
'This runs "deploy pub <theme>" on the provided list of themes.',
additionalArgs: '<array of theme slugs>',
run: ( args ) => deployThemes( args?.[ 1 ].split( /[ ,]+/ ) ),
},
'add-strict-typing': {
helpText: 'Adds strict typing to any changed themes.',
run: () => addStrictTypesToChangedThemes(),
},
'build-com-zip': {
helpText: 'Build the production zip file for the specified theme.',
additionalArgs: '<theme-slug>',
run: ( args ) => buildComZips( args?.[ 1 ].split( /[ ,]+/ ) ),
},
'checkout-core-theme': {
helpText:
'Use SVN to checkout the given core themes from the wpcom SVN repository.',
additionalArgs: '<theme-slug>',
run: ( args ) => checkoutCoreTheme( args?.[ 1 ] ),
},
'pull-all-themes': {
helpText:
'Use rsync to copy all public theme files from your sandbox to your local machine.',
run: pullAllThemes,
},
'pull-core-themes': {
helpText:
'Use rsync to copy all public CORE theme files from your sandbox to your local machine. CORE themes are any of the Twenty<whatever> themes.',
run: pullCoreThemes,
},
'push-core-themes': {
helpText:
'Use rsync to copy all public CORE theme files from your local machine to your sandbox. CORE themes are any of the Twenty<whatever> themes.',
run: pushCoreThemes,
},
'sync-core-theme': {
helpText:
'Given a theme slug and SVN revision, sync the theme from the specified revision to the latest. This requires the core theme to be currently checked out from the wpcom svn repository.',
additionalArgs: '<theme-slug> <since-revision>',
run: ( args ) => syncCoreTheme( args?.[ 1 ], args?.[ 2 ] ),
},
'deploy-sync-core-theme': {
helpText:
'Given a theme slug and SVN revision, sync the theme from the specified revision to the latest. This command contains additional prompts and error checking not provided by sync-core-theme.',
additionalArgs: '<theme-slug> <since-revision>',
run: ( args ) => deploySyncCoreTheme( args?.[ 1 ], args?.[ 2 ] ),
},
'create-core-github-pr': {
helpText:
'Given a theme slug and specific revision create a GitHub pull request from the resources currently on the sandbox.',
additionalArgs: '<theme-slug> <since-revision>',
run: ( args ) => createCoreGithubPR( args?.[ 1 ], args?.[ 2 ] ),
},
'update-theme-changelog': {
helpText:
'Use the commit log to build a list of recent changes and add them as a new changelog entry. If add-changes is true, the updated readme.txt will be staged.',
additionalArgs: '<theme-slug> <add-changes, true/false>',
run: ( args ) =>
updateThemeChangelog( args?.[ 1 ], false, args?.[ 2 ] ),
},
'rebuild-theme-changelog': {
helpText:
'Rebuild the entire change long from the given starting hash.',
additionalArgs: '<theme-slug> <since>',
run: ( args ) => rebuildThemeChangelog( args?.[ 1 ], args?.[ 2 ] ),
},
'escape-patterns': {
helpText:
'Escapes block patterns for pattern files that have changes (staged or unstaged).',
additionalArgs: '[directory]',
run: ( args ) => escapePatterns( args?.[ 1 ] ),
},
'validate-theme': {
helpText: [
'Validates a theme against the WordPress theme requirements.',
'--format=FORMAT',
wrapIndent( 'Output format. Possible values: *table*, json, dir.' ),
'--color=WHEN',
wrapIndent(
'Colorize the output for table or dir formats. The automatic mode only enables colors if an interactive terminal is detected. Possible values: *auto*, always, never.'
),
'--table-width=COLUMNS',
wrapIndent(
'Explicitly set the width of the table format instead of determining it automatically. Will default to 120 if omitted and width cannot be determined automatically.'
),
].join( '\n\n' ),
additionalArgs:
'[--format=FORMAT] [--color=WHEN] [--table-width=COLUMNS] <array of theme slugs>',
run: async ( args ) => {
args.shift();
const options = {};
while ( args[ 0 ] && args[ 0 ].startsWith( '--' ) ) {
const flag = args.shift().slice( 2 );
const [ key, value ] = flag.split( '=' );
const camelCaseKey = key.replace( /-([a-z])/g, ( [ , c ] ) =>
c.toUpperCase()
);
options[ camelCaseKey ] = value ?? true;
}
const themes = args[ 0 ] ? args[ 0 ].split( /[ ,]+/ ) : [];
if ( themes.length ) {
await validateThemes( themes, options );
}
},
},
help: {
helpText: 'Displays the main help message.',
run: ( args ) => showHelp( args?.[ 1 ] ),
},
};
( async function start() {
let args = process.argv.slice( 2 );
let command = args?.[ 0 ];
if ( ! commands[ command ] ) {
showHelp();
process.exit( 1 );
}
await commands[ command ].run( args );
} )();
function wrapIndent(
text,
indent = ' ',
newline = '\n',
width = process.stdout.columns || 80
) {
return text
.match(
new RegExp(
`.{1,${ width - indent.length - 1 }}(\\s+|$)|[^\\s]+?(\\s+|$)`,
'g'
)
)
.map( ( line ) => indent + line )
.join( newline );
}
function showHelp( command = '' ) {
if ( ! command || ! commands.hasOwnProperty( command ) ) {
console.log( `
node theme-utils.mjs [command]
Available commands:
_(theme-utils.mjs help [command] for more details)_
\t${ Object.keys( commands ).join( '\n\t' ) }
` );
return;
}
const { helpText, additionalArgs } = commands[ command ];
console.log( `
${ command } ${ additionalArgs ?? '' }
${ helpText }
` );
}
/*
Create list of changes from git logs
Optionally pass in a deployed hash or default to calling getLastDeployedHash()
Optionally pass in boolean bulletPoints to add bullet points to each commit log
*/
async function getCommitLogs( hash, bulletPoints, theme ) {
if ( ! hash ) {
hash = await getLastDeployedHash();
}
let format = 'format:%s';
let themeDir = '';
if ( bulletPoints ) {
format = 'format:"* %s"';
}
if ( theme ) {
themeDir = `-- ./${ theme }`;
}
let logs = await executeCommand(
`git log --reverse --pretty=${ format } ${ hash }..HEAD ${ themeDir }`
);
// Remove any double quotes from commit messages
logs = logs.replace( /"/g, '' );
return logs;
}
/*
Determine what changes would be deployed
*/
async function deployPreview() {
console.clear();
console.log(
'To ensure accuracy clean your sandbox before previewing. (It is not automatically done).'
);
let message = await checkForDeployability();
if ( message ) {
console.log( `\n${ message }\n\n` );
}
let hash = await getLastDeployedHash();
console.log( `Last deployed hash: ${ hash }` );
let changedThemes = await getChangedThemes( hash );
console.log( `The following themes have changes:\n${ changedThemes }` );
let logs = await getCommitLogs( hash );
console.log( `\n\nCommit log of changes to be deployed:\n\n${ logs }\n\n` );
}
async function addStrictTypesToChangedThemes() {
let hash = await getLastDeployedHash();
const changedThemes = await getChangedThemes( hash );
for ( let theme of changedThemes ) {
await executeCommand(
`
bash -c "./add-strict-types.sh ${ theme }"
`,
true
).catch( ( err ) => {
console.log( `Error adding strict types to ${ theme }: ${ err }` );
} );
}
}
/*
Execute the first phase of a deployment.
* Gets the last deployed hash from the sandbox
* Version bump all themes that have changes since the last deployment
* Commit the version bump change to github
* Clean the sandbox and ensure it is up-to-date
* Push all changed files (including removal of deleted files) since the last deployment
* Update the 'last deployed' hash on the sandbox
* Create a GitHub pull request based on the changes since the last deployment. The description including the commit messages since the last deployment.
* Open the GitHub pull request in your browser
* Create a tag in the github repository at this point of change which includes the GitHub pull request link in the description
*/
async function pushButtonDeploy() {
console.clear();
let prompt = await inquirer.prompt( [
{
type: 'confirm',
message:
'You are about to deploy /trunk. Are you ready to continue?',
name: 'continue',
default: false,
},
] );
if ( ! prompt.continue ) {
return;
}
let message = await checkForDeployability();
if ( message ) {
return console.log( `\n\n${ message }\n\n` );
}
try {
await cleanSandbox();
const hash = await getLastDeployedHash();
await addStrictTypesToChangedThemes();
const thingsWentBump = await versionBumpThemes();
if ( thingsWentBump ) {
prompt = await inquirer.prompt( [
{
type: 'confirm',
message:
'Are you good with the version bump and changelog updates? Make any manual adjustments now if necessary.',
name: 'continue',
default: false,
},
] );
if ( ! prompt.continue ) {
console.log(
`Aborted Automated Deploy Process at version bump changes.`
);
return;
}
}
const changedThemes = await getChangedThemes( hash );
if ( ! changedThemes.length ) {
console.log(
`\n\nEverything is upto date. Nothing new to deploy.\n\n`
);
return;
}
await pushChangesToSandbox();
await createGlotPressProject( changedThemes );
//push changes (from version bump)
if ( thingsWentBump ) {
prompt = await inquirer.prompt( [
{
type: 'confirm',
message:
'Are you ready to push this version bump change to the source repository (GitHub.com)?',
name: 'continue',
default: false,
},
] );
if ( ! prompt.continue ) {
console.log(
`Aborted Automated Deploy Process at version bump push change.`
);
return;
}
await executeCommand(
`
git commit -m "Version Bump";
git push --set-upstream origin trunk
`,
true
);
}
await updateLastDeployedHash();
let commitMessage = await buildGithubCommitMessageSince( hash );
// Make sure the themes/pub repo in sandbox is ready to create a PR to the A8C GitHub Host
prompt = await inquirer.prompt( [
{
type: 'confirm',
message:
'Before you can create the GitHub PR, login in A8C GitHub Enterprise Server from the themes/pub repo in your sandbox with the command "gh auth login" and using your SSH key.\nAre you logged in?',
name: 'continue',
default: false,
},
] );
if ( ! prompt.continue ) {
console.log(
`Aborted Automated Deploy Process at require to login in into A8C GitHub Enterprise Server in sandbox.`
);
return;
}
let prUrl = await createGithubPR( commitMessage );
let prId = prUrl.split( 'pull/' )[ 1 ];
await tagDeployment( {
hash: hash,
prId: prId,
} );
console.log(
`\n\nPhase One Complete\n\nYour sandbox has been updated and the PR 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`
);
prompt = await inquirer.prompt( [
{
type: 'confirm',
message: 'Are you ready to land these changes?',
name: 'continue',
default: false,
},
] );
if ( ! prompt.continue ) {
console.log(
`Aborted Automated Deploy Process Landing Phase\n\nYou will have to land these changes manually. The ID of the PR to land: ${ prId }`
);
return;
}
await landChanges( prId );
try {
await deployThemes( changedThemes );
} catch ( err ) {
prompt = await inquirer.prompt( [
{
type: 'confirm',
message: `There was an error deploying themes. ${ err } Do you wish to continue to the next step?`,
name: 'continue',
default: false,
},
] );
if ( ! prompt.continue ) {
console.log( `Aborted Automated Deploy during deploy phase.` );
return;
}
}
await buildComZips( changedThemes );
console.log(
`The following themes have changed:\n${ changedThemes.join(
'\n'
) }`
);
console.log( '\n\nAll Done!!\n\n' );
} catch ( err ) {
console.log( 'ERROR with deploy script: ', err );
}
}
async function deploySyncCoreTheme( theme, sinceRevision ) {
if ( ! theme ) {
console.log( 'Must supply theme to sync and revision to start from' );
return;
}
await cleanSandbox();
await checkoutCoreTheme( theme );
await syncCoreTheme( theme, sinceRevision );
let prompt = await inquirer.prompt( [
{
type: 'confirm',
message: `Changes have been synced locally. Please resolve any conflicts now. Are you ready to continue?`,
name: 'continue',
default: false,
},
] );
if ( ! prompt.continue ) {
console.log( `Aborted Core Sync Deploy.` );
return;
}
await pushThemeToSandbox( theme );
let prId = await createCoreGithubPR( theme, sinceRevision );
prompt = await inquirer.prompt( [
{
type: 'confirm',
message: 'Are you ready to land these changes?',
name: 'continue',
default: false,
},
] );
if ( ! prompt.continue ) {
console.log(
`Aborted Automated Deploy Sync Process Landing Phase\n\nYou will have to land these changes manually. The ID of the PR to land: ${ prId }`
);
return;
}
await landChanges( prId );
await deployThemes( [ theme ] );
await buildComZips( [ theme ] );
return;
}
async function buildCoreGithubCommitMessageSince( theme, sinceRevision ) {
let latestRevision = await executeCommand(
`svn info -r HEAD https://develop.svn.wordpress.org/trunk | grep Revision | egrep -o "[0-9]+"`
);
let logs = await executeCommand(
`svn log https://core.svn.wordpress.org/trunk/wp-content/themes/${ theme } -r${ sinceRevision }:HEAD`
);
// Remove any double or back quotes from commit messages
logs = logs.replace( /"/g, '' );
logs = logs.replace( /`/g, "'" );
logs = logs.replace( /\$/g, '%24' );
return `${ theme }: Merge latest core changes up to [wp${ latestRevision }]
Summary:
${ logs }
Test Plan: Activate ${ theme } and ensure nothing is broken
Reviewers:
#themes_team
Subscribers:
`;
}
/**
* Deploys the localy copy of a core theme to wpcom.
*/
async function createCoreGithubPR( theme, sinceRevision ) {
let commitMessage = await buildCoreGithubCommitMessageSince(
theme,
sinceRevision
);
let prUrl = await createGithubPR( commitMessage );
let prId = prUrl.split( 'pull/' )[ 1 ];
return prId;
}
/*
Build .zip file for .com
*/
async function buildComZip( themeSlug ) {
console.log( `Building ${ themeSlug } .zip` );
let styleCss = fs.readFileSync( `${ themeSlug }/style.css`, 'utf8' );
// Gets the theme version (Version:) and minimum WP version (Tested up to:) from the theme's style.css
let themeVersion = getThemeMetadata( styleCss, 'Version' );
let wpVersionCompat = getThemeMetadata( styleCss, 'Requires at least' );
if ( themeVersion && wpVersionCompat ) {
await executeOnSandbox(
`php ${ sandboxRootFolder }bin/themes/theme-downloads/build-theme-zip.php --stylesheet=pub/${ themeSlug } --themeversion=${ themeVersion } --wpversioncompat=${ wpVersionCompat };`,
true
);
} else {
console.log( 'Unable to build theme .zip.' );
if ( ! themeVersion ) {
console.log(
'Could not find theme version (Version:) in the theme style.css.'
);
}
if ( ! wpVersionCompat ) {
console.log(
'Could not find WP compat version (Requires at least:) in the theme style.css.'
);
}
console.log(
'Please build the .zip file for the theme manually.',
themeSlug
);
open( 'https://mc.a8c.com/themes/downloads/' );
}
}
async function buildComZips( themes ) {
console.log( `Building dotcom .zip files` );
const progress = startProgress( themes.length );
const failedThemes = [];
for ( let theme of themes ) {
try {
await buildComZip( theme );
} catch ( err ) {
console.log(
`There was an error building dotcom zip for ${ theme }. ${ err }`
);
failedThemes.push( theme );
}
progress.increment();
}
if ( failedThemes.length ) {
const tableConfig = {
columnDefault: {
width: 40,
},
header: {
alignment: 'center',
content: `There was an error building dotcom zip for following themes.`,
},
};
console.log(
table(
failedThemes.map( ( t ) => [ t ] ),
tableConfig
)
);
}
}
/*
Check to ensure that:
* The current branch is /trunk
* That trunk is up-to-date with origin/trunk
*/
async function checkForDeployability() {
let branchName = await executeCommand( 'git symbolic-ref --short HEAD' );
if ( branchName !== 'trunk' ) {
return 'Only the /trunk branch can be deployed.';
}
await executeCommand( 'git remote update', true );
let localMasterHash = await executeCommand( 'git rev-parse trunk' );
let remoteMasterHash = await executeCommand( 'git rev-parse origin/trunk' );
if ( localMasterHash !== remoteMasterHash ) {
return 'Local /trunk is out-of-date. Pull changes to continue.';
}
return null;
}
/*
Land the changes from the given PR ID. This is the "production merge".
*/
async function landChanges( prId ) {
return executeCommand(
`ssh -tt -A ${ remoteSSH } "cd ${ sandboxPublicThemesFolder } && gh pr merge ${ prId } --squash; exit;"`,
true
);
}
async function getChangedThemes( hash ) {
console.log( 'Determining all changed themes' );
let themes = await getActionableThemes();
let changedThemes = [];
for ( let theme of themes ) {
let hasChanges = await checkThemeForChanges( theme, hash );
if ( hasChanges ) {
changedThemes.push( theme );
}
}
return changedThemes;
}
/*
Deploy a collection of themes.
Part of the push-button-deploy process.
Can also be triggered to deploy a single theme with the command:
node ./theme-utils.mjs deploy-theme THEMENAME
*/
async function deployThemes( themes ) {
let response;
const failedThemes = [];
const progress = startProgress( themes.length );
for ( let theme of themes ) {
console.log( `Deploying ${ theme }` );
let deploySuccess = false;
let attempt = 0;
while ( ! deploySuccess && attempt <= 2 ) {
attempt++;
console.log( `\nattempt #${ attempt }\n\n` );
try {
response = await executeOnSandbox(
`deploy pub ${ theme };exit;`,
true,
true
);
deploySuccess = response.includes( 'successfully deployed to' );
} catch ( error ) {
deploySuccess = false;
}
if ( ! deploySuccess ) {
console.log(
'Deploy was not successful. Trying again in 10 seconds...'
);
await new Promise( ( resolve ) =>
setTimeout( resolve, 10000 )
);
} else {
console.log( 'Deploy successful.' );
}
}
if ( ! deploySuccess ) {
console.log(
`${ theme } was not sucessfully deployed and should be deployed manually.`
);
failedThemes.push( theme );
}
progress.increment();
}
if ( failedThemes.length ) {
const tableConfig = {
columnDefault: {
width: 40,
},
header: {
alignment: 'center',
content: `Following themes are not deployed.`,
},
};
console.log(
table(
failedThemes.map( ( t ) => [ t ] ),
tableConfig
)
);
}
}
/*
Provide the hash of the last managed deployment.
This hash is used to determine all the changes that have happened between that point and the current point.
*/
async function getLastDeployedHash() {
let result = await executeOnSandbox( `
cat ${ sandboxPublicThemesFolder }/.pub-git-hash
` );
return result;
}
/*
Update the 'last deployed hash' on the server with the current hash.
*/
async function updateLastDeployedHash() {
let hash = await executeCommand( `git rev-parse HEAD` );
await executeOnSandbox( `
echo '${ hash }' > ${ sandboxPublicThemesFolder }/.pub-git-hash
` );
}
/*
Version bump (increment version patch) any theme project that has had changes since the last deployment.
If a theme's version has already been changed since that last deployment then do not version bump it.
If any theme projects have had a version bump also version bump the parent project.
If a theme has changes also update its changelog.
Commit the change.
*/
async function versionBumpThemes( themeSlugs ) {
console.log( 'Version Bumping' );
const themes = themeSlugs ? themeSlugs : await getActionableThemes();
const latestTag = execSync( 'git describe --tags --abbrev=0' )
.toString()
.trim();
// Get the hash for the latest tag.
const hash = execSync( `git rev-parse ${ latestTag }` ).toString().trim();
let versionBumpCount = 0;
let changesWereMade = false;
for ( let theme of themes ) {
const hasChanges = await checkThemeForChanges( theme, hash );
if ( ! hasChanges ) {
continue;
}
versionBumpCount++;
const hasVersionBump = await checkThemeForVersionBump( theme, hash );
if ( hasVersionBump ) {
continue;
}
await versionBumpTheme( theme, true );
await updateThemeChangelog( theme, true );
changesWereMade = true;
}
//version bump the root project if there were changes to any of the themes
const rootHasVersionBump = await checkProjectForVersionBump( hash );
if ( versionBumpCount === 0 ) {
console.log(
'No changes detected; Root package version bump not required'
);
} else if ( ! rootHasVersionBump ) {
await executeCommand(
`npm version patch --no-git-tag-version && git add package.json package-lock.json`
);
changesWereMade = true;
}
return changesWereMade;
}
export function getThemeMetadata( styleCss, attribute, trimWPCom = true ) {
if ( ! styleCss || ! attribute ) {
return null;
}
switch ( attribute ) {
case 'Version':
const version = styleCss
.match( /(?<=Version:\s*).*?(?=\s*\r?\n|\rg)/gs )?.[ 0 ]
?.trim();
return trimWPCom ? version.replace( '-wpcom', '' ) : version;
case 'Requires at least':
return styleCss
.match(
/(?<=Requires at least:\s*).*?(?=\s*\r?\n|\rg)/gs
)?.[ 0 ]
?.trim();
default:
return styleCss
.match(new RegExp(`(?<=${attribute}:\\s*).*?(?=\\s*\\r?\\n|\\rg)`, 'gs'))?.[0]
?.trim();
}
}
/* Rebuild theme changelog from a given starting hash */
async function rebuildThemeChangelog( theme, since ) {
console.log(
`Rebuilding ${ theme } changelog since ${ since || 'forever' }`
);
if ( since ) {
since = `${ since }..HEAD`;
} else {
since = 'HEAD';
}
let hashes = await executeCommand(
`git rev-list ${ since } -- ./${ theme }`
);
hashes = hashes.split( '\n' );
let logs = '== Changelog ==\n';
for ( let hash of hashes ) {
let log = await executeCommand(
`git log -n 1 --pretty=format:"* %s" ${ hash }`
);
if ( log.includes( 'Version Bump' ) ) {
let previousStyleString = await executeCommand(
`git show ${ hash }:${ theme }/style.css 2>/dev/null`
);
let version = getThemeMetadata( previousStyleString, 'Version' );
logs += `\n= ${ version } =\n`;
} else {
// Remove any double quotes from commit messages
log = log.replace( /"/g, '' );
logs += log + '\n';
}
}
// Get theme readme.txt
let readmeFilePath = `${ theme }/readme.txt`;
// Update readme.txt
fs.readFile( readmeFilePath, 'utf8', function ( err, data ) {
let changelogSection = '== Changelog ==';
let regex = new RegExp( '^.*' + changelogSection + '.*$', 'gm' );
let formattedChangelog = data.replace( regex, logs );
fs.writeFile(
readmeFilePath,
formattedChangelog,
'utf8',
function ( err ) {
if ( err ) return console.log( err );
}
);
} );
}
/*
Update theme changelog using current commit logs.
Used by versionBumpThemes to update each theme changelog.
*/
async function updateThemeChangelog( theme, addChanges ) {
console.log( `Updating ${ theme } changelog` );
// Get theme version
let styleCss = fs.readFileSync( `${ theme }/style.css`, 'utf8' );
let version = getThemeMetadata( styleCss, 'Version' );
// Get list of updates with bullet points
const lastestTagHash = execSync( 'git describe --tags --abbrev=0' )
.toString()
.trim();
let logs = await getCommitLogs( lastestTagHash, true, theme );
// Get theme readme.txt
let readmeFilePath = `${ theme }/readme.txt`;
if ( ! existsSync( readmeFilePath ) ) {
console.log( `Unable to find a readme.txt for ${ theme }.` );
return;
}
// Build changelog entry
let newChangelogEntry = `== Changelog ==
= ${ version } =
${ logs }`;
// Update readme.txt
fs.readFile( readmeFilePath, 'utf8', function ( err, data ) {
let changelogSection = '== Changelog ==';
let regex = new RegExp( '^.*' + changelogSection + '.*$', 'gm' );
let formattedChangelog = data.replace( regex, newChangelogEntry );
fs.writeFile(
readmeFilePath,
formattedChangelog,
'utf8',
function ( err ) {
if ( err ) return console.log( err );
}
);
} );
// Stage readme.txt
if ( addChanges ) {
await executeCommand( `git add ${ readmeFilePath }` );
}
}
/*
Version Bump a Theme.
Used by versionBumpThemes to do the work of version bumping.
First increment the patch version in style.css
Then update any of these files with the new version: [package.json, style.scss, style-child-theme.scss]
*/
async function versionBumpTheme( theme, addChanges ) {
console.log( `${ theme } needs a version bump` );