zigup.zig 43 KB

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