forked from luapower/luapower
-
Notifications
You must be signed in to change notification settings - Fork 0
/
luapower.lua
2485 lines (2165 loc) · 70.5 KB
/
luapower.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
--luapower package reflection library.
--Written by Cosmin Apreutesei. Public Domain.
--[==[
This module uses the many conventions on how modules, C sources, binaries
and documentation is laid out in luapower to extract package and module
metadata.
CONVENTIONS:
* the git directory of a package is at `.mgit/<package>/.git`.
* the git work-dir is shared between all packages and it's the current
directory by default and is configured in luapower.luapower_dir.
* the currently supported platforms are in the luapower.platforms table.
* a module can signal that it doesn't support a platform by raising
an error containing the string 'platform not ' or 'arch not ' when it's
loaded.
* a module can signal that it's not a module but actually an app by
asserting it with assert(... ~= <module_name>, 'not a module').
* a module can signal that it requires a global variable that is set
by loading another module by raising an error ending with the string
'<module_name> not loaded'.
* a module's runtime dependencies that are bound to module keys can be
declared in its `__autoload` metatable field (see glue.autoload).
* name, description, author and license of a Lua module can be provided
on the first two line-comments written as:
-- [<name>:] <description>.
-- Written By: <author>. <license> [license].
-- Copyright (C) <author>. <license> [license].
* submodules can be put in folders or named `<module>_<submodule>.lua`.
* platform-specific Lua modules are found in `bin/<platform>/lua/<module>.lua`.
currently only luajit's `vmdef.lua` file is in there.
* Lua/C modules are found in `bin/<platform>/clib/<module>.dll|.so`
* C sources can be described in the metafile `csrc/<package>/WHAT` which
must look like this (the second line is optional and should only list
the binary dependencies of the library if any):
<libname> <version> from <browse-url> (<license> license)
requires: package1, package2 (platform1 platform2 ...), ...
* The WHAT file can also be used to describe Lua modules that are
developed outside of luapower (eg. `lexer`).
* packages can be organized into categories in the markdown file
`.mgit/luapower-cat.md` which must contain a two-level deep bullet list.
Any packages that are not listed there will be added automatically to the
`Misc` category.
* a package is known if it has a `.mgit/<package>.origin` file.
* a package is installed if it has a `.mgit/<package>` directory.
* not installed packages are those known but not installed.
* modules can be anywhere in the tree except in `csrc`, `media`, `.mgit`,
`bin`, `tmp` (but they can be in `bin/<platform>/clib` and
`bin/<platform>/lua`).
* docs are `*.md` files in Pandoc Markdown format and can be anywhere in
the tree where modules can be.
* modules that end in `_test`, `_demo`, `_demo_<arch>`, `_benchmark`
or `_app` are considered standalone scripts.
* packages containing Lua/C modules have an _implicit_ binary dependency
on the luajit package because they link against the LuaJIT library.
* packages with a C component must contain a build script named
`csrc/*/build-<platform>.sh` for each platform that it supports.
* the main doc file is `<package>.md`.
* platforms can be specified in the `platforms` tag of the package's main
doc file as comma-separated values.
* binary dependencies can be specified in the `requires` tag of the
package's main doc file just like in the WHAT file.
* .dasl files are listed as Lua/ASM modules and are tracked like Lua
modules and the `dynasm` module is loaded first.
* .t files are listed as Terra modules and are tracked like Terra modules
and the `terra` module is loaded first.
STATIC INFO:
* luapower_dir -> s luapower dir
* mgit_dir -> s .mgit dir relative to luapower dir
* supported_os_platforms -> t {os = {platform = true}}
* supported_platforms -> t {platform = true}
* builtin_modules -> t {module = true}
* luajit_builtin_modules -> t {module = true}
* loader_modules -> t {file_ext = loader_module_name}
* enviornments -> t {loader_module_name = env_name}
* default_license -> s default license
SOURCES OF INFORMATION:
* ffi.os, ffi.abi
* a module's ffi.load() call tree
* a module's require() call tree
* parsing a module for `require(<string_constant>)` calls
* parsing a module's top comment for name, tagline, author and license
* the list of `.mgit/<package>.origin` files
* the list of `.mgit/<package>` directories
* the parsing of `csrc/<package>/WHAT` file
* tags parsed from *.md files
* package category associations parsed from `.mgit/luapower-cat.md`
* the output of `git ls-files` (tracked files)
* the output of `git describe --tags --long --always` (package version)
* the output of `git --tags --simplify-by-decoration --pretty=%d` (tags)
* the output of `git describe --tags --abbrev=0` (current tag)
* the output of `git config --get remote.origin.url` (origin url)
* the output of `git log -1 --format=%at` (mtime of master branch)
* the output of `git log -1 --format=%at --follow <file>` (mtime of file)
* the output of `git log -1 --format=%at <tag>` (mtime of tag)
UTILS:
powerpath([subpath]) -> s (path in) luapower dir
mgitpath([subpath]) -> s (path in) mgit dir
git(package, cmd) -> s get the output of a git command
gitlines(package, cmd)->iter()->s iterate the output of a git command
module_name_cmp(m1, m2) -> t|f comp func for sorting module names
walk_tree(t, f) tree walker
CACHING:
memoize_package(f) -> f memoize a f(pkg[, arg2]) func
memoize(f) -> f memoize any func
clear_cache([pkg]) clear memoize cache for a pkg or all
PLATFORM:
check_platform([platform]) -> s check platform/get current platform
current_platform() -> s mingw|linux|osx..32|64
MGIT DIRECTORY INFO:
known_packages() -> t {name=true}
installed_packages() -> t {name=true}
not_installed_packages() -> t {name=true}
PARSING luapower-cat.md:
cats() -> t {name=, packages={{name=,note=},...}}
packages_cats() -> t {pkg=cat}
package_cat(pkg) -> s package's category
TRACKED FILES BREAKDOWN:
tracked_files([package]) -> t {path=package}
docs([package]) -> t {name=path}
headerdocs([package]) -> t {name=contents}
modules([package]) -> t {name=path}
scripts([package]) -> t {name=path}
file_types([package]) -> t {path='module'|'script'|...}
module_tree(package) -> t {name=, children=}
PARSING MD FILES:
docfile_tags(path) -> t {tag=val}
doc_tags([package], doc) -> t {tag=val}
PARSING LUA FILES:
module_requires_runtime(module) -> t {module=true}
modulefile_header(file) -> t {name=, descr=, author=, license=}
module_header([package], mod) -> t {name=, descr=, author=, license=}
module_headers(package) -> t {module=header_table}
PACKAGE REVERSE LOOKUP:
module_package(mod) -> s module's package
doc_package(doc) -> s doc's package
ffi_module_package(mod, pkg, plt)->s ffi module's package
CSRC DIRECTORY:
what_tags(package) -> t {realname=,version=,url=,license=,
dependencies={platf={dep=true}}}
bin_deps(package, platform) -> t {platform={package=}}
build_platforms(package) -> t {platform=true}
bin_platforms(package) -> t {platform=true}
declared_platforms(package) -> t {platform=true}
platforms(package) -> t {platform=true}
GIT INFO:
git_version(package) -> s current git version
git_tags(package) -> t {tag1, ...}
git_tag(package) -> s current tag
git_origin_url(package) -> s origin url
git_master_time(package) -> ts timestamp of last commit
git_file_time(package, file) -> ts timestamp of last modification
git_tag_time(package, tag) -> ts timestamp of tag
MODULE DEPENDENCY TRACKING:
module_loader(mod[, package]) -> s find a module's loader module if any
track_module(mod[, package]) -> t {loaderr=s | mdeps={mod=true},
ffi_deps={mod=true}}
UPDATING THE DEPENDENCY DB:
load_db() load luapower_db.lua
unload_db() unload it
save_db() save it
update_db_on_current_platform([pkg]) update db with local trackings
update_db(package, [platform], [mod]) update db with local or rpc trackings
track_module_platform(mod, [package], [platform])
server_status([platform]) -> t {platform = {os=, arch=}}
DEPENDENCY INFO BREAKDOWN:
module_load_error(mod, package, platform)
module_platforms(mod, package)
module_autoloads(mod, package, platform)
module_autoloaded(mod, package, platform)
module_requires_loadtime(mod, package, platform)
module_requires_loadtime_ffi(mod, package, platform)
module_requires_runtime(mod, package, platform)
module_requires_alltime(mod, package, platform)
MODULE INDIRECT DEPENDENCIES:
module_requires_loadtime_tree(mod, package, platform)
module_requires_loadtime_all(mod, package, platform)
module_requires_alltime_all(mod, package, platform)
module_requires_loadtime_int(mod, package, platform)
module_requires_loadtime_ext(mod, package, platform)
PACKAGE INDIRECT DEPENDENCIES:
bin_deps_all(package, platform)
REVERSE MODULE DEPENDENCIES:
module_required_loadtime(mod, package, platform)
module_required_alltime(mod, package, platform)
module_required_loadtime_all(mod, package, platform)
module_required_alltime_all(mod, package, platform)
REVERSE PACKAGE DEPENDENCIES:
rev_bin_deps(package, platform)
rev_bin_deps_all(package, platform)
ANALYTIC INFO:
module_tags() -> t {lang=, demo_module=, test_module=}
package_type(package) -> type 'Lua+ffi'|'Lua/C'|'Lua'|'C'|'other'
license(package) -> s license
module_tagline(package, mod) -> s tagline
build_order(packages, platform) -> t {pkg1,...}
CONSISTENCY CHECKS:
duplicate_docs()
undocumented_package(package)
load_errors([package], [platform])->t {mod=err}
GENERATING MGIT DEPS FILES:
update_mgit_deps([package]) (re)create .deps file(s)
RPC API:
connect(ip, port[, connect])->lp connect to a RPC server
lp.osarch() -> os, arch
lp.exec(func, ...) -> ...
lp.restart()
lp.stop()
]==]
local luapower = setmetatable({}, {__index = _G})
setfenv(1, luapower)
local fs = require'fs'
local glue = require'glue'
local ffi = require'ffi'
--config
------------------------------------------------------------------------------
--locations
luapower_dir = '.' --the location of the luapower tree to inspect on
mgit_dir = '.mgit' --relative to luapower_dir
--platforms
supported_os_list = {'mingw', 'linux', 'osx'}
supported_os_platforms = {
mingw = {mingw32 = true, mingw64 = true},
linux = {linux32 = true, linux64 = true},
osx = {osx32 = true, osx64 = true},
}
supported_platforms = {
mingw32 = true, mingw64 = true,
linux32 = true, linux64 = true,
osx32 = true, osx64 = true,
}
servers = {} --{platform = {'ip|host', port}}
--behavior
auto_update_db = true --update the db automatically when info is missing
allow_update_db_locally = true --allow dependency tracking on this machine
default_license = 'Public Domain'
local function plusfile(file)
return file and '/'..file or ''
end
--make a path given a luapower_dir-relative path
function powerpath(file)
return luapower_dir..plusfile(file)
end
--make an abs path given a mgit-dir relative path
function mgitpath(file)
return mgit_dir..plusfile(file)
end
--memoize pattern with total and partial cache invalidation
------------------------------------------------------------------------------
--memoize function that cannot have its cache cleared.
local memoize_permanent = glue.memoize
--memoize for functions where the first arg is an optional package name.
--cache on those functions can be cleared for individual packages.
local pkg_caches = {} --{func -> {pkg -> val}}
local nilkey = {}
function memoize_package(func)
local cache = {}
pkg_caches[func] = cache
return function(pkg, ...)
local k = pkg == nil and nilkey or pkg
local fn = cache[k]
if not fn then
fn = glue.memoize(function(...)
return func(pkg, ...)
end)
cache[k] = fn
end
return fn(...)
end
end
--generic memoize that can only have its entire cache cleared.
local rememoizers = {}
function memoize(func)
local memfunc
local function rememoize()
memfunc = glue.memoize(func)
end
rememoize()
rememoizers[func] = rememoize
return function(...)
return memfunc(...)
end
end
--clear memoization caches for a specific package or for all packages.
function clear_cache(pkg)
if pkg then
for _, cache in pairs(pkg_caches) do
cache[pkg] = nil
end
else
for _, cache in pairs(pkg_caches) do
for pkg in pairs(cache) do
cache[pkg] = nil
end
end
end
for _, rememoize in pairs(rememoizers) do
rememoize()
end
collectgarbage() --unload modules from the tracking Lua state
end
--other helpers
--filter a table with a filter function(key, value) -> truthy | falsy
local function filter(t, f)
local dt = {}
for k,v in pairs(t) do
if f(k,v) then
dt[k] = v
end
end
return dt
end
--data acquisition: readers and parsers
--============================================================================
--detect current platform
local platos = {Windows = 'mingw', Linux = 'linux', OSX = 'osx'}
current_platform = memoize_permanent(function()
return glue.assert(platos[ffi.os], 'unknown OS %s', ffi.os)
..(ffi.abi'32bit' and '32' or '64')
end)
--validate a platform if given, or return current platform if not given.
function check_platform(platform)
if not platform then
return current_platform()
end
glue.assert(supported_platforms[platform],
'unknown platform "%s"', platform)
return platform
end
--find dependencies of a module by tracking `require` and `ffi.load` calls.
------------------------------------------------------------------------------
--modules that we won't track because require'ing them
--is not necessary in any Lua version so there's no point "discovering"
--'luajit' as the package that sources these modules.
builtin_modules = {
string = true, table = true, coroutine = true, package = true, io = true,
math = true, os = true, _G = true, debug = true,
}
--install `require` and `ffi.load` trackers -- to be run in a new Lua state.
local function install_trackers(builtin_modules, filter)
--find Lua dependencies of a module by tracing its `require` calls.
local parents = {} --{module1, ...}
local dt = {} --{module = dep_table}
local lua_require = require
function require(m)
--create the module's tracking table
dt[m] = dt[m] or {}
--require the module directly if it doesn't need tracking.
if builtin_modules[m] then
return lua_require(m)
end
--register the module as a dependency for the parent at the top of
--the stack.
local parent = parents[#parents]
if parent then
dt[parent].mdeps = dt[parent].mdeps or {}
dt[parent].mdeps[m] = true
end
--push the module into the parents stack
table.insert(parents, m)
--check the error cache before loading the module
local ok, ret
local err = dt[m].loaderr
if err then
ok, ret = nil, err
else
ok, ret = pcall(lua_require, m)
if not ok then
--cache the error for future calls.
local err = ret:gsub(':?%s*[\n\r].*', '')
err = err:gsub('^.-[\\/]%.%.[\\/]%.%.[\\/]', '')
--remove source info for platform and arch load errors
local perr =
err:match'platform not .*'
or err:match'arch not .*'
--TODO: pre-load these modules...
--or err:match'[^%s]+ not loaded$'
err = perr or err
if not perr then
--TODO: remove this
--print(string.format('%-20s: %s', m, err))
end
dt[m] = {loaderr = err}
end
end
--pop the module from the parents stack
table.remove(parents)
if not ok then
error(ret, 2)
end
--copy the module's autoload table if it has one
--TODO: dive into the keys of module and check autoload on the keys too!
--eg. bitmap: 'colortypes.rgbaf' -> 'bitmap_rgbaf'
local mt = getmetatable(ret)
local auto = mt and rawget(mt, '__autoload')
if auto then
dt[m].autoloads = filter(auto, function(key, mod)
return type(key) == 'string' and type(mod) == 'string'
end)
end
return ret
end
--find C dependencies of a module by tracing the `ffi.load` calls.
local ffi = lua_require'ffi'
local ffi_load = ffi.load
function ffi.load(clib, ...)
local ok, ret = xpcall(ffi_load, debug.traceback, clib, ...)
local m = parents[#parents]
local t = dt[m]
t.ffi_deps = t.ffi_deps or {}
t.ffi_deps[clib] = ok
if not ok then
error(ret, 2)
else
return ret
end
end
--track a module, tracing its require and ffi.load calls.
--loader_m is an optional "loader" module that needs to be loaded
--before m can be loaded (eg. for loading .dasl files, see dynasm).
function track_module(m, loader_m)
--TODO: LuaSec clib modules crash if not loaded in specific order.
if m:find'^ssl%.' then return end
if loader_m then
local ok, err = pcall(require, loader_m)
if not ok then
--put the error on the account of mod
dt[m] = {loaderr = err} --clear deps
return dt[m]
end
end
pcall(require, m)
return dt[m]
end
end
--make a Lua state for loading modules in a clean environment for tracking.
--the tracker function is installed in the state as the global 'track_module'.
local tracking_state = function(env)
local luastate = require'luastate'
local state = luastate.open()
state:openlibs()
state:push{[0] = arg[0]} --used by some modules to get the exe dir
state:setglobal'arg'
state:push(install_trackers)
state:call(builtin_modules, filter)
return state
end
--track a module in the tracking Lua state which is reused on future calls.
--different states are created for different environments.
local function track_module(m, loader_m, env)
assert(m, 'module required')
local state = tracking_state(env)
state:getglobal'track_module'
return state:call(m, loader_m)
end
--dependency tracking based on parsing
------------------------------------------------------------------------------
--built-in modules that don't have parsable source code.
luajit_builtin_modules = {
--luajit built-ins.
ffi = true, bit = true, jit = true,
['jit.util'] = true, ['jit.profile'] = true,
--openresty built-ins.
['table.new'] = true,
['table.isempty'] = true,
['table.isarray'] = true,
['table.nkeys'] = true,
['table.clone'] = true,
['thread.exdata'] = true,
}
module_requires_runtime_parsed = memoize(function(m) --direct dependencies
local t = {}
if builtin_modules[m] or luajit_builtin_modules[m] then
return t
end
local path =
--search for .lua files in standard path
package.searchpath(m, package.path)
--search for .dasl files in the same path as .lua files
or package.searchpath(m, package.path:gsub('%.lua', '.dasl'))
if not path then
return t
end
local s = assert(glue.readfile(path))
--delete long comments
s = s:gsub('%-%-%[(=*)%[.*%]%1%]', '')
--delete long strings
s = s:gsub('%-%-%[%[.*%]%]', '')
--delete short comments
s = s:gsub('%-%-[^\n\r]*', '')
--delete the demo section (horrible parsing)
s = s:gsub('[\r\n]if not %.%.%. then%s+.-%s+end', '')
--local xxx = require'xxx'
for m in s:gmatch'[ \t]+local %w+[ \t]+=[ \t]+require%s*(%b\'\')' do
t[m:sub(2,-2)] = true
end
--local xxx = require"xxx"
for m in s:gmatch'[ \t]+local %w+[ \t]+=[ \t]+require%s*(%b"")' do
t[m:sub(2,-2)] = true
end
--local xxx = require("xxx") or local xxx = require('xxx')
for m in s:gmatch'[ \t]+local %w+[ \t]+=[ \t]+require%s*(%b())' do
m = glue.trim(m:sub(2,-2))
if m:find'^%b\'\'$' or m:find'^%b""$' then
m = m:sub(2,-2)
if m:find'^[a-z0-9%.]+$' then
t[m] = true
end
end
end
return t
end)
--module header parsing
------------------------------------------------------------------------------
local function parse_author_license_line(s, c)
local c = c and '%s*%-%-' or ''
local author, license =
s:match('^'..c..'%s*[Ww]ritten%s+[Bb]y%:?%s*([^%.]+)%.%s*([^%.]+)')
if not license then
author, license =
s:match('^'..c..'%s*[Cc]opyright%s*%([Cc]%)%s*([^%.]+)%.%s*([^%.]+)')
end
if license then
license = license:gsub('%s*[Ll]icense:?%s*', '')
if license:lower() == 'public domain' then
license = 'Public Domain'
end
end
return author, license
end
local function parse_name_descr_line(s, c)
local c = c and '%s*%-%-' or ''
local name, descr =
s:match('^'..c..'%s*([^%:]+)%:%s*(.*)') -- '--name: descr'
if not name then
descr = c ~= ''
and s:match'^%s*%-%-%[%[%s*(.-)%s*%]%]%[%-]+%s*$'
or nil -- '--[[ descr ]]--' (ffi_reflect.lua)
descr = descr or s:match('^'..c..'%s*([^%[].*)') -- '--descr'
end
descr = descr and descr:gsub('%.$', '')
return name, descr
end
local function parse_module_header(file)
local t = {}
local f = io.open(file, 'r')
--TODO: check if the module is a .lua file first (what else can it be?).
--TODO: parse "Author: XXX"
--TODO: parse "License: XXX"
--TODO: parse all comment lines before a non-comment line starts.
--TODO: parse long comments too.
if f then
local s1 = f:read'*l'
while s1 and (
s1:find'^%s*$' --skip empty lines
or s1:find'^%s*[%-=]+%s*$' --skip "section" delimiters (dynasm.lua)
) do
s1 = f:read'*l'
end
if s1 then
t.name, t.descr = parse_name_descr_line(s1, true)
if t.descr then
local s2 = f:read'*l'
if s2 then
t.author, t.license = parse_author_license_line(s2, true)
end
else
local sep = s1:match'%s*%-%-%[([=]*)%[%s*$' -- '--[==['
if sep then --in-header doc (terra/dynarray.lua).
local dt = {}
table.insert(dt, s1)
while true do
s1 = f:read'*l'
if not s1 then
break
end
if not t.descr then
t.name, t.descr = parse_name_descr_line(s1)
end
if not t.license then
t.author, t.license = parse_author_license_line(s1)
end
table.insert(dt, s1)
if s1:match('^(.-)%s*%]'..sep..'%]%s*$') then -- ']==]'
break
end
end
t.doc = table.concat(dt, '\n')
end
end
end
f:close()
end
return t
end
--comparison function for table.sort() for modules: sorts built-ins first.
------------------------------------------------------------------------------
function module_name_cmp(a, b)
if builtin_modules[a] == builtin_modules[b] or
luajit_builtin_modules[a] == luajit_builtin_modules[b]
then
--if a and be are in the same class, compare their names
return a < b
else
--compare classes (std. vs non-std. module)
return not (builtin_modules[b] or luajit_builtin_modules[b])
end
end
--filesystem reader
------------------------------------------------------------------------------
--recursive dir() -> iter() -> filename, path, mode
local function dir(p0, recurse)
assert(p0)
local t = {}
local function rec(p)
local dp = p0 .. (p and '/' .. p or '')
for f,d in fs.dir(dp) do
if f then
local ftype = d:attr'type'
table.insert(t, {f, p, ftype})
if recurse and ftype == 'dir' then
rec((p and p .. '/' .. f or f))
end
end
end
end
rec()
local i = 0
return function()
i = i + 1
if not t[i] then return end
return unpack(t[i], 1, 3)
end
end
--path/dir/file -> path/dir, file
local function split_path(path)
local filename = path:match'([^/]*)$'
local n = #path - #filename - 1
if n > 1 then n = n - 1 end --remove trailing '/' if the path is not '/'
return path:sub(1, n), filename
end
--open a file and return a gimme-the-next-line function and a close function.
local function more(filename)
local f, err = io.open(filename, 'r')
if not f then return nil, err end
local function more()
local s = f:read'*l'
if not s then f:close(); f = nil end
return s
end
local function close()
if f then f:close() end
end
return more, close
end
--git command output readers
------------------------------------------------------------------------------
--read a cmd output to a line iterator
local function pipe_lines(cmd)
if ffi.os == 'Windows' then
cmd = cmd .. ' 2> nul'
else
cmd = cmd .. ' 2> /dev/null'
end
local t = {}
glue.fcall(function(finally)
local f = assert(io.popen(cmd, 'r'))
finally(function()
f:close()
end)
f:setvbuf'full'
for line in f:lines() do
t[#t+1] = line
end
end)
local i = 0
return function()
i = i + 1
return t[i]
end
end
--read a cmd output to a string
local function read_pipe(cmd)
local t = {}
for line in pipe_lines(cmd) do
t[#t+1] = line
end
return table.concat(t, '\n')
end
local function git_dir(package)
return mgitpath(package..'/.git')
end
--git command string for a package repo
local function gitp(package, args)
local git = ffi.os == 'Windows' and 'git.exe' or 'git'
return git..' --git-dir="'..git_dir(package)..'" '..args
end
--execute function in a different current-directory.
local function in_dir(dir, func, ...)
local pwd = assert(fs.cd())
assert(fs.cd(dir))
local function pass(ok, ...)
fs.cd(pwd)
assert(ok, ...)
return ...
end
return pass(glue.pcall(func, ...))
end
function git(package, cmd)
return in_dir(powerpath(), read_pipe, gitp(package, cmd))
end
function gitlines(package, cmd)
return in_dir(powerpath(), pipe_lines, gitp(package, cmd))
end
--module finders
------------------------------------------------------------------------------
--path/*.lua -> Lua module name
local function lua_module_name(path)
if path:find'^bin/[^/]+/lua/' then --platform-specific module
path = path:gsub('^bin/[^/]+/lua/', '')
end
return path:gsub('/', '.'):match('(.-)%.lua$')
end
--path/*.dasl -> dasl module name
local function dasl_module_name(path)
return path:gsub('/', '.'):match('(.-)%.dasl$')
end
--path/*.dll|.so -> C module name
local function c_module_name(path)
local ext = package.cpath:match'%?%.([^;]+)' --dll, so
local name = path:match('bin/[^/]+/clib/(.-)%.'..ext..'$')
return name and name:gsub('/', '.')
end
--path/*.t -> Terra module name
local function terra_module_name(path)
if path:find'^bin/[^/]+/lua/' then --platform-specific module
path = path:gsub('^bin/[^/]+/lua/', '')
end
return path:gsub('/', '.'):match('(.-)%.t$')
end
--check if a file is a module and if it is, return the module name
local function module_name(path)
path = tostring(path)
return
lua_module_name(path)
or dasl_module_name(path)
or c_module_name(path)
or terra_module_name(path)
end
--'module_submodule' -> 'module'
--'module.submodule' -> 'module'
local function parent_module_name(mod)
local parent = mod:match'(.-)[_%.][^_%.]+$'
if not parent or parent == '' then return end
return parent
end
--tree builder and tree walker patterns
------------------------------------------------------------------------------
--tree builder based on a function that produces names and a function that
--resolves the parent name of a name.
--returns a tree of form:
-- {name = true, children = {name = NAME, children = ...}}
local function build_tree(get_names, get_parent)
local parents = {}
for name in get_names() do
parents[name] = get_parent(name) or true
end
local root = {name = true}
local function add_children(pnode)
for name, parent in pairs(parents) do
if parent == pnode.name then
local node = {name = name}
pnode.children = pnode.children or {}
table.insert(pnode.children, node)
add_children(node)
end
end
end
add_children(root)
return root
end
--tree walker: calls f(node, level, parent_node, node_index) for each node.
--depth-first traversal.
function walk_tree(t, f)
local function walk_children(pnode, level)
if type(pnode) ~= 'table' then return end
if not pnode.children then return end
for i,node in ipairs(pnode.children) do
f(node, level, pnode, i)
walk_children(node, level + 1)
end
end
walk_children(t, 0)
end
--WHAT file parser
------------------------------------------------------------------------------
--parse '<pkg1>, <pkg2> (<platform1> ...), ...' -> {platform->{pkg->true}}
local function parse_requires_list(values, deps)
deps = deps or {}
for s in glue.gsplit(values, ',') do
s = glue.trim(s)
if s ~= '' then
local s1, ps =
s:match'^([^%(]+)%s*%(%s*([^%)]+)%s*%)' --'pkg (platform1 ...)'
if ps then
s = glue.trim(s1)
for platform in glue.gsplit(ps, '%s+') do
glue.attr(deps, platform)[s] = true
end
else
for platform in pairs(supported_platforms) do
glue.attr(deps, platform)[s] = true
end
end
end
end
return deps
end
--parse 'lib (mod1 ...)' -> {lib->{module->true}}
local function parse_modules_list(values, modules)
modules = modules or {} --{lib->{module->true}}
for s in glue.gsplit(values, ',') do
s = glue.trim(s)
if s ~= '' then
local s, ps =
s:match'^([^%(]+)%s*%(%s*([^%)]+)%s*%)' --'lib (mod1 ...)'
if ps then
s = glue.trim(s)
modules[s] = {}
for mod in glue.gsplit(ps, '%s+') do
modules[s][mod] = true
end
else