zigup.zig 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  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, "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", "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. (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. }).close();
  607. },
  608. }
  609. const path_link = try makeZigPathLinkString(allocator);
  610. defer allocator.free(path_link);
  611. try verifyPathLink(allocator, path_link);
  612. const link_target = try std.fs.path.join(allocator, &[_][]const u8{ compiler_dir, "files", "zig" ++ builtin.target.exeFileExt() });
  613. defer allocator.free(link_target);
  614. if (builtin.os.tag == .windows) {
  615. try createExeLink(link_target, path_link);
  616. } else {
  617. _ = try loggyUpdateSymlink(link_target, path_link, .{});
  618. }
  619. }
  620. /// Verify that path_link will work. It verifies that `path_link` is
  621. /// in PATH and there is no zig executable in an earlier directory in PATH.
  622. fn verifyPathLink(allocator: Allocator, path_link: []const u8) !void {
  623. const path_link_dir = std.fs.path.dirname(path_link) orelse {
  624. std.log.err("invalid '--path-link' '{s}', it must be a file (not the root directory)", .{path_link});
  625. return error.AlreadyReported;
  626. };
  627. const path_link_dir_id = blk: {
  628. var dir = std.fs.openDirAbsolute(path_link_dir, .{}) catch |err| {
  629. std.log.err("unable to open the path-link directory '{s}': {s}", .{path_link_dir, @errorName(err)});
  630. return error.AlreadyReported;
  631. };
  632. defer dir.close();
  633. break :blk try FileId.initFromDir(dir, path_link);
  634. };
  635. if (builtin.os.tag == .windows) {
  636. const path_env = std.process.getEnvVarOwned(allocator, "PATH") catch |err| switch (err) {
  637. error.EnvironmentVariableNotFound => return,
  638. else => |e| return e,
  639. };
  640. defer allocator.free(path_env);
  641. var free_pathext: ?[]const u8 = null;
  642. defer if (free_pathext) |p| allocator.free(p);
  643. const pathext_env = blk: {
  644. if (std.process.getEnvVarOwned(allocator, "PATHEXT")) |env| {
  645. free_pathext = env;
  646. break :blk env;
  647. } else |err| switch (err) {
  648. error.EnvironmentVariableNotFound => break :blk "",
  649. else => |e| return e,
  650. }
  651. break :blk "";
  652. };
  653. var path_it = std.mem.tokenize(u8, path_env, ";");
  654. while (path_it.next()) |path| {
  655. switch (try compareDir(path_link_dir_id, path)) {
  656. .missing => continue,
  657. .match => return,
  658. .mismatch => {},
  659. }
  660. {
  661. const exe = try std.fs.path.join(allocator, &.{ path, "zig" });
  662. defer allocator.free(exe);
  663. try enforceNoZig(path_link, exe);
  664. }
  665. var ext_it = std.mem.tokenize(u8, pathext_env, ";");
  666. while (ext_it.next()) |ext| {
  667. if (ext.len == 0) continue;
  668. const basename = try std.mem.concat(allocator, u8, &.{"zig", ext});
  669. defer allocator.free(basename);
  670. const exe = try std.fs.path.join(allocator, &.{path, basename});
  671. defer allocator.free(exe);
  672. try enforceNoZig(path_link, exe);
  673. }
  674. }
  675. } else {
  676. var path_it = std.mem.tokenize(u8, std.os.getenv("PATH") orelse "", ":");
  677. while (path_it.next()) |path| {
  678. switch (try compareDir(path_link_dir_id, path)) {
  679. .missing => continue,
  680. .match => return,
  681. .mismatch => {},
  682. }
  683. const exe = try std.fs.path.join(allocator, &.{ path, "zig" });
  684. defer allocator.free(exe);
  685. try enforceNoZig(path_link, exe);
  686. }
  687. }
  688. std.log.err("the path link '{s}' is not in PATH", .{path_link});
  689. return error.AlreadyReported;
  690. }
  691. fn compareDir(dir_id: FileId, other_dir: []const u8) !enum { missing, match, mismatch } {
  692. var dir = std.fs.cwd().openDir(other_dir, .{}) catch |err| switch (err) {
  693. error.FileNotFound, error.NotDir, error.BadPathName => return .missing,
  694. else => |e| return e,
  695. };
  696. defer dir.close();
  697. return if (dir_id.eql(try FileId.initFromDir(dir, other_dir))) .match else .mismatch;
  698. }
  699. fn enforceNoZig(path_link: []const u8, exe: []const u8) !void {
  700. var file = std.fs.cwd().openFile(exe, .{}) catch |err| switch (err) {
  701. error.FileNotFound, error.IsDir => return,
  702. else => |e| return e,
  703. };
  704. defer file.close();
  705. // todo: on posix systems ignore the file if it is not executable
  706. std.log.err("path-link '{s}' is lower priority in PATH than '{s}'", .{path_link, exe});
  707. return error.AlreadyReported;
  708. }
  709. const FileId = struct {
  710. dev: if (builtin.os.tag == .windows) u32 else blk: {
  711. var st: std.os.Stat = undefined;
  712. break :blk @TypeOf(st.dev);
  713. },
  714. ino: if (builtin.os.tag == .windows) u64 else blk: {
  715. var st: std.os.Stat = undefined;
  716. break :blk @TypeOf(st.ino);
  717. },
  718. pub fn initFromFile(file: std.fs.File, filename_for_error: []const u8) !FileId {
  719. if (builtin.os.tag == .windows) {
  720. var info: win32.BY_HANDLE_FILE_INFORMATION = undefined;
  721. if (0 == win32.GetFileInformationByHandle(file.handle, &info)) {
  722. std.log.err("GetFileInformationByHandle on '{s}' failed, error={}", .{filename_for_error, std.os.windows.kernel32.GetLastError()});
  723. return error.AlreadyReported;
  724. }
  725. return FileId{
  726. .dev = info.dwVolumeSerialNumber,
  727. .ino = (@intCast(u64, info.nFileIndexHigh) << 32) | @intCast(u64, info.nFileIndexLow),
  728. };
  729. }
  730. const st = try std.os.fstat(file.handle);
  731. return FileId{
  732. .dev = st.dev,
  733. .ino = st.ino,
  734. };
  735. }
  736. pub fn initFromDir(dir: std.fs.Dir, name_for_error: []const u8) !FileId {
  737. if (builtin.os.tag == .windows) {
  738. return initFromFile(std.fs.File { .handle = dir.fd}, name_for_error);
  739. }
  740. return initFromFile(std.fs.File { .handle = dir.fd }, name_for_error);
  741. }
  742. pub fn eql(self: FileId, other: FileId) bool {
  743. return self.dev == other.dev and self.ino == other.ino;
  744. }
  745. };
  746. const win32 = struct {
  747. pub const BOOL = i32;
  748. pub const FILETIME = extern struct {
  749. dwLowDateTime: u32,
  750. dwHighDateTime: u32,
  751. };
  752. pub const BY_HANDLE_FILE_INFORMATION = extern struct {
  753. dwFileAttributes: u32,
  754. ftCreationTime: FILETIME,
  755. ftLastAccessTime: FILETIME,
  756. ftLastWriteTime: FILETIME,
  757. dwVolumeSerialNumber: u32,
  758. nFileSizeHigh: u32,
  759. nFileSizeLow: u32,
  760. nNumberOfLinks: u32,
  761. nFileIndexHigh: u32,
  762. nFileIndexLow: u32,
  763. };
  764. pub extern "KERNEL32" fn GetFileInformationByHandle(
  765. hFile: ?@import("std").os.windows.HANDLE,
  766. lpFileInformation: ?*BY_HANDLE_FILE_INFORMATION,
  767. ) callconv(@import("std").os.windows.WINAPI) BOOL;
  768. };
  769. const win32exelink = struct {
  770. const content = @embedFile(build_options.win32exelink_filename);
  771. const exe_offset: usize = if (builtin.os.tag != .windows) 0 else blk: {
  772. @setEvalBranchQuota(content.len * 2);
  773. const marker = "!!!THIS MARKS THE zig_exe_string MEMORY!!#";
  774. const offset = std.mem.indexOf(u8, content, marker) orelse {
  775. @compileError("win32exelink is missing the marker: " ++ marker);
  776. };
  777. if (std.mem.indexOf(u8, content[offset + 1 ..], marker) != null) {
  778. @compileError("win32exelink contains multiple markers (not implemented)");
  779. }
  780. break :blk offset + marker.len;
  781. };
  782. };
  783. fn createExeLink(link_target: []const u8, path_link: []const u8) !void {
  784. if (path_link.len > std.fs.MAX_PATH_BYTES) {
  785. std.debug.print("Error: path_link (size {}) is too large (max {})\n", .{path_link.len, std.fs.MAX_PATH_BYTES});
  786. return error.AlreadyReported;
  787. }
  788. const file = try std.fs.cwd().createFile(path_link, .{});
  789. defer file.close();
  790. try file.writer().writeAll(win32exelink.content[0 .. win32exelink.exe_offset]);
  791. try file.writer().writeAll(link_target);
  792. try file.writer().writeAll(win32exelink.content[win32exelink.exe_offset + link_target.len ..]);
  793. }
  794. const VersionKind = enum { release, dev };
  795. fn determineVersionKind(version: []const u8) VersionKind {
  796. return if (std.mem.indexOfAny(u8, version, "-+")) |_| .dev else .release;
  797. }
  798. fn getDefaultUrl(allocator: Allocator, compiler_version: []const u8) ![]const u8 {
  799. return switch (determineVersionKind(compiler_version)) {
  800. .dev => try std.fmt.allocPrint(allocator, "https://ziglang.org/builds/zig-" ++ url_platform ++ "-{0s}." ++ archive_ext, .{ compiler_version }),
  801. .release => try std.fmt.allocPrint(allocator, "https://ziglang.org/download/{s}/zig-" ++ url_platform ++ "-{0s}." ++ archive_ext, .{ compiler_version }),
  802. };
  803. }
  804. fn installCompiler(allocator: Allocator, compiler_dir: []const u8, url: []const u8) !void {
  805. if (try existsAbsolute(compiler_dir)) {
  806. loginfo("compiler '{s}' already installed", .{compiler_dir});
  807. return;
  808. }
  809. const installing_dir = try std.mem.concat(allocator, u8, &[_][]const u8{ compiler_dir, ".installing" });
  810. defer allocator.free(installing_dir);
  811. try loggyDeleteTreeAbsolute(installing_dir);
  812. try loggyMakeDirAbsolute(installing_dir);
  813. const archive_basename = std.fs.path.basename(url);
  814. var archive_root_dir: []const u8 = undefined;
  815. // download and extract archive
  816. {
  817. const archive_absolute = try std.fs.path.join(allocator, &[_][]const u8{ installing_dir, archive_basename });
  818. defer allocator.free(archive_absolute);
  819. loginfo("downloading '{s}' to '{s}'", .{ url, archive_absolute });
  820. downloadToFileAbsolute(allocator, url, archive_absolute) catch |e| switch (e) {
  821. error.HttpNon200StatusCode => {
  822. // TODO: more information would be good
  823. std.log.err("HTTP request failed (TODO: improve ziget library to get better error)", .{});
  824. // this removes the installing dir if the http request fails so we dont have random directories
  825. try loggyDeleteTreeAbsolute(installing_dir);
  826. return error.AlreadyReported;
  827. },
  828. else => return e,
  829. };
  830. if (std.mem.endsWith(u8, archive_basename, ".tar.xz")) {
  831. archive_root_dir = archive_basename[0 .. archive_basename.len - ".tar.xz".len];
  832. _ = try run(allocator, &[_][]const u8{ "tar", "xf", archive_absolute, "-C", installing_dir });
  833. } else {
  834. var recognized = false;
  835. if (builtin.os.tag == .windows) {
  836. if (std.mem.endsWith(u8, archive_basename, ".zip")) {
  837. recognized = true;
  838. archive_root_dir = archive_basename[0 .. archive_basename.len - ".zip".len];
  839. var installing_dir_opened = try std.fs.openDirAbsolute(installing_dir, .{});
  840. defer installing_dir_opened.close();
  841. loginfo("extracting archive to \"{s}\"", .{installing_dir});
  842. var timer = try std.time.Timer.start();
  843. var archive_file = try std.fs.openFileAbsolute(archive_absolute, .{});
  844. defer archive_file.close();
  845. const reader = archive_file.reader();
  846. var archive = try zarc.zip.load(allocator, reader);
  847. defer archive.deinit(allocator);
  848. _ = try archive.extract(reader, installing_dir_opened, .{});
  849. const time = timer.read();
  850. loginfo("extracted archive in {d:.2} s", .{@intToFloat(f32, time) / @intToFloat(f32, std.time.ns_per_s)});
  851. }
  852. }
  853. if (!recognized) {
  854. std.log.err("unknown archive extension '{s}'", .{archive_basename});
  855. return error.UnknownArchiveExtension;
  856. }
  857. }
  858. try loggyDeleteTreeAbsolute(archive_absolute);
  859. }
  860. {
  861. const extracted_dir = try std.fs.path.join(allocator, &[_][]const u8{ installing_dir, archive_root_dir });
  862. defer allocator.free(extracted_dir);
  863. const normalized_dir = try std.fs.path.join(allocator, &[_][]const u8{ installing_dir, "files" });
  864. defer allocator.free(normalized_dir);
  865. try loggyRenameAbsolute(extracted_dir, normalized_dir);
  866. }
  867. // TODO: write date information (so users can sort compilers by date)
  868. // finish installation by renaming the install dir
  869. try loggyRenameAbsolute(installing_dir, compiler_dir);
  870. }
  871. pub fn run(allocator: Allocator, argv: []const []const u8) !std.ChildProcess.Term {
  872. try logRun(allocator, argv);
  873. var proc = std.ChildProcess.init(argv, allocator);
  874. return proc.spawnAndWait();
  875. }
  876. fn logRun(allocator: Allocator, argv: []const []const u8) !void {
  877. var buffer = try allocator.alloc(u8, getCommandStringLength(argv));
  878. defer allocator.free(buffer);
  879. var prefix = false;
  880. var offset: usize = 0;
  881. for (argv) |arg| {
  882. if (prefix) {
  883. buffer[offset] = ' ';
  884. offset += 1;
  885. } else {
  886. prefix = true;
  887. }
  888. std.mem.copy(u8, buffer[offset .. offset + arg.len], arg);
  889. offset += arg.len;
  890. }
  891. std.debug.assert(offset == buffer.len);
  892. loginfo("[RUN] {s}", .{buffer});
  893. }
  894. pub fn getCommandStringLength(argv: []const []const u8) usize {
  895. var len: usize = 0;
  896. var prefix_length: u8 = 0;
  897. for (argv) |arg| {
  898. len += prefix_length + arg.len;
  899. prefix_length = 1;
  900. }
  901. return len;
  902. }
  903. pub fn getKeepReason(master_points_to_opt: ?[]const u8, default_compiler_opt: ?[]const u8, name: []const u8) ?[]const u8 {
  904. if (default_compiler_opt) |default_comp| {
  905. if (mem.eql(u8, default_comp, name)) {
  906. return "is default compiler";
  907. }
  908. }
  909. if (master_points_to_opt) |master_points_to| {
  910. if (mem.eql(u8, master_points_to, name)) {
  911. return "it is master";
  912. }
  913. }
  914. return null;
  915. }