Compare commits
44
Commits
v0.3.0
...
4c59e6edaa
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4c59e6edaa | ||
|
|
e8634c17a2 | ||
|
|
2e974e0503 | ||
|
|
8dc96d4605 | ||
|
|
37798d5deb | ||
|
|
311f514414 | ||
|
|
53dc317d7d | ||
|
|
f959509538 | ||
|
|
b07a2d8f75 | ||
|
|
c773fdf472 | ||
|
|
029b4f9da8 | ||
|
|
ee85be4e6b | ||
|
|
31dc062ce5 | ||
|
|
50278821ca | ||
|
|
e3510a96fb | ||
|
|
51625ed296 | ||
|
|
ca7ebc9563 | ||
|
|
a2ec8660c7 | ||
|
|
30fd2d5d75 | ||
|
|
277d8aa151 | ||
|
|
5056f8dd0a | ||
|
|
b3651aa5dd | ||
|
|
b8c49d4c13 | ||
|
|
b88d93c800 | ||
|
|
a58906a2a4 | ||
|
|
cffea6d806 | ||
|
|
fca84f5820 | ||
|
|
1bc4c00e23 | ||
|
|
0d15c61d67 | ||
|
|
0f26f7ac76 | ||
|
|
184386a96b | ||
|
|
69d4963e4f | ||
|
|
87ced5a47c | ||
|
|
f85dac3b25 | ||
|
|
1d9342186a | ||
|
|
f6a84416e6 | ||
|
|
01a7bd44b7 | ||
|
|
f123f2d6df | ||
|
|
94ff632b39 | ||
|
|
e09cc3f2d7 | ||
|
|
f09dbc8321 | ||
|
|
4e5c0e3b07 | ||
|
|
c270d37585 | ||
|
|
7aa45974a7 |
No files matched your search
Generated
+116
-12
@@ -247,6 +247,26 @@ dependencies = [
|
|||||||
"static_assertions",
|
"static_assertions",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "const-random"
|
||||||
|
version = "0.1.18"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359"
|
||||||
|
dependencies = [
|
||||||
|
"const-random-macro",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "const-random-macro"
|
||||||
|
version = "0.1.16"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e"
|
||||||
|
dependencies = [
|
||||||
|
"getrandom 0.2.17",
|
||||||
|
"once_cell",
|
||||||
|
"tiny-keccak",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "convert_case"
|
name = "convert_case"
|
||||||
version = "0.10.0"
|
version = "0.10.0"
|
||||||
@@ -292,6 +312,12 @@ dependencies = [
|
|||||||
"winapi",
|
"winapi",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "crunchy"
|
||||||
|
version = "0.2.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "crypto-common"
|
name = "crypto-common"
|
||||||
version = "0.1.7"
|
version = "0.1.7"
|
||||||
@@ -414,6 +440,15 @@ dependencies = [
|
|||||||
"windows-sys",
|
"windows-sys",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "dlv-list"
|
||||||
|
version = "0.5.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "442039f5147480ba31067cb00ada1adae6892028e40e45fc5de7b7df6dcc1b5f"
|
||||||
|
dependencies = [
|
||||||
|
"const-random",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "document-features"
|
name = "document-features"
|
||||||
version = "0.2.12"
|
version = "0.2.12"
|
||||||
@@ -429,6 +464,15 @@ version = "1.15.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
|
checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "encoding_rs"
|
||||||
|
version = "0.8.35"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "env_filter"
|
name = "env_filter"
|
||||||
version = "1.0.0"
|
version = "1.0.0"
|
||||||
@@ -580,6 +624,12 @@ dependencies = [
|
|||||||
"wasip3",
|
"wasip3",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "hashbrown"
|
||||||
|
version = "0.14.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "hashbrown"
|
name = "hashbrown"
|
||||||
version = "0.15.5"
|
version = "0.15.5"
|
||||||
@@ -679,6 +729,17 @@ version = "1.0.17"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
|
checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "java-properties"
|
||||||
|
version = "2.0.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "37bf6f484471c451f2b51eabd9e66b3fa7274550c5ec4b6c3d6070840945117f"
|
||||||
|
dependencies = [
|
||||||
|
"encoding_rs",
|
||||||
|
"lazy_static",
|
||||||
|
"regex",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "jiff"
|
name = "jiff"
|
||||||
version = "0.2.23"
|
version = "0.2.23"
|
||||||
@@ -853,15 +914,18 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mould"
|
name = "mould"
|
||||||
version = "0.2.1"
|
version = "0.6.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"clap",
|
"clap",
|
||||||
"crossterm",
|
"crossterm",
|
||||||
"dirs",
|
"dirs",
|
||||||
"env_logger",
|
"env_logger",
|
||||||
|
"java-properties",
|
||||||
"log",
|
"log",
|
||||||
|
"quick-xml",
|
||||||
"ratatui",
|
"ratatui",
|
||||||
|
"rust-ini",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"serde_yaml",
|
"serde_yaml",
|
||||||
@@ -956,6 +1020,16 @@ dependencies = [
|
|||||||
"num-traits",
|
"num-traits",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ordered-multimap"
|
||||||
|
version = "0.7.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "49203cdcae0030493bad186b28da2fa25645fa276a51b6fec8010d281e02ef79"
|
||||||
|
dependencies = [
|
||||||
|
"dlv-list",
|
||||||
|
"hashbrown 0.14.5",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "parking_lot"
|
name = "parking_lot"
|
||||||
version = "0.12.5"
|
version = "0.12.5"
|
||||||
@@ -1114,6 +1188,16 @@ dependencies = [
|
|||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "quick-xml"
|
||||||
|
version = "0.39.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "958f21e8e7ceb5a1aa7fa87fab28e7c75976e0bfe7e23ff069e0a260f894067d"
|
||||||
|
dependencies = [
|
||||||
|
"memchr",
|
||||||
|
"serde",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "quote"
|
name = "quote"
|
||||||
version = "1.0.45"
|
version = "1.0.45"
|
||||||
@@ -1284,6 +1368,16 @@ version = "0.8.10"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
|
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rust-ini"
|
||||||
|
version = "0.21.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "796e8d2b6696392a43bea58116b667fb4c29727dc5abd27d6acf338bb4f688c7"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"ordered-multimap",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rustc_version"
|
name = "rustc_version"
|
||||||
version = "0.4.1"
|
version = "0.4.1"
|
||||||
@@ -1366,6 +1460,7 @@ version = "1.0.149"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
|
checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"indexmap",
|
||||||
"itoa",
|
"itoa",
|
||||||
"memchr",
|
"memchr",
|
||||||
"serde",
|
"serde",
|
||||||
@@ -1642,10 +1737,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca"
|
checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "toml"
|
name = "tiny-keccak"
|
||||||
version = "1.0.6+spec-1.1.0"
|
version = "2.0.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "399b1124a3c9e16766831c6bba21e50192572cdd98706ea114f9502509686ffc"
|
checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237"
|
||||||
|
dependencies = [
|
||||||
|
"crunchy",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "toml"
|
||||||
|
version = "1.0.7+spec-1.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "dd28d57d8a6f6e458bc0b8784f8fdcc4b99a437936056fa122cb234f18656a96"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"indexmap",
|
"indexmap",
|
||||||
"serde_core",
|
"serde_core",
|
||||||
@@ -1658,27 +1762,27 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "toml_datetime"
|
name = "toml_datetime"
|
||||||
version = "1.0.0+spec-1.1.0"
|
version = "1.0.1+spec-1.1.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "32c2555c699578a4f59f0cc68e5116c8d7cabbd45e1409b989d4be085b53f13e"
|
checksum = "9b320e741db58cac564e26c607d3cc1fdc4a88fd36c879568c07856ed83ff3e9"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde_core",
|
"serde_core",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "toml_parser"
|
name = "toml_parser"
|
||||||
version = "1.0.9+spec-1.1.0"
|
version = "1.0.10+spec-1.1.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "702d4415e08923e7e1ef96cd5727c0dfed80b4d2fa25db9647fe5eb6f7c5a4c4"
|
checksum = "7df25b4befd31c4816df190124375d5a20c6b6921e2cad937316de3fccd63420"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"winnow",
|
"winnow",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "toml_writer"
|
name = "toml_writer"
|
||||||
version = "1.0.6+spec-1.1.0"
|
version = "1.0.7+spec-1.1.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ab16f14aed21ee8bfd8ec22513f7287cd4a91aa92e44edfe2c17ddd004e92607"
|
checksum = "f17aaa1c6e3dc22b1da4b6bba97d066e354c7945cac2f7852d4e4e7ca7a6b56d"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tui-input"
|
name = "tui-input"
|
||||||
@@ -1990,9 +2094,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "winnow"
|
name = "winnow"
|
||||||
version = "0.7.15"
|
version = "1.0.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
|
checksum = "a90e88e4667264a994d34e6d1ab2d26d398dcdca8b7f52bec8668957517fc7d8"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wit-bindgen"
|
name = "wit-bindgen"
|
||||||
|
|||||||
+28
-7
@@ -1,8 +1,8 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "mould"
|
|
||||||
version = "0.3.0"
|
|
||||||
edition = "2024"
|
|
||||||
authors = ["Nils Pukropp <nils@narl.io>"]
|
authors = ["Nils Pukropp <nils@narl.io>"]
|
||||||
|
edition = "2024"
|
||||||
|
name = "mould"
|
||||||
|
version = "0.6.0"
|
||||||
|
|
||||||
[[bin]]
|
[[bin]]
|
||||||
name = "mould"
|
name = "mould"
|
||||||
@@ -10,18 +10,39 @@ path = "src/main.rs"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow = "1.0.102"
|
anyhow = "1.0.102"
|
||||||
clap = { version = "4.6.0", features = ["derive"] }
|
|
||||||
crossterm = "0.29.0"
|
crossterm = "0.29.0"
|
||||||
dirs = "6.0.0"
|
dirs = "6.0.0"
|
||||||
env_logger = "0.11.9"
|
env_logger = "0.11.9"
|
||||||
|
java-properties = "2.0.0"
|
||||||
log = "0.4.29"
|
log = "0.4.29"
|
||||||
ratatui = "0.30.0"
|
ratatui = "0.30.0"
|
||||||
serde = { version = "1.0.228", features = ["derive"] }
|
rust-ini = "0.21.3"
|
||||||
serde_json = "1.0.149"
|
|
||||||
serde_yaml = "0.9.34"
|
serde_yaml = "0.9.34"
|
||||||
thiserror = "2.0.18"
|
thiserror = "2.0.18"
|
||||||
toml = "1.0.6"
|
|
||||||
tui-input = "0.15.0"
|
tui-input = "0.15.0"
|
||||||
|
|
||||||
|
[dependencies.serde]
|
||||||
|
version = "1.0.228"
|
||||||
|
features = ["derive"]
|
||||||
|
|
||||||
|
[dependencies.serde_json]
|
||||||
|
version = "1.0.149"
|
||||||
|
features = ["preserve_order"]
|
||||||
|
|
||||||
|
[dependencies.toml]
|
||||||
|
version = "1.0.7"
|
||||||
|
features = ["preserve_order"]
|
||||||
|
|
||||||
|
[dependencies.clap]
|
||||||
|
version = "4.6.0"
|
||||||
|
features = ["derive"]
|
||||||
|
|
||||||
|
[dependencies.quick-xml]
|
||||||
|
version = "0.39.2"
|
||||||
|
features = [
|
||||||
|
"serde",
|
||||||
|
"serialize",
|
||||||
|
]
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tempfile = "3.27.0"
|
tempfile = "3.27.0"
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
[[bin]]
|
|
||||||
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_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.3.0"
|
|
||||||
@@ -1,40 +1,61 @@
|
|||||||
# mould
|
# mould
|
||||||
|
|
||||||
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.
|
`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`, `TOML`, `XML`, `INI`, or `Properties` configurations, `mould` provides a fast, Vim-inspired workflow to get your environment ready.
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **Universal Format Support**: Handle `.env`, `JSON`, `YAML`, and `TOML` seamlessly.
|
- **Universal Format Support**: Read, edit, and write `.env`, `JSON`, `YAML`, `TOML`, `XML`, `INI`, and `Properties` files seamlessly.
|
||||||
- **Hierarchical Flattening**: Edit nested data structures (JSON, YAML, TOML) in a flat, searchable list.
|
- **Tree View Navigation**: Edit nested data structures in a depth-colored tree view, with foldable groups so a large `docker-compose.yml` stays readable.
|
||||||
- **Docker Compose Integration**: Automatically generate `docker-compose.override.yml` from `docker-compose.yml`.
|
- **Smart Template Discovery**: Rule-based resolver automatically discovers relationships (e.g., `.env.example` vs `.env`, `config.template.properties` vs `config.properties`) and highlights missing keys.
|
||||||
- **Vim-inspired Workflow**: Navigate with `j`/`k`, edit with `i`, and save with `:w`.
|
- **Strict Type Preservation**: Intelligently preserves data types (integers, booleans, strings) during edit-save cycles, ensuring your configuration stays valid.
|
||||||
- **Modern UI**: A polished, rounded interface featuring the Catppuccin Mocha palette.
|
- **Nothing Written Behind Your Back**: Keys that exist only in the template are marked `(missing)` and stay out of the output until you pull them in with `<Space>` (or `A` for all of them).
|
||||||
- **Highly Configurable**: Customize keybindings and themes via a simple TOML configuration.
|
- **Comment Preservation**: `.env` comments and blank lines survive a save, so the documentation in your `.env.example` is not the price of using the tool.
|
||||||
- **Dynamic Alignment**: Automatically aligns keys and values for perfect vertical readability.
|
- **Discoverable**: A header names the file being written and the template it is compared against; `?` opens the full keybinding reference, built from *your* config.
|
||||||
- **Default Value Visibility**: Keep track of original template values while editing.
|
- **Advanced Undo/Redo Engine**: Features a tree-based undo/redo history that ensures you never lose changes during complex branching edits. It properly tracks all modifications, including nested renames and item additions/deletions.
|
||||||
- **Incremental Merging**: Load existing values from an output file to continue where you left off.
|
- **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 with support for terminal transparency.
|
||||||
|
- **Highly Configurable**: Customize keybindings and semantic themes via a simple TOML user configuration.
|
||||||
|
- **Neovim Integration**: Comes with a built-in Neovim plugin for seamless in-editor configuration management.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
|
### 1. CLI Application
|
||||||
|
|
||||||
Ensure you have Rust and Cargo installed, then run:
|
Ensure you have Rust and Cargo installed, then run:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
|
# Install directly from the local path
|
||||||
cargo install --path .
|
cargo install --path .
|
||||||
```
|
```
|
||||||
|
|
||||||
Alternatively, you can build from source:
|
Alternatively, you can build from source:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
git clone <repository_url>
|
git clone https://git.narl.io/nvrl/mould-rs
|
||||||
cd mould
|
cd mould-rs
|
||||||
cargo build --release
|
cargo build --release
|
||||||
|
# The executable will be located in target/release/mould
|
||||||
```
|
```
|
||||||
|
|
||||||
The binary will be installed as `mould`.
|
### 2. Neovim Plugin
|
||||||
|
|
||||||
|
If you want to use `mould` directly inside Neovim, the repository includes a built-in Lua plugin that opens `mould` in a floating terminal buffer and synchronizes the file upon exit.
|
||||||
|
|
||||||
|
**Using `mini.deps`:**
|
||||||
|
```lua
|
||||||
|
add({
|
||||||
|
source = 'https://git.narl.io/nvrl/mould-rs',
|
||||||
|
checkout = 'main',
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
Provide an input template file to start editing:
|
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 live diffing.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
mould .env.example
|
mould .env.example
|
||||||
@@ -42,56 +63,190 @@ mould docker-compose.yml
|
|||||||
mould config.template.json -o config.json
|
mould config.template.json -o config.json
|
||||||
```
|
```
|
||||||
|
|
||||||
|
If you just run `mould` in a directory, it will automatically look for common template patterns like `.env.example` or `docker-compose.yml`.
|
||||||
|
|
||||||
|
### Inside Neovim
|
||||||
|
|
||||||
|
Open any configuration file in Neovim and run `:Mould`. It will launch a floating window targeting your active buffer.
|
||||||
|
|
||||||
### Keybindings (Default)
|
### Keybindings (Default)
|
||||||
|
|
||||||
- **Normal Mode**
|
Press `?` inside `mould` for the same list, rendered from your own configuration.
|
||||||
- `j` / `Down`: Move selection down
|
|
||||||
- `k` / `Up`: Move selection up
|
|
||||||
- `i`: Edit the value of the currently selected key (Enter Insert Mode)
|
|
||||||
- `/`: 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**
|
**Navigate**
|
||||||
- Type your value for the selected key.
|
|
||||||
- Arrow keys: Navigate within the input field
|
- `j` / `k` (or arrow keys): Move the selection
|
||||||
- `Enter` / `Esc`: Commit the value and return to Normal Mode
|
- `gg` / `G`: Jump to the top / bottom
|
||||||
|
- `Tab` or `za`: Fold or unfold the selected group
|
||||||
|
- `zM` / `zR`: Fold / unfold everything
|
||||||
|
- `/`: Search over keys *and* values. `Enter` keeps the query for `n` / `N`; `Esc` cancels and restores the cursor
|
||||||
|
- `n` / `N`: Jump to the next / previous match
|
||||||
|
|
||||||
|
**Edit**
|
||||||
|
|
||||||
|
- `i`: Edit the value with the cursor at the start. On a group, renames it instead
|
||||||
|
- `a`: Edit the value with the cursor at the end
|
||||||
|
- `s` / `S`: Replace the value (clears it first)
|
||||||
|
- `r`: Rename the current key or group (array indices cannot be renamed)
|
||||||
|
|
||||||
|
**Structure**
|
||||||
|
|
||||||
|
- `o` / `O`: Add an item below / above (as a sibling, or as an array element)
|
||||||
|
- `alt+o` / `alt+O`: Add a child group below / above
|
||||||
|
- `t`: Toggle the selected item between a group and a plain value
|
||||||
|
- `dd`: Delete the selected item and everything nested under it
|
||||||
|
|
||||||
|
**Template**
|
||||||
|
|
||||||
|
- `Space`: Take the template default for the selected `(missing)` entry
|
||||||
|
- `A`: Take every missing template default at once
|
||||||
|
|
||||||
|
**History**
|
||||||
|
|
||||||
|
- `u` / `U`: Undo / redo
|
||||||
|
- `g-` / `g+`: Switch between alternative branches of the undo tree
|
||||||
|
|
||||||
|
**Session**
|
||||||
|
|
||||||
|
- `?`: Toggle the keybinding reference
|
||||||
|
- `:`: Open the command prompt
|
||||||
|
- `q`: Quit (refused while there are unsaved changes)
|
||||||
|
|
||||||
|
**Commands**
|
||||||
|
|
||||||
|
- `:w`: Write the output file
|
||||||
|
- `:w <path>`: Write somewhere else, and keep writing there
|
||||||
|
- `:q`: Quit; `:q!` quits and discards changes
|
||||||
|
- `:wq` or `:x`: Write and quit
|
||||||
|
|
||||||
|
**Insert / Rename Modes**
|
||||||
|
|
||||||
|
- Type your value or key. Arrow keys navigate within the field
|
||||||
|
- `Enter`: Commit and return to Normal mode. Renames are checked for collisions
|
||||||
|
- `Esc`: Cancel. An item you just created and never named is removed again
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
mould can be configured using a `config.toml` file located in your user configuration directory (e.g., `~/.config/mould/config.toml` on Linux/macOS).
|
`mould` can be configured using a `config.toml` file located in your user configuration directory:
|
||||||
|
- **Linux/macOS**: `~/.config/mould/config.toml`
|
||||||
|
- **Windows**: `%AppData%\mould\config.toml`
|
||||||
|
|
||||||
Example configuration:
|
Example configuration:
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
|
[theme]
|
||||||
|
transparent = false
|
||||||
|
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]
|
[keybinds]
|
||||||
|
# A binding may list alternatives separated by commas.
|
||||||
|
# Named keys are written in angle brackets: <Space>, <Tab>.
|
||||||
down = "j"
|
down = "j"
|
||||||
up = "k"
|
up = "k"
|
||||||
edit = "i"
|
edit = "i"
|
||||||
|
edit_append = "a"
|
||||||
|
edit_substitute = "s,S"
|
||||||
save = ":w"
|
save = ":w"
|
||||||
quit = ":q"
|
quit = ":q"
|
||||||
normal_mode = "Esc"
|
quit_key = "q"
|
||||||
|
command = ":"
|
||||||
[theme]
|
search = "/"
|
||||||
# Enable transparency to let your terminal background show through
|
next_match = "n"
|
||||||
transparent = false
|
previous_match = "N"
|
||||||
|
jump_top = "gg"
|
||||||
# Custom color palette (Catppuccin Mocha defaults)
|
jump_bottom = "G"
|
||||||
crust = "#11111b"
|
append_item = "o"
|
||||||
surface0 = "#313244"
|
prepend_item = "O"
|
||||||
surface1 = "#45475a"
|
delete_item = "dd"
|
||||||
text = "#cdd6f4"
|
undo = "u"
|
||||||
blue = "#89b4fa"
|
redo = "U"
|
||||||
green = "#a6e3a1"
|
undo_branch_prev = "g-"
|
||||||
lavender = "#b4befe"
|
undo_branch_next = "g+"
|
||||||
mauve = "#cba6f7"
|
rename = "r"
|
||||||
peach = "#fab387"
|
append_group = "alt+o"
|
||||||
|
prepend_group = "alt+O"
|
||||||
|
toggle_group = "t"
|
||||||
|
add_missing = "<Space>"
|
||||||
|
accept_all = "A"
|
||||||
|
toggle_fold = "<Tab>,za"
|
||||||
|
fold_all = "zM"
|
||||||
|
unfold_all = "zR"
|
||||||
|
help = "?"
|
||||||
```
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Development & Architecture
|
||||||
|
|
||||||
|
`mould` is written in Rust and architected to decouple the file format parsing from the UI representation. This allows the TUI to render complex, nested configuration files in a unified tree-view.
|
||||||
|
|
||||||
|
### Core Architectural Principles:
|
||||||
|
|
||||||
|
- **Separation of Concerns**: Clear boundaries between UI rendering, application state, input handling, and file format logic.
|
||||||
|
- **Unified Data Model**: All parsed configuration data is normalized into a single `Vec<ConfigItem>` structure, simplifying application logic across different file types.
|
||||||
|
- **Vim-inspired Modality**: The application operates in distinct modes (`Normal`, `Insert`, `InsertKey`, `Search`, `Help`), each with specific keybinding behaviors, enabling efficient interaction.
|
||||||
|
- **One Keybinding Table**: Every Normal-mode key resolves through `KeybindsConfig::resolved()`, so a rebind takes effect in the dispatcher, the status-bar hints and the help overlay at once. `KeybindsConfig::conflicts()` reports any key bound to two actions rather than letting one silently shadow the other.
|
||||||
|
- **Non-linear Undo/Redo**: A robust undo tree allows users to revert and re-apply changes across complex branching edit histories.
|
||||||
|
|
||||||
|
### Key Components
|
||||||
|
|
||||||
|
1. **State Management & Undo Tree (`src/app.rs` & `src/undo.rs`)**
|
||||||
|
* The central state is maintained in the `App` struct, which tracks the currently loaded configuration variables, application modes, and user input buffer.
|
||||||
|
* It integrates an **UndoTree**, providing non-linear, branching history tracking for complex edits (additions, deletions, nested renaming). Each significant state change (`save_undo_state`) pushes a snapshot to this tree.
|
||||||
|
|
||||||
|
2. **Unified Data Model (`src/format/mod.rs`)**
|
||||||
|
* Regardless of the underlying file format (JSON, YAML, .env, etc.), all data is translated into a flattened `Vec<ConfigItem>`.
|
||||||
|
* A `ConfigItem` represents a single configuration entry. It contains:
|
||||||
|
* `key`: The display key (e.g., `port` or `[0]`).
|
||||||
|
* `path`: A `Vec<PathSegment>` (composed of `PathSegment::Key(String)` for object keys and `PathSegment::Index(usize)` for array indices) that defines its full hierarchical location.
|
||||||
|
* `value`: `Option<String>` holding the actual value.
|
||||||
|
* `is_group`: A boolean indicating if this item is a structural node (object or array).
|
||||||
|
* `status`: (`ItemStatus::Present`, `MissingFromActive`, `Overridden`) reflecting comparison with a template. Whether *you* edited an entry is tracked separately by `dirty`, so a config that legitimately differs from its example file does not render as if every line had just been touched.
|
||||||
|
* `value_type`: (`ValueType::String`, `Number`, `Bool`, `Null`) to ensure type preservation during writes.
|
||||||
|
* `collapsed` / `leading_trivia`: fold state, and the comment lines that preceded the entry in the source file.
|
||||||
|
|
||||||
|
3. **Format Handlers (`src/format/*`)**
|
||||||
|
* Each file format has a dedicated handler (`EnvHandler`, `IniHandler`, `HierarchicalHandler`, `PropertiesHandler`) implementing the `FormatHandler` trait.
|
||||||
|
* **`HierarchicalHandler`**: A generalized processor leveraging `serde_json::Value` as an intermediary layer to parse and write nested `JSON`, `YAML`, `TOML`, and even `XML` (via `quick-xml` transposition). This allows complex structures to be flattened for editing and then re-nested accurately.
|
||||||
|
* These handlers are responsible for translating between the file's native format and the `Vec<ConfigItem>` internal representation.
|
||||||
|
|
||||||
|
4. **Template Resolver (`src/resolver.rs`)**
|
||||||
|
* Automatically determines template-active file pairings without explicit user instruction.
|
||||||
|
* Uses hardcoded exact rules (e.g., `compose.yml` -> `compose.override.yml`) and generic fallback rules to strip `.example` or `.template` suffixes to find target output files dynamically.
|
||||||
|
|
||||||
|
5. **Terminal UI & Event Loop (`src/ui.rs` & `src/runner.rs`)**
|
||||||
|
* **UI Rendering (`src/ui.rs`)**: Powered by the `ratatui` library. Renders a flexible layout consisting of a styled hierarchical list, an active input field for editing, and a dynamic status bar.
|
||||||
|
* **Event Runner (`src/runner.rs`)**: Powered by `crossterm`. It polls for events rather than blocking, so terminal resizes and expiring status messages repaint without waiting for a keystroke. It resolves multi-key sequences (like `dd` or `gg`), delegates character input to the `tui-input` backend during active editing, and dispatches actions to mutate the `App` state.
|
||||||
|
|
||||||
|
6. **Neovim Plugin (`lua/mould/init.lua`)**
|
||||||
|
* Implements a Lua wrapper that calculates terminal geometries and launches the CLI `mould` binary inside an ephemeral, floating terminal buffer, ensuring automatic Neovim `checktime` synchronization upon `mould`'s exit.
|
||||||
|
|
||||||
|
### Development Process Highlights:
|
||||||
|
|
||||||
|
- **Iterative Refinement**: Features like key renaming, group creation, and advanced undo/redo were developed iteratively, responding to user feedback and progressively enhancing the core data model and interaction logic.
|
||||||
|
- **Robust Error Handling**: Key functions (`commit_input`, `enter_insert_key`) include collision detection and validation to ensure data integrity during user modifications.
|
||||||
|
- **Modality-driven Design**: The introduction of `InsertKey` mode and careful handling of `InsertVariant` demonstrates a commitment to a precise, context-aware user experience, minimizing ambiguity during editing.
|
||||||
|
- **Debugging and Performance**: Issues like UI "hangs" were traced to subtle interactions in key event processing and input buffer management, leading to refactored key sequence logic for improved responsiveness.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
|
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
|
||||||
+45
-28
@@ -7,43 +7,60 @@
|
|||||||
transparent = false
|
transparent = false
|
||||||
|
|
||||||
# Colors are specified in hex format ("#RRGGBB").
|
# Colors are specified in hex format ("#RRGGBB").
|
||||||
# Default values follow the Catppuccin Mocha palette.
|
# Default values follow the Semantic Catppuccin Mocha palette.
|
||||||
|
|
||||||
# Main background color (used when transparent = false).
|
bg_normal = "#1e1e2e"
|
||||||
crust = "#11111b"
|
bg_highlight = "#89b4fa"
|
||||||
|
bg_active = "#a6e3a1"
|
||||||
# Status bar background and other secondary UI elements.
|
bg_search = "#cba6f7"
|
||||||
surface0 = "#313244"
|
fg_normal = "#cdd6f4"
|
||||||
|
fg_dimmed = "#6c7086"
|
||||||
# Border and separator color.
|
fg_highlight = "#1e1e2e"
|
||||||
surface1 = "#45475a"
|
fg_warning = "#f38ba8"
|
||||||
|
fg_modified = "#fab387"
|
||||||
# Default text color.
|
fg_accent = "#b4befe"
|
||||||
text = "#cdd6f4"
|
border_normal = "#45475a"
|
||||||
|
border_active = "#a6e3a1"
|
||||||
# Selection highlight and "NORMAL" mode tag color.
|
tree_depth_1 = "#b4befe"
|
||||||
blue = "#89b4fa"
|
tree_depth_2 = "#cba6f7"
|
||||||
|
tree_depth_3 = "#89b4fa"
|
||||||
# Insert mode highlight and "INSERT" mode tag color.
|
tree_depth_4 = "#fab387"
|
||||||
green = "#a6e3a1"
|
|
||||||
|
|
||||||
# Keys/labels color.
|
|
||||||
lavender = "#b4befe"
|
|
||||||
|
|
||||||
# Section titles color.
|
|
||||||
mauve = "#cba6f7"
|
|
||||||
|
|
||||||
# Input field titles color.
|
|
||||||
peach = "#fab387"
|
|
||||||
|
|
||||||
[keybinds]
|
[keybinds]
|
||||||
# Keybindings for navigation and application control.
|
# Keybindings for navigation and application control.
|
||||||
|
#
|
||||||
|
# A binding may list alternatives separated by commas ("<Tab>,za").
|
||||||
|
# Named keys are written in angle brackets: <Space>, <Tab>.
|
||||||
|
# A key bound to two actions is reported on startup instead of silently
|
||||||
|
# shadowing one of them.
|
||||||
down = "j"
|
down = "j"
|
||||||
up = "k"
|
up = "k"
|
||||||
edit = "i"
|
edit = "i"
|
||||||
|
edit_append = "a"
|
||||||
|
edit_substitute = "s,S"
|
||||||
save = ":w"
|
save = ":w"
|
||||||
quit = ":q"
|
quit = ":q"
|
||||||
normal_mode = "Esc"
|
quit_key = "q"
|
||||||
|
command = ":"
|
||||||
search = "/"
|
search = "/"
|
||||||
next_match = "n"
|
next_match = "n"
|
||||||
previous_match = "N"
|
previous_match = "N"
|
||||||
|
jump_top = "gg"
|
||||||
|
jump_bottom = "G"
|
||||||
|
append_item = "o"
|
||||||
|
prepend_item = "O"
|
||||||
|
delete_item = "dd"
|
||||||
|
undo = "u"
|
||||||
|
redo = "U"
|
||||||
|
undo_branch_prev = "g-"
|
||||||
|
undo_branch_next = "g+"
|
||||||
|
rename = "r"
|
||||||
|
append_group = "alt+o"
|
||||||
|
prepend_group = "alt+O"
|
||||||
|
toggle_group = "t"
|
||||||
|
add_missing = "<Space>"
|
||||||
|
accept_all = "A"
|
||||||
|
toggle_fold = "<Tab>,za"
|
||||||
|
fold_all = "zM"
|
||||||
|
unfold_all = "zR"
|
||||||
|
help = "?"
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
local M = {}
|
||||||
|
|
||||||
|
-- Helper function to get a set of files currently in a directory
|
||||||
|
local function get_dir_files(dir)
|
||||||
|
local files = {}
|
||||||
|
if vim.fn.isdirectory(dir) == 1 then
|
||||||
|
for _, f in ipairs(vim.fn.readdir(dir)) do
|
||||||
|
files[f] = true
|
||||||
|
end
|
||||||
|
end
|
||||||
|
return files
|
||||||
|
end
|
||||||
|
|
||||||
|
local function open_floating_terminal(cmd, target_dir)
|
||||||
|
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)
|
||||||
|
|
||||||
|
-- Snapshot the directory contents BEFORE the command runs
|
||||||
|
local files_before = get_dir_files(target_dir)
|
||||||
|
|
||||||
|
vim.fn.termopen(cmd, {
|
||||||
|
on_exit = function()
|
||||||
|
-- Close the floating window and delete the terminal buffer
|
||||||
|
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
|
||||||
|
|
||||||
|
-- Snapshot the directory AFTER the command finishes
|
||||||
|
local files_after = get_dir_files(target_dir)
|
||||||
|
|
||||||
|
-- Compare to find the newly created file
|
||||||
|
for f, _ in pairs(files_after) do
|
||||||
|
if not files_before[f] then
|
||||||
|
local new_filepath = target_dir .. "/" .. f
|
||||||
|
|
||||||
|
-- Open the new file (wrapped in schedule to ensure it runs safely after term closes)
|
||||||
|
vim.schedule(function()
|
||||||
|
vim.cmd("edit " .. vim.fn.fnameescape(new_filepath))
|
||||||
|
-- Optional: Let the user know it worked
|
||||||
|
vim.notify("mould.nvim: Opened " .. f, vim.log.levels.INFO)
|
||||||
|
end)
|
||||||
|
|
||||||
|
break -- Assuming only one file is generated; we can stop looking
|
||||||
|
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
|
||||||
|
|
||||||
|
-- Get the directory of the current file
|
||||||
|
local target_dir = vim.fn.fnamemodify(filepath, ":p:h")
|
||||||
|
local cmd = string.format("mould %s", vim.fn.shellescape(filepath))
|
||||||
|
|
||||||
|
-- Pass the target directory to our terminal function
|
||||||
|
open_floating_terminal(cmd, target_dir)
|
||||||
|
end
|
||||||
|
|
||||||
|
return M
|
||||||
@@ -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" })
|
||||||
+935
-39
File diff suppressed because it is too large.
Load diff
+10
-5
@@ -1,13 +1,13 @@
|
|||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
/// mould: A TUI tool to generate and edit configuration files (.env, json, yaml, toml)
|
/// mould: A TUI tool to generate and edit configuration files.
|
||||||
#[derive(Parser, Debug)]
|
#[derive(Parser, Debug)]
|
||||||
#[command(
|
#[command(
|
||||||
author,
|
author,
|
||||||
version,
|
version,
|
||||||
about = "mould: A TUI tool to generate and edit configuration files (.env, json, yaml, toml)",
|
about = "mould: A TUI tool to generate and edit configuration files",
|
||||||
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.",
|
long_about = "mould allows you to interactively edit and generate configuration files using templates. It supports .env, JSON, YAML, TOML, XML, INI and Java properties files. 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"
|
after_help = "EXAMPLES:\n mould .env.example\n mould docker-compose.yml\n mould config.template.json -o config.json"
|
||||||
)]
|
)]
|
||||||
pub struct Cli {
|
pub struct Cli {
|
||||||
@@ -19,8 +19,13 @@ pub struct Cli {
|
|||||||
#[arg(short, long, value_name = "OUTPUT_FILE")]
|
#[arg(short, long, value_name = "OUTPUT_FILE")]
|
||||||
pub output: Option<PathBuf>,
|
pub output: Option<PathBuf>,
|
||||||
|
|
||||||
/// Override the format detection (env, json, yaml, toml)
|
/// Override the format detection
|
||||||
#[arg(short, long, value_name = "FORMAT", value_parser = ["env", "json", "yaml", "toml"])]
|
#[arg(
|
||||||
|
short,
|
||||||
|
long,
|
||||||
|
value_name = "FORMAT",
|
||||||
|
value_parser = ["env", "json", "yaml", "yml", "toml", "xml", "ini", "properties"]
|
||||||
|
)]
|
||||||
pub format: Option<String>,
|
pub format: Option<String>,
|
||||||
|
|
||||||
/// Increase verbosity for logging (can be used multiple times)
|
/// Increase verbosity for logging (can be used multiple times)
|
||||||
|
|||||||
+382
-71
@@ -1,3 +1,9 @@
|
|||||||
|
//! User configuration: theming and keybindings.
|
||||||
|
//!
|
||||||
|
//! Everything the TUI reacts to is declared here. Actions are resolved through
|
||||||
|
//! one table built from the user's config, so a rebound key takes effect
|
||||||
|
//! everywhere — including the on-screen hints and the help overlay.
|
||||||
|
|
||||||
use ratatui::style::Color;
|
use ratatui::style::Color;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::fs;
|
use std::fs;
|
||||||
@@ -8,24 +14,38 @@ use std::fs;
|
|||||||
pub struct ThemeConfig {
|
pub struct ThemeConfig {
|
||||||
/// If true, skip rendering the background block to let the terminal's transparency show.
|
/// If true, skip rendering the background block to let the terminal's transparency show.
|
||||||
pub transparent: bool,
|
pub transparent: bool,
|
||||||
/// Color for standard background areas (when not transparent).
|
/// Default background.
|
||||||
pub crust: String,
|
pub bg_normal: String,
|
||||||
/// Dark surface color for UI elements like the status bar.
|
/// Background for selected items and standard UI elements.
|
||||||
pub surface0: String,
|
pub bg_highlight: String,
|
||||||
/// Light surface color for borders and dividers.
|
/// Active element background (e.g., insert mode).
|
||||||
pub surface1: String,
|
pub bg_active: String,
|
||||||
/// Default text color.
|
/// Active element background (e.g., search mode).
|
||||||
pub text: String,
|
pub bg_search: String,
|
||||||
/// Color for selection highlighting and normal mode tag.
|
/// Standard text.
|
||||||
pub blue: String,
|
pub fg_normal: String,
|
||||||
/// Color for insert mode highlighting and success status.
|
/// Secondary/inactive text.
|
||||||
pub green: String,
|
pub fg_dimmed: String,
|
||||||
/// Accent color for configuration keys.
|
/// Text on selected items.
|
||||||
pub lavender: String,
|
pub fg_highlight: String,
|
||||||
/// Accent color for primary section titles.
|
/// Red/Alert color for missing items.
|
||||||
pub mauve: String,
|
pub fg_warning: String,
|
||||||
/// Accent color for input field titles.
|
/// Accent color for items edited this session.
|
||||||
pub peach: String,
|
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 {
|
impl ThemeConfig {
|
||||||
@@ -42,66 +62,190 @@ impl ThemeConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn crust(&self) -> Color {
|
pub fn bg_normal(&self) -> Color { Self::parse_hex(&self.bg_normal) }
|
||||||
Self::parse_hex(&self.crust)
|
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 surface0(&self) -> Color {
|
pub fn bg_search(&self) -> Color { Self::parse_hex(&self.bg_search) }
|
||||||
Self::parse_hex(&self.surface0)
|
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 surface1(&self) -> Color {
|
pub fn fg_highlight(&self) -> Color { Self::parse_hex(&self.fg_highlight) }
|
||||||
Self::parse_hex(&self.surface1)
|
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 text(&self) -> Color {
|
pub fn fg_accent(&self) -> Color { Self::parse_hex(&self.fg_accent) }
|
||||||
Self::parse_hex(&self.text)
|
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 blue(&self) -> Color {
|
pub fn tree_depth_1(&self) -> Color { Self::parse_hex(&self.tree_depth_1) }
|
||||||
Self::parse_hex(&self.blue)
|
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 green(&self) -> Color {
|
pub fn tree_depth_4(&self) -> Color { Self::parse_hex(&self.tree_depth_4) }
|
||||||
Self::parse_hex(&self.green)
|
|
||||||
}
|
|
||||||
pub fn lavender(&self) -> Color {
|
|
||||||
Self::parse_hex(&self.lavender)
|
|
||||||
}
|
|
||||||
pub fn mauve(&self) -> Color {
|
|
||||||
Self::parse_hex(&self.mauve)
|
|
||||||
}
|
|
||||||
pub fn peach(&self) -> Color {
|
|
||||||
Self::parse_hex(&self.peach)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for ThemeConfig {
|
impl Default for ThemeConfig {
|
||||||
/// Default theme: Catppuccin Mocha.
|
/// Default theme: Semantic Catppuccin Mocha.
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
transparent: false,
|
transparent: false,
|
||||||
crust: "#11111b".to_string(),
|
bg_normal: "#1e1e2e".to_string(), // base
|
||||||
surface0: "#313244".to_string(),
|
bg_highlight: "#89b4fa".to_string(), // blue
|
||||||
surface1: "#45475a".to_string(),
|
bg_active: "#a6e3a1".to_string(), // green
|
||||||
text: "#cdd6f4".to_string(),
|
bg_search: "#cba6f7".to_string(), // mauve
|
||||||
blue: "#89b4fa".to_string(),
|
fg_normal: "#cdd6f4".to_string(), // text
|
||||||
green: "#a6e3a1".to_string(),
|
fg_dimmed: "#6c7086".to_string(), // overlay0
|
||||||
lavender: "#b4befe".to_string(),
|
fg_highlight: "#1e1e2e".to_string(), // base (dark for contrast against highlights)
|
||||||
mauve: "#cba6f7".to_string(),
|
fg_warning: "#f38ba8".to_string(), // red
|
||||||
peach: "#fab387".to_string(),
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every action the user can trigger from Normal mode.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum Action {
|
||||||
|
Down,
|
||||||
|
Up,
|
||||||
|
JumpTop,
|
||||||
|
JumpBottom,
|
||||||
|
Search,
|
||||||
|
NextMatch,
|
||||||
|
PreviousMatch,
|
||||||
|
Edit,
|
||||||
|
EditAppend,
|
||||||
|
EditSubstitute,
|
||||||
|
Rename,
|
||||||
|
AppendItem,
|
||||||
|
PrependItem,
|
||||||
|
AppendGroup,
|
||||||
|
PrependGroup,
|
||||||
|
ToggleGroup,
|
||||||
|
DeleteItem,
|
||||||
|
AddMissing,
|
||||||
|
AcceptAll,
|
||||||
|
ToggleFold,
|
||||||
|
FoldAll,
|
||||||
|
UnfoldAll,
|
||||||
|
Undo,
|
||||||
|
Redo,
|
||||||
|
UndoBranchPrev,
|
||||||
|
UndoBranchNext,
|
||||||
|
Help,
|
||||||
|
Command,
|
||||||
|
Quit,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Action {
|
||||||
|
/// Short human-readable label, used by the status bar and help overlay.
|
||||||
|
pub fn label(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Action::Down => "move down",
|
||||||
|
Action::Up => "move up",
|
||||||
|
Action::JumpTop => "jump to top",
|
||||||
|
Action::JumpBottom => "jump to bottom",
|
||||||
|
Action::Search => "search keys and values",
|
||||||
|
Action::NextMatch => "next match",
|
||||||
|
Action::PreviousMatch => "previous match",
|
||||||
|
Action::Edit => "edit value (cursor at start)",
|
||||||
|
Action::EditAppend => "edit value (cursor at end)",
|
||||||
|
Action::EditSubstitute => "replace value",
|
||||||
|
Action::Rename => "rename key",
|
||||||
|
Action::AppendItem => "add item below",
|
||||||
|
Action::PrependItem => "add item above",
|
||||||
|
Action::AppendGroup => "add child group below",
|
||||||
|
Action::PrependGroup => "add child group above",
|
||||||
|
Action::ToggleGroup => "toggle group / value",
|
||||||
|
Action::DeleteItem => "delete item",
|
||||||
|
Action::AddMissing => "take template default",
|
||||||
|
Action::AcceptAll => "take all missing defaults",
|
||||||
|
Action::ToggleFold => "fold / unfold group",
|
||||||
|
Action::FoldAll => "fold everything",
|
||||||
|
Action::UnfoldAll => "unfold everything",
|
||||||
|
Action::Undo => "undo",
|
||||||
|
Action::Redo => "redo",
|
||||||
|
Action::UndoBranchPrev => "previous undo branch",
|
||||||
|
Action::UndoBranchNext => "next undo branch",
|
||||||
|
Action::Help => "show this help",
|
||||||
|
Action::Command => "command prompt",
|
||||||
|
Action::Quit => "quit",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Help-overlay grouping.
|
||||||
|
pub fn section(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Action::Down
|
||||||
|
| Action::Up
|
||||||
|
| Action::JumpTop
|
||||||
|
| Action::JumpBottom
|
||||||
|
| Action::Search
|
||||||
|
| Action::NextMatch
|
||||||
|
| Action::PreviousMatch
|
||||||
|
| Action::ToggleFold
|
||||||
|
| Action::FoldAll
|
||||||
|
| Action::UnfoldAll => "Navigate",
|
||||||
|
Action::Edit | Action::EditAppend | Action::EditSubstitute | Action::Rename => "Edit",
|
||||||
|
Action::AppendItem
|
||||||
|
| Action::PrependItem
|
||||||
|
| Action::AppendGroup
|
||||||
|
| Action::PrependGroup
|
||||||
|
| Action::ToggleGroup
|
||||||
|
| Action::DeleteItem => "Structure",
|
||||||
|
Action::AddMissing | Action::AcceptAll => "Template",
|
||||||
|
Action::Undo | Action::Redo | Action::UndoBranchPrev | Action::UndoBranchNext => {
|
||||||
|
"History"
|
||||||
|
}
|
||||||
|
Action::Help | Action::Command | Action::Quit => "Session",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Custom keybindings for navigation and application control.
|
/// Custom keybindings for navigation and application control.
|
||||||
|
///
|
||||||
|
/// A binding may list several alternatives separated by commas (`"<Tab>,za"`).
|
||||||
|
/// Non-character keys are written in angle brackets: `<Space>`, `<Tab>`.
|
||||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub struct KeybindsConfig {
|
pub struct KeybindsConfig {
|
||||||
pub down: String,
|
pub down: String,
|
||||||
pub up: String,
|
pub up: String,
|
||||||
pub edit: String,
|
pub edit: String,
|
||||||
|
pub edit_append: String,
|
||||||
|
pub edit_substitute: String,
|
||||||
|
/// Command string that saves, entered at the `:` prompt.
|
||||||
pub save: String,
|
pub save: String,
|
||||||
|
/// Command string that quits, entered at the `:` prompt.
|
||||||
pub quit: String,
|
pub quit: String,
|
||||||
pub normal_mode: String,
|
/// Normal-mode key that quits directly.
|
||||||
|
pub quit_key: String,
|
||||||
|
/// Normal-mode key that opens the `:` prompt.
|
||||||
|
pub command: String,
|
||||||
pub search: String,
|
pub search: String,
|
||||||
pub next_match: String,
|
pub next_match: String,
|
||||||
pub previous_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,
|
||||||
|
pub redo: String,
|
||||||
|
pub undo_branch_prev: String,
|
||||||
|
pub undo_branch_next: String,
|
||||||
|
pub rename: String,
|
||||||
|
pub append_group: String,
|
||||||
|
pub prepend_group: String,
|
||||||
|
pub toggle_group: String,
|
||||||
|
pub add_missing: String,
|
||||||
|
pub accept_all: String,
|
||||||
|
pub toggle_fold: String,
|
||||||
|
pub fold_all: String,
|
||||||
|
pub unfold_all: String,
|
||||||
|
pub help: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for KeybindsConfig {
|
impl Default for KeybindsConfig {
|
||||||
@@ -110,16 +254,120 @@ impl Default for KeybindsConfig {
|
|||||||
down: "j".to_string(),
|
down: "j".to_string(),
|
||||||
up: "k".to_string(),
|
up: "k".to_string(),
|
||||||
edit: "i".to_string(),
|
edit: "i".to_string(),
|
||||||
|
edit_append: "a".to_string(),
|
||||||
|
edit_substitute: "s,S".to_string(),
|
||||||
save: ":w".to_string(),
|
save: ":w".to_string(),
|
||||||
quit: ":q".to_string(),
|
quit: ":q".to_string(),
|
||||||
normal_mode: "Esc".to_string(),
|
quit_key: "q".to_string(),
|
||||||
|
command: ":".to_string(),
|
||||||
search: "/".to_string(),
|
search: "/".to_string(),
|
||||||
next_match: "n".to_string(),
|
next_match: "n".to_string(),
|
||||||
previous_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(),
|
||||||
|
redo: "U".to_string(),
|
||||||
|
undo_branch_prev: "g-".to_string(),
|
||||||
|
undo_branch_next: "g+".to_string(),
|
||||||
|
rename: "r".to_string(),
|
||||||
|
append_group: "alt+o".to_string(),
|
||||||
|
prepend_group: "alt+O".to_string(),
|
||||||
|
toggle_group: "t".to_string(),
|
||||||
|
add_missing: "<Space>".to_string(),
|
||||||
|
accept_all: "A".to_string(),
|
||||||
|
toggle_fold: "<Tab>,za".to_string(),
|
||||||
|
fold_all: "zM".to_string(),
|
||||||
|
unfold_all: "zR".to_string(),
|
||||||
|
help: "?".to_string(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl KeybindsConfig {
|
||||||
|
/// The full Normal-mode action table, in help-overlay order.
|
||||||
|
///
|
||||||
|
/// Returned as `(binding spec, action)`; a spec may hold comma-separated
|
||||||
|
/// alternatives, which [`Self::resolved`] expands.
|
||||||
|
pub fn table(&self) -> Vec<(&str, Action)> {
|
||||||
|
vec![
|
||||||
|
(&self.down, Action::Down),
|
||||||
|
(&self.up, Action::Up),
|
||||||
|
(&self.jump_top, Action::JumpTop),
|
||||||
|
(&self.jump_bottom, Action::JumpBottom),
|
||||||
|
(&self.search, Action::Search),
|
||||||
|
(&self.next_match, Action::NextMatch),
|
||||||
|
(&self.previous_match, Action::PreviousMatch),
|
||||||
|
(&self.toggle_fold, Action::ToggleFold),
|
||||||
|
(&self.fold_all, Action::FoldAll),
|
||||||
|
(&self.unfold_all, Action::UnfoldAll),
|
||||||
|
(&self.edit, Action::Edit),
|
||||||
|
(&self.edit_append, Action::EditAppend),
|
||||||
|
(&self.edit_substitute, Action::EditSubstitute),
|
||||||
|
(&self.rename, Action::Rename),
|
||||||
|
(&self.append_item, Action::AppendItem),
|
||||||
|
(&self.prepend_item, Action::PrependItem),
|
||||||
|
(&self.append_group, Action::AppendGroup),
|
||||||
|
(&self.prepend_group, Action::PrependGroup),
|
||||||
|
(&self.toggle_group, Action::ToggleGroup),
|
||||||
|
(&self.delete_item, Action::DeleteItem),
|
||||||
|
(&self.add_missing, Action::AddMissing),
|
||||||
|
(&self.accept_all, Action::AcceptAll),
|
||||||
|
(&self.undo, Action::Undo),
|
||||||
|
(&self.redo, Action::Redo),
|
||||||
|
(&self.undo_branch_prev, Action::UndoBranchPrev),
|
||||||
|
(&self.undo_branch_next, Action::UndoBranchNext),
|
||||||
|
(&self.help, Action::Help),
|
||||||
|
(&self.command, Action::Command),
|
||||||
|
(&self.quit_key, Action::Quit),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every individual key sequence with the action it triggers.
|
||||||
|
pub fn resolved(&self) -> Vec<(String, Action)> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for (spec, action) in self.table() {
|
||||||
|
for key in spec.split(',').map(str::trim).filter(|k| !k.is_empty()) {
|
||||||
|
out.push((key.to_string(), action));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first key sequence bound to an action, for display in hints.
|
||||||
|
pub fn key_for(&self, action: Action) -> String {
|
||||||
|
self.table()
|
||||||
|
.iter()
|
||||||
|
.find(|(_, a)| *a == action)
|
||||||
|
.and_then(|(spec, _)| spec.split(',').next())
|
||||||
|
.unwrap_or("")
|
||||||
|
.trim()
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reports any key sequence bound to more than one action.
|
||||||
|
///
|
||||||
|
/// Without this an accidental collision silently shadows an action, which is
|
||||||
|
/// exactly how `add_missing` ended up unreachable behind `edit_append`.
|
||||||
|
pub fn conflicts(&self) -> Vec<String> {
|
||||||
|
let resolved = self.resolved();
|
||||||
|
let mut conflicts = Vec::new();
|
||||||
|
for (i, (key, action)) in resolved.iter().enumerate() {
|
||||||
|
if let Some((_, other)) = resolved[..i].iter().find(|(k, _)| k == key) {
|
||||||
|
conflicts.push(format!(
|
||||||
|
"'{}' is bound to both {} and {}",
|
||||||
|
key,
|
||||||
|
other.label(),
|
||||||
|
action.label()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
conflicts
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Root configuration structure for mould.
|
/// Root configuration structure for mould.
|
||||||
#[derive(Debug, Deserialize, Serialize, Default, Clone)]
|
#[derive(Debug, Deserialize, Serialize, Default, Clone)]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
@@ -129,20 +377,83 @@ pub struct Config {
|
|||||||
pub keybinds: KeybindsConfig,
|
pub keybinds: KeybindsConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Loads the configuration from the user's home config directory (~/.config/mould/config.toml).
|
/// Loads the configuration from the user's config directory (`~/.config/mould/config.toml`).
|
||||||
/// Falls back to default settings if no configuration is found.
|
///
|
||||||
pub fn load_config() -> Config {
|
/// Returns the config alongside an optional problem description. A broken config
|
||||||
if let Some(mut config_dir) = dirs::config_dir() {
|
/// still falls back to defaults, but the caller surfaces the reason instead of
|
||||||
config_dir.push("mould");
|
/// leaving the user wondering why their settings did nothing.
|
||||||
config_dir.push("config.toml");
|
pub fn load_config() -> (Config, Option<String>) {
|
||||||
|
let Some(mut path) = dirs::config_dir() else {
|
||||||
|
return (Config::default(), None);
|
||||||
|
};
|
||||||
|
path.push("mould");
|
||||||
|
path.push("config.toml");
|
||||||
|
|
||||||
if config_dir.exists() {
|
if !path.exists() {
|
||||||
if let Ok(content) = fs::read_to_string(config_dir) {
|
return (Config::default(), None);
|
||||||
if let Ok(config) = toml::from_str(&content) {
|
}
|
||||||
return config;
|
|
||||||
|
let config = match fs::read_to_string(&path) {
|
||||||
|
Ok(content) => match toml::from_str::<Config>(&content) {
|
||||||
|
Ok(config) => config,
|
||||||
|
Err(e) => return (Config::default(), Some(e.message().to_string())),
|
||||||
|
},
|
||||||
|
Err(e) => return (Config::default(), Some(e.to_string())),
|
||||||
|
};
|
||||||
|
|
||||||
|
let conflicts = config.keybinds.conflicts();
|
||||||
|
let warning = conflicts.first().cloned();
|
||||||
|
(config, warning)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn defaults_have_no_conflicting_binds() {
|
||||||
|
assert!(KeybindsConfig::default().conflicts().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn conflicts_are_reported() {
|
||||||
|
let kb = KeybindsConfig {
|
||||||
|
add_missing: "a".to_string(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let conflicts = kb.conflicts();
|
||||||
|
assert_eq!(conflicts.len(), 1);
|
||||||
|
assert!(conflicts[0].contains("'a'"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The shipped example must stay loadable, or it teaches people a broken config.
|
||||||
|
#[test]
|
||||||
|
fn example_config_parses_and_matches_defaults() {
|
||||||
|
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/config.example.toml");
|
||||||
|
let content = std::fs::read_to_string(path).unwrap();
|
||||||
|
let config: Config = toml::from_str(&content).unwrap();
|
||||||
|
|
||||||
|
assert!(config.keybinds.conflicts().is_empty());
|
||||||
|
let defaults = KeybindsConfig::default();
|
||||||
|
for ((spec, action), (default_spec, _)) in
|
||||||
|
config.keybinds.table().iter().zip(defaults.table())
|
||||||
|
{
|
||||||
|
assert_eq!(
|
||||||
|
*spec, default_spec,
|
||||||
|
"example config drifted from the default for {:?}",
|
||||||
|
action
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert_eq!(config.theme.bg_normal, ThemeConfig::default().bg_normal);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn alternatives_expand() {
|
||||||
|
let kb = KeybindsConfig::default();
|
||||||
|
let resolved = kb.resolved();
|
||||||
|
assert!(resolved.iter().any(|(k, a)| k == "<Tab>" && *a == Action::ToggleFold));
|
||||||
|
assert!(resolved.iter().any(|(k, a)| k == "za" && *a == Action::ToggleFold));
|
||||||
|
// Hints show the first alternative.
|
||||||
|
assert_eq!(kb.key_for(Action::ToggleFold), "<Tab>");
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Config::default()
|
|
||||||
}
|
}
|
||||||
+1
-5
@@ -1,14 +1,10 @@
|
|||||||
use std::io;
|
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
/// Custom error types for the mould application.
|
/// Custom error types for the mould application.
|
||||||
#[derive(Error, Debug)]
|
#[derive(Error, Debug)]
|
||||||
pub enum MouldError {
|
pub enum MouldError {
|
||||||
#[error("IO error: {0}")]
|
#[error("IO error: {0}")]
|
||||||
Io(#[from] io::Error),
|
Io(#[from] std::io::Error),
|
||||||
|
|
||||||
#[error("Format error: {0}")]
|
|
||||||
Format(String),
|
|
||||||
|
|
||||||
#[error("File not found: {0}")]
|
#[error("File not found: {0}")]
|
||||||
FileNotFound(String),
|
FileNotFound(String),
|
||||||
|
|||||||
+149
-95
@@ -1,69 +1,73 @@
|
|||||||
use super::{EnvVar, FormatHandler};
|
//! Handler for flat `.env` (Environment) configuration files.
|
||||||
|
//!
|
||||||
|
//! This handler manages simple `KEY=VALUE` pairs. It does not support
|
||||||
|
//! native nesting or grouping, treating all entries as root-level variables.
|
||||||
|
//!
|
||||||
|
//! Comments and blank lines are preserved: each entry remembers the lines that
|
||||||
|
//! preceded it, and they are replayed on write. `.env.example` files carry most
|
||||||
|
//! of their documentation in comments, so dropping them on save would throw away
|
||||||
|
//! the very thing that makes the template useful.
|
||||||
|
|
||||||
|
use super::{ConfigItem, FormatHandler, ValueType, PathSegment};
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::io::{self, Write};
|
use std::io::Write;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
|
/// A format handler for parsing and writing `.env` files.
|
||||||
pub struct EnvHandler;
|
pub struct EnvHandler;
|
||||||
|
|
||||||
impl FormatHandler for EnvHandler {
|
impl FormatHandler for EnvHandler {
|
||||||
fn parse(&self, path: &Path) -> io::Result<Vec<EnvVar>> {
|
/// Parses an environment file into a flat list of `ConfigItem`s.
|
||||||
let content = fs::read_to_string(path)?;
|
fn parse(&self, path: &Path) -> anyhow::Result<Vec<ConfigItem>> {
|
||||||
let mut vars = Vec::new();
|
if !path.exists() {
|
||||||
|
return Ok(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 content = fs::read_to_string(path)?;
|
||||||
let parsed_val = val.trim().trim_matches('"').trim_matches('\'').to_string();
|
let mut vars = Vec::new();
|
||||||
vars.push(EnvVar {
|
let mut trivia: Vec<String> = Vec::new();
|
||||||
key: key.trim().to_string(),
|
|
||||||
value: parsed_val.clone(),
|
for raw_line in content.lines() {
|
||||||
default_value: parsed_val,
|
let line = raw_line.trim();
|
||||||
});
|
|
||||||
|
// Hold comments and blank lines until the entry they document.
|
||||||
|
if line.is_empty() || line.starts_with('#') {
|
||||||
|
trivia.push(line.to_string());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some((key, value)) = line.split_once('=') {
|
||||||
|
let key = key.trim().to_string();
|
||||||
|
let value = value.trim().to_string();
|
||||||
|
|
||||||
|
let mut item = ConfigItem::leaf(
|
||||||
|
key.clone(),
|
||||||
|
vec![PathSegment::Key(key)],
|
||||||
|
value,
|
||||||
|
0,
|
||||||
|
ValueType::String,
|
||||||
|
);
|
||||||
|
item.leading_trivia = std::mem::take(&mut trivia);
|
||||||
|
vars.push(item);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(vars)
|
Ok(vars)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn merge(&self, path: &Path, vars: &mut Vec<EnvVar>) -> io::Result<()> {
|
/// Writes the list of variables back to a flat `.env` file.
|
||||||
if !path.exists() {
|
fn write(&self, path: &Path, vars: &[ConfigItem]) -> anyhow::Result<()> {
|
||||||
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(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn write(&self, path: &Path, vars: &[EnvVar]) -> io::Result<()> {
|
|
||||||
let mut file = fs::File::create(path)?;
|
let mut file = fs::File::create(path)?;
|
||||||
for var in vars {
|
for var in vars {
|
||||||
writeln!(file, "{}={}", var.key, var.value)?;
|
// Groups are structural only, and template-only entries the user has
|
||||||
|
// not accepted must not leak into the output.
|
||||||
|
if !var.should_write() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for line in &var.leading_trivia {
|
||||||
|
writeln!(file, "{}", line)?;
|
||||||
|
}
|
||||||
|
writeln!(file, "{}={}", var.key, var.write_value())?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -72,66 +76,34 @@ impl FormatHandler for EnvHandler {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use std::io::Write;
|
use crate::format::ItemStatus;
|
||||||
use tempfile::NamedTempFile;
|
use tempfile::NamedTempFile;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_parse_env_example() {
|
fn test_parse_env_example() {
|
||||||
let mut file = NamedTempFile::new().unwrap();
|
let mut file = NamedTempFile::new().unwrap();
|
||||||
writeln!(
|
writeln!(file, "# Comment\nKEY1=value1\n KEY2 = value2 ").unwrap();
|
||||||
file,
|
|
||||||
"# A comment\nKEY1=value1\nKEY2=\"value2\"\nKEY3='value3'\nEMPTY="
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let handler = EnvHandler;
|
let handler = EnvHandler;
|
||||||
let vars = handler.parse(file.path()).unwrap();
|
let vars = handler.parse(file.path()).unwrap();
|
||||||
assert_eq!(vars.len(), 4);
|
|
||||||
|
assert_eq!(vars.len(), 2);
|
||||||
assert_eq!(vars[0].key, "KEY1");
|
assert_eq!(vars[0].key, "KEY1");
|
||||||
assert_eq!(vars[0].value, "value1");
|
assert_eq!(vars[0].value.as_deref(), Some("value1"));
|
||||||
assert_eq!(vars[0].default_value, "value1");
|
|
||||||
assert_eq!(vars[1].key, "KEY2");
|
assert_eq!(vars[1].key, "KEY2");
|
||||||
assert_eq!(vars[1].value, "value2");
|
assert_eq!(vars[1].value.as_deref(), Some("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 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, "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]
|
#[test]
|
||||||
fn test_write_env() {
|
fn test_write_env() {
|
||||||
let file = NamedTempFile::new().unwrap();
|
let file = NamedTempFile::new().unwrap();
|
||||||
let vars = vec![EnvVar {
|
let vars = vec![ConfigItem::leaf(
|
||||||
key: "KEY1".to_string(),
|
"KEY1",
|
||||||
value: "value1".to_string(),
|
vec![PathSegment::Key("KEY1".to_string())],
|
||||||
default_value: "def".to_string(),
|
"value1",
|
||||||
}];
|
0,
|
||||||
|
ValueType::String,
|
||||||
|
)];
|
||||||
|
|
||||||
let handler = EnvHandler;
|
let handler = EnvHandler;
|
||||||
handler.write(file.path(), &vars).unwrap();
|
handler.write(file.path(), &vars).unwrap();
|
||||||
@@ -139,4 +111,86 @@ mod tests {
|
|||||||
let content = fs::read_to_string(file.path()).unwrap();
|
let content = fs::read_to_string(file.path()).unwrap();
|
||||||
assert_eq!(content.trim(), "KEY1=value1");
|
assert_eq!(content.trim(), "KEY1=value1");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_merge_env() {
|
||||||
|
let template = NamedTempFile::new().unwrap();
|
||||||
|
writeln!(template.as_file(), "KEY1=template_val\nKEY2=default_val").unwrap();
|
||||||
|
|
||||||
|
let mut active_vars = vec![ConfigItem::leaf(
|
||||||
|
"KEY1",
|
||||||
|
vec![PathSegment::Key("KEY1".to_string())],
|
||||||
|
"active_val",
|
||||||
|
0,
|
||||||
|
ValueType::String,
|
||||||
|
)];
|
||||||
|
|
||||||
|
let handler = EnvHandler;
|
||||||
|
handler.merge(template.path(), &mut active_vars).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(active_vars.len(), 2);
|
||||||
|
|
||||||
|
// KEY1 differs from the template default, but the user has not touched it.
|
||||||
|
let key1 = active_vars.iter().find(|v| v.key == "KEY1").unwrap();
|
||||||
|
assert_eq!(key1.status, ItemStatus::Overridden);
|
||||||
|
assert!(!key1.dirty);
|
||||||
|
assert_eq!(key1.value.as_deref(), Some("active_val"));
|
||||||
|
assert_eq!(key1.template_value.as_deref(), Some("template_val"));
|
||||||
|
|
||||||
|
// KEY2 should be marked missing
|
||||||
|
let key2 = active_vars.iter().find(|v| v.key == "KEY2").unwrap();
|
||||||
|
assert_eq!(key2.status, ItemStatus::MissingFromActive);
|
||||||
|
assert_eq!(key2.value, None);
|
||||||
|
assert_eq!(key2.template_value.as_deref(), Some("default_val"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_comments_survive_roundtrip() {
|
||||||
|
let mut file = NamedTempFile::new().unwrap();
|
||||||
|
writeln!(file, "# database settings\nDB_HOST=localhost\n\n# api key, keep secret\nAPI_KEY=abc").unwrap();
|
||||||
|
|
||||||
|
let handler = EnvHandler;
|
||||||
|
let vars = handler.parse(file.path()).unwrap();
|
||||||
|
assert_eq!(vars[0].leading_trivia, vec!["# database settings"]);
|
||||||
|
assert_eq!(vars[1].leading_trivia, vec!["", "# api key, keep secret"]);
|
||||||
|
|
||||||
|
let out = NamedTempFile::new().unwrap();
|
||||||
|
handler.write(out.path(), &vars).unwrap();
|
||||||
|
let content = fs::read_to_string(out.path()).unwrap();
|
||||||
|
|
||||||
|
assert!(content.contains("# database settings"));
|
||||||
|
assert!(content.contains("# api key, keep secret"));
|
||||||
|
assert!(content.contains("DB_HOST=localhost"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_missing_items_are_not_written() {
|
||||||
|
let handler = EnvHandler;
|
||||||
|
let mut accepted = ConfigItem::leaf(
|
||||||
|
"KEEP",
|
||||||
|
vec![PathSegment::Key("KEEP".to_string())],
|
||||||
|
"yes",
|
||||||
|
0,
|
||||||
|
ValueType::String,
|
||||||
|
);
|
||||||
|
accepted.status = ItemStatus::Present;
|
||||||
|
|
||||||
|
let mut missing = ConfigItem::leaf(
|
||||||
|
"SKIP",
|
||||||
|
vec![PathSegment::Key("SKIP".to_string())],
|
||||||
|
"",
|
||||||
|
0,
|
||||||
|
ValueType::String,
|
||||||
|
);
|
||||||
|
missing.status = ItemStatus::MissingFromActive;
|
||||||
|
missing.value = None;
|
||||||
|
missing.template_value = Some("from_template".to_string());
|
||||||
|
|
||||||
|
let file = NamedTempFile::new().unwrap();
|
||||||
|
handler.write(file.path(), &[accepted, missing]).unwrap();
|
||||||
|
|
||||||
|
let content = fs::read_to_string(file.path()).unwrap();
|
||||||
|
assert!(content.contains("KEEP=yes"));
|
||||||
|
assert!(!content.contains("SKIP"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+527
-133
@@ -1,230 +1,424 @@
|
|||||||
use super::{EnvVar, FormatHandler, FormatType};
|
//! Provides a generalized handler for hierarchical configuration formats
|
||||||
|
//! (JSON, YAML, TOML, XML).
|
||||||
|
//!
|
||||||
|
//! This handler works by using `serde_json::Value` as an intermediary
|
||||||
|
//! representation. It "flattens" nested structures into a list of
|
||||||
|
//! `ConfigItem`s for the TUI, and "unflattens" them back into their
|
||||||
|
//! nested form when saving.
|
||||||
|
|
||||||
|
use super::{ConfigItem, FormatHandler, FormatType, ValueType, PathSegment};
|
||||||
use serde_json::{Map, Value};
|
use serde_json::{Map, Value};
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::io;
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
|
/// A format handler capable of processing nested configuration structures.
|
||||||
pub struct HierarchicalHandler {
|
pub struct HierarchicalHandler {
|
||||||
|
/// The specific file format this instance is configured to handle.
|
||||||
format_type: FormatType,
|
format_type: FormatType,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HierarchicalHandler {
|
impl HierarchicalHandler {
|
||||||
|
/// Creates a new hierarchical handler for the specified format.
|
||||||
pub fn new(format_type: FormatType) -> Self {
|
pub fn new(format_type: FormatType) -> Self {
|
||||||
Self { format_type }
|
Self { format_type }
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_value(&self, path: &Path) -> io::Result<Value> {
|
/// Reads a file and parses it into an intermediary `serde_json::Value`.
|
||||||
|
fn read_value(&self, path: &Path) -> anyhow::Result<Value> {
|
||||||
let content = fs::read_to_string(path)?;
|
let content = fs::read_to_string(path)?;
|
||||||
let value = match self.format_type {
|
let value = match self.format_type {
|
||||||
FormatType::Json => serde_json::from_str(&content)
|
FormatType::Json => serde_json::from_str(&content)?,
|
||||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
|
FormatType::Yaml => serde_yaml::from_str(&content)?,
|
||||||
FormatType::Yaml => serde_yaml::from_str(&content)
|
FormatType::Toml => toml::from_str(&content)?,
|
||||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
|
FormatType::Xml => xml_to_json(&content)?,
|
||||||
FormatType::Toml => toml::from_str(&content)
|
|
||||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
|
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
};
|
};
|
||||||
Ok(value)
|
Ok(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn write_value(&self, path: &Path, value: &Value) -> io::Result<()> {
|
/// Serializes a `serde_json::Value` and writes it to the specified path.
|
||||||
|
fn write_value(&self, path: &Path, value: &Value) -> anyhow::Result<()> {
|
||||||
let content = match self.format_type {
|
let content = match self.format_type {
|
||||||
FormatType::Json => serde_json::to_string_pretty(value)
|
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)?,
|
||||||
FormatType::Yaml => serde_yaml::to_string(value)
|
|
||||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
|
|
||||||
FormatType::Toml => {
|
FormatType::Toml => {
|
||||||
// toml requires the root to be a table
|
// TOML requires the root to be a table (Object).
|
||||||
if value.is_object() {
|
if value.is_object() {
|
||||||
let toml_value: toml::Value = serde_json::from_value(value.clone())
|
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)?
|
||||||
toml::to_string_pretty(&toml_value)
|
|
||||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
|
|
||||||
} else {
|
} else {
|
||||||
return Err(io::Error::new(
|
anyhow::bail!("Root of TOML must be an object");
|
||||||
io::ErrorKind::InvalidData,
|
|
||||||
"Root of TOML must be an object",
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
FormatType::Xml => json_to_xml(value),
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
};
|
};
|
||||||
fs::write(path, content)
|
fs::write(path, content)?;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn flatten(value: &Value, prefix: &str, vars: &mut Vec<EnvVar>) {
|
/// Converts an XML string into an intermediary `serde_json::Value`.
|
||||||
|
///
|
||||||
|
/// This implementation handles basic element nesting and text content.
|
||||||
|
/// Attributes are currently not supported.
|
||||||
|
fn xml_to_json(content: &str) -> anyhow::Result<Value> {
|
||||||
|
use quick_xml::reader::Reader;
|
||||||
|
use quick_xml::events::Event;
|
||||||
|
|
||||||
|
let mut reader = Reader::from_str(content);
|
||||||
|
reader.config_mut().trim_text(true);
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
|
||||||
|
/// Recursively parses XML elements into a nested Map structure.
|
||||||
|
fn parse_recursive(reader: &mut Reader<&[u8]>) -> anyhow::Result<Value> {
|
||||||
|
let mut map = Map::new();
|
||||||
|
let mut text = String::new();
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
|
||||||
|
loop {
|
||||||
|
match reader.read_event_into(&mut buf) {
|
||||||
|
Ok(Event::Start(e)) => {
|
||||||
|
let name = String::from_utf8_lossy(e.name().as_ref()).to_string();
|
||||||
|
let val = parse_recursive(reader)?;
|
||||||
|
|
||||||
|
// If multiple elements have the same name, they are collected into an Array.
|
||||||
|
if let Some(existing) = map.get_mut(&name) {
|
||||||
|
if let Some(arr) = existing.as_array_mut() {
|
||||||
|
arr.push(val);
|
||||||
|
} else {
|
||||||
|
let old = existing.take();
|
||||||
|
*existing = Value::Array(vec![old, val]);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
map.insert(name, val);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Event::End(_)) => break,
|
||||||
|
Ok(Event::Text(e)) => {
|
||||||
|
text.push_str(&String::from_utf8_lossy(e.as_ref()));
|
||||||
|
}
|
||||||
|
Ok(Event::Eof) => break,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
buf.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
if map.is_empty() {
|
||||||
|
if text.is_empty() {
|
||||||
|
Ok(Value::Null)
|
||||||
|
} else {
|
||||||
|
Ok(Value::String(text))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if !text.is_empty() {
|
||||||
|
// Special key used to store raw text content of an element that also has children.
|
||||||
|
map.insert("$text".to_string(), Value::String(text));
|
||||||
|
}
|
||||||
|
Ok(Value::Object(map))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move to the first start tag
|
||||||
|
loop {
|
||||||
|
match reader.read_event_into(&mut buf) {
|
||||||
|
Ok(Event::Start(e)) => {
|
||||||
|
let name = String::from_utf8_lossy(e.name().as_ref()).to_string();
|
||||||
|
let val = parse_recursive(&mut reader)?;
|
||||||
|
let mut root = Map::new();
|
||||||
|
root.insert(name, val);
|
||||||
|
return Ok(Value::Object(root));
|
||||||
|
}
|
||||||
|
Ok(Event::Eof) => break,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
buf.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Value::Object(Map::new()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Converts a nested `serde_json::Value` back into an XML string.
|
||||||
|
fn json_to_xml(value: &Value) -> String {
|
||||||
|
use quick_xml::Writer;
|
||||||
|
use quick_xml::events::{Event, BytesStart, BytesEnd, BytesText};
|
||||||
|
|
||||||
|
let mut writer = Writer::new_with_indent(Vec::new(), b' ', 4);
|
||||||
|
|
||||||
|
/// Recursively writes JSON values as XML elements.
|
||||||
|
fn write_recursive(writer: &mut Writer<Vec<u8>>, value: &Value, key_name: Option<&str>) {
|
||||||
|
if let Some(k) = key_name
|
||||||
|
&& k == "$text" {
|
||||||
|
if let Some(s) = value.as_str() {
|
||||||
|
writer.write_event(Event::Text(BytesText::new(s))).unwrap();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
match value {
|
match value {
|
||||||
Value::Object(map) => {
|
Value::Object(map) => {
|
||||||
|
if let Some(k) = key_name {
|
||||||
|
writer.write_event(Event::Start(BytesStart::new(k))).unwrap();
|
||||||
|
}
|
||||||
for (k, v) in map {
|
for (k, v) in map {
|
||||||
let new_prefix = if prefix.is_empty() {
|
if let Some(arr) = v.as_array() {
|
||||||
k.clone()
|
for item in arr {
|
||||||
|
write_recursive(writer, item, Some(k));
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
format!("{}.{}", prefix, k)
|
write_recursive(writer, v, Some(k));
|
||||||
};
|
}
|
||||||
flatten(v, &new_prefix, vars);
|
}
|
||||||
|
if let Some(k) = key_name {
|
||||||
|
writer.write_event(Event::End(BytesEnd::new(k))).unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Value::Array(arr) => {
|
Value::Array(arr) => {
|
||||||
for (i, v) in arr.iter().enumerate() {
|
for v in arr {
|
||||||
let new_prefix = format!("{}[{}]", prefix, i);
|
write_recursive(writer, v, key_name);
|
||||||
flatten(v, &new_prefix, vars);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Value::String(s) => {
|
Value::String(s) => {
|
||||||
vars.push(EnvVar {
|
if let Some(k) = key_name {
|
||||||
key: prefix.to_string(),
|
writer.write_event(Event::Start(BytesStart::new(k))).unwrap();
|
||||||
value: s.clone(),
|
}
|
||||||
default_value: s.clone(),
|
writer.write_event(Event::Text(BytesText::new(s))).unwrap();
|
||||||
});
|
if let Some(k) = key_name {
|
||||||
|
writer.write_event(Event::End(BytesEnd::new(k))).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Value::Number(n) => {
|
||||||
|
if let Some(k) = key_name {
|
||||||
|
writer.write_event(Event::Start(BytesStart::new(k))).unwrap();
|
||||||
|
}
|
||||||
|
writer.write_event(Event::Text(BytesText::new(&n.to_string()))).unwrap();
|
||||||
|
if let Some(k) = key_name {
|
||||||
|
writer.write_event(Event::End(BytesEnd::new(k))).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Value::Bool(b) => {
|
||||||
|
if let Some(k) = key_name {
|
||||||
|
writer.write_event(Event::Start(BytesStart::new(k))).unwrap();
|
||||||
|
}
|
||||||
|
writer.write_event(Event::Text(BytesText::new(&b.to_string()))).unwrap();
|
||||||
|
if let Some(k) = key_name {
|
||||||
|
writer.write_event(Event::End(BytesEnd::new(k))).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Value::Null => {
|
||||||
|
if let Some(k) = key_name {
|
||||||
|
writer.write_event(Event::Empty(BytesStart::new(k))).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if value.is_object() {
|
||||||
|
for (k, v) in value.as_object().unwrap() {
|
||||||
|
if let Some(arr) = v.as_array() {
|
||||||
|
for item in arr {
|
||||||
|
write_recursive(&mut writer, item, Some(k));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
write_recursive(&mut writer, v, Some(k));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
write_recursive(&mut writer, value, None);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut out = String::from_utf8(writer.into_inner()).unwrap();
|
||||||
|
if !out.ends_with('\n') {
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Recursively flattens a nested `serde_json::Value` into a list of `ConfigItem`s.
|
||||||
|
///
|
||||||
|
/// This function translates the structural hierarchy of the JSON into
|
||||||
|
/// linear entries with associated paths and depth levels for UI rendering.
|
||||||
|
fn flatten(value: &Value, current_path: Vec<PathSegment>, key_name: Option<String>, depth: usize, vars: &mut Vec<ConfigItem>) {
|
||||||
|
let mut next_path = current_path.clone();
|
||||||
|
|
||||||
|
if let Some(ref k) = key_name {
|
||||||
|
if !current_path.is_empty() {
|
||||||
|
// It's a key in an object, so append to path
|
||||||
|
next_path.push(PathSegment::Key(k.clone()));
|
||||||
|
} else {
|
||||||
|
// First element, maybe root
|
||||||
|
if !k.is_empty() {
|
||||||
|
next_path.push(PathSegment::Key(k.clone()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let display_key = match next_path.last() {
|
||||||
|
Some(PathSegment::Key(k)) => k.clone(),
|
||||||
|
Some(PathSegment::Index(i)) => format!("[{}]", i),
|
||||||
|
None => "".to_string(),
|
||||||
|
};
|
||||||
|
|
||||||
|
match value {
|
||||||
|
Value::Object(map) => {
|
||||||
|
if !next_path.is_empty() {
|
||||||
|
vars.push(ConfigItem::group(display_key, next_path.clone(), depth));
|
||||||
|
}
|
||||||
|
let next_depth = if next_path.is_empty() { depth } else { depth + 1 };
|
||||||
|
for (k, v) in map {
|
||||||
|
flatten(v, next_path.clone(), Some(k.clone()), next_depth, vars);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Value::Array(arr) => {
|
||||||
|
if !next_path.is_empty() {
|
||||||
|
vars.push(ConfigItem::group(display_key, next_path.clone(), depth));
|
||||||
|
}
|
||||||
|
let next_depth = if next_path.is_empty() { depth } else { depth + 1 };
|
||||||
|
for (i, v) in arr.iter().enumerate() {
|
||||||
|
let mut arr_path = next_path.clone();
|
||||||
|
arr_path.push(PathSegment::Index(i));
|
||||||
|
flatten(v, arr_path, None, next_depth, vars);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Value::String(s) => {
|
||||||
|
vars.push(ConfigItem::leaf(display_key, next_path.clone(), s.clone(), depth, ValueType::String));
|
||||||
}
|
}
|
||||||
Value::Number(n) => {
|
Value::Number(n) => {
|
||||||
let s = n.to_string();
|
let s = n.to_string();
|
||||||
vars.push(EnvVar {
|
vars.push(ConfigItem::leaf(display_key, next_path.clone(), s.clone(), depth, ValueType::Number));
|
||||||
key: prefix.to_string(),
|
|
||||||
value: s.clone(),
|
|
||||||
default_value: s.clone(),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
Value::Bool(b) => {
|
Value::Bool(b) => {
|
||||||
let s = b.to_string();
|
let s = b.to_string();
|
||||||
vars.push(EnvVar {
|
vars.push(ConfigItem::leaf(display_key, next_path.clone(), s.clone(), depth, ValueType::Bool));
|
||||||
key: prefix.to_string(),
|
|
||||||
value: s.clone(),
|
|
||||||
default_value: s.clone(),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
Value::Null => {
|
Value::Null => {
|
||||||
vars.push(EnvVar {
|
vars.push(ConfigItem::leaf(display_key, next_path.clone(), "", depth, ValueType::Null));
|
||||||
key: prefix.to_string(),
|
|
||||||
value: "".to_string(),
|
|
||||||
default_value: "".to_string(),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Removed unused update_leaf and update_leaf_value functions
|
|
||||||
|
|
||||||
impl FormatHandler for HierarchicalHandler {
|
impl FormatHandler for HierarchicalHandler {
|
||||||
fn parse(&self, path: &Path) -> io::Result<Vec<EnvVar>> {
|
fn parse(&self, path: &Path) -> anyhow::Result<Vec<ConfigItem>> {
|
||||||
let value = self.read_value(path)?;
|
let value = self.read_value(path)?;
|
||||||
let mut vars = Vec::new();
|
let mut vars = Vec::new();
|
||||||
flatten(&value, "", &mut vars);
|
flatten(&value, Vec::new(), Some("".to_string()), 0, &mut vars);
|
||||||
Ok(vars)
|
Ok(vars)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn merge(&self, path: &Path, vars: &mut Vec<EnvVar>) -> io::Result<()> {
|
fn write(&self, path: &Path, vars: &[ConfigItem]) -> anyhow::Result<()> {
|
||||||
if !path.exists() {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
let existing_value = self.read_value(path)?;
|
|
||||||
let mut existing_vars = Vec::new();
|
|
||||||
flatten(&existing_value, "", &mut existing_vars);
|
|
||||||
|
|
||||||
for var in vars.iter_mut() {
|
|
||||||
if let Some(existing) = existing_vars.iter().find(|v| v.key == var.key) {
|
|
||||||
var.value = existing.value.clone();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn write(&self, path: &Path, vars: &[EnvVar]) -> io::Result<()> {
|
|
||||||
let mut root = Value::Object(Map::new());
|
let mut root = Value::Object(Map::new());
|
||||||
for var in vars {
|
for var in vars {
|
||||||
insert_into_value(&mut root, &var.key, &var.value);
|
if var.should_write() {
|
||||||
|
insert_into_value(&mut root, &var.path, var.write_value(), var.value_type);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
self.write_value(path, &root)
|
self.write_value(path, &root)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn insert_into_value(root: &mut Value, path: &str, new_val_str: &str) {
|
/// Reconstructs a nested `serde_json::Value` from a hierarchical path and a leaf value.
|
||||||
let mut parts = path.split('.');
|
///
|
||||||
let last_part = match parts.next_back() {
|
/// This is the core "unflattening" logic used when saving modified configuration.
|
||||||
Some(p) => p,
|
fn insert_into_value(root: &mut Value, path: &[PathSegment], new_val_str: &str, value_type: ValueType) {
|
||||||
None => return,
|
if path.is_empty() {
|
||||||
};
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
let mut current = root;
|
let mut current = root;
|
||||||
for part in parts {
|
|
||||||
let (key, idx) = parse_array_key(part);
|
// Traverse all but the last segment to build the intermediate structure.
|
||||||
|
for i in 0..path.len() - 1 {
|
||||||
|
let segment = &path[i];
|
||||||
|
let next_segment = &path[i + 1];
|
||||||
|
|
||||||
|
match segment {
|
||||||
|
PathSegment::Key(key) => {
|
||||||
if !current.is_object() {
|
if !current.is_object() {
|
||||||
*current = Value::Object(Map::new());
|
*current = Value::Object(Map::new());
|
||||||
}
|
}
|
||||||
let map = current.as_object_mut().unwrap();
|
let map = current.as_object_mut().unwrap();
|
||||||
|
|
||||||
let next_node = map.entry(key.to_string()).or_insert_with(|| {
|
let next_node = map.entry(key.clone()).or_insert_with(|| {
|
||||||
if idx.is_some() {
|
match next_segment {
|
||||||
Value::Array(Vec::new())
|
PathSegment::Index(_) => Value::Array(Vec::new()),
|
||||||
} else {
|
PathSegment::Key(_) => Value::Object(Map::new()),
|
||||||
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;
|
current = next_node;
|
||||||
}
|
}
|
||||||
|
PathSegment::Index(idx) => {
|
||||||
|
if !current.is_array() {
|
||||||
|
*current = Value::Array(Vec::new());
|
||||||
|
}
|
||||||
|
let arr = current.as_array_mut().unwrap();
|
||||||
|
while arr.len() <= *idx {
|
||||||
|
match next_segment {
|
||||||
|
PathSegment::Index(_) => arr.push(Value::Array(Vec::new())),
|
||||||
|
PathSegment::Key(_) => arr.push(Value::Object(Map::new())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
current = &mut arr[*idx];
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let (final_key, final_idx) = parse_array_key(last_part);
|
// Insert the actual leaf value at the end of the path.
|
||||||
if !current.is_object() {
|
let final_segment = &path[path.len() - 1];
|
||||||
*current = Value::Object(Map::new());
|
|
||||||
}
|
|
||||||
let map = current.as_object_mut().unwrap();
|
|
||||||
|
|
||||||
// Attempt basic type inference
|
// Attempt to preserve the original data type during insertion.
|
||||||
let final_val = if let Ok(n) = new_val_str.parse::<i64>() {
|
let final_val = match value_type {
|
||||||
|
ValueType::Number => {
|
||||||
|
if let Ok(n) = new_val_str.parse::<i64>() {
|
||||||
Value::Number(n.into())
|
Value::Number(n.into())
|
||||||
} else if let Ok(b) = new_val_str.parse::<bool>() {
|
} 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)
|
Value::Bool(b)
|
||||||
} else {
|
} else {
|
||||||
Value::String(new_val_str.to_string())
|
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 {
|
match final_segment {
|
||||||
let next_node = map
|
PathSegment::Key(key) => {
|
||||||
.entry(final_key.to_string())
|
if !current.is_object() {
|
||||||
.or_insert_with(|| Value::Array(Vec::new()));
|
*current = Value::Object(Map::new());
|
||||||
if !next_node.is_array() {
|
|
||||||
*next_node = Value::Array(Vec::new());
|
|
||||||
}
|
}
|
||||||
let arr = next_node.as_array_mut().unwrap();
|
let map = current.as_object_mut().unwrap();
|
||||||
while arr.len() <= i {
|
map.insert(key.clone(), final_val);
|
||||||
|
}
|
||||||
|
PathSegment::Index(idx) => {
|
||||||
|
if !current.is_array() {
|
||||||
|
*current = Value::Array(Vec::new());
|
||||||
|
}
|
||||||
|
let arr = current.as_array_mut().unwrap();
|
||||||
|
while arr.len() <= *idx {
|
||||||
arr.push(Value::Null);
|
arr.push(Value::Null);
|
||||||
}
|
}
|
||||||
arr[i] = final_val;
|
arr[*idx] = 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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use crate::format::ItemStatus;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_flatten_unflatten() {
|
fn test_json_flatten_unflatten() {
|
||||||
let mut vars = Vec::new();
|
let mut vars = Vec::new();
|
||||||
let json = serde_json::json!({
|
let json = serde_json::json!({
|
||||||
"services": {
|
"services": {
|
||||||
@@ -237,17 +431,217 @@ mod tests {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
flatten(&json, "", &mut vars);
|
flatten(&json, Vec::new(), Some("".to_string()), 0, &mut vars);
|
||||||
assert_eq!(vars.len(), 2);
|
assert_eq!(vars.len(), 6);
|
||||||
|
|
||||||
let mut root = Value::Object(Map::new());
|
let mut root = Value::Object(Map::new());
|
||||||
for var in vars {
|
for var in vars {
|
||||||
insert_into_value(&mut root, &var.key, &var.value);
|
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();
|
let unflattened_json = serde_json::to_string(&root).unwrap();
|
||||||
assert!(unflattened_json.contains("\"8080:80\""));
|
assert!(unflattened_json.contains("\"8080:80\""));
|
||||||
assert!(unflattened_json.contains("true"));
|
assert!(unflattened_json.contains("true"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_type_preservation() {
|
||||||
|
let mut vars = Vec::new();
|
||||||
|
let json = serde_json::json!({
|
||||||
|
"port_num": 8080,
|
||||||
|
"port_str": "8080",
|
||||||
|
"is_enabled": true,
|
||||||
|
"is_enabled_str": "true",
|
||||||
|
"float_num": 42.42,
|
||||||
|
"float_str": "42.42"
|
||||||
|
});
|
||||||
|
|
||||||
|
flatten(&json, Vec::new(), Some("".to_string()), 0, &mut vars);
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let unflattened = root.as_object().unwrap();
|
||||||
|
|
||||||
|
assert!(unflattened["port_num"].is_number(), "port_num should be a number");
|
||||||
|
assert_eq!(unflattened["port_num"].as_i64(), Some(8080));
|
||||||
|
|
||||||
|
assert!(unflattened["port_str"].is_string(), "port_str should be a string");
|
||||||
|
assert_eq!(unflattened["port_str"].as_str(), Some("8080"));
|
||||||
|
|
||||||
|
assert!(unflattened["is_enabled"].is_boolean(), "is_enabled should be a boolean");
|
||||||
|
assert_eq!(unflattened["is_enabled"].as_bool(), Some(true));
|
||||||
|
|
||||||
|
assert!(unflattened["is_enabled_str"].is_string(), "is_enabled_str should be a string");
|
||||||
|
assert_eq!(unflattened["is_enabled_str"].as_str(), Some("true"));
|
||||||
|
|
||||||
|
assert!(unflattened["float_num"].is_number(), "float_num should be a number");
|
||||||
|
assert_eq!(unflattened["float_num"].as_f64(), Some(42.42));
|
||||||
|
|
||||||
|
assert!(unflattened["float_str"].is_string(), "float_str should be a string");
|
||||||
|
assert_eq!(unflattened["float_str"].as_str(), Some("42.42"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_yaml_flatten_unflatten() {
|
||||||
|
let yaml_str = "
|
||||||
|
server:
|
||||||
|
port: 8080
|
||||||
|
port_str: \"8080\"
|
||||||
|
enabled: true
|
||||||
|
";
|
||||||
|
let yaml_val: Value = serde_yaml::from_str(yaml_str).unwrap();
|
||||||
|
let mut vars = Vec::new();
|
||||||
|
flatten(&yaml_val, Vec::new(), Some("".to_string()), 0, &mut vars);
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let unflattened_yaml = serde_yaml::to_string(&root).unwrap();
|
||||||
|
assert!(unflattened_yaml.contains("port: 8080"));
|
||||||
|
assert!(unflattened_yaml.contains("port_str: '8080'") || unflattened_yaml.contains("port_str: \"8080\""));
|
||||||
|
assert!(unflattened_yaml.contains("enabled: true"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_toml_flatten_unflatten() {
|
||||||
|
let toml_str = "
|
||||||
|
[server]
|
||||||
|
port = 8080
|
||||||
|
port_str = \"8080\"
|
||||||
|
enabled = true
|
||||||
|
";
|
||||||
|
let toml_val: toml::Value = toml::from_str(toml_str).unwrap();
|
||||||
|
let json_val: Value = serde_json::to_value(toml_val).unwrap();
|
||||||
|
|
||||||
|
let mut vars = Vec::new();
|
||||||
|
flatten(&json_val, Vec::new(), Some("".to_string()), 0, &mut vars);
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let toml_root: toml::Value = serde_json::from_value(root).unwrap();
|
||||||
|
let unflattened_toml = toml::to_string(&toml_root).unwrap();
|
||||||
|
|
||||||
|
assert!(unflattened_toml.contains("port = 8080"));
|
||||||
|
assert!(unflattened_toml.contains("port_str = \"8080\""));
|
||||||
|
assert!(unflattened_toml.contains("enabled = true"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_group_rename_write() {
|
||||||
|
let mut vars = Vec::new();
|
||||||
|
let json = serde_json::json!({
|
||||||
|
"old_group": {
|
||||||
|
"key": "val"
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
flatten(&json, Vec::new(), Some("".to_string()), 0, &mut vars);
|
||||||
|
assert_eq!(vars.len(), 2);
|
||||||
|
assert_eq!(vars[0].key, "old_group");
|
||||||
|
assert!(vars[0].is_group);
|
||||||
|
assert_eq!(vars[1].key, "key");
|
||||||
|
assert_eq!(vars[1].path_string(), "old_group.key");
|
||||||
|
|
||||||
|
// Manually simulate a rename of "old_group" to "new_group"
|
||||||
|
vars[0].key = "new_group".to_string();
|
||||||
|
vars[0].path = vec![PathSegment::Key("new_group".to_string())];
|
||||||
|
vars[1].path = vec![
|
||||||
|
PathSegment::Key("new_group".to_string()),
|
||||||
|
PathSegment::Key("key".to_string()),
|
||||||
|
];
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let out = serde_json::to_string(&root).unwrap();
|
||||||
|
assert!(out.contains("\"new_group\""));
|
||||||
|
assert!(out.contains("\"key\":\"val\""));
|
||||||
|
assert!(!out.contains("\"old_group\""));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn missing_nested_keys_are_spliced_beside_their_siblings() {
|
||||||
|
use std::io::Write;
|
||||||
|
let handler = HierarchicalHandler::new(FormatType::Json);
|
||||||
|
|
||||||
|
let mut template = tempfile::NamedTempFile::new().unwrap();
|
||||||
|
write!(
|
||||||
|
template,
|
||||||
|
r#"{{"server":{{"host":"localhost","port":8080}},"debug":false}}"#
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// The active config is missing `server.port` entirely.
|
||||||
|
let mut active = Vec::new();
|
||||||
|
flatten(
|
||||||
|
&serde_json::json!({"server": {"host": "example.com"}, "debug": true}),
|
||||||
|
Vec::new(),
|
||||||
|
Some("".to_string()),
|
||||||
|
0,
|
||||||
|
&mut active,
|
||||||
|
);
|
||||||
|
|
||||||
|
handler.merge(template.path(), &mut active).unwrap();
|
||||||
|
|
||||||
|
let order: Vec<String> = active.iter().map(|v| v.path_string()).collect();
|
||||||
|
assert_eq!(order, vec!["server", "server.host", "server.port", "debug"]);
|
||||||
|
|
||||||
|
let port = active.iter().find(|v| v.key == "port").unwrap();
|
||||||
|
assert_eq!(port.status, ItemStatus::MissingFromActive);
|
||||||
|
assert_eq!(port.depth, 1);
|
||||||
|
assert_eq!(port.template_value.as_deref(), Some("8080"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_malformed_file_is_an_error_not_an_empty_document() {
|
||||||
|
use std::io::Write;
|
||||||
|
let handler = HierarchicalHandler::new(FormatType::Json);
|
||||||
|
let mut file = tempfile::NamedTempFile::new().unwrap();
|
||||||
|
write!(file, "{{ not json").unwrap();
|
||||||
|
|
||||||
|
assert!(handler.parse(file.path()).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unaccepted_template_entries_are_not_written() {
|
||||||
|
let handler = HierarchicalHandler::new(FormatType::Json);
|
||||||
|
let mut vars = Vec::new();
|
||||||
|
flatten(
|
||||||
|
&serde_json::json!({"kept": "yes", "skipped": "no"}),
|
||||||
|
Vec::new(),
|
||||||
|
Some("".to_string()),
|
||||||
|
0,
|
||||||
|
&mut vars,
|
||||||
|
);
|
||||||
|
let skipped = vars.iter_mut().find(|v| v.key == "skipped").unwrap();
|
||||||
|
skipped.status = ItemStatus::MissingFromActive;
|
||||||
|
skipped.template_value = skipped.value.take();
|
||||||
|
|
||||||
|
let file = tempfile::NamedTempFile::new().unwrap();
|
||||||
|
handler.write(file.path(), &vars).unwrap();
|
||||||
|
|
||||||
|
let content = std::fs::read_to_string(file.path()).unwrap();
|
||||||
|
assert!(content.contains("kept"));
|
||||||
|
assert!(!content.contains("skipped"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
use super::{ConfigItem, FormatHandler, ValueType, PathSegment};
|
||||||
|
use ini::Ini;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
pub struct IniHandler;
|
||||||
|
|
||||||
|
impl FormatHandler for IniHandler {
|
||||||
|
fn parse(&self, path: &Path) -> anyhow::Result<Vec<ConfigItem>> {
|
||||||
|
let conf = Ini::load_from_file(path)?;
|
||||||
|
let mut vars = Vec::new();
|
||||||
|
|
||||||
|
for (section, prop) in &conf {
|
||||||
|
let section_name = section.unwrap_or_default();
|
||||||
|
|
||||||
|
if !section_name.is_empty() {
|
||||||
|
vars.push(ConfigItem::group(
|
||||||
|
section_name,
|
||||||
|
vec![PathSegment::Key(section_name.to_string())],
|
||||||
|
0,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (key, value) in prop {
|
||||||
|
let path = if section_name.is_empty() {
|
||||||
|
vec![PathSegment::Key(key.to_string())]
|
||||||
|
} else {
|
||||||
|
vec![PathSegment::Key(section_name.to_string()), PathSegment::Key(key.to_string())]
|
||||||
|
};
|
||||||
|
|
||||||
|
vars.push(ConfigItem::leaf(
|
||||||
|
key,
|
||||||
|
path,
|
||||||
|
value,
|
||||||
|
if section_name.is_empty() { 0 } else { 1 },
|
||||||
|
ValueType::String,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(vars)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write(&self, path: &Path, vars: &[ConfigItem]) -> anyhow::Result<()> {
|
||||||
|
let mut conf = Ini::new();
|
||||||
|
for var in vars {
|
||||||
|
if var.should_write() {
|
||||||
|
let val = var.write_value();
|
||||||
|
|
||||||
|
if var.path.len() == 2 {
|
||||||
|
if let (PathSegment::Key(section), PathSegment::Key(key)) = (&var.path[0], &var.path[1]) {
|
||||||
|
conf.with_section(Some(section)).set(key, val);
|
||||||
|
}
|
||||||
|
} else if var.path.len() == 1
|
||||||
|
&& let PathSegment::Key(key) = &var.path[0] {
|
||||||
|
conf.with_section(None::<String>).set(key, val);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
conf.write_to_file(path)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use tempfile::NamedTempFile;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_section_rename_write() {
|
||||||
|
let handler = IniHandler;
|
||||||
|
let mut vars = vec![
|
||||||
|
ConfigItem::group("server", vec![PathSegment::Key("server".to_string())], 0),
|
||||||
|
ConfigItem::leaf(
|
||||||
|
"port",
|
||||||
|
vec![PathSegment::Key("server".to_string()), PathSegment::Key("port".to_string())],
|
||||||
|
"8080",
|
||||||
|
1,
|
||||||
|
ValueType::String,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
|
// Rename "server" to "srv"
|
||||||
|
vars[0].key = "srv".to_string();
|
||||||
|
vars[0].path = vec![PathSegment::Key("srv".to_string())];
|
||||||
|
|
||||||
|
// Update child path
|
||||||
|
vars[1].path = vec![PathSegment::Key("srv".to_string()), PathSegment::Key("port".to_string())];
|
||||||
|
|
||||||
|
let file = NamedTempFile::new().unwrap();
|
||||||
|
handler.write(file.path(), &vars).unwrap();
|
||||||
|
|
||||||
|
let content = std::fs::read_to_string(file.path()).unwrap();
|
||||||
|
assert!(content.contains("[srv]"));
|
||||||
|
assert!(content.contains("port=8080"));
|
||||||
|
assert!(!content.contains("[server]"));
|
||||||
|
}
|
||||||
|
}
|
||||||
+268
-18
@@ -1,30 +1,273 @@
|
|||||||
use std::io;
|
//! This module defines the unified data model used by `mould` to represent
|
||||||
|
//! configuration data across all supported file formats.
|
||||||
|
//!
|
||||||
|
//! By normalizing heterogeneous structures (like nested YAML or flat .env)
|
||||||
|
//! into a standard tree-like representation, the TUI logic remains
|
||||||
|
//! independent of the underlying file format.
|
||||||
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
pub mod env;
|
pub mod env;
|
||||||
pub mod hierarchical;
|
pub mod hierarchical;
|
||||||
|
pub mod ini;
|
||||||
|
pub mod properties;
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
/// Represents the status of a configuration item relative to its template.
|
||||||
pub struct EnvVar {
|
///
|
||||||
pub key: String,
|
/// This describes the *template comparison* only. Whether the user has edited
|
||||||
pub value: String,
|
/// an item during this session is tracked separately by [`ConfigItem::dirty`],
|
||||||
pub default_value: String,
|
/// so that a config which legitimately differs from its example file does not
|
||||||
|
/// render as if every line had just been touched.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum ItemStatus {
|
||||||
|
/// Item exists in the active configuration and matches the template (or no template exists).
|
||||||
|
Present,
|
||||||
|
/// Item exists in the template but is missing from the active configuration.
|
||||||
|
MissingFromActive,
|
||||||
|
/// Item exists in both, but the active value differs from the template default.
|
||||||
|
Overridden,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Hints about the original data type to ensure correct serialization during writes.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum ValueType {
|
||||||
|
/// Standard text.
|
||||||
|
String,
|
||||||
|
/// Numeric values (integers or floats).
|
||||||
|
Number,
|
||||||
|
/// True/False values.
|
||||||
|
Bool,
|
||||||
|
/// Representing an explicit null or empty value.
|
||||||
|
Null,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A single segment in a hierarchical configuration path.
|
||||||
|
///
|
||||||
|
/// For example, `services[0].image` would be represented as:
|
||||||
|
/// `[Key("services"), Index(0), Key("image")]`
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
|
pub enum PathSegment {
|
||||||
|
/// A named key in an object/map.
|
||||||
|
Key(String),
|
||||||
|
/// A numeric index in an array/list.
|
||||||
|
Index(usize),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for PathSegment {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
PathSegment::Key(k) => write!(f, "{}", k),
|
||||||
|
PathSegment::Index(i) => write!(f, "[{}]", i),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The unified representation of a single configuration entry.
|
||||||
|
///
|
||||||
|
/// This model is used for UI rendering and internal manipulation.
|
||||||
|
/// Format-specific handlers are responsible for translating their native
|
||||||
|
/// data into this structure.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ConfigItem {
|
||||||
|
/// The short display name of the key (e.g., `port`).
|
||||||
|
pub key: String,
|
||||||
|
/// The full hierarchical path defining this item's location in the config tree.
|
||||||
|
pub path: Vec<PathSegment>,
|
||||||
|
/// The active value of the configuration entry.
|
||||||
|
pub value: Option<String>,
|
||||||
|
/// The value found in the template file (if any).
|
||||||
|
pub template_value: Option<String>,
|
||||||
|
/// A fallback value to use if the item is missing.
|
||||||
|
pub default_value: Option<String>,
|
||||||
|
/// Visual depth in the tree (used for indentation in the TUI).
|
||||||
|
pub depth: usize,
|
||||||
|
/// True if this item represents a structural node (object or array) rather than a leaf value.
|
||||||
|
pub is_group: bool,
|
||||||
|
/// Comparison status relative to the template.
|
||||||
|
pub status: ItemStatus,
|
||||||
|
/// Metadata about the original data type.
|
||||||
|
pub value_type: ValueType,
|
||||||
|
/// True if the user changed this item during the current session.
|
||||||
|
pub dirty: bool,
|
||||||
|
/// True if this group's children are folded away in the tree view.
|
||||||
|
pub collapsed: bool,
|
||||||
|
/// Comment and blank lines that preceded this entry in the source file.
|
||||||
|
///
|
||||||
|
/// Replayed verbatim on write by formats that carry inline documentation
|
||||||
|
/// (currently `.env`), so that annotated templates survive a save.
|
||||||
|
pub leading_trivia: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for ConfigItem {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
key: String::new(),
|
||||||
|
path: Vec::new(),
|
||||||
|
value: None,
|
||||||
|
template_value: None,
|
||||||
|
default_value: None,
|
||||||
|
depth: 0,
|
||||||
|
is_group: false,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: ValueType::String,
|
||||||
|
dirty: false,
|
||||||
|
collapsed: false,
|
||||||
|
leading_trivia: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ConfigItem {
|
||||||
|
/// Builds a structural node (object, array, or section).
|
||||||
|
pub fn group(key: impl Into<String>, path: Vec<PathSegment>, depth: usize) -> Self {
|
||||||
|
Self {
|
||||||
|
key: key.into(),
|
||||||
|
path,
|
||||||
|
depth,
|
||||||
|
is_group: true,
|
||||||
|
value_type: ValueType::Null,
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds a leaf entry holding an actual value.
|
||||||
|
///
|
||||||
|
/// `template_value` and `default_value` are intentionally left unset: they are
|
||||||
|
/// populated by [`FormatHandler::merge`] from the template file, and mean
|
||||||
|
/// nothing when a file is parsed on its own.
|
||||||
|
pub fn leaf(
|
||||||
|
key: impl Into<String>,
|
||||||
|
path: Vec<PathSegment>,
|
||||||
|
value: impl Into<String>,
|
||||||
|
depth: usize,
|
||||||
|
value_type: ValueType,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
key: key.into(),
|
||||||
|
path,
|
||||||
|
value: Some(value.into()),
|
||||||
|
depth,
|
||||||
|
value_type,
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a human-readable string representation of the full path (e.g., `server.port`).
|
||||||
|
pub fn path_string(&self) -> String {
|
||||||
|
let mut s = String::new();
|
||||||
|
for (i, segment) in self.path.iter().enumerate() {
|
||||||
|
match segment {
|
||||||
|
PathSegment::Key(k) => {
|
||||||
|
if i > 0 {
|
||||||
|
s.push('.');
|
||||||
|
}
|
||||||
|
s.push_str(k);
|
||||||
|
}
|
||||||
|
PathSegment::Index(idx) => {
|
||||||
|
s.push_str(&format!("[{}]", idx));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True if this entry belongs in the output file.
|
||||||
|
///
|
||||||
|
/// Items that exist only in the template and have not been accepted by the
|
||||||
|
/// user are deliberately omitted, which is what makes the "(missing)" marker
|
||||||
|
/// mean something: nothing is written until it is pulled in explicitly.
|
||||||
|
pub fn should_write(&self) -> bool {
|
||||||
|
!self.is_group && self.status != ItemStatus::MissingFromActive
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The string that should be serialized for this entry.
|
||||||
|
pub fn write_value(&self) -> &str {
|
||||||
|
self.value.as_deref().unwrap_or("")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True if this item sits inside the subtree rooted at `prefix` (and is not `prefix` itself).
|
||||||
|
pub fn is_descendant_of(&self, prefix: &[PathSegment]) -> bool {
|
||||||
|
self.path.len() > prefix.len() && self.path.starts_with(prefix)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Supported configuration file formats.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum FormatType {
|
pub enum FormatType {
|
||||||
Env,
|
Env,
|
||||||
Json,
|
Json,
|
||||||
Yaml,
|
Yaml,
|
||||||
Toml,
|
Toml,
|
||||||
|
Xml,
|
||||||
|
Ini,
|
||||||
|
Properties,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Defines the interface for parsing, merging, and writing configuration files.
|
||||||
|
///
|
||||||
|
/// Implementing this trait allows `mould` to support new file formats.
|
||||||
pub trait FormatHandler {
|
pub trait FormatHandler {
|
||||||
fn parse(&self, path: &Path) -> io::Result<Vec<EnvVar>>;
|
/// Parses a file into the unified `Vec<ConfigItem>` representation.
|
||||||
fn merge(&self, path: &Path, vars: &mut Vec<EnvVar>) -> io::Result<()>;
|
fn parse(&self, path: &Path) -> anyhow::Result<Vec<ConfigItem>>;
|
||||||
fn write(&self, path: &Path, vars: &[EnvVar]) -> io::Result<()>;
|
|
||||||
|
/// Merges an active configuration with a template file.
|
||||||
|
///
|
||||||
|
/// This identifies missing keys, records template defaults, and splices
|
||||||
|
/// template-only entries in at their natural position so that the tree view
|
||||||
|
/// keeps reflecting the real structure.
|
||||||
|
fn merge(&self, path: &Path, vars: &mut Vec<ConfigItem>) -> anyhow::Result<()> {
|
||||||
|
if !path.exists() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let template_vars = self.parse(path)?;
|
||||||
|
|
||||||
|
for var in vars.iter_mut() {
|
||||||
|
if let Some(template_var) = template_vars.iter().find(|v| v.path == var.path) {
|
||||||
|
var.template_value = template_var.value.clone();
|
||||||
|
var.default_value = template_var.value.clone();
|
||||||
|
|
||||||
|
var.status = if var.value == template_var.value {
|
||||||
|
ItemStatus::Present
|
||||||
|
} else {
|
||||||
|
ItemStatus::Overridden
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
// Exists in active, but not in template.
|
||||||
|
var.status = ItemStatus::Present;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Splice in template-only entries. `template_vars` is in document order
|
||||||
|
// (a pre-order walk of the tree), so tracking an anchor as we go keeps
|
||||||
|
// each missing entry next to the siblings it belongs with instead of
|
||||||
|
// stranding it at the end of the list.
|
||||||
|
let mut anchor = 0usize;
|
||||||
|
for template_var in &template_vars {
|
||||||
|
if let Some(pos) = vars.iter().position(|v| v.path == template_var.path) {
|
||||||
|
anchor = pos + 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut new_item = template_var.clone();
|
||||||
|
new_item.status = ItemStatus::MissingFromActive;
|
||||||
|
new_item.template_value = template_var.value.clone();
|
||||||
|
new_item.default_value = template_var.value.clone();
|
||||||
|
new_item.value = None;
|
||||||
|
|
||||||
|
let at = anchor.min(vars.len());
|
||||||
|
vars.insert(at, new_item);
|
||||||
|
anchor = at + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes the unified representation back to the original file format.
|
||||||
|
fn write(&self, path: &Path, vars: &[ConfigItem]) -> anyhow::Result<()>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Automatically detects the configuration format based on file extension or an explicit override.
|
||||||
pub fn detect_format(path: &Path, override_format: Option<String>) -> FormatType {
|
pub fn detect_format(path: &Path, override_format: Option<String>) -> FormatType {
|
||||||
if let Some(fmt) = override_format {
|
if let Some(fmt) = override_format {
|
||||||
match fmt.to_lowercase().as_str() {
|
match fmt.to_lowercase().as_str() {
|
||||||
@@ -32,27 +275,34 @@ pub fn detect_format(path: &Path, override_format: Option<String>) -> FormatType
|
|||||||
"json" => return FormatType::Json,
|
"json" => return FormatType::Json,
|
||||||
"yaml" | "yml" => return FormatType::Yaml,
|
"yaml" | "yml" => return FormatType::Yaml,
|
||||||
"toml" => return FormatType::Toml,
|
"toml" => return FormatType::Toml,
|
||||||
|
"xml" => return FormatType::Xml,
|
||||||
|
"ini" => return FormatType::Ini,
|
||||||
|
"properties" => return FormatType::Properties,
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let file_name = path.file_name().unwrap_or_default().to_string_lossy();
|
let ext = path.extension().and_then(|s| s.to_str()).unwrap_or_default();
|
||||||
if file_name.ends_with(".json") {
|
match ext {
|
||||||
FormatType::Json
|
"json" => FormatType::Json,
|
||||||
} else if file_name.ends_with(".yaml") || file_name.ends_with(".yml") {
|
"yaml" | "yml" => FormatType::Yaml,
|
||||||
FormatType::Yaml
|
"toml" => FormatType::Toml,
|
||||||
} else if file_name.ends_with(".toml") {
|
"xml" => FormatType::Xml,
|
||||||
FormatType::Toml
|
"ini" => FormatType::Ini,
|
||||||
} else {
|
"properties" => FormatType::Properties,
|
||||||
FormatType::Env
|
_ => FormatType::Env,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Factory function to return the appropriate handler implementation for a given format.
|
||||||
pub fn get_handler(format: FormatType) -> Box<dyn FormatHandler> {
|
pub fn get_handler(format: FormatType) -> Box<dyn FormatHandler> {
|
||||||
match format {
|
match format {
|
||||||
FormatType::Env => Box::new(env::EnvHandler),
|
FormatType::Env => Box::new(env::EnvHandler),
|
||||||
FormatType::Json => Box::new(hierarchical::HierarchicalHandler::new(FormatType::Json)),
|
FormatType::Json => Box::new(hierarchical::HierarchicalHandler::new(FormatType::Json)),
|
||||||
FormatType::Yaml => Box::new(hierarchical::HierarchicalHandler::new(FormatType::Yaml)),
|
FormatType::Yaml => Box::new(hierarchical::HierarchicalHandler::new(FormatType::Yaml)),
|
||||||
FormatType::Toml => Box::new(hierarchical::HierarchicalHandler::new(FormatType::Toml)),
|
FormatType::Toml => Box::new(hierarchical::HierarchicalHandler::new(FormatType::Toml)),
|
||||||
|
FormatType::Xml => Box::new(hierarchical::HierarchicalHandler::new(FormatType::Xml)),
|
||||||
|
FormatType::Ini => Box::new(ini::IniHandler),
|
||||||
|
FormatType::Properties => Box::new(properties::PropertiesHandler),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
use super::{ConfigItem, FormatHandler, ValueType, PathSegment};
|
||||||
|
use java_properties::{LineContent, PropertiesIter, PropertiesWriter};
|
||||||
|
use std::fs::File;
|
||||||
|
use std::io::{BufReader, BufWriter};
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
pub struct PropertiesHandler;
|
||||||
|
|
||||||
|
impl FormatHandler for PropertiesHandler {
|
||||||
|
fn parse(&self, path: &Path) -> anyhow::Result<Vec<ConfigItem>> {
|
||||||
|
let file = File::open(path)?;
|
||||||
|
let reader = BufReader::new(file);
|
||||||
|
let iter = PropertiesIter::new(reader);
|
||||||
|
|
||||||
|
let mut vars = Vec::new();
|
||||||
|
let mut groups = std::collections::HashSet::new();
|
||||||
|
|
||||||
|
for line_result in iter {
|
||||||
|
let line = line_result?;
|
||||||
|
|
||||||
|
if let LineContent::KVPair(path, value) = line.consume_content() {
|
||||||
|
// Add groups based on dot notation
|
||||||
|
let parts: Vec<&str> = path.split('.').collect();
|
||||||
|
let mut current_path = Vec::new();
|
||||||
|
|
||||||
|
for (i, part) in parts.iter().enumerate().take(parts.len().saturating_sub(1)) {
|
||||||
|
current_path.push(PathSegment::Key(part.to_string()));
|
||||||
|
|
||||||
|
if groups.insert(current_path.clone()) {
|
||||||
|
vars.push(ConfigItem::group(*part, current_path.clone(), i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut final_path = current_path.clone();
|
||||||
|
let last_key = parts.last().unwrap_or(&"").to_string();
|
||||||
|
final_path.push(PathSegment::Key(last_key.clone()));
|
||||||
|
|
||||||
|
vars.push(ConfigItem::leaf(
|
||||||
|
last_key,
|
||||||
|
final_path,
|
||||||
|
value,
|
||||||
|
parts.len().saturating_sub(1),
|
||||||
|
ValueType::String,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
Ok(vars)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write(&self, path: &Path, vars: &[ConfigItem]) -> anyhow::Result<()> {
|
||||||
|
let file = File::create(path)?;
|
||||||
|
let writer = BufWriter::new(file);
|
||||||
|
let mut prop_writer = PropertiesWriter::new(writer);
|
||||||
|
|
||||||
|
for var in vars {
|
||||||
|
if var.should_write() {
|
||||||
|
prop_writer.write(&var.path_string(), var.write_value())?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
prop_writer.finish()?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use tempfile::NamedTempFile;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_group_rename_write() {
|
||||||
|
let handler = PropertiesHandler;
|
||||||
|
let mut vars = vec![
|
||||||
|
ConfigItem::group("server", vec![PathSegment::Key("server".to_string())], 0),
|
||||||
|
ConfigItem::leaf(
|
||||||
|
"port",
|
||||||
|
vec![PathSegment::Key("server".to_string()), PathSegment::Key("port".to_string())],
|
||||||
|
"8080",
|
||||||
|
1,
|
||||||
|
ValueType::String,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
|
// Rename "server" to "srv"
|
||||||
|
vars[0].key = "srv".to_string();
|
||||||
|
vars[0].path = vec![PathSegment::Key("srv".to_string())];
|
||||||
|
|
||||||
|
// Update child path
|
||||||
|
vars[1].path = vec![PathSegment::Key("srv".to_string()), PathSegment::Key("port".to_string())];
|
||||||
|
|
||||||
|
let file = NamedTempFile::new().unwrap();
|
||||||
|
handler.write(file.path(), &vars).unwrap();
|
||||||
|
|
||||||
|
let content = std::fs::read_to_string(file.path()).unwrap();
|
||||||
|
assert!(content.contains("srv.port=8080"));
|
||||||
|
assert!(!content.contains("server.port=8080"));
|
||||||
|
}
|
||||||
|
}
|
||||||
+56
-136
@@ -5,6 +5,8 @@ mod error;
|
|||||||
mod format;
|
mod format;
|
||||||
mod runner;
|
mod runner;
|
||||||
mod ui;
|
mod ui;
|
||||||
|
mod resolver;
|
||||||
|
mod undo;
|
||||||
|
|
||||||
use app::App;
|
use app::App;
|
||||||
use config::load_config;
|
use config::load_config;
|
||||||
@@ -13,123 +15,14 @@ use format::{detect_format, get_handler};
|
|||||||
use log::{error, info, warn};
|
use log::{error, info, warn};
|
||||||
use runner::AppRunner;
|
use runner::AppRunner;
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
|
|
||||||
|
use anyhow::Context;
|
||||||
use crossterm::{
|
use crossterm::{
|
||||||
event::{DisableMouseCapture, EnableMouseCapture},
|
|
||||||
execute,
|
execute,
|
||||||
terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
|
terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
|
||||||
};
|
};
|
||||||
use ratatui::{Terminal, backend::CrosstermBackend};
|
use ratatui::{Terminal, backend::CrosstermBackend};
|
||||||
|
|
||||||
/// 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();
|
|
||||||
|
|
||||||
// Standard mappings
|
|
||||||
if file_name == ".env.example" || file_name == ".env.template" {
|
|
||||||
return input.with_file_name(".env");
|
|
||||||
}
|
|
||||||
|
|
||||||
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<()> {
|
fn main() -> anyhow::Result<()> {
|
||||||
let args = cli::parse();
|
let args = cli::parse();
|
||||||
|
|
||||||
@@ -152,7 +45,7 @@ fn main() -> anyhow::Result<()> {
|
|||||||
}
|
}
|
||||||
path
|
path
|
||||||
}
|
}
|
||||||
None => match find_input_file() {
|
None => match resolver::find_input_file() {
|
||||||
Some(path) => {
|
Some(path) => {
|
||||||
info!("Discovered template: {}", path.display());
|
info!("Discovered template: {}", path.display());
|
||||||
path
|
path
|
||||||
@@ -171,55 +64,82 @@ fn main() -> anyhow::Result<()> {
|
|||||||
let format_type = detect_format(&input_path, args.format);
|
let format_type = detect_format(&input_path, args.format);
|
||||||
let handler = get_handler(format_type);
|
let handler = get_handler(format_type);
|
||||||
|
|
||||||
|
// Smart Comparison Logic
|
||||||
|
let (active_path, template_path) = resolver::resolve_paths(&input_path);
|
||||||
|
|
||||||
let output_path = args
|
let output_path = args
|
||||||
.output
|
.output
|
||||||
.unwrap_or_else(|| determine_output_path(&input_path));
|
.unwrap_or_else(|| active_path.clone().unwrap_or_else(|| resolver::determine_output_path(&input_path)));
|
||||||
|
|
||||||
info!("Output: {}", output_path.display());
|
info!("Output: {}", output_path.display());
|
||||||
|
|
||||||
let mut vars = handler.parse(&input_path).map_err(|e| {
|
// 1. Load active config if it exists.
|
||||||
error!("Failed to parse input file: {}", e);
|
//
|
||||||
MouldError::Format(format!("Failed to parse {}: {}", input_path.display(), e))
|
// A parse failure must be fatal: opening an editor over a file we could not
|
||||||
})?;
|
// read would present an empty document, and the next `:w` would truncate a
|
||||||
|
// perfectly good config.
|
||||||
|
let mut vars = if let Some(active) = &active_path {
|
||||||
|
handler
|
||||||
|
.parse(active)
|
||||||
|
.with_context(|| format!("could not parse {}", active.display()))?
|
||||||
|
} else {
|
||||||
|
Vec::new()
|
||||||
|
};
|
||||||
|
|
||||||
|
// 2. Load template config and merge
|
||||||
|
if let Some(template) = &template_path {
|
||||||
|
info!("Comparing with template: {}", template.display());
|
||||||
|
if vars.is_empty() {
|
||||||
|
vars = handler
|
||||||
|
.parse(template)
|
||||||
|
.with_context(|| format!("could not parse template {}", template.display()))?;
|
||||||
|
// Only the template exists, so nothing has been accepted into the
|
||||||
|
// active config yet. Keep each template value as the default on offer.
|
||||||
|
for v in vars.iter_mut() {
|
||||||
|
if !v.is_group {
|
||||||
|
v.status = crate::format::ItemStatus::MissingFromActive;
|
||||||
|
v.template_value = v.value.take();
|
||||||
|
v.default_value = v.template_value.clone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
handler
|
||||||
|
.merge(template, &mut vars)
|
||||||
|
.with_context(|| format!("could not parse template {}", template.display()))?;
|
||||||
|
}
|
||||||
|
} else if vars.is_empty() {
|
||||||
|
// Fallback if no template and active is empty
|
||||||
|
vars = handler
|
||||||
|
.parse(&input_path)
|
||||||
|
.with_context(|| format!("could not parse {}", input_path.display()))?;
|
||||||
|
}
|
||||||
|
|
||||||
if vars.is_empty() {
|
if vars.is_empty() {
|
||||||
warn!("No variables found in {}", input_path.display());
|
warn!("No variables found.");
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Err(e) = handler.merge(&output_path, &mut vars) {
|
let (config, config_error) = load_config();
|
||||||
warn!("Could not merge existing output file: {}", e);
|
let mut app = App::new(vars, output_path.clone(), template_path.clone());
|
||||||
|
if let Some(err) = config_error {
|
||||||
|
app.set_status(format!("config.toml ignored: {}", err));
|
||||||
}
|
}
|
||||||
|
|
||||||
let config = load_config();
|
|
||||||
let mut app = App::new(vars);
|
|
||||||
|
|
||||||
// Terminal lifecycle
|
// Terminal lifecycle
|
||||||
enable_raw_mode()
|
enable_raw_mode()
|
||||||
.map_err(|e| MouldError::Terminal(format!("Failed to enable raw mode: {}", e)))?;
|
.map_err(|e| MouldError::Terminal(format!("Failed to enable raw mode: {}", e)))?;
|
||||||
let mut stdout = io::stdout();
|
let mut stdout = io::stdout();
|
||||||
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)
|
execute!(stdout, EnterAlternateScreen)
|
||||||
.map_err(|e| MouldError::Terminal(format!("Failed to enter alternate screen: {}", e)))?;
|
.map_err(|e| MouldError::Terminal(format!("Failed to enter alternate screen: {}", e)))?;
|
||||||
let backend = CrosstermBackend::new(stdout);
|
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)))?;
|
.map_err(|e| MouldError::Terminal(format!("Failed to create terminal backend: {}", e)))?;
|
||||||
|
|
||||||
let mut runner = AppRunner::new(
|
let mut runner = AppRunner::new(&mut terminal, &mut app, &config, handler.as_ref());
|
||||||
&mut terminal,
|
|
||||||
&mut app,
|
|
||||||
&config,
|
|
||||||
&output_path,
|
|
||||||
handler.as_ref(),
|
|
||||||
);
|
|
||||||
let res = runner.run();
|
let res = runner.run();
|
||||||
|
|
||||||
// Restoration
|
// Restoration
|
||||||
disable_raw_mode().ok();
|
disable_raw_mode().ok();
|
||||||
execute!(
|
execute!(terminal.backend_mut(), LeaveAlternateScreen).ok();
|
||||||
terminal.backend_mut(),
|
|
||||||
LeaveAlternateScreen,
|
|
||||||
DisableMouseCapture
|
|
||||||
)
|
|
||||||
.ok();
|
|
||||||
terminal.show_cursor().ok();
|
terminal.show_cursor().ok();
|
||||||
|
|
||||||
match res {
|
match res {
|
||||||
|
|||||||
+294
@@ -0,0 +1,294 @@
|
|||||||
|
//! Automatically resolves relationships between template and active configuration files.
|
||||||
|
//!
|
||||||
|
//! The resolver allows `mould` to be run without explicit output arguments
|
||||||
|
//! by intelligently guessing the counterpart of a given input file based
|
||||||
|
//! on common naming conventions.
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
pub struct Rule {
|
||||||
|
pub template_suffix: &'static str,
|
||||||
|
pub active_suffix: &'static str,
|
||||||
|
pub is_exact_match: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const RULES: &[Rule] = &[
|
||||||
|
// Exact matches
|
||||||
|
Rule {
|
||||||
|
template_suffix: "compose.yml",
|
||||||
|
active_suffix: "compose.override.yml",
|
||||||
|
is_exact_match: true,
|
||||||
|
},
|
||||||
|
Rule {
|
||||||
|
template_suffix: "compose.yaml",
|
||||||
|
active_suffix: "compose.override.yaml",
|
||||||
|
is_exact_match: true,
|
||||||
|
},
|
||||||
|
Rule {
|
||||||
|
template_suffix: "docker-compose.yml",
|
||||||
|
active_suffix: "docker-compose.override.yml",
|
||||||
|
is_exact_match: true,
|
||||||
|
},
|
||||||
|
Rule {
|
||||||
|
template_suffix: "docker-compose.yaml",
|
||||||
|
active_suffix: "docker-compose.override.yaml",
|
||||||
|
is_exact_match: true,
|
||||||
|
},
|
||||||
|
// Pattern matches
|
||||||
|
Rule {
|
||||||
|
template_suffix: ".env.example",
|
||||||
|
active_suffix: ".env",
|
||||||
|
is_exact_match: false,
|
||||||
|
},
|
||||||
|
Rule {
|
||||||
|
template_suffix: ".env.template",
|
||||||
|
active_suffix: ".env",
|
||||||
|
is_exact_match: false,
|
||||||
|
},
|
||||||
|
Rule {
|
||||||
|
template_suffix: ".example.json",
|
||||||
|
active_suffix: ".json",
|
||||||
|
is_exact_match: false,
|
||||||
|
},
|
||||||
|
Rule {
|
||||||
|
template_suffix: ".template.json",
|
||||||
|
active_suffix: ".json",
|
||||||
|
is_exact_match: false,
|
||||||
|
},
|
||||||
|
Rule {
|
||||||
|
template_suffix: ".example.yml",
|
||||||
|
active_suffix: ".yml",
|
||||||
|
is_exact_match: false,
|
||||||
|
},
|
||||||
|
Rule {
|
||||||
|
template_suffix: ".template.yml",
|
||||||
|
active_suffix: ".yml",
|
||||||
|
is_exact_match: false,
|
||||||
|
},
|
||||||
|
Rule {
|
||||||
|
template_suffix: ".example.yaml",
|
||||||
|
active_suffix: ".yaml",
|
||||||
|
is_exact_match: false,
|
||||||
|
},
|
||||||
|
Rule {
|
||||||
|
template_suffix: ".template.yaml",
|
||||||
|
active_suffix: ".yaml",
|
||||||
|
is_exact_match: false,
|
||||||
|
},
|
||||||
|
Rule {
|
||||||
|
template_suffix: ".example.toml",
|
||||||
|
active_suffix: ".toml",
|
||||||
|
is_exact_match: false,
|
||||||
|
},
|
||||||
|
Rule {
|
||||||
|
template_suffix: ".template.toml",
|
||||||
|
active_suffix: ".toml",
|
||||||
|
is_exact_match: false,
|
||||||
|
},
|
||||||
|
Rule {
|
||||||
|
template_suffix: ".example.xml",
|
||||||
|
active_suffix: ".xml",
|
||||||
|
is_exact_match: false,
|
||||||
|
},
|
||||||
|
Rule {
|
||||||
|
template_suffix: ".template.xml",
|
||||||
|
active_suffix: ".xml",
|
||||||
|
is_exact_match: false,
|
||||||
|
},
|
||||||
|
Rule {
|
||||||
|
template_suffix: ".example.ini",
|
||||||
|
active_suffix: ".ini",
|
||||||
|
is_exact_match: false,
|
||||||
|
},
|
||||||
|
Rule {
|
||||||
|
template_suffix: ".template.ini",
|
||||||
|
active_suffix: ".ini",
|
||||||
|
is_exact_match: false,
|
||||||
|
},
|
||||||
|
Rule {
|
||||||
|
template_suffix: ".example.properties",
|
||||||
|
active_suffix: ".properties",
|
||||||
|
is_exact_match: false,
|
||||||
|
},
|
||||||
|
Rule {
|
||||||
|
template_suffix: ".template.properties",
|
||||||
|
active_suffix: ".properties",
|
||||||
|
is_exact_match: false,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
pub const DEFAULT_CANDIDATES: &[&str] = &[
|
||||||
|
".env.example",
|
||||||
|
"compose.yml",
|
||||||
|
"docker-compose.yml",
|
||||||
|
".env.template",
|
||||||
|
"compose.yaml",
|
||||||
|
"docker-compose.yaml",
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Helper to automatically determine the output file path based on common naming conventions.
|
||||||
|
pub fn determine_output_path(input: &Path) -> PathBuf {
|
||||||
|
let file_name = input.file_name().unwrap_or_default().to_string_lossy();
|
||||||
|
|
||||||
|
for rule in RULES {
|
||||||
|
if rule.is_exact_match {
|
||||||
|
if file_name == rule.template_suffix {
|
||||||
|
return input.with_file_name(rule.active_suffix);
|
||||||
|
}
|
||||||
|
} else if file_name == rule.template_suffix {
|
||||||
|
return input.with_file_name(rule.active_suffix);
|
||||||
|
} else if let Some(base) = file_name.strip_suffix(rule.template_suffix) {
|
||||||
|
return input.with_file_name(format!("{}{}", base, rule.active_suffix));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
input.with_extension(format!(
|
||||||
|
"{}.out",
|
||||||
|
input.extension().unwrap_or_default().to_string_lossy()
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Discovers common configuration template files in the current directory.
|
||||||
|
pub fn find_input_file() -> Option<PathBuf> {
|
||||||
|
// Priority 1: Exact matches for well-known defaults
|
||||||
|
for &name in DEFAULT_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();
|
||||||
|
|
||||||
|
for rule in RULES {
|
||||||
|
if !rule.is_exact_match && name_str.ends_with(rule.template_suffix) {
|
||||||
|
if name_str.contains(".env") || name_str.contains("compose") {
|
||||||
|
return Some(entry.path());
|
||||||
|
}
|
||||||
|
if fallback.is_none() {
|
||||||
|
fallback = Some(entry.path());
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(path) = fallback {
|
||||||
|
return Some(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolves the active and template paths given an input path.
|
||||||
|
/// Returns `(active_path, template_path)`.
|
||||||
|
pub fn resolve_paths(input: &Path) -> (Option<PathBuf>, Option<PathBuf>) {
|
||||||
|
let file_name = input.file_name().unwrap_or_default().to_string_lossy();
|
||||||
|
|
||||||
|
// Check if the input matches any known template pattern
|
||||||
|
let mut is_template = false;
|
||||||
|
for rule in RULES {
|
||||||
|
if rule.is_exact_match {
|
||||||
|
if file_name == rule.template_suffix {
|
||||||
|
is_template = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} else if file_name.ends_with(rule.template_suffix) {
|
||||||
|
is_template = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback template detection
|
||||||
|
if !is_template && (file_name.contains(".example") || file_name.contains(".template")) {
|
||||||
|
is_template = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if is_template {
|
||||||
|
let expected_active = determine_output_path(input);
|
||||||
|
let active = if expected_active.exists() {
|
||||||
|
Some(expected_active)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
(active, Some(input.to_path_buf()))
|
||||||
|
} else {
|
||||||
|
// Input is treated as the active config
|
||||||
|
let active = Some(input.to_path_buf());
|
||||||
|
let mut template = None;
|
||||||
|
|
||||||
|
// Try to reverse match rules to find a template
|
||||||
|
for rule in RULES {
|
||||||
|
if rule.is_exact_match {
|
||||||
|
if file_name == rule.active_suffix {
|
||||||
|
let t = input.with_file_name(rule.template_suffix);
|
||||||
|
if t.exists() {
|
||||||
|
template = Some(t);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if file_name.ends_with(rule.active_suffix) {
|
||||||
|
if file_name == rule.active_suffix {
|
||||||
|
let t = input.with_file_name(rule.template_suffix);
|
||||||
|
if t.exists() {
|
||||||
|
template = Some(t);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} else if let Some(base) = file_name.strip_suffix(rule.active_suffix) {
|
||||||
|
let t = input.with_file_name(format!("{}{}", base, rule.template_suffix));
|
||||||
|
if t.exists() {
|
||||||
|
template = Some(t);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback reverse detection
|
||||||
|
if template.is_none() {
|
||||||
|
let possible_templates = [
|
||||||
|
format!("{}.example", file_name),
|
||||||
|
format!("{}.template", file_name),
|
||||||
|
];
|
||||||
|
for t in possible_templates {
|
||||||
|
let p = input.with_file_name(t);
|
||||||
|
if p.exists() {
|
||||||
|
template = Some(p);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
(active, template)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_determine_output_path() {
|
||||||
|
assert_eq!(
|
||||||
|
determine_output_path(Path::new(".env.example")),
|
||||||
|
PathBuf::from(".env")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
determine_output_path(Path::new("compose.yml")),
|
||||||
|
PathBuf::from("compose.override.yml")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
determine_output_path(Path::new("config.template.json")),
|
||||||
|
PathBuf::from("config.json")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
determine_output_path(Path::new("config.example")),
|
||||||
|
PathBuf::from("config.example.out")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+254
-77
@@ -1,73 +1,116 @@
|
|||||||
use crate::app::{App, Mode};
|
//! Orchestrates the main application execution, terminal events, and TUI rendering.
|
||||||
use crate::config::Config;
|
//!
|
||||||
|
//! The `AppRunner` owns the event loop, turns raw key events into the
|
||||||
|
//! [`Action`]s declared in the user's config, and runs the `:` command line.
|
||||||
|
|
||||||
|
use crate::app::{App, InsertVariant, Mode};
|
||||||
|
use crate::config::{Action, Config};
|
||||||
use crate::format::FormatHandler;
|
use crate::format::FormatHandler;
|
||||||
use crossterm::event::{self, Event, KeyCode, KeyEvent};
|
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
|
||||||
use ratatui::Terminal;
|
use ratatui::Terminal;
|
||||||
use ratatui::backend::Backend;
|
use ratatui::backend::Backend;
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::path::Path;
|
use std::path::PathBuf;
|
||||||
|
use std::time::Duration;
|
||||||
use tui_input::backend::crossterm::EventHandler;
|
use tui_input::backend::crossterm::EventHandler;
|
||||||
|
|
||||||
|
/// How often the loop wakes up with no input, so timed UI state can settle.
|
||||||
|
const TICK: Duration = Duration::from_millis(250);
|
||||||
|
|
||||||
/// Manages the main application execution loop, event handling, and terminal interaction.
|
/// Manages the main application execution loop, event handling, and terminal interaction.
|
||||||
pub struct AppRunner<'a, B: Backend> {
|
pub struct AppRunner<'a, B: Backend> {
|
||||||
/// Reference to the terminal instance.
|
/// Reference to the terminal instance.
|
||||||
terminal: &'a mut Terminal<B>,
|
terminal: &'a mut Terminal<B>,
|
||||||
/// Mutable reference to the application state.
|
/// Mutable reference to the application state.
|
||||||
app: &'a mut App,
|
app: &'a mut App,
|
||||||
/// Loaded user configuration.
|
/// Loaded user configuration (keybinds, theme).
|
||||||
config: &'a Config,
|
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 for the specific file format (env, json, yaml, toml).
|
||||||
handler: &'a dyn FormatHandler,
|
handler: &'a dyn FormatHandler,
|
||||||
|
/// Every key sequence and the action it triggers, resolved from the config once.
|
||||||
|
bindings: Vec<(String, Action)>,
|
||||||
/// Buffer for storing active command entry (e.g., ":w").
|
/// Buffer for storing active command entry (e.g., ":w").
|
||||||
command_buffer: String,
|
command_buffer: String,
|
||||||
|
/// Buffer for storing multi-key sequence of presses (e.g., "gg").
|
||||||
|
key_sequence: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, B: Backend> AppRunner<'a, B>
|
impl<'a, B: Backend> AppRunner<'a, B>
|
||||||
where
|
where
|
||||||
io::Error: From<B::Error>,
|
io::Error: From<B::Error>,
|
||||||
{
|
{
|
||||||
/// Creates a new runner instance.
|
/// Creates a new runner instance with all required dependencies.
|
||||||
pub fn new(
|
pub fn new(
|
||||||
terminal: &'a mut Terminal<B>,
|
terminal: &'a mut Terminal<B>,
|
||||||
app: &'a mut App,
|
app: &'a mut App,
|
||||||
config: &'a Config,
|
config: &'a Config,
|
||||||
output_path: &'a Path,
|
|
||||||
handler: &'a dyn FormatHandler,
|
handler: &'a dyn FormatHandler,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
terminal,
|
terminal,
|
||||||
app,
|
app,
|
||||||
config,
|
config,
|
||||||
output_path,
|
|
||||||
handler,
|
handler,
|
||||||
|
bindings: config.keybinds.resolved(),
|
||||||
command_buffer: String::new(),
|
command_buffer: String::new(),
|
||||||
|
key_sequence: String::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Starts the main application loop.
|
/// Starts the main application loop.
|
||||||
|
///
|
||||||
|
/// This loop continues until `self.app.running` is set to false. It polls
|
||||||
|
/// rather than blocking so that a resize or an expiring status message
|
||||||
|
/// repaints without waiting for the next keystroke.
|
||||||
pub fn run(&mut self) -> io::Result<()> {
|
pub fn run(&mut self) -> io::Result<()> {
|
||||||
while self.app.running {
|
while self.app.running {
|
||||||
self.terminal
|
self.terminal
|
||||||
.draw(|f| crate::ui::draw(f, self.app, self.config))?;
|
.draw(|f| crate::ui::draw(f, self.app, self.config))?;
|
||||||
|
|
||||||
if let Event::Key(key) = event::read()? {
|
if !event::poll(TICK)? {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
match event::read()? {
|
||||||
|
// Key *releases* are delivered on some terminals; acting on both
|
||||||
|
// edges would fire every binding twice.
|
||||||
|
Event::Key(key) if key.kind != KeyEventKind::Release => {
|
||||||
self.handle_key_event(key)?;
|
self.handle_key_event(key)?;
|
||||||
}
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Primary dispatcher for all keyboard events.
|
/// Primary dispatcher for all keyboard events.
|
||||||
|
///
|
||||||
|
/// It delegates handling to specialized methods based on the
|
||||||
|
/// current application mode.
|
||||||
fn handle_key_event(&mut self, key: KeyEvent) -> io::Result<()> {
|
fn handle_key_event(&mut self, key: KeyEvent) -> io::Result<()> {
|
||||||
match self.app.mode {
|
match self.app.mode {
|
||||||
Mode::Normal => self.handle_normal_mode(key),
|
Mode::Normal => self.handle_normal_mode(key),
|
||||||
Mode::Insert => self.handle_insert_mode(key),
|
Mode::Insert | Mode::InsertKey => self.handle_insert_mode(key),
|
||||||
Mode::Search => self.handle_search_mode(key),
|
Mode::Search => self.handle_search_mode(key),
|
||||||
|
Mode::Help => self.handle_help_mode(key),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The help overlay scrolls with the usual movement keys; anything else closes it.
|
||||||
|
fn handle_help_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
||||||
|
let token = Self::key_token(key);
|
||||||
|
let is = |action| token.as_deref() == Some(self.config.keybinds.key_for(action)).as_deref();
|
||||||
|
|
||||||
|
if is(Action::Down) || key.code == KeyCode::Down {
|
||||||
|
self.app.scroll_help(true);
|
||||||
|
} else if is(Action::Up) || key.code == KeyCode::Up {
|
||||||
|
self.app.scroll_help(false);
|
||||||
|
} else {
|
||||||
|
self.app.toggle_help();
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Handles keys in Normal mode, separating navigation from command entry.
|
/// Handles keys in Normal mode, separating navigation from command entry.
|
||||||
fn handle_normal_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
fn handle_normal_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
||||||
if !self.command_buffer.is_empty() {
|
if !self.command_buffer.is_empty() {
|
||||||
@@ -83,68 +126,156 @@ where
|
|||||||
KeyCode::Enter => {
|
KeyCode::Enter => {
|
||||||
let cmd = self.command_buffer.clone();
|
let cmd = self.command_buffer.clone();
|
||||||
self.command_buffer.clear();
|
self.command_buffer.clear();
|
||||||
self.execute_command(&cmd)
|
self.app.prompt = None;
|
||||||
|
self.execute_command(cmd.trim())
|
||||||
}
|
}
|
||||||
KeyCode::Esc => {
|
KeyCode::Esc => {
|
||||||
self.command_buffer.clear();
|
self.command_buffer.clear();
|
||||||
self.app.status_message = None;
|
self.app.prompt = None;
|
||||||
|
self.app.clear_status();
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
KeyCode::Backspace => {
|
KeyCode::Backspace => {
|
||||||
self.command_buffer.pop();
|
self.command_buffer.pop();
|
||||||
self.sync_command_status();
|
self.sync_command_prompt();
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
KeyCode::Char(c) => {
|
KeyCode::Char(c) => {
|
||||||
self.command_buffer.push(c);
|
self.command_buffer.push(c);
|
||||||
self.sync_command_status();
|
self.sync_command_prompt();
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
_ => Ok(()),
|
_ => Ok(()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handles primary navigation (j/k) and transitions to insert or command modes.
|
/// Renders a key event as the string used in the keybinding config.
|
||||||
fn handle_navigation_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
///
|
||||||
if let KeyCode::Char(c) = key.code {
|
/// Named keys are spelled in angle brackets (`<Space>`) so that they can
|
||||||
let c_str = c.to_string();
|
/// never be confused with a sequence of ordinary characters.
|
||||||
if c_str == self.config.keybinds.down {
|
fn key_token(key: KeyEvent) -> Option<String> {
|
||||||
self.app.next();
|
let base = match key.code {
|
||||||
} else if c_str == self.config.keybinds.up {
|
KeyCode::Char(' ') => "<Space>".to_string(),
|
||||||
self.app.previous();
|
KeyCode::Char(c) => c.to_string(),
|
||||||
} else if c_str == self.config.keybinds.edit {
|
KeyCode::Tab => "<Tab>".to_string(),
|
||||||
self.app.enter_insert();
|
KeyCode::BackTab => "<S-Tab>".to_string(),
|
||||||
} else if c_str == ":" {
|
_ => return None,
|
||||||
self.command_buffer.push(':');
|
};
|
||||||
self.sync_command_status();
|
|
||||||
} else if c_str == "q" {
|
if key.modifiers.contains(KeyModifiers::ALT) {
|
||||||
self.app.running = false;
|
Some(format!("alt+{}", base))
|
||||||
} else if c_str == self.config.keybinds.search {
|
|
||||||
self.app.mode = Mode::Search;
|
|
||||||
self.app.search_query.clear();
|
|
||||||
self.app.status_message = Some(format!("{} ", self.config.keybinds.search));
|
|
||||||
} else if c_str == self.config.keybinds.next_match {
|
|
||||||
self.app.jump_next_match();
|
|
||||||
} else if c_str == self.config.keybinds.previous_match {
|
|
||||||
self.app.jump_previous_match();
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
|
Some(base)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handles primary navigation and transitions to insert or command modes.
|
||||||
|
///
|
||||||
|
/// This method manages multi-key sequences (like `gg`) and immediate
|
||||||
|
/// actions (like `i`). It correctly re-evaluates sequences to prevent
|
||||||
|
/// "one-key-behind" responsiveness bugs.
|
||||||
|
fn handle_navigation_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
||||||
|
let Some(token) = Self::key_token(key) else {
|
||||||
|
// Reset the sequence buffer if a non-character key is pressed.
|
||||||
|
self.key_sequence.clear();
|
||||||
match key.code {
|
match key.code {
|
||||||
KeyCode::Down => self.app.next(),
|
KeyCode::Down => self.app.next(),
|
||||||
KeyCode::Up => self.app.previous(),
|
KeyCode::Up => self.app.previous(),
|
||||||
KeyCode::Enter => self.save_file()?,
|
KeyCode::Enter => {
|
||||||
|
self.save_file(None);
|
||||||
|
}
|
||||||
|
KeyCode::Esc => self.app.clear_status(),
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
|
||||||
|
self.key_sequence.push_str(&token);
|
||||||
|
|
||||||
|
let mut action = self.find_binding();
|
||||||
|
if action.is_none() {
|
||||||
|
if self.is_prefix_binding() {
|
||||||
|
// A partial multi-key bind (like the first 'g' of 'gg'): wait.
|
||||||
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
// Not a match and not a prefix: restart from the current key.
|
||||||
|
self.key_sequence = token;
|
||||||
|
action = self.find_binding();
|
||||||
|
if action.is_none() && !self.is_prefix_binding() {
|
||||||
|
self.key_sequence.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let Some(action) = action else { return Ok(()) };
|
||||||
|
self.key_sequence.clear();
|
||||||
|
self.dispatch(action);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Applies a resolved action to the application state.
|
||||||
|
fn dispatch(&mut self, action: Action) {
|
||||||
|
match action {
|
||||||
|
Action::Down => self.app.next(),
|
||||||
|
Action::Up => self.app.previous(),
|
||||||
|
Action::JumpTop => self.app.jump_top(),
|
||||||
|
Action::JumpBottom => self.app.jump_bottom(),
|
||||||
|
Action::Edit => self.app.enter_insert(InsertVariant::Start),
|
||||||
|
Action::EditAppend => self.app.enter_insert(InsertVariant::End),
|
||||||
|
Action::EditSubstitute => self.app.enter_insert(InsertVariant::Substitute),
|
||||||
|
Action::Rename => self.app.enter_insert_key(),
|
||||||
|
Action::Search => {
|
||||||
|
self.app.begin_search();
|
||||||
|
self.sync_search_prompt();
|
||||||
|
}
|
||||||
|
Action::NextMatch => self.app.jump_next_match(),
|
||||||
|
Action::PreviousMatch => self.app.jump_previous_match(),
|
||||||
|
Action::AppendItem => self.app.add_item(true, false, false),
|
||||||
|
Action::PrependItem => self.app.add_item(false, false, false),
|
||||||
|
Action::AppendGroup => self.app.add_item(true, true, true),
|
||||||
|
Action::PrependGroup => self.app.add_item(false, true, true),
|
||||||
|
Action::DeleteItem => self.app.delete_selected(),
|
||||||
|
Action::ToggleGroup => {
|
||||||
|
self.app.toggle_group_selected();
|
||||||
|
self.app.save_undo_state();
|
||||||
|
}
|
||||||
|
Action::AddMissing => self.app.accept_selected(),
|
||||||
|
Action::AcceptAll => self.app.accept_all_missing(),
|
||||||
|
Action::ToggleFold => self.app.toggle_fold(),
|
||||||
|
Action::FoldAll => self.app.set_all_folds(true),
|
||||||
|
Action::UnfoldAll => self.app.set_all_folds(false),
|
||||||
|
Action::Undo => self.app.undo(),
|
||||||
|
Action::Redo => self.app.redo(),
|
||||||
|
Action::UndoBranchPrev => self.app.cycle_undo_branch(false),
|
||||||
|
Action::UndoBranchNext => self.app.cycle_undo_branch(true),
|
||||||
|
Action::Help => self.app.toggle_help(),
|
||||||
|
Action::Command => {
|
||||||
|
self.command_buffer.push(':');
|
||||||
|
self.sync_command_prompt();
|
||||||
|
}
|
||||||
|
Action::Quit => self.request_quit(false),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Looks up the current `key_sequence` in the configured keybindings.
|
||||||
|
fn find_binding(&self) -> Option<Action> {
|
||||||
|
self.bindings
|
||||||
|
.iter()
|
||||||
|
.find(|(bind, _)| *bind == self.key_sequence)
|
||||||
|
.map(|(_, action)| *action)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns true if the current `key_sequence` is a partial prefix of any configured bind.
|
||||||
|
fn is_prefix_binding(&self) -> bool {
|
||||||
|
self.bindings
|
||||||
|
.iter()
|
||||||
|
.any(|(bind, _)| bind.starts_with(&self.key_sequence) && bind != &self.key_sequence)
|
||||||
|
}
|
||||||
|
|
||||||
/// Delegates key events to the `tui_input` handler during active editing.
|
/// Delegates key events to the `tui_input` handler during active editing.
|
||||||
fn handle_insert_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
fn handle_insert_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
||||||
match key.code {
|
match key.code {
|
||||||
KeyCode::Esc | KeyCode::Enter => {
|
KeyCode::Esc => self.app.cancel_insert(),
|
||||||
self.app.enter_normal();
|
KeyCode::Enter => self.app.enter_normal(),
|
||||||
}
|
|
||||||
_ => {
|
_ => {
|
||||||
self.app.input.handle_event(&Event::Key(key));
|
self.app.input.handle_event(&Event::Key(key));
|
||||||
}
|
}
|
||||||
@@ -152,21 +283,21 @@ where
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handles search mode key events.
|
/// Handles search mode key events and live-updates the match position.
|
||||||
fn handle_search_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
fn handle_search_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
||||||
match key.code {
|
match key.code {
|
||||||
KeyCode::Enter | KeyCode::Esc => {
|
// Enter keeps the query so `n`/`N` continue to work; Esc abandons it
|
||||||
self.app.mode = Mode::Normal;
|
// and puts the cursor back where the search started.
|
||||||
self.app.status_message = None;
|
KeyCode::Enter => self.app.end_search(true),
|
||||||
}
|
KeyCode::Esc => self.app.end_search(false),
|
||||||
KeyCode::Backspace => {
|
KeyCode::Backspace => {
|
||||||
self.app.search_query.pop();
|
self.app.search_query.pop();
|
||||||
self.app.status_message = Some(format!("{}{}", self.config.keybinds.search, self.app.search_query));
|
self.sync_search_prompt();
|
||||||
self.app.jump_next_match();
|
self.app.jump_next_match();
|
||||||
}
|
}
|
||||||
KeyCode::Char(c) => {
|
KeyCode::Char(c) => {
|
||||||
self.app.search_query.push(c);
|
self.app.search_query.push(c);
|
||||||
self.app.status_message = Some(format!("{}{}", self.config.keybinds.search, self.app.search_query));
|
self.sync_search_prompt();
|
||||||
self.app.jump_next_match();
|
self.app.jump_next_match();
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
@@ -174,39 +305,85 @@ where
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Logic to map command strings (like ":w") to internal application actions.
|
/// Maps command strings (like `:w`) to internal application actions.
|
||||||
fn execute_command(&mut self, cmd: &str) -> io::Result<()> {
|
fn execute_command(&mut self, cmd: &str) -> io::Result<()> {
|
||||||
if cmd == self.config.keybinds.save {
|
let kb = &self.config.keybinds;
|
||||||
self.save_file()
|
let save = kb.save.clone();
|
||||||
} else if cmd == self.config.keybinds.quit {
|
let quit = kb.quit.clone();
|
||||||
self.app.running = false;
|
|
||||||
Ok(())
|
// `:w some/other/path` retargets the write without changing the session.
|
||||||
} else if cmd == ":wq" {
|
if let Some(rest) = cmd.strip_prefix(&format!("{} ", save)) {
|
||||||
self.save_file()?;
|
let target = PathBuf::from(rest.trim());
|
||||||
self.app.running = false;
|
self.save_file(Some(target));
|
||||||
Ok(())
|
return Ok(());
|
||||||
} else {
|
|
||||||
self.app.status_message = Some(format!("Unknown command: {}", cmd));
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Attempts to write the current app state to the specified output file.
|
match cmd {
|
||||||
fn save_file(&mut self) -> io::Result<()> {
|
c if c == save => {
|
||||||
if self.handler.write(self.output_path, &self.app.vars).is_ok() {
|
self.save_file(None);
|
||||||
self.app.status_message = Some(format!("Saved to {}", self.output_path.display()));
|
}
|
||||||
} else {
|
c if c == quit => self.request_quit(false),
|
||||||
self.app.status_message = Some("Error saving file".to_string());
|
":q!" => self.request_quit(true),
|
||||||
|
":wq" | ":x" => {
|
||||||
|
if self.save_file(None) {
|
||||||
|
self.app.running = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
":help" | ":h" => self.app.toggle_help(),
|
||||||
|
other => self.app.set_status(format!("Unknown command: {}", other)),
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Synchronizes the status bar display with the active command buffer.
|
/// Quits, refusing to discard unsaved work unless `force` is set.
|
||||||
fn sync_command_status(&mut self) {
|
fn request_quit(&mut self, force: bool) {
|
||||||
if self.command_buffer.is_empty() {
|
if self.app.is_dirty && !force {
|
||||||
self.app.status_message = None;
|
self.app.set_status(format!(
|
||||||
} else {
|
"Unsaved changes — {} to save, :q! to discard",
|
||||||
self.app.status_message = Some(self.command_buffer.clone());
|
self.config.keybinds.save
|
||||||
|
));
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
self.app.running = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes the current state to disk. Returns true on success.
|
||||||
|
fn save_file(&mut self, target: Option<PathBuf>) -> bool {
|
||||||
|
let path = target.unwrap_or_else(|| self.app.output_path.clone());
|
||||||
|
match self.handler.write(&path, &self.app.vars) {
|
||||||
|
Ok(()) => {
|
||||||
|
self.app.output_path = path.clone();
|
||||||
|
self.app.is_dirty = false;
|
||||||
|
for var in self.app.vars.iter_mut() {
|
||||||
|
var.dirty = false;
|
||||||
|
}
|
||||||
|
self.app.set_status(format!("Saved to {}", path.display()));
|
||||||
|
true
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
// The reason matters: a read-only path and an unrepresentable
|
||||||
|
// document fail very differently.
|
||||||
|
self.app.set_status(format!("Could not save {}: {}", path.display(), e));
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Synchronizes the prompt line with the active command buffer.
|
||||||
|
fn sync_command_prompt(&mut self) {
|
||||||
|
self.app.prompt = if self.command_buffer.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(self.command_buffer.clone())
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Synchronizes the prompt line with the active search query.
|
||||||
|
fn sync_search_prompt(&mut self) {
|
||||||
|
self.app.prompt = Some(format!(
|
||||||
|
"{}{}",
|
||||||
|
self.config.keybinds.key_for(Action::Search),
|
||||||
|
self.app.search_query
|
||||||
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,11 +1,18 @@
|
|||||||
|
//! Renders the hierarchical Terminal User Interface (TUI).
|
||||||
|
//!
|
||||||
|
//! The screen is four things stacked: a header naming the files in play, the
|
||||||
|
//! item tree, a detail/edit pane for the selection, and a status bar. Nothing
|
||||||
|
//! here mutates state beyond the widget list itself.
|
||||||
|
|
||||||
use crate::app::{App, Mode};
|
use crate::app::{App, Mode};
|
||||||
use crate::config::Config;
|
use crate::config::{Action, Config, ThemeConfig};
|
||||||
|
use crate::format::{ItemStatus, ValueType};
|
||||||
use ratatui::{
|
use ratatui::{
|
||||||
Frame,
|
Frame,
|
||||||
layout::{Constraint, Direction, Layout},
|
layout::{Alignment, Constraint, Direction, Layout, Rect},
|
||||||
style::{Modifier, Style},
|
style::{Modifier, Style},
|
||||||
text::{Line, Span},
|
text::{Line, Span},
|
||||||
widgets::{Block, BorderType, Borders, List, ListItem, ListState, Paragraph},
|
widgets::{Block, BorderType, Borders, Clear, List, ListItem, ListState, Paragraph},
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Renders the main application interface using ratatui.
|
/// Renders the main application interface using ratatui.
|
||||||
@@ -13,15 +20,15 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
|||||||
let theme = &config.theme;
|
let theme = &config.theme;
|
||||||
let size = f.area();
|
let size = f.area();
|
||||||
|
|
||||||
// Render the main background (optional based on transparency config).
|
// Render the main background.
|
||||||
if !theme.transparent {
|
if !theme.transparent {
|
||||||
f.render_widget(
|
f.render_widget(
|
||||||
Block::default().style(Style::default().bg(theme.crust())),
|
Block::default().style(Style::default().bg(theme.bg_normal())),
|
||||||
size,
|
size,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Horizontal layout with 1-character side margins.
|
// Define outer margins.
|
||||||
let outer_layout = Layout::default()
|
let outer_layout = Layout::default()
|
||||||
.direction(Direction::Horizontal)
|
.direction(Direction::Horizontal)
|
||||||
.constraints([
|
.constraints([
|
||||||
@@ -31,98 +38,157 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
|||||||
])
|
])
|
||||||
.split(size);
|
.split(size);
|
||||||
|
|
||||||
// Vertical layout for the main UI components.
|
// Split the center area vertically.
|
||||||
let chunks = Layout::default()
|
let chunks = Layout::default()
|
||||||
.direction(Direction::Vertical)
|
.direction(Direction::Vertical)
|
||||||
.constraints([
|
.constraints([
|
||||||
Constraint::Length(1), // Top margin
|
Constraint::Length(1), // Top margin
|
||||||
Constraint::Min(3), // Main list
|
Constraint::Min(3), // Main tree list
|
||||||
Constraint::Length(3), // Focused input field
|
Constraint::Length(3), // Detail / edit pane
|
||||||
Constraint::Length(1), // Spacer
|
Constraint::Length(1), // Spacer
|
||||||
Constraint::Length(1), // Status bar
|
Constraint::Length(1), // Status bar
|
||||||
])
|
])
|
||||||
.split(outer_layout[1]);
|
.split(outer_layout[1]);
|
||||||
|
|
||||||
// Build the interactive list of configuration variables.
|
draw_tree(f, chunks[1], app, config);
|
||||||
let matching_indices = app.matching_indices();
|
draw_detail(f, chunks[2], app, theme);
|
||||||
let items: Vec<ListItem> = app
|
draw_status(f, chunks[4], app, config);
|
||||||
.vars
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.map(|(i, var)| {
|
|
||||||
let is_selected = i == app.selected;
|
|
||||||
let is_match = matching_indices.contains(&i);
|
|
||||||
|
|
||||||
// Show live input text for the selected item if in Insert mode.
|
if app.mode == Mode::Help {
|
||||||
let val = if is_selected && matches!(app.mode, Mode::Insert) {
|
draw_help(f, size, config, app.help_scroll);
|
||||||
app.input.value()
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renders the item tree, skipping anything inside a folded group.
|
||||||
|
fn draw_tree(f: &mut Frame, area: Rect, app: &App, config: &Config) {
|
||||||
|
let theme = &config.theme;
|
||||||
|
let matching = app.matching_indices();
|
||||||
|
let visible = app.visible_indices();
|
||||||
|
|
||||||
|
let items: Vec<ListItem> = visible
|
||||||
|
.iter()
|
||||||
|
.map(|&i| {
|
||||||
|
let var = &app.vars[i];
|
||||||
|
let is_selected = i == app.selected;
|
||||||
|
let is_match = matching.contains(&i);
|
||||||
|
let is_missing = var.status == ItemStatus::MissingFromActive;
|
||||||
|
|
||||||
|
let indent = " ".repeat(var.depth);
|
||||||
|
// A group that can be folded says so; leaves are just indented.
|
||||||
|
let prefix = if var.is_group {
|
||||||
|
if var.collapsed { "▸ " } else { "▾ " }
|
||||||
} else {
|
} else {
|
||||||
&var.value
|
" "
|
||||||
|
};
|
||||||
|
|
||||||
|
let depth_color = match var.depth % 4 {
|
||||||
|
0 => theme.tree_depth_1(),
|
||||||
|
1 => theme.tree_depth_2(),
|
||||||
|
2 => theme.tree_depth_3(),
|
||||||
|
_ => theme.tree_depth_4(),
|
||||||
};
|
};
|
||||||
|
|
||||||
let key_style = if is_selected {
|
let key_style = if is_selected {
|
||||||
Style::default()
|
Style::default()
|
||||||
.fg(theme.crust())
|
.fg(theme.fg_highlight())
|
||||||
.add_modifier(Modifier::BOLD)
|
.add_modifier(Modifier::BOLD)
|
||||||
} else if is_match {
|
} else if is_match {
|
||||||
Style::default()
|
Style::default()
|
||||||
.fg(theme.mauve())
|
.fg(theme.bg_search())
|
||||||
.add_modifier(Modifier::UNDERLINED)
|
.add_modifier(Modifier::UNDERLINED)
|
||||||
} else {
|
} else if is_missing {
|
||||||
Style::default().fg(theme.lavender())
|
|
||||||
};
|
|
||||||
|
|
||||||
let value_style = if is_selected {
|
|
||||||
Style::default().fg(theme.crust())
|
|
||||||
} else {
|
|
||||||
Style::default().fg(theme.text())
|
|
||||||
};
|
|
||||||
|
|
||||||
// Path styling for nested keys (e.g., a.b.c)
|
|
||||||
let mut key_spans = Vec::new();
|
|
||||||
if let Some(last_dot) = var.key.rfind('.') {
|
|
||||||
let path = &var.key[..=last_dot];
|
|
||||||
let key = &var.key[last_dot + 1..];
|
|
||||||
|
|
||||||
let path_style = if is_selected {
|
|
||||||
Style::default()
|
Style::default()
|
||||||
.fg(theme.crust())
|
.fg(theme.fg_dimmed())
|
||||||
.add_modifier(Modifier::DIM)
|
.add_modifier(Modifier::DIM)
|
||||||
} else {
|
} else {
|
||||||
Style::default().fg(theme.surface1())
|
Style::default().fg(depth_color)
|
||||||
};
|
};
|
||||||
|
|
||||||
key_spans.push(Span::styled(path, path_style));
|
let mut key_spans = vec![
|
||||||
key_spans.push(Span::styled(key, key_style));
|
Span::raw(indent.clone()),
|
||||||
|
Span::styled(prefix, Style::default().fg(theme.border_normal())),
|
||||||
|
Span::styled(&var.key, key_style),
|
||||||
|
];
|
||||||
|
|
||||||
|
let tag_style = |color| {
|
||||||
|
if is_selected {
|
||||||
|
Style::default()
|
||||||
|
.fg(theme.fg_highlight())
|
||||||
|
.add_modifier(Modifier::BOLD)
|
||||||
} else {
|
} else {
|
||||||
key_spans.push(Span::styled(&var.key, key_style));
|
Style::default().fg(color).add_modifier(Modifier::BOLD)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if is_missing {
|
||||||
|
let label = if var.is_group { " (missing group)" } else { " (missing)" };
|
||||||
|
key_spans.push(Span::styled(label, tag_style(theme.fg_warning())));
|
||||||
|
}
|
||||||
|
// "changed" means changed by you, in this session — not merely
|
||||||
|
// different from the template, which is the normal case.
|
||||||
|
if var.dirty {
|
||||||
|
key_spans.push(Span::styled(" (*)", tag_style(theme.fg_modified())));
|
||||||
|
}
|
||||||
|
if var.is_group && var.collapsed {
|
||||||
|
let hidden = app.vars.iter().filter(|v| v.is_descendant_of(&var.path)).count();
|
||||||
|
key_spans.push(Span::styled(
|
||||||
|
format!(" {} hidden", hidden),
|
||||||
|
Style::default().fg(theme.fg_dimmed()),
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let item_style = if is_selected {
|
let item_style = if is_selected {
|
||||||
Style::default().bg(theme.blue())
|
Style::default().bg(theme.bg_highlight())
|
||||||
} else {
|
} else {
|
||||||
Style::default().fg(theme.text())
|
Style::default().fg(theme.fg_normal())
|
||||||
};
|
};
|
||||||
|
|
||||||
// Two-line layout for better readability:
|
if var.is_group {
|
||||||
// Line 1: Key (path.key)
|
return ListItem::new(Line::from(key_spans)).style(item_style);
|
||||||
// Line 2: Value
|
}
|
||||||
let lines = vec![
|
|
||||||
Line::from(key_spans),
|
|
||||||
Line::from(vec![
|
|
||||||
Span::styled(
|
|
||||||
" └─ ",
|
|
||||||
if is_selected {
|
|
||||||
Style::default().fg(theme.crust())
|
|
||||||
} else {
|
|
||||||
Style::default().fg(theme.surface1())
|
|
||||||
},
|
|
||||||
),
|
|
||||||
Span::styled(val, value_style),
|
|
||||||
]),
|
|
||||||
];
|
|
||||||
|
|
||||||
ListItem::new(lines).style(item_style)
|
// Value line.
|
||||||
|
let live_edit = is_selected && app.mode == Mode::Insert;
|
||||||
|
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!("{} └─ ", indent))];
|
||||||
|
|
||||||
|
if live_edit {
|
||||||
|
val_spans.push(Span::styled(app.input.value().to_string(), value_style));
|
||||||
|
} else if is_missing {
|
||||||
|
// Nothing has been accepted yet, so show what is on offer.
|
||||||
|
let offer = var.template_value.as_deref().unwrap_or("");
|
||||||
|
val_spans.push(Span::styled(
|
||||||
|
format!("({})", offer),
|
||||||
|
Style::default()
|
||||||
|
.fg(theme.fg_dimmed())
|
||||||
|
.add_modifier(Modifier::ITALIC),
|
||||||
|
));
|
||||||
|
} else {
|
||||||
|
val_spans.push(Span::styled(
|
||||||
|
var.value.as_deref().unwrap_or("").to_string(),
|
||||||
|
value_style,
|
||||||
|
));
|
||||||
|
|
||||||
|
if let Some(default) = &var.template_value
|
||||||
|
&& Some(default) != var.value.as_ref()
|
||||||
|
{
|
||||||
|
let 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!(" [default: {}]", default), style));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ListItem::new(vec![Line::from(key_spans), Line::from(val_spans)]).style(item_style)
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
@@ -130,105 +196,505 @@ pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
|||||||
Block::default()
|
Block::default()
|
||||||
.borders(Borders::ALL)
|
.borders(Borders::ALL)
|
||||||
.border_type(BorderType::Rounded)
|
.border_type(BorderType::Rounded)
|
||||||
.title(" Config Variables ")
|
.title(file_header(app, theme))
|
||||||
.title_style(
|
.title(counts_header(app, theme))
|
||||||
Style::default()
|
.border_style(Style::default().fg(theme.border_normal())),
|
||||||
.fg(theme.mauve())
|
|
||||||
.add_modifier(Modifier::BOLD),
|
|
||||||
)
|
|
||||||
.border_style(Style::default().fg(theme.surface1())),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
let mut state = ListState::default();
|
let mut state = ListState::default();
|
||||||
state.select(Some(app.selected));
|
state.select(Some(app.visible_position()));
|
||||||
f.render_stateful_widget(list, chunks[1], &mut state);
|
f.render_stateful_widget(list, area, &mut state);
|
||||||
|
}
|
||||||
|
|
||||||
// Render the focused input area.
|
/// `output ← template`, so the user always knows what `:w` will touch.
|
||||||
let current_var = app.vars.get(app.selected);
|
fn file_header<'a>(app: &'a App, theme: &ThemeConfig) -> Line<'a> {
|
||||||
let input_title = if let Some(var) = current_var {
|
let mut spans = vec![
|
||||||
if var.default_value.is_empty() {
|
Span::raw(" "),
|
||||||
format!(" Editing: {} ", var.key)
|
Span::styled(
|
||||||
} else {
|
display_path(&app.output_path),
|
||||||
format!(" Editing: {} (Default: {}) ", var.key, var.default_value)
|
Style::default()
|
||||||
|
.fg(theme.fg_accent())
|
||||||
|
.add_modifier(Modifier::BOLD),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
|
if let Some(template) = &app.template_path {
|
||||||
|
spans.push(Span::styled(" ← ", Style::default().fg(theme.fg_dimmed())));
|
||||||
|
spans.push(Span::styled(
|
||||||
|
display_path(template),
|
||||||
|
Style::default().fg(theme.fg_dimmed()),
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
spans.push(Span::raw(" "));
|
||||||
|
Line::from(spans)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Right-aligned summary of what still needs attention.
|
||||||
|
fn counts_header<'a>(app: &App, theme: &ThemeConfig) -> Line<'a> {
|
||||||
|
let mut spans = vec![Span::raw(" ")];
|
||||||
|
let missing = app.missing_count();
|
||||||
|
let changed = app.changed_count();
|
||||||
|
|
||||||
|
if missing > 0 {
|
||||||
|
spans.push(Span::styled(
|
||||||
|
format!("{} missing ", missing),
|
||||||
|
Style::default()
|
||||||
|
.fg(theme.fg_warning())
|
||||||
|
.add_modifier(Modifier::BOLD),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if changed > 0 {
|
||||||
|
spans.push(Span::styled(
|
||||||
|
format!("{} changed ", changed),
|
||||||
|
Style::default().fg(theme.fg_modified()),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if missing == 0 && changed == 0 {
|
||||||
|
spans.push(Span::styled(
|
||||||
|
"in sync ",
|
||||||
|
Style::default().fg(theme.fg_dimmed()),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Line::from(spans).alignment(Alignment::Right)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shortens a path to its file name when it sits in the working directory.
|
||||||
|
fn display_path(path: &std::path::Path) -> String {
|
||||||
|
let cwd = std::env::current_dir().unwrap_or_default();
|
||||||
|
path.strip_prefix(&cwd)
|
||||||
|
.unwrap_or(path)
|
||||||
|
.display()
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The pane under the tree: a read-only summary in Normal mode, the editor otherwise.
|
||||||
|
fn draw_detail(f: &mut Frame, area: Rect, app: &App, theme: &ThemeConfig) {
|
||||||
|
let editing = matches!(app.mode, Mode::Insert | Mode::InsertKey);
|
||||||
|
let current = app.vars.get(app.selected);
|
||||||
|
|
||||||
|
let title = match (current, app.mode) {
|
||||||
|
(Some(var), Mode::InsertKey) => format!(" Rename: {} ", var.path_string()),
|
||||||
|
(Some(var), Mode::Insert) => format!(" Editing: {} ", var.path_string()),
|
||||||
|
(Some(var), _) => format!(" {} ", var.path_string()),
|
||||||
|
(None, _) => " Empty ".to_string(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let body: Line = if editing {
|
||||||
|
Line::from(app.input.value().to_string())
|
||||||
|
} else if let Some(var) = current {
|
||||||
|
// Read-only facts about the selection, so the box never looks like a
|
||||||
|
// second place to type when it is not one.
|
||||||
|
let mut spans = vec![Span::styled(
|
||||||
|
match var.value_type {
|
||||||
|
ValueType::String => "text",
|
||||||
|
ValueType::Number => "number",
|
||||||
|
ValueType::Bool => "bool",
|
||||||
|
ValueType::Null => if var.is_group { "group" } else { "empty" },
|
||||||
|
},
|
||||||
|
Style::default().fg(theme.fg_accent()),
|
||||||
|
)];
|
||||||
|
|
||||||
|
let status = match var.status {
|
||||||
|
ItemStatus::MissingFromActive => Some(("not in output yet", theme.fg_warning())),
|
||||||
|
ItemStatus::Overridden => Some(("differs from template", theme.fg_dimmed())),
|
||||||
|
ItemStatus::Present => None,
|
||||||
|
};
|
||||||
|
if let Some((label, color)) = status {
|
||||||
|
spans.push(Span::raw(" · "));
|
||||||
|
spans.push(Span::styled(label, Style::default().fg(color)));
|
||||||
|
}
|
||||||
|
if var.dirty {
|
||||||
|
spans.push(Span::raw(" · "));
|
||||||
|
spans.push(Span::styled(
|
||||||
|
"edited",
|
||||||
|
Style::default().fg(theme.fg_modified()),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if let Some(default) = &var.template_value {
|
||||||
|
spans.push(Span::raw(" · "));
|
||||||
|
spans.push(Span::styled(
|
||||||
|
format!("template: {}", default),
|
||||||
|
Style::default().fg(theme.fg_dimmed()),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Line::from(spans)
|
||||||
} else {
|
} else {
|
||||||
" Input ".to_string()
|
Line::from(Span::styled(
|
||||||
|
"no entries — press o to add one",
|
||||||
|
Style::default().fg(theme.fg_dimmed()),
|
||||||
|
))
|
||||||
};
|
};
|
||||||
|
|
||||||
let input_border_color = match app.mode {
|
let border_color = if editing {
|
||||||
Mode::Insert => theme.green(),
|
theme.border_active()
|
||||||
Mode::Normal | Mode::Search => theme.surface1(),
|
} else {
|
||||||
|
theme.border_normal()
|
||||||
};
|
};
|
||||||
|
|
||||||
let input_text = app.input.value();
|
let pane = Paragraph::new(body)
|
||||||
let cursor_pos = app.input.visual_cursor();
|
.style(Style::default().fg(theme.fg_normal()))
|
||||||
|
|
||||||
let input = Paragraph::new(input_text)
|
|
||||||
.style(Style::default().fg(theme.text()))
|
|
||||||
.block(
|
.block(
|
||||||
Block::default()
|
Block::default()
|
||||||
.borders(Borders::ALL)
|
.borders(Borders::ALL)
|
||||||
.border_type(BorderType::Rounded)
|
.border_type(BorderType::Rounded)
|
||||||
.title(input_title)
|
.title(title)
|
||||||
.title_style(
|
.title_style(
|
||||||
Style::default()
|
Style::default()
|
||||||
.fg(theme.peach())
|
.fg(theme.fg_accent())
|
||||||
.add_modifier(Modifier::BOLD),
|
.add_modifier(Modifier::BOLD),
|
||||||
)
|
)
|
||||||
.border_style(Style::default().fg(input_border_color)),
|
.border_style(Style::default().fg(border_color)),
|
||||||
);
|
);
|
||||||
f.render_widget(input, chunks[2]);
|
f.render_widget(pane, area);
|
||||||
|
|
||||||
// Position the terminal cursor correctly when in Insert mode.
|
if editing {
|
||||||
if let Mode::Insert = app.mode {
|
|
||||||
f.set_cursor_position(ratatui::layout::Position::new(
|
f.set_cursor_position(ratatui::layout::Position::new(
|
||||||
chunks[2].x + 1 + cursor_pos as u16,
|
area.x + 1 + app.input.visual_cursor() as u16,
|
||||||
chunks[2].y + 1,
|
area.y + 1,
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Render the modern pill-style status bar.
|
/// Mode indicator plus either the active prompt, a transient message, or hints.
|
||||||
let (mode_str, mode_style) = match app.mode {
|
fn draw_status(f: &mut Frame, area: Rect, app: &App, config: &Config) {
|
||||||
Mode::Normal => (
|
let theme = &config.theme;
|
||||||
" NORMAL ",
|
let (mode_str, mode_bg) = match app.mode {
|
||||||
Style::default()
|
Mode::Normal => (" NORMAL ", theme.bg_highlight()),
|
||||||
.bg(theme.blue())
|
Mode::Insert => (" INSERT ", theme.bg_active()),
|
||||||
.fg(theme.crust())
|
Mode::InsertKey => (" RENAME ", theme.bg_active()),
|
||||||
.add_modifier(Modifier::BOLD),
|
Mode::Search => (" SEARCH ", theme.bg_search()),
|
||||||
),
|
Mode::Help => (" HELP ", theme.bg_search()),
|
||||||
Mode::Insert => (
|
|
||||||
" INSERT ",
|
|
||||||
Style::default()
|
|
||||||
.bg(theme.green())
|
|
||||||
.fg(theme.crust())
|
|
||||||
.add_modifier(Modifier::BOLD),
|
|
||||||
),
|
|
||||||
Mode::Search => (
|
|
||||||
" SEARCH ",
|
|
||||||
Style::default()
|
|
||||||
.bg(theme.mauve())
|
|
||||||
.fg(theme.crust())
|
|
||||||
.add_modifier(Modifier::BOLD),
|
|
||||||
),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let status_msg = app
|
let message = app
|
||||||
.status_message
|
.prompt
|
||||||
.as_deref()
|
.clone()
|
||||||
.unwrap_or_else(|| match app.mode {
|
.or_else(|| app.status_text().map(str::to_string))
|
||||||
Mode::Normal => " navigation | i: edit | /: search | :w: save | :q: quit ",
|
.unwrap_or_else(|| hints(app, config));
|
||||||
Mode::Insert => " Esc: back to normal | Enter: commit ",
|
|
||||||
Mode::Search => " Esc: back to normal | type to filter ",
|
|
||||||
});
|
|
||||||
|
|
||||||
let status_line = Line::from(vec![
|
let status_line = Line::from(vec![
|
||||||
Span::styled(mode_str, mode_style),
|
|
||||||
Span::styled(
|
Span::styled(
|
||||||
format!(" {} ", status_msg),
|
mode_str,
|
||||||
Style::default().bg(theme.surface0()).fg(theme.text()),
|
Style::default()
|
||||||
|
.bg(mode_bg)
|
||||||
|
.fg(theme.bg_normal())
|
||||||
|
.add_modifier(Modifier::BOLD),
|
||||||
|
),
|
||||||
|
Span::styled(
|
||||||
|
format!(" {} ", message),
|
||||||
|
Style::default()
|
||||||
|
.bg(theme.border_normal())
|
||||||
|
.fg(theme.fg_normal()),
|
||||||
),
|
),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
let status = Paragraph::new(status_line).style(Style::default().bg(theme.surface0()));
|
f.render_widget(
|
||||||
f.render_widget(status, chunks[4]);
|
Paragraph::new(status_line).style(Style::default().bg(theme.border_normal())),
|
||||||
|
area,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A handful of hints that fit on one line; the rest lives behind the help key.
|
||||||
|
fn hints(app: &App, config: &Config) -> String {
|
||||||
|
let kb = &config.keybinds;
|
||||||
|
let help = format!("{} help", kb.key_for(Action::Help));
|
||||||
|
|
||||||
|
match app.mode {
|
||||||
|
Mode::Insert => "Esc cancel · Enter commit".to_string(),
|
||||||
|
Mode::InsertKey => "Esc cancel · Enter rename".to_string(),
|
||||||
|
Mode::Search => match app.match_progress() {
|
||||||
|
Some((_, 0)) => "no matches · Esc cancel".to_string(),
|
||||||
|
Some((cur, total)) => format!("match {}/{} · Enter keep · Esc cancel", cur, total),
|
||||||
|
None => "type to search keys and values · Esc cancel".to_string(),
|
||||||
|
},
|
||||||
|
Mode::Help => format!(
|
||||||
|
"{}/{} scroll · any other key closes",
|
||||||
|
kb.key_for(Action::Down),
|
||||||
|
kb.key_for(Action::Up)
|
||||||
|
),
|
||||||
|
Mode::Normal => {
|
||||||
|
let mut parts = vec![format!("{}/{} move", kb.key_for(Action::Down), kb.key_for(Action::Up))];
|
||||||
|
|
||||||
|
if app.selected_is_missing() {
|
||||||
|
parts.push(format!("{} take default", kb.key_for(Action::AddMissing)));
|
||||||
|
} else if app.selected_is_group() {
|
||||||
|
parts.push(format!("{} fold", kb.key_for(Action::ToggleFold)));
|
||||||
|
parts.push(format!("{} rename", kb.key_for(Action::Rename)));
|
||||||
|
} else {
|
||||||
|
parts.push(format!("{} edit", kb.key_for(Action::Edit)));
|
||||||
|
parts.push(format!("{} rename", kb.key_for(Action::Rename)));
|
||||||
|
}
|
||||||
|
|
||||||
|
parts.push(format!("{} search", kb.key_for(Action::Search)));
|
||||||
|
parts.push(format!("{} save", kb.save));
|
||||||
|
parts.push(help);
|
||||||
|
parts.join(" · ")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One line of the help overlay.
|
||||||
|
enum HelpRow {
|
||||||
|
Section(&'static str),
|
||||||
|
Bind(String, &'static str),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds the full reference: every configured binding, then the `:` commands.
|
||||||
|
fn help_rows(config: &Config) -> Vec<HelpRow> {
|
||||||
|
let kb = &config.keybinds;
|
||||||
|
let mut rows = Vec::new();
|
||||||
|
let mut section = "";
|
||||||
|
|
||||||
|
for (spec, action) in kb.table() {
|
||||||
|
if action.section() != section {
|
||||||
|
section = action.section();
|
||||||
|
rows.push(HelpRow::Section(section));
|
||||||
|
}
|
||||||
|
rows.push(HelpRow::Bind(spec.to_string(), action.label()));
|
||||||
|
}
|
||||||
|
|
||||||
|
rows.push(HelpRow::Section("Commands"));
|
||||||
|
rows.push(HelpRow::Bind(kb.save.clone(), "write the output file"));
|
||||||
|
rows.push(HelpRow::Bind(format!("{} <path>", kb.save), "write somewhere else"));
|
||||||
|
rows.push(HelpRow::Bind(kb.quit.clone(), "quit (refused if unsaved)"));
|
||||||
|
rows.push(HelpRow::Bind(":q!".to_string(), "quit, discarding changes"));
|
||||||
|
rows.push(HelpRow::Bind(":wq".to_string(), "write and quit"));
|
||||||
|
rows
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renders one help row into styled spans of a fixed width.
|
||||||
|
fn help_spans<'a>(row: Option<&'a HelpRow>, theme: &ThemeConfig, width: usize) -> Vec<Span<'a>> {
|
||||||
|
let key_width = 11;
|
||||||
|
match row {
|
||||||
|
Some(HelpRow::Section(name)) => vec![Span::styled(
|
||||||
|
format!("{:<width$}", name, width = width),
|
||||||
|
Style::default()
|
||||||
|
.fg(theme.fg_accent())
|
||||||
|
.add_modifier(Modifier::BOLD),
|
||||||
|
)],
|
||||||
|
Some(HelpRow::Bind(spec, label)) => {
|
||||||
|
let label_width = width.saturating_sub(key_width + 2);
|
||||||
|
vec![
|
||||||
|
Span::styled(
|
||||||
|
format!(" {:<width$}", spec, width = key_width),
|
||||||
|
Style::default().fg(theme.bg_search()),
|
||||||
|
),
|
||||||
|
Span::styled(
|
||||||
|
format!("{:<width$}", truncate(label, label_width), width = label_width),
|
||||||
|
Style::default().fg(theme.fg_normal()),
|
||||||
|
),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
None => vec![Span::raw(" ".repeat(width))],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Clips a label to the space available, with an ellipsis when it does not fit.
|
||||||
|
fn truncate(text: &str, width: usize) -> String {
|
||||||
|
if text.chars().count() <= width {
|
||||||
|
return text.to_string();
|
||||||
|
}
|
||||||
|
text.chars().take(width.saturating_sub(1)).collect::<String>() + "…"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Full keybinding reference, laid out in two columns so it fits a short terminal.
|
||||||
|
fn draw_help(f: &mut Frame, area: Rect, config: &Config, scroll_offset: usize) {
|
||||||
|
let theme = &config.theme;
|
||||||
|
let rows = help_rows(config);
|
||||||
|
|
||||||
|
// Break into two columns at the section boundary nearest the midpoint, so a
|
||||||
|
// group of related keys is never split across the gutter.
|
||||||
|
let midpoint = rows.len().div_ceil(2);
|
||||||
|
let split = (0..rows.len())
|
||||||
|
.filter(|&i| matches!(rows[i], HelpRow::Section(_)))
|
||||||
|
.min_by_key(|&i| i.abs_diff(midpoint))
|
||||||
|
.unwrap_or(midpoint);
|
||||||
|
|
||||||
|
let (left, right) = rows.split_at(split);
|
||||||
|
let column_width = 36usize;
|
||||||
|
let gutter = 2usize;
|
||||||
|
|
||||||
|
let lines: Vec<Line> = (0..left.len().max(right.len()))
|
||||||
|
.map(|i| {
|
||||||
|
let mut spans = help_spans(left.get(i), theme, column_width);
|
||||||
|
spans.push(Span::raw(" ".repeat(gutter)));
|
||||||
|
spans.extend(help_spans(right.get(i), theme, column_width));
|
||||||
|
Line::from(spans)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let popup = centered_rect(
|
||||||
|
(column_width * 2 + gutter + 2) as u16,
|
||||||
|
area,
|
||||||
|
lines.len() as u16 + 2,
|
||||||
|
);
|
||||||
|
// On a terminal too short for the whole reference, scroll rather than clip
|
||||||
|
// silently: a key the user cannot see is a key they do not have.
|
||||||
|
let rows_shown = popup.height.saturating_sub(2) as usize;
|
||||||
|
let max_scroll = lines.len().saturating_sub(rows_shown);
|
||||||
|
let scroll = scroll_offset.min(max_scroll);
|
||||||
|
let title = if max_scroll > 0 {
|
||||||
|
format!(" Keys — {}/{} ", (scroll + rows_shown).min(lines.len()), lines.len())
|
||||||
|
} else {
|
||||||
|
" Keys ".to_string()
|
||||||
|
};
|
||||||
|
f.render_widget(Clear, popup);
|
||||||
|
f.render_widget(
|
||||||
|
Paragraph::new(lines)
|
||||||
|
.scroll((scroll as u16, 0))
|
||||||
|
.style(Style::default().bg(theme.bg_normal()).fg(theme.fg_normal()))
|
||||||
|
.block(
|
||||||
|
Block::default()
|
||||||
|
.borders(Borders::ALL)
|
||||||
|
.border_type(BorderType::Rounded)
|
||||||
|
.title(title)
|
||||||
|
.title_style(
|
||||||
|
Style::default()
|
||||||
|
.fg(theme.fg_accent())
|
||||||
|
.add_modifier(Modifier::BOLD),
|
||||||
|
)
|
||||||
|
.border_style(Style::default().fg(theme.border_active())),
|
||||||
|
),
|
||||||
|
popup,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Centers a popup of the given size inside `area`, clamped to what fits.
|
||||||
|
fn centered_rect(width: u16, area: Rect, height: u16) -> Rect {
|
||||||
|
let w = width.min(area.width.saturating_sub(2)).max(1);
|
||||||
|
let h = height.min(area.height.saturating_sub(2)).max(1);
|
||||||
|
Rect {
|
||||||
|
x: area.x + (area.width.saturating_sub(w)) / 2,
|
||||||
|
y: area.y + (area.height.saturating_sub(h)) / 2,
|
||||||
|
width: w,
|
||||||
|
height: h,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::format::{ConfigItem, PathSegment};
|
||||||
|
use ratatui::Terminal;
|
||||||
|
use ratatui::backend::TestBackend;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
/// Renders one frame and returns it as plain text lines.
|
||||||
|
fn render(app: &mut App, config: &Config) -> Vec<String> {
|
||||||
|
let mut terminal = Terminal::new(TestBackend::new(80, 20)).unwrap();
|
||||||
|
terminal.draw(|f| draw(f, app, config)).unwrap();
|
||||||
|
let buffer = terminal.backend().buffer().clone();
|
||||||
|
(0..buffer.area.height)
|
||||||
|
.map(|y| {
|
||||||
|
(0..buffer.area.width)
|
||||||
|
.map(|x| buffer[(x, y)].symbol())
|
||||||
|
.collect::<String>()
|
||||||
|
.trim_end()
|
||||||
|
.to_string()
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sample_app() -> App {
|
||||||
|
let mut token = ConfigItem::leaf(
|
||||||
|
"API_KEY",
|
||||||
|
vec![PathSegment::Key("API_KEY".to_string())],
|
||||||
|
"",
|
||||||
|
0,
|
||||||
|
ValueType::String,
|
||||||
|
);
|
||||||
|
token.status = ItemStatus::MissingFromActive;
|
||||||
|
token.value = None;
|
||||||
|
token.template_value = Some("changeme".to_string());
|
||||||
|
|
||||||
|
App::new(
|
||||||
|
vec![
|
||||||
|
ConfigItem::leaf(
|
||||||
|
"DB_HOST",
|
||||||
|
vec![PathSegment::Key("DB_HOST".to_string())],
|
||||||
|
"prod.internal",
|
||||||
|
0,
|
||||||
|
ValueType::String,
|
||||||
|
),
|
||||||
|
token,
|
||||||
|
],
|
||||||
|
PathBuf::from(".env"),
|
||||||
|
Some(PathBuf::from(".env.example")),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn header_names_the_files_and_counts_the_work() {
|
||||||
|
let config = Config::default();
|
||||||
|
let mut app = sample_app();
|
||||||
|
let frame = render(&mut app, &config).join("\n");
|
||||||
|
|
||||||
|
assert!(frame.contains(".env"), "{frame}");
|
||||||
|
assert!(frame.contains(".env.example"), "{frame}");
|
||||||
|
assert!(frame.contains("1 missing"), "{frame}");
|
||||||
|
assert!(frame.contains("(missing)"), "{frame}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn status_bar_offers_the_help_key_and_fits_the_terminal() {
|
||||||
|
let config = Config::default();
|
||||||
|
let mut app = sample_app();
|
||||||
|
app.selected = 1; // the entry that is missing from the output
|
||||||
|
let frame = render(&mut app, &config);
|
||||||
|
let status = frame.last().unwrap();
|
||||||
|
|
||||||
|
assert!(status.contains("NORMAL"), "{status}");
|
||||||
|
assert!(status.contains("? help"), "{status}");
|
||||||
|
// The hint line must survive an 80-column terminal without truncation.
|
||||||
|
assert!(status.chars().count() <= 80, "{status}");
|
||||||
|
// On a missing entry the offer to take the default is what matters.
|
||||||
|
assert!(status.contains("take default"), "{status}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn help_overlay_lists_bindings() {
|
||||||
|
let config = Config::default();
|
||||||
|
let mut app = sample_app();
|
||||||
|
app.toggle_help();
|
||||||
|
let frame = render(&mut app, &config).join("\n");
|
||||||
|
|
||||||
|
assert!(frame.contains("Navigate"), "{frame}");
|
||||||
|
assert!(frame.contains("Template"), "{frame}");
|
||||||
|
assert!(frame.contains("take template default"), "{frame}");
|
||||||
|
assert!(frame.contains("History"), "{frame}");
|
||||||
|
assert!(frame.contains("Session"), "{frame}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn help_overlay_scrolls_when_the_terminal_is_short() {
|
||||||
|
let config = Config::default();
|
||||||
|
let mut app = sample_app();
|
||||||
|
app.toggle_help();
|
||||||
|
|
||||||
|
// Too short to show everything at once: say so, and let the rest be reached.
|
||||||
|
let frame = render(&mut app, &config).join("\n");
|
||||||
|
assert!(frame.contains("Keys — "), "{frame}");
|
||||||
|
assert!(!frame.contains(":q!"), "{frame}");
|
||||||
|
|
||||||
|
for _ in 0..10 {
|
||||||
|
app.scroll_help(true);
|
||||||
|
}
|
||||||
|
let frame = render(&mut app, &config).join("\n");
|
||||||
|
assert!(frame.contains(":q!"), "{frame}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn transient_status_replaces_hints_then_gives_them_back() {
|
||||||
|
let config = Config::default();
|
||||||
|
let mut app = sample_app();
|
||||||
|
app.set_status("Saved to .env");
|
||||||
|
|
||||||
|
let frame = render(&mut app, &config);
|
||||||
|
assert!(frame.last().unwrap().contains("Saved to .env"));
|
||||||
|
|
||||||
|
app.clear_status();
|
||||||
|
let frame = render(&mut app, &config);
|
||||||
|
assert!(frame.last().unwrap().contains("? help"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
+302
@@ -0,0 +1,302 @@
|
|||||||
|
use crate::format::ConfigItem;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
/// Represents a single snapshot of the application state for undo/redo purposes.
|
||||||
|
pub struct EditAction {
|
||||||
|
/// The complete list of configuration items at the time of the action.
|
||||||
|
pub state: Vec<ConfigItem>,
|
||||||
|
/// The index of the item that was selected during this action.
|
||||||
|
pub selected: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A node in the undo tree, representing a point in the application's history.
|
||||||
|
pub struct UndoNode {
|
||||||
|
/// The state data captured at this history point.
|
||||||
|
pub action: EditAction,
|
||||||
|
/// ID of the parent node (previous state). Root node has None.
|
||||||
|
pub parent: Option<usize>,
|
||||||
|
/// IDs of all states that branched off from this one.
|
||||||
|
pub children: Vec<usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A non-linear undo/redo system that tracks history as a branching tree.
|
||||||
|
///
|
||||||
|
/// Unlike a simple stack, an UndoTree allows users to undo several steps,
|
||||||
|
/// make a new change (creating a branch), and still navigate through
|
||||||
|
/// the most recent history path.
|
||||||
|
pub struct UndoTree {
|
||||||
|
/// Map of node IDs to their respective history nodes.
|
||||||
|
nodes: HashMap<usize, UndoNode>,
|
||||||
|
/// The ID of the node representing the current application state.
|
||||||
|
current_node: usize,
|
||||||
|
/// Counter for assigning unique IDs to new nodes.
|
||||||
|
next_id: usize,
|
||||||
|
/// Tracks the most recently active branch for each node.
|
||||||
|
/// This allows the 'redo' operation to follow the path the user
|
||||||
|
/// actually took when multiple branches exist.
|
||||||
|
latest_branch: HashMap<usize, usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UndoTree {
|
||||||
|
/// Creates a new undo tree initialized with the starting application state.
|
||||||
|
pub fn new(initial_state: Vec<ConfigItem>, initial_selected: usize) -> Self {
|
||||||
|
let root_id = 0;
|
||||||
|
let root_node = UndoNode {
|
||||||
|
action: EditAction {
|
||||||
|
state: initial_state,
|
||||||
|
selected: initial_selected,
|
||||||
|
},
|
||||||
|
parent: None,
|
||||||
|
children: Vec::new(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut nodes = HashMap::new();
|
||||||
|
nodes.insert(root_id, root_node);
|
||||||
|
|
||||||
|
Self {
|
||||||
|
nodes,
|
||||||
|
current_node: root_id,
|
||||||
|
next_id: 1,
|
||||||
|
latest_branch: HashMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pushes a new state onto the tree, branching off from the current node.
|
||||||
|
///
|
||||||
|
/// This creates a new child node for the current position and updates
|
||||||
|
/// the branch tracking to ensure this new path is preferred during redo.
|
||||||
|
pub fn push(&mut self, state: Vec<ConfigItem>, selected: usize) {
|
||||||
|
let new_id = self.next_id;
|
||||||
|
self.next_id += 1;
|
||||||
|
|
||||||
|
let new_node = UndoNode {
|
||||||
|
action: EditAction { state, selected },
|
||||||
|
parent: Some(self.current_node),
|
||||||
|
children: Vec::new(),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add to nodes
|
||||||
|
self.nodes.insert(new_id, new_node);
|
||||||
|
|
||||||
|
// Update parent's children
|
||||||
|
if let Some(parent_node) = self.nodes.get_mut(&self.current_node) {
|
||||||
|
parent_node.children.push(new_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Record this as the latest branch for the parent
|
||||||
|
self.latest_branch.insert(self.current_node, new_id);
|
||||||
|
|
||||||
|
// Move current pointer
|
||||||
|
self.current_node = new_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves the current pointer back to the parent node and returns the previous state.
|
||||||
|
/// Returns None if the current node is the root (no more history to undo).
|
||||||
|
pub fn undo(&mut self) -> Option<&EditAction> {
|
||||||
|
if let Some(current) = self.nodes.get(&self.current_node)
|
||||||
|
&& let Some(parent_id) = current.parent {
|
||||||
|
self.current_node = parent_id;
|
||||||
|
return self.nodes.get(&parent_id).map(|n| &n.action);
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves the current pointer forward to the latest child branch and returns the state.
|
||||||
|
///
|
||||||
|
/// Redo follows the `latest_branch` map to decide which path to take
|
||||||
|
/// if multiple branches exist. If no branch is recorded, it defaults to the
|
||||||
|
/// most recently created child.
|
||||||
|
pub fn redo(&mut self) -> Option<&EditAction> {
|
||||||
|
if let Some(next_id) = self.latest_branch.get(&self.current_node).copied() {
|
||||||
|
self.current_node = next_id;
|
||||||
|
return self.nodes.get(&next_id).map(|n| &n.action);
|
||||||
|
} else {
|
||||||
|
// Fallback: if there is no recorded latest branch but there are children
|
||||||
|
let current_id = self.current_node;
|
||||||
|
if let Some(current) = self.nodes.get(¤t_id)
|
||||||
|
&& let Some(&first_child_id) = current.children.last() {
|
||||||
|
self.current_node = first_child_id;
|
||||||
|
self.latest_branch.insert(current_id, first_child_id);
|
||||||
|
return self.nodes.get(&first_child_id).map(|n| &n.action);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Discards the current node, moving back to its parent.
|
||||||
|
///
|
||||||
|
/// Used when an action is rolled back before the user ever saw it as a
|
||||||
|
/// distinct step, such as a newly added item abandoned at the rename prompt.
|
||||||
|
pub fn pop(&mut self) {
|
||||||
|
let Some(current) = self.nodes.get(&self.current_node) else { return };
|
||||||
|
let Some(parent_id) = current.parent else { return };
|
||||||
|
|
||||||
|
let removed = self.current_node;
|
||||||
|
self.nodes.remove(&removed);
|
||||||
|
if let Some(parent) = self.nodes.get_mut(&parent_id) {
|
||||||
|
parent.children.retain(|&c| c != removed);
|
||||||
|
}
|
||||||
|
if self.latest_branch.get(&parent_id) == Some(&removed) {
|
||||||
|
match self.nodes.get(&parent_id).and_then(|p| p.children.last()) {
|
||||||
|
Some(&fallback) => {
|
||||||
|
self.latest_branch.insert(parent_id, fallback);
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
self.latest_branch.remove(&parent_id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.latest_branch.remove(&removed);
|
||||||
|
self.current_node = parent_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Which forward branch redo would take, as `(index, total)`, both 1-based.
|
||||||
|
///
|
||||||
|
/// `None` when the current node has no children at all.
|
||||||
|
pub fn branch_position(&self) -> Option<(usize, usize)> {
|
||||||
|
let current = self.nodes.get(&self.current_node)?;
|
||||||
|
if current.children.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let preferred = self
|
||||||
|
.latest_branch
|
||||||
|
.get(&self.current_node)
|
||||||
|
.copied()
|
||||||
|
.or_else(|| current.children.last().copied())?;
|
||||||
|
let index = current
|
||||||
|
.children
|
||||||
|
.iter()
|
||||||
|
.position(|&c| c == preferred)
|
||||||
|
.unwrap_or(0);
|
||||||
|
Some((index + 1, current.children.len()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Picks a different forward branch at the current point.
|
||||||
|
///
|
||||||
|
/// Returns the new `(index, total)` position, or `None` when there is no
|
||||||
|
/// alternative history to choose from.
|
||||||
|
pub fn cycle_branch(&mut self, forward: bool) -> Option<(usize, usize)> {
|
||||||
|
let (index, total) = self.branch_position()?;
|
||||||
|
if total < 2 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let next = if forward {
|
||||||
|
index % total
|
||||||
|
} else {
|
||||||
|
(index + total - 2) % total
|
||||||
|
};
|
||||||
|
let child = self.nodes.get(&self.current_node)?.children[next];
|
||||||
|
self.latest_branch.insert(self.current_node, child);
|
||||||
|
Some((next + 1, total))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::format::ValueType;
|
||||||
|
|
||||||
|
fn dummy_item(key: &str) -> ConfigItem {
|
||||||
|
ConfigItem::leaf(key, vec![], key, 0, ValueType::String)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_undo_redo_tree() {
|
||||||
|
let state1 = vec![dummy_item("A")];
|
||||||
|
let mut tree = UndoTree::new(state1.clone(), 0);
|
||||||
|
|
||||||
|
// Push state 2
|
||||||
|
let state2 = vec![dummy_item("B")];
|
||||||
|
tree.push(state2.clone(), 1);
|
||||||
|
|
||||||
|
// Push state 3
|
||||||
|
let state3 = vec![dummy_item("C")];
|
||||||
|
tree.push(state3.clone(), 2);
|
||||||
|
|
||||||
|
// Undo -> State 2
|
||||||
|
let action = tree.undo().unwrap();
|
||||||
|
assert_eq!(action.state[0].key, "B");
|
||||||
|
assert_eq!(action.selected, 1);
|
||||||
|
|
||||||
|
// Undo -> State 1
|
||||||
|
let action = tree.undo().unwrap();
|
||||||
|
assert_eq!(action.state[0].key, "A");
|
||||||
|
assert_eq!(action.selected, 0);
|
||||||
|
|
||||||
|
// Undo again -> None (already at root)
|
||||||
|
assert!(tree.undo().is_none());
|
||||||
|
|
||||||
|
// Redo -> State 2
|
||||||
|
let action = tree.redo().unwrap();
|
||||||
|
assert_eq!(action.state[0].key, "B");
|
||||||
|
assert_eq!(action.selected, 1);
|
||||||
|
|
||||||
|
// Redo -> State 3
|
||||||
|
let action = tree.redo().unwrap();
|
||||||
|
assert_eq!(action.state[0].key, "C");
|
||||||
|
assert_eq!(action.selected, 2);
|
||||||
|
|
||||||
|
// Branching: Undo twice to State 1
|
||||||
|
tree.undo();
|
||||||
|
tree.undo();
|
||||||
|
|
||||||
|
// Push State 4 (from State 1)
|
||||||
|
let state4 = vec![dummy_item("D")];
|
||||||
|
tree.push(state4.clone(), 3);
|
||||||
|
|
||||||
|
// Undo -> State 1
|
||||||
|
let action = tree.undo().unwrap();
|
||||||
|
assert_eq!(action.state[0].key, "A");
|
||||||
|
|
||||||
|
// Redo -> State 4 (follows latest branch D, not old branch B)
|
||||||
|
let action = tree.redo().unwrap();
|
||||||
|
assert_eq!(action.state[0].key, "D");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_redo_fallback_fix() {
|
||||||
|
let state1 = vec![dummy_item("A")];
|
||||||
|
let mut tree = UndoTree::new(state1.clone(), 0);
|
||||||
|
|
||||||
|
let state2 = vec![dummy_item("B")];
|
||||||
|
tree.push(state2.clone(), 1);
|
||||||
|
|
||||||
|
tree.undo();
|
||||||
|
// Redo should move to state 2
|
||||||
|
let action = tree.redo().unwrap();
|
||||||
|
assert_eq!(action.state[0].key, "B");
|
||||||
|
|
||||||
|
// Calling redo again should NOT change the current node or returned action
|
||||||
|
// (since it's already at the latest child)
|
||||||
|
assert!(tree.redo().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_pop_discards_current_state() {
|
||||||
|
let mut tree = UndoTree::new(vec![dummy_item("A")], 0);
|
||||||
|
tree.push(vec![dummy_item("B")], 1);
|
||||||
|
|
||||||
|
tree.pop();
|
||||||
|
|
||||||
|
// Back at A, with nothing left to redo into.
|
||||||
|
assert!(tree.redo().is_none());
|
||||||
|
assert!(tree.undo().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_branch_cycling() {
|
||||||
|
let mut tree = UndoTree::new(vec![dummy_item("A")], 0);
|
||||||
|
tree.push(vec![dummy_item("B")], 0);
|
||||||
|
tree.undo();
|
||||||
|
tree.push(vec![dummy_item("C")], 0);
|
||||||
|
tree.undo();
|
||||||
|
|
||||||
|
// Two futures hang off the root; redo prefers the newest.
|
||||||
|
assert_eq!(tree.branch_position(), Some((2, 2)));
|
||||||
|
assert_eq!(tree.redo().unwrap().state[0].key, "C");
|
||||||
|
|
||||||
|
tree.undo();
|
||||||
|
tree.cycle_branch(true);
|
||||||
|
assert_eq!(tree.redo().unwrap().state[0].key, "B");
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user