49 Commits

Author SHA1 Message Date
utox39
3cfae25a75 build: bump version to 0.20.0 2025-08-26 03:38:47 +02:00
utox39
d841a6a726 docs(README): update README 2025-08-25 03:35:07 +02:00
utox39
7e7d964fd4 build: set minimum zig version to v0.15.1 2025-08-25 03:33:36 +02:00
utox39
a9091f1c93 build: bump version to 0.11.0 2025-08-25 03:32:08 +02:00
utox39
d9ac4e58fc refactor(linux-network): use the new managed array list 2025-08-25 03:18:31 +02:00
utox39
9c4e032c04 refactor(linux-gpu): use the new managed array list 2025-08-25 03:16:45 +02:00
utox39
5730f14897 feat(linux-shell): use process.Child.run 2025-08-25 03:12:56 +02:00
utox39
f57fc5d9ab feat(macos-shell): use process.Child.run 2025-08-25 03:12:29 +02:00
utox39
e7f7205a44 feat(macos-packages): use fmt.bufPrint instead of io.fixedBufferStream and fmt.formatInt 2025-08-25 02:17:42 +02:00
utox39
8768e85b80 refactor(macos-network): use the new managed array list 2025-08-25 02:12:52 +02:00
utox39
27995745e4 refactor(macos-gpu): use the new cfTypeRefToZigString function instead of the old cfStringToZigString 2025-08-25 02:09:52 +02:00
utox39
092171ef7f refactor(macos-utils): converts a CFTypeRef casted to CFStringRef to a Zig string 2025-08-25 02:04:41 +02:00
utox39
84a5edba4c refactor(formatters): use new managed array list 2025-08-25 01:49:45 +02:00
utox39
212e3c3bc8 refactor(config): use new managed array list 2025-08-25 01:47:48 +02:00
utox39
9020345b00 refactor: use new managed array list 2025-08-25 01:46:55 +02:00
utox39
b7ba91d664 build: update build.zig 2025-08-25 01:40:43 +02:00
utox39
1c97ed3685 feat(ascii): add a workaround for alignment that is no longer supported in combination with Unicode 2025-08-25 01:38:37 +02:00
utox39
316238f9ea feat(utils): add a utility function to get the length of the longest ascii art row 2025-08-25 01:25:59 +02:00
utox39
7ad5181381 feat(utils): add a utility function to count the codepoints in a string 2025-08-25 01:23:52 +02:00
utox39
02406a7644 refactor(utils): use new zig stdout implementation 2025-08-25 01:17:16 +02:00
utox39
30970649c2 refactor(ascii): use new managed array list 2025-08-24 22:02:14 +02:00
utox39
981d5ee579 refactor(ascii): use new zig stdout implementation 2025-08-24 22:00:51 +02:00
utox39
8aa0f4972e feat(macos-packages): use new array_list 2025-08-23 00:18:24 +02:00
utox39
da70f9ee06 build: bump version to 0.10.0 2025-08-11 02:35:28 +02:00
utox39
b6628c3135 Merge pull request #12 from utox39/feat-config/config-improvements
Feat config/config improvements
2025-08-11 02:34:16 +02:00
utox39
c66d127c4d feat(formatters): add formatter for the 'custom' module 2025-08-10 00:41:06 +02:00
utox39
f3c9b6e9a6 feat(config): add 'custom' module 2025-08-10 00:38:42 +02:00
utox39
d55af958e7 feat(utils): add workaround for start index greater than length 2025-08-10 00:37:37 +02:00
utox39
3bcfff5bdc build: bump version to 0.9.1 2025-08-06 20:57:27 +02:00
utox39
42edc5c24b fix(utils): fix typo 2025-08-06 20:57:10 +02:00
utox39
537a324275 build: bump version to 0.9.0 2025-08-06 00:03:00 +02:00
utox39
224a7d29d8 Merge pull request #11 from utox39/feat/parse-shell-version
Feat/parse shell version
2025-08-06 00:01:34 +02:00
utox39
eb477e5154 refactor(shell): remove the 'allocator' parameter 2025-08-05 23:13:42 +02:00
utox39
2d1c7506d8 feat(shell): parse bash shell version 2025-08-04 02:37:52 +02:00
utox39
428d882591 Merge pull request #10 from utox39/feat/handle-shell-env-var-not-found
Feat/handle shell env var not found
2025-08-04 00:40:29 +02:00
utox39
a1c62a56ae build: bump version to 0.8.1 2025-08-04 00:38:33 +02:00
utox39
5b423d1cef feat(shell): handle 'SHELL' env var not found 2025-08-04 00:35:09 +02:00
utox39
6574945e56 docs(README): update README 2025-08-02 00:25:25 +02:00
utox39
66bb544c0a build: bump version to 0.8.0 2025-08-02 00:22:06 +02:00
utox39
d90c1d2e9a Merge pull request #9 from utox39/feat/adaptive-print
Feat/adaptive print
2025-08-02 00:20:35 +02:00
utox39
0beec60a8a fix(linux-kernel): fix kernel info parsing by trimming null bytes 2025-08-01 06:25:30 +02:00
utox39
7669da5ae8 refactor(formatters): remove unnecessary spaces in the formatted uptime string 2025-08-01 05:55:11 +02:00
utox39
1267a71250 feat: print the ascii art if the width of the terminal is greater than the left alignment (45) + the longest sys info string length 2025-08-01 04:10:00 +02:00
utox39
2aa90c04ff feat: add a utility function to get the length of the longest sys info string 2025-08-01 03:51:11 +02:00
utox39
f6d1c2dc72 feat: add adaptive printing based on terminal width 2025-07-31 01:47:12 +02:00
utox39
9df0845530 feat: add a utility function to retrieve the terminal size 2025-07-31 01:43:40 +02:00
utox39
3b3c29e22d Merge pull request #8 from utox39/fix-linux-gpu/fix-memory-leak
Fix linux gpu/fix memory leak
2025-07-29 17:08:10 +02:00
utox39
a866952f86 build: bump version to 0.7.4 2025-07-29 17:06:40 +02:00
utox39
5d7bdd8041 fix(linux-gpu): fix memory leak 2025-07-29 17:05:30 +02:00
17 changed files with 244 additions and 71 deletions

