-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjslint_ci.sh
2739 lines (2645 loc) · 74.1 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
# 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 branch -d -r origin/aa
# git config --global diff.algorithm histogram
# 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 shCiBranchPromote origin alpha beta
# sh jslint_ci.sh shRunWithScreenshotTxt .artifact/screenshot_changelog.svg head -n50 CHANGELOG.md
# vim rgx-lowercase \L\1\e
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 run headless-chrome to screenshot url $1 with
# window-size $2
node --input-type=module -e '
import moduleChildProcess from "child_process";
import modulePath from "path";
import moduleUrl from "url";
// init debugInline
(function () {
let consoleError = console.error;
globalThis.debugInline = globalThis.debugInline || function (...argList) {
// this function will both print <argList> to stderr and return <argList>[0]
consoleError("\n\ndebugInline");
consoleError(...argList);
consoleError("\n");
return argList[0];
};
}());
(async function () {
let child;
let exitCode;
let file;
let timeStart;
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";
child = moduleChildProcess.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",
"--ignore-certificate-errors",
"--incognito",
"--screenshot",
"--timeout=30000",
"--user-data-dir=/dev/null",
"--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);
});
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
local BRANCH
local FILE
node --input-type=module -e '
process.exit(Number(
`${process.version.split(".")[0]}.${process.arch}.${process.platform}`
!== process.env.CI_NODE_VERSION_ARCH_PLATFORM
));
' || return 0
# init .git/config
git config --local user.email "github-actions@users.noreply.github.com"
git config --local user.name "github-actions"
# init $BRANCH
BRANCH="$(git rev-parse --abbrev-ref HEAD)"
git pull --unshallow origin "$BRANCH"
# init $UPSTREAM_OWNER
export UPSTREAM_OWNER="${UPSTREAM_OWNER:-jslint-org}"
# init $UPSTREAM_REPO
export UPSTREAM_REPO="${UPSTREAM_REPO:-jslint}"
# screenshot changelog and files
node --input-type=module -e '
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"
]
].forEach(function (argList) {
moduleChildProcess.spawn("sh", argList, {
stdio: [
"ignore", 1, 2
]
}).on("exit", function (exitCode) {
if (exitCode) {
process.exit(exitCode);
}
});
});
}());
' "$@" # '
shCiArtifactUploadCustom
# 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-$BRANCH
rm -rf "branch-$BRANCH"
mkdir -p "branch-$BRANCH"
(set -e
cd "branch-$BRANCH"
git init -b branch1
git pull --depth=1 .. "$BRANCH"
rm -rf .git
git add -f .
)
# update root-dir with branch-beta
if [ "$BRANCH" = 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-$BRANCH and $GITHUB_REPOSITORY
sed -i \
-e "s|/branch-[0-9A-Z_a-z]*/|/branch-$BRANCH/|g" \
-e "s|\b$UPSTREAM_OWNER/$UPSTREAM_REPO\b|$GITHUB_REPOSITORY|g" \
-e "s|\b$UPSTREAM_OWNER\.github\.io/$UPSTREAM_REPO\b|$(
printf "$GITHUB_REPOSITORY" | sed -e "s|/|.github.io/|"
)|g" \
"branch-$BRANCH/README.md"
git status
git commit -am "update dir branch-$BRANCH" || true
# if branch-gh-pages has more than 50 commits,
# then backup and squash commits
if [ "$(git rev-list --count gh-pages)" -gt 50 ]
then
# backup
shGitCmdWithGithubToken push origin -f gh-pages:gh-pages-backup
# squash commits
git checkout --orphan squash1
git commit --quiet -am squash || true
# reset branch-gh-pages to squashed-commit
git push . -f squash1:gh-pages
git checkout gh-pages
# force-push squashed-commit
shGitCmdWithGithubToken push origin -f gh-pages
fi
# list files
shGitLsTree
# push branch-gh-pages
shGitCmdWithGithubToken push origin gh-pages
# validate http-links
(set -e
cd "branch-$BRANCH"
sleep 15
shDirHttplinkValidate
)
)}
shCiArtifactUploadCustom() {(set -e
return
)}
shCiBase() {(set -e
# this function will run base-ci
# update table-of-contents in README.md
node --input-type=module -e '
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\n\n#|\n###) (.*)/g
), function (ignore, level, title) {
if (title === "Table of Contents") {
ii += 1;
return "";
}
if (ii < 0) {
return "";
}
switch (level.trim()) {
case "#":
ii += 1;
toc += "\n" + ii + ". [" + title + "](#";
break;
case "###":
toc += " - [" + title + "](#";
break;
}
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);
}());
' "$@" # '
shCiBaseCustom
git diff
)}
shCiBaseCustom() {(set -e
return
)}
shCiBranchPromote() {(set -e
# this function will promote branch $REMOTE/$BRANCH1 to branch $REMOTE/$BRANCH2
local BRANCH1
local BRANCH2
local REMOTE
REMOTE="$1"
shift
BRANCH1="$1"
shift
BRANCH2="$1"
shift
git fetch "$REMOTE" "$BRANCH1"
git push "$REMOTE" "$REMOTE/$BRANCH1:$BRANCH2" "$@"
)}
shDirHttplinkValidate() {(set -e
# this function will validate http-links embedded in .html and .md files
node --input-type=module -e '
import moduleFs from "fs";
import moduleHttps from "https";
import moduleUrl from "url";
(async function () {
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");
data.replace((
/\bhttps?:\/\/.*?(?:[\s")\]]|\W?$)/gm
), function (url) {
let req;
url = url.slice(0, -1).replace((
/[\u0022\u0027]/g
), "").replace((
/\/branch-\w+?\//g
), "/branch-alpha/").replace((
/\bjslint-org\/jslint\b/g
), process.env.GITHUB_REPOSITORY || "jslint-org/jslint").replace((
/\bjslint-org\.github\.io\/jslint\b/g
), String(
process.env.GITHUB_REPOSITORY || "jslint-org/jslint"
).replace("/", ".github.io/"));
if (url.startsWith("http://")) {
throw new Error("shDirHttplinkValidate - insecure link " + url);
}
// ignore duplicate-link
if (dict.hasOwnProperty(url)) {
return "";
}
dict[url] = true;
req = moduleHttps.request(moduleUrl.parse(
url
), function (res) {
console.error(
"shDirHttplinkValidate " + res.statusCode + " " + url
);
if (!(res.statusCode < 400)) {
throw new Error(
"shDirHttplinkValidate - " + file
+ " - unreachable link " + 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 (url.length === 0 || url.startsWith("data:")) {
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
);
if (!exists) {
throw new Error(
"shDirHttplinkValidate - " + file
+ " - unreachable link " + 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 $GITHUB_TOKEN
local CMD
local EXIT_CODE
local REMOTE
local URL
printf "shGitCmdWithGithubToken $*\n"
CMD="$1"
shift
REMOTE="$1"
shift
URL="$(
git config "remote.$REMOTE.url" \
| sed -e "s|https://|https://x-access-token:$GITHUB_TOKEN@|"
)"
EXIT_CODE=0
# hide $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"
)}
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 \
-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
local BRANCH
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 .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 use:
# shGitLsTree | sort -rk3 # sort by date
# shGitLsTree | sort -rk4 # sort by size
node --input-type=module -e '
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"
], {
encoding: "utf8",
stdio: [
"ignore", "pipe", 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", "pipe", 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(""));
});
}());
' "$@" # '
)}
shGitSquashPop() {(set -e
# this function will squash HEAD to given $COMMIT
# http://stackoverflow.com/questions/5189560
# /how-can-i-squash-my-last-x-commits-together-using-git
COMMIT="$1"
MESSAGE="$2"
# reset git to previous $COMMIT
git reset "$COMMIT"
git add .
# commit HEAD immediately after previous $COMMIT
git commit -am "$MESSAGE" || true
)}
shGrep() {(set -e
# this function will recursively grep . for $REGEXP
REGEXP="$1"
shift
FILE_FILTER="\
/\\.|~$|/(obj|release)/|(\\b|_)(\\.\\d|\
archive|artifact|\
bower_component|build|\
coverage|\
doc|\
external|\
fixture|\
git_module|\
jquery|\
log|\
min|misc|mock|\
node_module|\
old|\
raw|\rollup|\
swp|\
tmp|\
vendor)s{0,1}(\\b|_)\
"
find . -type f |
grep -v -E "$FILE_FILTER" |
tr "\n" "\000" |
xargs -0 grep -HIin -E "$REGEXP" "$@" |
tee /tmp/shGrep.txt || true
)}
shGrepReplace() {(set -e
# this function will inline grep-and-replace /tmp/shGrep.txt
node --input-type=module -e '
import moduleFs from "fs";
import moduleOs from "os";
import modulePath from "path";
(async function () {
"use strict";
let data;
let dict = {};
data = await moduleFs.promises.readFile((
moduleOs.tmpdir() + "/shGrep.txt"
), "utf8");
data = data.replace((
/^(.+?):(\d+?):(.*?)$/gm
), function (ignore, file, lineno, str) {
dict[file] = dict[file] || moduleFs.readFileSync( //jslint-quiet
modulePath.resolve(file),
"utf8"
).split("\n");
dict[file][lineno - 1] = str;
return "";
});
Object.entries(dict).forEach(function ([
file, data
]) {
moduleFs.promises.writeFile(file, data.join("\n"));
});
}());
' "$@" # '
)}
shHttpFileServer() {(set -e
# this function will run simple node http-file-server on port $PORT
if [ ! "$npm_config_mode_auto_restart" ]
then
local EXIT_CODE
EXIT_CODE=0
export npm_config_mode_auto_restart=1
while true
do
printf "\n"
git diff --color 2>/dev/null | cat || true
printf "\nshHttpFileServer - (re)starting $*\n"
(shHttpFileServer "$@") || EXIT_CODE="$?"
printf "process exited with code $EXIT_CODE\n"
# if $EXIT_CODE != 77, then exit process
# http://en.wikipedia.org/wiki/Unix_signal
if [ "$EXIT_CODE" != 77 ]
then
break
fi
# else restart process after 1 second
sleep 1
done
return
fi
node --input-type=module -e '
import moduleChildProcess from "child_process";
import moduleFs from "fs";
import moduleHttp from "http";
import modulePath from "path";
import moduleRepl from "repl";
import moduleUrl from "url";
// init debugInline
(function () {
let consoleError = console.error;
globalThis.debugInline = globalThis.debugInline || function (...argList) {
// this function will both print <argList> to stderr and return <argList>[0]
consoleError("\n\ndebugInline");
consoleError(...argList);
consoleError("\n");
return argList[0];
};
}());
(async function httpFileServer() {
// this function will start http-file-server
let contentTypeDict = {
".bmp": "image/bmp",
".cjs": "application/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".gif": "image/gif",
".htm": "text/html; charset=utf-8",
".html": "text/html; charset=utf-8",
".jpe": "image/jpeg",
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".js": "application/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
".md": "text/markdown; charset=utf-8",
".mjs": "application/javascript; charset=utf-8",
".pdf": "application/pdf",
".png": "image/png",
".svg": "image/svg+xml; charset=utf-8",
".txt": "text/plain; charset=utf-8",
".wasm": "application/wasm",
".woff": "font/woff",
".woff2": "font/woff2",
".xml": "application/xml; charset=utf-8",
"/": "text/html; charset=utf-8"
};
if (process.argv[1]) {
await import("file://" + modulePath.resolve(process.argv[1]));
}
process.env.PORT = process.env.PORT || "8080";
console.error("http-file-server listening on port " + process.env.PORT);
moduleHttp.createServer(function (req, res) {
let file;
let pathname;
let timeStart;
// init timeStart
timeStart = Date.now();
// init pathname
pathname = moduleUrl.parse(req.url).pathname;
// debug - serverLog
res.on("close", function () {
if (pathname === "/favicon.ico") {
return;
}
console.error(
"serverLog - "
+ new Date(timeStart).toISOString() + " - "
+ (Date.now() - timeStart) + "ms - "
+ (res.statusCode || 0) + " " + req.method + " " + pathname
);
});
// debug - echo request
if (pathname === "/echo") {
res.write(JSON.stringify(req.headers, undefined, 4) + "\n");
req.pipe(res);
return;
}
// replace trailing "/" with "/index.html"
file = pathname.slice(1).replace((
/\/$/
), "/index.html");
// resolve file
file = modulePath.resolve(file);
// security - disable parent-directory lookup
if (!file.startsWith(process.cwd() + modulePath.sep)) {
res.statusCode = 404;
res.end();
return;
}
moduleFs.readFile(file, function (err, data) {
let contentType;
if (err) {
res.statusCode = 404;
res.end();
return;
}
contentType = contentTypeDict[(
/^\/$|\.[^.]*?$|$/m
).exec(file)[0]];
if (contentType) {
res.setHeader("content-type", contentType);
}
res.end(data);
});
}).listen(process.env.PORT);
}());
(function jslintDir() {
// this function will jslint current-directory
moduleFs.stat((
process.env.HOME + "/jslint.mjs"
), function (ignore, exists) {
if (exists) {
moduleChildProcess.spawn("node", [
process.env.HOME + "/jslint.mjs", "."
], {
stdio: [
"ignore", 1, 2
]
});
}
});
}());
(function replStart() {
// this function will start repl-debugger
let that;
// start repl
that = moduleRepl.start({
useGlobal: true
});
// init history
that.setupHistory(modulePath.resolve(
process.env.HOME + "/.node_repl_history"
), function () {
return;
});
// save eval-function
that.evalDefault = that.eval;
// hook custom-eval-function
that.eval = function (script, context, file, onError) {
script.replace((
/^(\S+) (.*?)\n/
), function (ignore, match1, match2) {
switch (match1) {
// syntax-sugar - run shell-cmd
case "$":
switch (match2.split(" ").slice(0, 2).join(" ")) {
// syntax-sugar - run git diff
case "git diff":
match2 += " --color";
break;
// syntax-sugar - run git log
case "git log":
match2 += " -n 10";
break;
// syntax-sugar - run ll
case "ll":
match2 = "ls -Fal";
break;
}
match2 = match2.replace((
/^git /
), "git --no-pager ");
// run shell-cmd
console.error("$ " + match2);
moduleChildProcess.spawn(match2, {
shell: true,
stdio: [
"ignore", 1, 2
]
// print exitCode
}).on("exit", function (exitCode) {
console.error("$ EXIT_CODE=" + exitCode);
that.evalDefault("\n", context, file, onError);
});
script = "\n";
break;
// syntax-sugar - map text with charCodeAt
case "charCode":
console.error(
match2.split("").map(function (chr) {
return (
"\\u"
+ chr.charCodeAt(0).toString(16).padStart(4, 0)
);
}).join("")
);
script = "\n";
break;
// syntax-sugar - sort chr
case "charSort":
console.error(JSON.stringify(match2.split("").sort().join("")));
script = "\n";
break;
// syntax-sugar - list obj-keys, sorted by item-type
// console.error(Object.keys(global).map(function(key){return(typeof global[key]===\u0027object\u0027&&global[key]&&global[key]===global[key]?\u0027global\u0027:typeof global[key])+\u0027 \u0027+key;}).sort().join(\u0027\n\u0027)) //jslint-quiet
case "keys":
script = (
"console.error(Object.keys(" + match2
+ ").map(function(key){return("
+ "typeof " + match2 + "[key]===\u0027object\u0027&&"
+ match2 + "[key]&&"
+ match2 + "[key]===global[key]"
+ "?\u0027global\u0027"
+ ":typeof " + match2 + "[key]"
+ ")+\u0027 \u0027+key;"
+ "}).sort().join(\u0027\\n\u0027))\n"
);
break;
// syntax-sugar - print String(val)
case "print":
script = "console.error(String(" + match2 + "))\n";
break;
}
});
// eval script
that.evalDefault(script, context, file, onError);
};
}());
(function watchDir() {
// this function will watch current-directory for changes