build.zig 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. const std = @import("std");
  2. const Builder = std.build.Builder;
  3. const Step = std.build.Step;
  4. const assert = std.debug.assert;
  5. const print = std.debug.print;
  6. const Exercise = struct {
  7. /// main_file must have the format key_name.zig.
  8. /// The key will be used as a shorthand to build
  9. /// just one example.
  10. main_file: []const u8,
  11. /// This is the desired output of the program.
  12. /// A program passes if its output ends with this string.
  13. output: []const u8,
  14. /// This is an optional hint to give if the program does not succeed.
  15. hint: []const u8 = "",
  16. /// By default, we verify output against stderr.
  17. /// Set this to true to check stdout instead.
  18. check_stdout: bool = false,
  19. /// Returns the name of the main file with .zig stripped.
  20. pub fn baseName(self: Exercise) []const u8 {
  21. assert(std.mem.endsWith(u8, self.main_file, ".zig"));
  22. return self.main_file[0 .. self.main_file.len - 4];
  23. }
  24. /// Returns the key of the main file, the string before the '_' with
  25. /// "zero padding" removed.
  26. /// For example, "001_hello.zig" has the key "1".
  27. pub fn key(self: Exercise) []const u8 {
  28. const end_index = std.mem.indexOfScalar(u8, self.main_file, '_');
  29. assert(end_index != null); // main file must be key_description.zig
  30. // remove zero padding by advancing index past '0's
  31. var start_index: usize = 0;
  32. while (self.main_file[start_index] == '0') start_index += 1;
  33. return self.main_file[start_index..end_index.?];
  34. }
  35. };
  36. const exercises = [_]Exercise{
  37. .{
  38. .main_file = "001_hello.zig",
  39. .output = "Hello world",
  40. .hint = "DON'T PANIC!\nRead the error above.\nSee how it has something to do with 'main'?\nOpen up the source file as noted and read the comments.\nYou can do this!",
  41. },
  42. .{
  43. .main_file = "002_std.zig",
  44. .output = "Standard Library",
  45. },
  46. .{
  47. .main_file = "003_assignment.zig",
  48. .output = "55 314159 -11",
  49. .hint = "There are three mistakes in this one!",
  50. },
  51. .{
  52. .main_file = "004_arrays.zig",
  53. .output = "Fourth: 7, Length: 8",
  54. .hint = "There are two things to complete here.",
  55. },
  56. .{
  57. .main_file = "005_arrays2.zig",
  58. .output = "LEET: 1337, Bits: 100110011001",
  59. .hint = "Fill in the two arrays.",
  60. },
  61. .{
  62. .main_file = "006_strings.zig",
  63. .output = "d=d ha ha ha Major Tom",
  64. .hint = "Each '???' needs something filled in.",
  65. },
  66. .{
  67. .main_file = "007_strings2.zig",
  68. .output = "Ziggy played guitar\nJamming good with Andrew Kelley\nAnd the Spiders from Mars",
  69. .hint = "Please fix the lyrics!",
  70. },
  71. .{
  72. .main_file = "008_quiz.zig",
  73. .output = "Program in Zig!",
  74. .hint = "See if you can fix the program!",
  75. },
  76. .{
  77. .main_file = "009_if.zig",
  78. .output = "Foo is 1!",
  79. },
  80. .{
  81. .main_file = "010_if2.zig",
  82. .output = "With the discount, the price is $17.",
  83. },
  84. .{
  85. .main_file = "011_while.zig",
  86. .output = "2 4 8 16 32 64 128 256 512 n=1024",
  87. .hint = "You probably want a 'less than' condition.",
  88. },
  89. .{
  90. .main_file = "012_while2.zig",
  91. .output = "2 4 8 16 32 64 128 256 512 n=1024",
  92. .hint = "It might help to look back at the previous exercise.",
  93. },
  94. .{
  95. .main_file = "013_while3.zig",
  96. .output = "1 2 4 7 8 11 13 14 16 17 19",
  97. },
  98. .{
  99. .main_file = "014_while4.zig",
  100. .output = "n=4",
  101. },
  102. .{
  103. .main_file = "015_for.zig",
  104. .output = "A Dramatic Story: :-) :-) :-( :-| :-) The End.",
  105. },
  106. .{
  107. .main_file = "016_for2.zig",
  108. .output = "13",
  109. },
  110. .{
  111. .main_file = "017_quiz2.zig",
  112. .output = "1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16,",
  113. .hint = "This is a famous game!",
  114. },
  115. .{
  116. .main_file = "018_functions.zig",
  117. .output = "Answer to the Ultimate Question: 42",
  118. .hint = "Can you help write the function?",
  119. },
  120. .{
  121. .main_file = "019_functions2.zig",
  122. .output = "2 4 8 16",
  123. },
  124. .{
  125. .main_file = "020_quiz3.zig",
  126. .output = "32 64 128 256",
  127. .hint = "Unexpected pop quiz! Help!",
  128. },
  129. .{
  130. .main_file = "021_errors.zig",
  131. .output = "2<4. 3<4. 4=4. 5>4. 6>4.",
  132. .hint = "What's the deal with fours?",
  133. },
  134. .{
  135. .main_file = "022_errors2.zig",
  136. .output = "I compiled",
  137. .hint = "Get the error union type right to allow this to compile.",
  138. },
  139. .{
  140. .main_file = "023_errors3.zig",
  141. .output = "a=64, b=22",
  142. },
  143. .{
  144. .main_file = "024_errors4.zig",
  145. .output = "a=20, b=14, c=10",
  146. },
  147. .{
  148. .main_file = "025_errors5.zig",
  149. .output = "a=0, b=19, c=0",
  150. },
  151. .{
  152. .main_file = "026_hello2.zig",
  153. .output = "Hello world!",
  154. .hint = "Try using a try!",
  155. .check_stdout = true,
  156. },
  157. .{
  158. .main_file = "027_defer.zig",
  159. .output = "One Two",
  160. },
  161. .{
  162. .main_file = "028_defer2.zig",
  163. .output = "(Goat) (Cat) (Dog) (Dog) (Goat) (Unknown) done.",
  164. },
  165. .{
  166. .main_file = "029_errdefer.zig",
  167. .output = "Getting number...got 5. Getting number...failed!",
  168. },
  169. .{
  170. .main_file = "030_switch.zig",
  171. .output = "ZIG?",
  172. },
  173. .{
  174. .main_file = "031_switch2.zig",
  175. .output = "ZIG!",
  176. },
  177. .{
  178. .main_file = "032_unreachable.zig",
  179. .output = "1 2 3 9 8 7",
  180. },
  181. .{
  182. .main_file = "033_iferror.zig",
  183. .output = "2<4. 3<4. 4=4. 5>4. 6>4.",
  184. .hint = "Seriously, what's the deal with fours?",
  185. },
  186. .{
  187. .main_file = "034_quiz4.zig",
  188. .output = "my_num=42",
  189. .hint = "Can you make this work?",
  190. .check_stdout = true,
  191. },
  192. .{
  193. .main_file = "035_enums.zig",
  194. .output = "1 2 3 9 8 7",
  195. .hint = "This problem seems familiar...",
  196. },
  197. .{
  198. .main_file = "036_enums2.zig",
  199. .output = "<p>\n <span style=\"color: #ff0000\">Red</span>\n <span style=\"color: #00ff00\">Green</span>\n <span style=\"color: #0000ff\">Blue</span>\n</p>",
  200. .hint = "I'm feeling blue about this.",
  201. },
  202. .{
  203. .main_file = "037_structs.zig",
  204. .output = "Your wizard has 90 health and 25 gold.",
  205. },
  206. .{
  207. .main_file = "038_structs2.zig",
  208. .output = "Character 1 - G:20 H:100 XP:10\nCharacter 2 - G:10 H:100 XP:20",
  209. },
  210. .{
  211. .main_file = "039_pointers.zig",
  212. .output = "num1: 5, num2: 5",
  213. .hint = "Pointers aren't so bad.",
  214. },
  215. .{
  216. .main_file = "040_pointers2.zig",
  217. .output = "a: 12, b: 12",
  218. },
  219. .{
  220. .main_file = "041_pointers3.zig",
  221. .output = "foo=6, bar=11",
  222. },
  223. .{
  224. .main_file = "042_pointers4.zig",
  225. .output = "num: 5, more_nums: 1 1 5 1",
  226. },
  227. .{
  228. .main_file = "043_pointers5.zig",
  229. .output = "Wizard (G:10 H:100 XP:20)",
  230. },
  231. .{
  232. .main_file = "044_quiz5.zig",
  233. .output = "Elephant A. Elephant B. Elephant C.",
  234. .hint = "Oh no! We forgot Elephant B!",
  235. },
  236. .{
  237. .main_file = "045_optionals.zig",
  238. .output = "The Ultimate Answer: 42.",
  239. },
  240. .{
  241. .main_file = "046_optionals2.zig",
  242. .output = "Elephant A. Elephant B. Elephant C.",
  243. .hint = "Elephants again!",
  244. },
  245. .{
  246. .main_file = "047_methods.zig",
  247. .output = "5 aliens. 4 aliens. 1 aliens. 0 aliens. Earth is saved!",
  248. .hint = "Use the heat ray. And the method!",
  249. },
  250. .{
  251. .main_file = "048_methods2.zig",
  252. .output = "A B C",
  253. .hint = "This just needs one little fix.",
  254. },
  255. .{
  256. .main_file = "049_quiz6.zig",
  257. .output = "A B C Cv Bv Av",
  258. .hint = "Now you're writting Zig!",
  259. },
  260. .{
  261. .main_file = "050_no_value.zig",
  262. .output = "That is not dead which can eternal lie / And with strange aeons even death may die.",
  263. },
  264. .{
  265. .main_file = "051_values.zig",
  266. .output = "1:false!. 2:true!. 3:true!. XP before:0, after:200.",
  267. },
  268. .{
  269. .main_file = "052_slices.zig",
  270. .output = "Hand1: A 4 K 8 Hand2: 5 2 Q J",
  271. },
  272. .{
  273. .main_file = "053_slices2.zig",
  274. .output = "'all your base are belong to us.' 'for great justice.'",
  275. },
  276. .{
  277. .main_file = "054_manypointers.zig",
  278. .output = "Memory is a resource.",
  279. },
  280. .{
  281. .main_file = "055_unions.zig",
  282. .output = "Insect report! Ant alive is: true. Bee visited 15 flowers.",
  283. },
  284. .{
  285. .main_file = "056_unions2.zig",
  286. .output = "Insect report! Ant alive is: true. Bee visited 16 flowers.",
  287. },
  288. .{
  289. .main_file = "057_unions3.zig",
  290. .output = "Insect report! Ant alive is: true. Bee visited 17 flowers.",
  291. },
  292. .{
  293. .main_file = "058_quiz7.zig",
  294. .output = "Archer's Point--2->Bridge--1->Dogwood Grove--3->Cottage--2->East Pond--1->Fox Pond",
  295. .hint = "This is the biggest program we've seen yet. But you can do it!"
  296. },
  297. .{
  298. .main_file = "059_integers.zig",
  299. .output = "Zig is cool.",
  300. },
  301. .{
  302. .main_file = "060_floats.zig",
  303. .output = "Shuttle liftoff weight: 1995796kg",
  304. },
  305. .{
  306. .main_file = "061_coercions.zig",
  307. .output = "Letter: A",
  308. },
  309. .{
  310. .main_file = "062_loop_expressions.zig",
  311. .output = "Current language: Zig",
  312. .hint = "Surely the current language is 'Zig'!",
  313. },
  314. .{
  315. .main_file = "063_labels.zig",
  316. .output = "Enjoy your Cheesy Chili!",
  317. },
  318. .{
  319. .main_file = "064_builtins.zig",
  320. .output = "1101 + 0101 = 0010 (true). Furthermore, 11110000 backwards is 00001111.",
  321. },
  322. .{
  323. .main_file = "065_builtins2.zig",
  324. .output = "A Narcissus loves all Narcissuses. He has room in his heart for: me myself.",
  325. },
  326. .{
  327. .main_file = "066_comptime.zig",
  328. .output = "Immutable: 12345, 987.654; Mutable: 54321, 456.789; Types: comptime_int, comptime_float, u32, f32",
  329. .hint = "It may help to read this one out loud to your favorite stuffed animal until it sinks in completely."
  330. },
  331. .{
  332. .main_file = "067_comptime2.zig",
  333. .output = "A BB CCC DDDD",
  334. },
  335. .{
  336. .main_file = "068_comptime3.zig",
  337. .output = "Minnow (1:32, 4 x 2)\nShark (1:16, 8 x 5)\nWhale (1:1, 143 x 95)\n",
  338. },
  339. .{
  340. .main_file = "069_comptime4.zig",
  341. .output = "s1={ 1, 2, 3 }, s2={ 1, 2, 3, 4, 5 }, s3={ 1, 2, 3, 4, 5, 6, 7 }",
  342. },
  343. };
  344. /// Check the zig version to make sure it can compile the examples properly.
  345. /// This will compile with Zig 0.6.0 and later.
  346. fn checkVersion() bool {
  347. if (!@hasDecl(std.builtin, "zig_version")) {
  348. return false;
  349. }
  350. // When changing this version, be sure to also update README.md in two places:
  351. // 1) Getting Started
  352. // 2) Version Changes
  353. const needed_version = std.SemanticVersion.parse("0.8.0-dev.1983") catch unreachable;
  354. const version = std.builtin.zig_version;
  355. const order = version.order(needed_version);
  356. return order != .lt;
  357. }
  358. pub fn build(b: *Builder) void {
  359. // Use a comptime branch for the version check.
  360. // If this fails, code after this block is not compiled.
  361. // It is parsed though, so versions of zig from before 0.6.0
  362. // cannot do the version check and will just fail to compile.
  363. // We could fix this by moving the ziglings code to a separate file,
  364. // but 0.5.0 was a long time ago, it is unlikely that anyone who
  365. // attempts these exercises is still using it.
  366. if (comptime !checkVersion()) {
  367. // very old versions of Zig used warn instead of print.
  368. const stderrPrintFn = if (@hasDecl(std.debug, "print")) std.debug.print else std.debug.warn;
  369. stderrPrintFn(
  370. \\ERROR: Sorry, it looks like your version of zig is too old. :-(
  371. \\
  372. \\Ziglings requires development build
  373. \\
  374. \\ 0.8.0-dev.1065
  375. \\
  376. \\or higher. Please download a development ("master") build from
  377. \\https://ziglang.org/download/
  378. \\
  379. , .{});
  380. std.os.exit(0);
  381. }
  382. use_color_escapes = false;
  383. switch (b.color) {
  384. .on => use_color_escapes = true,
  385. .off => use_color_escapes = false,
  386. .auto => {
  387. if (std.io.getStdErr().supportsAnsiEscapeCodes()) {
  388. use_color_escapes = true;
  389. } else if (std.builtin.os.tag == .windows) {
  390. const w32 = struct {
  391. const WINAPI = std.os.windows.WINAPI;
  392. const DWORD = std.os.windows.DWORD;
  393. const ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004;
  394. const STD_ERROR_HANDLE = @bitCast(DWORD, @as(i32, -12));
  395. extern "kernel32" fn GetStdHandle(id: DWORD) callconv(WINAPI) ?*c_void;
  396. extern "kernel32" fn GetConsoleMode(console: ?*c_void, out_mode: *DWORD) callconv(WINAPI) u32;
  397. extern "kernel32" fn SetConsoleMode(console: ?*c_void, mode: DWORD) callconv(WINAPI) u32;
  398. };
  399. const handle = w32.GetStdHandle(w32.STD_ERROR_HANDLE);
  400. var mode: w32.DWORD = 0;
  401. if (w32.GetConsoleMode(handle, &mode) != 0) {
  402. mode |= w32.ENABLE_VIRTUAL_TERMINAL_PROCESSING;
  403. use_color_escapes = w32.SetConsoleMode(handle, mode) != 0;
  404. }
  405. }
  406. },
  407. }
  408. if (use_color_escapes) {
  409. red_text = "\x1b[31m";
  410. green_text = "\x1b[32m";
  411. bold_text = "\x1b[1m";
  412. reset_text = "\x1b[0m";
  413. }
  414. const header_step = b.addLog(
  415. \\
  416. \\ _ _ _
  417. \\ ___(_) __ _| (_)_ __ __ _ ___
  418. \\ |_ | |/ _' | | | '_ \ / _' / __|
  419. \\ / /| | (_| | | | | | | (_| \__ \
  420. \\ /___|_|\__, |_|_|_| |_|\__, |___/
  421. \\ |___/ |___/
  422. \\
  423. \\
  424. , .{});
  425. const verify_all = b.step("ziglings", "Check all ziglings");
  426. verify_all.dependOn(&header_step.step);
  427. b.default_step = verify_all;
  428. var prev_chain_verify = verify_all;
  429. const use_healed = b.option(bool, "healed", "Run exercises from patches/healed") orelse false;
  430. for (exercises) |ex| {
  431. const base_name = ex.baseName();
  432. const file_path = std.fs.path.join(b.allocator, &[_][]const u8{
  433. if (use_healed) "patches/healed" else "exercises", ex.main_file,
  434. }) catch unreachable;
  435. const build_step = b.addExecutable(base_name, file_path);
  436. build_step.install();
  437. const verify_step = ZiglingStep.create(b, ex, use_healed);
  438. const key = ex.key();
  439. const named_test = b.step(b.fmt("{s}_test", .{key}), b.fmt("Run {s} without checking output", .{ex.main_file}));
  440. const run_step = build_step.run();
  441. named_test.dependOn(&run_step.step);
  442. const named_install = b.step(b.fmt("{s}_install", .{key}), b.fmt("Install {s} to zig-cache/bin", .{ex.main_file}));
  443. named_install.dependOn(&build_step.install_step.?.step);
  444. const named_verify = b.step(key, b.fmt("Check {s} only", .{ex.main_file}));
  445. named_verify.dependOn(&verify_step.step);
  446. const chain_verify = b.allocator.create(Step) catch unreachable;
  447. chain_verify.* = Step.initNoOp(.Custom, b.fmt("chain {s}", .{key}), b.allocator);
  448. chain_verify.dependOn(&verify_step.step);
  449. const named_chain = b.step(b.fmt("{s}_start", .{key}), b.fmt("Check all solutions starting at {s}", .{ex.main_file}));
  450. named_chain.dependOn(&header_step.step);
  451. named_chain.dependOn(chain_verify);
  452. prev_chain_verify.dependOn(chain_verify);
  453. prev_chain_verify = chain_verify;
  454. }
  455. }
  456. var use_color_escapes = false;
  457. var red_text: []const u8 = "";
  458. var green_text: []const u8 = "";
  459. var bold_text: []const u8 = "";
  460. var reset_text: []const u8 = "";
  461. const ZiglingStep = struct {
  462. step: Step,
  463. exercise: Exercise,
  464. builder: *Builder,
  465. use_healed: bool,
  466. pub fn create(builder: *Builder, exercise: Exercise, use_healed: bool) *@This() {
  467. const self = builder.allocator.create(@This()) catch unreachable;
  468. self.* = .{
  469. .step = Step.init(.Custom, exercise.main_file, builder.allocator, make),
  470. .exercise = exercise,
  471. .builder = builder,
  472. .use_healed = use_healed,
  473. };
  474. return self;
  475. }
  476. fn make(step: *Step) anyerror!void {
  477. const self = @fieldParentPtr(@This(), "step", step);
  478. self.makeInternal() catch {
  479. if (self.exercise.hint.len > 0) {
  480. print("\n{s}HINT: {s}{s}", .{ bold_text, self.exercise.hint, reset_text });
  481. }
  482. print("\n{s}Edit exercises/{s} and run this again.{s}", .{ red_text, self.exercise.main_file, reset_text });
  483. print("\n{s}To continue from this zigling, use this command:{s}\n {s}zig build {s}{s}\n", .{ red_text, reset_text, bold_text, self.exercise.key(), reset_text });
  484. std.os.exit(0);
  485. };
  486. }
  487. fn makeInternal(self: *@This()) !void {
  488. print("Compiling {s}...\n", .{self.exercise.main_file});
  489. const exe_file = try self.doCompile();
  490. print("Checking {s}...\n", .{self.exercise.main_file});
  491. const cwd = self.builder.build_root;
  492. const argv = [_][]const u8{exe_file};
  493. const child = std.ChildProcess.init(&argv, self.builder.allocator) catch unreachable;
  494. defer child.deinit();
  495. child.cwd = cwd;
  496. child.env_map = self.builder.env_map;
  497. child.stdin_behavior = .Inherit;
  498. if (self.exercise.check_stdout) {
  499. child.stdout_behavior = .Pipe;
  500. child.stderr_behavior = .Inherit;
  501. } else {
  502. child.stdout_behavior = .Inherit;
  503. child.stderr_behavior = .Pipe;
  504. }
  505. child.spawn() catch |err| {
  506. print("{s}Unable to spawn {s}: {s}{s}\n", .{ red_text, argv[0], @errorName(err), reset_text });
  507. return err;
  508. };
  509. // Allow up to 1 MB of stdout capture
  510. const max_output_len = 1 * 1024 * 1024;
  511. const output = if (self.exercise.check_stdout)
  512. try child.stdout.?.reader().readAllAlloc(self.builder.allocator, max_output_len)
  513. else
  514. try child.stderr.?.reader().readAllAlloc(self.builder.allocator, max_output_len);
  515. // at this point stdout is closed, wait for the process to terminate
  516. const term = child.wait() catch |err| {
  517. print("{s}Unable to spawn {s}: {s}{s}\n", .{ red_text, argv[0], @errorName(err), reset_text });
  518. return err;
  519. };
  520. // make sure it exited cleanly.
  521. switch (term) {
  522. .Exited => |code| {
  523. if (code != 0) {
  524. print("{s}{s} exited with error code {d} (expected {d}){s}\n", .{ red_text, self.exercise.main_file, code, 0, reset_text });
  525. return error.BadExitCode;
  526. }
  527. },
  528. else => {
  529. print("{s}{s} terminated unexpectedly{s}\n", .{ red_text, self.exercise.main_file, reset_text });
  530. return error.UnexpectedTermination;
  531. },
  532. }
  533. // validate the output
  534. if (std.mem.indexOf(u8, output, self.exercise.output) == null) {
  535. print(
  536. \\
  537. \\{s}----------- Expected this output -----------{s}
  538. \\{s}
  539. \\{s}----------- but found -----------{s}
  540. \\{s}
  541. \\{s}-----------{s}
  542. \\
  543. , .{ red_text, reset_text, self.exercise.output, red_text, reset_text, output, red_text, reset_text });
  544. return error.InvalidOutput;
  545. }
  546. print("{s}PASSED: {s}{s}\n", .{ green_text, output, reset_text });
  547. }
  548. // The normal compile step calls os.exit, so we can't use it as a library :(
  549. // This is a stripped down copy of std.build.LibExeObjStep.make.
  550. fn doCompile(self: *@This()) ![]const u8 {
  551. const builder = self.builder;
  552. var zig_args = std.ArrayList([]const u8).init(builder.allocator);
  553. defer zig_args.deinit();
  554. zig_args.append(builder.zig_exe) catch unreachable;
  555. zig_args.append("build-exe") catch unreachable;
  556. if (builder.color != .auto) {
  557. zig_args.append("--color") catch unreachable;
  558. zig_args.append(@tagName(builder.color)) catch unreachable;
  559. }
  560. const zig_file = std.fs.path.join(builder.allocator, &[_][]const u8{ if (self.use_healed) "patches/healed" else "exercises", self.exercise.main_file }) catch unreachable;
  561. zig_args.append(builder.pathFromRoot(zig_file)) catch unreachable;
  562. zig_args.append("--cache-dir") catch unreachable;
  563. zig_args.append(builder.pathFromRoot(builder.cache_root)) catch unreachable;
  564. zig_args.append("--enable-cache") catch unreachable;
  565. const argv = zig_args.items;
  566. var code: u8 = undefined;
  567. const output_dir_nl = builder.execAllowFail(argv, &code, .Inherit) catch |err| {
  568. switch (err) {
  569. error.FileNotFound => {
  570. print("{s}{s}: Unable to spawn the following command: file not found{s}\n", .{ red_text, self.exercise.main_file, reset_text });
  571. for (argv) |v| print("{s} ", .{v});
  572. print("\n", .{});
  573. },
  574. error.ExitCodeFailure => {
  575. print("{s}{s}: The following command exited with error code {}:{s}\n", .{ red_text, self.exercise.main_file, code, reset_text });
  576. for (argv) |v| print("{s} ", .{v});
  577. print("\n", .{});
  578. },
  579. error.ProcessTerminated => {
  580. print("{s}{s}: The following command terminated unexpectedly:{s}\n", .{ red_text, self.exercise.main_file, reset_text });
  581. for (argv) |v| print("{s} ", .{v});
  582. print("\n", .{});
  583. },
  584. else => {},
  585. }
  586. return err;
  587. };
  588. const build_output_dir = std.mem.trimRight(u8, output_dir_nl, "\r\n");
  589. const target_info = std.zig.system.NativeTargetInfo.detect(
  590. builder.allocator,
  591. .{},
  592. ) catch unreachable;
  593. const target = target_info.target;
  594. const file_name = std.zig.binNameAlloc(builder.allocator, .{
  595. .root_name = self.exercise.baseName(),
  596. .target = target,
  597. .output_mode = .Exe,
  598. .link_mode = .Static,
  599. .version = null,
  600. }) catch unreachable;
  601. return std.fs.path.join(builder.allocator, &[_][]const u8{
  602. build_output_dir, file_name,
  603. });
  604. }
  605. };