zigup.zig 40 KB

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