-
Notifications
You must be signed in to change notification settings - Fork 0
/
z.lua
2751 lines (2590 loc) · 70.8 KB
/
z.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
#! /usr/bin/env lua
--=====================================================================
--
-- z.lua - a cd command that learns, by skywind 2018, 2019, 2020, 2021
-- Licensed under MIT license.
--
-- Version 1.8.12, Last Modified: 2021/02/15 00:05
--
-- * 10x faster than fasd and autojump, 3x faster than z.sh
-- * available for posix shells: bash, zsh, sh, ash, dash, busybox
-- * available for fish shell, power shell and windows cmd
-- * compatible with lua 5.1, 5.2 and 5.3+
--
-- USE:
-- * z foo # cd to most frecent dir matching foo
-- * z foo bar # cd to most frecent dir matching foo and bar
-- * z -r foo # cd to highest ranked dir matching foo
-- * z -t foo # cd to most recently accessed dir matching foo
-- * z -l foo # list matches instead of cd
-- * z -c foo # restrict matches to subdirs of $PWD
-- * z -e foo # echo the best match, don't cd
-- * z -x path # remove path from history
-- * z -i foo # cd with interactive selection
-- * z -I foo # cd with interactive selection using fzf
-- * z -b foo # cd to the parent directory starting with foo
--
-- Bash Install:
-- * put something like this in your .bashrc:
-- eval "$(lua /path/to/z.lua --init bash)"
--
-- Bash Enhanced Mode:
-- * put something like this in your .bashrc:
-- eval "$(lua /path/to/z.lua --init bash enhanced)"
--
-- Bash fzf tab completion Mode:
-- * put something like this in your .bashrc:
-- eval "$(lua /path/to/z.lua --init bash fzf)"
--
-- Zsh Install:
-- * put something like this in your .zshrc:
-- eval "$(lua /path/to/z.lua --init zsh)"
--
-- Posix Shell Install:
-- * put something like this in your .profile:
-- eval "$(lua /path/to/z.lua --init posix)"
--
-- Fish Shell Install:
-- * put something like this in your config file:
-- source (lua /path/to/z.lua --init fish | psub)
--
-- Power Shell Install:
-- * put something like this in your config file:
-- Invoke-Expression (& {
-- (lua /path/to/z.lua --init powershell) -join "`n" })
--
-- Windows Install (with Clink):
-- * copy z.lua and z.cmd to clink's home directory
-- * Add clink's home to %PATH% (z.cmd can be called anywhere)
-- * Ensure that "lua" can be called in %PATH%
--
-- Windows Cmder Install:
-- * copy z.lua and z.cmd to cmder/vendor
-- * Add cmder/vendor to %PATH%
-- * Ensure that "lua" can be called in %PATH%
--
-- Windows WSL-1:
-- * Install lua-filesystem module before init z.lua:
-- sudo apt-get install lua-filesystem
--
-- Configure (optional):
-- set $_ZL_CMD in .bashrc/.zshrc to change the command (default z).
-- set $_ZL_DATA in .bashrc/.zshrc to change the datafile (default ~/.zlua).
-- set $_ZL_NO_PROMPT_COMMAND if you're handling PROMPT_COMMAND yourself.
-- set $_ZL_EXCLUDE_DIRS to a comma separated list of dirs to exclude.
-- set $_ZL_ADD_ONCE to 1 to update database only if $PWD changed.
-- set $_ZL_CD to specify your own cd command
-- set $_ZL_ECHO to 1 to display new directory name after cd.
-- set $_ZL_MAXAGE to define a aging threshold (default is 5000).
-- set $_ZL_MATCH_MODE to 1 to enable enhanced matching mode.
-- set $_ZL_NO_CHECK to 1 to disable path validation. z --purge to clear.
-- set $_ZL_USE_LFS to 1 to use lua-filesystem package
-- set $_ZL_HYPHEN to 1 to stop treating hyphen as a regexp keyword
--
--=====================================================================
-----------------------------------------------------------------------
-- Module Header
-----------------------------------------------------------------------
local modname = 'z'
local MM = {}
_G[modname] = MM
package.loaded[modname] = MM --return modname
setmetatable(MM, {__index = _G})
if _ENV ~= nil then
_ENV[modname] = MM
else
setfenv(1, MM)
end
-----------------------------------------------------------------------
-- Environment
-----------------------------------------------------------------------
local windows = package.config:sub(1, 1) ~= '/' and true or false
local in_module = pcall(debug.getlocal, 4, 1) and true or false
local utils = {}
os.path = {}
os.argv = arg ~= nil and arg or {}
os.path.sep = windows and '\\' or '/'
-----------------------------------------------------------------------
-- Global Variable
-----------------------------------------------------------------------
MAX_AGE = 5000
DATA_FILE = '~/.zlua'
PRINT_MODE = '<stdout>'
PWD = ''
Z_METHOD = 'frecent'
Z_SUBDIR = false
Z_INTERACTIVE = 0
Z_EXCLUDE = {}
Z_CMD = 'z'
Z_MATCHMODE = 0
Z_MATCHNAME = false
Z_SKIPPWD = false
Z_HYPHEN = false
os.LOG_NAME = os.getenv('_ZL_LOG_NAME')
-----------------------------------------------------------------------
-- string lib
-----------------------------------------------------------------------
function string:split(sSeparator, nMax, bRegexp)
assert(sSeparator ~= '')
assert(nMax == nil or nMax >= 1)
local aRecord = {}
if self:len() > 0 then
local bPlain = not bRegexp
nMax = nMax or -1
local nField, nStart = 1, 1
local nFirst, nLast = self:find(sSeparator, nStart, bPlain)
while nFirst and nMax ~= 0 do
aRecord[nField] = self:sub(nStart, nFirst - 1)
nField = nField + 1
nStart = nLast + 1
nFirst, nLast = self:find(sSeparator, nStart, bPlain)
nMax = nMax - 1
end
aRecord[nField] = self:sub(nStart)
else
aRecord[1] = ''
end
return aRecord
end
function string:startswith(text)
local size = text:len()
if self:sub(1, size) == text then
return true
end
return false
end
function string:endswith(text)
return text == "" or self:sub(-#text) == text
end
function string:lstrip()
if self == nil then return nil end
local s = self:gsub('^%s+', '')
return s
end
function string:rstrip()
if self == nil then return nil end
local s = self:gsub('%s+$', '')
return s
end
function string:strip()
return self:lstrip():rstrip()
end
function string:rfind(key)
if key == '' then
return self:len(), 0
end
local length = self:len()
local start, ends = self:reverse():find(key:reverse(), 1, true)
if start == nil then
return nil
end
return (length - ends + 1), (length - start + 1)
end
function string:join(parts)
if parts == nil or #parts == 0 then
return ''
end
local size = #parts
local text = ''
local index = 1
while index <= size do
if index == 1 then
text = text .. parts[index]
else
text = text .. self .. parts[index]
end
index = index + 1
end
return text
end
-----------------------------------------------------------------------
-- table size
-----------------------------------------------------------------------
function table.length(T)
local count = 0
if T == nil then return 0 end
for _ in pairs(T) do count = count + 1 end
return count
end
-----------------------------------------------------------------------
-- print table
-----------------------------------------------------------------------
function dump(o)
if type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then k = '"'..k..'"' end
s = s .. '['..k..'] = ' .. dump(v) .. ','
end
return s .. '} '
else
return tostring(o)
end
end
-----------------------------------------------------------------------
-- print table
-----------------------------------------------------------------------
function printT(table, level)
key = ""
local func = function(table, level) end
func = function(table, level)
level = level or 1
local indent = ""
for i = 1, level do
indent = indent.." "
end
if key ~= "" then
print(indent..key.." ".."=".." ".."{")
else
print(indent .. "{")
end
key = ""
for k, v in pairs(table) do
if type(v) == "table" then
key = k
func(v, level + 1)
else
local content = string.format("%s%s = %s", indent .. " ",tostring(k), tostring(v))
print(content)
end
end
print(indent .. "}")
end
func(table, level)
end
-----------------------------------------------------------------------
-- invoke command and retrive output
-----------------------------------------------------------------------
function os.call(command)
local fp = io.popen(command)
if fp == nil then
return nil
end
local line = fp:read('*l')
fp:close()
return line
end
-----------------------------------------------------------------------
-- write log
-----------------------------------------------------------------------
function os.log(text)
if not os.LOG_NAME then
return
end
local fp = io.open(os.LOG_NAME, 'a')
if not fp then
return
end
local date = "[" .. os.date('%Y-%m-%d %H:%M:%S') .. "] "
fp:write(date .. text .. "\n")
fp:close()
end
-----------------------------------------------------------------------
-- ffi optimize (luajit has builtin ffi module)
-----------------------------------------------------------------------
os.native = {}
os.native.status, os.native.ffi = pcall(require, "ffi")
if os.native.status then
local ffi = os.native.ffi
if windows then
ffi.cdef[[
int GetFullPathNameA(const char *name, uint32_t size, char *out, char **name);
int ReplaceFileA(const char *dstname, const char *srcname, void *, uint32_t, void *, void *);
uint32_t GetTickCount(void);
uint32_t GetFileAttributesA(const char *name);
uint32_t GetCurrentDirectoryA(uint32_t size, char *ptr);
uint32_t GetShortPathNameA(const char *longname, char *shortname, uint32_t size);
uint32_t GetLongPathNameA(const char *shortname, char *longname, uint32_t size);
]]
local kernel32 = ffi.load('kernel32.dll')
local buffer = ffi.new('char[?]', 4100)
local INVALID_FILE_ATTRIBUTES = 0xffffffff
local FILE_ATTRIBUTE_DIRECTORY = 0x10
os.native.kernel32 = kernel32
function os.native.GetFullPathName(name)
local hr = kernel32.GetFullPathNameA(name, 4096, buffer, nil)
return (hr > 0) and ffi.string(buffer, hr) or nil
end
function os.native.ReplaceFile(replaced, replacement)
local hr = kernel32.ReplaceFileA(replaced, replacement, nil, 2, nil, nil)
return (hr ~= 0) and true or false
end
function os.native.GetTickCount()
return kernel32.GetTickCount()
end
function os.native.GetFileAttributes(name)
return kernel32.GetFileAttributesA(name)
end
function os.native.GetLongPathName(name)
local hr = kernel32.GetLongPathNameA(name, buffer, 4096)
return (hr ~= 0) and ffi.string(buffer, hr) or nil
end
function os.native.GetShortPathName(name)
local hr = kernel32.GetShortPathNameA(name, buffer, 4096)
return (hr ~= 0) and ffi.string(buffer, hr) or nil
end
function os.native.GetRealPathName(name)
local short = os.native.GetShortPathName(name)
if short then
return os.native.GetLongPathName(short)
end
return nil
end
function os.native.exists(name)
local attr = os.native.GetFileAttributes(name)
return attr ~= INVALID_FILE_ATTRIBUTES
end
function os.native.isdir(name)
local attr = os.native.GetFileAttributes(name)
local isdir = FILE_ATTRIBUTE_DIRECTORY
if attr == INVALID_FILE_ATTRIBUTES then
return false
end
return (attr % (2 * isdir)) >= isdir
end
function os.native.getcwd()
local hr = kernel32.GetCurrentDirectoryA(4096, buffer)
if hr <= 0 then return nil end
return ffi.string(buffer, hr)
end
else
ffi.cdef[[
typedef struct { long tv_sec; long tv_usec; } timeval;
int gettimeofday(timeval *tv, void *tz);
int access(const char *name, int mode);
char *realpath(const char *path, char *resolve);
char *getcwd(char *buf, size_t size);
]]
local timeval = ffi.new('timeval[?]', 1)
local buffer = ffi.new('char[?]', 4100)
function os.native.gettimeofday()
local hr = ffi.C.gettimeofday(timeval, nil)
local sec = tonumber(timeval[0].tv_sec)
local usec = tonumber(timeval[0].tv_usec)
return sec + (usec * 0.000001)
end
function os.native.access(name, mode)
return ffi.C.access(name, mode)
end
function os.native.realpath(name)
local path = ffi.C.realpath(name, buffer)
return (path ~= nil) and ffi.string(buffer) or nil
end
function os.native.getcwd()
local hr = ffi.C.getcwd(buffer, 4099)
return hr ~= nil and ffi.string(buffer) or nil
end
end
function os.native.tickcount()
if windows then
return os.native.GetTickCount()
else
return math.floor(os.native.gettimeofday() * 1000)
end
end
os.native.init = true
end
-----------------------------------------------------------------------
-- get current path
-----------------------------------------------------------------------
function os.pwd()
if os.native and os.native.getcwd then
local hr = os.native.getcwd()
if hr then return hr end
end
if os.getcwd then
return os.getcwd()
end
if windows then
local fp = io.popen('cd')
if fp == nil then
return ''
end
local line = fp:read('*l')
fp:close()
return line
else
local fp = io.popen('pwd')
if fp == nil then
return ''
end
local line = fp:read('*l')
fp:close()
return line
end
end
-----------------------------------------------------------------------
-- which executable
-----------------------------------------------------------------------
function os.path.which(exename)
local path = os.getenv('PATH')
if windows then
paths = ('.;' .. path):split(';')
else
paths = path:split(':')
end
for _, path in pairs(paths) do
if not windows then
local name = path .. '/' .. exename
if os.path.exists(name) then
return name
end
else
for _, ext in pairs({'.exe', '.cmd', '.bat'}) do
local name = path .. '\\' .. exename .. ext
if path == '.' then
name = exename .. ext
end
if os.path.exists(name) then
return name
end
end
end
end
return nil
end
-----------------------------------------------------------------------
-- absolute path (simulated)
-----------------------------------------------------------------------
function os.path.absolute(path)
local pwd = os.pwd()
return os.path.normpath(os.path.join(pwd, path))
end
-----------------------------------------------------------------------
-- absolute path (system call, can fall back to os.path.absolute)
-----------------------------------------------------------------------
function os.path.abspath(path)
if path == '' then path = '.' end
if os.native and os.native.GetFullPathName then
local test = os.native.GetFullPathName(path)
if test then return test end
end
if windows then
local script = 'FOR /f "delims=" %%i IN ("%s") DO @echo %%~fi'
local script = string.format(script, path)
local script = 'cmd.exe /C ' .. script .. ' 2> nul'
local output = os.call(script)
local test = output:gsub('%s$', '')
if test ~= nil and test ~= '' then
return test
end
else
local test = os.path.which('realpath')
if test ~= nil and test ~= '' then
test = os.call('realpath -s \'' .. path .. '\' 2> /dev/null')
if test ~= nil and test ~= '' then
return test
end
test = os.call('realpath \'' .. path .. '\' 2> /dev/null')
if test ~= nil and test ~= '' then
return test
end
end
local test = os.path.which('perl')
if test ~= nil and test ~= '' then
local s = 'perl -MCwd -e "print Cwd::realpath(\\$ARGV[0])" \'%s\''
local s = string.format(s, path)
test = os.call(s)
if test ~= nil and test ~= '' then
return test
end
end
for _, python in pairs({'python', 'python2', 'python3'}) do
local s = 'sys.stdout.write(os.path.abspath(sys.argv[1]))'
local s = '-c "import os, sys;' .. s .. '" \'' .. path .. '\''
local s = python .. ' ' .. s
local test = os.path.which(python)
if test ~= nil and test ~= '' then
return os.call(s)
end
end
end
return os.path.absolute(path)
end
-----------------------------------------------------------------------
-- dir exists
-----------------------------------------------------------------------
function os.path.isdir(pathname)
if pathname == '/' then
return true
elseif pathname == '' then
return false
elseif windows then
if pathname == '\\' then
return true
end
end
if os.native and os.native.isdir then
return os.native.isdir(pathname)
end
if clink and os.isdir then
return os.isdir(pathname)
end
local name = pathname
if (not name:endswith('/')) and (not name:endswith('\\')) then
name = name .. os.path.sep
end
return os.path.exists(name)
end
-----------------------------------------------------------------------
-- file or path exists
-----------------------------------------------------------------------
function os.path.exists(name)
if name == '/' then
return true
end
if os.native and os.native.exists then
return os.native.exists(name)
end
local ok, err, code = os.rename(name, name)
if not ok then
if code == 13 or code == 17 then
return true
elseif code == 30 then
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
end
elseif name:sub(-1) == '/' and code == 20 and (not windows) then
local test = name .. '.'
ok, err, code = os.rename(test, test)
if code == 16 or code == 13 or code == 22 then
return true
end
end
return false
end
return true
end
-----------------------------------------------------------------------
-- is absolute path
-----------------------------------------------------------------------
function os.path.isabs(path)
if path == nil or path == '' then
return false
elseif path:sub(1, 1) == '/' then
return true
end
if windows then
local head = path:sub(1, 1)
if head == '\\' then
return true
elseif path:match('^%a:[/\\]') ~= nil then
return true
end
end
return false
end
-----------------------------------------------------------------------
-- normalize path
-----------------------------------------------------------------------
function os.path.norm(pathname)
if windows then
pathname = pathname:gsub('\\', '/')
end
if windows then
pathname = pathname:gsub('/', '\\')
end
return pathname
end
-----------------------------------------------------------------------
-- normalize . and ..
-----------------------------------------------------------------------
function os.path.normpath(path)
if os.path.sep ~= '/' then
path = path:gsub('\\', '/')
end
path = path:gsub('/+', '/')
local srcpath = path
local basedir = ''
local isabs = false
if windows and path:sub(2, 2) == ':' then
basedir = path:sub(1, 2)
path = path:sub(3, -1)
end
if path:sub(1, 1) == '/' then
basedir = basedir .. '/'
isabs = true
path = path:sub(2, -1)
end
local parts = path:split('/')
local output = {}
for _, path in ipairs(parts) do
if path == '.' or path == '' then
elseif path == '..' then
local size = #output
if size == 0 then
if not isabs then
table.insert(output, '..')
end
elseif output[size] == '..' then
table.insert(output, '..')
else
table.remove(output, size)
end
else
table.insert(output, path)
end
end
path = basedir .. string.join('/', output)
if windows then path = path:gsub('/', '\\') end
return path == '' and '.' or path
end
-----------------------------------------------------------------------
-- join two path
-----------------------------------------------------------------------
function os.path.join(path1, path2)
if path1 == nil or path1 == '' then
if path2 == nil or path2 == '' then
return ''
else
return path2
end
elseif path2 == nil or path2 == '' then
local head = path1:sub(-1, -1)
if head == '/' or (windows and head == '\\') then
return path1
end
return path1 .. os.path.sep
elseif os.path.isabs(path2) then
if windows then
local head = path2:sub(1, 1)
if head == '/' or head == '\\' then
if path1:match('^%a:') then
return path1:sub(1, 2) .. path2
end
end
end
return path2
elseif windows then
local d1 = path1:match('^%a:') and path1:sub(1, 2) or ''
local d2 = path2:match('^%a:') and path2:sub(1, 2) or ''
if d1 ~= '' then
if d2 ~= '' then
if d1:lower() == d2:lower() then
return d2 .. os.path.join(path1:sub(3), path2:sub(3))
else
return path2
end
end
elseif d2 ~= '' then
return path2
end
end
local postsep = true
local len1 = path1:len()
local len2 = path2:len()
if path1:sub(-1, -1) == '/' then
postsep = false
elseif windows then
if path1:sub(-1, -1) == '\\' then
postsep = false
elseif len1 == 2 and path1:sub(2, 2) == ':' then
postsep = false
end
end
if postsep then
return path1 .. os.path.sep .. path2
else
return path1 .. path2
end
end
-----------------------------------------------------------------------
-- split
-----------------------------------------------------------------------
function os.path.split(path)
if path == '' then
return '', ''
end
local pos = path:rfind('/')
if os.path.sep == '\\' then
local p2 = path:rfind('\\')
if pos == nil and p2 ~= nil then
pos = p2
elseif pos ~= nil and p2 ~= nil then
pos = (pos < p2) and pos or p2
end
if path:match('^%a:[/\\]') and pos == nil then
return path:sub(1, 2), path:sub(3)
end
end
if pos == nil then
if windows then
local drive = path:match('^%a:') and path:sub(1, 2) or ''
if drive ~= '' then
return path:sub(1, 2), path:sub(3)
end
end
return '', path
elseif pos == 1 then
return path:sub(1, 1), path:sub(2)
elseif windows then
local drive = path:match('^%a:') and path:sub(1, 2) or ''
if pos == 3 and drive ~= '' then
return path:sub(1, 3), path:sub(4)
end
end
local head = path:sub(1, pos)
local tail = path:sub(pos + 1)
if not windows then
local test = string.rep('/', head:len())
if head ~= test then
head = head:gsub('/+$', '')
end
else
local t1 = string.rep('/', head:len())
local t2 = string.rep('\\', head:len())
if head ~= t1 and head ~= t2 then
head = head:gsub('[/\\]+$', '')
end
end
return head, tail
end
-----------------------------------------------------------------------
-- check subdir
-----------------------------------------------------------------------
function os.path.subdir(basename, subname)
if windows then
basename = basename:gsub('\\', '/')
subname = subname:gsub('\\', '/')
basename = basename:lower()
subname = subname:lower()
end
local last = basename:sub(-1, -1)
if last ~= '/' then
basename = basename .. '/'
end
if subname:find(basename, 0, true) == 1 then
return true
end
return false
end
-----------------------------------------------------------------------
-- check single name element
-----------------------------------------------------------------------
function os.path.single(path)
if string.match(path, '/') then
return false
end
if windows then
if string.match(path, '\\') then
return false
end
end
return true
end
-----------------------------------------------------------------------
-- expand user home
-----------------------------------------------------------------------
function os.path.expand(pathname)
if not pathname:find('~') then
return pathname
end
local home = ''
if windows then
home = os.getenv('USERPROFILE')
else
home = os.getenv('HOME')
end
if pathname == '~' then
return home
end
local head = pathname:sub(1, 2)
if windows then
if head == '~/' or head == '~\\' then
return home .. '\\' .. pathname:sub(3, -1)
end
elseif head == '~/' then
return home .. '/' .. pathname:sub(3, -1)
end
return pathname
end
-----------------------------------------------------------------------
-- search executable
-----------------------------------------------------------------------
function os.path.search(name)
end
-----------------------------------------------------------------------
-- get lua executable
-----------------------------------------------------------------------
function os.interpreter()
if os.argv == nil then
io.stderr:write("cannot get arguments (arg), recompiled your lua\n")
return nil
end
local lua = os.argv[-1]
if lua == nil then
io.stderr:write("cannot get executable name, recompiled your lua\n")
end
if os.path.single(lua) then
local path = os.path.which(lua)
if not os.path.isabs(path) then
return os.path.abspath(path)
end
return path
end
return os.path.abspath(lua)
end
-----------------------------------------------------------------------
-- get script name
-----------------------------------------------------------------------
function os.scriptname()
if os.argv == nil then
io.stderr:write("cannot get arguments (arg), recompiled your lua\n")
return nil
end
local script = os.argv[0]
if script == nil then
io.stderr:write("cannot get script name, recompiled your lua\n")
end
return os.path.abspath(script)
end
-----------------------------------------------------------------------
-- get environ
-----------------------------------------------------------------------
function os.environ(name, default)
local value = os.getenv(name)
if os.envmap ~= nil and type(os.envmap) == 'table' then
local t = os.envmap[name]
value = (t ~= nil and type(t) == 'string') and t or value
end
if value == nil then
return default
elseif type(default) == 'boolean' then
value = value:lower()
if value == '0' or value == '' or value == 'no' then
return false
elseif value == 'false' or value == 'n' or value == 'f' then
return false
else
return true
end
elseif type(default) == 'number' then
value = tonumber(value)
if value == nil then
return default
else
return value
end
elseif type(default) == 'string' then
return value
elseif type(default) == 'table' then
return value:sep(',')
end
end
-----------------------------------------------------------------------
-- parse option
-----------------------------------------------------------------------
function os.getopt(argv)
local args = {}
local options = {}
argv = argv ~= nil and argv or os.argv
if argv == nil then
return nil, nil
elseif (#argv) == 0 then
return options, args
end
local count = #argv
local index = 1
while index <= count do
local arg = argv[index]
local head = arg:sub(1, 1)
if arg ~= '' then
if head ~= '-' then
break
end
if arg == '-' then
options['-'] = ''
elseif arg == '--' then
options['-'] = '-'
elseif arg:match('^-%d+$') then
options['-'] = arg:sub(2)
else
local part = arg:split('=')
options[part[1]] = part[2] ~= nil and part[2] or ''
end
end
index = index + 1
end
while index <= count do
table.insert(args, argv[index])
index = index + 1
end
return options, args
end
-----------------------------------------------------------------------
-- generate random seed
-----------------------------------------------------------------------
function math.random_init()
-- random seed from os.time()
local seed = tostring(os.time() * 1000)
seed = seed .. tostring(math.random(99999999))
if os.argv ~= nil then
for _, key in ipairs(os.argv) do
seed = seed .. '/' .. key
end
end
local ppid = os.getenv('PPID')
seed = (ppid ~= nil) and (seed .. '/' .. ppid) or seed
-- random seed from socket.gettime()