3 Commits

Author SHA1 Message Date
fa1f013640 fix(ci): add libpci-dev for zig build
All checks were successful
Release / build (push) Successful in 37s
2026-02-24 17:18:23 +00:00
c14e14fc6c fix(ci): add libpci-dev for zig build 2026-02-24 17:18:13 +00:00
2854d2a922 ci: add release workflow for x86_64 builds
Some checks failed
Release / build (push) Failing after 19s
2026-02-24 16:57:29 +00:00
19 changed files with 413 additions and 513 deletions

View File

@@ -0,0 +1,48 @@
name: Release
on:
push:
tags:
- "v*"
permissions:
contents: write
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install dependencies
run: |
sudo apt-get update
sudo apt-get install -y libpci-dev zip
- name: Install Zig
uses: mlugg/setup-zig@v2
with:
version: 0.15.2
- name: Build
run: zig build -Doptimize=ReleaseSafe
- name: Package and release
env:
GITEA_TOKEN: ${{ secrets.RELEASE_TOKEN }}
run: |
cd zig-out/bin
zip ../../zigfetch-x86_64-linux.zip zigfetch
cd ../..
RELEASE_ID=$(curl -s -X POST "https://gitea.bitua.io/api/v1/repos/bitua/zigfetch/releases" \
-H "Authorization: token ${GITEA_TOKEN}" \
-H "Content-Type: application/json" \
-d "{\"tag_name\": \"${GITHUB_REF_NAME}\", \"name\": \"${GITHUB_REF_NAME}\"}" | jq -r .id)
echo "Release ID: $RELEASE_ID"
curl -s -X POST "https://gitea.bitua.io/api/v1/repos/bitua/zigfetch/releases/${RELEASE_ID}/assets?name=zigfetch-x86_64-linux.zip" \
-H "Authorization: token ${GITEA_TOKEN}" \
-F "attachment=@zigfetch-x86_64-linux.zip"

1
.gitignore vendored
View File

@@ -1,3 +1,2 @@
*zig-* *zig-*
result result
.tool-versions

View File

@@ -25,11 +25,13 @@ pub fn build(b: *std.Build) void {
}); });
if (target.result.os.tag == .macos) { if (target.result.os.tag == .macos) {
exe.root_module.linkFramework("CoreFoundation", .{ .needed = true }); exe.linkFramework("CoreFoundation");
exe.root_module.linkFramework("IOKit", .{ .needed = true }); exe.linkFramework("IOKit");
} else if (target.result.os.tag == .linux) { }
exe.root_module.link_libc = true;
exe.root_module.linkSystemLibrary("pci", .{ .needed = true }); if (target.result.os.tag == .linux) {
exe.linkLibC();
exe.linkSystemLibrary("pci");
} }
// This declares intent for the executable to be installed into the // This declares intent for the executable to be installed into the

View File

