-
-
Notifications
You must be signed in to change notification settings - Fork 804
/
Copy pathpublish_packages.js
1552 lines (1451 loc) · 56.6 KB
/
publish_packages.js
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
#!/usr/bin/env node
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eslint-disable node/no-sync, no-console, max-statements, max-lines-per-function, max-lines, node/no-unsupported-features/node-builtins */
'use strict';
// MODULES //
var join = require( 'path' ).join;
var shell = require( 'child_process' ).execSync;
var fs = require( 'fs' );
var tmpdir = require( 'os' ).tmpdir;
var logger = require( 'debug' );
var ghpages = require( 'gh-pages' );
var semver = require( 'semver' );
var CLI = require( '@stdlib/cli/ctor' );
var setTopics = require( '@stdlib/_tools/github/set-topics' );
var createRepo = require( '@stdlib/_tools/github/create-repo' );
var name2bucket = require( '@stdlib/_tools/pkgs/name2bucket' );
var writeFileSync = require( '@stdlib/fs/write-file' ).sync;
var readFileSync = require( '@stdlib/fs/read-file' ).sync;
var readJSON = require( '@stdlib/fs/read-json' ).sync;
var existsSync = require( '@stdlib/fs/exists' ).sync;
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var contains = require( '@stdlib/assert/contains' );
var memoize = require( '@stdlib/utils/memoize' );
var repeat = require( '@stdlib/string/repeat' );
var trim = require( '@stdlib/string/trim' );
var copy = require( '@stdlib/utils/copy' );
var sample = require( '@stdlib/random/sample' );
var rootDir = require( '@stdlib/_tools/utils/root-dir' );
var rescape = require( '@stdlib/utils/escape-regexp-string' );
var replace = require( '@stdlib/string/replace' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var removeFirst = require( '@stdlib/string/remove-first' );
var reFromString = require( '@stdlib/utils/regexp-from-string' );
var startsWith = require( '@stdlib/string/starts-with' );
var substringAfterLast = require( '@stdlib/string/substring-after-last' );
var currentYear = require( '@stdlib/time/current-year' );
var namespaceDeps = require( '@stdlib/_tools/pkgs/namespace-deps' );
var depList = require( '@stdlib/_tools/pkgs/dep-list' );
var name2standalone = require( '@stdlib/_tools/pkgs/name2standalone' );
var generateChangelog = require( '@stdlib/_tools/changelog/generate' );
var toposort = require( '@stdlib/_tools/pkgs/toposort' ).sync;
var ENV = require( '@stdlib/process/env' );
// VARIABLES //
var cli = new CLI();
var flags = cli.flags();
var args = cli.args();
var debug = logger( 'scripts:publish-packages' );
var START_PKG_INDEX = parseInt( flags[ 'start-index' ], 10 ) || 0;
var END_PKG_INDEX = ( flags[ 'end-index' ] === void 0 ) ? 9999 : parseInt( flags[ 'end-index' ], 10 );
var MAX_TREE_DEPTH = 99;
var KEEP_ALIVE_SAMPLE_SIZE = 1000;
var topics = setTopics.factory( {
'token': ENV.GITHUB_TOKEN
}, onTopics );
var CURRENT_YEAR = currentYear();
var INSTALLATION_SECTION_BASIC = [
'<section class="installation">',
'',
'## Installation',
'',
'```bash',
'npm install @stdlib/<pkg>',
'```',
'',
'</section>',
''
].join( '\n' );
var INSTALLATION_SECTION_BUNDLES = [
'<section class="installation">',
'',
'## Installation',
'',
'```bash',
'npm install @stdlib/<pkg>',
'```',
'',
'Alternatively,',
'',
'- To load the package in a website via a `script` tag without installation and bundlers, use the [ES Module][es-module] available on the [`esm`][esm-url] branch (see [README][esm-readme]).',
'- If you are using Deno, visit the [`deno`][deno-url] branch (see [README][deno-readme] for usage intructions).',
'- For use in Observable, or in browser/node environments, use the [Universal Module Definition (UMD)][umd] build available on the [`umd`][umd-url] branch (see [README][umd-readme]).',
'<cli>',
'The [branches.md][branches-url] file summarizes the available branches and displays a diagram illustrating their relationships.',
'',
'To view installation and usage instructions specific to each branch build, be sure to explicitly navigate to the respective README files on each branch, as linked to above.',
'',
'</section>',
''
].join( '\n' );
var INSTALLATION_SECTION_BUNDLES_CLI = [
'- To use as a general utility for the command line, install the corresponding [CLI package][cli-section] globally.',
''
].join( '\n' );
var CLI_INSTALLATION_SECTION = [
'<section class="installation">',
'',
'## Installation',
'',
'To use as a general utility, install the CLI package globally',
'',
'```bash',
'npm install -g @stdlib/<pkg>-cli',
'```',
'',
'</section>',
''
].join( '\n' );
var mainDir = join( __dirname, '..', '..', '..', '..', '..' );
var DOTFILES = [ '.editorconfig', '.gitignore', '.gitattributes', '.npmrc', 'CONTRIBUTORS', 'NOTICE', 'CITATION.cff' ];
var WORKFLOW_CLOSE_PULLS = [
'#/',
'# @license Apache-2.0',
'#',
'# Copyright (c) 2021 The Stdlib Authors.',
'#',
'# Licensed under the Apache License, Version 2.0 (the "License");',
'# you may not use this file except in compliance with the License.',
'# You may obtain a copy of the License at',
'#',
'# http://www.apache.org/licenses/LICENSE-2.0',
'#',
'# Unless required by applicable law or agreed to in writing, software',
'# distributed under the License is distributed on an "AS IS" BASIS,',
'# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.',
'# See the License for the specific language governing permissions and',
'# limitations under the License.',
'#/',
'',
'# Workflow name:',
'name: close_pull_requests',
'',
'# Workflow triggers:',
'on:',
' pull_request_target:',
' types: [opened]',
'',
'# Workflow jobs:',
'jobs:',
'',
' # Define job to close all pull requests:',
' run:',
'',
' # Define the type of virtual host machine on which to run the job:',
' runs-on: ubuntu-latest',
'',
' # Define the sequence of job steps...',
' steps:',
'',
' # Close pull request',
' - name: \'Close pull request\'',
' # Pin action to full length commit SHA corresponding to v3.1.2',
' uses: superbrothers/close-pull-request@9c18513d320d7b2c7185fb93396d0c664d5d8448',
' with:',
' comment: |',
' Thank you for submitting a pull request. :raised_hands:',
' ',
' We greatly appreciate your willingness to submit a contribution. However, we are not accepting pull requests against this repository, as all development happens on the [main project repository](https://github.com/stdlib-js/stdlib).',
' ',
' We kindly request that you submit this pull request against the [respective directory](<pkg-path>) of the main repository where we’ll review and provide feedback. If this is your first stdlib contribution, be sure to read the [contributing guide](https://github.com/stdlib-js/stdlib/blob/develop/CONTRIBUTING.md) which provides guidelines and instructions for submitting contributions.',
' ',
' Thank you again, and we look forward to receiving your contribution! :smiley:',
' ',
' Best,',
' The stdlib team'
].join( '\n' );
var PULL_REQUEST_TEMPLATE = [
'<!-- ----------^ Click "Preview"! -->',
'',
'We are excited about your pull request, but unfortunately we are not accepting pull requests against this repository, as all development happens on the [main project repository](https://github.com/stdlib-js/stdlib). We kindly request that you submit this pull request against the [respective directory](<pkg-path>) of the main repository where we’ll review and provide feedback. ',
'',
'If this is your first stdlib contribution, be sure to read the [contributing guide](https://github.com/stdlib-js/stdlib/blob/develop/CONTRIBUTING.md) which provides guidelines and instructions for submitting contributions. You may also consult the [development guide](https://github.com/stdlib-js/stdlib/blob/develop/docs/development.md) for help on developing stdlib.',
'',
'We look forward to receiving your contribution! :smiley:'
].join( '\n' );
var FUNDING = {
'type': 'opencollective',
'url': 'https://opencollective.com/stdlib'
};
var BRANCHES = [
'<!--',
'',
'@license Apache-2.0',
'',
'Copyright (c) 2022 The Stdlib Authors.',
'',
'Licensed under the Apache License, Version 2.0 (the "License");',
'you may not use this file except in compliance with the License.',
'You may obtain a copy of the License at',
'',
' http://www.apache.org/licenses/LICENSE-2.0',
'',
'Unless required by applicable law or agreed to in writing, software',
'distributed under the License is distributed on an "AS IS" BASIS,',
'WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.',
'See the License for the specific language governing permissions and',
'limitations under the License.',
'',
'-->',
'',
'# Branches',
'',
'This repository has the following branches:',
'',
'- **main**: default branch generated from the [stdlib project][stdlib-url], where all development takes place.',
'- **production**: [production build][production-url] of the package (e.g., reformatted error messages to reduce bundle sizes and thus the number of bytes transmitted over a network).',
'- **esm**: [ES Module][esm-url] branch for use via a `script` tag without the need for installation and bundlers (see [README][esm-readme]).',
'- **deno**: [Deno][deno-url] branch for use in Deno (see [README][deno-readme]).',
'- **umd**: [UMD][umd-url] branch for use in Observable, or in dual browser/Node.js environments (see [README][umd-readme]).',
'',
'The following diagram illustrates the relationships among the above branches:',
'',
'```mermaid',
'graph TD;',
'A[stdlib]-->|generate standalone package|B;',
'B[main] -->|productionize| C[production];',
'C -->|bundle| D[esm];',
'C -->|bundle| E[deno];',
'C -->|bundle| F[umd];',
'',
'%% click A href "<pkg-path>"',
'%% click B href "https://github.com/stdlib-js/<pkg>/tree/main"',
'%% click C href "https://github.com/stdlib-js/<pkg>/tree/production"',
'%% click D href "https://github.com/stdlib-js/<pkg>/tree/esm"',
'%% click E href "https://github.com/stdlib-js/<pkg>/tree/deno"',
'%% click F href "https://github.com/stdlib-js/<pkg>/tree/umd"',
'```',
'',
'[stdlib-url]: <pkg-path>',
'[production-url]: https://github.com/stdlib-js/<pkg>/tree/production',
'[deno-url]: https://github.com/stdlib-js/<pkg>/tree/deno',
'[deno-readme]: https://github.com/stdlib-js/<pkg>/blob/deno/README.md',
'[umd-url]: https://github.com/stdlib-js/<pkg>/tree/umd',
'[umd-readme]: https://github.com/stdlib-js/<pkg>/blob/umd/README.md',
'[esm-url]: https://github.com/stdlib-js/<pkg>/tree/esm',
'[esm-readme]: https://github.com/stdlib-js/<pkg>/blob/esm/README.md'
].join( '\n' );
var BRANCHES_WITH_CLI = [
'<!--',
'',
'@license Apache-2.0',
'',
'Copyright (c) 2023 The Stdlib Authors.',
'',
'Licensed under the Apache License, Version 2.0 (the "License");',
'you may not use this file except in compliance with the License.',
'You may obtain a copy of the License at',
'',
' http://www.apache.org/licenses/LICENSE-2.0',
'',
'Unless required by applicable law or agreed to in writing, software',
'distributed under the License is distributed on an "AS IS" BASIS,',
'WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.',
'See the License for the specific language governing permissions and',
'limitations under the License.',
'',
'-->',
'',
'# Branches',
'',
'This repository has the following branches:',
'',
'- **main**: default branch generated from the [stdlib project][stdlib-url], where all development takes place.',
'- **production**: [production build][production-url] of the package (e.g., reformatted error messages to reduce bundle sizes and thus the number of bytes transmitted over a network).',
'- **esm**: [ES Module][esm-url] branch for use via a `script` tag without the need for installation and bundlers (see [README][esm-readme]).',
'- **deno**: [Deno][deno-url] branch for use in Deno (see [README][deno-readme]).',
'- **umd**: [UMD][umd-url] branch for use in Observable, or in dual browser/Node.js environments (see [README][umd-readme]).',
'- **cli**: [CLI][cli-url] branch for use on the command line.',
'',
'The following diagram illustrates the relationships among the above branches:',
'',
'```mermaid',
'graph TD;',
'A[stdlib]-->|generate standalone package|B;',
'B[main] -->|productionize| C[production];',
'C -->|bundle| D[esm];',
'C -->|bundle| E[deno];',
'C -->|bundle| F[umd];',
'C -->|extract| G[cli];',
'',
'%% click A href "<pkg-path>"',
'%% click B href "https://github.com/stdlib-js/<pkg>/tree/main"',
'%% click C href "https://github.com/stdlib-js/<pkg>/tree/production"',
'%% click D href "https://github.com/stdlib-js/<pkg>/tree/esm"',
'%% click E href "https://github.com/stdlib-js/<pkg>/tree/deno"',
'%% click F href "https://github.com/stdlib-js/<pkg>/tree/umd"',
'%% click G href "https://github.com/stdlib-js/<pkg>/tree/cli"',
'```',
'',
'[stdlib-url]: <pkg-path>',
'[production-url]: https://github.com/stdlib-js/<pkg>/tree/production',
'[deno-url]: https://github.com/stdlib-js/<pkg>/tree/deno',
'[deno-readme]: https://github.com/stdlib-js/<pkg>/blob/deno/README.md',
'[umd-url]: https://github.com/stdlib-js/<pkg>/tree/umd',
'[umd-readme]: https://github.com/stdlib-js/<pkg>/blob/umd/README.md',
'[esm-url]: https://github.com/stdlib-js/<pkg>/tree/esm',
'[esm-readme]: https://github.com/stdlib-js/<pkg>/blob/esm/README.md',
'[cli-url]: https://github.com/stdlib-js/<pkg>/tree/cli'
].join( '\n' );
var RE_CLI_USAGE_SECTION = /(## CLI\r?\n\r?\n\s*)(<!-- CLI usage documentation\. -->\r?\n\r?\n\s*)?<section\s+class\s*=\s*"usage"\s*>/;
var RE_C_USAGE_SECTION = /(<!-- C usage documentation\. -->\r?\n\r?\n\s*)<section\s+class\s*=\s*"usage"\s*>/;
var RE_USAGE_SECTION = /<section\s+class\s*=\s*"usage"\s*>/;
var BASIC_GITHUB_TOPICS = [
'nodejs',
'javascript',
'stdlib',
'node',
'node-js'
];
var RE_ALLOWED_TOPIC_CHARS = /^[A-Z0-9-]+$/i;
var memoizedNPMversionForDeps = memoize( npmVersion );
var memoizedNPMversionForDevDeps = memoize( npmVersion );
// FUNCTIONS //
/**
* Returns a cron schedule for a given package.
*
* @private
* @param {string} pkg - package name
* @returns {string} cron schedule
*/
function cronSchedule( pkg ) {
var mins = name2bucket( pkg, 60 );
var hrs = name2bucket( pkg, 24 );
var dow = name2bucket( pkg, 7 );
return mins+' '+hrs+' * * '+dow;
}
/**
* Gets the latest version of a package on npm.
*
* @private
* @param {string} pkg - package name
* @returns {string} latest version published to npm
*/
function npmVersion( pkg ) {
var command = 'npm view '+pkg+' version --silent';
try {
return '^'+trim( shell( command ).toString() );
} catch ( error ) {
debug( 'Encountered an error when attempting to get the latest version of package `%s`: %s', pkg, error.message );
return 'github:stdlib-js/' + replace( pkg, '@stdlib/', '' ) + '#main';
}
}
/**
* Populates the dependencies and devDependencies fields of a package.json object.
*
* @private
* @param {Object} pkgJSON - package.json object
* @param {Array} deps - dependencies
* @param {Array} devDeps - devDependencies
* @param {Object} mainJSON - main repo package.json object
* @param {boolean} useGitHub - boolean indicating whether to use GitHub URLs for dependencies
* @returns {Object} package.json object
*/
function populateDeps( pkgJSON, deps, devDeps, mainJSON, useGitHub ) {
var mainVersion;
var out;
var dep;
var i;
out = copy( pkgJSON );
for ( i = 0; i < deps.length; i++ ) {
dep = deps[ i ];
if ( startsWith( dep, '@stdlib' ) ) {
if (
!contains( dep, '_tools' ) &&
( !contains( dep, 'plot' ) || dep === '@stdlib/plot' )
) {
if ( useGitHub ) {
out.dependencies[ dep ] = 'github:stdlib-js/' + replace( dep, '@stdlib/', '' ) + '#main';
} else {
out.dependencies[ dep ] = memoizedNPMversionForDeps( dep );
}
}
} else {
out.dependencies[ dep ] = mainJSON.dependencies[ dep ];
}
}
for ( i = 0; i < devDeps.length; i++ ) {
dep = devDeps[ i ];
if (
!contains( deps, dep )
) {
if (
startsWith( dep, '@stdlib' )
) {
if (
!contains( dep, '_tools' ) &&
( !contains( dep, 'plot' ) || dep === '@stdlib/plot' )
) {
if ( useGitHub ) {
out.devDependencies[ dep ] = 'github:stdlib-js/' + replace( dep, '@stdlib/', '' ) + '#main';
} else {
out.devDependencies[ dep ] = memoizedNPMversionForDevDeps( dep );
}
}
} else {
mainVersion = mainJSON.devDependencies[ dep ];
out.devDependencies[ dep ] = mainVersion;
}
}
}
return out;
}
/**
* Cleans up the `gh-pages` cache directory.
*
* @private
* @returns {void}
*/
function cleanCache() {
var command = 'rm -rf '+join( mainDir, 'node_modules', '.cache', 'gh-pages' );
console.log( 'Clean-up cached gh-pages files: %s', command );
console.log( shell( command ).toString() );
}
/**
* Returns a section for the main project to be appended to the standalone package README.md files.
*
* @private
* @param {boolean} customLicense - boolean indicating whether the standalone package contains a custom license file
* @param {string} branch - branch for build status badge
* @param {boolean} hasBundles - boolean indicating whether the standalone package contains browser bundles
* @param {boolean} hasCLI - boolean indicating whether the standalone package contains a CLI
* @returns {string} main repo section
*/
function mainRepoSection( customLicense, branch, hasBundles, hasCLI ) {
/* eslint-disable function-call-argument-newline, function-paren-newline */
var out = [
'',
'<section class="main-repo" >',
'',
'* * *',
'',
'## Notice',
'',
'This package is part of [stdlib][stdlib], a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing. The library provides a collection of robust, high performance libraries for mathematics, statistics, streams, utilities, and more.',
'',
'For more information on the project, filing bug reports and feature requests, and guidance on how to develop [stdlib][stdlib], see the main project [repository][stdlib].',
'',
'#### Community',
'',
'[![Chat][chat-image]][chat-url]',
'',
'---'
];
if ( !customLicense ) {
out.push(
'',
'## License',
'',
'See [LICENSE][stdlib-license].',
''
);
}
out.push(
'',
'## Copyright',
'',
'Copyright © 2016-'+CURRENT_YEAR+'. The Stdlib [Authors][stdlib-authors].',
'',
'</section>',
'',
'<!-- /.stdlib -->',
'',
'<!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->',
'',
'<section class="links">',
'',
'[npm-image]: http://img.shields.io/npm/v/@stdlib/<pkg>.svg',
'[npm-url]: https://npmjs.org/package/@stdlib/<pkg>',
'',
'[test-image]: https://github.com/stdlib-js/<pkg>/actions/workflows/test.yml/badge.svg?branch=' + branch,
'[test-url]: https://github.com/stdlib-js/<pkg>/actions/workflows/test.yml?query=branch:' + branch,
'',
'[coverage-image]: https://img.shields.io/codecov/c/github/stdlib-js/<pkg>/main.svg',
'[coverage-url]: https://codecov.io/github/stdlib-js/<pkg>?branch=main',
'',
'<!--',
'',
'[dependencies-image]: https://img.shields.io/david/stdlib-js/<pkg>.svg',
'[dependencies-url]: https://david-dm.org/stdlib-js/<pkg>/main',
'',
'-->',
'',
'[chat-image]: https://img.shields.io/gitter/room/stdlib-js/stdlib.svg',
'[chat-url]: https://app.gitter.im/#/room/#stdlib-js_stdlib:gitter.im',
'',
'[stdlib]: https://github.com/stdlib-js/stdlib',
'',
'[stdlib-authors]: https://github.com/stdlib-js/stdlib/graphs/contributors'
);
if ( hasCLI ) {
out.push(
'',
'[cli-section]: https://github.com/stdlib-js/<pkg>#cli',
'[cli-url]: https://github.com/stdlib-js/<pkg>/tree/cli',
'[@stdlib/<pkg>]: https://github.com/stdlib-js/<pkg>'
);
}
if ( hasBundles ) {
out.push(
'',
'[umd]: https://github.com/umdjs/umd',
'[es-module]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules',
'',
'[deno-url]: https://github.com/stdlib-js/<pkg>/tree/deno',
'[deno-readme]: https://github.com/stdlib-js/<pkg>/blob/deno/README.md',
'[umd-url]: https://github.com/stdlib-js/<pkg>/tree/umd',
'[umd-readme]: https://github.com/stdlib-js/<pkg>/blob/umd/README.md',
'[esm-url]: https://github.com/stdlib-js/<pkg>/tree/esm',
'[esm-readme]: https://github.com/stdlib-js/<pkg>/blob/esm/README.md',
'[branches-url]: https://github.com/stdlib-js/<pkg>/blob/main/branches.md'
);
}
if ( !customLicense ) {
out.push(
'',
'[stdlib-license]: https://raw.githubusercontent.com/stdlib-js/<pkg>/main/LICENSE'
);
}
return out.join( '\n' );
/* eslint-enable function-call-argument-newline, function-paren-newline */
}
/**
* Creates a list of GitHub topics.
*
* @private
* @param {StringArray} words - list of keywords
* @returns {StringArray} list of topics
*/
function createTopics( words ) {
var word;
var out;
var i;
out = [];
for ( i = 0; i < words.length; i++ ) {
word = words[ i ];
if (
!startsWith( word, 'std' ) &&
word.length <= 35 // GitHub topics may not have more than 35 characters
) {
word = replace( word, ' ', '-' ); // GitHub topics may not include spaces, but allow hyphens
if ( RE_ALLOWED_TOPIC_CHARS.test( word ) ) {
out.push( word );
}
}
}
return BASIC_GITHUB_TOPICS.concat( out ).slice( 0, 20 ); // GitHub repositories may not have more than 20 topics
}
/**
* Function invoked upon replacing the topics of a repository.
*
* @private
* @param {(Error|null)} error - encountered error
* @param {Object} data - response data
* @param {Object} info - response info
* @returns {void}
*/
function onTopics( error, data, info ) {
if ( error ) {
return console.error( error );
}
console.log( 'Replaced topics for repository.' );
console.log( 'Response data: '+JSON.stringify( data ) );
console.log( 'Rate limit: '+JSON.stringify( info ) );
}
/**
* Publishes a package to the respective GitHub repository.
*
* @private
* @param {string} pkg - package name
* @param {Function} clbk - callback function
* @throws {Error} no input files
* @returns {void}
*/
function publish( pkg, clbk ) {
var fmtProdMsgVersion;
var triggerRelease;
var customLicense;
var isTopLevelNS;
var workflowPath;
var ghpagesOpts;
var jscodeshift;
var pkgJsonPath;
var releaseType;
var extractCLI;
var repoExists;
var readmePath;
var noBundles;
var changelog;
var contents;
var mainJSON;
var schedule;
var workflow;
var command;
var devDeps;
var distPkg;
var pkgJSON;
var version;
var badges;
var branch;
var nLines;
var readme;
var mdPath;
var about;
var alias;
var deps;
var dist;
var file;
var opts;
var src;
var pth;
var i;
src = join( mainDir, 'lib/node_modules', '@stdlib', pkg );
distPkg = replace( pkg, /\//g, '-' );
pth = 'https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/'+pkg;
dist = join( mainDir, 'build', '@stdlib', distPkg );
command = 'git ls-remote https://'+ ENV.GITHUB_TOKEN + '@github.com/stdlib-js/'+distPkg+'.git main';
try {
shell( command );
repoExists = true;
} catch ( error ) {
console.error( 'Encountered an error when attempting to check whether the repository exists. Error: %s', error.message );
repoExists = false;
}
command = 'git ls-remote --tags --sort="v:refname" https://'+ ENV.GITHUB_TOKEN + '@github.com/stdlib-js/'+distPkg+'.git | grep -E \'v[0-9]+.[0-9]+.[0-9]+\'';
debug( 'Executing command to retrieve last version: %s', command );
try {
command = shell( command ).toString();
version = substringAfterLast( command, '/' );
version = replace( version, /[-a-z.]*\^{}/, '' );
version = trim( removeFirst( version ) ); // Remove leading `v`...
} catch ( error ) {
console.error( 'Encountered an error when attempting to retrieve the last version. Error: %s', error.message );
}
if ( !version ) {
version = '0.0.0';
}
else if ( flags[ 'only-unpublished' ] ) {
// Case: the package has already been published (as indicated by the presence of a version tag) and the `--only-unpublished` flag is set, so we skip the package...
return invokeCallback( null, 'skipped' );
}
changelog = generateChangelog( '@stdlib/'+pkg, flags[ 'release-type' ] );
releaseType = changelog.releaseType;
mainJSON = readJSON( join( mainDir, 'package.json' ) );
console.log( 'Creating directory and copying source files...' );
command = 'mkdir -p '+dist;
debug( 'Creating build directory: %s', command );
shell( command );
isTopLevelNS = !contains( pkg, '/' );
if ( isTopLevelNS ) {
// Copy all files and subdirectories:
command = 'cp -r '+src+'/* '+dist;
}
else {
// Do not copy nested packages which will instead be pulled in as separate dependencies:
command = 'rsync -r --ignore-missing-args --include=\'benchmark/***\' --include=\'bin/***\' --include=\'data/***\' --include=\'docs/***\' --include=\'etc/***\' --include=\'examples/***\' --include=\'lib/***\' --include=\'include/***\' --include=\'scripts/***\' --include=\'src/***\' --include=\'static/***\' --include=\'test/***\' --exclude=\'*/***\' '+src+'/*** '+dist;
}
debug( 'Copying files: %s', command );
shell( command );
debug( 'Copying configuration files...' );
for ( i = 0; i < DOTFILES.length; i++ ) {
file = DOTFILES[ i ];
fs.copyFileSync( join( mainDir, file ), join( dist, file ) );
}
if ( existsSync( join( dist, 'LICENSE' ) ) ) {
customLicense = true;
} else {
fs.copyFileSync( join( __dirname, 'templates', 'license_apache2.txt' ), join( dist, 'LICENSE' ) );
command = [
'# Extract custom licenses from all descendant packages:',
'find '+src+' -type f -name "LICENSE" -exec cat {} \\; > LICENSE.tmp',
'',
'# Check whether LICENSE.tmp is empty:',
'if [ -s LICENSE.tmp ]; then',
'',
' # Attach attribution notice to LICENSE file:',
' cat '+dist+'/LICENSE '+join( __dirname, 'templates', 'license_attribution.txt' )+' LICENSE.tmp > LICENSE.out',
'',
' # Remove duplicate licenses, i.e., multiline strings:',
' awk -v RS= \'!x[$0]++{print; print ""}\' LICENSE.out > LICENSE.tmp',
'',
' # Move LICENSE.tmp to LICENSE:',
' mv LICENSE.tmp '+dist+'/LICENSE',
'',
' # Remove temporary file:',
' rm LICENSE.out',
'fi'
].join( '\n' );
shell( command );
customLicense = false;
}
fs.copyFileSync( join( __dirname, 'templates', '.npmignore.txt' ), join( dist, '.npmignore' ) );
fs.copyFileSync( join( __dirname, 'templates', 'Makefile.txt' ), join( dist, 'Makefile' ) );
fs.copyFileSync( join( __dirname, 'templates', '.eslintrc.js.txt' ), join( dist, '.eslintrc.js' ) );
writeFileSync( join( dist, 'CHANGELOG.md' ), changelog.content );
fs.copyFileSync( join( __dirname, 'templates', 'SECURITY.md.txt' ), join( dist, 'SECURITY.md' ) );
pkgJsonPath = join( dist, 'package.json' );
pkgJSON = readJSON( pkgJsonPath );
pkgJSON.name = '@stdlib/'+distPkg;
// Check if the package should not contain browser bundles:
noBundles = pkgJSON[ '__stdlib__' ] &&
pkgJSON[ '__stdlib__' ][ 'envs' ] &&
( pkgJSON[ '__stdlib__' ][ 'envs' ][ 'browser' ] === false );
if ( isTopLevelNS ) {
deps = namespaceDeps( '@stdlib/'+pkg, {
'level': 1,
'dev': false
});
deps = name2standalone( deps );
devDeps = namespaceDeps( '@stdlib/'+pkg, {
'level': 1,
'dev': true
});
devDeps = name2standalone( devDeps );
} else {
deps = depList( '@stdlib/'+pkg, {
'dev': false
});
deps = name2standalone( deps );
devDeps = depList( '@stdlib/'+pkg, {
'dev': true
});
devDeps = name2standalone( devDeps );
}
command = 'grep -r proxyquire '+dist+' | wc -l';
debug( 'Count the number of lines including `proxyquire`: %s', command );
nLines = shell( command ).toString();
if ( parseInt( nLines, 10 ) > 0 && !contains( devDeps, 'proxyquire' ) ) {
// Case: `proxyquire` is used outside of package code, e.g. in test fixtures, and has to be separately included in the list of development dependencies
devDeps.push( 'proxyquire' );
}
triggerRelease = (
releaseType === 'patch' ||
releaseType === 'minor' ||
releaseType === 'major'
);
if ( triggerRelease ) {
version = semver.inc( version, releaseType );
}
debug( 'Copying and populating README.md file...' );
readmePath = join( dist, 'README.md' );
readme = readFileSync( readmePath, 'utf-8' );
extractCLI = !isTopLevelNS && RE_CLI_USAGE_SECTION.test( readme );
readme = replace( readme, RE_CLI_USAGE_SECTION, replacer );
readme = replace( readme, RE_C_USAGE_SECTION, replacer );
readme = replace( readme, RE_USAGE_SECTION, replacer );
about = readFileSync( join( __dirname, 'templates', 'about_details.txt' ), 'utf-8' );
readme = replace( readme, /\n#/, '\n\n'+about+'\n\n#' );
badges = '[![NPM version][npm-image]][npm-url]';
badges += ' ';
if ( contains( devDeps, 'tape' ) ) {
badges += '[![Build Status][test-image]][test-url]';
badges += ' ';
badges += '[![Coverage Status][coverage-image]][coverage-url]';
badges += ' ';
}
badges += '<!-- ';
badges += '[![dependencies][dependencies-image]][dependencies-url]';
badges += ' -->';
readme = replace( readme, /\n>/, '\n'+badges+'\n\n>' );
readme = replace( readme, '\'@stdlib/'+pkg, '\'@stdlib/'+distPkg );
branch = ( triggerRelease ) ? 'v'+version : 'main';
if ( contains( readme, '<section class="links">' ) ) {
readme = replace( readme, '<section class="links">', mainRepoSection( customLicense, branch, !noBundles, extractCLI ) );
} else {
readme += mainRepoSection( customLicense, branch, !noBundles, extractCLI );
readme += '\n\n';
readme += '</section>';
readme += '\n\n';
readme += '<!-- /.links -->';
}
readme = replace( readme, '<pkg>', distPkg );
writeFileSync( readmePath, readme );
opts = {
'cwd': dist
};
command = [
'find . -type f -name \'*.md\' -print0 ', // Find all regular Markdown files in the destination directory and print their full names to standard output...
'| xargs -0 ', // Convert standard input to the arguments for following `sed` command...
'sed -Ei ', // Edit files in-place without creating a backup...
'\'s/',
'(@stdlib\\/'+distPkg+')([^:]*)\\]: https.*$', // Match start of internal package link until end of line...
'/',
'\\1\\2]: https:\\/\\/github.com\\/stdlib-js\\/'+distPkg+'\\/tree\\/main\\2', // Replacement string generated via back-referencing the two created capture groups...
'/g\'' // Replace all occurrences and not just the first...
].join( '' );
debug( 'Executing command: %s', command );
shell( command, opts );
command = [
'find . -type f -name \'*.md\' -print0 ', // Find all regular Markdown files in the destination directory and print their full names to standard output...
'| xargs -0 ', // Convert standard input to the arguments for following `sed` command...
'sed -Ei ', // Edit files in-place without creating a backup...
'"/',
'^[^:]+: https:\\/\\/github.com\\/stdlib-js\\/stdlib\\/tree\\/develop\\/lib\\/node_modules\\/%40stdlib\\/', // Match start of external `@stdlib` package link (as internal ones are already processed) until end of line...
'/ ',
[
'{',
' h', // Copy pattern space to hold space...
' s/:.*/: https:\\/\\/github.com\\/stdlib-js\\//', // Replace everything after the colon in the matched pattern with the beginning of new replacement URL...
' x', // Exchange the contents of the hold and pattern spaces...
' s/[^:]+: https:\\/\\/github.com\\/stdlib-js\\/stdlib\\/tree\\/develop\\/lib\\/node_modules\\/%40stdlib\\///', // Remove everything up to the beginning of the existing main project URL in the pattern space...
' s/\\//-/g', // Replace all occurrences of `/` with `-`...
' H', // Append pattern space to hold space...
' g', // Copy hold space to pattern space...
' s/\\n//', // Remove newline character added when appending pattern space to hold space
'}'
].join( '\n' ),
'"'
].join( '' );
debug( 'Executing command: %s', command );
shell( command, opts );
if ( isTopLevelNS ) {
// Rewrite internal packages as relative paths outside of documentation:
for ( i = 0; i < MAX_TREE_DEPTH; i++ ) {
command = [
'find . -mindepth '+(1+i)+' -maxdepth '+(2+i)+' -type f \\( -name \'*.[jt]s\' \\) -print0 ', // Find all JavaScript and TypeScript files in the destination directory at the respective depth and print their full names to standard output...
'| xargs -0 ', // Convert standard input to the arguments for following `sed` command...
'sed -Ei ', // Edit files in-place without creating a backup...
'"/',
'\'@stdlib\\/types', // Skip over `@stdlib/types`...
'/b; ',
'/',
'^[^\\*].+\'@stdlib\\/'+pkg, // Match internal packages outside of JSDoc comments...
'/',
[
'{',
' s/\'@stdlib\\/'+pkg+'(.+)/\'.'+repeat( '\\/..', i+1 )+'\\1/', // Replace the start of internal package requires with a relative path of the respective depth
'}'
].join( '\n' ),
'"'
].join( '' );
debug( 'Executing command: %s', command );
try {
shell( command, opts );
} catch ( err ) {
// Break out of loop in case of no input files...
debug( 'Encountered an error: %s', err.message );
break;
}
}
}
else {
command = [
'find . -type f \\( -name \'*.[jt]s\' -o -name \'*.md\' -o -name \'cli\' -o -name \'*.js.txt\' \\) -print0 ', // Find all JavaScript and TypeScript files in the destination directory and print their full names to standard output...
'| xargs -0 ', // Convert standard input to the arguments for following `sed` command...
'sed -Ei ', // Edit files in-place without creating a backup...
'"/',
'\'@stdlib\\/types', // Skip over `@stdlib/types`...
'/b; ',
'/',
'\\/\\/ returns', // Skip over `// returns` annotations...
'/b; ',
'/',
'\'@stdlib\\/', // Match `@stdlib` packages...
'/ ',
[
'{',
' h', // Copy pattern space to hold space...
' s/^.+(\'.*$)/\\1/', // Remove everything before the last single quote
' x', // Exchange the contents of the hold and pattern spaces...
' s/\'[^\']*$//', // Remove everything after the last single quote
' s/\\//-/2g', // Replace any but the first occurrence of `/` with `-`...
' s/-data-([^\']*[.][^\']*)/\\/data\\/\\1/', // Revert back to backslashes for part of require path loading files from a package's `data` directory
' G', // Append hold space to pattern space...
' s/\\n//', // Remove newline character added when appending hold space to pattern space
'}'
].join( '\n' ),
'"'
].join( '' );
debug( 'Executing command: %s', command );
shell( command, opts );
// Rewrite related packages in READMEs to point to standalone packages:
command = [
'find . -type f -name \'*.md\' ', // Find all Markdown files in the destination directory and print their full names to standard output...
'-exec ', // Convert standard input to the arguments for following `sed` command...
'sed -i ', // Edit files in-place...
'\'',
's/`@stdlib\\/\\([^/]*\\)\\/\\(.*\\)/`@stdlib\\/\\1-\\2/g', // Replace all forward slashes in package names except the first one...
'\'',
' {} +'
].join( '' );
debug( 'Executing command: %s', command );
shell( command, opts );
command = [
'find . -type f -name \'*.js\' -print0 ', // Find all JavaScript files in the destination directory and print their full names to standard output...
'| xargs -0 ', // Convert standard input to the arguments for following `sed` command...
'sed -Ei ', // Edit files in-place without creating a backup...
'"/',
'@module @stdlib\\/', // Match @stdlib packages in JSDoc @module comment...
'/s/',
'\\/',
'/',
'-',
'/2g"' // Replace all forward slashes in package name except the first one...
].join( '' );
debug( 'Executing command: %s', command );
shell( command, opts );
command = [
'find . -type f -name \'include.gypi\' -print0 ', // Find all `include.gypi` files in the destination directory and print their full names to standard output...
'| xargs -r -0 ', // Convert standard input to the arguments for following `sed` command...
'sed -Ei ', // Edit files in-place without creating a backup...
'"s/',
'@stdlib\\/utils\\/library-manifest',
'/',
'@stdlib\\/utils-library-manifest', // Replace with standalone `library-manifest` package
'/"'
].join( '' );
debug( 'Executing command: %s', command );
shell( command, opts );
command = [
'find . -type f -name \'manifest.json\' -print0 ', // Find all `manifest.json` files in the destination directory and print their full names to standard output...
'| xargs -r -0 ', // Convert standard input to the arguments for following `sed` command if `find` returns output...
'sed -Ei ', // Edit files in-place without creating a backup...
'"/',
'@stdlib\\/[^ ]+', // Match @stdlib package names in dependencies
'/s/',
'\\/',
'/',
'-',
'/2g"' // Replace all forward slashes in package names except the first one...
].join( '' );
debug( 'Executing command: %s', command );
shell( command, opts );
}
pkgJSON.homepage = 'https://stdlib.io';
pkgJSON.repository = {
'type': 'git',
'url': 'git://github.com/stdlib-js/'+distPkg+'.git'
};
// Ensure `npm install` does not automatically build a native add-on...
if ( pkgJSON.gypfile ) {
// TODO: consider removing this once we have determined our native add-on story for individual packages
pkgJSON.gypfile = false;