-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgrab.lua
1406 lines (1273 loc) · 45.4 KB
/
grab.lua
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
-- Grab : Official OpenComputerScripts Installer
-- Created By Kiritow
local computer=require('computer')
local component=require('component')
local shell=require('shell')
local filesystem=require('filesystem')
local serialization=require('serialization')
local event=require('event')
local term=require('term')
local args,options=shell.parse(...)
local grab_version="Grab v2.5.1.2-alpha"
local grab_infos={
version=grab_version,
grab_options=options
}
local usage_text=[===[Grab - Official OpenComputerScripts Installer
Usage:
grab [<options>] <command> ...
Options:
--cn Skip link check and use mirror site in China. See Link check in Notice for more information.
--help Display this help page.
--version Display version and exit.
--router=<Router File> [Deprecated] Given a file which will be loaded and returns a route function like:
function(RepoName: string, Branch: string ,FileAddress: string): string
--proxy=<Proxy File> Given a file which will be loaded and returns a proxy function like:
function(Url : string): boolean, string
--bin=<path> Set binary install root path.
--lib=<path> Set library install root path.
-f,--force Force overwrite existing files.
-y,--yes Skip interactive confirm.
--skip-install Library installers will not be executed.
--refuse-license <License> Set refused license. Separate multiple values with ','
--accept-license <License> Set accepted license. Separate multiple values with ','
Command:
install <Project> ...: Install projects. Dependency will be installed automatically.
uninstall <Project> ...: Uninstall projects. Dependency will NOT be removed automatically.
verify <Provider> ... : Verify program provider info.
add <Provider> ... : Add program provider info.
update: Update program info.
clear: Clear program info.
list: List available projects.
search <Name or Pattern> : Search projects by name
show <Project> : Show more info about project.
download <Filename> ...: Directly download files. (Just like the old `update`!)
Notice:
License
By downloading and using Grab, you are indicating your agreement to MIT license. (https://github.com/Kiritow/OpenComputerScripts/blob/master/LICENSE)
All scripts in official OpenComputerScript repository are under MIT license.
Before downloading any package under other licenses, Grab will ask you to agree with it.
This confirmation can be skipped by calling Grab with --accept-license.
Example:
--accept-license=mit means MIT License is accepted.
--refuse-license=mit means MIT License is refused.
--accept-license means all licenses are accepted.
--refuse-license means all licenses are refused. (Official packages are not affected.)
If a license is both accepted and refused, it will be refused.
Program Provider
A package is considered to be official only if it does not specified repo and proxy. Official packages usually only depend on official packages.
You can also install packages from unofficial program provider with Grab, but Grab will not check its security.
Notice that override of official packages is not allowed.
Router and Proxy
[Deprecated] route_func(RepoName: string, Branch: string ,FileAddress: string): string
A route function takes repo, branch and file address as arguments, and returns a resolved url.
It can be used to boost downloading by redirecting requests to mirror site.
As router functions can be used to redirect requests, Grab will give an warning if --router option presents.
[Warning] --router option is deprecated and will be removed in future.
proxy_func(Url : string): boolean, string
A proxy function takes url as argument, and returns at least 2 values.
It can be used to handle different protocols or low-level network operations like downloading files via SOCKS5 proxy or in-game modem network.
The first returned value is true if content is downloaded successfully. Thus, the second value will be the downloaded content.
If the first value is false, the downloading is failed. The second value will then be the error message.
If proxy functions throw an error, Grab will try the default downloader.
Installer
A package can provide an installer for Grab. It will be loaded and executed after the package is ready.
Thus require(...) calls on depended libraries is ok.
From Grab v2.4.6, installer should return a function, which will be later called with a table filled with some information.
If nothing is returned, Grab will give an warning and ignore it.
From Grab v2.4.8, option `installer` is deprecated. Use __installer__ instead.
Link Check
Grab will perform a link check before downloading anything. The link check will choose to download from Github or mirror site in China.
This might only be useful for official packages.
]===]
-- Install man document.
local function _local_install()
local f=io.open("/etc/grab/grab.version","w")
if(f) then
f:write(grab_version)
f:close()
end
f=io.open("/usr/man/grab","w")
if(f) then
f:write(usage_text)
f:close()
end
end
if(not filesystem.exists("/etc/grab/grab.version")) then
_local_install()
else
local f=io.open("/etc/grab/grab.version","r")
if(f) then
local installed_version=f:read("a")
f:close()
if(installed_version~=grab_version) then
_local_install()
end
end
end
local function show_usage()
if(filesystem.exists("/usr/man/grab")) then
os.execute("less /usr/man/grab")
else
local temp_name=os.tmpname()
local f=io.open(temp_name,"w")
f:write(usage_text)
f:close()
os.execute("less " .. temp_name)
os.execute("rm " .. temp_name)
end
end
local valid_options={
["cn"]=true,
["help"]=true,
["version"]=true,
["router"]="string",
["proxy"]="string",
["bin"]="string",
["lib"]="string",
["f"]=true,
["force"]=true,
["y"]=true,
["yes"]=true,
["skip-install"]=true,
["refuse-license"]=true,
["accept-license"]=true,
}
local valid_command={
["install"]=true,
["uninstall"]=true,
["verify"]=true,
["add"]=true,
["update"]=true,
["clear"]=true,
["list"]=true,
["search"]=true,
["show"]=true,
["download"]=true
}
for k,v in pairs(options) do
if(not valid_options[k]) then
if(string.len(k)>1) then
print("Unknown option: --" .. k)
else
print("Unknown option: -" .. k)
end
return
elseif(type(valid_options[k])=="string") then
if(type(options[k])~=valid_options[k]) then
print("Invalid option type: Option type of --" .. k .. " should be " .. valid_options[k])
return
end
end
end
if( #args<1 and not next(options) ) then
print("grab: try 'grab --help' for more information.")
return
end
if(options["help"]) then
show_usage()
return
end
if(options["version"]) then
print(grab_version)
return
end
local function optionYes()
return options["y"] or options["yes"]
end
local function optionForce()
return options["f"] or options["force"]
end
local function check_internet()
if(not options["proxy"] and not component.list("internet")()) then
print("Error: An internet card is required to run this program.")
return false
else
-- If proxy presents, internet card is not required. Programs may handle network requests via in-game modem network.
return true
end
end
local function default_downloader(url)
if(not component.list("internet")()) then
return false,"No internet card found."
end
local handle=component.internet.request(url)
while true do
local ret,err=handle.finishConnect()
if(ret==nil) then
return false,err
elseif(ret==true) then
break
else
local ev=event.pull(0.05,"interrupted")
if(ev~=nil) then
handle.close()
return false,"Interrupted from terminal."
end
end
end
local code=handle.response()
if(code~=200) then
handle.close()
return false,"Response code " .. code .. " is not 200."
end
local result=''
while true do
local temp=handle.read()
if(temp==nil) then break end
result=result .. temp
end
handle.close()
return true,result
end
local download
if(not options["proxy"]) then
download=default_downloader
else
local ok,err=pcall(function()
local fn,xerr=loadfile(options["proxy"])
if(not fn) then
error(xerr)
else
tmp=fn()
if(type(tmp)~="function") then
error("Loaded proxy returns " .. type(tmp) .. " instead of a function.")
end
download=function(url)
local pok,ok,data=pcall(tmp,url)
if(pok) then
return ok,data
else
return default_downloader(url)
end
end
end
end)
if(not ok) then
print("Unable to load proxy file: " .. err)
return
end
print("[WARN] Proxy presents. Be aware of security issues.")
end
local function link_check()
local ok,data=download("http://registry.kiritow.com/gateway")
if(ok and data=="CN") then
return true
else
return false
end
end
local function _MirrorUrlGen(RepoName,Branch,FileAddress)
return "http://kiritow.com:3000/" .. RepoName .. "/raw/" .. Branch .. "/" .. FileAddress
end
local function _GithubUrlGen(RepoName,Branch,FileAddress)
return "https://raw.githubusercontent.com/" .. RepoName .. "/" .. Branch .. "/" .. FileAddress
end
local UrlGenerator
if(not options["router"]) then
if(options["cn"] or link_check()) then
UrlGenerator=_MirrorUrlGen
else
UrlGenerator=_GithubUrlGen
end
else
print("[WARN] --router option is deprecated and will be removed in future.")
local ok,err=pcall(function()
local fn,xerr=loadfile(options["router"])
if(not fn) then
error(xerr)
else
UrlGenerator=fn()
if(type(UrlGenerator)~="function") then
error("Loaded router returns " .. type(UrlGenerator) .. " instead of a function.")
end
end
end)
if(not ok) then
print("Unable to load router file: " .. err)
return
end
print("[WARN] Router presents. Be aware of security issues.")
end
local function IsOfficial(tb_package)
if(tb_package.repo==nil and
tb_package.proxy==nil and
tb_package.provider==nil
) then
return true
else
return false
end
end
local grab_dir=''
local function CheckGrabDir()
local locations={"/etc/grab","/home/.grab","/tmp/.grab"}
for idx,position in ipairs(locations) do
if(filesystem.isDirectory(position)) then
grab_dir=position
return true
else
local ok=filesystem.makeDirectory(position)
if(ok) then grab_dir=position return true end
end
end
return false
end
if(not CheckGrabDir()) then
print("[Error] Grab working directory not usable.")
return
else
print("Grab directory: " .. grab_dir)
end
local function VerifyDB(this_db)
for k,t in pairs(this_db) do
if(type(k)~="string") then
return false,"Invalid key type: " .. type(k)
elseif(type(t)~="table") then
return false,"Invalid value type: " .. type(t)
elseif(not t.title) then
return false,"Library " .. k .. " does not provide title."
elseif(not t.info) then
return false,"Library " .. k .. " does not provide info."
elseif(not t.files) then
return false,"Library " .. k .. " has no file."
end
for kk,vv in pairs(t.files) do
if(type(kk)=="number") then
if(type(vv)~="string") then
return false,"Library " .. k .. " file " .. kk .. " has invalid value type " .. type(vv)
end
elseif(type(kk)=="string") then
if(type(vv)=="table") then
for idx,val in pairs(vv) do
if(type(idx)~="number" or type(val)~="string") then
return false,"Library " .. k .. " file " .. kk .. " table has invalid key,value type: " .. type(idx) .. "," .. type(val)
end
end
elseif(type(vv)~="string") then
return false,"Library " .. k .. " file " .. kk .. " has invalid value type " .. type(vv)
end
else
return false,"Library " .. k .. " file has invalid key type " .. type(kk)
end
end
if(t.author and type(t.author)~="string") then
return false,"Library " .. k .. " has invalid author type: " .. type(t.author)
end
if(t.contact and type(t.contact)~="string") then
return false,"Library " .. k .. " has invalid contact type: " .. type(t.contact)
end
if(t.requires) then
for kk,vv in pairs(t.requires) do
if(type(kk)~="number" or type(vv)~="string") then
return false,"Library " .. k .. " has invalid requires with key type " .. type(kk) .. ", value type " .. type(vv)
end
end
end
if(t.license) then
if(type(t.license.name)~="string") then
return false,"Library " .. k .. " has invalid license name type " .. type(t.license.name)
elseif(type(t.license.url)~="string") then
return false,"Library " .. k .. " has invalid license url type " .. type(t.license.url)
end
end
if(t.provider) then
if(type(t.provider)~="string") then
return false,"Library " .. k .. " has invalid provider type " .. type(t.provider)
end
end
if(t.hidden~=nil) then
if(type(t.hidden)~="boolean") then
return false,"Library " .. k .. " has invalid hidden type " .. type(t.hidden)
end
end
end
return true,"No error detected."
end
local function CheckAndLoadEx(raw_content,chunkname)
local fn,err=load(raw_content,chunkname)
if(fn) then
local ok,result=pcall(fn)
if(ok) then
return result
else return nil,result end
end
return nil,err
end
local function CheckAndLoad(raw_content,chunkname)
local result,err=CheckAndLoadEx(raw_content,chunkname)
if(not result) then
return result,err
end
local ok,err=VerifyDB(result)
if(not ok) then
return nil,err
else
return result
end
end
local function ReadDB(read_from_this)
if(read_from_this) then
local f=io.open(read_from_this,"r")
if(f) then
local result=serialization.unserialize(f:read("*a"))
f:close()
return result,filename
else
return nil
end
end
local filename=grab_dir .. "/programs.info"
local a,b=ReadDB(filename)
if(a) then return a,b end
return nil
end
local function WriteDB(filename,tb)
local f=io.open(filename,"w")
if(f) then
f:write(serialization.serialize(tb))
f:close()
return true
end
return false
end
local function UpdateDB(main_tb,new_tb,checked) -- Change values with same key in main_tb to values in new_tb. Add new items to main_tb
for k,v in pairs(new_tb) do
if(checked and main_tb[k]) then
if(IsOfficial(main_tb[k])) then
print("UpdateDB: Attempted to override official library: " .. k)
return false
else
print("UpdateDB: Override library: " .. k)
end
end
main_tb[k]=v
end
return true
end
local function CreateDB(tb,checked) -- If checked, merging is not allowed.
local filename=grab_dir .. "/programs.info"
local main_db=ReadDB(filename)
if(main_db) then
if(not UpdateDB(main_db,tb,checked)) then
return nil
end
if(WriteDB(filename,main_db)) then
return filename
end
else
if(WriteDB(filename,tb)) then
return filename
end
end
end
local function GetDBVersion()
local f=io.open(grab_dir .. "/list.version","rb")
if(not f) then
return ''
else
local s=f:read("*a")
f:close()
return s
end
end
local function SaveDBVersion(ver)
local f=io.open(grab_dir .. "/list.version","wb")
if(not f) then
return false
else
f:write(ver)
f:close()
return true
end
end
if(args[1]=="clear") then
print("Clearing programs info...")
filesystem.remove(grab_dir .. "/programs.info")
print("Programs info cleaned. You may want to run `grab update` now.")
return
end
if(args[1]=="update") then
if(not check_internet()) then return end
print("Checking package list version...")
local ok,result=download("http://registry.kiritow.com/listver")
local remoteURL
local remoteVer
if(not ok) then
print("[Skipped] Skipped package list version checking: " .. result)
remoteURL=UrlGenerator('Kiritow/OpenComputerScripts','master','programs.info')
remoteVer=nil
else
if(GetDBVersion()==result) then
print("Already up to date.")
else
remoteURL="http://registry.kiritow.com/list/" .. result
remoteVer=result
end
end
print("Updating package list....")
io.write("Downloading... ")
ok,result=download(remoteURL)
if(not ok) then
print("[Failed] " .. result)
return
else
print("[OK]")
io.write("Validating... ")
local tb_data,validate_err=CheckAndLoad("return " .. result,"Remote ProgramDB")
result=nil -- release memory
if(tb_data) then
print("[OK]")
io.write("Saving files... ")
local dbfilename=CreateDB(tb_data,false)
if(dbfilename) then
print("[OK]")
print("Package list updated and saved to " .. dbfilename)
else
print("[Failed] Unable to save package list.")
return
end
else
print("[Failed]" .. validate_err)
return
end
end
print("Updating package list version...")
if(remoteVer) then
SaveDBVersion(remoteVer)
else
print("[Skipped] Not update from registry.")
end
return
end
local db,dbfilename=ReadDB()
local function check_db()
if(db) then return true
else
print("No programs info found on this computer.")
print("Please run `grab update` first.")
return false
end
end
local function pairsKey(tb)
local tmp={}
for k in pairs(tb) do table.insert(tmp,k) end
table.sort(tmp)
local i=0
return function()
i=i+1
return tmp[i],tb[tmp[i]]
end,tb,nil
end
if(args[1]=="verify") then
if(#args<2) then
print("Nothing to verify.")
return
end
for i=2,#args,1 do
local url=string.match(args[i],"^http[s]?://%S+")
if(url==nil) then
local filename=args[i]
local f=io.open(filename,"r")
if(not f) then
print("Unable to open local file: " .. filename)
else
local content=f:read("*a")
f:close()
local t,err=CheckAndLoad("return " .. content,"Local ProgramDB")
if(t) then
print("[Verified] Contains the following library: ")
for k in pairsKey(t) do
print(k)
end
else
print("Failed to load local file: " .. filename .. ". Error: " .. err)
end
end
else
print("Downloading from " .. url)
local ok,result=download(url)
if(not ok) then
print("[Download Failed] " .. result)
else
local t,err=CheckAndLoad("return " .. result,"Remote ProgramDB")
if(t) then
print("[Verified] Contains the following library: ")
for k in pairs(t) do
print(k)
end
else
print("Failed to load downloaded content. Error: " .. err)
end
end
end
end
return
end
if(args[1]=="add") then
if(#args<2) then
print("Nothing to add.")
return
end
if(not check_db()) then
return
end
print("[WARN] Adding unofficial program providers may have security issues.")
for i=2,#args,1 do
local url=string.match(args[i],"^http[s]?://%S+")
if(url==nil) then
local filename=args[i]
local f=io.open(filename,"r")
if(not f) then
print("Unable to open local file: " .. filename)
else
local content=f:read("*a")
f:close()
local t,err=CheckAndLoad("return " .. content,"Local ProgramDB")
if(t) then
print("Updating with local file: " .. filename)
local fname=CreateDB(t,true)
if(fname) then
print("Programs info updated and saved to " .. fname)
else
print("Unable to update programs info.")
end
else
print("Failed to load local file: " .. filename .. ". Error: " .. err)
end
end
else
print("Downloading from " .. url)
local ok,result=download(url)
if(not ok) then
print("[Download Failed] " .. result)
else
local t,err=CheckAndLoad("return " .. result,"Remote ProgramDB")
if(t) then
print("Updating with downloaded content...")
local fname=CreateDB(t,true)
if(fname) then
print("Programs info updated and saved to " .. fname)
else
print("Unable to update programs info.")
end
else
print("Failed to load downloaded content. Error: " .. err)
end
end
end
end
return
end
local function getshowbyte(n)
if(n<1024) then
return string.format("%.1f B",n+0.0)
elseif(n<1024*1024) then
return string.format("%.1f KB",n/1024)
else
return string.format("%.1f MB",n/1024/1024)
end
end
local function getshowtime(n)
if(n<60) then
return string.format("%.1fs",n+0.0)
else
return string.format("%.0fm%.0fs",n/3600,n%3600)
end
end
local function getshowspeed(n)
if(n<1024) then
return string.format("%.1f B/s",n+0.0)
elseif(n<1024*1024) then
return string.format("%.1f KB/s",n/1024)
else
return string.format("%.1f MB/s",n/1024/1024)
end
end
local function try_resolve_path(src,dst,only_parse)
-- TIPS:
-- filesystem.makeDirectory(...) can throw error because it does not check arguments.
local fsMakeDir
if(not only_parse) then
fsMakeDir=filesystem.makeDirectory
else
fsMakeDir=function() return true end
end
if(type(src)~="string") then -- Only source path is specified in programs.info
local segs=filesystem.segments(dst)
return true,segs[#segs]
end
dst=string.gsub(
string.gsub(
dst,
"__bin__",
options["bin"] or "/usr/bin"
),
"__lib__",
options["lib"] or "/usr/lib"
)
if(dst:sub(dst:len())=='/') then -- dst is a directory. prepare it and build the filename.
if(not fsMakeDir(dst) and not filesystem.exists(dst)) then
return false,"Failed to create directory: " .. dst
else
local tb_segsrc=filesystem.segments(src)
return true,dst .. tb_segsrc[#tb_segsrc]
end
else -- dst is the filename. Prepare directories.
local tb_segdst=filesystem.segments(dst)
if(#tb_segdst>1) then
local name=table.concat(tb_segdst,"/",1,#tb_segdst-1)
if(not fsMakeDir(name) and not filesystem.exists(name)) then
return false,"Failed to create directory: " .. name
end
end
return true,dst
end
end
local function string_similar_value(a,b)
local x,y=a:len(),b:len()
local min=( (x>y) and y or x)
local c=0
for i=1,min do
if(a:sub(i,i)==b:sub(i,i)) then
c=c+1
end
end
return c
end
local function miss_suggestion(wrong_name,ktb)
local max=0
local maxname=nil
for this_lib in pairs(ktb) do
local a=string_similar_value(wrong_name,this_lib)
if(a>max) then
max=a
maxname=this_lib
end
end
return maxname,max
end
local function will_overwrite(filename)
if(optionForce()) then
return false
else
local f=io.open(filename,"rb")
if(f) then
f:close()
print("[Error] Stop before overwrite regular file: " .. filename)
return true
else
return false
end
end
end
if(args[1]=="install") then
if(#args<2) then
print("Nothing to install.")
return
else
if(not check_internet()) then return end
print("Checking programs info...")
end
if(not check_db()) then return end
if(optionForce()) then
print("[WARN] Using force mode. I sure hope you know what you are doing.")
end
local to_install={}
for i=2,#args,1 do
to_install[args[i]]=true
end
local newly_added=0
while true do
local to_add={}
for this_lib in pairs(to_install) do
if(not db[this_lib]) then
print("Library '" .. this_lib .. "' not found.")
local maybe_this=miss_suggestion(this_lib,db)
if(maybe_this) then
print("You might want library '" .. maybe_this .. "'.")
end
return
else
if(db[this_lib].requires) then
for idx,this_req in ipairs(db[this_lib].requires) do
if(not to_install[this_req] and not to_add[this_req]) then
newly_added=newly_added+1
to_add[this_req]=true
end
end
end
end
end
for this_lib in pairs(to_add) do
to_install[this_lib]=true
end
if(newly_added==0) then break
else
newly_added=0
end
end
print("About to install the following libraries:")
local count_libs=0
local count_files=0
io.write("\t")
for this_lib in pairsKey(to_install) do
io.write(this_lib .. " ")
count_libs=count_libs+1
for k in pairs(db[this_lib].files) do
count_files=count_files+1
end
end
print("\n" .. count_libs .. " libraries will be installed. " .. count_files .. " files will be downloaded.")
local warn_libs_unofficial={}
for this_lib in pairs(to_install) do
if(not IsOfficial(db[this_lib])) then
table.insert(warn_libs_unofficial,this_lib)
end
end
if(next(warn_libs_unofficial)) then
print("[WARN] The following libraries are unofficial. Install at your own risk.")
print("\t" .. table.concat(warn_libs_unofficial," "))
end
-- If more libraries will be installed or unofficial libraries present, pop up a confirm.
if(not optionYes() and (count_libs>#args-1 or next(warn_libs_unofficial))) then
io.write("Do you want to continue? [Y/n]: ")
local line=io.read("l")
if(not (line:len()<1 or line:sub(1,1)=="Y" or line:sub(1,1)=="y")) then
print("Aborted.")
return
end
end
-- Third-Party programs or unofficial programs may have license.
print("Checking License...")
local accepted_license={}
local refused_license={}
if(options["accept-license"]) then
if(type(options["accept-license"])=="boolean") then
accepted_license["__ALL__"]=true
else
local next_license=string.gmatch(options["accept-license"] .. ',',"[A-Za-z0-9]+,")
while true do
local this_license=next_license()
if(not this_license) then break end
this_license=string.lower(string.gsub(this_license,',',''))
accepted_license[this_license]=true
end
end
end
if(options["refuse-license"]) then
if(type(options["refuse-license"])=="boolean") then
refused_license["__ALL__"]=true
else
local next_license=string.gmatch(options["refuse-license"] .. ',',"[A-Za-z0-9]+,")
while true do
local this_license=next_license()
if(not this_license) then break end
this_license=string.lower(string.gsub(this_license,',',''))
refused_license[this_license]=true
end
end
end
for this_lib in pairs(to_install) do
if(not IsOfficial(db[this_lib]) and db[this_lib].license) then
if(refused_license["__ALL__"] or refused_license[string.lower(db[this_lib].license.name)]) then
print("[License Refused] License " .. db[this_lib].license.name .. " for library " .. this_lib .. " is refused.")
return
elseif(accepted_license["__ALL__"] or accepted_license[string.lower(db[this_lib].license.name)]) then
print("Accepted license " .. db[this_lib].license.name .. " for library " .. this_lib)
else
-- Download the license and show it to user.
print("Downloading license " .. db[this_lib].license.name .. " for library " .. this_lib .. " from: " .. db[this_lib].license.url)
local ok,result=download(db[this_lib].license.url)
if(not ok) then
print("[Download Failed] Failed to download license.")
return
end
local temp_name=os.tmpname()
local f=io.open(temp_name,"w")
f:write("----------Grab----------\nYou have to agree with this license for library " .. this_lib .. "\n------------------------\n\n")
f:write(result)
f:close()
local confirmed=false
while not confirmed do
os.execute("less " .. temp_name)
print("Do you agree with that license?")
print("(Y) - Yes. (N) - No. (A) - View it again.")
while true do
local x=io.read()
if(x~=nil) then
if(x=='y' or x=='Y') then
confirmed=1
break
elseif(x=='n' or x=='N') then
confirmed=2
break
elseif(x=='a' or x=='A') then
break
end
end
end
end
filesystem.remove(temp_name)
if(confirmed==2) then