@@ -65,28 +65,28 @@ test "parse ffffff" {
try std.testing.expect((result.r == 255) and (result.g == 255) and (result.b == 255)); try std.testing.expect((result.r == 255) and (result.g == 255) and (result.b == 255));
} }
pub fn printAsciiAndModules(gpa: std.mem.Allocator, io: std.Io, ascii_art_path: ?[]u8, sys_info_list: std.array_list.Managed([]u8)) !void { pub fn printAsciiAndModules(allocator: std.mem.Allocator, ascii_art_path: ?[]u8, sys_info_list: std.array_list.Managed([]u8)) !void {
var stdout_buffer: [2048]u8 = undefined; var stdout_buffer: [2048]u8 = undefined;
var stdout_file_writer: std.Io.File.Writer = .init(.stdout(), io, &stdout_buffer); var stdout_writer = std.fs.File.stdout().writer(&stdout_buffer);
const stdout = &stdout_file_writer.interface; const stdout = &stdout_writer.interface;
var ascii_art_data: []const u8 = undefined; var ascii_art_data: []const u8 = undefined;
if (ascii_art_path) |ascii| { if (ascii_art_path) |ascii| {
const ascii_file = try std.Io.Dir.cwd().openFile(io, ascii, .{ .mode = .read_only }); const ascii_file = try std.fs.cwd().openFile(ascii, .{ .mode = .read_only });
defer ascii_file.close(io); defer ascii_file.close();
const file_size = (try ascii_file.stat(io)).size; const file_size = (try ascii_file.stat()).size;
ascii_art_data = try utils.readFile(gpa, io, ascii_file, file_size); ascii_art_data = try utils.readFile(allocator, ascii_file, file_size);
} else { } else {
ascii_art_data = @embedFile("./assets/ascii/guy_fawks.txt"); ascii_art_data = @embedFile("./assets/ascii/guy_fawks.txt");
} }
defer if (ascii_art_path != null) { defer if (ascii_art_path != null) {
gpa.free(ascii_art_data); allocator.free(ascii_art_data);
}; };
var lines = std.mem.splitScalar(u8, ascii_art_data, '\n'); var lines = std.mem.splitScalar(u8, ascii_art_data, '\n');
var ascii_art_content_list = std.array_list.Managed([]const u8).init(gpa); var ascii_art_content_list = std.array_list.Managed([]const u8).init(allocator);
defer ascii_art_content_list.deinit(); defer ascii_art_content_list.deinit();
while (lines.next()) |line| { while (lines.next()) |line| {
@@ -116,7 +116,7 @@ pub fn printAsciiAndModules(gpa: std.mem.Allocator, io: std.Io, ascii_art_path:
while (i < max_len) : (i += 1) { while (i < max_len) : (i += 1) {
// Print the ascii art if the width of the terminal is greater than the spacing (5) + the longest ascii art row length + the longest sys info string length // Print the ascii art if the width of the terminal is greater than the spacing (5) + the longest ascii art row length + the longest sys info string length
if (can_print_ascii_art) { if (can_print_ascii_art) {
const alignment_buffer = try gpa.alloc(u8, if (i < ascii_art_len) longest_ascii_art_row_len - (try utils.countCodepoints(ascii_art_items[i])) + spacing else longest_ascii_art_row_len + spacing); const alignment_buffer = try allocator.alloc(u8, if (i < ascii_art_len) longest_ascii_art_row_len - (try utils.countCodepoints(ascii_art_items[i])) + spacing else longest_ascii_art_row_len + spacing);
@memset(alignment_buffer, ' '); @memset(alignment_buffer, ' ');
if (i < ascii_art_len) { if (i < ascii_art_len) {
@@ -125,7 +125,7 @@ pub fn printAsciiAndModules(gpa: std.mem.Allocator, io: std.Io, ascii_art_path:
try stdout.print("{s}", .{alignment_buffer}); try stdout.print("{s}", .{alignment_buffer});
} }
gpa.free(alignment_buffer); allocator.free(alignment_buffer);
try stdout.flush(); try stdout.flush();
} }
@@ -151,6 +151,6 @@ pub fn printAsciiAndModules(gpa: std.mem.Allocator, io: std.Io, ascii_art_path:
} }
for (sys_info_list.items) |item| { for (sys_info_list.items) |item| {
gpa.free(item); allocator.free(item);
} }
} }

View File

@@ -1,5 +1,5 @@
const std = @import("std"); const std = @import("std");
const display = @import("display.zig"); const ascii = @import("ascii.zig");
const utils = @import("utils.zig"); const utils = @import("utils.zig");
pub const Module = struct { pub const Module = struct {
@@ -44,8 +44,8 @@ pub fn getUsernameHostnameColor(config: ?std.json.Parsed(Config)) ?[]u8 {
} else return null; } else return null;
} }
pub fn getModulesTypes(gpa: std.mem.Allocator, config: ?std.json.Parsed(Config)) !std.array_list.Managed(ModuleType) { pub fn getModulesTypes(allocator: std.mem.Allocator, config: ?std.json.Parsed(Config)) !std.array_list.Managed(ModuleType) {
var modules_list = std.array_list.Managed(ModuleType).init(gpa); var modules_list = std.array_list.Managed(ModuleType).init(allocator);
if (config) |c| { if (config) |c| {
for (c.value.modules) |module| { for (c.value.modules) |module| {
@@ -62,23 +62,23 @@ pub fn getModulesTypes(gpa: std.mem.Allocator, config: ?std.json.Parsed(Config))
return modules_list; return modules_list;
} }
pub fn readConfigFile(gpa: std.mem.Allocator, io: std.Io, environ: std.process.Environ) !?std.json.Parsed(Config) { pub fn readConfigFile(allocator: std.mem.Allocator) !?std.json.Parsed(Config) {
const home = try std.process.Environ.getAlloc(environ, gpa, "HOME"); const home = try std.process.getEnvVarOwned(allocator, "HOME");
defer gpa.free(home); defer allocator.free(home);
const config_abs_path = try std.mem.concat(gpa, u8, &.{ home, "/.config/zigfetch/config.json" }); const config_abs_path = try std.mem.concat(allocator, u8, &.{ home, "/.config/zigfetch/config.json" });
defer gpa.free(config_abs_path); defer allocator.free(config_abs_path);
const config_file = std.Io.Dir.openFileAbsolute(io, config_abs_path, .{ .mode = .read_only }) catch |err| switch (err) { const config_file = std.fs.openFileAbsolute(config_abs_path, .{ .mode = .read_only }) catch |err| switch (err) {
error.FileNotFound => return null, error.FileNotFound => return null,
else => return err, else => return err,
}; };
defer config_file.close(io); defer config_file.close();
const file_size = (try config_file.stat(io)).size; const file_size = (try config_file.stat()).size;
const config_data = try utils.readFile(gpa, io, config_file, file_size); const config_data = try utils.readFile(allocator, config_file, file_size);
defer gpa.free(config_data); defer allocator.free(config_data);
return try std.json.parseFromSlice(Config, gpa, config_data, .{ .allocate = .alloc_always }); return try std.json.parseFromSlice(Config, allocator, config_data, .{ .allocate = .alloc_always });
} }

View File

@@ -1,6 +1,6 @@
const builtin = @import("builtin"); const builtin = @import("builtin");
const std = @import("std"); const std = @import("std");
const display = @import("display.zig"); const ascii = @import("ascii.zig");
const detection = @import("detection.zig").os_module; const detection = @import("detection.zig").os_module;
const Result = union(enum) { const Result = union(enum) {
@@ -8,13 +8,7 @@ const Result = union(enum) {
string_arraylist: std.array_list.Managed([]u8), string_arraylist: std.array_list.Managed([]u8),
}; };
pub const FormatterContext = struct { pub const formatters = [_]*const fn (allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) anyerror!Result{
gpa: std.mem.Allocator,
io: std.Io,
environ: std.process.Environ,
};
pub const formatters = [_]*const fn (fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) anyerror!Result{
&getFormattedOsInfo, &getFormattedOsInfo,
&getFormattedKernelInfo, &getFormattedKernelInfo,
&getFormattedUptimeInfo, &getFormattedUptimeInfo,
@@ -32,7 +26,7 @@ pub const formatters = [_]*const fn (fmt_ctx: FormatterContext, key: []const u8,
&getFormattedCustom, &getFormattedCustom,
}; };
pub const default_formatters = [_]*const fn (fmt_ctx: FormatterContext) anyerror!Result{ pub const default_formatters = [_]*const fn (allocator: std.mem.Allocator) anyerror!Result{
&getDefaultFormattedOsInfo, &getDefaultFormattedOsInfo,
&getDefaultFormattedKernelInfo, &getDefaultFormattedKernelInfo,
&getDefaultFormattedUptimeInfo, &getDefaultFormattedUptimeInfo,
@@ -49,168 +43,101 @@ pub const default_formatters = [_]*const fn (fmt_ctx: FormatterContext) anyerror
&getDefaultFormattedLocaleInfo, &getDefaultFormattedLocaleInfo,
}; };
pub fn getFormattedUsernameHostname(gpa: std.mem.Allocator, color: []const u8, username: []const u8, hostname: []const u8) ![]u8 { pub fn getFormattedUsernameHostname(allocator: std.mem.Allocator, color: []const u8, username: []const u8, hostname: []const u8) ![]u8 {
return try std.fmt.allocPrint(gpa, "{s}{s}{s}@{s}{s}{s}", .{ return try std.fmt.allocPrint(allocator, "{s}{s}{s}@{s}{s}{s}", .{
color, color,
username, username,
display.Reset, ascii.Reset,
color, color,
hostname, hostname,
display.Reset, ascii.Reset,
}); });
} }
pub fn getDefaultFormattedKernelInfo(fmt_ctx: FormatterContext) !Result { pub fn getDefaultFormattedKernelInfo(allocator: std.mem.Allocator) !Result {
return try getFormattedKernelInfo(fmt_ctx, "Kernel", display.Yellow); return try getFormattedKernelInfo(allocator, "Kernel", ascii.Yellow);
} }
pub fn getFormattedKernelInfo(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedKernelInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
const allocator = fmt_ctx.gpa;
const kernel_info = try detection.system.getKernelInfo(allocator); const kernel_info = try detection.system.getKernelInfo(allocator);
defer allocator.free(kernel_info.kernel_name); defer allocator.free(kernel_info.kernel_name);
defer allocator.free(kernel_info.kernel_release); defer allocator.free(kernel_info.kernel_release);
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s} {s}", .{ return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s} {s}", .{ key_color, key, ascii.Reset, kernel_info.kernel_name, kernel_info.kernel_release }) };
key_color,
key,
display.Reset,
kernel_info.kernel_name,
kernel_info.kernel_release,
}) };
} }
pub fn getDefaultFormattedOsInfo(fmt_ctx: FormatterContext) !Result { pub fn getDefaultFormattedOsInfo(allocator: std.mem.Allocator) !Result {
return try getFormattedOsInfo(fmt_ctx, "OS", display.Yellow); return try getFormattedOsInfo(allocator, "OS", ascii.Yellow);
} }
pub fn getFormattedOsInfo(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedOsInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
const allocator = fmt_ctx.gpa; const os_info = try detection.system.getOsInfo(allocator);
const io = fmt_ctx.io;
const os_info = if (builtin.os.tag == .macos) try detection.system.getOsInfo(allocator) else if (builtin.os.tag == .linux) try detection.system.getOsInfo(allocator, io);
defer allocator.free(os_info); defer allocator.free(os_info);
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s}", .{ return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s}", .{ key_color, key, ascii.Reset, os_info }) };
key_color,
key,
display.Reset,
os_info,
}) };
} }
pub fn getDefaultFormattedLocaleInfo(fmt_ctx: FormatterContext) !Result { pub fn getDefaultFormattedLocaleInfo(allocator: std.mem.Allocator) !Result {
return try getFormattedLocaleInfo(fmt_ctx, "Locale", display.Yellow); return try getFormattedLocaleInfo(allocator, "Locale", ascii.Yellow);
} }
pub fn getFormattedLocaleInfo(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedLocaleInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
const allocator = fmt_ctx.gpa; const locale = try detection.system.getLocale(allocator);
const environ = fmt_ctx.environ;
const locale = try detection.system.getLocale(allocator, environ);
defer allocator.free(locale); defer allocator.free(locale);
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s}", .{ return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s}", .{ key_color, key, ascii.Reset, locale }) };
key_color,
key,
display.Reset,
locale,
}) };
} }
pub fn getDefaultFormattedUptimeInfo(fmt_ctx: FormatterContext) !Result { pub fn getDefaultFormattedUptimeInfo(allocator: std.mem.Allocator) !Result {
return try getFormattedUptimeInfo(fmt_ctx, "Uptime", display.Yellow); return try getFormattedUptimeInfo(allocator, "Uptime", ascii.Yellow);
} }
pub fn getFormattedUptimeInfo(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedUptimeInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
const allocator = fmt_ctx.gpa; const uptime = try detection.system.getSystemUptime();
const io = fmt_ctx.io; return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {} days, {} hours, {} minutes", .{ key_color, key, ascii.Reset, uptime.days, uptime.hours, uptime.minutes }) };
const uptime = if (builtin.os.tag == .macos) try detection.system.getSystemUptime(io) else if (builtin.os.tag == .linux) try detection.system.getSystemUptime();
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {} days, {} hours, {} minutes", .{
key_color,
key,
display.Reset,
uptime.days,
uptime.hours,
uptime.minutes,
}) };
} }
pub fn getDefaultFormattedPackagesInfo(fmt_ctx: FormatterContext) !Result { pub fn getDefaultFormattedPackagesInfo(allocator: std.mem.Allocator) !Result {
return try getFormattedPackagesInfo(fmt_ctx, "Packages", display.Yellow); return try getFormattedPackagesInfo(allocator, "Packages", ascii.Yellow);
} }
pub fn getFormattedPackagesInfo(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedPackagesInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
const allocator = fmt_ctx.gpa; const packages_info = try detection.packages.getPackagesInfo(allocator);
const io = fmt_ctx.io;
const environ = fmt_ctx.environ;
const packages_info = if (builtin.os.tag == .macos) try detection.packages.getPackagesInfo(allocator, io) else if (builtin.os.tag == .linux) try detection.packages.getPackagesInfo(allocator, io, environ);
defer allocator.free(packages_info); defer allocator.free(packages_info);
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s}{s}", .{ return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s}{s}", .{ key_color, key, ascii.Reset, packages_info }) };
key_color,
key,
display.Reset,
packages_info,
}) };
} }
pub fn getDefaultFormattedShellInfo(fmt_ctx: FormatterContext) !Result { pub fn getDefaultFormattedShellInfo(allocator: std.mem.Allocator) !Result {
return try getFormattedShellInfo(fmt_ctx, "Shell", display.Yellow); return try getFormattedShellInfo(allocator, "Shell", ascii.Yellow);
} }
pub fn getFormattedShellInfo(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedShellInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
const allocator = fmt_ctx.gpa; const shell = try detection.user.getShell(allocator);
const io = fmt_ctx.io;
const environ = fmt_ctx.environ;
const shell = try detection.user.getShell(allocator, io, environ);
defer allocator.free(shell); defer allocator.free(shell);
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s}", .{ return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s}", .{ key_color, key, ascii.Reset, shell[0..(shell.len - 1)] }) };
key_color,
key,
display.Reset,
shell[0..(shell.len - 1)],
}) };
} }
pub fn getDefaultFormattedCpuInfo(fmt_ctx: FormatterContext) !Result { pub fn getDefaultFormattedCpuInfo(allocator: std.mem.Allocator) !Result {
return try getFormattedCpuInfo(fmt_ctx, "Cpu", display.Yellow); return try getFormattedCpuInfo(allocator, "Cpu", ascii.Yellow);
} }
pub fn getFormattedCpuInfo(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedCpuInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
const allocator = fmt_ctx.gpa; const cpu_info = try detection.hardware.getCpuInfo(allocator);
const io = fmt_ctx.io;
const cpu_info = if (builtin.os.tag == .macos) try detection.hardware.getCpuInfo(allocator) else if (builtin.os.tag == .linux) try detection.hardware.getCpuInfo(allocator, io);
defer allocator.free(cpu_info.cpu_name); defer allocator.free(cpu_info.cpu_name);
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s} ({}) @ {d:.2} GHz", .{ return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s} ({}) @ {d:.2} GHz", .{ key_color, key, ascii.Reset, cpu_info.cpu_name, cpu_info.cpu_cores, cpu_info.cpu_max_freq }) };
key_color,
key,
display.Reset,
cpu_info.cpu_name,
cpu_info.cpu_cores,
cpu_info.cpu_max_freq,
}) };
} }
pub fn getDefaultFormattedGpuInfo(fmt_ctx: FormatterContext) !Result { pub fn getDefaultFormattedGpuInfo(allocator: std.mem.Allocator) !Result {
return try getFormattedGpuInfo(fmt_ctx, "Gpu", display.Yellow); if (builtin.os.tag == .macos) {
return try getFormattedGpuInfo(allocator, "Gpu", ascii.Yellow);
} else if (builtin.os.tag == .linux) {
return try getFormattedGpuInfo(allocator, "Gpu", ascii.Yellow);
}
} }
pub fn getFormattedGpuInfo(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedGpuInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
const allocator = fmt_ctx.gpa;
if (builtin.os.tag == .macos) { if (builtin.os.tag == .macos) {
const gpu_info = try detection.hardware.getGpuInfo(allocator); const gpu_info = try detection.hardware.getGpuInfo(allocator);
defer allocator.free(gpu_info.gpu_name); defer allocator.free(gpu_info.gpu_name);
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s} ({}) @ {d:.2} GHz", .{ return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s} ({}) @ {d:.2} GHz", .{ key_color, key, ascii.Reset, gpu_info.gpu_name, gpu_info.gpu_cores, gpu_info.gpu_freq }) };
key_color,
key,
display.Reset,
gpu_info.gpu_name,
gpu_info.gpu_cores,
gpu_info.gpu_freq,
}) };
} else if (builtin.os.tag == .linux) { } else if (builtin.os.tag == .linux) {
var formatted_gpu_info_list = std.array_list.Managed([]u8).init(allocator); var formatted_gpu_info_list = std.array_list.Managed([]u8).init(allocator);
@@ -219,21 +146,9 @@ pub fn getFormattedGpuInfo(fmt_ctx: FormatterContext, key: []const u8, key_color
for (gpu_info_list.items) |g| { for (gpu_info_list.items) |g| {
var formatted_gpu_info: []u8 = undefined; var formatted_gpu_info: []u8 = undefined;
if ((g.gpu_cores == 0) or (g.gpu_freq == 0.0)) { if ((g.gpu_cores == 0) or (g.gpu_freq == 0.0)) {
formatted_gpu_info = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s}", .{ formatted_gpu_info = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s}", .{ key_color, key, ascii.Reset, g.gpu_name });
key_color,
key,
display.Reset,
g.gpu_name,
});
} else { } else {
formatted_gpu_info = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s} ({}) @ {d:.2} GHz", .{ formatted_gpu_info = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s} ({}) @ {d:.2} GHz", .{ key_color, key, ascii.Reset, g.gpu_name, g.gpu_cores, g.gpu_freq });
key_color,
key,
display.Reset,
g.gpu_name,
g.gpu_cores,
g.gpu_freq,
});
} }
try formatted_gpu_info_list.append(formatted_gpu_info); try formatted_gpu_info_list.append(formatted_gpu_info);
allocator.free(g.gpu_name); allocator.free(g.gpu_name);
@@ -244,111 +159,67 @@ pub fn getFormattedGpuInfo(fmt_ctx: FormatterContext, key: []const u8, key_color
} }
} }
pub fn getDefaultFormattedRamInfo(fmt_ctx: FormatterContext) !Result { pub fn getDefaultFormattedRamInfo(allocator: std.mem.Allocator) !Result {
return try getFormattedRamInfo(fmt_ctx, "Ram", display.Yellow); return try getFormattedRamInfo(allocator, "Ram", ascii.Yellow);
} }
pub fn getFormattedRamInfo(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedRamInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
const allocator = fmt_ctx.gpa; const ram_info = if (builtin.os.tag == .macos) try detection.hardware.getRamInfo() else if (builtin.os.tag == .linux) try detection.hardware.getRamInfo(allocator);
const io = fmt_ctx.io; return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {d:.2} / {d:.2} GiB ({}%)", .{ key_color, key, ascii.Reset, ram_info.ram_usage, ram_info.ram_size, ram_info.ram_usage_percentage }) };
const ram_info = if (builtin.os.tag == .macos) try detection.hardware.getRamInfo() else if (builtin.os.tag == .linux) try detection.hardware.getRamInfo(allocator, io);
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {d:.2} / {d:.2} GiB ({}%)", .{
key_color,
key,
display.Reset,
ram_info.ram_usage,
ram_info.ram_size,
ram_info.ram_usage_percentage,
}) };
} }
pub fn getDefaultFormattedSwapInfo(fmt_ctx: FormatterContext) !Result { pub fn getDefaultFormattedSwapInfo(allocator: std.mem.Allocator) !Result {
return try getFormattedSwapInfo(fmt_ctx, "Swap", display.Yellow); return try getFormattedSwapInfo(allocator, "Swap", ascii.Yellow);
} }
pub fn getFormattedSwapInfo(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedSwapInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
const allocator = fmt_ctx.gpa; const swap_info = if (builtin.os.tag == .macos) try detection.hardware.getSwapInfo() else if (builtin.os.tag == .linux) try detection.hardware.getSwapInfo(allocator);
const io = fmt_ctx.io;
const swap_info = if (builtin.os.tag == .macos) try detection.hardware.getSwapInfo() else if (builtin.os.tag == .linux) try detection.hardware.getSwapInfo(allocator, io);
if (swap_info) |s| { if (swap_info) |s| {
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {d:.2} / {d:.2} GiB ({}%)", .{ return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {d:.2} / {d:.2} GiB ({}%)", .{ key_color, key, ascii.Reset, s.swap_usage, s.swap_size, s.swap_usage_percentage }) };
key_color,
key,
display.Reset,
s.swap_usage,
s.swap_size,
s.swap_usage_percentage,
}) };
} else { } else {
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} Disabled", .{ key_color, key, display.Reset }) }; return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} Disabled", .{ key_color, key, ascii.Reset }) };
} }
} }
pub fn getDefaultFormattedDiskInfo(fmt_ctx: FormatterContext) !Result { pub fn getDefaultFormattedDiskInfo(allocator: std.mem.Allocator) !Result {
return try getFormattedDiskInfo(fmt_ctx, "Disk", display.Yellow); return try getFormattedDiskInfo(allocator, "Disk", ascii.Yellow);
} }
pub fn getFormattedDiskInfo(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedDiskInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
const allocator = fmt_ctx.gpa;
const disk_info = try detection.hardware.getDiskSize("/"); const disk_info = try detection.hardware.getDiskSize("/");
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s} ({s}):{s} {d:.2} / {d:.2} GB ({}%)", .{ return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s} ({s}):{s} {d:.2} / {d:.2} GB ({}%)", .{ key_color, key, disk_info.disk_path, ascii.Reset, disk_info.disk_usage, disk_info.disk_size, disk_info.disk_usage_percentage }) };
key_color,
key,
disk_info.disk_path,
display.Reset,
disk_info.disk_usage,
disk_info.disk_size,
disk_info.disk_usage_percentage,
}) };
} }
pub fn getDefaultFormattedWindowManagerInfo(fmt_ctx: FormatterContext) !Result { pub fn getDefaultFormattedWindowManagerInfo(allocator: std.mem.Allocator) !Result {
return try getFormattedWindowManagerInfo(fmt_ctx, "WM", display.Yellow); return try getFormattedWindowManagerInfo(allocator, "WM", ascii.Yellow);
} }
pub fn getFormattedWindowManagerInfo(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedWindowManagerInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
const allocator = fmt_ctx.gpa; const wm = try detection.system.getWindowManagerInfo(allocator);
const io = fmt_ctx.io;
const wm = if (builtin.os.tag == .macos) try detection.system.getWindowManagerInfo(allocator) else if (builtin.os.tag == .linux) try detection.system.getWindowManagerInfo(allocator, io);
defer allocator.free(wm); defer allocator.free(wm);
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s}", .{ key_color, key, display.Reset, wm }) }; return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s}", .{ key_color, key, ascii.Reset, wm }) };
} }
pub fn getDefaultFormattedTerminalNameInfo(fmt_ctx: FormatterContext) !Result { pub fn getDefaultFormattedTerminalNameInfo(allocator: std.mem.Allocator) !Result {
return try getFormattedTerminalNameInfo(fmt_ctx, "Terminal", display.Yellow); return try getFormattedTerminalNameInfo(allocator, "Terminal", ascii.Yellow);
} }
pub fn getFormattedTerminalNameInfo(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedTerminalNameInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
const allocator = fmt_ctx.gpa; const terminal_name = try detection.user.getTerminalName(allocator);
const environ = fmt_ctx.environ;
const terminal_name = try detection.user.getTerminalName(allocator, environ);
defer allocator.free(terminal_name); defer allocator.free(terminal_name);
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s}", .{ key_color, key, display.Reset, terminal_name }) }; return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s}", .{ key_color, key, ascii.Reset, terminal_name }) };
} }
pub fn getDefaultFormattedNetInfo(fmt_ctx: FormatterContext) !Result { pub fn getDefaultFormattedNetInfo(allocator: std.mem.Allocator) !Result {
return try getFormattedNetInfo(fmt_ctx, "Local IP", display.Yellow); return try getFormattedNetInfo(allocator, "Local IP", ascii.Yellow);
} }
pub fn getFormattedNetInfo(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedNetInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
const allocator = fmt_ctx.gpa;
var formatted_net_info_list = std.array_list.Managed([]u8).init(allocator); var formatted_net_info_list = std.array_list.Managed([]u8).init(allocator);
var net_info_list = try detection.network.getNetInfo(allocator); var net_info_list = try detection.network.getNetInfo(allocator);
for (net_info_list.items) |n| { for (net_info_list.items) |n| {
try formatted_net_info_list.append(try std.fmt.allocPrint(allocator, "{s}{s} ({s}):{s} {s}", .{ try formatted_net_info_list.append(try std.fmt.allocPrint(allocator, "{s}{s} ({s}):{s} {s}", .{ key_color, key, n.interface_name, ascii.Reset, n.ipv4_addr }));
key_color,
key,
n.interface_name,
display.Reset,
n.ipv4_addr,
}));
allocator.free(n.interface_name); allocator.free(n.interface_name);
allocator.free(n.ipv4_addr); allocator.free(n.ipv4_addr);
} }
@@ -357,8 +228,6 @@ pub fn getFormattedNetInfo(fmt_ctx: FormatterContext, key: []const u8, key_color
return Result{ .string_arraylist = formatted_net_info_list }; return Result{ .string_arraylist = formatted_net_info_list };
} }
pub fn getFormattedCustom(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedCustom(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
const allocator = fmt_ctx.gpa; return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}{s}", .{ key_color, key, ascii.Reset }) };
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}{s}", .{ key_color, key, display.Reset }) };
} }

