zigup.zig 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102
  1. const std = @import("std");
  2. const builtin = @import("builtin");
  3. const mem = std.mem;
  4. const ArrayList = std.ArrayList;
  5. const Allocator = mem.Allocator;
  6. const fixdeletetree = @import("fixdeletetree.zig");
  7. const arch = switch (builtin.cpu.arch) {
  8. .x86_64 => "x86_64",
  9. .aarch64 => "aarch64",
  10. .arm => "armv7a",
  11. .riscv64 => "riscv64",
  12. .powerpc64le => "powerpc64le",
  13. .powerpc => "powerpc",
  14. else => @compileError("Unsupported CPU Architecture"),
  15. };
  16. const os = switch (builtin.os.tag) {
  17. .windows => "windows",
  18. .linux => "linux",
  19. .macos => "macos",
  20. else => @compileError("Unsupported OS"),
  21. };
  22. const url_platform = os ++ "-" ++ arch;
  23. const json_platform = arch ++ "-" ++ os;
  24. const archive_ext = if (builtin.os.tag == .windows) "zip" else "tar.xz";
  25. var global_optional_install_dir: ?[]const u8 = null;
  26. var global_optional_path_link: ?[]const u8 = null;
  27. var global_enable_log = true;
  28. fn loginfo(comptime fmt: []const u8, args: anytype) void {
  29. if (global_enable_log) {
  30. std.debug.print(fmt ++ "\n", args);
  31. }
  32. }
  33. pub fn oom(e: error{OutOfMemory}) noreturn {
  34. @panic(@errorName(e));
  35. }
  36. const DownloadResult = union(enum) {
  37. ok: void,
  38. err: []u8,
  39. pub fn deinit(self: DownloadResult, allocator: Allocator) void {
  40. switch (self) {
  41. .ok => {},
  42. .err => |e| allocator.free(e),
  43. }
  44. }
  45. };
  46. fn download(allocator: Allocator, url: []const u8, writer: anytype) DownloadResult {
  47. const uri = std.Uri.parse(url) catch |err| std.debug.panic(
  48. "failed to parse url '{s}' with {s}",
  49. .{ url, @errorName(err) },
  50. );
  51. var client = std.http.Client{ .allocator = allocator };
  52. defer client.deinit();
  53. client.initDefaultProxies(allocator) catch |err| return .{ .err = std.fmt.allocPrint(
  54. allocator,
  55. "failed to query the HTTP proxy settings with {s}",
  56. .{@errorName(err)},
  57. ) catch |e| oom(e) };
  58. var header_buffer: [4096]u8 = undefined;
  59. var request = client.open(.GET, uri, .{
  60. .server_header_buffer = &header_buffer,
  61. .keep_alive = false,
  62. }) catch |err| return .{ .err = std.fmt.allocPrint(
  63. allocator,
  64. "failed to connect to the HTTP server with {s}",
  65. .{@errorName(err)},
  66. ) catch |e| oom(e) };
  67. defer request.deinit();
  68. request.send() catch |err| return .{ .err = std.fmt.allocPrint(
  69. allocator,
  70. "failed to send the HTTP request with {s}",
  71. .{@errorName(err)},
  72. ) catch |e| oom(e) };
  73. request.wait() catch |err| return .{ .err = std.fmt.allocPrint(
  74. allocator,
  75. "failed to read the HTTP response headers with {s}",
  76. .{@errorName(err)},
  77. ) catch |e| oom(e) };
  78. if (request.response.status != .ok) return .{ .err = std.fmt.allocPrint(
  79. allocator,
  80. "HTTP server replied with unsuccessful response '{d} {s}'",
  81. .{ @intFromEnum(request.response.status), request.response.status.phrase() orelse "" },
  82. ) catch |e| oom(e) };
  83. // TODO: we take advantage of request.response.content_length
  84. var buf: [std.mem.page_size]u8 = undefined;
  85. while (true) {
  86. const len = request.reader().read(&buf) catch |err| return .{ .err = std.fmt.allocPrint(
  87. allocator,
  88. "failed to read the HTTP response body with {s}'",
  89. .{@errorName(err)},
  90. ) catch |e| oom(e) };
  91. if (len == 0)
  92. return .ok;
  93. writer.writeAll(buf[0..len]) catch |err| return .{ .err = std.fmt.allocPrint(
  94. allocator,
  95. "failed to write the HTTP response body with {s}'",
  96. .{@errorName(err)},
  97. ) catch |e| oom(e) };
  98. }
  99. }
  100. const DownloadStringResult = union(enum) {
  101. ok: []u8,
  102. err: []u8,
  103. };
  104. fn downloadToString(allocator: Allocator, url: []const u8) DownloadStringResult {
  105. var response_array_list = ArrayList(u8).initCapacity(allocator, 20 * 1024) catch |e| oom(e); // 20 KB (modify if response is expected to be bigger)
  106. defer response_array_list.deinit();
  107. switch (download(allocator, url, response_array_list.writer())) {
  108. .ok => return .{ .ok = response_array_list.toOwnedSlice() catch |e| oom(e) },
  109. .err => |e| return .{ .err = e },
  110. }
  111. }
  112. fn ignoreHttpCallback(request: []const u8) void {
  113. _ = request;
  114. }
  115. fn getHomeDir() ![]const u8 {
  116. return std.posix.getenv("HOME") orelse {
  117. std.log.err("cannot find install directory, $HOME environment variable is not set", .{});
  118. return error.MissingHomeEnvironmentVariable;
  119. };
  120. }
  121. fn allocInstallDirString(allocator: Allocator) ![]const u8 {
  122. // TODO: maybe support ZIG_INSTALL_DIR environment variable?
  123. // TODO: maybe support a file on the filesystem to configure install dir?
  124. if (builtin.os.tag == .windows) {
  125. const self_exe_dir = try std.fs.selfExeDirPathAlloc(allocator);
  126. defer allocator.free(self_exe_dir);
  127. return std.fs.path.join(allocator, &.{ self_exe_dir, "zig" });
  128. }
  129. const home = try getHomeDir();
  130. if (!std.fs.path.isAbsolute(home)) {
  131. std.log.err("$HOME environment variable '{s}' is not an absolute path", .{home});
  132. return error.BadHomeEnvironmentVariable;
  133. }
  134. return std.fs.path.join(allocator, &[_][]const u8{ home, "zig" });
  135. }
  136. const GetInstallDirOptions = struct {
  137. create: bool,
  138. };
  139. fn getInstallDir(allocator: Allocator, options: GetInstallDirOptions) ![]const u8 {
  140. var optional_dir_to_free_on_error: ?[]const u8 = null;
  141. errdefer if (optional_dir_to_free_on_error) |dir| allocator.free(dir);
  142. const install_dir = init: {
  143. if (global_optional_install_dir) |dir| break :init dir;
  144. optional_dir_to_free_on_error = try allocInstallDirString(allocator);
  145. break :init optional_dir_to_free_on_error.?;
  146. };
  147. std.debug.assert(std.fs.path.isAbsolute(install_dir));
  148. loginfo("install directory '{s}'", .{install_dir});
  149. if (options.create) {
  150. loggyMakeDirAbsolute(install_dir) catch |e| switch (e) {
  151. error.PathAlreadyExists => {},
  152. else => return e,
  153. };
  154. }
  155. return install_dir;
  156. }
  157. fn makeZigPathLinkString(allocator: Allocator) ![]const u8 {
  158. if (global_optional_path_link) |path| return path;
  159. const zigup_dir = try std.fs.selfExeDirPathAlloc(allocator);
  160. defer allocator.free(zigup_dir);
  161. return try std.fs.path.join(allocator, &[_][]const u8{ zigup_dir, comptime "zig" ++ builtin.target.exeFileExt() });
  162. }
  163. // TODO: this should be in standard lib
  164. fn toAbsolute(allocator: Allocator, path: []const u8) ![]u8 {
  165. std.debug.assert(!std.fs.path.isAbsolute(path));
  166. const cwd = try std.process.getCwdAlloc(allocator);
  167. defer allocator.free(cwd);
  168. return std.fs.path.join(allocator, &[_][]const u8{ cwd, path });
  169. }
  170. fn help() void {
  171. std.io.getStdErr().writeAll(
  172. \\Download and manage zig compilers.
  173. \\
  174. \\Common Usage:
  175. \\
  176. \\ zigup VERSION download and set VERSION compiler as default
  177. \\ zigup fetch VERSION download VERSION compiler
  178. \\ zigup default [VERSION] get or set the default compiler
  179. \\ zigup list list installed compiler versions
  180. \\ zigup clean [VERSION] deletes the given compiler version, otherwise, cleans all compilers
  181. \\ that aren't the default, master, or marked to keep.
  182. \\ zigup keep VERSION mark a compiler to be kept during clean
  183. \\ zigup run VERSION ARGS... run the given VERSION of the compiler with the given ARGS...
  184. \\
  185. \\Uncommon Usage:
  186. \\
  187. \\ zigup fetch-index download and print the download index json
  188. \\
  189. \\Common Options:
  190. \\ --install-dir DIR override the default install location
  191. \\ --path-link PATH path to the `zig` symlink that points to the default compiler
  192. \\ this will typically be a file path within a PATH directory so
  193. \\ that the user can just run `zig`
  194. \\
  195. ) catch unreachable;
  196. }
  197. fn getCmdOpt(args: [][]const u8, i: *usize) ![]const u8 {
  198. i.* += 1;
  199. if (i.* == args.len) {
  200. std.log.err("option '{s}' requires an argument", .{args[i.* - 1]});
  201. return error.AlreadyReported;
  202. }
  203. return args[i.*];
  204. }
  205. pub fn main() !u8 {
  206. return main2() catch |e| switch (e) {
  207. error.AlreadyReported => return 1,
  208. else => return e,
  209. };
  210. }
  211. pub fn main2() !u8 {
  212. if (builtin.os.tag == .windows) {
  213. _ = try std.os.windows.WSAStartup(2, 2);
  214. }
  215. var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
  216. const allocator = arena.allocator();
  217. const args_array = try std.process.argsAlloc(allocator);
  218. // no need to free, os will do it
  219. //defer std.process.argsFree(allocator, argsArray);
  220. var args = if (args_array.len == 0) args_array else args_array[1..];
  221. // parse common options
  222. //
  223. {
  224. var i: usize = 0;
  225. var newlen: usize = 0;
  226. while (i < args.len) : (i += 1) {
  227. const arg = args[i];
  228. if (std.mem.eql(u8, "--install-dir", arg)) {
  229. global_optional_install_dir = try getCmdOpt(args, &i);
  230. if (!std.fs.path.isAbsolute(global_optional_install_dir.?)) {
  231. global_optional_install_dir = try toAbsolute(allocator, global_optional_install_dir.?);
  232. }
  233. } else if (std.mem.eql(u8, "--path-link", arg)) {
  234. global_optional_path_link = try getCmdOpt(args, &i);
  235. if (!std.fs.path.isAbsolute(global_optional_path_link.?)) {
  236. global_optional_path_link = try toAbsolute(allocator, global_optional_path_link.?);
  237. }
  238. } else if (std.mem.eql(u8, "-h", arg) or std.mem.eql(u8, "--help", arg)) {
  239. help();
  240. return 0;
  241. } else {
  242. if (newlen == 0 and std.mem.eql(u8, "run", arg)) {
  243. return try runCompiler(allocator, args[i + 1 ..]);
  244. }
  245. args[newlen] = args[i];
  246. newlen += 1;
  247. }
  248. }
  249. args = args[0..newlen];
  250. }
  251. if (args.len == 0) {
  252. help();
  253. return 1;
  254. }
  255. if (std.mem.eql(u8, "fetch-index", args[0])) {
  256. if (args.len != 1) {
  257. std.log.err("'index' command requires 0 arguments but got {d}", .{args.len - 1});
  258. return 1;
  259. }
  260. var download_index = try fetchDownloadIndex(allocator);
  261. defer download_index.deinit(allocator);
  262. try std.io.getStdOut().writeAll(download_index.text);
  263. return 0;
  264. }
  265. if (std.mem.eql(u8, "fetch", args[0])) {
  266. if (args.len != 2) {
  267. std.log.err("'fetch' command requires 1 argument but got {d}", .{args.len - 1});
  268. return 1;
  269. }
  270. try fetchCompiler(allocator, args[1], .leave_default);
  271. return 0;
  272. }
  273. if (std.mem.eql(u8, "clean", args[0])) {
  274. if (args.len == 1) {
  275. try cleanCompilers(allocator, null);
  276. } else if (args.len == 2) {
  277. try cleanCompilers(allocator, args[1]);
  278. } else {
  279. std.log.err("'clean' command requires 0 or 1 arguments but got {d}", .{args.len - 1});
  280. return 1;
  281. }
  282. return 0;
  283. }
  284. if (std.mem.eql(u8, "keep", args[0])) {
  285. if (args.len != 2) {
  286. std.log.err("'keep' command requires 1 argument but got {d}", .{args.len - 1});
  287. return 1;
  288. }
  289. try keepCompiler(allocator, args[1]);
  290. return 0;
  291. }
  292. if (std.mem.eql(u8, "list", args[0])) {
  293. if (args.len != 1) {
  294. std.log.err("'list' command requires 0 arguments but got {d}", .{args.len - 1});
  295. return 1;
  296. }
  297. try listCompilers(allocator);
  298. return 0;
  299. }
  300. if (std.mem.eql(u8, "default", args[0])) {
  301. if (args.len == 1) {
  302. try printDefaultCompiler(allocator);
  303. return 0;
  304. }
  305. if (args.len == 2) {
  306. const version_string = args[1];
  307. const install_dir_string = try getInstallDir(allocator, .{ .create = true });
  308. defer allocator.free(install_dir_string);
  309. const resolved_version_string = init_resolved: {
  310. if (!std.mem.eql(u8, version_string, "master"))
  311. break :init_resolved version_string;
  312. const optional_master_dir: ?[]const u8 = blk: {
  313. var install_dir = std.fs.openDirAbsolute(install_dir_string, .{ .iterate = true }) catch |e| switch (e) {
  314. error.FileNotFound => break :blk null,
  315. else => return e,
  316. };
  317. defer install_dir.close();
  318. break :blk try getMasterDir(allocator, &install_dir);
  319. };
  320. // no need to free master_dir, this is a short lived program
  321. break :init_resolved optional_master_dir orelse {
  322. std.log.err("master has not been fetched", .{});
  323. return 1;
  324. };
  325. };
  326. const compiler_dir = try std.fs.path.join(allocator, &[_][]const u8{ install_dir_string, resolved_version_string });
  327. defer allocator.free(compiler_dir);
  328. try setDefaultCompiler(allocator, compiler_dir, .verify_existence);
  329. return 0;
  330. }
  331. std.log.err("'default' command requires 1 or 2 arguments but got {d}", .{args.len - 1});
  332. return 1;
  333. }
  334. if (args.len == 1) {
  335. try fetchCompiler(allocator, args[0], .set_default);
  336. return 0;
  337. }
  338. const command = args[0];
  339. args = args[1..];
  340. std.log.err("command not impl '{s}'", .{command});
  341. return 1;
  342. //const optionalInstallPath = try find_zigs(allocator);
  343. }
  344. pub fn runCompiler(allocator: Allocator, args: []const []const u8) !u8 {
  345. // disable log so we don't add extra output to whatever the compiler will output
  346. global_enable_log = false;
  347. if (args.len <= 1) {
  348. std.log.err("zigup run requires at least 2 arguments: zigup run VERSION PROG ARGS...", .{});
  349. return 1;
  350. }
  351. const version_string = args[0];
  352. const install_dir_string = try getInstallDir(allocator, .{ .create = true });
  353. defer allocator.free(install_dir_string);
  354. const compiler_dir = try std.fs.path.join(allocator, &[_][]const u8{ install_dir_string, version_string });
  355. defer allocator.free(compiler_dir);
  356. if (!try existsAbsolute(compiler_dir)) {
  357. std.log.err("compiler '{s}' does not exist, fetch it first with: zigup fetch {0s}", .{version_string});
  358. return 1;
  359. }
  360. var argv = std.ArrayList([]const u8).init(allocator);
  361. try argv.append(try std.fs.path.join(allocator, &.{ compiler_dir, "files", comptime "zig" ++ builtin.target.exeFileExt() }));
  362. try argv.appendSlice(args[1..]);
  363. // TODO: use "execve" if on linux
  364. var proc = std.process.Child.init(argv.items, allocator);
  365. const ret_val = try proc.spawnAndWait();
  366. switch (ret_val) {
  367. .Exited => |code| return code,
  368. else => |result| {
  369. std.log.err("compiler exited with {}", .{result});
  370. return 0xff;
  371. },
  372. }
  373. }
  374. const SetDefault = enum { set_default, leave_default };
  375. fn fetchCompiler(allocator: Allocator, version_arg: []const u8, set_default: SetDefault) !void {
  376. const install_dir = try getInstallDir(allocator, .{ .create = true });
  377. defer allocator.free(install_dir);
  378. var optional_download_index: ?DownloadIndex = null;
  379. // This is causing an LLVM error
  380. //defer if (optionalDownloadIndex) |_| optionalDownloadIndex.?.deinit(allocator);
  381. // Also I would rather do this, but it doesn't work because of const issues
  382. //defer if (optionalDownloadIndex) |downloadIndex| downloadIndex.deinit(allocator);
  383. const VersionUrl = struct { version: []const u8, url: []const u8 };
  384. // NOTE: we only fetch the download index if the user wants to download 'master', we can skip
  385. // this step for all other versions because the version to URL mapping is fixed (see getDefaultUrl)
  386. const is_master = std.mem.eql(u8, version_arg, "master");
  387. const version_url = blk: {
  388. if (!is_master)
  389. break :blk VersionUrl{ .version = version_arg, .url = try getDefaultUrl(allocator, version_arg) };
  390. optional_download_index = try fetchDownloadIndex(allocator);
  391. const master = optional_download_index.?.json.value.object.get("master").?;
  392. const compiler_version = master.object.get("version").?.string;
  393. const master_linux = master.object.get(json_platform).?;
  394. const master_linux_tarball = master_linux.object.get("tarball").?.string;
  395. break :blk VersionUrl{ .version = compiler_version, .url = master_linux_tarball };
  396. };
  397. const compiler_dir = try std.fs.path.join(allocator, &[_][]const u8{ install_dir, version_url.version });
  398. defer allocator.free(compiler_dir);
  399. try installCompiler(allocator, compiler_dir, version_url.url);
  400. if (is_master) {
  401. const master_symlink = try std.fs.path.join(allocator, &[_][]const u8{ install_dir, "master" });
  402. defer allocator.free(master_symlink);
  403. if (builtin.os.tag == .windows) {
  404. var file = try std.fs.createFileAbsolute(master_symlink, .{});
  405. defer file.close();
  406. try file.writer().writeAll(version_url.version);
  407. } else {
  408. _ = try loggyUpdateSymlink(version_url.version, master_symlink, .{ .is_directory = true });
  409. }
  410. }
  411. if (set_default == .set_default) {
  412. try setDefaultCompiler(allocator, compiler_dir, .existence_verified);
  413. }
  414. }
  415. const download_index_url = "https://ziglang.org/download/index.json";
  416. const DownloadIndex = struct {
  417. text: []u8,
  418. json: std.json.Parsed(std.json.Value),
  419. pub fn deinit(self: *DownloadIndex, allocator: Allocator) void {
  420. self.json.deinit();
  421. allocator.free(self.text);
  422. }
  423. };
  424. fn fetchDownloadIndex(allocator: Allocator) !DownloadIndex {
  425. const text = switch (downloadToString(allocator, download_index_url)) {
  426. .ok => |text| text,
  427. .err => |err| {
  428. std.log.err("download '{s}' failed: {s}", .{ download_index_url, err });
  429. return error.AlreadyReported;
  430. },
  431. };
  432. errdefer allocator.free(text);
  433. var json = try std.json.parseFromSlice(std.json.Value, allocator, text, .{});
  434. errdefer json.deinit();
  435. return DownloadIndex{ .text = text, .json = json };
  436. }
  437. fn loggyMakeDirAbsolute(dir_absolute: []const u8) !void {
  438. if (builtin.os.tag == .windows) {
  439. loginfo("mkdir \"{s}\"", .{dir_absolute});
  440. } else {
  441. loginfo("mkdir '{s}'", .{dir_absolute});
  442. }
  443. try std.fs.makeDirAbsolute(dir_absolute);
  444. }
  445. fn loggyDeleteTreeAbsolute(dir_absolute: []const u8) !void {
  446. if (builtin.os.tag == .windows) {
  447. loginfo("rd /s /q \"{s}\"", .{dir_absolute});
  448. } else {
  449. loginfo("rm -rf '{s}'", .{dir_absolute});
  450. }
  451. try fixdeletetree.deleteTreeAbsolute(dir_absolute);
  452. }
  453. pub fn loggyRenameAbsolute(old_path: []const u8, new_path: []const u8) !void {
  454. loginfo("mv '{s}' '{s}'", .{ old_path, new_path });
  455. try std.fs.renameAbsolute(old_path, new_path);
  456. }
  457. pub fn loggySymlinkAbsolute(target_path: []const u8, sym_link_path: []const u8, flags: std.fs.Dir.SymLinkFlags) !void {
  458. loginfo("ln -s '{s}' '{s}'", .{ target_path, sym_link_path });
  459. // NOTE: can't use symLinkAbsolute because it requires target_path to be absolute but we don't want that
  460. // not sure if it is a bug in the standard lib or not
  461. //try std.fs.symLinkAbsolute(target_path, sym_link_path, flags);
  462. _ = flags;
  463. try std.posix.symlink(target_path, sym_link_path);
  464. }
  465. /// returns: true if the symlink was updated, false if it was already set to the given `target_path`
  466. pub fn loggyUpdateSymlink(target_path: []const u8, sym_link_path: []const u8, flags: std.fs.Dir.SymLinkFlags) !bool {
  467. var current_target_path_buffer: [std.fs.max_path_bytes]u8 = undefined;
  468. if (std.fs.readLinkAbsolute(sym_link_path, &current_target_path_buffer)) |current_target_path| {
  469. if (std.mem.eql(u8, target_path, current_target_path)) {
  470. loginfo("symlink '{s}' already points to '{s}'", .{ sym_link_path, target_path });
  471. return false; // already up-to-date
  472. }
  473. try std.posix.unlink(sym_link_path);
  474. } else |e| switch (e) {
  475. error.FileNotFound => {},
  476. error.NotLink => {
  477. std.debug.print(
  478. "unable to update/overwrite the 'zig' PATH symlink, the file '{s}' already exists and is not a symlink\n",
  479. .{sym_link_path},
  480. );
  481. std.process.exit(1);
  482. },
  483. else => return e,
  484. }
  485. try loggySymlinkAbsolute(target_path, sym_link_path, flags);
  486. return true; // updated
  487. }
  488. // TODO: this should be in std lib somewhere
  489. fn existsAbsolute(absolutePath: []const u8) !bool {
  490. std.fs.cwd().access(absolutePath, .{}) catch |e| switch (e) {
  491. error.FileNotFound => return false,
  492. error.PermissionDenied => return e,
  493. error.InputOutput => return e,
  494. error.SystemResources => return e,
  495. error.SymLinkLoop => return e,
  496. error.FileBusy => return e,
  497. error.Unexpected => unreachable,
  498. error.InvalidUtf8 => return e,
  499. error.InvalidWtf8 => return e,
  500. error.ReadOnlyFileSystem => unreachable,
  501. error.NameTooLong => unreachable,
  502. error.BadPathName => unreachable,
  503. };
  504. return true;
  505. }
  506. fn listCompilers(allocator: Allocator) !void {
  507. const install_dir_string = try getInstallDir(allocator, .{ .create = false });
  508. defer allocator.free(install_dir_string);
  509. var install_dir = std.fs.openDirAbsolute(install_dir_string, .{ .iterate = true }) catch |e| switch (e) {
  510. error.FileNotFound => return,
  511. else => return e,
  512. };
  513. defer install_dir.close();
  514. const stdout = std.io.getStdOut().writer();
  515. {
  516. var it = install_dir.iterate();
  517. while (try it.next()) |entry| {
  518. if (entry.kind != .directory)
  519. continue;
  520. if (std.mem.endsWith(u8, entry.name, ".installing"))
  521. continue;
  522. try stdout.print("{s}\n", .{entry.name});
  523. }
  524. }
  525. }
  526. fn keepCompiler(allocator: Allocator, compiler_version: []const u8) !void {
  527. const install_dir_string = try getInstallDir(allocator, .{ .create = true });
  528. defer allocator.free(install_dir_string);
  529. var install_dir = try std.fs.openDirAbsolute(install_dir_string, .{ .iterate = true });
  530. defer install_dir.close();
  531. var compiler_dir = install_dir.openDir(compiler_version, .{}) catch |e| switch (e) {
  532. error.FileNotFound => {
  533. std.log.err("compiler not found: {s}", .{compiler_version});
  534. return error.AlreadyReported;
  535. },
  536. else => return e,
  537. };
  538. var keep_fd = try compiler_dir.createFile("keep", .{});
  539. keep_fd.close();
  540. loginfo("created '{s}{c}{s}{c}{s}'", .{ install_dir_string, std.fs.path.sep, compiler_version, std.fs.path.sep, "keep" });
  541. }
  542. fn cleanCompilers(allocator: Allocator, compiler_name_opt: ?[]const u8) !void {
  543. const install_dir_string = try getInstallDir(allocator, .{ .create = true });
  544. defer allocator.free(install_dir_string);
  545. // getting the current compiler
  546. const default_comp_opt = try getDefaultCompiler(allocator);
  547. defer if (default_comp_opt) |default_compiler| allocator.free(default_compiler);
  548. var install_dir = std.fs.openDirAbsolute(install_dir_string, .{ .iterate = true }) catch |e| switch (e) {
  549. error.FileNotFound => return,
  550. else => return e,
  551. };
  552. defer install_dir.close();
  553. const master_points_to_opt = try getMasterDir(allocator, &install_dir);
  554. defer if (master_points_to_opt) |master_points_to| allocator.free(master_points_to);
  555. if (compiler_name_opt) |compiler_name| {
  556. if (getKeepReason(master_points_to_opt, default_comp_opt, compiler_name)) |reason| {
  557. std.log.err("cannot clean '{s}' ({s})", .{ compiler_name, reason });
  558. return error.AlreadyReported;
  559. }
  560. loginfo("deleting '{s}{c}{s}'", .{ install_dir_string, std.fs.path.sep, compiler_name });
  561. try fixdeletetree.deleteTree(install_dir, compiler_name);
  562. } else {
  563. var it = install_dir.iterate();
  564. while (try it.next()) |entry| {
  565. if (entry.kind != .directory)
  566. continue;
  567. if (getKeepReason(master_points_to_opt, default_comp_opt, entry.name)) |reason| {
  568. loginfo("keeping '{s}' ({s})", .{ entry.name, reason });
  569. continue;
  570. }
  571. {
  572. var compiler_dir = try install_dir.openDir(entry.name, .{});
  573. defer compiler_dir.close();
  574. if (compiler_dir.access("keep", .{})) |_| {
  575. loginfo("keeping '{s}' (has keep file)", .{entry.name});
  576. continue;
  577. } else |e| switch (e) {
  578. error.FileNotFound => {},
  579. else => return e,
  580. }
  581. }
  582. loginfo("deleting '{s}{c}{s}'", .{ install_dir_string, std.fs.path.sep, entry.name });
  583. try fixdeletetree.deleteTree(install_dir, entry.name);
  584. }
  585. }
  586. }
  587. fn readDefaultCompiler(allocator: Allocator, buffer: *[std.fs.max_path_bytes + 1]u8) !?[]const u8 {
  588. const path_link = try makeZigPathLinkString(allocator);
  589. defer allocator.free(path_link);
  590. if (builtin.os.tag == .windows) {
  591. var file = std.fs.openFileAbsolute(path_link, .{}) catch |e| switch (e) {
  592. error.FileNotFound => return null,
  593. else => return e,
  594. };
  595. defer file.close();
  596. try file.seekTo(win32exelink.exe_offset);
  597. const len = try file.readAll(buffer);
  598. if (len != buffer.len) {
  599. std.log.err("path link file '{s}' is too small", .{path_link});
  600. return error.AlreadyReported;
  601. }
  602. const target_exe = std.mem.sliceTo(buffer, 0);
  603. return try allocator.dupe(u8, targetPathToVersion(target_exe));
  604. }
  605. const target_path = std.fs.readLinkAbsolute(path_link, buffer[0..std.fs.max_path_bytes]) catch |e| switch (e) {
  606. error.FileNotFound => return null,
  607. else => return e,
  608. };
  609. defer allocator.free(target_path);
  610. return try allocator.dupe(u8, targetPathToVersion(target_path));
  611. }
  612. fn targetPathToVersion(target_path: []const u8) []const u8 {
  613. return std.fs.path.basename(std.fs.path.dirname(std.fs.path.dirname(target_path).?).?);
  614. }
  615. fn readMasterDir(buffer: *[std.fs.max_path_bytes]u8, install_dir: *std.fs.Dir) !?[]const u8 {
  616. if (builtin.os.tag == .windows) {
  617. var file = install_dir.openFile("master", .{}) catch |e| switch (e) {
  618. error.FileNotFound => return null,
  619. else => return e,
  620. };
  621. defer file.close();
  622. return buffer[0..try file.readAll(buffer)];
  623. }
  624. return install_dir.readLink("master", buffer) catch |e| switch (e) {
  625. error.FileNotFound => return null,
  626. else => return e,
  627. };
  628. }
  629. fn getDefaultCompiler(allocator: Allocator) !?[]const u8 {
  630. var buffer: [std.fs.max_path_bytes + 1]u8 = undefined;
  631. const slice_path = (try readDefaultCompiler(allocator, &buffer)) orelse return null;
  632. const path_to_return = try allocator.alloc(u8, slice_path.len);
  633. @memcpy(path_to_return, slice_path);
  634. return path_to_return;
  635. }
  636. fn getMasterDir(allocator: Allocator, install_dir: *std.fs.Dir) !?[]const u8 {
  637. var buffer: [std.fs.max_path_bytes]u8 = undefined;
  638. const slice_path = (try readMasterDir(&buffer, install_dir)) orelse return null;
  639. const path_to_return = try allocator.alloc(u8, slice_path.len);
  640. @memcpy(path_to_return, slice_path);
  641. return path_to_return;
  642. }
  643. fn printDefaultCompiler(allocator: Allocator) !void {
  644. const default_compiler_opt = try getDefaultCompiler(allocator);
  645. defer if (default_compiler_opt) |default_compiler| allocator.free(default_compiler);
  646. const stdout = std.io.getStdOut().writer();
  647. if (default_compiler_opt) |default_compiler| {
  648. try stdout.print("{s}\n", .{default_compiler});
  649. } else {
  650. try stdout.writeAll("<no-default>\n");
  651. }
  652. }
  653. const ExistVerify = enum { existence_verified, verify_existence };
  654. fn setDefaultCompiler(allocator: Allocator, compiler_dir: []const u8, exist_verify: ExistVerify) !void {
  655. switch (exist_verify) {
  656. .existence_verified => {},
  657. .verify_existence => {
  658. var dir = std.fs.openDirAbsolute(compiler_dir, .{}) catch |err| switch (err) {
  659. error.FileNotFound => {
  660. std.log.err("compiler '{s}' is not installed", .{std.fs.path.basename(compiler_dir)});
  661. return error.AlreadyReported;
  662. },
  663. else => |e| return e,
  664. };
  665. dir.close();
  666. },
  667. }
  668. const path_link = try makeZigPathLinkString(allocator);
  669. defer allocator.free(path_link);
  670. const link_target = try std.fs.path.join(
  671. allocator,
  672. &[_][]const u8{ compiler_dir, "files", comptime "zig" ++ builtin.target.exeFileExt() },
  673. );
  674. defer allocator.free(link_target);
  675. if (builtin.os.tag == .windows) {
  676. try createExeLink(link_target, path_link);
  677. } else {
  678. _ = try loggyUpdateSymlink(link_target, path_link, .{});
  679. }
  680. try verifyPathLink(allocator, path_link);
  681. }
  682. /// Verify that path_link will work. It verifies that `path_link` is
  683. /// in PATH and there is no zig executable in an earlier directory in PATH.
  684. fn verifyPathLink(allocator: Allocator, path_link: []const u8) !void {
  685. const path_link_dir = std.fs.path.dirname(path_link) orelse {
  686. std.log.err("invalid '--path-link' '{s}', it must be a file (not the root directory)", .{path_link});
  687. return error.AlreadyReported;
  688. };
  689. const path_link_dir_id = blk: {
  690. var dir = std.fs.openDirAbsolute(path_link_dir, .{}) catch |err| {
  691. std.log.err("unable to open the path-link directory '{s}': {s}", .{ path_link_dir, @errorName(err) });
  692. return error.AlreadyReported;
  693. };
  694. defer dir.close();
  695. break :blk try FileId.initFromDir(dir, path_link);
  696. };
  697. if (builtin.os.tag == .windows) {
  698. const path_env = std.process.getEnvVarOwned(allocator, "PATH") catch |err| switch (err) {
  699. error.EnvironmentVariableNotFound => return,
  700. else => |e| return e,
  701. };
  702. defer allocator.free(path_env);
  703. var free_pathext: ?[]const u8 = null;
  704. defer if (free_pathext) |p| allocator.free(p);
  705. const pathext_env = blk: {
  706. if (std.process.getEnvVarOwned(allocator, "PATHEXT")) |env| {
  707. free_pathext = env;
  708. break :blk env;
  709. } else |err| switch (err) {
  710. error.EnvironmentVariableNotFound => break :blk "",
  711. else => |e| return e,
  712. }
  713. break :blk "";
  714. };
  715. var path_it = std.mem.tokenizeScalar(u8, path_env, ';');
  716. while (path_it.next()) |path| {
  717. switch (try compareDir(path_link_dir_id, path)) {
  718. .missing => continue,
  719. // can't be the same directory because we were able to open and get
  720. // the file id for path_link_dir_id
  721. .access_denied => {},
  722. .match => return,
  723. .mismatch => {},
  724. }
  725. {
  726. const exe = try std.fs.path.join(allocator, &.{ path, "zig" });
  727. defer allocator.free(exe);
  728. try enforceNoZig(path_link, exe);
  729. }
  730. var ext_it = std.mem.tokenizeScalar(u8, pathext_env, ';');
  731. while (ext_it.next()) |ext| {
  732. if (ext.len == 0) continue;
  733. const basename = try std.mem.concat(allocator, u8, &.{ "zig", ext });
  734. defer allocator.free(basename);
  735. const exe = try std.fs.path.join(allocator, &.{ path, basename });
  736. defer allocator.free(exe);
  737. try enforceNoZig(path_link, exe);
  738. }
  739. }
  740. } else {
  741. var path_it = std.mem.tokenizeScalar(u8, std.posix.getenv("PATH") orelse "", ':');
  742. while (path_it.next()) |path| {
  743. switch (try compareDir(path_link_dir_id, path)) {
  744. .missing => continue,
  745. // can't be the same directory because we were able to open and get
  746. // the file id for path_link_dir_id
  747. .access_denied => {},
  748. .match => return,
  749. .mismatch => {},
  750. }
  751. const exe = try std.fs.path.join(allocator, &.{ path, "zig" });
  752. defer allocator.free(exe);
  753. try enforceNoZig(path_link, exe);
  754. }
  755. }
  756. std.log.err("the path link '{s}' is not in PATH", .{path_link});
  757. return error.AlreadyReported;
  758. }
  759. fn compareDir(dir_id: FileId, other_dir: []const u8) !enum { missing, access_denied, match, mismatch } {
  760. var dir = std.fs.cwd().openDir(other_dir, .{}) catch |err| switch (err) {
  761. error.FileNotFound, error.NotDir, error.BadPathName => return .missing,
  762. error.AccessDenied => return .access_denied,
  763. else => |e| return e,
  764. };
  765. defer dir.close();
  766. return if (dir_id.eql(try FileId.initFromDir(dir, other_dir))) .match else .mismatch;
  767. }
  768. fn enforceNoZig(path_link: []const u8, exe: []const u8) !void {
  769. var file = std.fs.cwd().openFile(exe, .{}) catch |err| switch (err) {
  770. error.FileNotFound, error.IsDir => return,
  771. error.AccessDenied => return, // if there is a Zig it must not be accessible
  772. else => |e| return e,
  773. };
  774. defer file.close();
  775. // todo: on posix systems ignore the file if it is not executable
  776. std.log.err("zig compiler '{s}' is higher priority in PATH than the path-link '{s}'", .{ exe, path_link });
  777. }
  778. const FileId = struct {
  779. dev: if (builtin.os.tag == .windows) u32 else blk: {
  780. const st: std.posix.Stat = undefined;
  781. break :blk @TypeOf(st.dev);
  782. },
  783. ino: if (builtin.os.tag == .windows) u64 else blk: {
  784. const st: std.posix.Stat = undefined;
  785. break :blk @TypeOf(st.ino);
  786. },
  787. pub fn initFromFile(file: std.fs.File, filename_for_error: []const u8) !FileId {
  788. if (builtin.os.tag == .windows) {
  789. var info: win32.BY_HANDLE_FILE_INFORMATION = undefined;
  790. if (0 == win32.GetFileInformationByHandle(file.handle, &info)) {
  791. std.log.err("GetFileInformationByHandle on '{s}' failed, error={}", .{ filename_for_error, std.os.windows.kernel32.GetLastError() });
  792. return error.AlreadyReported;
  793. }
  794. return FileId{
  795. .dev = info.dwVolumeSerialNumber,
  796. .ino = (@as(u64, @intCast(info.nFileIndexHigh)) << 32) | @as(u64, @intCast(info.nFileIndexLow)),
  797. };
  798. }
  799. const st = try std.posix.fstat(file.handle);
  800. return FileId{
  801. .dev = st.dev,
  802. .ino = st.ino,
  803. };
  804. }
  805. pub fn initFromDir(dir: std.fs.Dir, name_for_error: []const u8) !FileId {
  806. if (builtin.os.tag == .windows) {
  807. return initFromFile(std.fs.File{ .handle = dir.fd }, name_for_error);
  808. }
  809. return initFromFile(std.fs.File{ .handle = dir.fd }, name_for_error);
  810. }
  811. pub fn eql(self: FileId, other: FileId) bool {
  812. return self.dev == other.dev and self.ino == other.ino;
  813. }
  814. };
  815. const win32 = struct {
  816. pub const BOOL = i32;
  817. pub const FILETIME = extern struct {
  818. dwLowDateTime: u32,
  819. dwHighDateTime: u32,
  820. };
  821. pub const BY_HANDLE_FILE_INFORMATION = extern struct {
  822. dwFileAttributes: u32,
  823. ftCreationTime: FILETIME,
  824. ftLastAccessTime: FILETIME,
  825. ftLastWriteTime: FILETIME,
  826. dwVolumeSerialNumber: u32,
  827. nFileSizeHigh: u32,
  828. nFileSizeLow: u32,
  829. nNumberOfLinks: u32,
  830. nFileIndexHigh: u32,
  831. nFileIndexLow: u32,
  832. };
  833. pub extern "kernel32" fn GetFileInformationByHandle(
  834. hFile: ?@import("std").os.windows.HANDLE,
  835. lpFileInformation: ?*BY_HANDLE_FILE_INFORMATION,
  836. ) callconv(@import("std").os.windows.WINAPI) BOOL;
  837. };
  838. const win32exelink = struct {
  839. const content = @embedFile("win32exelink");
  840. const exe_offset: usize = if (builtin.os.tag != .windows) 0 else blk: {
  841. @setEvalBranchQuota(content.len * 2);
  842. const marker = "!!!THIS MARKS THE zig_exe_string MEMORY!!#";
  843. const offset = std.mem.indexOf(u8, content, marker) orelse {
  844. @compileError("win32exelink is missing the marker: " ++ marker);
  845. };
  846. if (std.mem.indexOf(u8, content[offset + 1 ..], marker) != null) {
  847. @compileError("win32exelink contains multiple markers (not implemented)");
  848. }
  849. break :blk offset + marker.len;
  850. };
  851. };
  852. fn createExeLink(link_target: []const u8, path_link: []const u8) !void {
  853. if (path_link.len > std.fs.max_path_bytes) {
  854. std.debug.print("Error: path_link (size {}) is too large (max {})\n", .{ path_link.len, std.fs.max_path_bytes });
  855. return error.AlreadyReported;
  856. }
  857. const file = std.fs.cwd().createFile(path_link, .{}) catch |err| switch (err) {
  858. error.IsDir => {
  859. std.debug.print(
  860. "unable to create the exe link, the path '{s}' is a directory\n",
  861. .{path_link},
  862. );
  863. std.process.exit(1);
  864. },
  865. else => |e| return e,
  866. };
  867. defer file.close();
  868. try file.writer().writeAll(win32exelink.content[0..win32exelink.exe_offset]);
  869. try file.writer().writeAll(link_target);
  870. try file.writer().writeAll(win32exelink.content[win32exelink.exe_offset + link_target.len ..]);
  871. }
  872. const VersionKind = enum { release, dev };
  873. fn determineVersionKind(version: []const u8) VersionKind {
  874. return if (std.mem.indexOfAny(u8, version, "-+")) |_| .dev else .release;
  875. }
  876. fn getDefaultUrl(allocator: Allocator, compiler_version: []const u8) ![]const u8 {
  877. return switch (determineVersionKind(compiler_version)) {
  878. .dev => try std.fmt.allocPrint(allocator, "https://ziglang.org/builds/zig-" ++ url_platform ++ "-{0s}." ++ archive_ext, .{compiler_version}),
  879. .release => try std.fmt.allocPrint(allocator, "https://ziglang.org/download/{s}/zig-" ++ url_platform ++ "-{0s}." ++ archive_ext, .{compiler_version}),
  880. };
  881. }
  882. fn installCompiler(allocator: Allocator, compiler_dir: []const u8, url: []const u8) !void {
  883. if (try existsAbsolute(compiler_dir)) {
  884. loginfo("compiler '{s}' already installed", .{compiler_dir});
  885. return;
  886. }
  887. const installing_dir = try std.mem.concat(allocator, u8, &[_][]const u8{ compiler_dir, ".installing" });
  888. defer allocator.free(installing_dir);
  889. try loggyDeleteTreeAbsolute(installing_dir);
  890. try loggyMakeDirAbsolute(installing_dir);
  891. const archive_basename = std.fs.path.basename(url);
  892. var archive_root_dir: []const u8 = undefined;
  893. // download and extract archive
  894. {
  895. const archive_absolute = try std.fs.path.join(allocator, &[_][]const u8{ installing_dir, archive_basename });
  896. defer allocator.free(archive_absolute);
  897. loginfo("downloading '{s}' to '{s}'", .{ url, archive_absolute });
  898. switch (blk: {
  899. const file = try std.fs.createFileAbsolute(archive_absolute, .{});
  900. // note: important to close the file before we handle errors below
  901. // since it will delete the parent directory of this file
  902. defer file.close();
  903. break :blk download(allocator, url, file.writer());
  904. }) {
  905. .ok => {},
  906. .err => |err| {
  907. std.log.err("download '{s}' failed: {s}", .{ url, err });
  908. // this removes the installing dir if the http request fails so we dont have random directories
  909. try loggyDeleteTreeAbsolute(installing_dir);
  910. return error.AlreadyReported;
  911. },
  912. }
  913. if (std.mem.endsWith(u8, archive_basename, ".tar.xz")) {
  914. archive_root_dir = archive_basename[0 .. archive_basename.len - ".tar.xz".len];
  915. _ = try run(allocator, &[_][]const u8{ "tar", "xf", archive_absolute, "-C", installing_dir });
  916. } else {
  917. var recognized = false;
  918. if (builtin.os.tag == .windows) {
  919. if (std.mem.endsWith(u8, archive_basename, ".zip")) {
  920. recognized = true;
  921. archive_root_dir = archive_basename[0 .. archive_basename.len - ".zip".len];
  922. var installing_dir_opened = try std.fs.openDirAbsolute(installing_dir, .{});
  923. defer installing_dir_opened.close();
  924. loginfo("extracting archive to \"{s}\"", .{installing_dir});
  925. var timer = try std.time.Timer.start();
  926. var archive_file = try std.fs.openFileAbsolute(archive_absolute, .{});
  927. defer archive_file.close();
  928. try std.zip.extract(installing_dir_opened, archive_file.seekableStream(), .{});
  929. const time = timer.read();
  930. loginfo("extracted archive in {d:.2} s", .{@as(f32, @floatFromInt(time)) / @as(f32, @floatFromInt(std.time.ns_per_s))});
  931. }
  932. }
  933. if (!recognized) {
  934. std.log.err("unknown archive extension '{s}'", .{archive_basename});
  935. return error.UnknownArchiveExtension;
  936. }
  937. }
  938. try loggyDeleteTreeAbsolute(archive_absolute);
  939. }
  940. {
  941. const extracted_dir = try std.fs.path.join(allocator, &[_][]const u8{ installing_dir, archive_root_dir });
  942. defer allocator.free(extracted_dir);
  943. const normalized_dir = try std.fs.path.join(allocator, &[_][]const u8{ installing_dir, "files" });
  944. defer allocator.free(normalized_dir);
  945. try loggyRenameAbsolute(extracted_dir, normalized_dir);
  946. }
  947. // TODO: write date information (so users can sort compilers by date)
  948. // finish installation by renaming the install dir
  949. try loggyRenameAbsolute(installing_dir, compiler_dir);
  950. }
  951. pub fn run(allocator: Allocator, argv: []const []const u8) !std.process.Child.Term {
  952. try logRun(allocator, argv);
  953. var proc = std.process.Child.init(argv, allocator);
  954. return proc.spawnAndWait();
  955. }
  956. fn logRun(allocator: Allocator, argv: []const []const u8) !void {
  957. var buffer = try allocator.alloc(u8, getCommandStringLength(argv));
  958. defer allocator.free(buffer);
  959. var prefix = false;
  960. var offset: usize = 0;
  961. for (argv) |arg| {
  962. if (prefix) {
  963. buffer[offset] = ' ';
  964. offset += 1;
  965. } else {
  966. prefix = true;
  967. }
  968. @memcpy(buffer[offset .. offset + arg.len], arg);
  969. offset += arg.len;
  970. }
  971. std.debug.assert(offset == buffer.len);
  972. loginfo("[RUN] {s}", .{buffer});
  973. }
  974. pub fn getCommandStringLength(argv: []const []const u8) usize {
  975. var len: usize = 0;
  976. var prefix_length: u8 = 0;
  977. for (argv) |arg| {
  978. len += prefix_length + arg.len;
  979. prefix_length = 1;
  980. }
  981. return len;
  982. }
  983. pub fn getKeepReason(master_points_to_opt: ?[]const u8, default_compiler_opt: ?[]const u8, name: []const u8) ?[]const u8 {
  984. if (default_compiler_opt) |default_comp| {
  985. if (mem.eql(u8, default_comp, name)) {
  986. return "is default compiler";
  987. }
  988. }
  989. if (master_points_to_opt) |master_points_to| {
  990. if (mem.eql(u8, master_points_to, name)) {
  991. return "it is master";
  992. }
  993. }
  994. return null;
  995. }