nob.h 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162
  1. // This is a complete backward incompatible rewrite of https://github.com/tsoding/nobuild
  2. // because I'm really unhappy with the direction it is going. It's gonna sit in this repo
  3. // until it's matured enough and then I'll probably extract it to its own repo.
  4. // Copyright 2023 Alexey Kutepov <[email protected]>
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining
  7. // a copy of this software and associated documentation files (the
  8. // "Software"), to deal in the Software without restriction, including
  9. // without limitation the rights to use, copy, modify, merge, publish,
  10. // distribute, sublicense, and/or sell copies of the Software, and to
  11. // permit persons to whom the Software is furnished to do so, subject to
  12. // the following conditions:
  13. //
  14. // The above copyright notice and this permission notice shall be
  15. // included in all copies or substantial portions of the Software.
  16. //
  17. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  18. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  20. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  21. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  22. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  23. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  24. #ifndef NOB_H_
  25. #define NOB_H_
  26. #define NOB_ASSERT assert
  27. #define NOB_REALLOC realloc
  28. #define NOB_FREE free
  29. #include <assert.h>
  30. #include <stdbool.h>
  31. #include <stdlib.h>
  32. #include <stdio.h>
  33. #include <stdarg.h>
  34. #include <string.h>
  35. #include <errno.h>
  36. #include <ctype.h>
  37. #ifdef _WIN32
  38. # define WIN32_LEAN_AND_MEAN
  39. # define _WINUSER_
  40. # define _WINGDI_
  41. # define _IMM_
  42. # define _WINCON_
  43. # include <windows.h>
  44. # include <direct.h>
  45. # include <shellapi.h>
  46. #else
  47. # include <sys/types.h>
  48. # include <sys/wait.h>
  49. # include <sys/stat.h>
  50. # include <unistd.h>
  51. # include <fcntl.h>
  52. #endif
  53. #ifdef _WIN32
  54. # define NOB_LINE_END "\r\n"
  55. #else
  56. # define NOB_LINE_END "\n"
  57. #endif
  58. #define NOB_ARRAY_LEN(array) (sizeof(array)/sizeof(array[0]))
  59. #define NOB_ARRAY_GET(array, index) \
  60. (NOB_ASSERT((size_t)index < NOB_ARRAY_LEN(array)), array[(size_t)index])
  61. typedef enum {
  62. NOB_INFO,
  63. NOB_WARNING,
  64. NOB_ERROR,
  65. } Nob_Log_Level;
  66. void nob_log(Nob_Log_Level level, const char *fmt, ...);
  67. // It is an equivalent of shift command from bash. It basically pops a command line
  68. // argument from the beginning.
  69. char *nob_shift_args(int *argc, char ***argv);
  70. typedef struct {
  71. const char **items;
  72. size_t count;
  73. size_t capacity;
  74. } Nob_File_Paths;
  75. typedef enum {
  76. NOB_FILE_REGULAR = 0,
  77. NOB_FILE_DIRECTORY,
  78. NOB_FILE_SYMLINK,
  79. NOB_FILE_OTHER,
  80. } Nob_File_Type;
  81. bool nob_mkdir_if_not_exists(const char *path);
  82. bool nob_copy_file(const char *src_path, const char *dst_path);
  83. bool nob_copy_directory_recursively(const char *src_path, const char *dst_path);
  84. bool nob_read_entire_dir(const char *parent, Nob_File_Paths *children);
  85. bool nob_write_entire_file(const char *path, const void *data, size_t size);
  86. Nob_File_Type nob_get_file_type(const char *path);
  87. #define nob_return_defer(value) do { result = (value); goto defer; } while(0)
  88. // Initial capacity of a dynamic array
  89. #define NOB_DA_INIT_CAP 256
  90. // Append an item to a dynamic array
  91. #define nob_da_append(da, item) \
  92. do { \
  93. if ((da)->count >= (da)->capacity) { \
  94. (da)->capacity = (da)->capacity == 0 ? NOB_DA_INIT_CAP : (da)->capacity*2; \
  95. (da)->items = NOB_REALLOC((da)->items, (da)->capacity*sizeof(*(da)->items)); \
  96. NOB_ASSERT((da)->items != NULL && "Buy more RAM lol"); \
  97. } \
  98. \
  99. (da)->items[(da)->count++] = (item); \
  100. } while (0)
  101. #define nob_da_free(da) NOB_FREE((da).items)
  102. // Append several items to a dynamic array
  103. #define nob_da_append_many(da, new_items, new_items_count) \
  104. do { \
  105. if ((da)->count + (new_items_count) > (da)->capacity) { \
  106. if ((da)->capacity == 0) { \
  107. (da)->capacity = NOB_DA_INIT_CAP; \
  108. } \
  109. while ((da)->count + (new_items_count) > (da)->capacity) { \
  110. (da)->capacity *= 2; \
  111. } \
  112. (da)->items = NOB_REALLOC((da)->items, (da)->capacity*sizeof(*(da)->items)); \
  113. NOB_ASSERT((da)->items != NULL && "Buy more RAM lol"); \
  114. } \
  115. memcpy((da)->items + (da)->count, (new_items), (new_items_count)*sizeof(*(da)->items)); \
  116. (da)->count += (new_items_count); \
  117. } while (0)
  118. typedef struct {
  119. char *items;
  120. size_t count;
  121. size_t capacity;
  122. } Nob_String_Builder;
  123. bool nob_read_entire_file(const char *path, Nob_String_Builder *sb);
  124. // Append a sized buffer to a string builder
  125. #define nob_sb_append_buf(sb, buf, size) nob_da_append_many(sb, buf, size)
  126. // Append a NULL-terminated string to a string builder
  127. #define nob_sb_append_cstr(sb, cstr) \
  128. do { \
  129. const char *s = (cstr); \
  130. size_t n = strlen(s); \
  131. nob_da_append_many(sb, s, n); \
  132. } while (0)
  133. // Append a single NULL character at the end of a string builder. So then you can
  134. // use it a NULL-terminated C string
  135. #define nob_sb_append_null(sb) nob_da_append_many(sb, "", 1)
  136. // Free the memory allocated by a string builder
  137. #define nob_sb_free(sb) NOB_FREE((sb).items)
  138. // Process handle
  139. #ifdef _WIN32
  140. typedef HANDLE Nob_Proc;
  141. #define NOB_INVALID_PROC INVALID_HANDLE_VALUE
  142. #else
  143. typedef int Nob_Proc;
  144. #define NOB_INVALID_PROC (-1)
  145. #endif // _WIN32
  146. typedef struct {
  147. Nob_Proc *items;
  148. size_t count;
  149. size_t capacity;
  150. } Nob_Procs;
  151. bool nob_procs_wait(Nob_Procs procs);
  152. // Wait until the process has finished
  153. bool nob_proc_wait(Nob_Proc proc);
  154. // A command - the main workhorse of Nob. Nob is all about building commands an running them
  155. typedef struct {
  156. const char **items;
  157. size_t count;
  158. size_t capacity;
  159. } Nob_Cmd;
  160. // Render a string representation of a command into a string builder. Keep in mind the the
  161. // string builder is not NULL-terminated by default. Use nob_sb_append_null if you plan to
  162. // use it as a C string.
  163. void nob_cmd_render(Nob_Cmd cmd, Nob_String_Builder *render);
  164. #define nob_cmd_append(cmd, ...) \
  165. nob_da_append_many(cmd, \
  166. ((const char*[]){__VA_ARGS__}), \
  167. (sizeof((const char*[]){__VA_ARGS__})/sizeof(const char*)))
  168. // Free all the memory allocated by command arguments
  169. #define nob_cmd_free(cmd) NOB_FREE(cmd.items)
  170. // Run command asynchronously
  171. Nob_Proc nob_cmd_run_async(Nob_Cmd cmd);
  172. // Run command synchronously
  173. bool nob_cmd_run_sync(Nob_Cmd cmd);
  174. #ifndef NOB_TEMP_CAPACITY
  175. #define NOB_TEMP_CAPACITY (8*1024*1024)
  176. #endif // NOB_TEMP_CAPACITY
  177. char *nob_temp_strdup(const char *cstr);
  178. void *nob_temp_alloc(size_t size);
  179. char *nob_temp_sprintf(const char *format, ...);
  180. void nob_temp_reset(void);
  181. size_t nob_temp_save(void);
  182. void nob_temp_rewind(size_t checkpoint);
  183. int is_path1_modified_after_path2(const char *path1, const char *path2);
  184. bool nob_rename(const char *old_path, const char *new_path);
  185. int nob_needs_rebuild(const char *output_path, const char **input_paths, size_t input_paths_count);
  186. int nob_needs_rebuild1(const char *output_path, const char *input_path);
  187. int nob_file_exists(const char *file_path);
  188. // TODO: add MinGW support for Go Rebuild Urself™ Technology
  189. #ifndef NOB_REBUILD_URSELF
  190. # if _WIN32
  191. # if defined(__GNUC__)
  192. # define NOB_REBUILD_URSELF(binary_path, source_path) "gcc", "-o", binary_path, source_path
  193. # elif defined(__clang__)
  194. # define NOB_REBUILD_URSELF(binary_path, source_path) "clang", "-o", binary_path, source_path
  195. # elif defined(_MSC_VER)
  196. # define NOB_REBUILD_URSELF(binary_path, source_path) "cl.exe", nob_temp_sprintf("/Fe:%s", (binary_path)), source_path
  197. # endif
  198. # else
  199. # define NOB_REBUILD_URSELF(binary_path, source_path) "cc", "-o", binary_path, source_path
  200. # endif
  201. #endif
  202. // Go Rebuild Urself™ Technology
  203. //
  204. // How to use it:
  205. // int main(int argc, char** argv) {
  206. // GO_REBUILD_URSELF(argc, argv);
  207. // // actual work
  208. // return 0;
  209. // }
  210. //
  211. // After your added this macro every time you run ./nobuild it will detect
  212. // that you modified its original source code and will try to rebuild itself
  213. // before doing any actual work. So you only need to bootstrap your build system
  214. // once.
  215. //
  216. // The modification is detected by comparing the last modified times of the executable
  217. // and its source code. The same way the make utility usually does it.
  218. //
  219. // The rebuilding is done by using the REBUILD_URSELF macro which you can redefine
  220. // if you need a special way of bootstraping your build system. (which I personally
  221. // do not recommend since the whole idea of nobuild is to keep the process of bootstrapping
  222. // as simple as possible and doing all of the actual work inside of the nobuild)
  223. //
  224. #define NOB_GO_REBUILD_URSELF(argc, argv) \
  225. do { \
  226. const char *source_path = __FILE__; \
  227. assert(argc >= 1); \
  228. const char *binary_path = argv[0]; \
  229. \
  230. int rebuild_is_needed = nob_needs_rebuild(binary_path, &source_path, 1); \
  231. if (rebuild_is_needed < 0) exit(1); \
  232. if (rebuild_is_needed) { \
  233. Nob_String_Builder sb = {0}; \
  234. nob_sb_append_cstr(&sb, binary_path); \
  235. nob_sb_append_cstr(&sb, ".old"); \
  236. nob_sb_append_null(&sb); \
  237. \
  238. if (!nob_rename(binary_path, sb.items)) exit(1); \
  239. Nob_Cmd rebuild = {0}; \
  240. nob_cmd_append(&rebuild, NOB_REBUILD_URSELF(binary_path, source_path)); \
  241. bool rebuild_succeeded = nob_cmd_run_sync(rebuild); \
  242. nob_cmd_free(rebuild); \
  243. if (!rebuild_succeeded) { \
  244. nob_rename(sb.items, binary_path); \
  245. exit(1); \
  246. } \
  247. \
  248. Nob_Cmd cmd = {0}; \
  249. nob_da_append_many(&cmd, argv, argc); \
  250. if (!nob_cmd_run_sync(cmd)) exit(1); \
  251. exit(0); \
  252. } \
  253. } while(0)
  254. // The implementation idea is stolen from https://github.com/zhiayang/nabs
  255. typedef struct {
  256. size_t count;
  257. const char *data;
  258. } Nob_String_View;
  259. const char *nob_temp_sv_to_cstr(Nob_String_View sv);
  260. Nob_String_View nob_sv_chop_by_delim(Nob_String_View *sv, char delim);
  261. Nob_String_View nob_sv_trim(Nob_String_View sv);
  262. bool nob_sv_eq(Nob_String_View a, Nob_String_View b);
  263. Nob_String_View nob_sv_from_cstr(const char *cstr);
  264. Nob_String_View nob_sv_from_parts(const char *data, size_t count);
  265. // printf macros for String_View
  266. #ifndef SV_Fmt
  267. #define SV_Fmt "%.*s"
  268. #endif // SV_Fmt
  269. #ifndef SV_Arg
  270. #define SV_Arg(sv) (int) (sv).count, (sv).data
  271. #endif // SV_Arg
  272. // USAGE:
  273. // String_View name = ...;
  274. // printf("Name: "SV_Fmt"\n", SV_Arg(name));
  275. // minirent.h HEADER BEGIN ////////////////////////////////////////
  276. // Copyright 2021 Alexey Kutepov <[email protected]>
  277. //
  278. // Permission is hereby granted, free of charge, to any person obtaining
  279. // a copy of this software and associated documentation files (the
  280. // "Software"), to deal in the Software without restriction, including
  281. // without limitation the rights to use, copy, modify, merge, publish,
  282. // distribute, sublicense, and/or sell copies of the Software, and to
  283. // permit persons to whom the Software is furnished to do so, subject to
  284. // the following conditions:
  285. //
  286. // The above copyright notice and this permission notice shall be
  287. // included in all copies or substantial portions of the Software.
  288. //
  289. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  290. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  291. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  292. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  293. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  294. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  295. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  296. //
  297. // ============================================================
  298. //
  299. // minirent — 0.0.1 — A subset of dirent interface for Windows.
  300. //
  301. // https://github.com/tsoding/minirent
  302. //
  303. // ============================================================
  304. //
  305. // ChangeLog (https://semver.org/ is implied)
  306. //
  307. // 0.0.2 Automatically include dirent.h on non-Windows
  308. // platforms
  309. // 0.0.1 First Official Release
  310. #ifndef _WIN32
  311. #include <dirent.h>
  312. #else // _WIN32
  313. #define WIN32_LEAN_AND_MEAN
  314. #include "windows.h"
  315. struct dirent
  316. {
  317. char d_name[MAX_PATH+1];
  318. };
  319. typedef struct DIR DIR;
  320. static DIR *opendir(const char *dirpath);
  321. static struct dirent *readdir(DIR *dirp);
  322. static int closedir(DIR *dirp);
  323. #endif // _WIN32
  324. // minirent.h HEADER END ////////////////////////////////////////
  325. #endif // NOB_H_
  326. #ifdef NOB_IMPLEMENTATION
  327. static size_t nob_temp_size = 0;
  328. static char nob_temp[NOB_TEMP_CAPACITY] = {0};
  329. bool nob_mkdir_if_not_exists(const char *path)
  330. {
  331. #ifdef _WIN32
  332. int result = mkdir(path);
  333. #else
  334. int result = mkdir(path, 0755);
  335. #endif
  336. if (result < 0) {
  337. if (errno == EEXIST) {
  338. nob_log(NOB_INFO, "directory `%s` already exists", path);
  339. return true;
  340. }
  341. nob_log(NOB_ERROR, "could not create directory `%s`: %s", path, strerror(errno));
  342. return false;
  343. }
  344. nob_log(NOB_INFO, "created directory `%s`", path);
  345. return true;
  346. }
  347. bool nob_copy_file(const char *src_path, const char *dst_path)
  348. {
  349. nob_log(NOB_INFO, "copying %s -> %s", src_path, dst_path);
  350. #ifdef _WIN32
  351. if (!CopyFile(src_path, dst_path, FALSE)) {
  352. nob_log(NOB_ERROR, "Could not copy file: %lu", GetLastError());
  353. return false;
  354. }
  355. return true;
  356. #else
  357. int src_fd = -1;
  358. int dst_fd = -1;
  359. size_t buf_size = 32*1024;
  360. char *buf = NOB_REALLOC(NULL, buf_size);
  361. NOB_ASSERT(buf != NULL && "Buy more RAM lol!!");
  362. bool result = true;
  363. src_fd = open(src_path, O_RDONLY);
  364. if (src_fd < 0) {
  365. nob_log(NOB_ERROR, "Could not open file %s: %s", src_path, strerror(errno));
  366. nob_return_defer(false);
  367. }
  368. struct stat src_stat;
  369. if (fstat(src_fd, &src_stat) < 0) {
  370. nob_log(NOB_ERROR, "Could not get mode of file %s: %s", src_path, strerror(errno));
  371. nob_return_defer(false);
  372. }
  373. dst_fd = open(dst_path, O_CREAT | O_TRUNC | O_WRONLY, src_stat.st_mode);
  374. if (dst_fd < 0) {
  375. nob_log(NOB_ERROR, "Could not create file %s: %s", dst_path, strerror(errno));
  376. nob_return_defer(false);
  377. }
  378. for (;;) {
  379. ssize_t n = read(src_fd, buf, buf_size);
  380. if (n == 0) break;
  381. if (n < 0) {
  382. nob_log(NOB_ERROR, "Could not read from file %s: %s", src_path, strerror(errno));
  383. nob_return_defer(false);
  384. }
  385. char *buf2 = buf;
  386. while (n > 0) {
  387. ssize_t m = write(dst_fd, buf2, n);
  388. if (m < 0) {
  389. nob_log(NOB_ERROR, "Could not write to file %s: %s", dst_path, strerror(errno));
  390. nob_return_defer(false);
  391. }
  392. n -= m;
  393. buf2 += m;
  394. }
  395. }
  396. defer:
  397. free(buf);
  398. close(src_fd);
  399. close(dst_fd);
  400. return result;
  401. #endif
  402. }
  403. void nob_cmd_render(Nob_Cmd cmd, Nob_String_Builder *render)
  404. {
  405. for (size_t i = 0; i < cmd.count; ++i) {
  406. const char *arg = cmd.items[i];
  407. if (arg == NULL) break;
  408. if (i > 0) nob_sb_append_cstr(render, " ");
  409. if (!strchr(arg, ' ')) {
  410. nob_sb_append_cstr(render, arg);
  411. } else {
  412. nob_da_append(render, '\'');
  413. nob_sb_append_cstr(render, arg);
  414. nob_da_append(render, '\'');
  415. }
  416. }
  417. }
  418. Nob_Proc nob_cmd_run_async(Nob_Cmd cmd)
  419. {
  420. if (cmd.count < 1) {
  421. nob_log(NOB_ERROR, "Could not run empty command");
  422. return NOB_INVALID_PROC;
  423. }
  424. Nob_String_Builder sb = {0};
  425. nob_cmd_render(cmd, &sb);
  426. nob_sb_append_null(&sb);
  427. nob_log(NOB_INFO, "CMD: %s", sb.items);
  428. nob_sb_free(sb);
  429. memset(&sb, 0, sizeof(sb));
  430. #ifdef _WIN32
  431. // https://docs.microsoft.com/en-us/windows/win32/procthread/creating-a-child-process-with-redirected-input-and-output
  432. STARTUPINFO siStartInfo;
  433. ZeroMemory(&siStartInfo, sizeof(siStartInfo));
  434. siStartInfo.cb = sizeof(STARTUPINFO);
  435. // NOTE: theoretically setting NULL to std handles should not be a problem
  436. // https://docs.microsoft.com/en-us/windows/console/getstdhandle?redirectedfrom=MSDN#attachdetach-behavior
  437. // TODO: check for errors in GetStdHandle
  438. siStartInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
  439. siStartInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
  440. siStartInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
  441. siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
  442. PROCESS_INFORMATION piProcInfo;
  443. ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));
  444. // TODO: use a more reliable rendering of the command instead of cmd_render
  445. // cmd_render is for logging primarily
  446. nob_cmd_render(cmd, &sb);
  447. nob_sb_append_null(&sb);
  448. BOOL bSuccess = CreateProcessA(NULL, sb.items, NULL, NULL, TRUE, 0, NULL, NULL, &siStartInfo, &piProcInfo);
  449. nob_sb_free(sb);
  450. if (!bSuccess) {
  451. nob_log(NOB_ERROR, "Could not create child process: %lu", GetLastError());
  452. return NOB_INVALID_PROC;
  453. }
  454. CloseHandle(piProcInfo.hThread);
  455. return piProcInfo.hProcess;
  456. #else
  457. pid_t cpid = fork();
  458. if (cpid < 0) {
  459. nob_log(NOB_ERROR, "Could not fork child process: %s", strerror(errno));
  460. return NOB_INVALID_PROC;
  461. }
  462. if (cpid == 0) {
  463. // NOTE: This leaks a bit of memory in the child process.
  464. // But do we actually care? It's a one off leak anyway...
  465. Nob_Cmd cmd_null = {0};
  466. nob_da_append_many(&cmd_null, cmd.items, cmd.count);
  467. nob_cmd_append(&cmd_null, NULL);
  468. if (execvp(cmd.items[0], (char * const*) cmd_null.items) < 0) {
  469. nob_log(NOB_ERROR, "Could not exec child process: %s", strerror(errno));
  470. exit(1);
  471. }
  472. NOB_ASSERT(0 && "unreachable");
  473. }
  474. return cpid;
  475. #endif
  476. }
  477. bool nob_procs_wait(Nob_Procs procs)
  478. {
  479. bool success = true;
  480. for (size_t i = 0; i < procs.count; ++i) {
  481. success = nob_proc_wait(procs.items[i]) && success;
  482. }
  483. return success;
  484. }
  485. bool nob_proc_wait(Nob_Proc proc)
  486. {
  487. if (proc == NOB_INVALID_PROC) return false;
  488. #ifdef _WIN32
  489. DWORD result = WaitForSingleObject(
  490. proc, // HANDLE hHandle,
  491. INFINITE // DWORD dwMilliseconds
  492. );
  493. if (result == WAIT_FAILED) {
  494. nob_log(NOB_ERROR, "could not wait on child process: %lu", GetLastError());
  495. return false;
  496. }
  497. DWORD exit_status;
  498. if (!GetExitCodeProcess(proc, &exit_status)) {
  499. nob_log(NOB_ERROR, "could not get process exit code: %lu", GetLastError());
  500. return false;
  501. }
  502. if (exit_status != 0) {
  503. nob_log(NOB_ERROR, "command exited with exit code %lu", exit_status);
  504. return false;
  505. }
  506. CloseHandle(proc);
  507. return true;
  508. #else
  509. for (;;) {
  510. int wstatus = 0;
  511. if (waitpid(proc, &wstatus, 0) < 0) {
  512. nob_log(NOB_ERROR, "could not wait on command (pid %d): %s", proc, strerror(errno));
  513. return false;
  514. }
  515. if (WIFEXITED(wstatus)) {
  516. int exit_status = WEXITSTATUS(wstatus);
  517. if (exit_status != 0) {
  518. nob_log(NOB_ERROR, "command exited with exit code %d", exit_status);
  519. return false;
  520. }
  521. break;
  522. }
  523. if (WIFSIGNALED(wstatus)) {
  524. nob_log(NOB_ERROR, "command process was terminated by %s", strsignal(WTERMSIG(wstatus)));
  525. return false;
  526. }
  527. }
  528. return true;
  529. #endif
  530. }
  531. bool nob_cmd_run_sync(Nob_Cmd cmd)
  532. {
  533. Nob_Proc p = nob_cmd_run_async(cmd);
  534. if (p == NOB_INVALID_PROC) return false;
  535. return nob_proc_wait(p);
  536. }
  537. char *nob_shift_args(int *argc, char ***argv)
  538. {
  539. NOB_ASSERT(*argc > 0);
  540. char *result = **argv;
  541. (*argv) += 1;
  542. (*argc) -= 1;
  543. return result;
  544. }
  545. void nob_log(Nob_Log_Level level, const char *fmt, ...)
  546. {
  547. switch (level) {
  548. case NOB_INFO:
  549. fprintf(stderr, "[INFO] ");
  550. break;
  551. case NOB_WARNING:
  552. fprintf(stderr, "[WARNING] ");
  553. break;
  554. case NOB_ERROR:
  555. fprintf(stderr, "[ERROR] ");
  556. break;
  557. default:
  558. NOB_ASSERT(0 && "unreachable");
  559. }
  560. va_list args;
  561. va_start(args, fmt);
  562. vfprintf(stderr, fmt, args);
  563. va_end(args);
  564. fprintf(stderr, "\n");
  565. }
  566. bool nob_read_entire_dir(const char *parent, Nob_File_Paths *children)
  567. {
  568. bool result = true;
  569. DIR *dir = NULL;
  570. dir = opendir(parent);
  571. if (dir == NULL) {
  572. nob_log(NOB_ERROR, "Could not open directory %s: %s", parent, strerror(errno));
  573. nob_return_defer(false);
  574. }
  575. errno = 0;
  576. struct dirent *ent = readdir(dir);
  577. while (ent != NULL) {
  578. nob_da_append(children, nob_temp_strdup(ent->d_name));
  579. ent = readdir(dir);
  580. }
  581. if (errno != 0) {
  582. nob_log(NOB_ERROR, "Could not read directory %s: %s", parent, strerror(errno));
  583. nob_return_defer(false);
  584. }
  585. defer:
  586. if (dir) closedir(dir);
  587. return result;
  588. }
  589. bool nob_write_entire_file(const char *path, const void *data, size_t size)
  590. {
  591. bool result = true;
  592. FILE *f = fopen(path, "wb");
  593. if (f == NULL) {
  594. nob_log(NOB_ERROR, "Could not open file %s for writing: %s\n", path, strerror(errno));
  595. nob_return_defer(false);
  596. }
  597. // len
  598. // v
  599. // aaaaaaaaaa
  600. // ^
  601. // data
  602. const char *buf = data;
  603. while (size > 0) {
  604. size_t n = fwrite(buf, 1, size, f);
  605. if (ferror(f)) {
  606. nob_log(NOB_ERROR, "Could not write into file %s: %s\n", path, strerror(errno));
  607. nob_return_defer(false);
  608. }
  609. size -= n;
  610. buf += n;
  611. }
  612. defer:
  613. if (f) fclose(f);
  614. return result;
  615. }
  616. Nob_File_Type nob_get_file_type(const char *path)
  617. {
  618. #ifdef _WIN32
  619. DWORD attr = GetFileAttributesA(path);
  620. if (attr == INVALID_FILE_ATTRIBUTES) {
  621. nob_log(NOB_ERROR, "Could not get file attributes of %s: %lu", path, GetLastError());
  622. return -1;
  623. }
  624. if (attr & FILE_ATTRIBUTE_DIRECTORY) return NOB_FILE_DIRECTORY;
  625. // TODO: detect symlinks on Windows (whatever that means on Windows anyway)
  626. return NOB_FILE_REGULAR;
  627. #else // _WIN32
  628. struct stat statbuf;
  629. if (stat(path, &statbuf) < 0) {
  630. nob_log(NOB_ERROR, "Could not get stat of %s: %s", path, strerror(errno));
  631. return -1;
  632. }
  633. switch (statbuf.st_mode & S_IFMT) {
  634. case S_IFDIR: return NOB_FILE_DIRECTORY;
  635. case S_IFREG: return NOB_FILE_REGULAR;
  636. case S_IFLNK: return NOB_FILE_SYMLINK;
  637. default: return NOB_FILE_OTHER;
  638. }
  639. #endif // _WIN32
  640. }
  641. bool nob_copy_directory_recursively(const char *src_path, const char *dst_path)
  642. {
  643. bool result = true;
  644. Nob_File_Paths children = {0};
  645. Nob_String_Builder src_sb = {0};
  646. Nob_String_Builder dst_sb = {0};
  647. size_t temp_checkpoint = nob_temp_save();
  648. Nob_File_Type type = nob_get_file_type(src_path);
  649. if (type < 0) return false;
  650. switch (type) {
  651. case NOB_FILE_DIRECTORY: {
  652. if (!nob_mkdir_if_not_exists(dst_path)) nob_return_defer(false);
  653. if (!nob_read_entire_dir(src_path, &children)) nob_return_defer(false);
  654. for (size_t i = 0; i < children.count; ++i) {
  655. if (strcmp(children.items[i], ".") == 0) continue;
  656. if (strcmp(children.items[i], "..") == 0) continue;
  657. src_sb.count = 0;
  658. nob_sb_append_cstr(&src_sb, src_path);
  659. nob_sb_append_cstr(&src_sb, "/");
  660. nob_sb_append_cstr(&src_sb, children.items[i]);
  661. nob_sb_append_null(&src_sb);
  662. dst_sb.count = 0;
  663. nob_sb_append_cstr(&dst_sb, dst_path);
  664. nob_sb_append_cstr(&dst_sb, "/");
  665. nob_sb_append_cstr(&dst_sb, children.items[i]);
  666. nob_sb_append_null(&dst_sb);
  667. if (!nob_copy_directory_recursively(src_sb.items, dst_sb.items)) {
  668. nob_return_defer(false);
  669. }
  670. }
  671. } break;
  672. case NOB_FILE_REGULAR: {
  673. if (!nob_copy_file(src_path, dst_path)) {
  674. nob_return_defer(false);
  675. }
  676. } break;
  677. case NOB_FILE_SYMLINK: {
  678. nob_log(NOB_WARNING, "TODO: Copying symlinks is not supported yet");
  679. } break;
  680. case NOB_FILE_OTHER: {
  681. nob_log(NOB_ERROR, "Unsupported type of file %s", src_path);
  682. nob_return_defer(false);
  683. } break;
  684. default: NOB_ASSERT(0 && "unreachable");
  685. }
  686. defer:
  687. nob_temp_rewind(temp_checkpoint);
  688. nob_da_free(src_sb);
  689. nob_da_free(dst_sb);
  690. nob_da_free(children);
  691. return result;
  692. }
  693. char *nob_temp_strdup(const char *cstr)
  694. {
  695. size_t n = strlen(cstr);
  696. char *result = nob_temp_alloc(n + 1);
  697. NOB_ASSERT(result != NULL && "Increase NOB_TEMP_CAPACITY");
  698. memcpy(result, cstr, n);
  699. result[n] = '\0';
  700. return result;
  701. }
  702. void *nob_temp_alloc(size_t size)
  703. {
  704. if (nob_temp_size + size > NOB_TEMP_CAPACITY) return NULL;
  705. void *result = &nob_temp[nob_temp_size];
  706. nob_temp_size += size;
  707. return result;
  708. }
  709. char *nob_temp_sprintf(const char *format, ...)
  710. {
  711. va_list args;
  712. va_start(args, format);
  713. int n = vsnprintf(NULL, 0, format, args);
  714. va_end(args);
  715. NOB_ASSERT(n >= 0);
  716. char *result = nob_temp_alloc(n + 1);
  717. NOB_ASSERT(result != NULL && "Extend the size of the temporary allocator");
  718. // TODO: use proper arenas for the temporary allocator;
  719. va_start(args, format);
  720. vsnprintf(result, n + 1, format, args);
  721. va_end(args);
  722. return result;
  723. }
  724. void nob_temp_reset(void)
  725. {
  726. nob_temp_size = 0;
  727. }
  728. size_t nob_temp_save(void)
  729. {
  730. return nob_temp_size;
  731. }
  732. void nob_temp_rewind(size_t checkpoint)
  733. {
  734. nob_temp_size = checkpoint;
  735. }
  736. const char *nob_temp_sv_to_cstr(Nob_String_View sv)
  737. {
  738. char *result = nob_temp_alloc(sv.count + 1);
  739. NOB_ASSERT(result != NULL && "Extend the size of the temporary allocator");
  740. memcpy(result, sv.data, sv.count);
  741. result[sv.count] = '\0';
  742. return result;
  743. }
  744. int nob_needs_rebuild(const char *output_path, const char **input_paths, size_t input_paths_count)
  745. {
  746. #ifdef _WIN32
  747. BOOL bSuccess;
  748. HANDLE output_path_fd = CreateFile(output_path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL);
  749. if (output_path_fd == INVALID_HANDLE_VALUE) {
  750. // NOTE: if output does not exist it 100% must be rebuilt
  751. if (GetLastError() == ERROR_FILE_NOT_FOUND) return 1;
  752. nob_log(NOB_ERROR, "Could not open file %s: %lu", output_path, GetLastError());
  753. return -1;
  754. }
  755. FILETIME output_path_time;
  756. bSuccess = GetFileTime(output_path_fd, NULL, NULL, &output_path_time);
  757. CloseHandle(output_path_fd);
  758. if (!bSuccess) {
  759. nob_log(NOB_ERROR, "Could not get time of %s: %lu", output_path, GetLastError());
  760. return -1;
  761. }
  762. for (size_t i = 0; i < input_paths_count; ++i) {
  763. const char *input_path = input_paths[i];
  764. HANDLE input_path_fd = CreateFile(input_path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL);
  765. if (input_path_fd == INVALID_HANDLE_VALUE) {
  766. // NOTE: non-existing input is an error cause it is needed for building in the first place
  767. nob_log(NOB_ERROR, "Could not open file %s: %lu", input_path, GetLastError());
  768. return -1;
  769. }
  770. FILETIME input_path_time;
  771. bSuccess = GetFileTime(input_path_fd, NULL, NULL, &input_path_time);
  772. CloseHandle(input_path_fd);
  773. if (!bSuccess) {
  774. nob_log(NOB_ERROR, "Could not get time of %s: %lu", input_path, GetLastError());
  775. return -1;
  776. }
  777. // NOTE: if even a single input_path is fresher than output_path that's 100% rebuild
  778. if (CompareFileTime(&input_path_time, &output_path_time) == 1) return 1;
  779. }
  780. return 0;
  781. #else
  782. struct stat statbuf = {0};
  783. if (stat(output_path, &statbuf) < 0) {
  784. // NOTE: if output does not exist it 100% must be rebuilt
  785. if (errno == ENOENT) return 1;
  786. nob_log(NOB_ERROR, "could not stat %s: %s", output_path, strerror(errno));
  787. return -1;
  788. }
  789. int output_path_time = statbuf.st_mtime;
  790. for (size_t i = 0; i < input_paths_count; ++i) {
  791. const char *input_path = input_paths[i];
  792. if (stat(input_path, &statbuf) < 0) {
  793. // NOTE: non-existing input is an error cause it is needed for building in the first place
  794. nob_log(NOB_ERROR, "could not stat %s: %s", input_path, strerror(errno));
  795. return -1;
  796. }
  797. int input_path_time = statbuf.st_mtime;
  798. // NOTE: if even a single input_path is fresher than output_path that's 100% rebuild
  799. if (input_path_time > output_path_time) return 1;
  800. }
  801. return 0;
  802. #endif
  803. }
  804. int nob_needs_rebuild1(const char *output_path, const char *input_path)
  805. {
  806. return nob_needs_rebuild(output_path, &input_path, 1);
  807. }
  808. bool nob_rename(const char *old_path, const char *new_path)
  809. {
  810. nob_log(NOB_INFO, "renaming %s -> %s", old_path, new_path);
  811. #ifdef _WIN32
  812. if (!MoveFileEx(old_path, new_path, MOVEFILE_REPLACE_EXISTING)) {
  813. nob_log(NOB_ERROR, "could not rename %s to %s: %lu", old_path, new_path, GetLastError());
  814. return false;
  815. }
  816. #else
  817. if (rename(old_path, new_path) < 0) {
  818. nob_log(NOB_ERROR, "could not rename %s to %s: %s", old_path, new_path, strerror(errno));
  819. return false;
  820. }
  821. #endif // _WIN32
  822. return true;
  823. }
  824. bool nob_read_entire_file(const char *path, Nob_String_Builder *sb)
  825. {
  826. bool result = true;
  827. FILE *f = fopen(path, "rb");
  828. if (f == NULL) nob_return_defer(false);
  829. if (fseek(f, 0, SEEK_END) < 0) nob_return_defer(false);
  830. long m = ftell(f);
  831. if (m < 0) nob_return_defer(false);
  832. if (fseek(f, 0, SEEK_SET) < 0) nob_return_defer(false);
  833. size_t new_count = sb->count + m;
  834. if (new_count > sb->capacity) {
  835. sb->items = realloc(sb->items, new_count);
  836. NOB_ASSERT(sb->items != NULL && "Buy more RAM lool!!");
  837. sb->capacity = new_count;
  838. }
  839. fread(sb->items + sb->count, m, 1, f);
  840. if (ferror(f)) {
  841. // TODO: Afaik, ferror does not set errno. So the error reporting in defer is not correct in this case.
  842. nob_return_defer(false);
  843. }
  844. sb->count = new_count;
  845. defer:
  846. if (!result) nob_log(NOB_ERROR, "Could not read file %s: %s", path, strerror(errno));
  847. if (f) fclose(f);
  848. return result;
  849. }
  850. Nob_String_View nob_sv_chop_by_delim(Nob_String_View *sv, char delim)
  851. {
  852. size_t i = 0;
  853. while (i < sv->count && sv->data[i] != delim) {
  854. i += 1;
  855. }
  856. Nob_String_View result = nob_sv_from_parts(sv->data, i);
  857. if (i < sv->count) {
  858. sv->count -= i + 1;
  859. sv->data += i + 1;
  860. } else {
  861. sv->count -= i;
  862. sv->data += i;
  863. }
  864. return result;
  865. }
  866. Nob_String_View nob_sv_from_parts(const char *data, size_t count)
  867. {
  868. Nob_String_View sv;
  869. sv.count = count;
  870. sv.data = data;
  871. return sv;
  872. }
  873. Nob_String_View nob_sv_trim_left(Nob_String_View sv)
  874. {
  875. size_t i = 0;
  876. while (i < sv.count && isspace(sv.data[i])) {
  877. i += 1;
  878. }
  879. return nob_sv_from_parts(sv.data + i, sv.count - i);
  880. }
  881. Nob_String_View nob_sv_trim_right(Nob_String_View sv)
  882. {
  883. size_t i = 0;
  884. while (i < sv.count && isspace(sv.data[sv.count - 1 - i])) {
  885. i += 1;
  886. }
  887. return nob_sv_from_parts(sv.data, sv.count - i);
  888. }
  889. Nob_String_View nob_sv_trim(Nob_String_View sv)
  890. {
  891. return nob_sv_trim_right(nob_sv_trim_left(sv));
  892. }
  893. Nob_String_View nob_sv_from_cstr(const char *cstr)
  894. {
  895. return nob_sv_from_parts(cstr, strlen(cstr));
  896. }
  897. bool nob_sv_eq(Nob_String_View a, Nob_String_View b)
  898. {
  899. if (a.count != b.count) {
  900. return false;
  901. } else {
  902. return memcmp(a.data, b.data, a.count) == 0;
  903. }
  904. }
  905. // RETURNS:
  906. // 0 - file does not exists
  907. // 1 - file exists
  908. // -1 - error while checking if file exists. The error is logged
  909. int nob_file_exists(const char *file_path)
  910. {
  911. #if _WIN32
  912. // TODO: distinguish between "does not exists" and other errors
  913. DWORD dwAttrib = GetFileAttributesA(file_path);
  914. return dwAttrib != INVALID_FILE_ATTRIBUTES;
  915. #else
  916. struct stat statbuf;
  917. if (stat(file_path, &statbuf) < 0) {
  918. if (errno == ENOENT) return 0;
  919. nob_log(NOB_ERROR, "Could not check if file %s exists: %s", file_path, strerror(errno));
  920. return -1;
  921. }
  922. return 1;
  923. #endif
  924. }
  925. // minirent.h SOURCE BEGIN ////////////////////////////////////////
  926. #ifdef _WIN32
  927. struct DIR
  928. {
  929. HANDLE hFind;
  930. WIN32_FIND_DATA data;
  931. struct dirent *dirent;
  932. };
  933. DIR *opendir(const char *dirpath)
  934. {
  935. assert(dirpath);
  936. char buffer[MAX_PATH];
  937. snprintf(buffer, MAX_PATH, "%s\\*", dirpath);
  938. DIR *dir = (DIR*)calloc(1, sizeof(DIR));
  939. dir->hFind = FindFirstFile(buffer, &dir->data);
  940. if (dir->hFind == INVALID_HANDLE_VALUE) {
  941. // TODO: opendir should set errno accordingly on FindFirstFile fail
  942. // https://docs.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-getlasterror
  943. errno = ENOSYS;
  944. goto fail;
  945. }
  946. return dir;
  947. fail:
  948. if (dir) {
  949. free(dir);
  950. }
  951. return NULL;
  952. }
  953. struct dirent *readdir(DIR *dirp)
  954. {
  955. assert(dirp);
  956. if (dirp->dirent == NULL) {
  957. dirp->dirent = (struct dirent*)calloc(1, sizeof(struct dirent));
  958. } else {
  959. if(!FindNextFile(dirp->hFind, &dirp->data)) {
  960. if (GetLastError() != ERROR_NO_MORE_FILES) {
  961. // TODO: readdir should set errno accordingly on FindNextFile fail
  962. // https://docs.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-getlasterror
  963. errno = ENOSYS;
  964. }
  965. return NULL;
  966. }
  967. }
  968. memset(dirp->dirent->d_name, 0, sizeof(dirp->dirent->d_name));
  969. strncpy(
  970. dirp->dirent->d_name,
  971. dirp->data.cFileName,
  972. sizeof(dirp->dirent->d_name) - 1);
  973. return dirp->dirent;
  974. }
  975. int closedir(DIR *dirp)
  976. {
  977. assert(dirp);
  978. if(!FindClose(dirp->hFind)) {
  979. // TODO: closedir should set errno accordingly on FindClose fail
  980. // https://docs.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-getlasterror
  981. errno = ENOSYS;
  982. return -1;
  983. }
  984. if (dirp->dirent) {
  985. free(dirp->dirent);
  986. }
  987. free(dirp);
  988. return 0;
  989. }
  990. #endif // _WIN32
  991. // minirent.h SOURCE END ////////////////////////////////////////
  992. #endif