View File

@@ -14,7 +14,7 @@ Zigfetch is a minimal [neofetch](https://github.com/dylanaraps/neofetch)/[fastfe
## Requirements
- \>= [zig v0.14.0](https://ziglang.org/)
- \>= [zig v0.15.1](https://ziglang.org/)
### Linux only
@@ -69,7 +69,7 @@ $ cp /path/to/zigfetch/config.json ~/.config/zigfetch/config.json
## Roadtrip
- [ ] Add ASCII art for each operating system and Linux distro
- [ ] Add GPU info for Linux
- [x] Add GPU info for Linux
- [ ] Add packages info for Linux
- [x] Add user customization
- [ ] Add support for Windows

View File

@@ -17,9 +17,11 @@ pub fn build(b: *std.Build) void {
const exe = b.addExecutable(.{
.name = "zigfetch",
.root_module = b.createModule(.{
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
}),
});
if (target.result.os.tag == .macos) {
@@ -61,9 +63,11 @@ pub fn build(b: *std.Build) void {
run_step.dependOn(&run_cmd.step);
const exe_unit_tests = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
}),
});
const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);

View File

@@ -10,7 +10,7 @@
// This is a [Semantic Version](https://semver.org/).
// In a future version of Zig it will be used for package deduplication.
.version = "0.7.3",
.version = "0.20.0",
// Together with name, this represents a globally unique package
// identifier. This field is generated by the Zig toolchain when the
@@ -28,7 +28,7 @@
// Tracks the earliest Zig version that the package considers to be a
// supported use case.
.minimum_zig_version = "0.14.0",
.minimum_zig_version = "0.15.1",
// This field is optional.
// Each dependency must either provide a `url` and `hash`, or a `path`.

View File

@@ -1,4 +1,5 @@
const std = @import("std");
const utils = @import("./utils.zig");
pub const Reset = "\x1b[0m";
pub const Bold = "\x1b[1m";
@@ -64,10 +65,10 @@ test "parse ffffff" {
try std.testing.expect((result.r == 255) and (result.g == 255) and (result.b == 255));
}
pub fn printAscii(allocator: std.mem.Allocator, sys_info_list: std.ArrayList([]u8)) !void {
const stdout_file = std.io.getStdOut().writer();
var bw = std.io.bufferedWriter(stdout_file);
const stdout = bw.writer();
pub fn printAscii(allocator: std.mem.Allocator, sys_info_list: std.array_list.Managed([]u8)) !void {
var stdout_buffer: [2048]u8 = undefined;
var stdout_writer = std.fs.File.stdout().writer(&stdout_buffer);
const stdout = &stdout_writer.interface;
// const ascii_art_path = "./assets/ascii/guy_fawks.txt";
// var file = try std.fs.cwd().openFile(ascii_art_path, .{});
@@ -79,7 +80,7 @@ pub fn printAscii(allocator: std.mem.Allocator, sys_info_list: std.ArrayList([]u
var lines = std.mem.splitScalar(u8, ascii_art_data, '\n');
var ascii_art_content_list = std.ArrayList([]const u8).init(allocator);
var ascii_art_content_list = std.array_list.Managed([]const u8).init(allocator);
defer ascii_art_content_list.deinit();
while (lines.next()) |line| {
@@ -89,18 +90,39 @@ pub fn printAscii(allocator: std.mem.Allocator, sys_info_list: std.ArrayList([]u
const ascii_art_items = ascii_art_content_list.items;
const sys_info_items = sys_info_list.items;
const terminal_size = try utils.getTerminalSize();
const terminal_width: usize = @intCast(terminal_size.width);
const spacing: usize = 5;
const longest_ascii_art_row_len: usize = try utils.getLongestAsciiArtRowLen(ascii_art_items);
const longest_sys_info_string_len = utils.getLongestSysInfoStringLen(sys_info_items);
const can_print_ascii_art: bool = terminal_width > longest_ascii_art_row_len + longest_sys_info_string_len + spacing;
const ascii_art_len: usize = ascii_art_items.len;
const sys_info_len: usize = sys_info_items.len;
const max_len: usize = if (ascii_art_len > sys_info_len) ascii_art_len else sys_info_len;
// NOTE: sys_info_len + 3 to be able to print the colors
const max_len: usize = if ((ascii_art_len > sys_info_len) and can_print_ascii_art) ascii_art_len else sys_info_len + 3;
var i: usize = 0;
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
if (can_print_ascii_art) {
const alignment_buffer = try allocator.alloc(u8, longest_ascii_art_row_len - (try utils.countCodepoints(ascii_art_items[i])) + spacing);
@memset(alignment_buffer, ' ');
if (i < ascii_art_len) {
try stdout.print("{s:<40} \t", .{ascii_art_items[i]});
try stdout.print("{s}{s}", .{ ascii_art_items[i], alignment_buffer });
} else {
try stdout.print("{s:<40}", .{""});
try stdout.print("{s}", .{alignment_buffer});
}
allocator.free(alignment_buffer);
try stdout.flush();
}
try bw.flush();
if (i < sys_info_len) {
try stdout.print("{s}\n", .{sys_info_items[i]});
@@ -119,7 +141,7 @@ pub fn printAscii(allocator: std.mem.Allocator, sys_info_list: std.ArrayList([]u
} else {
try stdout.print("\n", .{});
}
try bw.flush();
try stdout.flush();
}
for (sys_info_list.items) |item| {

View File

@@ -26,10 +26,11 @@ pub const ModuleType = enum {
net,
terminal,
locale,
custom,
};
pub fn getModulesTypes(allocator: std.mem.Allocator, config: ?std.json.Parsed(Config)) !std.ArrayList(ModuleType) {
var modules_list = std.ArrayList(ModuleType).init(allocator);
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(allocator);
if (config) |c| {
for (c.value.modules) |module| {

View File

@@ -5,7 +5,7 @@ const detection = @import("detection.zig").os_module;
const Result = union(enum) {
string: []u8,
string_arraylist: std.ArrayList([]u8),
string_arraylist: std.array_list.Managed([]u8),
};
pub const formatters = [_]*const fn (allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) anyerror!Result{
@@ -22,6 +22,7 @@ pub const formatters = [_]*const fn (allocator: std.mem.Allocator, key: []const
&getFormattedNetInfo,
&getFormattedTerminalNameInfo,
&getFormattedLocaleInfo,
&getFormattedCustom,
};
pub const default_formatters = [_]*const fn (allocator: std.mem.Allocator) anyerror!Result{
@@ -78,7 +79,7 @@ pub fn getDefaultFormattedUptimeInfo(allocator: std.mem.Allocator) !Result {
pub fn getFormattedUptimeInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
const uptime = try detection.system.getSystemUptime();
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 }) };
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 }) };
}
pub fn getDefaultFormattedPackagesInfo(allocator: std.mem.Allocator) !Result {
@@ -129,7 +130,7 @@ pub fn getFormattedGpuInfo(allocator: std.mem.Allocator, key: []const u8, key_co
defer allocator.free(gpu_info.gpu_name);
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 }) };
} else if (builtin.os.tag == .linux) {
var formatted_gpu_info_list = std.ArrayList([]u8).init(allocator);
var formatted_gpu_info_list = std.array_list.Managed([]u8).init(allocator);
const gpu_info_list = try detection.hardware.getGpuInfo(allocator);
@@ -195,7 +196,7 @@ pub fn getDefaultFormattedNetInfo(allocator: std.mem.Allocator) !Result {
}
pub fn getFormattedNetInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
var formatted_net_info_list = std.ArrayList([]u8).init(allocator);
var formatted_net_info_list = std.array_list.Managed([]u8).init(allocator);
var net_info_list = try detection.network.getNetInfo(allocator);
for (net_info_list.items) |n| {
@@ -207,3 +208,7 @@ pub fn getFormattedNetInfo(allocator: std.mem.Allocator, key: []const u8, key_co
return Result{ .string_arraylist = formatted_net_info_list };
}
pub fn getFormattedCustom(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}{s}", .{ key_color, key, ascii.Reset }) };
}

View File

@@ -113,8 +113,8 @@ pub fn getCpuInfo(allocator: std.mem.Allocator) !CpuInfo {
};
}
pub fn getGpuInfo(allocator: std.mem.Allocator) !std.ArrayList(GpuInfo) {
var gpu_info_list = std.ArrayList(GpuInfo).init(allocator);
pub fn getGpuInfo(allocator: std.mem.Allocator) !std.array_list.Managed(GpuInfo) {
var gpu_info_list = std.array_list.Managed(GpuInfo).init(allocator);
const display_controller = 0x03;
@@ -145,7 +145,15 @@ pub fn getGpuInfo(allocator: std.mem.Allocator) !std.ArrayList(GpuInfo) {
const gpu_name = try allocator.dupe(u8, std.mem.span(name));
const parsed_gpu_name = try parseGpuName(allocator, gpu_name) orelse gpu_name;
const maybe_parsed_gpu_name = try parseGpuName(allocator, gpu_name);
var parsed_gpu_name: []u8 = undefined;
if (maybe_parsed_gpu_name != null) {
allocator.free(gpu_name);
parsed_gpu_name = maybe_parsed_gpu_name.?;
} else {
parsed_gpu_name = gpu_name;
}
try gpu_info_list.append(GpuInfo{
.gpu_name = parsed_gpu_name,

View File

@@ -11,8 +11,8 @@ pub const NetInfo = struct {
ipv4_addr: []u8,
};
pub fn getNetInfo(allocator: std.mem.Allocator) !std.ArrayList(NetInfo) {
var net_info_list = std.ArrayList(NetInfo).init(allocator);
pub fn getNetInfo(allocator: std.mem.Allocator) !std.array_list.Managed(NetInfo) {
var net_info_list = std.array_list.Managed(NetInfo).init(allocator);
var ifap: ?*c_ifaddrs.ifaddrs = null;
if (c_ifaddrs.getifaddrs(&ifap) != 0) {

View File

@@ -70,8 +70,8 @@ pub fn getKernelInfo(allocator: std.mem.Allocator) !KernelInfo {
}
return KernelInfo{
.kernel_name = try allocator.dupe(u8, &uts.sysname),
.kernel_release = try allocator.dupe(u8, &uts.release),
.kernel_name = try allocator.dupe(u8, std.mem.sliceTo(&uts.sysname, 0)),
.kernel_release = try allocator.dupe(u8, std.mem.sliceTo(&uts.release, 0)),
};
}

View File

@@ -6,21 +6,33 @@ pub fn getUsername(allocator: std.mem.Allocator) ![]u8 {
}
pub fn getShell(allocator: std.mem.Allocator) ![]u8 {
const shell = try std.process.getEnvVarOwned(allocator, "SHELL");
const shell = std.process.getEnvVarOwned(allocator, "SHELL") catch |err| if (err == error.EnvironmentVariableNotFound) {
return allocator.dupe(u8, "Unknown");
} else return err;
var child = std.process.Child.init(&[_][]const u8{ shell, "--version" }, allocator);
defer allocator.free(shell);
child.stdout_behavior = .Pipe;
child.stderr_behavior = .Pipe;
const result = try std.process.Child.run(.{ .allocator = allocator, .argv = &[_][]const u8{ shell, "--version" } });
const result_stdout = result.stdout;
try child.spawn();
if (std.mem.indexOf(u8, shell, "bash") != null) {
const bash_version = parseBashVersion(result_stdout);
defer allocator.free(result_stdout);
return try std.fmt.allocPrint(allocator, "{s} {s}", .{ "bash", bash_version.? });
}
const output = try child.stdout.?.reader().readAllAlloc(allocator, 1024 * 1024);
return result_stdout;
}
_ = try child.wait();
fn parseBashVersion(shell_version_output: []u8) ?[]u8 {
const end_index = std.mem.indexOf(u8, shell_version_output, "(");
if (end_index == null) return null;
return output;
const version_keyword = "version ";
const version_keyword_index = std.mem.indexOf(u8, shell_version_output[0..end_index.?], version_keyword);
if (version_keyword_index == null) return null;
return shell_version_output[version_keyword_index.? + version_keyword.len .. end_index.?];
}
pub fn getTerminalName(allocator: std.mem.Allocator) ![]u8 {

View File

@@ -236,7 +236,7 @@ pub fn getGpuInfo(allocator: 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.CFGetTypeID(name_ref) == c_iokit.CFStringGetTypeID()) {
const accel_name = utils.cfStringToZigString(allocator, @as(c_iokit.CFStringRef, @ptrCast(name_ref))) catch {
const accel_name = utils.cfTypeRefToZigString(allocator, name_ref) catch {
return gpu_info;
};

View File

@@ -11,8 +11,8 @@ pub const NetInfo = struct {
ipv4_addr: []u8,
};
pub fn getNetInfo(allocator: std.mem.Allocator) !std.ArrayList(NetInfo) {
var net_info_list = std.ArrayList(NetInfo).init(allocator);
pub fn getNetInfo(allocator: std.mem.Allocator) !std.array_list.Managed(NetInfo) {
var net_info_list = std.array_list.Managed(NetInfo).init(allocator);
var ifap: ?*c_ifaddrs.ifaddrs = null;
if (c_ifaddrs.getifaddrs(&ifap) != 0) {

View File

@@ -2,34 +2,25 @@ const std = @import("std");
const utils = @import("utils.zig");
pub fn getPackagesInfo(allocator: std.mem.Allocator) ![]const u8 {
var packages_info = std.ArrayList(u8).init(allocator);
var packages_info = std.array_list.Managed(u8).init(allocator);
defer packages_info.deinit();
const homebrew_packages = countHomebrewPackages() 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() catch |err| if (err == error.FileNotFound) 0 else return err;
var buffer: [10]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buffer);
var buffer: [32]u8 = undefined;
if (homebrew_packages > 0) {
try std.fmt.formatInt(homebrew_packages, 10, .lower, .{}, fbs.writer());
try packages_info.appendSlice(" brew: ");
try packages_info.appendSlice(fbs.getWritten());
try packages_info.appendSlice(try std.fmt.bufPrint(&buffer, " brew: {d}", .{homebrew_packages}));
}
if (homebrew_casks > 0) {
fbs.reset();
try std.fmt.formatInt(homebrew_casks, 10, .lower, .{}, fbs.writer());
try packages_info.appendSlice(" brew-cask: ");
try packages_info.appendSlice(fbs.getWritten());
try packages_info.appendSlice(try std.fmt.bufPrint(&buffer, " brew-cask: {d}", .{homebrew_casks}));
}
if (macports_packages > 0) {
fbs.reset();
try std.fmt.formatInt(macports_packages, 10, .lower, .{}, fbs.writer());
try packages_info.appendSlice(" macports: ");
try packages_info.appendSlice(fbs.getWritten());
try packages_info.appendSlice(try std.fmt.bufPrint(&buffer, " macports: {d}", .{macports_packages}));
}
return try allocator.dupe(u8, packages_info.items);

View File

@@ -9,21 +9,33 @@ pub fn getUsername(allocator: std.mem.Allocator) ![]u8 {
}
pub fn getShell(allocator: std.mem.Allocator) ![]u8 {
const shell = try std.process.getEnvVarOwned(allocator, "SHELL");
const shell = std.process.getEnvVarOwned(allocator, "SHELL") catch |err| if (err == error.EnvironmentVariableNotFound) {
return allocator.dupe(u8, "Unknown");
} else return err;
var child = std.process.Child.init(&[_][]const u8{ shell, "--version" }, allocator);
defer allocator.free(shell);
child.stdout_behavior = .Pipe;
child.stderr_behavior = .Pipe;
const result = try std.process.Child.run(.{ .allocator = allocator, .argv = &[_][]const u8{ shell, "--version" } });
const result_stdout = result.stdout;
try child.spawn();
if (std.mem.indexOf(u8, shell, "bash") != null) {
const bash_version = parseBashVersion(result_stdout);
defer allocator.free(result_stdout);
return try std.fmt.allocPrint(allocator, "{s} {s}", .{ "bash", bash_version.? });
}
const output = try child.stdout.?.reader().readAllAlloc(allocator, 1024 * 1024);
return result_stdout;
}
_ = try child.wait();
fn parseBashVersion(shell_version_output: []u8) ?[]u8 {
const end_index = std.mem.indexOf(u8, shell_version_output, "(");
if (end_index == null) return null;
return output;
const version_keyword = "version ";
const version_keyword_index = std.mem.indexOf(u8, shell_version_output[0..end_index.?], version_keyword);
if (version_keyword_index == null) return null;
return shell_version_output[version_keyword_index.? + version_keyword.len .. end_index.?];
}
pub fn getTerminalName(allocator: std.mem.Allocator) ![]u8 {

View File

@@ -1,8 +1,10 @@
const std = @import("std");
const c_iokit = @cImport(@cInclude("IOKit/IOKitLib.h"));
/// Converts a CFString to a Zig string.
pub fn cfStringToZigString(allocator: std.mem.Allocator, cf_string: c_iokit.CFStringRef) ![]u8 {
/// Converts a CFTypeRef casted to CFStringRef to a Zig string.
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 length = c_iokit.CFStringGetLength(cf_string);
const max_size = c_iokit.CFStringGetMaximumSizeForEncoding(length, c_iokit.kCFStringEncodingUTF8) + 1;
const max_size_usize = @as(usize, @intCast(max_size));

View File

@@ -10,7 +10,7 @@ pub fn main() !void {
const allocator = gpa.allocator();
defer _ = gpa.deinit();
var sys_info_list = std.ArrayList([]u8).init(allocator);
var sys_info_list = std.array_list.Managed([]u8).init(allocator);
defer sys_info_list.deinit();
errdefer {

116
src/utils.zig Normal file
View File

@@ -0,0 +1,116 @@
const std = @import("std");
const builtin = @import("builtin");
pub const TermSize = struct {
width: u16,
height: u16,
};
pub fn getTerminalSize() !TermSize {
// https://github.com/softprops/zig-termsize (https://github.com/softprops/zig-termsize/blob/main/src/main.zig)
const stdout = std.fs.File.stdout();
switch (builtin.os.tag) {
.windows => {
var buf: std.os.windows.CONSOLE_SCREEN_BUFFER_INFO = undefined;
switch (std.os.windows.kernel32.GetConsoleScreenBufferInfo(stdout.handle, &buf)) {
std.os.windows.TRUE => return TermSize{
.width = @intCast(buf.srWindow.Right - buf.srWindow.Left + 1),
.height = @intCast(buf.srWindow.Bottom - buf.srWindow.Top + 1),
},
else => return error.GetConsoleScreenBufferInfoFailed,
}
},
.linux, .macos => {
var buf: std.posix.winsize = undefined;
switch (std.posix.errno(
std.posix.system.ioctl(
stdout.handle,
std.posix.T.IOCGWINSZ,
@intFromPtr(&buf),
),
)) {
std.posix.E.SUCCESS => return TermSize{
.width = buf.col,
.height = buf.row,
},
else => return error.IoctlFailed,
}
},
else => return error.UnsupportedOperatingSystem,
}
}
test "getTerminalSize" {
const terminal_size = try getTerminalSize();
std.debug.print("Height: {}, Width {}\n", .{ terminal_size.height, terminal_size.width });
try std.testing.expect((terminal_size.height > 0) and (terminal_size.width > 0));
}
pub fn getLongestSysInfoStringLen(strings: []const []const u8) usize {
const ansi_reset = "\x1b[0m";
var longest_len: usize = 0;
// Ignore the username@host and the separator
for (strings[2..]) |s| {
const ansi_restet_index = std.mem.indexOf(u8, s, ansi_reset);
var start: usize = 0;
if (ansi_restet_index != null) {
// `start` is the index of the last character of the ANSI reset escape sequence + 1
start = ansi_restet_index.? + ansi_reset.len + 1;
if (start > s.len) continue;
}
longest_len = @max(longest_len, s[start..].len);
}
return longest_len;
}
test "getLongestSysInfoStringLen" {
const strings = [_][]const u8{ "", "", "test", "test-test", "test1" };
try std.testing.expectEqual(strings[3].len, getLongestSysInfoStringLen(strings[0..]));
}
pub fn countCodepoints(str: []const u8) !usize {
var count: usize = 0;
var i: usize = 0;
while (i < str.len) {
const byte_len = try std.unicode.utf8ByteSequenceLength(str[i]);
if ((i + byte_len > str.len) or (!std.unicode.utf8ValidateSlice(str[i .. i + byte_len]))) return error.InvalidUtf8;
count += 1;
i += byte_len;
}
return count;
}
test "countCodepoints" {
const str = " ████████████████";
try std.testing.expectEqual(28, try countCodepoints(str));
}
pub fn getLongestAsciiArtRowLen(ascii_art: []const []const u8) !usize {
var longest_len: usize = 0;
for (ascii_art) |ascii_row| {
longest_len = @max(longest_len, try countCodepoints(ascii_row));
}
return longest_len;
}
test "getLongestAsciiArtRowLen" {
const rows = [_][]const u8{ " ████████████████", "██░░░░██████████░░ ░░██████████░░░░██" };
try std.testing.expectEqual(40, try getLongestAsciiArtRowLen(rows[0..]));
}