-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpck.cmd
1405 lines (1231 loc) · 48.3 KB
/
pck.cmd
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
::bat
:: PCK Package Manager for Windows
:: https://github.com/cubernetes/PCK
@ECHO OFF
SETLOCAL EnableDelayedExpansion EnableExtensions
CALL :Init "%~1"
::CALL :ParsePackageConfigFile "!PackagesFilePath!"
::ENDLOCAL
::EXIT /B 0
CALL :Main "%~0" %*
ENDLOCAL & SET "PATH=%PATH%" & SET "PATHEXT=%PATHEXT%"
EXIT /B 0
REM ------------------------ ColorEcho ------------------------
:ColorEcho
SETLOCAL
REM Needed to print excalamation points.
SETLOCAL DisableDelayedExpansion
SET "Type=[%~1] "
SET "Clr=%~2"
SET "AddNewline=%~3"
SET "ComplyWithVerboseSetting=%~4"
FOR /F "TOKENS=4*" %%A IN ('ECHO %*') DO (SET "Message=%%~B")
1>NUL SET /A "Check=(!ComplyWithVerboseSetting) | Verbose"
REM /!\ With logical operators: NOT verbose OR Verbose
REM ! Which is equivalent to: verbose -> Verbose
REM ! Which means the only way this function will NOT echo anything is, when "Verbose" is 0 [meaning verbose output will be suppressed]
REM ! and "verbose" is 1, meaning the following echo statements comply with the aforementioned "Verbose" setting. In any other case, it will be echoed.
SETLOCAL EnableDelayedExpansion EnableExtensions
SET "Style=0"
REM ANSI escape codes, see https://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html
IF "!Clr!"=="black" SET "Style=30"
IF "!Clr!"=="red" SET "Style=31;1"
IF "!Clr!"=="green" SET "Style=32"
IF "!Clr!"=="yellow" SET "Style=33"
IF "!Clr!"=="blue" SET "Style=34;1"
IF "!Clr!"=="magenta" SET "Style=35"
IF "!Clr!"=="white" SET "Style=37"
IF "!Clr!"=="cyan" SET "Style=36"
IF "!Clr!"=="orange" SET "Style=38;5;208"
IF "!Clr!"=="def" (
IF "!Type!"=="[ERROR] " SET "Style=31;1"
IF "!Type!"=="[ACTION] " SET "Style=34;1"
IF "!Type!"=="[INFO] " SET "Style=33"
IF "!Type!"=="[WARNING] " SET "Style=38;5;208"
IF "!Type!"=="[SUCCESS] " SET "Style=32"
IF "!Type!"=="[FAIL] " SET "Style=31;1"
)
IF "!Type!"=="[] " SET "Type="
IF "!Check!"=="1" (
IF "!AddNewline!"=="1" (
ECHO !ESC![!Style!m!Type!!Message!!ESC![0m
) ELSE (
<NUL SET /P=!ESC![!Style!m!Type!!Message!!ESC![0m
)
)
ENDLOCAL
EXIT /B 0
REM ----------------------- GetProgramPath -----------------------
:GetProgramPath
SETLOCAL
SET "FileName=%~1"
SET "DefaultLocation=%~2"
SET "ReturnVar1=%~3"
IF EXIST "!System32!\where.exe" (
SET "Where="!System32!\where.exe""
) ELSE (
FOR /F "DELIMS=" %%A IN (
'2^>NUL where where'
) DO (
SET "Where="%%~A""
GOTO :Continue
)
)
:Continue
SET "ProgramPath="
FOR /F "DELIMS=" %%A IN (
'2^>NUL "!Where!" "!DefaultLocation!":"!FileName!"'
) DO (
SET "ProgramPath=%%~A"
GOTO :Found
)
FOR /F "DELIMS=" %%A IN (
'2^>NUL "!Where!" "!FileName!"'
) DO (
SET "ProgramPath=%%~A"
GOTO :Found
)
CALL :ColorEcho WARNING def 1 0 "!FileName! was not found."
ENDLOCAL & SET "%ReturnVar1%=not found"
EXIT /B 1
:Found
ENDLOCAL & SET "%ReturnVar1%=%ProgramPath%"
EXIT /B 0
REM ------------------------ WarnAboutIgnoredArgs ------------------------
:WarnAboutIgnoredArgs
SETLOCAL
SET "MaxNumberOfArgs=%~1"
SET "ExtraArgs= "
SET "Command=%~2"
SET "CommandWithArgs=!Command!"
SHIFT
SHIFT
SET "NumberOfArgs=0"
FOR /L %%A IN (1,1,50) DO (
CALL SET "ShiftedArg=%%1"
IF "!ShiftedArg!"=="" (
GOTO :NoArgsAnymore
)
SET /A "NumberOfArgs+=1"
SHIFT
CALL CALL SET "CommandWithArgs=!CommandWithArgs! %%%%0"
IF !NumberOfArgs! GTR !MaxNumberOfArgs! (
CALL CALL SET "ExtraArgs=!ExtraArgs! %%%%0"
)
)
CALL :ColorEcho WARNING def 1 0 "You specified 50 or more args to the command !Command!."
:NoArgsAnymore
SET "ExtraArgs=!ExtraArgs:~2!"
%$Trim% CommandWithArgs SingleQuote
%$ToLower% ExtraArgs
%$ToLower% CommandWithArgs
IF !NumberOfArgs! GTR !MaxNumberOfArgs! (
SET /A "Difference=NumberOfArgs - MaxNumberOfArgs"
IF "!Difference!"=="1" (
CALL :ColorEcho WARNING def 1 0 "The last argument (`!ExtraArgs!`) in the command `!CommandWithArgs!` was ignored."
) ELSE (
CALL :ColorEcho WARNING def 1 0 "The last !Difference! arguments (`!ExtraArgs!`) in the command `!CommandWithArgs!` were ignored."
)
ENDLOCAL
EXIT /B 1
)
ENDLOCAL
EXIT /B 0
REM ------------------------ Error ------------------------
REM Source: https://stackoverflow.com/a/61782349
:Error - Cleanly exit batch processing, regardless how many CALLs
CALL :ColorEcho "" white 1 0 ""
CALL :Cleanup "%0"
CALL :ColorEcho ACTION def 1 0 "Exiting."
IF NOT EXIST "!TmpDir!\ExitBatchYes.txt" CALL :BuildYes
1>NUL 2>&1 <"!TmpDir!\ExitBatchYes.txt" CALL :CtrlC
:CtrlC
CMD /C EXIT -1073741510
:BuildYes - Establish a Yes file for the language used by the OS
SETLOCAL
SET "Yes="
1>NUL COPY NUL "!TmpDir!\ExitBatchYes.txt"
FOR /F "DELIMS=(/ TOKENS=2" %%Y IN ('^<NUL COPY /-Y NUL "!TmpDir!\ExitBatchYes.txt"') DO (
IF NOT DEFINED Yes (
SET "Yes=%%Y"
)
)
>"!TmpDir!\ExitBatchYes.txt" ECHO !Yes!
ENDLOCAL
EXIT /B 0
REM ------------------------ FollowURL ------------------------
:FollowURL
SETLOCAL
REM URL can't be passed literally, but must be passed as the variable name that contains the URL.
REM Must be done this way to prevent percent doubling.
SET "URL=!%~1!"
SET "ReturnVar1=%~2"
SET "LastRedirectURL="
FOR /F "TOKENS=2 DELIMS= " %%A IN ('2^>NUL curl --silent --location --head -X GET "!URL!" ^| "!Findstr!" /I "Location: "') DO (SET "LastRedirectURL=%%A")
IF NOT DEFINED LastRedirectURL SET "LastRedirectURL=!URL!"
ENDLOCAL & SET "%ReturnVar1%=%LastRedirectURL%"
EXIT /B 0
REM ----------------------- ListPackages -------------------------
:ListPackages
SETLOCAL
SET "Regex=!%~1!"
IF DEFINED Regex (
IF "!Arg2:~0,1!"=="-" (
CALL :ColorEcho ERROR def 1 0 "Your regex starts with a minus ("-"). Please escape it using a backslash ("\")."
CALL :ColorEcho INFO def 1 0 "The reason for this error is unclear to me, but you know, it's batch."
GOTO :Error
)
CALL :ColorEcho ACTION def 1 1 "Showing all available packages that match the regex `!Regex!`."
FOR /F "TOKENS=1,2 EOL=# DELIMS=; " %%A IN ('TYPE "!PackagesFilePath!" ^| "!Findstr!" /I /R "^^[!AlnumCharClass!]*!Regex![!AlnumCharClass!]*;" ^| "!Sort!"') DO @(
IF NOT EXIST "!BaseDir!\%%~A%%~B" (
ECHO - %%~A
) ELSE (
ECHO %ESC%[32m- %%~A [already installed]%ESC%[0m
)
)
) ELSE (
CALL :ColorEcho ACTION def 1 1 "Showing all available packages."
FOR /F "TOKENS=1,2 EOL=# DELIMS=; " %%A IN ('TYPE "!PackagesFilePath!" ^| "!Sort!"') DO (
IF NOT EXIST "!BaseDir!\%%~A%%~B" (
ECHO - %%~A
) ELSE (
ECHO %ESC%[32m- %%~A [already installed]%ESC%[0m
)
)
)
ENDLOCAL
EXIT /B 0
REM ----------------------- InstallPackage -------------------------
:InstallPackage
SETLOCAL
SET "Package=%~1"
CALL :WarnAboutIgnoredArgs 1 %*
REM --------------------------- Install package ---------------------------
FOR /F "TOKENS=1,2,3,4,5 EOL=# DELIMS=; " %%A IN ('TYPE "!PackagesFilePath!" ^| "!Sort!"') DO (
SET "Name=%%~A"
%$ToLower% Name
IF "!Name!"=="!Package!" (
SET "RelPath=%%~B"
SET "URL=%%~C"
SET "URL32bit=%%~D"
SET "RelPath=!RelPath:~1!"
IF EXIST "!BaseDir!\!Name!\!RelPath!" (
CALL :ColorEcho INFO def 1 1 "!Name! is already installed in "!BaseDir!\!Name!". Use it with "!BaseDir!\!Name!\!RelPath!"."
ENDLOCAL & EXIT /B 0
)
CALL :ColorEcho INFO def 1 1 "Package "!Package!" found!"
CALL :FollowURL URL LastRedirectURL
CALL :FollowURL URL32bit LastRedirectURL32bit
CALL :DetermineFileExtensionOfURL LastRedirectURL FileExtension
CALL :DetermineFileExtensionOfURL LastRedirectURL32bit FileExtension32bit
REM a => Architecture is 64 bit
REM b => File type for 64 bit version is not unknown and not undetermined
REM c => File type for 32 bit version is not unknown and not undetermined
REM
REM Truth table:
REM a b c Error Use b instead of c
REM 0 0 0 1 0
REM 0 0 1 0 0
REM 0 1 0 1 0
REM 0 1 1 0 0
REM 1 0 0 1 0
REM 1 0 1 0 0
REM 1 1 0 0 1
REM 1 1 1 0 1
REM To get a formular for the Error variable, we can use a disjunctive normal form:
REM Error = (¬a ∧ ¬b ∧ ¬c) ∨ (¬a ∧ b ∧ ¬c) ∨ (a ∧ ¬b ∧ ¬c) <=>
REM Error = (¬a ∧ ¬c) ∨ (¬b ∧ ¬c)
REM With:
REM ∧ = AND
REM ∨ = OR
REM ¬ = NOT
REM In batch:
REM SET /A "Error=(!a & !b) | (!b & !c)"
REM
REM Forumular for when to use the 64 bit version:
REM SET /A "CanUse64Bit=a & b"
SET "_ErrorString=unknown undetermined"
SET "a=0"
SET "b=0"
SET "c=0"
IF "!Architecture!"=="64" SET "a=1"
CALL CALL SET "TmpString=%%%%_ErrorString:%%FileExtension%%=%%%%"
CALL CALL SET "TmpString32bit=%%%%_ErrorString:%%FileExtension32bit%%=%%%%"
IF "!TmpString!"=="!_ErrorString!" SET "b=1"
IF "!TmpString32bit!"=="!_ErrorString!" SET "c=1"
REM Escaping exclamation points because of DelayedExpansion
SET /A "Error=(^!a & ^!c)|(^!b & ^!c)"
IF "!Error!"=="1" (
CALL :ColorEcho ERROR def 1 0 "There was no compatible version found for your machine."
CMD /C ^""!DifferentCmdLine!" i "!Name!"^"
GOTO :Error
)
SET /A "CanUse64Bit=a & b"
IF "!CanUse64Bit!"=="1" (
CALL :ColorEcho ACTION def 1 0 "Getting 64 bit version of "!Package!"."
CALL :Download LastRedirectURL "!TmpDir!\!Name!.!FileExtension!"
SET "Extension=!FileExtension!"
) ELSE (
CALL :ColorEcho ACTION def 1 0 "Getting 32 bit version of "!Package!"."
CALL :Download LastRedirectURL32bit "!TmpDir!\!Name!.!FileExtension32bit!"
SET "Extension=!FileExtension32bit!"
)
CALL :CreateFolder "!BaseDir!\!Name!"
IF "!Extension!"=="zip" (
CALL :Unzip "!TmpDir!\!Name!.zip" "!BaseDir!\!Name!"
)
IF "!Extension!"=="7z" (
CALL :Extract7z "!TmpDir!\!Name!.7z" "!BaseDir!\!Name!"
)
IF "!Extension!"=="exe" (
CALL :CheckExeExtractable "!TmpDir!\!Name!.exe" isExtractable
IF "!IsExtractable!"=="1" (
CALL :ExtractExe "!TmpDir!\!Name!.zip" "!BaseDir!\!Name!"
) ELSE (
CALL :CheckExeInstaller "!TmpDir!\!Name!.exe" isInstaller
IF NOT "!IsInstaller!"=="1" (
CALL :InstallExe "!TmpDir!\!Name!.zip" "!BaseDir!\!Name!"
) ELSE (
MOVE "!TmpDir!\!Name!.exe" "!BaseDir!\!Name!"
)
)
)
IF "!Extension!"=="msi" (
CALL :ExtractMsi "!TmpDir!\!Name!.msi" "!BaseDir!\!Name!"
REM Since you can always extract any MSI with windows built-in msiexec-utility, there's no need
REM to install any msi. Option to actually install it might be added later
REM CALL :InstallMsi "!TmpDir!\!Name!.msi" "!BaseDir!\!Name!"
)
IF "!Extension!"=="bat" (
MOVE "!TmpDir!\!Name!.bat" "!BaseDir!\!Name!"
)
IF "!Extension!"=="ahk" (
MOVE "!TmpDir!\!Name!.ahk" "!BaseDir!\!Name!"
)
FOR /F "DELIMS=" %%A IN ("!RelPath!") DO (SET "File=%%~nxA")
IF DEFINED File (
CALL CALL SET "RelPathDir=%%%%RelPath:%%File%%=%%%%"
) ELSE (
SET "RelPathDir=!RelPath!"
)
CALL :CreateShortcutWithVbs "!BaseDir!\!Name!\!RelPath!" "!BaseDir!\!Name!\!RelPathDir!" "!RedirectsDir!\!Name!.lnk"
ENDLOCAL & EXIT /B 0
)
)
ENDLOCAL
EXIT /B 1
REM ----------------------- ShowInformation -------------------------
:ShowInformation
SETLOCAL
SET "Package=%~1"
SET "Offline=%~2"
IF DEFINED Offline (
IF NOT "!Offline!"=="offline" (
CALL :ColorEcho WARNING def 1 0 "Ignoring unknown argument `!Offline!`."
SET "a=0"
SET "b=0"
SET "c=0"
IF "!Architecture!"=="64" SET "a=1"
CALL CALL SET "TmpString=%%%%_ErrorString:%%FileExtension%%=%%%%"
CALL CALL SET "TmpString32bit=%%%%_ErrorString:%%FileExtension32bit%%=%%%%"
IF "!TmpString!"=="!_ErrorString!" SET "b=1"
IF "!TmpString32bit!"=="!_ErrorString!" SET "c=1"
SET "Offline="
)
)
FOR /F "TOKENS=1,2,3,4,5 EOL=# DELIMS=; " %%A IN ('TYPE "!PackagesFilePath!" ^| "!Sort!"') DO (
SETLOCAL
IF "!Package!"=="all" (
SET "Pkg=%%~A"
) ELSE (
SET "Pkg=!Package!"
)
IF "%%~A"=="!Pkg!" (
SET "Name=%%~A"
SET "RelPath=%%~B"
SET "URL=%%~C"
SET "URL32bit=%%~D"
SET "WhereToFindURLs=%%~E"
IF NOT DEFINED Offline (
CALL :FollowURL URL LastRedirectURL
CALL :FollowURL URL32bit LastRedirectURL32bit
CALL :GetFileSize LastRedirectURL FileSize FileSizeMB
CALL :GetFileSize LastRedirectURL32bit FileSize32bit FileSizeMB32bit
SET "FileSize=~!FileSizeMB! MB (!FileSize! Bytes)"
SET "FileSize32bit=~!FileSizeMB32bit! MB (!FileSize32bit! Bytes)"
CALL :DetermineFileExtensionOfURL LastRedirectURL FileExtension
CALL :DetermineFileExtensionOfURL LastRedirectURL32bit FileExtension32bit
)
CALL :ColorEcho ACTION def 1 1 "Showing information for "!Pkg!"."
CALL :ColorEcho "" white 1 0 ""
CALL :ColorEcho "" cyan 1 0 "### General Information ###"
ECHO Name/Runstring: !ESC![4m!Name!!ESC![0m
ECHO Relative path to binary or folder: !ESC![4m!RelPath!!ESC![0m
ECHO Where to find new download links: !ESC![4m!WhereToFindURLs!!ESC![0m
CALL :ColorEcho "" cyan 1 0 "### 64 bit ###"
ECHO Download link: !ESC![4m!URL!!ESC![0m
IF NOT DEFINED Offline (
ECHO Direct download link ^(derived from above^): !ESC![32;4m!LastRedirectURL!!ESC![0m
ECHO File size: !ESC![4m!FileSize!!ESC![0m
ECHO File type: !ESC![4m!FileExtension!!ESC![0m
)
CALL :ColorEcho "" cyan 1 0 "### 32 bit ###"
ECHO Download link: !ESC![4m!URL32bit!!ESC![0m
IF NOT DEFINED Offline (
ECHO Direct download link ^(derived from above^): !ESC![32;4m!LastRedirectURL32bit!!ESC![0m
ECHO File size: !ESC![4m!FileSize32bit!!ESC![0m
ECHO File type: !ESC![4m!FileExtension32bit!!ESC![0m
)
IF DEFINED Offline (
CALL :ColorEcho "" white 1 1 ""
CALL :ColorEcho INFO def 1 1 "There was information left out because of the offline argument."
)
IF NOT "!Package!"=="all" (
ENDLOCAL
EXIT /B 0
)
)
ENDLOCAL
)
IF NOT "!Package!"=="all" (
CALL :ColorEcho ERROR def 1 0 "The package "!Package!" could not be found in "!PackagesFilePath!"."
GOTO :Error
) ELSE (
CALL :ColorEcho INFO def 1 1 "Successfully showed information for all packages."
)
ENDLOCAL
EXIT /B 0
REM ------------------------ Download ------------------------
:Download
SETLOCAL
SET "URLReference=%~1"
SET "DestFile=%~2"
SET "FileName=%~n2"
REM DownloadWithVbs = 1 --> force download with vbs
SET "DownloadWithVbs=%~3"
REM untested code
IF "!Curl!"=="not found" (
SET "CurlNotFound=1"
)
SET /A "Check=^!CurlNotFound & ^!DownloadWithVbs"
IF "!Check!"=="1" (
CALL :ColorEcho ACTION def 1 0 "Downloading !FileName! with curl:"
CALL :DownloadWithCurl "!URLReference!" "!DestFile!"
) ELSE (
CALL :ColorEcho ACTION def 1 0 "Downloading !FileName! with VBScript:"
CALL :DownloadWithVbs "!URLReference!" "!DestFile!"
)
IF EXIST "!DestFile!" (
CALL :ColorEcho SUCCESS def 1 0 "Successfully downloaded !FileName!^!"
) ELSE (
CALL :ColorEcho FAIL def 1 0 "Failed^! Could not download !FileName!^!"
CALL :ColorEcho ERROR def 1 0 "!FileName! could not be downloaded from this URL: !%URLReference%!. Please check if the URL is active."
GOTO :Error
)
ENDLOCAL
EXIT /B 0
REM ------------------------ DownloadWithCurl ------------------------
:DownloadWithCurl
SETLOCAL
SET "URL=!%~1!"
SET "DestFile=%~2"
SET "TmpTIME=!TIME:~,-3!"
SET "FinishedAt=!TmpTIME: =0!, !DATE!"
1>NUL "!Chcp!" 1252
"!Powershell!" -Command Remove-Item Alias:curl; curl --location """!URL!""" --output """!DestFile!""" 2^>^&1 ^| Select-String k ^| Foreach-Object {$data = (([string] $_).Trim() -Split '\s+')[0,1,3,9]; Write-Host -NoNewline """[PROGRESS] !ESC![37;1;4m$($data[0])%%!ESC![0m: $($data[2])B / $($data[1])B. Elapsed: $($data[3]).!WhiteSpaceBuffer!!CR!"""}; $FinishedAt=cmd.exe '/V /C SET "TmpTIME=^^^!TIME:~,-3^^^!"^&SET "FinishedAt=^^^!TmpTIME: =0^^^!, ^^^!DATE^^^!"^&ECHO ^^^!FinishedAt^^^!'; $FinishedAt=$FinishedAt.Trim().Replace('""""', ''); Write-Host """!ESC![32m[PROGRESS] !ESC![32;1;4m100%%!ESC![0m!ESC![32m: $($data[2])B / $($data[1])B. Elapsed: $($data[3]). Finished at $($FinishedAt).!ESC![0m"""
1>NUL "!Chcp!" 65001
ENDLOCAL
EXIT /B 0
REM ------------------------ DownloadWithVbs ------------------------
:DownloadWithVbs
SETLOCAL
REM Progress bar can hardly be implemented. Use this only to bootstrap to download curl or something similar.
SET "URL=!%~1!"
SET "DestFile=%~2"
REM Source: https://stackoverflow.com/a/2973344
ECHO DIM xHttp: Set xHttp=CreateObject("Microsoft.XMLHTTP") >"!TmpDir!\DownloadWithVbs.vbs"
REM ECHO DIM xHttp: Set xHttp2=CreateObject("MSXML2.XMLHTTP.3.0") >>"!TmpDir!\DownloadWithVbs.vbs"
REM ECHO DIM xHttp: Set xHttp3=CreateObject("MSXML2.XMLHTTP.6.0") >>"!TmpDir!\DownloadWithVbs.vbs"
REM ECHO DIM xHttp: Set xHttp4=CreateObject("MSXML2.ServerXMLHTTP") >>"!TmpDir!\DownloadWithVbs.vbs"
REM ECHO DIM xHttp: Set xHttp5=CreateObject("MSXML2.ServerXMLHTTP.3.0") >>"!TmpDir!\DownloadWithVbs.vbs"
REM ECHO DIM xHttp: Set xHttp6=CreateObject("MSXML2.ServerXMLHTTP.6.0") >>"!TmpDir!\DownloadWithVbs.vbs"
REM ECHO DIM xHttp: Set xHttp7=CreateObject("MSXML2.XMLHTTP") >>"!TmpDir!\DownloadWithVbs.vbs"
REM ECHO DIM xHttp: Set xHttp8=CreateObject("WinHttp.WinHttpRequest.5.1") >>"!TmpDir!\DownloadWithVbs.vbs"
ECHO DIM bStrm: Set bStrm=CreateObject("ADODB.Stream") >>"!TmpDir!\DownloadWithVbs.vbs"
ECHO xHttp.Open "GET", "!URL!", False >>"!TmpDir!\DownloadWithVbs.vbs"
ECHO xHttp.Send >>"!TmpDir!\DownloadWithVbs.vbs"
ECHO With bStrm >>"!TmpDir!\DownloadWithVbs.vbs"
ECHO .type=1 '//binary >>"!TmpDir!\DownloadWithVbs.vbs"
ECHO .open >>"!TmpDir!\DownloadWithVbs.vbs"
ECHO .write xHttp.responseBody >>"!TmpDir!\DownloadWithVbs.vbs"
ECHO .saveToFile "!DestFile!", 2 '//overwrite >>"!TmpDir!\DownloadWithVbs.vbs"
ECHO End With >>"!TmpDir!\DownloadWithVbs.vbs"
ECHO Set xHttp = Nothing >>"!TmpDir!\DownloadWithVbs.vbs"
ECHO Set bStrm = Nothing >>"!TmpDir!\DownloadWithVbs.vbs"
"!Cscript!" //NOLOGO "!TmpDir!\DownloadWithVbs.vbs"
ENDLOCAL
EXIT /B 0
REM ------------------------ DownloadDependency ------------------------
:DownloadDependency
SETLOCAL
SET "Package=%~1"
CALL :ColorEcho ACTION def 1 1 "!Package! will now be downloaded in a separate process."
CALL :ColorEcho "" white 1 1 ""
CALL :ColorEcho "" white 1 1 "[-----Installing dependency: !Package!-----]"
CMD /C ^""!DifferentCmdLine!" !Package!^"
CALL :ColorEcho "" white 1 1 "[------Done------]"
CALL :ColorEcho "" white 1 1 ""
ENDLOCAL
EXIT /B 0
REM ------------------------ Extract7z ------------------------
:Extract7z
SETLOCAL
SET "SrcFile=%~1"
SET "FileName=%~n1"
SET "DestFolder=%~2"
CALL :GetProgramPath 7z "!7zDir!" 7z
IF "!7z!"=="not found" (
CALL :DownloadDependency 7zip
)
CALL :GetProgramPath 7z "!7zDir!" 7z
IF "!7z!"=="not found" (
CALL :ColorEcho ERROR def 1 0 "Could not install dependency 7z to extract 7zip archive."
GOTO :Error
) ELSE (
CALL :ColorEcho ACTION def 1 0 "Unzipping !FileName! with 7z:"
1>NUL 2>&1 "!7z!" x -bsp1 -o"!DestFolder!" "!SrcFile!"
)
SET "ItemCount=0"
FOR /F %%A IN ('DIR "!DestFolder!" /A /B') DO (1>NUL SET /A "ItemCount+=1")
IF NOT "!ItemCount!"=="0" (
CALL :ColorEcho SUCCESS def 1 1 "Successfully unzipped "!SrcFile!" to "!DestFolder!"^!"
) ELSE (
CALL :ColorEcho ERROR def 1 1 "Could not unzip "!SrcFile!" to "!DestFolder!"."
GOTO :Error
)
CALL :RemoveNestedFolderStructure "!DestFolder!" "!DestFolder!"
ENDLOCAL
EXIT /B 0
REM ------------------------ Unzip ------------------------
:Unzip
SETLOCAL
SET "SrcFile=%~1"
SET "FileName=%~n1"
SET "DestFolder=%~2"
CALL :GetProgramPath 7z "!7zDir!" 7z
IF "!7z!"=="not found" (
CALL :DownloadDependency 7zip
)
CALL :GetProgramPath 7z "!7zDir!" 7z
IF "!7z!"=="not found" (
CALL :ColorEcho ACTION def 1 0 "Unzipping !FileName! with VBScript instead:"
CALL :UnzipWithVbs "!SrcFile!" "!DestFolder!"
) ELSE (
CALL :ColorEcho ACTION def 1 0 "Unzipping !FileName! with 7z:"
1>NUL 2>&1 "!7z!" x -bsp1 -o"!DestFolder!" "!SrcFile!"
)
SET "ItemCount=0"
FOR /F %%A IN ('DIR "!DestFolder!" /A /B') DO (1>NUL SET /A "ItemCount+=1")
IF NOT "!ItemCount!"=="0" (
CALL :ColorEcho SUCCESS def 1 1 "Successfully unzipped "!SrcFile!" to "!DestFolder!"^!"
) ELSE (
CALL :ColorEcho ERROR def 1 1 "Could not unzip "!SrcFile!" to "!DestFolder!"."
GOTO :Error
)
CALL :RemoveNestedFolderStructure "!DestFolder!" "!DestFolder!"
ENDLOCAL
EXIT /B 0
REM ------------------------ UnzipWithVbs ------------------------
:UnzipWithVbs
SETLOCAL
SET "SrcFile=%~1"
SET "DestFolder=%~2"
REM Source: https://stackoverflow.com
ECHO UnzipTo="!DestFolder!" >"!TmpDir!\Unzip.vbs"
ECHO Set FSO=CreateObject("Scripting.FileSystemObject") >>"!TmpDir!\Unzip.vbs"
ECHO If Not FSO.FolderExists(UnzipTo) Then >>"!TmpDir!\Unzip.vbs"
ECHO FSO.CreateFolder(UnzipTo) >>"!TmpDir!\Unzip.vbs"
ECHO End If >>"!TmpDir!\Unzip.vbs"
ECHO Set objShell=CreateObject("Shell.Application") >>"!TmpDir!\Unzip.vbs"
ECHO Set filesInZip=objShell.NameSpace("!SrcFile!").Items >>"!TmpDir!\Unzip.vbs"
ECHO objShell.NameSpace(UnzipTo).MoveHere(filesInZip) >>"!TmpDir!\Unzip.vbs"
ECHO Set FSO=Nothing >>"!TmpDir!\Unzip.vbs"
ECHO Set objShell=Nothing >>"!TmpDir!\Unzip.vbs"
"!Cscript!" //NOLOGO "!TmpDir!\Unzip.vbs"
REM TODO: Catch Unzipping error
ENDLOCAL
EXIT /B 0
REM ------------------------ ExtractMsi ------------------------
:ExtractMsi
SETLOCAL
SET "SrcFile=%~1"
SET "DestFolder=%~2"
2>NUL RD /S /Q "!DestFolder!"
"!System32!\msiexec.exe" /a "!SrcFile!" /qn TargetDir="!DestFolder!"
FOR /F "DELIMS=" %%A IN ('DIR "!DestFolder!" /A-D /B') DO (DEL "!DestFolder!\%%A")
CALL :RemoveNestedFolderStructure "!DestFolder!" "!DestFolder!"
ENDLOCAL
EXIT /B 0
REM ------------------------ RemoveNestedFolderStructure ------------------------
:RemoveNestedFolderStructure
SETLOCAL
SET "TargetFolder=%~f1"
SET "DestFolder=%~f2"
SET "ItemCount=0"
FOR /F %%A IN ('DIR "!TargetFolder!" /A /B') DO (1>NUL SET /A "ItemCount+=1")
IF !ItemCount! GEQ 2 (
IF NOT "!TargetFolder!"=="!DestFolder!" (
CALL :MoveFilesWithVbsAndDeleteDirWrapper "!TargetFolder!" "!DestFolder!"
)
) ELSE IF !ItemCount! EQU 1 (
SET "Directory=NotADirectory"
FOR /F "DELIMS=" %%A IN ('DIR "!TargetFolder!" /AD /B') DO (SET "Directory=%%A")
IF NOT "!Directory!"=="NotADirectory" (
CALL :RemoveNestedFolderStructure "!TargetFolder!\!Directory!" "!DestFolder!"
) ELSE IF NOT "!TargetFolder!"=="!DestFolder!" (
CALL :MoveFilesWithVbsAndDeleteDirWrapper "!TargetFolder!" "!DestFolder!"
)
) ELSE (
ENDLOCAL
EXIT /B 1
)
ENDLOCAL
EXIT /B 0
REM ------------------------ MoveFilesWithVbsAndDeleteDirWrapper ------------------------
:MoveFilesWithVbsAndDeleteDirWrapper
SETLOCAL
SET "SrcFolder=%~1"
SET "DestFolder=%~2"
CALL :ColorEcho INFO def 1 1 "The contents of the zip file need to be moved up one folder."
CALL :ColorEcho ACTION def 1 1 "Moving the contents of "!SrcFolder!" to "!DestFolder!" with VBScript:"
CALL :MoveFilesWithVbsAndDeleteDir "!SrcFolder!" "!DestFolder!"
CALL :ColorEcho SUCCESS def 1 1 "Successfully moved the contents one folder up^!"
ENDLOCAL
EXIT /B 0
REM ------------------------ MoveFilesWithVbsAndDeleteDir ------------------------
:MoveFilesWithVbsAndDeleteDir
SETLOCAL
REM NO trailing backslash for SrcFolder.
SET "SrcFolder=%~1"
SET "DestFolder=%~2"
REM Source: https://social.technet.microsoft.com/Forums/es-ES/8baf14c5-1888-489f-87ef-ed9516ed9f53/progress-bar-for-vbscript
ECHO Set ShellApp = CreateObject("Shell.Application") >"!TmpDir!\MoveFilesWithVbsAndDeleteDir.vbs"
ECHO Set Folder = ShellApp.Namespace("!DestFolder!") >>"!TmpDir!\MoveFilesWithVbsAndDeleteDir.vbs"
ECHO Folder.MoveHere "!SrcFolder!\*" >>"!TmpDir!\MoveFilesWithVbsAndDeleteDir.vbs"
"!Cscript!" //NOLOGO "!TmpDir!\MoveFilesWithVbsAndDeleteDir.vbs"
2>NUL RD "!SrcFolder!"
ENDLOCAL
EXIT /B 0
REM ------------------------ CreateShortcutWithVbs ------------------------
:CreateShortcutWithVbs
SETLOCAL
SET "ScrFileOrFolder=%~1"
SET "WorkingDirectory=%~2"
SET "DestShortcutFile=%~3"
REM Source: https://docs.microsoft.com/de-de/troubleshoot/windows-client/admin-development/create-desktop-shortcut-with-wsh
ECHO Dim WshShell: Set WshShell = CreateObject("Wscript.Shell") >"!TmpDir!\CreateShortcut.vbs"
ECHO Set oMyShortcut = WshShell.CreateShortcut("!DestShortcutFile!") >>"!TmpDir!\CreateShortcut.vbs"
ECHO oMyShortcut.WindowStyle = 4 >>"!TmpDir!\CreateShortcut.vbs"
ECHO OMyShortcut.TargetPath = "!ScrFileOrFolder!" >>"!TmpDir!\CreateShortcut.vbs"
ECHO OMyShortcut.WorkingDirectory = "!WorkingDirectory!" >>"!TmpDir!\CreateShortcut.vbs"
ECHO oMyShortCut.Save >>"!TmpDir!\CreateShortcut.vbs"
ECHO Set oMyShortCut = Nothing >>"!TmpDir!\CreateShortcut.vbs"
ECHO Set WshShell = Nothing >>"!TmpDir!\CreateShortcut.vbs"
"!Cscript!" //NOLOGO "!TmpDir!\CreateShortcut.vbs"
ENDLOCAL
EXIT /B 0
REM ------------------------ CreateFolder ------------------------
:CreateFolder
SETLOCAL
SET "DestFolder=%~1"
IF NOT EXIST "!DestFolder!" (
CALL :ColorEcho ACTION def 0 1 "Creating directory "!DestFolder!"..."
2>NUL MD "!DestFolder!"
IF NOT EXIST "!DestFolder!" (
CALL :ColorEcho "" red 1 1 " Failed^!"
CALL :ColorEcho ERROR def 1 0 "Directory "!DestFolder!" could not be created. Run as admin or in a different location."
GOTO :Error
)
CALL :ColorEcho "" green 1 1 " Success^!"
)
ENDLOCAL
EXIT /B 0
REM ------------------------ GetFileSize ------------------------
:GetFileSize
SETLOCAL
SET "URL=!%~1!"
SET "ReturnVar1=%~2"
SET "ReturnVar2=%~3"
FOR /F "TOKENS=2 DELIMS= " %%A IN ('2^>NUL "!Curl!" --head --silent --location "!URL!" ^| "!Findstr!" /I "Content-Length: "') DO (SET "_FileSize_=%%A")
>NUL SET /A "_FileSize_=_FileSize_ / 1"
>NUL SET /A "_FileSizeMB_=_FileSize_ / 1000000"
ENDLOCAL & SET "%ReturnVar1%=%_FileSize_%" & SET "%ReturnVar2%=%_FileSizeMB_%"
EXIT /B 0
REM ------------------------ DetermineFileExtensionOfURL ------------------------
:DetermineFileExtensionOfURL
SETLOCAL
SET "URL=!%~1!"
SET "ReturnVar1=%~2"
SET "TmpFile=!TmpDir!\determineFileExtension.extension"
2>NUL DEL "!TmpFile!"
1>NUL "!Chcp!" 1252
"!Powershell!" -Command Remove-Item Alias:curl; curl --location --range 0-32 """!URL!""" --output """!TmpFile!""" 2^>^&1 ^| Select-String k ^| Foreach-Object {$data = ^(^([string] $_^).Trim^(^) -Split '\s+'^)[0,1,3,9]; If ^( ^(Invoke-Expression^($data[2].replace^('k','*1000'^).replace^('M','*1000000'^)^)^) -gt 26 ^){ exit }}
1>NUL "!Chcp!" 65001
IF NOT EXIST "!TmpFile!" (
IF NOT "!LastRedirectURL!"=="" CALL :ColorEcho WARNING def 1 0 "File type for URL "!URL!" could not be determined, because there probably was some problem with curl."
SET "FileExtension=undetermined"
) ELSE (
CALL :DetermineFileExtension "!TmpFile!" FileExtension
)
ENDLOCAL & SET "%ReturnVar1%=%FileExtension%"
EXIT /B 0
REM ------------------------ DetermineFileExtension ------------------------
:DetermineFileExtension
SETLOCAL
SET "ScrFile=%~1"
SET "ReturnVar1=%~2"
REM Get first 26 Bytes
1>NUL "!Chcp!" 1252
FOR /F "DELIMS=" %%A IN ('"!Powershell!" -Command ^(Get-Content '!ScrFile!' -Encoding byte -TotalCount 26^) -Join ' '') DO (SET "First26Bytes=%%A")
1>NUL "!Chcp!" 65001
REM Check signatures/magic bytes
REM Current managable file types: zip, 7z, exe, msi, bat/cmd
IF "!First26Bytes:~,5!"=="77 90" (
SET "FileExtension=exe"
GOTO :Finish2
)
IF "!First26Bytes:~,9!"=="80 75 3 4" (
SET "FileExtension=zip"
GOTO :Finish2
)
IF "!First26Bytes:~,15!"=="58 58 98 97 116" (
REM Because bat/cmd files are plain text, the only way to determine the file type is to
REM manually add the first bytes. Therefore, every batch file that is supposed to be
REM recognized by this package manager must start with "::bat" without the qoutes.
SET "FileExtension=bat"
GOTO :Finish2
)
IF "!First26Bytes:~,13!"=="59 97 104 107" (
REM Cf. IF statement for bat extension, this time with ;ahk
SET "FileExtension=ahk"
GOTO :Finish2
)
IF "!First26Bytes:~,20!"=="55 122 188 175 39 28" (
SET "FileExtension=7z"
GOTO :Finish2
)
IF "!First26Bytes!"=="208 207 17 224 161 177 26 225 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 62 0" (
SET "FileExtension=msi"
GOTO :Finish2
)
SET "FileExtension=unknown"
:Finish2
ENDLOCAL & SET "%ReturnVar1%=%FileExtension%"
EXIT /B 0
REM ------------------------ UpdatePath ------------------------
:UpdatePath
SETLOCAL
CALL :GetPaths "PATH" "OldPATH" "OldSystemPATH"
REM Update this local PATH.
IF "!PATH:%RedirectsDir%=!"=="!PATH!" (
IF NOT "!PATH:~-1!"==";" SET "PATH=!PATH!;"
SET "PATH=!PATH!!RedirectsDir!;!PckDir!"
)
IF "!OldPATH:%RedirectsDir%=!;!OldSystemPATH:%RedirectsDir%=!"=="!OldPATH!;!OldSystemPATH!" (
CALL :ColorEcho INFO def 1 1 "Redirects and PCK directory are not in PATH"
CALL :ColorEcho ACTION def 0 1 "Adding Redirects and PCK directory permanently to PATH with SETX..."
1>NUL 2>&1 SETX PATH "!OldPATH!!RedirectsDir!;!PckDir!"
CALL :GetPaths "PATH" "OldPATH" "OldSystemPATH"
IF "!OldPATH:%RedirectsDir%=!;!OldSystemPATH:%RedirectsDir%=!"=="!OldPATH!;!OldSystemPATH!" (
CALL :ColorEcho "" red 1 1 " Failed^!"
CALL :ColorEcho WARNING def 1 0 "For some unknown reason the Redirects and PCK directories could not be added to PATH."
CALL :Anomaly
) ELSE (
CALL :ColorEcho "" green 1 1 " Success^!"
)
)
ENDLOCAL & SET "PATH=%PATH%"
EXIT /B 0
REM ------------------------ UpdatePathExt ------------------------
:UpdatePathExt
SETLOCAL
CALL :GetPaths "PATHEXT" "OldPATHEXT" "OldSystemPATHEXT"
REM Update this local PATHEXT
IF NOT "!PATHEXT:~-1!"==";" SET "PATHEXT=!PATHEXT!;"
IF "!PATHEXT:.LNK=!"=="!PATHEXT!" (
SET "PATHEXT=!PATHEXT!.LNK"
)
::%$Split% PATHEXT ;
::SET PATHEXT
IF "!OldPATHEXT:.LNK=!;!OldSystemPATHEXT:.LNK=!"=="!OldPATHEXT!;!OldSystemPATHEXT!" (
CALL :ColorEcho INFO def 1 1 "Extension ".LNK" is not in "PATHEXT"."
CALL :ColorEcho ACTION def 0 1 "Adding extension ".LNK" permanently to "PATHEXT" with SETX..."
IF NOT "!OldPATHEXT!"==";" (
1>NUL 2>&1 SETX PATHEXT "!OldPATHEXT!.LNK"
) ELSE (
IF "!PATHEXT:.LNK=!"=="!PATHEXT!" (
1>NUL 2>&1 SETX PATHEXT "!PATHEXT!.LNK"
) ELSE (
1>NUL 2>&1 SETX PATHEXT "!PATHEXT!"
)
)
CALL :GetPaths "PATHEXT" "OldPATHEXT" "OldSystemPATHEXT"
IF "!OldPATHEXT:.LNK=!;!OldSystemPATHEXT:.LNK=!"=="!OldPATHEXT!;!OldSystemPATHEXT!" (
CALL :ColorEcho "" red 1 1 " Failed^!"
CALL :ColorEcho WARNING def 1 0 "For some unknown reason, the ".LNK" extension could not be added to the "PATHEXT" environment variable."
CALL :Anomaly
)
CALL :ColorEcho "" green 1 1 " Success^!"
)
ENDLOCAL & SET "PATHEXT=%PATHEXT%"
EXIT /B 0
REM ------------------------ GetPaths ------------------------
:GetPaths
SETLOCAL
SET "EnvVar=%~1"
SET "ReturnVar1=%~2"
SET "ReturnVar2=%~3"
FOR /F "TOKENS=* SKIP=2" %%A IN ('2^>NUL "!System32!\reg.exe" QUERY "HKEY_CURRENT_USER\Environment" /V "!EnvVar!"') DO (SET "OldPATH=%%A;")
IF NOT DEFINED OldPATH SET "OldPATH=PATH REG_SZ ;"
SET "OldPATH=!OldPATH:REG_SZ=|!"
FOR /F "TOKENS=2 DELIMS=^|" %%A IN ("!OldPATH!") DO (SET "OldPATH=%%A")
CALL :Trim OldPATH OldPATH
SET "OldPATH=!OldPATH:;;=;!"
FOR /F "TOKENS=* SKIP=2" %%A IN ('2^>NUL "!System32!\reg.exe" QUERY "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /V "!EnvVar!"') DO (SET "OldSystemPATH=%%A;")
IF NOT DEFINED OldSystemPATH SET "OldSystemPATH=PATH REG_SZ ;"
SET "OldSystemPATH=!OldSystemPATH:REG_SZ=|!"
FOR /F "TOKENS=2 DELIMS=^|" %%A IN ("!OldSystemPATH!") DO (SET "OldSystemPATH=%%A")
CALL :Trim OldSystemPATH OldSystemPATH
SET "OldSystemPATH=!OldSystemPATH:;;=;!"
ENDLOCAL & SET "%ReturnVar1%=%OldPATH%" & SET "%ReturnVar2%=%OldSystemPATH%"
EXIT /B 0
REM ------------------------ TrimFast ------------------------
:TrimFast
SETLOCAL
SET "String=!%~1!"
SET "ReturnVar1=%~2"
SET String=!String:"='!
CALL :_TrimFast TrimmedString !String!
SET TrimmedString=!TrimmedString:'="!
ENDLOCAL & SET "%ReturnVar1%=%TrimmedString%"
EXIT /B 0
:_TrimFast
SETLOCAL
FOR /F "TOKENS=1*" %%A IN ("%*") DO (ENDLOCAL & SET "%1=%%B")
EXIT /B 0
REM ------------------------ Trim ------------------------
REM Source: https://stackoverflow.com/a/48050848/13823467
:Trim
SETLOCAL
REM Must be defined here.
(SET LF=^
%= BLANK LINE REQUIRED =%
)
REM Must be defined here.
SET "CR=" & IF NOT DEFINED CR FOR /F "SKIP=1" %%C IN ('ECHO(^|"!Replace!" ? . /W /U') DO (SET "CR=%%C")
SET "ddx=!"
SETLOCAL EnableDelayedExpansion
SET "Die="
IF NOT DEFINED %1 (
CALL :ColorEcho WARNING def 1 0 "Trimming failed, because variable "%1" is not defined."
SET "Die=1"
) ELSE (
SET "Str=!%1!"
)
IF NOT DEFINED Die FOR %%L IN ("!LF!") DO (
IF "!Str!" NEQ "!Str:%%~L=!" (
CALL :ColorEcho WARNING def 1 0 "Trimming failed, because variable "%1" contains linefeeds."
SET "Die=1"
)
)
IF NOT DEFINED Die FOR %%C IN ("!CR!") DO (
IF "!Str!" NEQ "!Str:%%~C=!" (
CALL :ColorEcho WARNING def 1 0 "Trimming failed, because variable "%1" contains carriage returns."
SET "Die=1"
)
)
IF DEFINED Die GOTO :Die
(FOR /F EOL^= %%A IN ("!Str!") DO REM NOP
) || (
CALL :ColorEcho WARNING def 1 0 "Trimming failed, because variable "%1" consists entirely of whitespace."
ENDLOCAL & ENDLOCAL & SET "%2=" & EXIT /B 0
)
SET "Str=!Str:^=^^^^!"
SET "Str=!Str:"=""!"
SET "Str=%Str:!=^^^!%" !
CALL :_TRIM "%%Str%%
IF NOT DEFINED ddx SET "Str=!Str:^=^^^^!"
IF NOT DEFINED ddx SET "Str=%Str:!=^^^!%" !
SET "Str=!Str:""="!"
FOR /F TOKENS^=*^ EOL^= %%A IN ("!Str!") DO (
ENDLOCAL & ENDLOCAL & SET "%2=%%A" !
)
EXIT /B 0
:Die
ENDLOCAL & ENDLOCAL & SET "%2=" & EXIT /B 1
:_TRIM
SET "Str=%~1" !
EXIT /B 0
REM "
REM ------------------------ StripQuotes ------------------------
:StripQuotes
SETLOCAL
SET "String=!%~1!"
SET "ReturnVar1=%~2"