Compare commits
30 Commits
6eddd02fb4
...
release/0.
| Author | SHA1 | Date | |
|---|---|---|---|
| 1d9342186a | |||
| f6a84416e6 | |||
| 01a7bd44b7 | |||
| f123f2d6df | |||
| 94ff632b39 | |||
| f09dbc8321 | |||
| 4e5c0e3b07 | |||
| 7aa45974a7 | |||
| 14f1be5a2a | |||
| 49eac25d48 | |||
| 0ce858da5c | |||
| 3459c67377 | |||
| 84945b9d83 | |||
| 0c217c5129 | |||
| 7b2217886c | |||
| 68cd6543b3 | |||
| 6c8fc7268b | |||
| 93c5c30021 | |||
| 53902af934 | |||
| 7a7ae1ffdb | |||
| f413d5e2eb | |||
| e72fdd9fcb | |||
| 7aa12f1a31 | |||
| d52422d839 | |||
| a274938368 | |||
| 253c69363d | |||
| ac7b67748d | |||
| 8cee54007f | |||
| 361df64b04 | |||
| 0baf53b1eb |
@@ -19,6 +19,7 @@ jobs:
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
cache: false
|
||||
|
||||
- name: Get Version
|
||||
id: get_version
|
||||
@@ -31,30 +32,39 @@ jobs:
|
||||
echo "TAG=v$VERSION" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Build
|
||||
run: cargo build --release
|
||||
- name: Check if Release Exists
|
||||
id: check_release
|
||||
shell: bash
|
||||
run: |
|
||||
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" \
|
||||
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
|
||||
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/tags/${{ steps.get_version.outputs.TAG }}")
|
||||
|
||||
if [ "$HTTP_STATUS" = "200" ]; then
|
||||
echo "EXISTS=true" >> $GITHUB_OUTPUT
|
||||
echo "Release already exists for tag ${{ steps.get_version.outputs.TAG }}. Skipping creation."
|
||||
else
|
||||
echo "EXISTS=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Create Release
|
||||
id: create_release
|
||||
uses: https://github.com/actions/create-release@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Build
|
||||
if: steps.check_release.outputs.EXISTS == 'false'
|
||||
run: |
|
||||
cargo build --release
|
||||
mv target/release/mould target/release/mould-${{ steps.get_version.outputs.TAG }}-linux-amd64
|
||||
|
||||
- name: Create Release and Upload Asset
|
||||
if: steps.check_release.outputs.EXISTS == 'false'
|
||||
uses: https://github.com/softprops/action-gh-release@v1
|
||||
with:
|
||||
tag_name: ${{ steps.get_version.outputs.TAG }}
|
||||
release_name: Release ${{ steps.get_version.outputs.TAG }}
|
||||
name: Release ${{ steps.get_version.outputs.TAG }}
|
||||
body: |
|
||||
Automated release for version ${{ steps.get_version.outputs.VERSION }}
|
||||
Commit: ${{ github.sha }}
|
||||
Branch: ${{ github.ref_name }}
|
||||
files: target/release/mould-${{ steps.get_version.outputs.TAG }}-linux-amd64
|
||||
draft: false
|
||||
prerelease: false
|
||||
|
||||
- name: Upload Release Asset
|
||||
uses: https://github.com/actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
||||
asset_path: ./target/release/cenv
|
||||
asset_name: cenv-${{ steps.get_version.outputs.TAG }}-linux-amd64
|
||||
asset_content_type: application/octet-stream
|
||||
|
||||
35
.gitea/workflows/version-check.yaml
Normal file
35
.gitea/workflows/version-check.yaml
Normal file
@@ -0,0 +1,35 @@
|
||||
name: Version Check
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- 'Cargo.toml'
|
||||
|
||||
jobs:
|
||||
check-version:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Compare versions
|
||||
shell: bash
|
||||
run: |
|
||||
NEW_VERSION=$(grep -m 1 '^version =' Cargo.toml | cut -d '"' -f 2)
|
||||
|
||||
git fetch origin ${{ github.base_ref }}
|
||||
OLD_VERSION=$(git show origin/${{ github.base_ref }}:Cargo.toml | grep -m 1 '^version =' | cut -d '"' -f 2)
|
||||
|
||||
echo "Old version (main): $OLD_VERSION"
|
||||
echo "New version (PR): $NEW_VERSION"
|
||||
|
||||
if [ "$NEW_VERSION" = "$OLD_VERSION" ]; then
|
||||
echo "Error: Cargo.toml version has not been updated in this PR!"
|
||||
exit 1
|
||||
else
|
||||
echo "Success: Version updated from $OLD_VERSION to $NEW_VERSION"
|
||||
fi
|
||||
249
Cargo.lock
generated
249
Cargo.lock
generated
@@ -17,6 +17,80 @@ version = "0.2.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
|
||||
|
||||
[[package]]
|
||||
name = "anstream"
|
||||
version = "0.6.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"anstyle-parse 0.2.7",
|
||||
"anstyle-query",
|
||||
"anstyle-wincon",
|
||||
"colorchoice",
|
||||
"is_terminal_polyfill",
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstream"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"anstyle-parse 1.0.0",
|
||||
"anstyle-query",
|
||||
"anstyle-wincon",
|
||||
"colorchoice",
|
||||
"is_terminal_polyfill",
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle"
|
||||
version = "1.0.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-parse"
|
||||
version = "0.2.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2"
|
||||
dependencies = [
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-parse"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
|
||||
dependencies = [
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-query"
|
||||
version = "1.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
|
||||
dependencies = [
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-wincon"
|
||||
version = "3.0.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"once_cell_polyfill",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anyhow"
|
||||
version = "1.0.102"
|
||||
@@ -101,18 +175,6 @@ dependencies = [
|
||||
"rustversion",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cenv-rs"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"crossterm",
|
||||
"dirs",
|
||||
"ratatui",
|
||||
"serde",
|
||||
"tempfile",
|
||||
"toml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.4"
|
||||
@@ -125,6 +187,52 @@ version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b193af5b67834b676abd72466a96c1024e6a6ad978a1f484bd90b85c94041351"
|
||||
dependencies = [
|
||||
"clap_builder",
|
||||
"clap_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_builder"
|
||||
version = "4.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f"
|
||||
dependencies = [
|
||||
"anstream 1.0.0",
|
||||
"anstyle",
|
||||
"clap_lex",
|
||||
"strsim",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_derive"
|
||||
version = "4.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1110bd8a634a1ab8cb04345d8d878267d57c3cf1b38d91b71af6686408bbca6a"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_lex"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
|
||||
|
||||
[[package]]
|
||||
name = "colorchoice"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
|
||||
|
||||
[[package]]
|
||||
name = "compact_str"
|
||||
version = "0.9.0"
|
||||
@@ -321,6 +429,29 @@ version = "1.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
|
||||
|
||||
[[package]]
|
||||
name = "env_filter"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7a1c3cc8e57274ec99de65301228b537f1e4eedc1b8e0f9411c6caac8ae7308f"
|
||||
dependencies = [
|
||||
"log",
|
||||
"regex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "env_logger"
|
||||
version = "0.11.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b2daee4ea451f429a58296525ddf28b45a3b64f1acf6587e2067437bb11e218d"
|
||||
dependencies = [
|
||||
"anstream 0.6.21",
|
||||
"anstyle",
|
||||
"env_filter",
|
||||
"jiff",
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.2"
|
||||
@@ -527,6 +658,12 @@ dependencies = [
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "is_terminal_polyfill"
|
||||
version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.14.0"
|
||||
@@ -542,6 +679,30 @@ version = "1.0.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
|
||||
|
||||
[[package]]
|
||||
name = "jiff"
|
||||
version = "0.2.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1a3546dc96b6d42c5f24902af9e2538e82e39ad350b0c766eb3fbf2d8f3d8359"
|
||||
dependencies = [
|
||||
"jiff-static",
|
||||
"log",
|
||||
"portable-atomic",
|
||||
"portable-atomic-util",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jiff-static"
|
||||
version = "0.2.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2a8c8b344124222efd714b73bb41f8b5120b27a7cc1c75593a6ff768d9d05aa4"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.91"
|
||||
@@ -690,6 +851,26 @@ dependencies = [
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mould"
|
||||
version = "0.4.2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
"crossterm",
|
||||
"dirs",
|
||||
"env_logger",
|
||||
"log",
|
||||
"ratatui",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_yaml",
|
||||
"tempfile",
|
||||
"thiserror 2.0.18",
|
||||
"toml",
|
||||
"tui-input",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nix"
|
||||
version = "0.29.0"
|
||||
@@ -754,6 +935,12 @@ version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "once_cell_polyfill"
|
||||
version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
||||
|
||||
[[package]]
|
||||
name = "option-ext"
|
||||
version = "0.2.0"
|
||||
@@ -893,6 +1080,15 @@ version = "1.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"
|
||||
|
||||
[[package]]
|
||||
name = "portable-atomic-util"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "091397be61a01d4be58e7841595bd4bfedb15f1cd54977d79b8271e94ed799a3"
|
||||
dependencies = [
|
||||
"portable-atomic",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "powerfmt"
|
||||
version = "0.2.0"
|
||||
@@ -1186,6 +1382,19 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_yaml"
|
||||
version = "0.9.34+deprecated"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"
|
||||
dependencies = [
|
||||
"indexmap",
|
||||
"itoa",
|
||||
"ryu",
|
||||
"serde",
|
||||
"unsafe-libyaml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.10.9"
|
||||
@@ -1471,6 +1680,16 @@ version = "1.0.6+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ab16f14aed21ee8bfd8ec22513f7287cd4a91aa92e44edfe2c17ddd004e92607"
|
||||
|
||||
[[package]]
|
||||
name = "tui-input"
|
||||
version = "0.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "79c1ee964298f136020f5f69e0e601f4d3a1f610a7baf1af9fcb96152e8a2c45"
|
||||
dependencies = [
|
||||
"ratatui",
|
||||
"unicode-width",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.19.0"
|
||||
@@ -1518,6 +1737,12 @@ version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
|
||||
|
||||
[[package]]
|
||||
name = "unsafe-libyaml"
|
||||
version = "0.2.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861"
|
||||
|
||||
[[package]]
|
||||
name = "utf8parse"
|
||||
version = "0.2.2"
|
||||
|
||||
30
Cargo.toml
30
Cargo.toml
@@ -1,19 +1,33 @@
|
||||
[package]
|
||||
name = "cenv-rs"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
authors = ["Nils Pukropp <nils@narl.io>"]
|
||||
|
||||
[[bin]]
|
||||
name = "cenv"
|
||||
name = "mould"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.102"
|
||||
crossterm = "0.29.0"
|
||||
dirs = "6.0.0"
|
||||
env_logger = "0.11.9"
|
||||
log = "0.4.29"
|
||||
ratatui = "0.30.0"
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = "1.0.149"
|
||||
serde_yaml = "0.9.34"
|
||||
thiserror = "2.0.18"
|
||||
toml = "1.0.6"
|
||||
tui-input = "0.15.0"
|
||||
|
||||
[dependencies.clap]
|
||||
features = ["derive"]
|
||||
version = "4.6.0"
|
||||
|
||||
[dependencies.serde]
|
||||
features = ["derive"]
|
||||
version = "1.0.228"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3.27.0"
|
||||
|
||||
[package]
|
||||
authors = ["Nils Pukropp <nils@narl.io>"]
|
||||
edition = "2024"
|
||||
name = "mould"
|
||||
version = "0.4.2"
|
||||
|
||||
2
LICENSE
2
LICENSE
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 The cenv-rs Contributors
|
||||
Copyright (c) 2026 Nils Pukropp <nils@narl.io>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
99
README.md
99
README.md
@@ -1,16 +1,22 @@
|
||||
# cenv-rs
|
||||
# mould
|
||||
|
||||
cenv-rs is a Rust-based Terminal User Interface (TUI) tool designed to help developers interactively generate `.env` files from `.env.example` templates. With a focus on speed and usability, it features Vim-like keybindings and out-of-the-box support for theming, defaulting to the Catppuccin Mocha palette.
|
||||
mould is a modern Terminal User Interface (TUI) tool designed for interactively generating and editing configuration files from templates. Whether you are setting up a `.env` file from an example, creating a `docker-compose.override.yml`, or editing nested `JSON`, `YAML`, or `TOML` configurations, mould provides a fast, Vim-inspired workflow to get your environment ready.
|
||||
|
||||
## Features
|
||||
|
||||
- Parse `.env.example` files to extract keys, default values, and comments.
|
||||
- Vim-like keybindings for quick navigation and editing.
|
||||
- Built-in theming support with Catppuccin Mocha as the default.
|
||||
- Configurable through a standard TOML file.
|
||||
- **Universal Format Support**: Handle `.env`, `JSON`, `YAML`, and `TOML` seamlessly.
|
||||
- **Tree View Navigation**: Edit nested data structures (JSON, YAML, TOML) in a beautiful, depth-colored tree view.
|
||||
- **Smart Template Comparison**: Automatically discovers `.env.example` vs `.env` relationships and highlights missing or modified keys.
|
||||
- **Add Missing Keys**: Instantly pull missing keys and their default values from your template into your active configuration with a single keystroke.
|
||||
- **Neovim Integration**: Comes with a built-in Neovim plugin for seamless in-editor configuration management.
|
||||
- **Docker Compose Integration**: Automatically generate `docker-compose.override.yml` from `docker-compose.yml`.
|
||||
- **Vim-inspired Workflow**: Navigate with `j`/`k`, `gg`/`G`, edit with `i`, search with `/`, and save with `:w`.
|
||||
- **Modern UI**: A polished, rounded interface featuring a semantic Catppuccin Mocha palette.
|
||||
- **Highly Configurable**: Customize keybindings and semantic themes via a simple TOML configuration.
|
||||
|
||||
## Installation
|
||||
|
||||
### CLI Application
|
||||
Ensure you have Rust and Cargo installed, then run:
|
||||
|
||||
```sh
|
||||
@@ -21,42 +27,99 @@ Alternatively, you can build from source:
|
||||
|
||||
```sh
|
||||
git clone <repository_url>
|
||||
cd cenv-rs
|
||||
cd mould
|
||||
cargo build --release
|
||||
```
|
||||
|
||||
### Neovim Plugin
|
||||
If you use a plugin manager like `mini.deps`, you can add the repository directly:
|
||||
|
||||
```lua
|
||||
add({
|
||||
source = 'https://git.narl.io/nvrl/mould-rs',
|
||||
checkout = 'main',
|
||||
})
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Navigate to a directory containing a `.env.example` file and run:
|
||||
Provide an input template file to start editing. `mould` is smart enough to figure out if it's looking at a template or an active file, and will search for its counterpart to provide diffing.
|
||||
|
||||
```sh
|
||||
cenv-rs
|
||||
mould .env.example
|
||||
mould docker-compose.yml
|
||||
mould config.template.json -o config.json
|
||||
```
|
||||
|
||||
### Keybindings
|
||||
### Keybindings (Default)
|
||||
|
||||
- **Normal Mode**
|
||||
- `j` / `Down`: Move selection down
|
||||
- `k` / `Up`: Move selection up
|
||||
- `i`: Edit the value of the currently selected key (Enter Insert Mode)
|
||||
- `:w` or `Enter`: Save the current configuration to `.env`
|
||||
- `q` or `:q`: Quit the application without saving
|
||||
- `Esc`: Clear current prompt or return from actions
|
||||
- `gg`: Jump to the top
|
||||
- `G`: Jump to the bottom
|
||||
- `i`: Edit value (cursor at start)
|
||||
- `A`: Edit value (cursor at end)
|
||||
- `S`: Substitute value (clear and edit)
|
||||
- `o`: Append a new item to the current array
|
||||
- `O`: Prepend a new item to the current array
|
||||
- `dd`: Delete the currently selected variable or group
|
||||
- `u`: Undo the last change
|
||||
- `a`: Add missing value from template to active config
|
||||
- `/`: Search for configuration keys (Jump to matches)
|
||||
- `n`: Jump to the next search match
|
||||
- `N`: Jump to the previous search match
|
||||
- `:w` or `Enter`: Save the current configuration to the output file
|
||||
- `:q` or `q`: Quit the application
|
||||
- `:wq`: Save and quit
|
||||
- `Esc`: Clear current command prompt
|
||||
|
||||
- **Insert Mode**
|
||||
- Type your value for the selected key.
|
||||
- `Esc`: Return to Normal Mode
|
||||
- Arrow keys: Navigate within the input field
|
||||
- `Enter` / `Esc`: Commit the value and return to Normal Mode
|
||||
|
||||
## Configuration
|
||||
|
||||
cenv-rs can be configured using a `config.toml` file located in your user configuration directory (e.g., `~/.config/cenv-rs/config.toml` on Linux/macOS).
|
||||
mould can be configured using a `config.toml` file located in your user configuration directory (e.g., `~/.config/mould/config.toml` on Linux/macOS).
|
||||
|
||||
Example configuration:
|
||||
|
||||
```toml
|
||||
[keybinds]
|
||||
down = "j"
|
||||
up = "k"
|
||||
edit = "i"
|
||||
save = ":w"
|
||||
quit = ":q"
|
||||
normal_mode = "Esc"
|
||||
search = "/"
|
||||
next_match = "n"
|
||||
previous_match = "N"
|
||||
jump_top = "gg"
|
||||
jump_bottom = "G"
|
||||
|
||||
[theme]
|
||||
# Default theme is "catppuccin_mocha"
|
||||
name = "catppuccin_mocha"
|
||||
# Enable transparency to let your terminal background show through
|
||||
transparent = false
|
||||
|
||||
# Custom color palette (Semantic Catppuccin Mocha defaults)
|
||||
bg_normal = "#1e1e2e"
|
||||
bg_highlight = "#89b4fa"
|
||||
bg_active = "#a6e3a1"
|
||||
bg_search = "#cba6f7"
|
||||
fg_normal = "#cdd6f4"
|
||||
fg_dimmed = "#6c7086"
|
||||
fg_highlight = "#1e1e2e"
|
||||
fg_warning = "#f38ba8"
|
||||
fg_modified = "#fab387"
|
||||
fg_accent = "#b4befe"
|
||||
border_normal = "#45475a"
|
||||
border_active = "#a6e3a1"
|
||||
tree_depth_1 = "#b4befe"
|
||||
tree_depth_2 = "#cba6f7"
|
||||
tree_depth_3 = "#89b4fa"
|
||||
tree_depth_4 = "#fab387"
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
47
config.example.toml
Normal file
47
config.example.toml
Normal file
@@ -0,0 +1,47 @@
|
||||
# mould Configuration Example
|
||||
# Place this file at ~/.config/mould/config.toml (Linux/macOS)
|
||||
# or %AppData%\mould\config.toml (Windows)
|
||||
|
||||
[theme]
|
||||
# If true, skip rendering the background block to let the terminal's transparency show.
|
||||
transparent = false
|
||||
|
||||
# Colors are specified in hex format ("#RRGGBB").
|
||||
# Default values follow the Semantic Catppuccin Mocha palette.
|
||||
|
||||
bg_normal = "#1e1e2e"
|
||||
bg_highlight = "#89b4fa"
|
||||
bg_active = "#a6e3a1"
|
||||
bg_search = "#cba6f7"
|
||||
fg_normal = "#cdd6f4"
|
||||
fg_dimmed = "#6c7086"
|
||||
fg_highlight = "#1e1e2e"
|
||||
fg_warning = "#f38ba8"
|
||||
fg_modified = "#fab387"
|
||||
fg_accent = "#b4befe"
|
||||
border_normal = "#45475a"
|
||||
border_active = "#a6e3a1"
|
||||
tree_depth_1 = "#b4befe"
|
||||
tree_depth_2 = "#cba6f7"
|
||||
tree_depth_3 = "#89b4fa"
|
||||
tree_depth_4 = "#fab387"
|
||||
|
||||
[keybinds]
|
||||
# Keybindings for navigation and application control.
|
||||
down = "j"
|
||||
up = "k"
|
||||
edit = "i"
|
||||
edit_append = "A"
|
||||
edit_substitute = "S"
|
||||
save = ":w"
|
||||
quit = ":q"
|
||||
normal_mode = "Esc"
|
||||
search = "/"
|
||||
next_match = "n"
|
||||
previous_match = "N"
|
||||
jump_top = "gg"
|
||||
jump_bottom = "G"
|
||||
append_item = "o"
|
||||
prepend_item = "O"
|
||||
delete_item = "dd"
|
||||
undo = "u"
|
||||
54
lua/mould/init.lua
Normal file
54
lua/mould/init.lua
Normal file
@@ -0,0 +1,54 @@
|
||||
local M = {}
|
||||
|
||||
local function open_floating_terminal(cmd)
|
||||
local buf = vim.api.nvim_create_buf(false, true)
|
||||
local width = math.floor(vim.o.columns * 0.9)
|
||||
local height = math.floor(vim.o.lines * 0.9)
|
||||
local col = math.floor((vim.o.columns - width) / 2)
|
||||
local row = math.floor((vim.o.lines - height) / 2)
|
||||
|
||||
local win_config = {
|
||||
relative = "editor",
|
||||
width = width,
|
||||
height = height,
|
||||
col = col,
|
||||
row = row,
|
||||
style = "minimal",
|
||||
border = "rounded",
|
||||
}
|
||||
|
||||
local win = vim.api.nvim_open_win(buf, true, win_config)
|
||||
|
||||
-- Record the original buffer to reload it later
|
||||
local original_buf = vim.api.nvim_get_current_buf()
|
||||
local original_file = vim.api.nvim_buf_get_name(original_buf)
|
||||
|
||||
vim.fn.termopen(cmd, {
|
||||
on_exit = function()
|
||||
vim.api.nvim_win_close(win, true)
|
||||
vim.api.nvim_buf_delete(buf, { force = true })
|
||||
|
||||
-- Reload the original file if it exists
|
||||
if vim.fn.filereadable(original_file) == 1 then
|
||||
vim.schedule(function()
|
||||
vim.cmd("checktime " .. vim.fn.fnameescape(original_file))
|
||||
end)
|
||||
end
|
||||
end,
|
||||
})
|
||||
|
||||
vim.cmd("startinsert")
|
||||
end
|
||||
|
||||
function M.open()
|
||||
local filepath = vim.api.nvim_buf_get_name(0)
|
||||
if filepath == "" then
|
||||
vim.notify("mould.nvim: Cannot open mould for an unnamed buffer.", vim.log.levels.ERROR)
|
||||
return
|
||||
end
|
||||
|
||||
local cmd = string.format("mould %s", vim.fn.shellescape(filepath))
|
||||
open_floating_terminal(cmd)
|
||||
end
|
||||
|
||||
return M
|
||||
8
plugin/mould.lua
Normal file
8
plugin/mould.lua
Normal file
@@ -0,0 +1,8 @@
|
||||
if vim.g.loaded_mould == 1 then
|
||||
return
|
||||
end
|
||||
vim.g.loaded_mould = 1
|
||||
|
||||
vim.api.nvim_create_user_command("Mould", function()
|
||||
require("mould").open()
|
||||
end, { desc = "Open mould for the current buffer" })
|
||||
342
src/app.rs
342
src/app.rs
@@ -1,35 +1,81 @@
|
||||
use crate::env::EnvVar;
|
||||
use crate::format::ConfigItem;
|
||||
use tui_input::Input;
|
||||
|
||||
/// Represents the current operating mode of the application.
|
||||
pub enum Mode {
|
||||
/// Standard navigation and command mode.
|
||||
Normal,
|
||||
/// Active text entry mode for modifying values.
|
||||
Insert,
|
||||
/// Active search mode for filtering keys.
|
||||
Search,
|
||||
}
|
||||
|
||||
pub enum InsertVariant {
|
||||
Start,
|
||||
End,
|
||||
Substitute,
|
||||
}
|
||||
|
||||
/// The core application state, holding all configuration variables and UI status.
|
||||
pub struct App {
|
||||
pub vars: Vec<EnvVar>,
|
||||
/// The list of configuration variables being edited.
|
||||
pub vars: Vec<ConfigItem>,
|
||||
/// Index of the currently selected variable in the list.
|
||||
pub selected: usize,
|
||||
/// The current interaction mode (Normal or Insert).
|
||||
pub mode: Mode,
|
||||
/// Whether the main application loop should continue running.
|
||||
pub running: bool,
|
||||
/// An optional message to display in the status bar (e.g., "Saved to .env").
|
||||
pub status_message: Option<String>,
|
||||
/// The active text input buffer for the selected variable.
|
||||
pub input: Input,
|
||||
/// The current search query for filtering keys.
|
||||
pub search_query: String,
|
||||
/// Stack of previous variable states for undo functionality.
|
||||
pub undo_stack: Vec<Vec<ConfigItem>>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub fn new(vars: Vec<EnvVar>) -> Self {
|
||||
/// Initializes a new application instance with the provided variables.
|
||||
pub fn new(vars: Vec<ConfigItem>) -> Self {
|
||||
let initial_input = vars.get(0).and_then(|v| v.value.clone()).unwrap_or_default();
|
||||
Self {
|
||||
vars,
|
||||
selected: 0,
|
||||
mode: Mode::Normal,
|
||||
running: true,
|
||||
status_message: None,
|
||||
input: Input::new(initial_input),
|
||||
search_query: String::new(),
|
||||
undo_stack: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the indices of variables that match the search query.
|
||||
pub fn matching_indices(&self) -> Vec<usize> {
|
||||
if self.search_query.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let query = self.search_query.to_lowercase();
|
||||
self.vars
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, v)| v.key.to_lowercase().contains(&query))
|
||||
.map(|(i, _)| i)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Moves the selection to the next variable in the list, wrapping around if necessary.
|
||||
pub fn next(&mut self) {
|
||||
if !self.vars.is_empty() {
|
||||
self.selected = (self.selected + 1) % self.vars.len();
|
||||
self.sync_input_with_selected();
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves the selection to the previous variable in the list, wrapping around if necessary.
|
||||
pub fn previous(&mut self) {
|
||||
if !self.vars.is_empty() {
|
||||
if self.selected == 0 {
|
||||
@@ -37,19 +83,299 @@ impl App {
|
||||
} else {
|
||||
self.selected -= 1;
|
||||
}
|
||||
self.sync_input_with_selected();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn enter_insert(&mut self) {
|
||||
self.mode = Mode::Insert;
|
||||
/// Jumps to the top of the list.
|
||||
pub fn jump_top(&mut self) {
|
||||
if !self.vars.is_empty() {
|
||||
self.selected = 0;
|
||||
self.sync_input_with_selected();
|
||||
}
|
||||
}
|
||||
|
||||
/// Jumps to the bottom of the list.
|
||||
pub fn jump_bottom(&mut self) {
|
||||
if !self.vars.is_empty() {
|
||||
self.selected = self.vars.len() - 1;
|
||||
self.sync_input_with_selected();
|
||||
}
|
||||
}
|
||||
|
||||
/// Jumps to the next variable that matches the search query.
|
||||
pub fn jump_next_match(&mut self) {
|
||||
let indices = self.matching_indices();
|
||||
if indices.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let next_match = indices
|
||||
.iter()
|
||||
.find(|&&i| i > self.selected)
|
||||
.or_else(|| indices.first());
|
||||
|
||||
if let Some(&index) = next_match {
|
||||
self.selected = index;
|
||||
self.sync_input_with_selected();
|
||||
}
|
||||
}
|
||||
|
||||
/// Jumps to the previous variable that matches the search query.
|
||||
pub fn jump_previous_match(&mut self) {
|
||||
let indices = self.matching_indices();
|
||||
if indices.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let prev_match = indices
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|&&i| i < self.selected)
|
||||
.or_else(|| indices.last());
|
||||
|
||||
if let Some(&index) = prev_match {
|
||||
self.selected = index;
|
||||
self.sync_input_with_selected();
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates the input buffer to reflect the value of the currently selected variable.
|
||||
pub fn sync_input_with_selected(&mut self) {
|
||||
if let Some(var) = self.vars.get(self.selected) {
|
||||
let val = var.value.clone().unwrap_or_default();
|
||||
self.input = Input::new(val);
|
||||
}
|
||||
}
|
||||
|
||||
/// Commits the current text in the input buffer back to the selected variable's value.
|
||||
pub fn commit_input(&mut self) {
|
||||
if let Some(var) = self.vars.get_mut(self.selected) {
|
||||
if !var.is_group {
|
||||
var.value = Some(self.input.value().to_string());
|
||||
var.status = crate::format::ItemStatus::Modified;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Transitions the application into Insert Mode with a specific variant.
|
||||
pub fn enter_insert(&mut self, variant: InsertVariant) {
|
||||
if let Some(var) = self.vars.get(self.selected) {
|
||||
if !var.is_group {
|
||||
self.save_undo_state();
|
||||
self.mode = Mode::Insert;
|
||||
match variant {
|
||||
InsertVariant::Start => {
|
||||
use tui_input::InputRequest;
|
||||
self.input.handle(InputRequest::GoToStart);
|
||||
}
|
||||
InsertVariant::End => {
|
||||
use tui_input::InputRequest;
|
||||
self.input.handle(InputRequest::GoToEnd);
|
||||
}
|
||||
InsertVariant::Substitute => {
|
||||
self.input = Input::new(String::new());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Commits the current input and transitions the application into Normal Mode.
|
||||
pub fn enter_normal(&mut self) {
|
||||
self.commit_input();
|
||||
self.mode = Mode::Normal;
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn quit(&mut self) {
|
||||
self.running = false;
|
||||
/// Deletes the currently selected item. If it's a group, deletes all children.
|
||||
pub fn delete_selected(&mut self) {
|
||||
if self.vars.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
self.save_undo_state();
|
||||
let selected_path = self.vars[self.selected].path.clone();
|
||||
let is_group = self.vars[self.selected].is_group;
|
||||
|
||||
// Identify if the item being removed is an array item
|
||||
let array_info = parse_index(&selected_path);
|
||||
|
||||
// 1. Identify all items to remove
|
||||
let mut to_remove = Vec::new();
|
||||
to_remove.push(self.selected);
|
||||
|
||||
if is_group {
|
||||
let prefix_dot = format!("{}.", selected_path);
|
||||
let prefix_bracket = format!("{}[", selected_path);
|
||||
for (i, var) in self.vars.iter().enumerate() {
|
||||
if i == self.selected {
|
||||
continue;
|
||||
}
|
||||
if var.path.starts_with(&prefix_dot) || var.path.starts_with(&prefix_bracket) {
|
||||
to_remove.push(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Perform removal (reverse order to preserve indices)
|
||||
to_remove.sort_unstable_by(|a, b| b.cmp(a));
|
||||
for i in to_remove {
|
||||
self.vars.remove(i);
|
||||
}
|
||||
|
||||
// 3. Re-index subsequent array items if applicable
|
||||
if let Some((base, removed_idx)) = array_info {
|
||||
let base = base.to_string();
|
||||
for var in self.vars.iter_mut() {
|
||||
if var.path.starts_with(&base) {
|
||||
// We need to find the index segment that matches this array
|
||||
if let Some((b, i, suffix)) = find_array_segment(&var.path, &base) {
|
||||
if b == base && i > removed_idx {
|
||||
let new_idx = i - 1;
|
||||
var.path = format!("{}[{}]{}", base, new_idx, suffix);
|
||||
// Also update key if it matches the old index exactly
|
||||
if var.key == format!("[{}]", i) {
|
||||
var.key = format!("[{}]", new_idx);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Adjust selection
|
||||
if self.selected >= self.vars.len() && !self.vars.is_empty() {
|
||||
self.selected = self.vars.len() - 1;
|
||||
}
|
||||
self.sync_input_with_selected();
|
||||
}
|
||||
|
||||
/// Adds a new item to an array if the selected item is part of one.
|
||||
pub fn add_array_item(&mut self, after: bool) {
|
||||
if self.vars.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
self.save_undo_state();
|
||||
let (base, idx, depth) = {
|
||||
let selected_item = &self.vars[self.selected];
|
||||
if selected_item.is_group {
|
||||
return;
|
||||
}
|
||||
let path = &selected_item.path;
|
||||
if let Some((base, idx)) = parse_index(path) {
|
||||
(base.to_string(), idx, selected_item.depth)
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let new_idx = if after { idx + 1 } else { idx };
|
||||
let insert_pos = if after {
|
||||
self.selected + 1
|
||||
} else {
|
||||
self.selected
|
||||
};
|
||||
|
||||
// 1. Shift all items in this array that have index >= new_idx
|
||||
for var in self.vars.iter_mut() {
|
||||
if var.path.starts_with(&base) {
|
||||
if let Some((b, i)) = parse_index(&var.path) {
|
||||
if b == base && i >= new_idx {
|
||||
var.path = format!("{}[{}]", base, i + 1);
|
||||
// Also update key if it was just the index
|
||||
if var.key == format!("[{}]", i) {
|
||||
var.key = format!("[{}]", i + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Insert new item
|
||||
let new_item = ConfigItem {
|
||||
key: format!("[{}]", new_idx),
|
||||
path: format!("{}[{}]", base, new_idx),
|
||||
value: Some("".to_string()),
|
||||
template_value: None,
|
||||
default_value: None,
|
||||
depth,
|
||||
is_group: false,
|
||||
status: crate::format::ItemStatus::Modified,
|
||||
value_type: crate::format::ValueType::String,
|
||||
};
|
||||
self.vars.insert(insert_pos, new_item);
|
||||
self.selected = insert_pos;
|
||||
self.sync_input_with_selected();
|
||||
self.enter_insert(InsertVariant::Start);
|
||||
self.status_message = None;
|
||||
}
|
||||
|
||||
/// Status bar helpers
|
||||
pub fn selected_is_group(&self) -> bool {
|
||||
self.vars.get(self.selected).map(|v| v.is_group).unwrap_or(false)
|
||||
}
|
||||
|
||||
pub fn selected_is_array(&self) -> bool {
|
||||
self.vars.get(self.selected)
|
||||
.map(|v| !v.is_group && v.path.contains('['))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
pub fn selected_is_missing(&self) -> bool {
|
||||
self.vars.get(self.selected)
|
||||
.map(|v| v.status == crate::format::ItemStatus::MissingFromActive)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Saves the current state of variables to the undo stack.
|
||||
pub fn save_undo_state(&mut self) {
|
||||
self.undo_stack.push(self.vars.clone());
|
||||
if self.undo_stack.len() > 50 {
|
||||
self.undo_stack.remove(0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reverts to the last saved state of variables.
|
||||
pub fn undo(&mut self) {
|
||||
if let Some(previous_vars) = self.undo_stack.pop() {
|
||||
self.vars = previous_vars;
|
||||
if self.selected >= self.vars.len() && !self.vars.is_empty() {
|
||||
self.selected = self.vars.len() - 1;
|
||||
}
|
||||
self.sync_input_with_selected();
|
||||
self.status_message = Some("Undo applied".to_string());
|
||||
} else {
|
||||
self.status_message = Some("Nothing to undo".to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_index(path: &str) -> Option<(&str, usize)> {
|
||||
if let Some(end) = path.rfind(']') {
|
||||
let segment = &path[..=end];
|
||||
if let Some(start) = segment.rfind('[') {
|
||||
if let Ok(idx) = segment[start + 1..end].parse::<usize>() {
|
||||
// Return the base and index
|
||||
return Some((&path[..start], idx));
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Helper to find an array segment in a path given a base prefix.
|
||||
fn find_array_segment<'a>(path: &'a str, base: &str) -> Option<(&'a str, usize, &'a str)> {
|
||||
if !path.starts_with(base) {
|
||||
return None;
|
||||
}
|
||||
let remaining = &path[base.len()..];
|
||||
if remaining.starts_with('[') {
|
||||
if let Some(end) = remaining.find(']') {
|
||||
if let Ok(idx) = remaining[1..end].parse::<usize>() {
|
||||
return Some((&path[..base.len()], idx, &remaining[end + 1..]));
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
34
src/cli.rs
Normal file
34
src/cli.rs
Normal file
@@ -0,0 +1,34 @@
|
||||
use clap::Parser;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// mould: A TUI tool to generate and edit configuration files (.env, json, yaml, toml)
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(
|
||||
author,
|
||||
version,
|
||||
about = "mould: A TUI tool to generate and edit configuration files (.env, json, yaml, toml)",
|
||||
long_about = "mould allows you to interactively edit and generate configuration files using templates. It supports various formats including .env, JSON, YAML, and TOML. It features a modern TUI with Vim-inspired keybindings and out-of-the-box support for theming.",
|
||||
after_help = "EXAMPLES:\n mould .env.example\n mould docker-compose.yml\n mould config.template.json -o config.json"
|
||||
)]
|
||||
pub struct Cli {
|
||||
/// The input template file (e.g., .env.example, config.json.template, docker-compose.yml)
|
||||
#[arg(required = false, value_name = "INPUT_FILE")]
|
||||
pub input: Option<PathBuf>,
|
||||
|
||||
/// Optional output file. If not provided, it will be inferred.
|
||||
#[arg(short, long, value_name = "OUTPUT_FILE")]
|
||||
pub output: Option<PathBuf>,
|
||||
|
||||
/// Override the format detection (env, json, yaml, toml)
|
||||
#[arg(short, long, value_name = "FORMAT", value_parser = ["env", "json", "yaml", "toml"])]
|
||||
pub format: Option<String>,
|
||||
|
||||
/// Increase verbosity for logging (can be used multiple times)
|
||||
#[arg(short, long, action = clap::ArgAction::Count)]
|
||||
pub verbose: u8,
|
||||
}
|
||||
|
||||
/// Parses and returns the command-line arguments.
|
||||
pub fn parse() -> Cli {
|
||||
Cli::parse()
|
||||
}
|
||||
143
src/config.rs
143
src/config.rs
@@ -1,28 +1,165 @@
|
||||
use ratatui::style::Color;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs;
|
||||
|
||||
/// Configuration for the application's appearance.
|
||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||
#[serde(default)]
|
||||
pub struct ThemeConfig {
|
||||
pub name: String,
|
||||
/// If true, skip rendering the background block to let the terminal's transparency show.
|
||||
pub transparent: bool,
|
||||
/// Default background.
|
||||
pub bg_normal: String,
|
||||
/// Background for selected items and standard UI elements.
|
||||
pub bg_highlight: String,
|
||||
/// Active element background (e.g., insert mode).
|
||||
pub bg_active: String,
|
||||
/// Active element background (e.g., search mode).
|
||||
pub bg_search: String,
|
||||
/// Standard text.
|
||||
pub fg_normal: String,
|
||||
/// Secondary/inactive text.
|
||||
pub fg_dimmed: String,
|
||||
/// Text on selected items.
|
||||
pub fg_highlight: String,
|
||||
/// Red/Alert color for missing items.
|
||||
pub fg_warning: String,
|
||||
/// Accent color for modified items.
|
||||
pub fg_modified: String,
|
||||
/// High-contrast accent for titles and active UI elements.
|
||||
pub fg_accent: String,
|
||||
/// Borders.
|
||||
pub border_normal: String,
|
||||
/// Active borders (e.g., input mode).
|
||||
pub border_active: String,
|
||||
/// Color for tree indentation depth 1.
|
||||
pub tree_depth_1: String,
|
||||
/// Color for tree indentation depth 2.
|
||||
pub tree_depth_2: String,
|
||||
/// Color for tree indentation depth 3.
|
||||
pub tree_depth_3: String,
|
||||
/// Color for tree indentation depth 4.
|
||||
pub tree_depth_4: String,
|
||||
}
|
||||
|
||||
impl ThemeConfig {
|
||||
/// Internal helper to parse a hex color string ("#RRGGBB") into a TUI Color.
|
||||
fn parse_hex(hex: &str) -> Color {
|
||||
let hex = hex.trim_start_matches('#');
|
||||
if hex.len() == 6 {
|
||||
let r = u8::from_str_radix(&hex[0..2], 16).unwrap_or(0);
|
||||
let g = u8::from_str_radix(&hex[2..4], 16).unwrap_or(0);
|
||||
let b = u8::from_str_radix(&hex[4..6], 16).unwrap_or(0);
|
||||
Color::Rgb(r, g, b)
|
||||
} else {
|
||||
Color::Reset
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bg_normal(&self) -> Color { Self::parse_hex(&self.bg_normal) }
|
||||
pub fn bg_highlight(&self) -> Color { Self::parse_hex(&self.bg_highlight) }
|
||||
pub fn bg_active(&self) -> Color { Self::parse_hex(&self.bg_active) }
|
||||
pub fn bg_search(&self) -> Color { Self::parse_hex(&self.bg_search) }
|
||||
pub fn fg_normal(&self) -> Color { Self::parse_hex(&self.fg_normal) }
|
||||
pub fn fg_dimmed(&self) -> Color { Self::parse_hex(&self.fg_dimmed) }
|
||||
pub fn fg_highlight(&self) -> Color { Self::parse_hex(&self.fg_highlight) }
|
||||
pub fn fg_warning(&self) -> Color { Self::parse_hex(&self.fg_warning) }
|
||||
pub fn fg_modified(&self) -> Color { Self::parse_hex(&self.fg_modified) }
|
||||
pub fn fg_accent(&self) -> Color { Self::parse_hex(&self.fg_accent) }
|
||||
pub fn border_normal(&self) -> Color { Self::parse_hex(&self.border_normal) }
|
||||
pub fn border_active(&self) -> Color { Self::parse_hex(&self.border_active) }
|
||||
pub fn tree_depth_1(&self) -> Color { Self::parse_hex(&self.tree_depth_1) }
|
||||
pub fn tree_depth_2(&self) -> Color { Self::parse_hex(&self.tree_depth_2) }
|
||||
pub fn tree_depth_3(&self) -> Color { Self::parse_hex(&self.tree_depth_3) }
|
||||
pub fn tree_depth_4(&self) -> Color { Self::parse_hex(&self.tree_depth_4) }
|
||||
}
|
||||
|
||||
impl Default for ThemeConfig {
|
||||
/// Default theme: Semantic Catppuccin Mocha.
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
name: "catppuccin_mocha".to_string(),
|
||||
transparent: false,
|
||||
bg_normal: "#1e1e2e".to_string(), // base
|
||||
bg_highlight: "#89b4fa".to_string(), // blue
|
||||
bg_active: "#a6e3a1".to_string(), // green
|
||||
bg_search: "#cba6f7".to_string(), // mauve
|
||||
fg_normal: "#cdd6f4".to_string(), // text
|
||||
fg_dimmed: "#6c7086".to_string(), // overlay0
|
||||
fg_highlight: "#1e1e2e".to_string(), // base (dark for contrast against highlights)
|
||||
fg_warning: "#f38ba8".to_string(), // red
|
||||
fg_modified: "#fab387".to_string(), // peach
|
||||
fg_accent: "#b4befe".to_string(), // lavender
|
||||
border_normal: "#45475a".to_string(), // surface1
|
||||
border_active: "#a6e3a1".to_string(), // green
|
||||
tree_depth_1: "#b4befe".to_string(), // lavender
|
||||
tree_depth_2: "#cba6f7".to_string(), // mauve
|
||||
tree_depth_3: "#89b4fa".to_string(), // blue
|
||||
tree_depth_4: "#fab387".to_string(), // peach
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Custom keybindings for navigation and application control.
|
||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||
#[serde(default)]
|
||||
pub struct KeybindsConfig {
|
||||
pub down: String,
|
||||
pub up: String,
|
||||
pub edit: String,
|
||||
pub edit_append: String,
|
||||
pub edit_substitute: String,
|
||||
pub save: String,
|
||||
pub quit: String,
|
||||
pub normal_mode: String,
|
||||
pub search: String,
|
||||
pub next_match: String,
|
||||
pub previous_match: String,
|
||||
pub jump_top: String,
|
||||
pub jump_bottom: String,
|
||||
pub append_item: String,
|
||||
pub prepend_item: String,
|
||||
pub delete_item: String,
|
||||
pub undo: String,
|
||||
}
|
||||
|
||||
impl Default for KeybindsConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
down: "j".to_string(),
|
||||
up: "k".to_string(),
|
||||
edit: "i".to_string(),
|
||||
edit_append: "A".to_string(),
|
||||
edit_substitute: "S".to_string(),
|
||||
save: ":w".to_string(),
|
||||
quit: ":q".to_string(),
|
||||
normal_mode: "Esc".to_string(),
|
||||
search: "/".to_string(),
|
||||
next_match: "n".to_string(),
|
||||
previous_match: "N".to_string(),
|
||||
jump_top: "gg".to_string(),
|
||||
jump_bottom: "G".to_string(),
|
||||
append_item: "o".to_string(),
|
||||
prepend_item: "O".to_string(),
|
||||
delete_item: "dd".to_string(),
|
||||
undo: "u".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Root configuration structure for mould.
|
||||
#[derive(Debug, Deserialize, Serialize, Default, Clone)]
|
||||
pub struct Config {
|
||||
#[serde(default)]
|
||||
pub theme: ThemeConfig,
|
||||
#[serde(default)]
|
||||
pub keybinds: KeybindsConfig,
|
||||
}
|
||||
|
||||
/// Loads the configuration from the user's home config directory (~/.config/mould/config.toml).
|
||||
/// Falls back to default settings if no configuration is found.
|
||||
pub fn load_config() -> Config {
|
||||
if let Some(mut config_dir) = dirs::config_dir() {
|
||||
config_dir.push("cenv-rs");
|
||||
config_dir.push("mould");
|
||||
config_dir.push("config.toml");
|
||||
|
||||
if config_dir.exists() {
|
||||
|
||||
141
src/env.rs
141
src/env.rs
@@ -1,141 +0,0 @@
|
||||
use std::fs;
|
||||
use std::io::{self, Write};
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct EnvVar {
|
||||
pub key: String,
|
||||
pub value: String,
|
||||
pub default_value: String,
|
||||
}
|
||||
|
||||
pub fn parse_env_example<P: AsRef<Path>>(path: P) -> io::Result<Vec<EnvVar>> {
|
||||
let content = fs::read_to_string(path)?;
|
||||
let mut vars = Vec::new();
|
||||
|
||||
for line in content.lines() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue; // Skip comments and empty lines
|
||||
}
|
||||
|
||||
if let Some((key, val)) = line.split_once('=') {
|
||||
let parsed_val = val.trim().trim_matches('"').trim_matches('\'').to_string();
|
||||
vars.push(EnvVar {
|
||||
key: key.trim().to_string(),
|
||||
value: parsed_val.clone(),
|
||||
default_value: parsed_val,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(vars)
|
||||
}
|
||||
|
||||
pub fn merge_env<P: AsRef<Path>>(path: P, vars: &mut Vec<EnvVar>) -> io::Result<()> {
|
||||
if !path.as_ref().exists() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let content = fs::read_to_string(path)?;
|
||||
for line in content.lines() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some((key, val)) = line.split_once('=') {
|
||||
let key = key.trim();
|
||||
let parsed_val = val.trim().trim_matches('"').trim_matches('\'').to_string();
|
||||
|
||||
if let Some(var) = vars.iter_mut().find(|v| v.key == key) {
|
||||
var.value = parsed_val;
|
||||
} else {
|
||||
vars.push(EnvVar {
|
||||
key: key.to_string(),
|
||||
value: parsed_val.clone(),
|
||||
default_value: String::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn write_env<P: AsRef<Path>>(path: P, vars: &[EnvVar]) -> io::Result<()> {
|
||||
let mut file = fs::File::create(path)?;
|
||||
for var in vars {
|
||||
writeln!(file, "{}={}", var.key, var.value)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
#[test]
|
||||
fn test_parse_env_example() {
|
||||
let mut file = NamedTempFile::new().unwrap();
|
||||
writeln!(
|
||||
file,
|
||||
"# A comment\nKEY1=value1\nKEY2=\"value2\"\nKEY3='value3'\nEMPTY="
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let vars = parse_env_example(file.path()).unwrap();
|
||||
assert_eq!(vars.len(), 4);
|
||||
assert_eq!(vars[0].key, "KEY1");
|
||||
assert_eq!(vars[0].value, "value1");
|
||||
assert_eq!(vars[0].default_value, "value1");
|
||||
assert_eq!(vars[1].key, "KEY2");
|
||||
assert_eq!(vars[1].value, "value2");
|
||||
assert_eq!(vars[2].key, "KEY3");
|
||||
assert_eq!(vars[2].value, "value3");
|
||||
assert_eq!(vars[3].key, "EMPTY");
|
||||
assert_eq!(vars[3].value, "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_merge_env() {
|
||||
let mut example_file = NamedTempFile::new().unwrap();
|
||||
writeln!(example_file, "KEY1=default1\nKEY2=default2").unwrap();
|
||||
let mut vars = parse_env_example(example_file.path()).unwrap();
|
||||
|
||||
let mut env_file = NamedTempFile::new().unwrap();
|
||||
writeln!(env_file, "KEY1=custom1\nKEY3=custom3").unwrap();
|
||||
|
||||
merge_env(env_file.path(), &mut vars).unwrap();
|
||||
|
||||
assert_eq!(vars.len(), 3);
|
||||
assert_eq!(vars[0].key, "KEY1");
|
||||
assert_eq!(vars[0].value, "custom1");
|
||||
assert_eq!(vars[0].default_value, "default1");
|
||||
|
||||
assert_eq!(vars[1].key, "KEY2");
|
||||
assert_eq!(vars[1].value, "default2");
|
||||
assert_eq!(vars[1].default_value, "default2");
|
||||
|
||||
assert_eq!(vars[2].key, "KEY3");
|
||||
assert_eq!(vars[2].value, "custom3");
|
||||
assert_eq!(vars[2].default_value, "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_write_env() {
|
||||
let file = NamedTempFile::new().unwrap();
|
||||
let vars = vec![EnvVar {
|
||||
key: "KEY1".to_string(),
|
||||
value: "value1".to_string(),
|
||||
default_value: "def".to_string(),
|
||||
}];
|
||||
|
||||
write_env(file.path(), &vars).unwrap();
|
||||
|
||||
let content = fs::read_to_string(file.path()).unwrap();
|
||||
assert_eq!(content.trim(), "KEY1=value1");
|
||||
}
|
||||
}
|
||||
18
src/error.rs
Normal file
18
src/error.rs
Normal file
@@ -0,0 +1,18 @@
|
||||
use std::io;
|
||||
use thiserror::Error;
|
||||
|
||||
/// Custom error types for the mould application.
|
||||
#[derive(Error, Debug)]
|
||||
pub enum MouldError {
|
||||
#[error("IO error: {0}")]
|
||||
Io(#[from] io::Error),
|
||||
|
||||
#[error("Format error: {0}")]
|
||||
Format(String),
|
||||
|
||||
#[error("File not found: {0}")]
|
||||
FileNotFound(String),
|
||||
|
||||
#[error("Terminal error: {0}")]
|
||||
Terminal(String),
|
||||
}
|
||||
173
src/format/env.rs
Normal file
173
src/format/env.rs
Normal file
@@ -0,0 +1,173 @@
|
||||
use super::{ConfigItem, FormatHandler, ItemStatus, ValueType};
|
||||
use std::fs;
|
||||
use std::io::{self, Write};
|
||||
use std::path::Path;
|
||||
|
||||
pub struct EnvHandler;
|
||||
|
||||
impl FormatHandler for EnvHandler {
|
||||
fn parse(&self, path: &Path) -> io::Result<Vec<ConfigItem>> {
|
||||
let content = fs::read_to_string(path)?;
|
||||
let mut vars = Vec::new();
|
||||
|
||||
for line in content.lines() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue; // Skip comments and empty lines
|
||||
}
|
||||
|
||||
if let Some((key, val)) = line.split_once('=') {
|
||||
let parsed_val = val.trim().trim_matches('"').trim_matches('\'').to_string();
|
||||
vars.push(ConfigItem {
|
||||
key: key.trim().to_string(),
|
||||
path: key.trim().to_string(),
|
||||
value: Some(parsed_val.clone()),
|
||||
template_value: Some(parsed_val.clone()),
|
||||
default_value: Some(parsed_val),
|
||||
depth: 0,
|
||||
is_group: false,
|
||||
status: ItemStatus::Present,
|
||||
value_type: ValueType::String,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(vars)
|
||||
}
|
||||
|
||||
fn merge(&self, path: &Path, vars: &mut Vec<ConfigItem>) -> io::Result<()> {
|
||||
if !path.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let content = fs::read_to_string(path)?;
|
||||
for line in content.lines() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some((key, val)) = line.split_once('=') {
|
||||
let key = key.trim();
|
||||
let parsed_val = val.trim().trim_matches('"').trim_matches('\'').to_string();
|
||||
|
||||
if let Some(var) = vars.iter_mut().find(|v| v.key == key) {
|
||||
if var.value.as_deref() != Some(&parsed_val) {
|
||||
var.value = Some(parsed_val);
|
||||
var.status = ItemStatus::Modified;
|
||||
}
|
||||
} else {
|
||||
vars.push(ConfigItem {
|
||||
key: key.to_string(),
|
||||
path: key.to_string(),
|
||||
value: Some(parsed_val),
|
||||
template_value: None,
|
||||
default_value: None,
|
||||
depth: 0,
|
||||
is_group: false,
|
||||
status: ItemStatus::MissingFromTemplate,
|
||||
value_type: ValueType::String,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Mark missing from active
|
||||
for var in vars.iter_mut() {
|
||||
if var.status == ItemStatus::Present && var.value.is_none() {
|
||||
var.status = ItemStatus::MissingFromActive;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write(&self, path: &Path, vars: &[ConfigItem]) -> io::Result<()> {
|
||||
let mut file = fs::File::create(path)?;
|
||||
for var in vars {
|
||||
if !var.is_group {
|
||||
let val = var.value.as_deref()
|
||||
.or(var.template_value.as_deref())
|
||||
.unwrap_or("");
|
||||
writeln!(file, "{}={}", var.key, val)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
#[test]
|
||||
fn test_parse_env_example() {
|
||||
let mut file = NamedTempFile::new().unwrap();
|
||||
writeln!(
|
||||
file,
|
||||
"# A comment\nKEY1=value1\nKEY2=\"value2\"\nKEY3='value3'\nEMPTY="
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let handler = EnvHandler;
|
||||
let vars = handler.parse(file.path()).unwrap();
|
||||
assert_eq!(vars.len(), 4);
|
||||
assert_eq!(vars[0].key, "KEY1");
|
||||
assert_eq!(vars[0].value.as_deref(), Some("value1"));
|
||||
assert_eq!(vars[1].key, "KEY2");
|
||||
assert_eq!(vars[1].value.as_deref(), Some("value2"));
|
||||
assert_eq!(vars[2].key, "KEY3");
|
||||
assert_eq!(vars[2].value.as_deref(), Some("value3"));
|
||||
assert_eq!(vars[3].key, "EMPTY");
|
||||
assert_eq!(vars[3].value.as_deref(), Some(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_merge_env() {
|
||||
let mut example_file = NamedTempFile::new().unwrap();
|
||||
writeln!(example_file, "KEY1=default1\nKEY2=default2").unwrap();
|
||||
let handler = EnvHandler;
|
||||
let mut vars = handler.parse(example_file.path()).unwrap();
|
||||
|
||||
let mut env_file = NamedTempFile::new().unwrap();
|
||||
writeln!(env_file, "KEY1=custom1\nKEY3=custom3").unwrap();
|
||||
|
||||
handler.merge(env_file.path(), &mut vars).unwrap();
|
||||
|
||||
assert_eq!(vars.len(), 3);
|
||||
assert_eq!(vars[0].key, "KEY1");
|
||||
assert_eq!(vars[0].value.as_deref(), Some("custom1"));
|
||||
assert_eq!(vars[0].status, ItemStatus::Modified);
|
||||
|
||||
assert_eq!(vars[1].key, "KEY2");
|
||||
assert_eq!(vars[1].value.as_deref(), Some("default2"));
|
||||
|
||||
assert_eq!(vars[2].key, "KEY3");
|
||||
assert_eq!(vars[2].value.as_deref(), Some("custom3"));
|
||||
assert_eq!(vars[2].status, ItemStatus::MissingFromTemplate);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_write_env() {
|
||||
let file = NamedTempFile::new().unwrap();
|
||||
let vars = vec![ConfigItem {
|
||||
key: "KEY1".to_string(),
|
||||
path: "KEY1".to_string(),
|
||||
value: Some("value1".to_string()),
|
||||
template_value: None,
|
||||
default_value: None,
|
||||
depth: 0,
|
||||
is_group: false,
|
||||
status: ItemStatus::Present,
|
||||
value_type: ValueType::String,
|
||||
}];
|
||||
|
||||
let handler = EnvHandler;
|
||||
handler.write(file.path(), &vars).unwrap();
|
||||
|
||||
let content = fs::read_to_string(file.path()).unwrap();
|
||||
assert_eq!(content.trim(), "KEY1=value1");
|
||||
}
|
||||
}
|
||||
353
src/format/hierarchical.rs
Normal file
353
src/format/hierarchical.rs
Normal file
@@ -0,0 +1,353 @@
|
||||
use super::{ConfigItem, FormatHandler, FormatType, ItemStatus, ValueType};
|
||||
use serde_json::{Map, Value};
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
pub struct HierarchicalHandler {
|
||||
format_type: FormatType,
|
||||
}
|
||||
|
||||
impl HierarchicalHandler {
|
||||
pub fn new(format_type: FormatType) -> Self {
|
||||
Self { format_type }
|
||||
}
|
||||
|
||||
fn read_value(&self, path: &Path) -> io::Result<Value> {
|
||||
let content = fs::read_to_string(path)?;
|
||||
let value = match self.format_type {
|
||||
FormatType::Json => serde_json::from_str(&content)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
|
||||
FormatType::Yaml => serde_yaml::from_str(&content)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
|
||||
FormatType::Toml => toml::from_str(&content)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn write_value(&self, path: &Path, value: &Value) -> io::Result<()> {
|
||||
let content = match self.format_type {
|
||||
FormatType::Json => serde_json::to_string_pretty(value)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
|
||||
FormatType::Yaml => serde_yaml::to_string(value)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
|
||||
FormatType::Toml => {
|
||||
// toml requires the root to be a table
|
||||
if value.is_object() {
|
||||
let toml_value: toml::Value = serde_json::from_value(value.clone())
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
|
||||
toml::to_string_pretty(&toml_value)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
|
||||
} else {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Root of TOML must be an object",
|
||||
));
|
||||
}
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
fs::write(path, content)
|
||||
}
|
||||
}
|
||||
|
||||
fn flatten(value: &Value, prefix: &str, depth: usize, key_name: &str, vars: &mut Vec<ConfigItem>) {
|
||||
let path = if prefix.is_empty() {
|
||||
key_name.to_string()
|
||||
} else if key_name.is_empty() {
|
||||
prefix.to_string()
|
||||
} else if key_name.starts_with('[') {
|
||||
format!("{}{}", prefix, key_name)
|
||||
} else {
|
||||
format!("{}.{}", prefix, key_name)
|
||||
};
|
||||
|
||||
match value {
|
||||
Value::Object(map) => {
|
||||
if !path.is_empty() {
|
||||
vars.push(ConfigItem {
|
||||
key: key_name.to_string(),
|
||||
path: path.clone(),
|
||||
value: None,
|
||||
template_value: None,
|
||||
default_value: None,
|
||||
depth,
|
||||
is_group: true,
|
||||
status: ItemStatus::Present,
|
||||
value_type: ValueType::Null,
|
||||
});
|
||||
}
|
||||
let next_depth = if path.is_empty() { depth } else { depth + 1 };
|
||||
for (k, v) in map {
|
||||
flatten(v, &path, next_depth, k, vars);
|
||||
}
|
||||
}
|
||||
Value::Array(arr) => {
|
||||
if !path.is_empty() {
|
||||
vars.push(ConfigItem {
|
||||
key: key_name.to_string(),
|
||||
path: path.clone(),
|
||||
value: None,
|
||||
template_value: None,
|
||||
default_value: None,
|
||||
depth,
|
||||
is_group: true,
|
||||
status: ItemStatus::Present,
|
||||
value_type: ValueType::Null,
|
||||
});
|
||||
}
|
||||
let next_depth = if path.is_empty() { depth } else { depth + 1 };
|
||||
for (i, v) in arr.iter().enumerate() {
|
||||
let array_key = format!("[{}]", i);
|
||||
flatten(v, &path, next_depth, &array_key, vars);
|
||||
}
|
||||
}
|
||||
Value::String(s) => {
|
||||
vars.push(ConfigItem {
|
||||
key: key_name.to_string(),
|
||||
path: path.clone(),
|
||||
value: Some(s.clone()),
|
||||
template_value: Some(s.clone()),
|
||||
default_value: Some(s.clone()),
|
||||
depth,
|
||||
is_group: false,
|
||||
status: ItemStatus::Present,
|
||||
value_type: ValueType::String,
|
||||
});
|
||||
}
|
||||
Value::Number(n) => {
|
||||
let s = n.to_string();
|
||||
vars.push(ConfigItem {
|
||||
key: key_name.to_string(),
|
||||
path: path.clone(),
|
||||
value: Some(s.clone()),
|
||||
template_value: Some(s.clone()),
|
||||
default_value: Some(s.clone()),
|
||||
depth,
|
||||
is_group: false,
|
||||
status: ItemStatus::Present,
|
||||
value_type: ValueType::Number,
|
||||
});
|
||||
}
|
||||
Value::Bool(b) => {
|
||||
let s = b.to_string();
|
||||
vars.push(ConfigItem {
|
||||
key: key_name.to_string(),
|
||||
path: path.clone(),
|
||||
value: Some(s.clone()),
|
||||
template_value: Some(s.clone()),
|
||||
default_value: Some(s.clone()),
|
||||
depth,
|
||||
is_group: false,
|
||||
status: ItemStatus::Present,
|
||||
value_type: ValueType::Bool,
|
||||
});
|
||||
}
|
||||
Value::Null => {
|
||||
vars.push(ConfigItem {
|
||||
key: key_name.to_string(),
|
||||
path: path.clone(),
|
||||
value: Some("".to_string()),
|
||||
template_value: Some("".to_string()),
|
||||
default_value: Some("".to_string()),
|
||||
depth,
|
||||
is_group: false,
|
||||
status: ItemStatus::Present,
|
||||
value_type: ValueType::Null,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FormatHandler for HierarchicalHandler {
|
||||
fn parse(&self, path: &Path) -> io::Result<Vec<ConfigItem>> {
|
||||
let value = self.read_value(path)?;
|
||||
let mut vars = Vec::new();
|
||||
flatten(&value, "", 0, "", &mut vars);
|
||||
Ok(vars)
|
||||
}
|
||||
|
||||
fn merge(&self, path: &Path, vars: &mut Vec<ConfigItem>) -> io::Result<()> {
|
||||
if !path.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
let existing_value = self.read_value(path)?;
|
||||
let mut existing_vars = Vec::new();
|
||||
flatten(&existing_value, "", 0, "", &mut existing_vars);
|
||||
|
||||
for var in vars.iter_mut() {
|
||||
if let Some(existing) = existing_vars.iter().find(|v| v.path == var.path) {
|
||||
if var.value != existing.value {
|
||||
var.value = existing.value.clone();
|
||||
var.status = ItemStatus::Modified;
|
||||
}
|
||||
} else {
|
||||
var.status = ItemStatus::MissingFromActive;
|
||||
}
|
||||
}
|
||||
|
||||
// Find keys in active that are not in template
|
||||
let mut to_add = Vec::new();
|
||||
for existing in existing_vars {
|
||||
if !vars.iter().any(|v| v.path == existing.path) {
|
||||
let mut new_item = existing.clone();
|
||||
new_item.status = ItemStatus::MissingFromTemplate;
|
||||
new_item.template_value = None;
|
||||
new_item.default_value = None;
|
||||
to_add.push(new_item);
|
||||
}
|
||||
}
|
||||
|
||||
// Basic insertion logic for extra keys (could be improved to insert at correct depth/position)
|
||||
vars.extend(to_add);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write(&self, path: &Path, vars: &[ConfigItem]) -> io::Result<()> {
|
||||
let mut root = Value::Object(Map::new());
|
||||
for var in vars {
|
||||
if !var.is_group {
|
||||
let val = var.value.as_deref()
|
||||
.or(var.template_value.as_deref())
|
||||
.unwrap_or("");
|
||||
insert_into_value(&mut root, &var.path, val, var.value_type);
|
||||
}
|
||||
}
|
||||
self.write_value(path, &root)
|
||||
}
|
||||
}
|
||||
|
||||
fn insert_into_value(root: &mut Value, path: &str, new_val_str: &str, value_type: ValueType) {
|
||||
let mut parts = path.split('.');
|
||||
let last_part = match parts.next_back() {
|
||||
Some(p) => p,
|
||||
None => return,
|
||||
};
|
||||
|
||||
let mut current = root;
|
||||
for part in parts {
|
||||
let (key, idx) = parse_array_key(part);
|
||||
if !current.is_object() {
|
||||
*current = Value::Object(Map::new());
|
||||
}
|
||||
let map = current.as_object_mut().unwrap();
|
||||
|
||||
let next_node = map.entry(key.to_string()).or_insert_with(|| {
|
||||
if idx.is_some() {
|
||||
Value::Array(Vec::new())
|
||||
} else {
|
||||
Value::Object(Map::new())
|
||||
}
|
||||
});
|
||||
|
||||
if let Some(i) = idx {
|
||||
if !next_node.is_array() {
|
||||
*next_node = Value::Array(Vec::new());
|
||||
}
|
||||
let arr = next_node.as_array_mut().unwrap();
|
||||
while arr.len() <= i {
|
||||
arr.push(Value::Object(Map::new()));
|
||||
}
|
||||
current = &mut arr[i];
|
||||
} else {
|
||||
current = next_node;
|
||||
}
|
||||
}
|
||||
|
||||
let (final_key, final_idx) = parse_array_key(last_part);
|
||||
if !current.is_object() {
|
||||
*current = Value::Object(Map::new());
|
||||
}
|
||||
let map = current.as_object_mut().unwrap();
|
||||
|
||||
// Use the preserved ValueType instead of aggressive inference
|
||||
let final_val = match value_type {
|
||||
ValueType::Number => {
|
||||
if let Ok(n) = new_val_str.parse::<i64>() {
|
||||
Value::Number(n.into())
|
||||
} else if let Ok(f) = new_val_str.parse::<f64>() {
|
||||
if let Some(n) = serde_json::Number::from_f64(f) {
|
||||
Value::Number(n)
|
||||
} else {
|
||||
Value::String(new_val_str.to_string())
|
||||
}
|
||||
} else {
|
||||
Value::String(new_val_str.to_string())
|
||||
}
|
||||
}
|
||||
ValueType::Bool => {
|
||||
if let Ok(b) = new_val_str.parse::<bool>() {
|
||||
Value::Bool(b)
|
||||
} else {
|
||||
Value::String(new_val_str.to_string())
|
||||
}
|
||||
}
|
||||
ValueType::Null if new_val_str.is_empty() => Value::Null,
|
||||
_ => Value::String(new_val_str.to_string()),
|
||||
};
|
||||
|
||||
if let Some(i) = final_idx {
|
||||
let next_node = map
|
||||
.entry(final_key.to_string())
|
||||
.or_insert_with(|| Value::Array(Vec::new()));
|
||||
if !next_node.is_array() {
|
||||
*next_node = Value::Array(Vec::new());
|
||||
}
|
||||
let arr = next_node.as_array_mut().unwrap();
|
||||
while arr.len() <= i {
|
||||
arr.push(Value::Null);
|
||||
}
|
||||
arr[i] = final_val;
|
||||
} else {
|
||||
map.insert(final_key.to_string(), final_val);
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_array_key(part: &str) -> (&str, Option<usize>) {
|
||||
if part.ends_with(']') && part.contains('[') {
|
||||
let start_idx = part.find('[').unwrap();
|
||||
let key = &part[..start_idx];
|
||||
let idx = part[start_idx + 1..part.len() - 1].parse::<usize>().ok();
|
||||
(key, idx)
|
||||
} else {
|
||||
(part, None)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_flatten_unflatten() {
|
||||
let mut vars = Vec::new();
|
||||
let json = serde_json::json!({
|
||||
"services": {
|
||||
"web": {
|
||||
"ports": ["8080:80"],
|
||||
"environment": {
|
||||
"DEBUG": true
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
flatten(&json, "", 0, "", &mut vars);
|
||||
assert_eq!(vars.len(), 6);
|
||||
|
||||
let mut root = Value::Object(Map::new());
|
||||
for var in vars {
|
||||
if !var.is_group {
|
||||
insert_into_value(&mut root, &var.path, var.value.as_deref().unwrap_or(""), var.value_type);
|
||||
}
|
||||
}
|
||||
|
||||
// When unflattening, it parses bool back
|
||||
let unflattened_json = serde_json::to_string(&root).unwrap();
|
||||
assert!(unflattened_json.contains("\"8080:80\""));
|
||||
assert!(unflattened_json.contains("true"));
|
||||
}
|
||||
}
|
||||
80
src/format/mod.rs
Normal file
80
src/format/mod.rs
Normal file
@@ -0,0 +1,80 @@
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
pub mod env;
|
||||
pub mod hierarchical;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ItemStatus {
|
||||
Present,
|
||||
MissingFromActive,
|
||||
MissingFromTemplate,
|
||||
Modified,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ValueType {
|
||||
String,
|
||||
Number,
|
||||
Bool,
|
||||
Null,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ConfigItem {
|
||||
pub key: String,
|
||||
pub path: String,
|
||||
pub value: Option<String>,
|
||||
pub template_value: Option<String>,
|
||||
pub default_value: Option<String>,
|
||||
pub depth: usize,
|
||||
pub is_group: bool,
|
||||
pub status: ItemStatus,
|
||||
pub value_type: ValueType,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum FormatType {
|
||||
Env,
|
||||
Json,
|
||||
Yaml,
|
||||
Toml,
|
||||
}
|
||||
|
||||
pub trait FormatHandler {
|
||||
fn parse(&self, path: &Path) -> io::Result<Vec<ConfigItem>>;
|
||||
fn merge(&self, path: &Path, vars: &mut Vec<ConfigItem>) -> io::Result<()>;
|
||||
fn write(&self, path: &Path, vars: &[ConfigItem]) -> io::Result<()>;
|
||||
}
|
||||
|
||||
pub fn detect_format(path: &Path, override_format: Option<String>) -> FormatType {
|
||||
if let Some(fmt) = override_format {
|
||||
match fmt.to_lowercase().as_str() {
|
||||
"env" => return FormatType::Env,
|
||||
"json" => return FormatType::Json,
|
||||
"yaml" | "yml" => return FormatType::Yaml,
|
||||
"toml" => return FormatType::Toml,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let file_name = path.file_name().unwrap_or_default().to_string_lossy();
|
||||
if file_name.ends_with(".json") {
|
||||
FormatType::Json
|
||||
} else if file_name.ends_with(".yaml") || file_name.ends_with(".yml") {
|
||||
FormatType::Yaml
|
||||
} else if file_name.ends_with(".toml") {
|
||||
FormatType::Toml
|
||||
} else {
|
||||
FormatType::Env
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_handler(format: FormatType) -> Box<dyn FormatHandler> {
|
||||
match format {
|
||||
FormatType::Env => Box::new(env::EnvHandler),
|
||||
FormatType::Json => Box::new(hierarchical::HierarchicalHandler::new(FormatType::Json)),
|
||||
FormatType::Yaml => Box::new(hierarchical::HierarchicalHandler::new(FormatType::Yaml)),
|
||||
FormatType::Toml => Box::new(hierarchical::HierarchicalHandler::new(FormatType::Toml)),
|
||||
}
|
||||
}
|
||||
393
src/main.rs
393
src/main.rs
@@ -1,171 +1,286 @@
|
||||
mod app;
|
||||
mod cli;
|
||||
mod config;
|
||||
mod env;
|
||||
mod error;
|
||||
mod format;
|
||||
mod runner;
|
||||
mod ui;
|
||||
|
||||
use app::{App, Mode};
|
||||
use app::App;
|
||||
use config::load_config;
|
||||
use env::{merge_env, parse_env_example, write_env};
|
||||
use std::error::Error;
|
||||
use error::MouldError;
|
||||
use format::{detect_format, get_handler};
|
||||
use log::{error, info, warn};
|
||||
use runner::AppRunner;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crossterm::{
|
||||
event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode},
|
||||
event::{DisableMouseCapture, EnableMouseCapture},
|
||||
execute,
|
||||
terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
|
||||
};
|
||||
use ratatui::{
|
||||
Terminal,
|
||||
backend::{Backend, CrosstermBackend},
|
||||
};
|
||||
use ratatui::{Terminal, backend::CrosstermBackend};
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let example_path = ".env.example";
|
||||
let env_path = ".env";
|
||||
/// Helper to automatically determine the output file path based on common naming conventions.
|
||||
fn determine_output_path(input: &Path) -> PathBuf {
|
||||
let file_name = input.file_name().unwrap_or_default().to_string_lossy();
|
||||
|
||||
// Load vars
|
||||
let mut vars = parse_env_example(example_path).unwrap_or_else(|_| vec![]);
|
||||
if vars.is_empty() {
|
||||
println!("No variables found in .env.example or file does not exist.");
|
||||
println!("Please run this tool in a directory with a valid .env.example file.");
|
||||
return Ok(());
|
||||
// Standard mappings
|
||||
if file_name == ".env.example" || file_name == ".env.template" {
|
||||
return input.with_file_name(".env");
|
||||
}
|
||||
|
||||
// Merge existing .env if present
|
||||
let _ = merge_env(env_path, &mut vars);
|
||||
if file_name == "docker-compose.yml" || file_name == "compose.yml" {
|
||||
return input.with_file_name("compose.override.yml");
|
||||
}
|
||||
if file_name == "docker-compose.yaml" || file_name == "compose.yaml" {
|
||||
return input.with_file_name("compose.override.yaml");
|
||||
}
|
||||
|
||||
// Pattern-based mappings
|
||||
if let Some(base) = file_name.strip_suffix(".env.example") {
|
||||
return input.with_file_name(format!("{}.env", base));
|
||||
}
|
||||
if let Some(base) = file_name.strip_suffix(".env.template") {
|
||||
return input.with_file_name(format!("{}.env", base));
|
||||
}
|
||||
if let Some(base) = file_name.strip_suffix(".example.json") {
|
||||
return input.with_file_name(format!("{}.json", base));
|
||||
}
|
||||
if let Some(base) = file_name.strip_suffix(".template.json") {
|
||||
return input.with_file_name(format!("{}.json", base));
|
||||
}
|
||||
if let Some(base) = file_name.strip_suffix(".example.yml") {
|
||||
return input.with_file_name(format!("{}.yml", base));
|
||||
}
|
||||
if let Some(base) = file_name.strip_suffix(".template.yml") {
|
||||
return input.with_file_name(format!("{}.yml", base));
|
||||
}
|
||||
if let Some(base) = file_name.strip_suffix(".example.yaml") {
|
||||
return input.with_file_name(format!("{}.yaml", base));
|
||||
}
|
||||
if let Some(base) = file_name.strip_suffix(".template.yaml") {
|
||||
return input.with_file_name(format!("{}.yaml", base));
|
||||
}
|
||||
if let Some(base) = file_name.strip_suffix(".example.toml") {
|
||||
return input.with_file_name(format!("{}.toml", base));
|
||||
}
|
||||
if let Some(base) = file_name.strip_suffix(".template.toml") {
|
||||
return input.with_file_name(format!("{}.toml", base));
|
||||
}
|
||||
|
||||
input.with_extension(format!(
|
||||
"{}.out",
|
||||
input.extension().unwrap_or_default().to_string_lossy()
|
||||
))
|
||||
}
|
||||
|
||||
/// Discovers common configuration template files in the current directory.
|
||||
fn find_input_file() -> Option<PathBuf> {
|
||||
let candidates = [
|
||||
".env.example",
|
||||
"compose.yml",
|
||||
"docker-compose.yml",
|
||||
".env.template",
|
||||
"compose.yaml",
|
||||
"docker-compose.yaml",
|
||||
];
|
||||
|
||||
// Priority 1: Exact matches for well-known defaults
|
||||
for name in &candidates {
|
||||
let path = PathBuf::from(name);
|
||||
if path.exists() {
|
||||
return Some(path);
|
||||
}
|
||||
}
|
||||
|
||||
// Priority 2: Pattern matches
|
||||
if let Ok(entries) = std::fs::read_dir(".") {
|
||||
let mut fallback = None;
|
||||
for entry in entries.flatten() {
|
||||
let name = entry.file_name();
|
||||
let name_str = name.to_string_lossy();
|
||||
|
||||
if name_str.ends_with(".env.example")
|
||||
|| name_str.ends_with(".env.template")
|
||||
|| name_str.ends_with(".example.json")
|
||||
|| name_str.ends_with(".template.json")
|
||||
|| name_str.ends_with(".example.yml")
|
||||
|| name_str.ends_with(".template.yml")
|
||||
|| name_str.ends_with(".example.yaml")
|
||||
|| name_str.ends_with(".template.yaml")
|
||||
|| name_str.ends_with(".example.toml")
|
||||
|| name_str.ends_with(".template.toml")
|
||||
{
|
||||
// Prefer .env.* or compose.* if multiple matches
|
||||
if name_str.contains(".env") || name_str.contains("compose") {
|
||||
return Some(entry.path());
|
||||
}
|
||||
if fallback.is_none() {
|
||||
fallback = Some(entry.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(path) = fallback {
|
||||
return Some(path);
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
let args = cli::parse();
|
||||
|
||||
// Initialize logger with verbosity from CLI
|
||||
let log_level = match args.verbose {
|
||||
0 => log::LevelFilter::Warn,
|
||||
1 => log::LevelFilter::Info,
|
||||
_ => log::LevelFilter::Debug,
|
||||
};
|
||||
env_logger::Builder::new()
|
||||
.filter_level(log_level)
|
||||
.format_timestamp(None)
|
||||
.init();
|
||||
|
||||
let input_path = match args.input {
|
||||
Some(path) => {
|
||||
if !path.exists() {
|
||||
error!("Input file not found: {}", path.display());
|
||||
return Err(MouldError::FileNotFound(path.display().to_string()).into());
|
||||
}
|
||||
path
|
||||
}
|
||||
None => match find_input_file() {
|
||||
Some(path) => {
|
||||
info!("Discovered template: {}", path.display());
|
||||
path
|
||||
}
|
||||
None => {
|
||||
error!("No template file provided and none discovered in current directory.");
|
||||
println!("Usage: mould <INPUT_FILE>");
|
||||
println!("Supported defaults: .env.example, compose.yml, docker-compose.yml, etc.");
|
||||
return Err(MouldError::FileNotFound("None".to_string()).into());
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
info!("Input: {}", input_path.display());
|
||||
|
||||
let format_type = detect_format(&input_path, args.format);
|
||||
let handler = get_handler(format_type);
|
||||
|
||||
// Smart Comparison Logic
|
||||
let input_name = input_path.file_name().unwrap_or_default().to_string_lossy();
|
||||
let is_template_input = input_name.contains(".example") || input_name.contains(".template") || input_name == "compose.yml" || input_name == "docker-compose.yml";
|
||||
|
||||
let mut template_path = None;
|
||||
let mut active_path = None;
|
||||
|
||||
if is_template_input {
|
||||
template_path = Some(input_path.clone());
|
||||
let expected_active = determine_output_path(&input_path);
|
||||
if expected_active.exists() {
|
||||
active_path = Some(expected_active);
|
||||
}
|
||||
} else {
|
||||
// Input is likely an active config (e.g., .env)
|
||||
active_path = Some(input_path.clone());
|
||||
// Try to find a template
|
||||
let possible_templates = [
|
||||
format!("{}.example", input_name),
|
||||
format!("{}.template", input_name),
|
||||
];
|
||||
for t in possible_templates {
|
||||
let p = input_path.with_file_name(t);
|
||||
if p.exists() {
|
||||
template_path = Some(p);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let output_path = args
|
||||
.output
|
||||
.unwrap_or_else(|| active_path.clone().unwrap_or_else(|| determine_output_path(&input_path)));
|
||||
|
||||
info!("Output: {}", output_path.display());
|
||||
|
||||
// 1. Load active config if it exists
|
||||
let mut vars = if let Some(active) = &active_path {
|
||||
handler.parse(active).unwrap_or_default()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
// 2. Load template config and merge
|
||||
if let Some(template) = &template_path {
|
||||
info!("Comparing with template: {}", template.display());
|
||||
let template_vars = handler.parse(template).unwrap_or_default();
|
||||
if vars.is_empty() {
|
||||
vars = template_vars;
|
||||
// If we only have template, everything is missing from active initially
|
||||
for v in vars.iter_mut() {
|
||||
v.status = crate::format::ItemStatus::MissingFromActive;
|
||||
v.value = None;
|
||||
}
|
||||
} else {
|
||||
// Merge template into active
|
||||
handler.merge(template, &mut vars).unwrap_or_default();
|
||||
}
|
||||
} else if vars.is_empty() {
|
||||
// Fallback if no template and active is empty
|
||||
vars = handler.parse(&input_path).map_err(|e| {
|
||||
error!("Failed to parse input file: {}", e);
|
||||
MouldError::Format(format!("Failed to parse {}: {}", input_path.display(), e))
|
||||
})?;
|
||||
}
|
||||
|
||||
if vars.is_empty() {
|
||||
warn!("No variables found.");
|
||||
}
|
||||
|
||||
let config = load_config();
|
||||
let mut app = App::new(vars);
|
||||
|
||||
// Setup terminal
|
||||
enable_raw_mode()?;
|
||||
// Terminal lifecycle
|
||||
enable_raw_mode()
|
||||
.map_err(|e| MouldError::Terminal(format!("Failed to enable raw mode: {}", e)))?;
|
||||
let mut stdout = io::stdout();
|
||||
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
|
||||
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)
|
||||
.map_err(|e| MouldError::Terminal(format!("Failed to enter alternate screen: {}", e)))?;
|
||||
let backend = CrosstermBackend::new(stdout);
|
||||
let mut terminal = Terminal::new(backend)?;
|
||||
let mut terminal = Terminal::new(backend)
|
||||
.map_err(|e| MouldError::Terminal(format!("Failed to create terminal backend: {}", e)))?;
|
||||
|
||||
// Run app
|
||||
let res = run_app(&mut terminal, &mut app, &config, env_path);
|
||||
let mut runner = AppRunner::new(
|
||||
&mut terminal,
|
||||
&mut app,
|
||||
&config,
|
||||
&output_path,
|
||||
handler.as_ref(),
|
||||
);
|
||||
let res = runner.run();
|
||||
|
||||
// Restore terminal
|
||||
disable_raw_mode()?;
|
||||
// Restoration
|
||||
disable_raw_mode().ok();
|
||||
execute!(
|
||||
terminal.backend_mut(),
|
||||
LeaveAlternateScreen,
|
||||
DisableMouseCapture
|
||||
)?;
|
||||
terminal.show_cursor()?;
|
||||
)
|
||||
.ok();
|
||||
terminal.show_cursor().ok();
|
||||
|
||||
if let Err(err) = res {
|
||||
println!("{:?}", err);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_app<B: Backend>(
|
||||
terminal: &mut Terminal<B>,
|
||||
app: &mut App,
|
||||
config: &config::Config,
|
||||
env_path: &str,
|
||||
) -> io::Result<()>
|
||||
where
|
||||
io::Error: From<B::Error>,
|
||||
{
|
||||
// For handling commands like :w, :q
|
||||
let mut command_buffer = String::new();
|
||||
|
||||
loop {
|
||||
terminal.draw(|f| ui::draw(f, app, config))?;
|
||||
|
||||
if let Event::Key(key) = event::read()? {
|
||||
match app.mode {
|
||||
Mode::Normal => {
|
||||
if !command_buffer.is_empty() {
|
||||
if key.code == KeyCode::Enter {
|
||||
match command_buffer.as_str() {
|
||||
":w" => {
|
||||
if write_env(env_path, &app.vars).is_ok() {
|
||||
app.status_message = Some("Saved to .env".to_string());
|
||||
} else {
|
||||
app.status_message =
|
||||
Some("Error saving to .env".to_string());
|
||||
}
|
||||
}
|
||||
":q" => return Ok(()),
|
||||
":wq" => {
|
||||
write_env(env_path, &app.vars)?;
|
||||
return Ok(());
|
||||
}
|
||||
_ => {
|
||||
app.status_message = Some("Unknown command".to_string());
|
||||
}
|
||||
}
|
||||
command_buffer.clear();
|
||||
} else if key.code == KeyCode::Esc {
|
||||
command_buffer.clear();
|
||||
app.status_message = None;
|
||||
} else if key.code == KeyCode::Backspace {
|
||||
command_buffer.pop();
|
||||
if command_buffer.is_empty() {
|
||||
app.status_message = None;
|
||||
} else {
|
||||
app.status_message = Some(command_buffer.clone());
|
||||
}
|
||||
} else if let KeyCode::Char(c) = key.code {
|
||||
command_buffer.push(c);
|
||||
app.status_message = Some(command_buffer.clone());
|
||||
}
|
||||
} else {
|
||||
match key.code {
|
||||
KeyCode::Char('q') => return Ok(()),
|
||||
KeyCode::Char('j') | KeyCode::Down => app.next(),
|
||||
KeyCode::Char('k') | KeyCode::Up => app.previous(),
|
||||
KeyCode::Char('i') => {
|
||||
app.enter_insert();
|
||||
app.status_message = None;
|
||||
}
|
||||
KeyCode::Char(':') => {
|
||||
command_buffer.push(':');
|
||||
app.status_message = Some(command_buffer.clone());
|
||||
}
|
||||
KeyCode::Enter => {
|
||||
// Default action for Enter in Normal mode is save
|
||||
if write_env(env_path, &app.vars).is_ok() {
|
||||
app.status_message = Some("Saved to .env".to_string());
|
||||
} else {
|
||||
app.status_message = Some("Error saving to .env".to_string());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Mode::Insert => match key.code {
|
||||
KeyCode::Esc => {
|
||||
app.enter_normal();
|
||||
}
|
||||
KeyCode::Char(c) => {
|
||||
if let Some(var) = app.vars.get_mut(app.selected) {
|
||||
var.value.push(c);
|
||||
}
|
||||
}
|
||||
KeyCode::Backspace => {
|
||||
if let Some(var) = app.vars.get_mut(app.selected) {
|
||||
var.value.pop();
|
||||
}
|
||||
}
|
||||
KeyCode::Enter => {
|
||||
app.enter_normal();
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
}
|
||||
match res {
|
||||
Ok(_) => {
|
||||
info!("Successfully finished mould session.");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
if !app.running {
|
||||
break;
|
||||
Err(e) => {
|
||||
error!("Application error during run: {}", e);
|
||||
Err(e.into())
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
282
src/runner.rs
Normal file
282
src/runner.rs
Normal file
@@ -0,0 +1,282 @@
|
||||
use crate::app::{App, InsertVariant, Mode};
|
||||
use crate::config::Config;
|
||||
use crate::format::FormatHandler;
|
||||
use crossterm::event::{self, Event, KeyCode, KeyEvent};
|
||||
use ratatui::Terminal;
|
||||
use ratatui::backend::Backend;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use tui_input::backend::crossterm::EventHandler;
|
||||
|
||||
/// Manages the main application execution loop, event handling, and terminal interaction.
|
||||
pub struct AppRunner<'a, B: Backend> {
|
||||
/// Reference to the terminal instance.
|
||||
terminal: &'a mut Terminal<B>,
|
||||
/// Mutable reference to the application state.
|
||||
app: &'a mut App,
|
||||
/// Loaded user configuration.
|
||||
config: &'a Config,
|
||||
/// Path where the final configuration will be saved.
|
||||
output_path: &'a Path,
|
||||
/// Handler for the specific file format (env, json, yaml, toml).
|
||||
handler: &'a dyn FormatHandler,
|
||||
/// Buffer for storing active command entry (e.g., ":w").
|
||||
command_buffer: String,
|
||||
/// Buffer for storing sequence of key presses (e.g., "gg").
|
||||
key_sequence: String,
|
||||
}
|
||||
|
||||
impl<'a, B: Backend> AppRunner<'a, B>
|
||||
where
|
||||
io::Error: From<B::Error>,
|
||||
{
|
||||
/// Creates a new runner instance.
|
||||
pub fn new(
|
||||
terminal: &'a mut Terminal<B>,
|
||||
app: &'a mut App,
|
||||
config: &'a Config,
|
||||
output_path: &'a Path,
|
||||
handler: &'a dyn FormatHandler,
|
||||
) -> Self {
|
||||
Self {
|
||||
terminal,
|
||||
app,
|
||||
config,
|
||||
output_path,
|
||||
handler,
|
||||
command_buffer: String::new(),
|
||||
key_sequence: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the main application loop.
|
||||
pub fn run(&mut self) -> io::Result<()> {
|
||||
while self.app.running {
|
||||
self.terminal
|
||||
.draw(|f| crate::ui::draw(f, self.app, self.config))?;
|
||||
|
||||
if let Event::Key(key) = event::read()? {
|
||||
self.handle_key_event(key)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Primary dispatcher for all keyboard events.
|
||||
fn handle_key_event(&mut self, key: KeyEvent) -> io::Result<()> {
|
||||
match self.app.mode {
|
||||
Mode::Normal => self.handle_normal_mode(key),
|
||||
Mode::Insert => self.handle_insert_mode(key),
|
||||
Mode::Search => self.handle_search_mode(key),
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles keys in Normal mode, separating navigation from command entry.
|
||||
fn handle_normal_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
||||
if !self.command_buffer.is_empty() {
|
||||
self.handle_command_mode(key)
|
||||
} else {
|
||||
self.handle_navigation_mode(key)
|
||||
}
|
||||
}
|
||||
|
||||
/// Logic for entering and executing ":" style commands.
|
||||
fn handle_command_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
||||
match key.code {
|
||||
KeyCode::Enter => {
|
||||
let cmd = self.command_buffer.clone();
|
||||
self.command_buffer.clear();
|
||||
self.execute_command(&cmd)
|
||||
}
|
||||
KeyCode::Esc => {
|
||||
self.command_buffer.clear();
|
||||
self.app.status_message = None;
|
||||
Ok(())
|
||||
}
|
||||
KeyCode::Backspace => {
|
||||
self.command_buffer.pop();
|
||||
self.sync_command_status();
|
||||
Ok(())
|
||||
}
|
||||
KeyCode::Char(c) => {
|
||||
self.command_buffer.push(c);
|
||||
self.sync_command_status();
|
||||
Ok(())
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles primary navigation (j/k) and transitions to insert or command modes.
|
||||
fn handle_navigation_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
||||
if let KeyCode::Char(c) = key.code {
|
||||
self.key_sequence.push(c);
|
||||
|
||||
// Collect all configured keybinds
|
||||
let binds = [
|
||||
(&self.config.keybinds.down, "down"),
|
||||
(&self.config.keybinds.up, "up"),
|
||||
(&self.config.keybinds.edit, "edit"),
|
||||
(&self.config.keybinds.edit_append, "edit_append"),
|
||||
(&self.config.keybinds.edit_substitute, "edit_substitute"),
|
||||
(&self.config.keybinds.search, "search"),
|
||||
(&self.config.keybinds.next_match, "next_match"),
|
||||
(&self.config.keybinds.previous_match, "previous_match"),
|
||||
(&self.config.keybinds.jump_top, "jump_top"),
|
||||
(&self.config.keybinds.jump_bottom, "jump_bottom"),
|
||||
(&self.config.keybinds.append_item, "append_item"),
|
||||
(&self.config.keybinds.prepend_item, "prepend_item"),
|
||||
(&self.config.keybinds.delete_item, "delete_item"),
|
||||
(&self.config.keybinds.undo, "undo"),
|
||||
(&"a".to_string(), "add_missing"),
|
||||
(&":".to_string(), "command"),
|
||||
(&"q".to_string(), "quit"),
|
||||
];
|
||||
|
||||
let mut exact_match = None;
|
||||
let mut prefix_match = false;
|
||||
|
||||
for (bind, action) in binds.iter() {
|
||||
if bind == &&self.key_sequence {
|
||||
exact_match = Some(*action);
|
||||
break;
|
||||
} else if bind.starts_with(&self.key_sequence) {
|
||||
prefix_match = true;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(action) = exact_match {
|
||||
self.key_sequence.clear();
|
||||
match action {
|
||||
"down" => self.app.next(),
|
||||
"up" => self.app.previous(),
|
||||
"edit" => self.app.enter_insert(InsertVariant::Start),
|
||||
"edit_append" => self.app.enter_insert(InsertVariant::End),
|
||||
"edit_substitute" => self.app.enter_insert(InsertVariant::Substitute),
|
||||
"search" => {
|
||||
self.app.mode = Mode::Search;
|
||||
self.app.search_query.clear();
|
||||
self.app.status_message = Some(format!("{} ", self.config.keybinds.search));
|
||||
}
|
||||
"next_match" => self.app.jump_next_match(),
|
||||
"previous_match" => self.app.jump_previous_match(),
|
||||
"jump_top" => self.app.jump_top(),
|
||||
"jump_bottom" => self.app.jump_bottom(),
|
||||
"append_item" => self.app.add_array_item(true),
|
||||
"prepend_item" => self.app.add_array_item(false),
|
||||
"delete_item" => self.app.delete_selected(),
|
||||
"undo" => self.app.undo(),
|
||||
"add_missing" => {
|
||||
self.app.save_undo_state();
|
||||
self.add_missing_item();
|
||||
}
|
||||
"command" => {
|
||||
self.command_buffer.push(':');
|
||||
self.sync_command_status();
|
||||
}
|
||||
"quit" => self.app.running = false,
|
||||
_ => {}
|
||||
}
|
||||
} else if !prefix_match {
|
||||
// Not an exact match and not a prefix for any bind, clear and restart seq
|
||||
self.key_sequence.clear();
|
||||
self.key_sequence.push(c);
|
||||
}
|
||||
} else {
|
||||
// Non-character keys reset the sequence buffer
|
||||
self.key_sequence.clear();
|
||||
match key.code {
|
||||
KeyCode::Down => self.app.next(),
|
||||
KeyCode::Up => self.app.previous(),
|
||||
KeyCode::Enter => self.save_file()?,
|
||||
KeyCode::Esc => self.app.status_message = None,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Adds a missing item from the template to the active configuration.
|
||||
fn add_missing_item(&mut self) {
|
||||
if let Some(var) = self.app.vars.get_mut(self.app.selected) {
|
||||
if var.status == crate::format::ItemStatus::MissingFromActive {
|
||||
var.status = crate::format::ItemStatus::Present;
|
||||
if !var.is_group {
|
||||
var.value = var.template_value.clone();
|
||||
}
|
||||
self.app.sync_input_with_selected();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Delegates key events to the `tui_input` handler during active editing.
|
||||
fn handle_insert_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
||||
match key.code {
|
||||
KeyCode::Esc | KeyCode::Enter => {
|
||||
self.app.enter_normal();
|
||||
}
|
||||
_ => {
|
||||
self.app.input.handle_event(&Event::Key(key));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Handles search mode key events.
|
||||
fn handle_search_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
||||
match key.code {
|
||||
KeyCode::Enter | KeyCode::Esc => {
|
||||
self.app.mode = Mode::Normal;
|
||||
self.app.status_message = None;
|
||||
}
|
||||
KeyCode::Backspace => {
|
||||
self.app.search_query.pop();
|
||||
self.app.status_message = Some(format!("{}{}", self.config.keybinds.search, self.app.search_query));
|
||||
self.app.jump_next_match();
|
||||
}
|
||||
KeyCode::Char(c) => {
|
||||
self.app.search_query.push(c);
|
||||
self.app.status_message = Some(format!("{}{}", self.config.keybinds.search, self.app.search_query));
|
||||
self.app.jump_next_match();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Logic to map command strings (like ":w") to internal application actions.
|
||||
fn execute_command(&mut self, cmd: &str) -> io::Result<()> {
|
||||
if cmd == self.config.keybinds.save {
|
||||
self.save_file()
|
||||
} else if cmd == self.config.keybinds.quit {
|
||||
self.app.running = false;
|
||||
Ok(())
|
||||
} else if cmd == ":wq" {
|
||||
self.save_file()?;
|
||||
self.app.running = false;
|
||||
Ok(())
|
||||
} else {
|
||||
self.app.status_message = Some(format!("Unknown command: {}", cmd));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Attempts to write the current app state to the specified output file.
|
||||
fn save_file(&mut self) -> io::Result<()> {
|
||||
if self.handler.write(self.output_path, &self.app.vars).is_ok() {
|
||||
self.app.status_message = Some(format!("Saved to {}", self.output_path.display()));
|
||||
} else {
|
||||
self.app.status_message = Some("Error saving file".to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Synchronizes the status bar display with the active command buffer.
|
||||
fn sync_command_status(&mut self) {
|
||||
if self.command_buffer.is_empty() {
|
||||
self.app.status_message = None;
|
||||
} else {
|
||||
self.app.status_message = Some(self.command_buffer.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
353
src/ui.rs
353
src/ui.rs
@@ -3,148 +3,311 @@ use crate::config::Config;
|
||||
use ratatui::{
|
||||
Frame,
|
||||
layout::{Constraint, Direction, Layout},
|
||||
style::{Color, Modifier, Style},
|
||||
style::{Modifier, Style},
|
||||
text::{Line, Span},
|
||||
widgets::{Block, Borders, List, ListItem, ListState, Paragraph},
|
||||
widgets::{Block, BorderType, Borders, List, ListItem, ListState, Paragraph},
|
||||
};
|
||||
|
||||
// Catppuccin Mocha Palette
|
||||
const MANTLE: Color = Color::Rgb(24, 24, 37);
|
||||
const BASE: Color = Color::Rgb(30, 30, 46);
|
||||
const TEXT: Color = Color::Rgb(205, 214, 244);
|
||||
const BLUE: Color = Color::Rgb(137, 180, 250);
|
||||
const GREEN: Color = Color::Rgb(166, 227, 161);
|
||||
const SURFACE1: Color = Color::Rgb(69, 71, 90);
|
||||
|
||||
pub fn draw(f: &mut Frame, app: &mut App, _config: &Config) {
|
||||
/// Renders the main application interface using ratatui.
|
||||
pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
||||
let theme = &config.theme;
|
||||
let size = f.area();
|
||||
|
||||
// Theming (defaults to Mocha, can be extended later via _config)
|
||||
let bg_color = BASE;
|
||||
let fg_color = TEXT;
|
||||
let highlight_color = BLUE;
|
||||
let insert_color = GREEN;
|
||||
// Render the main background (optional based on transparency config).
|
||||
if !theme.transparent {
|
||||
f.render_widget(
|
||||
Block::default().style(Style::default().bg(theme.bg_normal())),
|
||||
size,
|
||||
);
|
||||
}
|
||||
|
||||
// Background
|
||||
let block = Block::default().style(Style::default().bg(bg_color).fg(fg_color));
|
||||
f.render_widget(block, size);
|
||||
|
||||
let chunks = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
// Horizontal layout with 1-character side margins.
|
||||
let outer_layout = Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints([
|
||||
Constraint::Min(3), // List
|
||||
Constraint::Length(3), // Input area
|
||||
Constraint::Length(1), // Status bar
|
||||
Constraint::Length(1),
|
||||
Constraint::Min(0),
|
||||
Constraint::Length(1),
|
||||
])
|
||||
.split(size);
|
||||
|
||||
// List
|
||||
// Vertical layout for the main UI components.
|
||||
let chunks = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([
|
||||
Constraint::Length(1), // Top margin
|
||||
Constraint::Min(3), // Main list
|
||||
Constraint::Length(3), // Focused input field
|
||||
Constraint::Length(1), // Spacer
|
||||
Constraint::Length(1), // Status bar
|
||||
])
|
||||
.split(outer_layout[1]);
|
||||
|
||||
// Build the interactive list of configuration variables.
|
||||
let matching_indices = app.matching_indices();
|
||||
let items: Vec<ListItem> = app
|
||||
.vars
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, var)| {
|
||||
let style = if i == app.selected {
|
||||
Style::default()
|
||||
.fg(bg_color)
|
||||
.bg(highlight_color)
|
||||
.add_modifier(Modifier::BOLD)
|
||||
let is_selected = i == app.selected;
|
||||
let is_match = matching_indices.contains(&i);
|
||||
|
||||
// Indentation based on depth
|
||||
let indent = " ".repeat(var.depth);
|
||||
let prefix = if var.is_group { "+ " } else { " " };
|
||||
|
||||
// Determine colors based on depth
|
||||
let depth_color = if is_selected {
|
||||
theme.bg_normal()
|
||||
} else {
|
||||
Style::default().fg(fg_color)
|
||||
match var.depth % 4 {
|
||||
0 => theme.tree_depth_1(),
|
||||
1 => theme.tree_depth_2(),
|
||||
2 => theme.tree_depth_3(),
|
||||
3 => theme.tree_depth_4(),
|
||||
_ => theme.fg_normal(),
|
||||
}
|
||||
};
|
||||
|
||||
let content = format!(" {} = {} ", var.key, var.value);
|
||||
ListItem::new(Line::from(content)).style(style)
|
||||
// Determine colors based on status and selection
|
||||
let text_color = if is_selected {
|
||||
theme.fg_highlight()
|
||||
} else {
|
||||
match var.status {
|
||||
crate::format::ItemStatus::MissingFromActive if !var.is_group => theme.fg_dimmed(),
|
||||
crate::format::ItemStatus::Modified => theme.fg_modified(),
|
||||
_ => theme.fg_normal(),
|
||||
}
|
||||
};
|
||||
|
||||
let key_style = if is_selected {
|
||||
Style::default()
|
||||
.fg(theme.fg_highlight())
|
||||
.add_modifier(Modifier::BOLD)
|
||||
} else if is_match {
|
||||
Style::default()
|
||||
.fg(theme.bg_search())
|
||||
.add_modifier(Modifier::UNDERLINED)
|
||||
} else if var.status == crate::format::ItemStatus::MissingFromActive && !var.is_group {
|
||||
Style::default()
|
||||
.fg(theme.fg_dimmed())
|
||||
.add_modifier(Modifier::DIM)
|
||||
} else {
|
||||
Style::default().fg(depth_color)
|
||||
};
|
||||
|
||||
let mut key_spans = vec![
|
||||
Span::raw(indent),
|
||||
Span::styled(prefix, Style::default().fg(theme.border_normal())),
|
||||
Span::styled(&var.key, key_style),
|
||||
];
|
||||
|
||||
// Add status indicator if not present (only for leaf variables)
|
||||
if !var.is_group {
|
||||
match var.status {
|
||||
crate::format::ItemStatus::MissingFromActive => {
|
||||
let missing_style = if is_selected {
|
||||
Style::default().fg(theme.fg_highlight()).add_modifier(Modifier::BOLD)
|
||||
} else {
|
||||
Style::default().fg(theme.fg_warning()).add_modifier(Modifier::BOLD)
|
||||
};
|
||||
key_spans.push(Span::styled(" (missing)", missing_style));
|
||||
}
|
||||
crate::format::ItemStatus::Modified => {
|
||||
if !is_selected {
|
||||
key_spans.push(Span::styled(" (*)", Style::default().fg(theme.fg_modified())));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let item_style = if is_selected {
|
||||
Style::default().bg(theme.bg_highlight())
|
||||
} else {
|
||||
Style::default().fg(text_color)
|
||||
};
|
||||
|
||||
if var.is_group {
|
||||
ListItem::new(Line::from(key_spans)).style(item_style)
|
||||
} else {
|
||||
// Show live input text for the selected item if in Insert mode.
|
||||
let val = if is_selected && matches!(app.mode, Mode::Insert) {
|
||||
app.input.value()
|
||||
} else {
|
||||
var.value.as_deref().unwrap_or("")
|
||||
};
|
||||
|
||||
let value_style = if is_selected {
|
||||
Style::default().fg(theme.fg_highlight())
|
||||
} else {
|
||||
Style::default().fg(theme.fg_normal())
|
||||
};
|
||||
|
||||
let mut val_spans = vec![
|
||||
Span::raw(format!("{} └─ ", " ".repeat(var.depth))),
|
||||
Span::styled(val, value_style),
|
||||
];
|
||||
|
||||
if let Some(t_val) = &var.template_value {
|
||||
if Some(t_val) != var.value.as_ref() {
|
||||
let t_style = if is_selected {
|
||||
Style::default().fg(theme.bg_normal()).add_modifier(Modifier::DIM)
|
||||
} else {
|
||||
Style::default().fg(theme.fg_dimmed()).add_modifier(Modifier::ITALIC)
|
||||
};
|
||||
val_spans.push(Span::styled(format!(" [Def: {}]", t_val), t_style));
|
||||
}
|
||||
}
|
||||
|
||||
ListItem::new(vec![Line::from(key_spans), Line::from(val_spans)]).style(item_style)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let list = List::new(items)
|
||||
.block(
|
||||
Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.title(" Environment Variables ")
|
||||
.border_style(Style::default().fg(SURFACE1)),
|
||||
)
|
||||
.highlight_style(
|
||||
Style::default()
|
||||
.fg(bg_color)
|
||||
.bg(highlight_color)
|
||||
.add_modifier(Modifier::BOLD),
|
||||
);
|
||||
let list = List::new(items).block(
|
||||
Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.border_type(BorderType::Rounded)
|
||||
.title(" Config Variables ")
|
||||
.title_style(
|
||||
Style::default()
|
||||
.fg(theme.fg_accent())
|
||||
.add_modifier(Modifier::BOLD),
|
||||
)
|
||||
.border_style(Style::default().fg(theme.border_normal())),
|
||||
);
|
||||
|
||||
let mut state = ListState::default();
|
||||
state.select(Some(app.selected));
|
||||
f.render_stateful_widget(list, chunks[0], &mut state);
|
||||
f.render_stateful_widget(list, chunks[1], &mut state);
|
||||
|
||||
// Input Area
|
||||
// Render the focused input area.
|
||||
let current_var = app.vars.get(app.selected);
|
||||
let input_title = if let Some(var) = current_var {
|
||||
if var.default_value.is_empty() {
|
||||
format!(" Editing: {} ", var.key)
|
||||
let mut input_title = " Input ".to_string();
|
||||
let mut extra_info = String::new();
|
||||
|
||||
if let Some(var) = current_var {
|
||||
if var.is_group {
|
||||
input_title = format!(" Group: {} ", var.path);
|
||||
} else {
|
||||
format!(" Editing: {} (Default: {}) ", var.key, var.default_value)
|
||||
input_title = format!(" Editing: {} ", var.path);
|
||||
if let Some(t_val) = &var.template_value {
|
||||
extra_info = format!(" [Template: {}]", t_val);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let input_border_color = match app.mode {
|
||||
Mode::Insert => theme.border_active(),
|
||||
Mode::Normal | Mode::Search => theme.border_normal(),
|
||||
};
|
||||
|
||||
let input_text = app.input.value();
|
||||
let cursor_pos = app.input.visual_cursor();
|
||||
|
||||
// Show template value in normal mode if it differs
|
||||
let display_text = if let Some(var) = current_var {
|
||||
if var.is_group {
|
||||
"<group>".to_string()
|
||||
} else if matches!(app.mode, Mode::Normal) {
|
||||
format!("{}{}", input_text, extra_info)
|
||||
} else {
|
||||
input_text.to_string()
|
||||
}
|
||||
} else {
|
||||
" Input ".to_string()
|
||||
input_text.to_string()
|
||||
};
|
||||
|
||||
let input_color = match app.mode {
|
||||
Mode::Insert => insert_color,
|
||||
Mode::Normal => SURFACE1,
|
||||
};
|
||||
|
||||
let input_text = if let Some(var) = current_var {
|
||||
var.value.as_str()
|
||||
} else {
|
||||
""
|
||||
};
|
||||
|
||||
let input = Paragraph::new(input_text)
|
||||
.style(Style::default().fg(fg_color))
|
||||
let input = Paragraph::new(display_text)
|
||||
.style(Style::default().fg(theme.fg_normal()))
|
||||
.block(
|
||||
Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.border_type(BorderType::Rounded)
|
||||
.title(input_title)
|
||||
.border_style(Style::default().fg(input_color)),
|
||||
.title_style(
|
||||
Style::default()
|
||||
.fg(theme.fg_accent()) // Make title pop
|
||||
.add_modifier(Modifier::BOLD),
|
||||
)
|
||||
.border_style(Style::default().fg(input_border_color)),
|
||||
);
|
||||
f.render_widget(input, chunks[1]);
|
||||
f.render_widget(input, chunks[2]);
|
||||
|
||||
// Position the terminal cursor correctly when in Insert mode.
|
||||
if let Mode::Insert = app.mode {
|
||||
let input_area = chunks[1];
|
||||
// Cursor positioning
|
||||
f.set_cursor_position(ratatui::layout::Position::new(
|
||||
input_area.x + 1 + input_text.chars().count() as u16,
|
||||
input_area.y + 1,
|
||||
chunks[2].x + 1 + cursor_pos as u16,
|
||||
chunks[2].y + 1,
|
||||
));
|
||||
}
|
||||
|
||||
// Status bar
|
||||
let status_style = Style::default().bg(MANTLE).fg(fg_color);
|
||||
let mode_str = match app.mode {
|
||||
Mode::Normal => " NORMAL ",
|
||||
Mode::Insert => " INSERT ",
|
||||
};
|
||||
let mode_style = match app.mode {
|
||||
Mode::Normal => Style::default()
|
||||
.bg(BLUE)
|
||||
.fg(bg_color)
|
||||
.add_modifier(Modifier::BOLD),
|
||||
Mode::Insert => Style::default()
|
||||
.bg(GREEN)
|
||||
.fg(bg_color)
|
||||
.add_modifier(Modifier::BOLD),
|
||||
// Render the modern pill-style status bar.
|
||||
let (mode_str, mode_style) = match app.mode {
|
||||
Mode::Normal => (
|
||||
" NORMAL ",
|
||||
Style::default()
|
||||
.bg(theme.bg_highlight())
|
||||
.fg(theme.bg_normal())
|
||||
.add_modifier(Modifier::BOLD),
|
||||
),
|
||||
Mode::Insert => (
|
||||
" INSERT ",
|
||||
Style::default()
|
||||
.bg(theme.bg_active())
|
||||
.fg(theme.bg_normal())
|
||||
.add_modifier(Modifier::BOLD),
|
||||
),
|
||||
Mode::Search => (
|
||||
" SEARCH ",
|
||||
Style::default()
|
||||
.bg(theme.bg_search())
|
||||
.fg(theme.bg_normal())
|
||||
.add_modifier(Modifier::BOLD),
|
||||
),
|
||||
};
|
||||
|
||||
let status_msg = app
|
||||
.status_message
|
||||
.as_deref()
|
||||
.unwrap_or(" j/k: navigate | i: edit | :w/Enter: save | q/:q: quit ");
|
||||
let status_msg = if let Some(msg) = &app.status_message {
|
||||
msg.clone()
|
||||
} else {
|
||||
let kb = &config.keybinds;
|
||||
match app.mode {
|
||||
Mode::Normal => {
|
||||
let mut parts = vec![
|
||||
format!("{}/{} move", kb.down, kb.up),
|
||||
format!("{}/{} jump", kb.jump_top, kb.jump_bottom),
|
||||
format!("{} search", kb.search),
|
||||
];
|
||||
if !app.selected_is_group() {
|
||||
parts.push(format!("{}/{}/{} edit", kb.edit, kb.edit_append, kb.edit_substitute));
|
||||
}
|
||||
if app.selected_is_missing() {
|
||||
parts.push(format!("{} add", "a")); // 'a' is currently hardcoded in runner
|
||||
}
|
||||
if app.selected_is_array() {
|
||||
parts.push(format!("{}/{} array", kb.append_item, kb.prepend_item));
|
||||
}
|
||||
parts.push(format!("{} del", kb.delete_item));
|
||||
parts.push(format!("{} undo", kb.undo));
|
||||
parts.push(format!("{} save", kb.save));
|
||||
parts.push(format!("{} quit", kb.quit));
|
||||
parts.join(" · ")
|
||||
}
|
||||
Mode::Insert => "Esc normal · Enter commit".to_string(),
|
||||
Mode::Search => "Esc normal · type to filter".to_string(),
|
||||
}
|
||||
};
|
||||
|
||||
let status_line = Line::from(vec![
|
||||
Span::styled(mode_str, mode_style),
|
||||
Span::styled(format!(" {} ", status_msg), status_style),
|
||||
Span::styled(
|
||||
format!(" {} ", status_msg),
|
||||
Style::default().bg(theme.border_normal()).fg(theme.fg_normal()),
|
||||
),
|
||||
]);
|
||||
|
||||
let status = Paragraph::new(status_line).style(status_style);
|
||||
f.render_widget(status, chunks[2]);
|
||||
let status = Paragraph::new(status_line).style(Style::default().bg(theme.border_normal()));
|
||||
f.render_widget(status, chunks[4]);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user