114 Commits

Author SHA1 Message Date
utox39
1949f607a1 refactor: rename all 'allocator' args to 'gpa' 2026-02-15 18:00:59 +01:00
utox39
739b8d49f0 fix(linux-shell): fix bash version parsing 2026-02-13 15:34:44 +01:00
utox39
0cc20bcce6 fix(formatters): make correct function calls 2026-02-12 20:30:35 +01:00
utox39
3c909aff0e refactor(linux-packages): use new Io and Environ 2026-02-12 20:28:56 +01:00
utox39
e9f34fa62d refactor(linux-system): use new Io 2026-02-12 18:20:52 +01:00
utox39
20d33b165e refactor(linux-hardware): use new Io 2026-02-12 18:09:31 +01:00
utox39
a62eece487 refactor(linux-system): use new Io 2026-02-12 17:56:07 +01:00
utox39
dff5b6e516 refactor(linux-hardware): use new Io 2026-02-12 17:55:12 +01:00
utox39
524fec5821 chore: update .gitignore 2026-02-12 16:52:36 +01:00
utox39
73e493809e feat(formatters): add FormatterContext 2026-02-12 16:51:40 +01:00
utox39
fff21b39fc refactor: rename ascii.zig to dispaly.zig 2026-02-11 20:00:38 +01:00
utox39
b6b2c158ea refactor(utils): use new Io 2026-02-11 19:53:35 +01:00
utox39
36959a5e9f refactor(terminal-name): use the new Environ 2026-02-11 19:24:47 +01:00
utox39
cf7b62ac90 refactor(macos-shell): use process.run function and new Environ 2026-02-11 19:21:38 +01:00
utox39
d04745ad63 refactor(macos-shell): use process.run function 2026-02-11 19:01:02 +01:00
utox39
5771e03281 refactor(macos-shell): use new Environ 2026-02-11 18:57:34 +01:00
utox39
6c70dac17c refactor(macos-uptime): use new Io Timestamp 2026-02-11 18:51:10 +01:00
utox39
525156f4c6 refactor(macos-system): use new Environ method 2026-02-11 18:33:41 +01:00
utox39
51f6ddc2d1 refactor(linux-user): use new Environ method 2026-02-11 18:33:03 +01:00
utox39
9764de5353 refactor(config): use new Environ method 2026-02-11 15:45:24 +01:00
utox39
c3bbae9959 refactor(utils): use new Io 2026-02-11 15:44:41 +01:00
utox39
f60c4e56b2 refactor(config): use new Environ methods and new Io 2026-02-11 15:44:07 +01:00
utox39
a7d1baef92 refactor: use new Io 2026-02-11 15:41:41 +01:00
utox39
4388bbd5d5 refactor(ascii): use new Io 2026-02-11 14:59:25 +01:00
utox39
c13015db27 build: update build.zig 2026-02-11 13:37:49 +01:00
utox39
8bd839a567 chore: update .gitignore 2026-02-10 16:28:26 +01:00
utox39
7c7b214c1d build: add default.nix 2026-02-10 16:24:11 +01:00
utox39
41af324564 docs(README): update README 2025-12-21 02:29:06 +01:00
utox39
366cd7b497 docs(README): update README 2025-12-21 02:26:38 +01:00
utox39
d85ae15fe6 build(build.yml): add a new path 2025-12-15 23:41:40 +01:00
utox39
19edc21b89 build(build.yml): bump zig version to 0.15.2 2025-12-15 23:40:07 +01:00
utox39
d50ccb06b1 build(build.yml): bump to macos-15 x86_64 2025-12-15 23:37:26 +01:00
utox39
c8fb8d6a3e Merge pull request #30 from utox39/feat-linux/packages
Feat linux/packages
2025-12-15 23:33:33 +01:00
utox39
df0f21bc48 docs: update README 2025-12-15 23:29:33 +01:00
utox39
8258df5aae docs: update README 2025-12-15 23:26:49 +01:00
utox39
937746ad50 build: bump version to 0.25.0 2025-12-15 23:16:16 +01:00
utox39
6ca8dcf334 perf(linux-packages): improve nix packages counting speed by adding a cache system 2025-12-15 23:12:44 +01:00
utox39
87d31a9112 refactor(linux-packages): switch Flatpak package counting to filesystem-based method 2025-12-14 20:19:54 +01:00
utox39
c867ea69c6 feat(linux-packages): add packages count 2025-12-14 02:28:52 +01:00
utox39
29d5bb1d98 refactor(linux-packages): change a comment 2025-12-14 02:09:50 +01:00
utox39
a88aab97ff feat(linux-packages): add xbps packages count 2025-12-14 02:08:27 +01:00
utox39
2de0d6ec09 feat(linux-packages): add pacman packages count 2025-12-09 21:24:24 +01:00
utox39
6f4e4eb044 refactor(utils): move countEntries from macos utils in common utils 2025-12-09 19:35:10 +01:00
utox39
a64db7a7d3 feat(linux-packages): add dpkg packages count 2025-12-09 18:25:57 +01:00
utox39
e2cbda50c1 fix(linux-packages): fix a memory leak caused by the child process writing to stderr 2025-12-09 18:25:40 +01:00
utox39
51de84d210 refactor(linux-packages): rename countFlatpaks to countFlatpakPackages 2025-12-06 23:17:24 +01:00
utox39
b9dc58fabe feat(linux-packages): add Nix packages count 2025-12-06 19:28:12 +01:00
utox39
2dfcadf413 feat(linux-packages): add flatpak packages count 2025-12-06 19:27:16 +01:00
utox39
2ea3adef12 build: add shell.nix 2025-11-15 16:06:25 +01:00
utox39
b4b92abcb5 docs(README): update README 2025-10-17 19:20:06 +02:00
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
27 changed files with 1137 additions and 306 deletions

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

@@ -0,0 +1,100 @@
name: Build
on:
push:
branches: ["main"]
paths:
- ".github/workflows/build.yml"
- "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-15
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.2
- 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

4
.gitignore vendored
View File

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

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!**

157
README.md
View File

