Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c9ac3bda59 | ||
|
|
53579f9c65 | ||
|
|
0bba69fd51 | ||
|
|
38dabd2ace | ||
|
|
94b4c23299 | ||
|
|
941558cb92 | ||
|
|
0c478ae39d |
@@ -3,3 +3,5 @@
|
||||
/.idea
|
||||
*.exe
|
||||
./Cargo.lock
|
||||
**/target
|
||||
**/Cargo.lock
|
||||
|
||||
Generated
+473
-17
@@ -11,6 +11,56 @@ 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"
|
||||
@@ -41,9 +91,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.4.3"
|
||||
version = "1.4.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "509591b7bcd67f4ef775afad7662703b4935daaa6ec0e5605cfb1090b32a2b6d"
|
||||
checksum = "0ad534f4357a5264cce5019c989cf66a4f0dc4e0d1b1d15f8aacec0ff7360273"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"shlex",
|
||||
@@ -55,6 +105,61 @@ 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 = "convert_case"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9"
|
||||
dependencies = [
|
||||
"unicode-segmentation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-channel"
|
||||
version = "0.5.16"
|
||||
@@ -70,12 +175,70 @@ version = "0.8.22"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"
|
||||
|
||||
[[package]]
|
||||
name = "crossterm"
|
||||
version = "0.29.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"crossterm_winapi",
|
||||
"derive_more",
|
||||
"document-features",
|
||||
"mio",
|
||||
"parking_lot",
|
||||
"rustix",
|
||||
"signal-hook",
|
||||
"signal-hook-mio",
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossterm_winapi"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b"
|
||||
dependencies = [
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deranged"
|
||||
version = "0.5.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
|
||||
|
||||
[[package]]
|
||||
name = "derive_more"
|
||||
version = "2.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"
|
||||
dependencies = [
|
||||
"derive_more-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "derive_more-impl"
|
||||
version = "2.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"
|
||||
dependencies = [
|
||||
"convert_case",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"rustc_version",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "document-features"
|
||||
version = "0.2.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"
|
||||
dependencies = [
|
||||
"litrs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dunce"
|
||||
version = "1.0.5"
|
||||
@@ -83,10 +246,32 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.17.0"
|
||||
name = "dyn-clone"
|
||||
version = "1.0.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d"
|
||||
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.18.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"
|
||||
|
||||
[[package]]
|
||||
name = "errno"
|
||||
version = "0.3.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
@@ -94,6 +279,61 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890"
|
||||
|
||||
[[package]]
|
||||
name = "fuzzy-matcher"
|
||||
version = "0.3.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "54614a3312934d066701a80f20f15fa3b56d67ac7722b39eea5b4c9dd1d66c94"
|
||||
dependencies = [
|
||||
"thread_local",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"r-efi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "inquire"
|
||||
version = "0.9.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6654738b8024300cf062d04a1c13c10c8e2cea598ec1c47dc9b6641159429756"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"crossterm",
|
||||
"dyn-clone",
|
||||
"fuzzy-matcher",
|
||||
"unicode-segmentation",
|
||||
"unicode-width",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inventory"
|
||||
version = "0.3.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a4f0c30c76f2f4ccee3fe55a2435f691ca00c0e4bd87abe4f4a851b1d4dac39b"
|
||||
dependencies = [
|
||||
"rustversion",
|
||||
]
|
||||
|
||||
[[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"
|
||||
@@ -106,6 +346,18 @@ version = "0.2.189"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
|
||||
|
||||
[[package]]
|
||||
name = "litrs"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"
|
||||
|
||||
[[package]]
|
||||
name = "lock_api"
|
||||
version = "0.4.14"
|
||||
@@ -123,18 +375,18 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
|
||||
|
||||
[[package]]
|
||||
name = "lua-src"
|
||||
version = "550.1.1"
|
||||
version = "551.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "75c110c2fa33f34e0de05448e1f3eb2e0631e7a69e2d8ae1586cffc9fc9f9949"
|
||||
checksum = "087097f9936a7d819bda525b32d6e96f9c54f3d35ff23ff72fc0c1697d2127db"
|
||||
dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "luajit-src"
|
||||
version = "210.7.2+b925b3e"
|
||||
version = "210.7.3+1ee778a"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "920cf654b23d217c550ceea57c32cd2a413ea27b6d47ed77b5ee0cf655adefa6"
|
||||
checksum = "869665372263eb337b14f480cfb864b89f12eade4eb42cb415f71517b4a67572"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"which",
|
||||
@@ -156,12 +408,38 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "mirror"
|
||||
name = "mio"
|
||||
version = "1.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"log",
|
||||
"wasi",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mirror-cli"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
"inquire",
|
||||
"mirror-core",
|
||||
"mlua",
|
||||
"tempfile",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mirror-core"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"mlua",
|
||||
"serde",
|
||||
"thiserror",
|
||||
"tinyjson",
|
||||
"tracing",
|
||||
"tracing-appender",
|
||||
@@ -169,16 +447,31 @@ dependencies = [
|
||||
"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.0"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ad72ffa037cf5970c9860674f32f703fda25d86cf217475fe7a79c5f9961bcaa"
|
||||
checksum = "d96e5d00f19d8c46c71ceaced99593b90c31c57aa1fe2cb3e93a8b1698eedba9"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"either",
|
||||
"inventory",
|
||||
"libc",
|
||||
"mlua-sys",
|
||||
"mlua_derive",
|
||||
"num-traits",
|
||||
"parking_lot",
|
||||
"rustc-hash",
|
||||
@@ -186,9 +479,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "mlua-sys"
|
||||
version = "0.11.0"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92136787b906d4e55cfe96cd6c62e010bb1a56889d0d6cf83eb016dbad07576b"
|
||||
checksum = "b806d7ade031f5d6607eae3e283fb034cb795a76247dd0d1ba753c8c42debccf"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"cfg-if",
|
||||
@@ -198,6 +491,17 @@ dependencies = [
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mlua_derive"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "87de1e4bdfaa4bb99d8c1449d8a34b0f19e649ef68eb5d4e8dbf1e9ec6f4a084"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nu-ansi-term"
|
||||
version = "0.50.3"
|
||||
@@ -228,6 +532,12 @@ version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "once_cell_polyfill"
|
||||
version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot"
|
||||
version = "0.12.5"
|
||||
@@ -287,6 +597,12 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "6.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||
|
||||
[[package]]
|
||||
name = "redox_syscall"
|
||||
version = "0.5.18"
|
||||
@@ -319,12 +635,56 @@ version = "2.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
|
||||
|
||||
[[package]]
|
||||
name = "rustc_version"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
|
||||
dependencies = [
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustversion"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
||||
|
||||
[[package]]
|
||||
name = "scopeguard"
|
||||
version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
|
||||
|
||||
[[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"
|
||||
@@ -360,12 +720,49 @@ version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook"
|
||||
version = "0.3.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"signal-hook-registry",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook-mio"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"mio",
|
||||
"signal-hook",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook-registry"
|
||||
version = "1.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
|
||||
dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[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"
|
||||
@@ -394,6 +791,19 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.27.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.20"
|
||||
@@ -539,6 +949,24 @@ version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-segmentation"
|
||||
version = "1.13.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-width"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
|
||||
|
||||
[[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"
|
||||
@@ -546,14 +974,42 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
|
||||
|
||||
[[package]]
|
||||
name = "which"
|
||||
version = "8.0.5"
|
||||
name = "wasi"
|
||||
version = "0.11.1+wasi-snapshot-preview1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f3ef584124b911bcc3875c2f1472e80f24361ceb789bd1c62b3e9a3df9ff43c"
|
||||
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
|
||||
|
||||
[[package]]
|
||||
name = "which"
|
||||
version = "8.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bae2f2b2b816647a1cab1acc91f5bd20812d53cb344382635ec2181940c8034f"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winapi"
|
||||
version = "0.3.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
|
||||
dependencies = [
|
||||
"winapi-i686-pc-windows-gnu",
|
||||
"winapi-x86_64-pc-windows-gnu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winapi-i686-pc-windows-gnu"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
|
||||
|
||||
[[package]]
|
||||
name = "winapi-x86_64-pc-windows-gnu"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
|
||||
+15
-11
@@ -1,19 +1,24 @@
|
||||
[package]
|
||||
name = "mirror"
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = [
|
||||
"mirror-core", "mirror-cli",
|
||||
"mirror-shim",
|
||||
]
|
||||
|
||||
#[package]
|
||||
#name = "mirror"
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.94"
|
||||
license = "MIT OR Unlicense"
|
||||
description = "A fast, safe Rust shim launcher for Scoop"
|
||||
|
||||
[profile.release]
|
||||
opt-level = "z"
|
||||
panic = "abort"
|
||||
|
||||
[dependencies]
|
||||
[workspace.dependencies]
|
||||
anyhow = "1.0.104"
|
||||
|
||||
mlua = { version = "0.12.0", features = ["lua54", "vendored","send"] }
|
||||
mlua = { version = "0.12.0", features = ["lua54", "vendored","send","macros"] }
|
||||
windows-sys = { version = "0.61.2", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_System_Com",
|
||||
@@ -30,9 +35,8 @@ dunce = "1.0.5"
|
||||
tracing = "0.1.44"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter","fmt"] }
|
||||
tracing-appender = "0.2"
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
tinyjson="2.5.1"
|
||||
#toml = "1.1.4+spec-1.1.0"
|
||||
|
||||
|
||||
[features]
|
||||
default = ["args"]
|
||||
args=[]
|
||||
@@ -0,0 +1,27 @@
|
||||
-- commands/commands.lua
|
||||
|
||||
return {
|
||||
-- 1. 单文件子命令 (commands/use.lua)
|
||||
["use"] = {
|
||||
description = "Switch the active version of a tool",
|
||||
module = mr.command("use")
|
||||
},
|
||||
|
||||
-- 2. 单文件子命令 (commands/list.lua)
|
||||
["list"] = {
|
||||
description = "List available and currently activated versions",
|
||||
module = mr.command("list")
|
||||
},
|
||||
|
||||
-- 3. 复杂多文件子命令 (加载 commands/log/init.lua)
|
||||
["log"] = {
|
||||
description = "View or configure mirror runtime logs",
|
||||
module = mr.command("log")
|
||||
},
|
||||
|
||||
-- 4. 支持别名快捷映射 (例如 mr ls 等价于 mr list)
|
||||
["ls"] = {
|
||||
description = "Alias for list",
|
||||
module = mr.command("list")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "mirror-cli"
|
||||
version = { workspace = true }
|
||||
edition = { workspace = true }
|
||||
description = "Mirror CLI Manager"
|
||||
# 显式指定生成的二进制文件名
|
||||
[[bin]]
|
||||
name = "mr"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
mirror-core = { path = "../mirror-core" }
|
||||
clap = { version = "4.6.6", features = ["cargo", "color", "derive","string"] }
|
||||
inquire="0.9.4"
|
||||
tempfile="3.27.0"# 用于安全原子写入
|
||||
mlua = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
@@ -0,0 +1,76 @@
|
||||
use crate::commands::dynamic::MrCommand;
|
||||
use clap::{Arg, ArgAction, Command};
|
||||
use mirror_core::LogLevel;
|
||||
use std::ffi::OsString;
|
||||
// 核心保留字:系统底座命令,神圣不可侵犯
|
||||
const RESERVED_COMMANDS: &[&str] = &["use", "log", "help"];
|
||||
// 引入强类型枚举
|
||||
pub fn build(dynamic_cmds: MrCommand) -> Command {
|
||||
let mut app = Command::new("mr")
|
||||
.about(env!("CARGO_PKG_DESCRIPTION"))
|
||||
.version(env!("CARGO_PKG_VERSION"))
|
||||
.arg_required_else_help(true)
|
||||
.subcommand(log_subcommand())
|
||||
.subcommand(use_subcommand());
|
||||
|
||||
for (name, sub_cmd) in dynamic_cmds.commands {
|
||||
if RESERVED_COMMANDS.contains(&name.as_str()) {
|
||||
// 用户要是手痒写了 use.lua 或 log.lua,直接装作没看见
|
||||
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
|
||||
}
|
||||
/// 核心内置命令:版本切换
|
||||
fn use_subcommand() -> Command {
|
||||
Command::new("use")
|
||||
.about("切换指定工具的生效版本 (支持交互式选择)")
|
||||
.arg(
|
||||
Arg::new("tool")
|
||||
.required(true)
|
||||
.value_name("TOOL")
|
||||
.help("目标工具名称(在 mirror.lua 中声明的 key,例如 node)"),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("version")
|
||||
.required(false)
|
||||
.value_name("VERSION")
|
||||
.help("目标版本号(省略时进入交互式单选)"),
|
||||
)
|
||||
}
|
||||
|
||||
/// 构建基础 CLI 骨架(内置 Rust 原生命令与参数规则)
|
||||
fn log_subcommand() -> Command {
|
||||
Command::new("log")
|
||||
.about("查看或修改 mirror.ini 日志配置")
|
||||
.arg(
|
||||
Arg::new("level")
|
||||
.short('l')
|
||||
.long("level")
|
||||
.value_name("LEVEL")
|
||||
.help("设置日志级别 (off, error, warn, info, debug, trace)")
|
||||
.value_parser(clap::value_parser!(LogLevel)),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("dir")
|
||||
.short('d')
|
||||
.long("dir")
|
||||
.value_name("PATH")
|
||||
.help("设置日志存放路径(绝对路径或相对于 base_dir 的相对路径)"),
|
||||
)
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
use anyhow::{Context, Result};
|
||||
use mirror_core::{Layout, LogConfig, LogLevel};
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
// Rust 原生处理 log 命令逻辑
|
||||
pub(crate) fn log_handle(layout: &Layout, matches: &clap::ArgMatches) -> Result<()> {
|
||||
let log_ini_path = layout.base_dir.join("mirror.ini");
|
||||
|
||||
let new_level = matches.get_one::<LogLevel>("level").copied();
|
||||
let new_dir = matches.get_one::<String>("dir").map(|s| s.trim());
|
||||
// 1. 反序列化:读取并解析现有配置;若文件不存在则使用默认配置
|
||||
let mut config: LogConfig = if log_ini_path.is_file() {
|
||||
let content = fs::read_to_string(&log_ini_path)
|
||||
.with_context(|| format!("读取配置文件失败: {}", log_ini_path.display()))?;
|
||||
content.parse().unwrap_or_default()
|
||||
} else {
|
||||
LogConfig::default()
|
||||
};
|
||||
// 2. 修改配置并写盘(仅更新用户指定的字段,未指定的字段保留原值)
|
||||
if new_level.is_some() || new_dir.is_some() {
|
||||
if let Some(lvl) = new_level {
|
||||
config.level = lvl;
|
||||
}
|
||||
if let Some(dir) = new_dir {
|
||||
config.log_dir = Some(PathBuf::from(dir));
|
||||
}
|
||||
|
||||
// 序列化写回
|
||||
fs::write(&log_ini_path, config.to_string())
|
||||
.with_context(|| format!("写入日志配置文件失败: {}", log_ini_path.display()))?;
|
||||
|
||||
let actual_dir = config.resolve_log_dir(&layout.base_dir);
|
||||
println!("✔ 日志配置已更新:");
|
||||
println!(" 日志级别: {}", config.level.as_str());
|
||||
println!(" 日志目录: {}", actual_dir.display());
|
||||
println!(" 配置文件: {}", log_ini_path.display());
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// 3. 无修改参数时,展示当前配置状态
|
||||
println!("=== Mirror 日志配置 ===");
|
||||
println!("配置文件: {}", log_ini_path.display());
|
||||
println!("---------------------");
|
||||
|
||||
if log_ini_path.is_file() {
|
||||
print!("{config}");
|
||||
} else {
|
||||
println!("状态: 配置文件尚未创建");
|
||||
println!("当前生效级别: {} (默认)", config.level.as_str());
|
||||
println!(
|
||||
"默认日志目录: {}",
|
||||
config.resolve_log_dir(&layout.base_dir).display()
|
||||
);
|
||||
println!("\n提示: 可使用 'mr log -l debug' 或 'mr log -d my_logs' 进行配置修改");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
use crate::validators;
|
||||
use mirror_core::{conversion_err, validation_error};
|
||||
use mlua::{FromLua, Lua, Value};
|
||||
use std::collections::HashMap;
|
||||
|
||||
const ALLOWED_KEYS: &[&str] = &["module", "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(conversion_err(
|
||||
other.type_name(),
|
||||
"MrCommand",
|
||||
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(conversion_err(
|
||||
cmd_entry.type_name(),
|
||||
"MrCommand",
|
||||
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(conversion_err(
|
||||
other.type_name(),
|
||||
"MrSubCommand",
|
||||
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 module_val = table.get::<Value>("module")?;
|
||||
// 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 module_val {
|
||||
Value::String(s) => {
|
||||
// 兜底归一化(防止用户手写 module = "a/b" 时未走 mr.command)
|
||||
// 同时兼容直接写字符串的情况
|
||||
s.to_str()?.replace(['/', '\\'], ".")
|
||||
}
|
||||
other => {
|
||||
return Err(mlua::Error::runtime(format!(
|
||||
"module 必须通过 mr.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,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
pub(crate) mod builtin;
|
||||
pub(crate) mod dynamic;
|
||||
mod use_cmd;
|
||||
|
||||
pub use use_cmd::switch_version;
|
||||
@@ -0,0 +1,145 @@
|
||||
use inquire::Select;
|
||||
use std::fs::{self, File};
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
// 引入你的 mirror-core 类型
|
||||
use mirror_core::{MirrorRegistry, TargetConfig};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum UseError {
|
||||
ToolNotFound(String),
|
||||
NotVersioned(String),
|
||||
HomeDirNotFound(PathBuf),
|
||||
NoVersionsAvailable(PathBuf),
|
||||
UserCancelled,
|
||||
Io(io::Error),
|
||||
TargetValidationFailed(PathBuf),
|
||||
}
|
||||
|
||||
/// 执行版本切换主流程
|
||||
pub fn switch_version(
|
||||
registry: &MirrorRegistry,
|
||||
tool_name: &str,
|
||||
target_version: Option<&str>,
|
||||
) -> Result<(), UseError> {
|
||||
// 1. 获取配置并断言必须是多版本工具
|
||||
let spec = registry
|
||||
.targets
|
||||
.get(tool_name)
|
||||
.ok_or_else(|| UseError::ToolNotFound(tool_name.to_string()))?;
|
||||
|
||||
let (home, version_file) = match &spec.target {
|
||||
TargetConfig::Versioned {
|
||||
home, version_file, ..
|
||||
} => {
|
||||
let v_file = version_file.as_deref().unwrap_or(".version");
|
||||
(home, v_file)
|
||||
}
|
||||
TargetConfig::Static(_) => {
|
||||
return Err(UseError::NotVersioned(tool_name.to_string()));
|
||||
}
|
||||
};
|
||||
|
||||
if !home.exists() {
|
||||
return Err(UseError::HomeDirNotFound(home.clone()));
|
||||
}
|
||||
|
||||
// 2. 扫描候选版本目录
|
||||
let available_versions = scan_versions(home)?;
|
||||
if available_versions.is_empty() {
|
||||
return Err(UseError::NoVersionsAvailable(home.clone()));
|
||||
}
|
||||
|
||||
// 3. 确定目标版本(命令行传入 OR 唤起 Inquire 单选菜单)
|
||||
let selected_ver = match target_version {
|
||||
Some(ver) => {
|
||||
// 如果用户传了参,校验是否在候选集中(防呆)
|
||||
if !available_versions.iter().any(|v| v == ver) {
|
||||
eprintln!(
|
||||
"警告: 目录 {:?} 下未发现版本 '{}',仍将强制写入。",
|
||||
home, ver
|
||||
);
|
||||
}
|
||||
ver.to_string()
|
||||
}
|
||||
None => {
|
||||
// 尝试读取当前已激活的版本,作为 Inquire 的默认初始高亮项
|
||||
let current_version_path = home.join(version_file);
|
||||
let current_ver = fs::read_to_string(¤t_version_path)
|
||||
.map(|s| s.trim().to_string())
|
||||
.ok();
|
||||
|
||||
prompt_user_select(&available_versions, current_ver.as_deref())?
|
||||
}
|
||||
};
|
||||
|
||||
// 4. 原子化持久化写入版本文件
|
||||
let dest_version_path = home.join(version_file);
|
||||
atomic_write(&dest_version_path, &selected_ver).map_err(UseError::Io)?;
|
||||
|
||||
println!("✔ 已成功将 '{}' 切换至版本: {}", tool_name, selected_ver);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 扫描 home 目录下的非隐藏有效子文件夹作为版本列表
|
||||
fn scan_versions(home: &Path) -> Result<Vec<String>, UseError> {
|
||||
let mut versions = Vec::new();
|
||||
|
||||
let entries = fs::read_dir(home).map_err(UseError::Io)?;
|
||||
for entry in entries.filter_map(|e| e.ok()) {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
if let Some(dir_name) = path.file_name().and_then(|n| n.to_str()) {
|
||||
// 排除以点开头的隐藏目录(如 .git, .cache)
|
||||
if !dir_name.starts_with('.') {
|
||||
versions.push(dir_name.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 自然排序版本列表
|
||||
versions.sort();
|
||||
Ok(versions)
|
||||
}
|
||||
|
||||
/// 唤起 Inquire 进行交互单选
|
||||
fn prompt_user_select(
|
||||
versions: &[String],
|
||||
default_version: Option<&str>,
|
||||
) -> Result<String, UseError> {
|
||||
let mut prompt = Select::new("请选择要激活的目标版本:", versions.to_vec());
|
||||
|
||||
// 如果能读取到当前版本,默认选中该项
|
||||
if let Some(def) = default_version {
|
||||
if let Some(idx) = versions.iter().position(|v| v == def) {
|
||||
prompt.starting_cursor = idx;
|
||||
}
|
||||
}
|
||||
|
||||
prompt.prompt().map_err(|_| UseError::UserCancelled)
|
||||
}
|
||||
|
||||
/// 使用临时文件同目录重命名实现“原子写入”
|
||||
///
|
||||
/// 杜绝中途掉电、杀死进程导致的空文件损坏
|
||||
fn atomic_write(dest_path: &Path, content: &str) -> io::Result<()> {
|
||||
let parent_dir = dest_path
|
||||
.parent()
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "Parent dir not found"))?;
|
||||
|
||||
// 必须在目标文件的同级目录下创建临时文件,跨盘符/分区会导致原子重命名 (Rename) 失败
|
||||
let mut temp_file = NamedTempFile::new_in(parent_dir)?;
|
||||
|
||||
// 写入纯净内容,并强制落盘刷新 (Flush)
|
||||
temp_file.write_all(content.trim().as_bytes())?;
|
||||
temp_file.write_all(b"\n")?; // 末尾留标准换行符
|
||||
temp_file.as_file().sync_all()?;
|
||||
|
||||
// 核心操作:原子覆盖(在 Windows 上内部会调用 ReplaceFileW,在 Unix 则是 rename)
|
||||
temp_file.persist(dest_path).map_err(|e| e.error)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
|
||||
pub struct ExecuteError {
|
||||
pub code: i32,
|
||||
pub source: anyhow::Error,
|
||||
}
|
||||
|
||||
impl ExecuteError {
|
||||
pub fn new(code: i32, err: impl Into<anyhow::Error>) -> Self {
|
||||
Self {
|
||||
code,
|
||||
source: err.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
use crate::cli;
|
||||
use crate::commands::{builtin, dynamic::MrCommand};
|
||||
use crate::error::ExecuteError;
|
||||
use crate::plugins::register_mr_command;
|
||||
use crate::commands::switch_version;
|
||||
use anyhow::{Context, Result};
|
||||
use mirror_core::{Layout, LuaRuntime, register_basics};
|
||||
use mirror_core::MirrorRegistry;
|
||||
// 成功的标准退出码
|
||||
pub const EXIT_SUCCESS: i32 = 0;
|
||||
|
||||
// mr CLI 专有错误退出码
|
||||
pub const EXIT_CONFIG_ERROR: i32 = 10; // 配置文件加载、解析失败
|
||||
pub const EXIT_RUNTIME_ERROR: i32 = 11; // Lua 运行时初始化或脚本执行异常
|
||||
pub const EXIT_COMMAND_NOT_FOUND: i32 = 12; // 找不到指定的子命令
|
||||
pub const EXIT_BUILTIN_ERROR: i32 = 13; // 原生命令(如 log)执行失败
|
||||
|
||||
pub fn run(layout: &Layout) -> Result<(), ExecuteError> {
|
||||
|
||||
|
||||
let runtime = LuaRuntime::builder()
|
||||
.with(|lua| register_basics(lua, layout))
|
||||
.with(register_mr_command)
|
||||
.build()
|
||||
.map_err(|e| ExecuteError::new(EXIT_RUNTIME_ERROR, e))?;
|
||||
|
||||
let registry_file = layout.base_dir.join("commands").join("commands.lua");
|
||||
let commands: MrCommand = runtime
|
||||
.eval_script(®istry_file)
|
||||
.with_context(|| format!("加载命令配置失败: {}", registry_file.display()))
|
||||
.map_err(|e| ExecuteError::new(EXIT_CONFIG_ERROR, e))?;
|
||||
|
||||
let app = cli::build(commands.clone());
|
||||
let matches = app.get_matches();
|
||||
|
||||
match matches.subcommand() {
|
||||
|
||||
Some(("use", sub_matches)) => {
|
||||
let tool = sub_matches.get_one::<String>("tool").unwrap();
|
||||
let version = sub_matches.get_one::<String>("version").map(|s| s.as_str());
|
||||
|
||||
// 惰性加载 mirror.lua:按需获取 MirrorRegistry
|
||||
let mirror_file = layout.base_dir.join("mirror.lua");
|
||||
let registry: MirrorRegistry = runtime
|
||||
.eval_script(&mirror_file)
|
||||
.with_context(|| format!("解析主配置失败: {}", mirror_file.display()))
|
||||
.map_err(|e| ExecuteError::new(EXIT_CONFIG_ERROR, e))?;
|
||||
|
||||
if let Err(e) = switch_version(®istry, tool, version) {
|
||||
eprintln!("[mr] 切换失败: {:?}", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// 分支 A: 原生 Rust 实现的命令
|
||||
Some(("log", sub_m)) => {
|
||||
builtin::log_handle(&layout, sub_m)
|
||||
.map_err(|e| ExecuteError::new(EXIT_BUILTIN_ERROR, e))?;
|
||||
}
|
||||
|
||||
// 分支 B: 动态 Lua 注册的命令
|
||||
Some((cmd_name, sub_m)) => {
|
||||
let sub_cmd = commands.get(cmd_name).ok_or_else(|| {
|
||||
ExecuteError::new(
|
||||
EXIT_COMMAND_NOT_FOUND,
|
||||
anyhow::anyhow!("未找到子命令 '{cmd_name}'"),
|
||||
)
|
||||
})?;
|
||||
|
||||
let raw_args = cli::extract_raw_args(sub_m);
|
||||
runtime
|
||||
.require_and_run(&sub_cmd.module, raw_args)
|
||||
.map_err(|e| {
|
||||
ExecuteError::new(
|
||||
EXIT_COMMAND_NOT_FOUND,
|
||||
anyhow::anyhow!("执行子命令 '{}' 失败: {:#}", cmd_name, e),
|
||||
)
|
||||
})?;
|
||||
}
|
||||
|
||||
// 分支 C: 未输入子命令(通常已被 Clap 的 arg_required_else_help 拦截)
|
||||
None => {}//unreachable!(),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
use crate::executor::EXIT_SUCCESS;
|
||||
use anyhow::Context;
|
||||
use mirror_core::{Layout, init_logging_from};
|
||||
use std::process::exit;
|
||||
use tracing::{debug, error};
|
||||
|
||||
mod cli;
|
||||
mod commands;
|
||||
mod error;
|
||||
mod executor;
|
||||
mod plugins;
|
||||
mod validators;
|
||||
|
||||
fn main() {
|
||||
let current_exe = match std::env::current_exe().context("获取代理程序路径失败") {
|
||||
Ok(exe) => exe,
|
||||
Err(e) => {
|
||||
eprintln!("垫片启动失败: {:#}", e);
|
||||
exit(1);
|
||||
}
|
||||
};
|
||||
let layout = match Layout::from(¤t_exe) {
|
||||
Ok(l) => l,
|
||||
Err(e) => {
|
||||
eprintln!("解析程序目录布局失败: {:#}", e);
|
||||
exit(1);
|
||||
}
|
||||
};
|
||||
let _guard = init_logging_from(&layout);
|
||||
|
||||
debug!("=== 管理程序启动 ===");
|
||||
debug!(
|
||||
exe = %current_exe.display(),
|
||||
target_name = %layout.target_name,
|
||||
"日志系统与布局上下文已就位"
|
||||
);
|
||||
// 核心运行:成功退出 0,失败根据 AppError 里的 code 退出
|
||||
if let Err(app_err) = executor::run(&layout) {
|
||||
error!("{:#}", app_err.source);
|
||||
exit(app_err.code);
|
||||
}
|
||||
|
||||
exit(EXIT_SUCCESS);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
use mirror_core::Result;
|
||||
use mlua::{Lua, Table, Value};
|
||||
|
||||
/// 仅存在于 CLI 侧的 DSL 扩展函数
|
||||
pub fn register_mr_command(lua: &Lua) -> Result<()> {
|
||||
let globals = lua.globals();
|
||||
|
||||
let mr_table: Table = match globals.get("mr")? {
|
||||
Value::Table(tbl) => tbl,
|
||||
_ => {
|
||||
let tbl = lua.create_table()?;
|
||||
globals.set("mr", &tbl)?;
|
||||
tbl
|
||||
}
|
||||
};
|
||||
|
||||
let command_fn = lua.create_function(|_lua, mod_path: String| {
|
||||
let normalized = mod_path.replace(['/', '\\'], ".");
|
||||
Ok(normalized)
|
||||
})?;
|
||||
|
||||
mr_table.set("command", command_fn)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
use mirror_core::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)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "mirror-core"
|
||||
version = { workspace = true }
|
||||
edition = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
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 }
|
||||
thiserror = "2.0.20"
|
||||
|
||||
|
||||
|
||||
[features]
|
||||
default = []
|
||||
args = []
|
||||
@@ -0,0 +1,39 @@
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::OsString;
|
||||
|
||||
/// 单个目标程序的代理规格配置
|
||||
|
||||
|
||||
/// 1. 核心参数路由解析(Delegation 到 Spec 的路由逻辑)
|
||||
pub fn expand_aliases<I, S>(aliases: &HashMap<String, Vec<OsString>>, 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) = 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
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub(crate) mod alias;
|
||||
pub(crate) mod tokens;
|
||||
@@ -1,75 +1,4 @@
|
||||
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('\\', "/")
|
||||
}
|
||||
|
||||
/// 将 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
|
||||
/// - 自动过滤连续空格
|
||||
@@ -136,7 +65,6 @@ pub fn parse_tokens(input: &str) -> Vec<OsString> {
|
||||
|
||||
tokens
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -230,4 +158,4 @@ mod tests {
|
||||
// 场景 8:未闭合引号的容错处理(会尽量追加到当前 Token 中)
|
||||
assert_tokens!("echo \"hello world", vec!["echo", "hello world"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
use crate::{Error, Result};
|
||||
use mlua::LuaString;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::fmt;
|
||||
|
||||
/// Lua 字符串 -> OsString(Linux 直接透传字节,Windows 回退到系统代码页)
|
||||
pub(crate) fn lua_string_2_os_string(s: &LuaString) -> 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(Error::EncodingError {
|
||||
from: "LuaString",
|
||||
to: "OsString".to_string(),
|
||||
message: format!("字符串{:?}包含无效或当前系统无法识别的编码字节", s),
|
||||
});
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 跨平台检查 `OsStr` 中是否含 NUL 字符
|
||||
pub(crate) fn ensure_no_nul(context: &impl fmt::Display, os_str: &OsStr) -> Result<()> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
if os_str.as_bytes().contains(&0) {
|
||||
return Err(Error::ContainsNul(format!(
|
||||
"{} 的值不能包含 NUL 字符",
|
||||
context
|
||||
)));
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
if os_str.encode_wide().any(|c| c == 0) {
|
||||
return Err(Error::ContainsNul(format!(
|
||||
"{} 的值不能包含 NUL 字符",
|
||||
context
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
//! Lua 边界层:只负责把 Lua 值搬成 DTO,不做任何语义判断。
|
||||
//!
|
||||
//! 这一层实现的是 mlua 的 `FromLua`,错误天然是 `mlua::Error`。
|
||||
//! 领域规则(必填字段、类型、编码、命令名、别名环)全部在 `model.rs` 的
|
||||
//! `TryFrom` 里,那里的错误统一是 `crate::Error`。
|
||||
|
||||
use super::model::{MirrorSpec, TargetSpec};
|
||||
use mlua::{FromLua, Lua, Table, Value};
|
||||
|
||||
/// 注册表 DTO:键值对原样保留,命令名合法性交给领域层判断。
|
||||
pub(crate) struct MirrorSpecDto {
|
||||
pub entries: Vec<(Value, TargetSpecDto)>,
|
||||
}
|
||||
|
||||
impl FromLua for MirrorSpecDto {
|
||||
fn from_lua(value: Value, _lua: &Lua) -> mlua::Result<Self> {
|
||||
let root = value
|
||||
.as_table()
|
||||
.ok_or_else(|| mlua::Error::FromLuaConversionError {
|
||||
from: value.type_name(),
|
||||
to: "Table".into(),
|
||||
message: Some("mirror 全局注册表顶层必须是 table".into()),
|
||||
})?;
|
||||
|
||||
let mut entries = Vec::new();
|
||||
for pair in root.pairs::<Value, Value>() {
|
||||
let (key, entry) = pair?;
|
||||
let entry = entry
|
||||
.as_table()
|
||||
.ok_or_else(|| mlua::Error::FromLuaConversionError {
|
||||
from: entry.type_name(),
|
||||
to: "Table".into(),
|
||||
message: Some(format!(
|
||||
"目标工具 '{}' 的配置必须是 table,实际是 {}",
|
||||
display_key(&key),
|
||||
entry.type_name()
|
||||
)),
|
||||
})?;
|
||||
entries.push((key, TargetSpecDto::from_table(&entry)?));
|
||||
}
|
||||
Ok(Self { entries })
|
||||
}
|
||||
}
|
||||
|
||||
/// 单个目标工具配置的 DTO:字段原样保留,类型判断留给领域层。
|
||||
///
|
||||
/// 字段一律用 `Value`:Lua 里"字段不存在"和"字段是 nil"是同一件事,
|
||||
/// 都用 `Value::Nil` 表示。用 `Option<Value>` 反而会有两种"缺失"写法。
|
||||
pub(crate) struct TargetSpecDto {
|
||||
pub target: TargetDto,
|
||||
pub args: Value,
|
||||
pub env: Value,
|
||||
pub aliases: Value,
|
||||
}
|
||||
|
||||
impl TargetSpecDto {
|
||||
fn from_table(table: &Table) -> mlua::Result<Self> {
|
||||
Ok(Self {
|
||||
target: TargetDto::from_value(table.get::<Value>("target")?)?,
|
||||
args: table.get::<Value>("args")?,
|
||||
env: table.get::<Value>("env")?,
|
||||
aliases: table.get::<Value>("aliases")?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// target 的"形状":标量还是多版本 table。
|
||||
///
|
||||
/// `Value::Nil`(字段没写)会落进 `Scalar`,由领域层决定它是错误还是默认值。
|
||||
/// 字符串能不能当路径、table 里 `home` 是否必填,也都留给领域层判断。
|
||||
pub(crate) enum TargetDto {
|
||||
Scalar(Value),
|
||||
Versioned {
|
||||
home: Value,
|
||||
version_file: Value,
|
||||
current: Value,
|
||||
},
|
||||
}
|
||||
|
||||
impl TargetDto {
|
||||
fn from_value(value: Value) -> mlua::Result<Self> {
|
||||
match value {
|
||||
Value::Table(table) => Ok(Self::Versioned {
|
||||
home: table.get::<Value>("home")?,
|
||||
version_file: table.get::<Value>("version_file")?,
|
||||
current: table.get::<Value>("current")?,
|
||||
}),
|
||||
other => Ok(Self::Scalar(other)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 错误信息里显示注册表 key;非字符串 key 退化成类型名。
|
||||
fn display_key(key: &Value) -> String {
|
||||
match key {
|
||||
Value::String(s) => s
|
||||
.to_str()
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|_| "<非 UTF-8>".to_string()),
|
||||
other => other.type_name().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 兼容适配器
|
||||
//
|
||||
// 消费方目前仍使用 `runtime.eval_script::<MirrorRegistry>(...)` 和
|
||||
// `MirrorTarget::from_lua(...)`,所以保留这两个薄适配器:
|
||||
// 边界提取(DTO)→ 领域转换(TryFrom)→ 错误翻译(Into)。
|
||||
// 领域逻辑一行都不在这两个 impl 里。
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
impl FromLua for MirrorSpec {
|
||||
fn from_lua(value: Value, lua: &Lua) -> mlua::Result<Self> {
|
||||
let dto = MirrorSpecDto::from_lua(value, lua)?;
|
||||
MirrorSpec::try_from(dto).map_err(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
impl FromLua for TargetSpec {
|
||||
fn from_lua(value: Value, _lua: &Lua) -> mlua::Result<Self> {
|
||||
let table = value
|
||||
.as_table()
|
||||
.ok_or_else(|| mlua::Error::FromLuaConversionError {
|
||||
from: value.type_name(),
|
||||
to: "Table".into(),
|
||||
message: Some("目标工具配置必须是 table".into()),
|
||||
})?;
|
||||
let dto = TargetSpecDto::from_table(&table)?;
|
||||
TargetSpec::try_from(dto).map_err(Into::into)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
pub(crate) mod convert;
|
||||
pub(crate) mod dto;
|
||||
pub(crate) mod model;
|
||||
pub(crate) mod naming;
|
||||
pub(crate) mod values;
|
||||
|
||||
pub use model::{MirrorSpec, Target, TargetSpec};
|
||||
pub use naming::parse_command_name;
|
||||
|
||||
// 兼容旧名:mirror-shim / mirror-cli 目前仍按这些名字引用。
|
||||
// 等消费方迁移到 MirrorSpec / TargetSpec / Target 后可以删掉。
|
||||
pub type MirrorRegistry = MirrorSpec;
|
||||
pub type MirrorTarget = TargetSpec;
|
||||
pub type TargetConfig = Target;
|
||||
|
||||
use crate::{LuaRuntime, Result};
|
||||
use std::path::Path;
|
||||
|
||||
/// 配置加载入口:边界提取(DTO)→ 领域转换(TryFrom)。
|
||||
///
|
||||
/// 调用方拿到的错误全部是 `crate::Error`;DTO 与 mlua 的错误类型
|
||||
/// 都被关在这个函数内部。
|
||||
pub fn load_mirror_spec(runtime: &LuaRuntime, path: impl AsRef<Path>) -> Result<MirrorSpec> {
|
||||
let dto: dto::MirrorSpecDto = runtime.eval_script(path)?;
|
||||
MirrorSpec::try_from(dto)
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
//! 领域模型:只描述"配置应该长什么样",不实现 mlua 的 `FromLua`。
|
||||
//!
|
||||
//! 两阶段加载:
|
||||
//! 1. `config::dto` 把 Lua 值搬成 DTO(边界,错误是 mlua 形状)
|
||||
//! 2. 本文件的 `TryFrom<DTO>` 做语义校验与类型转换(错误全部是 `crate::Error`)
|
||||
|
||||
use crate::config::convert::{ensure_no_nul, lua_string_2_os_string};
|
||||
use crate::config::dto::{MirrorSpecDto, TargetDto, TargetSpecDto};
|
||||
use crate::config::values::{parse_aliases, parse_args, parse_env};
|
||||
use crate::{Error, Result, parse_command_name};
|
||||
use mlua::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub struct MirrorSpec {
|
||||
pub targets: HashMap<String, TargetSpec>,
|
||||
}
|
||||
|
||||
impl TryFrom<MirrorSpecDto> for MirrorSpec {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(dto: MirrorSpecDto) -> Result<Self> {
|
||||
let mut targets = HashMap::with_capacity(dto.entries.len());
|
||||
for (key, tool) in dto.entries {
|
||||
let name = parse_command_name(&key)?;
|
||||
targets.insert(name, TargetSpec::try_from(tool)?);
|
||||
}
|
||||
Ok(Self { targets })
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct TargetSpec {
|
||||
/// 目标程序可执行文件路径
|
||||
pub target: Target,
|
||||
/// 默认预设参数列表
|
||||
pub args: Vec<OsString>,
|
||||
/// 参数别名映射表(用于展开以 mr: 为前缀的别名)
|
||||
pub aliases: HashMap<String, Vec<OsString>>,
|
||||
/// 注入/覆盖的环境变量
|
||||
pub env: HashMap<String, OsString>,
|
||||
}
|
||||
|
||||
impl TargetSpec {
|
||||
pub fn resolve_args<I, S>(&self, args: I) -> Vec<OsString>
|
||||
where
|
||||
I: IntoIterator<Item = S>,
|
||||
S: AsRef<OsStr>,
|
||||
{
|
||||
crate::args::alias::expand_aliases(&self.aliases, args)
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<TargetSpecDto> for TargetSpec {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(dto: TargetSpecDto) -> Result<Self> {
|
||||
let target = Target::try_from(dto.target)?;
|
||||
|
||||
let args = match dto.args {
|
||||
Value::Nil => Vec::new(),
|
||||
value => parse_args(&value)?,
|
||||
};
|
||||
let aliases = match dto.aliases {
|
||||
Value::Nil => HashMap::new(),
|
||||
value => parse_aliases(&value)?,
|
||||
};
|
||||
let env = match dto.env {
|
||||
Value::Nil => HashMap::new(),
|
||||
value => parse_env(&value)?,
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
target,
|
||||
args,
|
||||
aliases,
|
||||
env,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// 目标可执行文件的定位配置(支持静态路径与多版本 Table)
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Target {
|
||||
/// 静态单版本工具
|
||||
Static(PathBuf),
|
||||
/// 多版本管理
|
||||
Versioned {
|
||||
/// 工具主根目录(供 mr use 扫描候选版本)
|
||||
home: PathBuf,
|
||||
/// 版本真相源文件名(如 ".version",可选,默认 ".version")
|
||||
version_file: Option<String>,
|
||||
/// 当前激活版本的可执行文件完整路径(若未激活或不存在则为 None)
|
||||
current: Option<PathBuf>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Default for Target {
|
||||
fn default() -> Self {
|
||||
Target::Static(PathBuf::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl Target {
|
||||
/// 垫片程序(mirror-shim)专用快速通道:提取最终可执行路径
|
||||
///
|
||||
/// - Static: 返回自身路径
|
||||
/// - Versioned: 返回 current 路径(若未激活则返回 None)
|
||||
pub fn executable_path(&self) -> Option<&PathBuf> {
|
||||
match self {
|
||||
Target::Static(path) => Some(path),
|
||||
Target::Versioned { current, .. } => current.as_ref(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 管理程序(mr-cli)专用辅助方法:判断是否支持多版本
|
||||
pub fn is_versioned(&self) -> bool {
|
||||
matches!(self, Target::Versioned { .. })
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<TargetDto> for Target {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(dto: TargetDto) -> Result<Self> {
|
||||
match dto {
|
||||
TargetDto::Scalar(Value::String(s)) => {
|
||||
let os_str = lua_string_2_os_string(&s)?;
|
||||
ensure_no_nul(&"target", &os_str)?;
|
||||
Ok(Target::Static(PathBuf::from(os_str)))
|
||||
}
|
||||
TargetDto::Scalar(Value::Nil) => Err(Error::MissingField {
|
||||
field: "target(应为字符串路径或多版本配置表)".into(),
|
||||
}),
|
||||
TargetDto::Scalar(other) => Err(Error::TypeMismatch {
|
||||
field: "target".into(),
|
||||
expected: "有效路径字符串或多版本配置表",
|
||||
actual: other.type_name(),
|
||||
}),
|
||||
TargetDto::Versioned {
|
||||
home,
|
||||
version_file,
|
||||
current,
|
||||
} => {
|
||||
let home = required_path(home, "home(多版本 target 表)", "target.home")?;
|
||||
let version_file = optional_string(version_file, "target.version_file")?;
|
||||
let current = optional_path(current, "target.current")?;
|
||||
|
||||
Ok(Target::Versioned {
|
||||
home,
|
||||
version_file,
|
||||
current,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 必填路径字段:缺失/nil 报 `MissingField`,类型不符报 `TypeMismatch`
|
||||
fn required_path(value: Value, field: &str, context: &str) -> Result<PathBuf> {
|
||||
match value {
|
||||
Value::Nil => Err(Error::MissingField {
|
||||
field: field.to_string(),
|
||||
}),
|
||||
Value::String(s) => {
|
||||
let os_str = lua_string_2_os_string(&s)?;
|
||||
ensure_no_nul(&context, &os_str)?;
|
||||
Ok(PathBuf::from(os_str))
|
||||
}
|
||||
other => Err(Error::TypeMismatch {
|
||||
field: context.to_string(),
|
||||
expected: "路径字符串",
|
||||
actual: other.type_name(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// 可选字符串字段:缺失/nil 视为 None
|
||||
fn optional_string(value: Value, context: &str) -> Result<Option<String>> {
|
||||
match value {
|
||||
Value::Nil => Ok(None),
|
||||
Value::String(s) => {
|
||||
let os_str = lua_string_2_os_string(&s)?;
|
||||
ensure_no_nul(&context, &os_str)?;
|
||||
Ok(Some(os_str.to_string_lossy().into_owned()))
|
||||
}
|
||||
other => Err(Error::TypeMismatch {
|
||||
field: context.to_string(),
|
||||
expected: "字符串 (String)",
|
||||
actual: other.type_name(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// 可选路径字段:缺失/nil 视为 None
|
||||
fn optional_path(value: Value, context: &str) -> Result<Option<PathBuf>> {
|
||||
match value {
|
||||
Value::Nil => Ok(None),
|
||||
Value::String(s) => {
|
||||
let os_str = lua_string_2_os_string(&s)?;
|
||||
ensure_no_nul(&context, &os_str)?;
|
||||
Ok(Some(PathBuf::from(os_str)))
|
||||
}
|
||||
other => Err(Error::TypeMismatch {
|
||||
field: context.to_string(),
|
||||
expected: "有效路径字符串 (LuaString) 或 nil",
|
||||
actual: other.type_name(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// 领域转换直接产出 crate::Error,不再被 mlua 包一层
|
||||
#[test]
|
||||
fn scalar_target_with_wrong_type_is_domain_error() {
|
||||
let err = Target::try_from(TargetDto::Scalar(Value::Integer(42))).unwrap_err();
|
||||
match err {
|
||||
Error::TypeMismatch { field, actual, .. } => {
|
||||
assert_eq!(field, "target");
|
||||
assert_eq!(actual, "integer");
|
||||
}
|
||||
other => panic!("unexpected error: {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn versioned_target_requires_home() {
|
||||
let dto = TargetDto::Versioned {
|
||||
home: Value::Nil,
|
||||
version_file: Value::Nil,
|
||||
current: Value::Nil,
|
||||
};
|
||||
let err = Target::try_from(dto).unwrap_err();
|
||||
assert!(matches!(err, Error::MissingField { field } if field.starts_with("home")));
|
||||
}
|
||||
|
||||
/// 字段不存在和字段是 nil,在 Lua 里是同一件事
|
||||
#[test]
|
||||
fn nil_target_is_missing_field() {
|
||||
let err = Target::try_from(TargetDto::Scalar(Value::Nil)).unwrap_err();
|
||||
assert!(matches!(err, Error::MissingField { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optional_field_type_is_checked() {
|
||||
let err = optional_string(Value::Integer(1), "target.version_file").unwrap_err();
|
||||
assert!(matches!(err, Error::TypeMismatch { field, .. } if field == "target.version_file"));
|
||||
|
||||
let err = optional_path(Value::Integer(1), "target.current").unwrap_err();
|
||||
assert!(matches!(err, Error::TypeMismatch { field, .. } if field == "target.current"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_target_is_missing_field() {
|
||||
let dto = TargetSpecDto {
|
||||
target: TargetDto::Scalar(Value::Nil),
|
||||
args: Value::Nil,
|
||||
env: Value::Nil,
|
||||
aliases: Value::Nil,
|
||||
};
|
||||
let err = TargetSpec::try_from(dto).unwrap_err();
|
||||
assert!(matches!(err, Error::MissingField { .. }));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
//! 名称规则:注册表键(命令名)、环境变量名、别名键。
|
||||
//!
|
||||
//! 三类名称的规则不同:
|
||||
//! - 命令名:非空、不能含空白字符、不能含 `=`、不能含 NUL
|
||||
//! - 环境变量名 / 别名:非空、不能含 `=`、不能含 NUL(允许空格)
|
||||
|
||||
use crate::{Error, NameKind, Result};
|
||||
use mlua::Value;
|
||||
|
||||
/// 校验注册表键(命令名)
|
||||
pub fn parse_command_name(name: &Value) -> Result<String> {
|
||||
let name = parse_string(name, NameKind::Command)?;
|
||||
|
||||
if name.trim().is_empty() {
|
||||
return Err(invalid(NameKind::Command, "不能为空字符串"));
|
||||
}
|
||||
if name.contains(|c: char| c.is_whitespace()) {
|
||||
return Err(invalid(
|
||||
NameKind::Command,
|
||||
format!("[{name}] 不能包含空格或空白字符"),
|
||||
));
|
||||
}
|
||||
if name.contains('=') {
|
||||
return Err(invalid(NameKind::Command, format!("[{name}] 不能包含 '='")));
|
||||
}
|
||||
if name.contains('\0') {
|
||||
return Err(invalid(
|
||||
NameKind::Command,
|
||||
format!("[{name}] 不能包含 NUL 字符"),
|
||||
));
|
||||
}
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// 校验环境变量名 / 别名键
|
||||
pub(crate) fn parse_name(kind: NameKind, name: &Value) -> Result<String> {
|
||||
let name = parse_string(name, kind)?;
|
||||
|
||||
if name.is_empty() {
|
||||
return Err(invalid(kind, "不能为空"));
|
||||
}
|
||||
if name.contains('=') {
|
||||
return Err(invalid(kind, format!("[{name}] 不能包含 '='")));
|
||||
}
|
||||
if name.contains('\0') {
|
||||
return Err(invalid(kind, format!("[{name}] 不能包含 NUL 字符")));
|
||||
}
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// 取字符串值;类型不对报 `TypeMismatch`,字节不是 UTF-8 报 `EncodingError`
|
||||
fn parse_string(value: &Value, kind: NameKind) -> Result<String> {
|
||||
match value {
|
||||
Value::String(s) => {
|
||||
s.to_str()
|
||||
.map(|text| text.to_string())
|
||||
.map_err(|e| Error::EncodingError {
|
||||
from: "LuaString",
|
||||
to: "String".to_string(),
|
||||
message: format!("{kind}不是合法的 UTF-8 字符串: {e}"),
|
||||
})
|
||||
}
|
||||
other => Err(Error::TypeMismatch {
|
||||
field: kind.to_string(),
|
||||
expected: "字符串 (String)",
|
||||
actual: other.type_name(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid(kind: NameKind, reason: impl Into<String>) -> Error {
|
||||
Error::InvalidName {
|
||||
kind,
|
||||
reason: reason.into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use mlua::Lua;
|
||||
|
||||
fn string(lua: &Lua, text: &str) -> Value {
|
||||
Value::String(lua.create_string(text).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_name_accepts_plain_name() {
|
||||
let lua = Lua::new();
|
||||
assert_eq!(parse_command_name(&string(&lua, "git")).unwrap(), "git");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_name_rejects_whitespace_and_equals() {
|
||||
let lua = Lua::new();
|
||||
for bad in ["git status", "git=1", " ", ""] {
|
||||
let err = parse_command_name(&string(&lua, bad)).unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
Error::InvalidName {
|
||||
kind: NameKind::Command,
|
||||
..
|
||||
}
|
||||
),
|
||||
"unexpected error for {bad:?}: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_name_type_error_is_type_mismatch() {
|
||||
let err = parse_command_name(&Value::Integer(1)).unwrap_err();
|
||||
assert!(matches!(err, Error::TypeMismatch { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn env_name_allows_space_but_rejects_equals() {
|
||||
let lua = Lua::new();
|
||||
assert_eq!(
|
||||
parse_name(NameKind::EnvVar, &string(&lua, "MY VAR")).unwrap(),
|
||||
"MY VAR"
|
||||
);
|
||||
let err = parse_name(NameKind::EnvVar, &string(&lua, "FOO=1")).unwrap_err();
|
||||
assert!(matches!(
|
||||
err,
|
||||
Error::InvalidName {
|
||||
kind: NameKind::EnvVar,
|
||||
..
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alias_name_rejects_empty() {
|
||||
let lua = Lua::new();
|
||||
let err = parse_name(NameKind::Alias, &string(&lua, "")).unwrap_err();
|
||||
assert!(matches!(
|
||||
err,
|
||||
Error::InvalidName {
|
||||
kind: NameKind::Alias,
|
||||
..
|
||||
}
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
use super::as_table;
|
||||
use super::scalar::{ScalarMode, to_os_strings};
|
||||
use super::sequence::as_strict_sequence;
|
||||
use crate::config::naming::parse_name;
|
||||
use crate::{Error, NameKind, Result};
|
||||
use mlua::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::OsString;
|
||||
|
||||
const CONTEXT: &str = "命令行别名 (aliases)";
|
||||
/// 数组嵌套上限,防止畸形配置打爆调用栈
|
||||
const MAX_DEPTH: usize = 16;
|
||||
/// `mr:` 引用链的最大深度
|
||||
const MAX_ALIAS_DEPTH: usize = 32;
|
||||
|
||||
/// `aliases = { name = value }` → 已展开的别名表。
|
||||
///
|
||||
/// value 是"命令行片段":字符串按 shell 规则分词,数组逐项处理。
|
||||
/// `mr:other` 在加载期递归展开;引用不存在的别名时原样保留;循环引用报错。
|
||||
pub(crate) fn parse_aliases(value: &Value) -> Result<HashMap<String, Vec<OsString>>> {
|
||||
let table = as_table(value, CONTEXT)?;
|
||||
let mut raw: HashMap<String, Vec<OsString>> = HashMap::with_capacity(table.raw_len().min(128));
|
||||
|
||||
for pair in table.pairs::<Value, Value>() {
|
||||
let (raw_key, raw_value) = pair?;
|
||||
let name = parse_name(NameKind::Alias, &raw_key)?;
|
||||
let context = format!("别名 '{name}'");
|
||||
|
||||
let mut parts = Vec::new();
|
||||
flatten(&raw_value, &context, 0, &mut parts)?;
|
||||
raw.insert(name, parts);
|
||||
}
|
||||
|
||||
expand_graph(&raw)
|
||||
}
|
||||
|
||||
/// 递归展平标量与嵌套数组,字符串按 shell 规则分词
|
||||
fn flatten(value: &Value, context: &str, depth: usize, out: &mut Vec<OsString>) -> Result<()> {
|
||||
if depth > MAX_DEPTH {
|
||||
return Err(Error::ParseError(format!(
|
||||
"{context} 的数组嵌套层级过深(超过 {MAX_DEPTH} 层)"
|
||||
)));
|
||||
}
|
||||
match value {
|
||||
Value::Table(table) => {
|
||||
for item in as_strict_sequence(table, context)? {
|
||||
flatten(&item, context, depth + 1, out)?;
|
||||
}
|
||||
}
|
||||
scalar => out.extend(to_os_strings(scalar, ScalarMode::Tokens, context)?),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 一次 DFS 完成"环检测 + 递归展开 + 结果缓存"
|
||||
fn expand_graph(raw: &HashMap<String, Vec<OsString>>) -> Result<HashMap<String, Vec<OsString>>> {
|
||||
let mut cache: HashMap<String, Vec<OsString>> = HashMap::with_capacity(raw.len());
|
||||
let mut stack: Vec<String> = Vec::new();
|
||||
|
||||
for key in raw.keys() {
|
||||
resolve(key, raw, &mut cache, &mut stack)?;
|
||||
}
|
||||
Ok(cache)
|
||||
}
|
||||
|
||||
fn resolve(
|
||||
key: &str,
|
||||
raw: &HashMap<String, Vec<OsString>>,
|
||||
cache: &mut HashMap<String, Vec<OsString>>,
|
||||
stack: &mut Vec<String>,
|
||||
) -> Result<Vec<OsString>> {
|
||||
if let Some(done) = cache.get(key) {
|
||||
return Ok(done.clone());
|
||||
}
|
||||
if stack.iter().any(|pending| pending == key) {
|
||||
return Err(Error::AliasCycle {
|
||||
name: key.to_string(),
|
||||
});
|
||||
}
|
||||
if stack.len() >= MAX_ALIAS_DEPTH {
|
||||
return Err(Error::AliasTooDeep {
|
||||
max: MAX_ALIAS_DEPTH,
|
||||
});
|
||||
}
|
||||
|
||||
stack.push(key.to_string());
|
||||
|
||||
let mut expanded = Vec::new();
|
||||
if let Some(args) = raw.get(key) {
|
||||
for arg in args {
|
||||
let text = arg.to_string_lossy();
|
||||
let referenced = text
|
||||
.strip_prefix("mr:")
|
||||
.filter(|name| raw.contains_key(*name))
|
||||
.map(str::to_string);
|
||||
|
||||
match referenced {
|
||||
Some(name) => expanded.extend(resolve(&name, raw, cache, stack)?),
|
||||
None => expanded.push(arg.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stack.pop();
|
||||
cache.insert(key.to_string(), expanded.clone());
|
||||
Ok(expanded)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use mlua::Lua;
|
||||
|
||||
fn with_aliases(code: &str) -> Result<HashMap<String, Vec<OsString>>> {
|
||||
let lua = Lua::new();
|
||||
let value: Value = lua.load(code).eval().unwrap();
|
||||
parse_aliases(&value)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokenizes_values_and_expands_references() {
|
||||
let aliases = with_aliases(
|
||||
r#"return { base = "log --graph", all = { "mr:base", "--all" }, blank = " " }"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
aliases.get("base").unwrap(),
|
||||
&vec![OsString::from("log"), OsString::from("--graph")]
|
||||
);
|
||||
assert_eq!(
|
||||
aliases.get("all").unwrap(),
|
||||
&vec![
|
||||
OsString::from("log"),
|
||||
OsString::from("--graph"),
|
||||
OsString::from("--all"),
|
||||
]
|
||||
);
|
||||
assert!(aliases.get("blank").unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_number_and_boolean_are_supported() {
|
||||
let aliases = with_aliases(r#"return { n = 10, b = true }"#).unwrap();
|
||||
assert_eq!(aliases.get("n").unwrap(), &vec![OsString::from("10")]);
|
||||
assert_eq!(aliases.get("b").unwrap(), &vec![OsString::from("true")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_reference_is_kept_literal() {
|
||||
let aliases = with_aliases(r#"return { a = "mr:nope" }"#).unwrap();
|
||||
assert_eq!(aliases.get("a").unwrap(), &vec![OsString::from("mr:nope")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cycle_is_reported() {
|
||||
let err = with_aliases(r#"return { a = "mr:b", b = "mr:a" }"#).unwrap_err();
|
||||
assert!(matches!(err, Error::AliasCycle { .. }), "unexpected: {err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_alias_name_is_reported() {
|
||||
let err = with_aliases(r#"return { [""] = "x" }"#).unwrap_err();
|
||||
assert!(matches!(
|
||||
err,
|
||||
Error::InvalidName {
|
||||
kind: NameKind::Alias,
|
||||
..
|
||||
}
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
use super::as_table;
|
||||
use super::scalar::{ScalarMode, to_os_strings};
|
||||
use super::sequence::as_strict_sequence;
|
||||
use crate::{Error, Result};
|
||||
use mlua::Value;
|
||||
use std::ffi::OsString;
|
||||
|
||||
const CONTEXT: &str = "命令行参数 (args)";
|
||||
|
||||
/// `args = { … }`:一个数组元素就是一个参数(空串保留为空参数)。
|
||||
///
|
||||
/// 只支持一维基础标量:嵌套 table 会让"一个元素 = 一个参数"的语义失效。
|
||||
pub(crate) fn parse_args(value: &Value) -> Result<Vec<OsString>> {
|
||||
let table = as_table(value, CONTEXT)?;
|
||||
let items = as_strict_sequence(table, CONTEXT)?;
|
||||
|
||||
let mut args = Vec::with_capacity(items.len());
|
||||
for (i, item) in items.iter().enumerate() {
|
||||
if matches!(item, Value::Table(_)) {
|
||||
return Err(Error::ParseError(format!(
|
||||
"{CONTEXT} 仅支持一维数组,第 {} 个元素不能是 table",
|
||||
i + 1
|
||||
)));
|
||||
}
|
||||
let context = format!("{CONTEXT} 第 {} 个元素", i + 1);
|
||||
args.extend(to_os_strings(item, ScalarMode::Verbatim, &context)?);
|
||||
}
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use mlua::Lua;
|
||||
|
||||
fn with_args(code: &str) -> Result<Vec<OsString>> {
|
||||
let lua = Lua::new();
|
||||
let value: Value = lua.load(code).eval().unwrap();
|
||||
parse_args(&value)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_scalars_and_keeps_empty_string() {
|
||||
let args = with_args(r#"return { "--no-pager", 2, true, "" }"#).unwrap();
|
||||
assert_eq!(
|
||||
args,
|
||||
vec![
|
||||
OsString::from("--no-pager"),
|
||||
OsString::from("2"),
|
||||
OsString::from("true"),
|
||||
OsString::from(""),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_array_is_empty() {
|
||||
assert!(with_args("return {}").unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_nested_table() {
|
||||
let err = with_args(r#"return { { "a" } }"#).unwrap_err();
|
||||
assert!(matches!(err, Error::ParseError(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_sparse_array() {
|
||||
let err = with_args(r#"return { "a", nil, "b" }"#).unwrap_err();
|
||||
assert!(matches!(err, Error::ParseError(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_non_table() {
|
||||
let err = with_args(r#"return "-B""#).unwrap_err();
|
||||
assert!(matches!(err, Error::TypeMismatch { .. }));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
use super::as_table;
|
||||
use super::scalar::{ScalarMode, to_os_strings};
|
||||
use super::sequence::as_strict_sequence;
|
||||
use crate::config::naming::parse_name;
|
||||
use crate::{Error, NameKind, Result};
|
||||
use mlua::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::OsString;
|
||||
|
||||
const CONTEXT: &str = "环境变量 (env)";
|
||||
/// 数组嵌套上限,防止畸形配置打爆调用栈
|
||||
const MAX_DEPTH: usize = 16;
|
||||
|
||||
/// `env = { KEY = value }` → 环境变量表。
|
||||
///
|
||||
/// value 可以是标量,也可以是任意深度的数组;数组会递归展平,然后按系统
|
||||
/// 路径分隔符(Windows `;`)拼接。空字符串 / 空数组 → 空值(清空该变量)。
|
||||
pub(crate) fn parse_env(value: &Value) -> Result<HashMap<String, OsString>> {
|
||||
let table = as_table(value, CONTEXT)?;
|
||||
let mut env = HashMap::with_capacity(table.raw_len().min(128));
|
||||
|
||||
for pair in table.pairs::<Value, Value>() {
|
||||
let (raw_key, raw_value) = pair?;
|
||||
let name = parse_name(NameKind::EnvVar, &raw_key)?;
|
||||
let context = format!("环境变量 '{name}' 的值");
|
||||
|
||||
let mut parts = Vec::new();
|
||||
flatten(&raw_value, &context, 0, &mut parts)?;
|
||||
|
||||
let joined = std::env::join_paths(parts)
|
||||
.map_err(|e| Error::ParseError(format!("{context} 无法用系统路径分隔符拼接: {e}")))?;
|
||||
env.insert(name, joined);
|
||||
}
|
||||
|
||||
Ok(env)
|
||||
}
|
||||
|
||||
/// 递归展平标量与嵌套数组(env 的字符串不做分词,整段作为一个路径段)
|
||||
fn flatten(value: &Value, context: &str, depth: usize, out: &mut Vec<OsString>) -> Result<()> {
|
||||
if depth > MAX_DEPTH {
|
||||
return Err(Error::ParseError(format!(
|
||||
"{context} 的数组嵌套层级过深(超过 {MAX_DEPTH} 层)"
|
||||
)));
|
||||
}
|
||||
match value {
|
||||
Value::Table(table) => {
|
||||
for item in as_strict_sequence(table, context)? {
|
||||
flatten(&item, context, depth + 1, out)?;
|
||||
}
|
||||
}
|
||||
scalar => out.extend(to_os_strings(scalar, ScalarMode::Verbatim, context)?),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use mlua::Lua;
|
||||
|
||||
fn with_env(code: &str) -> Result<HashMap<String, OsString>> {
|
||||
let lua = Lua::new();
|
||||
let value: Value = lua.load(code).eval().unwrap();
|
||||
parse_env(&value)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flattens_nested_arrays_with_path_separator() {
|
||||
let env = with_env(r#"return { PATH = { "C:/a", { "C:/b", "C:/c" } } }"#).unwrap();
|
||||
assert_eq!(env.get("PATH").unwrap().to_str(), Some("C:/a;C:/b;C:/c"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalars_and_empty_values() {
|
||||
let env = with_env(r#"return { A = "", B = {}, C = 3, D = true }"#).unwrap();
|
||||
assert_eq!(env.get("A").unwrap().to_str(), Some(""));
|
||||
assert_eq!(env.get("B").unwrap().to_str(), Some(""));
|
||||
assert_eq!(env.get("C").unwrap().to_str(), Some("3"));
|
||||
assert_eq!(env.get("D").unwrap().to_str(), Some("true"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_key() {
|
||||
let err = with_env(r#"return { ["FOO=1"] = "x" }"#).unwrap_err();
|
||||
assert!(matches!(
|
||||
err,
|
||||
Error::InvalidName {
|
||||
kind: NameKind::EnvVar,
|
||||
..
|
||||
}
|
||||
));
|
||||
|
||||
let err = with_env(r#"return { [""] = "x" }"#).unwrap_err();
|
||||
assert!(matches!(
|
||||
err,
|
||||
Error::InvalidName {
|
||||
kind: NameKind::EnvVar,
|
||||
..
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_sparse_array_and_wrong_types() {
|
||||
let err = with_env(r#"return { P = { "a", nil, "b" } }"#).unwrap_err();
|
||||
assert!(matches!(err, Error::ParseError(_)));
|
||||
|
||||
let err = with_env(r#"return { F = function() end }"#).unwrap_err();
|
||||
assert!(matches!(err, Error::TypeMismatch { .. }));
|
||||
|
||||
let err = with_env(r#"return "PATH=C:/x""#).unwrap_err();
|
||||
assert!(matches!(err, Error::TypeMismatch { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_nul_in_value() {
|
||||
let err = with_env(r#"return { P = { string.char(0) } }"#).unwrap_err();
|
||||
assert!(matches!(err, Error::ContainsNul(_)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
//! Lua 值 → Rust 值的转换:`args` / `env` / `aliases`。
|
||||
//!
|
||||
//! 这一层只管"值本身":数组形状、元素类型、键合法性、分词与拼接。
|
||||
//! 产出的错误统一是 `crate::Error` 的结构化变体;字段级语义
|
||||
//! (必填、默认值)由 `model.rs` 决定。
|
||||
|
||||
mod aliases;
|
||||
mod args;
|
||||
mod env;
|
||||
mod scalar;
|
||||
mod sequence;
|
||||
|
||||
pub(crate) use aliases::parse_aliases;
|
||||
pub(crate) use args::parse_args;
|
||||
pub(crate) use env::parse_env;
|
||||
|
||||
use crate::{Error, Result};
|
||||
use mlua::{Table, Value};
|
||||
|
||||
/// 值必须是 table,否则报 `TypeMismatch`
|
||||
pub(crate) fn as_table<'a>(value: &'a Value, context: &str) -> Result<&'a Table> {
|
||||
value.as_table().ok_or_else(|| Error::TypeMismatch {
|
||||
field: context.to_string(),
|
||||
expected: "键值表 (table)",
|
||||
actual: value.type_name(),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
use crate::args::tokens::parse_tokens;
|
||||
use crate::config::convert::{ensure_no_nul, lua_string_2_os_string};
|
||||
use crate::{Error, Result};
|
||||
use mlua::Value;
|
||||
use std::ffi::OsString;
|
||||
|
||||
/// 字符串元素的处理策略
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum ScalarMode {
|
||||
/// 整体作为一个参数(args:一个数组元素 = 一个参数,空串保留为空参数)
|
||||
Verbatim,
|
||||
/// 按 shell 规则分词(aliases:"status -s" → 两个参数)
|
||||
Tokens,
|
||||
}
|
||||
|
||||
/// 标量 → 参数列表
|
||||
///
|
||||
/// - `Nil` 产生 0 个参数(在 env 里表示"清空该变量")
|
||||
/// - 字符串 / 整数 / 浮点 / 布尔都可以转成字符串
|
||||
/// - 其它类型报 `TypeMismatch`
|
||||
/// - 产出的每个 `OsString` 都会做 NUL 检查
|
||||
pub(super) fn to_os_strings(
|
||||
value: &Value,
|
||||
mode: ScalarMode,
|
||||
context: &str,
|
||||
) -> Result<Vec<OsString>> {
|
||||
let os_str: OsString = match value {
|
||||
Value::String(s) => lua_string_2_os_string(s)?,
|
||||
Value::Integer(i) => i.to_string().into(),
|
||||
Value::Number(n) => n.to_string().into(),
|
||||
Value::Boolean(b) => b.to_string().into(),
|
||||
Value::Nil => return Ok(Vec::new()),
|
||||
other => {
|
||||
return Err(Error::TypeMismatch {
|
||||
field: context.to_string(),
|
||||
expected: "string / number / boolean",
|
||||
actual: other.type_name(),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
ensure_no_nul(&context, &os_str)?;
|
||||
|
||||
Ok(match mode {
|
||||
ScalarMode::Verbatim => vec![os_str],
|
||||
ScalarMode::Tokens => match os_str.to_str() {
|
||||
Some(text) => parse_tokens(text),
|
||||
// 非 UTF-8 字节没法按 shell 规则切分,整体作为一个参数
|
||||
None => vec![os_str],
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
use crate::{Error, Result};
|
||||
use mlua::{Table, Value};
|
||||
|
||||
/// 严格连续的纯数组校验:一次遍历 `pairs`,要求键恰好是 `1..=n` 的连续整数。
|
||||
///
|
||||
/// 返回按顺序排列的元素。空洞(`{ "a", nil, "b" }`)或字典键都会报错。
|
||||
pub(super) fn as_strict_sequence(table: &Table, context: &str) -> Result<Vec<Value>> {
|
||||
let mut slots: Vec<Option<Value>> = Vec::with_capacity(table.raw_len().min(128));
|
||||
|
||||
for pair in table.pairs::<Value, Value>() {
|
||||
let (key, value) = pair?;
|
||||
let index = match key {
|
||||
Value::Integer(i) if i >= 1 => (i - 1) as usize,
|
||||
other => {
|
||||
return Err(Error::TypeMismatch {
|
||||
field: context.to_string(),
|
||||
expected: "连续整数下标 (数组)",
|
||||
actual: other.type_name(),
|
||||
});
|
||||
}
|
||||
};
|
||||
if slots.len() <= index {
|
||||
slots.resize_with(index + 1, || None);
|
||||
}
|
||||
slots[index] = Some(value);
|
||||
}
|
||||
|
||||
let mut items = Vec::with_capacity(slots.len());
|
||||
for (i, slot) in slots.into_iter().enumerate() {
|
||||
match slot {
|
||||
Some(value) => items.push(value),
|
||||
None => {
|
||||
return Err(Error::ParseError(format!(
|
||||
"{context} 第 {} 个元素为 nil 或不存在(请检查漏写引号或变量未定义)",
|
||||
i + 1
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(items)
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
use std::fmt;
|
||||
use std::path::PathBuf;
|
||||
use thiserror::Error;
|
||||
|
||||
/// 全局统一的 `Result` 别名,默认错误类型为 [`Error`]。
|
||||
pub type Result<T, E = Error> = std::result::Result<T, E>;
|
||||
|
||||
/// 名称所属的类别,用于区分命令名 / 环境变量名 / 别名的校验与报错
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum NameKind {
|
||||
Command,
|
||||
EnvVar,
|
||||
Alias,
|
||||
}
|
||||
|
||||
impl fmt::Display for NameKind {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::Command => "命令名",
|
||||
Self::EnvVar => "环境变量名",
|
||||
Self::Alias => "别名",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum Error {
|
||||
#[error("初始化 Lua 沙箱失败: {0}")]
|
||||
LuaInit(#[source] mlua::Error),
|
||||
|
||||
// #[error("构建 LuaRuntime 异常")]
|
||||
// BuildError,
|
||||
#[error("{kind}非法: {reason}")]
|
||||
InvalidName { kind: NameKind, reason: String },
|
||||
|
||||
#[error("别名 '{name}' 存在循环引用")]
|
||||
AliasCycle { name: String },
|
||||
|
||||
#[error("别名展开层级过深(超过 {max} 层)")]
|
||||
AliasTooDeep { max: usize },
|
||||
|
||||
#[error("{0}")]
|
||||
ContainsNul(String),
|
||||
|
||||
/// 值的结构不合法(数组空洞、字典键、嵌套过深等)
|
||||
#[error("{0}")]
|
||||
ParseError(String),
|
||||
|
||||
#[error("目录布局解析失败: {0}")]
|
||||
Layout(String),
|
||||
|
||||
#[error("注册全局变量 '{name}' 失败: {source}")]
|
||||
RegisterGlobal {
|
||||
name: &'static str,
|
||||
#[source]
|
||||
source: mlua::Error,
|
||||
},
|
||||
|
||||
#[error("{from} -> {to} 转换失败: {message}")]
|
||||
EncodingError {
|
||||
from: &'static str,
|
||||
to: String,
|
||||
message: String,
|
||||
},
|
||||
// 类型不符:Lua 值的类型与期望不符,用户应修改配置写法
|
||||
#[error("字段 {field} 类型不符:期望 {expected},实际是 {actual}")]
|
||||
TypeMismatch {
|
||||
field: String,
|
||||
expected: &'static str,
|
||||
actual: &'static str,
|
||||
},
|
||||
|
||||
#[error("缺少必填字段 {field}")]
|
||||
MissingField { field: String },
|
||||
|
||||
///读取脚本文件失败
|
||||
#[error("读取脚本文件失败 ({path}): {source}")]
|
||||
ScriptRead {
|
||||
path: PathBuf,
|
||||
#[source]
|
||||
source: std::io::Error,
|
||||
},
|
||||
|
||||
#[error("脚本 {path} 不是有效的 UTF-8 文件(请将 Lua 配置文件保存为 UTF-8 编码)")]
|
||||
InvalidUtf8 { path: PathBuf },
|
||||
|
||||
// 收敛所有来自 mlua 的错误,附带来源上下文
|
||||
#[error("Lua 执行异常 ({chunk}): {source}")]
|
||||
LuaRuntime {
|
||||
chunk: String,
|
||||
#[source]
|
||||
source: mlua::Error,
|
||||
},
|
||||
|
||||
#[error("模块 '{module_name}' 必须返回一个函数作为入口,实际返回了 {actual_type}")]
|
||||
InvalidModuleEntry {
|
||||
module_name: String,
|
||||
actual_type: &'static str,
|
||||
},
|
||||
|
||||
// #[error("插件/上下文挂载失败 '{name}': {source}")]
|
||||
// Plugin {
|
||||
// name: String,
|
||||
// #[source]
|
||||
// source: mlua::Error,
|
||||
// },
|
||||
#[error("Lua 适配层错误: {0}")]
|
||||
LuaAdapter(#[from] mlua::Error),
|
||||
|
||||
// #[error("设置 {0} 环境变量失败")]
|
||||
// SetMirrorDir(String),
|
||||
/// 用户自定义扩展错误,用于包装第三方插件产生的错误。
|
||||
#[error("用户自定义扩展错误: {0}")]
|
||||
Other(#[source] Box<dyn std::error::Error + Send + Sync>),
|
||||
}
|
||||
/// 出站转换:core 自己的错误 -> Lua 世界能看懂的错误。
|
||||
///
|
||||
/// 触发时机:函数返回 `mlua::Result<T>`,但 `?` 的表达式返回 `crate::Result<T>`。
|
||||
/// 有了这个 impl,Lua 边界的代码只写 `?`,不需要在每个调用点手工构造 mlua 错误。
|
||||
impl From<Error> for mlua::Error {
|
||||
fn from(err: Error) -> Self {
|
||||
match err {
|
||||
// 本来就是 mlua 的错误:原样透传,保留错误种类与位置信息
|
||||
Error::LuaInit(e) | Error::LuaAdapter(e) => e,
|
||||
// source 自带 chunk 名(set_name 已写入),所以这里直接透传内层错误
|
||||
Error::LuaRuntime { source, .. } => source,
|
||||
Error::EncodingError { from, to, message } => mlua::Error::FromLuaConversionError {
|
||||
from,
|
||||
to,
|
||||
message: Some(message),
|
||||
},
|
||||
Error::TypeMismatch {
|
||||
field,
|
||||
expected, actual,
|
||||
} => mlua::Error::FromLuaConversionError {
|
||||
from: actual,
|
||||
to: expected.into(),
|
||||
message: Some(format!("字段 '{field}' 类型不符")),
|
||||
},
|
||||
Error::MissingField { field } => {
|
||||
mlua::Error::RuntimeError(format!("缺少必填字段 {field}"))
|
||||
}
|
||||
// 其余是 core 的领域错误:翻译成 Lua 侧可见的运行时错误,
|
||||
// to_string() 由 thiserror 的 #[error("...")] 生成,也就是用户看到的中文
|
||||
other => mlua::Error::RuntimeError(other.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 将 MirrorTarget 构建为 Command 时可能触发的阻断性错误
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum TargetExecutionError {
|
||||
/// 多版本工具未激活版本 (current == None)
|
||||
UnselectedVersion { tool: String },
|
||||
/// 目标可执行文件物理不存在
|
||||
NotFound { tool: String, path: PathBuf },
|
||||
}
|
||||
|
||||
impl fmt::Display for TargetExecutionError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::UnselectedVersion { tool } => {
|
||||
write!(
|
||||
f,
|
||||
"工具 '{}' 当前未指定有效版本。\n提示: 请先运行 'mr use {}' 选择版本。",
|
||||
tool, tool
|
||||
)
|
||||
}
|
||||
Self::NotFound { tool, path } => {
|
||||
write!(f, "工具 '{}' 的目标程序不存在: {}", tool, path.display())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for TargetExecutionError {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// 领域错误出站后,原始的中文提示必须还在
|
||||
#[test]
|
||||
fn config_error_converts_to_lua_error_with_payload() {
|
||||
let lua_err: mlua::Error = Error::InvalidName {
|
||||
kind: NameKind::Command,
|
||||
reason: "不能为空".into(),
|
||||
}
|
||||
.into();
|
||||
assert!(
|
||||
lua_err.to_string().contains("不能为空"),
|
||||
"unexpected message: {lua_err}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Lua 原生错误出站时要原样透传,不能被包成 RuntimeError 丢掉种类
|
||||
#[test]
|
||||
fn native_lua_error_passes_through() {
|
||||
let lua_err: mlua::Error =
|
||||
Error::LuaAdapter(mlua::Error::RuntimeError("boom".into())).into();
|
||||
assert!(
|
||||
lua_err.to_string().contains("boom"),
|
||||
"unexpected message: {lua_err}"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn conversion_error_keeps_kind() {
|
||||
let lua_err: mlua::Error = Error::EncodingError {
|
||||
from: "LuaString",
|
||||
to: "OsString".into(),
|
||||
message: "坏字节".into(),
|
||||
}
|
||||
.into();
|
||||
assert!(matches!(
|
||||
lua_err,
|
||||
mlua::Error::FromLuaConversionError { .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_field_message_has_no_duplication() {
|
||||
let lua_err: mlua::Error = Error::MissingField {
|
||||
field: "home".into(),
|
||||
}
|
||||
.into();
|
||||
// mlua 会给 RuntimeError 加 "runtime error: " 前缀,所以只断言内容正确且不重复
|
||||
let message = lua_err.to_string();
|
||||
assert_eq!(message.matches("缺少必填字段").count(), 1, "{message}");
|
||||
assert!(message.contains("home"), "{message}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
use crate::{Error, Result};
|
||||
use std::env;
|
||||
use std::path::{Path, PathBuf};
|
||||
use tracing::debug;
|
||||
pub struct Layout {
|
||||
pub base_dir: PathBuf,
|
||||
pub target_name: String,
|
||||
}
|
||||
|
||||
impl Layout {
|
||||
/// 自动解析目录布局:
|
||||
/// 1. 优先使用环境变量 MIRROR_HOME
|
||||
/// 2. 兜底回退到当前垫片可执行文件所在目录推断 (exe -> bin -> root)
|
||||
pub fn from(current_exe: &Path) -> Result<Self> {
|
||||
let target_name = current_exe
|
||||
.file_stem()
|
||||
.and_then(|s| s.to_str())
|
||||
.ok_or_else(|| {
|
||||
Error::Layout(format!(
|
||||
"无法从路径 [{}] 提取有效的程序名称",
|
||||
current_exe.display()
|
||||
))
|
||||
})?
|
||||
.to_lowercase();
|
||||
|
||||
// 策略 1: 环境变量优先
|
||||
if let Ok(home_val) = env::var("MIRROR_HOME") {
|
||||
let trimmed = home_val.trim();
|
||||
if !trimmed.is_empty() {
|
||||
debug!(home = %trimmed, "检测到 MIRROR_HOME,采用环境变量配置");
|
||||
|
||||
return Self::from_base_dir(PathBuf::from(trimmed), target_name);
|
||||
}
|
||||
}
|
||||
|
||||
// 策略 2: 相对路径自动推断兜底
|
||||
debug!("未配置 MIRROR_HOME,尝试从当前可执行文件路径推断根目录");
|
||||
Self::from_executable(current_exe, target_name)
|
||||
}
|
||||
|
||||
/// 基于确定的根目录构建完整布局
|
||||
fn from_base_dir(base_dir: PathBuf, target_name: String) -> Result<Self> {
|
||||
if !base_dir.is_dir() {
|
||||
debug!("指定的根目录不存在或不是有效目录: [{}]", base_dir.display());
|
||||
return Err(Error::Layout(format!(
|
||||
"指定的根目录不存在或不是有效目录: [{}]",
|
||||
base_dir.display()
|
||||
)));
|
||||
}
|
||||
|
||||
let mirror_file = base_dir.join("mirror.lua");
|
||||
if !mirror_file.is_file() {
|
||||
debug!(
|
||||
"根目录 [{}] 下未找到核心配置文件 [mirror.lua]",
|
||||
base_dir.display()
|
||||
);
|
||||
return Err(Error::Layout(format!(
|
||||
"根目录 [{}] 下未找到核心配置文件 [mirror.lua]",
|
||||
base_dir.display()
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
base_dir,
|
||||
target_name,
|
||||
})
|
||||
}
|
||||
|
||||
/// 从当前可执行文件解析 shim 安装目录布局
|
||||
fn from_executable(exe_path: &Path, target_name: String) -> Result<Self> {
|
||||
// let exe_path = exe_path.as_ref();
|
||||
let start_dir = exe_path.parent().ok_or_else(|| {
|
||||
Error::Layout(format!("无法获取程序 [{}] 的所在目录", exe_path.display()))
|
||||
})?;
|
||||
|
||||
debug!("可执行程序所在目录: {}", start_dir.display());
|
||||
|
||||
// let base_dir = start_dir
|
||||
// .parent()
|
||||
// .with_context(|| format!("无法获取 bin 目录 [{}] 的父级 root 目录", bin_dir.display()))?
|
||||
// .to_path_buf();
|
||||
|
||||
// 2. 向上回溯寻找 mirror.lua 锚点
|
||||
let base_dir = find_base_dir_by_anchor(start_dir).ok_or_else(|| {
|
||||
Error::Layout(format!(
|
||||
"路径推导失败:从 [{}] 向上逐级回溯均未找到 [mirror.lua]。\n\
|
||||
提示: 请确保程序位于包含 mirror.lua 的项目内,或配置 MIRROR_HOME 环境变量。",
|
||||
start_dir.display()
|
||||
))
|
||||
})?;
|
||||
debug!("成功探测到 base_dir 目录 {}", base_dir.display());
|
||||
|
||||
// 此时 base_dir 下必然有 mirror.lua,直接构建
|
||||
Ok(Self {
|
||||
base_dir,
|
||||
target_name,
|
||||
})
|
||||
}
|
||||
}
|
||||
/// 向上查找包含 mirror.lua 的根目录
|
||||
fn find_base_dir_by_anchor(start_dir: &Path) -> Option<PathBuf> {
|
||||
let mut current = Some(start_dir);
|
||||
|
||||
// 最大向上回溯层级(例如 3~4 层,防止死循环跑到磁盘根目录甚至网络挂载点)
|
||||
let mut depth = 0;
|
||||
const MAX_DEPTH: usize = 4;
|
||||
|
||||
while let Some(dir) = current {
|
||||
if depth > MAX_DEPTH {
|
||||
debug!("超出最大向上回溯层级:4");
|
||||
break;
|
||||
}
|
||||
|
||||
// 只要当前目录下有 mirror.lua,这里就是真正的 base_dir!
|
||||
if dir.join("mirror.lua").is_file() {
|
||||
return Some(dir.to_path_buf());
|
||||
}
|
||||
|
||||
current = dir.parent();
|
||||
depth += 1;
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub(crate) mod layout;
|
||||
pub(crate) mod path;
|
||||
pub use layout::Layout;
|
||||
@@ -0,0 +1,10 @@
|
||||
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('\\', "/")
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
mod args;
|
||||
mod config;
|
||||
mod error;
|
||||
mod fs;
|
||||
mod logging;
|
||||
mod lua;
|
||||
|
||||
pub use config::{
|
||||
load_mirror_spec, parse_command_name, MirrorRegistry, MirrorSpec, MirrorTarget, Target,
|
||||
TargetConfig, TargetSpec,
|
||||
};
|
||||
pub use fs::Layout;
|
||||
// pub use mirror_shim::mirror::Mirror;
|
||||
pub use logging::{LogConfig, LogLevel, init_logging_from};
|
||||
pub use lua::{register_basics, LuaRuntime};
|
||||
|
||||
// 把 Result 和 Error 提升到根命名空间,给外部带来极致便利
|
||||
pub use error::{Error, NameKind, Result, TargetExecutionError};
|
||||
@@ -0,0 +1,187 @@
|
||||
use crate::fs::Layout;
|
||||
use std::convert::Infallible;
|
||||
use std::fs;
|
||||
use std::path::{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"
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 日志配置模型(对应 mirror.ini 的纯强类型表示)
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
pub struct LogConfig {
|
||||
pub level: LogLevel,
|
||||
pub log_dir: Option<PathBuf>,
|
||||
}
|
||||
impl LogConfig {
|
||||
/// 零依赖解析 ini / key-value 文本内容
|
||||
/// 计算日志目录的实际物理路径(相对路径基于 base_dir 拼接)
|
||||
pub fn resolve_log_dir(&self, base_dir: &Path) -> PathBuf {
|
||||
match &self.log_dir {
|
||||
Some(p) if p.is_absolute() => p.clone(),
|
||||
Some(p) => base_dir.join(p),
|
||||
None => base_dir.join("logs"),
|
||||
}
|
||||
}
|
||||
}
|
||||
// 协议 1: 反序列化 (INI 文本 -> LogConfig)
|
||||
impl FromStr for LogConfig {
|
||||
type Err = Infallible;
|
||||
|
||||
fn from_str(content: &str) -> Result<Self, Self::Err> {
|
||||
let mut config = Self::default();
|
||||
|
||||
for line in content.lines() {
|
||||
let line = line.trim();
|
||||
// 跳过空行、注释 (#, ;) 与 section 标头 ([...])
|
||||
if line.is_empty() || line.starts_with(['#', ';', '[']) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some((key, val)) = line.split_once('=') {
|
||||
let key = key.trim();
|
||||
let val = val.trim().trim_matches(['"', '\'']);
|
||||
|
||||
match key {
|
||||
"level" => {
|
||||
if let Ok(lvl) = LogLevel::from_str(val) {
|
||||
config.level = lvl;
|
||||
}
|
||||
}
|
||||
"log_dir" => {
|
||||
if !val.is_empty() {
|
||||
config.log_dir = Some(PathBuf::from(val));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(config)
|
||||
}
|
||||
}
|
||||
|
||||
// 协议 2: 序列化 (LogConfig -> INI 文本)
|
||||
impl std::fmt::Display for LogConfig {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
let dir_str = self
|
||||
.log_dir
|
||||
.as_deref()
|
||||
.and_then(|p| p.to_str())
|
||||
.unwrap_or("logs");
|
||||
|
||||
writeln!(f, "level = \"{}\"", self.level.as_str())?;
|
||||
writeln!(f, "log_dir = \"{}\"", dir_str)
|
||||
}
|
||||
}
|
||||
|
||||
/// 基于 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");
|
||||
|
||||
// 1. 读取并反序列化配置文件(缺失或异常时安全降级为 Default)
|
||||
let config: LogConfig = fs::read_to_string(&config_path)
|
||||
.ok()
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or_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);
|
||||
|
||||
// 3. 动态配置落盘文件层(仅在 verbose 级别启用)
|
||||
let (file_layer, guard) = if effective_level.is_verbose() {
|
||||
let (non_blocking, guard) = create_file_appender(&config.resolve_log_dir(&layout.base_dir));
|
||||
let layer = fmt::layer()
|
||||
.with_writer(non_blocking)
|
||||
.with_ansi(false)
|
||||
.with_target(false);
|
||||
(Some(layer), Some(guard))
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
|
||||
// 4. 统一组装并初始化 Subscriber(Option<Layer> 天然实现了 Layer trait)
|
||||
let _ = tracing_subscriber::registry()
|
||||
.with(filter)
|
||||
.with(stderr_layer)
|
||||
.with(file_layer)
|
||||
.try_init();
|
||||
|
||||
guard
|
||||
}
|
||||
|
||||
fn create_file_appender(output_dir: &Path) -> (NonBlocking, WorkerGuard) {
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
pub mod runtime;
|
||||
pub mod plugins;
|
||||
|
||||
pub use plugins::register_basics;
|
||||
pub use runtime::LuaRuntime;
|
||||
@@ -0,0 +1,167 @@
|
||||
use crate::error::{Error, Result};
|
||||
use crate::fs::{Layout, path::normalize_path_for_lua};
|
||||
use mlua::{Lua, Table, Value};
|
||||
use std::path::PathBuf;
|
||||
use std::{env, fs};
|
||||
use tracing::{debug, warn};
|
||||
|
||||
const MIRROR_DIR: &str = "__MIRROR_DIR__";
|
||||
|
||||
// 采用形式 A:直接传引用的普通函数
|
||||
pub fn register_basics(lua: &Lua, layout: &Layout) -> Result<()> {
|
||||
let base_dir = normalize_path_for_lua(&layout.base_dir);
|
||||
register_mirror_dir(lua, &base_dir)?;
|
||||
register_get_env(lua)?;
|
||||
setup_require(lua, &base_dir)?;
|
||||
register_mr_version(lua)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 注入全局锚点变量
|
||||
pub fn register_mirror_dir(lua: &Lua, base_dir: &str) -> Result<()> {
|
||||
debug!("设置 {MIRROR_DIR} 环境变量");
|
||||
lua.globals()
|
||||
.set(MIRROR_DIR, base_dir)
|
||||
.map_err(|e| Error::RegisterGlobal {
|
||||
name: MIRROR_DIR,
|
||||
source: e,
|
||||
})?;
|
||||
// .context(format!("设置 {MIRROR_DIR} 环境变量失败"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
///注入 get_env 供配置读取环境变量
|
||||
pub fn register_get_env(lua: &Lua) -> Result<()> {
|
||||
let globals = lua.globals();
|
||||
let get_env = lua.create_function(|lua, key: String| -> mlua::Result<Table> {
|
||||
// 缺失变量视为空字符串,拆分后得到空表(不贡献任何路径段)
|
||||
let value = env::var_os(key).unwrap_or_default();
|
||||
// 空输入返回空表;否则按平台分隔符拆分(split_paths 会剥离引号包裹)
|
||||
if value.is_empty() {
|
||||
return lua.create_table();
|
||||
}
|
||||
let table = lua.create_table()?;
|
||||
for (i, p) in env::split_paths(&value).enumerate() {
|
||||
// 3. 跨平台提取原始字节并转为 LuaString,保证 100% 无损
|
||||
#[cfg(unix)]
|
||||
let lua_str = {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
lua.create_string(p.as_os_str().as_bytes())?
|
||||
};
|
||||
|
||||
#[cfg(windows)]
|
||||
let lua_str = {
|
||||
// Windows 路径是 UTF-16,转成字符串或保持其字节表达
|
||||
let s = p.to_string_lossy();
|
||||
lua.create_string(s.as_bytes())?
|
||||
};
|
||||
|
||||
table.set(i + 1, lua_str)?;
|
||||
}
|
||||
|
||||
Ok(table)
|
||||
})?;
|
||||
// .context("注册 get_env 函数失败")?;
|
||||
|
||||
globals.set("get_env", get_env)?;
|
||||
// .context("挂载 get_env 全局函数失败")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 配置 package.path 并包装 require,拦截加载失败以提高容错性
|
||||
pub fn setup_require(lua: &Lua, base_dir: &str) -> Result<()> {
|
||||
let globals = lua.globals();
|
||||
|
||||
// 1. 安全加固并拓展 package 搜索路径
|
||||
let package = globals.get::<Table>("package")?;
|
||||
|
||||
let _ = package.set("cpath", "");
|
||||
let _ = package.set("loadlib", Value::Nil);
|
||||
|
||||
let commands_dir = format!("{}/commands", base_dir);
|
||||
let vendor_dir = format!("{}/vendor", base_dir);
|
||||
|
||||
let path = package.get::<String>("path")?;
|
||||
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.get("require")?;
|
||||
// .context("获取内置 require 函数失败")?;
|
||||
|
||||
let wrapped_require =
|
||||
lua.create_function(move |_lua, module: String| -> mlua::Result<Value> {
|
||||
match original_require.call::<Value>(module.as_str()) {
|
||||
Ok(value) => Ok(value),
|
||||
Err(e) => {
|
||||
warn!(
|
||||
module = %module,
|
||||
error = %e,
|
||||
"配置模块加载失败,已跳过该条目(可在独立配置文件中定义)"
|
||||
);
|
||||
Ok(Value::Nil)
|
||||
}
|
||||
}
|
||||
})?;
|
||||
// .context("创建包装版 require 函数失败")?;
|
||||
|
||||
// 3. 覆盖全局 require
|
||||
globals.set("require", wrapped_require)?;
|
||||
// .context("重载 require 函数失败")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 向 Lua 全局环境注册 `mr` 模块及其原生辅助函数
|
||||
pub fn register_mr_version(lua: &Lua) -> Result<()> {
|
||||
// 1. 获取或创建全局 `mr` Table
|
||||
let globals = lua.globals();
|
||||
let mr_table = match globals.get::<Value>("mr")? {
|
||||
Value::Table(t) => t,
|
||||
_ => {
|
||||
let t = lua.create_table()?;
|
||||
globals.set("mr", t.clone())?;
|
||||
t
|
||||
}
|
||||
};
|
||||
|
||||
// 2. 实现 mr.version(home, version_file) -> Option<String>
|
||||
// 规则:
|
||||
// - version_file 为可选参数,缺省默认使用 ".version"
|
||||
// - 文件不存在、空内容或读取失败时,安全返回 nil,绝不让 Lua 脚本崩盘
|
||||
// - 自动 trim 掉末尾的 \r\n,仅提取纯净版本号
|
||||
let version_fn = lua.create_function(
|
||||
|_lua, (home_str, version_file_opt): (String, Option<String>)| {
|
||||
let version_filename = version_file_opt
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.unwrap_or_else(|| ".version".to_string());
|
||||
|
||||
let mut target_path = PathBuf::from(home_str);
|
||||
target_path.push(version_filename);
|
||||
|
||||
// 读取文件并安全修剪
|
||||
match fs::read_to_string(&target_path) {
|
||||
Ok(content) => {
|
||||
let trimmed = content.trim();
|
||||
if trimmed.is_empty() {
|
||||
Ok(None::<String>) // 文件内容为空字符串时,视为未设置版本
|
||||
} else {
|
||||
Ok(Some(trimmed.to_string()))
|
||||
}
|
||||
}
|
||||
// 常见错误(NotFound 等)直接返回 nil,不抛出 Lua error
|
||||
Err(_) => Ok(None::<String>),
|
||||
}
|
||||
},
|
||||
)?;
|
||||
|
||||
// 3. 挂载到 mr 表
|
||||
mr_table.set("version", version_fn)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
use crate::error::{Error, Result};
|
||||
use mlua::{FromLua, Lua, StdLib, Value};
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use tracing::debug;
|
||||
|
||||
pub struct LuaRuntimeBuilder {
|
||||
lua: Result<Lua>,
|
||||
}
|
||||
impl LuaRuntimeBuilder {
|
||||
pub fn with<F>(mut self, extension: F) -> Self
|
||||
where
|
||||
F: FnOnce(&Lua) -> Result<()>,
|
||||
{
|
||||
// 如果前面已有错误,直接短路跳过后续操作
|
||||
if let Ok(ref lua) = self.lua {
|
||||
if let Err(e) = extension(lua) {
|
||||
self.lua = Err(e);
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// 收敛构建终点:一次性输出统一的 Result
|
||||
pub fn build(self) -> Result<LuaRuntime> {
|
||||
let lua = self.lua?;
|
||||
Ok(LuaRuntime { lua })
|
||||
}
|
||||
}
|
||||
|
||||
/// 将 Layout 相关的公共上下文组合为一个插件项
|
||||
|
||||
pub struct LuaRuntime {
|
||||
lua: Lua,
|
||||
}
|
||||
|
||||
impl LuaRuntime {
|
||||
/// 初始化限定权限的 Lua 沙箱环境
|
||||
pub fn builder() -> LuaRuntimeBuilder {
|
||||
// 只加载安全的标准库,剥离 os / io 等风险模块
|
||||
let lua = Lua::new_with(
|
||||
StdLib::TABLE | StdLib::STRING | StdLib::MATH | StdLib::PACKAGE,
|
||||
mlua::LuaOptions::default(),
|
||||
)
|
||||
.map_err(Error::LuaInit);
|
||||
|
||||
LuaRuntimeBuilder { 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).map_err(|e| Error::ScriptRead {
|
||||
path: path.to_path_buf(),
|
||||
source: e,
|
||||
})?;
|
||||
|
||||
let code = String::from_utf8(bytes).map_err(|_| Error::InvalidUtf8 {
|
||||
path: path.to_path_buf(),
|
||||
})?;
|
||||
debug!("code {:?}", code);
|
||||
// 使用 @<path> 格式标记 Chunk 名称,确保 Lua 报错时能精确回溯到对应的源文件名与行号。
|
||||
let chunk_name = format!("@{}", path.display());
|
||||
|
||||
self.lua
|
||||
.load(&code)
|
||||
.set_name(&chunk_name)
|
||||
.eval::<T>()
|
||||
.map_err(|e| Error::LuaRuntime {
|
||||
chunk: chunk_name,
|
||||
source: e,
|
||||
})
|
||||
}
|
||||
|
||||
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: Value = require.call(module_name)?;
|
||||
|
||||
let func = match handler_val {
|
||||
Value::Function(f) => f,
|
||||
other => {
|
||||
return Err(Error::InvalidModuleEntry {
|
||||
module_name: module_name.to_string(),
|
||||
actual_type: other.type_name(),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
let lua_args = self.lua.create_sequence_from(raw_args)?;
|
||||
func.call::<()>(lua_args)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::Layout;
|
||||
|
||||
/// 测试用运行时:和线上一样注册宿主函数(get_env / require 包装等)
|
||||
fn test_runtime() -> LuaRuntime {
|
||||
let layout = Layout {
|
||||
base_dir: std::env::temp_dir().join("mirror-core-test-layout"),
|
||||
target_name: "mirror-shim".to_string(),
|
||||
};
|
||||
LuaRuntime::builder()
|
||||
.with(|lua| crate::lua::register_basics(lua, &layout))
|
||||
.build()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_module_require_returns_nil() {
|
||||
let runtime = test_runtime();
|
||||
let value: Value = runtime
|
||||
.lua
|
||||
.load(r#"return require("rshim_test_no_such_module")"#)
|
||||
.eval()
|
||||
.unwrap();
|
||||
assert!(matches!(value, Value::Nil));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builtin_module_require_still_works() {
|
||||
let runtime = test_runtime();
|
||||
let value: Value = runtime
|
||||
.lua
|
||||
.load(r#"return pcall(require, "string")"#)
|
||||
.eval()
|
||||
.unwrap();
|
||||
assert!(matches!(value, Value::Boolean(true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_env_returns_split_table() {
|
||||
let runtime = test_runtime();
|
||||
let value: Value = runtime
|
||||
.lua
|
||||
.load(r#"return get_env("PATH")"#)
|
||||
.eval()
|
||||
.unwrap();
|
||||
let table = match value {
|
||||
Value::Table(t) => t,
|
||||
other => panic!("expected table, got {}", other.type_name()),
|
||||
};
|
||||
assert!(
|
||||
table.raw_len() >= 1,
|
||||
"PATH should have at least one segment"
|
||||
);
|
||||
|
||||
// split_paths 会剥离引号包裹,拆分段不应再含双引号
|
||||
for i in 1..=table.raw_len() {
|
||||
let seg: String = table.raw_get(i).unwrap();
|
||||
assert!(
|
||||
!seg.contains('"'),
|
||||
"segment should not contain quote: {seg:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_env_missing_returns_empty_table() {
|
||||
let runtime = test_runtime();
|
||||
let value: Value = runtime
|
||||
.lua
|
||||
.load(r#"return get_env("RSHIM_TEST_NO_SUCH_VAR_12345")"#)
|
||||
.eval()
|
||||
.unwrap();
|
||||
match value {
|
||||
Value::Table(t) => assert_eq!(t.raw_len(), 0),
|
||||
other => panic!("expected table, got {}", other.type_name()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 @@
|
||||
-- mirror.lua (总控制台)
|
||||
-- __MIRROR_DIR__ 已经在 Rust 中注入完毕,并且是正斜杠格式 (例如 C:/Tools)
|
||||
local base_dir = __MIRROR_DIR__
|
||||
base_dir = __MIRROR_DIR__
|
||||
|
||||
-- 1. 自定义局部变量,方便复用与后续维护
|
||||
local python_home = base_dir .. "/tools/python39"
|
||||
@@ -0,0 +1,39 @@
|
||||
---
|
||||
--- Generated by EmmyLua(https://github.com/EmmyLua)
|
||||
--- Created by Administrator.
|
||||
--- DateTime: 2026/9/10 20:16
|
||||
---
|
||||
|
||||
-- tools/node.lua
|
||||
local home = base_dir .. "/tools/node"
|
||||
local version_file = ".version"
|
||||
|
||||
-- 安全读取当前激活版本:未激活或文件不存在时返回 nil,不抛出异常
|
||||
local ver = mr.version(home, version_file)
|
||||
|
||||
return {
|
||||
-- 1. target 配置为 Table,自动对应 Rust 侧的 TargetConfig::Versioned
|
||||
target = {
|
||||
home = home,
|
||||
version_file = version_file,
|
||||
-- 若版本未激活,current 为 nil;若激活,则拼出绝对路径
|
||||
current = ver and (home .. "/" .. ver .. "/node.exe") or nil
|
||||
},
|
||||
|
||||
-- 2. 默认追加参数
|
||||
args = {},
|
||||
|
||||
-- 3. 别名映射(mr: 前缀可直接展开)
|
||||
aliases = {
|
||||
["v"] = { "--version" },
|
||||
},
|
||||
|
||||
-- 4. 环境变量联动:将对应版本的 bin 目录前置到 PATH
|
||||
env = {
|
||||
NODE_HOME = ver and (home .. "/" .. ver) or "",
|
||||
PATH = {
|
||||
ver and (home .. "/" .. ver) or "",
|
||||
get_env("PATH")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use mirror_core::MirrorTarget;
|
||||
use std::ffi::OsString;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use tracing::debug;
|
||||
pub fn to_command<P>(spec: &MirrorTarget, target: P, final_args: &[OsString]) -> Command
|
||||
where
|
||||
P: AsRef<Path>,
|
||||
{
|
||||
let mut cmd = Command::new(target.as_ref());
|
||||
|
||||
// 2. 传入预打平的别名字典,查表并展开所有以 `mr:` 为前缀的别名
|
||||
// let final_args = self.resolve_args(combined_args);
|
||||
debug!("拼接后的命令行参数{:?}", final_args);
|
||||
// 3. 将解析展开后的无环参数一次性注入 Command
|
||||
cmd.args(final_args);
|
||||
|
||||
// 4. 注入配置好的环境变量
|
||||
for (key, val) in &spec.env {
|
||||
// 直接应用环境变量(Lua 端已经处理好字符串拼接或列表合并)
|
||||
cmd.env(key, val);
|
||||
}
|
||||
|
||||
cmd
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
use mirror_core::MirrorRegistry;
|
||||
use crate::sys::{
|
||||
ERROR_ELEVATION_REQUIRED, EXIT_FAILED_LOAD_SHIM, EXIT_FAILED_SPAWN_PROG, EXIT_FAILED_WAIT_PROG,
|
||||
EXIT_PROG_TERMINATED, execute_elevated,
|
||||
};
|
||||
use mirror_core::{Layout, LuaRuntime, TargetConfig, TargetExecutionError, register_basics};
|
||||
use std::env;
|
||||
use std::ffi::OsString;
|
||||
use std::process::exit;
|
||||
use tracing::{error, warn};
|
||||
use crate::command;
|
||||
|
||||
pub fn run(layout: &Layout) -> i32 {
|
||||
let global_config = &layout.base_dir.join("mirror.lua");
|
||||
|
||||
if !global_config.is_file() {
|
||||
error!("主配置文件不存在: {}", global_config.display());
|
||||
return EXIT_FAILED_LOAD_SHIM;
|
||||
}
|
||||
|
||||
let runtime = match LuaRuntime::builder()
|
||||
.with(|lua| register_basics(lua, &layout))
|
||||
.build()
|
||||
{
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
error!("初始化 Lua 失败: {:#}", e);
|
||||
return EXIT_FAILED_LOAD_SHIM;
|
||||
}
|
||||
};
|
||||
|
||||
let registry: MirrorRegistry = match runtime.eval_script(&global_config) {
|
||||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
error!("加载命令配置 [{}] 失败: {:#}", global_config.display(), e);
|
||||
return EXIT_FAILED_LOAD_SHIM;
|
||||
}
|
||||
};
|
||||
|
||||
let target_name = layout.target_name.as_str();
|
||||
|
||||
let mr = match registry.targets.get(target_name) {
|
||||
Some(m) => m,
|
||||
None => {
|
||||
warn!("未在 mirror.lua 中找到目标配置 [{}]", target_name);
|
||||
return EXIT_FAILED_LOAD_SHIM;
|
||||
}
|
||||
};
|
||||
|
||||
// 1. 提取生效路径,缺失版本时直接抛出 UnselectedVersion
|
||||
let target_path = match mr.target.executable_path() {
|
||||
Some(path) => path,
|
||||
None => {
|
||||
warn!(
|
||||
"[mirror] 工具 '{}' 当前未指定生效版本。\n提示: 请先运行 'mr use {}' 选择版本。",
|
||||
target_name, target_name
|
||||
);
|
||||
return EXIT_FAILED_LOAD_SHIM;
|
||||
}
|
||||
};
|
||||
|
||||
// 3. 解析调用参数与代理 Mirror 配置
|
||||
let calling_args: Vec<_> = env::args_os().skip(1).collect();
|
||||
|
||||
let combined_args = mr.args.iter().chain(calling_args.iter());
|
||||
let final_args = mr.resolve_args(combined_args);
|
||||
// 构建 Command:复用 ShimConfig::to_command(含 args/env 注入),避免重复逻辑
|
||||
let mut cmd = command::to_command(mr,target_path, &final_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(target_path, &final_args, Some(&mr.env)))
|
||||
}
|
||||
Err(e) => {
|
||||
error!(
|
||||
"启动目标程序 [{}] 时发生错误: {}",
|
||||
target_path.to_string_lossy(),
|
||||
e
|
||||
);
|
||||
return EXIT_FAILED_SPAWN_PROG;
|
||||
}
|
||||
};
|
||||
// 5. 等待子进程退出
|
||||
match child.wait() {
|
||||
Ok(status) => status.code().unwrap_or(EXIT_PROG_TERMINATED),
|
||||
Err(e) => {
|
||||
error!(
|
||||
"等待目标程序 [{}] 执行完毕时发生错误: {}",
|
||||
target_path.to_string_lossy(),
|
||||
e
|
||||
);
|
||||
EXIT_FAILED_WAIT_PROG
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
use crate::sys::*;
|
||||
use anyhow::Context;
|
||||
use mirror_core::{init_logging_from, Layout};
|
||||
use std::{env, process::exit};
|
||||
use tracing::debug;
|
||||
|
||||
mod executor;
|
||||
pub mod sys;
|
||||
pub mod validators;
|
||||
pub mod command;
|
||||
|
||||
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();
|
||||
|
||||
let code = executor::run(&layout);
|
||||
exit(code);
|
||||
}
|
||||
@@ -2,7 +2,7 @@ use std::os::windows::ffi::OsStrExt;
|
||||
use std::{env, mem::size_of, path::Path, ptr::null_mut};
|
||||
|
||||
use std::ffi::{OsStr, OsString};
|
||||
|
||||
use tracing::error;
|
||||
use windows_sys::Win32::UI::Shell::{SHELLEXECUTEINFOW, ShellExecuteExW};
|
||||
|
||||
use windows_sys::Win32::Foundation::CloseHandle;
|
||||
@@ -40,7 +40,7 @@ unsafe extern "system" fn console_ctrl_handler(evt: u32) -> BOOL {
|
||||
CTRL_LOGOFF_EVENT => TRUE, //eprintln!("ctrl_logoff handled!"),
|
||||
CTRL_SHUTDOWN_EVENT => TRUE, //eprintln!("ctrl_shutdown handled!"),
|
||||
other => {
|
||||
eprintln!("未知的系统事件编号: {},未处理!", other);
|
||||
error!("未知的系统事件编号: {},未处理!", other);
|
||||
FALSE
|
||||
}
|
||||
}
|
||||
@@ -49,7 +49,7 @@ unsafe extern "system" fn console_ctrl_handler(evt: u32) -> BOOL {
|
||||
pub fn set_console_ctrl_handler() {
|
||||
let res: BOOL = unsafe { SetConsoleCtrlHandler(Some(console_ctrl_handler), TRUE) };
|
||||
if res == FALSE {
|
||||
eprintln!("警告: 注册控制台中断事件处理器失败。");
|
||||
error!("警告: 注册控制台中断事件处理器失败。");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
use anyhow::Context;
|
||||
use mlua::{Table, Value};
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use mirror_core::MirrorTarget;
|
||||
use mlua::{FromLua, Lua};
|
||||
|
||||
fn parse(src: &str) -> mlua::Result<MirrorTarget> {
|
||||
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 = MirrorTarget::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.executable_path().unwrap().to_path_buf(),
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
# mirror-log.ini
|
||||
level = debug
|
||||
log_dir = "logs"
|
||||
|
||||
# 或者带节结构:
|
||||
# [logger]
|
||||
# level = info
|
||||
# log_dir = /var/log/mirror
|
||||
@@ -1,25 +0,0 @@
|
||||
// 构造一个带上下文的 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
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
use anyhow::{Context, Result, bail};
|
||||
use std::env;
|
||||
use std::path::{Path, PathBuf};
|
||||
use tracing::debug;
|
||||
pub struct Layout {
|
||||
pub base_dir: PathBuf,
|
||||
pub bin_dir: PathBuf,
|
||||
pub tools_dir: PathBuf,
|
||||
pub lua_file: PathBuf,
|
||||
}
|
||||
|
||||
impl Layout {
|
||||
/// 自动解析目录布局:
|
||||
/// 1. 优先使用环境变量 MIRROR_HOME
|
||||
/// 2. 兜底回退到当前垫片可执行文件所在目录推断 (exe -> bin -> root)
|
||||
pub fn discover(current_exe: &Path) -> Result<Self> {
|
||||
// 策略 1: 环境变量优先
|
||||
if let Ok(home_val) = env::var("MIRROR_HOME") {
|
||||
let trimmed = home_val.trim();
|
||||
if !trimmed.is_empty() {
|
||||
debug!(home = %trimmed, "检测到 MIRROR_HOME,采用环境变量配置");
|
||||
return Self::from_base_dir(PathBuf::from(trimmed));
|
||||
}
|
||||
}
|
||||
|
||||
// 策略 2: 相对路径自动推断兜底
|
||||
debug!("未配置 MIRROR_HOME,尝试从当前可执行文件路径推断根目录");
|
||||
Self::from_executable(current_exe)
|
||||
}
|
||||
|
||||
/// 基于确定的根目录构建完整布局
|
||||
fn from_base_dir(base_dir: PathBuf) -> Result<Self> {
|
||||
if !base_dir.is_dir() {
|
||||
bail!("指定的根目录不存在或不是有效目录: [{}]", base_dir.display());
|
||||
}
|
||||
|
||||
let bin_dir = base_dir.join("bin");
|
||||
let tools_dir = base_dir.join("tools");
|
||||
let lua_file = base_dir.join("../mirror.lua");
|
||||
|
||||
Ok(Self {
|
||||
base_dir,
|
||||
bin_dir,
|
||||
tools_dir,
|
||||
lua_file,
|
||||
})
|
||||
}
|
||||
|
||||
/// 从当前可执行文件解析 shim 安装目录布局
|
||||
fn from_executable(exe_path: &Path) -> Result<Self> {
|
||||
// let exe_path = exe_path.as_ref();
|
||||
let bin_dir = exe_path
|
||||
.parent()
|
||||
.with_context(|| format!("无法获取程序 [{}] 的父级 bin 目录", exe_path.display()))?
|
||||
.to_path_buf();
|
||||
|
||||
debug!("bin_dir目录 {}", bin_dir.display());
|
||||
|
||||
let base_dir = bin_dir
|
||||
.parent()
|
||||
.with_context(|| format!("无法获取 bin 目录 [{}] 的父级 root 目录", bin_dir.display()))?
|
||||
.to_path_buf();
|
||||
debug!("base_dir 目录 {}", base_dir.display());
|
||||
|
||||
Self::from_base_dir(base_dir)
|
||||
}
|
||||
}
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
extern crate core;
|
||||
|
||||
pub mod error;
|
||||
mod layout;
|
||||
mod loader;
|
||||
mod logger;
|
||||
mod mirror;
|
||||
mod runtime;
|
||||
mod spec;
|
||||
pub mod sys;
|
||||
mod utils;
|
||||
mod validators;
|
||||
|
||||
pub use layout::Layout;
|
||||
pub use mirror::Mirror;
|
||||
pub use runtime::LuaRuntime;
|
||||
pub use spec::MirrorSpec;
|
||||
// pub use sys::{
|
||||
// ERROR_ELEVATION_REQUIRED, EXIT_FAILED_LOAD_SHIM, EXIT_FAILED_SPAWN_PROG, EXIT_FAILED_WAIT_PROG,
|
||||
// EXIT_PROG_TERMINATED, execute_elevated, set_console_ctrl_handler,
|
||||
// };
|
||||
|
||||
pub use utils::{lua_string_2_os_string, normalize_path_for_lua, parse_tokens};
|
||||
@@ -1,99 +0,0 @@
|
||||
use crate::spec::MirrorSpec;
|
||||
use crate::{Layout, LuaRuntime};
|
||||
use anyhow::{Context, Result, bail};
|
||||
use mlua::Table;
|
||||
use std::path::PathBuf;
|
||||
use tracing::{debug, trace, warn};
|
||||
|
||||
pub enum Source {
|
||||
Lua(LuaRuntime),
|
||||
Json,
|
||||
}
|
||||
|
||||
/// MirrorSpec 加载器,统一对外暴露多源解析接口
|
||||
pub struct SpecLoader;
|
||||
|
||||
impl SpecLoader {
|
||||
pub fn resolve_spec(source: &Source, layout: &Layout, target_name: &str) -> Result<MirrorSpec> {
|
||||
match source {
|
||||
Source::Lua(r) => Self::resolve_lua_spec(&r, layout, target_name),
|
||||
Source::Json => Self::load_from_json(layout),
|
||||
}
|
||||
}
|
||||
/// 从 Lua 脚本字符串加载 ShimSpec
|
||||
fn resolve_lua_spec(
|
||||
runtime: &LuaRuntime,
|
||||
layout: &Layout,
|
||||
target_name: &str,
|
||||
) -> Result<MirrorSpec> {
|
||||
// 策略 1: 尝试加载全局配置文件 mirror.lua
|
||||
let global_config = layout.base_dir.join("mirror.lua");
|
||||
|
||||
if global_config.is_file() {
|
||||
trace!(path = %global_config.display(), "发现全局配置文件,尝试解析");
|
||||
let root_table: Table = runtime.eval_script(&global_config)?;
|
||||
|
||||
// 检查 mirror.lua 中是否存在以 target_name 命名的 Table 节点
|
||||
if root_table
|
||||
.contains_key(target_name)
|
||||
.context("检查全局配置失败")?
|
||||
{
|
||||
let target_val: MirrorSpec = 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, "全局配置文件中未包含该目标,继续探查独立配置");
|
||||
}
|
||||
|
||||
let tools_dir: Option<PathBuf> = runtime.tools_dir()?;
|
||||
// 策略 2: 降级寻找独立文件 ({exe}.lua),优先顺序:tools/ > root/
|
||||
let target_filename = format!("{}.lua", target_name);
|
||||
|
||||
let effective_tools_dir = match tools_dir {
|
||||
Some(t) => {
|
||||
if t.is_absolute() {
|
||||
t.join(&target_filename)
|
||||
} else {
|
||||
layout.base_dir.join(t).join(&target_filename)
|
||||
}
|
||||
}
|
||||
None => layout.tools_dir.join(&target_filename),
|
||||
};
|
||||
|
||||
let candidates = [
|
||||
// layout.tools_dir.join(&target_filename),
|
||||
effective_tools_dir,
|
||||
layout.base_dir.join(&target_filename),
|
||||
];
|
||||
|
||||
for config_path in &candidates {
|
||||
if config_path.is_file() {
|
||||
debug!(path = %config_path.display(), "找到独立配置文件,开始加载");
|
||||
// 直接泛型反序列化为 MirrorSpec
|
||||
return runtime.eval_script::<MirrorSpec>(config_path);
|
||||
}
|
||||
trace!(path = %config_path.display(), "独立配置文件不存在,跳过");
|
||||
}
|
||||
|
||||
// 策略 3: 所有查找失败,抛出错误
|
||||
warn!(target = %target_name, "未找到任何匹配的配置文件");
|
||||
bail!(
|
||||
"未找到关于 '{}' 的配置。请检查 mirror.lua 或特定的 {}.lua 文件",
|
||||
target_name,
|
||||
target_name
|
||||
);
|
||||
}
|
||||
|
||||
/// 从 Lua 脚本文件加载 ShimSpec
|
||||
fn load_from_json(layout: &Layout) -> Result<MirrorSpec> {
|
||||
todo!("实现json来源")
|
||||
}
|
||||
}
|
||||
@@ -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(())
|
||||
// }
|
||||
-65
@@ -1,65 +0,0 @@
|
||||
use mirror::Mirror;
|
||||
use mirror::sys::*;
|
||||
use std::ffi::OsString;
|
||||
use std::{env, process::exit};
|
||||
use tracing_subscriber::{EnvFilter, fmt};
|
||||
|
||||
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();
|
||||
// 2. 注册 Windows 控制台信号
|
||||
set_console_ctrl_handler();
|
||||
// 3. 解析调用参数与代理 Mirror 配置
|
||||
let calling_args: Vec<_> = env::args_os().skip(1).collect();
|
||||
let mr = match Mirror::new() {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
eprintln!("加载代理(mirror)配置时发生错误: {}", e);
|
||||
exit(EXIT_FAILED_LOAD_SHIM);
|
||||
}
|
||||
};
|
||||
let combined_args = mr.spec.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.spec.target,
|
||||
&elevated_args,
|
||||
Some(&mr.spec.env),
|
||||
))
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"启动目标程序 [{}] 时发生错误: {}",
|
||||
mr.spec.target.to_string_lossy(),
|
||||
e
|
||||
);
|
||||
exit(EXIT_FAILED_SPAWN_PROG);
|
||||
}
|
||||
};
|
||||
// 5. 等待子进程退出
|
||||
let status = match child.wait() {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"等待目标程序 [{}] 执行完毕时发生错误: {}",
|
||||
mr.spec.target.to_string_lossy(),
|
||||
e
|
||||
);
|
||||
exit(EXIT_FAILED_WAIT_PROG);
|
||||
}
|
||||
};
|
||||
exit(status.code().unwrap_or(EXIT_PROG_TERMINATED))
|
||||
}
|
||||
-105
@@ -1,105 +0,0 @@
|
||||
use crate::loader::Source;
|
||||
use crate::loader::SpecLoader;
|
||||
use crate::{Layout, LuaRuntime, MirrorSpec};
|
||||
use anyhow::{Context, Result};
|
||||
use std::collections::HashMap;
|
||||
use std::env;
|
||||
use std::ffi::OsString;
|
||||
use std::process::Command;
|
||||
use tracing::debug;
|
||||
pub struct Mirror {
|
||||
pub spec: MirrorSpec,
|
||||
pub layout: Layout,
|
||||
pub target_name: String,
|
||||
}
|
||||
|
||||
impl Mirror {
|
||||
pub fn new() -> Result<Self> {
|
||||
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(),
|
||||
"开始加载 Mirror 配置"
|
||||
);
|
||||
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(),
|
||||
"Mirror 目录布局解析完成"
|
||||
);
|
||||
|
||||
let runtime = LuaRuntime::new(&layout)?;
|
||||
let spec = SpecLoader::resolve_spec(&Source::Lua(runtime), &layout, &target_name)?;
|
||||
|
||||
Ok(Self {
|
||||
spec,
|
||||
layout,
|
||||
target_name,
|
||||
})
|
||||
}
|
||||
|
||||
/// 1. 核心参数路由解析(Delegation 到 Spec 的路由逻辑)
|
||||
fn resolve_args<I, S>(&self, args: I, aliases: &HashMap<String, Vec<OsString>>) -> 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) = 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.spec.target);
|
||||
|
||||
// 2. 传入预打平的别名字典,查表并展开所有以 `mr:` 为前缀的别名
|
||||
let final_args = self.resolve_args(combined_args, &self.spec.aliases);
|
||||
println!("拼接后的命令行参数{:?}",final_args);
|
||||
// 3. 将解析展开后的无环参数一次性注入 Command
|
||||
cmd.args(&final_args);
|
||||
|
||||
// 4. 注入配置好的环境变量
|
||||
for (key, val) in &self.spec.env {
|
||||
// 直接应用环境变量(Lua 端已经处理好字符串拼接或列表合并)
|
||||
cmd.env(key, val);
|
||||
}
|
||||
|
||||
cmd
|
||||
}
|
||||
}
|
||||
-327
@@ -1,327 +0,0 @@
|
||||
use crate::Layout;
|
||||
use crate::error::syntax_error;
|
||||
use crate::utils::normalize_path_for_lua;
|
||||
use anyhow::{Context, Result};
|
||||
use mlua::{FromLua, Lua, StdLib, Table, Value};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::{env, fs};
|
||||
|
||||
const MIRROR_DIR: &str = "__MIRROR_DIR__";
|
||||
const MIRROR_TOOLS_DIR: &str = "__MIRROR_TOOLS_DIR__";
|
||||
// const MIRROR_LOG_LEVEL: &str = "__MIRROR_LOG_LEVEL__";
|
||||
const MIRROR_LOG_DIR: &str = "__MIRROR_LOG_DIR__";
|
||||
|
||||
pub struct LuaRuntime {
|
||||
lua: Lua,
|
||||
}
|
||||
|
||||
impl LuaRuntime {
|
||||
/// 初始化限定权限的 Lua 沙箱环境
|
||||
pub fn new(layout: &Layout) -> Result<Self> {
|
||||
// 只加载安全的标准库,剥离 os / io 等风险模块
|
||||
let lua = Lua::new_with(
|
||||
StdLib::TABLE | StdLib::STRING | StdLib::MATH | StdLib::PACKAGE,
|
||||
mlua::LuaOptions::default(),
|
||||
)
|
||||
.context("初始化 Lua 失败")?;
|
||||
|
||||
// 统一使用 POSIX 风格路径规范化路径字符串
|
||||
let base_dir = normalize_path_for_lua(&layout.base_dir);
|
||||
let tools_dir = normalize_path_for_lua(&layout.tools_dir);
|
||||
|
||||
// 1. 注入锚点变量 __MIRROR_DIR__(shim 安装根目录)
|
||||
Self::register_mirror_dir(&lua, &base_dir)?;
|
||||
|
||||
// 2. 安全暴露 get_env 供配置读取环境变量
|
||||
// 返回按平台路径分隔符拆分后的段数组(自动剥离引号包裹),
|
||||
// 便于 PATH 等列表变量直接嵌入数组:PATH = { prefix, get_env("PATH") }
|
||||
Self::register_get_env(&lua)?;
|
||||
// 3. 初始化并配置安全/容错的 require 机制
|
||||
Self::setup_require(&lua, &base_dir, &tools_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()
|
||||
)
|
||||
})?;
|
||||
tracing::trace!("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!("执行 Lua 配置文件失败: {}", path.display()))
|
||||
}
|
||||
|
||||
pub fn tools_dir(&self) -> Result<Option<PathBuf>> {
|
||||
self.lua
|
||||
.globals()
|
||||
.get(MIRROR_TOOLS_DIR)
|
||||
.context(format!("设置 {MIRROR_TOOLS_DIR} 失败"))
|
||||
}
|
||||
}
|
||||
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
|
||||
.create_function(|lua, key: String| -> mlua::Result<Table> {
|
||||
// 缺失变量视为空字符串,拆分后得到空表(不贡献任何路径段)
|
||||
let value = env::var_os(key).unwrap_or_default();
|
||||
// 空输入返回空表;否则按平台分隔符拆分(split_paths 会剥离引号包裹)
|
||||
if value.is_empty() {
|
||||
return lua.create_table();
|
||||
}
|
||||
let table = lua.create_table()?;
|
||||
for (i, p) in env::split_paths(&value).enumerate() {
|
||||
// 3. 跨平台提取原始字节并转为 LuaString,保证 100% 无损
|
||||
#[cfg(unix)]
|
||||
let lua_str = {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
lua.create_string(p.as_os_str().as_bytes())?
|
||||
};
|
||||
|
||||
#[cfg(windows)]
|
||||
let lua_str = {
|
||||
// Windows 路径是 UTF-16,转成字符串或保持其字节表达
|
||||
let s = p.to_string_lossy();
|
||||
lua.create_string(s.as_bytes())?
|
||||
};
|
||||
|
||||
table.set(i + 1, lua_str)?;
|
||||
}
|
||||
|
||||
Ok(table)
|
||||
})
|
||||
.context("注册 get_env 函数失败")?;
|
||||
|
||||
globals
|
||||
.set("get_env", get_env)
|
||||
.context("挂载 get_env 全局函数失败")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 通用的路径注册闭包生成器
|
||||
fn register_dir_reset_fn(
|
||||
lua: &Lua,
|
||||
global_fn_name: &str,
|
||||
target_global_key: &'static str,
|
||||
) -> Result<()> {
|
||||
let get_env = lua.create_function(move |lua, rel_path: String| {
|
||||
let clean_path = rel_path.trim().trim_start_matches('/');
|
||||
|
||||
lua.globals().set(target_global_key, clean_path)?;
|
||||
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
// 4. 将函数绑定至 Lua 全局作用域,供 Lua 调用
|
||||
lua.globals().set(global_fn_name, get_env)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn register_reset_tools_dir(lua: &Lua) -> Result<()> {
|
||||
Self::register_dir_reset_fn(lua, "reset_tools_dir", MIRROR_TOOLS_DIR)
|
||||
}
|
||||
fn register_reset_log_dir(lua: &Lua) -> Result<()> {
|
||||
Self::register_dir_reset_fn(lua, "reset_log_dir", MIRROR_LOG_DIR)
|
||||
}
|
||||
/// 配置 package.path 并包装 require,拦截加载失败以提高容错性
|
||||
fn setup_require(lua: &Lua, base_dir: &str, tools_dir: &str) -> Result<()> {
|
||||
let globals = lua.globals();
|
||||
|
||||
// 1. 安全加固并拓展 package 搜索路径
|
||||
if let Ok(package) = globals.get::<Table>("package") {
|
||||
let _ = package.set("cpath", "");
|
||||
let _ = package.set("loadlib", Value::Nil);
|
||||
|
||||
if let Ok(path) = package.get::<String>("path") {
|
||||
let new_path = format!(
|
||||
"{};{}/?.lua;{}/?/init.lua;{}/?.lua;{}/?/init.lua",
|
||||
path, base_dir, base_dir, tools_dir, tools_dir
|
||||
);
|
||||
let _ = package.set("path", new_path);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 获取原生 require 并通过闭包直接持有(无需向全局表注入备份变量)
|
||||
let original_require: mlua::Function = globals
|
||||
.get("require")
|
||||
.context("获取内置 require 函数失败")?;
|
||||
|
||||
let wrapped_require = lua
|
||||
.create_function(move |_lua, module: String| -> mlua::Result<Value> {
|
||||
match original_require.call::<Value>(module.as_str()) {
|
||||
Ok(value) => Ok(value),
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
module = %module,
|
||||
error = %e,
|
||||
"配置模块加载失败,已跳过该条目(可在独立配置文件中定义)"
|
||||
);
|
||||
Ok(Value::Nil)
|
||||
}
|
||||
}
|
||||
})
|
||||
.context("创建包装版 require 函数失败")?;
|
||||
|
||||
// 3. 覆盖全局 require
|
||||
globals
|
||||
.set("require", wrapped_require)
|
||||
.context("重载 require 函数失败")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{Layout, MirrorSpec};
|
||||
|
||||
fn test_layout() -> Layout {
|
||||
let root = std::env::temp_dir().join("rshim-test-layout");
|
||||
Layout {
|
||||
base_dir: root.clone(),
|
||||
bin_dir: root.join("bin"),
|
||||
tools_dir: root.join("tools"),
|
||||
lua_file: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_module_require_returns_nil() {
|
||||
let runtime = LuaRuntime::new(&test_layout()).unwrap();
|
||||
let value: Value = runtime
|
||||
.lua
|
||||
.load(r#"return require("rshim_test_no_such_module")"#)
|
||||
.eval()
|
||||
.unwrap();
|
||||
assert!(matches!(value, Value::Nil));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builtin_module_require_still_works() {
|
||||
let runtime = LuaRuntime::new(&test_layout()).unwrap();
|
||||
let value: Value = runtime
|
||||
.lua
|
||||
.load(r#"return pcall(require, "string")"#)
|
||||
.eval()
|
||||
.unwrap();
|
||||
assert!(matches!(value, Value::Boolean(true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_env_returns_split_table() {
|
||||
let runtime = LuaRuntime::new(&test_layout()).unwrap();
|
||||
let value: Value = runtime
|
||||
.lua
|
||||
.load(r#"return get_env("PATH")"#)
|
||||
.eval()
|
||||
.unwrap();
|
||||
let table = match value {
|
||||
Value::Table(t) => t,
|
||||
other => panic!("expected table, got {}", other.type_name()),
|
||||
};
|
||||
assert!(
|
||||
table.raw_len() >= 1,
|
||||
"PATH should have at least one segment"
|
||||
);
|
||||
|
||||
// split_paths 会剥离引号包裹,拆分段不应再含双引号
|
||||
for i in 1..=table.raw_len() {
|
||||
let seg: String = table.raw_get(i).unwrap();
|
||||
assert!(
|
||||
!seg.contains('"'),
|
||||
"segment should not contain quote: {seg:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_env_missing_returns_empty_table() {
|
||||
let runtime = LuaRuntime::new(&test_layout()).unwrap();
|
||||
let value: Value = runtime
|
||||
.lua
|
||||
.load(r#"return get_env("RSHIM_TEST_NO_SUCH_VAR_12345")"#)
|
||||
.eval()
|
||||
.unwrap();
|
||||
match value {
|
||||
Value::Table(t) => assert_eq!(t.raw_len(), 0),
|
||||
other => panic!("expected table, got {}", other.type_name()),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_with_get_env_joins_without_quote_error() {
|
||||
// 复现用户场景:PATH = { base_dir .. "/tools/numa", get_env("PATH") }
|
||||
// 宿主 PATH 即使含双引号,也应拆分后正常拼接,而不是报错
|
||||
let runtime = LuaRuntime::new(&test_layout()).unwrap();
|
||||
let cfg: MirrorSpec = runtime
|
||||
.lua
|
||||
.load(
|
||||
r#"
|
||||
return {
|
||||
target = __SHIM_DIR__ .. "/tools/numa/numa.exe",
|
||||
args = { "--help" },
|
||||
env = {
|
||||
PATH = { __SHIM_DIR__ .. "/tools/numa", get_env("PATH") }
|
||||
}
|
||||
}
|
||||
"#,
|
||||
)
|
||||
.eval()
|
||||
.unwrap();
|
||||
|
||||
let path = cfg.env.get("PATH").unwrap().to_str().unwrap();
|
||||
let prefix = std::env::temp_dir()
|
||||
.join("rshim-test-layout")
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/")
|
||||
+ "/tools/numa;";
|
||||
assert!(path.starts_with(&prefix), "unexpected PATH: {path}");
|
||||
|
||||
// 宿主 PATH 的段应被附加在配置前缀之后
|
||||
let host = std::env::var("PATH").unwrap_or_default();
|
||||
if !host.is_empty() {
|
||||
let host_first = std::env::split_paths(&host)
|
||||
.next()
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
assert!(
|
||||
path.contains(&host_first),
|
||||
"missing host PATH segment: {host_first}"
|
||||
);
|
||||
}
|
||||
|
||||
// 宿主 PATH 里引号包裹的畸形段(如 "D:\\...\\bin;")应被原样保留,
|
||||
// 而不是让整个配置加载失败
|
||||
if host.contains('"') {
|
||||
assert!(
|
||||
path.contains('"'),
|
||||
"quoted host segments should be preserved"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
-109
@@ -1,109 +0,0 @@
|
||||
use crate::error::validation_error;
|
||||
use crate::validators::{JsonValidator, LuaValidator};
|
||||
use anyhow::{Result, anyhow};
|
||||
use mlua::{FromLua, Lua, Value};
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
use tinyjson::JsonValue;
|
||||
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct MirrorSpec {
|
||||
pub target: PathBuf,
|
||||
pub args: Vec<OsString>,
|
||||
pub aliases: HashMap<String, Vec<OsString>>,
|
||||
pub env: HashMap<String, OsString>,
|
||||
}
|
||||
|
||||
/// 实现 FromLua Trait,由 mlua 自动处理 Table 转换
|
||||
impl FromLua for MirrorSpec {
|
||||
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(MirrorSpec {
|
||||
target,
|
||||
args,
|
||||
aliases,
|
||||
env,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&str> for MirrorSpec {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(json_str: &str) -> Result<Self> {
|
||||
// 1. 解析 JSON 字符串为 JsonValue 树
|
||||
let root = JsonValue::from_str(json_str).map_err(|e| anyhow!("JSON 语法错误: {}", e))?;
|
||||
|
||||
// 根节点必须是一个 JSON Object
|
||||
let map: &HashMap<String, JsonValue> = root
|
||||
.get()
|
||||
.ok_or_else(|| anyhow!("JSON 根节点必须是 Object 对象"))?;
|
||||
|
||||
// 1. target (必填)
|
||||
let target_val = map
|
||||
.get("target")
|
||||
.ok_or_else(|| anyhow!("缺少必填字段: target"))?;
|
||||
let target = JsonValidator::parse_target(target_val)?;
|
||||
|
||||
// 2. args (选填)
|
||||
let args = match map.get("args") {
|
||||
Some(args_val) => JsonValidator::parse_args(args_val)?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
|
||||
// 3. env (选填)
|
||||
let env = match map.get("env") {
|
||||
Some(env_val) => JsonValidator::parse_env(env_val)?,
|
||||
None => HashMap::new(),
|
||||
};
|
||||
let aliases = match map.get("aliases") {
|
||||
Some(env_val) => JsonValidator::parse_aliases(env_val)?,
|
||||
None => HashMap::new(),
|
||||
};
|
||||
Ok(MirrorSpec {
|
||||
target,
|
||||
args,
|
||||
aliases,
|
||||
env,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,810 +0,0 @@
|
||||
use crate::error::validation_error;
|
||||
use crate::{lua_string_2_os_string, parse_tokens};
|
||||
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;
|
||||
|
||||
/// 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>> {
|
||||
{
|
||||
println!("跟踪args1{}", value.type_name());
|
||||
#[cfg(not(feature = "args"))]
|
||||
Ok(Vec::new())
|
||||
}
|
||||
#[cfg(feature = "args")]
|
||||
{
|
||||
println!("跟踪args1{}", value.type_name());
|
||||
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?;
|
||||
println!("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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 专用于 JSON (tinyjson) 的类型校验与字段提取器
|
||||
//当前JsonValidator还为完全可用,后期会对其lua配置特别需要处理动态函数生成的值如:get_env("PATH")
|
||||
// 数据结构:{
|
||||
// "target": "C:/tools/git.exe",
|
||||
// "args": [
|
||||
// "--no-pager",
|
||||
// 2,
|
||||
// true
|
||||
// ],
|
||||
// "env": {
|
||||
// "PATH": ["C:/tools/git/bin", "C:/Windows"],
|
||||
// "HOME": "C:/tools/home",
|
||||
// "CONST": 3,
|
||||
// "BOOL": true
|
||||
// }
|
||||
// }
|
||||
pub struct JsonValidator;
|
||||
|
||||
impl JsonValidator {
|
||||
/// 校验并解析 target (必填,非空字符串)
|
||||
pub fn parse_target(val: &JsonValue) -> Result<PathBuf> {
|
||||
let s: &String = val
|
||||
.get()
|
||||
.ok_or_else(|| anyhow!("字段 'target' 必须是字符串"))?;
|
||||
|
||||
if s.trim().is_empty() {
|
||||
return Err(anyhow!("字段 'target' 不能为空字符串"));
|
||||
}
|
||||
Ok(PathBuf::from(s))
|
||||
}
|
||||
|
||||
/// 校验并解析 args (选填,必须为字符串数组)
|
||||
pub fn parse_args(val: &JsonValue) -> Result<Vec<OsString>> {
|
||||
let args_vec: &Vec<JsonValue> =
|
||||
val.get().ok_or_else(|| anyhow!("字段 'args' 必须是数组"))?;
|
||||
|
||||
args_vec
|
||||
.iter()
|
||||
.map(|item| {
|
||||
let s: &String = item
|
||||
.get()
|
||||
.ok_or_else(|| anyhow!("'args' 数组内的元素必须全为字符串"))?;
|
||||
Ok(OsString::from(s))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 校验并解析 env (选填,必须为 KV 对象)
|
||||
pub fn parse_env(val: &JsonValue) -> Result<HashMap<String, OsString>> {
|
||||
let env_map: &HashMap<String, JsonValue> = val
|
||||
.get()
|
||||
.ok_or_else(|| anyhow!("字段 'env' 必须是 Object 键值对"))?;
|
||||
let mut result = HashMap::new();
|
||||
for (k, v) in env_map {
|
||||
let mut segments = Vec::new();
|
||||
Self::collect_env_segments(v, &mut segments)?;
|
||||
|
||||
if !segments.is_empty() {
|
||||
// 根据操作系统自动拼接环境变量分隔符 (Windows 为 ';', Unix 为 ':')
|
||||
#[cfg(windows)]
|
||||
let sep = std::ffi::OsStr::new(";");
|
||||
#[cfg(not(windows))]
|
||||
let sep = std::ffi::OsStr::new(":");
|
||||
|
||||
let joined = segments.join(sep);
|
||||
result.insert(k.clone(), joined);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
pub fn parse_aliases(val: &JsonValue) -> Result<HashMap<String, Vec<OsString>>> {
|
||||
todo!()
|
||||
}
|
||||
// =========================================================================
|
||||
// 私有辅助方法
|
||||
// =========================================================================
|
||||
|
||||
/// 单个标量节点转换为 OsString (支持 String, Number, Boolean)
|
||||
fn value_to_os_string(val: &JsonValue, ctx: &str) -> Result<OsString> {
|
||||
if let Some(s) = val.get::<String>() {
|
||||
Ok(OsString::from(s))
|
||||
} else if let Some(n) = val.get::<f64>() {
|
||||
Ok(OsString::from(n.to_string()))
|
||||
} else if let Some(b) = val.get::<bool>() {
|
||||
Ok(OsString::from(b.to_string()))
|
||||
} else {
|
||||
Err(anyhow!("{} 内只支持字符串、数字或布尔类型", ctx))
|
||||
}
|
||||
}
|
||||
|
||||
/// 递归打平 env 节点中的数组/标量值
|
||||
fn collect_env_segments(val: &JsonValue, segments: &mut Vec<OsString>) -> Result<()> {
|
||||
if let Some(arr) = val.get::<Vec<JsonValue>>() {
|
||||
for item in arr {
|
||||
Self::collect_env_segments(item, segments)?;
|
||||
}
|
||||
} else {
|
||||
let parsed_segment = Self::value_to_os_string(val, "'env' 节点的 Value")?;
|
||||
segments.push(parsed_segment);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::MirrorSpec;
|
||||
use mlua::{FromLua, Lua};
|
||||
|
||||
fn parse(src: &str) -> mlua::Result<MirrorSpec> {
|
||||
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 = MirrorSpec::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());
|
||||
}
|
||||
}
|
||||
Vendored
+1527
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user