nobuild.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. // Copyright 2021 Alexey Kutepov <[email protected]>
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining
  4. // a copy of this software and associated documentation files (the
  5. // "Software"), to deal in the Software without restriction, including
  6. // without limitation the rights to use, copy, modify, merge, publish,
  7. // distribute, sublicense, and/or sell copies of the Software, and to
  8. // permit persons to whom the Software is furnished to do so, subject to
  9. // the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be
  12. // included in all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  18. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  19. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  20. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. //
  22. // ============================================================
  23. //
  24. // nobuild — 0.2.0 — Header only library for writing build recipes in C.
  25. //
  26. // https://github.com/tsoding/nobuild
  27. //
  28. // ============================================================
  29. #ifndef NOBUILD_H_
  30. #define NOBUILD_H_
  31. #include <assert.h>
  32. #include <stdio.h>
  33. #include <stdlib.h>
  34. #include <stdarg.h>
  35. #include <string.h>
  36. #include <errno.h>
  37. #ifdef _WIN32
  38. # define WIN32_LEAN_AND_MEAN
  39. # include "windows.h"
  40. # include <process.h>
  41. // minirent.h HEADER BEGIN ////////////////////////////////////////
  42. // Copyright 2021 Alexey Kutepov <[email protected]>
  43. //
  44. // Permission is hereby granted, free of charge, to any person obtaining
  45. // a copy of this software and associated documentation files (the
  46. // "Software"), to deal in the Software without restriction, including
  47. // without limitation the rights to use, copy, modify, merge, publish,
  48. // distribute, sublicense, and/or sell copies of the Software, and to
  49. // permit persons to whom the Software is furnished to do so, subject to
  50. // the following conditions:
  51. //
  52. // The above copyright notice and this permission notice shall be
  53. // included in all copies or substantial portions of the Software.
  54. //
  55. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  56. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  57. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  58. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  59. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  60. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  61. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  62. //
  63. // ============================================================
  64. //
  65. // minirent — 0.0.1 — A subset of dirent interface for Windows.
  66. //
  67. // https://github.com/tsoding/minirent
  68. //
  69. // ============================================================
  70. //
  71. // ChangeLog (https://semver.org/ is implied)
  72. //
  73. // 0.0.1 First Official Release
  74. #ifndef MINIRENT_H_
  75. #define MINIRENT_H_
  76. #define WIN32_LEAN_AND_MEAN
  77. #include "windows.h"
  78. struct dirent
  79. {
  80. char d_name[MAX_PATH+1];
  81. };
  82. typedef struct DIR DIR;
  83. DIR *opendir(const char *dirpath);
  84. struct dirent *readdir(DIR *dirp);
  85. int closedir(DIR *dirp);
  86. #endif // MINIRENT_H_
  87. // minirent.h HEADER END ////////////////////////////////////////
  88. #else
  89. # include <sys/stat.h>
  90. # include <sys/types.h>
  91. # include <sys/wait.h>
  92. # include <unistd.h>
  93. # include <dirent.h>
  94. #endif // _WIN32
  95. // TODO(#1): no way to disable echo in nobuild scripts
  96. // TODO(#2): no way to ignore fails
  97. #ifdef _WIN32
  98. # define PATH_SEP "\\"
  99. #else
  100. # define PATH_SEP "/"
  101. #endif // _WIN32
  102. #define PATH_SEP_LEN (sizeof(PATH_SEP) - 1)
  103. #define FOREACH_VARGS(param, arg, args, body) \
  104. do { \
  105. va_start(args, param); \
  106. for (const char *arg = va_arg(args, const char *); \
  107. arg != NULL; \
  108. arg = va_arg(args, const char *)) \
  109. { \
  110. body; \
  111. } \
  112. va_end(args); \
  113. } while(0)
  114. #define FOREACH_ARRAY(type, item, items, body) \
  115. do { \
  116. for (size_t i = 0; \
  117. i < sizeof(items) / sizeof((items)[0]); \
  118. ++i) \
  119. { \
  120. type item = items[i]; \
  121. body; \
  122. } \
  123. } while(0)
  124. #define FOREACH_FILE_IN_DIR(file, dirpath, body) \
  125. do { \
  126. struct dirent *dp = NULL; \
  127. DIR *dir = opendir(dirpath); \
  128. while ((dp = readdir(dir))) { \
  129. const char *file = dp->d_name; \
  130. body; \
  131. } \
  132. closedir(dir); \
  133. } while(0)
  134. // TODO(#5): there is no way to redirect the output of CMD to a file
  135. #define CMD(...) \
  136. do { \
  137. INFO(JOIN(" ", __VA_ARGS__)); \
  138. cmd_impl(69, __VA_ARGS__, NULL); \
  139. } while(0)
  140. const char *concat_impl(int ignore, ...);
  141. const char *concat_sep_impl(const char *sep, ...);
  142. const char *build__join(const char *sep, ...);
  143. int nobuild__ends_with(const char *str, const char *postfix);
  144. int nobuild__is_dir(const char *path);
  145. void mkdirs_impl(int ignore, ...);
  146. void cmd_impl(int ignore, ...);
  147. void nobuild_exec(const char **argv);
  148. const char *remove_ext(const char *path);
  149. char *shift(int *argc, char ***argv);
  150. void nobuild__rm(const char *path);
  151. #define CONCAT(...) concat_impl(69, __VA_ARGS__, NULL)
  152. #define CONCAT_SEP(sep, ...) build__deprecated_concat_sep(sep, __VA_ARGS__, NULL)
  153. #define JOIN(sep, ...) build__join(sep, __VA_ARGS__, NULL)
  154. #define PATH(...) JOIN(PATH_SEP, __VA_ARGS__)
  155. #define MKDIRS(...) mkdirs_impl(69, __VA_ARGS__, NULL)
  156. #define NOEXT(path) nobuild__remove_ext(path)
  157. #define ENDS_WITH(str, postfix) nobuild__ends_with(str, postfix)
  158. #define IS_DIR(path) nobuild__is_dir(path)
  159. #define RM(path) \
  160. do { \
  161. INFO("rm %s", path); \
  162. nobuild__rm(path); \
  163. } while(0)
  164. void nobuild_log(FILE *stream, const char *tag, const char *fmt, ...);
  165. void nobuild_vlog(FILE *stream, const char *tag, const char *fmt, va_list args);
  166. void INFO(const char *fmt, ...);
  167. void WARN(const char *fmt, ...);
  168. void ERRO(const char *fmt, ...);
  169. #endif // NOBUILD_H_
  170. #ifdef NOBUILD_IMPLEMENTATION
  171. #ifdef _WIN32
  172. // minirent.h IMPLEMENTATION BEGIN ////////////////////////////////////////
  173. struct DIR
  174. {
  175. HANDLE hFind;
  176. WIN32_FIND_DATA data;
  177. struct dirent *dirent;
  178. };
  179. DIR *opendir(const char *dirpath)
  180. {
  181. assert(dirpath);
  182. char buffer[MAX_PATH];
  183. snprintf(buffer, MAX_PATH, "%s\\*", dirpath);
  184. DIR *dir = (DIR*)calloc(1, sizeof(DIR));
  185. dir->hFind = FindFirstFile(buffer, &dir->data);
  186. if (dir->hFind == INVALID_HANDLE_VALUE) {
  187. errno = ENOSYS;
  188. goto fail;
  189. }
  190. return dir;
  191. fail:
  192. if (dir) {
  193. free(dir);
  194. }
  195. return NULL;
  196. }
  197. struct dirent *readdir(DIR *dirp)
  198. {
  199. assert(dirp);
  200. if (dirp->dirent == NULL) {
  201. dirp->dirent = (struct dirent*)calloc(1, sizeof(struct dirent));
  202. } else {
  203. if(!FindNextFile(dirp->hFind, &dirp->data)) {
  204. if (GetLastError() != ERROR_NO_MORE_FILES) {
  205. errno = ENOSYS;
  206. }
  207. return NULL;
  208. }
  209. }
  210. memset(dirp->dirent->d_name, 0, sizeof(dirp->dirent->d_name));
  211. strncpy(
  212. dirp->dirent->d_name,
  213. dirp->data.cFileName,
  214. sizeof(dirp->dirent->d_name) - 1);
  215. return dirp->dirent;
  216. }
  217. int closedir(DIR *dirp)
  218. {
  219. assert(dirp);
  220. if(!FindClose(dirp->hFind)) {
  221. errno = ENOSYS;
  222. return -1;
  223. }
  224. if (dirp->dirent) {
  225. free(dirp->dirent);
  226. }
  227. free(dirp);
  228. return 0;
  229. }
  230. // minirent.h IMPLEMENTATION END ////////////////////////////////////////
  231. #endif // _WIN32
  232. const char *build__join(const char *sep, ...)
  233. {
  234. const size_t sep_len = strlen(sep);
  235. size_t length = 0;
  236. size_t seps_count = 0;
  237. va_list args;
  238. FOREACH_VARGS(sep, arg, args, {
  239. length += strlen(arg);
  240. seps_count += 1;
  241. });
  242. assert(length > 0);
  243. seps_count -= 1;
  244. char *result = malloc(length + seps_count * sep_len + 1);
  245. length = 0;
  246. FOREACH_VARGS(sep, arg, args, {
  247. size_t n = strlen(arg);
  248. memcpy(result + length, arg, n);
  249. length += n;
  250. if (seps_count > 0) {
  251. memcpy(result + length, sep, sep_len);
  252. length += sep_len;
  253. seps_count -= 1;
  254. }
  255. });
  256. result[length] = '\0';
  257. return result;
  258. }
  259. const char *build__deprecated_concat_sep(const char *sep, ...)
  260. {
  261. WARN("DEPRECATED: Please don't use `CONCAT_SEP(sep, ...)`. Please use JOIN(sep, ...) instead. `CONCAT_SEP(sep, ...)` will be removed in the next major release.");
  262. const size_t sep_len = strlen(sep);
  263. size_t length = 0;
  264. size_t seps_count = 0;
  265. va_list args;
  266. FOREACH_VARGS(sep, arg, args, {
  267. length += strlen(arg);
  268. seps_count += 1;
  269. });
  270. assert(length > 0);
  271. seps_count -= 1;
  272. char *result = malloc(length + seps_count * sep_len + 1);
  273. length = 0;
  274. FOREACH_VARGS(sep, arg, args, {
  275. size_t n = strlen(arg);
  276. memcpy(result + length, arg, n);
  277. length += n;
  278. if (seps_count > 0) {
  279. memcpy(result + length, sep, sep_len);
  280. length += sep_len;
  281. seps_count -= 1;
  282. }
  283. });
  284. result[length] = '\0';
  285. return result;
  286. }
  287. const char *concat_sep_impl(const char *sep, ...)
  288. {
  289. WARN("DEPRECATED: Please don't use `concat_sep_impl(sep, ...)`. Please use JOIN(sep, ...) instead. `concat_sep_impl(sep, ...)` will be removed in the next major release.");
  290. const size_t sep_len = strlen(sep);
  291. size_t length = 0;
  292. size_t seps_count = 0;
  293. va_list args;
  294. FOREACH_VARGS(sep, arg, args, {
  295. length += strlen(arg);
  296. seps_count += 1;
  297. });
  298. assert(length > 0);
  299. seps_count -= 1;
  300. char *result = malloc(length + seps_count * sep_len + 1);
  301. length = 0;
  302. FOREACH_VARGS(sep, arg, args, {
  303. size_t n = strlen(arg);
  304. memcpy(result + length, arg, n);
  305. length += n;
  306. if (seps_count > 0) {
  307. memcpy(result + length, sep, sep_len);
  308. length += sep_len;
  309. seps_count -= 1;
  310. }
  311. });
  312. result[length] = '\0';
  313. return result;
  314. }
  315. void mkdirs_impl(int ignore, ...)
  316. {
  317. size_t length = 0;
  318. size_t seps_count = 0;
  319. va_list args;
  320. FOREACH_VARGS(ignore, arg, args, {
  321. length += strlen(arg);
  322. seps_count += 1;
  323. });
  324. assert(length > 0);
  325. seps_count -= 1;
  326. char *result = malloc(length + seps_count * PATH_SEP_LEN + 1);
  327. length = 0;
  328. FOREACH_VARGS(ignore, arg, args, {
  329. size_t n = strlen(arg);
  330. memcpy(result + length, arg, n);
  331. length += n;
  332. if (seps_count > 0) {
  333. memcpy(result + length, PATH_SEP, PATH_SEP_LEN);
  334. length += PATH_SEP_LEN;
  335. seps_count -= 1;
  336. }
  337. result[length] = '\0';
  338. INFO("mkdirs %s", result);
  339. if (mkdir(result, 0755) < 0) {
  340. if (errno == EEXIST) {
  341. WARN("directory %s already exists", result);
  342. } else {
  343. ERRO("could not create directory %s: %s", result, strerror(errno));
  344. exit(1);
  345. }
  346. }
  347. });
  348. }
  349. // TODO(#3): there is no way to remove a folder
  350. // TODO(#4): there is no way to remove a file
  351. const char *concat_impl(int ignore, ...)
  352. {
  353. size_t length = 0;
  354. va_list args;
  355. FOREACH_VARGS(ignore, arg, args, {
  356. length += strlen(arg);
  357. });
  358. char *result = malloc(length + 1);
  359. length = 0;
  360. FOREACH_VARGS(ignore, arg, args, {
  361. size_t n = strlen(arg);
  362. memcpy(result + length, arg, n);
  363. length += n;
  364. });
  365. result[length] = '\0';
  366. return result;
  367. }
  368. void nobuild_exec(const char **argv)
  369. {
  370. #ifdef _WIN32
  371. intptr_t status = _spawnvp(_P_WAIT, argv[0], (char * const*) argv);
  372. if (status < 0) {
  373. ERRO("could not start child process: %s", strerror(errno));
  374. exit(1);
  375. }
  376. if (status > 0) {
  377. ERRO("command exited with exit code %d", status);
  378. exit(1);
  379. }
  380. #else
  381. pid_t cpid = fork();
  382. if (cpid == -1) {
  383. ERRO("could not fork a child process: %s", strerror(errno));
  384. exit(1);
  385. }
  386. if (cpid == 0) {
  387. if (execvp(argv[0], (char * const*) argv) < 0) {
  388. ERRO("could not execute child process: %s", strerror(errno));
  389. exit(1);
  390. }
  391. } else {
  392. for (;;) {
  393. int wstatus = 0;
  394. wait(&wstatus);
  395. if (WIFEXITED(wstatus)) {
  396. int exit_status = WEXITSTATUS(wstatus);
  397. if (exit_status != 0) {
  398. ERRO("command exited with exit code %d", exit_status);
  399. exit(1);
  400. }
  401. break;
  402. }
  403. if (WIFSIGNALED(wstatus)) {
  404. ERRO("command process was terminated by signal %d", WTERMSIG(wstatus));
  405. exit(1);
  406. }
  407. }
  408. }
  409. #endif // _WIN32
  410. }
  411. void cmd_impl(int ignore, ...)
  412. {
  413. size_t argc = 0;
  414. va_list args;
  415. FOREACH_VARGS(ignore, arg, args, {
  416. argc += 1;
  417. });
  418. const char **argv = malloc(sizeof(const char*) * (argc + 1));
  419. argc = 0;
  420. FOREACH_VARGS(ignore, arg, args, {
  421. argv[argc++] = arg;
  422. });
  423. argv[argc] = NULL;
  424. assert(argc >= 1);
  425. nobuild_exec(argv);
  426. }
  427. const char *nobuild__remove_ext(const char *path)
  428. {
  429. size_t n = strlen(path);
  430. while (n > 0 && path[n - 1] != '.') {
  431. n -= 1;
  432. }
  433. if (n > 0) {
  434. char *result = malloc(n);
  435. memcpy(result, path, n);
  436. result[n - 1] = '\0';
  437. return result;
  438. } else {
  439. return path;
  440. }
  441. }
  442. const char *remove_ext(const char *path)
  443. {
  444. WARN("DEPRECATED: Please use `NOEXT(path)` instead of `remove_ext(path)`. `remove_ext(path)` will be removed in the next major release.");
  445. nobuild__remove_ext(path);
  446. }
  447. char *shift(int *argc, char ***argv)
  448. {
  449. assert(*argc > 0);
  450. char *result = **argv;
  451. *argv += 1;
  452. *argc -= 1;
  453. return result;
  454. }
  455. void nobuild_log(FILE *stream, const char *tag, const char *fmt, ...)
  456. {
  457. va_list args;
  458. va_start(args, fmt);
  459. nobuild_vlog(stream, tag, fmt, args);
  460. va_end(args);
  461. }
  462. void nobuild_vlog(FILE *stream, const char *tag, const char *fmt, va_list args)
  463. {
  464. fprintf(stream, "[%s] ", tag);
  465. vfprintf(stream, fmt, args);
  466. fprintf(stream, "\n");
  467. }
  468. void INFO(const char *fmt, ...)
  469. {
  470. va_list args;
  471. va_start(args, fmt);
  472. nobuild_vlog(stdout, "INFO", fmt, args);
  473. va_end(args);
  474. }
  475. void WARN(const char *fmt, ...)
  476. {
  477. va_list args;
  478. va_start(args, fmt);
  479. nobuild_vlog(stderr, "WARN", fmt, args);
  480. va_end(args);
  481. }
  482. void ERRO(const char *fmt, ...)
  483. {
  484. va_list args;
  485. va_start(args, fmt);
  486. nobuild_vlog(stderr, "ERRO", fmt, args);
  487. va_end(args);
  488. }
  489. int nobuild__ends_with(const char *str, const char *postfix)
  490. {
  491. const size_t str_n = strlen(str);
  492. const size_t postfix_n = strlen(postfix);
  493. return postfix_n <= str_n && strcmp(str + str_n - postfix_n, postfix) == 0;
  494. }
  495. int nobuild__is_dir(const char *path)
  496. {
  497. #ifdef _WIN32
  498. DWORD dwAttrib = GetFileAttributes(path);
  499. return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
  500. (dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
  501. #else
  502. struct stat statbuf = {0};
  503. if (stat(path, &statbuf) < 0) {
  504. if (errno == ENOENT) {
  505. return 0;
  506. }
  507. ERRO("could not retrieve information about file %s: %s",
  508. path, strerror(errno));
  509. exit(1);
  510. }
  511. return (statbuf.st_mode & S_IFMT) == S_IFDIR;
  512. #endif // _WIN32
  513. }
  514. void nobuild__rm(const char *path)
  515. {
  516. if (IS_DIR(path)) {
  517. FOREACH_FILE_IN_DIR(file, path, {
  518. if (strcmp(file, ".") != 0 && strcmp(file, "..") != 0) {
  519. nobuild__rm(PATH(path, file));
  520. }
  521. });
  522. if (rmdir(path) < 0) {
  523. if (errno = ENOENT) {
  524. WARN("directory %s does not exist");
  525. } else {
  526. ERRO("could not remove directory %s: %s", path, strerror(errno));
  527. exit(1);
  528. }
  529. }
  530. } else {
  531. if (unlink(path) < 0) {
  532. if (errno = ENOENT) {
  533. WARN("file %s does not exist");
  534. } else {
  535. ERRO("could not remove file %s: %s", path, strerror(errno));
  536. exit(1);
  537. }
  538. }
  539. }
  540. }
  541. #endif // NOBUILD_IMPLEMENTATION