@@ -2,18 +2,24 @@
![Zig](https://img.shields.io/badge/Zig-%23F7A41D.svg?style=flat&logo=zig&logoColor=white) ![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 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) ![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) ![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)
- [Usage](#usage) - [Usage](#usage)
- [Configuration](#configuration) - [Configuration](#configuration)
- [Roadtrip](#roadtrip) - [Roadtrip](#roadtrip)
- [Contributing](#contributing) - [Contributing](#contributing)
## Description ## Description
@@ -21,15 +27,17 @@ Zigfetch is a minimal [neofetch](https://github.com/dylanaraps/neofetch)/[fastfe
## Requirements ## Requirements
- \>= [zig v0.15.1](https://ziglang.org/) - \>= [zig v0.15.2](https://ziglang.org/)
### Linux only ### Linux only
- [libpci](https://github.com/pciutils/pciutils) - [libpci](https://github.com/pciutils/pciutils)
## Installation ## Installation
```console ### Build from source
```bash
# Clone the repo # Clone the repo
$ git clone https://github.com/utox39/zigfetch.git $ git clone https://github.com/utox39/zigfetch.git
@@ -43,10 +51,22 @@ $ zig build -Doptimize=ReleaseSafe
$ mv ./zig-out/zigfetch ~/bin/ $ mv ./zig-out/zigfetch ~/bin/
``` ```
### Via [Homebrew](https://brew.sh/)
```bash
brew install utox39/tap/zigfetch
```
### Other package managers
[![Packaging status](https://repology.org/badge/vertical-allrepos/zigfetch.svg)](https://repology.org/project/zigfetch/versions)
- nixpkg: Thanks to [@heisfer](https://github.com/heisfer)
## Usage ## Usage
```console ```bash
$ zigfetch zigfetch
``` ```
### Configuration ### Configuration
@@ -54,33 +74,114 @@ $ zigfetch
> [!IMPORTANT] > [!IMPORTANT]
> Currently, Zig does not have a built-in library for JSON validation via JSON schema, so it is very important to follow the pattern shown in the default configuration file ([config.json](https://github.com/utox39/zigfetch/blob/main/config.json)) to avoid errors > Currently, Zig does not have a built-in library for JSON validation via JSON schema, so it is very important to follow the pattern shown in the default configuration file ([config.json](https://github.com/utox39/zigfetch/blob/main/config.json)) to avoid errors
- Create the config folder - Create the config folder
```console ```bash
$ mkdir -p ~/.config/zigfetch mkdir -p ~/.config/zigfetch
``` ```
- Create the config file - Create the config file
```console ```bash
$ cd ~/.config/zigfetch cd ~/.config/zigfetch
$ touch config.json touch config.json
``` ```
- Or copy the default config (preferred way) - Or copy the default config (preferred way)
```console ```bash
$ 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 | Yes* | 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 |
\*(flatpak, nix, dpkg, pacman, xbps)
```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
- [x] Add GPU info for Linux - [x] Add GPU info for Linux
- [ ] Add packages info for Linux - [x] Add packages info for Linux
- [x] Add user customization - [x] Add user customization
- [ ] Add support for Windows - [ ] Add support for Windows
## 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

@@ -25,13 +25,11 @@ pub fn build(b: *std.Build) void {
}); });
if (target.result.os.tag == .macos) { if (target.result.os.tag == .macos) {
exe.linkFramework("CoreFoundation"); exe.root_module.linkFramework("CoreFoundation", .{ .needed = true });
exe.linkFramework("IOKit"); exe.root_module.linkFramework("IOKit", .{ .needed = true });
} } else if (target.result.os.tag == .linux) {
exe.root_module.link_libc = true;
if (target.result.os.tag == .linux) { exe.root_module.linkSystemLibrary("pci", .{ .needed = true });
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

@@ -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.21.0", .version = "0.25.0",
// 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.15.1", .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`.

20
default.nix Normal file
View File

@@ -0,0 +1,20 @@
{ pkgs ? import <nixpkgs> {} }:
pkgs.stdenv.mkDerivation {
pname = "zigfetch";
version = "0.25.0";
src = ./.;
nativeBuildInputs = with pkgs; [
zig.hook
];
buildInputs = with pkgs; [
pciutils
];
zigBuildFlags = [
"-Doptimize=ReleaseSafe"
];
}

13
shell.nix Normal file
View File

@@ -0,0 +1,13 @@
{ pkgs ? import <nixpkgs> {} }:
let
unstable = import (builtins.fetchTarball {
url = "https://github.com/NixOS/nixpkgs/archive/nixos-unstable.tar.gz";
}) {};
in
pkgs.mkShell {
buildInputs = [
unstable.zig
pkgs.pciutils
];
}

View File

@@ -1,6 +1,6 @@
const std = @import("std"); const std = @import("std");
const builtin = @import("builtin"); const display = @import("display.zig");
const ascii = @import("ascii.zig"); const utils = @import("utils.zig");
pub const Module = struct { pub const Module = struct {
type: []u8, type: []u8,
@@ -10,6 +10,7 @@ pub const Module = struct {
pub const Config = struct { pub const Config = struct {
ascii_abs_path: ?[]u8 = null, ascii_abs_path: ?[]u8 = null,
username_hostname_color: ?[]u8 = null,
modules: []Module, modules: []Module,
}; };
@@ -25,17 +26,26 @@ pub const ModuleType = enum {
swap, swap,
disk, disk,
net, net,
wm,
terminal, terminal,
locale, locale,
custom, custom,
}; };
pub fn getAsciiPath(config: ?std.json.Parsed(Config)) ?[]u8 { pub fn getAsciiPath(config: ?std.json.Parsed(Config)) ?[]u8 {
return config.?.value.ascii_abs_path; if (config) |c| {
return c.value.ascii_abs_path;
} else return null;
} }
pub fn getModulesTypes(allocator: std.mem.Allocator, config: ?std.json.Parsed(Config)) !std.array_list.Managed(ModuleType) { pub fn getUsernameHostnameColor(config: ?std.json.Parsed(Config)) ?[]u8 {
var modules_list = std.array_list.Managed(ModuleType).init(allocator); if (config) |c| {
return c.value.username_hostname_color;
} else return null;
}
pub fn getModulesTypes(gpa: std.mem.Allocator, config: ?std.json.Parsed(Config)) !std.array_list.Managed(ModuleType) {
var modules_list = std.array_list.Managed(ModuleType).init(gpa);
if (config) |c| { if (config) |c| {
for (c.value.modules) |module| { for (c.value.modules) |module| {
@@ -43,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;
} }
} }
@@ -51,21 +62,23 @@ pub fn getModulesTypes(allocator: std.mem.Allocator, config: ?std.json.Parsed(Co
return modules_list; return modules_list;
} }
pub fn readConfigFile(allocator: std.mem.Allocator) !?std.json.Parsed(Config) { pub fn readConfigFile(gpa: std.mem.Allocator, io: std.Io, environ: std.process.Environ) !?std.json.Parsed(Config) {
const home = try std.process.getEnvVarOwned(allocator, "HOME"); const home = try std.process.Environ.getAlloc(environ, gpa, "HOME");
defer allocator.free(home); defer gpa.free(home);
const config_abs_path = try std.mem.concat(allocator, u8, &.{ home, "/.config/zigfetch/config.json" }); const config_abs_path = try std.mem.concat(gpa, u8, &.{ home, "/.config/zigfetch/config.json" });
defer allocator.free(config_abs_path); defer gpa.free(config_abs_path);
const file = std.fs.openFileAbsolute(config_abs_path, .{ .mode = .read_only }) catch |err| switch (err) { const config_file = std.Io.Dir.openFileAbsolute(io, 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(io);
const data = try file.readToEndAlloc(allocator, std.math.maxInt(usize)); const file_size = (try config_file.stat(io)).size;
defer allocator.free(data);
return try std.json.parseFromSlice(Config, allocator, data, .{ .allocate = .alloc_always }); const config_data = try utils.readFile(gpa, io, config_file, file_size);
defer gpa.free(config_data);
return try std.json.parseFromSlice(Config, gpa, config_data, .{ .allocate = .alloc_always });
} }

View File

@@ -65,27 +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(allocator: std.mem.Allocator, ascii_art_path: ?[]u8, sys_info_list: std.array_list.Managed([]u8)) !void { pub fn printAsciiAndModules(gpa: std.mem.Allocator, io: std.Io, 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_writer = std.fs.File.stdout().writer(&stdout_buffer); var stdout_file_writer: std.Io.File.Writer = .init(.stdout(), io, &stdout_buffer);
const stdout = &stdout_writer.interface; const stdout = &stdout_file_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| {
var ascii_file = try std.fs.cwd().openFile(ascii, .{}); const ascii_file = try std.Io.Dir.cwd().openFile(io, ascii, .{ .mode = .read_only });
defer ascii_file.close(); defer ascii_file.close(io);
ascii_art_data = try ascii_file.readToEndAlloc(allocator, std.math.maxInt(usize)); const file_size = (try ascii_file.stat(io)).size;
ascii_art_data = try utils.readFile(gpa, io, 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) {
allocator.free(ascii_art_data); gpa.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(allocator); var ascii_art_content_list = std.array_list.Managed([]const u8).init(gpa);
defer ascii_art_content_list.deinit(); defer ascii_art_content_list.deinit();
while (lines.next()) |line| { while (lines.next()) |line| {
@@ -95,7 +96,7 @@ pub fn printAsciiAndModules(allocator: std.mem.Allocator, ascii_art_path: ?[]u8,
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 spacing: usize = 5; const spacing: usize = 5;
@@ -115,7 +116,7 @@ pub fn printAsciiAndModules(allocator: std.mem.Allocator, ascii_art_path: ?[]u8,
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 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); 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);
@memset(alignment_buffer, ' '); @memset(alignment_buffer, ' ');
if (i < ascii_art_len) { if (i < ascii_art_len) {
@@ -124,7 +125,7 @@ pub fn printAsciiAndModules(allocator: std.mem.Allocator, ascii_art_path: ?[]u8,
try stdout.print("{s}", .{alignment_buffer}); try stdout.print("{s}", .{alignment_buffer});
} }
allocator.free(alignment_buffer); gpa.free(alignment_buffer);
try stdout.flush(); try stdout.flush();
} }
@@ -150,6 +151,6 @@ pub fn printAsciiAndModules(allocator: std.mem.Allocator, ascii_art_path: ?[]u8,
} }
for (sys_info_list.items) |item| { for (sys_info_list.items) |item| {
allocator.free(item); gpa.free(item);
} }
} }

View File

@@ -1,6 +1,6 @@
const builtin = @import("builtin"); const builtin = @import("builtin");
const std = @import("std"); const std = @import("std");
const ascii = @import("ascii.zig"); const display = @import("display.zig");
const detection = @import("detection.zig").os_module; const detection = @import("detection.zig").os_module;
const Result = union(enum) { const Result = union(enum) {
@@ -8,7 +8,13 @@ const Result = union(enum) {
string_arraylist: std.array_list.Managed([]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 FormatterContext = struct {
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,
@@ -20,12 +26,13 @@ pub const formatters = [_]*const fn (allocator: std.mem.Allocator, key: []const
&getFormattedSwapInfo, &getFormattedSwapInfo,
&getFormattedDiskInfo, &getFormattedDiskInfo,
&getFormattedNetInfo, &getFormattedNetInfo,
&getFormattedWindowManagerInfo,
&getFormattedTerminalNameInfo, &getFormattedTerminalNameInfo,
&getFormattedLocaleInfo, &getFormattedLocaleInfo,
&getFormattedCustom, &getFormattedCustom,
}; };
pub const default_formatters = [_]*const fn (allocator: std.mem.Allocator) anyerror!Result{ pub const default_formatters = [_]*const fn (fmt_ctx: FormatterContext) anyerror!Result{
&getDefaultFormattedOsInfo, &getDefaultFormattedOsInfo,
&getDefaultFormattedKernelInfo, &getDefaultFormattedKernelInfo,
&getDefaultFormattedUptimeInfo, &getDefaultFormattedUptimeInfo,
@@ -37,98 +44,173 @@ pub const default_formatters = [_]*const fn (allocator: std.mem.Allocator) anyer
&getDefaultFormattedSwapInfo, &getDefaultFormattedSwapInfo,
&getDefaultFormattedDiskInfo, &getDefaultFormattedDiskInfo,
&getDefaultFormattedNetInfo, &getDefaultFormattedNetInfo,
&getDefaultFormattedWindowManagerInfo,
&getDefaultFormattedTerminalNameInfo, &getDefaultFormattedTerminalNameInfo,
&getDefaultFormattedLocaleInfo, &getDefaultFormattedLocaleInfo,
}; };
pub fn getDefaultFormattedKernelInfo(allocator: std.mem.Allocator) !Result { pub fn getFormattedUsernameHostname(gpa: std.mem.Allocator, color: []const u8, username: []const u8, hostname: []const u8) ![]u8 {
return try getFormattedKernelInfo(allocator, "Kernel", ascii.Yellow); return try std.fmt.allocPrint(gpa, "{s}{s}{s}@{s}{s}{s}", .{
color,
username,
display.Reset,
color,
hostname,
display.Reset,
});
} }
pub fn getFormattedKernelInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result { pub fn getDefaultFormattedKernelInfo(fmt_ctx: FormatterContext) !Result {
return try getFormattedKernelInfo(fmt_ctx, "Kernel", display.Yellow);
}
pub fn getFormattedKernelInfo(fmt_ctx: FormatterContext, 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}", .{ key_color, key, ascii.Reset, kernel_info.kernel_name, kernel_info.kernel_release }) }; return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s} {s}", .{
key_color,
key,
display.Reset,
kernel_info.kernel_name,
kernel_info.kernel_release,
}) };
} }
pub fn getDefaultFormattedOsInfo(allocator: std.mem.Allocator) !Result { pub fn getDefaultFormattedOsInfo(fmt_ctx: FormatterContext) !Result {
return try getFormattedOsInfo(allocator, "OS", ascii.Yellow); return try getFormattedOsInfo(fmt_ctx, "OS", display.Yellow);
} }
pub fn getFormattedOsInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedOsInfo(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result {
const os_info = try detection.system.getOsInfo(allocator); const allocator = fmt_ctx.gpa;
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}", .{ key_color, key, ascii.Reset, os_info }) }; return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s}", .{
key_color,
key,
display.Reset,
os_info,
}) };
} }
pub fn getDefaultFormattedLocaleInfo(allocator: std.mem.Allocator) !Result { pub fn getDefaultFormattedLocaleInfo(fmt_ctx: FormatterContext) !Result {
return try getFormattedLocaleInfo(allocator, "Locale", ascii.Yellow); return try getFormattedLocaleInfo(fmt_ctx, "Locale", display.Yellow);
} }
pub fn getFormattedLocaleInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedLocaleInfo(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result {
const locale = try detection.system.getLocale(allocator); const allocator = fmt_ctx.gpa;
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}", .{ key_color, key, ascii.Reset, locale }) }; return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s}", .{
key_color,
key,
display.Reset,
locale,
}) };
} }
pub fn getDefaultFormattedUptimeInfo(allocator: std.mem.Allocator) !Result { pub fn getDefaultFormattedUptimeInfo(fmt_ctx: FormatterContext) !Result {
return try getFormattedUptimeInfo(allocator, "Uptime", ascii.Yellow); return try getFormattedUptimeInfo(fmt_ctx, "Uptime", display.Yellow);
} }
pub fn getFormattedUptimeInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedUptimeInfo(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result {
const uptime = try detection.system.getSystemUptime(); const allocator = fmt_ctx.gpa;
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 io = fmt_ctx.io;
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(allocator: std.mem.Allocator) !Result { pub fn getDefaultFormattedPackagesInfo(fmt_ctx: FormatterContext) !Result {
return try getFormattedPackagesInfo(allocator, "Packages", ascii.Yellow); return try getFormattedPackagesInfo(fmt_ctx, "Packages", display.Yellow);
} }
pub fn getFormattedPackagesInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedPackagesInfo(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result {
if (builtin.os.tag == .macos) { const allocator = fmt_ctx.gpa;
const packages_info = try detection.packages.getPackagesInfo(allocator); const io = fmt_ctx.io;
defer allocator.free(packages_info); const environ = fmt_ctx.environ;
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s}{s}", .{ key_color, key, ascii.Reset, packages_info }) };
} else if (builtin.os.tag == .linux) { 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);
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} WIP", .{ key_color, key, ascii.Reset }) }; defer allocator.free(packages_info);
} return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s}{s}", .{
key_color,
key,
display.Reset,
packages_info,
}) };
} }
pub fn getDefaultFormattedShellInfo(allocator: std.mem.Allocator) !Result { pub fn getDefaultFormattedShellInfo(fmt_ctx: FormatterContext) !Result {
return try getFormattedShellInfo(allocator, "Shell", ascii.Yellow); return try getFormattedShellInfo(fmt_ctx, "Shell", display.Yellow);
} }
pub fn getFormattedShellInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedShellInfo(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result {
const shell = try detection.user.getShell(allocator); const allocator = fmt_ctx.gpa;
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}", .{ key_color, key, ascii.Reset, shell[0..(shell.len - 1)] }) }; return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s}", .{
key_color,
key,
display.Reset,
shell[0..(shell.len - 1)],
}) };
} }
pub fn getDefaultFormattedCpuInfo(allocator: std.mem.Allocator) !Result { pub fn getDefaultFormattedCpuInfo(fmt_ctx: FormatterContext) !Result {
return try getFormattedCpuInfo(allocator, "Cpu", ascii.Yellow); return try getFormattedCpuInfo(fmt_ctx, "Cpu", display.Yellow);
} }
pub fn getFormattedCpuInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedCpuInfo(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result {
const cpu_info = try detection.hardware.getCpuInfo(allocator); const allocator = fmt_ctx.gpa;
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", .{ key_color, key, ascii.Reset, cpu_info.cpu_name, cpu_info.cpu_cores, cpu_info.cpu_max_freq }) }; return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s} ({}) @ {d:.2} GHz", .{
key_color,
key,
display.Reset,
cpu_info.cpu_name,
cpu_info.cpu_cores,
cpu_info.cpu_max_freq,
}) };
} }
pub fn getDefaultFormattedGpuInfo(allocator: std.mem.Allocator) !Result { pub fn getDefaultFormattedGpuInfo(fmt_ctx: FormatterContext) !Result {
if (builtin.os.tag == .macos) { return try getFormattedGpuInfo(fmt_ctx, "Gpu", display.Yellow);
return try getFormattedGpuInfo(allocator, "Gpu", ascii.Yellow);
} else if (builtin.os.tag == .linux) {
return try getFormattedGpuInfo(allocator, "Gpu", ascii.Yellow);
}
} }
pub fn getFormattedGpuInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedGpuInfo(fmt_ctx: FormatterContext, 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", .{ 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,
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);
@@ -137,9 +219,21 @@ pub fn getFormattedGpuInfo(allocator: std.mem.Allocator, key: []const u8, key_co
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}", .{ key_color, key, ascii.Reset, g.gpu_name }); formatted_gpu_info = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s}", .{
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", .{ key_color, key, ascii.Reset, g.gpu_name, g.gpu_cores, g.gpu_freq }); formatted_gpu_info = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s} ({}) @ {d:.2} GHz", .{
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);
@@ -150,57 +244,111 @@ pub fn getFormattedGpuInfo(allocator: std.mem.Allocator, key: []const u8, key_co
} }
} }
pub fn getDefaultFormattedRamInfo(allocator: std.mem.Allocator) !Result { pub fn getDefaultFormattedRamInfo(fmt_ctx: FormatterContext) !Result {
return try getFormattedRamInfo(allocator, "Ram", ascii.Yellow); return try getFormattedRamInfo(fmt_ctx, "Ram", display.Yellow);
} }
pub fn getFormattedRamInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedRamInfo(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result {
const ram_info = if (builtin.os.tag == .macos) try detection.hardware.getRamInfo() else if (builtin.os.tag == .linux) try detection.hardware.getRamInfo(allocator); const allocator = fmt_ctx.gpa;
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 io = fmt_ctx.io;
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(allocator: std.mem.Allocator) !Result { pub fn getDefaultFormattedSwapInfo(fmt_ctx: FormatterContext) !Result {
return try getFormattedSwapInfo(allocator, "Swap", ascii.Yellow); return try getFormattedSwapInfo(fmt_ctx, "Swap", display.Yellow);
} }
pub fn getFormattedSwapInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedSwapInfo(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result {
const swap_info = if (builtin.os.tag == .macos) try detection.hardware.getSwapInfo() else if (builtin.os.tag == .linux) try detection.hardware.getSwapInfo(allocator); const allocator = fmt_ctx.gpa;
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 ({}%)", .{ key_color, key, ascii.Reset, s.swap_usage, s.swap_size, s.swap_usage_percentage }) }; return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {d:.2} / {d:.2} GiB ({}%)", .{
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, ascii.Reset }) }; return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} Disabled", .{ key_color, key, display.Reset }) };
} }
} }
pub fn getDefaultFormattedDiskInfo(allocator: std.mem.Allocator) !Result { pub fn getDefaultFormattedDiskInfo(fmt_ctx: FormatterContext) !Result {
return try getFormattedDiskInfo(allocator, "Disk", ascii.Yellow); return try getFormattedDiskInfo(fmt_ctx, "Disk", display.Yellow);
} }
pub fn getFormattedDiskInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedDiskInfo(fmt_ctx: FormatterContext, 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 ({}%)", .{ 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,
display.Reset,
disk_info.disk_usage,
disk_info.disk_size,
disk_info.disk_usage_percentage,
}) };
} }
pub fn getDefaultFormattedTerminalNameInfo(allocator: std.mem.Allocator) !Result { pub fn getDefaultFormattedWindowManagerInfo(fmt_ctx: FormatterContext) !Result {
return try getFormattedTerminalNameInfo(allocator, "Terminal", ascii.Yellow); return try getFormattedWindowManagerInfo(fmt_ctx, "WM", display.Yellow);
} }
pub fn getFormattedTerminalNameInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedWindowManagerInfo(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result {
const terminal_name = try detection.user.getTerminalName(allocator); const allocator = fmt_ctx.gpa;
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);
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s}", .{ key_color, key, display.Reset, wm }) };
}
pub fn getDefaultFormattedTerminalNameInfo(fmt_ctx: FormatterContext) !Result {
return try getFormattedTerminalNameInfo(fmt_ctx, "Terminal", display.Yellow);
}
pub fn getFormattedTerminalNameInfo(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result {
const allocator = fmt_ctx.gpa;
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, ascii.Reset, terminal_name }) }; return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s}", .{ key_color, key, display.Reset, terminal_name }) };
} }
pub fn getDefaultFormattedNetInfo(allocator: std.mem.Allocator) !Result { pub fn getDefaultFormattedNetInfo(fmt_ctx: FormatterContext) !Result {
return try getFormattedNetInfo(allocator, "Local IP", ascii.Yellow); return try getFormattedNetInfo(fmt_ctx, "Local IP", display.Yellow);
} }
pub fn getFormattedNetInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedNetInfo(fmt_ctx: FormatterContext, 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}", .{ key_color, key, n.interface_name, ascii.Reset, n.ipv4_addr })); try formatted_net_info_list.append(try std.fmt.allocPrint(allocator, "{s}{s} ({s}):{s} {s}", .{
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);
} }
@@ -209,6 +357,8 @@ pub fn getFormattedNetInfo(allocator: std.mem.Allocator, key: []const u8, key_co
return Result{ .string_arraylist = formatted_net_info_list }; return Result{ .string_arraylist = formatted_net_info_list };
} }
pub fn getFormattedCustom(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result { pub fn getFormattedCustom(fmt_ctx: FormatterContext, key: []const u8, key_color: []const u8) !Result {
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}{s}", .{ key_color, key, ascii.Reset }) }; const allocator = fmt_ctx.gpa;
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}{s}", .{ key_color, key, display.Reset }) };
} }

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"));
@@ -39,15 +40,22 @@ pub const DiskInfo = struct {
disk_usage_percentage: u8, disk_usage_percentage: u8,
}; };
pub fn getCpuInfo(allocator: std.mem.Allocator) !CpuInfo { pub fn getCpuInfo(gpa: std.mem.Allocator, io: std.Io) !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";
var file = try std.fs.cwd().openFile(cpuinfo_path, .{}); const cpuinfo_file = try std.Io.Dir.cwd().openFile(io, cpuinfo_path, .{ .mode = .read_only });
defer file.close(); defer cpuinfo_file.close(io);
const cpuinfo_data = try file.readToEndAlloc(allocator, std.math.maxInt(usize));
defer allocator.free(cpuinfo_data); // 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(gpa, io, cpuinfo_file, 512);
defer gpa.free(cpuinfo_data);
// Parsing /proc/cpuinfo // Parsing /proc/cpuinfo
var model_name: ?[]const u8 = null; var model_name: ?[]const u8 = null;
@@ -77,26 +85,26 @@ 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;
// 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.fs.accessAbsolute(cpuinfo_max_freq_path, .{ .mode = .read_only }) catch |err| { _ = std.Io.Dir.accessAbsolute(io, cpuinfo_max_freq_path, .{ .read = true }) catch |err| {
if (err == std.posix.AccessError.FileNotFound) { if (err == std.Io.Dir.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
var file2 = try std.fs.cwd().openFile(cpuinfo_max_freq_path, .{}); const maxfreq_file = try std.Io.Dir.cwd().openFile(io, cpuinfo_max_freq_path, .{ .mode = .read_only });
defer maxfreq_file.close(io);
defer file2.close(); const maxfreq_data = try utils.readFile(gpa, io, maxfreq_file, 32);
const cpuinfo_max_freq_data = try file2.readToEndAlloc(allocator, std.math.maxInt(usize)); defer gpa.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 {
@@ -107,14 +115,14 @@ pub fn getCpuInfo(allocator: std.mem.Allocator) !CpuInfo {
} }
return CpuInfo{ return CpuInfo{
.cpu_name = try allocator.dupe(u8, model_name orelse "Unknown"), .cpu_name = try gpa.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(allocator: std.mem.Allocator) !std.array_list.Managed(GpuInfo) { pub fn getGpuInfo(gpa: std.mem.Allocator) !std.array_list.Managed(GpuInfo) {
var gpu_info_list = std.array_list.Managed(GpuInfo).init(allocator); var gpu_info_list = std.array_list.Managed(GpuInfo).init(gpa);
const display_controller = 0x03; const display_controller = 0x03;
@@ -143,13 +151,13 @@ pub fn getGpuInfo(allocator: std.mem.Allocator) !std.array_list.Managed(GpuInfo)
devices.*.device_id, devices.*.device_id,
); );
const gpu_name = try allocator.dupe(u8, std.mem.span(name)); const gpu_name = try gpa.dupe(u8, std.mem.span(name));
const maybe_parsed_gpu_name = try parseGpuName(allocator, gpu_name); const maybe_parsed_gpu_name = try parseGpuName(gpa, 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) {
allocator.free(gpu_name); gpa.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;
@@ -165,7 +173,7 @@ pub fn getGpuInfo(allocator: 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 allocator.dupe(u8, "Unknown"), .gpu_name = try gpa.dupe(u8, "Unknown"),
.gpu_cores = 0, .gpu_cores = 0,
.gpu_freq = 0.0, .gpu_freq = 0.0,
}); });
@@ -174,24 +182,24 @@ pub fn getGpuInfo(allocator: std.mem.Allocator) !std.array_list.Managed(GpuInfo)
return gpu_info_list; return gpu_info_list;
} }
fn parseGpuName(allocator: std.mem.Allocator, name: []u8) !?[]u8 { fn parseGpuName(gpa: 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 allocator.alloc(u8, size); const parsed_gpu_name = try gpa.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 allocator.alloc(u8, size); const parsed_gpu_name = try gpa.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 allocator.alloc(u8, size); const parsed_gpu_name = try gpa.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;
@@ -200,13 +208,20 @@ fn parseGpuName(allocator: std.mem.Allocator, name: []u8) !?[]u8 {
return null; return null;
} }
pub fn getRamInfo(allocator: std.mem.Allocator) !RamInfo { pub fn getRamInfo(gpa: std.mem.Allocator, io: std.Io) !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.Io.Dir.cwd().openFile(io, meminfo_path, .{ .mode = .read_only });
defer file.close(); defer meminfo_file.close(io);
const meminfo_data = try file.readToEndAlloc(allocator, std.math.maxInt(usize));
defer allocator.free(meminfo_data); // 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(gpa, io, meminfo_file, 512);
defer gpa.free(meminfo_data);
// Parsing /proc/meminfo // Parsing /proc/meminfo
var total_mem: f64 = 0.0; var total_mem: f64 = 0.0;
@@ -262,13 +277,20 @@ pub fn getRamInfo(allocator: std.mem.Allocator) !RamInfo {
}; };
} }
pub fn getSwapInfo(allocator: std.mem.Allocator) !?SwapInfo { pub fn getSwapInfo(gpa: std.mem.Allocator, io: std.Io) !?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.Io.Dir.cwd().openFile(io, meminfo_path, .{ .mode = .read_only });
defer file.close(); defer meminfo_file.close(io);
const meminfo_data = try file.readToEndAlloc(allocator, std.math.maxInt(usize));
defer allocator.free(meminfo_data); // 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(gpa, io, meminfo_file, 512);
defer gpa.free(meminfo_data);
// Parsing /proc/meminfo // Parsing /proc/meminfo
var total_swap: f64 = 0.0; var total_swap: f64 = 0.0;

View File

@@ -2,3 +2,4 @@ pub const hardware = @import("./hardware.zig");
pub const network = @import("./network.zig"); pub const network = @import("./network.zig");
pub const system = @import("./system.zig"); pub const system = @import("./system.zig");
pub const user = @import("./user.zig"); pub const user = @import("./user.zig");
pub const packages = @import("./packages.zig");

View File

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

254
src/linux/packages.zig Normal file
View File

@@ -0,0 +1,254 @@
const std = @import("std");
const utils = @import("../utils.zig");
pub fn getPackagesInfo(gpa: std.mem.Allocator, io: std.Io, environ: std.process.Environ) ![]const u8 {
var packages_info = std.array_list.Managed(u8).init(gpa);
defer packages_info.deinit();
const flatpak_packages = countFlatpakPackages(io) catch |err| if (err == error.FileNotFound) 0 else return err;
const nix_packages = countNixPackages(gpa, io, environ) catch 0;
const dpkg_packages = countDpkgPackages(gpa, io) 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 xbps_packages = countXbpsPackages(gpa, io) catch |err| if (err == error.FileNotFound) 0 else return err;
var buffer: [32]u8 = undefined;
if (nix_packages > 0) {
try packages_info.appendSlice(try std.fmt.bufPrint(&buffer, " Nix: {d}", .{nix_packages}));
}
if (flatpak_packages > 0) {
try packages_info.appendSlice(try std.fmt.bufPrint(&buffer, " Flatpak: {d}", .{flatpak_packages}));
}
if (dpkg_packages > 0) {
try packages_info.appendSlice(try std.fmt.bufPrint(&buffer, " Dpkg: {d}", .{dpkg_packages}));
}
if (pacman_packages > 0) {
try packages_info.appendSlice(try std.fmt.bufPrint(&buffer, " Pacman: {d}", .{pacman_packages}));
}
if (xbps_packages > 0) {
try packages_info.appendSlice(try std.fmt.bufPrint(&buffer, " Xbps: {d}", .{xbps_packages}));
}
return try gpa.dupe(u8, packages_info.items);
}
fn countFlatpakPackages(io: std.Io) !usize {
const flatpak_apps = try countFlatpakApps(io);
const flatpak_runtimes = try countFlatpakRuntimes(io);
return flatpak_apps + flatpak_runtimes;
}
fn countFlatpakApps(io: std.Io) !usize {
var dir = try std.Io.Dir.openDirAbsolute(io, "/var/lib/flatpak/app/", .{ .iterate = true });
defer dir.close(io);
var iter = dir.iterate();
var count: usize = 0;
while (try iter.next(io)) |e| {
if (e.kind != .directory) continue;
var sub_dir = try dir.openDir(io, e.name, .{});
defer sub_dir.close(io);
var current = sub_dir.openDir(io, "current", .{}) catch continue;
defer current.close(io);
// If `current` was opened successfully, increment the count
count += 1;
}
return count;
}
fn countFlatpakRuntimes(io: std.Io) !usize {
var dir = try std.Io.Dir.openDirAbsolute(io, "/var/lib/flatpak/runtime/", .{ .iterate = true });
defer dir.close(io);
var iter = dir.iterate();
var counter: usize = 0;
while (try iter.next(io)) |e| {
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 });
defer arch_dir.close(io);
var arch_iter = arch_dir.iterate();
while (try arch_iter.next(io)) |arch_e| {
if (arch_e.kind != .directory) continue;
var sub_dir = try arch_dir.openDir(io, arch_e.name, .{ .iterate = true });
defer sub_dir.close(io);
var sub_iter = sub_dir.iterate();
while (try sub_iter.next(io)) |_| {
counter += 1;
}
}
}
return counter;
}
fn countNixPackages(gpa: std.mem.Allocator, io: std.Io, environ: std.process.Environ) !usize {
// `/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);
defer gpa.free(real_path);
var hash: [32]u8 = undefined;
std.crypto.hash.Blake3.hash(real_path, &hash, .{});
const hash_hex = try std.fmt.allocPrint(gpa, "{x}", .{hash});
defer gpa.free(hash_hex);
var count: usize = 0;
// 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) {
error.FileNotFound, error.InvalidCache => {
// nix-store --query --requisites /run/current-system | wc -l
const result = try std.process.run(gpa, io, .{ .argv = &[_][]const u8{
"sh",
"-c",
"nix-store --query --requisites /run/current-system | wc -l",
} });
const result_trimmed = std.mem.trim(u8, result.stdout, "\n");
defer gpa.free(result.stdout);
defer gpa.free(result.stderr);
count = try std.fmt.parseInt(usize, result_trimmed, 10);
try writeNixCache(gpa, io, environ, hash_hex, count);
return count;
},
else => return err,
};
return count;
}
fn getNixCachePath(gpa: std.mem.Allocator, environ: std.process.Environ) ![]const u8 {
const cache_dir_path = try getUnixCachePath(gpa, environ);
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) {
gpa.free(cache_dir_path);
const home = try std.process.Environ.getAlloc(environ, gpa, "HOME");
defer gpa.free(home);
cache_dir_path = try std.fs.path.join(gpa, &.{ home, ".cache" });
}
return cache_dir_path;
}
fn writeNixCache(gpa: std.mem.Allocator, io: std.Io, environ: std.process.Environ, hash: []const u8, count: usize) !void {
const nix_cache_dir_path = try getNixCachePath(gpa, environ);
defer gpa.free(nix_cache_dir_path);
std.Io.Dir.accessAbsolute(io, nix_cache_dir_path, .{ .read = true }) catch {
const cache_dir_path = try getUnixCachePath(gpa, environ);
defer gpa.free(cache_dir_path);
const cache_dir = try std.Io.Dir.openDirAbsolute(io, cache_dir_path, .{});
try cache_dir.createDirPath(io, "zigfetch/nix");
};
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 {
const cache_dir_path = try getNixCachePath(gpa, environ);
defer gpa.free(cache_dir_path);
var cache_dir = try std.Io.Dir.openDirAbsolute(io, cache_dir_path, .{});
defer cache_dir.close(io);
var cache_file = try cache_dir.openFile(io, "nix_cache", .{ .mode = .read_only });
defer cache_file.close(io);
const cache_size = (try cache_file.stat(io)).size;
const cache_content = try utils.readFile(gpa, io, cache_file, cache_size);
defer gpa.free(cache_content);
var cache_iter = std.mem.splitScalar(u8, cache_content, '\n');
const hash_needle = cache_iter.next().?;
if (!std.mem.eql(u8, hash, hash_needle)) {
return error.InvalidCache;
}
// The next element in the split is the package count
return std.fmt.parseInt(usize, cache_iter.next().?, 10);
}
fn countDpkgPackages(gpa: std.mem.Allocator, io: std.Io) !usize {
const dpkg_status_path = "/var/lib/dpkg/status";
const dpkg_file = try std.Io.Dir.openFileAbsolute(io, dpkg_status_path, .{ .mode = .read_only });
defer dpkg_file.close(io);
const file_size = (try dpkg_file.stat(io)).size;
const content = try utils.readFile(gpa, io, dpkg_file, file_size);
defer gpa.free(content);
var count: usize = 0;
var iter = std.mem.splitSequence(u8, content, "\n\n");
// TODO: find a way to avoid this loop
while (iter.next()) |_| {
count += 1;
}
// Subtruct 1 to remove an useless line
return count - 1;
}
fn countPacmanPackages(io: std.Io) !usize {
// Subtruct 1 to remove `ALPM_DB_VERSION` from the count
return try utils.countEntries(io, "/var/lib/pacman/local") - 1;
}
fn countXbpsPackages(gpa: std.mem.Allocator, io: std.Io) !usize {
var dir = try std.Io.Dir.openDirAbsolute(io, "/var/db/xbps/", .{ .iterate = true });
defer dir.close(io);
var count: usize = 0;
var dir_iter = dir.iterate();
while (try dir_iter.next(io)) |e| {
if ((e.kind == .file) and std.mem.startsWith(u8, e.name, "pkgdb-")) {
const pkgdb_file = try dir.openFile(io, e.name, .{ .mode = .read_only });
defer pkgdb_file.close(io);
const file_size = (try pkgdb_file.stat(io)).size;
const content = try utils.readFile(gpa, io, pkgdb_file, file_size);
defer gpa.free(content);
var file_iter = std.mem.splitSequence(u8, content, "<string>installed</string>");
// TODO: find a way to avoid this loop
while (file_iter.next()) |_| {
count += 1;
}
break;
}
}
// Subtruct 1 to remove an useless line
return count - 1;
}

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"));
@@ -15,18 +16,18 @@ pub const KernelInfo = struct {
kernel_release: []u8, kernel_release: []u8,
}; };
pub fn getHostname(allocator: std.mem.Allocator) ![]u8 { pub fn getHostname(gpa: 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 allocator.dupe(u8, hostnameEnv); const hostname = try gpa.dupe(u8, hostnameEnv);
return hostname; return hostname;
} }
pub fn getLocale(allocator: std.mem.Allocator) ![]u8 { pub fn getLocale(gpa: std.mem.Allocator, environ: std.process.Environ) ![]u8 {
const locale = std.process.getEnvVarOwned(allocator, "LANG") catch |err| if (err == error.EnvironmentVariableNotFound) { const locale = std.process.Environ.getAlloc(environ, gpa, "LANG") catch |err| if (err == error.EnvironmentVariableNotFound) {
return allocator.dupe(u8, "Unknown"); return gpa.dupe(u8, "Unknown");
} else return err; } else return err;
return locale; return locale;
} }
@@ -63,24 +64,25 @@ pub fn getSystemUptime() !SystemUptime {
}; };
} }
pub fn getKernelInfo(allocator: std.mem.Allocator) !KernelInfo { pub fn getKernelInfo(gpa: 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 allocator.dupe(u8, std.mem.sliceTo(&uts.sysname, 0)), .kernel_name = try gpa.dupe(u8, std.mem.sliceTo(&uts.sysname, 0)),
.kernel_release = try allocator.dupe(u8, std.mem.sliceTo(&uts.release, 0)), .kernel_release = try gpa.dupe(u8, std.mem.sliceTo(&uts.release, 0)),
}; };
} }
pub fn getOsInfo(allocator: std.mem.Allocator) ![]u8 { pub fn getOsInfo(gpa: std.mem.Allocator, io: std.Io) ![]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.Io.Dir.cwd().openFile(io, os_release_path, .{ .mode = .read_only });
defer file.close(); defer os_release_file.close(io);
const os_release_data = try file.readToEndAlloc(allocator, std.math.maxInt(usize)); const size = (try os_release_file.stat(io)).size;
defer allocator.free(os_release_data); const os_release_data = try utils.readFile(gpa, io, os_release_file, size);
defer gpa.free(os_release_data);
var pretty_name: ?[]const u8 = null; var pretty_name: ?[]const u8 = null;
@@ -96,5 +98,58 @@ pub fn getOsInfo(allocator: std.mem.Allocator) ![]u8 {
} }
} }
return try allocator.dupe(u8, pretty_name orelse "Unknown"); return try gpa.dupe(u8, pretty_name orelse "Unknown");
}
pub fn getWindowManagerInfo(gpa: std.mem.Allocator, io: std.Io) ![]const u8 {
var dir = try std.Io.Dir.cwd().openDir(io, "/proc/", .{ .iterate = true });
defer dir.close(io);
var wm_name: ?[]const u8 = null;
var iter = dir.iterate();
wm_name = outer: {
while (try iter.next(io)) |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.Io.Dir.cwd().openFile(io, file_name, .{ .mode = .read_only });
defer file.close(io);
// 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);
defer gpa.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 gpa.dupe(u8, proc_name_trimmed);
}
}
}
break :outer null;
};
return wm_name orelse gpa.dupe(u8, "Unknown");
} }

