zigup.zig 30 KB

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