-
Notifications
You must be signed in to change notification settings - Fork 463
/
jslint_ci.sh
3650 lines (3535 loc) · 102 KB
/
jslint_ci.sh
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
#!/bin/sh
## The Unlicense
##
## This is free and unencumbered software released into the public domain.
##
## Anyone is free to copy, modify, publish, use, compile, sell, or
## distribute this software, either in source code form or as a compiled
## binary, for any purpose, commercial or non-commercial, and by any
## means.
##
## In jurisdictions that recognize copyright laws, the author or authors
## of this software dedicate any and all copyright interest in the
## software to the public domain. We make this dedication for the benefit
## of the public at large and to the detriment of our heirs and
## successors. We intend this dedication to be an overt act of
## relinquishment in perpetuity of all present and future rights to this
## software under copyright law.
##
## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
## EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
## MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
## IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
## OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
## ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
## OTHER DEALINGS IN THE SOFTWARE.
# POSIX reference
# http://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html
# http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html
# sh one-liner
# git add .; npm run test2; git checkout .
# git branch -d -r origin/aa
# git config --global diff.algorithm histogram
# git fetch --prune
# git fetch origin alpha beta master && git fetch upstream alpha beta master
# git fetch origin alpha beta master --tags
# git fetch upstream "refs/tags/*:refs/tags/*"
# git ls-files --stage | sort
# git ls-remote --heads origin
# git update-index --chmod=+x aa.js
# head CHANGELOG.md -n50
# ln -f jslint.mjs ~/jslint.mjs
# openssl rand -base64 32 # random key
# sh jslint_ci.sh shRunWithScreenshotTxt .artifact/screenshot_changelog.svg head -n50 CHANGELOG.md
# vim rgx-lowercase \L\1\e
# charset - ascii
# \u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007
# \b\t\n\u000b\f\r\u000e\u000f
# \u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017
# \u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f
# !\"#$%&'()*+,-./0123456789:;<=>?
# @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_
# `abcdefghijklmnopqrstuvwxyz{|}~\u007f
shBashrcDebianInit() {
# This function will init debian:stable /etc/skel/.bashrc.
# https://sources.debian.org/src/bash/4.4-5/debian/skel.bashrc/
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples
# If not running interactively, don't do anything
case $- in
*i*) ;;
*) return;;
esac
# don't put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth
# append to the history file, don't overwrite it
shopt -s histappend
# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000
HISTFILESIZE=2000
# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize
# If set, the pattern "**" used in a pathname expansion context will
# match all files and zero or more directories and subdirectories.
#shopt -s globstar
# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"
# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
debian_chroot=$(cat /etc/debian_chroot)
fi
# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
xterm-color|*-256color) color_prompt=yes;;
esac
# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
#force_color_prompt=yes
if [ -n "$force_color_prompt" ]; then
if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
# We have color support; assume it's compliant with Ecma-48
# (ISO/IEC-6429). (Lack of such support is extremely rare, and such
# a case would tend to support setf rather than setaf.)
color_prompt=yes
else
color_prompt=
fi
fi
if [ "$color_prompt" = yes ]; then
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt
# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
;;
*)
;;
esac
# enable color support of ls and also add handy aliases
if [ -x /usr/bin/dircolors ]; then
test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
alias ls='ls --color=auto'
#alias dir='dir --color=auto'
#alias vdir='vdir --color=auto'
alias grep='grep --color=auto'
#alias fgrep='fgrep --color=auto'
#alias egrep='egrep --color=auto'
fi
# colored GCC warnings and errors
#export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'
# some more ls aliases
alias ll='ls -alF'
#alias la='ls -A'
#alias l='ls -CF'
# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if ! shopt -oq posix; then
if [ -f /usr/share/bash-completion/bash_completion ]; then
. /usr/share/bash-completion/bash_completion
elif [ -f /etc/bash_completion ]; then
. /etc/bash_completion
fi
fi
}
shBashrcWindowsInit() {
# This function will init windows-environment.
case "$(uname)" in
CYGWIN*)
;;
MINGW*)
;;
MSYS*)
;;
*)
return
;;
esac
# alias curl.exe
# if (! alias curl 2>/dev/null) && [ -f c:/windows/system32/curl.exe ]
# then
# alias curl=c:/windows/system32/curl.exe
# fi
# alias node.exe
if (! alias node 2>/dev/null)
then
alias node=node.exe
fi
}
shBrowserScreenshot() {(set -e
# This function will run headless-chrome to screenshot url $1.
node --input-type=module --eval '
import moduleChildProcess from "child_process";
import moduleFs from "fs";
import moduleOs from "os";
import modulePath from "path";
import moduleUrl from "url";
(async function () {
let child;
let exitCode;
let file;
let timeStart;
let tmpdir;
let url;
if (process.platform !== "linux") {
return;
}
timeStart = Date.now();
url = process.argv[1];
if (!(
/^\w+?:/
).test(url)) {
url = modulePath.resolve(url);
}
file = moduleUrl.parse(url).pathname;
// remove prefix $PWD from file
if (String(file + "/").startsWith(process.cwd() + "/")) {
file = file.replace(process.cwd(), "");
}
file = ".artifact/screenshot_browser_" + encodeURIComponent(file).replace((
/%/g
), "_").toLowerCase() + ".png";
tmpdir = await moduleFs.promises.mkdtemp(
moduleOs.tmpdir() + "/shBrowserScreenshot-"
);
child = moduleChildProcess.spawn(
(
process.platform === "darwin"
? "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
: process.platform === "win32"
? "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"
: "/usr/bin/google-chrome-stable"
),
[
"--headless",
"--ignore-certificate-errors",
"--incognito",
"--screenshot",
"--timeout=30000",
"--user-data-dir=" + tmpdir,
"--window-size=800x600",
"-screenshot=" + file,
(
(process.getuid && process.getuid() === 0)
? "--no-sandbox"
: ""
),
url
].concat(process.argv.filter(function (elem) {
return elem.startsWith("-");
})).filter(function (elem) {
return elem;
}),
{stdio: ["ignore", 1, 2]}
);
exitCode = await new Promise(function (resolve) {
child.on("exit", resolve);
});
await moduleFs.promises.rm(tmpdir, {recursive: true});
console.error(
"shBrowserScreenshot"
+ "\n - url - " + url
+ "\n - wrote - " + file
+ "\n - timeElapsed - " + (Date.now() - timeStart) + " ms"
+ "\n - EXIT_CODE=" + exitCode
);
}());
' "$@" # '
)}
shCiArtifactUpload() {(set -e
# This function will upload build-artifacts to branch-gh-pages.
# shCiArtifactUploadCustom() {(set -e
# # This function will run custom-code to upload build-artifacts.
# return
# )}
if ! (shCiMatrixIsmainName \
&& [ -f package.json ] \
&& grep -q '^ "shCiArtifactUpload": 1,$' package.json)
then
return
fi
mkdir -p .artifact
# init .git/config
git config --local user.email "[email protected]"
git config --local user.name "github-actions"
# init $GITHUB_BRANCH0
export GITHUB_BRANCH0="$(git rev-parse --abbrev-ref HEAD)"
git pull --unshallow origin "$GITHUB_BRANCH0"
# init $UPSTREAM_XXX
export UPSTREAM_REPOSITORY="$(node -p '(
/^(?:git\+)?https:\/\/github\.com\/([^\/]*?\/[^.]*?)\.git$/
).exec(require("./package.json").repository.url)[1]
')" # '
export UPSTREAM_GITHUB_IO="$(
printf "$UPSTREAM_REPOSITORY" | sed -e "s|/|.github.io/|"
)"
# init $GITHUB_XXX
export GITHUB_REPOSITORY="${GITHUB_REPOSITORY:-$UPSTREAM_REPOSITORY}"
export GITHUB_GITHUB_IO="$(
printf "$GITHUB_REPOSITORY" | sed -e "s|/|.github.io/|"
)"
# screenshot changelog and files
node --input-type=module --eval '
import moduleChildProcess from "child_process";
(function () {
[
// parallel-task - screenshot changelog
[
"jslint_ci.sh",
"shRunWithScreenshotTxt",
".artifact/screenshot_changelog.svg",
"head",
"-n50",
"CHANGELOG.md"
],
// parallel-task - screenshot files
[
"jslint_ci.sh",
"shRunWithScreenshotTxt",
".artifact/screenshot_package_listing.svg",
"shGitLsTree"
],
// parallel-task - screenshot logo
[
"jslint_ci.sh",
"shImageLogoCreate"
]
].forEach(function (argList) {
moduleChildProcess.spawn(
"sh",
argList,
{stdio: ["ignore", 1, 2]}
).on("exit", function (exitCode) {
if (exitCode) {
process.exit(exitCode);
}
});
});
}());
' "$@" # '
if (command -v shCiArtifactUploadCustom >/dev/null)
then
shCiArtifactUploadCustom
fi
# 1px-border around browser-screenshot
if (ls .artifact/screenshot_browser_*.png 2>/dev/null \
&& mogrify -version 2>&1 | grep -i imagemagick)
then
mogrify -shave 1x1 -bordercolor black -border 1 \
.artifact/screenshot_browser_*.png
fi
# add dir .artifact
git add -f .artifact
git rm --cached -r .artifact/tmp 2>/dev/null || true
git commit -am "add dir .artifact"
# checkout branch-gh-pages
git fetch origin gh-pages
git checkout -b gh-pages origin/gh-pages
# update dir branch-$GITHUB_BRANCH0
rm -rf "branch-$GITHUB_BRANCH0"
git clone . "branch-$GITHUB_BRANCH0" --branch="$GITHUB_BRANCH0"
rm -rf "branch-$GITHUB_BRANCH0/.git"
# add dir branch-$GITHUB_BRANCH0
git add -f "branch-$GITHUB_BRANCH0"
# update root-dir with branch-beta
if [ "$GITHUB_BRANCH0" = beta ]
then
rm -rf .artifact
git checkout beta .
# update apidoc.html
for FILE in apidoc.html
do
if [ -f ".artifact/$FILE" ]
then
cp -a ".artifact/$FILE" .
git add -f "$FILE"
fi
done
fi
# update README.md with branch-$GITHUB_BRANCH0 and $GITHUB_REPOSITORY
sed -i \
-e "s|/branch-[a-z]*/|/branch-$GITHUB_BRANCH0/|g" \
-e "s|\\b$UPSTREAM_GITHUB_IO\\b|$GITHUB_GITHUB_IO|g" \
-e "s|\\b$UPSTREAM_REPOSITORY\\b|$GITHUB_REPOSITORY|g" \
-e "s|_2fbranch-[a-z]*_2f|_2fbranch-${GITHUB_BRANCH0}_2f|g" \
"branch-$GITHUB_BRANCH0/README.md"
git status
# git push
shGitCommitPushOrSquash "" 50
# list files
shGitLsTree
# validate http-links
(
cd "branch-$GITHUB_BRANCH0"
sleep 15
shDirHttplinkValidate
)
)}
shCiBase() {(set -e
# This function will run base-ci.
# shCiBaseCustom() {(set -e
# # This function will run custom-code for base-ci.
# return
# )}
# shCiLintCustom() {(set -e
# # This function will run custom-code to lint files.
# )}
export GITHUB_BRANCH0="$(git rev-parse --abbrev-ref HEAD)"
# Auto-correct common errors in package.json.
npm pkg fix
# validate package.json.fileCount
node --input-type=module --eval '
import moduleFs from "fs";
globalThis.assert(
JSON.parse(
moduleFs.readFileSync("package.json") //jslint-ignore-line
).fileCount === Number(process.argv[1]),
`package.json.fileCount !== ${process.argv[1]}`
);
' "$(git ls-tree -r HEAD | wc -l)" # '
# update version in README.md, jslint.mjs, package.json from CHANGELOG.md
if [ "$(git branch --show-current)" = alpha ]
then
node --input-type=module --eval '
import moduleChildProcess from "child_process";
import moduleFs from "fs";
(async function () {
let fileDict = {};
let fileMain;
let fileModified;
let packageJson;
let versionBeta;
let versionMaster;
await Promise.all([
"CHANGELOG.md",
"README.md",
"package.json"
].map(async function (file) {
fileDict[file] = await moduleFs.promises.readFile(file, "utf8");
if (file === "package.json") {
packageJson = JSON.parse(fileDict[file]);
fileMain = packageJson.module || packageJson.main || "package.json";
fileDict[fileMain] = (
await moduleFs.promises.readFile(fileMain, "utf8")
);
}
}));
Array.from(fileDict["CHANGELOG.md"].matchAll(
/\n\n# v(\d\d\d\d\.\d\d?\.\d\d?(-.*?)?)\n/g
)).slice(0, 2).forEach(function ([
ignore, version, isBeta
]) {
versionBeta = versionBeta || version;
versionMaster = versionMaster || (!isBeta && version);
});
await Promise.all([
{
file: "README.md",
src: fileDict["README.md"].replace((
/(\[(?:main|master)<br>\()v\d\d\d\d\.\d\d?\.\d\d?\b/g
), `$1v${versionMaster}`)
}, {
file: "package.json",
src: fileDict["package.json"].replace((
/ "version": "\d\d\d\d\.\d\d?\.\d\d?(?:-.*?)?"/
), ` "version": "${versionBeta}"`)
}, {
file: fileMain,
// update version
src: fileDict[fileMain].replace((
/^let version = ".*?";$/m
), `let version = "v${versionBeta}";`)
}
].map(async function ({
file,
src
}) {
let src0 = fileDict[file];
if (src !== src0) {
console.error(`update file ${file}`);
fileModified = file;
await moduleFs.promises.writeFile(file, src);
}
}));
if (fileModified) {
moduleChildProcess.spawn(
"git",
["diff"],
{stdio: ["ignore", 1, 2]}
).on("exit", function () {
throw new Error("modified file " + fileModified);
});
}
}());
' "$@" # '
fi
# update table-of-contents in README.md
node --input-type=module --eval '
import moduleFs from "fs";
(async function () {
let data = await moduleFs.promises.readFile("README.md", "utf8");
data = data.replace((
/\n# Table of Contents$[\S\s]*?\n\n\n/m
), function () {
let ii = -1;
let toc = "\n# Table of Contents\n";
data.replace((
/((?:\n{3,}|\n+?(?:<br>)+?\n+?)(?:#|###|#####)) (\S.*)/g
), function (match0, level, title) {
if (title === "Table of Contents") {
ii += 1;
return "";
}
if (ii < 0) {
return "";
}
switch (level) {
case "\n\n<br>\n\n#####":
toc += " - [" + title + "](#";
break;
case "\n\n\n<br><br>\n#":
ii += 1;
toc += "\n" + ii + ". [" + title + "](#";
break;
case "\n\n\n<br><br>\n###":
toc += " - [" + title + "](#";
break;
default:
throw new Error(JSON.stringify(match0));
}
toc += title.toLowerCase().replace((
/[^ \-0-9A-Z_a-z]/g
), "").replace((
/ /g
), "-") + ")\n";
return "";
});
toc += "\n\n";
return toc;
});
await moduleFs.promises.writeFile("README.md", data);
}());
' "$@" # '
JSLINT_BETA=1 node jslint.mjs .
if (command -v shCiLintCustom >/dev/null)
then
shCiLintCustom
fi
if (command -v shCiLintCustom2 >/dev/null)
then
shCiLintCustom2
fi
if (command -v shCiBaseCustom >/dev/null)
then
shCiBaseCustom
fi
if (command -v shCiBaseCustom2 >/dev/null)
then
shCiBaseCustom2
fi
git diff
)}
shCiMatrixIsmainName() {(set -e
# This function will return 0 if current ci-job is main job.
CI_MATRIX_NAME="$(printf "$CI_MATRIX_NAME" | xargs)"
[ "$CI_MATRIX_NAME" ] && [ "$CI_MATRIX_NAME" = "$CI_MATRIX_NAME_MAIN" ]
)}
shCiMatrixIsmainNodeversion() {(set -e
# This function will return 0 if current ci-job is main job.
[ "$CI_MATRIX_NODE_VERSION" ] \
&& [ "$CI_MATRIX_NODE_VERSION" = "$CI_MATRIX_NODE_VERSION_MAIN" ]
)}
shCiPre() {(set -e
# This function will run pre-ci.
# shCiPreCustom() {(set -e
# # This function will run custom-code for pre-ci.
# return
# )}
if [ -f ./myci2.sh ]
then
. ./myci2.sh :
shMyciInit
fi
if (command -v shCiPreCustom >/dev/null)
then
shCiPreCustom
fi
if (command -v shCiPreCustom2 >/dev/null)
then
shCiPreCustom2
fi
)}
shCiPublishNpm() {(set -e
# This function will publish npm-package.
# shCiPublishNpmCustom() {(set -e
# # This function will run custom-code to publish npm-package.
# # npm publish --access public
# )}
if ! ([ -f package.json ] \
&& grep -q '^ "shCiPublishNpm": 1,$' package.json)
then
return
fi
# init package.json for npm-publish
npm install
# update package-name
if [ "$NPM_REGISTRY" = github ]
then
sed -i \
"s|^ \"name\":.*| \"name\": \"@$GITHUB_REPOSITORY\",|" \
package.json
fi
if (command -v shCiPublishNpmCustom >/dev/null)
then
shCiPublishNpmCustom
fi
)}
shCiPublishPypi() {(set -e
# This function will publish pypi-package.
# shCiPublishPypiCustom() {(set -e
# # This function will run custom-code to publish pypi-package.
# # npm publish --access public
# )}
if ! ([ -f pyproject.toml ] \
&& grep -q '^shCiPublishPypi = 1$' pyproject.toml)
then
return
fi
if (command -v shCiPublishPypiCustom >/dev/null)
then
shCiPublishPypiCustom
fi
)}
shDirHttplinkValidate() {(set -e
# This function will validate http-links embedded in .html and .md files.
# init $GITHUB_BRANCH0
export GITHUB_BRANCH0="${GITHUB_BRANCH0:-alpha}"
# init $UPSTREAM_XXX
export UPSTREAM_REPOSITORY="$(node -p '(
/^(?:git\+)?https:\/\/github\.com\/([^\/]*?\/[^.]*?)\.git$/
).exec(require("./package.json").repository.url)[1]
')" # '
export UPSTREAM_GITHUB_IO="$(
printf "$UPSTREAM_REPOSITORY" | sed -e "s|/|.github.io/|"
)"
# init $GITHUB_XXX
export GITHUB_REPOSITORY="${GITHUB_REPOSITORY:-$UPSTREAM_REPOSITORY}"
export GITHUB_GITHUB_IO="$(
printf "$GITHUB_REPOSITORY" | sed -e "s|/|.github.io/|"
)"
node --input-type=module --eval '
import moduleAssert from "assert";
import moduleFs from "fs";
import moduleHttps from "https";
(async function () {
let {
GITHUB_BRANCH0,
GITHUB_GITHUB_IO,
GITHUB_REPOSITORY,
UPSTREAM_GITHUB_IO,
UPSTREAM_REPOSITORY
} = process.env;
let dict = {};
Array.from(
await moduleFs.promises.readdir(".")
).forEach(async function (file) {
let data;
if (file === "CHANGELOG.md" || !(/.\.html$|.\.md$/m).test(file)) {
return;
}
data = await moduleFs.promises.readFile(file, "utf8");
// ignore link-rel-preconnect
data = data.replace((
/<link\b.+?\brel="preconnect".+?>/g
), "");
data.replace((
/\bhttps?:\/\/.+?([\s")\]]|\W?$)/gm
), function (url, removeLast) {
let req;
if (removeLast && removeLast !== "/") {
url = url.slice(0, -1);
}
url = url.replace((/["\u0027]/g), "");
url = url.replace(
(/\/branch-[a-z]+?\//g),
`/branch-${GITHUB_BRANCH0}/`
);
url = url.replace(
(/_2fbranch-[a-z]+?_2f/g),
`_2fbranch-${GITHUB_BRANCH0}_2f`
);
url = url.replace(
new RegExp(`\\b${UPSTREAM_REPOSITORY}\\b`, "g"),
GITHUB_REPOSITORY
);
url = url.replace(
new RegExp(`\\b${UPSTREAM_GITHUB_IO}\\b`, "g"),
GITHUB_GITHUB_IO
);
if ((
/^http:\/\/(?:127\.0\.0\.1|localhost|www\.w3\.org\/2000\/svg)(?:[\/:]|$)|^https:\/\/github\.com\/[\w.\-\/]+?\/compare\/[\w.\-\/]+?\.\.\.\w/m
).test(url)) {
return "";
}
moduleAssert.ok(
!url.startsWith("http://"),
`shDirHttplinkValidate - ${file} - insecure link - ${url}`
);
// ignore duplicate-link
if (dict.hasOwnProperty(url)) {
return "";
}
dict[url] = true;
req = moduleHttps.request(url, {
headers: {
"user-agent": "undefined"
}
}, function (res) {
console.error(
"shDirHttplinkValidate " + res.statusCode + " " + url
);
moduleAssert.ok(
res.statusCode < 400,
`shDirHttplinkValidate - ${file} - unreachable url ${url}`
);
req.abort();
res.destroy();
});
req.setTimeout(30000);
req.end();
return "";
});
data.replace((
/(\bhref=|\bsrc=|\burl\(|\[[^]+?\]\()("?.+?)(?:[")\]]|$)/gm
), function (ignore, linkType, url) {
if (!linkType.startsWith("[")) {
url = url.slice(1);
}
if ((
/^$|^\\|^data:/m
).test(url)) {
return "";
}
// ignore duplicate-link
if (dict.hasOwnProperty(url)) {
return "";
}
dict[url] = true;
if (!(
/^https?|^mailto:|^[#\/]/m
).test(url)) {
moduleFs.stat(url.split("?")[0], function (ignore, exists) {
console.error(
"shDirHttplinkValidate " + Boolean(exists) + " " + url
);
moduleAssert.ok(
exists,
(
`shDirHttplinkValidate - ${file}`
+ `- unreachable file ${url}`
)
);
});
}
return "";
});
});
}());
' "$@" # '
)}
shDuList() {(set -e
# This function will du $1 and sort its subdir by size.
du -md1 "$1" | sort -nr
)}
shGitCmdWithGithubToken() {(set -e
# This function will run git $CMD with $MY_GITHUB_TOKEN.
printf "shGitCmdWithGithubToken $*\n"
if [ -f .git/config ]
then
# security - scrub token from url
sed -i.bak "s|://.*@|://|g" .git/config
rm -f .git/config.bak
fi
CMD="$1"
case "$CMD" in
clone)
;;
ls-remote)
;;
*)
if [ ! "$MY_GITHUB_TOKEN" ]
then
git "$@"
return
fi
;;
esac
shift
URL="$1"
shift
if (printf "$URL" | grep -qv "^https://")
then
URL="$(git config "remote.$URL.url")"
fi
if [ "$MY_GITHUB_TOKEN" ]
then
URL="$(
printf "$URL" \
| sed -e "s|https://|https://x-access-token:$MY_GITHUB_TOKEN@|"
)"
fi
EXIT_CODE=0
# hide $MY_GITHUB_TOKEN in case of err
git "$CMD" "$URL" "$@" 2>/dev/null || EXIT_CODE="$?"
printf "shGitCmdWithGithubToken - EXIT_CODE=$EXIT_CODE\n" 1>&2
return "$EXIT_CODE"
)}
shGitCommitPushOrSquash() {(set -e
# This function will, if $COMMIT_COUNT > $COMMIT_LIMIT,
# then backup, squash, force-push,
# else normal-push.
BRANCH="$(git branch --show-current)"
COMMIT_MESSAGE="${1:-$(git diff HEAD --stat)}"
COMMIT_LIMIT="$2"
MODE_NOBACKUP="$3"
MODE_SQUASH="$4"
git commit -am "$COMMIT_MESSAGE" || true
COMMIT_COUNT="$(git rev-list --count HEAD)"
if [ "$COMMIT_COUNT" -gt "$COMMIT_LIMIT" ]
then
MODE_SQUASH=squash
fi
printf "shGitCommitPushOrSquash COMMIT_COUNT=$COMMIT_COUNT \
COMMIT_LIMIT=$COMMIT_LIMIT MODE_SQUASH=$MODE_SQUASH\n"
if [ "$MODE_SQUASH" != squash ]
then
shGitCmdWithGithubToken push origin "$BRANCH"
return
fi
# backup
if [ "$MODE_NOBACKUP" != nobackup ]
then
shGitCmdWithGithubToken push origin \
"$BRANCH:$BRANCH.backup_wday$(date -u +%w)" -f
fi
# squash commits
COMMIT_MESSAGE="[squashed $COMMIT_COUNT commits] $COMMIT_MESSAGE"
git branch -D __tmp1 2>/dev/null || true
git checkout --orphan __tmp1
git commit --quiet -am "$COMMIT_MESSAGE" || true
# reset branch to squashed-commit
git push . "__tmp1:$BRANCH" -f
git checkout "$BRANCH"
# force-push squashed-commit
shGitCmdWithGithubToken push origin "$BRANCH" -f
)}
shGitGc() {(set -e
# This function will gc unreachable .git objects.
# http://stackoverflow.com/questions/3797907/how-to-remove-unused-objects-from-a-git-repository
git remote prune origin
git \
-c gc.reflogExpire=0 \
-c gc.reflogExpireUnreachable=0 \
-c gc.rerereresolved=0 \
-c gc.rerereunresolved=0 \
-c gc.pruneExpire=now \
gc
)}
shGitInitBase() {(set -e
# This function will git init && create basic git-template from jslint-org/base.
git init
git config core.autocrlf input
git remote remove base 2>/dev/null || true
git remote add base https://github.com/jslint-org/base
git fetch base base
for BRANCH in base alpha
do
git branch -D "$BRANCH" 2>/dev/null || true
git checkout -b "$BRANCH" base/base
done
sed -i.bak "s|owner/repo|${1:-owner/repo}|" .gitconfig
rm -f .gitconfig.bak
cp .gitconfig .git/config
git commit -am "update owner/repo to $1" || true
)}
shGitLsTree() {(set -e
# This function will "git ls-tree" all files committed in HEAD.
# example usage:
# shGitLsTree | sort -rk3 # sort by date
# shGitLsTree | sort -rk4 # sort by size
node --input-type=module --eval '
import moduleChildProcess from "child_process";
(async function () {
let result;
// get file, mode, size
result = await new Promise(function (resolve) {
result = "";
moduleChildProcess.spawn(
"git",
["ls-tree", "-lr", "HEAD"],
{stdio: ["ignore", "overlapped", 2]}
).on("exit", function () {
resolve(result);
}).stdout.on("data", function (chunk) {
result += chunk;
}).setEncoding("utf8");
});
result = Array.from(result.matchAll(
/^(\S+?) +?\S+? +?\S+? +?(\S+?)\t(\S+?)$/gm
)).map(function ([
ignore, mode, size, file
]) {
return {
file,
mode: mode.slice(-3),
size: Number(size)
};
});
result = result.sort(function (aa, bb) {
return aa.file > bb.file || -1;
});
result = result.slice(0, 1000);
result.unshift({
file: ".",
mode: "755",
size: 0
});
// get date
result.forEach(function (elem) {
result[0].size += elem.size;
moduleChildProcess.spawn(
"git",
["log", "--max-count=1", "--format=%at", elem.file],
{stdio: ["ignore", "overlapped", 2]}
).stdout.on("data", function (chunk) {
elem.date = new Date(
Number(chunk) * 1000
).toISOString().slice(0, 19) + "Z";
});
});
process.on("exit", function () {
let iiPad;
let sizePad;
iiPad = String(result.length).length + 1;
sizePad = String(Math.ceil(result[0].size / 1024)).length;
process.stdout.write(result.map(function (elem, ii) {
return (
String(ii + ".").padStart(iiPad, " ")
+ " " + elem.mode
+ " " + elem.date
+ " " + String(
Math.ceil(elem.size / 1024)
).padStart(sizePad, " ") + " KB"
+ " " + elem.file
+ "\n"
);
}).join(""));
});
}());
' "$@" # '
)}
shGitPullrequestCleanup() {(set -e
# This function will cleanup pull-request after merge.
git fetch upstream beta
# verify no diff between alpha..upstream/beta
git diff alpha..upstream/beta
git push . HEAD:__pr_upstream_pre -f
git reset upstream/beta
git push origin alpha -f
git push origin alpha:beta
sh jslint_ci.sh shMyciUpdate
git push . HEAD:__pr_upstream -f
)}