-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnob.h
More file actions
2872 lines (2528 loc) · 104 KB
/
nob.h
File metadata and controls
2872 lines (2528 loc) · 104 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
/* nob - v3.1.0 - Public Domain - https://github.com/tsoding/nob.h
This library is the next generation of the [NoBuild](https://github.com/tsoding/nobuild) idea.
# Quick Example
```c
// nob.c
#define NOB_IMPLEMENTATION
#include "nob.h"
int main(int argc, char **argv)
{
NOB_GO_REBUILD_URSELF(argc, argv);
Nob_Cmd cmd = {0};
nob_cmd_append(&cmd, "cc", "-Wall", "-Wextra", "-o", "main", "main.c");
if (!nob_cmd_run(&cmd)) return 1;
return 0;
}
```
```console
$ cc -o nob nob.c
$ ./nob
```
The `nob` automatically rebuilds itself if `nob.c` is modified thanks to
the `NOB_GO_REBUILD_URSELF` macro (don't forget to check out how it works below)
# Stripping off `nob_` Prefixes
Since Pure C does not have any namespaces we prefix each name of the API with the `nob_` to avoid any
potential conflicts with any other names in your code. But sometimes it is very annoying and makes
the code noisy. Because of that you can drop the `nob_` prefix.
```c
// nob.c
#define NOB_IMPLEMENTATION
#include "nob.h"
int main(int argc, char **argv)
{
GO_REBUILD_URSELF(argc, argv);
Cmd cmd = {0};
cmd_append(&cmd, "cc", "-Wall", "-Wextra", "-o", "main", "main.c");
if (!cmd_run(&cmd)) return 1;
return 0;
}
```
If the lack of prefixes causes any problems you can disable the prefix stripping by defining
`NOB_UNSTRIP_PREFIX` feature macro before including "nob.h".
Not all the names have strippable prefixes. All the redefinable names like `NOB_REBUILD_URSELF`
for instance will retain their prefix always. Notable exception is the nob_log() function. Stripping
away the prefix results in log() which was historically always referring to the natural logarithmic
function that is already defined in math.h. So there is no reason to strip off the prefix for nob_log().
Another exception is nob_rename() which collides with the widely known POSIX function rename(2) if you
strip the prefix off.
The prefixes are stripped off only on the level of the preprocessor. The names of the functions in the
compiled object file will still retain the `nob_` prefix. Keep that in mind when you FFI with nob.h
from other languages (for whatever reason).
If only few specific names create conflicts for you, you can just #undef those names after the
`#include <nob.h>` without enabling `NOB_UNSTRIP_PREFIX` since they are macros anyway.
# Macro Interface
All these macros are `#define`d by the user before including nob.h
## Flags
Enable or disable certain aspects of nob.h
- NOB_IMPLEMENTATION - Enable definitions of the functions. By default only declarations are included.
See https://github.com/nothings/stb/blob/f58f558c120e9b32c217290b80bad1a0729fbb2c/docs/stb_howto.txt
for more info.
- NOB_WARN_DEPRECATED - Warn about the usage of deprecated function. We rarely actually remove deprecated functions,
but if you want to know what is discouraged you may want to enable this flag.
- NOB_EXPERIMENTAL_DELETE_OLD - Experimental feature that automatically removes `nob.old` files. It's unclear how well
it works on Windows, so it's experimental for now.
- NOB_UNSTRIP_PREFIX - do not strip the `nob_` prefixes from non-redefinable names.
- NOB_NO_ECHO - do not echo the actions various nob functions are doing (like nob_cmd_run(), nob_mkdir_if_not_exists(), etc).
## Redefinable Macros
Redefine default behaviors of nob.h.
- NOBDEF - Appends additional things to function declarations. You can do something like `#define NOBDEF static inline`.
- NOB_ASSERT(condition) - Redefine which assert() nob.h shall use.
- NOB_REALLOC(oldptr, size) - Redefine which realloc() nob.h shall use.
- NOB_FREE(ptr) - Redefine which free() nob.h shall use.
- NOB_DEPRECATED(message) - Redefine how nob.h shall mark functions as deprecated.
- NOB_DA_INIT_CAP - Redefine initial capacity of Dynamic Arrays.
- NOB_TEMP_CAPACITY - Redefine the capacity of the temporary storate.
- NOB_REBUILD_URSELF(binary_path, source_path) - redefine how nob.h shall rebuild itself.
- NOB_WIN32_ERR_MSG_SIZE - Redefine the capacity of the buffer for error message on Windows.
*/
#ifndef NOB_H_
#define NOB_H_
#ifdef _WIN32
# ifndef _CRT_SECURE_NO_WARNINGS
# define _CRT_SECURE_NO_WARNINGS (1)
# endif // _CRT_SECURE_NO_WARNINGS
#endif // _WIN32
#ifndef NOBDEF
/*
Goes before declarations and definitions of the nob functions. Useful to `#define NOBDEF static inline`
if your source code is a single file and you want the compiler to remove unused functions.
*/
#define NOBDEF
#endif /* NOBDEF */
#ifndef NOB_ASSERT
#include <assert.h>
#define NOB_ASSERT assert
#endif /* NOB_ASSERT */
#ifndef NOB_REALLOC
#include <stdlib.h>
#define NOB_REALLOC realloc
#endif /* NOB_REALLOC */
#ifndef NOB_FREE
#include <stdlib.h>
#define NOB_FREE free
#endif /* NOB_FREE */
#ifdef NOB_WARN_DEPRECATED
# ifndef NOB_DEPRECATED
# if defined(__GNUC__) || defined(__clang__)
# define NOB_DEPRECATED(message) __attribute__((deprecated(message)))
# elif defined(_MSC_VER)
# define NOB_DEPRECATED(message) __declspec(deprecated(message))
# else
# define NOB_DEPRECATED(...)
# endif
# endif /* NOB_DEPRECATED */
#else
# define NOB_DEPRECATED(...)
#endif /* NOB_WARN_DEPRECATED */
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <limits.h>
#include <time.h>
#ifdef _WIN32
# define WIN32_LEAN_AND_MEAN
# define _WINUSER_
# define _WINGDI_
# define _IMM_
# define _WINCON_
# include <windows.h>
# include <direct.h>
# include <io.h>
# include <shellapi.h>
#else
# ifdef __APPLE__
# include <mach-o/dyld.h>
# endif
# ifdef __FreeBSD__
# include <sys/sysctl.h>
# endif
# include <sys/types.h>
# include <sys/wait.h>
# include <sys/stat.h>
# include <unistd.h>
# include <fcntl.h>
# include <dirent.h>
#endif
#ifdef __HAIKU__
# include <image.h>
#endif
#ifdef _WIN32
# define NOB_LINE_END "\r\n"
#else
# define NOB_LINE_END "\n"
#endif
#if defined(__GNUC__) || defined(__clang__)
// https://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Function-Attributes.html
# ifdef __MINGW_PRINTF_FORMAT
# define NOB_PRINTF_FORMAT(STRING_INDEX, FIRST_TO_CHECK) __attribute__ ((format (__MINGW_PRINTF_FORMAT, STRING_INDEX, FIRST_TO_CHECK)))
# else
# define NOB_PRINTF_FORMAT(STRING_INDEX, FIRST_TO_CHECK) __attribute__ ((format (printf, STRING_INDEX, FIRST_TO_CHECK)))
# endif // __MINGW_PRINTF_FORMAT
#else
// TODO: implement NOB_PRINTF_FORMAT for MSVC
# define NOB_PRINTF_FORMAT(STRING_INDEX, FIRST_TO_CHECK)
#endif
#define NOB_UNUSED(value) (void)(value)
#define NOB_TODO(message) do { fprintf(stderr, "%s:%d: TODO: %s\n", __FILE__, __LINE__, message); abort(); } while(0)
#define NOB_UNREACHABLE(message) do { fprintf(stderr, "%s:%d: UNREACHABLE: %s\n", __FILE__, __LINE__, message); abort(); } while(0)
#define NOB_ARRAY_LEN(array) (sizeof(array)/sizeof(array[0]))
#define NOB_ARRAY_GET(array, index) \
(NOB_ASSERT((size_t)index < NOB_ARRAY_LEN(array)), array[(size_t)index])
typedef enum {
NOB_INFO,
NOB_WARNING,
NOB_ERROR,
NOB_NO_LOGS,
} Nob_Log_Level;
// Any messages with the level below nob_minimal_log_level are going to be suppressed.
extern Nob_Log_Level nob_minimal_log_level;
typedef void (nob_log_handler)(Nob_Log_Level level, const char *fmt, va_list args);
NOBDEF void nob_set_log_handler(nob_log_handler *handler);
NOBDEF nob_log_handler *nob_get_log_handler(void);
NOBDEF nob_log_handler nob_default_log_handler;
NOBDEF nob_log_handler nob_cancer_log_handler;
NOBDEF void nob_log(Nob_Log_Level level, const char *fmt, ...) NOB_PRINTF_FORMAT(2, 3);
// It is an equivalent of shift command from bash (do `help shift` in bash). It basically
// pops an element from the beginning of a sized array.
#define nob_shift(xs, xs_sz) (NOB_ASSERT((xs_sz) > 0), (xs_sz)--, *(xs)++)
// NOTE: nob_shift_args() is an alias for an old variant of nob_shift that only worked with
// the command line arguments passed to the main() function. nob_shift() is more generic.
// So nob_shift_args() is semi-deprecated, but I don't see much reason to urgently
// remove it. This alias does not hurt anybody.
#define nob_shift_args(argc, argv) nob_shift(*argv, *argc)
typedef struct {
const char **items;
size_t count;
size_t capacity;
} Nob_File_Paths;
typedef enum {
NOB_FILE_REGULAR = 0,
NOB_FILE_DIRECTORY,
NOB_FILE_SYMLINK,
NOB_FILE_OTHER,
} Nob_File_Type;
NOBDEF bool nob_mkdir_if_not_exists(const char *path);
NOBDEF bool nob_copy_file(const char *src_path, const char *dst_path);
NOBDEF bool nob_copy_directory_recursively(const char *src_path, const char *dst_path);
NOBDEF bool nob_read_entire_dir(const char *parent, Nob_File_Paths *children);
NOBDEF bool nob_write_entire_file(const char *path, const void *data, size_t size);
NOBDEF Nob_File_Type nob_get_file_type(const char *path);
NOBDEF bool nob_delete_file(const char *path);
typedef enum {
// If the current file is a directory go inside of it.
NOB_WALK_CONT,
// If the current file is a directory do not go inside of it.
NOB_WALK_SKIP,
// Stop the recursive traversal process entirely.
NOB_WALK_STOP,
} Nob_Walk_Action;
typedef struct {
// The path to the visited file
const char *path;
// The type of the visited file
Nob_File_Type type;
// How nested we currently are in the directory tree
size_t level;
// User data supplied in Nob_Walk_Dir_Opt.data
void *data;
// The action nob_walk_dir_opt() must perform after the Nob_Walk_Func has returned.
// Default is NOB_WALK_CONT.
Nob_Walk_Action *action;
} Nob_Walk_Entry;
// A function that is called by nob_walk_dir_opt() on each visited file.
// Nob_Walk_Entry provides the details about the visited file and also
// expects you to modify the `action` in case you want to alter the
// usual behavior of the recursive walking algorithm.
//
// If the function returns `false`, an error is assumed which causes the entire
// recursive walking process to exit and nob_walk_dir_opt() return `false`.
typedef bool (*Nob_Walk_Func)(Nob_Walk_Entry entry);
typedef struct {
// User data passed to Nob_Walk_Entry.data
void *data;
// Walk the directory in post-order visiting the leaf files first.
bool post_order;
} Nob_Walk_Dir_Opt;
NOBDEF bool nob_walk_dir_opt(const char *root, Nob_Walk_Func func, Nob_Walk_Dir_Opt);
#define nob_walk_dir(root, func, ...) nob_walk_dir_opt((root), (func), (Nob_Walk_Dir_Opt){__VA_ARGS__})
typedef struct {
char *name;
bool error;
struct {
#ifdef _WIN32
WIN32_FIND_DATA win32_data;
HANDLE win32_hFind;
bool win32_init;
#else
DIR *posix_dir;
struct dirent *posix_ent;
#endif // _WIN32
} nob__private;
} Nob_Dir_Entry;
// nob_dir_entry_open() - open the directory entry for iteration.
// RETURN:
// true - Sucess.
// false - Error. I will be logged automatically with nob_log().
NOBDEF bool nob_dir_entry_open(const char *dir_path, Nob_Dir_Entry *dir);
// nob_dir_entry_next() - acquire the next file in the directory.
// RETURN:
// true - Successfully acquired the next file.
// false - Either failure or no more files to iterate. In case of failure dir->error is set to true.
NOBDEF bool nob_dir_entry_next(Nob_Dir_Entry *dir);
NOBDEF void nob_dir_entry_close(Nob_Dir_Entry dir);
#define nob_return_defer(value) do { result = (value); goto defer; } while(0)
// Initial capacity of a dynamic array
#ifndef NOB_DA_INIT_CAP
#define NOB_DA_INIT_CAP 256
#endif
#ifdef __cplusplus
#define NOB_DECLTYPE_CAST(T) (decltype(T))
#else
#define NOB_DECLTYPE_CAST(T)
#endif // __cplusplus
#define nob_da_reserve(da, expected_capacity) \
do { \
if ((expected_capacity) > (da)->capacity) { \
if ((da)->capacity == 0) { \
(da)->capacity = NOB_DA_INIT_CAP; \
} \
while ((expected_capacity) > (da)->capacity) { \
(da)->capacity *= 2; \
} \
(da)->items = NOB_DECLTYPE_CAST((da)->items)NOB_REALLOC((da)->items, (da)->capacity * sizeof(*(da)->items)); \
NOB_ASSERT((da)->items != NULL && "Buy more RAM lol"); \
} \
} while (0)
// Append an item to a dynamic array
#define nob_da_append(da, item) \
do { \
nob_da_reserve((da), (da)->count + 1); \
(da)->items[(da)->count++] = (item); \
} while (0)
#define nob_da_free(da) NOB_FREE((da).items)
// Append several items to a dynamic array
#define nob_da_append_many(da, new_items, new_items_count) \
do { \
nob_da_reserve((da), (da)->count + (new_items_count)); \
memcpy((da)->items + (da)->count, (new_items), (new_items_count)*sizeof(*(da)->items)); \
(da)->count += (new_items_count); \
} while (0)
#define nob_da_resize(da, new_size) \
do { \
nob_da_reserve((da), new_size); \
(da)->count = (new_size); \
} while (0)
#define nob_da_last(da) (da)->items[(NOB_ASSERT((da)->count > 0), (da)->count-1)]
#define nob_da_remove_unordered(da, i) \
do { \
size_t j = (i); \
NOB_ASSERT(j < (da)->count); \
(da)->items[j] = (da)->items[--(da)->count]; \
} while(0)
// Foreach over Dynamic Arrays. Example:
// ```c
// typedef struct {
// int *items;
// size_t count;
// size_t capacity;
// } Numbers;
//
// Numbers xs = {0};
//
// nob_da_append(&xs, 69);
// nob_da_append(&xs, 420);
// nob_da_append(&xs, 1337);
//
// nob_da_foreach(int, x, &xs) {
// // `x` here is a pointer to the current element. You can get its index by taking a difference
// // between `x` and the start of the array which is `x.items`.
// size_t index = x - xs.items;
// nob_log(INFO, "%zu: %d", index, *x);
// }
// ```
#define nob_da_foreach(Type, it, da) for (Type *it = (da)->items; it < (da)->items + (da)->count; ++it)
typedef struct {
char *items;
size_t count;
size_t capacity;
} Nob_String_Builder;
#define nob_swap(T, a, b) do { T t = a; a = b; b = t; } while (0)
NOBDEF bool nob_read_entire_file(const char *path, Nob_String_Builder *sb);
NOBDEF int nob_sb_appendf(Nob_String_Builder *sb, const char *fmt, ...) NOB_PRINTF_FORMAT(2, 3);
// Pads the String_Builder (sb) to the desired word size boundary with 0s.
// Imagine we have sb that contains 5 `a`-s:
//
// aaaa|a
//
// If we pad align it by size 4 it will look like this:
//
// aaaa|a000| <- padded with 0s to the next size 4 boundary
//
// Useful when you are building some sort of binary format using String_Builder.
NOBDEF void nob_sb_pad_align(Nob_String_Builder *sb, size_t size);
// Append a sized buffer to a string builder
#define nob_sb_append_buf(sb, buf, size) nob_da_append_many(sb, buf, size)
// Append a NULL-terminated string to a string builder
#define nob_sb_append_cstr(sb, cstr) \
do { \
const char *s = (cstr); \
size_t n = strlen(s); \
nob_da_append_many(sb, s, n); \
} while (0)
// Append a single NULL character at the end of a string builder. So then you can
// use it a NULL-terminated C string
#define nob_sb_append_null(sb) nob_da_append_many(sb, "", 1)
#define nob_sb_append nob_da_append
// Free the memory allocated by a string builder
#define nob_sb_free(sb) NOB_FREE((sb).items)
// Process handle
#ifdef _WIN32
typedef HANDLE Nob_Proc;
#define NOB_INVALID_PROC INVALID_HANDLE_VALUE
typedef HANDLE Nob_Fd;
#define NOB_INVALID_FD INVALID_HANDLE_VALUE
#else
typedef int Nob_Proc;
#define NOB_INVALID_PROC (-1)
typedef int Nob_Fd;
#define NOB_INVALID_FD (-1)
#endif // _WIN32
NOBDEF Nob_Fd nob_fd_open_for_read(const char *path);
NOBDEF Nob_Fd nob_fd_open_for_write(const char *path);
NOBDEF void nob_fd_close(Nob_Fd fd);
typedef struct {
Nob_Proc *items;
size_t count;
size_t capacity;
} Nob_Procs;
// Wait until the process has finished
NOBDEF bool nob_proc_wait(Nob_Proc proc);
// Wait until all the processes have finished
NOBDEF bool nob_procs_wait(Nob_Procs procs);
// Wait until all the processes have finished and empty the procs array.
NOBDEF bool nob_procs_flush(Nob_Procs *procs);
// Alias to nob_procs_flush
NOB_DEPRECATED("Use `nob_procs_flush(&procs)` instead.")
NOBDEF bool nob_procs_wait_and_reset(Nob_Procs *procs);
// Append a new process to procs array and if procs.count reaches max_procs_count call nob_procs_wait_and_reset() on it
NOB_DEPRECATED("Use `nob_cmd_run(&cmd, .async = &procs, .max_procs = <integer>)` instead")
NOBDEF bool nob_procs_append_with_flush(Nob_Procs *procs, Nob_Proc proc, size_t max_procs_count);
// A command - the main workhorse of Nob. Nob is all about building commands and running them
typedef struct {
const char **items;
size_t count;
size_t capacity;
} Nob_Cmd;
// Options for nob_cmd_run_opt() function.
typedef struct {
// Run the command asynchronously appending its Nob_Proc to the provided Nob_Procs array
Nob_Procs *async;
// Maximum processes allowed in the .async list. Zero implies nob_nprocs().
size_t max_procs;
// Do not reset the command after execution.
bool dont_reset;
// Redirect stdin to file
const char *stdin_path;
// Redirect stdout to file
const char *stdout_path;
// Redirect stderr to file
const char *stderr_path;
} Nob_Cmd_Opt;
// Run the command with options.
NOBDEF bool nob_cmd_run_opt(Nob_Cmd *cmd, Nob_Cmd_Opt opt);
// Get amount of processors on the machine.
NOBDEF int nob_nprocs(void);
#define NOB_NANOS_PER_SEC (1000*1000*1000)
// The maximum time span representable is 584 years.
NOBDEF uint64_t nob_nanos_since_unspecified_epoch(void);
// Same as nob_cmd_run_opt but using cool variadic macro to set the default options.
// See https://x.com/vkrajacic/status/1749816169736073295 for more info on how to use such macros.
#define nob_cmd_run(cmd, ...) nob_cmd_run_opt((cmd), (Nob_Cmd_Opt){__VA_ARGS__})
// DEPRECATED:
//
// You were suppose to use this structure like this:
//
// ```c
// Nob_Fd fdin = nob_fd_open_for_read("input.txt");
// if (fdin == NOB_INVALID_FD) fail();
// Nob_Fd fdout = nob_fd_open_for_write("output.txt");
// if (fdout == NOB_INVALID_FD) fail();
// Nob_Cmd cmd = {0};
// nob_cmd_append(&cmd, "cat");
// if (!nob_cmd_run_sync_redirect_and_reset(&cmd, (Nob_Cmd_Redirect) {
// .fdin = &fdin,
// .fdout = &fdout
// })) fail();
// ```
//
// But these days you should do:
//
// ```c
// Nob_Cmd cmd = {0};
// nob_cmd_append(&cmd, "cat");
// if (!nob_cmd_run(&cmd, .stdin_path = "input.txt", .stdout_path = "output.txt")) fail();
// ```
typedef struct {
Nob_Fd *fdin;
Nob_Fd *fdout;
Nob_Fd *fderr;
} Nob_Cmd_Redirect;
// Render a string representation of a command into a string builder. Keep in mind the the
// string builder is not NULL-terminated by default. Use nob_sb_append_null if you plan to
// use it as a C string.
NOBDEF void nob_cmd_render(Nob_Cmd cmd, Nob_String_Builder *render);
#define nob_cmd_append(cmd, ...) \
nob__cmd_append(cmd, (sizeof((const char*[]){__VA_ARGS__})/sizeof(const char*)), __VA_ARGS__)
// TODO: nob_cmd_extend() evaluates other_cmd twice
#define nob_cmd_extend(cmd, other_cmd) \
nob_da_append_many(cmd, (other_cmd)->items, (other_cmd)->count)
// Free all the memory allocated by command arguments
#define nob_cmd_free(cmd) NOB_FREE(cmd.items)
// Run command asynchronously
NOB_DEPRECATED("Use `nob_cmd_run(&cmd, .async = &procs, .dont_reset = true)`.")
NOBDEF Nob_Proc nob_cmd_run_async(Nob_Cmd cmd);
// nob_cmd_run_async_and_reset() is just like nob_cmd_run_async() except it also resets cmd.count to 0
// so the Nob_Cmd instance can be seamlessly used several times in a row
NOB_DEPRECATED("Use `nob_cmd_run(&cmd, .async = &procs)` intead.")
NOBDEF Nob_Proc nob_cmd_run_async_and_reset(Nob_Cmd *cmd);
// Run redirected command asynchronously
NOB_DEPRECATED("Use `nob_cmd_run(&cmd, "
".async = &procs, "
".stdin_path = \"path/to/stdin\", "
".stdout_path = \"path/to/stdout\", "
".stderr_path = \"path/to/stderr\", "
".dont_reset = true"
")` instead.")
NOBDEF Nob_Proc nob_cmd_run_async_redirect(Nob_Cmd cmd, Nob_Cmd_Redirect redirect);
// Run redirected command asynchronously and set cmd.count to 0 and close all the opened files
NOB_DEPRECATED("Use `nob_cmd_run(&cmd, "
".async = &procs, "
".stdin_path = \"path/to/stdin\", "
".stdout_path = \"path/to/stdout\", "
".stderr_path = \"path/to/stderr\")` instead.")
NOBDEF Nob_Proc nob_cmd_run_async_redirect_and_reset(Nob_Cmd *cmd, Nob_Cmd_Redirect redirect);
// Run command synchronously
NOB_DEPRECATED("Use `nob_cmd_run(&cmd, .dont_reset = true)` instead.")
NOBDEF bool nob_cmd_run_sync(Nob_Cmd cmd);
// NOTE: nob_cmd_run_sync_and_reset() is just like nob_cmd_run_sync() except it also resets cmd.count to 0
// so the Nob_Cmd instance can be seamlessly used several times in a row
NOB_DEPRECATED("Use `nob_cmd_run(&cmd)` instead.")
NOBDEF bool nob_cmd_run_sync_and_reset(Nob_Cmd *cmd);
// Run redirected command synchronously
NOB_DEPRECATED("Use `nob_cmd_run(&cmd, "
".stdin_path = \"path/to/stdin\", "
".stdout_path = \"path/to/stdout\", "
".stderr_path = \"path/to/stderr\", "
".dont_reset = true"
")` instead.")
NOBDEF bool nob_cmd_run_sync_redirect(Nob_Cmd cmd, Nob_Cmd_Redirect redirect);
// Run redirected command synchronously and set cmd.count to 0 and close all the opened files
NOB_DEPRECATED("Use `nob_cmd_run(&cmd, "
".stdin_path = \"path/to/stdin\", "
".stdout_path = \"path/to/stdout\", "
".stderr_path = \"path/to/stderr\")` instead.")
NOBDEF bool nob_cmd_run_sync_redirect_and_reset(Nob_Cmd *cmd, Nob_Cmd_Redirect redirect);
#ifndef NOB_TEMP_CAPACITY
#define NOB_TEMP_CAPACITY (8*1024*1024)
#endif // NOB_TEMP_CAPACITY
NOBDEF char *nob_temp_strdup(const char *cstr);
NOBDEF char *nob_temp_strndup(const char *cstr, size_t size);
NOBDEF void *nob_temp_alloc(size_t size);
NOBDEF char *nob_temp_sprintf(const char *format, ...) NOB_PRINTF_FORMAT(1, 2);
NOBDEF char *nob_temp_vsprintf(const char *format, va_list ap);
// nob_temp_reset() - Resets the entire temporary storage to 0.
//
// It is generally not recommended to call this function ever. What you usually want to do is let's say you have a loop,
// that allocates some temporary objects and cleans them up at the end of each iteration. You should use
// nob_temp_save() and nob_temp_rewind() to organize such loop like this:
//
// ```c
// char *message = nob_temp_sprintf("This message is still valid after the loop below");
// while (!quit) {
// size_t mark = nob_temp_save();
// nob_temp_alloc(69);
// nob_temp_alloc(420);
// nob_temp_alloc(1337);
// nob_temp_rewind(mark);
// }
// printf("%s\n", message);
// ```
//
// That way all the temporary allocations created before the loop are still valid even after the loop.
// Such save/rewind blocks define lifetime boundaries of the temporary objects which also could be nested.
// This turns the temporary storage into kind of a second stack with a more manual management.
NOBDEF void nob_temp_reset(void);
NOBDEF size_t nob_temp_save(void);
NOBDEF void nob_temp_rewind(size_t checkpoint);
// Given any path returns the last part of that path.
// "/path/to/a/file.c" -> "file.c"; "/path/to/a/directory" -> "directory"
NOBDEF const char *nob_path_name(const char *path);
NOBDEF bool nob_rename(const char *old_path, const char *new_path);
NOBDEF int nob_needs_rebuild(const char *output_path, const char **input_paths, size_t input_paths_count);
NOBDEF int nob_needs_rebuild1(const char *output_path, const char *input_path);
NOBDEF int nob_file_exists(const char *file_path);
NOBDEF const char *nob_get_current_dir_temp(void);
NOBDEF bool nob_set_current_dir(const char *path);
// Returns you the directory part of the path allocated on the temporary storage.
NOBDEF char *nob_temp_dir_name(const char *path);
NOBDEF char *nob_temp_file_name(const char *path);
NOBDEF char *nob_temp_file_ext(const char *path);
NOBDEF char *nob_temp_running_executable_path(void);
// TODO: we should probably document somewhere all the compiler we support
// The nob_cc_* macros try to abstract away the specific compiler.
// They are verify basic and not particularly flexible, but you can redefine them if you need to
// or not use them at all and create your own abstraction on top of Nob_Cmd.
#ifndef nob_cc
# if _WIN32
# if defined(__GNUC__)
# define nob_cc(cmd) nob_cmd_append(cmd, "cc")
# elif defined(__clang__)
# define nob_cc(cmd) nob_cmd_append(cmd, "clang")
# elif defined(_MSC_VER)
# define nob_cc(cmd) nob_cmd_append(cmd, "cl.exe")
# elif defined(__TINYC__)
# define nob_cc(cmd) nob_cmd_append(cmd, "tcc")
# endif
# else
# define nob_cc(cmd) nob_cmd_append(cmd, "cc")
# endif
#endif // nob_cc
#ifndef nob_cc_flags
# if defined(_MSC_VER) && !defined(__clang__)
# define nob_cc_flags(cmd) nob_cmd_append(cmd, "/W4", "/nologo", "/D_CRT_SECURE_NO_WARNINGS")
# else
# define nob_cc_flags(cmd) nob_cmd_append(cmd, "-Wall", "-Wextra")
# endif
#endif // nob_cc_flags
#ifndef nob_cc_output
# if defined(_MSC_VER) && !defined(__clang__)
# define nob_cc_output(cmd, output_path) nob_cmd_append(cmd, nob_temp_sprintf("/Fe:%s", (output_path)), nob_temp_sprintf("/Fo:%s", (output_path)))
# else
# define nob_cc_output(cmd, output_path) nob_cmd_append(cmd, "-o", (output_path))
# endif
#endif // nob_cc_output
#ifndef nob_cc_inputs
# define nob_cc_inputs(cmd, ...) nob_cmd_append(cmd, __VA_ARGS__)
#endif // nob_cc_inputs
// TODO: add MinGW support for Go Rebuild Urself™ Technology and all the nob_cc_* macros above
// Musializer contributors came up with a pretty interesting idea of an optional prefix macro which could be useful for
// MinGW support:
// https://github.com/tsoding/musializer/blob/b7578cc76b9ecb573d239acc9ccf5a04d3aba2c9/src_build/nob_win64_mingw.c#L3-L9
// TODO: Maybe instead NOB_REBUILD_URSELF macro, the Go Rebuild Urself™ Technology should use the
// user defined nob_cc_* macros instead?
#ifndef NOB_REBUILD_URSELF
# if defined(_WIN32)
# if defined(__clang__)
# if defined(__cplusplus)
# define NOB_REBUILD_URSELF(binary_path, source_path) "clang", "-x", "c++", "-o", binary_path, source_path
# else
# define NOB_REBUILD_URSELF(binary_path, source_path) "clang", "-x", "c", "-o", binary_path, source_path
# endif
# elif defined(__GNUC__)
# if defined(__cplusplus)
# define NOB_REBUILD_URSELF(binary_path, source_path) "gcc", "-x", "c++", "-o", binary_path, source_path
# else
# define NOB_REBUILD_URSELF(binary_path, source_path) "gcc", "-x", "c", "-o", binary_path, source_path
# endif
# elif defined(_MSC_VER)
# define NOB_REBUILD_URSELF(binary_path, source_path) "cl.exe", nob_temp_sprintf("/Fe:%s", (binary_path)), source_path
# elif defined(__TINYC__)
# define NOB_REBUILD_URSELF(binary_path, source_path) "tcc", "-o", binary_path, source_path
# endif
# else
# if defined(__cplusplus)
# define NOB_REBUILD_URSELF(binary_path, source_path) "cc", "-x", "c++", "-o", binary_path, source_path
# else
# define NOB_REBUILD_URSELF(binary_path, source_path) "cc", "-x", "c", "-o", binary_path, source_path
# endif
# endif
#endif
// Go Rebuild Urself™ Technology
//
// How to use it:
// int main(int argc, char** argv) {
// NOB_GO_REBUILD_URSELF(argc, argv);
// // actual work
// return 0;
// }
//
// After you added this macro every time you run ./nob 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 NOB_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 ./nob)
//
NOBDEF void nob__go_rebuild_urself(int argc, char **argv, const char *source_path, ...);
#define NOB_GO_REBUILD_URSELF(argc, argv) nob__go_rebuild_urself(argc, argv, __FILE__, NULL)
// Sometimes your nob.c includes additional files, so you want the Go Rebuild Urself™ Technology to check
// if they also were modified and rebuild nob.c accordingly. For that we have NOB_GO_REBUILD_URSELF_PLUS():
// ```c
// #define NOB_IMPLEMENTATION
// #include "nob.h"
//
// #include "foo.c"
// #include "bar.c"
//
// int main(int argc, char **argv)
// {
// NOB_GO_REBUILD_URSELF_PLUS(argc, argv, "foo.c", "bar.c");
// // ...
// return 0;
// }
#define NOB_GO_REBUILD_URSELF_PLUS(argc, argv, ...) nob__go_rebuild_urself(argc, argv, __FILE__, __VA_ARGS__, NULL);
typedef struct {
size_t count;
const char *data;
} Nob_String_View;
NOBDEF const char *nob_temp_sv_to_cstr(Nob_String_View sv);
NOBDEF Nob_String_View nob_sv_chop_by_delim(Nob_String_View *sv, char delim);
NOBDEF Nob_String_View nob_sv_chop_left(Nob_String_View *sv, size_t n);
NOBDEF Nob_String_View nob_sv_trim(Nob_String_View sv);
NOBDEF Nob_String_View nob_sv_trim_left(Nob_String_View sv);
NOBDEF Nob_String_View nob_sv_trim_right(Nob_String_View sv);
NOBDEF bool nob_sv_eq(Nob_String_View a, Nob_String_View b);
NOBDEF bool nob_sv_end_with(Nob_String_View sv, const char *cstr);
NOBDEF bool nob_sv_starts_with(Nob_String_View sv, Nob_String_View expected_prefix);
NOBDEF Nob_String_View nob_sv_from_cstr(const char *cstr);
NOBDEF Nob_String_View nob_sv_from_parts(const char *data, size_t count);
// nob_sb_to_sv() enables you to just view Nob_String_Builder as Nob_String_View
#define nob_sb_to_sv(sb) nob_sv_from_parts((sb).items, (sb).count)
// printf macros for String_View
#ifndef SV_Fmt
#define SV_Fmt "%.*s"
#endif // SV_Fmt
#ifndef SV_Arg
#define SV_Arg(sv) (int) (sv).count, (sv).data
#endif // SV_Arg
// USAGE:
// String_View name = ...;
// printf("Name: "SV_Fmt"\n", SV_Arg(name));
#ifdef _WIN32
NOBDEF char *nob_win32_error_message(DWORD err);
#endif // _WIN32
#endif // NOB_H_
#ifdef NOB_IMPLEMENTATION
// This is like nob_proc_wait() but waits asynchronously. Depending on the platform ms means different thing.
// On Windows it means timeout. On POSIX it means for how long to sleep after checking if the process exited,
// so to not peg the core too much. Since this API is kinda of weird, the function is private for now.
static int nob__proc_wait_async(Nob_Proc proc, int ms);
// Starts the process for the command. Its main purpose is to be the base for nob_cmd_run() and nob_cmd_run_opt().
static Nob_Proc nob__cmd_start_process(Nob_Cmd cmd, Nob_Fd *fdin, Nob_Fd *fdout, Nob_Fd *fderr);
// Any messages with the level below nob_minimal_log_level are going to be suppressed.
Nob_Log_Level nob_minimal_log_level = NOB_INFO;
void nob__cmd_append(Nob_Cmd *cmd, size_t n, ...)
{
va_list args;
va_start(args, n);
for (size_t i = 0; i < n; ++i) {
const char *arg = va_arg(args, const char *);
nob_da_append(cmd, arg);
}
va_end(args);
}
#ifdef _WIN32
// Base on https://stackoverflow.com/a/75644008
// > .NET Core uses 4096 * sizeof(WCHAR) buffer on stack for FormatMessageW call. And...thats it.
// >
// > https://github.com/dotnet/runtime/blob/3b63eb1346f1ddbc921374a5108d025662fb5ffd/src/coreclr/utilcode/posterror.cpp#L264-L265
#ifndef NOB_WIN32_ERR_MSG_SIZE
#define NOB_WIN32_ERR_MSG_SIZE (4 * 1024)
#endif // NOB_WIN32_ERR_MSG_SIZE
NOBDEF char *nob_win32_error_message(DWORD err) {
static char win32ErrMsg[NOB_WIN32_ERR_MSG_SIZE] = {0};
DWORD errMsgSize = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, LANG_USER_DEFAULT, win32ErrMsg,
NOB_WIN32_ERR_MSG_SIZE, NULL);
if (errMsgSize == 0) {
if (GetLastError() != ERROR_MR_MID_NOT_FOUND) {
if (sprintf(win32ErrMsg, "Could not get error message for 0x%lX", err) > 0) {
return (char *)&win32ErrMsg;
} else {
return NULL;
}
} else {
if (sprintf(win32ErrMsg, "Invalid Windows Error code (0x%lX)", err) > 0) {
return (char *)&win32ErrMsg;
} else {
return NULL;
}
}
}
while (errMsgSize > 1 && isspace(win32ErrMsg[errMsgSize - 1])) {
win32ErrMsg[--errMsgSize] = '\0';
}
return win32ErrMsg;
}
#endif // _WIN32
// The implementation idea is stolen from https://github.com/zhiayang/nabs
NOBDEF void nob__go_rebuild_urself(int argc, char **argv, const char *source_path, ...)
{
const char *binary_path = nob_shift(argv, argc);
#ifdef _WIN32
// On Windows executables almost always invoked without extension, so
// it's ./nob, not ./nob.exe. For renaming the extension is a must.
if (!nob_sv_end_with(nob_sv_from_cstr(binary_path), ".exe")) {
binary_path = nob_temp_sprintf("%s.exe", binary_path);
}
#endif
Nob_File_Paths source_paths = {0};
nob_da_append(&source_paths, source_path);
va_list args;
va_start(args, source_path);
for (;;) {
const char *path = va_arg(args, const char*);
if (path == NULL) break;
nob_da_append(&source_paths, path);
}
va_end(args);
int rebuild_is_needed = nob_needs_rebuild(binary_path, source_paths.items, source_paths.count);
if (rebuild_is_needed < 0) exit(1); // error
if (!rebuild_is_needed) { // no rebuild is needed
NOB_FREE(source_paths.items);
return;
}
Nob_Cmd cmd = {0};
const char *old_binary_path = nob_temp_sprintf("%s.old", binary_path);
if (!nob_rename(binary_path, old_binary_path)) exit(1);
nob_cmd_append(&cmd, NOB_REBUILD_URSELF(binary_path, source_path));
Nob_Cmd_Opt opt = {0};
if (!nob_cmd_run_opt(&cmd, opt)) {
nob_rename(old_binary_path, binary_path);
exit(1);
}
#ifdef NOB_EXPERIMENTAL_DELETE_OLD
// TODO: this is an experimental behavior behind a compilation flag.
// Once it is confirmed that it does not cause much problems on both POSIX and Windows
// we may turn it on by default.
nob_delete_file(old_binary_path);
#endif // NOB_EXPERIMENTAL_DELETE_OLD
nob_cmd_append(&cmd, binary_path);
nob_da_append_many(&cmd, argv, argc);
if (!nob_cmd_run_opt(&cmd, opt)) exit(1);
exit(0);
}
static size_t nob_temp_size = 0;
static char nob_temp[NOB_TEMP_CAPACITY] = {0};
NOBDEF bool nob_mkdir_if_not_exists(const char *path)
{
#ifdef _WIN32
int result = _mkdir(path);
#else
int result = mkdir(path, 0755);
#endif
if (result < 0) {
if (errno == EEXIST) {
#ifndef NOB_NO_ECHO
nob_log(NOB_INFO, "directory `%s` already exists", path);
#endif // NOB_NO_ECHO
return true;
}
nob_log(NOB_ERROR, "could not create directory `%s`: %s", path, strerror(errno));
return false;
}
#ifndef NOB_NO_ECHO
nob_log(NOB_INFO, "created directory `%s`", path);
#endif // NOB_NO_ECHO
return true;
}
NOBDEF bool nob_copy_file(const char *src_path, const char *dst_path)
{
#ifndef NOB_NO_ECHO
nob_log(NOB_INFO, "copying %s -> %s", src_path, dst_path);
#endif // NOB_NO_ECHO
#ifdef _WIN32
if (!CopyFile(src_path, dst_path, FALSE)) {
nob_log(NOB_ERROR, "Could not copy file: %s", nob_win32_error_message(GetLastError()));
return false;
}
return true;
#else
int src_fd = -1;
int dst_fd = -1;
size_t buf_size = 32*1024;
char *buf = (char*)NOB_REALLOC(NULL, buf_size);
NOB_ASSERT(buf != NULL && "Buy more RAM lol!!");
bool result = true;
src_fd = open(src_path, O_RDONLY);
if (src_fd < 0) {