nob.h 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468
  1. /* nob - v1.23.0 - Public Domain - https://github.com/tsoding/nob.h
  2. This library is the next generation of the [NoBuild](https://github.com/tsoding/nobuild) idea.
  3. # Quick Example
  4. ```c
  5. // nob.c
  6. #define NOB_IMPLEMENTATION
  7. #include "nob.h"
  8. int main(int argc, char **argv)
  9. {
  10. NOB_GO_REBUILD_URSELF(argc, argv);
  11. Nob_Cmd cmd = {0};
  12. nob_cmd_append(&cmd, "cc", "-Wall", "-Wextra", "-o", "main", "main.c");
  13. if (!nob_cmd_run(&cmd)) return 1;
  14. return 0;
  15. }
  16. ```
  17. ```console
  18. $ cc -o nob nob.c
  19. $ ./nob
  20. ```
  21. The `nob` automatically rebuilds itself if `nob.c` is modified thanks to
  22. the `NOB_GO_REBUILD_URSELF` macro (don't forget to check out how it works below)
  23. # Stripping off `nob_` Prefixes
  24. Since Pure C does not have any namespaces we prefix each name of the API with the `nob_` to avoid any
  25. potential conflicts with any other names in your code. But sometimes it is very annoying and makes
  26. the code noisy. If you know that none of the names from nob.h conflict with anything in your code
  27. you can enable NOB_STRIP_PREFIX macro and just drop all the prefixes:
  28. ```c
  29. // nob.c
  30. #define NOB_IMPLEMENTATION
  31. #define NOB_STRIP_PREFIX
  32. #include "nob.h"
  33. int main(int argc, char **argv)
  34. {
  35. NOB_GO_REBUILD_URSELF(argc, argv);
  36. Cmd cmd = {0};
  37. cmd_append(&cmd, "cc", "-Wall", "-Wextra", "-o", "main", "main.c");
  38. if (!cmd_run(&cmd)) return 1;
  39. return 0;
  40. }
  41. ```
  42. Not all the names have strippable prefixes. All the redefinable names like `NOB_GO_REBUILD_URSELF`
  43. for instance will retain their prefix even if NOB_STRIP_PREFIX is enabled. Notable exception is the
  44. nob_log() function. Stripping away the prefix results in log() which was historically always referring
  45. to the natural logarithmic function that is already defined in math.h. So there is no reason to strip
  46. off the prefix for nob_log(). Another exception is nob_rename() which collides with the widely known
  47. POSIX function rename(2) if you strip the prefix off.
  48. The prefixes are stripped off only on the level of preprocessor. The names of the functions in the
  49. compiled object file will still retain the `nob_` prefix. Keep that in mind when you FFI with nob.h
  50. from other languages (for whatever reason).
  51. If only few specific names create conflicts for you, you can just #undef those names after the
  52. `#include <nob.h>` since they are macros anyway.
  53. # Macro Interface
  54. All these macros are `#define`d by the user before including nob.h
  55. ## Flags
  56. Enable or disable certain aspects of nob.h
  57. - NOB_IMPLEMENTATION - Enable definitions of the functions. By default only declarations are included.
  58. See https://github.com/nothings/stb/blob/f58f558c120e9b32c217290b80bad1a0729fbb2c/docs/stb_howto.txt
  59. for more info.
  60. - NOB_WARN_DEPRECATED - Warn about the usage of deprecated function. We rarely actually remove deprecated functions,
  61. but if you want to know what is discourage you may want to enable this flag.
  62. - NOB_EXPERIMENTAL_DELETE_OLD - Experimental feature that automatically removes `nob.old` files. It's unclear how well
  63. it works on Windows, so it's experimental for now.
  64. - NOB_STRIP_PREFIX - string the `nob_` prefixes from non-redefinable names.
  65. ## Redefinable Macros
  66. Redefine default behaviors of nob.h.
  67. - NOBDEF - Appends additional things to function declarations. You can do something like `#define NOBDEF static inline`.
  68. - NOB_ASSERT(condition) - Redefine which assert() nob.h shall use.
  69. - NOB_REALLOC(oldptr, size) - Redefine which realloc() nob.h shall use.
  70. - NOB_FREE(ptr) - Redefine which free() nob.h shall use.
  71. - NOB_DEPRECATED(message) - Redefine how nob.h shall mark functions as deprecated.
  72. - NOB_DA_INIT_CAP - Redefine initial capacity of Dynamic Arrays.
  73. - NOB_TEMP_CAPACITY - Redefine the capacity of the temporary storate.
  74. - NOB_REBUILD_URSELF(binary_path, source_path) - redefine how nob.h shall rebuild itself.
  75. - NOB_WIN32_ERR_MSG_SIZE - Redefine the capacity of the buffer for error message on Windows.
  76. */
  77. #ifndef NOB_H_
  78. #define NOB_H_
  79. #ifdef _WIN32
  80. #define _CRT_SECURE_NO_WARNINGS (1)
  81. #endif
  82. #ifndef NOBDEF
  83. /*
  84. Goes before declarations and definitions of the nob functions. Useful to `#define NOBDEF static inline`
  85. if your source code is a single file and you want the compiler to remove unused functions.
  86. */
  87. #define NOBDEF
  88. #endif /* NOBDEF */
  89. #ifndef NOB_ASSERT
  90. #include <assert.h>
  91. #define NOB_ASSERT assert
  92. #endif /* NOB_ASSERT */
  93. #ifndef NOB_REALLOC
  94. #include <stdlib.h>
  95. #define NOB_REALLOC realloc
  96. #endif /* NOB_REALLOC */
  97. #ifndef NOB_FREE
  98. #include <stdlib.h>
  99. #define NOB_FREE free
  100. #endif /* NOB_FREE */
  101. #ifdef NOB_WARN_DEPRECATED
  102. # ifndef NOB_DEPRECATED
  103. # if defined(__GNUC__) || defined(__clang__)
  104. # define NOB_DEPRECATED(message) __attribute__((deprecated(message)))
  105. # elif defined(_MSC_VER)
  106. # define NOB_DEPRECATED(message) __declspec(deprecated(message))
  107. # else
  108. # define NOB_DEPRECATED(...)
  109. # endif
  110. # endif /* NOB_DEPRECATED */
  111. #else
  112. # define NOB_DEPRECATED(...)
  113. #endif /* NOB_WARN_DEPRECATED */
  114. #include <stdbool.h>
  115. #include <stdint.h>
  116. #include <stdlib.h>
  117. #include <stdio.h>
  118. #include <stdarg.h>
  119. #include <string.h>
  120. #include <errno.h>
  121. #include <ctype.h>
  122. #include <limits.h>
  123. #include <time.h>
  124. #ifdef _WIN32
  125. # define WIN32_LEAN_AND_MEAN
  126. # define _WINUSER_
  127. # define _WINGDI_
  128. # define _IMM_
  129. # define _WINCON_
  130. # include <windows.h>
  131. # include <direct.h>
  132. # include <shellapi.h>
  133. #else
  134. # include <sys/types.h>
  135. # include <sys/wait.h>
  136. # include <sys/stat.h>
  137. # include <unistd.h>
  138. # include <fcntl.h>
  139. #endif
  140. #ifdef _WIN32
  141. # define NOB_LINE_END "\r\n"
  142. #else
  143. # define NOB_LINE_END "\n"
  144. #endif
  145. #if defined(__GNUC__) || defined(__clang__)
  146. // https://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Function-Attributes.html
  147. # ifdef __MINGW_PRINTF_FORMAT
  148. # define NOB_PRINTF_FORMAT(STRING_INDEX, FIRST_TO_CHECK) __attribute__ ((format (__MINGW_PRINTF_FORMAT, STRING_INDEX, FIRST_TO_CHECK)))
  149. # else
  150. # define NOB_PRINTF_FORMAT(STRING_INDEX, FIRST_TO_CHECK) __attribute__ ((format (printf, STRING_INDEX, FIRST_TO_CHECK)))
  151. # endif // __MINGW_PRINTF_FORMAT
  152. #else
  153. // TODO: implement NOB_PRINTF_FORMAT for MSVC
  154. # define NOB_PRINTF_FORMAT(STRING_INDEX, FIRST_TO_CHECK)
  155. #endif
  156. #define NOB_UNUSED(value) (void)(value)
  157. #define NOB_TODO(message) do { fprintf(stderr, "%s:%d: TODO: %s\n", __FILE__, __LINE__, message); abort(); } while(0)
  158. #define NOB_UNREACHABLE(message) do { fprintf(stderr, "%s:%d: UNREACHABLE: %s\n", __FILE__, __LINE__, message); abort(); } while(0)
  159. #define NOB_ARRAY_LEN(array) (sizeof(array)/sizeof(array[0]))
  160. #define NOB_ARRAY_GET(array, index) \
  161. (NOB_ASSERT((size_t)index < NOB_ARRAY_LEN(array)), array[(size_t)index])
  162. typedef enum {
  163. NOB_INFO,
  164. NOB_WARNING,
  165. NOB_ERROR,
  166. NOB_NO_LOGS,
  167. } Nob_Log_Level;
  168. // Any messages with the level below nob_minimal_log_level are going to be suppressed.
  169. extern Nob_Log_Level nob_minimal_log_level;
  170. NOBDEF void nob_log(Nob_Log_Level level, const char *fmt, ...) NOB_PRINTF_FORMAT(2, 3);
  171. // It is an equivalent of shift command from bash (do `help shift` in bash). It basically
  172. // pops an element from the beginning of a sized array.
  173. #define nob_shift(xs, xs_sz) (NOB_ASSERT((xs_sz) > 0), (xs_sz)--, *(xs)++)
  174. // NOTE: nob_shift_args() is an alias for an old variant of nob_shift that only worked with
  175. // the command line arguments passed to the main() function. nob_shift() is more generic.
  176. // So nob_shift_args() is semi-deprecated, but I don't see much reason to urgently
  177. // remove it. This alias does not hurt anybody.
  178. #define nob_shift_args(argc, argv) nob_shift(*argv, *argc)
  179. typedef struct {
  180. const char **items;
  181. size_t count;
  182. size_t capacity;
  183. } Nob_File_Paths;
  184. typedef enum {
  185. NOB_FILE_REGULAR = 0,
  186. NOB_FILE_DIRECTORY,
  187. NOB_FILE_SYMLINK,
  188. NOB_FILE_OTHER,
  189. } Nob_File_Type;
  190. NOBDEF bool nob_mkdir_if_not_exists(const char *path);
  191. NOBDEF bool nob_copy_file(const char *src_path, const char *dst_path);
  192. NOBDEF bool nob_copy_directory_recursively(const char *src_path, const char *dst_path);
  193. NOBDEF bool nob_read_entire_dir(const char *parent, Nob_File_Paths *children);
  194. NOBDEF bool nob_write_entire_file(const char *path, const void *data, size_t size);
  195. NOBDEF Nob_File_Type nob_get_file_type(const char *path);
  196. NOBDEF bool nob_delete_file(const char *path);
  197. #define nob_return_defer(value) do { result = (value); goto defer; } while(0)
  198. // Initial capacity of a dynamic array
  199. #ifndef NOB_DA_INIT_CAP
  200. #define NOB_DA_INIT_CAP 256
  201. #endif
  202. #ifdef __cplusplus
  203. #define NOB_DECLTYPE_CAST(T) (decltype(T))
  204. #else
  205. #define NOB_DECLTYPE_CAST(T)
  206. #endif // __cplusplus
  207. #define nob_da_reserve(da, expected_capacity) \
  208. do { \
  209. if ((expected_capacity) > (da)->capacity) { \
  210. if ((da)->capacity == 0) { \
  211. (da)->capacity = NOB_DA_INIT_CAP; \
  212. } \
  213. while ((expected_capacity) > (da)->capacity) { \
  214. (da)->capacity *= 2; \
  215. } \
  216. (da)->items = NOB_DECLTYPE_CAST((da)->items)NOB_REALLOC((da)->items, (da)->capacity * sizeof(*(da)->items)); \
  217. NOB_ASSERT((da)->items != NULL && "Buy more RAM lol"); \
  218. } \
  219. } while (0)
  220. // Append an item to a dynamic array
  221. #define nob_da_append(da, item) \
  222. do { \
  223. nob_da_reserve((da), (da)->count + 1); \
  224. (da)->items[(da)->count++] = (item); \
  225. } while (0)
  226. #define nob_da_free(da) NOB_FREE((da).items)
  227. // Append several items to a dynamic array
  228. #define nob_da_append_many(da, new_items, new_items_count) \
  229. do { \
  230. nob_da_reserve((da), (da)->count + (new_items_count)); \
  231. memcpy((da)->items + (da)->count, (new_items), (new_items_count)*sizeof(*(da)->items)); \
  232. (da)->count += (new_items_count); \
  233. } while (0)
  234. #define nob_da_resize(da, new_size) \
  235. do { \
  236. nob_da_reserve((da), new_size); \
  237. (da)->count = (new_size); \
  238. } while (0)
  239. #define nob_da_last(da) (da)->items[(NOB_ASSERT((da)->count > 0), (da)->count-1)]
  240. #define nob_da_remove_unordered(da, i) \
  241. do { \
  242. size_t j = (i); \
  243. NOB_ASSERT(j < (da)->count); \
  244. (da)->items[j] = (da)->items[--(da)->count]; \
  245. } while(0)
  246. // Foreach over Dynamic Arrays. Example:
  247. // ```c
  248. // typedef struct {
  249. // int *items;
  250. // size_t count;
  251. // size_t capacity;
  252. // } Numbers;
  253. //
  254. // Numbers xs = {0};
  255. //
  256. // nob_da_append(&xs, 69);
  257. // nob_da_append(&xs, 420);
  258. // nob_da_append(&xs, 1337);
  259. //
  260. // nob_da_foreach(int, x, &xs) {
  261. // // `x` here is a pointer to the current element. You can get its index by taking a difference
  262. // // between `x` and the start of the array which is `x.items`.
  263. // size_t index = x - xs.items;
  264. // nob_log(INFO, "%zu: %d", index, *x);
  265. // }
  266. // ```
  267. #define nob_da_foreach(Type, it, da) for (Type *it = (da)->items; it < (da)->items + (da)->count; ++it)
  268. typedef struct {
  269. char *items;
  270. size_t count;
  271. size_t capacity;
  272. } Nob_String_Builder;
  273. NOBDEF bool nob_read_entire_file(const char *path, Nob_String_Builder *sb);
  274. NOBDEF int nob_sb_appendf(Nob_String_Builder *sb, const char *fmt, ...) NOB_PRINTF_FORMAT(2, 3);
  275. // Append a sized buffer to a string builder
  276. #define nob_sb_append_buf(sb, buf, size) nob_da_append_many(sb, buf, size)
  277. // Append a NULL-terminated string to a string builder
  278. #define nob_sb_append_cstr(sb, cstr) \
  279. do { \
  280. const char *s = (cstr); \
  281. size_t n = strlen(s); \
  282. nob_da_append_many(sb, s, n); \
  283. } while (0)
  284. // Append a single NULL character at the end of a string builder. So then you can
  285. // use it a NULL-terminated C string
  286. #define nob_sb_append_null(sb) nob_da_append_many(sb, "", 1)
  287. // Free the memory allocated by a string builder
  288. #define nob_sb_free(sb) NOB_FREE((sb).items)
  289. // Process handle
  290. #ifdef _WIN32
  291. typedef HANDLE Nob_Proc;
  292. #define NOB_INVALID_PROC INVALID_HANDLE_VALUE
  293. typedef HANDLE Nob_Fd;
  294. #define NOB_INVALID_FD INVALID_HANDLE_VALUE
  295. #else
  296. typedef int Nob_Proc;
  297. #define NOB_INVALID_PROC (-1)
  298. typedef int Nob_Fd;
  299. #define NOB_INVALID_FD (-1)
  300. #endif // _WIN32
  301. NOBDEF Nob_Fd nob_fd_open_for_read(const char *path);
  302. NOBDEF Nob_Fd nob_fd_open_for_write(const char *path);
  303. NOBDEF void nob_fd_close(Nob_Fd fd);
  304. typedef struct {
  305. Nob_Proc *items;
  306. size_t count;
  307. size_t capacity;
  308. } Nob_Procs;
  309. // Wait until the process has finished
  310. NOBDEF bool nob_proc_wait(Nob_Proc proc);
  311. // Wait until all the processes have finished
  312. NOBDEF bool nob_procs_wait(Nob_Procs procs);
  313. // Wait until all the processes have finished and empty the procs array.
  314. NOBDEF bool nob_procs_flush(Nob_Procs *procs);
  315. // Alias to nob_procs_flush
  316. NOB_DEPRECATED("Use `nob_procs_flush(&procs)` instead.")
  317. NOBDEF bool nob_procs_wait_and_reset(Nob_Procs *procs);
  318. // Append a new process to procs array and if procs.count reaches max_procs_count call nob_procs_wait_and_reset() on it
  319. NOB_DEPRECATED("Use `nob_cmd_run(&cmd, .async = &procs, .max_procs = <integer>)` instead")
  320. NOBDEF bool nob_procs_append_with_flush(Nob_Procs *procs, Nob_Proc proc, size_t max_procs_count);
  321. // A command - the main workhorse of Nob. Nob is all about building commands and running them
  322. typedef struct {
  323. const char **items;
  324. size_t count;
  325. size_t capacity;
  326. } Nob_Cmd;
  327. // Options for nob_cmd_run_opt() function.
  328. typedef struct {
  329. // Run the command asynchronously appending its Nob_Proc to the provided Nob_Procs array
  330. Nob_Procs *async;
  331. // Maximum processes allowed in the .async list. Zero implies nob_nprocs().
  332. size_t max_procs;
  333. // Redirect stdin to file
  334. const char *stdin_path;
  335. // Redirect stdout to file
  336. const char *stdout_path;
  337. // Redirect stderr to file
  338. const char *stderr_path;
  339. } Nob_Cmd_Opt;
  340. // Run the command with options.
  341. NOBDEF bool nob_cmd_run_opt(Nob_Cmd *cmd, Nob_Cmd_Opt opt);
  342. // Get amount of processors on the machine.
  343. NOBDEF int nob_nprocs(void);
  344. #define NOB_NANOS_PER_SEC (1000*1000*1000)
  345. // The maximum time span representable is 584 years.
  346. NOBDEF uint64_t nob_nanos_since_unspecified_epoch(void);
  347. // Same as nob_cmd_run_opt but using cool variadic macro to set the default options.
  348. // See https://x.com/vkrajacic/status/1749816169736073295 for more info on how to use such macros.
  349. #define nob_cmd_run(cmd, ...) nob_cmd_run_opt((cmd), (Nob_Cmd_Opt){__VA_ARGS__})
  350. // DEPRECATED:
  351. //
  352. // You were suppose to use this structure like this:
  353. //
  354. // ```c
  355. // Nob_Fd fdin = nob_fd_open_for_read("input.txt");
  356. // if (fdin == NOB_INVALID_FD) fail();
  357. // Nob_Fd fdout = nob_fd_open_for_write("output.txt");
  358. // if (fdout == NOB_INVALID_FD) fail();
  359. // Nob_Cmd cmd = {0};
  360. // nob_cmd_append(&cmd, "cat");
  361. // if (!nob_cmd_run_sync_redirect_and_reset(&cmd, (Nob_Cmd_Redirect) {
  362. // .fdin = &fdin,
  363. // .fdout = &fdout
  364. // })) fail();
  365. // ```
  366. //
  367. // But these days you should do:
  368. //
  369. // ```c
  370. // Nob_Cmd cmd = {0};
  371. // nob_cmd_append(&cmd, "cat");
  372. // if (!nob_cmd_run(&cmd, .stdin_path = "input.txt", .stdout_path = "output.txt")) fail();
  373. // ```
  374. typedef struct {
  375. Nob_Fd *fdin;
  376. Nob_Fd *fdout;
  377. Nob_Fd *fderr;
  378. } Nob_Cmd_Redirect;
  379. // Render a string representation of a command into a string builder. Keep in mind the the
  380. // string builder is not NULL-terminated by default. Use nob_sb_append_null if you plan to
  381. // use it as a C string.
  382. NOBDEF void nob_cmd_render(Nob_Cmd cmd, Nob_String_Builder *render);
  383. #define nob_cmd_append(cmd, ...) \
  384. nob_da_append_many(cmd, \
  385. ((const char*[]){__VA_ARGS__}), \
  386. (sizeof((const char*[]){__VA_ARGS__})/sizeof(const char*)))
  387. // TODO: nob_cmd_extend() evaluates other_cmd twice
  388. #define nob_cmd_extend(cmd, other_cmd) \
  389. nob_da_append_many(cmd, (other_cmd)->items, (other_cmd)->count)
  390. // Free all the memory allocated by command arguments
  391. #define nob_cmd_free(cmd) NOB_FREE(cmd.items)
  392. // Run command asynchronously
  393. NOB_DEPRECATED("Use `nob_cmd_run(&cmd, .async = &procs)` instead, but keep in mind that it always resets the cmd array.")
  394. NOBDEF Nob_Proc nob_cmd_run_async(Nob_Cmd cmd);
  395. // nob_cmd_run_async_and_reset() is just like nob_cmd_run_async() except it also resets cmd.count to 0
  396. // so the Nob_Cmd instance can be seamlessly used several times in a row
  397. NOB_DEPRECATED("Use `nob_cmd_run(&cmd, .async = &procs)` intead.")
  398. NOBDEF Nob_Proc nob_cmd_run_async_and_reset(Nob_Cmd *cmd);
  399. // Run redirected command asynchronously
  400. NOB_DEPRECATED("Use `nob_cmd_run(&cmd, "
  401. ".async = &procs, "
  402. ".stdin_path = \"path/to/stdin\", "
  403. ".stdout_path = \"path/to/stdout\", "
  404. ".stderr_path = \"path/to/stderr\")` instead, "
  405. "but keep in mind that it always resets the cmd array.")
  406. NOBDEF Nob_Proc nob_cmd_run_async_redirect(Nob_Cmd cmd, Nob_Cmd_Redirect redirect);
  407. // Run redirected command asynchronously and set cmd.count to 0 and close all the opened files
  408. NOB_DEPRECATED("Use `nob_cmd_run(&cmd, "
  409. ".async = &procs, "
  410. ".stdin_path = \"path/to/stdin\", "
  411. ".stdout_path = \"path/to/stdout\", "
  412. ".stderr_path = \"path/to/stderr\")` instead.")
  413. NOBDEF Nob_Proc nob_cmd_run_async_redirect_and_reset(Nob_Cmd *cmd, Nob_Cmd_Redirect redirect);
  414. // Run command synchronously
  415. NOB_DEPRECATED("Use `nob_cmd_run(&cmd)` instead, "
  416. "but keep in mind that it always resets the cmd array.")
  417. NOBDEF bool nob_cmd_run_sync(Nob_Cmd cmd);
  418. // NOTE: nob_cmd_run_sync_and_reset() is just like nob_cmd_run_sync() except it also resets cmd.count to 0
  419. // so the Nob_Cmd instance can be seamlessly used several times in a row
  420. NOB_DEPRECATED("Use `nob_cmd_run(&cmd)` instead.")
  421. NOBDEF bool nob_cmd_run_sync_and_reset(Nob_Cmd *cmd);
  422. // Run redirected command synchronously
  423. NOB_DEPRECATED("Use `nob_cmd_run(&cmd, "
  424. ".stdin_path = \"path/to/stdin\", "
  425. ".stdout_path = \"path/to/stdout\", "
  426. ".stderr_path = \"path/to/stderr\")` instead, "
  427. "but keep in mind that it always resets the cmd array.")
  428. NOBDEF bool nob_cmd_run_sync_redirect(Nob_Cmd cmd, Nob_Cmd_Redirect redirect);
  429. // Run redirected command synchronously and set cmd.count to 0 and close all the opened files
  430. NOB_DEPRECATED("Use `nob_cmd_run(&cmd, "
  431. ".stdin_path = \"path/to/stdin\", "
  432. ".stdout_path = \"path/to/stdout\", "
  433. ".stderr_path = \"path/to/stderr\")` instead.")
  434. NOBDEF bool nob_cmd_run_sync_redirect_and_reset(Nob_Cmd *cmd, Nob_Cmd_Redirect redirect);
  435. #ifndef NOB_TEMP_CAPACITY
  436. #define NOB_TEMP_CAPACITY (8*1024*1024)
  437. #endif // NOB_TEMP_CAPACITY
  438. NOBDEF char *nob_temp_strdup(const char *cstr);
  439. NOBDEF void *nob_temp_alloc(size_t size);
  440. NOBDEF char *nob_temp_sprintf(const char *format, ...) NOB_PRINTF_FORMAT(1, 2);
  441. // nob_temp_reset() - Resets the entire temporary storage to 0.
  442. //
  443. // It is generally not recommended to call this function ever. What you usually want to do is let's say you have a loop,
  444. // that allocates some temporary objects and cleans them up at the end of each iteration. You should use
  445. // nob_temp_save() and nob_temp_rewind() to organize such loop like this:
  446. //
  447. // ```c
  448. // char *message = nob_temp_sprintf("This message is still valid after the loop below");
  449. // while (!quit) {
  450. // size_t mark = nob_temp_save();
  451. // nob_temp_alloc(69);
  452. // nob_temp_alloc(420);
  453. // nob_temp_alloc(1337);
  454. // nob_temp_rewind(mark);
  455. // }
  456. // printf("%s\n", message);
  457. // ```
  458. //
  459. // That way all the temporary allocations created before the loop are still valid even after the loop.
  460. // Such save/rewind blocks define lifetime boundaries of the temporary objects which also could be nested.
  461. // This turns the temporary storage into kind of a second stack with a more manual management.
  462. NOBDEF void nob_temp_reset(void);
  463. NOBDEF size_t nob_temp_save(void);
  464. NOBDEF void nob_temp_rewind(size_t checkpoint);
  465. // Given any path returns the last part of that path.
  466. // "/path/to/a/file.c" -> "file.c"; "/path/to/a/directory" -> "directory"
  467. NOBDEF const char *nob_path_name(const char *path);
  468. NOBDEF bool nob_rename(const char *old_path, const char *new_path);
  469. NOBDEF int nob_needs_rebuild(const char *output_path, const char **input_paths, size_t input_paths_count);
  470. NOBDEF int nob_needs_rebuild1(const char *output_path, const char *input_path);
  471. NOBDEF int nob_file_exists(const char *file_path);
  472. NOBDEF const char *nob_get_current_dir_temp(void);
  473. NOBDEF bool nob_set_current_dir(const char *path);
  474. // TODO: we should probably document somewhere all the compiler we support
  475. // The nob_cc_* macros try to abstract away the specific compiler.
  476. // They are verify basic and not particularly flexible, but you can redefine them if you need to
  477. // or not use them at all and create your own abstraction on top of Nob_Cmd.
  478. #ifndef nob_cc
  479. # if _WIN32
  480. # if defined(__GNUC__)
  481. # define nob_cc(cmd) nob_cmd_append(cmd, "cc")
  482. # elif defined(__clang__)
  483. # define nob_cc(cmd) nob_cmd_append(cmd, "clang")
  484. # elif defined(_MSC_VER)
  485. # define nob_cc(cmd) nob_cmd_append(cmd, "cl.exe")
  486. # endif
  487. # else
  488. # define nob_cc(cmd) nob_cmd_append(cmd, "cc")
  489. # endif
  490. #endif // nob_cc
  491. #ifndef nob_cc_flags
  492. # if defined(_MSC_VER) && !defined(__clang__)
  493. # define nob_cc_flags(cmd) nob_cmd_append(cmd, "/W4", "/nologo", "/D_CRT_SECURE_NO_WARNINGS")
  494. # else
  495. # define nob_cc_flags(cmd) nob_cmd_append(cmd, "-Wall", "-Wextra")
  496. # endif
  497. #endif // nob_cc_output
  498. #ifndef nob_cc_output
  499. # if defined(_MSC_VER) && !defined(__clang__)
  500. # define nob_cc_output(cmd, output_path) nob_cmd_append(cmd, nob_temp_sprintf("/Fe:%s", (output_path)))
  501. # else
  502. # define nob_cc_output(cmd, output_path) nob_cmd_append(cmd, "-o", (output_path))
  503. # endif
  504. #endif // nob_cc_output
  505. #ifndef nob_cc_inputs
  506. # define nob_cc_inputs(cmd, ...) nob_cmd_append(cmd, __VA_ARGS__)
  507. #endif // nob_cc_inputs
  508. // TODO: add MinGW support for Go Rebuild Urself™ Technology and all the nob_cc_* macros above
  509. // Musializer contributors came up with a pretty interesting idea of an optional prefix macro which could be useful for
  510. // MinGW support:
  511. // https://github.com/tsoding/musializer/blob/b7578cc76b9ecb573d239acc9ccf5a04d3aba2c9/src_build/nob_win64_mingw.c#L3-L9
  512. // TODO: Maybe instead NOB_REBUILD_URSELF macro, the Go Rebuild Urself™ Technology should use the
  513. // user defined nob_cc_* macros instead?
  514. #ifndef NOB_REBUILD_URSELF
  515. # if defined(_WIN32)
  516. # if defined(__GNUC__)
  517. # define NOB_REBUILD_URSELF(binary_path, source_path) "gcc", "-o", binary_path, source_path
  518. # elif defined(__clang__)
  519. # define NOB_REBUILD_URSELF(binary_path, source_path) "clang", "-o", binary_path, source_path
  520. # elif defined(_MSC_VER)
  521. # define NOB_REBUILD_URSELF(binary_path, source_path) "cl.exe", nob_temp_sprintf("/Fe:%s", (binary_path)), source_path
  522. # endif
  523. # else
  524. # define NOB_REBUILD_URSELF(binary_path, source_path) "cc", "-o", binary_path, source_path
  525. # endif
  526. #endif
  527. // Go Rebuild Urself™ Technology
  528. //
  529. // How to use it:
  530. // int main(int argc, char** argv) {
  531. // NOB_GO_REBUILD_URSELF(argc, argv);
  532. // // actual work
  533. // return 0;
  534. // }
  535. //
  536. // After you added this macro every time you run ./nob it will detect
  537. // that you modified its original source code and will try to rebuild itself
  538. // before doing any actual work. So you only need to bootstrap your build system
  539. // once.
  540. //
  541. // The modification is detected by comparing the last modified times of the executable
  542. // and its source code. The same way the make utility usually does it.
  543. //
  544. // The rebuilding is done by using the NOB_REBUILD_URSELF macro which you can redefine
  545. // if you need a special way of bootstraping your build system. (which I personally
  546. // do not recommend since the whole idea of NoBuild is to keep the process of bootstrapping
  547. // as simple as possible and doing all of the actual work inside of ./nob)
  548. //
  549. NOBDEF void nob__go_rebuild_urself(int argc, char **argv, const char *source_path, ...);
  550. #define NOB_GO_REBUILD_URSELF(argc, argv) nob__go_rebuild_urself(argc, argv, __FILE__, NULL)
  551. // Sometimes your nob.c includes additional files, so you want the Go Rebuild Urself™ Technology to check
  552. // if they also were modified and rebuild nob.c accordingly. For that we have NOB_GO_REBUILD_URSELF_PLUS():
  553. // ```c
  554. // #define NOB_IMPLEMENTATION
  555. // #include "nob.h"
  556. //
  557. // #include "foo.c"
  558. // #include "bar.c"
  559. //
  560. // int main(int argc, char **argv)
  561. // {
  562. // NOB_GO_REBUILD_URSELF_PLUS(argc, argv, "foo.c", "bar.c");
  563. // // ...
  564. // return 0;
  565. // }
  566. #define NOB_GO_REBUILD_URSELF_PLUS(argc, argv, ...) nob__go_rebuild_urself(argc, argv, __FILE__, __VA_ARGS__, NULL);
  567. typedef struct {
  568. size_t count;
  569. const char *data;
  570. } Nob_String_View;
  571. NOBDEF const char *nob_temp_sv_to_cstr(Nob_String_View sv);
  572. NOBDEF Nob_String_View nob_sv_chop_by_delim(Nob_String_View *sv, char delim);
  573. NOBDEF Nob_String_View nob_sv_chop_left(Nob_String_View *sv, size_t n);
  574. NOBDEF Nob_String_View nob_sv_trim(Nob_String_View sv);
  575. NOBDEF Nob_String_View nob_sv_trim_left(Nob_String_View sv);
  576. NOBDEF Nob_String_View nob_sv_trim_right(Nob_String_View sv);
  577. NOBDEF bool nob_sv_eq(Nob_String_View a, Nob_String_View b);
  578. NOBDEF bool nob_sv_end_with(Nob_String_View sv, const char *cstr);
  579. NOBDEF bool nob_sv_starts_with(Nob_String_View sv, Nob_String_View expected_prefix);
  580. NOBDEF Nob_String_View nob_sv_from_cstr(const char *cstr);
  581. NOBDEF Nob_String_View nob_sv_from_parts(const char *data, size_t count);
  582. // nob_sb_to_sv() enables you to just view Nob_String_Builder as Nob_String_View
  583. #define nob_sb_to_sv(sb) nob_sv_from_parts((sb).items, (sb).count)
  584. // printf macros for String_View
  585. #ifndef SV_Fmt
  586. #define SV_Fmt "%.*s"
  587. #endif // SV_Fmt
  588. #ifndef SV_Arg
  589. #define SV_Arg(sv) (int) (sv).count, (sv).data
  590. #endif // SV_Arg
  591. // USAGE:
  592. // String_View name = ...;
  593. // printf("Name: "SV_Fmt"\n", SV_Arg(name));
  594. // DEPRECATED: Usage of the bundled minirent.h below is deprecated, because it introduces more
  595. // problems than it solves. It will be removed in the next major release of nob.h. In the meantime,
  596. // it is recommended to `#define NOB_NO_MINIRENT` if it causes problems for you.
  597. // TODO: Use NOB_DEPRECATED for minirent.h declarations
  598. // minirent.h HEADER BEGIN ////////////////////////////////////////
  599. // Copyright 2021 Alexey Kutepov <[email protected]>
  600. //
  601. // Permission is hereby granted, free of charge, to any person obtaining
  602. // a copy of this software and associated documentation files (the
  603. // "Software"), to deal in the Software without restriction, including
  604. // without limitation the rights to use, copy, modify, merge, publish,
  605. // distribute, sublicense, and/or sell copies of the Software, and to
  606. // permit persons to whom the Software is furnished to do so, subject to
  607. // the following conditions:
  608. //
  609. // The above copyright notice and this permission notice shall be
  610. // included in all copies or substantial portions of the Software.
  611. //
  612. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  613. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  614. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  615. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  616. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  617. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  618. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  619. //
  620. // ============================================================
  621. //
  622. // minirent — 0.0.1 — A subset of dirent interface for Windows.
  623. //
  624. // https://github.com/tsoding/minirent
  625. //
  626. // ============================================================
  627. //
  628. // ChangeLog (https://semver.org/ is implied)
  629. //
  630. // 0.0.2 Automatically include dirent.h on non-Windows
  631. // platforms
  632. // 0.0.1 First Official Release
  633. #if !defined(_WIN32) || defined(NOB_NO_MINIRENT)
  634. #include <dirent.h>
  635. #else // _WIN32
  636. #define WIN32_LEAN_AND_MEAN
  637. #include "windows.h"
  638. struct dirent
  639. {
  640. char d_name[MAX_PATH+1];
  641. };
  642. typedef struct DIR DIR;
  643. static DIR *opendir(const char *dirpath);
  644. static struct dirent *readdir(DIR *dirp);
  645. static int closedir(DIR *dirp);
  646. #endif // _WIN32
  647. // minirent.h HEADER END ////////////////////////////////////////
  648. #ifdef _WIN32
  649. NOBDEF char *nob_win32_error_message(DWORD err);
  650. #endif // _WIN32
  651. #endif // NOB_H_
  652. #ifdef NOB_IMPLEMENTATION
  653. // This is like nob_proc_wait() but waits asynchronously. Depending on the platform ms means different thing.
  654. // On Windows it means timeout. On POSIX it means for how long to sleep after checking if the process exited,
  655. // so to not peg the core too much. Since this API is kinda of weird, the function is private for now.
  656. static int nob__proc_wait_async(Nob_Proc proc, int ms);
  657. // Starts the process for the command. Its main purpose is to be the base for nob_cmd_run() and nob_cmd_run_opt().
  658. static Nob_Proc nob__cmd_start_process(Nob_Cmd cmd, Nob_Fd *fdin, Nob_Fd *fdout, Nob_Fd *fderr);
  659. // Any messages with the level below nob_minimal_log_level are going to be suppressed.
  660. Nob_Log_Level nob_minimal_log_level = NOB_INFO;
  661. #ifdef _WIN32
  662. // Base on https://stackoverflow.com/a/75644008
  663. // > .NET Core uses 4096 * sizeof(WCHAR) buffer on stack for FormatMessageW call. And...thats it.
  664. // >
  665. // > https://github.com/dotnet/runtime/blob/3b63eb1346f1ddbc921374a5108d025662fb5ffd/src/coreclr/utilcode/posterror.cpp#L264-L265
  666. #ifndef NOB_WIN32_ERR_MSG_SIZE
  667. #define NOB_WIN32_ERR_MSG_SIZE (4 * 1024)
  668. #endif // NOB_WIN32_ERR_MSG_SIZE
  669. NOBDEF char *nob_win32_error_message(DWORD err) {
  670. static char win32ErrMsg[NOB_WIN32_ERR_MSG_SIZE] = {0};
  671. DWORD errMsgSize = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, LANG_USER_DEFAULT, win32ErrMsg,
  672. NOB_WIN32_ERR_MSG_SIZE, NULL);
  673. if (errMsgSize == 0) {
  674. if (GetLastError() != ERROR_MR_MID_NOT_FOUND) {
  675. if (sprintf(win32ErrMsg, "Could not get error message for 0x%lX", err) > 0) {
  676. return (char *)&win32ErrMsg;
  677. } else {
  678. return NULL;
  679. }
  680. } else {
  681. if (sprintf(win32ErrMsg, "Invalid Windows Error code (0x%lX)", err) > 0) {
  682. return (char *)&win32ErrMsg;
  683. } else {
  684. return NULL;
  685. }
  686. }
  687. }
  688. while (errMsgSize > 1 && isspace(win32ErrMsg[errMsgSize - 1])) {
  689. win32ErrMsg[--errMsgSize] = '\0';
  690. }
  691. return win32ErrMsg;
  692. }
  693. #endif // _WIN32
  694. // The implementation idea is stolen from https://github.com/zhiayang/nabs
  695. NOBDEF void nob__go_rebuild_urself(int argc, char **argv, const char *source_path, ...)
  696. {
  697. const char *binary_path = nob_shift(argv, argc);
  698. #ifdef _WIN32
  699. // On Windows executables almost always invoked without extension, so
  700. // it's ./nob, not ./nob.exe. For renaming the extension is a must.
  701. if (!nob_sv_end_with(nob_sv_from_cstr(binary_path), ".exe")) {
  702. binary_path = nob_temp_sprintf("%s.exe", binary_path);
  703. }
  704. #endif
  705. Nob_File_Paths source_paths = {0};
  706. nob_da_append(&source_paths, source_path);
  707. va_list args;
  708. va_start(args, source_path);
  709. for (;;) {
  710. const char *path = va_arg(args, const char*);
  711. if (path == NULL) break;
  712. nob_da_append(&source_paths, path);
  713. }
  714. va_end(args);
  715. int rebuild_is_needed = nob_needs_rebuild(binary_path, source_paths.items, source_paths.count);
  716. if (rebuild_is_needed < 0) exit(1); // error
  717. if (!rebuild_is_needed) { // no rebuild is needed
  718. NOB_FREE(source_paths.items);
  719. return;
  720. }
  721. Nob_Cmd cmd = {0};
  722. const char *old_binary_path = nob_temp_sprintf("%s.old", binary_path);
  723. if (!nob_rename(binary_path, old_binary_path)) exit(1);
  724. nob_cmd_append(&cmd, NOB_REBUILD_URSELF(binary_path, source_path));
  725. Nob_Cmd_Opt opt = {0};
  726. if (!nob_cmd_run_opt(&cmd, opt)) {
  727. nob_rename(old_binary_path, binary_path);
  728. exit(1);
  729. }
  730. #ifdef NOB_EXPERIMENTAL_DELETE_OLD
  731. // TODO: this is an experimental behavior behind a compilation flag.
  732. // Once it is confirmed that it does not cause much problems on both POSIX and Windows
  733. // we may turn it on by default.
  734. nob_delete_file(old_binary_path);
  735. #endif // NOB_EXPERIMENTAL_DELETE_OLD
  736. nob_cmd_append(&cmd, binary_path);
  737. nob_da_append_many(&cmd, argv, argc);
  738. if (!nob_cmd_run_opt(&cmd, opt)) exit(1);
  739. exit(0);
  740. }
  741. static size_t nob_temp_size = 0;
  742. static char nob_temp[NOB_TEMP_CAPACITY] = {0};
  743. NOBDEF bool nob_mkdir_if_not_exists(const char *path)
  744. {
  745. #ifdef _WIN32
  746. int result = _mkdir(path);
  747. #else
  748. int result = mkdir(path, 0755);
  749. #endif
  750. if (result < 0) {
  751. if (errno == EEXIST) {
  752. nob_log(NOB_INFO, "directory `%s` already exists", path);
  753. return true;
  754. }
  755. nob_log(NOB_ERROR, "could not create directory `%s`: %s", path, strerror(errno));
  756. return false;
  757. }
  758. nob_log(NOB_INFO, "created directory `%s`", path);
  759. return true;
  760. }
  761. NOBDEF bool nob_copy_file(const char *src_path, const char *dst_path)
  762. {
  763. nob_log(NOB_INFO, "copying %s -> %s", src_path, dst_path);
  764. #ifdef _WIN32
  765. if (!CopyFile(src_path, dst_path, FALSE)) {
  766. nob_log(NOB_ERROR, "Could not copy file: %s", nob_win32_error_message(GetLastError()));
  767. return false;
  768. }
  769. return true;
  770. #else
  771. int src_fd = -1;
  772. int dst_fd = -1;
  773. size_t buf_size = 32*1024;
  774. char *buf = (char*)NOB_REALLOC(NULL, buf_size);
  775. NOB_ASSERT(buf != NULL && "Buy more RAM lol!!");
  776. bool result = true;
  777. src_fd = open(src_path, O_RDONLY);
  778. if (src_fd < 0) {
  779. nob_log(NOB_ERROR, "Could not open file %s: %s", src_path, strerror(errno));
  780. nob_return_defer(false);
  781. }
  782. struct stat src_stat;
  783. if (fstat(src_fd, &src_stat) < 0) {
  784. nob_log(NOB_ERROR, "Could not get mode of file %s: %s", src_path, strerror(errno));
  785. nob_return_defer(false);
  786. }
  787. dst_fd = open(dst_path, O_CREAT | O_TRUNC | O_WRONLY, src_stat.st_mode);
  788. if (dst_fd < 0) {
  789. nob_log(NOB_ERROR, "Could not create file %s: %s", dst_path, strerror(errno));
  790. nob_return_defer(false);
  791. }
  792. for (;;) {
  793. ssize_t n = read(src_fd, buf, buf_size);
  794. if (n == 0) break;
  795. if (n < 0) {
  796. nob_log(NOB_ERROR, "Could not read from file %s: %s", src_path, strerror(errno));
  797. nob_return_defer(false);
  798. }
  799. char *buf2 = buf;
  800. while (n > 0) {
  801. ssize_t m = write(dst_fd, buf2, n);
  802. if (m < 0) {
  803. nob_log(NOB_ERROR, "Could not write to file %s: %s", dst_path, strerror(errno));
  804. nob_return_defer(false);
  805. }
  806. n -= m;
  807. buf2 += m;
  808. }
  809. }
  810. defer:
  811. NOB_FREE(buf);
  812. close(src_fd);
  813. close(dst_fd);
  814. return result;
  815. #endif
  816. }
  817. NOBDEF void nob_cmd_render(Nob_Cmd cmd, Nob_String_Builder *render)
  818. {
  819. for (size_t i = 0; i < cmd.count; ++i) {
  820. const char *arg = cmd.items[i];
  821. if (arg == NULL) break;
  822. if (i > 0) nob_sb_append_cstr(render, " ");
  823. if (!strchr(arg, ' ')) {
  824. nob_sb_append_cstr(render, arg);
  825. } else {
  826. nob_da_append(render, '\'');
  827. nob_sb_append_cstr(render, arg);
  828. nob_da_append(render, '\'');
  829. }
  830. }
  831. }
  832. #ifdef _WIN32
  833. // https://learn.microsoft.com/en-gb/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way
  834. static void nob__win32_cmd_quote(Nob_Cmd cmd, Nob_String_Builder *quoted)
  835. {
  836. for (size_t i = 0; i < cmd.count; ++i) {
  837. const char *arg = cmd.items[i];
  838. if (arg == NULL) break;
  839. size_t len = strlen(arg);
  840. if (i > 0) nob_da_append(quoted, ' ');
  841. if (len != 0 && NULL == strpbrk(arg, " \t\n\v\"")) {
  842. // no need to quote
  843. nob_da_append_many(quoted, arg, len);
  844. } else {
  845. // we need to escape:
  846. // 1. double quotes in the original arg
  847. // 2. consequent backslashes before a double quote
  848. size_t backslashes = 0;
  849. nob_da_append(quoted, '\"');
  850. for (size_t j = 0; j < len; ++j) {
  851. char x = arg[j];
  852. if (x == '\\') {
  853. backslashes += 1;
  854. } else {
  855. if (x == '\"') {
  856. // escape backslashes (if any) and the double quote
  857. for (size_t k = 0; k < 1+backslashes; ++k) {
  858. nob_da_append(quoted, '\\');
  859. }
  860. }
  861. backslashes = 0;
  862. }
  863. nob_da_append(quoted, x);
  864. }
  865. // escape backslashes (if any)
  866. for (size_t k = 0; k < backslashes; ++k) {
  867. nob_da_append(quoted, '\\');
  868. }
  869. nob_da_append(quoted, '\"');
  870. }
  871. }
  872. }
  873. #endif
  874. NOBDEF int nob_nprocs(void)
  875. {
  876. #ifdef _WIN32
  877. SYSTEM_INFO siSysInfo;
  878. GetSystemInfo(&siSysInfo);
  879. return siSysInfo.dwNumberOfProcessors;
  880. #else
  881. return sysconf(_SC_NPROCESSORS_ONLN);
  882. #endif
  883. }
  884. NOBDEF bool nob_cmd_run_opt(Nob_Cmd *cmd, Nob_Cmd_Opt opt)
  885. {
  886. bool result = true;
  887. Nob_Fd fdin = NOB_INVALID_FD;
  888. Nob_Fd fdout = NOB_INVALID_FD;
  889. Nob_Fd fderr = NOB_INVALID_FD;
  890. Nob_Fd *opt_fdin = NULL;
  891. Nob_Fd *opt_fdout = NULL;
  892. Nob_Fd *opt_fderr = NULL;
  893. size_t max_procs = opt.max_procs > 0 ? opt.max_procs : (size_t) nob_nprocs() + 1;
  894. if (opt.async && max_procs > 0) {
  895. while (opt.async->count >= max_procs) {
  896. for (size_t i = 0; i < opt.async->count; ++i) {
  897. int ret = nob__proc_wait_async(opt.async->items[i], 1);
  898. if (ret < 0) nob_return_defer(false);
  899. if (ret) {
  900. nob_da_remove_unordered(opt.async, i);
  901. break;
  902. }
  903. }
  904. }
  905. }
  906. if (opt.stdin_path) {
  907. fdin = nob_fd_open_for_read(opt.stdin_path);
  908. if (fdin == NOB_INVALID_FD) nob_return_defer(false);
  909. opt_fdin = &fdin;
  910. }
  911. if (opt.stdout_path) {
  912. fdout = nob_fd_open_for_write(opt.stdout_path);
  913. if (fdout == NOB_INVALID_FD) nob_return_defer(false);
  914. opt_fdout = &fdout;
  915. }
  916. if (opt.stderr_path) {
  917. fderr = nob_fd_open_for_write(opt.stderr_path);
  918. if (fderr == NOB_INVALID_FD) nob_return_defer(false);
  919. opt_fderr = &fderr;
  920. }
  921. Nob_Proc proc = nob__cmd_start_process(*cmd, opt_fdin, opt_fdout, opt_fderr);
  922. if (opt.async) {
  923. if (proc == NOB_INVALID_PROC) nob_return_defer(false);
  924. nob_da_append(opt.async, proc);
  925. } else {
  926. if (!nob_proc_wait(proc)) nob_return_defer(false);
  927. }
  928. defer:
  929. if (opt_fdin) nob_fd_close(*opt_fdin);
  930. if (opt_fdout) nob_fd_close(*opt_fdout);
  931. if (opt_fderr) nob_fd_close(*opt_fderr);
  932. cmd->count = 0;
  933. return result;
  934. }
  935. // The maximum time span representable is 584 years.
  936. NOBDEF uint64_t nob_nanos_since_unspecified_epoch(void)
  937. {
  938. #ifdef _WIN32
  939. LARGE_INTEGER Time;
  940. QueryPerformanceCounter(&Time);
  941. static LARGE_INTEGER Frequency = {0};
  942. if (Frequency.QuadPart == 0) {
  943. QueryPerformanceFrequency(&Frequency);
  944. }
  945. uint64_t Secs = Time.QuadPart / Frequency.QuadPart;
  946. uint64_t Nanos = Time.QuadPart % Frequency.QuadPart * NOB_NANOS_PER_SEC / Frequency.QuadPart;
  947. return NOB_NANOS_PER_SEC * Secs + Nanos;
  948. #else
  949. struct timespec ts;
  950. clock_gettime(CLOCK_MONOTONIC, &ts);
  951. return NOB_NANOS_PER_SEC * ts.tv_sec + ts.tv_nsec;
  952. #endif // _WIN32
  953. }
  954. NOBDEF Nob_Proc nob_cmd_run_async_redirect(Nob_Cmd cmd, Nob_Cmd_Redirect redirect)
  955. {
  956. return nob__cmd_start_process(cmd, redirect.fdin, redirect.fdout, redirect.fderr);
  957. }
  958. static Nob_Proc nob__cmd_start_process(Nob_Cmd cmd, Nob_Fd *fdin, Nob_Fd *fdout, Nob_Fd *fderr)
  959. {
  960. if (cmd.count < 1) {
  961. nob_log(NOB_ERROR, "Could not run empty command");
  962. return NOB_INVALID_PROC;
  963. }
  964. Nob_String_Builder sb = {0};
  965. nob_cmd_render(cmd, &sb);
  966. nob_sb_append_null(&sb);
  967. nob_log(NOB_INFO, "CMD: %s", sb.items);
  968. nob_sb_free(sb);
  969. memset(&sb, 0, sizeof(sb));
  970. #ifdef _WIN32
  971. // https://docs.microsoft.com/en-us/windows/win32/procthread/creating-a-child-process-with-redirected-input-and-output
  972. STARTUPINFO siStartInfo;
  973. ZeroMemory(&siStartInfo, sizeof(siStartInfo));
  974. siStartInfo.cb = sizeof(STARTUPINFO);
  975. // NOTE: theoretically setting NULL to std handles should not be a problem
  976. // https://docs.microsoft.com/en-us/windows/console/getstdhandle?redirectedfrom=MSDN#attachdetach-behavior
  977. // TODO: check for errors in GetStdHandle
  978. siStartInfo.hStdError = fderr ? *fderr : GetStdHandle(STD_ERROR_HANDLE);
  979. siStartInfo.hStdOutput = fdout ? *fdout : GetStdHandle(STD_OUTPUT_HANDLE);
  980. siStartInfo.hStdInput = fdin ? *fdin : GetStdHandle(STD_INPUT_HANDLE);
  981. siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
  982. PROCESS_INFORMATION piProcInfo;
  983. ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));
  984. nob__win32_cmd_quote(cmd, &sb);
  985. nob_sb_append_null(&sb);
  986. BOOL bSuccess = CreateProcessA(NULL, sb.items, NULL, NULL, TRUE, 0, NULL, NULL, &siStartInfo, &piProcInfo);
  987. nob_sb_free(sb);
  988. if (!bSuccess) {
  989. nob_log(NOB_ERROR, "Could not create child process for %s: %s", cmd.items[0], nob_win32_error_message(GetLastError()));
  990. return NOB_INVALID_PROC;
  991. }
  992. CloseHandle(piProcInfo.hThread);
  993. return piProcInfo.hProcess;
  994. #else
  995. pid_t cpid = fork();
  996. if (cpid < 0) {
  997. nob_log(NOB_ERROR, "Could not fork child process: %s", strerror(errno));
  998. return NOB_INVALID_PROC;
  999. }
  1000. if (cpid == 0) {
  1001. if (fdin) {
  1002. if (dup2(*fdin, STDIN_FILENO) < 0) {
  1003. nob_log(NOB_ERROR, "Could not setup stdin for child process: %s", strerror(errno));
  1004. exit(1);
  1005. }
  1006. }
  1007. if (fdout) {
  1008. if (dup2(*fdout, STDOUT_FILENO) < 0) {
  1009. nob_log(NOB_ERROR, "Could not setup stdout for child process: %s", strerror(errno));
  1010. exit(1);
  1011. }
  1012. }
  1013. if (fderr) {
  1014. if (dup2(*fderr, STDERR_FILENO) < 0) {
  1015. nob_log(NOB_ERROR, "Could not setup stderr for child process: %s", strerror(errno));
  1016. exit(1);
  1017. }
  1018. }
  1019. // NOTE: This leaks a bit of memory in the child process.
  1020. // But do we actually care? It's a one off leak anyway...
  1021. Nob_Cmd cmd_null = {0};
  1022. nob_da_append_many(&cmd_null, cmd.items, cmd.count);
  1023. nob_cmd_append(&cmd_null, NULL);
  1024. if (execvp(cmd.items[0], (char * const*) cmd_null.items) < 0) {
  1025. nob_log(NOB_ERROR, "Could not exec child process for %s: %s", cmd.items[0], strerror(errno));
  1026. exit(1);
  1027. }
  1028. NOB_UNREACHABLE("nob_cmd_run_async_redirect");
  1029. }
  1030. return cpid;
  1031. #endif
  1032. }
  1033. NOBDEF Nob_Proc nob_cmd_run_async(Nob_Cmd cmd)
  1034. {
  1035. return nob__cmd_start_process(cmd, NULL, NULL, NULL);
  1036. }
  1037. NOBDEF Nob_Proc nob_cmd_run_async_and_reset(Nob_Cmd *cmd)
  1038. {
  1039. Nob_Proc proc = nob__cmd_start_process(*cmd, NULL, NULL, NULL);
  1040. cmd->count = 0;
  1041. return proc;
  1042. }
  1043. NOBDEF Nob_Proc nob_cmd_run_async_redirect_and_reset(Nob_Cmd *cmd, Nob_Cmd_Redirect redirect)
  1044. {
  1045. Nob_Proc proc = nob__cmd_start_process(*cmd, redirect.fdin, redirect.fdout, redirect.fderr);
  1046. cmd->count = 0;
  1047. if (redirect.fdin) {
  1048. nob_fd_close(*redirect.fdin);
  1049. *redirect.fdin = NOB_INVALID_FD;
  1050. }
  1051. if (redirect.fdout) {
  1052. nob_fd_close(*redirect.fdout);
  1053. *redirect.fdout = NOB_INVALID_FD;
  1054. }
  1055. if (redirect.fderr) {
  1056. nob_fd_close(*redirect.fderr);
  1057. *redirect.fderr = NOB_INVALID_FD;
  1058. }
  1059. return proc;
  1060. }
  1061. NOBDEF Nob_Fd nob_fd_open_for_read(const char *path)
  1062. {
  1063. #ifndef _WIN32
  1064. Nob_Fd result = open(path, O_RDONLY);
  1065. if (result < 0) {
  1066. nob_log(NOB_ERROR, "Could not open file %s: %s", path, strerror(errno));
  1067. return NOB_INVALID_FD;
  1068. }
  1069. return result;
  1070. #else
  1071. // https://docs.microsoft.com/en-us/windows/win32/fileio/opening-a-file-for-reading-or-writing
  1072. SECURITY_ATTRIBUTES saAttr = {0};
  1073. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  1074. saAttr.bInheritHandle = TRUE;
  1075. Nob_Fd result = CreateFile(
  1076. path,
  1077. GENERIC_READ,
  1078. 0,
  1079. &saAttr,
  1080. OPEN_EXISTING,
  1081. FILE_ATTRIBUTE_READONLY,
  1082. NULL);
  1083. if (result == INVALID_HANDLE_VALUE) {
  1084. nob_log(NOB_ERROR, "Could not open file %s: %s", path, nob_win32_error_message(GetLastError()));
  1085. return NOB_INVALID_FD;
  1086. }
  1087. return result;
  1088. #endif // _WIN32
  1089. }
  1090. NOBDEF Nob_Fd nob_fd_open_for_write(const char *path)
  1091. {
  1092. #ifndef _WIN32
  1093. Nob_Fd result = open(path,
  1094. O_WRONLY | O_CREAT | O_TRUNC,
  1095. S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
  1096. if (result < 0) {
  1097. nob_log(NOB_ERROR, "could not open file %s: %s", path, strerror(errno));
  1098. return NOB_INVALID_FD;
  1099. }
  1100. return result;
  1101. #else
  1102. SECURITY_ATTRIBUTES saAttr = {0};
  1103. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  1104. saAttr.bInheritHandle = TRUE;
  1105. Nob_Fd result = CreateFile(
  1106. path, // name of the write
  1107. GENERIC_WRITE, // open for writing
  1108. 0, // do not share
  1109. &saAttr, // default security
  1110. CREATE_ALWAYS, // create always
  1111. FILE_ATTRIBUTE_NORMAL, // normal file
  1112. NULL // no attr. template
  1113. );
  1114. if (result == INVALID_HANDLE_VALUE) {
  1115. nob_log(NOB_ERROR, "Could not open file %s: %s", path, nob_win32_error_message(GetLastError()));
  1116. return NOB_INVALID_FD;
  1117. }
  1118. return result;
  1119. #endif // _WIN32
  1120. }
  1121. NOBDEF void nob_fd_close(Nob_Fd fd)
  1122. {
  1123. #ifdef _WIN32
  1124. CloseHandle(fd);
  1125. #else
  1126. close(fd);
  1127. #endif // _WIN32
  1128. }
  1129. NOBDEF bool nob_procs_wait(Nob_Procs procs)
  1130. {
  1131. bool success = true;
  1132. for (size_t i = 0; i < procs.count; ++i) {
  1133. success = nob_proc_wait(procs.items[i]) && success;
  1134. }
  1135. return success;
  1136. }
  1137. NOBDEF bool nob_procs_flush(Nob_Procs *procs)
  1138. {
  1139. bool success = nob_procs_wait(*procs);
  1140. procs->count = 0;
  1141. return success;
  1142. }
  1143. NOBDEF bool nob_procs_wait_and_reset(Nob_Procs *procs)
  1144. {
  1145. return nob_procs_flush(procs);
  1146. }
  1147. NOBDEF bool nob_proc_wait(Nob_Proc proc)
  1148. {
  1149. if (proc == NOB_INVALID_PROC) return false;
  1150. #ifdef _WIN32
  1151. DWORD result = WaitForSingleObject(
  1152. proc, // HANDLE hHandle,
  1153. INFINITE // DWORD dwMilliseconds
  1154. );
  1155. if (result == WAIT_FAILED) {
  1156. nob_log(NOB_ERROR, "could not wait on child process: %s", nob_win32_error_message(GetLastError()));
  1157. return false;
  1158. }
  1159. DWORD exit_status;
  1160. if (!GetExitCodeProcess(proc, &exit_status)) {
  1161. nob_log(NOB_ERROR, "could not get process exit code: %s", nob_win32_error_message(GetLastError()));
  1162. return false;
  1163. }
  1164. if (exit_status != 0) {
  1165. nob_log(NOB_ERROR, "command exited with exit code %lu", exit_status);
  1166. return false;
  1167. }
  1168. CloseHandle(proc);
  1169. return true;
  1170. #else
  1171. for (;;) {
  1172. int wstatus = 0;
  1173. if (waitpid(proc, &wstatus, 0) < 0) {
  1174. nob_log(NOB_ERROR, "could not wait on command (pid %d): %s", proc, strerror(errno));
  1175. return false;
  1176. }
  1177. if (WIFEXITED(wstatus)) {
  1178. int exit_status = WEXITSTATUS(wstatus);
  1179. if (exit_status != 0) {
  1180. nob_log(NOB_ERROR, "command exited with exit code %d", exit_status);
  1181. return false;
  1182. }
  1183. break;
  1184. }
  1185. if (WIFSIGNALED(wstatus)) {
  1186. nob_log(NOB_ERROR, "command process was terminated by signal %d", WTERMSIG(wstatus));
  1187. return false;
  1188. }
  1189. }
  1190. return true;
  1191. #endif
  1192. }
  1193. static int nob__proc_wait_async(Nob_Proc proc, int ms)
  1194. {
  1195. if (proc == NOB_INVALID_PROC) return false;
  1196. #ifdef _WIN32
  1197. DWORD result = WaitForSingleObject(
  1198. proc, // HANDLE hHandle,
  1199. ms // DWORD dwMilliseconds
  1200. );
  1201. if (result == WAIT_TIMEOUT) {
  1202. return 0;
  1203. }
  1204. if (result == WAIT_FAILED) {
  1205. nob_log(NOB_ERROR, "could not wait on child process: %s", nob_win32_error_message(GetLastError()));
  1206. return -1;
  1207. }
  1208. DWORD exit_status;
  1209. if (!GetExitCodeProcess(proc, &exit_status)) {
  1210. nob_log(NOB_ERROR, "could not get process exit code: %s", nob_win32_error_message(GetLastError()));
  1211. return -1;
  1212. }
  1213. if (exit_status != 0) {
  1214. nob_log(NOB_ERROR, "command exited with exit code %lu", exit_status);
  1215. return -1;
  1216. }
  1217. CloseHandle(proc);
  1218. return 1;
  1219. #else
  1220. long ns = ms*1000*1000;
  1221. struct timespec duration = {
  1222. .tv_sec = ns/(1000*1000*1000),
  1223. .tv_nsec = ns%(1000*1000*1000),
  1224. };
  1225. int wstatus = 0;
  1226. pid_t pid = waitpid(proc, &wstatus, WNOHANG);
  1227. if (pid < 0) {
  1228. nob_log(NOB_ERROR, "could not wait on command (pid %d): %s", proc, strerror(errno));
  1229. return -1;
  1230. }
  1231. if (pid == 0) {
  1232. nanosleep(&duration, NULL);
  1233. return 0;
  1234. }
  1235. if (WIFEXITED(wstatus)) {
  1236. int exit_status = WEXITSTATUS(wstatus);
  1237. if (exit_status != 0) {
  1238. nob_log(NOB_ERROR, "command exited with exit code %d", exit_status);
  1239. return -1;
  1240. }
  1241. return 1;
  1242. }
  1243. if (WIFSIGNALED(wstatus)) {
  1244. nob_log(NOB_ERROR, "command process was terminated by signal %d", WTERMSIG(wstatus));
  1245. return -1;
  1246. }
  1247. nanosleep(&duration, NULL);
  1248. return 0;
  1249. #endif
  1250. }
  1251. NOBDEF bool nob_procs_append_with_flush(Nob_Procs *procs, Nob_Proc proc, size_t max_procs_count)
  1252. {
  1253. nob_da_append(procs, proc);
  1254. if (procs->count >= max_procs_count) {
  1255. if (!nob_procs_flush(procs)) return false;
  1256. }
  1257. return true;
  1258. }
  1259. NOBDEF bool nob_cmd_run_sync_redirect(Nob_Cmd cmd, Nob_Cmd_Redirect redirect)
  1260. {
  1261. Nob_Proc p = nob__cmd_start_process(cmd, redirect.fdin, redirect.fdout, redirect.fderr);
  1262. return nob_proc_wait(p);
  1263. }
  1264. NOBDEF bool nob_cmd_run_sync(Nob_Cmd cmd)
  1265. {
  1266. Nob_Proc p = nob__cmd_start_process(cmd, NULL, NULL, NULL);
  1267. return nob_proc_wait(p);
  1268. }
  1269. NOBDEF bool nob_cmd_run_sync_and_reset(Nob_Cmd *cmd)
  1270. {
  1271. Nob_Proc p = nob__cmd_start_process(*cmd, NULL, NULL, NULL);
  1272. cmd->count = 0;
  1273. return nob_proc_wait(p);
  1274. }
  1275. NOBDEF bool nob_cmd_run_sync_redirect_and_reset(Nob_Cmd *cmd, Nob_Cmd_Redirect redirect)
  1276. {
  1277. Nob_Proc p = nob__cmd_start_process(*cmd, redirect.fdin, redirect.fdout, redirect.fderr);
  1278. cmd->count = 0;
  1279. if (redirect.fdin) {
  1280. nob_fd_close(*redirect.fdin);
  1281. *redirect.fdin = NOB_INVALID_FD;
  1282. }
  1283. if (redirect.fdout) {
  1284. nob_fd_close(*redirect.fdout);
  1285. *redirect.fdout = NOB_INVALID_FD;
  1286. }
  1287. if (redirect.fderr) {
  1288. nob_fd_close(*redirect.fderr);
  1289. *redirect.fderr = NOB_INVALID_FD;
  1290. }
  1291. return nob_proc_wait(p);
  1292. }
  1293. NOBDEF void nob_log(Nob_Log_Level level, const char *fmt, ...)
  1294. {
  1295. if (level < nob_minimal_log_level) return;
  1296. switch (level) {
  1297. case NOB_INFO:
  1298. fprintf(stderr, "[INFO] ");
  1299. break;
  1300. case NOB_WARNING:
  1301. fprintf(stderr, "[WARNING] ");
  1302. break;
  1303. case NOB_ERROR:
  1304. fprintf(stderr, "[ERROR] ");
  1305. break;
  1306. case NOB_NO_LOGS: return;
  1307. default:
  1308. NOB_UNREACHABLE("nob_log");
  1309. }
  1310. va_list args;
  1311. va_start(args, fmt);
  1312. vfprintf(stderr, fmt, args);
  1313. va_end(args);
  1314. fprintf(stderr, "\n");
  1315. }
  1316. NOBDEF bool nob_read_entire_dir(const char *parent, Nob_File_Paths *children)
  1317. {
  1318. bool result = true;
  1319. DIR *dir = NULL;
  1320. struct dirent *ent = NULL;
  1321. dir = opendir(parent);
  1322. if (dir == NULL) {
  1323. #ifdef _WIN32
  1324. nob_log(NOB_ERROR, "Could not open directory %s: %s", parent, nob_win32_error_message(GetLastError()));
  1325. #else
  1326. nob_log(NOB_ERROR, "Could not open directory %s: %s", parent, strerror(errno));
  1327. #endif // _WIN32
  1328. nob_return_defer(false);
  1329. }
  1330. errno = 0;
  1331. ent = readdir(dir);
  1332. while (ent != NULL) {
  1333. nob_da_append(children, nob_temp_strdup(ent->d_name));
  1334. ent = readdir(dir);
  1335. }
  1336. if (errno != 0) {
  1337. #ifdef _WIN32
  1338. nob_log(NOB_ERROR, "Could not read directory %s: %s", parent, nob_win32_error_message(GetLastError()));
  1339. #else
  1340. nob_log(NOB_ERROR, "Could not read directory %s: %s", parent, strerror(errno));
  1341. #endif // _WIN32
  1342. nob_return_defer(false);
  1343. }
  1344. defer:
  1345. if (dir) closedir(dir);
  1346. return result;
  1347. }
  1348. NOBDEF bool nob_write_entire_file(const char *path, const void *data, size_t size)
  1349. {
  1350. bool result = true;
  1351. const char *buf = NULL;
  1352. FILE *f = fopen(path, "wb");
  1353. if (f == NULL) {
  1354. nob_log(NOB_ERROR, "Could not open file %s for writing: %s\n", path, strerror(errno));
  1355. nob_return_defer(false);
  1356. }
  1357. // len
  1358. // v
  1359. // aaaaaaaaaa
  1360. // ^
  1361. // data
  1362. buf = (const char*)data;
  1363. while (size > 0) {
  1364. size_t n = fwrite(buf, 1, size, f);
  1365. if (ferror(f)) {
  1366. nob_log(NOB_ERROR, "Could not write into file %s: %s\n", path, strerror(errno));
  1367. nob_return_defer(false);
  1368. }
  1369. size -= n;
  1370. buf += n;
  1371. }
  1372. defer:
  1373. if (f) fclose(f);
  1374. return result;
  1375. }
  1376. NOBDEF Nob_File_Type nob_get_file_type(const char *path)
  1377. {
  1378. #ifdef _WIN32
  1379. DWORD attr = GetFileAttributesA(path);
  1380. if (attr == INVALID_FILE_ATTRIBUTES) {
  1381. nob_log(NOB_ERROR, "Could not get file attributes of %s: %s", path, nob_win32_error_message(GetLastError()));
  1382. return -1;
  1383. }
  1384. if (attr & FILE_ATTRIBUTE_DIRECTORY) return NOB_FILE_DIRECTORY;
  1385. // TODO: detect symlinks on Windows (whatever that means on Windows anyway)
  1386. return NOB_FILE_REGULAR;
  1387. #else // _WIN32
  1388. struct stat statbuf;
  1389. if (lstat(path, &statbuf) < 0) {
  1390. nob_log(NOB_ERROR, "Could not get stat of %s: %s", path, strerror(errno));
  1391. return (Nob_File_Type)(-1);
  1392. }
  1393. if (S_ISREG(statbuf.st_mode)) return NOB_FILE_REGULAR;
  1394. if (S_ISDIR(statbuf.st_mode)) return NOB_FILE_DIRECTORY;
  1395. if (S_ISLNK(statbuf.st_mode)) return NOB_FILE_SYMLINK;
  1396. return NOB_FILE_OTHER;
  1397. #endif // _WIN32
  1398. }
  1399. NOBDEF bool nob_delete_file(const char *path)
  1400. {
  1401. nob_log(NOB_INFO, "deleting %s", path);
  1402. #ifdef _WIN32
  1403. if (!DeleteFileA(path)) {
  1404. nob_log(NOB_ERROR, "Could not delete file %s: %s", path, nob_win32_error_message(GetLastError()));
  1405. return false;
  1406. }
  1407. return true;
  1408. #else
  1409. if (remove(path) < 0) {
  1410. nob_log(NOB_ERROR, "Could not delete file %s: %s", path, strerror(errno));
  1411. return false;
  1412. }
  1413. return true;
  1414. #endif // _WIN32
  1415. }
  1416. NOBDEF bool nob_copy_directory_recursively(const char *src_path, const char *dst_path)
  1417. {
  1418. bool result = true;
  1419. Nob_File_Paths children = {0};
  1420. Nob_String_Builder src_sb = {0};
  1421. Nob_String_Builder dst_sb = {0};
  1422. size_t temp_checkpoint = nob_temp_save();
  1423. Nob_File_Type type = nob_get_file_type(src_path);
  1424. if (type < 0) return false;
  1425. switch (type) {
  1426. case NOB_FILE_DIRECTORY: {
  1427. if (!nob_mkdir_if_not_exists(dst_path)) nob_return_defer(false);
  1428. if (!nob_read_entire_dir(src_path, &children)) nob_return_defer(false);
  1429. for (size_t i = 0; i < children.count; ++i) {
  1430. if (strcmp(children.items[i], ".") == 0) continue;
  1431. if (strcmp(children.items[i], "..") == 0) continue;
  1432. src_sb.count = 0;
  1433. nob_sb_append_cstr(&src_sb, src_path);
  1434. nob_sb_append_cstr(&src_sb, "/");
  1435. nob_sb_append_cstr(&src_sb, children.items[i]);
  1436. nob_sb_append_null(&src_sb);
  1437. dst_sb.count = 0;
  1438. nob_sb_append_cstr(&dst_sb, dst_path);
  1439. nob_sb_append_cstr(&dst_sb, "/");
  1440. nob_sb_append_cstr(&dst_sb, children.items[i]);
  1441. nob_sb_append_null(&dst_sb);
  1442. if (!nob_copy_directory_recursively(src_sb.items, dst_sb.items)) {
  1443. nob_return_defer(false);
  1444. }
  1445. }
  1446. } break;
  1447. case NOB_FILE_REGULAR: {
  1448. if (!nob_copy_file(src_path, dst_path)) {
  1449. nob_return_defer(false);
  1450. }
  1451. } break;
  1452. case NOB_FILE_SYMLINK: {
  1453. nob_log(NOB_WARNING, "TODO: Copying symlinks is not supported yet");
  1454. } break;
  1455. case NOB_FILE_OTHER: {
  1456. nob_log(NOB_ERROR, "Unsupported type of file %s", src_path);
  1457. nob_return_defer(false);
  1458. } break;
  1459. default: NOB_UNREACHABLE("nob_copy_directory_recursively");
  1460. }
  1461. defer:
  1462. nob_temp_rewind(temp_checkpoint);
  1463. nob_da_free(src_sb);
  1464. nob_da_free(dst_sb);
  1465. nob_da_free(children);
  1466. return result;
  1467. }
  1468. NOBDEF char *nob_temp_strdup(const char *cstr)
  1469. {
  1470. size_t n = strlen(cstr);
  1471. char *result = (char*)nob_temp_alloc(n + 1);
  1472. NOB_ASSERT(result != NULL && "Increase NOB_TEMP_CAPACITY");
  1473. memcpy(result, cstr, n);
  1474. result[n] = '\0';
  1475. return result;
  1476. }
  1477. NOBDEF void *nob_temp_alloc(size_t requested_size)
  1478. {
  1479. size_t word_size = sizeof(uintptr_t);
  1480. size_t size = (requested_size + word_size - 1)/word_size*word_size;
  1481. if (nob_temp_size + size > NOB_TEMP_CAPACITY) return NULL;
  1482. void *result = &nob_temp[nob_temp_size];
  1483. nob_temp_size += size;
  1484. return result;
  1485. }
  1486. NOBDEF char *nob_temp_sprintf(const char *format, ...)
  1487. {
  1488. va_list args;
  1489. va_start(args, format);
  1490. int n = vsnprintf(NULL, 0, format, args);
  1491. va_end(args);
  1492. NOB_ASSERT(n >= 0);
  1493. char *result = (char*)nob_temp_alloc(n + 1);
  1494. NOB_ASSERT(result != NULL && "Extend the size of the temporary allocator");
  1495. // TODO: use proper arenas for the temporary allocator;
  1496. va_start(args, format);
  1497. vsnprintf(result, n + 1, format, args);
  1498. va_end(args);
  1499. return result;
  1500. }
  1501. NOBDEF void nob_temp_reset(void)
  1502. {
  1503. nob_temp_size = 0;
  1504. }
  1505. NOBDEF size_t nob_temp_save(void)
  1506. {
  1507. return nob_temp_size;
  1508. }
  1509. NOBDEF void nob_temp_rewind(size_t checkpoint)
  1510. {
  1511. nob_temp_size = checkpoint;
  1512. }
  1513. NOBDEF const char *nob_temp_sv_to_cstr(Nob_String_View sv)
  1514. {
  1515. char *result = (char*)nob_temp_alloc(sv.count + 1);
  1516. NOB_ASSERT(result != NULL && "Extend the size of the temporary allocator");
  1517. memcpy(result, sv.data, sv.count);
  1518. result[sv.count] = '\0';
  1519. return result;
  1520. }
  1521. NOBDEF int nob_needs_rebuild(const char *output_path, const char **input_paths, size_t input_paths_count)
  1522. {
  1523. #ifdef _WIN32
  1524. BOOL bSuccess;
  1525. HANDLE output_path_fd = CreateFile(output_path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL);
  1526. if (output_path_fd == INVALID_HANDLE_VALUE) {
  1527. // NOTE: if output does not exist it 100% must be rebuilt
  1528. if (GetLastError() == ERROR_FILE_NOT_FOUND) return 1;
  1529. nob_log(NOB_ERROR, "Could not open file %s: %s", output_path, nob_win32_error_message(GetLastError()));
  1530. return -1;
  1531. }
  1532. FILETIME output_path_time;
  1533. bSuccess = GetFileTime(output_path_fd, NULL, NULL, &output_path_time);
  1534. CloseHandle(output_path_fd);
  1535. if (!bSuccess) {
  1536. nob_log(NOB_ERROR, "Could not get time of %s: %s", output_path, nob_win32_error_message(GetLastError()));
  1537. return -1;
  1538. }
  1539. for (size_t i = 0; i < input_paths_count; ++i) {
  1540. const char *input_path = input_paths[i];
  1541. HANDLE input_path_fd = CreateFile(input_path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL);
  1542. if (input_path_fd == INVALID_HANDLE_VALUE) {
  1543. // NOTE: non-existing input is an error cause it is needed for building in the first place
  1544. nob_log(NOB_ERROR, "Could not open file %s: %s", input_path, nob_win32_error_message(GetLastError()));
  1545. return -1;
  1546. }
  1547. FILETIME input_path_time;
  1548. bSuccess = GetFileTime(input_path_fd, NULL, NULL, &input_path_time);
  1549. CloseHandle(input_path_fd);
  1550. if (!bSuccess) {
  1551. nob_log(NOB_ERROR, "Could not get time of %s: %s", input_path, nob_win32_error_message(GetLastError()));
  1552. return -1;
  1553. }
  1554. // NOTE: if even a single input_path is fresher than output_path that's 100% rebuild
  1555. if (CompareFileTime(&input_path_time, &output_path_time) == 1) return 1;
  1556. }
  1557. return 0;
  1558. #else
  1559. struct stat statbuf = {0};
  1560. if (stat(output_path, &statbuf) < 0) {
  1561. // NOTE: if output does not exist it 100% must be rebuilt
  1562. if (errno == ENOENT) return 1;
  1563. nob_log(NOB_ERROR, "could not stat %s: %s", output_path, strerror(errno));
  1564. return -1;
  1565. }
  1566. int output_path_time = statbuf.st_mtime;
  1567. for (size_t i = 0; i < input_paths_count; ++i) {
  1568. const char *input_path = input_paths[i];
  1569. if (stat(input_path, &statbuf) < 0) {
  1570. // NOTE: non-existing input is an error cause it is needed for building in the first place
  1571. nob_log(NOB_ERROR, "could not stat %s: %s", input_path, strerror(errno));
  1572. return -1;
  1573. }
  1574. int input_path_time = statbuf.st_mtime;
  1575. // NOTE: if even a single input_path is fresher than output_path that's 100% rebuild
  1576. if (input_path_time > output_path_time) return 1;
  1577. }
  1578. return 0;
  1579. #endif
  1580. }
  1581. NOBDEF int nob_needs_rebuild1(const char *output_path, const char *input_path)
  1582. {
  1583. return nob_needs_rebuild(output_path, &input_path, 1);
  1584. }
  1585. NOBDEF const char *nob_path_name(const char *path)
  1586. {
  1587. #ifdef _WIN32
  1588. const char *p1 = strrchr(path, '/');
  1589. const char *p2 = strrchr(path, '\\');
  1590. const char *p = (p1 > p2)? p1 : p2; // NULL is ignored if the other search is successful
  1591. return p ? p + 1 : path;
  1592. #else
  1593. const char *p = strrchr(path, '/');
  1594. return p ? p + 1 : path;
  1595. #endif // _WIN32
  1596. }
  1597. NOBDEF bool nob_rename(const char *old_path, const char *new_path)
  1598. {
  1599. nob_log(NOB_INFO, "renaming %s -> %s", old_path, new_path);
  1600. #ifdef _WIN32
  1601. if (!MoveFileEx(old_path, new_path, MOVEFILE_REPLACE_EXISTING)) {
  1602. nob_log(NOB_ERROR, "could not rename %s to %s: %s", old_path, new_path, nob_win32_error_message(GetLastError()));
  1603. return false;
  1604. }
  1605. #else
  1606. if (rename(old_path, new_path) < 0) {
  1607. nob_log(NOB_ERROR, "could not rename %s to %s: %s", old_path, new_path, strerror(errno));
  1608. return false;
  1609. }
  1610. #endif // _WIN32
  1611. return true;
  1612. }
  1613. NOBDEF bool nob_read_entire_file(const char *path, Nob_String_Builder *sb)
  1614. {
  1615. bool result = true;
  1616. FILE *f = fopen(path, "rb");
  1617. size_t new_count = 0;
  1618. long long m = 0;
  1619. if (f == NULL) nob_return_defer(false);
  1620. if (fseek(f, 0, SEEK_END) < 0) nob_return_defer(false);
  1621. #ifndef _WIN32
  1622. m = ftell(f);
  1623. #else
  1624. m = _ftelli64(f);
  1625. #endif
  1626. if (m < 0) nob_return_defer(false);
  1627. if (fseek(f, 0, SEEK_SET) < 0) nob_return_defer(false);
  1628. new_count = sb->count + m;
  1629. if (new_count > sb->capacity) {
  1630. sb->items = NOB_DECLTYPE_CAST(sb->items)NOB_REALLOC(sb->items, new_count);
  1631. NOB_ASSERT(sb->items != NULL && "Buy more RAM lool!!");
  1632. sb->capacity = new_count;
  1633. }
  1634. fread(sb->items + sb->count, m, 1, f);
  1635. if (ferror(f)) {
  1636. // TODO: Afaik, ferror does not set errno. So the error reporting in defer is not correct in this case.
  1637. nob_return_defer(false);
  1638. }
  1639. sb->count = new_count;
  1640. defer:
  1641. if (!result) nob_log(NOB_ERROR, "Could not read file %s: %s", path, strerror(errno));
  1642. if (f) fclose(f);
  1643. return result;
  1644. }
  1645. NOBDEF int nob_sb_appendf(Nob_String_Builder *sb, const char *fmt, ...)
  1646. {
  1647. va_list args;
  1648. va_start(args, fmt);
  1649. int n = vsnprintf(NULL, 0, fmt, args);
  1650. va_end(args);
  1651. // NOTE: the new_capacity needs to be +1 because of the null terminator.
  1652. // However, further below we increase sb->count by n, not n + 1.
  1653. // This is because we don't want the sb to include the null terminator. The user can always sb_append_null() if they want it
  1654. nob_da_reserve(sb, sb->count + n + 1);
  1655. char *dest = sb->items + sb->count;
  1656. va_start(args, fmt);
  1657. vsnprintf(dest, n+1, fmt, args);
  1658. va_end(args);
  1659. sb->count += n;
  1660. return n;
  1661. }
  1662. NOBDEF Nob_String_View nob_sv_chop_by_delim(Nob_String_View *sv, char delim)
  1663. {
  1664. size_t i = 0;
  1665. while (i < sv->count && sv->data[i] != delim) {
  1666. i += 1;
  1667. }
  1668. Nob_String_View result = nob_sv_from_parts(sv->data, i);
  1669. if (i < sv->count) {
  1670. sv->count -= i + 1;
  1671. sv->data += i + 1;
  1672. } else {
  1673. sv->count -= i;
  1674. sv->data += i;
  1675. }
  1676. return result;
  1677. }
  1678. NOBDEF Nob_String_View nob_sv_chop_left(Nob_String_View *sv, size_t n)
  1679. {
  1680. if (n > sv->count) {
  1681. n = sv->count;
  1682. }
  1683. Nob_String_View result = nob_sv_from_parts(sv->data, n);
  1684. sv->data += n;
  1685. sv->count -= n;
  1686. return result;
  1687. }
  1688. NOBDEF Nob_String_View nob_sv_from_parts(const char *data, size_t count)
  1689. {
  1690. Nob_String_View sv;
  1691. sv.count = count;
  1692. sv.data = data;
  1693. return sv;
  1694. }
  1695. NOBDEF Nob_String_View nob_sv_trim_left(Nob_String_View sv)
  1696. {
  1697. size_t i = 0;
  1698. while (i < sv.count && isspace(sv.data[i])) {
  1699. i += 1;
  1700. }
  1701. return nob_sv_from_parts(sv.data + i, sv.count - i);
  1702. }
  1703. NOBDEF Nob_String_View nob_sv_trim_right(Nob_String_View sv)
  1704. {
  1705. size_t i = 0;
  1706. while (i < sv.count && isspace(sv.data[sv.count - 1 - i])) {
  1707. i += 1;
  1708. }
  1709. return nob_sv_from_parts(sv.data, sv.count - i);
  1710. }
  1711. NOBDEF Nob_String_View nob_sv_trim(Nob_String_View sv)
  1712. {
  1713. return nob_sv_trim_right(nob_sv_trim_left(sv));
  1714. }
  1715. NOBDEF Nob_String_View nob_sv_from_cstr(const char *cstr)
  1716. {
  1717. return nob_sv_from_parts(cstr, strlen(cstr));
  1718. }
  1719. NOBDEF bool nob_sv_eq(Nob_String_View a, Nob_String_View b)
  1720. {
  1721. if (a.count != b.count) {
  1722. return false;
  1723. } else {
  1724. return memcmp(a.data, b.data, a.count) == 0;
  1725. }
  1726. }
  1727. NOBDEF bool nob_sv_end_with(Nob_String_View sv, const char *cstr)
  1728. {
  1729. size_t cstr_count = strlen(cstr);
  1730. if (sv.count >= cstr_count) {
  1731. size_t ending_start = sv.count - cstr_count;
  1732. Nob_String_View sv_ending = nob_sv_from_parts(sv.data + ending_start, cstr_count);
  1733. return nob_sv_eq(sv_ending, nob_sv_from_cstr(cstr));
  1734. }
  1735. return false;
  1736. }
  1737. NOBDEF bool nob_sv_starts_with(Nob_String_View sv, Nob_String_View expected_prefix)
  1738. {
  1739. if (expected_prefix.count <= sv.count) {
  1740. Nob_String_View actual_prefix = nob_sv_from_parts(sv.data, expected_prefix.count);
  1741. return nob_sv_eq(expected_prefix, actual_prefix);
  1742. }
  1743. return false;
  1744. }
  1745. // RETURNS:
  1746. // 0 - file does not exists
  1747. // 1 - file exists
  1748. // -1 - error while checking if file exists. The error is logged
  1749. NOBDEF int nob_file_exists(const char *file_path)
  1750. {
  1751. #if _WIN32
  1752. // TODO: distinguish between "does not exists" and other errors
  1753. DWORD dwAttrib = GetFileAttributesA(file_path);
  1754. return dwAttrib != INVALID_FILE_ATTRIBUTES;
  1755. #else
  1756. struct stat statbuf;
  1757. if (stat(file_path, &statbuf) < 0) {
  1758. if (errno == ENOENT) return 0;
  1759. nob_log(NOB_ERROR, "Could not check if file %s exists: %s", file_path, strerror(errno));
  1760. return -1;
  1761. }
  1762. return 1;
  1763. #endif
  1764. }
  1765. NOBDEF const char *nob_get_current_dir_temp(void)
  1766. {
  1767. #ifdef _WIN32
  1768. DWORD nBufferLength = GetCurrentDirectory(0, NULL);
  1769. if (nBufferLength == 0) {
  1770. nob_log(NOB_ERROR, "could not get current directory: %s", nob_win32_error_message(GetLastError()));
  1771. return NULL;
  1772. }
  1773. char *buffer = (char*) nob_temp_alloc(nBufferLength);
  1774. if (GetCurrentDirectory(nBufferLength, buffer) == 0) {
  1775. nob_log(NOB_ERROR, "could not get current directory: %s", nob_win32_error_message(GetLastError()));
  1776. return NULL;
  1777. }
  1778. return buffer;
  1779. #else
  1780. char *buffer = (char*) nob_temp_alloc(PATH_MAX);
  1781. if (getcwd(buffer, PATH_MAX) == NULL) {
  1782. nob_log(NOB_ERROR, "could not get current directory: %s", strerror(errno));
  1783. return NULL;
  1784. }
  1785. return buffer;
  1786. #endif // _WIN32
  1787. }
  1788. NOBDEF bool nob_set_current_dir(const char *path)
  1789. {
  1790. #ifdef _WIN32
  1791. if (!SetCurrentDirectory(path)) {
  1792. nob_log(NOB_ERROR, "could not set current directory to %s: %s", path, nob_win32_error_message(GetLastError()));
  1793. return false;
  1794. }
  1795. return true;
  1796. #else
  1797. if (chdir(path) < 0) {
  1798. nob_log(NOB_ERROR, "could not set current directory to %s: %s", path, strerror(errno));
  1799. return false;
  1800. }
  1801. return true;
  1802. #endif // _WIN32
  1803. }
  1804. // minirent.h SOURCE BEGIN ////////////////////////////////////////
  1805. #if defined(_WIN32) && !defined(NOB_NO_MINIRENT)
  1806. struct DIR
  1807. {
  1808. HANDLE hFind;
  1809. WIN32_FIND_DATA data;
  1810. struct dirent *dirent;
  1811. };
  1812. NOBDEF DIR *opendir(const char *dirpath)
  1813. {
  1814. NOB_ASSERT(dirpath);
  1815. char buffer[MAX_PATH];
  1816. snprintf(buffer, MAX_PATH, "%s\\*", dirpath);
  1817. DIR *dir = (DIR*)NOB_REALLOC(NULL, sizeof(DIR));
  1818. memset(dir, 0, sizeof(DIR));
  1819. dir->hFind = FindFirstFile(buffer, &dir->data);
  1820. if (dir->hFind == INVALID_HANDLE_VALUE) {
  1821. // TODO: opendir should set errno accordingly on FindFirstFile fail
  1822. // https://docs.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-getlasterror
  1823. errno = ENOSYS;
  1824. goto fail;
  1825. }
  1826. return dir;
  1827. fail:
  1828. if (dir) {
  1829. NOB_FREE(dir);
  1830. }
  1831. return NULL;
  1832. }
  1833. NOBDEF struct dirent *readdir(DIR *dirp)
  1834. {
  1835. NOB_ASSERT(dirp);
  1836. if (dirp->dirent == NULL) {
  1837. dirp->dirent = (struct dirent*)NOB_REALLOC(NULL, sizeof(struct dirent));
  1838. memset(dirp->dirent, 0, sizeof(struct dirent));
  1839. } else {
  1840. if(!FindNextFile(dirp->hFind, &dirp->data)) {
  1841. if (GetLastError() != ERROR_NO_MORE_FILES) {
  1842. // TODO: readdir should set errno accordingly on FindNextFile fail
  1843. // https://docs.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-getlasterror
  1844. errno = ENOSYS;
  1845. }
  1846. return NULL;
  1847. }
  1848. }
  1849. memset(dirp->dirent->d_name, 0, sizeof(dirp->dirent->d_name));
  1850. strncpy(
  1851. dirp->dirent->d_name,
  1852. dirp->data.cFileName,
  1853. sizeof(dirp->dirent->d_name) - 1);
  1854. return dirp->dirent;
  1855. }
  1856. NOBDEF int closedir(DIR *dirp)
  1857. {
  1858. NOB_ASSERT(dirp);
  1859. if(!FindClose(dirp->hFind)) {
  1860. // TODO: closedir should set errno accordingly on FindClose fail
  1861. // https://docs.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-getlasterror
  1862. errno = ENOSYS;
  1863. return -1;
  1864. }
  1865. if (dirp->dirent) {
  1866. NOB_FREE(dirp->dirent);
  1867. }
  1868. NOB_FREE(dirp);
  1869. return 0;
  1870. }
  1871. #endif // _WIN32
  1872. // minirent.h SOURCE END ////////////////////////////////////////
  1873. #endif // NOB_IMPLEMENTATION
  1874. #ifndef NOB_STRIP_PREFIX_GUARD_
  1875. #define NOB_STRIP_PREFIX_GUARD_
  1876. // NOTE: The name stripping should be part of the header so it's not accidentally included
  1877. // several times. At the same time, it should be at the end of the file so to not create any
  1878. // potential conflicts in the NOB_IMPLEMENTATION. The header obviously cannot be at the end
  1879. // of the file because NOB_IMPLEMENTATION needs the forward declarations from there. So the
  1880. // solution is to split the header into two parts where the name stripping part is at the
  1881. // end of the file after the NOB_IMPLEMENTATION.
  1882. #ifdef NOB_STRIP_PREFIX
  1883. #define TODO NOB_TODO
  1884. #define UNREACHABLE NOB_UNREACHABLE
  1885. #define UNUSED NOB_UNUSED
  1886. #define ARRAY_LEN NOB_ARRAY_LEN
  1887. #define ARRAY_GET NOB_ARRAY_GET
  1888. #define INFO NOB_INFO
  1889. #define WARNING NOB_WARNING
  1890. #define ERROR NOB_ERROR
  1891. #define NO_LOGS NOB_NO_LOGS
  1892. #define Log_Level Nob_Log_Level
  1893. #define minimal_log_level nob_minimal_log_level
  1894. // NOTE: Name log is already defined in math.h and historically always was the natural logarithmic function.
  1895. // So there should be no reason to strip the `nob_` prefix in this specific case.
  1896. // #define log nob_log
  1897. #define shift nob_shift
  1898. #define shift_args nob_shift_args
  1899. #define File_Paths Nob_File_Paths
  1900. #define FILE_REGULAR NOB_FILE_REGULAR
  1901. #define FILE_DIRECTORY NOB_FILE_DIRECTORY
  1902. #define FILE_SYMLINK NOB_FILE_SYMLINK
  1903. #define FILE_OTHER NOB_FILE_OTHER
  1904. #define File_Type Nob_File_Type
  1905. #define mkdir_if_not_exists nob_mkdir_if_not_exists
  1906. #define copy_file nob_copy_file
  1907. #define copy_directory_recursively nob_copy_directory_recursively
  1908. #define read_entire_dir nob_read_entire_dir
  1909. #define write_entire_file nob_write_entire_file
  1910. #define get_file_type nob_get_file_type
  1911. #define delete_file nob_delete_file
  1912. #define return_defer nob_return_defer
  1913. #define da_append nob_da_append
  1914. #define da_free nob_da_free
  1915. #define da_append_many nob_da_append_many
  1916. #define da_resize nob_da_resize
  1917. #define da_reserve nob_da_reserve
  1918. #define da_last nob_da_last
  1919. #define da_remove_unordered nob_da_remove_unordered
  1920. #define da_foreach nob_da_foreach
  1921. #define String_Builder Nob_String_Builder
  1922. #define read_entire_file nob_read_entire_file
  1923. #define sb_appendf nob_sb_appendf
  1924. #define sb_append_buf nob_sb_append_buf
  1925. #define sb_append_cstr nob_sb_append_cstr
  1926. #define sb_append_null nob_sb_append_null
  1927. #define sb_free nob_sb_free
  1928. #define Proc Nob_Proc
  1929. #define INVALID_PROC NOB_INVALID_PROC
  1930. #define Fd Nob_Fd
  1931. #define INVALID_FD NOB_INVALID_FD
  1932. #define fd_open_for_read nob_fd_open_for_read
  1933. #define fd_open_for_write nob_fd_open_for_write
  1934. #define fd_close nob_fd_close
  1935. #define Procs Nob_Procs
  1936. #define proc_wait nob_proc_wait
  1937. #define procs_wait nob_procs_wait
  1938. #define procs_wait_and_reset nob_procs_wait_and_reset
  1939. #define procs_append_with_flush nob_procs_append_with_flush
  1940. #define procs_flush nob_procs_flush
  1941. #define Cmd Nob_Cmd
  1942. #define Cmd_Redirect Nob_Cmd_Redirect
  1943. #define Cmd_Opt Nob_Cmd_Opt
  1944. #define cmd_run_opt nob_cmd_run_opt
  1945. #define cmd_run nob_cmd_run
  1946. #define cmd_render nob_cmd_render
  1947. #define cmd_append nob_cmd_append
  1948. #define cmd_extend nob_cmd_extend
  1949. #define cmd_free nob_cmd_free
  1950. #define cmd_run_async nob_cmd_run_async
  1951. #define cmd_run_async_and_reset nob_cmd_run_async_and_reset
  1952. #define cmd_run_async_redirect nob_cmd_run_async_redirect
  1953. #define cmd_run_async_redirect_and_reset nob_cmd_run_async_redirect_and_reset
  1954. #define cmd_run_sync nob_cmd_run_sync
  1955. #define cmd_run_sync_and_reset nob_cmd_run_sync_and_reset
  1956. #define cmd_run_sync_redirect nob_cmd_run_sync_redirect
  1957. #define cmd_run_sync_redirect_and_reset nob_cmd_run_sync_redirect_and_reset
  1958. #define temp_strdup nob_temp_strdup
  1959. #define temp_alloc nob_temp_alloc
  1960. #define temp_sprintf nob_temp_sprintf
  1961. #define temp_reset nob_temp_reset
  1962. #define temp_save nob_temp_save
  1963. #define temp_rewind nob_temp_rewind
  1964. #define path_name nob_path_name
  1965. // NOTE: rename(2) is widely known POSIX function. We never wanna collide with it.
  1966. // #define rename nob_rename
  1967. #define needs_rebuild nob_needs_rebuild
  1968. #define needs_rebuild1 nob_needs_rebuild1
  1969. #define file_exists nob_file_exists
  1970. #define get_current_dir_temp nob_get_current_dir_temp
  1971. #define set_current_dir nob_set_current_dir
  1972. #define String_View Nob_String_View
  1973. #define temp_sv_to_cstr nob_temp_sv_to_cstr
  1974. #define sv_chop_by_delim nob_sv_chop_by_delim
  1975. #define sv_chop_left nob_sv_chop_left
  1976. #define sv_trim nob_sv_trim
  1977. #define sv_trim_left nob_sv_trim_left
  1978. #define sv_trim_right nob_sv_trim_right
  1979. #define sv_eq nob_sv_eq
  1980. #define sv_starts_with nob_sv_starts_with
  1981. #define sv_end_with nob_sv_end_with
  1982. #define sv_from_cstr nob_sv_from_cstr
  1983. #define sv_from_parts nob_sv_from_parts
  1984. #define sb_to_sv nob_sb_to_sv
  1985. #define win32_error_message nob_win32_error_message
  1986. #define nprocs nob_nprocs
  1987. #define nanos_since_unspecified_epoch nob_nanos_since_unspecified_epoch
  1988. #define NANOS_PER_SEC NOB_NANOS_PER_SEC
  1989. #endif // NOB_STRIP_PREFIX
  1990. #endif // NOB_STRIP_PREFIX_GUARD_
  1991. /*
  1992. Revision history:
  1993. 1.23.0 (2025-08-22) Introduce new API for running commands (by @rexim, @programmerlexi, @0x152a)
  1994. - Add nob_cmd_run()
  1995. - Add nob_cmd_run_opt()
  1996. - Add struct Nob_Cmd_Opt
  1997. - Add nob_procs_flush()
  1998. - Add nob_nprocs()
  1999. Deprecate old API for running commands. (by @rexim)
  2000. We do not plan to delete this API any time, but we believe that the new one is more convenient.
  2001. - Deprecate struct Nob_Cmd_Redirect{} (it's not explicitly marked with NOB_DEPRECATED, but functions that use it are)
  2002. - Turn nob_cmd_run_async() into a function (otherwise it's not deprecatable with NOB_DEPRECATED)
  2003. - Deprecate nob_cmd_run_async()
  2004. - Deprecate nob_cmd_run_async_and_reset()
  2005. - Deprecate nob_cmd_run_async_redirect()
  2006. - Deprecate nob_cmd_run_async_redirect_and_reset()
  2007. - Deprecate nob_cmd_run_sync()
  2008. - Deprecate nob_cmd_run_sync_and_reset()
  2009. - Deprecate nob_cmd_run_sync_redirect()
  2010. - Deprecate nob_cmd_run_sync_redirect_and_reset()
  2011. - Deprecate nob_procs_append_with_flush()
  2012. - Deprecate nob_procs_wait_and_reset()
  2013. Introduce deprecation mechanism (by @yuI4140, @rexim)
  2014. By default, deprecation warnings are not reported. You have to #define NOB_WARN_DEPRECATED to enable them.
  2015. - Add NOB_DEPRECATED()
  2016. - Add NOB_WARN_DEPRECATED
  2017. Add NOB_DECLTYPE_CAST() for C++-compatible casting of allocation results (by @rexim)
  2018. Introduce basic performance measuring mechanism (By @mikmart)
  2019. - Add nob_nanos_since_unspecified_epoch()
  2020. - Add NOB_NANOS_PER_SEC
  2021. 1.22.0 (2025-08-12) Add NOBDEF macro to the beginning of function declarations (by @minefreak19)
  2022. Add more flags to MSVC nob_cc_flags() (by @PieVieRo)
  2023. 1.21.0 (2025-08-11) Add NOB_NO_MINIRENT guard for "minirent.h" (by @fietec)
  2024. 1.20.9 (2025-08-11) Fix warnings on Windows: Define _CRT_SECURE_NO_WARNINGS, Rename mkdir to _mkdir (by @OetkenPurveyorOfCode)
  2025. 1.20.8 (2025-08-11) Fix the bug with nob_get_file_type() not identifying symlinks correctly on POSIX (By @samuellieberman)
  2026. 1.20.7 (2025-07-29) Align nob_temp_alloc() allocations by the word size (By @rexim)
  2027. 1.20.6 (2025-05-16) Never strip nob_* suffix from nob_rename (By @rexim)
  2028. 1.20.5 (2025-05-16) NOB_PRINTF_FORMAT() support for MinGW (By @KillerxDBr)
  2029. 1.20.4 (2025-05-16) More reliable rendering of the Windows command (By @vylsaz)
  2030. 1.20.3 (2025-05-16) Add check for __clang__ along with _MSC_VER checks (By @nashiora)
  2031. 1.20.2 (2025-04-24) Report the program name that failed to start up in nob_cmd_run_async_redirect() (By @rexim)
  2032. 1.20.1 (2025-04-16) Use vsnprintf() in nob_sb_appendf() instead of vsprintf() (By @LainLayer)
  2033. 1.20.0 (2025-04-16) Introduce nob_cc(), nob_cc_flags(), nob_cc_inputs(), nob_cc_output() macros (By @rexim)
  2034. 1.19.0 (2025-03-25) Add nob_procs_append_with_flush() (By @rexim and @anion155)
  2035. 1.18.0 (2025-03-24) Add nob_da_foreach() (By @rexim)
  2036. Allow file sizes greater than 2GB to be read on windows (By @satchelfrost and @KillerxDBr)
  2037. Fix nob_fd_open_for_write behaviour on windows so it truncates the opened files (By @twixuss)
  2038. 1.17.0 (2025-03-16) Factor out nob_da_reserve() (By @rexim)
  2039. Add nob_sb_appendf() (By @angelcaru)
  2040. 1.16.1 (2025-03-16) Make nob_da_resize() exponentially grow capacity similar to no_da_append_many()
  2041. 1.16.0 (2025-03-16) Introduce NOB_PRINTF_FORMAT
  2042. 1.15.1 (2025-03-16) Make nob.h compilable in gcc/clang with -std=c99 on POSIX. This includes:
  2043. not using strsignal()
  2044. using S_IS* stat macros instead of S_IF* flags
  2045. 1.15.0 (2025-03-03) Add nob_sv_chop_left()
  2046. 1.14.1 (2025-03-02) Add NOB_EXPERIMENTAL_DELETE_OLD flag that enables deletion of nob.old in Go Rebuild Urself™ Technology
  2047. 1.14.0 (2025-02-17) Add nob_da_last()
  2048. Add nob_da_remove_unordered()
  2049. 1.13.1 (2025-02-17) Fix segfault in nob_delete_file() (By @SileNce5k)
  2050. 1.13.0 (2025-02-11) Add nob_da_resize() (By @satchelfrost)
  2051. 1.12.0 (2025-02-04) Add nob_delete_file()
  2052. Add nob_sv_start_with()
  2053. 1.11.0 (2025-02-04) Add NOB_GO_REBUILD_URSELF_PLUS() (By @rexim)
  2054. 1.10.0 (2025-02-04) Make NOB_ASSERT, NOB_REALLOC, and NOB_FREE redefinable (By @OleksiiBulba)
  2055. 1.9.1 (2025-02-04) Fix signature of nob_get_current_dir_temp() (By @julianstoerig)
  2056. 1.9.0 (2024-11-06) Add Nob_Cmd_Redirect mechanism (By @rexim)
  2057. Add nob_path_name() (By @0dminnimda)
  2058. 1.8.0 (2024-11-03) Add nob_cmd_extend() (By @0dminnimda)
  2059. 1.7.0 (2024-11-03) Add nob_win32_error_message and NOB_WIN32_ERR_MSG_SIZE (By @KillerxDBr)
  2060. 1.6.0 (2024-10-27) Add nob_cmd_run_sync_and_reset()
  2061. Add nob_sb_to_sv()
  2062. Add nob_procs_wait_and_reset()
  2063. 1.5.1 (2024-10-25) Include limits.h for Linux musl libc (by @pgalkin)
  2064. 1.5.0 (2024-10-23) Add nob_get_current_dir_temp()
  2065. Add nob_set_current_dir()
  2066. 1.4.0 (2024-10-21) Fix UX issues with NOB_GO_REBUILD_URSELF on Windows when you call nob without the .exe extension (By @pgalkin)
  2067. Add nob_sv_end_with (By @pgalkin)
  2068. 1.3.2 (2024-10-21) Fix unreachable error in nob_log on passing NOB_NO_LOGS
  2069. 1.3.1 (2024-10-21) Fix redeclaration error for minimal_log_level (By @KillerxDBr)
  2070. 1.3.0 (2024-10-17) Add NOB_UNREACHABLE
  2071. 1.2.2 (2024-10-16) Fix compilation of nob_cmd_run_sync_and_reset on Windows (By @KillerxDBr)
  2072. 1.2.1 (2024-10-16) Add a separate include guard for NOB_STRIP_PREFIX.
  2073. 1.2.0 (2024-10-15) Make NOB_DA_INIT_CAP redefinable
  2074. Add NOB_STRIP_PREFIX which strips off nob_* prefix from all the user facing names
  2075. Add NOB_UNUSED macro
  2076. Add NOB_TODO macro
  2077. Add nob_sv_trim_left and nob_sv_trim_right declarations to the header part
  2078. 1.1.1 (2024-10-15) Remove forward declaration for is_path1_modified_after_path2
  2079. 1.1.0 (2024-10-15) nob_minimal_log_level
  2080. nob_cmd_run_sync_and_reset
  2081. 1.0.0 (2024-10-15) first release based on https://github.com/tsoding/musializer/blob/4ac7cce9874bc19e02d8c160c8c6229de8919401/nob.h
  2082. */
  2083. /*
  2084. Version Conventions:
  2085. We are following https://semver.org/ so the version has a format MAJOR.MINOR.PATCH:
  2086. - Modifying comments does not update the version.
  2087. - PATCH is incremented in case of a bug fix or refactoring without touching the API.
  2088. - MINOR is incremented when new functions and/or types are added in a way that does
  2089. not break any existing user code. We want to do this in the majority of the situation.
  2090. If we want to delete a certain function or type in favor of another one we should
  2091. just add the new function/type and deprecate the old one in a backward compatible way
  2092. and let them co-exist for a while.
  2093. - MAJOR update should be just a periodic cleanup of the DEPRECATED functions and types
  2094. without really modifying any existing functionality.
  2095. - Breaking backward compatibility in a MINOR release should be considered a bug and
  2096. should be promptly fixed in the next PATCH release.
  2097. Naming Conventions:
  2098. - All the user facing names should be prefixed with `nob_` or `NOB_` depending on the case.
  2099. - The prefixes of non-redefinable names should be strippable with NOB_STRIP_PREFIX (unless
  2100. explicitly stated otherwise like in case of nob_log).
  2101. - Internal functions should be prefixed with `nob__` (double underscore).
  2102. */
  2103. /*
  2104. ------------------------------------------------------------------------------
  2105. This software is available under 2 licenses -- choose whichever you prefer.
  2106. ------------------------------------------------------------------------------
  2107. ALTERNATIVE A - MIT License
  2108. Copyright (c) 2024 Alexey Kutepov
  2109. Permission is hereby granted, free of charge, to any person obtaining a copy of
  2110. this software and associated documentation files (the "Software"), to deal in
  2111. the Software without restriction, including without limitation the rights to
  2112. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  2113. of the Software, and to permit persons to whom the Software is furnished to do
  2114. so, subject to the following conditions:
  2115. The above copyright notice and this permission notice shall be included in all
  2116. copies or substantial portions of the Software.
  2117. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  2118. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  2119. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  2120. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  2121. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  2122. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  2123. SOFTWARE.
  2124. ------------------------------------------------------------------------------
  2125. ALTERNATIVE B - Public Domain (www.unlicense.org)
  2126. This is free and unencumbered software released into the public domain.
  2127. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
  2128. software, either in source code form or as a compiled binary, for any purpose,
  2129. commercial or non-commercial, and by any means.
  2130. In jurisdictions that recognize copyright laws, the author or authors of this
  2131. software dedicate any and all copyright interest in the software to the public
  2132. domain. We make this dedication for the benefit of the public at large and to
  2133. the detriment of our heirs and successors. We intend this dedication to be an
  2134. overt act of relinquishment in perpetuity of all present and future rights to
  2135. this software under copyright law.
  2136. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  2137. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  2138. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  2139. AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  2140. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  2141. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  2142. ------------------------------------------------------------------------------
  2143. */