zigup.zig 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  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 fixdeletetree = @import("fixdeletetree.zig");
  8. const arch = switch(builtin.cpu.arch) {
  9. .x86_64 => "x86_64",
  10. .aarch64 => "aarch64",
  11. else => @compileError("Unsupported CPU Architecture"),
  12. };
  13. const os = switch(builtin.os.tag) {
  14. .windows => "windows",
  15. .linux => "linux",
  16. .macos => "macos",
  17. else => @compileError("Unsupported OS"),
  18. };
  19. const url_platform = os ++ "-" ++ arch;
  20. const json_platform = arch ++ "-" ++ os;
  21. const archive_ext = if (builtin.os.tag == .windows) "zip" else "tar.xz";
  22. var global_optional_install_dir: ?[]const u8 = null;
  23. var global_optional_path_link: ?[]const u8 = null;
  24. //fn find_zigs(allocator: *Allocator) !?[][]u8 {
  25. // // don't worry about free for now, this is a short lived program
  26. //
  27. // if (builtin.os.tag == .windows) {
  28. // @panic("windows not implemented");
  29. // //const result = try runGetOutput(allocator, .{"where", "-a", "zig"});
  30. // } else {
  31. // const which_result = try cmdlinetool.runGetOutput(allocator, .{ "which", "zig" });
  32. // if (runutil.runFailed(&which_result)) {
  33. // return null;
  34. // }
  35. // if (which_result.stderr.len > 0) {
  36. // std.debug.print("which command failed with:\n{s}\n", .{which_result.stderr});
  37. // std.os.exit(1);
  38. // }
  39. // std.debug.print("which output:\n{s}\n", .{which_result.stdout});
  40. // {
  41. // var i = std.mem.split(which_result.stdout, "\n");
  42. // while (i.next()) |dir| {
  43. // std.debug.print("path '{s}'\n", .{dir});
  44. // }
  45. // }
  46. // }
  47. // @panic("not impl");
  48. //}
  49. fn download(allocator: *Allocator, url: []const u8, writer: anytype) !void {
  50. var download_options = ziget.request.DownloadOptions{
  51. .flags = 0,
  52. .allocator = allocator,
  53. .maxRedirects = 10,
  54. .forwardBufferSize = 4096,
  55. .maxHttpResponseHeaders = 8192,
  56. .onHttpRequest = ignoreHttpCallback,
  57. .onHttpResponse = ignoreHttpCallback,
  58. };
  59. var dowload_state = ziget.request.DownloadState.init();
  60. try ziget.request.download(
  61. ziget.url.parseUrl(url) catch unreachable,
  62. writer,
  63. download_options,
  64. &dowload_state,
  65. );
  66. }
  67. fn downloadToFileAbsolute(allocator: *Allocator, url: []const u8, file_absolute: []const u8) !void {
  68. const file = try std.fs.createFileAbsolute(file_absolute, .{});
  69. defer file.close();
  70. try download(allocator, url, file.writer());
  71. }
  72. fn downloadToString(allocator: *Allocator, url: []const u8) ![]u8 {
  73. var response_array_list = try ArrayList(u8).initCapacity(allocator, 20 * 1024); // 20 KB (modify if response is expected to be bigger)
  74. errdefer response_array_list.deinit();
  75. try download(allocator, url, response_array_list.writer());
  76. return response_array_list.toOwnedSlice();
  77. }
  78. fn ignoreHttpCallback(request: []const u8) void { _ = request; }
  79. fn getHomeDir() ![]const u8 {
  80. if (builtin.os.tag == .windows) {
  81. // TODO: replace with something else
  82. return "C:\\tools";
  83. }
  84. return std.os.getenv("HOME") orelse {
  85. std.debug.print("Error: cannot find install directory, $HOME environment variable is not set\n", .{});
  86. return error.MissingHomeEnvironmentVariable;
  87. };
  88. }
  89. fn allocInstallDirString(allocator: *Allocator) ![]const u8 {
  90. // TODO: maybe support ZIG_INSTALL_DIR environment variable?
  91. // TODO: maybe support a file on the filesystem to configure install dir?
  92. const home = try getHomeDir();
  93. if (!std.fs.path.isAbsolute(home)) {
  94. std.debug.print("Error: $HOME environment variable '{s}' is not an absolute path\n", .{home});
  95. return error.BadHomeEnvironmentVariable;
  96. }
  97. return std.fs.path.join(allocator, &[_][]const u8{ home, "zig" });
  98. }
  99. const GetInstallDirOptions = struct {
  100. create: bool,
  101. };
  102. fn getInstallDir(allocator: *Allocator, options: GetInstallDirOptions) ![]const u8 {
  103. var optional_dir_to_free_on_error: ?[]const u8 = null;
  104. errdefer if (optional_dir_to_free_on_error) |dir| allocator.free(dir);
  105. const install_dir = init: {
  106. if (global_optional_install_dir) |dir| break :init dir;
  107. optional_dir_to_free_on_error = try allocInstallDirString(allocator);
  108. break :init optional_dir_to_free_on_error.?;
  109. };
  110. std.debug.assert(std.fs.path.isAbsolute(install_dir));
  111. std.debug.print("install directory '{s}'\n", .{install_dir});
  112. if (options.create) {
  113. loggyMakeDirAbsolute(install_dir) catch |e| switch (e) {
  114. error.PathAlreadyExists => {},
  115. else => return e,
  116. };
  117. }
  118. return install_dir;
  119. }
  120. fn makeZigPathLinkString(allocator: *Allocator) ![]const u8 {
  121. if (global_optional_path_link) |path| return path;
  122. // for now we're just going to hardcode the path to $HOME/bin/zig
  123. const home = try getHomeDir();
  124. if (builtin.os.tag == .windows) {
  125. return try std.fs.path.join(allocator, &[_][]const u8{ home, "zig.bat" });
  126. }
  127. return try std.fs.path.join(allocator, &[_][]const u8{ home, "bin", "zig" });
  128. }
  129. // TODO: this should be in standard lib
  130. fn toAbsolute(allocator: *Allocator, path: []const u8) ![]u8 {
  131. std.debug.assert(!std.fs.path.isAbsolute(path));
  132. const cwd = try std.process.getCwdAlloc(allocator);
  133. defer allocator.free(cwd);
  134. return std.fs.path.join(allocator, &[_][]const u8{ cwd, path });
  135. }
  136. fn help() void {
  137. std.io.getStdErr().writeAll(
  138. \\Download and manage zig compilers.
  139. \\
  140. \\Common Usage:
  141. \\
  142. \\ zigup VERSION download and set VERSION compiler as default
  143. \\ zigup fetch VERSION download VERSION compiler
  144. \\ zigup default [VERSION] get or set the default compiler
  145. \\ zigup clean [VERSION] deletes the given compiler version, otherwise, cleans all compilers
  146. \\ that aren't the default, master, or marked to keep.
  147. \\ zigup keep VERSION mark a compiler to be kept during clean
  148. \\
  149. \\Uncommon Usage:
  150. \\
  151. \\ zigup fetch-index download and print the download index json
  152. \\
  153. \\Common Options:
  154. \\ --install-dir DIR override the default install location
  155. \\ --path-link PATH path to the `zig` symlink that points to the default compiler
  156. \\ this will typically be a file path within a PATH directory so
  157. \\ that the user can just run `zig`
  158. \\
  159. ) catch unreachable;
  160. }
  161. fn getCmdOpt(args: [][]const u8, i: *usize) ![]const u8 {
  162. i.* += 1;
  163. if (i.* == args.len) {
  164. std.debug.print("Error: option '{s}' requires an argument\n", .{args[i.* - 1]});
  165. return error.AlreadyReported;
  166. }
  167. return args[i.*];
  168. }
  169. pub fn main() !u8 {
  170. return main2() catch |e| switch (e) {
  171. error.AlreadyReported => return 1,
  172. else => return e,
  173. };
  174. }
  175. pub fn main2() !u8 {
  176. if (builtin.os.tag == .windows) {
  177. _ = try std.os.windows.WSAStartup(2, 2);
  178. }
  179. var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
  180. const allocator = &arena.allocator;
  181. const args_array = try std.process.argsAlloc(allocator);
  182. // no need to free, os will do it
  183. //defer std.process.argsFree(allocator, argsArray);
  184. var args = if (args_array.len == 0) args_array else args_array[1..];
  185. // parse common options
  186. //
  187. {
  188. var i: usize = 0;
  189. var newlen: usize = 0;
  190. while (i < args.len) : (i += 1) {
  191. const arg = args[i];
  192. if (std.mem.eql(u8, "--install-dir", arg)) {
  193. global_optional_install_dir = try getCmdOpt(args, &i);
  194. if (!std.fs.path.isAbsolute(global_optional_install_dir.?)) {
  195. global_optional_install_dir = try toAbsolute(allocator, global_optional_install_dir.?);
  196. }
  197. } else if (std.mem.eql(u8, "--path-link", arg)) {
  198. global_optional_path_link = try getCmdOpt(args, &i);
  199. if (!std.fs.path.isAbsolute(global_optional_path_link.?)) {
  200. global_optional_path_link = try toAbsolute(allocator, global_optional_path_link.?);
  201. }
  202. } else if (std.mem.eql(u8, "-h", arg) or std.mem.eql(u8, "--help", arg)) {
  203. help();
  204. return 1;
  205. } else {
  206. args[newlen] = args[i];
  207. newlen += 1;
  208. }
  209. }
  210. args = args[0..newlen];
  211. }
  212. if (args.len == 0) {
  213. help();
  214. return 1;
  215. }
  216. if (std.mem.eql(u8, "fetch-index", args[0])) {
  217. if (args.len != 1) {
  218. std.debug.print("Error: 'index' command requires 0 arguments but got {d}\n", .{args.len - 1});
  219. return 1;
  220. }
  221. var download_index = try fetchDownloadIndex(allocator);
  222. defer download_index.deinit(allocator);
  223. try std.io.getStdOut().writeAll(download_index.text);
  224. return 0;
  225. }
  226. if (std.mem.eql(u8, "fetch", args[0])) {
  227. if (args.len != 2) {
  228. std.debug.print("Error: 'fetch' command requires 1 argument but got {d}\n", .{args.len - 1});
  229. return 1;
  230. }
  231. try fetchCompiler(allocator, args[1], .leave_default);
  232. return 0;
  233. }
  234. if (std.mem.eql(u8, "clean", args[0])) {
  235. if (args.len == 1) {
  236. try cleanCompilers(allocator, null);
  237. } else if (args.len == 2) {
  238. try cleanCompilers(allocator, args[1]);
  239. } else {
  240. std.debug.print("Error: 'clean' command requires 0 or 1 arguments but got {d}\n", .{args.len - 1});
  241. return 1;
  242. }
  243. return 0;
  244. }
  245. if (std.mem.eql(u8, "keep", args[0])) {
  246. if (args.len != 2) {
  247. std.debug.print("Error: 'keep' command requires 1 argument but got {d}\n", .{args.len - 1});
  248. return 1;
  249. }
  250. try keepCompiler(allocator, args[1]);
  251. return 0;
  252. }
  253. if (std.mem.eql(u8, "list", args[0])) {
  254. if (args.len != 1) {
  255. std.debug.print("Error: 'list' command requires 0 arguments but got {d}\n", .{args.len - 1});
  256. return 1;
  257. }
  258. try listCompilers(allocator);
  259. return 0;
  260. }
  261. if (std.mem.eql(u8, "default", args[0])) {
  262. if (args.len == 1) {
  263. try printDefaultCompiler(allocator);
  264. return 0;
  265. }
  266. if (args.len == 2) {
  267. const version_string = args[1];
  268. const install_dir = try getInstallDir(allocator, .{ .create = true });
  269. defer allocator.free(install_dir);
  270. const compiler_dir = try std.fs.path.join(allocator, &[_][]const u8{ install_dir, version_string });
  271. defer allocator.free(compiler_dir);
  272. if (std.mem.eql(u8, version_string, "master")) {
  273. @panic("set default to master not implemented");
  274. } else {
  275. try setDefaultCompiler(allocator, compiler_dir);
  276. }
  277. return 0;
  278. }
  279. std.debug.print("Error: 'default' command requires 1 or 2 arguments but got {d}\n", .{args.len - 1});
  280. return 1;
  281. }
  282. if (args.len == 1) {
  283. try fetchCompiler(allocator, args[0], .set_default);
  284. return 0;
  285. }
  286. const command = args[0];
  287. args = args[1..];
  288. std.debug.print("command not impl '{s}'\n", .{command});
  289. return 1;
  290. //const optionalInstallPath = try find_zigs(allocator);
  291. }
  292. const SetDefault = enum { set_default, leave_default };
  293. fn fetchCompiler(allocator: *Allocator, version_arg: []const u8, set_default: SetDefault) !void {
  294. const install_dir = try getInstallDir(allocator, .{ .create = true });
  295. defer allocator.free(install_dir);
  296. var optional_download_index: ?DownloadIndex = null;
  297. // This is causing an LLVM error
  298. //defer if (optionalDownloadIndex) |_| optionalDownloadIndex.?.deinit(allocator);
  299. // Also I would rather do this, but it doesn't work because of const issues
  300. //defer if (optionalDownloadIndex) |downloadIndex| downloadIndex.deinit(allocator);
  301. const VersionUrl = struct { version: []const u8, url: []const u8 };
  302. // NOTE: we only fetch the download index if the user wants to download 'master', we can skip
  303. // this step for all other versions because the version to URL mapping is fixed (see getDefaultUrl)
  304. const is_master = std.mem.eql(u8, version_arg, "master");
  305. const version_url = blk: {
  306. if (!is_master)
  307. break :blk VersionUrl{ .version = version_arg, .url = try getDefaultUrl(allocator, version_arg) };
  308. optional_download_index = try fetchDownloadIndex(allocator);
  309. const master = optional_download_index.?.json.root.Object.get("master").?;
  310. const compiler_version = master.Object.get("version").?.String;
  311. const master_linux = master.Object.get(json_platform).?;
  312. const master_linux_tarball = master_linux.Object.get("tarball").?.String;
  313. break :blk VersionUrl{ .version = compiler_version, .url = master_linux_tarball };
  314. };
  315. const compiler_dir = try std.fs.path.join(allocator, &[_][]const u8{ install_dir, version_url.version });
  316. defer allocator.free(compiler_dir);
  317. try installCompiler(allocator, compiler_dir, version_url.url);
  318. if (is_master) {
  319. const master_symlink = try std.fs.path.join(allocator, &[_][]const u8{ install_dir, "master" });
  320. defer allocator.free(master_symlink);
  321. if (builtin.os.tag == .windows) {
  322. var file = try std.fs.createFileAbsolute(master_symlink, .{});
  323. defer file.close();
  324. try file.writer().writeAll(version_url.version);
  325. } else {
  326. _ = try loggyUpdateSymlink(version_url.version, master_symlink, .{ .is_directory = true });
  327. }
  328. }
  329. if (set_default == .set_default) {
  330. try setDefaultCompiler(allocator, compiler_dir);
  331. }
  332. }
  333. const download_index_url = "https://ziglang.org/download/index.json";
  334. const DownloadIndex = struct {
  335. text: []u8,
  336. json: std.json.ValueTree,
  337. pub fn deinit(self: *DownloadIndex, allocator: *Allocator) void {
  338. self.json.deinit();
  339. allocator.free(self.text);
  340. }
  341. };
  342. fn fetchDownloadIndex(allocator: *Allocator) !DownloadIndex {
  343. const text = downloadToString(allocator, download_index_url) catch |e| switch (e) {
  344. else => {
  345. std.debug.print("failed to download '{s}': {}\n", .{ download_index_url, e });
  346. return e;
  347. },
  348. };
  349. errdefer allocator.free(text);
  350. var json = init: {
  351. var parser = std.json.Parser.init(allocator, false);
  352. defer parser.deinit();
  353. break :init try parser.parse(text);
  354. };
  355. errdefer json.deinit();
  356. return DownloadIndex{ .text = text, .json = json };
  357. }
  358. fn loggyMakeDirAbsolute(dir_absolute: []const u8) !void {
  359. if (builtin.os.tag == .windows) {
  360. std.debug.print("mkdir \"{s}\"\n", .{dir_absolute});
  361. } else {
  362. std.debug.print("mkdir '{s}'\n", .{dir_absolute});
  363. }
  364. try std.fs.makeDirAbsolute(dir_absolute);
  365. }
  366. fn loggyDeleteTreeAbsolute(dir_absolute: []const u8) !void {
  367. if (builtin.os.tag == .windows) {
  368. std.debug.print("rd /s /q \"{s}\"\n", .{dir_absolute});
  369. } else {
  370. std.debug.print("rm -rf '{s}'\n", .{dir_absolute});
  371. }
  372. try fixdeletetree.deleteTreeAbsolute(dir_absolute);
  373. }
  374. pub fn loggyRenameAbsolute(old_path: []const u8, new_path: []const u8) !void {
  375. std.debug.print("mv '{s}' '{s}'\n", .{ old_path, new_path });
  376. try std.fs.renameAbsolute(old_path, new_path);
  377. }
  378. pub fn loggySymlinkAbsolute(target_path: []const u8, sym_link_path: []const u8, flags: std.fs.SymLinkFlags) !void {
  379. std.debug.print("ln -s '{s}' '{s}'\n", .{ target_path, sym_link_path });
  380. // NOTE: can't use symLinkAbsolute because it requires target_path to be absolute but we don't want that
  381. // not sure if it is a bug in the standard lib or not
  382. //try std.fs.symLinkAbsolute(target_path, sym_link_path, flags);
  383. _ = flags;
  384. try std.os.symlink(target_path, sym_link_path);
  385. }
  386. /// returns: true if the symlink was updated, false if it was already set to the given `target_path`
  387. pub fn loggyUpdateSymlink(target_path: []const u8, sym_link_path: []const u8, flags: std.fs.SymLinkFlags) !bool {
  388. var current_target_path_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined;
  389. if (std.fs.readLinkAbsolute(sym_link_path, &current_target_path_buffer)) |current_target_path| {
  390. if (std.mem.eql(u8, target_path, current_target_path)) {
  391. std.debug.print("symlink '{s}' already points to '{s}'\n", .{ sym_link_path, target_path });
  392. return false; // already up-to-date
  393. }
  394. try std.os.unlink(sym_link_path);
  395. } else |e| switch (e) {
  396. error.FileNotFound => {},
  397. else => return e,
  398. }
  399. try loggySymlinkAbsolute(target_path, sym_link_path, flags);
  400. return true; // updated
  401. }
  402. // TODO: this should be in std lib somewhere
  403. fn existsAbsolute(absolutePath: []const u8) !bool {
  404. std.fs.cwd().access(absolutePath, .{}) catch |e| switch (e) {
  405. error.FileNotFound => return false,
  406. error.PermissionDenied => return e,
  407. error.InputOutput => return e,
  408. error.SystemResources => return e,
  409. error.SymLinkLoop => return e,
  410. error.FileBusy => return e,
  411. error.Unexpected => unreachable,
  412. error.InvalidUtf8 => unreachable,
  413. error.ReadOnlyFileSystem => unreachable,
  414. error.NameTooLong => unreachable,
  415. error.BadPathName => unreachable,
  416. };
  417. return true;
  418. }
  419. fn listCompilers(allocator: *Allocator) !void {
  420. const install_dir_string = try getInstallDir(allocator, .{ .create = false });
  421. defer allocator.free(install_dir_string);
  422. var install_dir = std.fs.openDirAbsolute(install_dir_string, .{ .iterate = true }) catch |e| switch (e) {
  423. error.FileNotFound => return,
  424. else => return e,
  425. };
  426. defer install_dir.close();
  427. const stdout = std.io.getStdOut().writer();
  428. {
  429. var it = install_dir.iterate();
  430. while (try it.next()) |entry| {
  431. if (entry.kind != .Directory)
  432. continue;
  433. if (std.mem.endsWith(u8, entry.name, ".installing"))
  434. continue;
  435. try stdout.print("{s}\n", .{entry.name});
  436. }
  437. }
  438. }
  439. fn keepCompiler(allocator: *Allocator, compiler_version: []const u8) !void {
  440. const install_dir_string = try getInstallDir(allocator, .{ .create = true });
  441. defer allocator.free(install_dir_string);
  442. var install_dir = try std.fs.openDirAbsolute(install_dir_string, .{ .iterate = true });
  443. defer install_dir.close();
  444. var compiler_dir = install_dir.openDir(compiler_version, .{}) catch |e| switch (e) {
  445. error.FileNotFound => {
  446. std.debug.print("Error: compiler not found: {s}\n", .{compiler_version});
  447. return error.AlreadyReported;
  448. },
  449. else => return e,
  450. };
  451. var keep_fd = try compiler_dir.createFile("keep", .{});
  452. keep_fd.close();
  453. std.debug.print("created '{s}{c}{s}{c}{s}'\n", .{ install_dir_string, std.fs.path.sep, compiler_version, std.fs.path.sep, "keep" });
  454. }
  455. fn cleanCompilers(allocator: *Allocator, compiler_name_opt: ?[]const u8) !void {
  456. const install_dir_string = try getInstallDir(allocator, .{ .create = true });
  457. defer allocator.free(install_dir_string);
  458. // getting the current compiler
  459. const default_comp_opt = try getDefaultCompiler(allocator);
  460. defer if (default_comp_opt) |default_compiler| allocator.free(default_compiler);
  461. var install_dir = std.fs.openDirAbsolute(install_dir_string, .{ .iterate = true }) catch |e| switch (e) {
  462. error.FileNotFound => return,
  463. else => return e,
  464. };
  465. defer install_dir.close();
  466. const master_points_to_opt = try getMasterDir(allocator, &install_dir);
  467. defer if (master_points_to_opt) |master_points_to| allocator.free(master_points_to);
  468. if (compiler_name_opt) |compiler_name| {
  469. if (getKeepReason(master_points_to_opt, default_comp_opt, compiler_name)) |reason| {
  470. std.debug.print("Error: cannot clean '{s}' ({s})\n", .{ compiler_name, reason });
  471. return error.AlreadyReported;
  472. }
  473. std.debug.print("deleting '{s}{c}{s}'\n", .{ install_dir_string, std.fs.path.sep, compiler_name });
  474. try fixdeletetree.deleteTree(install_dir, compiler_name);
  475. } else {
  476. var it = install_dir.iterate();
  477. while (try it.next()) |entry| {
  478. if (entry.kind != .Directory)
  479. continue;
  480. if (getKeepReason(master_points_to_opt, default_comp_opt, entry.name)) |reason| {
  481. std.debug.print("keeping '{s}' ({s})\n", .{ entry.name, reason });
  482. continue;
  483. }
  484. var compiler_dir = try install_dir.openDir(entry.name, .{});
  485. defer compiler_dir.close();
  486. if (compiler_dir.access("keep", .{})) |_| {
  487. std.debug.print("keeping '{s}' (has keep file)\n", .{entry.name});
  488. continue;
  489. } else |e| switch (e) {
  490. error.FileNotFound => {},
  491. else => return e,
  492. }
  493. std.debug.print("deleting '{s}{c}{s}'\n", .{ install_dir_string, std.fs.path.sep, entry.name });
  494. try fixdeletetree.deleteTree(install_dir, entry.name);
  495. }
  496. }
  497. }
  498. fn readDefaultCompiler(allocator: *Allocator, buffer: *[std.fs.MAX_PATH_BYTES]u8) !?[]const u8 {
  499. const path_link = try makeZigPathLinkString(allocator);
  500. defer allocator.free(path_link);
  501. if (builtin.os.tag == .windows) {
  502. var file = std.fs.openFileAbsolute(path_link, .{}) catch |e| switch (e) {
  503. error.FileNotFound => return null,
  504. else => return e,
  505. };
  506. defer file.close();
  507. const content = try file.readToEndAlloc(allocator, 99999);
  508. defer allocator.free(content);
  509. if (content.len == 0) {
  510. std.log.err("path link file '{s}' is empty", .{path_link});
  511. return error.AlreadyReported;
  512. }
  513. if (content[0] != '@') {
  514. std.log.err("path link file '{s}' does not begin with the '@' character", .{path_link});
  515. return error.AlreadyReported;
  516. }
  517. if (!std.mem.endsWith(u8, content, " %*")) {
  518. std.log.err("path link file '{s}' does not end with ' %*'", .{path_link});
  519. return error.AlreadyReported;
  520. }
  521. const target_exe = content[1..content.len - 3];
  522. return try std.mem.dupe(allocator, u8, targetPathToVersion(target_exe));
  523. }
  524. const target_path = std.fs.readLinkAbsolute(path_link, buffer) catch |e| switch (e) {
  525. error.FileNotFound => return null,
  526. else => return e,
  527. };
  528. defer allocator.free(target_path);
  529. return try std.mem.dupe(allocator, u8, targetPathToVersion(target_path));
  530. }
  531. fn targetPathToVersion(target_path: []const u8) []const u8 {
  532. return std.fs.path.basename(std.fs.path.dirname(std.fs.path.dirname(target_path).?).?);
  533. }
  534. fn readMasterDir(buffer: *[std.fs.MAX_PATH_BYTES]u8, install_dir: *std.fs.Dir) !?[]const u8 {
  535. if (builtin.os.tag == .windows) {
  536. var file = install_dir.openFile("master", .{}) catch |e| switch (e) {
  537. error.FileNotFound => return null,
  538. else => return e,
  539. };
  540. defer file.close();
  541. return buffer[0..try file.readAll(buffer)];
  542. }
  543. return install_dir.readLink("master", buffer) catch |e| switch (e) {
  544. error.FileNotFound => return null,
  545. else => return e,
  546. };
  547. }
  548. fn getDefaultCompiler(allocator: *Allocator) !?[]const u8 {
  549. var buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined;
  550. const slice_path = (try readDefaultCompiler(allocator, &buffer)) orelse return null;
  551. var path_to_return = try allocator.alloc(u8, slice_path.len);
  552. std.mem.copy(u8, path_to_return, slice_path);
  553. return path_to_return;
  554. }
  555. fn getMasterDir(allocator: *Allocator, install_dir: *std.fs.Dir) !?[]const u8 {
  556. var buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined;
  557. const slice_path = (try readMasterDir(&buffer, install_dir)) orelse return null;
  558. var path_to_return = try allocator.alloc(u8, slice_path.len);
  559. std.mem.copy(u8, path_to_return, slice_path);
  560. return path_to_return;
  561. }
  562. fn printDefaultCompiler(allocator: *Allocator) !void {
  563. const default_compiler_opt = try getDefaultCompiler(allocator);
  564. defer if (default_compiler_opt) |default_compiler| allocator.free(default_compiler);
  565. const stdout = std.io.getStdOut().writer();
  566. if (default_compiler_opt) |default_compiler| {
  567. try stdout.print("{s}\n", .{default_compiler});
  568. } else {
  569. try stdout.writeAll("<no-default>\n");
  570. }
  571. }
  572. fn setDefaultCompiler(allocator: *Allocator, compiler_dir: []const u8) !void {
  573. const path_link = try makeZigPathLinkString(allocator);
  574. defer allocator.free(path_link);
  575. const link_target = try std.fs.path.join(allocator, &[_][]const u8{ compiler_dir, "files", "zig" ++ builtin.target.exeFileExt() });
  576. defer allocator.free(link_target);
  577. if (builtin.os.tag == .windows) {
  578. var file = try std.fs.cwd().createFile(path_link, .{});
  579. defer file.close();
  580. try file.writer().print("@{s} %*", .{link_target});
  581. } else {
  582. _ = try loggyUpdateSymlink(link_target, path_link, .{});
  583. }
  584. }
  585. fn getDefaultUrl(allocator: *Allocator, compiler_version: []const u8) ![]const u8 {
  586. return try std.fmt.allocPrint(allocator, "https://ziglang.org/download/{s}/zig-" ++ url_platform ++ "-{0s}." ++ archive_ext, .{ compiler_version });
  587. }
  588. fn installCompiler(allocator: *Allocator, compiler_dir: []const u8, url: []const u8) !void {
  589. if (try existsAbsolute(compiler_dir)) {
  590. std.debug.print("compiler '{s}' already installed\n", .{compiler_dir});
  591. return;
  592. }
  593. const installing_dir = try std.mem.concat(allocator, u8, &[_][]const u8{ compiler_dir, ".installing" });
  594. defer allocator.free(installing_dir);
  595. try loggyDeleteTreeAbsolute(installing_dir);
  596. try loggyMakeDirAbsolute(installing_dir);
  597. const archive_basename = std.fs.path.basename(url);
  598. var archive_root_dir: []const u8 = undefined;
  599. // download and extract archive
  600. {
  601. const archive_absolute = try std.fs.path.join(allocator, &[_][]const u8{ installing_dir, archive_basename });
  602. defer allocator.free(archive_absolute);
  603. std.debug.print("downloading '{s}' to '{s}'\n", .{ url, archive_absolute });
  604. downloadToFileAbsolute(allocator, url, archive_absolute) catch |e| switch (e) {
  605. error.HttpNon200StatusCode => {
  606. // TODO: more information would be good
  607. std.debug.print("HTTP request failed (TODO: improve ziget library to get better error)\n", .{});
  608. // this removes the installing dir if the http request fails so we dont have random directories
  609. try loggyDeleteTreeAbsolute(installing_dir);
  610. return error.AlreadyReported;
  611. },
  612. else => return e,
  613. };
  614. if (std.mem.endsWith(u8, archive_basename, ".tar.xz")) {
  615. archive_root_dir = archive_basename[0 .. archive_basename.len - ".tar.xz".len];
  616. _ = try run(allocator, &[_][]const u8{ "tar", "xf", archive_absolute, "-C", installing_dir });
  617. } else if (std.mem.endsWith(u8, archive_basename, ".zip")) {
  618. // for now we'll use "tar" which seems to exist on windows 10, but we should switch
  619. // to a zig implementation (i.e. https://github.com/SuperAuguste/zzip)
  620. archive_root_dir = archive_basename[0 .. archive_basename.len - ".zip".len];
  621. _ = try run(allocator, &[_][]const u8{ "tar", "-xf", archive_absolute, "-C", installing_dir });
  622. } else {
  623. std.debug.print("Error: unknown archive extension '{s}'\n", .{archive_basename});
  624. return error.UnknownArchiveExtension;
  625. }
  626. try loggyDeleteTreeAbsolute(archive_absolute);
  627. }
  628. {
  629. const extracted_dir = try std.fs.path.join(allocator, &[_][]const u8{ installing_dir, archive_root_dir });
  630. defer allocator.free(extracted_dir);
  631. const normalized_dir = try std.fs.path.join(allocator, &[_][]const u8{ installing_dir, "files" });
  632. defer allocator.free(normalized_dir);
  633. try loggyRenameAbsolute(extracted_dir, normalized_dir);
  634. }
  635. // TODO: write date information (so users can sort compilers by date)
  636. // finish installation by renaming the install dir
  637. try loggyRenameAbsolute(installing_dir, compiler_dir);
  638. }
  639. pub fn run(allocator: *std.mem.Allocator, argv: []const []const u8) !std.ChildProcess.Term {
  640. try logRun(allocator, argv);
  641. var proc = try std.ChildProcess.init(argv, allocator);
  642. defer proc.deinit();
  643. return proc.spawnAndWait();
  644. }
  645. fn logRun(allocator: *std.mem.Allocator, argv: []const []const u8) !void {
  646. var buffer = try allocator.alloc(u8, getCommandStringLength(argv));
  647. defer allocator.free(buffer);
  648. var prefix = false;
  649. var offset: usize = 0;
  650. for (argv) |arg| {
  651. if (prefix) {
  652. buffer[offset] = ' ';
  653. offset += 1;
  654. } else {
  655. prefix = true;
  656. }
  657. std.mem.copy(u8, buffer[offset .. offset + arg.len], arg);
  658. offset += arg.len;
  659. }
  660. std.debug.assert(offset == buffer.len);
  661. std.debug.print("[RUN] {s}\n", .{buffer});
  662. }
  663. pub fn getCommandStringLength(argv: []const []const u8) usize {
  664. var len: usize = 0;
  665. var prefix_length: u8 = 0;
  666. for (argv) |arg| {
  667. len += prefix_length + arg.len;
  668. prefix_length = 1;
  669. }
  670. return len;
  671. }
  672. pub fn getKeepReason(master_points_to_opt: ?[]const u8, default_compiler_opt: ?[]const u8, name: []const u8) ?[]const u8 {
  673. if (default_compiler_opt) |default_comp| {
  674. if (mem.eql(u8, default_comp, name)) {
  675. return "is default compiler";
  676. }
  677. }
  678. if (master_points_to_opt) |master_points_to| {
  679. if (mem.eql(u8, master_points_to, name)) {
  680. return "it is master";
  681. }
  682. }
  683. return null;
  684. }