Compare commits
9 Commits
feature-v0
...
feature-v0
| Author | SHA1 | Date | |
|---|---|---|---|
| 94b4c23299 | |||
| 941558cb92 | |||
| 0c478ae39d | |||
| 3db8945e16 | |||
| 219a6b3d51 | |||
| 9e1051737a | |||
| 8aba995fb0 | |||
| 0ac7a07133 | |||
| 75103dae3c |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -3,3 +3,5 @@
|
|||||||
/.idea
|
/.idea
|
||||||
*.exe
|
*.exe
|
||||||
./Cargo.lock
|
./Cargo.lock
|
||||||
|
**/target
|
||||||
|
**/Cargo.lock
|
||||||
|
|||||||
731
Cargo.lock
generated
Normal file
731
Cargo.lock
generated
Normal file
@@ -0,0 +1,731 @@
|
|||||||
|
# This file is automatically @generated by Cargo.
|
||||||
|
# It is not intended for manual editing.
|
||||||
|
version = 4
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "aho-corasick"
|
||||||
|
version = "1.1.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
|
||||||
|
dependencies = [
|
||||||
|
"memchr",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anstream"
|
||||||
|
version = "1.0.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
|
||||||
|
dependencies = [
|
||||||
|
"anstyle",
|
||||||
|
"anstyle-parse",
|
||||||
|
"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 = "1.0.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
|
||||||
|
dependencies = [
|
||||||
|
"utf8parse",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anstyle-query"
|
||||||
|
version = "1.1.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
|
||||||
|
dependencies = [
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anstyle-wincon"
|
||||||
|
version = "3.0.11"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
|
||||||
|
dependencies = [
|
||||||
|
"anstyle",
|
||||||
|
"once_cell_polyfill",
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anyhow"
|
||||||
|
version = "1.0.104"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "autocfg"
|
||||||
|
version = "1.5.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "bitflags"
|
||||||
|
version = "2.13.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "bstr"
|
||||||
|
version = "1.13.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f"
|
||||||
|
dependencies = [
|
||||||
|
"memchr",
|
||||||
|
"serde_core",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cc"
|
||||||
|
version = "1.4.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0ad534f4357a5264cce5019c989cf66a4f0dc4e0d1b1d15f8aacec0ff7360273"
|
||||||
|
dependencies = [
|
||||||
|
"find-msvc-tools",
|
||||||
|
"shlex",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cfg-if"
|
||||||
|
version = "1.0.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "clap"
|
||||||
|
version = "4.6.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "473c7e07f409a8d772161724aa8db6a765a2532a70f9667eeb7b49d3d02fbdca"
|
||||||
|
dependencies = [
|
||||||
|
"clap_builder",
|
||||||
|
"clap_derive",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "clap_builder"
|
||||||
|
version = "4.6.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7b48fea5a88e9ae728a2dcbedbfc0e730f7d60da42e1cb049a83c9fb8b789889"
|
||||||
|
dependencies = [
|
||||||
|
"anstream",
|
||||||
|
"anstyle",
|
||||||
|
"clap_lex",
|
||||||
|
"strsim",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "clap_derive"
|
||||||
|
version = "4.6.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d012d2b9d65aca7f18f4d9878a045bc17899bba951561ba5ec3c2ba1eed9a061"
|
||||||
|
dependencies = [
|
||||||
|
"heck",
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 3.0.3",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "clap_lex"
|
||||||
|
version = "1.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "colorchoice"
|
||||||
|
version = "1.0.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "crossbeam-channel"
|
||||||
|
version = "0.5.16"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d85363c37faeca707aef026efa9f3b34d077bce547e48f770770625c6013679e"
|
||||||
|
dependencies = [
|
||||||
|
"crossbeam-utils",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "crossbeam-utils"
|
||||||
|
version = "0.8.22"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "deranged"
|
||||||
|
version = "0.5.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "dunce"
|
||||||
|
version = "1.0.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "either"
|
||||||
|
version = "1.18.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "find-msvc-tools"
|
||||||
|
version = "0.1.11"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "heck"
|
||||||
|
version = "0.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "is_terminal_polyfill"
|
||||||
|
version = "1.70.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "lazy_static"
|
||||||
|
version = "1.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "libc"
|
||||||
|
version = "0.2.189"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "lock_api"
|
||||||
|
version = "0.4.14"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
|
||||||
|
dependencies = [
|
||||||
|
"scopeguard",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "log"
|
||||||
|
version = "0.4.33"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "lua-src"
|
||||||
|
version = "551.0.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "087097f9936a7d819bda525b32d6e96f9c54f3d35ff23ff72fc0c1697d2127db"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "luajit-src"
|
||||||
|
version = "210.7.3+1ee778a"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "869665372263eb337b14f480cfb864b89f12eade4eb42cb415f71517b4a67572"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
"which",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "matchers"
|
||||||
|
version = "0.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
|
||||||
|
dependencies = [
|
||||||
|
"regex-automata",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "memchr"
|
||||||
|
version = "2.8.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "mirror-cli"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"anyhow",
|
||||||
|
"clap",
|
||||||
|
"mirror-core",
|
||||||
|
"mlua",
|
||||||
|
"tracing",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "mirror-core"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"anyhow",
|
||||||
|
"dunce",
|
||||||
|
"mlua",
|
||||||
|
"serde",
|
||||||
|
"tinyjson",
|
||||||
|
"tracing",
|
||||||
|
"tracing-appender",
|
||||||
|
"tracing-subscriber",
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "mirror-shim"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"anyhow",
|
||||||
|
"mirror-core",
|
||||||
|
"mlua",
|
||||||
|
"tracing",
|
||||||
|
"tracing-appender",
|
||||||
|
"tracing-subscriber",
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "mlua"
|
||||||
|
version = "0.12.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d96e5d00f19d8c46c71ceaced99593b90c31c57aa1fe2cb3e93a8b1698eedba9"
|
||||||
|
dependencies = [
|
||||||
|
"bstr",
|
||||||
|
"either",
|
||||||
|
"libc",
|
||||||
|
"mlua-sys",
|
||||||
|
"num-traits",
|
||||||
|
"parking_lot",
|
||||||
|
"rustc-hash",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "mlua-sys"
|
||||||
|
version = "0.12.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b806d7ade031f5d6607eae3e283fb034cb795a76247dd0d1ba753c8c42debccf"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
"cfg-if",
|
||||||
|
"libc",
|
||||||
|
"lua-src",
|
||||||
|
"luajit-src",
|
||||||
|
"pkg-config",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "nu-ansi-term"
|
||||||
|
version = "0.50.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
||||||
|
dependencies = [
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "num-conv"
|
||||||
|
version = "0.2.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "num-traits"
|
||||||
|
version = "0.2.19"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||||
|
dependencies = [
|
||||||
|
"autocfg",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "once_cell"
|
||||||
|
version = "1.21.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "once_cell_polyfill"
|
||||||
|
version = "1.70.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "parking_lot"
|
||||||
|
version = "0.12.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
|
||||||
|
dependencies = [
|
||||||
|
"lock_api",
|
||||||
|
"parking_lot_core",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "parking_lot_core"
|
||||||
|
version = "0.9.12"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"libc",
|
||||||
|
"redox_syscall",
|
||||||
|
"smallvec",
|
||||||
|
"windows-link",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pin-project-lite"
|
||||||
|
version = "0.2.17"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pkg-config"
|
||||||
|
version = "0.3.34"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "powerfmt"
|
||||||
|
version = "0.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "proc-macro2"
|
||||||
|
version = "1.0.107"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||||
|
dependencies = [
|
||||||
|
"unicode-ident",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "quote"
|
||||||
|
version = "1.0.47"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "redox_syscall"
|
||||||
|
version = "0.5.18"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "regex-automata"
|
||||||
|
version = "0.4.18"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
|
||||||
|
dependencies = [
|
||||||
|
"aho-corasick",
|
||||||
|
"memchr",
|
||||||
|
"regex-syntax",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "regex-syntax"
|
||||||
|
version = "0.8.11"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rustc-hash"
|
||||||
|
version = "2.1.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "scopeguard"
|
||||||
|
version = "1.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde"
|
||||||
|
version = "1.0.229"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||||
|
dependencies = [
|
||||||
|
"serde_core",
|
||||||
|
"serde_derive",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde_core"
|
||||||
|
version = "1.0.229"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||||
|
dependencies = [
|
||||||
|
"serde_derive",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde_derive"
|
||||||
|
version = "1.0.229"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 3.0.3",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "sharded-slab"
|
||||||
|
version = "0.1.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
|
||||||
|
dependencies = [
|
||||||
|
"lazy_static",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "shlex"
|
||||||
|
version = "2.0.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "smallvec"
|
||||||
|
version = "1.15.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "strsim"
|
||||||
|
version = "0.11.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "symlink"
|
||||||
|
version = "0.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "syn"
|
||||||
|
version = "2.0.119"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"unicode-ident",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "syn"
|
||||||
|
version = "3.0.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"unicode-ident",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "thiserror"
|
||||||
|
version = "2.0.20"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f"
|
||||||
|
dependencies = [
|
||||||
|
"thiserror-impl",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "thiserror-impl"
|
||||||
|
version = "2.0.20"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 3.0.3",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "thread_local"
|
||||||
|
version = "1.1.10"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "time"
|
||||||
|
version = "0.3.55"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"
|
||||||
|
dependencies = [
|
||||||
|
"deranged",
|
||||||
|
"num-conv",
|
||||||
|
"powerfmt",
|
||||||
|
"serde_core",
|
||||||
|
"time-core",
|
||||||
|
"time-macros",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "time-core"
|
||||||
|
version = "0.1.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "time-macros"
|
||||||
|
version = "0.2.32"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"
|
||||||
|
dependencies = [
|
||||||
|
"num-conv",
|
||||||
|
"time-core",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tinyjson"
|
||||||
|
version = "2.5.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9ab95735ea2c8fd51154d01e39cf13912a78071c2d89abc49a7ef102a7dd725a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tracing"
|
||||||
|
version = "0.1.44"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
|
||||||
|
dependencies = [
|
||||||
|
"pin-project-lite",
|
||||||
|
"tracing-attributes",
|
||||||
|
"tracing-core",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tracing-appender"
|
||||||
|
version = "0.2.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c"
|
||||||
|
dependencies = [
|
||||||
|
"crossbeam-channel",
|
||||||
|
"symlink",
|
||||||
|
"thiserror",
|
||||||
|
"time",
|
||||||
|
"tracing-subscriber",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tracing-attributes"
|
||||||
|
version = "0.1.31"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 2.0.119",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tracing-core"
|
||||||
|
version = "0.1.36"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
|
||||||
|
dependencies = [
|
||||||
|
"once_cell",
|
||||||
|
"valuable",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tracing-log"
|
||||||
|
version = "0.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
|
||||||
|
dependencies = [
|
||||||
|
"log",
|
||||||
|
"once_cell",
|
||||||
|
"tracing-core",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tracing-subscriber"
|
||||||
|
version = "0.3.23"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"
|
||||||
|
dependencies = [
|
||||||
|
"matchers",
|
||||||
|
"nu-ansi-term",
|
||||||
|
"once_cell",
|
||||||
|
"regex-automata",
|
||||||
|
"sharded-slab",
|
||||||
|
"smallvec",
|
||||||
|
"thread_local",
|
||||||
|
"tracing",
|
||||||
|
"tracing-core",
|
||||||
|
"tracing-log",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unicode-ident"
|
||||||
|
version = "1.0.24"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "utf8parse"
|
||||||
|
version = "0.2.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "valuable"
|
||||||
|
version = "0.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "which"
|
||||||
|
version = "8.0.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "bae2f2b2b816647a1cab1acc91f5bd20812d53cb344382635ec2181940c8034f"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-link"
|
||||||
|
version = "0.2.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-sys"
|
||||||
|
version = "0.61.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
||||||
|
dependencies = [
|
||||||
|
"windows-link",
|
||||||
|
]
|
||||||
28
Cargo.toml
28
Cargo.toml
@@ -1,16 +1,21 @@
|
|||||||
[package]
|
[workspace]
|
||||||
name = "rshim"
|
resolver = "2"
|
||||||
|
members = [
|
||||||
|
"mirror-core", "mirror-cli",
|
||||||
|
"mirror-shim",
|
||||||
|
]
|
||||||
|
|
||||||
|
#[package]
|
||||||
|
#name = "mirror"
|
||||||
|
|
||||||
|
[workspace.package]
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
rust-version = "1.94"
|
rust-version = "1.94"
|
||||||
license = "MIT OR Unlicense"
|
license = "MIT OR Unlicense"
|
||||||
description = "A fast, safe Rust shim launcher for Scoop"
|
description = "A fast, safe Rust shim launcher for Scoop"
|
||||||
|
|
||||||
[profile.release]
|
[workspace.dependencies]
|
||||||
opt-level = "z"
|
|
||||||
panic = "abort"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
anyhow = "1.0.104"
|
anyhow = "1.0.104"
|
||||||
|
|
||||||
mlua = { version = "0.12.0", features = ["lua54", "vendored","send"] }
|
mlua = { version = "0.12.0", features = ["lua54", "vendored","send"] }
|
||||||
@@ -22,11 +27,16 @@ windows-sys = { version = "0.61.2", features = [
|
|||||||
"Win32_System_Threading",
|
"Win32_System_Threading",
|
||||||
"Win32_UI_Shell",
|
"Win32_UI_Shell",
|
||||||
"Win32_UI_WindowsAndMessaging",
|
"Win32_UI_WindowsAndMessaging",
|
||||||
|
"Win32_Globalization"
|
||||||
] }
|
] }
|
||||||
dunce = "1.0.5"
|
dunce = "1.0.5"
|
||||||
|
|
||||||
# 日志
|
# 日志
|
||||||
tracing = "0.1.44"
|
tracing = "0.1.44"
|
||||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
tracing-subscriber = { version = "0.3", features = ["env-filter","fmt"] }
|
||||||
tracing-appender = "0.2"
|
tracing-appender = "0.2"
|
||||||
encoding_rs = "0.8.35"
|
serde = { version = "1.0.229", features = ["derive"] }
|
||||||
|
tinyjson="2.5.1"
|
||||||
|
#toml = "1.1.4+spec-1.1.0"
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
12
build.rs
12
build.rs
@@ -20,7 +20,7 @@ fn main() {
|
|||||||
|
|
||||||
// cargo:rerun-if-changed -> 当指定文件变化时,重新运行 xxx
|
// cargo:rerun-if-changed -> 当指定文件变化时,重新运行 xxx
|
||||||
println!("cargo:rerun-if-changed=build.rs");
|
println!("cargo:rerun-if-changed=build.rs");
|
||||||
println!("cargo:rerun-if-changed=rshim.lua");
|
println!("cargo:rerun-if-changed=mirror.lua");
|
||||||
println!("cargo:rustc-env=OUTPUT_DIR={}", output_dir.display());
|
println!("cargo:rustc-env=OUTPUT_DIR={}", output_dir.display());
|
||||||
|
|
||||||
// 创建目录
|
// 创建目录
|
||||||
@@ -34,13 +34,13 @@ fn main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 复制文件
|
// 复制文件
|
||||||
let source = PathBuf::from(&manifest_dir).join("mimic.lua");
|
let source = PathBuf::from(&manifest_dir).join("mirror.lua");
|
||||||
let destination = output_dir.join("rshim.lua");
|
let destination = output_dir.join("mirror.lua");
|
||||||
|
|
||||||
if source.exists() {
|
if source.exists() {
|
||||||
fs::copy(&source, &destination).expect("Failed to copy mimic.lua");
|
fs::copy(&source, &destination).expect("Failed to copy mirror.lua");
|
||||||
println!("Copied mimic.lua to: {:?}", destination);
|
println!("Copied mirror.lua to: {:?}", destination);
|
||||||
} else {
|
} else {
|
||||||
panic!("mimic.lua not found at: {:?}", source);
|
panic!("mirror.lua not found at: {:?}", source);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
37
commands/commands.lua
Normal file
37
commands/commands.lua
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
-- commands/commands.lua
|
||||||
|
function command(mod_path)
|
||||||
|
-- 无论输入 "a/b/c" 还是 "a\b\c",统一替换为标准的 "a.b.c"
|
||||||
|
local normalized = mod_path:gsub("[/\\]", ".")
|
||||||
|
|
||||||
|
return {
|
||||||
|
__is_lazy_command = true,
|
||||||
|
module = normalized
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
|
||||||
|
return {
|
||||||
|
-- 1. 单文件子命令 (commands/use.lua)
|
||||||
|
["use"] = {
|
||||||
|
description = "Switch the active version of a tool",
|
||||||
|
handler = command("use")
|
||||||
|
},
|
||||||
|
|
||||||
|
-- 2. 单文件子命令 (commands/list.lua)
|
||||||
|
["list"] = {
|
||||||
|
description = "List available and currently activated versions",
|
||||||
|
handler = command("list")
|
||||||
|
},
|
||||||
|
|
||||||
|
-- 3. 复杂多文件子命令 (加载 commands/log/init.lua)
|
||||||
|
["log"] = {
|
||||||
|
description = "View or configure mirror runtime logs",
|
||||||
|
handler = command("log")
|
||||||
|
},
|
||||||
|
|
||||||
|
-- 4. 支持别名快捷映射 (例如 mr ls 等价于 mr list)
|
||||||
|
["ls"] = {
|
||||||
|
description = "Alias for list",
|
||||||
|
handler = command("list")
|
||||||
|
}
|
||||||
|
}
|
||||||
24
commands/log/init.lua
Normal file
24
commands/log/init.lua
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
-- commands/log/init.lua
|
||||||
|
local argparse = require("argparse")
|
||||||
|
local utils = require("log.utils") -- 支持相对目录级 require
|
||||||
|
|
||||||
|
return function(raw_args)
|
||||||
|
local parser = argparse("mr log", "Manage and view mirror logs.")
|
||||||
|
parser:option("-l --level", "Set log level"):choices({"trace", "debug", "info", "warn", "error"})
|
||||||
|
parser:option("-t --tail", "Show last N lines"):convert(tonumber)
|
||||||
|
|
||||||
|
local ok, args = pcall(function() return parser:parse(raw_args) end)
|
||||||
|
if not ok then
|
||||||
|
error("__ARGPARSE_HELP__")
|
||||||
|
end
|
||||||
|
|
||||||
|
if args.level then
|
||||||
|
print(utils.format_level(args.level))
|
||||||
|
mr.fs.write(__MIRROR_DIR__ .. "/mirror-log.ini", "level = \"" .. args.level .. "\"\n")
|
||||||
|
print("✔ Updated log level.")
|
||||||
|
elseif args.tail then
|
||||||
|
print(string.format("Tailing last %d lines...", args.tail))
|
||||||
|
else
|
||||||
|
print("Log module ready. Run 'mr log --help' for details.")
|
||||||
|
end
|
||||||
|
end
|
||||||
8
commands/log/utils.lua
Normal file
8
commands/log/utils.lua
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
-- commands/log/utils.lua
|
||||||
|
local M = {}
|
||||||
|
|
||||||
|
function M.format_level(level)
|
||||||
|
return string.format("==> [LOG LEVEL: %s] <==", string.upper(level))
|
||||||
|
end
|
||||||
|
|
||||||
|
return M
|
||||||
16
mirror-cli/Cargo.toml
Normal file
16
mirror-cli/Cargo.toml
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
[package]
|
||||||
|
name = "mirror-cli"
|
||||||
|
version = { workspace = true }
|
||||||
|
edition = { workspace = true }
|
||||||
|
|
||||||
|
# 显式指定生成的二进制文件名
|
||||||
|
[[bin]]
|
||||||
|
name = "mr"
|
||||||
|
path = "src/main.rs"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
mirror-core = { path = "../mirror-core" }
|
||||||
|
clap = { version = "4.6.6", features = ["cargo", "color", "derive","string"] }
|
||||||
|
mlua = { workspace = true }
|
||||||
|
anyhow = { workspace = true }
|
||||||
|
tracing = { workspace = true }
|
||||||
40
mirror-cli/src/app.rs
Normal file
40
mirror-cli/src/app.rs
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
use crate::cli;
|
||||||
|
use crate::commands::{builtin, dynamic::MrCommand};
|
||||||
|
use anyhow::{Context, Result, bail};
|
||||||
|
use tracing::debug;
|
||||||
|
use mirror_core::{init_logging_from, Layout, LuaRuntime};
|
||||||
|
|
||||||
|
pub fn run() -> Result<()> {
|
||||||
|
let exe = std::env::current_exe().context("获取代理程序路径失败")?;
|
||||||
|
let layout = Layout::from(&exe)?;
|
||||||
|
let _guard = init_logging_from(&layout);
|
||||||
|
|
||||||
|
debug!("=== 管理程序启动 ===");
|
||||||
|
|
||||||
|
let registry_file = layout.base_dir.join("commands").join("commands.lua");
|
||||||
|
|
||||||
|
let runtime = LuaRuntime::new(&layout)?;
|
||||||
|
let commands: MrCommand = runtime
|
||||||
|
.eval_script(®istry_file)
|
||||||
|
.with_context(|| format!("加载命令配置失败: {}", registry_file.display()))?;
|
||||||
|
|
||||||
|
let app = cli::build(commands.clone());
|
||||||
|
let matches = app.get_matches();
|
||||||
|
|
||||||
|
match matches.subcommand() {
|
||||||
|
// 分支 A: 原生 Rust 实现的命令
|
||||||
|
Some(("log", sub_m)) => builtin::log_handle(&layout, sub_m),
|
||||||
|
|
||||||
|
// 分支 B: 动态 Lua 注册的命令
|
||||||
|
Some((cmd_name, sub_m)) => {
|
||||||
|
let sub_cmd = commands
|
||||||
|
.get(cmd_name)
|
||||||
|
.with_context(|| format!("未找到子命令 '{cmd_name}'"))?;
|
||||||
|
let raw_args = cli::extract_raw_args(sub_m);
|
||||||
|
runtime.require_and_run(&sub_cmd.module, raw_args)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 分支 C: 未输入子命令(通常已被 Clap 的 arg_required_else_help 拦截)
|
||||||
|
None => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
62
mirror-cli/src/cli.rs
Normal file
62
mirror-cli/src/cli.rs
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
use crate::commands::dynamic::MrCommand;
|
||||||
|
use clap::{Arg, ArgAction, Command};
|
||||||
|
use mirror_core::LogLevel;
|
||||||
|
use std::ffi::OsString;
|
||||||
|
// 引入强类型枚举
|
||||||
|
pub fn build(dynamic_cmds: MrCommand) -> Command {
|
||||||
|
let mut app = Command::new("mr")
|
||||||
|
.about("Mirror CLI Manager")
|
||||||
|
.version("0.1.0")
|
||||||
|
.arg_required_else_help(true)
|
||||||
|
.subcommand(log_subcommand());
|
||||||
|
|
||||||
|
for (name, sub_cmd) in dynamic_cmds.commands {
|
||||||
|
if name == "log" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// let a =name.as_str()
|
||||||
|
// 开启 "string" feature 后,String 可以直接作为 Command 的入参
|
||||||
|
app = app.subcommand(
|
||||||
|
Command::new(name)
|
||||||
|
.about(sub_cmd.description)
|
||||||
|
.allow_external_subcommands(true),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
app
|
||||||
|
}
|
||||||
|
/// 构建基础 CLI 骨架(内置 Rust 原生命令与参数规则)
|
||||||
|
fn log_subcommand() -> Command {
|
||||||
|
Command::new("log")
|
||||||
|
.about("查看或修改 mirror.ini 日志配置")
|
||||||
|
.arg(
|
||||||
|
Arg::new("tail")
|
||||||
|
.short('t')
|
||||||
|
.long("tail")
|
||||||
|
.value_name("LINES")
|
||||||
|
.help("显示最近的 N 行日志")
|
||||||
|
.value_parser(clap::value_parser!(usize)),
|
||||||
|
)
|
||||||
|
.arg(
|
||||||
|
Arg::new("level")
|
||||||
|
.short('l')
|
||||||
|
.long("level")
|
||||||
|
.value_name("LEVEL")
|
||||||
|
.help("设置运行时日志级别")
|
||||||
|
.value_parser(clap::value_parser!(LogLevel)),
|
||||||
|
)
|
||||||
|
.arg(
|
||||||
|
Arg::new("follow")
|
||||||
|
.short('f')
|
||||||
|
.long("follow")
|
||||||
|
.help("持续跟踪日志输出 (tail -f)")
|
||||||
|
.action(ArgAction::SetTrue),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn extract_raw_args(matches: &clap::ArgMatches) -> Vec<String> {
|
||||||
|
matches
|
||||||
|
.get_many::<OsString>("")
|
||||||
|
.unwrap_or_default()
|
||||||
|
.map(|s| s.to_string_lossy().into_owned())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
35
mirror-cli/src/commands/builtin.rs
Normal file
35
mirror-cli/src/commands/builtin.rs
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
use anyhow::{Context, Result};
|
||||||
|
use mirror_core::{Layout, LogLevel};
|
||||||
|
use std::fs;
|
||||||
|
|
||||||
|
// Rust 原生处理 log 命令逻辑
|
||||||
|
pub(crate) fn log_handle(layout: &Layout, matches: &clap::ArgMatches) -> Result<()> {
|
||||||
|
let log_ini_path = layout.base_dir.join("../../../mirror-core/mirror.ini");
|
||||||
|
|
||||||
|
// 1. 处理设置日志等级
|
||||||
|
if let Some(&level) = matches.get_one::<LogLevel>("level") {
|
||||||
|
let content = format!("level = \"{}\"\nlog_dir = \"logs\"\n", level.as_str());
|
||||||
|
fs::write(&log_ini_path, content)
|
||||||
|
.with_context(|| format!("写入日志配置文件失败: {}", log_ini_path.display()))?;
|
||||||
|
println!("日志级别已更新为: {level} ({})", log_ini_path.display());
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 处理 tail 查看
|
||||||
|
if let Some(&tail_lines) = matches.get_one::<usize>("tail") {
|
||||||
|
println!("正在检索最后 {tail_lines} 行日志...");
|
||||||
|
// 原生 Rust 高性能按行倒序读取日志文件
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 默认打印当前配置
|
||||||
|
if log_ini_path.is_file() {
|
||||||
|
let current_ini = fs::read_to_string(&log_ini_path)
|
||||||
|
.with_context(|| format!("读取配置文件失败: {}", log_ini_path.display()))?;
|
||||||
|
println!("当前 mirror.ini 配置:\n{current_ini}");
|
||||||
|
} else {
|
||||||
|
println!("未找到 mirror.ini,当前使用默认全局级别: warn");
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
139
mirror-cli/src/commands/dynamic.rs
Normal file
139
mirror-cli/src/commands/dynamic.rs
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
use crate::validators;
|
||||||
|
use mirror_core::error::validation_error;
|
||||||
|
use mlua::{FromLua, Lua, Value};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
const ALLOWED_KEYS: &[&str] = &["handler", "description"];
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Clone)]
|
||||||
|
pub struct MrCommand {
|
||||||
|
pub commands: HashMap<String, MrSubCommand>,
|
||||||
|
}
|
||||||
|
impl MrCommand {
|
||||||
|
pub fn get(&self, name: &str) -> Option<&MrSubCommand> {
|
||||||
|
self.commands.get(name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromLua for MrCommand {
|
||||||
|
fn from_lua(value: Value, lua: &Lua) -> mlua::Result<Self> {
|
||||||
|
let root_tbl = match value {
|
||||||
|
Value::Table(t) => t,
|
||||||
|
other => {
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"commands 注册表的顶层配置必须是 Table,实际检测到: {}",
|
||||||
|
other.type_name()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut commands = HashMap::new();
|
||||||
|
|
||||||
|
for pair in root_tbl.pairs::<Value, Value>() {
|
||||||
|
let (cmd_name, cmd_entry) = pair?;
|
||||||
|
|
||||||
|
let cmd_name = validators::validate_command_name(&cmd_name)?;
|
||||||
|
// 2. 校验 entry 是否是 Table
|
||||||
|
if !cmd_entry.is_table() {
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"子命令 '{cmd_name}' 的配置必须是 Table,实际检测到: {}",
|
||||||
|
cmd_entry.type_name()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
// 3. 直接交由子命令解析,外层负责补充错误上下文
|
||||||
|
let cmd_def = MrSubCommand::from_lua(cmd_entry, lua).map_err(|err| {
|
||||||
|
validation_error(format!("子命令 '{cmd_name}' 配置解析失败:\n{err}"))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
commands.insert(cmd_name, cmd_def);
|
||||||
|
}
|
||||||
|
Ok(Self { commands })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[derive(Debug, Default, Clone)]
|
||||||
|
pub struct MrSubCommand {
|
||||||
|
/// 命令处理函数:必须是 Lua Function
|
||||||
|
pub(crate) module: String,
|
||||||
|
/// 命令行说明:必须是普通文本字符串
|
||||||
|
pub(crate) description: String ,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromLua for MrSubCommand {
|
||||||
|
fn from_lua(value: Value, _lua: &Lua) -> mlua::Result<Self> {
|
||||||
|
let table = match value {
|
||||||
|
Value::Table(t) => t,
|
||||||
|
other => {
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"配置必须是 Table,实际检测到: {}",
|
||||||
|
other.type_name()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// validators::LuaValidator::parse_command_entry(&tbl)
|
||||||
|
for pair in table.pairs::<Value, Value>() {
|
||||||
|
let (key, _) = pair?;
|
||||||
|
let key_str = validators::validate_command_name(&key)?;
|
||||||
|
|
||||||
|
if !ALLOWED_KEYS.contains(&key_str.as_str()) {
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"包含未知字段 '{key_str}'。\n\
|
||||||
|
==> 合法字段仅支持: {}\n\
|
||||||
|
==> 请检查是否存在拼写手误(例如把 handler 写成了 handle/handlr)",
|
||||||
|
ALLOWED_KEYS.join(", ")
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let handler_val = table.get::<Value>("handler")?;
|
||||||
|
// let handler_func = match handler_val {
|
||||||
|
// Value::Function(f) => f,
|
||||||
|
// Value::Boolean(true) => {
|
||||||
|
// return Err(validation_error(
|
||||||
|
// "子命令 handler 返回了布尔值 true。\n\
|
||||||
|
// ==>排查提示:脚本已成功加载,但未返回函数。\n\
|
||||||
|
// ==>请在末尾加上 'return function(args) ... end'。",
|
||||||
|
// ));
|
||||||
|
// }
|
||||||
|
// Value::Nil => {
|
||||||
|
// return Err(validation_error(
|
||||||
|
// "子命令缺少必填字段 handler(或对应脚本未返回函数)",
|
||||||
|
// ));
|
||||||
|
// }
|
||||||
|
// other => {
|
||||||
|
// return Err(validation_error(format!(
|
||||||
|
// "'handler' 必须是函数 (function),实际类型是: {}",
|
||||||
|
// other.type_name()
|
||||||
|
// )));
|
||||||
|
// }
|
||||||
|
// };
|
||||||
|
let module = match handler_val {
|
||||||
|
Value::Table(t) if t.get::<bool>("__is_lazy_command").unwrap_or(false) => {
|
||||||
|
t.get::<String>("module")?
|
||||||
|
}
|
||||||
|
Value::String(s) => s.to_str()?.to_string(), // 同时兼容直接写字符串的情况
|
||||||
|
other => {
|
||||||
|
return Err(mlua::Error::runtime(format!(
|
||||||
|
"handler 必须通过 command(\"xxx\") 声明,实际为 {}",
|
||||||
|
other.type_name()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 可选字段: args(缺失或 nil 时默认空列表;保留空字符串参数,与提权路径的 "" 语义一致)
|
||||||
|
let description_val = table.get::<Value>("description")?;
|
||||||
|
let description = match description_val {
|
||||||
|
Value::Nil => String::new(),
|
||||||
|
Value::String(s) => s.to_str()?.to_string(),
|
||||||
|
other => {
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"必须是字符串文本,实际类型是 {}",
|
||||||
|
other.type_name()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// let handler = lua.create_registry_value(handler_func)?;
|
||||||
|
Ok(Self {
|
||||||
|
module,
|
||||||
|
description,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
2
mirror-cli/src/commands/mod.rs
Normal file
2
mirror-cli/src/commands/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
pub(crate) mod builtin;
|
||||||
|
pub(crate) mod dynamic;
|
||||||
14
mirror-cli/src/main.rs
Normal file
14
mirror-cli/src/main.rs
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
mod app;
|
||||||
|
mod cli;
|
||||||
|
mod commands;
|
||||||
|
mod validators;
|
||||||
|
|
||||||
|
use std::process::ExitCode;
|
||||||
|
|
||||||
|
fn main() -> ExitCode {
|
||||||
|
if let Err(err) = app::run() {
|
||||||
|
eprintln!("\x1b[31m[mr error]\x1b[0m {:#}", err);
|
||||||
|
return ExitCode::FAILURE; // 返回退出码 1
|
||||||
|
}
|
||||||
|
ExitCode::SUCCESS // 返回退出码 0
|
||||||
|
}
|
||||||
41
mirror-cli/src/validators.rs
Normal file
41
mirror-cli/src/validators.rs
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
use mirror_core::error::validation_error;
|
||||||
|
use mlua::Value;
|
||||||
|
|
||||||
|
pub fn validate_command_name(name: &Value) -> mlua::Result<String> {
|
||||||
|
let name_str = match name {
|
||||||
|
Value::String(s) => s
|
||||||
|
.to_str()
|
||||||
|
.map_err(|_| validation_error("子命令名称必须是合法的 UTF-8 字符串"))?
|
||||||
|
.to_string(),
|
||||||
|
other => {
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"命令行键名类型错误:期望 string,实际是 {}",
|
||||||
|
other.type_name()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let trimmed = name_str.trim();
|
||||||
|
if trimmed.is_empty() {
|
||||||
|
return Err(validation_error("子命令名称不能为空字符串"));
|
||||||
|
}
|
||||||
|
// 2. 禁止包含空格与不可见控制符(否则 shell 与 clap 无法正确定位)
|
||||||
|
if name_str.contains(|c: char| c.is_whitespace()) {
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"子命令名称 [{name_str}] 非法:命令名不能包含空格或空白字符"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
if name_str.contains('=') {
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"子命令名称 [{}] 不能包含 '='",
|
||||||
|
name_str
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
if name_str.contains('\0') {
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"子命令名称 [{}] 不能包含 NUL 字符",
|
||||||
|
name_str
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(name_str)
|
||||||
|
}
|
||||||
16
mirror-core/Cargo.toml
Normal file
16
mirror-core/Cargo.toml
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
[package]
|
||||||
|
name = "mirror-core"
|
||||||
|
version = { workspace = true }
|
||||||
|
edition = { workspace = true }
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
anyhow = { workspace = true }
|
||||||
|
mlua = { workspace = true }
|
||||||
|
dunce = { workspace = true }
|
||||||
|
tinyjson = { workspace = true }
|
||||||
|
windows-sys = { workspace = true }
|
||||||
|
serde = { workspace = true }
|
||||||
|
# 日志
|
||||||
|
tracing = { workspace = true }
|
||||||
|
tracing-subscriber = { workspace = true }
|
||||||
|
tracing-appender = { workspace = true }
|
||||||
25
mirror-core/src/error.rs
Normal file
25
mirror-core/src/error.rs
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
// 构造一个带上下文的 FromLua 转换错误,便于定位配置问题
|
||||||
|
/// 配置校验错误
|
||||||
|
pub fn validation_error(message: impl Into<String>) -> mlua::Error {
|
||||||
|
mlua::Error::RuntimeError(message.into())
|
||||||
|
}
|
||||||
|
/// 将底层 Lua 语法错误转换为用户友好的提示
|
||||||
|
pub fn syntax_error(err: mlua::Error) -> mlua::Error {
|
||||||
|
match &err {
|
||||||
|
mlua::Error::SyntaxError { message, .. } => {
|
||||||
|
if message.contains("invalid escape sequence") || message.contains("unfinished string")
|
||||||
|
{
|
||||||
|
return validation_error(format!(
|
||||||
|
"配置文件语法错误:检测到非法的字符串转义。\n\
|
||||||
|
提示:在 Windows 路径末尾或字符串中使用反斜杠 '\\' 时:\n\
|
||||||
|
1. 请使用双反斜杠转义,例如: \"D:\\\\CNWei\\\\CNW\\\\Rust\\\\\"\n\
|
||||||
|
2. 或使用 Lua 原始字符串 (Raw String),例如: [[D:\\CNWei\\CNW\\Rust\\]]\n\
|
||||||
|
底层错误: {}",
|
||||||
|
message
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
err
|
||||||
|
}
|
||||||
@@ -5,49 +5,53 @@ use tracing::debug;
|
|||||||
pub struct Layout {
|
pub struct Layout {
|
||||||
pub base_dir: PathBuf,
|
pub base_dir: PathBuf,
|
||||||
pub bin_dir: PathBuf,
|
pub bin_dir: PathBuf,
|
||||||
pub tools_dir: PathBuf,
|
pub target_name: String,
|
||||||
pub lua_file: PathBuf,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Layout {
|
impl Layout {
|
||||||
/// 自动解析目录布局:
|
/// 自动解析目录布局:
|
||||||
/// 1. 优先使用环境变量 RSHIM_HOME
|
/// 1. 优先使用环境变量 MIRROR_HOME
|
||||||
/// 2. 兜底回退到当前垫片可执行文件所在目录推断 (exe -> bin -> root)
|
/// 2. 兜底回退到当前垫片可执行文件所在目录推断 (exe -> bin -> root)
|
||||||
pub fn discover(current_exe: &Path) -> Result<Self> {
|
pub fn from(current_exe: &Path) -> Result<Self> {
|
||||||
|
let target_name = current_exe
|
||||||
|
.file_stem()
|
||||||
|
.and_then(|s| s.to_str())
|
||||||
|
.with_context(|| format!("无法从路径 [{}] 提取有效的程序名称", current_exe.display()))?
|
||||||
|
.to_lowercase();
|
||||||
|
|
||||||
// 策略 1: 环境变量优先
|
// 策略 1: 环境变量优先
|
||||||
if let Ok(home_val) = env::var("MIMIC_HOME") {
|
if let Ok(home_val) = env::var("MIRROR_HOME") {
|
||||||
let trimmed = home_val.trim();
|
let trimmed = home_val.trim();
|
||||||
if !trimmed.is_empty() {
|
if !trimmed.is_empty() {
|
||||||
debug!(home = %trimmed, "检测到 MIMIC_HOME,采用环境变量配置");
|
|
||||||
return Self::from_base_dir(PathBuf::from(trimmed));
|
debug!(home = %trimmed, "检测到 MIRROR_HOME,采用环境变量配置");
|
||||||
|
|
||||||
|
return Self::from_base_dir(PathBuf::from(trimmed), target_name);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 策略 2: 相对路径自动推断兜底
|
// 策略 2: 相对路径自动推断兜底
|
||||||
debug!("未配置 MIMIC_HOME,尝试从当前可执行文件路径推断根目录");
|
debug!("未配置 MIRROR_HOME,尝试从当前可执行文件路径推断根目录");
|
||||||
Self::from_executable(current_exe)
|
Self::from_executable(current_exe, target_name)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 基于确定的根目录构建完整布局
|
/// 基于确定的根目录构建完整布局
|
||||||
fn from_base_dir(base_dir: PathBuf) -> Result<Self> {
|
fn from_base_dir(base_dir: PathBuf, target_name: String) -> Result<Self> {
|
||||||
if !base_dir.is_dir() {
|
if !base_dir.is_dir() {
|
||||||
bail!("指定的根目录不存在或不是有效目录: [{}]", base_dir.display());
|
bail!("指定的根目录不存在或不是有效目录: [{}]", base_dir.display());
|
||||||
}
|
}
|
||||||
|
|
||||||
let bin_dir = base_dir.join("bin");
|
let bin_dir = base_dir.join("bin");
|
||||||
let tools_dir = base_dir.join("tools");
|
|
||||||
let lua_file = base_dir.join("mimic.lua");
|
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
base_dir,
|
base_dir,
|
||||||
bin_dir,
|
bin_dir,
|
||||||
tools_dir,
|
target_name,
|
||||||
lua_file,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 从当前可执行文件解析 shim 安装目录布局
|
/// 从当前可执行文件解析 shim 安装目录布局
|
||||||
fn from_executable(exe_path: &Path) -> Result<Self> {
|
fn from_executable(exe_path: &Path, target_name: String) -> Result<Self> {
|
||||||
// let exe_path = exe_path.as_ref();
|
// let exe_path = exe_path.as_ref();
|
||||||
let bin_dir = exe_path
|
let bin_dir = exe_path
|
||||||
.parent()
|
.parent()
|
||||||
@@ -60,8 +64,9 @@ impl Layout {
|
|||||||
.parent()
|
.parent()
|
||||||
.with_context(|| format!("无法获取 bin 目录 [{}] 的父级 root 目录", bin_dir.display()))?
|
.with_context(|| format!("无法获取 bin 目录 [{}] 的父级 root 目录", bin_dir.display()))?
|
||||||
.to_path_buf();
|
.to_path_buf();
|
||||||
|
|
||||||
debug!("base_dir 目录 {}", base_dir.display());
|
debug!("base_dir 目录 {}", base_dir.display());
|
||||||
|
|
||||||
Self::from_base_dir(base_dir)
|
Self::from_base_dir(base_dir, target_name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
14
mirror-core/src/lib.rs
Normal file
14
mirror-core/src/lib.rs
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
pub mod error;
|
||||||
|
mod layout;
|
||||||
|
mod logger;
|
||||||
|
mod runtime;
|
||||||
|
mod utils;
|
||||||
|
mod validators;
|
||||||
|
|
||||||
|
pub use layout::Layout;
|
||||||
|
// pub use mirror_shim::mirror::Mirror;
|
||||||
|
pub use runtime::LuaRuntime;
|
||||||
|
|
||||||
|
pub use logger::{init_logging_from, LogLevel, Logger};
|
||||||
|
// pub use mirror_shim::utils::{lua_string_2_os_string, normalize_path_for_lua, parse_tokens};
|
||||||
|
pub use validators::validate_command_name;
|
||||||
185
mirror-core/src/logger.rs
Normal file
185
mirror-core/src/logger.rs
Normal file
@@ -0,0 +1,185 @@
|
|||||||
|
use crate::Layout;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use std::fs;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::str::FromStr;
|
||||||
|
use tracing_appender::non_blocking::{NonBlocking, WorkerGuard};
|
||||||
|
use tracing_subscriber::layer::SubscriberExt;
|
||||||
|
use tracing_subscriber::util::SubscriberInitExt;
|
||||||
|
use tracing_subscriber::{EnvFilter, fmt};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Deserialize, Default)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum LogLevel {
|
||||||
|
Off,
|
||||||
|
Error,
|
||||||
|
#[default]
|
||||||
|
Warn,
|
||||||
|
Info,
|
||||||
|
Debug,
|
||||||
|
Trace,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for LogLevel {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
write!(f, "{}", self.as_str())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LogLevel {
|
||||||
|
/// 是否需要激活写盘排查模式(Info 及以上更详细的级别)
|
||||||
|
pub fn is_verbose(&self) -> bool {
|
||||||
|
*self >= LogLevel::Info
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_str(&self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
LogLevel::Off => "off",
|
||||||
|
LogLevel::Error => "error",
|
||||||
|
LogLevel::Warn => "warn",
|
||||||
|
LogLevel::Info => "info",
|
||||||
|
LogLevel::Debug => "debug",
|
||||||
|
LogLevel::Trace => "trace",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl FromStr for LogLevel {
|
||||||
|
type Err = String;
|
||||||
|
|
||||||
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||||
|
match s.to_ascii_lowercase().as_str() {
|
||||||
|
"off" => Ok(LogLevel::Off),
|
||||||
|
"error" => Ok(LogLevel::Error),
|
||||||
|
"warn" => Ok(LogLevel::Warn),
|
||||||
|
"info" => Ok(LogLevel::Info),
|
||||||
|
"debug" => Ok(LogLevel::Debug),
|
||||||
|
"trace" => Ok(LogLevel::Trace),
|
||||||
|
_ => Err(format!(
|
||||||
|
"无效的日志级别 '{s}',可选值为: off, error, warn, info, debug, trace"
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Default)]
|
||||||
|
pub struct Logger {
|
||||||
|
#[serde(default)]
|
||||||
|
pub level: LogLevel,
|
||||||
|
pub log_dir: Option<PathBuf>,
|
||||||
|
}
|
||||||
|
impl Logger {
|
||||||
|
/// 零依赖解析 ini / key-value 文本内容
|
||||||
|
pub fn parse_ini(content: &str) -> Self {
|
||||||
|
let mut logger = Self::default();
|
||||||
|
|
||||||
|
for line in content.lines() {
|
||||||
|
let line = line.trim();
|
||||||
|
// 跳过空行、注释行 (# 或 ;) 和 section 头 ([...])
|
||||||
|
if line.is_empty()
|
||||||
|
|| line.starts_with('#')
|
||||||
|
|| line.starts_with(';')
|
||||||
|
|| line.starts_with('[')
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some((key, val)) = line.split_once('=') {
|
||||||
|
let key = key.trim();
|
||||||
|
let val = val.trim().trim_matches('"').trim_matches('\'');
|
||||||
|
|
||||||
|
match key {
|
||||||
|
"level" => {
|
||||||
|
if let Ok(lvl) = LogLevel::from_str(val) {
|
||||||
|
logger.level = lvl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"log_dir" => {
|
||||||
|
if !val.is_empty() {
|
||||||
|
logger.log_dir = Some(PathBuf::from(val));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// 基于 Layout 自动寻址 mirror.toml 并初始化日志系统。
|
||||||
|
/// 仅在开启详细日志(如 info/debug/trace)时激活异步文件记录并返回 `WorkerGuard`。
|
||||||
|
pub fn init_logging_from(layout: &Layout) -> Option<WorkerGuard> {
|
||||||
|
// 1. 在 layout.base_dir 目录下寻找 log.toml
|
||||||
|
// let config_path = layout.base_dir.join("mirror.toml");
|
||||||
|
let config_path = layout.base_dir.join("mirror.ini");
|
||||||
|
|
||||||
|
// 读取配置文件(如不存在或解析失败,降级回退到默认设置)
|
||||||
|
let config = if config_path.exists() {
|
||||||
|
fs::read_to_string(&config_path)
|
||||||
|
.map(|s| Logger::parse_ini(&s))
|
||||||
|
// .ok()
|
||||||
|
// .and_then(|s| toml::from_str::<Logger>(&s).ok())
|
||||||
|
.unwrap_or_default()
|
||||||
|
} else {
|
||||||
|
Logger::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
// 1. 优先读取环境变量 MIRROR_LOG_LEVEL,解析失败或未设置则退回到 config.level
|
||||||
|
let effective_level = std::env::var("MIRROR_LOG_LEVEL")
|
||||||
|
.ok()
|
||||||
|
.and_then(|val| LogLevel::from_str(&val).ok())
|
||||||
|
.unwrap_or(config.level);
|
||||||
|
if effective_level == LogLevel::Off {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let filter = EnvFilter::new(effective_level.as_str());
|
||||||
|
// 基础终端输出层
|
||||||
|
let stderr_layer = fmt::layer().with_writer(std::io::stderr).with_target(false);
|
||||||
|
|
||||||
|
// 2. 根据强类型枚举判断是否激活落盘模式
|
||||||
|
if effective_level.is_verbose() {
|
||||||
|
let (non_blocking, guard) = create_file_appender(layout, config.log_dir);
|
||||||
|
let file_layer = fmt::layer()
|
||||||
|
.with_writer(non_blocking)
|
||||||
|
.with_ansi(false)
|
||||||
|
.with_target(false);
|
||||||
|
|
||||||
|
let _ = tracing_subscriber::registry()
|
||||||
|
.with(filter)
|
||||||
|
.with(stderr_layer)
|
||||||
|
.with(file_layer)
|
||||||
|
.try_init();
|
||||||
|
|
||||||
|
Some(guard)
|
||||||
|
} else {
|
||||||
|
let _ = tracing_subscriber::registry()
|
||||||
|
.with(filter)
|
||||||
|
.with(stderr_layer)
|
||||||
|
.try_init();
|
||||||
|
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_file_appender(
|
||||||
|
layout: &Layout,
|
||||||
|
log_dir_override: Option<PathBuf>,
|
||||||
|
) -> (NonBlocking, WorkerGuard) {
|
||||||
|
let output_dir = match log_dir_override {
|
||||||
|
Some(user_path) => {
|
||||||
|
if user_path.is_relative() {
|
||||||
|
layout.base_dir.join(user_path)
|
||||||
|
} else {
|
||||||
|
user_path
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => layout.base_dir.join("logs"),
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Err(err) = fs::create_dir_all(&output_dir) {
|
||||||
|
eprintln!("[WARN] 创建日志目录 {} 失败: {}", output_dir.display(), err);
|
||||||
|
}
|
||||||
|
|
||||||
|
let file_appender = tracing_appender::rolling::daily(output_dir, "mirror.log");
|
||||||
|
tracing_appender::non_blocking(file_appender)
|
||||||
|
}
|
||||||
@@ -1,15 +1,13 @@
|
|||||||
use crate::{ShimConfig, Layout};
|
use crate::Layout;
|
||||||
use anyhow::{Context, Result, anyhow, bail};
|
use crate::error::syntax_error;
|
||||||
|
use crate::utils::normalize_path_for_lua;
|
||||||
|
use anyhow::{Context, Result};
|
||||||
use mlua::{FromLua, Lua, StdLib, Table, Value};
|
use mlua::{FromLua, Lua, StdLib, Table, Value};
|
||||||
use std::ffi::OsStr;
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use std::{env, fs};
|
use std::{env, fs};
|
||||||
/// 将 Path 转换为适合 Lua 使用的安全字符串路径
|
use tracing::{debug, trace, warn};
|
||||||
fn normalize_path_for_lua(path: &Path) -> String {
|
|
||||||
// 自动将 Windows UNC 规范路径转回传统路径
|
const MIRROR_DIR: &str = "__MIRROR_DIR__";
|
||||||
let simplified = dunce::simplified(path);
|
|
||||||
simplified.to_string_lossy().replace('\\', "/")
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct LuaRuntime {
|
pub struct LuaRuntime {
|
||||||
lua: Lua,
|
lua: Lua,
|
||||||
@@ -25,20 +23,96 @@ impl LuaRuntime {
|
|||||||
)
|
)
|
||||||
.context("初始化 Lua 失败")?;
|
.context("初始化 Lua 失败")?;
|
||||||
|
|
||||||
let globals = lua.globals();
|
|
||||||
|
|
||||||
// 统一使用 POSIX 风格路径规范化路径字符串
|
// 统一使用 POSIX 风格路径规范化路径字符串
|
||||||
let base_dir = normalize_path_for_lua(&layout.base_dir);
|
let base_dir = normalize_path_for_lua(&layout.base_dir);
|
||||||
let tools_dir = normalize_path_for_lua(&layout.tools_dir);
|
// let tools_dir = normalize_path_for_lua(&layout.tools_dir);
|
||||||
|
|
||||||
// 1. 注入锚点变量 __SHIM_DIR__(shim 安装根目录)
|
// 1. 注入锚点变量 __MIRROR_DIR__(shim 安装根目录)
|
||||||
globals
|
Self::register_mirror_dir(&lua, &base_dir)?;
|
||||||
.set("__SHIM_DIR__", base_dir.clone())
|
|
||||||
.context("设置 __SHIM_DIR__ 环境变量失败")?;
|
|
||||||
|
|
||||||
// 2. 安全暴露 get_env 供配置读取环境变量
|
// 2. 安全暴露 get_env 供配置读取环境变量
|
||||||
// 返回按平台路径分隔符拆分后的段数组(自动剥离引号包裹),
|
// 返回按平台路径分隔符拆分后的段数组(自动剥离引号包裹),
|
||||||
// 便于 PATH 等列表变量直接嵌入数组:PATH = { prefix, get_env("PATH") }
|
// 便于 PATH 等列表变量直接嵌入数组:PATH = { prefix, get_env("PATH") }
|
||||||
|
Self::register_get_env(&lua)?;
|
||||||
|
// 3. 初始化并配置安全/容错的 require 机制
|
||||||
|
Self::setup_require(&lua, &base_dir)?;
|
||||||
|
|
||||||
|
Ok(Self { lua })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 执行指定脚本文件,直接返回完整的 Lua Table
|
||||||
|
pub fn eval_script<T: FromLua>(&self, path: impl AsRef<Path>) -> Result<T> {
|
||||||
|
let path = path.as_ref();
|
||||||
|
|
||||||
|
let bytes =
|
||||||
|
fs::read(path).with_context(|| format!("无法读取配置文件: {}", path.display()))?;
|
||||||
|
|
||||||
|
let code = String::from_utf8(bytes).with_context(|| {
|
||||||
|
format!(
|
||||||
|
"{} 不是有效的 UTF-8 文件(请将 Lua 配置文件保存为 UTF-8 编码)",
|
||||||
|
path.display()
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
debug!("code {:?}", code);
|
||||||
|
// 使用 @<path> 格式标记 Chunk 名称,确保 Lua 报错时能精确回溯到对应的源文件名与行号。
|
||||||
|
let chunk_name = format!("@{}", path.display());
|
||||||
|
|
||||||
|
self.lua
|
||||||
|
.load(&code)
|
||||||
|
.set_name(&chunk_name)
|
||||||
|
.eval::<T>()
|
||||||
|
.map_err(syntax_error)
|
||||||
|
.with_context(|| format!("执行 {} 配置文件失败: {}", chunk_name,path.display()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 传入注册表的 handler key 与命令行原始参数,内部完成调用
|
||||||
|
pub fn call_handler(
|
||||||
|
&self,
|
||||||
|
handler_key: &mlua::RegistryKey,
|
||||||
|
args: Vec<String>,
|
||||||
|
) -> Result<()> {
|
||||||
|
let handler: mlua::Function = self.lua.registry_value(handler_key)?;
|
||||||
|
let lua_args = self.lua.create_sequence_from(args)?;
|
||||||
|
|
||||||
|
if let Err(err) = handler.call::<()>(lua_args) {
|
||||||
|
let msg = err.to_string();
|
||||||
|
// 内部消化类似 argparse 的帮助退出信号
|
||||||
|
if msg.contains("__ARGPARSE_HELP__") {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
anyhow::bail!("{msg}");
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn require_and_run(&self, module_name: &str, raw_args: Vec<String>) -> Result<()> {
|
||||||
|
let require: mlua::Function = self.lua.globals().get("require")?;
|
||||||
|
let handler_val: mlua::Value = require.call(module_name)?;
|
||||||
|
|
||||||
|
let func = match handler_val {
|
||||||
|
mlua::Value::Function(f) => f,
|
||||||
|
other => anyhow::bail!("模块 '{module_name}' 必须返回一个函数,实际为 {}", other.type_name()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let lua_args = self.lua.create_sequence_from(raw_args)?;
|
||||||
|
func.call::<()>(lua_args)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
impl LuaRuntime {
|
||||||
|
/// 注入全局锚点变量
|
||||||
|
fn register_mirror_dir(lua: &Lua, base_dir: &str) -> Result<()> {
|
||||||
|
lua.globals()
|
||||||
|
.set(MIRROR_DIR, base_dir)
|
||||||
|
.context(format!("设置 {MIRROR_DIR} 环境变量失败"))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
///注入 get_env 供配置读取环境变量
|
||||||
|
fn register_get_env(lua: &Lua) -> Result<()> {
|
||||||
|
let globals = lua.globals();
|
||||||
let get_env = lua
|
let get_env = lua
|
||||||
.create_function(|lua, key: String| -> mlua::Result<Table> {
|
.create_function(|lua, key: String| -> mlua::Result<Table> {
|
||||||
// 缺失变量视为空字符串,拆分后得到空表(不贡献任何路径段)
|
// 缺失变量视为空字符串,拆分后得到空表(不贡献任何路径段)
|
||||||
@@ -73,37 +147,42 @@ impl LuaRuntime {
|
|||||||
globals
|
globals
|
||||||
.set("get_env", get_env)
|
.set("get_env", get_env)
|
||||||
.context("挂载 get_env 全局函数失败")?;
|
.context("挂载 get_env 全局函数失败")?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 配置 package.path 并包装 require,拦截加载失败以提高容错性
|
||||||
|
fn setup_require(lua: &Lua, base_dir: &str) -> Result<()> {
|
||||||
|
let globals = lua.globals();
|
||||||
|
|
||||||
|
// 1. 安全加固并拓展 package 搜索路径
|
||||||
|
let package = globals.get::<Table>("package")?;
|
||||||
|
|
||||||
// 3. 配置 package.path,确保 require 行为正常
|
|
||||||
if let Ok(package) = globals.get::<Table>("package") {
|
|
||||||
let _ = package.set("cpath", "");
|
let _ = package.set("cpath", "");
|
||||||
let _ = package.set("loadlib", Value::Nil);
|
let _ = package.set("loadlib", Value::Nil);
|
||||||
|
|
||||||
if let Ok(path) = package.get::<String>("path") {
|
let commands_dir = format!("{}/commands", base_dir);
|
||||||
let new_path = format!(
|
let vendor_dir = format!("{}/vendor", base_dir);
|
||||||
"{};{}/?.lua;{}/?/init.lua;{}/?.lua;{}/?/init.lua",
|
|
||||||
path, base_dir, base_dir, tools_dir, tools_dir
|
|
||||||
);
|
|
||||||
let _ = package.set("path", new_path);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4. 包装 require:配置模块缺失/加载失败时记录日志并跳过该条目,
|
let path = package.get::<String>("path")?;
|
||||||
// 而不是让整个 mimic.lua 解析失败(排查问题时日志可见)
|
let new_path = format!(
|
||||||
|
"{};{}/?.lua;{}/?/init.lua;{}/?.lua;{}/?/init.lua;{}/?.lua;{}/?/init.lua;",
|
||||||
|
path, base_dir, base_dir, commands_dir, commands_dir, vendor_dir, vendor_dir
|
||||||
|
);
|
||||||
|
|
||||||
|
debug!("重新写入的 package 查找路径");
|
||||||
|
package.set("path", new_path)?;
|
||||||
|
|
||||||
|
// 2. 获取原生 require 并通过闭包直接持有(无需向全局表注入备份变量)
|
||||||
let original_require: mlua::Function = globals
|
let original_require: mlua::Function = globals
|
||||||
.get("require")
|
.get("require")
|
||||||
.context("获取内置 require 函数失败")?;
|
.context("获取内置 require 函数失败")?;
|
||||||
globals
|
|
||||||
.set("_rshim_original_require", &original_require)
|
|
||||||
.context("备份原始 require 函数失败")?;
|
|
||||||
|
|
||||||
let wrapped_require = lua
|
let wrapped_require = lua
|
||||||
.create_function(|lua, module: String| -> mlua::Result<Value> {
|
.create_function(move |_lua, module: String| -> mlua::Result<Value> {
|
||||||
let original: mlua::Function = lua.globals().get("_rshim_original_require")?;
|
match original_require.call::<Value>(module.as_str()) {
|
||||||
match original.call::<Value>(module.clone()) {
|
|
||||||
Ok(value) => Ok(value),
|
Ok(value) => Ok(value),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
tracing::warn!(
|
warn!(
|
||||||
module = %module,
|
module = %module,
|
||||||
error = %e,
|
error = %e,
|
||||||
"配置模块加载失败,已跳过该条目(可在独立配置文件中定义)"
|
"配置模块加载失败,已跳过该条目(可在独立配置文件中定义)"
|
||||||
@@ -114,51 +193,25 @@ impl LuaRuntime {
|
|||||||
})
|
})
|
||||||
.context("创建包装版 require 函数失败")?;
|
.context("创建包装版 require 函数失败")?;
|
||||||
|
|
||||||
|
// 3. 覆盖全局 require
|
||||||
globals
|
globals
|
||||||
.set("require", wrapped_require)
|
.set("require", wrapped_require)
|
||||||
.context("重载 require 函数失败")?;
|
.context("重载 require 函数失败")?;
|
||||||
|
|
||||||
Ok(Self { lua })
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 执行指定脚本文件,直接返回完整的 Lua Table
|
|
||||||
pub fn eval_script<T: FromLua>(&self, path: impl AsRef<Path>) -> Result<T> {
|
|
||||||
let path = path.as_ref();
|
|
||||||
// println!("path {:?}", path);
|
|
||||||
let bytes =
|
|
||||||
fs::read(path).with_context(|| format!("无法读取配置文件: {}", path.display()))?;
|
|
||||||
|
|
||||||
let code = String::from_utf8(bytes).with_context(|| {
|
|
||||||
format!(
|
|
||||||
"{} 不是有效的 UTF-8 文件(请将 Lua 配置文件保存为 UTF-8 编码)",
|
|
||||||
path.display()
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
println!("code {:?}", code);
|
|
||||||
let chunk_name = format!("@{}", path.display());
|
|
||||||
|
|
||||||
self.lua
|
|
||||||
.load(&code)
|
|
||||||
.set_name(&chunk_name)
|
|
||||||
.eval::<T>()
|
|
||||||
// .map_err(|e| anyhow!(e.to_string()))
|
|
||||||
.with_context(|| format!("执行 Lua 配置文件失败: {}", path.display()))
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::Layout;
|
use crate::{Layout, };
|
||||||
|
|
||||||
fn test_layout() -> Layout {
|
fn test_layout() -> Layout {
|
||||||
let root = std::env::temp_dir().join("rshim-test-layout");
|
let root = std::env::temp_dir().join("rshim-test-layout");
|
||||||
Layout {
|
Layout {
|
||||||
base_dir: root.clone(),
|
base_dir: root.clone(),
|
||||||
bin_dir: root.join("bin"),
|
bin_dir: root.join("bin"),
|
||||||
tools_dir: root.join("tools"),
|
target_name: "muna".to_string(),
|
||||||
lua_file: Default::default(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -225,56 +278,56 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
// #[test]
|
||||||
fn path_with_get_env_joins_without_quote_error() {
|
// fn path_with_get_env_joins_without_quote_error() {
|
||||||
// 复现用户场景:PATH = { base_dir .. "/tools/numa", get_env("PATH") }
|
// // 复现用户场景:PATH = { base_dir .. "/tools/numa", get_env("PATH") }
|
||||||
// 宿主 PATH 即使含双引号,也应拆分后正常拼接,而不是报错
|
// // 宿主 PATH 即使含双引号,也应拆分后正常拼接,而不是报错
|
||||||
let runtime = LuaRuntime::new(&test_layout()).unwrap();
|
// let runtime = LuaRuntime::new(&test_layout()).unwrap();
|
||||||
let cfg: ShimConfig = runtime
|
// let cfg: Mirror = runtime
|
||||||
.lua
|
// .lua
|
||||||
.load(
|
// .load(
|
||||||
r#"
|
// r#"
|
||||||
return {
|
// return {
|
||||||
target = __SHIM_DIR__ .. "/tools/numa/numa.exe",
|
// target = __SHIM_DIR__ .. "/tools/numa/numa.exe",
|
||||||
args = { "--help" },
|
// args = { "--help" },
|
||||||
env = {
|
// env = {
|
||||||
PATH = { __SHIM_DIR__ .. "/tools/numa", get_env("PATH") }
|
// PATH = { __SHIM_DIR__ .. "/tools/numa", get_env("PATH") }
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
"#,
|
// "#,
|
||||||
)
|
// )
|
||||||
.eval()
|
// .eval()
|
||||||
.unwrap();
|
// .unwrap();
|
||||||
|
//
|
||||||
let path = cfg.env.get("PATH").unwrap().to_str().unwrap();
|
// let path = cfg.env.get("PATH").unwrap().to_str().unwrap();
|
||||||
let prefix = std::env::temp_dir()
|
// let prefix = std::env::temp_dir()
|
||||||
.join("rshim-test-layout")
|
// .join("rshim-test-layout")
|
||||||
.to_string_lossy()
|
// .to_string_lossy()
|
||||||
.replace('\\', "/")
|
// .replace('\\', "/")
|
||||||
+ "/tools/numa;";
|
// + "/tools/numa;";
|
||||||
assert!(path.starts_with(&prefix), "unexpected PATH: {path}");
|
// assert!(path.starts_with(&prefix), "unexpected PATH: {path}");
|
||||||
|
//
|
||||||
// 宿主 PATH 的段应被附加在配置前缀之后
|
// // 宿主 PATH 的段应被附加在配置前缀之后
|
||||||
let host = std::env::var("PATH").unwrap_or_default();
|
// let host = std::env::var("PATH").unwrap_or_default();
|
||||||
if !host.is_empty() {
|
// if !host.is_empty() {
|
||||||
let host_first = std::env::split_paths(&host)
|
// let host_first = std::env::split_paths(&host)
|
||||||
.next()
|
// .next()
|
||||||
.unwrap()
|
// .unwrap()
|
||||||
.to_string_lossy()
|
// .to_string_lossy()
|
||||||
.into_owned();
|
// .into_owned();
|
||||||
assert!(
|
// assert!(
|
||||||
path.contains(&host_first),
|
// path.contains(&host_first),
|
||||||
"missing host PATH segment: {host_first}"
|
// "missing host PATH segment: {host_first}"
|
||||||
);
|
// );
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
// 宿主 PATH 里引号包裹的畸形段(如 "D:\\...\\bin;")应被原样保留,
|
// // 宿主 PATH 里引号包裹的畸形段(如 "D:\\...\\bin;")应被原样保留,
|
||||||
// 而不是让整个配置加载失败
|
// // 而不是让整个配置加载失败
|
||||||
if host.contains('"') {
|
// if host.contains('"') {
|
||||||
assert!(
|
// assert!(
|
||||||
path.contains('"'),
|
// path.contains('"'),
|
||||||
"quoted host segments should be preserved"
|
// "quoted host segments should be preserved"
|
||||||
);
|
// );
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
}
|
}
|
||||||
11
mirror-core/src/utils.rs
Normal file
11
mirror-core/src/utils.rs
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
use mlua::LuaString;
|
||||||
|
use std::ffi::OsString;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
/// 将 Path 转换为适合 Lua 使用的安全字符串路径
|
||||||
|
pub fn normalize_path_for_lua(path: &Path) -> String {
|
||||||
|
// 自动将 Windows UNC 规范路径转回传统路径
|
||||||
|
let simplified = dunce::simplified(path);
|
||||||
|
simplified.to_string_lossy().replace('\\', "/")
|
||||||
|
}
|
||||||
|
|
||||||
41
mirror-core/src/validators.rs
Normal file
41
mirror-core/src/validators.rs
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
use crate::error::validation_error;
|
||||||
|
use mlua::Value;
|
||||||
|
|
||||||
|
pub fn validate_command_name(name: &Value) -> mlua::Result<String> {
|
||||||
|
let name_str = match name {
|
||||||
|
Value::String(s) => s
|
||||||
|
.to_str()
|
||||||
|
.map_err(|_| validation_error("子命令名称必须是合法的 UTF-8 字符串"))?
|
||||||
|
.to_string(),
|
||||||
|
other => {
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"命令行键名类型错误:期望 string,实际是 {}",
|
||||||
|
other.type_name()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let trimmed = name_str.trim();
|
||||||
|
if trimmed.is_empty() {
|
||||||
|
return Err(validation_error("子命令名称不能为空字符串"));
|
||||||
|
}
|
||||||
|
// 2. 禁止包含空格与不可见控制符(否则 shell 与 clap 无法正确定位)
|
||||||
|
if name_str.contains(|c: char| c.is_whitespace()) {
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"子命令名称 [{name_str}] 非法:命令名不能包含空格或空白字符"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
if name_str.contains('=') {
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"子命令名称 [{}] 不能包含 '='",
|
||||||
|
name_str
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
if name_str.contains('\0') {
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"子命令名称 [{}] 不能包含 NUL 字符",
|
||||||
|
name_str
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(name_str)
|
||||||
|
}
|
||||||
25
mirror-shim/Cargo.toml
Normal file
25
mirror-shim/Cargo.toml
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
[package]
|
||||||
|
name = "mirror-shim"
|
||||||
|
version = { workspace = true }
|
||||||
|
edition = { workspace = true }
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
mirror-core = { path = "../mirror-core" }
|
||||||
|
|
||||||
|
anyhow = { workspace = true }
|
||||||
|
|
||||||
|
windows-sys = { workspace = true }
|
||||||
|
tracing = { workspace = true }
|
||||||
|
tracing-subscriber = { workspace = true }
|
||||||
|
tracing-appender = { workspace = true }
|
||||||
|
mlua ={workspace = true}
|
||||||
|
|
||||||
|
[features]
|
||||||
|
default = []
|
||||||
|
args = []
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
[profile.release]
|
||||||
|
opt-level = "z"
|
||||||
|
panic = "abort"
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
-- mimic.lua (总控制台)
|
-- mirror.lua (总控制台)
|
||||||
-- __SHIM_DIR__ 已经在 Rust 中注入完毕,并且是正斜杠格式 (例如 C:/Tools)
|
-- __MIRROR_DIR__ 已经在 Rust 中注入完毕,并且是正斜杠格式 (例如 C:/Tools)
|
||||||
local base_dir = __SHIM_DIR__
|
base_dir = __MIRROR_DIR__
|
||||||
|
|
||||||
-- 1. 自定义局部变量,方便复用与后续维护
|
-- 1. 自定义局部变量,方便复用与后续维护
|
||||||
local python_home = base_dir .. "/tools/python39"
|
local python_home = base_dir .. "/tools/python39"
|
||||||
@@ -10,9 +10,12 @@ return {
|
|||||||
-- 1. 标准相对路径 + 正斜杠拼接 (最推荐,绿色便携)
|
-- 1. 标准相对路径 + 正斜杠拼接 (最推荐,绿色便携)
|
||||||
---------------------------------------------------
|
---------------------------------------------------
|
||||||
["numa"] = {
|
["numa"] = {
|
||||||
|
home="",
|
||||||
target = base_dir .. "/tools/numa/numa.exe",
|
target = base_dir .. "/tools/numa/numa.exe",
|
||||||
-- 追加参数
|
-- 追加参数
|
||||||
args = { "--help" },
|
args = { "--help" },
|
||||||
|
|
||||||
|
aliases = {},
|
||||||
-- 注入环境变量,使用 get_env 获取宿主机当前值
|
-- 注入环境变量,使用 get_env 获取宿主机当前值
|
||||||
env = {
|
env = {
|
||||||
PATH = { base_dir .. "/tools/numa", get_env("PATH") }
|
PATH = { base_dir .. "/tools/numa", get_env("PATH") }
|
||||||
92
mirror-shim/src/main.rs
Normal file
92
mirror-shim/src/main.rs
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
use mirror_core::{init_logging_from, Layout, };
|
||||||
|
use crate::mirror::Mirror;
|
||||||
|
use std::ffi::OsString;
|
||||||
|
use std::{env, process::exit};
|
||||||
|
use anyhow::Context;
|
||||||
|
use tracing::{debug, error};
|
||||||
|
use crate::sys::*;
|
||||||
|
|
||||||
|
pub mod sys;
|
||||||
|
pub mod mirror;
|
||||||
|
pub mod validators;
|
||||||
|
pub mod utils;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let current_exe = match env::current_exe().context("获取代理程序路径失败"){
|
||||||
|
Ok(exe) => exe,
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("垫片启动失败: {:#}", e);
|
||||||
|
exit(EXIT_FAILED_LOAD_SHIM);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let layout =match Layout::from(¤t_exe){
|
||||||
|
Ok(l) => l,
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("解析程序目录布局失败: {:#}", e);
|
||||||
|
exit(EXIT_FAILED_LOAD_SHIM);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
//初始化日志:输出到 stderr,避免污染 shim 子进程的 stdout
|
||||||
|
let _guard = init_logging_from(&layout);
|
||||||
|
|
||||||
|
debug!("=== 垫片程序启动 ===");
|
||||||
|
debug!(
|
||||||
|
exe = %current_exe.display(),
|
||||||
|
target_name = %layout.target_name,
|
||||||
|
"日志系统与布局上下文已就位"
|
||||||
|
);
|
||||||
|
|
||||||
|
// 2. 注册 Windows 控制台信号
|
||||||
|
set_console_ctrl_handler();
|
||||||
|
|
||||||
|
// 3. 解析调用参数与代理 Mirror 配置
|
||||||
|
let calling_args: Vec<_> = env::args_os().skip(1).collect();
|
||||||
|
let mr = match Mirror::load(&layout) {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(e) => {
|
||||||
|
error!("加载代理(mirror)配置时发生错误: {}", e);
|
||||||
|
exit(EXIT_FAILED_LOAD_SHIM);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let combined_args = mr.args.iter().chain(calling_args.iter());
|
||||||
|
|
||||||
|
// 构建 Command:复用 ShimConfig::to_command(含 args/env 注入),避免重复逻辑
|
||||||
|
let mut cmd = mr.to_command(combined_args);
|
||||||
|
|
||||||
|
let mut child = match cmd.spawn() {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(e) if e.raw_os_error() == Some(ERROR_ELEVATION_REQUIRED) => {
|
||||||
|
// 提权回退时需要完整参数:配置默认参数 + 调用方透传参数
|
||||||
|
let elevated_args: Vec<OsString> = cmd.get_args().map(|s| s.to_os_string()).collect();
|
||||||
|
|
||||||
|
exit(execute_elevated(
|
||||||
|
&mr.target,
|
||||||
|
&elevated_args,
|
||||||
|
Some(&mr.env),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
error!(
|
||||||
|
"启动目标程序 [{}] 时发生错误: {}",
|
||||||
|
mr.target.to_string_lossy(),
|
||||||
|
e
|
||||||
|
);
|
||||||
|
exit(EXIT_FAILED_SPAWN_PROG);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// 5. 等待子进程退出
|
||||||
|
let status = match child.wait() {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(e) => {
|
||||||
|
error!(
|
||||||
|
"等待目标程序 [{}] 执行完毕时发生错误: {}",
|
||||||
|
mr.target.to_string_lossy(),
|
||||||
|
e
|
||||||
|
);
|
||||||
|
exit(EXIT_FAILED_WAIT_PROG);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
exit(status.code().unwrap_or(EXIT_PROG_TERMINATED))
|
||||||
|
}
|
||||||
196
mirror-shim/src/mirror.rs
Normal file
196
mirror-shim/src/mirror.rs
Normal file
@@ -0,0 +1,196 @@
|
|||||||
|
use mirror_core::error::validation_error;
|
||||||
|
use crate::validators::LuaValidator;
|
||||||
|
use anyhow::{Context, Result, bail};
|
||||||
|
use mlua::{FromLua, Lua, Table, Value};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::env;
|
||||||
|
use std::ffi::OsString;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::process::Command;
|
||||||
|
use tracing::{debug, trace};
|
||||||
|
use mirror_core::{Layout, LuaRuntime};
|
||||||
|
use mirror_core::validate_command_name;
|
||||||
|
|
||||||
|
struct MasterMirror{
|
||||||
|
master:HashMap<String,Mirror>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromLua for MasterMirror {
|
||||||
|
fn from_lua(value: Value, lua: &Lua) -> mlua::Result<Self> {
|
||||||
|
let root_tbl = match value {
|
||||||
|
Value::Table(t) => t,
|
||||||
|
other => {
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"mirror 注册表的顶层配置必须是 Table,实际检测到: {}",
|
||||||
|
other.type_name()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let mut master = HashMap::new();
|
||||||
|
for pair in root_tbl.pairs::<Value, Value>() {
|
||||||
|
let (cmd_name, cmd_entry) = pair?;
|
||||||
|
|
||||||
|
let cmd_name = validate_command_name(&cmd_name)?;
|
||||||
|
// 2. 校验 entry 是否是 Table
|
||||||
|
if !cmd_entry.is_table() {
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"子命令 '{cmd_name}' 的配置必须是 Table,实际检测到: {}",
|
||||||
|
cmd_entry.type_name()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
// 3. 直接交由子命令解析,外层负责补充错误上下文
|
||||||
|
let cmd_def = Mirror::from_lua(cmd_entry, lua).map_err(|err| {
|
||||||
|
validation_error(format!("子命令 '{cmd_name}' 配置解析失败:\n{err}"))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
master.insert(cmd_name, cmd_def);
|
||||||
|
}
|
||||||
|
Ok(Self { master })
|
||||||
|
}}
|
||||||
|
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct Mirror {
|
||||||
|
pub target: PathBuf,
|
||||||
|
pub args: Vec<OsString>,
|
||||||
|
pub aliases: HashMap<String, Vec<OsString>>,
|
||||||
|
pub env: HashMap<String, OsString>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Mirror {
|
||||||
|
pub fn load(layout: &Layout) -> Result<Self> {
|
||||||
|
// 策略 1: 尝试加载全局配置文件 mirror.lua
|
||||||
|
let global_config = layout.base_dir.join("mirror.lua");
|
||||||
|
|
||||||
|
if !global_config.is_file() {
|
||||||
|
bail!("主配置文件不存在: {}", global_config.display());
|
||||||
|
}
|
||||||
|
|
||||||
|
let runtime = LuaRuntime::new(layout)?;
|
||||||
|
|
||||||
|
let root_table: Table = runtime.eval_script(&global_config)?;
|
||||||
|
|
||||||
|
let target_name = layout.target_name.as_str();
|
||||||
|
|
||||||
|
// 检查 mirror.lua 中是否存在以 target_name 命名的 Table 节点
|
||||||
|
let target_val: Mirror = root_table
|
||||||
|
.get::<Option<Mirror>>(target_name)
|
||||||
|
.with_context(|| format!("读取目标配置 [{}] 失败", target_name))?
|
||||||
|
.ok_or_else(|| {
|
||||||
|
anyhow::anyhow!(
|
||||||
|
"在 'mirror.lua' 中未找到目标程序 [{}] 的配置注册",
|
||||||
|
target_name
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
debug!(
|
||||||
|
target = %target_name,
|
||||||
|
source = %global_config.display(),
|
||||||
|
"成功从全局配置文件中匹配到目标工具"
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(target_val)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 1. 核心参数路由解析(Delegation 到 Spec 的路由逻辑)
|
||||||
|
fn resolve_args<I, S>(&self, args: I) -> Vec<OsString>
|
||||||
|
where
|
||||||
|
I: IntoIterator<Item = S>,
|
||||||
|
S: AsRef<std::ffi::OsStr>,
|
||||||
|
{
|
||||||
|
let arg_iter = args.into_iter();
|
||||||
|
|
||||||
|
// 1. 预分配容量:利用迭代器的下限提示,避免多次 Realloc
|
||||||
|
let (lower_bound, _) = arg_iter.size_hint();
|
||||||
|
let mut expanded_args: Vec<OsString> = Vec::with_capacity(lower_bound);
|
||||||
|
|
||||||
|
for i in arg_iter {
|
||||||
|
let os_str = i.as_ref();
|
||||||
|
|
||||||
|
let arg_str = os_str.to_string_lossy();
|
||||||
|
|
||||||
|
// 检查参数是否带有 mr: 前缀
|
||||||
|
if let Some(alias_key) = arg_str.strip_prefix("mr:") {
|
||||||
|
// 如果在加载期打平好的字典中找到了对应的别名,直接展开追加
|
||||||
|
if let Some(alias_values) = self.aliases.get(alias_key) {
|
||||||
|
expanded_args.extend(alias_values.iter().cloned());
|
||||||
|
} else {
|
||||||
|
// 如果找不到对应的别名,按原样参数追加
|
||||||
|
expanded_args.push(os_str.to_os_string());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 普通参数,直接追加
|
||||||
|
expanded_args.push(os_str.to_os_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
expanded_args
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_command<I, S>(&self, combined_args: I) -> Command
|
||||||
|
where
|
||||||
|
I: IntoIterator<Item = S>,
|
||||||
|
S: AsRef<std::ffi::OsStr>,
|
||||||
|
{
|
||||||
|
let mut cmd = Command::new(&self.target);
|
||||||
|
|
||||||
|
// 2. 传入预打平的别名字典,查表并展开所有以 `mr:` 为前缀的别名
|
||||||
|
let final_args = self.resolve_args(combined_args);
|
||||||
|
debug!("拼接后的命令行参数{:?}", final_args);
|
||||||
|
// 3. 将解析展开后的无环参数一次性注入 Command
|
||||||
|
cmd.args(&final_args);
|
||||||
|
|
||||||
|
// 4. 注入配置好的环境变量
|
||||||
|
for (key, val) in &self.env {
|
||||||
|
// 直接应用环境变量(Lua 端已经处理好字符串拼接或列表合并)
|
||||||
|
cmd.env(key, val);
|
||||||
|
}
|
||||||
|
|
||||||
|
cmd
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl FromLua for Mirror {
|
||||||
|
fn from_lua(value: Value, _lua: &Lua) -> mlua::Result<Self> {
|
||||||
|
// 脚本返回必须是一个 Table 变体
|
||||||
|
let table = match value {
|
||||||
|
Value::Table(t) => t,
|
||||||
|
_ => {
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"期望得到一个 Lua Table 配置对象,实际是 {}",
|
||||||
|
value.type_name()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 必填字段: target(严格限定为字符串,避免数字被 mlua 宽松转为字符串后掩盖错误)
|
||||||
|
let target = match table.get::<Option<Value>>("target")? {
|
||||||
|
None | Some(Value::Nil) => {
|
||||||
|
return Err(validation_error("缺少必填字段 target(应为字符串路径)"));
|
||||||
|
}
|
||||||
|
Some(target_val) => LuaValidator::parse_target(&target_val)?,
|
||||||
|
};
|
||||||
|
|
||||||
|
// 可选字段: args(缺失或 nil 时默认空列表;保留空字符串参数,与提权路径的 "" 语义一致)
|
||||||
|
let args = match table.get::<Option<Value>>("args")? {
|
||||||
|
None | Some(Value::Nil) => Vec::new(),
|
||||||
|
Some(args_val) => LuaValidator::parse_args(&args_val)?,
|
||||||
|
};
|
||||||
|
|
||||||
|
// 可选字段: env(只允许缺失/nil,其他类型由 Option<Table> 转换报错,不再静默忽略)
|
||||||
|
let env = match table.get::<Option<Value>>("env")? {
|
||||||
|
None | Some(Value::Nil) => HashMap::new(),
|
||||||
|
Some(env_val) => LuaValidator::parse_env(&env_val)?,
|
||||||
|
};
|
||||||
|
|
||||||
|
// 可选字段: aliases(只允许缺失/nil,其他类型由 Option<Table> 转换报错,不再静默忽略)
|
||||||
|
let aliases = match table.get::<Option<Value>>("aliases")? {
|
||||||
|
None | Some(Value::Nil) => HashMap::new(),
|
||||||
|
Some(env_val) => LuaValidator::parse_aliases(&env_val)?,
|
||||||
|
};
|
||||||
|
// println!("环境变量结果:{:?}", env);
|
||||||
|
Ok(Self {
|
||||||
|
target,
|
||||||
|
args,
|
||||||
|
aliases,
|
||||||
|
env,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
6
mirror-shim/src/sys.rs
Normal file
6
mirror-shim/src/sys.rs
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
mod win;
|
||||||
|
|
||||||
|
pub use win::{
|
||||||
|
ERROR_ELEVATION_REQUIRED, EXIT_FAILED_LOAD_SHIM, EXIT_FAILED_SPAWN_PROG, EXIT_FAILED_WAIT_PROG,
|
||||||
|
EXIT_PROG_TERMINATED, execute_elevated, set_console_ctrl_handler,
|
||||||
|
};
|
||||||
@@ -1,10 +1,8 @@
|
|||||||
use rshim::Shim;
|
|
||||||
use std::os::windows::ffi::OsStrExt;
|
use std::os::windows::ffi::OsStrExt;
|
||||||
use std::{env, ffi::CString, mem::size_of, path::Path, process::exit, ptr::null_mut};
|
use std::{env, mem::size_of, path::Path, ptr::null_mut};
|
||||||
use tracing_subscriber::{EnvFilter, fmt};
|
|
||||||
|
|
||||||
use std::ffi::{OsStr, OsString};
|
use std::ffi::{OsStr, OsString};
|
||||||
|
use tracing::error;
|
||||||
use windows_sys::Win32::UI::Shell::{SHELLEXECUTEINFOW, ShellExecuteExW};
|
use windows_sys::Win32::UI::Shell::{SHELLEXECUTEINFOW, ShellExecuteExW};
|
||||||
|
|
||||||
use windows_sys::Win32::Foundation::CloseHandle;
|
use windows_sys::Win32::Foundation::CloseHandle;
|
||||||
@@ -20,15 +18,20 @@ use windows_sys::{
|
|||||||
Threading::{GetExitCodeProcess, INFINITE, WaitForSingleObject},
|
Threading::{GetExitCodeProcess, INFINITE, WaitForSingleObject},
|
||||||
},
|
},
|
||||||
UI::{
|
UI::{
|
||||||
Shell::{
|
Shell::{SEE_MASK_NOASYNC, SEE_MASK_NOCLOSEPROCESS},
|
||||||
SEE_MASK_NOASYNC, SEE_MASK_NOCLOSEPROCESS, SHELLEXECUTEINFOA, ShellExecuteExA,
|
|
||||||
},
|
|
||||||
WindowsAndMessaging::SW_NORMAL,
|
WindowsAndMessaging::SW_NORMAL,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
core::BOOL,
|
core::BOOL,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
pub const EXIT_FAILED_LOAD_SHIM: i32 = 1;
|
||||||
|
pub const EXIT_FAILED_SPAWN_PROG: i32 = 2;
|
||||||
|
pub const EXIT_FAILED_WAIT_PROG: i32 = 3;
|
||||||
|
pub const EXIT_PROG_TERMINATED: i32 = 4;
|
||||||
|
|
||||||
|
pub const ERROR_ELEVATION_REQUIRED: i32 = 740;
|
||||||
|
|
||||||
unsafe extern "system" fn console_ctrl_handler(evt: u32) -> BOOL {
|
unsafe extern "system" fn console_ctrl_handler(evt: u32) -> BOOL {
|
||||||
match evt {
|
match evt {
|
||||||
CTRL_C_EVENT => TRUE, //eprintln!("ctrl_c handled!"),
|
CTRL_C_EVENT => TRUE, //eprintln!("ctrl_c handled!"),
|
||||||
@@ -37,81 +40,24 @@ unsafe extern "system" fn console_ctrl_handler(evt: u32) -> BOOL {
|
|||||||
CTRL_LOGOFF_EVENT => TRUE, //eprintln!("ctrl_logoff handled!"),
|
CTRL_LOGOFF_EVENT => TRUE, //eprintln!("ctrl_logoff handled!"),
|
||||||
CTRL_SHUTDOWN_EVENT => TRUE, //eprintln!("ctrl_shutdown handled!"),
|
CTRL_SHUTDOWN_EVENT => TRUE, //eprintln!("ctrl_shutdown handled!"),
|
||||||
other => {
|
other => {
|
||||||
eprintln!("未知的系统事件编号: {},未处理!", other);
|
error!("未知的系统事件编号: {},未处理!", other);
|
||||||
FALSE
|
FALSE
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const EXIT_FAILED_LOAD_SHIM: i32 = 1;
|
pub fn set_console_ctrl_handler() {
|
||||||
const EXIT_FAILED_SPAWN_PROG: i32 = 2;
|
|
||||||
const EXIT_FAILED_WAIT_PROG: i32 = 3;
|
|
||||||
const EXIT_PROG_TERMINATED: i32 = 4;
|
|
||||||
|
|
||||||
const ERROR_ELEVATION_REQUIRED: i32 = 740;
|
|
||||||
fn main() {
|
|
||||||
// 初始化日志:输出到 stderr,避免污染 shim 子进程的 stdout
|
|
||||||
fmt()
|
|
||||||
.with_writer(std::io::stderr)
|
|
||||||
.with_env_filter(
|
|
||||||
EnvFilter::try_from_env("SHIM_LOG").unwrap_or_else(|_| EnvFilter::new("warn")),
|
|
||||||
)
|
|
||||||
.init();
|
|
||||||
|
|
||||||
let res: BOOL = unsafe { SetConsoleCtrlHandler(Some(console_ctrl_handler), TRUE) };
|
let res: BOOL = unsafe { SetConsoleCtrlHandler(Some(console_ctrl_handler), TRUE) };
|
||||||
if res == FALSE {
|
if res == FALSE {
|
||||||
eprintln!("警告: 注册控制台中断事件处理器失败。");
|
error!("警告: 注册控制台中断事件处理器失败。");
|
||||||
}
|
}
|
||||||
|
|
||||||
let calling_args: Vec<_> = env::args_os().skip(1).collect();
|
|
||||||
let shim = match Shim::load() {
|
|
||||||
Ok(v) => v,
|
|
||||||
Err(e) => {
|
|
||||||
eprintln!("加载代理(shim)配置时发生错误: {}", e);
|
|
||||||
exit(EXIT_FAILED_LOAD_SHIM);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// 构建 Command:复用 ShimConfig::to_command(含 args/env 注入),避免重复逻辑
|
|
||||||
let mut cmd = shim.to_command(&calling_args);
|
|
||||||
|
|
||||||
// 提权回退时需要完整参数:配置默认参数 + 调用方透传参数
|
|
||||||
let mut args = shim.args.clone();
|
|
||||||
args.extend_from_slice(&calling_args);
|
|
||||||
|
|
||||||
let mut child = match cmd.spawn() {
|
|
||||||
Ok(v) => v,
|
|
||||||
Err(e) if e.raw_os_error() == Some(ERROR_ELEVATION_REQUIRED) => {
|
|
||||||
exit(execute_elevated(&shim.target, &args, Some(&shim.env)))
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
eprintln!(
|
|
||||||
"启动目标程序 [{}] 时发生错误: {}",
|
|
||||||
shim.target.to_string_lossy(),
|
|
||||||
e
|
|
||||||
);
|
|
||||||
exit(EXIT_FAILED_SPAWN_PROG);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let status = match child.wait() {
|
|
||||||
Ok(v) => v,
|
|
||||||
Err(e) => {
|
|
||||||
eprintln!(
|
|
||||||
"等待目标程序 [{}] 执行完毕时发生错误: {}",
|
|
||||||
shim.target.to_string_lossy(),
|
|
||||||
e
|
|
||||||
);
|
|
||||||
exit(EXIT_FAILED_WAIT_PROG);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
exit(status.code().unwrap_or(EXIT_PROG_TERMINATED))
|
|
||||||
}
|
}
|
||||||
// 辅助函数:将任意 OsStr 转换为以 \0 结尾的 UTF-16 宽字符向量 (Vec<u16>)
|
|
||||||
fn to_wide_null(s: impl AsRef<OsStr>) -> Vec<u16> {
|
fn to_wide_null(s: impl AsRef<OsStr>) -> Vec<u16> {
|
||||||
s.as_ref().encode_wide().chain(std::iter::once(0)).collect()
|
s.as_ref().encode_wide().chain(std::iter::once(0)).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn execute_elevated(
|
pub fn execute_elevated(
|
||||||
program: &Path,
|
program: &Path,
|
||||||
args: &[OsString],
|
args: &[OsString],
|
||||||
env_vars: Option<&std::collections::HashMap<String, OsString>>,
|
env_vars: Option<&std::collections::HashMap<String, OsString>>,
|
||||||
@@ -148,27 +94,7 @@ fn execute_elevated(
|
|||||||
arguments_os.push("\"");
|
arguments_os.push("\"");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// let runas = CString::new("runas").unwrap();
|
|
||||||
// let program = CString::new(program.to_str().unwrap()).unwrap();
|
|
||||||
// let mut arguments = String::new();
|
|
||||||
// for arg in args.iter() {
|
|
||||||
// arguments.push(' ');
|
|
||||||
// if arg.len() == 0 {
|
|
||||||
// arguments.push_str("\"\"");
|
|
||||||
// } else if arg.find(&[' ', '\t', '"'][..]).is_none() {
|
|
||||||
// arguments.push_str(&arg);
|
|
||||||
// } else {
|
|
||||||
// arguments.push('"');
|
|
||||||
// for c in arg.chars() {
|
|
||||||
// match c {
|
|
||||||
// '\\' => arguments.push_str("\\\\"),
|
|
||||||
// '"' => arguments.push_str("\\\""),
|
|
||||||
// c => arguments.push(c),
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// arguments.push('"');
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// 3. 准备 Windows 宽字符参数
|
// 3. 准备 Windows 宽字符参数
|
||||||
let runas = to_wide_null("runas");
|
let runas = to_wide_null("runas");
|
||||||
let program_wide = to_wide_null(program.as_os_str());
|
let program_wide = to_wide_null(program.as_os_str());
|
||||||
@@ -223,13 +149,4 @@ fn execute_elevated(
|
|||||||
}
|
}
|
||||||
|
|
||||||
exit_code as i32
|
exit_code as i32
|
||||||
|
|
||||||
// let mut code: u32 = 0;
|
|
||||||
// unsafe {
|
|
||||||
// WaitForSingleObject(info.hProcess, INFINITE);
|
|
||||||
// if GetExitCodeProcess(info.hProcess, &mut code as *mut _) == FALSE {
|
|
||||||
// return EXIT_FAILED_WAIT_PROG;
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// code as i32
|
|
||||||
}
|
}
|
||||||
225
mirror-shim/src/utils.rs
Normal file
225
mirror-shim/src/utils.rs
Normal file
@@ -0,0 +1,225 @@
|
|||||||
|
use mlua::LuaString;
|
||||||
|
use std::ffi::OsString;
|
||||||
|
|
||||||
|
/// 将 Lua 字符串转为 Rust 字符串;非 UTF-8 按系统默认的 ANSI/OEM (如 GBK) 进行安全解码
|
||||||
|
pub fn lua_string_2_os_string(s: &LuaString) -> mlua::Result<OsString> {
|
||||||
|
let raw_bytes = &s.as_bytes();
|
||||||
|
// 1. Unix 平台:直接零拷贝透传原始字节(无损支持任意编码)
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::ffi::OsStrExt;
|
||||||
|
Ok(OsStr::from_bytes(raw_bytes).to_os_string())
|
||||||
|
}
|
||||||
|
// 2. Windows 平台:优先按 UTF-8 解码,失败则按当前系统本地代码页 (ANSI/GBK) 转换
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
// 先尝试标准的 UTF-8
|
||||||
|
if let Ok(utf8_str) = std::str::from_utf8(raw_bytes) {
|
||||||
|
return Ok(OsString::from(utf8_str));
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe {
|
||||||
|
use std::os::windows::ffi::OsStringExt;
|
||||||
|
use windows_sys::Win32::Globalization::{
|
||||||
|
CP_ACP, MB_ERR_INVALID_CHARS, MultiByteToWideChar,
|
||||||
|
};
|
||||||
|
|
||||||
|
if raw_bytes.is_empty() {
|
||||||
|
return Ok(OsString::new());
|
||||||
|
}
|
||||||
|
|
||||||
|
let len = MultiByteToWideChar(
|
||||||
|
CP_ACP,
|
||||||
|
MB_ERR_INVALID_CHARS,
|
||||||
|
raw_bytes.as_ptr(),
|
||||||
|
raw_bytes.len() as i32,
|
||||||
|
std::ptr::null_mut(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
|
||||||
|
if len <= 0 {
|
||||||
|
// 构造一个带上下文的 FromLua 转换错误,便于定位配置问题
|
||||||
|
return Err(mlua::Error::FromLuaConversionError {
|
||||||
|
from: "LuaString",
|
||||||
|
to: "OsString".to_string(),
|
||||||
|
message: Some(
|
||||||
|
format!("字符串{:?}包含无效或当前系统无法识别的编码字节", s).to_string(),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut buf = vec![0u16; len as usize];
|
||||||
|
MultiByteToWideChar(
|
||||||
|
CP_ACP,
|
||||||
|
MB_ERR_INVALID_CHARS,
|
||||||
|
raw_bytes.as_ptr(),
|
||||||
|
raw_bytes.len() as i32,
|
||||||
|
buf.as_mut_ptr(),
|
||||||
|
len,
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(OsString::from_wide(&buf))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 将输入的字符串按 Shell 规则切分为独立的 CLI 参数 Token
|
||||||
|
/// - 自动过滤连续空格
|
||||||
|
/// - 支持单引号 `'...'` 和双引号 `"..."` 包裹包含空格的参数
|
||||||
|
pub fn parse_tokens(input: &str) -> Vec<OsString> {
|
||||||
|
let mut tokens = Vec::new();
|
||||||
|
let mut current_token = String::new();
|
||||||
|
let mut in_quote: Option<char> = None;
|
||||||
|
let mut chars = input.chars().peekable();
|
||||||
|
|
||||||
|
while let Some(ch) = chars.next() {
|
||||||
|
match (ch, in_quote) {
|
||||||
|
// 处理转义字符 (例如 \")
|
||||||
|
('\\', _quote) => {
|
||||||
|
if let Some(&next_ch) = chars.peek() {
|
||||||
|
let should_escape = if cfg!(windows) {
|
||||||
|
// Windows 策略:只有在转义引号、反斜杠本身时才剥离 \
|
||||||
|
// (如果在双引号内部,空格也不应该被 \ 转义)
|
||||||
|
next_ch == '"' || next_ch == '\'' || next_ch == '\\'
|
||||||
|
} else {
|
||||||
|
// Unix 策略:标准 Shell 转义(引号、反斜杠、空格等)
|
||||||
|
next_ch == '"'
|
||||||
|
|| next_ch == '\''
|
||||||
|
|| next_ch == '\\'
|
||||||
|
|| next_ch.is_whitespace()
|
||||||
|
};
|
||||||
|
|
||||||
|
if should_escape {
|
||||||
|
chars.next(); // 消耗掉下一个字符
|
||||||
|
current_token.push(next_ch);
|
||||||
|
} else {
|
||||||
|
// 保留 Windows 路径分隔符或未知转义中的 \
|
||||||
|
current_token.push('\\');
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 结尾孤立的 \
|
||||||
|
current_token.push('\\');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 遇到引号:开启或关闭引号包裹
|
||||||
|
('"' | '\'', None) => {
|
||||||
|
in_quote = Some(ch);
|
||||||
|
}
|
||||||
|
('"' | '\'', Some(q)) if q == ch => {
|
||||||
|
in_quote = None;
|
||||||
|
}
|
||||||
|
// 引号外部遇到空白字符:切分出一个完整的 Token
|
||||||
|
(ch, None) if ch.is_whitespace() => {
|
||||||
|
if !current_token.is_empty() {
|
||||||
|
tokens.push(OsString::from(std::mem::take(&mut current_token)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 其他字符或引号内部字符:直接追加
|
||||||
|
(ch, _) => {
|
||||||
|
current_token.push(ch);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 收尾最后一个 Token
|
||||||
|
if !current_token.is_empty() {
|
||||||
|
tokens.push(OsString::from(current_token));
|
||||||
|
}
|
||||||
|
|
||||||
|
tokens
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::ffi::OsString;
|
||||||
|
/// 辅助宏:简化声明与断言对比
|
||||||
|
macro_rules! assert_tokens {
|
||||||
|
($input:expr, $expected:expr) => {
|
||||||
|
let actual = parse_tokens($input);
|
||||||
|
let expected_os: Vec<OsString> = $expected.into_iter().map(OsString::from).collect();
|
||||||
|
assert_eq!(
|
||||||
|
actual, expected_os,
|
||||||
|
"\n测试输入: {:?}\n期望输出: {:?}\n实际输出: {:?}",
|
||||||
|
$input, expected_os, actual
|
||||||
|
);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn test_parse_tokens_basic_split() {
|
||||||
|
// 场景 1:基础多参数拆分(空格分隔)
|
||||||
|
assert_tokens!("cargo run --verbose", vec!["cargo", "run", "--verbose"]);
|
||||||
|
assert_tokens!("git status", vec!["git", "status"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_tokens_multi_alias_ref() {
|
||||||
|
// 场景 2:多别名混合与组合引用
|
||||||
|
assert_tokens!(
|
||||||
|
"mr:run --bin mr:base_flags",
|
||||||
|
vec!["mr:run", "--bin", "mr:base_flags"]
|
||||||
|
);
|
||||||
|
assert_tokens!(
|
||||||
|
"mr:app1 mr:app2 --flag",
|
||||||
|
vec!["mr:app1", "mr:app2", "--flag"]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_tokens_continuous_whitespaces() {
|
||||||
|
// 场景 3:连续多空格与制表符过滤
|
||||||
|
assert_tokens!(
|
||||||
|
"mr:run --bin \t my_app",
|
||||||
|
vec!["mr:run", "--bin", "my_app"]
|
||||||
|
);
|
||||||
|
assert_tokens!(" cargo build ", vec!["cargo", "build"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_tokens_double_quotes() {
|
||||||
|
// 场景 4:双引号包裹包含空格的参数
|
||||||
|
assert_tokens!(
|
||||||
|
"git commit -m \"fix a bug\"",
|
||||||
|
vec!["git", "commit", "-m", "fix a bug"]
|
||||||
|
);
|
||||||
|
assert_tokens!("echo \"hello world\"", vec!["echo", "hello world"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_tokens_single_quotes() {
|
||||||
|
// 场景 5:单引号包裹包含空格的参数
|
||||||
|
assert_tokens!(
|
||||||
|
"gcc -O2 'my file.c' -o app",
|
||||||
|
vec!["gcc", "-O2", "my file.c", "-o", "app"]
|
||||||
|
);
|
||||||
|
assert_tokens!(
|
||||||
|
"python 'script with space.py'",
|
||||||
|
vec!["python", "script with space.py"]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_tokens_escaped_characters() {
|
||||||
|
// 场景 6:反斜杠转义字符
|
||||||
|
assert_tokens!("echo hello\\ world", vec!["echo", "hello\\", "world"]);
|
||||||
|
assert_tokens!(
|
||||||
|
"echo \"hello \\\"world\\\"\"",
|
||||||
|
vec!["echo", "hello \"world\""]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_tokens_single_scalar_and_edge_cases() {
|
||||||
|
// 场景 7:单标量参数与边界情况
|
||||||
|
assert_tokens!("git", vec!["git"]);
|
||||||
|
assert_tokens!("8000", vec!["8000"]);
|
||||||
|
assert_tokens!("", Vec::<&str>::new());
|
||||||
|
assert_tokens!(" ", Vec::<&str>::new());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_tokens_unclosed_quotes() {
|
||||||
|
// 场景 8:未闭合引号的容错处理(会尽量追加到当前 Token 中)
|
||||||
|
assert_tokens!("echo \"hello world", vec!["echo", "hello world"]);
|
||||||
|
}
|
||||||
|
}
|
||||||
706
mirror-shim/src/validators.rs
Normal file
706
mirror-shim/src/validators.rs
Normal file
@@ -0,0 +1,706 @@
|
|||||||
|
use mirror_core::error::validation_error;
|
||||||
|
use anyhow::{Context, Result, anyhow};
|
||||||
|
use mlua::{LuaString, Table, Value};
|
||||||
|
use std::collections::{HashMap, HashSet};
|
||||||
|
use std::ffi::OsString;
|
||||||
|
use std::fmt;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::str::FromStr;
|
||||||
|
// use tinyjson::JsonValue;
|
||||||
|
use tracing::debug;
|
||||||
|
use crate::utils::{lua_string_2_os_string, parse_tokens};
|
||||||
|
|
||||||
|
/// Lua 值校验器:针对不同上下文定义校验规则
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum LuaValidator {
|
||||||
|
/// 目标程序路径:必须是字符串路径
|
||||||
|
Target,
|
||||||
|
/// 命令行参数元素:仅支持一维基础标量,禁止嵌套 Table
|
||||||
|
Args,
|
||||||
|
/// 环境变量值:支持基础标量及多维嵌套 Table(递归展平)
|
||||||
|
Env,
|
||||||
|
Aliases,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for LuaValidator {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Target => write!(f, "目标路径 (target)"),
|
||||||
|
Self::Args => write!(f, "命令行参数 (args)"),
|
||||||
|
Self::Env => write!(f, "环境变量 (env)"),
|
||||||
|
Self::Aliases => write!(f, "命令行别名 (aliases)"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl LuaValidator {
|
||||||
|
fn parse_sequence(&self, index: i64, item: &Value) -> mlua::Result<()> {
|
||||||
|
match item {
|
||||||
|
Value::String(_) | Value::Integer(_) | Value::Number(_) | Value::Boolean(_) => Ok(()),
|
||||||
|
Value::Table(tbl) => match self {
|
||||||
|
Self::Env | Self::Aliases => self.validate_sequence_table(tbl),
|
||||||
|
Self::Args => Err(validation_error(format!(
|
||||||
|
"{} 仅支持一维数组,不能包含嵌套 Table,索引位置: {index}",
|
||||||
|
self
|
||||||
|
))),
|
||||||
|
Self::Target => Err(validation_error(format!("{} 仅支持字符串", self))),
|
||||||
|
},
|
||||||
|
other => Err(validation_error(format!(
|
||||||
|
"{} 第 {} 个元素类型无效: {}",
|
||||||
|
self,
|
||||||
|
index,
|
||||||
|
other.type_name()
|
||||||
|
))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 校验 Table 是否为严格连续的纯数组,并递归校验其内部元素
|
||||||
|
fn validate_sequence_table(&self, tbl: &Table) -> mlua::Result<()> {
|
||||||
|
let mut index = 1i64;
|
||||||
|
|
||||||
|
// 1. 顺序遍历连续整数索引 1..N
|
||||||
|
loop {
|
||||||
|
let item: Value = tbl.raw_get(index)?;
|
||||||
|
if matches!(&item, Value::Nil) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
self.parse_sequence(index, &item)?;
|
||||||
|
|
||||||
|
index += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 查漏:校验是否存在空洞索引或字典键 (Key-Value 键值对)
|
||||||
|
for pair in tbl.pairs::<Value, Value>() {
|
||||||
|
let (key, _) = pair?;
|
||||||
|
match key {
|
||||||
|
Value::Integer(i) if i >= 1 && i < index => {} // 已遍历放行
|
||||||
|
Value::Integer(_) => {
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"{} 第 {} 个元素为 nil 或不存在(请检查漏写引号或变量未定义)",
|
||||||
|
self, index
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"{} 必须是纯列表,不能包含键值对/字典结构",
|
||||||
|
self
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 底层 NUL 字符跨平台安全检查
|
||||||
|
fn ensure_no_nul(context: &impl fmt::Display, os_str: &std::ffi::OsStr) -> mlua::Result<()> {
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::ffi::OsStrExt;
|
||||||
|
if os_str.as_bytes().contains(&0) {
|
||||||
|
return Err(conversion_error(format!(
|
||||||
|
"{} 的值不能包含 NUL 字符",
|
||||||
|
context
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
use std::os::windows::ffi::OsStrExt;
|
||||||
|
if os_str.encode_wide().any(|c| c == 0) {
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"{} 的值不能包含 NUL 字符",
|
||||||
|
context
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 【纯粹数据转换与展开】将已通过校验的 Value 递归解析为 OsString 动态数组
|
||||||
|
fn collect_value_into(&self, value: &Value, out: &mut Vec<OsString>) -> mlua::Result<()> {
|
||||||
|
match value {
|
||||||
|
Value::Nil => {}
|
||||||
|
Value::String(s) => {
|
||||||
|
let os_str = lua_string_2_os_string(s)?;
|
||||||
|
match self {
|
||||||
|
Self::Args | Self::Aliases => {
|
||||||
|
if let Some(str_ref) = os_str.to_str() {
|
||||||
|
// 使用 Tokenizer 切分空格与引号
|
||||||
|
out.extend(parse_tokens(str_ref));
|
||||||
|
} else {
|
||||||
|
// 对于无法转为 UTF-8 的特殊二进制数据,作为整体追加
|
||||||
|
out.push(os_str);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Self::Env => {
|
||||||
|
out.push(os_str);
|
||||||
|
}
|
||||||
|
Self::Target => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Value::Integer(i) => out.push(OsString::from(i.to_string())),
|
||||||
|
Value::Number(n) => {
|
||||||
|
tracing::warn!(%self, value = %n, "浮点数将按十进制格式转换为字符串");
|
||||||
|
out.push(OsString::from(n.to_string()));
|
||||||
|
}
|
||||||
|
Value::Boolean(b) => {
|
||||||
|
tracing::warn!(%self, value = %b, "布尔值将转换为字符串");
|
||||||
|
out.push(OsString::from(b.to_string()));
|
||||||
|
}
|
||||||
|
Value::Table(tbl) => {
|
||||||
|
let mut index = 1i64;
|
||||||
|
loop {
|
||||||
|
let item: Value = tbl.raw_get(index)?;
|
||||||
|
if matches!(item, Value::Nil) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
Self::collect_value_into(self, &item, out)?;
|
||||||
|
index += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => unreachable!("传入收集器的 Value 应已通过 validate 校验"),
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn parse_name(name: &Value) -> mlua::Result<String> {
|
||||||
|
let name_str = match name {
|
||||||
|
Value::String(s) => match s.to_str() {
|
||||||
|
Ok(str_ref) => str_ref.to_string(),
|
||||||
|
Err(_) => return Err(validation_error("环境变量名必须是合法的 UTF-8 字符串")),
|
||||||
|
},
|
||||||
|
other => {
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"环境变量键名类型错误:期望 string,实际是 {}",
|
||||||
|
other.type_name()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if name_str.is_empty() {
|
||||||
|
return Err(validation_error("环境变量名不能为空"));
|
||||||
|
}
|
||||||
|
if name_str.contains('=') {
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"环境变量名 [{}] 不能包含 '='",
|
||||||
|
name_str
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
if name_str.contains('\0') {
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"环境变量名 [{}] 不能包含 NUL 字符",
|
||||||
|
name_str
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(name_str)
|
||||||
|
}
|
||||||
|
fn parse_val(&self, name: &str, value: &Value) -> mlua::Result<()> {
|
||||||
|
match value {
|
||||||
|
Value::Nil
|
||||||
|
| Value::String(_)
|
||||||
|
| Value::Integer(_)
|
||||||
|
| Value::Number(_)
|
||||||
|
| Value::Boolean(_) => Ok(()),
|
||||||
|
Value::Table(tbl) => self.validate_sequence_table(tbl),
|
||||||
|
other => Err(validation_error(format!(
|
||||||
|
"{} [{}]不支持 {} 类型, 仅支持 string/number/boolean 或嵌套数组",
|
||||||
|
self,
|
||||||
|
name,
|
||||||
|
other.type_name()
|
||||||
|
))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl LuaValidator {
|
||||||
|
/// 解析并校验 `target`
|
||||||
|
pub fn parse_target(value: &Value) -> mlua::Result<PathBuf> {
|
||||||
|
let ctx = Self::Target;
|
||||||
|
match value {
|
||||||
|
Value::String(s) => {
|
||||||
|
let os_str = lua_string_2_os_string(&s)?;
|
||||||
|
Self::ensure_no_nul(&ctx, &os_str)?;
|
||||||
|
Ok(PathBuf::from(os_str))
|
||||||
|
}
|
||||||
|
Value::Nil => Err(validation_error("缺少必填字段 target(应为字符串路径)")),
|
||||||
|
other => Err(validation_error(format!(
|
||||||
|
"{} 需为有效的路径且类型必须是字符串,实际类型是 {}",
|
||||||
|
ctx,
|
||||||
|
other.type_name()
|
||||||
|
))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 解析并校验 `args`
|
||||||
|
pub fn parse_args(value: &Value) -> mlua::Result<Vec<OsString>> {
|
||||||
|
{
|
||||||
|
debug!("args 配置已关闭 ");
|
||||||
|
#[cfg(not(feature = "args"))]
|
||||||
|
Ok(Vec::new())
|
||||||
|
}
|
||||||
|
#[cfg(feature = "args")]
|
||||||
|
{
|
||||||
|
debug!("args 配置已开启");
|
||||||
|
let ctx = Self::Args;
|
||||||
|
match value {
|
||||||
|
Value::Table(tbl) => {
|
||||||
|
ctx.validate_sequence_table(tbl)?;
|
||||||
|
|
||||||
|
let capacity = tbl.raw_len().min(128);
|
||||||
|
|
||||||
|
let mut raw_parts = Vec::with_capacity(capacity);
|
||||||
|
|
||||||
|
Self::collect_value_into(&ctx, value, &mut raw_parts)?;
|
||||||
|
|
||||||
|
for part in &raw_parts {
|
||||||
|
Self::ensure_no_nul(&ctx, &part)?;
|
||||||
|
}
|
||||||
|
Ok(raw_parts)
|
||||||
|
}
|
||||||
|
other => Err(validation_error(format!(
|
||||||
|
"{} 必须是数组列表,实际类型是 {}",
|
||||||
|
ctx,
|
||||||
|
other.type_name()
|
||||||
|
)))?,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 校验环境变量名的合法性(Windows 约束:非空、不含 '='、不含 NUL)
|
||||||
|
fn parse_env_name(name: &Value) -> mlua::Result<String> {
|
||||||
|
Self::parse_name(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 解析、校验并拼接单个环境变量键值对 (`key`, `value`) -> (`OsString`)
|
||||||
|
fn parse_env_val(
|
||||||
|
context: &LuaValidator,
|
||||||
|
name: &str,
|
||||||
|
raw_val: &Value,
|
||||||
|
) -> mlua::Result<OsString> {
|
||||||
|
context.parse_val(name, raw_val)?;
|
||||||
|
|
||||||
|
// let ctx = format!("{} [{}]", context, name);
|
||||||
|
let capacity = match raw_val {
|
||||||
|
Value::Table(t) => t.raw_len().min(128),
|
||||||
|
Value::Nil => 0,
|
||||||
|
_ => 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut parts = Vec::with_capacity(capacity);
|
||||||
|
|
||||||
|
Self::collect_value_into(&context, raw_val, &mut parts)?;
|
||||||
|
// context.collect_value_into(raw_val, &mut parts)?;
|
||||||
|
|
||||||
|
// 校验每个展开元素的 NUL 字符
|
||||||
|
for part in &parts {
|
||||||
|
Self::ensure_no_nul(&name, part)?;
|
||||||
|
}
|
||||||
|
// 3. 使用系统路径分隔符拼接数组列表
|
||||||
|
let joined_os_str = std::env::join_paths(parts).map_err(|e| {
|
||||||
|
validation_error(format!("{} 的值无法用系统路径分隔符拼接: {}", context, e))
|
||||||
|
})?;
|
||||||
|
Ok(joined_os_str)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 解析整个 `env` Table,直接返回安全的环境变量 Map
|
||||||
|
pub fn parse_env(value: &Value) -> mlua::Result<HashMap<String, OsString>> {
|
||||||
|
let ctx = Self::Env;
|
||||||
|
|
||||||
|
let Value::Table(tbl) = value else {
|
||||||
|
// 这里作为防御性校验,外部虽然 match 过了,但内层仍保持强类型安全
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"{} 必须是键值表 (table),实际类型是 {}",
|
||||||
|
ctx,
|
||||||
|
value.type_name()
|
||||||
|
)));
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut env_map = HashMap::new();
|
||||||
|
let mut n = 0i32;
|
||||||
|
|
||||||
|
for pair in tbl.pairs::<Value, Value>() {
|
||||||
|
n += 1;
|
||||||
|
|
||||||
|
let (raw_key, raw_val) = pair?;
|
||||||
|
debug!("env {} {}", n, raw_val.type_name());
|
||||||
|
|
||||||
|
// 1. 解析并校验 Key,拿到安全的 String
|
||||||
|
let key = Self::parse_env_name(&raw_key)?;
|
||||||
|
|
||||||
|
// 2. 借用 &name 传递给 Value 解析器作为上下文
|
||||||
|
let val = Self::parse_env_val(&ctx, &key, &raw_val)?;
|
||||||
|
|
||||||
|
env_map.insert(key, val);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(env_map)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LuaValidator {
|
||||||
|
/// 校验环境变量名的合法性(Windows 约束:非空、不含 '='、不含 NUL)
|
||||||
|
fn parse_aliases_name(name: &Value) -> mlua::Result<String> {
|
||||||
|
Self::parse_name(name)
|
||||||
|
}
|
||||||
|
fn parse_aliases_val(
|
||||||
|
context: &LuaValidator,
|
||||||
|
name: &str,
|
||||||
|
raw_val: &Value,
|
||||||
|
) -> mlua::Result<Vec<OsString>> {
|
||||||
|
context.parse_val(name, raw_val)?;
|
||||||
|
|
||||||
|
// let ctx = format!("{} [{}]", context, name);
|
||||||
|
// 预估容量:标量为 1,表取其实际长度(设置上限以防止异常输入)
|
||||||
|
let capacity = match raw_val {
|
||||||
|
Value::Table(t) => (t.raw_len() as usize).min(16),
|
||||||
|
Value::Nil => 0,
|
||||||
|
_ => 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut parts = Vec::with_capacity(capacity);
|
||||||
|
Self::collect_value_into(context, raw_val, &mut parts)?;
|
||||||
|
Ok(parts)
|
||||||
|
}
|
||||||
|
/// 解析并打平别名表 (aliases)
|
||||||
|
/// - 支持输入为 Nil / None / Table
|
||||||
|
/// - 别名的值支持:String, Number, Boolean, Nil, " " 空白串, Table(连续数组)
|
||||||
|
/// - 字符串作为整体参数保存,仅做 trim() 清理首尾空格,不按空格拆分
|
||||||
|
/// - 包含拓扑展开与死环检测
|
||||||
|
pub fn parse_aliases(value: &Value) -> mlua::Result<HashMap<String, Vec<OsString>>> {
|
||||||
|
let ctx = Self::Aliases;
|
||||||
|
// 1. 处理 nil / None 的情况,直接返回空 HashMap
|
||||||
|
let Value::Table(table) = value else {
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"{} 必须是键值表 (table) ,当前类型: {}",
|
||||||
|
ctx,
|
||||||
|
value.type_name()
|
||||||
|
)));
|
||||||
|
};
|
||||||
|
|
||||||
|
// 阶段一:提取原始别名映射 (Raw Extraction)
|
||||||
|
let mut raw_aliases: HashMap<String, Vec<OsString>> = HashMap::new();
|
||||||
|
|
||||||
|
for pair in table.pairs::<Value, Value>() {
|
||||||
|
let (raw_key, raw_val) = pair?;
|
||||||
|
let key = Self::parse_aliases_name(&raw_key)?;
|
||||||
|
let val = Self::parse_aliases_val(&ctx, &key, &raw_val)?;
|
||||||
|
|
||||||
|
raw_aliases.insert(key, val);
|
||||||
|
}
|
||||||
|
// 阶段二:递归拓扑打平与循环引用检测 (Flattening & Cycle Detection)
|
||||||
|
let mut visited_stack = HashSet::new();
|
||||||
|
|
||||||
|
for key in raw_aliases.keys() {
|
||||||
|
visited_stack.clear();
|
||||||
|
Self::detect_alias_cycle(key, &raw_aliases, &mut visited_stack)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 阶段三:无环前提下的高效展开
|
||||||
|
let mut flattened_aliases: HashMap<String, Vec<OsString>> =
|
||||||
|
HashMap::with_capacity(raw_aliases.len());
|
||||||
|
|
||||||
|
let mut resolved_args = Vec::new();
|
||||||
|
|
||||||
|
for key in raw_aliases.keys() {
|
||||||
|
resolved_args.clear();
|
||||||
|
Self::expand_alias_dfs(key, &raw_aliases, &mut resolved_args);
|
||||||
|
flattened_aliases.insert(key.clone(), resolved_args.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(flattened_aliases)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 仅用于校验别名依赖图中是否存在死循环(不消耗额外的参数拼接内存)
|
||||||
|
fn detect_alias_cycle(
|
||||||
|
current_key: &str,
|
||||||
|
raw_aliases: &HashMap<String, Vec<OsString>>,
|
||||||
|
visited_stack: &mut HashSet<String>,
|
||||||
|
) -> mlua::Result<()> {
|
||||||
|
// 递归栈中再次遇到相同的 Key,说明存在死循环
|
||||||
|
if visited_stack.contains(current_key) {
|
||||||
|
return Err(validation_error(format!(
|
||||||
|
"配置加载失败: 检测到别名循环嵌套依赖 'mr:{}'",
|
||||||
|
current_key
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(args) = raw_aliases.get(current_key) {
|
||||||
|
// 压栈
|
||||||
|
visited_stack.insert(current_key.to_string());
|
||||||
|
|
||||||
|
for arg in args {
|
||||||
|
let arg_str = arg.to_string_lossy();
|
||||||
|
if let Some(sub_key) = arg_str.strip_prefix("mr:") {
|
||||||
|
// 如果引用的子别名在映射表中存在,则深度优先校验
|
||||||
|
if raw_aliases.contains_key(sub_key) {
|
||||||
|
Self::detect_alias_cycle(sub_key, raw_aliases, visited_stack)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 出栈(回溯)
|
||||||
|
visited_stack.remove(current_key);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
/// 安全拓扑展开:在保证绝对无环的前提下递归展开 mr: 前缀参数
|
||||||
|
fn expand_alias_dfs(
|
||||||
|
current_key: &str,
|
||||||
|
raw_aliases: &HashMap<String, Vec<OsString>>,
|
||||||
|
out: &mut Vec<OsString>,
|
||||||
|
) {
|
||||||
|
if let Some(args) = raw_aliases.get(current_key) {
|
||||||
|
for arg in args {
|
||||||
|
let arg_str = arg.to_string_lossy();
|
||||||
|
if let Some(sub_key) = arg_str.strip_prefix("mr:") {
|
||||||
|
if raw_aliases.contains_key(sub_key) {
|
||||||
|
// 安全地直接递归展开,无需再检查死循环
|
||||||
|
Self::expand_alias_dfs(sub_key, raw_aliases, out);
|
||||||
|
} else {
|
||||||
|
// 找不到对应的别名,按原样参数输出
|
||||||
|
out.push(arg.clone());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 普通参数,直接输出
|
||||||
|
out.push(arg.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::Mirror;
|
||||||
|
use mlua::{FromLua, Lua};
|
||||||
|
|
||||||
|
fn parse(src: &str) -> mlua::Result<Mirror> {
|
||||||
|
let lua = Lua::new();
|
||||||
|
// 模拟 runtime 注入的 get_env:返回按平台分隔符拆分的段数组(空变量返回空表)
|
||||||
|
let get_env = lua
|
||||||
|
.create_function(|lua, key: String| -> mlua::Result<Table> {
|
||||||
|
let value = std::env::var(key).unwrap_or_default();
|
||||||
|
let segments: Vec<String> = if value.is_empty() {
|
||||||
|
Vec::new()
|
||||||
|
} else {
|
||||||
|
std::env::split_paths(std::ffi::OsStr::new(&value))
|
||||||
|
.map(|p| p.to_string_lossy().into_owned())
|
||||||
|
.collect()
|
||||||
|
};
|
||||||
|
lua.create_sequence_from(segments)
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
lua.globals().set("get_env", get_env).unwrap();
|
||||||
|
|
||||||
|
let value = lua.load(src).eval::<Value>()?;
|
||||||
|
let t = Mirror::from_lua(value, &lua);
|
||||||
|
println!("读取出的数据:{:?}", t.clone()?);
|
||||||
|
t
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_basic_config() {
|
||||||
|
let cfg = parse(
|
||||||
|
r#"
|
||||||
|
return {
|
||||||
|
target = "C:/tools/git.exe",
|
||||||
|
args = { "--no-pager",2},
|
||||||
|
env = {
|
||||||
|
PATH = { "C:/tools/git/bin", "C:/Windows", get_env("PATH")},
|
||||||
|
HOME = "C:/tools/home",
|
||||||
|
CONST = 3,
|
||||||
|
BOOL = true,
|
||||||
|
},
|
||||||
|
aliases = {
|
||||||
|
-- 1. 整体字符串(会自动 trim 首尾空格,保留为单个参数)
|
||||||
|
st = "status -s",
|
||||||
|
|
||||||
|
-- 2. 连续数组表 (Sequence Table)
|
||||||
|
lg = { "log", "--oneline", "-n", 10 },
|
||||||
|
|
||||||
|
-- 3. 标量数字与布尔值支持
|
||||||
|
v = 1,
|
||||||
|
quiet = true,
|
||||||
|
|
||||||
|
-- 4. 嵌套别名组合(加载期会自动展开并进行死环检测)
|
||||||
|
base_log = "log --graph",
|
||||||
|
all_log = { "mr:base_log", "--all","D:\\CNWei\\CNW\\Rust","D:/CNWei/CNW/Rust/" ,[[D:\CNWei\CNW\Rust\]]},
|
||||||
|
|
||||||
|
-- 5. nil 或空字符串(解析为空参数列表)
|
||||||
|
empty_alias = nil,
|
||||||
|
blank = " "
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(cfg.target, PathBuf::from("C:/tools/git.exe"));
|
||||||
|
// assert_eq!(cfg.args, vec!["--no-pager", "2"]);
|
||||||
|
assert_eq!(cfg.env.get("HOME").unwrap().to_str(), Some("C:/tools/home"));
|
||||||
|
// PATH 前缀来自配置,随后附加 get_env("PATH") 拆出的宿主 PATH 段
|
||||||
|
let path = cfg.env.get("PATH").unwrap().to_str().unwrap();
|
||||||
|
assert!(
|
||||||
|
path == "C:/tools/git/bin;C:/Windows"
|
||||||
|
|| path.starts_with("C:/tools/git/bin;C:/Windows;"),
|
||||||
|
"unexpected PATH: {path}"
|
||||||
|
);
|
||||||
|
// ==================== aliases 断言校验 ====================
|
||||||
|
|
||||||
|
// 1. 整体字符串:保留原样(trim 后),不切分空格
|
||||||
|
assert_eq!(
|
||||||
|
cfg.aliases.get("st").unwrap(),
|
||||||
|
&vec![OsString::from("status"), OsString::from("-s")]
|
||||||
|
);
|
||||||
|
|
||||||
|
// 2. 连续数组表:按顺序转为 OsString 列表
|
||||||
|
assert_eq!(
|
||||||
|
cfg.aliases.get("lg").unwrap(),
|
||||||
|
&vec![
|
||||||
|
OsString::from("log"),
|
||||||
|
OsString::from("--oneline"),
|
||||||
|
OsString::from("-n"),
|
||||||
|
OsString::from("10")
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
// 3. 标量数字与布尔值支持
|
||||||
|
assert_eq!(cfg.aliases.get("v").unwrap(), &vec![OsString::from("1")]);
|
||||||
|
assert_eq!(
|
||||||
|
cfg.aliases.get("quiet").unwrap(),
|
||||||
|
&vec![OsString::from("true")]
|
||||||
|
);
|
||||||
|
|
||||||
|
// 4. 嵌套别名组合:加载期递归拓扑打平
|
||||||
|
// base_log 本身为 "log --graph"
|
||||||
|
assert_eq!(
|
||||||
|
cfg.aliases.get("base_log").unwrap(),
|
||||||
|
&vec![OsString::from("log"), OsString::from("--graph")]
|
||||||
|
);
|
||||||
|
// all_log 展开 mr:base_log 替换为 "log --graph",追加 "--all"
|
||||||
|
assert_eq!(
|
||||||
|
cfg.aliases.get("all_log").unwrap(),
|
||||||
|
&vec![
|
||||||
|
OsString::from("log"),
|
||||||
|
OsString::from("--graph"),
|
||||||
|
OsString::from("--all"),
|
||||||
|
OsString::from("D:\\CNWei\\CNW\\Rust"),
|
||||||
|
OsString::from("D:/CNWei/CNW/Rust/"),
|
||||||
|
OsString::from("D:\\CNWei\\CNW\\Rust\\"),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
// 5. nil 与纯空白字符串:解析为空 Vec
|
||||||
|
assert_eq!(cfg.aliases.get("blank").unwrap(), &Vec::<OsString>::new());
|
||||||
|
// nil 键在遍历表时会被当作空或不存在,不产生 key 或值为空 Vec
|
||||||
|
assert!(
|
||||||
|
cfg.aliases
|
||||||
|
.get("empty_alias")
|
||||||
|
.map_or(true, |v| v.is_empty())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn missing_args_and_env_are_empty() {
|
||||||
|
let cfg = parse(r#"return { target = "t.exe" }"#).unwrap();
|
||||||
|
assert!(cfg.args.is_empty());
|
||||||
|
assert!(cfg.env.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keeps_empty_args() {
|
||||||
|
let cfg = parse(r#"return { target = "t.exe", args = { "" } }"#).unwrap();
|
||||||
|
assert_eq!(cfg.args, vec![""]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keeps_empty_env_value() {
|
||||||
|
let cfg = parse(r#"return { target = "t.exe", env = { FOO = "" } }"#).unwrap();
|
||||||
|
assert_eq!(cfg.env.get("FOO").unwrap().to_str(), Some(""));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn empty_array_clears_env_var() {
|
||||||
|
let cfg = parse(r#"return { target = "t.exe", env = { PATH = {} } }"#).unwrap();
|
||||||
|
assert_eq!(cfg.env.get("PATH").unwrap().to_str(), Some(""));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn expands_nested_env_array() {
|
||||||
|
// get_env("PATH") 现在返回拆分后的段数组,嵌套表应被递归展开
|
||||||
|
let cfg = parse(
|
||||||
|
r#"return { target = "t.exe", env = { PATH = { "C:/a", { "C:/b", "C:/c" } } } }"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
cfg.env.get("PATH").unwrap().to_str(),
|
||||||
|
Some("C:/a;C:/b;C:/c")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_wrong_env_type() {
|
||||||
|
assert!(parse(r#"return { target = "t.exe", env = "PATH=C:/x" }"#).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_sparse_env_array() {
|
||||||
|
assert!(parse(r#"return { target = "t.exe", env = { P = { "a", nil, "b" } } }"#).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_mixed_key_env_array() {
|
||||||
|
assert!(parse(r#"return { target = "t.exe", env = { P = { a = "b" } } }"#).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_invalid_env_key() {
|
||||||
|
assert!(parse(r#"return { target = "t.exe", env = { ["FOO=1"] = "x" } }"#).is_err());
|
||||||
|
assert!(parse(r#"return { target = "t.exe", env = { [""] = "x" } }"#).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_nul_in_env_value() {
|
||||||
|
assert!(parse(r#"return { target = "t.exe", env = { P = { string.char(0) } } }"#).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_quote_in_env_value() {
|
||||||
|
// Windows 的 join_paths 对含双引号的路径元素返回错误
|
||||||
|
assert!(
|
||||||
|
parse(r#"return { target = "t.exe", env = { P = { string.char(34) } } }"#).is_err()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_unsupported_env_value_type() {
|
||||||
|
assert!(parse(r#"return { target = "t.exe", env = { F = function() end } }"#).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn missing_target_is_error() {
|
||||||
|
assert!(parse(r#"return { args = { "x" } }"#).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_non_string_target() {
|
||||||
|
assert!(parse(r#"return { target = 123 }"#).is_err());
|
||||||
|
assert!(parse(r#"return { target = false }"#).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_non_string_args_element() {
|
||||||
|
// ValueShunt::Args 允许基础标量(数字/布尔)转字符串,仅禁止嵌套表
|
||||||
|
let cfg = parse(r#"return { target = "t.exe", args = { 1, true } }"#).unwrap();
|
||||||
|
assert_eq!(cfg.args, vec!["1", "true"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_sparse_args() {
|
||||||
|
assert!(parse(r#"return { target = "t.exe", args = { "a", nil, "b" } }"#).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_non_table_args() {
|
||||||
|
assert!(parse(r#"return { target = "t.exe", args = "-B" }"#).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
8
mirror.ini
Normal file
8
mirror.ini
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
# mirror-log.ini
|
||||||
|
level = debug
|
||||||
|
log_dir = "logs"
|
||||||
|
|
||||||
|
# 或者带节结构:
|
||||||
|
# [logger]
|
||||||
|
# level = info
|
||||||
|
# log_dir = /var/log/mirror
|
||||||
632
src/config.rs
632
src/config.rs
@@ -1,632 +0,0 @@
|
|||||||
use mlua::{FromLua, Lua, LuaString, ObjectLike, Table, Value};
|
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::ffi::OsString;
|
|
||||||
use std::fmt;
|
|
||||||
use std::fmt::Display;
|
|
||||||
use std::path::PathBuf;
|
|
||||||
use std::process::Command;
|
|
||||||
/// 构造一个带上下文的 FromLua 转换错误,便于定位配置问题
|
|
||||||
fn conversion_error(message: impl Into<String>) -> mlua::Error {
|
|
||||||
mlua::Error::FromLuaConversionError {
|
|
||||||
from: "Lua value",
|
|
||||||
to: "ShimConfig".into(),
|
|
||||||
message: Some(message.into()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 将 Lua 字符串转为 Rust 字符串;非 UTF-8 按系统默认的 ANSI/OEM (如 GBK) 进行安全解码
|
|
||||||
fn lua_string_2_os_string(s: &LuaString) -> mlua::Result<OsString> {
|
|
||||||
let raw_bytes = &s.as_bytes().to_vec();
|
|
||||||
// 1. Unix 平台:直接零拷贝透传原始字节(无损支持任意编码)
|
|
||||||
#[cfg(unix)]
|
|
||||||
{
|
|
||||||
use std::os::unix::ffi::OsStrExt;
|
|
||||||
Ok(OsStr::from_bytes(raw_bytes).to_os_string())
|
|
||||||
}
|
|
||||||
// 2. Windows 平台:优先按 UTF-8 解码,失败则按当前系统本地代码页 (ANSI/GBK) 转换
|
|
||||||
#[cfg(windows)]
|
|
||||||
{
|
|
||||||
// 先尝试标准的 UTF-8
|
|
||||||
if let Ok(utf8_str) = std::str::from_utf8(raw_bytes) {
|
|
||||||
return Ok(OsString::from(utf8_str));
|
|
||||||
}
|
|
||||||
|
|
||||||
// 非 UTF-8 时,按系统默认的 ANSI/OEM (如 GBK) 进行安全解码
|
|
||||||
let (cow, _, had_errors) = encoding_rs::GBK.decode(raw_bytes);
|
|
||||||
if had_errors {
|
|
||||||
return Err(mlua::Error::RuntimeError(
|
|
||||||
"路径包含无效/不支持的字节编码".into(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
Ok(OsString::from(cow.as_ref()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 按连续整数下标遍历表的序列部分;存在空洞或非序列键时返回错误,避免静默截断
|
|
||||||
|
|
||||||
/// Lua 值校验器:针对不同上下文定义校验规则
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum ValueValidator {
|
|
||||||
/// 目标程序路径:必须是字符串路径
|
|
||||||
Target,
|
|
||||||
/// 命令行参数元素:仅支持一维基础标量,禁止嵌套 Table
|
|
||||||
Args,
|
|
||||||
/// 环境变量值:支持基础标量及多维嵌套 Table(递归展平)
|
|
||||||
Env,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for ValueValidator {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
match self {
|
|
||||||
Self::Target => write!(f, "目标路径 (target)"),
|
|
||||||
Self::Args => write!(f, "命令行参数 (args)"),
|
|
||||||
Self::Env => write!(f, "环境变量 (env)"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl ValueValidator {
|
|
||||||
/// 【纯粹校验入口】只进行逻辑与结构判定,零副作用、不产生内存分配
|
|
||||||
pub fn validate(&self, value: &Value) -> mlua::Result<()> {
|
|
||||||
if matches!(self, Self::Target) {
|
|
||||||
println!("跟踪taget{}", value.type_name());
|
|
||||||
}
|
|
||||||
if matches!(self, Self::Args) {
|
|
||||||
println!("跟踪args2{}", value.type_name());
|
|
||||||
}
|
|
||||||
if matches!(self, Self::Env) {
|
|
||||||
println!("跟踪env{}", value.type_name());
|
|
||||||
}
|
|
||||||
match self {
|
|
||||||
Self::Target => match value {
|
|
||||||
Value::String(_) => Ok(()),
|
|
||||||
Value::Nil => Err(conversion_error("缺少必填字段 target(应为字符串路径)")),
|
|
||||||
other => Err(conversion_error(format!(
|
|
||||||
"{} 需为有效的路径且类型必须是字符串,实际类型是 {}",
|
|
||||||
self,
|
|
||||||
other.type_name()
|
|
||||||
))),
|
|
||||||
},
|
|
||||||
Self::Args => match value {
|
|
||||||
Value::Table(tbl) => self.validate_sequence_table(tbl),
|
|
||||||
other => Err(conversion_error(format!(
|
|
||||||
"{} 必须是数组列表,实际类型是 {}",
|
|
||||||
self,
|
|
||||||
other.type_name()
|
|
||||||
))),
|
|
||||||
},
|
|
||||||
Self::Env => match value {
|
|
||||||
Value::Nil
|
|
||||||
| Value::String(_)
|
|
||||||
| Value::Integer(_)
|
|
||||||
| Value::Number(_)
|
|
||||||
| Value::Boolean(_) => Ok(()),
|
|
||||||
Value::Table(tbl) => self.validate_sequence_table(tbl),
|
|
||||||
other => Err(conversion_error(format!(
|
|
||||||
"{} 不支持 {} 类型, 仅支持 string/number/boolean 或嵌套数组",
|
|
||||||
self,
|
|
||||||
other.type_name()
|
|
||||||
))),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 校验 Table 是否为严格连续的纯数组,并递归校验其内部元素
|
|
||||||
fn validate_sequence_table(&self, tbl: &Table) -> mlua::Result<()> {
|
|
||||||
let mut index = 1i64;
|
|
||||||
|
|
||||||
// 1. 顺序遍历连续整数索引 1..N
|
|
||||||
loop {
|
|
||||||
let item: Value = tbl.raw_get(index)?;
|
|
||||||
if matches!(item, Value::Nil) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
match self {
|
|
||||||
Self::Args => match item {
|
|
||||||
Value::Table(_) => {
|
|
||||||
return Err(conversion_error(format!(
|
|
||||||
"{} 仅支持一维数组,不能包含嵌套 Table,索引位置: {index}",
|
|
||||||
self
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
Value::String(_)|Value::Integer(_)|Value::Number(_)|Value::Boolean(_) => {}
|
|
||||||
_ => {return Err(conversion_error("args异常"))}
|
|
||||||
},
|
|
||||||
Self::Env => match item {
|
|
||||||
Value::Table(_) => self.validate(&item)?,
|
|
||||||
_ => {}
|
|
||||||
},
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
|
|
||||||
// // 元素规则判断
|
|
||||||
// match item {
|
|
||||||
// // Args 规则拦截:禁止嵌套数组
|
|
||||||
// Value::Table(_) if matches!(self, Self::Args) => {
|
|
||||||
// return Err(conversion_error(format!(
|
|
||||||
// "{} 仅支持一维数组,不能包含嵌套 Table,索引位置{index}",
|
|
||||||
// self
|
|
||||||
// )));
|
|
||||||
// }
|
|
||||||
// // 标量或合法嵌套表:调用 validate 递归深度判定
|
|
||||||
// _ => self.validate(&item)?,
|
|
||||||
// }
|
|
||||||
|
|
||||||
index += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. 查漏:校验是否存在空洞索引或字典键 (Key-Value 键值对)
|
|
||||||
for pair in tbl.pairs::<Value, Value>() {
|
|
||||||
let (key, _) = pair?;
|
|
||||||
match key {
|
|
||||||
Value::Integer(i) if i >= 1 && i < index => {} // 已遍历放行
|
|
||||||
Value::Integer(_) => {
|
|
||||||
return Err(conversion_error(format!(
|
|
||||||
"{} 第 {} 个元素为 nil 或不存在(请检查漏写引号或变量未定义)",
|
|
||||||
self, index
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
return Err(conversion_error(format!(
|
|
||||||
"{} 必须是纯列表,不能包含键值对/字典结构",
|
|
||||||
self
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 解析并校验 `target`
|
|
||||||
pub fn parse_target(value: &Value) -> mlua::Result<PathBuf> {
|
|
||||||
let validator = Self::Target;
|
|
||||||
validator.validate(&value)?;
|
|
||||||
let ctx = format!("{}", validator);
|
|
||||||
|
|
||||||
if let Value::String(s) = value {
|
|
||||||
let os_str = lua_string_2_os_string(&s)?;
|
|
||||||
Self::ensure_no_nul(&ctx, &os_str)?;
|
|
||||||
Ok(PathBuf::from(os_str))
|
|
||||||
} else {
|
|
||||||
unreachable!()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/// 解析并校验 `args`
|
|
||||||
pub fn parse_args(value: &Value) -> mlua::Result<Vec<OsString>> {
|
|
||||||
println!("跟踪args1{}", value.type_name());
|
|
||||||
let validator = Self::Args;
|
|
||||||
validator.validate(&value)?;
|
|
||||||
let ctx = format!("{}", validator);
|
|
||||||
|
|
||||||
let mut raw_parts = Vec::new();
|
|
||||||
collect_value_into(&ctx, value, &mut raw_parts)?;
|
|
||||||
|
|
||||||
for part in &raw_parts {
|
|
||||||
Self::ensure_no_nul(&ctx, &part)?;
|
|
||||||
}
|
|
||||||
Ok(raw_parts)
|
|
||||||
}
|
|
||||||
fn parse_env_name(name: &Value) -> mlua::Result<String> {
|
|
||||||
let name_str = match name {
|
|
||||||
Value::String(s) => match s.to_str() {
|
|
||||||
Ok(str_ref) => str_ref.to_string(),
|
|
||||||
Err(_) => return Err(conversion_error("环境变量名必须是合法的 UTF-8 字符串")),
|
|
||||||
},
|
|
||||||
other => {
|
|
||||||
return Err(conversion_error(format!(
|
|
||||||
"环境变量键名类型错误:期望 string,实际是 {}",
|
|
||||||
other.type_name()
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if name_str.is_empty() {
|
|
||||||
return Err(conversion_error("环境变量名不能为空"));
|
|
||||||
}
|
|
||||||
if name_str.contains('=') {
|
|
||||||
return Err(conversion_error(format!(
|
|
||||||
"环境变量名 [{}] 不能包含 '='",
|
|
||||||
name_str
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
if name_str.contains('\0') {
|
|
||||||
return Err(conversion_error(format!(
|
|
||||||
"环境变量名 [{}] 不能包含 NUL 字符",
|
|
||||||
name_str
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
Ok(name_str)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 解析、校验并拼接单个环境变量键值对 (`key`, `value`) -> (`String`, `OsString`)
|
|
||||||
fn parse_env_val(name: &str, raw_val: &Value) -> mlua::Result<OsString> {
|
|
||||||
Self::Env.validate(&raw_val)?;
|
|
||||||
|
|
||||||
let ctx = format!("环境变量 [{}]", name);
|
|
||||||
let mut parts = Vec::new();
|
|
||||||
|
|
||||||
collect_value_into(&ctx, raw_val, &mut parts)?;
|
|
||||||
|
|
||||||
// 校验每个展开元素的 NUL 字符
|
|
||||||
for part in &parts {
|
|
||||||
Self::ensure_no_nul(name, part)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. 使用系统路径分隔符拼接数组列表
|
|
||||||
let joined_os_str = std::env::join_paths(parts).map_err(|e| {
|
|
||||||
conversion_error(format!("{} 的值无法用系统路径分隔符拼接: {}", ctx, e))
|
|
||||||
})?;
|
|
||||||
Ok(joined_os_str)
|
|
||||||
}
|
|
||||||
/// 解析并校验单个环境变量键值对 (`key`, `val`) -> (`String`, `OsString`)
|
|
||||||
fn parse_env_pair(key: &Value, val: &Value) -> mlua::Result<(String, OsString)> {
|
|
||||||
// 1. 解析并校验 Key,拿到安全的 String
|
|
||||||
let name = Self::parse_env_name(key)?;
|
|
||||||
// 2. 借用 &name 传递给 Value 解析器作为上下文
|
|
||||||
let os_val = Self::parse_env_val(&name, val)?;
|
|
||||||
// 3. 所有权平滑转移,组装元组返回
|
|
||||||
Ok((name, os_val))
|
|
||||||
}
|
|
||||||
/// 解析整个 `env` Table,直接返回安全的环境变量 Map
|
|
||||||
pub fn parse_env(value: &Value) -> mlua::Result<HashMap<String, OsString>> {
|
|
||||||
let Value::Table(tbl) = value else {
|
|
||||||
// 这里作为防御性校验,外部虽然 match 过了,但内层仍保持强类型安全
|
|
||||||
return Err(conversion_error(format!(
|
|
||||||
"env 必须是键值表 (table),实际类型是 {}",
|
|
||||||
value.type_name()
|
|
||||||
)));
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut env_map = HashMap::new();
|
|
||||||
|
|
||||||
for pair in tbl.pairs::<Value, Value>() {
|
|
||||||
let (raw_key, raw_val) = pair?;
|
|
||||||
let (key, val) = Self::parse_env_pair(&raw_key, &raw_val)?;
|
|
||||||
env_map.insert(key, val);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(env_map)
|
|
||||||
}
|
|
||||||
// ================= 3. 底层 NUL 字符跨平台安全检查 =================
|
|
||||||
|
|
||||||
fn ensure_no_nul(context_desc: &str, os_str: &std::ffi::OsStr) -> mlua::Result<()> {
|
|
||||||
#[cfg(unix)]
|
|
||||||
{
|
|
||||||
use std::os::unix::ffi::OsStrExt;
|
|
||||||
if os_str.as_bytes().contains(&0) {
|
|
||||||
return Err(conversion_error(format!(
|
|
||||||
"{} 的值不能包含 NUL 字符",
|
|
||||||
context_desc
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#[cfg(windows)]
|
|
||||||
{
|
|
||||||
use std::os::windows::ffi::OsStrExt;
|
|
||||||
if os_str.encode_wide().any(|c| c == 0) {
|
|
||||||
return Err(conversion_error(format!(
|
|
||||||
"{} 的值不能包含 NUL 字符",
|
|
||||||
context_desc
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 【纯粹数据转换与展开】将已通过校验的 Value 递归解析为 OsString 动态数组
|
|
||||||
pub fn collect_value_into(
|
|
||||||
context: &impl fmt::Display,
|
|
||||||
value: &Value,
|
|
||||||
out: &mut Vec<OsString>,
|
|
||||||
) -> mlua::Result<()> {
|
|
||||||
match value {
|
|
||||||
Value::Nil => {}
|
|
||||||
Value::String(s) => out.push(lua_string_2_os_string(s)?),
|
|
||||||
Value::Integer(i) => out.push(OsString::from(i.to_string())),
|
|
||||||
Value::Number(n) => {
|
|
||||||
tracing::warn!(%context, value = %n, "浮点数将按十进制格式转换为字符串");
|
|
||||||
out.push(OsString::from(n.to_string()));
|
|
||||||
}
|
|
||||||
Value::Boolean(b) => {
|
|
||||||
tracing::warn!(%context, value = %b, "布尔值将转换为字符串");
|
|
||||||
out.push(OsString::from(b.to_string()));
|
|
||||||
}
|
|
||||||
Value::Table(tbl) => {
|
|
||||||
let mut index = 1i64;
|
|
||||||
loop {
|
|
||||||
let item: Value = tbl.raw_get(index)?;
|
|
||||||
if matches!(item, Value::Nil) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
collect_value_into(context, &item, out)?;
|
|
||||||
index += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => unreachable!("传入收集器的 Value 应已通过 validate 校验"),
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 校验环境变量名的合法性(Windows 约束:非空、不含 '='、不含 NUL)
|
|
||||||
// fn parse_env_name(name: &Value, val: &Value) -> mlua::Result<String> {
|
|
||||||
// let name_str = match name {
|
|
||||||
// Value::String(s) => s.to_str()?.to_string(),
|
|
||||||
//
|
|
||||||
// _ => {
|
|
||||||
// return Err(conversion_error(format!(
|
|
||||||
// "env 配置解析失败:(对应的值: {}, 类型: {}) 无效的键值!示例 HOME=\"/home\" 或 PATH = {{ \"C:/tools/\", \"D:/Windows\"}})",
|
|
||||||
// val.to_string()?,
|
|
||||||
// val.type_name()
|
|
||||||
// )));
|
|
||||||
// }
|
|
||||||
// };
|
|
||||||
// if name_str.is_empty() {
|
|
||||||
// return Err(conversion_error("环境变量名不能为空"));
|
|
||||||
// }
|
|
||||||
// if name_str.contains('=') {
|
|
||||||
// return Err(conversion_error(format!(
|
|
||||||
// "环境变量名 [{}] 不能包含 '='",
|
|
||||||
// name_str
|
|
||||||
// )));
|
|
||||||
// }
|
|
||||||
// if name_str.contains('\0') {
|
|
||||||
// return Err(conversion_error(format!(
|
|
||||||
// "环境变量名 [{}] 不能包含 NUL 字符",
|
|
||||||
// name_str
|
|
||||||
// )));
|
|
||||||
// }
|
|
||||||
// Ok(name_str)
|
|
||||||
// }
|
|
||||||
|
|
||||||
/// 递归将任意 Lua Value 展开为扁平的字符串片段列表
|
|
||||||
// fn collect_env_segments(value: Value, out: &mut Vec<OsString>) -> mlua::Result<()>{OK(())}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default)]
|
|
||||||
pub struct ShimConfig {
|
|
||||||
pub target: PathBuf,
|
|
||||||
pub args: Vec<OsString>,
|
|
||||||
pub env: HashMap<String, OsString>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ShimConfig {
|
|
||||||
/// 根据配置快速构建准备执行的 Command 对象
|
|
||||||
pub fn to_command<I, S>(&self, runtime_args: I) -> Command
|
|
||||||
where
|
|
||||||
I: IntoIterator<Item = S>,
|
|
||||||
S: AsRef<std::ffi::OsStr>,
|
|
||||||
{
|
|
||||||
let mut cmd = Command::new(&self.target);
|
|
||||||
|
|
||||||
// 1. 先追加配置里固定的默认参数 (例如: node, --max-old-space-size=4096)
|
|
||||||
cmd.args(&self.args);
|
|
||||||
|
|
||||||
// 2. 透传外部动态运行时参数
|
|
||||||
cmd.args(runtime_args);
|
|
||||||
|
|
||||||
for (key, val) in &self.env {
|
|
||||||
// 直接应用环境变量(Lua 端已经处理好字符串拼接或列表合并)
|
|
||||||
cmd.env(key, val);
|
|
||||||
}
|
|
||||||
|
|
||||||
cmd
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 实现 FromLua Trait,由 mlua 自动处理 Table 转换
|
|
||||||
impl FromLua for ShimConfig {
|
|
||||||
fn from_lua(value: Value, _lua: &Lua) -> mlua::Result<Self> {
|
|
||||||
// 脚本返回必须是一个 Table 变体
|
|
||||||
let table = match value {
|
|
||||||
Value::Table(t) => t,
|
|
||||||
_ => {
|
|
||||||
return Err(conversion_error(format!(
|
|
||||||
"期望得到一个 Lua Table 配置对象,实际是 {}",
|
|
||||||
value.type_name()
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// 必填字段: target(严格限定为字符串,避免数字被 mlua 宽松转为字符串后掩盖错误)
|
|
||||||
let target = match table.get::<Option<Value>>("target")? {
|
|
||||||
None | Some(Value::Nil) => {
|
|
||||||
return Err(conversion_error("缺少必填字段 target(应为字符串路径)"));
|
|
||||||
}
|
|
||||||
Some(target_val) => ValueValidator::parse_target(&target_val)?,
|
|
||||||
// Value::String(s) => lua_string_2_os_string(&s)?,
|
|
||||||
// Value::Nil => {
|
|
||||||
// return Err(conversion_error("缺少必填字段 target(应为字符串路径)"));
|
|
||||||
// }
|
|
||||||
// other => {
|
|
||||||
// return Err(conversion_error(format!(
|
|
||||||
// "target 需为有效的路径且类型必须是字符串,实际类型是 {}",
|
|
||||||
// other.type_name()
|
|
||||||
// )));
|
|
||||||
// }
|
|
||||||
};
|
|
||||||
// let mut args = Vec::new();
|
|
||||||
|
|
||||||
// 可选字段: args(缺失或 nil 时默认空列表;保留空字符串参数,与提权路径的 "" 语义一致)
|
|
||||||
let args = match table.get::<Option<Value>>("args")? {
|
|
||||||
None | Some(Value::Nil) => Vec::new(),
|
|
||||||
Some(args_val) => ValueValidator::parse_args(&args_val)?,
|
|
||||||
};
|
|
||||||
|
|
||||||
// 可选字段: env(只允许缺失/nil,其他类型由 Option<Table> 转换报错,不再静默忽略)
|
|
||||||
let env = match table.get::<Option<Value>>("env")? {
|
|
||||||
None | Some(Value::Nil) => HashMap::new(),
|
|
||||||
Some(ref env_val @ Value::Table(_)) => ValueValidator::parse_env(&env_val)?,
|
|
||||||
Some(other) => {
|
|
||||||
return Err(conversion_error(format!(
|
|
||||||
"env 必须是键值表 (table),实际类型是 {}",
|
|
||||||
other.type_name()
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
println!("环境变量结果:{:?}", env);
|
|
||||||
Ok(ShimConfig { target, args, env })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
fn parse(src: &str) -> mlua::Result<ShimConfig> {
|
|
||||||
let lua = Lua::new();
|
|
||||||
// 模拟 runtime 注入的 get_env:返回按平台分隔符拆分的段数组(空变量返回空表)
|
|
||||||
let get_env = lua
|
|
||||||
.create_function(|lua, key: String| -> mlua::Result<Table> {
|
|
||||||
let value = std::env::var(key).unwrap_or_default();
|
|
||||||
let segments: Vec<String> = if value.is_empty() {
|
|
||||||
Vec::new()
|
|
||||||
} else {
|
|
||||||
std::env::split_paths(std::ffi::OsStr::new(&value))
|
|
||||||
.map(|p| p.to_string_lossy().into_owned())
|
|
||||||
.collect()
|
|
||||||
};
|
|
||||||
lua.create_sequence_from(segments)
|
|
||||||
})
|
|
||||||
.unwrap();
|
|
||||||
lua.globals().set("get_env", get_env).unwrap();
|
|
||||||
|
|
||||||
let value = lua.load(src).eval::<Value>()?;
|
|
||||||
let t = ShimConfig::from_lua(value, &lua);
|
|
||||||
println!("读取出的数据:{:?}", t.clone()?);
|
|
||||||
t
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn parses_basic_config() {
|
|
||||||
let cfg = parse(
|
|
||||||
r#"
|
|
||||||
return {
|
|
||||||
target = "C:/tools/git.exe",
|
|
||||||
args = { "--no-pager"},
|
|
||||||
env = {
|
|
||||||
PATH = { "C:/tools/git/bin", "C:/Windows", get_env("PATH") },
|
|
||||||
HOME = "C:/tools/home",
|
|
||||||
CONST = 3,
|
|
||||||
BOOL = true,
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
"#,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(cfg.target, PathBuf::from("C:/tools/git.exe"));
|
|
||||||
assert_eq!(cfg.args, vec!["--no-pager"]);
|
|
||||||
assert_eq!(cfg.env.get("HOME").unwrap().to_str(), Some("C:/tools/home"));
|
|
||||||
// PATH 前缀来自配置,随后附加 get_env("PATH") 拆出的宿主 PATH 段
|
|
||||||
let path = cfg.env.get("PATH").unwrap().to_str().unwrap();
|
|
||||||
assert!(
|
|
||||||
path == "C:/tools/git/bin;C:/Windows"
|
|
||||||
|| path.starts_with("C:/tools/git/bin;C:/Windows;"),
|
|
||||||
"unexpected PATH: {path}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn missing_args_and_env_are_empty() {
|
|
||||||
let cfg = parse(r#"return { target = "t.exe" }"#).unwrap();
|
|
||||||
assert!(cfg.args.is_empty());
|
|
||||||
assert!(cfg.env.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn keeps_empty_args() {
|
|
||||||
let cfg = parse(r#"return { target = "t.exe", args = { "" } }"#).unwrap();
|
|
||||||
assert_eq!(cfg.args, vec![""]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn keeps_empty_env_value() {
|
|
||||||
let cfg = parse(r#"return { target = "t.exe", env = { FOO = "" } }"#).unwrap();
|
|
||||||
assert_eq!(cfg.env.get("FOO").unwrap().to_str(), Some(""));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn empty_array_clears_env_var() {
|
|
||||||
let cfg = parse(r#"return { target = "t.exe", env = { PATH = {} } }"#).unwrap();
|
|
||||||
assert_eq!(cfg.env.get("PATH").unwrap().to_str(), Some(""));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn expands_nested_env_array() {
|
|
||||||
// get_env("PATH") 现在返回拆分后的段数组,嵌套表应被递归展开
|
|
||||||
let cfg = parse(
|
|
||||||
r#"return { target = "t.exe", env = { PATH = { "C:/a", { "C:/b", "C:/c" } } } }"#,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
cfg.env.get("PATH").unwrap().to_str(),
|
|
||||||
Some("C:/a;C:/b;C:/c")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rejects_wrong_env_type() {
|
|
||||||
assert!(parse(r#"return { target = "t.exe", env = "PATH=C:/x" }"#).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rejects_sparse_env_array() {
|
|
||||||
assert!(parse(r#"return { target = "t.exe", env = { P = { "a", nil, "b" } } }"#).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rejects_mixed_key_env_array() {
|
|
||||||
assert!(parse(r#"return { target = "t.exe", env = { P = { a = "b" } } }"#).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rejects_invalid_env_key() {
|
|
||||||
assert!(parse(r#"return { target = "t.exe", env = { ["FOO=1"] = "x" } }"#).is_err());
|
|
||||||
assert!(parse(r#"return { target = "t.exe", env = { [""] = "x" } }"#).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rejects_nul_in_env_value() {
|
|
||||||
assert!(parse(r#"return { target = "t.exe", env = { P = { string.char(0) } } }"#).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rejects_quote_in_env_value() {
|
|
||||||
// Windows 的 join_paths 对含双引号的路径元素返回错误
|
|
||||||
assert!(
|
|
||||||
parse(r#"return { target = "t.exe", env = { P = { string.char(34) } } }"#).is_err()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rejects_unsupported_env_value_type() {
|
|
||||||
assert!(parse(r#"return { target = "t.exe", env = { F = function() end } }"#).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn missing_target_is_error() {
|
|
||||||
assert!(parse(r#"return { args = { "x" } }"#).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rejects_non_string_target() {
|
|
||||||
assert!(parse(r#"return { target = 123 }"#).is_err());
|
|
||||||
assert!(parse(r#"return { target = false }"#).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rejects_non_string_args_element() {
|
|
||||||
// ValueShunt::Args 允许基础标量(数字/布尔)转字符串,仅禁止嵌套表
|
|
||||||
let cfg = parse(r#"return { target = "t.exe", args = { 1, true } }"#).unwrap();
|
|
||||||
assert_eq!(cfg.args, vec!["1", "true"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rejects_sparse_args() {
|
|
||||||
assert!(parse(r#"return { target = "t.exe", args = { "a", nil, "b" } }"#).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rejects_non_table_args() {
|
|
||||||
assert!(parse(r#"return { target = "t.exe", args = "-B" }"#).is_err());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
11
src/lib.rs
11
src/lib.rs
@@ -1,11 +0,0 @@
|
|||||||
mod config;
|
|
||||||
mod layout;
|
|
||||||
mod logger;
|
|
||||||
mod runtime;
|
|
||||||
mod shim;
|
|
||||||
mod loader;
|
|
||||||
|
|
||||||
pub use config::ShimConfig;
|
|
||||||
pub use layout::Layout;
|
|
||||||
pub use runtime::LuaRuntime;
|
|
||||||
pub use shim::Shim;
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
use std::path::Path;
|
|
||||||
use tracing_appender::non_blocking::WorkerGuard;
|
|
||||||
use tracing_subscriber::{EnvFilter, fmt};
|
|
||||||
|
|
||||||
/// 初始化日志系统,返回的 `_guard` 必须在 main 作用域内保持存活直到程序退出
|
|
||||||
pub fn init_file_logger(log_dir: impl AsRef<Path>) -> Option<WorkerGuard> {
|
|
||||||
// 允许通过环境变量动态控制日志级别,如 SHIM_LOG=debug,默认 debug 或 info
|
|
||||||
let filter = EnvFilter::try_from_env("SHIM_LOG").unwrap_or_else(|_| EnvFilter::new("debug"));
|
|
||||||
|
|
||||||
// 1. 创建按天滚动的日志追加器 (每天生成类似 shim.2026-08-14.log)
|
|
||||||
let file_appender = tracing_appender::rolling::daily(log_dir, "shim.log");
|
|
||||||
|
|
||||||
// 2. 包装为非阻塞后台写入(不会拖慢主程序的启动与执行速度)
|
|
||||||
let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
|
|
||||||
|
|
||||||
// 3. 构建 Subscriber,只输出到文件,不输出到控制台
|
|
||||||
tracing_subscriber::fmt()
|
|
||||||
.with_env_filter(filter)
|
|
||||||
.with_writer(non_blocking) // 写入文件
|
|
||||||
.with_ansi(false) // 关闭终端彩色转义字符
|
|
||||||
.with_target(false) // 隐藏模块前缀(可选)
|
|
||||||
.init();
|
|
||||||
|
|
||||||
Some(guard)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 调用
|
|
||||||
// fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|
||||||
// // 假设日志存放在安装根目录下的 logs 文件夹
|
|
||||||
// // 也可以先快速推导 layout 拿到 log_dir
|
|
||||||
// let log_dir = "path/to/root_dir/logs";
|
|
||||||
// let _guard = init_file_logger(log_dir);
|
|
||||||
//
|
|
||||||
// // 此处写你的 Shim 业务逻辑
|
|
||||||
// // 业务代码中所有的 debug!/info!/warn! 都会静默写入文件,控制台干干净净
|
|
||||||
// let config = Shim::load()?;
|
|
||||||
//
|
|
||||||
// Ok(())
|
|
||||||
// }
|
|
||||||
101
src/shim.rs
101
src/shim.rs
@@ -1,101 +0,0 @@
|
|||||||
use crate::{LuaRuntime, ShimConfig, Layout};
|
|
||||||
use anyhow::{Context, Result, bail};
|
|
||||||
use mlua::{Table, Value};
|
|
||||||
use std::env;
|
|
||||||
use tracing::{debug, trace, warn};
|
|
||||||
pub struct Shim;
|
|
||||||
|
|
||||||
impl Shim {
|
|
||||||
pub fn load() -> Result<ShimConfig> {
|
|
||||||
let current_exe = env::current_exe().context("获取代理程序路径失败: {}")?;
|
|
||||||
debug!("当前目录 {}", current_exe.display());
|
|
||||||
|
|
||||||
let target_name = current_exe
|
|
||||||
.file_stem()
|
|
||||||
.and_then(|s| s.to_str())
|
|
||||||
.with_context(|| format!("无法从路径 [{}] 提取有效的程序名称", current_exe.display()))?
|
|
||||||
.to_lowercase();
|
|
||||||
debug!(
|
|
||||||
target_name = %target_name,
|
|
||||||
current_exe = %current_exe.display(),
|
|
||||||
"开始加载 Shim 配置"
|
|
||||||
);
|
|
||||||
let layout = Layout::discover(¤t_exe)?;
|
|
||||||
|
|
||||||
debug!(
|
|
||||||
root_dir = %layout.base_dir.display(),
|
|
||||||
bin_dir = %layout.bin_dir.display(),
|
|
||||||
tools_dir = %layout.tools_dir.display(),
|
|
||||||
"Shim 目录布局解析完成"
|
|
||||||
);
|
|
||||||
|
|
||||||
let runtime = LuaRuntime::new(&layout)?;
|
|
||||||
|
|
||||||
Self::resolve_config(&runtime, &layout, &target_name)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn resolve_config(
|
|
||||||
runtime: &LuaRuntime,
|
|
||||||
paths: &Layout,
|
|
||||||
target_name: &str,
|
|
||||||
) -> Result<ShimConfig> {
|
|
||||||
// 策略 1: 尝试加载全局配置文件 mimic.lua
|
|
||||||
let global_config = paths.base_dir.join("rshim.lua");
|
|
||||||
|
|
||||||
// if !global_config.is_file() {
|
|
||||||
// bail!(
|
|
||||||
// "未找到主配置文件: [{}],请确保在安装根目录创建 rshim.lua",
|
|
||||||
// global_config.display()
|
|
||||||
// );
|
|
||||||
// }
|
|
||||||
|
|
||||||
|
|
||||||
if global_config.is_file() {
|
|
||||||
trace!(path = %global_config.display(), "发现全局配置文件,尝试解析");
|
|
||||||
let root_table: Table = runtime.eval_script(&global_config)?;
|
|
||||||
|
|
||||||
// 检查 mimic.lua 中是否存在以 target_name 命名的 Table 节点
|
|
||||||
if root_table
|
|
||||||
.contains_key(target_name)
|
|
||||||
.context("检查全局配置失败")?
|
|
||||||
{
|
|
||||||
let target_val: ShimConfig = root_table
|
|
||||||
.get(target_name)
|
|
||||||
.with_context(|| format!("解析配置 [{}] 失败: ", target_name))?;
|
|
||||||
debug!(
|
|
||||||
target = %target_name,
|
|
||||||
source = %global_config.display(),
|
|
||||||
"成功从全局配置文件中匹配到目标工具"
|
|
||||||
);
|
|
||||||
|
|
||||||
return Ok(target_val);
|
|
||||||
}
|
|
||||||
// 穿透:若全局配置文件存在但未包含当前程序的 key,继续向下探查
|
|
||||||
trace!(target = %target_name, "全局配置文件中未包含该目标,继续探查独立配置");
|
|
||||||
}
|
|
||||||
|
|
||||||
// 策略 2: 降级寻找独立文件 ({exe}.lua),优先顺序:tools/ > root/
|
|
||||||
let target_filename = format!("{}.lua", target_name);
|
|
||||||
let candidates = [
|
|
||||||
paths.tools_dir.join(&target_filename),
|
|
||||||
paths.base_dir.join(&target_filename),
|
|
||||||
];
|
|
||||||
|
|
||||||
for config_path in &candidates {
|
|
||||||
if config_path.is_file() {
|
|
||||||
debug!(path = %config_path.display(), "找到独立配置文件,开始加载");
|
|
||||||
// 直接泛型反序列化为 ShimConfig
|
|
||||||
return runtime.eval_script::<ShimConfig>(config_path);
|
|
||||||
}
|
|
||||||
trace!(path = %config_path.display(), "独立配置文件不存在,跳过");
|
|
||||||
}
|
|
||||||
|
|
||||||
// 策略 3: 所有查找失败,抛出错误
|
|
||||||
warn!(target = %target_name, "未找到任何匹配的配置文件");
|
|
||||||
bail!(
|
|
||||||
"未找到关于 '{}' 的配置。请检查 mimic.lua 或特定的 {}.lua 文件",
|
|
||||||
target_name,
|
|
||||||
target_name
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
1527
vendor/argparse.lua
vendored
Normal file
1527
vendor/argparse.lua
vendored
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user