94 Commits

Author SHA1 Message Date
utox39
3847bc247a build: bump version to 0.24.2 2025-10-15 21:39:58 +02:00
utox39
784d52eac4 Merge pull request #28 from utox39/build/add-more-paths
build(build.yml): add more paths
2025-10-15 21:38:25 +02:00
utox39
f78406448a build(build.yml): add more paths 2025-10-15 21:37:54 +02:00
utox39
50b592b125 Merge pull request #27 from utox39/build/fix-paths
build(build.yml): fix paths
2025-10-15 21:34:16 +02:00
utox39
7faff1e70d build(build.yml): fix paths 2025-10-15 21:33:29 +02:00
utox39
c17b97608c Merge pull request #26 from utox39/refactor/use-utils-read-file
refactor(linux-wm): use utils.readFile
2025-10-15 21:29:24 +02:00
utox39
1e1ad7be17 feat(linux-wm): use utils.readFile 2025-10-15 21:25:29 +02:00
utox39
429c0f89b9 Merge pull request #25 from utox39/build/workflow-paths
build(build.yml): add paths
2025-10-15 20:33:45 +02:00
utox39
ad0617a7e5 build(build.yml): add paths 2025-10-15 20:32:12 +02:00
utox39
df75b0fdb5 docs(README): update README 2025-10-15 20:26:40 +02:00
utox39
89f68fe674 chore: add CONTRIBUTING.md 2025-10-15 20:22:31 +02:00
utox39
89dfeca508 docs(README): update README 2025-10-15 15:00:45 +02:00
utox39
a72ede5259 build: bump minimum zig version to 0.15.2 2025-10-15 15:00:19 +02:00
utox39
7254bda609 build: bump version to 0.24.1 2025-10-15 14:59:31 +02:00
utox39
d8ddd4a18e Merge pull request #24 from kirillrdy/main
Use the new `std.fs.File.read` function.
2025-10-15 14:46:02 +02:00
Kirill Radzikhovskyy
948554d022 The std.fs.File.Reader.read function was removed in Zig v0.15.2. 2025-10-15 10:31:33 +11:00
utox39
a9bb9cdeaf docs(README): update README 2025-10-11 18:21:20 +02:00
utox39
8132b0fc04 build: bump version to 0.24.0 2025-10-11 17:45:15 +02:00
utox39
d5bb5b19c5 Merge pull request #23 from utox39/refactor/use-new-fs-reader
Refactor: use the new fs reader
2025-10-11 17:42:01 +02:00
utox39
1d7a175d29 feat(ascii): read the ascii art file in read-only mode 2025-10-08 22:23:36 +02:00
utox39
61ceb027a6 refactor(linux): use utils.readFile to read the files 2025-10-08 22:13:23 +02:00
utox39
3e55f6a973 refactor(ascii): use utils.readFile to read the ascii art file 2025-10-08 22:12:17 +02:00
utox39
a5f4a60d46 refactor(config): use utils.readFile to read the config file 2025-10-08 22:06:41 +02:00
utox39
36ff1857b7 feat(utils): add a utility function to read files
This function uses the new fs.File.Reader to replace the deprecated fs.File.readToEndAlloc
2025-10-08 22:03:29 +02:00
utox39
48ab100e13 refactor(config): replace the deprecated readToEndAlloc with the new Reader 2025-10-07 09:50:06 +02:00
utox39
1363bad02d refactor(ascii): replace the deprecated readToEndAlloc with the new Reader 2025-10-07 09:47:08 +02:00
utox39
12435bae0e Merge pull request #22 from utox39/feat/window-manager
fix(macos-wm): fix wrong array size
2025-10-04 21:07:25 +02:00
utox39
d26be667a1 fix(macos-wm): fix wrong array size 2025-10-04 21:05:16 +02:00
utox39
b3ca5ae9eb Merge pull request #21 from utox39/feat/window-manager
Feat/window manager
2025-10-04 20:42:12 +02:00
utox39
e30c6ccc73 Merge branch 'main' into feat/window-manager 2025-10-04 20:41:13 +02:00
utox39
8599fe92cf build: bump version to 0.23.0 2025-10-04 20:36:09 +02:00
utox39
19facc09ef docs(README): update README 2025-10-04 20:31:22 +02:00
utox39
0aec3d8e5b Merge pull request #20 from utox39/fix/invalid-module-memory-leak
Fix a memory leak when the InvalidModule error occurs
2025-10-04 18:06:07 +02:00
utox39
dd2f50c79c build: bump version to 0.22.1 2025-10-04 17:57:29 +02:00
utox39
16bb74c47b fix(config): fix a memory leak when the InvalidModule error occurs 2025-10-04 17:55:50 +02:00
utox39
62df4a52dc feat(linux): add window manager info 2025-10-04 17:15:41 +02:00
utox39
20f9c6e1d5 Merge pull request #19 from utox39/build/remove-archive-creation
build: remove archive creation
2025-10-03 15:02:11 +02:00
utox39
b09443db4d build: remove archive-creation 2025-10-03 15:00:30 +02:00
utox39
dd3b79b32d Merge pull request #18 from utox39/build/fix-artifact-output
build: use the correct artifact path
2025-10-03 14:45:42 +02:00
utox39
22376139f2 build: use the correct artifact path 2025-10-03 14:43:25 +02:00
utox39
d6978cd4b2 feat(formatters): add window manager formatters 2025-10-03 12:50:19 +02:00
utox39
2f847fbef3 feat(config): add wm module 2025-10-03 12:40:54 +02:00
utox39
cec2b8068a feat(macos-wm): remove kwm from supported window managers 2025-09-20 01:05:59 +02:00
utox39
6564d85845 feat(macos): add window manager info 2025-09-15 14:59:24 +02:00
utox39
a835074ee6 docs(README): update README 2025-09-14 19:38:25 +02:00
utox39
3d16102f37 docs(README): update README 2025-09-14 19:23:02 +02:00
utox39
24a5e98089 docs(README): update README 2025-09-13 21:18:44 +02:00
utox39
f03f7e163c chore: add screenshots 2025-09-13 21:17:52 +02:00
utox39
69d02a4bb7 Merge pull request #16 from utox39/feat/add-username-hostname-color
Feat/add username hostname color
2025-09-13 20:07:32 +02:00
utox39
6a86a81fcc build: bump version to 0.22.0 2025-09-13 20:04:27 +02:00
utox39
a125053c70 refactor(config): remove unused import 2025-09-13 19:52:14 +02:00
utox39
d9ec3a7de7 feat: add logic for username and hostname colors 2025-09-13 18:41:15 +02:00
utox39
5f6460f46e feat(formatters): add getFormattedUsernameHostname function 2025-09-13 18:36:32 +02:00
utox39
aab5212e6e feat(config): add username_hostname_color field and getUsernameHostname function 2025-09-13 18:33:04 +02:00
utox39
abff59b7d6 fix(config): fix null value access when config file are not used 2025-09-13 17:40:53 +02:00
utox39
1dc0559b8e Merge pull request #15 from utox39/feat/handle-ioctl-error
Feat/handle ioctl error
2025-09-12 02:42:30 +02:00
utox39
2b32119bc7 fix: minor fix 2025-09-12 02:41:20 +02:00
utox39
837b7cd5c4 build: bump version to 0.21.1 2025-09-12 02:34:02 +02:00
utox39
6317269c4f test(utils): handle IoctlFailed error using default values 2025-09-12 02:31:31 +02:00
utox39
989b5b2305 feat(ascii): handle the IoctlFailed error using default values 2025-09-12 02:30:18 +02:00
utox39
c32318dac2 Merge pull request #14 from utox39/build/cross-compilation
Build/cross compilation
2025-09-12 02:14:07 +02:00
utox39
c64f2f384d docs(README): update README 2025-09-12 02:11:29 +02:00
utox39
c82622cf8e build: fix indentation 2025-09-12 02:00:56 +02:00
utox39
9babb021f1 chore: add github workflows 2025-09-12 01:54:32 +02:00
utox39
ef8b6bcebd Merge pull request #13 from utox39/feat/custom-ascii
Feat/custom ascii
2025-09-10 14:52:20 +02:00
utox39
acc4563d2d docs(README): update README 2025-09-10 14:47:12 +02:00
utox39
ea966cd474 build: bump version to 0.21.0 2025-09-10 14:29:58 +02:00
utox39
3214725e58 refactor: rename a function 2025-09-10 14:29:14 +02:00
utox39
f4a8c962e6 refactor: rename a variable 2025-09-10 14:27:46 +02:00
utox39
f7641c24a3 fix(ascii): fix the calculation of the alignment buffer size 2025-09-10 14:26:11 +02:00
utox39
20e2ef80d2 feat: add custom ascii art 2025-09-10 14:21:22 +02:00
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
22 changed files with 570 additions and 124 deletions