View File

@@ -1,24 +1,23 @@
const std = @import("std"); const std = @import("std");
pub fn getUsername(allocator: std.mem.Allocator) ![]u8 { pub fn getUsername(gpa: std.mem.Allocator, environ: std.process.Environ) ![]u8 {
const username = try std.process.getEnvVarOwned(allocator, "USER"); return try std.process.Environ.getAlloc(environ, gpa, "USER");
return username;
} }
pub fn getShell(allocator: std.mem.Allocator) ![]u8 { pub fn getShell(gpa: std.mem.Allocator, io: std.Io, environ: std.process.Environ) ![]u8 {
const shell = std.process.getEnvVarOwned(allocator, "SHELL") catch |err| if (err == error.EnvironmentVariableNotFound) { const shell = std.process.Environ.getAlloc(environ, gpa, "SHELL") catch |err| if (err == error.EnvironmentVariableNotFound) {
return allocator.dupe(u8, "Unknown"); return gpa.dupe(u8, "Unknown");
} else return err; } else return err;
defer allocator.free(shell); defer gpa.free(shell);
const result = try std.process.Child.run(.{ .allocator = allocator, .argv = &[_][]const u8{ shell, "--version" } }); const result = try std.process.run(gpa, io, .{ .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 allocator.free(result_stdout); defer gpa.free(result_stdout);
return try std.fmt.allocPrint(allocator, "{s} {s}", .{ "bash", bash_version.? }); return try std.fmt.allocPrint(gpa, "{s} {s}", .{ "bash", bash_version.? });
} }
return result_stdout; return result_stdout;
@@ -32,12 +31,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.?]; return shell_version_output[version_keyword_index.? + version_keyword.len .. end_index.? + 1];
} }
pub fn getTerminalName(allocator: std.mem.Allocator) ![]u8 { pub fn getTerminalName(gpa: std.mem.Allocator, environ: std.process.Environ) ![]u8 {
const term_program = std.process.getEnvVarOwned(allocator, "TERM_PROGRAM") catch |err| if (err == error.EnvironmentVariableNotFound) { const term_program = std.process.Environ.getAlloc(environ, gpa, "TERM_PROGRAM") catch |err| if (err == error.EnvironmentVariableNotFound) {
return allocator.dupe(u8, "Unknown"); return gpa.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(allocator: std.mem.Allocator) !CpuInfo { pub fn getCpuInfo(gpa: 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(allocator: std.mem.Allocator) !CpuInfo {
return error.FailedToGetCpuNameSize; return error.FailedToGetCpuNameSize;
} }
const cpu_name: []u8 = try allocator.alloc(u8, size - 1); const cpu_name: []u8 = try gpa.alloc(u8, size - 1);
errdefer allocator.free(cpu_name); errdefer gpa.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(allocator: std.mem.Allocator) !CpuInfo {
} }
// Get cpu architecture // Get cpu architecture
const arch: []u8 = try getCpuArch(allocator); const arch: []u8 = try getCpuArch(gpa);
defer allocator.free(arch); defer gpa.free(arch);
var cpu_freq_mhz: f64 = 0.0; var cpu_freq_mhz: f64 = 0.0;
@@ -82,22 +82,22 @@ pub fn getCpuInfo(allocator: 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(allocator: std.mem.Allocator) ![]u8 { fn getCpuArch(gpa: 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 allocator.alloc(u8, size); const machine: []u8 = try gpa.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 allocator.free(machine); defer gpa.free(machine);
return allocator.dupe(u8, std.mem.sliceTo(machine, 0)); return gpa.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(allocator: std.mem.Allocator) !GpuInfo { pub fn getGpuInfo(gpa: 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 allocator.dupe(u8, "Unknown"), .gpu_name = try gpa.dupe(u8, "Unknown"),
.gpu_cores = 0, .gpu_cores = 0,
.gpu_freq = 0.0, .gpu_freq = 0.0,
}; };
@@ -236,11 +236,11 @@ 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.cfTypeRefToZigString(allocator, name_ref) catch { const accel_name = utils.cfTypeRefToZigString(gpa, name_ref) catch {
return gpu_info; return gpu_info;
}; };
allocator.free(gpu_info.gpu_name); gpa.free(gpu_info.gpu_name);
gpu_info.gpu_name = accel_name; gpu_info.gpu_name = accel_name;
} }
} }
@@ -262,8 +262,8 @@ pub fn getGpuInfo(allocator: std.mem.Allocator) !GpuInfo {
} }
// Get cpu architecture // Get cpu architecture
const arch: []u8 = try getCpuArch(allocator); const arch: []u8 = try getCpuArch(gpa);
defer allocator.free(arch); defer gpa.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(allocator: std.mem.Allocator) !std.array_list.Managed(NetInfo) { pub fn getNetInfo(gpa: std.mem.Allocator) !std.array_list.Managed(NetInfo) {
var net_info_list = std.array_list.Managed(NetInfo).init(allocator); var net_info_list = std.array_list.Managed(NetInfo).init(gpa);
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(allocator: 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 allocator.dupe(u8, std.mem.span(ifa.ifa_name)), .interface_name = try gpa.dupe(u8, std.mem.span(ifa.ifa_name)),
.ipv4_addr = try allocator.dupe(u8, std.mem.span(ip)), .ipv4_addr = try gpa.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(allocator: std.mem.Allocator) ![]const u8 { pub fn getPackagesInfo(gpa: std.mem.Allocator, io: std.Io) ![]const u8 {
var packages_info = std.array_list.Managed(u8).init(allocator); var packages_info = std.array_list.Managed(u8).init(gpa);
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(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 homebrew_casks = countHomebrewCasks(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; const macports_packages = countMacportPackages(io) 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(allocator: std.mem.Allocator) ![]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 allocator.dupe(u8, packages_info.items); return try gpa.dupe(u8, packages_info.items);
} }
fn countHomebrewPackages() !usize { fn countHomebrewPackages(io: std.Io) !usize {
return try utils.countEntries("/opt/homebrew/Cellar"); return try utils.countEntries(io, "/opt/homebrew/Cellar");
} }
fn countHomebrewCasks() !usize { fn countHomebrewCasks(io: std.Io) !usize {
return try utils.countEntries("/opt/homebrew/Caskroom"); return try utils.countEntries(io, "/opt/homebrew/Caskroom");
} }
fn countMacportPackages() !usize { fn countMacportPackages(io: std.Io) !usize {
return try utils.countEntries("/opt/local/bin"); return try utils.countEntries(io, "/opt/local/bin");
} }

View File

@@ -16,18 +16,18 @@ pub const KernelInfo = struct {
}; };
/// Returns the hostname. /// Returns the hostname.
pub fn getHostname(allocator: std.mem.Allocator) ![]u8 { pub fn getHostname(gpa: 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 allocator.dupe(u8, hostnameEnv); const hostname = try gpa.dupe(u8, hostnameEnv);
return hostname; return hostname;
} }
pub fn getLocale(allocator: std.mem.Allocator) ![]u8 { pub fn getLocale(gpa: std.mem.Allocator, environ: std.process.Environ) ![]u8 {
const locale = std.process.getEnvVarOwned(allocator, "LANG") catch |err| if (err == error.EnvironmentVariableNotFound) { const locale = std.process.Environ.getAlloc(environ, gpa, "LANG") catch |err| if (err == error.EnvironmentVariableNotFound) {
return allocator.dupe(u8, "Unknown"); return gpa.dupe(u8, "Unknown");
} else return err; } else return err;
return locale; return locale;
} }
@@ -35,7 +35,7 @@ pub fn getLocale(allocator: std.mem.Allocator) ![]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() !SystemUptime { pub fn getSystemUptime(io: std.Io) !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() !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.time.timestamp())); const now_seconds = @as(f64, @floatFromInt(std.Io.Timestamp.now(io, .real).toSeconds()));
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() !SystemUptime {
}; };
} }
pub fn getKernelInfo(allocator: std.mem.Allocator) !KernelInfo { pub fn getKernelInfo(gpa: std.mem.Allocator) !KernelInfo {
var size: usize = 0; var size: usize = 0;
// --- KERNEL NAME --- // --- KERNEL NAME ---
@@ -80,8 +80,8 @@ pub fn getKernelInfo(allocator: std.mem.Allocator) !KernelInfo {
return error.FailedToGetKernelNameSize; return error.FailedToGetKernelNameSize;
} }
const kernel_type: []u8 = try allocator.alloc(u8, size - 1); const kernel_type: []u8 = try gpa.alloc(u8, size - 1);
errdefer allocator.free(kernel_type); errdefer gpa.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(allocator: std.mem.Allocator) !KernelInfo {
return error.FailedToGetKernelReleaseSize; return error.FailedToGetKernelReleaseSize;
} }
const os_release: []u8 = try allocator.alloc(u8, size - 1); const os_release: []u8 = try gpa.alloc(u8, size - 1);
errdefer allocator.free(os_release); errdefer gpa.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(allocator: std.mem.Allocator) !KernelInfo {
}; };
} }
pub fn getOsInfo(allocator: std.mem.Allocator) ![]u8 { pub fn getOsInfo(gpa: 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,15 +116,80 @@ pub fn getOsInfo(allocator: std.mem.Allocator) ![]u8 {
return error.FailedToGetCpuNameSize; return error.FailedToGetCpuNameSize;
} }
const os_version: []u8 = try allocator.alloc(u8, size - 1); const os_version: []u8 = try gpa.alloc(u8, size - 1);
defer allocator.free(os_version); defer gpa.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(allocator, "macOS {s}", .{os_version}); const os_info = try std.fmt.allocPrint(gpa, "macOS {s}", .{os_version});
return os_info; return os_info;
} }
pub fn getWindowManagerInfo(gpa: 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 gpa.alloc(u8, size);
defer gpa.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 gpa.dupe(u8, pathbuf[0..@intCast(path_len)]) else try gpa.dupe(u8, "unknown");
defer gpa.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 gpa.dupe(u8, basename);
}
}
}
break :outer null;
};
return wm_name orelse gpa.dupe(u8, "Quartz Compositor");
}

