nob.h 37 KB

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