zigup.zig 43 KB

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