nobuild.h 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. #ifndef NOBUILD_H_
  2. #define NOBUILD_H_
  3. #ifndef _WIN32
  4. # define _POSIX_C_SOURCE 200809L
  5. # include <sys/types.h>
  6. # include <sys/wait.h>
  7. # include <sys/stat.h>
  8. # include <unistd.h>
  9. # include <dirent.h>
  10. # include <fcntl.h>
  11. # define PATH_SEP "/"
  12. typedef pid_t Pid;
  13. typedef int Fd;
  14. #else
  15. # define WIN32_MEAN_AND_LEAN
  16. # include "windows.h"
  17. # include <process.h>
  18. # define PATH_SEP "\\"
  19. typedef HANDLE Pid;
  20. typedef HANDLE Fd;
  21. // minirent.h HEADER BEGIN ////////////////////////////////////////
  22. // Copyright 2021 Alexey Kutepov <[email protected]>
  23. //
  24. // Permission is hereby granted, free of charge, to any person obtaining
  25. // a copy of this software and associated documentation files (the
  26. // "Software"), to deal in the Software without restriction, including
  27. // without limitation the rights to use, copy, modify, merge, publish,
  28. // distribute, sublicense, and/or sell copies of the Software, and to
  29. // permit persons to whom the Software is furnished to do so, subject to
  30. // the following conditions:
  31. //
  32. // The above copyright notice and this permission notice shall be
  33. // included in all copies or substantial portions of the Software.
  34. //
  35. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  36. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  37. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  38. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  39. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  40. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  41. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  42. //
  43. // ============================================================
  44. //
  45. // minirent — 0.0.1 — A subset of dirent interface for Windows.
  46. //
  47. // https://github.com/tsoding/minirent
  48. //
  49. // ============================================================
  50. //
  51. // ChangeLog (https://semver.org/ is implied)
  52. //
  53. // 0.0.1 First Official Release
  54. #ifndef MINIRENT_H_
  55. #define MINIRENT_H_
  56. #define WIN32_LEAN_AND_MEAN
  57. #include "windows.h"
  58. struct dirent {
  59. char d_name[MAX_PATH+1];
  60. };
  61. typedef struct DIR DIR;
  62. DIR *opendir(const char *dirpath);
  63. struct dirent *readdir(DIR *dirp);
  64. int closedir(DIR *dirp);
  65. #endif // MINIRENT_H_
  66. // minirent.h HEADER END ////////////////////////////////////////
  67. LPSTR GetLastErrorAsString(void);
  68. #endif // _WIN32
  69. #include <assert.h>
  70. #include <stdio.h>
  71. #include <stdlib.h>
  72. #include <stdarg.h>
  73. #include <string.h>
  74. #include <errno.h>
  75. #define FOREACH_ARRAY(type, elem, array, body) \
  76. for (size_t elem_##index = 0; \
  77. elem_##index < array.count; \
  78. ++elem_##index) \
  79. { \
  80. type *elem = &array.elems[elem_##index]; \
  81. body; \
  82. }
  83. typedef const char * Cstr;
  84. int cstr_ends_with(Cstr cstr, Cstr postfix);
  85. #define ENDS_WITH(cstr, postfix) cstr_ends_with(cstr, postfix)
  86. Cstr cstr_no_ext(Cstr path);
  87. #define NOEXT(path) cstr_no_ext(path)
  88. typedef struct {
  89. Cstr *elems;
  90. size_t count;
  91. } Cstr_Array;
  92. Cstr_Array cstr_array_make(Cstr first, ...);
  93. Cstr_Array cstr_array_append(Cstr_Array cstrs, Cstr cstr);
  94. Cstr cstr_array_join(Cstr sep, Cstr_Array cstrs);
  95. #define JOIN(sep, ...) cstr_array_join(sep, cstr_array_make(__VA_ARGS__, NULL))
  96. #define CONCAT(...) JOIN("", __VA_ARGS__)
  97. #define PATH(...) JOIN(PATH_SEP, __VA_ARGS__)
  98. typedef struct {
  99. Fd read;
  100. Fd write;
  101. } Pipe;
  102. Pipe pipe_make(void);
  103. typedef struct {
  104. Cstr_Array line;
  105. } Cmd;
  106. Fd fd_open_for_read(Cstr path);
  107. Fd fd_open_for_write(Cstr path);
  108. void fd_close(Fd fd);
  109. void pid_wait(Pid pid);
  110. Cstr cmd_show(Cmd cmd);
  111. Pid cmd_run_async(Cmd cmd, Fd *fdin, Fd *fdout);
  112. void cmd_run_sync(Cmd cmd);
  113. typedef struct {
  114. Cmd *elems;
  115. size_t count;
  116. } Cmd_Array;
  117. #define CMD(...) \
  118. do { \
  119. Cmd cmd = { \
  120. .line = cstr_array_make(__VA_ARGS__, NULL) \
  121. }; \
  122. INFO("CMD: %s", cmd_show(cmd)); \
  123. cmd_run_sync(cmd); \
  124. } while (0)
  125. typedef enum {
  126. CHAIN_TOKEN_END = 0,
  127. CHAIN_TOKEN_IN,
  128. CHAIN_TOKEN_OUT,
  129. CHAIN_TOKEN_CMD
  130. } Chain_Token_Type;
  131. // A single token for the CHAIN(...) DSL syntax
  132. typedef struct {
  133. Chain_Token_Type type;
  134. Cstr_Array args;
  135. } Chain_Token;
  136. #define IN(path) \
  137. (Chain_Token) { \
  138. .type = CHAIN_TOKEN_IN, \
  139. .args = cstr_array_make(path, NULL) \
  140. }
  141. #define OUT(path) \
  142. (Chain_Token) { \
  143. .type = CHAIN_TOKEN_OUT, \
  144. .args = cstr_array_make(path, NULL) \
  145. }
  146. #define CHAIN_CMD(...) \
  147. (Chain_Token) { \
  148. .type = CHAIN_TOKEN_CMD, \
  149. .args = cstr_array_make(__VA_ARGS__, NULL) \
  150. }
  151. typedef struct {
  152. Cstr input_filepath;
  153. Cmd_Array cmds;
  154. Cstr output_filepath;
  155. } Chain;
  156. Chain chain_build_from_tokens(Chain_Token first, ...);
  157. void chain_run_sync(Chain chain);
  158. void chain_echo(Chain chain);
  159. #define CHAIN(...) \
  160. do { \
  161. Chain chain = chain_build_from_tokens(__VA_ARGS__, (Chain_Token) {0}); \
  162. chain_echo(chain); \
  163. chain_run_sync(chain); \
  164. } while(0)
  165. int path_is_dir(Cstr path);
  166. #define IS_DIR(path) path_is_dir(path)
  167. int path_exists(Cstr path);
  168. #define PATH_EXISTS(path) path_exists(path)
  169. void path_mkdirs(Cstr_Array path);
  170. #define MKDIRS(...) \
  171. do { \
  172. Cstr_Array path = cstr_array_make(__VA_ARGS__, NULL); \
  173. INFO("MKDIRS: %s", cstr_array_join(PATH_SEP, path)); \
  174. path_mkdirs(path); \
  175. } while (0)
  176. void path_rm(Cstr path);
  177. #define RM(path) \
  178. do { \
  179. INFO("RM: %s", path); \
  180. path_rm(path); \
  181. } while(0)
  182. #define FOREACH_FILE_IN_DIR(file, dirpath, body) \
  183. do { \
  184. struct dirent *dp = NULL; \
  185. DIR *dir = opendir(dirpath); \
  186. if (dir == NULL) { \
  187. PANIC("could not open directory %s: %s", \
  188. dirpath, strerror(errno)); \
  189. } \
  190. errno = 0; \
  191. while ((dp = readdir(dir))) { \
  192. const char *file = dp->d_name; \
  193. body; \
  194. } \
  195. \
  196. if (errno > 0) { \
  197. PANIC("could not read directory %s: %s", \
  198. dirpath, strerror(errno)); \
  199. } \
  200. \
  201. closedir(dir); \
  202. } while(0)
  203. #if defined(__GNUC__) || defined(__clang__)
  204. // https://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Function-Attributes.html
  205. #define NOBUILD_PRINTF_FORMAT(STRING_INDEX, FIRST_TO_CHECK) __attribute__ ((format (printf, STRING_INDEX, FIRST_TO_CHECK)))
  206. #else
  207. #define NOBUILD_PRINTF_FORMAT(STRING_INDEX, FIRST_TO_CHECK)
  208. #endif
  209. void VLOG(FILE *stream, Cstr tag, Cstr fmt, va_list args);
  210. void INFO(Cstr fmt, ...) NOBUILD_PRINTF_FORMAT(1, 2);
  211. void WARN(Cstr fmt, ...) NOBUILD_PRINTF_FORMAT(1, 2);
  212. void ERRO(Cstr fmt, ...) NOBUILD_PRINTF_FORMAT(1, 2);
  213. void PANIC(Cstr fmt, ...) NOBUILD_PRINTF_FORMAT(1, 2);
  214. char *shift_args(int *argc, char ***argv);
  215. #endif // NOBUILD_H_
  216. ////////////////////////////////////////////////////////////////////////////////
  217. #ifdef NOBUILD_IMPLEMENTATION
  218. #ifdef _WIN32
  219. LPSTR GetLastErrorAsString(void)
  220. {
  221. // https://stackoverflow.com/questions/1387064/how-to-get-the-error-message-from-the-error-code-returned-by-getlasterror
  222. DWORD errorMessageId = GetLastError();
  223. assert(errorMessageId != 0);
  224. LPSTR messageBuffer = NULL;
  225. DWORD size =
  226. FormatMessage(
  227. FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, // DWORD dwFlags,
  228. NULL, // LPCVOID lpSource,
  229. errorMessageId, // DWORD dwMessageId,
  230. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // DWORD dwLanguageId,
  231. (LPSTR) &messageBuffer, // LPTSTR lpBuffer,
  232. 0, // DWORD nSize,
  233. NULL // va_list *Arguments
  234. );
  235. return messageBuffer;
  236. }
  237. // minirent.h IMPLEMENTATION BEGIN ////////////////////////////////////////
  238. struct DIR {
  239. HANDLE hFind;
  240. WIN32_FIND_DATA data;
  241. struct dirent *dirent;
  242. };
  243. DIR *opendir(const char *dirpath)
  244. {
  245. assert(dirpath);
  246. char buffer[MAX_PATH];
  247. snprintf(buffer, MAX_PATH, "%s\\*", dirpath);
  248. DIR *dir = (DIR*)calloc(1, sizeof(DIR));
  249. dir->hFind = FindFirstFile(buffer, &dir->data);
  250. if (dir->hFind == INVALID_HANDLE_VALUE) {
  251. errno = ENOSYS;
  252. goto fail;
  253. }
  254. return dir;
  255. fail:
  256. if (dir) {
  257. free(dir);
  258. }
  259. return NULL;
  260. }
  261. struct dirent *readdir(DIR *dirp)
  262. {
  263. assert(dirp);
  264. if (dirp->dirent == NULL) {
  265. dirp->dirent = (struct dirent*)calloc(1, sizeof(struct dirent));
  266. } else {
  267. if(!FindNextFile(dirp->hFind, &dirp->data)) {
  268. if (GetLastError() != ERROR_NO_MORE_FILES) {
  269. errno = ENOSYS;
  270. }
  271. return NULL;
  272. }
  273. }
  274. memset(dirp->dirent->d_name, 0, sizeof(dirp->dirent->d_name));
  275. strncpy(
  276. dirp->dirent->d_name,
  277. dirp->data.cFileName,
  278. sizeof(dirp->dirent->d_name) - 1);
  279. return dirp->dirent;
  280. }
  281. int closedir(DIR *dirp)
  282. {
  283. assert(dirp);
  284. if(!FindClose(dirp->hFind)) {
  285. errno = ENOSYS;
  286. return -1;
  287. }
  288. if (dirp->dirent) {
  289. free(dirp->dirent);
  290. }
  291. free(dirp);
  292. return 0;
  293. }
  294. // minirent.h IMPLEMENTATION END ////////////////////////////////////////
  295. #endif // _WIN32
  296. Cstr_Array cstr_array_append(Cstr_Array cstrs, Cstr cstr)
  297. {
  298. Cstr_Array result = {
  299. .count = cstrs.count + 1
  300. };
  301. result.elems = malloc(sizeof(result.elems[0]) * result.count);
  302. memcpy(result.elems, cstrs.elems, cstrs.count * sizeof(result.elems[0]));
  303. result.elems[cstrs.count] = cstr;
  304. return result;
  305. }
  306. int cstr_ends_with(Cstr cstr, Cstr postfix)
  307. {
  308. const size_t cstr_len = strlen(cstr);
  309. const size_t postfix_len = strlen(postfix);
  310. return postfix_len <= cstr_len
  311. && strcmp(cstr + cstr_len - postfix_len, postfix) == 0;
  312. }
  313. Cstr cstr_no_ext(Cstr path)
  314. {
  315. size_t n = strlen(path);
  316. while (n > 0 && path[n - 1] != '.') {
  317. n -= 1;
  318. }
  319. if (n > 0) {
  320. char *result = malloc(n);
  321. memcpy(result, path, n);
  322. result[n - 1] = '\0';
  323. return result;
  324. } else {
  325. return path;
  326. }
  327. }
  328. Cstr_Array cstr_array_make(Cstr first, ...)
  329. {
  330. Cstr_Array result = {0};
  331. if (first == NULL) {
  332. return result;
  333. }
  334. result.count += 1;
  335. va_list args;
  336. va_start(args, first);
  337. for (Cstr next = va_arg(args, Cstr);
  338. next != NULL;
  339. next = va_arg(args, Cstr)) {
  340. result.count += 1;
  341. }
  342. va_end(args);
  343. result.elems = malloc(sizeof(result.elems[0]) * result.count);
  344. if (result.elems == NULL) {
  345. PANIC("could not allocate memory: %s", strerror(errno));
  346. }
  347. result.count = 0;
  348. result.elems[result.count++] = first;
  349. va_start(args, first);
  350. for (Cstr next = va_arg(args, Cstr);
  351. next != NULL;
  352. next = va_arg(args, Cstr)) {
  353. result.elems[result.count++] = next;
  354. }
  355. va_end(args);
  356. return result;
  357. }
  358. Cstr cstr_array_join(Cstr sep, Cstr_Array cstrs)
  359. {
  360. if (cstrs.count == 0) {
  361. return "";
  362. }
  363. const size_t sep_len = strlen(sep);
  364. size_t len = 0;
  365. for (size_t i = 0; i < cstrs.count; ++i) {
  366. len += strlen(cstrs.elems[i]);
  367. }
  368. const size_t result_len = (cstrs.count - 1) * sep_len + len + 1;
  369. char *result = malloc(sizeof(char) * result_len);
  370. if (result == NULL) {
  371. PANIC("could not allocate memory: %s", strerror(errno));
  372. }
  373. len = 0;
  374. for (size_t i = 0; i < cstrs.count; ++i) {
  375. if (i > 0) {
  376. memcpy(result + len, sep, sep_len);
  377. len += sep_len;
  378. }
  379. size_t elem_len = strlen(cstrs.elems[i]);
  380. memcpy(result + len, cstrs.elems[i], elem_len);
  381. len += elem_len;
  382. }
  383. result[len] = '\0';
  384. return result;
  385. }
  386. Pipe pipe_make(void)
  387. {
  388. Pipe pip = {0};
  389. #ifdef _WIN32
  390. // https://docs.microsoft.com/en-us/windows/win32/ProcThread/creating-a-child-process-with-redirected-input-and-output
  391. SECURITY_ATTRIBUTES saAttr = {0};
  392. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  393. saAttr.bInheritHandle = TRUE;
  394. if (!CreatePipe(&pip.read, &pip.write, &saAttr, 0)) {
  395. PANIC("Could not create pipe: %s", GetLastErrorAsString());
  396. }
  397. #else
  398. Fd pipefd[2];
  399. if (pipe(pipefd) < 0) {
  400. PANIC("Could not create pipe: %s", strerror(errno));
  401. }
  402. pip.read = pipefd[0];
  403. pip.write = pipefd[1];
  404. #endif // _WIN32
  405. return pip;
  406. }
  407. Fd fd_open_for_read(Cstr path)
  408. {
  409. #ifndef _WIN32
  410. Fd result = open(path, O_RDONLY);
  411. if (result < 0) {
  412. PANIC("Could not open file %s: %s", path, strerror(errno));
  413. }
  414. return result;
  415. #else
  416. // https://docs.microsoft.com/en-us/windows/win32/fileio/opening-a-file-for-reading-or-writing
  417. SECURITY_ATTRIBUTES saAttr = {0};
  418. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  419. saAttr.bInheritHandle = TRUE;
  420. Fd result = CreateFile(
  421. path,
  422. GENERIC_READ,
  423. 0,
  424. &saAttr,
  425. OPEN_EXISTING,
  426. FILE_ATTRIBUTE_READONLY,
  427. NULL);
  428. if (result == INVALID_HANDLE_VALUE) {
  429. PANIC("Could not open file %s", path);
  430. }
  431. return result;
  432. #endif // _WIN32
  433. }
  434. Fd fd_open_for_write(Cstr path)
  435. {
  436. #ifndef _WIN32
  437. Fd result = open(path,
  438. O_WRONLY | O_CREAT | O_TRUNC,
  439. S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
  440. if (result < 0) {
  441. PANIC("could not open file %s: %s", path, strerror(errno));
  442. }
  443. return result;
  444. #else
  445. SECURITY_ATTRIBUTES saAttr = {0};
  446. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  447. saAttr.bInheritHandle = TRUE;
  448. Fd result = CreateFile(
  449. path, // name of the write
  450. GENERIC_WRITE, // open for writing
  451. 0, // do not share
  452. &saAttr, // default security
  453. CREATE_NEW, // create new file only
  454. FILE_ATTRIBUTE_NORMAL, // normal file
  455. NULL // no attr. template
  456. );
  457. if (result == INVALID_HANDLE_VALUE) {
  458. PANIC("Could not open file %s: %s", path, GetLastErrorAsString());
  459. }
  460. return result;
  461. #endif // _WIN32
  462. }
  463. void fd_close(Fd fd)
  464. {
  465. #ifdef _WIN32
  466. CloseHandle(fd);
  467. #else
  468. close(fd);
  469. #endif // _WIN32
  470. }
  471. void pid_wait(Pid pid)
  472. {
  473. #ifdef _WIN32
  474. DWORD result = WaitForSingleObject(
  475. pid, // HANDLE hHandle,
  476. INFINITE // DWORD dwMilliseconds
  477. );
  478. if (result == WAIT_FAILED) {
  479. PANIC("could not wait on child process: %s", GetLastErrorAsString());
  480. }
  481. DWORD exit_status;
  482. if (GetExitCodeProcess(pid, &exit_status) == 0) {
  483. PANIC("could not get process exit code: %lu", GetLastError());
  484. }
  485. if (exit_status != 0) {
  486. PANIC("command exited with exit code %lu", exit_status);
  487. }
  488. CloseHandle(pid);
  489. #else
  490. for (;;) {
  491. int wstatus = 0;
  492. if (waitpid(pid, &wstatus, 0) < 0) {
  493. PANIC("could not wait on command (pid %d): %s", pid, strerror(errno));
  494. }
  495. if (WIFEXITED(wstatus)) {
  496. int exit_status = WEXITSTATUS(wstatus);
  497. if (exit_status != 0) {
  498. PANIC("command exited with exit code %d", exit_status);
  499. }
  500. break;
  501. }
  502. if (WIFSIGNALED(wstatus)) {
  503. PANIC("command process was terminated by %s", strsignal(WTERMSIG(wstatus)));
  504. }
  505. }
  506. #endif // _WIN32
  507. }
  508. Cstr cmd_show(Cmd cmd)
  509. {
  510. return cstr_array_join(" ", cmd.line);
  511. }
  512. Pid cmd_run_async(Cmd cmd, Fd *fdin, Fd *fdout)
  513. {
  514. #ifdef _WIN32
  515. // https://docs.microsoft.com/en-us/windows/win32/procthread/creating-a-child-process-with-redirected-input-and-output
  516. STARTUPINFO siStartInfo;
  517. ZeroMemory(&siStartInfo, sizeof(siStartInfo));
  518. siStartInfo.cb = sizeof(STARTUPINFO);
  519. // NOTE: theoretically setting NULL to std handles should not be a problem
  520. // https://docs.microsoft.com/en-us/windows/console/getstdhandle?redirectedfrom=MSDN#attachdetach-behavior
  521. siStartInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
  522. siStartInfo.hStdOutput = fdout ? *fdout : GetStdHandle(STD_OUTPUT_HANDLE);
  523. siStartInfo.hStdInput = fdin ? *fdin : GetStdHandle(STD_INPUT_HANDLE);
  524. siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
  525. PROCESS_INFORMATION piProcInfo;
  526. ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));
  527. BOOL bSuccess =
  528. CreateProcess(
  529. NULL,
  530. cstr_array_join(" ", cmd.line),
  531. NULL,
  532. NULL,
  533. TRUE,
  534. 0,
  535. NULL,
  536. NULL,
  537. &siStartInfo,
  538. &piProcInfo
  539. );
  540. if (!bSuccess) {
  541. PANIC("Could not create child process %s: %s\n",
  542. cmd_show(cmd), GetLastErrorAsString());
  543. }
  544. CloseHandle(piProcInfo.hThread);
  545. return piProcInfo.hProcess;
  546. #else
  547. pid_t cpid = fork();
  548. if (cpid < 0) {
  549. PANIC("Could not fork child process: %s: %s",
  550. cmd_show(cmd), strerror(errno));
  551. }
  552. if (cpid == 0) {
  553. Cstr_Array args = cstr_array_append(cmd.line, NULL);
  554. if (fdin) {
  555. if (dup2(*fdin, STDIN_FILENO) < 0) {
  556. PANIC("Could not setup stdin for child process: %s", strerror(errno));
  557. }
  558. }
  559. if (fdout) {
  560. if (dup2(*fdout, STDOUT_FILENO) < 0) {
  561. PANIC("Could not setup stdout for child process: %s", strerror(errno));
  562. }
  563. }
  564. if (execvp(args.elems[0], (char * const*) args.elems) < 0) {
  565. PANIC("Could not exec child process: %s: %s",
  566. cmd_show(cmd), strerror(errno));
  567. }
  568. }
  569. return cpid;
  570. #endif // _WIN32
  571. }
  572. void cmd_run_sync(Cmd cmd)
  573. {
  574. pid_wait(cmd_run_async(cmd, NULL, NULL));
  575. }
  576. static void chain_set_input_output_files_or_count_cmds(Chain *chain, Chain_Token token)
  577. {
  578. switch (token.type) {
  579. case CHAIN_TOKEN_CMD: {
  580. chain->cmds.count += 1;
  581. }
  582. break;
  583. case CHAIN_TOKEN_IN: {
  584. if (chain->input_filepath) {
  585. PANIC("Input file path was already set");
  586. }
  587. chain->input_filepath = token.args.elems[0];
  588. }
  589. break;
  590. case CHAIN_TOKEN_OUT: {
  591. if (chain->output_filepath) {
  592. PANIC("Output file path was already set");
  593. }
  594. chain->output_filepath = token.args.elems[0];
  595. }
  596. break;
  597. case CHAIN_TOKEN_END:
  598. default: {
  599. assert(0 && "unreachable");
  600. exit(1);
  601. }
  602. }
  603. }
  604. static void chain_push_cmd(Chain *chain, Chain_Token token)
  605. {
  606. if (token.type == CHAIN_TOKEN_CMD) {
  607. chain->cmds.elems[chain->cmds.count++] = (Cmd) {
  608. .line = token.args
  609. };
  610. }
  611. }
  612. Chain chain_build_from_tokens(Chain_Token first, ...)
  613. {
  614. Chain result = {0};
  615. chain_set_input_output_files_or_count_cmds(&result, first);
  616. va_list args;
  617. va_start(args, first);
  618. Chain_Token next = va_arg(args, Chain_Token);
  619. while (next.type != CHAIN_TOKEN_END) {
  620. chain_set_input_output_files_or_count_cmds(&result, next);
  621. next = va_arg(args, Chain_Token);
  622. }
  623. va_end(args);
  624. result.cmds.elems = malloc(sizeof(result.cmds.elems[0]) * result.cmds.count);
  625. if (result.cmds.elems == NULL) {
  626. PANIC("could not allocate memory: %s", strerror(errno));
  627. }
  628. result.cmds.count = 0;
  629. chain_push_cmd(&result, first);
  630. va_start(args, first);
  631. next = va_arg(args, Chain_Token);
  632. while (next.type != CHAIN_TOKEN_END) {
  633. chain_push_cmd(&result, next);
  634. next = va_arg(args, Chain_Token);
  635. }
  636. va_end(args);
  637. return result;
  638. }
  639. void chain_run_sync(Chain chain)
  640. {
  641. if (chain.cmds.count == 0) {
  642. return;
  643. }
  644. Pid *cpids = malloc(sizeof(Pid) * chain.cmds.count);
  645. Pipe pip = {0};
  646. Fd fdin = 0;
  647. Fd *fdprev = NULL;
  648. if (chain.input_filepath) {
  649. fdin = fd_open_for_read(chain.input_filepath);
  650. if (fdin < 0) {
  651. PANIC("could not open file %s: %s", chain.input_filepath, strerror(errno));
  652. }
  653. fdprev = &fdin;
  654. }
  655. for (size_t i = 0; i < chain.cmds.count - 1; ++i) {
  656. pip = pipe_make();
  657. cpids[i] = cmd_run_async(
  658. chain.cmds.elems[i],
  659. fdprev,
  660. &pip.write);
  661. if (fdprev) fd_close(*fdprev);
  662. fd_close(pip.write);
  663. fdprev = &fdin;
  664. fdin = pip.read;
  665. }
  666. {
  667. Fd fdout = 0;
  668. Fd *fdnext = NULL;
  669. if (chain.output_filepath) {
  670. fdout = fd_open_for_write(chain.output_filepath);
  671. if (fdout < 0) {
  672. PANIC("could not open file %s: %s",
  673. chain.output_filepath,
  674. strerror(errno));
  675. }
  676. fdnext = &fdout;
  677. }
  678. const size_t last = chain.cmds.count - 1;
  679. cpids[last] =
  680. cmd_run_async(
  681. chain.cmds.elems[last],
  682. fdprev,
  683. fdnext);
  684. if (fdprev) fd_close(*fdprev);
  685. if (fdnext) fd_close(*fdnext);
  686. }
  687. for (size_t i = 0; i < chain.cmds.count; ++i) {
  688. pid_wait(cpids[i]);
  689. }
  690. }
  691. void chain_echo(Chain chain)
  692. {
  693. printf("[INFO] CHAIN:");
  694. if (chain.input_filepath) {
  695. printf(" %s", chain.input_filepath);
  696. }
  697. FOREACH_ARRAY(Cmd, cmd, chain.cmds, {
  698. printf(" |> %s", cmd_show(*cmd));
  699. });
  700. if (chain.output_filepath) {
  701. printf(" |> %s", chain.output_filepath);
  702. }
  703. printf("\n");
  704. }
  705. int path_exists(Cstr path)
  706. {
  707. #ifdef _WIN32
  708. DWORD dwAttrib = GetFileAttributes(path);
  709. return (dwAttrib != INVALID_FILE_ATTRIBUTES);
  710. #else
  711. struct stat statbuf = {0};
  712. if (stat(path, &statbuf) < 0) {
  713. if (errno == ENOENT) {
  714. return 0;
  715. }
  716. PANIC("could not retrieve information about file %s: %s",
  717. path, strerror(errno));
  718. }
  719. return 1;
  720. #endif
  721. }
  722. int path_is_dir(Cstr path)
  723. {
  724. #ifdef _WIN32
  725. DWORD dwAttrib = GetFileAttributes(path);
  726. return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
  727. (dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
  728. #else
  729. struct stat statbuf = {0};
  730. if (stat(path, &statbuf) < 0) {
  731. if (errno == ENOENT) {
  732. return 0;
  733. }
  734. PANIC("could not retrieve information about file %s: %s",
  735. path, strerror(errno));
  736. }
  737. return S_ISDIR(statbuf.st_mode);
  738. #endif // _WIN32
  739. }
  740. void path_mkdirs(Cstr_Array path)
  741. {
  742. if (path.count == 0) {
  743. return;
  744. }
  745. size_t len = 0;
  746. for (size_t i = 0; i < path.count; ++i) {
  747. len += strlen(path.elems[i]);
  748. }
  749. size_t seps_count = path.count - 1;
  750. const size_t sep_len = strlen(PATH_SEP);
  751. char *result = malloc(len + seps_count * sep_len + 1);
  752. len = 0;
  753. for (size_t i = 0; i < path.count; ++i) {
  754. size_t n = strlen(path.elems[i]);
  755. memcpy(result + len, path.elems[i], n);
  756. len += n;
  757. if (seps_count > 0) {
  758. memcpy(result + len, PATH_SEP, sep_len);
  759. len += sep_len;
  760. seps_count -= 1;
  761. }
  762. result[len] = '\0';
  763. if (mkdir(result, 0755) < 0) {
  764. if (errno == EEXIST) {
  765. WARN("directory %s already exists", result);
  766. } else {
  767. PANIC("could not create directory %s: %s", result, strerror(errno));
  768. }
  769. }
  770. }
  771. }
  772. void path_rm(Cstr path)
  773. {
  774. if (IS_DIR(path)) {
  775. FOREACH_FILE_IN_DIR(file, path, {
  776. if (strcmp(file, ".") != 0 && strcmp(file, "..") != 0)
  777. {
  778. path_rm(PATH(path, file));
  779. }
  780. });
  781. if (rmdir(path) < 0) {
  782. if (errno == ENOENT) {
  783. WARN("directory %s does not exist", path);
  784. } else {
  785. PANIC("could not remove directory %s: %s", path, strerror(errno));
  786. }
  787. }
  788. } else {
  789. if (unlink(path) < 0) {
  790. if (errno == ENOENT) {
  791. WARN("file %s does not exist", path);
  792. } else {
  793. PANIC("could not remove file %s: %s", path, strerror(errno));
  794. }
  795. }
  796. }
  797. }
  798. void VLOG(FILE *stream, Cstr tag, Cstr fmt, va_list args)
  799. {
  800. fprintf(stream, "[%s] ", tag);
  801. vfprintf(stream, fmt, args);
  802. fprintf(stream, "\n");
  803. }
  804. void INFO(Cstr fmt, ...)
  805. {
  806. va_list args;
  807. va_start(args, fmt);
  808. VLOG(stdout, "INFO", fmt, args);
  809. va_end(args);
  810. }
  811. void WARN(Cstr fmt, ...)
  812. {
  813. va_list args;
  814. va_start(args, fmt);
  815. VLOG(stderr, "WARN", fmt, args);
  816. va_end(args);
  817. }
  818. void ERRO(Cstr fmt, ...)
  819. {
  820. va_list args;
  821. va_start(args, fmt);
  822. VLOG(stderr, "ERRO", fmt, args);
  823. va_end(args);
  824. }
  825. void PANIC(Cstr fmt, ...)
  826. {
  827. va_list args;
  828. va_start(args, fmt);
  829. VLOG(stderr, "ERRO", fmt, args);
  830. va_end(args);
  831. exit(1);
  832. }
  833. char *shift_args(int *argc, char ***argv)
  834. {
  835. assert(*argc > 0);
  836. char *result = **argv;
  837. *argc -= 1;
  838. *argv += 1;
  839. return result;
  840. }
  841. #endif // NOBUILD_IMPLEMENTATION