zigup.zig 31 KB

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