99
.github/workflows/build.yml vendored Normal file
View File

@@ -0,0 +1,99 @@
name: Build
on:
push:
branches: [ "main" ]
paths:
- 'src/**'
- 'build.zig'
- 'build.zig.zon'
jobs:
build:
strategy:
matrix:
include:
# Linux x86_64
- os: ubuntu-latest
target: x86_64-linux
runner_arch: x64
setup_deps: |
sudo apt-get update
sudo apt-get install -y libpci-dev
# macOS x86_64
- os: macos-13
target: x86_64-darwin
runner_arch: x64
setup_deps: ""
# macOS aarch64 (Apple Silicon)
- os: macos-latest
target: aarch64-darwin
runner_arch: arm64
setup_deps: ""
runs-on: ${{ matrix.os }}
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Zig
uses: mlugg/setup-zig@v2
with:
version: 0.15.1
- name: Setup platform dependencies
if: matrix.setup_deps != ''
run: ${{ matrix.setup_deps }}
- name: Cache Zig
uses: actions/cache@v4
with:
path: |
~/.cache/zig
zig-cache
key: ${{ runner.os }}-${{ matrix.target }}-zig-${{ hashFiles('build.zig', 'build.zig.zon') }}
restore-keys: |
${{ runner.os }}-${{ matrix.target }}-zig-
- name: Build for target
run: |
zig build -Doptimize=ReleaseSafe
mv zig-out/bin/zigfetch zig-out/bin/zigfetch-${{ matrix.target }}
- name: Verify binary
run: |
ls -la zig-out/bin/
file zig-out/bin/zigfetch-${{ matrix.target }}
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: zigfetch-${{ matrix.target }}
path: zig-out/bin/zigfetch-${{ matrix.target }}
retention-days: 3
test:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Zig
uses: mlugg/setup-zig@v2
with:
version: 0.15.1
- name: Setup dependencies
run: |
sudo apt-get update
sudo apt-get install -y libpci-dev
- name: Run tests
run: |
zig test src/ascii.zig
zig test src/utils.zig

