дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 17:47:08 +02:00
Порівняти коміти
26
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
7125a2179e | ||
|
|
3d2b0946de | ||
|
|
6c7282b442 | ||
|
|
1f79a7f805 | ||
|
|
3d1eaf71e4 | ||
|
|
138209c627 | ||
|
|
b283d352b7 | ||
|
|
f7f9dabe2b | ||
|
|
787d4fbcfa | ||
|
|
3fbd0e05a5 | ||
|
|
2d021a3414 | ||
|
|
cd7582c5e5 | ||
|
|
d16b852054 | ||
|
|
06223d9bd7 | ||
|
|
dcd81d601b | ||
|
|
762ebecd86 | ||
|
|
fd4efff6e3 | ||
|
|
8968974f42 | ||
|
|
5f083ae47c | ||
|
|
83b14b4329 | ||
|
|
74eefd6116 | ||
|
|
a96c70f2a7 | ||
|
|
304503b9f1 | ||
|
|
06cf8fb16a | ||
|
|
521e00d075 | ||
|
|
b4cad6ec1b |
No files matched your search
Створено
+198
-148
@@ -474,7 +474,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "457d7ed3f888dfd2c7af56d4975cade43c622f74bdcddfed6d4352f57acc6310"
|
||||
dependencies = [
|
||||
"futures-util",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"portable-atomic",
|
||||
"tokio",
|
||||
]
|
||||
@@ -1655,9 +1655,9 @@ dependencies = [
|
||||
"cfg-if",
|
||||
"crossbeam-utils",
|
||||
"hashbrown 0.14.5",
|
||||
"lock_api",
|
||||
"lock_api 0.4.14",
|
||||
"once_cell",
|
||||
"parking_lot_core",
|
||||
"parking_lot_core 0.9.12",
|
||||
"serde",
|
||||
]
|
||||
|
||||
@@ -2154,7 +2154,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2210,6 +2210,16 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "faster-hex"
|
||||
version = "2.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e4ede54fe330383a5de28c0a1f06668ff9dbf06c8094e1c5150c39488a5e911d"
|
||||
dependencies = [
|
||||
"defmt 0.3.101",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.5.0"
|
||||
@@ -2453,8 +2463,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"lock_api",
|
||||
"parking_lot",
|
||||
"lock_api 0.4.14",
|
||||
"parking_lot 0.12.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2734,9 +2744,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix"
|
||||
version = "0.89.0"
|
||||
version = "0.90.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2156d2e07fc3afa7632a82bf3cb0db91f995645a2852f642105c9ac9b52e1cb2"
|
||||
checksum = "b92b20c1560511a9014b16e29db2f3c6f0580d4fe289b70f41131277b065a3b0"
|
||||
dependencies = [
|
||||
"gix-actor",
|
||||
"gix-attributes",
|
||||
@@ -2788,9 +2798,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-actor"
|
||||
version = "0.44.0"
|
||||
version = "0.44.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2127da41042965ed205568a52443465806944f71c8acd73f48ec94b8cd8e798e"
|
||||
checksum = "78243d3371019288a40a75ba1a58de2815c32591fc87b9f7cb01918bce364ca8"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-date",
|
||||
@@ -2799,9 +2809,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-attributes"
|
||||
version = "0.37.0"
|
||||
version = "0.37.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0feca0b8919aba9f123b75de54062dd61eb37d2a2130f34be520da6ed8b8ef72"
|
||||
checksum = "6b9947d93a94d41ddde66ac655674269121cbebaf6cdee30d8d0e7dbe85edb4c"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -2816,27 +2826,27 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-bitmap"
|
||||
version = "0.6.0"
|
||||
version = "0.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "408cb9e482e0dcc5fc481850556348dda6981ec054a4a8e81a8e1bbf84f85eef"
|
||||
checksum = "9543567ee22142c81fdf75b2811160bec749a5b9f48665e4763f88b1789b8612"
|
||||
dependencies = [
|
||||
"gix-error",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-chunk"
|
||||
version = "0.10.0"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "626335faf30ed235744642c2309aa370683b8bb2757f1c22a807e274dff60074"
|
||||
checksum = "60cd5f0e47ffae98bad241ccbc031693765004fb4c2a419f7fda2963232af1e3"
|
||||
dependencies = [
|
||||
"gix-error",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-command"
|
||||
version = "0.12.0"
|
||||
version = "0.12.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac560c05e19455016a4a94b33a77debe59aaed8783da32a73d31c9975947152e"
|
||||
checksum = "2986e78ebad43510ccd7dd18bd9f22e9afd52f2de791e2979b9c715bacb6f0a8"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -2847,9 +2857,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-commitgraph"
|
||||
version = "0.41.0"
|
||||
version = "0.42.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dfede9936d4b789867c09722576aea4ceb0e3aacf962eef035ebab0686b41a80"
|
||||
checksum = "60b53b700d2a506cf98075099df1fcc0558265cbb47fd86bc6d03c231e4bd72a"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-chunk",
|
||||
@@ -2861,9 +2871,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-config"
|
||||
version = "0.62.0"
|
||||
version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65a9c000fa9a9154f22ffc8f8d74426e9300d759c2029e8701e2ba39d5d464ea"
|
||||
checksum = "3e11ccf82e9630c4e7befbae07cbe90e79de61dc73a34448c2dec70a13da9ebf"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-config-value",
|
||||
@@ -2881,9 +2891,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-config-value"
|
||||
version = "0.21.0"
|
||||
version = "0.21.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ab206c2fccfd35e0de7fb1b424997cfd42912062c66dae024e08a06e22d46674"
|
||||
checksum = "d7666081ef0ecc5e1dc54bc6ce16dac9d7b9490780f6c130393ef9e50c909d4a"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bstr",
|
||||
@@ -2895,9 +2905,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-date"
|
||||
version = "0.18.0"
|
||||
version = "0.18.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0f7eeeecc599082f32b5ea6a8c4c734e38be9730e2c09e3fe2851bb4692393e9"
|
||||
checksum = "4c538190012dbb536df54734ec38cc1109270c73f2f76585c011dd5b0c9f087c"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -2907,9 +2917,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-diff"
|
||||
version = "0.69.0"
|
||||
version = "0.70.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa640963fdcbc6b4718e48593c3917f5ae764b59fb5a96313cb5a757246d041d"
|
||||
checksum = "2c794988335792f85c3ca79c385c950b3a921a71ba3df361cb1f9e5b6bd4a6e4"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-attributes",
|
||||
@@ -2931,9 +2941,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-dir"
|
||||
version = "0.31.0"
|
||||
version = "0.32.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "84e916ef77f19161b738ae9913662bc36fed1e48256a943f40277b3a585841da"
|
||||
checksum = "af939f21c65d4f15457c72d08c874d454893185c51a3596e3c2bd3d9c567618d"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-discover",
|
||||
@@ -2951,9 +2961,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-discover"
|
||||
version = "0.57.0"
|
||||
version = "0.57.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7d0f8fd2c7e4b458eb3081362d49b54bd0131d23ecd49be802085a11f0d3cee"
|
||||
checksum = "4a0875f4e5408713fcf92265973cc38bf9dc5a93384ce218beba0572b7785a03"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"dunce",
|
||||
@@ -2966,18 +2976,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-error"
|
||||
version = "0.5.1"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bb3308a948a01b94ef13d9ee7a9b28c1303d8d9a9dc33b401ff40c2184d9e04a"
|
||||
checksum = "50ad6c42fa50280f382026ff838a8afa7ab2ad83e92349cab4392972baae69cd"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-filter"
|
||||
version = "0.36.0"
|
||||
version = "0.36.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9d8d932ee4043f7d77d15ee58d2be2bc95accea5dd1d77fd145de1b7c504551b"
|
||||
checksum = "f8df8d50fda4684c6ec366f75e4082ab6fc3d437d3deec30ff88462710b68d17"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"encoding_rs",
|
||||
@@ -2996,9 +3006,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-fs"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "44a05d043e670c055cd8b53d078562dc0bc1e322bff6b0376b407d37cf72dcc5"
|
||||
checksum = "808f23d897ddfe847d9b7206bda947901885be623bdf96b226a2dccf87f018c7"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -3011,9 +3021,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-glob"
|
||||
version = "0.29.0"
|
||||
version = "0.29.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7b0d03ab50fa841621031960679caf7fe94940968d9a0736d12a580f2c03e525"
|
||||
checksum = "7a12789fa68a150293ad8834d267b31044240532b5ccf2734d228fe985cba2be"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bstr",
|
||||
@@ -3025,11 +3035,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-hash"
|
||||
version = "0.28.0"
|
||||
version = "0.28.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "40ca156064e378d8c657084365846cedb8dc498c6ea4500965a64d74f12af2be"
|
||||
checksum = "b4802ffb87e051795822bfdaa8ab9075b23e316684f7054e6ce4a246b2b76f4e"
|
||||
dependencies = [
|
||||
"faster-hex",
|
||||
"faster-hex 0.10.1",
|
||||
"gix-error",
|
||||
"gix-utils",
|
||||
"sha1dc",
|
||||
@@ -3044,7 +3054,7 @@ checksum = "916cb6b2ec42ffaca624e7867bb382a4673015cb4ffcd7330b48085d02e4c615"
|
||||
dependencies = [
|
||||
"gix-hash",
|
||||
"hashbrown 0.17.1",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3062,9 +3072,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-imara-diff"
|
||||
version = "0.3.1"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c48eccd894bd15555b0346470e63491ded94aefe76b3fcb1052084b5a393238"
|
||||
checksum = "23347fa4a29a440eebf045d0bc21da465c0dc70434c2a4bcdfcc658f16c9e27e"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"hashbrown 0.17.1",
|
||||
@@ -3072,9 +3082,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-index"
|
||||
version = "0.57.0"
|
||||
version = "0.58.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc6db8b20a3dba8836daf90b24199600bb27dcfce3a127ec24ae61e15a7c5b68"
|
||||
checksum = "06bfc736774a623307eda890c918d308ef5acd37402bde2d6768fccb1f6ecb5d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bstr",
|
||||
@@ -3124,9 +3134,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-note"
|
||||
version = "0.3.0"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bd364f8bdceaed9e7f3ae40f324b16e39f20e9c7e6a6a058f7c6ec66c3e6205c"
|
||||
checksum = "8473688f2262f4364f521b39ce2a5dbe94494f327fc19c945318d7aff580952e"
|
||||
dependencies = [
|
||||
"gix-error",
|
||||
"gix-hash",
|
||||
@@ -3135,9 +3145,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-object"
|
||||
version = "0.66.0"
|
||||
version = "0.66.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0e38f50177e211642af154f9a7f710b7a3a637e635f9b6adb9d51973b0f9209"
|
||||
checksum = "beaf9086dd00b9d2a177ca3ae83210ce926cee7c0faa112e053851221cd8f94d"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-actor",
|
||||
@@ -3156,9 +3166,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-odb"
|
||||
version = "0.86.0"
|
||||
version = "0.87.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ca444f33f2140876ed6b5313c2b550b4af699008193c96f3bff5023afa9ef4ea"
|
||||
checksum = "941b5b99fed282a5b05b54ea486c36c76b558afe151e6804c3acdd5c8f3c3459"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"crc32fast",
|
||||
@@ -3175,15 +3185,15 @@ dependencies = [
|
||||
"gix-utils",
|
||||
"gix-zlib",
|
||||
"memmap2",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-pack"
|
||||
version = "0.76.0"
|
||||
version = "0.77.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bc5024cc503cd29461a705ae90b9eae772fa8f0e6fafc1c48513877dc374de05"
|
||||
checksum = "e2ef461798b1e6cb652192c69dfc9658dfc1bab457ef812dd1ab85d75104cbef"
|
||||
dependencies = [
|
||||
"clru",
|
||||
"crc32fast",
|
||||
@@ -3204,45 +3214,46 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-packetline"
|
||||
version = "0.24.0"
|
||||
version = "0.24.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "830e51b227f6a925fe9308858ac91170dd00fa2880f5480fc81e8a4594fe2c35"
|
||||
checksum = "6e198121152a397ad1007e3334931b04b393fa17f6af34f17b33e376b15bf5ea"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"faster-hex",
|
||||
"faster-hex 2.0.0",
|
||||
"gix-error",
|
||||
"gix-trace",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-parallel"
|
||||
version = "0.50.0"
|
||||
version = "0.50.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e994cf1eec247ba4be7f9e7c0d58cc73f83eecb5fcb9feb595df5ba3d2078546"
|
||||
checksum = "d3a5c86eeec0194a3444611b4762ba05cc5029408a617348b4f6a74a34c222cd"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
"gix-trace",
|
||||
"once_cell",
|
||||
"parking_lot",
|
||||
"parking_lot 0.13.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-path"
|
||||
version = "0.14.0"
|
||||
version = "0.14.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6d563d4d0c975ed0df4e853f9ec962a2ba46633b1d324e1a5582541fcae0c6b"
|
||||
checksum = "615e3ff75800c67022ec8065b67e0846420a88c5f484e6c4fd81c78472e4c77a"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
"gix-trace",
|
||||
"gix-validate",
|
||||
"winreg 0.56.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-pathspec"
|
||||
version = "0.22.0"
|
||||
version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3e3b7f03e516a8435d18c3cc2d446925940c81d409145ac21edb5a576f0625e4"
|
||||
checksum = "490aa03a11e0cbb998a0a593b75e27ea2e30df4ebd8f84f60e0641b9b72270e8"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bstr",
|
||||
@@ -3255,9 +3266,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-protocol"
|
||||
version = "0.67.0"
|
||||
version = "0.68.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "832b5dc46a3c0a6f6fa8f8e571c11074add4b545c6789799ae6d6c36ae1a294e"
|
||||
checksum = "83677ebae6a1a09dc07f2435b5ebe68470dc51afb74052135e98fd7c11f85ba9"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-date",
|
||||
@@ -3273,9 +3284,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-quote"
|
||||
version = "0.10.0"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c7f92bc1b13c09e88388578e8aa1e987ec35f28fca158c13b1baa7ab1a85b124"
|
||||
checksum = "5069a7ec021bb47abe9f12dcc075d292e8cf4a9dff5fffd38595b39c6b419aaa"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -3284,9 +3295,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-ref"
|
||||
version = "0.69.0"
|
||||
version = "0.69.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "073bc0928e1f747823b1eaed94918119dacef4c616532bc3d17e5b7457863471"
|
||||
checksum = "68686e4697b9cd15d1b152ef51df870513210ed22938eacc13b3672b76035f13"
|
||||
dependencies = [
|
||||
"gix-actor",
|
||||
"gix-error",
|
||||
@@ -3304,9 +3315,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-refspec"
|
||||
version = "0.47.0"
|
||||
version = "0.47.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ccc7010dae0df2900aa77cc67f8aca042cd80e35938ccc179010d863b1d42a0c"
|
||||
checksum = "2569309da6fdc230973cf5b846508154c0e813fda60f2b2da768cc5655ed312c"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -3317,9 +3328,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-revision"
|
||||
version = "0.51.0"
|
||||
version = "0.52.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "63210c1943b67fa700806c3c3486fc16a92b3ea871f5cf092340b8eec10a0ca1"
|
||||
checksum = "241465fc73530f41d0a1c18320c5e291365b7c2c2a3dfd07afe2a5d6265085c8"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bstr",
|
||||
@@ -3336,9 +3347,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-revwalk"
|
||||
version = "0.37.0"
|
||||
version = "0.38.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "800479fbbf1e7f94f663e07943a91add5499343e7aac611a81e6a0460fd44af6"
|
||||
checksum = "8b46edeacd25d9d3131941ae6bc91002bf7ba10e130393b7e9bc23d528625447"
|
||||
dependencies = [
|
||||
"gix-commitgraph",
|
||||
"gix-date",
|
||||
@@ -3351,9 +3362,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-sec"
|
||||
version = "0.16.0"
|
||||
version = "0.16.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5640f642a1b471616d48230b1def7ca743cb30903441ff84800cafbab3c0fddf"
|
||||
checksum = "9598d1f35baec7038c2d278bfcc18f1d8951f41dcc3f51ab6175661dfe5a6137"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"gix-path",
|
||||
@@ -3363,9 +3374,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-shallow"
|
||||
version = "0.15.0"
|
||||
version = "0.15.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94bc0720a3d6b10f18e3ac382a7780bcfc4c6bee94a8b5857b8e4ec94c50d754"
|
||||
checksum = "1d805949578724b5164c90ec6d19567832ccaa5ba8a3fe26f7befc52007e2407"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -3376,9 +3387,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-status"
|
||||
version = "0.36.0"
|
||||
version = "0.37.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "42d3174a9f3fb991cf25a7a609ab6c50f19baa7d5f8ce05a48c202f7db4ce3ba"
|
||||
checksum = "31b00c359278210e3cc0803d057db1d61c5d6694c21ed9ad0b8f8f862157247a"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"filetime",
|
||||
@@ -3398,14 +3409,13 @@ dependencies = [
|
||||
"gix-worktree",
|
||||
"hashbrown 0.16.1",
|
||||
"portable-atomic",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-submodule"
|
||||
version = "0.36.0"
|
||||
version = "0.36.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6d945257bd0d624ca844a5a36c79d748df080f355b0ac92d68793875aa529a3f"
|
||||
checksum = "d558a1307b6f3de2a92bd91d0570c53952d4f2329e6860813007508c8ed413dc"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-config",
|
||||
@@ -3425,22 +3435,22 @@ dependencies = [
|
||||
"dashmap",
|
||||
"gix-fs",
|
||||
"libc",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"tempfile",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-trace"
|
||||
version = "0.3.0"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "133f2de116104d637541831b6acb157898556d5eeec363ab2eb1c583adc6bb56"
|
||||
checksum = "1c96f84d731a96780e6a7ad5ee70b4ecc398499946b62617945fbaeb6ab878f8"
|
||||
|
||||
[[package]]
|
||||
name = "gix-transport"
|
||||
version = "0.61.0"
|
||||
version = "0.62.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e43d6b0097ea9f2f266d5d6c43b8f615ed3da7c686ec8771cd17c1cb33cb0de"
|
||||
checksum = "cdcd9cdfd8745aa38f926a4a380c13d76b200d7338de57fc492982cd5a6652ba"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-command",
|
||||
@@ -3456,9 +3466,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-traverse"
|
||||
version = "0.63.0"
|
||||
version = "0.64.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a668a6e7f7688e5a43eaf161f1471ffc559de1a5fd8471e861c64d59d1699e1e"
|
||||
checksum = "00171e00e91508300d0361072c4eb110ec0f1322d8b95ed36887231702a38ebc"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"gix-commitgraph",
|
||||
@@ -3473,9 +3483,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-url"
|
||||
version = "0.40.0"
|
||||
version = "0.40.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "04317dea7a5dd5253bbcab060c230f3de6a57d17cc9600c6cd7030bf4795b414"
|
||||
checksum = "def12e1016b872f1094442882f627905c59bd73480435291a4958cf373a8f28d"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -3486,9 +3496,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-utils"
|
||||
version = "0.5.1"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8e770b8c34311044d1addc7b18957db0ac27183707e1140dc90e6f674a6354e"
|
||||
checksum = "b5e6d46894c7a4fd9c5e26d233a0fa836002ba0af9a11aef58923d317c486e10"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"bytes",
|
||||
@@ -3501,9 +3511,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-validate"
|
||||
version = "0.13.0"
|
||||
version = "0.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cbcd59cc52742468bc5c8a0e7123390d154f45e6cbd37461b0dcecdc681f2179"
|
||||
checksum = "5d6f293fd8abd9bd9bc1e0a23541f73607e932b5a2bde2246320da38edde5726"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-error",
|
||||
@@ -3511,9 +3521,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-worktree"
|
||||
version = "0.58.0"
|
||||
version = "0.59.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a285c0f6b41e504e8bb81ca3f861c4da00cb3d5ced3210a4591112f22da6d38f"
|
||||
checksum = "fe92aec0a25cf073394492a6ee2aa4d27632acde91a653d34de0e4da6afb485d"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-attributes",
|
||||
@@ -3530,9 +3540,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gix-worktree-stream"
|
||||
version = "0.38.0"
|
||||
version = "0.39.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28d2789610e8179d4e0e8e51170a52a66483c103a8ad3c7db4d075b571856cb6"
|
||||
checksum = "3fe5d65793848ffb596f6c5596fd120b132038736525628227e2388ca454f64d"
|
||||
dependencies = [
|
||||
"gix-attributes",
|
||||
"gix-error",
|
||||
@@ -3545,14 +3555,14 @@ dependencies = [
|
||||
"gix-trace",
|
||||
"gix-traverse",
|
||||
"gix-utils",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-zlib"
|
||||
version = "0.3.0"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8c2edb206bf06f3c801f4f6789c696396171558ab9b4c7f1fe3ba4d39b00b0f4"
|
||||
checksum = "81a49a8b263d2a140f1c178ff93375b8d4cc7b1d3252cd87ce1ca88bce62b9b9"
|
||||
dependencies = [
|
||||
"gix-error",
|
||||
"zlib-rs",
|
||||
@@ -4156,7 +4166,7 @@ dependencies = [
|
||||
"ide-tools",
|
||||
"ide-vcs",
|
||||
"ide-vfs",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"rustix",
|
||||
"semver",
|
||||
"serde",
|
||||
@@ -4297,7 +4307,7 @@ dependencies = [
|
||||
"ide-language",
|
||||
"libc",
|
||||
"memchr",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"percent-encoding",
|
||||
"portable-pty",
|
||||
"serde",
|
||||
@@ -4329,7 +4339,7 @@ dependencies = [
|
||||
"notify",
|
||||
"open",
|
||||
"oracledb",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"reqwest",
|
||||
"rsa",
|
||||
"rustls",
|
||||
@@ -4385,7 +4395,7 @@ dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
"ed25519-dalek",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4403,7 +4413,7 @@ version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-android",
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
]
|
||||
@@ -4510,7 +4520,7 @@ dependencies = [
|
||||
"ide-workspace",
|
||||
"ignore",
|
||||
"jsonschema",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"quick-xml 0.42.0",
|
||||
"regex-lite",
|
||||
"regex-syntax",
|
||||
@@ -4540,7 +4550,7 @@ dependencies = [
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"reqwest",
|
||||
"rustls",
|
||||
"rustls-platform-verifier",
|
||||
@@ -4565,7 +4575,7 @@ dependencies = [
|
||||
"ide-language",
|
||||
"ignore",
|
||||
"nucleo-matcher",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"postcard",
|
||||
"rayon",
|
||||
"redb",
|
||||
@@ -4593,7 +4603,7 @@ version = "0.1.53"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
@@ -4634,7 +4644,7 @@ dependencies = [
|
||||
"ide-extension",
|
||||
"ide-text",
|
||||
"memchr",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"regex-lite",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4699,7 +4709,7 @@ dependencies = [
|
||||
"ide-vfs",
|
||||
"ignore",
|
||||
"lsp-types",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"percent-encoding",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4739,7 +4749,7 @@ dependencies = [
|
||||
"jupyter-protocol",
|
||||
"jupyter-zmq-client",
|
||||
"libc",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4759,7 +4769,7 @@ dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
"ide-extension",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4798,7 +4808,7 @@ dependencies = [
|
||||
"ide-run",
|
||||
"ide-ssh",
|
||||
"ignore",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4818,7 +4828,7 @@ dependencies = [
|
||||
"ide-language",
|
||||
"ide-workspace",
|
||||
"libc",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"portable-pty",
|
||||
"quick-xml 0.42.0",
|
||||
"serde",
|
||||
@@ -4900,7 +4910,7 @@ name = "ide-spell"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4917,7 +4927,7 @@ dependencies = [
|
||||
"ide-core",
|
||||
"keyring",
|
||||
"keyring-core",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"russh",
|
||||
"russh-sftp",
|
||||
"rustls",
|
||||
@@ -4967,7 +4977,7 @@ version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"portable-pty",
|
||||
"serde",
|
||||
"specta",
|
||||
@@ -4999,7 +5009,7 @@ dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
"libc",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
@@ -5046,7 +5056,7 @@ dependencies = [
|
||||
"ide-core",
|
||||
"ignore",
|
||||
"notify",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"rayon",
|
||||
"rustix",
|
||||
"serde",
|
||||
@@ -5087,7 +5097,7 @@ dependencies = [
|
||||
"ide-core",
|
||||
"ide-text",
|
||||
"ide-vfs",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -5241,7 +5251,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f"
|
||||
dependencies = [
|
||||
"io-lifetimes 3.0.1",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5279,7 +5289,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"
|
||||
dependencies = [
|
||||
"hermit-abi",
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5779,6 +5789,15 @@ dependencies = [
|
||||
"scopeguard",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lock_api"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65d91b22da179613dcf4d6ec8349563f52a363f6849e03b00dd0a185ec4a59af"
|
||||
dependencies = [
|
||||
"scopeguard",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.34"
|
||||
@@ -6750,7 +6769,7 @@ dependencies = [
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2-web-kit 0.3.2",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"percent-encoding",
|
||||
"reqwest",
|
||||
"security-framework",
|
||||
@@ -6940,8 +6959,18 @@ version = "0.12.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
|
||||
dependencies = [
|
||||
"lock_api",
|
||||
"parking_lot_core",
|
||||
"lock_api 0.4.14",
|
||||
"parking_lot_core 0.9.12",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a9cf937ca4e1d0b7578784559063422fc39ae7c5a00f02471f2614d5486fd226"
|
||||
dependencies = [
|
||||
"lock_api 0.5.0",
|
||||
"parking_lot_core 0.10.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6952,7 +6981,19 @@ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"redox_syscall",
|
||||
"redox_syscall 0.5.18",
|
||||
"smallvec",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot_core"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9cfff060068cc18aa7815010fcaf80c68c7fb9e85fc7f5c0f9bf142c21d19826"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"redox_syscall 0.9.5",
|
||||
"smallvec",
|
||||
"windows-link",
|
||||
]
|
||||
@@ -7403,7 +7444,7 @@ version = "31.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf52d87428247c5aa3760ac8e7d8b13ec7b3579b955a8c3f311668b6860acba5"
|
||||
dependencies = [
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7599,6 +7640,15 @@ dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_syscall"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_users"
|
||||
version = "0.5.3"
|
||||
@@ -7638,7 +7688,7 @@ dependencies = [
|
||||
"ahash",
|
||||
"fluent-uri 0.3.2",
|
||||
"once_cell",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"percent-encoding",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -7972,7 +8022,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8040,7 +8090,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8714,7 +8764,7 @@ dependencies = [
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2-quartz-core 0.3.2",
|
||||
"raw-window-handle",
|
||||
"redox_syscall",
|
||||
"redox_syscall 0.5.18",
|
||||
"tracing",
|
||||
"wasm-bindgen",
|
||||
"web-sys",
|
||||
@@ -8814,7 +8864,7 @@ version = "0.9.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
|
||||
dependencies = [
|
||||
"lock_api",
|
||||
"lock_api 0.4.14",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9088,7 +9138,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901"
|
||||
dependencies = [
|
||||
"new_debug_unreachable",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"phf_shared",
|
||||
"precomputed-hash",
|
||||
]
|
||||
@@ -9276,7 +9326,7 @@ dependencies = [
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2-ui-kit 0.3.2",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"percent-encoding",
|
||||
"raw-window-handle",
|
||||
"tao-macros",
|
||||
@@ -9784,10 +9834,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.3.4",
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9967,7 +10017,7 @@ dependencies = [
|
||||
"bytes",
|
||||
"libc",
|
||||
"mio",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"pin-project-lite",
|
||||
"signal-hook-registry",
|
||||
"socket2",
|
||||
@@ -11624,7 +11674,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -12422,7 +12472,7 @@ dependencies = [
|
||||
"log",
|
||||
"num-traits",
|
||||
"once_cell",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"rand 0.9.5",
|
||||
"regex",
|
||||
"scc",
|
||||
|
||||
+1
-1
@@ -108,7 +108,7 @@ jupyter-zmq-client = { version = "=2.0.0", default-features = false, features =
|
||||
jupyter-protocol = "=2.0.3"
|
||||
zeromq = { version = "0.6", default-features = false, features = ["tokio-runtime", "tcp-transport"] }
|
||||
lsp-types = "0.97"
|
||||
gix = { version = "0.89", default-features = false }
|
||||
gix = { version = "0.90", default-features = false }
|
||||
portable-pty = "0.9"
|
||||
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "http2", "charset", "socks", "gzip", "deflate", "brotli"] }
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
|
||||
|
||||
@@ -443,7 +443,15 @@ fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
|
||||
|
||||
/// Installs (or updates to) the registry's current version of `id`, streaming progress
|
||||
/// through `emit`, and points the agent file at it.
|
||||
pub fn install(paths: &RegistryPaths, id: &str, cancel: &CancellationToken, emit: Emit) -> IdeResult<()> {
|
||||
/// Installs agent `id`; an npm package retries against the public npm registry when the
|
||||
/// configured one misses it only with `public_npm_fallback`.
|
||||
pub fn install(
|
||||
paths: &RegistryPaths,
|
||||
id: &str,
|
||||
public_npm_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
let id = canonical_id(id);
|
||||
// The saved index is what the user picked from; fetch only when there is none.
|
||||
let text = match fs::read_to_string(&paths.cache_file) {
|
||||
@@ -455,9 +463,14 @@ pub fn install(paths: &RegistryPaths, id: &str, cancel: &CancellationToken, emit
|
||||
.iter()
|
||||
.find(|e| e.id == id)
|
||||
.ok_or_else(|| IdeError::not_found(format!("{id} is not in the ACP Registry")))?;
|
||||
install_entry(paths, entry, Platform::current(), &on_path, cancel, emit)
|
||||
let npm_installer =
|
||||
move |p: &Package, entry: &Entry, dir: &Path, platform, cancel: &CancellationToken, emit: Emit| {
|
||||
install_npm(p, entry, dir, platform, public_npm_fallback, cancel, emit)
|
||||
};
|
||||
install_entry_with(paths, entry, Platform::current(), &on_path, &npm_installer, cancel, emit)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn install_entry(
|
||||
paths: &RegistryPaths,
|
||||
entry: &Entry,
|
||||
@@ -466,7 +479,10 @@ fn install_entry(
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
install_entry_with(paths, entry, platform, on_path, &install_npm, cancel, emit)
|
||||
let npm_installer = |p: &Package, entry: &Entry, dir: &Path, platform, cancel: &CancellationToken, emit: Emit| {
|
||||
install_npm(p, entry, dir, platform, true, cancel, emit)
|
||||
};
|
||||
install_entry_with(paths, entry, platform, on_path, &npm_installer, cancel, emit)
|
||||
}
|
||||
|
||||
type NpmInstaller = dyn Fn(&Package, &Entry, &Path, Platform, &CancellationToken, Emit) -> IdeResult<PathBuf>;
|
||||
@@ -663,20 +679,23 @@ fn install_npm(
|
||||
entry: &Entry,
|
||||
dir: &Path,
|
||||
platform: Platform,
|
||||
public_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
let (name, _) = split_npm_spec(&p.package);
|
||||
let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?;
|
||||
install_npm_with(&npm, p, entry, dir, platform, cancel, emit)
|
||||
install_npm_with(&npm, p, entry, dir, platform, public_fallback, cancel, emit)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn install_npm_with(
|
||||
npm: &Path,
|
||||
p: &Package,
|
||||
entry: &Entry,
|
||||
dir: &Path,
|
||||
platform: Platform,
|
||||
public_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
@@ -704,6 +723,7 @@ fn install_npm_with(
|
||||
},
|
||||
&specs,
|
||||
false,
|
||||
public_fallback,
|
||||
cancel,
|
||||
emit,
|
||||
)?;
|
||||
@@ -1004,7 +1024,7 @@ mod tests {
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss() {
|
||||
fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss_unless_registries_are_configured_only() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let install_dir = dir.path().join("acme/1.2.0");
|
||||
fs::create_dir_all(&install_dir).unwrap();
|
||||
@@ -1043,8 +1063,8 @@ esac
|
||||
]}"#;
|
||||
let entry = parse(index).unwrap().remove(0);
|
||||
let pkg = entry.distribution.npx.as_ref().unwrap();
|
||||
let exe =
|
||||
install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
let exe = install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, true, &CancellationToken::new(), &|_| {})
|
||||
.unwrap();
|
||||
let calls: Vec<String> = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect();
|
||||
assert_eq!(calls.len(), 2, "{calls:?}");
|
||||
assert!(!calls[0].contains("--registry="), "{calls:?}");
|
||||
@@ -1052,6 +1072,15 @@ esac
|
||||
assert!(calls[1].contains("--@acme:registry=https://registry.npmjs.org/"), "{calls:?}");
|
||||
assert_eq!(exe, install_dir.join("node_modules/.bin/agent-acp"));
|
||||
assert!(exe.is_file());
|
||||
// Only the configured registries: the miss is the error, and npmjs is never asked.
|
||||
let only = dir.path().join("acme-only/1.2.0");
|
||||
fs::create_dir_all(&only).unwrap();
|
||||
let err =
|
||||
install_npm_with(&npm, pkg, &entry, &only, MAC_ARM, false, &CancellationToken::new(), &|_| {}).unwrap_err();
|
||||
let calls: Vec<String> = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect();
|
||||
assert_eq!(calls.len(), 3, "{calls:?}");
|
||||
assert!(!calls[2].contains("--registry="), "{calls:?}");
|
||||
assert!(err.message.contains("notarget"), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -486,6 +486,16 @@ pub struct LanguageCodeStyle {
|
||||
/// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub identifier_case: Option<String>,
|
||||
/// Java: organize imports switches to a wildcard import once this many
|
||||
/// classes of one package are used (jdtls `starThreshold`; IDEA's default
|
||||
/// 5; unset keeps the language server's default).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub class_count_to_use_import_with_star: Option<u32>,
|
||||
/// Java: organize imports switches to a wildcard static import once this
|
||||
/// many statically imported names are used (jdtls `staticStarThreshold`;
|
||||
/// IDEA's default 3; unset keeps the language server's default).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub names_count_to_use_static_import_with_star: Option<u32>,
|
||||
/// JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub semicolons: Option<String>,
|
||||
|
||||
@@ -432,6 +432,12 @@ pub struct ToolDownloadSettings {
|
||||
/// commas or whitespace and tried in order before the official host; empty keeps every
|
||||
/// download on its official host.
|
||||
pub github_mirror: String,
|
||||
/// Package registries only as configured (a company Nexus or Artifactory): npm and pnpm
|
||||
/// installs and update checks never retry against the public npm registry, and the IDE
|
||||
/// fetches nothing from public package registries itself (the JUnit Platform launcher from
|
||||
/// Maven Central, dependency version completion from Maven Central, npm, PyPI and
|
||||
/// crates.io). Off by default.
|
||||
pub configured_registries_only: bool,
|
||||
}
|
||||
|
||||
/// Absent profiles retain automatic discovery for existing projects.
|
||||
|
||||
@@ -157,6 +157,10 @@ pub struct ColumnInfo {
|
||||
pub nullable: bool,
|
||||
pub default: Option<String>,
|
||||
pub primary_key: bool,
|
||||
/// `None` when it has none, or the engine keeps no comments.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -172,6 +176,10 @@ pub struct IndexInfo {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(rename = "DbTableDetails")]
|
||||
pub struct TableDetails {
|
||||
/// The table's comment; `None` when it has none, or the engine keeps no comments.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub comment: Option<String>,
|
||||
pub columns: Vec<ColumnInfo>,
|
||||
pub indexes: Vec<IndexInfo>,
|
||||
pub foreign_keys: Vec<ForeignKey>,
|
||||
@@ -1119,11 +1127,18 @@ impl DbManager {
|
||||
let nullable = flag(&it.next().flatten());
|
||||
let default = it.next().flatten();
|
||||
let primary_key = flag(&it.next().flatten());
|
||||
Some(ColumnInfo { name, data_type, nullable, default, primary_key })
|
||||
let comment = it.next().flatten().filter(|c| !c.is_empty());
|
||||
Some(ColumnInfo { name, data_type, nullable, default, primary_key, comment })
|
||||
})
|
||||
.collect();
|
||||
if driver == DbDriver::Jdbc {
|
||||
return Ok(TableDetails { columns, indexes: vec![], foreign_keys: vec![], triggers: vec![] });
|
||||
return Ok(TableDetails {
|
||||
comment: None,
|
||||
columns,
|
||||
indexes: vec![],
|
||||
foreign_keys: vec![],
|
||||
triggers: vec![],
|
||||
});
|
||||
}
|
||||
let mut indexes: Vec<IndexInfo> = Vec::new();
|
||||
for r in pool.rows(&sql::indexes(driver, schema, table), MAX_META_ROWS).await? {
|
||||
@@ -1175,7 +1190,17 @@ impl DbManager {
|
||||
Some(TriggerInfo { name, timing, events })
|
||||
})
|
||||
.collect();
|
||||
Ok(TableDetails { columns, indexes, foreign_keys, triggers })
|
||||
let comment = match sql::table_comment(driver, schema, table) {
|
||||
Some(q) => pool.rows(&q, 1).await.map_or_else(
|
||||
|e| {
|
||||
tracing::warn!("table comment: {}", e.message);
|
||||
None
|
||||
},
|
||||
|rows| rows.into_iter().next().and_then(|r| r.into_iter().next().flatten()).filter(|c| !c.is_empty()),
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
Ok(TableDetails { comment, columns, indexes, foreign_keys, triggers })
|
||||
}
|
||||
|
||||
/// The object privileges granted on `table`; empty, without a query, on the engines
|
||||
|
||||
@@ -132,6 +132,7 @@ pub(crate) async fn table_details(pool: &SnowflakePool, schema: &str, table: &st
|
||||
nullable: yes(r.get("null?")),
|
||||
default: r.get("default").filter(|d| !d.is_empty()).map(str::to_owned),
|
||||
primary_key: yes(r.get("primary key")),
|
||||
comment: r.get("comment").filter(|c| !c.is_empty()).map(str::to_owned),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
@@ -140,7 +141,16 @@ pub(crate) async fn table_details(pool: &SnowflakePool, schema: &str, table: &st
|
||||
Ok(keys) => foreign_keys(&keys),
|
||||
Err(_) => Vec::new(),
|
||||
};
|
||||
Ok(TableDetails { columns, indexes: Vec::new(), foreign_keys, triggers: Vec::new() })
|
||||
// `LIKE` matches without case and with wildcards: the exact name picks the row.
|
||||
let like = format!("SHOW TABLES LIKE {} IN SCHEMA {}", quote_literal(DRIVER, table), schema_path(pool, schema));
|
||||
let comment = match show(pool, &like).await {
|
||||
Ok(shown) => shown
|
||||
.records()
|
||||
.find(|r| r.get("name") == Some(table))
|
||||
.and_then(|r| r.get("comment").filter(|c| !c.is_empty()).map(str::to_owned)),
|
||||
Err(_) => None,
|
||||
};
|
||||
Ok(TableDetails { comment, columns, indexes: Vec::new(), foreign_keys, triggers: Vec::new() })
|
||||
}
|
||||
|
||||
fn foreign_keys(shown: &Shown) -> Vec<ForeignKey> {
|
||||
|
||||
@@ -145,7 +145,8 @@ const SNOWFLAKE_TYPE: &str = "CASE WHEN data_type = 'NUMBER' THEN 'NUMBER(' || n
|
||||
WHEN data_type = 'TEXT' THEN 'VARCHAR(' || character_maximum_length || ')' \
|
||||
WHEN data_type LIKE 'TIME%' THEN data_type || '(' || datetime_precision || ')' ELSE data_type END";
|
||||
|
||||
/// Rows: `name, type, nullable (YES/NO or 0/1), default, is_pk (0/1)`.
|
||||
/// Rows: `name, type, nullable (YES/NO or 0/1), default, is_pk (0/1)`, and the column's
|
||||
/// comment on the engines that keep one (PostgreSQL, MySQL, Oracle, ClickHouse).
|
||||
pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
|
||||
match driver {
|
||||
@@ -153,7 +154,7 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
DbDriver::Clickhouse => format!(
|
||||
"SELECT name, type, CASE WHEN startsWith(type, 'Nullable(') \
|
||||
OR startsWith(type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, \
|
||||
if(default_kind = '', NULL, default_expression), is_in_primary_key \
|
||||
if(default_kind = '', NULL, default_expression), is_in_primary_key, comment \
|
||||
FROM system.columns WHERE database = {s} AND table = {t} ORDER BY position"
|
||||
),
|
||||
DbDriver::Sqlite => format!(
|
||||
@@ -166,13 +167,14 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name \
|
||||
AND k.table_schema = tc.table_schema AND k.table_name = tc.table_name \
|
||||
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = c.table_schema \
|
||||
AND tc.table_name = c.table_name AND k.column_name = c.column_name) THEN 1 ELSE 0 END \
|
||||
AND tc.table_name = c.table_name AND k.column_name = c.column_name) THEN 1 ELSE 0 END, \
|
||||
col_description(format('%I.%I', c.table_schema, c.table_name)::regclass, c.ordinal_position::int) \
|
||||
FROM information_schema.columns c WHERE c.table_schema = {s} AND c.table_name = {t} \
|
||||
ORDER BY c.ordinal_position"
|
||||
),
|
||||
DbDriver::Mysql => format!(
|
||||
"SELECT column_name, column_type, is_nullable, column_default, \
|
||||
CASE WHEN column_key = 'PRI' THEN 1 ELSE 0 END \
|
||||
CASE WHEN column_key = 'PRI' THEN 1 ELSE 0 END, column_comment \
|
||||
FROM information_schema.columns WHERE table_schema = {s} AND table_name = {t} \
|
||||
ORDER BY ordinal_position"
|
||||
),
|
||||
@@ -192,8 +194,10 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
),
|
||||
DbDriver::Oracle => format!(
|
||||
"SELECT c.column_name, c.data_type, DECODE(c.nullable, 'Y', 'YES', 'NO'), c.data_default, \
|
||||
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END \
|
||||
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END, cc.comments \
|
||||
FROM all_tab_columns c \
|
||||
LEFT JOIN all_col_comments cc ON cc.owner = c.owner AND cc.table_name = c.table_name \
|
||||
AND cc.column_name = c.column_name \
|
||||
LEFT JOIN (SELECT kc.column_name FROM all_constraints con \
|
||||
JOIN all_cons_columns kc ON kc.owner = con.owner AND kc.table_name = con.table_name \
|
||||
AND kc.constraint_name = con.constraint_name \
|
||||
@@ -204,6 +208,28 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// One row, one column: the table's comment (`NULL` or empty for none). `None` for the
|
||||
/// engines whose comments the IDE doesn't read here (Snowflake reads it with `SHOW`).
|
||||
pub fn table_comment(driver: DbDriver, schema: &str, table: &str) -> Option<String> {
|
||||
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
|
||||
match driver {
|
||||
DbDriver::Postgres => Some(format!(
|
||||
"SELECT obj_description(c.oid, 'pg_class') FROM pg_class c \
|
||||
JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = {s} AND c.relname = {t}"
|
||||
)),
|
||||
// A view's `table_comment` is the word `VIEW`.
|
||||
DbDriver::Mysql => Some(format!(
|
||||
"SELECT CASE WHEN table_type = 'VIEW' THEN NULL ELSE table_comment END \
|
||||
FROM information_schema.tables WHERE table_schema = {s} AND table_name = {t}"
|
||||
)),
|
||||
DbDriver::Oracle => {
|
||||
Some(format!("SELECT comments FROM all_tab_comments WHERE owner = {s} AND table_name = {t}"))
|
||||
}
|
||||
DbDriver::Clickhouse => Some(format!("SELECT comment FROM system.tables WHERE database = {s} AND name = {t}")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Rows: `index name, unique (0/1), column` (one row per indexed column, in order).
|
||||
// Key columns are paired from one series up to `max_index_keys` (the server's INDEX_MAX_KEYS, the
|
||||
// most columns an index or key has): unlike a series per catalog row, it lets the planner find the
|
||||
@@ -956,6 +982,22 @@ mod tests {
|
||||
assert_eq!(quote_literal(DbDriver::Mysql, "it's \\"), "'it''s \\\\'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_are_read_where_the_engine_keeps_them() {
|
||||
assert!(columns(DbDriver::Postgres, "public", "t").contains("col_description("));
|
||||
assert!(columns(DbDriver::Mysql, "db", "t").contains("column_comment"));
|
||||
assert!(columns(DbDriver::Oracle, "S", "T").contains("all_col_comments"));
|
||||
assert!(columns(DbDriver::Clickhouse, "db", "t").contains("is_in_primary_key, comment"));
|
||||
let pg = table_comment(DbDriver::Postgres, "public", "o'rders").unwrap();
|
||||
assert!(pg.contains("obj_description(c.oid, 'pg_class')") && pg.contains("'o''rders'"), "{pg}");
|
||||
assert!(table_comment(DbDriver::Mysql, "db", "t").unwrap().contains("table_comment"));
|
||||
assert!(table_comment(DbDriver::Oracle, "S", "T").unwrap().contains("all_tab_comments"));
|
||||
assert!(table_comment(DbDriver::Clickhouse, "db", "t").unwrap().contains("system.tables"));
|
||||
for driver in [DbDriver::Sqlite, DbDriver::SqlServer, DbDriver::Snowflake] {
|
||||
assert_eq!(table_comment(driver, "s", "t"), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clickhouse_escapes_backslashes_and_delimiters() {
|
||||
let driver = DbDriver::Clickhouse;
|
||||
|
||||
@@ -40,7 +40,8 @@ async fn create_schemas(db: &DbManager) {
|
||||
format!("DROP DATABASE IF EXISTS `{s}`"),
|
||||
format!("CREATE DATABASE `{s}` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"),
|
||||
format!(
|
||||
"CREATE TABLE `{s}`.`用户` (id INT PRIMARY KEY, name VARCHAR(20) COLLATE utf8mb4_bin, raw VARBINARY(4))"
|
||||
"CREATE TABLE `{s}`.`用户` (id INT PRIMARY KEY, name VARCHAR(20) COLLATE utf8mb4_bin COMMENT '名字', \
|
||||
raw VARBINARY(4)) COMMENT = '用户表'"
|
||||
),
|
||||
format!("CREATE INDEX `名字` ON `{s}`.`用户` (name)"),
|
||||
format!("INSERT INTO `{s}`.`用户` VALUES (1, 'ann', 0xCAFE)"),
|
||||
@@ -59,6 +60,9 @@ async fn assert_metadata_is_text(db: &DbManager) -> IdeResult<()> {
|
||||
let d = db.table_details("m", s, "用户").await?;
|
||||
let cols: Vec<_> = d.columns.iter().map(|c| c.name.as_str()).collect();
|
||||
assert_eq!(cols, ["id", "name", "raw"]);
|
||||
assert_eq!(d.comment.as_deref(), Some("用户表"));
|
||||
let comments: Vec<_> = d.columns.iter().map(|c| c.comment.as_deref()).collect();
|
||||
assert_eq!(comments, [None, Some("名字"), None]);
|
||||
assert!(d.indexes.iter().any(|i| i.name == "名字"), "{:?}", d.indexes);
|
||||
assert!(db.ddl("m", s, "用户").await?.contains("CREATE TABLE `用户`"));
|
||||
}
|
||||
|
||||
@@ -338,6 +338,8 @@ async fn table_details_routines_and_completion_on_older_catalogs() -> IdeResult<
|
||||
"CREATE TABLE oi_meta.lines (n INT PRIMARY KEY, o_region INT, o_id INT, \
|
||||
FOREIGN KEY (o_region, o_id) REFERENCES oi_meta.orders (region, id))",
|
||||
"CREATE INDEX lines_order ON oi_meta.lines (o_id, o_region)",
|
||||
"COMMENT ON TABLE oi_meta.orders IS 'Customer''s orders'",
|
||||
"COMMENT ON COLUMN oi_meta.orders.note IS 'Free text'",
|
||||
"CREATE FUNCTION oi_meta.twice(v INT) RETURNS INT AS 'SELECT v * 2' LANGUAGE sql",
|
||||
] {
|
||||
db.execute("p", stmt, 10, &c).await?;
|
||||
@@ -350,6 +352,10 @@ async fn table_details_routines_and_completion_on_older_catalogs() -> IdeResult<
|
||||
assert_eq!(details.foreign_keys[0].columns, ["o_region", "o_id"]);
|
||||
assert_eq!(details.foreign_keys[0].ref_columns, ["region", "id"]);
|
||||
let orders = db.table_details("p", "oi_meta", "orders").await?;
|
||||
assert_eq!(orders.comment.as_deref(), Some("Customer's orders"));
|
||||
let comments: Vec<_> = orders.columns.iter().map(|c| c.comment.as_deref()).collect();
|
||||
assert_eq!(comments, [None, None, Some("Free text")]);
|
||||
assert_eq!(details.comment, None);
|
||||
let key = orders.indexes.iter().find(|i| i.unique).expect("primary key index");
|
||||
assert_eq!(key.columns, ["region", "id"]);
|
||||
|
||||
|
||||
@@ -701,6 +701,12 @@ impl Host {
|
||||
self.requests.begin(id)
|
||||
}
|
||||
|
||||
/// Settings › Tools › Download Mirrors › Use only the configured package registries: nothing
|
||||
/// is fetched from public package registries the user's tools weren't pointed at.
|
||||
pub fn configured_registries_only(&self) -> bool {
|
||||
self.global_settings.effective().tool_downloads.configured_registries_only
|
||||
}
|
||||
|
||||
pub fn begin_project_request(&self, window: &str, id: RequestId) -> CancellationToken {
|
||||
let token = self.begin_project_read_request(window, id);
|
||||
if self.project(window).is_ok_and(|p| !p.is_trusted()) {
|
||||
|
||||
@@ -185,6 +185,7 @@ pub async fn agent_registry_install(
|
||||
) -> IdeResult<()> {
|
||||
// The agent then shows in `agent_providers`.
|
||||
let paths = registry_paths(host);
|
||||
let public_npm_fallback = !host.configured_registries_only();
|
||||
let installing = Installing::begin(&id)?;
|
||||
let cancel = host.begin_request(request);
|
||||
// Also a background task of every project window, so it stays visible and can be
|
||||
@@ -211,7 +212,7 @@ pub async fn agent_registry_install(
|
||||
move || cancel.cancel()
|
||||
});
|
||||
report(None, None, false);
|
||||
let result = ide_agent::registry::install(&paths, &id, &cancel, &|e| {
|
||||
let result = ide_agent::registry::install(&paths, &id, public_npm_fallback, &cancel, &|e| {
|
||||
match &e {
|
||||
InstallEvent::Line { text } => report(Some(text.clone()), None, false),
|
||||
InstallEvent::Progress { fraction, message } => {
|
||||
|
||||
@@ -767,6 +767,7 @@ pub async fn maven_dependency_completion(
|
||||
use ide_build::maven::completion::{PomCompletionKind, local_options};
|
||||
let project = host.project(window)?;
|
||||
let cache = host.dependency_versions.clone();
|
||||
let central = !host.configured_registries_only();
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = host
|
||||
.blocking(move || {
|
||||
@@ -785,7 +786,10 @@ pub async fn maven_dependency_completion(
|
||||
// The local repository answers at once: Central gets `CENTRAL_WAIT`, then the
|
||||
// lookup finishes in the background and fills the cache for the next request.
|
||||
// Offline, behind a proxy or rate-limited, a failed fetch never fails completion.
|
||||
let remote = {
|
||||
// Only the configured package registries: the local repository alone.
|
||||
let remote = if !central {
|
||||
Vec::new()
|
||||
} else {
|
||||
let (cache, target) = (cache.clone(), target.clone());
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
|
||||
@@ -212,6 +212,8 @@ pub async fn dependency_versions(
|
||||
let project = host.project(window)?;
|
||||
let cache = host.dependency_versions.clone();
|
||||
let config_dir = host.config_dir.clone();
|
||||
// npm and crates.io are asked directly; `go` goes through the configured GOPROXY.
|
||||
let public_registries = !host.configured_registries_only();
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = host
|
||||
.blocking(move || {
|
||||
@@ -228,6 +230,9 @@ pub async fn dependency_versions(
|
||||
let versions = cache.versions(&source, &dependency.package, &cancel)?;
|
||||
return Ok(vec![DependencyVersions { dependency, versions, update: None }]);
|
||||
}
|
||||
if !public_registries {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
if snap.path.file_name().is_some_and(|name| name == "package.json") {
|
||||
let Some(dependency) = offset.and_then(|offset| npm::dependency_at(&snap.text, offset)) else {
|
||||
return Ok(Vec::new());
|
||||
@@ -310,6 +315,9 @@ pub async fn pypi_package(
|
||||
request: RequestId,
|
||||
) -> IdeResult<Option<pypi::PypiPackage>> {
|
||||
let url = pypi::project_url(name.trim()).ok_or_else(|| IdeError::invalid("not a package name"))?;
|
||||
if host.configured_registries_only() {
|
||||
return Ok(None);
|
||||
}
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = host
|
||||
.blocking(move || {
|
||||
@@ -334,6 +342,9 @@ pub async fn pypi_package(
|
||||
/// PyPI's name list, which the first search downloads and a search a day later refreshes.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn pypi_search(host: &Host, window: &str, query: String, request: RequestId) -> IdeResult<Vec<String>> {
|
||||
if host.configured_registries_only() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let names = host.pypi_names.clone();
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = host
|
||||
|
||||
@@ -142,7 +142,8 @@ pub(crate) async fn resolve_launch(
|
||||
};
|
||||
if let Some(outputs) = built {
|
||||
progress("Resolving the classpath");
|
||||
let mut info = project.lsp.java_launch(&module, test, false, false, false, cancel).await?;
|
||||
let server = project.lsp.java_launch(&module, test, false, false, false, cancel);
|
||||
let mut info = server_launch_extras(server, SERVER_EXTRAS_WAIT).await?;
|
||||
let data_dir = host.local_data_dir.clone();
|
||||
let cancel = cancel.clone();
|
||||
return tokio::task::spawn_blocking(move || {
|
||||
@@ -393,6 +394,33 @@ fn is_maven_aggregator(root: &Path, model: &BuildModel, module: &Path) -> bool {
|
||||
/// Whether the IDE's Java build builds the module holding `path` (#4078): a Maven module unless
|
||||
/// Settings › Maven › Delegate IDE build/run actions to Maven asks for Maven; a Gradle module
|
||||
/// when Settings › Gradle › Build and run using asks for the IDE.
|
||||
/// How long a launch whose classpath the IDE's Java build resolved waits for what jdtls adds
|
||||
/// (the JDK it compiles against, the Java project root). jdtls can be busy for minutes importing
|
||||
/// a Maven project (resolving plugin dependencies), and the run doesn't need it:
|
||||
/// [`finish_launch`] picks the project's JDK or an installed one.
|
||||
const SERVER_EXTRAS_WAIT: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
/// jdtls' launch info, or an empty one when it doesn't answer within `wait` or fails.
|
||||
async fn server_launch_extras(
|
||||
server: impl std::future::Future<Output = IdeResult<JavaLaunchInfo>>,
|
||||
wait: std::time::Duration,
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
let fallback =
|
||||
|| JavaLaunchInfo { path_list_separator: if cfg!(windows) { ";" } else { ":" }.into(), ..Default::default() };
|
||||
match tokio::time::timeout(wait, server).await {
|
||||
Ok(Ok(info)) => Ok(info),
|
||||
Ok(Err(e)) if e.kind == ErrorKind::Cancelled => Err(e),
|
||||
Ok(Err(e)) => {
|
||||
tracing::warn!("Java launch without the language server's JDK: {}", e.message);
|
||||
Ok(fallback())
|
||||
}
|
||||
Err(_) => {
|
||||
tracing::info!(wait_ms = wait.as_millis(), "Java language server busy; launching without its JDK");
|
||||
Ok(fallback())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn served_by_service(root: &Path, model: &BuildModel, settings: &Settings, path: &Path) -> bool {
|
||||
let maven = model.maven.iter().flat_map(|m| m.projects.iter().map(|p| (root.join(&p.dir), true)));
|
||||
let gradle = model.gradle.iter().flat_map(|g| g.projects.iter().map(|p| (root.join(&p.dir), false)));
|
||||
@@ -922,7 +950,7 @@ pub async fn java_build_workspace(
|
||||
/// The JVM of OpenIDEA's JUnit runner for the module at `module`, given its resolved test classpath:
|
||||
/// the classpath with the runner and `junit-platform-launcher` of the engine's version (unless the
|
||||
/// classpath has one, or has JUnit 4 alone; from the engine's repository, else downloaded once from
|
||||
/// Maven Central), and,
|
||||
/// Maven Central unless only the configured package registries are allowed), and,
|
||||
/// for a Maven module, what its Surefire configuration gives the forked test JVM.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn java_junit_runner(
|
||||
@@ -935,6 +963,7 @@ pub async fn java_junit_runner(
|
||||
let project = host.project(window)?;
|
||||
let module = ide_core::project_roots::resolve(&project.root, &module);
|
||||
let data_dir = host.local_data_dir.clone();
|
||||
let registries_only = host.configured_registries_only();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let scope = workspace::scope_for(&project, &module)?;
|
||||
let model = load_launch_model(&scope);
|
||||
@@ -948,7 +977,9 @@ pub async fn java_junit_runner(
|
||||
let launcher = match ide_sdk::java::junit_launcher(&class_paths) {
|
||||
ide_sdk::java::JunitLauncher::OnClasspath | ide_sdk::java::JunitLauncher::Junit4 => None,
|
||||
ide_sdk::java::JunitLauncher::Found(path) => Some(path),
|
||||
ide_sdk::java::JunitLauncher::Missing(version) => Some(download_junit_launcher(&data_dir, &version)?),
|
||||
ide_sdk::java::JunitLauncher::Missing(version) => {
|
||||
Some(download_junit_launcher(&data_dir, &version, registries_only)?)
|
||||
}
|
||||
ide_sdk::java::JunitLauncher::NoPlatform => {
|
||||
return Err(IdeError::unavailable(
|
||||
"Neither JUnit 5 (junit-platform-engine) nor JUnit 4 is on the test classpath. To run these tests \
|
||||
@@ -1017,7 +1048,9 @@ fn junit_launch(
|
||||
}
|
||||
}
|
||||
|
||||
fn download_junit_launcher(data_dir: &Path, version: &str) -> IdeResult<PathBuf> {
|
||||
/// The launcher jar downloaded once from Maven Central; with only the configured package
|
||||
/// registries allowed (Settings › Tools › Download Mirrors), only one downloaded before.
|
||||
fn download_junit_launcher(data_dir: &Path, version: &str, registries_only: bool) -> IdeResult<PathBuf> {
|
||||
if version.is_empty() || !version.chars().all(|c| c.is_ascii_alphanumeric() || "._-".contains(c)) {
|
||||
return Err(IdeError::invalid(format!("Unexpected JUnit Platform version '{version}'")));
|
||||
}
|
||||
@@ -1026,6 +1059,14 @@ fn download_junit_launcher(data_dir: &Path, version: &str) -> IdeResult<PathBuf>
|
||||
if dest.is_file() {
|
||||
return Ok(dest);
|
||||
}
|
||||
if registries_only {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"{name} is not on the test classpath, and Settings › Tools › Download Mirrors allows only the \
|
||||
configured package registries, so it is not downloaded from Maven Central. Add \
|
||||
org.junit.platform:junit-platform-launcher to the test dependencies, or set Settings › Build Tools › \
|
||||
Maven › Run tests using to Maven."
|
||||
)));
|
||||
}
|
||||
std::fs::create_dir_all(dest.parent().expect("has a parent"))?;
|
||||
let url = format!("https://repo1.maven.org/maven2/org/junit/platform/junit-platform-launcher/{version}/{name}");
|
||||
let partial = dest.with_extension("jar.part");
|
||||
@@ -1060,6 +1101,22 @@ fn drop_processor_recreate_errors(info: &mut JavaLaunchInfo) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_busy_or_failing_language_server_does_not_block_a_resolved_launch() {
|
||||
let wait = std::time::Duration::from_secs(5);
|
||||
// jdtls importing a Maven project: no answer for minutes (#6122).
|
||||
let busy = server_launch_extras(std::future::pending(), wait).await.unwrap();
|
||||
assert!(busy.java_home.is_none() && busy.class_paths.is_empty());
|
||||
assert!(!busy.path_list_separator.is_empty());
|
||||
let failed = server_launch_extras(async { Err(IdeError::unavailable("timed out")) }, wait).await.unwrap();
|
||||
assert!(failed.java_home.is_none());
|
||||
let home = JavaLaunchInfo { java_home: Some(PathBuf::from("/jdk").into()), ..Default::default() };
|
||||
let answered = server_launch_extras(async { Ok(home) }, wait).await.unwrap();
|
||||
assert!(answered.java_home.is_some());
|
||||
let cancelled = server_launch_extras(async { Err(IdeError::cancelled()) }, wait).await;
|
||||
assert_eq!(cancelled.unwrap_err().kind, ErrorKind::Cancelled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn junit_launch_applies_the_surefire_configuration() {
|
||||
let surefire = ide_build::surefire::SurefireConfig {
|
||||
|
||||
@@ -217,6 +217,61 @@ impl SecretStore for FileSecretStore {
|
||||
}
|
||||
}
|
||||
|
||||
/// Plugin secrets in the OS credential store (Secret Service, Windows Credential
|
||||
/// Manager), like saved SSH and agent values. Without a credential store a value
|
||||
/// stays in the owner-only [`FileSecretStore`] file, which also still answers for
|
||||
/// values saved there by an older version until they are set again.
|
||||
pub struct CredentialSecretStore {
|
||||
store: ide_ssh::secrets::SecretFile,
|
||||
fallback: FileSecretStore,
|
||||
}
|
||||
|
||||
impl CredentialSecretStore {
|
||||
/// `dir`: the plugins' data directory (the index file and the fallback files live there).
|
||||
pub fn new(dir: PathBuf) -> Self {
|
||||
Self::with_store(ide_ssh::secrets::SecretFile::new(dir.join("plugin-secrets.json")), dir)
|
||||
}
|
||||
|
||||
fn with_store(store: ide_ssh::secrets::SecretFile, dir: PathBuf) -> Self {
|
||||
Self { store, fallback: FileSecretStore { dir } }
|
||||
}
|
||||
|
||||
fn key(plugin: &str, name: &str) -> String {
|
||||
format!("{plugin}/{name}")
|
||||
}
|
||||
|
||||
/// Drops a value from the fallback file, writing it only when it held one.
|
||||
fn forget_fallback(&self, plugin: &str, name: &str) -> Result<(), String> {
|
||||
if self.fallback.get(plugin, name).is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
self.fallback.set(plugin, name, None)
|
||||
}
|
||||
}
|
||||
|
||||
impl SecretStore for CredentialSecretStore {
|
||||
fn get(&self, plugin: &str, name: &str) -> Option<String> {
|
||||
self.store.get(&Self::key(plugin, name)).or_else(|| self.fallback.get(plugin, name))
|
||||
}
|
||||
|
||||
fn set(&self, plugin: &str, name: &str, value: Option<&str>) -> Result<(), String> {
|
||||
let key = Self::key(plugin, name);
|
||||
match value {
|
||||
Some(v) => match self.store.set(&key, v) {
|
||||
Ok(()) => self.forget_fallback(plugin, name),
|
||||
Err(e) => {
|
||||
tracing::warn!("plugin secrets: {key} is kept in the plugin's data directory: {}", e.message);
|
||||
self.fallback.set(plugin, name, Some(v))
|
||||
}
|
||||
},
|
||||
None => {
|
||||
self.store.delete(&key);
|
||||
self.forget_fallback(plugin, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Largest response body a plugin receives.
|
||||
const MAX_RESPONSE: usize = 16 << 20;
|
||||
/// Largest stdout / stderr kept from a process by default.
|
||||
@@ -4210,6 +4265,67 @@ mod tests {
|
||||
assert_eq!(std::fs::read_to_string(&outside).unwrap(), "unchanged");
|
||||
}
|
||||
|
||||
/// Plugin secrets go to the credential store; a value an older version left in
|
||||
/// the owner-only file keeps working until it is set again, and then leaves the file.
|
||||
#[test]
|
||||
fn plugin_secrets_go_to_the_credential_store() {
|
||||
ide_ssh::secrets::testing::use_memory_store();
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path().join("plugins");
|
||||
FileSecretStore { dir: dir.clone() }.set("acme.lint", "old", Some("legacy-3f9a")).unwrap();
|
||||
let secrets = CredentialSecretStore::new(dir.clone());
|
||||
assert_eq!(secrets.get("acme.lint", "old").as_deref(), Some("legacy-3f9a"));
|
||||
|
||||
secrets.set("acme.lint", "token", Some("value-7c1e")).unwrap();
|
||||
secrets.set("acme.lint", "old", Some("moved-5d2b")).unwrap();
|
||||
let on_disk = ide_ssh::secrets::testing::files_containing(tmp.path(), "value-7c1e");
|
||||
assert_eq!(on_disk, Vec::<PathBuf>::new());
|
||||
assert_eq!(ide_ssh::secrets::testing::files_containing(tmp.path(), "legacy-3f9a"), Vec::<PathBuf>::new());
|
||||
let again = CredentialSecretStore::new(dir);
|
||||
assert_eq!(again.get("acme.lint", "token").as_deref(), Some("value-7c1e"));
|
||||
assert_eq!(again.get("acme.lint", "old").as_deref(), Some("moved-5d2b"));
|
||||
assert_eq!(again.get("other.plugin", "token"), None);
|
||||
|
||||
again.set("acme.lint", "token", None).unwrap();
|
||||
assert_eq!(again.get("acme.lint", "token"), None);
|
||||
}
|
||||
|
||||
/// Without a credential store a value stays in the owner-only file.
|
||||
#[test]
|
||||
fn plugin_secrets_without_a_credential_store_stay_in_the_file() {
|
||||
struct NoStore;
|
||||
impl ide_ssh::secrets::Vault for NoStore {
|
||||
fn available(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn get(&self, _: &str, _: &str) -> ide_ssh::secrets::StoreResult<String> {
|
||||
Err(ide_ssh::secrets::StoreError::NoDefaultStore)
|
||||
}
|
||||
fn set(&self, _: &str, _: &str, _: &str) -> ide_ssh::secrets::StoreResult<()> {
|
||||
Err(ide_ssh::secrets::StoreError::NoDefaultStore)
|
||||
}
|
||||
fn delete(&self, _: &str, _: &str) -> ide_ssh::secrets::StoreResult<()> {
|
||||
Err(ide_ssh::secrets::StoreError::NoDefaultStore)
|
||||
}
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path().join("plugins");
|
||||
let store = ide_ssh::secrets::SecretFile::with_vault(
|
||||
dir.join("plugin-secrets.json"),
|
||||
|v| serde_json::from_value(v).ok(),
|
||||
Arc::new(NoStore),
|
||||
);
|
||||
let secrets = CredentialSecretStore::with_store(store, dir.clone());
|
||||
secrets.set("acme.lint", "token", Some("value-7c1e")).unwrap();
|
||||
assert_eq!(
|
||||
ide_ssh::secrets::testing::files_containing(tmp.path(), "value-7c1e"),
|
||||
[dir.join("acme.lint").join("secrets.json")]
|
||||
);
|
||||
assert_eq!(secrets.get("acme.lint", "token").as_deref(), Some("value-7c1e"));
|
||||
secrets.set("acme.lint", "token", None).unwrap();
|
||||
assert_eq!(secrets.get("acme.lint", "token"), None);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn storage_and_secrets_refuse_symlinked_private_directories() {
|
||||
|
||||
@@ -700,7 +700,10 @@ mod tests {
|
||||
// tampered package — and the official host must still be asked.
|
||||
let candidates = mirror::candidates(
|
||||
"https://github.com/acme/hello/releases/download/v1/acme.hello-1.0.0.oiplugin",
|
||||
&ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() },
|
||||
&ide_core::settings::ToolDownloadSettings {
|
||||
github_mirror: "https://gh-proxy.com/".into(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let asked: std::cell::RefCell<Vec<usize>> = std::cell::RefCell::new(Vec::new());
|
||||
let picked = try_sources(&candidates, |index, candidate| {
|
||||
@@ -731,7 +734,10 @@ mod tests {
|
||||
let url = "https://github.com/acme/hello/releases/download/v1/acme.hello-1.0.0.oiplugin";
|
||||
let through = mirror::candidates(
|
||||
url,
|
||||
&ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() },
|
||||
&ide_core::settings::ToolDownloadSettings {
|
||||
github_mirror: "https://gh-proxy.com/".into(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
assert_eq!(through.len(), 2);
|
||||
assert_eq!(through[0].url, format!("https://gh-proxy.com/{url}"));
|
||||
@@ -741,7 +747,10 @@ mod tests {
|
||||
// A local index's own package is not on GitHub: no prefix may carry it.
|
||||
let local = mirror::candidates(
|
||||
"/srv/market/a.oiplugin",
|
||||
&ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() },
|
||||
&ide_core::settings::ToolDownloadSettings {
|
||||
github_mirror: "https://gh-proxy.com/".into(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
assert_eq!(local.len(), 1);
|
||||
assert_eq!(local[0].url, "/srv/market/a.oiplugin");
|
||||
|
||||
@@ -63,7 +63,7 @@ pub mod views;
|
||||
pub mod web;
|
||||
mod websocket;
|
||||
|
||||
pub use api::{FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore};
|
||||
pub use api::{CredentialSecretStore, FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore};
|
||||
pub use build_graph::{BuildGraph, GradleModule};
|
||||
pub(crate) use hover::merge as merge_hover;
|
||||
pub use icons::{
|
||||
@@ -1949,6 +1949,12 @@ impl PluginHost {
|
||||
*self.shared.secrets.write() = store;
|
||||
}
|
||||
|
||||
/// Keeps plugin secrets in the OS credential store, with the owner-only
|
||||
/// files under the plugins directory as the fallback.
|
||||
pub fn use_credential_store(&self) {
|
||||
self.set_secret_store(Arc::new(CredentialSecretStore::new(self.shared.data_dir.clone())));
|
||||
}
|
||||
|
||||
/// Stores (or, with `None`, deletes) a secret the plugin declares under
|
||||
/// `[[contributes.secrets]]`.
|
||||
pub fn set_secret(&self, id: &str, name: &str, value: Option<&str>) -> IdeResult<()> {
|
||||
|
||||
@@ -211,7 +211,7 @@ fn write_index(
|
||||
|
||||
/// The download sources setting with `mirror` as the GitHub proxy prefix (Tools › Download sources).
|
||||
fn download_sources(mirror: &str) -> ide_core::settings::ToolDownloadSettings {
|
||||
ide_core::settings::ToolDownloadSettings { github_mirror: mirror.into() }
|
||||
ide_core::settings::ToolDownloadSettings { github_mirror: mirror.into(), ..Default::default() }
|
||||
}
|
||||
|
||||
/// Security audit lead 5: an index entry's id and version name the download file,
|
||||
|
||||
@@ -34,6 +34,20 @@ fn indent_settings(style: &LanguageCodeStyle) -> Option<Vec<(&'static str, Strin
|
||||
Some(settings)
|
||||
}
|
||||
|
||||
/// Java organize-imports thresholds as jdtls settings (IDEA's "Class count to use import with
|
||||
/// '*'" and "Names count to use static import with '*'"). Unset ones are IDEA's defaults, 5 and 3:
|
||||
/// jdtls' own are 99 (single imports), and it keeps a value it was sent until another one comes.
|
||||
/// A threshold the server configuration sets explicitly is kept.
|
||||
fn organize_imports_settings(style: Option<&LanguageCodeStyle>, inherited: &serde_json::Value) -> serde_json::Value {
|
||||
let explicit = |key: &str| inherited.pointer(&format!("/java/sources/organizeImports/{key}")).cloned();
|
||||
let class_count = style.and_then(|s| s.class_count_to_use_import_with_star).unwrap_or(5);
|
||||
let static_count = style.and_then(|s| s.names_count_to_use_static_import_with_star).unwrap_or(3);
|
||||
json!({
|
||||
"starThreshold": explicit("starThreshold").unwrap_or(json!(class_count)),
|
||||
"staticStarThreshold": explicit("staticStarThreshold").unwrap_or(json!(static_count)),
|
||||
})
|
||||
}
|
||||
|
||||
fn patch_profile_xml(mut xml: String, settings: &[(&'static str, String)]) -> String {
|
||||
for (id, value) in settings {
|
||||
let marker = format!(r#"<setting id="{id}" value=""#);
|
||||
@@ -84,6 +98,7 @@ pub fn configure_formatter(
|
||||
});
|
||||
let mut settings = cfg.settings.take().unwrap_or_else(|| json!({}));
|
||||
settings["java"]["format"]["settings"] = formatter_overrides(defaults, overrides);
|
||||
settings["java"]["sources"]["organizeImports"] = organize_imports_settings(style, &inherited);
|
||||
cfg.settings = Some(settings);
|
||||
let Some(style) = style else { return Ok(()) };
|
||||
let indent = indent_settings(style);
|
||||
@@ -300,6 +315,44 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn organize_imports_thresholds_default_to_idea_and_keep_explicit_server_settings() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let imports = |cfg: &LanguageServerConfig| {
|
||||
crate::handler::all_settings(cfg)["java"]["sources"]["organizeImports"].clone()
|
||||
};
|
||||
|
||||
let mut cfg = config("jdtls");
|
||||
let style = LanguageCodeStyle {
|
||||
class_count_to_use_import_with_star: Some(7),
|
||||
names_count_to_use_static_import_with_star: Some(4),
|
||||
..Default::default()
|
||||
};
|
||||
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
|
||||
assert_eq!(imports(&cfg), json!({"starThreshold": 7, "staticStarThreshold": 4}));
|
||||
|
||||
// Unset: IDEA's 5 and 3, not jdtls' 99 (#6026).
|
||||
let mut cfg = config("jdtls");
|
||||
let style = LanguageCodeStyle { names_count_to_use_static_import_with_star: Some(2), ..Default::default() };
|
||||
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
|
||||
assert_eq!(imports(&cfg), json!({"starThreshold": 5, "staticStarThreshold": 2}));
|
||||
let mut cfg = config("jdtls");
|
||||
configure_formatter(&mut cfg, None, &root, dir.path(), None).unwrap();
|
||||
assert_eq!(imports(&cfg), json!({"starThreshold": 5, "staticStarThreshold": 3}));
|
||||
|
||||
// A threshold set in the server configuration wins.
|
||||
let mut cfg = config("jdtls");
|
||||
cfg.settings = Some(json!({"java": {"sources": {"organizeImports": {"starThreshold": 99}}}}));
|
||||
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
|
||||
assert_eq!(imports(&cfg), json!({"starThreshold": 99, "staticStarThreshold": 2}));
|
||||
|
||||
let mut cfg = config("rust-analyzer");
|
||||
configure_formatter(&mut cfg, None, &root, dir.path(), None).unwrap();
|
||||
assert!(crate::handler::all_settings(&cfg)["java"].is_null());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_keeps_explicit_server_configuration_and_custom_accepts_absolute_paths() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -152,6 +152,8 @@ impl SshManager {
|
||||
let config = self.config(id)?;
|
||||
let secret = self.secret(&config);
|
||||
let session = Arc::new(self.connect(id, &SshTarget::from(&config), secret.as_deref()).await?);
|
||||
// The shared session carries the config's port forwards, restarted on every reconnect.
|
||||
session.start_forwards().await;
|
||||
self.sessions.lock().insert(id.to_owned(), session.clone());
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
@@ -7,7 +7,9 @@
|
||||
//! (or is recorded silently under `StrictHostKeyChecking accept-new`), and a
|
||||
//! changed key is refused unless host key checking is off.
|
||||
|
||||
use crate::target::{Hop, HostKeyPolicy, SshFiles, SshTarget, expand, home, resolve_hops};
|
||||
use crate::target::{
|
||||
ForwardDirection, Hop, HostKeyPolicy, PortForward, SshFiles, SshTarget, expand, home, resolve_hops,
|
||||
};
|
||||
use ide_core::remote_settings::SshAuth;
|
||||
use ide_core::{IdeError, IdeResult, error::ErrorKind};
|
||||
use parking_lot::Mutex;
|
||||
@@ -113,6 +115,18 @@ pub struct Session {
|
||||
/// Sessions of the `ProxyJump` hosts, kept alive under `handle`.
|
||||
_jumps: Vec<Handle<Client>>,
|
||||
label: String,
|
||||
/// The config's `LocalForward` / `RemoteForward`s, started by [`Session::start_forwards`].
|
||||
forwards: Vec<PortForward>,
|
||||
/// `LocalForward` listeners, stopped with the session.
|
||||
listeners: Mutex<Vec<tokio::task::AbortHandle>>,
|
||||
}
|
||||
|
||||
impl Drop for Session {
|
||||
fn drop(&mut self) {
|
||||
for listener in self.listeners.lock().drain(..) {
|
||||
listener.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -158,8 +172,50 @@ impl Session {
|
||||
sessions.push(handle);
|
||||
}
|
||||
let handle = sessions.pop().expect("at least one hop");
|
||||
let label = hops.last().expect("at least one hop").label();
|
||||
Ok(Session { handle, _jumps: sessions, label })
|
||||
let last = hops.last().expect("at least one hop");
|
||||
Ok(Session {
|
||||
handle,
|
||||
_jumps: sessions,
|
||||
label: last.label(),
|
||||
forwards: last.forwards.clone(),
|
||||
listeners: Mutex::default(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Starts the config's `LocalForward` / `RemoteForward`s, as `ssh` does on connecting: the
|
||||
/// SSH host listens for each `RemoteForward` (`tcpip-forward`), this machine for each
|
||||
/// `LocalForward`, until the session closes. A port that cannot be forwarded (in use, refused
|
||||
/// by the server) is skipped with a warning, as `ssh` goes on without it.
|
||||
pub async fn start_forwards(self: &Arc<Self>) {
|
||||
for f in &self.forwards {
|
||||
let what = format!("{}:{} → {}:{}", f.bind, f.port, f.host, f.host_port);
|
||||
match f.direction {
|
||||
ForwardDirection::Remote => match self.handle.tcpip_forward(f.bind.clone(), u32::from(f.port)).await {
|
||||
Ok(_) => tracing::info!("{}: RemoteForward {what}", self.label),
|
||||
Err(e) => tracing::warn!("{}: RemoteForward {what} failed: {e}", self.label),
|
||||
},
|
||||
ForwardDirection::Local => {
|
||||
let bind = match f.bind.as_str() {
|
||||
"localhost" => "127.0.0.1",
|
||||
"" => "0.0.0.0",
|
||||
b => b,
|
||||
};
|
||||
match tokio::net::TcpListener::bind((bind, f.port)).await {
|
||||
Ok(listener) => {
|
||||
let task = tokio::spawn(local_forward(
|
||||
listener,
|
||||
Arc::downgrade(self),
|
||||
f.host.clone(),
|
||||
f.host_port,
|
||||
));
|
||||
self.listeners.lock().push(task.abort_handle());
|
||||
tracing::info!("{}: LocalForward {what}", self.label);
|
||||
}
|
||||
Err(e) => tracing::warn!("{}: LocalForward {what} failed: {e}", self.label),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `user@host:port` of the target.
|
||||
@@ -404,6 +460,39 @@ fn io(message: impl Into<String>) -> IdeError {
|
||||
IdeError::new(ErrorKind::Io, message)
|
||||
}
|
||||
|
||||
/// A `LocalForward` listener: each connection goes through a `direct-tcpip` channel to
|
||||
/// `host:port` from the SSH host, while the session lives.
|
||||
async fn local_forward(listener: tokio::net::TcpListener, session: std::sync::Weak<Session>, host: String, port: u16) {
|
||||
while let Ok((mut socket, _)) = listener.accept().await {
|
||||
let Some(session) = session.upgrade().filter(|s| !s.is_closed()) else { return };
|
||||
let host = host.clone();
|
||||
tokio::spawn(async move {
|
||||
match session.direct_tcpip(&host, port).await {
|
||||
Ok(mut stream) => {
|
||||
drop(session);
|
||||
let _ = tokio::io::copy_bidirectional(&mut socket, &mut stream).await;
|
||||
}
|
||||
Err(e) => tracing::warn!("LocalForward: cannot open a channel to {host}:{port}: {e}"),
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// A `RemoteForward` connection: accepted once `host:port` here answers, then copied both ways.
|
||||
async fn remote_forward(channel: russh::Channel<Msg>, reply: client::ChannelOpenHandle, host: String, port: u16) {
|
||||
match tokio::net::TcpStream::connect((host.as_str(), port)).await {
|
||||
Ok(mut socket) => {
|
||||
reply.accept().await;
|
||||
let mut stream = channel.into_stream();
|
||||
let _ = tokio::io::copy_bidirectional(&mut socket, &mut stream).await;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("RemoteForward: cannot connect to {host}:{port}: {e}");
|
||||
reply.reject(russh::ChannelOpenFailure::ConnectFailed).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- connection ----------------------------------------------------------------
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -418,6 +507,8 @@ pub struct Client {
|
||||
known_hosts: PathBuf,
|
||||
host_key_policy: HostKeyPolicy,
|
||||
issue: Arc<Mutex<Option<HostKeyIssue>>>,
|
||||
/// The `RemoteForward`s whose connections this client accepts.
|
||||
remote_forwards: Vec<PortForward>,
|
||||
}
|
||||
|
||||
impl client::Handler for Client {
|
||||
@@ -442,6 +533,26 @@ impl client::Handler for Client {
|
||||
*self.issue.lock() = Some(issue);
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
async fn server_channel_open_forwarded_tcpip(
|
||||
&mut self,
|
||||
channel: russh::Channel<Msg>,
|
||||
_connected_address: &str,
|
||||
connected_port: u32,
|
||||
_originator_address: &str,
|
||||
_originator_port: u32,
|
||||
reply: client::ChannelOpenHandle,
|
||||
_session: &mut client::Session,
|
||||
) -> Result<(), Self::Error> {
|
||||
// Only a port this client asked the server to forward is accepted.
|
||||
match self.remote_forwards.iter().find(|f| u32::from(f.port) == connected_port) {
|
||||
Some(f) => {
|
||||
tokio::spawn(remote_forward(channel, reply, f.host.clone(), f.host_port));
|
||||
}
|
||||
None => reply.reject(russh::ChannelOpenFailure::AdministrativelyProhibited).await,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Client {
|
||||
@@ -600,6 +711,7 @@ where
|
||||
known_hosts: effective_known_hosts,
|
||||
host_key_policy: hop.host_key_policy,
|
||||
issue: issue.clone(),
|
||||
remote_forwards: hop.forwards.iter().filter(|f| f.direction == ForwardDirection::Remote).cloned().collect(),
|
||||
};
|
||||
let result = match stream {
|
||||
None => client::connect(config, (hop.host.as_str(), hop.port), handler).await,
|
||||
|
||||
@@ -54,6 +54,63 @@ pub(crate) struct Hop {
|
||||
pub host_key_policy: HostKeyPolicy,
|
||||
pub known_hosts: Option<PathBuf>,
|
||||
pub agent: Agent,
|
||||
/// `LocalForward` / `RemoteForward` of the config (the target's; jump hosts forward nothing).
|
||||
pub forwards: Vec<PortForward>,
|
||||
}
|
||||
|
||||
/// A `LocalForward` or `RemoteForward` of `~/.ssh/config`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PortForward {
|
||||
pub direction: ForwardDirection,
|
||||
/// Address the listening side binds: empty for every address, `localhost` by default.
|
||||
pub bind: String,
|
||||
pub port: u16,
|
||||
/// Where each connection goes, as the other side sees it.
|
||||
pub host: String,
|
||||
pub host_port: u16,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ForwardDirection {
|
||||
/// `LocalForward`: this machine listens, connections go to `host:host_port` from the SSH host.
|
||||
Local,
|
||||
/// `RemoteForward`: the SSH host listens, connections go to `host:host_port` from this machine.
|
||||
Remote,
|
||||
}
|
||||
|
||||
/// `[bind_address:]port host:hostport` (or the one-argument `-L` / `-R` form with colons); IPv6
|
||||
/// addresses in brackets. `None` for what isn't a TCP forward: a Unix socket, or `RemoteForward`'s
|
||||
/// dynamic (SOCKS) form.
|
||||
pub(crate) fn parse_forward(direction: ForwardDirection, value: &str) -> Option<PortForward> {
|
||||
let spec = split_args(value).join(":");
|
||||
let mut parts: Vec<String> = Vec::new();
|
||||
let mut cur = String::new();
|
||||
let mut bracket = false;
|
||||
for ch in spec.chars() {
|
||||
match ch {
|
||||
'[' if cur.is_empty() => bracket = true,
|
||||
']' if bracket => bracket = false,
|
||||
':' if !bracket => parts.push(std::mem::take(&mut cur)),
|
||||
'/' => return None,
|
||||
_ => cur.push(ch),
|
||||
}
|
||||
}
|
||||
parts.push(cur);
|
||||
let (bind, port, host, host_port) = match parts.as_slice() {
|
||||
[port, host, host_port] => (None, port, host, host_port),
|
||||
[bind, port, host, host_port] => (Some(bind.as_str()), port, host, host_port),
|
||||
_ => return None,
|
||||
};
|
||||
let bind = match bind {
|
||||
None => "localhost".to_owned(),
|
||||
Some("*") | Some("") => String::new(),
|
||||
Some(b) => b.to_owned(),
|
||||
};
|
||||
let (port, host_port) = (port.parse().ok()?, host_port.parse().ok()?);
|
||||
if host.is_empty() || host_port == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(PortForward { direction, bind, port, host: host.clone(), host_port })
|
||||
}
|
||||
|
||||
/// Where the SSH agent of a hop listens (`IdentityAgent`).
|
||||
@@ -158,6 +215,8 @@ struct RawConfig {
|
||||
host_key_policy: Option<HostKeyPolicy>,
|
||||
user_known_hosts_file: Option<String>,
|
||||
identity_agent: Option<String>,
|
||||
forwards: Vec<PortForward>,
|
||||
clear_forwardings: bool,
|
||||
}
|
||||
|
||||
fn strip_quotes(s: &str) -> &str {
|
||||
@@ -516,6 +575,23 @@ fn parse_config_file(
|
||||
out.user_known_hosts_file = Some(first);
|
||||
}
|
||||
}
|
||||
"localforward" | "remoteforward" => {
|
||||
let direction = if key.eq_ignore_ascii_case("localforward") {
|
||||
ForwardDirection::Local
|
||||
} else {
|
||||
ForwardDirection::Remote
|
||||
};
|
||||
match parse_forward(direction, value) {
|
||||
Some(f) if !out.forwards.contains(&f) => out.forwards.push(f),
|
||||
Some(_) => {}
|
||||
None => tracing::debug!("ssh config: {key} {value} is not a TCP port forward; skipped"),
|
||||
}
|
||||
}
|
||||
"clearallforwardings" => {
|
||||
if matches!(strip_quotes(value).to_ascii_lowercase().as_str(), "yes" | "true") {
|
||||
out.clear_forwardings = true;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -559,7 +635,8 @@ fn config_hop(
|
||||
if null_known_hosts { HostKeyPolicy::Off } else { raw.host_key_policy.unwrap_or(HostKeyPolicy::Ask) };
|
||||
let agent =
|
||||
identity_agent(raw.identity_agent.as_deref(), |p| expand(&expand_tokens(p, alias, &host, port, &user, &local)));
|
||||
let hop = Hop { host, port, user, identity_files, proxy_command, host_key_policy, known_hosts, agent };
|
||||
let forwards = if raw.clear_forwardings { Vec::new() } else { raw.forwards };
|
||||
let hop = Hop { host, port, user, identity_files, proxy_command, host_key_policy, known_hosts, agent, forwards };
|
||||
(hop, proxy_jump)
|
||||
}
|
||||
|
||||
@@ -574,7 +651,7 @@ fn jump_hop(config: Option<&Path>, spec: &str) -> Hop {
|
||||
_ => (rest, None),
|
||||
};
|
||||
let (hop, _) = config_hop(config, host, port, user);
|
||||
hop
|
||||
Hop { forwards: Vec::new(), ..hop }
|
||||
}
|
||||
|
||||
/// The SSH hosts to go through, the target last.
|
||||
@@ -597,6 +674,7 @@ pub(crate) fn resolve_hops(target: &SshTarget, config: Option<&Path>) -> IdeResu
|
||||
host_key_policy: HostKeyPolicy::Ask,
|
||||
known_hosts: None,
|
||||
agent: Agent::Default,
|
||||
forwards: Vec::new(),
|
||||
},
|
||||
None,
|
||||
)
|
||||
@@ -636,6 +714,40 @@ pub fn openssh_args(target: &SshTarget) -> Vec<String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_port_forwards_like_openssh() {
|
||||
let f = |d, v: &str| parse_forward(d, v).map(|f| (f.bind, f.port, f.host, f.host_port));
|
||||
let remote = ForwardDirection::Remote;
|
||||
assert_eq!(f(remote, "9222 127.0.0.1:9222"), Some(("localhost".into(), 9222, "127.0.0.1".into(), 9222)));
|
||||
assert_eq!(f(remote, "0.0.0.0:8080 web:80"), Some(("0.0.0.0".into(), 8080, "web".into(), 80)));
|
||||
assert_eq!(f(remote, "*:8080 web:80"), Some((String::new(), 8080, "web".into(), 80)));
|
||||
assert_eq!(f(remote, "[::1]:8080 [::1]:80"), Some(("::1".into(), 8080, "::1".into(), 80)));
|
||||
assert_eq!(f(ForwardDirection::Local, "5432:db:5432"), Some(("localhost".into(), 5432, "db".into(), 5432)));
|
||||
// Dynamic (SOCKS) and Unix socket forwards aren't TCP port forwards.
|
||||
assert_eq!(f(remote, "1080"), None);
|
||||
assert_eq!(f(remote, "/tmp/a.sock /tmp/b.sock"), None);
|
||||
assert_eq!(f(remote, "8080 web:http"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_forwards_belong_to_the_target_and_clear_all_forwardings_drops_them() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let config = dir.path().join("config");
|
||||
std::fs::write(
|
||||
&config,
|
||||
"Host box\n RemoteForward 9222 127.0.0.1:9222\n LocalForward 5432 db:5432\n ProxyJump gate\n\
|
||||
Host gate\n LocalForward 1 a:1\nHost quiet\n RemoteForward 9222 127.0.0.1:9222\n ClearAllForwardings yes\n",
|
||||
)
|
||||
.unwrap();
|
||||
let target = |host: &str| SshTarget { host: host.into(), auth: SshAuth::OpenSsh, ..Default::default() };
|
||||
let hops = resolve_hops(&target("box"), Some(&config)).unwrap();
|
||||
assert_eq!(hops.len(), 2);
|
||||
assert!(hops[0].forwards.is_empty(), "jump hosts forward nothing");
|
||||
let dirs: Vec<_> = hops[1].forwards.iter().map(|f| (f.direction, f.port)).collect();
|
||||
assert_eq!(dirs, [(ForwardDirection::Remote, 9222), (ForwardDirection::Local, 5432)]);
|
||||
assert!(resolve_hops(&target("quiet"), Some(&config)).unwrap()[0].forwards.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_aliases_and_proxy_jumps_from_ssh_config() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -98,6 +98,32 @@ impl server::Handler for Sshd {
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `RemoteForward`: listens on 127.0.0.1:`port` and forwards each connection back to the client.
|
||||
async fn tcpip_forward(
|
||||
&mut self,
|
||||
address: &str,
|
||||
port: &mut u32,
|
||||
session: &mut ServerSession,
|
||||
) -> Result<bool, Self::Error> {
|
||||
let Ok(listener) = TcpListener::bind(("127.0.0.1", *port as u16)).await else { return Ok(false) };
|
||||
let (handle, address, port) = (session.handle(), address.to_owned(), *port);
|
||||
tokio::spawn(async move {
|
||||
while let Ok((mut socket, peer)) = listener.accept().await {
|
||||
let Ok(channel) = handle
|
||||
.channel_open_forwarded_tcpip(address.clone(), port, "127.0.0.1", u32::from(peer.port()))
|
||||
.await
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
tokio::spawn(async move {
|
||||
let mut stream = channel.into_stream();
|
||||
let _ = tokio::io::copy_bidirectional(&mut stream, &mut socket).await;
|
||||
});
|
||||
}
|
||||
});
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
/// Echo server standing in for a remote service.
|
||||
@@ -443,3 +469,50 @@ async fn accept_new_records_an_unknown_key_and_still_refuses_a_changed_one() {
|
||||
let msg = denied(env.connect(&target, None).await);
|
||||
assert!(msg.contains("has changed"), "{msg}");
|
||||
}
|
||||
|
||||
/// A free local port (bound and released).
|
||||
fn free_port() -> u16 {
|
||||
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
|
||||
}
|
||||
|
||||
async fn echoes(port: u16) {
|
||||
let mut s = TcpStream::connect(("127.0.0.1", port)).await.expect("forwarded port listens");
|
||||
s.write_all(b"ping").await.unwrap();
|
||||
let mut buf = [0u8; 4];
|
||||
s.read_exact(&mut buf).await.unwrap();
|
||||
assert_eq!(&buf, b"ping");
|
||||
}
|
||||
|
||||
/// `RemoteForward` and `LocalForward` of `~/.ssh/config` are forwarded while the session lives (#6031).
|
||||
#[tokio::test]
|
||||
async fn config_port_forwards_follow_the_session() {
|
||||
let mut env = env().await;
|
||||
let (remote, local) = (free_port(), free_port());
|
||||
let config = env._tmp.path().join("ssh_config");
|
||||
std::fs::write(
|
||||
&config,
|
||||
format!(
|
||||
"Host box\n\tHostName 127.0.0.1\n\tStrictHostKeyChecking=no\n\tUserKnownHostsFile=/dev/null\n\
|
||||
\tRemoteForward {remote} 127.0.0.1:{echo}\n\tLocalForward 127.0.0.1:{local} localhost:{echo}\n\
|
||||
\tRemoteForward /tmp/remote.sock /tmp/local.sock\n",
|
||||
echo = env.echo_port
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
env.files.config = Some(config);
|
||||
let target = SshTarget {
|
||||
host: "box".into(),
|
||||
port: Some(env.ssh_port),
|
||||
user: "coder".into(),
|
||||
auth: SshAuth::OpenSsh,
|
||||
..Default::default()
|
||||
};
|
||||
let session = Arc::new(env.connect(&target, None).await.expect("connects"));
|
||||
session.start_forwards().await;
|
||||
// The SSH host's port reaches the echo server here; the local port reaches it from the SSH host.
|
||||
echoes(remote).await;
|
||||
echoes(local).await;
|
||||
drop(session);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
assert!(TcpStream::connect(("127.0.0.1", local)).await.is_err(), "a closed session stops its LocalForward");
|
||||
}
|
||||
@@ -1078,6 +1078,7 @@ impl Tools {
|
||||
},
|
||||
&specs,
|
||||
pnpm,
|
||||
!self.downloads.configured_registries_only,
|
||||
cancel,
|
||||
emit,
|
||||
)
|
||||
@@ -1463,6 +1464,12 @@ impl Tools {
|
||||
sources::openvsx_pick(&json, assets, self.platform)
|
||||
}
|
||||
ReleaseSource::MavenCentral { group, artifact } => {
|
||||
if self.downloads.configured_registries_only {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"{group}:{artifact} is downloaded from Maven Central, and Settings › Tools › Download Mirrors \
|
||||
allows only the configured package registries"
|
||||
)));
|
||||
}
|
||||
let xml = http.get_text(&sources::maven_metadata_url(group, artifact), cancel)?;
|
||||
sources::maven_pick(group, artifact, &xml)
|
||||
}
|
||||
@@ -1690,7 +1697,7 @@ impl Tools {
|
||||
// on a slow registry takes several seconds per package, more when run side by side.
|
||||
let out = match view(&[]) {
|
||||
Some((true, out)) => Some(out),
|
||||
Some((false, out)) if is_npm_registry_miss(&out) => {
|
||||
Some((false, out)) if !self.downloads.configured_registries_only && is_npm_registry_miss(&out) => {
|
||||
let extra = npm_public_registry_args([packages[0]], pnpm);
|
||||
view(&extra).and_then(|(ok, retry)| ok.then_some(retry))
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ mod tests {
|
||||
const ASSET: &str = "https://github.com/LuaLS/lua-language-server/releases/download/3.13.5/x.zip";
|
||||
|
||||
fn settings(mirror: &str) -> ToolDownloadSettings {
|
||||
ToolDownloadSettings { github_mirror: mirror.into() }
|
||||
ToolDownloadSettings { github_mirror: mirror.into(), ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -110,13 +110,15 @@ pub fn run_streamed_picking(
|
||||
}
|
||||
|
||||
/// Runs an `npm` / `pnpm` command against the user's configured registry first (preserving
|
||||
/// corporate mirrors, proxies, and CAs), and retries once against [`PUBLIC_NPM_REGISTRY`] when
|
||||
/// the configured registry misses the package/version or rejects auth. Preserves the primary
|
||||
/// error if the public registry is unreachable.
|
||||
/// corporate mirrors, proxies, and CAs), and with `public_fallback` retries once against
|
||||
/// [`PUBLIC_NPM_REGISTRY`] when the configured registry misses the package/version or rejects
|
||||
/// auth. Preserves the primary error if the public registry is unreachable. Without
|
||||
/// `public_fallback` (Settings › Tools › Download Mirrors) the configured registry's error stands.
|
||||
pub fn run_npm_with_public_fallback(
|
||||
mut build: impl FnMut(&[String]) -> Command,
|
||||
specs: &[String],
|
||||
pnpm: bool,
|
||||
public_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<String> {
|
||||
@@ -127,7 +129,7 @@ pub fn run_npm_with_public_fallback(
|
||||
return Ok(output);
|
||||
}
|
||||
let err = failed_command(&label, &output, &status);
|
||||
if cancel.is_cancelled() || !is_npm_registry_miss(&output) {
|
||||
if !public_fallback || cancel.is_cancelled() || !is_npm_registry_miss(&output) {
|
||||
return Err(err);
|
||||
}
|
||||
emit(InstallEvent::Line {
|
||||
|
||||
@@ -603,6 +603,34 @@ esac"#,
|
||||
assert!(!err.message.contains("ECONNRESET"), "{}", err.message);
|
||||
}
|
||||
|
||||
/// Settings › Tools › Download Mirrors › Use only the configured package registries: a registry
|
||||
/// that refuses a package (a firewall's 403) is the answer.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn configured_registries_only_never_reach_public_registries() {
|
||||
let env = Env::new();
|
||||
let log = env.root.parent().unwrap().join("npm-only.txt");
|
||||
env.script(&env.sys, "node", "exit 0");
|
||||
env.script(
|
||||
&env.sys,
|
||||
"npm",
|
||||
&format!(
|
||||
r#"echo "$@" >> '{log}'
|
||||
echo "npm error code E403" >&2
|
||||
echo "npm error 403 Forbidden - GET https://nexus.example/yaml-language-server - quarantined" >&2
|
||||
exit 1"#,
|
||||
log = log.display()
|
||||
),
|
||||
);
|
||||
let only = ToolDownloadSettings { configured_registries_only: true, ..Default::default() };
|
||||
let tools = env.tools().with_downloads(only);
|
||||
let err = tools.install("yaml-language-server", &langs(), &CancellationToken::new(), &|_| {}).unwrap_err();
|
||||
assert!(err.message.contains("quarantined"), "{}", err.message);
|
||||
let calls = fs::read_to_string(&log).unwrap();
|
||||
assert_eq!(calls.lines().count(), 1, "{calls}");
|
||||
assert!(!calls.contains("registry.npmjs.org"), "{calls}");
|
||||
}
|
||||
|
||||
/// Servers that load TypeScript as a library get one with its JS API: `@latest`
|
||||
/// is TypeScript 7 (native, no `ts.server`), which crashed vue-language-server (#25).
|
||||
/// Uninstalling one keeps the TypeScript another installed server still uses.
|
||||
@@ -1344,7 +1372,10 @@ esac"#,
|
||||
),
|
||||
);
|
||||
// The first mirror is down: the next one is tried before the official host.
|
||||
let downloads = ToolDownloadSettings { github_mirror: "https://down.mirror.test/, https://mirror.test/".into() };
|
||||
let downloads = ToolDownloadSettings {
|
||||
github_mirror: "https://down.mirror.test/, https://mirror.test/".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let emit = |_: InstallEvent| {};
|
||||
env.tools()
|
||||
.with_downloads(downloads)
|
||||
|
||||
@@ -191,6 +191,35 @@ impl DocState {
|
||||
self.disk_conflict = false;
|
||||
self.clean_text = (!self.large).then(|| self.doc.clone());
|
||||
}
|
||||
|
||||
/// The bytes saving `doc` with this document's encoding, BOM and conversion would write.
|
||||
fn bytes_for_save(&self, doc: &Document) -> IdeResult<Vec<u8>> {
|
||||
let text = doc.text_for_save();
|
||||
Ok(if self.native_to_ascii {
|
||||
ide_vfs::encode_properties_ascii(&text).into_bytes()
|
||||
} else {
|
||||
ide_vfs::encode(&text, &self.encoding, self.has_bom)?
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the file changed on disk since the buffer last matched it. A moved stamp with the
|
||||
/// same bytes (touch, a tool rewriting the file unchanged) is no change and its stamp is adopted. Reads the file
|
||||
/// only when the mtime moved but the length did not; without a clean text to compare (large
|
||||
/// files, a pending encoding, line-ending or BOM change, a reported conflict) a moved stamp counts.
|
||||
fn changed_on_disk(&mut self, meta: &std::fs::Metadata) -> bool {
|
||||
let mtime = ide_vfs::mtime_ms(meta);
|
||||
if mtime == self.disk_mtime && meta.len() == self.disk_len {
|
||||
return false;
|
||||
}
|
||||
let same_bytes = meta.len() == self.disk_len
|
||||
&& self.clean_text.as_ref().is_some_and(|clean| {
|
||||
self.bytes_for_save(clean).is_ok_and(|bytes| std::fs::read(&self.path).is_ok_and(|disk| disk == bytes))
|
||||
});
|
||||
if same_bytes {
|
||||
self.disk_mtime = mtime;
|
||||
}
|
||||
!same_bytes
|
||||
}
|
||||
}
|
||||
|
||||
fn keys_for(path: &Path) -> Vec<PathBuf> {
|
||||
@@ -924,7 +953,7 @@ impl Documents {
|
||||
&& !st.disk_conflict
|
||||
&& st.uri.is_none()
|
||||
&& let Ok(meta) = std::fs::metadata(&st.path)
|
||||
&& (ide_vfs::mtime_ms(&meta) != st.disk_mtime || meta.len() != st.disk_len)
|
||||
&& st.changed_on_disk(&meta)
|
||||
{
|
||||
st.disk_mtime = ide_vfs::mtime_ms(&meta);
|
||||
st.disk_len = meta.len();
|
||||
@@ -1411,6 +1440,9 @@ impl Documents {
|
||||
return Ok(());
|
||||
}
|
||||
if st.dirty {
|
||||
if !st.changed_on_disk(&meta) {
|
||||
return Ok(());
|
||||
}
|
||||
st.disk_mtime = mtime;
|
||||
st.disk_len = meta.len();
|
||||
st.disk_conflict = true;
|
||||
|
||||
@@ -314,12 +314,7 @@ fn hash_disk(hash: &mut blake3::Hasher, path: &Path, unsaved: &HashMap<PathBuf,
|
||||
|
||||
/// The bytes saving `state` would write.
|
||||
fn saved_bytes(state: &DocState) -> IdeResult<Vec<u8>> {
|
||||
let text = state.doc.text_for_save();
|
||||
Ok(if state.native_to_ascii {
|
||||
ide_vfs::encode_properties_ascii(&text).into_bytes()
|
||||
} else {
|
||||
ide_vfs::encode(&text, &state.encoding, state.has_bom)?
|
||||
})
|
||||
state.bytes_for_save(&state.doc)
|
||||
}
|
||||
|
||||
/// A reverted edit may leave the dirty flag set even when all saved bytes match.
|
||||
|
||||
@@ -350,6 +350,61 @@ fn autosave_checks_the_disk_before_the_watcher_reports_a_change() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Writes `bytes` with an mtime clearly after the current one, whatever the filesystem's granularity.
|
||||
fn rewrite_later(path: &Path, bytes: &[u8]) {
|
||||
let mtime = fs::metadata(path).unwrap().modified().unwrap() + std::time::Duration::from_secs(2);
|
||||
fs::write(path, bytes).unwrap();
|
||||
fs::File::options().write(true).open(path).unwrap().set_modified(mtime).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewriting_the_same_bytes_is_no_disk_conflict() {
|
||||
let f = fixture();
|
||||
let path = f.root.join("notes.txt");
|
||||
fs::write(&path, "alpha\nbeta\n").unwrap();
|
||||
let info = f.docs.open(&path).unwrap();
|
||||
f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap();
|
||||
// A touch, or a tool rewriting the file unchanged: only the mtime moves.
|
||||
rewrite_later(&path, b"alpha\nbeta\n");
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
assert!(f.docs.autosave(info.id).unwrap(), "autosave stopped on a file whose bytes did not change");
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "edited\nbeta\n");
|
||||
assert!(!f.events.lock().iter().any(|e| matches!(e, IdeEvent::DocDiskConflict { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autosave_ignores_a_rewrite_of_the_same_bytes_before_the_watcher_reports_it() {
|
||||
let f = fixture();
|
||||
let path = f.root.join("notes.txt");
|
||||
fs::write(&path, "alpha\nbeta\n").unwrap();
|
||||
let info = f.docs.open(&path).unwrap();
|
||||
f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap();
|
||||
rewrite_later(&path, b"alpha\nbeta\n");
|
||||
assert!(f.docs.autosave(info.id).unwrap(), "autosave stopped on a file whose bytes did not change");
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "edited\nbeta\n");
|
||||
}
|
||||
|
||||
/// Opens `bytes`, edits the buffer, then rewrites the file as `external` (same text, other bytes).
|
||||
fn assert_other_bytes_conflict(name: &str, bytes: &[u8], external: &[u8]) {
|
||||
let f = fixture();
|
||||
let path = f.root.join(name);
|
||||
fs::write(&path, bytes).unwrap();
|
||||
let info = f.docs.open(&path).unwrap();
|
||||
f.docs.edit(info.id, 0, change(0, 0, "x")).unwrap();
|
||||
rewrite_later(&path, external);
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
assert!(!f.docs.autosave(info.id).unwrap(), "{name}: autosave overwrote other bytes of the same text");
|
||||
assert_eq!(fs::read(&path).unwrap(), external);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_text_in_other_bytes_is_still_a_disk_conflict() {
|
||||
assert_other_bytes_conflict("crlf.txt", b"alpha\nbeta\n", b"alpha\r\nbeta\r\n");
|
||||
assert_other_bytes_conflict("bom.txt", b"alpha\n", b"\xEF\xBB\xBFalpha\n");
|
||||
// Same length: only the byte comparison tells them apart.
|
||||
assert_other_bytes_conflict("utf16.txt", b"\xFF\xFEa\x00\n\x00", b"\xFE\xFF\x00a\x00\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autosave_leaves_a_file_changed_on_disk_after_an_edit() {
|
||||
let f = fixture();
|
||||
|
||||
@@ -138,17 +138,18 @@ fn rollback_keeps_a_disk_conflict_of_an_unsaved_buffer() {
|
||||
let info = docs.open(&first).unwrap();
|
||||
docs.edit(info.id, info.version, ChangeSet { changes: vec![TextChange { from: 0, to: 3, insert: "own".into() }] })
|
||||
.unwrap();
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&first, "new")], ..Default::default() }).unwrap();
|
||||
// An external write the undo record still accepts (same bytes, new mtime) under the unsaved buffer.
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
std::fs::write(&first, "old\n").unwrap();
|
||||
// An external write under the unsaved buffer, warned about before the refactoring.
|
||||
let mtime = std::fs::metadata(&first).unwrap().modified().unwrap() + std::time::Duration::from_secs(2);
|
||||
std::fs::write(&first, "ext\n").unwrap();
|
||||
std::fs::File::options().write(true).open(&first).unwrap().set_modified(mtime).unwrap();
|
||||
docs.on_disk_changed(std::slice::from_ref(&first));
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&first, "new")], ..Default::default() }).unwrap();
|
||||
docs.undo_workspace_edit(undo_id(&events)).unwrap();
|
||||
let snap = docs.snapshot(info.id).unwrap();
|
||||
assert_eq!(snap.text, "own\n");
|
||||
assert!(snap.dirty);
|
||||
assert!(!docs.autosave(info.id).unwrap(), "autosave must not overwrite the external change");
|
||||
assert_eq!(std::fs::read_to_string(&first).unwrap(), "old\n");
|
||||
assert_eq!(std::fs::read_to_string(&first).unwrap(), "ext\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -114,6 +114,8 @@ All folding commands are also in **Code › Folding**. Fold regions come from th
|
||||
|
||||
Indentation and other style options are under **Settings › Editor › Code Style**, with a page per language. `.editorconfig` files in the project are read too.
|
||||
|
||||
Java has an **Imports** tab for IntelliSort-style options: **Class count to use import with '\*'** switches to a wildcard import once that many classes of one package are used, and **Names count to use static import with '\*'** does the same for statically imported names (999 keeps single imports). Both are passed through to the Java language server, whose defaults are 5 and 3, as in IDEA.
|
||||
|
||||
To format on every save, enable **Reformat code** (and optionally **Optimize imports**) in **Settings › Tools › Actions on Save**. Trailing spaces and the final line break on save are set in **Settings › Editor › General**, section **Save Files**.
|
||||
|
||||
## Tabs
|
||||
@@ -145,17 +147,19 @@ With tabs placed left or right, the tab column is as wide as its longest name, u
|
||||
|
||||
## View options
|
||||
|
||||
| Action | macOS | Windows / Linux |
|
||||
| ---------------------- | ----- | --------------- |
|
||||
| **Increase Font Size** | `⌥⇧.` | `Alt+Shift+.` |
|
||||
| **Decrease Font Size** | `⌥⇧,` | `Alt+Shift+,` |
|
||||
| **Scroll to Center** | `⌃L` | `Ctrl+M` |
|
||||
| **Scroll Up** | — | `Ctrl+Up` |
|
||||
| **Scroll Down** | — | `Ctrl+Down` |
|
||||
| **Scroll to Top** | — | — |
|
||||
| **Scroll to Bottom** | — | — |
|
||||
| Action | macOS | Windows / Linux |
|
||||
| ------------------------------------- | ----- | --------------- |
|
||||
| **Increase Font Size** | `⌥⇧.` | `Alt+Shift+.` |
|
||||
| **Decrease Font Size** | `⌥⇧,` | `Alt+Shift+,` |
|
||||
| **Scroll to Center** | `⌃L` | `Ctrl+M` |
|
||||
| **Scroll Up** | — | `Ctrl+Up` |
|
||||
| **Scroll Down** | — | `Ctrl+Down` |
|
||||
| **Scroll Up and Move if Necessary** | — | — |
|
||||
| **Scroll Down and Move if Necessary** | — | — |
|
||||
| **Scroll to Top** | — | — |
|
||||
| **Scroll to Bottom** | — | — |
|
||||
|
||||
**Scroll Up** and **Scroll Down** move the view by one line and leave the caret where it is, even when it scrolls out of sight. **Scroll to Top** and **Scroll to Bottom** show the start and the end of the file; the caret stays where it is too. They have no default shortcut: run them from Find Action or assign one in **Settings › Keymap**.
|
||||
**Scroll Up** and **Scroll Down** move the view by one line and leave the caret where it is, even when it scrolls out of sight. **Scroll Up and Move if Necessary** and **Scroll Down and Move if Necessary** also move the view by one line, but bring a caret the view doesn't show to its first or last line. **Scroll to Top** and **Scroll to Bottom** show the start and the end of the file; the caret stays where it is too. They have no default shortcut: run them from Find Action or assign one in **Settings › Keymap**.
|
||||
|
||||
- **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**.
|
||||
|
||||
@@ -90,7 +90,7 @@ Settings › Appearance & Behavior › System Settings, unless noted.
|
||||
| `dateFormat.overrideSystem` | `false` | **Override system date and time format** (Date Formats page). |
|
||||
| `dateFormat.pattern` | `"dd.MM.yyyy"` | Date pattern with `dd`, `MM`, `MMM`, `yy`, `yyyy`. |
|
||||
| `dateFormat.use24Hour` | `true` | 24-hour time. |
|
||||
| `dateFormat.pretty` | `true` | "Today", "Yesterday", "5 min ago". |
|
||||
| `dateFormat.pretty` | `true` | "Today", "Yesterday", "5 min ago" (in lists with time, in the annotate gutter as the day alone). |
|
||||
|
||||
### `[appearance]`
|
||||
|
||||
|
||||
@@ -145,17 +145,19 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
|
||||
|
||||
## 显示选项
|
||||
|
||||
| 操作 | macOS | Windows / Linux |
|
||||
| -------------- | ----- | --------------- |
|
||||
| **增大字体** | `⌥⇧.` | `Alt+Shift+.` |
|
||||
| **减小字体** | `⌥⇧,` | `Alt+Shift+,` |
|
||||
| **滚动到中央** | `⌃L` | `Ctrl+M` |
|
||||
| **向上滚动** | — | `Ctrl+Up` |
|
||||
| **向下滚动** | — | `Ctrl+Down` |
|
||||
| **滚动到顶部** | — | — |
|
||||
| **滚动到底部** | — | — |
|
||||
| 操作 | macOS | Windows / Linux |
|
||||
| ------------------------------ | ----- | --------------- |
|
||||
| **增大字体** | `⌥⇧.` | `Alt+Shift+.` |
|
||||
| **减小字体** | `⌥⇧,` | `Alt+Shift+,` |
|
||||
| **滚动到中央** | `⌃L` | `Ctrl+M` |
|
||||
| **向上滚动** | — | `Ctrl+Up` |
|
||||
| **向下滚动** | — | `Ctrl+Down` |
|
||||
| **向上滚动并在必要时移动光标** | — | — |
|
||||
| **向下滚动并在必要时移动光标** | — | — |
|
||||
| **滚动到顶部** | — | — |
|
||||
| **滚动到底部** | — | — |
|
||||
|
||||
**向上滚动** 和 **向下滚动** 把视图移动一行,光标保持原位,即使它因此移出可见区域。**滚动到顶部** 和 **滚动到底部** 显示文件的开头和结尾;光标同样保持原位。它们默认没有快捷键:在查找操作中运行,或在 **设置 › 按键映射** 中指定。
|
||||
**向上滚动** 和 **向下滚动** 把视图移动一行,光标保持原位,即使它因此移出可见区域。**向上滚动并在必要时移动光标** 和 **向下滚动并在必要时移动光标** 同样把视图移动一行,但会把不在视图中的光标移到视图的第一行或最后一行。**滚动到顶部** 和 **滚动到底部** 显示文件的开头和结尾;光标同样保持原位。它们默认没有快捷键:在查找操作中运行,或在 **设置 › 按键映射** 中指定。
|
||||
|
||||
- **视图 › 活动编辑器 › 软换行** 让当前编辑器的长行自动折行。想让某些文件类型默认软换行,在 **设置 › 编辑器 › 常规** 的 **软换行** 一节中设置。
|
||||
- **视图 › 重置字体大小** 撤销当前编辑器或焦点区域的字体缩放(**视图 › 重置所有编辑器中的字体大小** 会重置所有打开的编辑器)。用 `⌘` / `Ctrl` + 鼠标滚轮调整字号的功能默认关闭,可在 **设置 › 编辑器 › 常规** 的 **鼠标控制** 一节中打开,并可选择作用于 **当前编辑器**(默认)或 **所有编辑器**。
|
||||
|
||||
@@ -90,7 +90,7 @@ exclude = ["**/.git", "**/node_modules", "**/target", "**/dist"]
|
||||
| `dateFormat.overrideSystem` | `false` | **覆盖系统日期和时间格式**(日期格式页)。 |
|
||||
| `dateFormat.pattern` | `"dd.MM.yyyy"` | 日期格式,可用 `dd`、`MM`、`MMM`、`yy`、`yyyy`。 |
|
||||
| `dateFormat.use24Hour` | `true` | 使用 24 小时制。 |
|
||||
| `dateFormat.pretty` | `true` | 显示“今天”“昨天”“5 分钟前”这类相对时间。 |
|
||||
| `dateFormat.pretty` | `true` | 显示“今天”“昨天”“5 分钟前”这类相对时间(列表中带时间,注解装订区域仅显示日期)。 |
|
||||
|
||||
### `[appearance]`
|
||||
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* 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,3 +41,19 @@ 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");
|
||||
});
|
||||
@@ -4,10 +4,11 @@ test("image controls and metadata stay readable in a narrow editor", async ({ wo
|
||||
await page.setViewportSize({ width: 1080, height: 700 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const path = "/dev/acme-api/status.svg";
|
||||
const path = "/dev/acme-api/status.png";
|
||||
// A black 128 × 96 PNG.
|
||||
const image =
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" width="128" height="96"><rect width="128" height="96"/></svg>';
|
||||
window.__ipc.handlers.fs_read_image = () => "data:image/svg+xml," + encodeURIComponent(image);
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAIAAAABgCAYAAADVenpJAAAAtklEQVR42u3SQREAAAyDMPyb3oQ0jxjgqDqmiWAADIABMAAGwAAYAANgAAyAATAABsAAGAADYAAMgAEwAAbAABgAA2AADIABMAAGwAAYAANgAAyAATAABsAAGAADYAAMgAEwAAbAABgAA2AADIABMAAGwAAYAANgAAyAATAABsAAGAADYAAMgAEwAAbAABgAA2AADIABMAAGwAAYAANgAAyAATAABkAEA2AADIABMAAGwAAYgAUPjHPSwnYk55QAAAAASUVORK5CYII=";
|
||||
window.__ipc.handlers.fs_read_image = () => "data:image/png;base64," + image;
|
||||
window.__ipc.handlers.fs_probe = () => ({ size: 4096, binary: false, tooLarge: false });
|
||||
const contributions = "/src/workbench/contributions.ts";
|
||||
const { editorService } = await import(/* @vite-ignore */ contributions);
|
||||
@@ -18,9 +19,8 @@ test("image controls and metadata stay readable in a narrow editor", async ({ wo
|
||||
const zoomIn = toolbar.getByRole("button", { name: "Zoom In", exact: true });
|
||||
const actualSize = toolbar.getByRole("button", { name: "Actual Size", exact: true });
|
||||
const chessboard = toolbar.getByRole("button", { name: "Show Chessboard", exact: true });
|
||||
const showText = toolbar.getByRole("button", { name: "Open as Text", exact: true });
|
||||
const dimensions = toolbar.getByText(/128\s*×\s*96/);
|
||||
await expect(page.getByRole("img", { name: "status.svg", exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("img", { name: "status.png", exact: true })).toBeVisible();
|
||||
await expect(dimensions).toBeVisible();
|
||||
const wideHeight = (await toolbar.boundingBox())!.height;
|
||||
|
||||
@@ -31,8 +31,7 @@ test("image controls and metadata stay readable in a narrow editor", async ({ wo
|
||||
expect((await toolbar.boundingBox())!.height).toBeGreaterThan(wideHeight);
|
||||
expect((await dimensions.boundingBox())!.y).toBeGreaterThan((await zoomIn.boundingBox())!.y);
|
||||
await expect(dimensions).toHaveCSS("font-size", "13px");
|
||||
await expect(showText).toHaveCSS("white-space", "nowrap");
|
||||
for (const item of [zoomIn, actualSize, chessboard, showText, dimensions]) {
|
||||
for (const item of [zoomIn, actualSize, chessboard, dimensions]) {
|
||||
await expect(item).toBeInViewport({ ratio: 1 });
|
||||
}
|
||||
await expect(toolbar.getByText("4.0 KB", { exact: true })).toBeVisible();
|
||||
@@ -43,6 +42,33 @@ test("image controls and metadata stay readable in a narrow editor", async ({ wo
|
||||
await expect(toolbar.getByText("100%", { exact: true })).toBeVisible();
|
||||
await chessboard.click();
|
||||
await expect(chessboard).toHaveAttribute("aria-pressed", "false");
|
||||
await showText.click();
|
||||
});
|
||||
|
||||
test("an SVG file opens as its source with the image beside it", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
window.__ipc.handlers.fs_probe = () => ({ size: 96, binary: false, tooLarge: false });
|
||||
const contributions = "/src/workbench/contributions.ts";
|
||||
const { editorService } = await import(/* @vite-ignore */ contributions);
|
||||
await editorService().openFile("/dev/acme-api/status.svg");
|
||||
});
|
||||
const toolbar = page.getByRole("toolbar", { name: "Image viewer", exact: true });
|
||||
// Not an SVG yet: the preview says so, and draws the source once it is typed.
|
||||
await expect(page.getByText("The SVG source is not valid.", { exact: true })).toBeVisible();
|
||||
await page.locator(".cm-content").click();
|
||||
await page.keyboard.press("ControlOrMeta+A");
|
||||
await page.keyboard.insertText(
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" width="128" height="96"><rect width="128" height="96"/></svg>',
|
||||
);
|
||||
await expect(page.getByRole("img", { name: "status.svg", exact: true })).toBeVisible();
|
||||
await expect(toolbar.getByText(/128\s*×\s*96/)).toBeVisible();
|
||||
await expect(toolbar.getByRole("button", { name: "Open as Text", exact: true })).toHaveCount(0);
|
||||
|
||||
const layout = page.getByRole("toolbar", { name: "SVG editor layout", exact: true });
|
||||
await layout.getByRole("button", { name: "Preview Only", exact: true }).click();
|
||||
await expect(page.locator(".cm-content")).toBeHidden();
|
||||
await expect(page.getByRole("img", { name: "status.svg", exact: true })).toBeVisible();
|
||||
await layout.getByRole("button", { name: "Editor Only", exact: true }).click();
|
||||
await expect(toolbar).toHaveCount(0);
|
||||
await expect(page.locator(".cm-content")).toBeVisible();
|
||||
});
|
||||
@@ -2362,8 +2362,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 +2891,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 +3776,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
|
||||
|
||||
@@ -118,6 +118,9 @@ pub fn create_host(app: &AppHandle, data_dir: &Path, project_host: &Arc<ide_host
|
||||
host.set_downloads(project_host.global_settings.effective().tool_downloads);
|
||||
#[cfg(target_os = "macos")]
|
||||
host.set_secret_store(Arc::new(KeychainSecrets));
|
||||
// Secret Service / Windows Credential Manager elsewhere, like saved SSH and agent values.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
host.use_credential_store();
|
||||
ide_host::plugins::set_editor_providers(Some(&host));
|
||||
let weak = Arc::downgrade(project_host);
|
||||
host.set_project_policy(Arc::new(move |root| {
|
||||
|
||||
+37
-1
@@ -861,7 +861,7 @@ export const commands = {
|
||||
* The JVM of OpenIDEA's JUnit runner for the module at `module`, given its resolved test classpath:
|
||||
* the classpath with the runner and `junit-platform-launcher` of the engine's version (unless the
|
||||
* classpath has one, or has JUnit 4 alone; from the engine's repository, else downloaded once from
|
||||
* Maven Central), and,
|
||||
* Maven Central unless only the configured package registries are allowed), and,
|
||||
* for a Maven module, what its Surefire configuration gives the forked test JVM.
|
||||
*/
|
||||
javaJunitRunner: (module: string, classPaths: string[]) => typedError<JunitLaunch, IdeError>(__TAURI_INVOKE("java_junit_runner", { module, classPaths })),
|
||||
@@ -5256,6 +5256,8 @@ export type DbColumnInfo = {
|
||||
nullable: boolean,
|
||||
default: string | null,
|
||||
primaryKey: boolean,
|
||||
/** `None` when it has none, or the engine keeps no comments. */
|
||||
comment?: string | null,
|
||||
};
|
||||
|
||||
/** The schema model SQL completion and resolution work from. */
|
||||
@@ -5678,6 +5680,8 @@ export type DbStatementOutcome = {
|
||||
};
|
||||
|
||||
export type DbTableDetails = {
|
||||
/** The table's comment; `None` when it has none, or the engine keeps no comments. */
|
||||
comment?: string | null,
|
||||
columns: DbColumnInfo[],
|
||||
indexes: DbIndexInfo[],
|
||||
foreignKeys: DbForeignKey[],
|
||||
@@ -9158,6 +9162,18 @@ export type LanguageCodeStyle_Deserialize = {
|
||||
keywordCase?: string | null,
|
||||
/** SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`. */
|
||||
identifierCase?: string | null,
|
||||
/**
|
||||
* Java: organize imports switches to a wildcard import once this many
|
||||
* classes of one package are used (jdtls `starThreshold`; IDEA's default
|
||||
* 5; unset keeps the language server's default).
|
||||
*/
|
||||
classCountToUseImportWithStar?: number | null,
|
||||
/**
|
||||
* Java: organize imports switches to a wildcard static import once this
|
||||
* many statically imported names are used (jdtls `staticStarThreshold`;
|
||||
* IDEA's default 3; unset keeps the language server's default).
|
||||
*/
|
||||
namesCountToUseStaticImportWithStar?: number | null,
|
||||
/** JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`. */
|
||||
semicolons?: string | null,
|
||||
/** JavaScript / TypeScript › Punctuation › Quotes: `auto` | `single` | `double`. */
|
||||
@@ -9188,6 +9204,18 @@ export type LanguageCodeStyle_Serialize = {
|
||||
keywordCase?: string | null,
|
||||
/** SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`. */
|
||||
identifierCase?: string | null,
|
||||
/**
|
||||
* Java: organize imports switches to a wildcard import once this many
|
||||
* classes of one package are used (jdtls `starThreshold`; IDEA's default
|
||||
* 5; unset keeps the language server's default).
|
||||
*/
|
||||
classCountToUseImportWithStar?: number | null,
|
||||
/**
|
||||
* Java: organize imports switches to a wildcard static import once this
|
||||
* many statically imported names are used (jdtls `staticStarThreshold`;
|
||||
* IDEA's default 3; unset keeps the language server's default).
|
||||
*/
|
||||
namesCountToUseStaticImportWithStar?: number | null,
|
||||
/** JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`. */
|
||||
semicolons?: string | null,
|
||||
/** JavaScript / TypeScript › Punctuation › Quotes: `auto` | `single` | `double`. */
|
||||
@@ -14164,6 +14192,14 @@ export type ToolDownloadSettings = {
|
||||
* download on its official host.
|
||||
*/
|
||||
githubMirror?: string,
|
||||
/**
|
||||
* Package registries only as configured (a company Nexus or Artifactory): npm and pnpm
|
||||
* installs and update checks never retry against the public npm registry, and the IDE
|
||||
* fetches nothing from public package registries itself (the JUnit Platform launcher from
|
||||
* Maven Central, dependency version completion from Maven Central, npm, PyPI and
|
||||
* crates.io). Off by default.
|
||||
*/
|
||||
configuredRegistriesOnly?: boolean,
|
||||
};
|
||||
|
||||
/** UI-facing state of one tool. */
|
||||
|
||||
@@ -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 } from "@/workbench/contributions";
|
||||
import { maybeEditorService, type EditorInput, type MenuGroupContext } from "@/workbench/contributions";
|
||||
import { isSameOrInside } from "@/platform/paths";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { rootOfPath } from "@/platform/projectRoots";
|
||||
@@ -1017,6 +1017,37 @@ 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. */
|
||||
|
||||
@@ -70,7 +70,8 @@ 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, type LspPopup } from "@/editor/lsp/popupStore";
|
||||
import { caretAnchor, openPopup, updatePopup, useLspPopup } from "@/editor/lsp/popupStore";
|
||||
import { copyPathPopup } from "./copyPathChooser";
|
||||
import {
|
||||
cursorCodeBlockEnd,
|
||||
cursorCodeBlockStart,
|
||||
@@ -80,10 +81,12 @@ import {
|
||||
cursorParagraphBackward,
|
||||
cursorParagraphForward,
|
||||
scrollDown,
|
||||
scrollDownAndMove,
|
||||
scrollToBottom,
|
||||
scrollToCenter,
|
||||
scrollToTop,
|
||||
scrollUp,
|
||||
scrollUpAndMove,
|
||||
selectCodeBlockEnd,
|
||||
selectCodeBlockStart,
|
||||
selectPageBottom,
|
||||
@@ -111,7 +114,7 @@ import {
|
||||
import { useProject } from "@/platform/project";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { menuGroupItems, notifications } from "@/workbench/contributions";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { togglePinSelectedContent } from "@/workbench/toolwindows/content";
|
||||
import { useToolWindowLayout } from "@/workbench/toolwindows/store";
|
||||
import { toggleReadOnly } from "./fileAttributes";
|
||||
@@ -649,22 +652,6 @@ function copyPathReferencePopup(view: EditorView, slot: EditorSlot | null) {
|
||||
// The popup's items resolve against the open document; a notebook cell has none.
|
||||
if (!slot) return;
|
||||
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) },
|
||||
{
|
||||
@@ -681,26 +668,20 @@ function copyPathReferencePopup(view: EditorView, slot: EditorSlot | null) {
|
||||
value: pathWithLines(view.state, path),
|
||||
},
|
||||
];
|
||||
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,
|
||||
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) },
|
||||
[
|
||||
{
|
||||
id: "editor.copyReference",
|
||||
label: tx("Reference"),
|
||||
@@ -710,7 +691,7 @@ function copyPathReferencePopup(view: EditorView, slot: EditorSlot | null) {
|
||||
run: () => {},
|
||||
},
|
||||
],
|
||||
};
|
||||
);
|
||||
openPopup(popup);
|
||||
void resolveReference(view, slot)
|
||||
.then((reference) => {
|
||||
@@ -1080,6 +1061,12 @@ export function registerEditorActions(): () => void {
|
||||
caret("editor.scrollToCenter", "Scroll to Center", (v) => scrollToCenter(v), { category: "Editor Actions" }),
|
||||
caret("editor.scrollUp", "Scroll Up", (v) => scrollUp(v), { category: "Editor Actions" }),
|
||||
caret("editor.scrollDown", "Scroll Down", (v) => scrollDown(v), { category: "Editor Actions" }),
|
||||
caret("editor.scrollUpAndMove", "Scroll Up and Move if Necessary", (v) => scrollUpAndMove(v), {
|
||||
category: "Editor Actions",
|
||||
}),
|
||||
caret("editor.scrollDownAndMove", "Scroll Down and Move if Necessary", (v) => scrollDownAndMove(v), {
|
||||
category: "Editor Actions",
|
||||
}),
|
||||
caret("editor.scrollToTop", "Scroll to Top", (v) => scrollToTop(v), { category: "Editor Actions" }),
|
||||
caret("editor.scrollToBottom", "Scroll to Bottom", (v) => scrollToBottom(v), { category: "Editor Actions" }),
|
||||
caret("editor.moveToPageTop", "Move Caret to Page Top", (v) => cursorPageTop(v), { category: "Editor Actions" }),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { afterEach, beforeAll, describe, expect, it } from "vitest";
|
||||
import { EditorSelection, EditorState, StateEffect } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { indentService, type LanguageSupport } from "@codemirror/language";
|
||||
import { codeFolding, foldEffect, indentService, type LanguageSupport } from "@codemirror/language";
|
||||
import { languages } from "@codemirror/language-data";
|
||||
import { addCursorAbove, insertBlankLine, selectLine, toggleTabFocusMode } from "@codemirror/commands";
|
||||
import {
|
||||
@@ -14,9 +14,11 @@ import {
|
||||
nextParagraphBoundary,
|
||||
previousParagraphBoundary,
|
||||
scrollDown,
|
||||
scrollDownAndMove,
|
||||
scrollToBottom,
|
||||
scrollToTop,
|
||||
scrollUp,
|
||||
scrollUpAndMove,
|
||||
selectPageBottom,
|
||||
selectPageTop,
|
||||
selectParagraphForward,
|
||||
@@ -251,6 +253,104 @@ describe("Move Caret to Page Top / Bottom", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Scroll Up / Down and Move if Necessary", () => {
|
||||
/** jsdom has no layout: a scroller `height` line heights tall, scrolled to `top` line heights. */
|
||||
function scroller(view: EditorView, top: number, height: number) {
|
||||
const line = view.lineBlockAt(0).height;
|
||||
let px = top * line;
|
||||
Object.defineProperty(view.scrollDOM, "scrollTop", {
|
||||
configurable: true,
|
||||
get: () => px,
|
||||
set: (v: number) => (px = Math.max(0, v)),
|
||||
});
|
||||
Object.defineProperty(view, "documentTop", { configurable: true, get: () => -px });
|
||||
Object.defineProperty(view.scrollDOM, "clientHeight", { configurable: true, get: () => height * line });
|
||||
return () => px / line;
|
||||
}
|
||||
const lines = (marked: Record<number, string>) =>
|
||||
Array.from({ length: 10 }, (_, i) => marked[i] ?? `line ${i} text`).join("\n");
|
||||
const lineOf = (view: EditorView) => view.state.selection.ranges.map((r) => view.state.doc.lineAt(r.head).number - 1);
|
||||
const columnOf = (view: EditorView) =>
|
||||
view.state.selection.ranges.map((r) => r.head - view.state.doc.lineAt(r.head).from);
|
||||
|
||||
it("scrolls one line and keeps a caret that stays in view where it is", () => {
|
||||
const view = make(lines({ 4: "line 4 te|xt" }));
|
||||
const top = scroller(view, 2, 4);
|
||||
const before = view.state.selection;
|
||||
expect(scrollDownAndMove(view)).toBe(true);
|
||||
expect(top()).toBe(3);
|
||||
expect(view.state.selection.eq(before)).toBe(true);
|
||||
expect(scrollUpAndMove(view)).toBe(true);
|
||||
expect(top()).toBe(2);
|
||||
expect(view.state.selection.eq(before)).toBe(true);
|
||||
});
|
||||
|
||||
it("brings a caret that scrolls off the top down to the first line, keeping its column", () => {
|
||||
const view = make(lines({ 2: "line 2 te|xt" }));
|
||||
scroller(view, 2, 4);
|
||||
scrollDownAndMove(view);
|
||||
expect([lineOf(view), columnOf(view)]).toEqual([[3], [9]]);
|
||||
});
|
||||
|
||||
it("brings a caret that scrolls off the bottom up to the last line, keeping its column", () => {
|
||||
const view = make(lines({ 5: "li|ne 5 text" }));
|
||||
scroller(view, 2, 4);
|
||||
scrollUpAndMove(view);
|
||||
expect([lineOf(view), columnOf(view)]).toEqual([[4], [2]]);
|
||||
});
|
||||
|
||||
it("moves a caret already out of view to the nearest edge", () => {
|
||||
const view = make(lines({ 9: "line 9 |text" }));
|
||||
scroller(view, 0, 4);
|
||||
scrollDownAndMove(view);
|
||||
expect([lineOf(view), columnOf(view)]).toEqual([[4], [7]]);
|
||||
});
|
||||
|
||||
it("drops the selection of a caret it moves and keeps the others", () => {
|
||||
const view = make(lines({ 0: "|line 0 text" }));
|
||||
const at = (line: number, col: number) => view.state.doc.line(line + 1).from + col;
|
||||
view.dispatch({
|
||||
selection: EditorSelection.create(
|
||||
[EditorSelection.range(at(2, 0), at(2, 4)), EditorSelection.range(at(4, 0), at(4, 4))],
|
||||
1,
|
||||
),
|
||||
});
|
||||
scroller(view, 2, 4);
|
||||
scrollDownAndMove(view);
|
||||
expect(view.state.selection.ranges.map((r) => [r.anchor, r.head])).toEqual([
|
||||
[at(3, 4), at(3, 4)],
|
||||
[at(4, 0), at(4, 4)],
|
||||
]);
|
||||
expect(view.state.selection.mainIndex).toBe(1);
|
||||
});
|
||||
|
||||
it("keeps a caret at the end of a folded block the view shows", () => {
|
||||
const view = make(lines({ 7: "line 7 text|" }));
|
||||
const { doc } = view.state;
|
||||
view.dispatch({
|
||||
effects: [
|
||||
StateEffect.appendConfig.of(codeFolding()),
|
||||
foldEffect.of({ from: doc.line(6).to, to: doc.line(8).to }),
|
||||
],
|
||||
});
|
||||
expect(view.lineBlockAt(doc.line(8).to).from).toBe(doc.line(6).from);
|
||||
const before = view.state.selection;
|
||||
scroller(view, 1, 4);
|
||||
scrollDownAndMove(view);
|
||||
expect(view.state.selection.eq(before)).toBe(true);
|
||||
});
|
||||
|
||||
it("only scrolls at the top of the file when the caret stays in view", () => {
|
||||
const view = make(lines({ 1: "|line 1 text" }));
|
||||
const top = scroller(view, 0, 4);
|
||||
const before = view.state.selection;
|
||||
scrollUpAndMove(view);
|
||||
expect(top()).toBe(0);
|
||||
expect(view.state.selection.eq(before)).toBe(true);
|
||||
expect(view.state.doc.toString()).toBe(lines({}));
|
||||
});
|
||||
});
|
||||
|
||||
describe("code block navigation", () => {
|
||||
let js: LanguageSupport;
|
||||
beforeAll(async () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/** IDEA caret commands that CodeMirror has no equivalent for: Split Line, Scroll to Center / Up / Down / Top / Bottom, Page Top / Bottom, code block, brace and paragraph navigation. */
|
||||
/** IDEA caret commands that CodeMirror has no equivalent for: Split Line, Scroll to Center / Up / Down / Top / Bottom, Scroll Up / Down and Move if Necessary, Page Top / Bottom, code block, brace and paragraph navigation. */
|
||||
import { countColumn, EditorSelection, findColumn, type EditorState, type Transaction } from "@codemirror/state";
|
||||
import { EditorView, type Command } from "@codemirror/view";
|
||||
import { insertNewlineAndIndent } from "@codemirror/commands";
|
||||
@@ -66,15 +66,21 @@ function pageEdgeLine(view: EditorView, edge: "top" | "bottom"): number {
|
||||
return block.top >= bottom || (block.bottom > bottom && previous.top >= top) ? previous.from : block.from;
|
||||
}
|
||||
|
||||
/** `head` moved to the line starting at `lineStart`, keeping its visual column. */
|
||||
function sameColumnOn(state: EditorState, head: number, lineStart: number): number {
|
||||
const line = state.doc.lineAt(head);
|
||||
const target = state.doc.lineAt(lineStart);
|
||||
const column = countColumn(line.text, state.tabSize, head - line.from);
|
||||
return target.from + findColumn(target.text, column, state.tabSize);
|
||||
}
|
||||
|
||||
/** Move Caret to Page Top / Bottom (with Selection): every caret to that line, keeping its column. */
|
||||
function moveToPageEdge(edge: "top" | "bottom", extend = false): Command {
|
||||
return (view) => {
|
||||
const { state } = view;
|
||||
const target = state.doc.lineAt(pageEdgeLine(view, edge));
|
||||
const target = pageEdgeLine(view, edge);
|
||||
const ranges = state.selection.ranges.map((r) => {
|
||||
const line = state.doc.lineAt(r.head);
|
||||
const column = countColumn(line.text, state.tabSize, r.head - line.from);
|
||||
const head = target.from + findColumn(target.text, column, state.tabSize);
|
||||
const head = sameColumnOn(state, r.head, target);
|
||||
return extend ? EditorSelection.range(r.anchor, head) : EditorSelection.cursor(head);
|
||||
});
|
||||
view.dispatch({
|
||||
@@ -90,6 +96,35 @@ export const cursorPageBottom = moveToPageEdge("bottom");
|
||||
export const selectPageTop = moveToPageEdge("top", true);
|
||||
export const selectPageBottom = moveToPageEdge("bottom", true);
|
||||
|
||||
/**
|
||||
* Scroll Up / Down and Move if Necessary: move the viewport by one line, then bring
|
||||
* a caret outside the lines the view shows whole to the first or last of them,
|
||||
* keeping its column. Carets in view keep their place and selection.
|
||||
*/
|
||||
const scrollByLineAndMove =
|
||||
(lines: number): Command =>
|
||||
(view) => {
|
||||
scrollByLine(lines)(view);
|
||||
const { state } = view;
|
||||
const first = pageEdgeLine(view, "top");
|
||||
const last = view.lineBlockAt(pageEdgeLine(view, "bottom"));
|
||||
let moved = false;
|
||||
const ranges = state.selection.ranges.map((r) => {
|
||||
if (r.head >= first && r.head <= last.to) return r;
|
||||
moved = true;
|
||||
return EditorSelection.cursor(sameColumnOn(state, r.head, r.head < first ? first : last.from));
|
||||
});
|
||||
if (moved) {
|
||||
view.dispatch({
|
||||
selection: EditorSelection.create(ranges, state.selection.mainIndex),
|
||||
userEvent: "select.navigate",
|
||||
});
|
||||
}
|
||||
return true;
|
||||
};
|
||||
export const scrollUpAndMove = scrollByLineAndMove(-1);
|
||||
export const scrollDownAndMove = scrollByLineAndMove(1);
|
||||
|
||||
const NOT_CODE = /String|Comment|Regexp|Char|Template/;
|
||||
|
||||
/** `{` / `}` at `pos` when it is code (not inside a string or comment, as far as the syntax tree knows). */
|
||||
|
||||
@@ -24,6 +24,22 @@ import { installKeyboardDispatcher } from "@/platform/keymap";
|
||||
import { TEXT_WHEN } from "./actions";
|
||||
import { EDITOR_WHEN } from "@/editor/lsp/actions";
|
||||
import { setShownLine } from "@/editor/api";
|
||||
import { registerProjectActions } from "@/features/project-tree/actions";
|
||||
|
||||
/** `isTauri` is a spy (File Color writes need it true); the settings commands stand in for the backend. */
|
||||
const ipc = vi.hoisted(() => ({
|
||||
isTauri: vi.fn(() => false),
|
||||
settingsSet: vi.fn(async () => ({ status: "ok" as const, data: {} })),
|
||||
settingsGet: vi.fn(async () => ({})),
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (orig) => {
|
||||
const real = await orig<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...real,
|
||||
isTauri: ipc.isTauri,
|
||||
commands: { ...real.commands, settingsSet: ipc.settingsSet, settingsGet: ipc.settingsGet },
|
||||
};
|
||||
});
|
||||
|
||||
let ctrl: EditorController | null = null;
|
||||
|
||||
@@ -422,6 +438,46 @@ describe("EditorController", () => {
|
||||
expect(pane().tabs.map((t) => t.input.path)).toEqual(["/p/a.ts", "/p/c.ts"]);
|
||||
});
|
||||
|
||||
it("offers the project view's File Color submenu through actions", async () => {
|
||||
useProject.setState({
|
||||
project: { name: "p", root: "/p", trusted: true, isGit: false, settings: {} } as never,
|
||||
settings: {} as never,
|
||||
});
|
||||
ipc.isTauri.mockReturnValue(true);
|
||||
const disposeActions = registerProjectActions();
|
||||
try {
|
||||
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "", "/p/b.ts": "", "/elsewhere/c.ts": "" }));
|
||||
ctrl.start();
|
||||
await ctrl.openFile("/p/a.ts", { focus: false });
|
||||
const pane = () => useTabs.getState().panes[useTabs.getState().activePane]!;
|
||||
const raw = ctrl!.tabMenu(pane().id, pane().tabs[0]!);
|
||||
const entry = raw.find((i) => "label" in i && i.label === "File Color");
|
||||
expect(entry).toBeDefined();
|
||||
const items = resolveMenuItems((entry as { submenu: typeof raw }).submenu);
|
||||
expect(items.filter((i) => i.kind === "item").map((i) => i.label)).toEqual([
|
||||
"Blue",
|
||||
"Green",
|
||||
"Orange",
|
||||
"Rose",
|
||||
"Violet",
|
||||
"Yellow",
|
||||
"Gray",
|
||||
"Edit File Colors…",
|
||||
]);
|
||||
items.find((i) => i.label === "Blue")!.run!();
|
||||
await vi.waitFor(() => expect(ipc.settingsSet).toHaveBeenCalledTimes(2));
|
||||
expect(ipc.settingsSet).toHaveBeenNthCalledWith(1, "project", "scopes", expect.stringContaining('"file:a.ts"'));
|
||||
expect(ipc.settingsSet).toHaveBeenNthCalledWith(2, "project", "fileColors", expect.stringContaining("blue"));
|
||||
// A file outside the project has no File Color, as in the project view.
|
||||
await ctrl.openFile("/elsewhere/c.ts", { focus: false });
|
||||
const outside = pane().tabs.find((t) => t.input.path === "/elsewhere/c.ts")!;
|
||||
expect(ctrl.tabMenu(pane().id, outside).some((i) => "label" in i && i.label === "File Color")).toBe(false);
|
||||
ipc.isTauri.mockReturnValue(false);
|
||||
useProject.setState({ project: null, settings: null });
|
||||
} finally {
|
||||
disposeActions();
|
||||
}
|
||||
});
|
||||
it("keeps editor tabs and unsaved documents through attach and detach", async () => {
|
||||
const settings = {};
|
||||
useProject.setState({
|
||||
|
||||
@@ -12,7 +12,7 @@ import { create } from "zustand";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { formatBinding, hostBinding, shortcutLabel } from "@/platform/keymap";
|
||||
import { isSameOrInside } from "@/platform/paths";
|
||||
import { basename, dirname, useProject } from "@/platform/project";
|
||||
import { basename, dirname, relativePath, useProject } from "@/platform/project";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import {
|
||||
_emitEditorEvent,
|
||||
@@ -60,6 +60,7 @@ import { isUntitledUri, untitledTitle } from "@/platform/virtualDocs";
|
||||
import { isRemoteWindow, projectLocation } from "@/platform/remote";
|
||||
import { auxiliaryWindow } from "@/platform/auxWindow";
|
||||
import { fileIconName, showContextMenu, type MenuItem } from "@/ui";
|
||||
import { FILE_COLOR_NAMES, ownFileColor } from "@/platform/fileColors";
|
||||
import { canOpenWithSystemApp, canRevealInFileManager, fileManagerName } from "@/platform/fileManager";
|
||||
import {
|
||||
activateTab,
|
||||
@@ -2550,6 +2551,9 @@ export class EditorController implements SlotHost {
|
||||
{ kind: "separator" },
|
||||
...(path
|
||||
? ([
|
||||
...(inProject && path !== project!.root
|
||||
? ([{ label: "File Color", submenu: fileColorMenuItems(path) }, { kind: "separator" }] as MenuItem[])
|
||||
: []),
|
||||
{
|
||||
label: "Copy Path/Reference…",
|
||||
submenu: [
|
||||
@@ -2638,6 +2642,26 @@ export class EditorController implements SlotHost {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* File Color submenu of a file tab: the project view's File Color rows as action items carrying
|
||||
* the path (features/project-tree owns the model and the titles), so both menus agree.
|
||||
*/
|
||||
function fileColorMenuItems(path: string): MenuItem[] {
|
||||
const { project, settings } = useProject.getState();
|
||||
const current = project ? ownFileColor(relativePath(project.root, path), false, settings)?.toLowerCase() : null;
|
||||
return [
|
||||
...FILE_COLOR_NAMES.map((name): MenuItem => ({
|
||||
kind: "action",
|
||||
action: `file.${name}`,
|
||||
arg: path,
|
||||
checked: current === name,
|
||||
})),
|
||||
{ kind: "separator" },
|
||||
...(current ? [{ kind: "action" as const, action: "file.clearColor", arg: path }] : []),
|
||||
{ kind: "action", action: "file.editColors" },
|
||||
];
|
||||
}
|
||||
|
||||
/** Open In › for a file: Project View, Finder / Explorer / Files, associated app, Terminal. */
|
||||
function openInMenu(path: string, lines?: { line: number; endLine?: number }): MenuItem {
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
/** 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));
|
||||
}
|
||||
@@ -10,7 +10,8 @@ import {
|
||||
registerOverlay,
|
||||
registerStatusItem,
|
||||
} from "@/workbench/contributions";
|
||||
import { _provideCodePreview, _provideDocumentAttacher, editorsFor } from "@/editor/api";
|
||||
import { _provideCodePreview, _provideCopyPathChooser, _provideDocumentAttacher, editorsFor } from "@/editor/api";
|
||||
import { openCopyPathChooser } from "./copyPathChooser";
|
||||
import { isUntitledUri } from "@/platform/virtualDocs";
|
||||
import { formatDocument } from "@/editor/lsp/format";
|
||||
import { chooserTitle, locationItems, pinToFind } from "@/editor/lsp/navigation";
|
||||
@@ -82,6 +83,7 @@ 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),
|
||||
);
|
||||
|
||||
@@ -307,11 +307,13 @@ export function NavChildrenPopup({
|
||||
segment,
|
||||
anchor,
|
||||
openAbove = true,
|
||||
label,
|
||||
onClose,
|
||||
}: {
|
||||
segment: NavSegment;
|
||||
anchor: HTMLElement;
|
||||
openAbove?: boolean;
|
||||
label?: string;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const [stack, setStack] = useState<NavSegment[]>([segment]);
|
||||
@@ -366,7 +368,7 @@ export function NavChildrenPopup({
|
||||
anchor={anchor}
|
||||
placement={openAbove ? "top-start" : "bottom-start"}
|
||||
onClose={onClose}
|
||||
aria-label={top.label}
|
||||
aria-label={label ?? top.label}
|
||||
className={styles.childPopup}
|
||||
>
|
||||
{stack.length > 1 && (
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
Menu,
|
||||
Popup,
|
||||
SelectListbox,
|
||||
showContextMenu,
|
||||
badgeKind,
|
||||
fileIconName,
|
||||
revealHorizontally,
|
||||
@@ -33,6 +34,7 @@ import { editorController, isTextInput, useEditorStatus, useGotoLine, useTabs }
|
||||
import { languageInfo } from "../cm/languages";
|
||||
import { useDocMeta, useOutline, type DocMeta } from "../model/document";
|
||||
import { symbolChain } from "./outline";
|
||||
import { siblingSegment } from "./navBar";
|
||||
import { NavChildrenPopup } from "./NavBarPopup";
|
||||
import type { NavSegment } from "./navBar";
|
||||
import styles from "./EditorArea.module.css";
|
||||
@@ -166,9 +168,15 @@ function updateBreadcrumbEdges(row: HTMLDivElement) {
|
||||
function BreadcrumbStrip({
|
||||
trail,
|
||||
activateOnDown = false,
|
||||
onActivateAltDown,
|
||||
children,
|
||||
...props
|
||||
}: ComponentPropsWithoutRef<"nav"> & { trail: string; activateOnDown?: boolean }) {
|
||||
}: ComponentPropsWithoutRef<"nav"> & {
|
||||
trail: string;
|
||||
activateOnDown?: boolean;
|
||||
/** Alt+Down on a focused crumb opens its chooser (the crumb's element is passed). */
|
||||
onActivateAltDown?: (crumb: HTMLElement) => void;
|
||||
}) {
|
||||
const strip = useRef<HTMLDivElement>(null);
|
||||
useLayoutEffect(() => {
|
||||
const row = strip.current;
|
||||
@@ -189,10 +197,16 @@ function BreadcrumbStrip({
|
||||
<nav
|
||||
{...props}
|
||||
onKeyDown={(e) => {
|
||||
if (e.altKey || e.ctrlKey || e.metaKey) return;
|
||||
const buttons = [...(strip.current?.querySelectorAll("button") ?? [])];
|
||||
const index = buttons.indexOf(e.target as HTMLButtonElement);
|
||||
if (index < 0) return;
|
||||
if (e.altKey && !e.ctrlKey && !e.metaKey && e.key === "ArrowDown" && onActivateAltDown) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
onActivateAltDown?.(buttons[index]!);
|
||||
return;
|
||||
}
|
||||
if (e.altKey || e.ctrlKey || e.metaKey) return;
|
||||
let next: number;
|
||||
if (e.key === "ArrowLeft") next = Math.max(0, index - 1);
|
||||
else if (e.key === "ArrowRight") next = Math.min(buttons.length - 1, index + 1);
|
||||
@@ -354,6 +368,7 @@ export function CodeBreadcrumbs({
|
||||
const editorSettings = useProject((s) => s.settings?.editor);
|
||||
const language = useDocMeta((s) => s[path]?.language);
|
||||
const outline = useOutline((s) => s[path]);
|
||||
const [popup, setPopup] = useState<{ nav: NavSegment; anchor: HTMLElement } | null>(null);
|
||||
let chain = useCaretSymbols(path, outline);
|
||||
if (!chain) {
|
||||
// Not the active editor (another split): its own caret, as of this render.
|
||||
@@ -373,28 +388,56 @@ export function CodeBreadcrumbs({
|
||||
? monoFontFamily(family, fallbackFont, "var(--font-mono)")
|
||||
: undefined;
|
||||
const fontSize = editorSettings?.fontSize ?? undefined;
|
||||
const navigate = (item: OutlineItem) =>
|
||||
void editorController().openFile(path, {
|
||||
selection: { line: item.selection_range.start.line, col: item.selection_range.start.col },
|
||||
});
|
||||
// IDEA's breadcrumb chooser lives off the click: right-click or Alt+Down on a
|
||||
// crumb lists its siblings (Navigation Bar only).
|
||||
const chooseSiblings = (i: number, anchor: HTMLElement) => {
|
||||
if (!outline) return;
|
||||
setPopup({ nav: siblingSegment(path, chain, i), anchor });
|
||||
};
|
||||
const crumbMenu = (
|
||||
i: number,
|
||||
crumb: HTMLElement,
|
||||
e: { clientX: number; clientY: number; preventDefault: () => void },
|
||||
) => {
|
||||
e.preventDefault();
|
||||
if (outline)
|
||||
showContextMenu(e, [{ id: "chooseSymbol", label: "Choose Symbol…", run: () => chooseSiblings(i, crumb) }]);
|
||||
};
|
||||
return (
|
||||
<BreadcrumbStrip
|
||||
trail={JSON.stringify([path, fontFamily, fontSize, ...chain.map((item) => item.name)])}
|
||||
style={{ fontFamily, fontSize }}
|
||||
className={clsx(styles.codeCrumbs, position === "top" ? styles.codeCrumbsTop : styles.codeCrumbsBottom)}
|
||||
aria-label={tx("Code breadcrumbs")}
|
||||
onActivateAltDown={(crumb) => chooseSiblings(Number(crumb.dataset.crumbIndex), crumb)}
|
||||
>
|
||||
{chain.map((item, i) => (
|
||||
<BarButton
|
||||
key={`${item.name}:${item.detail ?? ""}:${item.selection_range.start.line}:${item.selection_range.start.col}`}
|
||||
data-crumb-index={i}
|
||||
className={styles.crumbButton}
|
||||
tooltip={item.detail ?? item.name}
|
||||
aria-current={i === chain.length - 1 ? "location" : undefined}
|
||||
onClick={() =>
|
||||
void editorController().openFile(path, {
|
||||
selection: { line: item.selection_range.start.line, col: item.selection_range.start.col },
|
||||
})
|
||||
}
|
||||
onClick={() => navigate(item)}
|
||||
onContextMenu={(e) => crumbMenu(i, e.currentTarget, e)}
|
||||
>
|
||||
<span className={styles.crumbLabel}>{item.name}</span>
|
||||
</BarButton>
|
||||
))}
|
||||
{popup && (
|
||||
<NavChildrenPopup
|
||||
key={`${popup.nav.kind}:${popup.nav.path}:${popup.nav.label}`}
|
||||
segment={popup.nav}
|
||||
anchor={popup.anchor}
|
||||
openAbove={position === "bottom"}
|
||||
label={tx("Choose a symbol")}
|
||||
onClose={() => setPopup(null)}
|
||||
/>
|
||||
)}
|
||||
</BreadcrumbStrip>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -67,6 +67,17 @@ export function symbolChildren(path: string, items: readonly OutlineItem[]): Nav
|
||||
return items.map((item) => ({ kind: "symbol", path, label: item.name, item }));
|
||||
}
|
||||
|
||||
/**
|
||||
* The segment whose children are the siblings of `chain[index]` (IDEA / PyCharm
|
||||
* breadcrumb chooser): the file for a top-level symbol, else its enclosing symbol.
|
||||
*/
|
||||
export function siblingSegment(path: string, chain: readonly OutlineItem[], index: number): NavSegment {
|
||||
const parent = index > 0 ? chain[index - 1]! : null;
|
||||
return parent
|
||||
? { kind: "symbol", path, label: parent.name, item: parent }
|
||||
: { kind: "file", path, label: nameOf(path) };
|
||||
}
|
||||
|
||||
export function iconOf(x: NavSegment | NavChild): string {
|
||||
if (x.kind === "dir") return "root" in x && x.root ? "module" : "folder";
|
||||
if (x.kind === "file") return fileIconName(x.label);
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { Profiler } from "react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import type { OutlineItem, Settings } from "@/platform/ipc";
|
||||
import type { EditorStatus } from "../controller";
|
||||
|
||||
const { openFile } = vi.hoisted(() => ({ openFile: vi.fn(async () => {}) }));
|
||||
|
||||
vi.mock("../controller", async () => {
|
||||
const { create } = await import("zustand");
|
||||
return {
|
||||
editorController: () => ({ openFile: vi.fn(), slots: new Map() }),
|
||||
editorController: () => ({ openFile, slots: new Map() }),
|
||||
useEditorStatus: create<{ status: EditorStatus | null }>(() => ({ status: null })),
|
||||
useGotoLine: create(() => ({ open: false })),
|
||||
useTabs: create(() => ({ panes: {}, activePane: "" })),
|
||||
@@ -21,6 +23,7 @@ const { useProject } = await import("@/platform/project");
|
||||
const { clearProjectViewLead, setProjectViewLead } = await import("@/workbench/contributions");
|
||||
const { Breadcrumbs, CodeBreadcrumbs } = await import("./StatusItems");
|
||||
const { NavBarPopup, openNavBarPopup, useNavBarPopup } = await import("./NavBarPopup");
|
||||
const { useContextMenuStore } = await import("@/ui");
|
||||
|
||||
const PATH = "/p/Orders.ts";
|
||||
const span = (from: number, to: number) => ({ start: { line: from, col: 0 }, end: { line: to, col: 0 } });
|
||||
@@ -307,3 +310,78 @@ it("elides the middle of a deep path without a duplicate React key", () => {
|
||||
view.unmount();
|
||||
useProject.setState({ project: null, settings: null });
|
||||
});
|
||||
|
||||
describe("code breadcrumb symbol chooser", () => {
|
||||
beforeEach(() => {
|
||||
openFile.mockClear();
|
||||
useProject.setState({
|
||||
settings: {
|
||||
editor: { breadcrumbs: { show: true, placement: "bottom", disabledLanguages: [] } },
|
||||
} as unknown as Settings,
|
||||
});
|
||||
useEditorStatus.setState({ status: caret(3, 4) });
|
||||
});
|
||||
|
||||
it("navigates to the crumb's symbol on plain click, as the IDE does", async () => {
|
||||
// Orders class with place/cancel methods; caret sits inside `place`.
|
||||
useOutline.setState({ [PATH]: [item("Orders", 0, 40, [item("place", 2, 10), item("cancel", 12, 20)])] });
|
||||
const view = render(<CodeBreadcrumbs path={PATH} tabId="t1" position="bottom" />);
|
||||
const crumbs = screen.getAllByRole("button");
|
||||
// The last crumb is the innermost symbol (place).
|
||||
const place = crumbs[crumbs.length - 1]!;
|
||||
expect(place.getAttribute("aria-haspopup")).toBeNull();
|
||||
fireEvent.click(place);
|
||||
await waitFor(() => expect(openFile).toHaveBeenCalledWith(PATH, { selection: { line: 2, col: 0 } }));
|
||||
// No chooser opened with the click: that belongs to the context menu / Alt+Down.
|
||||
expect(screen.queryByRole("listbox")).toBeNull();
|
||||
view.unmount();
|
||||
});
|
||||
|
||||
it("opens the sibling chooser from the crumb's context menu", async () => {
|
||||
useOutline.setState({ [PATH]: [item("Orders", 0, 40, [item("place", 2, 10), item("cancel", 12, 20)])] });
|
||||
const view = render(<CodeBreadcrumbs path={PATH} tabId="t1" position="bottom" />);
|
||||
const crumbs = screen.getAllByRole("button");
|
||||
fireEvent.contextMenu(crumbs[crumbs.length - 1]!);
|
||||
const menuItem = useContextMenuStore
|
||||
.getState()
|
||||
.menu?.items.find((i) => "label" in i && i.label === "Choose Symbol…") as { run?: () => void } | undefined;
|
||||
expect(menuItem?.run).toBeTruthy();
|
||||
act(() => menuItem!.run!());
|
||||
const list = await screen.findByRole("listbox", { name: "Orders" });
|
||||
expect(list.querySelectorAll('[role="option"]').length).toBeGreaterThan(0);
|
||||
// Selecting a sibling navigates.
|
||||
fireEvent.click(screen.getByRole("option", { name: "cancel" }));
|
||||
await waitFor(() =>
|
||||
expect(openFile).toHaveBeenCalledWith(PATH, {
|
||||
selection: { line: 12, col: 0 },
|
||||
focus: true,
|
||||
}),
|
||||
);
|
||||
view.unmount();
|
||||
});
|
||||
|
||||
it("opens the sibling chooser with Alt+Down while the strip has focus", async () => {
|
||||
useOutline.setState({ [PATH]: [item("Orders", 0, 40, [item("place", 2, 10), item("cancel", 12, 20)])] });
|
||||
const view = render(<CodeBreadcrumbs path={PATH} tabId="t1" position="bottom" />);
|
||||
const crumbs = screen.getAllByRole("button");
|
||||
const place = crumbs[crumbs.length - 1]!;
|
||||
place.focus();
|
||||
fireEvent.keyDown(place, { key: "ArrowDown", altKey: true });
|
||||
await screen.findByRole("listbox", { name: "Orders" });
|
||||
fireEvent.click(screen.getByRole("option", { name: "cancel" }));
|
||||
await waitFor(() =>
|
||||
expect(openFile).toHaveBeenCalledWith(PATH, {
|
||||
selection: { line: 12, col: 0 },
|
||||
focus: true,
|
||||
}),
|
||||
);
|
||||
view.unmount();
|
||||
});
|
||||
|
||||
it("hides the bar when there is no outline chain", () => {
|
||||
useOutline.setState({ [PATH]: [] });
|
||||
const view = render(<CodeBreadcrumbs path={PATH} tabId="t1" position="bottom" />);
|
||||
expect(screen.queryByRole("navigation", { name: "Code breadcrumbs" })).toBeNull();
|
||||
view.unmount();
|
||||
});
|
||||
});
|
||||
@@ -63,6 +63,7 @@ import { parameterInfoOrLeave, triggerSignatureHelp } from "./signature";
|
||||
import { featureBackoff } from "./availability";
|
||||
import { pathCompletionSource, pathContext, pathLike } from "./fileReferences";
|
||||
import { cssVariablePrefix, cssVariableSource, STYLESHEETS, type VariableOption } from "./cssVariables";
|
||||
import { javaDeclarationAt, variableNameSource } from "./variableNames";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { showHint } from "./hint";
|
||||
@@ -930,6 +931,9 @@ function gated(source: CompletionSource): CompletionSource {
|
||||
if (ctx.state.field(smartLookup, false) && source !== claimingLspSource) return null;
|
||||
const only = exclusiveSource(ctx);
|
||||
if (only) return source === contributedSource ? only(ctx) : null;
|
||||
// At a Java declaration's name only names fit: IDEA lists no live templates there, and
|
||||
// jdtls' own name proposals repeat the type (`orderBookOrderBook`).
|
||||
if (source !== variableNameSource && javaDeclarationAt(ctx)) return null;
|
||||
if (!ctx.explicit && (!editorPrefs().completion.autoPopup || inplaceRenameActive(ctx.state))) return null;
|
||||
if (!editorPrefs().completion.sortAlphabetically) return source(ctx);
|
||||
return Promise.resolve(source(ctx)).then(
|
||||
@@ -1208,6 +1212,7 @@ export function completionExtension() {
|
||||
gated(contributedSource),
|
||||
gated(pathFallbackSource),
|
||||
gated(cssVariableSource),
|
||||
gated(variableNameSource),
|
||||
],
|
||||
icons: false,
|
||||
addToOptions: [
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { declarationAt, namesForType, pluralize } from "./variableNames";
|
||||
|
||||
const names = (before: string) => {
|
||||
const found = declarationAt(before);
|
||||
return found ? namesForType(found.type) : null;
|
||||
};
|
||||
|
||||
describe("variable names by type (IDEA)", () => {
|
||||
it("suggests the type's name and its shorter endings", () => {
|
||||
expect(names(" private IMesCheckStandardService c")).toEqual([
|
||||
"iMesCheckStandardService",
|
||||
"mesCheckStandardService",
|
||||
"checkStandardService",
|
||||
"standardService",
|
||||
"service",
|
||||
]);
|
||||
expect(names(" MesProductPlan p")).toEqual(["mesProductPlan", "productPlan", "plan"]);
|
||||
expect(names(" UserServiceImpl ")).toEqual(["userService", "service"]);
|
||||
expect(names(" HttpURLConnection c")).toEqual(["httpURLConnection", "urlConnection", "connection"]);
|
||||
});
|
||||
|
||||
it("names collections, arrays, optionals and generic types by their contents", () => {
|
||||
expect(names("List<MesProductCheck> l")).toEqual([
|
||||
"mesProductChecks",
|
||||
"productChecks",
|
||||
"checks",
|
||||
"mesProductCheckList",
|
||||
"productCheckList",
|
||||
"checkList",
|
||||
"list",
|
||||
]);
|
||||
expect(names("Order[] ")).toEqual(["orders"]);
|
||||
expect(names("Optional<User> ")).toEqual(["user", "optionalUser", "userOptional", "optional"]);
|
||||
expect(names("Map<String, Order> ")).toEqual(["stringOrderMap", "orderMap", "map"]);
|
||||
expect(pluralize("Category")).toBe("Categories");
|
||||
expect(pluralize("Box")).toBe("Boxes");
|
||||
});
|
||||
|
||||
it("gives locals and parameters IDEA's short names", () => {
|
||||
expect(names(" String ")).toEqual(["s", "string"]);
|
||||
expect(names(" private String ")).toEqual(["string"]);
|
||||
expect(names(" int ")).toEqual(["i"]);
|
||||
expect(names(" } catch (IOException ")).toEqual(["e", "ioException", "exception"]);
|
||||
expect(names("void run(Order o")).toEqual(["order"]);
|
||||
});
|
||||
|
||||
it("is quiet where no name is declared", () => {
|
||||
expect(declarationAt(" return Foo")).toBeNull();
|
||||
expect(declarationAt(" return value ")).toBeNull();
|
||||
expect(declarationAt("class Foo ")).toBeNull();
|
||||
expect(declarationAt(" throw new Error ")).toBeNull();
|
||||
expect(declarationAt("@Autowired ")).toBeNull();
|
||||
expect(declarationAt(" private c")).toBeNull();
|
||||
expect(declarationAt(" var x")).toBeNull();
|
||||
expect(declarationAt(" foo.bar")).toBeNull();
|
||||
expect(declarationAt(" Foo f")).toEqual({ type: expect.objectContaining({ name: "Foo" }), typed: "f" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,211 @@
|
||||
/**
|
||||
* Variable names by type, as IDEA's JavaCodeStyleManager suggests them: typing the name of a
|
||||
* Java declaration (`private IUserService |`, `List<Order> |`, `catch (IOException |`) lists
|
||||
* `userService`, `service`, `orders`, `e`… The language server offers nothing there.
|
||||
*/
|
||||
import type { Completion, CompletionContext, CompletionResult } from "@codemirror/autocomplete";
|
||||
import { syntaxTree } from "@codemirror/language";
|
||||
import { lspDoc } from "./lsp";
|
||||
|
||||
/** The declared type at a name being typed: `Map<String, Order>[]` → `Map`, `[String, Order]`, array. */
|
||||
export interface DeclaredType {
|
||||
name: string;
|
||||
args: string[];
|
||||
array: boolean;
|
||||
kind: "field" | "parameter" | "local";
|
||||
}
|
||||
|
||||
const PRIMITIVES = new Set(["int", "long", "short", "byte", "char", "boolean", "float", "double"]);
|
||||
|
||||
/** Words before a type that make what follows something other than a declaration's name. */
|
||||
const NOT_A_DECLARATION = new Set([
|
||||
"new",
|
||||
"class",
|
||||
"interface",
|
||||
"enum",
|
||||
"record",
|
||||
"extends",
|
||||
"implements",
|
||||
"permits",
|
||||
"throws",
|
||||
"import",
|
||||
"package",
|
||||
"return",
|
||||
"throw",
|
||||
"yield",
|
||||
"assert",
|
||||
"goto",
|
||||
"var",
|
||||
"this",
|
||||
"super",
|
||||
]);
|
||||
|
||||
const FIELD_MODIFIERS = /\b(?:private|protected|public|static|volatile|transient)\b/;
|
||||
|
||||
const DECLARATION =
|
||||
/(^|[\s(,;{}])((?:[A-Za-z_$][\w$]*\.)*[A-Za-z_$][\w$]*)\s*(<[^;(){}=]*>)?((?:\s*\[\s*\])*)\s+([A-Za-z_$][\w$]*)?$/;
|
||||
|
||||
/**
|
||||
* The type whose variable's name ends `before` (the line up to the caret), with the name typed so
|
||||
* far; null when the caret isn't at a declared name.
|
||||
*/
|
||||
export function declarationAt(before: string): { type: DeclaredType; typed: string } | null {
|
||||
const m = DECLARATION.exec(before);
|
||||
if (!m) return null;
|
||||
const qualified = m[2]!;
|
||||
const name = qualified.slice(qualified.lastIndexOf(".") + 1);
|
||||
if (!PRIMITIVES.has(name) && !/^[A-Z]/.test(name)) return null;
|
||||
const head = before.slice(0, m.index + m[1]!.length);
|
||||
const previous = /([A-Za-z_@][\w]*)\s*$/.exec(head)?.[1];
|
||||
if (previous && (NOT_A_DECLARATION.has(previous) || previous.startsWith("@"))) return null;
|
||||
if (/@\s*$/.test(head)) return null;
|
||||
const params = /[(,]\s*$/.test(head) || /\(\s*(?:final\s+)?$/.test(head) || /\bcatch\s*\(\s*$/.test(head);
|
||||
const kind = params ? "parameter" : FIELD_MODIFIERS.test(head) ? "field" : "local";
|
||||
return {
|
||||
type: { name, args: typeArguments(m[3] ?? ""), array: !!m[4]?.trim(), kind },
|
||||
typed: m[5] ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
/** The top-level type arguments' simple names (`<String, List<Order>>` → `String`, `List`); `?` and bounds skipped. */
|
||||
function typeArguments(generic: string): string[] {
|
||||
const inner = generic.slice(1, -1);
|
||||
const out: string[] = [];
|
||||
let depth = 0;
|
||||
let current = "";
|
||||
for (const ch of inner) {
|
||||
if (ch === "<") depth++;
|
||||
if (ch === ">") depth--;
|
||||
if (ch === "," && depth === 0) {
|
||||
out.push(current);
|
||||
current = "";
|
||||
} else if (depth === 0 && ch !== ">") current += ch;
|
||||
}
|
||||
out.push(current);
|
||||
return out
|
||||
.map((a) => a.trim())
|
||||
.filter((a) => /^[A-Za-z_$][\w$.]*$/.test(a))
|
||||
.map((a) => a.slice(a.lastIndexOf(".") + 1));
|
||||
}
|
||||
|
||||
/** IDEA's NameUtilCore.nameToWordList: `IUserURLService` → `I`, `User`, `URL`, `Service`. */
|
||||
function words(name: string): string[] {
|
||||
return name.match(/[A-Z]+(?![a-z])|[A-Z]?[a-z0-9]+|[A-Z]/g) ?? [];
|
||||
}
|
||||
|
||||
/** StringUtil.pluralize for the usual cases. */
|
||||
export function pluralize(word: string): string {
|
||||
if (/(?:s|x|z|ch|sh)$/i.test(word)) return `${word}es`;
|
||||
if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
|
||||
return `${word}s`;
|
||||
}
|
||||
|
||||
/** `UserService` → `userService`, `service` (longest first); an all-caps first word goes lower case. */
|
||||
function suffixNames(name: string): string[] {
|
||||
const ws = words(name);
|
||||
const out: string[] = [];
|
||||
for (let i = 0; i < ws.length; i++) {
|
||||
const first = ws[i]!;
|
||||
if (!/^[A-Za-z]/.test(first)) continue;
|
||||
const head = first === first.toUpperCase() ? first.toLowerCase() : first[0]!.toLowerCase() + first.slice(1);
|
||||
out.push(head + ws.slice(i + 1).join(""));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const SHORT_NAMES: Record<string, string> = {
|
||||
int: "i",
|
||||
boolean: "b",
|
||||
byte: "b",
|
||||
char: "c",
|
||||
long: "l",
|
||||
short: "i",
|
||||
double: "v",
|
||||
float: "v",
|
||||
Integer: "i",
|
||||
Short: "i",
|
||||
Long: "l",
|
||||
Boolean: "b",
|
||||
Byte: "b",
|
||||
Character: "c",
|
||||
Double: "v",
|
||||
Float: "v",
|
||||
Object: "o",
|
||||
String: "s",
|
||||
};
|
||||
|
||||
const ITERABLES = new Set([
|
||||
"Iterable",
|
||||
"Collection",
|
||||
"List",
|
||||
"ArrayList",
|
||||
"LinkedList",
|
||||
"Set",
|
||||
"HashSet",
|
||||
"LinkedHashSet",
|
||||
"TreeSet",
|
||||
"SortedSet",
|
||||
"NavigableSet",
|
||||
"Queue",
|
||||
"Deque",
|
||||
"ArrayDeque",
|
||||
"PriorityQueue",
|
||||
"Stack",
|
||||
"Vector",
|
||||
"CopyOnWriteArrayList",
|
||||
]);
|
||||
|
||||
/** `UserServiceImpl` names a `userService`, as in IDEA. */
|
||||
const normalize = (name: string) => (name.length > 4 && name.endsWith("Impl") ? name.slice(0, -4) : name);
|
||||
|
||||
const JAVA_KEYWORDS = new Set(
|
||||
(
|
||||
"abstract assert boolean break byte case catch char class const continue default do double else enum extends " +
|
||||
"final finally float for goto if implements import instanceof int interface long native new package private " +
|
||||
"protected public return short static strictfp super switch synchronized this throw throws transient try void " +
|
||||
"volatile while true false null var record yield"
|
||||
).split(" "),
|
||||
);
|
||||
|
||||
/** The names IDEA suggests for a variable of `type`, best first. */
|
||||
export function namesForType(type: DeclaredType): string[] {
|
||||
const base: string[] = [];
|
||||
const short = type.kind === "field" ? undefined : SHORT_NAMES[type.name];
|
||||
if (short) base.push(type.array ? pluralize(short) : short);
|
||||
const name = normalize(type.name);
|
||||
if (type.args.length === 1 && ITERABLES.has(type.name)) base.push(pluralize(normalize(type.args[0]!)));
|
||||
if (type.args.length === 1 && type.name === "Optional") {
|
||||
const content = normalize(type.args[0]!);
|
||||
base.push(content, `optional${content}`);
|
||||
}
|
||||
if (type.args.length) base.push(type.args.map(normalize).join("") + name);
|
||||
const own = type.array ? pluralize(name) : name;
|
||||
if (type.kind === "parameter" && type.name.endsWith("Exception")) base.push("e");
|
||||
base.push(own);
|
||||
if (own.length > "Entity".length && own.endsWith("Entity")) base.push(own.slice(0, -"Entity".length));
|
||||
const out: string[] = [];
|
||||
for (const b of base) {
|
||||
for (const n of PRIMITIVES.has(b) || b.length === 1 ? [b] : suffixNames(b)) {
|
||||
if (!out.includes(n) && !JAVA_KEYWORDS.has(n) && /^[A-Za-z_$][\w$]*$/.test(n)) out.push(n);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The declaration under the caret in a Java file (not in a comment or string), or null. */
|
||||
export function javaDeclarationAt(ctx: CompletionContext): { type: DeclaredType; typed: string } | null {
|
||||
if (ctx.state.facet(lspDoc)?.language !== "java") return null;
|
||||
const node = syntaxTree(ctx.state).resolveInner(ctx.pos, -1);
|
||||
if (/Comment|String|TextBlock/.test(node.name)) return null;
|
||||
const line = ctx.state.doc.lineAt(ctx.pos);
|
||||
return declarationAt(line.text.slice(0, ctx.pos - line.from));
|
||||
}
|
||||
|
||||
/** Completion source: the type's names at a Java declaration's name. */
|
||||
export function variableNameSource(ctx: CompletionContext): CompletionResult | null {
|
||||
const found = javaDeclarationAt(ctx);
|
||||
if (!found) return null;
|
||||
const names = namesForType(found.type);
|
||||
const options: Completion[] = names.map((label, i) => ({ label, type: "variable", boost: 50 - i }));
|
||||
return options.length ? { from: ctx.pos - found.typed.length, options, validFor: /^[\w$]*$/ } : null;
|
||||
}
|
||||
@@ -24,7 +24,9 @@ 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,
|
||||
@@ -100,6 +102,18 @@ 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",
|
||||
@@ -941,17 +955,21 @@ export function Composer(props: ComposerProps) {
|
||||
};
|
||||
}, [addPaths, addImages]);
|
||||
|
||||
// Files and folders dragged from the Project view: the same `@` references.
|
||||
// Files and folders dragged from the Project view, and file tabs dragged from the editor:
|
||||
// the same `@` references.
|
||||
useEffect(() => {
|
||||
const el = boxRef.current;
|
||||
if (!el) return;
|
||||
return registerDropTarget(el, {
|
||||
accepts: (type) => type === FILES_DRAG,
|
||||
accepts: (type, data) => type === FILES_DRAG || (type === EDITOR_TAB_MIME && !!tabFilePath(data.payload)),
|
||||
over: () => setFileOver(true),
|
||||
leave: () => setFileOver(false),
|
||||
drop: (data) => {
|
||||
setFileOver(false);
|
||||
addPaths(data.payload.split("\n").filter(Boolean));
|
||||
if (data.type === EDITOR_TAB_MIME) {
|
||||
const path = tabFilePath(data.payload);
|
||||
if (path) addPaths([path]);
|
||||
} else addPaths(data.payload.split("\n").filter(Boolean));
|
||||
},
|
||||
});
|
||||
}, [addPaths]);
|
||||
|
||||
@@ -7,6 +7,7 @@ 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();
|
||||
@@ -123,6 +124,32 @@ 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", "projectView"],
|
||||
menus: ["editor", "editorTab", "projectView"],
|
||||
order: 80,
|
||||
items: (menu, { paths, dirs }) =>
|
||||
paths.length && !paths.some(isVirtualUri) && agentsHere()
|
||||
@@ -240,7 +240,8 @@ export function activate(): () => void {
|
||||
{
|
||||
kind: "action",
|
||||
action: "agents.sendToAgent",
|
||||
arg: menu === "projectView" ? paths.map((p, i) => (dirs?.[i] ? `${p}/` : p)) : undefined,
|
||||
// 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)),
|
||||
},
|
||||
]
|
||||
: [],
|
||||
|
||||
@@ -3,6 +3,7 @@ import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import type { AgentEntry, AgentEvent, AgentTask } from "@/bindings";
|
||||
import {
|
||||
dropOnEditor,
|
||||
menuGroupItems,
|
||||
useContributions,
|
||||
useEditorTabTitles,
|
||||
type EditorInput,
|
||||
@@ -595,3 +596,20 @@ 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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -70,6 +70,70 @@ 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)),
|
||||
),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/** Copy as › SQL INSERT / UPDATE / DELETE of the whole selected rows, in the selected order. */
|
||||
function sqlCopies(rows: readonly number[], extractor: ExtractorMenu): MenuItem[] {
|
||||
const copy = (format: ExportFormat) => () =>
|
||||
void Promise.resolve(extractor.table()).then((data) => {
|
||||
const picked = data && rows.flatMap((r) => (data.rows[r] ? [data.rows[r]] : []));
|
||||
if (picked?.length) void writeClipboardText(exportData(format, { ...data!, rows: picked }));
|
||||
});
|
||||
return [
|
||||
{ label: "SQL INSERT", run: copy("sql") },
|
||||
{ label: "SQL UPDATE", run: copy("sqlUpdates") },
|
||||
{ label: "SQL DELETE", run: copy("sqlDeletes") },
|
||||
];
|
||||
}
|
||||
|
||||
/** 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 (
|
||||
@@ -117,6 +181,8 @@ 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;
|
||||
@@ -248,7 +314,12 @@ export function DataView(props: DataViewProps) {
|
||||
driver={props.driver}
|
||||
sort={sort}
|
||||
onSort={onSort}
|
||||
rowMenu={props.rowMenu && ((rows) => props.rowMenu!(rows.map(at)))}
|
||||
copyAs={props.extractor && ((rows) => sqlCopies(rows.map(at), props.extractor!))}
|
||||
rowMenu={(rows) => {
|
||||
const own = props.rowMenu?.(rows.map(at)) ?? [];
|
||||
const view = viewMenu(panel, onPanelChange, props.extractor);
|
||||
return own.length ? [...own, { kind: "separator" }, ...view] : view;
|
||||
}}
|
||||
rowNumber={(r) => (props.firstRowNumber ?? 1) + at(r)}
|
||||
copyFormat={props.copyFormat}
|
||||
onSelectionChange={setRange}
|
||||
|
||||
@@ -954,6 +954,23 @@
|
||||
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;
|
||||
|
||||
@@ -10,6 +10,7 @@ import { notifications } from "@/workbench/contributions";
|
||||
import {
|
||||
DEFAULT_EXPORT_OPTIONS,
|
||||
EXPORT_FORMATS,
|
||||
SQL_FORMATS,
|
||||
exportData,
|
||||
type ExportData,
|
||||
type ExportFormat,
|
||||
@@ -169,7 +170,7 @@ export function ExportDialog({
|
||||
<CodePreview
|
||||
className={styles.exportPreviewText}
|
||||
aria-label="Export preview"
|
||||
sql={format === "sql"}
|
||||
sql={SQL_FORMATS.has(format)}
|
||||
text={preview + (data.rows.length > PREVIEW_ROWS ? `\n… ${data.rows.length - PREVIEW_ROWS} more rows` : "")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1013,3 +1013,106 @@ describe("local filter (#6022)", () => {
|
||||
expect(cities()).toEqual(["Shanghai", "Beijing", "Shenzhen", "Hangzhou"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the data view's context menu (DataGrip)", () => {
|
||||
const columns = [
|
||||
{ name: "id", type: "int" },
|
||||
{ name: "city", type: "text" },
|
||||
];
|
||||
const data = [
|
||||
["1", "Shanghai"],
|
||||
["2", "Beijing"],
|
||||
];
|
||||
const value = (r: number, c: number) => data[r]?.[c] ?? null;
|
||||
|
||||
it("toggles the side panels, switches the extractor and exports the whole table to the clipboard", async () => {
|
||||
const writeText = vi.fn(() => Promise.resolve());
|
||||
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } });
|
||||
const onPanelChange = vi.fn();
|
||||
const onExtractor = vi.fn();
|
||||
const table = () => ({ columns, rows: data, table: "cities", driver: "postgres" as const });
|
||||
const { rerender } = render(
|
||||
<>
|
||||
<DataView
|
||||
columns={columns}
|
||||
rowCount={2}
|
||||
value={value}
|
||||
panel="value"
|
||||
onPanelChange={onPanelChange}
|
||||
extractor={{ value: "csv", onChange: onExtractor, table }}
|
||||
/>
|
||||
<ContextMenuHost />
|
||||
</>,
|
||||
);
|
||||
const open = () => {
|
||||
fireEvent.mouseDown(screen.getAllByRole("gridcell")[0]!, { button: 0 });
|
||||
fireEvent.contextMenu(screen.getByRole("grid"), { clientX: 5, clientY: 5 });
|
||||
};
|
||||
open();
|
||||
expect(screen.getByRole("menuitemcheckbox", { name: /Open in Value Editor/ })).toHaveAttribute(
|
||||
"aria-checked",
|
||||
"true",
|
||||
);
|
||||
fireEvent.click(screen.getByRole("menuitemcheckbox", { name: /Show Record View/ }));
|
||||
expect(onPanelChange).toHaveBeenLastCalledWith("record");
|
||||
open();
|
||||
// The shown panel's entry hides it.
|
||||
fireEvent.click(screen.getByRole("menuitemcheckbox", { name: /Open in Value Editor/ }));
|
||||
expect(onPanelChange).toHaveBeenLastCalledWith(null);
|
||||
|
||||
open();
|
||||
await act(async () => void fireEvent.click(screen.getByRole("menuitem", { name: /Export Table to Clipboard/ })));
|
||||
expect(writeText).toHaveBeenCalledWith(exportData("csv", table()));
|
||||
|
||||
open();
|
||||
fireEvent.click(screen.getByRole("menuitem", { name: /Data Extractor/ }));
|
||||
expect(screen.getByRole("menuitemcheckbox", { name: /^CSV/ })).toHaveAttribute("aria-checked", "true");
|
||||
fireEvent.click(screen.getByRole("menuitemcheckbox", { name: /SQL Inserts/ }));
|
||||
expect(onExtractor).toHaveBeenCalledWith("sql");
|
||||
|
||||
// Without an extractor (a view with no toolbar one) only the panels are offered.
|
||||
rerender(
|
||||
<>
|
||||
<DataView columns={columns} rowCount={2} value={value} panel={null} onPanelChange={onPanelChange} />
|
||||
<ContextMenuHost />
|
||||
</>,
|
||||
);
|
||||
open();
|
||||
expect(screen.queryByRole("menuitem", { name: /Export Table to Clipboard/ })).toBeNull();
|
||||
expect(screen.getByRole("menuitemcheckbox", { name: /Show Aggregate View/ })).toHaveAttribute(
|
||||
"aria-checked",
|
||||
"false",
|
||||
);
|
||||
});
|
||||
|
||||
it("copies the selected whole rows as SQL INSERT / UPDATE / DELETE (#6143)", async () => {
|
||||
const writeText = vi.fn((_text: string) => Promise.resolve());
|
||||
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } });
|
||||
const keyed = [{ ...columns[0]!, primaryKey: true }, columns[1]!];
|
||||
const table = () => ({ columns: keyed, rows: data, table: "cities", driver: "postgres" as const });
|
||||
render(
|
||||
<>
|
||||
<DataView
|
||||
columns={keyed}
|
||||
rowCount={2}
|
||||
value={value}
|
||||
panel={null}
|
||||
onPanelChange={() => {}}
|
||||
extractor={{ value: "csv", onChange: () => {}, table }}
|
||||
/>
|
||||
<ContextMenuHost />
|
||||
</>,
|
||||
);
|
||||
// Only the second row's city cell: the statements still cover its whole row.
|
||||
fireEvent.mouseDown(screen.getAllByRole("gridcell")[3]!, { button: 0 });
|
||||
const copyAs = async (entry: string) => {
|
||||
fireEvent.contextMenu(screen.getByRole("grid"), { clientX: 5, clientY: 5 });
|
||||
fireEvent.click(screen.getByRole("menuitem", { name: /^Copy as/ }));
|
||||
await act(async () => void fireEvent.click(screen.getByRole("menuitem", { name: new RegExp(`^${entry}`) })));
|
||||
return writeText.mock.lastCall?.[0];
|
||||
};
|
||||
expect(await copyAs("SQL INSERT")).toBe("INSERT INTO cities (id, city) VALUES (2, 'Beijing');");
|
||||
expect(await copyAs("SQL UPDATE")).toBe("UPDATE cities SET city = 'Beijing' WHERE id = 2;");
|
||||
expect(await copyAs("SQL DELETE")).toBe("DELETE FROM cities WHERE id = 2;");
|
||||
});
|
||||
});
|
||||
@@ -86,6 +86,8 @@ export interface GridProps {
|
||||
onSort?: (column: string, add: boolean) => void;
|
||||
/** Extra context menu items for the selected rows. */
|
||||
rowMenu?: (rows: number[]) => MenuItem[];
|
||||
/** More Copy as entries for the selected rows (SQL statements of the whole rows). */
|
||||
copyAs?: (rows: number[]) => MenuItem[];
|
||||
/** Row number shown for row 0 (paging). */
|
||||
firstRowNumber?: number;
|
||||
/** Row number shown for a row (local sort / filter reorder them); `firstRowNumber + row` otherwise. */
|
||||
@@ -629,6 +631,10 @@ export function Grid(props: GridProps) {
|
||||
{ kind: "action", action: "db.copyAsTsv", label: "TSV", arg: cellActions.current },
|
||||
{ kind: "action", action: "db.copyAsCsv", label: "CSV", arg: cellActions.current },
|
||||
{ kind: "action", action: "db.copyAsOneRow", label: "One-Row", arg: cellActions.current },
|
||||
...(() => {
|
||||
const more = props.copyAs?.(selectedRows()) ?? [];
|
||||
return more.length ? [{ kind: "separator" } as const, ...more] : [];
|
||||
})(),
|
||||
],
|
||||
},
|
||||
{ kind: "action", action: "db.copyWithHeader", arg: cellActions.current },
|
||||
|
||||
@@ -4,7 +4,14 @@
|
||||
* Preview of the SQL they run), Remove Data Source, Data Source from URL, and the Quick Documentation popup.
|
||||
*/
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { call, commands, type DbColumnInfo, type DbDriver, type DbTableGrant } from "@/platform/ipc";
|
||||
import {
|
||||
call,
|
||||
commands,
|
||||
type DbColumnInfo,
|
||||
type DbDriver,
|
||||
type DbTableDetails,
|
||||
type DbTableGrant,
|
||||
} from "@/platform/ipc";
|
||||
import { highlightInto } from "@/editor/lsp/markdown";
|
||||
import {
|
||||
Button,
|
||||
@@ -14,6 +21,7 @@ import {
|
||||
Input,
|
||||
Popup,
|
||||
Icon,
|
||||
SearchField,
|
||||
Select,
|
||||
T,
|
||||
Tabs,
|
||||
@@ -27,6 +35,8 @@ import {
|
||||
canAlterColumn,
|
||||
createDatabaseSql,
|
||||
createSchemaSql,
|
||||
commentsSupported,
|
||||
createTableCommentSql,
|
||||
createTableSql,
|
||||
draftOf,
|
||||
dropDatabaseSql,
|
||||
@@ -52,6 +62,7 @@ import {
|
||||
renameDatabase,
|
||||
loadDetails,
|
||||
loadGrants,
|
||||
loadTables,
|
||||
openSourceDialog,
|
||||
readableDdl,
|
||||
refresh,
|
||||
@@ -538,6 +549,7 @@ function blankColumn(driver: DbDriver, n: number): ColumnDraft {
|
||||
notNull: false,
|
||||
default: "",
|
||||
primaryKey: false,
|
||||
comment: "",
|
||||
dropped: false,
|
||||
};
|
||||
}
|
||||
@@ -551,7 +563,8 @@ function ModifyTableDialog(props: ModifyProps) {
|
||||
if (table && !details) void loadDetails(id, schema, table);
|
||||
}, [details, id, schema, table]);
|
||||
if (!table) return <ModifyTableForm {...props} initial={null} />;
|
||||
if (details?.status === "ok") return <ModifyTableForm {...props} initial={details.value.columns} />;
|
||||
if (details?.status === "ok")
|
||||
return <ModifyTableForm {...props} initial={details.value.columns} details={details.value} />;
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
@@ -565,6 +578,64 @@ function ModifyTableDialog(props: ModifyProps) {
|
||||
);
|
||||
}
|
||||
|
||||
/** A read-only row of the Modify Table list (a key, foreign key, index or trigger). */
|
||||
interface ObjectRow {
|
||||
key: string;
|
||||
name: string;
|
||||
detail: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The groups after Columns, as DataGrip lists them: the primary key of the columns as edited,
|
||||
* then the foreign keys, indexes and triggers the table has (shown, not edited here).
|
||||
*/
|
||||
function objectGroups(
|
||||
columns: readonly ColumnDraft[],
|
||||
details: DbTableDetails | null | undefined,
|
||||
): Array<{ id: string; label: string; icon: string; rows: ObjectRow[] }> {
|
||||
const pk = columns.filter((c) => c.primaryKey && !c.dropped).map((c) => c.name);
|
||||
const list = (names: readonly string[]) => `(${names.join(", ")})`;
|
||||
return [
|
||||
{
|
||||
id: "keys",
|
||||
label: "Keys",
|
||||
icon: "db-key",
|
||||
rows: pk.length ? [{ key: "primary", name: "PRIMARY KEY", detail: list(pk) }] : [],
|
||||
},
|
||||
{
|
||||
id: "foreignKeys",
|
||||
label: "Foreign Keys",
|
||||
icon: "db-foreign-key",
|
||||
rows: (details?.foreignKeys ?? []).map((fk, i) => ({
|
||||
key: `fk-${i}`,
|
||||
name: list(fk.columns),
|
||||
detail: `→ ${fk.refTable} ${list(fk.refColumns)}`,
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "indexes",
|
||||
label: "Indexes",
|
||||
icon: "db-index",
|
||||
rows: (details?.indexes ?? []).map((ix) => ({
|
||||
key: `ix-${ix.name}`,
|
||||
name: ix.name,
|
||||
// `UNIQUE` is SQL, not UI text.
|
||||
detail: ix.unique ? ["UNIQUE", list(ix.columns)].join(" ") : list(ix.columns),
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "triggers",
|
||||
label: "Triggers",
|
||||
icon: "db-trigger",
|
||||
rows: (details?.triggers ?? []).map((t) => ({
|
||||
key: `tr-${t.name}`,
|
||||
name: t.name,
|
||||
detail: `${t.timing} ${t.events}`.toUpperCase(),
|
||||
})),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function ModifyTableForm({
|
||||
id,
|
||||
schema,
|
||||
@@ -572,7 +643,8 @@ function ModifyTableForm({
|
||||
focusColumn,
|
||||
addColumn,
|
||||
initial,
|
||||
}: ModifyProps & { initial: DbColumnInfo[] | null }) {
|
||||
details,
|
||||
}: ModifyProps & { initial: DbColumnInfo[] | null; details?: DbTableDetails }) {
|
||||
const driver = driverOf(id);
|
||||
const [name, setName] = useState(table ?? "table_name");
|
||||
const [columns, setColumns] = useState<ColumnDraft[]>(() => {
|
||||
@@ -587,11 +659,19 @@ function ModifyTableForm({
|
||||
return columns[Math.max(0, focus)]?.key ?? null;
|
||||
});
|
||||
const { busy, runAndClose } = useRunner();
|
||||
const comments = commentsSupported(driver);
|
||||
const [comment, setComment] = useState(details?.comment ?? "");
|
||||
|
||||
const statements = useMemo(() => {
|
||||
if (!table) return [createTableSql(driver, schema, name.trim() || "table_name", columns)];
|
||||
return alterTableSql(driver, schema, table, name, columns);
|
||||
}, [columns, driver, schema, table, name]);
|
||||
if (!table) {
|
||||
const created = name.trim() || "table_name";
|
||||
return [
|
||||
createTableSql(driver, schema, created, columns, comment),
|
||||
...createTableCommentSql(driver, schema, created, columns, comment),
|
||||
];
|
||||
}
|
||||
return alterTableSql(driver, schema, table, name, columns, { original: details?.comment ?? "", value: comment });
|
||||
}, [columns, driver, schema, table, name, comment, details?.comment]);
|
||||
|
||||
const current = columns.find((c) => c.key === selected) ?? null;
|
||||
const patch = (p: Partial<ColumnDraft>) =>
|
||||
@@ -611,6 +691,28 @@ function ModifyTableForm({
|
||||
}
|
||||
};
|
||||
const locked = !!current && !canAlterColumn(driver, current);
|
||||
// The list's filter (names and types) and its collapsed groups.
|
||||
const [filter, setFilter] = useState("");
|
||||
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(new Set());
|
||||
const query = filter.trim().toLowerCase();
|
||||
const matches = (...texts: string[]) => !query || texts.some((t) => t.toLowerCase().includes(query));
|
||||
const shownColumns = columns.filter((c) => matches(c.name, c.dataType));
|
||||
const groups = objectGroups(columns, details)
|
||||
.map((g) => ({ ...g, rows: g.rows.filter((r) => matches(r.name, r.detail)) }))
|
||||
.filter((g) => g.rows.length);
|
||||
const toggleGroup = (group: string) =>
|
||||
setCollapsed((c) => {
|
||||
const next = new Set(c);
|
||||
if (!next.delete(group)) next.add(group);
|
||||
return next;
|
||||
});
|
||||
const groupHeader = (group: string, label: string, count: number) => (
|
||||
<div className={styles.modifyGroup} onMouseDown={() => toggleGroup(group)}>
|
||||
<Icon name={collapsed.has(group) ? "chevron-right" : "chevron-down"} size={12} />
|
||||
<span>{tx(label)}</span>
|
||||
<span className={styles.treeType}>{count}</span>
|
||||
</div>
|
||||
);
|
||||
const showGrants = !!table && grantsSupported(driver);
|
||||
const [tab, setTab] = useState<"columns" | "grants">("columns");
|
||||
const title = table ? `Modify Table ${table}` : "Create Table";
|
||||
@@ -628,7 +730,14 @@ function ModifyTableForm({
|
||||
label: "OK",
|
||||
role: "default",
|
||||
disabled: busy || !statements.length || !name.trim(),
|
||||
onClick: () => void runAndClose(id, statements),
|
||||
onClick: () =>
|
||||
void runAndClose(id, statements).then((ok) => {
|
||||
if (!ok) return;
|
||||
// The tree and the next Modify Table show the table as it now is.
|
||||
const final = name.trim();
|
||||
void loadDetails(id, schema, final);
|
||||
if (final !== table) void loadTables(id, schema);
|
||||
}),
|
||||
},
|
||||
]}
|
||||
>
|
||||
@@ -646,6 +755,19 @@ function ModifyTableForm({
|
||||
/>
|
||||
<span className={styles.formHint}>{schema}</span>
|
||||
</div>
|
||||
{comments && (
|
||||
<div className={styles.formRow}>
|
||||
<label className={styles.formLabel} htmlFor="db-table-comment">
|
||||
<T>Comment:</T>
|
||||
</label>
|
||||
<Input
|
||||
id="db-table-comment"
|
||||
className={styles.fill}
|
||||
value={comment}
|
||||
onChange={(e) => setComment(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{showGrants && (
|
||||
<Tabs
|
||||
variant="compact"
|
||||
@@ -672,21 +794,52 @@ function ModifyTableForm({
|
||||
disabled={!current}
|
||||
onClick={remove}
|
||||
/>
|
||||
<SearchField
|
||||
variant="bare"
|
||||
className={styles.modifyFilter}
|
||||
value={filter}
|
||||
onChange={setFilter}
|
||||
placeholder="Filter by name or type"
|
||||
aria-label="Filter columns"
|
||||
/>
|
||||
</div>
|
||||
<div role="listbox" aria-label={tx("Columns")} className={styles.modifyList}>
|
||||
{columns.map((c) => (
|
||||
<div
|
||||
key={c.key}
|
||||
role="option"
|
||||
aria-selected={c.key === selected}
|
||||
tabIndex={-1}
|
||||
className={styles.modifyItem}
|
||||
data-dropped={c.dropped || undefined}
|
||||
onMouseDown={() => setSelected(c.key)}
|
||||
>
|
||||
<Icon name={c.primaryKey ? "db-column-key" : "db-column"} size={16} />
|
||||
<span className={styles.nodeLabel}>{c.name || "<unnamed>"}</span>
|
||||
<span className={styles.treeType}>{c.dataType}</span>
|
||||
<div role="group" aria-label={tx("Columns")}>
|
||||
{groupHeader("columns", "Columns", shownColumns.length)}
|
||||
{!collapsed.has("columns") &&
|
||||
shownColumns.map((c) => (
|
||||
<div
|
||||
key={c.key}
|
||||
role="option"
|
||||
aria-selected={c.key === selected}
|
||||
tabIndex={-1}
|
||||
className={styles.modifyItem}
|
||||
data-dropped={c.dropped || undefined}
|
||||
onMouseDown={() => setSelected(c.key)}
|
||||
>
|
||||
<Icon name={c.primaryKey ? "db-column-key" : "db-column"} size={16} />
|
||||
<span className={styles.nodeLabel}>{c.name || "<unnamed>"}</span>
|
||||
<span className={styles.treeType}>{c.dataType}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{groups.map((g) => (
|
||||
<div key={g.id} role="group" aria-label={tx(g.label)}>
|
||||
{groupHeader(g.id, g.label, g.rows.length)}
|
||||
{!collapsed.has(g.id) &&
|
||||
g.rows.map((r) => (
|
||||
<div
|
||||
key={r.key}
|
||||
role="option"
|
||||
aria-selected={false}
|
||||
aria-disabled
|
||||
className={styles.modifyItem}
|
||||
>
|
||||
<Icon name={g.icon} size={16} />
|
||||
<span className={styles.nodeLabel}>{r.name}</span>
|
||||
<span className={styles.treeType}>{r.detail}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@@ -746,6 +899,19 @@ function ModifyTableForm({
|
||||
disabled={current.dropped || locked}
|
||||
onChange={(e) => patch({ default: e.target.value })}
|
||||
/>
|
||||
{comments && (
|
||||
<>
|
||||
<label className={styles.formLabel} htmlFor="db-col-comment">
|
||||
<T>Column comment</T>
|
||||
</label>
|
||||
<Input
|
||||
id="db-col-comment"
|
||||
value={current.comment}
|
||||
disabled={current.dropped || locked}
|
||||
onChange={(e) => patch({ comment: e.target.value })}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{locked && (
|
||||
<>
|
||||
<span />
|
||||
|
||||
@@ -453,9 +453,9 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
|
||||
}
|
||||
};
|
||||
|
||||
const showExport = async (at: { x: number; y: number }) => {
|
||||
if (!r) return;
|
||||
// What is exported or copied is the whole values, not the starts the page carries.
|
||||
/** The result to export or copy: the whole values, not the starts the page carries. */
|
||||
const exportSource = async (): Promise<ExportData | null> => {
|
||||
if (!r) return null;
|
||||
if (hasCutCells(r)) {
|
||||
try {
|
||||
await loadPage(tab);
|
||||
@@ -466,17 +466,19 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
|
||||
body: e instanceof Error ? e.message : String(e),
|
||||
key: "db-whole-value",
|
||||
});
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
showContextMenu(
|
||||
at,
|
||||
exportMenu(
|
||||
{ columns, rows: rowsOf(r), driver, table: queryTable(text, { driver }) },
|
||||
queryTable(text, { driver }),
|
||||
extractor,
|
||||
),
|
||||
);
|
||||
return {
|
||||
columns: gridColumns.map((c) => ({ name: c.name, type: c.type, primaryKey: c.primaryKey })),
|
||||
rows: rowsOf(r),
|
||||
driver,
|
||||
table: queryTable(text, { driver }),
|
||||
};
|
||||
};
|
||||
const showExport = async (at: { x: number; y: number }) => {
|
||||
const data = await exportSource();
|
||||
if (data) showContextMenu(at, exportMenu(data, queryTable(text, { driver }), extractor));
|
||||
};
|
||||
|
||||
// Submit / Revert / Go to Column (⌘↩ / ⌥⌘Z / ⌘F12) reach the latest state through the handle, as in the table editor.
|
||||
@@ -635,6 +637,7 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
|
||||
panel={panel}
|
||||
onPanelChange={setPanel}
|
||||
copyFormat={copyFormatOf(extractor)}
|
||||
extractor={{ value: extractor, onChange: setExtractor, table: exportSource }}
|
||||
searchOpen={searchOpen}
|
||||
onSearchOpenChange={setSearchOpen}
|
||||
firstRowNumber={(tab.page ?? 0) * (tab.pageSize ?? 0) + 1}
|
||||
|
||||
@@ -440,6 +440,16 @@ export function TableEditor({ input }: { input: EditorInput }) {
|
||||
panel={panel}
|
||||
onPanelChange={setPanel}
|
||||
copyFormat={copyFormatOf(extractor)}
|
||||
extractor={{
|
||||
value: extractor,
|
||||
onChange: setExtractor,
|
||||
table: () => ({
|
||||
columns: gridColumns,
|
||||
rows: page.result.rows,
|
||||
table: ref.table,
|
||||
driver: sourceById(ref.id)?.driver ?? "sqlite",
|
||||
}),
|
||||
}}
|
||||
searchOpen={searchOpen}
|
||||
onSearchOpenChange={setSearchOpen}
|
||||
firstRowNumber={offset + 1}
|
||||
|
||||
@@ -195,3 +195,60 @@ it.each<ExportFormat>(["csv", "tsv", "sql", "markdown", "onerow"])("%s retains e
|
||||
const value = "9223372036854775807";
|
||||
expect(exportData(format, data(value))).toContain(value);
|
||||
});
|
||||
|
||||
describe("SQL statements of rows (#6143)", () => {
|
||||
const rows: ExportData = {
|
||||
columns: [
|
||||
{ name: "id", type: "INTEGER", primaryKey: true },
|
||||
{ name: "name", type: "TEXT" },
|
||||
{ name: "note", type: "TEXT" },
|
||||
],
|
||||
rows: [
|
||||
["2", "O'Hara", null],
|
||||
["1", "Ann", "x"],
|
||||
],
|
||||
table: "people",
|
||||
driver: "postgres",
|
||||
};
|
||||
|
||||
it("writes one statement per row, in order, matching rows by the primary key", () => {
|
||||
expect(exportData("sql", rows)).toBe(
|
||||
[
|
||||
`INSERT INTO people (id, name, note) VALUES (2, 'O''Hara', NULL);`,
|
||||
`INSERT INTO people (id, name, note) VALUES (1, 'Ann', 'x');`,
|
||||
].join("\n"),
|
||||
);
|
||||
expect(exportData("sqlUpdates", rows)).toBe(
|
||||
[
|
||||
`UPDATE people SET name = 'O''Hara', note = NULL WHERE id = 2;`,
|
||||
`UPDATE people SET name = 'Ann', note = 'x' WHERE id = 1;`,
|
||||
].join("\n"),
|
||||
);
|
||||
expect(exportData("sqlDeletes", rows)).toBe(
|
||||
[`DELETE FROM people WHERE id = 2;`, `DELETE FROM people WHERE id = 1;`].join("\n"),
|
||||
);
|
||||
expect(exportData("where", rows)).toBe(`WHERE (id = 2) OR (id = 1)`);
|
||||
expect(exportData("where", { ...rows, rows: rows.rows.slice(1) })).toBe(`WHERE id = 1`);
|
||||
});
|
||||
|
||||
it("matches on every column, saying so, when no key is known, and writes IS NULL for a null", () => {
|
||||
const keyless = { ...rows, columns: rows.columns.map((c) => ({ ...c, primaryKey: false })), rows: [rows.rows[0]!] };
|
||||
expect(exportData("sqlDeletes", keyless)).toBe(
|
||||
`-- No primary key is known: rows are matched on every column.\n` +
|
||||
`DELETE FROM people WHERE id = 2 AND name = 'O''Hara' AND note IS NULL;`,
|
||||
);
|
||||
// A null key value too.
|
||||
const nullKey = { ...rows, rows: [[null, "x", "y"]] };
|
||||
expect(exportData("sqlDeletes", nullKey)).toBe(`DELETE FROM people WHERE id IS NULL;`);
|
||||
});
|
||||
|
||||
it("escapes backslashes for drivers that read them, as SQL Inserts did", () => {
|
||||
const d: ExportData = {
|
||||
columns: [{ name: "p", type: "String" }],
|
||||
rows: [["a\\b'"]],
|
||||
table: "t",
|
||||
driver: "clickhouse",
|
||||
};
|
||||
expect(exportData("sql", d)).toBe(`INSERT INTO t (p) VALUES ('a\\\\b''');`);
|
||||
});
|
||||
});
|
||||
@@ -7,24 +7,40 @@
|
||||
import type { DbDriver } from "@/platform/ipc";
|
||||
import { jsonNumber } from "@/platform/losslessJson";
|
||||
import { isNumericColumn } from "./Grid";
|
||||
import { toCsv, toOneRow, toTsv, type Cell } from "./model";
|
||||
import { sqlLiteral, toCsv, toOneRow, toTsv, type Cell } from "./model";
|
||||
import { quoteIdent } from "./sql/complete";
|
||||
|
||||
export type ExportFormat = "csv" | "tsv" | "json" | "sql" | "markdown" | "onerow";
|
||||
export type ExportFormat =
|
||||
| "csv"
|
||||
| "tsv"
|
||||
| "json"
|
||||
| "sql"
|
||||
| "sqlUpdates"
|
||||
| "sqlDeletes"
|
||||
| "where"
|
||||
| "markdown"
|
||||
| "onerow";
|
||||
|
||||
/** The formats written as SQL (highlighted as SQL in the Export Data preview). */
|
||||
export const SQL_FORMATS: ReadonlySet<ExportFormat> = new Set(["sql", "sqlUpdates", "sqlDeletes", "where"]);
|
||||
|
||||
export const EXPORT_FORMATS: ReadonlyArray<{ id: ExportFormat; label: string; extension: string }> = [
|
||||
{ id: "csv", label: "CSV", extension: "csv" },
|
||||
{ id: "tsv", label: "TSV", extension: "tsv" },
|
||||
{ id: "json", label: "JSON", extension: "json" },
|
||||
{ id: "sql", label: "SQL Inserts", extension: "sql" },
|
||||
{ id: "sqlUpdates", label: "SQL Updates", extension: "sql" },
|
||||
{ id: "sqlDeletes", label: "SQL Deletes", extension: "sql" },
|
||||
{ id: "where", label: "Where Clause", extension: "sql" },
|
||||
{ id: "markdown", label: "Markdown", extension: "md" },
|
||||
{ id: "onerow", label: "One-Row", extension: "txt" },
|
||||
];
|
||||
|
||||
export interface ExportData {
|
||||
columns: ReadonlyArray<{ name: string; type: string }>;
|
||||
/** `primaryKey` columns identify a row in SQL Updates, SQL Deletes and Where Clause. */
|
||||
columns: ReadonlyArray<{ name: string; type: string; primaryKey?: boolean }>;
|
||||
rows: ReadonlyArray<readonly Cell[]>;
|
||||
/** Target of SQL inserts (the query's table, when it reads one). */
|
||||
/** Target of SQL statements (the query's table, when it reads one). */
|
||||
table: string;
|
||||
driver: DbDriver;
|
||||
}
|
||||
@@ -89,16 +105,11 @@ export function exportData(
|
||||
});
|
||||
return rows.length ? `[\n${rows.join(",\n")}\n]` : "[]";
|
||||
}
|
||||
case "sql": {
|
||||
const literal = (v: Cell, i: number) =>
|
||||
v === null
|
||||
? "NULL"
|
||||
: numeric[i] && Number.isFinite(Number(v))
|
||||
? v
|
||||
: `'${(d.driver === "clickhouse" || d.driver === "snowflake" ? v.replace(/\\/g, "\\\\") : v).replace(/'/g, "''")}'`;
|
||||
const head = `INSERT INTO ${quoteIdent(d.table, d.driver)} (${names.map((n) => quoteIdent(n, d.driver)).join(", ")}) VALUES`;
|
||||
return d.rows.map((r) => `${head} (${r.map(literal).join(", ")});`).join("\n");
|
||||
}
|
||||
case "sql":
|
||||
case "sqlUpdates":
|
||||
case "sqlDeletes":
|
||||
case "where":
|
||||
return sqlStatements(format, d, numeric);
|
||||
case "markdown": {
|
||||
const cell = (v: Cell) => (v ?? "").replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
|
||||
const t = laidOut(d, options);
|
||||
@@ -115,3 +126,41 @@ export function exportData(
|
||||
return toOneRow(d.rows, (c) => numeric[c]!);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* SQL Inserts, Updates, Deletes and the Where Clause of the rows, one statement per row in
|
||||
* their order. A row is identified by its primary key columns; with none known, by every
|
||||
* column, which the text says first.
|
||||
*/
|
||||
function sqlStatements(format: ExportFormat, d: ExportData, numeric: readonly boolean[]): string {
|
||||
const ident = (name: string) => quoteIdent(name, d.driver);
|
||||
const names = d.columns.map((c) => ident(c.name));
|
||||
const literal = (v: Cell | undefined, i: number) => sqlLiteral(v ?? null, numeric[i]!, d.driver);
|
||||
const table = ident(d.table);
|
||||
if (format === "sql")
|
||||
return d.rows
|
||||
.map((r) => `INSERT INTO ${table} (${names.join(", ")}) VALUES (${r.map(literal).join(", ")});`)
|
||||
.join("\n");
|
||||
const keys = d.columns.flatMap((c, i) => (c.primaryKey ? [i] : []));
|
||||
const match = keys.length ? keys : names.map((_, i) => i);
|
||||
const where = (r: readonly Cell[]) =>
|
||||
match.map((i) => (r[i] == null ? `${names[i]} IS NULL` : `${names[i]} = ${literal(r[i], i)}`)).join(" AND ");
|
||||
const note = keys.length || !d.rows.length ? "" : "-- No primary key is known: rows are matched on every column.\n";
|
||||
if (format === "where") {
|
||||
if (!d.rows.length) return "";
|
||||
const body = d.rows.length === 1 ? where(d.rows[0]!) : d.rows.map((r) => `(${where(r)})`).join(" OR ");
|
||||
return `${note}WHERE ${body}`;
|
||||
}
|
||||
if (format === "sqlDeletes") return note + d.rows.map((r) => `DELETE FROM ${table} WHERE ${where(r)};`).join("\n");
|
||||
// Updates set the other columns (every column when no key is known).
|
||||
const set = keys.length ? names.flatMap((_, i) => (keys.includes(i) ? [] : [i])) : match;
|
||||
return (
|
||||
note +
|
||||
d.rows
|
||||
.map(
|
||||
(r) =>
|
||||
`UPDATE ${table} SET ${set.map((i) => `${names[i]} = ${literal(r[i], i)}`).join(", ")} WHERE ${where(r)};`,
|
||||
)
|
||||
.join("\n")
|
||||
);
|
||||
}
|
||||
@@ -30,9 +30,18 @@ export function toTsv(header: readonly string[] | null, rows: ReadonlyArray<read
|
||||
* single-quoted with `'` doubled. `numeric(c)` decides quoting per column.
|
||||
*/
|
||||
export function toOneRow(rows: ReadonlyArray<readonly Cell[]>, numeric: (col: number) => boolean): string {
|
||||
const literal = (v: Cell, c: number) =>
|
||||
v === null ? "NULL" : numeric(c) && Number.isFinite(Number(v)) ? v : `'${v.replace(/'/g, "''")}'`;
|
||||
return rows.flatMap((r) => r.map(literal)).join(", ");
|
||||
return rows.flatMap((r) => r.map((v, c) => sqlLiteral(v, numeric(c)))).join(", ");
|
||||
}
|
||||
|
||||
/**
|
||||
* A value as an SQL literal: NULL, a number unquoted in a numeric column, else single-quoted
|
||||
* with `'` doubled (and `\\` doubled for drivers that read backslash escapes in strings).
|
||||
*/
|
||||
export function sqlLiteral(v: Cell, numeric: boolean, driver?: DbDriver): string {
|
||||
if (v === null) return "NULL";
|
||||
if (numeric && Number.isFinite(Number(v))) return v;
|
||||
const escaped = driver === "clickhouse" || driver === "snowflake" ? v.replace(/\\/g, "\\\\") : v;
|
||||
return `'${escaped.replace(/'/g, "''")}'`;
|
||||
}
|
||||
|
||||
/** RFC 4180 CSV; NULL is an empty field. */
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { ObjectDialogs } from "./ObjectDialogs";
|
||||
import { detailsKey, openDialog, useDatabase } from "./store";
|
||||
|
||||
const column = (name: string, dataType: string, primaryKey = false) => ({
|
||||
name,
|
||||
dataType,
|
||||
nullable: !primaryKey,
|
||||
default: null,
|
||||
primaryKey,
|
||||
});
|
||||
|
||||
function open() {
|
||||
useDatabase.setState({
|
||||
details: {
|
||||
[detailsKey("db", "main", "orders")]: {
|
||||
status: "ok",
|
||||
value: {
|
||||
columns: [column("id", "integer", true), column("customer_id", "integer"), column("note", "text")],
|
||||
indexes: [{ name: "orders_customer", unique: false, columns: ["customer_id"] }],
|
||||
foreignKeys: [
|
||||
{
|
||||
schema: "main",
|
||||
table: "orders",
|
||||
columns: ["customer_id"],
|
||||
refSchema: "main",
|
||||
refTable: "customers",
|
||||
refColumns: ["id"],
|
||||
},
|
||||
],
|
||||
triggers: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
} as never);
|
||||
openDialog({ kind: "modifyTable", id: "db", schema: "main", table: "orders" });
|
||||
render(<ObjectDialogs />);
|
||||
}
|
||||
|
||||
const rows = (group: string) =>
|
||||
within(screen.getByRole("group", { name: group }))
|
||||
.queryAllByRole("option")
|
||||
.map((o) => o.textContent);
|
||||
|
||||
afterEach(() => useDatabase.setState({ dialog: null, details: {}, sources: [] } as never));
|
||||
|
||||
describe("Modify Table's list (DataGrip)", () => {
|
||||
it("groups the columns, keys, foreign keys and indexes, and filters them by name or type", () => {
|
||||
open();
|
||||
expect(rows("Columns")).toEqual(["idinteger", "customer_idinteger", "notetext"]);
|
||||
expect(rows("Keys")).toEqual(["PRIMARY KEY(id)"]);
|
||||
expect(rows("Foreign Keys")).toEqual(["(customer_id)→ customers (id)"]);
|
||||
expect(rows("Indexes")).toEqual(["orders_customer(customer_id)"]);
|
||||
// No triggers: no group.
|
||||
expect(screen.queryByRole("group", { name: "Triggers" })).toBeNull();
|
||||
|
||||
// A group collapses from its header.
|
||||
fireEvent.mouseDown(within(screen.getByRole("group", { name: "Indexes" })).getByText("Indexes"));
|
||||
expect(rows("Indexes")).toEqual([]);
|
||||
|
||||
fireEvent.change(screen.getByRole("textbox", { name: "Filter columns" }), { target: { value: "TEXT" } });
|
||||
expect(rows("Columns")).toEqual(["notetext"]);
|
||||
expect(screen.queryByRole("group", { name: "Foreign Keys" })).toBeNull();
|
||||
|
||||
fireEvent.change(screen.getByRole("textbox", { name: "Filter columns" }), { target: { value: "customer" } });
|
||||
expect(rows("Columns")).toEqual(["customer_idinteger"]);
|
||||
expect(rows("Foreign Keys")).toEqual(["(customer_id)→ customers (id)"]);
|
||||
});
|
||||
|
||||
it("keeps Keys on the primary key as edited in Create Table", () => {
|
||||
openDialog({ kind: "modifyTable", id: "db", schema: "main", table: null });
|
||||
render(<ObjectDialogs />);
|
||||
expect(rows("Keys")).toEqual(["PRIMARY KEY(id)"]);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Add Column" }));
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: "Primary key" }));
|
||||
expect(rows("Keys")).toEqual(["PRIMARY KEY(id, column_2)"]);
|
||||
});
|
||||
|
||||
it("reads and edits the table's and the columns' comments where the engine keeps them", () => {
|
||||
useDatabase.setState({
|
||||
sources: [{ id: "pg", name: "pg", driver: "postgres" }],
|
||||
details: {
|
||||
[detailsKey("pg", "public", "orders")]: {
|
||||
status: "ok",
|
||||
value: {
|
||||
comment: "Customer orders",
|
||||
columns: [column("id", "integer", true), { ...column("note", "text"), comment: "Free text" }],
|
||||
indexes: [],
|
||||
foreignKeys: [],
|
||||
triggers: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
} as never);
|
||||
openDialog({ kind: "modifyTable", id: "pg", schema: "public", table: "orders", focusColumn: "note" });
|
||||
render(<ObjectDialogs />);
|
||||
expect(screen.getByLabelText("Comment:")).toHaveProperty("value", "Customer orders");
|
||||
expect(screen.getByLabelText("Column comment")).toHaveProperty("value", "Free text");
|
||||
fireEvent.change(screen.getByLabelText("Column comment"), { target: { value: "" } });
|
||||
fireEvent.change(screen.getByLabelText("Comment:"), { target: { value: "Orders" } });
|
||||
const preview = document.body.textContent ?? "";
|
||||
expect(preview).toContain("comment on table public.orders is 'Orders';");
|
||||
expect(preview).toContain("comment on column public.orders.note is null;");
|
||||
});
|
||||
|
||||
it("has no comment fields on an engine without comments", () => {
|
||||
open();
|
||||
expect(screen.queryByLabelText("Comment:")).toBeNull();
|
||||
expect(screen.queryByLabelText("Column comment")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
canModifyTable,
|
||||
createDatabaseSql,
|
||||
createSchemaSql,
|
||||
commentsSupported,
|
||||
createTableCommentSql,
|
||||
createTableSql,
|
||||
draftOf,
|
||||
dropDatabaseSql,
|
||||
@@ -188,6 +190,7 @@ describe("database object SQL", () => {
|
||||
notNull: false,
|
||||
default: "0",
|
||||
primaryKey: false,
|
||||
comment: "",
|
||||
dropped: false,
|
||||
});
|
||||
expect(alterTableSql("sqlite", "main", "users", "people", d)).toEqual([
|
||||
@@ -209,6 +212,71 @@ describe("database object SQL", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("table and column comments", () => {
|
||||
const commented = [col("id", "INTEGER", { primaryKey: true }), col("note", "TEXT", { comment: "Free text" })];
|
||||
|
||||
it("sets, changes and clears comments per engine", () => {
|
||||
const p = commented.map(draftOf);
|
||||
p[0] = { ...p[0]!, comment: "Order's id" };
|
||||
p[1] = { ...p[1]!, comment: "" };
|
||||
const table = { original: "", value: "Orders" };
|
||||
expect(alterTableSql("postgres", "public", "t", "t", p, table)).toEqual([
|
||||
"comment on table public.t is 'Orders';",
|
||||
"comment on column public.t.id is 'Order''s id';",
|
||||
"comment on column public.t.note is null;",
|
||||
]);
|
||||
expect(alterTableSql("oracle", "HR", "T", "T", p, { original: "Old", value: "" })).toEqual([
|
||||
"comment on table HR.T is '';",
|
||||
"comment on column HR.T.\"id\" is 'Order''s id';",
|
||||
"comment on column HR.T.\"note\" is '';",
|
||||
]);
|
||||
expect(alterTableSql("snowflake", "HR", "T", "T", p, { original: "Old", value: "" })).toEqual([
|
||||
"alter table HR.T unset comment;",
|
||||
"comment on column HR.T.\"id\" is 'Order''s id';",
|
||||
'alter table HR.T alter column "note" unset comment;',
|
||||
]);
|
||||
// MySQL keeps a column's comment in its definition.
|
||||
expect(alterTableSql("mysql", "app", "t", "t", p, { original: "", value: "a\\b" })).toEqual([
|
||||
"alter table app.t change column id id INTEGER comment 'Order''s id';",
|
||||
"alter table app.t change column note note TEXT;",
|
||||
"alter table app.t comment = 'a\\\\b';",
|
||||
]);
|
||||
expect(alterTableSql("sqlite", "main", "t", "t", p, table)).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps an unchanged comment, and comments a renamed column by its new name", () => {
|
||||
const p = commented.map(draftOf);
|
||||
expect(alterTableSql("postgres", "public", "t", "t", p, { original: "Orders", value: "Orders" })).toEqual([]);
|
||||
// A MySQL change of type keeps the column's comment.
|
||||
p[1] = { ...p[1]!, dataType: "varchar(40)" };
|
||||
expect(alterTableSql("mysql", "app", "t", "t", p)).toEqual([
|
||||
"alter table app.t change column note note varchar(40) comment 'Free text';",
|
||||
]);
|
||||
p[1] = { ...commented.map(draftOf)[1]!, name: "body", comment: "Body" };
|
||||
expect(alterTableSql("postgres", "public", "t", "renamed", p)).toEqual([
|
||||
"alter table public.t rename column note to body;",
|
||||
"comment on column public.t.body is 'Body';",
|
||||
"alter table public.t rename to renamed;",
|
||||
]);
|
||||
});
|
||||
|
||||
it("comments a new table", () => {
|
||||
const d = commented.map((c) => ({ ...draftOf(c, 0), original: null }));
|
||||
expect(createTableSql("mysql", "app", "t", d, "Orders")).toBe(
|
||||
"create table app.t\n(\n id INTEGER,\n note TEXT comment 'Free text',\n primary key (id)\n)\ncomment = 'Orders';\n",
|
||||
);
|
||||
expect(createTableCommentSql("mysql", "app", "t", d, "Orders")).toEqual([]);
|
||||
expect(createTableCommentSql("postgres", "public", "t", d, "Orders")).toEqual([
|
||||
"comment on table public.t is 'Orders';",
|
||||
"comment on column public.t.note is 'Free text';",
|
||||
]);
|
||||
expect(createTableCommentSql("postgres", "public", "t", d, "")).toEqual([
|
||||
"comment on column public.t.note is 'Free text';",
|
||||
]);
|
||||
expect(commentsSupported("sqlite")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("oracle object SQL", () => {
|
||||
const emp = [col("ID", "NUMBER", { primaryKey: true, nullable: false }), col("NAME", "VARCHAR2(40)")];
|
||||
const d = emp.map(draftOf);
|
||||
@@ -248,6 +316,7 @@ describe("oracle object SQL", () => {
|
||||
notNull: false,
|
||||
default: "SYSDATE",
|
||||
primaryKey: false,
|
||||
comment: "",
|
||||
dropped: false,
|
||||
} satisfies ColumnDraft);
|
||||
expect(alterTableSql("oracle", "HR", "EMPLOYEES", "EMPLOYEES", p)).toEqual([
|
||||
@@ -344,6 +413,7 @@ describe("snowflake object SQL", () => {
|
||||
notNull: false,
|
||||
default: "CURRENT_DATE",
|
||||
primaryKey: false,
|
||||
comment: "",
|
||||
dropped: false,
|
||||
} satisfies ColumnDraft);
|
||||
expect(alterTableSql("snowflake", "HR", "EMP", "STAFF", p)).toEqual([
|
||||
|
||||
@@ -305,6 +305,8 @@ export interface ColumnDraft {
|
||||
/** SQL expression; empty for none. */
|
||||
default: string;
|
||||
primaryKey: boolean;
|
||||
/** Empty for none. */
|
||||
comment: string;
|
||||
dropped: boolean;
|
||||
}
|
||||
|
||||
@@ -317,6 +319,7 @@ export function draftOf(c: DbColumnInfo, key: number): ColumnDraft {
|
||||
notNull: !c.nullable,
|
||||
default: c.default ?? "",
|
||||
primaryKey: c.primaryKey,
|
||||
comment: c.comment ?? "",
|
||||
dropped: false,
|
||||
};
|
||||
}
|
||||
@@ -335,21 +338,95 @@ function columnDefinition(driver: DbDriver, c: ColumnDraft): string {
|
||||
let s = `${ident(driver, c.name)} ${c.dataType.trim() || fallback}`;
|
||||
if (c.default.trim()) s += ` default ${c.default.trim()}`;
|
||||
if (c.notNull && driver !== "clickhouse") s += " not null";
|
||||
// MySQL keeps a column's comment in its definition: `change column` without it drops the comment.
|
||||
if (driver === "mysql" && c.comment) s += ` comment ${commentLiteral(driver, c.comment)}`;
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Engines whose table and column comments the Modify Table dialog reads and edits. */
|
||||
export function commentsSupported(driver: DbDriver): boolean {
|
||||
return driver === "postgres" || driver === "mysql" || driver === "oracle" || driver === "snowflake";
|
||||
}
|
||||
|
||||
/** A comment as a string literal (MySQL and Snowflake read backslash escapes). */
|
||||
function commentLiteral(driver: DbDriver, text: string): string {
|
||||
const escaped = driver === "mysql" || driver === "snowflake" ? text.replace(/\\/g, "\\\\") : text;
|
||||
return `'${escaped.replace(/'/g, "''")}'`;
|
||||
}
|
||||
|
||||
/** A table comment as the dialog started (`original`) and as edited. */
|
||||
export interface CommentEdit {
|
||||
original: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The statements setting the table's comment and its columns' (`comment on …` where the
|
||||
* engine has it; MySQL's column comments are part of the definition, see `columnDefinition`).
|
||||
* Columns are named as they end up; the table as it is (a rename comes after).
|
||||
*/
|
||||
function commentSql(
|
||||
driver: DbDriver,
|
||||
schema: string,
|
||||
table: string,
|
||||
columns: readonly ColumnDraft[],
|
||||
comment: CommentEdit | undefined,
|
||||
): string[] {
|
||||
if (!commentsSupported(driver)) return [];
|
||||
const q = qualifiedName(driver, schema, table);
|
||||
const out: string[] = [];
|
||||
if (comment && comment.value !== comment.original) {
|
||||
const v = comment.value;
|
||||
if (driver === "mysql") out.push(`alter table ${q} comment = ${commentLiteral(driver, v)};`);
|
||||
else if (!v && driver === "snowflake") out.push(`alter table ${q} unset comment;`);
|
||||
else out.push(`comment on table ${q} is ${v || driver !== "postgres" ? commentLiteral(driver, v) : "null"};`);
|
||||
}
|
||||
if (driver === "mysql") return out;
|
||||
for (const c of columns) {
|
||||
const name = c.name.trim() || c.original?.name;
|
||||
if (c.dropped || !name || c.comment === (c.original?.comment ?? "")) continue;
|
||||
const col = ident(driver, name);
|
||||
if (!c.comment && driver === "snowflake") out.push(`alter table ${q} alter column ${col} unset comment;`);
|
||||
else
|
||||
out.push(
|
||||
`comment on column ${q}.${col} is ${c.comment || driver !== "postgres" ? commentLiteral(driver, c.comment) : "null"};`,
|
||||
);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** `create table` for New › Table. */
|
||||
export function createTableSql(
|
||||
driver: DbDriver,
|
||||
schema: string,
|
||||
name: string,
|
||||
columns: readonly ColumnDraft[],
|
||||
comment = "",
|
||||
): string {
|
||||
const live = columns.filter((c) => !c.dropped && c.name.trim());
|
||||
const keys = live.filter((c) => c.primaryKey).map((c) => ident(driver, c.name));
|
||||
const items = live.map((c) => ` ${columnDefinition(driver, c)}`);
|
||||
if (keys.length && driver !== "clickhouse") items.push(` primary key (${keys.join(", ")})`);
|
||||
return `create table ${qualifiedName(driver, schema, name)}\n(\n${items.join(",\n")}\n)${driver === "clickhouse" ? "\nengine = MergeTree\norder by tuple()" : ""};\n`;
|
||||
const options =
|
||||
driver === "clickhouse"
|
||||
? "\nengine = MergeTree\norder by tuple()"
|
||||
: driver === "mysql" && comment
|
||||
? `\ncomment = ${commentLiteral(driver, comment)}`
|
||||
: "";
|
||||
return `create table ${qualifiedName(driver, schema, name)}\n(\n${items.join(",\n")}\n)${options};\n`;
|
||||
}
|
||||
|
||||
/** The `comment on` statements following New › Table's `create table` (MySQL takes them inline). */
|
||||
export function createTableCommentSql(
|
||||
driver: DbDriver,
|
||||
schema: string,
|
||||
name: string,
|
||||
columns: readonly ColumnDraft[],
|
||||
comment: string,
|
||||
): string[] {
|
||||
if (driver === "mysql") return [];
|
||||
const live = columns.filter((c) => !c.dropped && c.name.trim());
|
||||
return commentSql(driver, schema, name, live, { original: "", value: comment });
|
||||
}
|
||||
|
||||
/** Whether `alterTableSql` can express changing column `c` (SQLite only renames, adds and drops). */
|
||||
@@ -360,7 +437,7 @@ export function canAlterColumn(driver: DbDriver, c: ColumnDraft): boolean {
|
||||
/**
|
||||
* The statements turning the table `table` into `name` with `columns`
|
||||
* (Modify Table): renames, added / dropped columns, and — PostgreSQL / MySQL /
|
||||
* Oracle / Snowflake — type, nullability and default changes.
|
||||
* Oracle / Snowflake — type, nullability, default and comment changes, and the table's comment.
|
||||
*/
|
||||
export function alterTableSql(
|
||||
driver: DbDriver,
|
||||
@@ -368,6 +445,7 @@ export function alterTableSql(
|
||||
table: string,
|
||||
name: string,
|
||||
columns: readonly ColumnDraft[],
|
||||
comment?: CommentEdit,
|
||||
): string[] {
|
||||
if (!canModifyTable(driver)) return [];
|
||||
const out: string[] = [];
|
||||
@@ -391,7 +469,10 @@ export function alterTableSql(
|
||||
}
|
||||
const renamed = c.name.trim() && c.name !== o.name;
|
||||
const changed =
|
||||
c.dataType.trim() !== o.dataType || c.notNull !== !o.nullable || c.default.trim() !== (o.default ?? "").trim();
|
||||
c.dataType.trim() !== o.dataType ||
|
||||
c.notNull !== !o.nullable ||
|
||||
c.default.trim() !== (o.default ?? "").trim() ||
|
||||
(driver === "mysql" && c.comment !== (o.comment ?? ""));
|
||||
if (driver === "mysql" && (renamed || changed)) {
|
||||
out.push(`alter table ${q()} change column ${ident(driver, o.name)} ${columnDefinition(driver, c)};`);
|
||||
continue;
|
||||
@@ -439,6 +520,7 @@ export function alterTableSql(
|
||||
`alter table ${q()} alter column ${col} ${c.default.trim() ? `set default ${c.default.trim()}` : "drop default"};`,
|
||||
);
|
||||
}
|
||||
out.push(...commentSql(driver, schema, table, columns, comment));
|
||||
// Renamed last: the column statements above name the table as it was.
|
||||
if (name.trim() && name.trim() !== table)
|
||||
out.push(renameSql(driver, { kind: "table", schema, name: table }, name.trim()));
|
||||
|
||||
@@ -188,6 +188,15 @@ it("hands the window's whole list to the backend before startup, even after a fa
|
||||
);
|
||||
});
|
||||
|
||||
it("leaves the backend alone while no project is open", async () => {
|
||||
loadBreakpoints(null);
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
expect(ipc.debugReplaceBreakpoints).not.toHaveBeenCalled();
|
||||
loadBreakpoints("/p");
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(ipc.debugReplaceBreakpoints).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("flushes persisted breakpoints immediately after project loading", async () => {
|
||||
ipc.debugSetBreakpoints.mockResolvedValue({ status: "ok", data: [] });
|
||||
localStorage.setItem(
|
||||
|
||||
@@ -138,8 +138,10 @@ async function drainBreakpoints() {
|
||||
|
||||
/** Makes this window's whole list the backend's: files it no longer lists are cleared there. */
|
||||
async function replaceBreakpoints() {
|
||||
if (!isTauri() || useProject.getState().project?.trusted === false) return;
|
||||
const { byFile, muted } = useBreakpoints.getState();
|
||||
// Without a project (before one opens, after it closes) the backend holds no breakpoints for
|
||||
// this window and has none to clear.
|
||||
const { root, byFile, muted } = useBreakpoints.getState();
|
||||
if (!isTauri() || root === null || useProject.getState().project?.trusted === false) return;
|
||||
const files = Object.fromEntries(Object.entries(byFile).map(([path, list]) => [path, toBackend(list, muted, path)]));
|
||||
await call(commands.debugReplaceBreakpoints(files));
|
||||
}
|
||||
|
||||
@@ -605,7 +605,7 @@ export function ProjectView() {
|
||||
const rootNode = m.roots[0];
|
||||
if (!rootNode) return;
|
||||
setSelection(new Set([rootNode.key]), rootNode.key);
|
||||
showContextMenu(e, contextMenuItems([rootNode]));
|
||||
showContextMenu(e, contextMenuItems([rootNode], { x: e.clientX, y: e.clientY }));
|
||||
return;
|
||||
}
|
||||
const nodes = [...sel].map((k) => m.byKey.get(k)).filter((n): n is ProjectNode => !!n && !n.placeholder);
|
||||
@@ -614,7 +614,7 @@ export function ProjectView() {
|
||||
// Contributed groups may read the file first (bounded wait).
|
||||
const at = { x: e.clientX, y: e.clientY };
|
||||
void prepareMenuGroups("projectView", menuGroupContext(target)).then(() =>
|
||||
showContextMenu(at, contextMenuItems(target)),
|
||||
showContextMenu(at, contextMenuItems(target, at)),
|
||||
);
|
||||
}, []);
|
||||
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
/** Actions of the project view (Find Action, keymap, other features via `executeAction`). */
|
||||
import { activeEditor } from "@/editor/api";
|
||||
import { getAction, registerActions, type Action } from "@/platform/actions";
|
||||
import { executeAction, getAction, registerActions, type Action } from "@/platform/actions";
|
||||
import { getContext } from "@/platform/context";
|
||||
import { FILE_COLOR_NAMES } from "@/platform/fileColors";
|
||||
import { canRevealInFileManager, revealInFileManagerLabel } from "@/platform/fileManager";
|
||||
import { dirname, useProject } from "@/platform/project";
|
||||
import { showContextMenu, type MenuItem } from "@/ui";
|
||||
import { maybeEditorService, menuGroupItems, toolWindowService } from "@/workbench/contributions";
|
||||
import { OPTION_LABELS, SORT_LABELS, flipToggle, isToggled } from "./HeaderActions";
|
||||
import { compareTarget, newMenuItems, revealLabel } from "./contextMenu";
|
||||
import { LABELS, setFileColor } from "./fileColor";
|
||||
import { openNewPopup } from "./newPopupModel";
|
||||
import type { ProjectNode } from "./model";
|
||||
import {
|
||||
@@ -587,5 +589,28 @@ export function registerProjectActions(): () => void {
|
||||
...toggles,
|
||||
...modes,
|
||||
...sorts,
|
||||
// File Color of a single path (the project view's submenu; the editor tab menu references
|
||||
// these ids with a path argument instead of importing this feature).
|
||||
...FILE_COLOR_NAMES.map((name): Action => ({
|
||||
id: `file.${name}`,
|
||||
title: LABELS[name],
|
||||
category: "Project View",
|
||||
hidden: true,
|
||||
run: ({ arg }) => void setFileColor(String(arg), false, name),
|
||||
})),
|
||||
{
|
||||
id: "file.clearColor",
|
||||
title: "Clear File Color",
|
||||
category: "Project View",
|
||||
hidden: true,
|
||||
run: ({ arg }) => void setFileColor(String(arg), false, null),
|
||||
},
|
||||
{
|
||||
id: "file.editColors",
|
||||
title: "Edit File Colors…",
|
||||
category: "Project View",
|
||||
hidden: true,
|
||||
run: () => void executeAction("file.settings", "fileColors"),
|
||||
},
|
||||
]);
|
||||
}
|
||||
@@ -8,6 +8,11 @@ import { registerMenuGroup } from "@/workbench/contributions";
|
||||
import { contextMenuItems, keyLabel, revealLabel } from "./contextMenu";
|
||||
import type { ProjectNode } from "./model";
|
||||
import { useProjectTree } from "./store";
|
||||
import { closePopup, useLspPopup } from "@/editor/lsp/popupStore";
|
||||
import { _provideCopyPathChooser } from "@/editor/api";
|
||||
import { openCopyPathChooser } from "@/editor/core/copyPathChooser";
|
||||
|
||||
_provideCopyPathChooser(openCopyPathChooser);
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/platform/ipc")>()),
|
||||
@@ -79,6 +84,7 @@ beforeEach(() => {
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closePopup();
|
||||
disposers.forEach((d) => d());
|
||||
useProject.setState({ project: null, settings: null });
|
||||
useProjectTree.setState({ root: null });
|
||||
@@ -147,38 +153,56 @@ describe("project view context menu", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("lists contributed links in Copy Path/Reference…", () => {
|
||||
/** Runs Copy Path/Reference… and returns the chooser's rows as `label: preview`. */
|
||||
const chooser = (items: MenuItem[]) => {
|
||||
const item = resolveMenuItems(items).find((r) => r.label === "Copy Path/Reference…");
|
||||
expect(item?.submenu).toBeUndefined();
|
||||
item!.run!();
|
||||
const popup = useLspPopup.getState().popup;
|
||||
return popup?.kind === "list" ? popup.items.map((i) => `${i.label}: ${i.preview}`) : undefined;
|
||||
};
|
||||
|
||||
it("previews each way Copy Path/Reference… copies the selection, contributed links included", () => {
|
||||
disposers.push(
|
||||
registerMenuGroup({
|
||||
id: "test.link",
|
||||
menus: ["copyPath"],
|
||||
items: (_menu, ctx) => [
|
||||
{ label: `Link ${ctx.paths.join()} ${ctx.dirs?.join()}`, verbatim: true, run: () => undefined },
|
||||
{
|
||||
id: "test.link",
|
||||
label: "Link",
|
||||
verbatim: true,
|
||||
preview: `${ctx.paths.join()} ${ctx.dirs?.join()}`,
|
||||
run: () => undefined,
|
||||
},
|
||||
// Without a preview a contribution has nothing to show in the chooser.
|
||||
{ id: "test.bare", label: "Bare", run: () => undefined },
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(sub(contextMenuItems([node("/p/src", true)]), "Copy Path/Reference…")).toEqual([
|
||||
"Absolute Path",
|
||||
"File Name",
|
||||
"Path From Content Root",
|
||||
"-",
|
||||
"Link /p/src true",
|
||||
expect(chooser(contextMenuItems([node("/p/src", true), node("/p/src/a.ts")], { x: 10, y: 20 }))).toEqual([
|
||||
"Absolute Path: /p/src\n/p/src/a.ts",
|
||||
"File Name: src\na.ts",
|
||||
"Path From Content Root: src\nsrc/a.ts",
|
||||
"Link: /p/src,/p/src/a.ts true,false",
|
||||
]);
|
||||
expect(useLspPopup.getState().popup).toMatchObject({ layout: "copyPath", anchor: { x: 10, y: 20 } });
|
||||
});
|
||||
|
||||
it("lists contributed links in Copy Path/Reference… of library files too", () => {
|
||||
it("offers no content root paths for library files in Copy Path/Reference…", () => {
|
||||
disposers.push(
|
||||
registerMenuGroup({
|
||||
id: "test.link",
|
||||
menus: ["copyPath"],
|
||||
items: (_menu, ctx) => [{ label: `Link ${ctx.paths.join()}`, verbatim: true, run: () => undefined }],
|
||||
items: (_menu, ctx) => [
|
||||
{ id: "test.link", label: "Link", verbatim: true, preview: ctx.paths.join(), run: () => undefined },
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(sub(contextMenuItems([{ ...node("/root/.m2/lib.jar"), readOnly: true }]), "Copy Path/Reference…")).toEqual([
|
||||
"Absolute Path",
|
||||
"File Name",
|
||||
"-",
|
||||
"Link /root/.m2/lib.jar",
|
||||
expect(chooser(contextMenuItems([{ ...node("/root/.m2/lib.jar"), readOnly: true }]))).toEqual([
|
||||
"Absolute Path: /root/.m2/lib.jar",
|
||||
"File Name: lib.jar",
|
||||
"Link: /root/.m2/lib.jar",
|
||||
]);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
/** Context menu and "New" popup of the project view. */
|
||||
import { openCopyPathChooser } from "@/editor/api";
|
||||
import { executeAction, getAction } from "@/platform/actions";
|
||||
import type { PathKind } from "@/platform/copyPath";
|
||||
import { getContext } from "@/platform/context";
|
||||
import { canOpenWithSystemApp, canRevealInFileManager, fileManagerName } from "@/platform/fileManager";
|
||||
import { formatBinding, hostBinding, isMacHost, shortcutLabel } from "@/platform/keymap";
|
||||
@@ -18,6 +20,7 @@ import {
|
||||
canPaste,
|
||||
copyPaths,
|
||||
copySelection,
|
||||
pathsFor,
|
||||
delegate,
|
||||
deleteSelection,
|
||||
findFileUsages,
|
||||
@@ -151,6 +154,8 @@ function delegated(
|
||||
}
|
||||
|
||||
type Entry = MenuItem | null | false | undefined;
|
||||
/** Where a menu opens; popups its items open appear there. */
|
||||
type MenuPoint = { x: number; y: number } | "center";
|
||||
|
||||
/** A submenu of the present entries, or nothing when none is left (never an empty submenu). */
|
||||
function submenu(id: string, label: string, entries: Entry[], icon?: string): MenuItem | null {
|
||||
@@ -160,8 +165,13 @@ function submenu(id: string, label: string, entries: Entry[], icon?: string): Me
|
||||
}
|
||||
|
||||
/** Project view actions available for the selected files and directories. */
|
||||
export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
|
||||
if (nodes.some((n) => n.readOnly)) return libraryMenuItems(nodes.filter((n) => !n.group));
|
||||
/** `at`: where the menu opens, for the popups its items open (Copy Path/Reference…). */
|
||||
export function contextMenuItems(nodes: ProjectNode[], at: MenuPoint = "center"): MenuItem[] {
|
||||
if (nodes.some((n) => n.readOnly))
|
||||
return libraryMenuItems(
|
||||
nodes.filter((n) => !n.group),
|
||||
at,
|
||||
);
|
||||
const lead = nodes[0] ?? null;
|
||||
const single = nodes.length === 1 ? lead : null;
|
||||
const nonRoot = nodes.filter((n) => !n.root);
|
||||
@@ -217,22 +227,7 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
|
||||
disabled: !nonRoot.length,
|
||||
run: () => copySelection(false),
|
||||
},
|
||||
{
|
||||
id: "copyPath",
|
||||
label: "Copy Path/Reference…",
|
||||
submenu: [
|
||||
{
|
||||
id: "abs",
|
||||
label: "Absolute Path",
|
||||
shortcut: keyLabel("project.copyAbsolutePath"),
|
||||
run: () => void copyPaths("absolute", nodes),
|
||||
},
|
||||
{ id: "name", label: "File Name", run: () => void copyPaths("name", nodes) },
|
||||
{ id: "rel", label: "Path From Content Root", run: () => void copyPaths("relative", nodes) },
|
||||
{ kind: "separator" },
|
||||
...menuGroupItems("copyPath", menuGroupContext(nodes)),
|
||||
],
|
||||
},
|
||||
copyPathItem(nodes, at, false),
|
||||
{
|
||||
id: "paste",
|
||||
label: "Paste",
|
||||
@@ -464,27 +459,13 @@ function openInRightSplitItem(files: ProjectNode[]): MenuItem {
|
||||
}
|
||||
|
||||
/** Library sources (External Libraries) are read-only: copy, find and reveal only. */
|
||||
function libraryMenuItems(nodes: ProjectNode[]): MenuItem[] {
|
||||
function libraryMenuItems(nodes: ProjectNode[], at: MenuPoint): MenuItem[] {
|
||||
if (!nodes.length) return [];
|
||||
const single = nodes.length === 1 ? nodes[0]! : null;
|
||||
const folder = single?.dir ? single.path : null;
|
||||
const items: Entry[] = [
|
||||
{ id: "copy", label: "Copy", icon: "copy", shortcut: keyLabel("project.copy"), run: () => copySelection(false) },
|
||||
{
|
||||
id: "copyPath",
|
||||
label: "Copy Path/Reference…",
|
||||
submenu: [
|
||||
{
|
||||
id: "abs",
|
||||
label: "Absolute Path",
|
||||
shortcut: keyLabel("project.copyAbsolutePath"),
|
||||
run: () => void copyPaths("absolute", nodes),
|
||||
},
|
||||
{ id: "name", label: "File Name", run: () => void copyPaths("name", nodes) },
|
||||
{ kind: "separator" },
|
||||
...menuGroupItems("copyPath", menuGroupContext(nodes)),
|
||||
],
|
||||
},
|
||||
copyPathItem(nodes, at, true),
|
||||
{ kind: "separator" },
|
||||
!!folder && delegated("find.inPath", { directory: folder }, "Find in Files…", { icon: "search" }),
|
||||
!!folder && { kind: "separator" },
|
||||
@@ -518,6 +499,43 @@ export function revealLabel() {
|
||||
return fileManagerName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy Path/Reference…: a chooser previewing what each way copies for the selection (several
|
||||
* paths one per line), contributed links and references included. Library files have no
|
||||
* content or source root.
|
||||
*/
|
||||
function copyPathItem(nodes: ProjectNode[], at: MenuPoint, library: boolean): Entry {
|
||||
const row = (kind: PathKind, id: string, label: string) => {
|
||||
const paths = pathsFor(kind, nodes);
|
||||
return {
|
||||
id,
|
||||
label,
|
||||
// A selection only partly under a source root has no source-root path.
|
||||
preview: paths.length && paths.length === nodes.length ? paths.join("\n") : null,
|
||||
run: () => void copyPaths(kind, nodes),
|
||||
};
|
||||
};
|
||||
return {
|
||||
id: "copyPath",
|
||||
label: "Copy Path/Reference…",
|
||||
run: () =>
|
||||
openCopyPathChooser(
|
||||
at,
|
||||
[
|
||||
row("absolute", "project.copyAbsolutePath", "Absolute Path"),
|
||||
row("name", "project.copyFileName", "File Name"),
|
||||
...(library
|
||||
? []
|
||||
: [
|
||||
row("relative", "project.copyRelativePath", "Path From Content Root"),
|
||||
row("source", "project.copySourceRootPath", "Path From Source Root"),
|
||||
]),
|
||||
],
|
||||
menuGroupContext(nodes),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/** What contributed menu groups see: the selected (non-placeholder) paths. */
|
||||
export function menuGroupContext(nodes: ProjectNode[]): MenuGroupContext {
|
||||
const real = nodes.filter((n) => !n.placeholder);
|
||||
|
||||
@@ -8,7 +8,8 @@ import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { loadSettings, relativePath, useProject } from "@/platform/project";
|
||||
import type { MenuItem } from "@/ui";
|
||||
|
||||
const LABELS: Record<(typeof FILE_COLOR_NAMES)[number], string> = {
|
||||
/** English title per colour, also the title of its `file.<colour>` action (the editor tab menu). */
|
||||
export const LABELS: Record<(typeof FILE_COLOR_NAMES)[number], string> = {
|
||||
blue: "Blue",
|
||||
green: "Green",
|
||||
orange: "Orange",
|
||||
|
||||
@@ -128,6 +128,11 @@ export interface FileLink extends LinkPosition {
|
||||
}
|
||||
|
||||
/** The file links on the `shown` lines (a collapsed fold hides its links), in output order. */
|
||||
/** A copy of a line the model may still append to (the open last line). */
|
||||
function copyLine(line: ConsoleLine): ConsoleLine {
|
||||
return { ...line, spans: line.spans.map((span) => ({ ...span })) };
|
||||
}
|
||||
|
||||
export function fileLinks(lines: readonly ConsoleLine[], shown: (index: number) => boolean): FileLink[] {
|
||||
const links: FileLink[] = [];
|
||||
lines.forEach((line, i) => {
|
||||
@@ -257,7 +262,12 @@ export function ConsoleView({
|
||||
}: ConsoleViewProps) {
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const innerRef = useRef<HTMLDivElement>(null);
|
||||
const lines = model.lines;
|
||||
// Pause Output: the output so far stays on screen while the process keeps
|
||||
// writing; resuming shows everything that arrived meanwhile.
|
||||
const [paused, setPaused] = useState<readonly ConsoleLine[] | null>(null);
|
||||
const lines = paused ?? model.lines;
|
||||
const togglePaused = () =>
|
||||
setPaused((p) => (p ? null : model.lines.map((l, i, all) => (i === all.length - 1 ? copyLine(l) : l))));
|
||||
const patterns = useWorkflowSettings((s) => s.console.foldPatterns);
|
||||
const logColors = useWorkflowSettings((s) => s.console.logColors);
|
||||
const consoleRules = compileConsoleRules(useConsoleRules((s) => s.providers));
|
||||
@@ -539,7 +549,16 @@ export function ConsoleView({
|
||||
// Opens Settings › Console with the text added to the fold patterns, for OK / Cancel there.
|
||||
run: () => void executeAction("file.settings", `build.console#${foldText}`),
|
||||
},
|
||||
{ label: "Clear All", icon: "trash", disabled: !onClear, run: () => onClear?.() },
|
||||
{ label: "Pause Output", icon: "pause", checked: !!paused, run: togglePaused },
|
||||
{
|
||||
label: "Clear All",
|
||||
icon: "trash",
|
||||
disabled: !onClear,
|
||||
run: () => {
|
||||
setPaused(null);
|
||||
onClear?.();
|
||||
},
|
||||
},
|
||||
...(input
|
||||
? [{ kind: "separator" } as const, { label: "Send EOF", shortcut: "⌃D", run: () => input.onEof() }]
|
||||
: []),
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, within } from "@testing-library/react";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { hideContextMenu, useContextMenuStore } from "@/ui";
|
||||
import { ConsoleModel } from "./console";
|
||||
import { ConsoleView } from "./ConsoleView";
|
||||
|
||||
vi.mock("@tanstack/react-virtual", () => ({
|
||||
useVirtualizer: ({ count }: { count: number }) => ({
|
||||
getTotalSize: () => count * 20,
|
||||
getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, start: index * 20, key: index })),
|
||||
scrollToIndex: () => {},
|
||||
measureElement: () => {},
|
||||
measure: () => {},
|
||||
}),
|
||||
}));
|
||||
|
||||
beforeEach(() => useProject.setState({ settings: null }));
|
||||
afterEach(() => act(hideContextMenu));
|
||||
|
||||
function pauseItem(log: Element) {
|
||||
fireEvent.contextMenu(log);
|
||||
const items = useContextMenuStore.getState().menu?.items ?? [];
|
||||
return items.find((i) => "label" in i && i.label === "Pause Output") as
|
||||
| { checked?: boolean; run?: () => void }
|
||||
| undefined;
|
||||
}
|
||||
|
||||
it("Pause Output keeps the output on screen until it is resumed, then shows what arrived meanwhile", () => {
|
||||
const model = new ConsoleModel();
|
||||
model.append({ kind: "stdout", text: "first\nsecond " });
|
||||
const view = (version: number) => (
|
||||
<ConsoleView model={model} version={version} softWrap={false} follow={false} onFollowChange={() => {}} cwd="/" />
|
||||
);
|
||||
const { container, rerender } = render(view(1));
|
||||
const log = within(container).getByRole("log");
|
||||
expect(pauseItem(log)?.checked).toBe(false);
|
||||
act(() => pauseItem(log)!.run!());
|
||||
|
||||
// The open line and new lines keep arriving while paused, but are not shown.
|
||||
model.append({ kind: "stdout", text: "half\nthird\n" });
|
||||
rerender(view(2));
|
||||
expect(log.textContent).toContain("first");
|
||||
expect(log.textContent).toContain("second");
|
||||
expect(log.textContent).not.toContain("half");
|
||||
expect(log.textContent).not.toContain("third");
|
||||
expect(pauseItem(log)?.checked).toBe(true);
|
||||
|
||||
act(() => pauseItem(log)!.run!());
|
||||
expect(log.textContent).toContain("second half");
|
||||
expect(log.textContent).toContain("third");
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import { useMemo, type ComponentType } from "react";
|
||||
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { PageContext } from "../components/context";
|
||||
import { DEFAULT_SETTINGS } from "../model/schema";
|
||||
import { openSettings, stagedValue, useSettingsDialog } from "../model/staging";
|
||||
import { codeStyleLanguagePages } from "../pages/editor/codeStyle";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ languages: vi.fn() }));
|
||||
vi.mock("@/platform/ipc", async (original) => {
|
||||
const actual = await original<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...actual,
|
||||
isTauri: () => true,
|
||||
commands: {
|
||||
...actual.commands,
|
||||
languages: mocks.languages,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.languages.mockResolvedValue([
|
||||
{ id: "java", name: "Java", indent: { tabSize: 4, insertSpaces: true } },
|
||||
{ id: "rust", name: "Rust" },
|
||||
]);
|
||||
useProject.setState({ settings: structuredClone(DEFAULT_SETTINGS), project: null });
|
||||
openSettings("editor.codeStyle.java");
|
||||
});
|
||||
afterEach(cleanup);
|
||||
|
||||
function CodeStylePage({ id, Page }: { id: string; Page: ComponentType }) {
|
||||
const value = useMemo(() => ({ pageId: id, scope: "global" as const }), [id]);
|
||||
return (
|
||||
<PageContext.Provider value={value}>
|
||||
<Page />
|
||||
</PageContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
async function page(language: string) {
|
||||
const pages = await codeStyleLanguagePages();
|
||||
const spec = pages.find((p) => p.id === `editor.codeStyle.${language}`)!;
|
||||
render(<CodeStylePage id={spec.id} Page={spec.component!} />);
|
||||
}
|
||||
const value = () => stagedValue(useSettingsDialog.getState(), "global", "editor.codeStyle.languages");
|
||||
|
||||
describe("Java Imports (IntelliSort)", () => {
|
||||
it("stages the class-count and static-count options on the Java code style", async () => {
|
||||
await page("java");
|
||||
fireEvent.click(screen.getByRole("tab", { name: "Imports" }));
|
||||
fireEvent.change(screen.getByLabelText("Class count to use import with *"), { target: { value: "7" } });
|
||||
fireEvent.change(screen.getByLabelText("Names count to use static import with *"), { target: { value: "2" } });
|
||||
expect(value()).toEqual({
|
||||
java: { classCountToUseImportWithStar: 7, namesCountToUseStaticImportWithStar: 2 },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Reset to Language Defaults" }));
|
||||
expect(value()).toEqual({});
|
||||
});
|
||||
|
||||
it("keeps the Imports tab specific to Java", async () => {
|
||||
await page("rust");
|
||||
expect(screen.queryByRole("tab", { name: "Imports" })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -118,7 +118,7 @@ export interface ValidSettings extends WorkflowSettings {
|
||||
proxy: ProxySettingsValid;
|
||||
remoteDevelopment: { idleTimeoutMinutes: number };
|
||||
/** Tools › Download sources: a mirror prefix for the installer's release downloads. */
|
||||
toolDownloads: { githubMirror: string };
|
||||
toolDownloads: { githubMirror: string; configuredRegistriesOnly: boolean };
|
||||
languages: LanguagesValid;
|
||||
cmake: ReturnType<typeof validateCMake>;
|
||||
projectStructure: ProjectStructureValid;
|
||||
@@ -227,7 +227,7 @@ export const DEFAULT_SETTINGS: ValidSettings = {
|
||||
notifications: DEFAULT_NOTIFICATIONS,
|
||||
proxy: DEFAULT_PROXY,
|
||||
remoteDevelopment: { idleTimeoutMinutes: DEFAULT_REMOTE_IDLE_MINUTES },
|
||||
toolDownloads: { githubMirror: "" },
|
||||
toolDownloads: { githubMirror: "", configuredRegistriesOnly: false },
|
||||
languages: DEFAULT_LANGUAGES,
|
||||
cmake: {},
|
||||
projectStructure: DEFAULT_PROJECT_STRUCTURE,
|
||||
@@ -435,6 +435,7 @@ export function validateSettings(raw: Settings | unknown): ValidSettings {
|
||||
typeof obj(root.toolDownloads).githubMirror === "string"
|
||||
? String(obj(root.toolDownloads).githubMirror).trim()
|
||||
: "",
|
||||
configuredRegistriesOnly: obj(root.toolDownloads).configuredRegistriesOnly === true,
|
||||
},
|
||||
languages: validateLanguages(root.languages),
|
||||
cmake: validateCMake(root.cmake),
|
||||
|
||||
@@ -157,6 +157,11 @@ const COMMENTS = {
|
||||
keywords: ["Line comment at first column", "Add a space at line comment start"],
|
||||
};
|
||||
const CASE = { id: "case", label: "Case", keywords: ["Keywords", "Identifiers", "To upper", "To lower"] };
|
||||
const IMPORTS = {
|
||||
id: "imports",
|
||||
label: "Imports",
|
||||
keywords: ["imports", "static imports", "wildcard", "class count", "import with *"],
|
||||
};
|
||||
|
||||
const SPACES = { id: "spaces", label: "Spaces", keywords: ["Space", "Around binary operators", "Within braces"] };
|
||||
const PUNCTUATION = { id: "punctuation", label: "Punctuation", keywords: ["Semicolons", "Quotes"] };
|
||||
@@ -298,6 +303,41 @@ function LanguageStyle({ lang }: { lang: LanguageInfo }) {
|
||||
),
|
||||
});
|
||||
}
|
||||
if (lang.id === "java") {
|
||||
tabs.push({
|
||||
...IMPORTS,
|
||||
content: (
|
||||
<FormGroup>
|
||||
<Row
|
||||
label="Class count to use import with '*'"
|
||||
hint="Use a wildcard import once this many classes of one package are used (5 by default; 999 keeps single-class imports)."
|
||||
>
|
||||
<NumberInput
|
||||
value={own.classCountToUseImportWithStar ?? 5}
|
||||
onChange={(n) => set({ classCountToUseImportWithStar: n })}
|
||||
min={1}
|
||||
max={999}
|
||||
integer
|
||||
aria-label="Class count to use import with *"
|
||||
/>
|
||||
</Row>
|
||||
<Row
|
||||
label="Names count to use static import with '*'"
|
||||
hint="Use a wildcard static import once this many names are imported statically (3 by default; 999 keeps single imports)."
|
||||
>
|
||||
<NumberInput
|
||||
value={own.namesCountToUseStaticImportWithStar ?? 3}
|
||||
onChange={(n) => set({ namesCountToUseStaticImportWithStar: n })}
|
||||
min={1}
|
||||
max={999}
|
||||
integer
|
||||
aria-label="Names count to use static import with *"
|
||||
/>
|
||||
</Row>
|
||||
</FormGroup>
|
||||
),
|
||||
});
|
||||
}
|
||||
if (TS_STYLE_LANGUAGES.has(lang.id)) {
|
||||
tabs.push(
|
||||
{
|
||||
@@ -501,7 +541,14 @@ export async function codeStyleLanguagePages(): Promise<PageSpec[]> {
|
||||
...keywords,
|
||||
]),
|
||||
...(lang.id === "java"
|
||||
? ["Formatting profile", "IntelliJ IDEA", "Custom Eclipse formatter XML", "Eclipse formatter XML"]
|
||||
? [
|
||||
"Formatting profile",
|
||||
"IntelliJ IDEA",
|
||||
"Custom Eclipse formatter XML",
|
||||
"Eclipse formatter XML",
|
||||
IMPORTS.label,
|
||||
...IMPORTS.keywords,
|
||||
]
|
||||
: []),
|
||||
...(lang.id === "php" ? ["Alignment", "Align key-value pairs", "Align consecutive assignments"] : []),
|
||||
...(lang.id === "sql" ? [CASE.label, ...CASE.keywords, "Do not change"] : []),
|
||||
|
||||
@@ -892,7 +892,20 @@ export const TOOLS_PAGES: PageSpec[] = [
|
||||
title: "Download Mirrors",
|
||||
group: TOOLS_GROUP,
|
||||
order: 590,
|
||||
keywords: ["mirror", "download", "github", "proxy", "slow", "language server", "accelerate"],
|
||||
keywords: [
|
||||
"mirror",
|
||||
"download",
|
||||
"github",
|
||||
"proxy",
|
||||
"slow",
|
||||
"language server",
|
||||
"accelerate",
|
||||
"registry",
|
||||
"npm",
|
||||
"maven central",
|
||||
"nexus",
|
||||
"artifactory",
|
||||
],
|
||||
sections: [
|
||||
{
|
||||
title: "GitHub",
|
||||
@@ -905,6 +918,17 @@ export const TOOLS_PAGES: PageSpec[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Package Registries",
|
||||
options: [
|
||||
{
|
||||
kind: "toggle",
|
||||
key: "toolDownloads.configuredRegistriesOnly",
|
||||
label: "Use only the configured package registries",
|
||||
hint: "For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
} from "@/ui";
|
||||
import { useRowHeight } from "@/ui/density";
|
||||
import type { PopupAnchor } from "@/ui/Popup";
|
||||
import { isSubmenuAim, type MenuPointer } from "@/ui/menuAim";
|
||||
import { useActiveRepository, useWidgetBranch } from "./activeRepository";
|
||||
import {
|
||||
buildBranchRows,
|
||||
@@ -737,6 +738,14 @@ function MultiRepoPanel({
|
||||
const { menuFor, setMenuFor, openTagMenu } = useBranchSubmenu();
|
||||
const [repoMenu, setRepoMenu] = useState<{ root: string; el: HTMLElement; focus: boolean } | null>(null);
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const aim = useRef<{
|
||||
previous: MenuPointer | null;
|
||||
pointer: MenuPointer | null;
|
||||
moved: boolean;
|
||||
pending: number | null;
|
||||
timer?: ReturnType<typeof setTimeout>;
|
||||
}>({ previous: null, pointer: null, moved: false, pending: null });
|
||||
const repoMenuLabel = repoMenu ? tx`Branches of ${repoName(repoMenu.root)}` : "";
|
||||
const searchRef = useRef<HTMLInputElement>(null);
|
||||
/** Back from a repository's submenu to the search field. */
|
||||
const closeRepoMenu = () => {
|
||||
@@ -867,11 +876,52 @@ function MultiRepoPanel({
|
||||
}
|
||||
};
|
||||
// The pointer on a repository opens its branches right away; elsewhere it closes them.
|
||||
const hover = (i: number) => {
|
||||
const applyHover = (i: number) => {
|
||||
clearTimeout(aim.current.timer);
|
||||
aim.current.pending = null;
|
||||
setActive(i);
|
||||
if (rows[i]?.type === "repo") openSub(i, false);
|
||||
else setRepoMenu(null);
|
||||
};
|
||||
/** While the pointer heads for the open branch list, the rows it crosses wait (like submenus of a menu). */
|
||||
const aiming = () => {
|
||||
const { previous, pointer } = aim.current;
|
||||
const popup = repoMenu && document.querySelector(`[data-popup][aria-label="${CSS.escape(repoMenuLabel)}"]`);
|
||||
return !!popup && !!pointer && isSubmenuAim(previous, pointer, popup.getBoundingClientRect());
|
||||
};
|
||||
const deferHover = (i: number) => {
|
||||
clearTimeout(aim.current.timer);
|
||||
aim.current.pending = i;
|
||||
aim.current.timer = setTimeout(() => applyHover(i), 300);
|
||||
};
|
||||
const hover = (i: number) => {
|
||||
const fromPointer = aim.current.moved;
|
||||
aim.current.moved = false;
|
||||
const row = rows[i];
|
||||
const openRepo = row?.type === "repo" && row.repo.root === repoMenu?.root;
|
||||
if (fromPointer && repoMenu && !openRepo && aiming()) deferHover(i);
|
||||
else applyHover(i);
|
||||
};
|
||||
// Pointer positions for the aim check, recorded before the rows see the move (capture phase).
|
||||
useEffect(() => {
|
||||
if (!repoMenu) return;
|
||||
const onMove = (e: PointerEvent) => {
|
||||
const a = aim.current;
|
||||
if (a.pointer?.x === e.clientX && a.pointer.y === e.clientY) return;
|
||||
a.previous = a.pointer;
|
||||
a.pointer = { x: e.clientX, y: e.clientY };
|
||||
a.moved = true;
|
||||
if (a.pending === null) return;
|
||||
const popup = document.querySelector(`[data-popup][aria-label="${CSS.escape(repoMenuLabel)}"]`);
|
||||
if (popup?.contains(e.target as Node)) {
|
||||
clearTimeout(a.timer);
|
||||
a.pending = null;
|
||||
} else if (!aiming()) applyHover(a.pending);
|
||||
};
|
||||
document.addEventListener("pointermove", onMove, true);
|
||||
return () => document.removeEventListener("pointermove", onMove, true);
|
||||
});
|
||||
useEffect(() => () => clearTimeout(aim.current.timer), []);
|
||||
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
if (isNewBranchStroke(strokeOf(e))) {
|
||||
@@ -984,7 +1034,7 @@ function MultiRepoPanel({
|
||||
placement="right-start"
|
||||
offset={2}
|
||||
autoFocus={repoMenu.focus}
|
||||
aria-label={tx`Branches of ${repoName(repoMenu.root)}`}
|
||||
aria-label={repoMenuLabel}
|
||||
onClose={closeRepoMenu}
|
||||
className={styles.popup}
|
||||
>
|
||||
|
||||
@@ -276,6 +276,27 @@ describe("annotate Options", () => {
|
||||
const hidden = (v: EditorView) =>
|
||||
["date", "author", "revision"].filter((c) => v.dom.classList.contains(`cm-vcs-blame-hide-${c}`));
|
||||
|
||||
it("prints Today/Yesterday in the date cell when pretty formatting is on", async () => {
|
||||
const today = Date.now();
|
||||
const yesterday = today - 86_400_000;
|
||||
const recentLines: BlameLine[] = [
|
||||
{ commit: sha, author: "Aleks Zlateski", timeMs: today, summary: "today" },
|
||||
{ commit: otherSha, author: "Dan Crankshaw", timeMs: yesterday, summary: "yesterday" },
|
||||
];
|
||||
mocks.blame.mockResolvedValue({ status: "ok", data: recentLines });
|
||||
useProject.setState({ settings: { general: { dateFormat: { pretty: true } } } });
|
||||
const created = new EditorView({
|
||||
parent: document.body,
|
||||
state: EditorState.create({ doc: "first\nsecond\nthird", extensions: [blameSlot()] }),
|
||||
});
|
||||
view = created;
|
||||
await toggleAnnotations(created, "/repo/src/main.py");
|
||||
const cell = (commit: string) =>
|
||||
created.dom.querySelector<HTMLElement>(`.cm-vcs-blame [data-commit="${commit}"] .cm-vcs-blame-date`)?.textContent;
|
||||
expect(cell(sha)).toBe("Today");
|
||||
expect(cell(otherSha)).toBe("Yesterday");
|
||||
});
|
||||
|
||||
it("shows date and author by default and adds the revision from Options", async () => {
|
||||
view = await annotated();
|
||||
expect(
|
||||
|
||||
@@ -160,6 +160,15 @@ describe("buildMultiRepoRows", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("lists the current repository first, keeping the others' order and colours", () => {
|
||||
const rows = summary(buildMultiRepoRows({ ...input, current: "/p/ology-gateway", query: "" }));
|
||||
expect(rows.filter((r) => r.startsWith("repo"))).toEqual([
|
||||
"repo ology-gateway [dev] c3",
|
||||
"repo ology-collect [dev] c1",
|
||||
"repo ology-dependencies [dev] c2",
|
||||
]);
|
||||
});
|
||||
|
||||
it("groups common remote branches by remote when expanded", () => {
|
||||
const expanded = new Map([
|
||||
["common:local", false],
|
||||
|
||||
@@ -6,6 +6,7 @@ const mocks = vi.hoisted(() => ({
|
||||
update: vi.fn(),
|
||||
updateCurrent: vi.fn(),
|
||||
head: vi.fn(),
|
||||
checkout: vi.fn(),
|
||||
notify: vi.fn(),
|
||||
openWorktree: vi.fn(),
|
||||
}));
|
||||
@@ -22,7 +23,7 @@ vi.mock("../ops", async (original) => ({
|
||||
vi.mock("../openWorktree", () => ({ openWorktree: mocks.openWorktree }));
|
||||
vi.mock("@/platform/ipc", async (original) => {
|
||||
const real = await original<typeof import("@/platform/ipc")>();
|
||||
return { ...real, commands: { ...real.commands, vcsBranchInfo: mocks.head } };
|
||||
return { ...real, commands: { ...real.commands, vcsBranchInfo: mocks.head, vcsCheckout: mocks.checkout } };
|
||||
});
|
||||
vi.mock("@/workbench/contributions", async (original) => ({
|
||||
...(await original<typeof import("@/workbench/contributions")>()),
|
||||
@@ -30,7 +31,7 @@ vi.mock("@/workbench/contributions", async (original) => ({
|
||||
}));
|
||||
|
||||
import { branchMenu, commonBranchMenu } from "../branchMenu";
|
||||
import { branchUpdateSummary, updateBranches } from "../branchOps";
|
||||
import { branchUpdateSummary, checkoutAndUpdate, updateBranches } from "../branchOps";
|
||||
import { getAction } from "@/platform/actions";
|
||||
import { useProject } from "@/platform/project";
|
||||
import type { Settings } from "@/bindings";
|
||||
@@ -209,3 +210,38 @@ describe("branch common to several repositories", () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Checkout and Update", () => {
|
||||
const item = (items: ReturnType<typeof branchMenu>) =>
|
||||
items.find((i) => "label" in i && i.label === "Checkout and Update") as { disabled?: boolean } | undefined;
|
||||
|
||||
it("is offered for a local branch that is not checked out, and needs a tracked branch", () => {
|
||||
expect(item(branchMenu(branch("topic"), "main"))?.disabled).toBe(false);
|
||||
expect(item(branchMenu(branch("topic", { upstream: null }), "main"))?.disabled).toBe(true);
|
||||
expect(item(branchMenu(branch("origin/topic", { remote: true, upstream: null }), "main"))).toBeUndefined();
|
||||
expect(item(branchMenu(branch("main", { current: true }), "main"))).toBeUndefined();
|
||||
const common = { name: "feature", remote: false, current: false, favorite: false, upstream: true };
|
||||
expect(item(commonBranchMenu(common, ["/p", "/p/lib"], null))?.disabled).toBe(false);
|
||||
});
|
||||
|
||||
it("checks the branch out, then pulls it with the configured method", async () => {
|
||||
let head = "main";
|
||||
mocks.checkout.mockImplementation(async () => {
|
||||
head = "topic";
|
||||
return { status: "ok", data: { kind: "done" } };
|
||||
});
|
||||
mocks.head.mockImplementation(async () => ({ status: "ok", data: { head, upstream: `origin/${head}` } }));
|
||||
await checkoutAndUpdate(branch("topic"));
|
||||
expect(mocks.checkout).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.updateCurrent).toHaveBeenCalledWith([
|
||||
{ repo: "/p", op: { op: "pull", expectedBranch: "topic", rebase: false } },
|
||||
]);
|
||||
});
|
||||
|
||||
it("updates nothing when the checkout did not happen", async () => {
|
||||
mocks.checkout.mockResolvedValue({ status: "error", error: { kind: "failed", message: "nope" } });
|
||||
await checkoutAndUpdate(branch("topic"));
|
||||
expect(mocks.updateCurrent).not.toHaveBeenCalled();
|
||||
expect(mocks.update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -11,7 +11,7 @@ import { onWorkflowSettingsChange, workflowSettings } from "@/platform/workflowS
|
||||
import { showContextMenu, type MenuItem } from "@/ui";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { closeBlamePopup, scheduleCloseBlamePopup, scheduleOpenBlamePopup } from "./BlamePopup";
|
||||
import { formatDate } from "./model";
|
||||
import { formatPrettyDay } from "@/platform/dateFormat";
|
||||
import { saveVcsSetting } from "./settingsUi";
|
||||
import { useVcs } from "./store";
|
||||
|
||||
@@ -318,7 +318,7 @@ function build(lines: BlameLine[], doc: Text): BlameState {
|
||||
let label = labels.get(line.commit);
|
||||
if (!label && !isUncommitted(line)) {
|
||||
label = {
|
||||
date: formatDate(line.timeMs),
|
||||
date: line.timeMs ? formatPrettyDay(line.timeMs) : "",
|
||||
author: shortAuthorName(line.author, names),
|
||||
revision: line.commit.slice(0, 8),
|
||||
};
|
||||
|
||||
@@ -5,6 +5,7 @@ import { showContextMenu, useContextMenuStore, type MenuItem } from "@/ui";
|
||||
import { isFavoriteBranch } from "./branches";
|
||||
import {
|
||||
branchRef,
|
||||
checkoutAndUpdate,
|
||||
checkoutBranch,
|
||||
checkoutDetached,
|
||||
checkoutInRepos,
|
||||
@@ -158,6 +159,15 @@ export function branchMenu(
|
||||
}
|
||||
const items: MenuItem[] = [
|
||||
{ label: "Checkout", run: run(() => checkoutBranch(b)) },
|
||||
...(b.remote
|
||||
? []
|
||||
: [
|
||||
{
|
||||
label: "Checkout and Update",
|
||||
disabled: !b.upstream || updating || !!existingWorktree,
|
||||
run: run(() => checkoutAndUpdate(b)),
|
||||
},
|
||||
]),
|
||||
...(existingWorktree && !b.remote
|
||||
? [{ label: "Open Existing Worktree", icon: "folder", run: run(() => openWorktree(existingWorktree, true)) }]
|
||||
: []),
|
||||
@@ -327,6 +337,15 @@ export function commonBranchMenu(
|
||||
const base = bases[0];
|
||||
const items: MenuItem[] = [
|
||||
{ label: "Checkout", run: run(() => checkoutInRepos(b, roots)) },
|
||||
...(b.remote
|
||||
? []
|
||||
: [
|
||||
{
|
||||
label: "Checkout and Update",
|
||||
disabled: !b.upstream || !!useVcs.getState().remoteBusy || checkedOutInWorktree,
|
||||
run: run(() => checkoutAndUpdate(b, roots)),
|
||||
},
|
||||
]),
|
||||
newFrom,
|
||||
worktree,
|
||||
...(bases.every(Boolean)
|
||||
|
||||
@@ -1376,6 +1376,27 @@ export async function checkoutAndRebase({ branch, repos }: CheckoutRebaseTarget)
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Checkout and Update on a local branch: checks it out (in `roots`, or the
|
||||
* current repository), then updates it like Update does, in each repository
|
||||
* where the checkout took place.
|
||||
*/
|
||||
export async function checkoutAndUpdate(branch: NamedBranch, roots?: readonly string[]) {
|
||||
const project = useProject.getState().project;
|
||||
if (roots) await checkoutInRepos(branch, roots);
|
||||
else await checkoutBranch(branch);
|
||||
if (useProject.getState().project !== project) return;
|
||||
const repos: readonly (string | null)[] = roots ?? [currentRepo()];
|
||||
const heads = await Promise.all(
|
||||
repos.map(async (repo) => [repo, await call(commands.vcsBranchInfo(repo)).catch(() => null)] as const),
|
||||
);
|
||||
if (useProject.getState().project !== project) return;
|
||||
const targets = heads
|
||||
.filter(([, info]) => info?.head === branch.name)
|
||||
.map(([repo]) => ({ repo: repo ?? undefined, branch }));
|
||||
if (targets.length) await updateBranches(targets);
|
||||
}
|
||||
|
||||
export type BranchUpdateTarget = { repo?: string; branch?: Pick<Branch, "name" | "remote"> };
|
||||
|
||||
/** Update the named branches. Checked-out branches follow the configured update method. */
|
||||
|
||||
@@ -215,6 +215,9 @@ export function buildMultiRepoRows({
|
||||
if (m !== false)
|
||||
repoRows.push({ type: "repo", key: `repo:${repo.root}`, repo, color: repoColorIndex(i), matches: m });
|
||||
});
|
||||
// The repository this window works on comes first; the others keep their order (and colours).
|
||||
const currentRow = repoRows.findIndex((r) => r.type === "repo" && r.repo.root === current);
|
||||
if (currentRow > 0) repoRows.unshift(...repoRows.splice(currentRow, 1));
|
||||
blocks.push(repoRows);
|
||||
|
||||
/** A group row followed (when expanded) by its children; nothing when it has none. */
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
/**
|
||||
* Image editor kind (IDEA's image viewer): zoom in / out / fit / actual size,
|
||||
* ⌘/Ctrl+wheel zoom, transparency chessboard, dimensions and file size.
|
||||
* Images are read by the backend as `data:` URLs (the CSP allows those).
|
||||
* Images are read by the backend as `data:` URLs (the CSP allows those). As the preview of an SVG
|
||||
* file it shows the source as typed instead (`source`), drawn as an image so its scripts never run.
|
||||
*/
|
||||
import {
|
||||
useCallback,
|
||||
@@ -59,9 +60,19 @@ export function toggleChessboard() {
|
||||
}
|
||||
|
||||
const PADDING = 32;
|
||||
const NO_FOCUS_TARGET = { current: null };
|
||||
const INVALID_SVG = "invalid-svg";
|
||||
|
||||
export function ImageViewer({ input }: { input: EditorInput }) {
|
||||
/** An SVG source as an image URL. */
|
||||
export const svgDataUrl = (source: string) => `data:image/svg+xml;charset=utf-8,${encodeURIComponent(source)}`;
|
||||
|
||||
/**
|
||||
* `source`: the SVG text to show instead of the file on disk (the SVG editor's preview); null while
|
||||
* it isn't known yet.
|
||||
*/
|
||||
export function ImageViewer({ input, source }: { input: EditorInput; source?: string | null }) {
|
||||
const path = input.path!;
|
||||
const live = source !== undefined;
|
||||
const [src, setSrc] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [size, setSize] = useState<number | null>(null);
|
||||
@@ -75,18 +86,27 @@ export function ImageViewer({ input }: { input: EditorInput }) {
|
||||
const canvasRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
if (live) return;
|
||||
let current = true;
|
||||
Promise.all([call(commands.fsReadImage(path)), call(commands.fsProbe(path))])
|
||||
.then(([url, probe]) => {
|
||||
if (!live) return;
|
||||
if (!current) return;
|
||||
setSrc(url);
|
||||
setSize(probe.size);
|
||||
})
|
||||
.catch((e: unknown) => live && setError(e instanceof Error ? e.message : String(e)));
|
||||
.catch((e: unknown) => current && setError(e instanceof Error ? e.message : String(e)));
|
||||
return () => {
|
||||
live = false;
|
||||
current = false;
|
||||
};
|
||||
}, [path, reload]);
|
||||
}, [path, reload, live]);
|
||||
|
||||
// The typed source: each edit is drawn again, so an invalid SVG recovers once it's valid.
|
||||
const liveSrc = useMemo(() => (source ? svgDataUrl(source) : null), [source]);
|
||||
const liveSize = useMemo(() => (source ? new TextEncoder().encode(source).length : null), [source]);
|
||||
const [invalidSrc, setInvalidSrc] = useState<string | null>(null);
|
||||
const shownSrc = live ? liveSrc : src;
|
||||
const shownSize = live ? liveSize : size;
|
||||
const shownError = live ? (invalidSrc !== null && invalidSrc === liveSrc ? INVALID_SVG : null) : error;
|
||||
|
||||
const available = useCallback(() => {
|
||||
const el = canvasRef.current;
|
||||
@@ -133,7 +153,8 @@ export function ImageViewer({ input }: { input: EditorInput }) {
|
||||
};
|
||||
}, [handle]);
|
||||
|
||||
useForwardFocus(rootRef);
|
||||
// Beside the source editor, the preview leaves the editor's focus alone.
|
||||
useForwardFocus(live ? NO_FOCUS_TARGET : rootRef);
|
||||
|
||||
const onLoad = (img: HTMLImageElement) => {
|
||||
// SVGs without intrinsic size report 0×0; show them at a usable size.
|
||||
@@ -162,7 +183,7 @@ export function ImageViewer({ input }: { input: EditorInput }) {
|
||||
};
|
||||
el.addEventListener("wheel", onWheel, { passive: false });
|
||||
return () => el.removeEventListener("wheel", onWheel);
|
||||
}, [error, src]);
|
||||
}, [shownError, shownSrc]);
|
||||
|
||||
const onPointerDown = (e: ReactPointerEvent) => {
|
||||
if (e.button !== 0 && e.button !== 1) return;
|
||||
@@ -204,15 +225,17 @@ export function ImageViewer({ input }: { input: EditorInput }) {
|
||||
<div className={styles.imageActions}>
|
||||
<div className={styles.imageActionGroup}>
|
||||
<IconButton icon="chessboard" size="small" action="image.toggleChessboard" pressed={chessboard} />
|
||||
<IconButton
|
||||
icon="refresh"
|
||||
size="small"
|
||||
title="Reload from Disk"
|
||||
onClick={() => {
|
||||
setError(null);
|
||||
setReload((n) => n + 1);
|
||||
}}
|
||||
/>
|
||||
{!live && (
|
||||
<IconButton
|
||||
icon="refresh"
|
||||
size="small"
|
||||
title="Reload from Disk"
|
||||
onClick={() => {
|
||||
setError(null);
|
||||
setReload((n) => n + 1);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className={styles.imageActionGroup}>
|
||||
<IconButton icon="zoom-in" size="small" action="image.zoomIn" />
|
||||
@@ -221,7 +244,7 @@ export function ImageViewer({ input }: { input: EditorInput }) {
|
||||
<IconButton icon="maximize" size="small" action="image.fitToWindow" />
|
||||
</div>
|
||||
</div>
|
||||
{svg && (
|
||||
{svg && !live && (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.textButton}
|
||||
@@ -230,16 +253,18 @@ export function ImageViewer({ input }: { input: EditorInput }) {
|
||||
<T>Open as Text</T>
|
||||
</button>
|
||||
)}
|
||||
{(natural || size !== null || view) && (
|
||||
{(natural || shownSize !== null || view) && (
|
||||
<div className={styles.imageInfo}>
|
||||
{natural && <span>{`${natural.w} × ${natural.h}`}</span>}
|
||||
{size !== null && <span>{formatSize(size)}</span>}
|
||||
{shownSize !== null && <span>{formatSize(shownSize)}</span>}
|
||||
{view && <span>{zoomLabel(z)}</span>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{error ? (
|
||||
<div className={styles.message}>{tx`Cannot show the image: ${error}`}</div>
|
||||
{shownError ? (
|
||||
<div className={styles.message}>
|
||||
{shownError === INVALID_SVG ? tx("The SVG source is not valid.") : tx`Cannot show the image: ${shownError}`}
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
data-wheel-scroll
|
||||
@@ -250,9 +275,9 @@ export function ImageViewer({ input }: { input: EditorInput }) {
|
||||
onPointerUp={endDrag}
|
||||
onPointerCancel={endDrag}
|
||||
>
|
||||
{src && (
|
||||
{shownSrc && (
|
||||
<img
|
||||
src={src}
|
||||
src={shownSrc}
|
||||
alt={path.slice(path.lastIndexOf("/") + 1)}
|
||||
draggable={false}
|
||||
className={clsx(styles.image, chessboard && styles.chessboard, z >= 4 && styles.pixelated)}
|
||||
@@ -266,7 +291,7 @@ export function ImageViewer({ input }: { input: EditorInput }) {
|
||||
: { visibility: "hidden" }
|
||||
}
|
||||
onLoad={(e) => onLoad(e.currentTarget)}
|
||||
onError={() => setError("the file is not a valid image")}
|
||||
onError={() => (live ? setInvalidSrc(shownSrc) : setError("the file is not a valid image"))}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { IconButton } from "@/ui";
|
||||
import type { LayoutMode } from "./layoutModes";
|
||||
import styles from "./markdown/Markdown.module.css";
|
||||
|
||||
/** Editor Only / Editor and Preview / Preview Only buttons of a text editor with a preview. */
|
||||
export function LayoutActions({ tabId, mode, label }: { tabId: string; mode: LayoutMode; label: string }) {
|
||||
return (
|
||||
<div className={styles.layoutActions} role="toolbar" aria-label={label}>
|
||||
<IconButton
|
||||
icon="editor-only"
|
||||
iconSize={16}
|
||||
size="small"
|
||||
title="Editor Only"
|
||||
action="markdown.editorOnly"
|
||||
actionArg={tabId}
|
||||
pressed={mode === "editor"}
|
||||
/>
|
||||
<IconButton
|
||||
icon="editor-preview"
|
||||
iconSize={16}
|
||||
size="small"
|
||||
title="Editor and Preview"
|
||||
action="markdown.editorAndPreview"
|
||||
actionArg={tabId}
|
||||
pressed={mode === "split"}
|
||||
/>
|
||||
<IconButton
|
||||
icon="preview-only"
|
||||
iconSize={16}
|
||||
size="small"
|
||||
title="Preview Only"
|
||||
action="markdown.previewOnly"
|
||||
actionArg={tabId}
|
||||
pressed={mode === "preview"}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Non-text editors and the Markdown preview: images open in an image viewer,
|
||||
* binary and very large files in a read-only hex view (both through file
|
||||
* editor providers consulted by `openFile`), and Markdown files get IDEA's
|
||||
* editor providers consulted by `openFile`), and Markdown and SVG files get IDEA's
|
||||
* Editor / Editor and Preview / Preview layouts around the text editor.
|
||||
*/
|
||||
import { registerActions, type Action } from "@/platform/actions";
|
||||
@@ -29,12 +29,16 @@ import {
|
||||
imageInput,
|
||||
isImagePath,
|
||||
isMarkdownPath,
|
||||
isSvgPath,
|
||||
wantsHexView,
|
||||
} from "./fileKinds";
|
||||
import { ImageViewer, toggleChessboard, useImageViewers } from "./ImageViewer";
|
||||
import { HexViewer } from "./HexViewer";
|
||||
import { registerMarkdownLiveSource } from "./markdown/live";
|
||||
import { setMarkdownMode, useMarkdownSourceHidden, type MarkdownMode } from "./markdown/modes";
|
||||
import { setMarkdownMode, useMarkdownModes, useMarkdownSourceHidden } from "./markdown/modes";
|
||||
import type { LayoutMode } from "./layoutModes";
|
||||
import { registerSvgLiveSource } from "./svg/live";
|
||||
import { SvgLayoutActions, svgModes } from "./svg/SvgEditor";
|
||||
import { MarkdownLayoutActions } from "./markdown/MarkdownLayoutActions";
|
||||
import { canExtractImages, extractImages, EXTRACT_IMAGES, EXTRACT_IMAGES_TITLE } from "./markdown/extractImages";
|
||||
|
||||
@@ -65,19 +69,35 @@ function imageActions(): Action[] {
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The tab whose layout an Editor Only / Editor and Preview / Preview Only action sets: the one its
|
||||
* tab button passes, else the focused editor's when it's a Markdown or SVG file.
|
||||
*/
|
||||
function layoutTarget(arg: unknown): { tabId: string; set: (tabId: string, mode: LayoutMode) => void } | null {
|
||||
if (typeof arg === "string") {
|
||||
return { tabId: arg, set: svgModes.useModes.getState().byTab[arg] ? svgModes.set : setMarkdownMode };
|
||||
}
|
||||
const editor = activeEditor();
|
||||
const path = editor?.ctx.path ?? "";
|
||||
if (!editor?.tabId) return null;
|
||||
if (isSvgPath(path)) return { tabId: editor.tabId, set: svgModes.set };
|
||||
if (isMarkdownPath(path) || useMarkdownModes.getState().byTab[editor.tabId])
|
||||
return { tabId: editor.tabId, set: setMarkdownMode };
|
||||
return null;
|
||||
}
|
||||
|
||||
function markdownActions(): Action[] {
|
||||
const mode = (id: string, title: string, m: MarkdownMode, icon: string): Action => ({
|
||||
const mode = (id: string, title: string, m: LayoutMode, icon: string): Action => ({
|
||||
id,
|
||||
title,
|
||||
category: "Markdown",
|
||||
icon,
|
||||
keywords: ["markdown", "preview", "layout"],
|
||||
when: "textEditorActive && editorLangId == markdown",
|
||||
keywords: ["markdown", "svg", "preview", "layout"],
|
||||
when: "textEditorActive",
|
||||
enabled: ({ arg }) => !!layoutTarget(arg),
|
||||
run: ({ arg }) => {
|
||||
// The tab's layout buttons pass their tab; the keyboard acts on the focused editor's.
|
||||
const editor = activeEditor();
|
||||
const tabId = typeof arg === "string" ? arg : isMarkdownPath(editor?.ctx.path ?? "") ? editor?.tabId : undefined;
|
||||
if (tabId) setMarkdownMode(tabId, m);
|
||||
const target = layoutTarget(arg);
|
||||
target?.set(target.tabId, m);
|
||||
},
|
||||
});
|
||||
return [
|
||||
@@ -143,6 +163,15 @@ export function activate(): () => void {
|
||||
useSourceHidden: useMarkdownSourceHidden,
|
||||
}),
|
||||
registerMarkdownLiveSource(),
|
||||
registerTextEditorWrapper({
|
||||
id: "viewers.svg",
|
||||
fallback: true,
|
||||
matches: isSvgPath,
|
||||
component: lazyComponent(() => import("./svg/SvgEditor").then((m) => m.SvgEditor)),
|
||||
tabActions: SvgLayoutActions,
|
||||
useSourceHidden: svgModes.useSourceHidden,
|
||||
}),
|
||||
registerSvgLiveSource(),
|
||||
registerMenuGroup({
|
||||
id: EXTRACT_IMAGES,
|
||||
menus: ["editor"],
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Layout of a text editor with a preview (IDEA's TextEditorWithPreview): Editor Only / Editor and
|
||||
* Preview / Preview Only, per editor tab. Split panes showing the same file each keep their own;
|
||||
* tabs opened later take the layout chosen last for that kind of file.
|
||||
*/
|
||||
import { create, type StoreApi, type UseBoundStore } from "zustand";
|
||||
|
||||
export type LayoutMode = "editor" | "split" | "preview";
|
||||
|
||||
const MODES: readonly LayoutMode[] = ["editor", "split", "preview"];
|
||||
|
||||
export interface LayoutModesState {
|
||||
byTab: Record<string, LayoutMode>;
|
||||
/** Mode of tabs opened since: the last one chosen. */
|
||||
fallback: LayoutMode;
|
||||
}
|
||||
|
||||
export const modeOf = (s: LayoutModesState, tabId: string): LayoutMode => s.byTab[tabId] ?? s.fallback;
|
||||
|
||||
export interface LayoutModes {
|
||||
useModes: UseBoundStore<StoreApi<LayoutModesState>>;
|
||||
/** Preview Only hides the source editor of `tabId`. */
|
||||
useSourceHidden: (tabId: string) => boolean;
|
||||
/** Fixes a shown tab's mode, so choosing one in another tab doesn't change it. */
|
||||
pin: (tabId: string) => void;
|
||||
set: (tabId: string, mode: LayoutMode) => void;
|
||||
}
|
||||
|
||||
/** The layouts of one kind of file, the last one chosen kept under `storageKey`. */
|
||||
export function createLayoutModes(storageKey: string): LayoutModes {
|
||||
const stored = (): LayoutMode => {
|
||||
try {
|
||||
const v = localStorage.getItem(storageKey);
|
||||
return MODES.includes(v as LayoutMode) ? (v as LayoutMode) : "split";
|
||||
} catch {
|
||||
return "split";
|
||||
}
|
||||
};
|
||||
const useModes = create<LayoutModesState>(() => ({ byTab: {}, fallback: stored() }));
|
||||
return {
|
||||
useModes,
|
||||
useSourceHidden: (tabId) => useModes((s) => modeOf(s, tabId) === "preview"),
|
||||
pin: (tabId) => {
|
||||
if (useModes.getState().byTab[tabId]) return;
|
||||
useModes.setState((s) => ({ byTab: { ...s.byTab, [tabId]: s.fallback } }));
|
||||
},
|
||||
set: (tabId, mode) => {
|
||||
useModes.setState((s) => ({ byTab: { ...s.byTab, [tabId]: mode }, fallback: mode }));
|
||||
try {
|
||||
localStorage.setItem(storageKey, mode);
|
||||
} catch {
|
||||
// Per-viewer convenience only.
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача