дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-28 13:32:29 +02:00
Порівняти коміти
43
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
1bd6036b67 | ||
|
|
112a4da502 | ||
|
|
dcd81d601b | ||
|
|
762ebecd86 | ||
|
|
fd4efff6e3 | ||
|
|
8968974f42 | ||
|
|
5f083ae47c | ||
|
|
83b14b4329 | ||
|
|
74eefd6116 | ||
|
|
a96c70f2a7 | ||
|
|
304503b9f1 | ||
|
|
06cf8fb16a | ||
|
|
521e00d075 | ||
|
|
b4cad6ec1b | ||
|
|
62e26fa7e3 | ||
|
|
1119467ab4 | ||
|
|
e1ce850a29 | ||
|
|
3e39368d43 | ||
|
|
b2a5ea1594 | ||
|
|
902d8ca257 | ||
|
|
92b5b5306f | ||
|
|
707cee9b0b | ||
|
|
d64be035c6 | ||
|
|
cb60c742fc | ||
|
|
b245335cc6 | ||
|
|
e13ed093ec | ||
|
|
aa0f8105af | ||
|
|
0adc816a56 | ||
|
|
ea29339b6b | ||
|
|
84854bed0e | ||
|
|
81b6cb7af6 | ||
|
|
ffe96c2ca2 | ||
|
|
33bd5372b6 | ||
|
|
44aeb95993 | ||
|
|
fa6b4be6f5 | ||
|
|
144cd90175 | ||
|
|
da3b621345 | ||
|
|
b301e2bbe1 | ||
|
|
feac919a1b | ||
|
|
0155d74084 | ||
|
|
130f75e7e8 | ||
|
|
2abd65aedd | ||
|
|
1b3e4fac6a |
No files matched your search
Створено
+200
-148
@@ -474,7 +474,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "457d7ed3f888dfd2c7af56d4975cade43c622f74bdcddfed6d4352f57acc6310"
|
||||
dependencies = [
|
||||
"futures-util",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"portable-atomic",
|
||||
"tokio",
|
||||
]
|
||||
@@ -1655,9 +1655,9 @@ dependencies = [
|
||||
"cfg-if",
|
||||
"crossbeam-utils",
|
||||
"hashbrown 0.14.5",
|
||||
"lock_api",
|
||||
"lock_api 0.4.14",
|
||||
"once_cell",
|
||||
"parking_lot_core",
|
||||
"parking_lot_core 0.9.12",
|
||||
"serde",
|
||||
]
|
||||
|
||||
@@ -2154,7 +2154,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2210,6 +2210,16 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "faster-hex"
|
||||
version = "2.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e4ede54fe330383a5de28c0a1f06668ff9dbf06c8094e1c5150c39488a5e911d"
|
||||
dependencies = [
|
||||
"defmt 0.3.101",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.5.0"
|
||||
@@ -2453,8 +2463,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"lock_api",
|
||||
"parking_lot",
|
||||
"lock_api 0.4.14",
|
||||
"parking_lot 0.12.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2734,9 +2744,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix"
|
||||
version = "0.89.0"
|
||||
version = "0.90.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2156d2e07fc3afa7632a82bf3cb0db91f995645a2852f642105c9ac9b52e1cb2"
|
||||
checksum = "b92b20c1560511a9014b16e29db2f3c6f0580d4fe289b70f41131277b065a3b0"
|
||||
dependencies = [
|
||||
"gix-actor",
|
||||
"gix-attributes",
|
||||
@@ -2788,9 +2798,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-actor"
|
||||
version = "0.44.0"
|
||||
version = "0.44.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2127da41042965ed205568a52443465806944f71c8acd73f48ec94b8cd8e798e"
|
||||
checksum = "78243d3371019288a40a75ba1a58de2815c32591fc87b9f7cb01918bce364ca8"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-date",
|
||||
@@ -2799,9 +2809,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-attributes"
|
||||
version = "0.37.0"
|
||||
version = "0.37.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0feca0b8919aba9f123b75de54062dd61eb37d2a2130f34be520da6ed8b8ef72"
|
||||
checksum = "6b9947d93a94d41ddde66ac655674269121cbebaf6cdee30d8d0e7dbe85edb4c"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -2816,27 +2826,27 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-bitmap"
|
||||
version = "0.6.0"
|
||||
version = "0.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "408cb9e482e0dcc5fc481850556348dda6981ec054a4a8e81a8e1bbf84f85eef"
|
||||
checksum = "9543567ee22142c81fdf75b2811160bec749a5b9f48665e4763f88b1789b8612"
|
||||
dependencies = [
|
||||
"gix-error",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-chunk"
|
||||
version = "0.10.0"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "626335faf30ed235744642c2309aa370683b8bb2757f1c22a807e274dff60074"
|
||||
checksum = "60cd5f0e47ffae98bad241ccbc031693765004fb4c2a419f7fda2963232af1e3"
|
||||
dependencies = [
|
||||
"gix-error",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-command"
|
||||
version = "0.12.0"
|
||||
version = "0.12.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac560c05e19455016a4a94b33a77debe59aaed8783da32a73d31c9975947152e"
|
||||
checksum = "2986e78ebad43510ccd7dd18bd9f22e9afd52f2de791e2979b9c715bacb6f0a8"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -2847,9 +2857,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-commitgraph"
|
||||
version = "0.41.0"
|
||||
version = "0.42.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dfede9936d4b789867c09722576aea4ceb0e3aacf962eef035ebab0686b41a80"
|
||||
checksum = "60b53b700d2a506cf98075099df1fcc0558265cbb47fd86bc6d03c231e4bd72a"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-chunk",
|
||||
@@ -2861,9 +2871,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-config"
|
||||
version = "0.62.0"
|
||||
version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65a9c000fa9a9154f22ffc8f8d74426e9300d759c2029e8701e2ba39d5d464ea"
|
||||
checksum = "3e11ccf82e9630c4e7befbae07cbe90e79de61dc73a34448c2dec70a13da9ebf"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-config-value",
|
||||
@@ -2881,9 +2891,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-config-value"
|
||||
version = "0.21.0"
|
||||
version = "0.21.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ab206c2fccfd35e0de7fb1b424997cfd42912062c66dae024e08a06e22d46674"
|
||||
checksum = "d7666081ef0ecc5e1dc54bc6ce16dac9d7b9490780f6c130393ef9e50c909d4a"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bstr",
|
||||
@@ -2895,9 +2905,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-date"
|
||||
version = "0.18.0"
|
||||
version = "0.18.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0f7eeeecc599082f32b5ea6a8c4c734e38be9730e2c09e3fe2851bb4692393e9"
|
||||
checksum = "4c538190012dbb536df54734ec38cc1109270c73f2f76585c011dd5b0c9f087c"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -2907,9 +2917,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-diff"
|
||||
version = "0.69.0"
|
||||
version = "0.70.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa640963fdcbc6b4718e48593c3917f5ae764b59fb5a96313cb5a757246d041d"
|
||||
checksum = "2c794988335792f85c3ca79c385c950b3a921a71ba3df361cb1f9e5b6bd4a6e4"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-attributes",
|
||||
@@ -2931,9 +2941,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-dir"
|
||||
version = "0.31.0"
|
||||
version = "0.32.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "84e916ef77f19161b738ae9913662bc36fed1e48256a943f40277b3a585841da"
|
||||
checksum = "af939f21c65d4f15457c72d08c874d454893185c51a3596e3c2bd3d9c567618d"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-discover",
|
||||
@@ -2951,9 +2961,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-discover"
|
||||
version = "0.57.0"
|
||||
version = "0.57.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7d0f8fd2c7e4b458eb3081362d49b54bd0131d23ecd49be802085a11f0d3cee"
|
||||
checksum = "4a0875f4e5408713fcf92265973cc38bf9dc5a93384ce218beba0572b7785a03"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"dunce",
|
||||
@@ -2966,18 +2976,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-error"
|
||||
version = "0.5.1"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bb3308a948a01b94ef13d9ee7a9b28c1303d8d9a9dc33b401ff40c2184d9e04a"
|
||||
checksum = "50ad6c42fa50280f382026ff838a8afa7ab2ad83e92349cab4392972baae69cd"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-filter"
|
||||
version = "0.36.0"
|
||||
version = "0.36.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9d8d932ee4043f7d77d15ee58d2be2bc95accea5dd1d77fd145de1b7c504551b"
|
||||
checksum = "f8df8d50fda4684c6ec366f75e4082ab6fc3d437d3deec30ff88462710b68d17"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"encoding_rs",
|
||||
@@ -2996,9 +3006,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-fs"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "44a05d043e670c055cd8b53d078562dc0bc1e322bff6b0376b407d37cf72dcc5"
|
||||
checksum = "808f23d897ddfe847d9b7206bda947901885be623bdf96b226a2dccf87f018c7"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -3011,9 +3021,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-glob"
|
||||
version = "0.29.0"
|
||||
version = "0.29.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7b0d03ab50fa841621031960679caf7fe94940968d9a0736d12a580f2c03e525"
|
||||
checksum = "7a12789fa68a150293ad8834d267b31044240532b5ccf2734d228fe985cba2be"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bstr",
|
||||
@@ -3025,11 +3035,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-hash"
|
||||
version = "0.28.0"
|
||||
version = "0.28.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "40ca156064e378d8c657084365846cedb8dc498c6ea4500965a64d74f12af2be"
|
||||
checksum = "b4802ffb87e051795822bfdaa8ab9075b23e316684f7054e6ce4a246b2b76f4e"
|
||||
dependencies = [
|
||||
"faster-hex",
|
||||
"faster-hex 0.10.1",
|
||||
"gix-error",
|
||||
"gix-utils",
|
||||
"sha1dc",
|
||||
@@ -3044,7 +3054,7 @@ checksum = "916cb6b2ec42ffaca624e7867bb382a4673015cb4ffcd7330b48085d02e4c615"
|
||||
dependencies = [
|
||||
"gix-hash",
|
||||
"hashbrown 0.17.1",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3062,9 +3072,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-imara-diff"
|
||||
version = "0.3.1"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c48eccd894bd15555b0346470e63491ded94aefe76b3fcb1052084b5a393238"
|
||||
checksum = "23347fa4a29a440eebf045d0bc21da465c0dc70434c2a4bcdfcc658f16c9e27e"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"hashbrown 0.17.1",
|
||||
@@ -3072,9 +3082,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-index"
|
||||
version = "0.57.0"
|
||||
version = "0.58.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc6db8b20a3dba8836daf90b24199600bb27dcfce3a127ec24ae61e15a7c5b68"
|
||||
checksum = "06bfc736774a623307eda890c918d308ef5acd37402bde2d6768fccb1f6ecb5d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bstr",
|
||||
@@ -3124,9 +3134,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-note"
|
||||
version = "0.3.0"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bd364f8bdceaed9e7f3ae40f324b16e39f20e9c7e6a6a058f7c6ec66c3e6205c"
|
||||
checksum = "8473688f2262f4364f521b39ce2a5dbe94494f327fc19c945318d7aff580952e"
|
||||
dependencies = [
|
||||
"gix-error",
|
||||
"gix-hash",
|
||||
@@ -3135,9 +3145,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-object"
|
||||
version = "0.66.0"
|
||||
version = "0.66.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0e38f50177e211642af154f9a7f710b7a3a637e635f9b6adb9d51973b0f9209"
|
||||
checksum = "beaf9086dd00b9d2a177ca3ae83210ce926cee7c0faa112e053851221cd8f94d"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-actor",
|
||||
@@ -3156,9 +3166,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-odb"
|
||||
version = "0.86.0"
|
||||
version = "0.87.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ca444f33f2140876ed6b5313c2b550b4af699008193c96f3bff5023afa9ef4ea"
|
||||
checksum = "941b5b99fed282a5b05b54ea486c36c76b558afe151e6804c3acdd5c8f3c3459"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"crc32fast",
|
||||
@@ -3175,15 +3185,15 @@ dependencies = [
|
||||
"gix-utils",
|
||||
"gix-zlib",
|
||||
"memmap2",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-pack"
|
||||
version = "0.76.0"
|
||||
version = "0.77.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bc5024cc503cd29461a705ae90b9eae772fa8f0e6fafc1c48513877dc374de05"
|
||||
checksum = "e2ef461798b1e6cb652192c69dfc9658dfc1bab457ef812dd1ab85d75104cbef"
|
||||
dependencies = [
|
||||
"clru",
|
||||
"crc32fast",
|
||||
@@ -3204,45 +3214,46 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-packetline"
|
||||
version = "0.24.0"
|
||||
version = "0.24.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "830e51b227f6a925fe9308858ac91170dd00fa2880f5480fc81e8a4594fe2c35"
|
||||
checksum = "6e198121152a397ad1007e3334931b04b393fa17f6af34f17b33e376b15bf5ea"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"faster-hex",
|
||||
"faster-hex 2.0.0",
|
||||
"gix-error",
|
||||
"gix-trace",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-parallel"
|
||||
version = "0.50.0"
|
||||
version = "0.50.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e994cf1eec247ba4be7f9e7c0d58cc73f83eecb5fcb9feb595df5ba3d2078546"
|
||||
checksum = "d3a5c86eeec0194a3444611b4762ba05cc5029408a617348b4f6a74a34c222cd"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
"gix-trace",
|
||||
"once_cell",
|
||||
"parking_lot",
|
||||
"parking_lot 0.13.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-path"
|
||||
version = "0.14.0"
|
||||
version = "0.14.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6d563d4d0c975ed0df4e853f9ec962a2ba46633b1d324e1a5582541fcae0c6b"
|
||||
checksum = "615e3ff75800c67022ec8065b67e0846420a88c5f484e6c4fd81c78472e4c77a"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
"gix-trace",
|
||||
"gix-validate",
|
||||
"winreg 0.56.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-pathspec"
|
||||
version = "0.22.0"
|
||||
version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3e3b7f03e516a8435d18c3cc2d446925940c81d409145ac21edb5a576f0625e4"
|
||||
checksum = "490aa03a11e0cbb998a0a593b75e27ea2e30df4ebd8f84f60e0641b9b72270e8"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bstr",
|
||||
@@ -3255,9 +3266,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-protocol"
|
||||
version = "0.67.0"
|
||||
version = "0.68.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "832b5dc46a3c0a6f6fa8f8e571c11074add4b545c6789799ae6d6c36ae1a294e"
|
||||
checksum = "83677ebae6a1a09dc07f2435b5ebe68470dc51afb74052135e98fd7c11f85ba9"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-date",
|
||||
@@ -3273,9 +3284,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-quote"
|
||||
version = "0.10.0"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c7f92bc1b13c09e88388578e8aa1e987ec35f28fca158c13b1baa7ab1a85b124"
|
||||
checksum = "5069a7ec021bb47abe9f12dcc075d292e8cf4a9dff5fffd38595b39c6b419aaa"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -3284,9 +3295,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-ref"
|
||||
version = "0.69.0"
|
||||
version = "0.69.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "073bc0928e1f747823b1eaed94918119dacef4c616532bc3d17e5b7457863471"
|
||||
checksum = "68686e4697b9cd15d1b152ef51df870513210ed22938eacc13b3672b76035f13"
|
||||
dependencies = [
|
||||
"gix-actor",
|
||||
"gix-error",
|
||||
@@ -3304,9 +3315,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-refspec"
|
||||
version = "0.47.0"
|
||||
version = "0.47.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ccc7010dae0df2900aa77cc67f8aca042cd80e35938ccc179010d863b1d42a0c"
|
||||
checksum = "2569309da6fdc230973cf5b846508154c0e813fda60f2b2da768cc5655ed312c"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -3317,9 +3328,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-revision"
|
||||
version = "0.51.0"
|
||||
version = "0.52.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "63210c1943b67fa700806c3c3486fc16a92b3ea871f5cf092340b8eec10a0ca1"
|
||||
checksum = "241465fc73530f41d0a1c18320c5e291365b7c2c2a3dfd07afe2a5d6265085c8"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bstr",
|
||||
@@ -3336,9 +3347,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-revwalk"
|
||||
version = "0.37.0"
|
||||
version = "0.38.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "800479fbbf1e7f94f663e07943a91add5499343e7aac611a81e6a0460fd44af6"
|
||||
checksum = "8b46edeacd25d9d3131941ae6bc91002bf7ba10e130393b7e9bc23d528625447"
|
||||
dependencies = [
|
||||
"gix-commitgraph",
|
||||
"gix-date",
|
||||
@@ -3351,9 +3362,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-sec"
|
||||
version = "0.16.0"
|
||||
version = "0.16.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5640f642a1b471616d48230b1def7ca743cb30903441ff84800cafbab3c0fddf"
|
||||
checksum = "9598d1f35baec7038c2d278bfcc18f1d8951f41dcc3f51ab6175661dfe5a6137"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"gix-path",
|
||||
@@ -3363,9 +3374,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-shallow"
|
||||
version = "0.15.0"
|
||||
version = "0.15.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94bc0720a3d6b10f18e3ac382a7780bcfc4c6bee94a8b5857b8e4ec94c50d754"
|
||||
checksum = "1d805949578724b5164c90ec6d19567832ccaa5ba8a3fe26f7befc52007e2407"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -3376,9 +3387,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-status"
|
||||
version = "0.36.0"
|
||||
version = "0.37.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "42d3174a9f3fb991cf25a7a609ab6c50f19baa7d5f8ce05a48c202f7db4ce3ba"
|
||||
checksum = "31b00c359278210e3cc0803d057db1d61c5d6694c21ed9ad0b8f8f862157247a"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"filetime",
|
||||
@@ -3398,14 +3409,13 @@ dependencies = [
|
||||
"gix-worktree",
|
||||
"hashbrown 0.16.1",
|
||||
"portable-atomic",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-submodule"
|
||||
version = "0.36.0"
|
||||
version = "0.36.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6d945257bd0d624ca844a5a36c79d748df080f355b0ac92d68793875aa529a3f"
|
||||
checksum = "d558a1307b6f3de2a92bd91d0570c53952d4f2329e6860813007508c8ed413dc"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-config",
|
||||
@@ -3425,22 +3435,22 @@ dependencies = [
|
||||
"dashmap",
|
||||
"gix-fs",
|
||||
"libc",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"tempfile",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-trace"
|
||||
version = "0.3.0"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "133f2de116104d637541831b6acb157898556d5eeec363ab2eb1c583adc6bb56"
|
||||
checksum = "1c96f84d731a96780e6a7ad5ee70b4ecc398499946b62617945fbaeb6ab878f8"
|
||||
|
||||
[[package]]
|
||||
name = "gix-transport"
|
||||
version = "0.61.0"
|
||||
version = "0.62.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e43d6b0097ea9f2f266d5d6c43b8f615ed3da7c686ec8771cd17c1cb33cb0de"
|
||||
checksum = "cdcd9cdfd8745aa38f926a4a380c13d76b200d7338de57fc492982cd5a6652ba"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-command",
|
||||
@@ -3456,9 +3466,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-traverse"
|
||||
version = "0.63.0"
|
||||
version = "0.64.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a668a6e7f7688e5a43eaf161f1471ffc559de1a5fd8471e861c64d59d1699e1e"
|
||||
checksum = "00171e00e91508300d0361072c4eb110ec0f1322d8b95ed36887231702a38ebc"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"gix-commitgraph",
|
||||
@@ -3473,9 +3483,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-url"
|
||||
version = "0.40.0"
|
||||
version = "0.40.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "04317dea7a5dd5253bbcab060c230f3de6a57d17cc9600c6cd7030bf4795b414"
|
||||
checksum = "def12e1016b872f1094442882f627905c59bd73480435291a4958cf373a8f28d"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -3486,9 +3496,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-utils"
|
||||
version = "0.5.1"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8e770b8c34311044d1addc7b18957db0ac27183707e1140dc90e6f674a6354e"
|
||||
checksum = "b5e6d46894c7a4fd9c5e26d233a0fa836002ba0af9a11aef58923d317c486e10"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"bytes",
|
||||
@@ -3501,9 +3511,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-validate"
|
||||
version = "0.13.0"
|
||||
version = "0.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cbcd59cc52742468bc5c8a0e7123390d154f45e6cbd37461b0dcecdc681f2179"
|
||||
checksum = "5d6f293fd8abd9bd9bc1e0a23541f73607e932b5a2bde2246320da38edde5726"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -3511,9 +3521,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-worktree"
|
||||
version = "0.58.0"
|
||||
version = "0.59.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a285c0f6b41e504e8bb81ca3f861c4da00cb3d5ced3210a4591112f22da6d38f"
|
||||
checksum = "fe92aec0a25cf073394492a6ee2aa4d27632acde91a653d34de0e4da6afb485d"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-attributes",
|
||||
@@ -3530,9 +3540,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-worktree-stream"
|
||||
version = "0.38.0"
|
||||
version = "0.39.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28d2789610e8179d4e0e8e51170a52a66483c103a8ad3c7db4d075b571856cb6"
|
||||
checksum = "3fe5d65793848ffb596f6c5596fd120b132038736525628227e2388ca454f64d"
|
||||
dependencies = [
|
||||
"gix-attributes",
|
||||
"gix-error",
|
||||
@@ -3545,14 +3555,14 @@ dependencies = [
|
||||
"gix-trace",
|
||||
"gix-traverse",
|
||||
"gix-utils",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-zlib"
|
||||
version = "0.3.0"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8c2edb206bf06f3c801f4f6789c696396171558ab9b4c7f1fe3ba4d39b00b0f4"
|
||||
checksum = "81a49a8b263d2a140f1c178ff93375b8d4cc7b1d3252cd87ce1ca88bce62b9b9"
|
||||
dependencies = [
|
||||
"gix-error",
|
||||
"zlib-rs",
|
||||
@@ -4156,7 +4166,7 @@ dependencies = [
|
||||
"ide-tools",
|
||||
"ide-vcs",
|
||||
"ide-vfs",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"rustix",
|
||||
"semver",
|
||||
"serde",
|
||||
@@ -4297,7 +4307,7 @@ dependencies = [
|
||||
"ide-language",
|
||||
"libc",
|
||||
"memchr",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"percent-encoding",
|
||||
"portable-pty",
|
||||
"serde",
|
||||
@@ -4329,7 +4339,7 @@ dependencies = [
|
||||
"notify",
|
||||
"open",
|
||||
"oracledb",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"reqwest",
|
||||
"rsa",
|
||||
"rustls",
|
||||
@@ -4385,7 +4395,7 @@ dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
"ed25519-dalek",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4403,7 +4413,7 @@ version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-android",
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
]
|
||||
@@ -4510,7 +4520,7 @@ dependencies = [
|
||||
"ide-workspace",
|
||||
"ignore",
|
||||
"jsonschema",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"quick-xml 0.42.0",
|
||||
"regex-lite",
|
||||
"regex-syntax",
|
||||
@@ -4540,7 +4550,7 @@ dependencies = [
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"reqwest",
|
||||
"rustls",
|
||||
"rustls-platform-verifier",
|
||||
@@ -4565,7 +4575,7 @@ dependencies = [
|
||||
"ide-language",
|
||||
"ignore",
|
||||
"nucleo-matcher",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"postcard",
|
||||
"rayon",
|
||||
"redb",
|
||||
@@ -4593,7 +4603,7 @@ version = "0.1.53"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
@@ -4634,7 +4644,7 @@ dependencies = [
|
||||
"ide-extension",
|
||||
"ide-text",
|
||||
"memchr",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"regex-lite",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4699,7 +4709,7 @@ dependencies = [
|
||||
"ide-vfs",
|
||||
"ignore",
|
||||
"lsp-types",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"percent-encoding",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4739,7 +4749,7 @@ dependencies = [
|
||||
"jupyter-protocol",
|
||||
"jupyter-zmq-client",
|
||||
"libc",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4759,7 +4769,7 @@ dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
"ide-extension",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4798,7 +4808,7 @@ dependencies = [
|
||||
"ide-run",
|
||||
"ide-ssh",
|
||||
"ignore",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4816,8 +4826,9 @@ dependencies = [
|
||||
"ide-build",
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
"ide-workspace",
|
||||
"libc",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"portable-pty",
|
||||
"quick-xml 0.42.0",
|
||||
"serde",
|
||||
@@ -4899,7 +4910,7 @@ name = "ide-spell"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4916,7 +4927,7 @@ dependencies = [
|
||||
"ide-core",
|
||||
"keyring",
|
||||
"keyring-core",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"russh",
|
||||
"russh-sftp",
|
||||
"rustls",
|
||||
@@ -4966,7 +4977,7 @@ version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"portable-pty",
|
||||
"serde",
|
||||
"specta",
|
||||
@@ -4998,7 +5009,7 @@ dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
"libc",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
@@ -5045,7 +5056,7 @@ dependencies = [
|
||||
"ide-core",
|
||||
"ignore",
|
||||
"notify",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"rayon",
|
||||
"rustix",
|
||||
"serde",
|
||||
@@ -5086,7 +5097,7 @@ dependencies = [
|
||||
"ide-core",
|
||||
"ide-text",
|
||||
"ide-vfs",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -5096,6 +5107,7 @@ dependencies = [
|
||||
"toml_edit 0.25.17+spec-1.1.0",
|
||||
"tracing",
|
||||
"uuid",
|
||||
"winreg 0.56.0",
|
||||
"zip",
|
||||
]
|
||||
|
||||
@@ -5239,7 +5251,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f"
|
||||
dependencies = [
|
||||
"io-lifetimes 3.0.1",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5277,7 +5289,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"
|
||||
dependencies = [
|
||||
"hermit-abi",
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5777,6 +5789,15 @@ dependencies = [
|
||||
"scopeguard",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lock_api"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65d91b22da179613dcf4d6ec8349563f52a363f6849e03b00dd0a185ec4a59af"
|
||||
dependencies = [
|
||||
"scopeguard",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.34"
|
||||
@@ -6748,7 +6769,7 @@ dependencies = [
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2-web-kit 0.3.2",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"percent-encoding",
|
||||
"reqwest",
|
||||
"security-framework",
|
||||
@@ -6938,8 +6959,18 @@ version = "0.12.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
|
||||
dependencies = [
|
||||
"lock_api",
|
||||
"parking_lot_core",
|
||||
"lock_api 0.4.14",
|
||||
"parking_lot_core 0.9.12",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a9cf937ca4e1d0b7578784559063422fc39ae7c5a00f02471f2614d5486fd226"
|
||||
dependencies = [
|
||||
"lock_api 0.5.0",
|
||||
"parking_lot_core 0.10.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6950,7 +6981,19 @@ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"redox_syscall",
|
||||
"redox_syscall 0.5.18",
|
||||
"smallvec",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot_core"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9cfff060068cc18aa7815010fcaf80c68c7fb9e85fc7f5c0f9bf142c21d19826"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"redox_syscall 0.9.5",
|
||||
"smallvec",
|
||||
"windows-link",
|
||||
]
|
||||
@@ -7401,7 +7444,7 @@ version = "31.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf52d87428247c5aa3760ac8e7d8b13ec7b3579b955a8c3f311668b6860acba5"
|
||||
dependencies = [
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7597,6 +7640,15 @@ dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_syscall"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_users"
|
||||
version = "0.5.3"
|
||||
@@ -7636,7 +7688,7 @@ dependencies = [
|
||||
"ahash",
|
||||
"fluent-uri 0.3.2",
|
||||
"once_cell",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"percent-encoding",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -7970,7 +8022,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8038,7 +8090,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8712,7 +8764,7 @@ dependencies = [
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2-quartz-core 0.3.2",
|
||||
"raw-window-handle",
|
||||
"redox_syscall",
|
||||
"redox_syscall 0.5.18",
|
||||
"tracing",
|
||||
"wasm-bindgen",
|
||||
"web-sys",
|
||||
@@ -8812,7 +8864,7 @@ version = "0.9.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
|
||||
dependencies = [
|
||||
"lock_api",
|
||||
"lock_api 0.4.14",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9086,7 +9138,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901"
|
||||
dependencies = [
|
||||
"new_debug_unreachable",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"phf_shared",
|
||||
"precomputed-hash",
|
||||
]
|
||||
@@ -9274,7 +9326,7 @@ dependencies = [
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2-ui-kit 0.3.2",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"percent-encoding",
|
||||
"raw-window-handle",
|
||||
"tao-macros",
|
||||
@@ -9782,10 +9834,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.3.4",
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9965,7 +10017,7 @@ dependencies = [
|
||||
"bytes",
|
||||
"libc",
|
||||
"mio",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"pin-project-lite",
|
||||
"signal-hook-registry",
|
||||
"socket2",
|
||||
@@ -11622,7 +11674,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -12420,7 +12472,7 @@ dependencies = [
|
||||
"log",
|
||||
"num-traits",
|
||||
"once_cell",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"rand 0.9.5",
|
||||
"regex",
|
||||
"scc",
|
||||
|
||||
+1
-1
@@ -108,7 +108,7 @@ jupyter-zmq-client = { version = "=2.0.0", default-features = false, features =
|
||||
jupyter-protocol = "=2.0.3"
|
||||
zeromq = { version = "0.6", default-features = false, features = ["tokio-runtime", "tcp-transport"] }
|
||||
lsp-types = "0.97"
|
||||
gix = { version = "0.89", default-features = false }
|
||||
gix = { version = "0.90", default-features = false }
|
||||
portable-pty = "0.9"
|
||||
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "http2", "charset", "socks", "gzip", "deflate", "brotli"] }
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
|
||||
|
||||
@@ -6,6 +6,12 @@
|
||||
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
|
||||
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
|
||||
|
||||
## DuckDB symbol
|
||||
|
||||
DuckDB is a trademark of the DuckDB Foundation. The data source icon uses the
|
||||
light and dark symbols from the [DuckDB Design Manual](https://duckdb.org/design/manual/#logo-usage).
|
||||
The SVG paths and colors are preserved. See the [DuckDB trademark guidelines](https://duckdb.org/trademark_guidelines.html).
|
||||
|
||||
## Agent logos
|
||||
|
||||
The `src/ui/openidea/agents/` logos of agents listed in the
|
||||
@@ -149,6 +155,7 @@ languages whose JetBrains icons are not open source (Go, Ruby, Dart, Lua, Zig,
|
||||
Svelte, …). Those using the page-with-corner-badge layout (`goMod`, `goWork`,
|
||||
`dotenv`, `readme`, `lock`, `license`) reuse the page outline of the Apache-2.0
|
||||
expui `fileTypes/h.svg`; that outline is modified from the original by JetBrains.
|
||||
`goTest` adds a scaled copy of the Apache-2.0 expui `nodes/test.svg` as its badge.
|
||||
`src/ui/openidea/runConfigurations/springBoot*.svg` (the Spring Boot run configuration
|
||||
leaf) is OpenIDEA's own drawing.
|
||||
|
||||
|
||||
@@ -155,13 +155,14 @@ pub(crate) fn is_fast_option(id: &str) -> bool {
|
||||
}
|
||||
|
||||
/// Whether an option's available values and default belong to the selected model
|
||||
/// (`thought_level`, `context_tier`, and `model_config` options like `context` and `fast`)
|
||||
/// (`thought_level`, `context_tier`, and `model_config` options like `context`, `fast` and `service_tier`)
|
||||
/// rather than the provider as a whole.
|
||||
pub(crate) fn is_per_model_option(o: &AgentConfigOption) -> bool {
|
||||
matches!(o.category.as_deref(), Some("thought_level" | "context_tier" | "model_config"))
|
||||
|| matches!(o.id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|
||||
|| is_fast_option(&o.id)
|
||||
|| is_context_option(&o.id)
|
||||
|| o.id == "service_tier"
|
||||
}
|
||||
|
||||
/// A `configOptions` array; only select options are kept (the UI shows them as dropdowns).
|
||||
@@ -531,6 +532,15 @@ mod tests {
|
||||
assert_eq!(ids(&c), [("allow_all", Some("off")), ("approval", Some("ask"))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn service_tier_is_per_model() {
|
||||
let options = options_of(&json!({ "configOptions": [
|
||||
{ "id": "service_tier", "type": "select", "currentValue": "false",
|
||||
"options": [{ "value": "false" }, { "value": "true" }] }
|
||||
] }));
|
||||
assert!(is_per_model_option(&options[0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effort_context_and_fast_are_per_model_options() {
|
||||
let mut c = options_of(&json!({
|
||||
|
||||
@@ -450,6 +450,10 @@ struct TaskFile {
|
||||
/// The user named the task: its agent's own title updates no longer replace it.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
title_renamed: bool,
|
||||
/// [`NewAgentTask::ephemeral`]: the task file is never written, and new sessions ask the
|
||||
/// agent not to save their history.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
ephemeral: bool,
|
||||
/// Start the first session as a fork of a recorded native one (once).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pending_native_fork: Option<ForkStart>,
|
||||
@@ -479,6 +483,9 @@ fn canonical_uuid(value: &str) -> bool {
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct PendingModel {
|
||||
/// Native Codex intent, including when this model cannot expose a Fast control.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
retained_service_tier: Option<AgentConfigChoice>,
|
||||
model: AgentConfigChoice,
|
||||
candidate: Option<AgentConfigValue>,
|
||||
options: Vec<AgentConfigOption>,
|
||||
@@ -494,6 +501,11 @@ impl PendingModel {
|
||||
});
|
||||
wanted.push(self.model.clone());
|
||||
wanted.extend(self.choices.iter().cloned());
|
||||
if let Some(choice) = &self.retained_service_tier
|
||||
&& !wanted.iter().any(|c| c.id == choice.id)
|
||||
{
|
||||
wanted.push(choice.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -527,6 +539,8 @@ struct TaskState {
|
||||
pending_rollback: u32,
|
||||
/// The user named the task; see `TaskFile::title_renamed`.
|
||||
title_renamed: bool,
|
||||
/// [`NewAgentTask::ephemeral`].
|
||||
ephemeral: bool,
|
||||
/// See `TaskFile::pending_native_fork`: cleared once a session is established.
|
||||
pending_native_fork: Option<ForkStart>,
|
||||
/// A turn is running or about to (prompts arriving now are queued).
|
||||
@@ -554,7 +568,12 @@ impl TaskState {
|
||||
}
|
||||
task.config.retain(|o| !config::is_per_model_option(o));
|
||||
task.config.extend(pending.options.iter().cloned().map(|mut option| {
|
||||
if let Some(choice) = pending.choices.iter().find(|choice| choice.id == option.id) {
|
||||
if let Some(choice) = pending
|
||||
.choices
|
||||
.iter()
|
||||
.chain(pending.retained_service_tier.iter())
|
||||
.find(|choice| choice.id == option.id)
|
||||
{
|
||||
option.current = Some(choice.value.clone());
|
||||
}
|
||||
option
|
||||
@@ -805,6 +824,14 @@ impl AgentManager {
|
||||
provider::set_builtin_command(&dir, self.shared.env_secrets(), id, command.as_deref())
|
||||
}
|
||||
|
||||
/// Sets the extra arguments of a directly launched built-in ACP agent; empty resets them.
|
||||
pub fn set_builtin_additional_args(&self, id: &str, args: Vec<String>) -> IdeResult<()> {
|
||||
let Some(dir) = self.shared.paths.custom_agents_dir.as_deref() else {
|
||||
return Err(IdeError::unavailable("there is no custom agents directory"));
|
||||
};
|
||||
provider::set_builtin_additional_args(dir, self.shared.env_secrets(), id, args)
|
||||
}
|
||||
|
||||
/// Sets the environment variables built-in `id` starts with; empty clears them.
|
||||
pub fn set_builtin_env(&self, id: &str, env: std::collections::BTreeMap<String, String>) -> IdeResult<()> {
|
||||
let Some(dir) = self.shared.paths.custom_agents_dir.clone() else {
|
||||
@@ -1050,6 +1077,7 @@ impl AgentManager {
|
||||
subagents: Vec::new(),
|
||||
pending_rollback: 0,
|
||||
title_renamed: true,
|
||||
ephemeral: false,
|
||||
pending_native_fork: None,
|
||||
};
|
||||
let handle = Task::restore(file, self.shared.clone());
|
||||
@@ -1135,6 +1163,7 @@ impl AgentManager {
|
||||
subagents: Vec::new(),
|
||||
pending_rollback: 0,
|
||||
title_renamed: true,
|
||||
ephemeral: false,
|
||||
pending_native_fork: Some(ForkStart { source: session_id.to_owned(), target }),
|
||||
};
|
||||
let handle = Task::restore(file, self.shared.clone());
|
||||
@@ -1264,6 +1293,7 @@ impl AgentManager {
|
||||
subagents: Vec::new(),
|
||||
pending_rollback: 0,
|
||||
title_renamed: false,
|
||||
ephemeral: req.ephemeral,
|
||||
pending_native_fork: None,
|
||||
};
|
||||
let handle = Task::restore(file, self.shared.clone());
|
||||
@@ -1630,6 +1660,7 @@ impl AgentManager {
|
||||
subagents: s.conversation.saved_subagents(),
|
||||
pending_rollback: total - keep,
|
||||
title_renamed: s.title_renamed,
|
||||
ephemeral: s.ephemeral,
|
||||
pending_native_fork: None,
|
||||
}
|
||||
};
|
||||
@@ -2501,7 +2532,7 @@ impl Task {
|
||||
turns.push(Some(Arc::new(last)));
|
||||
}
|
||||
let mut wanted = file.wanted;
|
||||
let pending_model = file.pending_switch.or_else(|| {
|
||||
let mut pending_model = file.pending_switch.or_else(|| {
|
||||
let id = file.pending_model?;
|
||||
let index = wanted.iter().position(|choice| choice.id == id)?;
|
||||
let model = wanted.remove(index);
|
||||
@@ -2516,8 +2547,14 @@ impl Task {
|
||||
.and_then(|o| o.values.iter().find(|v| v.value == model.value))
|
||||
.cloned();
|
||||
let options = catalog.thought_levels.get(&model.value).cloned().unwrap_or_default();
|
||||
Some(PendingModel { model, candidate, options, choices: Vec::new() })
|
||||
Some(PendingModel { model, candidate, options, choices: Vec::new(), retained_service_tier: None })
|
||||
});
|
||||
if let Some(pending) = &mut pending_model
|
||||
&& pending.retained_service_tier.is_none()
|
||||
&& shared.spec(&task.provider).is_some_and(|spec| spec.driver == provider::Driver::Codex)
|
||||
{
|
||||
pending.retained_service_tier = wanted.iter().find(|c| c.id == "service_tier").cloned();
|
||||
}
|
||||
Arc::new(Self {
|
||||
id: task.id.clone(),
|
||||
shared,
|
||||
@@ -2535,6 +2572,7 @@ impl Task {
|
||||
turns,
|
||||
pending_rollback: file.pending_rollback,
|
||||
title_renamed: file.title_renamed,
|
||||
ephemeral: file.ephemeral,
|
||||
pending_native_fork: file.pending_native_fork,
|
||||
busy: false,
|
||||
background_tasks: Vec::new(),
|
||||
@@ -2791,7 +2829,9 @@ impl Task {
|
||||
let mut file = self.file.lock();
|
||||
// Read before the copy: whatever was asked for up to now is in it.
|
||||
let asked = self.saves_asked.load(Ordering::Acquire);
|
||||
if file.deleted || file.saved >= asked {
|
||||
// A throwaway task is never written: one its caller couldn't delete (a window closed
|
||||
// while it ran) is gone after a restart.
|
||||
if file.deleted || file.saved >= asked || self.state.lock().ephemeral {
|
||||
return;
|
||||
}
|
||||
let copy = {
|
||||
@@ -2811,6 +2851,7 @@ impl Task {
|
||||
subagents: s.conversation.saved_subagents(),
|
||||
pending_rollback: s.pending_rollback,
|
||||
title_renamed: s.title_renamed,
|
||||
ephemeral: s.ephemeral,
|
||||
pending_native_fork: s.pending_native_fork.clone(),
|
||||
}
|
||||
};
|
||||
@@ -3092,7 +3133,13 @@ impl Task {
|
||||
.filter(|pending| pending.model.value == value)
|
||||
.map(|pending| pending.choices)
|
||||
.unwrap_or_default();
|
||||
let retained_service_tier = self
|
||||
.shared
|
||||
.spec(&provider)
|
||||
.filter(|spec| spec.driver == provider::Driver::Codex)
|
||||
.and_then(|_| s.wanted.iter().find(|c| c.id == "service_tier").cloned());
|
||||
s.pending_model = Some(PendingModel {
|
||||
retained_service_tier,
|
||||
model: AgentConfigChoice { id: target.id, value },
|
||||
candidate: Some(candidate),
|
||||
options,
|
||||
@@ -3476,6 +3523,21 @@ impl Task {
|
||||
let cwd_s = dunce::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf()).to_string_lossy().into_owned();
|
||||
let pending_native_fork = self.state.lock().pending_native_fork.clone();
|
||||
|
||||
let mut opening_params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots);
|
||||
if spec.driver == provider::Driver::Codex {
|
||||
let s = self.state.lock();
|
||||
let mut wanted = s.wanted.clone();
|
||||
if let Some(pending) = pending_model {
|
||||
pending.apply(&mut wanted, &s.task.config);
|
||||
}
|
||||
// Restore intent even when the resumed model cannot expose the Fast control.
|
||||
if let Some(fast) =
|
||||
wanted.iter().find(|c| c.id == "service_tier").and_then(|c| c.value.parse::<bool>().ok())
|
||||
{
|
||||
opening_params["_meta"]["openidea"]["codexFast"] = json!(fast);
|
||||
}
|
||||
}
|
||||
|
||||
let mut tried_auth = false;
|
||||
let mut session = None;
|
||||
if let Some(fork) = pending_native_fork {
|
||||
@@ -3485,7 +3547,7 @@ impl Task {
|
||||
allow_acp_fallback: false,
|
||||
});
|
||||
}
|
||||
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots);
|
||||
let mut params = opening_params.clone();
|
||||
params["sessionId"] = json!(&fork.source);
|
||||
if let Some(target) = &fork.target {
|
||||
match params["_meta"].as_object_mut() {
|
||||
@@ -3522,7 +3584,7 @@ impl Task {
|
||||
// The replay goes before what this turn already showed (the user's message).
|
||||
let shown = self.adopts_replay().then(|| self.take_entries());
|
||||
self.replaying.store(true, Ordering::Release);
|
||||
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots);
|
||||
let mut params = opening_params.clone();
|
||||
params["sessionId"] = json!(&id);
|
||||
let loaded = self.request_with_auth(&peer, &init, &mut tried_auth, "session/load", params).await;
|
||||
tokio::time::sleep(REPLAY_GRACE).await;
|
||||
@@ -3576,7 +3638,10 @@ impl Task {
|
||||
let (session_id, result) = match session {
|
||||
Some(s) => s,
|
||||
None => {
|
||||
let params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots);
|
||||
let mut params = opening_params;
|
||||
if self.state.lock().ephemeral {
|
||||
mark_ephemeral(&mut params);
|
||||
}
|
||||
let v = self.request_with_auth(&peer, &init, &mut tried_auth, "session/new", params).await.map_err(
|
||||
|e| match self.sign_in_error(&e, Some(&sign_in_message)) {
|
||||
Some(msg) => SessionOpenError { message: msg, allow_acp_fallback: false },
|
||||
@@ -3687,7 +3752,10 @@ impl Task {
|
||||
if config::is_per_model_option(&o) && !model_options {
|
||||
continue;
|
||||
}
|
||||
let already = (known || explicit) && o.current.as_deref() == Some(choice.value.as_str());
|
||||
// A displayed tier can be inherited. Preserve an explicit Fast/Standard choice
|
||||
// even when it currently looks the same, so subsequent turns receive the override.
|
||||
let already =
|
||||
o.id != "service_tier" && (known || explicit) && o.current.as_deref() == Some(choice.value.as_str());
|
||||
if already || !o.values.iter().any(|v| v.value == choice.value) {
|
||||
continue;
|
||||
}
|
||||
@@ -4636,6 +4704,15 @@ fn session_params(cwd: &str, mcp: &McpForSession, skills: Option<&skills::Delive
|
||||
params
|
||||
}
|
||||
|
||||
/// `_meta.openidea.ephemeral` of `session/new`: the native drivers start the session without
|
||||
/// saving it (Claude Code `--no-session-persistence`, Codex `ephemeral` threads).
|
||||
fn mark_ephemeral(params: &mut Value) {
|
||||
if !params["_meta"]["openidea"].is_object() {
|
||||
params["_meta"]["openidea"] = json!({});
|
||||
}
|
||||
params["_meta"]["openidea"]["ephemeral"] = json!(true);
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
}
|
||||
|
||||
@@ -612,6 +612,9 @@ pub struct AgentProvider {
|
||||
/// Executable and arguments actually launched, without flattening paths containing spaces.
|
||||
pub program: String,
|
||||
pub args: Vec<String>,
|
||||
/// Settings-managed suffix of `args`; absent for launches that cannot be edited.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub additional_args: Option<Vec<String>>,
|
||||
pub default_program: Option<String>,
|
||||
pub default_args: Vec<String>,
|
||||
pub login_hint: Option<String>,
|
||||
@@ -700,6 +703,10 @@ pub struct NewAgentTask {
|
||||
/// `!` command runs in it first.
|
||||
#[serde(default)]
|
||||
pub idle: bool,
|
||||
/// A throwaway task (Generate Commit Message): it isn't saved, so it doesn't outlive a
|
||||
/// restart, and the agent keeps no session history of its own for it.
|
||||
#[serde(default)]
|
||||
pub ephemeral: bool,
|
||||
}
|
||||
|
||||
/// A file the task changed: against [`AgentTask::base_commit`], or against `HEAD` in the
|
||||
|
||||
@@ -178,6 +178,8 @@ struct Session {
|
||||
additional_dirs: Vec<String>,
|
||||
/// The staged skills' `--settings` JSON (`skillOverrides` for the native ones too).
|
||||
skills_settings: Option<String>,
|
||||
/// `_meta.openidea.ephemeral`: `--no-session-persistence`, nothing saved under `~/.claude`.
|
||||
ephemeral: bool,
|
||||
shim: Weak<Shim>,
|
||||
st: Mutex<State>,
|
||||
/// Serializes (re)starting the process.
|
||||
@@ -376,6 +378,7 @@ impl Shim {
|
||||
skills_add_dir: skills.and_then(|s| s.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
|
||||
additional_dirs: additional_dirs(params),
|
||||
skills_settings: skills.and_then(|s| s.get("claudeSettings")).and_then(Value::as_str).map(str::to_owned),
|
||||
ephemeral: params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool).unwrap_or(false),
|
||||
shim: Arc::downgrade(self),
|
||||
st: Mutex::new(State {
|
||||
proc: None,
|
||||
@@ -731,6 +734,9 @@ impl Session {
|
||||
if let Some(settings) = &self.skills_settings {
|
||||
args.extend(["--settings".to_owned(), settings.clone()]);
|
||||
}
|
||||
if self.ephemeral {
|
||||
args.push("--no-session-persistence".to_owned());
|
||||
}
|
||||
args.extend(start.args());
|
||||
let launch =
|
||||
Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() };
|
||||
|
||||
@@ -464,6 +464,7 @@ async fn replay_simple() {
|
||||
let args = r.cli.launched.lock()[0].clone();
|
||||
assert!(args.windows(2).any(|w| w == ["--session-id", r.session.as_str()]), "{args:?}");
|
||||
assert!(args.contains(&"--permission-prompt-tool".to_owned()));
|
||||
assert!(!args.contains(&"--no-session-persistence".to_owned()));
|
||||
let user = r.sent(0).into_iter().find(|m| m["type"] == "user").unwrap();
|
||||
assert_eq!(user["message"]["content"][0]["text"], "Reply with exactly: hello there");
|
||||
}
|
||||
@@ -1428,3 +1429,16 @@ fn additional_directories_are_read_from_the_session_params() {
|
||||
assert_eq!(additional_dirs(¶ms), ["/w/web", "/w/docs"]);
|
||||
assert!(additional_dirs(&json!({ "cwd": "/w/api" })).is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_ephemeral_session_is_not_saved() {
|
||||
let cli = replay_cli(load_fixture("simple"));
|
||||
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
|
||||
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
|
||||
let h =
|
||||
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
|
||||
let params = json!({ "cwd": h.cwd, "mcpServers": [], "_meta": { "openidea": { "ephemeral": true } } });
|
||||
h.request("session/new", params).await.unwrap();
|
||||
let args = cli.launched.lock()[0].clone();
|
||||
assert!(args.contains(&"--no-session-persistence".to_owned()), "{args:?}");
|
||||
}
|
||||
@@ -108,7 +108,7 @@ pub(crate) async fn discover(
|
||||
let options = translate::config_options(&models, &settings);
|
||||
let levels = crate::config::options_of(&json!({ "configOptions": options }))
|
||||
.into_iter()
|
||||
.filter(|o| o.category.as_deref() == Some("thought_level"))
|
||||
.filter(|o| matches!(o.category.as_deref(), Some("thought_level" | "model_config")))
|
||||
.collect();
|
||||
(model.id.clone(), levels)
|
||||
})
|
||||
@@ -492,8 +492,14 @@ impl CodexShim {
|
||||
self.prepare_project_trust(params).await;
|
||||
let mut request = json!({ "cwd": params.get("cwd") });
|
||||
apply_thread_config(params, &mut request);
|
||||
// Not written to `~/.codex/sessions`, so it isn't listed among the past threads.
|
||||
if params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool) == Some(true) {
|
||||
request["ephemeral"] = json!(true);
|
||||
}
|
||||
let result = self.call("thread/start", request).await?;
|
||||
let (id, options) = self.open_thread(&result, &models, None);
|
||||
let mut settings = Settings::of(&result, &models);
|
||||
settings.fast_override = params.pointer("/_meta/openidea/codexFast").and_then(Value::as_bool);
|
||||
let (id, options) = self.open_thread(&result, &models, Some(settings));
|
||||
if id.is_empty() {
|
||||
return Err(error(codes::INTERNAL_ERROR, "codex started no thread"));
|
||||
}
|
||||
@@ -510,7 +516,9 @@ impl CodexShim {
|
||||
let mut request = json!({ "threadId": id, "cwd": params.get("cwd") });
|
||||
apply_thread_config(params, &mut request);
|
||||
let result = self.call("thread/resume", request).await?;
|
||||
let (_, options) = self.open_thread(&result, &models, None);
|
||||
let mut settings = Settings::of(&result, &models);
|
||||
settings.fast_override = params.pointer("/_meta/openidea/codexFast").and_then(Value::as_bool);
|
||||
let (_, options) = self.open_thread(&result, &models, Some(settings));
|
||||
let cwd = self.state.lock().threads.get(id).and_then(|t| t.cwd.clone());
|
||||
let thread = result.get("thread").unwrap_or(&Value::Null);
|
||||
for update in translate::history(thread, cwd.as_deref()) {
|
||||
@@ -613,6 +621,9 @@ impl CodexShim {
|
||||
if let Some(effort) = &s.effort {
|
||||
request["effort"] = json!(effort);
|
||||
}
|
||||
if let Some(tier) = s.service_tier_override(&models) {
|
||||
request["serviceTier"] = json!(tier);
|
||||
}
|
||||
}
|
||||
self.call("turn/start", request).await
|
||||
}
|
||||
@@ -1595,3 +1606,6 @@ fn mcp_text(response: &Value) -> String {
|
||||
.collect::<Vec<_>>();
|
||||
format!("MCP servers:\n{}", lines.join("\n"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod reconnect_tests;
|
||||
@@ -0,0 +1,217 @@
|
||||
//! User-facing task operations through the native shim, with a local app-server stand-in.
|
||||
use super::*;
|
||||
use crate::{AgentManager, AgentPrompt, AgentStatus, Isolation, NewAgentTask};
|
||||
|
||||
#[derive(Default)]
|
||||
struct Runtime {
|
||||
models: Mutex<HashMap<String, String>>,
|
||||
hide_a: std::sync::atomic::AtomicBool,
|
||||
turns: Mutex<Vec<Value>>,
|
||||
tiers: Mutex<HashMap<String, Value>>,
|
||||
servers: Mutex<Vec<Peer>>,
|
||||
}
|
||||
struct Connection {
|
||||
runtime: Arc<Runtime>,
|
||||
peer: OnceLock<Peer>,
|
||||
}
|
||||
impl Handler for Connection {
|
||||
fn on_notification(&self, _: &str, _: Value) {}
|
||||
fn on_request(&self, method: &str, p: Value) -> Result<Value, (i64, String)> {
|
||||
match method {
|
||||
"initialize" => Ok(json!({})),
|
||||
"model/list" => {
|
||||
let mut data = vec![json!({"id":"b", "model":"b", "serviceTiers":[]})];
|
||||
if !self.runtime.hide_a.swap(false, std::sync::atomic::Ordering::SeqCst) {
|
||||
data.insert(0, json!({"id":"a", "model":"a", "isDefault":true, "serviceTiers":[{"id":"fast"}]}));
|
||||
}
|
||||
Ok(json!({"data":data}))
|
||||
}
|
||||
"config/read" => Ok(json!({"layers":[]})),
|
||||
"skills/list" => Ok(json!({"data":[]})),
|
||||
"thread/start" | "thread/resume" => {
|
||||
let mut models = self.runtime.models.lock();
|
||||
let id = p["threadId"].as_str().map(str::to_owned).unwrap_or_else(|| format!("s{}", models.len()));
|
||||
let model = models.entry(id.clone()).or_insert_with(|| "a".into()).clone();
|
||||
Ok(json!({"thread":{"id":id,"name":"fixture","turns":[]}, "model":model,
|
||||
"serviceTier":self.runtime.tiers.lock().get(&id).cloned().unwrap_or(json!("fast"))}))
|
||||
}
|
||||
"turn/start" => {
|
||||
let id = p["threadId"].as_str().unwrap();
|
||||
self.runtime.models.lock().insert(id.into(), p["model"].as_str().unwrap().into());
|
||||
if let Some(tier) = p.get("serviceTier") {
|
||||
self.runtime.tiers.lock().insert(id.into(), tier.clone());
|
||||
}
|
||||
self.runtime.turns.lock().push(p.clone());
|
||||
self.peer
|
||||
.get()
|
||||
.unwrap()
|
||||
.notify(
|
||||
"turn/completed",
|
||||
json!({"threadId":id,
|
||||
"turn":{"id":"t","status":"completed"}}),
|
||||
)
|
||||
.unwrap();
|
||||
Ok(json!({"turn":{"id":"t"}}))
|
||||
}
|
||||
_ => Err((codes::METHOD_NOT_FOUND, method.into())),
|
||||
}
|
||||
}
|
||||
}
|
||||
fn manager(dir: &Path, runtime: Arc<Runtime>) -> AgentManager {
|
||||
let agents = dir.join("agents");
|
||||
crate::provider::set_builtin_command(&agents, None, "codex", Some("/missing/fixture-codex")).unwrap();
|
||||
AgentManager::with_connector(
|
||||
crate::AgentPaths {
|
||||
project_root: dir.into(),
|
||||
store_dir: dir.join("store"),
|
||||
worktrees_dir: dir.join("worktrees"),
|
||||
models_file: dir.join("models.json"),
|
||||
custom_agents_dir: Some(agents),
|
||||
home_dir: Some(dir.into()),
|
||||
env_secrets: None,
|
||||
catalogs: Arc::default(),
|
||||
},
|
||||
tokio::runtime::Handle::current(),
|
||||
Arc::new(move |spec, _, client, _| {
|
||||
assert_eq!(spec.driver, crate::provider::Driver::Codex);
|
||||
let handler = Arc::new(Connection { runtime: runtime.clone(), peer: OnceLock::new() });
|
||||
let (a, b) = tokio::io::duplex(1 << 20);
|
||||
let (r, w) = tokio::io::split(b);
|
||||
let server = Peer::connect_framed(r, w, handler.clone(), Framing::Lines);
|
||||
handler.peer.set(server.clone()).ok().unwrap();
|
||||
runtime.servers.lock().push(server);
|
||||
attach(client, |events| {
|
||||
let (r, w) = tokio::io::split(a);
|
||||
Ok(Peer::connect_framed(r, w, events, Framing::Lines))
|
||||
})
|
||||
}),
|
||||
)
|
||||
}
|
||||
fn prompt() -> AgentPrompt {
|
||||
AgentPrompt { text: "fixture".into(), ..Default::default() }
|
||||
}
|
||||
async fn ready(mgr: &AgentManager, id: &str) {
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
let task = mgr.task(id).unwrap();
|
||||
let (status, busy) = {
|
||||
let s = task.state.lock();
|
||||
(s.task.status, s.busy)
|
||||
};
|
||||
assert_ne!(status, AgentStatus::Failed);
|
||||
if status == AgentStatus::Ready && !busy {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn send(mgr: &AgentManager, id: &str) {
|
||||
mgr.prompt(id, prompt(), false).await.unwrap();
|
||||
ready(mgr, id).await;
|
||||
}
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn explicit_tier_survives_standard_only_reconnect_before_immediate_prompt() {
|
||||
for late_model in [0, 1, 2, 3] {
|
||||
for choice in [Some("true"), Some("false"), None] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let runtime = Arc::new(Runtime::default());
|
||||
let mgr = manager(tmp.path(), runtime.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
provider: "codex".into(),
|
||||
prompt: prompt(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
ready(&mgr, &task.id).await;
|
||||
let catalog_config = mgr.task(&task.id).unwrap().state.lock().task.config.clone();
|
||||
if let Some(value) = choice {
|
||||
mgr.set_config(&task.id, "service_tier", value.into()).await.unwrap();
|
||||
}
|
||||
send(&mgr, &task.id).await;
|
||||
assert_eq!(
|
||||
runtime.turns.lock().last().unwrap().get("serviceTier"),
|
||||
choice.map(|v| json!(if v == "true" { "fast" } else { "default" })).as_ref()
|
||||
);
|
||||
mgr.set_config(&task.id, "model", "b".into()).await.unwrap();
|
||||
assert!(!mgr.task(&task.id).unwrap().state.lock().task.config.iter().any(|o| o.id == "service_tier"));
|
||||
send(&mgr, &task.id).await;
|
||||
assert_eq!(
|
||||
runtime.turns.lock().last().unwrap().get("serviceTier"),
|
||||
choice.map(|_| json!("default")).as_ref()
|
||||
);
|
||||
mgr.shutdown();
|
||||
drop(mgr);
|
||||
runtime.hide_a.store(late_model >= 2, std::sync::atomic::Ordering::SeqCst);
|
||||
let mut mgr = manager(tmp.path(), runtime.clone());
|
||||
send(&mgr, &task.id).await; // Reconnect while still on Standard-only B.
|
||||
assert!(!mgr.task(&task.id).unwrap().state.lock().task.config.iter().any(|o| o.id == "service_tier"));
|
||||
assert_eq!(
|
||||
runtime.turns.lock().last().unwrap().get("serviceTier"),
|
||||
choice.map(|_| json!("default")).as_ref()
|
||||
);
|
||||
if late_model != 0 {
|
||||
// Catalog knows A, but the session's picker has not received it yet.
|
||||
let current = mgr.task(&task.id).unwrap();
|
||||
let mut s = current.state.lock();
|
||||
let catalog = serde_json::from_value(
|
||||
json!({"fingerprint":"fixture", "schema":2, "config":catalog_config, "thoughtLevels":{"a":catalog_config.iter().filter(|o|crate::config::is_per_model_option(o)).collect::<Vec<_>>() }}),
|
||||
)
|
||||
.unwrap();
|
||||
mgr.shared
|
||||
.known
|
||||
.lock()
|
||||
.entry("codex".into())
|
||||
.or_default()
|
||||
.catalogs
|
||||
.insert(mgr.shared.root_key(), catalog);
|
||||
s.task.config.iter_mut().find(|o| o.id == "model").unwrap().values.retain(|v| v.value != "a");
|
||||
}
|
||||
mgr.set_config(&task.id, "model", "a".into()).await.unwrap();
|
||||
if late_model == 3 {
|
||||
// An older saved pending switch has no retained intent field.
|
||||
mgr.task(&task.id).unwrap().state.lock().pending_model.as_mut().unwrap().retained_service_tier = None;
|
||||
mgr.shutdown();
|
||||
mgr = manager(tmp.path(), runtime.clone());
|
||||
}
|
||||
let displayed = mgr
|
||||
.task(&task.id)
|
||||
.unwrap()
|
||||
.state
|
||||
.lock()
|
||||
.snapshot()
|
||||
.config
|
||||
.iter()
|
||||
.find(|o| o.id == "service_tier")
|
||||
.unwrap()
|
||||
.current
|
||||
.clone();
|
||||
assert_eq!(displayed.as_deref(), Some(choice.unwrap_or("true")));
|
||||
send(&mgr, &task.id).await; // No sleeps/retries between selecting A and submitting.
|
||||
assert_eq!(
|
||||
runtime.turns.lock().last().unwrap().get("serviceTier"),
|
||||
choice.map(|v| json!(if v == "true" { "fast" } else { "default" })).as_ref()
|
||||
);
|
||||
let other = mgr
|
||||
.create(NewAgentTask {
|
||||
provider: "codex".into(),
|
||||
prompt: prompt(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
ready(&mgr, &other.id).await;
|
||||
assert!(
|
||||
runtime.turns.lock().last().unwrap().get("serviceTier").is_none(),
|
||||
"choices must not leak to another task"
|
||||
);
|
||||
mgr.shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -110,7 +110,8 @@ for line in sys.stdin:
|
||||
cursor = request['params']['cursor']
|
||||
model = 'one' if cursor is None else 'two'
|
||||
result = {'data': [{'id': model, 'isDefault': cursor is None,
|
||||
'defaultReasoningEffort': 'low', 'supportedReasoningEfforts': [{'reasoningEffort': 'low'}]}],
|
||||
'defaultReasoningEffort': 'low', 'supportedReasoningEfforts': [{'reasoningEffort': 'low'}],
|
||||
'serviceTiers': [{'id': 'fast', 'name': 'Fast', 'description': ''}] if cursor is None else []}],
|
||||
'nextCursor': 'second-page' if cursor is None else None}
|
||||
else:
|
||||
raise RuntimeError('must not create a thread or prompt: ' + method)
|
||||
@@ -125,6 +126,7 @@ for line in sys.stdin:
|
||||
driver: crate::provider::Driver::Codex,
|
||||
command: script.to_string_lossy().into_owned(),
|
||||
args: Vec::new(),
|
||||
additional_args_len: 0,
|
||||
env: Vec::new(),
|
||||
login_hint: String::new(),
|
||||
source: crate::AgentSource::Builtin,
|
||||
@@ -138,6 +140,9 @@ for line in sys.stdin:
|
||||
.collect();
|
||||
assert_eq!(models, ["one", "two"]);
|
||||
assert_eq!(found.levels.keys().map(String::as_str).collect::<Vec<_>>(), ["one", "two"]);
|
||||
assert!(found.config.iter().any(|o| o.id == SERVICE_TIER));
|
||||
assert!(found.levels["one"].iter().any(|o| o.id == SERVICE_TIER));
|
||||
assert!(found.levels["two"].iter().all(|o| o.id != SERVICE_TIER));
|
||||
let requests = std::fs::read_to_string(tmp.path().join("requests")).unwrap();
|
||||
let requests: Vec<Value> = requests.lines().map(|line| serde_json::from_str(line).unwrap()).collect();
|
||||
assert_eq!(
|
||||
@@ -162,6 +167,72 @@ for line in sys.stdin:
|
||||
|
||||
// ---- Pure translations -------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn fast_is_offered_only_when_the_model_advertises_it() {
|
||||
for capability in [
|
||||
json!({ "additionalSpeedTiers": ["fast"] }),
|
||||
json!({ "serviceTiers": [{ "id": "fast", "name": "Fast", "description": "" }] }),
|
||||
json!({ "serviceTiers": [{ "id": "priority", "name": "Fast", "description": "" }] }),
|
||||
] {
|
||||
let mut model = json!({ "id": "supported", "isDefault": true });
|
||||
model.as_object_mut().unwrap().extend(capability.as_object().unwrap().clone());
|
||||
let models = models_of(&json!({ "data": [model, { "id": "unsupported" }] }));
|
||||
let mut settings = Settings::of(&json!({}), &models);
|
||||
let options = config_options(&models, &settings);
|
||||
let fast = options.as_array().unwrap().iter().find(|o| o["id"] == "service_tier").expect("Fast option");
|
||||
assert_eq!(fast["category"], "model_config");
|
||||
assert_eq!(fast["currentValue"], "false");
|
||||
assert!(settings.set(&models, "service_tier", "true").is_ok());
|
||||
assert!(settings.set(&models, "service_tier", "invalid").is_err());
|
||||
let selected = settings.service_tier_override(&models).map(str::to_owned);
|
||||
settings.set(&models, "model", "unsupported").unwrap();
|
||||
assert!(config_options(&models, &settings).as_array().unwrap().iter().all(|o| o["id"] != "service_tier"));
|
||||
assert!(settings.set(&models, "service_tier", "true").is_err());
|
||||
assert_eq!(settings.service_tier_override(&models), Some("default"));
|
||||
settings.set(&models, "model", "supported").unwrap();
|
||||
assert_eq!(settings.service_tier_override(&models), selected.as_deref());
|
||||
let options = config_options(&models, &settings);
|
||||
assert_eq!(
|
||||
options.as_array().unwrap().iter().find(|o| o["id"] == SERVICE_TIER).unwrap()["currentValue"],
|
||||
"true"
|
||||
);
|
||||
}
|
||||
for capability in [json!({}), json!({ "additionalSpeedTiers": [] }), json!({ "serviceTiers": [] })] {
|
||||
let mut model = json!({ "id": "old", "isDefault": true });
|
||||
model.as_object_mut().unwrap().extend(capability.as_object().unwrap().clone());
|
||||
let models = models_of(&json!({ "data": [model] }));
|
||||
let settings = Settings::of(&json!({}), &models);
|
||||
assert!(config_options(&models, &settings).as_array().unwrap().iter().all(|o| o["id"] != "service_tier"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fast_defaults_do_not_become_user_overrides() {
|
||||
let models = models_of(&json!({ "data": [{
|
||||
"id": "m", "isDefault": true, "defaultServiceTier": "fast",
|
||||
"serviceTiers": [{ "id": "fast", "name": "Fast", "description": "" }]
|
||||
}] }));
|
||||
for (reported, current) in [
|
||||
(json!({}), "true"),
|
||||
(json!({ "serviceTier": null }), "false"),
|
||||
(json!({ "serviceTier": "fast" }), "true"),
|
||||
(json!({ "serviceTier": "priority" }), "true"),
|
||||
(json!({ "serviceTier": "default" }), "false"),
|
||||
] {
|
||||
let mut settings = Settings::of(&reported, &models);
|
||||
let options = config_options(&models, &settings);
|
||||
assert_eq!(
|
||||
options.as_array().unwrap().iter().find(|o| o["id"] == SERVICE_TIER).unwrap()["currentValue"],
|
||||
current
|
||||
);
|
||||
assert_eq!(settings.service_tier_override(&models), None);
|
||||
settings.set(&models, SERVICE_TIER, "true").unwrap();
|
||||
assert_eq!(settings.service_tier_override(&models), Some("fast"));
|
||||
settings.set(&models, SERVICE_TIER, "false").unwrap();
|
||||
assert_eq!(settings.service_tier_override(&models), Some("default"));
|
||||
}
|
||||
}
|
||||
|
||||
fn models() -> Vec<ModelInfo> {
|
||||
models_of(&json!({"data": [
|
||||
{"id": "big", "model": "big", "displayName": "Big", "description": "d", "hidden": false, "isDefault": true,
|
||||
@@ -185,6 +256,8 @@ fn settings_follow_the_thread_and_the_models() {
|
||||
Settings {
|
||||
model: "big".into(),
|
||||
effort: Some("low".into()),
|
||||
service_tier: None,
|
||||
fast_override: None,
|
||||
mode: Mode::Ask,
|
||||
collaboration_mode: DEFAULT_COLLABORATION_MODE.into(),
|
||||
collaboration_mode_override: None,
|
||||
@@ -648,6 +721,7 @@ enum Scenario {
|
||||
Steer,
|
||||
Simple,
|
||||
MultiTurn,
|
||||
ServiceTier { first: Option<bool>, second: Option<bool> },
|
||||
Approvals,
|
||||
UsageLimit,
|
||||
Subagent,
|
||||
@@ -666,6 +740,7 @@ impl Scenario {
|
||||
Scenario::Steer => "steer",
|
||||
Scenario::Simple => "simple",
|
||||
Scenario::MultiTurn => "multi_turn",
|
||||
Scenario::ServiceTier { .. } => "multi_turn",
|
||||
Scenario::Approvals => "approvals",
|
||||
Scenario::UsageLimit => "usage_limit",
|
||||
Scenario::Subagent => "subagent",
|
||||
@@ -772,6 +847,16 @@ async fn drive(scenario: Scenario, acp: &Peer, client: &Client, cwd: &str, threa
|
||||
out.push(("effort", request(acp, "session/set_config_option", set(EFFORT, "high")).await));
|
||||
out.push(("second", request(acp, "session/prompt", prompt("Reply with: two")).await));
|
||||
}
|
||||
Scenario::ServiceTier { first, second } => {
|
||||
for (label, choice) in [("first", first), ("second", second)] {
|
||||
if let Some(fast) = choice {
|
||||
request(acp, "session/set_config_option", set(SERVICE_TIER, if fast { "true" } else { "false" }))
|
||||
.await
|
||||
.expect("the model advertises Fast");
|
||||
}
|
||||
out.push((label, request(acp, "session/prompt", prompt("Reply with: hi")).await));
|
||||
}
|
||||
}
|
||||
Scenario::Approvals => {
|
||||
client.answers.lock().extend([Some("accept"), None]);
|
||||
out.push(("prompt", request(acp, "session/prompt", prompt("Run `touch b.txt`, then write a.txt.")).await));
|
||||
@@ -1304,6 +1389,44 @@ fn thread_names_are_the_first_line_of_the_reply() {
|
||||
assert_eq!(thread_name(&"x".repeat(100)).map(|n| n.chars().count()), Some(80));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fast_selection_reaches_the_first_and_next_turn_and_standard_clears_it() {
|
||||
for (first, second, expected) in [
|
||||
(Some(true), Some(false), [Some("fast"), Some("default")]),
|
||||
(Some(false), Some(true), [Some("default"), Some("fast")]),
|
||||
(Some(true), None, [Some("fast"), Some("fast")]),
|
||||
(None, None, [None, None]),
|
||||
] {
|
||||
let scenario = Scenario::ServiceTier { first, second };
|
||||
let mut transcript = load(scenario.file());
|
||||
for (out, frame) in &mut transcript.frames {
|
||||
if *out {
|
||||
continue;
|
||||
}
|
||||
if let Some(models) = frame.pointer_mut("/result/data").and_then(Value::as_array_mut) {
|
||||
for model in models {
|
||||
model["serviceTiers"] = json!([{ "id": "fast", "name": "Fast", "description": "" }]);
|
||||
model["defaultServiceTier"] = json!("fast");
|
||||
}
|
||||
}
|
||||
if frame.pointer("/result/thread").is_some() {
|
||||
frame["result"]["serviceTier"] = json!("fast");
|
||||
}
|
||||
}
|
||||
let (results, _client, frames, _meta, _codex) = replay_transcript(scenario, transcript).await;
|
||||
assert!(result(&results, "first").is_ok());
|
||||
assert!(result(&results, "second").is_ok());
|
||||
let starts = sent(&frames, "turn/start");
|
||||
assert_eq!(starts.len(), 2);
|
||||
for (start, expected) in starts.iter().zip(expected) {
|
||||
assert_eq!(start["params"].get("serviceTier"), expected.map(|value| json!(value)).as_ref());
|
||||
assert!(start["params"].get("serviceTierForTurn").is_none());
|
||||
}
|
||||
assert!(sent(&frames, "turn/settings/update").is_empty());
|
||||
assert!(sent(&frames, "config/value/write").is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn settings_apply_to_the_next_turn() {
|
||||
let (results, client, frames, _) = replay(Scenario::MultiTurn).await;
|
||||
@@ -1891,3 +2014,40 @@ fn workspace_roots_join_the_thread_roots() {
|
||||
apply_thread_config(&json!({ "cwd": "/w/api", "mcpServers": [] }), &mut request);
|
||||
assert!(request.get("runtimeWorkspaceRoots").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_ephemeral_session_starts_an_ephemeral_thread() {
|
||||
for ephemeral in [true, false] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let cwd = tmp.path().to_string_lossy().into_owned();
|
||||
let server = Arc::new(TrustServer {
|
||||
cwd: cwd.clone(),
|
||||
disabled: false,
|
||||
other_project: false,
|
||||
write_error: false,
|
||||
overridden: false,
|
||||
calls: Mutex::default(),
|
||||
});
|
||||
let client = Arc::new(Client::default());
|
||||
let (ours, theirs) = tokio::io::duplex(1 << 16);
|
||||
let (read, write) = tokio::io::split(theirs);
|
||||
let native = Peer::connect_framed(read, write, server.clone(), Framing::Lines);
|
||||
let acp = attach(client.clone(), |events| {
|
||||
let (read, write) = tokio::io::split(ours);
|
||||
Ok(Peer::connect_framed(read, write, events, Framing::Lines))
|
||||
})
|
||||
.unwrap();
|
||||
request(&acp, "initialize", json!({})).await.unwrap();
|
||||
let mut params = json!({"cwd": cwd, "mcpServers": []});
|
||||
if ephemeral {
|
||||
params["_meta"] = json!({"openidea": {"ephemeral": true}});
|
||||
}
|
||||
request(&acp, "session/new", params).await.unwrap();
|
||||
let calls = server.calls.lock();
|
||||
let (_, start) = calls.iter().find(|(m, _)| m == "thread/start").unwrap();
|
||||
assert_eq!(start.get("ephemeral"), ephemeral.then_some(&Value::Bool(true)), "{start}");
|
||||
drop(calls);
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
}
|
||||
@@ -97,6 +97,8 @@ pub(super) struct ModelInfo {
|
||||
/// `(effort, description)`.
|
||||
pub efforts: Vec<(String, String)>,
|
||||
pub default_effort: Option<String>,
|
||||
pub fast_tier: Option<String>,
|
||||
pub default_service_tier: Option<String>,
|
||||
pub is_default: bool,
|
||||
pub hidden: bool,
|
||||
}
|
||||
@@ -123,6 +125,22 @@ pub(super) fn models_of(list: &Value) -> Vec<ModelInfo> {
|
||||
})
|
||||
.collect(),
|
||||
default_effort: str_of(m, "defaultReasoningEffort"),
|
||||
fast_tier: m
|
||||
.get("serviceTiers")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|tier| tier.get("id").and_then(Value::as_str))
|
||||
.chain(
|
||||
m.get("additionalSpeedTiers")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_str),
|
||||
)
|
||||
.find(|tier| is_fast_tier(tier))
|
||||
.map(str::to_owned),
|
||||
default_service_tier: str_of(m, "defaultServiceTier"),
|
||||
is_default: m.get("isDefault").and_then(Value::as_bool) == Some(true),
|
||||
hidden: m.get("hidden").and_then(Value::as_bool) == Some(true),
|
||||
id,
|
||||
@@ -137,6 +155,9 @@ pub(super) struct Settings {
|
||||
/// A model id from `model/list`, or the one the thread reported.
|
||||
pub model: String,
|
||||
pub effort: Option<String>,
|
||||
pub service_tier: Option<String>,
|
||||
/// No choice preserves the runtime's default; false explicitly selects Standard.
|
||||
pub fast_override: Option<bool>,
|
||||
pub mode: Mode,
|
||||
/// Codex's Default/Plan collaboration mode. It is sent with each turn because it is
|
||||
/// part of the turn contract rather than the sandbox permission mode above.
|
||||
@@ -158,6 +179,12 @@ impl Settings {
|
||||
let mut s = Settings {
|
||||
model,
|
||||
effort: str_of(result, "reasoningEffort"),
|
||||
service_tier: match result.get("serviceTier") {
|
||||
// A live thread can explicitly report Standard even when the catalog defaults to Fast.
|
||||
Some(Value::Null) => Some("default".into()),
|
||||
_ => str_of(result, "serviceTier"),
|
||||
},
|
||||
fast_override: None,
|
||||
mode: Mode::of(
|
||||
result.get("approvalPolicy").unwrap_or(&Value::Null),
|
||||
result.get("sandbox").unwrap_or(&Value::Null),
|
||||
@@ -205,6 +232,16 @@ impl Settings {
|
||||
}
|
||||
self.effort = Some(value.to_owned());
|
||||
}
|
||||
SERVICE_TIER => {
|
||||
if !models.iter().any(|m| m.id == self.model && m.fast_tier.is_some()) {
|
||||
return Err(format!("{} has no Fast mode", self.model));
|
||||
}
|
||||
self.fast_override = Some(match value {
|
||||
"true" => true,
|
||||
"false" => false,
|
||||
_ => return Err(format!("unknown Fast mode {value}")),
|
||||
});
|
||||
}
|
||||
MODE => self.mode = Mode::parse(value).ok_or_else(|| format!("unknown mode {value}"))?,
|
||||
COLLABORATION_MODE => {
|
||||
if !matches!(value, DEFAULT_COLLABORATION_MODE | PLAN_COLLABORATION_MODE) {
|
||||
@@ -217,16 +254,32 @@ impl Settings {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `turn/start.serviceTier`: omission inherits; "default" explicitly resets Fast.
|
||||
pub fn service_tier_override<'a>(&self, models: &'a [ModelInfo]) -> Option<&'a str> {
|
||||
match self.fast_override {
|
||||
Some(true) => Some(
|
||||
models.iter().find(|m| m.id == self.model).and_then(|m| m.fast_tier.as_deref()).unwrap_or("default"),
|
||||
),
|
||||
Some(false) => Some("default"),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) const MODEL: &str = "model";
|
||||
pub(super) const EFFORT: &str = "reasoning_effort";
|
||||
pub(super) const SERVICE_TIER: &str = "service_tier";
|
||||
pub(super) const MODE: &str = "mode";
|
||||
pub(super) const COLLABORATION_MODE: &str = "collaboration_mode";
|
||||
pub(super) const DEFAULT_COLLABORATION_MODE: &str = "default";
|
||||
pub(super) const PLAN_COLLABORATION_MODE: &str = "plan";
|
||||
|
||||
/// ACP `configOptions`: model, reasoning effort (for models that have it) and mode.
|
||||
fn is_fast_tier(tier: &str) -> bool {
|
||||
matches!(tier, "fast" | "priority")
|
||||
}
|
||||
|
||||
/// ACP `configOptions`: model, its supported settings and session modes.
|
||||
pub(super) fn config_options(models: &[ModelInfo], s: &Settings) -> Value {
|
||||
let mut model_values: Vec<Value> = models
|
||||
.iter()
|
||||
@@ -253,6 +306,16 @@ pub(super) fn config_options(models: &[ModelInfo], s: &Settings) -> Value {
|
||||
"currentValue": effort, "options": values,
|
||||
}));
|
||||
}
|
||||
if let Some(model) = models.iter().find(|m| m.id == s.model && m.fast_tier.is_some()) {
|
||||
let fast = s.fast_override.unwrap_or_else(|| {
|
||||
s.service_tier.as_deref().or(model.default_service_tier.as_deref()).is_some_and(is_fast_tier)
|
||||
});
|
||||
out.push(json!({
|
||||
"id": SERVICE_TIER, "name": "Fast", "category": "model_config", "type": "select",
|
||||
"currentValue": if fast { "true" } else { "false" },
|
||||
"options": [select_value("false", "Standard", None), select_value("true", "Fast", None)],
|
||||
}));
|
||||
}
|
||||
out.push(json!({
|
||||
"id": MODE, "name": "Mode", "category": "mode", "type": "select", "currentValue": s.mode.id(),
|
||||
"options": Mode::ALL.iter().map(|m| select_value(m.id(), m.name(), Some(m.description()))).collect::<Vec<_>>(),
|
||||
|
||||
@@ -33,6 +33,8 @@ pub(crate) struct ProviderSpec {
|
||||
pub driver: Driver,
|
||||
pub command: String,
|
||||
pub args: Vec<String>,
|
||||
/// Number of trailing arguments added by the built-in agent's settings.
|
||||
pub additional_args_len: usize,
|
||||
pub env: Vec<(String, String)>,
|
||||
/// How to sign in when the agent reports it needs authentication.
|
||||
pub login_hint: String,
|
||||
@@ -96,6 +98,7 @@ fn builtins() -> Vec<ProviderSpec> {
|
||||
driver: *driver,
|
||||
command: cmd[0].into(),
|
||||
args: cmd[1..].iter().map(|a| (*a).to_owned()).collect(),
|
||||
additional_args_len: 0,
|
||||
env: Vec::new(),
|
||||
login_hint: (*hint).into(),
|
||||
source: AgentSource::Builtin,
|
||||
@@ -347,16 +350,28 @@ pub(crate) fn is_unlisted(spec: &ProviderSpec) -> bool {
|
||||
UNLISTED.contains(&spec.id.as_str()) && builtin_spec(&spec.id).as_ref() == Some(spec)
|
||||
}
|
||||
|
||||
fn uses_package_runner(command: &str) -> bool {
|
||||
matches!(command, "npx" | "bunx" | "uvx")
|
||||
}
|
||||
|
||||
fn allows_additional_args(builtin: &ProviderSpec, driver: Driver) -> bool {
|
||||
builtin.driver == Driver::Acp && driver == Driver::Acp && !uses_package_runner(&builtin.command)
|
||||
}
|
||||
|
||||
/// Public launch metadata, keeping the built-in defaults separate from agent-file overrides.
|
||||
pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
let builtin = builtin_spec(&spec.id);
|
||||
let reason = if matches!(spec.source, AgentSource::Registry { .. }) {
|
||||
Some(AgentCommandReadOnlyReason::Registry)
|
||||
} else if let Some(default) = &builtin {
|
||||
matches!(default.command.as_str(), "npx" | "bunx" | "uvx").then_some(AgentCommandReadOnlyReason::PackageRunner)
|
||||
uses_package_runner(&default.command).then_some(AgentCommandReadOnlyReason::PackageRunner)
|
||||
} else {
|
||||
Some(AgentCommandReadOnlyReason::CustomAgent)
|
||||
};
|
||||
let additional_args = builtin
|
||||
.as_ref()
|
||||
.filter(|b| reason.is_none() && allows_additional_args(b, spec.driver))
|
||||
.map(|_| spec.args[spec.args.len() - spec.additional_args_len..].to_vec());
|
||||
AgentProvider {
|
||||
id: spec.id.clone(),
|
||||
name: spec.name.clone(),
|
||||
@@ -366,6 +381,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
.join(" "),
|
||||
program: spec.command.clone(),
|
||||
args: spec.args.clone(),
|
||||
additional_args,
|
||||
default_program: builtin.as_ref().map(|b| b.command.clone()),
|
||||
default_args: builtin.as_ref().map(|b| b.args.clone()).unwrap_or_default(),
|
||||
login_hint: Some(spec.login_hint(&ide_jsonrpc::resolve_spawn_program(&spec.command, &spec.env))),
|
||||
@@ -391,7 +407,24 @@ pub(crate) fn set_builtin_command(
|
||||
command: Option<&str>,
|
||||
) -> IdeResult<()> {
|
||||
update_builtin(custom_dir, secrets, id, |agent, builtin| {
|
||||
agent.command = command.unwrap_or(&builtin.command).to_owned()
|
||||
agent.command = command.unwrap_or(&builtin.command).to_owned();
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Appends arguments to a directly launched built-in ACP agent; an empty list resets them.
|
||||
pub(crate) fn set_builtin_additional_args(
|
||||
custom_dir: &Path,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
id: &str,
|
||||
args: Vec<String>,
|
||||
) -> IdeResult<()> {
|
||||
update_builtin(custom_dir, secrets, id, |agent, builtin| {
|
||||
if !allows_additional_args(builtin, agent.driver) {
|
||||
return Err(IdeError::invalid(format!("{id} does not support additional arguments")));
|
||||
}
|
||||
agent.additional_args = args;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -427,7 +460,10 @@ pub(crate) fn set_builtin_env(
|
||||
return agent.write(&file).map_err(Into::into);
|
||||
}
|
||||
}
|
||||
update_builtin(custom_dir, secrets, id, |agent, _| agent.env = env)
|
||||
update_builtin(custom_dir, secrets, id, |agent, _| {
|
||||
agent.env = env;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Changes built-in `id`'s agent file; a file left with only the built-in's values is removed.
|
||||
@@ -435,7 +471,7 @@ fn update_builtin(
|
||||
custom_dir: &Path,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
id: &str,
|
||||
change: impl FnOnce(&mut CustomAgent, &ProviderSpec),
|
||||
change: impl FnOnce(&mut CustomAgent, &ProviderSpec) -> IdeResult<()>,
|
||||
) -> IdeResult<()> {
|
||||
let Some(builtin) = builtin_spec(id) else {
|
||||
return Err(IdeError::invalid(format!("{id} is not a built-in agent")));
|
||||
@@ -449,6 +485,7 @@ fn update_builtin(
|
||||
driver: builtin.driver,
|
||||
command: builtin.command.clone(),
|
||||
args: builtin.args.clone(),
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: None,
|
||||
}
|
||||
@@ -456,11 +493,12 @@ fn update_builtin(
|
||||
if agent.registry.is_some() {
|
||||
return Err(IdeError::invalid(format!("{id} is installed from the ACP Registry")));
|
||||
}
|
||||
change(&mut agent, &builtin);
|
||||
change(&mut agent, &builtin)?;
|
||||
if agent.command == builtin.command
|
||||
&& agent.name.as_deref() == Some(builtin.name.as_str())
|
||||
&& agent.driver == builtin.driver
|
||||
&& agent.args == builtin.args
|
||||
&& agent.additional_args.is_empty()
|
||||
&& agent.env.is_empty()
|
||||
{
|
||||
match std::fs::remove_file(&file) {
|
||||
@@ -502,6 +540,7 @@ pub(crate) fn save_custom(
|
||||
driver: Driver::Acp,
|
||||
command: input.command.clone(),
|
||||
args: input.args.clone(),
|
||||
additional_args: Vec::new(),
|
||||
env: input.env.clone(),
|
||||
registry: None,
|
||||
}
|
||||
@@ -572,6 +611,7 @@ pub(crate) fn import_acp(
|
||||
driver: Driver::Acp,
|
||||
command: server.command,
|
||||
args: server.args,
|
||||
additional_args: Vec::new(),
|
||||
env: server.env,
|
||||
registry: None,
|
||||
}
|
||||
@@ -615,6 +655,9 @@ pub(crate) struct CustomAgent {
|
||||
pub command: String,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub args: Vec<String>,
|
||||
/// Kept separate from `args` so Settings reset does not erase a hand-written launch line.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub additional_args: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Set when the agent was installed from the ACP Registry.
|
||||
@@ -746,6 +789,7 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
driver: agent.driver,
|
||||
command: agent.command,
|
||||
args: agent.args,
|
||||
additional_args_len: 0,
|
||||
env,
|
||||
login_hint: "Sign in with the agent's own command line first.".into(),
|
||||
source,
|
||||
@@ -763,6 +807,10 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
spec.args = crate::native::copilot::headless_args(&spec.args);
|
||||
}
|
||||
if spec.source == AgentSource::Custom {
|
||||
if allows_additional_args(existing, spec.driver) {
|
||||
spec.additional_args_len = agent.additional_args.len();
|
||||
spec.args.extend(agent.additional_args);
|
||||
}
|
||||
spec.source = AgentSource::Builtin;
|
||||
}
|
||||
*existing = spec;
|
||||
@@ -1043,6 +1091,53 @@ mod tests {
|
||||
set_builtin_env(dir.path(), None, "not-a-builtin", env).unwrap_err();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn additional_args_append_and_reset_without_replacing_agent_file_overrides() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let omp = || load(Some(root), None).into_iter().find(|spec| spec.id == "omp").unwrap();
|
||||
assert_eq!(describe(&omp()).additional_args, Some(vec![]));
|
||||
set_builtin_additional_args(root, None, "omp", vec!["--extra".into()]).unwrap();
|
||||
assert_eq!(omp().args, ["acp", "--extra"]);
|
||||
set_builtin_additional_args(root, None, "omp", vec![]).unwrap();
|
||||
assert!(!root.join("omp.toml").exists());
|
||||
|
||||
let file = root.join("omp.toml");
|
||||
std::fs::write(
|
||||
&file,
|
||||
"name = \"My OMP\"\ncommand = \"/opt/my tools/omp\"\nargs = [\"acp\", \"--manual\"]\n[env]\nKEEP = \"value\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
let original = omp();
|
||||
let extra = vec!["--label".into(), "two words".into(), String::new()];
|
||||
set_builtin_additional_args(root, None, "omp", extra.clone()).unwrap();
|
||||
let configured = omp();
|
||||
assert_eq!(configured.args, ["acp", "--manual", "--label", "two words", ""]);
|
||||
assert_eq!(describe(&configured).additional_args, Some(extra));
|
||||
set_builtin_additional_args(root, None, "omp", vec![]).unwrap();
|
||||
assert_eq!(omp(), original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn additional_args_cannot_modify_managed_or_non_acp_launches() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::write(
|
||||
root.join("gemini.toml"),
|
||||
"command = \"gemini\"\nargs = [\"--experimental-acp\"]\n[registry]\nid = \"gemini\"\nversion = \"1\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(root.join("mine.toml"), "command = \"mine\"\n").unwrap();
|
||||
std::fs::write(root.join("omp.toml"), "command = \"omp\"\ndriver = \"codex\"\n").unwrap();
|
||||
let before = load(Some(root), None);
|
||||
for id in ["gemini", "mine", "omp", "codex", "claude-acp"] {
|
||||
let spec = before.iter().find(|spec| spec.id == id).unwrap();
|
||||
assert!(describe(spec).additional_args.is_none());
|
||||
assert!(set_builtin_additional_args(root, None, id, vec!["--extra".into()]).is_err());
|
||||
}
|
||||
assert_eq!(load(Some(root), None), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_copilot_allows_only_the_github_account_override() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
@@ -1052,6 +1147,7 @@ mod tests {
|
||||
driver: Driver::Acp,
|
||||
command: "/tools/copilot".into(),
|
||||
args: vec!["--acp".into()],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::from([("REGISTRY_SETTING".into(), "kept".into())]),
|
||||
registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.0".into() }),
|
||||
}
|
||||
@@ -1108,6 +1204,7 @@ mod tests {
|
||||
driver: Driver::Acp,
|
||||
command: "amp".into(),
|
||||
args: vec![],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: Some(RegistryRef { id: "amp-acp".into(), version: "1.0.0".into() }),
|
||||
}
|
||||
@@ -1133,6 +1230,7 @@ mod tests {
|
||||
driver: Driver::Claude,
|
||||
command: "/old/claude".into(),
|
||||
args: vec![],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: None,
|
||||
};
|
||||
@@ -1186,6 +1284,7 @@ mod tests {
|
||||
driver: Driver::Acp,
|
||||
command: "/data/agents/tools/amp-acp/0.10.0/amp-acp".into(),
|
||||
args: vec!["acp".into()],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::from([("K".to_owned(), "v".to_owned())]),
|
||||
registry: Some(RegistryRef { id: "amp-acp".into(), version: "0.10.0".into() }),
|
||||
};
|
||||
|
||||
@@ -443,7 +443,15 @@ fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
|
||||
|
||||
/// Installs (or updates to) the registry's current version of `id`, streaming progress
|
||||
/// through `emit`, and points the agent file at it.
|
||||
pub fn install(paths: &RegistryPaths, id: &str, cancel: &CancellationToken, emit: Emit) -> IdeResult<()> {
|
||||
/// Installs agent `id`; an npm package retries against the public npm registry when the
|
||||
/// configured one misses it only with `public_npm_fallback`.
|
||||
pub fn install(
|
||||
paths: &RegistryPaths,
|
||||
id: &str,
|
||||
public_npm_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
let id = canonical_id(id);
|
||||
// The saved index is what the user picked from; fetch only when there is none.
|
||||
let text = match fs::read_to_string(&paths.cache_file) {
|
||||
@@ -455,9 +463,14 @@ pub fn install(paths: &RegistryPaths, id: &str, cancel: &CancellationToken, emit
|
||||
.iter()
|
||||
.find(|e| e.id == id)
|
||||
.ok_or_else(|| IdeError::not_found(format!("{id} is not in the ACP Registry")))?;
|
||||
install_entry(paths, entry, Platform::current(), &on_path, cancel, emit)
|
||||
let npm_installer =
|
||||
move |p: &Package, entry: &Entry, dir: &Path, platform, cancel: &CancellationToken, emit: Emit| {
|
||||
install_npm(p, entry, dir, platform, public_npm_fallback, cancel, emit)
|
||||
};
|
||||
install_entry_with(paths, entry, Platform::current(), &on_path, &npm_installer, cancel, emit)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn install_entry(
|
||||
paths: &RegistryPaths,
|
||||
entry: &Entry,
|
||||
@@ -466,7 +479,10 @@ fn install_entry(
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
install_entry_with(paths, entry, platform, on_path, &install_npm, cancel, emit)
|
||||
let npm_installer = |p: &Package, entry: &Entry, dir: &Path, platform, cancel: &CancellationToken, emit: Emit| {
|
||||
install_npm(p, entry, dir, platform, true, cancel, emit)
|
||||
};
|
||||
install_entry_with(paths, entry, platform, on_path, &npm_installer, cancel, emit)
|
||||
}
|
||||
|
||||
type NpmInstaller = dyn Fn(&Package, &Entry, &Path, Platform, &CancellationToken, Emit) -> IdeResult<PathBuf>;
|
||||
@@ -550,6 +566,7 @@ fn install_entry_with(
|
||||
driver: Driver::Acp,
|
||||
command: exe.to_string_lossy().into_owned(),
|
||||
args,
|
||||
additional_args: Vec::new(),
|
||||
env,
|
||||
registry: Some(RegistryRef { id: entry.id.clone(), version: entry.version.clone() }),
|
||||
};
|
||||
@@ -662,20 +679,23 @@ fn install_npm(
|
||||
entry: &Entry,
|
||||
dir: &Path,
|
||||
platform: Platform,
|
||||
public_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
let (name, _) = split_npm_spec(&p.package);
|
||||
let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?;
|
||||
install_npm_with(&npm, p, entry, dir, platform, cancel, emit)
|
||||
install_npm_with(&npm, p, entry, dir, platform, public_fallback, cancel, emit)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn install_npm_with(
|
||||
npm: &Path,
|
||||
p: &Package,
|
||||
entry: &Entry,
|
||||
dir: &Path,
|
||||
platform: Platform,
|
||||
public_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
@@ -703,6 +723,7 @@ fn install_npm_with(
|
||||
},
|
||||
&specs,
|
||||
false,
|
||||
public_fallback,
|
||||
cancel,
|
||||
emit,
|
||||
)?;
|
||||
@@ -941,6 +962,7 @@ mod tests {
|
||||
driver: Driver::Acp,
|
||||
command: "/x".into(),
|
||||
args: vec![],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: Some(RegistryRef { id: id.into(), version: version.into() }),
|
||||
};
|
||||
@@ -1002,7 +1024,7 @@ mod tests {
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss() {
|
||||
fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss_unless_registries_are_configured_only() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let install_dir = dir.path().join("acme/1.2.0");
|
||||
fs::create_dir_all(&install_dir).unwrap();
|
||||
@@ -1041,8 +1063,8 @@ esac
|
||||
]}"#;
|
||||
let entry = parse(index).unwrap().remove(0);
|
||||
let pkg = entry.distribution.npx.as_ref().unwrap();
|
||||
let exe =
|
||||
install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
let exe = install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, true, &CancellationToken::new(), &|_| {})
|
||||
.unwrap();
|
||||
let calls: Vec<String> = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect();
|
||||
assert_eq!(calls.len(), 2, "{calls:?}");
|
||||
assert!(!calls[0].contains("--registry="), "{calls:?}");
|
||||
@@ -1050,6 +1072,15 @@ esac
|
||||
assert!(calls[1].contains("--@acme:registry=https://registry.npmjs.org/"), "{calls:?}");
|
||||
assert_eq!(exe, install_dir.join("node_modules/.bin/agent-acp"));
|
||||
assert!(exe.is_file());
|
||||
// Only the configured registries: the miss is the error, and npmjs is never asked.
|
||||
let only = dir.path().join("acme-only/1.2.0");
|
||||
fs::create_dir_all(&only).unwrap();
|
||||
let err =
|
||||
install_npm_with(&npm, pkg, &entry, &only, MAC_ARM, false, &CancellationToken::new(), &|_| {}).unwrap_err();
|
||||
let calls: Vec<String> = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect();
|
||||
assert_eq!(calls.len(), 3, "{calls:?}");
|
||||
assert!(!calls[2].contains("--registry="), "{calls:?}");
|
||||
assert!(err.message.contains("notarget"), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1168,6 +1199,7 @@ esac
|
||||
driver: Driver::Acp,
|
||||
command: "/data/tools/copilot/1.0.104/node_modules/.bin/copilot".into(),
|
||||
args: vec!["--acp".into()],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.104".into() }),
|
||||
}
|
||||
|
||||
@@ -177,6 +177,9 @@ impl Handler for FakeAgent {
|
||||
})
|
||||
.unwrap_or_default();
|
||||
self.mcp_calls.lock().push((method.to_owned(), names));
|
||||
if params.pointer("/_meta/openidea/ephemeral") == Some(&json!(true)) {
|
||||
self.calls.lock().push("ephemeral".into());
|
||||
}
|
||||
}
|
||||
let session = params.get("sessionId").and_then(Value::as_str).unwrap_or("s1").to_owned();
|
||||
match method {
|
||||
@@ -648,6 +651,32 @@ async fn saved_conversation_reads_do_not_start_or_load_the_agent() {
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_ephemeral_task_is_not_saved_and_asks_for_an_unsaved_session() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
for ephemeral in [true, false] {
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("Write a commit message"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
ephemeral,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
assert_eq!(agent.calls.lock().iter().any(|c| c == "ephemeral"), ephemeral);
|
||||
mgr.shutdown();
|
||||
// The caller never deleted it (its window closed): only a saved task comes back.
|
||||
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
assert_eq!(restored.task(&task.id).is_ok(), !ephemeral);
|
||||
restored.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn claude_commands_share_catalog_discovery_and_persist_results() {
|
||||
@@ -3173,6 +3202,46 @@ async fn rapid_idle_model_switches_share_discovery_and_never_apply_a_stale_compl
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn explicit_service_tier_reaches_the_session_even_when_it_matches_the_reported_default() {
|
||||
for value in [None, Some("false"), Some("true")] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
*agent.extra_options.lock() = vec![json!({
|
||||
"id": "service_tier", "name": "Fast", "category": "model_config", "type": "select",
|
||||
"currentValue": value.unwrap_or("true"),
|
||||
"options": [{"value": "false"}, {"value": "true"}]
|
||||
})];
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("again"),
|
||||
provider: "codex".into(),
|
||||
config: value
|
||||
.map(|value| vec![AgentConfigChoice { id: "service_tier".into(), value: value.into() }])
|
||||
.unwrap_or_default(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let calls = agent.calls.lock();
|
||||
let prompt = calls.iter().position(|call| call == "session/prompt").unwrap();
|
||||
if let Some(value) = value {
|
||||
let setting = calls
|
||||
.iter()
|
||||
.position(|call| call == &format!("session/set_config_option \"{value}\""))
|
||||
.expect("an explicit tier must not be mistaken for an inherited default");
|
||||
assert!(setting < prompt);
|
||||
} else {
|
||||
assert!(!calls.iter().any(|call| call == "session/set_config_option"));
|
||||
}
|
||||
drop(calls);
|
||||
mgr.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn upfront_effort_is_validated_after_changing_model_before_the_prompt() {
|
||||
for (effort, applied) in [("medium", true), ("high", false)] {
|
||||
@@ -5549,6 +5618,7 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
|
||||
mcp_overrides: BTreeMap::from([("slack".into(), false)]),
|
||||
idle: false,
|
||||
skill_overrides: BTreeMap::new(),
|
||||
ephemeral: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -5611,6 +5681,7 @@ async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idl
|
||||
("tdd".into(), AgentSkillMode::Auto),
|
||||
("noisy".into(), AgentSkillMode::Off),
|
||||
]),
|
||||
ephemeral: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -5754,6 +5825,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
idle: false,
|
||||
skill_overrides: BTreeMap::new(),
|
||||
ephemeral: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -5780,6 +5852,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
idle: false,
|
||||
skill_overrides: BTreeMap::new(),
|
||||
ephemeral: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -9,6 +9,7 @@ mod modules;
|
||||
mod parse;
|
||||
mod single;
|
||||
mod structure;
|
||||
mod tsc_watch;
|
||||
mod up_to_date;
|
||||
|
||||
pub use fingerprint::{LaunchFingerprint, launch_fingerprint, menu_fingerprint};
|
||||
@@ -23,6 +24,7 @@ pub use structure::{
|
||||
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
|
||||
structure_outputs, structure_plan, structure_war_plan, structure_web_artifacts,
|
||||
};
|
||||
pub use tsc_watch::{tsc_watch, tsc_watch_roots};
|
||||
pub use up_to_date::{menu_up_to_date, record_menu_build};
|
||||
|
||||
use crate::process::{self, Stream};
|
||||
@@ -812,6 +814,11 @@ pub fn run(
|
||||
|
||||
/// Per-file editor / Problems diagnostics of the messages that have a position.
|
||||
pub fn diagnostics(messages: &[BuildMessage]) -> BTreeMap<PathBuf, Vec<Diagnostic>> {
|
||||
diagnostics_from(messages, DIAGNOSTICS_SOURCE)
|
||||
}
|
||||
|
||||
/// [`diagnostics`] reported by `source`.
|
||||
pub fn diagnostics_from(messages: &[BuildMessage], source: &str) -> BTreeMap<PathBuf, Vec<Diagnostic>> {
|
||||
let mut out: BTreeMap<PathBuf, Vec<Diagnostic>> = BTreeMap::new();
|
||||
for m in messages {
|
||||
let (Some(path), Some(range)) = (&m.path, m.range) else { continue };
|
||||
@@ -819,11 +826,11 @@ pub fn diagnostics(messages: &[BuildMessage]) -> BTreeMap<PathBuf, Vec<Diagnosti
|
||||
range,
|
||||
severity: m.severity,
|
||||
message: m.text.clone(),
|
||||
source: Some(DIAGNOSTICS_SOURCE.to_owned()),
|
||||
source: Some(source.to_owned()),
|
||||
code: m.code.clone(),
|
||||
unnecessary: false,
|
||||
deprecated: false,
|
||||
server: Some(DIAGNOSTICS_SOURCE.to_owned()),
|
||||
server: Some(source.to_owned()),
|
||||
});
|
||||
}
|
||||
out
|
||||
|
||||
@@ -0,0 +1,450 @@
|
||||
//! Problems › TypeScript project errors: the project's own `tsc --watch` on each root
|
||||
//! `tsconfig.json`, its output parsed like Build's tsc step, one compilation at a time.
|
||||
//!
|
||||
//! A background check never writes into the project. A plain project runs `tsc --noEmit -p`
|
||||
//! with its `.tsbuildinfo` (written by `composite` / `incremental` even without emit) moved to a
|
||||
//! scratch folder. `tsc -b` cannot check without emitting (`--noEmit` fails with TS6310 on
|
||||
//! composite references), and plain `tsc -p` on a project with references needs their built
|
||||
//! `.d.ts` (TS6305). So a solution runs `tsc -b` on scratch copies of its configurations: each
|
||||
//! `extends` the real one and only sends the outputs and `.tsbuildinfo` to the scratch folder,
|
||||
//! keeping every option, file list and source position of the project.
|
||||
|
||||
use super::parse::{Format, OutputParser, RawMessage};
|
||||
use super::{BuildMessage, Lines, PathMap, resolve};
|
||||
use crate::process;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
// ponytail: one `tsc` per root; past this the shallowest roots win. Raise it, or watch
|
||||
// on demand, if monorepos without a solution tsconfig need more.
|
||||
const MAX_ROOTS: usize = 8;
|
||||
|
||||
/// The configurations among `found` (the `tsconfig.json` files of the project) that no other
|
||||
/// one references: the ones a watcher runs on. Referenced projects are checked by their solution.
|
||||
pub fn tsc_watch_roots(found: Vec<PathBuf>) -> Vec<PathBuf> {
|
||||
let referenced: BTreeSet<PathBuf> = found.iter().flat_map(|c| references(c)).collect();
|
||||
let mut roots: Vec<PathBuf> = found.into_iter().filter(|c| !referenced.contains(c)).collect();
|
||||
roots.sort_by_key(|c| (c.components().count(), c.clone()));
|
||||
roots.truncate(MAX_ROOTS);
|
||||
roots
|
||||
}
|
||||
|
||||
fn read_json(path: &Path) -> Option<Value> {
|
||||
let text = std::fs::read_to_string(path).ok()?;
|
||||
serde_json::from_str(&ide_core::jsonc::strip(&text)).ok()
|
||||
}
|
||||
|
||||
/// The configurations `config` lists in `references` (a folder means its `tsconfig.json`).
|
||||
fn references(config: &Path) -> Vec<PathBuf> {
|
||||
let Some(json) = read_json(config) else { return Vec::new() };
|
||||
let dir = config.parent().unwrap_or(Path::new(""));
|
||||
let refs = json.get("references").and_then(|r| r.as_array()).into_iter().flatten();
|
||||
refs.filter_map(|r| r.get("path")?.as_str())
|
||||
.map(|p| {
|
||||
let p = super::normalize(&dir.join(p));
|
||||
if p.extension().is_some_and(|e| e == "json") { p } else { p.join("tsconfig.json") }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A configuration and the ones it `extends`, most derived first, each with its folder (the
|
||||
/// base of its relative paths). A package base (`@tsconfig/node20/tsconfig.json`) is looked up
|
||||
/// in `node_modules` above the configuration.
|
||||
fn chain(config: &Path) -> Vec<(PathBuf, Value)> {
|
||||
let mut out = Vec::new();
|
||||
let mut next = vec![config.to_path_buf()];
|
||||
// A cycle or a deep chain ends here.
|
||||
while let Some(path) = next.pop().filter(|_| out.len() < 16) {
|
||||
let Some(json) = read_json(&path) else { continue };
|
||||
let dir = path.parent().unwrap_or(Path::new("")).to_path_buf();
|
||||
let bases: Vec<String> = match json.get("extends") {
|
||||
Some(Value::String(s)) => vec![s.clone()],
|
||||
Some(Value::Array(a)) => a.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
// Later bases override earlier ones: visit them first.
|
||||
next.extend(bases.iter().filter_map(|b| resolve_base(&dir, b)));
|
||||
out.push((dir, json));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn resolve_base(dir: &Path, base: &str) -> Option<PathBuf> {
|
||||
let with_json = |p: PathBuf| {
|
||||
if p.is_dir() {
|
||||
p.join("tsconfig.json")
|
||||
} else if p.extension().is_some_and(|e| e == "json") {
|
||||
p
|
||||
} else {
|
||||
let mut s = p.into_os_string();
|
||||
s.push(".json");
|
||||
PathBuf::from(s)
|
||||
}
|
||||
};
|
||||
if base.starts_with('.') || Path::new(base).is_absolute() {
|
||||
return Some(with_json(super::normalize(&dir.join(base))));
|
||||
}
|
||||
dir.ancestors().map(|a| with_json(a.join("node_modules").join(base))).find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// The first value of `key` (a top-level key, or `compilerOptions.<key>`) along `chain`, with the
|
||||
/// folder it is relative to.
|
||||
fn lookup<'a>(chain: &'a [(PathBuf, Value)], key: &str) -> Option<(&'a Path, &'a Value)> {
|
||||
chain.iter().find_map(|(dir, json)| {
|
||||
let value = match key.strip_prefix("compilerOptions.") {
|
||||
Some(option) => json.get("compilerOptions")?.get(option)?,
|
||||
None => json.get(key)?,
|
||||
};
|
||||
Some((dir.as_path(), value))
|
||||
})
|
||||
}
|
||||
|
||||
/// The scratch copy of `config` for `tsc -b`: the real configuration with its outputs and
|
||||
/// `.tsbuildinfo` in `scratch` (file `<n>`), referencing the scratch copies `refs`. Settings that
|
||||
/// default relative to the configuration's own folder are spelled out, since the copy lives
|
||||
/// elsewhere: the files (`**/*`), their exclusions (`node_modules`, the output folder) and the
|
||||
/// `rootDir` of a composite project.
|
||||
fn scratch_config(config: &Path, scratch: &Path, n: usize, refs: &[PathBuf]) -> Value {
|
||||
let chain = chain(config);
|
||||
let dir = config.parent().unwrap_or(Path::new(""));
|
||||
let out = scratch.join(n.to_string());
|
||||
let mut options = json!({ "outDir": out, "tsBuildInfoFile": scratch.join(format!("{n}.tsbuildinfo")) });
|
||||
if lookup(&chain, "compilerOptions.declarationDir").is_some() {
|
||||
options["declarationDir"] = json!(out);
|
||||
}
|
||||
if lookup(&chain, "compilerOptions.outFile").is_some() {
|
||||
options["outFile"] = json!(out.join("out.js"));
|
||||
}
|
||||
if lookup(&chain, "compilerOptions.composite").is_some_and(|(_, v)| v == &json!(true))
|
||||
&& lookup(&chain, "compilerOptions.rootDir").is_none()
|
||||
{
|
||||
options["rootDir"] = json!(dir);
|
||||
}
|
||||
let mut copy = json!({
|
||||
"extends": config,
|
||||
"compilerOptions": options,
|
||||
"references": refs.iter().map(|r| json!({ "path": r })).collect::<Vec<_>>(),
|
||||
});
|
||||
if lookup(&chain, "include").is_none() && lookup(&chain, "files").is_none() {
|
||||
copy["include"] = json!([dir.join("**/*")]);
|
||||
}
|
||||
if lookup(&chain, "exclude").is_none() {
|
||||
let mut exclude = vec![dir.join("node_modules")];
|
||||
if let Some((base, Value::String(out_dir))) = lookup(&chain, "compilerOptions.outDir") {
|
||||
exclude.push(super::normalize(&base.join(out_dir)));
|
||||
}
|
||||
copy["exclude"] = json!(exclude);
|
||||
}
|
||||
copy
|
||||
}
|
||||
|
||||
/// The `tsc` arguments that watch `config` without writing into the project, writing the
|
||||
/// scratch configurations a solution needs into `scratch`.
|
||||
fn watch_args(config: &Path, scratch: &Path) -> std::io::Result<Vec<String>> {
|
||||
let path = |p: &Path| p.to_string_lossy().into_owned();
|
||||
let mut args: Vec<String> = if references(config).is_empty() {
|
||||
let name = config.file_name().map_or_else(|| "tsconfig.json".into(), |n| n.to_string_lossy().into_owned());
|
||||
let info = path(&scratch.join("tsconfig.tsbuildinfo"));
|
||||
["--noEmit", "-p", &name, "--incremental", "--tsBuildInfoFile", &info].map(String::from).to_vec()
|
||||
} else {
|
||||
// Every configuration the solution reaches gets a number: the solution 0, then in order.
|
||||
let mut numbers: BTreeMap<PathBuf, usize> = BTreeMap::from([(config.to_path_buf(), 0)]);
|
||||
let mut queue = vec![config.to_path_buf()];
|
||||
let mut i = 0;
|
||||
while i < queue.len() {
|
||||
let current = queue[i].clone();
|
||||
let refs: Vec<PathBuf> = references(¤t)
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let next = numbers.len();
|
||||
let n = *numbers.entry(r.clone()).or_insert_with(|| {
|
||||
queue.push(r);
|
||||
next
|
||||
});
|
||||
scratch.join(format!("{n}.json"))
|
||||
})
|
||||
.collect();
|
||||
let copy = scratch_config(¤t, scratch, numbers[¤t], &refs);
|
||||
std::fs::write(scratch.join(format!("{}.json", numbers[¤t])), copy.to_string())?;
|
||||
i += 1;
|
||||
}
|
||||
vec!["-b".into(), path(&scratch.join("0.json"))]
|
||||
};
|
||||
args.extend(["--watch", "--pretty", "false", "--preserveWatchOutput"].map(String::from));
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
/// The project's own `tsc` (`node_modules/.bin` from the configuration's folder up to `root`).
|
||||
fn local_tsc(root: &Path, dir: &Path) -> Option<PathBuf> {
|
||||
dir.ancestors()
|
||||
.take_while(|d| d.starts_with(root))
|
||||
.find_map(|d| ide_core::tool_path::find_command("tsc", d.join("node_modules/.bin").as_os_str(), dir))
|
||||
}
|
||||
|
||||
/// The messages of one compilation at a time: tsc ends each with
|
||||
/// `… - Found 2 errors. Watching for file changes.` `tsc -b` reports the errors of every
|
||||
/// project of the solution that has some, rebuilt this time or not ("out of date because it had
|
||||
/// errors"), so each compilation's list replaces the last.
|
||||
#[derive(Default)]
|
||||
struct Compilations {
|
||||
parser: Option<OutputParser>,
|
||||
raws: Vec<RawMessage>,
|
||||
}
|
||||
|
||||
impl Compilations {
|
||||
fn feed(&mut self, line: &str) -> Option<Vec<RawMessage>> {
|
||||
let parser = self.parser.get_or_insert_with(|| OutputParser::new(Format::Tsc));
|
||||
if line.contains("Watching for file changes.") {
|
||||
self.raws.extend(parser.finish());
|
||||
return Some(std::mem::take(&mut self.raws));
|
||||
}
|
||||
self.raws.extend(parser.feed(line).messages);
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// A scratch folder of this process for `config`, removed when dropped.
|
||||
struct Scratch(PathBuf);
|
||||
|
||||
impl Scratch {
|
||||
fn new(config: &Path) -> std::io::Result<Self> {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut hash = std::collections::hash_map::DefaultHasher::new();
|
||||
config.hash(&mut hash);
|
||||
let dir = std::env::temp_dir().join("openidea-tsc-watch").join(format!(
|
||||
"{}-{:016x}",
|
||||
std::process::id(),
|
||||
hash.finish()
|
||||
));
|
||||
// Fresh: a `.tsbuildinfo` left by an earlier run would make tsc skip unchanged projects.
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
Ok(Scratch(dir))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Scratch {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the project's `tsc --watch` on `config` until `cancel` fires or tsc exits, handing the
|
||||
/// messages of every finished compilation (all of them, an empty list when it passes) to
|
||||
/// `on_compilation`. Not found when the project has no TypeScript of its own.
|
||||
pub fn tsc_watch(
|
||||
root: &Path,
|
||||
config: &Path,
|
||||
cancel: &CancellationToken,
|
||||
mut on_compilation: impl FnMut(Vec<BuildMessage>),
|
||||
) -> IdeResult<()> {
|
||||
let dir = config.parent().ok_or_else(|| IdeError::invalid("no tsconfig folder"))?;
|
||||
let tsc = local_tsc(root, dir).ok_or_else(|| IdeError::not_found("no local typescript"))?;
|
||||
let scratch = Scratch::new(config)?;
|
||||
let args = watch_args(config, &scratch.0)?;
|
||||
let paths = PathMap::new(root);
|
||||
let mut compilations = Compilations::default();
|
||||
let program = tsc.to_string_lossy();
|
||||
process::run_bounded(&program, &args, dir, &BTreeMap::new(), cancel, |_, line| {
|
||||
if let Some(raws) = compilations.feed(line) {
|
||||
// Fresh file texts each time: the files changed since the last compilation.
|
||||
let mut lines = Lines::default();
|
||||
on_compilation(raws.into_iter().map(|r| resolve(r, dir, &paths, &mut lines)).collect());
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn write(dir: &Path, rel: &str, text: &str) {
|
||||
let p = dir.join(rel);
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(p, text).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roots_are_the_configurations_no_other_one_references() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
// A solution with references (one by folder, one by file), plus an unrelated package.
|
||||
write(
|
||||
root,
|
||||
"tsconfig.json",
|
||||
r#"{ "files": [], // solution
|
||||
"references": [{ "path": "./packages/a" }, { "path": "packages/b/tsconfig.json" },] }"#,
|
||||
);
|
||||
write(root, "packages/a/tsconfig.json", r#"{"compilerOptions": {"composite": true}}"#);
|
||||
write(root, "packages/b/tsconfig.json", r#"{"compilerOptions": {"composite": true}}"#);
|
||||
write(root, "tools/cli/tsconfig.json", "{}");
|
||||
let found = ["tools/cli", "packages/b", "", "packages/a"].map(|d| root.join(d).join("tsconfig.json"));
|
||||
assert_eq!(tsc_watch_roots(found.to_vec()), [root.join("tsconfig.json"), root.join("tools/cli/tsconfig.json")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_solution_is_checked_through_scratch_copies_of_its_configurations() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (root, scratch) = (tmp.path().join("p"), tmp.path().join("scratch"));
|
||||
std::fs::create_dir_all(&scratch).unwrap();
|
||||
write(
|
||||
&root,
|
||||
"tsconfig.json",
|
||||
r#"{"files": [], "references": [{"path": "./packages/a"}, {"path": "./packages/b"}]}"#,
|
||||
);
|
||||
// a: composite, every setting by default.
|
||||
write(&root, "packages/a/tsconfig.json", r#"{"compilerOptions": {"composite": true}}"#);
|
||||
// b: references a, settles its files, outputs and root in a shared base.
|
||||
write(
|
||||
&root,
|
||||
"packages/b/tsconfig.json",
|
||||
r#"{"extends": "../../tsconfig.base", "references": [{"path": "../a"}], "compilerOptions": {"outFile": "b.js"}}"#,
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"tsconfig.base.json",
|
||||
r#"{"compilerOptions": {"composite": true, "rootDir": ".", "outDir": "dist", "declarationDir": "types"},
|
||||
"include": ["packages/*/src"]}"#,
|
||||
);
|
||||
let args = watch_args(&root.join("tsconfig.json"), &scratch).unwrap();
|
||||
let s = |p: &str| scratch.join(p).to_string_lossy().into_owned();
|
||||
assert_eq!(args, ["-b", &s("0.json"), "--watch", "--pretty", "false", "--preserveWatchOutput"]);
|
||||
let copy = |n: usize| read_json(&scratch.join(format!("{n}.json"))).unwrap();
|
||||
let path = |p: &Path| json!(p);
|
||||
assert_eq!(
|
||||
copy(0),
|
||||
json!({
|
||||
"extends": path(&root.join("tsconfig.json")),
|
||||
"compilerOptions": {"outDir": path(&scratch.join("0")), "tsBuildInfoFile": s("0.tsbuildinfo")},
|
||||
"references": [{"path": s("1.json")}, {"path": s("2.json")}],
|
||||
"exclude": [path(&root.join("node_modules"))],
|
||||
})
|
||||
);
|
||||
let a = root.join("packages/a");
|
||||
assert_eq!(
|
||||
copy(1),
|
||||
json!({
|
||||
"extends": path(&a.join("tsconfig.json")),
|
||||
"compilerOptions": {
|
||||
"outDir": path(&scratch.join("1")), "tsBuildInfoFile": s("1.tsbuildinfo"), "rootDir": path(&a),
|
||||
},
|
||||
"references": [],
|
||||
"include": [path(&a.join("**/*"))],
|
||||
"exclude": [path(&a.join("node_modules"))],
|
||||
})
|
||||
);
|
||||
let b = root.join("packages/b");
|
||||
assert_eq!(
|
||||
copy(2),
|
||||
json!({
|
||||
"extends": path(&b.join("tsconfig.json")),
|
||||
"compilerOptions": {
|
||||
"outDir": path(&scratch.join("2")), "tsBuildInfoFile": s("2.tsbuildinfo"),
|
||||
"declarationDir": path(&scratch.join("2")), "outFile": path(&scratch.join("2/out.js")),
|
||||
},
|
||||
"references": [{"path": s("1.json")}],
|
||||
"exclude": [path(&b.join("node_modules")), path(&root.join("dist"))],
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_composite_package_base_gets_its_root_folder() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (root, scratch) = (tmp.path().join("p"), tmp.path().join("scratch"));
|
||||
write(&root, "node_modules/@acme/tsconfig/base.json", r#"{"compilerOptions": {"composite": true}}"#);
|
||||
write(&root, "app/tsconfig.json", r#"{"extends": "@acme/tsconfig/base", "include": ["src"]}"#);
|
||||
let copy = scratch_config(&root.join("app/tsconfig.json"), &scratch, 3, &[]);
|
||||
assert_eq!(copy["compilerOptions"]["rootDir"], json!(root.join("app")));
|
||||
assert_eq!(copy.get("include"), None, "the files come from the real configuration");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_compilation_reports_its_own_messages() {
|
||||
// `tsc --noEmit --watch --pretty false --preserveWatchOutput`, as printed.
|
||||
let output = "\
|
||||
2:14:08 PM - Starting compilation in watch mode...
|
||||
|
||||
2:14:09 PM - Found 0 errors. Watching for file changes.
|
||||
2:14:12 PM - File change detected. Starting incremental compilation...
|
||||
|
||||
src/b.ts(1,37): error TS2322: Type 'string' is not assignable to type 'number'.
|
||||
src/c.ts(2,1): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
|
||||
Type 'string' is not assignable to type 'number'.
|
||||
|
||||
2:14:12 PM - Found 2 errors. Watching for file changes.
|
||||
2:14:15 PM - File change detected. Starting incremental compilation...
|
||||
|
||||
2:14:15 PM - Found 0 errors. Watching for file changes.";
|
||||
let mut compilations = Compilations::default();
|
||||
let found: Vec<Vec<(String, Option<String>)>> = output
|
||||
.lines()
|
||||
.filter_map(|l| compilations.feed(l))
|
||||
.map(|raws| raws.into_iter().map(|r| (r.path.unwrap_or_default(), r.code)).collect())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
found,
|
||||
[
|
||||
vec![],
|
||||
vec![("src/b.ts".into(), Some("TS2322".into())), ("src/c.ts".into(), Some("TS2345".into()))],
|
||||
vec![]
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_projects_tsc_reports_until_cancelled() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
write(root, "app/tsconfig.json", "{}");
|
||||
write(root, "app/src/b.ts", "export const b: number = a;\n");
|
||||
// A watcher that prints one compilation and keeps running, like `tsc --watch`.
|
||||
write(
|
||||
root,
|
||||
"node_modules/.bin/tsc",
|
||||
"#!/bin/sh\necho \"$@\" > args.txt\n\
|
||||
echo 'src/b.ts(1,26): error TS2322: Type string is not assignable to type number.'\n\
|
||||
echo '1:00:00 PM - Found 1 error. Watching for file changes.'\nexec sleep 30\n",
|
||||
);
|
||||
let bin = root.join("node_modules/.bin/tsc");
|
||||
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
let mut compilations = Vec::new();
|
||||
let started = std::time::Instant::now();
|
||||
let result = tsc_watch(root, &root.join("app/tsconfig.json"), &cancel, |messages| {
|
||||
compilations.push(messages);
|
||||
cancel.cancel();
|
||||
});
|
||||
assert_eq!(result.unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
|
||||
assert!(started.elapsed().as_secs() < 10, "cancelling stops the watcher");
|
||||
let [messages] = &compilations[..] else { panic!("{compilations:?}") };
|
||||
let paths: Vec<_> = messages.iter().map(|m| (m.path.clone().map(PathBuf::from), m.range)).collect();
|
||||
let at = |l, c| ide_core::Pos::new(l, c);
|
||||
assert_eq!(paths, [(Some(root.join("app/src/b.ts")), Some(ide_core::Range::new(at(0, 25), at(0, 26))))]);
|
||||
let args = std::fs::read_to_string(root.join("app/args.txt")).unwrap();
|
||||
let (check, rest) = args.trim().split_once(" --tsBuildInfoFile ").unwrap();
|
||||
assert_eq!(check, "--noEmit -p tsconfig.json --incremental");
|
||||
let (info, watch) = rest.split_once(' ').unwrap();
|
||||
assert_eq!(watch, "--watch --pretty false --preserveWatchOutput");
|
||||
// The `.tsbuildinfo` goes to a scratch folder outside the project, gone with the watcher.
|
||||
let scratch = Path::new(info).parent().unwrap();
|
||||
assert!(scratch.starts_with(std::env::temp_dir()) && !scratch.starts_with(root), "{info}");
|
||||
assert!(!scratch.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_local_typescript_runs_nothing() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
write(tmp.path(), "tsconfig.json", "{}");
|
||||
let err = tsc_watch(tmp.path(), &tmp.path().join("tsconfig.json"), &CancellationToken::new(), |_| {
|
||||
panic!("no compilation without typescript")
|
||||
})
|
||||
.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::NotFound);
|
||||
}
|
||||
}
|
||||
@@ -486,6 +486,15 @@ pub struct LanguageCodeStyle {
|
||||
/// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub identifier_case: Option<String>,
|
||||
/// JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub semicolons: Option<String>,
|
||||
/// JavaScript / TypeScript › Punctuation › Quotes: `auto` | `single` | `double`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub quotes: Option<String>,
|
||||
/// JavaScript / TypeScript › Spaces, by tsserver format option (`insertSpaceAfterCommaDelimiter`).
|
||||
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub spaces: BTreeMap<String, bool>,
|
||||
}
|
||||
|
||||
/// Editor › Code Style (General tab + per-language overrides).
|
||||
|
||||
@@ -432,6 +432,12 @@ pub struct ToolDownloadSettings {
|
||||
/// commas or whitespace and tried in order before the official host; empty keeps every
|
||||
/// download on its official host.
|
||||
pub github_mirror: String,
|
||||
/// Package registries only as configured (a company Nexus or Artifactory): npm and pnpm
|
||||
/// installs and update checks never retry against the public npm registry, and the IDE
|
||||
/// fetches nothing from public package registries itself (the JUnit Platform launcher from
|
||||
/// Maven Central, dependency version completion from Maven Central, npm, PyPI and
|
||||
/// crates.io). Off by default.
|
||||
pub configured_registries_only: bool,
|
||||
}
|
||||
|
||||
/// Absent profiles retain automatic discovery for existing projects.
|
||||
@@ -1212,6 +1218,8 @@ pub struct LanguagesSettings {
|
||||
pub prettier: ExternalFormatterSettings,
|
||||
pub oxfmt: ExternalFormatterSettings,
|
||||
pub biome: ExternalFormatterSettings,
|
||||
/// dprint formats every file its configuration covers: `languages` is unused.
|
||||
pub dprint: ExternalFormatterSettings,
|
||||
pub ruff: ExternalFormatterSettings,
|
||||
pub black: ExternalFormatterSettings,
|
||||
pub java: JavaSettings,
|
||||
@@ -1238,6 +1246,7 @@ impl Default for LanguagesSettings {
|
||||
languages: BIOME_LANGUAGES.iter().map(|&l| l.into()).collect(),
|
||||
..ExternalFormatterSettings::default()
|
||||
},
|
||||
dprint: ExternalFormatterSettings { languages: Vec::new(), ..ExternalFormatterSettings::default() },
|
||||
ruff: ExternalFormatterSettings {
|
||||
languages: vec!["python".into()],
|
||||
..ExternalFormatterSettings::default()
|
||||
@@ -1315,6 +1324,7 @@ impl LanguagesSettings {
|
||||
ExternalFormatter::Prettier => &self.prettier,
|
||||
ExternalFormatter::Oxfmt => &self.oxfmt,
|
||||
ExternalFormatter::Biome => &self.biome,
|
||||
ExternalFormatter::Dprint => &self.dprint,
|
||||
ExternalFormatter::Ruff => &self.ruff,
|
||||
ExternalFormatter::Black => &self.black,
|
||||
}
|
||||
@@ -1328,6 +1338,7 @@ pub enum ExternalFormatter {
|
||||
Prettier,
|
||||
Oxfmt,
|
||||
Biome,
|
||||
Dprint,
|
||||
Ruff,
|
||||
Black,
|
||||
}
|
||||
@@ -1339,6 +1350,7 @@ impl ExternalFormatter {
|
||||
Self::Prettier => "prettier",
|
||||
Self::Oxfmt => "oxfmt",
|
||||
Self::Biome => "biome",
|
||||
Self::Dprint => "dprint",
|
||||
Self::Ruff => "ruff",
|
||||
Self::Black => "black",
|
||||
}
|
||||
@@ -1349,11 +1361,11 @@ impl ExternalFormatter {
|
||||
pub const BIOME_LANGUAGES: [&str; 8] =
|
||||
["css", "graphql", "javascript", "javascriptreact", "typescript", "typescriptreact", "json", "jsonc"];
|
||||
|
||||
/// An external formatter (Prettier, oxfmt, Biome, Ruff, Black) and the languages it formats.
|
||||
/// An external formatter (Prettier, oxfmt, Biome, dprint, Ruff, Black) and the languages it formats.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ExternalFormatterSettings {
|
||||
/// Empty path: project node_modules (Prettier/oxfmt/Biome), managed installation, then PATH.
|
||||
/// Empty path: project node_modules (Prettier/oxfmt/Biome/dprint), managed installation, then PATH.
|
||||
pub path: String,
|
||||
/// Ruff only: directory containing its configuration, or a configuration file.
|
||||
pub configuration_directory: String,
|
||||
@@ -1724,11 +1736,14 @@ pub struct TypeScriptSettings {
|
||||
/// plugin (hybrid mode; a Vue project's program alone needs ~3 GiB, and the
|
||||
/// vtsls default 3072 dies in a GC death spiral), else unset (vtsls default).
|
||||
pub tsserver_max_memory: u32,
|
||||
/// Problems › TypeScript project errors: the project's own `tsc --watch` per root
|
||||
/// `tsconfig.json` reports the errors of files that are not open.
|
||||
pub watch_problems: bool,
|
||||
}
|
||||
|
||||
impl Default for TypeScriptSettings {
|
||||
fn default() -> Self {
|
||||
Self { version: "bundled".into(), tsserver_max_memory: 0 }
|
||||
Self { version: "bundled".into(), tsserver_max_memory: 0, watch_problems: false }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use ide_core::{CancellationToken, IdeResult};
|
||||
use ide_db::{DataSource, DbDriver, DbJdbcDriver, DbManager, SortKey};
|
||||
use ide_db::{DataSource, DbDriver, DbJdbcDriver, DbManager, DbProperty, SortKey};
|
||||
use std::{path::Path, sync::Arc};
|
||||
|
||||
fn manager(dir: &Path) -> DbManager {
|
||||
@@ -89,21 +89,25 @@ async fn named_jdbc_sources_persist_the_type_and_reject_a_profile_for_another_ty
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
|
||||
async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir()?;
|
||||
let db = manager(tmp.path());
|
||||
fn register_duckdb(db: &DbManager, vendor: Option<&str>) -> IdeResult<()> {
|
||||
let jar = std::env::var("DUCKDB_JDBC_JAR").expect("DUCKDB_JDBC_JAR");
|
||||
assert_eq!(ide_db::jdbc_driver_classes(std::slice::from_ref(&jar))?, ["org.duckdb.DuckDBDriver"]);
|
||||
db.save_jdbc_driver(DbJdbcDriver {
|
||||
id: "duck".into(),
|
||||
name: "DuckDB".into(),
|
||||
vendor: None,
|
||||
vendor: vendor.map(str::to_owned),
|
||||
jars: vec![jar],
|
||||
class_name: "org.duckdb.DuckDBDriver".into(),
|
||||
url_template: "jdbc:duckdb:".into(),
|
||||
})?;
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
|
||||
async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir()?;
|
||||
let db = manager(tmp.path());
|
||||
register_duckdb(&db, None)?;
|
||||
let source = DataSource {
|
||||
id: "test".into(),
|
||||
name: "DuckDB".into(),
|
||||
@@ -157,6 +161,104 @@ async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
|
||||
async fn duckdb_named_file_enforces_read_only_at_open() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir()?;
|
||||
let db = manager(tmp.path());
|
||||
register_duckdb(&db, Some("duckdb"))?;
|
||||
let file = tmp.path().join("example.duckdb");
|
||||
let mut source = DataSource {
|
||||
id: "test".into(),
|
||||
name: "DuckDB".into(),
|
||||
driver: DbDriver::Jdbc,
|
||||
vendor: "duckdb".into(),
|
||||
global: true,
|
||||
jdbc_driver: "duck".into(),
|
||||
url: format!("jdbc:duckdb:{}", file.display()),
|
||||
file: Some(file.clone().into()),
|
||||
read_only: true,
|
||||
..Default::default()
|
||||
};
|
||||
let cancel = CancellationToken::new();
|
||||
let err = db.test(&source, None, None).await.unwrap_err();
|
||||
assert!(err.message.contains("existing database file"), "{}", err.message);
|
||||
assert!(!file.exists());
|
||||
|
||||
source.read_only = false;
|
||||
db.save_sources(vec![source.clone()]).await?;
|
||||
db.execute("test", "create table items (id int)", 1, &cancel).await?;
|
||||
db.execute("test", "insert into items values (1)", 1, &cancel).await?;
|
||||
db.disconnect("test").await;
|
||||
|
||||
source.read_only = true;
|
||||
let reopened = manager(tmp.path());
|
||||
assert!(reopened.test(&source, None, None).await?.to_lowercase().contains("duckdb"));
|
||||
let mut conflicting = source.clone();
|
||||
for options in ["; access_mode = READ_WRITE", "; duckdb.read_only = false"] {
|
||||
conflicting.url = format!("{}{options}", source.url);
|
||||
let err = reopened.test(&conflicting, None, None).await.unwrap_err();
|
||||
assert!(err.message.contains("conflicts with Read-only"), "{}", err.message);
|
||||
}
|
||||
conflicting.url = source.url.clone();
|
||||
conflicting.properties.push(DbProperty { name: "ACCESS_MODE".into(), value: "READ_WRITE".into() });
|
||||
let err = reopened.test(&conflicting, None, None).await.unwrap_err();
|
||||
assert!(err.message.contains("conflicts with Read-only"), "{}", err.message);
|
||||
|
||||
reopened.save_sources(vec![source.clone()]).await?;
|
||||
assert_eq!(reopened.source("test")?.vendor, "duckdb");
|
||||
assert_eq!(reopened.execute("test", "select id from items", 1, &cancel).await?.rows, [vec![Some("1".into())]]);
|
||||
for query in ["insert into items values (2)", "create table added (id int)"] {
|
||||
let err = reopened.execute("test", query, 1, &cancel).await.unwrap_err();
|
||||
assert!(err.message.to_lowercase().contains("read-only"), "{}", err.message);
|
||||
}
|
||||
assert!(!reopened.tables("test", "main").await?.iter().any(|table| table.name == "added"));
|
||||
reopened.disconnect("test").await;
|
||||
|
||||
source.read_only = false;
|
||||
reopened.save_sources(vec![source]).await?;
|
||||
reopened.execute("test", "insert into items values (2)", 1, &cancel).await?;
|
||||
assert_eq!(
|
||||
reopened.execute("test", "select count(*) from items", 1, &cancel).await?.rows,
|
||||
[vec![Some("2".into())]]
|
||||
);
|
||||
reopened.disconnect("test").await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
|
||||
async fn duckdb_named_memory_lives_until_disconnect() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir()?;
|
||||
let db = manager(tmp.path());
|
||||
register_duckdb(&db, Some("duckdb"))?;
|
||||
let mut source = DataSource {
|
||||
id: "test".into(),
|
||||
name: "DuckDB (memory)".into(),
|
||||
driver: DbDriver::Jdbc,
|
||||
vendor: "duckdb".into(),
|
||||
global: true,
|
||||
jdbc_driver: "duck".into(),
|
||||
url: "jdbc:duckdb:".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let cancel = CancellationToken::new();
|
||||
db.save_sources(vec![source.clone()]).await?;
|
||||
db.execute("test", "create table session_items as select 42 as id", 1, &cancel).await?;
|
||||
assert_eq!(db.execute("test", "select id from session_items", 1, &cancel).await?.rows, [vec![Some("42".into())]]);
|
||||
db.disconnect("test").await;
|
||||
assert!(!db.tables("test", "main").await?.iter().any(|table| table.name == "session_items"));
|
||||
db.disconnect("test").await;
|
||||
|
||||
source.read_only = true;
|
||||
for url in ["jdbc:duckdb:", "jdbc:duckdb::memory:"] {
|
||||
source.url = url.into();
|
||||
let err = db.test(&source, None, None).await.unwrap_err();
|
||||
assert!(err.message.contains("existing database file"), "{}", err.message);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires CLICKHOUSE_JDBC_CLASSPATH and a loopback ClickHouse fixture on CLICKHOUSE_JDBC_TEST_PORT"]
|
||||
async fn clickhouse_vendor_driver_reads_catalog_and_results() -> IdeResult<()> {
|
||||
|
||||
@@ -46,6 +46,13 @@ pub enum Capability {
|
||||
/// the manifest does not list; each answer applies to one host. Plain
|
||||
/// HTTP elsewhere always needs `net.http:<host>`.
|
||||
NetAsk,
|
||||
/// The host of the `string` setting `key`, approved when the user applies
|
||||
/// its value in Settings (`net:setting:server`, `net.http:setting:server`).
|
||||
/// HTTPS (and loopback HTTP) unless `http`.
|
||||
NetSetting {
|
||||
http: bool,
|
||||
key: String,
|
||||
},
|
||||
/// Unencrypted HTTP to one host.
|
||||
NetHttp(String),
|
||||
/// A local socket or named pipe on the project machine.
|
||||
@@ -89,6 +96,7 @@ impl Capability {
|
||||
| Self::VcsWrite
|
||||
| Self::Net(_)
|
||||
| Self::NetAsk
|
||||
| Self::NetSetting { .. }
|
||||
| Self::NetHttp(_)
|
||||
| Self::Secrets
|
||||
| Self::InputEvents
|
||||
@@ -139,6 +147,12 @@ impl Capability {
|
||||
"Ask to connect to a host that is not on the list the first time it tries; you allow or refuse each host, and can revoke the allowed ones"
|
||||
.into()
|
||||
}
|
||||
Self::NetSetting { http, key } if *http => {
|
||||
format!("Connect to the host set in the `{key}` setting over unencrypted HTTP (from the machine the project is on)")
|
||||
}
|
||||
Self::NetSetting { http: _, key } => {
|
||||
format!("Connect to the host set in the `{key}` setting (from the machine the project is on)")
|
||||
}
|
||||
Self::NetHttp(host) => {
|
||||
format!("Connect to {host} over unencrypted HTTP (from the machine the project is on)")
|
||||
}
|
||||
@@ -184,6 +198,19 @@ pub fn host_matches(pattern: &str, host: &str) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates a manifest-style host (letters, digits and `-` labels, at most 253
|
||||
/// bytes) and returns it lowercased. A `*` is never valid here — only a
|
||||
/// `net:`/`net.http:` grant itself may carry the `*.` subdomain pattern, and a
|
||||
/// host taken from a setting value never does.
|
||||
pub fn manifest_host(host: &str) -> Result<String, String> {
|
||||
let valid = !host.is_empty()
|
||||
&& host.len() <= 253
|
||||
&& host.split('.').all(|label| {
|
||||
!label.is_empty() && label.len() <= 63 && label.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
|
||||
});
|
||||
valid.then(|| host.to_ascii_lowercase()).ok_or_else(|| "invalid host".into())
|
||||
}
|
||||
|
||||
/// Validates a socket path; a grant may use `*` in its last segment only.
|
||||
pub fn validate_ipc_name(name: &str, pattern: bool) -> Result<(), String> {
|
||||
let pipe = name.starts_with(r"\\.\pipe\");
|
||||
@@ -273,6 +300,8 @@ impl fmt::Display for Capability {
|
||||
Self::ClipboardRead => f.write_str("clipboard.read"),
|
||||
Self::Net(h) => write!(f, "net:{h}"),
|
||||
Self::NetAsk => f.write_str("net:ask"),
|
||||
Self::NetSetting { http, key } if *http => write!(f, "net.http:setting:{key}"),
|
||||
Self::NetSetting { http: _, key } => write!(f, "net:setting:{key}"),
|
||||
Self::NetHttp(h) => write!(f, "net.http:{h}"),
|
||||
Self::Ipc(p) => write!(f, "ipc:{p}"),
|
||||
Self::Process(b) => write!(f, "process:{b}"),
|
||||
@@ -300,23 +329,27 @@ impl FromStr for Capability {
|
||||
if kind == "net" && arg == "ask" {
|
||||
return Ok(Self::NetAsk);
|
||||
}
|
||||
let host = arg.strip_prefix("*.").unwrap_or(arg);
|
||||
let valid = !host.is_empty()
|
||||
&& host.len() <= 253
|
||||
&& host.split('.').all(|label| {
|
||||
!label.is_empty()
|
||||
&& label.len() <= 63
|
||||
&& label.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
|
||||
});
|
||||
if valid {
|
||||
Ok(if kind == "net" {
|
||||
Self::Net(arg.to_ascii_lowercase())
|
||||
// `net:setting:<key>` names the plugin's `string` setting the
|
||||
// host comes from; the same key rule as a settings schema.
|
||||
if let Some(key) = arg.strip_prefix("setting:") {
|
||||
let valid_key = !key.is_empty()
|
||||
&& key.len() <= 64
|
||||
&& key.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c));
|
||||
return if valid_key {
|
||||
Ok(Self::NetSetting { http: kind == "net.http", key: key.to_owned() })
|
||||
} else {
|
||||
Self::NetHttp(arg.to_ascii_lowercase())
|
||||
})
|
||||
} else {
|
||||
Err(format!("invalid host in {s:?}"))
|
||||
Err(format!("invalid setting key in {s:?}"))
|
||||
};
|
||||
}
|
||||
manifest_host(arg.strip_prefix("*.").unwrap_or(arg))
|
||||
.map(|_| {
|
||||
if kind == "net" {
|
||||
Self::Net(arg.to_ascii_lowercase())
|
||||
} else {
|
||||
Self::NetHttp(arg.to_ascii_lowercase())
|
||||
}
|
||||
})
|
||||
.map_err(|_| format!("invalid host in {s:?}"))
|
||||
}
|
||||
"ipc" => {
|
||||
validate_ipc_name(arg, true)?;
|
||||
@@ -555,6 +588,77 @@ mod net_ask_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod net_setting_tests {
|
||||
use super::*;
|
||||
|
||||
/// `net:setting:<key>` names a settings key instead of a host: the host
|
||||
/// comes from the setting's value and is approved when the user sets it
|
||||
/// (#3809).
|
||||
#[test]
|
||||
fn setting_derived_grants_parse_and_print() {
|
||||
for s in ["net:setting:server", "net.http:setting:server"] {
|
||||
let cap: Capability = s.parse().unwrap();
|
||||
assert_eq!(cap.to_string(), s, "{s}");
|
||||
assert_eq!(cap.risk(), Risk::Medium, "{s}");
|
||||
}
|
||||
assert_eq!(
|
||||
"net:setting:server".parse::<Capability>().unwrap(),
|
||||
Capability::NetSetting { http: false, key: "server".into() }
|
||||
);
|
||||
assert_eq!(
|
||||
"net.http:setting:server".parse::<Capability>().unwrap(),
|
||||
Capability::NetSetting { http: true, key: "server".into() }
|
||||
);
|
||||
assert!(!"net:setting:server".parse::<Capability>().unwrap().auto_migrates());
|
||||
let derived = "net:setting:server".parse::<Capability>().unwrap();
|
||||
assert!(derived.describe().contains("`server`"));
|
||||
assert!("net.http:setting:server".parse::<Capability>().unwrap().describe().contains("unencrypted"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_derived_grants_stay_strict() {
|
||||
for s in ["net:setting:", "net:setting:a b", "net:setting:a:b", "net.http:setting:"] {
|
||||
assert!(s.parse::<Capability>().is_err(), "{s}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The derivation covers nothing by itself: a literal-host grant and a
|
||||
/// setting-derived grant are different grants, and the host materializes
|
||||
/// only after the user approves the setting's value.
|
||||
#[test]
|
||||
fn derived_grants_do_not_cover_literal_hosts() {
|
||||
let derived: Capability = "net:setting:server".parse().unwrap();
|
||||
let literal: Capability = "net:gitlab.intranet.example".parse().unwrap();
|
||||
assert!(!derived.covers(&literal));
|
||||
assert!(!literal.covers(&derived));
|
||||
assert!(!derived.covers(&"net.http:gitlab.intranet.example".parse().unwrap()));
|
||||
assert!(!derived.covers(&"net:setting:other".parse().unwrap()));
|
||||
}
|
||||
|
||||
/// The host of a setting value passes the same rules as a manifest host,
|
||||
/// and a `*` is refused (`net:*` stays impossible).
|
||||
#[test]
|
||||
fn value_hosts_follow_the_manifest_host_rules() {
|
||||
assert_eq!(manifest_host("GitLab.Intranet.Example").unwrap(), "gitlab.intranet.example");
|
||||
for bad in
|
||||
["", "*", "*.example.com", "a b", "under_score.example", "gitlab.intranet.example.", &"a".repeat(254)]
|
||||
{
|
||||
assert!(manifest_host(bad).is_err(), "{bad}");
|
||||
}
|
||||
let long = ["a".repeat(61), "b".repeat(61), "c".repeat(61), "d".repeat(61)].join(".");
|
||||
assert_eq!(long.len(), 247);
|
||||
assert!(manifest_host(&long).is_ok());
|
||||
assert!(
|
||||
manifest_host(&["a".repeat(63), "b".repeat(63), "c".repeat(63), "d".repeat(63)].join(".")).is_err(),
|
||||
"over 253 bytes"
|
||||
);
|
||||
assert!(manifest_host(&"a".repeat(64)).is_err(), "over 63 bytes per label");
|
||||
// Pattern grants keep working: only a value (and a bare host) refuses `*`.
|
||||
assert!("net:*.github.com".parse::<Capability>().is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod database_tests {
|
||||
use super::*;
|
||||
|
||||
@@ -58,6 +58,10 @@ pub struct Grant {
|
||||
/// Exact hosts approved through `net:ask`, separate from manifest grants.
|
||||
#[serde(default)]
|
||||
pub net_hosts: BTreeSet<String>,
|
||||
/// Hosts approved for `net:setting:<key>` / `net.http:setting:<key>`
|
||||
/// grants, keyed by the grant: the user approved the value in Settings.
|
||||
#[serde(default)]
|
||||
pub setting_hosts: BTreeMap<String, String>,
|
||||
/// Optional capabilities the user declined (not asked again until re-confirmed).
|
||||
#[serde(default)]
|
||||
pub declined: BTreeSet<String>,
|
||||
@@ -209,6 +213,7 @@ impl Ledger {
|
||||
if !req.required.iter().chain(&req.optional).any(|c| c == &Capability::NetAsk) {
|
||||
grant.net_hosts.clear();
|
||||
}
|
||||
retain_setting_hosts(grant, req);
|
||||
if !grant.confirmed {
|
||||
return Decision::NeedsConfirmation { new: req.required.clone(), first_time: true };
|
||||
}
|
||||
@@ -236,6 +241,7 @@ impl Ledger {
|
||||
if !req.required.iter().chain(&req.optional).any(|c| c == &Capability::NetAsk) {
|
||||
grant.net_hosts.clear();
|
||||
}
|
||||
retain_setting_hosts(grant, req);
|
||||
grant.plugin_id = req.plugin_id.to_owned();
|
||||
grant.version = req.version.to_owned();
|
||||
grant.package_hash = req.package_hash.to_owned();
|
||||
@@ -269,6 +275,9 @@ impl Ledger {
|
||||
if cap == &Capability::NetAsk {
|
||||
grant.net_hosts.clear();
|
||||
}
|
||||
if matches!(cap, Capability::NetSetting { .. }) {
|
||||
grant.setting_hosts.remove(&s);
|
||||
}
|
||||
if let Capability::Process(_) | Capability::JavaAgent = cap {
|
||||
grant.binaries.remove(&s);
|
||||
for binaries in grant.project_binaries.values_mut() {
|
||||
@@ -292,6 +301,21 @@ impl Ledger {
|
||||
self.grants.get_mut(subject).is_some_and(|g| g.net_hosts.remove(host))
|
||||
}
|
||||
|
||||
/// Remembers the host the user approved for a `net:setting:` grant: it
|
||||
/// covers requests only while the setting still holds it.
|
||||
pub fn remember_setting_host(&mut self, subject: &Subject, cap: &Capability, host: &str) -> bool {
|
||||
let Some(grant) = self.grants.get_mut(subject) else { return false };
|
||||
if !grant.confirmed || !grant.has(cap) || host.contains('*') {
|
||||
return false;
|
||||
}
|
||||
grant.setting_hosts.insert(cap.to_string(), host.to_owned());
|
||||
true
|
||||
}
|
||||
|
||||
pub fn forget_setting_host(&mut self, subject: &Subject, cap: &Capability) -> bool {
|
||||
self.grants.get_mut(subject).is_some_and(|g| g.setting_hosts.remove(&cap.to_string()).is_some())
|
||||
}
|
||||
|
||||
/// Records the program approved for a `process:` grant (or the jar of a `java.agent` one).
|
||||
pub fn set_binary(&mut self, subject: &Subject, cap: &Capability, binary: BinaryGrant) {
|
||||
if let Some(grant) = self.grants.get_mut(subject) {
|
||||
@@ -393,6 +417,19 @@ pub fn by_risk(caps: &[Capability]) -> Vec<(Risk, Vec<Capability>)> {
|
||||
groups.into_iter().map(|(r, v)| (r.0, v)).collect()
|
||||
}
|
||||
|
||||
/// Drops setting-derived hosts the manifest no longer asks for, like
|
||||
/// `net_hosts` are dropped when `net:ask` is removed.
|
||||
fn retain_setting_hosts(grant: &mut Grant, req: &Request<'_>) {
|
||||
let declared: Vec<String> = req
|
||||
.required
|
||||
.iter()
|
||||
.chain(&req.optional)
|
||||
.filter(|c| matches!(c, Capability::NetSetting { .. }))
|
||||
.map(|c| c.to_string())
|
||||
.collect();
|
||||
grant.setting_hosts.retain(|cap, _| declared.contains(cap));
|
||||
}
|
||||
|
||||
/// Pins an explicitly selected executable, retaining a multicall shim's filename.
|
||||
pub fn approve_program(path: &Path) -> Result<BinaryGrant, String> {
|
||||
if !path.is_absolute() || !is_executable(path) {
|
||||
@@ -589,6 +626,58 @@ mod tests {
|
||||
assert!(l.get(&r.subject).unwrap().net_hosts.is_empty());
|
||||
}
|
||||
|
||||
/// A setting-derived host is approved per grant, survives re-confirmation,
|
||||
/// is replaced by the next approval, and goes when the grant or the
|
||||
/// manifest declaration goes (#3809).
|
||||
#[test]
|
||||
fn setting_hosts_are_approved_per_grant_and_drop_with_it() {
|
||||
let mut l = Ledger::in_memory();
|
||||
let r = req("1.0.0", "h", &["project.read"], &["net:setting:server", "net.http:setting:server"]);
|
||||
l.confirm(
|
||||
&r,
|
||||
&["net:setting:server".parse().unwrap(), "net.http:setting:server".parse().unwrap()],
|
||||
BTreeMap::new(),
|
||||
);
|
||||
let cap: Capability = "net:setting:server".parse().unwrap();
|
||||
let other: Capability = "net.http:setting:server".parse().unwrap();
|
||||
|
||||
// Not granted (declined optional, or not confirmed): refused.
|
||||
let declined = req("1.0.0", "h", &["project.read"], &["net:setting:server"]);
|
||||
let mut l2 = Ledger::in_memory();
|
||||
l2.confirm(&declined, &[], BTreeMap::new());
|
||||
assert!(!l2.remember_setting_host(&declined.subject, &cap, "jira.corp.example"), "declined optional");
|
||||
let never = req("1.0.0", "h", &["project.read"], &[]);
|
||||
let mut l3 = Ledger::in_memory();
|
||||
assert!(!l3.remember_setting_host(&never.subject, &cap, "jira.corp.example"), "never confirmed");
|
||||
|
||||
assert!(l.remember_setting_host(&r.subject, &cap, "gitlab.intranet.example"));
|
||||
assert!(!l.remember_setting_host(&r.subject, &cap, "*"), "a wildcard value is refused");
|
||||
assert_eq!(
|
||||
l.get(&r.subject).unwrap().setting_hosts.get("net:setting:server").map(String::as_str),
|
||||
Some("gitlab.intranet.example")
|
||||
);
|
||||
// The other transport is its own record; the derived grant itself covers no host.
|
||||
assert!(l.remember_setting_host(&r.subject, &other, "jira.corp.example"));
|
||||
assert!(!l.get(&r.subject).unwrap().has(&Capability::Net("gitlab.intranet.example".into())));
|
||||
// Re-confirmation keeps the approval; a manifest that drops the grant drops the record.
|
||||
l.confirm(&r, &["net:setting:server".parse().unwrap()], BTreeMap::new());
|
||||
assert_eq!(
|
||||
l.get(&r.subject).unwrap().setting_hosts.get("net:setting:server").map(String::as_str),
|
||||
Some("gitlab.intranet.example")
|
||||
);
|
||||
let without = req("2.0.0", "h2", &["project.read"], &[]);
|
||||
assert!(matches!(l.decide(&without), Decision::Allowed { .. }), "same or fewer needs: silent");
|
||||
assert!(l.get(&r.subject).unwrap().setting_hosts.is_empty(), "records follow the manifest");
|
||||
|
||||
// Revoking the capability clears its record.
|
||||
l.confirm(&r, &["net:setting:server".parse().unwrap()], BTreeMap::new());
|
||||
l.remember_setting_host(&r.subject, &cap, "gitlab.intranet.example");
|
||||
assert!(l.set(&r.subject, &cap, false));
|
||||
assert!(l.get(&r.subject).unwrap().setting_hosts.is_empty());
|
||||
// Forgetting without a record is an error.
|
||||
assert!(!l.forget_setting_host(&r.subject, &cap));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migration_grants_low_risk_only() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -26,7 +26,9 @@ mod resolve;
|
||||
mod ui;
|
||||
mod when;
|
||||
|
||||
pub use capability::{Capability, CapabilityInfo, Risk, expand_ipc_name, host_matches, validate_ipc_name};
|
||||
pub use capability::{
|
||||
Capability, CapabilityInfo, Risk, expand_ipc_name, host_matches, manifest_host, validate_ipc_name,
|
||||
};
|
||||
pub use index::ContributionIndex;
|
||||
pub use manifest::{
|
||||
ActivationEvent, CATEGORIES, Capabilities, ENGINE_VERSION, EVENT_KINDS, LEGACY_API, MANIFEST_FILE, MAX_CATEGORIES,
|
||||
|
||||
@@ -372,6 +372,9 @@ impl Manifest {
|
||||
if matches!(cap, Capability::Agents) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 18)?;
|
||||
}
|
||||
if matches!(cap, Capability::NetSetting { .. }) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 18)?;
|
||||
}
|
||||
if matches!(cap, Capability::JavaAgent) {
|
||||
return Err(
|
||||
"`java.agent` comes from `[[contributes.javaAgents]]`: remove it from [capabilities]".into()
|
||||
@@ -767,6 +770,20 @@ required = [\"lsp:phoxite\"]
|
||||
assert_eq!(m.capabilities.optional, [Capability::ClipboardRead]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_derived_net_capabilities_need_the_current_api_minor() {
|
||||
for cap in ["net:setting:server", "net.http:setting:server"] {
|
||||
let caps = format!("[capabilities]\noptional = [\"{cap}\"]\n");
|
||||
assert!(
|
||||
err(&format!("{}{caps}", BASE.replace("^1.2", "^1.17"))).contains("new in plugin API 1.18"),
|
||||
"{cap}"
|
||||
);
|
||||
let m = Manifest::parse(&format!("{}{caps}", BASE.replace("^1.2", "^1.18"))).unwrap();
|
||||
assert_eq!(m.capabilities.optional.len(), 1, "{cap}");
|
||||
assert_eq!(m.capabilities.optional[0].to_string(), cap);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_agent_capability_is_not_declared() {
|
||||
for list in ["required", "optional"] {
|
||||
|
||||
@@ -15,6 +15,52 @@ const OXFMT_CONFIGS: [&str; 4] = [".oxfmtrc.json", ".oxfmtrc.jsonc", "oxfmt.conf
|
||||
/// A Biome configuration, or Biome installed as a project dependency (it then uses its defaults).
|
||||
const BIOME_MARKERS: [&str; 3] = ["biome.json", "biome.jsonc", "node_modules/@biomejs/biome/package.json"];
|
||||
|
||||
/// dprint's configuration files, and dprint installed as a project dependency.
|
||||
const DPRINT_MARKERS: [&str; 5] =
|
||||
["dprint.json", ".dprint.json", "dprint.jsonc", ".dprint.jsonc", "node_modules/dprint/package.json"];
|
||||
|
||||
/// The nearest of `names` in `file`'s folder or above, up to the project `root` (none outside it).
|
||||
fn find_in_project(file: &Path, root: &Path, names: &[&str]) -> Option<PathBuf> {
|
||||
file.parent()?
|
||||
.ancestors()
|
||||
.take_while(|dir| dir.starts_with(root))
|
||||
.find_map(|dir| names.iter().map(|name| dir.join(name)).find(|p| p.is_file()))
|
||||
}
|
||||
|
||||
fn dprint_project(file: &Path, root: &Path) -> bool {
|
||||
find_in_project(file, root, &DPRINT_MARKERS).is_some()
|
||||
}
|
||||
|
||||
/// `dprint editor-info` results by configuration file (the project root without one) and the
|
||||
/// configuration's modification time. Failures are kept too: an offline plugin download would
|
||||
/// otherwise time out again on every format.
|
||||
// ponytail: `extends` files and a configuration outside the project are not watched; editing one needs a change of the project's file (or a restart).
|
||||
type EditorInfo = (Option<std::time::SystemTime>, IdeResult<String>);
|
||||
static DPRINT_EDITOR_INFO: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<PathBuf, EditorInfo>>> =
|
||||
std::sync::LazyLock::new(Default::default);
|
||||
|
||||
/// Whether the dprint configuration found for `file` (from its folder, as dprint finds it) has a
|
||||
/// plugin for it. `retry` runs `editor-info` again after a remembered failure.
|
||||
fn dprint_covers(tools: &Tools, custom: Option<&Path>, file: &Path, root: &Path, retry: bool) -> IdeResult<bool> {
|
||||
let dir = file.parent().ok_or_else(|| IdeError::invalid("dprint: file has no directory"))?;
|
||||
let config = find_in_project(file, root, &DPRINT_MARKERS[..4]);
|
||||
let modified = config.as_ref().and_then(|c| std::fs::metadata(c).and_then(|m| m.modified()).ok());
|
||||
let key = config.unwrap_or_else(|| root.to_path_buf());
|
||||
let cached = {
|
||||
let cache = DPRINT_EDITOR_INFO.lock().unwrap_or_else(|e| e.into_inner());
|
||||
cache.get(&key).filter(|(at, info)| *at == modified && !(retry && info.is_err())).map(|(_, info)| info.clone())
|
||||
};
|
||||
let info = cached.unwrap_or_else(|| {
|
||||
let info = tools.formatter_command("dprint", file, custom).and_then(|mut command| {
|
||||
command.current_dir(dir);
|
||||
formatter::dprint_editor_info(command)
|
||||
});
|
||||
DPRINT_EDITOR_INFO.lock().unwrap_or_else(|e| e.into_inner()).insert(key, (modified, info.clone()));
|
||||
info
|
||||
})?;
|
||||
formatter::dprint_covers(&info, file)
|
||||
}
|
||||
|
||||
/// Reformat Code uses Biome below a Biome configuration or installation, unless the nearest
|
||||
/// configuration turns its formatter off (Biome lints, another tool formats).
|
||||
fn biome_formats(file: &Path) -> bool {
|
||||
@@ -31,6 +77,69 @@ fn biome_formats(file: &Path) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
const PRETTIER_CONFIGS: [&str; 18] = [
|
||||
".prettierrc",
|
||||
".prettierrc.json",
|
||||
".prettierrc.json5",
|
||||
".prettierrc.yaml",
|
||||
".prettierrc.yml",
|
||||
".prettierrc.toml",
|
||||
".prettierrc.js",
|
||||
".prettierrc.cjs",
|
||||
".prettierrc.mjs",
|
||||
".prettierrc.ts",
|
||||
".prettierrc.cts",
|
||||
".prettierrc.mts",
|
||||
"prettier.config.js",
|
||||
"prettier.config.cjs",
|
||||
"prettier.config.mjs",
|
||||
"prettier.config.ts",
|
||||
"prettier.config.cts",
|
||||
"prettier.config.mts",
|
||||
];
|
||||
|
||||
/// A Prettier configuration applies to `file`: a configuration file or a `prettier` key in a
|
||||
/// `package.json` above it.
|
||||
fn prettier_configured(file: &Path) -> bool {
|
||||
PRETTIER_CONFIGS.iter().any(|name| formatter::find_up(file, Path::new(name)).is_some())
|
||||
|| file.ancestors().skip(1).any(|dir| {
|
||||
std::fs::read_to_string(dir.join("package.json"))
|
||||
.ok()
|
||||
.and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
|
||||
.is_some_and(|v| v.get("prettier").is_some())
|
||||
})
|
||||
}
|
||||
|
||||
/// The languages whose server formats in the IDE's code style (`ts_code_style`).
|
||||
const CODE_STYLE_LANGUAGES: [&str; 4] = ["javascript", "javascriptreact", "typescript", "typescriptreact"];
|
||||
|
||||
/// In Automatic mode, the project's own configuration of `tool` wins over the TypeScript server,
|
||||
/// whose output follows the IDE's code style. Not before the tool is installed (`resolves`): a fresh
|
||||
/// clone keeps formatting with the server until `npm install`.
|
||||
fn project_takes_over(tool: ExternalFormatter, language: &str, file: &Path, resolves: impl FnOnce() -> bool) -> bool {
|
||||
CODE_STYLE_LANGUAGES.contains(&language) && project_configured(tool, file) && resolves()
|
||||
}
|
||||
|
||||
/// Format on save runs the external tool: its own setting, or the editor's when the tool takes over
|
||||
/// from the language server (Black, dprint, or a project configuration), so saving keeps formatting.
|
||||
fn runs_on_save(tool: ExternalFormatter, run_on_save: bool, takes_over: bool, format_on_save: bool) -> bool {
|
||||
run_on_save
|
||||
|| ((matches!(tool, ExternalFormatter::Black | ExternalFormatter::Dprint) || takes_over) && format_on_save)
|
||||
}
|
||||
|
||||
/// The project configures `tool`. Every formatter needs an arm. dprint is chosen before this check
|
||||
/// (`dprint_project`), so it never reaches it.
|
||||
fn project_configured(tool: ExternalFormatter, file: &Path) -> bool {
|
||||
match tool {
|
||||
ExternalFormatter::Prettier => prettier_configured(file),
|
||||
ExternalFormatter::Oxfmt => {
|
||||
OXFMT_CONFIGS.iter().any(|name| formatter::find_up(file, Path::new(name)).is_some())
|
||||
}
|
||||
ExternalFormatter::Biome => biome_formats(file),
|
||||
ExternalFormatter::Ruff | ExternalFormatter::Black | ExternalFormatter::Dprint => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `pyproject.toml` Black reads for `file`, in the project root Black finds: the nearest folder
|
||||
/// with `.git`, `.hg`, or a `pyproject.toml` that has `[tool.black]` (one without it is skipped).
|
||||
/// `None` when that root has no `pyproject.toml`: Black then reads the user's configuration.
|
||||
@@ -533,18 +642,58 @@ async fn provider_edits(
|
||||
}
|
||||
return Ok(Some(edits));
|
||||
}
|
||||
let mut selected = external_tool(options.tool, language.as_ref(), &snap.path, &settings.languages)?;
|
||||
// dprint formats what its configuration covers, before the language's own formatters.
|
||||
let dprint = &settings.languages.dprint;
|
||||
let forced_dprint = options.tool == Some(ExternalFormatter::Dprint);
|
||||
let auto_dprint = options.tool.is_none()
|
||||
&& (dprint.prefer || dprint_project(&snap.path, &project.root))
|
||||
&& project.require_trust().is_ok();
|
||||
let mut selected = None;
|
||||
if forced_dprint || auto_dprint {
|
||||
host.require_trust(window)?;
|
||||
let tools = Tools::new(&host.local_data_dir);
|
||||
let custom = ide_sdk::apply::setting_path(&project.root, &dprint.path);
|
||||
let (path, root) = (snap.path.clone(), project.root.clone());
|
||||
let covers =
|
||||
tokio::task::spawn_blocking(move || dprint_covers(&tools, custom.as_deref(), &path, &root, forced_dprint))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
match covers {
|
||||
Ok(true) => selected = Some(ExternalFormatter::Dprint),
|
||||
Ok(false) if forced_dprint => {
|
||||
return Err(
|
||||
IdeError::invalid("The dprint configuration has no plugin for this file").with_tool("dprint")
|
||||
);
|
||||
}
|
||||
Ok(false) => {}
|
||||
Err(e) if forced_dprint => return Err(e.with_tool("dprint")),
|
||||
// Not installed, no configuration, plugins not downloadable: the usual formatter.
|
||||
Err(e) => tracing::warn!("dprint editor-info failed, using the usual formatter: {}", e.message),
|
||||
}
|
||||
}
|
||||
if selected.is_none() {
|
||||
selected = external_tool(options.tool, language.as_ref(), &snap.path, &settings.languages)?;
|
||||
}
|
||||
let mut takes_over = false;
|
||||
// Black is selected only when configured or preferred: the Ruff server's formatting doesn't replace it.
|
||||
if let Some(tool) = selected
|
||||
&& options.tool.is_none()
|
||||
&& tool != ExternalFormatter::Dprint
|
||||
&& tool != ExternalFormatter::Black
|
||||
&& !settings.languages.formatter(tool).prefer
|
||||
&& match doc {
|
||||
Some(doc) => project.lsp.can_format(doc).await?,
|
||||
None => project.lsp.can_format_text(&snap.path, &snap.language).await,
|
||||
}
|
||||
{
|
||||
selected = None;
|
||||
takes_over = project_takes_over(tool, snap.language.as_str(), &snap.path, || {
|
||||
let custom = ide_sdk::apply::setting_path(&project.root, &settings.languages.formatter(tool).path);
|
||||
Tools::new(&host.local_data_dir).formatter_command(tool.name(), &snap.path, custom.as_deref()).is_ok()
|
||||
});
|
||||
if !takes_over
|
||||
&& match doc {
|
||||
Some(doc) => project.lsp.can_format(doc).await?,
|
||||
None => project.lsp.can_format_text(&snap.path, &snap.language).await,
|
||||
}
|
||||
{
|
||||
selected = None;
|
||||
}
|
||||
}
|
||||
let Some(selected) = selected else {
|
||||
if options.on_save && !settings.editor.format_on_save {
|
||||
@@ -566,17 +715,24 @@ async fn provider_edits(
|
||||
.map_err(|e| IdeError::internal(e.to_string()));
|
||||
};
|
||||
let tool_settings = settings.languages.formatter(selected);
|
||||
// Black takes over from the language server in its projects, so Format on save runs it too.
|
||||
let runs_on_save =
|
||||
tool_settings.run_on_save || (selected == ExternalFormatter::Black && settings.editor.format_on_save);
|
||||
if options.on_save && !runs_on_save {
|
||||
if options.on_save && !runs_on_save(selected, tool_settings.run_on_save, takes_over, settings.editor.format_on_save)
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
host.require_trust(window)?;
|
||||
if snap.read_only {
|
||||
return Err(IdeError::invalid("The file is read-only"));
|
||||
}
|
||||
let config = language.and_then(|l| l.formatter).expect("external_tool selects languages with a formatter");
|
||||
let config = language
|
||||
.and_then(|l| l.formatter)
|
||||
.or_else(|| {
|
||||
(selected == ExternalFormatter::Dprint).then(|| ide_language::FormatterConfig {
|
||||
tool: "dprint".into(),
|
||||
parser: String::new(),
|
||||
range: false,
|
||||
})
|
||||
})
|
||||
.expect("external_tool selects languages with a formatter");
|
||||
let tool = selected.name();
|
||||
let name = formatter::display_name(tool);
|
||||
let mut custom = ide_sdk::apply::setting_path(&project.root, &tool_settings.path);
|
||||
@@ -727,7 +883,7 @@ pub async fn python_import_edits(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ExternalFormatter::{Biome, Black, Oxfmt, Prettier, Ruff};
|
||||
use ExternalFormatter::{Biome, Black, Dprint, Oxfmt, Prettier, Ruff};
|
||||
use ide_core::LanguageId;
|
||||
use ide_language::LanguageRegistry;
|
||||
|
||||
@@ -945,6 +1101,90 @@ mod tests {
|
||||
assert_eq!(black_pyproject(&file), Some(repo.join("pkg/pyproject.toml")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dprint_configuration_or_dependency_in_the_project_marks_a_dprint_project() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("home/project");
|
||||
let file = root.join("web/src/app.ts");
|
||||
assert!(!dprint_project(&file, &root));
|
||||
for marker in DPRINT_MARKERS {
|
||||
let path = root.join("web").join(marker);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&path, "{}").unwrap();
|
||||
assert!(dprint_project(&file, &root), "{marker}");
|
||||
assert!(!dprint_project(&root.join("api/main.ts"), &root), "{marker}");
|
||||
// A file outside the project is not below the project's dprint.
|
||||
assert!(!dprint_project(&dir.path().join("elsewhere/web/src/app.ts"), &root), "{marker}");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
}
|
||||
// dprint installed above the project (a stray `~/node_modules/dprint`) doesn't count.
|
||||
let stray = dir.path().join("home/node_modules/dprint/package.json");
|
||||
std::fs::create_dir_all(stray.parent().unwrap()).unwrap();
|
||||
std::fs::write(&stray, "{}").unwrap();
|
||||
std::fs::write(dir.path().join("home/dprint.json"), "{}").unwrap();
|
||||
assert!(!dprint_project(&file, &root));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn dprint_coverage_comes_from_editor_info_cached_per_configuration() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::create_dir_all(root.join("src")).unwrap();
|
||||
let config = root.join("dprint.json");
|
||||
std::fs::write(&config, "{}").unwrap();
|
||||
// Shell builtins only: the command runs with the tools' empty PATH.
|
||||
let info = r#"{"plugins":[{"fileExtensions":["ts"],"fileNames":["Dockerfile"]}]}"#;
|
||||
let fake = root.join("fake-dprint");
|
||||
let script = format!(
|
||||
"#!/bin/sh\necho run >> \"$0.runs\"\n[ -f fail ] && {{ echo 'bad config' >&2; exit 1; }}\nprintf '%s' '{info}'\n"
|
||||
);
|
||||
std::fs::write(&fake, script).unwrap();
|
||||
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let tools = Tools::with_paths(root.join("tools"), Default::default(), ide_tools::platform::Platform::current());
|
||||
let runs = || std::fs::read_to_string(root.join("fake-dprint.runs")).unwrap_or_default().lines().count();
|
||||
let covers = |file: &str, retry| dprint_covers(&tools, Some(&fake), &root.join(file), root, retry);
|
||||
|
||||
assert!(covers("src/app.ts", false).unwrap());
|
||||
assert!(covers("src/Dockerfile", false).unwrap());
|
||||
// Not covered: the usual formatter takes the file.
|
||||
assert!(!covers("src/main.py", false).unwrap());
|
||||
assert_eq!(runs(), 1);
|
||||
|
||||
// A changed configuration is read again, and its error is dprint's.
|
||||
std::fs::write(root.join("src/fail"), "").unwrap();
|
||||
let later = std::fs::metadata(&config).unwrap().modified().unwrap() + std::time::Duration::from_secs(5);
|
||||
std::fs::File::options().write(true).open(&config).unwrap().set_modified(later).unwrap();
|
||||
let error = covers("src/app.ts", false).unwrap_err();
|
||||
assert!(error.message.contains("bad config"), "{}", error.message);
|
||||
assert_eq!(error.data, Some(ide_core::error::ErrorData::Tool { tool: "dprint".into(), missing: false }));
|
||||
assert_eq!(runs(), 2);
|
||||
// The failure is remembered (an offline download would time out again), unless retried.
|
||||
assert!(covers("src/app.ts", false).is_err());
|
||||
assert_eq!(runs(), 2);
|
||||
std::fs::remove_file(root.join("src/fail")).unwrap();
|
||||
assert!(covers("src/app.ts", true).unwrap());
|
||||
assert_eq!(runs(), 3);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn dprint_without_a_project_configuration_runs_once_per_project() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::create_dir_all(root.join("a/b")).unwrap();
|
||||
let fake = root.join("fake-dprint");
|
||||
std::fs::write(&fake, "#!/bin/sh\necho run >> \"$0.runs\"\nprintf '%s' '{\"plugins\":[]}'\n").unwrap();
|
||||
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let tools = Tools::with_paths(root.join("tools"), Default::default(), ide_tools::platform::Platform::current());
|
||||
for file in ["a/x.ts", "a/b/y.ts", "z.ts"] {
|
||||
assert!(!dprint_covers(&tools, Some(&fake), &root.join(file), root, false).unwrap());
|
||||
}
|
||||
assert_eq!(std::fs::read_to_string(root.join("fake-dprint.runs")).unwrap().lines().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn biome_config_or_dependency_selects_biome_for_its_languages() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
@@ -1011,6 +1251,55 @@ mod tests {
|
||||
assert_eq!(tool(None, "typescript", file, &settings).unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_configuration_of_the_formatter_wins_over_the_language_server() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::create_dir_all(root.join("a/src")).unwrap();
|
||||
std::fs::create_dir_all(root.join("b/src")).unwrap();
|
||||
std::fs::create_dir_all(root.join("c/src")).unwrap();
|
||||
std::fs::write(root.join("a/.prettierrc.json"), "{}").unwrap();
|
||||
std::fs::write(root.join("b/package.json"), r#"{ "prettier": { "semi": false } }"#).unwrap();
|
||||
std::fs::write(root.join("c/package.json"), r#"{ "name": "c" }"#).unwrap();
|
||||
std::fs::write(root.join("c/biome.json"), "{}").unwrap();
|
||||
assert!(project_configured(Prettier, &root.join("a/src/app.ts")));
|
||||
assert!(project_configured(Prettier, &root.join("b/src/app.ts")));
|
||||
assert!(!project_configured(Prettier, &root.join("c/src/app.ts")));
|
||||
assert!(project_configured(Biome, &root.join("c/src/app.ts")));
|
||||
assert!(!project_configured(Oxfmt, &root.join("c/src/app.ts")));
|
||||
std::fs::write(root.join("c/.oxfmtrc.json"), "{}").unwrap();
|
||||
assert!(project_configured(Oxfmt, &root.join("c/src/app.ts")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_typescript_server_languages_give_way_to_an_installed_project_formatter() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join(".prettierrc"), "{}").unwrap();
|
||||
let file = |name: &str| dir.path().join(name);
|
||||
for language in ["typescript", "typescriptreact", "javascript", "javascriptreact"] {
|
||||
assert!(project_takes_over(Prettier, language, &file("a.ts"), || true), "{language}");
|
||||
}
|
||||
for language in ["json", "css", "html", "yaml", "markdown", "vue"] {
|
||||
assert!(!project_takes_over(Prettier, language, &file("a.json"), || true), "{language}");
|
||||
}
|
||||
// Configured but not installed yet (before `npm install`): the language server formats.
|
||||
assert!(!project_takes_over(Prettier, "typescript", &file("a.ts"), || false));
|
||||
// No configuration: the tool isn't even looked up.
|
||||
assert!(!project_takes_over(Biome, "typescript", &file("a.ts"), || panic!("resolved")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_on_save_keeps_running_when_the_project_formatter_takes_over() {
|
||||
// Format on save formatted with the language server before; the tool that replaces it does too.
|
||||
assert!(runs_on_save(Prettier, false, true, true));
|
||||
assert!(!runs_on_save(Prettier, false, true, false));
|
||||
assert!(runs_on_save(Black, false, false, true));
|
||||
assert!(runs_on_save(Dprint, false, false, true));
|
||||
// Selected by the settings, not taking over: only its own Run on save.
|
||||
assert!(!runs_on_save(Prettier, false, false, true));
|
||||
assert!(runs_on_save(Prettier, true, false, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forced_tool_runs_that_formatter_or_reports_why_not() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -27,6 +27,8 @@ mod requests;
|
||||
pub mod rpc;
|
||||
pub mod shell_env;
|
||||
pub mod trust;
|
||||
mod ts_code_style;
|
||||
mod tsc_watch;
|
||||
pub mod web_server;
|
||||
|
||||
pub use project::{Project, history_retention};
|
||||
@@ -425,6 +427,9 @@ impl Host {
|
||||
if let Some(phpstan) = &project.phpstan {
|
||||
phpstan.stop();
|
||||
}
|
||||
if let Some(watch) = &project.tsc_watch {
|
||||
watch.stop();
|
||||
}
|
||||
project.documents.clear_workspace_edit_history();
|
||||
project.agents.detach_sinks();
|
||||
project.flutter.stop();
|
||||
@@ -654,6 +659,9 @@ impl Host {
|
||||
if let Some(phpstan) = &project.phpstan {
|
||||
phpstan.stop();
|
||||
}
|
||||
if let Some(watch) = &project.tsc_watch {
|
||||
watch.stop();
|
||||
}
|
||||
project.documents.clear_workspace_edit_history();
|
||||
project.notebooks.stop_admission();
|
||||
project.agents.shutdown();
|
||||
@@ -693,6 +701,12 @@ impl Host {
|
||||
self.requests.begin(id)
|
||||
}
|
||||
|
||||
/// Settings › Tools › Download Mirrors › Use only the configured package registries: nothing
|
||||
/// is fetched from public package registries the user's tools weren't pointed at.
|
||||
pub fn configured_registries_only(&self) -> bool {
|
||||
self.global_settings.effective().tool_downloads.configured_registries_only
|
||||
}
|
||||
|
||||
pub fn begin_project_request(&self, window: &str, id: RequestId) -> CancellationToken {
|
||||
let token = self.begin_project_read_request(window, id);
|
||||
if self.project(window).is_ok_and(|p| !p.is_trusted()) {
|
||||
|
||||
@@ -380,6 +380,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
"Appearance",
|
||||
vec![
|
||||
act("editor.toggleZen", "Enter Distraction Free Mode"),
|
||||
act("view.toggleZenMode", "Enter Zen Mode"),
|
||||
act("window.toggleFullScreen", "Toggle Full Screen"),
|
||||
toggle("view.toggleCompactMode", "Compact Mode"),
|
||||
toggle("view.togglePresentationAssistant", "Presentation Assistant"),
|
||||
@@ -623,6 +624,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("run.debugContext", "Debug Context Configuration"),
|
||||
act("run.coverage", "Run with Coverage"),
|
||||
act("run.profile", "Profile"),
|
||||
act("profiler.openSnapshot", "Open Profiler Snapshot…"),
|
||||
act("run.stop", "Stop"),
|
||||
SEP,
|
||||
act("run.chooseConfig", "Run…"),
|
||||
|
||||
@@ -88,6 +88,13 @@ pub fn agent_set_command(host: &Host, window: &str, id: String, command: Option<
|
||||
host.project(window)?.agents.set_builtin_command(&id, command)
|
||||
}
|
||||
|
||||
/// Sets additional launch arguments for a built-in ACP agent; an empty list resets them.
|
||||
#[command(trust = trusted)]
|
||||
pub fn agent_set_additional_args(host: &Host, window: &str, id: String, args: Vec<String>) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.set_builtin_additional_args(&id, args)
|
||||
}
|
||||
|
||||
/// Environment variables built-in agent `id` starts with (saved in its agent file);
|
||||
/// an empty map clears them.
|
||||
#[command(trust = trusted)]
|
||||
@@ -178,6 +185,7 @@ pub async fn agent_registry_install(
|
||||
) -> IdeResult<()> {
|
||||
// The agent then shows in `agent_providers`.
|
||||
let paths = registry_paths(host);
|
||||
let public_npm_fallback = !host.configured_registries_only();
|
||||
let installing = Installing::begin(&id)?;
|
||||
let cancel = host.begin_request(request);
|
||||
// Also a background task of every project window, so it stays visible and can be
|
||||
@@ -204,7 +212,7 @@ pub async fn agent_registry_install(
|
||||
move || cancel.cancel()
|
||||
});
|
||||
report(None, None, false);
|
||||
let result = ide_agent::registry::install(&paths, &id, &cancel, &|e| {
|
||||
let result = ide_agent::registry::install(&paths, &id, public_npm_fallback, &cancel, &|e| {
|
||||
match &e {
|
||||
InstallEvent::Line { text } => report(Some(text.clone()), None, false),
|
||||
InstallEvent::Progress { fraction, message } => {
|
||||
@@ -1485,6 +1493,7 @@ ide_command::domain!(
|
||||
agent_rollback,
|
||||
agent_rollback_changes,
|
||||
agent_send_queued_now,
|
||||
agent_set_additional_args,
|
||||
agent_set_command,
|
||||
agent_shell,
|
||||
agent_set_config,
|
||||
|
||||
@@ -767,6 +767,7 @@ pub async fn maven_dependency_completion(
|
||||
use ide_build::maven::completion::{PomCompletionKind, local_options};
|
||||
let project = host.project(window)?;
|
||||
let cache = host.dependency_versions.clone();
|
||||
let central = !host.configured_registries_only();
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = host
|
||||
.blocking(move || {
|
||||
@@ -785,7 +786,10 @@ pub async fn maven_dependency_completion(
|
||||
// The local repository answers at once: Central gets `CENTRAL_WAIT`, then the
|
||||
// lookup finishes in the background and fills the cache for the next request.
|
||||
// Offline, behind a proxy or rate-limited, a failed fetch never fails completion.
|
||||
let remote = {
|
||||
// Only the configured package registries: the local repository alone.
|
||||
let remote = if !central {
|
||||
Vec::new()
|
||||
} else {
|
||||
let (cache, target) = (cache.clone(), target.clone());
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
|
||||
@@ -212,6 +212,8 @@ pub async fn dependency_versions(
|
||||
let project = host.project(window)?;
|
||||
let cache = host.dependency_versions.clone();
|
||||
let config_dir = host.config_dir.clone();
|
||||
// npm and crates.io are asked directly; `go` goes through the configured GOPROXY.
|
||||
let public_registries = !host.configured_registries_only();
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = host
|
||||
.blocking(move || {
|
||||
@@ -228,6 +230,9 @@ pub async fn dependency_versions(
|
||||
let versions = cache.versions(&source, &dependency.package, &cancel)?;
|
||||
return Ok(vec![DependencyVersions { dependency, versions, update: None }]);
|
||||
}
|
||||
if !public_registries {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
if snap.path.file_name().is_some_and(|name| name == "package.json") {
|
||||
let Some(dependency) = offset.and_then(|offset| npm::dependency_at(&snap.text, offset)) else {
|
||||
return Ok(Vec::new());
|
||||
@@ -310,6 +315,9 @@ pub async fn pypi_package(
|
||||
request: RequestId,
|
||||
) -> IdeResult<Option<pypi::PypiPackage>> {
|
||||
let url = pypi::project_url(name.trim()).ok_or_else(|| IdeError::invalid("not a package name"))?;
|
||||
if host.configured_registries_only() {
|
||||
return Ok(None);
|
||||
}
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = host
|
||||
.blocking(move || {
|
||||
@@ -334,6 +342,9 @@ pub async fn pypi_package(
|
||||
/// PyPI's name list, which the first search downloads and a search a day later refreshes.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn pypi_search(host: &Host, window: &str, query: String, request: RequestId) -> IdeResult<Vec<String>> {
|
||||
if host.configured_registries_only() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let names = host.pypi_names.clone();
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = host
|
||||
|
||||
@@ -922,7 +922,7 @@ pub async fn java_build_workspace(
|
||||
/// The JVM of OpenIDEA's JUnit runner for the module at `module`, given its resolved test classpath:
|
||||
/// the classpath with the runner and `junit-platform-launcher` of the engine's version (unless the
|
||||
/// classpath has one, or has JUnit 4 alone; from the engine's repository, else downloaded once from
|
||||
/// Maven Central), and,
|
||||
/// Maven Central unless only the configured package registries are allowed), and,
|
||||
/// for a Maven module, what its Surefire configuration gives the forked test JVM.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn java_junit_runner(
|
||||
@@ -935,6 +935,7 @@ pub async fn java_junit_runner(
|
||||
let project = host.project(window)?;
|
||||
let module = ide_core::project_roots::resolve(&project.root, &module);
|
||||
let data_dir = host.local_data_dir.clone();
|
||||
let registries_only = host.configured_registries_only();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let scope = workspace::scope_for(&project, &module)?;
|
||||
let model = load_launch_model(&scope);
|
||||
@@ -948,7 +949,9 @@ pub async fn java_junit_runner(
|
||||
let launcher = match ide_sdk::java::junit_launcher(&class_paths) {
|
||||
ide_sdk::java::JunitLauncher::OnClasspath | ide_sdk::java::JunitLauncher::Junit4 => None,
|
||||
ide_sdk::java::JunitLauncher::Found(path) => Some(path),
|
||||
ide_sdk::java::JunitLauncher::Missing(version) => Some(download_junit_launcher(&data_dir, &version)?),
|
||||
ide_sdk::java::JunitLauncher::Missing(version) => {
|
||||
Some(download_junit_launcher(&data_dir, &version, registries_only)?)
|
||||
}
|
||||
ide_sdk::java::JunitLauncher::NoPlatform => {
|
||||
return Err(IdeError::unavailable(
|
||||
"Neither JUnit 5 (junit-platform-engine) nor JUnit 4 is on the test classpath. To run these tests \
|
||||
@@ -1017,7 +1020,9 @@ fn junit_launch(
|
||||
}
|
||||
}
|
||||
|
||||
fn download_junit_launcher(data_dir: &Path, version: &str) -> IdeResult<PathBuf> {
|
||||
/// The launcher jar downloaded once from Maven Central; with only the configured package
|
||||
/// registries allowed (Settings › Tools › Download Mirrors), only one downloaded before.
|
||||
fn download_junit_launcher(data_dir: &Path, version: &str, registries_only: bool) -> IdeResult<PathBuf> {
|
||||
if version.is_empty() || !version.chars().all(|c| c.is_ascii_alphanumeric() || "._-".contains(c)) {
|
||||
return Err(IdeError::invalid(format!("Unexpected JUnit Platform version '{version}'")));
|
||||
}
|
||||
@@ -1026,6 +1031,14 @@ fn download_junit_launcher(data_dir: &Path, version: &str) -> IdeResult<PathBuf>
|
||||
if dest.is_file() {
|
||||
return Ok(dest);
|
||||
}
|
||||
if registries_only {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"{name} is not on the test classpath, and Settings › Tools › Download Mirrors allows only the \
|
||||
configured package registries, so it is not downloaded from Maven Central. Add \
|
||||
org.junit.platform:junit-platform-launcher to the test dependencies, or set Settings › Build Tools › \
|
||||
Maven › Run tests using to Maven."
|
||||
)));
|
||||
}
|
||||
std::fs::create_dir_all(dest.parent().expect("has a parent"))?;
|
||||
let url = format!("https://repo1.maven.org/maven2/org/junit/platform/junit-platform-launcher/{version}/{name}");
|
||||
let partial = dest.with_extension("jar.part");
|
||||
|
||||
@@ -7,7 +7,7 @@ use crate::Project;
|
||||
use ide_command::command;
|
||||
use ide_core::{DocId, IdeResult, IpcPath, LanguageId, Location, Pos};
|
||||
use ide_index::{ExtensionCount, FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
|
||||
use ide_language::{FileReference, WebReference};
|
||||
use ide_language::{CSS_VARIABLE, FileReference, WebReference};
|
||||
use ide_workspace::file_refs::{self, PathCompletion};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
@@ -25,6 +25,18 @@ pub struct WebGoto {
|
||||
|
||||
const MAX_WEB_TARGETS: usize = 200;
|
||||
|
||||
/// A custom property declaration (`--accent: #3b82f6`), for `var(--…)` completion and hover.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CssVariable {
|
||||
pub name: String,
|
||||
/// The declared value, whitespace collapsed.
|
||||
pub value: Option<String>,
|
||||
pub location: Location,
|
||||
}
|
||||
|
||||
const MAX_CSS_VARIABLES: usize = 5000;
|
||||
|
||||
/// A Python class definition and the base names written in its source. The UI builds a
|
||||
/// name → locations index from every class in the project (attached dependency roots
|
||||
/// included) to compute ↑ overrides / ↓ overridden gutter markers without a language
|
||||
@@ -185,6 +197,41 @@ pub async fn web_goto(host: &Host, window: &str, doc: DocId, pos: Pos) -> IdeRes
|
||||
.await
|
||||
}
|
||||
|
||||
/// Custom properties declared in `doc` (from its current text, first) and in the project's
|
||||
/// other stylesheets (from the index, so kept up to date as files change).
|
||||
#[command(trust = always)]
|
||||
pub async fn web_css_variables(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec<CssVariable>> {
|
||||
let project = host.project(window)?;
|
||||
let syntax = host.syntax();
|
||||
blocking(move || {
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
let own = if snap.large { Vec::new() } else { syntax.web_definitions(&snap.language, &snap.text) };
|
||||
let mut out: Vec<CssVariable> = own
|
||||
.into_iter()
|
||||
.filter(|t| t.kind == CSS_VARIABLE)
|
||||
.map(|t| CssVariable {
|
||||
name: t.name,
|
||||
value: t.container,
|
||||
location: Location { path: snap.path.clone(), range: t.range, uri: None },
|
||||
})
|
||||
.collect();
|
||||
out.extend(
|
||||
project
|
||||
.index
|
||||
.symbols_prefixed("--", CSS_VARIABLE, MAX_CSS_VARIABLES)
|
||||
.into_iter()
|
||||
.filter(|m| *m.path != *snap.path)
|
||||
.map(|m| CssVariable {
|
||||
name: m.name,
|
||||
value: m.container,
|
||||
location: Location { path: m.path, range: m.range, uri: None },
|
||||
}),
|
||||
);
|
||||
Ok(out)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// The file a Python import path (`a.b.c`, or `.x` relative to `from`) names; `None` when
|
||||
/// no project or content root has it.
|
||||
#[command(trust = always)]
|
||||
@@ -450,6 +497,7 @@ ide_command::domain!(
|
||||
recent_files,
|
||||
remove_recent,
|
||||
scope_files,
|
||||
web_css_variables,
|
||||
web_goto,
|
||||
web_unresolved_references,
|
||||
);
|
||||
@@ -22,6 +22,8 @@ pub struct ProjectInfo {
|
||||
pub workspace: Option<ide_workspace::workspace::Workspace>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub unity: Option<ide_workspace::unity::UnityProjectInfo>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub unreal: Option<ide_workspace::unreal::UnrealProjectInfo>,
|
||||
}
|
||||
|
||||
pub fn info(project: &Project) -> ProjectInfo {
|
||||
@@ -45,6 +47,7 @@ pub fn info(project: &Project) -> ProjectInfo {
|
||||
root: project.root.clone().into(),
|
||||
workspace,
|
||||
unity: ide_workspace::unity::detect(&project.root),
|
||||
unreal: ide_workspace::unreal::detect(&project.root),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,6 +128,11 @@ pub fn settings_set(
|
||||
if key == "terminal" || key.starts_with("terminal.") {
|
||||
super::term::apply_output_rate(host, window);
|
||||
}
|
||||
if "languages.typescript.watchProblems".starts_with(&key)
|
||||
&& let Some(watch) = host.project(window).ok().and_then(|p| p.tsc_watch.clone())
|
||||
{
|
||||
watch.apply(&host.runtime);
|
||||
}
|
||||
let sink = host.window_sink(window);
|
||||
sink.emit(IdeEvent::SettingsChanged { key });
|
||||
if let Some(root) = applied.roots_changed {
|
||||
|
||||
@@ -24,6 +24,12 @@ struct LogAccess {
|
||||
cache: PathBuf,
|
||||
}
|
||||
|
||||
fn external_log_of(host: &Host, window: &str, path: &Path) -> Option<std::sync::Arc<Repo>> {
|
||||
host.external_logs.read().get(host.owner_window(window)).and_then(|repos| {
|
||||
repos.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().components().count()).cloned()
|
||||
})
|
||||
}
|
||||
|
||||
/// Immutable Git objects exposed through the editor's ordinary read-only VFS.
|
||||
/// `encoding` re-decodes the blob with it ("Reload with Encoding") instead of
|
||||
/// the project's detection.
|
||||
@@ -81,9 +87,7 @@ async fn revision_text(
|
||||
encoding: Option<&str>,
|
||||
) -> IdeResult<Option<(String, &'static encoding_rs::Encoding, bool)>> {
|
||||
let project = host.project(window).ok();
|
||||
let external = host.external_logs.read().get(host.owner_window(window)).and_then(|rs| {
|
||||
rs.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().components().count()).cloned()
|
||||
});
|
||||
let external = external_log_of(host, window, path);
|
||||
let (path, rev, encoding) = (path.to_path_buf(), rev.to_owned(), encoding.map(str::to_owned));
|
||||
blocking(move || {
|
||||
fn with_repo<T>(
|
||||
@@ -622,9 +626,7 @@ pub async fn vcs_staging_line_hunks(
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_file_at(host: &Host, window: &str, path: PathBuf, rev: Option<String>) -> IdeResult<Option<String>> {
|
||||
let project = host.project(window).ok();
|
||||
let external = host.external_logs.read().get(host.owner_window(window)).and_then(|rs| {
|
||||
rs.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().components().count()).cloned()
|
||||
});
|
||||
let external = external_log_of(host, window, &path);
|
||||
blocking(move || {
|
||||
if let Some(project) = project {
|
||||
return project.with_log_backend_of(&path, |r| {
|
||||
@@ -640,14 +642,37 @@ pub async fn vcs_file_at(host: &Host, window: &str, path: PathBuf, rev: Option<S
|
||||
.await
|
||||
}
|
||||
|
||||
/// An image at the selected Git revision or index stage as a data URL, absent if the path is missing.
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_image_at(host: &Host, window: &str, path: PathBuf, rev: String) -> IdeResult<Option<String>> {
|
||||
let project = host.project(window).ok();
|
||||
let external = external_log_of(host, window, &path);
|
||||
blocking(move || {
|
||||
let mime = ide_vfs::image_mime(&path)
|
||||
.ok_or_else(|| ide_core::IdeError::invalid(format!("{} is not a supported image", path.display())))?;
|
||||
let read = |repo: &Repo| repo.file_bytes_at_bounded(&path, &rev, ide_vfs::MAX_IMAGE_SIZE as usize);
|
||||
let bytes = if let Some(project) = project {
|
||||
if !ide_vfs::on_local_drive(&path)
|
||||
&& external.is_none()
|
||||
&& !project.repos().all().iter().any(|repo| ide_vfs::same_share(repo.root(), &path))
|
||||
{
|
||||
return Err(ide_core::IdeError::invalid("image is not on a local drive or an opened share"));
|
||||
}
|
||||
project.with_log_repo_of(&path, read)?
|
||||
} else {
|
||||
read(external.as_deref().ok_or_else(|| ide_core::IdeError::unavailable("external Git log is not open"))?)?
|
||||
};
|
||||
Ok(bytes.map(|bytes| format!("data:{mime};base64,{}", ide_vfs::base64(&bytes))))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// The file's git mode at `rev` (`100644`, `100755`, `120000`…), `"WT"` for the
|
||||
/// worktree; `None` when absent there. Lets the diff viewer report a mode-only change.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn vcs_file_mode(host: &Host, window: &str, path: PathBuf, rev: Option<String>) -> IdeResult<Option<String>> {
|
||||
let project = host.project(window).ok();
|
||||
let external = host.external_logs.read().get(host.owner_window(window)).and_then(|rs| {
|
||||
rs.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().components().count()).cloned()
|
||||
});
|
||||
let external = external_log_of(host, window, &path);
|
||||
blocking(move || {
|
||||
if let Some(project) = project {
|
||||
return project.with_log_backend_of(&path, |r| r.file_mode_at(&path, rev.as_deref()));
|
||||
@@ -3200,6 +3225,7 @@ ide_command::domain!(
|
||||
vcs_discard,
|
||||
vcs_edit_remote,
|
||||
vcs_file_at,
|
||||
vcs_image_at,
|
||||
vcs_file_mode,
|
||||
vcs_diff_entries,
|
||||
vcs_git_version,
|
||||
|
||||
@@ -686,6 +686,9 @@ pub(super) struct Shared {
|
||||
net_prompts: Mutex<HashMap<String, Option<Instant>>>,
|
||||
pub net_hosts_session_only: AtomicBool,
|
||||
session_net_hosts: Mutex<HashMap<String, BTreeSet<String>>>,
|
||||
/// Setting-derived approvals kept for the session only (remote hosts),
|
||||
/// plugin → `net:setting:` grant → its approved host.
|
||||
pub(super) session_setting_hosts: Mutex<HashMap<String, BTreeMap<String, String>>>,
|
||||
pub(super) next_prompt: AtomicU64,
|
||||
pub(super) run_configurations: super::run_detectors::DynamicConfigurations,
|
||||
pub(super) run_targets: Mutex<super::run_targets::Targets>,
|
||||
@@ -733,6 +736,29 @@ pub(super) struct Shared {
|
||||
/// A window's log tabs of one plugin: key → what it runs, oldest first.
|
||||
type LogTabs = Vec<(String, ide_plugin::ServiceLog)>;
|
||||
|
||||
/// The settings key a `net:setting:` grant derives its host from.
|
||||
fn setting_key(cap: &Capability) -> String {
|
||||
match cap {
|
||||
Capability::NetSetting { key, .. } => key.clone(),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The host a setting value names: a bare host, or a URL the user pasted
|
||||
/// (`https://jira.corp.example/`), checked with the manifest host rules — a `*`
|
||||
/// is refused. `Ok(None)` when the value is empty (the setting is cleared).
|
||||
pub(super) fn setting_host(value: &str) -> Result<Option<String>, String> {
|
||||
let value = value.trim();
|
||||
if value.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let host =
|
||||
if value.contains("://") { ide_plugin::net_host(value)? } else { value.trim_end_matches('.').to_owned() };
|
||||
ide_extension::manifest_host(&host)
|
||||
.map(Some)
|
||||
.map_err(|_| format!("{value:?} is not a host (example.com) or a URL (https://example.com/)"))
|
||||
}
|
||||
|
||||
/// Log tabs a plugin's code may have open in one window; opening more forgets
|
||||
/// the oldest (that tab can no longer start its program).
|
||||
const MAX_LOG_TABS: usize = 32;
|
||||
@@ -771,6 +797,7 @@ impl Shared {
|
||||
net_prompts: Mutex::default(),
|
||||
net_hosts_session_only: AtomicBool::new(false),
|
||||
session_net_hosts: Mutex::default(),
|
||||
session_setting_hosts: Mutex::default(),
|
||||
next_prompt: AtomicU64::new(1),
|
||||
run_configurations: Arc::default(),
|
||||
run_targets: Mutex::default(),
|
||||
@@ -1038,6 +1065,7 @@ impl Shared {
|
||||
self.withdraw_prompts(plugin);
|
||||
self.net_prompts.lock().remove(plugin);
|
||||
self.session_net_hosts.lock().remove(plugin);
|
||||
self.session_setting_hosts.lock().remove(plugin);
|
||||
let removed: Vec<(Option<String>, String)> = {
|
||||
let mut contexts = self.contexts.lock();
|
||||
let keys: Vec<_> = contexts.keys().filter(|(_, p, _)| p == plugin).cloned().collect();
|
||||
@@ -1556,6 +1584,51 @@ fn project_subdirectory(root: &Path, cwd: &str) -> Result<PathBuf, HostError> {
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
impl PluginApi {
|
||||
/// The value of `key` the user set for this plugin, as a plain string
|
||||
/// (`None` when unset or not a string).
|
||||
pub(super) fn setting_value(&self, key: &str) -> Option<String> {
|
||||
let raw = self.setting(None, key)?;
|
||||
serde_json::from_str::<String>(&raw).ok()
|
||||
}
|
||||
|
||||
/// The plugin's `net:setting:` grants with their hosts: the approved host
|
||||
/// while the setting still holds it, and the pending one to approve
|
||||
/// otherwise (`None` when the value is unset or not a host).
|
||||
pub(super) fn net_setting_hosts(&self, subject: &Subject) -> Vec<(Capability, Option<String>, Option<String>)> {
|
||||
let derived: Vec<Capability> = self
|
||||
.pkg
|
||||
.manifest
|
||||
.capabilities
|
||||
.all()
|
||||
.filter(|c| matches!(c, Capability::NetSetting { .. }))
|
||||
.cloned()
|
||||
.collect();
|
||||
if derived.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let ledger = self.shared.ledger.lock();
|
||||
let grant = ledger.get(subject).filter(|g| g.confirmed);
|
||||
let session = self.shared.session_setting_hosts.lock().get(self.id()).cloned().unwrap_or_default();
|
||||
derived
|
||||
.into_iter()
|
||||
.map(|cap| {
|
||||
let current = self.setting_value(&setting_key(&cap)).and_then(|v| setting_host(&v).ok()).flatten();
|
||||
let record = grant.and_then(|g| g.setting_hosts.get(&cap.to_string())).map(String::as_str);
|
||||
let session_host = session.get(&cap.to_string()).map(String::as_str);
|
||||
// An approval covers requests only while the setting still holds it.
|
||||
let approved = [record, session_host]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find(|host| current.as_deref() == Some(host))
|
||||
.map(str::to_owned);
|
||||
let pending = current.filter(|host| approved.as_deref() != Some(host));
|
||||
(cap, approved, pending)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl HostApi for PluginApi {
|
||||
fn database_upsert(&self, root: &Path, source: ide_plugin::PluginDataSource) -> Result<(), HostError> {
|
||||
let (host, db) = self.database_host(root)?;
|
||||
@@ -2798,6 +2871,16 @@ impl HostApi for PluginApi {
|
||||
return Ok(None);
|
||||
}
|
||||
let host = host.trim_end_matches('.').to_ascii_lowercase();
|
||||
// A host the plugin derives from a setting is approved in Settings,
|
||||
// not asked about here: pending or revoked, it stays denied without a
|
||||
// dialog (#3809).
|
||||
if self.pkg.manifest.capabilities.all().any(|cap| {
|
||||
matches!(cap, Capability::NetSetting { http: false, key: _ })
|
||||
&& self.setting_value(&setting_key(cap)).and_then(|v| setting_host(&v).ok()).flatten().as_deref()
|
||||
== Some(host.as_str())
|
||||
}) {
|
||||
return Ok(None);
|
||||
}
|
||||
{
|
||||
let ledger = self.shared.ledger.lock();
|
||||
if let Some(grant) = ledger.get(subject)
|
||||
|
||||
@@ -700,7 +700,10 @@ mod tests {
|
||||
// tampered package — and the official host must still be asked.
|
||||
let candidates = mirror::candidates(
|
||||
"https://github.com/acme/hello/releases/download/v1/acme.hello-1.0.0.oiplugin",
|
||||
&ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() },
|
||||
&ide_core::settings::ToolDownloadSettings {
|
||||
github_mirror: "https://gh-proxy.com/".into(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let asked: std::cell::RefCell<Vec<usize>> = std::cell::RefCell::new(Vec::new());
|
||||
let picked = try_sources(&candidates, |index, candidate| {
|
||||
@@ -731,7 +734,10 @@ mod tests {
|
||||
let url = "https://github.com/acme/hello/releases/download/v1/acme.hello-1.0.0.oiplugin";
|
||||
let through = mirror::candidates(
|
||||
url,
|
||||
&ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() },
|
||||
&ide_core::settings::ToolDownloadSettings {
|
||||
github_mirror: "https://gh-proxy.com/".into(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
assert_eq!(through.len(), 2);
|
||||
assert_eq!(through[0].url, format!("https://gh-proxy.com/{url}"));
|
||||
@@ -741,7 +747,10 @@ mod tests {
|
||||
// A local index's own package is not on GitHub: no prefix may carry it.
|
||||
let local = mirror::candidates(
|
||||
"/srv/market/a.oiplugin",
|
||||
&ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() },
|
||||
&ide_core::settings::ToolDownloadSettings {
|
||||
github_mirror: "https://gh-proxy.com/".into(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
assert_eq!(local.len(), 1);
|
||||
assert_eq!(local[0].url, "/srv/market/a.oiplugin");
|
||||
|
||||
@@ -1174,6 +1174,92 @@ impl PluginHost {
|
||||
self.info_of(id)
|
||||
}
|
||||
|
||||
/// Approves the host the plugin's `net:setting:<key>` grant derives from
|
||||
/// the setting's value right now: the dialog when the user applies the
|
||||
/// value in Settings, or the pending row's Approve action. `expected` is
|
||||
/// the host the user was shown: when the setting changed since (the plugin
|
||||
/// can write its own settings), nothing is approved. On a remote host the
|
||||
/// approval is kept for the session only, like `net:ask` (#3809).
|
||||
pub fn approve_net_setting(&self, id: &str, setting: &str, http: bool, expected: &str) -> IdeResult<PluginInfo> {
|
||||
let _guard = self.lifecycle.lock();
|
||||
let plugin = self.get(id)?;
|
||||
self.check_not_uninstalling(&plugin)?;
|
||||
let cap = Capability::NetSetting { http, key: setting.to_owned() };
|
||||
if !plugin.manifest().declares(&cap) {
|
||||
return Err(IdeError::invalid(format!("plugin {id:?} does not declare {cap}")));
|
||||
}
|
||||
let api = api::PluginApi { pkg: plugin.pkg.clone(), shared: self.shared.clone() };
|
||||
let value = api
|
||||
.setting_value(setting)
|
||||
.ok_or_else(|| IdeError::invalid(format!("setting {setting:?} holds no value")))?;
|
||||
let host = api::setting_host(&value)
|
||||
.map_err(IdeError::invalid)?
|
||||
.ok_or_else(|| IdeError::invalid(format!("setting {setting:?} holds no host")))?;
|
||||
if host != expected {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"setting {setting:?} now holds {host}, not {expected}: approve the new value instead"
|
||||
)));
|
||||
}
|
||||
let session_only = self.shared.net_hosts_session_only.load(std::sync::atomic::Ordering::Relaxed);
|
||||
if !session_only {
|
||||
let mut ledger = self.ledger.lock();
|
||||
if !ledger.remember_setting_host(&plugin.subject(), &cap, &host) {
|
||||
return Err(IdeError::invalid(format!("plugin {id:?} does not have {cap} granted")));
|
||||
}
|
||||
self.save_ledger(&ledger);
|
||||
}
|
||||
self.stop(&plugin);
|
||||
if session_only {
|
||||
self.shared.session_setting_hosts.lock().entry(id.to_owned()).or_default().insert(cap.to_string(), host);
|
||||
}
|
||||
if !self.state.lock().disabled.contains(id) {
|
||||
self.start(&plugin);
|
||||
}
|
||||
// Plugins that need this one follow it: running again, or blocked while it can't run.
|
||||
self.settle_dependents(id);
|
||||
self.changed();
|
||||
self.info_of(id)
|
||||
}
|
||||
|
||||
/// The host a `net:setting:<key>` grant derives from `value` (a bare host
|
||||
/// or a URL), for the approval dialog; an error refuses the value.
|
||||
pub fn net_setting_host(&self, id: &str, setting: &str, value: &str) -> IdeResult<String> {
|
||||
let plugin = self.get(id)?;
|
||||
let cap = Capability::NetSetting { http: false, key: setting.to_owned() };
|
||||
if !plugin.manifest().declares(&cap)
|
||||
&& !plugin.manifest().declares(&Capability::NetSetting { http: true, key: setting.to_owned() })
|
||||
{
|
||||
return Err(IdeError::invalid(format!("plugin {id:?} does not declare a setting grant for {setting:?}")));
|
||||
}
|
||||
api::setting_host(value)
|
||||
.map_err(IdeError::invalid)?
|
||||
.ok_or_else(|| IdeError::invalid(format!("{value:?} holds no host")))
|
||||
}
|
||||
|
||||
/// Drops the approved host of a `net:setting:<key>` grant (its revoke
|
||||
/// action, or the setting's value being cleared). Nothing recorded: still
|
||||
/// fine, the state is already as asked.
|
||||
pub fn forget_net_setting(&self, id: &str, setting: &str, http: bool) -> IdeResult<PluginInfo> {
|
||||
let _guard = self.lifecycle.lock();
|
||||
let plugin = self.get(id)?;
|
||||
self.check_not_uninstalling(&plugin)?;
|
||||
let cap = Capability::NetSetting { http, key: setting.to_owned() };
|
||||
{
|
||||
let mut ledger = self.ledger.lock();
|
||||
ledger.forget_setting_host(&plugin.subject(), &cap);
|
||||
self.save_ledger(&ledger);
|
||||
}
|
||||
self.shared.session_setting_hosts.lock().get_mut(id).map(|hosts| hosts.remove(&cap.to_string()));
|
||||
self.stop(&plugin);
|
||||
if !self.state.lock().disabled.contains(id) {
|
||||
self.start(&plugin);
|
||||
}
|
||||
// Plugins that need this one follow it: running again, or blocked while it can't run.
|
||||
self.settle_dependents(id);
|
||||
self.changed();
|
||||
self.info_of(id)
|
||||
}
|
||||
|
||||
/// Grants or revokes one declared capability (Settings › Plugins › Permissions).
|
||||
/// Revoking a required one stops the plugin until consent is given again.
|
||||
pub fn set_capability(&self, id: &str, capability: &str, granted: bool) -> IdeResult<PluginInfo> {
|
||||
@@ -1191,6 +1277,10 @@ impl PluginHost {
|
||||
return Err(IdeError::invalid(format!("plugin {id:?} has not been confirmed yet")));
|
||||
}
|
||||
ledger.set(&subject, &cap, granted);
|
||||
if !granted {
|
||||
// A session-only approval of a setting-derived host goes with its grant.
|
||||
self.shared.session_setting_hosts.lock().get_mut(id).map(|hosts| hosts.remove(&cap.to_string()));
|
||||
}
|
||||
if granted
|
||||
&& cap == Capability::JavaAgent
|
||||
&& let Some(jar) = agent_jar_grant(plugin.manifest(), plugin.dir())
|
||||
@@ -2748,6 +2838,7 @@ impl PluginHost {
|
||||
fn prepare(&self, pkg: &Package) -> Result<ide_extension::PreparedSet, String> {
|
||||
plugin_icon(pkg)?;
|
||||
let mut set = self.registry.prepare(pkg)?;
|
||||
check_setting_grants(pkg)?;
|
||||
for icon in [&pkg.manifest.icon, &pkg.manifest.icon_dark].into_iter().flatten() {
|
||||
if !set.files.contains(icon) {
|
||||
set.files.push(icon.clone());
|
||||
@@ -2906,7 +2997,7 @@ impl PluginHost {
|
||||
meta.declared_extra = set.capabilities.clone();
|
||||
meta.error = None;
|
||||
}
|
||||
let (granted, pending) = match decision {
|
||||
let (mut granted, pending) = match decision {
|
||||
Decision::Allowed { granted, pending } => (granted, pending),
|
||||
Decision::NeedsConfirmation { new, .. } => {
|
||||
let mut meta = plugin.meta.lock();
|
||||
@@ -2919,6 +3010,19 @@ impl PluginHost {
|
||||
if let Err(e) = self.registry.commit(set) {
|
||||
return self.set_failed(plugin, e);
|
||||
}
|
||||
// Setting-derived network grants materialize their approved host while
|
||||
// the setting holds it: `net:setting:server` acts as `net:<host>`, so
|
||||
// the request path keeps its rules (`net_capability` / `covers`).
|
||||
let api = api::PluginApi { pkg: plugin.pkg.clone(), shared: self.shared.clone() };
|
||||
for (cap, approved, _pending) in api.net_setting_hosts(&plugin.subject()) {
|
||||
if let Some(host) = approved {
|
||||
match cap {
|
||||
Capability::NetSetting { http: false, key: _ } => granted.push(Capability::Net(host)),
|
||||
Capability::NetSetting { http: true, key: _ } => granted.push(Capability::NetHttp(host)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
{
|
||||
let mut meta = plugin.meta.lock();
|
||||
meta.granted = granted;
|
||||
@@ -3374,6 +3478,21 @@ impl PluginHost {
|
||||
.filter(|g| g.confirmed && g.has(&Capability::NetAsk) && m.declares(&Capability::NetAsk))
|
||||
.map(|g| g.net_hosts.iter().cloned().collect())
|
||||
.unwrap_or_default();
|
||||
// Setting-derived hosts, listed next to the `net:ask` ones: the
|
||||
// approved host, and a pending one the setting now holds.
|
||||
let net_settings = if m.capabilities.all().any(|c| matches!(c, Capability::NetSetting { .. })) {
|
||||
let api = api::PluginApi { pkg: p.pkg.clone(), shared: self.shared.clone() };
|
||||
api.net_setting_hosts(&p.subject())
|
||||
.into_iter()
|
||||
.filter(|(cap, ..)| grant.as_ref().is_some_and(|g| g.confirmed && g.has(cap)))
|
||||
.map(|(cap, approved, pending)| {
|
||||
let Capability::NetSetting { http, key } = cap else { unreachable!() };
|
||||
types::PluginNetSetting { setting: key, http, host: approved, pending }
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
PluginInfo {
|
||||
id: m.id.clone(),
|
||||
name: m.name.clone(),
|
||||
@@ -3414,6 +3533,7 @@ impl PluginHost {
|
||||
has_code: m.wasm.is_some(),
|
||||
capabilities,
|
||||
net_hosts,
|
||||
net_settings,
|
||||
contributions: self.registry.contributions(&m.id),
|
||||
activation: m.activation.iter().map(ToString::to_string).collect(),
|
||||
warnings: meta.warnings.clone(),
|
||||
@@ -3442,6 +3562,37 @@ fn agent_jar_grant(manifest: &Manifest, dir: &Path) -> Option<BinaryGrant> {
|
||||
Some(BinaryGrant { path, hash })
|
||||
}
|
||||
|
||||
/// `net:setting:<key>` grants name a `string` setting of the plugin's own
|
||||
/// settings schema; checked like the other manifest checks, at install and
|
||||
/// start (#3809).
|
||||
fn check_setting_grants(pkg: &Package) -> Result<(), String> {
|
||||
let derived: Vec<&Capability> =
|
||||
pkg.manifest.capabilities.all().filter(|c| matches!(c, Capability::NetSetting { .. })).collect();
|
||||
if derived.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut strings = BTreeSet::new();
|
||||
for decl in pkg.manifest.declarations(ui_points::SETTINGS) {
|
||||
let decl = ui_points::settings(pkg, decl)?;
|
||||
for property in decl.json.get("properties").and_then(|p| p.as_array()).into_iter().flatten() {
|
||||
if property.get("type").and_then(|t| t.as_str()) == Some("string")
|
||||
&& let Some(key) = property.get("key").and_then(|k| k.as_str())
|
||||
{
|
||||
strings.insert(key.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
for cap in derived {
|
||||
let Capability::NetSetting { http: _, key } = cap else { continue };
|
||||
if !strings.contains(key.as_str()) {
|
||||
return Err(format!(
|
||||
"capability `{cap}` needs a `string` setting {key:?} in the plugin's own settings schema"
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Consent / Settings: surface exact contributed JVM flags on the `java.agent` permission.
|
||||
fn annotate_java_agent_vm_options(capabilities: &mut [CapabilityInfo], manifest: &Manifest) {
|
||||
let opts = java_agents::declared_vm_options(manifest);
|
||||
|
||||
@@ -76,6 +76,20 @@ pub struct PluginJavaAgent {
|
||||
pub executor: Option<String>,
|
||||
}
|
||||
|
||||
/// A `net:setting:` grant's host for Settings › Plugins: the approved one while the setting holds it, else the pending one.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginNetSetting {
|
||||
/// The setting key the host comes from (`server` of `net:setting:server`).
|
||||
pub setting: String,
|
||||
/// Plain HTTP (`net.http:setting:`) instead of HTTPS (and loopback HTTP).
|
||||
pub http: bool,
|
||||
/// The approved host, while the setting still holds it.
|
||||
pub host: Option<String>,
|
||||
/// The host the setting holds now when it is not the approved one.
|
||||
pub pending: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginInfo {
|
||||
@@ -101,6 +115,8 @@ pub struct PluginInfo {
|
||||
/// HTTPS hosts the user allowed through `net:ask` ("always allow"),
|
||||
/// none of them declared by the manifest; each can be revoked.
|
||||
pub net_hosts: Vec<String>,
|
||||
/// Setting-derived hosts (`net:setting:`), approved in Settings, listed next to the `net:ask` ones.
|
||||
pub net_settings: Vec<PluginNetSetting>,
|
||||
/// What it contributes while live (point + label).
|
||||
pub contributions: Vec<ContributionInfo>,
|
||||
/// `activation` events of the manifest.
|
||||
|
||||
@@ -73,6 +73,7 @@ pub struct Project {
|
||||
pub(crate) widget_preview: ide_flutter::ToolServer,
|
||||
pub(crate) kotlin_bridge: Option<Arc<crate::kotlin_bridge::KotlinBridge>>,
|
||||
pub(crate) phpstan: Option<Arc<crate::phpstan::Phpstan>>,
|
||||
pub(crate) tsc_watch: Option<Arc<crate::tsc_watch::TscWatch>>,
|
||||
pub(crate) watcher: Arc<Watcher>,
|
||||
/// Watchers of the Project Structure content roots outside the project folder.
|
||||
pub(crate) content_watchers: Mutex<Vec<(PathBuf, Watcher)>>,
|
||||
@@ -207,7 +208,9 @@ impl Host {
|
||||
let root = member.as_ref().unwrap_or(window_root);
|
||||
ide_sdk::apply::server_launch_overrides(cfg, &effective);
|
||||
ide_sdk::apply::configure_server(cfg, root, server_root, &effective);
|
||||
crate::ts_code_style::configure(cfg, server_root, &effective);
|
||||
ide_sdk::apply::configure_vue_module_resolution(cfg, &data_dir);
|
||||
ide_sdk::apply::configure_path_aliases(cfg, server_root, &data_dir);
|
||||
let container_python = effective.languages.python.run_target().is_some();
|
||||
crate::ops::sdk::container_python::configure_server(cfg, &data_dir, root, &effective);
|
||||
// Attached dependency projects are source, so basedpyright/Pyright should
|
||||
@@ -396,6 +399,8 @@ impl Host {
|
||||
trusted.clone(),
|
||||
);
|
||||
documents.add_observer(phpstan.clone());
|
||||
let tsc_watch = crate::tsc_watch::TscWatch::new(root.clone(), settings.clone(), sink.clone(), trusted.clone());
|
||||
documents.add_observer(tsc_watch.clone());
|
||||
let repos = Arc::new(RwLock::new(Repos::enclosing(&root)?));
|
||||
for repo in repos.read().all() {
|
||||
repo.set_execution_allowed(trusted.load(Ordering::Acquire));
|
||||
@@ -690,6 +695,7 @@ impl Host {
|
||||
notebooks,
|
||||
kotlin_bridge: Some(kotlin_bridge),
|
||||
phpstan: Some(phpstan),
|
||||
tsc_watch: Some(tsc_watch),
|
||||
watcher,
|
||||
content_watchers: Mutex::new(content_watchers),
|
||||
lsp_watchers: Mutex::new(Vec::new()),
|
||||
@@ -750,6 +756,9 @@ impl Host {
|
||||
if let Some(phpstan) = &project.phpstan {
|
||||
phpstan.start(&self.runtime);
|
||||
}
|
||||
if let Some(watch) = &project.tsc_watch {
|
||||
watch.apply(&self.runtime);
|
||||
}
|
||||
if let Some(cmd) = post_start {
|
||||
self.environment.spawn_post_start(cmd, project.root.clone(), project.sink.clone());
|
||||
}
|
||||
@@ -950,6 +959,7 @@ impl Host {
|
||||
notebooks,
|
||||
kotlin_bridge: None,
|
||||
phpstan: None,
|
||||
tsc_watch: None,
|
||||
watcher: Arc::new(watcher),
|
||||
content_watchers: Mutex::new(Vec::new()),
|
||||
lsp_watchers: Mutex::new(Vec::new()),
|
||||
|
||||
@@ -267,6 +267,9 @@ impl crate::Host {
|
||||
if let Some(phpstan) = &project.phpstan {
|
||||
phpstan.interrupt();
|
||||
}
|
||||
if let Some(watch) = &project.tsc_watch {
|
||||
watch.apply(&self.runtime);
|
||||
}
|
||||
if !trusted {
|
||||
if let Some(plugins) = self.plugin_host() {
|
||||
plugins.withdraw_project_run_targets(&project.root);
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
//! Editor › Code Style › JavaScript / TypeScript (Spaces, Punctuation) as the TypeScript
|
||||
//! servers' `typescript.format.*` / `typescript.preferences.*` settings (`javascript.*` for
|
||||
//! JavaScript and JSX). tsserver applies them to Reformat Code and to the code it writes:
|
||||
//! quick fixes, auto-imports, refactorings and organize imports.
|
||||
|
||||
use ide_core::editor_settings::LanguageCodeStyle;
|
||||
use ide_core::settings::Settings;
|
||||
use ide_language::LanguageServerConfig;
|
||||
use ide_workspace::EditorConfig;
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
const SERVERS: [&str; 2] = ["vtsls", "typescript-language-server"];
|
||||
|
||||
/// tsserver's space options the Spaces tab sets, with the IntelliJ `.editorconfig` property
|
||||
/// (`ij_<language>_<name>`) that sets the same thing.
|
||||
const SPACES: [(&str, Option<&str>); 14] = [
|
||||
("insertSpaceAfterCommaDelimiter", Some("space_after_comma")),
|
||||
("insertSpaceAfterSemicolonInForStatements", Some("space_after_semicolon")),
|
||||
("insertSpaceBeforeAndAfterBinaryOperators", None),
|
||||
("insertSpaceAfterKeywordsInControlFlowStatements", None),
|
||||
("insertSpaceAfterFunctionKeywordForAnonymousFunctions", Some("space_before_function_left_parenth")),
|
||||
("insertSpaceBeforeFunctionParenthesis", Some("space_before_method_parentheses")),
|
||||
("insertSpaceAfterConstructor", None),
|
||||
("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis", None),
|
||||
("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets", Some("spaces_within_brackets")),
|
||||
("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces", Some("spaces_within_object_literal_braces")),
|
||||
("insertSpaceAfterOpeningAndBeforeClosingEmptyBraces", None),
|
||||
("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces", Some("spaces_within_interpolation_expressions")),
|
||||
("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces", None),
|
||||
("insertSpaceAfterTypeAssertion", None),
|
||||
];
|
||||
|
||||
/// Adds the code style of JavaScript and TypeScript to a TypeScript server's settings. A file's
|
||||
/// `.editorconfig` comes first, as in the editor (resolved for the server root's `index.ts` /
|
||||
/// `index.js`: the servers take one configuration per project); the server's own settings win.
|
||||
pub fn configure(cfg: &mut LanguageServerConfig, server_root: &Path, settings: &Settings) {
|
||||
if !SERVERS.contains(&cfg.name.as_str()) {
|
||||
return;
|
||||
}
|
||||
let code_style = &settings.editor.code_style;
|
||||
let editorconfig = code_style.editorconfig.then(EditorConfig::new);
|
||||
let mut layer = Map::new();
|
||||
for (language, ext) in [("typescript", "ts"), ("javascript", "js")] {
|
||||
let pairs = editorconfig
|
||||
.as_ref()
|
||||
.and_then(|e| e.resolve_pairs(&server_root.join(format!("index.{ext}"))))
|
||||
.unwrap_or_default();
|
||||
let section = section(language, code_style.languages.get(language), &pairs);
|
||||
if !section.is_empty() {
|
||||
layer.insert(language.into(), Value::Object(section));
|
||||
}
|
||||
}
|
||||
if layer.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut merged = Value::Object(layer);
|
||||
if let Some(own) = cfg.settings.take() {
|
||||
ide_sdk::apply::merge(&mut merged, own);
|
||||
}
|
||||
cfg.settings = Some(merged);
|
||||
}
|
||||
|
||||
/// The `format` and `preferences` of one language's section.
|
||||
fn section(
|
||||
language: &str,
|
||||
style: Option<&LanguageCodeStyle>,
|
||||
editorconfig: &HashMap<String, String>,
|
||||
) -> Map<String, Value> {
|
||||
let get = |key: &str| editorconfig.get(key).map(|v| v.to_ascii_lowercase());
|
||||
let flag = |name: &str| match get(&format!("ij_{language}_{name}")).as_deref() {
|
||||
Some("true") => Some(true),
|
||||
Some("false") => Some(false),
|
||||
_ => None,
|
||||
};
|
||||
let pick = |value: Option<&String>, allowed: &[&str]| value.filter(|v| allowed.contains(&v.as_str())).cloned();
|
||||
|
||||
let mut format = Map::new();
|
||||
for (key, ij) in SPACES {
|
||||
if let Some(on) = ij.and_then(flag).or_else(|| style.and_then(|s| s.spaces.get(key).copied())) {
|
||||
format.insert(key.into(), json!(on));
|
||||
}
|
||||
}
|
||||
let semicolons = flag("use_semicolon_after_statement")
|
||||
.map(|on| if on { "insert" } else { "remove" }.to_owned())
|
||||
.or_else(|| pick(style.and_then(|s| s.semicolons.as_ref()), &["ignore", "insert", "remove"]));
|
||||
if let Some(semicolons) = semicolons {
|
||||
format.insert("semicolons".into(), json!(semicolons));
|
||||
}
|
||||
let quotes = pick(get("quote_type").as_ref(), &["auto", "single", "double"])
|
||||
.or_else(|| flag("use_double_quotes").map(|on| if on { "double" } else { "single" }.to_owned()))
|
||||
.or_else(|| pick(style.and_then(|s| s.quotes.as_ref()), &["auto", "single", "double"]));
|
||||
|
||||
let mut section = Map::new();
|
||||
if !format.is_empty() {
|
||||
section.insert("format".into(), Value::Object(format));
|
||||
}
|
||||
// vtsls reads `quoteStyle` (VS Code's name), typescript-language-server tsserver's `quotePreference`.
|
||||
if let Some(quotes) = quotes {
|
||||
section.insert("preferences".into(), json!({ "quoteStyle": quotes, "quotePreference": quotes }));
|
||||
}
|
||||
section
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn server(name: &str) -> LanguageServerConfig {
|
||||
serde_json::from_value(json!({ "name": name, "command": name })).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_style_reaches_typescript_and_javascript_sections() {
|
||||
let mut settings = Settings::default();
|
||||
let ts = LanguageCodeStyle {
|
||||
semicolons: Some("remove".into()),
|
||||
quotes: Some("single".into()),
|
||||
spaces: [("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces".into(), false)].into(),
|
||||
..Default::default()
|
||||
};
|
||||
settings.editor.code_style.languages.insert("typescript".into(), ts);
|
||||
let js = LanguageCodeStyle { semicolons: Some("insert".into()), ..Default::default() };
|
||||
settings.editor.code_style.languages.insert("javascript".into(), js);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut cfg = server("vtsls");
|
||||
cfg.settings = Some(json!({ "typescript": { "preferences": { "quoteStyle": "double" } } }));
|
||||
configure(&mut cfg, dir.path(), &settings);
|
||||
assert_eq!(
|
||||
cfg.settings.unwrap(),
|
||||
json!({
|
||||
"typescript": {
|
||||
"format": { "semicolons": "remove", "insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": false },
|
||||
// The server's own settings win.
|
||||
"preferences": { "quoteStyle": "double", "quotePreference": "single" },
|
||||
},
|
||||
"javascript": { "format": { "semicolons": "insert" } },
|
||||
})
|
||||
);
|
||||
|
||||
let mut eslint = server("eslint");
|
||||
configure(&mut eslint, dir.path(), &settings);
|
||||
assert_eq!(eslint.settings, None);
|
||||
let mut untouched = server("vtsls");
|
||||
configure(&mut untouched, dir.path(), &Settings::default());
|
||||
assert_eq!(untouched.settings, None, "nothing set: the server's defaults");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editorconfig_comes_first() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(
|
||||
dir.path().join(".editorconfig"),
|
||||
"root = true\n[*.ts]\nquote_type = double\nij_typescript_use_semicolon_after_statement = false\n\
|
||||
ij_typescript_space_after_comma = false\n[*.js]\nij_javascript_use_double_quotes = false\n",
|
||||
)
|
||||
.unwrap();
|
||||
let mut settings = Settings::default();
|
||||
let ts = LanguageCodeStyle {
|
||||
semicolons: Some("insert".into()),
|
||||
quotes: Some("single".into()),
|
||||
..Default::default()
|
||||
};
|
||||
settings.editor.code_style.languages.insert("typescript".into(), ts);
|
||||
let mut cfg = server("typescript-language-server");
|
||||
configure(&mut cfg, dir.path(), &settings);
|
||||
let s = cfg.settings.unwrap();
|
||||
assert_eq!(
|
||||
s["typescript"]["format"],
|
||||
json!({ "semicolons": "remove", "insertSpaceAfterCommaDelimiter": false })
|
||||
);
|
||||
assert_eq!(s["typescript"]["preferences"]["quotePreference"], "double");
|
||||
assert_eq!(s["javascript"]["preferences"]["quoteStyle"], "single");
|
||||
|
||||
settings.editor.code_style.editorconfig = false;
|
||||
let mut cfg = server("vtsls");
|
||||
configure(&mut cfg, dir.path(), &settings);
|
||||
let s = cfg.settings.unwrap();
|
||||
assert_eq!(s["typescript"]["format"], json!({ "semicolons": "insert" }));
|
||||
assert_eq!(s.get("javascript"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
//! Problems › TypeScript project errors (`languages.typescript.watchProblems`): the project's own
|
||||
//! `tsc --watch` per root `tsconfig.json` -> `tsc` diagnostics. Files open in an editor keep only
|
||||
//! the language server's errors, so the watcher's are held back for them until they close.
|
||||
|
||||
use ide_core::{CancellationToken, Diagnostic, IdeEvent, SharedSink};
|
||||
use ide_workspace::SettingsStore;
|
||||
use ide_workspace::documents::{DocumentInfo, DocumentObserver};
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
const SOURCE: &str = "tsc";
|
||||
/// How deep below the project the walk looks for `tsconfig.json` (`apps/web/tsconfig.json` is 3).
|
||||
const MAX_DEPTH: usize = 4;
|
||||
/// Folders whose configurations are not the project's own: test inputs and samples, often
|
||||
/// broken on purpose.
|
||||
const SKIPPED: [&str; 6] = ["node_modules", "fixtures", "__fixtures__", "testdata", "examples", "example"];
|
||||
|
||||
/// The `tsconfig.json` files of the project, without the ones in ignored (`.gitignore`), hidden,
|
||||
/// excluded (`excludes`) or [`SKIPPED`] folders.
|
||||
fn configs(root: &Path, excludes: &[String]) -> Vec<PathBuf> {
|
||||
let excludes = ide_vfs::ExcludeMatcher::new(excludes);
|
||||
let base = root.to_path_buf();
|
||||
let mut walk = ignore::WalkBuilder::new(root);
|
||||
walk.max_depth(Some(MAX_DEPTH)).require_git(ide_core::ignored::inside_git_repo(root)).follow_links(false);
|
||||
walk.filter_entry(move |entry| {
|
||||
let skipped = entry.file_type().is_some_and(|t| t.is_dir())
|
||||
&& entry.file_name().to_str().is_some_and(|name| SKIPPED.contains(&name));
|
||||
!skipped && entry.path().strip_prefix(&base).is_ok_and(|rel| !excludes.is_match(rel))
|
||||
});
|
||||
let mut found: Vec<PathBuf> = walk
|
||||
.build()
|
||||
.flatten()
|
||||
.filter(|e| e.file_name() == "tsconfig.json" && e.file_type().is_some_and(|t| t.is_file()))
|
||||
.map(ignore::DirEntry::into_path)
|
||||
.collect();
|
||||
found.sort();
|
||||
found
|
||||
}
|
||||
|
||||
pub(crate) struct TscWatch {
|
||||
root: PathBuf,
|
||||
settings: Arc<SettingsStore>,
|
||||
sink: SharedSink,
|
||||
trusted: Arc<AtomicBool>,
|
||||
state: Mutex<State>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
/// The running watchers, cancelled to stop them.
|
||||
running: Option<CancellationToken>,
|
||||
/// The project closed: nothing starts again.
|
||||
closed: bool,
|
||||
/// The last compilation's diagnostics of each root configuration.
|
||||
results: BTreeMap<PathBuf, BTreeMap<PathBuf, Vec<Diagnostic>>>,
|
||||
/// Files open in an editor.
|
||||
open: HashSet<PathBuf>,
|
||||
/// What the UI was last sent.
|
||||
shown: BTreeMap<PathBuf, Vec<Diagnostic>>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// Every root's diagnostics of the files not open, a problem two roots report listed once.
|
||||
fn wanted(&self) -> BTreeMap<PathBuf, Vec<Diagnostic>> {
|
||||
let mut out: BTreeMap<PathBuf, Vec<Diagnostic>> = BTreeMap::new();
|
||||
for files in self.results.values() {
|
||||
for (path, items) in files.iter().filter(|(p, _)| !self.open.contains(*p)) {
|
||||
let list = out.entry(path.clone()).or_default();
|
||||
for d in items {
|
||||
if !list.iter().any(|o| o.range == d.range && o.message == d.message) {
|
||||
list.push(d.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The files whose diagnostics change, with their new list (empty clears them).
|
||||
fn refresh(&mut self) -> Vec<(PathBuf, Vec<Diagnostic>)> {
|
||||
let wanted = self.wanted();
|
||||
let mut changes: Vec<(PathBuf, Vec<Diagnostic>)> =
|
||||
self.shown.keys().filter(|p| !wanted.contains_key(*p)).map(|p| (p.clone(), Vec::new())).collect();
|
||||
changes.extend(
|
||||
wanted.iter().filter(|(p, items)| self.shown.get(*p) != Some(items)).map(|(p, i)| (p.clone(), i.clone())),
|
||||
);
|
||||
self.shown = wanted;
|
||||
changes
|
||||
}
|
||||
}
|
||||
|
||||
impl TscWatch {
|
||||
pub(crate) fn new(
|
||||
root: PathBuf,
|
||||
settings: Arc<SettingsStore>,
|
||||
sink: SharedSink,
|
||||
trusted: Arc<AtomicBool>,
|
||||
) -> Arc<Self> {
|
||||
Arc::new(Self { root, settings, sink, trusted, state: Mutex::new(State::default()) })
|
||||
}
|
||||
|
||||
/// Starts the watchers when the option is on in a trusted project, else stops them and
|
||||
/// clears their errors. Called on open, on a settings change and on a trust change.
|
||||
pub(crate) fn apply(self: &Arc<Self>, runtime: &tokio::runtime::Handle) {
|
||||
let wanted =
|
||||
self.trusted.load(Ordering::Acquire) && self.settings.effective().languages.typescript.watch_problems;
|
||||
if !wanted {
|
||||
return self.halt(false);
|
||||
}
|
||||
let mut state = self.state.lock();
|
||||
if !state.closed && state.running.is_none() {
|
||||
let cancel = CancellationToken::new();
|
||||
state.running = Some(cancel.clone());
|
||||
let this = self.clone();
|
||||
runtime.spawn_blocking(move || this.start(&cancel));
|
||||
}
|
||||
}
|
||||
|
||||
/// The project closed.
|
||||
pub(crate) fn stop(&self) {
|
||||
self.halt(true);
|
||||
}
|
||||
|
||||
fn halt(&self, closed: bool) {
|
||||
let mut state = self.state.lock();
|
||||
state.closed |= closed;
|
||||
if let Some(cancel) = state.running.take() {
|
||||
cancel.cancel();
|
||||
state.results.clear();
|
||||
self.publish(&mut state);
|
||||
}
|
||||
}
|
||||
|
||||
/// One thread per root configuration, each running its `tsc --watch` until `cancel`.
|
||||
fn start(self: &Arc<Self>, cancel: &CancellationToken) {
|
||||
let excludes = self.settings.effective().exclude_globs();
|
||||
for config in ide_build::compile::tsc_watch_roots(configs(&self.root, &excludes)) {
|
||||
if cancel.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
let (this, cancel) = (self.clone(), cancel.clone());
|
||||
std::thread::spawn(move || this.watch(&config, &cancel));
|
||||
}
|
||||
}
|
||||
|
||||
fn watch(&self, config: &Path, cancel: &CancellationToken) {
|
||||
let result = ide_build::compile::tsc_watch(&self.root, config, cancel, |messages| {
|
||||
tracing::debug!(config = %config.display(), messages = messages.len(), "tsc --watch compiled");
|
||||
let mut files = ide_build::compile::diagnostics_from(&messages, SOURCE);
|
||||
// Messages about the scratch configurations or files outside the project.
|
||||
files.retain(|path, _| path.starts_with(&self.root));
|
||||
self.compiled(config, files, cancel);
|
||||
});
|
||||
match result {
|
||||
Ok(()) => tracing::debug!(config = %config.display(), "tsc --watch ended"),
|
||||
Err(e) => tracing::debug!(config = %config.display(), %e, "tsc --watch did not run"),
|
||||
}
|
||||
// Without a watcher its errors would go stale.
|
||||
self.compiled(config, BTreeMap::new(), cancel);
|
||||
}
|
||||
|
||||
fn compiled(&self, config: &Path, files: BTreeMap<PathBuf, Vec<Diagnostic>>, cancel: &CancellationToken) {
|
||||
let mut state = self.state.lock();
|
||||
// Under the lock: `apply` cancels and clears under it, so a stopped watcher adds nothing.
|
||||
if cancel.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
if files.is_empty() {
|
||||
state.results.remove(config);
|
||||
} else {
|
||||
state.results.insert(config.to_path_buf(), files);
|
||||
}
|
||||
self.publish(&mut state);
|
||||
}
|
||||
|
||||
/// Sends the changes, under the lock so they reach the UI in the order decided here.
|
||||
fn publish(&self, state: &mut State) {
|
||||
for (path, items) in state.refresh() {
|
||||
self.sink.emit(IdeEvent::Diagnostics { path: path.into(), source: SOURCE.into(), items });
|
||||
}
|
||||
}
|
||||
|
||||
fn set_open(&self, path: &Path, open: bool) {
|
||||
let mut state = self.state.lock();
|
||||
let changed = if open { state.open.insert(path.to_path_buf()) } else { state.open.remove(path) };
|
||||
if changed {
|
||||
self.publish(&mut state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DocumentObserver for TscWatch {
|
||||
fn opened(&self, info: &DocumentInfo) {
|
||||
self.set_open(&info.path.0, true);
|
||||
}
|
||||
|
||||
fn closed(&self, _doc: ide_core::DocId, path: &Path) {
|
||||
self.set_open(path, false);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::{Pos, Range, Severity};
|
||||
|
||||
fn diag(line: u32, message: &str) -> Diagnostic {
|
||||
Diagnostic {
|
||||
range: Range::new(Pos::new(line, 0), Pos::new(line, 1)),
|
||||
severity: Severity::Error,
|
||||
message: message.into(),
|
||||
source: Some(SOURCE.into()),
|
||||
code: None,
|
||||
unnecessary: false,
|
||||
deprecated: false,
|
||||
server: Some(SOURCE.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn files(entries: &[(&str, Vec<Diagnostic>)]) -> BTreeMap<PathBuf, Vec<Diagnostic>> {
|
||||
entries.iter().map(|(p, d)| (PathBuf::from(p), d.clone())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_files_keep_only_the_language_servers_errors() {
|
||||
let mut state = State::default();
|
||||
let b = diag(0, "Type 'string' is not assignable to type 'number'.");
|
||||
state
|
||||
.results
|
||||
.insert("/p/tsconfig.json".into(), files(&[("/p/b.ts", vec![b.clone()]), ("/p/c.ts", vec![diag(1, "c")])]));
|
||||
// The same problem from a second root is listed once.
|
||||
state.results.insert("/p/src/tsconfig.json".into(), files(&[("/p/b.ts", vec![b.clone()])]));
|
||||
assert_eq!(state.refresh(), [("/p/b.ts".into(), vec![b.clone()]), ("/p/c.ts".into(), vec![diag(1, "c")])]);
|
||||
assert!(state.refresh().is_empty(), "nothing changed, nothing sent");
|
||||
|
||||
state.open.insert("/p/b.ts".into());
|
||||
assert_eq!(state.refresh(), [("/p/b.ts".into(), vec![])]);
|
||||
state.open.remove(Path::new("/p/b.ts"));
|
||||
assert_eq!(state.refresh(), [("/p/b.ts".into(), vec![b])]);
|
||||
|
||||
// Fixed: the next compilation reports nothing for the files.
|
||||
state.results.clear();
|
||||
assert_eq!(state.refresh(), [("/p/b.ts".into(), vec![]), ("/p/c.ts".into(), vec![])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configs_skip_ignored_excluded_and_sample_folders() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for dir in
|
||||
["", "apps/web", "test/fixtures/broken", "examples/demo", "generated", "vendor/lib", ".cache", "a/b/c/d"]
|
||||
{
|
||||
std::fs::create_dir_all(root.join(dir)).unwrap();
|
||||
std::fs::write(root.join(dir).join("tsconfig.json"), "{}").unwrap();
|
||||
}
|
||||
std::fs::write(root.join(".gitignore"), "/vendor/\n").unwrap();
|
||||
let found = configs(root, &["generated".into()]);
|
||||
assert_eq!(found, [root.join("apps/web/tsconfig.json"), root.join("tsconfig.json")]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn the_option_starts_and_stops_the_projects_tsc() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::time::{Duration, Instant};
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("p");
|
||||
std::fs::create_dir_all(root.join("src")).unwrap();
|
||||
std::fs::create_dir_all(root.join("node_modules/.bin")).unwrap();
|
||||
std::fs::write(root.join("tsconfig.json"), "{}").unwrap();
|
||||
std::fs::write(root.join("src/b.ts"), "export const b: number = a;\n").unwrap();
|
||||
// Records its process, prints one compilation and keeps watching, like `tsc --watch`.
|
||||
let tsc = root.join("node_modules/.bin/tsc");
|
||||
std::fs::write(
|
||||
&tsc,
|
||||
"#!/bin/sh\necho $$ >> pids.txt\n\
|
||||
echo 'src/b.ts(1,26): error TS2322: Type string is not assignable to type number.'\n\
|
||||
echo '1:00:00 PM - Found 1 error. Watching for file changes.'\nexec sleep 60\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&tsc, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
let settings = Arc::new(SettingsStore::load(&tmp.path().join("config"), Some(&root)));
|
||||
let events: Arc<Mutex<Vec<(PathBuf, usize)>>> = Arc::default();
|
||||
let sink: SharedSink = Arc::new({
|
||||
let events = events.clone();
|
||||
move |e: IdeEvent| {
|
||||
if let IdeEvent::Diagnostics { path, source, items } = e {
|
||||
assert_eq!(source, SOURCE);
|
||||
events.lock().push((path.0, items.len()));
|
||||
}
|
||||
}
|
||||
});
|
||||
let trusted = Arc::new(AtomicBool::new(true));
|
||||
let watch = TscWatch::new(root.clone(), settings.clone(), sink, trusted.clone());
|
||||
let runtime = tokio::runtime::Handle::current();
|
||||
let b = root.join("src/b.ts");
|
||||
let pids = || -> Vec<u32> {
|
||||
std::fs::read_to_string(root.join("pids.txt"))
|
||||
.unwrap_or_default()
|
||||
.lines()
|
||||
.filter_map(|l| l.parse().ok())
|
||||
.collect()
|
||||
};
|
||||
let until = |what: &str, ok: &dyn Fn() -> bool| {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while !ok() {
|
||||
assert!(Instant::now() < deadline, "timed out waiting for {what}");
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
};
|
||||
let last = || events.lock().iter().rev().find(|(p, _)| *p == b).map(|(_, n)| *n);
|
||||
let set = |on: bool| {
|
||||
settings
|
||||
.set(ide_workspace::settings::SettingsScope::Project, "languages.typescript.watchProblems", on.into())
|
||||
.unwrap();
|
||||
watch.apply(&runtime);
|
||||
};
|
||||
|
||||
// Off by default: nothing runs.
|
||||
watch.apply(&runtime);
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
assert!(pids().is_empty() && events.lock().is_empty());
|
||||
|
||||
set(true);
|
||||
until("the error of b.ts", &|| last() == Some(1));
|
||||
let first = pids()[0];
|
||||
// Applying again (another setting changed) keeps the one watcher.
|
||||
watch.apply(&runtime);
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
assert_eq!(pids(), [first]);
|
||||
|
||||
set(false);
|
||||
assert_eq!(last(), Some(0), "turning it off clears its errors at once");
|
||||
until("tsc to stop", &|| !ide_core::process::process_alive(first));
|
||||
|
||||
// Restricted Mode stops it too, and trusting the project starts it again.
|
||||
set(true);
|
||||
until("a second tsc", &|| pids().len() == 2 && last() == Some(1));
|
||||
trusted.store(false, Ordering::Release);
|
||||
watch.apply(&runtime);
|
||||
assert_eq!(last(), Some(0));
|
||||
until("tsc to stop", &|| !ide_core::process::process_alive(pids()[1]));
|
||||
trusted.store(true, Ordering::Release);
|
||||
watch.apply(&runtime);
|
||||
until("a third tsc", &|| pids().len() == 3 && last() == Some(1));
|
||||
|
||||
// Closing the project stops it for good.
|
||||
watch.stop();
|
||||
assert_eq!(last(), Some(0));
|
||||
until("tsc to stop", &|| !ide_core::process::process_alive(pids()[2]));
|
||||
watch.apply(&runtime);
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
assert_eq!(pids().len(), 3, "nothing starts after the project closed");
|
||||
}
|
||||
}
|
||||
@@ -211,7 +211,7 @@ fn write_index(
|
||||
|
||||
/// The download sources setting with `mirror` as the GitHub proxy prefix (Tools › Download sources).
|
||||
fn download_sources(mirror: &str) -> ide_core::settings::ToolDownloadSettings {
|
||||
ide_core::settings::ToolDownloadSettings { github_mirror: mirror.into() }
|
||||
ide_core::settings::ToolDownloadSettings { github_mirror: mirror.into(), ..Default::default() }
|
||||
}
|
||||
|
||||
/// Security audit lead 5: an index entry's id and version name the download file,
|
||||
|
||||
@@ -110,3 +110,49 @@ async fn external_history_is_readable_and_never_becomes_a_write_target() {
|
||||
assert!(!deleted.exists());
|
||||
host.close_project("main");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn revision_images_use_the_selected_git_blob_and_window() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("repo");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
git(&root, &["init", "-b", "main"]);
|
||||
let old = root.join("old.PNG");
|
||||
let new = root.join("new.webp");
|
||||
std::fs::write(&old, [0x89, 0x00, 0xff]).unwrap();
|
||||
std::fs::write(root.join("icon.svg"), b"<svg/>").unwrap();
|
||||
std::fs::write(root.join("photo.jpeg"), [0xff, 0xd8]).unwrap();
|
||||
git(&root, &["add", "."]);
|
||||
git(&root, &["commit", "-m", "old image"]);
|
||||
let first = git(&root, &["rev-parse", "HEAD"]);
|
||||
git(&root, &["mv", "old.PNG", "new.webp"]);
|
||||
std::fs::write(&new, [0xff, 0xfe]).unwrap();
|
||||
git(&root, &["commit", "-am", "rename and change image"]);
|
||||
std::fs::write(&new, [0x00, 0x80]).unwrap();
|
||||
git(&root, &["add", "new.webp"]);
|
||||
std::fs::write(&new, "working tree only").unwrap();
|
||||
|
||||
let host = Host::new(common::host_config(&base));
|
||||
let read = |window, path: &Path, rev: &str| vcs::vcs_image_at(&host, window, path.to_owned(), rev.to_owned());
|
||||
assert!(read("standalone", &old, &first).await.is_err());
|
||||
vcs::vcs_open_external_log(&host, "standalone", root.clone()).await.unwrap();
|
||||
assert_eq!(read("standalone", &old, &first).await.unwrap().as_deref(), Some("data:image/png;base64,iQD/"));
|
||||
assert!(read("another-window", &old, &first).await.is_err());
|
||||
|
||||
host.trust.decide(&root, false, false).unwrap();
|
||||
host.open_project("project", &root).unwrap();
|
||||
assert_eq!(read("project", &new, "HEAD").await.unwrap().as_deref(), Some("data:image/webp;base64,//4="));
|
||||
assert_eq!(read("project", &new, ":0").await.unwrap().as_deref(), Some("data:image/webp;base64,AIA="));
|
||||
assert_eq!(read("project", &old, "HEAD").await.unwrap(), None);
|
||||
assert_eq!(
|
||||
read("project", &root.join("icon.svg"), "HEAD").await.unwrap().as_deref(),
|
||||
Some("data:image/svg+xml;base64,PHN2Zy8+")
|
||||
);
|
||||
assert_eq!(
|
||||
read("project", &root.join("photo.jpeg"), "HEAD").await.unwrap().as_deref(),
|
||||
Some("data:image/jpeg;base64,/9g=")
|
||||
);
|
||||
assert!(read("project", &base.join("outside.png"), "HEAD").await.is_err());
|
||||
assert!(read("project", &root.join("file.txt"), "HEAD").await.is_err());
|
||||
}
|
||||
@@ -696,6 +696,131 @@ async fn typescript() {
|
||||
smoke("typescript", TYPESCRIPT).await;
|
||||
}
|
||||
|
||||
/// The latest `tsc` diagnostics of `path` (Problems › TypeScript Project Errors), `None` before any.
|
||||
fn tsc_errors(events: &Events, path: &Path) -> Option<Vec<String>> {
|
||||
events.lock().unwrap().iter().rev().find_map(|e| match e {
|
||||
IdeEvent::Diagnostics { path: p, source, items } if source == "tsc" && **p == *path => {
|
||||
Some(items.iter().map(|d| d.message.clone()).collect())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Problems › TypeScript Project Errors (#6073): the project's own `tsc --watch` reports the error
|
||||
/// an edit of one file causes in another that is not open, holds it back while that file is open,
|
||||
/// clears it once fixed, checks a solution with project references as well, and writes nothing
|
||||
/// into the project. TypeScript comes from `OPENIDEA_SMOKE_TYPESCRIPT` (a `typescript` package
|
||||
/// folder), else the global npm install.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
#[ignore = "language smoke: needs typescript"]
|
||||
async fn typescript_project_errors() {
|
||||
let typescript = std::env::var_os("OPENIDEA_SMOKE_TYPESCRIPT").map_or_else(
|
||||
|| {
|
||||
let out = std::process::Command::new("npm").args(["root", "-g"]).output().expect("npm root -g");
|
||||
PathBuf::from(String::from_utf8_lossy(&out.stdout).trim()).join("typescript")
|
||||
},
|
||||
PathBuf::from,
|
||||
);
|
||||
assert!(typescript.join("bin/tsc").is_file(), "no TypeScript in {}", typescript.display());
|
||||
let checks = Checks {
|
||||
files: &[
|
||||
// Fails from the start: its error marks the end of the first compilation.
|
||||
("src/probe.ts", "export const probe: number = \"x\";\n"),
|
||||
("packages/tsconfig.json", r#"{"files": [], "references": [{"path": "./core"}, {"path": "./app"}]}"#),
|
||||
(
|
||||
"packages/core/tsconfig.json",
|
||||
r#"{"compilerOptions": {"composite": true, "strict": true, "outDir": "out"}}"#,
|
||||
),
|
||||
("packages/core/index.ts", "export const version: number = 1;\n"),
|
||||
(
|
||||
"packages/app/tsconfig.json",
|
||||
r#"{"compilerOptions": {"composite": true, "strict": true, "outDir": "out"}, "references": [{"path": "../core"}]}"#,
|
||||
),
|
||||
(
|
||||
"packages/app/index.ts",
|
||||
"import { version } from \"../core/index\";\nexport const label: string = version;\n",
|
||||
),
|
||||
],
|
||||
..TYPESCRIPT
|
||||
};
|
||||
let smoke = Smoke::start("typescript", &checks).await;
|
||||
let root = smoke.root.clone();
|
||||
std::fs::create_dir_all(root.join("node_modules/.bin")).unwrap();
|
||||
std::os::unix::fs::symlink(&typescript, root.join("node_modules/typescript")).unwrap();
|
||||
std::os::unix::fs::symlink("../typescript/bin/tsc", root.join("node_modules/.bin/tsc")).unwrap();
|
||||
async fn wait(what: &str, ok: impl Fn() -> bool) {
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
while !ok() {
|
||||
assert!(Instant::now() < deadline, "timed out waiting for {what}");
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
}
|
||||
}
|
||||
let errors = |file: &str| tsc_errors(&smoke.events, &root.join(file));
|
||||
let has = |file: &'static str, text: &'static str| {
|
||||
move || errors(file).is_some_and(|e| e.iter().any(|m| m.contains(text)))
|
||||
};
|
||||
let clear = |file: &'static str| move || errors(file).is_some_and(|e| e.is_empty());
|
||||
let set = |on: bool| {
|
||||
let scope = ide_workspace::settings::SettingsScope::Project;
|
||||
ops::project::settings_set(
|
||||
&smoke.host,
|
||||
WINDOW,
|
||||
scope,
|
||||
"languages.typescript.watchProblems".into(),
|
||||
on.to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
};
|
||||
|
||||
set(true);
|
||||
wait("the first compilation", has("src/probe.ts", "not assignable")).await;
|
||||
wait("the solution's error", has("packages/app/index.ts", "not assignable to type 'string'")).await;
|
||||
|
||||
// Renaming an export in money.ts breaks index.ts, which is not open.
|
||||
let money = root.join("src/money.ts");
|
||||
let original = std::fs::read_to_string(&money).unwrap();
|
||||
std::fs::write(&money, original.replace("export function formatMoney", "export function formatPrice")).unwrap();
|
||||
wait("index.ts to break", has("src/index.ts", "formatMoney")).await;
|
||||
assert_eq!(errors("src/money.ts"), None, "the edited file itself is fine");
|
||||
|
||||
// Open, it shows the language server's errors only; closed again, the watcher's.
|
||||
let doc = ops::doc::doc_open(&smoke.host, WINDOW, root.join("src/index.ts")).await.unwrap();
|
||||
wait("index.ts held back while open", clear("src/index.ts")).await;
|
||||
ops::doc::doc_close(&smoke.host, WINDOW, doc.id).await.unwrap();
|
||||
wait("index.ts back once closed", has("src/index.ts", "formatMoney")).await;
|
||||
|
||||
std::fs::write(&money, &original).unwrap();
|
||||
// The fixture's own error (an unused function) stays.
|
||||
let fixed =
|
||||
move || errors("src/index.ts").is_some_and(|e| !e.is_empty() && !e.iter().any(|m| m.contains("formatMoney")));
|
||||
wait("index.ts fixed", fixed).await;
|
||||
|
||||
set(false);
|
||||
wait("every error cleared", || {
|
||||
["src/probe.ts", "src/index.ts", "packages/app/index.ts"].into_iter().all(|f| clear(f)())
|
||||
})
|
||||
.await;
|
||||
|
||||
// A background check writes nothing into the project: no `.js`, `.d.ts` or `.tsbuildinfo`.
|
||||
fn outputs(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
for entry in std::fs::read_dir(dir).unwrap().flatten() {
|
||||
let path = entry.path();
|
||||
if entry.file_name() == "node_modules" {
|
||||
continue;
|
||||
}
|
||||
if path.is_dir() {
|
||||
outputs(&path, out);
|
||||
} else if [".js", ".d.ts", ".tsbuildinfo"].iter().any(|ext| path.to_string_lossy().ends_with(ext)) {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut written = Vec::new();
|
||||
outputs(&root, &mut written);
|
||||
assert_eq!(written, Vec::<PathBuf>::new());
|
||||
}
|
||||
|
||||
const PYTHON: Checks = Checks {
|
||||
fixture: "python-app",
|
||||
// Ruff (lint, quick fixes, formatting) starts in projects configured for it.
|
||||
|
||||
@@ -6631,6 +6631,272 @@ fn net_ask_session_hosts_are_ephemeral_and_cleared_with_plugin_grants() {
|
||||
assert_eq!(seen.lock().len(), 9);
|
||||
}
|
||||
|
||||
/// Sets a plugin's global setting value in the test workspace.
|
||||
fn set_setting(f: &Fixture, plugin: &str, value: &str) {
|
||||
let mut map = serde_json::Map::new();
|
||||
map.insert("server".into(), serde_json::Value::String(value.into()));
|
||||
f.workspace.global_settings.lock().insert(plugin.to_owned(), map);
|
||||
}
|
||||
|
||||
fn net_setting_of<'a>(info: &'a PluginInfo, setting: &str) -> Option<&'a PluginNetSetting> {
|
||||
info.net_settings.iter().find(|s| s.setting == setting && !s.http)
|
||||
}
|
||||
|
||||
fn http_setting_of<'a>(info: &'a PluginInfo, setting: &str) -> Option<&'a PluginNetSetting> {
|
||||
info.net_settings.iter().find(|s| s.setting == setting && s.http)
|
||||
}
|
||||
|
||||
/// `net:setting:` grants: the host is approved in Settings, materializes while
|
||||
/// the setting holds it, replaces and clears with it, and never asks at
|
||||
/// request time — a pending host stays denied without a dialog (#3809).
|
||||
#[test]
|
||||
fn net_setting_grants_approve_replace_and_clear_with_the_setting() {
|
||||
use ide_extension::ledger::{Ledger, Subject};
|
||||
let f = fixture(Limits::default());
|
||||
f.install(&sample("net-setting"));
|
||||
let subject = Subject::Installed("netsetting".into());
|
||||
let (port, seen) = http_server("relay ok", |_| Duration::ZERO);
|
||||
let url = format!("http://127.0.0.1:{port}/");
|
||||
|
||||
// Unset: denied exactly as today, unattended and attended, no dialog.
|
||||
let err = f.run("netsetting", "fetch", Some(&url)).unwrap_err();
|
||||
assert!(err.contains("net:127.0.0.1") && err.contains("not granted"), "{err}");
|
||||
let err = f.host.run_command("netsetting", "fetch", Some(&url), Invocation::default()).unwrap_err();
|
||||
assert!(err.message.contains("not granted"), "{err:?}");
|
||||
assert!(!f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::PromptRequested { .. })));
|
||||
assert_eq!(seen.lock().len(), 0);
|
||||
|
||||
// Approved when the value is applied in Settings: the host materializes.
|
||||
set_setting(&f, "netsetting", &url);
|
||||
// The host the user was shown must still be the setting's value: a value
|
||||
// the plugin wrote after the dialog opened is not approved in its place.
|
||||
let err = f.host.approve_net_setting("netsetting", "server", false, "jira.corp.example").unwrap_err();
|
||||
assert!(err.message.contains("now holds 127.0.0.1"), "{err:?}");
|
||||
assert_eq!(net_setting_of(&f.host.info_of("netsetting").unwrap(), "server").unwrap().host, None);
|
||||
f.host.approve_net_setting("netsetting", "server", false, "127.0.0.1").unwrap();
|
||||
let info = f.host.info_of("netsetting").unwrap();
|
||||
let entry = net_setting_of(&info, "server").unwrap();
|
||||
assert_eq!(entry.host.as_deref(), Some("127.0.0.1"));
|
||||
assert_eq!(entry.pending, None);
|
||||
assert_eq!(seen.lock().len(), 0);
|
||||
for invocation in [f.inv(), Invocation::default()] {
|
||||
let result = f.host.run_command("netsetting", "fetch", Some(&url), invocation).unwrap();
|
||||
assert_eq!(result.as_deref(), Some("relay ok"));
|
||||
}
|
||||
assert_eq!(seen.lock().len(), 2);
|
||||
assert!(!f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::PromptRequested { .. })));
|
||||
assert_eq!(
|
||||
Ledger::load(&f.plugins_dir).get(&subject).unwrap().setting_hosts.get("net:setting:server").map(String::as_str),
|
||||
Some("127.0.0.1")
|
||||
);
|
||||
|
||||
// A value that changed anywhere else is not approved: pending, and a call
|
||||
// to it is denied without a dialog — unattended and from a window.
|
||||
set_setting(&f, "netsetting", "jira.corp.example");
|
||||
let info = f.host.info_of("netsetting").unwrap();
|
||||
let entry = net_setting_of(&info, "server").unwrap();
|
||||
assert_eq!(entry.host, None);
|
||||
assert_eq!(entry.pending.as_deref(), Some("jira.corp.example"));
|
||||
let err = f.run("netsetting", "fetch", Some("http://jira.corp.example/")).unwrap_err();
|
||||
assert!(err.contains("not granted"), "{err}");
|
||||
let err = f
|
||||
.host
|
||||
.run_command("netsetting", "fetch", Some("http://jira.corp.example/"), Invocation::default())
|
||||
.unwrap_err();
|
||||
assert!(err.message.contains("not granted"), "{err:?}");
|
||||
assert!(!f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::PromptRequested { .. })));
|
||||
assert_eq!(seen.lock().len(), 2);
|
||||
|
||||
// The old host no longer materializes either: it is not the setting's value.
|
||||
f.host.set_enabled("netsetting", false).unwrap();
|
||||
f.host.set_enabled("netsetting", true).unwrap();
|
||||
let err = f.run("netsetting", "fetch", Some(&url)).unwrap_err();
|
||||
assert!(err.contains("not granted"), "{err}");
|
||||
assert_eq!(seen.lock().len(), 2);
|
||||
|
||||
// The Approve action replaces the approval only after the user confirms it.
|
||||
f.host.approve_net_setting("netsetting", "server", false, "jira.corp.example").unwrap();
|
||||
let info = f.host.info_of("netsetting").unwrap();
|
||||
let entry = net_setting_of(&info, "server").unwrap();
|
||||
assert_eq!(entry.host.as_deref(), Some("jira.corp.example"));
|
||||
assert_eq!(entry.pending, None);
|
||||
assert_eq!(
|
||||
Ledger::load(&f.plugins_dir).get(&subject).unwrap().setting_hosts.get("net:setting:server").map(String::as_str),
|
||||
Some("jira.corp.example")
|
||||
);
|
||||
// And the old loopback host stays denied now.
|
||||
let err = f.run("netsetting", "fetch", Some(&url)).unwrap_err();
|
||||
assert!(err.contains("not granted"), "{err}");
|
||||
assert_eq!(seen.lock().len(), 2);
|
||||
|
||||
// Revoking the manifest grant drops the record; granting it back asks for
|
||||
// a fresh approval.
|
||||
f.host.set_capability("netsetting", "net:setting:server", false).unwrap();
|
||||
assert!(Ledger::load(&f.plugins_dir).get(&subject).unwrap().setting_hosts.is_empty());
|
||||
f.host.set_capability("netsetting", "net:setting:server", true).unwrap();
|
||||
let info = f.host.info_of("netsetting").unwrap();
|
||||
let entry = net_setting_of(&info, "server").unwrap();
|
||||
assert_eq!(entry.host, None);
|
||||
assert_eq!(entry.pending.as_deref(), Some("jira.corp.example"));
|
||||
|
||||
// Clearing the setting removes the grant.
|
||||
f.host.approve_net_setting("netsetting", "server", false, "jira.corp.example").unwrap();
|
||||
set_setting(&f, "netsetting", "");
|
||||
f.host.forget_net_setting("netsetting", "server", false).unwrap();
|
||||
assert!(Ledger::load(&f.plugins_dir).get(&subject).unwrap().setting_hosts.is_empty());
|
||||
let info = f.host.info_of("netsetting").unwrap();
|
||||
let entry = net_setting_of(&info, "server").unwrap();
|
||||
assert_eq!(entry.host, None);
|
||||
assert_eq!(entry.pending, None);
|
||||
let err = f
|
||||
.host
|
||||
.run_command("netsetting", "fetch", Some("http://jira.corp.example/"), Invocation::default())
|
||||
.unwrap_err();
|
||||
assert!(err.message.contains("not granted"), "{err:?}");
|
||||
assert_eq!(seen.lock().len(), 2);
|
||||
}
|
||||
|
||||
/// `net.http:setting:` reaches plain HTTP on a non-loopback address; its
|
||||
/// record is kept per transport, next to the HTTPS one.
|
||||
#[test]
|
||||
fn net_http_setting_grants_reach_plain_http_per_transport() {
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
let f = fixture(Limits::default());
|
||||
f.install(&sample("net-setting"));
|
||||
// 127.0.0.2 is this machine's loopback too, but not in the loopback list
|
||||
// of `net_capability`: its plain HTTP needs the `net.http:` grant.
|
||||
// macOS only configures 127.0.0.1 on lo0 by default.
|
||||
let Ok(listener) = std::net::TcpListener::bind("127.0.0.2:0") else {
|
||||
eprintln!("skipped: 127.0.0.2 is not bound to a loopback interface here");
|
||||
return;
|
||||
};
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let url = format!("http://127.0.0.2:{port}/");
|
||||
let seen: Arc<Mutex<Vec<String>>> = Arc::default();
|
||||
{
|
||||
let seen = seen.clone();
|
||||
std::thread::spawn(move || {
|
||||
for stream in listener.incoming().flatten() {
|
||||
let mut reader = BufReader::new(stream.try_clone().unwrap());
|
||||
let mut writer = stream;
|
||||
let mut line = String::new();
|
||||
let mut len = 0;
|
||||
loop {
|
||||
let read = reader.read_line(&mut line).unwrap_or(0);
|
||||
if read == 0 || line == "\r\n" {
|
||||
break;
|
||||
}
|
||||
if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") {
|
||||
len = v.trim().parse().unwrap_or(0);
|
||||
}
|
||||
line.clear();
|
||||
}
|
||||
let mut req = vec![0; len];
|
||||
let _ = reader.read_exact(&mut req);
|
||||
let body = "plain ok";
|
||||
let _ = writer.write_all(
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\ncontent-length: {}\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
seen.lock().push("served".into());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Plain HTTP elsewhere stays out of the ask flow entirely, unattended and attended.
|
||||
let err = f.run("netsetting", "fetch", Some(&url)).unwrap_err();
|
||||
assert!(err.contains("net.http:127.0.0.2") && err.contains("not granted"), "{err}");
|
||||
assert!(!f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::PromptRequested { .. })));
|
||||
|
||||
// Approved for the `net.http:` transport only: the record is its own.
|
||||
set_setting(&f, "netsetting", &url);
|
||||
f.host.approve_net_setting("netsetting", "server", true, "127.0.0.2").unwrap();
|
||||
let info = f.host.info_of("netsetting").unwrap();
|
||||
let entry = http_setting_of(&info, "server").unwrap();
|
||||
assert_eq!(entry.host.as_deref(), Some("127.0.0.2"));
|
||||
assert!(entry.http);
|
||||
// The HTTPS transport has no approval of its own: the setting's host is pending there.
|
||||
let https = net_setting_of(&info, "server").unwrap();
|
||||
assert_eq!(https.host, None);
|
||||
assert_eq!(https.pending.as_deref(), Some("127.0.0.2"));
|
||||
for invocation in [f.inv(), Invocation::default()] {
|
||||
let result = f.host.run_command("netsetting", "fetch", Some(&url), invocation).unwrap();
|
||||
assert_eq!(result.as_deref(), Some("plain ok"));
|
||||
}
|
||||
assert_eq!(seen.lock().len(), 2);
|
||||
assert!(!f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::PromptRequested { .. })));
|
||||
|
||||
// A `net:` grant for the same host would not cover plain HTTP; without the
|
||||
// `net.http:` approval the request stays denied (redirect rules unchanged).
|
||||
f.host.forget_net_setting("netsetting", "server", true).unwrap();
|
||||
let err = f.host.run_command("netsetting", "fetch", Some(&url), Invocation::default()).unwrap_err();
|
||||
assert!(err.message.contains("net.http:127.0.0.2") && err.message.contains("not granted"), "{err:?}");
|
||||
assert_eq!(seen.lock().len(), 2);
|
||||
}
|
||||
|
||||
/// On a remote host, a setting-derived approval is kept for the session only,
|
||||
/// like the `net:ask` answers (#3809).
|
||||
#[test]
|
||||
fn net_setting_approvals_are_session_only_on_remote_hosts() {
|
||||
use ide_extension::ledger::{Ledger, Subject};
|
||||
let f = fixture(Limits::default());
|
||||
f.host.set_net_hosts_session_only();
|
||||
f.install(&sample("net-setting"));
|
||||
let subject = Subject::Installed("netsetting".into());
|
||||
let (port, seen) = http_server("session ok", |_| Duration::ZERO);
|
||||
let url = format!("http://127.0.0.1:{port}/");
|
||||
|
||||
set_setting(&f, "netsetting", &url);
|
||||
f.host.approve_net_setting("netsetting", "server", false, "127.0.0.1").unwrap();
|
||||
for invocation in [f.inv(), Invocation::default()] {
|
||||
let result = f.host.run_command("netsetting", "fetch", Some(&url), invocation).unwrap();
|
||||
assert_eq!(result.as_deref(), Some("session ok"));
|
||||
}
|
||||
assert_eq!(seen.lock().len(), 2);
|
||||
assert!(Ledger::load(&f.plugins_dir).get(&subject).unwrap().setting_hosts.is_empty());
|
||||
|
||||
// Nothing was written: the approval dies with the session (disable/enable).
|
||||
f.host.set_enabled("netsetting", false).unwrap();
|
||||
f.host.set_enabled("netsetting", true).unwrap();
|
||||
let err = f.host.run_command("netsetting", "fetch", Some(&url), Invocation::default()).unwrap_err();
|
||||
assert!(err.message.contains("not granted"), "{err:?}");
|
||||
assert!(!f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::PromptRequested { .. })));
|
||||
assert_eq!(seen.lock().len(), 2);
|
||||
}
|
||||
|
||||
/// A `net:setting:` grant must name a `string` setting in the plugin's own
|
||||
/// schema; checked at install like the other manifest checks (#3809).
|
||||
#[test]
|
||||
fn a_setting_grant_needs_a_string_setting_in_the_own_schema() {
|
||||
let f = fixture(Limits::default());
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let pkg = dir.path().join("net-setting-bad");
|
||||
copy_dir(&sample("net-setting"), &pkg);
|
||||
let manifest = pkg.join("plugin.toml");
|
||||
let text = std::fs::read_to_string(&manifest).unwrap();
|
||||
std::fs::write(&manifest, text.replace("net:setting:server", "net:setting:missing")).unwrap();
|
||||
let err = f.host.install_from_dir(&pkg, &Consent::all()).unwrap_err();
|
||||
assert!(err.message.contains("`net:setting:missing`") && err.message.contains("string"), "{err:?}");
|
||||
|
||||
let pkg = dir.path().join("net-setting-number");
|
||||
copy_dir(&sample("net-setting"), &pkg);
|
||||
let schema = pkg.join("settings.json");
|
||||
let text = std::fs::read_to_string(&schema).unwrap();
|
||||
std::fs::write(
|
||||
&schema,
|
||||
text.replace(
|
||||
"\"type\":\"string\",\"title\":\"Server\",\"default\":\"\"",
|
||||
"\"type\":\"number\",\"title\":\"Server\",\"default\":0",
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let err = f.host.install_from_dir(&pkg, &Consent::all()).unwrap_err();
|
||||
assert!(err.message.contains("net:setting:server") && err.message.contains("string"), "{err:?}");
|
||||
}
|
||||
|
||||
/// Runs api14's `fetch` in its window; once the `net:ask` question arrives,
|
||||
/// answers it (`None`: dismisses). Returns the command's result and the prompt.
|
||||
fn net_ask_run_and_answer(
|
||||
|
||||
@@ -52,6 +52,7 @@ fn arm(root: &Path, markers: &Path) -> Armed {
|
||||
git(root, &["config", key, value]);
|
||||
}
|
||||
std::fs::write(root.join("src/a.txt"), "one\ntwo\n").unwrap();
|
||||
std::fs::write(root.join("asset.jpg"), [0xff, 0xd8]).unwrap();
|
||||
git(root, &["add", "."]);
|
||||
git(root, &["commit", "-qm", "first"]);
|
||||
let first = git(root, &["rev-parse", "HEAD"]);
|
||||
@@ -168,6 +169,7 @@ async fn restricted_vcs_commands_run_no_program_of_the_repository() {
|
||||
call!("vcs_line_hunks", "", vcs::vcs_line_hunks(host, w, file.clone())),
|
||||
call!("vcs_staging_line_hunks", "", vcs::vcs_staging_line_hunks(host, w, file.clone(), None)),
|
||||
call!("vcs_file_at", "", vcs::vcs_file_at(host, w, file.clone(), None)),
|
||||
call!("vcs_image_at", "", vcs::vcs_image_at(host, w, project.root.join("asset.jpg"), ":0".into())),
|
||||
call!(
|
||||
"vcs_diff_entries",
|
||||
"",
|
||||
|
||||
@@ -391,6 +391,11 @@ impl ProjectIndex {
|
||||
matching::symbols_named_within(&self.shared.data.read(), name, kind, roots, limit)
|
||||
}
|
||||
|
||||
/// Symbols of `kind` whose name starts with `prefix`, by path then position.
|
||||
pub fn symbols_prefixed(&self, prefix: &str, kind: SymbolKind, limit: usize) -> Vec<SymbolMatch> {
|
||||
matching::symbols_prefixed(&self.shared.data.read(), prefix, kind, limit)
|
||||
}
|
||||
|
||||
/// Symbols named exactly one of `names` whose file is inside `root`, at most `limit` per name.
|
||||
pub fn symbols_named_any(&self, names: &[String], root: &Path, limit: usize) -> Vec<SymbolMatch> {
|
||||
matching::symbols_named_any(&self.shared.data.read(), names, root, limit)
|
||||
|
||||
@@ -716,6 +716,34 @@ pub(crate) fn symbols_named_within(
|
||||
out
|
||||
}
|
||||
|
||||
/// Symbols of `kind` whose name starts with `prefix` (CSS custom properties: `--`), by path
|
||||
/// then position.
|
||||
pub(crate) fn symbols_prefixed(data: &IndexData, prefix: &str, kind: SymbolKind, limit: usize) -> Vec<SymbolMatch> {
|
||||
let syms = &data.syms;
|
||||
let mut out: Vec<SymbolMatch> = data
|
||||
.files
|
||||
.iter()
|
||||
.flatten()
|
||||
.flat_map(|e| {
|
||||
(e.sym_start..e.sym_start + e.sym_len)
|
||||
.filter(|&i| syms.kind(i) == kind && syms.name(i).starts_with(prefix))
|
||||
.map(move |i| SymbolMatch {
|
||||
name: syms.name(i).to_string(),
|
||||
kind,
|
||||
container: syms.container(i).map(str::to_owned),
|
||||
path: e.path.clone().into(),
|
||||
rel_path: e.rel.to_string(),
|
||||
range: syms.range(i),
|
||||
score: 0,
|
||||
indices: Vec::new(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
out.sort_by(|a, b| a.rel_path.cmp(&b.rel_path).then_with(|| a.range.cmp(&b.range)));
|
||||
out.truncate(limit);
|
||||
out
|
||||
}
|
||||
|
||||
/// Symbols named exactly one of `names` whose file is inside `root`, at most `limit` per
|
||||
/// name, by path then position: one walk over the index for every name an agent reply shows.
|
||||
pub(crate) fn symbols_named_any(data: &IndexData, names: &[String], root: &Path, limit: usize) -> Vec<SymbolMatch> {
|
||||
|
||||
@@ -675,6 +675,37 @@ fn css_selectors_are_found_by_exact_name() {
|
||||
assert!(idx.symbols_named(".card", Some(SymbolKind::Field), 10).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn css_custom_properties_are_listed_with_their_values_and_follow_edits() {
|
||||
let f = Fixture::new(&[
|
||||
("theme/light.css", ":root {\n --bg: #fff;\n --gap:\n 4px 8px;\n}\n"),
|
||||
("theme/dark.scss", "[data-theme=dark] { .x { --bg: rgb(0 0 0) !important; } }\n"),
|
||||
("theme/extra.less", ".a { --ring: var(--bg); color: red; }\n"),
|
||||
]);
|
||||
let idx = f.open();
|
||||
let vars = |idx: &ProjectIndex| -> Vec<(String, String, Option<String>)> {
|
||||
idx.symbols_prefixed("--", SymbolKind::Variable, 100)
|
||||
.into_iter()
|
||||
.map(|m| (m.rel_path, m.name, m.container))
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(
|
||||
vars(&idx),
|
||||
vec![
|
||||
("theme/dark.scss".into(), "--bg".into(), Some("rgb(0 0 0) !important".into())),
|
||||
("theme/extra.less".into(), "--ring".into(), Some("var(--bg)".into())),
|
||||
("theme/light.css".into(), "--bg".into(), Some("#fff".into())),
|
||||
("theme/light.css".into(), "--gap".into(), Some("4px 8px".into())),
|
||||
]
|
||||
);
|
||||
let light = f.root.join("theme/light.css");
|
||||
std::fs::write(&light, ":root { --fg: #222; }\n").unwrap();
|
||||
idx.update(std::slice::from_ref(&light), &[]);
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
let names: Vec<String> = vars(&idx).into_iter().filter(|v| v.0 == "theme/light.css").map(|v| v.1).collect();
|
||||
assert_eq!(names, vec!["--fg".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbols_named_within_keeps_out_of_root_matches_from_evicting_a_root() {
|
||||
let f = Fixture::new(&[
|
||||
|
||||
@@ -28,7 +28,9 @@ pub use syntax::{
|
||||
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_kinds, merge_visibility,
|
||||
set_external_syntax, shift_pos, shift_range,
|
||||
};
|
||||
pub use syntax::{MethodBody, PhpAlignment, PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression};
|
||||
pub use syntax::{
|
||||
MethodBody, PhpAlignment, PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression, bundler_aliases,
|
||||
};
|
||||
|
||||
/// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`].
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
//! Path aliases of a Vite, Rollup (`@rollup/plugin-alias`) or esbuild configuration, read
|
||||
//! without running it.
|
||||
|
||||
use super::parse;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use tree_sitter::{Language, Node};
|
||||
|
||||
/// `[alias, target]` pairs of the bundler configuration `text` in `dir`: every `alias`
|
||||
/// property (Vite's `resolve.alias`, esbuild's `alias`) and, when the file uses
|
||||
/// `@rollup/plugin-alias`, its `entries`. Both object (`{ '@': … }`) and array
|
||||
/// (`[{ find, replacement }]`) forms. Targets are string literals, `path.resolve` /
|
||||
/// `path.join` of `__dirname`, `process.cwd()` and literals, or
|
||||
/// `fileURLToPath(new URL(…, import.meta.url))`, with `dir` as the configuration's
|
||||
/// directory and working directory; relative literals stay relative. Aliases computed any
|
||||
/// other way (variables, functions, regular expressions) are skipped.
|
||||
pub fn bundler_aliases(text: &str, dir: &Path) -> Vec<(String, String)> {
|
||||
let language = Language::new(tree_sitter_typescript::LANGUAGE_TYPESCRIPT);
|
||||
let Some(tree) = parse(&language, text, None) else { return Vec::new() };
|
||||
let rollup = text.contains("@rollup/plugin-alias");
|
||||
let cx = Cx { src: text, dir };
|
||||
let mut out = Vec::new();
|
||||
let mut stack = vec![tree.root_node()];
|
||||
while let Some(node) = stack.pop() {
|
||||
if node.kind() == "pair"
|
||||
&& let (Some(key), Some(value)) = (node.child_by_field_name("key"), node.child_by_field_name("value"))
|
||||
&& match cx.name(key) {
|
||||
Some("alias") => true,
|
||||
Some("entries") => rollup,
|
||||
_ => false,
|
||||
}
|
||||
{
|
||||
cx.collect(value, &mut out);
|
||||
}
|
||||
stack.extend(node.named_children(&mut node.walk()));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
struct Cx<'a> {
|
||||
src: &'a str,
|
||||
dir: &'a Path,
|
||||
}
|
||||
|
||||
impl Cx<'_> {
|
||||
fn text(&self, n: Node) -> &str {
|
||||
n.utf8_text(self.src.as_bytes()).unwrap_or("")
|
||||
}
|
||||
|
||||
/// A non-computed property key's name.
|
||||
fn name(&self, key: Node) -> Option<&str> {
|
||||
match key.kind() {
|
||||
"property_identifier" => Some(self.text(key)),
|
||||
"string" => self.literal(key),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The value of a string literal without escapes.
|
||||
fn literal(&self, s: Node) -> Option<&str> {
|
||||
match s.named_children(&mut s.walk()).collect::<Vec<_>>()[..] {
|
||||
[] => Some(""),
|
||||
[f] if f.kind() == "string_fragment" => Some(self.text(f)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn collect(&self, value: Node, out: &mut Vec<(String, String)>) {
|
||||
let value = unwrap(value);
|
||||
match value.kind() {
|
||||
"object" => {
|
||||
for pair in value.named_children(&mut value.walk()).filter(|n| n.kind() == "pair") {
|
||||
let name = pair.child_by_field_name("key").and_then(|k| self.name(k));
|
||||
let target = pair.child_by_field_name("value").and_then(|v| self.eval(v));
|
||||
if let (Some(name), Some(target)) = (name, target) {
|
||||
out.push((name.to_owned(), target));
|
||||
}
|
||||
}
|
||||
}
|
||||
"array" => {
|
||||
for entry in value.named_children(&mut value.walk()).map(unwrap).filter(|n| n.kind() == "object") {
|
||||
let field = |field: &str| {
|
||||
entry.named_children(&mut entry.walk()).find_map(|p| {
|
||||
let key = p.child_by_field_name("key").filter(|_| p.kind() == "pair")?;
|
||||
(self.name(key) == Some(field)).then(|| p.child_by_field_name("value")).flatten()
|
||||
})
|
||||
};
|
||||
let name = field("find").filter(|f| f.kind() == "string").and_then(|f| self.literal(f));
|
||||
let target = field("replacement").and_then(|r| self.eval(r));
|
||||
if let (Some(name), Some(target)) = (name, target) {
|
||||
out.push((name.to_owned(), target));
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The path `n` statically evaluates to.
|
||||
fn eval(&self, n: Node) -> Option<String> {
|
||||
let n = unwrap(n);
|
||||
match n.kind() {
|
||||
"string" => self.literal(n).map(str::to_owned),
|
||||
"template_string" => {
|
||||
let mut s = String::new();
|
||||
for part in n.named_children(&mut n.walk()) {
|
||||
match part.kind() {
|
||||
"string_fragment" => s.push_str(self.text(part)),
|
||||
"template_substitution" => s.push_str(&self.eval(part.named_child(0)?)?),
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
Some(s)
|
||||
}
|
||||
"identifier" if self.text(n) == "__dirname" => Some(self.dir_string()),
|
||||
"call_expression" => {
|
||||
let callee = n.child_by_field_name("function")?;
|
||||
let args = n.child_by_field_name("arguments")?;
|
||||
let args: Vec<Node> = args.named_children(&mut args.walk()).collect();
|
||||
match self.callee_name(callee)? {
|
||||
"resolve" => {
|
||||
let mut path = self.dir.to_path_buf();
|
||||
for arg in args {
|
||||
path.push(self.eval(arg)?);
|
||||
}
|
||||
Some(normalize(&path))
|
||||
}
|
||||
"join" => {
|
||||
let parts: Option<Vec<String>> = args.into_iter().map(|a| self.eval(a)).collect();
|
||||
Some(normalize(Path::new(&parts?.join("/"))))
|
||||
}
|
||||
"fileURLToPath" if args.len() == 1 => self.file_url(args[0]),
|
||||
"cwd" if args.is_empty() && self.text(callee) == "process.cwd" => Some(self.dir_string()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
// `new URL('./src', import.meta.url).pathname`
|
||||
"member_expression" if n.child_by_field_name("property").is_some_and(|p| self.text(p) == "pathname") => {
|
||||
self.file_url(n.child_by_field_name("object")?)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `path.resolve` / `resolve` / `path.posix.join` / … → `resolve`.
|
||||
fn callee_name(&self, callee: Node) -> Option<&str> {
|
||||
match callee.kind() {
|
||||
"identifier" => Some(self.text(callee)),
|
||||
"member_expression" => callee.child_by_field_name("property").map(|p| self.text(p)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `new URL('./src', import.meta.url)` → `<dir>/src`.
|
||||
fn file_url(&self, n: Node) -> Option<String> {
|
||||
let n = unwrap(n);
|
||||
if n.kind() != "new_expression" || n.child_by_field_name("constructor").map(|c| self.text(c)) != Some("URL") {
|
||||
return None;
|
||||
}
|
||||
let args = n.child_by_field_name("arguments")?;
|
||||
let [spec, base] = args.named_children(&mut args.walk()).collect::<Vec<_>>()[..] else { return None };
|
||||
if self.text(base) != "import.meta.url" {
|
||||
return None;
|
||||
}
|
||||
let spec = self.eval(spec)?;
|
||||
Some(normalize(&self.dir.join(spec.trim_start_matches('/'))))
|
||||
}
|
||||
|
||||
fn dir_string(&self) -> String {
|
||||
self.dir.to_string_lossy().into_owned()
|
||||
}
|
||||
}
|
||||
|
||||
/// Through `( … )`, `… as T`, `… satisfies T`.
|
||||
fn unwrap(n: Node) -> Node {
|
||||
match n.kind() {
|
||||
"parenthesized_expression" | "as_expression" | "satisfies_expression" | "non_null_expression" => {
|
||||
n.named_child(0).map_or(n, unwrap)
|
||||
}
|
||||
_ => n,
|
||||
}
|
||||
}
|
||||
|
||||
/// Lexical `.` / `..` removal, like Node's `path.resolve`.
|
||||
fn normalize(path: &Path) -> String {
|
||||
let mut out = PathBuf::new();
|
||||
for c in path.components() {
|
||||
match c {
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir => {
|
||||
if !out.pop() && !out.has_root() {
|
||||
out.push("..");
|
||||
}
|
||||
}
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// With `/` separators, so that the expectations hold on Windows too.
|
||||
fn aliases(text: &str) -> Vec<(String, String)> {
|
||||
bundler_aliases(text, Path::new("/p")).into_iter().map(|(a, t)| (a, t.replace('\\', "/"))).collect()
|
||||
}
|
||||
|
||||
fn pairs(list: &[(&str, &str)]) -> Vec<(String, String)> {
|
||||
list.iter().map(|(a, b)| ((*a).to_owned(), (*b).to_owned())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_vite_object_aliases() {
|
||||
let text = r#"import { defineConfig } from 'vite';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath, URL } from 'node:url';
|
||||
export default defineConfig({
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, 'src'),
|
||||
comps: path.resolve(__dirname, './src/components'),
|
||||
'~lib': fileURLToPath(new URL('./lib', import.meta.url)),
|
||||
up: path.join(__dirname, '..', 'shared'),
|
||||
root: '/src',
|
||||
tpl: `${__dirname}/tpl`,
|
||||
cwd: path.resolve(process.cwd(), 'app'),
|
||||
vue: 'vue/dist/vue.esm-bundler.js',
|
||||
dynamic: someDir,
|
||||
[computed]: path.resolve(__dirname, 'x'),
|
||||
},
|
||||
},
|
||||
});"#;
|
||||
assert_eq!(
|
||||
aliases(text),
|
||||
pairs(&[
|
||||
("@", "/p/src"),
|
||||
("comps", "/p/src/components"),
|
||||
("~lib", "/p/lib"),
|
||||
("up", "/shared"),
|
||||
("root", "/src"),
|
||||
("tpl", "/p/tpl"),
|
||||
("cwd", "/p/app"),
|
||||
("vue", "vue/dist/vue.esm-bundler.js"),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_array_aliases_and_rollup_entries() {
|
||||
let vite = r#"export default {
|
||||
resolve: { alias: [
|
||||
{ find: '@', replacement: resolve(__dirname, 'src') },
|
||||
{ find: /^~(.*)$/, replacement: '$1' },
|
||||
{ find: 'x', replacement: compute() },
|
||||
] },
|
||||
};"#;
|
||||
assert_eq!(aliases(vite), pairs(&[("@", "/p/src")]));
|
||||
let rollup = r#"import alias from '@rollup/plugin-alias';
|
||||
export default { plugins: [alias({ entries: [{ find: 'utils', replacement: './src/utils' }] })] };"#;
|
||||
assert_eq!(aliases(rollup), pairs(&[("utils", "./src/utils")]));
|
||||
// `entries` means nothing without the alias plugin.
|
||||
assert!(aliases("export default { entries: { a: './a' } };").is_empty());
|
||||
let esbuild = r#"require('esbuild').build({ entryPoints: ['a.js'], alias: { '@': './src' } });"#;
|
||||
assert_eq!(aliases(esbuild), pairs(&[("@", "./src")]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_configurations_yield_nothing() {
|
||||
assert!(
|
||||
aliases("export default defineConfig(({ mode }) => ({ resolve: { alias: makeAliases(mode) } }));")
|
||||
.is_empty()
|
||||
);
|
||||
assert!(aliases("this is not { javascript").is_empty());
|
||||
assert!(aliases("").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Tree-sitter driven structure: outline, folding, symbol tags, selection ranges, highlighting.
|
||||
|
||||
mod bundler_aliases;
|
||||
mod cache;
|
||||
mod configuration;
|
||||
mod external;
|
||||
@@ -21,6 +22,7 @@ mod vue;
|
||||
mod web;
|
||||
|
||||
use crate::{FoldRange, LanguageConfig, LanguageRegistry, ScriptRegion, SymbolTag};
|
||||
pub use bundler_aliases::bundler_aliases;
|
||||
pub use cache::{MAX_CACHED_TREES, SyntaxCache, SyntaxCacheStats};
|
||||
pub use configuration::ConfigurationKey;
|
||||
pub use external::{ExternalFold, ExternalSymbol, ExternalSyntax, ExternalToken, set_external_syntax};
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
//!
|
||||
//! Definitions (`.card`, `#main`, `--accent`) come from stylesheets and the
|
||||
//! `<style>` elements of HTML documents and feed the symbol index (see
|
||||
//! [`super::Syntax::tags`]), so a lookup is an exact index query.
|
||||
//! [`super::Syntax::tags`]), so a lookup is an exact index query. A `--name` symbol carries
|
||||
//! its declared value as its container.
|
||||
|
||||
use super::lines::{LineIndex, byte_at};
|
||||
use super::{Grammar, parse};
|
||||
@@ -119,17 +120,17 @@ pub(crate) fn definitions(g: &Grammar, css: Option<&Grammar>, tree: &Tree, text:
|
||||
walk(css_tree.root_node(), &mut |n| {
|
||||
let def = match n.kind() {
|
||||
"class_name" if n.parent().is_some_and(|p| p.kind() == "class_selector") => {
|
||||
Some((format!(".{}", text_of(n, css_text)), CSS_CLASS))
|
||||
Some((format!(".{}", text_of(n, css_text)), CSS_CLASS, None))
|
||||
}
|
||||
"id_name" => Some((format!("#{}", text_of(n, css_text)), CSS_ID)),
|
||||
"id_name" => Some((format!("#{}", text_of(n, css_text)), CSS_ID, None)),
|
||||
"property_name" if text_of(n, css_text).starts_with("--") => {
|
||||
Some((text_of(n, css_text).to_owned(), CSS_VARIABLE))
|
||||
Some((text_of(n, css_text).to_owned(), CSS_VARIABLE, declared_value(n, css_text)))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some((name, kind)) = def {
|
||||
if let Some((name, kind, container)) = def {
|
||||
let range = idx.range(base + n.start_byte(), base + n.end_byte());
|
||||
out.push(SymbolTag { name, kind, container: None, range, bases: Vec::new() });
|
||||
out.push(SymbolTag { name, kind, container, range, bases: Vec::new() });
|
||||
}
|
||||
true
|
||||
});
|
||||
@@ -137,6 +138,18 @@ pub(crate) fn definitions(g: &Grammar, css: Option<&Grammar>, tree: &Tree, text:
|
||||
out
|
||||
}
|
||||
|
||||
/// The value a custom property declares (`n` is its `property_name`), whitespace collapsed and
|
||||
/// cut at [`MAX_VALUE_CHARS`]: the container of its `--name` symbol, so completion and hover
|
||||
/// show it without reading the file.
|
||||
fn declared_value(n: Node, text: &str) -> Option<String> {
|
||||
let decl = n.parent().filter(|p| p.kind() == "declaration")?;
|
||||
let rest = text.get(n.end_byte()..decl.end_byte())?.trim_start().strip_prefix(':')?;
|
||||
let value = rest.trim().trim_end_matches(';').split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
(!value.is_empty()).then(|| value.chars().take(MAX_VALUE_CHARS).collect())
|
||||
}
|
||||
|
||||
const MAX_VALUE_CHARS: usize = 120;
|
||||
|
||||
/// The whitespace-separated token of `value` (starting at byte `base`) around byte `at`.
|
||||
fn token_at(value: &str, base: usize, at: usize) -> Option<(usize, &str)> {
|
||||
let rel = at.checked_sub(base)?;
|
||||
|
||||
@@ -881,6 +881,94 @@ async fn vue_hybrid_mode_end_to_end() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The path-alias tsserver plugin (`ide-sdk/src/path-aliases.js`) on vtsls: a Vite alias the
|
||||
/// tsconfig doesn't define resolves, completes and isn't reported; one it defines keeps the
|
||||
/// tsconfig's target. Set `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i @vtsls/language-server typescript@6`.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires @vtsls/language-server (OPENIDEA_TEST_NPM_TOOLS)"]
|
||||
async fn bundler_path_aliases_resolve_below_tsconfig_paths() {
|
||||
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
let slash = |p: &Path| p.to_string_lossy().replace('\\', "/");
|
||||
for dir in ["src", "own", "plugin/node_modules/openidea-path-aliases"] {
|
||||
std::fs::create_dir_all(root.join(dir)).unwrap();
|
||||
}
|
||||
// What the settings hook writes for `alias: { '@': path.resolve(__dirname, 'src') }`.
|
||||
let plugin = root.join("plugin/node_modules/openidea-path-aliases");
|
||||
std::fs::write(plugin.join("index.js"), include_str!("../../ide-sdk/src/path-aliases.js")).unwrap();
|
||||
let src = slash(&root.join("src"));
|
||||
let paths = serde_json::json!({ slash(&root): { "@": [src], "@/*": [format!("{src}/*")] } });
|
||||
std::fs::write(plugin.join("paths.json"), paths.to_string()).unwrap();
|
||||
std::fs::write(root.join("package.json"), "{\"name\":\"app\",\"private\":true}").unwrap();
|
||||
let tsconfig = |paths: &str| {
|
||||
format!(
|
||||
"{{\"compilerOptions\":{{\"strict\":true,\"module\":\"ESNext\",\"moduleResolution\":\"Bundler\"{paths}}},\"include\":[\"src\"]}}"
|
||||
)
|
||||
};
|
||||
std::fs::write(root.join("tsconfig.json"), tsconfig("")).unwrap();
|
||||
std::fs::write(root.join("src/a.ts"), "export const answer = 42;\n").unwrap();
|
||||
std::fs::write(root.join("own/a.ts"), "export const answer = 1;\n").unwrap();
|
||||
let main = root.join("src/main.ts");
|
||||
let text = "import { answer } from '@/a';\nimport '@/';\nconst n: number = answer + '';\n";
|
||||
std::fs::write(&main, text).unwrap();
|
||||
let init = serde_json::json!({ "vtsls": { "tsserver": { "globalPlugins": [{
|
||||
"name": "openidea-path-aliases",
|
||||
"location": root.join("plugin").to_string_lossy(),
|
||||
"enableForWorkspaceTypeScriptVersions": true,
|
||||
}] } } });
|
||||
let ts = || lang("typescript", "ts", npm_server(&tools, "vtsls", "vtsls", Some(init.clone())));
|
||||
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![ts()]));
|
||||
let doc = DocId::next();
|
||||
mgr.did_open(doc, &main, &LanguageId::new("typescript"), 1, text);
|
||||
let defs = retry("definition through the alias", Duration::from_secs(90), || {
|
||||
let mgr = mgr.clone();
|
||||
let a = root.join("src/a.ts");
|
||||
// The syntax server answers with the import itself until the project is loaded.
|
||||
async move {
|
||||
mgr.goto(doc, Pos::new(0, 10), GotoKind::Definition).await.ok().filter(|d| d.iter().any(|d| d.path == a))
|
||||
}
|
||||
})
|
||||
.await;
|
||||
assert_eq!(defs.len(), 1);
|
||||
retry("path completion after @/", Duration::from_secs(30), || {
|
||||
let mgr = mgr.clone();
|
||||
async move {
|
||||
let list = mgr.completion(doc, Pos::new(1, 10), Some("/".into()), Default::default()).await.ok()?;
|
||||
list.items.iter().any(|i| i.label == "a" || i.label == "a.ts").then_some(())
|
||||
}
|
||||
})
|
||||
.await;
|
||||
// The deliberate type error is reported; the aliased import is not.
|
||||
let diagnostics = retry("diagnostics", Duration::from_secs(30), || {
|
||||
let found = events.lock().iter().rev().find_map(|e| match e {
|
||||
IdeEvent::Diagnostics { path, items, .. } if path == &main && !items.is_empty() => Some(items.clone()),
|
||||
_ => None,
|
||||
});
|
||||
async move { found }
|
||||
})
|
||||
.await;
|
||||
assert!(diagnostics.iter().all(|d| !d.message.contains("Cannot find module")), "{diagnostics:?}");
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
|
||||
// The tsconfig's own `@/*` wins.
|
||||
std::fs::write(root.join("tsconfig.json"), tsconfig(",\"paths\":{\"@/*\":[\"./own/*\"]}")).unwrap();
|
||||
let (mgr, _events) = manager(&root, LanguageRegistry::from_configs(vec![ts()]));
|
||||
let doc = DocId::next();
|
||||
mgr.did_open(doc, &main, &LanguageId::new("typescript"), 1, text);
|
||||
let defs = retry("definition through the tsconfig paths", Duration::from_secs(90), || {
|
||||
let mgr = mgr.clone();
|
||||
let own = root.join("own/a.ts");
|
||||
async move {
|
||||
mgr.goto(doc, Pos::new(0, 10), GotoKind::Definition).await.ok().filter(|d| d.iter().any(|d| d.path == own))
|
||||
}
|
||||
})
|
||||
.await;
|
||||
assert_eq!(defs.len(), 1);
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
|
||||
const NG_APP_TS: &str = "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.html',\n})\nexport class App {\n title = 'demo';\n}\n";
|
||||
const NG_APP_HTML: &str = "<h1>{{ title }}</h1>\n<p>{{ missing }}</p>\n";
|
||||
const NG_INLINE_TS: &str = "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-inline',\n template: `<b>{{ count }}</b>`,\n})\nexport class Inline {\n count = 1;\n}\n";
|
||||
|
||||
+337
@@ -0,0 +1,337 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "anyhow"
|
||||
version = "1.0.104"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
|
||||
|
||||
[[package]]
|
||||
name = "foldhash"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.17.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||
dependencies = [
|
||||
"foldhash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "id-arena"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "2.14.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown",
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "leb128fmt"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
|
||||
|
||||
[[package]]
|
||||
name = "macro-string"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "openidea-plugin"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"wit-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "openidea-plugin-netsetting"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"openidea-plugin",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prettyplease"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "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"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.154"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "wasm-encoder"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a"
|
||||
dependencies = [
|
||||
"leb128fmt",
|
||||
"wasmparser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-metadata"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"indexmap",
|
||||
"wasm-encoder",
|
||||
"wasmparser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmparser"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"hashbrown",
|
||||
"indexmap",
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.63.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"wit-bindgen-rust-macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen-core"
|
||||
version = "0.63.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"heck",
|
||||
"wit-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen-rust"
|
||||
version = "0.63.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"heck",
|
||||
"indexmap",
|
||||
"prettyplease",
|
||||
"syn",
|
||||
"wasm-metadata",
|
||||
"wit-bindgen-core",
|
||||
"wit-component",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen-rust-macro"
|
||||
version = "0.63.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"macro-string",
|
||||
"prettyplease",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"wit-bindgen-core",
|
||||
"wit-bindgen-rust",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-component"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bitflags",
|
||||
"indexmap",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"wasm-encoder",
|
||||
"wasm-metadata",
|
||||
"wasmparser",
|
||||
"wit-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-parser"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"hashbrown",
|
||||
"id-arena",
|
||||
"indexmap",
|
||||
"log",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"unicode-ident",
|
||||
"wasmparser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "openidea-plugin-netsetting"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
[workspace]
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
openidea-plugin = { path = "../../../../../sdk/rust/openidea-plugin" }
|
||||
serde_json = "1"
|
||||
|
||||
[profile.release]
|
||||
opt-level = "s"
|
||||
lto = true
|
||||
strip = true
|
||||
codegen-units = 1
|
||||
panic = "abort"
|
||||
Бінарний файл не відображається.
@@ -0,0 +1 @@
|
||||
04c8f881e25aae1b7298f554f3c4ab38251eec48e8d88656d73cad019eb1644c
|
||||
@@ -0,0 +1,17 @@
|
||||
id = "netsetting"
|
||||
name = "Setting-derived network grants"
|
||||
version = "0.1.0"
|
||||
engines.openidea = "^1.18"
|
||||
wasm = "dist/plugin.wasm"
|
||||
activation = ["on-command:*"]
|
||||
|
||||
[capabilities]
|
||||
required = ["storage"]
|
||||
optional = ["net:setting:server", "net.http:setting:server"]
|
||||
|
||||
[contributes.settings]
|
||||
schema = "settings.json"
|
||||
|
||||
[[contributes.commands]]
|
||||
id = "fetch"
|
||||
title = "fetch"
|
||||
@@ -0,0 +1 @@
|
||||
{"properties":{"server":{"type":"string","title":"Server","default":""}}}
|
||||
@@ -0,0 +1,178 @@
|
||||
use openidea_plugin::{Error, Event, Invocation, Plugin, StatusItem, StatusMenuEntry, host, register_plugin};
|
||||
#[derive(Default)]
|
||||
struct Api14;
|
||||
impl Plugin for Api14 {
|
||||
fn run_command(&mut self, id: &str, ctx: &Invocation, arg: Option<&str>) -> Result<Option<String>, Error> {
|
||||
let arg = arg.unwrap_or_default();
|
||||
match id {
|
||||
"open-editors" => Ok(Some(format!("{:?}", host::open_editors()?))),
|
||||
"open-editor" => {
|
||||
host::open_editor(arg, Some(openidea_plugin::Range::default()))?;
|
||||
Ok(None)
|
||||
}
|
||||
"set-selections" => {
|
||||
ctx.editor().unwrap().set_selections(&[openidea_plugin::Range::default()])?;
|
||||
Ok(None)
|
||||
}
|
||||
"reveal" => {
|
||||
ctx.editor().unwrap().reveal(openidea_plugin::Range::default())?;
|
||||
Ok(None)
|
||||
}
|
||||
"search-text" => {
|
||||
let result = ctx
|
||||
.project()
|
||||
.unwrap()
|
||||
.search_text(&openidea_plugin::TextQuery { pattern: arg.into(), ..Default::default() }, 10)?;
|
||||
Ok(Some(format!("{result:?}")))
|
||||
}
|
||||
"read-bytes" => Ok(Some(format!("{:?}", ctx.project().unwrap().read_bytes(arg)?))),
|
||||
"problems" => Ok(Some(format!("{:?}", host::problems(if arg.is_empty() { None } else { Some(arg) })?))),
|
||||
"decorations" => {
|
||||
host::set_decorations(
|
||||
arg,
|
||||
"test",
|
||||
&[openidea_plugin::Decoration {
|
||||
range: openidea_plugin::Range::default(),
|
||||
style: "highlight".into(),
|
||||
hover: Some("hover".into()),
|
||||
after: Some("after".into()),
|
||||
}],
|
||||
)?;
|
||||
Ok(None)
|
||||
}
|
||||
"clear-decorations" => {
|
||||
host::clear_decorations("test")?;
|
||||
Ok(None)
|
||||
}
|
||||
"file-decoration" => {
|
||||
host::set_file_decoration(
|
||||
arg,
|
||||
"test",
|
||||
&openidea_plugin::FileDecoration { badge: Some("OK".into()), style: "added".into(), tooltip: None },
|
||||
)?;
|
||||
Ok(None)
|
||||
}
|
||||
"clear-file-decorations" => {
|
||||
host::clear_file_decorations("test")?;
|
||||
Ok(None)
|
||||
}
|
||||
"vcs-log" => Ok(Some(format!(
|
||||
"{:?}",
|
||||
ctx.project().unwrap().vcs_log(if arg.is_empty() { None } else { Some(arg) }, 10)?
|
||||
))),
|
||||
"vcs-blame" => Ok(Some(format!("{:?}", ctx.project().unwrap().vcs_blame(arg)?))),
|
||||
"vcs-diff" => ctx.project().unwrap().vcs_diff(if arg.is_empty() { None } else { Some(arg) }, None),
|
||||
"ipc" => {
|
||||
let stream = host::ipc_connect(arg)?;
|
||||
stream.write(b"echo")?;
|
||||
let bytes = stream.read(4, 2000)?;
|
||||
stream.close()?;
|
||||
Ok(Some(String::from_utf8_lossy(&bytes).into()))
|
||||
}
|
||||
"fetch" => {
|
||||
let response = host::fetch(&openidea_plugin::HttpRequest::get(arg))?;
|
||||
Ok(Some(String::from_utf8_lossy(&response.body).into()))
|
||||
}
|
||||
"global-status" | "window-status" => {
|
||||
let item = StatusItem { text: arg.into(), tooltip: None, command: Some("events".into()) };
|
||||
if id == "global-status" {
|
||||
host::set_status_item("state", &item);
|
||||
} else {
|
||||
host::set_window_status_item("state", &item)?;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
"menu-status" | "bad-menu-status" => {
|
||||
let item = StatusItem { text: arg.into(), tooltip: None, command: None };
|
||||
let command = if id == "menu-status" { "events" } else { "undeclared" };
|
||||
let menu = [
|
||||
StatusMenuEntry::Header("App".into()),
|
||||
StatusMenuEntry::action("Open", command).with_description("https://app.test").with_argument("web"),
|
||||
StatusMenuEntry::Separator,
|
||||
];
|
||||
host::set_status_item_menu("menu", &item, &menu)?;
|
||||
Ok(None)
|
||||
}
|
||||
"remove-window-status" => {
|
||||
host::remove_window_status_item("state")?;
|
||||
Ok(None)
|
||||
}
|
||||
"execute" => host::execute_command(arg, Some("argument")),
|
||||
"oauth" => {
|
||||
let redirect = host::begin_loopback("oauth/callback")?;
|
||||
host::output_append("oauth", &redirect.redirect_uri())?;
|
||||
redirect.wait(2000)
|
||||
}
|
||||
"secret" => {
|
||||
host::secret_set("token", arg)?;
|
||||
Ok(None)
|
||||
}
|
||||
"delete-secret" => {
|
||||
host::secret_delete("token")?;
|
||||
Ok(None)
|
||||
}
|
||||
"undeclared-secret" => {
|
||||
host::secret_set("undeclared", arg)?;
|
||||
Ok(None)
|
||||
}
|
||||
"output" => {
|
||||
host::output_append("test", arg)?;
|
||||
host::output_reveal("test")?;
|
||||
Ok(None)
|
||||
}
|
||||
"process-run" => Ok(Some(host::run_process("api14-tool", &[], None)?.stdout)),
|
||||
"process-run-command" => Ok(Some(host::run_command(&host::Command::new("api14-tool"), None, None)?.stdout)),
|
||||
"process-start" => {
|
||||
let child = host::start(&host::Command::new("api14-tool"), None)?;
|
||||
Ok(Some(child.wait(2000)?.stdout))
|
||||
}
|
||||
"terminal" => {
|
||||
host::open_terminal("API test", "api14-tool", &[])?;
|
||||
Ok(None)
|
||||
}
|
||||
"log" => {
|
||||
host::open_log_tab(
|
||||
"api-test",
|
||||
"API test",
|
||||
&openidea_plugin::details::ProcessLog {
|
||||
program: "api14-tool".into(),
|
||||
args: Vec::new(),
|
||||
toggles: Vec::new(),
|
||||
},
|
||||
)?;
|
||||
Ok(None)
|
||||
}
|
||||
"events" => host::storage::get("events"),
|
||||
_ => Err(Error::NotFound(id.into())),
|
||||
}
|
||||
}
|
||||
fn handle_events(&mut self, events: &[Event], ctx: &Invocation) {
|
||||
let mut received: Vec<serde_json::Value> =
|
||||
host::storage::get("events").unwrap().map(|s| serde_json::from_str(&s).unwrap()).unwrap_or_default();
|
||||
for event in events {
|
||||
if let Event::Other { kind, data } = event {
|
||||
let editor = ctx.editor().map(|e| {
|
||||
(
|
||||
e.path(),
|
||||
e.selections()
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|r| [r.start.line, r.start.character, r.end.line, r.end.character])
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
});
|
||||
received.push(serde_json::json!({ "kind": kind, "data": data, "editor": editor }));
|
||||
}
|
||||
}
|
||||
host::storage::set("events", &serde_json::to_string(&received).unwrap()).unwrap();
|
||||
}
|
||||
}
|
||||
impl openidea_plugin::TestResults for Api14 {
|
||||
fn parse(&mut self, _config: &str, _chunk: &str) -> Vec<openidea_plugin::PluginTestEvent> {
|
||||
vec![]
|
||||
}
|
||||
fn select_tests(&mut self, config: &str, tests: &[Vec<String>]) -> Option<Vec<String>> {
|
||||
(config == "tests").then(|| tests.iter().map(|p| p.join("::")).collect())
|
||||
}
|
||||
}
|
||||
register_plugin!(Api14, test_results);
|
||||
@@ -123,7 +123,7 @@ fn source_location(entry: &Value) -> Option<(PathBuf, u32)> {
|
||||
/// Adds a V8 CPU profile (`node --cpu-prof`), weighted by sampled time in milliseconds.
|
||||
pub(crate) fn add_cpuprofile(b: &mut TreeBuilder, json: &str) -> Result<(), String> {
|
||||
let v: Value = serde_json::from_str(json).map_err(|e| e.to_string())?;
|
||||
let nodes = v.get("nodes").and_then(Value::as_array).ok_or("not a CPU profile: no nodes")?;
|
||||
let nodes = v.get("nodes").and_then(Value::as_array).ok_or("no nodes")?;
|
||||
let mut by_id: HashMap<i64, &Value> = HashMap::new();
|
||||
let mut parent: HashMap<i64, i64> = HashMap::new();
|
||||
for n in nodes {
|
||||
|
||||
@@ -109,6 +109,8 @@ pub enum ProfileSpec {
|
||||
/// ran no code of `root` (the package manager of an npm script) are left
|
||||
/// out when another one did.
|
||||
CpuProfiles { dir: IpcPath, root: IpcPath },
|
||||
/// One `.cpuprofile` the user opened (saved by `node --cpu-prof`, Chrome DevTools, CI).
|
||||
CpuProfileFile { path: IpcPath },
|
||||
/// Collapsed-stack files with extension `ext` in `dir`; relative frame files resolve
|
||||
/// against `base`. `jvm_root`: map JVM class frames to sources below it. For the
|
||||
/// allocation modes the last frame of a JVM stack is the allocated type.
|
||||
@@ -172,6 +174,26 @@ pub fn collect(spec: &ProfileSpec) -> IdeResult<Profile> {
|
||||
}
|
||||
Ok(b.finish("node --cpu-prof", "ms", ProfileMode::Cpu))
|
||||
}
|
||||
ProfileSpec::CpuProfileFile { path } => {
|
||||
let path: &Path = path.as_ref();
|
||||
let name =
|
||||
path.file_name().map_or_else(|| path.display().to_string(), |n| n.to_string_lossy().into_owned());
|
||||
let text =
|
||||
std::fs::read_to_string(path).map_err(|e| IdeError::invalid(format!("Cannot read {name}: {e}")))?;
|
||||
formats::add_cpuprofile(&mut b, &text)
|
||||
.map_err(|e| IdeError::invalid(format!("{name} is not a V8 CPU profile ({e}).")))?;
|
||||
if b.is_empty() {
|
||||
return Err(IdeError::invalid(format!("{name} has no samples.")));
|
||||
}
|
||||
let mut profile = b.finish("V8 CPU profile", "ms", ProfileMode::Cpu);
|
||||
// A profile recorded on another machine (CI) names files that aren't here.
|
||||
for f in &mut profile.frames {
|
||||
if f.file.as_ref().is_some_and(|p| !p.is_file()) {
|
||||
(f.file, f.line) = (None, None);
|
||||
}
|
||||
}
|
||||
Ok(profile)
|
||||
}
|
||||
ProfileSpec::Folded { profiler, dir, ext, base, jvm_root, mode } => {
|
||||
for f in files_with_ext(dir, ext) {
|
||||
formats::add_folded(&mut b, &std::fs::read_to_string(&f)?, base, *mode != ProfileMode::Cpu);
|
||||
@@ -251,6 +273,48 @@ mod tests {
|
||||
assert!(p.frames.iter().any(|f| f.name == "byte[]" && f.kind == ProfileFrameKind::AllocatedType));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_opened_cpuprofile_keeps_only_local_sources() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let src = dir.path().join("index.js");
|
||||
std::fs::write(&src, "").unwrap();
|
||||
let url = |p: &Path| format!("file://{}", p.display()).replace('\\', "/");
|
||||
let json = format!(
|
||||
r#"{{"nodes":[
|
||||
{{"id":1,"callFrame":{{"functionName":"(root)","url":"","lineNumber":-1}},"children":[2,3]}},
|
||||
{{"id":2,"callFrame":{{"functionName":"here","url":"{}","lineNumber":3}}}},
|
||||
{{"id":3,"callFrame":{{"functionName":"onCi","url":"file:///home/runner/work/app/x.js","lineNumber":1}}}}],
|
||||
"samples":[2,3,2],"timeDeltas":[0,1000,1000]}}"#,
|
||||
url(&src)
|
||||
);
|
||||
let path = dir.path().join("CPU.cpuprofile");
|
||||
std::fs::write(&path, json).unwrap();
|
||||
let p = collect(&ProfileSpec::CpuProfileFile { path: path.into() }).unwrap();
|
||||
assert_eq!((p.unit.as_str(), p.mode), ("ms", ProfileMode::Cpu));
|
||||
let frame = |name: &str| p.frames.iter().find(|f| f.name == name).unwrap();
|
||||
assert_eq!(frame("here").file.as_deref(), Some(src.as_path()));
|
||||
assert_eq!(frame("here").line, Some(3));
|
||||
assert_eq!((frame("onCi").file.as_ref(), frame("onCi").line), (None, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_opened_file_that_is_no_cpuprofile_is_an_error() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for (file, text, says) in [
|
||||
("notes.cpuprofile", "hello", "is not a V8 CPU profile"),
|
||||
("other.cpuprofile", r#"{"a":1}"#, "is not a V8 CPU profile (no nodes)"),
|
||||
("empty.cpuprofile", r#"{"nodes":[],"samples":[],"timeDeltas":[]}"#, "has no samples"),
|
||||
] {
|
||||
let path = dir.path().join(file);
|
||||
std::fs::write(&path, text).unwrap();
|
||||
let err = collect(&ProfileSpec::CpuProfileFile { path: path.into() }).unwrap_err();
|
||||
assert_eq!(err.message.split_once(' ').unwrap().0, file);
|
||||
assert!(err.message.contains(says), "{}", err.message);
|
||||
}
|
||||
let missing = collect(&ProfileSpec::CpuProfileFile { path: dir.path().join("gone.cpuprofile").into() });
|
||||
assert!(missing.unwrap_err().message.starts_with("Cannot read gone.cpuprofile"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpu_profile_stays_in_samples() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -8,6 +8,7 @@ license.workspace = true
|
||||
[dependencies]
|
||||
ide-core.workspace = true
|
||||
ide-language.workspace = true
|
||||
ide-workspace.workspace = true
|
||||
dunce.workspace = true
|
||||
encoding_rs.workspace = true
|
||||
serde.workspace = true
|
||||
|
||||
@@ -120,6 +120,8 @@ struct FileConfig {
|
||||
target: Option<String>,
|
||||
#[serde(alias = "testRunner")]
|
||||
test_runner: Option<String>,
|
||||
#[serde(default)]
|
||||
watch: bool,
|
||||
}
|
||||
|
||||
pub(crate) fn slug(s: &str) -> String {
|
||||
@@ -186,6 +188,7 @@ fn convert(configs: Vec<FileConfig>, local: bool) -> Vec<RunConfig> {
|
||||
stop_command: non_empty(c.stop_command),
|
||||
target: non_empty(c.target),
|
||||
test_runner: non_empty(c.test_runner),
|
||||
watch: c.watch,
|
||||
executor: None,
|
||||
},
|
||||
});
|
||||
@@ -288,6 +291,7 @@ fn to_table(c: &RunConfig) -> Table {
|
||||
("show-on-stderr", x.show_on_stderr),
|
||||
("focus-tool-window", x.focus_tool_window),
|
||||
("emulate-terminal", x.emulate_terminal),
|
||||
("watch", x.watch),
|
||||
] {
|
||||
if on {
|
||||
t.insert(key, value(true));
|
||||
|
||||
@@ -84,11 +84,16 @@ pub(crate) fn detect_with_profiles(
|
||||
}
|
||||
}
|
||||
detect_projects(root, &["build.zig"], zig::detect, &mut out);
|
||||
dotnet::detect(root, &mut out);
|
||||
// A UE project's `.sln` lists the engine's own tool projects; expanding it would bury the
|
||||
// run menu under dozens of `.NET Project` entries that cannot run from here.
|
||||
if !ide_workspace::unreal::is_project(root) {
|
||||
dotnet::detect(root, &mut out);
|
||||
}
|
||||
detect_projects(root, &["Makefile", "makefile", "GNUmakefile"], detect_make, &mut out);
|
||||
detect_projects(root, &["justfile", "Justfile", ".justfile"], detect_just, &mut out);
|
||||
detect_godot(root, &mut out);
|
||||
detect_projects(root, &["pubspec.yaml"], detect_flutter, &mut out);
|
||||
detect_unreal(root, &mut out);
|
||||
crate::external::detect(root, &mut out);
|
||||
|
||||
let mut seen = HashSet::new();
|
||||
@@ -235,16 +240,23 @@ pub(crate) fn is_test_script(name: &str) -> bool {
|
||||
}
|
||||
|
||||
/// The test runner a `package.json` script starts, when its output and test selection differ
|
||||
/// from Jest / Vitest's: `playwright test`, `mocha`, or `node --test` (`tsx --test`) with Node's own
|
||||
/// from Jest / Vitest's: `playwright test`, `cypress run`, `mocha`, or `node --test` (`tsx --test`) with Node's own
|
||||
/// reporters (the IDE adds its reporter next to them, which a reporter chosen here would clash with).
|
||||
fn script_test_runner(script: &str) -> Option<&'static str> {
|
||||
let tokens: Vec<&str> = script.split(|c: char| c.is_whitespace() || matches!(c, '&' | '|' | ';')).collect();
|
||||
if tokens.windows(2).any(|w| w[0] == "playwright" && w[1] == "test") {
|
||||
return Some("playwright");
|
||||
}
|
||||
if tokens.windows(2).any(|w| w[0] == "cypress" && w[1] == "run") {
|
||||
return Some("cypress");
|
||||
}
|
||||
if tokens.iter().any(|t| matches!(t.rsplit('/').next(), Some("mocha" | "_mocha"))) {
|
||||
return Some("mocha");
|
||||
}
|
||||
// Jasmine too, through the IDE's hook like Mocha.
|
||||
if tokens.iter().any(|t| matches!(t.rsplit('/').next(), Some("jasmine" | "jasmine.js"))) {
|
||||
return Some("jasmine");
|
||||
}
|
||||
let node = tokens.iter().position(|t| matches!(*t, "node" | "tsx"))?;
|
||||
// Node's own options: up to the script (`node server.js --test` passes `--test` to the program).
|
||||
let mut options = Vec::new();
|
||||
@@ -271,6 +283,15 @@ const PLAYWRIGHT_CONFIGS: &[&str] = &[
|
||||
"playwright.config.cjs",
|
||||
];
|
||||
|
||||
const CYPRESS_CONFIGS: &[&str] = &[
|
||||
"cypress.config.ts",
|
||||
"cypress.config.js",
|
||||
"cypress.config.mts",
|
||||
"cypress.config.mjs",
|
||||
"cypress.config.cts",
|
||||
"cypress.config.cjs",
|
||||
];
|
||||
|
||||
/// Pushes the package's scripts; returns the test runners they start.
|
||||
fn push_scripts(
|
||||
pkg: &Json,
|
||||
@@ -325,6 +346,29 @@ fn push_playwright(
|
||||
out.push(c);
|
||||
}
|
||||
|
||||
/// `npx cypress run` for a package that depends on Cypress or has its configuration, when no script runs it.
|
||||
fn push_cypress(
|
||||
dir: &Path,
|
||||
pkg: &Json,
|
||||
runners: &HashSet<&str>,
|
||||
prefix: Option<&str>,
|
||||
cwd: Option<PathBuf>,
|
||||
out: &mut Vec<RunConfig>,
|
||||
) {
|
||||
let depends =
|
||||
["dependencies", "devDependencies"].iter().any(|k| pkg.get(k).and_then(|d| d.get("cypress")).is_some());
|
||||
if runners.contains("cypress") || !(depends || first_existing(dir, CYPRESS_CONFIGS).is_some()) {
|
||||
return;
|
||||
}
|
||||
let (id, name) = match prefix {
|
||||
Some(p) => (format!("cypress:{p}"), format!("{p}: cypress run")),
|
||||
None => ("cypress".to_owned(), "cypress run".to_owned()),
|
||||
};
|
||||
let mut c = config(id, name, "cypress", "npx", &["cypress", "run"]).in_dir(cwd.clone()).test();
|
||||
c.extras.module = cwd.as_deref().map(ide_core::ipc_path::to_ipc);
|
||||
out.push(c);
|
||||
}
|
||||
|
||||
fn detect_node(root: &Path, out: &mut Vec<RunConfig>) {
|
||||
let mut covered = HashSet::new();
|
||||
let projects =
|
||||
@@ -342,7 +386,8 @@ fn detect_node(root: &Path, out: &mut Vec<RunConfig>) {
|
||||
let prefix = (dir != root).then_some(label.as_str());
|
||||
let cwd = (dir != root).then_some(rel);
|
||||
let runners = push_scripts(&pkg, pm, prefix, cwd.clone(), out);
|
||||
push_playwright(&dir, &runners, prefix, cwd, out);
|
||||
push_playwright(&dir, &runners, prefix, cwd.clone(), out);
|
||||
push_cypress(&dir, &pkg, &runners, prefix, cwd, out);
|
||||
for member_dir in ide_core::project_roots::node_workspace_members(&dir) {
|
||||
if !covered.insert(member_dir.clone()) {
|
||||
continue;
|
||||
@@ -356,7 +401,8 @@ fn detect_node(root: &Path, out: &mut Vec<RunConfig>) {
|
||||
.unwrap_or_else(|| ide_core::ipc_path::to_ipc(&rel));
|
||||
let name = if dir == root { name } else { format!("{label}:{name}") };
|
||||
let runners = push_scripts(&member, pm, Some(&name), Some(rel.clone()), out);
|
||||
push_playwright(&member_dir, &runners, Some(&name), Some(rel), out);
|
||||
push_playwright(&member_dir, &runners, Some(&name), Some(rel.clone()), out);
|
||||
push_cypress(&member_dir, &member, &runners, Some(&name), Some(rel), out);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1567,6 +1613,49 @@ pub(crate) fn just_recipes(src: &str) -> Vec<String> {
|
||||
|
||||
// ---------------------------------------------------------------- godot
|
||||
|
||||
// ---------------------------------------------------------------- unreal
|
||||
|
||||
/// Unreal Engine projects (`.uproject`) run through the engine's editor executable, which reads
|
||||
/// its start-up mode from the command line: no flag is the editor, `-game` the game and `-server`
|
||||
/// a dedicated server. All three exist for every project, blueprint-only ones included, because
|
||||
/// the mode is decided at start-up rather than built.
|
||||
fn detect_unreal(root: &Path, out: &mut Vec<RunConfig>) {
|
||||
detect_projects_matching(root, |dir| ide_workspace::unreal::project_file(dir).is_some(), detect_one_unreal, out);
|
||||
}
|
||||
|
||||
/// One Unreal project: the editor, the game and a dedicated server, all run by the same
|
||||
/// `UnrealEditor.exe` and differing only in the flag.
|
||||
fn detect_one_unreal(root: &Path, out: &mut Vec<RunConfig>) {
|
||||
let Some(info) = ide_workspace::unreal::detect(root) else { return };
|
||||
// Detection already resolved the engine; a project without one offers nothing to run.
|
||||
let Some(found) = info.engine.as_ref() else {
|
||||
tracing::debug!("no Unreal Engine installation for {}", root.display());
|
||||
return;
|
||||
};
|
||||
let engine =
|
||||
ide_workspace::unreal::engine::EngineInstall { id: found.id.clone(), root: PathBuf::from(&found.root) };
|
||||
let Some(project) = ide_workspace::unreal::project_file(root) else { return };
|
||||
let editor = engine.editor().to_string_lossy().into_owned();
|
||||
out.extend(unreal_configs(&project, &editor));
|
||||
}
|
||||
|
||||
/// The editor, the game and a dedicated server: the three start-up modes the engine documents,
|
||||
/// all run by `UnrealEditor.exe` and differing only in the flag.
|
||||
fn unreal_configs(project: &Path, editor: &str) -> Vec<RunConfig> {
|
||||
let project = project.to_string_lossy().into_owned();
|
||||
[
|
||||
("unreal:editor", "Unreal Editor", None),
|
||||
("unreal:game", "Unreal Game", Some("-game")),
|
||||
("unreal:server", "Unreal Server", Some("-server")),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(id, name, flag)| {
|
||||
let args: Vec<&str> = std::iter::once(project.as_str()).chain(flag).collect();
|
||||
config(id.to_owned(), name, "unreal", editor, &args).debug("lldb-dap")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- rebar3 / mix
|
||||
|
||||
/// rebar3 (Erlang): the shell with the applications started, the EUnit tests and, with
|
||||
@@ -1649,3 +1738,23 @@ fn detect_just(root: &Path, out: &mut Vec<RunConfig>) {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_unreal_project_offers_the_editor_the_game_and_a_dedicated_server() {
|
||||
let configs = unreal_configs(Path::new("/p/Game.uproject"), "UE/UnrealEditor.exe");
|
||||
let listed: Vec<(&str, &str)> = configs.iter().map(|c| (c.id.as_str(), c.name.as_str())).collect();
|
||||
assert_eq!(
|
||||
listed,
|
||||
[("unreal:editor", "Unreal Editor"), ("unreal:game", "Unreal Game"), ("unreal:server", "Unreal Server"),]
|
||||
);
|
||||
assert_eq!(configs[0].args, ["/p/Game.uproject"]);
|
||||
assert_eq!(configs[1].args, ["/p/Game.uproject", "-game"]);
|
||||
assert_eq!(configs[2].args, ["/p/Game.uproject", "-server"]);
|
||||
assert!(configs.iter().all(|c| c.command == "UE/UnrealEditor.exe" && c.cwd.is_none()));
|
||||
assert!(configs.iter().all(|c| c.debug_adapter.as_deref() == Some("lldb-dap") && c.kind == "unreal"));
|
||||
}
|
||||
}
|
||||
@@ -19,11 +19,15 @@ pub(crate) fn detect(root: &Path, out: &mut Vec<RunConfig>) {
|
||||
let path = entry.path();
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
if entry.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
if !name.starts_with('.')
|
||||
// Case-insensitive: Unreal's generated trees (`Binaries`, `Intermediate`, …) hold
|
||||
// tens of thousands of files and copies of the engine's own tool projects.
|
||||
let lower = name.to_ascii_lowercase();
|
||||
if !lower.starts_with('.')
|
||||
&& !matches!(
|
||||
name.as_str(),
|
||||
lower.as_str(),
|
||||
"bin" | "obj" | "node_modules" | "target" | "build" | "dist" | "vendor" | "packages"
|
||||
)
|
||||
&& !ide_workspace::unreal::GENERATED_DIRS.iter().any(|dir| dir.eq_ignore_ascii_case(&lower))
|
||||
{
|
||||
dirs.push(path);
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ const COMMON: &[&str] = &["cwd", "env", "envFile"];
|
||||
const PYTHON_LAUNCH: &[&str] = &["program", "module", "args", "python", "pythonArgs"];
|
||||
const PYTHON_ATTACH: &[&str] = &["connect", "host", "port", "pathMappings"];
|
||||
const NODE_LAUNCH: &[&str] = &["program", "args", "runtimeExecutable", "runtimeArgs"];
|
||||
const NODE_ATTACH: &[&str] = &["address", "port", "localRoot", "remoteRoot"];
|
||||
const NODE_ATTACH: &[&str] = &["address", "port", "localRoot", "remoteRoot", "restart"];
|
||||
const NODE_TERMINAL: &[&str] = &["command"];
|
||||
const BROWSER_LAUNCH: &[&str] = &["url", "webRoot"];
|
||||
const DART_LAUNCH: &[&str] = &["program", "args", "toolArgs", "deviceId", "flutterMode"];
|
||||
@@ -254,6 +254,10 @@ impl Cx<'_> {
|
||||
if obj.get("pathMappings").and_then(Value::as_array).is_some_and(|m| m.len() > 1) {
|
||||
ignored.push("pathMappings".into());
|
||||
}
|
||||
// A restart policy's delays and attempts: the option reconnects with js-debug's defaults.
|
||||
if handled.contains(&"restart") && obj.get("restart").is_some_and(Value::is_object) {
|
||||
ignored.push("restart".into());
|
||||
}
|
||||
ignored.sort();
|
||||
Ok(Found { config, members: Vec::new(), ignored })
|
||||
}
|
||||
@@ -349,6 +353,10 @@ impl Cx<'_> {
|
||||
let port = self.string(obj, "port")?.unwrap_or_else(|| "9229".into());
|
||||
let mut c = config(name, "node-remote", String::new(), Vec::new(), Some("js-debug"));
|
||||
c.extras.params = BTreeMap::from([("host".into(), host), ("port".into(), port)]);
|
||||
// Reconnect automatically: `true`, or a restart policy object (its delays are noted as ignored).
|
||||
if matches!(obj.get("restart"), Some(Value::Bool(true) | Value::Object(_))) {
|
||||
c.extras.params.insert("restart".into(), "true".into());
|
||||
}
|
||||
self.roots(obj, &mut c)?;
|
||||
Ok(c)
|
||||
}
|
||||
|
||||
@@ -188,6 +188,10 @@ pub struct RunExtras {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub test_runner: Option<String>,
|
||||
/// Jest / Vitest "Watch for changes": the run stays alive and reruns the tests after each edit.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
#[specta(optional)]
|
||||
pub watch: bool,
|
||||
/// The plugin executor a launch goes through ("Run with <title>"): the plugin's id. Set
|
||||
/// on the launched copy, not saved; the plugin's executor-bound Java agent loads only then.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
@@ -217,6 +221,7 @@ impl Default for RunExtras {
|
||||
stop_command: None,
|
||||
target: None,
|
||||
test_runner: None,
|
||||
watch: false,
|
||||
executor: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,6 +134,7 @@ fn extras_round_trip_and_local_file() {
|
||||
shared.extras.open_tool_window = Some(false);
|
||||
shared.extras.focus_tool_window = true;
|
||||
shared.extras.emulate_terminal = true;
|
||||
shared.extras.watch = true;
|
||||
shared.extras.stop_command = Some("docker stop server".into());
|
||||
let mut local = sample().remove(1);
|
||||
local.extras.local = true;
|
||||
|
||||
@@ -76,6 +76,31 @@ fn playwright_scripts_and_configs() {
|
||||
assert_eq!(site.debug_adapter.as_deref(), Some("js-debug"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cypress_scripts_dependencies_and_configs() {
|
||||
let dir = project(&[
|
||||
("package.json", r#"{"scripts":{"cy:run":"cypress run --browser chrome","cy:open":"cypress open"}}"#),
|
||||
("cypress.config.ts", ""),
|
||||
("web/package.json", r#"{"devDependencies":{"cypress":"^15.0.0"}}"#),
|
||||
("docs/package.json", r#"{"scripts":{"build":"vite build"}}"#),
|
||||
("docs/cypress.config.js", ""),
|
||||
]);
|
||||
let c = detect(dir.path());
|
||||
let run = find(&c, "npm:cy:run");
|
||||
assert!(run.is_test);
|
||||
assert_eq!(run.extras.test_runner.as_deref(), Some("cypress"));
|
||||
assert!(!find(&c, "npm:cy:open").is_test);
|
||||
// The root's script runs Cypress already.
|
||||
assert!(!ids(&c).contains(&"cypress"));
|
||||
let web = find(&c, "cypress:web");
|
||||
assert_eq!(cmdline(web), "npx cypress run");
|
||||
assert_eq!(web.name, "web: cypress run");
|
||||
assert!(web.is_test && web.detected);
|
||||
assert_eq!(web.kind, "cypress");
|
||||
assert_eq!(web.cwd.as_deref(), Some(Path::new("web")));
|
||||
assert_eq!(find(&c, "cypress:docs").kind, "cypress");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn node_test_scripts() {
|
||||
let dir = project(&[(
|
||||
@@ -106,6 +131,20 @@ fn mocha_scripts() {
|
||||
assert!(!find(&c, "npm:lint").is_test);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jasmine_scripts() {
|
||||
let dir = project(&[(
|
||||
"package.json",
|
||||
r#"{"scripts":{"spec":"jasmine --config=spec/support/jasmine.json","test":"tsc && node node_modules/jasmine/bin/jasmine.js","browser":"jasmine-browser-runner runSpecs"}}"#,
|
||||
)]);
|
||||
let c = detect(dir.path());
|
||||
let spec = find(&c, "npm:spec");
|
||||
assert!(spec.is_test);
|
||||
assert_eq!(spec.extras.test_runner.as_deref(), Some("jasmine"));
|
||||
assert_eq!(find(&c, "npm:test").extras.test_runner.as_deref(), Some("jasmine"));
|
||||
assert!(!find(&c, "npm:browser").is_test);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_manager_selection() {
|
||||
for (lock, pm) in [("yarn.lock", "yarn"), ("bun.lockb", "bun"), ("bun.lock", "bun"), ("package-lock.json", "npm")] {
|
||||
@@ -1378,3 +1417,40 @@ fn sbt_projects() {
|
||||
assert_eq!(cmdline(&detect(dir.path())[1]), "./sbt test");
|
||||
}
|
||||
}
|
||||
|
||||
/// UE writes a `.sln` listing the engine's own tool projects; expanding it buries the run menu.
|
||||
#[test]
|
||||
fn a_solution_in_a_unreal_project_is_not_expanded_into_dotnet_configurations() {
|
||||
let dir = project(&[
|
||||
("Game.uproject", r#"{"FileVersion":3,"EngineAssociation":"5.8"}"#),
|
||||
(
|
||||
"Game.sln",
|
||||
r#"Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Game", "Source\Game\Game.csproj", "{00000000-0000-0000-0000-000000000000}"
|
||||
EndProject
|
||||
"#,
|
||||
),
|
||||
(
|
||||
"Source/Game/Game.csproj",
|
||||
r#"<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType></PropertyGroup></Project>"#,
|
||||
),
|
||||
]);
|
||||
let c = detect(dir.path());
|
||||
assert!(c.iter().all(|c| !c.kind.starts_with("dotnet")), "{:?}", ids(&c));
|
||||
}
|
||||
|
||||
/// The engine keeps copies of its tool projects under the generated trees, which hold no code
|
||||
/// anyone runs from here — and on a real project they are deep enough to slow detection down.
|
||||
#[test]
|
||||
fn csproj_under_unreal_generated_directories_is_not_detected() {
|
||||
let exe =
|
||||
r#"<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType></PropertyGroup></Project>"#;
|
||||
let dir = project(&[
|
||||
("Intermediate/ProjectFiles/UnrealBuildTool/UnrealBuildTool.csproj", exe),
|
||||
("Binaries/Win64/ShaderCopy/ShaderCopy.csproj", exe),
|
||||
("Saved/Tools/Helper/Helper.csproj", exe),
|
||||
("DerivedDataCache/Worker/Worker.csproj", exe),
|
||||
]);
|
||||
let c = detect(dir.path());
|
||||
assert!(c.is_empty(), "{:?}", ids(&c));
|
||||
}
|
||||
@@ -380,6 +380,9 @@ fn attach_requests_become_remote_debug_configurations() {
|
||||
"pathMappings": [{ "localRoot": "${workspaceFolder}", "remoteRoot": "/app" }] },
|
||||
{ "name": "Attach to Node", "type": "node", "request": "attach", "port": 9230,
|
||||
"localRoot": "${workspaceFolder}/web", "remoteRoot": "/usr/src/app", "restart": true },
|
||||
{ "name": "Attach (no restart)", "type": "pwa-node", "request": "attach", "restart": false },
|
||||
{ "name": "Attach (restart policy)", "type": "node", "request": "attach",
|
||||
"restart": { "delay": 500, "maxAttempts": 5 } },
|
||||
{ "name": "Attach to PID", "type": "debugpy", "request": "attach", "processId": "${command:pickProcess}" },
|
||||
{ "name": "Odd", "type": "node", "request": "test" }
|
||||
]
|
||||
@@ -402,7 +405,13 @@ fn attach_requests_become_remote_debug_configurations() {
|
||||
assert_eq!(node.extras.params["port"], "9230");
|
||||
assert_eq!(node.extras.params["localRoot"], "web");
|
||||
assert_eq!(node.extras.params["remoteRoot"], "/usr/src/app");
|
||||
assert_eq!(ignored(&r, "Attach to Node"), ["restart"]);
|
||||
assert_eq!(node.extras.params["restart"], "true");
|
||||
assert!(ignored(&r, "Attach to Node").is_empty());
|
||||
let off = get(&r, "Attach (no restart)");
|
||||
assert!(!off.extras.params.contains_key("restart"));
|
||||
assert!(ignored(&r, "Attach (no restart)").is_empty());
|
||||
assert_eq!(get(&r, "Attach (restart policy)").extras.params["restart"], "true");
|
||||
assert_eq!(ignored(&r, "Attach (restart policy)"), ["restart"]);
|
||||
|
||||
assert_eq!(reason(&r, "Attach to PID"), &SkipReason::UnsupportedAttach);
|
||||
assert_eq!(reason(&r, "Odd"), &SkipReason::UnsupportedRequest { request: "test".into() });
|
||||
|
||||
@@ -905,7 +905,7 @@ pub fn native_tsdk(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
const PYTHON_SERVERS: [&str; 8] =
|
||||
["basedpyright", "pyright", "ty", "pyrefly", "pylsp", "jedi-language-server", "ruff", "djlsp"];
|
||||
|
||||
pub(crate) fn merge(base: &mut Value, layer: Value) {
|
||||
pub fn merge(base: &mut Value, layer: Value) {
|
||||
match (base, layer) {
|
||||
(Value::Object(base), Value::Object(layer)) => {
|
||||
for (k, v) in layer {
|
||||
@@ -1513,7 +1513,10 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
|
||||
&& !server_root.ancestors().any(|d| d.join("tsconfig.json").is_file() || d.join("jsconfig.json").is_file())
|
||||
{
|
||||
let node = node_dir(root, s).map(|d| d.join(exe("node"))).filter(|p| p.is_file()).or_else(|| which("node"));
|
||||
cfg.tsserver_project_extras.paths = vue::cli_paths(server_root, node.as_deref());
|
||||
let mut paths = vue::cli_paths(server_root, node.as_deref());
|
||||
// The project's own Vite / Rollup / esbuild aliases replace the Vue template's `@`.
|
||||
paths.extend(crate::path_aliases::paths(server_root));
|
||||
cfg.tsserver_project_extras.paths = paths;
|
||||
}
|
||||
if name == vue::SERVER {
|
||||
configure_vue_typescript(cfg, root, server_root, s);
|
||||
@@ -1610,6 +1613,42 @@ pub fn configure_vue_module_resolution(cfg: &mut LanguageServerConfig, data_dir:
|
||||
true
|
||||
}
|
||||
|
||||
/// Registers the tsserver plugin that adds the Vite / Rollup / esbuild path aliases of each
|
||||
/// package under `server_root` to that package's tsserver projects' `paths`, below
|
||||
/// tsconfig.json / jsconfig.json's own (#6020). Only vtsls hosts tsserver plugins (not
|
||||
/// TypeScript 7's native server). No-op without aliases.
|
||||
pub fn configure_path_aliases(cfg: &mut LanguageServerConfig, server_root: &Path, data_dir: &Path) -> bool {
|
||||
if cfg.name != "vtsls" || !cfg.tsserver_project {
|
||||
return false;
|
||||
}
|
||||
let packages = crate::path_aliases::packages(server_root);
|
||||
if packages.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let Some(plugin) = crate::path_aliases::tsserver_plugin(data_dir, server_root, &packages) else {
|
||||
return false;
|
||||
};
|
||||
let mut current =
|
||||
cfg.initialization_options.as_ref().and_then(|v| serde_json::to_value(v).ok()).unwrap_or_else(|| json!({}));
|
||||
let mut node = &mut current;
|
||||
for key in ["vtsls", "tsserver"] {
|
||||
node = object_entry(node, key);
|
||||
}
|
||||
let plugins =
|
||||
node.as_object_mut().expect("made an object above").entry("globalPlugins").or_insert_with(|| json!([]));
|
||||
if !plugins.is_array() {
|
||||
*plugins = json!([]);
|
||||
}
|
||||
let plugins = plugins.as_array_mut().expect("made an array above");
|
||||
plugins.retain(|p| p.get("name").and_then(Value::as_str) != Some(crate::path_aliases::PLUGIN));
|
||||
plugins.push(plugin);
|
||||
match toml::Value::try_from(current) {
|
||||
Ok(v) => cfg.initialization_options = Some(v),
|
||||
Err(e) => tracing::warn!("{}: cannot apply settings to initialization options: {e}", cfg.name),
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The servers `language` uses after Settings › Language Servers: the
|
||||
/// definition's ones that aren't disabled, then the ones defined in settings for it.
|
||||
pub fn language_servers(language: &str, defined: &[LanguageServerConfig], s: &Settings) -> Vec<LanguageServerConfig> {
|
||||
|
||||
@@ -23,6 +23,7 @@ pub mod locate;
|
||||
pub mod lombok;
|
||||
pub mod maven_profiles;
|
||||
mod npm;
|
||||
mod path_aliases;
|
||||
pub mod php;
|
||||
pub mod pinned;
|
||||
pub mod python;
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
"use strict";
|
||||
// Adds a project's Vite / Rollup / esbuild path aliases to every tsserver project's
|
||||
// `compilerOptions.paths`, below the project's own `paths`: tsserver reads only
|
||||
// tsconfig.json / jsconfig.json, so `@/` imports resolved by the bundler resolve to nothing
|
||||
// in the editor and complete no paths. The IDE writes the aliases of each directory holding
|
||||
// a bundler configuration, as absolute `paths` entries, to `paths.json` next to this file.
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const key = (dir) => {
|
||||
const resolved = path.resolve(dir);
|
||||
return process.platform === "win32" ? resolved.toLowerCase() : resolved;
|
||||
};
|
||||
|
||||
// The aliases of the configuration nearest `dir` within its package: a workspace member
|
||||
// gets its own configuration's, never the monorepo root's.
|
||||
function aliasesFor(packages, dir) {
|
||||
for (dir = path.resolve(dir); ; dir = path.dirname(dir)) {
|
||||
const aliases = packages.get(key(dir));
|
||||
if (aliases) return aliases;
|
||||
if (fs.existsSync(path.join(dir, "package.json")) || path.dirname(dir) === dir) return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = () => ({
|
||||
create(info) {
|
||||
const host = info.languageServiceHost;
|
||||
let aliases;
|
||||
try {
|
||||
const packages = JSON.parse(fs.readFileSync(path.join(__dirname, "paths.json"), "utf8"));
|
||||
const byDir = new Map(Object.entries(packages).map(([dir, paths]) => [key(dir), paths]));
|
||||
aliases = aliasesFor(byDir, info.project.getCurrentDirectory());
|
||||
} catch {
|
||||
return info.languageService;
|
||||
}
|
||||
if (!aliases || !host || typeof host.getCompilationSettings !== "function") {
|
||||
return info.languageService;
|
||||
}
|
||||
const getCompilationSettings = host.getCompilationSettings.bind(host);
|
||||
// The same options object while the project's own stay the same, so the program is kept.
|
||||
let own;
|
||||
let merged;
|
||||
host.getCompilationSettings = () => {
|
||||
const options = getCompilationSettings();
|
||||
if (options !== own) {
|
||||
own = options;
|
||||
merged = { ...options, paths: { ...aliases, ...options.paths } };
|
||||
}
|
||||
return merged;
|
||||
};
|
||||
return info.languageService;
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,250 @@
|
||||
//! Path aliases of the project's Vite, Rollup (`@rollup/plugin-alias`) or esbuild
|
||||
//! configuration, for tsserver (vtsls), which only reads tsconfig.json / jsconfig.json
|
||||
//! `paths`. Read statically: the configuration is never run.
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::path::Path;
|
||||
|
||||
pub(crate) type Paths = std::collections::BTreeMap<String, Vec<String>>;
|
||||
/// [`paths`] of each directory holding a bundler configuration, by directory (`/` separated).
|
||||
pub(crate) type Packages = std::collections::BTreeMap<String, Paths>;
|
||||
|
||||
/// The tsserver plugin that adds a project's [`Packages`] entry to its `compilerOptions.paths`.
|
||||
pub(crate) const PLUGIN: &str = "openidea-path-aliases";
|
||||
const PLUGIN_JS: &str = include_str!("path-aliases.js");
|
||||
|
||||
/// Configurations read, in priority order (the first one defining an alias wins).
|
||||
const CONFIGS: &[&str] = &[
|
||||
"vite.config.ts",
|
||||
"vite.config.mts",
|
||||
"vite.config.cts",
|
||||
"vite.config.js",
|
||||
"vite.config.mjs",
|
||||
"vite.config.cjs",
|
||||
"rollup.config.ts",
|
||||
"rollup.config.mts",
|
||||
"rollup.config.js",
|
||||
"rollup.config.mjs",
|
||||
"rollup.config.cjs",
|
||||
"esbuild.config.ts",
|
||||
"esbuild.config.mts",
|
||||
"esbuild.config.js",
|
||||
"esbuild.config.mjs",
|
||||
"esbuild.config.cjs",
|
||||
];
|
||||
|
||||
/// `compilerOptions.paths` (`@/*` → `<root>/src/*`) for the directory aliases of the
|
||||
/// bundler configurations in `root` itself. Empty without any.
|
||||
pub(crate) fn paths(root: &Path) -> Paths {
|
||||
let mut aliases: Vec<(String, String)> = Vec::new();
|
||||
for config in CONFIGS.iter().map(|f| root.join(f)) {
|
||||
let Ok(text) = std::fs::read_to_string(&config) else { continue };
|
||||
for (name, target) in ide_language::bundler_aliases(&text, root) {
|
||||
if !aliases.iter().any(|(n, _)| *n == name) {
|
||||
aliases.push((name, target_dir(root, &target)));
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::vue::alias_paths(&aliases)
|
||||
}
|
||||
|
||||
/// The aliases of every package (workspace member) under `root`: the bundler configurations
|
||||
/// of each directory down to a monorepo's `apps/web` / `packages/ui/demo`, honouring ignore
|
||||
/// files and skipping `node_modules`. The plugin gives a tsserver project the entry of its
|
||||
/// own package only.
|
||||
pub(crate) fn packages(root: &Path) -> Packages {
|
||||
// ponytail: bounded walk; deeper workspace members go without aliases.
|
||||
const MAX_DEPTH: usize = 4;
|
||||
const MAX_ENTRIES: usize = 50_000;
|
||||
let mut walker = ignore::WalkBuilder::new(root);
|
||||
walker
|
||||
.max_depth(Some(MAX_DEPTH))
|
||||
.require_git(ide_core::ignored::inside_git_repo(root))
|
||||
.follow_links(false)
|
||||
.filter_entry(|e| e.file_name() != "node_modules");
|
||||
let mut dirs: Vec<std::path::PathBuf> = walker
|
||||
.build()
|
||||
.take(MAX_ENTRIES)
|
||||
.flatten()
|
||||
.filter(|e| CONFIGS.iter().any(|c| e.file_name() == *c))
|
||||
.filter_map(|e| e.path().parent().map(Path::to_path_buf))
|
||||
.collect();
|
||||
dirs.sort();
|
||||
dirs.dedup();
|
||||
dirs.into_iter()
|
||||
.map(|dir| (dir.to_string_lossy().replace('\\', "/"), paths(&dir)))
|
||||
.filter(|(_, paths)| !paths.is_empty())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Vite resolves `/src` from the project root; esbuild a relative target from the working
|
||||
/// directory (the project root here). A `/`-rooted target without a drive or UNC prefix is
|
||||
/// root-relative on Windows too, unless it is an existing directory elsewhere.
|
||||
fn target_dir(root: &Path, target: &str) -> String {
|
||||
let path = Path::new(target);
|
||||
let path = if path.is_absolute() && (path.is_dir() || !target.starts_with('/')) {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
root.join(target.trim_start_matches('/').trim_start_matches("./"))
|
||||
};
|
||||
path.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// The vtsls `globalPlugins` entry of the plugin, written with `packages` under `data_dir`.
|
||||
/// Each server root gets its own copy, as the plugin reads its aliases next to itself.
|
||||
/// `None` when the data dir cannot be written.
|
||||
pub(crate) fn tsserver_plugin(data_dir: &Path, root: &Path, packages: &Packages) -> Option<serde_json::Value> {
|
||||
let key = Sha256::digest(root.to_string_lossy().as_bytes());
|
||||
let key: String = key.iter().take(8).map(|b| format!("{b:02x}")).collect();
|
||||
let location = data_dir.join("tsplugins").join("path-aliases").join(key);
|
||||
let dir = location.join("node_modules").join(PLUGIN);
|
||||
std::fs::create_dir_all(&dir).ok()?;
|
||||
let json = serde_json::to_string(packages).ok()?;
|
||||
for (file, content) in [("index.js", PLUGIN_JS), ("paths.json", json.as_str())] {
|
||||
if std::fs::read(dir.join(file)).ok().as_deref() != Some(content.as_bytes()) {
|
||||
std::fs::write(dir.join(file), content).ok()?;
|
||||
}
|
||||
}
|
||||
Some(serde_json::json!({
|
||||
"name": PLUGIN,
|
||||
"location": location.to_string_lossy(),
|
||||
"enableForWorkspaceTypeScriptVersions": true,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn vite_aliases_become_paths() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let t = &dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::create_dir_all(t.join("src/components")).unwrap();
|
||||
std::fs::create_dir_all(t.join("lib")).unwrap();
|
||||
assert!(paths(t).is_empty());
|
||||
std::fs::write(
|
||||
t.join("vite.config.ts"),
|
||||
r#"import path from 'path';
|
||||
export default { resolve: { alias: [
|
||||
{ find: '@', replacement: path.resolve(__dirname, 'src') },
|
||||
{ find: 'comps', replacement: '/src/components' },
|
||||
{ find: 'vue', replacement: 'vue/dist/vue.esm-bundler.js' },
|
||||
] } };"#,
|
||||
)
|
||||
.unwrap();
|
||||
// A later configuration adds aliases but doesn't override the Vite ones.
|
||||
std::fs::write(
|
||||
t.join("rollup.config.mjs"),
|
||||
"import alias from '@rollup/plugin-alias';\nexport default { plugins: [alias({ entries: { '@': './lib', lib: './lib' } })] };",
|
||||
)
|
||||
.unwrap();
|
||||
let slash = |p: std::path::PathBuf| p.to_string_lossy().replace('\\', "/");
|
||||
let (src, comps, lib) = (slash(t.join("src")), slash(t.join("src/components")), slash(t.join("lib")));
|
||||
assert_eq!(
|
||||
paths(t),
|
||||
Paths::from([
|
||||
("@".into(), vec![src.clone()]),
|
||||
("@/*".into(), vec![format!("{src}/*")]),
|
||||
("comps".into(), vec![comps.clone()]),
|
||||
("comps/*".into(), vec![format!("{comps}/*")]),
|
||||
("lib".into(), vec![lib.clone()]),
|
||||
("lib/*".into(), vec![format!("{lib}/*")]),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_workspace_member_gets_its_own_configuration() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let t = &dunce::canonicalize(tmp.path()).unwrap();
|
||||
let vite = |dir: &str| {
|
||||
std::fs::create_dir_all(t.join(dir).join("src")).unwrap();
|
||||
let config = "export default { resolve: { alias: { '@': path.resolve(__dirname, 'src') } } };";
|
||||
std::fs::write(t.join(dir).join("vite.config.ts"), config).unwrap();
|
||||
};
|
||||
vite("");
|
||||
vite("apps/web");
|
||||
vite("node_modules/dep");
|
||||
std::fs::create_dir_all(t.join("packages/ui")).unwrap();
|
||||
let slash = |p: std::path::PathBuf| p.to_string_lossy().replace('\\', "/");
|
||||
let packages = packages(t);
|
||||
assert_eq!(packages.keys().cloned().collect::<Vec<_>>(), [slash(t.to_path_buf()), slash(t.join("apps/web"))]);
|
||||
assert_eq!(packages[&slash(t.join("apps/web"))]["@"], [slash(t.join("apps/web/src"))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_relative_targets_stay_in_the_root_on_every_platform() {
|
||||
let root = Path::new("/p");
|
||||
let slash = |s: String| s.replace('\\', "/");
|
||||
assert_eq!(slash(target_dir(root, "/src/components")), "/p/src/components");
|
||||
assert_eq!(slash(target_dir(root, "./lib")), "/p/lib");
|
||||
let here = std::env::current_dir().unwrap();
|
||||
assert_eq!(target_dir(root, &here.to_string_lossy()), here.to_string_lossy());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_plugin_is_written_with_its_aliases() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let packages = Packages::from([("/p".into(), Paths::from([("@/*".into(), vec!["/p/src/*".into()])]))]);
|
||||
let plugin = tsserver_plugin(tmp.path(), Path::new("/p"), &packages).unwrap();
|
||||
assert_eq!(plugin["name"], PLUGIN);
|
||||
let dir = Path::new(plugin["location"].as_str().unwrap()).join("node_modules").join(PLUGIN);
|
||||
assert_eq!(std::fs::read_to_string(dir.join("index.js")).unwrap(), PLUGIN_JS);
|
||||
assert_eq!(std::fs::read_to_string(dir.join("paths.json")).unwrap(), r#"{"/p":{"@/*":["/p/src/*"]}}"#);
|
||||
let other = tsserver_plugin(tmp.path(), Path::new("/q"), &packages).unwrap();
|
||||
assert_ne!(other["location"], plugin["location"], "one copy per server root");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_plugin_adds_the_aliases_of_the_projects_package_below_its_own_paths() {
|
||||
let Some(node) = crate::exec::which("node") else { return };
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let t = &dunce::canonicalize(tmp.path()).unwrap();
|
||||
for dir in ["", "apps/web/nested", "apps/api"] {
|
||||
std::fs::create_dir_all(t.join(dir)).unwrap();
|
||||
}
|
||||
for dir in ["", "apps/web", "apps/api"] {
|
||||
std::fs::write(t.join(dir).join("package.json"), "{}").unwrap();
|
||||
}
|
||||
let slash = |p: std::path::PathBuf| p.to_string_lossy().replace('\\', "/");
|
||||
let packages = Packages::from([
|
||||
(slash(t.to_path_buf()), Paths::from([("@/*".into(), vec!["/root/*".into()])])),
|
||||
(
|
||||
slash(t.join("apps/web")),
|
||||
Paths::from([("@/*".into(), vec!["/web/*".into()]), ("~/*".into(), vec!["/web/lib/*".into()])]),
|
||||
),
|
||||
]);
|
||||
let plugin = tsserver_plugin(&t.join("data"), t, &packages).unwrap();
|
||||
let index = Path::new(plugin["location"].as_str().unwrap()).join("node_modules").join(PLUGIN);
|
||||
// tsserver calls the factory, then `create` with the project and its host.
|
||||
let script = "const create = (dir, settings) => { const host = { getCompilationSettings: settings }; \
|
||||
require(process.argv[1])({}).create({ project: { getCurrentDirectory: () => dir }, \
|
||||
languageServiceHost: host, languageService: {} }); return host; }; \
|
||||
let own = { strict: true, paths: { '@/*': ['./own/*'] } }; \
|
||||
const web = create(process.argv[2] + '/apps/web/nested', () => own); \
|
||||
const a = web.getCompilationSettings(); const same = a === web.getCompilationSettings(); \
|
||||
own = { strict: false }; const b = web.getCompilationSettings(); \
|
||||
const api = create(process.argv[2] + '/apps/api', () => ({})).getCompilationSettings(); \
|
||||
const root = create(process.argv[2], () => ({})).getCompilationSettings(); \
|
||||
process.stdout.write(JSON.stringify({ a, same, b, api, root }));";
|
||||
let out = crate::exec::query_in(
|
||||
&node,
|
||||
&["-e", script, &index.to_string_lossy(), &t.to_string_lossy()],
|
||||
None,
|
||||
&[],
|
||||
std::time::Duration::from_secs(30),
|
||||
);
|
||||
let out: serde_json::Value = serde_json::from_str(&out.unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
out,
|
||||
serde_json::json!({
|
||||
"a": { "strict": true, "paths": { "@/*": ["./own/*"], "~/*": ["/web/lib/*"] } },
|
||||
"same": true,
|
||||
"b": { "strict": false, "paths": { "@/*": ["/web/*"], "~/*": ["/web/lib/*"] } },
|
||||
"api": {},
|
||||
"root": { "paths": { "@/*": ["/root/*"] } },
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3511,6 +3511,44 @@ fn vue_module_resolution_plugin_follows_the_vue_plugin() {
|
||||
assert_eq!(plugins.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vtsls_gets_the_path_alias_plugin_for_vite_aliases() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (root, data) = (tmp.path().join("app"), tmp.path().join("data"));
|
||||
std::fs::create_dir_all(root.join("src")).unwrap();
|
||||
let mut cfg = server("vtsls");
|
||||
cfg.tsserver_project = true;
|
||||
assert!(!crate::apply::configure_path_aliases(&mut cfg, &root, &data), "no bundler configuration");
|
||||
std::fs::write(
|
||||
root.join("vite.config.js"),
|
||||
"import path from 'path';\nexport default { resolve: { alias: { '@': path.resolve(__dirname, 'src') } } };",
|
||||
)
|
||||
.unwrap();
|
||||
let mut other = server("typescript-language-server");
|
||||
other.tsserver_project = true;
|
||||
assert!(!crate::apply::configure_path_aliases(&mut other, &root, &data));
|
||||
// TypeScript 7's native server hosts no plugins.
|
||||
let mut native = server("vtsls");
|
||||
assert!(!crate::apply::configure_path_aliases(&mut native, &root, &data));
|
||||
crate::apply::merge_init_options(
|
||||
&mut cfg,
|
||||
serde_json::json!({ "vtsls": { "tsserver": { "globalPlugins": [crate::vue::tsserver_plugin(Path::new("/vue"))] } } }),
|
||||
);
|
||||
for _ in 0..2 {
|
||||
assert!(crate::apply::configure_path_aliases(&mut cfg, &root, &data));
|
||||
let init = serde_json::to_value(cfg.initialization_options.as_ref().unwrap()).unwrap();
|
||||
let names: Vec<_> = init
|
||||
.pointer("/vtsls/tsserver/globalPlugins")
|
||||
.unwrap()
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|p| p["name"].clone())
|
||||
.collect();
|
||||
assert_eq!(names, ["@vue/typescript-plugin", "openidea-path-aliases"], "kept once, after the others");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_the_vue_plugin_the_module_resolution_plugin_stays_out() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -152,9 +152,11 @@ fn webpack_aliases(root: &Path, config: &Path, node: &Path) -> Option<Vec<(Strin
|
||||
}
|
||||
|
||||
/// Directory aliases as `paths`; `name$` (exact module) and file aliases have no equivalent.
|
||||
fn alias_paths(aliases: &[(String, String)]) -> Paths {
|
||||
pub(crate) fn alias_paths(aliases: &[(String, String)]) -> Paths {
|
||||
let mut paths = Paths::new();
|
||||
for (name, target) in aliases {
|
||||
// `'@/': '/src/'` is the `@` alias too.
|
||||
let name = name.trim_end_matches('/');
|
||||
let dir = Path::new(target);
|
||||
if name.is_empty() || name.ends_with('$') || name.contains('*') || !dir.is_absolute() || !dir.is_dir() {
|
||||
continue;
|
||||
@@ -162,7 +164,7 @@ fn alias_paths(aliases: &[(String, String)]) -> Paths {
|
||||
let dir = target.replace('\\', "/");
|
||||
let dir = dir.trim_end_matches('/');
|
||||
paths.insert(format!("{name}/*"), vec![format!("{dir}/*")]);
|
||||
paths.insert(name.clone(), vec![dir.to_owned()]);
|
||||
paths.insert(name.to_owned(), vec![dir.to_owned()]);
|
||||
}
|
||||
paths
|
||||
}
|
||||
|
||||
@@ -172,6 +172,10 @@ pub fn arguments(
|
||||
args.push("-".into());
|
||||
return args;
|
||||
}
|
||||
if tool == "dprint" {
|
||||
// dprint finds its configuration from the working directory, the file's folder.
|
||||
return vec!["fmt".into(), "--stdin".into(), file.as_os_str().to_owned()];
|
||||
}
|
||||
if tool == "biome" {
|
||||
// Biome finds its `biome.json` and ignore files from the file's path itself.
|
||||
let mut path = OsString::from("--stdin-file-path=");
|
||||
@@ -292,6 +296,30 @@ pub fn run_php_cs_fixer(mut command: Command, cancel: &CancellationToken) -> Ide
|
||||
.map_err(|e| IdeError::invalid(format!("PHP-CS-Fixer: {}", e.message.trim())))
|
||||
}
|
||||
|
||||
/// `dprint editor-info`: the plugins of the configuration dprint finds. The first run downloads
|
||||
/// them, hence the longer timeout.
|
||||
pub fn dprint_editor_info(mut command: Command) -> IdeResult<String> {
|
||||
command.arg("editor-info");
|
||||
crate::process::run_input(&mut command, "", Duration::from_secs(120), &Default::default())
|
||||
.map_err(|e| e.with_tool("dprint"))
|
||||
}
|
||||
|
||||
/// Whether a plugin listed by `dprint editor-info` formats `file`, by its extension or file name.
|
||||
pub fn dprint_covers(editor_info: &str, file: &Path) -> IdeResult<bool> {
|
||||
let info: serde_json::Value = serde_json::from_str(editor_info)
|
||||
.map_err(|e| IdeError::invalid(format!("dprint: unexpected editor-info output: {e}")).with_tool("dprint"))?;
|
||||
let Some(name) = file.file_name().and_then(|n| n.to_str()) else { return Ok(false) };
|
||||
let lower = name.to_lowercase();
|
||||
fn strings(v: &serde_json::Value) -> impl Iterator<Item = &str> {
|
||||
v.as_array().into_iter().flatten().filter_map(|s| s.as_str())
|
||||
}
|
||||
Ok(info["plugins"].as_array().into_iter().flatten().any(|plugin| {
|
||||
strings(&plugin["fileNames"]).any(|n| n == name)
|
||||
|| strings(&plugin["fileExtensions"])
|
||||
.any(|ext| lower.strip_suffix(&ext.to_lowercase()).is_some_and(|rest| rest.ends_with('.')))
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn run(tool: &str, mut command: Command, text: &str, cancel: &CancellationToken) -> IdeResult<String> {
|
||||
crate::process::run_input(&mut command, text, Duration::from_secs(15), cancel).map_err(|e| e.with_tool(tool))
|
||||
}
|
||||
@@ -457,6 +485,40 @@ mod tests {
|
||||
assert!(!supports_range("biome", &config));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dprint_runs_the_nearest_package_on_stdin_for_what_its_plugins_cover() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::create_dir_all(root.join("node_modules/dprint")).unwrap();
|
||||
std::fs::write(root.join("node_modules/dprint/package.json"), r#"{"bin":"bin.cjs"}"#).unwrap();
|
||||
std::fs::write(root.join("node_modules/dprint/bin.cjs"), "").unwrap();
|
||||
let file = root.join("packages/web/src/app.ts");
|
||||
let path = std::env::var_os("PATH").unwrap_or_default();
|
||||
let tools = Tools::with_paths(root.join("tools"), path, crate::platform::Platform::current());
|
||||
let command = tools.formatter_command("dprint", &file, None).unwrap();
|
||||
assert_eq!(Path::new(command.get_program()).file_stem().unwrap(), "node");
|
||||
|
||||
let config = FormatterConfig { tool: "prettier".into(), parser: "typescript".into(), range: true };
|
||||
let range =
|
||||
Some(FormatRange { start_offset: 3, end_offset: 9, start_line: 1, start_col: 1, end_line: 1, end_col: 7 });
|
||||
assert_eq!(
|
||||
arguments("dprint", &config, &file, 4, false, range, None),
|
||||
["fmt".into(), "--stdin".into(), file.clone().into_os_string()]
|
||||
);
|
||||
assert!(!supports_range("dprint", &config));
|
||||
|
||||
let info = r#"{"schemaVersion":5,"plugins":[
|
||||
{"fileExtensions":["ts","tsx","d.mts"],"fileNames":[]},
|
||||
{"fileExtensions":["toml"],"fileNames":["Dockerfile"]}]}"#;
|
||||
let covers = |name: &str| dprint_covers(info, &root.join(name)).unwrap();
|
||||
assert!(covers("src/app.ts") && covers("src/App.TSX") && covers("types/x.d.mts"));
|
||||
assert!(covers("Cargo.toml") && covers("Dockerfile"));
|
||||
assert!(!covers("README.md") && !covers("main.mts") && !covers("ts") && !covers("dockerfile"));
|
||||
assert!(!dprint_covers(r#"{"plugins":[]}"#, &file).unwrap());
|
||||
let invalid = dprint_covers("No config file found", &file).unwrap_err();
|
||||
assert_eq!(invalid.data, Some(ide_core::error::ErrorData::Tool { tool: "dprint".into(), missing: false }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ruff_formats_stdin_and_uses_its_config_and_range_flags() {
|
||||
let config = FormatterConfig { tool: "ruff".into(), parser: "python".into(), range: true };
|
||||
|
||||
@@ -1078,6 +1078,7 @@ impl Tools {
|
||||
},
|
||||
&specs,
|
||||
pnpm,
|
||||
!self.downloads.configured_registries_only,
|
||||
cancel,
|
||||
emit,
|
||||
)
|
||||
@@ -1463,6 +1464,12 @@ impl Tools {
|
||||
sources::openvsx_pick(&json, assets, self.platform)
|
||||
}
|
||||
ReleaseSource::MavenCentral { group, artifact } => {
|
||||
if self.downloads.configured_registries_only {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"{group}:{artifact} is downloaded from Maven Central, and Settings › Tools › Download Mirrors \
|
||||
allows only the configured package registries"
|
||||
)));
|
||||
}
|
||||
let xml = http.get_text(&sources::maven_metadata_url(group, artifact), cancel)?;
|
||||
sources::maven_pick(group, artifact, &xml)
|
||||
}
|
||||
@@ -1690,7 +1697,7 @@ impl Tools {
|
||||
// on a slow registry takes several seconds per package, more when run side by side.
|
||||
let out = match view(&[]) {
|
||||
Some((true, out)) => Some(out),
|
||||
Some((false, out)) if is_npm_registry_miss(&out) => {
|
||||
Some((false, out)) if !self.downloads.configured_registries_only && is_npm_registry_miss(&out) => {
|
||||
let extra = npm_public_registry_args([packages[0]], pnpm);
|
||||
view(&extra).and_then(|(ok, retry)| ok.then_some(retry))
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ mod tests {
|
||||
const ASSET: &str = "https://github.com/LuaLS/lua-language-server/releases/download/3.13.5/x.zip";
|
||||
|
||||
fn settings(mirror: &str) -> ToolDownloadSettings {
|
||||
ToolDownloadSettings { github_mirror: mirror.into() }
|
||||
ToolDownloadSettings { github_mirror: mirror.into(), ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -110,13 +110,15 @@ pub fn run_streamed_picking(
|
||||
}
|
||||
|
||||
/// Runs an `npm` / `pnpm` command against the user's configured registry first (preserving
|
||||
/// corporate mirrors, proxies, and CAs), and retries once against [`PUBLIC_NPM_REGISTRY`] when
|
||||
/// the configured registry misses the package/version or rejects auth. Preserves the primary
|
||||
/// error if the public registry is unreachable.
|
||||
/// corporate mirrors, proxies, and CAs), and with `public_fallback` retries once against
|
||||
/// [`PUBLIC_NPM_REGISTRY`] when the configured registry misses the package/version or rejects
|
||||
/// auth. Preserves the primary error if the public registry is unreachable. Without
|
||||
/// `public_fallback` (Settings › Tools › Download Mirrors) the configured registry's error stands.
|
||||
pub fn run_npm_with_public_fallback(
|
||||
mut build: impl FnMut(&[String]) -> Command,
|
||||
specs: &[String],
|
||||
pnpm: bool,
|
||||
public_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<String> {
|
||||
@@ -127,7 +129,7 @@ pub fn run_npm_with_public_fallback(
|
||||
return Ok(output);
|
||||
}
|
||||
let err = failed_command(&label, &output, &status);
|
||||
if cancel.is_cancelled() || !is_npm_registry_miss(&output) {
|
||||
if !public_fallback || cancel.is_cancelled() || !is_npm_registry_miss(&output) {
|
||||
return Err(err);
|
||||
}
|
||||
emit(InstallEvent::Line {
|
||||
|
||||
@@ -192,6 +192,17 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
needs: NODE,
|
||||
homepage: "https://oxc.rs/docs/guide/usage/formatter",
|
||||
},
|
||||
ToolSpec {
|
||||
name: "dprint",
|
||||
display: "dprint",
|
||||
kind: Formatter,
|
||||
commands: &["dprint"],
|
||||
method: Method::Npm { packages: &["dprint"] },
|
||||
fallback: None,
|
||||
version: ver("dprint"),
|
||||
needs: NODE,
|
||||
homepage: "https://dprint.dev",
|
||||
},
|
||||
ToolSpec {
|
||||
name: "oxlint",
|
||||
display: "oxlint",
|
||||
@@ -1355,7 +1366,7 @@ mod tests {
|
||||
known.insert((d.adapter.clone(), d.command.clone()));
|
||||
}
|
||||
}
|
||||
// The host selects the formatter of each file (Prettier, oxfmt or Biome) and runs its own CLIs.
|
||||
// The host selects the formatter of each file (Prettier, oxfmt, Biome or dprint) and runs its own CLIs.
|
||||
for t in TOOLS.iter().filter(|t| !matches!(t.kind, Plugin | Formatter | Cli)) {
|
||||
assert!(
|
||||
known.contains(&(t.name.to_string(), t.commands[0].to_string())),
|
||||
|
||||
@@ -603,6 +603,34 @@ esac"#,
|
||||
assert!(!err.message.contains("ECONNRESET"), "{}", err.message);
|
||||
}
|
||||
|
||||
/// Settings › Tools › Download Mirrors › Use only the configured package registries: a registry
|
||||
/// that refuses a package (a firewall's 403) is the answer.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn configured_registries_only_never_reach_public_registries() {
|
||||
let env = Env::new();
|
||||
let log = env.root.parent().unwrap().join("npm-only.txt");
|
||||
env.script(&env.sys, "node", "exit 0");
|
||||
env.script(
|
||||
&env.sys,
|
||||
"npm",
|
||||
&format!(
|
||||
r#"echo "$@" >> '{log}'
|
||||
echo "npm error code E403" >&2
|
||||
echo "npm error 403 Forbidden - GET https://nexus.example/yaml-language-server - quarantined" >&2
|
||||
exit 1"#,
|
||||
log = log.display()
|
||||
),
|
||||
);
|
||||
let only = ToolDownloadSettings { configured_registries_only: true, ..Default::default() };
|
||||
let tools = env.tools().with_downloads(only);
|
||||
let err = tools.install("yaml-language-server", &langs(), &CancellationToken::new(), &|_| {}).unwrap_err();
|
||||
assert!(err.message.contains("quarantined"), "{}", err.message);
|
||||
let calls = fs::read_to_string(&log).unwrap();
|
||||
assert_eq!(calls.lines().count(), 1, "{calls}");
|
||||
assert!(!calls.contains("registry.npmjs.org"), "{calls}");
|
||||
}
|
||||
|
||||
/// Servers that load TypeScript as a library get one with its JS API: `@latest`
|
||||
/// is TypeScript 7 (native, no `ts.server`), which crashed vue-language-server (#25).
|
||||
/// Uninstalling one keeps the TypeScript another installed server still uses.
|
||||
@@ -1344,7 +1372,10 @@ esac"#,
|
||||
),
|
||||
);
|
||||
// The first mirror is down: the next one is tried before the official host.
|
||||
let downloads = ToolDownloadSettings { github_mirror: "https://down.mirror.test/, https://mirror.test/".into() };
|
||||
let downloads = ToolDownloadSettings {
|
||||
github_mirror: "https://down.mirror.test/, https://mirror.test/".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let emit = |_: InstallEvent| {};
|
||||
env.tools()
|
||||
.with_downloads(downloads)
|
||||
|
||||
@@ -288,6 +288,13 @@ pub(crate) fn outgoing_commits(
|
||||
) -> Option<OutgoingCommits> {
|
||||
let name = source.shorten().to_str_lossy();
|
||||
let remote = repo.find_remote(default_push_remote(repo, remotes, Some(&name))?).ok()?;
|
||||
// As in IDEA, only a destination the branch is set up with: its upstream or a push refspec.
|
||||
// The remote branch of the same name is only what Push proposes for a new branch.
|
||||
if repo.branch_remote_ref_name(source, gix::remote::Direction::Fetch).is_none()
|
||||
&& configured_destination(repo, source, &name, remote.refspecs(gix::remote::Direction::Push)).is_none()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let target = branch_push_target(repo, source, &remote).ok()?.selection;
|
||||
if target.special_ref {
|
||||
return None;
|
||||
|
||||
@@ -162,6 +162,29 @@ impl Repo {
|
||||
blob_at(&repo, &indexed, rev)
|
||||
}
|
||||
|
||||
/// Raw bytes of the selected commit or index entry, bounded before loading its blob.
|
||||
pub fn file_bytes_at_bounded(&self, path: &Path, rev: &str, max: usize) -> IdeResult<Option<Vec<u8>>> {
|
||||
let _scope = self.execution_scope();
|
||||
let repo = self.gix()?;
|
||||
let given = self.given_rel_path(path)?;
|
||||
let indexed = self.index_spelling(given.clone());
|
||||
let Some((mode, id)) = revision_entry(&repo, &given, &indexed, rev)? else { return Ok(None) };
|
||||
if !mode.is_blob_or_symlink() {
|
||||
return Ok(None);
|
||||
}
|
||||
if let Some(header) = repo.try_find_header(id).map_err(gx)? {
|
||||
if header.size() > max as u64 {
|
||||
return Err(IdeError::invalid(format!("{} is too large to preview", path.display())));
|
||||
}
|
||||
return Ok(Some(repo.find_object(id).map_err(gx)?.detach().data));
|
||||
}
|
||||
// A partial clone may only have the tree. Keep Git's on-demand fetch under
|
||||
// the repository's execution policy and cap the bytes captured from it.
|
||||
let args = ["cat-file", "blob", &id.to_string()];
|
||||
let out = crate::cli::run_bounded(self.root(), &args, &ide_core::CancellationToken::new(), max)?;
|
||||
Ok(Some(out.stdout))
|
||||
}
|
||||
|
||||
pub fn diff_entry_at(&self, path: &Path, rev: &str) -> IdeResult<Option<DiffEntry>> {
|
||||
let _scope = self.execution_scope();
|
||||
let repo = self.gix()?;
|
||||
@@ -183,14 +206,7 @@ impl Repo {
|
||||
.and_then(|child| child.head().ok()?.1);
|
||||
return Ok(Some(DiffEntry { mode: "160000".into(), gitlink }));
|
||||
}
|
||||
let entry = if !rev.starts_with(':') && indexed != given {
|
||||
match entry_at(&repo, &given, rev)? {
|
||||
Some(entry) => Some(entry),
|
||||
None => entry_at(&repo, &indexed, rev)?,
|
||||
}
|
||||
} else {
|
||||
entry_at(&repo, &indexed, rev)?
|
||||
};
|
||||
let entry = revision_entry(&repo, &given, &indexed, rev)?;
|
||||
Ok(entry.map(|(mode, id)| DiffEntry {
|
||||
mode: format!("{:o}", mode.value()),
|
||||
gitlink: mode.is_commit().then(|| id.to_string()),
|
||||
@@ -334,6 +350,22 @@ pub(crate) fn mode_at(repo: &gix::Repository, rel: &str, rev: &str) -> IdeResult
|
||||
Ok(entry_at(repo, rel, rev)?.map(|(mode, _)| format!("{:o}", mode.value())))
|
||||
}
|
||||
|
||||
/// Prefer the spelling in the revision to a later case-only rename in the index.
|
||||
fn revision_entry(
|
||||
repo: &gix::Repository,
|
||||
given: &str,
|
||||
indexed: &str,
|
||||
rev: &str,
|
||||
) -> IdeResult<Option<(gix::objs::tree::EntryMode, gix::ObjectId)>> {
|
||||
if !rev.starts_with(':')
|
||||
&& indexed != given
|
||||
&& let Some(entry) = entry_at(repo, given, rev)?
|
||||
{
|
||||
return Ok(Some(entry));
|
||||
}
|
||||
entry_at(repo, indexed, rev)
|
||||
}
|
||||
|
||||
fn entry_at(
|
||||
repo: &gix::Repository,
|
||||
rel: &str,
|
||||
|
||||
@@ -1808,6 +1808,37 @@ fn outgoing_commits_follow_the_push_target_and_its_fetch_refspec() {
|
||||
assert!(repo.inspect_push(&selection, false, &cancel).unwrap().remote_tip.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outgoing_commits_need_an_upstream_or_a_push_refspec() {
|
||||
// A new branch reuses the name of an old one still on the server.
|
||||
let (fx, _) = Fixture::with_origin();
|
||||
fx.git(&["switch", "-q", "-c", "topic"]);
|
||||
fx.write("b.txt", "old topic\n");
|
||||
fx.commit_all("Old topic");
|
||||
fx.git(&["push", "-q", "origin", "topic"]);
|
||||
fx.git(&["switch", "-q", "main"]);
|
||||
fx.git(&["branch", "-q", "-D", "topic"]);
|
||||
fx.write("c.txt", "main\n");
|
||||
fx.commit_all("Main moves on");
|
||||
fx.git(&["push", "-q", "origin", "main"]);
|
||||
fx.git(&["switch", "-q", "--no-track", "-c", "topic", "origin/main"]);
|
||||
let repo = fx.repo();
|
||||
|
||||
let info = repo.branch_info().unwrap();
|
||||
assert!(info.upstream.is_none());
|
||||
assert!(info.outgoing.is_none());
|
||||
assert!(repo.branches().unwrap().iter().find(|b| b.current).unwrap().outgoing.is_none());
|
||||
// Push still proposes the remote branch of the same name.
|
||||
let selection = repo.default_push_target(None).unwrap().unwrap().selection;
|
||||
assert_eq!((&*selection.remote, &*selection.target), ("origin", "topic"));
|
||||
|
||||
fx.git(&["config", "remote.origin.push", "refs/heads/topic:refs/heads/topic"]);
|
||||
assert_eq!(repo.branch_info().unwrap().outgoing.map(|o| o.count), Some(1));
|
||||
fx.git(&["config", "--unset", "remote.origin.push"]);
|
||||
fx.git(&["branch", "-q", "--set-upstream-to=origin/topic"]);
|
||||
assert_eq!(repo.branch_info().unwrap().outgoing.map(|o| o.count), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn push_up_to_commit_prefers_a_containing_local_branch_and_only_publishes_the_selection() {
|
||||
let (fx, bare) = Fixture::with_origin();
|
||||
|
||||
@@ -963,6 +963,21 @@ fn file_at_revisions_and_index() {
|
||||
assert_eq!(repo.file_at(&p, Some("no-such-rev"), encoding_rs::UTF_8).unwrap_err().kind, ErrorKind::NotFound);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_revision_bytes_check_the_selected_blob_size() {
|
||||
let fx = Fixture::new();
|
||||
let path = fx.path("image.png");
|
||||
std::fs::write(&path, [0xff, 0x00, 0xfe]).unwrap();
|
||||
fx.commit_all("image");
|
||||
std::fs::write(&path, [0x80]).unwrap();
|
||||
fx.git(&["add", "image.png"]);
|
||||
let repo = fx.repo();
|
||||
assert_eq!(repo.file_bytes_at_bounded(&path, "HEAD", 3).unwrap().unwrap(), [0xff, 0x00, 0xfe]);
|
||||
assert_eq!(repo.file_bytes_at_bounded(&path, ":0", 1).unwrap().unwrap(), [0x80]);
|
||||
assert_eq!(repo.file_bytes_at_bounded(&path, "HEAD", 2).unwrap_err().kind, ErrorKind::InvalidInput);
|
||||
assert_eq!(repo.file_bytes_at_bounded(&fx.path("absent.png"), "HEAD", 0).unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_at_in_a_blobless_clone() {
|
||||
let fx = Fixture::new();
|
||||
|
||||
@@ -24,8 +24,8 @@ pub use archive::{
|
||||
read_archive_entry, split_archive_path,
|
||||
};
|
||||
pub use bytes::{
|
||||
ByteRange, FileProbe, MAX_RANGE_LEN, base64, content_path_allowed, image_mime, on_local_drive, probe,
|
||||
read_data_url, read_range, same_share,
|
||||
ByteRange, FileProbe, MAX_IMAGE_SIZE, MAX_RANGE_LEN, base64, content_path_allowed, image_mime, on_local_drive,
|
||||
probe, read_data_url, read_range, same_share,
|
||||
};
|
||||
pub use compare::{
|
||||
DirectoryCompareEntry, DirectoryCompareMode, DirectoryCompareProgress, DirectoryCompareStatus, DirectorySyncAction,
|
||||
|
||||
@@ -25,5 +25,8 @@ uuid.workspace = true
|
||||
zip.workspace = true
|
||||
encoding_rs.workspace = true
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
winreg = "0.56"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -260,6 +260,13 @@ impl EditorConfig {
|
||||
|
||||
/// Effective properties for `file` (absolute); `None` when no section applies.
|
||||
pub fn resolve(&self, file: &Path) -> Option<EditorConfigProps> {
|
||||
let props = props_from(&self.resolve_pairs(file)?);
|
||||
(!props.is_empty()).then_some(props)
|
||||
}
|
||||
|
||||
/// Every `key = value` that applies to `file` (keys lower-cased), domain-specific ones
|
||||
/// (`quote_type`, `ij_*`) included; `None` when no section applies.
|
||||
pub fn resolve_pairs(&self, file: &Path) -> Option<HashMap<String, String>> {
|
||||
let mut chain: Vec<(PathBuf, Arc<ParsedFile>)> = Vec::new();
|
||||
for dir in file.ancestors().skip(1) {
|
||||
if let Some(parsed) = self.load(&dir.join(FILE_NAME)) {
|
||||
@@ -286,11 +293,7 @@ impl EditorConfig {
|
||||
}
|
||||
}
|
||||
}
|
||||
if !matched {
|
||||
return None;
|
||||
}
|
||||
let props = props_from(&map);
|
||||
(!props.is_empty()).then_some(props)
|
||||
matched.then_some(map)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ pub mod roots;
|
||||
pub mod settings;
|
||||
pub mod text_refs;
|
||||
pub mod unity;
|
||||
pub mod unreal;
|
||||
pub mod window_groups;
|
||||
pub mod workspace;
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
//! Unreal Engine project identity, read from the `.uproject` at the root.
|
||||
//!
|
||||
//! Only the root and the engine tree are looked at: everything else in a UE project is
|
||||
//! content, generated output, or engine code, and must never be walked.
|
||||
|
||||
pub mod engine;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Generated directory beside the project root; excluded from the index, the search and the tree.
|
||||
pub const GENERATED_DIRS: &[&str] = &["Binaries", "Intermediate", "Saved", "DerivedDataCache"];
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UnrealProjectInfo {
|
||||
/// The engine the project builds against. `None` means none could be located, which is the
|
||||
/// only reason such a project offers no run configuration at all.
|
||||
pub engine: Option<UnrealEngine>,
|
||||
}
|
||||
|
||||
/// A located engine, shown so a project without run configurations says why.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UnrealEngine {
|
||||
/// `5.8` for a launcher install, or the registry key a source build registered under.
|
||||
pub id: String,
|
||||
/// Absolute engine root.
|
||||
pub root: String,
|
||||
}
|
||||
|
||||
/// The `.uproject` directly inside `root`, picked by name order when a folder has several.
|
||||
pub fn project_file(root: &Path) -> Option<PathBuf> {
|
||||
let mut found: Vec<PathBuf> = std::fs::read_dir(root)
|
||||
.ok()?
|
||||
.flatten()
|
||||
.filter(|e| e.file_type().is_ok_and(|t| t.is_file()))
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("uproject")))
|
||||
.collect();
|
||||
found.sort();
|
||||
found.into_iter().next()
|
||||
}
|
||||
|
||||
pub fn is_project(root: &Path) -> bool {
|
||||
project_file(root).is_some()
|
||||
}
|
||||
|
||||
pub fn detect(root: &Path) -> Option<UnrealProjectInfo> {
|
||||
let file = project_file(root)?;
|
||||
let association = std::fs::read_to_string(&file)
|
||||
.ok()
|
||||
.and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
|
||||
.and_then(|json| json.get("EngineAssociation")?.as_str().map(|v| v.trim().to_owned()))
|
||||
.filter(|v| !v.is_empty());
|
||||
let engine = engine::locate(association.as_deref())
|
||||
.map(|found| UnrealEngine { id: found.id, root: found.root.to_string_lossy().into_owned() });
|
||||
Some(UnrealProjectInfo { engine })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn write(path: &Path, text: &str) {
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_directory_holding_a_uproject_is_a_project() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
write(&root.join("Arts.uproject"), r#"{"FileVersion":3,"EngineAssociation":"5.8","Plugins":[]}"#);
|
||||
std::fs::create_dir_all(root.join("Content")).unwrap();
|
||||
assert!(is_project(root));
|
||||
assert!(detect(root).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_directory_without_a_uproject_is_not_a_project() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
write(&temp.path().join("Source/Game.Target.cs"), "");
|
||||
assert!(!is_project(temp.path()));
|
||||
assert!(detect(temp.path()).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
//! Locating an installed Unreal Engine.
|
||||
//!
|
||||
//! A launcher install registers its directory per version under `HKLM` and a source build under
|
||||
//! `HKCU`, keyed by whatever the `.uproject`'s `EngineAssociation` names.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// A registered engine, keyed by whatever the machine calls it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct EngineInstall {
|
||||
/// `5.8` for a launcher install, a GUID-like key for a source build.
|
||||
pub id: String,
|
||||
pub root: PathBuf,
|
||||
}
|
||||
|
||||
impl EngineInstall {
|
||||
/// The editor executable, which runs every start-up mode.
|
||||
pub fn editor(&self) -> PathBuf {
|
||||
self.root.join("Engine").join("Binaries").join("Win64").join("UnrealEditor.exe")
|
||||
}
|
||||
}
|
||||
|
||||
/// The engine `association` names, following Unreal's own lookup: the association is the key a
|
||||
/// registered directory is stored under, so an unknown or empty one locates nothing.
|
||||
pub fn locate(association: Option<&str>) -> Option<EngineInstall> {
|
||||
pick(installed(), association)
|
||||
}
|
||||
|
||||
fn pick(installs: Vec<EngineInstall>, association: Option<&str>) -> Option<EngineInstall> {
|
||||
let id = association?;
|
||||
// A registered directory that is gone is a leftover from an uninstalled engine.
|
||||
installs.into_iter().find(|i| i.id.eq_ignore_ascii_case(id) && i.root.is_dir())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn installed() -> Vec<EngineInstall> {
|
||||
use winreg::RegKey;
|
||||
use winreg::enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE};
|
||||
|
||||
let mut out = Vec::new();
|
||||
if let Ok(key) = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey(r"SOFTWARE\EpicGames\Unreal Engine") {
|
||||
for id in key.enum_keys().flatten() {
|
||||
let Ok(sub) = key.open_subkey(&id) else { continue };
|
||||
let Ok(dir) = sub.get_value::<String, _>("InstalledDirectory") else { continue };
|
||||
if !dir.trim().is_empty() {
|
||||
out.push(EngineInstall { id, root: PathBuf::from(dir) });
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Ok(key) = RegKey::predef(HKEY_CURRENT_USER).open_subkey(r"SOFTWARE\Epic Games\Unreal Engine\Builds") {
|
||||
for (id, _) in key.enum_values().flatten() {
|
||||
let Ok(dir) = key.get_value::<String, _>(&id) else { continue };
|
||||
if !dir.trim().is_empty() {
|
||||
out.push(EngineInstall { id, root: PathBuf::from(dir) });
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn installed() -> Vec<EngineInstall> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A fake install whose directory exists, so `pick` treats it as usable.
|
||||
fn install(dir: &std::path::Path, id: &str) -> EngineInstall {
|
||||
let root = dir.join(format!("UE_{id}"));
|
||||
std::fs::create_dir_all(root.join("Engine/Binaries/Win64")).unwrap();
|
||||
EngineInstall { id: id.to_owned(), root }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_association_picks_that_install_and_nothing_else() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let installs = vec![install(temp.path(), "5.8"), install(temp.path(), "5.3")];
|
||||
assert_eq!(pick(installs.clone(), Some("5.3")).unwrap().id, "5.3");
|
||||
assert_eq!(pick(installs, Some("4.27")), None);
|
||||
assert_eq!(pick(Vec::new(), None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_registered_engine_that_was_deleted_is_not_picked() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let ghost = EngineInstall { id: "5.8".to_owned(), root: temp.path().join("gone") };
|
||||
assert_eq!(pick(vec![ghost], Some("5.8")), None);
|
||||
}
|
||||
}
|
||||
@@ -130,6 +130,8 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
|
||||
- **Built-in**: for each built-in agent, whether its executable was found on `PATH`, a field to point at a **Custom executable**, **Environment variables** for the agent process (written as `NAME=value; OTHER=value`; the values are kept in the OS credential store) and how to sign in. Changes apply to new sessions. When the agent is a global npm install (such as Claude Code, Codex or Gemini CLI), **Check for updates** compares it with npm's latest stable release and **Update to…** updates that installation.
|
||||
- **ACP Registry**: agents published in the [ACP Registry](https://agentclientprotocol.com). Search, **Install**, **Update** and **Remove**. Installed agents are kept in OpenIDEA's data directory; downloads are checked against the registry's SHA-256 when it provides one.
|
||||
|
||||
For a built-in ACP agent launched directly, such as OMP, **Launch › Additional arguments** appends arguments to its existing launch command. Separate arguments with spaces and quote values that contain spaces. **Apply** saves the arguments for the next process launch; the command preview shows the saved result. **Reset additional arguments** clears just this field, leaving the executable, environment and any hand-written `args` in the agent file alone.
|
||||
|
||||
**Settings › Agents › Chat** chooses what the task header shows: **Context window usage**, **Time spent on the task**, **Usage limits** (when the agent reports them, such as Claude Code) and **Session cost**.
|
||||
|
||||
### External MCP servers
|
||||
|
||||
@@ -20,12 +20,19 @@ Open it from **Tools › Database** or **View › Tool Windows › Database**. T
|
||||
| ClickHouse | ClickHouse (over HTTP) |
|
||||
| Snowflake | Snowflake (over HTTPS, see below) |
|
||||
| SQLite | SQLite |
|
||||
| DuckDB | DuckDB (official JDBC driver) |
|
||||
|
||||
Presets set the default port and, where needed, SSL (for example Redshift, Neon and Supabase require SSL).
|
||||
|
||||
## DuckDB
|
||||
|
||||
Choose **New › Data Source › DuckDB**. In **Manage Drivers…**, add the [official DuckDB JDBC JAR](https://duckdb.org/docs/stable/clients/java) and save the profile. OpenIDEA fills in the driver class and URL template. A Java 17 or newer runtime is required.
|
||||
|
||||
Choose **File** to open an existing database or create a new file, **In memory** for a temporary database that lasts until disconnect, or **JDBC URL** to enter a DuckDB URL directly. To inspect an existing file without changing it, enable **Read-only** in **Options**. The official driver applies this setting when it opens the file.
|
||||
|
||||
## JDBC drivers
|
||||
|
||||
In a named data source's **General** tab, **Driver** defaults to **Built-in**. Use **Manage Drivers…** to view or add JDBC profiles for that data source type. Select the profile from **Driver** to use JDBC while keeping the source type and icon. **Go to Driver** opens the selected profile and its JAR list. Choose **New › Data Source › Custom JDBC** for databases without a preset, or open its **Manage Drivers…** to see all profiles and change their associated types.
|
||||
For presets with a built-in driver, **Driver** defaults to **Built-in** in the **General** tab. Use **Manage Drivers…** to view or add JDBC profiles for that data source type. Select the profile from **Driver** to use JDBC while keeping the source type and icon. **Go to Driver** opens the selected profile and its JAR list. Choose **New › Data Source › Custom JDBC** for databases without a preset, or open its **Manage Drivers…** to see all profiles and change their associated types.
|
||||
|
||||
Add a named profile with the vendor's driver JAR, any dependency JARs, the fully qualified driver class, and an optional JDBC URL template. OpenIDEA reads the driver classes declared in the selected JARs. You can choose a different class or enter its full name manually. Use `{host}`, `{port}`, `{database}` or `{file}` in a template to get matching connection fields, or edit the JDBC URL directly. Only import drivers you trust. OpenIDEA loads their code in a separate process using an installed Java 17 or newer runtime.
|
||||
|
||||
@@ -42,7 +49,7 @@ Profiles are reused across projects. If a project file changes a connection's UR
|
||||
Click **+** in the Database tool window (or press `⌘N` / `Alt+Insert` there) and choose:
|
||||
|
||||
- **Data Source ›** a preset from the list above.
|
||||
- **Data Source from File…** to open a SQLite file.
|
||||
- **Data Source from File…** to open a DuckDB (`.duckdb`) or SQLite file.
|
||||
- **Data Source from URL…** to paste a URL such as `postgresql://user@localhost:5432/db`. Schemes like `mysql://`, `mariadb://`, `sqlserver://`, `oracle://`, `clickhouse://`, `sqlite:path` and `jdbc:` URLs are accepted.
|
||||
- **Import from Clipboard** to read a connection URL from the clipboard.
|
||||
|
||||
|
||||
@@ -55,6 +55,8 @@ The editor follows IntelliJ IDEA's behaviour and default keymap. Shortcuts below
|
||||
|
||||
**Move Caret Forward a Paragraph** / **Backward a Paragraph** jump each caret over a run of non-blank lines to the blank line after or before it (a line of only spaces or tabs counts as blank), or to the end or start of the file; their **with Selection** variants select up to there. They have no default shortcut.
|
||||
|
||||
**Move Caret to Next Word** / **Previous Word in Different "CamelHumps" Mode** (and their **with Selection** variants), **Delete to Word Start** and **Delete to Word End in Different "CamelHumps" Mode** move or delete by word the other way from **Settings › Editor › General › Smart Keys › Use "CamelHumps" words**: by hump (`parse|HTML|Document`) while it is off, by whole word while it is on. They have no default shortcut.
|
||||
|
||||
**Edit › Sort Lines** and **Edit › Reverse Lines** reorder the selected lines (the whole file without a selection); they have no default shortcut. Sort Lines orders by character code, so uppercase letters come before lowercase ones.
|
||||
|
||||
**Cut up to Line End** cuts from each caret to the end of its line, together with the line break when only whitespace is left (or the caret is already at the line end), so pressing it again on the same caret cuts the next line too; those repeated cuts collect into one clipboard entry. **Delete to Line Start** and **Delete to Line End** delete the same way without copying (to the line start, or the line break before the caret at the line start), or delete the selection. They have no default shortcut except in the Eclipse keymaps (`⇧⌘⌦` / `Ctrl+Shift+Delete` for Delete to Line End).
|
||||
@@ -108,7 +110,7 @@ All folding commands are also in **Code › Folding**. Fold regions come from th
|
||||
| **Auto-Indent Lines** | `⌃⌥I` | `Ctrl+Alt+I` |
|
||||
| **Optimize Imports** | `⌃⌥O` | `Ctrl+Alt+O` |
|
||||
|
||||
**Reformat Code** formats the selection, or the whole file when nothing is selected, as one undo step. The formatting comes from the file's language server or from the formatter the language is configured with (for example Ruff for Python, Prettier, oxfmt or Biome for web languages; find their commands as **Reformat with …** in Find Action). **Reformat File…** also lets you choose the scope and optimize imports.
|
||||
**Reformat Code** formats the selection, or the whole file when nothing is selected, as one undo step. The formatting comes from the file's language server or from the formatter the language is configured with (for example Ruff for Python, Prettier, oxfmt or Biome for web languages, dprint in dprint projects; find their commands as **Reformat with …** in Find Action). **Reformat File…** also lets you choose the scope and optimize imports.
|
||||
|
||||
Indentation and other style options are under **Settings › Editor › Code Style**, with a page per language. `.editorconfig` files in the project are read too.
|
||||
|
||||
@@ -158,6 +160,7 @@ With tabs placed left or right, the tab column is as wide as its longest name, u
|
||||
- **View › Active Editor › Soft-Wrap** wraps long lines in the current editor. To wrap some file types by default, use **Settings › Editor › General**, section **Soft Wraps**.
|
||||
- **View › Reset Font Size** undoes font zoom in the active editor or focused surface (**View › Reset Font Size in All Editors** resets every open editor). Changing the font size with `⌘` / `Ctrl` + mouse wheel (scoped to **Active editor** by default, or **All editors**) can be turned on in **Settings › Editor › General**, section **Mouse Control**.
|
||||
- **View › Appearance › Enter Distraction Free Mode** hides tool windows, tabs, the status bar and the gutter and centres the text. Run the same command again to leave.
|
||||
- **View › Appearance › Enter Zen Mode** turns on Distraction Free Mode and full screen together; **Exit Zen Mode** turns both off.
|
||||
- **Show Line Numbers**, **Show Indent Guides**, **Show Sticky Lines** and **Show Whitespaces** turn these on or off in every editor. Run them from Find Action, or right-click the gutter and open **Appearance**.
|
||||
- Line numbers, whitespace, indent guides, caret style and the intention bulb are in **Settings › Editor › General › Appearance**. Breadcrumbs and sticky lines (the enclosing declarations pinned at the top while you scroll) have their own pages under **Settings › Editor › General**.
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ When a project opens, OpenIDEA scans its build files (also in nested projects of
|
||||
| `package.json` | One per `scripts` entry, run with the package manager of the lock file (npm, pnpm, yarn or bun). `test`, `test:*`, `jest` and `vitest` scripts are marked as tests. |
|
||||
| `deno.json` / `deno.jsonc` | Deno tasks |
|
||||
| `playwright.config.*` | Scripts that run `playwright test` are tests; without one, `npx playwright test` |
|
||||
| `cypress.config.*` / `cypress` dependency | Scripts that run `cypress run` are tests; without one, `npx cypress run` (a Cypress configuration) |
|
||||
| `Cargo.toml` | `cargo run` for each binary, `cargo test`, `cargo build`; workspace members are included |
|
||||
| `build.gradle(.kts)` / `pom.xml` | Gradle and Maven run configurations |
|
||||
| `go.mod` / `go.work` | Go programs and tests |
|
||||
|
||||
@@ -41,6 +41,7 @@ Classes and symbols come from the IDE's own index (available as soon as a file i
|
||||
- **Recent Files** lists recently opened files and the tool windows; type to filter.
|
||||
- **Recent Locations** shows the places you visited or edited with a few lines of code around each. Press the shortcut again (or check **Show changed only**) to see only edited places.
|
||||
- **Switcher** works like an application switcher: hold `⌃` / `Ctrl`, press `⇥` / `Tab` to move through open files and tool windows, and release to switch.
|
||||
- **Back** / **Forward** walks your navigation history across editor locations, split panes, and non-file editor tabs (such as diffs, agent chats, and terminal tabs), skipping entries for deleted tasks or closed terminal sessions.
|
||||
- **Select In…** reveals the current file in the Project view or another tool window.
|
||||
|
||||
## Find and replace in a file
|
||||
|
||||
Loaded 100 of 367 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача