A pretty printer for zig
zig

no color and disable

altagos.dev 9d24ba6c 3633f6b6

verified
+21 -4
+21 -4
pretty.zig
··· 17 17 Options{}; 18 18 19 19 pub const Options = struct { 20 + no_color: bool = false, 21 + disable: bool = false, 22 + 20 23 indent_width: comptime_int = 2, 21 24 22 25 inline_arrays: bool = false, ··· 60 63 color_false: Io.Terminal.Color = .bright_red, 61 64 62 65 pub inline fn getColor(comptime this: Theme, comptime color: Color) Io.Terminal.Color { 63 - return switch (color) { 64 - inline else => |col| @field(this, "color_" ++ @tagName(col)), 65 - }; 66 + return @field(this, "color_" ++ @tagName(color)); 66 67 } 67 68 }; 68 69 ··· 71 72 } 72 73 73 74 pub fn PrettyWithOptions(comptime T: type, comptime options: Options) type { 75 + if (default_options.disable) return struct { 76 + value: T, 77 + 78 + pub fn init(val: T) @This() { 79 + return .{ .value = val }; 80 + } 81 + 82 + pub fn format(this: *const @This(), w: *std.Io.Writer) error{WriteFailed}!void { 83 + try w.print("{any}", .{this.value}); 84 + } 85 + }; 86 + 74 87 const global = struct { 75 88 var tty: ?Io.Terminal = null; 76 89 }; ··· 96 109 var run = Runtime{ 97 110 .out = w, 98 111 .tty = global.tty.?, 112 + .no_color = options.no_color, 99 113 }; 100 114 101 115 return innerFmt(T, ctx, &run, this.value, .{}); ··· 107 121 out: *Io.Writer, 108 122 tty: Io.Terminal, 109 123 110 - depth: usize = 0, 124 + no_color: bool = default_options.no_color, 111 125 112 126 pub inline fn print( 113 127 this: *const Runtime, ··· 126 140 comptime ctx: Context, 127 141 comptime color: Theme.Color, 128 142 ) void { 143 + if (this.no_color or default_options.no_color) return; 129 144 this.tty.setColor(ctx.options.theme.getColor(color)) catch {}; 130 145 } 131 146 132 147 pub inline fn setColorRaw(this: *const Runtime, color: Io.Terminal.Color) void { 148 + if (this.no_color or default_options.no_color) return; 133 149 this.tty.setColor(color) catch {}; 134 150 } 135 151 136 152 pub inline fn resetColor(this: *const Runtime) void { 153 + if (this.no_color or default_options.no_color) return; 137 154 this.tty.setColor(.reset) catch {}; 138 155 } 139 156 };