-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathomm.lua
More file actions
2924 lines (2775 loc) · 88.2 KB
/
Copy pathomm.lua
File metadata and controls
2924 lines (2775 loc) · 88.2 KB
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
--[[-------------------------------------------------------------------------
##OMM, a lua based extensible build engine.
Inspired by and stealing code snippets from Steve Donovan's [lake][].
Using modified versions of
Roland Yonaba's [30log][] and
god6or@gmail.com's [os.cmdl][].
Required 3rd party modules:
[luafilesystem][], [winapi][] / [luaposix][]
(best viewed with a folding editor like [ZBS][].)
[lake]: https://github.com/stevedonovan/Lake
[30log]: https://github.com/Yonaba/30log
[os.cmdl]: https://github.com/edartuz/lua-cmdl
[luafilesystem]: https://github.com/keplerproject/luafilesystem/
[winapi]: https://github.com/stevedonovan/winapi
[luaposix]: https://github.com/luaposix/luaposix/
[ZBS]: https://github.com/pkulchenko/ZeroBraneStudio
@author Ulrich Schmidt
@copyright 2016
@license MIT/X11
--]]-------------------------------------------------------------------------
--luacheck: globals arg _DEBUG
--require "luacov"
--_DEBUG = true;
--
local VERSION = "1.0";
local MSG1 = "omm 1.0.2 (2019/08/04)\n A lua based extensible build engine.\n";
local USAGE = [=[
Usage: OMM [options] [target[,...]]
Options:
%s
special targets:
* clean delete all intermediate files.
* CLEAN delete all intermediate and result files.
Please report bugs to u.sch.zw@gmx.de
]=];
local MAKEFILENAME = "makefile.omm"; -- default makefile name.
local SCRIPTEXT = ".omm";
local INCLUDESCRIPTEXT = ".omi";
--
-- [] =======================================================================
--
local table_sort, io_popen, io_stderr, io_open, os_remove, os_getenv, os_tmpname, os_exit =
table.sort, io.popen, io.stderr, io.open, os.remove, os.getenv, os.tmpname, os.exit;
local print, concat, insert, remove, max, min, tointeger =
print, table.concat, table.insert, table.remove, math.max, math.min, math.tointeger;
local pairs, ipairs, type, getmetatable, rawget, select, error, os_execute, package =
pairs, ipairs, type, getmetatable, rawget, select, error, os.execute, package;
local pcall, require, loadfile, setmetatable, tonumber, setfenv, debug_getinfo =
pcall, require, loadfile, setmetatable, tonumber, setfenv, debug.getinfo;
--
-- [] =======================================================================
--
package.preload["33log"] = function(...) --luacheck: ignore
local pairs, ipairs, type, getmetatable, rawget, select =
pairs, ipairs, type, getmetatable, rawget, select;
local setmetatable = setmetatable;
local insert = table.insert;
local classes = {}; -- all classes indexed by her classname.
local class;
local function split(s)
local i1 = 1;
local ls = {};
while true do
local i2, i3 = s:find("%s+", i1);
if not i2 then
insert(ls, s:sub(i1));
return ls;
end;
insert(ls, s:sub(i1, i2 - 1));
i1 = i3 + 1;
end;
end;
local function copy(src, dst)
src = src or {}
dst = dst or {};
for k, v in pairs(src) do dst[k] = v; end;
return dst;
end;
local function class_index(self, i)
return rawget(getmetatable(self), i);
end;
local function class_is(self, kind)
if not rawget(self, "__classname") then
self = getmetatable(self);
end;
if type(kind) == "string" then
kind = split(kind);
end;
for _, n in ipairs(kind) do
local kMT = classes[n];
if kMT then
local s = self;
while s do
if s == kMT then
return true;
end;
s = getmetatable(s);
end;
end;
end;
return false;
end;
local function isClass(...) -- ([self,] var, kind)
local var, kind;
if select(1, ...) == class then
var, kind = select(2, ...);
else
var, kind = select(1, ...);
end;
if type(var) ~= "table" then
return false;
end;
if var.is ~= class_is then
return false;
end;
if not kind then
return true;
end;
if type(kind) == "string" then
return class_is(var, kind);
end;
if isClass(kind) then
return class_is(var, kind.__classname);
end;
if type(kind) == "table" then
for _, k in ipairs(kind) do
if isClass(var, k) then
return true;
end;
end;
return false;
end;
error("isClass(); wrong parameter 'kind'.", 2);
end;
local function class_newindex(self, field, value)
local mt = getmetatable(self);
if mt[field] == nil then
rawset(self, field, value);
else
error(('%s field "%s" is readonly.'):format(self, field), 2)
end;
end;
local function class_new(self, ...)
if rawget(self,'__classname') == nil then error('new() should be called from a class.', 2) end;
local instance = setmetatable({}, self);
if self.init then
return self.init(instance, ...);
end;
return instance;
end;
local function class_singleton(self, ...)
local o = self:new(...);
self.new = function()
return o;
end;
return o;
end;
local function class_is_singleton(self)
return self.new ~= class_new;
end;
local function class_subclass(self, name, extra_params)
if type(name) == "table" then extra_params = name; name = nil; end;
local newClass = copy(extra_params, copy(self));
newClass.__classname = name or "class#" .. #classes+1;
newClass.super = self;
newClass = setmetatable(newClass, self);
if classes[newClass.__classname] then
error(("subclass(): class '%s' already defined."):format(newClass.__classname), 2);
end;
if name then classes[name] = newClass; end;
return newClass;
end;
local function class_protect(self)
if rawget(self,'__classname') == nil then error('protect() should be called from a class.', 2) end;
rawset(self, "__newindex", class_newindex);
end;
local function class_unprotect(self)
if rawget(self,'__classname') == nil then error('unprotect() should be called from a class.', 2) end;
rawset(self, "__newindex", nil);
end;
local function class_init(self, param)
if type(param) == "table" then
for n, v in pairs(param) do
self[n] = v;
end;
end;
return self;
end;
--
local clBase = {
__classname = "base";
__index = class_index;
init = class_init;
new = class_new;
singleton = class_singleton;
is_singleton = class_is_singleton;
subclass = class_subclass;
is = class_is;
protect = class_protect;
unprotect = class_unprotect;
}
--
class = setmetatable({
},{
__call = isClass;
__index = classes;
}
);
--
classes[clBase.__classname] = clBase;
--
return class;
end;
package.preload["33list"] = function(...) --luacheck: ignore
local concat, insert, remove = table.concat, table.insert, table.remove;
local error = error;
--
local class = require "33log";
--
local clList = class.base:subclass("List", {
__call = function(self) -- iterator()
local i = 0;
return function()
i = i + 1;
return self[i];
end;
end
});
clList.insert = function(self, item, idx)
if idx then
insert(self, idx, item);
else
insert(self, item);
end;
end;
clList.remove = function(self, idx)
remove(self, idx)
end;
clList.add = function(self, tbl)
if type(tbl) == "table" then
for _, v in ipairs(tbl) do insert(self, v); end;
end;
return self;
end;
clList.copy = function(self)
return clList:new(self)
end;
clList.index = function(self, val)
for i, v in ipairs(self) do
if v == val then return i end;
end;
end;
clList.find = function(self, field, value)
for _, v in ipairs(self) do
if v[field] == value then return v; end;
end;
end;
clList.erase = function(self, l2)
for _, v in ipairs(l2) do
local idx = self:index(v);
if idx then remove(self, idx); end;
end;
end;
clList.concat = function(self, field, sep)
local res = {};
for _, o in ipairs(self) do insert(res, o[field]); end;
return concat(res, sep or " ");
end;
--
-- [unique list class] ==============================================
--
local clUList = clList:subclass("UList", {
__key = 1, -- default
--__allowed = "base", -- default
});
clUList.init = function(self, ...)
clUList.super.init(self, ...);
self.__dir = {};
local kf = self.__key;
for _, obj in ipairs(self) do
if self.__dir[obj[kf]] then
error(("<class %s> double key detected."):format(self.__classname));
end;
self.__dir[obj[kf]] = obj;
end;
return self;
end;
clUList.add = function(self, item)
local kf = self.__key or 1;
if class(item, self.__allowed) then
if self.__dir[item[kf]] then
error(("cant overwrite value '%s'"):format(item[kf]));
--return nil, self.__dir[item[kf]];
else
insert(self, item);
self.__dir[item[kf]] = item;
end;
elseif type(item) == "table" then
for _, v in ipairs(item) do
self:add(v);
end;
else
error("parameter needs to be a object or a list of objects.", 2);
end;
return self;
end;
clUList.find = function(self, field, value)
if type(value) == "nil" then
return self.__dir[field];
elseif type(field) == "nil" then
return self.__dir[value];
else
return clUList.super.find(self, field, value);
end;
end;
clUList.new_item = function(self, ...)
local item = class.classes[self.__allowed]:new(...);
self:add(item);
return item;
end;
clUList.concat = function(self, field, sep)
return clUList.super.concat(self, field or self.__key, sep);
end;
--
-- [string list class] ===============================================
--
local clStrList = clList:subclass("StrList");
clStrList.init = function(self, stringlist)
self.__dir = {};
if stringlist then
if type(stringlist) == "string" then
stringlist = {stringlist};
end;
for _, s in ipairs(stringlist) do
self:add(s)
end;
end;
return self;
end;
clStrList.add = function(self, item, delim)
local function split(s, re)
if type(s) ~= "string" then return s; end;
local i1 = 1;
local ls = {};
re = re or '%s+';
while true do
local i2, i3 = s:find(re, i1);
if not i2 then
insert(ls, s:sub(i1));
return ls;
end;
insert(ls, s:sub(i1, i2 - 1));
i1 = i3 + 1;
end;
end;
if type(item) == "string" then
item = split(item, delim);
end;
if type(item) == "table" then
for _, v in ipairs(item) do
if type(v) ~= "string" then
error("clStrList.add(): parameter needs to be a string or a list of strings.", 2);
end;
if #v > 0 and not self.__dir[v] then
insert(self, v);
self.__dir[v] = v;
end;
end;
elseif item ~= nil then
error("clStrList.add(): parameter needs to be a string or a list of strings.", 2);
end;
return self;
end;
clStrList.find = function(self, value)
return self.__dir[value];
end;
clStrList.concat = function(self, sep)
return concat(self, sep or " ");
end;
--
return class;
end;
package.preload["Cmdl"] = function(...) --luacheck: ignore
local insert, concat = table.insert, table.concat;
local tonumber, table_sort = tonumber, table.sort;
local function split(s, re)
if type(s) ~= "string" then return s; end;
local i1 = 1;
local ls = {};
re = re or '%s+';
while true do
local i2, i3 = s:find(re, i1);
if not i2 then
insert(ls, s:sub(i1));
return ls;
end;
insert(ls, s:sub(i1, i2 - 1));
i1 = i3 + 1;
end;
end;
local cmdl = arg or {};
--[[ Parse command line parameters.
input: argv, argsd,
default: arg, cmdl.argsd,
argv - array of command line arguments,
argsd - array of tables, each table describes a single command, and its fields:
tag - short tag used as parameter key in results table,
cmd - commands synonyms array e.g. {'-h','--help','/?'},
descr - command description (used to generate help text),
def - list of default values, when the switch is found without parameters.
default - list of default values to use, when this switch is not found.
multiple - if true, allows this command multiple times
if false the 2nd occurance creates a error.
params - list of command parameters descriptors, each table containing fields:
t - parameter type:
str (string - default),
int (integer - bin/oct/hex/dec),
float (float), integer/float arguments.
min,max - allowed numeric range (for int/float) or string length range (for strings)
delim (char) - alows multiple values in one parameter separated by <char>.
this cmd alows 1 parameter definitions only.
re - regexp used to check string parameter,
vals - list of possible parameter values,
returns:
error: nil, string:error message
ok: table:args
- table of parsed parameters in the form
{tag={value[,valuem...]}}.
--]]
cmdl.parse = function(argv, argsd)
local result = {};
-- use default parameters, if no parameter given ..
argv, argsd = argv or arg, argsd or cmdl.argsd;
--
local argc, err;
local othercnt = 1;
local shortParamNames = {};
local paramd = {}; --parameter descriptors (for faster search)
-- fill paramd & shortParamNames list...
for _, descr in ipairs(argsd) do
for _, cmd in pairs(descr.cmd) do
if cmd:match"^%-[^%-]" then insert(shortParamNames, cmd); end; --remember short params
paramd[cmd] = descr;
end;
end;
-- sort shortParamNames
table_sort(shortParamNames, function(a, b) return ((#a == #b) and a < b) or #a > #b; end);
--
local function switch(str, others)
if not str then return; end;
local cmd, argd, val;
-- long arg test
cmd, val = str:match"^(%-%-[^=%s]+)[=]?(.*)";
-- short arg test
if not cmd and str:match"^%-[^%-]" then
for _, sw in ipairs(shortParamNames) do
sw = sw:gsub("([%-%?])","%%%1");
if str:match("^"..sw) then
cmd, val = str:match("^("..sw..")(.*)$");
val = val and #val > 0 and val or nil;
break;
end;
end;
end;
-- prepare result
argd = paramd[cmd];
-- no result: others arg test
if not argd and others then
others = others[othercnt];
if others.multiple or (#others.params == 1 and others.params[1].delim) then
return others, str;
end;
othercnt = othercnt + 1;
return others, str;
end;
val = val and #val > 0 and val or nil;
return argd, val;
end;
local function blocked(argd)
if argd and argd.blockedby then
for _, sw in ipairs(argd.blockedby) do
if result[sw] then
err = argc;
return true;
end;
end;
end;
return false;
end;
local function storeValue(argd, str)
local function value_ok(val, paramd)
if paramd.t == 'int' then -- parameter is int
-- determine number base
local base = 10
local baseChar = val:match('^0([bBoOdDxX])')
if baseChar then -- 0x base given
baseChar = baseChar:lower()
if baseChar == 'b' then base = 2 -- binary
elseif baseChar == 'o' then base = 8 -- octal
elseif baseChar == 'd' then base = 10 -- decimal
elseif baseChar == 'x' then base = 16 -- hexadecimal
end
val = val:sub(3, -1) -- extract numeric part
end;
val = tonumber(val, base); -- convert to number
if val then -- no error during conversion - check min/max
-- min/max given - check
if ((paramd.min) and (val < paramd.min)) or
((paramd.max) and (val > paramd.max)) then
return;
end;
end;
elseif paramd.t == 'float' then -- parameter is float
val = tonumber(val) -- convert to number
if val then
-- min/max given - check
if ((paramd.min) and (val < paramd.min)) or
((paramd.max) and (val > paramd.max)) then
return;
end;
end;
else -- parameter is string
if paramd.re then -- check with regexp if given
local m = val:match(paramd.re);
if (m == nil) or (#m ~= #val) then return; end;
end;
if val then
-- check for min/max string length
if ((paramd.min) and (#val < paramd.min)) or
((paramd.max) and (#val > paramd.max)) then
return;
end;
end;
end;
-- check for allowed values list
if paramd.vals then
for _, _val in pairs(paramd.vals) do
if val == _val then return val; end;
end;
-- value not found in values array - error
return;
end;
return val;
end;
--
if str then
-- switch takes parameters?
if not argd.params then err = argc; return; end;
result[argd.tag] = result[argd.tag] or {};
local result = result[argd.tag];
-- switch takes one parameter multiple times?
if #argd.params == 1 and argd.params[1].delim then
local strl = split(str, argd.params[1].delim);
for _, _str in ipairs(strl) do
_str = value_ok(_str, argd.params[1])
if _str then
insert(result, _str);
else
err = argc;
return;
end;
end;
return;
end;
-- switch takes one parameter?
if #argd.params == 1 then
str = value_ok(str, argd.params[1])
if str then
insert(result, str);
else
err = argc;
end;
return;
end;
-- switch takes multiple parameter?
if #argd.params > 1 then
local strl = split(str, argd.delim);
if #argd.params ~= #strl then err = argc; return; end;
local res = {};
for i = 1, #argd do
strl[i] = value_ok(strl[i], argd.params[i])
if strl[i] then
insert(res, strl[i]);
else
err = argc;
return
end;
end;
if argd.multiple then
insert{result, res};
else
for _, v in ipairs(res) do
insert(result, v);
end;
end;
return;
end;
--error("This should not happen here.");
elseif argd.params then
if argd.params.def then
result[argd.tag] = argd.params.def;
else
err = min(argc, #argv);
end;
else
result[argd.tag] = {true};
end;
end;
-- scanning loop
argc = 1;
local nxtargd, nxtval;
while (argc <= #argv) do
local argd, val;
argd, val, nxtargd, nxtval = nxtargd, nxtval; --luacheck: ignore
-- expand next switch, if nessesary
if not argd then argd, val = switch(argv[argc], argsd.others); end;
if blocked(argd) then
err = argc;
break;
end;
if val then -- value attached to switch ...
if argd.params then
storeValue(argd, val);
else
err = argc;
end;
elseif not argd.params then
storeValue(argd, nil);
elseif argd.params then
nxtargd, nxtval = switch(argv[argc+1]);
if not nxtargd then
argc = argc + 1;
storeValue(argd, argv[argc]);
else
storeValue(argd);
end;
end;
if err then break; end;
argc = argc + 1;
end;
-- handle errors
if err then -- generate error message
local msg = "";
for i = 1, #argv do
if i == err then
msg = msg .. " [?> ".. argv[i] .." <?]";
else
msg = msg .. " " .. argv[i];
end;
end
return nil, msg; -- error, error message
end;
-- fill in default values for ommited parameters.
for _, _argd in ipairs(argsd) do
if _argd.default and result[_argd.tag] == nil then
result[_argd.tag] = _argd.default;
end;
end;
-- flatten result list for simple parameters...
for _, _argd in ipairs(argsd) do
if result[_argd.tag] and (not _argd.params or (#_argd.params == 1 and
not (_argd.multiple or _argd.params[1].delim))) then
result[_argd.tag] = result[_argd.tag][1] or true;
end;
end;
--
return result;
end;
-- generates help text from description table
cmdl.help = function(indent)
local result = {};
indent = indent or 0;
if not cmdl.argsd then error("cmdl.help() - no parameter definition found."); end;
for _, arg in ipairs(cmdl.argsd) do
local cmdl = string.rep(" ", indent);
for _, cmd in ipairs(arg.cmd) do
cmdl = cmdl .. cmd .. ', ';
end
cmdl = cmdl:sub(1, -3);
if arg.params then
cmdl = cmdl .. '=';
for _, param in ipairs(arg.params) do
if param.values then -- show list of values
cmdl = cmdl .. "";
for _, v in ipairs(param.values) do cmdl = cmdl .. v .. '|' end;
cmdl = cmdl:sub(1,-2) .. ' ';
elseif param.min or param.max then -- show min/max
cmdl = cmdl..'['
if param.min then cmdl = cmdl .. param.min end;
cmdl = cmdl .. '..';
if param.max then cmdl = cmdl .. param.max end;
cmdl = cmdl .. '] ';
else -- else show parameter type
local t = param.lbl or param.t or 'str';
--t = t:upper();
cmdl = cmdl .. t;
if param.delim then
cmdl = cmdl .. "{" .. param.delim .. t .. "}";
end;
end;
end;
else
cmdl = cmdl .. ' ';
end;
insert(result, {cmdl, arg.descr});
end;
local maxlen = 0;
for _, t in ipairs(result) do
if #t[1] > maxlen then maxlen = #t[1]; end;
end;
for i, t in ipairs(result) do
result[i] = t[1] .. string.rep(" ", maxlen - #t[1]) .. " " .. t[2];
end;
return concat(result,"\n");
end;
--
return cmdl;
end;
--
-- [] =======================================================================
--
local class = require "33log";
require "33list";
local lfs = require "lfs";
local attributes, mkdir = lfs.attributes, lfs.mkdir;
--
local DIRSEP = package.config:sub(1, 1); --luacheck: ignore
local WINDOWS = DIRSEP == '\\' or nil;
local MAKELEVEL = 0;
local Make;
--
--=== [utils] ===============================================================
local warning, warningMF, quit, quitMF, dprint, chdir, choose, pick, split,
shell, execute, roTable, pairsByKeys,
luaVersion,
winapi, posix,
ENV, PWD, NUMCORES;
do
local ok;
if WINDOWS then
ok, winapi = pcall(require, "winapi");
if not ok then winapi = nil; end;
else
ok, posix = pcall(require, "posix");
if not ok then posix = nil; end;
end;
--
local update_pwd;
--
local dir_stack = {};
function update_pwd()
local dir = lfs.currentdir();
if WINDOWS then dir = dir:lower() end;
PWD = dir:gsub("\\", "/");
end;
function chdir(path)
if not path then return end
if path == '!' or path == '<' then
lfs.chdir(remove(dir_stack))
else
insert(dir_stack, lfs.currentdir())
local res, err = lfs.chdir(path)
if not res then quitMF(err) end;
end;
update_pwd();
end;
--
function roTable(t)
local proxy = {}
local mt = { -- create metatable
__index = t;
__newindex = function()
quit("attempt to write a read-only table field.", 2)
end;
}
setmetatable(proxy, mt)
return proxy
end;
function pairsByKeys(t)
local a = {};
for n in pairs(t) do insert(a, n); end;
table_sort(a, function(a, b)
return (type(a) == type(b)) and (a < b) or (type(a) < type(b))
end
);
local i = 0; -- iterator variable
return function() -- iterator function
i = i + 1;
return a[i], a[i] and t[a[i]];
end;
end;
function choose(cond, v1, v2)
if type(cond) == 'string' then
cond = cond ~= '0' and cond ~= 'false'
end;
if cond then return v1 else return v2 end;
end;
function pick(a, b, ...)
if a ~= nil then
return a;
elseif select("#", ...) == 0 then
return b;
else
return pick(b, ...);
end;
end;
function split(s, re)
if type(s) ~= "string" then return s; end;
local i1 = 1;
local ls = {};
re = re or '%s+';
while true do
local i2, i3 = s:find(re, i1);
if not i2 then
insert(ls, s:sub(i1));
return ls;
end;
insert(ls, s:sub(i1, i2 - 1));
i1 = i3 + 1;
end;
end;
function shell(cmd, ...)
cmd = cmd:format(...)
local inf = io_popen(cmd..' 2>&1','r');
if not inf then return '' end;
local res = inf:read('*a');
inf:close();
return res:gsub('\n$','');
end;
function execute(cmd, quiet)
-- 4 spaces at the end of the line means quiet run.
if quiet or cmd:find("%s%s%s%s$") then
cmd = cmd:gsub("%s*$"," > ") .. choose(WINDOWS, 'NUL', '/dev/null') .. " 2>&1";
end
local res1, _, res3 = os_execute(cmd)
if type(res1) == "number" then
return res1 == 0, res1;
else
return res1, res3;
end
end;
-- debug print when `_DEBUG == true`
function dprint(msg, ...)
if _DEBUG then print(msg:format(...)); end;
end;
--
ENV = setmetatable({}, {
__index = function(_, key)
return os_getenv(key)
end;
__newindex = function(_, key, value)
local M = winapi or posix or quitMF("ENV[]: need winapi/posix for environment writes.");
M.setenv(key, value);
end;
}
);
--
update_pwd();
--
end;
--
--=== [filename and path functions] =========================================
local fn_temp, fn_isabs, fn_canonical, fn_join, fn_isFile,
fn_isDir, fn_defaultExt, fn_exists, fn_forceExt, fn_splitext,
fn_get_ext, fn_splitpath, fn_ensurePath, fn_basename, fn_path_lua,
fn_cleanup, fn_abs, fn_rel, fn_which, fn_filetime,
fn_get_files, fn_files_from_mask, fn_get_directories;
do
--
function fn_temp ()
local res = os_tmpname();
if WINDOWS then -- note this necessary workaround for Windows
res = ENV.TMP .. res;
end;
return res;
end;
function fn_isabs(path)
return path and ((path:find '^"*%a:' or path:find '^"*[\\/]') ~= nil);
end;
function fn_canonical(p)
if type(p) ~= 'string' then quit("canonical(): wrong parameter.", 2) end;
if WINDOWS then
local res;
if p:find("%s+") then
res = '"'..p..'"';
else
res = p;
end;
res = res:gsub('/', '\\');
return res; --:lower();
else
p = p:gsub(" ", "\\ ")
return p;
end;
end;
function fn_cleanup(path)
-- shorten path by removing ".."s.
while path:find("/[^%./]+/%.%./") do
path = path:gsub("/[^%./]+/%.%./", "/");
end;
path = path:gsub("/[^%./]+/%.%.$", "");
path = path:gsub("/%.$", "");
return path;
end;
function fn_join(...)
local param = {...}
local t = {}
for i = 1, select("#", ...) do
if param[i] then insert(t, param[i]) end;
end;
param = t;
local idx = 1;
-- start concatination with last absolute path ...
for i, path in ipairs(param) do
if fn_isabs(path) then idx = i; end;
end;
-- remove trailing slashes ...
for i = idx, #param do
local n = param[i];
if n:sub(-1) == "/" or n:sub(-1) == "\\" then param[i] = n:sub(1, -2); end;
end;
--
return fn_cleanup(concat(param, "/", idx))
end;
function fn_isFile(fname, types)
-- types: string, eg: "directory,file"
types = types or "file";
local mode = attributes(fname, 'mode');
return mode and types:find(mode) and true;
end;