-
Notifications
You must be signed in to change notification settings - Fork 0
/
nobuild.h
1746 lines (1458 loc) · 47.4 KB
/
nobuild.h
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
#ifndef NOBUILD_H_
#define NOBUILD_H_
#if defined(__GNUC__) || (defined(__clang__) && !defined(_MSC_VER))
# define NOBUILD__DEPRECATED(func) __attribute__ ((deprecated)) func
#elif defined(_MSC_VER)
# define NOBUILD__DEPRECATED(func) __declspec (deprecated) func
#endif
#ifndef _WIN32
# define _POSIX_C_SOURCE 200809L
# include <sys/types.h>
# include <sys/wait.h>
# include <sys/stat.h>
# include <unistd.h>
# include <dirent.h>
# include <fcntl.h>
# define PATH_SEP "/"
typedef pid_t Pid;
typedef int Fd;
#else
# define WIN32_MEAN_AND_LEAN
# include <windows.h>
# include <process.h>
# include <direct.h>
# define PATH_SEP "\\"
typedef HANDLE Pid;
typedef HANDLE Fd;
// minirent.h HEADER BEGIN ////////////////////////////////////////
// Copyright 2021 Alexey Kutepov <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// ============================================================
//
// minirent — 0.0.1 — A subset of dirent interface for Windows.
//
// https://github.com/tsoding/minirent
//
// ============================================================
//
// ChangeLog (https://semver.org/ is implied)
//
// 0.0.1 First Official Release
#ifndef MINIRENT_H_
#define MINIRENT_H_
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
struct dirent {
char d_name[MAX_PATH+1];
};
typedef struct DIR DIR;
DIR *opendir(const char *dirpath);
struct dirent *readdir(DIR *dirp);
int closedir(DIR *dirp);
#endif // MINIRENT_H_
// minirent.h HEADER END ////////////////////////////////////////
// TODO(#28): use GetLastErrorAsString everywhere on Windows error reporting
LPSTR GetLastErrorAsString(void);
#endif // _WIN32
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#if defined(__GNUC__) || defined(__clang__)
// https://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Function-Attributes.html
# define NOBUILD_PRINTF_FORMAT(STRING_INDEX, FIRST_TO_CHECK) __attribute__ ((format (printf, STRING_INDEX, FIRST_TO_CHECK)))
#else
# define NOBUILD_PRINTF_FORMAT(STRING_INDEX, FIRST_TO_CHECK)
#endif
#define FOREACH_ARRAY(type, elem, array, body) \
for (size_t elem_##index = 0; \
elem_##index < array.count; \
++elem_##index) \
{ \
type *elem = &array.elems[elem_##index]; \
body; \
}
typedef const char * Cstr;
int cstr_ends_with(Cstr cstr, Cstr postfix);
#define ENDS_WITH(cstr, postfix) cstr_ends_with(cstr, postfix)
int cstr_starts_with(Cstr cstr, Cstr prefix);
#define STARTS_WITH(cstr, prefix) cstr_starts_with(cstr, prefix)
NOBUILD__DEPRECATED(Cstr cstr_no_ext(Cstr path));
typedef struct {
Cstr *elems;
size_t count;
size_t capacity;
} Cstr_Array;
Cstr_Array cstr_array_make(Cstr first, ...);
#define CSTR_ARRAY_MAKE(first, ...) cstr_array_make(first, ##__VA_ARGS__, NULL)
Cstr_Array cstr_array_append(Cstr_Array cstrs, Cstr cstr);
Cstr cstr_array_remove(Cstr_Array *cstrs, Cstr cstr);
Cstr_Array cstr_array_concat(Cstr_Array cstrs_a, Cstr_Array cstrs_b);
Cstr_Array cstr_array_from_cstr(Cstr cstr, Cstr delim);
#define SPLIT(cstr, delim) cstr_array_from_cstr(cstr, delim)
Cstr cstr_array_join(Cstr sep, Cstr_Array cstrs);
#define JOIN(sep, ...) cstr_array_join(sep, cstr_array_make(__VA_ARGS__, NULL))
#define CONCAT(...) JOIN("", __VA_ARGS__)
#define PATH(...) JOIN(PATH_SEP, __VA_ARGS__)
typedef struct {
Fd read;
Fd write;
} Pipe;
Pipe pipe_make(void);
typedef struct {
Cstr_Array line;
} Cmd;
Fd fd_open_for_read(Cstr path);
Fd fd_open_for_write(Cstr path);
size_t fd_read(Fd fd, void *buf, size_t count);
size_t fd_write(Fd fd, void *buf, size_t count);
int fd_printf(Fd fd, Cstr fmt, ...) NOBUILD_PRINTF_FORMAT(2, 3);
void fd_close(Fd fd);
void pid_wait(Pid pid);
Cstr cmd_show(Cmd cmd);
Pid cmd_run_async(Cmd cmd, Fd *fdin, Fd *fdout);
void cmd_run_sync(Cmd cmd);
typedef struct {
Cmd *elems;
size_t count;
} Cmd_Array;
// TODO(#1): no way to disable echo in nobuild scripts
// TODO(#2): no way to ignore fails
#define CMD(...) \
do { \
Cmd cmd = { \
.line = cstr_array_make(__VA_ARGS__, NULL) \
}; \
INFO("CMD: %s", cmd_show(cmd)); \
cmd_run_sync(cmd); \
} while (0)
typedef enum {
CHAIN_TOKEN_END = 0,
CHAIN_TOKEN_IN,
CHAIN_TOKEN_OUT,
CHAIN_TOKEN_CMD
} Chain_Token_Type;
// A single token for the CHAIN(...) DSL syntax
typedef struct {
Chain_Token_Type type;
Cstr_Array args;
} Chain_Token;
#ifndef _WIN32
Chain_Token_Type __attribute__((deprecated)) IN_is_deprecated_use_CHAIN_IN_instead(Chain_Token_Type t) { return t; }
Chain_Token_Type __attribute__((deprecated)) OLD_is_deprecated_use_CHAIN_OLD_instead(Chain_Token_Type t) { return t; }
#else
Chain_Token_Type __declspec(deprecated("IN is already defined by WinAPI, use `CHAIN_IN` instead.")) IN_is_deprecated_use_CHAIN_IN_instead(Chain_Token_Type t) { return t; }
Chain_Token_Type __declspec(deprecated("OUT is already defined by WinAPI, use `CHAIN_OUT` instead.")) OLD_is_deprecated_use_CHAIN_OLD_instead(Chain_Token_Type t) { return t; }
#endif
// TODO(#17): IN and OUT are already taken by WinAPI
#define IN(path) \
(Chain_Token) { \
.type = IN_is_deprecated_use_CHAIN_IN_instead(CHAIN_TOKEN_IN), \
.args = cstr_array_make(path, NULL) \
}
#define OUT(path) \
(Chain_Token) { \
.type = OLD_is_deprecated_use_CHAIN_OLD_instead(CHAIN_TOKEN_OUT), \
.args = cstr_array_make(path, NULL) \
}
#define CHAIN_IN(path) \
(Chain_Token) { \
.type = CHAIN_TOKEN_IN, \
.args = cstr_array_make(path, NULL) \
}
#define CHAIN_OUT(path) \
(Chain_Token) { \
.type = CHAIN_TOKEN_OUT, \
.args = cstr_array_make(path, NULL) \
}
#define CHAIN_CMD(...) \
(Chain_Token) { \
.type = CHAIN_TOKEN_CMD, \
.args = cstr_array_make(__VA_ARGS__, NULL) \
}
// TODO(#20): pipes do not allow redirecting stderr
typedef struct {
Cstr input_filepath;
Cmd_Array cmds;
Cstr output_filepath;
} Chain;
Chain chain_build_from_tokens(Chain_Token first, ...);
void chain_run_sync(Chain chain);
void chain_echo(Chain chain);
// TODO(#15): PIPE does not report where exactly a syntactic error has happened
#define CHAIN(...) \
do { \
Chain chain = chain_build_from_tokens(__VA_ARGS__, (Chain_Token) {0}); \
chain_echo(chain); \
chain_run_sync(chain); \
} while(0)
#ifndef REBUILD_URSELF
# if _WIN32
# if defined(__GNUC__)
# define REBUILD_URSELF(binary_path, source_path) CMD("gcc", "-o", binary_path, source_path)
# elif defined(__clang__)
# define REBUILD_URSELF(binary_path, source_path) CMD("clang", "-o", binary_path, source_path)
# elif defined(_MSC_VER)
# define REBUILD_URSELF(binary_path, source_path) CMD("cl.exe", source_path)
# endif
# else
# define REBUILD_URSELF(binary_path, source_path) CMD("cc", "-o", binary_path, source_path)
# endif
#endif
// Go Rebuild Urself™ Technology
//
// How to use it:
// int main(int argc, char** argv) {
// GO_REBUILD_URSELF(argc, argv);
// // actual work
// return 0;
// }
//
// After your added this macro every time you run ./nobuild it will detect
// that you modified its original source code and will try to rebuild itself
// before doing any actual work. So you only need to bootstrap your build system
// once.
//
// The modification is detected by comparing the last modified times of the executable
// and its source code. The same way the make utility usually does it.
//
// The rebuilding is done by using the REBUILD_URSELF macro which you can redefine
// if you need a special way of bootstraping your build system. (which I personally
// do not recommend since the whole idea of nobuild is to keep the process of bootstrapping
// as simple as possible and doing all of the actual work inside of the nobuild)
//
#define GO_REBUILD_URSELF(argc, argv) \
do { \
const char *source_path = __FILE__; \
assert(argc >= 1); \
const char *binary_path = argv[0]; \
\
if (is_path1_modified_after_path2(source_path, binary_path)) { \
RENAME(binary_path, CONCAT(binary_path, ".old")); \
REBUILD_URSELF(binary_path, source_path); \
Cmd cmd = { \
.line = { \
.elems = (Cstr*) argv, \
.count = (size_t) argc, \
}, \
}; \
INFO("CMD: %s", cmd_show(cmd)); \
cmd_run_sync(cmd); \
exit(0); \
} \
} while(0)
// The implementation idea is stolen from https://github.com/zhiayang/nabs
void rebuild_urself(const char *binary_path, const char *source_path);
Cstr path_no_ext(Cstr path);
#define NOEXT(path) path_no_ext(path)
int is_path1_modified_after_path2(Cstr path1, Cstr path2);
#define IS_NEWER(path1, path2) is_path1_modified_after_path2(path1, path2)
Cstr path_dirname(Cstr path);
#define DIRNAME(path) path_dirname(path)
Cstr path_basename(Cstr path);
#define BASENAME(path) path_basename(path)
int path_is_dir(Cstr path);
#define IS_DIR(path) path_is_dir(path)
int path_is_file(Cstr path);
#define IS_FILE(path) path_is_file(path)
int path_exists(Cstr path);
#define PATH_EXISTS(path) path_exists(path)
void path_mkdirs(Cstr_Array path);
#define MKDIRS(...) \
do { \
Cstr_Array path = cstr_array_make(__VA_ARGS__, NULL); \
INFO("MKDIRS: %s", cstr_array_join(PATH_SEP, path)); \
path_mkdirs(path); \
} while (0)
void path_rename(Cstr old_path, Cstr new_path);
#define RENAME(old_path, new_path) \
do { \
INFO("RENAME: %s -> %s", old_path, new_path); \
path_rename(old_path, new_path); \
} while (0)
void path_copy(Cstr old_path, Cstr new_path);
#define COPY(old_path, new_path) \
do { \
INFO("COPY: %s -> %s", old_path, new_path); \
path_copy(old_path, new_path); \
} while(0)
void path_rm(Cstr path);
#define RM(path) \
do { \
INFO("RM: %s", path); \
path_rm(path); \
} while(0)
#define FOREACH_FILE_IN_DIR(file, dirpath, body) \
do { \
struct dirent *dp = NULL; \
DIR *dir = opendir(dirpath); \
if (dir == NULL) { \
PANIC("could not open directory %s: %s", \
dirpath, nobuild__strerror(errno)); \
} \
errno = 0; \
while ((dp = readdir(dir))) { \
const char *file = dp->d_name; \
body; \
} \
\
if (errno > 0) { \
PANIC("could not read directory %s: %s", \
dirpath, nobuild__strerror(errno)); \
} \
\
closedir(dir); \
} while(0)
NOBUILD__DEPRECATED(void VLOG(FILE *stream, Cstr tag, Cstr fmt, va_list args));
typedef enum LogLevels {
LOG_LEVELS_TODO,
LOG_LEVELS_INFO,
LOG_LEVELS_WARN,
LOG_LEVELS_ERRO,
} LogLevels;
LogLevels logLevel = LOG_LEVELS_TODO;
void info(Cstr fmt, ...) NOBUILD_PRINTF_FORMAT(1, 2);
#define INFO(fmt, ...) info("%s:%d: " fmt, __func__, __LINE__, ##__VA_ARGS__)
void warn(Cstr fmt, ...) NOBUILD_PRINTF_FORMAT(1, 2);
#define WARN(fmt, ...) warn("%s:%d: " fmt, __func__, __LINE__, ##__VA_ARGS__)
void erro(Cstr fmt, ...) NOBUILD_PRINTF_FORMAT(1, 2);
#define ERRO(fmt, ...) erro("%s:%d: " fmt, __func__, __LINE__, ##__VA_ARGS__)
void panic(Cstr fmt, ...) NOBUILD_PRINTF_FORMAT(1, 2);
#define PANIC(fmt, ...) panic("%s:%d: " fmt, __func__, __LINE__, ##__VA_ARGS__)
void todo(Cstr fmt, ...) NOBUILD_PRINTF_FORMAT(1, 2);
#define TODO(fmt, ...) todo("%s:%d: " fmt, __func__, __LINE__, ##__VA_ARGS__)
void todo_safe(Cstr fmt, ...) NOBUILD_PRINTF_FORMAT(1, 2);
#define TODO_SAFE(fmt, ...) todo_safe("%s:%d: " fmt, __func__, __LINE__, ##__VA_ARGS__)
char *shift_args(int *argc, char ***argv);
void file_to_c_array(Cstr path, Cstr out_path, Cstr array_type, Cstr array_name, int null_term);
#define FILE_TO_C_ARRAY(path, out_path, array_name) file_to_c_array(path, out_path, "unsigned char", array_name, 1)
#endif // NOBUILD_H_
////////////////////////////////////////////////////////////////////////////////
#ifdef NOBUILD_IMPLEMENTATION
#ifndef NOBUILD_I_
#define NOBUILD_I_
#ifdef _WIN32
LPSTR GetLastErrorAsString(void)
{
// https://stackoverflow.com/questions/1387064/how-to-get-the-error-message-from-the-error-code-returned-by-getlasterror
DWORD errorMessageId = GetLastError();
assert(errorMessageId != 0);
LPSTR messageBuffer = NULL;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, // DWORD dwFlags,
NULL, // LPCVOID lpSource,
errorMessageId, // DWORD dwMessageId,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // DWORD dwLanguageId,
(LPSTR) &messageBuffer, // LPTSTR lpBuffer,
0, // DWORD nSize,
NULL // va_list *Arguments
);
return messageBuffer;
}
// minirent.h IMPLEMENTATION BEGIN ////////////////////////////////////////
struct DIR {
HANDLE hFind;
WIN32_FIND_DATA data;
struct dirent *dirent;
};
DIR *opendir(const char *dirpath)
{
assert(dirpath);
char buffer[MAX_PATH];
snprintf(buffer, MAX_PATH, "%s\\*", dirpath);
DIR *dir = (DIR*)calloc(1, sizeof(DIR));
dir->hFind = FindFirstFile(buffer, &dir->data);
if (dir->hFind == INVALID_HANDLE_VALUE) {
errno = ENOSYS;
goto fail;
}
return dir;
fail:
if (dir) {
free(dir);
}
return NULL;
}
struct dirent *readdir(DIR *dirp)
{
assert(dirp);
if (dirp->dirent == NULL) {
dirp->dirent = (struct dirent*)calloc(1, sizeof(struct dirent));
} else {
if(!FindNextFile(dirp->hFind, &dirp->data)) {
if (GetLastError() != ERROR_NO_MORE_FILES) {
errno = ENOSYS;
}
return NULL;
}
}
memset(dirp->dirent->d_name, 0, sizeof(dirp->dirent->d_name));
strncpy_s(
dirp->dirent->d_name,
sizeof(dirp->dirent->d_name),
dirp->data.cFileName,
sizeof(dirp->dirent->d_name) - 1);
return dirp->dirent;
}
int closedir(DIR *dirp)
{
assert(dirp);
if(!FindClose(dirp->hFind)) {
errno = ENOSYS;
return -1;
}
if (dirp->dirent) {
free(dirp->dirent);
}
free(dirp);
return 0;
}
// minirent.h IMPLEMENTATION END ////////////////////////////////////////
#endif // _WIN32
Cstr nobuild__strerror(int errnum)
{
#ifndef _WIN32
return strerror(errnum);
#else
static char buffer[1024];
strerror_s(buffer, 1024, errnum);
return buffer;
#endif
}
Cstr_Array cstr_array_append(Cstr_Array cstrs, Cstr cstr)
{
if (cstrs.capacity < 1) {
cstrs.elems = realloc(cstrs.elems, sizeof *cstrs.elems * (cstrs.count + 10));
cstrs.capacity += 10;
if (cstrs.elems == NULL) {
PANIC("Could not allocate memory: %s", nobuild__strerror(errno));
}
}
cstrs.elems[cstrs.count++] = cstr;
cstrs.capacity--;
return cstrs;
}
Cstr cstr_array_remove(Cstr_Array *cstrs, Cstr cstr)
{
if (cstrs->count == 0) {
return NULL;
}
if (cstr == NULL) {
cstrs->capacity++;
return cstrs->elems[--cstrs->count];
}
// Find the index of the element to be removed
const size_t cstr_len = strlen(cstr);
for (size_t i = 0; i < cstrs->count; i++) {
const size_t elem_len = strlen(cstrs->elems[i]);
if (elem_len != cstr_len || strcmp(cstrs->elems[i], cstr) != 0) {
continue;
}
// Shift elements left if found the cstr
Cstr ret = cstrs->elems[i];
for (size_t j = i; j < cstrs->count - 1; j++) {
cstrs->elems[j] = cstrs->elems[j + 1];
}
cstrs->count--;
cstrs->capacity++;
// TODO: Might want to realloc array if capacity is too high
return ret;
}
// The string was not found
return NULL;
}
Cstr_Array cstr_array_concat(Cstr_Array cstrs_a, Cstr_Array cstrs_b)
{
if (cstrs_a.capacity < cstrs_b.count) {
cstrs_a.elems = realloc(cstrs_a.elems, sizeof *cstrs_a.elems * (cstrs_a.count + cstrs_b.count));
cstrs_a.capacity += cstrs_b.count;
if (cstrs_a.elems == NULL) {
PANIC("Could not allocate memory: %s", nobuild__strerror(errno));
}
}
memcpy(cstrs_a.elems + cstrs_a.count, cstrs_b.elems, sizeof *cstrs_a.elems * cstrs_b.count);
cstrs_a.count += cstrs_b.count;
cstrs_a.capacity -= cstrs_b.count;
return cstrs_a;
}
int cstr_ends_with(Cstr cstr, Cstr postfix)
{
const size_t cstr_len = strlen(cstr);
const size_t postfix_len = strlen(postfix);
return postfix_len <= cstr_len
&& strcmp(cstr + cstr_len - postfix_len, postfix) == 0;
}
int cstr_starts_with(Cstr cstr, Cstr prefix)
{
const size_t cstr_len = strlen(cstr);
const size_t prefix_len = strlen(prefix);
return prefix_len <= cstr_len && strncmp(cstr, prefix, prefix_len) == 0;
}
Cstr cstr_no_ext(Cstr path)
{
WARN("This function is deprecated. Use `path_no_ext` instead");
return path_no_ext(path);
}
Cstr_Array cstr_array_make(Cstr first, ...)
{
Cstr_Array result = {0};
if (first == NULL) {
return result;
}
result.count += 1;
va_list args;
va_start(args, first);
for (Cstr next = va_arg(args, Cstr);
next != NULL;
next = va_arg(args, Cstr)) {
result.count += 1;
}
va_end(args);
result.elems = malloc(sizeof *result.elems * result.count);
if (result.elems == NULL) {
PANIC("could not allocate memory: %s", nobuild__strerror(errno));
}
result.count = 0;
result.elems[result.count++] = first;
va_start(args, first);
for (Cstr next = va_arg(args, Cstr);
next != NULL;
next = va_arg(args, Cstr)) {
result.elems[result.count++] = next;
}
va_end(args);
return result;
}
Cstr_Array cstr_array_from_cstr(Cstr cstr, Cstr delim)
{
size_t len = strlen(cstr);
size_t d_len = strlen(delim);
size_t substr_count = 1;
for (size_t i = 0; i < len; ++i) {
if ((len - i) < d_len) {
break;
}
size_t delim_found = 0;
for (size_t j = 0; j < d_len; ++j) {
if (cstr[i+j] != delim[j]) {
delim_found = 0;
break;
}
delim_found = 1;
}
if (delim_found) {
substr_count++;
i += d_len - 1;
}
}
// if dlen == 0 or was never found
if (substr_count == 1) {
// TODO: differentiate between delim == null and delim == "" and delim not found
// Split the string into an array of strings, where each string is a single character
return cstr_array_make(cstr, NULL);
}
Cstr_Array ret = { .count = substr_count };
ret.elems = malloc(sizeof(Cstr) * ret.count);
if (ret.elems == NULL) {
PANIC("Could not allocate memory: %s", nobuild__strerror(errno));
}
size_t substr_start = 0;
size_t substr_index = 0;
for (size_t i = 0; i < len; ++i) {
if ((len - i) < d_len) {
break;
}
size_t delim_found = 0;
for (size_t j = 0; j < d_len; ++j) {
if (cstr[i+j] != delim[j]) {
delim_found = 0;
break;
}
delim_found = 1;
}
if (!delim_found) {
continue;
}
size_t substr_len = i - substr_start;
char *substr = calloc(substr_len + 1, sizeof(unsigned char));
if (substr == NULL) {
PANIC("Could not allocate memory: %s", nobuild__strerror(errno));
}
ret.elems[substr_index++] = memcpy(substr, (cstr+substr_start), substr_len * sizeof(unsigned char));
i += d_len - 1;
substr_start = i + 1;
}
// Add the last substring
size_t substr_len = len - substr_start;
char *substr = malloc(substr_len * sizeof(unsigned char));
if (substr == NULL) {
PANIC("Could not allocate memory: %s", nobuild__strerror(errno));
}
ret.elems[substr_index++] = memcpy(substr, (cstr+substr_start), substr_len * sizeof(unsigned char));
return ret;
}
Cstr cstr_array_join(Cstr sep, Cstr_Array cstrs)
{
if (cstrs.count == 0) {
return "";
}
const size_t sep_len = strlen(sep);
size_t len = 0;
for (size_t i = 0; i < cstrs.count; ++i) {
len += strlen(cstrs.elems[i]);
}
const size_t result_len = (cstrs.count - 1) * sep_len + len + 1;
char *result = malloc(sizeof(char) * result_len);
if (result == NULL) {
PANIC("could not allocate memory: %s", nobuild__strerror(errno));
}
len = 0;
for (size_t i = 0; i < cstrs.count; ++i) {
if (i > 0) {
memcpy(result + len, sep, sep_len);
len += sep_len;
}
size_t elem_len = strlen(cstrs.elems[i]);
memcpy(result + len, cstrs.elems[i], elem_len);
len += elem_len;
}
result[len] = '\0';
return result;
}
Pipe pipe_make(void)
{
Pipe pip = {0};
#ifdef _WIN32
// https://docs.microsoft.com/en-us/windows/win32/ProcThread/creating-a-child-process-with-redirected-input-and-output
SECURITY_ATTRIBUTES saAttr = {0};
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
if (!CreatePipe(&pip.read, &pip.write, &saAttr, 0)) {
PANIC("Could not create pipe: %s", GetLastErrorAsString());
}
#else
Fd pipefd[2];
if (pipe(pipefd) < 0) {
PANIC("Could not create pipe: %s", nobuild__strerror(errno));
}
pip.read = pipefd[0];
pip.write = pipefd[1];
#endif // _WIN32
return pip;
}
Fd fd_open_for_read(Cstr path)
{
#ifndef _WIN32
Fd result = open(path, O_RDONLY);
if (result < 0) {
PANIC("Could not open file %s: %s", path, nobuild__strerror(errno));
}
return result;
#else
// https://docs.microsoft.com/en-us/windows/win32/fileio/opening-a-file-for-reading-or-writing
SECURITY_ATTRIBUTES saAttr = {0};
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
Fd result = CreateFile(
path,
GENERIC_READ,
0,
&saAttr,
OPEN_EXISTING,
FILE_ATTRIBUTE_READONLY,
NULL);
if (result == INVALID_HANDLE_VALUE) {
PANIC("Could not open file %s", path);
}
return result;
#endif // _WIN32
}
Fd fd_open_for_write(Cstr path)
{
#ifndef _WIN32
Fd result = open(path,
O_WRONLY | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (result < 0) {
PANIC("could not open file %s: %s", path, nobuild__strerror(errno));
}
return result;
#else
SECURITY_ATTRIBUTES saAttr = {0};
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
Fd result = CreateFile(
path, // name of the write
GENERIC_WRITE, // open for writing
0, // do not share
&saAttr, // default security
CREATE_NEW, // create new file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL // no attr. template
);
if (result == INVALID_HANDLE_VALUE) {
PANIC("Could not open file %s: %s", path, GetLastErrorAsString());
}
return result;
#endif // _WIN32
}
size_t fd_read(Fd fd, void *buf, size_t count)
{
#ifndef _WIN32
ssize_t bytes = read(fd, buf, count);
if (bytes == -1) {
ERRO("Read error: %s", strerror(errno));
return 0;
}
#else
DWORD bytes;
if (!ReadFile(fd, buf, (DWORD) count, &bytes, NULL)) {
ERRO("Read error: %s", GetLastErrorAsString());
return 0;
}
#endif
return (size_t) bytes;
}
size_t fd_write(Fd fd, void *buf, size_t count)
{
#ifndef _WIN32
ssize_t bytes = write(fd, buf, (size_t) count);
if (bytes == -1) {
ERRO("Write error: %s", strerror(errno));
return 0;
}
#else
DWORD bytes;
if (!WriteFile(fd, buf, (DWORD) count, &bytes, NULL)) {
ERRO("Write error: %s", GetLastErrorAsString());
return 0;
}
#endif
return (size_t) bytes;
}
int fd_printf(Fd fd, Cstr fmt, ...) {
va_list args;
va_start(args, fmt);
int len = vsnprintf(NULL, 0, fmt, args);
va_end(args);
if (len < 0) {
return len;
}
// MSVC does not support variable length arrays
#ifndef _WIN32
char buffer[len+1];
#else
char *buffer = malloc(sizeof *buffer * (len+1));
#endif
va_start(args, fmt);
int result = vsnprintf(buffer, (size_t)(len + 1), fmt, args);
va_end(args);
if (result < 0) {
return result;
}
fd_write(fd, buffer, (size_t) result);
#ifdef _WIN32
free(buffer);
#endif
return result;
}
void fd_close(Fd fd)
{
#ifdef _WIN32
CloseHandle(fd);
#else
close(fd);
#endif // _WIN32
}
void pid_wait(Pid pid)
{
#ifdef _WIN32
DWORD result = WaitForSingleObject(
pid, // HANDLE hHandle,
INFINITE // DWORD dwMilliseconds
);
if (result == WAIT_FAILED) {
PANIC("could not wait on child process: %s", GetLastErrorAsString());
}
DWORD exit_status;
if (GetExitCodeProcess(pid, &exit_status) == 0) {
PANIC("could not get process exit code: %lu", GetLastError());
}
if (exit_status != 0) {
PANIC("command exited with exit code %lu", exit_status);
}
CloseHandle(pid);
#else
for (;;) {
int wstatus = 0;
if (waitpid(pid, &wstatus, 0) < 0) {
PANIC("could not wait on command (pid %d): %s", pid, nobuild__strerror(errno));
}
if (WIFEXITED(wstatus)) {
int exit_status = WEXITSTATUS(wstatus);
if (exit_status != 0) {
ERRO("command exited with exit code %d", exit_status);
}
break;
}
if (WIFSIGNALED(wstatus)) {
PANIC("command process was terminated by %s", strsignal(WTERMSIG(wstatus)));
}
}
#endif // _WIN32
}
Cstr cmd_show(Cmd cmd)
{
// TODO(#31): cmd_show does not render the command line properly
// - No string literals when arguments contains space
// - No escaping of special characters
// - Etc.