Compare commits
184 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fa1f013640 | |||
| c14e14fc6c | |||
| 2854d2a922 | |||
|
|
8bd839a567 | ||
|
|
7c7b214c1d | ||
|
|
41af324564 | ||
|
|
366cd7b497 | ||
|
|
d85ae15fe6 | ||
|
|
19edc21b89 | ||
|
|
d50ccb06b1 | ||
|
|
c8fb8d6a3e | ||
|
|
df0f21bc48 | ||
|
|
8258df5aae | ||
|
|
937746ad50 | ||
|
|
6ca8dcf334 | ||
|
|
87d31a9112 | ||
|
|
c867ea69c6 | ||
|
|
29d5bb1d98 | ||
|
|
a88aab97ff | ||
|
|
2de0d6ec09 | ||
|
|
6f4e4eb044 | ||
|
|
a64db7a7d3 | ||
|
|
e2cbda50c1 | ||
|
|
51de84d210 | ||
|
|
b9dc58fabe | ||
|
|
2dfcadf413 | ||
|
|
2ea3adef12 | ||
|
|
b4b92abcb5 | ||
|
|
3847bc247a | ||
|
|
784d52eac4 | ||
|
|
f78406448a | ||
|
|
50b592b125 | ||
|
|
7faff1e70d | ||
|
|
c17b97608c | ||
|
|
1e1ad7be17 | ||
|
|
429c0f89b9 | ||
|
|
ad0617a7e5 | ||
|
|
df75b0fdb5 | ||
|
|
89f68fe674 | ||
|
|
89dfeca508 | ||
|
|
a72ede5259 | ||
|
|
7254bda609 | ||
|
|
d8ddd4a18e | ||
|
|
948554d022 | ||
|
|
a9bb9cdeaf | ||
|
|
8132b0fc04 | ||
|
|
d5bb5b19c5 | ||
|
|
1d7a175d29 | ||
|
|
61ceb027a6 | ||
|
|
3e55f6a973 | ||
|
|
a5f4a60d46 | ||
|
|
36ff1857b7 | ||
|
|
48ab100e13 | ||
|
|
1363bad02d | ||
|
|
12435bae0e | ||
|
|
d26be667a1 | ||
|
|
b3ca5ae9eb | ||
|
|
e30c6ccc73 | ||
|
|
8599fe92cf | ||
|
|
19facc09ef | ||
|
|
0aec3d8e5b | ||
|
|
dd2f50c79c | ||
|
|
16bb74c47b | ||
|
|
62df4a52dc | ||
|
|
20f9c6e1d5 | ||
|
|
b09443db4d | ||
|
|
dd3b79b32d | ||
|
|
22376139f2 | ||
|
|
d6978cd4b2 | ||
|
|
2f847fbef3 | ||
|
|
cec2b8068a | ||
|
|
6564d85845 | ||
|
|
a835074ee6 | ||
|
|
3d16102f37 | ||
|
|
24a5e98089 | ||
|
|
f03f7e163c | ||
|
|
69d02a4bb7 | ||
|
|
6a86a81fcc | ||
|
|
a125053c70 | ||
|
|
d9ec3a7de7 | ||
|
|
5f6460f46e | ||
|
|
aab5212e6e | ||
|
|
abff59b7d6 | ||
|
|
1dc0559b8e | ||
|
|
2b32119bc7 | ||
|
|
837b7cd5c4 | ||
|
|
6317269c4f | ||
|
|
989b5b2305 | ||
|
|
c32318dac2 | ||
|
|
c64f2f384d | ||
|
|
c82622cf8e | ||
|
|
9babb021f1 | ||
|
|
ef8b6bcebd | ||
|
|
acc4563d2d | ||
|
|
ea966cd474 | ||
|
|
3214725e58 | ||
|
|
f4a8c962e6 | ||
|
|
f7641c24a3 | ||
|
|
20e2ef80d2 | ||
|
|
3cfae25a75 | ||
|
|
d841a6a726 | ||
|
|
7e7d964fd4 | ||
|
|
a9091f1c93 | ||
|
|
d9ac4e58fc | ||
|
|
9c4e032c04 | ||
|
|
5730f14897 | ||
|
|
f57fc5d9ab | ||
|
|
e7f7205a44 | ||
|
|
8768e85b80 | ||
|
|
27995745e4 | ||
|
|
092171ef7f | ||
|
|
84a5edba4c | ||
|
|
212e3c3bc8 | ||
|
|
9020345b00 | ||
|
|
b7ba91d664 | ||
|
|
1c97ed3685 | ||
|
|
316238f9ea | ||
|
|
7ad5181381 | ||
|
|
02406a7644 | ||
|
|
30970649c2 | ||
|
|
981d5ee579 | ||
|
|
8aa0f4972e | ||
|
|
da70f9ee06 | ||
|
|
b6628c3135 | ||
|
|
c66d127c4d | ||
|
|
f3c9b6e9a6 | ||
|
|
d55af958e7 | ||
|
|
3bcfff5bdc | ||
|
|
42edc5c24b | ||
|
|
537a324275 | ||
|
|
224a7d29d8 | ||
|
|
eb477e5154 | ||
|
|
2d1c7506d8 | ||
|
|
428d882591 | ||
|
|
a1c62a56ae | ||
|
|
5b423d1cef | ||
|
|
6574945e56 | ||
|
|
66bb544c0a | ||
|
|
d90c1d2e9a | ||
|
|
0beec60a8a | ||
|
|
7669da5ae8 | ||
|
|
1267a71250 | ||
|
|
2aa90c04ff | ||
|
|
f6d1c2dc72 | ||
|
|
9df0845530 | ||
|
|
3b3c29e22d | ||
|
|
a866952f86 | ||
|
|
5d7bdd8041 | ||
|
|
635dfe00db | ||
|
|
064e8e9597 | ||
|
|
785915d833 | ||
|
|
e492443a2c | ||
|
|
f1bebb08e9 | ||
|
|
f3af8712d2 | ||
|
|
67a2e19ac4 | ||
|
|
2de5047eb7 | ||
|
|
e88586c47a | ||
|
|
28f94d87ed | ||
|
|
0d7f606b7d | ||
|
|
ec0e3ffd18 | ||
|
|
f73b1be023 | ||
|
|
3a5a268bbe | ||
|
|
bdf4a3f7d7 | ||
|
|
68cc541575 | ||
|
|
e28a3b96e5 | ||
|
|
01ad39c0b5 | ||
|
|
a18fd7ade8 | ||
|
|
3e14691e14 | ||
|
|
4eab0e4487 | ||
|
|
3b737ed4d7 | ||
|
|
073d512b67 | ||
|
|
707f94bd8b | ||
|
|
de214a4a89 | ||
|
|
5b63b30a4f | ||
|
|
9af26702cc | ||
|
|
c660fc903f | ||
|
|
90abbcb1fd | ||
|
|
a52dd145da | ||
|
|
5faf60e53d | ||
|
|
7993cab4df | ||
|
|
b4ec1b6d2d | ||
|
|
cd40fe34d2 | ||
|
|
5e71eaf3f6 | ||
|
|
7ac43a2694 |
48
.gitea/workflows/release.yml
Normal file
48
.gitea/workflows/release.yml
Normal 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
100
.github/workflows/build.yml
vendored
Normal 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
3
.gitignore
vendored
@@ -1 +1,2 @@
|
||||
*zig-*
|
||||
*zig-*
|
||||
result
|
||||
|
||||
18
CONTRIBUTING.md
Normal file
18
CONTRIBUTING.md
Normal 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!**
|
||||
141
README.md
141
README.md
@@ -1,5 +1,18 @@
|
||||
# Zigfetch
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
| Default config | Custom config |
|
||||
| :-----------------------------------------------------: | :---------------------------------------------------: |
|
||||
|  |  |
|
||||
|
||||
---
|
||||
|
||||
- [Description](#description)
|
||||
- [Requirements](#requirements)
|
||||
- [Installation](#installation)
|
||||
@@ -14,11 +27,17 @@ Zigfetch is a minimal [neofetch](https://github.com/dylanaraps/neofetch)/[fastfe
|
||||
|
||||
## Requirements
|
||||
|
||||
- [zig v0.14.0](https://ziglang.org/)
|
||||
- \>= [zig v0.15.2](https://ziglang.org/)
|
||||
|
||||
### Linux only
|
||||
|
||||
- [libpci](https://github.com/pciutils/pciutils)
|
||||
|
||||
## Installation
|
||||
|
||||
```console
|
||||
### Build from source
|
||||
|
||||
```bash
|
||||
# Clone the repo
|
||||
$ git clone https://github.com/utox39/zigfetch.git
|
||||
|
||||
@@ -32,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
|
||||
|
||||
[](https://repology.org/project/zigfetch/versions)
|
||||
|
||||
- nixpkg: Thanks to [@heisfer](https://github.com/heisfer)
|
||||
|
||||
## Usage
|
||||
|
||||
```console
|
||||
$ zigfetch
|
||||
```bash
|
||||
zigfetch
|
||||
```
|
||||
|
||||
### Configuration
|
||||
@@ -45,30 +76,112 @@ $ zigfetch
|
||||
|
||||
- Create the config folder
|
||||
|
||||
```console
|
||||
$ mkdir -p ~/.config/zigfetch
|
||||
```bash
|
||||
mkdir -p ~/.config/zigfetch
|
||||
```
|
||||
|
||||
- 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)
|
||||
|
||||
```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
|
||||
- [ ] Add GPU info for Linux
|
||||
- [ ] Add packages info for Linux
|
||||
- [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!
|
||||
|
||||
BIN
assets/screenshot-custom-config.png
Normal file
BIN
assets/screenshot-custom-config.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 209 KiB |
BIN
assets/screenshot-default-config.png
Normal file
BIN
assets/screenshot-default-config.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 200 KiB |
17
build.zig
17
build.zig
@@ -17,9 +17,11 @@ pub fn build(b: *std.Build) void {
|
||||
|
||||
const exe = b.addExecutable(.{
|
||||
.name = "zigfetch",
|
||||
.root_source_file = b.path("src/main.zig"),
|
||||
.target = target,
|
||||
.optimize = optimize,
|
||||
.root_module = b.createModule(.{
|
||||
.root_source_file = b.path("src/main.zig"),
|
||||
.target = target,
|
||||
.optimize = optimize,
|
||||
}),
|
||||
});
|
||||
|
||||
if (target.result.os.tag == .macos) {
|
||||
@@ -29,6 +31,7 @@ pub fn build(b: *std.Build) void {
|
||||
|
||||
if (target.result.os.tag == .linux) {
|
||||
exe.linkLibC();
|
||||
exe.linkSystemLibrary("pci");
|
||||
}
|
||||
|
||||
// This declares intent for the executable to be installed into the
|
||||
@@ -60,9 +63,11 @@ pub fn build(b: *std.Build) void {
|
||||
run_step.dependOn(&run_cmd.step);
|
||||
|
||||
const exe_unit_tests = b.addTest(.{
|
||||
.root_source_file = b.path("src/main.zig"),
|
||||
.target = target,
|
||||
.optimize = optimize,
|
||||
.root_module = b.createModule(.{
|
||||
.root_source_file = b.path("src/main.zig"),
|
||||
.target = target,
|
||||
.optimize = optimize,
|
||||
}),
|
||||
});
|
||||
|
||||
const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);
|
||||
|
||||
@@ -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.5.1",
|
||||
.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.14.0",
|
||||
.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
20
default.nix
Normal 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
13
shell.nix
Normal 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
|
||||
];
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
const std = @import("std");
|
||||
const utils = @import("./utils.zig");
|
||||
|
||||
pub const Reset = "\x1b[0m";
|
||||
pub const Bold = "\x1b[1m";
|
||||
@@ -64,22 +65,28 @@ test "parse ffffff" {
|
||||
try std.testing.expect((result.r == 255) and (result.g == 255) and (result.b == 255));
|
||||
}
|
||||
|
||||
pub fn printAscii(allocator: std.mem.Allocator, sys_info_list: std.ArrayList([]u8)) !void {
|
||||
const stdout_file = std.io.getStdOut().writer();
|
||||
var bw = std.io.bufferedWriter(stdout_file);
|
||||
const stdout = bw.writer();
|
||||
pub fn printAsciiAndModules(allocator: std.mem.Allocator, ascii_art_path: ?[]u8, sys_info_list: std.array_list.Managed([]u8)) !void {
|
||||
var stdout_buffer: [2048]u8 = undefined;
|
||||
var stdout_writer = std.fs.File.stdout().writer(&stdout_buffer);
|
||||
const stdout = &stdout_writer.interface;
|
||||
|
||||
// const ascii_art_path = "./assets/ascii/guy_fawks.txt";
|
||||
// var file = try std.fs.cwd().openFile(ascii_art_path, .{});
|
||||
// defer file.close();
|
||||
// const ascii_art_data = try file.readToEndAlloc(allocator, std.math.maxInt(usize));
|
||||
// defer allocator.free(ascii_art_data);
|
||||
var ascii_art_data: []const u8 = undefined;
|
||||
if (ascii_art_path) |ascii| {
|
||||
const ascii_file = try std.fs.cwd().openFile(ascii, .{ .mode = .read_only });
|
||||
defer ascii_file.close();
|
||||
const file_size = (try ascii_file.stat()).size;
|
||||
ascii_art_data = try utils.readFile(allocator, ascii_file, file_size);
|
||||
} else {
|
||||
ascii_art_data = @embedFile("./assets/ascii/guy_fawks.txt");
|
||||
}
|
||||
|
||||
const ascii_art_data = @embedFile("./assets/ascii/guy_fawks.txt");
|
||||
defer if (ascii_art_path != null) {
|
||||
allocator.free(ascii_art_data);
|
||||
};
|
||||
|
||||
var lines = std.mem.splitScalar(u8, ascii_art_data, '\n');
|
||||
|
||||
var ascii_art_content_list = std.ArrayList([]const u8).init(allocator);
|
||||
var ascii_art_content_list = std.array_list.Managed([]const u8).init(allocator);
|
||||
defer ascii_art_content_list.deinit();
|
||||
|
||||
while (lines.next()) |line| {
|
||||
@@ -89,27 +96,50 @@ pub fn printAscii(allocator: std.mem.Allocator, sys_info_list: std.ArrayList([]u
|
||||
const ascii_art_items = ascii_art_content_list.items;
|
||||
const sys_info_items = sys_info_list.items;
|
||||
|
||||
const terminal_size = utils.getTerminalSize() catch utils.TermSize{ .height = 50, .width = 50 };
|
||||
const terminal_width: usize = @intCast(terminal_size.width);
|
||||
|
||||
const spacing: usize = 5;
|
||||
|
||||
const longest_ascii_art_row_len: usize = try utils.getLongestAsciiArtRowLen(ascii_art_items);
|
||||
const longest_sys_info_string_len = utils.getLongestSysInfoStringLen(sys_info_items);
|
||||
|
||||
const can_print_ascii_art: bool = terminal_width > longest_ascii_art_row_len + longest_sys_info_string_len + spacing;
|
||||
|
||||
const ascii_art_len: usize = ascii_art_items.len;
|
||||
const sys_info_len: usize = sys_info_items.len;
|
||||
const max_len: usize = if (ascii_art_len > sys_info_len) ascii_art_len else sys_info_len;
|
||||
|
||||
// NOTE: sys_info_len + 3 to be able to print the colors
|
||||
const max_len: usize = if ((ascii_art_len > sys_info_len) and can_print_ascii_art) ascii_art_len else sys_info_len + 3;
|
||||
|
||||
var i: usize = 0;
|
||||
while (i < max_len) : (i += 1) {
|
||||
if (i < ascii_art_len) {
|
||||
try stdout.print("{s:<40} \t", .{ascii_art_items[i]});
|
||||
} else {
|
||||
try stdout.print("{s:<40}", .{""});
|
||||
// Print the ascii art if the width of the terminal is greater than the spacing (5) + the longest ascii art row length + the longest sys info string length
|
||||
if (can_print_ascii_art) {
|
||||
const alignment_buffer = try allocator.alloc(u8, if (i < ascii_art_len) longest_ascii_art_row_len - (try utils.countCodepoints(ascii_art_items[i])) + spacing else longest_ascii_art_row_len + spacing);
|
||||
@memset(alignment_buffer, ' ');
|
||||
|
||||
if (i < ascii_art_len) {
|
||||
try stdout.print("{s}{s}", .{ ascii_art_items[i], alignment_buffer });
|
||||
} else {
|
||||
try stdout.print("{s}", .{alignment_buffer});
|
||||
}
|
||||
|
||||
allocator.free(alignment_buffer);
|
||||
|
||||
try stdout.flush();
|
||||
}
|
||||
try bw.flush();
|
||||
|
||||
if (i < sys_info_len) {
|
||||
try stdout.print("{s}\n", .{sys_info_items[i]});
|
||||
} else if (i == sys_info_len + 1) {
|
||||
// Print the first row of colors
|
||||
for (0..8) |j| {
|
||||
try stdout.print("\x1b[48;5;{d}m \x1b[0m", .{j});
|
||||
}
|
||||
try stdout.print("\n", .{});
|
||||
} else if (i == sys_info_len + 2) {
|
||||
// Print the second row of colors
|
||||
for (8..16) |j| {
|
||||
try stdout.print("\x1b[48;5;{d}m \x1b[0m", .{j});
|
||||
}
|
||||
@@ -117,7 +147,7 @@ pub fn printAscii(allocator: std.mem.Allocator, sys_info_list: std.ArrayList([]u
|
||||
} else {
|
||||
try stdout.print("\n", .{});
|
||||
}
|
||||
try bw.flush();
|
||||
try stdout.flush();
|
||||
}
|
||||
|
||||
for (sys_info_list.items) |item| {
|
||||
|
||||
@@ -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,
|
||||
@@ -9,6 +9,8 @@ pub const Module = struct {
|
||||
};
|
||||
|
||||
pub const Config = struct {
|
||||
ascii_abs_path: ?[]u8 = null,
|
||||
username_hostname_color: ?[]u8 = null,
|
||||
modules: []Module,
|
||||
};
|
||||
|
||||
@@ -23,13 +25,27 @@ pub const ModuleType = enum {
|
||||
ram,
|
||||
swap,
|
||||
disk,
|
||||
net,
|
||||
wm,
|
||||
terminal,
|
||||
locale,
|
||||
net, // It must always be the last element of this array
|
||||
custom,
|
||||
};
|
||||
|
||||
pub fn getModulesTypes(allocator: std.mem.Allocator, config: ?std.json.Parsed(Config)) !std.ArrayList(ModuleType) {
|
||||
var modules_list = std.ArrayList(ModuleType).init(allocator);
|
||||
pub fn getAsciiPath(config: ?std.json.Parsed(Config)) ?[]u8 {
|
||||
if (config) |c| {
|
||||
return c.value.ascii_abs_path;
|
||||
} else return null;
|
||||
}
|
||||
|
||||
pub fn getUsernameHostnameColor(config: ?std.json.Parsed(Config)) ?[]u8 {
|
||||
if (config) |c| {
|
||||
return c.value.username_hostname_color;
|
||||
} else return null;
|
||||
}
|
||||
|
||||
pub fn getModulesTypes(allocator: std.mem.Allocator, config: ?std.json.Parsed(Config)) !std.array_list.Managed(ModuleType) {
|
||||
var modules_list = std.array_list.Managed(ModuleType).init(allocator);
|
||||
|
||||
if (config) |c| {
|
||||
for (c.value.modules) |module| {
|
||||
@@ -37,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;
|
||||
}
|
||||
}
|
||||
@@ -52,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 });
|
||||
}
|
||||
|
||||
@@ -3,7 +3,12 @@ const std = @import("std");
|
||||
const ascii = @import("ascii.zig");
|
||||
const detection = @import("detection.zig").os_module;
|
||||
|
||||
pub const formatters = [_]*const fn (allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) anyerror![]u8{
|
||||
const Result = union(enum) {
|
||||
string: []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{
|
||||
&getFormattedOsInfo,
|
||||
&getFormattedKernelInfo,
|
||||
&getFormattedUptimeInfo,
|
||||
@@ -14,11 +19,14 @@ pub const formatters = [_]*const fn (allocator: std.mem.Allocator, key: []const
|
||||
&getFormattedRamInfo,
|
||||
&getFormattedSwapInfo,
|
||||
&getFormattedDiskInfo,
|
||||
&getFormattedNetInfo,
|
||||
&getFormattedWindowManagerInfo,
|
||||
&getFormattedTerminalNameInfo,
|
||||
&getFormattedLocaleInfo,
|
||||
&getFormattedCustom,
|
||||
};
|
||||
|
||||
pub const default_formatters = [_]*const fn (allocator: std.mem.Allocator) anyerror![]u8{
|
||||
pub const default_formatters = [_]*const fn (allocator: std.mem.Allocator) anyerror!Result{
|
||||
&getDefaultFormattedOsInfo,
|
||||
&getDefaultFormattedKernelInfo,
|
||||
&getDefaultFormattedUptimeInfo,
|
||||
@@ -29,146 +37,185 @@ pub const default_formatters = [_]*const fn (allocator: std.mem.Allocator) anyer
|
||||
&getDefaultFormattedRamInfo,
|
||||
&getDefaultFormattedSwapInfo,
|
||||
&getDefaultFormattedDiskInfo,
|
||||
&getDefaultFormattedNetInfo,
|
||||
&getDefaultFormattedWindowManagerInfo,
|
||||
&getDefaultFormattedTerminalNameInfo,
|
||||
&getDefaultFormattedLocaleInfo,
|
||||
};
|
||||
|
||||
pub fn getDefaultFormattedKernelInfo(allocator: std.mem.Allocator) ![]u8 {
|
||||
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);
|
||||
}
|
||||
|
||||
pub fn getFormattedKernelInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) ![]u8 {
|
||||
pub fn getFormattedKernelInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
|
||||
const kernel_info = try detection.system.getKernelInfo(allocator);
|
||||
defer allocator.free(kernel_info.kernel_name);
|
||||
defer allocator.free(kernel_info.kernel_release);
|
||||
|
||||
return 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, ascii.Reset, kernel_info.kernel_name, kernel_info.kernel_release }) };
|
||||
}
|
||||
|
||||
pub fn getDefaultFormattedOsInfo(allocator: std.mem.Allocator) ![]u8 {
|
||||
pub fn getDefaultFormattedOsInfo(allocator: std.mem.Allocator) !Result {
|
||||
return try getFormattedOsInfo(allocator, "OS", ascii.Yellow);
|
||||
}
|
||||
|
||||
pub fn getFormattedOsInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) ![]u8 {
|
||||
pub fn getFormattedOsInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
|
||||
const os_info = try detection.system.getOsInfo(allocator);
|
||||
defer allocator.free(os_info);
|
||||
return 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, ascii.Reset, os_info }) };
|
||||
}
|
||||
|
||||
pub fn getDefaultFormattedLocaleInfo(allocator: std.mem.Allocator) ![]u8 {
|
||||
pub fn getDefaultFormattedLocaleInfo(allocator: std.mem.Allocator) !Result {
|
||||
return try getFormattedLocaleInfo(allocator, "Locale", ascii.Yellow);
|
||||
}
|
||||
|
||||
pub fn getFormattedLocaleInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) ![]u8 {
|
||||
pub fn getFormattedLocaleInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
|
||||
const locale = try detection.system.getLocale(allocator);
|
||||
defer allocator.free(locale);
|
||||
return 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, ascii.Reset, locale }) };
|
||||
}
|
||||
|
||||
pub fn getDefaultFormattedUptimeInfo(allocator: std.mem.Allocator) ![]u8 {
|
||||
pub fn getDefaultFormattedUptimeInfo(allocator: std.mem.Allocator) !Result {
|
||||
return try getFormattedUptimeInfo(allocator, "Uptime", ascii.Yellow);
|
||||
}
|
||||
|
||||
pub fn getFormattedUptimeInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) ![]u8 {
|
||||
pub fn getFormattedUptimeInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
|
||||
const uptime = try detection.system.getSystemUptime();
|
||||
return try std.fmt.allocPrint(allocator, "{s}{s}:{s} {} days, {} hours, {} minutes ", .{ key_color, key, ascii.Reset, uptime.days, uptime.hours, uptime.minutes });
|
||||
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {} days, {} hours, {} minutes", .{ key_color, key, ascii.Reset, uptime.days, uptime.hours, uptime.minutes }) };
|
||||
}
|
||||
|
||||
pub fn getDefaultFormattedPackagesInfo(allocator: std.mem.Allocator) ![]u8 {
|
||||
pub fn getDefaultFormattedPackagesInfo(allocator: std.mem.Allocator) !Result {
|
||||
return try getFormattedPackagesInfo(allocator, "Packages", ascii.Yellow);
|
||||
}
|
||||
|
||||
pub fn getFormattedPackagesInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) ![]u8 {
|
||||
if (builtin.os.tag == .macos) {
|
||||
const packages_info = try detection.packages.getPackagesInfo(allocator);
|
||||
defer allocator.free(packages_info);
|
||||
return try std.fmt.allocPrint(allocator, "{s}{s}:{s}{s}", .{ key_color, key, ascii.Reset, packages_info });
|
||||
} else if (builtin.os.tag == .linux) {
|
||||
return try std.fmt.allocPrint(allocator, "{s}{s}:{s} WIP", .{ key_color, key, ascii.Reset });
|
||||
}
|
||||
pub fn getFormattedPackagesInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
|
||||
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) ![]u8 {
|
||||
pub fn getDefaultFormattedShellInfo(allocator: std.mem.Allocator) !Result {
|
||||
return try getFormattedShellInfo(allocator, "Shell", ascii.Yellow);
|
||||
}
|
||||
|
||||
pub fn getFormattedShellInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) ![]u8 {
|
||||
pub fn getFormattedShellInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
|
||||
const shell = try detection.user.getShell(allocator);
|
||||
defer allocator.free(shell);
|
||||
return 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, ascii.Reset, shell[0..(shell.len - 1)] }) };
|
||||
}
|
||||
|
||||
pub fn getDefaultFormattedCpuInfo(allocator: std.mem.Allocator) ![]u8 {
|
||||
pub fn getDefaultFormattedCpuInfo(allocator: std.mem.Allocator) !Result {
|
||||
return try getFormattedCpuInfo(allocator, "Cpu", ascii.Yellow);
|
||||
}
|
||||
|
||||
pub fn getFormattedCpuInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) ![]u8 {
|
||||
pub fn getFormattedCpuInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
|
||||
const cpu_info = try detection.hardware.getCpuInfo(allocator);
|
||||
defer allocator.free(cpu_info.cpu_name);
|
||||
return 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, ascii.Reset, cpu_info.cpu_name, cpu_info.cpu_cores, cpu_info.cpu_max_freq }) };
|
||||
}
|
||||
|
||||
pub fn getDefaultFormattedGpuInfo(allocator: std.mem.Allocator) ![]u8 {
|
||||
return try getFormattedGpuInfo(allocator, "Gpu", ascii.Yellow);
|
||||
pub fn getDefaultFormattedGpuInfo(allocator: std.mem.Allocator) !Result {
|
||||
if (builtin.os.tag == .macos) {
|
||||
return try getFormattedGpuInfo(allocator, "Gpu", ascii.Yellow);
|
||||
} else if (builtin.os.tag == .linux) {
|
||||
return try getFormattedGpuInfo(allocator, "Gpu", ascii.Yellow);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn getFormattedGpuInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) ![]u8 {
|
||||
pub fn getFormattedGpuInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
|
||||
if (builtin.os.tag == .macos) {
|
||||
const gpu_info = try detection.hardware.getGpuInfo(allocator);
|
||||
defer allocator.free(gpu_info.gpu_name);
|
||||
return try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s} ({}) @ {d:.2} GHz", .{ key_color, key, ascii.Reset, gpu_info.gpu_name, gpu_info.gpu_cores, gpu_info.gpu_freq });
|
||||
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}:{s} {s} ({}) @ {d:.2} GHz", .{ key_color, key, ascii.Reset, gpu_info.gpu_name, gpu_info.gpu_cores, gpu_info.gpu_freq }) };
|
||||
} else if (builtin.os.tag == .linux) {
|
||||
return try std.fmt.allocPrint(allocator, "{s}{s}:{s} WIP", .{ key_color, key, ascii.Reset });
|
||||
var formatted_gpu_info_list = std.array_list.Managed([]u8).init(allocator);
|
||||
|
||||
const gpu_info_list = try detection.hardware.getGpuInfo(allocator);
|
||||
|
||||
for (gpu_info_list.items) |g| {
|
||||
var formatted_gpu_info: []u8 = undefined;
|
||||
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 });
|
||||
} 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 });
|
||||
}
|
||||
try formatted_gpu_info_list.append(formatted_gpu_info);
|
||||
allocator.free(g.gpu_name);
|
||||
}
|
||||
gpu_info_list.deinit();
|
||||
|
||||
return Result{ .string_arraylist = formatted_gpu_info_list };
|
||||
}
|
||||
}
|
||||
|
||||
pub fn getDefaultFormattedRamInfo(allocator: std.mem.Allocator) ![]u8 {
|
||||
pub fn getDefaultFormattedRamInfo(allocator: std.mem.Allocator) !Result {
|
||||
return try getFormattedRamInfo(allocator, "Ram", ascii.Yellow);
|
||||
}
|
||||
|
||||
pub fn getFormattedRamInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) ![]u8 {
|
||||
pub fn getFormattedRamInfo(allocator: std.mem.Allocator, 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);
|
||||
return 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 });
|
||||
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 }) };
|
||||
}
|
||||
|
||||
pub fn getDefaultFormattedSwapInfo(allocator: std.mem.Allocator) ![]u8 {
|
||||
pub fn getDefaultFormattedSwapInfo(allocator: std.mem.Allocator) !Result {
|
||||
return try getFormattedSwapInfo(allocator, "Swap", ascii.Yellow);
|
||||
}
|
||||
|
||||
pub fn getFormattedSwapInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) ![]u8 {
|
||||
pub fn getFormattedSwapInfo(allocator: std.mem.Allocator, 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);
|
||||
if (swap_info) |s| {
|
||||
return try std.fmt.allocPrint(allocator, "{s}{s}:{s} {d:.2} / {d:.2} GiB ({}%)", .{ key_color, key, ascii.Reset, s.swap_usage, s.swap_usage, s.swap_usage_percentage });
|
||||
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 }) };
|
||||
} else {
|
||||
return 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, ascii.Reset }) };
|
||||
}
|
||||
}
|
||||
|
||||
pub fn getDefaultFormattedDiskInfo(allocator: std.mem.Allocator) ![]u8 {
|
||||
pub fn getDefaultFormattedDiskInfo(allocator: std.mem.Allocator) !Result {
|
||||
return try getFormattedDiskInfo(allocator, "Disk", ascii.Yellow);
|
||||
}
|
||||
|
||||
pub fn getFormattedDiskInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) ![]u8 {
|
||||
pub fn getFormattedDiskInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
|
||||
const disk_info = try detection.hardware.getDiskSize("/");
|
||||
return try std.fmt.allocPrint(allocator, "{s}{s} ({s}):{s} {d:.2} / {d:.2} GB ({}%)", .{ key_color, key, disk_info.disk_path, ascii.Reset, disk_info.disk_usage, disk_info.disk_size, disk_info.disk_usage_percentage });
|
||||
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s} ({s}):{s} {d:.2} / {d:.2} GB ({}%)", .{ key_color, key, disk_info.disk_path, ascii.Reset, disk_info.disk_usage, disk_info.disk_size, disk_info.disk_usage_percentage }) };
|
||||
}
|
||||
|
||||
pub fn getDefaultFormattedTerminalNameInfo(allocator: std.mem.Allocator) ![]u8 {
|
||||
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);
|
||||
}
|
||||
|
||||
pub fn getFormattedTerminalNameInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) ![]u8 {
|
||||
pub fn getFormattedTerminalNameInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
|
||||
const terminal_name = try detection.user.getTerminalName(allocator);
|
||||
defer allocator.free(terminal_name);
|
||||
return 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, ascii.Reset, terminal_name }) };
|
||||
}
|
||||
|
||||
pub fn getDefaultFormattedNetInfo(allocator: std.mem.Allocator) ![]u8 {
|
||||
pub fn getDefaultFormattedNetInfo(allocator: std.mem.Allocator) !Result {
|
||||
return try getFormattedNetInfo(allocator, "Local IP", ascii.Yellow);
|
||||
}
|
||||
|
||||
pub fn getFormattedNetInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !std.ArrayList([]u8) {
|
||||
var formatted_net_info_list = std.ArrayList([]u8).init(allocator);
|
||||
pub fn getFormattedNetInfo(allocator: std.mem.Allocator, key: []const u8, key_color: []const u8) !Result {
|
||||
var formatted_net_info_list = std.array_list.Managed([]u8).init(allocator);
|
||||
|
||||
var net_info_list = try detection.network.getNetInfo(allocator);
|
||||
for (net_info_list.items) |n| {
|
||||
@@ -178,5 +225,9 @@ pub fn getFormattedNetInfo(allocator: std.mem.Allocator, key: []const u8, key_co
|
||||
}
|
||||
net_info_list.deinit();
|
||||
|
||||
return 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 {
|
||||
return Result{ .string = try std.fmt.allocPrint(allocator, "{s}{s}{s}", .{ key_color, key, ascii.Reset }) };
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
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"));
|
||||
|
||||
/// Struct representing CPU informations
|
||||
pub const CpuInfo = struct {
|
||||
@@ -9,6 +11,13 @@ pub const CpuInfo = struct {
|
||||
cpu_max_freq: f32,
|
||||
};
|
||||
|
||||
/// Struct representing GPU informations
|
||||
pub const GpuInfo = struct {
|
||||
gpu_name: []u8,
|
||||
gpu_cores: i32,
|
||||
gpu_freq: f64,
|
||||
};
|
||||
|
||||
/// Struct representing RAM usage informations
|
||||
pub const RamInfo = struct {
|
||||
ram_size: f64,
|
||||
@@ -36,13 +45,21 @@ 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
|
||||
var model_name: ?[]const u8 = null;
|
||||
var cpu_max_freq_mhz_str: ?[]const u8 = null;
|
||||
|
||||
var lines = std.mem.splitScalar(u8, cpuinfo_data, '\n');
|
||||
while (lines.next()) |line| {
|
||||
@@ -52,22 +69,50 @@ pub fn getCpuInfo(allocator: std.mem.Allocator) !CpuInfo {
|
||||
_ = parts.next(); // discards the key
|
||||
if (parts.next()) |value| {
|
||||
model_name = std.mem.trim(u8, value, " ");
|
||||
break;
|
||||
}
|
||||
} else if (std.mem.startsWith(u8, trimmed, "cpu MHz") and cpu_max_freq_mhz_str == null) {
|
||||
var parts = std.mem.splitScalar(u8, trimmed, ':');
|
||||
_ = parts.next(); // discard the key
|
||||
if (parts.next()) |value| {
|
||||
cpu_max_freq_mhz_str = std.mem.trim(u8, value, " ");
|
||||
}
|
||||
}
|
||||
|
||||
if ((model_name != null) and (cpu_max_freq_mhz_str != null)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Reads /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq
|
||||
const cpuinfo_max_freq_path = "/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);
|
||||
var cpu_max_freq: f32 = 0.0;
|
||||
|
||||
// Parsing /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq
|
||||
const trimmed = std.mem.trim(u8, cpuinfo_max_freq_data, " \n\r");
|
||||
const cpu_max_freq_khz: f32 = try std.fmt.parseFloat(f32, trimmed);
|
||||
const cpu_max_freq: f32 = cpu_max_freq_khz / 1_000_000;
|
||||
// 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;
|
||||
|
||||
// Checks if /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq exists
|
||||
_ = std.fs.accessAbsolute(cpuinfo_max_freq_path, .{ .mode = .read_only }) catch |err| {
|
||||
if (err == std.posix.AccessError.FileNotFound) {
|
||||
cmf_exists = false;
|
||||
}
|
||||
};
|
||||
|
||||
if (cmf_exists) {
|
||||
// Reads /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq
|
||||
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, 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 {
|
||||
if (cpu_max_freq_mhz_str != null) {
|
||||
const cpu_max_freq_mhz: f32 = try std.fmt.parseFloat(f32, cpu_max_freq_mhz_str.?);
|
||||
cpu_max_freq = cpu_max_freq_mhz / 1_000;
|
||||
}
|
||||
}
|
||||
|
||||
return CpuInfo{
|
||||
.cpu_name = try allocator.dupe(u8, model_name orelse "Unknown"),
|
||||
@@ -76,12 +121,106 @@ pub fn getCpuInfo(allocator: std.mem.Allocator) !CpuInfo {
|
||||
};
|
||||
}
|
||||
|
||||
pub fn getGpuInfo(allocator: std.mem.Allocator) !std.array_list.Managed(GpuInfo) {
|
||||
var gpu_info_list = std.array_list.Managed(GpuInfo).init(allocator);
|
||||
|
||||
const display_controller = 0x03;
|
||||
|
||||
const pacc = c_libpci.pci_alloc();
|
||||
defer c_libpci.pci_cleanup(pacc);
|
||||
c_libpci.pci_init(pacc);
|
||||
c_libpci.pci_scan_bus(pacc);
|
||||
|
||||
var devices = pacc.*.devices;
|
||||
while (devices != null) : (devices = devices.*.next) {
|
||||
// NOTE: for references: https://github.com/pciutils/pciutils/blob/3ec74c71c01878f92e751f15bb8febe720c3ab40/lib/access.c#L194
|
||||
const known_fields = c_libpci.pci_fill_info(devices, c_libpci.PCI_FILL_IDENT | c_libpci.PCI_FILL_CLASS);
|
||||
if (known_fields <= 0) {
|
||||
return error.NoLibpciFieldsFound;
|
||||
}
|
||||
|
||||
if ((devices.*.device_class >> 8) == display_controller) {
|
||||
var name_buffer: [256]u8 = undefined;
|
||||
|
||||
const name = c_libpci.pci_lookup_name(
|
||||
pacc,
|
||||
&name_buffer,
|
||||
name_buffer.len,
|
||||
c_libpci.PCI_LOOKUP_VENDOR | c_libpci.PCI_LOOKUP_DEVICE,
|
||||
devices.*.vendor_id,
|
||||
devices.*.device_id,
|
||||
);
|
||||
|
||||
const gpu_name = try allocator.dupe(u8, std.mem.span(name));
|
||||
|
||||
const maybe_parsed_gpu_name = try parseGpuName(allocator, gpu_name);
|
||||
var parsed_gpu_name: []u8 = undefined;
|
||||
|
||||
if (maybe_parsed_gpu_name != null) {
|
||||
allocator.free(gpu_name);
|
||||
parsed_gpu_name = maybe_parsed_gpu_name.?;
|
||||
} else {
|
||||
parsed_gpu_name = gpu_name;
|
||||
}
|
||||
|
||||
try gpu_info_list.append(GpuInfo{
|
||||
.gpu_name = parsed_gpu_name,
|
||||
.gpu_cores = 0,
|
||||
.gpu_freq = 0.0,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (gpu_info_list.items.len == 0) {
|
||||
try gpu_info_list.append(GpuInfo{
|
||||
.gpu_name = try allocator.dupe(u8, "Unknown"),
|
||||
.gpu_cores = 0,
|
||||
.gpu_freq = 0.0,
|
||||
});
|
||||
}
|
||||
|
||||
return gpu_info_list;
|
||||
}
|
||||
|
||||
fn parseGpuName(allocator: std.mem.Allocator, name: []u8) !?[]u8 {
|
||||
// NOTE: for references: https://github.com/pciutils/pciutils/blob/master/pci.ids
|
||||
|
||||
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 parsed_gpu_name = try allocator.alloc(u8, size);
|
||||
_ = std.mem.replace(u8, name, "Advanced Micro Devices, Inc. [AMD/ATI]", "AMD", parsed_gpu_name);
|
||||
|
||||
return parsed_gpu_name;
|
||||
} else if (std.mem.startsWith(u8, name, "Intel Corporation")) {
|
||||
const size = std.mem.replacementSize(u8, name, "Intel Corporation", "Intel");
|
||||
const parsed_gpu_name = try allocator.alloc(u8, size);
|
||||
_ = std.mem.replace(u8, name, "Intel Corporation", "Intel", parsed_gpu_name);
|
||||
|
||||
return parsed_gpu_name;
|
||||
} else if (std.mem.startsWith(u8, name, "NVIDIA Corporation")) {
|
||||
const size = std.mem.replacementSize(u8, name, "NVIDIA Corporation", "NVIDIA");
|
||||
const parsed_gpu_name = try allocator.alloc(u8, size);
|
||||
_ = std.mem.replace(u8, name, "NVIDIA Corporation", "NVIDIA", parsed_gpu_name);
|
||||
|
||||
return parsed_gpu_name;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
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
|
||||
@@ -141,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
|
||||
@@ -203,7 +349,7 @@ pub fn getDiskSize(disk_path: []const u8) !DiskInfo {
|
||||
}
|
||||
|
||||
const total_size = stat.f_blocks * stat.f_frsize;
|
||||
const free_size = stat.f_bavail * stat.f_frsize;
|
||||
const free_size = stat.f_bfree * stat.f_frsize;
|
||||
const used_size = total_size - free_size;
|
||||
|
||||
const used_size_percentage = (used_size * 100) / total_size;
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -11,8 +11,8 @@ pub const NetInfo = struct {
|
||||
ipv4_addr: []u8,
|
||||
};
|
||||
|
||||
pub fn getNetInfo(allocator: std.mem.Allocator) !std.ArrayList(NetInfo) {
|
||||
var net_info_list = std.ArrayList(NetInfo).init(allocator);
|
||||
pub fn getNetInfo(allocator: std.mem.Allocator) !std.array_list.Managed(NetInfo) {
|
||||
var net_info_list = std.array_list.Managed(NetInfo).init(allocator);
|
||||
|
||||
var ifap: ?*c_ifaddrs.ifaddrs = null;
|
||||
if (c_ifaddrs.getifaddrs(&ifap) != 0) {
|
||||
|
||||
242
src/linux/packages.zig
Normal file
242
src/linux/packages.zig
Normal 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;
|
||||
}
|
||||
@@ -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"));
|
||||
|
||||
@@ -70,16 +71,17 @@ pub fn getKernelInfo(allocator: std.mem.Allocator) !KernelInfo {
|
||||
}
|
||||
|
||||
return KernelInfo{
|
||||
.kernel_name = try allocator.dupe(u8, &uts.sysname),
|
||||
.kernel_release = try allocator.dupe(u8, &uts.release),
|
||||
.kernel_name = try allocator.dupe(u8, std.mem.sliceTo(&uts.sysname, 0)),
|
||||
.kernel_release = try allocator.dupe(u8, std.mem.sliceTo(&uts.release, 0)),
|
||||
};
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
@@ -6,26 +6,38 @@ pub fn getUsername(allocator: std.mem.Allocator) ![]u8 {
|
||||
}
|
||||
|
||||
pub fn getShell(allocator: std.mem.Allocator) ![]u8 {
|
||||
const shell = try std.process.getEnvVarOwned(allocator, "SHELL");
|
||||
const shell = std.process.getEnvVarOwned(allocator, "SHELL") catch |err| if (err == error.EnvironmentVariableNotFound) {
|
||||
return allocator.dupe(u8, "Unknown");
|
||||
} else return err;
|
||||
|
||||
var child = std.process.Child.init(&[_][]const u8{ shell, "--version" }, allocator);
|
||||
defer allocator.free(shell);
|
||||
|
||||
child.stdout_behavior = .Pipe;
|
||||
child.stderr_behavior = .Pipe;
|
||||
const result = try std.process.Child.run(.{ .allocator = allocator, .argv = &[_][]const u8{ shell, "--version" } });
|
||||
const result_stdout = result.stdout;
|
||||
|
||||
try child.spawn();
|
||||
if (std.mem.indexOf(u8, shell, "bash") != null) {
|
||||
const bash_version = parseBashVersion(result_stdout);
|
||||
defer allocator.free(result_stdout);
|
||||
return try std.fmt.allocPrint(allocator, "{s} {s}", .{ "bash", bash_version.? });
|
||||
}
|
||||
|
||||
const output = try child.stdout.?.reader().readAllAlloc(allocator, 1024 * 1024);
|
||||
return result_stdout;
|
||||
}
|
||||
|
||||
_ = try child.wait();
|
||||
fn parseBashVersion(shell_version_output: []u8) ?[]u8 {
|
||||
const end_index = std.mem.indexOf(u8, shell_version_output, "(");
|
||||
if (end_index == null) return null;
|
||||
|
||||
return output;
|
||||
const version_keyword = "version ";
|
||||
const version_keyword_index = std.mem.indexOf(u8, shell_version_output[0..end_index.?], version_keyword);
|
||||
if (version_keyword_index == null) return null;
|
||||
|
||||
return shell_version_output[version_keyword_index.? + version_keyword.len .. end_index.?];
|
||||
}
|
||||
|
||||
pub fn getTerminalName(allocator: std.mem.Allocator) ![]u8 {
|
||||
const term_progrm = std.process.getEnvVarOwned(allocator, "TERM_PROGRAM") catch |err| if (err == error.EnvironmentVariableNotFound) {
|
||||
const term_program = std.process.getEnvVarOwned(allocator, "TERM_PROGRAM") catch |err| if (err == error.EnvironmentVariableNotFound) {
|
||||
return allocator.dupe(u8, "Unknown");
|
||||
} else return err;
|
||||
return term_progrm;
|
||||
return term_program;
|
||||
}
|
||||
|
||||
@@ -172,7 +172,6 @@ fn getCpuFreqAppleSilicon() !f64 {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: test on intel machine
|
||||
pub fn getCpuFreqIntel() f64 {
|
||||
var freq: f64 = 0;
|
||||
var size: usize = @sizeOf(f64);
|
||||
@@ -237,7 +236,7 @@ pub fn getGpuInfo(allocator: std.mem.Allocator) !GpuInfo {
|
||||
|
||||
if (c_iokit.CFDictionaryGetValueIfPresent(@as(c_iokit.CFDictionaryRef, @ptrCast(properties_ptr)), model_key, &name_ref) == c_iokit.TRUE) {
|
||||
if (c_iokit.CFGetTypeID(name_ref) == c_iokit.CFStringGetTypeID()) {
|
||||
const accel_name = utils.cfStringToZigString(allocator, @as(c_iokit.CFStringRef, @ptrCast(name_ref))) catch {
|
||||
const accel_name = utils.cfTypeRefToZigString(allocator, name_ref) catch {
|
||||
return gpu_info;
|
||||
};
|
||||
|
||||
@@ -419,7 +418,7 @@ pub fn getDiskSize(disk_path: []const u8) !DiskInfo {
|
||||
}
|
||||
|
||||
const total_size = stat.f_blocks * stat.f_frsize;
|
||||
const free_size = stat.f_bavail * stat.f_frsize;
|
||||
const free_size = stat.f_bfree * stat.f_frsize;
|
||||
const used_size = total_size - free_size;
|
||||
|
||||
const used_size_percentage = (used_size * 100) / total_size;
|
||||
|
||||
@@ -11,8 +11,8 @@ pub const NetInfo = struct {
|
||||
ipv4_addr: []u8,
|
||||
};
|
||||
|
||||
pub fn getNetInfo(allocator: std.mem.Allocator) !std.ArrayList(NetInfo) {
|
||||
var net_info_list = std.ArrayList(NetInfo).init(allocator);
|
||||
pub fn getNetInfo(allocator: std.mem.Allocator) !std.array_list.Managed(NetInfo) {
|
||||
var net_info_list = std.array_list.Managed(NetInfo).init(allocator);
|
||||
|
||||
var ifap: ?*c_ifaddrs.ifaddrs = null;
|
||||
if (c_ifaddrs.getifaddrs(&ifap) != 0) {
|
||||
|
||||
@@ -1,35 +1,26 @@
|
||||
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.ArrayList(u8).init(allocator);
|
||||
var packages_info = std.array_list.Managed(u8).init(allocator);
|
||||
defer packages_info.deinit();
|
||||
|
||||
const homebrew_packages = countHomebrewPackages() catch |err| if (err == error.FileNotFound) 0 else return err;
|
||||
const homebrew_casks = countHomebrewCasks() catch |err| if (err == error.FileNotFound) 0 else return err;
|
||||
const macports_packages = countMacportPackages() catch |err| if (err == error.FileNotFound) 0 else return err;
|
||||
|
||||
var buffer: [10]u8 = undefined;
|
||||
var fbs = std.io.fixedBufferStream(&buffer);
|
||||
var buffer: [32]u8 = undefined;
|
||||
|
||||
if (homebrew_packages > 0) {
|
||||
try std.fmt.formatInt(homebrew_packages, 10, .lower, .{}, fbs.writer());
|
||||
try packages_info.appendSlice(" brew: ");
|
||||
try packages_info.appendSlice(fbs.getWritten());
|
||||
try packages_info.appendSlice(try std.fmt.bufPrint(&buffer, " brew: {d}", .{homebrew_packages}));
|
||||
}
|
||||
|
||||
if (homebrew_casks > 0) {
|
||||
fbs.reset();
|
||||
try std.fmt.formatInt(homebrew_casks, 10, .lower, .{}, fbs.writer());
|
||||
try packages_info.appendSlice(" brew-cask: ");
|
||||
try packages_info.appendSlice(fbs.getWritten());
|
||||
try packages_info.appendSlice(try std.fmt.bufPrint(&buffer, " brew-cask: {d}", .{homebrew_casks}));
|
||||
}
|
||||
|
||||
if (macports_packages > 0) {
|
||||
fbs.reset();
|
||||
try std.fmt.formatInt(macports_packages, 10, .lower, .{}, fbs.writer());
|
||||
try packages_info.appendSlice(" macports: ");
|
||||
try packages_info.appendSlice(fbs.getWritten());
|
||||
try packages_info.appendSlice(try std.fmt.bufPrint(&buffer, " macports: {d}", .{macports_packages}));
|
||||
}
|
||||
|
||||
return try allocator.dupe(u8, packages_info.items);
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
@@ -9,26 +9,38 @@ pub fn getUsername(allocator: std.mem.Allocator) ![]u8 {
|
||||
}
|
||||
|
||||
pub fn getShell(allocator: std.mem.Allocator) ![]u8 {
|
||||
const shell = try std.process.getEnvVarOwned(allocator, "SHELL");
|
||||
const shell = std.process.getEnvVarOwned(allocator, "SHELL") catch |err| if (err == error.EnvironmentVariableNotFound) {
|
||||
return allocator.dupe(u8, "Unknown");
|
||||
} else return err;
|
||||
|
||||
var child = std.process.Child.init(&[_][]const u8{ shell, "--version" }, allocator);
|
||||
defer allocator.free(shell);
|
||||
|
||||
child.stdout_behavior = .Pipe;
|
||||
child.stderr_behavior = .Pipe;
|
||||
const result = try std.process.Child.run(.{ .allocator = allocator, .argv = &[_][]const u8{ shell, "--version" } });
|
||||
const result_stdout = result.stdout;
|
||||
|
||||
try child.spawn();
|
||||
if (std.mem.indexOf(u8, shell, "bash") != null) {
|
||||
const bash_version = parseBashVersion(result_stdout);
|
||||
defer allocator.free(result_stdout);
|
||||
return try std.fmt.allocPrint(allocator, "{s} {s}", .{ "bash", bash_version.? });
|
||||
}
|
||||
|
||||
const output = try child.stdout.?.reader().readAllAlloc(allocator, 1024 * 1024);
|
||||
return result_stdout;
|
||||
}
|
||||
|
||||
_ = try child.wait();
|
||||
fn parseBashVersion(shell_version_output: []u8) ?[]u8 {
|
||||
const end_index = std.mem.indexOf(u8, shell_version_output, "(");
|
||||
if (end_index == null) return null;
|
||||
|
||||
return output;
|
||||
const version_keyword = "version ";
|
||||
const version_keyword_index = std.mem.indexOf(u8, shell_version_output[0..end_index.?], version_keyword);
|
||||
if (version_keyword_index == null) return null;
|
||||
|
||||
return shell_version_output[version_keyword_index.? + version_keyword.len .. end_index.?];
|
||||
}
|
||||
|
||||
pub fn getTerminalName(allocator: std.mem.Allocator) ![]u8 {
|
||||
const term_progrm = std.process.getEnvVarOwned(allocator, "TERM_PROGRAM") catch |err| if (err == error.EnvironmentVariableNotFound) {
|
||||
const term_program = std.process.getEnvVarOwned(allocator, "TERM_PROGRAM") catch |err| if (err == error.EnvironmentVariableNotFound) {
|
||||
return allocator.dupe(u8, "Unknown");
|
||||
} else return err;
|
||||
return term_progrm;
|
||||
return term_program;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
const std = @import("std");
|
||||
const c_iokit = @cImport(@cInclude("IOKit/IOKitLib.h"));
|
||||
|
||||
/// Converts a CFString to a Zig string.
|
||||
pub fn cfStringToZigString(allocator: std.mem.Allocator, cf_string: c_iokit.CFStringRef) ![]u8 {
|
||||
/// Converts a CFTypeRef casted to CFStringRef to a Zig string.
|
||||
pub fn cfTypeRefToZigString(allocator: std.mem.Allocator, cf_type_ref: c_iokit.CFTypeRef) ![]u8 {
|
||||
const cf_string: c_iokit.CFStringRef = @ptrFromInt(@intFromPtr(cf_type_ref));
|
||||
|
||||
const length = c_iokit.CFStringGetLength(cf_string);
|
||||
const max_size = c_iokit.CFStringGetMaximumSizeForEncoding(length, c_iokit.kCFStringEncodingUTF8) + 1;
|
||||
const max_size_usize = @as(usize, @intCast(max_size));
|
||||
@@ -21,17 +23,3 @@ pub fn cfStringToZigString(allocator: std.mem.Allocator, cf_string: c_iokit.CFSt
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
54
src/main.zig
54
src/main.zig
@@ -10,11 +10,11 @@ pub fn main() !void {
|
||||
const allocator = gpa.allocator();
|
||||
defer _ = gpa.deinit();
|
||||
|
||||
var sys_info_list = std.ArrayList([]u8).init(allocator);
|
||||
defer sys_info_list.deinit();
|
||||
var modules_list = std.array_list.Managed([]u8).init(allocator);
|
||||
defer modules_list.deinit();
|
||||
|
||||
errdefer {
|
||||
for (sys_info_list.items) |info| {
|
||||
for (modules_list.items) |info| {
|
||||
allocator.free(info);
|
||||
}
|
||||
}
|
||||
@@ -27,24 +27,32 @@ pub fn main() !void {
|
||||
|
||||
const username = try detection.user.getUsername(allocator);
|
||||
const hostname = try detection.system.getHostname(allocator);
|
||||
try sys_info_list.append(try std.fmt.allocPrint(allocator, "{s}{s}{s}@{s}{s}{s}", .{
|
||||
ascii.Yellow,
|
||||
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);
|
||||
|
||||
const separtor_buffer = try allocator.alloc(u8, username.len + hostname.len + 1);
|
||||
@memset(separtor_buffer, '-');
|
||||
try sys_info_list.append(separtor_buffer);
|
||||
try modules_list.append(separtor_buffer);
|
||||
|
||||
if (modules_types.items.len == 0) {
|
||||
inline for (0..formatters.formatters.len) |i| {
|
||||
try sys_info_list.append(try formatters.default_formatters[i](allocator));
|
||||
inline for (0..formatters.default_formatters.len) |i| {
|
||||
const result = try formatters.default_formatters[i](allocator);
|
||||
switch (result) {
|
||||
.string => |r| try modules_list.append(r),
|
||||
.string_arraylist => |r| {
|
||||
defer r.deinit();
|
||||
try modules_list.appendSlice(r.items);
|
||||
},
|
||||
}
|
||||
}
|
||||
} else if (conf) |c| {
|
||||
for (modules_types.items, c.value.modules) |module_type, module| {
|
||||
@@ -52,18 +60,16 @@ pub fn main() !void {
|
||||
const rgb = try ascii.hexColorToRgb(module.key_color);
|
||||
const key_color = try std.fmt.bufPrint(&buf, "\x1b[38;2;{d};{d};{d}m", .{ rgb.r, rgb.g, rgb.b });
|
||||
|
||||
if (module_type == config.ModuleType.net) {
|
||||
var formatted_net_info_list = try formatters.getFormattedNetInfo(allocator, module.key, key_color);
|
||||
defer formatted_net_info_list.deinit();
|
||||
|
||||
try sys_info_list.appendSlice(formatted_net_info_list.items);
|
||||
|
||||
continue;
|
||||
const result = try formatters.formatters[@intFromEnum(module_type)](allocator, module.key, key_color);
|
||||
switch (result) {
|
||||
.string => |r| try modules_list.append(r),
|
||||
.string_arraylist => |r| {
|
||||
defer r.deinit();
|
||||
try modules_list.appendSlice(r.items);
|
||||
},
|
||||
}
|
||||
|
||||
try sys_info_list.append(try formatters.formatters[@intFromEnum(module_type)](allocator, module.key, key_color));
|
||||
}
|
||||
}
|
||||
|
||||
try ascii.printAscii(allocator, sys_info_list);
|
||||
try ascii.printAsciiAndModules(allocator, config.getAsciiPath(conf), modules_list);
|
||||
}
|
||||
|
||||
141
src/utils.zig
Normal file
141
src/utils.zig
Normal file
@@ -0,0 +1,141 @@
|
||||
const std = @import("std");
|
||||
const builtin = @import("builtin");
|
||||
|
||||
pub const TermSize = struct {
|
||||
width: u16,
|
||||
height: u16,
|
||||
};
|
||||
|
||||
pub fn getTerminalSize() !TermSize {
|
||||
// https://github.com/softprops/zig-termsize (https://github.com/softprops/zig-termsize/blob/main/src/main.zig)
|
||||
|
||||
const stdout = std.fs.File.stdout();
|
||||
|
||||
switch (builtin.os.tag) {
|
||||
.windows => {
|
||||
var buf: std.os.windows.CONSOLE_SCREEN_BUFFER_INFO = undefined;
|
||||
switch (std.os.windows.kernel32.GetConsoleScreenBufferInfo(stdout.handle, &buf)) {
|
||||
std.os.windows.TRUE => return TermSize{
|
||||
.width = @intCast(buf.srWindow.Right - buf.srWindow.Left + 1),
|
||||
.height = @intCast(buf.srWindow.Bottom - buf.srWindow.Top + 1),
|
||||
},
|
||||
else => return error.GetConsoleScreenBufferInfoFailed,
|
||||
}
|
||||
},
|
||||
.linux, .macos => {
|
||||
var buf: std.posix.winsize = undefined;
|
||||
switch (std.posix.errno(
|
||||
std.posix.system.ioctl(
|
||||
stdout.handle,
|
||||
std.posix.T.IOCGWINSZ,
|
||||
@intFromPtr(&buf),
|
||||
),
|
||||
)) {
|
||||
std.posix.E.SUCCESS => return TermSize{
|
||||
.width = buf.col,
|
||||
.height = buf.row,
|
||||
},
|
||||
else => return error.IoctlFailed,
|
||||
}
|
||||
},
|
||||
else => return error.UnsupportedOperatingSystem,
|
||||
}
|
||||
}
|
||||
|
||||
test "getTerminalSize" {
|
||||
const terminal_size = getTerminalSize() catch TermSize{ .height = 50, .width = 50 };
|
||||
|
||||
std.debug.print("Height: {}, Width {}\n", .{ terminal_size.height, terminal_size.width });
|
||||
|
||||
try std.testing.expect((terminal_size.height > 0) and (terminal_size.width > 0));
|
||||
}
|
||||
|
||||
pub fn getLongestSysInfoStringLen(strings: []const []const u8) usize {
|
||||
const ansi_reset = "\x1b[0m";
|
||||
var longest_len: usize = 0;
|
||||
|
||||
// Ignore the username@host and the separator
|
||||
for (strings[2..]) |s| {
|
||||
const ansi_restet_index = std.mem.indexOf(u8, s, ansi_reset);
|
||||
var start: usize = 0;
|
||||
|
||||
if (ansi_restet_index != null) {
|
||||
// `start` is the index of the last character of the ANSI reset escape sequence + 1
|
||||
start = ansi_restet_index.? + ansi_reset.len + 1;
|
||||
|
||||
if (start > s.len) continue;
|
||||
}
|
||||
|
||||
longest_len = @max(longest_len, s[start..].len);
|
||||
}
|
||||
|
||||
return longest_len;
|
||||
}
|
||||
|
||||
test "getLongestSysInfoStringLen" {
|
||||
const strings = [_][]const u8{ "", "", "test", "test-test", "test1" };
|
||||
|
||||
try std.testing.expectEqual(strings[3].len, getLongestSysInfoStringLen(strings[0..]));
|
||||
}
|
||||
|
||||
pub fn countCodepoints(str: []const u8) !usize {
|
||||
var count: usize = 0;
|
||||
var i: usize = 0;
|
||||
|
||||
while (i < str.len) {
|
||||
const byte_len = try std.unicode.utf8ByteSequenceLength(str[i]);
|
||||
if ((i + byte_len > str.len) or (!std.unicode.utf8ValidateSlice(str[i .. i + byte_len]))) return error.InvalidUtf8;
|
||||
|
||||
count += 1;
|
||||
i += byte_len;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
test "countCodepoints" {
|
||||
const str = " ████████████████";
|
||||
|
||||
try std.testing.expectEqual(28, try countCodepoints(str));
|
||||
}
|
||||
|
||||
pub fn getLongestAsciiArtRowLen(ascii_art: []const []const u8) !usize {
|
||||
var longest_len: usize = 0;
|
||||
|
||||
for (ascii_art) |ascii_row| {
|
||||
longest_len = @max(longest_len, try countCodepoints(ascii_row));
|
||||
}
|
||||
|
||||
return longest_len;
|
||||
}
|
||||
|
||||
test "getLongestAsciiArtRowLen" {
|
||||
const rows = [_][]const u8{ " ████████████████", "██░░░░██████████░░ ░░██████████░░░░██" };
|
||||
|
||||
try std.testing.expectEqual(40, try getLongestAsciiArtRowLen(rows[0..]));
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
Reference in New Issue
Block a user