zigup.zig 27 KB

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