92 Commits

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

View File

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

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

3
.gitignore vendored
View File

@@ -1 +1,2 @@
*zig-*
*zig-*
result

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)
![GitHub Release](https://img.shields.io/github/v/release/utox39/zigfetch)
![GitHub License](https://img.shields.io/github/license/utox39/zigfetch)
![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/utox39/zigfetch/build.yml)
![macOS](https://img.shields.io/badge/mac%20os-000000?style=flat&logo=macos&logoColor=F0F0F0)
![Linux](https://img.shields.io/badge/Linux-FCC624?style=flat&logo=linux&logoColor=black)
| Default config | Custom config |
| :-----------------------------------------------------: | :---------------------------------------------------: |
| ![dafault-config](assets/screenshot-default-config.png) | ![custom-config](assets/screenshot-custom-config.png) |
---
- [Description](#description)
- [Requirements](#requirements)
- [Installation](#installation)
- [Usage](#usage)
- [Configuration](#configuration)
- [Roadtrip](#roadtrip)
- [Contributing](#contributing)
- [Description](#description)
- [Requirements](#requirements)
- [Installation](#installation)
- [Usage](#usage)
- [Configuration](#configuration)
- [Roadtrip](#roadtrip)
- [Contributing](#contributing)
## Description
@@ -21,15 +27,17 @@ Zigfetch is a minimal [neofetch](https://github.com/dylanaraps/neofetch)/[fastfe
## Requirements
- \>= [zig v0.15.1](https://ziglang.org/)
- \>= [zig v0.15.2](https://ziglang.org/)
### Linux only
- [libpci](https://github.com/pciutils/pciutils)
- [libpci](https://github.com/pciutils/pciutils)
## Installation
```console
### Build from source
```bash
# Clone the repo
$ git clone https://github.com/utox39/zigfetch.git
@@ -43,10 +51,22 @@ $ zig build -Doptimize=ReleaseSafe
$ 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
```console
$ zigfetch
```bash
zigfetch
```
### Configuration
@@ -54,33 +74,114 @@ $ zigfetch
> [!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
- Create the config folder
- Create the config folder
```console
$ mkdir -p ~/.config/zigfetch
```bash
mkdir -p ~/.config/zigfetch
```
- Create the config file
- Create the config file
```console
$ cd ~/.config/zigfetch
$ touch config.json
```bash
cd ~/.config/zigfetch
touch config.json
```
- Or copy the default config (preferred way)
- Or copy the default config (preferred way)
```console
$ cp /path/to/zigfetch/config.json ~/.config/zigfetch/config.json
```bash
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
- [ ] Add ASCII art for each operating system and Linux distro
- [x] Add GPU info for Linux
- [ ] Add packages info for Linux
- [x] Add user customization
- [ ] Add support for Windows
- [ ] Add ASCII art for each operating system and Linux distro
- [x] Add GPU info for Linux
- [x] Add packages info for Linux
- [x] Add user customization
- [ ] Add support for Windows
## 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

@@ -10,7 +10,7 @@
// This is a [Semantic Version](https://semver.org/).
// In a future version of Zig it will be used for package deduplication.
.version = "0.21.0",
.version = "0.25.0",
// Together with name, this represents a globally unique package
// identifier. This field is generated by the Zig toolchain when the
@@ -28,7 +28,7 @@
// Tracks the earliest Zig version that the package considers to be a
// supported use case.
.minimum_zig_version = "0.15.1",
.minimum_zig_version = "0.15.2",
// This field is optional.
// 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

@@ -72,9 +72,10 @@ pub fn printAsciiAndModules(allocator: std.mem.Allocator, ascii_art_path: ?[]u8,
var ascii_art_data: []const u8 = undefined;
if (ascii_art_path) |ascii| {
var ascii_file = try std.fs.cwd().openFile(ascii, .{});
const ascii_file = try std.fs.cwd().openFile(ascii, .{ .mode = .read_only });
defer ascii_file.close();
ascii_art_data = try ascii_file.readToEndAlloc(allocator, std.math.maxInt(usize));
const file_size = (try ascii_file.stat()).size;
ascii_art_data = try utils.readFile(allocator, ascii_file, file_size);
} else {
ascii_art_data = @embedFile("./assets/ascii/guy_fawks.txt");
}
@@ -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 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 spacing: usize = 5;

View File

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

View File

@@ -20,6 +20,7 @@ pub const formatters = [_]*const fn (allocator: std.mem.Allocator, key: []const
&getFormattedSwapInfo,
&getFormattedDiskInfo,
&getFormattedNetInfo,
&getFormattedWindowManagerInfo,
&getFormattedTerminalNameInfo,
&getFormattedLocaleInfo,
&getFormattedCustom,
@@ -37,10 +38,22 @@ pub const default_formatters = [_]*const fn (allocator: std.mem.Allocator) anyer
&getDefaultFormattedSwapInfo,
&getDefaultFormattedDiskInfo,
&getDefaultFormattedNetInfo,
&getDefaultFormattedWindowManagerInfo,
&getDefaultFormattedTerminalNameInfo,
&getDefaultFormattedLocaleInfo,
};
pub fn getFormattedUsernameHostname(allocator: std.mem.Allocator, color: []const u8, username: []const u8, hostname: []const u8) ![]u8 {
return try std.fmt.allocPrint(allocator, "{s}{s}{s}@{s}{s}{s}", .{
color,
username,
ascii.Reset,
color,
hostname,
ascii.Reset,
});
}
pub fn getDefaultFormattedKernelInfo(allocator: std.mem.Allocator) !Result {
return try getFormattedKernelInfo(allocator, "Kernel", ascii.Yellow);
}
@@ -87,13 +100,9 @@ pub fn getDefaultFormattedPackagesInfo(allocator: std.mem.Allocator) !Result {
}
pub fn getFormattedPackagesInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
if (builtin.os.tag == .macos) {
const packages_info = try detection.packages.getPackagesInfo(allocator);
defer allocator.free(packages_info);
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) {
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} WIP", .{ key_color, key, ascii.Reset }) };
}
const packages_info = try detection.packages.getPackagesInfo(allocator);
defer allocator.free(packages_info);
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s}{s}", .{ key_color, key, ascii.Reset, packages_info }) };
}
pub fn getDefaultFormattedShellInfo(allocator: std.mem.Allocator) !Result {
@@ -181,6 +190,16 @@ pub fn getFormattedDiskInfo(allocator: std.mem.Allocator, key: []const u8, key_c
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s} ({s}):{s} {d:.2} / {d:.2} GB ({}%)", .{ key_color, key, disk_info.disk_path, ascii.Reset, disk_info.disk_usage, disk_info.disk_size, disk_info.disk_usage_percentage }) };
}
pub fn getDefaultFormattedWindowManagerInfo(allocator: std.mem.Allocator) !Result {
return try getFormattedWindowManagerInfo(allocator, "WM", ascii.Yellow);
}
pub fn getFormattedWindowManagerInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
const wm = try detection.system.getWindowManagerInfo(allocator);
defer allocator.free(wm);
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s}", .{ key_color, key, ascii.Reset, wm }) };
}
pub fn getDefaultFormattedTerminalNameInfo(allocator: std.mem.Allocator) !Result {
return try getFormattedTerminalNameInfo(allocator, "Terminal", ascii.Yellow);
}

View File

@@ -1,4 +1,5 @@
const std = @import("std");
const utils = @import("../utils.zig");
const c_unistd = @cImport(@cInclude("unistd.h"));
const c_statvfs = @cImport(@cInclude("sys/statvfs.h"));
const c_libpci = @cImport(@cInclude("pci/pci.h"));
@@ -44,9 +45,16 @@ pub fn getCpuInfo(allocator: std.mem.Allocator) !CpuInfo {
// Reads /proc/cpuinfo
const cpuinfo_path = "/proc/cpuinfo";
var file = try std.fs.cwd().openFile(cpuinfo_path, .{});
defer file.close();
const cpuinfo_data = try file.readToEndAlloc(allocator, std.math.maxInt(usize));
const cpuinfo_file = try std.fs.cwd().openFile(cpuinfo_path, .{ .mode = .read_only });
defer cpuinfo_file.close();
// NOTE: procfs is a pseudo-filesystem, so it is not possible to determine the size of a file
// https://docs.kernel.org/filesystems/proc.html
// https://en.wikipedia.org/wiki/Procfs
//
// Only the first section (core 0) will be parsed
// 512 is more than enough
const cpuinfo_data = try utils.readFile(allocator, cpuinfo_file, 512);
defer allocator.free(cpuinfo_data);
// Parsing /proc/cpuinfo
@@ -77,6 +85,7 @@ pub fn getCpuInfo(allocator: std.mem.Allocator) !CpuInfo {
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";
var cmf_exists: bool = true;
@@ -89,14 +98,13 @@ pub fn getCpuInfo(allocator: std.mem.Allocator) !CpuInfo {
if (cmf_exists) {
// Reads /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq
var file2 = try std.fs.cwd().openFile(cpuinfo_max_freq_path, .{});
defer file2.close();
const cpuinfo_max_freq_data = try file2.readToEndAlloc(allocator, std.math.maxInt(usize));
defer allocator.free(cpuinfo_max_freq_data);
const maxfreq_file = try std.fs.cwd().openFile(cpuinfo_max_freq_path, .{ .mode = .read_only });
defer maxfreq_file.close();
const maxfreq_data = try utils.readFile(allocator, maxfreq_file, 32);
defer allocator.free(maxfreq_data);
// 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);
cpu_max_freq = cpu_max_freq_khz / 1_000_000;
} else {
@@ -203,9 +211,16 @@ fn parseGpuName(allocator: std.mem.Allocator, name: []u8) !?[]u8 {
pub fn getRamInfo(allocator: std.mem.Allocator) !RamInfo {
// Reads /proc/meminfo
const meminfo_path = "/proc/meminfo";
const file = try std.fs.cwd().openFile(meminfo_path, .{});
defer file.close();
const meminfo_data = try file.readToEndAlloc(allocator, std.math.maxInt(usize));
const meminfo_file = try std.fs.cwd().openFile(meminfo_path, .{ .mode = .read_only });
defer meminfo_file.close();
// NOTE: procfs is a pseudo-filesystem, so it is not possible to determine the size of a file
// https://docs.kernel.org/filesystems/proc.html
// https://en.wikipedia.org/wiki/Procfs
//
// We only need to read the first few lines
// 512 is more than enough
const meminfo_data = try utils.readFile(allocator, meminfo_file, 512);
defer allocator.free(meminfo_data);
// Parsing /proc/meminfo
@@ -265,9 +280,16 @@ pub fn getRamInfo(allocator: std.mem.Allocator) !RamInfo {
pub fn getSwapInfo(allocator: std.mem.Allocator) !?SwapInfo {
// Reads /proc/meminfo
const meminfo_path = "/proc/meminfo";
const file = try std.fs.cwd().openFile(meminfo_path, .{});
defer file.close();
const meminfo_data = try file.readToEndAlloc(allocator, std.math.maxInt(usize));
const meminfo_file = try std.fs.cwd().openFile(meminfo_path, .{ .mode = .read_only });
defer meminfo_file.close();
// NOTE: procfs is a pseudo-filesystem, so it is not possible to determine the size of a file
// https://docs.kernel.org/filesystems/proc.html
// https://en.wikipedia.org/wiki/Procfs
//
// We only need to read the first few lines
// 512 is ok
const meminfo_data = try utils.readFile(allocator, meminfo_file, 512);
defer allocator.free(meminfo_data);
// Parsing /proc/meminfo

View File

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

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

@@ -0,0 +1,242 @@
const std = @import("std");
const utils = @import("../utils.zig");
pub fn getPackagesInfo(allocator: std.mem.Allocator) ![]const u8 {
var packages_info = std.array_list.Managed(u8).init(allocator);
defer packages_info.deinit();
const flatpak_packages = countFlatpakPackages() catch |err| if (err == error.FileNotFound) 0 else return err;
const nix_packages = countNixPackages(allocator) catch 0;
const dpkg_packages = countDpkgPackages(allocator) catch |err| if (err == error.FileNotFound) 0 else return err;
const pacman_packages = countPacmanPackages() catch |err| if (err == error.FileNotFound) 0 else return err;
const xbps_packages = countXbpsPackages(allocator) 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 allocator.dupe(u8, packages_info.items);
}
fn countFlatpakPackages() !usize {
const flatpak_apps = try countFlatpakApps();
const flatpak_runtimes = try countFlatpakRuntimes();
return flatpak_apps + flatpak_runtimes;
}
fn countFlatpakApps() !usize {
var dir = try std.fs.openDirAbsolute("/var/lib/flatpak/app/", .{ .iterate = true });
defer dir.close();
var iter = dir.iterate();
var count: usize = 0;
while (try iter.next()) |e| {
if (e.kind != .directory) continue;
var sub_dir = try dir.openDir(e.name, .{});
defer sub_dir.close();
var current = sub_dir.openDir("current", .{}) catch continue;
defer current.close();
// If `current` was opened successfully, increment the count
count += 1;
}
return count;
}
fn countFlatpakRuntimes() !usize {
var dir = try std.fs.openDirAbsolute("/var/lib/flatpak/runtime/", .{ .iterate = true });
defer dir.close();
var iter = dir.iterate();
var counter: usize = 0;
while (try iter.next()) |e| {
if (std.mem.endsWith(u8, e.name, ".Locale") or std.mem.endsWith(u8, e.name, ".Debug")) continue;
var arch_dir = try dir.openDir(e.name, .{ .iterate = true });
defer arch_dir.close();
var arch_iter = arch_dir.iterate();
while (try arch_iter.next()) |arch_e| {
if (arch_e.kind != .directory) continue;
var sub_dir = try arch_dir.openDir(arch_e.name, .{ .iterate = true });
defer sub_dir.close();
var sub_iter = sub_dir.iterate();
while (try sub_iter.next()) |_| {
counter += 1;
}
}
}
return counter;
}
fn countNixPackages(allocator: std.mem.Allocator) !usize {
// `/run/current-system` is a sym-link, so we need to obtein the real path
const real_path = try std.fs.realpathAlloc(allocator, "/run/current-system");
defer allocator.free(real_path);
var hash: [32]u8 = undefined;
std.crypto.hash.Blake3.hash(real_path, &hash, .{});
const hash_hex = try std.fmt.allocPrint(allocator, "{x}", .{hash});
defer allocator.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(allocator, hash_hex) catch |err| switch (err) {
error.FileNotFound, error.InvalidCache => {
// nix-store --query --requisites /run/current-system | wc -l
const result = try std.process.Child.run(.{ .allocator = allocator, .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 allocator.free(result.stdout);
defer allocator.free(result.stderr);
count = try std.fmt.parseInt(usize, result_trimmed, 10);
try writeNixCache(allocator, hash_hex, count);
return count;
},
else => return err,
};
return count;
}
fn getNixCachePath(allocator: std.mem.Allocator) ![]const u8 {
var cache_dir_path = std.process.getEnvVarOwned(allocator, "XDG_CACHE_HOME") catch try allocator.dupe(u8, "");
if (cache_dir_path.len == 0) {
allocator.free(cache_dir_path);
const home = try std.process.getEnvVarOwned(allocator, "HOME");
defer allocator.free(home);
cache_dir_path = try std.fs.path.join(allocator, &.{ home, ".cache", "zigfetch", "nix" });
} else {
cache_dir_path = try std.fs.path.join(allocator, &.{ cache_dir_path, "zigfetch", "nix" });
}
return cache_dir_path;
}
fn writeNixCache(allocator: std.mem.Allocator, hash: []const u8, count: usize) !void {
const cache_dir_path = try getNixCachePath(allocator);
defer allocator.free(cache_dir_path);
try std.fs.cwd().makePath(cache_dir_path);
var cache_dir = try std.fs.cwd().openDir(cache_dir_path, .{});
defer cache_dir.close();
var cache_file = try cache_dir.createFile("nix_cache", .{ .truncate = true });
defer cache_file.close();
const cache_content = try std.fmt.allocPrint(allocator, "{s}\n{d}", .{ hash, count });
defer allocator.free(cache_content);
try cache_file.writeAll(cache_content);
}
fn checkNixCache(allocator: std.mem.Allocator, hash: []const u8) !usize {
const cache_dir_path = try getNixCachePath(allocator);
defer allocator.free(cache_dir_path);
var cache_dir = try std.fs.cwd().openDir(cache_dir_path, .{});
defer cache_dir.close();
var cache_file = try cache_dir.openFile("nix_cache", .{ .mode = .read_only });
const cache_size = (try cache_file.stat()).size;
const cache_content = try utils.readFile(allocator, cache_file, cache_size);
defer allocator.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(allocator: std.mem.Allocator) !usize {
const dpkg_status_path = "/var/lib/dpkg/status";
const dpkg_file = try std.fs.cwd().openFile(dpkg_status_path, .{ .mode = .read_only });
defer dpkg_file.close();
const file_size = (try dpkg_file.stat()).size;
const content = try utils.readFile(allocator, dpkg_file, file_size);
defer allocator.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() !usize {
// Subtruct 1 to remove `ALPM_DB_VERSION` from the count
return try utils.countEntries("/var/lib/pacman/local") - 1;
}
fn countXbpsPackages(allocator: std.mem.Allocator) !usize {
var dir = try std.fs.openDirAbsolute("/var/db/xbps/", .{ .iterate = true });
defer dir.close();
var count: usize = 0;
var dir_iter = dir.iterate();
while (try dir_iter.next()) |e| {
if ((e.kind == .file) and std.mem.startsWith(u8, e.name, "pkgdb-")) {
const pkgdb_file = try dir.openFile(e.name, .{ .mode = .read_only });
defer pkgdb_file.close();
const file_size = (try pkgdb_file.stat()).size;
const content = try utils.readFile(allocator, pkgdb_file, file_size);
defer allocator.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 utils = @import("../utils.zig");
const c_sysinfo = @cImport(@cInclude("sys/sysinfo.h"));
const c_utsname = @cImport(@cInclude("sys/utsname.h"));
@@ -77,9 +78,10 @@ pub fn getKernelInfo(allocator: std.mem.Allocator) !KernelInfo {
pub fn getOsInfo(allocator: std.mem.Allocator) ![]u8 {
const os_release_path = "/etc/os-release";
const file = try std.fs.cwd().openFile(os_release_path, .{});
defer file.close();
const os_release_data = try file.readToEndAlloc(allocator, std.math.maxInt(usize));
const os_release_file = try std.fs.cwd().openFile(os_release_path, .{ .mode = .read_only });
defer os_release_file.close();
const size = (try os_release_file.stat()).size;
const os_release_data = try utils.readFile(allocator, os_release_file, size);
defer allocator.free(os_release_data);
var pretty_name: ?[]const u8 = null;
@@ -98,3 +100,56 @@ pub fn getOsInfo(allocator: std.mem.Allocator) ![]u8 {
return try allocator.dupe(u8, pretty_name orelse "Unknown");
}
pub fn getWindowManagerInfo(allocator: std.mem.Allocator) ![]const u8 {
var dir = try std.fs.cwd().openDir("/proc/", .{ .iterate = true });
defer dir.close();
var wm_name: ?[]const u8 = null;
var iter = dir.iterate();
wm_name = outer: {
while (try iter.next()) |entry| {
if (entry.kind != .directory) continue;
// Check if the entry name is numeric
_ = std.fmt.parseInt(i32, entry.name, 10) catch continue;
var buf: [1024]u8 = undefined;
const file_name = try std.fmt.bufPrint(&buf, "/proc/{s}/comm", .{entry.name});
const file = try std.fs.cwd().openFile(file_name, .{ .mode = .read_only });
defer file.close();
// NOTE: https://stackoverflow.com/questions/23534263/what-is-the-maximum-allowed-limit-on-the-length-of-a-process-name
const proc_name = try utils.readFile(allocator, file, 16);
defer allocator.free(proc_name);
const proc_name_trimmed = std.mem.trim(u8, proc_name, "\n");
const supported_wms: [9][]const u8 = .{
"i3", // https://i3wm.org/
// "i3gaps", // TODO: find a way to recognize i3gaps
"sway", // https://swaywm.org/
// "swayfx", // TODO: find a way to recognize swayfx
"niri", // https://github.com/YaLTeR/niri
"dwm", // https://dwm.suckless.org/
// "qtile", // TODO: find a way to recognize qtile
"awesome", // https://awesomewm.org/
"river", // https://codeberg.org/river/river
"hyprland", // https://hypr.land/
"bspwm", // https://github.com/baskerville/bspwm
"openbox", // https://openbox.org/
};
inline for (supported_wms) |wm| {
if (std.ascii.eqlIgnoreCase(wm, proc_name_trimmed)) {
break :outer try allocator.dupe(u8, proc_name_trimmed);
}
}
}
break :outer null;
};
return wm_name orelse allocator.dupe(u8, "Unknown");
}

View File

@@ -1,5 +1,5 @@
const std = @import("std");
const utils = @import("utils.zig");
const utils = @import("../utils.zig");
pub fn getPackagesInfo(allocator: std.mem.Allocator) ![]const u8 {
var packages_info = std.array_list.Managed(u8).init(allocator);

View File

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

View File

@@ -23,17 +23,3 @@ pub fn cfTypeRefToZigString(allocator: std.mem.Allocator, cf_type_ref: c_iokit.C
return allocator.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

@@ -27,14 +27,15 @@ pub fn main() !void {
const username = try detection.user.getUsername(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,
username,
ascii.Reset,
ascii.Yellow,
hostname,
ascii.Reset,
}));
const username_hostname_color = if (config.getUsernameHostnameColor(conf)) |color| blk: {
var buf: [32]u8 = undefined;
const rgb = try ascii.hexColorToRgb(color);
const formatted_color = try std.fmt.bufPrint(&buf, "\x1b[38;2;{d};{d};{d}m", .{ rgb.r, rgb.g, rgb.b });
break :blk formatted_color;
} else ascii.Yellow;
try modules_list.append(try formatters.getFormattedUsernameHostname(allocator, username_hostname_color, username, hostname));
allocator.free(hostname);
allocator.free(username);

View File

@@ -43,7 +43,7 @@ pub fn getTerminalSize() !TermSize {
}
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 });
@@ -114,3 +114,28 @@ test "getLongestAsciiArtRowLen" {
try std.testing.expectEqual(40, try getLongestAsciiArtRowLen(rows[0..]));
}
pub fn readFile(allocator: std.mem.Allocator, file: std.fs.File, size: usize) ![]const u8 {
var file_buf = try allocator.alloc(u8, size);
defer allocator.free(file_buf);
const read = try file.read(file_buf);
const data = file_buf[0..read];
return allocator.dupe(u8, data);
}
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;
}