zigup.zig 40 KB

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