-
Notifications
You must be signed in to change notification settings - Fork 0
/
njs50-package-manager.xml
1825 lines (1565 loc) · 61.1 KB
/
njs50-package-manager.xml
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
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE MudletPackage>
<MudletPackage version="1.001">
<TriggerPackage />
<TimerPackage>
<Timer isActive="no" isFolder="no" isTempTimer="no" isOffsetTimer="no">
<name>check for updates</name>
<script>expandAlias('njs50pm status')</script>
<command></command>
<packageName></packageName>
<time>00:20:00.000</time>
</Timer>
<Timer isActive="yes" isFolder="no" isTempTimer="no" isOffsetTimer="no">
<name>auto update packages</name>
<script>-- nb: even tho this runs every two hours, the check will only
-- happen once per day while mudlet remains open
njs50pm.autoUpdateCheck()</script>
<command></command>
<packageName></packageName>
<time>02:00:00.000</time>
</Timer>
</TimerPackage>
<AliasPackage>
<Alias isActive="yes" isFolder="no">
<name>njs50pm</name>
<script>cecho('\n<green>njs50pm:<white> package manager commands\n')
cecho('<white>njs50pm help<reset> - View the contents of this help file\n')
cecho('<white>njs50pm list<reset> - List packages available to install\n')
cecho('<white>njs50pm install <package><reset> - Show status of installed packages\n')
cecho('<white>njs50pm update<reset> - Update any installed packages if possible\n')
cecho('<white>njs50pm update <package><reset> - Update a specific package if possible\n')
cecho('<white>njs50pm status<reset> - Show status of installed packages\n')
cecho('\n')
</script>
<command></command>
<packageName></packageName>
<regex>^(njs50pm|njs50pm help)$</regex>
</Alias>
<Alias isActive="yes" isFolder="no">
<name>njs50pm list</name>
<script>-- cecho('\n\n<green>njs50pm:<white> available packages...\n')
njs50pm.list()</script>
<command></command>
<packageName></packageName>
<regex>^njs50pm list$</regex>
</Alias>
<Alias isActive="yes" isFolder="no">
<name>njs50pm install</name>
<script>local pkg = matches[2]
cecho('\n\n<green>njs50pm:<white> installing package : ' .. pkg .. '\n')
njs50pm.install(pkg)
</script>
<command></command>
<packageName></packageName>
<regex>^njs50pm install (.*)$</regex>
</Alias>
<Alias isActive="yes" isFolder="no">
<name>njs50pm update</name>
<script>cecho('\n\n<green>njs50pm:<white> checking for updates...\n')
njs50pm.updateAll()</script>
<command></command>
<packageName></packageName>
<regex>^njs50pm update$</regex>
</Alias>
<Alias isActive="yes" isFolder="no">
<name>njs50pm update specific</name>
<script>local pkg = matches[2]
cecho('\n\n<green>njs50pm:<white> updating package : ' .. pkg .. '\n')
-- clear the cache if we are trying to upgrade a specific package
njs50pm.clearCache(pkg)
njs50pm.upgradeIfAvailable(pkg)
-- njs50pm.updateAll()</script>
<command></command>
<packageName></packageName>
<regex>^njs50pm update (.*)$</regex>
</Alias>
<Alias isActive="yes" isFolder="no">
<name>njs50pm uninstall</name>
<script>local pkg = matches[2]
cecho('\n\n<green>njs50pm:<white> uninstalling package : ' .. pkg .. '\n')
njs50pm.uninstall(pkg)
-- njs50pm.updateAll()</script>
<command></command>
<packageName></packageName>
<regex>^njs50pm uninstall (.*)$</regex>
</Alias>
<Alias isActive="yes" isFolder="no">
<name>njs50pm status</name>
<script>cecho('\n\n<green>njs50pm:<white> installed package status...\n')
njs50pm.showStatus()</script>
<command></command>
<packageName></packageName>
<regex>^njs50pm status$</regex>
</Alias>
</AliasPackage>
<ActionPackage />
<ScriptPackage>
<Script isActive="yes" isFolder="no">
<name>njs50pm</name>
<packageName></packageName>
<script>-- exmaples:
-- install tfecat / my mapper
-- lua njs50pm.install({module = 'tfecat', githubPath = '/mudlet/tfecat.module'})
-- lua njs50pm.install({module = 'tfe-mapper'})
-- modify a packages metadata to make it look like it needs an update
-- lua setPackageInfo('tfecat', "njs50-hash", 'bannana')
-- check all installed modules status
-- lua njs50pm.showStatus()
-- get all available updates
-- lua njs50pm.updateAll()
-- update a single module if there is an update
-- lua njs50pm.upgradeIfAvailable('tfecat')
njs50pm = njs50pm or {}
-- until the mudlet functions persist...
njs50pm.setPackageInfo = function(package, variable, value)
if not njs50pm.packageInfo then
njs50pm.packageInfo = {}
if io.exists(getMudletHomeDir().."/njs50PackageInfo.lua") then
table.load(getMudletHomeDir().."/njs50PackageInfo.lua", njs50pm.packageInfo)
end
end
-- -- set the packageInfo anyway?
-- setPackageInfo(package, variable, value)
njs50pm.packageInfo[package] = njs50pm.packageInfo[package] or {}
if (value == '') then
value = nil
end
njs50pm.packageInfo[package][variable] = value
table.save(getMudletHomeDir().."/njs50PackageInfo.lua", njs50pm.packageInfo)
end
njs50pm.getPackageInfo = function(package, variable)
if not njs50pm.packageInfo then
njs50pm.packageInfo = {}
if io.exists(getMudletHomeDir().."/njs50PackageInfo.lua") then
table.load(getMudletHomeDir().."/njs50PackageInfo.lua", njs50pm.packageInfo)
end
end
local vp = njs50pm.packageInfo[package] or {}
local value = vp[variable]
if not value then
value = ""
end
return value
end
njs50pm.log = function(pkg, msg)
cecho('\n<green>njs50pm: <white>' .. pkg .. ' package ' .. msg .. '!\n')
end
njs50pm.isInstalled = function(package)
return table.contains(getPackages(), package)
end
njs50pm.getStatus = function(callback)
-- make sure all installed packages have the correct metadata
njs50pm.checkPackageMetadata()
local co
local installed = {}
co = coroutine.create(function()
for idx, mod in ipairs(getPackages()) do
local package = njs50pm.getLocalMetadata(mod)
if package.hash ~= '' then
package.callback = function(hash)
table.insert(installed, {
name = mod,
metadata = package,
remoteHash = hash
})
local ok, errorMsg = coroutine.resume(co)
if not ok then
error("Error in co-routine njs50pm: " .. errorMsg)
end
end
njs50pm.getRemoteHash(package)
coroutine.yield()
end
end
callback(installed)
end)
local ok, errorMsg = coroutine.resume(co)
if not ok then
error("Error in co-routine njs50pm: " .. errorMsg)
end
end
njs50pm.showStatus = function()
njs50pm.getStatus(function(installed)
if (#installed > 0) then
for idx, package in ipairs(installed) do
cecho('<white>' .. package.name .. ' : ')
if (package.remoteHash == package.metadata.hash) then
cecho('<green>latest version: <white>' .. package.metadata.hash .. '\n')
else
cecho('<orange>update available: <white>' .. package.remoteHash .. ' from ' .. package.metadata.hash .. '\n')
end
end
else
cecho('\n<green>njs50pm:<white> no packages installed\n\n')
end
end)
end
njs50pm.updateAll = function()
njs50pm.getStatus(function(installed)
local co
co = coroutine.create(function()
if (#installed > 0) then
for idx, package in ipairs(installed) do
cecho('<white>' .. package.name .. ' : ')
if (package.remoteHash == package.metadata.hash) then
cecho('<green>latest version\n')
else
cecho('<orange>updating\n')
njs50pm.upgradeIfAvailable(package.name, function()
local ok, errorMsg = coroutine.resume(co)
if not ok then
error("Error in upgrade co-routine njs50pm: " .. errorMsg)
end
end)
coroutine.yield()
end
end
else
cecho('\n<green>njs50pm:<white> no packages installed\n\n')
end
end) -- end coroutine
local ok, errorMsg = coroutine.resume(co)
if not ok then
error("Error in co-routine njs50pm: " .. errorMsg)
end
end)
end
njs50pm.upgradeIfAvailable = function(mod, cb)
if not mod or mod == '' then
cecho('\n<red>njs50pm:<white> module is a required option\n\n')
return
end
local options = njs50pm.getLocalMetadata(mod)
if (options.module == '') then
cecho('\n<red>njs50pm:<white> package not found (' .. mod .. ') \n\n')
return
end
options.callback = cb
njs50pm.isUpdateAvailable({
module = options.module,
githubUser = options.githubUser,
branch = options.branch,
callback = function(bUpdateAvailable)
if (bUpdateAvailable) then
cecho('\n<yellow>njs50pm:<white> ' .. options.module .. ' has an update available!\n')
njs50pm.install(options)
else
cecho('\n<green>njs50pm:<white> ' .. options.module .. ' is up to date!\n')
if (cb) then cb() end
end
end
})
end
njs50pm.isUpdateAvailable = function(options)
if not options or type(options) ~= 'table' or not options.module then
cecho('\n<red>njs50pm:<white> module is a required option\n\n')
return
end
options.githubUser = options.githubUser or 'njs50'
options.branch = options.branch or 'main'
options.callback = options.callback or display
local currentHash = njs50pm.getPackageInfo(options.module, 'njs50-hash')
njs50pm.getRemoteHash({
module = options.module,
githubUser = options.githubUser,
branch = options.branch,
callback = function(hash)
options.callback(hash ~= currentHash)
end,
})
end
njs50pm.uninstall = function(package)
if (njs50pm.isInstalled(package)) then
njs50pm.setPackageInfo(package, "njs50-module", '')
njs50pm.setPackageInfo(package, "njs50-hash", '')
njs50pm.setPackageInfo(package, "njs50-branch", '')
njs50pm.setPackageInfo(package, "njs50-githubUser", '')
njs50pm.setPackageInfo(package, "njs50-githubPath", '')
uninstallPackage(package)
njs50pm.log(package, 'uninstalled')
else
njs50pm.log(package, 'was not installed')
end
end
njs50pm.install = function (options)
if type(options) == 'string' then
if (options ~= '' and njs50pm.packages[options]) then
options = njs50pm.packages[options]
else
cecho('\n<red>njs50pm:<white> unknown package: ' .. options .. '\n\n')
return
end
end
if not options or type(options) ~= 'table' or not options.module then
cecho('\n<red>njs50pm:<white> a package is a required \n\n')
return
end
if table.contains(getModules(), options.module) then
cecho('\n<red>njs50pm:<white> this package is already installed as a module!\n\n')
return
end
options.githubUser = options.githubUser or 'njs50'
options.branch = options.branch or 'main'
options.callback = options.callback or function() end
options.githubPath = options.githubPath or ''
njs50pm.getRemoteHash({
module = options.module,
githubUser = options.githubUser,
branch = options.branch,
callback = function(hash)
-- njs50/tfecat/fb20eb10f6c0e0bf40354b62a0a3a752642075e6/mudlet/tfecat.module/tfecat.xml
local URL = 'https://raw.githubusercontent.com/' .. options.githubUser ..
'/' .. options.module .. '/' .. hash .. options.githubPath ..
'/' .. options.module .. '.xml'
local installHandler
installHandler = registerAnonymousEventHandler("sysInstallPackage", function(_, name)
-- stop if what got installed isn't my thing
if name ~= options.module then
return
end
killAnonymousEventHandler(installHandler)
njs50pm.setPackageInfo(options.module, "njs50-module", options.module)
njs50pm.setPackageInfo(options.module, "njs50-hash", hash)
njs50pm.setPackageInfo(options.module, "njs50-branch", options.branch)
njs50pm.setPackageInfo(options.module, "njs50-githubUser", options.githubUser)
njs50pm.setPackageInfo(options.module, "njs50-githubPath", options.githubPath)
njs50pm.log(options.module, 'installed')
raiseEvent('COMMON:njs50-module-updated-' .. options.module)
options.callback()
end)
if (njs50pm.isInstalled(options.module)) then
uninstallPackage(options.module)
njs50pm.log(options.module, 'uninstalled')
tempTimer(2, function()
installPackage(URL)
end)
else
installPackage(URL)
end
end
})
end
njs50pm.getLocalMetadata = function(mod)
return {
['module'] = njs50pm.getPackageInfo(mod, "njs50-module"),
hash = njs50pm.getPackageInfo(mod, "njs50-hash"),
branch = njs50pm.getPackageInfo(mod, "njs50-branch"),
githubUser = njs50pm.getPackageInfo(mod, "njs50-githubUser"),
githubPath = njs50pm.getPackageInfo(mod, "njs50-githubPath"),
}
end
-- options are:
-- module (required) i.e tfecat
--
-- branch (optional, defaults to main)
--
njs50pm.checkRateLimit = function()
--
local url = "https://api.github.com/rate_limit"
local header = {["Content-Type"] = "application/json"}
local responseHandler, errorHandler
local selfDestruct = function()
killAnonymousEventHandler(responseHandler)
killAnonymousEventHandler(errorHandler)
end
-- first we create something to handle the success, and tell us what we got
responseHandler = registerAnonymousEventHandler('sysGetHttpDone', function(event, rurl, response)
if rurl == url then
selfDestruct()
response = yajl.to_value(response)
if (response.rate.remaining == 0) then
-- cecho('\n<orange>GITHUB:<white> API unlocks in ' .. common.formatElapsedTime((response.rate.reset) - getEpoch()) .. '\n')
cecho('\n<orange>GITHUB:<white> API unlocks in ' .. tostring((response.rate.reset) - getEpoch()) .. 's\n')
else
cecho('\n<green>GITHUB:<white> ' .. tostring(response.rate.remaining) .. ' API requests remaining\n')
end
end
end)
-- then we create something to handle the error message, and tell us what went wrong
errorHandler = registerAnonymousEventHandler('sysGetHttpError', function(event, response, rurl)
if rurl == url then
selfDestruct()
cecho('\n<red>njs50pm:<white> failed to retrieve rate limit data from github\n\n')
display(response)
end
end)
-- Lastly, we make the request:
getHTTP(url, header)
end
njs50pm.hashCache = njs50pm.hashCache or {}
njs50pm.clearCache = function(module)
if not module or module == '' then
njs50pm.hashCache = {}
else
njs50pm.hashCache[module] = nil
end
end
njs50pm.cacheTime = 20 * 60 -- 20 minutes
njs50pm.cacheRequest = function(module, response)
njs50pm.hashCache[module] = {
data = response,
dt = getEpoch()
}
end
njs50pm.getCachedRequest = function(module, branch)
if branch and branch ~= '' then
module = module .. '-' .. branch
end
local cr = njs50pm.hashCache[module]
if (cr and getEpoch() - cr.dt < njs50pm.cacheTime) then
cecho('\n<green>njs50pm:<white> loaded ' .. module .. ' hash from cache\n')
-- display(cr.data)
return cr.data
end
return nil
end
njs50pm.getRemoteHash = function(options)
if not options or type(options) ~= 'table' or not options.module then
cecho('\n<red>njs50pm:<white> module is a required option\n\n')
return
end
options.githubUser = options.githubUser or 'njs50'
options.branch = options.branch or 'main'
options.callback = options.callback or display
local url = "https://api.github.com/repos/" .. options.githubUser .. "/" .. options.module .. "/branches"
local header = {["Content-Type"] = "application/json"}
local cachedRequest = njs50pm.getCachedRequest(options.module, options.branch)
if (cachedRequest) then
-- because of coroutine this needs to happen outside this execution
tempTimer(0, function()
options.callback(cachedRequest)
end)
return
end
local responseHandler, errorHandler
local selfDestruct = function()
killAnonymousEventHandler(responseHandler)
killAnonymousEventHandler(errorHandler)
end
-- first we create something to handle the success, and tell us what we got
responseHandler = registerAnonymousEventHandler('sysGetHttpDone', function(event, rurl, response)
if rurl == url then
selfDestruct()
response = yajl.to_value(response)
for idx, branch in ipairs(response) do
if (branch.name == options.branch) then
njs50pm.cacheRequest(options.module, branch.commit.sha)
return options.callback(branch.commit.sha)
end
end
cecho('\n<orange>njs50pm:<white> module or branch not found\n\n')
end
end)
-- then we create something to handle the error message, and tell us what went wrong
errorHandler = registerAnonymousEventHandler('sysGetHttpError', function(event, response, rurl)
if rurl == url then
selfDestruct()
cecho('\n<red>njs50pm:<white> failed to retrieve versions from github\n\n')
display(response)
njs50pm.checkRateLimit()
end
end)
-- Lastly, we make the request:
getHTTP(url, header)
end
njs50pm.checkPackageMetadata = function()
local installed = getPackages()
-- njs50pm.packages
for idx, package in ipairs(installed) do
if (njs50pm.packages[package]) then
local pdata = njs50pm.packages[package]
local md = njs50pm.getLocalMetadata(package)
if (md.module == '') then
njs50pm.log(package, 'updating metadata')
njs50pm.setPackageInfo(package, "njs50-module", package)
njs50pm.setPackageInfo(package, "njs50-hash", 'forcing-an-update')
njs50pm.setPackageInfo(package, "njs50-branch", pdata.branch)
njs50pm.setPackageInfo(package, "njs50-githubUser", pdata.githubUser)
njs50pm.setPackageInfo(package, "njs50-githubPath", pdata.githubPath)
end
end
end
--
-- if md.module == '' then
-- end
end
njs50pm.setupTestUpdate = function()
njs50pm.setPackageInfo('tfecat', "njs50-hash", 'forcing-an-update')
njs50pm.setPackageInfo('tfe-mapper', "njs50-hash", 'forcing-an-update')
njs50pm.setPackageInfo('njs50-tfe', "njs50-hash", 'forcing-an-update')
end</script>
<eventHandlerList />
</Script>
<Script isActive="yes" isFolder="no">
<name>njs50pm: package registry</name>
<packageName></packageName>
<script>njs50pm = njs50pm or {}
njs50pm.packages = njs50pm.packages or {}
njs50pm.packages["tfecat"] = {
name = 'tfecat',
description = 'better than the tfecat website, and in game!',
module = 'tfecat',
branch = 'master',
githubPath = '/mudlet/tfecat.module',
githubUser = 'njs50',
}
njs50pm.packages["tfe-mapper"] = {
name = 'tfe-mapper',
description = 'a mapper for tfe by njs50',
module = 'tfe-mapper',
branch = 'master',
githubPath = '',
githubUser = 'njs50',
}
njs50pm.packages["njs50-tfe"] = {
name = 'njs50-tfe',
description = 'a dump of my personal code, probably unusable',
module = 'njs50-tfe',
branch = 'main',
githubPath = '',
githubUser = 'njs50',
}
njs50pm.packages["njs50-package-manager"] = {
name = 'njs50-package-manager',
description = 'this package manager!',
module = 'njs50-package-manager',
branch = 'main',
githubPath = '',
githubUser = 'njs50',
}
njs50pm.list = function()
local st = demonnic.TableMaker:new({
edgeCharacter = '|'
})
st:addColumn({name = "Package", width = 25, textColor = "<green>"})
st:addColumn({name = "Description", width = 52, textColor = "<white>", ["alignment"] = "left"})
for pname, pdata in pairs(njs50pm.packages) do
st:addRow({pname, ' ' .. pdata.description})
end
cecho(st:assemble())
end</script>
<eventHandlerList />
</Script>
<ScriptGroup isActive="yes" isFolder="yes">
<name>demonnic</name>
<packageName></packageName>
<script>-------------------------------------------------
-- Put your Lua functions here. --
-- --
-- Note that you can also use external scripts --
-------------------------------------------------
</script>
<eventHandlerList />
<ScriptGroup isActive="yes" isFolder="yes">
<name>TextFormatter</name>
<packageName></packageName>
<script></script>
<eventHandlerList />
<Script isActive="yes" isFolder="no">
<name>standaloneFormatter</name>
<packageName></packageName>
<script>--- fText processing
-- @module demonnic
demonnic = demonnic or {}
function demonnic:wordWrap(str, limit, indent, indent1)
-- pulled from http://lua-users.org/wiki/StringRecipes
indent = indent or ""
indent1 = indent1 or indent
limit = limit or 72
local here = 1-#indent1
local function check(sp, st, word, fi)
if fi - here > limit then
here = st - #indent
return "\n"..indent..word
end
end
return indent1..str:gsub("(%s+)()(%S+)()", check)
end
function demonnic:fText(str, opts)
local options = demonnic:fixFormatOptions(str, opts)
if options.wrap and (options.strLen > options.effWidth) then
local wrapped = demonnic:wordWrap(str, options.effWidth)
local lines = wrapped:split("\n")
local formatted = {}
options.fixed = false
for _,line in ipairs(lines) do
table.insert(formatted, demonnic:fLine(line, options))
end
return table.concat(formatted, "\n")
else
return demonnic:fLine(str, options)
end
end
function demonnic:fixFormatOptions(str, opts)
if opts.fixed then return table.deepcopy(opts) end
--Set up all the things we might call the different echo types
local dec = {"d", "decimal", "dec"}
local hex = {"h", "hexidecimal", "hex"}
local col = {"c", "color", "colour", "col", "name"}
if opts == nil then opts = {} end -- don't overwrite options if they passed them
--but if they passed something other than a table as the options than oopsie!
if type(opts) ~= "table" then
error("Improper argument: options expected to be passed as table")
end
--now we make a copy of the table, so we don't edit the original during all this
local options = table.deepcopy(opts)
if options.wrap == nil then options.wrap = true end --wrap by default.
options.formatType = options.formatType or "" --by default, no color formatting.
options.width = options.width or 80 --default 80 width
options.cap = options.cap or "" --no cap by default
options.spacer = options.spacer or " " --default spacer is the space character
options.alignment = options.alignment or "center" --default alignment is centered
if options.nogap == nil then options.nogap = false end
if options.inside == nil then options.inside = false end --by default, we don't put the spacer inside
if not options.mirror == false then options.mirror = options.mirror or true end--by default, we do want to use mirroring for the caps
--setup default options for colors based on the color formatting type
if table.contains(dec, options.formatType) then
options.capColor = options.capColor or "<255,255,255>"
options.spacerColor = options.spacerColor or "<255,255,255>"
options.textColor = options.textColor or "<255,255,255>"
options.colorReset = "<r>"
options.colorPattern = "<%d+,%d+,%d+:?%d*,?%d*,?%d*>"
elseif table.contains(hex, options.formatType) then
options.capColor = options.capColor or "#FFFFFF"
options.spacerColor = options.spacerColor or "#FFFFFF"
options.textColor = options.textColor or "#FFFFFF"
options.colorReset = "#r"
options.colorPattern = 'c|%d%d%d%d%d%d'
elseif table.contains(col, options.formatType) then
options.capColor = options.capColor or "<white>"
options.spacerColor = options.spacerColor or "<white>"
options.textColor = options.textColor or "<white>"
options.colorReset = "<reset>"
options.colorPattern = "<%w*_?%w*:?%w*_?%w*>"
else
options.capColor = ""
options.spacerColor = ""
options.textColor = ""
options.colorReset = ""
options.colorPattern = ""
end
options.originalString = str
options.strippedString = string.gsub(tostring(str), options.colorPattern, "")
options.strLen = string.len(options.strippedString)
options.leftCap = options.cap
options.rightCap = options.cap
options.capLen = string.len(options.cap)
local gapSpaces = 0
if not options.nogap then
if options.alignment == "center" then
gapSpaces = 2
else
gapSpaces = 1
end
end
options.nontextlength = options.width - options.strLen - gapSpaces
options.leftPadLen = math.floor(options.nontextlength / 2)
options.rightPadLen = options.nontextlength - options.leftPadLen
options.effWidth = options.width - ((options.capLen * gapSpaces) + gapSpaces)
if options.capLen > options.leftPadLen then
options.cap = options.cap:sub(1, leftPadLen)
options.capLen = string.len(options.cap)
end
options.fixed = true
return options
end
function demonnic:fLine(str,opts)
local options = demonnic:fixFormatOptions(str,opts)
local leftCap = options.leftCap
local rightCap = options.rightCap
local leftPadLen = options.leftPadLen
local rightPadLen = options.rightPadLen
local capLen = options.capLen
if options.alignment == "center" then --we're going to center something
if options.mirror then --if we're reversing the left cap and the right cap (IE {{[[ turns into ]]}} )
rightCap = string.gsub(rightCap, "<", ">")
rightCap = string.gsub(rightCap, "%[", "%]")
rightCap = string.gsub(rightCap, "{", "}")
rightCap = string.gsub(rightCap, "%(", "%)")
rightCap = string.reverse(rightCap)
end --otherwise, they'll be the same, so don't do anything
if not options.nogap then str = string.format(" %s ", str) end
elseif options.alignment == "right" then --we'll right-align the text
leftPadLen = leftPadLen + rightPadLen
rightPadLen = 0
rightCap = ""
if not options.nogap then str = string.format(" %s", str) end
else --Ok, so if it's not center or right, we assume it's left. We don't do justified. Sorry.
rightPadLen = rightPadLen + leftPadLen
leftPadLen = 0
leftCap = ""
if not options.nogap then str = string.format("%s ", str) end
end--that's it, took care of both left, right, and center formattings, now to output the durn thing.
local fullLeftCap = string.format("%s%s%s", options.capColor, leftCap, options.colorReset)
local fullLeftSpacer = string.format("%s%s%s", options.spacerColor, string.rep(options.spacer, (leftPadLen - capLen)), options.colorReset)
local fullText = string.format("%s%s%s", options.textColor, str, options.colorReset)
local fullRightSpacer = string.format("%s%s%s", options.spacerColor, string.rep(options.spacer, (rightPadLen - capLen)), options.colorReset)
local fullRightCap = string.format("%s%s%s", options.capColor, rightCap, options.colorReset)
if options.inside then
-- "endcap===== some text =====endcap"
-- "endcap===== some text =====pacdne"
-- "endcap================= some text"
-- "some text =================endcap"
local finalString = string.format("%s%s%s%s%s", fullLeftCap, fullLeftSpacer, fullText, fullRightSpacer, fullRightCap)
return finalString
else
--"=====endcap some text endcap====="
--"=====endcap some text pacdne====="
--"=================endcap some text"
--"some text endcap================="
local finalString = string.format("%s%s%s%s%s", fullLeftSpacer, fullLeftCap, fullText, fullRightCap, fullRightSpacer)
return finalString
end
end
function demonnic:align(str, opts)
local options = {}
if opts == nil then
opts = {}
end
if type(opts) == "table" then
options = table.deepcopy(opts)
options.formatType = ""
options.wrap = false
else
error("Improper argument: options expected to be passed as table")
end
options = demonnic:fixFormatOptions(str, options)
return demonnic:fLine(str, options)
end
function demonnic:dalign(str, opts)
local options = {}
if opts == nil then
opts = {}
end
if type(opts) == "table" then
options = table.deepcopy(opts)
options.formatType = "d"
options.wrap = false
else
error("Improper argument: options expected to be passed as table")
end
options = demonnic:fixFormatOptions(str, options)
return demonnic:fLine(str, options)
end
function demonnic:calign(str, opts)
local options = {}
if opts == nil then
opts = {}
end
if type(opts) == "table" then
options = table.deepcopy(opts)
options.formatType = "c"
options.wrap = false
else
error("Improper argument: options expected to be passed as table")
end
options = demonnic:fixFormatOptions(str, options)
return demonnic:fLine(str, options)
end
function demonnic:halign(str, opts)
local options = {}
if opts == nil then
opts = {}
end
if type(opts) == "table" then
options = table.deepcopy(opts)
options.formatType = "h"
options.wrap = false
else
error("Improper argument: options expected to be passed as table")
end
options = demonnic:fixFormatOptions(str, options)
return demonnic:fLine(str, options)
end
function demonnic:cfText(str, opts)
local options = {}
if opts == nil then opts = {} end
if type(opts) == "table" then
options = table.deepcopy(opts)
options.formatType = "c"
else
error("Improper argument: options expected to be passed as table")
end
options = demonnic:fixFormatOptions(str, options)
return demonnic:fText(str, options)
end
function demonnic:dfText(str, opts)
local options = {}
if opts == nil then opts = {} end
if type(opts) == "table" then
options = table.deepcopy(opts)
options.formatType = "d"
else
error("Improper argument: options expected to be passed as table")
end
options = demonnic:fixFormatOptions(str, options)
return demonnic:fText(str, options)
end
function demonnic:hfText(str, opts)
local options = {}
if opts == nil then opts = {} end
if type(opts) == "table" then
options = table.deepcopy(opts)