-
Notifications
You must be signed in to change notification settings - Fork 9
/
lib.utility2.sh
executable file
·3086 lines (2987 loc) · 90.5 KB
/
lib.utility2.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
# jslint utility2:true
# POSIX reference
# http://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html
# http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html
# curl with custom CA certificates
# openssl x509 -in a00.pem -text
# openssl verify --verbose -CAfile ca.pem a00.pem
# openssl x509 -outform der -in a00.pem -out a00.crt
# cp a00.crt /usr/local/share/ca-certificates/
# update-ca-certificates
# sh one-liner
# http://sed.sourceforge.net/sed1line.txt
# apt list --installed
# export NODE_TLS_REJECT_UNAUTHORIZED=0 # use with caution
# git branch -d -r origin/aa
# git config --global diff.algorithm histogram
# git fetch origin alpha beta master --tags
# git ls-files --stage | sort
# git ls-remote --heads origin
# git update-index --chmod=+x aa.js
# gpupdate /force
# npm test --mode-coverage --mode-test-case2=_testCase_webpage_default,testCase_nop_default
# openssl rand -base64 32 # random key
# printf "$USERNAME:$(openssl passwd -apr1 "$PASSWD")\n" # htpasswd
# shCryptoWithGithubOrg aa shGithubApiRateLimitGet
# shCryptoWithGithubOrg aa shGithubRepoTouch aa/node-aa-bb alpha "[build app]"
# shDockerRestartUtility2 work kaizhu256/node-utility2
# shDockerSh work 'PORT=4065 npm start'
# shDockerSh work 'shUtility2DependentsShellEval shBuildApp'
# utility2 shReadmeEval example.js
# vim rgx-lowercase \L\1\e
shBaseInit() {
# this function will init bash-login base-env, and is intended for aws-ec2 setup
local FILE || return "$?"
# PATH=/usr/local/bin:/usr/bin:/bin
# init $PATH_BIN
if [ ! "$PATH_BIN" ]
then
export PATH_BIN="$HOME/bin:$HOME/node_modules/.bin\
:/usr/local/n/bin:/usr/local/bin:/usr/local/sbin" || return "$?"
export PATH="$PATH_BIN:$PATH" || return "$?"
fi
# init $PATH_OS
case "$(uname)" in
Darwin)
if [ ! "$PATH_OS" ]
then
export PATH_OS="$HOME/bin/darwin" || return "$?"
export PATH="$PATH_OS:$PATH" || return "$?"
fi
;;
Linux)
if [ ! "$PATH_OS" ]
then
export PATH_OS="$HOME/bin/linux" || return "$?"
export PATH="$PATH_OS:$PATH" || return "$?"
fi
;;
esac
# init lib.utility2.sh and .bashrc2
for FILE in "$HOME/lib.utility2.sh" "$HOME/.bashrc2"
do
# source $FILE
if [ -f "$FILE" ]
then
. "$FILE" || return "$?"
fi
done
# init ubuntu .bashrc
shBashrcDebianInit || return "$?"
# init custom alias
alias lld="ls -adlF" || return "$?"
}
shBaseInstall() {
# this function will automate installing .bashrc, .screenrc, .vimrc, and
# lib.utility2.sh in $HOME
# example use:
# curl -Lf -o "$HOME/lib.utility2.sh" https://raw.githubusercontent.com/kaizhu256/node-utility2/alpha/lib.utility2.sh && . "$HOME/lib.utility2.sh" && shBaseInstall
for FILE in .screenrc .vimrc lib.utility2.sh
do
curl -Lf -o "$HOME/$FILE" \
"https://raw.githubusercontent.com/kaizhu256/node-utility2/alpha/$FILE" ||
return "$?"
done
# backup .bashrc
if [ -f "$HOME/.bashrc" ] && [ ! -f "$HOME/.bashrc.00" ]
then
cp "$HOME/.bashrc" "$HOME/.bashrc.00" || return "$?"
fi
# create .bashrc
printf '. "$HOME/lib.utility2.sh" && shBaseInit\n' > "$HOME/.bashrc" ||
return "$?"
# init .ssh/authorized_keys.root
if [ -f "$HOME/.ssh/authorized_keys.root" ]
then
mv "$HOME/.ssh/authorized_keys.root" "$HOME/.ssh/authorized_keys" ||
return "$?"
fi
# source .bashrc
. "$HOME/.bashrc" || return "$?"
}
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
}
shBrowserScreenshot() {(set -e
# this function will screenshot url "$1" with headless-chrome
node -e '
/* jslint utility2:true */
(function () {
"use strict";
let file;
let sep;
let timeStart;
let url;
let {
CI_BRANCH,
CI_HOST,
MODE_CI,
UTILITY2_DIR_BUILD
} = process.env;
sep = require("path").sep;
timeStart = Date.now();
url = process.argv[1];
if (!(
/^\w+?:/
).test(url)) {
url = require("path").resolve(url);
}
file = require("url").parse(url).pathname;
// remove prefix $PWD from file
if (String(file + sep).indexOf(process.cwd() + sep) === 0) {
file = file.replace(process.cwd(), "");
}
file = require("path").resolve(
UTILITY2_DIR_BUILD + "/screenshot." + MODE_CI + ".browser." +
encodeURIComponent(file.replace(
"/build.." + CI_BRANCH + ".." + CI_HOST + "/",
"/build/"
)) + ".png"
);
process.on("exit", function (exitCode) {
if (typeof exitCode === "object" && exitCode) {
console.error(exitCode);
exitCode = 1;
}
console.error(
"\nshBrowserScreenshot" + " - " + (Date.now() - timeStart) + " ms" +
" - EXIT_CODE=" + exitCode + " - " + url + " - " + file + "\n"
);
});
process.on("uncaughtException", process.exit);
process.on("unhandledRejection", process.exit);
require("child_process").spawn((
process.platform === "darwin"
? "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
: process.platform === "win32"
? "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
: "/usr/bin/google-chrome-stable"
), [
"--headless",
"--incognito",
"--screenshot",
"--timeout=30000",
"--window-size=800x600",
"-screenshot=" + file,
(
process.platform === "linux"
? "--no-sandbox"
: ""
),
url
], {
stdio: [
"ignore", 1, 2
]
});
}());
' "$1" "$2" # '
)}
shBrowserTest() {(set -e
# this function will spawn google-chrome-process to test url $1,
# and merge test-report into existing test-report
shCiPrint "shBrowserTest - $1"
# run browser-test
lib.utility2.js utility2.browserTest "$1"
# create test-report artifacts
lib.utility2.js utility2.testReportCreate
)}
shBuildApidoc() {(set -e
# this function will build apidoc
shEnvSanitize
npm test --mode-coverage="" --mode-test-case=testCase_buildApidoc_default
)}
shBuildApp() {(set -e
# this function will build app in "$PWD"
shEnvSanitize
shCiInit
# cleanup empty-file
find . -maxdepth 1 -empty | xargs rm -f
# hardlink file .gitignore, lib.xxx, assets.utility2.rollup.js
# hardlink file ~/lib.utility2.sh, bin/utility2
# bin/utility2-apidoc, bin/utility2-istanbul, bin/utility2-jslint
# update file .travis.yml, npm_scripts.sh
node -e '
/* jslint utility2:true */
(async function () {
"use strict";
let dirBin;
let dirDev;
let fileList;
let fs;
let path;
fs = require("fs");
path = require("path");
dirBin = process.env.HOME + "/bin";
dirDev = process.env.HOME + "/Documents/utility2";
try {
await fs.promises.access(dirDev + "/lib.utility2.js");
} catch (ignore) {
return;
}
// hardlink file $HOME/lib.utility2.sh, $HOME/bin/utility2-xxx
[
[
dirDev + "/lib.utility2.sh", process.env.HOME + "/lib.utility2.sh"
],
[
dirDev + "/lib.utility2.sh", dirBin + "/utility2"
],
[
dirDev + "/lib.apidoc.js", dirBin + "/utility2-apidoc"
],
[
dirDev + "/lib.istanbul.js", dirBin + "/utility2-istanbul"
],
[
dirDev + "/lib.jslint.js", dirBin + "/utility2-jslint"
]
].forEach(function ([
aa, bb
], ii) {
// hardlink file $HOME/lib.utility2.sh synchronously to prevent
// race-condition with hardlink file $HOME/bin/utility2
if (ii === 0) {
try {
fs.unlinkSync(bb);
} catch (ignore) {}
fs.linkSync(aa, bb);
} else {
fs.unlink(bb, function (ignore) {
fs.link(aa, bb, function (err) {
if (err) {
throw err;
}
});
});
}
console.error("shBuildApp - hardlink - " + path.resolve(bb));
});
if (process.cwd() === path.resolve(dirDev)) {
return;
}
// hardlink file .gitignore, lib.xxx, assets.utility2.rollup.js
fileList = await fs.promises.readdir(dirDev);
fileList.concat("assets.utility2.rollup.js").forEach(async function (file) {
if (!(
file === ".gitignore" ||
file === "assets.utility2.rollup.js" ||
file.indexOf("lib.") === 0
)) {
return;
}
try {
await fs.promises.access(file);
} catch (ignore) {
return;
}
await fs.promises.unlink(file);
await fs.promises.link((
file === "assets.utility2.rollup.js"
? dirDev + "/.tmp/build/app/assets.utility2.rollup.js"
: dirDev + "/" + file
), file);
console.error("shBuildApp - hardlink - " + path.resolve(file));
});
// update file .travis.yml, npm_scripts.sh
[
".travis.yml", "npm_scripts.sh"
].forEach(async function (file) {
let aa;
let bb;
let data;
try {
data = await fs.promises.readFile(file, "utf8");
} catch (ignore) {
return;
}
bb = data;
aa = await fs.promises.readFile(dirDev + "/" + file, "utf8");
[
(
/\n\u0020{4}-\u0020secure:\u0020.*?\u0020#\u0020CRYPTO_AES_KEY\n/
), (
/\n\u0020{4}#\u0020run\u0020cmd\u0020-\u0020custom\n[\S\s]*?\n\u0020{4}esac\n/
), (
/\n\)\}\n[\S\s]*?\n#\u0020run\u0020cmd\n/
)
].forEach(function (rgx) {
bb.replace(rgx, function (match2) {
aa.replace(rgx, function (match1) {
aa = aa.replace(match1, function () {
return match2;
});
return "";
});
return "";
});
});
if (aa !== bb) {
await fs.promises.writeFile(file, aa);
console.error("shBuildApp - updated - " + path.resolve(file));
}
});
}());
' # '
# create file if not exists
# .gitignore, .travis.yml, LICENSE, npm_scripts.sh
# package.json
# README.md, lib.$npm_package.nameLib.js, test.js
node -e '
/* jslint utility2:true */
(async function (local) {
"use strict";
let fs;
let modeUtility2Rollup;
fs = require("fs");
// fetch file .gitignore, .travis.yml, LICENSE, npm_scripts.sh
[
".gitignore", ".travis.yml", "LICENSE", "npm_scripts.sh"
].forEach(async function (file) {
try {
await fs.promises.access(file);
} catch (ignore) {
return;
}
require("https").request((
"https://raw.githubusercontent.com/kaizhu256/node-utility2" +
"/alpha/" + file
), function (res) {
res.pipe(fs.createWriteStream(file).on("close", async function () {
if (file === "npm_scripts.sh") {
await fs.promises.chmod(file, 0o755);
}
}));
}).end();
});
// create file package.json
(async function () {
let aa;
let bb;
aa = await fs.promises.readFile("package.json", "utf8");
bb = JSON.stringify(local.objectDeepCopyWithKeysSorted(
Object.assign({
"description": "the greatest app in the world!",
"main": "lib." + process.env.npm_package_nameLib + ".js",
"name": process.env.npm_package_name,
"scripts": {
"test": "./npm_scripts.sh"
},
"version": "0.0.1"
}, JSON.parse(aa))
), undefined, 4) + "\n";
if (bb !== aa) {
await fs.promises.writeFile("package.json", bb);
console.error("shBuildApp - modified - package.json");
}
}());
// create file README.md, lib.$npm_package.nameLib.js, test.js
try {
await fs.promises.access("assets.utility2.rollup.js");
modeUtility2Rollup = true;
} catch (ignore) {
return;
}
[
"README.md",
"lib." + process.env.npm_package_nameLib + ".js",
"test.js"
].forEach(async function (file) {
try {
await fs.promises.access(file);
} catch (ignore) {
return;
}
await fs.promises.writeFile(file, local.templateRenderMyApp((
file === "README.md"
? local.assetsDict["/assets.readme.template.md"]
: file === "test.js"
? local.assetsDict["/assets.test.template.js"]
: local.assetsDict["/assets.my_app.template.js"]
).replace("require(\u0027utility2\u0027)", function (match0) {
return (
modeUtility2Rollup
? "require(\u0027./assets.utility2.rollup.js\u0027)"
: match0
);
})).trimRight() + "\n");
console.error("shBuildApp - modified - " + file);
});
}(require(process.env.UTILITY2_DIR_BIN)));
' # '
# build app
npm test --mode-coverage="" --mode-test-case=testCase_buildApp_default
# git diff
if [ -d .git ]
then
git --no-pager diff HEAD
fi
)}
shCiInit() {
# this function will init env
export CI_BRANCH="${CI_BRANCH:-$(
git rev-parse --abbrev-ref HEAD 2>/dev/null
)}"
if [ "$CI_BRANCH" ]
then
export CI_COMMIT_ID="$(git rev-parse --verify HEAD)"
export CI_COMMIT_MESSAGE="$(git log -1 --pretty=%s)"
export CI_HOST=127.0.0.1
fi
# init env - $GITHUB_ACTIONS
if [ "$GITHUB_ACTIONS" ]
then
export CI_BRANCH="$(printf "$GITHUB_REF" | grep -Eo "[^/]*$")"
export CI_HOST=github.com
fi
# init env - $TRAVIS
if [ "$TRAVIS" ]
then
export CI_BRANCH="$TRAVIS_BRANCH"
export CI_HOST=travis-ci.com
fi
eval "$(node -e '
/* jslint utility2:true */
(function () {
"use strict";
let cmd;
let dataReadme;
let fs;
let packageJson;
let path;
let {
HOME,
UTILITY2_DIR_BUILD,
CI_BRANCH,
CI_COMMIT_ID,
CI_COMMIT_MESSAGE,
NODE_OPTIONS = ""
} = process.env;
function exportVar(key, val) {
/*
* this function will export "key=val" to shell-env
*/
cmd += "export " + key + "=\u0027" + String(val || "").replace((
/\u0027/g
), "\u0027\"\u0027\"\u0027") + "\u0027\n";
}
fs = require("fs");
path = require("path");
cmd = "";
cmd += "# shCiInit env\n";
cmd += "# ";
exportVar("PWD", process.cwd());
// init packageJson
packageJson = (
fs.existsSync("package.json")
? JSON.parse(fs.readFileSync("package.json"))
: {
name: "my-app",
version: "0.0.1"
}
);
// init $npm_package_*
[
"description",
"homepage",
"main",
"name",
"nameLib",
"nameOriginal",
"private",
"version"
].forEach(function (key) {
switch (key) {
case "nameLib":
exportVar("npm_package_nameLib", String(
packageJson.nameLib || packageJson.name
).replace((
/\W/g
), "_"));
break;
default:
exportVar("npm_package_" + key, packageJson[key]);
}
});
// init $GITHUB_FULLNAME, $GITHUB_OWNER, $GITHUB_REPO
String(
(packageJson.repository && packageJson.repository.url) ||
packageJson.repository ||
""
).replace((
/([^\/]+?)\/([^\/]+?)(?:\.git)?$/
), function (ignore, owner, repo) {
exportVar("GITHUB_FULLNAME", owner + "/" + repo);
exportVar("GITHUB_OWNER", owner);
exportVar("GITHUB_REPO", repo);
});
// init $UTILITY2_BIN, $UTILITY2_DIR_*
Array.from([
process.cwd(),
path.resolve(HOME + "/Documents/utility2"),
(function () {
try {
return path.dirname(require.resolve("utility2"));
} catch (ignore) {}
}()),
path.resolve(HOME + "/node_modules/utility2")
]).some(function (dir) {
if (!dir || !fs.existsSync(dir + "/lib.utility2.js")) {
return;
}
exportVar("UTILITY2_BIN", path.resolve(dir + "/lib.utility2.sh"));
exportVar("UTILITY2_DIR_BIN", dir);
exportVar(
"UTILITY2_DIR_BUILD",
path.resolve(UTILITY2_DIR_BUILD || ".tmp/build")
);
// interpolate $PATH
cmd += (
"export PATH=\"$PATH:" +
dir + ":" + path.resolve(dir + "/../.bin") + "\"\n"
);
// mkdir $UTILITY2_DIR_BUILD
dir = path.resolve(".tmp/build");
fs.mkdirSync(dir, {
recursive: true
});
console.error("shCiInit - mkdir - " + dir);
return true;
});
// init $CI_xxx, $NODE_OPTIONS
exportVar("CI_BRANCH", CI_BRANCH);
exportVar("CI_COMMIT_ID", CI_COMMIT_ID);
exportVar("CI_COMMIT_MESSAGE", CI_COMMIT_MESSAGE);
exportVar("NODE_OPTIONS", (
NODE_OPTIONS.indexOf("--unhandled-rejections=") >= 0
? NODE_OPTIONS
: String(NODE_OPTIONS + " --unhandled-rejections=throw").trim()
));
process.stderr.write(cmd);
process.stdout.write(cmd);
// extract embedded-scripts from README.md to .tmp/README.xxx
dataReadme = "";
try {
dataReadme = require("fs").readFileSync("README.md", "utf8");
} catch (ignore) {}
dataReadme.replace((
/\n```\w*?(\n[#*\/\s]*?(\w[\w\-]*?\.\w*?)[\n"][\S\s]*?\n)```\n/g
), function (ignore, dataEmbedded, file, ii, dataReadme) {
dataEmbedded = (
// preserve lineno
dataReadme.slice(0, ii).replace((
/.*/g
), "") + "\n" +
dataEmbedded.replace((
// parse "\" line-continuation
/\\\n/g
), "")
);
file = require("path").resolve(".tmp/README." + file);
require("fs").writeFile(file, dataEmbedded.trimEnd() + "\n", function (
err
) {
if (err) {
throw err;
}
console.error("shCiInit - wrote - " + file);
});
return "";
});
}());
')" || return "$?" # '
}
shCiInternal() {(set -e
# this function will run internal-ci
local FILE
(
shEnvSanitize
# run shCiBefore
if (type shCiBefore > /dev/null 2>&1)
then
shCiBefore
fi
export npm_config_mode_test_report_merge=1
# npm-test
export MODE_CI=npmTest
npm test --mode-coverage
# create apidoc.html
export MODE_CI=buildApidoc
shBuildApidoc
# create screenshot.npmPackageListing.svg
export MODE_CI=npmPackageListing
shRunWithScreenshotTxt eval \
"printf \"package files\n\n\" && shGitLsTree"
# create screenshot.npmPackageDependencyTree.svg
shNpmPackageDependencyTreeCreate "$npm_package_name" \
"$GITHUB_FULLNAME#alpha"
# create screenshot.npmPackageCliHelp.svg
export MODE_CI=npmPackageCliHelp
shRunWithScreenshotTxt eval "$(node -e '
/* jslint utility2:true */
(function () {
"use strict";
let file;
try {
file = require("path").resolve(Object.values(JSON.parse(
require("fs").readFileSync("package.json", "utf8")
).bin)[0]);
if (require("fs").existsSync(file)) {
process.stdout.write(file + " --help");
}
} catch (ignore) {}
process.stdout.write("printf none");
}());
')" # '
# create screenshot.gitLog.svg
export MODE_CI=gitLog
shRunWithScreenshotTxt git log -50 --pretty="%ai\\u000a%B"
# screenshot apidoc.html, coverage.lib.html, test-report.html
export MODE_CI=ci
FILE="$(
find "$UTILITY2_DIR_BUILD" -name *.js.html 2>/dev/null | tail -n 1
)"
cp "$FILE" "$UTILITY2_DIR_BUILD/coverage.lib.html"
for FILE in apidoc.html coverage.lib.html test-report.html
do
FILE="$UTILITY2_DIR_BUILD/$FILE"
shBrowserScreenshot "file://$FILE" &
done
)
if [ ! "$GITHUB_TOKEN" ]
then
shCiPrint "no GITHUB_TOKEN"
return
fi
export npm_config_mode_test_report_merge=1
# build and deploy app to github
(export MODE_CI=buildApp && shBuildApp && shCiUpload && shSleep 15)
# run shCiAfter
if (type shCiAfter > /dev/null 2>&1)
then
shCiAfter
fi
# list $UTILITY2_DIR_BUILD
find "$UTILITY2_DIR_BUILD" | sort
# upload $UTILITY2_DIR_BUILD to github-gh-pages and
# if number of commits > $COMMIT_LIMIT, then squash older commits
if [ "$CI_BRANCH" = alpha ] ||
[ "$CI_BRANCH" = beta ] ||
[ "$CI_BRANCH" = master ]
then
COMMIT_LIMIT=100 shCiUpload
fi
shGitInfo
# validate http-link in README.md
shSleep 60
shReadmeLinkValidate
)}
shCiMain() {(set -e
# this function will run main-ci
export MODE_CI=ci
# init env - $TRAVIS
if [ "$TRAVIS" ]
then
git remote remove origin 2>/dev/null || true
git remote add origin "https://github.com/$GITHUB_FULLNAME"
# decrypt and exec encrypted data
if [ "$CRYPTO_AES_KEY" ]
then
eval "$(shCryptoTravisDecrypt)"
fi
fi
# init env - $GITHUB_ACTIONS
if [ "$GITHUB_ACTIONS" ]
then
git remote remove origin 2>/dev/null || true
git remote add origin "https://github.com/$GITHUB_FULLNAME"
fi
# init git config
if (! git config user.email > /dev/null 2>&1)
then
git config --global user.email ci
git config --global user.name ci
fi
case "$CI_BRANCH" in
alpha)
shCiInternal
;;
beta)
shCiInternal
;;
docker.*)
export CI_BRANCH=alpha
shCiInternal
;;
master)
shCiInternal
;;
publish)
export CI_BRANCH=alpha
# init .npmrc
printf "//registry.npmjs.org/:_authToken=$NPM_TOKEN" > "$HOME/.npmrc"
if (grep -q -E ' shNpmTestPublished' README.md)
then
# npm publish
shNpmPublishAlias || true
else
shCiPrint "skip npm-publish"
fi
# security - cleanup .npmrc
rm -f "$HOME/.npmrc"
shSleep 5
shCiInternal
;;
esac
if [ ! "$GITHUB_TOKEN" ]
then
return
fi
case "$CI_BRANCH" in
alpha)
case "$CI_COMMIT_MESSAGE" in
"[npm publish]"*)
shGitCmdWithGithubToken push "https://github.com/$GITHUB_FULLNAME" \
HEAD:publish
;;
esac
;;
beta)
;;
master)
git tag "$npm_package_version" || true
shGitCmdWithGithubToken push "https://github.com/$GITHUB_FULLNAME" \
"$npm_package_version" || true
;;
publish)
# security - cleanup .npmrc
rm -f "$HOME/.npmrc"
shGitCmdWithGithubToken push "https://github.com/$GITHUB_FULLNAME" \
HEAD:beta
;;
esac
)}
shCiPrint() {(set -e
# this function will print debug-info about current ci-state
node -e '
/* jslint utility2:true */
(function () {
"use strict";
process.stderr.write(
"\n\u001b[35m[MODE_CI=" + process.env.MODE_CI + "]\u001b[0m - " +
new Date().toISOString() + " - " + process.argv[1] + "\n\n"
);
}());
' "$1" # '
)}
shCiUpload() {(set -e
# this function will upload dir $UTILITY2_DIR_BUILD to github-gh-pages
local DIR
local URL
shCiPrint "shCiUpload - upload - $UTILITY2_DIR_BUILD to \
https://github.com/$GITHUB_FULLNAME/tree/gh-pages/build..$CI_BRANCH..$CI_HOST"
URL="https://github.com/$GITHUB_FULLNAME"
# init $DIR
DIR=/tmp/shCiUpload
rm -rf "$DIR"
shGitCmdWithGithubToken clone "$URL" --single-branch -b gh-pages "$DIR"
cd "$DIR"
# cleanup screenshot
rm -f build/*127.0.0.1*
case "$CI_COMMIT_MESSAGE" in
"[build clean]"*)
shCiPrint "shCiUpload - [build clean]"
rm -rf build
;;
esac
# copy $UTILITY2_DIR_BUILD
cp -a "$UTILITY2_DIR_BUILD" .
rm -rf "build..$CI_BRANCH..$CI_HOST"
cp -a "$UTILITY2_DIR_BUILD" "build..$CI_BRANCH..$CI_HOST"
# disable github-jekyll
touch .nojekyll
git add .
git commit -am "[ci skip] update gh-pages" || true
# if number of commits > $COMMIT_LIMIT, then
# backup gh-pages to gh-pages.backup, and then
# squash to $COMMIT_LIMIT/2 in git-repo-branch
if [ "$COMMIT_LIMIT" ] &&
[ "$(git rev-list HEAD --count)" -gt "$COMMIT_LIMIT" ]
then
shGitCmdWithGithubToken push "$URL" -f HEAD:gh-pages.backup
shGitSquashShift "$(($COMMIT_LIMIT / 2))"
fi
shGitCmdWithGithubToken push "$URL" -f HEAD:gh-pages
if [ "$CI_BRANCH" = alpha ] && [ "$npm_package_description" ]
then
shGithubRepoDescriptionUpdate \
"$GITHUB_FULLNAME" "$npm_package_description" || true
fi
)}
shCryptoAesXxxCbcRawDecrypt() {(set -e
# this function will inplace aes-xxx-cbc decrypt stdin with given hex-key $1
# example use:
# printf 'hello world\n' | shCryptoAesXxxCbcRawEncrypt 0123456789abcdef0123456789abcdef | shCryptoAesXxxCbcRawDecrypt 0123456789abcdef0123456789abcdef
node -e '
/* jslint utility2:true */
(function () {
"use strict";
let bufList;
function cryptoAesXxxCbcRawDecrypt(opt, onError) {
/*
* this function will aes-xxx-cbc decrypt with given <opt>
* example use:
data = new Uint8Array([1,2,3]);
key = '"'"'0123456789abcdef0123456789abcdef'"'"';
mode = undefined;
cryptoAesXxxCbcRawEncrypt({
data,
key,
mode
}, function (err, data) {
console.assert(!err, err);
cryptoAesXxxCbcRawDecrypt({
data,
key,
mode
}, console.log);
});
*/
let cipher;
let crypto;
let data;
let ii;
let iv;
let key;
// init key
key = new Uint8Array(0.5 * opt.key.length);
ii = 0;
while (ii < key.byteLength) {
key[ii] = parseInt(opt.key.slice(2 * ii, 2 * ii + 2), 16);