zigup.zig 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  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. else => return e,
  425. }
  426. try loggySymlinkAbsolute(target_path, sym_link_path, flags);
  427. return true; // updated
  428. }
  429. // TODO: this should be in std lib somewhere
  430. fn existsAbsolute(absolutePath: []const u8) !bool {
  431. std.fs.cwd().access(absolutePath, .{}) catch |e| switch (e) {
  432. error.FileNotFound => return false,
  433. error.PermissionDenied => return e,
  434. error.InputOutput => return e,
  435. error.SystemResources => return e,
  436. error.SymLinkLoop => return e,
  437. error.FileBusy => return e,
  438. error.Unexpected => unreachable,
  439. error.InvalidUtf8 => unreachable,
  440. error.ReadOnlyFileSystem => unreachable,
  441. error.NameTooLong => unreachable,
  442. error.BadPathName => unreachable,
  443. };
  444. return true;
  445. }
  446. fn listCompilers(allocator: Allocator) !void {
  447. const install_dir_string = try getInstallDir(allocator, .{ .create = false });
  448. defer allocator.free(install_dir_string);
  449. var install_dir = std.fs.openIterableDirAbsolute(install_dir_string, .{}) catch |e| switch (e) {
  450. error.FileNotFound => return,
  451. else => return e,
  452. };
  453. defer install_dir.close();
  454. const stdout = std.io.getStdOut().writer();
  455. {
  456. var it = install_dir.iterate();
  457. while (try it.next()) |entry| {
  458. if (entry.kind != .directory)
  459. continue;
  460. if (std.mem.endsWith(u8, entry.name, ".installing"))
  461. continue;
  462. try stdout.print("{s}\n", .{entry.name});
  463. }
  464. }
  465. }
  466. fn keepCompiler(allocator: Allocator, compiler_version: []const u8) !void {
  467. const install_dir_string = try getInstallDir(allocator, .{ .create = true });
  468. defer allocator.free(install_dir_string);
  469. var install_dir = try std.fs.openIterableDirAbsolute(install_dir_string, .{});
  470. defer install_dir.close();
  471. var compiler_dir = install_dir.dir.openDir(compiler_version, .{}) catch |e| switch (e) {
  472. error.FileNotFound => {
  473. std.log.err("compiler not found: {s}", .{compiler_version});
  474. return error.AlreadyReported;
  475. },
  476. else => return e,
  477. };
  478. var keep_fd = try compiler_dir.createFile("keep", .{});
  479. keep_fd.close();
  480. loginfo("created '{s}{c}{s}{c}{s}'", .{ install_dir_string, std.fs.path.sep, compiler_version, std.fs.path.sep, "keep" });
  481. }
  482. fn cleanCompilers(allocator: Allocator, compiler_name_opt: ?[]const u8) !void {
  483. const install_dir_string = try getInstallDir(allocator, .{ .create = true });
  484. defer allocator.free(install_dir_string);
  485. // getting the current compiler
  486. const default_comp_opt = try getDefaultCompiler(allocator);
  487. defer if (default_comp_opt) |default_compiler| allocator.free(default_compiler);
  488. var install_dir = std.fs.openIterableDirAbsolute(install_dir_string, .{}) catch |e| switch (e) {
  489. error.FileNotFound => return,
  490. else => return e,
  491. };
  492. defer install_dir.close();
  493. const master_points_to_opt = try getMasterDir(allocator, &install_dir.dir);
  494. defer if (master_points_to_opt) |master_points_to| allocator.free(master_points_to);
  495. if (compiler_name_opt) |compiler_name| {
  496. if (getKeepReason(master_points_to_opt, default_comp_opt, compiler_name)) |reason| {
  497. std.log.err("cannot clean '{s}' ({s})", .{ compiler_name, reason });
  498. return error.AlreadyReported;
  499. }
  500. loginfo("deleting '{s}{c}{s}'", .{ install_dir_string, std.fs.path.sep, compiler_name });
  501. try fixdeletetree.deleteTree(install_dir.dir, compiler_name);
  502. } else {
  503. var it = install_dir.iterate();
  504. while (try it.next()) |entry| {
  505. if (entry.kind != .directory)
  506. continue;
  507. if (getKeepReason(master_points_to_opt, default_comp_opt, entry.name)) |reason| {
  508. loginfo("keeping '{s}' ({s})", .{ entry.name, reason });
  509. continue;
  510. }
  511. {
  512. var compiler_dir = try install_dir.dir.openDir(entry.name, .{});
  513. defer compiler_dir.close();
  514. if (compiler_dir.access("keep", .{})) |_| {
  515. loginfo("keeping '{s}' (has keep file)", .{entry.name});
  516. continue;
  517. } else |e| switch (e) {
  518. error.FileNotFound => {},
  519. else => return e,
  520. }
  521. }
  522. loginfo("deleting '{s}{c}{s}'", .{ install_dir_string, std.fs.path.sep, entry.name });
  523. try fixdeletetree.deleteTree(install_dir.dir, entry.name);
  524. }
  525. }
  526. }
  527. fn readDefaultCompiler(allocator: Allocator, buffer: *[std.fs.MAX_PATH_BYTES + 1]u8) !?[]const u8 {
  528. const path_link = try makeZigPathLinkString(allocator);
  529. defer allocator.free(path_link);
  530. if (builtin.os.tag == .windows) {
  531. var file = std.fs.openFileAbsolute(path_link, .{}) catch |e| switch (e) {
  532. error.FileNotFound => return null,
  533. else => return e,
  534. };
  535. defer file.close();
  536. try file.seekTo(win32exelink.exe_offset);
  537. const len = try file.readAll(buffer);
  538. if (len != buffer.len) {
  539. std.log.err("path link file '{s}' is too small", .{path_link});
  540. return error.AlreadyReported;
  541. }
  542. const target_exe = std.mem.sliceTo(buffer, 0);
  543. return try allocator.dupe(u8, targetPathToVersion(target_exe));
  544. }
  545. const target_path = std.fs.readLinkAbsolute(path_link, buffer[0..std.fs.MAX_PATH_BYTES]) catch |e| switch (e) {
  546. error.FileNotFound => return null,
  547. else => return e,
  548. };
  549. defer allocator.free(target_path);
  550. return try allocator.dupe(u8, targetPathToVersion(target_path));
  551. }
  552. fn targetPathToVersion(target_path: []const u8) []const u8 {
  553. return std.fs.path.basename(std.fs.path.dirname(std.fs.path.dirname(target_path).?).?);
  554. }
  555. fn readMasterDir(buffer: *[std.fs.MAX_PATH_BYTES]u8, install_dir: *std.fs.Dir) !?[]const u8 {
  556. if (builtin.os.tag == .windows) {
  557. var file = install_dir.openFile("master", .{}) catch |e| switch (e) {
  558. error.FileNotFound => return null,
  559. else => return e,
  560. };
  561. defer file.close();
  562. return buffer[0..try file.readAll(buffer)];
  563. }
  564. return install_dir.readLink("master", buffer) catch |e| switch (e) {
  565. error.FileNotFound => return null,
  566. else => return e,
  567. };
  568. }
  569. fn getDefaultCompiler(allocator: Allocator) !?[]const u8 {
  570. var buffer: [std.fs.MAX_PATH_BYTES + 1]u8 = undefined;
  571. const slice_path = (try readDefaultCompiler(allocator, &buffer)) orelse return null;
  572. var path_to_return = try allocator.alloc(u8, slice_path.len);
  573. std.mem.copy(u8, path_to_return, slice_path);
  574. return path_to_return;
  575. }
  576. fn getMasterDir(allocator: Allocator, install_dir: *std.fs.Dir) !?[]const u8 {
  577. var buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined;
  578. const slice_path = (try readMasterDir(&buffer, install_dir)) 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 printDefaultCompiler(allocator: Allocator) !void {
  584. const default_compiler_opt = try getDefaultCompiler(allocator);
  585. defer if (default_compiler_opt) |default_compiler| allocator.free(default_compiler);
  586. const stdout = std.io.getStdOut().writer();
  587. if (default_compiler_opt) |default_compiler| {
  588. try stdout.print("{s}\n", .{default_compiler});
  589. } else {
  590. try stdout.writeAll("<no-default>\n");
  591. }
  592. }
  593. const ExistVerify = enum { existence_verified, verify_existence };
  594. fn setDefaultCompiler(allocator: Allocator, compiler_dir: []const u8, exist_verify: ExistVerify) !void {
  595. switch (exist_verify) {
  596. .existence_verified => {},
  597. .verify_existence => {
  598. var dir = std.fs.openDirAbsolute(compiler_dir, .{}) catch |err| switch (err) {
  599. error.FileNotFound => {
  600. std.log.err("compiler '{s}' is not installed", .{std.fs.path.basename(compiler_dir)});
  601. return error.AlreadyReported;
  602. },
  603. else => |e| return e,
  604. };
  605. dir.close();
  606. },
  607. }
  608. const path_link = try makeZigPathLinkString(allocator);
  609. defer allocator.free(path_link);
  610. const link_target = try std.fs.path.join(allocator, &[_][]const u8{ compiler_dir, "files", comptime "zig" ++ builtin.target.exeFileExt() });
  611. defer allocator.free(link_target);
  612. if (builtin.os.tag == .windows) {
  613. try createExeLink(link_target, path_link);
  614. } else {
  615. _ = try loggyUpdateSymlink(link_target, path_link, .{});
  616. }
  617. try verifyPathLink(allocator, path_link);
  618. }
  619. /// Verify that path_link will work. It verifies that `path_link` is
  620. /// in PATH and there is no zig executable in an earlier directory in PATH.
  621. fn verifyPathLink(allocator: Allocator, path_link: []const u8) !void {
  622. const path_link_dir = std.fs.path.dirname(path_link) orelse {
  623. std.log.err("invalid '--path-link' '{s}', it must be a file (not the root directory)", .{path_link});
  624. return error.AlreadyReported;
  625. };
  626. const path_link_dir_id = blk: {
  627. var dir = std.fs.openDirAbsolute(path_link_dir, .{}) catch |err| {
  628. std.log.err("unable to open the path-link directory '{s}': {s}", .{ path_link_dir, @errorName(err) });
  629. return error.AlreadyReported;
  630. };
  631. defer dir.close();
  632. break :blk try FileId.initFromDir(dir, path_link);
  633. };
  634. if (builtin.os.tag == .windows) {
  635. const path_env = std.process.getEnvVarOwned(allocator, "PATH") catch |err| switch (err) {
  636. error.EnvironmentVariableNotFound => return,
  637. else => |e| return e,
  638. };
  639. defer allocator.free(path_env);
  640. var free_pathext: ?[]const u8 = null;
  641. defer if (free_pathext) |p| allocator.free(p);
  642. const pathext_env = blk: {
  643. if (std.process.getEnvVarOwned(allocator, "PATHEXT")) |env| {
  644. free_pathext = env;
  645. break :blk env;
  646. } else |err| switch (err) {
  647. error.EnvironmentVariableNotFound => break :blk "",
  648. else => |e| return e,
  649. }
  650. break :blk "";
  651. };
  652. var path_it = std.mem.tokenize(u8, path_env, ";");
  653. while (path_it.next()) |path| {
  654. switch (try compareDir(path_link_dir_id, path)) {
  655. .missing => continue,
  656. .match => return,
  657. .mismatch => {},
  658. }
  659. {
  660. const exe = try std.fs.path.join(allocator, &.{ path, "zig" });
  661. defer allocator.free(exe);
  662. try enforceNoZig(path_link, exe);
  663. }
  664. var ext_it = std.mem.tokenize(u8, pathext_env, ";");
  665. while (ext_it.next()) |ext| {
  666. if (ext.len == 0) continue;
  667. const basename = try std.mem.concat(allocator, u8, &.{ "zig", ext });
  668. defer allocator.free(basename);
  669. const exe = try std.fs.path.join(allocator, &.{ path, basename });
  670. defer allocator.free(exe);
  671. try enforceNoZig(path_link, exe);
  672. }
  673. }
  674. } else {
  675. var path_it = std.mem.tokenize(u8, std.os.getenv("PATH") orelse "", ":");
  676. while (path_it.next()) |path| {
  677. switch (try compareDir(path_link_dir_id, path)) {
  678. .missing => continue,
  679. .match => return,
  680. .mismatch => {},
  681. }
  682. const exe = try std.fs.path.join(allocator, &.{ path, "zig" });
  683. defer allocator.free(exe);
  684. try enforceNoZig(path_link, exe);
  685. }
  686. }
  687. std.log.err("the path link '{s}' is not in PATH", .{path_link});
  688. return error.AlreadyReported;
  689. }
  690. fn compareDir(dir_id: FileId, other_dir: []const u8) !enum { missing, match, mismatch } {
  691. var dir = std.fs.cwd().openDir(other_dir, .{}) catch |err| switch (err) {
  692. error.FileNotFound, error.NotDir, error.BadPathName => return .missing,
  693. else => |e| return e,
  694. };
  695. defer dir.close();
  696. return if (dir_id.eql(try FileId.initFromDir(dir, other_dir))) .match else .mismatch;
  697. }
  698. fn enforceNoZig(path_link: []const u8, exe: []const u8) !void {
  699. var file = std.fs.cwd().openFile(exe, .{}) catch |err| switch (err) {
  700. error.FileNotFound, error.IsDir => return,
  701. else => |e| return e,
  702. };
  703. defer file.close();
  704. // todo: on posix systems ignore the file if it is not executable
  705. std.log.err("zig compiler '{s}' is higher priority in PATH than the path-link '{s}'", .{ exe, path_link });
  706. }
  707. const FileId = struct {
  708. dev: if (builtin.os.tag == .windows) u32 else blk: {
  709. var st: std.os.Stat = undefined;
  710. break :blk @TypeOf(st.dev);
  711. },
  712. ino: if (builtin.os.tag == .windows) u64 else blk: {
  713. var st: std.os.Stat = undefined;
  714. break :blk @TypeOf(st.ino);
  715. },
  716. pub fn initFromFile(file: std.fs.File, filename_for_error: []const u8) !FileId {
  717. if (builtin.os.tag == .windows) {
  718. var info: win32.BY_HANDLE_FILE_INFORMATION = undefined;
  719. if (0 == win32.GetFileInformationByHandle(file.handle, &info)) {
  720. std.log.err("GetFileInformationByHandle on '{s}' failed, error={}", .{ filename_for_error, std.os.windows.kernel32.GetLastError() });
  721. return error.AlreadyReported;
  722. }
  723. return FileId{
  724. .dev = info.dwVolumeSerialNumber,
  725. .ino = (@as(u64, @intCast(info.nFileIndexHigh)) << 32) | @as(u64, @intCast(info.nFileIndexLow)),
  726. };
  727. }
  728. const st = try std.os.fstat(file.handle);
  729. return FileId{
  730. .dev = st.dev,
  731. .ino = st.ino,
  732. };
  733. }
  734. pub fn initFromDir(dir: std.fs.Dir, name_for_error: []const u8) !FileId {
  735. if (builtin.os.tag == .windows) {
  736. return initFromFile(std.fs.File{ .handle = dir.fd }, name_for_error);
  737. }
  738. return initFromFile(std.fs.File{ .handle = dir.fd }, name_for_error);
  739. }
  740. pub fn eql(self: FileId, other: FileId) bool {
  741. return self.dev == other.dev and self.ino == other.ino;
  742. }
  743. };
  744. const win32 = struct {
  745. pub const BOOL = i32;
  746. pub const FILETIME = extern struct {
  747. dwLowDateTime: u32,
  748. dwHighDateTime: u32,
  749. };
  750. pub const BY_HANDLE_FILE_INFORMATION = extern struct {
  751. dwFileAttributes: u32,
  752. ftCreationTime: FILETIME,
  753. ftLastAccessTime: FILETIME,
  754. ftLastWriteTime: FILETIME,
  755. dwVolumeSerialNumber: u32,
  756. nFileSizeHigh: u32,
  757. nFileSizeLow: u32,
  758. nNumberOfLinks: u32,
  759. nFileIndexHigh: u32,
  760. nFileIndexLow: u32,
  761. };
  762. pub extern "kernel32" fn GetFileInformationByHandle(
  763. hFile: ?@import("std").os.windows.HANDLE,
  764. lpFileInformation: ?*BY_HANDLE_FILE_INFORMATION,
  765. ) callconv(@import("std").os.windows.WINAPI) BOOL;
  766. };
  767. const win32exelink = struct {
  768. const content = @embedFile("win32exelink");
  769. const exe_offset: usize = if (builtin.os.tag != .windows) 0 else blk: {
  770. @setEvalBranchQuota(content.len * 2);
  771. const marker = "!!!THIS MARKS THE zig_exe_string MEMORY!!#";
  772. const offset = std.mem.indexOf(u8, content, marker) orelse {
  773. @compileError("win32exelink is missing the marker: " ++ marker);
  774. };
  775. if (std.mem.indexOf(u8, content[offset + 1 ..], marker) != null) {
  776. @compileError("win32exelink contains multiple markers (not implemented)");
  777. }
  778. break :blk offset + marker.len;
  779. };
  780. };
  781. fn createExeLink(link_target: []const u8, path_link: []const u8) !void {
  782. if (path_link.len > std.fs.MAX_PATH_BYTES) {
  783. std.debug.print("Error: path_link (size {}) is too large (max {})\n", .{ path_link.len, std.fs.MAX_PATH_BYTES });
  784. return error.AlreadyReported;
  785. }
  786. const file = try std.fs.cwd().createFile(path_link, .{});
  787. defer file.close();
  788. try file.writer().writeAll(win32exelink.content[0..win32exelink.exe_offset]);
  789. try file.writer().writeAll(link_target);
  790. try file.writer().writeAll(win32exelink.content[win32exelink.exe_offset + link_target.len ..]);
  791. }
  792. const VersionKind = enum { release, dev };
  793. fn determineVersionKind(version: []const u8) VersionKind {
  794. return if (std.mem.indexOfAny(u8, version, "-+")) |_| .dev else .release;
  795. }
  796. fn getDefaultUrl(allocator: Allocator, compiler_version: []const u8) ![]const u8 {
  797. return switch (determineVersionKind(compiler_version)) {
  798. .dev => try std.fmt.allocPrint(allocator, "https://ziglang.org/builds/zig-" ++ url_platform ++ "-{0s}." ++ archive_ext, .{compiler_version}),
  799. .release => try std.fmt.allocPrint(allocator, "https://ziglang.org/download/{s}/zig-" ++ url_platform ++ "-{0s}." ++ archive_ext, .{compiler_version}),
  800. };
  801. }
  802. fn installCompiler(allocator: Allocator, compiler_dir: []const u8, url: []const u8) !void {
  803. if (try existsAbsolute(compiler_dir)) {
  804. loginfo("compiler '{s}' already installed", .{compiler_dir});
  805. return;
  806. }
  807. const installing_dir = try std.mem.concat(allocator, u8, &[_][]const u8{ compiler_dir, ".installing" });
  808. defer allocator.free(installing_dir);
  809. try loggyDeleteTreeAbsolute(installing_dir);
  810. try loggyMakeDirAbsolute(installing_dir);
  811. const archive_basename = std.fs.path.basename(url);
  812. var archive_root_dir: []const u8 = undefined;
  813. // download and extract archive
  814. {
  815. const archive_absolute = try std.fs.path.join(allocator, &[_][]const u8{ installing_dir, archive_basename });
  816. defer allocator.free(archive_absolute);
  817. loginfo("downloading '{s}' to '{s}'", .{ url, archive_absolute });
  818. downloadToFileAbsolute(allocator, url, archive_absolute) catch |e| switch (e) {
  819. error.HttpNon200StatusCode => {
  820. // TODO: more information would be good
  821. std.log.err("HTTP request failed (TODO: improve ziget library to get better error)", .{});
  822. // this removes the installing dir if the http request fails so we dont have random directories
  823. try loggyDeleteTreeAbsolute(installing_dir);
  824. return error.AlreadyReported;
  825. },
  826. else => return e,
  827. };
  828. if (std.mem.endsWith(u8, archive_basename, ".tar.xz")) {
  829. archive_root_dir = archive_basename[0 .. archive_basename.len - ".tar.xz".len];
  830. _ = try run(allocator, &[_][]const u8{ "tar", "xf", archive_absolute, "-C", installing_dir });
  831. } else {
  832. var recognized = false;
  833. if (builtin.os.tag == .windows) {
  834. if (std.mem.endsWith(u8, archive_basename, ".zip")) {
  835. recognized = true;
  836. archive_root_dir = archive_basename[0 .. archive_basename.len - ".zip".len];
  837. var installing_dir_opened = try std.fs.openDirAbsolute(installing_dir, .{});
  838. defer installing_dir_opened.close();
  839. loginfo("extracting archive to \"{s}\"", .{installing_dir});
  840. var timer = try std.time.Timer.start();
  841. var archive_file = try std.fs.openFileAbsolute(archive_absolute, .{});
  842. defer archive_file.close();
  843. const reader = archive_file.reader();
  844. var archive = try zarc.zip.load(allocator, reader);
  845. defer archive.deinit(allocator);
  846. _ = try archive.extract(reader, installing_dir_opened, .{});
  847. const time = timer.read();
  848. loginfo("extracted archive in {d:.2} s", .{@as(f32, @floatFromInt(time)) / @as(f32, @floatFromInt(std.time.ns_per_s))});
  849. }
  850. }
  851. if (!recognized) {
  852. std.log.err("unknown archive extension '{s}'", .{archive_basename});
  853. return error.UnknownArchiveExtension;
  854. }
  855. }
  856. try loggyDeleteTreeAbsolute(archive_absolute);
  857. }
  858. {
  859. const extracted_dir = try std.fs.path.join(allocator, &[_][]const u8{ installing_dir, archive_root_dir });
  860. defer allocator.free(extracted_dir);
  861. const normalized_dir = try std.fs.path.join(allocator, &[_][]const u8{ installing_dir, "files" });
  862. defer allocator.free(normalized_dir);
  863. try loggyRenameAbsolute(extracted_dir, normalized_dir);
  864. }
  865. // TODO: write date information (so users can sort compilers by date)
  866. // finish installation by renaming the install dir
  867. try loggyRenameAbsolute(installing_dir, compiler_dir);
  868. }
  869. pub fn run(allocator: Allocator, argv: []const []const u8) !std.ChildProcess.Term {
  870. try logRun(allocator, argv);
  871. var proc = std.ChildProcess.init(argv, allocator);
  872. return proc.spawnAndWait();
  873. }
  874. fn logRun(allocator: Allocator, argv: []const []const u8) !void {
  875. var buffer = try allocator.alloc(u8, getCommandStringLength(argv));
  876. defer allocator.free(buffer);
  877. var prefix = false;
  878. var offset: usize = 0;
  879. for (argv) |arg| {
  880. if (prefix) {
  881. buffer[offset] = ' ';
  882. offset += 1;
  883. } else {
  884. prefix = true;
  885. }
  886. std.mem.copy(u8, buffer[offset .. offset + arg.len], arg);
  887. offset += arg.len;
  888. }
  889. std.debug.assert(offset == buffer.len);
  890. loginfo("[RUN] {s}", .{buffer});
  891. }
  892. pub fn getCommandStringLength(argv: []const []const u8) usize {
  893. var len: usize = 0;
  894. var prefix_length: u8 = 0;
  895. for (argv) |arg| {
  896. len += prefix_length + arg.len;
  897. prefix_length = 1;
  898. }
  899. return len;
  900. }
  901. pub fn getKeepReason(master_points_to_opt: ?[]const u8, default_compiler_opt: ?[]const u8, name: []const u8) ?[]const u8 {
  902. if (default_compiler_opt) |default_comp| {
  903. if (mem.eql(u8, default_comp, name)) {
  904. return "is default compiler";
  905. }
  906. }
  907. if (master_points_to_opt) |master_points_to| {
  908. if (mem.eql(u8, master_points_to, name)) {
  909. return "it is master";
  910. }
  911. }
  912. return null;
  913. }