View File

@@ -3,25 +3,24 @@ 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(allocator: std.mem.Allocator) ![]u8 { pub fn getUsername(gpa: std.mem.Allocator, environ: std.process.Environ) ![]u8 {
const username = try std.process.getEnvVarOwned(allocator, "USER"); return try std.process.Environ.getAlloc(environ, gpa, "USER");
return username;
} }
pub fn getShell(allocator: std.mem.Allocator) ![]u8 { pub fn getShell(gpa: std.mem.Allocator, io: std.Io, environ: std.process.Environ) ![]u8 {
const shell = std.process.getEnvVarOwned(allocator, "SHELL") catch |err| if (err == error.EnvironmentVariableNotFound) { const shell = std.process.Environ.getAlloc(environ, gpa, "SHELL") catch |err| if (err == error.EnvironmentVariableNotFound) {
return allocator.dupe(u8, "Unknown"); return gpa.dupe(u8, "Unknown");
} else return err; } else return err;
defer allocator.free(shell); defer gpa.free(shell);
const result = try std.process.Child.run(.{ .allocator = allocator, .argv = &[_][]const u8{ shell, "--version" } }); const result = try std.process.run(gpa, io, .{ .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 allocator.free(result_stdout); defer gpa.free(result_stdout);
return try std.fmt.allocPrint(allocator, "{s} {s}", .{ "bash", bash_version.? }); return try std.fmt.allocPrint(gpa, "{s} {s}", .{ "bash", bash_version.? });
} }
return result_stdout; return result_stdout;
@@ -38,9 +37,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(allocator: std.mem.Allocator) ![]u8 { pub fn getTerminalName(gpa: std.mem.Allocator, environ: std.process.Environ) ![]u8 {
const term_program = std.process.getEnvVarOwned(allocator, "TERM_PROGRAM") catch |err| if (err == error.EnvironmentVariableNotFound) { const term_program = std.process.Environ.getAlloc(environ, gpa, "TERM_PROGRAM") catch |err| if (err == error.EnvironmentVariableNotFound) {
return allocator.dupe(u8, "Unknown"); return gpa.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(allocator: std.mem.Allocator, cf_type_ref: c_iokit.CFTypeRef) ![]u8 { pub fn cfTypeRefToZigString(gpa: 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 allocator.alloc(u8, max_size_usize); const buffer = try gpa.alloc(u8, max_size_usize);
errdefer allocator.free(buffer); errdefer gpa.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,19 +21,5 @@ pub fn cfTypeRefToZigString(allocator: std.mem.Allocator, cf_type_ref: c_iokit.C
actual_len += 1; actual_len += 1;
} }
return allocator.realloc(buffer, actual_len); return gpa.realloc(buffer, actual_len);
}
pub fn countEntries(dir_path: []const u8) !usize {
var dir = try std.fs.openDirAbsolute(dir_path, .{ .iterate = true });
defer dir.close();
var count: usize = 0;
var iter = dir.iterate();
while (try iter.next()) |_| {
count += 1;
}
return count;
} }

View File

@@ -1,11 +1,12 @@
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 ascii = @import("ascii.zig"); const display = @import("display.zig");
const config = @import("config.zig"); const config = @import("config.zig");
const formatters = @import("formatters.zig"); const formatters = @import("formatters.zig");
pub fn main() !void { pub fn main(init: std.process.Init) !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();
@@ -19,22 +20,23 @@ pub fn main() !void {
} }
} }
const conf = try config.readConfigFile(allocator); const conf = try config.readConfigFile(allocator, io, init.minimal.environ);
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); const username = try detection.user.getUsername(allocator, init.minimal.environ);
const hostname = try detection.system.getHostname(allocator); const hostname = try detection.system.getHostname(allocator);
try modules_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 display.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 display.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);
@@ -42,9 +44,15 @@ pub fn main() !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](allocator); const result = try formatters.default_formatters[i](fmt_ctx);
switch (result) { switch (result) {
.string => |r| try modules_list.append(r), .string => |r| try modules_list.append(r),
.string_arraylist => |r| { .string_arraylist => |r| {
@@ -56,10 +64,10 @@ pub fn main() !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 ascii.hexColorToRgb(module.key_color); const rgb = try display.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)](allocator, module.key, key_color); const result = try formatters.formatters[@intFromEnum(module_type)](fmt_ctx, 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| {
@@ -70,5 +78,6 @@ pub fn main() !void {
} }
} }
try ascii.printAsciiAndModules(allocator, config.getAsciiPath(conf), modules_list); // TODO: return the formatted ascii and modules to print instead of directly print them
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.fs.File.stdout(); const stdout = std.Io.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 });
@@ -114,3 +114,28 @@ 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 {
var file_buf = try gpa.alloc(u8, size);
defer gpa.free(file_buf);
const read = try file.readPositionalAll(io, file_buf, 0);
const data = file_buf[0..read];
return gpa.dupe(u8, data);
}
pub fn countEntries(io: std.Io, dir_path: []const u8) !usize {
var dir = try std.Io.Dir.openDirAbsolute(io, dir_path, .{ .iterate = true });
defer dir.close(io);
var count: usize = 0;
var iter = dir.iterate();
while (try iter.next(io)) |_| {
count += 1;
}
return count;
}