дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 01:01:17 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
14884e4214 |
No files matched your search
Створено
+148
-200
@@ -474,7 +474,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "457d7ed3f888dfd2c7af56d4975cade43c622f74bdcddfed6d4352f57acc6310"
|
||||
dependencies = [
|
||||
"futures-util",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"portable-atomic",
|
||||
"tokio",
|
||||
]
|
||||
@@ -1655,9 +1655,9 @@ dependencies = [
|
||||
"cfg-if",
|
||||
"crossbeam-utils",
|
||||
"hashbrown 0.14.5",
|
||||
"lock_api 0.4.14",
|
||||
"lock_api",
|
||||
"once_cell",
|
||||
"parking_lot_core 0.9.12",
|
||||
"parking_lot_core",
|
||||
"serde",
|
||||
]
|
||||
|
||||
@@ -2154,7 +2154,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2210,16 +2210,6 @@ 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"
|
||||
@@ -2463,8 +2453,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"lock_api 0.4.14",
|
||||
"parking_lot 0.12.5",
|
||||
"lock_api",
|
||||
"parking_lot",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2744,9 +2734,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix"
|
||||
version = "0.90.0"
|
||||
version = "0.89.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b92b20c1560511a9014b16e29db2f3c6f0580d4fe289b70f41131277b065a3b0"
|
||||
checksum = "2156d2e07fc3afa7632a82bf3cb0db91f995645a2852f642105c9ac9b52e1cb2"
|
||||
dependencies = [
|
||||
"gix-actor",
|
||||
"gix-attributes",
|
||||
@@ -2798,9 +2788,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-actor"
|
||||
version = "0.44.1"
|
||||
version = "0.44.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78243d3371019288a40a75ba1a58de2815c32591fc87b9f7cb01918bce364ca8"
|
||||
checksum = "2127da41042965ed205568a52443465806944f71c8acd73f48ec94b8cd8e798e"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-date",
|
||||
@@ -2809,9 +2799,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-attributes"
|
||||
version = "0.37.1"
|
||||
version = "0.37.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6b9947d93a94d41ddde66ac655674269121cbebaf6cdee30d8d0e7dbe85edb4c"
|
||||
checksum = "0feca0b8919aba9f123b75de54062dd61eb37d2a2130f34be520da6ed8b8ef72"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -2826,27 +2816,27 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-bitmap"
|
||||
version = "0.6.2"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9543567ee22142c81fdf75b2811160bec749a5b9f48665e4763f88b1789b8612"
|
||||
checksum = "408cb9e482e0dcc5fc481850556348dda6981ec054a4a8e81a8e1bbf84f85eef"
|
||||
dependencies = [
|
||||
"gix-error",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-chunk"
|
||||
version = "0.10.2"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "60cd5f0e47ffae98bad241ccbc031693765004fb4c2a419f7fda2963232af1e3"
|
||||
checksum = "626335faf30ed235744642c2309aa370683b8bb2757f1c22a807e274dff60074"
|
||||
dependencies = [
|
||||
"gix-error",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-command"
|
||||
version = "0.12.2"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2986e78ebad43510ccd7dd18bd9f22e9afd52f2de791e2979b9c715bacb6f0a8"
|
||||
checksum = "ac560c05e19455016a4a94b33a77debe59aaed8783da32a73d31c9975947152e"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -2857,9 +2847,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-commitgraph"
|
||||
version = "0.42.0"
|
||||
version = "0.41.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "60b53b700d2a506cf98075099df1fcc0558265cbb47fd86bc6d03c231e4bd72a"
|
||||
checksum = "dfede9936d4b789867c09722576aea4ceb0e3aacf962eef035ebab0686b41a80"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-chunk",
|
||||
@@ -2871,9 +2861,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-config"
|
||||
version = "0.62.2"
|
||||
version = "0.62.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3e11ccf82e9630c4e7befbae07cbe90e79de61dc73a34448c2dec70a13da9ebf"
|
||||
checksum = "65a9c000fa9a9154f22ffc8f8d74426e9300d759c2029e8701e2ba39d5d464ea"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-config-value",
|
||||
@@ -2891,9 +2881,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-config-value"
|
||||
version = "0.21.2"
|
||||
version = "0.21.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d7666081ef0ecc5e1dc54bc6ce16dac9d7b9490780f6c130393ef9e50c909d4a"
|
||||
checksum = "ab206c2fccfd35e0de7fb1b424997cfd42912062c66dae024e08a06e22d46674"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bstr",
|
||||
@@ -2905,9 +2895,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-date"
|
||||
version = "0.18.1"
|
||||
version = "0.18.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4c538190012dbb536df54734ec38cc1109270c73f2f76585c011dd5b0c9f087c"
|
||||
checksum = "0f7eeeecc599082f32b5ea6a8c4c734e38be9730e2c09e3fe2851bb4692393e9"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -2917,9 +2907,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-diff"
|
||||
version = "0.70.0"
|
||||
version = "0.69.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2c794988335792f85c3ca79c385c950b3a921a71ba3df361cb1f9e5b6bd4a6e4"
|
||||
checksum = "aa640963fdcbc6b4718e48593c3917f5ae764b59fb5a96313cb5a757246d041d"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-attributes",
|
||||
@@ -2941,9 +2931,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-dir"
|
||||
version = "0.32.0"
|
||||
version = "0.31.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af939f21c65d4f15457c72d08c874d454893185c51a3596e3c2bd3d9c567618d"
|
||||
checksum = "84e916ef77f19161b738ae9913662bc36fed1e48256a943f40277b3a585841da"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-discover",
|
||||
@@ -2961,9 +2951,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-discover"
|
||||
version = "0.57.1"
|
||||
version = "0.57.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4a0875f4e5408713fcf92265973cc38bf9dc5a93384ce218beba0572b7785a03"
|
||||
checksum = "a7d0f8fd2c7e4b458eb3081362d49b54bd0131d23ecd49be802085a11f0d3cee"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"dunce",
|
||||
@@ -2976,18 +2966,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-error"
|
||||
version = "0.5.3"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "50ad6c42fa50280f382026ff838a8afa7ab2ad83e92349cab4392972baae69cd"
|
||||
checksum = "bb3308a948a01b94ef13d9ee7a9b28c1303d8d9a9dc33b401ff40c2184d9e04a"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-filter"
|
||||
version = "0.36.1"
|
||||
version = "0.36.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8df8d50fda4684c6ec366f75e4082ab6fc3d437d3deec30ff88462710b68d17"
|
||||
checksum = "9d8d932ee4043f7d77d15ee58d2be2bc95accea5dd1d77fd145de1b7c504551b"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"encoding_rs",
|
||||
@@ -3006,9 +2996,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-fs"
|
||||
version = "0.24.1"
|
||||
version = "0.24.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "808f23d897ddfe847d9b7206bda947901885be623bdf96b226a2dccf87f018c7"
|
||||
checksum = "44a05d043e670c055cd8b53d078562dc0bc1e322bff6b0376b407d37cf72dcc5"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -3021,9 +3011,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-glob"
|
||||
version = "0.29.1"
|
||||
version = "0.29.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7a12789fa68a150293ad8834d267b31044240532b5ccf2734d228fe985cba2be"
|
||||
checksum = "7b0d03ab50fa841621031960679caf7fe94940968d9a0736d12a580f2c03e525"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bstr",
|
||||
@@ -3035,11 +3025,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-hash"
|
||||
version = "0.28.1"
|
||||
version = "0.28.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4802ffb87e051795822bfdaa8ab9075b23e316684f7054e6ce4a246b2b76f4e"
|
||||
checksum = "40ca156064e378d8c657084365846cedb8dc498c6ea4500965a64d74f12af2be"
|
||||
dependencies = [
|
||||
"faster-hex 0.10.1",
|
||||
"faster-hex",
|
||||
"gix-error",
|
||||
"gix-utils",
|
||||
"sha1dc",
|
||||
@@ -3054,7 +3044,7 @@ checksum = "916cb6b2ec42ffaca624e7867bb382a4673015cb4ffcd7330b48085d02e4c615"
|
||||
dependencies = [
|
||||
"gix-hash",
|
||||
"hashbrown 0.17.1",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3072,9 +3062,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-imara-diff"
|
||||
version = "0.3.4"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23347fa4a29a440eebf045d0bc21da465c0dc70434c2a4bcdfcc658f16c9e27e"
|
||||
checksum = "1c48eccd894bd15555b0346470e63491ded94aefe76b3fcb1052084b5a393238"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"hashbrown 0.17.1",
|
||||
@@ -3082,9 +3072,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-index"
|
||||
version = "0.58.0"
|
||||
version = "0.57.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06bfc736774a623307eda890c918d308ef5acd37402bde2d6768fccb1f6ecb5d"
|
||||
checksum = "fc6db8b20a3dba8836daf90b24199600bb27dcfce3a127ec24ae61e15a7c5b68"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bstr",
|
||||
@@ -3134,9 +3124,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-note"
|
||||
version = "0.3.1"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8473688f2262f4364f521b39ce2a5dbe94494f327fc19c945318d7aff580952e"
|
||||
checksum = "bd364f8bdceaed9e7f3ae40f324b16e39f20e9c7e6a6a058f7c6ec66c3e6205c"
|
||||
dependencies = [
|
||||
"gix-error",
|
||||
"gix-hash",
|
||||
@@ -3145,9 +3135,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-object"
|
||||
version = "0.66.1"
|
||||
version = "0.66.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "beaf9086dd00b9d2a177ca3ae83210ce926cee7c0faa112e053851221cd8f94d"
|
||||
checksum = "f0e38f50177e211642af154f9a7f710b7a3a637e635f9b6adb9d51973b0f9209"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-actor",
|
||||
@@ -3166,9 +3156,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-odb"
|
||||
version = "0.87.0"
|
||||
version = "0.86.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "941b5b99fed282a5b05b54ea486c36c76b558afe151e6804c3acdd5c8f3c3459"
|
||||
checksum = "ca444f33f2140876ed6b5313c2b550b4af699008193c96f3bff5023afa9ef4ea"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"crc32fast",
|
||||
@@ -3185,15 +3175,15 @@ dependencies = [
|
||||
"gix-utils",
|
||||
"gix-zlib",
|
||||
"memmap2",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-pack"
|
||||
version = "0.77.0"
|
||||
version = "0.76.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e2ef461798b1e6cb652192c69dfc9658dfc1bab457ef812dd1ab85d75104cbef"
|
||||
checksum = "bc5024cc503cd29461a705ae90b9eae772fa8f0e6fafc1c48513877dc374de05"
|
||||
dependencies = [
|
||||
"clru",
|
||||
"crc32fast",
|
||||
@@ -3214,46 +3204,45 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-packetline"
|
||||
version = "0.24.2"
|
||||
version = "0.24.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e198121152a397ad1007e3334931b04b393fa17f6af34f17b33e376b15bf5ea"
|
||||
checksum = "830e51b227f6a925fe9308858ac91170dd00fa2880f5480fc81e8a4594fe2c35"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"faster-hex 2.0.0",
|
||||
"faster-hex",
|
||||
"gix-error",
|
||||
"gix-trace",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-parallel"
|
||||
version = "0.50.2"
|
||||
version = "0.50.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3a5c86eeec0194a3444611b4762ba05cc5029408a617348b4f6a74a34c222cd"
|
||||
checksum = "e994cf1eec247ba4be7f9e7c0d58cc73f83eecb5fcb9feb595df5ba3d2078546"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
"gix-trace",
|
||||
"once_cell",
|
||||
"parking_lot 0.13.0",
|
||||
"parking_lot",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-path"
|
||||
version = "0.14.2"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "615e3ff75800c67022ec8065b67e0846420a88c5f484e6c4fd81c78472e4c77a"
|
||||
checksum = "a6d563d4d0c975ed0df4e853f9ec962a2ba46633b1d324e1a5582541fcae0c6b"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
"gix-trace",
|
||||
"gix-validate",
|
||||
"winreg 0.56.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-pathspec"
|
||||
version = "0.22.1"
|
||||
version = "0.22.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "490aa03a11e0cbb998a0a593b75e27ea2e30df4ebd8f84f60e0641b9b72270e8"
|
||||
checksum = "3e3b7f03e516a8435d18c3cc2d446925940c81d409145ac21edb5a576f0625e4"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bstr",
|
||||
@@ -3266,9 +3255,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-protocol"
|
||||
version = "0.68.0"
|
||||
version = "0.67.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "83677ebae6a1a09dc07f2435b5ebe68470dc51afb74052135e98fd7c11f85ba9"
|
||||
checksum = "832b5dc46a3c0a6f6fa8f8e571c11074add4b545c6789799ae6d6c36ae1a294e"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-date",
|
||||
@@ -3284,9 +3273,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-quote"
|
||||
version = "0.10.2"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5069a7ec021bb47abe9f12dcc075d292e8cf4a9dff5fffd38595b39c6b419aaa"
|
||||
checksum = "c7f92bc1b13c09e88388578e8aa1e987ec35f28fca158c13b1baa7ab1a85b124"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -3295,9 +3284,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-ref"
|
||||
version = "0.69.1"
|
||||
version = "0.69.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "68686e4697b9cd15d1b152ef51df870513210ed22938eacc13b3672b76035f13"
|
||||
checksum = "073bc0928e1f747823b1eaed94918119dacef4c616532bc3d17e5b7457863471"
|
||||
dependencies = [
|
||||
"gix-actor",
|
||||
"gix-error",
|
||||
@@ -3315,9 +3304,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-refspec"
|
||||
version = "0.47.1"
|
||||
version = "0.47.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2569309da6fdc230973cf5b846508154c0e813fda60f2b2da768cc5655ed312c"
|
||||
checksum = "ccc7010dae0df2900aa77cc67f8aca042cd80e35938ccc179010d863b1d42a0c"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -3328,9 +3317,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-revision"
|
||||
version = "0.52.0"
|
||||
version = "0.51.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "241465fc73530f41d0a1c18320c5e291365b7c2c2a3dfd07afe2a5d6265085c8"
|
||||
checksum = "63210c1943b67fa700806c3c3486fc16a92b3ea871f5cf092340b8eec10a0ca1"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bstr",
|
||||
@@ -3347,9 +3336,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-revwalk"
|
||||
version = "0.38.0"
|
||||
version = "0.37.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b46edeacd25d9d3131941ae6bc91002bf7ba10e130393b7e9bc23d528625447"
|
||||
checksum = "800479fbbf1e7f94f663e07943a91add5499343e7aac611a81e6a0460fd44af6"
|
||||
dependencies = [
|
||||
"gix-commitgraph",
|
||||
"gix-date",
|
||||
@@ -3362,9 +3351,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-sec"
|
||||
version = "0.16.1"
|
||||
version = "0.16.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9598d1f35baec7038c2d278bfcc18f1d8951f41dcc3f51ab6175661dfe5a6137"
|
||||
checksum = "5640f642a1b471616d48230b1def7ca743cb30903441ff84800cafbab3c0fddf"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"gix-path",
|
||||
@@ -3374,9 +3363,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-shallow"
|
||||
version = "0.15.1"
|
||||
version = "0.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d805949578724b5164c90ec6d19567832ccaa5ba8a3fe26f7befc52007e2407"
|
||||
checksum = "94bc0720a3d6b10f18e3ac382a7780bcfc4c6bee94a8b5857b8e4ec94c50d754"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -3387,9 +3376,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-status"
|
||||
version = "0.37.0"
|
||||
version = "0.36.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "31b00c359278210e3cc0803d057db1d61c5d6694c21ed9ad0b8f8f862157247a"
|
||||
checksum = "42d3174a9f3fb991cf25a7a609ab6c50f19baa7d5f8ce05a48c202f7db4ce3ba"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"filetime",
|
||||
@@ -3409,13 +3398,14 @@ dependencies = [
|
||||
"gix-worktree",
|
||||
"hashbrown 0.16.1",
|
||||
"portable-atomic",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-submodule"
|
||||
version = "0.36.1"
|
||||
version = "0.36.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d558a1307b6f3de2a92bd91d0570c53952d4f2329e6860813007508c8ed413dc"
|
||||
checksum = "6d945257bd0d624ca844a5a36c79d748df080f355b0ac92d68793875aa529a3f"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-config",
|
||||
@@ -3435,22 +3425,22 @@ dependencies = [
|
||||
"dashmap",
|
||||
"gix-fs",
|
||||
"libc",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"tempfile",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-trace"
|
||||
version = "0.3.2"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c96f84d731a96780e6a7ad5ee70b4ecc398499946b62617945fbaeb6ab878f8"
|
||||
checksum = "133f2de116104d637541831b6acb157898556d5eeec363ab2eb1c583adc6bb56"
|
||||
|
||||
[[package]]
|
||||
name = "gix-transport"
|
||||
version = "0.62.0"
|
||||
version = "0.61.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cdcd9cdfd8745aa38f926a4a380c13d76b200d7338de57fc492982cd5a6652ba"
|
||||
checksum = "2e43d6b0097ea9f2f266d5d6c43b8f615ed3da7c686ec8771cd17c1cb33cb0de"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-command",
|
||||
@@ -3466,9 +3456,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-traverse"
|
||||
version = "0.64.0"
|
||||
version = "0.63.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "00171e00e91508300d0361072c4eb110ec0f1322d8b95ed36887231702a38ebc"
|
||||
checksum = "a668a6e7f7688e5a43eaf161f1471ffc559de1a5fd8471e861c64d59d1699e1e"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"gix-commitgraph",
|
||||
@@ -3483,9 +3473,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-url"
|
||||
version = "0.40.1"
|
||||
version = "0.40.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "def12e1016b872f1094442882f627905c59bd73480435291a4958cf373a8f28d"
|
||||
checksum = "04317dea7a5dd5253bbcab060c230f3de6a57d17cc9600c6cd7030bf4795b414"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -3496,9 +3486,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-utils"
|
||||
version = "0.5.3"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b5e6d46894c7a4fd9c5e26d233a0fa836002ba0af9a11aef58923d317c486e10"
|
||||
checksum = "f8e770b8c34311044d1addc7b18957db0ac27183707e1140dc90e6f674a6354e"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"bytes",
|
||||
@@ -3511,9 +3501,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-validate"
|
||||
version = "0.13.2"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5d6f293fd8abd9bd9bc1e0a23541f73607e932b5a2bde2246320da38edde5726"
|
||||
checksum = "cbcd59cc52742468bc5c8a0e7123390d154f45e6cbd37461b0dcecdc681f2179"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -3521,9 +3511,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-worktree"
|
||||
version = "0.59.0"
|
||||
version = "0.58.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe92aec0a25cf073394492a6ee2aa4d27632acde91a653d34de0e4da6afb485d"
|
||||
checksum = "a285c0f6b41e504e8bb81ca3f861c4da00cb3d5ced3210a4591112f22da6d38f"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-attributes",
|
||||
@@ -3540,9 +3530,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-worktree-stream"
|
||||
version = "0.39.0"
|
||||
version = "0.38.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3fe5d65793848ffb596f6c5596fd120b132038736525628227e2388ca454f64d"
|
||||
checksum = "28d2789610e8179d4e0e8e51170a52a66483c103a8ad3c7db4d075b571856cb6"
|
||||
dependencies = [
|
||||
"gix-attributes",
|
||||
"gix-error",
|
||||
@@ -3555,14 +3545,14 @@ dependencies = [
|
||||
"gix-trace",
|
||||
"gix-traverse",
|
||||
"gix-utils",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-zlib"
|
||||
version = "0.4.1"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "81a49a8b263d2a140f1c178ff93375b8d4cc7b1d3252cd87ce1ca88bce62b9b9"
|
||||
checksum = "8c2edb206bf06f3c801f4f6789c696396171558ab9b4c7f1fe3ba4d39b00b0f4"
|
||||
dependencies = [
|
||||
"gix-error",
|
||||
"zlib-rs",
|
||||
@@ -4166,7 +4156,7 @@ dependencies = [
|
||||
"ide-tools",
|
||||
"ide-vcs",
|
||||
"ide-vfs",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"rustix",
|
||||
"semver",
|
||||
"serde",
|
||||
@@ -4307,7 +4297,7 @@ dependencies = [
|
||||
"ide-language",
|
||||
"libc",
|
||||
"memchr",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"portable-pty",
|
||||
"serde",
|
||||
@@ -4339,7 +4329,7 @@ dependencies = [
|
||||
"notify",
|
||||
"open",
|
||||
"oracledb",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"reqwest",
|
||||
"rsa",
|
||||
"rustls",
|
||||
@@ -4395,7 +4385,7 @@ dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
"ed25519-dalek",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4413,7 +4403,7 @@ version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-android",
|
||||
"ide-core",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
]
|
||||
@@ -4520,7 +4510,7 @@ dependencies = [
|
||||
"ide-workspace",
|
||||
"ignore",
|
||||
"jsonschema",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"quick-xml 0.42.0",
|
||||
"regex-lite",
|
||||
"regex-syntax",
|
||||
@@ -4550,7 +4540,7 @@ dependencies = [
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"reqwest",
|
||||
"rustls",
|
||||
"rustls-platform-verifier",
|
||||
@@ -4575,7 +4565,7 @@ dependencies = [
|
||||
"ide-language",
|
||||
"ignore",
|
||||
"nucleo-matcher",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"postcard",
|
||||
"rayon",
|
||||
"redb",
|
||||
@@ -4603,7 +4593,7 @@ version = "0.1.53"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
@@ -4644,7 +4634,7 @@ dependencies = [
|
||||
"ide-extension",
|
||||
"ide-text",
|
||||
"memchr",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"regex-lite",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4709,7 +4699,7 @@ dependencies = [
|
||||
"ide-vfs",
|
||||
"ignore",
|
||||
"lsp-types",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4749,7 +4739,7 @@ dependencies = [
|
||||
"jupyter-protocol",
|
||||
"jupyter-zmq-client",
|
||||
"libc",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4769,7 +4759,7 @@ dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
"ide-extension",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4808,7 +4798,7 @@ dependencies = [
|
||||
"ide-run",
|
||||
"ide-ssh",
|
||||
"ignore",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4826,9 +4816,8 @@ dependencies = [
|
||||
"ide-build",
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
"ide-workspace",
|
||||
"libc",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"portable-pty",
|
||||
"quick-xml 0.42.0",
|
||||
"serde",
|
||||
@@ -4910,7 +4899,7 @@ name = "ide-spell"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4927,7 +4916,7 @@ dependencies = [
|
||||
"ide-core",
|
||||
"keyring",
|
||||
"keyring-core",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"russh",
|
||||
"russh-sftp",
|
||||
"rustls",
|
||||
@@ -4977,7 +4966,7 @@ version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"portable-pty",
|
||||
"serde",
|
||||
"specta",
|
||||
@@ -5009,7 +4998,7 @@ dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
"libc",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
@@ -5056,7 +5045,7 @@ dependencies = [
|
||||
"ide-core",
|
||||
"ignore",
|
||||
"notify",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"rayon",
|
||||
"rustix",
|
||||
"serde",
|
||||
@@ -5097,7 +5086,7 @@ dependencies = [
|
||||
"ide-core",
|
||||
"ide-text",
|
||||
"ide-vfs",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -5107,7 +5096,6 @@ dependencies = [
|
||||
"toml_edit 0.25.17+spec-1.1.0",
|
||||
"tracing",
|
||||
"uuid",
|
||||
"winreg 0.56.0",
|
||||
"zip",
|
||||
]
|
||||
|
||||
@@ -5251,7 +5239,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f"
|
||||
dependencies = [
|
||||
"io-lifetimes 3.0.1",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5289,7 +5277,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"
|
||||
dependencies = [
|
||||
"hermit-abi",
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5789,15 +5777,6 @@ 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"
|
||||
@@ -6769,7 +6748,7 @@ dependencies = [
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2-web-kit 0.3.2",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"reqwest",
|
||||
"security-framework",
|
||||
@@ -6959,18 +6938,8 @@ version = "0.12.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
|
||||
dependencies = [
|
||||
"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",
|
||||
"lock_api",
|
||||
"parking_lot_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6981,19 +6950,7 @@ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"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",
|
||||
"redox_syscall",
|
||||
"smallvec",
|
||||
"windows-link",
|
||||
]
|
||||
@@ -7444,7 +7401,7 @@ version = "31.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf52d87428247c5aa3760ac8e7d8b13ec7b3579b955a8c3f311668b6860acba5"
|
||||
dependencies = [
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7640,15 +7597,6 @@ 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"
|
||||
@@ -7688,7 +7636,7 @@ dependencies = [
|
||||
"ahash",
|
||||
"fluent-uri 0.3.2",
|
||||
"once_cell",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -8022,7 +7970,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8090,7 +8038,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8764,7 +8712,7 @@ dependencies = [
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2-quartz-core 0.3.2",
|
||||
"raw-window-handle",
|
||||
"redox_syscall 0.5.18",
|
||||
"redox_syscall",
|
||||
"tracing",
|
||||
"wasm-bindgen",
|
||||
"web-sys",
|
||||
@@ -8864,7 +8812,7 @@ version = "0.9.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
|
||||
dependencies = [
|
||||
"lock_api 0.4.14",
|
||||
"lock_api",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9138,7 +9086,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901"
|
||||
dependencies = [
|
||||
"new_debug_unreachable",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"phf_shared",
|
||||
"precomputed-hash",
|
||||
]
|
||||
@@ -9326,7 +9274,7 @@ dependencies = [
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2-ui-kit 0.3.2",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"raw-window-handle",
|
||||
"tao-macros",
|
||||
@@ -9834,10 +9782,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.4.3",
|
||||
"getrandom 0.3.4",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -10017,7 +9965,7 @@ dependencies = [
|
||||
"bytes",
|
||||
"libc",
|
||||
"mio",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"pin-project-lite",
|
||||
"signal-hook-registry",
|
||||
"socket2",
|
||||
@@ -11674,7 +11622,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -12472,7 +12420,7 @@ dependencies = [
|
||||
"log",
|
||||
"num-traits",
|
||||
"once_cell",
|
||||
"parking_lot 0.12.5",
|
||||
"parking_lot",
|
||||
"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.90", default-features = false }
|
||||
gix = { version = "0.89", 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"] }
|
||||
|
||||
@@ -9,7 +9,6 @@ mod modules;
|
||||
mod parse;
|
||||
mod single;
|
||||
mod structure;
|
||||
mod tsc_watch;
|
||||
mod up_to_date;
|
||||
|
||||
pub use fingerprint::{LaunchFingerprint, launch_fingerprint, menu_fingerprint};
|
||||
@@ -24,7 +23,6 @@ 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};
|
||||
@@ -814,11 +812,6 @@ 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 };
|
||||
@@ -826,11 +819,11 @@ pub fn diagnostics_from(messages: &[BuildMessage], source: &str) -> BTreeMap<Pat
|
||||
range,
|
||||
severity: m.severity,
|
||||
message: m.text.clone(),
|
||||
source: Some(source.to_owned()),
|
||||
source: Some(DIAGNOSTICS_SOURCE.to_owned()),
|
||||
code: m.code.clone(),
|
||||
unnecessary: false,
|
||||
deprecated: false,
|
||||
server: Some(source.to_owned()),
|
||||
server: Some(DIAGNOSTICS_SOURCE.to_owned()),
|
||||
});
|
||||
}
|
||||
out
|
||||
|
||||
@@ -1,450 +0,0 @@
|
||||
//! 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,15 +486,6 @@ 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).
|
||||
|
||||
@@ -1730,14 +1730,11 @@ 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, watch_problems: false }
|
||||
Self { version: "bundled".into(), tsserver_max_memory: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -46,13 +46,6 @@ 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.
|
||||
@@ -96,7 +89,6 @@ impl Capability {
|
||||
| Self::VcsWrite
|
||||
| Self::Net(_)
|
||||
| Self::NetAsk
|
||||
| Self::NetSetting { .. }
|
||||
| Self::NetHttp(_)
|
||||
| Self::Secrets
|
||||
| Self::InputEvents
|
||||
@@ -147,12 +139,6 @@ 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)")
|
||||
}
|
||||
@@ -198,19 +184,6 @@ 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\");
|
||||
@@ -300,8 +273,6 @@ 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}"),
|
||||
@@ -329,27 +300,23 @@ impl FromStr for Capability {
|
||||
if kind == "net" && arg == "ask" {
|
||||
return Ok(Self::NetAsk);
|
||||
}
|
||||
// `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() })
|
||||
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())
|
||||
} else {
|
||||
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())
|
||||
}
|
||||
Self::NetHttp(arg.to_ascii_lowercase())
|
||||
})
|
||||
.map_err(|_| format!("invalid host in {s:?}"))
|
||||
} else {
|
||||
Err(format!("invalid host in {s:?}"))
|
||||
}
|
||||
}
|
||||
"ipc" => {
|
||||
validate_ipc_name(arg, true)?;
|
||||
@@ -588,77 +555,6 @@ 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,10 +58,6 @@ 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>,
|
||||
@@ -213,7 +209,6 @@ 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 };
|
||||
}
|
||||
@@ -241,7 +236,6 @@ 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();
|
||||
@@ -275,9 +269,6 @@ 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() {
|
||||
@@ -301,21 +292,6 @@ 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) {
|
||||
@@ -417,19 +393,6 @@ 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) {
|
||||
@@ -626,58 +589,6 @@ 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,9 +26,7 @@ mod resolve;
|
||||
mod ui;
|
||||
mod when;
|
||||
|
||||
pub use capability::{
|
||||
Capability, CapabilityInfo, Risk, expand_ipc_name, host_matches, manifest_host, validate_ipc_name,
|
||||
};
|
||||
pub use capability::{Capability, CapabilityInfo, Risk, expand_ipc_name, host_matches, validate_ipc_name};
|
||||
pub use index::ContributionIndex;
|
||||
pub use manifest::{
|
||||
ActivationEvent, CATEGORIES, Capabilities, ENGINE_VERSION, EVENT_KINDS, LEGACY_API, MANIFEST_FILE, MAX_CATEGORIES,
|
||||
|
||||
@@ -372,9 +372,6 @@ 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()
|
||||
@@ -770,20 +767,6 @@ 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"] {
|
||||
|
||||
@@ -77,69 +77,6 @@ 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.
|
||||
@@ -674,26 +611,18 @@ async fn provider_edits(
|
||||
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
|
||||
{
|
||||
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;
|
||||
&& 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 {
|
||||
@@ -715,8 +644,10 @@ async fn provider_edits(
|
||||
.map_err(|e| IdeError::internal(e.to_string()));
|
||||
};
|
||||
let tool_settings = settings.languages.formatter(selected);
|
||||
if options.on_save && !runs_on_save(selected, tool_settings.run_on_save, takes_over, settings.editor.format_on_save)
|
||||
{
|
||||
// Black and dprint take over from the language server in their projects, so Format on save runs them too.
|
||||
let runs_on_save = tool_settings.run_on_save
|
||||
|| (matches!(selected, ExternalFormatter::Black | ExternalFormatter::Dprint) && settings.editor.format_on_save);
|
||||
if options.on_save && !runs_on_save {
|
||||
return Ok(None);
|
||||
}
|
||||
host.require_trust(window)?;
|
||||
@@ -883,7 +814,7 @@ pub async fn python_import_edits(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ExternalFormatter::{Biome, Black, Dprint, Oxfmt, Prettier, Ruff};
|
||||
use ExternalFormatter::{Biome, Black, Oxfmt, Prettier, Ruff};
|
||||
use ide_core::LanguageId;
|
||||
use ide_language::LanguageRegistry;
|
||||
|
||||
@@ -1251,55 +1182,6 @@ 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,8 +27,6 @@ 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};
|
||||
@@ -427,9 +425,6 @@ 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();
|
||||
@@ -659,9 +654,6 @@ 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();
|
||||
|
||||
@@ -380,7 +380,6 @@ 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"),
|
||||
|
||||
@@ -22,8 +22,6 @@ 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 {
|
||||
@@ -47,7 +45,6 @@ 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),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,11 +125,6 @@ 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,12 +24,6 @@ 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.
|
||||
@@ -87,7 +81,9 @@ async fn revision_text(
|
||||
encoding: Option<&str>,
|
||||
) -> IdeResult<Option<(String, &'static encoding_rs::Encoding, bool)>> {
|
||||
let project = host.project(window).ok();
|
||||
let external = external_log_of(host, window, path);
|
||||
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 (path, rev, encoding) = (path.to_path_buf(), rev.to_owned(), encoding.map(str::to_owned));
|
||||
blocking(move || {
|
||||
fn with_repo<T>(
|
||||
@@ -626,7 +622,9 @@ 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 = external_log_of(host, window, &path);
|
||||
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()
|
||||
});
|
||||
blocking(move || {
|
||||
if let Some(project) = project {
|
||||
return project.with_log_backend_of(&path, |r| {
|
||||
@@ -642,37 +640,14 @@ 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 = external_log_of(host, window, &path);
|
||||
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()
|
||||
});
|
||||
blocking(move || {
|
||||
if let Some(project) = project {
|
||||
return project.with_log_backend_of(&path, |r| r.file_mode_at(&path, rev.as_deref()));
|
||||
@@ -3225,7 +3200,6 @@ ide_command::domain!(
|
||||
vcs_discard,
|
||||
vcs_edit_remote,
|
||||
vcs_file_at,
|
||||
vcs_image_at,
|
||||
vcs_file_mode,
|
||||
vcs_diff_entries,
|
||||
vcs_git_version,
|
||||
|
||||
@@ -686,9 +686,6 @@ 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>,
|
||||
@@ -736,29 +733,6 @@ 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;
|
||||
@@ -797,7 +771,6 @@ 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(),
|
||||
@@ -1065,7 +1038,6 @@ 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();
|
||||
@@ -1584,51 +1556,6 @@ 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)?;
|
||||
@@ -2871,16 +2798,6 @@ 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)
|
||||
|
||||
@@ -1174,92 +1174,6 @@ 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> {
|
||||
@@ -1277,10 +1191,6 @@ 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())
|
||||
@@ -2838,7 +2748,6 @@ 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());
|
||||
@@ -2997,7 +2906,7 @@ impl PluginHost {
|
||||
meta.declared_extra = set.capabilities.clone();
|
||||
meta.error = None;
|
||||
}
|
||||
let (mut granted, pending) = match decision {
|
||||
let (granted, pending) = match decision {
|
||||
Decision::Allowed { granted, pending } => (granted, pending),
|
||||
Decision::NeedsConfirmation { new, .. } => {
|
||||
let mut meta = plugin.meta.lock();
|
||||
@@ -3010,19 +2919,6 @@ 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;
|
||||
@@ -3478,21 +3374,6 @@ 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(),
|
||||
@@ -3533,7 +3414,6 @@ 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(),
|
||||
@@ -3562,37 +3442,6 @@ 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,20 +76,6 @@ 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 {
|
||||
@@ -115,8 +101,6 @@ 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,7 +73,6 @@ 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)>>,
|
||||
@@ -208,7 +207,6 @@ 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();
|
||||
@@ -399,8 +397,6 @@ 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));
|
||||
@@ -695,7 +691,6 @@ 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()),
|
||||
@@ -756,9 +751,6 @@ 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());
|
||||
}
|
||||
@@ -959,7 +951,6 @@ 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,9 +267,6 @@ 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);
|
||||
|
||||
@@ -1,183 +0,0 @@
|
||||
//! 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);
|
||||
}
|
||||
}
|
||||
@@ -1,359 +0,0 @@
|
||||
//! 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");
|
||||
}
|
||||
}
|
||||
@@ -110,49 +110,3 @@ 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,131 +696,6 @@ 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,272 +6631,6 @@ 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,7 +52,6 @@ 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"]);
|
||||
@@ -169,7 +168,6 @@ 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",
|
||||
"",
|
||||
|
||||
-337
@@ -1,337 +0,0 @@
|
||||
# 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"
|
||||
@@ -1,21 +0,0 @@
|
||||
[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"
|
||||
Бінарний файл не відображається.
@@ -1 +0,0 @@
|
||||
04c8f881e25aae1b7298f554f3c4ab38251eec48e8d88656d73cad019eb1644c
|
||||
@@ -1,17 +0,0 @@
|
||||
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"
|
||||
@@ -1 +0,0 @@
|
||||
{"properties":{"server":{"type":"string","title":"Server","default":""}}}
|
||||
@@ -1,178 +0,0 @@
|
||||
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);
|
||||
@@ -8,7 +8,6 @@ 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
|
||||
|
||||
@@ -84,16 +84,11 @@ pub(crate) fn detect_with_profiles(
|
||||
}
|
||||
}
|
||||
detect_projects(root, &["build.zig"], zig::detect, &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);
|
||||
}
|
||||
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();
|
||||
@@ -240,16 +235,13 @@ 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`, `cypress run`, `mocha`, or `node --test` (`tsx --test`) with Node's own
|
||||
/// from Jest / Vitest's: `playwright test`, `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");
|
||||
}
|
||||
@@ -283,15 +275,6 @@ 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,
|
||||
@@ -346,29 +329,6 @@ 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 =
|
||||
@@ -386,8 +346,7 @@ 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.clone(), out);
|
||||
push_cypress(&dir, &pkg, &runners, prefix, cwd, out);
|
||||
push_playwright(&dir, &runners, prefix, cwd, out);
|
||||
for member_dir in ide_core::project_roots::node_workspace_members(&dir) {
|
||||
if !covered.insert(member_dir.clone()) {
|
||||
continue;
|
||||
@@ -401,8 +360,7 @@ 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.clone()), out);
|
||||
push_cypress(&member_dir, &member, &runners, Some(&name), Some(rel), out);
|
||||
push_playwright(&member_dir, &runners, Some(&name), Some(rel), out);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1613,49 +1571,6 @@ 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
|
||||
@@ -1738,23 +1653,3 @@ 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,15 +19,11 @@ 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()) {
|
||||
// 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('.')
|
||||
if !name.starts_with('.')
|
||||
&& !matches!(
|
||||
lower.as_str(),
|
||||
name.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);
|
||||
}
|
||||
|
||||
@@ -76,31 +76,6 @@ 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(&[(
|
||||
@@ -1417,40 +1392,3 @@ 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));
|
||||
}
|
||||
@@ -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 fn merge(base: &mut Value, layer: Value) {
|
||||
pub(crate) fn merge(base: &mut Value, layer: Value) {
|
||||
match (base, layer) {
|
||||
(Value::Object(base), Value::Object(layer)) => {
|
||||
for (k, v) in layer {
|
||||
|
||||
@@ -288,13 +288,6 @@ 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,29 +162,6 @@ 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()?;
|
||||
@@ -206,7 +183,14 @@ impl Repo {
|
||||
.and_then(|child| child.head().ok()?.1);
|
||||
return Ok(Some(DiffEntry { mode: "160000".into(), gitlink }));
|
||||
}
|
||||
let entry = revision_entry(&repo, &given, &indexed, rev)?;
|
||||
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)?
|
||||
};
|
||||
Ok(entry.map(|(mode, id)| DiffEntry {
|
||||
mode: format!("{:o}", mode.value()),
|
||||
gitlink: mode.is_commit().then(|| id.to_string()),
|
||||
@@ -350,22 +334,6 @@ 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,37 +1808,6 @@ 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,21 +963,6 @@ 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_IMAGE_SIZE, MAX_RANGE_LEN, base64, content_path_allowed, image_mime, on_local_drive,
|
||||
probe, read_data_url, read_range, same_share,
|
||||
ByteRange, FileProbe, 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,8 +25,5 @@ uuid.workspace = true
|
||||
zip.workspace = true
|
||||
encoding_rs.workspace = true
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
winreg = "0.56"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -260,13 +260,6 @@ 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)) {
|
||||
@@ -293,7 +286,11 @@ impl EditorConfig {
|
||||
}
|
||||
}
|
||||
}
|
||||
matched.then_some(map)
|
||||
if !matched {
|
||||
return None;
|
||||
}
|
||||
let props = props_from(&map);
|
||||
(!props.is_empty()).then_some(props)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,6 @@ pub mod roots;
|
||||
pub mod settings;
|
||||
pub mod text_refs;
|
||||
pub mod unity;
|
||||
pub mod unreal;
|
||||
pub mod window_groups;
|
||||
pub mod workspace;
|
||||
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
//! 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());
|
||||
}
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
//! 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);
|
||||
}
|
||||
}
|
||||
@@ -55,8 +55,6 @@ 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).
|
||||
@@ -160,7 +158,6 @@ 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,7 +20,6 @@ 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 |
|
||||
|
||||
@@ -32,7 +32,7 @@ Running a single test creates a temporary run configuration based on the project
|
||||
| Language | Gutter icons on | Runs with |
|
||||
| --------------------------- | --------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
|
||||
| Rust | `#[test]` functions, `mod tests` | `cargo test`, `cargo nextest` |
|
||||
| JavaScript / TypeScript | `test`, `it`, `describe`, `suite`, `context` (also `.each`, `.only`, `.skip`) | Jest or Vitest via test script; Playwright; Cypress; Deno, Bun |
|
||||
| JavaScript / TypeScript | `test`, `it`, `describe`, `suite`, `context` (also `.each`, `.only`, `.skip`) | Jest or Vitest via the test script; Playwright Test; Deno, Bun |
|
||||
| Python | pytest `def test_*` and `class Test*`, unittest `TestCase` subclasses | pytest, Django `manage.py test` |
|
||||
| Go | `func TestX(t *testing.T)`, benchmarks | `go test` |
|
||||
| Java, Kotlin, Scala, Groovy | JUnit `@Test`, `@ParameterizedTest`, `@RepeatedTest`, `@TestFactory`, `@TestTemplate`; TestNG | Maven Surefire (`-Dtest=`) or Gradle (`--tests`) |
|
||||
@@ -68,7 +68,7 @@ Detected test configurations show results in the tree automatically. For your ow
|
||||
| **Rerun** (in the Run tool window) | `⌘R` | `Ctrl+F5` |
|
||||
| **Rerun Failed Tests** | — | — |
|
||||
|
||||
**Rerun Failed Tests** (in the Run tool window toolbar and Find Action) runs only the tests that failed in the last run, using each tool's filter syntax. It works for Cargo, Jest / Vitest, Playwright, Cypress (with `@cypress/grep`), `node --test`, Mocha, pytest, Django, PHPUnit, Go, Maven / Gradle and .NET runs, and for plugin test frameworks.
|
||||
**Rerun Failed Tests** (in the Run tool window toolbar and Find Action) runs only the tests that failed in the last run, using each tool's filter syntax. It works for Cargo, Jest / Vitest, Playwright, `node --test`, Mocha, pytest, Django, PHPUnit, Go, Maven / Gradle and .NET runs, and for plugin test frameworks.
|
||||
|
||||
Jasmine runs get it too, selecting the failed specs with `--filter=`.
|
||||
|
||||
|
||||
@@ -28,10 +28,6 @@ Two behaviours differ from the servers' defaults: renaming a symbol never introd
|
||||
|
||||
Inlay hints show parameter names at literal arguments, inferred variable types and enum member values; turn kinds off in **Settings › Editor › Inlay Hints**.
|
||||
|
||||
### Project-wide type errors
|
||||
|
||||
The language server checks open files only. To keep the type errors of the whole project in the Problems tool window, turn on **TypeScript Project Errors (tsc --watch)** in the Problems tool window's ⋮ menu (off by default, saved in the project settings). The IDE then runs the project's own `node_modules/.bin/tsc --noEmit --watch` for each `tsconfig.json` that no other one references (`tsc -b --watch` for a solution with project references) and replaces the errors after every compilation. It never writes into the project: outputs and `.tsbuildinfo` files go to a temporary folder. Configurations in folders that are ignored (`.gitignore`), excluded, hidden, or named `fixtures`, `examples` or `testdata` are skipped. Files open in an editor show the language server's errors instead, and an error that Build also reported is listed once. Nothing runs without a local `typescript` or in Restricted Mode.
|
||||
|
||||
### TypeScript version
|
||||
|
||||
**Settings › Languages & Frameworks › TypeScript** picks the TypeScript that `vtsls` and `typescript-language-server` load:
|
||||
@@ -83,12 +79,6 @@ The Astro and Angular servers also run from the project's own `node_modules/.bin
|
||||
|
||||
On these pages, **Formatting provider** chooses between **Automatic (language server first)** and the tool itself, **Run on save** formats on save, and **Enabled languages** limits which languages the tool handles.
|
||||
|
||||
With **Automatic**, a JavaScript or TypeScript file below the tool's own configuration (a Prettier configuration file or `prettier` key in `package.json`, an oxfmt configuration, or Biome's) is formatted by that tool rather than by the language server, once the tool is installed (before `npm install`, the language server formats). **Settings › Editor › General › Reformat code on save** then runs the tool too.
|
||||
|
||||
### Code style
|
||||
|
||||
**Settings › Editor › Code Style › JavaScript** and **TypeScript** have **Spaces** (after commas, around operators, within braces and so on) and **Punctuation** (semicolons: keep, use or don't use; quotes: as in the file, single or double). They are saved per project with the other code style settings and sent to the TypeScript server, which applies them to **Reformat Code** and to the code it adds: quick fixes, auto-imports, refactorings and **Optimize Imports**. JSX files follow JavaScript and TSX files TypeScript. When EditorConfig support is on, the project's `.editorconfig` comes first where it sets `quote_type` or the IntelliJ properties `ij_typescript_use_semicolon_after_statement`, `ij_typescript_use_double_quotes`, `ij_typescript_space_after_comma`, `ij_typescript_spaces_within_object_literal_braces` and the like (`ij_javascript_*` for JavaScript). tsserver has no trailing-comma option, so trailing commas stay as written.
|
||||
|
||||
### Biome lint
|
||||
|
||||
In a Biome project, Biome's diagnostics show in the editor and the Problems tool window, and `⌥⏎` / `Alt+Enter` offers its quick fixes and suppressions. Biome's safe fixes (`source.fixAll.biome`) run with **Code › Code Cleanup** and, when **Settings › Tools › Actions on Save › Run code cleanup** is on, on save. When Biome's formatter is enabled, its fix-all formats the file too.
|
||||
@@ -99,7 +89,6 @@ OpenIDEA detects run configurations when the project opens:
|
||||
|
||||
- One configuration per `package.json` script (`npm run build`, `pnpm run dev`, …), for the root package, nested packages and workspace members. Scripts named `test`, `jest`, `vitest` or `test:*`, and scripts that run `playwright test`, `node --test`, `mocha` or `jasmine`, are test configurations.
|
||||
- `playwright test` (through `npx`) for a package with a `playwright.config.*` that no script runs.
|
||||
- `cypress run` (through `npx`) for a package that depends on `cypress` or has a `cypress.config.*`, when no script runs `cypress run` (scripts that do are test configurations). Its **Cypress** configuration chooses the testing type (end-to-end or component), the browser, the specs and further options.
|
||||
- One per task in `deno.json` / `deno.jsonc` (`deno task <name>`).
|
||||
|
||||
In `package.json`, the gutter shows run icons on each `scripts` entry to run or debug it.
|
||||
@@ -112,8 +101,6 @@ In `package.json`, the gutter shows run icons on each `scripts` entry to run or
|
||||
|
||||
Jest, Vitest, Playwright Test, `node --test`, Mocha and Jasmine output is turned into the test tree, with **Rerun Failed Tests**. Playwright runs report through its `list` reporter unless the configuration names another; a test in the gutter runs by its line (`file:line`), and runs with several projects show each project under its file. `node --test` runs report through the IDE's reporter next to `spec`, added to `NODE_OPTIONS` (a script that chooses its own `--test-reporter` runs without the tree); single tests and reruns are selected by full name (`--test-name-pattern`). Mocha runs keep their reporter and load an IDE hook through `NODE_OPTIONS` that reports each test with its line; single tests and reruns use `--grep`, and in projects that test with Mocha or `node --test`, tests in `test/` get gutter icons whatever their file name. Jasmine runs work the same way, with `--filter=` in place of `--grep`; `fdescribe`, `fit` and `xit` get gutter icons too, and in projects that test with Jasmine so do specs in `spec/` (`cartSpec.js`). **Run with Coverage** works for scripts that run `vitest` or `jest` (Vitest needs a coverage provider such as `@vitest/coverage-v8`; the IDE offers to add it) and for `node` / `tsx` / `ts-node` runs through `c8`. See [Testing](/en/guide/testing) and [Coverage](/en/guide/coverage).
|
||||
|
||||
Cypress runs report through Cypress's built-in `teamcity` reporter unless the configuration names another, and show each spec's suites and tests in the test tree; selecting a test opens its declaration. `*.cy.*` files get gutter icons, and run on the project's Cypress configuration (other tests stay on its other runner); a spec runs with `--spec`, and a spec that mounts components (`cy.mount`) or sits in `cypress/component/` runs with `--component`. `cypress run` can't select tests by name, so single tests, suites and **Rerun Failed Tests** pass their full titles to the [`@cypress/grep`](https://github.com/cypress-io/cypress/tree/develop/npm/grep) plugin: as `--expose grep=…` on Cypress 15.10 and later (`@cypress/grep` 7), and in the `CYPRESS_grep` environment variable (earlier versions). Without a grep plugin among the dependencies (`@cypress/grep`, `cypress-grep`), they run their whole spec files, a notification says so, and the tree shows every test that ran.
|
||||
|
||||
## Debugging
|
||||
|
||||
Debugging uses the JavaScript Debugger (vscode-js-debug); if it is missing, the first debug session offers to install it.
|
||||
|
||||
@@ -55,8 +55,6 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
|
||||
|
||||
**将光标移至下一段落** / **上一段落** 让每个光标越过一段连续的非空行,跳到其后或其前的空行(只含空格或制表符的行也算空行),没有空行时跳到文件末尾或开头;对应的 **并选择** 版本选择到该处。它们默认没有快捷键。
|
||||
|
||||
**以另一种“驼峰”模式将光标移至下一个单词** / **上一个单词**(及其 **并选择** 版本)、**以另一种“驼峰”模式删除到单词开头** 和 **删除到单词结尾** 按与 **设置 › 编辑器 › 常规 › 智能键 › 使用“驼峰”单词** 相反的方式按单词移动或删除:该选项关闭时按驼峰片段(`parse|HTML|Document`),开启时按整个单词。它们默认没有快捷键。
|
||||
|
||||
**剪切到行尾** 从每个光标剪切到所在行的行尾;光标后只剩空白(或光标已在行尾)时连同换行符一起剪切,所以在同一光标处再按一次会剪切下一行,这些连续的剪切合并为剪贴板中的一条内容。**删除到行首** 和 **删除到行尾** 以同样方式删除但不复制(删除到行首时,若光标在行首则删除前面的换行符),有选区时删除选区。除 Eclipse 键位映射(删除到行尾为 `⇧⌘⌦` / `Ctrl+Shift+Delete`)外,它们默认没有快捷键。
|
||||
|
||||
**贪婪退格** 一次删除每个光标前的所有空格、制表符和换行符,直到前一个非空白字符;光标前是其他字符或有选区时,它与 `⌫` / `Backspace` 相同。它默认没有快捷键。
|
||||
@@ -160,7 +158,6 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
|
||||
- **视图 › 活动编辑器 › 软换行** 让当前编辑器的长行自动折行。想让某些文件类型默认软换行,在 **设置 › 编辑器 › 常规** 的 **软换行** 一节中设置。
|
||||
- **视图 › 重置字体大小** 撤销当前编辑器或焦点区域的字体缩放(**视图 › 重置所有编辑器中的字体大小** 会重置所有打开的编辑器)。用 `⌘` / `Ctrl` + 鼠标滚轮调整字号的功能默认关闭,可在 **设置 › 编辑器 › 常规** 的 **鼠标控制** 一节中打开,并可选择作用于 **当前编辑器**(默认)或 **所有编辑器**。
|
||||
- **视图 › 外观 › 进入无干扰模式** 隐藏工具窗口、标签页、状态栏和装订区域,并让正文居中。再执行一次即可退出。
|
||||
- **视图 › 外观 › 进入 Zen 模式** 同时开启无干扰模式和全屏;**退出 Zen 模式** 同时关闭两者。
|
||||
- **显示行号**、**显示缩进参考线**、**显示粘滞行** 和 **显示空白** 在所有编辑器中打开或关闭对应显示。可从查找操作运行,或右键单击装订区域并打开 **外观**。
|
||||
- 行号、空白字符、缩进参考线、光标样式和意图灯泡在 **设置 › 编辑器 › 常规 › 外观** 中设置。痕迹导航和粘滞行(滚动时把所在的声明固定在顶部)在 **设置 › 编辑器 › 常规** 下各有单独的页面。
|
||||
|
||||
|
||||
@@ -20,7 +20,6 @@ description: "创建、编辑和启动运行配置,从装订区运行代码,
|
||||
| `package.json` | 每个 `scripts` 条目一个,使用锁文件对应的包管理器(npm、pnpm、yarn 或 bun)。`test`、`test:*`、`jest`、`vitest` 脚本会标记为测试。 |
|
||||
| `deno.json` / `deno.jsonc` | Deno task |
|
||||
| `playwright.config.*` | 运行 `playwright test` 的脚本是测试配置;没有这样的脚本时为 `npx playwright test` |
|
||||
| `cypress.config.*` / `cypress` 依赖 | 运行 `cypress run` 的脚本是测试配置;没有这样的脚本时为 `npx cypress run`(Cypress 配置) |
|
||||
| `Cargo.toml` | 每个二进制一个 `cargo run`,以及 `cargo test`、`cargo build`;包含 workspace 成员 |
|
||||
| `build.gradle(.kts)` / `pom.xml` | Gradle、Maven 运行配置 |
|
||||
| `go.mod` / `go.work` | Go 程序和测试 |
|
||||
|
||||
@@ -28,7 +28,7 @@ OpenIDEA 直接使用项目自己的测试工具(Cargo、Jest、pytest、Maven
|
||||
| 语言 | 装订区图标位置 | 运行方式 |
|
||||
| --------------------------- | --------------------------------------------------------------------------------------------- | ----------------------------------------------------- |
|
||||
| Rust | `#[test]` 函数、`mod tests` | `cargo test`、`cargo nextest` |
|
||||
| JavaScript / TypeScript | `test`、`it`、`describe`、`suite`、`context`(含 `.each`、`.only`、`.skip`) | Jest / Vitest(脚本);Playwright;Cypress;Deno、Bun |
|
||||
| JavaScript / TypeScript | `test`、`it`、`describe`、`suite`、`context`(含 `.each`、`.only`、`.skip`) | 用测试脚本运行 Jest 或 Vitest;Playwright;Deno、Bun |
|
||||
| Python | pytest 的 `def test_*`、`class Test*`,unittest 的 `TestCase` 子类 | pytest、Django `manage.py test` |
|
||||
| Go | `func TestX(t *testing.T)`、基准测试 | `go test` |
|
||||
| Java、Kotlin、Scala、Groovy | JUnit `@Test`、`@ParameterizedTest`、`@RepeatedTest`、`@TestFactory`、`@TestTemplate`;TestNG | Maven Surefire(`-Dtest=`)或 Gradle(`--tests`) |
|
||||
@@ -64,7 +64,7 @@ RSpec 有自己的配置类型(**RSpec 测试**)和检测到的 `rspec` 配
|
||||
| **重新运行**(在“运行”工具窗口中) | `⌘R` | `Ctrl+F5` |
|
||||
| **重新运行失败的测试** | — | — |
|
||||
|
||||
**重新运行失败的测试**(在“运行”工具窗口工具栏和“查找操作”中)只运行上一次失败的测试,会按各个工具自己的过滤语法生成命令。支持 Cargo、Jest / Vitest、Playwright、Cypress(需 `@cypress/grep`)、`node --test`、Mocha、pytest、Django、PHPUnit、Go、Maven / Gradle 和 .NET,以及插件接入的测试框架。
|
||||
**重新运行失败的测试**(在“运行”工具窗口工具栏和“查找操作”中)只运行上一次失败的测试,会按各个工具自己的过滤语法生成命令。支持 Cargo、Jest / Vitest、Playwright、`node --test`、Mocha、pytest、Django、PHPUnit、Go、Maven / Gradle 和 .NET,以及插件接入的测试框架。
|
||||
|
||||
Jasmine 运行也支持,用 `--filter=` 选出失败的测试。
|
||||
|
||||
|
||||
@@ -28,10 +28,6 @@ TypeScript 服务器以 `tsconfig.json`、`jsconfig.json` 或 `package.json` 所
|
||||
|
||||
嵌入提示会显示字面量实参的参数名、推断出的变量类型和枚举成员的值;可以在 **设置 › 编辑器 › 嵌入提示** 中按类型关闭。
|
||||
|
||||
### 整个项目的类型错误
|
||||
|
||||
语言服务器只检查已打开的文件。要在 Problems 工具窗口里保留整个项目的类型错误,在 Problems 工具窗口的 ⋮ 菜单中打开 **TypeScript 项目错误(tsc --watch)**(默认关闭,保存在项目设置中)。IDE 会对每个没有被其他配置引用的 `tsconfig.json` 运行项目自己的 `node_modules/.bin/tsc --noEmit --watch`(带项目引用的解决方案配置运行 `tsc -b --watch`),每次编译后替换这些错误。它不会向项目写入任何文件:编译输出和 `.tsbuildinfo` 都写到临时目录。被 `.gitignore` 忽略、被排除、隐藏或名为 `fixtures`、`examples`、`testdata` 的目录里的配置会被跳过。在编辑器中打开的文件改为显示语言服务器的错误;Build 也报告过的同一个错误只列出一次。没有本地 `typescript` 或处于受限模式时不会运行。
|
||||
|
||||
### TypeScript 版本
|
||||
|
||||
**设置 › 语言和框架 › TypeScript** 决定 `vtsls` 和 `typescript-language-server` 加载哪个 TypeScript:
|
||||
@@ -84,12 +80,6 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript
|
||||
|
||||
这些页面上,**格式化工具** 可选 **自动(优先语言服务器)** 或工具本身,**保存时运行** 控制保存时格式化,**启用的语言** 限定工具处理哪些语言。
|
||||
|
||||
选 **自动** 时,位于该工具自身配置之下的 JavaScript、TypeScript 文件(Prettier 配置文件或 `package.json` 里的 `prettier` 键、oxfmt 配置、Biome 配置)由该工具格式化,而不是语言服务器;前提是该工具已安装(`npm install` 之前仍由语言服务器格式化)。这时 **设置 › 编辑器 › 常规 › 保存时重新格式化代码** 也会运行该工具。
|
||||
|
||||
### 代码样式
|
||||
|
||||
**设置 › 编辑器 › 代码样式 › JavaScript** 和 **TypeScript** 有 **空格**(逗号后、运算符两侧、花括号内等)和 **标点**(分号:保持原样、使用或不使用;引号:与文件一致、单引号或双引号)两个标签页。它们和其他代码样式设置一起按项目保存,并发送给 TypeScript 服务器:服务器将其用于 **重新格式化代码**,以及它添加的代码,包括快速修复、自动导入、重构和 **优化导入**。JSX 文件跟随 JavaScript,TSX 文件跟随 TypeScript。启用 EditorConfig 支持时,项目 `.editorconfig` 中设置的 `quote_type` 或 IntelliJ 属性 `ij_typescript_use_semicolon_after_statement`、`ij_typescript_use_double_quotes`、`ij_typescript_space_after_comma`、`ij_typescript_spaces_within_object_literal_braces` 等(JavaScript 用 `ij_javascript_*`)优先。tsserver 没有尾随逗号选项,尾随逗号保持原样。
|
||||
|
||||
### Biome 检查
|
||||
|
||||
在 Biome 项目中,Biome 的诊断显示在编辑器和“问题”工具窗口里,`⌥⏎` / `Alt+Enter` 提供它的快速修复和抑制。Biome 的安全修复(`source.fixAll.biome`)随 **代码 › 代码清理** 运行;开启 **设置 › 工具 › 保存时操作 › 运行代码清理** 后,保存时也会运行。Biome 的格式化器开启时,它的全部修复也会格式化文件。
|
||||
@@ -100,7 +90,6 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript
|
||||
|
||||
- 每个 `package.json` 脚本一个配置(`npm run build`、`pnpm run dev` 等),覆盖根包、嵌套包和 workspace 成员。名为 `test`、`jest`、`vitest` 或 `test:*` 的脚本,以及运行 `playwright test`、`node --test`、`mocha` 或 `jasmine` 的脚本,是测试配置。
|
||||
- 有 `playwright.config.*` 但没有脚本运行它的包:通过 `npx` 运行的 `playwright test`。
|
||||
- 依赖 `cypress` 或有 `cypress.config.*`、但没有脚本运行 `cypress run` 的包:通过 `npx` 运行的 `cypress run`(运行它的脚本是测试配置)。它的 **Cypress** 配置可以选择测试类型(端到端或组件)、浏览器、spec 文件和其他选项。
|
||||
- `deno.json` / `deno.jsonc` 中每个 task 一个配置(`deno task <name>`)。
|
||||
|
||||
在 `package.json` 中,每个 `scripts` 条目旁的边栏图标可以直接运行或调试该脚本。
|
||||
@@ -113,8 +102,6 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript
|
||||
|
||||
Jest、Vitest、Playwright Test、`node --test`、Mocha 和 Jasmine 的输出会解析成测试树,支持 **重新运行失败的测试**。Playwright 运行时使用它的 `list` 报告器(配置里指定了其他报告器时除外);从行号栏运行单个测试时按行号选择(`file:line`),有多个 project 的运行会在文件下按 project 分组。`node --test` 运行时,IDE 通过 `NODE_OPTIONS` 在 `spec` 旁加上自己的报告器(脚本自己指定了 `--test-reporter` 时不显示测试树);单个测试和重新运行按完整名称选择(`--test-name-pattern`)。Mocha 运行保留它自己的报告器,并通过 `NODE_OPTIONS` 加载 IDE 的钩子,逐个报告测试及其所在行;单个测试和重新运行使用 `--grep`,在用 Mocha 或 `node --test` 测试的项目里,`test/` 目录下的测试不论文件名都有行号栏图标。Jasmine 运行的方式相同,用 `--filter=` 代替 `--grep`;`fdescribe`、`fit` 和 `xit` 也有行号栏图标,在用 Jasmine 测试的项目里,`spec/` 目录下的测试(`cartSpec.js`)也有。**使用覆盖率运行** 支持调用 `vitest` 或 `jest` 的脚本(Vitest 需要 `@vitest/coverage-v8` 之类的覆盖率 provider,缺失时 IDE 会提示添加),以及通过 `c8` 运行的 `node` / `tsx` / `ts-node`。详见[测试](/zh/guide/testing)和[覆盖率](/zh/guide/coverage)。
|
||||
|
||||
Cypress 运行时使用 Cypress 内置的 `teamcity` 报告器(配置里指定了其他报告器时除外),测试树按 spec 列出其中的 suite 和测试;选中测试会打开它的声明处。`*.cy.*` 文件有行号栏图标,并用项目的 Cypress 配置运行(其他测试仍用项目的另一个测试运行器);运行 spec 时使用 `--spec`,挂载组件(`cy.mount`)或位于 `cypress/component/` 的 spec 会加上 `--component`。`cypress run` 不能按名称选择测试,所以单个测试、suite 和 **重新运行失败的测试** 会把完整标题交给 [`@cypress/grep`](https://github.com/cypress-io/cypress/tree/develop/npm/grep) 插件:Cypress 15.10 及以上用 `--expose grep=…`(`@cypress/grep` 7),更早的版本用环境变量 `CYPRESS_grep`。依赖中没有 grep 插件(`@cypress/grep`、`cypress-grep`)时,会运行整个 spec 文件,并弹出通知说明,测试树显示实际运行的所有测试。
|
||||
|
||||
## 调试
|
||||
|
||||
调试使用 JavaScript 调试器(vscode-js-debug);未安装时,第一次调试会提示安装。
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
/**
|
||||
* Git Branches of a project with several repositories: the current repository is listed first,
|
||||
* and moving the pointer from a repository row toward its open branch list keeps that list open
|
||||
* while it crosses the other repository rows (like a submenu of a menu). Git is stubbed at the
|
||||
* IPC layer.
|
||||
*/
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const ROOTS = ["/dev/acme/app", "/dev/acme/lib", "/dev/acme/tools", "/dev/acme/web"];
|
||||
|
||||
async function openBranches(page: Page) {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ roots }) => {
|
||||
const h = window.__ipc.handlers;
|
||||
const branch = (name: string, current = false) => ({
|
||||
name,
|
||||
current,
|
||||
remote: false,
|
||||
upstream: null,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
lastCommitMs: null,
|
||||
commit: "1111111",
|
||||
});
|
||||
const repoName = (root: string) => root.split("/").pop()!;
|
||||
h.vcs_roots = () =>
|
||||
roots.map((root) => ({ root, operation: null, head: "main", headCommit: "1111111", hasRemotes: false }));
|
||||
h.vcs_branch_info = () => ({
|
||||
head: "main",
|
||||
headCommit: "1111111",
|
||||
upstream: null,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
operation: null,
|
||||
});
|
||||
h.vcs_status = () => [];
|
||||
h.vcs_tags = () => [];
|
||||
h.vcs_branches = (args: { repo?: string | null }) => [
|
||||
branch("main", true),
|
||||
branch(`only-${repoName(args?.repo ?? roots[0]!)}`),
|
||||
];
|
||||
const vcsModule = "/src/features/vcs/store.ts";
|
||||
const { useVcs, refreshNow, loadBranches } = await import(/* @vite-ignore */ vcsModule);
|
||||
// The window works on the third repository.
|
||||
useVcs.setState({ available: true, root: roots[0], repo: roots[2], branchesLoaded: false });
|
||||
await refreshNow();
|
||||
await loadBranches();
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
await executeAction("vcs.branches");
|
||||
},
|
||||
{ roots: ROOTS },
|
||||
);
|
||||
const list = page.getByRole("listbox", { name: "Repositories and branches" });
|
||||
await expect(list).toBeVisible();
|
||||
return list;
|
||||
}
|
||||
|
||||
const center = async (locator: ReturnType<Page["locator"]>) => {
|
||||
const box = (await locator.boundingBox())!;
|
||||
return { x: box.x + box.width / 2, y: box.y + box.height / 2, box };
|
||||
};
|
||||
|
||||
test("multi-repository Git Branches lists the current repository first and keeps a branch list open on the way to it", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const list = await openBranches(page);
|
||||
const rows = list.getByRole("option").filter({ has: page.locator("[data-row-key^='repo:']") });
|
||||
await expect(rows).toHaveCount(4);
|
||||
await expect(rows.first()).toContainText("tools");
|
||||
|
||||
// Open the first repository's branches, then head diagonally into the list across the rows below.
|
||||
const first = await center(rows.nth(0));
|
||||
await page.mouse.move(first.x, first.y);
|
||||
const branchesOfTools = page.getByRole("dialog", { name: "Branches of tools" });
|
||||
await expect(branchesOfTools).toBeVisible();
|
||||
const target = (await branchesOfTools.boundingBox())!;
|
||||
const last = await center(rows.nth(3));
|
||||
await page.mouse.move(target.x + 12, last.y, { steps: 12 });
|
||||
await expect(branchesOfTools).toBeVisible();
|
||||
await expect(branchesOfTools.getByText("only-tools", { exact: true })).toBeVisible();
|
||||
|
||||
// Moving straight onto another repository row switches to its branches.
|
||||
const second = await center(rows.nth(1));
|
||||
await page.mouse.move(second.x - 40, second.y);
|
||||
await page.mouse.move(second.x - 60, second.y);
|
||||
const branchesOfApp = page.getByRole("dialog", { name: "Branches of app" });
|
||||
await expect(branchesOfApp).toBeVisible();
|
||||
await expect(branchesOfTools).toBeHidden();
|
||||
|
||||
// Stopping on a row while heading for the open list switches only after a short delay.
|
||||
const third = await center(rows.nth(2));
|
||||
const appList = (await branchesOfApp.boundingBox())!;
|
||||
await page.mouse.move(appList.x - 30, second.y);
|
||||
await page.mouse.move(appList.x - 6, third.y);
|
||||
await expect(branchesOfApp).toBeVisible();
|
||||
await expect(page.getByRole("dialog", { name: "Branches of lib" })).toBeVisible();
|
||||
await expect(branchesOfApp).toBeHidden();
|
||||
});
|
||||
@@ -41,19 +41,3 @@ test("Copy Path/Reference keeps its preview and shortcut visible and can be resi
|
||||
await expect(popup).toBeHidden();
|
||||
await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(path);
|
||||
});
|
||||
|
||||
test("Copy Path/Reference… in the Project view previews what each row copies", async ({ workbench: page, context }) => {
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await page.getByRole("treeitem", { name: "build.gradle.kts" }).click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "Copy Path/Reference…" }).click();
|
||||
|
||||
const popup = page.getByRole("dialog", { name: "Copy Path/Reference…" });
|
||||
const name = popup.getByRole("option", { name: /^File Name/ });
|
||||
await expect(name.locator('[title="build.gradle.kts"]')).toBeVisible();
|
||||
await expect(popup.getByRole("option", { name: /^Path From Content Root/ })).toBeVisible();
|
||||
await page.keyboard.type("file name");
|
||||
await expect(name).toHaveAttribute("aria-selected", "true");
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(popup).toBeHidden();
|
||||
await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe("build.gradle.kts");
|
||||
});
|
||||
@@ -411,8 +411,7 @@ test("rename owns deletion and Cmd+Enter without editing the previously focused
|
||||
await page.keyboard.press("Meta+a");
|
||||
const query = "SELECT 'keep this query';\nSELECT 2;";
|
||||
await page.keyboard.insertText(query);
|
||||
// Caret on the first line (Cmd+Up is Jump to Navigation Bar, not a caret move).
|
||||
await content.locator(".cm-line").first().click();
|
||||
await page.keyboard.press("Meta+ArrowUp");
|
||||
await expect(content).toHaveText(query.replace("\n", ""));
|
||||
|
||||
await choose(page, "Result 1", "Rename Tab");
|
||||
@@ -440,7 +439,8 @@ test("rename owns deletion and Cmd+Enter without editing the previously focused
|
||||
await expect(content).toHaveText(query.replace("\n", ""));
|
||||
|
||||
// The editor's own Delete Line shortcut still works after the dialog closes.
|
||||
await content.locator(".cm-line").first().click();
|
||||
await content.click();
|
||||
await page.keyboard.press("Meta+ArrowUp");
|
||||
await page.keyboard.press("Meta+Backspace");
|
||||
await expect(content.locator(".cm-line").filter({ hasText: /SELECT/ })).toHaveCount(1);
|
||||
});
|
||||
|
||||
@@ -1,248 +0,0 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const ROOT = "/dev/acme-api";
|
||||
|
||||
async function pngVersions(page: Page) {
|
||||
return page.evaluate(() => {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = 4;
|
||||
canvas.height = 3;
|
||||
const ctx = canvas.getContext("2d")!;
|
||||
ctx.fillStyle = "teal";
|
||||
ctx.fillRect(0, 0, 4, 3);
|
||||
const head = canvas.toDataURL();
|
||||
ctx.clearRect(2, 1, 1, 1);
|
||||
ctx.fillStyle = "rgba(0, 128, 128, 0.5)";
|
||||
ctx.fillRect(2, 1, 1, 1);
|
||||
const index = canvas.toDataURL();
|
||||
ctx.clearRect(0, 0, 2, 1);
|
||||
return { head, index, local: canvas.toDataURL() };
|
||||
});
|
||||
}
|
||||
|
||||
async function expectCount(page: Page, count: number) {
|
||||
await expect(
|
||||
page.getByRole("status").filter({ hasText: new RegExp(`^${count} changed pixels?$`, "i") }),
|
||||
).toBeVisible();
|
||||
}
|
||||
|
||||
test("Commit Changes renders a PNG and highlights one alpha-only change", async ({ workbench: page }) => {
|
||||
await openFromTree(page, "build.gradle.kts");
|
||||
await stubDesktop(page);
|
||||
const { head, index: local } = await pngVersions(page);
|
||||
const file = "status.png";
|
||||
const path = ROOT + "/" + file;
|
||||
await page.evaluate(
|
||||
async ({ root, path, file, head, local }) => {
|
||||
const handlers = window.__ipc.handlers;
|
||||
const branch = { head: "main", headCommit: "1111111", operation: null, upstream: null, ahead: 0, behind: 0 };
|
||||
handlers.vcs_roots = () => [{ root, ...branch }];
|
||||
handlers.vcs_branch_info = () => branch;
|
||||
handlers.vcs_branches = () => [];
|
||||
handlers.vcs_stashes = () => [];
|
||||
handlers.vcs_status = () => [{ path, relPath: file, staged: null, unstaged: "modified", renamedFrom: null }];
|
||||
handlers.vcs_image_at = ({ rev }) => (rev === "HEAD" ? head : null);
|
||||
handlers.fs_read_image = () => local;
|
||||
const store = "/src/features/vcs/store.ts";
|
||||
const { useVcs, refreshNow } = await import(/* @vite-ignore */ store);
|
||||
useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false });
|
||||
await refreshNow();
|
||||
},
|
||||
{ root: ROOT, path, file, head, local },
|
||||
);
|
||||
await page.keyboard.press("Meta+k");
|
||||
await page.getByRole("tree", { name: "Changes" }).getByText(file, { exact: true }).dblclick();
|
||||
const toolbar = page.getByRole("toolbar", { name: "Image diff" });
|
||||
const highlight = toolbar.getByRole("button", { name: "Highlight changed pixels" });
|
||||
await highlight.click();
|
||||
await expectCount(page, 1);
|
||||
const mask = page.getByLabel("Pixel difference mask");
|
||||
await expect(mask).toBeVisible();
|
||||
const pixels = await mask.evaluate((element) => {
|
||||
const canvas = element as HTMLCanvasElement;
|
||||
const data = canvas.getContext("2d")!.getImageData(0, 0, canvas.width, canvas.height).data;
|
||||
return Array.from({ length: canvas.width * canvas.height }, (_, i) => data.slice(4 * i, 4 * i + 4).join(","));
|
||||
});
|
||||
expect(pixels).toHaveLength(12);
|
||||
expect(pixels.filter((pixel) => pixel !== pixels[0])).toEqual([pixels[6]]);
|
||||
expect(pixels[6]).not.toBe(pixels[0]);
|
||||
await highlight.click();
|
||||
await expect(mask).toBeHidden();
|
||||
expect(await ipcCalls(page, "vcs_image_at")).toContainEqual({ path, rev: "HEAD" });
|
||||
expect(await ipcCalls(page, "fs_read_image")).toContainEqual({ path });
|
||||
});
|
||||
|
||||
test("staged and unstaged PNG diffs compare the index with the specified side", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
const images = await pngVersions(page);
|
||||
await page.evaluate(({ head, index, local }) => {
|
||||
window.__ipc.handlers.vcs_image_at = ({ rev }) => (rev === "HEAD" ? head : rev === ":0" ? index : null);
|
||||
window.__ipc.handlers.fs_read_image = () => local;
|
||||
}, images);
|
||||
for (const [side, count] of [
|
||||
["staged", 1],
|
||||
["unstaged", 2],
|
||||
] as const) {
|
||||
await page.evaluate(
|
||||
async ({ side, root }) => {
|
||||
const input = "/src/features/vcs/diffInput.ts";
|
||||
const { openDiff, workingDiffData } = await import(/* @vite-ignore */ input);
|
||||
const path = root + "/status.png";
|
||||
const status = { path, relPath: "status.png", staged: "modified", unstaged: "modified", renamedFrom: null };
|
||||
await openDiff(workingDiffData(path, undefined, side, status));
|
||||
},
|
||||
{ side, root: ROOT },
|
||||
);
|
||||
const highlight = page.getByRole("button", { name: "Highlight changed pixels" });
|
||||
await highlight.click();
|
||||
await expectCount(page, count);
|
||||
await highlight.click();
|
||||
}
|
||||
});
|
||||
|
||||
test("the three-way PNG diff labels each revision and compares all three pairs", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
const images = await pngVersions(page);
|
||||
await page.evaluate(async ({ head, index, local }) => {
|
||||
window.__ipc.handlers.vcs_image_at = ({ rev }) => (rev === "HEAD" ? head : rev === ":0" ? index : null);
|
||||
window.__ipc.handlers.fs_read_image = () => local;
|
||||
const input = "/src/features/vcs/diffInput.ts";
|
||||
const { openDiff, stagingGutterDiffData } = await import(/* @vite-ignore */ input);
|
||||
await openDiff(stagingGutterDiffData("/dev/acme-api/status.png"));
|
||||
}, images);
|
||||
for (const [label, url] of [
|
||||
["HEAD", images.head],
|
||||
["Staged (index)", images.index],
|
||||
["Local Version", images.local],
|
||||
] as const) {
|
||||
await expect(page.getByRole("img", { name: label, exact: true })).toHaveAttribute("src", url);
|
||||
}
|
||||
const toolbar = page.getByRole("toolbar", { name: "Image diff" });
|
||||
await toolbar.getByRole("button", { name: "Highlight changed pixels" }).click();
|
||||
await expectCount(page, 1);
|
||||
for (const [pair, count] of [
|
||||
["Staged (index) ↔ Local Version", 2],
|
||||
["HEAD ↔ Local Version", 3],
|
||||
] as const) {
|
||||
await toolbar.getByRole("button", { name: "Compare revisions" }).click();
|
||||
await page.getByRole("option", { name: pair }).click();
|
||||
await expectCount(page, count);
|
||||
}
|
||||
});
|
||||
|
||||
for (const ext of ["jpg", "jpeg", "webp", "svg"] as const) {
|
||||
test(`renders both historical revisions of a renamed .${ext} without a working file`, async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
const path = `${ROOT}/current.${ext}`;
|
||||
const oldPath = `${ROOT}/original.${ext}`;
|
||||
await page.evaluate(
|
||||
async ({ path, oldPath, ext }) => {
|
||||
const before =
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" width="8" height="6"><rect width="8" height="6"/></svg>';
|
||||
const after = before.replace("<rect ", '<rect id="same-shape" ');
|
||||
const url = (source: string) => "data:image/svg+xml;base64," + btoa(source);
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = 8;
|
||||
canvas.height = 6;
|
||||
const ctx = canvas.getContext("2d")!;
|
||||
const encode = (color: string) => {
|
||||
ctx.fillStyle = color;
|
||||
ctx.fillRect(0, 0, 8, 6);
|
||||
// WebKit can decode WebP even when its canvas encoder would return PNG.
|
||||
if (ext === "webp") {
|
||||
const bytes =
|
||||
color === "white"
|
||||
? "UklGRiIAAABXRUJQVlA4TBYAAAAvB0ABAAfQ//73v/8BgCD8b5uI6H8I"
|
||||
: "UklGRiAAAABXRUJQVlA4TBMAAAAvB0ABAAcQEf0PAAThf9tERP9DAA==";
|
||||
return "data:image/webp;base64," + bytes;
|
||||
}
|
||||
return canvas.toDataURL("image/jpeg");
|
||||
};
|
||||
const left = ext === "svg" ? url(before) : encode("white");
|
||||
const right = ext === "svg" ? url(after) : encode("black");
|
||||
const handlers = window.__ipc.handlers;
|
||||
handlers.vcs_image_at = (args) => {
|
||||
if (args.path === oldPath && args.rev === "11111111") return left;
|
||||
if (args.path === path && args.rev === "22222222") return right;
|
||||
return null;
|
||||
};
|
||||
handlers.vcs_file_at = (args) => (args.path === oldPath ? before : after);
|
||||
const input = "/src/features/vcs/diffInput.ts";
|
||||
const { openDiff, commitFileDiffData } = await import(/* @vite-ignore */ input);
|
||||
await openDiff(
|
||||
commitFileDiffData(
|
||||
{ id: "22222222", shortId: "22222222", parents: ["11111111"], repo: "/dev/acme-api" },
|
||||
{ path: "current." + ext, oldPath: "original." + ext, kind: "renamed" },
|
||||
),
|
||||
);
|
||||
},
|
||||
{ path, oldPath, ext },
|
||||
);
|
||||
const toolbar = page.getByRole("toolbar", { name: "Image diff" });
|
||||
await toolbar.getByRole("button", { name: "Highlight changed pixels" }).click();
|
||||
await expectCount(page, ext === "svg" ? 0 : 48);
|
||||
expect(await ipcCalls(page, "fs_read_image")).toEqual([]);
|
||||
if (ext === "svg") {
|
||||
await toolbar.getByRole("button", { name: "View source diff" }).click();
|
||||
const xml = page.locator(".cm-content").filter({ hasText: "same-shape" });
|
||||
await expect(xml).toBeVisible();
|
||||
await page.getByRole("button", { name: "Image preview" }).click();
|
||||
await expect(xml).toBeHidden();
|
||||
await expect(page.getByRole("button", { name: "View source diff" })).toBeVisible();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Identical opaque teal RGBA rows encoded with zlib levels 0 and 9. The cropped version removes the rightmost column.
|
||||
const originalPng =
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAPklEQVR4AQEzAMz/AACAgP8AgID/AICA/wCAgP8AAICA/wCAgP8AgID/AICA/wAAgID/AICA/wCAgP8AgID/UTEX9btCu2YAAAAASUVORK5CYII=";
|
||||
const recompressedPng =
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAEUlEQVR42mNgaGj4j4IJCgAAUTEX9X/prpgAAAAASUVORK5CYII=";
|
||||
const croppedPng =
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAMAAAADCAYAAABWKLW/AAAAEElEQVR42mNgaGj4D8c4OQBRFBH4p8q4GwAAAABJRU5ErkJggg==";
|
||||
|
||||
for (const [scenario, count] of [
|
||||
["recompressed", 0],
|
||||
["cropped", 3],
|
||||
["added", 12],
|
||||
["deleted", 12],
|
||||
] as const) {
|
||||
test(`shows ${count} changed pixels for historical PNGs (${scenario})`, async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ scenario, before, after }) => {
|
||||
const input = "/src/features/vcs/diffInput.ts";
|
||||
const { openDiff, commitFileDiffData } = await import(/* @vite-ignore */ input);
|
||||
window.__ipc.handlers.vcs_image_at = ({ rev }) =>
|
||||
"data:image/png;base64," + (rev === "11111111" ? before : after);
|
||||
const kind = scenario === "added" || scenario === "deleted" ? scenario : "modified";
|
||||
await openDiff(
|
||||
commitFileDiffData(
|
||||
{ id: "22222222", shortId: "22222222", parents: ["11111111"], repo: "/dev/acme-api" },
|
||||
{ path: "snapshot.png", kind },
|
||||
),
|
||||
);
|
||||
},
|
||||
{ scenario, before: originalPng, after: scenario === "cropped" ? croppedPng : recompressedPng },
|
||||
);
|
||||
if (scenario === "added" || scenario === "deleted") {
|
||||
const missing = scenario === "added" ? "(does not exist)" : "(deleted)";
|
||||
await expect(page.getByRole("region", { name: missing }).getByText("No image on this side")).toBeVisible();
|
||||
const rev = scenario === "added" ? "22222222" : "11111111";
|
||||
await expect(page.getByRole("img", { name: rev })).toBeVisible();
|
||||
const reads = await ipcCalls(page, "vcs_image_at");
|
||||
expect(new Set(reads.map((call) => call.rev))).toEqual(new Set([rev]));
|
||||
}
|
||||
await page.getByRole("button", { name: "Highlight changed pixels" }).click();
|
||||
await expectCount(page, count);
|
||||
if (scenario === "cropped") {
|
||||
const changed = await page.getByLabel("Pixel difference mask").evaluate((element) => {
|
||||
const ctx = (element as HTMLCanvasElement).getContext("2d")!;
|
||||
const rgba = ctx.getImageData(0, 0, 4, 3).data;
|
||||
return Array.from({ length: 12 }, (_, i) => i).filter((i) => rgba[i * 4] !== rgba[i * 4 + 1]);
|
||||
});
|
||||
expect(changed).toEqual([3, 7, 11]);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -10,7 +10,6 @@ something to show.
|
||||
| `rust-app/` | cargo | `cargo run` | `cargo test` | `cargo test --features failing-tests` | unused variable in `src/parser.rs` |
|
||||
| `ts-app/` | Node 22+, pnpm/npm | `pnpm start` | `pnpm test` (vitest) | `OPENIDEA_FAIL=1 pnpm test` | unused function in `src/index.ts` |
|
||||
| `playwright-app/` | Node 22+, npm (Playwright Test, no browser needed) | — | `npm test` | `OPENIDEA_FAIL=1 npm test` | unused function in `src/checkout.ts` |
|
||||
| `cypress-app/` | Node 22+, npm (Cypress 16 with its Electron, no server needed) | — | `npm run e2e` | `npm run e2e -- --expose fail=1` | unused function in `src/cart.ts` |
|
||||
| `node-test-app/` | Node 22+, npm (no dependencies) | — | `npm test` (node:test) | `OPENIDEA_FAIL=1 npm test` | unused constant in `src/inventory.js` |
|
||||
| `mocha-app/` | Node 22+, npm | — | `npm test` (Mocha) | `OPENIDEA_FAIL=1 npm test` | unused constant in `src/pricing.js` |
|
||||
| `jasmine-app/` | Node 22+, npm | — | `npm test` (Jasmine) | `OPENIDEA_FAIL=1 npm test` | unused constant in `src/cart.js` |
|
||||
@@ -48,7 +47,7 @@ git init -q && git add -A && git commit -qm "initial" # for the VCS checks
|
||||
```
|
||||
|
||||
Then open the folder with **File › Open…** (`⌘⇧⌥O`) or from the Welcome screen.
|
||||
For `ts-app` / `playwright-app` / `mocha-app` / `polyglot/web` run `pnpm install` first (`npm install` for `biome-app`, `cypress-app`, `dprint-app` and `stylelint-app`); for `python-app` create a
|
||||
For `ts-app` / `playwright-app` / `mocha-app` / `polyglot/web` run `pnpm install` first (`npm install` for `biome-app`, `dprint-app` and `stylelint-app`); for `python-app` create a
|
||||
venv (`python3 -m venv .venv && .venv/bin/pip install -e '.[dev]'`); for
|
||||
`php-app` run `composer install` (debugging it needs Xdebug in the PHP on `PATH`).
|
||||
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
node_modules
|
||||
cypress/screenshots
|
||||
cypress/videos
|
||||
cypress/downloads
|
||||
@@ -1,5 +0,0 @@
|
||||
import { defineConfig } from "cypress";
|
||||
|
||||
export default defineConfig({
|
||||
e2e: { video: false, screenshotOnRunFailure: false },
|
||||
});
|
||||
@@ -1,33 +0,0 @@
|
||||
import { discount, subtotal, withTax, type Item } from "../../src/cart";
|
||||
|
||||
const mug: Item = { sku: "mug", price: 12, quantity: 2 };
|
||||
const lamp: Item = { sku: "lamp", price: 40, quantity: 1 };
|
||||
|
||||
describe("cart", () => {
|
||||
it("adds up the items", () => {
|
||||
cy.wrap(subtotal([mug, lamp])).should("eq", 64);
|
||||
});
|
||||
|
||||
context("totals", () => {
|
||||
it("adds the tax", () => {
|
||||
cy.wrap(withTax(64)).should("eq", 70.4);
|
||||
});
|
||||
|
||||
// Fails on purpose with `--expose fail=1`.
|
||||
it("rounds to cents", () => {
|
||||
cy.wrap(withTax(Cypress.expose("fail") ? 1.01 : 1)).should("eq", 1.1);
|
||||
});
|
||||
});
|
||||
|
||||
it.skip("keeps the cart between visits", () => {});
|
||||
});
|
||||
|
||||
describe("discounts", () => {
|
||||
it("halves the total", () => {
|
||||
expect(discount(64, "HALF")).to.equal(32);
|
||||
});
|
||||
|
||||
it("rejects unknown codes", () => {
|
||||
expect(() => discount(64, "NOPE")).to.throw("unknown code");
|
||||
});
|
||||
});
|
||||
@@ -1,4 +0,0 @@
|
||||
// Lets the IDE run single tests, suites and failed tests by title.
|
||||
import { register } from "@cypress/grep";
|
||||
|
||||
register();
|
||||
@@ -1,15 +0,0 @@
|
||||
{
|
||||
"name": "openidea-fixture-cart",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "OpenIDEA QA fixture: Cypress specs for a cart module (Cypress's own Electron, no server needed)",
|
||||
"scripts": {
|
||||
"e2e": "cypress run",
|
||||
"lint": "tsc -p . --noEmit"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@cypress/grep": "^7.0.0",
|
||||
"cypress": "^16.0.0",
|
||||
"typescript": "^5.6.0"
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
export interface Item {
|
||||
sku: string;
|
||||
price: number;
|
||||
quantity: number;
|
||||
}
|
||||
|
||||
const TAX_RATE = 0.1;
|
||||
|
||||
export function subtotal(items: Item[]): number {
|
||||
return items.reduce((sum, i) => sum + i.price * i.quantity, 0);
|
||||
}
|
||||
|
||||
export function withTax(total: number): number {
|
||||
// FIXME: tax rates differ by region
|
||||
return Math.round(total * (1 + TAX_RATE) * 100) / 100;
|
||||
}
|
||||
|
||||
export function discount(total: number, code: string): number {
|
||||
if (code === "HALF") return Math.round(total * 50) / 100;
|
||||
throw new Error(`unknown code: ${code}`);
|
||||
}
|
||||
|
||||
// An intentional warning: never used.
|
||||
function roundDown(value: number): number {
|
||||
return Math.floor(value);
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true,
|
||||
"types": ["cypress"]
|
||||
},
|
||||
"include": ["src", "cypress", "cypress.config.ts"]
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
id = "json"
|
||||
name = "JSON"
|
||||
formatter = { tool = "prettier", parser = "json", range = true }
|
||||
extensions = ["json", "geojson", "topojson", "webmanifest", "har", "avsc", "jsonl", "ndjson", "json.map", "uproject", "uplugin"]
|
||||
extensions = ["json", "geojson", "topojson", "webmanifest", "har", "avsc", "jsonl", "ndjson", "json.map"]
|
||||
filenames = [".prettierrc", ".watchmanconfig", "composer.lock", ".arcconfig"]
|
||||
indent = { tab-size = 2, insert-spaces = true }
|
||||
ui-mode = "JSON"
|
||||
|
||||
+34
-53
@@ -351,35 +351,33 @@ installing (or when a new version asks for more). Low-risk capabilities are
|
||||
listed; high-risk ones are called out as equivalent to running code on the
|
||||
machine. Users can revoke optional capabilities in Settings › Plugins.
|
||||
|
||||
| Capability | Risk | Unlocks today |
|
||||
| ------------------------ | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `ide.commands` | high | Run any IDE action or other plugins' commands as if you chose them, including running programs, committing and pushing. API 1.4; declared own commands are exempt. |
|
||||
| `database.sources` | medium | API 1.4: manage only the plugin's own project database sources, write their secure credentials and request connection; trusted projects only. |
|
||||
| `project.read` | low | `Project::root`, `read_file`, `read_bytes`, `find_files`, `symbols`, `search_text`, `host::projects`, `publish_diagnostics`, `problems`, editor opening and decorations |
|
||||
| `project.write` | high | `Project::write_file` — creates and replaces text files inside the open projects, the settings and build scripts a trusted project runs included |
|
||||
| `fs.read:<path>` | high | `host::fs::read_file`, `read_bytes`, `stat`, `read_dir` — files outside the projects, under the grant's directory |
|
||||
| `fs.write:<path>` | high | `host::fs::write_file`, `write_bytes` — files under that path; doesn't imply reading |
|
||||
| `editor.read` | low | `TextEditor::document`, `selections`, `host::open_editors` |
|
||||
| `editor.write` | medium | `TextEditor::apply_edits` |
|
||||
| `vcs.read` | low | `Project::vcs_status`, `vcs_remotes`, `vcs_log`, `vcs_blame`, `vcs_diff` (new reads require trust), `host::pending_commit`, before-commit checks |
|
||||
| `vcs.write` | medium | `Project::vcs_fetch` (trusted projects only), `host::set_commit_message` |
|
||||
| `build.read` | low | API 1.10: `Project::build_dependencies`, the Maven / Gradle dependency graph the IDE resolved; trusted projects only |
|
||||
| `storage` | low | `host::storage` (64 MiB per plugin, counting UTF-8 bytes of keys and values) |
|
||||
| `events` | low | file opened/saved, editor focused, repository changed events |
|
||||
| `events.input` | medium | `action-performed` and `input-mode-changed` events |
|
||||
| `process:<program>` | high | `Project::run_process`, language servers, debug adapters, runs |
|
||||
| `lsp:<server>` | high | API 1.9: `Project::language_server_request` / `language_server_notify` to that running language server (its name in the language definition); trusted projects only |
|
||||
| `java.agent` | high | API 1.10: the `[[contributes.javaAgents]]` jar runs inside the Java applications you start; derived from that declaration, never listed |
|
||||
| `net:<host>` | medium | `host::fetch` over HTTPS (also loopback HTTP); `*.example.com` matches subdomains |
|
||||
| `net:ask` | medium | Ask the user at the first request to an HTTPS (or loopback) host that is not declared; one answer per host, revocable; API 1.5 |
|
||||
| `net.http:<host>` | medium | Unencrypted HTTP to that host; API 1.4, same wildcard rules as `net:` |
|
||||
| `net:setting:<key>` | medium | API 1.18: the host of the plugin's `string` setting `<key>` over HTTPS (also loopback HTTP), approved when the user applies the value in Settings; bare host or URL |
|
||||
| `net.http:setting:<key>` | medium | API 1.18: the same setting's host over unencrypted HTTP, approved the same way |
|
||||
| `ipc:<path>` | high | Local Unix sockets or Windows named pipes on the project machine; API 1.4 |
|
||||
| `secrets` | medium | `{{secret:<name>}}` in request headers, `host::secret_is_set`, `secret_set`, `secret_delete` |
|
||||
| `clipboard` | medium | `host::copy_to_clipboard` and the clipboard API in the plugin's web views |
|
||||
| `clipboard.read` | medium | API 1.11: `host::read_clipboard`, the clipboard's text and image, only in commands and view actions the user ran |
|
||||
| `agents` | medium | API 1.18: `host::fork_agent_session`, fork a recorded native agent session into a new task in the project; trusted projects only |
|
||||
| Capability | Risk | Unlocks today |
|
||||
| ------------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `ide.commands` | high | Run any IDE action or other plugins' commands as if you chose them, including running programs, committing and pushing. API 1.4; declared own commands are exempt. |
|
||||
| `database.sources` | medium | API 1.4: manage only the plugin's own project database sources, write their secure credentials and request connection; trusted projects only. |
|
||||
| `project.read` | low | `Project::root`, `read_file`, `read_bytes`, `find_files`, `symbols`, `search_text`, `host::projects`, `publish_diagnostics`, `problems`, editor opening and decorations |
|
||||
| `project.write` | high | `Project::write_file` — creates and replaces text files inside the open projects, the settings and build scripts a trusted project runs included |
|
||||
| `fs.read:<path>` | high | `host::fs::read_file`, `read_bytes`, `stat`, `read_dir` — files outside the projects, under the grant's directory |
|
||||
| `fs.write:<path>` | high | `host::fs::write_file`, `write_bytes` — files under that path; doesn't imply reading |
|
||||
| `editor.read` | low | `TextEditor::document`, `selections`, `host::open_editors` |
|
||||
| `editor.write` | medium | `TextEditor::apply_edits` |
|
||||
| `vcs.read` | low | `Project::vcs_status`, `vcs_remotes`, `vcs_log`, `vcs_blame`, `vcs_diff` (new reads require trust), `host::pending_commit`, before-commit checks |
|
||||
| `vcs.write` | medium | `Project::vcs_fetch` (trusted projects only), `host::set_commit_message` |
|
||||
| `build.read` | low | API 1.10: `Project::build_dependencies`, the Maven / Gradle dependency graph the IDE resolved; trusted projects only |
|
||||
| `storage` | low | `host::storage` (64 MiB per plugin, counting UTF-8 bytes of keys and values) |
|
||||
| `events` | low | file opened/saved, editor focused, repository changed events |
|
||||
| `events.input` | medium | `action-performed` and `input-mode-changed` events |
|
||||
| `process:<program>` | high | `Project::run_process`, language servers, debug adapters, runs |
|
||||
| `lsp:<server>` | high | API 1.9: `Project::language_server_request` / `language_server_notify` to that running language server (its name in the language definition); trusted projects only |
|
||||
| `java.agent` | high | API 1.10: the `[[contributes.javaAgents]]` jar runs inside the Java applications you start; derived from that declaration, never listed |
|
||||
| `net:<host>` | medium | `host::fetch` over HTTPS (also loopback HTTP); `*.example.com` matches subdomains |
|
||||
| `net:ask` | medium | Ask the user at the first request to an HTTPS (or loopback) host that is not declared; one answer per host, revocable; API 1.5 |
|
||||
| `net.http:<host>` | medium | Unencrypted HTTP to that host; API 1.4, same wildcard rules as `net:` |
|
||||
| `ipc:<path>` | high | Local Unix sockets or Windows named pipes on the project machine; API 1.4 |
|
||||
| `secrets` | medium | `{{secret:<name>}}` in request headers, `host::secret_is_set`, `secret_set`, `secret_delete` |
|
||||
| `clipboard` | medium | `host::copy_to_clipboard` and the clipboard API in the plugin's web views |
|
||||
| `clipboard.read` | medium | API 1.11: `host::read_clipboard`, the clipboard's text and image, only in commands and view actions the user ran |
|
||||
| `agents` | medium | API 1.18: `host::fork_agent_session`, fork a recorded native agent session into a new task in the project; trusted projects only |
|
||||
|
||||
`process:` capabilities are also derived from what the contributions start: a
|
||||
language's `language-servers` and `debugger` commands and a run detector's
|
||||
@@ -2046,23 +2044,6 @@ so the plugin should tell the user to run the action once interactively. Plain H
|
||||
to other hosts never goes through this flow: declare `net.http:<host>`. A
|
||||
manifest using `net:ask` declares `engines.openidea = "^1.5"`.
|
||||
|
||||
A setting-derived grant, `net:setting:<key>` (API 1.18), names a `string` setting of
|
||||
the plugin's own schema instead of a host; `net.http:setting:<key>` is the same
|
||||
over plain HTTP. The key is checked at install like the other manifest checks, and
|
||||
the manifest declares `engines.openidea = "^1.18"`. When the user applies the
|
||||
setting's value in Settings, a dialog names the plugin, the setting and the host —
|
||||
which may be a bare host or a URL — and states plainly that a `net.http:` connection
|
||||
is unencrypted. **Deny is the default**: only an explicit approval materializes the
|
||||
host, which then behaves exactly like a `net:<host>` (or `net.http:<host>`) grant —
|
||||
all ports, no subdomains, `*` refused, redirects unchanged. A value that reaches the
|
||||
plugin any other way (a hand-edited settings file, a project settings file, a value
|
||||
written by the plugin itself) is not approved: the plugin's permissions show the host
|
||||
as pending with an **Approve** action. Changing the setting replaces the approval only
|
||||
after the user confirms it; clearing the setting removes it. The approved hosts are
|
||||
listed next to the `net:ask` ones and revocable. Unattended calls to a pending or
|
||||
revoked host return `denied` without a dialog, like `net:ask`; on remote hosts the
|
||||
approval is kept for the session only.
|
||||
|
||||
A host answer covers all ports of that host, like `net:<host>`, and never
|
||||
covers subdomains or wildcard patterns. IDNs are shown in ASCII (punycode);
|
||||
IP literals use their canonical form. Redirects are checked against the
|
||||
@@ -2362,8 +2343,8 @@ argument, JSON text:
|
||||
|
||||
`host::start_run` still starts only the plugin's own configurations. To launch
|
||||
the user's configuration with the plugin's Java agent, bind the agent to an
|
||||
executor (_Java agents_): **Run '`<name>`' with `<title>`** and **Debug '`<name>`'
|
||||
with `<title>`** then appear in this menu for Application, Spring Boot and JAR
|
||||
executor (_Java agents_): **Run '<name>' with <title>** and **Debug '<name>'
|
||||
with <title>** then appear in this menu for Application, Spring Boot and JAR
|
||||
Application configurations, and go through the normal launch (build,
|
||||
classpath, JDK, debugger, Stop).
|
||||
|
||||
@@ -2891,11 +2872,11 @@ jdk = "jetbrains" # optional: only those VM options on
|
||||
shortened command line moves only the classpath into its argument file.
|
||||
- **Executors** (API 1.18). With `executor = "<title>"` (1–40 characters) the
|
||||
agent no longer loads into every launch. The plugin gets an executor beside
|
||||
Run and Debug instead, as IDEA's "Run with JRebel" or "Profile": **Run '`<name>`'
|
||||
with `<title>`** and **Debug '`<name>`' with `<title>`** in the run widget's ⋮ menu,
|
||||
Run and Debug instead, as IDEA's "Run with JRebel" or "Profile": **Run '<name>'
|
||||
with <title>** and **Debug '<name>' with <title>** in the run widget's ⋮ menu,
|
||||
the gutter's ▶ menu, the context menus' run entries and the Services context
|
||||
menu of those configurations, plus the actions **Run with `<title>`** and
|
||||
**Debug with `<title>`** (Find Action, Keymap). Only launches through them get
|
||||
menu of those configurations, plus the actions **Run with <title>** and
|
||||
**Debug with <title>** (Find Action, Keymap). Only launches through them get
|
||||
the agent and its `vmOptions`; the grant and jar pin are the same. Without
|
||||
`java.agent` the IDE says so instead of launching, and a configuration on a
|
||||
run target is refused the same way.
|
||||
@@ -3776,7 +3757,7 @@ no generic env-forwarding flags are added. Container env is forwarded only if
|
||||
the wrapper's own conventions allow it.
|
||||
|
||||
Registration never changes a selection. The first registration prompts the
|
||||
project's windows: “Use `<name>` for running PHP / Node / Composer in this project?”
|
||||
project's windows: “Use <name> for running PHP / Node / Composer in this project?”
|
||||
with **Use** / **Not now**. The first answer is remembered on the host per
|
||||
project + plugin + target id. Use sets the project's default run target and its
|
||||
PHP and Node run-target choices; Not now leaves settings alone. Interpreters
|
||||
|
||||
@@ -252,52 +252,6 @@ pub async fn plugin_revoke_net_host(state: State<'_, AppState>, id: String, host
|
||||
blocking(move || plugins.revoke_net_host(&id, &host)).await
|
||||
}
|
||||
|
||||
/// The host a `net:setting:` grant derives from `value` (a bare host or a
|
||||
/// URL), validated with the manifest host rules; an error refuses the value.
|
||||
#[desktop_command(trust = always)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn plugin_net_setting_host(
|
||||
state: State<'_, AppState>,
|
||||
id: String,
|
||||
setting: String,
|
||||
value: String,
|
||||
) -> IdeResult<String> {
|
||||
let plugins = state.plugins.clone();
|
||||
blocking(move || plugins.net_setting_host(&id, &setting, &value)).await
|
||||
}
|
||||
|
||||
/// Approves `host` for the plugin's `net:setting:<key>` grant (applied in
|
||||
/// Settings, or the pending row); refused when the setting no longer holds it.
|
||||
#[desktop_command(trust = outside_restricted)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn plugin_approve_net_setting(
|
||||
state: State<'_, AppState>,
|
||||
id: String,
|
||||
setting: String,
|
||||
http: bool,
|
||||
host: String,
|
||||
) -> IdeResult<PluginInfo> {
|
||||
let plugins = state.plugins.clone();
|
||||
blocking(move || plugins.approve_net_setting(&id, &setting, http, &host)).await
|
||||
}
|
||||
|
||||
/// Drops the approved host of a `net:setting:<key>` grant (revoked, or the
|
||||
/// setting's value cleared).
|
||||
#[desktop_command(trust = outside_restricted)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn plugin_forget_net_setting(
|
||||
state: State<'_, AppState>,
|
||||
id: String,
|
||||
setting: String,
|
||||
http: bool,
|
||||
) -> IdeResult<PluginInfo> {
|
||||
let plugins = state.plugins.clone();
|
||||
blocking(move || plugins.forget_net_setting(&id, &setting, http)).await
|
||||
}
|
||||
|
||||
/// Links a development plugin folder (`openidea-plugin link` does the same from a terminal).
|
||||
#[desktop_command(trust = trusted)]
|
||||
#[tauri::command]
|
||||
@@ -696,10 +650,8 @@ pub fn plugin_set_theme_frame(state: State<'_, AppState>, color: Option<String>)
|
||||
|
||||
ide_command::desktop_domain!(
|
||||
plugin_activation_event,
|
||||
plugin_approve_net_setting,
|
||||
plugin_assets,
|
||||
plugin_catalog,
|
||||
plugin_forget_net_setting,
|
||||
plugin_grant,
|
||||
plugin_install_dir,
|
||||
plugin_installed_intellij_themes,
|
||||
@@ -709,7 +661,6 @@ ide_command::desktop_domain!(
|
||||
plugin_market,
|
||||
plugin_market_download,
|
||||
plugin_market_url,
|
||||
plugin_net_setting_host,
|
||||
plugin_preview_install,
|
||||
plugin_read_intellij_theme,
|
||||
plugin_reload,
|
||||
|
||||
@@ -849,7 +849,6 @@ mod tests {
|
||||
"window.toggleFullScreen",
|
||||
"view.toggleTheme",
|
||||
"editor.toggleZen",
|
||||
"view.toggleZenMode",
|
||||
"view.toggleToolbar",
|
||||
"view.toggleToolWindowBars",
|
||||
"view.toggleStatusBar",
|
||||
|
||||
@@ -1529,7 +1529,6 @@ mod tests {
|
||||
settings: Default::default(),
|
||||
workspace: None,
|
||||
unity: None,
|
||||
unreal: None,
|
||||
})
|
||||
.unwrap())
|
||||
}
|
||||
|
||||
@@ -456,7 +456,6 @@ plugin_answer_command trusted project_host bin
|
||||
plugin_answer_commit trusted project_host bindings sync
|
||||
plugin_answer_prompt trusted project_host bindings sync
|
||||
plugin_answer_run_target trusted project_host bindings async
|
||||
plugin_approve_net_setting outside_restricted desktop bindings async
|
||||
plugin_assets always desktop bindings async
|
||||
plugin_cancel_task trusted project_host bindings sync
|
||||
plugin_catalog always desktop bindings async
|
||||
@@ -471,7 +470,6 @@ plugin_decoration_sets trusted project_host bin
|
||||
plugin_endpoints trusted project_host bindings async
|
||||
plugin_event_kinds trusted project_host bindings async
|
||||
plugin_finish_operation trusted project_host bindings sync
|
||||
plugin_forget_net_setting outside_restricted desktop bindings async
|
||||
plugin_formatters trusted project_host bindings sync
|
||||
plugin_grant outside_restricted desktop bindings async
|
||||
plugin_install_dir outside_restricted desktop bindings async
|
||||
@@ -489,7 +487,6 @@ plugin_navigation_goto trusted project_host bin
|
||||
plugin_navigation_index trusted project_host bindings async
|
||||
plugin_navigation_invalidate trusted project_host bindings sync
|
||||
plugin_navigation_markers trusted project_host bindings async
|
||||
plugin_net_setting_host always desktop bindings async
|
||||
plugin_parse_test_results trusted project_host bindings async
|
||||
plugin_post_events trusted project_host bindings sync
|
||||
plugin_prepare_debug_run trusted project_host bindings async
|
||||
@@ -755,7 +752,6 @@ vcs_has_commit always project_host bin
|
||||
vcs_has_hook always project_host bindings async
|
||||
vcs_ignore_blame_revision trusted project_host bindings async
|
||||
vcs_ignored_files always project_host bindings async
|
||||
vcs_image_at always project_host bindings async
|
||||
vcs_init always project_host bindings async
|
||||
vcs_inspect_push trusted project_host bindings async
|
||||
vcs_invalidate_log_signatures always project_host bindings async
|
||||
|
||||
@@ -1226,11 +1226,6 @@ export const commands = {
|
||||
*/
|
||||
pluginAnswerPrompt: (promptId: string, answer: string[] | null) => __TAURI_INVOKE<boolean>("plugin_answer_prompt", { promptId, answer }),
|
||||
pluginAnswerRunTarget: (id: string, useTarget: boolean) => typedError<Settings_Serialize, IdeError>(__TAURI_INVOKE("plugin_answer_run_target", { id, useTarget })),
|
||||
/**
|
||||
* Approves `host` for the plugin's `net:setting:<key>` grant (applied in
|
||||
* Settings, or the pending row); refused when the setting no longer holds it.
|
||||
*/
|
||||
pluginApproveNetSetting: (id: string, setting: string, http: boolean, host: string) => typedError<PluginInfo, IdeError>(__TAURI_INVOKE("plugin_approve_net_setting", { id, setting, http, host })),
|
||||
/** Validated assets of a plugin whose id starts with `prefix` (icon theme mapping and SVGs). */
|
||||
pluginAssets: (pluginId: string, prefix: string) => typedError<([string, string])[], IdeError>(__TAURI_INVOKE("plugin_assets", { pluginId, prefix })),
|
||||
/** Cancels a plugin task (`taskStarted` with `cancellable`). */
|
||||
@@ -1263,11 +1258,6 @@ export const commands = {
|
||||
pluginEventKinds: () => __TAURI_INVOKE<EventKind[]>("plugin_event_kinds"),
|
||||
/** Reports exactly one completion from the operation's launching window. */
|
||||
pluginFinishOperation: (id: string, status: number | null, stopped: boolean) => typedError<boolean, IdeError>(__TAURI_INVOKE("plugin_finish_operation", { id, status, stopped })),
|
||||
/**
|
||||
* Drops the approved host of a `net:setting:<key>` grant (revoked, or the
|
||||
* setting's value cleared).
|
||||
*/
|
||||
pluginForgetNetSetting: (id: string, setting: string, http: boolean) => typedError<PluginInfo, IdeError>(__TAURI_INVOKE("plugin_forget_net_setting", { id, setting, http })),
|
||||
pluginFormatters: () => typedError<FormatterChoice[], IdeError>(__TAURI_INVOKE("plugin_formatters")),
|
||||
/** Confirms a plugin waiting for consent (project plugins, new capabilities). */
|
||||
pluginGrant: (id: string, consent: Consent) => typedError<PluginInfo, IdeError>(__TAURI_INVOKE("plugin_grant", { id, consent })),
|
||||
@@ -1307,11 +1297,6 @@ export const commands = {
|
||||
pluginNavigationIndex: (paths: string[], request: RequestId) => typedError<null, IdeError>(__TAURI_INVOKE("plugin_navigation_index", { paths, request })),
|
||||
pluginNavigationInvalidate: (paths: string[] | null) => typedError<null, IdeError>(__TAURI_INVOKE("plugin_navigation_invalidate", { paths })),
|
||||
pluginNavigationMarkers: (paths: string[]) => typedError<FileMarkers[], IdeError>(__TAURI_INVOKE("plugin_navigation_markers", { paths })),
|
||||
/**
|
||||
* The host a `net:setting:` grant derives from `value` (a bare host or a
|
||||
* URL), validated with the manifest host rules; an error refuses the value.
|
||||
*/
|
||||
pluginNetSettingHost: (id: string, setting: string, value: string) => typedError<string, IdeError>(__TAURI_INVOKE("plugin_net_setting_host", { id, setting, value })),
|
||||
/** Parses one batch of an owned test configuration's output. */
|
||||
pluginParseTestResults: (config: string, chunk: string) => typedError<PluginTestEvent[] | null, IdeError>(__TAURI_INVOKE("plugin_parse_test_results", { config, chunk })),
|
||||
/** Workbench events from this window (only the kinds of `plugin_event_kinds`). */
|
||||
@@ -1463,7 +1448,6 @@ export const commands = {
|
||||
settings: Settings_Serialize,
|
||||
workspace?: Workspace_Serialize | null,
|
||||
unity?: UnityProjectInfo | null,
|
||||
unreal?: UnrealProjectInfo | null,
|
||||
} | null>("project_current"),
|
||||
/**
|
||||
* File › Rename Project…: the project's display name (title bar, recent
|
||||
@@ -2147,8 +2131,6 @@ export const commands = {
|
||||
vcsHasHook: (repo: string | null, name: string) => typedError<boolean, IdeError>(__TAURI_INVOKE("vcs_has_hook", { repo, name })),
|
||||
vcsIgnoreBlameRevision: (path: string, commit: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_ignore_blame_revision", { path, commit })),
|
||||
vcsIgnoredFiles: () => typedError<FileStatus[], IdeError>(__TAURI_INVOKE("vcs_ignored_files")),
|
||||
/** An image at the selected Git revision or index stage as a data URL, absent if the path is missing. */
|
||||
vcsImageAt: (path: string, rev: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("vcs_image_at", { path, rev })),
|
||||
/**
|
||||
* `git init` in `dir` (VCS › Create Git Repository…): with the git of the window's project when
|
||||
* it is trusted, the default one in a window without a project.
|
||||
@@ -9158,12 +9140,6 @@ export type LanguageCodeStyle_Deserialize = {
|
||||
keywordCase?: string | null,
|
||||
/** SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`. */
|
||||
identifierCase?: string | null,
|
||||
/** JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`. */
|
||||
semicolons?: string | null,
|
||||
/** JavaScript / TypeScript › Punctuation › Quotes: `auto` | `single` | `double`. */
|
||||
quotes?: string | null,
|
||||
/** JavaScript / TypeScript › Spaces, by tsserver format option (`insertSpaceAfterCommaDelimiter`). */
|
||||
spaces?: { [key in string]: boolean },
|
||||
};
|
||||
|
||||
/** Editor › Code Style › <Language> › Tabs and Indents (unset fields inherit). */
|
||||
@@ -9188,12 +9164,6 @@ export type LanguageCodeStyle_Serialize = {
|
||||
keywordCase?: string | null,
|
||||
/** SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`. */
|
||||
identifierCase?: string | null,
|
||||
/** JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`. */
|
||||
semicolons?: string | null,
|
||||
/** JavaScript / TypeScript › Punctuation › Quotes: `auto` | `single` | `double`. */
|
||||
quotes?: string | null,
|
||||
/** JavaScript / TypeScript › Spaces, by tsserver format option (`insertSpaceAfterCommaDelimiter`). */
|
||||
spaces?: { [key in string]: boolean },
|
||||
};
|
||||
|
||||
/** Language identifier, e.g. `rust`, `typescript`, `kotlin`. Matches LSP `languageId`. */
|
||||
@@ -11101,8 +11071,6 @@ export type PluginInfo = {
|
||||
* none of them declared by the manifest; each can be revoked.
|
||||
*/
|
||||
netHosts: string[],
|
||||
/** Setting-derived hosts (`net:setting:`), approved in Settings, listed next to the `net:ask` ones. */
|
||||
netSettings: PluginNetSetting[],
|
||||
/** What it contributes while live (point + label). */
|
||||
contributions: ContributionInfo[],
|
||||
/** `activation` events of the manifest. */
|
||||
@@ -11159,18 +11127,6 @@ export type PluginLocation = {
|
||||
range: Range,
|
||||
};
|
||||
|
||||
/** A `net:setting:` grant's host for Settings › Plugins: the approved one while the setting holds it, else the pending one. */
|
||||
export type PluginNetSetting = {
|
||||
/** The setting key the host comes from (`server` of `net:setting:server`). */
|
||||
setting: string,
|
||||
/** Plain HTTP (`net.http:setting:`) instead of HTTPS (and loopback HTTP). */
|
||||
http: boolean,
|
||||
/** The approved host, while the setting still holds it. */
|
||||
host: string | null,
|
||||
/** The host the setting holds now when it is not the approved one. */
|
||||
pending: string | null,
|
||||
};
|
||||
|
||||
/** A line a view's `process` body printed. */
|
||||
export type PluginOutputLine = {
|
||||
stderr: boolean,
|
||||
@@ -11627,7 +11583,6 @@ export type ProjectInfo_Deserialize = {
|
||||
settings: Settings_Deserialize,
|
||||
workspace?: Workspace_Deserialize | null,
|
||||
unity?: UnityProjectInfo | null,
|
||||
unreal?: UnrealProjectInfo | null,
|
||||
};
|
||||
|
||||
export type ProjectInfo_Serialize = {
|
||||
@@ -11639,7 +11594,6 @@ export type ProjectInfo_Serialize = {
|
||||
settings: Settings_Serialize,
|
||||
workspace?: Workspace_Serialize | null,
|
||||
unity?: UnityProjectInfo | null,
|
||||
unreal?: UnrealProjectInfo | null,
|
||||
};
|
||||
|
||||
/** An interpreter another project uses: the project root and the SDK itself. */
|
||||
@@ -14310,11 +14264,6 @@ export type TypeScriptSettings = {
|
||||
* vtsls default 3072 dies in a GC death spiral), else unset (vtsls default).
|
||||
*/
|
||||
tsserverMaxMemory?: number,
|
||||
/**
|
||||
* Problems › TypeScript project errors: the project's own `tsc --watch` per root
|
||||
* `tsconfig.json` reports the errors of files that are not open.
|
||||
*/
|
||||
watchProblems?: boolean,
|
||||
};
|
||||
|
||||
/** A misspelt word. */
|
||||
@@ -14363,22 +14312,6 @@ export type UnityProjectInfo = {
|
||||
projects: string[],
|
||||
};
|
||||
|
||||
/** A located engine, shown so a project without run configurations says why. */
|
||||
export type UnrealEngine = {
|
||||
/** `5.8` for a launcher install, or the registry key a source build registered under. */
|
||||
id: string,
|
||||
/** Absolute engine root. */
|
||||
root: string,
|
||||
};
|
||||
|
||||
export type 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.
|
||||
*/
|
||||
engine: UnrealEngine | null,
|
||||
};
|
||||
|
||||
/** A requirement the project's interpreter does not satisfy. */
|
||||
export type UnsatisfiedRequirement = {
|
||||
dependency: ManifestDependency,
|
||||
|
||||
@@ -34,7 +34,7 @@ import type { LanguageDescription } from "@codemirror/language";
|
||||
import type { HunkKind } from "@/bindings";
|
||||
import type { LineEnding } from "@/platform/ipc";
|
||||
import { create } from "zustand";
|
||||
import { maybeEditorService, type EditorInput, type MenuGroupContext } from "@/workbench/contributions";
|
||||
import { maybeEditorService, type EditorInput } from "@/workbench/contributions";
|
||||
import { isSameOrInside } from "@/platform/paths";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { rootOfPath } from "@/platform/projectRoots";
|
||||
@@ -254,25 +254,6 @@ export function editorsFor(path: string): TextEditorHandle[] {
|
||||
return [...useEditorRegistry.getState().editors].filter((e) => e.ctx.path === path);
|
||||
}
|
||||
|
||||
/**
|
||||
* While a cell editor of a custom editor (a notebook) has focus, it stands in for the
|
||||
* active editor's view: the notebook publishes the editor context keys for it and
|
||||
* editor actions resolve to it, like a text tab's view. The owner keeps this current
|
||||
* on focus changes (see `_setFocusedCellEditor`); editor/core re-reads it whenever it
|
||||
* republishes contexts, so actions never fall back to the last text tab.
|
||||
*/
|
||||
let focusedCell: EditorView | null = null;
|
||||
|
||||
/** The focused cell editor standing in for the active editor's view, if any. */
|
||||
export function focusedCellEditor(): EditorView | null {
|
||||
return focusedCell;
|
||||
}
|
||||
|
||||
/** Published by the custom editor owning the cell editors (a notebook); `null` once none has focus. */
|
||||
export function _setFocusedCellEditor(view: EditorView | null) {
|
||||
focusedCell = view;
|
||||
}
|
||||
|
||||
// --- called by editor/core only ---------------------------------------------
|
||||
|
||||
export function _setActiveEditor(handle: TextEditorHandle | null) {
|
||||
@@ -1017,37 +998,6 @@ export function _provideCodePreview(provider: typeof codePreviewProvider) {
|
||||
codePreviewProvider = provider;
|
||||
}
|
||||
|
||||
/** A row of the Copy Path/Reference… chooser. */
|
||||
export interface CopyPathRow {
|
||||
/** The action whose shortcut the row shows. */
|
||||
id: string;
|
||||
/** English label, translated by the chooser. */
|
||||
label: string;
|
||||
/** The copied text; a row without one is left out. */
|
||||
preview: string | null;
|
||||
run: () => void;
|
||||
}
|
||||
|
||||
type CopyPathChooser = (
|
||||
anchor: { x: number; y: number } | "center",
|
||||
rows: readonly CopyPathRow[],
|
||||
ctx: MenuGroupContext,
|
||||
) => void;
|
||||
let copyPathChooser: CopyPathChooser | null = null;
|
||||
|
||||
/**
|
||||
* The editor's Copy Path/Reference… chooser for files outside an editor (the Project view's
|
||||
* selection): `rows`, then the rows contributed to the `copyPath` menu for `ctx`, with previews.
|
||||
*/
|
||||
export function openCopyPathChooser(...args: Parameters<CopyPathChooser>): void {
|
||||
copyPathChooser?.(...args);
|
||||
}
|
||||
|
||||
/** @internal editor/core only. */
|
||||
export function _provideCopyPathChooser(open: CopyPathChooser) {
|
||||
copyPathChooser = open;
|
||||
}
|
||||
|
||||
let workspaceHistory: ((id: number, redo: boolean) => Promise<void>) | null = null;
|
||||
|
||||
/** Undo/redo a refactoring through the same history used by editor commands. */
|
||||
|
||||
@@ -7,7 +7,6 @@ import { foldEffect, syntaxTree, toggleFold } from "@codemirror/language";
|
||||
import { acceptCompletion, completionStatus } from "@codemirror/autocomplete";
|
||||
import { executeAction, registerActions, type Action } from "@/platform/actions";
|
||||
import { getContext } from "@/platform/context";
|
||||
import { focusedCellEditor } from "@/editor/api";
|
||||
import { focusedSoftWrapSurface } from "@/workbench/softWrap";
|
||||
import { resetSurfaceFontZoom, stepFocusedSurfaceFontZoom, stepSurfaceFontZoomIn } from "@/workbench/contributions";
|
||||
import { editorController, useGotoLine, useTabs } from "./controller";
|
||||
@@ -20,7 +19,6 @@ import {
|
||||
deleteLine,
|
||||
duplicateEntireLines,
|
||||
duplicateLineOrSelection,
|
||||
inDifferentHumpsMode,
|
||||
joinLines,
|
||||
moveStatementDown,
|
||||
moveStatementUp,
|
||||
@@ -70,8 +68,7 @@ import { customRegions } from "./cm/regions";
|
||||
import { toggleRenderedViewAtCaret } from "./cm/renderedDocs";
|
||||
import { enclosingHeaders } from "./cm/stickyScroll";
|
||||
import { moveElementLeft, moveElementRight } from "./cm/moveElement";
|
||||
import { caretAnchor, openPopup, updatePopup, useLspPopup } from "@/editor/lsp/popupStore";
|
||||
import { copyPathPopup } from "./copyPathChooser";
|
||||
import { caretAnchor, openPopup, updatePopup, useLspPopup, type LspPopup } from "@/editor/lsp/popupStore";
|
||||
import {
|
||||
cursorCodeBlockEnd,
|
||||
cursorCodeBlockStart,
|
||||
@@ -112,7 +109,7 @@ import {
|
||||
import { useProject } from "@/platform/project";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { menuGroupItems, notifications } from "@/workbench/contributions";
|
||||
import { togglePinSelectedContent } from "@/workbench/toolwindows/content";
|
||||
import { useToolWindowLayout } from "@/workbench/toolwindows/store";
|
||||
import { toggleReadOnly } from "./fileAttributes";
|
||||
@@ -168,15 +165,8 @@ function withTextView(run: (view: EditorView) => unknown, editable: boolean) {
|
||||
};
|
||||
}
|
||||
|
||||
function withView(run: (view: EditorView, slot: EditorSlot | null) => unknown) {
|
||||
function withView(run: (view: EditorView, slot: EditorSlot) => unknown) {
|
||||
return () => {
|
||||
// While a notebook cell editor has focus it is the editor the action runs in
|
||||
// (the notebook publishes the editor context keys for it), never the last text tab.
|
||||
const cell = focusedCellEditor();
|
||||
if (cell) {
|
||||
run(cell, null);
|
||||
return;
|
||||
}
|
||||
const slot = activeSlot();
|
||||
if (!slot?.view) return;
|
||||
run(slot.view, slot);
|
||||
@@ -646,10 +636,24 @@ function pathWithLines(state: EditorState, path: string, kind: "relative" | "abs
|
||||
return `${pathToCopy(kind, path)}:${first}${last > first ? `-${last}` : ""}`;
|
||||
}
|
||||
|
||||
function copyPathReferencePopup(view: EditorView, slot: EditorSlot | null) {
|
||||
// The popup's items resolve against the open document; a notebook cell has none.
|
||||
if (!slot) return;
|
||||
function copyPathReferencePopup(view: EditorView, slot: EditorSlot) {
|
||||
const path = slot.model.path;
|
||||
const contributed = menuGroupItems("copyPath", {
|
||||
paths: [path],
|
||||
...selectedLineContext(view.state),
|
||||
}).flatMap((item) =>
|
||||
(item.kind ?? "item") === "item" && "run" in item && item.id && item.run && item.preview
|
||||
? [
|
||||
{
|
||||
id: item.id,
|
||||
label: item.verbatim ? item.label : tx(item.label),
|
||||
preview: item.preview,
|
||||
shortcut: shortcutLabel(item.id),
|
||||
run: item.run,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
);
|
||||
const flavours = [
|
||||
{ id: "project.copyAbsolutePath", label: "Absolute Path", value: pathToCopy("absolute", path) },
|
||||
{
|
||||
@@ -666,20 +670,26 @@ function copyPathReferencePopup(view: EditorView, slot: EditorSlot | null) {
|
||||
value: pathWithLines(view.state, path),
|
||||
},
|
||||
];
|
||||
const popup = copyPathPopup(
|
||||
caretAnchor(view, view.state.selection.main.head),
|
||||
flavours.map((f) => ({
|
||||
id: f.id,
|
||||
label: f.label,
|
||||
preview: f.value,
|
||||
run: () => {
|
||||
const lineNumbered =
|
||||
f.id === "editor.copyPathWithLineNumber" || f.id === "editor.copyAbsolutePathWithLineNumber";
|
||||
void executeAction(f.id, lineNumbered ? f.value : path);
|
||||
},
|
||||
})),
|
||||
{ paths: [path], ...selectedLineContext(view.state) },
|
||||
[
|
||||
const popup: Extract<LspPopup, { kind: "list" }> = {
|
||||
kind: "list",
|
||||
title: tx("Copy Path/Reference…"),
|
||||
layout: "copyPath",
|
||||
anchor: caretAnchor(view, view.state.selection.main.head),
|
||||
items: [
|
||||
...flavours
|
||||
.filter((f) => f.value !== null)
|
||||
.map((f) => ({
|
||||
id: f.id,
|
||||
label: tx(f.label),
|
||||
preview: f.value!,
|
||||
shortcut: shortcutLabel(f.id),
|
||||
run: () => {
|
||||
const lineNumbered =
|
||||
f.id === "editor.copyPathWithLineNumber" || f.id === "editor.copyAbsolutePathWithLineNumber";
|
||||
void executeAction(f.id, lineNumbered ? f.value : path);
|
||||
},
|
||||
})),
|
||||
...contributed,
|
||||
{
|
||||
id: "editor.copyReference",
|
||||
label: tx("Reference"),
|
||||
@@ -689,7 +699,7 @@ function copyPathReferencePopup(view: EditorView, slot: EditorSlot | null) {
|
||||
run: () => {},
|
||||
},
|
||||
],
|
||||
);
|
||||
};
|
||||
openPopup(popup);
|
||||
void resolveReference(view, slot)
|
||||
.then((reference) => {
|
||||
@@ -782,7 +792,7 @@ export function registerEditorActions(): () => void {
|
||||
const text = (
|
||||
id: string,
|
||||
title: string,
|
||||
run: (view: EditorView, slot: EditorSlot | null) => unknown,
|
||||
run: (view: EditorView, slot: EditorSlot) => unknown,
|
||||
extra: Partial<Action> = {},
|
||||
): Action => ({
|
||||
id,
|
||||
@@ -910,18 +920,6 @@ export function registerEditorActions(): () => void {
|
||||
category: "Editor Actions",
|
||||
keyWhen: "editorTextFocus || diffEditorFocus",
|
||||
}),
|
||||
edit(
|
||||
"code.deleteToWordStartInDifferentHumpsMode",
|
||||
'Delete to Word Start in Different "CamelHumps" Mode',
|
||||
(v) => inDifferentHumpsMode("deleteToStart", editorPrefs().smartKeys.camelHumps)(v),
|
||||
{ category: "Editor Actions", keyWhen: "editorTextFocus || diffEditorFocus" },
|
||||
),
|
||||
edit(
|
||||
"code.deleteToWordEndInDifferentHumpsMode",
|
||||
'Delete to Word End in Different "CamelHumps" Mode',
|
||||
(v) => inDifferentHumpsMode("deleteToEnd", editorPrefs().smartKeys.camelHumps)(v),
|
||||
{ category: "Editor Actions", keyWhen: "editorTextFocus || diffEditorFocus" },
|
||||
),
|
||||
edit("code.moveLineUp", "Move Line Up", (v) => moveLineUp(v)),
|
||||
edit("code.moveLineDown", "Move Line Down", (v) => moveLineDown(v)),
|
||||
edit("code.moveElementLeft", "Move Element Left", (v) => moveElementLeft(v), {
|
||||
@@ -930,38 +928,24 @@ export function registerEditorActions(): () => void {
|
||||
edit("code.moveElementRight", "Move Element Right", (v) => moveElementRight(v), {
|
||||
keywords: ["swap argument", "move parameter"],
|
||||
}),
|
||||
text("code.moveStatementUp", "Move Statement Up", (v, slot) => slot && moveStatement(v, slot, true)),
|
||||
text("code.moveStatementDown", "Move Statement Down", (v, slot) => slot && moveStatement(v, slot, false)),
|
||||
text(
|
||||
"code.extendSelection",
|
||||
"Extend Selection",
|
||||
(_v, slot) => {
|
||||
if (slot) void queueSelection(slot, extend);
|
||||
},
|
||||
{
|
||||
category: "Edit",
|
||||
},
|
||||
),
|
||||
text(
|
||||
"code.shrinkSelection",
|
||||
"Shrink Selection",
|
||||
(_v, slot) => {
|
||||
if (slot) void queueSelection(slot, shrink);
|
||||
},
|
||||
{
|
||||
category: "Edit",
|
||||
},
|
||||
),
|
||||
text("code.moveStatementUp", "Move Statement Up", (v, slot) => moveStatement(v, slot, true)),
|
||||
text("code.moveStatementDown", "Move Statement Down", (v, slot) => moveStatement(v, slot, false)),
|
||||
text("code.extendSelection", "Extend Selection", (_v, slot) => void queueSelection(slot, extend), {
|
||||
category: "Edit",
|
||||
}),
|
||||
text("code.shrinkSelection", "Shrink Selection", (_v, slot) => void queueSelection(slot, shrink), {
|
||||
category: "Edit",
|
||||
}),
|
||||
text("code.fold", "Collapse", (v) => foldAtCaret(v), { category: "Folding", keywords: ["fold"] }),
|
||||
text("code.unfold", "Expand", (v) => unfoldAtCaret(v), { category: "Folding", keywords: ["unfold"] }),
|
||||
text("code.foldToggle", "Toggle Fold", (v) => toggleFold(v), { category: "Folding" }),
|
||||
text("code.cyclicExpandWord", "Cyclic Expand Word", (v, slot) => slot && expandWord(v, slot, "backward"), {
|
||||
text("code.cyclicExpandWord", "Cyclic Expand Word", (v, slot) => expandWord(v, slot, "backward"), {
|
||||
keywords: ["hippie", "complete word", "dabbrev"],
|
||||
}),
|
||||
text(
|
||||
"code.cyclicExpandWordBackward",
|
||||
"Cyclic Expand Word (Backward)",
|
||||
(v, slot) => slot && expandWord(v, slot, "forward"),
|
||||
(v, slot) => expandWord(v, slot, "forward"),
|
||||
{
|
||||
keywords: ["hippie", "complete word", "dabbrev"],
|
||||
},
|
||||
@@ -972,7 +956,7 @@ export function registerEditorActions(): () => void {
|
||||
when: TEXT_WHEN,
|
||||
run: ({ arg }) => {
|
||||
if (typeof arg === "string") copyReference(Promise.resolve(arg));
|
||||
else withView((v, slot) => slot && copyReference(resolveReference(v, slot)))();
|
||||
else withView((v, slot) => copyReference(resolveReference(v, slot)))();
|
||||
},
|
||||
category: "Edit",
|
||||
keywords: ["fully qualified name", "fqn", "copy path"],
|
||||
@@ -999,13 +983,8 @@ export function registerEditorActions(): () => void {
|
||||
icon: "soft-wrap",
|
||||
keywords: ["word wrap", "line wrap"],
|
||||
when: "textEditorActive || softWrapSurfaceFocus",
|
||||
// Cell editors wrap always; without the cell the setting is the active text tab's.
|
||||
toggled: () =>
|
||||
focusedSoftWrapSurface()?.enabled() ??
|
||||
(focusedCellEditor() ? true : (activeSlot()?.model.softWrapOn() ?? false)),
|
||||
toggled: () => focusedSoftWrapSurface()?.enabled() ?? activeSlot()?.model.softWrapOn() ?? false,
|
||||
run: () => {
|
||||
// Don't flip the last text tab's setting while a notebook cell has focus.
|
||||
if (focusedCellEditor()) return;
|
||||
const surface = focusedSoftWrapSurface();
|
||||
if (surface) surface.toggle();
|
||||
else activeSlot()?.model.toggleSoftWrap();
|
||||
@@ -1017,12 +996,8 @@ export function registerEditorActions(): () => void {
|
||||
category: "View",
|
||||
keywords: ["render documentation comments", "javadoc", "rendered doc", "comments"],
|
||||
when: "textEditorActive",
|
||||
toggled: () => (focusedCellEditor() ? false : (activeSlot()?.model.renderedDocsOn() ?? false)),
|
||||
run: () => {
|
||||
// Notebook cells have no doc-comment rendering: leave it, don't toggle the last text tab's.
|
||||
if (focusedCellEditor()) return;
|
||||
activeSlot()?.model.toggleRenderedDocs();
|
||||
},
|
||||
toggled: () => activeSlot()?.model.renderedDocsOn() ?? false,
|
||||
run: () => activeSlot()?.model.toggleRenderedDocs(),
|
||||
},
|
||||
text("editor.toggleRenderedView", "Toggle Rendered View", (v) => toggleRenderedViewAtCaret(v), {
|
||||
category: "View",
|
||||
@@ -1030,11 +1005,11 @@ export function registerEditorActions(): () => void {
|
||||
}),
|
||||
text("code.foldAll", "Collapse All", (v) => collapseAll(v), { category: "Folding", icon: "collapse-all" }),
|
||||
text("code.unfoldAll", "Expand All", (v) => expandAll(v), { category: "Folding", icon: "expand-all" }),
|
||||
text("code.expandDocComments", "Expand Doc Comments", (v, slot) => slot && foldDocComments(v, slot, false), {
|
||||
text("code.expandDocComments", "Expand Doc Comments", (v, slot) => foldDocComments(v, slot, false), {
|
||||
category: "Folding",
|
||||
keywords: ["unfold", "documentation comments", "javadoc"],
|
||||
}),
|
||||
text("code.collapseDocComments", "Collapse Doc Comments", (v, slot) => slot && foldDocComments(v, slot, true), {
|
||||
text("code.collapseDocComments", "Collapse Doc Comments", (v, slot) => foldDocComments(v, slot, true), {
|
||||
category: "Folding",
|
||||
keywords: ["fold", "documentation comments", "javadoc"],
|
||||
}),
|
||||
@@ -1048,11 +1023,7 @@ export function registerEditorActions(): () => void {
|
||||
}),
|
||||
occurrence("code.addCaretNextOccurrence", "Add Selection for Next Occurrence", addNextOccurrence),
|
||||
occurrence("code.selectAllOccurrences", "Select All Occurrences", selectAllOccurrences),
|
||||
text(
|
||||
"code.completeStatement",
|
||||
"Complete Current Statement",
|
||||
(v, slot) => slot && completeCurrentStatement(v, slot),
|
||||
),
|
||||
text("code.completeStatement", "Complete Current Statement", (v, slot) => completeCurrentStatement(v, slot)),
|
||||
edit("code.startNewLine", "Start New Line", (v) => startNewLine(v)),
|
||||
edit("code.startNewLineBefore", "Start New Line Before Current", (v) => startNewLineBefore(v)),
|
||||
edit("code.splitLine", "Split Line", (v) => splitLine(v)),
|
||||
@@ -1112,30 +1083,6 @@ export function registerEditorActions(): () => void {
|
||||
(v) => selectParagraphBackward(v),
|
||||
{ category: "Editor Actions" },
|
||||
),
|
||||
caret(
|
||||
"editor.nextWordInDifferentHumpsMode",
|
||||
'Move Caret to Next Word in Different "CamelHumps" Mode',
|
||||
(v) => inDifferentHumpsMode("right", editorPrefs().smartKeys.camelHumps)(v),
|
||||
{ category: "Editor Actions" },
|
||||
),
|
||||
caret(
|
||||
"editor.previousWordInDifferentHumpsMode",
|
||||
'Move Caret to Previous Word in Different "CamelHumps" Mode',
|
||||
(v) => inDifferentHumpsMode("left", editorPrefs().smartKeys.camelHumps)(v),
|
||||
{ category: "Editor Actions" },
|
||||
),
|
||||
caret(
|
||||
"editor.nextWordInDifferentHumpsModeWithSelection",
|
||||
'Move Caret to Next Word in Different "CamelHumps" Mode with Selection',
|
||||
(v) => inDifferentHumpsMode("selectRight", editorPrefs().smartKeys.camelHumps)(v),
|
||||
{ category: "Editor Actions" },
|
||||
),
|
||||
caret(
|
||||
"editor.previousWordInDifferentHumpsModeWithSelection",
|
||||
'Move Caret to Previous Word in Different "CamelHumps" Mode with Selection',
|
||||
(v) => inDifferentHumpsMode("selectLeft", editorPrefs().smartKeys.camelHumps)(v),
|
||||
{ category: "Editor Actions" },
|
||||
),
|
||||
text("editor.contextInfo", "Context Info", (v) => showContextInfo(v), {
|
||||
category: "View",
|
||||
keywords: ["enclosing method", "enclosing class", "where am I"],
|
||||
@@ -1188,7 +1135,7 @@ export function registerEditorActions(): () => void {
|
||||
category: "Editor Actions",
|
||||
keywords: ["overwrite mode", "overtype"],
|
||||
toggled: () => {
|
||||
const view = focusedCellEditor() ?? activeSlot()?.view;
|
||||
const view = activeSlot()?.view;
|
||||
return view ? isOverwrite(view.state) : false;
|
||||
},
|
||||
}),
|
||||
@@ -1215,7 +1162,7 @@ export function registerEditorActions(): () => void {
|
||||
text(
|
||||
"code.fillParagraph",
|
||||
"Fill Paragraph",
|
||||
(v, slot) => slot && fillParagraph(v, hardWrapAt(slot.model.settings(), slot.model.info)),
|
||||
(v, slot) => fillParagraph(v, hardWrapAt(slot.model.settings(), slot.model.info)),
|
||||
{
|
||||
category: "Edit",
|
||||
keywords: ["wrap", "reflow", "rewrap comment"],
|
||||
@@ -1229,16 +1176,9 @@ export function registerEditorActions(): () => void {
|
||||
category: "Edit",
|
||||
keywords: ["spaces", "indentation"],
|
||||
}),
|
||||
text(
|
||||
"code.unwrap",
|
||||
"Unwrap/Remove…",
|
||||
(_v, slot) => {
|
||||
if (slot) void unwrapAtCaret(slot);
|
||||
},
|
||||
{
|
||||
keywords: ["unwrap", "remove if"],
|
||||
},
|
||||
),
|
||||
text("code.unwrap", "Unwrap/Remove…", (_v, slot) => void unwrapAtCaret(slot), {
|
||||
keywords: ["unwrap", "remove if"],
|
||||
}),
|
||||
text("code.foldSelection", "Fold Selection / Remove Region", (v) => foldSelection(v), { category: "Folding" }),
|
||||
{
|
||||
id: "editor.toggleColumnSelection",
|
||||
@@ -1247,7 +1187,7 @@ export function registerEditorActions(): () => void {
|
||||
keywords: ["block selection", "rectangular selection"],
|
||||
when: "textEditorActive",
|
||||
toggled: () => {
|
||||
const view = focusedCellEditor() ?? activeSlot()?.view;
|
||||
const view = activeSlot()?.view;
|
||||
return view ? isColumnMode(view.state) : false;
|
||||
},
|
||||
run: withView((v) => toggleColumnMode(v)),
|
||||
@@ -1325,8 +1265,7 @@ export function registerEditorActions(): () => void {
|
||||
when: "textEditorActive",
|
||||
run: () => {
|
||||
const slot = activeSlot();
|
||||
// A notebook has no document model to toggle: leave it rather than the last text tab's file.
|
||||
if (slot && !focusedCellEditor()) toggleReadOnly(slot.model);
|
||||
if (slot) toggleReadOnly(slot.model);
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -1625,7 +1564,7 @@ export function registerEditorActions(): () => void {
|
||||
when: TEXT_WHEN,
|
||||
run: ({ arg }) => {
|
||||
if (typeof arg === "string") copyEditorPath(arg);
|
||||
else withView((view, slot) => slot && copyEditorPath(pathWithLines(view.state, slot.model.path)))();
|
||||
else withView((view, slot) => copyEditorPath(pathWithLines(view.state, slot.model.path)))();
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -1635,7 +1574,7 @@ export function registerEditorActions(): () => void {
|
||||
when: TEXT_WHEN,
|
||||
run: ({ arg }) => {
|
||||
if (typeof arg === "string") copyEditorPath(arg);
|
||||
else withView((view, slot) => slot && copyEditorPath(pathWithLines(view.state, slot.model.path, "absolute")))();
|
||||
else withView((view, slot) => copyEditorPath(pathWithLines(view.state, slot.model.path, "absolute")))();
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -24,15 +24,10 @@ import {
|
||||
} from "@codemirror/language";
|
||||
import {
|
||||
copyLineDown,
|
||||
cursorGroupLeft,
|
||||
cursorGroupRight,
|
||||
deleteGroupForward,
|
||||
deleteLine as deleteDocLine,
|
||||
insertNewlineAndIndent,
|
||||
moveLineDown,
|
||||
moveLineUp,
|
||||
selectGroupLeft,
|
||||
selectGroupRight,
|
||||
} from "@codemirror/commands";
|
||||
import { SearchCursor } from "@codemirror/search";
|
||||
import { humpLeft, humpRight, wordStartLeft } from "../model/camelHumps";
|
||||
@@ -95,21 +90,6 @@ export const deleteHumpForward = deleteHump(true);
|
||||
/** ⌥⌫ / Ctrl+Backspace without CamelHumps: the whitespace before the caret and the word (or punctuation run) before it. */
|
||||
export const deleteWordBackward = deleteHump(false, false);
|
||||
|
||||
/** The word moves and deletes the editor keys run in each mode (`caretExtension`): `[without CamelHumps, with CamelHumps]`. */
|
||||
const WORD_COMMANDS = {
|
||||
left: [cursorGroupLeft, cursorHumpLeft],
|
||||
right: [cursorGroupRight, cursorHumpRight],
|
||||
selectLeft: [selectGroupLeft, selectHumpLeft],
|
||||
selectRight: [selectGroupRight, selectHumpRight],
|
||||
deleteToStart: [deleteWordBackward, deleteHumpBackward],
|
||||
deleteToEnd: [deleteGroupForward, deleteHumpForward],
|
||||
} satisfies Record<string, [Command, Command]>;
|
||||
|
||||
/** IDEA's "… in Different "CamelHumps" Mode": the word command of the mode "Use CamelHumps words" is not set to. */
|
||||
export function inDifferentHumpsMode(op: keyof typeof WORD_COMMANDS, camelHumps: boolean): Command {
|
||||
return WORD_COMMANDS[op][camelHumps ? 0 : 1];
|
||||
}
|
||||
|
||||
// --- lines / selections -------------------------------------------------------
|
||||
|
||||
/**
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
deleteWordBackward,
|
||||
duplicateEntireLines,
|
||||
duplicateLineOrSelection,
|
||||
inDifferentHumpsMode,
|
||||
moveStatementDown,
|
||||
moveStatementUp,
|
||||
nextOccurrence,
|
||||
@@ -229,57 +228,6 @@ describe("Delete to Word Start", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('in Different "CamelHumps" Mode', () => {
|
||||
function run(text: string, op: Parameters<typeof inDifferentHumpsMode>[0], camelHumps: boolean, times = 1) {
|
||||
const v = make(text);
|
||||
for (let i = 0; i < times; i++) inDifferentHumpsMode(op, camelHumps)(v);
|
||||
return show(v);
|
||||
}
|
||||
|
||||
it("moves by humps while the setting is off", () => {
|
||||
expect(run("|parseHTMLDocument x", "right", false)).toBe("parse|HTMLDocument x");
|
||||
expect(run("|parseHTMLDocument x", "right", false, 2)).toBe("parseHTML|Document x");
|
||||
expect(run("x parseHTMLDocument|", "left", false)).toBe("x parseHTML|Document");
|
||||
expect(run("|snake_case_name", "right", false)).toBe("snake_|case_name");
|
||||
});
|
||||
|
||||
it("moves by whole words while the setting is on", () => {
|
||||
expect(run("|parseHTMLDocument x", "right", true)).toBe("parseHTMLDocument| x");
|
||||
expect(run("x parseHTMLDocument|", "left", true)).toBe("x |parseHTMLDocument");
|
||||
});
|
||||
|
||||
it("extends the selection from its anchor in the with Selection variants", () => {
|
||||
expect(run("|fooBarBaz", "selectRight", false, 2)).toBe("[fooBar]Baz");
|
||||
expect(run("fooBarBaz|", "selectLeft", false)).toBe("fooBar[Baz]");
|
||||
expect(run("|fooBar baz", "selectRight", true)).toBe("[fooBar] baz");
|
||||
});
|
||||
|
||||
it("moves every caret, and leaves a selection at its edge without extending", () => {
|
||||
expect(run("|fooBar\n|bazQux", "right", false)).toBe("foo|Bar\nbaz|Qux");
|
||||
expect(run("[fooBar]Baz", "right", false)).toBe("fooBar|Baz");
|
||||
expect(run("foo[BarBaz]", "left", false)).toBe("foo|BarBaz");
|
||||
});
|
||||
|
||||
it("deletes to the word start or end of the other mode", () => {
|
||||
expect(run("a.fooBar|", "deleteToStart", false)).toBe("a.foo|");
|
||||
expect(run("a.fooBar|", "deleteToStart", true)).toBe("a.|");
|
||||
expect(run("|fooBar.b", "deleteToEnd", false)).toBe("|Bar.b");
|
||||
expect(run("|fooBar.b", "deleteToEnd", true)).toBe("|.b");
|
||||
expect(run("foo [BarBaz] qux", "deleteToEnd", false)).toBe("foo | qux");
|
||||
expect(run("foo [BarBaz] qux", "deleteToEnd", true)).toBe("foo | qux");
|
||||
expect(run("aBc|\nxYz|", "deleteToStart", false)).toBe("a|\nx|");
|
||||
});
|
||||
|
||||
it("does not delete in a read-only editor", () => {
|
||||
for (const camelHumps of [false, true]) {
|
||||
const v = make("foo|Bar", EditorState.readOnly.of(true));
|
||||
expect(inDifferentHumpsMode("deleteToStart", camelHumps)(v)).toBe(false);
|
||||
expect(inDifferentHumpsMode("deleteToEnd", camelHumps)(v)).toBe(false);
|
||||
expect(show(v)).toBe("foo|Bar");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("paste reformatting", () => {
|
||||
/** One unit deeper after a line ending in `{`. */
|
||||
const braceIndent = indentService.of((cx, pos) => {
|
||||
|
||||
@@ -20,7 +20,6 @@ import {
|
||||
_provideNavigationHistory,
|
||||
_provideOpenEditorPaths,
|
||||
_setActiveEditor,
|
||||
focusedCellEditor,
|
||||
shownLine,
|
||||
type NavigationLocation,
|
||||
} from "@/editor/api";
|
||||
@@ -1117,9 +1116,6 @@ export class EditorController implements SlotHost {
|
||||
const slot = this.activeSlot;
|
||||
const meta = slot?.model.getMeta();
|
||||
const s = useTabs.getState();
|
||||
// A focused notebook cell editor stands in for the active text editor (the notebook
|
||||
// publishes the editor context keys for it): republishing on tab churn keeps them on.
|
||||
const cell = focusedCellEditor();
|
||||
setContext("editorPath", slot?.model.path ?? null);
|
||||
setContext("editorLangId", meta?.language ?? null);
|
||||
setContext("editorReadOnly", !!meta?.readOnly);
|
||||
@@ -1129,8 +1125,8 @@ export class EditorController implements SlotHost {
|
||||
Object.values(s.panes).some((p) => p.tabs.length > 0),
|
||||
);
|
||||
setContext("editorSplit", paneIds(s).length > 1);
|
||||
setContext("editorTextFocus", cell ? cell.hasFocus : !!slot?.view?.hasFocus);
|
||||
setContext("textEditorActive", !!slot || !!cell);
|
||||
setContext("editorTextFocus", !!slot?.view?.hasFocus);
|
||||
setContext("textEditorActive", !!slot);
|
||||
}
|
||||
|
||||
// --- navigation history --------------------------------------------------------------
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
/** The Copy Path/Reference… chooser: each way to copy, with a preview of the text it copies. */
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { menuGroupItems, type MenuGroupContext } from "@/workbench/contributions";
|
||||
import { openPopup, type ListPopupItem, type LspPopup, type PopupPoint } from "@/editor/lsp/popupStore";
|
||||
import type { CopyPathRow } from "@/editor/api";
|
||||
|
||||
/** The chooser's popup: `rows`, then the rows contributed to the `copyPath` menu for `ctx`. */
|
||||
export function copyPathPopup(
|
||||
anchor: PopupPoint | "center",
|
||||
rows: readonly CopyPathRow[],
|
||||
ctx: MenuGroupContext,
|
||||
trailing: readonly ListPopupItem[] = [],
|
||||
): Extract<LspPopup, { kind: "list" }> {
|
||||
const contributed = menuGroupItems("copyPath", ctx).flatMap((item) =>
|
||||
(item.kind ?? "item") === "item" && "run" in item && item.id && item.run && item.preview
|
||||
? [
|
||||
{
|
||||
id: item.id,
|
||||
label: item.verbatim ? item.label : tx(item.label),
|
||||
preview: item.preview,
|
||||
shortcut: shortcutLabel(item.id),
|
||||
run: item.run,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
);
|
||||
return {
|
||||
kind: "list",
|
||||
title: tx("Copy Path/Reference…"),
|
||||
layout: "copyPath",
|
||||
anchor,
|
||||
items: [
|
||||
...rows.flatMap((row) =>
|
||||
row.preview === null
|
||||
? []
|
||||
: [{ id: row.id, label: tx(row.label), preview: row.preview, shortcut: shortcutLabel(row.id), run: row.run }],
|
||||
),
|
||||
...contributed,
|
||||
...trailing,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/** Opens the chooser for files outside an editor (`openCopyPathChooser` of `@/editor/api`). */
|
||||
export function openCopyPathChooser(
|
||||
anchor: PopupPoint | "center",
|
||||
rows: readonly CopyPathRow[],
|
||||
ctx: MenuGroupContext,
|
||||
): void {
|
||||
openPopup(copyPathPopup(anchor, rows, ctx));
|
||||
}
|
||||
@@ -1,223 +0,0 @@
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { executeAction, registerActions } from "@/platform/actions";
|
||||
import { evaluateWhen, getContext, useContextKeys } from "@/platform/context";
|
||||
import { installKeyboardDispatcher } from "@/platform/keymap";
|
||||
import { _setFocusedCellEditor } from "@/editor/api";
|
||||
import { TEXT_WHEN, registerEditorActions } from "./actions";
|
||||
import { editorController, useEditorStatus, useTabs } from "./controller";
|
||||
import { initialTabsState } from "./model/tabs";
|
||||
import { columnModeField, isColumnMode } from "./cm/columnMode";
|
||||
|
||||
const toggleReadOnlyMock = vi.hoisted(() => vi.fn());
|
||||
vi.mock("./fileAttributes", async (original) => ({
|
||||
...(await original<typeof import("./fileAttributes")>()),
|
||||
toggleReadOnly: toggleReadOnlyMock,
|
||||
}));
|
||||
|
||||
const ctrl = editorController();
|
||||
let disposeActions: () => void;
|
||||
beforeAll(() => {
|
||||
disposeActions = registerEditorActions();
|
||||
ctrl.start();
|
||||
});
|
||||
afterAll(() => {
|
||||
ctrl.stop();
|
||||
disposeActions();
|
||||
});
|
||||
afterEach(() => {
|
||||
useTabs.setState(initialTabsState(), true);
|
||||
useEditorStatus.setState({ status: null });
|
||||
useContextKeys.setState({}, true);
|
||||
_setFocusedCellEditor(null);
|
||||
toggleReadOnlyMock.mockClear();
|
||||
});
|
||||
|
||||
/** A bare editor standing in for a focused notebook cell (the fact CellEditor publishes). */
|
||||
function focusedCell(doc = "x = 1\n"): { view: EditorView; clear: () => void } {
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
// `columnModeField`: what a cell editor carries through its own extension list.
|
||||
const view = new EditorView({ doc, parent: host, extensions: columnModeField });
|
||||
view.focus();
|
||||
if (!view.hasFocus) throw new Error("the jsdom view did not take focus");
|
||||
_setFocusedCellEditor(view);
|
||||
return { view, clear: () => _setFocusedCellEditor(null) };
|
||||
}
|
||||
|
||||
function disposeView(cell: { view: EditorView }): void {
|
||||
cell.view.destroy();
|
||||
cell.view.dom.remove();
|
||||
}
|
||||
|
||||
describe("editor context keys with a focused notebook cell", () => {
|
||||
it("keeps the keys on while a cell editor has focus, with no text editor open", () => {
|
||||
const cell = focusedCell();
|
||||
try {
|
||||
ctrl.publishContext();
|
||||
expect(getContext().textEditorActive).toBe(true);
|
||||
expect(getContext().editorTextFocus).toBe(true);
|
||||
// Republishing (tab churn, pane focus) must not drop the keys.
|
||||
ctrl.publishContext();
|
||||
expect(getContext().textEditorActive).toBe(true);
|
||||
expect(getContext().editorTextFocus).toBe(true);
|
||||
} finally {
|
||||
cell.clear();
|
||||
disposeView(cell);
|
||||
}
|
||||
});
|
||||
|
||||
it("lets a focused cell editor win over the mounted but unfocused text editor", async () => {
|
||||
await ctrl.openFile("/p/a.ts", { focus: false });
|
||||
const slot = ctrl.activeSlot!;
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
try {
|
||||
const textView = slot.mount(host);
|
||||
ctrl.onMounted(slot);
|
||||
const cell = focusedCell();
|
||||
ctrl.publishContext();
|
||||
expect(getContext().editorTextFocus).toBe(true);
|
||||
expect(textView.hasFocus).toBe(false);
|
||||
cell.clear();
|
||||
disposeView(cell);
|
||||
} finally {
|
||||
host.remove();
|
||||
}
|
||||
});
|
||||
|
||||
it("drops the keys once no cell editor has focus", () => {
|
||||
const cell = focusedCell();
|
||||
try {
|
||||
ctrl.publishContext();
|
||||
expect(getContext().textEditorActive).toBe(true);
|
||||
cell.clear();
|
||||
ctrl.publishContext();
|
||||
expect(getContext().textEditorActive).toBe(false);
|
||||
expect(getContext().editorTextFocus).toBe(false);
|
||||
} finally {
|
||||
disposeView(cell);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps a text tab's own keys when no cell editor is focused", async () => {
|
||||
await ctrl.openFile("/p/a.ts", { focus: false });
|
||||
const slot = ctrl.activeSlot!;
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
try {
|
||||
const view = slot.mount(host);
|
||||
ctrl.onMounted(slot);
|
||||
view.focus();
|
||||
ctrl.publishContext();
|
||||
expect(getContext().textEditorActive).toBe(true);
|
||||
expect(getContext().editorTextFocus).toBe(true);
|
||||
} finally {
|
||||
host.remove();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("editor actions in a focused notebook cell", () => {
|
||||
it("run in the focused cell editor, not the last text tab", async () => {
|
||||
await ctrl.openFile("/p/a.ts", { focus: false });
|
||||
const slot = ctrl.activeSlot!;
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
try {
|
||||
const textView = slot.mount(host);
|
||||
ctrl.onMounted(slot);
|
||||
const cell = focusedCell();
|
||||
ctrl.publishContext();
|
||||
await executeAction("editor.toggleColumnSelection");
|
||||
expect(isColumnMode(cell.view.state)).toBe(true);
|
||||
expect(isColumnMode(textView.state)).toBe(false);
|
||||
cell.clear();
|
||||
disposeView(cell);
|
||||
} finally {
|
||||
host.remove();
|
||||
}
|
||||
});
|
||||
|
||||
it("do not toggle the last text tab's read-only attribute", async () => {
|
||||
await ctrl.openFile("/p/a.ts", { focus: false });
|
||||
const slot = ctrl.activeSlot!;
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
try {
|
||||
slot.mount(host);
|
||||
ctrl.onMounted(slot);
|
||||
const cell = focusedCell();
|
||||
await executeAction("file.toggleReadOnly");
|
||||
expect(toggleReadOnlyMock).not.toHaveBeenCalled();
|
||||
// Without a focused cell the text editor is toggled, as before.
|
||||
cell.clear();
|
||||
ctrl.publishContext();
|
||||
await executeAction("file.toggleReadOnly");
|
||||
expect(toggleReadOnlyMock).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
host.remove();
|
||||
}
|
||||
});
|
||||
|
||||
it("give the keyboard to the cell: ⌥⌘L reaches an editor action there", () => {
|
||||
const cell = focusedCell();
|
||||
ctrl.publishContext();
|
||||
const reformat = vi.fn();
|
||||
const disposeStub = registerActions([
|
||||
{ id: "code.reformat", title: "Reformat Code", category: "Code", when: TEXT_WHEN, run: reformat },
|
||||
]);
|
||||
const uninstall = installKeyboardDispatcher(window);
|
||||
try {
|
||||
const event = new KeyboardEvent("keydown", {
|
||||
key: "l",
|
||||
code: "KeyL",
|
||||
altKey: true,
|
||||
metaKey: true,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
});
|
||||
cell.view.contentDOM.dispatchEvent(event);
|
||||
expect(reformat).toHaveBeenCalledOnce();
|
||||
expect(event.defaultPrevented).toBe(true);
|
||||
} finally {
|
||||
uninstall();
|
||||
disposeStub();
|
||||
cell.clear();
|
||||
disposeView(cell);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Copy Path with a notebook tab", () => {
|
||||
it("resolves the notebook tab's path while a cell editor has focus", () => {
|
||||
const paneId = useTabs.getState().activePane;
|
||||
useTabs.setState((s) => ({
|
||||
...s,
|
||||
panes: {
|
||||
...s.panes,
|
||||
[paneId]: {
|
||||
...s.panes[paneId]!,
|
||||
tabs: [
|
||||
{
|
||||
id: "nb-1",
|
||||
input: { kind: "notebook", key: "notebook:/p/a.ipynb", path: "/p/a.ipynb" },
|
||||
preview: false,
|
||||
pinned: false,
|
||||
},
|
||||
],
|
||||
active: "nb-1",
|
||||
mru: ["nb-1"],
|
||||
},
|
||||
},
|
||||
}));
|
||||
const cell = focusedCell();
|
||||
try {
|
||||
ctrl.publishContext();
|
||||
expect(ctrl.activePath()).toBe("/p/a.ipynb");
|
||||
expect(evaluateWhen("textEditorActive", getContext())).toBe(true);
|
||||
} finally {
|
||||
cell.clear();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -10,8 +10,7 @@ import {
|
||||
registerOverlay,
|
||||
registerStatusItem,
|
||||
} from "@/workbench/contributions";
|
||||
import { _provideCodePreview, _provideCopyPathChooser, _provideDocumentAttacher, editorsFor } from "@/editor/api";
|
||||
import { openCopyPathChooser } from "./copyPathChooser";
|
||||
import { _provideCodePreview, _provideDocumentAttacher, editorsFor } from "@/editor/api";
|
||||
import { isUntitledUri } from "@/platform/virtualDocs";
|
||||
import { formatDocument } from "@/editor/lsp/format";
|
||||
import { chooserTitle, locationItems, pinToFind } from "@/editor/lsp/navigation";
|
||||
@@ -83,7 +82,6 @@ export function activate(): void | (() => void) {
|
||||
},
|
||||
});
|
||||
_provideDocumentAttacher((path, options) => attachDocument(ctrl.manager, path, options));
|
||||
_provideCopyPathChooser(openCopyPathChooser);
|
||||
_provideCodePreview((path, editable) =>
|
||||
previewExtensions(path, ctrl.manager.settings()?.editor, ctrl.manager.backend, editable),
|
||||
);
|
||||
|
||||
@@ -1,145 +0,0 @@
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { getContext, setContext, useContextKeys } from "@/platform/context";
|
||||
import { _setFocusedCellEditor } from "@/editor/api";
|
||||
import { registerLspActions } from "./actions";
|
||||
import { registerInlineCompletionActions } from "./inlineCompletion";
|
||||
import { editorController, useEditorStatus, useTabs } from "@/editor/core/controller";
|
||||
import { initialTabsState } from "@/editor/core/model/tabs";
|
||||
|
||||
const { formatDocument, showIntentions, refactorThis, requestInline, showHint } = vi.hoisted(() => ({
|
||||
formatDocument: vi.fn(),
|
||||
showIntentions: vi.fn(),
|
||||
refactorThis: vi.fn(),
|
||||
requestInline: vi.fn(),
|
||||
showHint: vi.fn(),
|
||||
}));
|
||||
vi.mock("./format", async (original) => ({
|
||||
...(await original<typeof import("./format")>()),
|
||||
formatDocument,
|
||||
}));
|
||||
vi.mock("./intentions", async (original) => ({
|
||||
...(await original<typeof import("./intentions")>()),
|
||||
showIntentions,
|
||||
}));
|
||||
vi.mock("@/editor/refactor", async (original) => ({
|
||||
...(await original<typeof import("@/editor/refactor")>()),
|
||||
refactorThis,
|
||||
}));
|
||||
vi.mock("./inlineCompletion", async (original) => ({
|
||||
...(await original<typeof import("./inlineCompletion")>()),
|
||||
requestInline,
|
||||
}));
|
||||
vi.mock("./hint", async (original) => ({
|
||||
...(await original<typeof import("./hint")>()),
|
||||
showHint,
|
||||
}));
|
||||
|
||||
const ctrl = editorController();
|
||||
let dispose: () => void;
|
||||
beforeAll(() => {
|
||||
const lsp = registerLspActions();
|
||||
const inline = registerInlineCompletionActions();
|
||||
dispose = () => {
|
||||
inline();
|
||||
lsp();
|
||||
};
|
||||
ctrl.start();
|
||||
});
|
||||
afterAll(() => {
|
||||
ctrl.stop();
|
||||
dispose();
|
||||
});
|
||||
afterEach(() => {
|
||||
useTabs.setState(initialTabsState(), true);
|
||||
useEditorStatus.setState({ status: null });
|
||||
useContextKeys.setState({}, true);
|
||||
_setFocusedCellEditor(null);
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
/** Mounts the text editor of an open tab (a background text tab, as in a split with a notebook). */
|
||||
async function mountTextEditor(path = "/p/a.ts"): Promise<EditorView> {
|
||||
await ctrl.openFile(path, { focus: false });
|
||||
const slot = ctrl.activeSlot!;
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
const view = slot.mount(host);
|
||||
ctrl.onMounted(slot);
|
||||
return view;
|
||||
}
|
||||
|
||||
/** A bare editor standing in for a focused notebook cell (the fact CellEditor publishes). */
|
||||
function focusedCell(): { view: EditorView; clear: () => void } {
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
const view = new EditorView({ doc: "x = 1\nprint(x)\n", parent: host });
|
||||
view.focus();
|
||||
if (!view.hasFocus) throw new Error("the jsdom view did not take focus");
|
||||
_setFocusedCellEditor(view);
|
||||
return {
|
||||
view,
|
||||
clear: () => {
|
||||
_setFocusedCellEditor(null);
|
||||
view.destroy();
|
||||
view.dom.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("editor actions with a focused notebook cell", () => {
|
||||
it("run in the focused cell, not the last text tab", async () => {
|
||||
const textView = await mountTextEditor();
|
||||
const cell = focusedCell();
|
||||
setContext("projectOpen", true);
|
||||
try {
|
||||
ctrl.publishContext();
|
||||
expect(getContext().editorTextFocus).toBe(true);
|
||||
await executeAction("code.reformat");
|
||||
await executeAction("code.showIntentions");
|
||||
await executeAction("refactor.thisMenu");
|
||||
expect(formatDocument).toHaveBeenCalledWith(cell.view, { explicit: true });
|
||||
expect(showIntentions).toHaveBeenCalledWith(cell.view);
|
||||
expect(refactorThis).toHaveBeenCalledWith(cell.view, expect.any(Function));
|
||||
expect(showHint).not.toHaveBeenCalled();
|
||||
// The background text editor was not acted on (it is the view `activeEditor()` holds).
|
||||
expect(formatDocument).not.toHaveBeenCalledWith(textView, { explicit: true });
|
||||
expect(showIntentions).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
cell.clear();
|
||||
hostRemove(textView);
|
||||
}
|
||||
});
|
||||
|
||||
it("keep running in the focused text editor when no cell editor is focused", async () => {
|
||||
const view = await mountTextEditor();
|
||||
setContext("projectOpen", true);
|
||||
view.focus();
|
||||
await vi.waitFor(() => expect(getContext().editorTextFocus).toBe(true));
|
||||
await executeAction("code.reformat");
|
||||
expect(formatDocument).toHaveBeenCalledWith(view, { explicit: true });
|
||||
expect(formatDocument).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("target the focused cell for inline completion", async () => {
|
||||
const textView = await mountTextEditor();
|
||||
const cell = focusedCell();
|
||||
try {
|
||||
ctrl.publishContext();
|
||||
await executeAction("editor.inlineCompletion.trigger");
|
||||
await vi.waitFor(() => expect(showHint).toHaveBeenCalled());
|
||||
expect(showHint).toHaveBeenCalledWith(cell.view, expect.any(String));
|
||||
expect(showHint).not.toHaveBeenCalledWith(textView, expect.anything());
|
||||
} finally {
|
||||
cell.clear();
|
||||
hostRemove(textView);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function hostRemove(view: EditorView): void {
|
||||
const host = view.dom.parentElement;
|
||||
view.destroy();
|
||||
host?.remove();
|
||||
}
|
||||
@@ -2,14 +2,7 @@
|
||||
import { generateActionIcon, isGenerateAction } from "./generate";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { executeAction, registerActions, type Action } from "@/platform/actions";
|
||||
import {
|
||||
activeEditor,
|
||||
editorsFor,
|
||||
focusedCellEditor,
|
||||
registerSaveParticipant,
|
||||
whenSynced,
|
||||
type TextEditorHandle,
|
||||
} from "@/editor/api";
|
||||
import { activeEditor, editorsFor, registerSaveParticipant, whenSynced, type TextEditorHandle } from "@/editor/api";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { maybeEditorService } from "@/workbench/contributions";
|
||||
import { useProject } from "@/platform/project";
|
||||
@@ -74,13 +67,6 @@ export const GENERATE_KEY_WHEN = GENERATE_LANGUAGES.map((id) => `editorLangId ==
|
||||
|
||||
function withEditor(run: (view: EditorView) => unknown): Action["run"] {
|
||||
return () => {
|
||||
// While a notebook cell editor has focus it is the editor the action runs in
|
||||
// (the notebook publishes the editor context keys for it), never the last text tab.
|
||||
const cell = focusedCellEditor();
|
||||
if (cell) {
|
||||
void run(cell);
|
||||
return;
|
||||
}
|
||||
const ed = activeEditor();
|
||||
if (!ed) return;
|
||||
void run(ed.view);
|
||||
@@ -453,9 +439,6 @@ export function registerLspActions(): () => void {
|
||||
category: "Refactor",
|
||||
when: "projectOpen",
|
||||
run: ({ ctx }) => {
|
||||
// A focused notebook cell is the editor here, like for Show Context Actions.
|
||||
const cell = focusedCellEditor();
|
||||
if (cell && evaluateWhen(EDITOR_WHEN, ctx)) return refactorThis(cell, startRename);
|
||||
const ed = activeEditor();
|
||||
if (ed && evaluateWhen(EDITOR_WHEN, ctx)) return refactorThis(ed.view, startRename);
|
||||
showNothingHere();
|
||||
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
type RequestId,
|
||||
unavailableText,
|
||||
} from "@/platform/ipc";
|
||||
import { activeEditor, focusedCellEditor } from "@/editor/api";
|
||||
import { activeEditor } from "@/editor/api";
|
||||
import { docOf, isUnavailable, lspRequest } from "./lsp";
|
||||
import { offsetToPos, rangeToOffsets } from "./positions";
|
||||
import { showHint } from "./hint";
|
||||
@@ -288,8 +288,7 @@ const VISIBLE = `editorTextFocus && ${CONTEXT_KEY}`;
|
||||
|
||||
function onView(run: (view: EditorView) => unknown): Action["run"] {
|
||||
return () => {
|
||||
// A focused notebook cell editor is the editor (the notebook publishes the editor keys).
|
||||
const view = focusedCellEditor() ?? activeEditor()?.view;
|
||||
const view = activeEditor()?.view;
|
||||
if (view) void run(view);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -24,9 +24,7 @@ import { registerKeyClaim } from "@/platform/keymap";
|
||||
import { isVirtualUri } from "@/platform/virtualDocs";
|
||||
import { copySourceOf } from "@/platform/clipboardSource";
|
||||
import {
|
||||
EDITOR_TAB_MIME,
|
||||
getAgentContextSources,
|
||||
maybeEditorService,
|
||||
notifications,
|
||||
OWNS_FILE_DROP,
|
||||
type AgentContextSource,
|
||||
@@ -102,18 +100,6 @@ type Item =
|
||||
|
||||
const isSection = (item: Item) => item.kind === "section";
|
||||
|
||||
/** The file of an editor tab drag payload (`{paneId, tabId}`), null for virtual and non-file tabs. */
|
||||
const tabFilePath = (payload: string): string | null => {
|
||||
try {
|
||||
const p = JSON.parse(payload) as { paneId?: unknown; tabId?: unknown };
|
||||
if (typeof p.paneId !== "string" || typeof p.tabId !== "string") return null;
|
||||
const input = maybeEditorService()?.tabInput?.(p.paneId, p.tabId);
|
||||
return input?.kind === "file" && input.path && !isVirtualUri(input.path) ? input.path : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const SECTION_TITLES: Record<Section, string> = {
|
||||
command: "Commands",
|
||||
skill: "Skills",
|
||||
@@ -955,21 +941,17 @@ export function Composer(props: ComposerProps) {
|
||||
};
|
||||
}, [addPaths, addImages]);
|
||||
|
||||
// Files and folders dragged from the Project view, and file tabs dragged from the editor:
|
||||
// the same `@` references.
|
||||
// Files and folders dragged from the Project view: the same `@` references.
|
||||
useEffect(() => {
|
||||
const el = boxRef.current;
|
||||
if (!el) return;
|
||||
return registerDropTarget(el, {
|
||||
accepts: (type, data) => type === FILES_DRAG || (type === EDITOR_TAB_MIME && !!tabFilePath(data.payload)),
|
||||
accepts: (type) => type === FILES_DRAG,
|
||||
over: () => setFileOver(true),
|
||||
leave: () => setFileOver(false),
|
||||
drop: (data) => {
|
||||
setFileOver(false);
|
||||
if (data.type === EDITOR_TAB_MIME) {
|
||||
const path = tabFilePath(data.payload);
|
||||
if (path) addPaths([path]);
|
||||
} else addPaths(data.payload.split("\n").filter(Boolean));
|
||||
addPaths(data.payload.split("\n").filter(Boolean));
|
||||
},
|
||||
});
|
||||
}, [addPaths]);
|
||||
|
||||
@@ -7,7 +7,6 @@ import userEvent from "@testing-library/user-event";
|
||||
import { caretOf, setCaret, textOf, typeChars, typeIn } from "./composerTesting";
|
||||
import chipStyles from "./ReferenceChip.module.css";
|
||||
import { FILES_DRAG, dragSession } from "@/ui";
|
||||
import { EDITOR_TAB_MIME, provideEditorService, type EditorService } from "@/workbench/contributions";
|
||||
import { useProject } from "@/platform/project";
|
||||
|
||||
const findFiles = vi.fn();
|
||||
@@ -124,32 +123,6 @@ describe("Composer dropped paths", () => {
|
||||
expect(textOf(box)).toBe("@src/a.ts @src/dir/ ");
|
||||
});
|
||||
|
||||
it("references the file of an editor tab dragged onto it and ignores other tabs", () => {
|
||||
provideEditorService({
|
||||
tabInput: (_pane: string, tab: string) =>
|
||||
tab === "file"
|
||||
? { kind: "file", key: "/p/src/a.ts", path: "/p/src/a.ts" }
|
||||
: { kind: "agentSession", key: "agent:one", data: { task: "one" } },
|
||||
} as unknown as EditorService);
|
||||
const box = renderComposer();
|
||||
const restore = document.elementFromPoint;
|
||||
document.elementFromPoint = () => box;
|
||||
try {
|
||||
act(() => {
|
||||
const other = dragSession({
|
||||
type: EDITOR_TAB_MIME,
|
||||
payload: JSON.stringify({ paneId: "p", tabId: "session" }),
|
||||
});
|
||||
expect(other.drop(0, 0)).toBe(false);
|
||||
const file = dragSession({ type: EDITOR_TAB_MIME, payload: JSON.stringify({ paneId: "p", tabId: "file" }) });
|
||||
expect(file.drop(0, 0)).toBe(true);
|
||||
});
|
||||
} finally {
|
||||
document.elementFromPoint = restore;
|
||||
}
|
||||
expect(textOf(box)).toBe("@src/a.ts ");
|
||||
});
|
||||
|
||||
it("deduplicates live references and allows a deleted reference to be dropped again", () => {
|
||||
const box = renderComposer();
|
||||
drop(box, "/p/src/a.ts\n/p/src/a.ts\n/p/src/dir/");
|
||||
|
||||
@@ -232,7 +232,7 @@ export function activate(): () => void {
|
||||
registerStatusItem({ id: "agents.status", align: "right", priority: 3, title: "Agents", component: AgentsStatus }),
|
||||
registerMenuGroup({
|
||||
id: "agents.send",
|
||||
menus: ["editor", "editorTab", "projectView"],
|
||||
menus: ["editor", "projectView"],
|
||||
order: 80,
|
||||
items: (menu, { paths, dirs }) =>
|
||||
paths.length && !paths.some(isVirtualUri) && agentsHere()
|
||||
@@ -240,8 +240,7 @@ export function activate(): () => void {
|
||||
{
|
||||
kind: "action",
|
||||
action: "agents.sendToAgent",
|
||||
// The editor sends its selection; a tab or the Project view sends the files.
|
||||
arg: menu === "editor" ? undefined : paths.map((p, i) => (dirs?.[i] ? `${p}/` : p)),
|
||||
arg: menu === "projectView" ? paths.map((p, i) => (dirs?.[i] ? `${p}/` : p)) : undefined,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
|
||||
@@ -3,7 +3,6 @@ import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import type { AgentEntry, AgentEvent, AgentTask } from "@/bindings";
|
||||
import {
|
||||
dropOnEditor,
|
||||
menuGroupItems,
|
||||
useContributions,
|
||||
useEditorTabTitles,
|
||||
type EditorInput,
|
||||
@@ -596,20 +595,3 @@ describe("the diff of an agent change", () => {
|
||||
expect(backend.openInput.mock.lastCall![0].data.chain).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Send to Agent menus", () => {
|
||||
it("sends the selection from the editor and the files from an editor tab or the Project view", () => {
|
||||
const dispose = activate();
|
||||
try {
|
||||
const send = (menu: "editor" | "editorTab" | "projectView", dirs?: boolean[]) =>
|
||||
menuGroupItems(menu, { paths: ["/p/a.ts", "/p/src"].slice(0, dirs ? 2 : 1), dirs }).find(
|
||||
(i) => "action" in i && i.action === "agents.sendToAgent",
|
||||
);
|
||||
expect(send("editor")).toMatchObject({ arg: undefined });
|
||||
expect(send("editorTab")).toMatchObject({ arg: ["/p/a.ts"] });
|
||||
expect(send("projectView", [false, true])).toMatchObject({ arg: ["/p/a.ts", "/p/src/"] });
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,6 @@ import { _resetI18nForTests, setLocale } from "@/platform/i18n";
|
||||
import { useKeymap } from "@/platform/keymap";
|
||||
import * as ipc from "@/platform/ipc";
|
||||
import { resetDistractionFree, setDistractionFree } from "@/workbench/distractionFree";
|
||||
import { useFullscreen } from "@/workbench/zenMode";
|
||||
import { registerStatusItem, registerToolWindow } from "@/workbench/contributions";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { _reloadLayouts, saveLayout } from "@/workbench/toolwindows/layouts";
|
||||
@@ -334,19 +333,6 @@ describe("window-scoped menu labels", () => {
|
||||
resetDistractionFree();
|
||||
});
|
||||
|
||||
it("flips Enter / Exit Zen Mode only while Distraction Free Mode and full screen are both on", () => {
|
||||
const label = () => buildMenuConfig("macos").labels["menu.view.toggleZenMode"];
|
||||
expect(label()).toBe("Enter Zen Mode");
|
||||
setDistractionFree(true);
|
||||
expect(label()).toBe("Enter Zen Mode");
|
||||
useFullscreen.setState({ on: true });
|
||||
expect(label()).toBe("Exit Zen Mode");
|
||||
setDistractionFree(false);
|
||||
expect(label()).toBe("Enter Zen Mode");
|
||||
useFullscreen.setState({ on: false });
|
||||
resetDistractionFree();
|
||||
});
|
||||
|
||||
it("formats Recompile with the active local Java filename across locales", async () => {
|
||||
try {
|
||||
expect(buildMenuConfig("macos").labels["menu.build.compileFile"]).toBe("Recompile");
|
||||
|
||||
@@ -344,14 +344,6 @@ describe("loose files (LightEdit)", () => {
|
||||
expect(fsReadDir).toHaveBeenCalledWith("/x/a.txt");
|
||||
expect(lightEditOpen).toHaveBeenCalledWith("/x/a.txt");
|
||||
});
|
||||
|
||||
it("opens the folder of a dropped .uproject instead of the file", async () => {
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "current" }));
|
||||
await openPaths(["/work/Game/Game.uproject"], async () => false);
|
||||
expect(windowOpenFiles).not.toHaveBeenCalled();
|
||||
expect(lightEditOpen).not.toHaveBeenCalled();
|
||||
expect(openProject).toHaveBeenCalledWith("/work/Game");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Open Containing Folder as Project", () => {
|
||||
|
||||
@@ -23,7 +23,6 @@ import { useProject } from "@/platform/project";
|
||||
import { syncRemoteRecentMenu } from "@/platform/remote";
|
||||
import { useContributions, useMenuSlotItems, useStandaloneEditor } from "@/workbench/contributions";
|
||||
import { useDistractionFree } from "@/workbench/distractionFree";
|
||||
import { useFullscreen } from "@/workbench/zenMode";
|
||||
import { javaFileNameOf, menuLabelParams } from "@/workbench/menuLabels";
|
||||
import { orderStatusItems } from "@/workbench/StatusBar";
|
||||
import { statusWidgetRows } from "@/workbench/statusBarWidgets";
|
||||
@@ -279,10 +278,6 @@ export function installMenuBridge(): () => void {
|
||||
useDistractionFree.subscribe((s, prev) => {
|
||||
if (s.active !== prev.active) push();
|
||||
}),
|
||||
// View › Appearance › Enter / Exit Zen Mode also follows full screen.
|
||||
useFullscreen.subscribe((s, prev) => {
|
||||
if (s.on !== prev.on && useDistractionFree.getState().active) push();
|
||||
}),
|
||||
// Window › Hide All Tool Windows reads "Restore Tool Windows" while it would restore them.
|
||||
useToolWindowLayout.subscribe((s, prev) => {
|
||||
if (toolWindowsRestorable(s) !== toolWindowsRestorable(prev)) push();
|
||||
|
||||
@@ -128,19 +128,14 @@ export async function openFiles(files: readonly string[]): Promise<void> {
|
||||
|
||||
const pathIsDir = (path: string) => call(commands.fsReadDir(path)).then(() => true);
|
||||
|
||||
/** A file that names the project around it: dropping it opens that folder, as a double-click would. */
|
||||
const projectMarker = /\.uproject$/i;
|
||||
|
||||
/** Opens dropped paths: files as loose files ({@link openFiles}), the first folder as a project. */
|
||||
export async function openPaths(
|
||||
paths: readonly string[],
|
||||
isDir: (path: string) => Promise<boolean> = pathIsDir,
|
||||
): Promise<void> {
|
||||
const kinds = await Promise.all(paths.map((p) => isDir(p).catch(() => false)));
|
||||
// An Unreal project is dragged in as its `.uproject`, which names the folder to open.
|
||||
const marker = paths.find((p, i) => !kinds[i] && projectMarker.test(p));
|
||||
const files = paths.filter((p, i) => !kinds[i] && p !== marker);
|
||||
const dir = paths.find((_, i) => kinds[i]) ?? (marker ? dirname(marker) : undefined);
|
||||
const files = paths.filter((_, i) => !kinds[i]);
|
||||
const dir = paths.find((_, i) => kinds[i]);
|
||||
await openFiles(files);
|
||||
if (dir) await openProjectWithPolicy(dir);
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import { useCallback, useMemo, useRef, useState, useSyncExternalStore, type Keyb
|
||||
import { create } from "zustand";
|
||||
import clsx from "clsx";
|
||||
import type { Diagnostic, Severity } from "@/bindings";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { useEditorRegistry } from "@/editor/api";
|
||||
import { previewColors } from "@/editor/lineTokens";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
@@ -104,8 +103,6 @@ useProblemsOptions.subscribe((s) => {
|
||||
/** The Problems tool window's ⋮ menu entries. */
|
||||
export function useProblemsHeaderMenu(): MenuItem[] {
|
||||
const o = useProblemsOptions();
|
||||
const tscWatch = useProject((s) => s.settings?.languages?.typescript?.watchProblems ?? false);
|
||||
const hasProject = useProject((s) => s.project !== null);
|
||||
const toggle = (key: keyof ProblemsOptions) => () => useProblemsOptions.setState({ [key]: !o[key] });
|
||||
return [
|
||||
{ kind: "header", label: "Sort By" },
|
||||
@@ -114,25 +111,9 @@ export function useProblemsHeaderMenu(): MenuItem[] {
|
||||
{ kind: "separator" },
|
||||
{ id: "preview", label: "Show Preview", checked: o.preview, run: toggle("preview") },
|
||||
{ id: "autoscroll", label: "Autoscroll to Source", checked: o.autoscroll, run: toggle("autoscroll") },
|
||||
{ kind: "separator" },
|
||||
{
|
||||
id: "tscWatch",
|
||||
label: "TypeScript Project Errors (tsc --watch)",
|
||||
checked: tscWatch,
|
||||
disabled: !hasProject,
|
||||
run: () => void setTscWatch(!tscWatch),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/** Runs the project's own `tsc --watch` and lists its errors in Problems (project setting). */
|
||||
async function setTscWatch(on: boolean) {
|
||||
const settings = await call(
|
||||
commands.settingsSet("project", "languages.typescript.watchProblems", JSON.stringify(on)),
|
||||
);
|
||||
useProject.setState({ settings });
|
||||
}
|
||||
|
||||
const group = (s: Severity): "error" | "warning" | "info" => (s === "hint" ? "info" : s);
|
||||
|
||||
type FileNode = { kind: "file"; key: string; path: string; items: Diagnostic[]; error: boolean };
|
||||
|
||||
@@ -64,35 +64,6 @@ describe("counts", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("a problem two sources report", () => {
|
||||
beforeEach(() => clearProblems());
|
||||
|
||||
it("is listed and counted once (Build's tsc step and the tsc watcher)", () => {
|
||||
const counts = () => useProblems.getState().counts.error;
|
||||
const listed = () => fileDiagnostics(useProblems.getState().map, "/p/b.ts").map((x) => x.source);
|
||||
applyDiagnosticsEvent("/p/b.ts", "tsc", [d(1, "error", "tsc"), d(2, "error", "tsc")]);
|
||||
applyDiagnosticsEvent("/p/b.ts", "build", [d(1, "error", "build")]);
|
||||
expect(listed()).toEqual(["build", "tsc"]);
|
||||
expect(counts()).toBe(2);
|
||||
expect(projectCounts(useProblems.getState().map).error).toBe(2);
|
||||
// Either source alone still shows it.
|
||||
applyDiagnosticsEvent("/p/b.ts", "tsc", []);
|
||||
expect(listed()).toEqual(["build"]);
|
||||
expect(counts()).toBe(1);
|
||||
applyDiagnosticsEvent("/p/b.ts", "build", []);
|
||||
expect(listed()).toEqual([]);
|
||||
expect(counts()).toBe(0);
|
||||
});
|
||||
|
||||
it("keeps other sources as they are, and different problems on one line", () => {
|
||||
let map = mergeDiagnostics(mergeDiagnostics(new Map(), "/a", "ra", [d(1)]), "/a", "eslint", [d(1)]);
|
||||
expect(fileDiagnostics(map, "/a")).toHaveLength(2);
|
||||
map = mergeDiagnostics(map, "/a", "build", [{ ...d(1), message: "another" }]);
|
||||
map = mergeDiagnostics(map, "/a", "tsc", [d(1)]);
|
||||
expect(fileDiagnostics(map, "/a")).toHaveLength(4);
|
||||
});
|
||||
});
|
||||
|
||||
describe("store + decorations", () => {
|
||||
beforeEach(() => clearProblems());
|
||||
|
||||
|
||||
@@ -65,26 +65,14 @@ const SEVERITY_ORDER: Record<Severity, number> = { error: 0, warning: 1, info: 2
|
||||
// A file's sources map is replaced whenever its diagnostics change, so it keys the merged list.
|
||||
const merged = new WeakMap<FileDiagnostics, readonly Diagnostic[]>();
|
||||
|
||||
const sameProblem = (d: Diagnostic) =>
|
||||
`${d.range.start.line}:${d.range.start.col}-${d.range.end.line}:${d.range.end.col} ${d.severity} ${d.message}`;
|
||||
|
||||
/**
|
||||
* All diagnostics of a file across sources, ordered by position then severity. An error both
|
||||
* Build and the tsc watcher report is listed once.
|
||||
*/
|
||||
/** All diagnostics of a file across sources, ordered by position then severity. */
|
||||
export function fileDiagnostics(map: ProblemsMap, path: string): readonly Diagnostic[] {
|
||||
return mergedSources(map.get(path));
|
||||
}
|
||||
|
||||
function mergedSources(sources: FileDiagnostics | undefined): readonly Diagnostic[] {
|
||||
const sources = map.get(path);
|
||||
if (!sources) return [];
|
||||
let items = merged.get(sources);
|
||||
if (!items) {
|
||||
// Build's tsc step and the tsc watcher (Problems › TypeScript Project Errors) print the same errors.
|
||||
const build = sources.get("build");
|
||||
const built = build && sources.has("tsc") ? new Set(build.map(sameProblem)) : null;
|
||||
items = [...sources]
|
||||
.flatMap(([source, list]) => (built && source === "tsc" ? list.filter((d) => !built.has(sameProblem(d))) : list))
|
||||
items = [...sources.values()]
|
||||
.flat()
|
||||
.sort(
|
||||
(a, b) =>
|
||||
a.range.start.line - b.range.start.line ||
|
||||
@@ -165,7 +153,7 @@ export function countSeverities(diags: Iterable<Diagnostic>): SeverityCounts {
|
||||
|
||||
export function projectCounts(map: ProblemsMap): SeverityCounts {
|
||||
const c: SeverityCounts = { error: 0, warning: 0, info: 0, hint: 0 };
|
||||
for (const sources of map.values()) for (const d of mergedSources(sources)) c[d.severity]++;
|
||||
for (const sources of map.values()) for (const items of sources.values()) for (const d of items) c[d.severity]++;
|
||||
return c;
|
||||
}
|
||||
|
||||
@@ -257,13 +245,12 @@ function applyTo(snapshot: ProblemsSnapshot, path: string, source: string, items
|
||||
|
||||
export function applyDiagnosticsEvent(path: string, source: string, items: readonly Diagnostic[]) {
|
||||
useProblems.setState((s) => {
|
||||
// The file's sources map is replaced, not changed, so this is the list before the event.
|
||||
const before = mergedSources(s.map.get(path));
|
||||
const before = s.map.get(path)?.get(source) ?? [];
|
||||
const raw = applyTo(s.raw, path, source, items);
|
||||
if (!raw) return s;
|
||||
const map = applyTo(s.map, path, source, applyProfile(inspectionProfile(), source, items));
|
||||
if (!map) return { raw };
|
||||
return { raw, map, counts: recount(s.counts, before, mergedSources(map.get(path))) };
|
||||
return { raw, map, counts: recount(s.counts, before, map.get(path)?.get(source) ?? []) };
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { renderHook } from "@testing-library/react";
|
||||
import type { Settings } from "@/bindings";
|
||||
|
||||
const settingsSet = vi.fn(async (_scope: string, _key: string, _value: string) => ({
|
||||
status: "ok" as const,
|
||||
data: { languages: { typescript: { watchProblems: true } } } as Settings,
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (orig) => {
|
||||
const actual = await orig<typeof import("@/platform/ipc")>();
|
||||
return { ...actual, commands: { ...actual.commands, settingsSet } };
|
||||
});
|
||||
|
||||
const { useProblemsHeaderMenu } = await import("./ProblemsView");
|
||||
const { useProject } = await import("@/platform/project");
|
||||
|
||||
afterEach(() => {
|
||||
useProject.setState({ project: null, settings: null });
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
const tscWatchItem = () =>
|
||||
renderHook(() => useProblemsHeaderMenu()).result.current.find((i) => "id" in i && i.id === "tscWatch");
|
||||
|
||||
it("turns the project's tsc --watch on from the Problems menu", async () => {
|
||||
useProject.setState({
|
||||
project: { root: "/p" } as never,
|
||||
settings: { languages: { typescript: { watchProblems: false } } } as Settings,
|
||||
});
|
||||
const item = tscWatchItem();
|
||||
expect(item).toMatchObject({ checked: false, disabled: false });
|
||||
if (item && "run" in item) item.run?.();
|
||||
await vi.waitFor(() =>
|
||||
expect(settingsSet).toHaveBeenCalledWith("project", "languages.typescript.watchProblems", "true"),
|
||||
);
|
||||
await vi.waitFor(() => expect(useProject.getState().settings?.languages?.typescript?.watchProblems).toBe(true));
|
||||
});
|
||||
|
||||
it("is off and unavailable without a project", () => {
|
||||
expect(tscWatchItem()).toMatchObject({ checked: false, disabled: true });
|
||||
});
|
||||
@@ -70,56 +70,6 @@ export function ExtractorSelect({ value, onChange }: { value: ExportFormat; onCh
|
||||
export const copyFormatOf = (extractor: ExportFormat): CopyFormat =>
|
||||
extractor === "csv" ? "csv" : extractor === "onerow" ? "onerow" : "tsv";
|
||||
|
||||
/** The toolbar's extractor; `table` is the whole table to export (`null`: nothing, already reported). */
|
||||
export interface ExtractorMenu {
|
||||
value: ExportFormat;
|
||||
onChange: (f: ExportFormat) => void;
|
||||
table: () => ExportData | null | Promise<ExportData | null>;
|
||||
}
|
||||
|
||||
const PANEL_ENTRIES: ReadonlyArray<{ panel: DataPanel; label: string }> = [
|
||||
{ panel: "record", label: "Show Record View" },
|
||||
{ panel: "value", label: "Open in Value Editor" },
|
||||
{ panel: "aggregates", label: "Show Aggregate View" },
|
||||
];
|
||||
|
||||
/**
|
||||
* The view's entries of the grid's context menu (DataGrip's): the side panels, checked while
|
||||
* shown, then the toolbar's extractor and Export Table to Clipboard when the view has them.
|
||||
*/
|
||||
export function viewMenu(
|
||||
panel: DataPanel | null,
|
||||
onPanelChange: (panel: DataPanel | null) => void,
|
||||
extractor?: ExtractorMenu,
|
||||
): MenuItem[] {
|
||||
const items: MenuItem[] = PANEL_ENTRIES.map(({ panel: p, label }) => ({
|
||||
label,
|
||||
checked: panel === p,
|
||||
run: () => onPanelChange(panel === p ? null : p),
|
||||
}));
|
||||
if (!extractor) return items;
|
||||
return [
|
||||
...items,
|
||||
{ kind: "separator" },
|
||||
{
|
||||
label: "Data Extractor",
|
||||
submenu: EXPORT_FORMATS.map((f) => ({
|
||||
label: f.label,
|
||||
checked: f.id === extractor.value,
|
||||
run: () => extractor.onChange(f.id),
|
||||
})),
|
||||
},
|
||||
{
|
||||
label: "Export Table to Clipboard",
|
||||
icon: "copy",
|
||||
run: () =>
|
||||
void Promise.resolve(extractor.table()).then(
|
||||
(data) => data && writeClipboardText(exportData(extractor.value, data)),
|
||||
),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/** The Record / Value / Aggregates panel's toggle (IDEA's "Show Value Editor"). */
|
||||
export function PanelToggle({ panel, onChange }: { panel: DataPanel | null; onChange: (p: DataPanel | null) => void }) {
|
||||
return (
|
||||
@@ -167,8 +117,6 @@ export interface DataViewProps extends Pick<
|
||||
onPanelChange: (panel: DataPanel | null) => void;
|
||||
/** Plain ⌘C's copy format (the toolbar's extractor; TSV by default). */
|
||||
copyFormat?: CopyFormat;
|
||||
/** The toolbar's extractor, also offered in the grid's context menu with the whole table to copy. */
|
||||
extractor?: ExtractorMenu;
|
||||
/** The search bar is shown (the toolbar's search button, ⌘F in the grid). */
|
||||
searchOpen?: boolean;
|
||||
onSearchOpenChange?: (open: boolean) => void;
|
||||
@@ -300,11 +248,7 @@ export function DataView(props: DataViewProps) {
|
||||
driver={props.driver}
|
||||
sort={sort}
|
||||
onSort={onSort}
|
||||
rowMenu={(rows) => {
|
||||
const own = props.rowMenu?.(rows.map(at)) ?? [];
|
||||
const view = viewMenu(panel, onPanelChange, props.extractor);
|
||||
return own.length ? [...own, { kind: "separator" }, ...view] : view;
|
||||
}}
|
||||
rowMenu={props.rowMenu && ((rows) => props.rowMenu!(rows.map(at)))}
|
||||
rowNumber={(r) => (props.firstRowNumber ?? 1) + at(r)}
|
||||
copyFormat={props.copyFormat}
|
||||
onSelectionChange={setRange}
|
||||
|
||||
@@ -954,23 +954,6 @@
|
||||
padding: 2px 4px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.modifyFilter {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.modifyGroup {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
height: 22px;
|
||||
padding: 0 6px;
|
||||
color: var(--fg-muted);
|
||||
cursor: default;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.modifyGroup:hover {
|
||||
color: var(--fg);
|
||||
}
|
||||
.modifyList {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
|
||||
Loaded 100 of 207 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача