feat: implement moonfetch (fastfetch clone in MoonBit native)
Copilot Setup Steps / copilot-setup-steps (push) Successful in 21s

This commit is contained in:
nandi committed 2026-11-17 22:19:58 +00:00
commit ca918a4a34
21 files changed
+2129

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
# Git Hooks
## Pre-commit Hook
This pre-commit hook performs automatic checks before finalizing your commit.
### Usage Instructions
To use this pre-commit hook:
1. Make the hook executable if it isn't already:
```bash
chmod +x .githooks/pre-commit
```
2. Configure Git to use the hooks in the .githooks directory:
```bash
git config core.hooksPath .githooks
```
3. The hook will automatically run when you execute `git commit`
+3
View File
@@ -0,0 +1,3 @@
#!/bin/sh
moon check
+41
View File
@@ -0,0 +1,41 @@
# Reference: https://docs.github.com/en/copilot/how-tos/use-copilot-agents/coding-agent/customize-the-agent-environment
name: "Copilot Setup Steps"
# Automatically run the setup steps when they are changed to allow for easy validation, and
# allow manual testing through the repository's "Actions" tab
on:
workflow_dispatch:
push:
paths:
- .github/workflows/copilot-setup-steps.yml
pull_request:
paths:
- .github/workflows/copilot-setup-steps.yml
jobs:
# The job MUST be called `copilot-setup-steps` or it will not be picked up by Copilot.
copilot-setup-steps:
runs-on: ubuntu-latest
# Set the permissions to the lowest permissions possible needed for your steps.
# Copilot will be given its own token for its operations.
permissions:
# If you want to clone the repository as part of your setup steps, for example to install dependencies, you'll need the `contents: read` permission. If you don't clone the repository in your setup steps, Copilot will do this for you automatically after the steps complete.
contents: read
# You can define any steps you want, and they will run before the agent starts.
# If you do not check out your code, Copilot will do this for you.
steps:
- name: Checkout code
uses: actions/checkout@v5
- name: Set up MoonBit
run: |
curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash
echo "$HOME/.moon/bin" >> $GITHUB_PATH
- name: Update MoonBit dependencies
run: |
moon version --all
moon update
+6
View File
@@ -0,0 +1,6 @@
.DS_Store
_build/
target/
target
.mooncakes/
.moonagent/
+53
View File
@@ -0,0 +1,53 @@
# Project Agents.md Guide
This is a [MoonBit](https://docs.moonbitlang.com) project.
You can browse and install extra skills here:
<https://github.com/moonbitlang/skills>
## Project Structure
- MoonBit packages are organized per directory; each directory contains a
`moon.pkg` file listing its dependencies. Each package has its files and
blackbox test files (ending in `_test.mbt`) and whitebox test files (ending in
`_wbtest.mbt`).
- In the toplevel directory, there is a `moon.mod` file listing module
metadata.
## Coding convention
- MoonBit code is organized in block style, each block is separated by `///|`,
the order of each block is irrelevant. In some refactorings, you can process
block by block independently.
- Try to keep deprecated blocks in file called `deprecated.mbt` in each
directory.
## Tooling
- `moon fmt` is used to format your code properly.
- `moon ide` provides project navigation helpers like `peek-def`, `outline`, and
`find-references`. See $moonbit-agent-guide for details.
- `moon info` is used to update the generated interface of the package, each
package has a generated interface file `.mbti`, it is a brief formal
description of the package. If nothing in `.mbti` changes, this means your
change does not bring the visible changes to the external package users, it is
typically a safe refactoring.
- In the last step, run `moon info && moon fmt` to update the interface and
format the code. Check the diffs of `.mbti` file to see if the changes are
expected.
- Run `moon test` to check tests pass. MoonBit supports snapshot testing; when
changes affect outputs, run `moon test --update` to refresh snapshots.
- Prefer `assert_eq` or `assert_true(pattern is Pattern(...))` for results that
are stable or very unlikely to change. For snapshot tests that record
structured debugging output, derive `Debug` and use `debug_inspect`, rather
than deriving `Show` for debugging. For solid, well-defined results (e.g.
scientific computations), prefer assertion tests. You can use
`moon coverage analyze > uncovered.log` to see which parts of your code are
not covered by tests.
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+38
View File
@@ -0,0 +1,38 @@
# moonfetch
A `fastfetch` clone written in **MoonBit** targeting the native backend (`native`).
## Features
- **ASCII Art Logos**: Auto-detected from `/etc/os-release` (`moonbit`, `debian`, `ubuntu`, `arch`, `fedora`, `alpine`, `linux`) or selectable via `--logo <name>` / `--no-logo`.
- **System Info Modules**:
- `user@hostname` + separator
- OS (`PRETTY_NAME` + arch)
- Host / Model (`/sys/devices/virtual/dmi/id/*` or container/VM detection)
- Kernel (`uname`)
- Uptime (`/proc/uptime`)
- Packages (`dpkg`, `apk`, `pacman`)
- Shell & Terminal (`$SHELL`, `$TERM_PROGRAM`/`$TERM`, `TIOCGWINSZ`)
- DE / WM (`$XDG_CURRENT_DESKTOP`, `$WAYLAND_DISPLAY`, `$DISPLAY`)
- CPU (`/proc/cpuinfo`)
- Memory (`/proc/meminfo`)
- Disk (`/`) (`statvfs`)
- Local IP (`getifaddrs`) & Locale (`$LC_ALL`/`$LANG`)
- ANSI 16-color palette bar
- **CLI Options**:
- `-h`, `--help`
- `-v`, `--version`
- `-l`, `--logo <name>` / `--no-logo`
- `--no-color`
- `--json`
- `-s`, `--structure <modules>` (colon- or comma-separated)
- `-c`, `--config <path>`
## Build & Test
```bash
moon check --target native
moon test --target native
moon build --target native --release
./_build/native/release/build/cmd/main/main.exe
```
Symlink
+1
View File
@@ -0,0 +1 @@
README.mbt.md
+188
View File
@@ -0,0 +1,188 @@
///|
#derive(Eq, Debug)
pub struct CliOptions {
show_help : Bool
show_version : Bool
logo : String?
no_logo : Bool
json : Bool
no_color : Bool
structure : Array[String]
config_path : String?
error : String?
}
///|
pub fn default_structure() -> Array[String] {
[
"title", "separator", "os", "host", "kernel", "uptime", "packages", "shell",
"terminal", "de", "cpu", "memory", "disk", "localip", "locale", "break", "colors",
]
}
///|
pub fn CliOptions::default() -> CliOptions {
{
show_help: false,
show_version: false,
logo: None,
no_logo: false,
json: false,
no_color: false,
structure: default_structure(),
config_path: None,
error: None,
}
}
///|
pub fn parse_structure(s : String) -> Array[String] {
let normalized = s.replace_all(old=",", new=":")
let out : Array[String] = []
for part in normalized.split(":") {
let item = part.trim().to_owned().to_lower()
if !item.is_empty() {
out.push(item)
}
}
if out.is_empty() {
default_structure()
} else {
out
}
}
///|
pub fn parse_config_content(content : String, base : CliOptions) -> CliOptions {
let mut logo = base.logo
let mut no_logo = base.no_logo
let mut json = base.json
let mut no_color = base.no_color
let mut structure = base.structure
for line_view in content.split("\n") {
let line = line_view.trim().to_owned()
if line.is_empty() || line.has_prefix("#") || line == "{" || line == "}" {
continue
}
let clean = if line.has_suffix(",") {
line.unsafe_substring(start=0, end=line.length() - 1)
} else {
line
}
let sep_idx = match clean.find("=") {
Some(i) => Some(i)
None => clean.find(":")
}
match sep_idx {
Some(idx) => {
let key = trim_quotes(clean.unsafe_substring(start=0, end=idx)).to_lower()
let val = trim_quotes(
clean.unsafe_substring(start=idx + 1, end=clean.length()),
)
match key {
"logo" =>
if val.to_lower() == "none" {
no_logo = true
} else if !val.is_empty() {
logo = Some(val)
}
"no_logo" | "no-logo" => no_logo = val.to_lower() == "true"
"json" => json = val.to_lower() == "true"
"no_color" | "no-color" => no_color = val.to_lower() == "true"
"structure" => structure = parse_structure(val)
_ => ()
}
}
None => ()
}
}
{ ..base, logo, no_logo, json, no_color, structure, }
}
///|
pub fn parse_args(args : Array[String]) -> CliOptions {
let mut opts = CliOptions::default()
let mut i = 0
while i < args.length() {
let arg = args[i]
if arg == "-h" || arg == "--help" {
opts = { ..opts, show_help: true, }
} else if arg == "-v" || arg == "--version" {
opts = { ..opts, show_version: true, }
} else if arg == "--no-logo" {
opts = { ..opts, no_logo: true, }
} else if arg == "--json" {
opts = { ..opts, json: true, }
} else if arg == "--no-color" {
opts = { ..opts, no_color: true, }
} else if arg == "-l" || arg == "--logo" {
if i + 1 >= args.length() {
return { ..opts, error: Some("Missing value for \{arg}"), }
}
i += 1
let val = args[i]
if val.to_lower() == "none" {
opts = { ..opts, no_logo: true, }
} else {
opts = { ..opts, logo: Some(val), }
}
} else if arg.has_prefix("--logo=") {
let val = arg.unsafe_substring(start=7, end=arg.length())
if val.to_lower() == "none" {
opts = { ..opts, no_logo: true, }
} else {
opts = { ..opts, logo: Some(val), }
}
} else if arg == "-s" || arg == "--structure" {
if i + 1 >= args.length() {
return { ..opts, error: Some("Missing value for \{arg}"), }
}
i += 1
opts = { ..opts, structure: parse_structure(args[i]), }
} else if arg.has_prefix("--structure=") {
let val = arg.unsafe_substring(start=12, end=arg.length())
opts = { ..opts, structure: parse_structure(val), }
} else if arg == "-c" || arg == "--config" {
if i + 1 >= args.length() {
return { ..opts, error: Some("Missing value for \{arg}"), }
}
i += 1
opts = { ..opts, config_path: Some(args[i]), }
} else if arg.has_prefix("--config=") {
let val = arg.unsafe_substring(start=9, end=arg.length())
opts = { ..opts, config_path: Some(val), }
} else {
return { ..opts, error: Some("Unknown argument: \{arg}"), }
}
i += 1
}
opts
}
///|
pub fn version_text() -> String {
"moonfetch 0.1.0 (MoonBit native)"
}
///|
pub fn help_text() -> String {
let logos = available_logos().join(", ")
[
"moonfetch - A fastfetch clone written in MoonBit",
"",
"Usage: moonfetch [OPTIONS]",
"",
"Options:",
" -h, --help Show this help message and exit",
" -v, --version Show version information and exit",
" -l, --logo <name> Select ASCII logo (\{logos})",
" --no-logo Disable the ASCII logo",
" --no-color Disable ANSI color output",
" --json Output system information as JSON",
" -s, --structure <modules> Colon-separated modules to display",
" (title, separator, os, host, kernel, uptime,",
" packages, shell, terminal, de, cpu, memory,",
" disk, localip, locale, break, colors)",
" -c, --config <path> Load options from a config file",
].join("\n")
}
+27
View File
@@ -0,0 +1,27 @@
///|
fn main {
let raw_args = @env.args()
let cli_args : Array[String] = []
for i in 1..<raw_args.length() {
cli_args.push(raw_args[i])
}
let opts = @lib.resolve_options(cli_args)
match opts.error {
Some(msg) => {
println("Error: \{msg}")
println("Run 'moonfetch --help' for usage.")
@env.exit(1)
}
None => ()
}
if opts.show_help {
println(@lib.help_text())
return
}
if opts.show_version {
println(@lib.version_text())
return
}
let info = @lib.collect_system_info()
println(@lib.render_fetch(info, opts))
}
+6
View File
@@ -0,0 +1,6 @@
import {
"experiments/moonfetch" @lib,
"moonbitlang/core/env",
}
pkgtype(kind: "executable")
+12
View File
@@ -0,0 +1,12 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/moonfetch/cmd/main"
// Values
// Errors
// Types and methods
// Type aliases
// Traits
+141
View File
@@ -0,0 +1,141 @@
///|
pub struct Logo {
name : String
primary_color : String
secondary_color : String
lines : Array[String]
}
///|
pub fn detect_logo_name(os_id : String) -> String {
match os_id.to_lower() {
"debian" => "debian"
"ubuntu" | "linuxmint" | "pop" => "ubuntu"
"arch" | "endeavouros" | "manjaro" | "cachyos" => "arch"
"fedora" | "rhel" | "centos" | "rocky" | "almalinux" => "fedora"
"alpine" => "alpine"
_ => "moonbit"
}
}
///|
pub fn get_logo(name : String) -> Logo {
match name.to_lower() {
"debian" =>
{
name: "debian",
primary_color: "\u001b[1;31m",
secondary_color: "\u001b[31m",
lines: [
" _,met$$$$$gg. ", " ,g$$$$$$$$$$$$$$$P. ", " ,g$$P\" \"\"\"Y$$.\". ",
" ,$$P' `$$$. ", "',$$P ,ggs. `$$b: ", "`d$$' ,$P\"' . $$$ ",
" $$P d$' , $$P ", " $$: $$. - ,d$$' ", " $$; Y$b._ _,d$P' ",
" Y$$. `.`\"Y$$$$P\"' ", " `$$b \"-.__ ",
" `Y$$ ", " `Y$$. ", " `$$b. ",
" `Y$$b. ", " `\"Y$b._ ", " `\"\"\" ",
],
}
"ubuntu" =>
{
name: "ubuntu",
primary_color: "\u001b[1;33m",
secondary_color: "\u001b[1;31m",
lines: [
" .-/+oossssoo+/-. ", " `:+ssssssssssssssssss+:` ",
" -+ssssssssssssssssssyyssss+- ", " .ossssssssssssssssssdMMMNysssso. ",
" /ssssssssssshdmmNNmmyNMMMMhssssss/ ", " +ssssssssshmydMMMMMMMNddddyssssssss+ ",
" /sssssssshNMMMyhhyyyyhmNMMMNhssssssss/ ", ".ssssssssdMMMNhsssssssssshNMMMdssssssss. ",
"+sssshhhyNMMNyssssssssssssyNMMMysssssss+ ", "ossyNMMMNyMMhsssssssssssssshmmmhssssssso ",
"ossyNMMMNyMMhsssssssssssssshmmmhssssssso ", "+sssshhhyNMMNyssssssssssssyNMMMysssssss+ ",
".ssssssssdMMMNhsssssssssshNMMMdssssssss. ", " /sssssssshNMMMyhhyyyyhdNMMMNhssssssss/ ",
" +sssssssssdmydMMMMMMMMddddyssssssss+ ", " /ssssssssssshdmNNNNmyNMMMMhssssss/ ",
" .ossssssssssssssssssdMMMNysssso. ", " -+sssssssssssssssssyyyssss+- ",
" `:+ssssssssssssssssss+:` ", " .-/+oossssoo+/-. ",
],
}
"arch" =>
{
name: "arch",
primary_color: "\u001b[1;36m",
secondary_color: "\u001b[36m",
lines: [
" -` ", " .o+` ",
" `ooo/ ", " `+oooo: ",
" `+oooooo: ", " -+oooooo+: ",
" `/:-:++oooo+: ", " `/++++/+++++++: ",
" `/++++++++++++++: ", " `/+++ooooooooooooo/` ",
" ./ooosssso++osssssso+` ", " .oossssso-````/ossssss+` ",
" -osssssso. :ssssssso. ", " :osssssss/ osssso+++. ",
" /ossssssss/ +ssssooo/- ", " `/ossssso+/:- -:/+osssso+- ",
" `+sso+:-` `.-/+oso: ", " `++:. `-/+/ ",
" .` `/ ",
],
}
"fedora" =>
{
name: "fedora",
primary_color: "\u001b[1;34m",
secondary_color: "\u001b[34m",
lines: [
" .',;::::;,'. ", " .';:cccccccccccc:;,. ",
" .;cccccccccccccccccccccc;. ", " .:cccccccccccccccccccccccccc:. ",
" .;ccccccccccccc;.:dddl:.;ccccccc;. ", " .:ccccccccccccc;OWMKOOXMWd;ccccccc:. ",
".:ccccccccccccc;KMMc;cc;xMMc;ccccccc:. ", ",cccccccccccccc;MMM.;cc;;WW:;cccccccc, ",
":cccccccccccccc;MMM.;cccccccccccccccc: ", ":ccccccc;oxOOOo;MMM0OOk.;cccccccccccc: ",
"cccccc;0MMKxdd:;MMMkddc.;cccccccccccc; ", "ccccc;XM0';cccc;MMM.;cccccccccccccccc' ",
"ccccc;MMo;ccccc;MMW.;ccccccccccccccc; ", "ccccc;0MNc.ccc.xMMd;ccccccccccccccc; ",
"cccccc;dNMWXXXWM0:;cccccccccccccc:, ", "cccccccc;.:odl:.;cccccccccccccc:,. ",
":cccccccccccccccccccccccccccc:'. ", ".:cccccccccccccccccccccc:;,.. ",
" '::cccccccccccccc::;,. ",
],
}
"alpine" =>
{
name: "alpine",
primary_color: "\u001b[1;34m",
secondary_color: "\u001b[36m",
lines: [
" .hddddddddddddddddddddddh. ", " :dddddddddddddddddddddddddd: ",
" /dddddddddddddddddddddddddddd/ ", " +dddddddddddddddddddddddddddddd+ ",
" `sdddddddddddddddddddddddddddddddds` ", " `ydddddddddddd++hdddddddddddddddddddy` ",
".hddddddddddd+` `+ddddh:-sdddddddddddh. ", "hdddddddddd+` `+y: .sddddddddddh ",
"ddddddddh+` `//` `.` -sddddddddd ", "ddddddh+` `/hddh/` `:s- -sddddddd ",
"ddddh+` `/+/dddddh/` `+s- -sddddd ", "ddd+` `/o` :dddddddh/` `oy- .yddd ",
"hdddyo+ohddyosdddddddddho+oydddyo+ohdddh ", ".hddddddddddddddddddddddddddddddddddddh. ",
" `yddddddddddddddddddddddddddddddddddy` ", " `sdddddddddddddddddddddddddddddddds` ",
" +dddddddddddddddddddddddddddddd+ ", " /dddddddddddddddddddddddddddd/ ",
" :dddddddddddddddddddddddddd: ", " .hddddddddddddddddddddddh. ",
],
}
"linux" =>
{
name: "linux",
primary_color: "\u001b[1;33m",
secondary_color: "\u001b[1;37m",
lines: [
" ##### ", " ####### ", " ##O#O## ",
" ####### ", " ########### ", " ############# ",
" ############### ", " ################ ", " ################# ",
"##################### ", "##################### ", " ################# ",
" ############# ", " ########### ",
],
}
_ =>
{
name: "moonbit",
primary_color: "\u001b[1;35m",
secondary_color: "\u001b[1;33m",
lines: [
" _..._ ", " .:::::::. * ", " ::::::::::: ",
" ::::::::::::: . ", " ::::::' `::: ", " :::::' `:: ",
" ::::: .: * ", " :::::. .:: ", " ::::::. .::: ",
" ::::::::::::' . ", " ':::::::::' ", " `'::::'' * ",
],
}
}
}
///|
pub fn available_logos() -> Array[String] {
["moonbit", "debian", "ubuntu", "arch", "fedora", "alpine", "linux", "none"]
}
+19
View File
@@ -0,0 +1,19 @@
name = "experiments/moonfetch"
version = "0.1.0"
readme = "README.mbt.md"
repository = "https://git.site.latha.org/experiments/moonfetch"
license = "Apache-2.0"
keywords = [ "fastfetch", "sysinfo", "cli", "linux" ]
preferred_target = "native"
description = "A fastfetch clone written in MoonBit for Linux (native target)."
import {
"moonbitlang/x@0.5.7",
}
+13
View File
@@ -0,0 +1,13 @@
import {
"moonbitlang/core/encoding/utf8",
"moonbitlang/core/env",
"moonbitlang/x/fs",
}
import {
"experiments/moonfetch" @lib,
} for "test"
options(
"native-stub": [ "native_stubs.c" ],
)
+172
View File
@@ -0,0 +1,172 @@
///|
test "parse_os_release debian" {
let sample =
#|PRETTY_NAME="Debian GNU/Linux 12 (bookworm)"
#|NAME="Debian GNU/Linux"
#|VERSION_ID="12"
#|ID=debian
let res = @lib.parse_os_release(sample)
assert_eq(res.pretty_name, "Debian GNU/Linux 12 (bookworm)")
assert_eq(res.id, "debian")
assert_eq(res.name, "Debian GNU/Linux")
assert_eq(res.version_id, "12")
}
///|
test "parse_os_release fallback pretty_name" {
let sample =
#|NAME="Alpine Linux"
#|ID=alpine
#|VERSION_ID=3.20
let res = @lib.parse_os_release(sample)
assert_eq(res.pretty_name, "Alpine Linux 3.20")
assert_eq(res.id, "alpine")
}
///|
test "parse_cpuinfo" {
let sample =
#|processor : 0
#|model name : AMD EPYC 7763 64-Core Processor
#|cpu MHz : 2445.406
#|
#|processor : 1
#|model name : AMD EPYC 7763 64-Core Processor
#|cpu MHz : 2445.406
let cpu = @lib.parse_cpuinfo(sample)
assert_eq(cpu.model, "AMD EPYC 7763 64-Core Processor")
assert_eq(cpu.cores, 2)
assert_eq(cpu.mhz, "2445.406")
}
///|
test "parse_meminfo with MemAvailable" {
let sample =
#|MemTotal: 16384000 kB
#|MemFree: 2000000 kB
#|MemAvailable: 12288000 kB
let mem = @lib.parse_meminfo(sample)
assert_eq(mem.total_kib, 16384000UL)
assert_eq(mem.available_kib, 12288000UL)
assert_eq(mem.used_kib, 4096000UL)
}
///|
test "parse_meminfo fallback without MemAvailable" {
let sample =
#|MemTotal: 8000000 kB
#|MemFree: 1000000 kB
#|Buffers: 500000 kB
#|Cached: 2500000 kB
let mem = @lib.parse_meminfo(sample)
assert_eq(mem.available_kib, 4000000UL)
assert_eq(mem.used_kib, 4000000UL)
}
///|
test "parse_uptime_seconds and format_uptime" {
assert_eq(@lib.parse_uptime_seconds("45.67 80.12\n"), 45)
assert_eq(@lib.format_uptime(45), "45 secs")
assert_eq(@lib.format_uptime(65), "1 min")
assert_eq(@lib.format_uptime(3665), "1 hour, 1 min")
assert_eq(@lib.format_uptime(90120), "1 day, 1 hour, 2 mins")
}
///|
test "format_usage" {
let one_gib : UInt64 = 1073741824UL
let four_gib : UInt64 = 4UL * one_gib
assert_eq(@lib.format_usage(one_gib, four_gib), "1.00 GiB / 4.00 GiB (25%)")
assert_eq(@lib.format_usage(0UL, 0UL), "Unknown")
}
///|
test "count_dpkg_installed and count_apk_installed" {
let dpkg =
#|Package: bash
#|Status: install ok installed
#|
#|Package: removed-pkg
#|Status: deinstall ok config-files
#|
#|Package: curl
#|Status: install ok installed
assert_eq(@lib.count_dpkg_installed(dpkg), 2)
let apk =
#|P:busybox
#|V:1.36.1
#|P:musl
#|V:1.2.4
assert_eq(@lib.count_apk_installed(apk), 2)
}
///|
test "cli parse_args" {
let opts = @lib.parse_args([
"--logo", "arch", "--no-color", "--structure", "title:os:memory",
])
assert_eq(opts.logo, Some("arch"))
assert_eq(opts.no_color, true)
assert_eq(opts.no_logo, false)
assert_eq(opts.structure, ["title", "os", "memory"])
assert_eq(opts.error, None)
let err_opts = @lib.parse_args(["--unknown-flag"])
assert_true(err_opts.error is Some(_))
let no_logo_opts = @lib.parse_args(["--logo=none", "--json"])
assert_eq(no_logo_opts.no_logo, true)
assert_eq(no_logo_opts.json, true)
}
///|
test "parse_config_content" {
let cfg =
#|# sample config
#|logo = "moonbit"
#|no_color = true
#|structure = "title,os,kernel"
let opts = @lib.parse_config_content(cfg, @lib.CliOptions::default())
assert_eq(opts.logo, Some("moonbit"))
assert_eq(opts.no_color, true)
assert_eq(opts.structure, ["title", "os", "kernel"])
}
///|
test "visible_len and render_fetch no_color" {
assert_eq(@lib.visible_len("\u001b[1;31mhello\u001b[0m"), 5)
let info : @lib.SystemInfo = {
username: "alice",
hostname: "box",
os_id: "debian",
os_name: "Debian 12 x86_64",
host_model: "KVM",
kernel: "Linux 6.1",
arch: "x86_64",
uptime: "10 mins",
uptime_secs: 600,
packages: "100 (dpkg)",
shell: "bash 5.2",
terminal: "xterm (80x24)",
de_wm: "Headless / TTY",
cpu: "Test CPU (4)",
memory: "1.00 GiB / 4.00 GiB (25%)",
mem_used_kib: 1048576UL,
mem_total_kib: 4194304UL,
disk: "2.00 GiB / 10.00 GiB (20%)",
disk_used_bytes: 2147483648UL,
disk_total_bytes: 10737418240UL,
local_ip: "10.0.0.2",
locale: "C.UTF-8",
}
let opts = @lib.parse_args([
"--no-logo", "--no-color", "--structure", "title:separator:os:kernel",
])
let out = @lib.render_fetch(info, opts)
assert_eq(
out, "alice@box\n---------\nOS: Debian 12 x86_64\nKernel: Linux 6.1",
)
let json_out = info.to_json()
assert_true(json_out.contains("\"username\": \"alice\""))
assert_true(json_out.contains("\"os\": \"Debian 12 x86_64\""))
}
+158
View File
@@ -0,0 +1,158 @@
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/statvfs.h>
#include <sys/types.h>
#include <sys/utsname.h>
#include <unistd.h>
#include "moonbit.h"
static moonbit_bytes_t cstr_to_moonbit_bytes(const char *s) {
if (!s) {
return moonbit_make_bytes(0, 0);
}
size_t len = strlen(s);
moonbit_bytes_t b = moonbit_make_bytes((int32_t)len, 0);
if (len > 0) {
memcpy(b, s, len);
}
return b;
}
MOONBIT_FFI_EXPORT moonbit_bytes_t moonfetch_uname_info(void) {
struct utsname u;
if (uname(&u) != 0) {
return cstr_to_moonbit_bytes("");
}
char buf[1024];
snprintf(buf, sizeof(buf), "%s\n%s\n%s\n%s", u.sysname, u.nodename, u.release,
u.machine);
return cstr_to_moonbit_bytes(buf);
}
MOONBIT_FFI_EXPORT moonbit_bytes_t moonfetch_get_username(void) {
const char *env_user = getenv("USER");
if (env_user && env_user[0] != '\0') {
return cstr_to_moonbit_bytes(env_user);
}
struct passwd *pw = getpwuid(geteuid());
if (pw && pw->pw_name) {
return cstr_to_moonbit_bytes(pw->pw_name);
}
return cstr_to_moonbit_bytes("user");
}
MOONBIT_FFI_EXPORT moonbit_bytes_t moonfetch_get_disk_usage(moonbit_bytes_t path) {
struct statvfs st;
if (statvfs((const char *)path, &st) != 0) {
return cstr_to_moonbit_bytes("");
}
unsigned long long total =
(unsigned long long)st.f_blocks * (unsigned long long)st.f_frsize;
unsigned long long avail =
(unsigned long long)st.f_bavail * (unsigned long long)st.f_frsize;
unsigned long long free_all =
(unsigned long long)st.f_bfree * (unsigned long long)st.f_frsize;
unsigned long long used = total >= free_all ? (total - free_all) : 0;
(void)avail;
char buf[128];
snprintf(buf, sizeof(buf), "%llu,%llu", used, total);
return cstr_to_moonbit_bytes(buf);
}
MOONBIT_FFI_EXPORT moonbit_bytes_t moonfetch_get_term_size(void) {
struct winsize ws;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col > 0 &&
ws.ws_row > 0) {
char buf[64];
snprintf(buf, sizeof(buf), "%u,%u", (unsigned)ws.ws_col,
(unsigned)ws.ws_row);
return cstr_to_moonbit_bytes(buf);
}
return cstr_to_moonbit_bytes("");
}
MOONBIT_FFI_EXPORT moonbit_bytes_t moonfetch_get_local_ip(void) {
struct ifaddrs *ifaddr = NULL;
if (getifaddrs(&ifaddr) != 0) {
return cstr_to_moonbit_bytes("");
}
char result[INET_ADDRSTRLEN] = "";
for (struct ifaddrs *ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
if (!ifa->ifa_addr || ifa->ifa_addr->sa_family != AF_INET) {
continue;
}
if (ifa->ifa_name && strcmp(ifa->ifa_name, "lo") == 0) {
continue;
}
struct sockaddr_in *sa = (struct sockaddr_in *)ifa->ifa_addr;
if (inet_ntop(AF_INET, &sa->sin_addr, result, sizeof(result)) != NULL) {
if (strncmp(result, "127.", 4) != 0) {
break;
}
result[0] = '\0';
}
}
freeifaddrs(ifaddr);
return cstr_to_moonbit_bytes(result);
}
MOONBIT_FFI_EXPORT moonbit_bytes_t moonfetch_popen_first_line(moonbit_bytes_t cmd) {
FILE *fp = popen((const char *)cmd, "r");
if (!fp) {
return cstr_to_moonbit_bytes("");
}
char buf[512];
buf[0] = '\0';
if (fgets(buf, sizeof(buf), fp) != NULL) {
size_t len = strlen(buf);
while (len > 0 && (buf[len - 1] == '\n' || buf[len - 1] == '\r')) {
buf[--len] = '\0';
}
}
pclose(fp);
return cstr_to_moonbit_bytes(buf);
}
MOONBIT_FFI_EXPORT moonbit_bytes_t moonfetch_read_file_stream(moonbit_bytes_t path) {
FILE *fp = fopen((const char *)path, "rb");
if (!fp) {
return moonbit_make_bytes(0, 0);
}
size_t cap = 4096;
size_t len = 0;
char *buf = (char *)malloc(cap);
if (!buf) {
fclose(fp);
return moonbit_make_bytes(0, 0);
}
while (1) {
if (len + 4096 > cap) {
size_t new_cap = cap * 2;
char *new_buf = (char *)realloc(buf, new_cap);
if (!new_buf) {
break;
}
buf = new_buf;
cap = new_cap;
}
size_t n = fread(buf + len, 1, 4096, fp);
len += n;
if (n < 4096) {
break;
}
}
fclose(fp);
moonbit_bytes_t res = moonbit_make_bytes((int32_t)len, 0);
if (len > 0) {
memcpy(res, buf, len);
}
free(buf);
return res;
}
+262
View File
@@ -0,0 +1,262 @@
///|
#derive(Eq, Debug)
pub struct OsRelease {
pretty_name : String
id : String
name : String
version_id : String
}
///|
#derive(Eq, Debug)
pub struct CpuInfo {
model : String
cores : Int32
mhz : String
}
///|
#derive(Eq, Debug)
pub struct MemInfo {
total_kib : UInt64
available_kib : UInt64
used_kib : UInt64
}
///|
pub fn trim_quotes(s : String) -> String {
let trimmed = s.trim().to_owned()
if trimmed.length() >= 2 {
if (trimmed.has_prefix("\"") && trimmed.has_suffix("\"")) ||
(trimmed.has_prefix("'") && trimmed.has_suffix("'")) {
return trimmed.unsafe_substring(start=1, end=trimmed.length() - 1)
}
}
trimmed
}
///|
pub fn parse_os_release(content : String) -> OsRelease {
let mut pretty_name = ""
let mut id = ""
let mut name = ""
let mut version_id = ""
for line_view in content.split("\n") {
let line = line_view.trim().to_owned()
if line.is_empty() || line.has_prefix("#") {
continue
}
match line.find("=") {
Some(idx) => {
let key = line.unsafe_substring(start=0, end=idx).trim().to_owned()
let val = trim_quotes(
line.unsafe_substring(start=idx + 1, end=line.length()),
)
match key {
"PRETTY_NAME" => pretty_name = val
"ID" => id = val.to_lower()
"NAME" => name = val
"VERSION_ID" => version_id = val
_ => ()
}
}
None => ()
}
}
if pretty_name.is_empty() && !name.is_empty() {
pretty_name = if version_id.is_empty() {
name
} else {
"\{name} \{version_id}"
}
}
{ pretty_name, id, name, version_id, }
}
///|
pub fn parse_uint64_str(s : String) -> UInt64 {
let mut acc : UInt64 = 0UL
let mut started = false
for ch in s {
if ch >= '0' && ch <= '9' {
started = true
acc = acc * 10UL + (ch.to_int() - '0'.to_int()).to_uint64()
} else if started {
break
}
}
acc
}
///|
pub fn parse_int_str(s : String) -> Int32 {
parse_uint64_str(s).to_int()
}
///|
pub fn parse_cpuinfo(content : String) -> CpuInfo {
let mut model = ""
let mut cores = 0
let mut mhz = ""
for line_view in content.split("\n") {
let line = line_view.trim().to_owned()
if line.is_empty() {
continue
}
match line.find(":") {
Some(idx) => {
let key = line.unsafe_substring(start=0, end=idx).trim().to_owned()
let val = line
.unsafe_substring(start=idx + 1, end=line.length())
.trim()
.to_owned()
match key {
"processor" => cores += 1
"model name" | "Hardware" | "Processor" =>
if model.is_empty() {
model = val
}
"cpu MHz" => if mhz.is_empty() { mhz = val }
_ => ()
}
}
None => ()
}
}
if cores == 0 && !model.is_empty() {
cores = 1
}
{ model, cores, mhz, }
}
///|
pub fn parse_meminfo(content : String) -> MemInfo {
let mut total_kib : UInt64 = 0UL
let mut free_kib : UInt64 = 0UL
let mut available_kib : UInt64 = 0UL
let mut buffers_kib : UInt64 = 0UL
let mut cached_kib : UInt64 = 0UL
let mut has_available = false
for line_view in content.split("\n") {
let line = line_view.trim().to_owned()
match line.find(":") {
Some(idx) => {
let key = line.unsafe_substring(start=0, end=idx).trim().to_owned()
let val_str = line
.unsafe_substring(start=idx + 1, end=line.length())
.trim()
.to_owned()
let val = parse_uint64_str(val_str)
match key {
"MemTotal" => total_kib = val
"MemFree" => free_kib = val
"MemAvailable" => {
available_kib = val
has_available = true
}
"Buffers" => buffers_kib = val
"Cached" => cached_kib = val
_ => ()
}
}
None => ()
}
}
if !has_available {
available_kib = free_kib + buffers_kib + cached_kib
}
let used_kib = if total_kib >= available_kib {
total_kib - available_kib
} else {
0UL
}
{ total_kib, available_kib, used_kib, }
}
///|
pub fn parse_uptime_seconds(content : String) -> Int32 {
let trimmed = content.trim().to_owned()
let mut secs = 0
for ch in trimmed {
if ch >= '0' && ch <= '9' {
secs = secs * 10 + (ch.to_int() - '0'.to_int())
} else {
break
}
}
secs
}
///|
pub fn format_uptime(total_secs : Int32) -> String {
if total_secs < 60 {
return "\{total_secs} secs"
}
let days = total_secs / 86400
let hours = total_secs % 86400 / 3600
let mins = total_secs % 3600 / 60
let parts : Array[String] = []
if days > 0 {
parts.push(if days == 1 { "1 day" } else { "\{days} days" })
}
if hours > 0 {
parts.push(if hours == 1 { "1 hour" } else { "\{hours} hours" })
}
if mins > 0 || parts.is_empty() {
parts.push(if mins == 1 { "1 min" } else { "\{mins} mins" })
}
parts.join(", ")
}
///|
fn format_two_decimals(hundredths : UInt64) -> String {
let whole = hundredths / 100UL
let frac = hundredths % 100UL
let frac_str = if frac < 10UL { "0\{frac}" } else { "\{frac}" }
"\{whole}.\{frac_str}"
}
///|
pub fn format_bytes_human(bytes : UInt64) -> String {
let gib : UInt64 = 1073741824UL
let mib : UInt64 = 1048576UL
if bytes >= gib {
let hundredths = bytes * 100UL / gib
"\{format_two_decimals(hundredths)} GiB"
} else {
let hundredths = bytes * 100UL / mib
"\{format_two_decimals(hundredths)} MiB"
}
}
///|
pub fn format_usage(used_bytes : UInt64, total_bytes : UInt64) -> String {
if total_bytes == 0UL {
return "Unknown"
}
let pct = used_bytes * 100UL / total_bytes
"\{format_bytes_human(used_bytes)} / \{format_bytes_human(total_bytes)} (\{pct}%)"
}
///|
pub fn count_dpkg_installed(content : String) -> Int32 {
let mut count = 0
for line_view in content.split("\n") {
let line = line_view.trim().to_owned()
if line == "Status: install ok installed" {
count += 1
}
}
count
}
///|
pub fn count_apk_installed(content : String) -> Int32 {
let mut count = 0
for line_view in content.split("\n") {
if line_view.has_prefix("P:") {
count += 1
}
}
count
}
+141
View File
@@ -0,0 +1,141 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/moonfetch"
import {
"moonbitlang/core/debug",
}
// Values
pub fn available_logos() -> Array[String]
pub fn collect_system_info() -> SystemInfo
pub fn count_apk_installed(String) -> Int32
pub fn count_dpkg_installed(String) -> Int32
pub fn default_structure() -> Array[String]
pub fn detect_logo_name(String) -> String
pub fn escape_json_string(String) -> String
pub fn format_bytes_human(UInt64) -> String
pub fn format_uptime(Int32) -> String
pub fn format_usage(UInt64, UInt64) -> String
pub fn get_logo(String) -> Logo
pub fn help_text() -> String
pub fn pad_right_visible(String, Int32) -> String
pub fn parse_args(Array[String]) -> CliOptions
pub fn parse_config_content(String, CliOptions) -> CliOptions
pub fn parse_cpuinfo(String) -> CpuInfo
pub fn parse_int_str(String) -> Int32
pub fn parse_meminfo(String) -> MemInfo
pub fn parse_os_release(String) -> OsRelease
pub fn parse_structure(String) -> Array[String]
pub fn parse_uint64_str(String) -> UInt64
pub fn parse_uptime_seconds(String) -> Int32
pub fn render_colors_bar(Bool) -> Array[String]
pub fn render_fetch(SystemInfo, CliOptions) -> String
pub fn render_info_lines(SystemInfo, Array[String], String, Bool) -> Array[String]
pub fn resolve_options(Array[String]) -> CliOptions
pub fn trim_quotes(String) -> String
pub fn version_text() -> String
pub fn visible_len(String) -> Int32
// Errors
// Types and methods
#derive(Eq, @debug.Debug)
pub struct CliOptions {
show_help : Bool
show_version : Bool
logo : String?
no_logo : Bool
json : Bool
no_color : Bool
structure : Array[String]
config_path : String?
error : String?
}
pub fn CliOptions::default() -> Self
#derive(Eq, @debug.Debug)
pub struct CpuInfo {
model : String
cores : Int32
mhz : String
}
pub struct Logo {
name : String
primary_color : String
secondary_color : String
lines : Array[String]
}
#derive(Eq, @debug.Debug)
pub struct MemInfo {
total_kib : UInt64
available_kib : UInt64
used_kib : UInt64
}
#derive(Eq, @debug.Debug)
pub struct OsRelease {
pretty_name : String
id : String
name : String
version_id : String
}
pub(all) struct SystemInfo {
username : String
hostname : String
os_id : String
os_name : String
host_model : String
kernel : String
arch : String
uptime : String
uptime_secs : Int32
packages : String
shell : String
terminal : String
de_wm : String
cpu : String
memory : String
mem_used_kib : UInt64
mem_total_kib : UInt64
disk : String
disk_used_bytes : UInt64
disk_total_bytes : UInt64
local_ip : String
locale : String
}
pub fn SystemInfo::to_json(Self) -> String
// Type aliases
// Traits
+171
View File
@@ -0,0 +1,171 @@
///|
pub fn visible_len(s : String) -> Int32 {
let mut count = 0
let mut in_esc = false
for ch in s {
if in_esc {
if (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') {
in_esc = false
}
} else if ch == '\u001b' {
in_esc = true
} else {
count += 1
}
}
count
}
///|
pub fn pad_right_visible(s : String, target_width : Int32) -> String {
let vlen = visible_len(s)
if vlen >= target_width {
return s
}
let buf = StringBuilder()
buf.write_string(s)
for _ in 0..<(target_width - vlen) {
buf.write_char(' ')
}
buf.to_string()
}
///|
fn colorize(text : String, ansi : String, no_color : Bool) -> String {
if no_color || ansi.is_empty() {
text
} else {
"\{ansi}\{text}\u001b[0m"
}
}
///|
pub fn render_colors_bar(no_color : Bool) -> Array[String] {
if no_color {
return ["[0][1][2][3][4][5][6][7]", "[8][9][A][B][C][D][E][F]"]
}
let row1 = StringBuilder()
let row2 = StringBuilder()
for i in 0..<8 {
let c1 = 30 + i
let c2 = 90 + i
row1.write_string("\u001b[\{c1}m███\u001b[0m")
row2.write_string("\u001b[\{c2}m███\u001b[0m")
}
[row1.to_string(), row2.to_string()]
}
///|
fn format_kv(
label : String,
value : String,
accent : String,
no_color : Bool,
) -> String {
let key = colorize("\{label}:", accent, no_color)
"\{key} \{value}"
}
///|
pub fn render_info_lines(
info : SystemInfo,
structure : Array[String],
accent : String,
no_color : Bool,
) -> Array[String] {
let lines : Array[String] = []
let bold_accent = if accent.is_empty() { "\u001b[1;36m" } else { accent }
for mod_name in structure {
match mod_name {
"title" => {
let user = colorize(info.username, bold_accent, no_color)
let host = colorize(info.hostname, bold_accent, no_color)
lines.push("\{user}@\{host}")
}
"separator" => {
let total = info.username.length() + 1 + info.hostname.length()
let buf = StringBuilder()
for _ in 0..<total {
buf.write_char('-')
}
lines.push(buf.to_string())
}
"os" => lines.push(format_kv("OS", info.os_name, bold_accent, no_color))
"host" =>
lines.push(format_kv("Host", info.host_model, bold_accent, no_color))
"kernel" =>
lines.push(format_kv("Kernel", info.kernel, bold_accent, no_color))
"uptime" =>
lines.push(format_kv("Uptime", info.uptime, bold_accent, no_color))
"packages" =>
lines.push(format_kv("Packages", info.packages, bold_accent, no_color))
"shell" =>
lines.push(format_kv("Shell", info.shell, bold_accent, no_color))
"terminal" =>
lines.push(format_kv("Terminal", info.terminal, bold_accent, no_color))
"de" | "wm" | "de/wm" =>
lines.push(format_kv("DE/WM", info.de_wm, bold_accent, no_color))
"cpu" => lines.push(format_kv("CPU", info.cpu, bold_accent, no_color))
"memory" | "mem" =>
lines.push(format_kv("Memory", info.memory, bold_accent, no_color))
"disk" =>
lines.push(format_kv("Disk (/)", info.disk, bold_accent, no_color))
"localip" | "ip" =>
lines.push(format_kv("Local IP", info.local_ip, bold_accent, no_color))
"locale" =>
lines.push(format_kv("Locale", info.locale, bold_accent, no_color))
"break" => lines.push("")
"colors" => {
let bars = render_colors_bar(no_color)
for b in bars {
lines.push(b)
}
}
_ => ()
}
}
lines
}
///|
pub fn render_fetch(info : SystemInfo, opts : CliOptions) -> String {
if opts.json {
return info.to_json()
}
let logo_name = match opts.logo {
Some(name) => name
None => detect_logo_name(info.os_id)
}
let logo = get_logo(logo_name)
let info_lines = render_info_lines(
info,
opts.structure,
logo.primary_color,
opts.no_color,
)
if opts.no_logo {
return info_lines.join("\n")
}
let mut logo_width = 0
for l in logo.lines {
let w = visible_len(l)
if w > logo_width {
logo_width = w
}
}
let gap = 3
let total_rows = if logo.lines.length() > info_lines.length() {
logo.lines.length()
} else {
info_lines.length()
}
let out : Array[String] = []
for i in 0..<total_rows {
let left_raw = if i < logo.lines.length() { logo.lines[i] } else { "" }
let left_padded = pad_right_visible(left_raw, logo_width + gap)
let left_colored = colorize(left_padded, logo.primary_color, opts.no_color)
let right = if i < info_lines.length() { info_lines[i] } else { "" }
out.push("\{left_colored}\{right}")
}
out.join("\n")
}
+454
View File
@@ -0,0 +1,454 @@
///|
extern "C" fn moonfetch_uname_info_ffi() -> Bytes = "moonfetch_uname_info"
///|
extern "C" fn moonfetch_get_username_ffi() -> Bytes = "moonfetch_get_username"
///|
#borrow(path)
extern "C" fn moonfetch_get_disk_usage_ffi(path : Bytes) -> Bytes = "moonfetch_get_disk_usage"
///|
extern "C" fn moonfetch_get_term_size_ffi() -> Bytes = "moonfetch_get_term_size"
///|
extern "C" fn moonfetch_get_local_ip_ffi() -> Bytes = "moonfetch_get_local_ip"
///|
#borrow(cmd)
extern "C" fn moonfetch_popen_first_line_ffi(cmd : Bytes) -> Bytes = "moonfetch_popen_first_line"
///|
#borrow(path)
extern "C" fn moonfetch_read_file_stream_ffi(path : Bytes) -> Bytes = "moonfetch_read_file_stream"
///|
fn to_c_bytes(s : String) -> Bytes {
@utf8.encode(s) + Bytes::make(1, (0).to_byte())
}
///|
fn from_c_bytes(b : Bytes) -> String {
@utf8.decode_lossy(b)
}
///|
fn try_read_file(path : String) -> String? {
if !@fs.path_exists(path) {
return None
}
let bytes = moonfetch_read_file_stream_ffi(to_c_bytes(path))
if bytes.length() == 0 {
None
} else {
Some(@utf8.decode_lossy(bytes))
}
}
///|
fn read_trimmed_file(path : String) -> String {
match try_read_file(path) {
Some(s) => s.trim().to_owned()
None => ""
}
}
///|
pub(all) struct SystemInfo {
username : String
hostname : String
os_id : String
os_name : String
host_model : String
kernel : String
arch : String
uptime : String
uptime_secs : Int32
packages : String
shell : String
terminal : String
de_wm : String
cpu : String
memory : String
mem_used_kib : UInt64
mem_total_kib : UInt64
disk : String
disk_used_bytes : UInt64
disk_total_bytes : UInt64
local_ip : String
locale : String
}
///|
fn basename(path : String) -> String {
let parts : Array[String] = []
for p in path.split("/") {
let s = p.to_owned()
if !s.is_empty() {
parts.push(s)
}
}
if parts.is_empty() {
path
} else {
parts[parts.length() - 1]
}
}
///|
fn detect_packages() -> String {
let counts : Array[String] = []
match try_read_file("/var/lib/dpkg/status") {
Some(content) => {
let n = count_dpkg_installed(content)
if n > 0 {
counts.push("\{n} (dpkg)")
}
}
None => ()
}
match try_read_file("/lib/apk/db/installed") {
Some(content) => {
let n = count_apk_installed(content)
if n > 0 {
counts.push("\{n} (apk)")
}
}
None => ()
}
if counts.is_empty() && @fs.path_exists("/var/lib/pacman/local") {
try {
let entries = @fs.read_dir("/var/lib/pacman/local")
let mut n = 0
for e in entries {
if e != "ALPM_DB_VERSION" {
n += 1
}
}
if n > 0 {
counts.push("\{n} (pacman)")
}
} catch {
_ => ()
}
}
if counts.is_empty() {
"Unknown"
} else {
counts.join(", ")
}
}
///|
fn detect_host_model() -> String {
let prod = read_trimmed_file("/sys/devices/virtual/dmi/id/product_name")
let ver = read_trimmed_file("/sys/devices/virtual/dmi/id/product_version")
let vendor = read_trimmed_file("/sys/devices/virtual/dmi/id/sys_vendor")
if !prod.is_empty() && prod != "None" {
if !ver.is_empty() && ver != "None" && ver != prod {
return "\{prod} (\{ver})"
}
return prod
}
if !vendor.is_empty() && vendor != "None" {
return vendor
}
let dt_model = read_trimmed_file("/proc/device-tree/model")
if !dt_model.is_empty() {
return dt_model
}
if @fs.path_exists("/.dockerenv") {
return "Docker Container"
}
"Linux VM / Host"
}
///|
fn detect_shell() -> String {
match @env.get_env_var("SHELL") {
Some(sh) => {
let name = basename(sh)
if name == "bash" {
let ver = from_c_bytes(
moonfetch_popen_first_line_ffi(
to_c_bytes("bash --version 2>/dev/null | head -n1"),
),
)
match ver.find("version ") {
Some(idx) => {
let rest = ver.unsafe_substring(start=idx + 8, end=ver.length())
match rest.find("(") {
Some(p) =>
"bash " +
rest.unsafe_substring(start=0, end=p).trim().to_owned()
None => "bash"
}
}
None => "bash"
}
} else {
name
}
}
None => "Unknown"
}
}
///|
fn detect_terminal() -> String {
let term_prog = match @env.get_env_var("TERM_PROGRAM") {
Some(v) => v
None =>
match @env.get_env_var("TERM") {
Some(v) => v
None => "Unknown"
}
}
let size_raw = from_c_bytes(moonfetch_get_term_size_ffi())
if size_raw.is_empty() {
term_prog
} else {
match size_raw.find(",") {
Some(idx) => {
let cols = size_raw.unsafe_substring(start=0, end=idx)
let rows = size_raw.unsafe_substring(
start=idx + 1,
end=size_raw.length(),
)
"\{term_prog} (\{cols}x\{rows})"
}
None => term_prog
}
}
}
///|
fn detect_de_wm() -> String {
match @env.get_env_var("XDG_CURRENT_DESKTOP") {
Some(v) => if !v.is_empty() { return v }
None => ()
}
match @env.get_env_var("DESKTOP_SESSION") {
Some(v) => if !v.is_empty() { return v }
None => ()
}
match @env.get_env_var("WAYLAND_DISPLAY") {
Some(v) => if !v.is_empty() { return "Wayland (\{v})" }
None => ()
}
match @env.get_env_var("DISPLAY") {
Some(v) => if !v.is_empty() { return "X11 (\{v})" }
None => ()
}
"Headless / TTY"
}
///|
fn detect_locale() -> String {
match @env.get_env_var("LC_ALL") {
Some(v) => if !v.is_empty() { return v }
None => ()
}
match @env.get_env_var("LANG") {
Some(v) => if !v.is_empty() { return v }
None => ()
}
"C"
}
///|
pub fn collect_system_info() -> SystemInfo {
let uname_raw = from_c_bytes(moonfetch_uname_info_ffi())
let uname_parts : Array[String] = []
for part in uname_raw.split("\n") {
uname_parts.push(part.to_owned())
}
let sysname = if uname_parts.length() > 0 { uname_parts[0] } else { "Linux" }
let nodename = if uname_parts.length() > 1 {
uname_parts[1]
} else {
"localhost"
}
let release = if uname_parts.length() > 2 { uname_parts[2] } else { "" }
let arch = if uname_parts.length() > 3 { uname_parts[3] } else { "" }
let username = from_c_bytes(moonfetch_get_username_ffi())
let os_rel = match try_read_file("/etc/os-release") {
Some(c) => parse_os_release(c)
None =>
{ pretty_name: sysname, id: "linux", name: sysname, version_id: "", }
}
let os_name = if os_rel.pretty_name.is_empty() {
"\{sysname} \{arch}"
} else if arch.is_empty() {
os_rel.pretty_name
} else {
"\{os_rel.pretty_name} \{arch}"
}
let kernel = if release.is_empty() {
sysname
} else {
"\{sysname} \{release}"
}
let uptime_secs = match try_read_file("/proc/uptime") {
Some(c) => parse_uptime_seconds(c)
None => 0
}
let uptime = format_uptime(uptime_secs)
let cpu_parsed = match try_read_file("/proc/cpuinfo") {
Some(c) => parse_cpuinfo(c)
None => { model: "Unknown CPU", cores: 1, mhz: "", }
}
let cpu = if cpu_parsed.model.is_empty() {
"Unknown (\{cpu_parsed.cores} cores)"
} else {
"\{cpu_parsed.model} (\{cpu_parsed.cores})"
}
let mem_parsed = match try_read_file("/proc/meminfo") {
Some(c) => parse_meminfo(c)
None => { total_kib: 0UL, available_kib: 0UL, used_kib: 0UL, }
}
let memory = format_usage(
mem_parsed.used_kib * 1024UL,
mem_parsed.total_kib * 1024UL,
)
let disk_raw = from_c_bytes(moonfetch_get_disk_usage_ffi(to_c_bytes("/")))
let mut disk_used_bytes : UInt64 = 0UL
let mut disk_total_bytes : UInt64 = 0UL
match disk_raw.find(",") {
Some(idx) => {
disk_used_bytes = parse_uint64_str(
disk_raw.unsafe_substring(start=0, end=idx),
)
disk_total_bytes = parse_uint64_str(
disk_raw.unsafe_substring(start=idx + 1, end=disk_raw.length()),
)
}
None => ()
}
let disk = format_usage(disk_used_bytes, disk_total_bytes)
let local_ip_raw = from_c_bytes(moonfetch_get_local_ip_ffi())
let local_ip = if local_ip_raw.is_empty() { "None" } else { local_ip_raw }
{
username,
hostname: nodename,
os_id: os_rel.id,
os_name,
host_model: detect_host_model(),
kernel,
arch,
uptime,
uptime_secs,
packages: detect_packages(),
shell: detect_shell(),
terminal: detect_terminal(),
de_wm: detect_de_wm(),
cpu,
memory,
mem_used_kib: mem_parsed.used_kib,
mem_total_kib: mem_parsed.total_kib,
disk,
disk_used_bytes,
disk_total_bytes,
local_ip,
locale: detect_locale(),
}
}
///|
pub fn escape_json_string(s : String) -> String {
let buf = StringBuilder()
for ch in s {
match ch {
'"' => buf.write_string("\\\"")
'\\' => buf.write_string("\\\\")
'\n' => buf.write_string("\\n")
'\r' => buf.write_string("\\r")
'\t' => buf.write_string("\\t")
_ => buf.write_char(ch)
}
}
buf.to_string()
}
///|
pub fn SystemInfo::to_json(self : SystemInfo) -> String {
let e = escape_json_string
let lines = [
"{",
" \"username\": \"\{e(self.username)}\",",
" \"hostname\": \"\{e(self.hostname)}\",",
" \"os_id\": \"\{e(self.os_id)}\",",
" \"os\": \"\{e(self.os_name)}\",",
" \"host\": \"\{e(self.host_model)}\",",
" \"kernel\": \"\{e(self.kernel)}\",",
" \"arch\": \"\{e(self.arch)}\",",
" \"uptime\": \"\{e(self.uptime)}\",",
" \"uptime_secs\": \{self.uptime_secs},",
" \"packages\": \"\{e(self.packages)}\",",
" \"shell\": \"\{e(self.shell)}\",",
" \"terminal\": \"\{e(self.terminal)}\",",
" \"de_wm\": \"\{e(self.de_wm)}\",",
" \"cpu\": \"\{e(self.cpu)}\",",
" \"memory\": \"\{e(self.memory)}\",",
" \"mem_used_kib\": \{self.mem_used_kib},",
" \"mem_total_kib\": \{self.mem_total_kib},",
" \"disk\": \"\{e(self.disk)}\",",
" \"disk_used_bytes\": \{self.disk_used_bytes},",
" \"disk_total_bytes\": \{self.disk_total_bytes},",
" \"local_ip\": \"\{e(self.local_ip)}\",",
" \"locale\": \"\{e(self.locale)}\"",
"}",
]
lines.join("\n")
}
///|
pub fn resolve_options(args : Array[String]) -> CliOptions {
let cli_opts = parse_args(args)
match cli_opts.error {
Some(_) => return cli_opts
None => ()
}
match cli_opts.config_path {
Some(path) =>
match try_read_file(path) {
Some(content) => {
let from_cfg = parse_config_content(content, CliOptions::default())
let mut merged = from_cfg
let cli_only = parse_args(args)
if cli_only.show_help {
merged = { ..merged, show_help: true, }
}
if cli_only.show_version {
merged = { ..merged, show_version: true, }
}
if cli_only.no_logo {
merged = { ..merged, no_logo: true, }
}
if cli_only.json {
merged = { ..merged, json: true, }
}
if cli_only.no_color {
merged = { ..merged, no_color: true, }
}
match cli_only.logo {
Some(l) => merged = { ..merged, logo: Some(l), }
None => ()
}
if cli_only.structure != default_structure() {
merged = { ..merged, structure: cli_only.structure, }
}
{ ..merged, config_path: Some(path), }
}
None => { ..cli_opts, error: Some("Config file not found: \{path}"), }
}
None => cli_opts
}
}