18
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,18 @@
# How to contribute to Zigfetch
## Did you find a bug?
- Do not open up a GitHub issue if the bug is a security vulnerability, refer to the [security policy](https://github.com/utox39/zigfetch/blob/main/SECURITY.md).
- Ensure the bug was not already reported by searching on GitHub under [Issues](https://github.com/utox39/zigfetch/issues).
- If you're unable to find an open issue addressing the problem, open a new one.
## Do you want to make some changes to the code or documentation?
1. Fork the repo.
2. Create a new branch (because the `main` branch is protected).
3. Commit and push the changes to the new branch.
4. Open a pull request.
---
**Thank you for your contribution!**

104
README.md
View File

@@ -1,5 +1,18 @@
# Zigfetch # Zigfetch
![Zig](https://img.shields.io/badge/Zig-%23F7A41D.svg?style=flat&logo=zig&logoColor=white)
![GitHub Release](https://img.shields.io/github/v/release/utox39/zigfetch)
![GitHub License](https://img.shields.io/github/license/utox39/zigfetch)
![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/utox39/zigfetch/build.yml)
![macOS](https://img.shields.io/badge/mac%20os-000000?style=flat&logo=macos&logoColor=F0F0F0)
![Linux](https://img.shields.io/badge/Linux-FCC624?style=flat&logo=linux&logoColor=black)
| Default config | Custom config |
| :-----------------------------------------------------: | :---------------------------------------------------: |
| ![dafault-config](assets/screenshot-default-config.png) | ![custom-config](assets/screenshot-custom-config.png) |
---
- [Description](#description) - [Description](#description)
- [Requirements](#requirements) - [Requirements](#requirements)
- [Installation](#installation) - [Installation](#installation)
@@ -14,7 +27,7 @@ Zigfetch is a minimal [neofetch](https://github.com/dylanaraps/neofetch)/[fastfe
## Requirements ## Requirements
- \>= [zig v0.14.0](https://ziglang.org/) - \>= [zig v0.15.2](https://ziglang.org/)
### Linux only ### Linux only
@@ -22,6 +35,8 @@ Zigfetch is a minimal [neofetch](https://github.com/dylanaraps/neofetch)/[fastfe
## Installation ## Installation
### Build from source
```console ```console
# Clone the repo # Clone the repo
$ git clone https://github.com/utox39/zigfetch.git $ git clone https://github.com/utox39/zigfetch.git
@@ -36,6 +51,12 @@ $ zig build -Doptimize=ReleaseSafe
$ mv ./zig-out/zigfetch ~/bin/ $ mv ./zig-out/zigfetch ~/bin/
``` ```
### Via [Homebrew](https://brew.sh/)
```console
$ brew install utox39/tap/zigfetch
```
## Usage ## Usage
```console ```console
@@ -66,6 +87,85 @@ $ touch config.json
$ cp /path/to/zigfetch/config.json ~/.config/zigfetch/config.json $ cp /path/to/zigfetch/config.json ~/.config/zigfetch/config.json
``` ```
#### Modules
Available modules:
- Os
- Kernel
- Uptime
- Packages
- Shell
- Cpu
- Gpu
- Ram
- Swap
- Disk
- Net
- WM (Window Manager)
- Terminal
- Locale
- Custom
| Module type | Linux | macOS | Windows |
| :---------: | :-------------: | :----------------------: | :-----: |
| os | Yes | Yes | WIP |
| kernel | Yes | Yes | WIP |
| uptime | Yes | Yes | WIP |
| packages | WIP | Yes (Homebrew, Macports) | WIP |
| shell | Yes (bash, zsh) | Yes (bash, zsh) | WIP |
| cpu | Yes | Yes | WIP |
| gpu | Yes | Yes (Apple Silicon only) | WIP |
| ram | Yes | Yes | WIP |
| swap | Yes | Yes | WIP |
| disk | Yes | Yes | WIP |
| net | Yes | Yes | WIP |
| wm | Yes | Yes | WIP |
| terminal | Yes | Yes | WIP |
| locale | Yes | Yes | WIP |
```json
"modules": [
{
"type": "os",
"key": "OS",
"key_color": "#5E81AC"
},
...
]
```
#### Custom module
```json
"modules": [
{
"type": "custom",
"key": "-----------",
"key_color": "#5E81AC"
},
...
]
```
#### Custom ASCII art
To use an ASCII art of your choice:
```json
"ascii_abs_path": "absolute_path/to/your/ascii_art.txt"
```
Don't use the `~` character.
#### Username and Hostname color
To change the Username and Hostname color (HEX colors only):
```json
"username_hostname_color": "#5E81AC"
```
## Roadtrip ## Roadtrip
- [ ] Add ASCII art for each operating system and Linux distro - [ ] Add ASCII art for each operating system and Linux distro
@@ -76,4 +176,4 @@ $ cp /path/to/zigfetch/config.json ~/.config/zigfetch/config.json
## Contributing ## Contributing
If you would like to contribute to this project just create a pull request which I will try to review as soon as possible. Please see [CONTIBUTING](https://github.com/utox39/zigfetch/blob/main/CONTRIBUTING.md). Thanks!

Binary file not shown.

After

Width:  |  Height:  |  Size: 209 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 200 KiB

View File

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

View File

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

View File

@@ -65,22 +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 printAscii(allocator: std.mem.Allocator, sys_info_list: std.ArrayList([]u8)) !void { pub fn printAsciiAndModules(allocator: std.mem.Allocator, ascii_art_path: ?[]u8, sys_info_list: std.array_list.Managed([]u8)) !void {
const stdout_file = std.io.getStdOut().writer(); var stdout_buffer: [2048]u8 = undefined;
var bw = std.io.bufferedWriter(stdout_file); var stdout_writer = std.fs.File.stdout().writer(&stdout_buffer);
const stdout = bw.writer(); const stdout = &stdout_writer.interface;
// const ascii_art_path = "./assets/ascii/guy_fawks.txt"; var ascii_art_data: []const u8 = undefined;
// var file = try std.fs.cwd().openFile(ascii_art_path, .{}); if (ascii_art_path) |ascii| {
// defer file.close(); const ascii_file = try std.fs.cwd().openFile(ascii, .{ .mode = .read_only });
// const ascii_art_data = try file.readToEndAlloc(allocator, std.math.maxInt(usize)); defer ascii_file.close();
// defer allocator.free(ascii_art_data); const file_size = (try ascii_file.stat()).size;
ascii_art_data = try utils.readFile(allocator, ascii_file, file_size);
} else {
ascii_art_data = @embedFile("./assets/ascii/guy_fawks.txt");
}
const ascii_art_data = @embedFile("./assets/ascii/guy_fawks.txt"); defer if (ascii_art_path != null) {
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.ArrayList([]const u8).init(allocator); 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| {
@@ -90,13 +96,15 @@ pub fn printAscii(allocator: std.mem.Allocator, sys_info_list: std.ArrayList([]u
const ascii_art_items = ascii_art_content_list.items; const ascii_art_items = ascii_art_content_list.items;
const sys_info_items = sys_info_list.items; const sys_info_items = sys_info_list.items;
const terminal_size = try utils.getTerminalSize(); const terminal_size = utils.getTerminalSize() catch utils.TermSize{ .height = 50, .width = 50 };
const terminal_width: usize = @intCast(terminal_size.width); const terminal_width: usize = @intCast(terminal_size.width);
const left_alignment: usize = 45; 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 longest_sys_info_string_len = utils.getLongestSysInfoStringLen(sys_info_items);
const can_print_ascii_art: bool = terminal_width > left_alignment + longest_sys_info_string_len;
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 ascii_art_len: usize = ascii_art_items.len;
const sys_info_len: usize = sys_info_items.len; const sys_info_len: usize = sys_info_items.len;
@@ -106,14 +114,20 @@ pub fn printAscii(allocator: std.mem.Allocator, sys_info_list: std.ArrayList([]u
var i: usize = 0; var i: usize = 0;
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 left alignment (45) + 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 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, ' ');
if (i < ascii_art_len) { if (i < ascii_art_len) {
try stdout.print("{s:<45}", .{ascii_art_items[i]}); try stdout.print("{s}{s}", .{ ascii_art_items[i], alignment_buffer });
} else { } else {
try stdout.print("{s:<45}", .{""}); try stdout.print("{s}", .{alignment_buffer});
} }
try bw.flush();
allocator.free(alignment_buffer);
try stdout.flush();
} }
if (i < sys_info_len) { if (i < sys_info_len) {
@@ -133,7 +147,7 @@ pub fn printAscii(allocator: std.mem.Allocator, sys_info_list: std.ArrayList([]u
} else { } else {
try stdout.print("\n", .{}); try stdout.print("\n", .{});
} }
try bw.flush(); try stdout.flush();
} }
for (sys_info_list.items) |item| { for (sys_info_list.items) |item| {

View File

@@ -1,6 +1,6 @@
const std = @import("std"); const std = @import("std");
const builtin = @import("builtin");
const ascii = @import("ascii.zig"); const ascii = @import("ascii.zig");
const utils = @import("utils.zig");
pub const Module = struct { pub const Module = struct {
type: []u8, type: []u8,
@@ -9,6 +9,8 @@ pub const Module = struct {
}; };
pub const Config = struct { pub const Config = struct {
ascii_abs_path: ?[]u8 = null,
username_hostname_color: ?[]u8 = null,
modules: []Module, modules: []Module,
}; };
@@ -24,13 +26,26 @@ pub const ModuleType = enum {
swap, swap,
disk, disk,
net, net,
wm,
terminal, terminal,
locale, locale,
custom, custom,
}; };
pub fn getModulesTypes(allocator: std.mem.Allocator, config: ?std.json.Parsed(Config)) !std.ArrayList(ModuleType) { pub fn getAsciiPath(config: ?std.json.Parsed(Config)) ?[]u8 {
var modules_list = std.ArrayList(ModuleType).init(allocator); if (config) |c| {
return c.value.ascii_abs_path;
} else return null;
}
pub fn getUsernameHostnameColor(config: ?std.json.Parsed(Config)) ?[]u8 {
if (config) |c| {
return c.value.username_hostname_color;
} else return null;
}
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| { if (config) |c| {
for (c.value.modules) |module| { for (c.value.modules) |module| {
@@ -38,6 +53,7 @@ pub fn getModulesTypes(allocator: std.mem.Allocator, config: ?std.json.Parsed(Co
if (module_enum) |m| { if (module_enum) |m| {
try modules_list.append(m); try modules_list.append(m);
} else { } else {
modules_list.deinit();
return error.InvalidModule; return error.InvalidModule;
} }
} }
@@ -53,14 +69,16 @@ pub fn readConfigFile(allocator: std.mem.Allocator) !?std.json.Parsed(Config) {
const config_abs_path = try std.mem.concat(allocator, u8, &.{ home, "/.config/zigfetch/config.json" }); const config_abs_path = try std.mem.concat(allocator, u8, &.{ home, "/.config/zigfetch/config.json" });
defer allocator.free(config_abs_path); defer allocator.free(config_abs_path);
const file = std.fs.openFileAbsolute(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 file.close(); defer config_file.close();
const data = try file.readToEndAlloc(allocator, std.math.maxInt(usize)); const file_size = (try config_file.stat()).size;
defer allocator.free(data);
return try std.json.parseFromSlice(Config, allocator, data, .{ .allocate = .alloc_always }); const config_data = try utils.readFile(allocator, config_file, file_size);
defer allocator.free(config_data);
return try std.json.parseFromSlice(Config, allocator, config_data, .{ .allocate = .alloc_always });
} }

View File

@@ -5,7 +5,7 @@ const detection = @import("detection.zig").os_module;
const Result = union(enum) { const Result = union(enum) {
string: []u8, 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{ pub const formatters = [_]*const fn (allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) anyerror!Result{
@@ -20,6 +20,7 @@ pub const formatters = [_]*const fn (allocator: std.mem.Allocator, key: []const
&getFormattedSwapInfo, &getFormattedSwapInfo,
&getFormattedDiskInfo, &getFormattedDiskInfo,
&getFormattedNetInfo, &getFormattedNetInfo,
&getFormattedWindowManagerInfo,
&getFormattedTerminalNameInfo, &getFormattedTerminalNameInfo,
&getFormattedLocaleInfo, &getFormattedLocaleInfo,
&getFormattedCustom, &getFormattedCustom,
@@ -37,10 +38,22 @@ pub const default_formatters = [_]*const fn (allocator: std.mem.Allocator) anyer
&getDefaultFormattedSwapInfo, &getDefaultFormattedSwapInfo,
&getDefaultFormattedDiskInfo, &getDefaultFormattedDiskInfo,
&getDefaultFormattedNetInfo, &getDefaultFormattedNetInfo,
&getDefaultFormattedWindowManagerInfo,
&getDefaultFormattedTerminalNameInfo, &getDefaultFormattedTerminalNameInfo,
&getDefaultFormattedLocaleInfo, &getDefaultFormattedLocaleInfo,
}; };
pub fn getFormattedUsernameHostname(allocator: std.mem.Allocator, color: []const u8, username: []const u8, hostname: []const u8) ![]u8 {
return try std.fmt.allocPrint(allocator, "{s}{s}{s}@{s}{s}{s}", .{
color,
username,
ascii.Reset,
color,
hostname,
ascii.Reset,
});
}
pub fn getDefaultFormattedKernelInfo(allocator: std.mem.Allocator) !Result { pub fn getDefaultFormattedKernelInfo(allocator: std.mem.Allocator) !Result {
return try getFormattedKernelInfo(allocator, "Kernel", ascii.Yellow); return try getFormattedKernelInfo(allocator, "Kernel", ascii.Yellow);
} }
@@ -130,7 +143,7 @@ pub fn getFormattedGpuInfo(allocator: std.mem.Allocator, key: []const u8, key_co
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", .{ key_color, key, ascii.Reset, gpu_info.gpu_name, gpu_info.gpu_cores, gpu_info.gpu_freq }) }; 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) { } 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); const gpu_info_list = try detection.hardware.getGpuInfo(allocator);
@@ -181,6 +194,16 @@ pub fn getFormattedDiskInfo(allocator: std.mem.Allocator, key: []const u8, key_c
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 }) }; 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 }) };
} }
pub fn getDefaultFormattedWindowManagerInfo(allocator: std.mem.Allocator) !Result {
return try getFormattedWindowManagerInfo(allocator, "WM", ascii.Yellow);
}
pub fn getFormattedWindowManagerInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
const wm = try detection.system.getWindowManagerInfo(allocator);
defer allocator.free(wm);
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s}", .{ key_color, key, ascii.Reset, wm }) };
}
pub fn getDefaultFormattedTerminalNameInfo(allocator: std.mem.Allocator) !Result { pub fn getDefaultFormattedTerminalNameInfo(allocator: std.mem.Allocator) !Result {
return try getFormattedTerminalNameInfo(allocator, "Terminal", ascii.Yellow); return try getFormattedTerminalNameInfo(allocator, "Terminal", ascii.Yellow);
} }
@@ -196,7 +219,7 @@ pub fn getDefaultFormattedNetInfo(allocator: std.mem.Allocator) !Result {
} }
pub fn getFormattedNetInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !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); var net_info_list = try detection.network.getNetInfo(allocator);
for (net_info_list.items) |n| { for (net_info_list.items) |n| {

View File

@@ -1,4 +1,5 @@
const std = @import("std"); const std = @import("std");
const utils = @import("../utils.zig");
const c_unistd = @cImport(@cInclude("unistd.h")); const c_unistd = @cImport(@cInclude("unistd.h"));
const c_statvfs = @cImport(@cInclude("sys/statvfs.h")); const c_statvfs = @cImport(@cInclude("sys/statvfs.h"));
const c_libpci = @cImport(@cInclude("pci/pci.h")); const c_libpci = @cImport(@cInclude("pci/pci.h"));
@@ -44,9 +45,16 @@ pub fn getCpuInfo(allocator: std.mem.Allocator) !CpuInfo {
// Reads /proc/cpuinfo // Reads /proc/cpuinfo
const cpuinfo_path = "/proc/cpuinfo"; const cpuinfo_path = "/proc/cpuinfo";
var file = try std.fs.cwd().openFile(cpuinfo_path, .{}); const cpuinfo_file = try std.fs.cwd().openFile(cpuinfo_path, .{ .mode = .read_only });
defer file.close(); defer cpuinfo_file.close();
const cpuinfo_data = try file.readToEndAlloc(allocator, std.math.maxInt(usize));
// 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://en.wikipedia.org/wiki/Procfs
//
// Only the first section (core 0) will be parsed
// 512 is more than enough
const cpuinfo_data = try utils.readFile(allocator, cpuinfo_file, 512);
defer allocator.free(cpuinfo_data); defer allocator.free(cpuinfo_data);
// Parsing /proc/cpuinfo // Parsing /proc/cpuinfo
@@ -77,6 +85,7 @@ pub fn getCpuInfo(allocator: std.mem.Allocator) !CpuInfo {
var cpu_max_freq: f32 = 0.0; var cpu_max_freq: f32 = 0.0;
// NOTE: this is the preferred approach beacause it is the most accurate
const cpuinfo_max_freq_path = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"; const cpuinfo_max_freq_path = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq";
var cmf_exists: bool = true; var cmf_exists: bool = true;
@@ -89,14 +98,13 @@ pub fn getCpuInfo(allocator: std.mem.Allocator) !CpuInfo {
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
var file2 = try std.fs.cwd().openFile(cpuinfo_max_freq_path, .{}); const maxfreq_file = try std.fs.cwd().openFile(cpuinfo_max_freq_path, .{ .mode = .read_only });
defer maxfreq_file.close();
defer file2.close(); const maxfreq_data = try utils.readFile(allocator, maxfreq_file, 32);
const cpuinfo_max_freq_data = try file2.readToEndAlloc(allocator, std.math.maxInt(usize)); defer allocator.free(maxfreq_data);
defer allocator.free(cpuinfo_max_freq_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, cpuinfo_max_freq_data, " \n\r"); const trimmed = std.mem.trim(u8, maxfreq_data, " \n\r");
const cpu_max_freq_khz: f32 = try std.fmt.parseFloat(f32, trimmed); const cpu_max_freq_khz: f32 = try std.fmt.parseFloat(f32, trimmed);
cpu_max_freq = cpu_max_freq_khz / 1_000_000; cpu_max_freq = cpu_max_freq_khz / 1_000_000;
} else { } else {
@@ -113,8 +121,8 @@ pub fn getCpuInfo(allocator: std.mem.Allocator) !CpuInfo {
}; };
} }
pub fn getGpuInfo(allocator: std.mem.Allocator) !std.ArrayList(GpuInfo) { pub fn getGpuInfo(allocator: std.mem.Allocator) !std.array_list.Managed(GpuInfo) {
var gpu_info_list = std.ArrayList(GpuInfo).init(allocator); var gpu_info_list = std.array_list.Managed(GpuInfo).init(allocator);
const display_controller = 0x03; const display_controller = 0x03;
@@ -203,9 +211,16 @@ fn parseGpuName(allocator: std.mem.Allocator, name: []u8) !?[]u8 {
pub fn getRamInfo(allocator: std.mem.Allocator) !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 file = try std.fs.cwd().openFile(meminfo_path, .{}); const meminfo_file = try std.fs.cwd().openFile(meminfo_path, .{ .mode = .read_only });
defer file.close(); defer meminfo_file.close();
const meminfo_data = try file.readToEndAlloc(allocator, std.math.maxInt(usize));
// 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://en.wikipedia.org/wiki/Procfs
//
// We only need to read the first few lines
// 512 is more than enough
const meminfo_data = try utils.readFile(allocator, meminfo_file, 512);
defer allocator.free(meminfo_data); defer allocator.free(meminfo_data);
// Parsing /proc/meminfo // Parsing /proc/meminfo
@@ -265,9 +280,16 @@ pub fn getRamInfo(allocator: std.mem.Allocator) !RamInfo {
pub fn getSwapInfo(allocator: std.mem.Allocator) !?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 file = try std.fs.cwd().openFile(meminfo_path, .{}); const meminfo_file = try std.fs.cwd().openFile(meminfo_path, .{ .mode = .read_only });
defer file.close(); defer meminfo_file.close();
const meminfo_data = try file.readToEndAlloc(allocator, std.math.maxInt(usize));
// 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://en.wikipedia.org/wiki/Procfs
//
// We only need to read the first few lines
// 512 is ok
const meminfo_data = try utils.readFile(allocator, meminfo_file, 512);
defer allocator.free(meminfo_data); defer allocator.free(meminfo_data);
// Parsing /proc/meminfo // Parsing /proc/meminfo

View File

@@ -11,8 +11,8 @@ pub const NetInfo = struct {
ipv4_addr: []u8, ipv4_addr: []u8,
}; };
pub fn getNetInfo(allocator: std.mem.Allocator) !std.ArrayList(NetInfo) { pub fn getNetInfo(allocator: std.mem.Allocator) !std.array_list.Managed(NetInfo) {
var net_info_list = std.ArrayList(NetInfo).init(allocator); 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) {

View File

@@ -1,4 +1,5 @@
const std = @import("std"); const std = @import("std");
const utils = @import("../utils.zig");
const c_sysinfo = @cImport(@cInclude("sys/sysinfo.h")); const c_sysinfo = @cImport(@cInclude("sys/sysinfo.h"));
const c_utsname = @cImport(@cInclude("sys/utsname.h")); const c_utsname = @cImport(@cInclude("sys/utsname.h"));
@@ -77,9 +78,10 @@ pub fn getKernelInfo(allocator: std.mem.Allocator) !KernelInfo {
pub fn getOsInfo(allocator: std.mem.Allocator) ![]u8 { pub fn getOsInfo(allocator: std.mem.Allocator) ![]u8 {
const os_release_path = "/etc/os-release"; const os_release_path = "/etc/os-release";
const file = try std.fs.cwd().openFile(os_release_path, .{}); const os_release_file = try std.fs.cwd().openFile(os_release_path, .{ .mode = .read_only });
defer file.close(); defer os_release_file.close();
const os_release_data = try file.readToEndAlloc(allocator, std.math.maxInt(usize)); const size = (try os_release_file.stat()).size;
const os_release_data = try utils.readFile(allocator, os_release_file, size);
defer allocator.free(os_release_data); defer allocator.free(os_release_data);
var pretty_name: ?[]const u8 = null; var pretty_name: ?[]const u8 = null;
@@ -98,3 +100,56 @@ pub fn getOsInfo(allocator: std.mem.Allocator) ![]u8 {
return try allocator.dupe(u8, pretty_name orelse "Unknown"); return try allocator.dupe(u8, pretty_name orelse "Unknown");
} }
pub fn getWindowManagerInfo(allocator: std.mem.Allocator) ![]const u8 {
var dir = try std.fs.cwd().openDir("/proc/", .{ .iterate = true });
defer dir.close();
var wm_name: ?[]const u8 = null;
var iter = dir.iterate();
wm_name = outer: {
while (try iter.next()) |entry| {
if (entry.kind != .directory) continue;
// Check if the entry name is numeric
_ = std.fmt.parseInt(i32, entry.name, 10) catch continue;
var buf: [1024]u8 = undefined;
const file_name = try std.fmt.bufPrint(&buf, "/proc/{s}/comm", .{entry.name});
const file = try std.fs.cwd().openFile(file_name, .{ .mode = .read_only });
defer file.close();
// 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(allocator, file, 16);
defer allocator.free(proc_name);
const proc_name_trimmed = std.mem.trim(u8, proc_name, "\n");
const supported_wms: [9][]const u8 = .{
"i3", // https://i3wm.org/
// "i3gaps", // TODO: find a way to recognize i3gaps
"sway", // https://swaywm.org/
// "swayfx", // TODO: find a way to recognize swayfx
"niri", // https://github.com/YaLTeR/niri
"dwm", // https://dwm.suckless.org/
// "qtile", // TODO: find a way to recognize qtile
"awesome", // https://awesomewm.org/
"river", // https://codeberg.org/river/river
"hyprland", // https://hypr.land/
"bspwm", // https://github.com/baskerville/bspwm
"openbox", // https://openbox.org/
};
inline for (supported_wms) |wm| {
if (std.ascii.eqlIgnoreCase(wm, proc_name_trimmed)) {
break :outer try allocator.dupe(u8, proc_name_trimmed);
}
}
}
break :outer null;
};
return wm_name orelse allocator.dupe(u8, "Unknown");
}

View File

@@ -10,25 +10,18 @@ pub fn getShell(allocator: std.mem.Allocator) ![]u8 {
return allocator.dupe(u8, "Unknown"); return allocator.dupe(u8, "Unknown");
} else return err; } else return err;
var child = std.process.Child.init(&[_][]const u8{ shell, "--version" }, allocator);
defer allocator.free(shell); defer allocator.free(shell);
child.stdout_behavior = .Pipe; const result = try std.process.Child.run(.{ .allocator = allocator, .argv = &[_][]const u8{ shell, "--version" } });
child.stderr_behavior = .Pipe; const result_stdout = result.stdout;
try child.spawn();
const output = try child.stdout.?.reader().readAllAlloc(allocator, 1024 * 1024);
_ = try child.wait();
if (std.mem.indexOf(u8, shell, "bash") != null) { if (std.mem.indexOf(u8, shell, "bash") != null) {
const bash_version = parseBashVersion(output); const bash_version = parseBashVersion(result_stdout);
defer allocator.free(output); defer allocator.free(result_stdout);
return try std.fmt.allocPrint(allocator, "{s} {s}", .{ "bash", bash_version.? }); return try std.fmt.allocPrint(allocator, "{s} {s}", .{ "bash", bash_version.? });
} }
return output; return result_stdout;
} }
fn parseBashVersion(shell_version_output: []u8) ?[]u8 { fn parseBashVersion(shell_version_output: []u8) ?[]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.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.cfStringToZigString(allocator, @as(c_iokit.CFStringRef, @ptrCast(name_ref))) catch { const accel_name = utils.cfTypeRefToZigString(allocator, name_ref) catch {
return gpu_info; return gpu_info;
}; };

View File

@@ -11,8 +11,8 @@ pub const NetInfo = struct {
ipv4_addr: []u8, ipv4_addr: []u8,
}; };
pub fn getNetInfo(allocator: std.mem.Allocator) !std.ArrayList(NetInfo) { pub fn getNetInfo(allocator: std.mem.Allocator) !std.array_list.Managed(NetInfo) {
var net_info_list = std.ArrayList(NetInfo).init(allocator); 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) {

View File

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

View File

@@ -128,3 +128,68 @@ pub fn getOsInfo(allocator: std.mem.Allocator) ![]u8 {
return os_info; return os_info;
} }
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 size: usize = 0;
// First call to get the dimension
if (c_sysctl.sysctl(&name, name.len, null, &size, null, 0) != 0) {
return error.SysctlFailed;
}
const buffer: []u8 = try allocator.alloc(u8, size);
defer allocator.free(buffer);
// Second call to retrieve process data
if (c_sysctl.sysctl(&name, name.len, buffer.ptr, &size, null, 0) != 0) {
return error.SysctlFailed;
}
// Ensure the buffer size is valid
if (size % @sizeOf(c_sysctl.struct_kinfo_proc) != 0) {
return error.InvalidBufferSize;
}
const kinfo_list = std.mem.bytesAsSlice(c_sysctl.struct_kinfo_proc, buffer);
var wm_name: ?[]const u8 = null;
const supported_wms: [6][]const u8 = .{
"aerospace",
"amethyst",
"chunkwm",
"rectangle",
"spectacle",
"yabai",
};
wm_name = outer: {
for (kinfo_list) |kinfo| {
const pid = kinfo.kp_proc.p_pid;
if (pid <= 0) continue;
// Gets the process pathname
var pathbuf: [c_libproc.PROC_PIDPATHINFO_MAXSIZE]u8 = undefined;
// 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 proc_pathname = if (path_len > 0) try allocator.dupe(u8, pathbuf[0..@intCast(path_len)]) else try allocator.dupe(u8, "unknown");
defer allocator.free(proc_pathname);
inline for (supported_wms) |wm| {
if (std.ascii.endsWithIgnoreCase(proc_pathname, wm)) {
const basename = if (std.mem.lastIndexOfScalar(u8, proc_pathname, '/')) |index|
proc_pathname[index + 1 ..]
else
proc_pathname;
break :outer try allocator.dupe(u8, basename);
}
}
}
break :outer null;
};
return wm_name orelse allocator.dupe(u8, "Quartz Compositor");
}

View File

@@ -13,25 +13,18 @@ pub fn getShell(allocator: std.mem.Allocator) ![]u8 {
return allocator.dupe(u8, "Unknown"); return allocator.dupe(u8, "Unknown");
} else return err; } else return err;
var child = std.process.Child.init(&[_][]const u8{ shell, "--version" }, allocator);
defer allocator.free(shell); defer allocator.free(shell);
child.stdout_behavior = .Pipe; const result = try std.process.Child.run(.{ .allocator = allocator, .argv = &[_][]const u8{ shell, "--version" } });
child.stderr_behavior = .Pipe; const result_stdout = result.stdout;
try child.spawn();
const output = try child.stdout.?.reader().readAllAlloc(allocator, 1024 * 1024);
_ = try child.wait();
if (std.mem.indexOf(u8, shell, "bash") != null) { if (std.mem.indexOf(u8, shell, "bash") != null) {
const bash_version = parseBashVersion(output); const bash_version = parseBashVersion(result_stdout);
defer allocator.free(output); defer allocator.free(result_stdout);
return try std.fmt.allocPrint(allocator, "{s} {s}", .{ "bash", bash_version.? }); return try std.fmt.allocPrint(allocator, "{s} {s}", .{ "bash", bash_version.? });
} }
return output; return result_stdout;
} }
fn parseBashVersion(shell_version_output: []u8) ?[]u8 { fn parseBashVersion(shell_version_output: []u8) ?[]u8 {

View File

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

View File

@@ -10,11 +10,11 @@ pub fn main() !void {
const allocator = gpa.allocator(); const allocator = gpa.allocator();
defer _ = gpa.deinit(); defer _ = gpa.deinit();
var sys_info_list = std.ArrayList([]u8).init(allocator); var modules_list = std.array_list.Managed([]u8).init(allocator);
defer sys_info_list.deinit(); defer modules_list.deinit();
errdefer { errdefer {
for (sys_info_list.items) |info| { for (modules_list.items) |info| {
allocator.free(info); allocator.free(info);
} }
} }
@@ -27,29 +27,30 @@ pub fn main() !void {
const username = try detection.user.getUsername(allocator); const username = try detection.user.getUsername(allocator);
const hostname = try detection.system.getHostname(allocator); const hostname = try detection.system.getHostname(allocator);
try sys_info_list.append(try std.fmt.allocPrint(allocator, "{s}{s}{s}@{s}{s}{s}", .{
ascii.Yellow, const username_hostname_color = if (config.getUsernameHostnameColor(conf)) |color| blk: {
username, var buf: [32]u8 = undefined;
ascii.Reset, const rgb = try ascii.hexColorToRgb(color);
ascii.Yellow, const formatted_color = try std.fmt.bufPrint(&buf, "\x1b[38;2;{d};{d};{d}m", .{ rgb.r, rgb.g, rgb.b });
hostname, break :blk formatted_color;
ascii.Reset, } else ascii.Yellow;
}));
try modules_list.append(try formatters.getFormattedUsernameHostname(allocator, username_hostname_color, username, hostname));
allocator.free(hostname); allocator.free(hostname);
allocator.free(username); allocator.free(username);
const separtor_buffer = try allocator.alloc(u8, username.len + hostname.len + 1); const separtor_buffer = try allocator.alloc(u8, username.len + hostname.len + 1);
@memset(separtor_buffer, '-'); @memset(separtor_buffer, '-');
try sys_info_list.append(separtor_buffer); try modules_list.append(separtor_buffer);
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](allocator); const result = try formatters.default_formatters[i](allocator);
switch (result) { switch (result) {
.string => |r| try sys_info_list.append(r), .string => |r| try modules_list.append(r),
.string_arraylist => |r| { .string_arraylist => |r| {
defer r.deinit(); defer r.deinit();
try sys_info_list.appendSlice(r.items); try modules_list.appendSlice(r.items);
}, },
} }
} }
@@ -61,14 +62,14 @@ pub fn main() !void {
const result = try formatters.formatters[@intFromEnum(module_type)](allocator, module.key, key_color); const result = try formatters.formatters[@intFromEnum(module_type)](allocator, module.key, key_color);
switch (result) { switch (result) {
.string => |r| try sys_info_list.append(r), .string => |r| try modules_list.append(r),
.string_arraylist => |r| { .string_arraylist => |r| {
defer r.deinit(); defer r.deinit();
try sys_info_list.appendSlice(r.items); try modules_list.appendSlice(r.items);
}, },
} }
} }
} }
try ascii.printAscii(allocator, sys_info_list); try ascii.printAsciiAndModules(allocator, 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.getStdOut(); const stdout = std.fs.File.stdout();
switch (builtin.os.tag) { switch (builtin.os.tag) {
.windows => { .windows => {
@@ -43,7 +43,7 @@ pub fn getTerminalSize() !TermSize {
} }
test "getTerminalSize" { test "getTerminalSize" {
const terminal_size = try getTerminalSize(); const terminal_size = getTerminalSize() catch TermSize{ .height = 50, .width = 50 };
std.debug.print("Height: {}, Width {}\n", .{ terminal_size.height, terminal_size.width }); std.debug.print("Height: {}, Width {}\n", .{ terminal_size.height, terminal_size.width });
@@ -77,3 +77,51 @@ test "getLongestSysInfoStringLen" {
try std.testing.expectEqual(strings[3].len, getLongestSysInfoStringLen(strings[0..])); 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..]));
}
pub fn readFile(allocator: std.mem.Allocator, file: std.fs.File, size: usize) ![]const u8 {
var file_buf = try allocator.alloc(u8, size);
defer allocator.free(file_buf);
const read = try file.read(file_buf);
const data = file_buf[0..read];
return allocator.dupe(u8, data);
}