refactor all the scripts

This commit is contained in:
LordMZTE 2023-07-01 19:20:02 +02:00
parent 3a3c9bc59f
commit b55f0ae22d
Signed by: LordMZTE
GPG key ID: B64802DC33A64FF6
14 changed files with 63 additions and 87 deletions

View file

@ -1,3 +1,4 @@
#![warn(clippy::pedantic)]
use std::sync::Arc;
use unicode_segmentation::UnicodeSegmentation;
@ -16,6 +17,8 @@ use i3status_rs::{
BarState,
};
mod catppuccin;
#[tokio::main(flavor = "current_thread")]
async fn main() {
if let Err(e) = try_main().await {
@ -25,7 +28,7 @@ async fn main() {
serde_json::to_writer(
std::io::stdout(),
&err_widget.get_data(&Default::default(), 0).unwrap(),
&err_widget.get_data(&SharedConfig::default(), 0).unwrap(),
)
.unwrap();
println!(",");
@ -36,8 +39,6 @@ async fn main() {
}
}
mod catppuccin;
async fn try_main() -> anyhow::Result<()> {
env_logger::try_init()?;
protocol::init(false);

View file

@ -14,9 +14,8 @@ pub fn populateEnvironment(env: *std.process.EnvMap) !bool {
// buffer for small one-off operations while `buf` is in use
var sbuf: [512]u8 = undefined;
if (env.get("MZTE_ENV_SET")) |_| {
if (env.get("MZTE_ENV_SET")) |_|
return false;
}
const alloc = env.hash_map.allocator;
const home = if (env.get("HOME")) |home| try alloc.dupe(u8, home) else blk: {
@ -28,13 +27,13 @@ pub fn populateEnvironment(env: *std.process.EnvMap) !bool {
try env.put("MZTE_ENV_SET", "1");
// XDG vars
inline for (.{
for ([_][2][]const u8{
.{ "XDG_DATA_HOME", ".local/share" },
.{ "XDG_CONFIG_HOME", ".config" },
.{ "XDG_STATE_HOME", ".local/state" },
.{ "XDG_CACHE_HOME", ".local/cache" },
}) |kv| {
try env.put(kv.@"0", try std.fmt.bufPrint(&sbuf, "{s}/{s}", .{ home, kv.@"1" }));
try env.put(kv[0], try std.fmt.bufPrint(&sbuf, "{s}/{s}", .{ home, kv[1] }));
}
// set shell to fish to prevent anything from defaulting to mzteinit
@ -115,14 +114,13 @@ pub fn populateEnvironment(env: *std.process.EnvMap) !bool {
var bufstream = std.io.fixedBufferStream(&buf);
var b = delimitedWriter(bufstream.writer(), ':');
const fixed_home = [_][]const u8{
for ([_][]const u8{
".mix/escripts",
".cargo/bin",
".local/bin",
"go/bin",
".roswell/bin",
};
for (fixed_home) |fixed| {
}) |fixed| {
try b.push(try std.fmt.bufPrint(&sbuf, "{s}/{s}", .{ home, fixed }));
}

View file

@ -57,20 +57,12 @@ fn tryMain() !void {
var env_map = std.process.EnvMap.init(alloc);
defer env_map.deinit();
for (std.os.environ) |env_var| {
var idx: usize = 0;
while (env_var[idx] != '=') {
idx += 1;
}
const eq_idx = idx;
while (env_var[idx] != 0) {
idx += 1;
}
for (std.os.environ) |env_var_z| {
const env_var = std.mem.span(env_var_z);
const eq_idx = std.mem.indexOfScalar(u8, env_var, '=').?;
const key = env_var[0..eq_idx];
const value = env_var[eq_idx + 1 .. idx];
const value = env_var[eq_idx + 1 ..];
try env_map.put(key, value);
}
@ -90,14 +82,14 @@ fn tryMain() !void {
}
while (true) {
try util.writeAnsiClear(stdout.writer());
try stdout.writer().writeAll(util.ansi_clear);
const cmd = ui(&stdout) catch |e| {
std.debug.print("Error rendering the UI: {}\n", .{e});
break;
};
try util.writeAnsiClear(stdout.writer());
try stdout.writer().writeAll(util.ansi_clear);
try stdout.flush();
var exit = util.ExitMode.run;

View file

@ -15,12 +15,9 @@ pub fn getCurrentSystemDaemon() !SystemDaemon {
if (cache.daemon) |d|
return d;
const systemd_stat: ?std.fs.File.Stat = std.fs.cwd().statFile("/etc/systemd") catch |e| blk: {
if (e == error.FileNotFound) {
break :blk null;
}
return e;
const systemd_stat: ?std.fs.File.Stat = std.fs.cwd().statFile("/etc/systemd") catch |e| switch (e) {
error.FileNotFound => null,
else => return e,
};
const daemon: SystemDaemon = if (systemd_stat) |_| .systemd else .none;

View file

@ -1,5 +1,3 @@
pub fn writeAnsiClear(writer: anytype) !void {
try writer.writeAll("\x1b[2J\x1b[1;1H");
}
pub const ansi_clear = "\x1b[2J\x1b[1;1H";
pub const ExitMode = enum { run, immediate, delayed };

View file

@ -6,8 +6,8 @@ pub const std_options = struct {
};
const browsers = &[_][]const u8{
"luakit",
"firefox",
"luakit",
"chromium",
};

View file

@ -48,12 +48,13 @@ pub fn main() !void {
),
};
var buf = std.BoundedArray(u8, 1024 * 8).init(0) catch unreachable;
prompt.render(buf.writer(), options) catch |e| {
buf.resize(0) catch unreachable;
buf.writer().print("Render Error: {s}\n|> ", .{@errorName(e)}) catch unreachable;
var buf: [1024 * 8]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buf);
prompt.render(fbs.writer(), options) catch |e| {
fbs.reset();
fbs.writer().print("Render Error: {s}\n|> ", .{@errorName(e)}) catch unreachable;
};
try std.io.getStdOut().writeAll(buf.slice());
try std.io.getStdOut().writeAll(fbs.getWritten());
} else {
return error.UnknownCommand;
}

View file

@ -49,10 +49,7 @@ fn Renderer(comptime Writer: type) type {
const Self = @This();
pub fn render(self: *Self) !void {
const left_color = if (self.options.status == 0)
Color{ .Green = {} }
else
Color{ .Red = {} };
const left_color: Color = if (self.options.status == 0) .Green else .Red;
try self.setStyle(.{ .foreground = left_color });
try self.writer.writeAll(symbols.top_left);
@ -85,7 +82,7 @@ fn Renderer(comptime Writer: type) type {
});
try self.writer.writeAll(symbols.right_separator ++ " ");
try self.setStyle(.{
.foreground = .{ .Black = {} },
.foreground = .Black,
.background = mode_color,
.font_style = .{ .bold = true },
});
@ -177,8 +174,8 @@ fn Renderer(comptime Writer: type) type {
// write root-relative path
if (!written_path) {
try self.setStyle(.{
.background = .{ .Yellow = {} },
.foreground = .{ .Red = {} },
.background = .Yellow,
.foreground = .Red,
});
try self.writer.writeAll(" " ++ symbols.root);
@ -201,14 +198,14 @@ fn Renderer(comptime Writer: type) type {
fn renderPathSep(self: *Self) !void {
try self.setStyle(.{
.background = self.last_style.?.background,
.foreground = .{ .Blue = {} },
.foreground = .Blue,
});
try self.writer.writeAll(" " ++ symbols.path_separator ++ " ");
try self.setStyle(.{
.background = self.last_style.?.background,
.foreground = .{ .Black = {} },
.foreground = .Black,
});
}
@ -235,7 +232,7 @@ fn Renderer(comptime Writer: type) type {
try self.drawLeftSep(bg);
try self.setStyle(.{
.background = bg,
.foreground = .{ .Black = {} },
.foreground = .Black,
.font_style = .{ .bold = true },
});
try self.writer.writeAll(" <new branch>");
@ -277,27 +274,27 @@ fn Renderer(comptime Writer: type) type {
try self.setStyle(.{
.background = ref_bg,
.foreground = .{ .Black = {} },
.foreground = .Black,
.font_style = .{ .bold = true },
});
// using print here because name is a cstring
try self.writer.print(" {s}", .{name});
if (counts.staged > 0) {
try self.drawLeftSep(.{ .Green = {} });
try self.drawLeftSep(.Green);
try self.setStyle(.{
.background = .{ .Green = {} },
.foreground = .{ .Black = {} },
.background = .Green,
.foreground = .Black,
});
try self.writer.print(" {}{s}", .{ counts.staged, symbols.staged });
}
if (counts.unstaged > 0) {
try self.drawLeftSep(.{ .Magenta = {} });
try self.drawLeftSep(.Magenta);
try self.setStyle(.{
.background = .{ .Magenta = {} },
.foreground = .{ .Black = {} },
.background = .Magenta,
.foreground = .Black,
});
try self.writer.print(" {}{s}", .{ counts.unstaged, symbols.unstaged });
@ -351,20 +348,20 @@ fn gitStatusCb(
}
const GitStatusCounts = struct {
staged: c_int = 0,
unstaged: c_int = 0,
staged: u32 = 0,
unstaged: u32 = 0,
pub fn getColor(self: *GitStatusCounts) Color {
const has_staged = self.staged > 0;
const has_unstaged = self.unstaged > 0;
return if (!has_staged and !has_unstaged)
Color{ .Blue = {} }
.Blue
else if (has_staged and has_unstaged)
Color{ .Magenta = {} }
.Magenta
else if (has_staged)
Color{ .Green = {} }
.Green
else
Color{ .Grey = 200 };
.{ .Grey = 200 };
}
};

View file

@ -2,7 +2,6 @@ const std = @import("std");
files: std.ArrayList([]u8),
filename_arena: std.heap.ArenaAllocator,
buf: [64]u8 = undefined,
const Self = @This();
@ -32,17 +31,16 @@ pub fn walk(self: *Self, dir: std.fs.IterableDir) anyerror!void {
try self.walk(subdir);
},
.sym_link => {
const p = try dir.dir.readLink(e.name, &self.buf);
var p_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
const p = try dir.dir.readLink(e.name, &p_buf);
var subdir = dir.dir.openIterableDir(p, .{}) catch |err| {
switch (err) {
std.fs.Dir.OpenError.NotDir => {
error.NotDir => {
const fpath = try self.filename_arena.allocator().dupe(u8, p);
try self.files.append(fpath);
continue;
},
else => {
return err;
},
else => return err,
}
};
defer subdir.close();

View file

@ -61,7 +61,11 @@ pub fn main() !u8 {
}
fn walkLocalWps(walker: *Walker, home_s: []const u8) !void {
const home = std.fs.cwd().openDir(home_s, .{}) catch return;
const local_wp = home.openIterableDir(".local/share/backgrounds/", .{}) catch return;
const wp_path = try std.fs.path.join(walker.files.allocator, &.{home_s, ".local/share/backgrounds"});
defer walker.files.allocator.free(wp_path);
var local_wp = try std.fs.cwd().openIterableDir(wp_path, .{});
defer local_wp.close();
try walker.walk(local_wp);
}

View file

@ -3,11 +3,7 @@ const c = @import("ffi.zig").c;
pub fn getHeadCount() !i32 {
const display_name = c.getenv("DISPLAY") orelse return error.DisplayNotSet;
const display = c.XOpenDisplay(display_name);
if (display == null) {
return error.CouldntOpenDisplay;
}
const display = c.XOpenDisplay(display_name) orelse return error.CouldntOpenDisplay;
defer _ = c.XCloseDisplay(display);
@ -16,11 +12,7 @@ pub fn getHeadCount() !i32 {
}
var screens: c_int = 0;
const info = c.XineramaQueryScreens(display, &screens);
if (info == null) {
return error.XineramaError;
}
const info = c.XineramaQueryScreens(display, &screens) orelse return error.XineramaError;
defer _ = c.XFree(info);
return screens;

View file

@ -36,9 +36,10 @@ pub fn init() !ClipboardConnection {
};
}
pub fn deinit(self: ClipboardConnection) void {
pub fn deinit(self: *ClipboardConnection) void {
_ = c.XDestroyWindow(self.dpy, self.win);
_ = c.XCloseDisplay(self.dpy);
self.* = undefined;
}
pub fn provide(self: ClipboardConnection, data: []const u8) !void {

View file

@ -27,7 +27,7 @@ pub fn xGetWindowName(dpy: *c.Display, win: c.Window) ?[]u8 {
var format: c_int = 0;
var n: c_ulong = 0;
var extra: c_ulong = 0;
var name_cstr: [*c]u8 = undefined;
var name_cstr: ?[*:0]u8 = null;
_ = c.XGetWindowProperty(
dpy,
win,
@ -43,8 +43,5 @@ pub fn xGetWindowName(dpy: *c.Display, win: c.Window) ?[]u8 {
&name_cstr,
);
if (name_cstr == null)
return null;
return name_cstr[0..@intCast(n)];
return (name_cstr orelse return null)[0..@intCast(n)];
}

View file

@ -27,7 +27,7 @@ pub fn main() !void {
);
defer alloc.free(filename);
const cp = try ClipboardConnection.init();
var cp = try ClipboardConnection.init();
defer cp.deinit();
const cp_data = try cp.getText();