const std = @import("std"); const Header = std.http.Header; const Client = std.http.Client; const Reader = std.Io.Reader; const Child = std.process.Child; const Dir = std.fs.Dir; const Writer = std.Io.Writer; const ArrayList = std.ArrayList; const Allocator = std.mem.Allocator; const builtin = @import("builtin"); const cli = @import("cli.zig"); const colors = @import("colors.zig"); pub var stderr: *Writer = undefined; pub var stdout: *Writer = undefined; /// Decode a base64 string, used for parsing out build artifacts generated by the CLI program's /// build.zig which are stored in the executable as a module. pub fn base64Decode(allocator: Allocator, input: []const u8) ![]const u8 { const decoder = std.base64.Base64Decoder.init( std.base64.url_safe_no_pad.alphabet_chars, std.base64.url_safe_no_pad.pad_char, ); const size = try decoder.calcSizeForSlice(input); const ptr = try allocator.alloc(u8, size); try decoder.decode(ptr, input); return ptr; } const icons = .{ .check = "✅", .cross = "❌", }; /// Print a success confirmation. pub fn printSuccess(message: ?[]const u8) !void { try stdout.print(" " ++ icons.check ++ " {s}\n", .{message orelse ""}); } /// Print a failure confirmation. pub fn printFailure() !void { try stderr.print(" " ++ icons.cross ++ "\n", .{}); } const PrintContext = enum { success, failure }; /// Print some output in with a given context to std{out,err} pub fn print(comptime context: PrintContext, comptime message: []const u8, args: anytype) !void { switch (context) { .success => try stdout.print( std.fmt.comptimePrint("{s} {s}\n", .{ icons.check, colors.green(message) }), args, ), .failure => try stderr.print( std.fmt.comptimePrint("{s} {s}\n", .{ icons.cross, colors.red(message) }), args, ), } } /// Detects a Jetzig project directory either in the current directory or one of its parent /// directories. pub fn detectJetzigProjectDir() !Dir { var dir = try std.fs.cwd().openDir(".", .{}); const max_parent_dirs: usize = 100; // Prevent symlink loops or other weird stuff. for (0..max_parent_dirs) |_| { if (try isPath(dir, "build.zig", .file) and try isPath(dir, "src/app/views", .dir)) return dir; dir = dir.openDir("..", .{}) catch |err| { switch (err) { error.FileNotFound, error.NotDir => { try stderr.print( "Encountered unexpected detecting Jetzig project directory: {s}\n", .{@errorName(err)}, ); return error.JetzigCommandError; }, else => return err, } }; continue; } try stderr.print( \\Exceeded maximum parent directory depth. \\Unable to detect Jetzig project directory. \\ , .{}, ); return error.JetzigCommandError; } fn isPath(dir: Dir, sub_path: []const u8, path_type: enum { file, dir }) !bool { switch (path_type) { .file => { _ = dir.statFile(sub_path) catch |err| { switch (err) { error.FileNotFound => return false, else => return err, } }; return true; }, .dir => { var test_dir = dir.openDir(sub_path, .{}) catch |err| { switch (err) { error.FileNotFound, error.NotDir => return false, else => return err, } }; test_dir.close(); return true; }, } } // Strip leading and trailing whitespace from a u8 slice. pub inline fn strip(input: []const u8) []const u8 { return std.mem.trim(u8, input, &std.ascii.whitespace); } /// Attempts to confirm if a string input is in CamelCase. False if the first character is /// not alphabetic lower-case or if the input contains underscores. pub fn isCamelCase(input: []const u8) bool { if (input.len == 0) return false; if (!std.mem.containsAtLeast(u8, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 1, &[_]u8{input[0]})) return false; if (std.mem.containsAtLeast(u8, input, 1, "_")) return false; return true; } pub fn execCommand(allocator: Allocator, argv: []const []const u8) !void { try stdout.print("[exec]", .{}); for (argv) |arg| try stdout.print(" {s}", .{arg}); try stdout.print("\n", .{}); if (std.process.can_execv) { return std.process.execv(allocator, argv); } else { var dir = try detectJetzigProjectDir(); defer dir.close(); const path = try dir.realpathAlloc(allocator, "."); defer allocator.free(path); try runCommandStreaming(allocator, path, argv); } } pub fn runCommandStreaming(allocator: Allocator, install_path: []const u8, argv: []const []const u8) !void { var child: Child = .init(argv, allocator); child.stdin_behavior = .Ignore; child.stdout_behavior = .Inherit; child.stderr_behavior = .Inherit; child.cwd = install_path; try child.spawn(); _ = try child.wait(); } /// Runs a command as a child process in Jetzig project directory and verifies successful exit /// code. pub fn runCommand(allocator: Allocator, argv: []const []const u8) !void { var dir = try detectJetzigProjectDir(); defer dir.close(); try runCommandInDir(allocator, argv, .{ .dir = dir }, .{}); } const _Dir = union(enum) { path: []const u8, dir: std.fs.Dir, }; pub const RunOptions = struct { output: enum { stream, capture } = .capture, wait: bool = true, }; /// Runs a command as a child process in the given directory and verifies successful exit code. pub fn runCommandInDir(allocator: Allocator, argv: []const []const u8, dir: _Dir, options: RunOptions) !void { const cwd_path = switch (dir) { .path => |capture| capture, .dir => |capture| try capture.realpathAlloc(allocator, "."), }; defer if (dir == .dir) allocator.free(cwd_path); const output_behaviour: Child.StdIo = switch (options.output) { .stream => .Inherit, .capture => .Pipe, }; var child: Child = .init(argv, allocator); child.stdin_behavior = .Ignore; child.stdout_behavior = output_behaviour; child.stderr_behavior = output_behaviour; if (options.output == .stream) { child.stdout = .stdout(); child.stderr = .stderr(); } child.cwd = cwd_path; var stdout_array: ArrayList(u8) = try .initCapacity(allocator, 0); var stderr_array: ArrayList(u8) = try .initCapacity(allocator, 0); errdefer { stdout_array.deinit(allocator); stderr_array.deinit(allocator); } try child.spawn(); switch (options.output) { .capture => try collectOutput(child, allocator, &stdout_array, &stderr_array), .stream => {}, } if (!options.wait) return; const result: Child.RunResult = .{ .term = try child.wait(), .stdout = try stdout_array.toOwnedSlice(allocator), .stderr = try stderr_array.toOwnedSlice(allocator), }; defer allocator.free(result.stdout); defer allocator.free(result.stderr); if (result.term.Exited != 0) { try printFailure(); if (result.stdout.len > 0) try stderr.print("\n[stdout]:\n{s}\n", .{result.stdout}); if (result.stderr.len > 0) try stderr.print("\n[stderr]:\n{s}\n", .{result.stderr}); return error.JetzigCommandError; } const message = try std.mem.join(allocator, " ", argv); defer allocator.free(message); try printSuccess(message); } fn collectOutput( child: Child, allocator: Allocator, stdout_array: *ArrayList(u8), stderr_array: *ArrayList(u8), ) !void { const max_output_bytes = 50 * 1024; std.debug.assert(child.stdout_behavior == .Pipe); std.debug.assert(child.stderr_behavior == .Pipe); var poller = std.Io.poll(allocator, enum { stdout, stderr }, .{ .stdout = child.stdout.?, .stderr = child.stderr.?, }); defer poller.deinit(); try stdout.print("(working) .", .{}); while (try poller.poll()) { if (poller.reader(.stdout).bufferedLen() > max_output_bytes) return error.StdoutStreamTooLong; if (poller.reader(.stderr).bufferedLen() > max_output_bytes) return error.StderrStreamTooLong; try stdout.print(".", .{}); } try stdout.print(" (done)\n", .{}); try writeFifoDataToArrayList(allocator, stdout_array, poller.reader(.stdout)); try writeFifoDataToArrayList(allocator, stderr_array, poller.reader(.stderr)); } // Copy the buffered data from the poller's reader to the array list. // After the poller is done, the reader's buffer contains all the data that was read. fn writeFifoDataToArrayList(allocator: Allocator, list: *ArrayList(u8), reader: *Reader) !void { try list.appendSlice(allocator, reader.buffered()); } /// Generate a full GitHub URL for passing to `zig fetch`. pub fn githubUrl(allocator: Allocator) ![]const u8 { var client: Client = .{ .allocator = allocator }; defer client.deinit(); var buf: Writer.Allocating = .init(allocator); defer buf.deinit(); const writer = &buf.writer; try writer.writeAll("https://api.github.com/repos/jetzig-framework/jetzig/branches/"); if (builtin.zig_version.build) |_| try writer.writeAll("main") else try writer.print("zig-{[major]d}.{[minor]d}", .{ .major = builtin.zig_version.major, .minor = builtin.zig_version.minor, }); const url = try buf.toOwnedSlice(); defer allocator.free(url); const extra_headers = &[_]Header{.{ .name = "X-GitHub-Api-Version", .value = "2022-11-28", }}; const fetch_result = try client.fetch(.{ .location = .{ .url = url }, .extra_headers = extra_headers, .response_writer = writer, }); if (fetch_result.status != .ok) { try stderr.print("Error fetching from GitHub: {s}\n", .{url}); return error.JetzigCommandError; } const response = try buf.toOwnedSlice(); defer allocator.free(response); const parsed_response = try std.json.parseFromSlice( struct { commit: struct { sha: []const u8 } }, allocator, response, .{ .ignore_unknown_fields = true }, ); defer parsed_response.deinit(); try writer.print( "https://github.com/jetzig-framework/jetzig/archive/{s}.tar.gz", .{parsed_response.value.commit.sha}, ); return buf.toOwnedSlice(); } /// Attempt to locate the main application executable in `zig-out/bin/` pub fn locateExecutable( allocator: Allocator, dir: Dir, options: struct { relative: bool = false }, ) !?[]const u8 { const file = dir.openFile(".jetzig", .{}) catch |err| { switch (err) { error.FileNotFound => return null, else => return err, } }; const content = try file.readToEndAlloc(allocator, 1024); defer allocator.free(content); const exe_name = strip(content); const suffix = if (builtin.os.tag == .windows) ".exe" else ""; const full_name = try std.mem.concat(allocator, u8, &[_][]const u8{ exe_name, suffix }); defer allocator.free(full_name); // XXX: Will fail if user sets a custom install path. var bin_dir = try dir.openDir("zig-out/bin", .{ .iterate = true }); defer bin_dir.close(); var walker = try bin_dir.walk(allocator); defer walker.deinit(); while (try walker.next()) |entry| { if (entry.kind == .file and std.mem.eql(u8, entry.path, full_name)) { if (options.relative) return try std.fs.path.join( allocator, &[_][]const u8{ "zig-out", "bin", entry.path }, ); return try bin_dir.realpathAlloc(allocator, entry.path); } } return null; } pub fn environmentBuildOption(environment: cli.Environment) []const u8 { return switch (environment) { inline else => |tag| "-Denvironment=" ++ @tagName(tag), }; } pub fn unicodePrint(comptime fmt: []const u8, args: anytype) !void { if (builtin.os.tag != .windows) // Non-Windows platforms just print normally return stdout.print(fmt, args); // Windows-specific code const cp_out = try UTF8ConsoleOutput.init(); defer cp_out.deinit(); try stdout.print(fmt, args); } const UTF8ConsoleOutput = struct { original: c_uint, fn init() !UTF8ConsoleOutput { const original = std.os.windows.kernel32.GetConsoleOutputCP(); if (original == 0) return error.FailedToGetConsoleOutputCP; const result = std.os.windows.kernel32.SetConsoleOutputCP(65001); // UTF-8 code page if (result == 0) return error.FailedToSetConsoleOutputCP; return .{ .original = original }; } fn deinit(self: UTF8ConsoleOutput) void { _ = std.os.windows.kernel32.SetConsoleOutputCP(self.original); } };