View File

@@ -40,13 +40,13 @@ pub const DiskInfo = struct {
disk_usage_percentage: u8, disk_usage_percentage: u8,
}; };
pub fn getCpuInfo(gpa: std.mem.Allocator, io: std.Io) !CpuInfo { pub fn getCpuInfo(allocator: std.mem.Allocator) !CpuInfo {
const cpu_cores = c_unistd.sysconf(c_unistd._SC_NPROCESSORS_ONLN); const cpu_cores = c_unistd.sysconf(c_unistd._SC_NPROCESSORS_ONLN);
// Reads /proc/cpuinfo // Reads /proc/cpuinfo
const cpuinfo_path = "/proc/cpuinfo"; const cpuinfo_path = "/proc/cpuinfo";
const cpuinfo_file = try std.Io.Dir.cwd().openFile(io, cpuinfo_path, .{ .mode = .read_only }); const cpuinfo_file = try std.fs.cwd().openFile(cpuinfo_path, .{ .mode = .read_only });
defer cpuinfo_file.close(io); defer cpuinfo_file.close();
// NOTE: procfs is a pseudo-filesystem, so it is not possible to determine the size of a file // NOTE: procfs is a pseudo-filesystem, so it is not possible to determine the size of a file
// https://docs.kernel.org/filesystems/proc.html // https://docs.kernel.org/filesystems/proc.html
@@ -54,8 +54,8 @@ pub fn getCpuInfo(gpa: std.mem.Allocator, io: std.Io) !CpuInfo {
// //
// Only the first section (core 0) will be parsed // Only the first section (core 0) will be parsed
// 512 is more than enough // 512 is more than enough
const cpuinfo_data = try utils.readFile(gpa, io, cpuinfo_file, 512); const cpuinfo_data = try utils.readFile(allocator, cpuinfo_file, 512);
defer gpa.free(cpuinfo_data); defer allocator.free(cpuinfo_data);
// Parsing /proc/cpuinfo // Parsing /proc/cpuinfo
var model_name: ?[]const u8 = null; var model_name: ?[]const u8 = null;
@@ -90,18 +90,18 @@ pub fn getCpuInfo(gpa: std.mem.Allocator, io: std.Io) !CpuInfo {
var cmf_exists: bool = true; var cmf_exists: bool = true;
// Checks if /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq exists // Checks if /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq exists
_ = std.Io.Dir.accessAbsolute(io, cpuinfo_max_freq_path, .{ .read = true }) catch |err| { _ = std.fs.accessAbsolute(cpuinfo_max_freq_path, .{ .mode = .read_only }) catch |err| {
if (err == std.Io.Dir.AccessError.FileNotFound) { if (err == std.posix.AccessError.FileNotFound) {
cmf_exists = false; cmf_exists = false;
} }
}; };
if (cmf_exists) { if (cmf_exists) {
// Reads /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq // Reads /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq
const maxfreq_file = try std.Io.Dir.cwd().openFile(io, cpuinfo_max_freq_path, .{ .mode = .read_only }); const maxfreq_file = try std.fs.cwd().openFile(cpuinfo_max_freq_path, .{ .mode = .read_only });
defer maxfreq_file.close(io); defer maxfreq_file.close();
const maxfreq_data = try utils.readFile(gpa, io, maxfreq_file, 32); const maxfreq_data = try utils.readFile(allocator, maxfreq_file, 32);
defer gpa.free(maxfreq_data); defer allocator.free(maxfreq_data);
// Parsing /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq // Parsing /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq
const trimmed = std.mem.trim(u8, maxfreq_data, " \n\r"); const trimmed = std.mem.trim(u8, maxfreq_data, " \n\r");
@@ -115,14 +115,14 @@ pub fn getCpuInfo(gpa: std.mem.Allocator, io: std.Io) !CpuInfo {
} }
return CpuInfo{ return CpuInfo{
.cpu_name = try gpa.dupe(u8, model_name orelse "Unknown"), .cpu_name = try allocator.dupe(u8, model_name orelse "Unknown"),
.cpu_cores = @as(i32, @intCast(cpu_cores)), .cpu_cores = @as(i32, @intCast(cpu_cores)),
.cpu_max_freq = cpu_max_freq, .cpu_max_freq = cpu_max_freq,
}; };
} }
pub fn getGpuInfo(gpa: std.mem.Allocator) !std.array_list.Managed(GpuInfo) { pub fn getGpuInfo(allocator: std.mem.Allocator) !std.array_list.Managed(GpuInfo) {
var gpu_info_list = std.array_list.Managed(GpuInfo).init(gpa); var gpu_info_list = std.array_list.Managed(GpuInfo).init(allocator);
const display_controller = 0x03; const display_controller = 0x03;
@@ -151,13 +151,13 @@ pub fn getGpuInfo(gpa: std.mem.Allocator) !std.array_list.Managed(GpuInfo) {
devices.*.device_id, devices.*.device_id,
); );
const gpu_name = try gpa.dupe(u8, std.mem.span(name)); const gpu_name = try allocator.dupe(u8, std.mem.span(name));
const maybe_parsed_gpu_name = try parseGpuName(gpa, gpu_name); const maybe_parsed_gpu_name = try parseGpuName(allocator, gpu_name);
var parsed_gpu_name: []u8 = undefined; var parsed_gpu_name: []u8 = undefined;
if (maybe_parsed_gpu_name != null) { if (maybe_parsed_gpu_name != null) {
gpa.free(gpu_name); allocator.free(gpu_name);
parsed_gpu_name = maybe_parsed_gpu_name.?; parsed_gpu_name = maybe_parsed_gpu_name.?;
} else { } else {
parsed_gpu_name = gpu_name; parsed_gpu_name = gpu_name;
@@ -173,7 +173,7 @@ pub fn getGpuInfo(gpa: std.mem.Allocator) !std.array_list.Managed(GpuInfo) {
if (gpu_info_list.items.len == 0) { if (gpu_info_list.items.len == 0) {
try gpu_info_list.append(GpuInfo{ try gpu_info_list.append(GpuInfo{
.gpu_name = try gpa.dupe(u8, "Unknown"), .gpu_name = try allocator.dupe(u8, "Unknown"),
.gpu_cores = 0, .gpu_cores = 0,
.gpu_freq = 0.0, .gpu_freq = 0.0,
}); });
@@ -182,24 +182,24 @@ pub fn getGpuInfo(gpa: std.mem.Allocator) !std.array_list.Managed(GpuInfo) {
return gpu_info_list; return gpu_info_list;
} }
fn parseGpuName(gpa: std.mem.Allocator, name: []u8) !?[]u8 { fn parseGpuName(allocator: std.mem.Allocator, name: []u8) !?[]u8 {
// NOTE: for references: https://github.com/pciutils/pciutils/blob/master/pci.ids // NOTE: for references: https://github.com/pciutils/pciutils/blob/master/pci.ids
if (std.mem.startsWith(u8, name, "Advanced Micro Devices, Inc. [AMD/ATI]")) { if (std.mem.startsWith(u8, name, "Advanced Micro Devices, Inc. [AMD/ATI]")) {
const size = std.mem.replacementSize(u8, name, "Advanced Micro Devices, Inc. [AMD/ATI]", "AMD"); const size = std.mem.replacementSize(u8, name, "Advanced Micro Devices, Inc. [AMD/ATI]", "AMD");
const parsed_gpu_name = try gpa.alloc(u8, size); const parsed_gpu_name = try allocator.alloc(u8, size);
_ = std.mem.replace(u8, name, "Advanced Micro Devices, Inc. [AMD/ATI]", "AMD", parsed_gpu_name); _ = std.mem.replace(u8, name, "Advanced Micro Devices, Inc. [AMD/ATI]", "AMD", parsed_gpu_name);
return parsed_gpu_name; return parsed_gpu_name;
} else if (std.mem.startsWith(u8, name, "Intel Corporation")) { } else if (std.mem.startsWith(u8, name, "Intel Corporation")) {
const size = std.mem.replacementSize(u8, name, "Intel Corporation", "Intel"); const size = std.mem.replacementSize(u8, name, "Intel Corporation", "Intel");
const parsed_gpu_name = try gpa.alloc(u8, size); const parsed_gpu_name = try allocator.alloc(u8, size);
_ = std.mem.replace(u8, name, "Intel Corporation", "Intel", parsed_gpu_name); _ = std.mem.replace(u8, name, "Intel Corporation", "Intel", parsed_gpu_name);
return parsed_gpu_name; return parsed_gpu_name;
} else if (std.mem.startsWith(u8, name, "NVIDIA Corporation")) { } else if (std.mem.startsWith(u8, name, "NVIDIA Corporation")) {
const size = std.mem.replacementSize(u8, name, "NVIDIA Corporation", "NVIDIA"); const size = std.mem.replacementSize(u8, name, "NVIDIA Corporation", "NVIDIA");
const parsed_gpu_name = try gpa.alloc(u8, size); const parsed_gpu_name = try allocator.alloc(u8, size);
_ = std.mem.replace(u8, name, "NVIDIA Corporation", "NVIDIA", parsed_gpu_name); _ = std.mem.replace(u8, name, "NVIDIA Corporation", "NVIDIA", parsed_gpu_name);
return parsed_gpu_name; return parsed_gpu_name;
@@ -208,11 +208,11 @@ fn parseGpuName(gpa: std.mem.Allocator, name: []u8) !?[]u8 {
return null; return null;
} }
pub fn getRamInfo(gpa: std.mem.Allocator, io: std.Io) !RamInfo { pub fn getRamInfo(allocator: std.mem.Allocator) !RamInfo {
// Reads /proc/meminfo // Reads /proc/meminfo
const meminfo_path = "/proc/meminfo"; const meminfo_path = "/proc/meminfo";
const meminfo_file = try std.Io.Dir.cwd().openFile(io, meminfo_path, .{ .mode = .read_only }); const meminfo_file = try std.fs.cwd().openFile(meminfo_path, .{ .mode = .read_only });
defer meminfo_file.close(io); defer meminfo_file.close();
// NOTE: procfs is a pseudo-filesystem, so it is not possible to determine the size of a file // NOTE: procfs is a pseudo-filesystem, so it is not possible to determine the size of a file
// https://docs.kernel.org/filesystems/proc.html // https://docs.kernel.org/filesystems/proc.html
@@ -220,8 +220,8 @@ pub fn getRamInfo(gpa: std.mem.Allocator, io: std.Io) !RamInfo {
// //
// We only need to read the first few lines // We only need to read the first few lines
// 512 is more than enough // 512 is more than enough
const meminfo_data = try utils.readFile(gpa, io, meminfo_file, 512); const meminfo_data = try utils.readFile(allocator, meminfo_file, 512);
defer gpa.free(meminfo_data); defer allocator.free(meminfo_data);
// Parsing /proc/meminfo // Parsing /proc/meminfo
var total_mem: f64 = 0.0; var total_mem: f64 = 0.0;
@@ -277,11 +277,11 @@ pub fn getRamInfo(gpa: std.mem.Allocator, io: std.Io) !RamInfo {
}; };
} }
pub fn getSwapInfo(gpa: std.mem.Allocator, io: std.Io) !?SwapInfo { pub fn getSwapInfo(allocator: std.mem.Allocator) !?SwapInfo {
// Reads /proc/meminfo // Reads /proc/meminfo
const meminfo_path = "/proc/meminfo"; const meminfo_path = "/proc/meminfo";
const meminfo_file = try std.Io.Dir.cwd().openFile(io, meminfo_path, .{ .mode = .read_only }); const meminfo_file = try std.fs.cwd().openFile(meminfo_path, .{ .mode = .read_only });
defer meminfo_file.close(io); defer meminfo_file.close();
// NOTE: procfs is a pseudo-filesystem, so it is not possible to determine the size of a file // NOTE: procfs is a pseudo-filesystem, so it is not possible to determine the size of a file
// https://docs.kernel.org/filesystems/proc.html // https://docs.kernel.org/filesystems/proc.html
@@ -289,8 +289,8 @@ pub fn getSwapInfo(gpa: std.mem.Allocator, io: std.Io) !?SwapInfo {
// //
// We only need to read the first few lines // We only need to read the first few lines
// 512 is ok // 512 is ok
const meminfo_data = try utils.readFile(gpa, io, meminfo_file, 512); const meminfo_data = try utils.readFile(allocator, meminfo_file, 512);
defer gpa.free(meminfo_data); defer allocator.free(meminfo_data);
// Parsing /proc/meminfo // Parsing /proc/meminfo
var total_swap: f64 = 0.0; var total_swap: f64 = 0.0;

View File

@@ -11,8 +11,8 @@ pub const NetInfo = struct {
ipv4_addr: []u8, ipv4_addr: []u8,
}; };
pub fn getNetInfo(gpa: std.mem.Allocator) !std.array_list.Managed(NetInfo) { pub fn getNetInfo(allocator: std.mem.Allocator) !std.array_list.Managed(NetInfo) {
var net_info_list = std.array_list.Managed(NetInfo).init(gpa); var net_info_list = std.array_list.Managed(NetInfo).init(allocator);
var ifap: ?*c_ifaddrs.ifaddrs = null; var ifap: ?*c_ifaddrs.ifaddrs = null;
if (c_ifaddrs.getifaddrs(&ifap) != 0) { if (c_ifaddrs.getifaddrs(&ifap) != 0) {
@@ -35,8 +35,8 @@ pub fn getNetInfo(gpa: std.mem.Allocator) !std.array_list.Managed(NetInfo) {
const ip_str = c_inet.inet_ntop(c_inet.AF_INET, &addr_in.sin_addr, &ip_buf, c_inet.INET_ADDRSTRLEN); const ip_str = c_inet.inet_ntop(c_inet.AF_INET, &addr_in.sin_addr, &ip_buf, c_inet.INET_ADDRSTRLEN);
if (ip_str) |ip| { if (ip_str) |ip| {
try net_info_list.append(NetInfo{ try net_info_list.append(NetInfo{
.interface_name = try gpa.dupe(u8, std.mem.span(ifa.ifa_name)), .interface_name = try allocator.dupe(u8, std.mem.span(ifa.ifa_name)),
.ipv4_addr = try gpa.dupe(u8, std.mem.span(ip)), .ipv4_addr = try allocator.dupe(u8, std.mem.span(ip)),
}); });
} }
} }

View File

@@ -1,15 +1,15 @@
const std = @import("std"); const std = @import("std");
const utils = @import("../utils.zig"); const utils = @import("../utils.zig");
pub fn getPackagesInfo(gpa: std.mem.Allocator, io: std.Io, environ: std.process.Environ) ![]const u8 { pub fn getPackagesInfo(allocator: std.mem.Allocator) ![]const u8 {
var packages_info = std.array_list.Managed(u8).init(gpa); var packages_info = std.array_list.Managed(u8).init(allocator);
defer packages_info.deinit(); defer packages_info.deinit();
const flatpak_packages = countFlatpakPackages(io) catch |err| if (err == error.FileNotFound) 0 else return err; const flatpak_packages = countFlatpakPackages() catch |err| if (err == error.FileNotFound) 0 else return err;
const nix_packages = countNixPackages(gpa, io, environ) catch 0; const nix_packages = countNixPackages(allocator) catch 0;
const dpkg_packages = countDpkgPackages(gpa, io) catch |err| if (err == error.FileNotFound) 0 else return err; const dpkg_packages = countDpkgPackages(allocator) catch |err| if (err == error.FileNotFound) 0 else return err;
const pacman_packages = countPacmanPackages(io) catch |err| if (err == error.FileNotFound) 0 else return err; const pacman_packages = countPacmanPackages() catch |err| if (err == error.FileNotFound) 0 else return err;
const xbps_packages = countXbpsPackages(gpa, io) catch |err| if (err == error.FileNotFound) 0 else return err; const xbps_packages = countXbpsPackages(allocator) catch |err| if (err == error.FileNotFound) 0 else return err;
var buffer: [32]u8 = undefined; var buffer: [32]u8 = undefined;
@@ -33,32 +33,32 @@ pub fn getPackagesInfo(gpa: std.mem.Allocator, io: std.Io, environ: std.process.
try packages_info.appendSlice(try std.fmt.bufPrint(&buffer, " Xbps: {d}", .{xbps_packages})); try packages_info.appendSlice(try std.fmt.bufPrint(&buffer, " Xbps: {d}", .{xbps_packages}));
} }
return try gpa.dupe(u8, packages_info.items); return try allocator.dupe(u8, packages_info.items);
} }
fn countFlatpakPackages(io: std.Io) !usize { fn countFlatpakPackages() !usize {
const flatpak_apps = try countFlatpakApps(io); const flatpak_apps = try countFlatpakApps();
const flatpak_runtimes = try countFlatpakRuntimes(io); const flatpak_runtimes = try countFlatpakRuntimes();
return flatpak_apps + flatpak_runtimes; return flatpak_apps + flatpak_runtimes;
} }
fn countFlatpakApps(io: std.Io) !usize { fn countFlatpakApps() !usize {
var dir = try std.Io.Dir.openDirAbsolute(io, "/var/lib/flatpak/app/", .{ .iterate = true }); var dir = try std.fs.openDirAbsolute("/var/lib/flatpak/app/", .{ .iterate = true });
defer dir.close(io); defer dir.close();
var iter = dir.iterate(); var iter = dir.iterate();
var count: usize = 0; var count: usize = 0;
while (try iter.next(io)) |e| { while (try iter.next()) |e| {
if (e.kind != .directory) continue; if (e.kind != .directory) continue;
var sub_dir = try dir.openDir(io, e.name, .{}); var sub_dir = try dir.openDir(e.name, .{});
defer sub_dir.close(io); defer sub_dir.close();
var current = sub_dir.openDir(io, "current", .{}) catch continue; var current = sub_dir.openDir("current", .{}) catch continue;
defer current.close(io); defer current.close();
// If `current` was opened successfully, increment the count // If `current` was opened successfully, increment the count
count += 1; count += 1;
@@ -67,27 +67,27 @@ fn countFlatpakApps(io: std.Io) !usize {
return count; return count;
} }
fn countFlatpakRuntimes(io: std.Io) !usize { fn countFlatpakRuntimes() !usize {
var dir = try std.Io.Dir.openDirAbsolute(io, "/var/lib/flatpak/runtime/", .{ .iterate = true }); var dir = try std.fs.openDirAbsolute("/var/lib/flatpak/runtime/", .{ .iterate = true });
defer dir.close(io); defer dir.close();
var iter = dir.iterate(); var iter = dir.iterate();
var counter: usize = 0; var counter: usize = 0;
while (try iter.next(io)) |e| { while (try iter.next()) |e| {
if (std.mem.endsWith(u8, e.name, ".Locale") or std.mem.endsWith(u8, e.name, ".Debug")) continue; if (std.mem.endsWith(u8, e.name, ".Locale") or std.mem.endsWith(u8, e.name, ".Debug")) continue;
var arch_dir = try dir.openDir(io, e.name, .{ .iterate = true }); var arch_dir = try dir.openDir(e.name, .{ .iterate = true });
defer arch_dir.close(io); defer arch_dir.close();
var arch_iter = arch_dir.iterate(); var arch_iter = arch_dir.iterate();
while (try arch_iter.next(io)) |arch_e| { while (try arch_iter.next()) |arch_e| {
if (arch_e.kind != .directory) continue; if (arch_e.kind != .directory) continue;
var sub_dir = try arch_dir.openDir(io, arch_e.name, .{ .iterate = true }); var sub_dir = try arch_dir.openDir(arch_e.name, .{ .iterate = true });
defer sub_dir.close(io); defer sub_dir.close();
var sub_iter = sub_dir.iterate(); var sub_iter = sub_dir.iterate();
while (try sub_iter.next(io)) |_| { while (try sub_iter.next()) |_| {
counter += 1; counter += 1;
} }
} }
@@ -96,35 +96,35 @@ fn countFlatpakRuntimes(io: std.Io) !usize {
return counter; return counter;
} }
fn countNixPackages(gpa: std.mem.Allocator, io: std.Io, environ: std.process.Environ) !usize { fn countNixPackages(allocator: std.mem.Allocator) !usize {
// `/run/current-system` is a sym-link, so we need to obtein the real path // `/run/current-system` is a sym-link, so we need to obtein the real path
const real_path = try std.Io.Dir.realPathFileAbsoluteAlloc(io, "/run/current-system", gpa); const real_path = try std.fs.realpathAlloc(allocator, "/run/current-system");
defer gpa.free(real_path); defer allocator.free(real_path);
var hash: [32]u8 = undefined; var hash: [32]u8 = undefined;
std.crypto.hash.Blake3.hash(real_path, &hash, .{}); std.crypto.hash.Blake3.hash(real_path, &hash, .{});
const hash_hex = try std.fmt.allocPrint(gpa, "{x}", .{hash}); const hash_hex = try std.fmt.allocPrint(allocator, "{x}", .{hash});
defer gpa.free(hash_hex); defer allocator.free(hash_hex);
var count: usize = 0; var count: usize = 0;
// Inspired by https://github.com/fastfetch-cli/fastfetch/blob/608382109cda6623e53f318e8aced54cf8e5a042/src/detection/packages/packages_nix.c#L81 // Inspired by https://github.com/fastfetch-cli/fastfetch/blob/608382109cda6623e53f318e8aced54cf8e5a042/src/detection/packages/packages_nix.c#L81
count = checkNixCache(gpa, io, environ, hash_hex) catch |err| switch (err) { count = checkNixCache(allocator, hash_hex) catch |err| switch (err) {
error.FileNotFound, error.InvalidCache => { error.FileNotFound, error.InvalidCache => {
// nix-store --query --requisites /run/current-system | wc -l // nix-store --query --requisites /run/current-system | wc -l
const result = try std.process.run(gpa, io, .{ .argv = &[_][]const u8{ const result = try std.process.Child.run(.{ .allocator = allocator, .argv = &[_][]const u8{
"sh", "sh",
"-c", "-c",
"nix-store --query --requisites /run/current-system | wc -l", "nix-store --query --requisites /run/current-system | wc -l",
} }); } });
const result_trimmed = std.mem.trim(u8, result.stdout, "\n"); const result_trimmed = std.mem.trim(u8, result.stdout, "\n");
defer gpa.free(result.stdout); defer allocator.free(result.stdout);
defer gpa.free(result.stderr); defer allocator.free(result.stderr);
count = try std.fmt.parseInt(usize, result_trimmed, 10); count = try std.fmt.parseInt(usize, result_trimmed, 10);
try writeNixCache(gpa, io, environ, hash_hex, count); try writeNixCache(allocator, hash_hex, count);
return count; return count;
}, },
@@ -134,57 +134,45 @@ fn countNixPackages(gpa: std.mem.Allocator, io: std.Io, environ: std.process.Env
return count; return count;
} }
fn getNixCachePath(gpa: std.mem.Allocator, environ: std.process.Environ) ![]const u8 { fn getNixCachePath(allocator: std.mem.Allocator) ![]const u8 {
const cache_dir_path = try getUnixCachePath(gpa, environ); var cache_dir_path = std.process.getEnvVarOwned(allocator, "XDG_CACHE_HOME") catch try allocator.dupe(u8, "");
defer gpa.free(cache_dir_path);
return try std.fs.path.join(gpa, &.{ cache_dir_path, "zigfetch", "nix" });
}
fn getUnixCachePath(gpa: std.mem.Allocator, environ: std.process.Environ) ![]const u8 {
var cache_dir_path = std.process.Environ.getAlloc(environ, gpa, "XDG_CACHE_HOME") catch try gpa.dupe(u8, "");
if (cache_dir_path.len == 0) { if (cache_dir_path.len == 0) {
gpa.free(cache_dir_path); allocator.free(cache_dir_path);
const home = try std.process.Environ.getAlloc(environ, gpa, "HOME"); const home = try std.process.getEnvVarOwned(allocator, "HOME");
defer gpa.free(home); defer allocator.free(home);
cache_dir_path = try std.fs.path.join(gpa, &.{ home, ".cache" }); cache_dir_path = try std.fs.path.join(allocator, &.{ home, ".cache", "zigfetch", "nix" });
} else {
cache_dir_path = try std.fs.path.join(allocator, &.{ cache_dir_path, "zigfetch", "nix" });
} }
return cache_dir_path; return cache_dir_path;
} }
fn writeNixCache(gpa: std.mem.Allocator, io: std.Io, environ: std.process.Environ, hash: []const u8, count: usize) !void { fn writeNixCache(allocator: std.mem.Allocator, hash: []const u8, count: usize) !void {
const nix_cache_dir_path = try getNixCachePath(gpa, environ); const cache_dir_path = try getNixCachePath(allocator);
defer gpa.free(nix_cache_dir_path); defer allocator.free(cache_dir_path);
std.Io.Dir.accessAbsolute(io, nix_cache_dir_path, .{ .read = true }) catch { try std.fs.cwd().makePath(cache_dir_path);
const cache_dir_path = try getUnixCachePath(gpa, environ); var cache_dir = try std.fs.cwd().openDir(cache_dir_path, .{});
defer gpa.free(cache_dir_path); defer cache_dir.close();
var cache_file = try cache_dir.createFile("nix_cache", .{ .truncate = true });
defer cache_file.close();
const cache_dir = try std.Io.Dir.openDirAbsolute(io, cache_dir_path, .{}); const cache_content = try std.fmt.allocPrint(allocator, "{s}\n{d}", .{ hash, count });
try cache_dir.createDirPath(io, "zigfetch/nix"); defer allocator.free(cache_content);
}; try cache_file.writeAll(cache_content);
var nix_cache_dir = try std.Io.Dir.openDirAbsolute(io, nix_cache_dir_path, .{});
defer nix_cache_dir.close(io);
var cache_file = try nix_cache_dir.createFile(io, "nix_cache", .{ .truncate = true });
defer cache_file.close(io);
const cache_content = try std.fmt.allocPrint(gpa, "{s}\n{d}\n", .{ hash, count });
defer gpa.free(cache_content);
try cache_file.writePositionalAll(io, cache_content, 0);
} }
fn checkNixCache(gpa: std.mem.Allocator, io: std.Io, environ: std.process.Environ, hash: []const u8) !usize { fn checkNixCache(allocator: std.mem.Allocator, hash: []const u8) !usize {
const cache_dir_path = try getNixCachePath(gpa, environ); const cache_dir_path = try getNixCachePath(allocator);
defer gpa.free(cache_dir_path); defer allocator.free(cache_dir_path);
var cache_dir = try std.Io.Dir.openDirAbsolute(io, cache_dir_path, .{}); var cache_dir = try std.fs.cwd().openDir(cache_dir_path, .{});
defer cache_dir.close(io); defer cache_dir.close();
var cache_file = try cache_dir.openFile(io, "nix_cache", .{ .mode = .read_only }); var cache_file = try cache_dir.openFile("nix_cache", .{ .mode = .read_only });
defer cache_file.close(io); const cache_size = (try cache_file.stat()).size;
const cache_size = (try cache_file.stat(io)).size; const cache_content = try utils.readFile(allocator, cache_file, cache_size);
const cache_content = try utils.readFile(gpa, io, cache_file, cache_size); defer allocator.free(cache_content);
defer gpa.free(cache_content);
var cache_iter = std.mem.splitScalar(u8, cache_content, '\n'); var cache_iter = std.mem.splitScalar(u8, cache_content, '\n');
@@ -197,14 +185,14 @@ fn checkNixCache(gpa: std.mem.Allocator, io: std.Io, environ: std.process.Enviro
return std.fmt.parseInt(usize, cache_iter.next().?, 10); return std.fmt.parseInt(usize, cache_iter.next().?, 10);
} }
fn countDpkgPackages(gpa: std.mem.Allocator, io: std.Io) !usize { fn countDpkgPackages(allocator: std.mem.Allocator) !usize {
const dpkg_status_path = "/var/lib/dpkg/status"; const dpkg_status_path = "/var/lib/dpkg/status";
const dpkg_file = try std.Io.Dir.openFileAbsolute(io, dpkg_status_path, .{ .mode = .read_only }); const dpkg_file = try std.fs.cwd().openFile(dpkg_status_path, .{ .mode = .read_only });
defer dpkg_file.close(io); defer dpkg_file.close();
const file_size = (try dpkg_file.stat(io)).size; const file_size = (try dpkg_file.stat()).size;
const content = try utils.readFile(gpa, io, dpkg_file, file_size); const content = try utils.readFile(allocator, dpkg_file, file_size);
defer gpa.free(content); defer allocator.free(content);
var count: usize = 0; var count: usize = 0;
var iter = std.mem.splitSequence(u8, content, "\n\n"); var iter = std.mem.splitSequence(u8, content, "\n\n");
@@ -217,27 +205,27 @@ fn countDpkgPackages(gpa: std.mem.Allocator, io: std.Io) !usize {
return count - 1; return count - 1;
} }
fn countPacmanPackages(io: std.Io) !usize { fn countPacmanPackages() !usize {
// Subtruct 1 to remove `ALPM_DB_VERSION` from the count // Subtruct 1 to remove `ALPM_DB_VERSION` from the count
return try utils.countEntries(io, "/var/lib/pacman/local") - 1; return try utils.countEntries("/var/lib/pacman/local") - 1;
} }
fn countXbpsPackages(gpa: std.mem.Allocator, io: std.Io) !usize { fn countXbpsPackages(allocator: std.mem.Allocator) !usize {
var dir = try std.Io.Dir.openDirAbsolute(io, "/var/db/xbps/", .{ .iterate = true }); var dir = try std.fs.openDirAbsolute("/var/db/xbps/", .{ .iterate = true });
defer dir.close(io); defer dir.close();
var count: usize = 0; var count: usize = 0;
var dir_iter = dir.iterate(); var dir_iter = dir.iterate();
while (try dir_iter.next(io)) |e| { while (try dir_iter.next()) |e| {
if ((e.kind == .file) and std.mem.startsWith(u8, e.name, "pkgdb-")) { if ((e.kind == .file) and std.mem.startsWith(u8, e.name, "pkgdb-")) {
const pkgdb_file = try dir.openFile(io, e.name, .{ .mode = .read_only }); const pkgdb_file = try dir.openFile(e.name, .{ .mode = .read_only });
defer pkgdb_file.close(io); defer pkgdb_file.close();
const file_size = (try pkgdb_file.stat(io)).size; const file_size = (try pkgdb_file.stat()).size;
const content = try utils.readFile(gpa, io, pkgdb_file, file_size); const content = try utils.readFile(allocator, pkgdb_file, file_size);
defer gpa.free(content); defer allocator.free(content);
var file_iter = std.mem.splitSequence(u8, content, "<string>installed</string>"); var file_iter = std.mem.splitSequence(u8, content, "<string>installed</string>");
// TODO: find a way to avoid this loop // TODO: find a way to avoid this loop

View File

@@ -16,18 +16,18 @@ pub const KernelInfo = struct {
kernel_release: []u8, kernel_release: []u8,
}; };
pub fn getHostname(gpa: std.mem.Allocator) ![]u8 { pub fn getHostname(allocator: std.mem.Allocator) ![]u8 {
var buf: [std.posix.HOST_NAME_MAX]u8 = undefined; var buf: [std.posix.HOST_NAME_MAX]u8 = undefined;
const hostnameEnv = try std.posix.gethostname(&buf); const hostnameEnv = try std.posix.gethostname(&buf);
const hostname = try gpa.dupe(u8, hostnameEnv); const hostname = try allocator.dupe(u8, hostnameEnv);
return hostname; return hostname;
} }
pub fn getLocale(gpa: std.mem.Allocator, environ: std.process.Environ) ![]u8 { pub fn getLocale(allocator: std.mem.Allocator) ![]u8 {
const locale = std.process.Environ.getAlloc(environ, gpa, "LANG") catch |err| if (err == error.EnvironmentVariableNotFound) { const locale = std.process.getEnvVarOwned(allocator, "LANG") catch |err| if (err == error.EnvironmentVariableNotFound) {
return gpa.dupe(u8, "Unknown"); return allocator.dupe(u8, "Unknown");
} else return err; } else return err;
return locale; return locale;
} }
@@ -64,25 +64,25 @@ pub fn getSystemUptime() !SystemUptime {
}; };
} }
pub fn getKernelInfo(gpa: std.mem.Allocator) !KernelInfo { pub fn getKernelInfo(allocator: std.mem.Allocator) !KernelInfo {
var uts: c_utsname.struct_utsname = undefined; var uts: c_utsname.struct_utsname = undefined;
if (c_utsname.uname(&uts) != 0) { if (c_utsname.uname(&uts) != 0) {
return error.UnameFailed; return error.UnameFailed;
} }
return KernelInfo{ return KernelInfo{
.kernel_name = try gpa.dupe(u8, std.mem.sliceTo(&uts.sysname, 0)), .kernel_name = try allocator.dupe(u8, std.mem.sliceTo(&uts.sysname, 0)),
.kernel_release = try gpa.dupe(u8, std.mem.sliceTo(&uts.release, 0)), .kernel_release = try allocator.dupe(u8, std.mem.sliceTo(&uts.release, 0)),
}; };
} }
pub fn getOsInfo(gpa: std.mem.Allocator, io: std.Io) ![]u8 { pub fn getOsInfo(allocator: std.mem.Allocator) ![]u8 {
const os_release_path = "/etc/os-release"; const os_release_path = "/etc/os-release";
const os_release_file = try std.Io.Dir.cwd().openFile(io, os_release_path, .{ .mode = .read_only }); const os_release_file = try std.fs.cwd().openFile(os_release_path, .{ .mode = .read_only });
defer os_release_file.close(io); defer os_release_file.close();
const size = (try os_release_file.stat(io)).size; const size = (try os_release_file.stat()).size;
const os_release_data = try utils.readFile(gpa, io, os_release_file, size); const os_release_data = try utils.readFile(allocator, os_release_file, size);
defer gpa.free(os_release_data); defer allocator.free(os_release_data);
var pretty_name: ?[]const u8 = null; var pretty_name: ?[]const u8 = null;
@@ -98,18 +98,18 @@ pub fn getOsInfo(gpa: std.mem.Allocator, io: std.Io) ![]u8 {
} }
} }
return try gpa.dupe(u8, pretty_name orelse "Unknown"); return try allocator.dupe(u8, pretty_name orelse "Unknown");
} }
pub fn getWindowManagerInfo(gpa: std.mem.Allocator, io: std.Io) ![]const u8 { pub fn getWindowManagerInfo(allocator: std.mem.Allocator) ![]const u8 {
var dir = try std.Io.Dir.cwd().openDir(io, "/proc/", .{ .iterate = true }); var dir = try std.fs.cwd().openDir("/proc/", .{ .iterate = true });
defer dir.close(io); defer dir.close();
var wm_name: ?[]const u8 = null; var wm_name: ?[]const u8 = null;
var iter = dir.iterate(); var iter = dir.iterate();
wm_name = outer: { wm_name = outer: {
while (try iter.next(io)) |entry| { while (try iter.next()) |entry| {
if (entry.kind != .directory) continue; if (entry.kind != .directory) continue;
// Check if the entry name is numeric // Check if the entry name is numeric
@@ -117,12 +117,12 @@ pub fn getWindowManagerInfo(gpa: std.mem.Allocator, io: std.Io) ![]const u8 {
var buf: [1024]u8 = undefined; var buf: [1024]u8 = undefined;
const file_name = try std.fmt.bufPrint(&buf, "/proc/{s}/comm", .{entry.name}); const file_name = try std.fmt.bufPrint(&buf, "/proc/{s}/comm", .{entry.name});
const file = try std.Io.Dir.cwd().openFile(io, file_name, .{ .mode = .read_only }); const file = try std.fs.cwd().openFile(file_name, .{ .mode = .read_only });
defer file.close(io); defer file.close();
// NOTE: https://stackoverflow.com/questions/23534263/what-is-the-maximum-allowed-limit-on-the-length-of-a-process-name // NOTE: https://stackoverflow.com/questions/23534263/what-is-the-maximum-allowed-limit-on-the-length-of-a-process-name
const proc_name = try utils.readFile(gpa, io, file, 16); const proc_name = try utils.readFile(allocator, file, 16);
defer gpa.free(proc_name); defer allocator.free(proc_name);
const proc_name_trimmed = std.mem.trim(u8, proc_name, "\n"); const proc_name_trimmed = std.mem.trim(u8, proc_name, "\n");
@@ -143,7 +143,7 @@ pub fn getWindowManagerInfo(gpa: std.mem.Allocator, io: std.Io) ![]const u8 {
inline for (supported_wms) |wm| { inline for (supported_wms) |wm| {
if (std.ascii.eqlIgnoreCase(wm, proc_name_trimmed)) { if (std.ascii.eqlIgnoreCase(wm, proc_name_trimmed)) {
break :outer try gpa.dupe(u8, proc_name_trimmed); break :outer try allocator.dupe(u8, proc_name_trimmed);
} }
} }
} }
@@ -151,5 +151,5 @@ pub fn getWindowManagerInfo(gpa: std.mem.Allocator, io: std.Io) ![]const u8 {
break :outer null; break :outer null;
}; };
return wm_name orelse gpa.dupe(u8, "Unknown"); return wm_name orelse allocator.dupe(u8, "Unknown");
} }

View File

@@ -1,23 +1,24 @@
const std = @import("std"); const std = @import("std");
pub fn getUsername(gpa: std.mem.Allocator, environ: std.process.Environ) ![]u8 { pub fn getUsername(allocator: std.mem.Allocator) ![]u8 {
return try std.process.Environ.getAlloc(environ, gpa, "USER"); const username = try std.process.getEnvVarOwned(allocator, "USER");
return username;
} }
pub fn getShell(gpa: std.mem.Allocator, io: std.Io, environ: std.process.Environ) ![]u8 { pub fn getShell(allocator: std.mem.Allocator) ![]u8 {
const shell = std.process.Environ.getAlloc(environ, gpa, "SHELL") catch |err| if (err == error.EnvironmentVariableNotFound) { const shell = std.process.getEnvVarOwned(allocator, "SHELL") catch |err| if (err == error.EnvironmentVariableNotFound) {
return gpa.dupe(u8, "Unknown"); return allocator.dupe(u8, "Unknown");
} else return err; } else return err;
defer gpa.free(shell); defer allocator.free(shell);
const result = try std.process.run(gpa, io, .{ .argv = &[_][]const u8{ shell, "--version" } }); const result = try std.process.Child.run(.{ .allocator = allocator, .argv = &[_][]const u8{ shell, "--version" } });
const result_stdout = result.stdout; const result_stdout = result.stdout;
if (std.mem.indexOf(u8, shell, "bash") != null) { if (std.mem.indexOf(u8, shell, "bash") != null) {
const bash_version = parseBashVersion(result_stdout); const bash_version = parseBashVersion(result_stdout);
defer gpa.free(result_stdout); defer allocator.free(result_stdout);
return try std.fmt.allocPrint(gpa, "{s} {s}", .{ "bash", bash_version.? }); return try std.fmt.allocPrint(allocator, "{s} {s}", .{ "bash", bash_version.? });
} }
return result_stdout; return result_stdout;
@@ -31,12 +32,12 @@ fn parseBashVersion(shell_version_output: []u8) ?[]u8 {
const version_keyword_index = std.mem.indexOf(u8, shell_version_output[0..end_index.?], version_keyword); const version_keyword_index = std.mem.indexOf(u8, shell_version_output[0..end_index.?], version_keyword);
if (version_keyword_index == null) return null; if (version_keyword_index == null) return null;
return shell_version_output[version_keyword_index.? + version_keyword.len .. end_index.? + 1]; return shell_version_output[version_keyword_index.? + version_keyword.len .. end_index.?];
} }
pub fn getTerminalName(gpa: std.mem.Allocator, environ: std.process.Environ) ![]u8 { pub fn getTerminalName(allocator: std.mem.Allocator) ![]u8 {
const term_program = std.process.Environ.getAlloc(environ, gpa, "TERM_PROGRAM") catch |err| if (err == error.EnvironmentVariableNotFound) { const term_program = std.process.getEnvVarOwned(allocator, "TERM_PROGRAM") catch |err| if (err == error.EnvironmentVariableNotFound) {
return gpa.dupe(u8, "Unknown"); return allocator.dupe(u8, "Unknown");
} else return err; } else return err;
return term_program; return term_program;
} }

View File

@@ -42,7 +42,7 @@ pub const DiskInfo = struct {
disk_usage_percentage: u8, disk_usage_percentage: u8,
}; };
pub fn getCpuInfo(gpa: std.mem.Allocator) !CpuInfo { pub fn getCpuInfo(allocator: std.mem.Allocator) !CpuInfo {
var size: usize = 0; var size: usize = 0;
// First call to sysctlbyname to get the size of the string // First call to sysctlbyname to get the size of the string
@@ -50,8 +50,8 @@ pub fn getCpuInfo(gpa: std.mem.Allocator) !CpuInfo {
return error.FailedToGetCpuNameSize; return error.FailedToGetCpuNameSize;
} }
const cpu_name: []u8 = try gpa.alloc(u8, size - 1); const cpu_name: []u8 = try allocator.alloc(u8, size - 1);
errdefer gpa.free(cpu_name); errdefer allocator.free(cpu_name);
// Second call to sysctlbyname to get the CPU name // Second call to sysctlbyname to get the CPU name
if (c_sysctl.sysctlbyname("machdep.cpu.brand_string", cpu_name.ptr, &size, null, 0) != 0) { if (c_sysctl.sysctlbyname("machdep.cpu.brand_string", cpu_name.ptr, &size, null, 0) != 0) {
@@ -66,8 +66,8 @@ pub fn getCpuInfo(gpa: std.mem.Allocator) !CpuInfo {
} }
// Get cpu architecture // Get cpu architecture
const arch: []u8 = try getCpuArch(gpa); const arch: []u8 = try getCpuArch(allocator);
defer gpa.free(arch); defer allocator.free(arch);
var cpu_freq_mhz: f64 = 0.0; var cpu_freq_mhz: f64 = 0.0;
@@ -82,22 +82,22 @@ pub fn getCpuInfo(gpa: std.mem.Allocator) !CpuInfo {
return CpuInfo{ .cpu_name = cpu_name, .cpu_cores = n_cpu, .cpu_max_freq = cpu_freq_ghz }; return CpuInfo{ .cpu_name = cpu_name, .cpu_cores = n_cpu, .cpu_max_freq = cpu_freq_ghz };
} }
fn getCpuArch(gpa: std.mem.Allocator) ![]u8 { fn getCpuArch(allocator: std.mem.Allocator) ![]u8 {
var size: usize = 0; var size: usize = 0;
if (c_sysctl.sysctlbyname("hw.machine", null, &size, null, 0) != 0) { if (c_sysctl.sysctlbyname("hw.machine", null, &size, null, 0) != 0) {
return error.SysctlbynameFailed; return error.SysctlbynameFailed;
} }
const machine: []u8 = try gpa.alloc(u8, size); const machine: []u8 = try allocator.alloc(u8, size);
if (c_sysctl.sysctlbyname("hw.machine", machine.ptr, &size, null, 0) != 0) { if (c_sysctl.sysctlbyname("hw.machine", machine.ptr, &size, null, 0) != 0) {
return error.SysctlbynameFailed; return error.SysctlbynameFailed;
} }
defer gpa.free(machine); defer allocator.free(machine);
return gpa.dupe(u8, std.mem.sliceTo(machine, 0)); return allocator.dupe(u8, std.mem.sliceTo(machine, 0));
} }
fn getCpuFreqAppleSilicon() !f64 { fn getCpuFreqAppleSilicon() !f64 {
@@ -184,11 +184,11 @@ pub fn getCpuFreqIntel() f64 {
return freq / 1_000_000.0; return freq / 1_000_000.0;
} }
pub fn getGpuInfo(gpa: std.mem.Allocator) !GpuInfo { pub fn getGpuInfo(allocator: std.mem.Allocator) !GpuInfo {
// TODO: add support for non-Apple Silicon Macs // TODO: add support for non-Apple Silicon Macs
var gpu_info = GpuInfo{ var gpu_info = GpuInfo{
.gpu_name = try gpa.dupe(u8, "Unknown"), .gpu_name = try allocator.dupe(u8, "Unknown"),
.gpu_cores = 0, .gpu_cores = 0,
.gpu_freq = 0.0, .gpu_freq = 0.0,
}; };
@@ -236,11 +236,11 @@ pub fn getGpuInfo(gpa: std.mem.Allocator) !GpuInfo {
if (c_iokit.CFDictionaryGetValueIfPresent(@as(c_iokit.CFDictionaryRef, @ptrCast(properties_ptr)), model_key, &name_ref) == c_iokit.TRUE) { if (c_iokit.CFDictionaryGetValueIfPresent(@as(c_iokit.CFDictionaryRef, @ptrCast(properties_ptr)), model_key, &name_ref) == c_iokit.TRUE) {
if (c_iokit.CFGetTypeID(name_ref) == c_iokit.CFStringGetTypeID()) { if (c_iokit.CFGetTypeID(name_ref) == c_iokit.CFStringGetTypeID()) {
const accel_name = utils.cfTypeRefToZigString(gpa, name_ref) catch { const accel_name = utils.cfTypeRefToZigString(allocator, name_ref) catch {
return gpu_info; return gpu_info;
}; };
gpa.free(gpu_info.gpu_name); allocator.free(gpu_info.gpu_name);
gpu_info.gpu_name = accel_name; gpu_info.gpu_name = accel_name;
} }
} }
@@ -262,8 +262,8 @@ pub fn getGpuInfo(gpa: std.mem.Allocator) !GpuInfo {
} }
// Get cpu architecture // Get cpu architecture
const arch: []u8 = try getCpuArch(gpa); const arch: []u8 = try getCpuArch(allocator);
defer gpa.free(arch); defer allocator.free(arch);
var gpu_freq_mhz: f64 = 0.0; var gpu_freq_mhz: f64 = 0.0;

View File

@@ -11,8 +11,8 @@ pub const NetInfo = struct {
ipv4_addr: []u8, ipv4_addr: []u8,
}; };
pub fn getNetInfo(gpa: std.mem.Allocator) !std.array_list.Managed(NetInfo) { pub fn getNetInfo(allocator: std.mem.Allocator) !std.array_list.Managed(NetInfo) {
var net_info_list = std.array_list.Managed(NetInfo).init(gpa); var net_info_list = std.array_list.Managed(NetInfo).init(allocator);
var ifap: ?*c_ifaddrs.ifaddrs = null; var ifap: ?*c_ifaddrs.ifaddrs = null;
if (c_ifaddrs.getifaddrs(&ifap) != 0) { if (c_ifaddrs.getifaddrs(&ifap) != 0) {
@@ -35,8 +35,8 @@ pub fn getNetInfo(gpa: std.mem.Allocator) !std.array_list.Managed(NetInfo) {
const ip_str = c_inet.inet_ntop(c_inet.AF_INET, &addr_in.sin_addr, &ip_buf, c_inet.INET_ADDRSTRLEN); const ip_str = c_inet.inet_ntop(c_inet.AF_INET, &addr_in.sin_addr, &ip_buf, c_inet.INET_ADDRSTRLEN);
if (ip_str) |ip| { if (ip_str) |ip| {
try net_info_list.append(NetInfo{ try net_info_list.append(NetInfo{
.interface_name = try gpa.dupe(u8, std.mem.span(ifa.ifa_name)), .interface_name = try allocator.dupe(u8, std.mem.span(ifa.ifa_name)),
.ipv4_addr = try gpa.dupe(u8, std.mem.span(ip)), .ipv4_addr = try allocator.dupe(u8, std.mem.span(ip)),
}); });
} }
} }

View File

@@ -1,13 +1,13 @@
const std = @import("std"); const std = @import("std");
const utils = @import("../utils.zig"); const utils = @import("../utils.zig");
pub fn getPackagesInfo(gpa: std.mem.Allocator, io: std.Io) ![]const u8 { pub fn getPackagesInfo(allocator: std.mem.Allocator) ![]const u8 {
var packages_info = std.array_list.Managed(u8).init(gpa); var packages_info = std.array_list.Managed(u8).init(allocator);
defer packages_info.deinit(); defer packages_info.deinit();
const homebrew_packages = countHomebrewPackages(io) catch |err| if (err == error.FileNotFound) 0 else return err; const homebrew_packages = countHomebrewPackages() catch |err| if (err == error.FileNotFound) 0 else return err;
const homebrew_casks = countHomebrewCasks(io) catch |err| if (err == error.FileNotFound) 0 else return err; const homebrew_casks = countHomebrewCasks() catch |err| if (err == error.FileNotFound) 0 else return err;
const macports_packages = countMacportPackages(io) catch |err| if (err == error.FileNotFound) 0 else return err; const macports_packages = countMacportPackages() catch |err| if (err == error.FileNotFound) 0 else return err;
var buffer: [32]u8 = undefined; var buffer: [32]u8 = undefined;
@@ -23,17 +23,17 @@ pub fn getPackagesInfo(gpa: std.mem.Allocator, io: std.Io) ![]const u8 {
try packages_info.appendSlice(try std.fmt.bufPrint(&buffer, " macports: {d}", .{macports_packages})); try packages_info.appendSlice(try std.fmt.bufPrint(&buffer, " macports: {d}", .{macports_packages}));
} }
return try gpa.dupe(u8, packages_info.items); return try allocator.dupe(u8, packages_info.items);
} }
fn countHomebrewPackages(io: std.Io) !usize { fn countHomebrewPackages() !usize {
return try utils.countEntries(io, "/opt/homebrew/Cellar"); return try utils.countEntries("/opt/homebrew/Cellar");
} }
fn countHomebrewCasks(io: std.Io) !usize { fn countHomebrewCasks() !usize {
return try utils.countEntries(io, "/opt/homebrew/Caskroom"); return try utils.countEntries("/opt/homebrew/Caskroom");
} }
fn countMacportPackages(io: std.Io) !usize { fn countMacportPackages() !usize {
return try utils.countEntries(io, "/opt/local/bin"); return try utils.countEntries("/opt/local/bin");
} }

View File

@@ -16,18 +16,18 @@ pub const KernelInfo = struct {
}; };
/// Returns the hostname. /// Returns the hostname.
pub fn getHostname(gpa: std.mem.Allocator) ![]u8 { pub fn getHostname(allocator: std.mem.Allocator) ![]u8 {
var buf: [std.posix.HOST_NAME_MAX]u8 = undefined; var buf: [std.posix.HOST_NAME_MAX]u8 = undefined;
const hostnameEnv = try std.posix.gethostname(&buf); const hostnameEnv = try std.posix.gethostname(&buf);
const hostname = try gpa.dupe(u8, hostnameEnv); const hostname = try allocator.dupe(u8, hostnameEnv);
return hostname; return hostname;
} }
pub fn getLocale(gpa: std.mem.Allocator, environ: std.process.Environ) ![]u8 { pub fn getLocale(allocator: std.mem.Allocator) ![]u8 {
const locale = std.process.Environ.getAlloc(environ, gpa, "LANG") catch |err| if (err == error.EnvironmentVariableNotFound) { const locale = std.process.getEnvVarOwned(allocator, "LANG") catch |err| if (err == error.EnvironmentVariableNotFound) {
return gpa.dupe(u8, "Unknown"); return allocator.dupe(u8, "Unknown");
} else return err; } else return err;
return locale; return locale;
} }
@@ -35,7 +35,7 @@ pub fn getLocale(gpa: std.mem.Allocator, environ: std.process.Environ) ![]u8 {
/// Returns the system uptime. /// Returns the system uptime.
/// ///
/// Uses `sysctl` to fetch the system boot time and calculates the elapsed time. /// Uses `sysctl` to fetch the system boot time and calculates the elapsed time.
pub fn getSystemUptime(io: std.Io) !SystemUptime { pub fn getSystemUptime() !SystemUptime {
const seconds_per_day: f64 = 86400.0; const seconds_per_day: f64 = 86400.0;
const hours_per_day: f64 = 24.0; const hours_per_day: f64 = 24.0;
const seconds_per_hour: f64 = 3600.0; const seconds_per_hour: f64 = 3600.0;
@@ -49,7 +49,7 @@ pub fn getSystemUptime(io: std.Io) !SystemUptime {
var name = [_]c_int{ c_sysctl.CTL_KERN, c_sysctl.KERN_BOOTTIME }; var name = [_]c_int{ c_sysctl.CTL_KERN, c_sysctl.KERN_BOOTTIME };
if (c_sysctl.sysctl(&name, name.len, &boot_time, &size, null, 0) == 0) { if (c_sysctl.sysctl(&name, name.len, &boot_time, &size, null, 0) == 0) {
const boot_seconds = @as(f64, @floatFromInt(boot_time.tv_sec)); const boot_seconds = @as(f64, @floatFromInt(boot_time.tv_sec));
const now_seconds = @as(f64, @floatFromInt(std.Io.Timestamp.now(io, .real).toSeconds())); const now_seconds = @as(f64, @floatFromInt(std.time.timestamp()));
uptime_seconds = now_seconds - boot_seconds; uptime_seconds = now_seconds - boot_seconds;
} else { } else {
return error.UnableToGetSystemUptime; return error.UnableToGetSystemUptime;
@@ -71,7 +71,7 @@ pub fn getSystemUptime(io: std.Io) !SystemUptime {
}; };
} }
pub fn getKernelInfo(gpa: std.mem.Allocator) !KernelInfo { pub fn getKernelInfo(allocator: std.mem.Allocator) !KernelInfo {
var size: usize = 0; var size: usize = 0;
// --- KERNEL NAME --- // --- KERNEL NAME ---
@@ -80,8 +80,8 @@ pub fn getKernelInfo(gpa: std.mem.Allocator) !KernelInfo {
return error.FailedToGetKernelNameSize; return error.FailedToGetKernelNameSize;
} }
const kernel_type: []u8 = try gpa.alloc(u8, size - 1); const kernel_type: []u8 = try allocator.alloc(u8, size - 1);
errdefer gpa.free(kernel_type); errdefer allocator.free(kernel_type);
// Second call to sysctlbyname to get the kernel name // Second call to sysctlbyname to get the kernel name
if (c_sysctl.sysctlbyname("kern.ostype", kernel_type.ptr, &size, null, 0) != 0) { if (c_sysctl.sysctlbyname("kern.ostype", kernel_type.ptr, &size, null, 0) != 0) {
@@ -94,8 +94,8 @@ pub fn getKernelInfo(gpa: std.mem.Allocator) !KernelInfo {
return error.FailedToGetKernelReleaseSize; return error.FailedToGetKernelReleaseSize;
} }
const os_release: []u8 = try gpa.alloc(u8, size - 1); const os_release: []u8 = try allocator.alloc(u8, size - 1);
errdefer gpa.free(os_release); errdefer allocator.free(os_release);
// Second call to sysctlbyname to get the kernel release // Second call to sysctlbyname to get the kernel release
if (c_sysctl.sysctlbyname("kern.osrelease", os_release.ptr, &size, null, 0) != 0) { if (c_sysctl.sysctlbyname("kern.osrelease", os_release.ptr, &size, null, 0) != 0) {
@@ -108,7 +108,7 @@ pub fn getKernelInfo(gpa: std.mem.Allocator) !KernelInfo {
}; };
} }
pub fn getOsInfo(gpa: std.mem.Allocator) ![]u8 { pub fn getOsInfo(allocator: std.mem.Allocator) ![]u8 {
var size: usize = 0; var size: usize = 0;
// First call to sysctlbyname to get the size of the string // First call to sysctlbyname to get the size of the string
@@ -116,20 +116,20 @@ pub fn getOsInfo(gpa: std.mem.Allocator) ![]u8 {
return error.FailedToGetCpuNameSize; return error.FailedToGetCpuNameSize;
} }
const os_version: []u8 = try gpa.alloc(u8, size - 1); const os_version: []u8 = try allocator.alloc(u8, size - 1);
defer gpa.free(os_version); defer allocator.free(os_version);
// Second call to sysctlbyname to get the os version // Second call to sysctlbyname to get the os version
if (c_sysctl.sysctlbyname("kern.osproductversion", os_version.ptr, &size, null, 0) != 0) { if (c_sysctl.sysctlbyname("kern.osproductversion", os_version.ptr, &size, null, 0) != 0) {
return error.FailedToGetOsVersion; return error.FailedToGetOsVersion;
} }
const os_info = try std.fmt.allocPrint(gpa, "macOS {s}", .{os_version}); const os_info = try std.fmt.allocPrint(allocator, "macOS {s}", .{os_version});
return os_info; return os_info;
} }
pub fn getWindowManagerInfo(gpa: std.mem.Allocator) ![]const u8 { pub fn getWindowManagerInfo(allocator: std.mem.Allocator) ![]const u8 {
var name = [_]c_int{ c_sysctl.CTL_KERN, c_sysctl.KERN_PROC, c_sysctl.KERN_PROC_ALL }; var name = [_]c_int{ c_sysctl.CTL_KERN, c_sysctl.KERN_PROC, c_sysctl.KERN_PROC_ALL };
var size: usize = 0; var size: usize = 0;
@@ -138,8 +138,8 @@ pub fn getWindowManagerInfo(gpa: std.mem.Allocator) ![]const u8 {
return error.SysctlFailed; return error.SysctlFailed;
} }
const buffer: []u8 = try gpa.alloc(u8, size); const buffer: []u8 = try allocator.alloc(u8, size);
defer gpa.free(buffer); defer allocator.free(buffer);
// Second call to retrieve process data // Second call to retrieve process data
if (c_sysctl.sysctl(&name, name.len, buffer.ptr, &size, null, 0) != 0) { if (c_sysctl.sysctl(&name, name.len, buffer.ptr, &size, null, 0) != 0) {
@@ -173,8 +173,8 @@ pub fn getWindowManagerInfo(gpa: std.mem.Allocator) ![]const u8 {
var pathbuf: [c_libproc.PROC_PIDPATHINFO_MAXSIZE]u8 = undefined; var pathbuf: [c_libproc.PROC_PIDPATHINFO_MAXSIZE]u8 = undefined;
// c_libproc.proc_pidpath saves the process name in `pathbuf` and returns the len // c_libproc.proc_pidpath saves the process name in `pathbuf` and returns the len
const path_len = @as(usize, @intCast(c_libproc.proc_pidpath(pid, &pathbuf, pathbuf.len))); const path_len = @as(usize, @intCast(c_libproc.proc_pidpath(pid, &pathbuf, pathbuf.len)));
const proc_pathname = if (path_len > 0) try gpa.dupe(u8, pathbuf[0..@intCast(path_len)]) else try gpa.dupe(u8, "unknown"); const proc_pathname = if (path_len > 0) try allocator.dupe(u8, pathbuf[0..@intCast(path_len)]) else try allocator.dupe(u8, "unknown");
defer gpa.free(proc_pathname); defer allocator.free(proc_pathname);
inline for (supported_wms) |wm| { inline for (supported_wms) |wm| {
if (std.ascii.endsWithIgnoreCase(proc_pathname, wm)) { if (std.ascii.endsWithIgnoreCase(proc_pathname, wm)) {
@@ -183,7 +183,7 @@ pub fn getWindowManagerInfo(gpa: std.mem.Allocator) ![]const u8 {
else else
proc_pathname; proc_pathname;
break :outer try gpa.dupe(u8, basename); break :outer try allocator.dupe(u8, basename);
} }
} }
} }
@@ -191,5 +191,5 @@ pub fn getWindowManagerInfo(gpa: std.mem.Allocator) ![]const u8 {
break :outer null; break :outer null;
}; };
return wm_name orelse gpa.dupe(u8, "Quartz Compositor"); return wm_name orelse allocator.dupe(u8, "Quartz Compositor");
} }

View File

@@ -3,24 +3,25 @@ const std = @import("std");
/// Returns the current logged-in user's username. /// Returns the current logged-in user's username.
/// Uses the environment variable `USER`. /// Uses the environment variable `USER`.
/// The caller is responsible for freeing the allocated memory. /// The caller is responsible for freeing the allocated memory.
pub fn getUsername(gpa: std.mem.Allocator, environ: std.process.Environ) ![]u8 { pub fn getUsername(allocator: std.mem.Allocator) ![]u8 {
return try std.process.Environ.getAlloc(environ, gpa, "USER"); const username = try std.process.getEnvVarOwned(allocator, "USER");
return username;
} }
pub fn getShell(gpa: std.mem.Allocator, io: std.Io, environ: std.process.Environ) ![]u8 { pub fn getShell(allocator: std.mem.Allocator) ![]u8 {
const shell = std.process.Environ.getAlloc(environ, gpa, "SHELL") catch |err| if (err == error.EnvironmentVariableNotFound) { const shell = std.process.getEnvVarOwned(allocator, "SHELL") catch |err| if (err == error.EnvironmentVariableNotFound) {
return gpa.dupe(u8, "Unknown"); return allocator.dupe(u8, "Unknown");
} else return err; } else return err;
defer gpa.free(shell); defer allocator.free(shell);
const result = try std.process.run(gpa, io, .{ .argv = &[_][]const u8{ shell, "--version" } }); const result = try std.process.Child.run(.{ .allocator = allocator, .argv = &[_][]const u8{ shell, "--version" } });
const result_stdout = result.stdout; const result_stdout = result.stdout;
if (std.mem.indexOf(u8, shell, "bash") != null) { if (std.mem.indexOf(u8, shell, "bash") != null) {
const bash_version = parseBashVersion(result_stdout); const bash_version = parseBashVersion(result_stdout);
defer gpa.free(result_stdout); defer allocator.free(result_stdout);
return try std.fmt.allocPrint(gpa, "{s} {s}", .{ "bash", bash_version.? }); return try std.fmt.allocPrint(allocator, "{s} {s}", .{ "bash", bash_version.? });
} }
return result_stdout; return result_stdout;
@@ -37,9 +38,9 @@ fn parseBashVersion(shell_version_output: []u8) ?[]u8 {
return shell_version_output[version_keyword_index.? + version_keyword.len .. end_index.?]; return shell_version_output[version_keyword_index.? + version_keyword.len .. end_index.?];
} }
pub fn getTerminalName(gpa: std.mem.Allocator, environ: std.process.Environ) ![]u8 { pub fn getTerminalName(allocator: std.mem.Allocator) ![]u8 {
const term_program = std.process.Environ.getAlloc(environ, gpa, "TERM_PROGRAM") catch |err| if (err == error.EnvironmentVariableNotFound) { const term_program = std.process.getEnvVarOwned(allocator, "TERM_PROGRAM") catch |err| if (err == error.EnvironmentVariableNotFound) {
return gpa.dupe(u8, "Unknown"); return allocator.dupe(u8, "Unknown");
} else return err; } else return err;
return term_program; return term_program;
} }

View File

@@ -2,15 +2,15 @@ const std = @import("std");
const c_iokit = @cImport(@cInclude("IOKit/IOKitLib.h")); const c_iokit = @cImport(@cInclude("IOKit/IOKitLib.h"));
/// Converts a CFTypeRef casted to CFStringRef to a Zig string. /// Converts a CFTypeRef casted to CFStringRef to a Zig string.
pub fn cfTypeRefToZigString(gpa: std.mem.Allocator, cf_type_ref: c_iokit.CFTypeRef) ![]u8 { pub fn cfTypeRefToZigString(allocator: std.mem.Allocator, cf_type_ref: c_iokit.CFTypeRef) ![]u8 {
const cf_string: c_iokit.CFStringRef = @ptrFromInt(@intFromPtr(cf_type_ref)); const cf_string: c_iokit.CFStringRef = @ptrFromInt(@intFromPtr(cf_type_ref));
const length = c_iokit.CFStringGetLength(cf_string); const length = c_iokit.CFStringGetLength(cf_string);
const max_size = c_iokit.CFStringGetMaximumSizeForEncoding(length, c_iokit.kCFStringEncodingUTF8) + 1; const max_size = c_iokit.CFStringGetMaximumSizeForEncoding(length, c_iokit.kCFStringEncodingUTF8) + 1;
const max_size_usize = @as(usize, @intCast(max_size)); const max_size_usize = @as(usize, @intCast(max_size));
const buffer = try gpa.alloc(u8, max_size_usize); const buffer = try allocator.alloc(u8, max_size_usize);
errdefer gpa.free(buffer); errdefer allocator.free(buffer);
if (c_iokit.CFStringGetCString(cf_string, buffer.ptr, @as(c_iokit.CFIndex, @intCast(buffer.len)), c_iokit.kCFStringEncodingUTF8) == c_iokit.FALSE) { if (c_iokit.CFStringGetCString(cf_string, buffer.ptr, @as(c_iokit.CFIndex, @intCast(buffer.len)), c_iokit.kCFStringEncodingUTF8) == c_iokit.FALSE) {
return error.StringConversionFailed; return error.StringConversionFailed;
@@ -21,5 +21,5 @@ pub fn cfTypeRefToZigString(gpa: std.mem.Allocator, cf_type_ref: c_iokit.CFTypeR
actual_len += 1; actual_len += 1;
} }
return gpa.realloc(buffer, actual_len); return allocator.realloc(buffer, actual_len);
} }

View File

@@ -1,12 +1,11 @@
const std = @import("std"); const std = @import("std");
const builtin = @import("builtin"); const builtin = @import("builtin");
const detection = @import("detection.zig").os_module; const detection = @import("detection.zig").os_module;
const display = @import("display.zig"); const ascii = @import("ascii.zig");
const config = @import("config.zig"); const config = @import("config.zig");
const formatters = @import("formatters.zig"); const formatters = @import("formatters.zig");
pub fn main(init: std.process.Init) !void { pub fn main() !void {
const io = init.io;
var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator(); const allocator = gpa.allocator();
defer _ = gpa.deinit(); defer _ = gpa.deinit();
@@ -20,21 +19,21 @@ pub fn main(init: std.process.Init) !void {
} }
} }
const conf = try config.readConfigFile(allocator, io, init.minimal.environ); const conf = try config.readConfigFile(allocator);
defer if (conf) |c| c.deinit(); defer if (conf) |c| c.deinit();
const modules_types = try config.getModulesTypes(allocator, conf); const modules_types = try config.getModulesTypes(allocator, conf);
defer modules_types.deinit(); defer modules_types.deinit();
const username = try detection.user.getUsername(allocator, init.minimal.environ); const username = try detection.user.getUsername(allocator);
const hostname = try detection.system.getHostname(allocator); const hostname = try detection.system.getHostname(allocator);
const username_hostname_color = if (config.getUsernameHostnameColor(conf)) |color| blk: { const username_hostname_color = if (config.getUsernameHostnameColor(conf)) |color| blk: {
var buf: [32]u8 = undefined; var buf: [32]u8 = undefined;
const rgb = try display.hexColorToRgb(color); const rgb = try ascii.hexColorToRgb(color);
const formatted_color = try std.fmt.bufPrint(&buf, "\x1b[38;2;{d};{d};{d}m", .{ rgb.r, rgb.g, rgb.b }); const formatted_color = try std.fmt.bufPrint(&buf, "\x1b[38;2;{d};{d};{d}m", .{ rgb.r, rgb.g, rgb.b });
break :blk formatted_color; break :blk formatted_color;
} else display.Yellow; } else ascii.Yellow;
try modules_list.append(try formatters.getFormattedUsernameHostname(allocator, username_hostname_color, username, hostname)); try modules_list.append(try formatters.getFormattedUsernameHostname(allocator, username_hostname_color, username, hostname));
allocator.free(hostname); allocator.free(hostname);
@@ -44,15 +43,9 @@ pub fn main(init: std.process.Init) !void {
@memset(separtor_buffer, '-'); @memset(separtor_buffer, '-');
try modules_list.append(separtor_buffer); try modules_list.append(separtor_buffer);
const fmt_ctx = formatters.FormatterContext{
.gpa = allocator,
.environ = init.minimal.environ,
.io = init.io,
};
if (modules_types.items.len == 0) { if (modules_types.items.len == 0) {
inline for (0..formatters.default_formatters.len) |i| { inline for (0..formatters.default_formatters.len) |i| {
const result = try formatters.default_formatters[i](fmt_ctx); const result = try formatters.default_formatters[i](allocator);
switch (result) { switch (result) {
.string => |r| try modules_list.append(r), .string => |r| try modules_list.append(r),
.string_arraylist => |r| { .string_arraylist => |r| {
@@ -64,10 +57,10 @@ pub fn main(init: std.process.Init) !void {
} else if (conf) |c| { } else if (conf) |c| {
for (modules_types.items, c.value.modules) |module_type, module| { for (modules_types.items, c.value.modules) |module_type, module| {
var buf: [32]u8 = undefined; var buf: [32]u8 = undefined;
const rgb = try display.hexColorToRgb(module.key_color); const rgb = try ascii.hexColorToRgb(module.key_color);
const key_color = try std.fmt.bufPrint(&buf, "\x1b[38;2;{d};{d};{d}m", .{ rgb.r, rgb.g, rgb.b }); const key_color = try std.fmt.bufPrint(&buf, "\x1b[38;2;{d};{d};{d}m", .{ rgb.r, rgb.g, rgb.b });
const result = try formatters.formatters[@intFromEnum(module_type)](fmt_ctx, module.key, key_color); const result = try formatters.formatters[@intFromEnum(module_type)](allocator, module.key, key_color);
switch (result) { switch (result) {
.string => |r| try modules_list.append(r), .string => |r| try modules_list.append(r),
.string_arraylist => |r| { .string_arraylist => |r| {
@@ -78,6 +71,5 @@ pub fn main(init: std.process.Init) !void {
} }
} }
// TODO: return the formatted ascii and modules to print instead of directly print them try ascii.printAsciiAndModules(allocator, config.getAsciiPath(conf), modules_list);
try display.printAsciiAndModules(allocator, io, config.getAsciiPath(conf), modules_list);
} }

View File

@@ -9,7 +9,7 @@ pub const TermSize = struct {
pub fn getTerminalSize() !TermSize { pub fn getTerminalSize() !TermSize {
// https://github.com/softprops/zig-termsize (https://github.com/softprops/zig-termsize/blob/main/src/main.zig) // https://github.com/softprops/zig-termsize (https://github.com/softprops/zig-termsize/blob/main/src/main.zig)
const stdout = std.Io.File.stdout(); const stdout = std.fs.File.stdout();
switch (builtin.os.tag) { switch (builtin.os.tag) {
.windows => { .windows => {
@@ -115,25 +115,25 @@ test "getLongestAsciiArtRowLen" {
try std.testing.expectEqual(40, try getLongestAsciiArtRowLen(rows[0..])); try std.testing.expectEqual(40, try getLongestAsciiArtRowLen(rows[0..]));
} }
pub fn readFile(gpa: std.mem.Allocator, io: std.Io, file: std.Io.File, size: usize) ![]const u8 { pub fn readFile(allocator: std.mem.Allocator, file: std.fs.File, size: usize) ![]const u8 {
var file_buf = try gpa.alloc(u8, size); var file_buf = try allocator.alloc(u8, size);
defer gpa.free(file_buf); defer allocator.free(file_buf);
const read = try file.readPositionalAll(io, file_buf, 0); const read = try file.read(file_buf);
const data = file_buf[0..read]; const data = file_buf[0..read];
return gpa.dupe(u8, data); return allocator.dupe(u8, data);
} }
pub fn countEntries(io: std.Io, dir_path: []const u8) !usize { pub fn countEntries(dir_path: []const u8) !usize {
var dir = try std.Io.Dir.openDirAbsolute(io, dir_path, .{ .iterate = true }); var dir = try std.fs.openDirAbsolute(dir_path, .{ .iterate = true });
defer dir.close(io); defer dir.close();
var count: usize = 0; var count: usize = 0;
var iter = dir.iterate(); var iter = dir.iterate();
while (try iter.next(io)) |_| { while (try iter.next()) |_| {
count += 1; count += 1;
} }