forked from starwing/lpath
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lpath.c
2144 lines (1918 loc) · 71 KB
/
lpath.c
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
#define LUA_LIB
#include <lua.h>
#include <time.h>
#include <lauxlib.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
/* compatible */
#if LUA_VERSION_NUM < 502
# define LUA_OK 0
# define lua_rawlen lua_objlen
# define lua_getuservalue lua_getfenv
# define lua_setuservalue lua_setfenv
# ifndef LUA_GCISRUNNING /* not LuaJIT 2.1 */
# define luaL_newlib(L,l) (lua_newtable(L), luaL_register(L,NULL,l))
static lua_Integer lua_tointegerx(lua_State *L, int idx, int *pisint) {
*pisint = lua_type(L, idx) == LUA_TNUMBER;
return *pisint ? lua_tointeger(L, idx) : 0;
}
# ifndef luaL_testudata
# define luaL_testudata luaL_testudata
static void *luaL_testudata(lua_State *L, int ud, const char *tname) {
void *p = lua_touserdata(L, ud);
if (p != NULL) {
if (lua_getmetatable(L, ud)) {
luaL_getmetatable(L, tname);
if (!lua_rawequal(L, -1, -2)) p = NULL;
lua_pop(L, 2);
return p;
}
}
return NULL;
}
# endif /* luaL_testudata */
# endif /* not LuaJIT 2.1 */
#endif /* Lua 5.1 */
#if LUA_VERSION_NUM >= 502
# define lua52_pushstring lua_pushstring
#else
static const char *lua52_pushstring(lua_State *L, const char *s)
{ lua_pushstring(L, s); return lua_tostring(L, -1); }
#endif
#if LUA_VERSION_NUM >= 503
# define lua53_rawgetp lua_rawgetp
#elif LUA_VERSION_NUM == 502
static int lua53_rawgetp(lua_State *L, int idx, const void *p)
{ lua_rawgetp(L, idx, p); return lua_type(L, -1); }
#else
static int lua53_rawgetp(lua_State *L, int idx, const void *p)
{ lua_pushlightuserdata(L, (void*)p); lua_rawget(L, idx); return lua_type(L, -1); }
#ifndef lua_rawsetp
#define lua_rawsetp lua_rawsetp
static void lua_rawsetp(lua_State *L, int idx, const void *p)
{ lua_pushlightuserdata(L, (void*)p); lua_insert(L, -2); lua_rawset(L, idx); }
#endif
#endif
#ifndef LUAMOD_API
# define LUAMOD_API LUALIB_API
#endif
#define LP_VERSION "path 0.3"
/* vector routines */
typedef struct VecHeader { unsigned len, cap; } VecHeader;
#define VEC_MIN_LEN (4)
#define VEC_MAX_LEN (~(unsigned)0 - 100)
#define vec_init(A) ((A) = NULL)
#define vec_free(A) (vec_resize(NULL,A,0), vec_init(A))
#define vec_reset(A) vec_setlen(A,0)
#define vec_setlen(A,N) ((A) ? vec_rawlen(A) = (unsigned)(N) : 0u)
#define vec_(A) ((VecHeader*)(A)-1)
#define vec_sz(A) (sizeof(*(A)))
#define vec_rawlen(A) (vec_(A)->len)
#define vec_rawcap(A) (vec_(A)->cap)
#define vec_rawend(A) (&(A)[vec_rawlen(A)])
#define vec_hdr(A) ((A) ? vec_(A) : NULL)
#define vec_len(A) ((A) ? vec_rawlen(A) : 0u)
#define vec_cap(A) ((A) ? vec_rawcap(A) : 0u)
#define vec_end(A) ((A) ? vec_rawend(A) : NULL)
#define vec_rawgrow(L,A,N) (vec_grow_((L),(void**)&(A),(unsigned)(N),vec_sz(A)))
#define vec_resize(L,A,N) (vec_resize_((L),(void**)&(A),(N),vec_sz(A)))
#define vec_grow(L,A,N) (assert(L), vec_rawgrow(L,A,N), vec_rawend(A))
#define vec_push(L,A,V) (*vec_grow(L,A,1)=(V), vec_rawlen(A) += 1)
#define vec_pop(A) (vec_len(A) ? vec_rawlen(A) -= 1 : 0)
#define vec_fill(L,A,V,S) (memcpy(vec_grow(L,A,(S)+1),(V),(S)*vec_sz(A)))
#define vec_extend(L,A,V,S) (vec_fill(L,A,V,S), vec_rawlen(A)+=(unsigned)(S))
#define vec_concat(L,A,V) vec_extend(L,A,V,strlen(V))
static int vec_resize_(lua_State *L, void **pA, unsigned cap, size_t objlen) {
VecHeader *AI, *oldAI = (assert(pA), vec_hdr(*pA));
if (cap == 0) { free(oldAI); vec_init(*pA); return 1; }
AI = (VecHeader*)realloc(oldAI, sizeof(VecHeader) + cap*objlen);
if (AI == NULL) return L ? luaL_error(L, "out of memory") : 0;
if (!oldAI) AI->cap = AI->len = 0;
if (AI->cap > cap) AI->cap = cap;
AI->cap = cap;
*pA = (void*)(AI + 1);
return 1;
}
static int vec_grow_(lua_State *L, void **pA, unsigned len, size_t objlen) {
unsigned cap = vec_cap(*pA);
unsigned exp = vec_len(*pA) + len;
if (cap < exp) {
unsigned newcap = VEC_MIN_LEN;
while (newcap < VEC_MAX_LEN/objlen && newcap < exp)
newcap += newcap>>1;
if (newcap < exp) return L ? luaL_error(L, "out of memory") : 0;
return vec_resize_(L, pA, newcap, objlen);
}
return 1;
}
/* state */
#define LP_STATE_KEY ((void*)(ptrdiff_t)0x9A76B0FF)
#define LP_WALKER_TYPE "lpath.Walker"
#define LP_GLOB_TYPE "lpath.Glob"
#define LP_PARTS_ITER "lpath.PartsIter"
typedef struct lp_Part lp_Part;
typedef struct lp_State lp_State;
typedef struct lp_Walker lp_Walker;
#define LP_WALKER_PUBLIC \
char *path; \
int level; \
lp_WalkState state; \
lp_WalkPart *parts /* 'pos' is readonly, others are undefined */
typedef enum lp_WalkState {
LP_WALKINIT,
LP_WALKIN,
LP_WALKFILE,
LP_WALKOUT,
LP_WALKDIR,
} lp_WalkState;
struct lp_Part {
const char *s, *e;
};
typedef struct lp_PartResult {
lp_Part *parts; /* drive & parts list */
int dots; /* count of '..', -1 for '/', -2 for "//" */
} lp_PartResult;
struct lp_State {
lua_State *L;
char *buf;
lp_PartResult pr, pr1;
#ifdef _WIN32
wchar_t *wbuf;
int cp;
#endif /* _WIN32 */
};
static size_t lp_len(lp_Part s) { return s.e - s.s; }
static lp_Part lp_part(const char *s, size_t len)
{ lp_Part p; return (p.s = s, p.e = s+len, p); }
static int lp_pushresult(lp_State *S)
{ return lua_pushlstring(S->L, S->buf, vec_len(S->buf)), 1; }
static void lp_resetpr(lp_PartResult *pr)
{ vec_reset(pr->parts), pr->dots = 0; }
static void lp_freepr(lp_PartResult *pr)
{ if (pr) vec_free(pr->parts), pr->dots = 0; }
static int lpL_delstate(lua_State *L) {
lp_State *S = (lp_State*)lua_touserdata(L, 1);
if (S != NULL) {
lp_freepr(&S->pr);
lp_freepr(&S->pr1);
vec_free(S->buf);
#ifdef _WIN32
vec_free(S->wbuf);
#endif
memset(S, 0, sizeof(lp_State));
}
return 0;
}
static lp_State *lp_resetstate(lp_State *S) {
lp_resetpr(&S->pr);
lp_resetpr(&S->pr1);
vec_reset(S->buf);
#ifdef _WIN32
vec_reset(S->wbuf);
#endif
return S;
}
static lp_State *lp_getstate(lua_State *L) {
lp_State *S;
if (lua53_rawgetp(L, LUA_REGISTRYINDEX, LP_STATE_KEY) == LUA_TUSERDATA)
S = (lp_State*)lua_touserdata(L, -1);
else {
S = (lp_State*)lua_newuserdata(L, sizeof(lp_State));
memset(S, 0, sizeof(lp_State));
lua_createtable(L, 0, 1);
lua_pushcfunction(L, lpL_delstate);
lua_setfield(L, -2, "__gc");
lua_setmetatable(L, -2);
lua_rawsetp(L, LUA_REGISTRYINDEX, LP_STATE_KEY);
}
lua_pop(L, 1);
S->L = L;
return lp_resetstate(S);
}
/* path algorithm */
#if _WIN32
# define LP_DIRSEP "\\"
# define LP_ALTSEP "/"
# define LP_EXTSEP "."
# define LP_CURDIR "."
# define LP_PARDIR ".."
# define LP_PATHSEP ";"
# define LP_DEVNULL "nul"
#else
# define LP_DIRSEP "/"
# define LP_ALTSEP "/"
# define LP_EXTSEP "."
# define LP_CURDIR "."
# define LP_PARDIR ".."
# define LP_PATHSEP ":"
# define LP_DEVNULL "/dev/null"
#endif
#define LP_LEN(NAME) (sizeof(LP_##NAME)-1)
#define lp_isdirsep(ch) ((ch) == LP_DIRSEP[0] || (ch) == LP_ALTSEP[0])
#define lp_isdirend(ch) (lp_isdirsep(ch) || ch == '\0')
#define lp_iscurdir(s) (memcmp((s),LP_CURDIR,LP_LEN(CURDIR)) == 0 && lp_isdirend(s[LP_LEN(CURDIR)]))
#define lp_ispardir(s) (memcmp((s),LP_PARDIR,LP_LEN(PARDIR)) == 0 && lp_isdirend(s[LP_LEN(PARDIR)]))
#define lp_charequal(ch1,ch2) (lp_normchar(ch1) == lp_normchar(ch2))
static const char *lp_nextsep(const char *p) {
while (*p != '\0' && !lp_isdirsep(*p))
++p;
return p;
}
static int lp_splitdrive(const char *s, lp_Part *p) {
if (!(p->s = p->e = s)) return 0;
#ifdef _WIN32
if (lp_isdirsep(s[0]) && lp_isdirsep(s[1]) && !lp_isdirsep(s[2])) {
if (lp_isdirsep(s[3])) {
if (s[2] == '?') { /* raw path? */
p->e += s[4] && s[5] == ':' ? 6 : 4;
return lp_isdirsep(*p->e);
}
if (s[2] == '.') { /* device path? */
p->e = lp_isdirsep(s[4]) ? (p->s = s + 4) :
(s[4] ? lp_nextsep(s + 4) : s + 4);
return 1;
}
}
if (*(p->e = lp_nextsep(s + 2)) == '\0') /* normal path? */
return p->e = p->s, 1;
return p->e = lp_nextsep(p->e + 1), 1; /* UNC path */
}
p->e += s[0] && s[1] == ':' ? 2 : 0;
return lp_isdirsep(*p->e);
#else
return !lp_isdirsep(s[0]) ? 0 :
(lp_isdirsep(s[1]) && !lp_isdirsep(s[2])) ? 2 : 1;
#endif
}
static int lp_normchar(int ch) {
#ifdef _WIN32
if (lp_isdirsep(ch))
return LP_DIRSEP[0];
if (ch >= 'a' && ch <='z')
return ch + 'A' - 'a';
#endif
return ch;
}
static int lp_driveequal(lp_Part d1, lp_Part d2) {
size_t l = lp_len(d2);
if (l == 0) return 1;
if (lp_len(d1) != l) return 0;
while (d1.s < d1.e && d2.s < d2.e && lp_charequal(*d1.s, *d2.s))
++d1.s, ++d2.s;
return d1.s == d1.e;
}
static void lp_joinraw(lua_State *L, const char *s, lp_PartResult *pr) {
while (*s != '\0') {
lp_Part *cur = vec_grow(L, pr->parts, 1);
while (lp_isdirsep(*s)) ++s;
cur->s = s;
cur->e = s = lp_nextsep(s);
if (lp_iscurdir(cur->s)) {
if (*cur->e == '\0') vec_rawlen(pr->parts) += 1;
cur->e = cur->s;
} else if (!lp_ispardir(cur->s))
vec_rawlen(pr->parts) += 1;
else if (vec_rawlen(pr->parts) > 1)
vec_rawlen(pr->parts) -= 1;
else if (pr->dots >= 0)
pr->dots += 1;
}
}
static int lp_joinparts(lua_State *L, const char *s, lp_PartResult *pr) {
lp_Part drive;
int root = lp_splitdrive(s, &drive);
if (!vec_len(pr->parts))
vec_push(L, pr->parts, drive);
else if (!lp_driveequal(pr->parts[0], drive))
vec_rawlen(pr->parts) = 1, pr->parts[0] = drive, pr->dots = -root;
if (root) /* is absolute path? */
vec_rawlen(pr->parts) = 1, pr->dots = -root;
if (vec_rawlen(pr->parts) > 1 && lp_len(vec_rawend(pr->parts)[-1]) == 0)
vec_rawlen(pr->parts) -= 1; /* remove trailing '/' */
if (vec_rawlen(pr->parts) > 1 && *drive.e == '\0')
vec_push(L, pr->parts, lp_part(drive.e, 0)); /* empty? add '/' */
else /* join path to current parts */
lp_joinraw(L, drive.e, pr);
return pr->dots;
}
static char *lp_applydrive(lua_State *L, char **pp, lp_Part drive) {
const char *s;
for (s = drive.s; s < drive.e; ++s)
vec_push(L, *pp, lp_normchar(*s));
return *pp;
}
static char *lp_applyparts(lua_State *L, char **pp, lp_PartResult *pr) {
int i, len = vec_len(pr->parts);
if (len) {
lp_applydrive(L, pp, pr->parts[0]);
if (pr->dots == -1) vec_concat(L, *pp, LP_DIRSEP);
if (pr->dots == -2) vec_concat(L, *pp, LP_DIRSEP LP_DIRSEP);
if (pr->dots > 0) {
vec_concat(L, *pp, LP_PARDIR);
for (i = 1; i < pr->dots; ++i)
vec_concat(L, *pp, LP_DIRSEP LP_PARDIR);
if (len > 1) vec_concat(L, *pp, LP_DIRSEP);
}
for (i = 1; i < len; ++i) {
if (i > 1) vec_concat(L, *pp, LP_DIRSEP);
vec_extend(L, *pp, pr->parts[i].s, lp_len(pr->parts[i]));
}
}
if (vec_len(*pp) == 0) vec_push(L, *pp, LP_CURDIR[0]);
*vec_grow(L, *pp, 1) = 0;
return *pp;
}
static lp_Part lp_name(lp_PartResult *pr) {
unsigned len = vec_len(pr->parts);
lp_Part *name;
if (len == 1 || (len == 2 && lp_len(pr->parts[1]) == 0))
return pr->dots > 0 ? lp_part(LP_PARDIR, sizeof(LP_PARDIR)-1)
: lp_part(NULL, 0);
name = vec_rawend(pr->parts);
return lp_len(name[-1]) ? name[-1] : name[-2];
}
static const char *lp_splitext(lp_Part name) {
const char *p = name.e;
while (name.s < p && *p != LP_EXTSEP[0])
--p;
return name.s < p && p != name.e - 1 ? p : name.e;
}
static int lp_indexparts(lua_State *L, int idx, lp_PartResult *pr) {
int len = (int)vec_len(pr->parts);
int extra = pr->dots < 0 || (len && lp_len(pr->parts[0]));
len += (pr->dots > 0 ? pr->dots : 0) + extra - 1 -
(len && lp_len(pr->parts[len-1]) == 0);
if (idx < 0) idx += len + 1;
if (!(idx >= 1 && idx <= len)) return 0;
if (extra && idx == 1) {
luaL_Buffer B;
const char *s;
luaL_buffinit(L, &B);
for (s = pr->parts[0].s; s < pr->parts[0].e; ++s)
luaL_addchar(&B, lp_normchar(*s));
luaL_addstring(&B, pr->dots == -1 ?
LP_DIRSEP : pr->dots == -2 ? LP_DIRSEP LP_DIRSEP : "");
luaL_pushresult(&B);
} else if (idx <= pr->dots)
lua_pushstring(L, LP_PARDIR);
else {
idx -= (pr->dots < 0 ? 0 : pr->dots) + extra;
if (idx < 0 || idx >= (int)vec_len(pr->parts))
return lua_pushliteral(L, ""), 1;
lua_pushlstring(L, pr->parts[idx].s, lp_len(pr->parts[idx]));
}
return 1;
}
static lp_State *lp_joinargs(lua_State *L, int start, int count) {
lp_State *S = lp_getstate(L);
int i;
for (i = start; i <= count; ++i)
lp_joinparts(L, luaL_checkstring(L, i), &S->pr);
return S;
}
/* system specfied utils */
#define LP_MAX_TMPNUM 1000000
#define LP_MAX_TMPCNT 6 /* 10 ** LP_MAX_TMPCNT */
#define lp_bool(L,b) (lua_pushboolean((L), (b)), 1)
#ifdef _WIN32
# define WIN32_LEAN_AND_MEAN
# include <Windows.h>
#define LP_PLATFORM "windows"
#define lp_pusherror(L,t,f) lpP_pusherrmsg((L), GetLastError(), (t), (f))
static const char *lpP_win32error(lua_State *L, DWORD errnum) {
lp_State *S = lp_getstate(L);
const char *ret = NULL;
LPWSTR msg = NULL;
DWORD len = FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL, errnum,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR)&msg, 0, NULL);
if (len == 0) return "get system error message error";
ret = vec_grow(L, S->buf, ((size_t)len*3 + 1));
int bc = WideCharToMultiByte(S->cp, 0, msg, len + 1,
(char*)ret, len*3 + 1, NULL, NULL);
LocalFree(msg);
if (bc > (int)len*3 + 1) return "error message too large";
if (bc == 0) return "mutibyte: format error message error";
vec_rawlen(S->buf) += bc-1;
return ret;
}
static int lpP_pusherrmsg(lua_State *L, DWORD err, const char *title, const char *fn) {
const char *lfn = lua52_pushstring(L, fn), *msg = lpP_win32error(L, err);
lua_pushnil(L);
if (title && lfn)
lua_pushfstring(L, "%s:%s:(errno=%d): %s", title, lfn, err, msg);
else
lua_pushfstring(L, "%s:(errno=%d): %s", title ? title : lfn, err, msg);
lua_remove(L, -3);
return -2;
}
static LPWSTR lpP_addl2wstring(lua_State *L, LPWSTR *ws, LPCSTR s, int bc, int cp) {
int size = (bc = bc < 0 ? (int)strlen(s) : bc) + 1, wc;
if (bc == 0) return *vec_grow(L, *ws, 1) = 0, vec_rawend(*ws);
wc = MultiByteToWideChar(cp, 0, s, bc,
vec_grow(L, *ws, size), size);
if (wc > bc) size = wc + 1,
wc = MultiByteToWideChar(cp, 0, s, bc,
vec_grow(L, *ws, size), size);
if (wc == 0) lp_pusherror(L, "unicode", NULL), lua_error(L);
vec_rawlen(*ws) += wc, *vec_grow(L, *ws, 1) = 0;
return vec_rawend(*ws) - (ptrdiff_t)wc;
}
static LPSTR lpP_addlw2string(lua_State *L, LPSTR *s, LPCWSTR ws, int wc, int cp) {
int size = ((wc = wc < 0 ? (int)wcslen(ws) : wc) + 1) * 3, bc;
if (wc == 0) return *vec_grow(L, *s, 1) = 0, vec_rawend(*s);
bc = WideCharToMultiByte(cp, 0, ws, wc,
vec_grow(L, *s, size), size, NULL, NULL);
if (bc > size) size = bc + 1,
bc = WideCharToMultiByte(cp, 0, ws, wc,
vec_grow(L, *s, size), size, NULL, NULL);
if (bc == 0) lp_pusherror(L, "multibyte", NULL), lua_error(L);
vec_rawlen(*s) += bc, *vec_grow(L, *s, 1) = 0;
return vec_rawend(*s) - (ptrdiff_t)bc;
}
static int lpL_ansi(lua_State *L) {
lp_State *S = lp_getstate(L);
size_t len;
const char *utf8;
switch (lua_type(L, 1)) {
case LUA_TNONE:
case LUA_TNIL: return S->cp = CP_ACP, 0;
case LUA_TNUMBER: return S->cp = (UINT)lua_tonumber(L, 1), 0;
case LUA_TSTRING:
utf8 = lua_tolstring(L, 1, &len);
lpP_addl2wstring(L, &S->wbuf, utf8, (int)len, CP_UTF8);
lpP_addlw2string(L, &S->buf, S->wbuf, -1, S->cp);
return lp_pushresult(S);
default:
lua_pushfstring(L, "number/string expected, got %s",
luaL_typename(L, 1));
return luaL_argerror(L, 1, lua_tostring(L, -1));
}
}
static int lpL_utf8(lua_State *L) {
lp_State *S = lp_getstate(L);
size_t len;
const char *ansi;
switch (lua_type(L, 1)) {
case LUA_TNONE:
case LUA_TNIL: return S->cp = CP_UTF8, 0;
case LUA_TNUMBER: return S->cp = (UINT)lua_tonumber(L, 1), 0;
case LUA_TSTRING:
ansi = lua_tolstring(L, 1, &len);
lpP_addl2wstring(L, &S->wbuf, ansi, (int)len, S->cp);
lpP_addlw2string(L, &S->buf, S->wbuf, -1, CP_UTF8);
return lp_pushresult(S);
default:
lua_pushfstring(L, "number/string expected, got %s",
luaL_typename(L, 1));
return luaL_argerror(L, 1, lua_tostring(L, -1));
}
return 0;
}
/* scandir */
typedef struct lp_WalkPart {
HANDLE *hFile;
unsigned pos;
} lp_WalkPart;
struct lp_Walker {
LP_WALKER_PUBLIC;
/* private */
int cp;
WCHAR *wpath;
WIN32_FIND_DATAW wfd;
DWORD err;
};
static void lp_initwalker(lp_State *S, lp_Walker *w, char *s, int level) {
memset(w, 0, sizeof(*w));
w->cp = S->cp;
w->path = s;
w->level = level;
w->state = LP_WALKINIT;
}
static void lp_freewalker(lp_Walker *w) {
int i, len;
for (i = 0, len = vec_len(w->parts); i < len; ++i)
FindClose(w->parts[i].hFile);
vec_free(w->path);
vec_free(w->wpath);
vec_free(w->parts);
}
static int lpW_init(lua_State *L, lp_Walker *w) {
DWORD attr = GetFileAttributesW(lpP_addl2wstring(L,
&w->wpath, w->path, -1, w->cp));
if (w->path[0] != '\0' && attr == INVALID_FILE_ATTRIBUTES)
return 0;
if (w->path[0] != '\0' && (attr & FILE_ATTRIBUTE_DIRECTORY) == 0)
return w->state = LP_WALKFILE;
return w->state = LP_WALKIN;
}
static int lpW_in(lua_State *L, lp_Walker *w) {
lp_WalkPart *lst = vec_grow(L, w->parts, 1);
WCHAR *pathend = vec_grow(L, w->wpath, 3);
if (vec_rawlen(w->wpath) && !lp_isdirsep(pathend[-1])) {
vec_push(L, w->wpath, LP_DIRSEP[0]);
vec_push(L, w->path, LP_DIRSEP[0]);
}
memcpy(vec_rawend(w->wpath), L"*", 2 * sizeof(WCHAR));
lst->hFile = FindFirstFileW(w->wpath, &w->wfd);
if (lst->hFile == INVALID_HANDLE_VALUE) return 0;
w->err = ERROR_ALREADY_ASSIGNED;
lst->pos = vec_rawlen(w->wpath);
vec_rawlen(w->parts) += 1;
return 1;
}
static int lpW_out(lua_State *L, lp_Walker *w) {
lp_WalkPart *lst = vec_rawend(w->parts) - 1;
DWORD err = GetLastError();
if (err != ERROR_NO_MORE_FILES)
return lpP_pusherrmsg(L, err, "walkfile", w->path);
FindClose(lst->hFile);
vec_rawlen(w->wpath) = vec_rawlen(w->path) = lst->pos ? lst->pos - 1 : 0;
*vec_rawend(w->path) = (char)(*vec_rawend(w->wpath) = 0);
vec_rawlen(w->parts) -= 1;
return ++w->level, w->state = LP_WALKOUT;
}
static int lpW_file(lua_State *L, lp_Walker *w) {
lp_WalkPart* lst;
size_t len;
if (vec_len(w->parts) == 0) return 0;
lst = vec_rawend(w->parts) - 1;
if (w->err == ERROR_ALREADY_ASSIGNED)
w->err = ERROR_SUCCESS;
else if (!FindNextFileW(vec_rawend(w->parts)[-1].hFile, &w->wfd)) {
w->err = GetLastError();
if (w->err == ERROR_NO_MORE_FILES)
return w->err = ERROR_SUCCESS, LP_WALKOUT;
}
if (w->err != ERROR_SUCCESS) return lp_pusherror(L, "walknext", w->path);
if (wcscmp(w->wfd.cFileName, L"" LP_CURDIR) == 0
|| wcscmp(w->wfd.cFileName, L"" LP_PARDIR) == 0)
return LP_WALKDIR;
vec_rawlen(w->path) = vec_rawlen(w->wpath) = lst->pos;
len = wcslen(w->wfd.cFileName);
lpP_addlw2string(L, &w->path, w->wfd.cFileName, (int)len, w->cp);
vec_extend(L, w->wpath, w->wfd.cFileName, len);
*vec_grow(L, w->wpath, 1) = 0;
return w->wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ?
LP_WALKIN : LP_WALKFILE;
}
/* dir operations */
static LPWSTR lpP_addwstring(lp_State *S, const char *s) {
return lpP_addl2wstring(S->L, &S->wbuf, s,
(s == S->buf ? (int)vec_len(s) : -1), S->cp);
}
static int lpL_getcwd(lua_State *L) {
lp_State *S = lp_getstate(L);
vec_reset(S->buf), vec_reset(S->wbuf);
DWORD wc = GetCurrentDirectoryW(MAX_PATH, vec_grow(L, S->wbuf, MAX_PATH));
if (wc >= MAX_PATH)
wc = GetCurrentDirectoryW(wc + 1, vec_grow(L, S->wbuf, wc + 1));
if (wc == 0) return lp_pusherror(L, "getcwd", NULL);
return lpP_addlw2string(L, &S->buf, S->wbuf, wc, S->cp), lp_pushresult(S);
}
static int lpL_binpath(lua_State *L) {
lp_State *S = lp_getstate(L);
DWORD wc = MAX_PATH, r, err;
while (!(r = GetModuleFileNameW(NULL, vec_grow(S->L, S->wbuf, wc), wc))
|| r == wc) {
if ((err = GetLastError()) == ERROR_SUCCESS)
break;
if (r == 0 || err != ERROR_INSUFFICIENT_BUFFER)
return -lpP_pusherrmsg(L, err, "binpath", NULL);
wc += wc << 1;
if (wc >= (~(DWORD)0 >> 1)) return luaL_error(L, "out of memory");
}
return lpP_addlw2string(L, &S->buf, S->wbuf, r, S->cp), lp_pushresult(S);
}
static int lp_chdir(lp_State *S, const char *s) {
return !SetCurrentDirectoryW(lpP_addwstring(S, s)) ?
lp_pusherror(S->L, "chdir", s) : 0;
}
static int lp_mkdir(lp_State *S, const char *s) {
if (!CreateDirectoryW(lpP_addwstring(S, s), NULL)) {
DWORD err = GetLastError();
if (err != ERROR_ALREADY_EXISTS)
return lpP_pusherrmsg(S->L, err, "mkdir", s);
}
return 0;
}
static int lp_rmdir(lp_State *S, const char *s) {
return !RemoveDirectoryW(lpP_addwstring(S, s)) ?
lp_pusherror(S->L, "rmdir", s) : 0;
}
static int lp_makedirs(lp_State *S, const char *s) {
size_t i, len = strlen(s);
LPWSTR ws = lpP_addl2wstring(S->L, &S->wbuf, s, (int)len, S->cp);
lp_Part drive;
i = (lp_splitdrive(s, &drive), drive.e - s) + 1;
for (; i <= len; ++i) {
while (i < len && !lp_isdirsep(ws[i])) ++i;
ws[i] = 0;
if (!CreateDirectoryW(S->wbuf, NULL)) {
DWORD err = GetLastError();
if (err != ERROR_ALREADY_EXISTS)
return lpP_pusherrmsg(S->L, err, "makedirs", s);
}
if (i != len) ws[i] = LP_DIRSEP[0];
}
return 0;
}
static int lp_removedirs(lp_State *S, lp_Walker *w, int *pcount, void *ud) {
(void)ud;
if (w->state == LP_WALKFILE)
return ++*pcount, DeleteFileW(w->wpath) ?
0 : lp_pusherror(S->L, "remove", w->path);
if (w->state == LP_WALKDIR || w->state == LP_WALKOUT)
return ++*pcount, RemoveDirectoryW(w->wpath) ?
0 : lp_pusherror(S->L, "rmdir", w->path);
return 0;
}
static int lp_unlockdirs(lp_State *S, lp_Walker *w, int *pcount, void *ud) {
(void)ud;
if (w->state == LP_WALKFILE)
return ++*pcount, SetFileAttributesW(w->wpath,
GetFileAttributesW(w->wpath) & ~FILE_ATTRIBUTE_READONLY) ?
0 : lp_pusherror(S->L, "unlock", w->path);
return 0;
}
static int lpL_tmpdir(lua_State* L) {
size_t postfixlen = LP_MAX_TMPCNT + 6;
const char *prefix = luaL_optstring(L, 1, "lua_");
lp_State *S = lp_getstate(L);
DWORD wc = GetTempPathW(MAX_PATH, vec_grow(L, S->wbuf, MAX_PATH));
WCHAR *wbuf;
if (wc > MAX_PATH) wc = GetTempPathW(wc, vec_grow(L, S->wbuf, wc));
if (wc == 0) return -lp_pusherror(L, "tmpdir", NULL);
vec_rawlen(S->wbuf) += wc;
wbuf = vec_grow(L, S->wbuf, postfixlen);
srand(((int)(ptrdiff_t)&L) ^ clock());
if (!lp_isdirsep(wbuf[-1])) vec_push(L, S->wbuf, LP_DIRSEP[0]);
do {
int magic = ((unsigned)rand()<<16|rand()) % LP_MAX_TMPNUM;
swprintf(wbuf, postfixlen, L"%hs%d", prefix, magic);
} while (GetFileAttributesW(S->wbuf) != INVALID_FILE_ATTRIBUTES);
assert(S->wbuf != NULL);
if (!CreateDirectoryW(S->wbuf, NULL))
return -lp_pusherror(L, "tmpdir", lua_tostring(L, -1));
return lpP_addlw2string(L, &S->buf, S->wbuf, -1, S->cp), lp_pushresult(S);
}
/* file operations */
static int lpP_optftime(lua_State *L, int idx, PFILETIME pft) {
ULARGE_INTEGER ln;
if (lua_isnoneornil(L, idx))
return 0;
ln.QuadPart = (ULONGLONG)luaL_checkinteger(L, idx);
pft->dwLowDateTime = ln.LowPart;
pft->dwHighDateTime = ln.HighPart;
return 1;
}
static HANDLE lpP_open(LPCWSTR ws, DWORD dwDesiredAccess, DWORD dwCreationDisposition) {
return CreateFileW(ws, /* file to open */
dwDesiredAccess, /* open for write attributes */
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, /* share for everything */
NULL, /* default security */
dwCreationDisposition, /* existing file only */
FILE_FLAG_BACKUP_SEMANTICS, /* open directory also */
NULL); /* no attr. template */
}
static int lp_exists(lp_State *S, const char *s) {
HANDLE hFile = lpP_open(lpP_addwstring(S, s), 0, OPEN_EXISTING);
int r = hFile != INVALID_HANDLE_VALUE;
return CloseHandle(hFile), lp_bool(S->L, r);
}
static int lp_size(lp_State *S, const char *s) {
WIN32_FILE_ATTRIBUTE_DATA fad;
ULARGE_INTEGER ul;
if (!GetFileAttributesExW(lpP_addwstring(S, s), GetFileExInfoStandard, &fad))
return lp_pusherror(S->L, "size", s);
ul.LowPart = fad.nFileSizeLow;
ul.HighPart = fad.nFileSizeHigh;
return lua_pushinteger(S->L, ul.QuadPart), 1;
}
static int lpP_touch(lua_State *L) {
FILETIME at, mt;
SYSTEMTIME st;
HANDLE *phFile = (HANDLE*)lua_touserdata(L, 1);
const char *s = lua_tostring(L, 2);
lpP_optftime(L, 3, &at);
lpP_optftime(L, 4, &mt);
GetSystemTime(&st);
SystemTimeToFileTime(&st, &mt), at = mt;
return SetFileTime(*phFile, NULL, &at, &mt) ? 0 :
(lp_pusherror(L, "touch", s), lua_error(L));
}
static int lpL_touch(lua_State *L) {
lp_State *S = lp_getstate(L);
int ret;
size_t len;
const char *s = luaL_checklstring(L, 1, &len);
LPCWSTR ws = lpP_addl2wstring(L, &S->wbuf, s, (int)len, S->cp);
HANDLE hFile = lpP_open(ws, FILE_WRITE_ATTRIBUTES, OPEN_ALWAYS);
if (hFile == INVALID_HANDLE_VALUE)
return -lp_pusherror(S->L, "open", s);
lua_settop(L, 3);
lua_pushcfunction(L, lpP_touch);
lua_pushlightuserdata(L, &hFile);
lua_pushvalue(L, 1);
lua_pushvalue(L, 2);
lua_pushvalue(L, 3);
ret = lua_pcall(L, 4, 0, 0);
CloseHandle(hFile);
return ret == LUA_OK ? lp_bool(L, 1) :
(lua_pushnil(L), lua_insert(L, -2), 2);
}
static int lp_remove(lp_State *S, const char *s) {
return DeleteFileW(lpP_addwstring(S, s)) ? 0 :
lp_pusherror(S->L, "remove", s);
}
static int lpL_rename(lua_State *L) {
lp_State *S = lp_getstate(L);
size_t flen, tlen;
const char *from = luaL_checklstring(L, 1, &flen);
const char *to = luaL_checklstring(L, 2, &tlen);
LPWSTR wto = (lpP_addl2wstring(L, &S->wbuf, from, (int)flen+1, S->cp),
lpP_addl2wstring(L, &S->wbuf, to, (int)tlen, S->cp));
return MoveFileW(S->wbuf, wto) ? lp_bool(L, 1) :
-lp_pusherror(L, "rename", to);
}
static int lpL_copy(lua_State *L) {
lp_State *S = lp_getstate(L);
size_t flen, tlen;
const char *from = luaL_checklstring(L, 1, &flen);
const char *to = luaL_checklstring(L, 2, &tlen);
int failIfExists = lua_toboolean(L, 3);
LPWSTR wto = (lpP_addl2wstring(L, &S->wbuf, from, (int)flen+1, S->cp),
lpP_addl2wstring(L, &S->wbuf, to, (int)tlen, S->cp));
return CopyFileW(S->wbuf, wto, failIfExists) ? lp_bool(L, 1) :
-lp_pusherror(L, "copy", to);
}
static DWORD lp_CreateSymbolicLinkW(lua_State *L, LPCWSTR lpSymlinkFileName, LPCWSTR lpTargetFileName, DWORD dwFlags) {
typedef BOOLEAN APIENTRY F(LPCWSTR lpSymlinkFileName, LPCWSTR lpTargetFileName, DWORD dwFlags);
static F* f;
if (!f) {
HMODULE hModule = GetModuleHandleA("KERNEL32.dll");
if (hModule != NULL) {
union { F *f; FARPROC v; } u;
u.v = GetProcAddress(hModule, "CreateSymbolicLinkW");
f = u.f;
}
if (!f) return luaL_error(L, "CreateSymbolicLinkW not implemented");
}
return f(lpSymlinkFileName, lpTargetFileName, dwFlags);
}
static int lpL_symlink(lua_State *L) {
lp_State *S = lp_getstate(L);
size_t flen, tlen;
const char *from = luaL_checklstring(L, 1, &flen);
const char *to = luaL_checklstring(L, 2, &tlen);
int dir = lua_toboolean(L, 3) ? /*SYMBOLIC_LINK_FLAG_DIRECTORY=*/1 : 0;
LPWSTR wto = (lpP_addl2wstring(L, &S->wbuf, from, (int)flen+1, S->cp),
lpP_addl2wstring(L, &S->wbuf, to, (int)tlen, S->cp));
return lp_CreateSymbolicLinkW(L, wto, S->wbuf, dir) ? lp_bool(L, 1) :
-lp_pusherror(L, "copy", to);
}
/* path informations */
static int lp_abs(lp_State *S, const char *s) {
LPWSTR ws = (lpP_addwstring(S, s),
vec_push(S->L, S->wbuf, 0),
vec_grow(S->L, S->wbuf, MAX_PATH));
DWORD wc = GetFullPathNameW(S->wbuf, MAX_PATH, ws, NULL);
if (wc >= MAX_PATH) {
ws = vec_grow(S->L, S->wbuf, wc + 1);
wc = GetFullPathNameW(S->wbuf, wc, ws, NULL);
}
if (wc == 0) return lp_pusherror(S->L, "abs", s);
vec_reset(S->buf), lpP_addlw2string(S->L, &S->buf, ws, wc, S->cp);
return lp_pushresult(S);
}
#define lpP_isattr(N,ATTR) do { \
DWORD attr = GetFileAttributesW(lpP_addwstring(S, s)); \
return (attr != INVALID_FILE_ATTRIBUTES \
&& N(attr&FILE_ATTRIBUTE_##ATTR))?0:lp_bool(S->L,0); } while (0)
static int lp_isdir(lp_State *S, const char *s) {lpP_isattr(,DIRECTORY); }
static int lp_islink(lp_State *S, const char *s) {lpP_isattr(,REPARSE_POINT);}
static int lp_isfile(lp_State *S, const char *s) {lpP_isattr(!,DIRECTORY); }
static int lpP_ismount(lp_State *S, const char *s) {
int wc, len = (int)vec_len(S->pr.parts);
int noparts = (len == 1 || (len == 2 && lp_len(S->pr.parts[1]) == 0));
LPWSTR ws;
if (len < 1) return 0;
if (lp_len(S->pr.parts[0]) && lp_isdirsep(*S->pr.parts[0].s))
return (S->pr.dots < 0 && noparts);
if (S->pr.dots < 0 && noparts) return 1;
ws = (lpP_addwstring(S, s),
wc = vec_len(S->wbuf),
vec_push(S->L, S->wbuf, 0),
vec_grow(S->L, S->wbuf, MAX_PATH));
if (!GetVolumePathNameW(S->wbuf, ws, MAX_PATH)) return 0;
if (lp_isdirsep(S->wbuf[wc-1])) S->wbuf[wc-1] = 0;
if (wc = (int)wcslen(ws), lp_isdirsep(ws[wc-1])) ws[wc-1] = 0;
return wcscmp(S->wbuf, ws) == 0;
}
static int lp_ismount(lp_State *S, const char *s) {
int ret;
if ((ret = lp_abs(S, s)) != 1) return ret;
lp_joinparts(S->L, s = lua_tostring(S->L, -1), &lp_resetstate(S)->pr);
return lpP_ismount(S, s) ? 0 : lp_bool(S->L, 0);
}
#define lp_time(ty, field) do { \
LPWSTR ws = lpP_addwstring(S, s); \
WIN32_FILE_ATTRIBUTE_DATA fad; \
if (!GetFileAttributesExW(ws, GetFileExInfoStandard, &fad)) \
return lp_pusherror(S->L, #ty "time", s); \
return lpP_pushtime(S->L, &fad.ft##field); } while (0)
static int lpP_pushtime(lua_State *L, const FILETIME *pft) {
ULARGE_INTEGER ln;
ln.LowPart = pft->dwLowDateTime;
ln.HighPart = pft->dwHighDateTime;
return lua_pushinteger(L, (lua_Integer)ln.QuadPart), 1;
}
static int lp_ctime(lp_State *S, const char *s) {lp_time(c, CreationTime); }
static int lp_mtime(lp_State *S, const char *s) {lp_time(m, LastWriteTime); }
static int lp_atime(lp_State *S, const char *s) {lp_time(a, LastAccessTime);}
static DWORD lp_GetFinalPathNameByHandleW(lua_State *L, HANDLE hFile, LPWSTR lpszFilePath, DWORD cchFilePath, DWORD dwFlags) {
typedef DWORD WINAPI F(HANDLE hFile, LPWSTR lpszFilePath, DWORD cchFilePath, DWORD dwFlags);
static F* f;
if (!f) {
HMODULE hModule = GetModuleHandleA("KERNEL32.dll");
if (hModule != NULL) {
union { F *f; FARPROC v; } u;
u.v = GetProcAddress(hModule, "GetFinalPathNameByHandleW");
f = u.f;
}
if (!f) return luaL_error(L, "GetFinalPathNameByHandleW not implemented");
}
return f(hFile, lpszFilePath, cchFilePath, dwFlags);
}
static int lpP_realpath(lua_State *L) {
lp_State *S = (lp_State*)lua_touserdata(L, 1);
HANDLE *phFile = (HANDLE*)lua_touserdata(L, 2);
LPWSTR ret = vec_grow(S->L, S->wbuf, MAX_PATH);
DWORD wc = lp_GetFinalPathNameByHandleW(S->L, *phFile, ret, MAX_PATH, 0);
if (wc >= MAX_PATH) {
ret = vec_grow(S->L, S->wbuf, wc);
wc = lp_GetFinalPathNameByHandleW(S->L, *phFile, ret, wc, 0);
}
if (wc == 0) return lp_pusherror(S->L, "resolve", S->buf), lua_error(L);
if (wc <= MAX_PATH + 4) ret += 4, wc -= 4;
vec_reset(S->buf), lpP_addlw2string(S->L, &S->buf, ret, wc, S->cp);
return lp_pushresult(S);
}
static int lp_realpath(lp_State *S, const char *s) {
int ret;
HANDLE hFile = lpP_open(lpP_addwstring(S, s), 0, OPEN_EXISTING);
lua_pushcfunction(S->L, lpP_realpath);
lua_pushlightuserdata(S->L, S);
lua_pushlightuserdata(S->L, &hFile);
ret = lua_pcall(S->L, 2, 1, 0);
CloseHandle(hFile);
return ret == LUA_OK ? 1 : (lua_pushnil(S->L), lua_insert(S->L, -2), 2);
}
/* utils */
static int lp_readreg(lp_State *S, HKEY hkey, LPCWSTR key) {
DWORD wc = MAX_PATH, ret;
LPWSTR ws = (vec_reset(S->wbuf), vec_grow(S->L, S->wbuf, wc));
while ((ret = RegQueryValueExW(hkey, key, NULL, NULL, (LPBYTE)ws, &wc))
!= ERROR_SUCCESS) {
if (ret != ERROR_MORE_DATA) {
lua_pushstring(S->L,
lpP_addlw2string(S->L, &S->buf, key, -1, S->cp));
return lpP_pusherrmsg(S->L, ret, "uname", lua_tostring(S->L, -1));
}
ws = vec_grow(S->L, S->wbuf, wc);
}
vec_rawlen(S->wbuf) = wc;
*vec_grow(S->L, S->wbuf, 1) = 0;
return 0;
}