Compare commits
57 Commits
6eddd02fb4
...
release/0.
| Author | SHA1 | Date | |
|---|---|---|---|
| b07a2d8f75 | |||
| 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 | |||
| 14f1be5a2a | |||
| 49eac25d48 | |||
| 0ce858da5c | |||
| 3459c67377 | |||
| 84945b9d83 | |||
| 0c217c5129 | |||
| 7b2217886c | |||
| 68cd6543b3 | |||
| 6c8fc7268b | |||
| 93c5c30021 | |||
| 53902af934 | |||
| 7a7ae1ffdb | |||
| f413d5e2eb | |||
| e72fdd9fcb | |||
| 7aa12f1a31 | |||
| d52422d839 | |||
| a274938368 | |||
| 253c69363d | |||
| ac7b67748d | |||
| 8cee54007f | |||
| 361df64b04 | |||
| 0baf53b1eb |
@@ -19,6 +19,7 @@ jobs:
|
|||||||
uses: actions-rust-lang/setup-rust-toolchain@v1
|
uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||||
with:
|
with:
|
||||||
toolchain: stable
|
toolchain: stable
|
||||||
|
cache: false
|
||||||
|
|
||||||
- name: Get Version
|
- name: Get Version
|
||||||
id: get_version
|
id: get_version
|
||||||
@@ -31,30 +32,39 @@ jobs:
|
|||||||
echo "TAG=v$VERSION" >> $GITHUB_OUTPUT
|
echo "TAG=v$VERSION" >> $GITHUB_OUTPUT
|
||||||
fi
|
fi
|
||||||
|
|
||||||
- name: Build
|
- name: Check if Release Exists
|
||||||
run: cargo build --release
|
id: check_release
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" \
|
||||||
|
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
|
||||||
|
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/tags/${{ steps.get_version.outputs.TAG }}")
|
||||||
|
|
||||||
- name: Create Release
|
if [ "$HTTP_STATUS" = "200" ]; then
|
||||||
id: create_release
|
echo "EXISTS=true" >> $GITHUB_OUTPUT
|
||||||
uses: https://github.com/actions/create-release@v1
|
echo "Release already exists for tag ${{ steps.get_version.outputs.TAG }}. Skipping creation."
|
||||||
env:
|
else
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
echo "EXISTS=false" >> $GITHUB_OUTPUT
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
if: steps.check_release.outputs.EXISTS == 'false'
|
||||||
|
run: |
|
||||||
|
cargo build --release
|
||||||
|
mv target/release/mould target/release/mould-${{ steps.get_version.outputs.TAG }}-linux-amd64
|
||||||
|
|
||||||
|
- name: Create Release and Upload Asset
|
||||||
|
if: steps.check_release.outputs.EXISTS == 'false'
|
||||||
|
uses: https://github.com/softprops/action-gh-release@v1
|
||||||
with:
|
with:
|
||||||
tag_name: ${{ steps.get_version.outputs.TAG }}
|
tag_name: ${{ steps.get_version.outputs.TAG }}
|
||||||
release_name: Release ${{ steps.get_version.outputs.TAG }}
|
name: Release ${{ steps.get_version.outputs.TAG }}
|
||||||
body: |
|
body: |
|
||||||
Automated release for version ${{ steps.get_version.outputs.VERSION }}
|
Automated release for version ${{ steps.get_version.outputs.VERSION }}
|
||||||
Commit: ${{ github.sha }}
|
Commit: ${{ github.sha }}
|
||||||
Branch: ${{ github.ref_name }}
|
Branch: ${{ github.ref_name }}
|
||||||
|
files: target/release/mould-${{ steps.get_version.outputs.TAG }}-linux-amd64
|
||||||
draft: false
|
draft: false
|
||||||
prerelease: false
|
prerelease: false
|
||||||
|
|
||||||
- name: Upload Release Asset
|
|
||||||
uses: https://github.com/actions/upload-release-asset@v1
|
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
with:
|
|
||||||
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
|
||||||
asset_path: ./target/release/cenv
|
|
||||||
asset_name: cenv-${{ steps.get_version.outputs.TAG }}-linux-amd64
|
|
||||||
asset_content_type: application/octet-stream
|
|
||||||
|
|||||||
35
.gitea/workflows/version-check.yaml
Normal file
35
.gitea/workflows/version-check.yaml
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
name: Version Check
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
paths:
|
||||||
|
- 'Cargo.toml'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
check-version:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Compare versions
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
NEW_VERSION=$(grep -m 1 '^version =' Cargo.toml | cut -d '"' -f 2)
|
||||||
|
|
||||||
|
git fetch origin ${{ github.base_ref }}
|
||||||
|
OLD_VERSION=$(git show origin/${{ github.base_ref }}:Cargo.toml | grep -m 1 '^version =' | cut -d '"' -f 2)
|
||||||
|
|
||||||
|
echo "Old version (main): $OLD_VERSION"
|
||||||
|
echo "New version (PR): $NEW_VERSION"
|
||||||
|
|
||||||
|
if [ "$NEW_VERSION" = "$OLD_VERSION" ]; then
|
||||||
|
echo "Error: Cargo.toml version has not been updated in this PR!"
|
||||||
|
exit 1
|
||||||
|
else
|
||||||
|
echo "Success: Version updated from $OLD_VERSION to $NEW_VERSION"
|
||||||
|
fi
|
||||||
375
Cargo.lock
generated
375
Cargo.lock
generated
@@ -17,6 +17,80 @@ version = "0.2.21"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
|
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anstream"
|
||||||
|
version = "0.6.21"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a"
|
||||||
|
dependencies = [
|
||||||
|
"anstyle",
|
||||||
|
"anstyle-parse 0.2.7",
|
||||||
|
"anstyle-query",
|
||||||
|
"anstyle-wincon",
|
||||||
|
"colorchoice",
|
||||||
|
"is_terminal_polyfill",
|
||||||
|
"utf8parse",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anstream"
|
||||||
|
version = "1.0.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
|
||||||
|
dependencies = [
|
||||||
|
"anstyle",
|
||||||
|
"anstyle-parse 1.0.0",
|
||||||
|
"anstyle-query",
|
||||||
|
"anstyle-wincon",
|
||||||
|
"colorchoice",
|
||||||
|
"is_terminal_polyfill",
|
||||||
|
"utf8parse",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anstyle"
|
||||||
|
version = "1.0.14"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anstyle-parse"
|
||||||
|
version = "0.2.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2"
|
||||||
|
dependencies = [
|
||||||
|
"utf8parse",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anstyle-parse"
|
||||||
|
version = "1.0.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
|
||||||
|
dependencies = [
|
||||||
|
"utf8parse",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anstyle-query"
|
||||||
|
version = "1.1.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
|
||||||
|
dependencies = [
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anstyle-wincon"
|
||||||
|
version = "3.0.11"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
|
||||||
|
dependencies = [
|
||||||
|
"anstyle",
|
||||||
|
"once_cell_polyfill",
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "anyhow"
|
name = "anyhow"
|
||||||
version = "1.0.102"
|
version = "1.0.102"
|
||||||
@@ -101,18 +175,6 @@ dependencies = [
|
|||||||
"rustversion",
|
"rustversion",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "cenv-rs"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"crossterm",
|
|
||||||
"dirs",
|
|
||||||
"ratatui",
|
|
||||||
"serde",
|
|
||||||
"tempfile",
|
|
||||||
"toml",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cfg-if"
|
name = "cfg-if"
|
||||||
version = "1.0.4"
|
version = "1.0.4"
|
||||||
@@ -125,6 +187,52 @@ version = "0.2.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
|
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "clap"
|
||||||
|
version = "4.6.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b193af5b67834b676abd72466a96c1024e6a6ad978a1f484bd90b85c94041351"
|
||||||
|
dependencies = [
|
||||||
|
"clap_builder",
|
||||||
|
"clap_derive",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "clap_builder"
|
||||||
|
version = "4.6.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f"
|
||||||
|
dependencies = [
|
||||||
|
"anstream 1.0.0",
|
||||||
|
"anstyle",
|
||||||
|
"clap_lex",
|
||||||
|
"strsim",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "clap_derive"
|
||||||
|
version = "4.6.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1110bd8a634a1ab8cb04345d8d878267d57c3cf1b38d91b71af6686408bbca6a"
|
||||||
|
dependencies = [
|
||||||
|
"heck",
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 2.0.117",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "clap_lex"
|
||||||
|
version = "1.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "colorchoice"
|
||||||
|
version = "1.0.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "compact_str"
|
name = "compact_str"
|
||||||
version = "0.9.0"
|
version = "0.9.0"
|
||||||
@@ -139,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"
|
||||||
@@ -184,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"
|
||||||
@@ -306,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"
|
||||||
@@ -321,6 +464,38 @@ 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]]
|
||||||
|
name = "env_filter"
|
||||||
|
version = "1.0.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7a1c3cc8e57274ec99de65301228b537f1e4eedc1b8e0f9411c6caac8ae7308f"
|
||||||
|
dependencies = [
|
||||||
|
"log",
|
||||||
|
"regex",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "env_logger"
|
||||||
|
version = "0.11.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b2daee4ea451f429a58296525ddf28b45a3b64f1acf6587e2067437bb11e218d"
|
||||||
|
dependencies = [
|
||||||
|
"anstream 0.6.21",
|
||||||
|
"anstyle",
|
||||||
|
"env_filter",
|
||||||
|
"jiff",
|
||||||
|
"log",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "equivalent"
|
name = "equivalent"
|
||||||
version = "1.0.2"
|
version = "1.0.2"
|
||||||
@@ -449,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"
|
||||||
@@ -527,6 +708,12 @@ dependencies = [
|
|||||||
"syn 2.0.117",
|
"syn 2.0.117",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "is_terminal_polyfill"
|
||||||
|
version = "1.70.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "itertools"
|
name = "itertools"
|
||||||
version = "0.14.0"
|
version = "0.14.0"
|
||||||
@@ -542,6 +729,41 @@ 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]]
|
||||||
|
name = "jiff"
|
||||||
|
version = "0.2.23"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1a3546dc96b6d42c5f24902af9e2538e82e39ad350b0c766eb3fbf2d8f3d8359"
|
||||||
|
dependencies = [
|
||||||
|
"jiff-static",
|
||||||
|
"log",
|
||||||
|
"portable-atomic",
|
||||||
|
"portable-atomic-util",
|
||||||
|
"serde_core",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "jiff-static"
|
||||||
|
version = "0.2.23"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2a8c8b344124222efd714b73bb41f8b5120b27a7cc1c75593a6ff768d9d05aa4"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 2.0.117",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "js-sys"
|
name = "js-sys"
|
||||||
version = "0.3.91"
|
version = "0.3.91"
|
||||||
@@ -690,6 +912,29 @@ dependencies = [
|
|||||||
"windows-sys",
|
"windows-sys",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "mould"
|
||||||
|
version = "0.5.0"
|
||||||
|
dependencies = [
|
||||||
|
"anyhow",
|
||||||
|
"clap",
|
||||||
|
"crossterm",
|
||||||
|
"dirs",
|
||||||
|
"env_logger",
|
||||||
|
"java-properties",
|
||||||
|
"log",
|
||||||
|
"quick-xml",
|
||||||
|
"ratatui",
|
||||||
|
"rust-ini",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"serde_yaml",
|
||||||
|
"tempfile",
|
||||||
|
"thiserror 2.0.18",
|
||||||
|
"toml",
|
||||||
|
"tui-input",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "nix"
|
name = "nix"
|
||||||
version = "0.29.0"
|
version = "0.29.0"
|
||||||
@@ -754,6 +999,12 @@ version = "1.21.4"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "once_cell_polyfill"
|
||||||
|
version = "1.70.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "option-ext"
|
name = "option-ext"
|
||||||
version = "0.2.0"
|
version = "0.2.0"
|
||||||
@@ -769,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"
|
||||||
@@ -893,6 +1154,15 @@ version = "1.13.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"
|
checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "portable-atomic-util"
|
||||||
|
version = "0.2.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "091397be61a01d4be58e7841595bd4bfedb15f1cd54977d79b8271e94ed799a3"
|
||||||
|
dependencies = [
|
||||||
|
"portable-atomic",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "powerfmt"
|
name = "powerfmt"
|
||||||
version = "0.2.0"
|
version = "0.2.0"
|
||||||
@@ -918,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"
|
||||||
@@ -1088,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"
|
||||||
@@ -1170,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",
|
||||||
@@ -1186,6 +1477,19 @@ dependencies = [
|
|||||||
"serde_core",
|
"serde_core",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde_yaml"
|
||||||
|
version = "0.9.34+deprecated"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"
|
||||||
|
dependencies = [
|
||||||
|
"indexmap",
|
||||||
|
"itoa",
|
||||||
|
"ryu",
|
||||||
|
"serde",
|
||||||
|
"unsafe-libyaml",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "sha2"
|
name = "sha2"
|
||||||
version = "0.10.9"
|
version = "0.10.9"
|
||||||
@@ -1433,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",
|
||||||
@@ -1449,27 +1762,37 @@ 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]]
|
||||||
|
name = "tui-input"
|
||||||
|
version = "0.15.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "79c1ee964298f136020f5f69e0e601f4d3a1f610a7baf1af9fcb96152e8a2c45"
|
||||||
|
dependencies = [
|
||||||
|
"ratatui",
|
||||||
|
"unicode-width",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "typenum"
|
name = "typenum"
|
||||||
@@ -1518,6 +1841,12 @@ version = "0.2.6"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
|
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unsafe-libyaml"
|
||||||
|
version = "0.2.11"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "utf8parse"
|
name = "utf8parse"
|
||||||
version = "0.2.2"
|
version = "0.2.2"
|
||||||
@@ -1765,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"
|
||||||
|
|||||||
21
Cargo.toml
21
Cargo.toml
@@ -1,19 +1,30 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "cenv-rs"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
authors = ["Nils Pukropp <nils@narl.io>"]
|
authors = ["Nils Pukropp <nils@narl.io>"]
|
||||||
|
edition = "2024"
|
||||||
|
name = "mould"
|
||||||
|
version = "0.5.0"
|
||||||
|
|
||||||
[[bin]]
|
[[bin]]
|
||||||
name = "cenv"
|
name = "mould"
|
||||||
path = "src/main.rs"
|
path = "src/main.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
anyhow = "1.0.102"
|
||||||
crossterm = "0.29.0"
|
crossterm = "0.29.0"
|
||||||
dirs = "6.0.0"
|
dirs = "6.0.0"
|
||||||
|
env_logger = "0.11.9"
|
||||||
|
java-properties = "2.0.0"
|
||||||
|
log = "0.4.29"
|
||||||
ratatui = "0.30.0"
|
ratatui = "0.30.0"
|
||||||
|
rust-ini = "0.21.3"
|
||||||
serde = { version = "1.0.228", features = ["derive"] }
|
serde = { version = "1.0.228", features = ["derive"] }
|
||||||
toml = "1.0.6"
|
serde_json = { version = "1.0.149", features = ["preserve_order"] }
|
||||||
|
serde_yaml = "0.9.34"
|
||||||
|
thiserror = "2.0.18"
|
||||||
|
toml = { version = "1.0.7", features = ["preserve_order"] }
|
||||||
|
tui-input = "0.15.0"
|
||||||
|
clap = { version = "4.6.0", features = ["derive"] }
|
||||||
|
quick-xml = { version = "0.39.2", features = ["serde", "serialize"] }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tempfile = "3.27.0"
|
tempfile = "3.27.0"
|
||||||
|
|||||||
2
LICENSE
2
LICENSE
@@ -1,6 +1,6 @@
|
|||||||
MIT License
|
MIT License
|
||||||
|
|
||||||
Copyright (c) 2026 The cenv-rs Contributors
|
Copyright (c) 2026 Nils Pukropp <nils@narl.io>
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
|||||||
169
README.md
169
README.md
@@ -1,64 +1,187 @@
|
|||||||
# cenv-rs
|
# mould
|
||||||
|
|
||||||
cenv-rs is a Rust-based Terminal User Interface (TUI) tool designed to help developers interactively generate `.env` files from `.env.example` templates. With a focus on speed and usability, it features Vim-like keybindings and out-of-the-box support for theming, defaulting to the Catppuccin Mocha palette.
|
mould is a modern Terminal User Interface (TUI) tool designed for interactively generating and editing configuration files from templates. Whether you are setting up a `.env` file from an example, creating a `docker-compose.override.yml`, or editing nested `JSON`, `YAML`, `TOML`, `XML`, `INI`, or `Properties` configurations, mould provides a fast, Vim-inspired workflow to get your environment ready.
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- Parse `.env.example` files to extract keys, default values, and comments.
|
- **Universal Format Support**: Read, edit, and write `.env`, `JSON`, `YAML`, `TOML`, `XML`, `INI`, and `Properties` files seamlessly.
|
||||||
- Vim-like keybindings for quick navigation and editing.
|
- **Tree View Navigation**: Edit nested data structures in a beautiful, depth-colored tree view.
|
||||||
- Built-in theming support with Catppuccin Mocha as the default.
|
- **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.
|
||||||
- Configurable through a standard TOML file.
|
- **Strict Type Preservation**: Intelligently preserves data types (integers, booleans, strings) during edit-save cycles, ensuring your configuration stays valid.
|
||||||
|
- **Add Missing Keys**: Instantly pull missing keys and their default values from your template into your active configuration with a single keystroke.
|
||||||
|
- **Advanced Undo/Redo Engine**: Features a tree-based undo/redo history that ensures you never lose changes during complex branching edits.
|
||||||
|
- **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 cenv-rs
|
cd mould-rs
|
||||||
cargo build --release
|
cargo build --release
|
||||||
|
# The executable will be located in target/release/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
|
||||||
|
|
||||||
Navigate to a directory containing a `.env.example` file and run:
|
Provide an input template file to start editing. `mould` is smart enough to figure out if it's looking at a template or an active file, and will search for its counterpart to provide live diffing.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
cenv-rs
|
mould .env.example
|
||||||
|
mould docker-compose.yml
|
||||||
|
mould config.template.json -o config.json
|
||||||
```
|
```
|
||||||
|
|
||||||
### Keybindings
|
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)
|
||||||
|
|
||||||
- **Normal Mode**
|
- **Normal Mode**
|
||||||
- `j` / `Down`: Move selection down
|
- `j` / `Down`: Move selection down
|
||||||
- `k` / `Up`: Move selection up
|
- `k` / `Up`: Move selection up
|
||||||
- `i`: Edit the value of the currently selected key (Enter Insert Mode)
|
- `gg`: Jump to the top
|
||||||
- `:w` or `Enter`: Save the current configuration to `.env`
|
- `G`: Jump to the bottom
|
||||||
- `q` or `:q`: Quit the application without saving
|
- `i`: Edit value (cursor at start)
|
||||||
- `Esc`: Clear current prompt or return from actions
|
- `a`: Edit value (cursor at end)
|
||||||
|
- `s`: Substitute value (clear and edit)
|
||||||
|
- `r`: Rename the current key
|
||||||
|
- `o`: Append a new item (as a sibling or array element)
|
||||||
|
- `O`: Prepend a new item
|
||||||
|
- `alt+o` / `alt+O`: Append/Prepend a new group/object
|
||||||
|
- `t`: Toggle between group/object and standard value
|
||||||
|
- `dd`: Delete the currently selected variable or group (removes all nested children)
|
||||||
|
- `u`: Undo the last change
|
||||||
|
- `U`: Redo the reverted change
|
||||||
|
- `a`: Add missing value from template to active config
|
||||||
|
- `/`: Search for configuration keys
|
||||||
|
- `n` / `N`: Jump to next / previous search match
|
||||||
|
- `:w` or `Enter`: Save the current configuration
|
||||||
|
- `:q` or `q`: Quit the application
|
||||||
|
- `:wq`: Save and quit
|
||||||
|
- `Esc`: Clear current command prompt
|
||||||
|
|
||||||
- **Insert Mode**
|
- **Insert / Rename Modes**
|
||||||
- Type your value for the selected key.
|
- Type your value/key string.
|
||||||
- `Esc`: Return to Normal Mode
|
- Arrow keys: Navigate within the input field
|
||||||
|
- `Enter`: Commit the value and return to Normal Mode
|
||||||
|
- `Esc`: Cancel edits and return to Normal Mode
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
cenv-rs can be configured using a `config.toml` file located in your user configuration directory (e.g., `~/.config/cenv-rs/config.toml` on Linux/macOS).
|
`mould` can be configured using a `config.toml` file located in your user configuration directory:
|
||||||
|
- **Linux/macOS**: `~/.config/mould/config.toml`
|
||||||
|
- **Windows**: `%AppData%\mould\config.toml`
|
||||||
|
|
||||||
Example configuration:
|
Example configuration:
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
[theme]
|
[theme]
|
||||||
# Default theme is "catppuccin_mocha"
|
transparent = false
|
||||||
name = "catppuccin_mocha"
|
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]
|
||||||
|
down = "j"
|
||||||
|
up = "k"
|
||||||
|
edit = "i"
|
||||||
|
edit_append = "a"
|
||||||
|
edit_substitute = "s"
|
||||||
|
save = ":w"
|
||||||
|
quit = ":q"
|
||||||
|
normal_mode = "Esc"
|
||||||
|
search = "/"
|
||||||
|
next_match = "n"
|
||||||
|
previous_match = "N"
|
||||||
|
jump_top = "gg"
|
||||||
|
jump_bottom = "G"
|
||||||
|
append_item = "o"
|
||||||
|
prepend_item = "O"
|
||||||
|
delete_item = "dd"
|
||||||
|
undo = "u"
|
||||||
|
redo = "U"
|
||||||
|
rename = "r"
|
||||||
|
append_group = "alt+o"
|
||||||
|
prepend_group = "alt+O"
|
||||||
|
toggle_group = "t"
|
||||||
```
|
```
|
||||||
|
|
||||||
## License
|
---
|
||||||
|
|
||||||
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
|
## 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 Architecture
|
||||||
|
|
||||||
|
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 (`Normal`, `Insert`, `InsertKey`, `Search`), and user input buffer.
|
||||||
|
- It integrates an **UndoTree**, providing non-linear, branching history tracking for complex edits (additions, deletions, nested renaming).
|
||||||
|
|
||||||
|
2. **Unified Data Model (`src/format/mod.rs`)**
|
||||||
|
- Regardless of the underlying format, all data is translated into a flattened `Vec<ConfigItem>`.
|
||||||
|
- A `ConfigItem` contains its structural path (`Vec<PathSegment>` handling nested Object Keys and Array Indices), values, type metadata (`ValueType`), and template comparison statuses (e.g., `MissingFromActive`).
|
||||||
|
|
||||||
|
3. **Format Handlers (`src/format/*`)**
|
||||||
|
- **`env.rs` & `properties.rs`**: Handlers for flat key-value files.
|
||||||
|
- **`hierarchical.rs`**: 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).
|
||||||
|
- **`ini.rs`**: Handles traditional `[Section]` based INI configurations.
|
||||||
|
|
||||||
|
4. **Template Resolver (`src/resolver.rs`)**
|
||||||
|
- Automatically determines structural pairings without explicit 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**: Powered by `ratatui`. Renders a conditional side-by-side or vertical layout consisting of a styled hierarchical List, an active Input field, and a status bar indicating keybind availability.
|
||||||
|
- **Event Runner**: Powered by `crossterm`. Intercepts keystrokes, resolves sequences (like `dd` or `gg`), delegates to the `tui-input` backend during active editing, and interacts with the internal API to mutate the configuration tree.
|
||||||
|
|
||||||
|
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, triggering automatic Neovim `checktime` syncs on exit.
|
||||||
|
|||||||
52
config.example.toml
Normal file
52
config.example.toml
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
# mould Configuration Example
|
||||||
|
# Place this file at ~/.config/mould/config.toml (Linux/macOS)
|
||||||
|
# or %AppData%\mould\config.toml (Windows)
|
||||||
|
|
||||||
|
[theme]
|
||||||
|
# If true, skip rendering the background block to let the terminal's transparency show.
|
||||||
|
transparent = false
|
||||||
|
|
||||||
|
# Colors are specified in hex format ("#RRGGBB").
|
||||||
|
# Default values follow the Semantic Catppuccin Mocha palette.
|
||||||
|
|
||||||
|
bg_normal = "#1e1e2e"
|
||||||
|
bg_highlight = "#89b4fa"
|
||||||
|
bg_active = "#a6e3a1"
|
||||||
|
bg_search = "#cba6f7"
|
||||||
|
fg_normal = "#cdd6f4"
|
||||||
|
fg_dimmed = "#6c7086"
|
||||||
|
fg_highlight = "#1e1e2e"
|
||||||
|
fg_warning = "#f38ba8"
|
||||||
|
fg_modified = "#fab387"
|
||||||
|
fg_accent = "#b4befe"
|
||||||
|
border_normal = "#45475a"
|
||||||
|
border_active = "#a6e3a1"
|
||||||
|
tree_depth_1 = "#b4befe"
|
||||||
|
tree_depth_2 = "#cba6f7"
|
||||||
|
tree_depth_3 = "#89b4fa"
|
||||||
|
tree_depth_4 = "#fab387"
|
||||||
|
|
||||||
|
[keybinds]
|
||||||
|
# Keybindings for navigation and application control.
|
||||||
|
down = "j"
|
||||||
|
up = "k"
|
||||||
|
edit = "i"
|
||||||
|
edit_append = "a"
|
||||||
|
edit_substitute = "s"
|
||||||
|
save = ":w"
|
||||||
|
quit = ":q"
|
||||||
|
normal_mode = "Esc"
|
||||||
|
search = "/"
|
||||||
|
next_match = "n"
|
||||||
|
previous_match = "N"
|
||||||
|
jump_top = "gg"
|
||||||
|
jump_bottom = "G"
|
||||||
|
append_item = "o"
|
||||||
|
prepend_item = "O"
|
||||||
|
delete_item = "dd"
|
||||||
|
undo = "u"
|
||||||
|
redo = "U"
|
||||||
|
rename = "r"
|
||||||
|
append_group = "alt+o"
|
||||||
|
prepend_group = "alt+O"
|
||||||
|
toggle_group = "t"
|
||||||
54
lua/mould/init.lua
Normal file
54
lua/mould/init.lua
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
local M = {}
|
||||||
|
|
||||||
|
local function open_floating_terminal(cmd)
|
||||||
|
local buf = vim.api.nvim_create_buf(false, true)
|
||||||
|
local width = math.floor(vim.o.columns * 0.9)
|
||||||
|
local height = math.floor(vim.o.lines * 0.9)
|
||||||
|
local col = math.floor((vim.o.columns - width) / 2)
|
||||||
|
local row = math.floor((vim.o.lines - height) / 2)
|
||||||
|
|
||||||
|
local win_config = {
|
||||||
|
relative = "editor",
|
||||||
|
width = width,
|
||||||
|
height = height,
|
||||||
|
col = col,
|
||||||
|
row = row,
|
||||||
|
style = "minimal",
|
||||||
|
border = "rounded",
|
||||||
|
}
|
||||||
|
|
||||||
|
local win = vim.api.nvim_open_win(buf, true, win_config)
|
||||||
|
|
||||||
|
-- Record the original buffer to reload it later
|
||||||
|
local original_buf = vim.api.nvim_get_current_buf()
|
||||||
|
local original_file = vim.api.nvim_buf_get_name(original_buf)
|
||||||
|
|
||||||
|
vim.fn.termopen(cmd, {
|
||||||
|
on_exit = function()
|
||||||
|
vim.api.nvim_win_close(win, true)
|
||||||
|
vim.api.nvim_buf_delete(buf, { force = true })
|
||||||
|
|
||||||
|
-- Reload the original file if it exists
|
||||||
|
if vim.fn.filereadable(original_file) == 1 then
|
||||||
|
vim.schedule(function()
|
||||||
|
vim.cmd("checktime " .. vim.fn.fnameescape(original_file))
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
end,
|
||||||
|
})
|
||||||
|
|
||||||
|
vim.cmd("startinsert")
|
||||||
|
end
|
||||||
|
|
||||||
|
function M.open()
|
||||||
|
local filepath = vim.api.nvim_buf_get_name(0)
|
||||||
|
if filepath == "" then
|
||||||
|
vim.notify("mould.nvim: Cannot open mould for an unnamed buffer.", vim.log.levels.ERROR)
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
local cmd = string.format("mould %s", vim.fn.shellescape(filepath))
|
||||||
|
open_floating_terminal(cmd)
|
||||||
|
end
|
||||||
|
|
||||||
|
return M
|
||||||
8
plugin/mould.lua
Normal file
8
plugin/mould.lua
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
if vim.g.loaded_mould == 1 then
|
||||||
|
return
|
||||||
|
end
|
||||||
|
vim.g.loaded_mould = 1
|
||||||
|
|
||||||
|
vim.api.nvim_create_user_command("Mould", function()
|
||||||
|
require("mould").open()
|
||||||
|
end, { desc = "Open mould for the current buffer" })
|
||||||
547
src/app.rs
547
src/app.rs
@@ -1,35 +1,85 @@
|
|||||||
use crate::env::EnvVar;
|
use crate::format::{ConfigItem, PathSegment};
|
||||||
|
use tui_input::Input;
|
||||||
|
use crate::undo::UndoTree;
|
||||||
|
|
||||||
|
/// Represents the current operating mode of the application.
|
||||||
pub enum Mode {
|
pub enum Mode {
|
||||||
|
/// Standard navigation and command mode.
|
||||||
Normal,
|
Normal,
|
||||||
|
/// Active text entry mode for modifying values.
|
||||||
Insert,
|
Insert,
|
||||||
|
/// Active text entry mode for modifying keys.
|
||||||
|
InsertKey,
|
||||||
|
/// Active search mode for filtering keys.
|
||||||
|
Search,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub enum InsertVariant {
|
||||||
|
Start,
|
||||||
|
End,
|
||||||
|
Substitute,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The core application state, holding all configuration variables and UI status.
|
||||||
pub struct App {
|
pub struct App {
|
||||||
pub vars: Vec<EnvVar>,
|
/// The list of configuration variables being edited.
|
||||||
|
pub vars: Vec<ConfigItem>,
|
||||||
|
/// Index of the currently selected variable in the list.
|
||||||
pub selected: usize,
|
pub selected: usize,
|
||||||
|
/// The current interaction mode (Normal or Insert).
|
||||||
pub mode: Mode,
|
pub mode: Mode,
|
||||||
|
/// Whether the main application loop should continue running.
|
||||||
pub running: bool,
|
pub running: bool,
|
||||||
|
/// An optional message to display in the status bar (e.g., "Saved to .env").
|
||||||
pub status_message: Option<String>,
|
pub status_message: Option<String>,
|
||||||
|
/// The active text input buffer for the selected variable.
|
||||||
|
pub input: Input,
|
||||||
|
/// The current search query for filtering keys.
|
||||||
|
pub search_query: String,
|
||||||
|
/// Undo history structured as a tree
|
||||||
|
pub undo_tree: UndoTree,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl App {
|
impl App {
|
||||||
pub fn new(vars: Vec<EnvVar>) -> Self {
|
/// Initializes a new application instance with the provided variables.
|
||||||
|
pub fn new(vars: Vec<ConfigItem>) -> Self {
|
||||||
|
let initial_input = vars.first().and_then(|v| v.value.clone()).unwrap_or_default();
|
||||||
|
let undo_tree = UndoTree::new(vars.clone(), 0);
|
||||||
Self {
|
Self {
|
||||||
vars,
|
vars,
|
||||||
selected: 0,
|
selected: 0,
|
||||||
mode: Mode::Normal,
|
mode: Mode::Normal,
|
||||||
running: true,
|
running: true,
|
||||||
status_message: None,
|
status_message: None,
|
||||||
|
input: Input::new(initial_input),
|
||||||
|
search_query: String::new(),
|
||||||
|
undo_tree,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns the indices of variables that match the search query.
|
||||||
|
pub fn matching_indices(&self) -> Vec<usize> {
|
||||||
|
if self.search_query.is_empty() {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
let query = self.search_query.to_lowercase();
|
||||||
|
self.vars
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.filter(|(_, v)| v.key.to_lowercase().contains(&query))
|
||||||
|
.map(|(i, _)| i)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves the selection to the next variable in the list, wrapping around if necessary.
|
||||||
pub fn next(&mut self) {
|
pub fn next(&mut self) {
|
||||||
if !self.vars.is_empty() {
|
if !self.vars.is_empty() {
|
||||||
self.selected = (self.selected + 1) % self.vars.len();
|
self.selected = (self.selected + 1) % self.vars.len();
|
||||||
|
self.sync_input_with_selected();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Moves the selection to the previous variable in the list, wrapping around if necessary.
|
||||||
pub fn previous(&mut self) {
|
pub fn previous(&mut self) {
|
||||||
if !self.vars.is_empty() {
|
if !self.vars.is_empty() {
|
||||||
if self.selected == 0 {
|
if self.selected == 0 {
|
||||||
@@ -37,19 +87,502 @@ impl App {
|
|||||||
} else {
|
} else {
|
||||||
self.selected -= 1;
|
self.selected -= 1;
|
||||||
}
|
}
|
||||||
|
self.sync_input_with_selected();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn enter_insert(&mut self) {
|
/// Jumps to the top of the list.
|
||||||
|
pub fn jump_top(&mut self) {
|
||||||
|
if !self.vars.is_empty() {
|
||||||
|
self.selected = 0;
|
||||||
|
self.sync_input_with_selected();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Jumps to the bottom of the list.
|
||||||
|
pub fn jump_bottom(&mut self) {
|
||||||
|
if !self.vars.is_empty() {
|
||||||
|
self.selected = self.vars.len() - 1;
|
||||||
|
self.sync_input_with_selected();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Jumps to the next variable that matches the search query.
|
||||||
|
pub fn jump_next_match(&mut self) {
|
||||||
|
let indices = self.matching_indices();
|
||||||
|
if indices.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let next_match = indices
|
||||||
|
.iter()
|
||||||
|
.find(|&&i| i > self.selected)
|
||||||
|
.or_else(|| indices.first());
|
||||||
|
|
||||||
|
if let Some(&index) = next_match {
|
||||||
|
self.selected = index;
|
||||||
|
self.sync_input_with_selected();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Jumps to the previous variable that matches the search query.
|
||||||
|
pub fn jump_previous_match(&mut self) {
|
||||||
|
let indices = self.matching_indices();
|
||||||
|
if indices.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let prev_match = indices
|
||||||
|
.iter()
|
||||||
|
.rev()
|
||||||
|
.find(|&&i| i < self.selected)
|
||||||
|
.or_else(|| indices.last());
|
||||||
|
|
||||||
|
if let Some(&index) = prev_match {
|
||||||
|
self.selected = index;
|
||||||
|
self.sync_input_with_selected();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Updates the input buffer to reflect the value of the currently selected variable.
|
||||||
|
pub fn sync_input_with_selected(&mut self) {
|
||||||
|
if let Some(var) = self.vars.get(self.selected) {
|
||||||
|
let val = match self.mode {
|
||||||
|
Mode::InsertKey => var.key.clone(),
|
||||||
|
_ => var.value.clone().unwrap_or_default(),
|
||||||
|
};
|
||||||
|
self.input = Input::new(val);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Commits the current text in the input buffer back to the selected variable's value or key.
|
||||||
|
/// Returns true if commit was successful, false if there was an error (e.g. collision).
|
||||||
|
pub fn commit_input(&mut self) -> bool {
|
||||||
|
match self.mode {
|
||||||
|
Mode::Insert => {
|
||||||
|
if let Some(var) = self.vars.get_mut(self.selected)
|
||||||
|
&& !var.is_group {
|
||||||
|
var.value = Some(self.input.value().to_string());
|
||||||
|
var.status = crate::format::ItemStatus::Modified;
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
Mode::InsertKey => {
|
||||||
|
let new_key = self.input.value().trim().to_string();
|
||||||
|
if new_key.is_empty() {
|
||||||
|
self.status_message = Some("Key cannot be empty".to_string());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
let selected_var = self.vars[self.selected].clone();
|
||||||
|
if selected_var.key == new_key {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collision check: siblings share the same parent path
|
||||||
|
let parent_path = if selected_var.path.len() > 1 {
|
||||||
|
&selected_var.path[..selected_var.path.len() - 1]
|
||||||
|
} else {
|
||||||
|
&[]
|
||||||
|
};
|
||||||
|
|
||||||
|
let exists = self.vars.iter().enumerate().any(|(i, v)| {
|
||||||
|
i != self.selected
|
||||||
|
&& v.path.len() == selected_var.path.len()
|
||||||
|
&& v.path.starts_with(parent_path)
|
||||||
|
&& v.key == new_key
|
||||||
|
});
|
||||||
|
|
||||||
|
if exists {
|
||||||
|
self.status_message = Some(format!("Key already exists: {}", new_key));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update selected item's key and path
|
||||||
|
let old_path = selected_var.path.clone();
|
||||||
|
let mut new_path = parent_path.to_vec();
|
||||||
|
new_path.push(PathSegment::Key(new_key.clone()));
|
||||||
|
|
||||||
|
{
|
||||||
|
let var = self.vars.get_mut(self.selected).unwrap();
|
||||||
|
var.key = new_key;
|
||||||
|
var.path = new_path.clone();
|
||||||
|
var.status = crate::format::ItemStatus::Modified;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update paths of all children if it's a group
|
||||||
|
if selected_var.is_group {
|
||||||
|
for var in self.vars.iter_mut() {
|
||||||
|
if var.path.starts_with(&old_path) && var.path.len() > old_path.len() {
|
||||||
|
let mut p = new_path.clone();
|
||||||
|
p.extend(var.path[old_path.len()..].iter().cloned());
|
||||||
|
var.path = p;
|
||||||
|
var.status = crate::format::ItemStatus::Modified;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
_ => true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Transitions the application into Insert Mode for keys.
|
||||||
|
pub fn enter_insert_key(&mut self) {
|
||||||
|
if !self.vars.is_empty() {
|
||||||
|
if let Some(var) = self.vars.get(self.selected)
|
||||||
|
&& matches!(var.path.last(), Some(PathSegment::Index(_))) {
|
||||||
|
self.status_message = Some("Cannot rename array indices".to_string());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.mode = Mode::InsertKey;
|
||||||
|
self.sync_input_with_selected();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Transitions the application into Insert Mode with a specific variant.
|
||||||
|
pub fn enter_insert(&mut self, variant: InsertVariant) {
|
||||||
|
if let Some(var) = self.vars.get(self.selected) {
|
||||||
|
if var.is_group {
|
||||||
|
self.enter_insert_key();
|
||||||
|
} else {
|
||||||
|
if !matches!(variant, InsertVariant::Substitute) {
|
||||||
|
self.sync_input_with_selected();
|
||||||
|
}
|
||||||
self.mode = Mode::Insert;
|
self.mode = Mode::Insert;
|
||||||
|
match variant {
|
||||||
|
InsertVariant::Start => {
|
||||||
|
use tui_input::InputRequest;
|
||||||
|
self.input.handle(InputRequest::GoToStart);
|
||||||
|
}
|
||||||
|
InsertVariant::End => {
|
||||||
|
use tui_input::InputRequest;
|
||||||
|
self.input.handle(InputRequest::GoToEnd);
|
||||||
|
}
|
||||||
|
InsertVariant::Substitute => {
|
||||||
|
self.input = Input::new(String::new());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Commits the current input and transitions the application into Normal Mode.
|
||||||
pub fn enter_normal(&mut self) {
|
pub fn enter_normal(&mut self) {
|
||||||
|
if self.commit_input() {
|
||||||
|
self.save_undo_state();
|
||||||
self.mode = Mode::Normal;
|
self.mode = Mode::Normal;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
/// Cancels the current input and transitions the application into Normal Mode.
|
||||||
pub fn quit(&mut self) {
|
pub fn cancel_insert(&mut self) {
|
||||||
self.running = false;
|
self.mode = Mode::Normal;
|
||||||
|
self.sync_input_with_selected();
|
||||||
|
self.status_message = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deletes the currently selected item. If it's a group, deletes all children.
|
||||||
|
pub fn delete_selected(&mut self) {
|
||||||
|
if self.vars.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let selected_path = self.vars[self.selected].path.clone();
|
||||||
|
let is_group = self.vars[self.selected].is_group;
|
||||||
|
|
||||||
|
// 1. Identify all items to remove
|
||||||
|
let mut to_remove = Vec::new();
|
||||||
|
to_remove.push(self.selected);
|
||||||
|
|
||||||
|
if is_group {
|
||||||
|
for (i, var) in self.vars.iter().enumerate() {
|
||||||
|
if i == self.selected {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// An item is a child if its path starts with the selected path
|
||||||
|
if var.path.starts_with(&selected_path) {
|
||||||
|
to_remove.push(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Perform removal (reverse order to preserve indices)
|
||||||
|
to_remove.sort_unstable_by(|a, b| b.cmp(a));
|
||||||
|
for i in to_remove {
|
||||||
|
self.vars.remove(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Re-index subsequent array items if applicable
|
||||||
|
if let Some(PathSegment::Index(removed_idx)) = selected_path.last() {
|
||||||
|
let base_path = &selected_path[..selected_path.len() - 1];
|
||||||
|
|
||||||
|
for var in self.vars.iter_mut() {
|
||||||
|
if var.path.starts_with(base_path) && var.path.len() >= selected_path.len() {
|
||||||
|
// Check if the element at the level of the removed index is an index
|
||||||
|
if let PathSegment::Index(i) = var.path[selected_path.len() - 1]
|
||||||
|
&& i > *removed_idx {
|
||||||
|
let new_idx = i - 1;
|
||||||
|
var.path[selected_path.len() - 1] = PathSegment::Index(new_idx);
|
||||||
|
|
||||||
|
// If this was an array element itself (not a child property), update its key
|
||||||
|
if var.path.len() == selected_path.len() {
|
||||||
|
var.key = format!("[{}]", new_idx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Adjust selection
|
||||||
|
if self.selected >= self.vars.len() && !self.vars.is_empty() {
|
||||||
|
self.selected = self.vars.len() - 1;
|
||||||
|
}
|
||||||
|
self.sync_input_with_selected();
|
||||||
|
self.save_undo_state();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds a new item relative to the selected item.
|
||||||
|
pub fn add_item(&mut self, after: bool, is_group: bool, as_child: bool) {
|
||||||
|
if self.vars.is_empty() {
|
||||||
|
let new_key = if is_group { "NEW_GROUP".to_string() } else { "NEW_VAR".to_string() };
|
||||||
|
self.vars.push(ConfigItem {
|
||||||
|
key: new_key.clone(),
|
||||||
|
path: vec![PathSegment::Key(new_key)],
|
||||||
|
value: if is_group { None } else { Some("".to_string()) },
|
||||||
|
template_value: None,
|
||||||
|
default_value: None,
|
||||||
|
depth: 0,
|
||||||
|
is_group,
|
||||||
|
status: crate::format::ItemStatus::Modified,
|
||||||
|
value_type: if is_group { crate::format::ValueType::Null } else { crate::format::ValueType::String },
|
||||||
|
});
|
||||||
|
self.selected = 0;
|
||||||
|
self.sync_input_with_selected();
|
||||||
|
self.save_undo_state();
|
||||||
|
if is_group {
|
||||||
|
self.enter_insert_key();
|
||||||
|
} else {
|
||||||
|
self.enter_insert(InsertVariant::Start);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let selected_item = self.vars[self.selected].clone();
|
||||||
|
|
||||||
|
// 1. Determine new item properties (path, key, depth, position)
|
||||||
|
let mut new_path;
|
||||||
|
let new_depth;
|
||||||
|
let insert_pos;
|
||||||
|
let mut is_array_item = false;
|
||||||
|
|
||||||
|
if !as_child && let Some(PathSegment::Index(idx)) = selected_item.path.last() {
|
||||||
|
// ARRAY ITEM LOGIC (Adding sibling to an existing index)
|
||||||
|
is_array_item = true;
|
||||||
|
let base_path = selected_item.path[..selected_item.path.len() - 1].to_vec();
|
||||||
|
let new_idx = if after { idx + 1 } else { *idx };
|
||||||
|
insert_pos = if after { self.selected + 1 } else { self.selected };
|
||||||
|
|
||||||
|
// Shift subsequent indices
|
||||||
|
for var in self.vars.iter_mut() {
|
||||||
|
if var.path.starts_with(&base_path) && var.path.len() > base_path.len()
|
||||||
|
&& let PathSegment::Index(i) = var.path[base_path.len()]
|
||||||
|
&& i >= new_idx {
|
||||||
|
var.path[base_path.len()] = PathSegment::Index(i + 1);
|
||||||
|
if var.path.len() == base_path.len() + 1 {
|
||||||
|
var.key = format!("[{}]", i + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
new_path = base_path;
|
||||||
|
new_path.push(PathSegment::Index(new_idx));
|
||||||
|
new_depth = selected_item.depth;
|
||||||
|
} else if as_child && selected_item.is_group {
|
||||||
|
// ADD AS CHILD OF GROUP
|
||||||
|
insert_pos = self.selected + 1;
|
||||||
|
new_path = selected_item.path.clone();
|
||||||
|
new_depth = selected_item.depth + 1;
|
||||||
|
|
||||||
|
// Check if this group already contains array items
|
||||||
|
if self.is_array_group(&selected_item.path) {
|
||||||
|
is_array_item = true;
|
||||||
|
let new_idx = 0; // Prepend to array
|
||||||
|
new_path.push(PathSegment::Index(new_idx));
|
||||||
|
|
||||||
|
// Shift existing children
|
||||||
|
for var in self.vars.iter_mut() {
|
||||||
|
if var.path.starts_with(&selected_item.path) && var.path.len() > selected_item.path.len()
|
||||||
|
&& let PathSegment::Index(i) = var.path[selected_item.path.len()] {
|
||||||
|
var.path[selected_item.path.len()] = PathSegment::Index(i + 1);
|
||||||
|
if var.path.len() == selected_item.path.len() + 1 {
|
||||||
|
var.key = format!("[{}]", i + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// ADD AS SIBLING
|
||||||
|
let parent_path = if selected_item.path.len() > 1 {
|
||||||
|
selected_item.path[..selected_item.path.len() - 1].to_vec()
|
||||||
|
} else {
|
||||||
|
Vec::new()
|
||||||
|
};
|
||||||
|
|
||||||
|
insert_pos = if after {
|
||||||
|
let mut p = self.selected + 1;
|
||||||
|
while p < self.vars.len() && self.vars[p].path.starts_with(&selected_item.path) {
|
||||||
|
p += 1;
|
||||||
|
}
|
||||||
|
p
|
||||||
|
} else {
|
||||||
|
self.selected
|
||||||
|
};
|
||||||
|
|
||||||
|
new_path = parent_path;
|
||||||
|
new_depth = selected_item.depth;
|
||||||
|
|
||||||
|
// If the parent is an array group, this is also an array item
|
||||||
|
if !new_path.is_empty() && self.is_array_group(&new_path) {
|
||||||
|
is_array_item = true;
|
||||||
|
if let Some(PathSegment::Index(idx)) = selected_item.path.last() {
|
||||||
|
let new_idx = if after { idx + 1 } else { *idx };
|
||||||
|
new_path.push(PathSegment::Index(new_idx));
|
||||||
|
} else {
|
||||||
|
new_path.push(PathSegment::Index(0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Generate a unique key for non-array items
|
||||||
|
let final_key = if is_array_item {
|
||||||
|
if let Some(PathSegment::Index(idx)) = new_path.last() {
|
||||||
|
format!("[{}]", idx)
|
||||||
|
} else {
|
||||||
|
"NEW_VAR".to_string()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let mut count = 1;
|
||||||
|
let mut candidate = if is_group { "NEW_GROUP".to_string() } else { "NEW_VAR".to_string() };
|
||||||
|
let parent_path_slice = new_path.as_slice();
|
||||||
|
|
||||||
|
while self.vars.iter().any(|v| {
|
||||||
|
v.path.starts_with(parent_path_slice)
|
||||||
|
&& v.path.len() == parent_path_slice.len() + 1
|
||||||
|
&& v.key == candidate
|
||||||
|
}) {
|
||||||
|
candidate = if is_group { format!("NEW_GROUP_{}", count) } else { format!("NEW_VAR_{}", count) };
|
||||||
|
count += 1;
|
||||||
|
}
|
||||||
|
new_path.push(PathSegment::Key(candidate.clone()));
|
||||||
|
candidate
|
||||||
|
};
|
||||||
|
|
||||||
|
// 3. Insert new item
|
||||||
|
let new_item = ConfigItem {
|
||||||
|
key: final_key,
|
||||||
|
path: new_path,
|
||||||
|
value: if is_group { None } else { Some("".to_string()) },
|
||||||
|
template_value: None,
|
||||||
|
default_value: None,
|
||||||
|
depth: new_depth,
|
||||||
|
is_group,
|
||||||
|
status: crate::format::ItemStatus::Modified,
|
||||||
|
value_type: if is_group { crate::format::ValueType::Null } else { crate::format::ValueType::String },
|
||||||
|
};
|
||||||
|
|
||||||
|
self.vars.insert(insert_pos, new_item);
|
||||||
|
self.selected = insert_pos;
|
||||||
|
self.save_undo_state();
|
||||||
|
|
||||||
|
if is_array_item {
|
||||||
|
self.sync_input_with_selected();
|
||||||
|
self.enter_insert(InsertVariant::Start);
|
||||||
|
} else {
|
||||||
|
self.enter_insert_key();
|
||||||
|
}
|
||||||
|
self.status_message = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Toggles the group status of the currently selected item.
|
||||||
|
pub fn toggle_group_selected(&mut self) {
|
||||||
|
if let Some(var) = self.vars.get_mut(self.selected) {
|
||||||
|
// Cannot toggle array items (always vars)
|
||||||
|
if matches!(var.path.last(), Some(PathSegment::Index(_))) {
|
||||||
|
self.status_message = Some("Cannot toggle array items".to_string());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var.is_group = !var.is_group;
|
||||||
|
if var.is_group {
|
||||||
|
var.value = None;
|
||||||
|
var.value_type = crate::format::ValueType::Null;
|
||||||
|
} else {
|
||||||
|
var.value = Some("".to_string());
|
||||||
|
var.value_type = crate::format::ValueType::String;
|
||||||
|
}
|
||||||
|
var.status = crate::format::ItemStatus::Modified;
|
||||||
|
self.sync_input_with_selected();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Status bar helpers
|
||||||
|
pub fn selected_is_group(&self) -> bool {
|
||||||
|
self.vars.get(self.selected).map(|v| v.is_group).unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_array_group(&self, group_path: &[PathSegment]) -> bool {
|
||||||
|
self.vars.iter().any(|v|
|
||||||
|
v.path.starts_with(group_path)
|
||||||
|
&& v.path.len() == group_path.len() + 1
|
||||||
|
&& matches!(v.path.last(), Some(PathSegment::Index(_)))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn selected_is_array(&self) -> bool {
|
||||||
|
self.vars.get(self.selected)
|
||||||
|
.map(|v| !v.is_group && matches!(v.path.last(), Some(PathSegment::Index(_))))
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn selected_is_missing(&self) -> bool {
|
||||||
|
self.vars.get(self.selected)
|
||||||
|
.map(|v| v.status == crate::format::ItemStatus::MissingFromActive)
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Saves the current state of variables to the undo tree.
|
||||||
|
pub fn save_undo_state(&mut self) {
|
||||||
|
self.undo_tree.push(self.vars.clone(), self.selected);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reverts to the previous state in the undo tree.
|
||||||
|
pub fn undo(&mut self) {
|
||||||
|
if let Some(action) = self.undo_tree.undo() {
|
||||||
|
self.vars = action.state.clone();
|
||||||
|
self.selected = action.selected;
|
||||||
|
if self.selected >= self.vars.len() && !self.vars.is_empty() {
|
||||||
|
self.selected = self.vars.len() - 1;
|
||||||
|
}
|
||||||
|
self.sync_input_with_selected();
|
||||||
|
self.status_message = Some("Undo applied".to_string());
|
||||||
|
} else {
|
||||||
|
self.status_message = Some("Nothing to undo".to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Advances to the next state in the undo tree.
|
||||||
|
pub fn redo(&mut self) {
|
||||||
|
if let Some(action) = self.undo_tree.redo() {
|
||||||
|
self.vars = action.state.clone();
|
||||||
|
self.selected = action.selected;
|
||||||
|
if self.selected >= self.vars.len() && !self.vars.is_empty() {
|
||||||
|
self.selected = self.vars.len() - 1;
|
||||||
|
}
|
||||||
|
self.sync_input_with_selected();
|
||||||
|
self.status_message = Some("Redo applied".to_string());
|
||||||
|
} else {
|
||||||
|
self.status_message = Some("Nothing to redo".to_string());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
34
src/cli.rs
Normal file
34
src/cli.rs
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
use clap::Parser;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
/// mould: A TUI tool to generate and edit configuration files (.env, json, yaml, toml)
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
#[command(
|
||||||
|
author,
|
||||||
|
version,
|
||||||
|
about = "mould: A TUI tool to generate and edit configuration files (.env, json, yaml, toml)",
|
||||||
|
long_about = "mould allows you to interactively edit and generate configuration files using templates. It supports various formats including .env, JSON, YAML, and TOML. It features a modern TUI with Vim-inspired keybindings and out-of-the-box support for theming.",
|
||||||
|
after_help = "EXAMPLES:\n mould .env.example\n mould docker-compose.yml\n mould config.template.json -o config.json"
|
||||||
|
)]
|
||||||
|
pub struct Cli {
|
||||||
|
/// The input template file (e.g., .env.example, config.json.template, docker-compose.yml)
|
||||||
|
#[arg(required = false, value_name = "INPUT_FILE")]
|
||||||
|
pub input: Option<PathBuf>,
|
||||||
|
|
||||||
|
/// Optional output file. If not provided, it will be inferred.
|
||||||
|
#[arg(short, long, value_name = "OUTPUT_FILE")]
|
||||||
|
pub output: Option<PathBuf>,
|
||||||
|
|
||||||
|
/// Override the format detection (env, json, yaml, toml)
|
||||||
|
#[arg(short, long, value_name = "FORMAT", value_parser = ["env", "json", "yaml", "toml"])]
|
||||||
|
pub format: Option<String>,
|
||||||
|
|
||||||
|
/// Increase verbosity for logging (can be used multiple times)
|
||||||
|
#[arg(short, long, action = clap::ArgAction::Count)]
|
||||||
|
pub verbose: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses and returns the command-line arguments.
|
||||||
|
pub fn parse() -> Cli {
|
||||||
|
Cli::parse()
|
||||||
|
}
|
||||||
161
src/config.rs
161
src/config.rs
@@ -1,37 +1,182 @@
|
|||||||
|
use ratatui::style::Color;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::fs;
|
use std::fs;
|
||||||
|
|
||||||
|
/// Configuration for the application's appearance.
|
||||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||||
|
#[serde(default)]
|
||||||
pub struct ThemeConfig {
|
pub struct ThemeConfig {
|
||||||
pub name: String,
|
/// If true, skip rendering the background block to let the terminal's transparency show.
|
||||||
|
pub transparent: bool,
|
||||||
|
/// Default background.
|
||||||
|
pub bg_normal: String,
|
||||||
|
/// Background for selected items and standard UI elements.
|
||||||
|
pub bg_highlight: String,
|
||||||
|
/// Active element background (e.g., insert mode).
|
||||||
|
pub bg_active: String,
|
||||||
|
/// Active element background (e.g., search mode).
|
||||||
|
pub bg_search: String,
|
||||||
|
/// Standard text.
|
||||||
|
pub fg_normal: String,
|
||||||
|
/// Secondary/inactive text.
|
||||||
|
pub fg_dimmed: String,
|
||||||
|
/// Text on selected items.
|
||||||
|
pub fg_highlight: String,
|
||||||
|
/// Red/Alert color for missing items.
|
||||||
|
pub fg_warning: String,
|
||||||
|
/// Accent color for modified items.
|
||||||
|
pub fg_modified: String,
|
||||||
|
/// High-contrast accent for titles and active UI elements.
|
||||||
|
pub fg_accent: String,
|
||||||
|
/// Borders.
|
||||||
|
pub border_normal: String,
|
||||||
|
/// Active borders (e.g., input mode).
|
||||||
|
pub border_active: String,
|
||||||
|
/// Color for tree indentation depth 1.
|
||||||
|
pub tree_depth_1: String,
|
||||||
|
/// Color for tree indentation depth 2.
|
||||||
|
pub tree_depth_2: String,
|
||||||
|
/// Color for tree indentation depth 3.
|
||||||
|
pub tree_depth_3: String,
|
||||||
|
/// Color for tree indentation depth 4.
|
||||||
|
pub tree_depth_4: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ThemeConfig {
|
||||||
|
/// Internal helper to parse a hex color string ("#RRGGBB") into a TUI Color.
|
||||||
|
fn parse_hex(hex: &str) -> Color {
|
||||||
|
let hex = hex.trim_start_matches('#');
|
||||||
|
if hex.len() == 6 {
|
||||||
|
let r = u8::from_str_radix(&hex[0..2], 16).unwrap_or(0);
|
||||||
|
let g = u8::from_str_radix(&hex[2..4], 16).unwrap_or(0);
|
||||||
|
let b = u8::from_str_radix(&hex[4..6], 16).unwrap_or(0);
|
||||||
|
Color::Rgb(r, g, b)
|
||||||
|
} else {
|
||||||
|
Color::Reset
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn bg_normal(&self) -> Color { Self::parse_hex(&self.bg_normal) }
|
||||||
|
pub fn bg_highlight(&self) -> Color { Self::parse_hex(&self.bg_highlight) }
|
||||||
|
pub fn bg_active(&self) -> Color { Self::parse_hex(&self.bg_active) }
|
||||||
|
pub fn bg_search(&self) -> Color { Self::parse_hex(&self.bg_search) }
|
||||||
|
pub fn fg_normal(&self) -> Color { Self::parse_hex(&self.fg_normal) }
|
||||||
|
pub fn fg_dimmed(&self) -> Color { Self::parse_hex(&self.fg_dimmed) }
|
||||||
|
pub fn fg_highlight(&self) -> Color { Self::parse_hex(&self.fg_highlight) }
|
||||||
|
pub fn fg_warning(&self) -> Color { Self::parse_hex(&self.fg_warning) }
|
||||||
|
pub fn fg_modified(&self) -> Color { Self::parse_hex(&self.fg_modified) }
|
||||||
|
pub fn fg_accent(&self) -> Color { Self::parse_hex(&self.fg_accent) }
|
||||||
|
pub fn border_normal(&self) -> Color { Self::parse_hex(&self.border_normal) }
|
||||||
|
pub fn border_active(&self) -> Color { Self::parse_hex(&self.border_active) }
|
||||||
|
pub fn tree_depth_1(&self) -> Color { Self::parse_hex(&self.tree_depth_1) }
|
||||||
|
pub fn tree_depth_2(&self) -> Color { Self::parse_hex(&self.tree_depth_2) }
|
||||||
|
pub fn tree_depth_3(&self) -> Color { Self::parse_hex(&self.tree_depth_3) }
|
||||||
|
pub fn tree_depth_4(&self) -> Color { Self::parse_hex(&self.tree_depth_4) }
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for ThemeConfig {
|
impl Default for ThemeConfig {
|
||||||
|
/// Default theme: Semantic Catppuccin Mocha.
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
name: "catppuccin_mocha".to_string(),
|
transparent: false,
|
||||||
|
bg_normal: "#1e1e2e".to_string(), // base
|
||||||
|
bg_highlight: "#89b4fa".to_string(), // blue
|
||||||
|
bg_active: "#a6e3a1".to_string(), // green
|
||||||
|
bg_search: "#cba6f7".to_string(), // mauve
|
||||||
|
fg_normal: "#cdd6f4".to_string(), // text
|
||||||
|
fg_dimmed: "#6c7086".to_string(), // overlay0
|
||||||
|
fg_highlight: "#1e1e2e".to_string(), // base (dark for contrast against highlights)
|
||||||
|
fg_warning: "#f38ba8".to_string(), // red
|
||||||
|
fg_modified: "#fab387".to_string(), // peach
|
||||||
|
fg_accent: "#b4befe".to_string(), // lavender
|
||||||
|
border_normal: "#45475a".to_string(), // surface1
|
||||||
|
border_active: "#a6e3a1".to_string(), // green
|
||||||
|
tree_depth_1: "#b4befe".to_string(), // lavender
|
||||||
|
tree_depth_2: "#cba6f7".to_string(), // mauve
|
||||||
|
tree_depth_3: "#89b4fa".to_string(), // blue
|
||||||
|
tree_depth_4: "#fab387".to_string(), // peach
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Custom keybindings for navigation and application control.
|
||||||
|
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||||
|
#[serde(default)]
|
||||||
|
pub struct KeybindsConfig {
|
||||||
|
pub down: String,
|
||||||
|
pub up: String,
|
||||||
|
pub edit: String,
|
||||||
|
pub edit_append: String,
|
||||||
|
pub edit_substitute: String,
|
||||||
|
pub save: String,
|
||||||
|
pub quit: String,
|
||||||
|
pub normal_mode: String,
|
||||||
|
pub search: String,
|
||||||
|
pub next_match: String,
|
||||||
|
pub previous_match: String,
|
||||||
|
pub jump_top: String,
|
||||||
|
pub jump_bottom: String,
|
||||||
|
pub append_item: String,
|
||||||
|
pub prepend_item: String,
|
||||||
|
pub delete_item: String,
|
||||||
|
pub undo: String,
|
||||||
|
pub redo: String,
|
||||||
|
pub rename: String,
|
||||||
|
pub append_group: String,
|
||||||
|
pub prepend_group: String,
|
||||||
|
pub toggle_group: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for KeybindsConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
down: "j".to_string(),
|
||||||
|
up: "k".to_string(),
|
||||||
|
edit: "i".to_string(),
|
||||||
|
edit_append: "a".to_string(),
|
||||||
|
edit_substitute: "s".to_string(),
|
||||||
|
save: ":w".to_string(),
|
||||||
|
quit: ":q".to_string(),
|
||||||
|
normal_mode: "Esc".to_string(),
|
||||||
|
search: "/".to_string(),
|
||||||
|
next_match: "n".to_string(),
|
||||||
|
previous_match: "N".to_string(),
|
||||||
|
jump_top: "gg".to_string(),
|
||||||
|
jump_bottom: "G".to_string(),
|
||||||
|
append_item: "o".to_string(),
|
||||||
|
prepend_item: "O".to_string(),
|
||||||
|
delete_item: "dd".to_string(),
|
||||||
|
undo: "u".to_string(),
|
||||||
|
redo: "U".to_string(),
|
||||||
|
rename: "r".to_string(),
|
||||||
|
append_group: "alt+o".to_string(),
|
||||||
|
prepend_group: "alt+O".to_string(),
|
||||||
|
toggle_group: "t".to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Root configuration structure for mould.
|
||||||
#[derive(Debug, Deserialize, Serialize, Default, Clone)]
|
#[derive(Debug, Deserialize, Serialize, Default, Clone)]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub theme: ThemeConfig,
|
pub theme: ThemeConfig,
|
||||||
|
#[serde(default)]
|
||||||
|
pub keybinds: KeybindsConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Loads the configuration from the user's home config directory (~/.config/mould/config.toml).
|
||||||
|
/// Falls back to default settings if no configuration is found.
|
||||||
pub fn load_config() -> Config {
|
pub fn load_config() -> Config {
|
||||||
if let Some(mut config_dir) = dirs::config_dir() {
|
if let Some(mut config_dir) = dirs::config_dir() {
|
||||||
config_dir.push("cenv-rs");
|
config_dir.push("mould");
|
||||||
config_dir.push("config.toml");
|
config_dir.push("config.toml");
|
||||||
|
|
||||||
if config_dir.exists() {
|
if config_dir.exists()
|
||||||
if let Ok(content) = fs::read_to_string(config_dir) {
|
&& let Ok(content) = fs::read_to_string(config_dir)
|
||||||
if let Ok(config) = toml::from_str(&content) {
|
&& let Ok(config) = toml::from_str(&content) {
|
||||||
return config;
|
return config;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
Config::default()
|
Config::default()
|
||||||
}
|
}
|
||||||
|
|||||||
141
src/env.rs
141
src/env.rs
@@ -1,141 +0,0 @@
|
|||||||
use std::fs;
|
|
||||||
use std::io::{self, Write};
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct EnvVar {
|
|
||||||
pub key: String,
|
|
||||||
pub value: String,
|
|
||||||
pub default_value: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn parse_env_example<P: AsRef<Path>>(path: P) -> io::Result<Vec<EnvVar>> {
|
|
||||||
let content = fs::read_to_string(path)?;
|
|
||||||
let mut vars = Vec::new();
|
|
||||||
|
|
||||||
for line in content.lines() {
|
|
||||||
let line = line.trim();
|
|
||||||
if line.is_empty() || line.starts_with('#') {
|
|
||||||
continue; // Skip comments and empty lines
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some((key, val)) = line.split_once('=') {
|
|
||||||
let parsed_val = val.trim().trim_matches('"').trim_matches('\'').to_string();
|
|
||||||
vars.push(EnvVar {
|
|
||||||
key: key.trim().to_string(),
|
|
||||||
value: parsed_val.clone(),
|
|
||||||
default_value: parsed_val,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(vars)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn merge_env<P: AsRef<Path>>(path: P, vars: &mut Vec<EnvVar>) -> io::Result<()> {
|
|
||||||
if !path.as_ref().exists() {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
let content = fs::read_to_string(path)?;
|
|
||||||
for line in content.lines() {
|
|
||||||
let line = line.trim();
|
|
||||||
if line.is_empty() || line.starts_with('#') {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some((key, val)) = line.split_once('=') {
|
|
||||||
let key = key.trim();
|
|
||||||
let parsed_val = val.trim().trim_matches('"').trim_matches('\'').to_string();
|
|
||||||
|
|
||||||
if let Some(var) = vars.iter_mut().find(|v| v.key == key) {
|
|
||||||
var.value = parsed_val;
|
|
||||||
} else {
|
|
||||||
vars.push(EnvVar {
|
|
||||||
key: key.to_string(),
|
|
||||||
value: parsed_val.clone(),
|
|
||||||
default_value: String::new(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn write_env<P: AsRef<Path>>(path: P, vars: &[EnvVar]) -> io::Result<()> {
|
|
||||||
let mut file = fs::File::create(path)?;
|
|
||||||
for var in vars {
|
|
||||||
writeln!(file, "{}={}", var.key, var.value)?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use std::io::Write;
|
|
||||||
use tempfile::NamedTempFile;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_parse_env_example() {
|
|
||||||
let mut file = NamedTempFile::new().unwrap();
|
|
||||||
writeln!(
|
|
||||||
file,
|
|
||||||
"# A comment\nKEY1=value1\nKEY2=\"value2\"\nKEY3='value3'\nEMPTY="
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let vars = parse_env_example(file.path()).unwrap();
|
|
||||||
assert_eq!(vars.len(), 4);
|
|
||||||
assert_eq!(vars[0].key, "KEY1");
|
|
||||||
assert_eq!(vars[0].value, "value1");
|
|
||||||
assert_eq!(vars[0].default_value, "value1");
|
|
||||||
assert_eq!(vars[1].key, "KEY2");
|
|
||||||
assert_eq!(vars[1].value, "value2");
|
|
||||||
assert_eq!(vars[2].key, "KEY3");
|
|
||||||
assert_eq!(vars[2].value, "value3");
|
|
||||||
assert_eq!(vars[3].key, "EMPTY");
|
|
||||||
assert_eq!(vars[3].value, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_merge_env() {
|
|
||||||
let mut example_file = NamedTempFile::new().unwrap();
|
|
||||||
writeln!(example_file, "KEY1=default1\nKEY2=default2").unwrap();
|
|
||||||
let mut vars = parse_env_example(example_file.path()).unwrap();
|
|
||||||
|
|
||||||
let mut env_file = NamedTempFile::new().unwrap();
|
|
||||||
writeln!(env_file, "KEY1=custom1\nKEY3=custom3").unwrap();
|
|
||||||
|
|
||||||
merge_env(env_file.path(), &mut vars).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(vars.len(), 3);
|
|
||||||
assert_eq!(vars[0].key, "KEY1");
|
|
||||||
assert_eq!(vars[0].value, "custom1");
|
|
||||||
assert_eq!(vars[0].default_value, "default1");
|
|
||||||
|
|
||||||
assert_eq!(vars[1].key, "KEY2");
|
|
||||||
assert_eq!(vars[1].value, "default2");
|
|
||||||
assert_eq!(vars[1].default_value, "default2");
|
|
||||||
|
|
||||||
assert_eq!(vars[2].key, "KEY3");
|
|
||||||
assert_eq!(vars[2].value, "custom3");
|
|
||||||
assert_eq!(vars[2].default_value, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_write_env() {
|
|
||||||
let file = NamedTempFile::new().unwrap();
|
|
||||||
let vars = vec![EnvVar {
|
|
||||||
key: "KEY1".to_string(),
|
|
||||||
value: "value1".to_string(),
|
|
||||||
default_value: "def".to_string(),
|
|
||||||
}];
|
|
||||||
|
|
||||||
write_env(file.path(), &vars).unwrap();
|
|
||||||
|
|
||||||
let content = fs::read_to_string(file.path()).unwrap();
|
|
||||||
assert_eq!(content.trim(), "KEY1=value1");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
14
src/error.rs
Normal file
14
src/error.rs
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
use thiserror::Error;
|
||||||
|
|
||||||
|
/// Custom error types for the mould application.
|
||||||
|
#[derive(Error, Debug)]
|
||||||
|
pub enum MouldError {
|
||||||
|
#[error("IO error: {0}")]
|
||||||
|
Io(#[from] std::io::Error),
|
||||||
|
|
||||||
|
#[error("File not found: {0}")]
|
||||||
|
FileNotFound(String),
|
||||||
|
|
||||||
|
#[error("Terminal error: {0}")]
|
||||||
|
Terminal(String),
|
||||||
|
}
|
||||||
136
src/format/env.rs
Normal file
136
src/format/env.rs
Normal file
@@ -0,0 +1,136 @@
|
|||||||
|
use super::{ConfigItem, FormatHandler, ItemStatus, ValueType, PathSegment};
|
||||||
|
use std::fs;
|
||||||
|
use std::io::Write;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
pub struct EnvHandler;
|
||||||
|
|
||||||
|
impl FormatHandler for EnvHandler {
|
||||||
|
fn parse(&self, path: &Path) -> anyhow::Result<Vec<ConfigItem>> {
|
||||||
|
let content = fs::read_to_string(path)?;
|
||||||
|
let mut vars = Vec::new();
|
||||||
|
|
||||||
|
for line in content.lines() {
|
||||||
|
let line = line.trim();
|
||||||
|
if line.is_empty() || line.starts_with('#') {
|
||||||
|
continue; // Skip comments and empty lines
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some((key, val)) = line.split_once('=') {
|
||||||
|
let parsed_val = val.trim().trim_matches('"').trim_matches('\'').to_string();
|
||||||
|
let key_str = key.trim().to_string();
|
||||||
|
vars.push(ConfigItem {
|
||||||
|
key: key_str.clone(),
|
||||||
|
path: vec![PathSegment::Key(key_str)],
|
||||||
|
value: Some(parsed_val.clone()),
|
||||||
|
template_value: Some(parsed_val.clone()),
|
||||||
|
default_value: Some(parsed_val),
|
||||||
|
depth: 0,
|
||||||
|
is_group: false,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: ValueType::String,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(vars)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write(&self, path: &Path, vars: &[ConfigItem]) -> anyhow::Result<()> {
|
||||||
|
let mut file = fs::File::create(path)?;
|
||||||
|
for var in vars {
|
||||||
|
if !var.is_group {
|
||||||
|
let val = var.value.as_deref()
|
||||||
|
.or(var.template_value.as_deref())
|
||||||
|
.unwrap_or("");
|
||||||
|
writeln!(file, "{}={}", var.key, val)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::io::Write;
|
||||||
|
use tempfile::NamedTempFile;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_env_example() {
|
||||||
|
let mut file = NamedTempFile::new().unwrap();
|
||||||
|
writeln!(
|
||||||
|
file,
|
||||||
|
"# A comment\nKEY1=value1\nKEY2=\"value2\"\nKEY3='value3'\nEMPTY="
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let handler = EnvHandler;
|
||||||
|
let vars = handler.parse(file.path()).unwrap();
|
||||||
|
assert_eq!(vars.len(), 4);
|
||||||
|
assert_eq!(vars[0].key, "KEY1");
|
||||||
|
assert_eq!(vars[0].value.as_deref(), Some("value1"));
|
||||||
|
assert_eq!(vars[1].key, "KEY2");
|
||||||
|
assert_eq!(vars[1].value.as_deref(), Some("value2"));
|
||||||
|
assert_eq!(vars[2].key, "KEY3");
|
||||||
|
assert_eq!(vars[2].value.as_deref(), Some("value3"));
|
||||||
|
assert_eq!(vars[3].key, "EMPTY");
|
||||||
|
assert_eq!(vars[3].value.as_deref(), Some(""));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_merge_env() {
|
||||||
|
let handler = EnvHandler;
|
||||||
|
|
||||||
|
let mut env_file = NamedTempFile::new().unwrap();
|
||||||
|
writeln!(env_file, "KEY1=custom1\nKEY3=custom3").unwrap();
|
||||||
|
let mut vars = handler.parse(env_file.path()).unwrap(); // Active vars
|
||||||
|
|
||||||
|
let mut example_file = NamedTempFile::new().unwrap();
|
||||||
|
writeln!(example_file, "KEY1=default1\nKEY2=default2").unwrap();
|
||||||
|
|
||||||
|
handler.merge(example_file.path(), &mut vars).unwrap(); // Merge template into active
|
||||||
|
|
||||||
|
// Should preserve order of active, then append template
|
||||||
|
assert_eq!(vars.len(), 3);
|
||||||
|
|
||||||
|
// Active key that exists in template
|
||||||
|
assert_eq!(vars[0].key, "KEY1");
|
||||||
|
assert_eq!(vars[0].value.as_deref(), Some("custom1")); // Keeps active value
|
||||||
|
assert_eq!(vars[0].template_value.as_deref(), Some("default1")); // Gets template default
|
||||||
|
assert_eq!(vars[0].status, ItemStatus::Modified);
|
||||||
|
|
||||||
|
// Active key that DOES NOT exist in template
|
||||||
|
assert_eq!(vars[1].key, "KEY3");
|
||||||
|
assert_eq!(vars[1].value.as_deref(), Some("custom3"));
|
||||||
|
assert_eq!(vars[1].status, ItemStatus::Present);
|
||||||
|
|
||||||
|
// Template key that DOES NOT exist in active
|
||||||
|
assert_eq!(vars[2].key, "KEY2");
|
||||||
|
assert_eq!(vars[2].value.as_deref(), None); // Missing from active
|
||||||
|
assert_eq!(vars[2].template_value.as_deref(), Some("default2"));
|
||||||
|
assert_eq!(vars[2].status, ItemStatus::MissingFromActive);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_write_env() {
|
||||||
|
let file = NamedTempFile::new().unwrap();
|
||||||
|
let vars = vec![ConfigItem {
|
||||||
|
key: "KEY1".to_string(),
|
||||||
|
path: vec![PathSegment::Key("KEY1".to_string())],
|
||||||
|
value: Some("value1".to_string()),
|
||||||
|
template_value: None,
|
||||||
|
default_value: None,
|
||||||
|
depth: 0,
|
||||||
|
is_group: false,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: ValueType::String,
|
||||||
|
}];
|
||||||
|
|
||||||
|
let handler = EnvHandler;
|
||||||
|
handler.write(file.path(), &vars).unwrap();
|
||||||
|
|
||||||
|
let content = fs::read_to_string(file.path()).unwrap();
|
||||||
|
assert_eq!(content.trim(), "KEY1=value1");
|
||||||
|
}
|
||||||
|
}
|
||||||
618
src/format/hierarchical.rs
Normal file
618
src/format/hierarchical.rs
Normal file
@@ -0,0 +1,618 @@
|
|||||||
|
use super::{ConfigItem, FormatHandler, FormatType, ItemStatus, ValueType, PathSegment};
|
||||||
|
use serde_json::{Map, Value};
|
||||||
|
use std::fs;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
pub struct HierarchicalHandler {
|
||||||
|
format_type: FormatType,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HierarchicalHandler {
|
||||||
|
pub fn new(format_type: FormatType) -> Self {
|
||||||
|
Self { format_type }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_value(&self, path: &Path) -> anyhow::Result<Value> {
|
||||||
|
let content = fs::read_to_string(path)?;
|
||||||
|
let value = match self.format_type {
|
||||||
|
FormatType::Json => serde_json::from_str(&content)?,
|
||||||
|
FormatType::Yaml => serde_yaml::from_str(&content)?,
|
||||||
|
FormatType::Toml => toml::from_str(&content)?,
|
||||||
|
FormatType::Xml => xml_to_json(&content)?,
|
||||||
|
_ => unreachable!(),
|
||||||
|
};
|
||||||
|
Ok(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_value(&self, path: &Path, value: &Value) -> anyhow::Result<()> {
|
||||||
|
let content = match self.format_type {
|
||||||
|
FormatType::Json => serde_json::to_string_pretty(value)?,
|
||||||
|
FormatType::Yaml => serde_yaml::to_string(value)?,
|
||||||
|
FormatType::Toml => {
|
||||||
|
// toml requires the root to be a table
|
||||||
|
if value.is_object() {
|
||||||
|
let toml_value: toml::Value = serde_json::from_value(value.clone())?;
|
||||||
|
toml::to_string_pretty(&toml_value)?
|
||||||
|
} else {
|
||||||
|
anyhow::bail!("Root of TOML must be an object");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
FormatType::Xml => json_to_xml(value),
|
||||||
|
_ => unreachable!(),
|
||||||
|
};
|
||||||
|
fs::write(path, content)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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();
|
||||||
|
|
||||||
|
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 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() {
|
||||||
|
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()))
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
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 {
|
||||||
|
Value::Object(map) => {
|
||||||
|
if let Some(k) = key_name {
|
||||||
|
writer.write_event(Event::Start(BytesStart::new(k))).unwrap();
|
||||||
|
}
|
||||||
|
for (k, v) in map {
|
||||||
|
if let Some(arr) = v.as_array() {
|
||||||
|
for item in arr {
|
||||||
|
write_recursive(writer, item, Some(k));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
write_recursive(writer, v, Some(k));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(k) = key_name {
|
||||||
|
writer.write_event(Event::End(BytesEnd::new(k))).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Value::Array(arr) => {
|
||||||
|
for v in arr {
|
||||||
|
write_recursive(writer, v, key_name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Value::String(s) => {
|
||||||
|
if let Some(k) = key_name {
|
||||||
|
writer.write_event(Event::Start(BytesStart::new(k))).unwrap();
|
||||||
|
}
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Quick-XML adds a trailing newline occasionally, or we might need one
|
||||||
|
let mut out = String::from_utf8(writer.into_inner()).unwrap();
|
||||||
|
if !out.ends_with('\n') {
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
key: display_key,
|
||||||
|
path: next_path.clone(),
|
||||||
|
value: None,
|
||||||
|
template_value: None,
|
||||||
|
default_value: None,
|
||||||
|
depth,
|
||||||
|
is_group: true,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: ValueType::Null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let next_depth = if 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 {
|
||||||
|
key: display_key,
|
||||||
|
path: next_path.clone(),
|
||||||
|
value: None,
|
||||||
|
template_value: None,
|
||||||
|
default_value: None,
|
||||||
|
depth,
|
||||||
|
is_group: true,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: ValueType::Null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let next_depth = if 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 {
|
||||||
|
key: display_key,
|
||||||
|
path: next_path.clone(),
|
||||||
|
value: Some(s.clone()),
|
||||||
|
template_value: Some(s.clone()),
|
||||||
|
default_value: Some(s.clone()),
|
||||||
|
depth,
|
||||||
|
is_group: false,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: ValueType::String,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Value::Number(n) => {
|
||||||
|
let s = n.to_string();
|
||||||
|
vars.push(ConfigItem {
|
||||||
|
key: display_key,
|
||||||
|
path: next_path.clone(),
|
||||||
|
value: Some(s.clone()),
|
||||||
|
template_value: Some(s.clone()),
|
||||||
|
default_value: Some(s.clone()),
|
||||||
|
depth,
|
||||||
|
is_group: false,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: ValueType::Number,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Value::Bool(b) => {
|
||||||
|
let s = b.to_string();
|
||||||
|
vars.push(ConfigItem {
|
||||||
|
key: display_key,
|
||||||
|
path: next_path.clone(),
|
||||||
|
value: Some(s.clone()),
|
||||||
|
template_value: Some(s.clone()),
|
||||||
|
default_value: Some(s.clone()),
|
||||||
|
depth,
|
||||||
|
is_group: false,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: ValueType::Bool,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Value::Null => {
|
||||||
|
vars.push(ConfigItem {
|
||||||
|
key: display_key,
|
||||||
|
path: next_path.clone(),
|
||||||
|
value: Some("".to_string()),
|
||||||
|
template_value: Some("".to_string()),
|
||||||
|
default_value: Some("".to_string()),
|
||||||
|
depth,
|
||||||
|
is_group: false,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: ValueType::Null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FormatHandler for HierarchicalHandler {
|
||||||
|
fn parse(&self, path: &Path) -> anyhow::Result<Vec<ConfigItem>> {
|
||||||
|
let value = self.read_value(path)?;
|
||||||
|
let mut vars = Vec::new();
|
||||||
|
flatten(&value, Vec::new(), Some("".to_string()), 0, &mut vars);
|
||||||
|
Ok(vars)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write(&self, path: &Path, vars: &[ConfigItem]) -> anyhow::Result<()> {
|
||||||
|
let mut root = Value::Object(Map::new());
|
||||||
|
for var in vars {
|
||||||
|
if !var.is_group {
|
||||||
|
let val = var.value.as_deref()
|
||||||
|
.or(var.template_value.as_deref())
|
||||||
|
.unwrap_or("");
|
||||||
|
insert_into_value(&mut root, &var.path, val, var.value_type);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.write_value(path, &root)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn insert_into_value(root: &mut Value, path: &[PathSegment], new_val_str: &str, value_type: ValueType) {
|
||||||
|
if path.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut current = root;
|
||||||
|
|
||||||
|
// Traverse all but the last segment
|
||||||
|
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() {
|
||||||
|
*current = Value::Object(Map::new());
|
||||||
|
}
|
||||||
|
let map = current.as_object_mut().unwrap();
|
||||||
|
|
||||||
|
let next_node = map.entry(key.clone()).or_insert_with(|| {
|
||||||
|
match next_segment {
|
||||||
|
PathSegment::Index(_) => Value::Array(Vec::new()),
|
||||||
|
PathSegment::Key(_) => Value::Object(Map::new()),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
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];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle the final segment
|
||||||
|
let final_segment = &path[path.len() - 1];
|
||||||
|
|
||||||
|
let final_val = match value_type {
|
||||||
|
ValueType::Number => {
|
||||||
|
if let Ok(n) = new_val_str.parse::<i64>() {
|
||||||
|
Value::Number(n.into())
|
||||||
|
} else if let Ok(f) = new_val_str.parse::<f64>() {
|
||||||
|
if let Some(n) = serde_json::Number::from_f64(f) {
|
||||||
|
Value::Number(n)
|
||||||
|
} else {
|
||||||
|
Value::String(new_val_str.to_string())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Value::String(new_val_str.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ValueType::Bool => {
|
||||||
|
if let Ok(b) = new_val_str.parse::<bool>() {
|
||||||
|
Value::Bool(b)
|
||||||
|
} else {
|
||||||
|
Value::String(new_val_str.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ValueType::Null if new_val_str.is_empty() => Value::Null,
|
||||||
|
_ => Value::String(new_val_str.to_string()),
|
||||||
|
};
|
||||||
|
|
||||||
|
match final_segment {
|
||||||
|
PathSegment::Key(key) => {
|
||||||
|
if !current.is_object() {
|
||||||
|
*current = Value::Object(Map::new());
|
||||||
|
}
|
||||||
|
let map = current.as_object_mut().unwrap();
|
||||||
|
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[*idx] = final_val;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_json_flatten_unflatten() {
|
||||||
|
let mut vars = Vec::new();
|
||||||
|
let json = serde_json::json!({
|
||||||
|
"services": {
|
||||||
|
"web": {
|
||||||
|
"ports": ["8080:80"],
|
||||||
|
"environment": {
|
||||||
|
"DEBUG": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
flatten(&json, Vec::new(), Some("".to_string()), 0, &mut vars);
|
||||||
|
assert_eq!(vars.len(), 6);
|
||||||
|
|
||||||
|
let mut root = Value::Object(Map::new());
|
||||||
|
for var in vars {
|
||||||
|
if !var.is_group {
|
||||||
|
insert_into_value(&mut root, &var.path, var.value.as_deref().unwrap_or(""), var.value_type);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let unflattened_json = serde_json::to_string(&root).unwrap();
|
||||||
|
assert!(unflattened_json.contains("\"8080:80\""));
|
||||||
|
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_eq!(vars[0].is_group, true);
|
||||||
|
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"
|
||||||
|
let old_path = vars[0].path.clone();
|
||||||
|
let new_key = "new_group".to_string();
|
||||||
|
let mut new_path = vec![PathSegment::Key(new_key.clone())];
|
||||||
|
|
||||||
|
vars[0].key = new_key;
|
||||||
|
vars[0].path = new_path.clone();
|
||||||
|
|
||||||
|
// Update child path
|
||||||
|
vars[1].path = vec![PathSegment::Key("new_group".to_string()), PathSegment::Key("key".to_string())];
|
||||||
|
|
||||||
|
let handler = HierarchicalHandler::new(FormatType::Json);
|
||||||
|
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\""));
|
||||||
|
}
|
||||||
|
}
|
||||||
125
src/format/ini.rs
Normal file
125
src/format/ini.rs
Normal file
@@ -0,0 +1,125 @@
|
|||||||
|
use super::{ConfigItem, FormatHandler, ItemStatus, 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 {
|
||||||
|
key: section_name.to_string(),
|
||||||
|
path: vec![PathSegment::Key(section_name.to_string())],
|
||||||
|
value: None,
|
||||||
|
template_value: None,
|
||||||
|
default_value: None,
|
||||||
|
depth: 0,
|
||||||
|
is_group: true,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: ValueType::Null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
key: key.to_string(),
|
||||||
|
path,
|
||||||
|
value: Some(value.to_string()),
|
||||||
|
template_value: Some(value.to_string()),
|
||||||
|
default_value: Some(value.to_string()),
|
||||||
|
depth: if section_name.is_empty() { 0 } else { 1 },
|
||||||
|
is_group: false,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: ValueType::String,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(vars)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write(&self, path: &Path, vars: &[ConfigItem]) -> anyhow::Result<()> {
|
||||||
|
let mut conf = Ini::new();
|
||||||
|
for var in vars {
|
||||||
|
if !var.is_group {
|
||||||
|
let val = var.value.as_deref()
|
||||||
|
.or(var.template_value.as_deref())
|
||||||
|
.unwrap_or("");
|
||||||
|
|
||||||
|
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;
|
||||||
|
use std::io::Write;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_section_rename_write() {
|
||||||
|
let handler = IniHandler;
|
||||||
|
let mut vars = vec![
|
||||||
|
ConfigItem {
|
||||||
|
key: "server".to_string(),
|
||||||
|
path: vec![PathSegment::Key("server".to_string())],
|
||||||
|
value: None,
|
||||||
|
template_value: None,
|
||||||
|
default_value: None,
|
||||||
|
depth: 0,
|
||||||
|
is_group: true,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: ValueType::Null,
|
||||||
|
},
|
||||||
|
ConfigItem {
|
||||||
|
key: "port".to_string(),
|
||||||
|
path: vec![PathSegment::Key("server".to_string()), PathSegment::Key("port".to_string())],
|
||||||
|
value: Some("8080".to_string()),
|
||||||
|
template_value: Some("8080".to_string()),
|
||||||
|
default_value: Some("8080".to_string()),
|
||||||
|
depth: 1,
|
||||||
|
is_group: false,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: 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]"));
|
||||||
|
}
|
||||||
|
}
|
||||||
157
src/format/mod.rs
Normal file
157
src/format/mod.rs
Normal file
@@ -0,0 +1,157 @@
|
|||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
pub mod env;
|
||||||
|
pub mod hierarchical;
|
||||||
|
pub mod ini;
|
||||||
|
pub mod properties;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum ItemStatus {
|
||||||
|
Present,
|
||||||
|
MissingFromActive,
|
||||||
|
Modified,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum ValueType {
|
||||||
|
String,
|
||||||
|
Number,
|
||||||
|
Bool,
|
||||||
|
Null,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
|
pub enum PathSegment {
|
||||||
|
Key(String),
|
||||||
|
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),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ConfigItem {
|
||||||
|
pub key: String,
|
||||||
|
pub path: Vec<PathSegment>,
|
||||||
|
pub value: Option<String>,
|
||||||
|
pub template_value: Option<String>,
|
||||||
|
pub default_value: Option<String>,
|
||||||
|
pub depth: usize,
|
||||||
|
pub is_group: bool,
|
||||||
|
pub status: ItemStatus,
|
||||||
|
pub value_type: ValueType,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ConfigItem {
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum FormatType {
|
||||||
|
Env,
|
||||||
|
Json,
|
||||||
|
Yaml,
|
||||||
|
Toml,
|
||||||
|
Xml,
|
||||||
|
Ini,
|
||||||
|
Properties,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait FormatHandler {
|
||||||
|
fn parse(&self, path: &Path) -> anyhow::Result<Vec<ConfigItem>>;
|
||||||
|
fn merge(&self, path: &Path, vars: &mut Vec<ConfigItem>) -> anyhow::Result<()> {
|
||||||
|
if !path.exists() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let template_vars = self.parse(path).unwrap_or_default();
|
||||||
|
|
||||||
|
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();
|
||||||
|
|
||||||
|
if var.value != template_var.value {
|
||||||
|
var.status = ItemStatus::Modified;
|
||||||
|
} else {
|
||||||
|
var.status = ItemStatus::Present;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Exists in active, but not in template
|
||||||
|
var.status = ItemStatus::Present;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add items from template that are missing in active
|
||||||
|
for template_var in template_vars {
|
||||||
|
if !vars.iter().any(|v| v.path == template_var.path) {
|
||||||
|
let mut new_item = template_var.clone();
|
||||||
|
new_item.status = ItemStatus::MissingFromActive;
|
||||||
|
new_item.value = None;
|
||||||
|
vars.push(new_item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn write(&self, path: &Path, vars: &[ConfigItem]) -> anyhow::Result<()>;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn detect_format(path: &Path, override_format: Option<String>) -> FormatType {
|
||||||
|
if let Some(fmt) = override_format {
|
||||||
|
match fmt.to_lowercase().as_str() {
|
||||||
|
"env" => return FormatType::Env,
|
||||||
|
"json" => return FormatType::Json,
|
||||||
|
"yaml" | "yml" => return FormatType::Yaml,
|
||||||
|
"toml" => return FormatType::Toml,
|
||||||
|
"xml" => return FormatType::Xml,
|
||||||
|
"ini" => return FormatType::Ini,
|
||||||
|
"properties" => return FormatType::Properties,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let ext = path.extension().and_then(|s| s.to_str()).unwrap_or_default();
|
||||||
|
match ext {
|
||||||
|
"json" => FormatType::Json,
|
||||||
|
"yaml" | "yml" => FormatType::Yaml,
|
||||||
|
"toml" => FormatType::Toml,
|
||||||
|
"xml" => FormatType::Xml,
|
||||||
|
"ini" => FormatType::Ini,
|
||||||
|
"properties" => FormatType::Properties,
|
||||||
|
_ => FormatType::Env,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_handler(format: FormatType) -> Box<dyn FormatHandler> {
|
||||||
|
match format {
|
||||||
|
FormatType::Env => Box::new(env::EnvHandler),
|
||||||
|
FormatType::Json => Box::new(hierarchical::HierarchicalHandler::new(FormatType::Json)),
|
||||||
|
FormatType::Yaml => Box::new(hierarchical::HierarchicalHandler::new(FormatType::Yaml)),
|
||||||
|
FormatType::Toml => Box::new(hierarchical::HierarchicalHandler::new(FormatType::Toml)),
|
||||||
|
FormatType::Xml => Box::new(hierarchical::HierarchicalHandler::new(FormatType::Xml)),
|
||||||
|
FormatType::Ini => Box::new(ini::IniHandler),
|
||||||
|
FormatType::Properties => Box::new(properties::PropertiesHandler),
|
||||||
|
}
|
||||||
|
}
|
||||||
133
src/format/properties.rs
Normal file
133
src/format/properties.rs
Normal file
@@ -0,0 +1,133 @@
|
|||||||
|
use super::{ConfigItem, FormatHandler, ItemStatus, 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 {
|
||||||
|
key: part.to_string(),
|
||||||
|
path: current_path.clone(),
|
||||||
|
value: None,
|
||||||
|
template_value: None,
|
||||||
|
default_value: None,
|
||||||
|
depth: i,
|
||||||
|
is_group: true,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: ValueType::Null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
key: last_key,
|
||||||
|
path: final_path,
|
||||||
|
value: Some(value.clone()),
|
||||||
|
template_value: Some(value.clone()),
|
||||||
|
default_value: Some(value.clone()),
|
||||||
|
depth: parts.len().saturating_sub(1),
|
||||||
|
is_group: false,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: ValueType::String,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// We don't sort here to preserve the original file order!
|
||||||
|
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.is_group {
|
||||||
|
let val = var.value.as_deref()
|
||||||
|
.or(var.template_value.as_deref())
|
||||||
|
.unwrap_or("");
|
||||||
|
prop_writer.write(&var.path_string(), val)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
prop_writer.finish()?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use tempfile::NamedTempFile;
|
||||||
|
use std::io::Write;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_group_rename_write() {
|
||||||
|
let handler = PropertiesHandler;
|
||||||
|
let mut vars = vec![
|
||||||
|
ConfigItem {
|
||||||
|
key: "server".to_string(),
|
||||||
|
path: vec![PathSegment::Key("server".to_string())],
|
||||||
|
value: None,
|
||||||
|
template_value: None,
|
||||||
|
default_value: None,
|
||||||
|
depth: 0,
|
||||||
|
is_group: true,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: ValueType::Null,
|
||||||
|
},
|
||||||
|
ConfigItem {
|
||||||
|
key: "port".to_string(),
|
||||||
|
path: vec![PathSegment::Key("server".to_string()), PathSegment::Key("port".to_string())],
|
||||||
|
value: Some("8080".to_string()),
|
||||||
|
template_value: Some("8080".to_string()),
|
||||||
|
default_value: Some("8080".to_string()),
|
||||||
|
depth: 1,
|
||||||
|
is_group: false,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: 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"));
|
||||||
|
}
|
||||||
|
}
|
||||||
258
src/main.rs
258
src/main.rs
@@ -1,171 +1,149 @@
|
|||||||
mod app;
|
mod app;
|
||||||
|
mod cli;
|
||||||
mod config;
|
mod config;
|
||||||
mod env;
|
mod error;
|
||||||
|
mod format;
|
||||||
|
mod runner;
|
||||||
mod ui;
|
mod ui;
|
||||||
|
mod resolver;
|
||||||
|
mod undo;
|
||||||
|
|
||||||
use app::{App, Mode};
|
use app::App;
|
||||||
use config::load_config;
|
use config::load_config;
|
||||||
use env::{merge_env, parse_env_example, write_env};
|
use error::MouldError;
|
||||||
use std::error::Error;
|
use format::{detect_format, get_handler};
|
||||||
|
use log::{error, info, warn};
|
||||||
|
use runner::AppRunner;
|
||||||
use std::io;
|
use std::io;
|
||||||
|
|
||||||
use crossterm::{
|
use crossterm::{
|
||||||
event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode},
|
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::{
|
use ratatui::{Terminal, backend::CrosstermBackend};
|
||||||
Terminal,
|
|
||||||
backend::{Backend, CrosstermBackend},
|
|
||||||
};
|
|
||||||
|
|
||||||
fn main() -> Result<(), Box<dyn Error>> {
|
fn main() -> anyhow::Result<()> {
|
||||||
let example_path = ".env.example";
|
let args = cli::parse();
|
||||||
let env_path = ".env";
|
|
||||||
|
|
||||||
// Load vars
|
// Initialize logger with verbosity from CLI
|
||||||
let mut vars = parse_env_example(example_path).unwrap_or_else(|_| vec![]);
|
let log_level = match args.verbose {
|
||||||
|
0 => log::LevelFilter::Warn,
|
||||||
|
1 => log::LevelFilter::Info,
|
||||||
|
_ => log::LevelFilter::Debug,
|
||||||
|
};
|
||||||
|
env_logger::Builder::new()
|
||||||
|
.filter_level(log_level)
|
||||||
|
.format_timestamp(None)
|
||||||
|
.init();
|
||||||
|
|
||||||
|
let input_path = match args.input {
|
||||||
|
Some(path) => {
|
||||||
|
if !path.exists() {
|
||||||
|
error!("Input file not found: {}", path.display());
|
||||||
|
return Err(MouldError::FileNotFound(path.display().to_string()).into());
|
||||||
|
}
|
||||||
|
path
|
||||||
|
}
|
||||||
|
None => match resolver::find_input_file() {
|
||||||
|
Some(path) => {
|
||||||
|
info!("Discovered template: {}", path.display());
|
||||||
|
path
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
error!("No template file provided and none discovered in current directory.");
|
||||||
|
println!("Usage: mould <INPUT_FILE>");
|
||||||
|
println!("Supported defaults: .env.example, compose.yml, docker-compose.yml, etc.");
|
||||||
|
return Err(MouldError::FileNotFound("None".to_string()).into());
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
info!("Input: {}", input_path.display());
|
||||||
|
|
||||||
|
let format_type = detect_format(&input_path, args.format);
|
||||||
|
let handler = get_handler(format_type);
|
||||||
|
|
||||||
|
// Smart Comparison Logic
|
||||||
|
let (active_path, template_path) = resolver::resolve_paths(&input_path);
|
||||||
|
|
||||||
|
let output_path = args
|
||||||
|
.output
|
||||||
|
.unwrap_or_else(|| active_path.clone().unwrap_or_else(|| resolver::determine_output_path(&input_path)));
|
||||||
|
|
||||||
|
info!("Output: {}", output_path.display());
|
||||||
|
|
||||||
|
// 1. Load active config if it exists
|
||||||
|
let mut vars = if let Some(active) = &active_path {
|
||||||
|
handler.parse(active).unwrap_or_default()
|
||||||
|
} else {
|
||||||
|
Vec::new()
|
||||||
|
};
|
||||||
|
|
||||||
|
// 2. Load template config and merge
|
||||||
|
if let Some(template) = &template_path {
|
||||||
|
info!("Comparing with template: {}", template.display());
|
||||||
|
let template_vars = handler.parse(template).unwrap_or_default();
|
||||||
if vars.is_empty() {
|
if vars.is_empty() {
|
||||||
println!("No variables found in .env.example or file does not exist.");
|
vars = template_vars;
|
||||||
println!("Please run this tool in a directory with a valid .env.example file.");
|
// If we only have template, everything is missing from active initially
|
||||||
return Ok(());
|
for v in vars.iter_mut() {
|
||||||
|
v.status = crate::format::ItemStatus::MissingFromActive;
|
||||||
|
v.value = None;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Merge template into active
|
||||||
|
handler.merge(template, &mut vars).unwrap_or_default();
|
||||||
|
}
|
||||||
|
} else if vars.is_empty() {
|
||||||
|
// Fallback if no template and active is empty
|
||||||
|
vars = handler.parse(&input_path)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Merge existing .env if present
|
if vars.is_empty() {
|
||||||
let _ = merge_env(env_path, &mut vars);
|
warn!("No variables found.");
|
||||||
|
}
|
||||||
|
|
||||||
let config = load_config();
|
let config = load_config();
|
||||||
let mut app = App::new(vars);
|
let mut app = App::new(vars);
|
||||||
|
|
||||||
// Setup terminal
|
// Terminal lifecycle
|
||||||
enable_raw_mode()?;
|
enable_raw_mode()
|
||||||
|
.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, EnableMouseCapture)
|
||||||
|
.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)))?;
|
||||||
|
|
||||||
// Run app
|
let mut runner = AppRunner::new(
|
||||||
let res = run_app(&mut terminal, &mut app, &config, env_path);
|
&mut terminal,
|
||||||
|
&mut app,
|
||||||
|
&config,
|
||||||
|
&output_path,
|
||||||
|
handler.as_ref(),
|
||||||
|
);
|
||||||
|
let res = runner.run();
|
||||||
|
|
||||||
// Restore terminal
|
// Restoration
|
||||||
disable_raw_mode()?;
|
disable_raw_mode().ok();
|
||||||
execute!(
|
execute!(
|
||||||
terminal.backend_mut(),
|
terminal.backend_mut(),
|
||||||
LeaveAlternateScreen,
|
LeaveAlternateScreen,
|
||||||
DisableMouseCapture
|
DisableMouseCapture
|
||||||
)?;
|
)
|
||||||
terminal.show_cursor()?;
|
.ok();
|
||||||
|
terminal.show_cursor().ok();
|
||||||
if let Err(err) = res {
|
|
||||||
println!("{:?}", err);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
match res {
|
||||||
|
Ok(_) => {
|
||||||
|
info!("Successfully finished mould session.");
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
Err(e) => {
|
||||||
fn run_app<B: Backend>(
|
error!("Application error during run: {}", e);
|
||||||
terminal: &mut Terminal<B>,
|
Err(e.into())
|
||||||
app: &mut App,
|
}
|
||||||
config: &config::Config,
|
}
|
||||||
env_path: &str,
|
|
||||||
) -> io::Result<()>
|
|
||||||
where
|
|
||||||
io::Error: From<B::Error>,
|
|
||||||
{
|
|
||||||
// For handling commands like :w, :q
|
|
||||||
let mut command_buffer = String::new();
|
|
||||||
|
|
||||||
loop {
|
|
||||||
terminal.draw(|f| ui::draw(f, app, config))?;
|
|
||||||
|
|
||||||
if let Event::Key(key) = event::read()? {
|
|
||||||
match app.mode {
|
|
||||||
Mode::Normal => {
|
|
||||||
if !command_buffer.is_empty() {
|
|
||||||
if key.code == KeyCode::Enter {
|
|
||||||
match command_buffer.as_str() {
|
|
||||||
":w" => {
|
|
||||||
if write_env(env_path, &app.vars).is_ok() {
|
|
||||||
app.status_message = Some("Saved to .env".to_string());
|
|
||||||
} else {
|
|
||||||
app.status_message =
|
|
||||||
Some("Error saving to .env".to_string());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
":q" => return Ok(()),
|
|
||||||
":wq" => {
|
|
||||||
write_env(env_path, &app.vars)?;
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
app.status_message = Some("Unknown command".to_string());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
command_buffer.clear();
|
|
||||||
} else if key.code == KeyCode::Esc {
|
|
||||||
command_buffer.clear();
|
|
||||||
app.status_message = None;
|
|
||||||
} else if key.code == KeyCode::Backspace {
|
|
||||||
command_buffer.pop();
|
|
||||||
if command_buffer.is_empty() {
|
|
||||||
app.status_message = None;
|
|
||||||
} else {
|
|
||||||
app.status_message = Some(command_buffer.clone());
|
|
||||||
}
|
|
||||||
} else if let KeyCode::Char(c) = key.code {
|
|
||||||
command_buffer.push(c);
|
|
||||||
app.status_message = Some(command_buffer.clone());
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
match key.code {
|
|
||||||
KeyCode::Char('q') => return Ok(()),
|
|
||||||
KeyCode::Char('j') | KeyCode::Down => app.next(),
|
|
||||||
KeyCode::Char('k') | KeyCode::Up => app.previous(),
|
|
||||||
KeyCode::Char('i') => {
|
|
||||||
app.enter_insert();
|
|
||||||
app.status_message = None;
|
|
||||||
}
|
|
||||||
KeyCode::Char(':') => {
|
|
||||||
command_buffer.push(':');
|
|
||||||
app.status_message = Some(command_buffer.clone());
|
|
||||||
}
|
|
||||||
KeyCode::Enter => {
|
|
||||||
// Default action for Enter in Normal mode is save
|
|
||||||
if write_env(env_path, &app.vars).is_ok() {
|
|
||||||
app.status_message = Some("Saved to .env".to_string());
|
|
||||||
} else {
|
|
||||||
app.status_message = Some("Error saving to .env".to_string());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Mode::Insert => match key.code {
|
|
||||||
KeyCode::Esc => {
|
|
||||||
app.enter_normal();
|
|
||||||
}
|
|
||||||
KeyCode::Char(c) => {
|
|
||||||
if let Some(var) = app.vars.get_mut(app.selected) {
|
|
||||||
var.value.push(c);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
KeyCode::Backspace => {
|
|
||||||
if let Some(var) = app.vars.get_mut(app.selected) {
|
|
||||||
var.value.pop();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
KeyCode::Enter => {
|
|
||||||
app.enter_normal();
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !app.running {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
197
src/resolver.rs
Normal file
197
src/resolver.rs
Normal file
@@ -0,0 +1,197 @@
|
|||||||
|
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"));
|
||||||
|
}
|
||||||
|
}
|
||||||
339
src/runner.rs
Normal file
339
src/runner.rs
Normal file
@@ -0,0 +1,339 @@
|
|||||||
|
use crate::app::{App, InsertVariant, Mode};
|
||||||
|
use crate::config::Config;
|
||||||
|
use crate::format::FormatHandler;
|
||||||
|
use crossterm::event::{self, Event, KeyCode, KeyEvent};
|
||||||
|
use ratatui::Terminal;
|
||||||
|
use ratatui::backend::Backend;
|
||||||
|
use std::io;
|
||||||
|
use std::path::Path;
|
||||||
|
use tui_input::backend::crossterm::EventHandler;
|
||||||
|
|
||||||
|
/// Manages the main application execution loop, event handling, and terminal interaction.
|
||||||
|
pub struct AppRunner<'a, B: Backend> {
|
||||||
|
/// Reference to the terminal instance.
|
||||||
|
terminal: &'a mut Terminal<B>,
|
||||||
|
/// Mutable reference to the application state.
|
||||||
|
app: &'a mut App,
|
||||||
|
/// Loaded user configuration.
|
||||||
|
config: &'a Config,
|
||||||
|
/// Path where the final configuration will be saved.
|
||||||
|
output_path: &'a Path,
|
||||||
|
/// Handler for the specific file format (env, json, yaml, toml).
|
||||||
|
handler: &'a dyn FormatHandler,
|
||||||
|
/// Buffer for storing active command entry (e.g., ":w").
|
||||||
|
command_buffer: String,
|
||||||
|
/// Buffer for storing sequence of key presses (e.g., "gg").
|
||||||
|
key_sequence: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, B: Backend> AppRunner<'a, B>
|
||||||
|
where
|
||||||
|
io::Error: From<B::Error>,
|
||||||
|
{
|
||||||
|
/// Creates a new runner instance.
|
||||||
|
pub fn new(
|
||||||
|
terminal: &'a mut Terminal<B>,
|
||||||
|
app: &'a mut App,
|
||||||
|
config: &'a Config,
|
||||||
|
output_path: &'a Path,
|
||||||
|
handler: &'a dyn FormatHandler,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
terminal,
|
||||||
|
app,
|
||||||
|
config,
|
||||||
|
output_path,
|
||||||
|
handler,
|
||||||
|
command_buffer: String::new(),
|
||||||
|
key_sequence: String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts the main application loop.
|
||||||
|
pub fn run(&mut self) -> io::Result<()> {
|
||||||
|
while self.app.running {
|
||||||
|
self.terminal
|
||||||
|
.draw(|f| crate::ui::draw(f, self.app, self.config))?;
|
||||||
|
|
||||||
|
if let Event::Key(key) = event::read()? {
|
||||||
|
self.handle_key_event(key)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Primary dispatcher for all keyboard events.
|
||||||
|
fn handle_key_event(&mut self, key: KeyEvent) -> io::Result<()> {
|
||||||
|
match self.app.mode {
|
||||||
|
Mode::Normal => self.handle_normal_mode(key),
|
||||||
|
Mode::Insert => self.handle_insert_mode(key),
|
||||||
|
Mode::InsertKey => self.handle_insert_key_mode(key),
|
||||||
|
Mode::Search => self.handle_search_mode(key),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handles keys in Normal mode, separating navigation from command entry.
|
||||||
|
fn handle_normal_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
||||||
|
if !self.command_buffer.is_empty() {
|
||||||
|
self.handle_command_mode(key)
|
||||||
|
} else {
|
||||||
|
self.handle_navigation_mode(key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Logic for entering and executing ":" style commands.
|
||||||
|
fn handle_command_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
||||||
|
match key.code {
|
||||||
|
KeyCode::Enter => {
|
||||||
|
let cmd = self.command_buffer.clone();
|
||||||
|
self.command_buffer.clear();
|
||||||
|
self.execute_command(&cmd)
|
||||||
|
}
|
||||||
|
KeyCode::Esc => {
|
||||||
|
self.command_buffer.clear();
|
||||||
|
self.app.status_message = None;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
KeyCode::Backspace => {
|
||||||
|
self.command_buffer.pop();
|
||||||
|
self.sync_command_status();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
KeyCode::Char(c) => {
|
||||||
|
self.command_buffer.push(c);
|
||||||
|
self.sync_command_status();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
_ => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handles primary navigation (j/k) and transitions to insert or command modes.
|
||||||
|
fn handle_navigation_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
||||||
|
let key_str = if let KeyCode::Char(c) = key.code {
|
||||||
|
let mut s = String::new();
|
||||||
|
if key.modifiers.contains(event::KeyModifiers::ALT) {
|
||||||
|
s.push_str("alt+");
|
||||||
|
}
|
||||||
|
s.push(c);
|
||||||
|
s
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
};
|
||||||
|
|
||||||
|
if !key_str.is_empty() {
|
||||||
|
self.key_sequence.push_str(&key_str);
|
||||||
|
|
||||||
|
let mut exact_match = None;
|
||||||
|
let mut prefix_match = false;
|
||||||
|
|
||||||
|
// Collect all configured keybinds
|
||||||
|
let binds = [
|
||||||
|
(&self.config.keybinds.down, "down"),
|
||||||
|
(&self.config.keybinds.up, "up"),
|
||||||
|
(&self.config.keybinds.edit, "edit"),
|
||||||
|
(&self.config.keybinds.edit_append, "edit_append"),
|
||||||
|
(&self.config.keybinds.edit_substitute, "edit_substitute"),
|
||||||
|
(&"S".to_string(), "edit_substitute"),
|
||||||
|
(&self.config.keybinds.search, "search"),
|
||||||
|
(&self.config.keybinds.next_match, "next_match"),
|
||||||
|
(&self.config.keybinds.previous_match, "previous_match"),
|
||||||
|
(&self.config.keybinds.jump_top, "jump_top"),
|
||||||
|
(&self.config.keybinds.jump_bottom, "jump_bottom"),
|
||||||
|
(&self.config.keybinds.append_item, "append_item"),
|
||||||
|
(&self.config.keybinds.prepend_item, "prepend_item"),
|
||||||
|
(&self.config.keybinds.delete_item, "delete_item"),
|
||||||
|
(&self.config.keybinds.undo, "undo"),
|
||||||
|
(&self.config.keybinds.redo, "redo"),
|
||||||
|
(&self.config.keybinds.rename, "rename"),
|
||||||
|
(&self.config.keybinds.append_group, "append_group"),
|
||||||
|
(&self.config.keybinds.prepend_group, "prepend_group"),
|
||||||
|
(&self.config.keybinds.toggle_group, "toggle_group"),
|
||||||
|
(&"a".to_string(), "add_missing"),
|
||||||
|
(&":".to_string(), "command"),
|
||||||
|
(&"q".to_string(), "quit"),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (bind, action) in binds.iter() {
|
||||||
|
if bind == &&self.key_sequence {
|
||||||
|
exact_match = Some(*action);
|
||||||
|
break;
|
||||||
|
} else if bind.starts_with(&self.key_sequence) {
|
||||||
|
prefix_match = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if exact_match.is_none() && !prefix_match {
|
||||||
|
// Not a match and not a prefix, restart with current key
|
||||||
|
self.key_sequence.clear();
|
||||||
|
self.key_sequence.push_str(&key_str);
|
||||||
|
|
||||||
|
for (bind, action) in binds.iter() {
|
||||||
|
if bind == &&self.key_sequence {
|
||||||
|
exact_match = Some(*action);
|
||||||
|
break;
|
||||||
|
} else if bind.starts_with(&self.key_sequence) {
|
||||||
|
prefix_match = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(action) = exact_match {
|
||||||
|
self.key_sequence.clear();
|
||||||
|
match action {
|
||||||
|
"down" => self.app.next(),
|
||||||
|
"up" => self.app.previous(),
|
||||||
|
"edit" => self.app.enter_insert(InsertVariant::Start),
|
||||||
|
"edit_append" => self.app.enter_insert(InsertVariant::End),
|
||||||
|
"edit_substitute" => self.app.enter_insert(InsertVariant::Substitute),
|
||||||
|
"search" => {
|
||||||
|
self.app.mode = Mode::Search;
|
||||||
|
self.app.search_query.clear();
|
||||||
|
self.app.status_message = Some(format!("{} ", self.config.keybinds.search));
|
||||||
|
}
|
||||||
|
"next_match" => self.app.jump_next_match(),
|
||||||
|
"previous_match" => self.app.jump_previous_match(),
|
||||||
|
"jump_top" => self.app.jump_top(),
|
||||||
|
"jump_bottom" => self.app.jump_bottom(),
|
||||||
|
"append_item" => self.app.add_item(true, false, false),
|
||||||
|
"prepend_item" => self.app.add_item(false, false, false),
|
||||||
|
"delete_item" => self.app.delete_selected(),
|
||||||
|
"undo" => self.app.undo(),
|
||||||
|
"redo" => self.app.redo(),
|
||||||
|
"rename" => self.app.enter_insert_key(),
|
||||||
|
"append_group" => self.app.add_item(true, true, true),
|
||||||
|
"prepend_group" => self.app.add_item(false, true, true),
|
||||||
|
"toggle_group" => {
|
||||||
|
self.app.toggle_group_selected();
|
||||||
|
self.app.save_undo_state();
|
||||||
|
}
|
||||||
|
"add_missing" => {
|
||||||
|
self.add_missing_item();
|
||||||
|
}
|
||||||
|
"command" => {
|
||||||
|
self.command_buffer.push(':');
|
||||||
|
self.sync_command_status();
|
||||||
|
}
|
||||||
|
"quit" => self.app.running = false,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
} else if !prefix_match {
|
||||||
|
self.key_sequence.clear();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Non-character keys reset the sequence buffer
|
||||||
|
self.key_sequence.clear();
|
||||||
|
match key.code {
|
||||||
|
KeyCode::Down => self.app.next(),
|
||||||
|
KeyCode::Up => self.app.previous(),
|
||||||
|
KeyCode::Enter => self.save_file()?,
|
||||||
|
KeyCode::Esc => self.app.status_message = None,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds a missing item from the template to the active configuration.
|
||||||
|
fn add_missing_item(&mut self) {
|
||||||
|
if let Some(var) = self.app.vars.get_mut(self.app.selected)
|
||||||
|
&& var.status == crate::format::ItemStatus::MissingFromActive {
|
||||||
|
var.status = crate::format::ItemStatus::Present;
|
||||||
|
if !var.is_group {
|
||||||
|
var.value = var.template_value.clone();
|
||||||
|
}
|
||||||
|
self.app.sync_input_with_selected();
|
||||||
|
self.app.save_undo_state();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delegates key events to the `tui_input` handler during active editing.
|
||||||
|
fn handle_insert_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
||||||
|
match key.code {
|
||||||
|
KeyCode::Esc => {
|
||||||
|
self.app.cancel_insert();
|
||||||
|
}
|
||||||
|
KeyCode::Enter => {
|
||||||
|
self.app.enter_normal();
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
self.app.input.handle_event(&Event::Key(key));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handles keys in InsertKey mode.
|
||||||
|
fn handle_insert_key_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
||||||
|
match key.code {
|
||||||
|
KeyCode::Esc => {
|
||||||
|
self.app.cancel_insert();
|
||||||
|
}
|
||||||
|
KeyCode::Enter => {
|
||||||
|
self.app.enter_normal();
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
self.app.input.handle_event(&Event::Key(key));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handles search mode key events.
|
||||||
|
fn handle_search_mode(&mut self, key: KeyEvent) -> io::Result<()> {
|
||||||
|
match key.code {
|
||||||
|
KeyCode::Enter | KeyCode::Esc => {
|
||||||
|
self.app.mode = Mode::Normal;
|
||||||
|
self.app.status_message = None;
|
||||||
|
}
|
||||||
|
KeyCode::Backspace => {
|
||||||
|
self.app.search_query.pop();
|
||||||
|
self.app.status_message = Some(format!("{}{}", self.config.keybinds.search, self.app.search_query));
|
||||||
|
self.app.jump_next_match();
|
||||||
|
}
|
||||||
|
KeyCode::Char(c) => {
|
||||||
|
self.app.search_query.push(c);
|
||||||
|
self.app.status_message = Some(format!("{}{}", self.config.keybinds.search, self.app.search_query));
|
||||||
|
self.app.jump_next_match();
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Logic to map command strings (like ":w") to internal application actions.
|
||||||
|
fn execute_command(&mut self, cmd: &str) -> io::Result<()> {
|
||||||
|
if cmd == self.config.keybinds.save {
|
||||||
|
self.save_file()
|
||||||
|
} else if cmd == self.config.keybinds.quit {
|
||||||
|
self.app.running = false;
|
||||||
|
Ok(())
|
||||||
|
} else if cmd == ":wq" {
|
||||||
|
self.save_file()?;
|
||||||
|
self.app.running = false;
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
self.app.status_message = Some(format!("Unknown command: {}", cmd));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Attempts to write the current app state to the specified output file.
|
||||||
|
fn save_file(&mut self) -> io::Result<()> {
|
||||||
|
if self.handler.write(self.output_path, &self.app.vars).is_ok() {
|
||||||
|
self.app.status_message = Some(format!("Saved to {}", self.output_path.display()));
|
||||||
|
} else {
|
||||||
|
self.app.status_message = Some("Error saving file".to_string());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Synchronizes the status bar display with the active command buffer.
|
||||||
|
fn sync_command_status(&mut self) {
|
||||||
|
if self.command_buffer.is_empty() {
|
||||||
|
self.app.status_message = None;
|
||||||
|
} else {
|
||||||
|
self.app.status_message = Some(self.command_buffer.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
363
src/ui.rs
363
src/ui.rs
@@ -3,148 +3,333 @@ use crate::config::Config;
|
|||||||
use ratatui::{
|
use ratatui::{
|
||||||
Frame,
|
Frame,
|
||||||
layout::{Constraint, Direction, Layout},
|
layout::{Constraint, Direction, Layout},
|
||||||
style::{Color, Modifier, Style},
|
style::{Modifier, Style},
|
||||||
text::{Line, Span},
|
text::{Line, Span},
|
||||||
widgets::{Block, Borders, List, ListItem, ListState, Paragraph},
|
widgets::{Block, BorderType, Borders, List, ListItem, ListState, Paragraph},
|
||||||
};
|
};
|
||||||
|
|
||||||
// Catppuccin Mocha Palette
|
/// Renders the main application interface using ratatui.
|
||||||
const MANTLE: Color = Color::Rgb(24, 24, 37);
|
pub fn draw(f: &mut Frame, app: &mut App, config: &Config) {
|
||||||
const BASE: Color = Color::Rgb(30, 30, 46);
|
let theme = &config.theme;
|
||||||
const TEXT: Color = Color::Rgb(205, 214, 244);
|
|
||||||
const BLUE: Color = Color::Rgb(137, 180, 250);
|
|
||||||
const GREEN: Color = Color::Rgb(166, 227, 161);
|
|
||||||
const SURFACE1: Color = Color::Rgb(69, 71, 90);
|
|
||||||
|
|
||||||
pub fn draw(f: &mut Frame, app: &mut App, _config: &Config) {
|
|
||||||
let size = f.area();
|
let size = f.area();
|
||||||
|
|
||||||
// Theming (defaults to Mocha, can be extended later via _config)
|
// Render the main background (optional based on transparency config).
|
||||||
let bg_color = BASE;
|
if !theme.transparent {
|
||||||
let fg_color = TEXT;
|
f.render_widget(
|
||||||
let highlight_color = BLUE;
|
Block::default().style(Style::default().bg(theme.bg_normal())),
|
||||||
let insert_color = GREEN;
|
size,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Background
|
// Horizontal layout with 1-character side margins.
|
||||||
let block = Block::default().style(Style::default().bg(bg_color).fg(fg_color));
|
let outer_layout = Layout::default()
|
||||||
f.render_widget(block, size);
|
.direction(Direction::Horizontal)
|
||||||
|
|
||||||
let chunks = Layout::default()
|
|
||||||
.direction(Direction::Vertical)
|
|
||||||
.constraints([
|
.constraints([
|
||||||
Constraint::Min(3), // List
|
Constraint::Length(1),
|
||||||
Constraint::Length(3), // Input area
|
Constraint::Min(0),
|
||||||
Constraint::Length(1), // Status bar
|
Constraint::Length(1),
|
||||||
])
|
])
|
||||||
.split(size);
|
.split(size);
|
||||||
|
|
||||||
// List
|
// Vertical layout for the main UI components.
|
||||||
|
let chunks = Layout::default()
|
||||||
|
.direction(Direction::Vertical)
|
||||||
|
.constraints([
|
||||||
|
Constraint::Length(1), // Top margin
|
||||||
|
Constraint::Min(3), // Main list
|
||||||
|
Constraint::Length(3), // Focused input field
|
||||||
|
Constraint::Length(1), // Spacer
|
||||||
|
Constraint::Length(1), // Status bar
|
||||||
|
])
|
||||||
|
.split(outer_layout[1]);
|
||||||
|
|
||||||
|
// Build the interactive list of configuration variables.
|
||||||
|
let matching_indices = app.matching_indices();
|
||||||
let items: Vec<ListItem> = app
|
let items: Vec<ListItem> = app
|
||||||
.vars
|
.vars
|
||||||
.iter()
|
.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.map(|(i, var)| {
|
.map(|(i, var)| {
|
||||||
let style = if i == app.selected {
|
let is_selected = i == app.selected;
|
||||||
Style::default()
|
let is_match = matching_indices.contains(&i);
|
||||||
.fg(bg_color)
|
|
||||||
.bg(highlight_color)
|
// Indentation based on depth
|
||||||
.add_modifier(Modifier::BOLD)
|
let indent = " ".repeat(var.depth);
|
||||||
|
let prefix = if var.is_group { "+ " } else { " " };
|
||||||
|
|
||||||
|
// Determine colors based on depth
|
||||||
|
let depth_color = if is_selected {
|
||||||
|
theme.bg_normal()
|
||||||
} else {
|
} else {
|
||||||
Style::default().fg(fg_color)
|
match var.depth % 4 {
|
||||||
|
0 => theme.tree_depth_1(),
|
||||||
|
1 => theme.tree_depth_2(),
|
||||||
|
2 => theme.tree_depth_3(),
|
||||||
|
3 => theme.tree_depth_4(),
|
||||||
|
_ => theme.fg_normal(),
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let content = format!(" {} = {} ", var.key, var.value);
|
// Determine colors based on status and selection
|
||||||
ListItem::new(Line::from(content)).style(style)
|
let text_color = if is_selected {
|
||||||
|
theme.fg_highlight()
|
||||||
|
} else {
|
||||||
|
match var.status {
|
||||||
|
crate::format::ItemStatus::MissingFromActive if !var.is_group => theme.fg_dimmed(),
|
||||||
|
crate::format::ItemStatus::Modified => theme.fg_modified(),
|
||||||
|
_ => theme.fg_normal(),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let key_style = if is_selected {
|
||||||
|
Style::default()
|
||||||
|
.fg(theme.fg_highlight())
|
||||||
|
.add_modifier(Modifier::BOLD)
|
||||||
|
} else if is_match {
|
||||||
|
Style::default()
|
||||||
|
.fg(theme.bg_search())
|
||||||
|
.add_modifier(Modifier::UNDERLINED)
|
||||||
|
} else if var.status == crate::format::ItemStatus::MissingFromActive && !var.is_group {
|
||||||
|
Style::default()
|
||||||
|
.fg(theme.fg_dimmed())
|
||||||
|
.add_modifier(Modifier::DIM)
|
||||||
|
} else {
|
||||||
|
Style::default().fg(depth_color)
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut key_spans = vec![
|
||||||
|
Span::raw(indent),
|
||||||
|
Span::styled(prefix, Style::default().fg(theme.border_normal())),
|
||||||
|
Span::styled(&var.key, key_style),
|
||||||
|
];
|
||||||
|
|
||||||
|
// Add status indicator if not present
|
||||||
|
match var.status {
|
||||||
|
crate::format::ItemStatus::MissingFromActive if !var.is_group => {
|
||||||
|
let missing_style = if is_selected {
|
||||||
|
Style::default().fg(theme.fg_highlight()).add_modifier(Modifier::BOLD)
|
||||||
|
} else {
|
||||||
|
Style::default().fg(theme.fg_warning()).add_modifier(Modifier::BOLD)
|
||||||
|
};
|
||||||
|
key_spans.push(Span::styled(" (missing)", missing_style));
|
||||||
|
}
|
||||||
|
crate::format::ItemStatus::MissingFromActive if var.is_group => {
|
||||||
|
let missing_style = if is_selected {
|
||||||
|
Style::default().fg(theme.fg_highlight()).add_modifier(Modifier::BOLD)
|
||||||
|
} else {
|
||||||
|
Style::default().fg(theme.fg_warning()).add_modifier(Modifier::BOLD)
|
||||||
|
};
|
||||||
|
key_spans.push(Span::styled(" (missing group)", missing_style));
|
||||||
|
}
|
||||||
|
crate::format::ItemStatus::Modified => {
|
||||||
|
if !is_selected {
|
||||||
|
key_spans.push(Span::styled(" (*)", Style::default().fg(theme.fg_modified())));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
let item_style = if is_selected {
|
||||||
|
Style::default().bg(theme.bg_highlight())
|
||||||
|
} else {
|
||||||
|
Style::default().fg(text_color)
|
||||||
|
};
|
||||||
|
|
||||||
|
if var.is_group {
|
||||||
|
ListItem::new(Line::from(key_spans)).style(item_style)
|
||||||
|
} else {
|
||||||
|
// Show live input text for the selected item if in Insert mode.
|
||||||
|
let val = if is_selected && matches!(app.mode, Mode::Insert) {
|
||||||
|
app.input.value()
|
||||||
|
} else {
|
||||||
|
var.value.as_deref().unwrap_or("")
|
||||||
|
};
|
||||||
|
|
||||||
|
let value_style = if is_selected {
|
||||||
|
Style::default().fg(theme.fg_highlight())
|
||||||
|
} else {
|
||||||
|
Style::default().fg(theme.fg_normal())
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut val_spans = vec![
|
||||||
|
Span::raw(format!("{} └─ ", " ".repeat(var.depth))),
|
||||||
|
Span::styled(val, value_style),
|
||||||
|
];
|
||||||
|
|
||||||
|
if let Some(t_val) = &var.template_value
|
||||||
|
&& Some(t_val) != var.value.as_ref() {
|
||||||
|
let t_style = if is_selected {
|
||||||
|
Style::default().fg(theme.bg_normal()).add_modifier(Modifier::DIM)
|
||||||
|
} else {
|
||||||
|
Style::default().fg(theme.fg_dimmed()).add_modifier(Modifier::ITALIC)
|
||||||
|
};
|
||||||
|
val_spans.push(Span::styled(format!(" [Def: {}]", t_val), t_style));
|
||||||
|
}
|
||||||
|
|
||||||
|
ListItem::new(vec![Line::from(key_spans), Line::from(val_spans)]).style(item_style)
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
let list = List::new(items)
|
let list = List::new(items).block(
|
||||||
.block(
|
|
||||||
Block::default()
|
Block::default()
|
||||||
.borders(Borders::ALL)
|
.borders(Borders::ALL)
|
||||||
.title(" Environment Variables ")
|
.border_type(BorderType::Rounded)
|
||||||
.border_style(Style::default().fg(SURFACE1)),
|
.title(" Config Variables ")
|
||||||
)
|
.title_style(
|
||||||
.highlight_style(
|
|
||||||
Style::default()
|
Style::default()
|
||||||
.fg(bg_color)
|
.fg(theme.fg_accent())
|
||||||
.bg(highlight_color)
|
|
||||||
.add_modifier(Modifier::BOLD),
|
.add_modifier(Modifier::BOLD),
|
||||||
|
)
|
||||||
|
.border_style(Style::default().fg(theme.border_normal())),
|
||||||
);
|
);
|
||||||
|
|
||||||
let mut state = ListState::default();
|
let mut state = ListState::default();
|
||||||
state.select(Some(app.selected));
|
state.select(Some(app.selected));
|
||||||
f.render_stateful_widget(list, chunks[0], &mut state);
|
f.render_stateful_widget(list, chunks[1], &mut state);
|
||||||
|
|
||||||
// Input Area
|
// Render the focused input area.
|
||||||
let current_var = app.vars.get(app.selected);
|
let current_var = app.vars.get(app.selected);
|
||||||
let input_title = if let Some(var) = current_var {
|
let mut input_title = " Input ".to_string();
|
||||||
if var.default_value.is_empty() {
|
let mut extra_info = String::new();
|
||||||
format!(" Editing: {} ", var.key)
|
|
||||||
|
if let Some(var) = current_var {
|
||||||
|
if matches!(app.mode, Mode::InsertKey) {
|
||||||
|
input_title = format!(" Rename Key: {} ", var.path_string());
|
||||||
|
} else if var.is_group {
|
||||||
|
input_title = format!(" Group: {} ", var.path_string());
|
||||||
} else {
|
} else {
|
||||||
format!(" Editing: {} (Default: {}) ", var.key, var.default_value)
|
input_title = format!(" Editing: {} ", var.path_string());
|
||||||
|
if let Some(t_val) = &var.template_value {
|
||||||
|
extra_info = format!(" [Template: {}]", t_val);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let input_border_color = match app.mode {
|
||||||
|
Mode::Insert | Mode::InsertKey => theme.border_active(),
|
||||||
|
Mode::Normal | Mode::Search => theme.border_normal(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let input_text = app.input.value();
|
||||||
|
let cursor_pos = app.input.visual_cursor();
|
||||||
|
|
||||||
|
// Show template value in normal mode if it differs
|
||||||
|
let display_text = if let Some(var) = current_var {
|
||||||
|
if matches!(app.mode, Mode::InsertKey) {
|
||||||
|
input_text.to_string()
|
||||||
|
} else if var.is_group {
|
||||||
|
"<group>".to_string()
|
||||||
|
} else if matches!(app.mode, Mode::Normal) {
|
||||||
|
format!("{}{}", input_text, extra_info)
|
||||||
|
} else {
|
||||||
|
input_text.to_string()
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
" Input ".to_string()
|
input_text.to_string()
|
||||||
};
|
};
|
||||||
|
|
||||||
let input_color = match app.mode {
|
let input = Paragraph::new(display_text)
|
||||||
Mode::Insert => insert_color,
|
.style(Style::default().fg(theme.fg_normal()))
|
||||||
Mode::Normal => SURFACE1,
|
|
||||||
};
|
|
||||||
|
|
||||||
let input_text = if let Some(var) = current_var {
|
|
||||||
var.value.as_str()
|
|
||||||
} else {
|
|
||||||
""
|
|
||||||
};
|
|
||||||
|
|
||||||
let input = Paragraph::new(input_text)
|
|
||||||
.style(Style::default().fg(fg_color))
|
|
||||||
.block(
|
.block(
|
||||||
Block::default()
|
Block::default()
|
||||||
.borders(Borders::ALL)
|
.borders(Borders::ALL)
|
||||||
|
.border_type(BorderType::Rounded)
|
||||||
.title(input_title)
|
.title(input_title)
|
||||||
.border_style(Style::default().fg(input_color)),
|
.title_style(
|
||||||
|
Style::default()
|
||||||
|
.fg(theme.fg_accent()) // Make title pop
|
||||||
|
.add_modifier(Modifier::BOLD),
|
||||||
|
)
|
||||||
|
.border_style(Style::default().fg(input_border_color)),
|
||||||
);
|
);
|
||||||
f.render_widget(input, chunks[1]);
|
f.render_widget(input, chunks[2]);
|
||||||
|
|
||||||
if let Mode::Insert = app.mode {
|
// Position the terminal cursor correctly when in Insert mode.
|
||||||
let input_area = chunks[1];
|
if matches!(app.mode, Mode::Insert) || matches!(app.mode, Mode::InsertKey) {
|
||||||
// Cursor positioning
|
|
||||||
f.set_cursor_position(ratatui::layout::Position::new(
|
f.set_cursor_position(ratatui::layout::Position::new(
|
||||||
input_area.x + 1 + input_text.chars().count() as u16,
|
chunks[2].x + 1 + cursor_pos as u16,
|
||||||
input_area.y + 1,
|
chunks[2].y + 1,
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Status bar
|
// Render the modern pill-style status bar.
|
||||||
let status_style = Style::default().bg(MANTLE).fg(fg_color);
|
let (mode_str, mode_style) = match app.mode {
|
||||||
let mode_str = match app.mode {
|
Mode::Normal => (
|
||||||
Mode::Normal => " NORMAL ",
|
" NORMAL ",
|
||||||
Mode::Insert => " INSERT ",
|
Style::default()
|
||||||
};
|
.bg(theme.bg_highlight())
|
||||||
let mode_style = match app.mode {
|
.fg(theme.bg_normal())
|
||||||
Mode::Normal => Style::default()
|
|
||||||
.bg(BLUE)
|
|
||||||
.fg(bg_color)
|
|
||||||
.add_modifier(Modifier::BOLD),
|
.add_modifier(Modifier::BOLD),
|
||||||
Mode::Insert => Style::default()
|
),
|
||||||
.bg(GREEN)
|
Mode::Insert => (
|
||||||
.fg(bg_color)
|
" INSERT ",
|
||||||
|
Style::default()
|
||||||
|
.bg(theme.bg_active())
|
||||||
|
.fg(theme.bg_normal())
|
||||||
.add_modifier(Modifier::BOLD),
|
.add_modifier(Modifier::BOLD),
|
||||||
|
),
|
||||||
|
Mode::InsertKey => (
|
||||||
|
" RENAME ",
|
||||||
|
Style::default()
|
||||||
|
.bg(theme.bg_active())
|
||||||
|
.fg(theme.bg_normal())
|
||||||
|
.add_modifier(Modifier::BOLD),
|
||||||
|
),
|
||||||
|
Mode::Search => (
|
||||||
|
" SEARCH ",
|
||||||
|
Style::default()
|
||||||
|
.bg(theme.bg_search())
|
||||||
|
.fg(theme.bg_normal())
|
||||||
|
.add_modifier(Modifier::BOLD),
|
||||||
|
),
|
||||||
};
|
};
|
||||||
|
|
||||||
let status_msg = app
|
let status_msg = if let Some(msg) = &app.status_message {
|
||||||
.status_message
|
msg.clone()
|
||||||
.as_deref()
|
} else {
|
||||||
.unwrap_or(" j/k: navigate | i: edit | :w/Enter: save | q/:q: quit ");
|
let kb = &config.keybinds;
|
||||||
|
match app.mode {
|
||||||
|
Mode::Normal => {
|
||||||
|
let mut parts = vec![
|
||||||
|
format!("{}/{} move", kb.down, kb.up),
|
||||||
|
format!("{}/{} jump", kb.jump_top, kb.jump_bottom),
|
||||||
|
format!("{} search", kb.search),
|
||||||
|
];
|
||||||
|
if !app.selected_is_group() {
|
||||||
|
parts.push(format!("{}/{}/{} edit", kb.edit, kb.edit_append, kb.edit_substitute));
|
||||||
|
}
|
||||||
|
parts.push(format!("{} rename", kb.rename));
|
||||||
|
parts.push(format!("{} toggle", kb.toggle_group));
|
||||||
|
if app.selected_is_missing() {
|
||||||
|
parts.push(format!("{} add", "a")); // 'a' is currently hardcoded in runner
|
||||||
|
}
|
||||||
|
if app.selected_is_array() {
|
||||||
|
parts.push(format!("{}/{} array", kb.append_item, kb.prepend_item));
|
||||||
|
} else {
|
||||||
|
parts.push(format!("{}/{} add", kb.append_item, kb.prepend_item));
|
||||||
|
parts.push(format!("{}/{} group", kb.append_group, kb.prepend_group));
|
||||||
|
}
|
||||||
|
parts.push(format!("{} del", kb.delete_item));
|
||||||
|
parts.push(format!("{} undo", kb.undo));
|
||||||
|
parts.push(format!("{} save", kb.save));
|
||||||
|
parts.push(format!("{} quit", kb.quit));
|
||||||
|
parts.join(" · ")
|
||||||
|
}
|
||||||
|
Mode::Insert => "Esc cancel · Enter commit".to_string(),
|
||||||
|
Mode::InsertKey => "Esc cancel · Enter rename".to_string(),
|
||||||
|
Mode::Search => "Esc normal · type to filter".to_string(),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
let status_line = Line::from(vec![
|
let status_line = Line::from(vec![
|
||||||
Span::styled(mode_str, mode_style),
|
Span::styled(mode_str, mode_style),
|
||||||
Span::styled(format!(" {} ", status_msg), status_style),
|
Span::styled(
|
||||||
|
format!(" {} ", status_msg),
|
||||||
|
Style::default().bg(theme.border_normal()).fg(theme.fg_normal()),
|
||||||
|
),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
let status = Paragraph::new(status_line).style(status_style);
|
let status = Paragraph::new(status_line).style(Style::default().bg(theme.border_normal()));
|
||||||
f.render_widget(status, chunks[2]);
|
f.render_widget(status, chunks[4]);
|
||||||
}
|
}
|
||||||
|
|||||||
187
src/undo.rs
Normal file
187
src/undo.rs
Normal file
@@ -0,0 +1,187 @@
|
|||||||
|
use crate::format::ConfigItem;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
pub struct EditAction {
|
||||||
|
pub state: Vec<ConfigItem>,
|
||||||
|
pub selected: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct UndoNode {
|
||||||
|
pub action: EditAction,
|
||||||
|
pub parent: Option<usize>,
|
||||||
|
pub children: Vec<usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct UndoTree {
|
||||||
|
nodes: HashMap<usize, UndoNode>,
|
||||||
|
current_node: usize,
|
||||||
|
next_id: usize,
|
||||||
|
// Track the latest child added to a node to know which branch to follow on redo
|
||||||
|
latest_branch: HashMap<usize, usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UndoTree {
|
||||||
|
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(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::format::{ItemStatus, ValueType};
|
||||||
|
|
||||||
|
fn dummy_item(key: &str) -> ConfigItem {
|
||||||
|
ConfigItem {
|
||||||
|
key: key.to_string(),
|
||||||
|
path: vec![],
|
||||||
|
value: Some(key.to_string()),
|
||||||
|
template_value: None,
|
||||||
|
default_value: None,
|
||||||
|
depth: 0,
|
||||||
|
is_group: false,
|
||||||
|
status: ItemStatus::Present,
|
||||||
|
value_type: 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user