mirror of
https://github.com/nushell/nushell.git
synced 2025-07-08 18:37:07 +02:00
Compare commits
859 Commits
Author | SHA1 | Date | |
---|---|---|---|
5c81bcef1a | |||
8cba59040f | |||
735864c384 | |||
63cb01e83b | |||
ef38805ef9 | |||
82e6873702 | |||
df15fc24fe | |||
7ca62b7b35 | |||
8f4c182a0c | |||
acd2fe8c51 | |||
5c57d6a74d | |||
2ac63910f6 | |||
55689ddb50 | |||
3aab69110e | |||
b9e65e35b8 | |||
356e05177c | |||
e48b94965b | |||
2f731fa1ae | |||
e6be167797 | |||
bfe7133e7c | |||
5f8d8b4a4b | |||
b67b6f7fc5 | |||
560c2e63ac | |||
7f758d3e51 | |||
cc04b9a916 | |||
3005fe10e5 | |||
34b3a49cae | |||
8144926dc7 | |||
5f92fd20e9 | |||
6481bf272c | |||
15406a4247 | |||
9e667cc879 | |||
3e55addbdd | |||
e5ff72120a | |||
ffde939df3 | |||
43108de547 | |||
fa113172da | |||
7ead89844a | |||
74724dee80 | |||
db4b26c1ac | |||
8e7405bf49 | |||
77aee7e543 | |||
60041879f3 | |||
a6e455efc3 | |||
8e538c650e | |||
234ba197d7 | |||
5a34671343 | |||
9b139330f8 | |||
6564ed710d | |||
4954a762b7 | |||
8eece32a8d | |||
4b9f479e5c | |||
429c4332b1 | |||
01a00641f9 | |||
55bb501c71 | |||
c55b5c0a55 | |||
ca275f59da | |||
e752d8a964 | |||
fe1174bf16 | |||
1de57eb2b6 | |||
acd7c98c39 | |||
0e4729b203 | |||
6a0c88d516 | |||
dacf80f34a | |||
9ce61dc677 | |||
b912d4c1ea | |||
b150f9f5d8 | |||
9c435fee75 | |||
ce071f2498 | |||
057de06613 | |||
8695b57584 | |||
c9652bce00 | |||
bf86cd50a5 | |||
b4a1f0f003 | |||
8d8304cf91 | |||
92c1051143 | |||
9ebb61fc2d | |||
2254805a6d | |||
6cbd42974b | |||
8584aa79a2 | |||
a3bf2bff49 | |||
5e8754bd85 | |||
a45bd0301a | |||
45c17d9664 | |||
39cdf56214 | |||
9e9fe83bfd | |||
e735d0c561 | |||
39e51f1953 | |||
43a3983d36 | |||
a8b4e81408 | |||
6c13c67528 | |||
2a484a3e7e | |||
a78cd6e231 | |||
a528c043fe | |||
47f9fd3644 | |||
fe9f732c5f | |||
a5d02a0737 | |||
7a945848de | |||
a92949b5c3 | |||
d5ae979094 | |||
388e84e7ef | |||
a5af77dd72 | |||
a2dd948e71 | |||
fe60fb8679 | |||
250071939b | |||
0ea973b78b | |||
a2a346e39c | |||
6dc7ff2335 | |||
1acc2bfd96 | |||
10d65b611f | |||
edb61fc1d5 | |||
155de9f6fc | |||
b82e279f9d | |||
6bbe5b6255 | |||
1019acb7a3 | |||
83b1ec83c9 | |||
d9a00a876b | |||
e4625acf24 | |||
7fb48b9a2f | |||
5fcbefb7b4 | |||
345cdef113 | |||
a7c1b363eb | |||
d45e9671d4 | |||
517dc6d39e | |||
e590d3587c | |||
bdaa32666a | |||
9804cd82f8 | |||
59b85e549c | |||
dae4a9b091 | |||
fb10e1dfc5 | |||
4ca47258a0 | |||
b37662c7e1 | |||
3076378373 | |||
4c4c1f6147 | |||
35c8485442 | |||
3268ecd116 | |||
44493dac51 | |||
6f9b9914cf | |||
ffb9ab9eef | |||
5fe0ca418d | |||
ecc820a8c1 | |||
6047b04208 | |||
8d8b011702 | |||
07c9f681c7 | |||
c422c6cc3d | |||
e251f3a0b4 | |||
77ca73f414 | |||
48c75831fc | |||
4b8a259916 | |||
5733a13409 | |||
f9049c4c6c | |||
66b5931438 | |||
503052b669 | |||
7d6a32c5f8 | |||
a1b7261121 | |||
5a4b6f0f7f | |||
78b227d1ef | |||
07598c9620 | |||
7413ef2824 | |||
0cc735a7b2 | |||
d00038eb4b | |||
47af701380 | |||
24b4ac692e | |||
fb72da0e82 | |||
d339902dc6 | |||
393f424f1c | |||
c8f54476c9 | |||
d42c2b2dbc | |||
ed64a44b82 | |||
1855dfb656 | |||
91c01bf6b3 | |||
29256b161c | |||
32f098d91d | |||
06996d8c7f | |||
2306ef3063 | |||
f82a1d8e4e | |||
f0e0ab35fc | |||
3b20d6890c | |||
6eb00f6c60 | |||
4ecec59224 | |||
bf3bb66c3e | |||
6b3236715b | |||
cbedc8403f | |||
1d68c48a92 | |||
fff4de5c44 | |||
45d33e70db | |||
9b35d59023 | |||
71611dec4f | |||
a122e55129 | |||
6cedc05384 | |||
8efbb48cb0 | |||
0bfa769b7d | |||
5afc49250f | |||
efb81a1277 | |||
4a8124ad1e | |||
8ddebcb932 | |||
b2d7427d2d | |||
b4400c4896 | |||
5a8d4c628f | |||
ebdb7ac2d8 | |||
a33a7960bb | |||
3603610026 | |||
017151dff1 | |||
e892aad3f6 | |||
ad90b6e5f3 | |||
4da7bbbb59 | |||
b9808c8598 | |||
36036d9308 | |||
99c0a2575f | |||
487789b45b | |||
b3d6896977 | |||
8ee52b6ee1 | |||
46dba8853a | |||
eb4d19fb9c | |||
c3678764b4 | |||
9bb2c8faf5 | |||
74dcac3b0d | |||
6d51e34d0a | |||
de76c7a57d | |||
0e23400510 | |||
d0a83fec69 | |||
57510f2fd2 | |||
58b96fdede | |||
9e3d6c3bfd | |||
4a955d7e76 | |||
637283ffad | |||
5afbfb5c2c | |||
d128c0e02b | |||
60e6ea5abd | |||
415607706f | |||
f2b977b9c5 | |||
35e8420780 | |||
1c5846e1fb | |||
5ec6edb9c5 | |||
5d8bedfbe4 | |||
0477493734 | |||
e6b196c141 | |||
49960beb35 | |||
1b677f167e | |||
d881481758 | |||
a3ea0c304a | |||
4fda6d7eaa | |||
771e24913d | |||
aded2c1937 | |||
e54b867e8e | |||
c12b4b4af7 | |||
87ddba0193 | |||
a29b61bd4f | |||
7c6ea81dd4 | |||
d06ebb1686 | |||
d93953a56f | |||
74283c3ebc | |||
8a030f3bfc | |||
5518ffd248 | |||
bcdb9bf5b4 | |||
3509bde1a9 | |||
add20873d0 | |||
427db0d101 | |||
7bac0b417f | |||
56efbd7de9 | |||
91282d4404 | |||
398976e43e | |||
f723bc6989 | |||
22142bd4ae | |||
caf1432dc7 | |||
65c90d5b45 | |||
50ca77437d | |||
71b4949843 | |||
54a18991ab | |||
1fcb98289a | |||
01e5ba01f6 | |||
1134c2f16c | |||
d18cf19a3f | |||
2ec2028637 | |||
b84a01cb1d | |||
ca4d8008d4 | |||
a256f6d0d1 | |||
0aa6954f33 | |||
68d98fcf24 | |||
87086262f3 | |||
3fab427383 | |||
61fa826159 | |||
0b9fc4ff3a | |||
1817d5e01e | |||
0ca0f8ec17 | |||
6be5631477 | |||
678e942bd8 | |||
83ddf0ebe2 | |||
eaea00366b | |||
0788fe5e72 | |||
b2257a5ca3 | |||
3bf5999ef4 | |||
8a85299575 | |||
3db0aed9f7 | |||
09276db2a5 | |||
0e496f900d | |||
1ed645c6c2 | |||
bc6948dc89 | |||
e9c17daecd | |||
53beba7acc | |||
ed0fce9aa6 | |||
995603b08c | |||
a49e5b30ff | |||
97e7d550c8 | |||
bc54930bc6 | |||
0d6e43097d | |||
393717dbb4 | |||
da8cb14f8b | |||
9f01cf333c | |||
d391e912ff | |||
8b185a4008 | |||
90b65018b6 | |||
7ec5f2f2eb | |||
332f1192a6 | |||
944cad35bf | |||
86ae27b0c1 | |||
d9a888528a | |||
05f1b41275 | |||
5b03bca138 | |||
d409171ba8 | |||
0567407f85 | |||
6872d2ac2a | |||
ad4450f9e8 | |||
d8478ca690 | |||
aab31833a2 | |||
c0648a83be | |||
744a28b31d | |||
b4b68afa17 | |||
dd22647fcd | |||
f66136bc86 | |||
8cf9bc9993 | |||
d0aa69bfcb | |||
4a1d12462f | |||
8d5fbc6fcb | |||
85bfdba1e2 | |||
546c753d1e | |||
2c3aade057 | |||
be52f7fb07 | |||
ec5396a352 | |||
403bf1a734 | |||
05ff7a9925 | |||
5c2a767987 | |||
35798ce0cc | |||
47d6a66fbf | |||
616f065324 | |||
1e39a1a7a3 | |||
66ad83c15c | |||
c48e9cdf5b | |||
6a274b860a | |||
2f8a52d256 | |||
0f4a073eaf | |||
626410b2aa | |||
a193b85123 | |||
0f40c44ed2 | |||
cd6f86052d | |||
b9858ea8f8 | |||
cb1eefd24a | |||
a1840e9d20 | |||
b01cbf82c3 | |||
e89c796b41 | |||
758351c732 | |||
77d33766f1 | |||
b0be6c3013 | |||
93e5d8edc9 | |||
9c6bfc0be9 | |||
77e73cef66 | |||
7d963776a0 | |||
ecc153cbef | |||
d1309a36b2 | |||
1d3f6105f5 | |||
e36a2947b9 | |||
64f50a179e | |||
f9cf1d943c | |||
10a42de64f | |||
c66bd5e809 | |||
3f224db990 | |||
491a9c019c | |||
77e9f8d7df | |||
14bf0b000e | |||
0ca49091c0 | |||
bb8949f2b2 | |||
ef7fbf4bf9 | |||
eb2e2e6370 | |||
a8eef9af33 | |||
400a9d3b1e | |||
7095d8994e | |||
2d41613039 | |||
1552eb921a | |||
0ac3f7a1c8 | |||
bddb63ccb5 | |||
7625aed200 | |||
19beafa865 | |||
8543b0789d | |||
bdaa01165e | |||
b2a557d4ed | |||
0903a891e4 | |||
1b2916988e | |||
d74a260883 | |||
31d9c0889c | |||
222c0f11c3 | |||
106ca65c58 | |||
4c97b3dd28 | |||
e672689a76 | |||
2579a827fc | |||
8c487edf62 | |||
0b97f52a8b | |||
21b84a6d65 | |||
d3be5ec750 | |||
4b16406050 | |||
b0ce602e4b | |||
aa876ce24f | |||
71fdf717a8 | |||
4de0347fdc | |||
f34ac9be62 | |||
12652f897a | |||
24ee381fea | |||
494a07f6f3 | |||
61455b457d | |||
57ce6a7c66 | |||
0bd4d27e8d | |||
1701303279 | |||
fd09609b44 | |||
c7583ecdb7 | |||
4eec4a27c7 | |||
86faf753bd | |||
79d0735864 | |||
808e523adc | |||
a52386e837 | |||
c26d91fb61 | |||
0a5f8f05da | |||
a13946e3ef | |||
2e01bf9cba | |||
7e82f8d9b5 | |||
2bef85a913 | |||
e435196956 | |||
af1ab39851 | |||
baddc86d9d | |||
de6bab59bf | |||
0ff1cb1ea6 | |||
3e9bb4028a | |||
878e08cfa4 | |||
4e78f3649b | |||
ccd72fa64a | |||
03e688ea7b | |||
7e949595bd | |||
d31a51e3bc | |||
0df847da15 | |||
6af59cb0ea | |||
2ad0fcb377 | |||
f34034ae58 | |||
0e2167884d | |||
e445c41454 | |||
454d1a995c | |||
62575c9a4f | |||
4898750fc1 | |||
48b4471382 | |||
f7b8f97873 | |||
4ae1b1cc26 | |||
b7a34498e3 | |||
10fd3115c2 | |||
df60793e3b | |||
a4952bc029 | |||
f6ca62384e | |||
d6141881f2 | |||
f93033c20b | |||
33fb17776a | |||
b864a455f2 | |||
b9c78a05aa | |||
26c36e932e | |||
bd096430cb | |||
6148314dcd | |||
a7b5bd18ba | |||
e01eb42e74 | |||
c1d76bfac7 | |||
12483fac92 | |||
1a62d87a42 | |||
2ccbefe01e | |||
438062d7fc | |||
0a1af85200 | |||
5bf077d64f | |||
dec0a2517f | |||
324d625324 | |||
e22b70acff | |||
a5c604c283 | |||
644164fab3 | |||
592e677caf | |||
cc7bdebc1c | |||
27d798270b | |||
50f1e33965 | |||
ffc3727a1e | |||
b093d5d10d | |||
9e589a9d93 | |||
f8d2bff283 | |||
0a2e711351 | |||
ba5258d716 | |||
c358400351 | |||
a3f817d71b | |||
c6e2607868 | |||
a29da8c95b | |||
a09aaf3495 | |||
ffc8e752a5 | |||
6ca07b87b9 | |||
49e45915f0 | |||
96e3a3de68 | |||
2aa5c2c41f | |||
4b3e3a37a3 | |||
2492165fcb | |||
c602b5a1e8 | |||
9bbb9711e4 | |||
680405e527 | |||
44595b44c5 | |||
b27c7702f9 | |||
378a3ae05f | |||
836a56b347 | |||
b36ac8f2f8 | |||
b1e7bb899a | |||
7c285750c7 | |||
e93a8b1d32 | |||
42f0b55de0 | |||
253b223e65 | |||
85bfdca578 | |||
4dd9d0d46b | |||
fd1ac5106d | |||
b572b4ecbd | |||
585e104608 | |||
d0aefa99eb | |||
728e95c52b | |||
83087e0f9d | |||
3fb1e37473 | |||
9890966fa4 | |||
aba0fb0000 | |||
0e86ba4b63 | |||
fc23c6721a | |||
f4a129a792 | |||
8deecc0137 | |||
c7966e81c2 | |||
2659c359e9 | |||
e389e51b2b | |||
0ab6b66d8f | |||
8608d8d873 | |||
d34a2c353f | |||
150b0b6b86 | |||
d0e0701a88 | |||
28b20c5ec3 | |||
9088ef182e | |||
c4d1aa452d | |||
66e52b7cfc | |||
e761954cf0 | |||
58829e3560 | |||
62652cf8c1 | |||
4482862a40 | |||
d80ba00590 | |||
81dd4a8450 | |||
101ed629a4 | |||
95ec2fcce7 | |||
73bc3389e5 | |||
bc38a6a795 | |||
e89866bedb | |||
ca09dbbbee | |||
fa4531fd17 | |||
d17c970f8c | |||
6ca62ef131 | |||
8e84e33638 | |||
b9be416937 | |||
0a8c9b22b0 | |||
527c44ed84 | |||
8ee015a847 | |||
e8cabd16d5 | |||
88e07b5ea4 | |||
f3ee8b50e3 | |||
68ad854b0d | |||
789b2e603a | |||
66398fbf77 | |||
daeb3e5187 | |||
1fd1a3a456 | |||
30ac2d220c | |||
ade7bde813 | |||
cba3e100a0 | |||
664d8d3573 | |||
d5ce509e3a | |||
2f10d19c98 | |||
4c787af26d | |||
8136170431 | |||
007916c2c1 | |||
208ffdc1da | |||
4468dc835c | |||
90a2352337 | |||
0a9d14fcb3 | |||
7863fb1087 | |||
072d2a919d | |||
ccbdc9f6d8 | |||
0f5ea16605 | |||
1cd70d7505 | |||
b0775b3f1e | |||
2894668b3e | |||
1096e653b0 | |||
9777d755d5 | |||
58529aa0b2 | |||
64b6c02a22 | |||
0780300fb3 | |||
b9106b633b | |||
23dfaa2933 | |||
cfd2cc4970 | |||
710349768f | |||
f4bd78b86d | |||
ddb7e4e179 | |||
00601f1835 | |||
c31225fdcf | |||
16b99ed0ba | |||
3b6d340603 | |||
99aea0c71c | |||
023e244958 | |||
659d890ecf | |||
8e9ed14b89 | |||
f4bf7316fe | |||
0527f9bf0d | |||
055edd886d | |||
5e70d4121a | |||
f9b5d8bc5e | |||
2917c045fb | |||
6e6ef862c5 | |||
a7fdca05c6 | |||
ddc33dc74a | |||
a562f492e3 | |||
58f0d0b945 | |||
67d1249b2b | |||
66e5e42fb1 | |||
1f01b6438f | |||
bea7ec33c1 | |||
b5561f35b9 | |||
b796cda060 | |||
4c308b7f2f | |||
d50eb9b41b | |||
9168301369 | |||
e8d930f659 | |||
aef88aa03e | |||
ec4370069a | |||
c79ece2b21 | |||
99076af18b | |||
a0e3ad2b70 | |||
e89e734ca2 | |||
9945241b77 | |||
215ed141e7 | |||
f189ee67a1 | |||
babc7d3baf | |||
8f4807020f | |||
31e1410191 | |||
24d7227e27 | |||
c130ca1bc6 | |||
4db960c0a6 | |||
d13ce2aec9 | |||
5e957ecda6 | |||
17a265b197 | |||
3fabc8e1e6 | |||
517ef7cde7 | |||
ad14b763f9 | |||
f74694d5a3 | |||
1ea39abcff | |||
7402589775 | |||
e0cd5a714a | |||
c6eea5de6b | |||
809416e3f0 | |||
040d812343 | |||
72465e6724 | |||
ab480856a5 | |||
6ae497eedc | |||
421bc828ef | |||
ed65886ae5 | |||
8c7e2dbdf9 | |||
afb4209f10 | |||
1d8775d237 | |||
8787ec9fe8 | |||
1f810cd26a | |||
f4d7d19370 | |||
e616b2e247 | |||
2a39332d51 | |||
3c6b10c6b2 | |||
2a9226a55c | |||
3d65fd7cc4 | |||
36ddbfdc85 | |||
76292ef10c | |||
9ae2e528c5 | |||
2849e28c2b | |||
9d0e52b94d | |||
731f5f8523 | |||
9d6d43ee55 | |||
f9e99048c4 | |||
e1df8d14b4 | |||
b9419e0f36 | |||
e03c354e89 | |||
2e44e4d33c | |||
5cbaabeeab | |||
d64e381085 | |||
41306aa7e0 | |||
0bb2e47c98 | |||
ef660be285 | |||
4bac90a3b2 | |||
4182fc203e | |||
10e36c4233 | |||
bef397228f | |||
5cf47767d7 | |||
8f2d2535dc | |||
2aae8e6382 | |||
ba12b0de0d | |||
3552d03f6c | |||
8d5165c449 | |||
d8027656b5 | |||
4f57c5d56e | |||
2c5c81815a | |||
b97bfe9297 | |||
db07657e40 | |||
2d98d0fcc2 | |||
e6f6f17c6d | |||
166a927c20 | |||
625fe8866c | |||
69e7aa9fc9 | |||
a775cfe177 | |||
9e4a2ab824 | |||
24aa1f312a | |||
cde56741fb | |||
bbe694a622 | |||
7e575a718b | |||
ea9ca8b4ed | |||
0fe2884397 | |||
2982a2c963 | |||
6a43e1a64d | |||
3b5172a8fa | |||
be32aeee70 | |||
adcc74ab8d | |||
8acced56b2 | |||
f823c7cb5d | |||
26e6516626 | |||
5979e0cd0c | |||
3ba1bfc369 | |||
efa0e6eb62 | |||
159b4bd7dc | |||
2611c9525e | |||
0353eb4a12 | |||
92c4097f8d | |||
a909c60f05 | |||
56a9eab7eb | |||
7221eb7f39 | |||
b0b0482d71 | |||
49ab559992 | |||
3dd21c635a | |||
835bbb2e44 | |||
2ee2370a71 | |||
54dd65cfe1 | |||
b004aacd69 | |||
48b7b415e2 | |||
544cea95e1 | |||
8aa2632661 | |||
5419e8ae9d | |||
d4d28ab796 | |||
b8db928c58 | |||
bf45a5860e | |||
ca543fc8af | |||
57cf805e12 | |||
1ae9157985 | |||
206a6ae6c9 | |||
82ac590412 | |||
9a274128ce | |||
5664ee7bda | |||
9a56665c6b | |||
8044fb2db0 | |||
3a59ab9f14 | |||
f609a4f26a | |||
80463d12fb | |||
cef05d3553 | |||
5879b0df99 | |||
95cd9dd2b2 | |||
424d5611a5 | |||
9bff68a4f6 | |||
a9bdc655c1 | |||
9b617de6f0 | |||
771270d526 | |||
26d1307476 | |||
86707b9972 | |||
52cb865c5c | |||
3ea027a136 | |||
00469de93e | |||
9bc4e6794d | |||
429127793f | |||
75cb3fcc5f | |||
f0e87da830 | |||
c5639cd9fa | |||
95d4922e44 | |||
bdd52f0111 | |||
7bd07cb351 | |||
249afc5df4 | |||
d7af461173 | |||
b17e9f4ed0 | |||
6862734580 | |||
9e1f645428 | |||
c4818d79f3 | |||
d1a78a58cd | |||
65d0b5b9d9 | |||
614bc2a943 | |||
27b06358ea | |||
e56c01d0e2 | |||
ececca7ad2 | |||
e9cc417fd5 | |||
81a7d17b33 | |||
9382dd6d55 | |||
7aa2a57434 | |||
9b88ea5b60 | |||
8bfcea8054 | |||
f3d2be7a56 | |||
be31182969 | |||
b543063749 | |||
ce0060e6b0 | |||
35b12fe5ec | |||
6ac26094da | |||
8c6a0f68d4 | |||
f5d6672ccf | |||
db06edc5d3 | |||
568927349d | |||
4f812a7f34 | |||
38fc42d352 | |||
b4c5693ac6 | |||
79000aa5e0 | |||
2415381682 | |||
b499e7c682 | |||
d8cde2ae89 | |||
ddc00014be | |||
9ffa3e55c2 | |||
45fe3be83e | |||
dd6fe6a04a | |||
e76b38882c | |||
11bdab7e61 | |||
3d682fe957 | |||
a43e66ef92 | |||
3be7996e79 | |||
5041a4ffa3 | |||
b16b3c0b7f | |||
852ec3f9a0 | |||
dd7b7311b3 | |||
9364bad625 | |||
6fc5244439 | |||
8e1112c1dd | |||
9d1cb1bfaf | |||
216d7d035f | |||
ead6fbdf9c | |||
5b616770df | |||
23a5c5dc09 | |||
74656bf976 | |||
d8a2e0e9a3 | |||
046e46b962 | |||
ec08e4bc6d | |||
05e07ddf5c | |||
757d7479af | |||
440feaf74a | |||
22c50185b5 | |||
3a2c7900d6 | |||
fa8629300f | |||
37dc226996 | |||
4e1f94026c | |||
d27263af97 | |||
215f1af1da |
5
.githooks/pre-commit
Executable file
5
.githooks/pre-commit
Executable file
@ -0,0 +1,5 @@
|
|||||||
|
#!/usr/bin/env nu
|
||||||
|
|
||||||
|
use ../toolkit.nu fmt
|
||||||
|
|
||||||
|
fmt --check --verbose
|
6
.githooks/pre-push
Executable file
6
.githooks/pre-push
Executable file
@ -0,0 +1,6 @@
|
|||||||
|
#!/usr/bin/env nu
|
||||||
|
|
||||||
|
use ../toolkit.nu [fmt, clippy]
|
||||||
|
|
||||||
|
fmt --check --verbose
|
||||||
|
clippy --verbose
|
1
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
1
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@ -1,5 +1,6 @@
|
|||||||
name: Bug Report
|
name: Bug Report
|
||||||
description: Create a report to help us improve
|
description: Create a report to help us improve
|
||||||
|
labels: ["needs-triage"]
|
||||||
body:
|
body:
|
||||||
- type: textarea
|
- type: textarea
|
||||||
id: description
|
id: description
|
||||||
|
2
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
2
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
@ -1,6 +1,6 @@
|
|||||||
name: Feature Request
|
name: Feature Request
|
||||||
description: "When you want a new feature for something that doesn't already exist"
|
description: "When you want a new feature for something that doesn't already exist"
|
||||||
labels: "enhancement"
|
labels: ["needs-triage", "enhancement"]
|
||||||
body:
|
body:
|
||||||
- type: textarea
|
- type: textarea
|
||||||
id: problem
|
id: problem
|
||||||
|
11
.github/ISSUE_TEMPLATE/standard-library-bug-or-feature-report.md
vendored
Normal file
11
.github/ISSUE_TEMPLATE/standard-library-bug-or-feature-report.md
vendored
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
---
|
||||||
|
name: standard library bug or feature report
|
||||||
|
about: Used to submit issues related to the nu standard library
|
||||||
|
title: ''
|
||||||
|
labels: ['needs-triage', 'std-library']
|
||||||
|
assignees: ''
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Describe the bug or feature**
|
||||||
|
A clear and concise description of what the bug is.
|
20
.github/dependabot.yml
vendored
Normal file
20
.github/dependabot.yml
vendored
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
# To get started with Dependabot version updates, you'll need to specify which
|
||||||
|
# package ecosystems to update and where the package manifests are located.
|
||||||
|
# Please see the documentation for all configuration options:
|
||||||
|
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
|
||||||
|
|
||||||
|
# docs
|
||||||
|
# https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
|
||||||
|
version: 2
|
||||||
|
updates:
|
||||||
|
- package-ecosystem: "cargo"
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
|
ignore:
|
||||||
|
- dependency-name: "*"
|
||||||
|
update-types: ["version-update:semver-patch"]
|
||||||
|
- package-ecosystem: "github-actions"
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
26
.github/pull_request_template.md
vendored
26
.github/pull_request_template.md
vendored
@ -1,24 +1,32 @@
|
|||||||
|
|
||||||
# Description
|
# Description
|
||||||
|
<!--
|
||||||
|
Thank you for improving Nushell. Please, check our [contributing guide](../CONTRIBUTING.md) and talk to the core team before making major changes.
|
||||||
|
|
||||||
_(Thank you for improving Nushell. Please, check our [contributing guide](../CONTRIBUTING.md) and talk to the core team before making major changes.)_
|
Description of your pull request goes here. **Provide examples and/or screenshots** if your changes affect the user experience.
|
||||||
|
-->
|
||||||
_(Description of your pull request goes here. **Provide examples and/or screenshots** if your changes affect the user experience.)_
|
|
||||||
|
|
||||||
# User-Facing Changes
|
# User-Facing Changes
|
||||||
|
<!-- List of all changes that impact the user experience here. This helps us keep track of breaking changes. -->
|
||||||
_(List of all changes that impact the user experience here. This helps us keep track of breaking changes.)_
|
|
||||||
|
|
||||||
# Tests + Formatting
|
# Tests + Formatting
|
||||||
|
<!--
|
||||||
Don't forget to add tests that cover your changes.
|
Don't forget to add tests that cover your changes.
|
||||||
|
|
||||||
Make sure you've run and fixed any issues with these commands:
|
Make sure you've run and fixed any issues with these commands:
|
||||||
|
|
||||||
- `cargo fmt --all -- --check` to check standard code formatting (`cargo fmt --all` applies these changes)
|
- `cargo fmt --all -- --check` to check standard code formatting (`cargo fmt --all` applies these changes)
|
||||||
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect` to check that you're using the standard code style
|
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect -A clippy::result_large_err` to check that you're using the standard code style
|
||||||
- `cargo test --workspace` to check that all tests pass
|
- `cargo test --workspace` to check that all tests pass
|
||||||
|
- `cargo run -- crates/nu-std/tests/run.nu` to run the tests for the standard library
|
||||||
|
|
||||||
|
> **Note**
|
||||||
|
> from `nushell` you can also use the `toolkit` as follows
|
||||||
|
> ```bash
|
||||||
|
> use toolkit.nu # or use an `env_change` hook to activate it automatically
|
||||||
|
> toolkit check pr
|
||||||
|
> ```
|
||||||
|
-->
|
||||||
|
|
||||||
# After Submitting
|
# After Submitting
|
||||||
|
<!-- If your PR had any user-facing changes, update [the documentation](https://github.com/nushell/nushell.github.io) after the PR is merged, if necessary. This will help us keep the docs up to date. -->
|
||||||
If your PR had any user-facing changes, update [the documentation](https://github.com/nushell/nushell.github.io) after the PR is merged, if necessary. This will help us keep the docs up to date.
|
|
||||||
|
93
.github/workflows/ci.yml
vendored
93
.github/workflows/ci.yml
vendored
@ -15,8 +15,22 @@ jobs:
|
|||||||
# builds to link against a too-new-for-many-Linux-installs glibc version. Consider
|
# builds to link against a too-new-for-many-Linux-installs glibc version. Consider
|
||||||
# revisiting this when 20.04 is closer to EOL (April 2025)
|
# revisiting this when 20.04 is closer to EOL (April 2025)
|
||||||
platform: [windows-latest, macos-latest, ubuntu-20.04]
|
platform: [windows-latest, macos-latest, ubuntu-20.04]
|
||||||
|
style: [default, dataframe]
|
||||||
rust:
|
rust:
|
||||||
- stable
|
- stable
|
||||||
|
include:
|
||||||
|
- style: default
|
||||||
|
flags: ""
|
||||||
|
- style: dataframe
|
||||||
|
flags: "--features=dataframe "
|
||||||
|
exclude:
|
||||||
|
# only test dataframes on Ubuntu (the fastest platform)
|
||||||
|
- platform: windows-latest
|
||||||
|
style: dataframe
|
||||||
|
- platform: macos-latest
|
||||||
|
style: dataframe
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
runs-on: ${{ matrix.platform }}
|
runs-on: ${{ matrix.platform }}
|
||||||
env:
|
env:
|
||||||
@ -26,13 +40,13 @@ jobs:
|
|||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
|
|
||||||
- name: Setup Rust toolchain and cache
|
- name: Setup Rust toolchain and cache
|
||||||
uses: actions-rust-lang/setup-rust-toolchain@v1.3.4
|
uses: actions-rust-lang/setup-rust-toolchain@v1.4.4
|
||||||
|
|
||||||
- name: cargo fmt
|
- name: cargo fmt
|
||||||
run: cargo fmt --all -- --check
|
run: cargo fmt --all -- --check
|
||||||
|
|
||||||
- name: Clippy
|
- name: Clippy
|
||||||
run: cargo clippy --workspace --exclude nu_plugin_* -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect
|
run: cargo clippy --workspace ${{ matrix.flags }}--exclude nu_plugin_* -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect -A clippy::result_large_err
|
||||||
|
|
||||||
nu-tests:
|
nu-tests:
|
||||||
env:
|
env:
|
||||||
@ -63,14 +77,14 @@ jobs:
|
|||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
|
|
||||||
- name: Setup Rust toolchain and cache
|
- name: Setup Rust toolchain and cache
|
||||||
uses: actions-rust-lang/setup-rust-toolchain@v1.3.4
|
uses: actions-rust-lang/setup-rust-toolchain@v1.4.4
|
||||||
|
|
||||||
- name: Tests
|
- name: Tests
|
||||||
run: cargo test --workspace --profile ci --exclude nu_plugin_* ${{ matrix.flags }}
|
run: cargo test --workspace --profile ci --exclude nu_plugin_* ${{ matrix.flags }}
|
||||||
|
|
||||||
python-virtualenv:
|
std-lib-and-python-virtualenv:
|
||||||
env:
|
env:
|
||||||
NUSHELL_CARGO_TARGET: ci
|
NU_LOG_LEVEL: DEBUG
|
||||||
|
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: true
|
fail-fast: true
|
||||||
@ -87,10 +101,22 @@ jobs:
|
|||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
|
|
||||||
- name: Setup Rust toolchain and cache
|
- name: Setup Rust toolchain and cache
|
||||||
uses: actions-rust-lang/setup-rust-toolchain@v1.3.4
|
uses: actions-rust-lang/setup-rust-toolchain@v1.4.4
|
||||||
|
|
||||||
- name: Install Nushell
|
- name: Install Nushell
|
||||||
run: cargo install --locked --path=. --profile ci --no-default-features
|
# prior to [*standard library: bring the tests into the main CI*](#8525)
|
||||||
|
# there was a `--profile ci` here in the `cargo install`, as well as
|
||||||
|
# `NUSHELL_CARGO_TARGET: ci` in the prelude above.
|
||||||
|
#
|
||||||
|
# this caused a "stackoverflow" error in the CI on windows,
|
||||||
|
# see [this failing job](https://github.com/nushell/nushell/actions/runs/4512034615/jobs/7944945590)
|
||||||
|
#
|
||||||
|
# the CI profile has been removed in 00b820de9021227d1910a9ea388297ee7aee308e
|
||||||
|
# as part of #8525.
|
||||||
|
run: cargo install --path . --locked --no-default-features
|
||||||
|
|
||||||
|
- name: Standard library tests
|
||||||
|
run: nu -c 'use std; std run-tests --path crates/nu-std'
|
||||||
|
|
||||||
- name: Setup Python
|
- name: Setup Python
|
||||||
uses: actions/setup-python@v4
|
uses: actions/setup-python@v4
|
||||||
@ -99,12 +125,20 @@ jobs:
|
|||||||
|
|
||||||
- run: python -m pip install tox
|
- run: python -m pip install tox
|
||||||
|
|
||||||
|
# Get only the latest tagged version for stability reasons
|
||||||
- name: Install virtualenv
|
- name: Install virtualenv
|
||||||
run: git clone https://github.com/pypa/virtualenv.git
|
run: git clone https://github.com/pypa/virtualenv.git
|
||||||
shell: bash
|
shell: bash
|
||||||
|
|
||||||
- name: Test Nushell in virtualenv
|
- name: Test Nushell in virtualenv
|
||||||
run: cd virtualenv && tox -e ${{ matrix.py }} -- -k nushell
|
run: |
|
||||||
|
cd virtualenv
|
||||||
|
# if we encounter problems with bleeding edge tests pin to the latest tag
|
||||||
|
# git checkout $(git describe --tags | cut -d - -f 1)
|
||||||
|
# We need to disable failing on coverage levels.
|
||||||
|
nu -c "open pyproject.toml | upsert tool.coverage.report.fail_under 1 | save patchproject.toml"
|
||||||
|
mv patchproject.toml pyproject.toml
|
||||||
|
tox -e ${{ matrix.py }} -- -k nushell
|
||||||
shell: bash
|
shell: bash
|
||||||
|
|
||||||
# Build+test plugins on their own, without the rest of Nu. This helps with CI parallelization and
|
# Build+test plugins on their own, without the rest of Nu. This helps with CI parallelization and
|
||||||
@ -126,10 +160,49 @@ jobs:
|
|||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
|
|
||||||
- name: Setup Rust toolchain and cache
|
- name: Setup Rust toolchain and cache
|
||||||
uses: actions-rust-lang/setup-rust-toolchain@v1.3.4
|
uses: actions-rust-lang/setup-rust-toolchain@v1.4.4
|
||||||
|
|
||||||
- name: Clippy
|
- name: Clippy
|
||||||
run: cargo clippy --package nu_plugin_* ${{ matrix.flags }} -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect
|
run: cargo clippy --package nu_plugin_* ${{ matrix.flags }} -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect -A clippy::result_large_err
|
||||||
|
|
||||||
- name: Tests
|
- name: Tests
|
||||||
run: cargo test --profile ci --package nu_plugin_*
|
run: cargo test --profile ci --package nu_plugin_*
|
||||||
|
|
||||||
|
|
||||||
|
nu-coverage:
|
||||||
|
if: false
|
||||||
|
env:
|
||||||
|
NUSHELL_CARGO_TARGET: ci
|
||||||
|
|
||||||
|
strategy:
|
||||||
|
fail-fast: true
|
||||||
|
matrix:
|
||||||
|
# disabled mac due to problems with merging coverage and similarity to linux
|
||||||
|
# disabled windows due to running out of disk space when having too many crates or tests
|
||||||
|
platform: [ubuntu-20.04] # windows-latest
|
||||||
|
rust:
|
||||||
|
- stable
|
||||||
|
|
||||||
|
runs-on: ${{ matrix.platform }}
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Setup Rust toolchain and cache
|
||||||
|
uses: actions-rust-lang/setup-rust-toolchain@v1.4.4
|
||||||
|
- name: Install cargo-llvm-cov
|
||||||
|
uses: taiki-e/install-action@cargo-llvm-cov
|
||||||
|
|
||||||
|
- name: Tests
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
source <(cargo llvm-cov show-env --export-prefix) # Set the environment variables needed to get coverage.
|
||||||
|
cargo llvm-cov clean --workspace # Remove artifacts that may affect the coverage results.
|
||||||
|
cargo build --workspace --profile ci
|
||||||
|
cargo test --workspace --profile ci
|
||||||
|
cargo llvm-cov report --profile ci --lcov --output-path lcov.info
|
||||||
|
|
||||||
|
- name: Upload coverage reports to Codecov with GitHub Action
|
||||||
|
uses: codecov/codecov-action@v3
|
||||||
|
with:
|
||||||
|
files: lcov.info
|
||||||
|
41
.github/workflows/manual.yml
vendored
41
.github/workflows/manual.yml
vendored
@ -1,41 +0,0 @@
|
|||||||
# This is a basic workflow that is manually triggered
|
|
||||||
# Don't run it unless you know what you are doing
|
|
||||||
|
|
||||||
name: Manual Workflow for Winget Submission
|
|
||||||
|
|
||||||
# Controls when the action will run. Workflow runs when manually triggered using the UI
|
|
||||||
# or API.
|
|
||||||
on:
|
|
||||||
workflow_dispatch:
|
|
||||||
# Inputs the workflow accepts.
|
|
||||||
inputs:
|
|
||||||
ver:
|
|
||||||
# Friendly description to be shown in the UI instead of 'ver'
|
|
||||||
description: 'The nushell version to release'
|
|
||||||
# Default value if no value is explicitly provided
|
|
||||||
default: '0.66.0'
|
|
||||||
# Input has to be provided for the workflow to run
|
|
||||||
required: true
|
|
||||||
uri:
|
|
||||||
# Friendly description to be shown in the UI instead of 'uri'
|
|
||||||
description: 'The nushell windows .msi package URI to publish'
|
|
||||||
# Default value if no value is explicitly provided
|
|
||||||
default: 'https://github.com/nushell/nushell/releases/download/0.66.0/nu-0.66.0-x86_64-pc-windows-msvc.msi'
|
|
||||||
# Input has to be provided for the workflow to run
|
|
||||||
required: true
|
|
||||||
|
|
||||||
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
|
|
||||||
jobs:
|
|
||||||
# This workflow contains a single job
|
|
||||||
rls-winget-pkg:
|
|
||||||
name: Publish winget package manually
|
|
||||||
# The type of runner that the job will run on
|
|
||||||
runs-on: windows-latest
|
|
||||||
|
|
||||||
# Steps represent a sequence of tasks that will be executed as part of the job
|
|
||||||
steps:
|
|
||||||
# Runs commands using the runners shell
|
|
||||||
- name: Submit package to Windows Package Manager Community Repository Manually
|
|
||||||
run: |
|
|
||||||
iwr https://github.com/microsoft/winget-create/releases/download/v1.0.4.0/wingetcreate.exe -OutFile wingetcreate.exe
|
|
||||||
.\wingetcreate.exe update Nushell.Nushell -s -v ${{ github.event.inputs.ver }} -u ${{ github.event.inputs.uri }} -t ${{ secrets.NUSHELL_PAT }}
|
|
108
.github/workflows/release-pkg.nu
vendored
108
.github/workflows/release-pkg.nu
vendored
@ -6,19 +6,38 @@
|
|||||||
# REF:
|
# REF:
|
||||||
# 1. https://github.com/volks73/cargo-wix
|
# 1. https://github.com/volks73/cargo-wix
|
||||||
|
|
||||||
|
# Instructions for manually creating an MSI for Winget Releases when they fail
|
||||||
# Added 2022-11-29 when Windows packaging wouldn't work
|
# Added 2022-11-29 when Windows packaging wouldn't work
|
||||||
# because softprops/action-gh-release was broken
|
# Updated again on 2023-02-23 because msis are still failing validation
|
||||||
# To run this manual for windows
|
# To run this manual for windows here are the steps I take
|
||||||
# let-env TARGET = 'x86_64-pc-windows-msvc'
|
# checkout the release you want to publish
|
||||||
# let-env TARGET_RUSTFLAGS = ''
|
# 1. git checkout 0.76.0
|
||||||
# let-env GITHUB_WORKSPACE = 'C:\Users\dschroeder\source\repos\forks\nushell'
|
# unset CARGO_TARGET_DIR if set (I have to do this in the parent shell to get it to work)
|
||||||
# Pass 1 let-env _EXTRA_ = 'bin'
|
# 2. $env:CARGO_TARGET_DIR = ""
|
||||||
# Pass 2 let-env _EXTRA_ = 'msi'
|
# 2. hide-env CARGO_TARGET_DIR
|
||||||
|
# 3. let-env TARGET = 'x86_64-pc-windows-msvc'
|
||||||
|
# 4. let-env TARGET_RUSTFLAGS = ''
|
||||||
|
# 5. let-env GITHUB_WORKSPACE = 'C:\Users\dschroeder\source\repos\forks\nushell'
|
||||||
|
# 6. let-env GITHUB_OUTPUT = 'C:\Users\dschroeder\source\repos\forks\nushell\output\out.txt'
|
||||||
|
# 7. let-env OS = 'windows-latest'
|
||||||
# make sure 7z.exe is in your path https://www.7-zip.org/download.html
|
# make sure 7z.exe is in your path https://www.7-zip.org/download.html
|
||||||
|
# 8. let-env Path = ($env.Path | append 'c:\apps\7-zip')
|
||||||
# make sure aria2c.exe is in your path https://github.com/aria2/aria2
|
# make sure aria2c.exe is in your path https://github.com/aria2/aria2
|
||||||
|
# 9. let-env Path = ($env.Path | append 'c:\path\to\aria2c')
|
||||||
# make sure you have the wixtools installed https://wixtoolset.org/
|
# make sure you have the wixtools installed https://wixtoolset.org/
|
||||||
# set os below like this because it's what github's runner is named
|
# 10. let-env Path = ($env.Path | append 'C:\Users\dschroeder\AppData\Local\tauri\WixTools')
|
||||||
# let os = 'windows-latest'
|
# You need to run the release-pkg twice. The first pass, with _EXTRA_ as 'bin', makes the output
|
||||||
|
# folder and builds everything. The second pass, that generates the msi file, with _EXTRA_ as 'msi'
|
||||||
|
# 11. let-env _EXTRA_ = 'bin'
|
||||||
|
# 12. source .github\workflows\release-pkg.nu
|
||||||
|
# 13. cd ..
|
||||||
|
# 14. let-env _EXTRA_ = 'msi'
|
||||||
|
# 15. source .github\workflows\release-pkg.nu
|
||||||
|
# After msi is generated, you have to update winget-pkgs repo, you'll need to patch the release
|
||||||
|
# by deleting the existing msi and uploading this new msi. Then you'll need to update the hash
|
||||||
|
# on the winget-pkgs PR. To generate the hash, run this command
|
||||||
|
# 16. open target\wix\nu-0.74.0-x86_64-pc-windows-msvc.msi | hash sha256
|
||||||
|
# Then, just take the output and put it in the winget-pkgs PR for the hash on the msi
|
||||||
|
|
||||||
|
|
||||||
# The main binary file to be released
|
# The main binary file to be released
|
||||||
@ -31,17 +50,17 @@ let flags = $env.TARGET_RUSTFLAGS
|
|||||||
let dist = $'($env.GITHUB_WORKSPACE)/output'
|
let dist = $'($env.GITHUB_WORKSPACE)/output'
|
||||||
let version = (open Cargo.toml | get package.version)
|
let version = (open Cargo.toml | get package.version)
|
||||||
|
|
||||||
$'Debugging info:'
|
print $'Debugging info:'
|
||||||
print { version: $version, bin: $bin, os: $os, target: $target, src: $src, flags: $flags, dist: $dist }; hr-line -b
|
print { version: $version, bin: $bin, os: $os, target: $target, src: $src, flags: $flags, dist: $dist }; hr-line -b
|
||||||
|
|
||||||
# $env
|
# $env
|
||||||
|
|
||||||
let USE_UBUNTU = 'ubuntu-20.04'
|
let USE_UBUNTU = 'ubuntu-20.04'
|
||||||
|
|
||||||
$'(char nl)Packaging ($bin) v($version) for ($target) in ($src)...'; hr-line -b
|
print $'(char nl)Packaging ($bin) v($version) for ($target) in ($src)...'; hr-line -b
|
||||||
if not ('Cargo.lock' | path exists) { cargo generate-lockfile }
|
if not ('Cargo.lock' | path exists) { cargo generate-lockfile }
|
||||||
|
|
||||||
$'Start building ($bin)...'; hr-line
|
print $'Start building ($bin)...'; hr-line
|
||||||
|
|
||||||
# ----------------------------------------------------------------------------
|
# ----------------------------------------------------------------------------
|
||||||
# Build for Ubuntu and macOS
|
# Build for Ubuntu and macOS
|
||||||
@ -51,23 +70,18 @@ if $os in [$USE_UBUNTU, 'macos-latest'] {
|
|||||||
sudo apt update
|
sudo apt update
|
||||||
sudo apt-get install libxcb-composite0-dev -y
|
sudo apt-get install libxcb-composite0-dev -y
|
||||||
}
|
}
|
||||||
if $target == 'aarch64-unknown-linux-gnu' {
|
match $target {
|
||||||
sudo apt-get install gcc-aarch64-linux-gnu -y
|
'aarch64-unknown-linux-gnu' => {
|
||||||
let-env CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER = 'aarch64-linux-gnu-gcc'
|
sudo apt-get install gcc-aarch64-linux-gnu -y
|
||||||
cargo-build-nu $flags
|
let-env CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER = 'aarch64-linux-gnu-gcc'
|
||||||
} else if $target == 'armv7-unknown-linux-gnueabihf' {
|
cargo-build-nu $flags
|
||||||
sudo apt-get install pkg-config gcc-arm-linux-gnueabihf -y
|
}
|
||||||
let-env CARGO_TARGET_ARMV7_UNKNOWN_LINUX_GNUEABIHF_LINKER = 'arm-linux-gnueabihf-gcc'
|
_ => {
|
||||||
cargo-build-nu $flags
|
# musl-tools to fix 'Failed to find tool. Is `musl-gcc` installed?'
|
||||||
} else if $target == 'riscv64gc-unknown-linux-gnu' {
|
# Actually just for x86_64-unknown-linux-musl target
|
||||||
sudo apt-get install gcc-riscv64-linux-gnu -y
|
if $os == $USE_UBUNTU { sudo apt install musl-tools -y }
|
||||||
let-env CARGO_TARGET_RISCV64GC_UNKNOWN_LINUX_GNU_LINKER = 'riscv64-linux-gnu-gcc'
|
cargo-build-nu $flags
|
||||||
cargo-build-nu $flags
|
}
|
||||||
} else {
|
|
||||||
# musl-tools to fix 'Failed to find tool. Is `musl-gcc` installed?'
|
|
||||||
# Actually just for x86_64-unknown-linux-musl target
|
|
||||||
if $os == $USE_UBUNTU { sudo apt install musl-tools -y }
|
|
||||||
cargo-build-nu $flags
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -75,6 +89,7 @@ if $os in [$USE_UBUNTU, 'macos-latest'] {
|
|||||||
# Build for Windows without static-link-openssl feature
|
# Build for Windows without static-link-openssl feature
|
||||||
# ----------------------------------------------------------------------------
|
# ----------------------------------------------------------------------------
|
||||||
if $os in ['windows-latest'] {
|
if $os in ['windows-latest'] {
|
||||||
|
# let-env CARGO_BUILD_TARGET = $target
|
||||||
if ($flags | str trim | is-empty) {
|
if ($flags | str trim | is-empty) {
|
||||||
cargo build --release --all --target $target
|
cargo build --release --all --target $target
|
||||||
} else {
|
} else {
|
||||||
@ -88,31 +103,36 @@ if $os in ['windows-latest'] {
|
|||||||
let suffix = if $os == 'windows-latest' { '.exe' }
|
let suffix = if $os == 'windows-latest' { '.exe' }
|
||||||
# nu, nu_plugin_* were all included
|
# nu, nu_plugin_* were all included
|
||||||
let executable = $'target/($target)/release/($bin)*($suffix)'
|
let executable = $'target/($target)/release/($bin)*($suffix)'
|
||||||
$'Current executable file: ($executable)'
|
print $'Current executable file: ($executable)'
|
||||||
|
|
||||||
cd $src; mkdir $dist;
|
cd $src; mkdir $dist;
|
||||||
rm -rf $'target/($target)/release/*.d' $'target/($target)/release/nu_pretty_hex*'
|
rm -rf $'target/($target)/release/*.d' $'target/($target)/release/nu_pretty_hex*'
|
||||||
$'(char nl)All executable files:'; hr-line
|
print $'(char nl)All executable files:'; hr-line
|
||||||
ls -f $executable
|
# We have to use `print` here to make sure the command output is displayed
|
||||||
|
print (ls -f $executable); sleep 1sec
|
||||||
|
|
||||||
$'(char nl)Copying release files...'; hr-line
|
print $'(char nl)Copying release files...'; hr-line
|
||||||
cp -v README.release.txt $'($dist)/README.txt'
|
"To use Nu plugins, use the register command to tell Nu where to find the plugin. For example:
|
||||||
|
|
||||||
|
> register ./nu_plugin_query" | save $'($dist)/README.txt'
|
||||||
[LICENSE $executable] | each {|it| cp -rv $it $dist } | flatten
|
[LICENSE $executable] | each {|it| cp -rv $it $dist } | flatten
|
||||||
|
# Sleep a few seconds to make sure the cp process finished successfully
|
||||||
|
sleep 3sec
|
||||||
|
|
||||||
$'(char nl)Check binary release version detail:'; hr-line
|
print $'(char nl)Check binary release version detail:'; hr-line
|
||||||
let ver = if $os == 'windows-latest' {
|
let ver = if $os == 'windows-latest' {
|
||||||
(do -i { ./output/nu.exe -c 'version' }) | str join
|
(do -i { .\output\nu.exe -c 'version' }) | str join
|
||||||
} else {
|
} else {
|
||||||
(do -i { ./output/nu -c 'version' }) | str join
|
(do -i { ./output/nu -c 'version' }) | str join
|
||||||
}
|
}
|
||||||
if ($ver | str trim | is-empty) {
|
if ($ver | str trim | is-empty) {
|
||||||
$'(ansi r)Incompatible nu binary...(ansi reset)'
|
print $'(ansi r)Incompatible nu binary...(ansi reset)'
|
||||||
} else { $ver }
|
} else { print $ver }
|
||||||
|
|
||||||
# ----------------------------------------------------------------------------
|
# ----------------------------------------------------------------------------
|
||||||
# Create a release archive and send it to output for the following steps
|
# Create a release archive and send it to output for the following steps
|
||||||
# ----------------------------------------------------------------------------
|
# ----------------------------------------------------------------------------
|
||||||
cd $dist; $'(char nl)Creating release archive...'; hr-line
|
cd $dist; print $'(char nl)Creating release archive...'; hr-line
|
||||||
if $os in [$USE_UBUNTU, 'macos-latest'] {
|
if $os in [$USE_UBUNTU, 'macos-latest'] {
|
||||||
|
|
||||||
let files = (ls | get name)
|
let files = (ls | get name)
|
||||||
@ -122,7 +142,7 @@ if $os in [$USE_UBUNTU, 'macos-latest'] {
|
|||||||
mkdir $dest
|
mkdir $dest
|
||||||
$files | each {|it| mv $it $dest } | ignore
|
$files | each {|it| mv $it $dest } | ignore
|
||||||
|
|
||||||
$'(char nl)(ansi g)Archive contents:(ansi reset)'; hr-line; ls $dest
|
print $'(char nl)(ansi g)Archive contents:(ansi reset)'; hr-line; ls $dest
|
||||||
|
|
||||||
tar -czf $archive $dest
|
tar -czf $archive $dest
|
||||||
print $'archive: ---> ($archive)'; ls $archive
|
print $'archive: ---> ($archive)'; ls $archive
|
||||||
@ -133,7 +153,7 @@ if $os in [$USE_UBUNTU, 'macos-latest'] {
|
|||||||
|
|
||||||
let releaseStem = $'($bin)-($version)-($target)'
|
let releaseStem = $'($bin)-($version)-($target)'
|
||||||
|
|
||||||
$'(char nl)Download less related stuffs...'; hr-line
|
print $'(char nl)Download less related stuffs...'; hr-line
|
||||||
aria2c https://github.com/jftuga/less-Windows/releases/download/less-v608/less.exe -o less.exe
|
aria2c https://github.com/jftuga/less-Windows/releases/download/less-v608/less.exe -o less.exe
|
||||||
aria2c https://raw.githubusercontent.com/jftuga/less-Windows/master/LICENSE -o LICENSE-for-less.txt
|
aria2c https://raw.githubusercontent.com/jftuga/less-Windows/master/LICENSE -o LICENSE-for-less.txt
|
||||||
|
|
||||||
@ -141,18 +161,18 @@ if $os in [$USE_UBUNTU, 'macos-latest'] {
|
|||||||
if (get-env _EXTRA_) == 'msi' {
|
if (get-env _EXTRA_) == 'msi' {
|
||||||
|
|
||||||
let wixRelease = $'($src)/target/wix/($releaseStem).msi'
|
let wixRelease = $'($src)/target/wix/($releaseStem).msi'
|
||||||
$'(char nl)Start creating Windows msi package...'
|
print $'(char nl)Start creating Windows msi package...'
|
||||||
cd $src; hr-line
|
cd $src; hr-line
|
||||||
# Wix need the binaries be stored in target/release/
|
# Wix need the binaries be stored in target/release/
|
||||||
cp -r $'($dist)/*' target/release/
|
cp -r $'($dist)/*' target/release/
|
||||||
cargo install cargo-wix --version 0.3.3
|
cargo install cargo-wix --version 0.3.4
|
||||||
cargo wix --no-build --nocapture --package nu --output $wixRelease
|
cargo wix --no-build --nocapture --package nu --output $wixRelease
|
||||||
print $'archive: ---> ($wixRelease)';
|
print $'archive: ---> ($wixRelease)';
|
||||||
echo $"archive=($wixRelease)" | save --append $env.GITHUB_OUTPUT
|
echo $"archive=($wixRelease)" | save --append $env.GITHUB_OUTPUT
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
|
|
||||||
$'(char nl)(ansi g)Archive contents:(ansi reset)'; hr-line; ls
|
print $'(char nl)(ansi g)Archive contents:(ansi reset)'; hr-line; ls
|
||||||
let archive = $'($dist)/($releaseStem).zip'
|
let archive = $'($dist)/($releaseStem).zip'
|
||||||
7z a $archive *
|
7z a $archive *
|
||||||
print $'archive: ---> ($archive)';
|
print $'archive: ---> ($archive)';
|
||||||
|
23
.github/workflows/release.yml
vendored
23
.github/workflows/release.yml
vendored
@ -23,11 +23,10 @@ jobs:
|
|||||||
- aarch64-apple-darwin
|
- aarch64-apple-darwin
|
||||||
- x86_64-apple-darwin
|
- x86_64-apple-darwin
|
||||||
- x86_64-pc-windows-msvc
|
- x86_64-pc-windows-msvc
|
||||||
|
- aarch64-pc-windows-msvc
|
||||||
- x86_64-unknown-linux-gnu
|
- x86_64-unknown-linux-gnu
|
||||||
- x86_64-unknown-linux-musl
|
- x86_64-unknown-linux-musl
|
||||||
- aarch64-unknown-linux-gnu
|
- aarch64-unknown-linux-gnu
|
||||||
- armv7-unknown-linux-gnueabihf
|
|
||||||
- riscv64gc-unknown-linux-gnu
|
|
||||||
extra: ['bin']
|
extra: ['bin']
|
||||||
include:
|
include:
|
||||||
- target: aarch64-apple-darwin
|
- target: aarch64-apple-darwin
|
||||||
@ -44,6 +43,14 @@ jobs:
|
|||||||
extra: msi
|
extra: msi
|
||||||
os: windows-latest
|
os: windows-latest
|
||||||
target_rustflags: ''
|
target_rustflags: ''
|
||||||
|
- target: aarch64-pc-windows-msvc
|
||||||
|
extra: 'bin'
|
||||||
|
os: windows-latest
|
||||||
|
target_rustflags: ''
|
||||||
|
- target: aarch64-pc-windows-msvc
|
||||||
|
extra: msi
|
||||||
|
os: windows-latest
|
||||||
|
target_rustflags: ''
|
||||||
- target: x86_64-unknown-linux-gnu
|
- target: x86_64-unknown-linux-gnu
|
||||||
os: ubuntu-20.04
|
os: ubuntu-20.04
|
||||||
target_rustflags: ''
|
target_rustflags: ''
|
||||||
@ -53,29 +60,23 @@ jobs:
|
|||||||
- target: aarch64-unknown-linux-gnu
|
- target: aarch64-unknown-linux-gnu
|
||||||
os: ubuntu-20.04
|
os: ubuntu-20.04
|
||||||
target_rustflags: ''
|
target_rustflags: ''
|
||||||
- target: armv7-unknown-linux-gnueabihf
|
|
||||||
os: ubuntu-20.04
|
|
||||||
target_rustflags: ''
|
|
||||||
- target: riscv64gc-unknown-linux-gnu
|
|
||||||
os: ubuntu-20.04
|
|
||||||
target_rustflags: ''
|
|
||||||
|
|
||||||
runs-on: ${{matrix.os}}
|
runs-on: ${{matrix.os}}
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3.1.0
|
- uses: actions/checkout@v3
|
||||||
|
|
||||||
- name: Update Rust Toolchain Target
|
- name: Update Rust Toolchain Target
|
||||||
run: |
|
run: |
|
||||||
echo "targets = ['${{matrix.target}}']" >> rust-toolchain.toml
|
echo "targets = ['${{matrix.target}}']" >> rust-toolchain.toml
|
||||||
|
|
||||||
- name: Setup Rust toolchain and cache
|
- name: Setup Rust toolchain and cache
|
||||||
uses: actions-rust-lang/setup-rust-toolchain@v1.3.4
|
uses: actions-rust-lang/setup-rust-toolchain@v1.4.4
|
||||||
|
|
||||||
- name: Setup Nushell
|
- name: Setup Nushell
|
||||||
uses: hustcer/setup-nu@v3
|
uses: hustcer/setup-nu@v3
|
||||||
with:
|
with:
|
||||||
version: 0.72.1
|
version: 0.79.0
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
28
.github/workflows/stale.yml
vendored
28
.github/workflows/stale.yml
vendored
@ -1,28 +0,0 @@
|
|||||||
name: 'Close stale issues and PRs'
|
|
||||||
#on: [workflow_dispatch]
|
|
||||||
on:
|
|
||||||
schedule:
|
|
||||||
- cron: '30 1 * * *'
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
issues: write
|
|
||||||
pull-requests: write
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
stale:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/stale@v3
|
|
||||||
with:
|
|
||||||
#debug-only: true
|
|
||||||
ascending: true
|
|
||||||
operations-per-run: 520
|
|
||||||
enable-statistics: true
|
|
||||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
close-issue-message: 'This issue has been marked stale for more than 100000 days without activity. Closing this issue, but if you find that the issue is still valid, please reopen.'
|
|
||||||
close-pr-message: 'This PR has been marked stale for more than 100 days without activity. Closing this PR, but if you are still working on it, please reopen.'
|
|
||||||
days-before-issue-stale: 90
|
|
||||||
days-before-pr-stale: 45
|
|
||||||
days-before-issue-close: 100000
|
|
||||||
days-before-pr-close: 100
|
|
||||||
exempt-issue-labels: 'exempt,keep'
|
|
13
.github/workflows/typos.yml
vendored
Normal file
13
.github/workflows/typos.yml
vendored
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
name: Typos
|
||||||
|
on: [pull_request]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
run:
|
||||||
|
name: Spell Check with Typos
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout Actions Repository
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Check spelling
|
||||||
|
uses: crate-ci/typos@master
|
21
.github/workflows/winget-submission.yml
vendored
21
.github/workflows/winget-submission.yml
vendored
@ -1,9 +1,14 @@
|
|||||||
name: Submit Nushell package to Windows Package Manager Community Repository
|
name: Submit Nushell package to Windows Package Manager Community Repository
|
||||||
|
|
||||||
on:
|
on:
|
||||||
workflow_dispatch:
|
|
||||||
release:
|
release:
|
||||||
types: [published]
|
types: [released]
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
tag_name:
|
||||||
|
description: 'Specific tag name'
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
|
|
||||||
@ -12,8 +17,10 @@ jobs:
|
|||||||
runs-on: windows-latest
|
runs-on: windows-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Submit package to Windows Package Manager Community Repository
|
- name: Submit package to Windows Package Manager Community Repository
|
||||||
run: |
|
uses: vedantmgoyal2009/winget-releaser@v2
|
||||||
iwr https://github.com/microsoft/winget-create/releases/download/v1.0.4.0/wingetcreate.exe -OutFile wingetcreate.exe
|
with:
|
||||||
$github = Get-Content '${{ github.event_path }}' | ConvertFrom-Json
|
identifier: Nushell.Nushell
|
||||||
$installerUrl = $github.release.assets | Where-Object -Property name -match 'windows-msvc.msi' | Select -ExpandProperty browser_download_url -First 1
|
version: ${{ inputs.tag_name || github.event.release.tag_name }}
|
||||||
.\wingetcreate.exe update Nushell.Nushell -s -v $github.release.tag_name -u $installerUrl -t ${{ secrets.NUSHELL_PAT }}
|
release-tag: ${{ inputs.tag_name || github.event.release.tag_name }}
|
||||||
|
token: ${{ secrets.NUSHELL_PAT }}
|
||||||
|
fork-user: fdncred
|
||||||
|
12
.gitignore
vendored
12
.gitignore
vendored
@ -22,6 +22,9 @@ debian/nu/
|
|||||||
# VSCode's IDE items
|
# VSCode's IDE items
|
||||||
.vscode/*
|
.vscode/*
|
||||||
|
|
||||||
|
# JetBrains' Fleet IDE
|
||||||
|
.fleet/*
|
||||||
|
|
||||||
# Visual Studio Extension SourceGear Rust items
|
# Visual Studio Extension SourceGear Rust items
|
||||||
VSWorkspaceSettings.json
|
VSWorkspaceSettings.json
|
||||||
unstable_cargo_features.txt
|
unstable_cargo_features.txt
|
||||||
@ -38,4 +41,11 @@ tarpaulin-report.html
|
|||||||
.vs/*
|
.vs/*
|
||||||
*.rsproj
|
*.rsproj
|
||||||
*.rsproj.user
|
*.rsproj.user
|
||||||
*.sln
|
*.sln
|
||||||
|
|
||||||
|
# direnv
|
||||||
|
.direnv/
|
||||||
|
.envrc
|
||||||
|
|
||||||
|
# pre-commit-hooks
|
||||||
|
.pre-commit-config.yaml
|
||||||
|
12
.typos.toml
Normal file
12
.typos.toml
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
[files]
|
||||||
|
extend-exclude = ["crates/nu-command/tests/commands/table.rs", "*.tsv", "*.json", "*.txt"]
|
||||||
|
|
||||||
|
[default.extend-words]
|
||||||
|
# Ignore false-positives
|
||||||
|
nd = "nd"
|
||||||
|
fo = "fo"
|
||||||
|
ons = "ons"
|
||||||
|
ba = "ba"
|
||||||
|
Plasticos = "Plasticos"
|
||||||
|
IIF = "IIF"
|
||||||
|
numer = "numer"
|
123
CONTRIBUTING.md
123
CONTRIBUTING.md
@ -59,7 +59,12 @@ The most comprehensive test suite we have is the `nu-test-support` crate. For te
|
|||||||
- Run Clippy on Nushell:
|
- Run Clippy on Nushell:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect
|
cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect -A clippy::result_large_err
|
||||||
|
```
|
||||||
|
or via the `toolkit.nu` command:
|
||||||
|
```shell
|
||||||
|
use toolkit.nu clippy
|
||||||
|
clippy
|
||||||
```
|
```
|
||||||
|
|
||||||
- Run all tests:
|
- Run all tests:
|
||||||
@ -68,6 +73,17 @@ The most comprehensive test suite we have is the `nu-test-support` crate. For te
|
|||||||
cargo test --workspace
|
cargo test --workspace
|
||||||
```
|
```
|
||||||
|
|
||||||
|
along with dataframe tests
|
||||||
|
|
||||||
|
```shell
|
||||||
|
cargo test --workspace --features=dataframe
|
||||||
|
```
|
||||||
|
or via the `toolkit.nu` command:
|
||||||
|
```shell
|
||||||
|
use toolkit.nu test
|
||||||
|
test
|
||||||
|
```
|
||||||
|
|
||||||
- Run all tests for a specific command
|
- Run all tests for a specific command
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
@ -79,12 +95,30 @@ The most comprehensive test suite we have is the `nu-test-support` crate. For te
|
|||||||
```shell
|
```shell
|
||||||
cargo fmt --all -- --check
|
cargo fmt --all -- --check
|
||||||
```
|
```
|
||||||
|
or via the `toolkit.nu` command:
|
||||||
|
```shell
|
||||||
|
use toolkit.nu fmt
|
||||||
|
fmt --check
|
||||||
|
```
|
||||||
|
|
||||||
- Format the code in the project
|
- Format the code in the project
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
cargo fmt --all
|
cargo fmt --all
|
||||||
```
|
```
|
||||||
|
or via the `toolkit.nu` command:
|
||||||
|
```shell
|
||||||
|
use toolkit.nu fmt
|
||||||
|
fmt
|
||||||
|
```
|
||||||
|
|
||||||
|
- Set up `git` hooks to check formatting and run `clippy` before committing and pushing:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
use toolkit.nu setup-git-hooks
|
||||||
|
setup-git-hooks
|
||||||
|
```
|
||||||
|
_Unfortunately, this hook isn't available on Windows._
|
||||||
|
|
||||||
### Debugging Tips
|
### Debugging Tips
|
||||||
|
|
||||||
@ -99,3 +133,90 @@ The most comprehensive test suite we have is the `nu-test-support` crate. For te
|
|||||||
cargo run --release -- --log-level trace --log-target file
|
cargo run --release -- --log-level trace --log-target file
|
||||||
open $"($nu.temp-path)/nu-($nu.pid).log"
|
open $"($nu.temp-path)/nu-($nu.pid).log"
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Git etiquette
|
||||||
|
|
||||||
|
As nushell thrives on its broad base of volunteer contributors and maintainers with different backgrounds we have a few guidelines for how we best utilize git and GitHub for our contributions. We strive to balance three goals with those recommendations:
|
||||||
|
|
||||||
|
1. The **volunteer maintainers and contributors** can easily follow the changes you propose, gauge the impact, and come to help you or make a decision.
|
||||||
|
2. **You as a contributor** can focus most of your time on improving the quality of the nushell project and contributing your expertise to the code or documentation.
|
||||||
|
3. Making sure we can trace back *why* decisions were made in the past.
|
||||||
|
This includes discarded approaches. Also we want to quickly identify regressions and fix when something broke.
|
||||||
|
|
||||||
|
### How we merge PRs
|
||||||
|
|
||||||
|
In general the maintainers **squash** all changes of your PR into a single commit when merging.
|
||||||
|
|
||||||
|
This keeps a clean enough linear history, while not forcing you to conform to a too strict style while iterating in your PR or fixing small problems. As an added benefit the commits on the `main` branch are tied to the discussion that happened in the PR through their `#1234` issue number.
|
||||||
|
|
||||||
|
> **Note**
|
||||||
|
> **Pro advice:** In some circumstances, we can agree on rebase-merging a particularly large but connected PR as a series of atomic commits onto the `main` branch to ensure we can more easily revert or bisect particular aspects.
|
||||||
|
|
||||||
|
### A good PR makes a change!
|
||||||
|
|
||||||
|
As a result of this PR-centric strategy and the general goal that the reviewers should easily understand your change, the **PR title and description matters** a great deal!
|
||||||
|
|
||||||
|
Make sure your description is **concise** but contains all relevant information and context.
|
||||||
|
This means demonstrating what changes, ideally through nushell code or output **examples**.
|
||||||
|
Furthermore links to technical documentation or instructions for folks that want to play with your change make the review process much easier.
|
||||||
|
|
||||||
|
> **Note**
|
||||||
|
> Try to follow the suggestions in our PR message template to make sure we can quickly focus on the technical merits and impact on the users.
|
||||||
|
|
||||||
|
#### A PR should limit itself to a single functional change or related set of same changes.
|
||||||
|
|
||||||
|
Mixing different changes in the same PR will make the review process much harder. A PR might get stuck on one aspect while we would actually like to land another change. Furthermore, if we are forced to revert a change, mixing and matching different aspects makes fixing bugs or regressions much harder.
|
||||||
|
|
||||||
|
Thus, please try to **separate out unrelated changes**!
|
||||||
|
**Don't** mix unrelated refactors with a potentially contested change.
|
||||||
|
Stylistic fixes and housekeeping can be bundled up into singular PRs.
|
||||||
|
|
||||||
|
#### Guidelines for the PR title
|
||||||
|
|
||||||
|
The PR title should be concise but contain everything for a contributor to know if they should help out in the review of this particular change.
|
||||||
|
|
||||||
|
**DON'T**
|
||||||
|
- `Update file/in/some/deeply/nested/path.rs`
|
||||||
|
- Why are you making this change?
|
||||||
|
- `Fix 2134`
|
||||||
|
- What has to be fixed?
|
||||||
|
- Hard to follow when not online on GitHub.
|
||||||
|
- ``Ignore `~` expansion``
|
||||||
|
- In what context should this change take effect?
|
||||||
|
- `[feature] refactor the whole parser and also make nushell indentation-sensitive, upgrade to using Cpython. Let me know what you think!`
|
||||||
|
- Be concise
|
||||||
|
- Maybe break up into smaller commits or PRs if the title already appears too long?
|
||||||
|
|
||||||
|
**DO**
|
||||||
|
- Mention the nushell feature or command that is affected.
|
||||||
|
- ``Fix URL parsing in `http get` (issue #1234)``
|
||||||
|
- You can mention the issue number if other context is there.
|
||||||
|
- In general, mention all related issues in the description to crosslink (e.g. `Fixes #1234`, `Closes #6789`)
|
||||||
|
- For internal changes mention the area or symbols affected if it helps to clarify
|
||||||
|
- ``Factor out `quote_string()` from parser to reuse in `explore` ``
|
||||||
|
|
||||||
|
### Review process / Merge conflicts
|
||||||
|
|
||||||
|
> **Note**
|
||||||
|
> Keep in mind that the maintainers are volunteers that need to allocate their attention to several different areas and active PRs. We will try to get back to you as soon as possible.
|
||||||
|
|
||||||
|
You can help us to make the review process a smooth experience:
|
||||||
|
- Testing:
|
||||||
|
- We generally review in detail after all the tests pass. Let us know if there is a problem you want to discuss to fix a test failure or forces us to accept a breaking change.
|
||||||
|
- If you fix a bug, it is highly recommended that you add a test that reproduces the original issue/panic in a minimal form.
|
||||||
|
- In general, added tests help us to understand which assumptions go into a particular addition/change.
|
||||||
|
- Try to also test corner cases where those assumptions might break. This can be more valuable than simply adding many similar tests.
|
||||||
|
- Commit history inside a PR during code review:
|
||||||
|
- Good **atomic commits** can help follow larger changes, but we are not pedantic.
|
||||||
|
- We don't shame fixup commits while you try to figure out a problem. They can help others see what you tried and what didn't work. (see our [squash policy](#how-we-merge-prs))
|
||||||
|
- During active review constant **force pushing** just to amend changes can be confusing!
|
||||||
|
- GitHub's UI presents reviewers with less options to compare diffs
|
||||||
|
- fetched branches for experimentation become invalid!
|
||||||
|
- the notification a maintainer receives has a low signal-to-noise ratio
|
||||||
|
- Git pros *can* use their judgement to rebase/squash to clean up the history *if it aids the understanding* of a larger change during review
|
||||||
|
- Merge conflicts:
|
||||||
|
- In general you should take care of resolving merge conflicts.
|
||||||
|
- Use your judgement whether to `git merge main` or to `git rebase main`
|
||||||
|
- Choose what simplifies having confidence in the conflict resolution and the review. **Merge commits in your branch are OK** in the squash model.
|
||||||
|
- Feel free to notify your reviewers or affected PR authors if your change might cause larger conflicts with another change.
|
||||||
|
- During the rollup of multiple PRs, we may choose to resolve merge conflicts and CI failures ourselves. (Allow maintainers to push to your branch to enable us to do this quickly.)
|
||||||
|
2819
Cargo.lock
generated
2819
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
129
Cargo.toml
129
Cargo.toml
@ -1,16 +1,17 @@
|
|||||||
[package]
|
[package]
|
||||||
authors = ["The Nushell Project Developers"]
|
authors = ["The Nushell Project Developers"]
|
||||||
|
build = "scripts/build.rs"
|
||||||
default-run = "nu"
|
default-run = "nu"
|
||||||
description = "A new type of shell"
|
description = "A new type of shell"
|
||||||
documentation = "https://www.nushell.sh/book/"
|
documentation = "https://www.nushell.sh/book/"
|
||||||
edition = "2018"
|
edition = "2021"
|
||||||
exclude = ["images"]
|
exclude = ["images"]
|
||||||
homepage = "https://www.nushell.sh"
|
homepage = "https://www.nushell.sh"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
name = "nu"
|
name = "nu"
|
||||||
repository = "https://github.com/nushell/nushell"
|
repository = "https://github.com/nushell/nushell"
|
||||||
rust-version = "1.60"
|
rust-version = "1.60"
|
||||||
version = "0.73.0"
|
version = "0.81.0"
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
@ -27,6 +28,9 @@ members = [
|
|||||||
"crates/nu-engine",
|
"crates/nu-engine",
|
||||||
"crates/nu-parser",
|
"crates/nu-parser",
|
||||||
"crates/nu-system",
|
"crates/nu-system",
|
||||||
|
"crates/nu-cmd-extra",
|
||||||
|
"crates/nu-cmd-lang",
|
||||||
|
"crates/nu-cmd-dataframe",
|
||||||
"crates/nu-command",
|
"crates/nu-command",
|
||||||
"crates/nu-protocol",
|
"crates/nu-protocol",
|
||||||
"crates/nu-plugin",
|
"crates/nu-plugin",
|
||||||
@ -35,85 +39,97 @@ members = [
|
|||||||
"crates/nu_plugin_example",
|
"crates/nu_plugin_example",
|
||||||
"crates/nu_plugin_query",
|
"crates/nu_plugin_query",
|
||||||
"crates/nu_plugin_custom_values",
|
"crates/nu_plugin_custom_values",
|
||||||
|
"crates/nu_plugin_formats",
|
||||||
|
"crates/nu-std",
|
||||||
"crates/nu-utils",
|
"crates/nu-utils",
|
||||||
]
|
]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
chrono = { version = "0.4.23", features = ["serde"] }
|
nu-cli = { path = "./crates/nu-cli", version = "0.81.0" }
|
||||||
crossterm = "0.24.0"
|
nu-color-config = { path = "./crates/nu-color-config", version = "0.81.0" }
|
||||||
ctrlc = "3.2.1"
|
nu-cmd-lang = { path = "./crates/nu-cmd-lang", version = "0.81.0" }
|
||||||
log = "0.4"
|
nu-cmd-dataframe = { path = "./crates/nu-cmd-dataframe", version = "0.81.0", optional = true }
|
||||||
miette = { version = "5.1.0", features = ["fancy-no-backtrace"] }
|
nu-command = { path = "./crates/nu-command", version = "0.81.0" }
|
||||||
nu-ansi-term = "0.46.0"
|
nu-engine = { path = "./crates/nu-engine", version = "0.81.0" }
|
||||||
nu-cli = { path="./crates/nu-cli", version = "0.73.0" }
|
nu-json = { path = "./crates/nu-json", version = "0.81.0" }
|
||||||
nu-color-config = { path = "./crates/nu-color-config", version = "0.73.0" }
|
nu-parser = { path = "./crates/nu-parser", version = "0.81.0" }
|
||||||
nu-command = { path="./crates/nu-command", version = "0.73.0" }
|
nu-path = { path = "./crates/nu-path", version = "0.81.0" }
|
||||||
nu-engine = { path="./crates/nu-engine", version = "0.73.0" }
|
nu-plugin = { path = "./crates/nu-plugin", optional = true, version = "0.81.0" }
|
||||||
nu-json = { path="./crates/nu-json", version = "0.73.0" }
|
nu-pretty-hex = { path = "./crates/nu-pretty-hex", version = "0.81.0" }
|
||||||
nu-parser = { path="./crates/nu-parser", version = "0.73.0" }
|
nu-protocol = { path = "./crates/nu-protocol", version = "0.81.0" }
|
||||||
nu-path = { path="./crates/nu-path", version = "0.73.0" }
|
nu-system = { path = "./crates/nu-system", version = "0.81.0" }
|
||||||
nu-plugin = { path = "./crates/nu-plugin", optional = true, version = "0.73.0" }
|
nu-table = { path = "./crates/nu-table", version = "0.81.0" }
|
||||||
nu-pretty-hex = { path = "./crates/nu-pretty-hex", version = "0.73.0" }
|
nu-term-grid = { path = "./crates/nu-term-grid", version = "0.81.0" }
|
||||||
nu-protocol = { path = "./crates/nu-protocol", version = "0.73.0" }
|
nu-std = { path = "./crates/nu-std", version = "0.81.0" }
|
||||||
nu-system = { path = "./crates/nu-system", version = "0.73.0" }
|
nu-utils = { path = "./crates/nu-utils", version = "0.81.0" }
|
||||||
nu-table = { path = "./crates/nu-table", version = "0.73.0" }
|
nu-ansi-term = "0.47.0"
|
||||||
nu-term-grid = { path = "./crates/nu-term-grid", version = "0.73.0" }
|
reedline = { version = "0.20.0", features = ["bashisms", "sqlite"]}
|
||||||
nu-utils = { path = "./crates/nu-utils", version = "0.73.0" }
|
|
||||||
reedline = { version = "0.14.0", features = ["bashisms", "sqlite"]}
|
|
||||||
|
|
||||||
rayon = "1.5.1"
|
crossterm = "0.26"
|
||||||
is_executable = "1.0.1"
|
ctrlc = "3.2"
|
||||||
simplelog = "0.12.0"
|
log = "0.4"
|
||||||
time = "0.3.12"
|
miette = { version = "5.9", features = ["fancy-no-backtrace"] }
|
||||||
|
serde_json = "1.0"
|
||||||
|
simplelog = "0.12"
|
||||||
|
time = "0.3"
|
||||||
|
|
||||||
[target.'cfg(not(target_os = "windows"))'.dependencies]
|
[target.'cfg(not(target_os = "windows"))'.dependencies]
|
||||||
# Our dependencies don't use OpenSSL on Windows
|
# Our dependencies don't use OpenSSL on Windows
|
||||||
openssl = { version = "0.10.38", features = ["vendored"], optional = true }
|
openssl = { version = "0.10", features = ["vendored"], optional = true }
|
||||||
signal-hook = { version = "0.3.14", default-features = false }
|
signal-hook = { version = "0.3", default-features = false }
|
||||||
|
|
||||||
|
|
||||||
[target.'cfg(windows)'.build-dependencies]
|
[target.'cfg(windows)'.build-dependencies]
|
||||||
winres = "0.1"
|
winresource = "0.1"
|
||||||
|
|
||||||
[target.'cfg(target_family = "unix")'.dependencies]
|
[target.'cfg(target_family = "unix")'.dependencies]
|
||||||
nix = { version = "0.25", default-features = false, features = ["signal", "process", "fs", "term"]}
|
nix = { version = "0.26", default-features = false, features = [
|
||||||
|
"signal",
|
||||||
|
"process",
|
||||||
|
"fs",
|
||||||
|
"term",
|
||||||
|
] }
|
||||||
atty = "0.2"
|
atty = "0.2"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
nu-test-support = { path="./crates/nu-test-support", version = "0.73.0" }
|
nu-test-support = { path = "./crates/nu-test-support", version = "0.81.0" }
|
||||||
tempfile = "3.2.0"
|
tempfile = "3.5"
|
||||||
assert_cmd = "2.0.2"
|
assert_cmd = "2.0"
|
||||||
pretty_assertions = "1.0.0"
|
criterion = "0.4"
|
||||||
serial_test = "0.8.0"
|
pretty_assertions = "1.0"
|
||||||
hamcrest2 = "0.3.0"
|
serial_test = "1.0"
|
||||||
rstest = {version = "0.15.0", default-features = false}
|
rstest = { version = "0.17", default-features = false }
|
||||||
itertools = "0.10.3"
|
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
plugin = ["nu-plugin", "nu-cli/plugin", "nu-parser/plugin", "nu-command/plugin", "nu-protocol/plugin", "nu-engine/plugin"]
|
plugin = [
|
||||||
# extra used to be more useful but now it's the same as default. Leaving it in for backcompat with existing build scripts
|
"nu-plugin",
|
||||||
extra = ["default"]
|
"nu-cli/plugin",
|
||||||
|
"nu-parser/plugin",
|
||||||
|
"nu-command/plugin",
|
||||||
|
"nu-protocol/plugin",
|
||||||
|
"nu-engine/plugin",
|
||||||
|
]
|
||||||
default = ["plugin", "which-support", "trash-support", "sqlite"]
|
default = ["plugin", "which-support", "trash-support", "sqlite"]
|
||||||
stable = ["default"]
|
stable = ["default"]
|
||||||
wasi = []
|
wasi = ["nu-cmd-lang/wasi"]
|
||||||
|
|
||||||
# Enable to statically link OpenSSL; otherwise the system version will be used. Not enabled by default because it takes a while to build
|
# Enable to statically link OpenSSL; otherwise the system version will be used. Not enabled by default because it takes a while to build
|
||||||
static-link-openssl = ["dep:openssl"]
|
static-link-openssl = ["dep:openssl", "nu-cmd-lang/static-link-openssl"]
|
||||||
|
|
||||||
# Stable (Default)
|
# Stable (Default)
|
||||||
which-support = ["nu-command/which-support"]
|
which-support = ["nu-command/which-support", "nu-cmd-lang/which-support"]
|
||||||
trash-support = ["nu-command/trash-support"]
|
trash-support = ["nu-command/trash-support", "nu-cmd-lang/trash-support"]
|
||||||
|
|
||||||
# Extra
|
# Extra feature for nushell
|
||||||
|
extra = ["nu-command/extra", "nu-cmd-lang/extra"]
|
||||||
|
|
||||||
# Dataframe feature for nushell
|
# Dataframe feature for nushell
|
||||||
dataframe = ["nu-command/dataframe"]
|
dataframe = ["nu-command/dataframe", "nu-cmd-lang/dataframe"]
|
||||||
|
|
||||||
# SQLite commands for nushell
|
# SQLite commands for nushell
|
||||||
sqlite = ["nu-command/sqlite"]
|
sqlite = ["nu-command/sqlite", "nu-cmd-lang/sqlite"]
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
opt-level = "s" # Optimize for size
|
opt-level = "s" # Optimize for size
|
||||||
strip = "debuginfo"
|
strip = "debuginfo"
|
||||||
lto = "thin"
|
lto = "thin"
|
||||||
|
|
||||||
@ -135,8 +151,17 @@ debug = false
|
|||||||
[[bin]]
|
[[bin]]
|
||||||
name = "nu"
|
name = "nu"
|
||||||
path = "src/main.rs"
|
path = "src/main.rs"
|
||||||
|
bench = false
|
||||||
|
|
||||||
# To use a development version of a dependency please use a global override here
|
# To use a development version of a dependency please use a global override here
|
||||||
# changing versions in each sub-crate of the workspace is tedious
|
# changing versions in each sub-crate of the workspace is tedious
|
||||||
[patch.crates-io]
|
[patch.crates-io]
|
||||||
# reedline = { git = "https://github.com/nushell/reedline.git", branch = "main" }
|
# reedline = { git = "https://github.com/nushell/reedline.git", branch = "main"}
|
||||||
|
# nu-ansi-term = {git = "https://github.com/nushell/nu-ansi-term.git", branch = "main"}
|
||||||
|
|
||||||
|
# Criterion benchmarking setup
|
||||||
|
# Run all benchmarks with `cargo bench`
|
||||||
|
# Run individual benchmarks like `cargo bench -- <regex>` e.g. `cargo bench -- parse`
|
||||||
|
[[bench]]
|
||||||
|
name = "benchmarks"
|
||||||
|
harness = false
|
||||||
|
9
Cross.toml
Normal file
9
Cross.toml
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
# Configuration for cross-rs: https://github.com/cross-rs/cross
|
||||||
|
# Run cross-rs like this:
|
||||||
|
# cross build --target aarch64-unknown-linux-musl --release
|
||||||
|
|
||||||
|
[target.aarch64-unknown-linux-gnu]
|
||||||
|
dockerfile = "./docker/cross-rs/aarch64-unknown-linux-gnu.dockerfile"
|
||||||
|
|
||||||
|
[target.aarch64-unknown-linux-musl]
|
||||||
|
dockerfile = "./docker/cross-rs/aarch64-unknown-linux-musl.dockerfile"
|
2
LICENSE
2
LICENSE
@ -1,6 +1,6 @@
|
|||||||
MIT License
|
MIT License
|
||||||
|
|
||||||
Copyright (c) 2019 - 2022 The Nushell Project Developers
|
Copyright (c) 2019 - 2023 The Nushell Project Developers
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
34
README.md
34
README.md
@ -1,21 +1,23 @@
|
|||||||
# Nushell <!-- omit in toc -->
|
# Nushell <!-- omit in toc -->
|
||||||
[](https://crates.io/crates/nu)
|
[](https://crates.io/crates/nu)
|
||||||

|
[](https://github.com/nushell/nushell/actions)
|
||||||
[](https://discord.gg/NtAbbGn)
|
[](https://discord.gg/NtAbbGn)
|
||||||
[](https://changelog.com/podcast/363)
|
[](https://changelog.com/podcast/363)
|
||||||
[](https://twitter.com/nu_shell)
|
[](https://twitter.com/nu_shell)
|
||||||

|
[](https://github.com/nushell/nushell/graphs/commit-activity)
|
||||||

|
[](https://github.com/nushell/nushell/graphs/contributors)
|
||||||
|
[](https://codecov.io/gh/nushell/nushell)
|
||||||
|
|
||||||
A new type of shell.
|
A new type of shell.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
## Table of Contents <!-- omit in toc -->
|
## Table of Contents <!-- omit in toc -->
|
||||||
|
|
||||||
- [Status](#status)
|
- [Status](#status)
|
||||||
- [Learning About Nu](#learning-about-nu)
|
- [Learning About Nu](#learning-about-nu)
|
||||||
- [Installation](#installation)
|
- [Installation](#installation)
|
||||||
|
- [Configuration](#configuration)
|
||||||
- [Philosophy](#philosophy)
|
- [Philosophy](#philosophy)
|
||||||
- [Pipelines](#pipelines)
|
- [Pipelines](#pipelines)
|
||||||
- [Opening files](#opening-files)
|
- [Opening files](#opening-files)
|
||||||
@ -32,7 +34,7 @@ This project has reached a minimum-viable-product level of quality. Many people
|
|||||||
|
|
||||||
## Learning About Nu
|
## Learning About Nu
|
||||||
|
|
||||||
The [Nushell book](https://www.nushell.sh/book/) is the primary source of Nushell documentation. You can find [a full list of Nu commands in the book](https://www.nushell.sh/book/command_reference.html), and we have many examples of using Nu in our [cookbook](https://www.nushell.sh/cookbook/).
|
The [Nushell book](https://www.nushell.sh/book/) is the primary source of Nushell documentation. You can find [a full list of Nu commands in the book](https://www.nushell.sh/commands/), and we have many examples of using Nu in our [cookbook](https://www.nushell.sh/cookbook/).
|
||||||
|
|
||||||
We're also active on [Discord](https://discord.gg/NtAbbGn) and [Twitter](https://twitter.com/nu_shell); come and chat with us!
|
We're also active on [Discord](https://discord.gg/NtAbbGn) and [Twitter](https://twitter.com/nu_shell); come and chat with us!
|
||||||
|
|
||||||
@ -47,13 +49,29 @@ brew install nushell
|
|||||||
winget install nushell
|
winget install nushell
|
||||||
```
|
```
|
||||||
|
|
||||||
To use `Nu` in Github Action, check [setup-nu](https://github.com/marketplace/actions/setup-nu) for more detail.
|
To use `Nu` in GitHub Action, check [setup-nu](https://github.com/marketplace/actions/setup-nu) for more detail.
|
||||||
|
|
||||||
Detailed installation instructions can be found in the [installation chapter of the book](https://www.nushell.sh/book/installation.html). Nu is available via many package managers:
|
Detailed installation instructions can be found in the [installation chapter of the book](https://www.nushell.sh/book/installation.html). Nu is available via many package managers:
|
||||||
|
|
||||||
[](https://repology.org/project/nushell/versions)
|
[](https://repology.org/project/nushell/versions)
|
||||||
|
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
The default configurations can be found at [sample_config](crates/nu-utils/src/sample_config)
|
||||||
|
which are the configuration files one gets when they startup Nushell for the first time.
|
||||||
|
|
||||||
|
It sets all of the default configuration to run Nushell. From here one can
|
||||||
|
then customize this file for their specific needs.
|
||||||
|
|
||||||
|
To see where *config.nu* is located on your system simply type this command.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
$nu.config-path
|
||||||
|
```
|
||||||
|
|
||||||
|
Please see our [book](https://www.nushell.sh) for all of the Nushell documentation.
|
||||||
|
|
||||||
|
|
||||||
## Philosophy
|
## Philosophy
|
||||||
|
|
||||||
@ -174,6 +192,9 @@ These binaries interact with nu via a simple JSON-RPC protocol where the command
|
|||||||
If the plugin is a filter, data streams to it one element at a time, and it can stream data back in return via stdin/stdout.
|
If the plugin is a filter, data streams to it one element at a time, and it can stream data back in return via stdin/stdout.
|
||||||
If the plugin is a sink, it is given the full vector of final data and is given free reign over stdin/stdout to use as it pleases.
|
If the plugin is a sink, it is given the full vector of final data and is given free reign over stdin/stdout to use as it pleases.
|
||||||
|
|
||||||
|
The [awesome-nu repo](https://github.com/nushell/awesome-nu#plugins) lists a variety of nu-plugins while the [showcase repo](https://github.com/nushell/showcase) *shows* off informative blog posts that have been written about Nushell along with videos that highlight technical
|
||||||
|
topics that have been presented.
|
||||||
|
|
||||||
## Goals
|
## Goals
|
||||||
|
|
||||||
Nu adheres closely to a set of goals that make up its design philosophy. As features are added, they are checked against these goals.
|
Nu adheres closely to a set of goals that make up its design philosophy. As features are added, they are checked against these goals.
|
||||||
@ -218,6 +239,7 @@ Please submit an issue or PR to be added to this list.
|
|||||||
- [oh-my-posh](https://ohmyposh.dev)
|
- [oh-my-posh](https://ohmyposh.dev)
|
||||||
- [Couchbase Shell](https://couchbase.sh)
|
- [Couchbase Shell](https://couchbase.sh)
|
||||||
- [virtualenv](https://github.com/pypa/virtualenv)
|
- [virtualenv](https://github.com/pypa/virtualenv)
|
||||||
|
- [atuin](https://github.com/ellie/atuin)
|
||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
|
@ -1,3 +0,0 @@
|
|||||||
To use Nu plugins, use the register command to tell Nu where to find the plugin. For example:
|
|
||||||
|
|
||||||
> register ./nu_plugin_query
|
|
Before Width: | Height: | Size: 1.2 MiB After Width: | Height: | Size: 1.2 MiB |
7
benches/README.md
Normal file
7
benches/README.md
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
# Criterion benchmarks
|
||||||
|
|
||||||
|
These are benchmarks using [Criterion](https://github.com/bheisler/criterion.rs), a microbenchmarking tool for Rust.
|
||||||
|
|
||||||
|
Run all benchmarks with `cargo bench`
|
||||||
|
|
||||||
|
Or run individual benchmarks like `cargo bench -- <regex>` e.g. `cargo bench -- parse`
|
191
benches/benchmarks.rs
Normal file
191
benches/benchmarks.rs
Normal file
@ -0,0 +1,191 @@
|
|||||||
|
use criterion::{criterion_group, criterion_main, BatchSize, Criterion};
|
||||||
|
use nu_cli::eval_source;
|
||||||
|
use nu_parser::parse;
|
||||||
|
use nu_plugin::{EncodingType, PluginResponse};
|
||||||
|
use nu_protocol::{PipelineData, Span, Value};
|
||||||
|
use nu_utils::{get_default_config, get_default_env};
|
||||||
|
|
||||||
|
// FIXME: All benchmarks live in this 1 file to speed up build times when benchmarking.
|
||||||
|
// When the *_benchmarks functions were in different files, `cargo bench` would build
|
||||||
|
// an executable for every single one - incredibly slowly. Would be nice to figure out
|
||||||
|
// a way to split things up again.
|
||||||
|
|
||||||
|
fn parser_benchmarks(c: &mut Criterion) {
|
||||||
|
let mut engine_state = nu_command::create_default_context();
|
||||||
|
// parsing config.nu breaks without PWD set
|
||||||
|
engine_state.add_env_var(
|
||||||
|
"PWD".into(),
|
||||||
|
Value::string("/some/dir".to_string(), Span::test_data()),
|
||||||
|
);
|
||||||
|
|
||||||
|
let default_env = get_default_env().as_bytes();
|
||||||
|
c.bench_function("parse_default_env_file", |b| {
|
||||||
|
b.iter_batched(
|
||||||
|
|| nu_protocol::engine::StateWorkingSet::new(&engine_state),
|
||||||
|
|mut working_set| parse(&mut working_set, None, default_env, false),
|
||||||
|
BatchSize::SmallInput,
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
|
let default_config = get_default_config().as_bytes();
|
||||||
|
c.bench_function("parse_default_config_file", |b| {
|
||||||
|
b.iter_batched(
|
||||||
|
|| nu_protocol::engine::StateWorkingSet::new(&engine_state),
|
||||||
|
|mut working_set| parse(&mut working_set, None, default_config, false),
|
||||||
|
BatchSize::SmallInput,
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
|
c.bench_function("eval default_env.nu", |b| {
|
||||||
|
b.iter(|| {
|
||||||
|
let mut engine_state = nu_command::create_default_context();
|
||||||
|
let mut stack = nu_protocol::engine::Stack::new();
|
||||||
|
eval_source(
|
||||||
|
&mut engine_state,
|
||||||
|
&mut stack,
|
||||||
|
get_default_env().as_bytes(),
|
||||||
|
"default_env.nu",
|
||||||
|
PipelineData::empty(),
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
c.bench_function("eval default_config.nu", |b| {
|
||||||
|
b.iter(|| {
|
||||||
|
let mut engine_state = nu_command::create_default_context();
|
||||||
|
// parsing config.nu breaks without PWD set
|
||||||
|
engine_state.add_env_var(
|
||||||
|
"PWD".into(),
|
||||||
|
Value::string("/some/dir".to_string(), Span::test_data()),
|
||||||
|
);
|
||||||
|
let mut stack = nu_protocol::engine::Stack::new();
|
||||||
|
eval_source(
|
||||||
|
&mut engine_state,
|
||||||
|
&mut stack,
|
||||||
|
get_default_config().as_bytes(),
|
||||||
|
"default_config.nu",
|
||||||
|
PipelineData::empty(),
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn eval_benchmarks(c: &mut Criterion) {
|
||||||
|
c.bench_function("eval default_env.nu", |b| {
|
||||||
|
b.iter(|| {
|
||||||
|
let mut engine_state = nu_command::create_default_context();
|
||||||
|
let mut stack = nu_protocol::engine::Stack::new();
|
||||||
|
eval_source(
|
||||||
|
&mut engine_state,
|
||||||
|
&mut stack,
|
||||||
|
get_default_env().as_bytes(),
|
||||||
|
"default_env.nu",
|
||||||
|
PipelineData::empty(),
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
c.bench_function("eval default_config.nu", |b| {
|
||||||
|
b.iter(|| {
|
||||||
|
let mut engine_state = nu_command::create_default_context();
|
||||||
|
// parsing config.nu breaks without PWD set
|
||||||
|
engine_state.add_env_var(
|
||||||
|
"PWD".into(),
|
||||||
|
Value::string("/some/dir".to_string(), Span::test_data()),
|
||||||
|
);
|
||||||
|
let mut stack = nu_protocol::engine::Stack::new();
|
||||||
|
eval_source(
|
||||||
|
&mut engine_state,
|
||||||
|
&mut stack,
|
||||||
|
get_default_config().as_bytes(),
|
||||||
|
"default_config.nu",
|
||||||
|
PipelineData::empty(),
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// generate a new table data with `row_cnt` rows, `col_cnt` columns.
|
||||||
|
fn encoding_test_data(row_cnt: usize, col_cnt: usize) -> Value {
|
||||||
|
let columns: Vec<String> = (0..col_cnt).map(|x| format!("col_{x}")).collect();
|
||||||
|
let vals: Vec<Value> = (0..col_cnt as i64).map(Value::test_int).collect();
|
||||||
|
|
||||||
|
Value::List {
|
||||||
|
vals: (0..row_cnt)
|
||||||
|
.map(|_| Value::test_record(columns.clone(), vals.clone()))
|
||||||
|
.collect(),
|
||||||
|
span: Span::test_data(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn encoding_benchmarks(c: &mut Criterion) {
|
||||||
|
let mut group = c.benchmark_group("Encoding");
|
||||||
|
let test_cnt_pairs = [
|
||||||
|
(100, 5),
|
||||||
|
(100, 10),
|
||||||
|
(100, 15),
|
||||||
|
(1000, 5),
|
||||||
|
(1000, 10),
|
||||||
|
(1000, 15),
|
||||||
|
(10000, 5),
|
||||||
|
(10000, 10),
|
||||||
|
(10000, 15),
|
||||||
|
];
|
||||||
|
for (row_cnt, col_cnt) in test_cnt_pairs.into_iter() {
|
||||||
|
for fmt in ["json", "msgpack"] {
|
||||||
|
group.bench_function(&format!("{fmt} encode {row_cnt} * {col_cnt}"), |b| {
|
||||||
|
let mut res = vec![];
|
||||||
|
let test_data =
|
||||||
|
PluginResponse::Value(Box::new(encoding_test_data(row_cnt, col_cnt)));
|
||||||
|
let encoder = EncodingType::try_from_bytes(fmt.as_bytes()).unwrap();
|
||||||
|
b.iter(|| encoder.encode_response(&test_data, &mut res))
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
group.finish();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decoding_benchmarks(c: &mut Criterion) {
|
||||||
|
let mut group = c.benchmark_group("Decoding");
|
||||||
|
let test_cnt_pairs = [
|
||||||
|
(100, 5),
|
||||||
|
(100, 10),
|
||||||
|
(100, 15),
|
||||||
|
(1000, 5),
|
||||||
|
(1000, 10),
|
||||||
|
(1000, 15),
|
||||||
|
(10000, 5),
|
||||||
|
(10000, 10),
|
||||||
|
(10000, 15),
|
||||||
|
];
|
||||||
|
for (row_cnt, col_cnt) in test_cnt_pairs.into_iter() {
|
||||||
|
for fmt in ["json", "msgpack"] {
|
||||||
|
group.bench_function(&format!("{fmt} decode for {row_cnt} * {col_cnt}"), |b| {
|
||||||
|
let mut res = vec![];
|
||||||
|
let test_data =
|
||||||
|
PluginResponse::Value(Box::new(encoding_test_data(row_cnt, col_cnt)));
|
||||||
|
let encoder = EncodingType::try_from_bytes(fmt.as_bytes()).unwrap();
|
||||||
|
encoder.encode_response(&test_data, &mut res).unwrap();
|
||||||
|
let mut binary_data = std::io::Cursor::new(res);
|
||||||
|
b.iter(|| {
|
||||||
|
binary_data.set_position(0);
|
||||||
|
encoder.decode_response(&mut binary_data)
|
||||||
|
})
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
group.finish();
|
||||||
|
}
|
||||||
|
|
||||||
|
criterion_group!(
|
||||||
|
benches,
|
||||||
|
parser_benchmarks,
|
||||||
|
eval_benchmarks,
|
||||||
|
encoding_benchmarks,
|
||||||
|
decoding_benchmarks
|
||||||
|
);
|
||||||
|
criterion_main!(benches);
|
@ -1,36 +0,0 @@
|
|||||||
@echo off
|
|
||||||
@echo -------------------------------------------------------------------
|
|
||||||
@echo Building nushell (nu.exe) with dataframes and all the plugins
|
|
||||||
@echo -------------------------------------------------------------------
|
|
||||||
@echo.
|
|
||||||
|
|
||||||
echo Building nushell.exe
|
|
||||||
cargo build cargo build --features=dataframe
|
|
||||||
@echo.
|
|
||||||
|
|
||||||
@cd crates\nu_plugin_example
|
|
||||||
echo Building nu_plugin_example.exe
|
|
||||||
cargo build
|
|
||||||
@echo.
|
|
||||||
|
|
||||||
@cd ..\..\crates\nu_plugin_gstat
|
|
||||||
echo Building nu_plugin_gstat.exe
|
|
||||||
cargo build
|
|
||||||
@echo.
|
|
||||||
|
|
||||||
@cd ..\..\crates\nu_plugin_inc
|
|
||||||
echo Building nu_plugin_inc.exe
|
|
||||||
cargo build
|
|
||||||
@echo.
|
|
||||||
|
|
||||||
@cd ..\..\crates\nu_plugin_query
|
|
||||||
echo Building nu_plugin_query.exe
|
|
||||||
cargo build
|
|
||||||
@echo.
|
|
||||||
|
|
||||||
@cd ..\..\crates\nu_plugin_custom_values
|
|
||||||
echo Building nu_plugin_custom_values.exe
|
|
||||||
cargo build
|
|
||||||
@echo.
|
|
||||||
|
|
||||||
@cd ..\..
|
|
23
build-all.nu
23
build-all.nu
@ -1,23 +0,0 @@
|
|||||||
echo '-------------------------------------------------------------------'
|
|
||||||
echo 'Building nushell (nu) with dataframes and all the plugins'
|
|
||||||
echo '-------------------------------------------------------------------'
|
|
||||||
|
|
||||||
echo $'(char nl)Building nushell'
|
|
||||||
echo '----------------------------'
|
|
||||||
cargo build --features=dataframe
|
|
||||||
|
|
||||||
let plugins = [
|
|
||||||
nu_plugin_inc,
|
|
||||||
nu_plugin_gstat,
|
|
||||||
nu_plugin_query,
|
|
||||||
nu_plugin_example,
|
|
||||||
nu_plugin_custom_values,
|
|
||||||
]
|
|
||||||
|
|
||||||
for plugin in $plugins {
|
|
||||||
$'(char nl)Building ($plugin)'
|
|
||||||
'----------------------------'
|
|
||||||
cd $'crates/($plugin)'
|
|
||||||
cargo build
|
|
||||||
ignore
|
|
||||||
}
|
|
17
codecov.yml
Normal file
17
codecov.yml
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
coverage:
|
||||||
|
status:
|
||||||
|
project:
|
||||||
|
default:
|
||||||
|
target: 55%
|
||||||
|
threshold: 2%
|
||||||
|
patch:
|
||||||
|
default:
|
||||||
|
informational: true
|
||||||
|
|
||||||
|
comment:
|
||||||
|
layout: reach, diff, files
|
||||||
|
behavior: default
|
||||||
|
require_base: yes
|
||||||
|
require_head: yes
|
||||||
|
after_n_builds: 1 # Disabled windows else: 2
|
||||||
|
|
@ -5,35 +5,38 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-cli"
|
|||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
name = "nu-cli"
|
name = "nu-cli"
|
||||||
version = "0.73.0"
|
version = "0.81.0"
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
bench = false
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
nu-test-support = { path="../nu-test-support", version = "0.73.0" }
|
nu-test-support = { path = "../nu-test-support", version = "0.81.0" }
|
||||||
nu-command = { path = "../nu-command", version = "0.73.0" }
|
rstest = { version = "0.17.0", default-features = false }
|
||||||
rstest = {version = "0.15.0", default-features = false}
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
nu-engine = { path = "../nu-engine", version = "0.73.0" }
|
nu-command = { path = "../nu-command", version = "0.81.0" }
|
||||||
nu-path = { path = "../nu-path", version = "0.73.0" }
|
nu-engine = { path = "../nu-engine", version = "0.81.0" }
|
||||||
nu-parser = { path = "../nu-parser", version = "0.73.0" }
|
nu-path = { path = "../nu-path", version = "0.81.0" }
|
||||||
nu-protocol = { path = "../nu-protocol", version = "0.73.0" }
|
nu-parser = { path = "../nu-parser", version = "0.81.0" }
|
||||||
nu-utils = { path = "../nu-utils", version = "0.73.0" }
|
nu-protocol = { path = "../nu-protocol", version = "0.81.0" }
|
||||||
nu-ansi-term = "0.46.0"
|
nu-utils = { path = "../nu-utils", version = "0.81.0" }
|
||||||
nu-color-config = { path = "../nu-color-config", version = "0.73.0" }
|
nu-color-config = { path = "../nu-color-config", version = "0.81.0" }
|
||||||
reedline = { version = "0.14.0", features = ["bashisms", "sqlite"]}
|
nu-ansi-term = "0.47.0"
|
||||||
|
reedline = { version = "0.20.0", features = ["bashisms", "sqlite"]}
|
||||||
|
|
||||||
atty = "0.2.14"
|
atty = "0.2"
|
||||||
chrono = { default-features = false, features = ["std"], version = "0.4.23" }
|
chrono = { default-features = false, features = ["std"], version = "0.4" }
|
||||||
crossterm = "0.24.0"
|
crossterm = "0.26"
|
||||||
fancy-regex = "0.10.0"
|
fancy-regex = "0.11"
|
||||||
fuzzy-matcher = "0.3.7"
|
fuzzy-matcher = "0.3"
|
||||||
is_executable = "1.0.1"
|
is_executable = "1.0"
|
||||||
once_cell = "1.16.0"
|
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
miette = { version = "5.1.0", features = ["fancy-no-backtrace"] }
|
miette = { version = "5.9", features = ["fancy-no-backtrace"] }
|
||||||
|
once_cell = "1.17"
|
||||||
percent-encoding = "2"
|
percent-encoding = "2"
|
||||||
sysinfo = "0.26.2"
|
sysinfo = "0.29"
|
||||||
thiserror = "1.0.31"
|
unicode-segmentation = "1.10"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
plugin = []
|
plugin = []
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
MIT License
|
MIT License
|
||||||
|
|
||||||
Copyright (c) 2019 - 2022 The Nushell Project Developers
|
Copyright (c) 2019 - 2023 The Nushell Project Developers
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
138
crates/nu-cli/src/commands/commandline.rs
Normal file
138
crates/nu-cli/src/commands/commandline.rs
Normal file
@ -0,0 +1,138 @@
|
|||||||
|
use nu_engine::CallExt;
|
||||||
|
use nu_protocol::ast::Call;
|
||||||
|
use nu_protocol::engine::{Command, EngineState, Stack};
|
||||||
|
use nu_protocol::Category;
|
||||||
|
use nu_protocol::IntoPipelineData;
|
||||||
|
use nu_protocol::{PipelineData, ShellError, Signature, SyntaxShape, Type, Value};
|
||||||
|
use unicode_segmentation::UnicodeSegmentation;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Commandline;
|
||||||
|
|
||||||
|
impl Command for Commandline {
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
"commandline"
|
||||||
|
}
|
||||||
|
|
||||||
|
fn signature(&self) -> Signature {
|
||||||
|
Signature::build("commandline")
|
||||||
|
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
|
||||||
|
.switch(
|
||||||
|
"cursor",
|
||||||
|
"Set or get the current cursor position",
|
||||||
|
Some('c'),
|
||||||
|
)
|
||||||
|
.switch(
|
||||||
|
"append",
|
||||||
|
"appends the string to the end of the buffer",
|
||||||
|
Some('a'),
|
||||||
|
)
|
||||||
|
.switch(
|
||||||
|
"insert",
|
||||||
|
"inserts the string into the buffer at the cursor position",
|
||||||
|
Some('i'),
|
||||||
|
)
|
||||||
|
.switch(
|
||||||
|
"replace",
|
||||||
|
"replaces the current contents of the buffer (default)",
|
||||||
|
Some('r'),
|
||||||
|
)
|
||||||
|
.optional(
|
||||||
|
"cmd",
|
||||||
|
SyntaxShape::String,
|
||||||
|
"the string to perform the operation with",
|
||||||
|
)
|
||||||
|
.category(Category::Core)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn usage(&self) -> &str {
|
||||||
|
"View or modify the current command line input buffer."
|
||||||
|
}
|
||||||
|
|
||||||
|
fn search_terms(&self) -> Vec<&str> {
|
||||||
|
vec!["repl", "interactive"]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(
|
||||||
|
&self,
|
||||||
|
engine_state: &EngineState,
|
||||||
|
stack: &mut Stack,
|
||||||
|
call: &Call,
|
||||||
|
_input: PipelineData,
|
||||||
|
) -> Result<PipelineData, ShellError> {
|
||||||
|
if let Some(cmd) = call.opt::<Value>(engine_state, stack, 0)? {
|
||||||
|
let mut buffer = engine_state
|
||||||
|
.repl_buffer_state
|
||||||
|
.lock()
|
||||||
|
.expect("repl buffer state mutex");
|
||||||
|
let mut cursor_pos = engine_state
|
||||||
|
.repl_cursor_pos
|
||||||
|
.lock()
|
||||||
|
.expect("repl cursor pos mutex");
|
||||||
|
|
||||||
|
if call.has_flag("cursor") {
|
||||||
|
let cmd_str = cmd.as_string()?;
|
||||||
|
match cmd_str.parse::<i64>() {
|
||||||
|
Ok(n) => {
|
||||||
|
*cursor_pos = if n <= 0 {
|
||||||
|
0usize
|
||||||
|
} else {
|
||||||
|
buffer
|
||||||
|
.grapheme_indices(true)
|
||||||
|
.map(|(i, _c)| i)
|
||||||
|
.nth(n as usize)
|
||||||
|
.unwrap_or(buffer.len())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
return Err(ShellError::CantConvert {
|
||||||
|
to_type: "int".to_string(),
|
||||||
|
from_type: "string".to_string(),
|
||||||
|
span: cmd.span()?,
|
||||||
|
help: Some(format!(
|
||||||
|
r#"string "{cmd_str}" does not represent a valid integer"#
|
||||||
|
)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if call.has_flag("append") {
|
||||||
|
buffer.push_str(&cmd.as_string()?);
|
||||||
|
} else if call.has_flag("insert") {
|
||||||
|
let cmd_str = cmd.as_string()?;
|
||||||
|
buffer.insert_str(*cursor_pos, &cmd_str);
|
||||||
|
*cursor_pos += cmd_str.len();
|
||||||
|
} else {
|
||||||
|
*buffer = cmd.as_string()?;
|
||||||
|
*cursor_pos = buffer.len();
|
||||||
|
}
|
||||||
|
Ok(Value::Nothing { span: call.head }.into_pipeline_data())
|
||||||
|
} else {
|
||||||
|
let buffer = engine_state
|
||||||
|
.repl_buffer_state
|
||||||
|
.lock()
|
||||||
|
.expect("repl buffer state mutex");
|
||||||
|
if call.has_flag("cursor") {
|
||||||
|
let cursor_pos = engine_state
|
||||||
|
.repl_cursor_pos
|
||||||
|
.lock()
|
||||||
|
.expect("repl cursor pos mutex");
|
||||||
|
let char_pos = buffer
|
||||||
|
.grapheme_indices(true)
|
||||||
|
.chain(std::iter::once((buffer.len(), "")))
|
||||||
|
.position(|(i, _c)| i == *cursor_pos)
|
||||||
|
.expect("Cursor position isn't on a grapheme boundary");
|
||||||
|
Ok(Value::String {
|
||||||
|
val: char_pos.to_string(),
|
||||||
|
span: call.head,
|
||||||
|
}
|
||||||
|
.into_pipeline_data())
|
||||||
|
} else {
|
||||||
|
Ok(Value::String {
|
||||||
|
val: buffer.to_string(),
|
||||||
|
span: call.head,
|
||||||
|
}
|
||||||
|
.into_pipeline_data())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
33
crates/nu-cli/src/commands/default_context.rs
Normal file
33
crates/nu-cli/src/commands/default_context.rs
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
use nu_protocol::engine::{EngineState, StateWorkingSet};
|
||||||
|
|
||||||
|
use crate::commands::*;
|
||||||
|
|
||||||
|
pub fn add_cli_context(mut engine_state: EngineState) -> EngineState {
|
||||||
|
let delta = {
|
||||||
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
||||||
|
|
||||||
|
macro_rules! bind_command {
|
||||||
|
( $( $command:expr ),* $(,)? ) => {
|
||||||
|
$( working_set.add_decl(Box::new($command)); )*
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
bind_command! {
|
||||||
|
Commandline,
|
||||||
|
History,
|
||||||
|
HistorySession,
|
||||||
|
Keybindings,
|
||||||
|
KeybindingsDefault,
|
||||||
|
KeybindingsList,
|
||||||
|
KeybindingsListen,
|
||||||
|
};
|
||||||
|
|
||||||
|
working_set.render()
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Err(err) = engine_state.merge_delta(delta) {
|
||||||
|
eprintln!("Error creating default context: {err:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
engine_state
|
||||||
|
}
|
@ -2,7 +2,7 @@ use nu_protocol::ast::Call;
|
|||||||
use nu_protocol::engine::{Command, EngineState, Stack};
|
use nu_protocol::engine::{Command, EngineState, Stack};
|
||||||
use nu_protocol::{
|
use nu_protocol::{
|
||||||
Category, Example, HistoryFileFormat, IntoInterruptiblePipelineData, PipelineData, ShellError,
|
Category, Example, HistoryFileFormat, IntoInterruptiblePipelineData, PipelineData, ShellError,
|
||||||
Signature, Span, Value,
|
Signature, Span, Type, Value,
|
||||||
};
|
};
|
||||||
use reedline::{
|
use reedline::{
|
||||||
FileBackedHistory, History as ReedlineHistory, HistoryItem, SearchDirection, SearchQuery,
|
FileBackedHistory, History as ReedlineHistory, HistoryItem, SearchDirection, SearchQuery,
|
||||||
@ -18,11 +18,16 @@ impl Command for History {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Get the command history"
|
"Get the command history."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> nu_protocol::Signature {
|
fn signature(&self) -> nu_protocol::Signature {
|
||||||
Signature::build("history")
|
Signature::build("history")
|
||||||
|
.input_output_types(vec![
|
||||||
|
(Type::Nothing, Type::Table(vec![])),
|
||||||
|
(Type::Nothing, Type::Nothing),
|
||||||
|
])
|
||||||
|
.allow_variants_without_examples(true)
|
||||||
.switch("clear", "Clears out the history entries", Some('c'))
|
.switch("clear", "Clears out the history entries", Some('c'))
|
||||||
.switch(
|
.switch(
|
||||||
"long",
|
"long",
|
||||||
@ -38,7 +43,7 @@ impl Command for History {
|
|||||||
_stack: &mut Stack,
|
_stack: &mut Stack,
|
||||||
call: &Call,
|
call: &Call,
|
||||||
_input: PipelineData,
|
_input: PipelineData,
|
||||||
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
|
) -> Result<PipelineData, ShellError> {
|
||||||
let head = call.head;
|
let head = call.head;
|
||||||
|
|
||||||
// todo for sqlite history this command should be an alias to `open ~/.config/nushell/history.sqlite3 | get history`
|
// todo for sqlite history this command should be an alias to `open ~/.config/nushell/history.sqlite3 | get history`
|
||||||
@ -86,7 +91,7 @@ impl Command for History {
|
|||||||
match engine_state.config.history_file_format {
|
match engine_state.config.history_file_format {
|
||||||
HistoryFileFormat::PlainText => Ok(history_reader
|
HistoryFileFormat::PlainText => Ok(history_reader
|
||||||
.and_then(|h| {
|
.and_then(|h| {
|
||||||
h.search(SearchQuery::everything(SearchDirection::Forward))
|
h.search(SearchQuery::everything(SearchDirection::Forward, None))
|
||||||
.ok()
|
.ok()
|
||||||
})
|
})
|
||||||
.map(move |entries| {
|
.map(move |entries| {
|
||||||
@ -109,7 +114,7 @@ impl Command for History {
|
|||||||
.into_pipeline_data(ctrlc)),
|
.into_pipeline_data(ctrlc)),
|
||||||
HistoryFileFormat::Sqlite => Ok(history_reader
|
HistoryFileFormat::Sqlite => Ok(history_reader
|
||||||
.and_then(|h| {
|
.and_then(|h| {
|
||||||
h.search(SearchQuery::everything(SearchDirection::Forward))
|
h.search(SearchQuery::everything(SearchDirection::Forward, None))
|
||||||
.ok()
|
.ok()
|
||||||
})
|
})
|
||||||
.map(move |entries| {
|
.map(move |entries| {
|
@ -1,6 +1,8 @@
|
|||||||
use nu_protocol::ast::Call;
|
use nu_protocol::ast::Call;
|
||||||
use nu_protocol::engine::{Command, EngineState, Stack};
|
use nu_protocol::engine::{Command, EngineState, Stack};
|
||||||
use nu_protocol::{Category, Example, IntoPipelineData, PipelineData, Signature, Value};
|
use nu_protocol::{
|
||||||
|
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Type, Value,
|
||||||
|
};
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct HistorySession;
|
pub struct HistorySession;
|
||||||
@ -11,11 +13,13 @@ impl Command for HistorySession {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Get the command history session"
|
"Get the command history session."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> nu_protocol::Signature {
|
fn signature(&self) -> nu_protocol::Signature {
|
||||||
Signature::build("history session").category(Category::Misc)
|
Signature::build("history session")
|
||||||
|
.category(Category::Misc)
|
||||||
|
.input_output_types(vec![(Type::Nothing, Type::Int)])
|
||||||
}
|
}
|
||||||
|
|
||||||
fn examples(&self) -> Vec<Example> {
|
fn examples(&self) -> Vec<Example> {
|
||||||
@ -32,7 +36,7 @@ impl Command for HistorySession {
|
|||||||
_stack: &mut Stack,
|
_stack: &mut Stack,
|
||||||
call: &Call,
|
call: &Call,
|
||||||
_input: PipelineData,
|
_input: PipelineData,
|
||||||
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
|
) -> Result<PipelineData, ShellError> {
|
||||||
Ok(Value::int(engine_state.history_session_id, call.head).into_pipeline_data())
|
Ok(Value::int(engine_state.history_session_id, call.head).into_pipeline_data())
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -2,7 +2,7 @@ use nu_engine::get_full_help;
|
|||||||
use nu_protocol::{
|
use nu_protocol::{
|
||||||
ast::Call,
|
ast::Call,
|
||||||
engine::{Command, EngineState, Stack},
|
engine::{Command, EngineState, Stack},
|
||||||
Category, IntoPipelineData, PipelineData, Signature, Value,
|
Category, IntoPipelineData, PipelineData, ShellError, Signature, Type, Value,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
@ -14,11 +14,17 @@ impl Command for Keybindings {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
Signature::build(self.name()).category(Category::Platform)
|
Signature::build(self.name())
|
||||||
|
.category(Category::Platform)
|
||||||
|
.input_output_types(vec![(Type::Nothing, Type::String)])
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Keybindings related commands"
|
"Keybindings related commands."
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extra_usage(&self) -> &str {
|
||||||
|
"You must use one of the following subcommands. Using this command as-is will only produce this help message."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn search_terms(&self) -> Vec<&str> {
|
fn search_terms(&self) -> Vec<&str> {
|
||||||
@ -31,7 +37,7 @@ impl Command for Keybindings {
|
|||||||
stack: &mut Stack,
|
stack: &mut Stack,
|
||||||
call: &Call,
|
call: &Call,
|
||||||
_input: PipelineData,
|
_input: PipelineData,
|
||||||
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
|
) -> Result<PipelineData, ShellError> {
|
||||||
Ok(Value::String {
|
Ok(Value::String {
|
||||||
val: get_full_help(
|
val: get_full_help(
|
||||||
&Keybindings.signature(),
|
&Keybindings.signature(),
|
@ -1,7 +1,7 @@
|
|||||||
use nu_protocol::{
|
use nu_protocol::{
|
||||||
ast::Call,
|
ast::Call,
|
||||||
engine::{Command, EngineState, Stack},
|
engine::{Command, EngineState, Stack},
|
||||||
Category, Example, IntoPipelineData, PipelineData, Signature, Value,
|
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Type, Value,
|
||||||
};
|
};
|
||||||
use reedline::get_reedline_default_keybindings;
|
use reedline::get_reedline_default_keybindings;
|
||||||
|
|
||||||
@ -14,11 +14,13 @@ impl Command for KeybindingsDefault {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
Signature::build(self.name()).category(Category::Platform)
|
Signature::build(self.name())
|
||||||
|
.category(Category::Platform)
|
||||||
|
.input_output_types(vec![(Type::Nothing, Type::Table(vec![]))])
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"List default keybindings"
|
"List default keybindings."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn examples(&self) -> Vec<Example> {
|
fn examples(&self) -> Vec<Example> {
|
||||||
@ -35,7 +37,7 @@ impl Command for KeybindingsDefault {
|
|||||||
_stack: &mut Stack,
|
_stack: &mut Stack,
|
||||||
call: &Call,
|
call: &Call,
|
||||||
_input: PipelineData,
|
_input: PipelineData,
|
||||||
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
|
) -> Result<PipelineData, ShellError> {
|
||||||
let records = get_reedline_default_keybindings()
|
let records = get_reedline_default_keybindings()
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|(mode, modifier, code, event)| {
|
.map(|(mode, modifier, code, event)| {
|
@ -1,7 +1,7 @@
|
|||||||
use nu_protocol::{
|
use nu_protocol::{
|
||||||
ast::Call,
|
ast::Call,
|
||||||
engine::{Command, EngineState, Stack},
|
engine::{Command, EngineState, Stack},
|
||||||
Category, Example, IntoPipelineData, PipelineData, Signature, Span, Value,
|
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Span, Type, Value,
|
||||||
};
|
};
|
||||||
use reedline::{
|
use reedline::{
|
||||||
get_reedline_edit_commands, get_reedline_keybinding_modifiers, get_reedline_keycodes,
|
get_reedline_edit_commands, get_reedline_keybinding_modifiers, get_reedline_keycodes,
|
||||||
@ -18,6 +18,7 @@ impl Command for KeybindingsList {
|
|||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
Signature::build(self.name())
|
Signature::build(self.name())
|
||||||
|
.input_output_types(vec![(Type::Nothing, Type::Table(vec![]))])
|
||||||
.switch("modifiers", "list of modifiers", Some('m'))
|
.switch("modifiers", "list of modifiers", Some('m'))
|
||||||
.switch("keycodes", "list of keycodes", Some('k'))
|
.switch("keycodes", "list of keycodes", Some('k'))
|
||||||
.switch("modes", "list of edit modes", Some('o'))
|
.switch("modes", "list of edit modes", Some('o'))
|
||||||
@ -27,7 +28,7 @@ impl Command for KeybindingsList {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"List available options that can be used to create keybindings"
|
"List available options that can be used to create keybindings."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn examples(&self) -> Vec<Example> {
|
fn examples(&self) -> Vec<Example> {
|
||||||
@ -56,7 +57,7 @@ impl Command for KeybindingsList {
|
|||||||
_stack: &mut Stack,
|
_stack: &mut Stack,
|
||||||
call: &Call,
|
call: &Call,
|
||||||
_input: PipelineData,
|
_input: PipelineData,
|
||||||
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
|
) -> Result<PipelineData, ShellError> {
|
||||||
let records = if call.named_len() == 0 {
|
let records = if call.named_len() == 0 {
|
||||||
let all_options = vec!["modifiers", "keycodes", "edits", "modes", "events"];
|
let all_options = vec!["modifiers", "keycodes", "edits", "modes", "events"];
|
||||||
all_options
|
all_options
|
@ -3,7 +3,7 @@ use crossterm::{event::Event, event::KeyCode, event::KeyEvent, terminal};
|
|||||||
use nu_protocol::ast::Call;
|
use nu_protocol::ast::Call;
|
||||||
use nu_protocol::engine::{Command, EngineState, Stack};
|
use nu_protocol::engine::{Command, EngineState, Stack};
|
||||||
use nu_protocol::{
|
use nu_protocol::{
|
||||||
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Span, Value,
|
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Span, Type, Value,
|
||||||
};
|
};
|
||||||
use std::io::{stdout, Write};
|
use std::io::{stdout, Write};
|
||||||
|
|
||||||
@ -20,7 +20,10 @@ impl Command for KeybindingsListen {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
Signature::build(self.name()).category(Category::Platform)
|
Signature::build(self.name())
|
||||||
|
.category(Category::Platform)
|
||||||
|
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
|
||||||
|
.allow_variants_without_examples(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn run(
|
fn run(
|
||||||
@ -90,7 +93,7 @@ pub fn print_events(engine_state: &EngineState) -> Result<Value, ShellError> {
|
|||||||
}
|
}
|
||||||
terminal::disable_raw_mode()?;
|
terminal::disable_raw_mode()?;
|
||||||
|
|
||||||
Ok(Value::nothing(Span::test_data()))
|
Ok(Value::nothing(Span::unknown()))
|
||||||
}
|
}
|
||||||
|
|
||||||
// this fn is totally ripped off from crossterm's examples
|
// this fn is totally ripped off from crossterm's examples
|
||||||
@ -99,7 +102,13 @@ pub fn print_events(engine_state: &EngineState) -> Result<Value, ShellError> {
|
|||||||
// are printed, it's a good chance your terminal is eating
|
// are printed, it's a good chance your terminal is eating
|
||||||
// those events.
|
// those events.
|
||||||
fn print_events_helper(event: Event) -> Result<Value, ShellError> {
|
fn print_events_helper(event: Event) -> Result<Value, ShellError> {
|
||||||
if let Event::Key(KeyEvent { code, modifiers }) = event {
|
if let Event::Key(KeyEvent {
|
||||||
|
code,
|
||||||
|
modifiers,
|
||||||
|
kind,
|
||||||
|
state,
|
||||||
|
}) = event
|
||||||
|
{
|
||||||
match code {
|
match code {
|
||||||
KeyCode::Char(c) => {
|
KeyCode::Char(c) => {
|
||||||
let record = Value::Record {
|
let record = Value::Record {
|
||||||
@ -108,14 +117,18 @@ fn print_events_helper(event: Event) -> Result<Value, ShellError> {
|
|||||||
"code".into(),
|
"code".into(),
|
||||||
"modifier".into(),
|
"modifier".into(),
|
||||||
"flags".into(),
|
"flags".into(),
|
||||||
|
"kind".into(),
|
||||||
|
"state".into(),
|
||||||
],
|
],
|
||||||
vals: vec![
|
vals: vec![
|
||||||
Value::string(format!("{}", c), Span::test_data()),
|
Value::string(format!("{c}"), Span::unknown()),
|
||||||
Value::string(format!("{:#08x}", u32::from(c)), Span::test_data()),
|
Value::string(format!("{:#08x}", u32::from(c)), Span::unknown()),
|
||||||
Value::string(format!("{:?}", modifiers), Span::test_data()),
|
Value::string(format!("{modifiers:?}"), Span::unknown()),
|
||||||
Value::string(format!("{:#08b}", modifiers), Span::test_data()),
|
Value::string(format!("{modifiers:#08b}"), Span::unknown()),
|
||||||
|
Value::string(format!("{kind:?}"), Span::unknown()),
|
||||||
|
Value::string(format!("{state:?}"), Span::unknown()),
|
||||||
],
|
],
|
||||||
span: Span::test_data(),
|
span: Span::unknown(),
|
||||||
};
|
};
|
||||||
Ok(record)
|
Ok(record)
|
||||||
}
|
}
|
||||||
@ -123,11 +136,11 @@ fn print_events_helper(event: Event) -> Result<Value, ShellError> {
|
|||||||
let record = Value::Record {
|
let record = Value::Record {
|
||||||
cols: vec!["code".into(), "modifier".into(), "flags".into()],
|
cols: vec!["code".into(), "modifier".into(), "flags".into()],
|
||||||
vals: vec![
|
vals: vec![
|
||||||
Value::string(format!("{:?}", code), Span::test_data()),
|
Value::string(format!("{code:?}"), Span::unknown()),
|
||||||
Value::string(format!("{:?}", modifiers), Span::test_data()),
|
Value::string(format!("{modifiers:?}"), Span::unknown()),
|
||||||
Value::string(format!("{:#08b}", modifiers), Span::test_data()),
|
Value::string(format!("{modifiers:#08b}"), Span::unknown()),
|
||||||
],
|
],
|
||||||
span: Span::test_data(),
|
span: Span::unknown(),
|
||||||
};
|
};
|
||||||
Ok(record)
|
Ok(record)
|
||||||
}
|
}
|
||||||
@ -135,20 +148,9 @@ fn print_events_helper(event: Event) -> Result<Value, ShellError> {
|
|||||||
} else {
|
} else {
|
||||||
let record = Value::Record {
|
let record = Value::Record {
|
||||||
cols: vec!["event".into()],
|
cols: vec!["event".into()],
|
||||||
vals: vec![Value::string(format!("{:?}", event), Span::test_data())],
|
vals: vec![Value::string(format!("{event:?}"), Span::unknown())],
|
||||||
span: Span::test_data(),
|
span: Span::unknown(),
|
||||||
};
|
};
|
||||||
Ok(record)
|
Ok(record)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use crate::KeybindingsListen;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn examples_work_as_expected() {
|
|
||||||
use crate::test_examples;
|
|
||||||
test_examples(KeybindingsListen {})
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,9 +1,18 @@
|
|||||||
|
mod commandline;
|
||||||
|
mod default_context;
|
||||||
|
mod history;
|
||||||
|
mod history_session;
|
||||||
mod keybindings;
|
mod keybindings;
|
||||||
mod keybindings_default;
|
mod keybindings_default;
|
||||||
mod keybindings_list;
|
mod keybindings_list;
|
||||||
mod keybindings_listen;
|
mod keybindings_listen;
|
||||||
|
|
||||||
|
pub use commandline::Commandline;
|
||||||
|
pub use history::History;
|
||||||
|
pub use history_session::HistorySession;
|
||||||
pub use keybindings::Keybindings;
|
pub use keybindings::Keybindings;
|
||||||
pub use keybindings_default::KeybindingsDefault;
|
pub use keybindings_default::KeybindingsDefault;
|
||||||
pub use keybindings_list::KeybindingsList;
|
pub use keybindings_list::KeybindingsList;
|
||||||
pub use keybindings_listen::KeybindingsListen;
|
pub use keybindings_listen::KeybindingsListen;
|
||||||
|
|
||||||
|
pub use default_context::add_cli_context;
|
@ -37,7 +37,8 @@ impl CommandCompletion {
|
|||||||
) -> Vec<String> {
|
) -> Vec<String> {
|
||||||
let mut executables = vec![];
|
let mut executables = vec![];
|
||||||
|
|
||||||
let paths = self.engine_state.get_env_var("PATH");
|
// os agnostic way to get the PATH env var
|
||||||
|
let paths = self.engine_state.get_path_env_var();
|
||||||
|
|
||||||
if let Some(paths) = paths {
|
if let Some(paths) = paths {
|
||||||
if let Ok(paths) = paths.as_list() {
|
if let Ok(paths) = paths.as_list() {
|
||||||
@ -87,7 +88,7 @@ impl CommandCompletion {
|
|||||||
|
|
||||||
let filter_predicate = |command: &[u8]| match_algorithm.matches_u8(command, partial);
|
let filter_predicate = |command: &[u8]| match_algorithm.matches_u8(command, partial);
|
||||||
|
|
||||||
let results = working_set
|
let mut results = working_set
|
||||||
.find_commands_by_predicate(filter_predicate)
|
.find_commands_by_predicate(filter_predicate)
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(move |x| Suggestion {
|
.map(move |x| Suggestion {
|
||||||
@ -96,20 +97,8 @@ impl CommandCompletion {
|
|||||||
extra: None,
|
extra: None,
|
||||||
span: reedline::Span::new(span.start - offset, span.end - offset),
|
span: reedline::Span::new(span.start - offset, span.end - offset),
|
||||||
append_whitespace: true,
|
append_whitespace: true,
|
||||||
});
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
let results_aliases = working_set
|
|
||||||
.find_aliases_by_predicate(filter_predicate)
|
|
||||||
.into_iter()
|
|
||||||
.map(move |x| Suggestion {
|
|
||||||
value: String::from_utf8_lossy(&x).to_string(),
|
|
||||||
description: None,
|
|
||||||
extra: None,
|
|
||||||
span: reedline::Span::new(span.start - offset, span.end - offset),
|
|
||||||
append_whitespace: true,
|
|
||||||
});
|
|
||||||
|
|
||||||
let mut results = results.chain(results_aliases).collect::<Vec<_>>();
|
|
||||||
|
|
||||||
let partial = working_set.get_span_contents(span);
|
let partial = working_set.get_span_contents(span);
|
||||||
let partial = String::from_utf8_lossy(partial).to_string();
|
let partial = String::from_utf8_lossy(partial).to_string();
|
||||||
@ -168,7 +157,7 @@ impl Completer for CommandCompletion {
|
|||||||
.take_while(|x| {
|
.take_while(|x| {
|
||||||
matches!(
|
matches!(
|
||||||
x.1,
|
x.1,
|
||||||
FlatShape::InternalCall
|
FlatShape::InternalCall(_)
|
||||||
| FlatShape::External
|
| FlatShape::External
|
||||||
| FlatShape::ExternalArg
|
| FlatShape::ExternalArg
|
||||||
| FlatShape::Literal
|
| FlatShape::Literal
|
||||||
@ -196,8 +185,9 @@ impl Completer for CommandCompletion {
|
|||||||
|
|
||||||
let config = working_set.get_config();
|
let config = working_set.get_config();
|
||||||
let commands = if matches!(self.flat_shape, nu_parser::FlatShape::External)
|
let commands = if matches!(self.flat_shape, nu_parser::FlatShape::External)
|
||||||
|| matches!(self.flat_shape, nu_parser::FlatShape::InternalCall)
|
|| matches!(self.flat_shape, nu_parser::FlatShape::InternalCall(_))
|
||||||
|| ((span.end - span.start) == 0)
|
|| ((span.end - span.start) == 0)
|
||||||
|
|| is_passthrough_command(working_set.delta.get_file_contents())
|
||||||
{
|
{
|
||||||
// we're in a gap or at a command
|
// we're in a gap or at a command
|
||||||
if working_set.get_span_contents(span).is_empty() && !self.force_completion_after_space
|
if working_set.get_span_contents(span).is_empty() && !self.force_completion_after_space
|
||||||
@ -225,3 +215,107 @@ impl Completer for CommandCompletion {
|
|||||||
SortBy::LevenshteinDistance
|
SortBy::LevenshteinDistance
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn find_non_whitespace_index(contents: &[u8], start: usize) -> usize {
|
||||||
|
match contents.get(start..) {
|
||||||
|
Some(contents) => {
|
||||||
|
contents
|
||||||
|
.iter()
|
||||||
|
.take_while(|x| x.is_ascii_whitespace())
|
||||||
|
.count()
|
||||||
|
+ start
|
||||||
|
}
|
||||||
|
None => start,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_passthrough_command(working_set_file_contents: &[(Vec<u8>, usize, usize)]) -> bool {
|
||||||
|
for (contents, _, _) in working_set_file_contents {
|
||||||
|
let last_pipe_pos_rev = contents.iter().rev().position(|x| x == &b'|');
|
||||||
|
let last_pipe_pos = last_pipe_pos_rev.map(|x| contents.len() - x).unwrap_or(0);
|
||||||
|
|
||||||
|
let cur_pos = find_non_whitespace_index(contents, last_pipe_pos);
|
||||||
|
|
||||||
|
let result = match contents.get(cur_pos..) {
|
||||||
|
Some(contents) => contents.starts_with(b"sudo "),
|
||||||
|
None => false,
|
||||||
|
};
|
||||||
|
if result {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod command_completions_tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_find_non_whitespace_index() {
|
||||||
|
let commands = vec![
|
||||||
|
(" hello", 4),
|
||||||
|
("sudo ", 0),
|
||||||
|
(" sudo ", 2),
|
||||||
|
(" sudo ", 2),
|
||||||
|
(" hello ", 1),
|
||||||
|
(" hello ", 3),
|
||||||
|
(" hello | sudo ", 4),
|
||||||
|
(" sudo|sudo", 5),
|
||||||
|
("sudo | sudo ", 0),
|
||||||
|
(" hello sud", 1),
|
||||||
|
];
|
||||||
|
for (idx, ele) in commands.iter().enumerate() {
|
||||||
|
let index = find_non_whitespace_index(&Vec::from(ele.0.as_bytes()), 0);
|
||||||
|
assert_eq!(index, ele.1, "Failed on index {}", idx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_is_last_command_passthrough() {
|
||||||
|
let commands = vec![
|
||||||
|
(" hello", false),
|
||||||
|
(" sudo ", true),
|
||||||
|
("sudo ", true),
|
||||||
|
(" hello", false),
|
||||||
|
(" sudo", false),
|
||||||
|
(" sudo ", true),
|
||||||
|
(" sudo ", true),
|
||||||
|
(" sudo ", true),
|
||||||
|
(" hello ", false),
|
||||||
|
(" hello | sudo ", true),
|
||||||
|
(" sudo|sudo", false),
|
||||||
|
("sudo | sudo ", true),
|
||||||
|
(" hello sud", false),
|
||||||
|
(" sudo | sud ", false),
|
||||||
|
(" sudo|sudo ", true),
|
||||||
|
(" sudo | sudo ls | sudo ", true),
|
||||||
|
];
|
||||||
|
for (idx, ele) in commands.iter().enumerate() {
|
||||||
|
let input = ele.0.as_bytes();
|
||||||
|
|
||||||
|
let mut engine_state = EngineState::new();
|
||||||
|
engine_state.add_file("test.nu".into(), vec![]);
|
||||||
|
|
||||||
|
let delta = {
|
||||||
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
||||||
|
let _ = working_set.add_file("child.nu".into(), input);
|
||||||
|
working_set.render()
|
||||||
|
};
|
||||||
|
|
||||||
|
let result = engine_state.merge_delta(delta);
|
||||||
|
assert!(
|
||||||
|
result.is_ok(),
|
||||||
|
"Merge delta has failed: {}",
|
||||||
|
result.err().unwrap()
|
||||||
|
);
|
||||||
|
|
||||||
|
let is_passthrough_command = is_passthrough_command(engine_state.get_file_contents());
|
||||||
|
assert_eq!(
|
||||||
|
is_passthrough_command, ele.1,
|
||||||
|
"index for '{}': {}",
|
||||||
|
ele.0, idx
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -104,7 +104,7 @@ impl NuCompleter {
|
|||||||
return Some(result);
|
return Some(result);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(err) => println!("failed to eval completer block: {}", err),
|
Err(err) => println!("failed to eval completer block: {err}"),
|
||||||
}
|
}
|
||||||
|
|
||||||
None
|
None
|
||||||
@ -113,14 +113,13 @@ impl NuCompleter {
|
|||||||
fn completion_helper(&mut self, line: &str, pos: usize) -> Vec<Suggestion> {
|
fn completion_helper(&mut self, line: &str, pos: usize) -> Vec<Suggestion> {
|
||||||
let mut working_set = StateWorkingSet::new(&self.engine_state);
|
let mut working_set = StateWorkingSet::new(&self.engine_state);
|
||||||
let offset = working_set.next_span_start();
|
let offset = working_set.next_span_start();
|
||||||
let (mut new_line, alias_offset) = try_find_alias(line.as_bytes(), &working_set);
|
|
||||||
let initial_line = line.to_string();
|
let initial_line = line.to_string();
|
||||||
let alias_total_offset: usize = alias_offset.iter().sum();
|
let mut line = line.to_string();
|
||||||
new_line.insert(alias_total_offset + pos, b'a');
|
line.insert(pos, 'a');
|
||||||
let pos = offset + pos;
|
let pos = offset + pos;
|
||||||
let config = self.engine_state.get_config();
|
let config = self.engine_state.get_config();
|
||||||
|
|
||||||
let (output, _err) = parse(&mut working_set, Some("completer"), &new_line, false, &[]);
|
let output = parse(&mut working_set, Some("completer"), line.as_bytes(), false);
|
||||||
|
|
||||||
for pipeline in output.pipelines.into_iter() {
|
for pipeline in output.pipelines.into_iter() {
|
||||||
for pipeline_element in pipeline.elements {
|
for pipeline_element in pipeline.elements {
|
||||||
@ -128,12 +127,17 @@ impl NuCompleter {
|
|||||||
PipelineElement::Expression(_, expr)
|
PipelineElement::Expression(_, expr)
|
||||||
| PipelineElement::Redirection(_, _, expr)
|
| PipelineElement::Redirection(_, _, expr)
|
||||||
| PipelineElement::And(_, expr)
|
| PipelineElement::And(_, expr)
|
||||||
| PipelineElement::Or(_, expr) => {
|
| PipelineElement::Or(_, expr)
|
||||||
|
| PipelineElement::SameTargetRedirection { cmd: (_, expr), .. }
|
||||||
|
| PipelineElement::SeparateRedirection { out: (_, expr), .. } => {
|
||||||
let flattened: Vec<_> = flatten_expression(&working_set, &expr);
|
let flattened: Vec<_> = flatten_expression(&working_set, &expr);
|
||||||
let span_offset: usize = alias_offset.iter().sum();
|
|
||||||
let mut spans: Vec<String> = vec![];
|
let mut spans: Vec<String> = vec![];
|
||||||
|
|
||||||
for (flat_idx, flat) in flattened.iter().enumerate() {
|
for (flat_idx, flat) in flattened.iter().enumerate() {
|
||||||
|
let is_passthrough_command = spans
|
||||||
|
.first()
|
||||||
|
.filter(|content| *content == &String::from("sudo"))
|
||||||
|
.is_some();
|
||||||
// Read the current spam to string
|
// Read the current spam to string
|
||||||
let current_span = working_set.get_span_contents(flat.0).to_vec();
|
let current_span = working_set.get_span_contents(flat.0).to_vec();
|
||||||
let current_span_str = String::from_utf8_lossy(¤t_span);
|
let current_span_str = String::from_utf8_lossy(¤t_span);
|
||||||
@ -149,24 +153,17 @@ impl NuCompleter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Complete based on the last span
|
// Complete based on the last span
|
||||||
if pos + span_offset >= flat.0.start && pos + span_offset < flat.0.end {
|
if pos >= flat.0.start && pos < flat.0.end {
|
||||||
// Context variables
|
// Context variables
|
||||||
let most_left_var =
|
let most_left_var =
|
||||||
most_left_variable(flat_idx, &working_set, flattened.clone());
|
most_left_variable(flat_idx, &working_set, flattened.clone());
|
||||||
|
|
||||||
// Create a new span
|
// Create a new span
|
||||||
let new_span = if flat_idx == 0 {
|
let new_span = Span::new(flat.0.start, flat.0.end - 1);
|
||||||
Span::new(flat.0.start, flat.0.end - 1 - span_offset)
|
|
||||||
} else {
|
|
||||||
Span::new(
|
|
||||||
flat.0.start - span_offset,
|
|
||||||
flat.0.end - 1 - span_offset,
|
|
||||||
)
|
|
||||||
};
|
|
||||||
|
|
||||||
// Parses the prefix. Completion should look up to the cursor position, not after.
|
// Parses the prefix. Completion should look up to the cursor position, not after.
|
||||||
let mut prefix = working_set.get_span_contents(flat.0).to_vec();
|
let mut prefix = working_set.get_span_contents(flat.0).to_vec();
|
||||||
let index = pos - (flat.0.start - span_offset);
|
let index = pos - flat.0.start;
|
||||||
prefix.drain(index..);
|
prefix.drain(index..);
|
||||||
|
|
||||||
// Variables completion
|
// Variables completion
|
||||||
@ -216,8 +213,9 @@ impl NuCompleter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// specially check if it is currently empty - always complete commands
|
// specially check if it is currently empty - always complete commands
|
||||||
if flat_idx == 0
|
if (is_passthrough_command && flat_idx == 1)
|
||||||
&& working_set.get_span_contents(new_span).is_empty()
|
|| (flat_idx == 0
|
||||||
|
&& working_set.get_span_contents(new_span).is_empty())
|
||||||
{
|
{
|
||||||
let mut completer = CommandCompletion::new(
|
let mut completer = CommandCompletion::new(
|
||||||
self.engine_state.clone(),
|
self.engine_state.clone(),
|
||||||
@ -238,7 +236,7 @@ impl NuCompleter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Completions that depends on the previous expression (e.g: use, source-env)
|
// Completions that depends on the previous expression (e.g: use, source-env)
|
||||||
if flat_idx > 0 {
|
if (is_passthrough_command && flat_idx > 1) || flat_idx > 0 {
|
||||||
if let Some(previous_expr) = flattened.get(flat_idx - 1) {
|
if let Some(previous_expr) = flattened.get(flat_idx - 1) {
|
||||||
// Read the content for the previous expression
|
// Read the content for the previous expression
|
||||||
let prev_expr_str =
|
let prev_expr_str =
|
||||||
@ -385,85 +383,6 @@ impl ReedlineCompleter for NuCompleter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type MatchedAlias = Vec<(Vec<u8>, Vec<u8>)>;
|
|
||||||
|
|
||||||
// Handler the completion when giving lines contains at least one alias. (e.g: `g checkout`)
|
|
||||||
// that `g` is an alias of `git`
|
|
||||||
fn try_find_alias(line: &[u8], working_set: &StateWorkingSet) -> (Vec<u8>, Vec<usize>) {
|
|
||||||
// An vector represents the offsets of alias
|
|
||||||
// e.g: the offset is 2 for the alias `g` of `git`
|
|
||||||
let mut alias_offset = vec![];
|
|
||||||
let mut output = vec![];
|
|
||||||
if let Some(matched_alias) = search_alias(line, working_set) {
|
|
||||||
let mut lens = matched_alias.len();
|
|
||||||
for (input_vec, line_vec) in matched_alias {
|
|
||||||
alias_offset.push(line_vec.len() - input_vec.len());
|
|
||||||
output.extend(line_vec);
|
|
||||||
if lens > 1 {
|
|
||||||
output.push(b' ');
|
|
||||||
lens -= 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !line.is_empty() {
|
|
||||||
let last = line.last().expect("input is empty");
|
|
||||||
if last == &b' ' {
|
|
||||||
output.push(b' ');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
output = line.to_vec();
|
|
||||||
}
|
|
||||||
|
|
||||||
(output, alias_offset)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn search_alias(input: &[u8], working_set: &StateWorkingSet) -> Option<MatchedAlias> {
|
|
||||||
let mut vec_names = vec![];
|
|
||||||
let mut vec_alias = vec![];
|
|
||||||
let mut pos = 0;
|
|
||||||
let mut is_alias = false;
|
|
||||||
for (index, character) in input.iter().enumerate() {
|
|
||||||
if *character == b' ' {
|
|
||||||
let range = &input[pos..index];
|
|
||||||
vec_names.push(range.to_owned());
|
|
||||||
pos = index + 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Push the rest to names vector.
|
|
||||||
if pos < input.len() {
|
|
||||||
vec_names.push(input[pos..].to_owned());
|
|
||||||
}
|
|
||||||
|
|
||||||
for name in &vec_names {
|
|
||||||
if let Some(alias_id) = working_set.find_alias(&name[..]) {
|
|
||||||
let alias_span = working_set.get_alias(alias_id);
|
|
||||||
let mut span_vec = vec![];
|
|
||||||
is_alias = true;
|
|
||||||
for alias in alias_span {
|
|
||||||
let name = working_set.get_span_contents(*alias);
|
|
||||||
if !name.is_empty() {
|
|
||||||
span_vec.push(name);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Join span of vector together for complex alias, e.g: `f` is an alias for `git remote -v`
|
|
||||||
let full_aliases = span_vec.join(&[b' '][..]);
|
|
||||||
vec_alias.push(full_aliases);
|
|
||||||
} else {
|
|
||||||
vec_alias.push(name.to_owned());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if is_alias {
|
|
||||||
// Zip names and alias vectors, the original inputs and its aliases mapping.
|
|
||||||
// e.g:(['g'], ['g','i','t'])
|
|
||||||
let output = vec_names.into_iter().zip(vec_alias).collect();
|
|
||||||
Some(output)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// reads the most left variable returning it's name (e.g: $myvar)
|
// reads the most left variable returning it's name (e.g: $myvar)
|
||||||
// and the depth (a.b.c)
|
// and the depth (a.b.c)
|
||||||
fn most_left_variable(
|
fn most_left_variable(
|
||||||
@ -484,7 +403,7 @@ fn most_left_variable(
|
|||||||
let result = working_set.get_span_contents(item.0).to_vec();
|
let result = working_set.get_span_contents(item.0).to_vec();
|
||||||
|
|
||||||
match item.1 {
|
match item.1 {
|
||||||
FlatShape::Variable => {
|
FlatShape::Variable(_) => {
|
||||||
variables_found.push(result);
|
variables_found.push(result);
|
||||||
found_var = true;
|
found_var = true;
|
||||||
|
|
||||||
@ -575,3 +494,63 @@ pub fn map_value_completions<'a>(
|
|||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod completer_tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_completion_helper() {
|
||||||
|
let mut engine_state = nu_command::create_default_context();
|
||||||
|
|
||||||
|
// Custom additions
|
||||||
|
let delta = {
|
||||||
|
let working_set = nu_protocol::engine::StateWorkingSet::new(&engine_state);
|
||||||
|
working_set.render()
|
||||||
|
};
|
||||||
|
|
||||||
|
let result = engine_state.merge_delta(delta);
|
||||||
|
assert!(
|
||||||
|
result.is_ok(),
|
||||||
|
"Error merging delta: {:?}",
|
||||||
|
result.err().unwrap()
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut completer = NuCompleter::new(engine_state.into(), Stack::new());
|
||||||
|
let dataset = vec![
|
||||||
|
("sudo", false, "", Vec::new()),
|
||||||
|
("sudo l", true, "l", vec!["ls", "let", "lines", "loop"]),
|
||||||
|
(" sudo", false, "", Vec::new()),
|
||||||
|
(" sudo le", true, "le", vec!["let", "length"]),
|
||||||
|
(
|
||||||
|
"ls | c",
|
||||||
|
true,
|
||||||
|
"c",
|
||||||
|
vec!["cd", "config", "const", "cp", "cal"],
|
||||||
|
),
|
||||||
|
("ls | sudo m", true, "m", vec!["mv", "mut", "move"]),
|
||||||
|
];
|
||||||
|
for (line, has_result, begins_with, expected_values) in dataset {
|
||||||
|
let result = completer.completion_helper(line, line.len());
|
||||||
|
// Test whether the result is empty or not
|
||||||
|
assert_eq!(!result.is_empty(), has_result, "line: {}", line);
|
||||||
|
|
||||||
|
// Test whether the result begins with the expected value
|
||||||
|
result
|
||||||
|
.iter()
|
||||||
|
.for_each(|x| assert!(x.value.starts_with(begins_with)));
|
||||||
|
|
||||||
|
// Test whether the result contains all the expected values
|
||||||
|
assert_eq!(
|
||||||
|
result
|
||||||
|
.iter()
|
||||||
|
.map(|x| expected_values.contains(&x.value.as_str()))
|
||||||
|
.filter(|x| *x)
|
||||||
|
.count(),
|
||||||
|
expected_values.len(),
|
||||||
|
"line: {}",
|
||||||
|
line
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -6,7 +6,7 @@ use nu_protocol::{
|
|||||||
PipelineData, Span, Type, Value,
|
PipelineData, Span, Type, Value,
|
||||||
};
|
};
|
||||||
use reedline::Suggestion;
|
use reedline::Suggestion;
|
||||||
use std::sync::Arc;
|
use std::{collections::HashMap, sync::Arc};
|
||||||
|
|
||||||
use super::completer::map_value_completions;
|
use super::completer::map_value_completions;
|
||||||
|
|
||||||
@ -66,6 +66,7 @@ impl Completer for CustomCompletion {
|
|||||||
],
|
],
|
||||||
redirect_stdout: true,
|
redirect_stdout: true,
|
||||||
redirect_stderr: true,
|
redirect_stderr: true,
|
||||||
|
parser_info: HashMap::new(),
|
||||||
},
|
},
|
||||||
PipelineData::empty(),
|
PipelineData::empty(),
|
||||||
);
|
);
|
||||||
@ -73,8 +74,8 @@ impl Completer for CustomCompletion {
|
|||||||
let mut custom_completion_options = None;
|
let mut custom_completion_options = None;
|
||||||
|
|
||||||
// Parse result
|
// Parse result
|
||||||
let suggestions = match result {
|
let suggestions = result
|
||||||
Ok(pd) => {
|
.map(|pd| {
|
||||||
let value = pd.into_value(span);
|
let value = pd.into_value(span);
|
||||||
match &value {
|
match &value {
|
||||||
Value::Record { .. } => {
|
Value::Record { .. } => {
|
||||||
@ -131,9 +132,8 @@ impl Completer for CustomCompletion {
|
|||||||
Value::List { vals, .. } => map_value_completions(vals.iter(), span, offset),
|
Value::List { vals, .. } => map_value_completions(vals.iter(), span, offset),
|
||||||
_ => vec![],
|
_ => vec![],
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
_ => vec![],
|
.unwrap_or_default();
|
||||||
};
|
|
||||||
|
|
||||||
if let Some(custom_completion_options) = custom_completion_options {
|
if let Some(custom_completion_options) = custom_completion_options {
|
||||||
filter(&prefix, suggestions, &custom_completion_options)
|
filter(&prefix, suggestions, &custom_completion_options)
|
||||||
|
@ -8,7 +8,7 @@ use std::fs;
|
|||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use super::{partial_from, prepend_base_dir};
|
use super::{partial_from, prepend_base_dir, SortBy};
|
||||||
|
|
||||||
const SEP: char = std::path::MAIN_SEPARATOR;
|
const SEP: char = std::path::MAIN_SEPARATOR;
|
||||||
|
|
||||||
@ -33,14 +33,7 @@ impl Completer for DirectoryCompletion {
|
|||||||
_: usize,
|
_: usize,
|
||||||
options: &CompletionOptions,
|
options: &CompletionOptions,
|
||||||
) -> Vec<Suggestion> {
|
) -> Vec<Suggestion> {
|
||||||
let cwd = if let Some(d) = self.engine_state.get_env_var("PWD") {
|
let cwd = self.engine_state.current_work_dir();
|
||||||
match d.as_string() {
|
|
||||||
Ok(s) => s,
|
|
||||||
Err(_) => "".to_string(),
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
"".to_string()
|
|
||||||
};
|
|
||||||
let partial = String::from_utf8_lossy(&prefix).to_string();
|
let partial = String::from_utf8_lossy(&prefix).to_string();
|
||||||
|
|
||||||
// Filter only the folders
|
// Filter only the folders
|
||||||
@ -67,12 +60,20 @@ impl Completer for DirectoryCompletion {
|
|||||||
|
|
||||||
// Sort items
|
// Sort items
|
||||||
let mut sorted_items = items;
|
let mut sorted_items = items;
|
||||||
sorted_items.sort_by(|a, b| a.value.cmp(&b.value));
|
|
||||||
sorted_items.sort_by(|a, b| {
|
match self.get_sort_by() {
|
||||||
let a_distance = levenshtein_distance(&prefix_str, &a.value);
|
SortBy::Ascending => {
|
||||||
let b_distance = levenshtein_distance(&prefix_str, &b.value);
|
sorted_items.sort_by(|a, b| a.value.cmp(&b.value));
|
||||||
a_distance.cmp(&b_distance)
|
}
|
||||||
});
|
SortBy::LevenshteinDistance => {
|
||||||
|
sorted_items.sort_by(|a, b| {
|
||||||
|
let a_distance = levenshtein_distance(&prefix_str, &a.value);
|
||||||
|
let b_distance = levenshtein_distance(&prefix_str, &b.value);
|
||||||
|
a_distance.cmp(&b_distance)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
|
||||||
// Separate the results between hidden and non hidden
|
// Separate the results between hidden and non hidden
|
||||||
let mut hidden: Vec<Suggestion> = vec![];
|
let mut hidden: Vec<Suggestion> = vec![];
|
||||||
@ -126,7 +127,7 @@ pub fn directory_completion(
|
|||||||
let mut file_name = entry.file_name().to_string_lossy().into_owned();
|
let mut file_name = entry.file_name().to_string_lossy().into_owned();
|
||||||
if matches(&partial, &file_name, options) {
|
if matches(&partial, &file_name, options) {
|
||||||
let mut path = if prepend_base_dir(original_input, &base_dir_name) {
|
let mut path = if prepend_base_dir(original_input, &base_dir_name) {
|
||||||
format!("{}{}", base_dir_name, file_name)
|
format!("{base_dir_name}{file_name}")
|
||||||
} else {
|
} else {
|
||||||
file_name.to_string()
|
file_name.to_string()
|
||||||
};
|
};
|
||||||
@ -142,7 +143,7 @@ pub fn directory_completion(
|
|||||||
|| path.contains(' ')
|
|| path.contains(' ')
|
||||||
|| path.contains('#')
|
|| path.contains('#')
|
||||||
{
|
{
|
||||||
path = format!("`{}`", path);
|
path = format!("`{path}`");
|
||||||
}
|
}
|
||||||
|
|
||||||
Some((span, path))
|
Some((span, path))
|
||||||
|
@ -58,7 +58,7 @@ impl Completer for DotNuCompletion {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Check if the base_dir is a folder
|
// Check if the base_dir is a folder
|
||||||
if base_dir != format!(".{}", SEP) {
|
if base_dir != format!(".{SEP}") {
|
||||||
// Add the base dir into the directories to be searched
|
// Add the base dir into the directories to be searched
|
||||||
search_dirs.push(base_dir.clone());
|
search_dirs.push(base_dir.clone());
|
||||||
|
|
||||||
@ -70,14 +70,7 @@ impl Completer for DotNuCompletion {
|
|||||||
partial = base_dir_partial;
|
partial = base_dir_partial;
|
||||||
} else {
|
} else {
|
||||||
// Fetch the current folder
|
// Fetch the current folder
|
||||||
let current_folder = if let Some(d) = self.engine_state.get_env_var("PWD") {
|
let current_folder = self.engine_state.current_work_dir();
|
||||||
match d.as_string() {
|
|
||||||
Ok(s) => s,
|
|
||||||
Err(_) => "".to_string(),
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
"".to_string()
|
|
||||||
};
|
|
||||||
is_current_folder = true;
|
is_current_folder = true;
|
||||||
|
|
||||||
// Add the current folder and the lib dirs into the
|
// Add the current folder and the lib dirs into the
|
||||||
|
@ -7,6 +7,8 @@ use reedline::Suggestion;
|
|||||||
use std::path::{is_separator, Path};
|
use std::path::{is_separator, Path};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use super::SortBy;
|
||||||
|
|
||||||
const SEP: char = std::path::MAIN_SEPARATOR;
|
const SEP: char = std::path::MAIN_SEPARATOR;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
@ -30,14 +32,7 @@ impl Completer for FileCompletion {
|
|||||||
_: usize,
|
_: usize,
|
||||||
options: &CompletionOptions,
|
options: &CompletionOptions,
|
||||||
) -> Vec<Suggestion> {
|
) -> Vec<Suggestion> {
|
||||||
let cwd = if let Some(d) = self.engine_state.get_env_var("PWD") {
|
let cwd = self.engine_state.current_work_dir();
|
||||||
match d.as_string() {
|
|
||||||
Ok(s) => s,
|
|
||||||
Err(_) => "".to_string(),
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
"".to_string()
|
|
||||||
};
|
|
||||||
let prefix = String::from_utf8_lossy(&prefix).to_string();
|
let prefix = String::from_utf8_lossy(&prefix).to_string();
|
||||||
let output: Vec<_> = file_path_completion(span, &prefix, &cwd, options)
|
let output: Vec<_> = file_path_completion(span, &prefix, &cwd, options)
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@ -62,12 +57,20 @@ impl Completer for FileCompletion {
|
|||||||
|
|
||||||
// Sort items
|
// Sort items
|
||||||
let mut sorted_items = items;
|
let mut sorted_items = items;
|
||||||
sorted_items.sort_by(|a, b| a.value.cmp(&b.value));
|
|
||||||
sorted_items.sort_by(|a, b| {
|
match self.get_sort_by() {
|
||||||
let a_distance = levenshtein_distance(&prefix_str, &a.value);
|
SortBy::Ascending => {
|
||||||
let b_distance = levenshtein_distance(&prefix_str, &b.value);
|
sorted_items.sort_by(|a, b| a.value.cmp(&b.value));
|
||||||
a_distance.cmp(&b_distance)
|
}
|
||||||
});
|
SortBy::LevenshteinDistance => {
|
||||||
|
sorted_items.sort_by(|a, b| {
|
||||||
|
let a_distance = levenshtein_distance(&prefix_str, &a.value);
|
||||||
|
let b_distance = levenshtein_distance(&prefix_str, &b.value);
|
||||||
|
a_distance.cmp(&b_distance)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
|
||||||
// Separate the results between hidden and non hidden
|
// Separate the results between hidden and non hidden
|
||||||
let mut hidden: Vec<Suggestion> = vec![];
|
let mut hidden: Vec<Suggestion> = vec![];
|
||||||
@ -131,7 +134,7 @@ pub fn file_path_completion(
|
|||||||
let mut file_name = entry.file_name().to_string_lossy().into_owned();
|
let mut file_name = entry.file_name().to_string_lossy().into_owned();
|
||||||
if matches(&partial, &file_name, options) {
|
if matches(&partial, &file_name, options) {
|
||||||
let mut path = if prepend_base_dir(original_input, &base_dir_name) {
|
let mut path = if prepend_base_dir(original_input, &base_dir_name) {
|
||||||
format!("{}{}", base_dir_name, file_name)
|
format!("{base_dir_name}{file_name}")
|
||||||
} else {
|
} else {
|
||||||
file_name.to_string()
|
file_name.to_string()
|
||||||
};
|
};
|
||||||
@ -146,8 +149,20 @@ pub fn file_path_completion(
|
|||||||
|| path.contains('"')
|
|| path.contains('"')
|
||||||
|| path.contains(' ')
|
|| path.contains(' ')
|
||||||
|| path.contains('#')
|
|| path.contains('#')
|
||||||
|
|| path.contains('(')
|
||||||
|
|| path.contains(')')
|
||||||
|
|| path.starts_with('0')
|
||||||
|
|| path.starts_with('1')
|
||||||
|
|| path.starts_with('2')
|
||||||
|
|| path.starts_with('3')
|
||||||
|
|| path.starts_with('4')
|
||||||
|
|| path.starts_with('5')
|
||||||
|
|| path.starts_with('6')
|
||||||
|
|| path.starts_with('7')
|
||||||
|
|| path.starts_with('8')
|
||||||
|
|| path.starts_with('9')
|
||||||
{
|
{
|
||||||
path = format!("`{}`", path);
|
path = format!("`{path}`");
|
||||||
}
|
}
|
||||||
|
|
||||||
Some((span, path))
|
Some((span, path))
|
||||||
@ -175,7 +190,7 @@ pub fn matches(partial: &str, from: &str, options: &CompletionOptions) -> bool {
|
|||||||
|
|
||||||
/// Returns whether the base_dir should be prepended to the file path
|
/// Returns whether the base_dir should be prepended to the file path
|
||||||
pub fn prepend_base_dir(input: &str, base_dir: &str) -> bool {
|
pub fn prepend_base_dir(input: &str, base_dir: &str) -> bool {
|
||||||
if base_dir == format!(".{}", SEP) {
|
if base_dir == format!(".{SEP}") {
|
||||||
// if the current base_dir path is the local folder we only add a "./" prefix if the user
|
// if the current base_dir path is the local folder we only add a "./" prefix if the user
|
||||||
// input already includes a local folder prefix.
|
// input already includes a local folder prefix.
|
||||||
let manually_entered = {
|
let manually_entered = {
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
use crate::completions::{Completer, CompletionOptions};
|
use crate::completions::{Completer, CompletionOptions};
|
||||||
use nu_engine::eval_variable;
|
use nu_engine::{column::get_columns, eval_variable};
|
||||||
use nu_protocol::{
|
use nu_protocol::{
|
||||||
engine::{EngineState, Stack, StateWorkingSet},
|
engine::{EngineState, Stack, StateWorkingSet},
|
||||||
Span, Value,
|
Span, Value,
|
||||||
@ -9,6 +9,8 @@ use reedline::Suggestion;
|
|||||||
use std::str;
|
use std::str;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use super::MatchAlgorithm;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct VariableCompletion {
|
pub struct VariableCompletion {
|
||||||
engine_state: Arc<EngineState>, // TODO: Is engine state necessary? It's already a part of working set in fetch()
|
engine_state: Arc<EngineState>, // TODO: Is engine state necessary? It's already a part of working set in fetch()
|
||||||
@ -73,10 +75,11 @@ impl Completer for VariableCompletion {
|
|||||||
for suggestion in
|
for suggestion in
|
||||||
nested_suggestions(val.clone(), nested_levels, current_span)
|
nested_suggestions(val.clone(), nested_levels, current_span)
|
||||||
{
|
{
|
||||||
if options
|
if options.match_algorithm.matches_u8_insensitive(
|
||||||
.match_algorithm
|
options.case_sensitive,
|
||||||
.matches_u8(suggestion.value.as_bytes(), &prefix)
|
suggestion.value.as_bytes(),
|
||||||
{
|
&prefix,
|
||||||
|
) {
|
||||||
output.push(suggestion);
|
output.push(suggestion);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -86,10 +89,11 @@ impl Completer for VariableCompletion {
|
|||||||
} else {
|
} else {
|
||||||
// No nesting provided, return all env vars
|
// No nesting provided, return all env vars
|
||||||
for env_var in env_vars {
|
for env_var in env_vars {
|
||||||
if options
|
if options.match_algorithm.matches_u8_insensitive(
|
||||||
.match_algorithm
|
options.case_sensitive,
|
||||||
.matches_u8(env_var.0.as_bytes(), &prefix)
|
env_var.0.as_bytes(),
|
||||||
{
|
&prefix,
|
||||||
|
) {
|
||||||
output.push(Suggestion {
|
output.push(Suggestion {
|
||||||
value: env_var.0,
|
value: env_var.0,
|
||||||
description: None,
|
description: None,
|
||||||
@ -116,10 +120,11 @@ impl Completer for VariableCompletion {
|
|||||||
for suggestion in
|
for suggestion in
|
||||||
nested_suggestions(nuval, self.var_context.1.clone(), current_span)
|
nested_suggestions(nuval, self.var_context.1.clone(), current_span)
|
||||||
{
|
{
|
||||||
if options
|
if options.match_algorithm.matches_u8_insensitive(
|
||||||
.match_algorithm
|
options.case_sensitive,
|
||||||
.matches_u8(suggestion.value.as_bytes(), &prefix)
|
suggestion.value.as_bytes(),
|
||||||
{
|
&prefix,
|
||||||
|
) {
|
||||||
output.push(suggestion);
|
output.push(suggestion);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -138,10 +143,11 @@ impl Completer for VariableCompletion {
|
|||||||
for suggestion in
|
for suggestion in
|
||||||
nested_suggestions(value, self.var_context.1.clone(), current_span)
|
nested_suggestions(value, self.var_context.1.clone(), current_span)
|
||||||
{
|
{
|
||||||
if options
|
if options.match_algorithm.matches_u8_insensitive(
|
||||||
.match_algorithm
|
options.case_sensitive,
|
||||||
.matches_u8(suggestion.value.as_bytes(), &prefix)
|
suggestion.value.as_bytes(),
|
||||||
{
|
&prefix,
|
||||||
|
) {
|
||||||
output.push(suggestion);
|
output.push(suggestion);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -153,10 +159,11 @@ impl Completer for VariableCompletion {
|
|||||||
|
|
||||||
// Variable completion (e.g: $en<tab> to complete $env)
|
// Variable completion (e.g: $en<tab> to complete $env)
|
||||||
for builtin in builtins {
|
for builtin in builtins {
|
||||||
if options
|
if options.match_algorithm.matches_u8_insensitive(
|
||||||
.match_algorithm
|
options.case_sensitive,
|
||||||
.matches_u8(builtin.as_bytes(), &prefix)
|
builtin.as_bytes(),
|
||||||
{
|
&prefix,
|
||||||
|
) {
|
||||||
output.push(Suggestion {
|
output.push(Suggestion {
|
||||||
value: builtin.to_string(),
|
value: builtin.to_string(),
|
||||||
description: None,
|
description: None,
|
||||||
@ -172,13 +179,13 @@ impl Completer for VariableCompletion {
|
|||||||
let mut removed_overlays = vec![];
|
let mut removed_overlays = vec![];
|
||||||
// Working set scope vars
|
// Working set scope vars
|
||||||
for scope_frame in working_set.delta.scope.iter().rev() {
|
for scope_frame in working_set.delta.scope.iter().rev() {
|
||||||
for overlay_frame in scope_frame
|
for overlay_frame in scope_frame.active_overlays(&mut removed_overlays).rev() {
|
||||||
.active_overlays(&mut removed_overlays)
|
|
||||||
.iter()
|
|
||||||
.rev()
|
|
||||||
{
|
|
||||||
for v in &overlay_frame.vars {
|
for v in &overlay_frame.vars {
|
||||||
if options.match_algorithm.matches_u8(v.0, &prefix) {
|
if options.match_algorithm.matches_u8_insensitive(
|
||||||
|
options.case_sensitive,
|
||||||
|
v.0,
|
||||||
|
&prefix,
|
||||||
|
) {
|
||||||
output.push(Suggestion {
|
output.push(Suggestion {
|
||||||
value: String::from_utf8_lossy(v.0).to_string(),
|
value: String::from_utf8_lossy(v.0).to_string(),
|
||||||
description: None,
|
description: None,
|
||||||
@ -193,14 +200,13 @@ impl Completer for VariableCompletion {
|
|||||||
|
|
||||||
// Permanent state vars
|
// Permanent state vars
|
||||||
// for scope in &self.engine_state.scope {
|
// for scope in &self.engine_state.scope {
|
||||||
for overlay_frame in self
|
for overlay_frame in self.engine_state.active_overlays(&removed_overlays).rev() {
|
||||||
.engine_state
|
|
||||||
.active_overlays(&removed_overlays)
|
|
||||||
.iter()
|
|
||||||
.rev()
|
|
||||||
{
|
|
||||||
for v in &overlay_frame.vars {
|
for v in &overlay_frame.vars {
|
||||||
if options.match_algorithm.matches_u8(v.0, &prefix) {
|
if options.match_algorithm.matches_u8_insensitive(
|
||||||
|
options.case_sensitive,
|
||||||
|
v.0,
|
||||||
|
&prefix,
|
||||||
|
) {
|
||||||
output.push(Suggestion {
|
output.push(Suggestion {
|
||||||
value: String::from_utf8_lossy(v.0).to_string(),
|
value: String::from_utf8_lossy(v.0).to_string(),
|
||||||
description: None,
|
description: None,
|
||||||
@ -247,7 +253,33 @@ fn nested_suggestions(
|
|||||||
|
|
||||||
output
|
output
|
||||||
}
|
}
|
||||||
|
Value::LazyRecord { val, .. } => {
|
||||||
|
// Add all the columns as completion
|
||||||
|
for column_name in val.column_names() {
|
||||||
|
output.push(Suggestion {
|
||||||
|
value: column_name.to_string(),
|
||||||
|
description: None,
|
||||||
|
extra: None,
|
||||||
|
span: current_span,
|
||||||
|
append_whitespace: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
output
|
||||||
|
}
|
||||||
|
Value::List { vals, span: _ } => {
|
||||||
|
for column_name in get_columns(vals.as_slice()) {
|
||||||
|
output.push(Suggestion {
|
||||||
|
value: column_name,
|
||||||
|
description: None,
|
||||||
|
extra: None,
|
||||||
|
span: current_span,
|
||||||
|
append_whitespace: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
output
|
||||||
|
}
|
||||||
_ => output,
|
_ => output,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -275,9 +307,51 @@ fn recursive_value(val: Value, sublevels: Vec<Vec<u8>>) -> Value {
|
|||||||
span: Span::unknown(),
|
span: Span::unknown(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
Value::LazyRecord { val, span: _ } => {
|
||||||
|
for col in val.column_names() {
|
||||||
|
if col.as_bytes().to_vec() == next_sublevel {
|
||||||
|
return recursive_value(
|
||||||
|
val.get_column_value(col).unwrap_or_default(),
|
||||||
|
sublevels.into_iter().skip(1).collect(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Current sublevel value not found
|
||||||
|
return Value::Nothing {
|
||||||
|
span: Span::unknown(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
Value::List { vals, span } => {
|
||||||
|
for col in get_columns(vals.as_slice()) {
|
||||||
|
if col.as_bytes().to_vec() == next_sublevel {
|
||||||
|
return recursive_value(
|
||||||
|
Value::List { vals, span }
|
||||||
|
.get_data_by_key(&col)
|
||||||
|
.unwrap_or_default(),
|
||||||
|
sublevels.into_iter().skip(1).collect(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Current sublevel value not found
|
||||||
|
return Value::Nothing {
|
||||||
|
span: Span::unknown(),
|
||||||
|
};
|
||||||
|
}
|
||||||
_ => return val,
|
_ => return val,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
val
|
val
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl MatchAlgorithm {
|
||||||
|
pub fn matches_u8_insensitive(&self, sensitive: bool, haystack: &[u8], needle: &[u8]) -> bool {
|
||||||
|
if sensitive {
|
||||||
|
self.matches_u8(haystack, needle)
|
||||||
|
} else {
|
||||||
|
self.matches_u8(&haystack.to_ascii_lowercase(), &needle.to_ascii_lowercase())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -1,14 +1,13 @@
|
|||||||
use crate::util::{eval_source, report_error};
|
use crate::util::eval_source;
|
||||||
#[cfg(feature = "plugin")]
|
|
||||||
use log::info;
|
|
||||||
#[cfg(feature = "plugin")]
|
|
||||||
use nu_parser::ParseError;
|
|
||||||
#[cfg(feature = "plugin")]
|
#[cfg(feature = "plugin")]
|
||||||
use nu_path::canonicalize_with;
|
use nu_path::canonicalize_with;
|
||||||
use nu_protocol::engine::{EngineState, Stack, StateWorkingSet};
|
use nu_protocol::engine::{EngineState, Stack, StateWorkingSet};
|
||||||
#[cfg(feature = "plugin")]
|
use nu_protocol::report_error;
|
||||||
use nu_protocol::Spanned;
|
|
||||||
use nu_protocol::{HistoryFileFormat, PipelineData};
|
use nu_protocol::{HistoryFileFormat, PipelineData};
|
||||||
|
#[cfg(feature = "plugin")]
|
||||||
|
use nu_protocol::{ParseError, Spanned};
|
||||||
|
#[cfg(feature = "plugin")]
|
||||||
|
use nu_utils::utils::perf;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
#[cfg(feature = "plugin")]
|
#[cfg(feature = "plugin")]
|
||||||
@ -24,6 +23,8 @@ pub fn read_plugin_file(
|
|||||||
plugin_file: Option<Spanned<String>>,
|
plugin_file: Option<Spanned<String>>,
|
||||||
storage_path: &str,
|
storage_path: &str,
|
||||||
) {
|
) {
|
||||||
|
let start_time = std::time::Instant::now();
|
||||||
|
let mut plug_path = String::new();
|
||||||
// Reading signatures from signature file
|
// Reading signatures from signature file
|
||||||
// The plugin.nu file stores the parsed signature collected from each registered plugin
|
// The plugin.nu file stores the parsed signature collected from each registered plugin
|
||||||
add_plugin_file(engine_state, plugin_file, storage_path);
|
add_plugin_file(engine_state, plugin_file, storage_path);
|
||||||
@ -31,7 +32,7 @@ pub fn read_plugin_file(
|
|||||||
let plugin_path = engine_state.plugin_signatures.clone();
|
let plugin_path = engine_state.plugin_signatures.clone();
|
||||||
if let Some(plugin_path) = plugin_path {
|
if let Some(plugin_path) = plugin_path {
|
||||||
let plugin_filename = plugin_path.to_string_lossy();
|
let plugin_filename = plugin_path.to_string_lossy();
|
||||||
|
plug_path = plugin_filename.to_string();
|
||||||
if let Ok(contents) = std::fs::read(&plugin_path) {
|
if let Ok(contents) = std::fs::read(&plugin_path) {
|
||||||
eval_source(
|
eval_source(
|
||||||
engine_state,
|
engine_state,
|
||||||
@ -39,11 +40,19 @@ pub fn read_plugin_file(
|
|||||||
&contents,
|
&contents,
|
||||||
&plugin_filename,
|
&plugin_filename,
|
||||||
PipelineData::empty(),
|
PipelineData::empty(),
|
||||||
|
false,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
info!("read_plugin_file {}:{}:{}", file!(), line!(), column!());
|
perf(
|
||||||
|
&format!("read_plugin_file {}", &plug_path),
|
||||||
|
start_time,
|
||||||
|
file!(),
|
||||||
|
line!(),
|
||||||
|
column!(),
|
||||||
|
engine_state.get_config().use_ansi_coloring,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "plugin")]
|
#[cfg(feature = "plugin")]
|
||||||
@ -56,12 +65,11 @@ pub fn add_plugin_file(
|
|||||||
let working_set = StateWorkingSet::new(engine_state);
|
let working_set = StateWorkingSet::new(engine_state);
|
||||||
let cwd = working_set.get_cwd();
|
let cwd = working_set.get_cwd();
|
||||||
|
|
||||||
match canonicalize_with(&plugin_file.item, cwd) {
|
if let Ok(path) = canonicalize_with(&plugin_file.item, cwd) {
|
||||||
Ok(path) => engine_state.plugin_signatures = Some(path),
|
engine_state.plugin_signatures = Some(path)
|
||||||
Err(_) => {
|
} else {
|
||||||
let e = ParseError::FileNotFound(plugin_file.item, plugin_file.span);
|
let e = ParseError::FileNotFound(plugin_file.item, plugin_file.span);
|
||||||
report_error(&working_set, &e);
|
report_error(&working_set, &e);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} else if let Some(mut plugin_path) = nu_path::config_dir() {
|
} else if let Some(mut plugin_path) = nu_path::config_dir() {
|
||||||
// Path to store plugins signatures
|
// Path to store plugins signatures
|
||||||
@ -86,6 +94,7 @@ pub fn eval_config_contents(
|
|||||||
&contents,
|
&contents,
|
||||||
&config_filename,
|
&config_filename,
|
||||||
PipelineData::empty(),
|
PipelineData::empty(),
|
||||||
|
false,
|
||||||
);
|
);
|
||||||
|
|
||||||
// Merge the environment in case env vars changed in the config
|
// Merge the environment in case env vars changed in the config
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
use crate::util::report_error;
|
|
||||||
use log::info;
|
use log::info;
|
||||||
use miette::Result;
|
use miette::Result;
|
||||||
use nu_engine::{convert_env_values, eval_block};
|
use nu_engine::{convert_env_values, eval_block};
|
||||||
use nu_parser::parse;
|
use nu_parser::parse;
|
||||||
use nu_protocol::engine::Stack;
|
use nu_protocol::engine::Stack;
|
||||||
|
use nu_protocol::report_error;
|
||||||
use nu_protocol::{
|
use nu_protocol::{
|
||||||
engine::{EngineState, StateWorkingSet},
|
engine::{EngineState, StateWorkingSet},
|
||||||
PipelineData, Spanned, Value,
|
PipelineData, Spanned, Value,
|
||||||
@ -34,9 +34,9 @@ pub fn evaluate_commands(
|
|||||||
|
|
||||||
let mut working_set = StateWorkingSet::new(engine_state);
|
let mut working_set = StateWorkingSet::new(engine_state);
|
||||||
|
|
||||||
let (output, err) = parse(&mut working_set, None, commands.item.as_bytes(), false, &[]);
|
let output = parse(&mut working_set, None, commands.item.as_bytes(), false);
|
||||||
if let Some(err) = err {
|
if let Some(err) = working_set.parse_errors.first() {
|
||||||
report_error(&working_set, &err);
|
report_error(&working_set, err);
|
||||||
|
|
||||||
std::process::exit(1);
|
std::process::exit(1);
|
||||||
}
|
}
|
@ -1,10 +1,11 @@
|
|||||||
use crate::util::{eval_source, report_error};
|
use crate::util::eval_source;
|
||||||
use log::info;
|
use log::info;
|
||||||
use log::trace;
|
use log::trace;
|
||||||
use miette::{IntoDiagnostic, Result};
|
use miette::{IntoDiagnostic, Result};
|
||||||
use nu_engine::{convert_env_values, current_dir};
|
use nu_engine::{convert_env_values, current_dir};
|
||||||
use nu_parser::parse;
|
use nu_parser::parse;
|
||||||
use nu_path::canonicalize_with;
|
use nu_path::canonicalize_with;
|
||||||
|
use nu_protocol::report_error;
|
||||||
use nu_protocol::{
|
use nu_protocol::{
|
||||||
ast::Call,
|
ast::Call,
|
||||||
engine::{EngineState, Stack, StateWorkingSet},
|
engine::{EngineState, Stack, StateWorkingSet},
|
||||||
@ -29,44 +30,36 @@ pub fn evaluate_file(
|
|||||||
|
|
||||||
let cwd = current_dir(engine_state, stack)?;
|
let cwd = current_dir(engine_state, stack)?;
|
||||||
|
|
||||||
let file_path = {
|
let file_path = canonicalize_with(&path, cwd).unwrap_or_else(|e| {
|
||||||
match canonicalize_with(&path, &cwd) {
|
let working_set = StateWorkingSet::new(engine_state);
|
||||||
Ok(p) => p,
|
report_error(
|
||||||
Err(e) => {
|
&working_set,
|
||||||
let working_set = StateWorkingSet::new(engine_state);
|
&ShellError::FileNotFoundCustom(
|
||||||
report_error(
|
format!("Could not access file '{}': {:?}", path, e.to_string()),
|
||||||
&working_set,
|
Span::unknown(),
|
||||||
&ShellError::FileNotFoundCustom(
|
),
|
||||||
format!("Could not access file '{}': {:?}", path, e.to_string()),
|
);
|
||||||
Span::unknown(),
|
std::process::exit(1);
|
||||||
),
|
});
|
||||||
);
|
|
||||||
std::process::exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let file_path_str = match file_path.to_str() {
|
let file_path_str = file_path.to_str().unwrap_or_else(|| {
|
||||||
Some(s) => s,
|
let working_set = StateWorkingSet::new(engine_state);
|
||||||
None => {
|
report_error(
|
||||||
let working_set = StateWorkingSet::new(engine_state);
|
&working_set,
|
||||||
report_error(
|
&ShellError::NonUtf8Custom(
|
||||||
&working_set,
|
format!(
|
||||||
&ShellError::NonUtf8Custom(
|
"Input file name '{}' is not valid UTF8",
|
||||||
format!(
|
file_path.to_string_lossy()
|
||||||
"Input file name '{}' is not valid UTF8",
|
|
||||||
file_path.to_string_lossy()
|
|
||||||
),
|
|
||||||
Span::unknown(),
|
|
||||||
),
|
),
|
||||||
);
|
Span::unknown(),
|
||||||
std::process::exit(1);
|
),
|
||||||
}
|
);
|
||||||
};
|
std::process::exit(1);
|
||||||
|
});
|
||||||
|
|
||||||
let file = match std::fs::read(&file_path).into_diagnostic() {
|
let file = std::fs::read(&file_path)
|
||||||
Ok(p) => p,
|
.into_diagnostic()
|
||||||
Err(e) => {
|
.unwrap_or_else(|e| {
|
||||||
let working_set = StateWorkingSet::new(engine_state);
|
let working_set = StateWorkingSet::new(engine_state);
|
||||||
report_error(
|
report_error(
|
||||||
&working_set,
|
&working_set,
|
||||||
@ -80,22 +73,34 @@ pub fn evaluate_file(
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
std::process::exit(1);
|
std::process::exit(1);
|
||||||
}
|
});
|
||||||
};
|
|
||||||
|
|
||||||
engine_state.start_in_file(Some(file_path_str));
|
engine_state.start_in_file(Some(file_path_str));
|
||||||
|
|
||||||
let mut parent = file_path.clone();
|
let parent = file_path.parent().unwrap_or_else(|| {
|
||||||
parent.pop();
|
let working_set = StateWorkingSet::new(engine_state);
|
||||||
|
report_error(
|
||||||
|
&working_set,
|
||||||
|
&ShellError::FileNotFoundCustom(
|
||||||
|
format!("The file path '{file_path_str}' does not have a parent"),
|
||||||
|
Span::unknown(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
std::process::exit(1);
|
||||||
|
});
|
||||||
|
|
||||||
stack.add_env_var(
|
stack.add_env_var(
|
||||||
"FILE_PWD".to_string(),
|
"FILE_PWD".to_string(),
|
||||||
Value::string(parent.to_string_lossy(), Span::unknown()),
|
Value::string(parent.to_string_lossy(), Span::unknown()),
|
||||||
);
|
);
|
||||||
|
stack.add_env_var(
|
||||||
|
"CURRENT_FILE".to_string(),
|
||||||
|
Value::string(file_path.to_string_lossy(), Span::unknown()),
|
||||||
|
);
|
||||||
|
|
||||||
let mut working_set = StateWorkingSet::new(engine_state);
|
let mut working_set = StateWorkingSet::new(engine_state);
|
||||||
trace!("parsing file: {}", file_path_str);
|
trace!("parsing file: {}", file_path_str);
|
||||||
let _ = parse(&mut working_set, Some(file_path_str), &file, false, &[]);
|
let _ = parse(&mut working_set, Some(file_path_str), &file, false);
|
||||||
|
|
||||||
if working_set.find_decl(b"main", &Type::Any).is_some() {
|
if working_set.find_decl(b"main", &Type::Any).is_some() {
|
||||||
let args = format!("main {}", args.join(" "));
|
let args = format!("main {}", args.join(" "));
|
||||||
@ -106,13 +111,21 @@ pub fn evaluate_file(
|
|||||||
&file,
|
&file,
|
||||||
file_path_str,
|
file_path_str,
|
||||||
PipelineData::empty(),
|
PipelineData::empty(),
|
||||||
|
true,
|
||||||
) {
|
) {
|
||||||
std::process::exit(1);
|
std::process::exit(1);
|
||||||
}
|
}
|
||||||
if !eval_source(engine_state, stack, args.as_bytes(), "<commandline>", input) {
|
if !eval_source(
|
||||||
|
engine_state,
|
||||||
|
stack,
|
||||||
|
args.as_bytes(),
|
||||||
|
"<commandline>",
|
||||||
|
input,
|
||||||
|
true,
|
||||||
|
) {
|
||||||
std::process::exit(1);
|
std::process::exit(1);
|
||||||
}
|
}
|
||||||
} else if !eval_source(engine_state, stack, &file, file_path_str, input) {
|
} else if !eval_source(engine_state, stack, &file, file_path_str, input, true) {
|
||||||
std::process::exit(1);
|
std::process::exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -121,7 +134,7 @@ pub fn evaluate_file(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn print_table_or_error(
|
pub(crate) fn print_table_or_error(
|
||||||
engine_state: &mut EngineState,
|
engine_state: &mut EngineState,
|
||||||
stack: &mut Stack,
|
stack: &mut Stack,
|
||||||
mut pipeline_data: PipelineData,
|
mut pipeline_data: PipelineData,
|
||||||
@ -137,43 +150,34 @@ pub fn print_table_or_error(
|
|||||||
|
|
||||||
if let PipelineData::Value(Value::Error { error }, ..) = &pipeline_data {
|
if let PipelineData::Value(Value::Error { error }, ..) = &pipeline_data {
|
||||||
let working_set = StateWorkingSet::new(engine_state);
|
let working_set = StateWorkingSet::new(engine_state);
|
||||||
|
report_error(&working_set, &**error);
|
||||||
report_error(&working_set, error);
|
|
||||||
|
|
||||||
std::process::exit(1);
|
std::process::exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
match engine_state.find_decl("table".as_bytes(), &[]) {
|
if let Some(decl_id) = engine_state.find_decl("table".as_bytes(), &[]) {
|
||||||
Some(decl_id) => {
|
let command = engine_state.get_decl(decl_id);
|
||||||
let command = engine_state.get_decl(decl_id);
|
if command.get_block_id().is_some() {
|
||||||
if command.get_block_id().is_some() {
|
print_or_exit(pipeline_data, engine_state, config);
|
||||||
print_or_exit(pipeline_data, engine_state, config);
|
} else {
|
||||||
} else {
|
// The final call on table command, it's ok to set redirect_output to false.
|
||||||
let table = command.run(
|
let mut call = Call::new(Span::new(0, 0));
|
||||||
engine_state,
|
call.redirect_stdout = false;
|
||||||
stack,
|
let table = command.run(engine_state, stack, &call, pipeline_data);
|
||||||
&Call::new(Span::new(0, 0)),
|
|
||||||
pipeline_data,
|
|
||||||
);
|
|
||||||
|
|
||||||
match table {
|
match table {
|
||||||
Ok(table) => {
|
Ok(table) => {
|
||||||
print_or_exit(table, engine_state, config);
|
print_or_exit(table, engine_state, config);
|
||||||
}
|
}
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
let working_set = StateWorkingSet::new(engine_state);
|
let working_set = StateWorkingSet::new(engine_state);
|
||||||
|
report_error(&working_set, &error);
|
||||||
report_error(&working_set, &error);
|
std::process::exit(1);
|
||||||
|
|
||||||
std::process::exit(1);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
None => {
|
} else {
|
||||||
print_or_exit(pipeline_data, engine_state, config);
|
print_or_exit(pipeline_data, engine_state, config);
|
||||||
}
|
}
|
||||||
};
|
|
||||||
|
|
||||||
// Make sure everything has finished
|
// Make sure everything has finished
|
||||||
if let Some(exit_code) = exit_code {
|
if let Some(exit_code) = exit_code {
|
||||||
@ -194,14 +198,12 @@ fn print_or_exit(pipeline_data: PipelineData, engine_state: &mut EngineState, co
|
|||||||
if let Value::Error { error } = item {
|
if let Value::Error { error } = item {
|
||||||
let working_set = StateWorkingSet::new(engine_state);
|
let working_set = StateWorkingSet::new(engine_state);
|
||||||
|
|
||||||
report_error(&working_set, &error);
|
report_error(&working_set, &*error);
|
||||||
|
|
||||||
std::process::exit(1);
|
std::process::exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut out = item.into_string("\n", config);
|
let out = item.into_string("\n", config) + "\n";
|
||||||
out.push('\n');
|
let _ = stdout_write_all_and_flush(out).map_err(|err| eprintln!("{err}"));
|
||||||
|
|
||||||
let _ = stdout_write_all_and_flush(out).map_err(|err| eprintln!("{}", err));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
mod commands;
|
mod commands;
|
||||||
mod completions;
|
mod completions;
|
||||||
mod config_files;
|
mod config_files;
|
||||||
|
mod eval_cmds;
|
||||||
mod eval_file;
|
mod eval_file;
|
||||||
mod menus;
|
mod menus;
|
||||||
mod nu_highlight;
|
mod nu_highlight;
|
||||||
@ -13,18 +14,19 @@ mod syntax_highlight;
|
|||||||
mod util;
|
mod util;
|
||||||
mod validation;
|
mod validation;
|
||||||
|
|
||||||
pub use commands::evaluate_commands;
|
pub use commands::add_cli_context;
|
||||||
pub use completions::{FileCompletion, NuCompleter};
|
pub use completions::{FileCompletion, NuCompleter};
|
||||||
pub use config_files::eval_config_contents;
|
pub use config_files::eval_config_contents;
|
||||||
|
pub use eval_cmds::evaluate_commands;
|
||||||
pub use eval_file::evaluate_file;
|
pub use eval_file::evaluate_file;
|
||||||
pub use menus::{DescriptionMenu, NuHelpCompleter};
|
pub use menus::{DescriptionMenu, NuHelpCompleter};
|
||||||
|
pub use nu_command::util::get_init_cwd;
|
||||||
pub use nu_highlight::NuHighlight;
|
pub use nu_highlight::NuHighlight;
|
||||||
pub use print::Print;
|
pub use print::Print;
|
||||||
pub use prompt::NushellPrompt;
|
pub use prompt::NushellPrompt;
|
||||||
pub use repl::evaluate_repl;
|
pub use repl::evaluate_repl;
|
||||||
pub use repl::{eval_env_change_hook, eval_hook};
|
|
||||||
pub use syntax_highlight::NuHighlighter;
|
pub use syntax_highlight::NuHighlighter;
|
||||||
pub use util::{eval_source, gather_parent_env_vars, get_init_cwd, report_error, report_error_new};
|
pub use util::{eval_source, gather_parent_env_vars};
|
||||||
pub use validation::NuValidator;
|
pub use validation::NuValidator;
|
||||||
|
|
||||||
#[cfg(feature = "plugin")]
|
#[cfg(feature = "plugin")]
|
||||||
|
@ -411,10 +411,10 @@ impl DescriptionMenu {
|
|||||||
RESET
|
RESET
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
format!(" {}\r\n", example)
|
format!(" {example}\r\n")
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
format!(" {}\r\n", example)
|
format!(" {example}\r\n")
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
@ -429,7 +429,7 @@ impl DescriptionMenu {
|
|||||||
examples,
|
examples,
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
format!("\r\n\r\nExamples:\r\n{}", examples,)
|
format!("\r\n\r\nExamples:\r\n{examples}",)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -57,7 +57,9 @@ impl NuHelpCompleter {
|
|||||||
let _ = write!(long_desc, "Usage:\r\n > {}\r\n", sig.call_signature());
|
let _ = write!(long_desc, "Usage:\r\n > {}\r\n", sig.call_signature());
|
||||||
|
|
||||||
if !sig.named.is_empty() {
|
if !sig.named.is_empty() {
|
||||||
long_desc.push_str(&get_flags_section(sig))
|
long_desc.push_str(&get_flags_section(sig, |v| {
|
||||||
|
v.into_string_parsable(", ", &self.0.config)
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
if !sig.required_positional.is_empty()
|
if !sig.required_positional.is_empty()
|
||||||
@ -69,10 +71,18 @@ impl NuHelpCompleter {
|
|||||||
let _ = write!(long_desc, " {}: {}\r\n", positional.name, positional.desc);
|
let _ = write!(long_desc, " {}: {}\r\n", positional.name, positional.desc);
|
||||||
}
|
}
|
||||||
for positional in &sig.optional_positional {
|
for positional in &sig.optional_positional {
|
||||||
|
let opt_suffix = if let Some(value) = &positional.default_value {
|
||||||
|
format!(
|
||||||
|
" (optional, default: {})",
|
||||||
|
&value.into_string_parsable(", ", &self.0.config),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
(" (optional)").to_string()
|
||||||
|
};
|
||||||
let _ = write!(
|
let _ = write!(
|
||||||
long_desc,
|
long_desc,
|
||||||
" (optional) {}: {}\r\n",
|
" (optional) {}: {}{}\r\n",
|
||||||
positional.name, positional.desc
|
positional.name, positional.desc, opt_suffix
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -81,13 +81,10 @@ fn convert_to_suggestions(
|
|||||||
) -> Vec<Suggestion> {
|
) -> Vec<Suggestion> {
|
||||||
match value {
|
match value {
|
||||||
Value::Record { .. } => {
|
Value::Record { .. } => {
|
||||||
let text = match value
|
let text = value
|
||||||
.get_data_by_key("value")
|
.get_data_by_key("value")
|
||||||
.and_then(|val| val.as_string().ok())
|
.and_then(|val| val.as_string().ok())
|
||||||
{
|
.unwrap_or_else(|| "No value key".to_string());
|
||||||
Some(val) => val,
|
|
||||||
None => "No value key".to_string(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let description = value
|
let description = value
|
||||||
.get_data_by_key("description")
|
.get_data_by_key("description")
|
||||||
@ -157,7 +154,7 @@ fn convert_to_suggestions(
|
|||||||
.flat_map(|val| convert_to_suggestions(val, line, pos, only_buffer_difference))
|
.flat_map(|val| convert_to_suggestions(val, line, pos, only_buffer_difference))
|
||||||
.collect(),
|
.collect(),
|
||||||
_ => vec![Suggestion {
|
_ => vec![Suggestion {
|
||||||
value: format!("Not a record: {:?}", value),
|
value: format!("Not a record: {value:?}"),
|
||||||
description: None,
|
description: None,
|
||||||
extra: None,
|
extra: None,
|
||||||
span: reedline::Span {
|
span: reedline::Span {
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
use nu_protocol::ast::Call;
|
use nu_protocol::ast::Call;
|
||||||
use nu_protocol::engine::{Command, EngineState, Stack};
|
use nu_protocol::engine::{Command, EngineState, Stack};
|
||||||
use nu_protocol::{Category, Example, PipelineData, ShellError, Signature, Value};
|
use nu_protocol::{Category, Example, PipelineData, ShellError, Signature, Type, Value};
|
||||||
use reedline::Highlighter;
|
use reedline::Highlighter;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
@ -12,7 +12,9 @@ impl Command for NuHighlight {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
Signature::build("nu-highlight").category(Category::Strings)
|
Signature::build("nu-highlight")
|
||||||
|
.category(Category::Strings)
|
||||||
|
.input_output_types(vec![(Type::String, Type::String)])
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
@ -33,7 +35,7 @@ impl Command for NuHighlight {
|
|||||||
let head = call.head;
|
let head = call.head;
|
||||||
|
|
||||||
let ctrlc = engine_state.ctrlc.clone();
|
let ctrlc = engine_state.ctrlc.clone();
|
||||||
let engine_state = engine_state.clone();
|
let engine_state = std::sync::Arc::new(engine_state.clone());
|
||||||
let config = engine_state.get_config().clone();
|
let config = engine_state.get_config().clone();
|
||||||
|
|
||||||
let highlighter = crate::NuHighlighter {
|
let highlighter = crate::NuHighlighter {
|
||||||
@ -51,7 +53,9 @@ impl Command for NuHighlight {
|
|||||||
span: head,
|
span: head,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(err) => Value::Error { error: err },
|
Err(err) => Value::Error {
|
||||||
|
error: Box::new(err),
|
||||||
|
},
|
||||||
},
|
},
|
||||||
ctrlc,
|
ctrlc,
|
||||||
)
|
)
|
||||||
|
@ -2,7 +2,8 @@ use nu_engine::CallExt;
|
|||||||
use nu_protocol::ast::Call;
|
use nu_protocol::ast::Call;
|
||||||
use nu_protocol::engine::{Command, EngineState, Stack};
|
use nu_protocol::engine::{Command, EngineState, Stack};
|
||||||
use nu_protocol::{
|
use nu_protocol::{
|
||||||
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, SyntaxShape, Value,
|
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, SyntaxShape, Type,
|
||||||
|
Value,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
@ -15,6 +16,7 @@ impl Command for Print {
|
|||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
Signature::build("print")
|
Signature::build("print")
|
||||||
|
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
|
||||||
.rest("rest", SyntaxShape::Any, "the values to print")
|
.rest("rest", SyntaxShape::Any, "the values to print")
|
||||||
.switch(
|
.switch(
|
||||||
"no-newline",
|
"no-newline",
|
||||||
@ -26,7 +28,7 @@ impl Command for Print {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Print the given values to stdout"
|
"Print the given values to stdout."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn extra_usage(&self) -> &str {
|
fn extra_usage(&self) -> &str {
|
||||||
@ -45,15 +47,20 @@ Since this command has no output, there is no point in piping it with other comm
|
|||||||
engine_state: &EngineState,
|
engine_state: &EngineState,
|
||||||
stack: &mut Stack,
|
stack: &mut Stack,
|
||||||
call: &Call,
|
call: &Call,
|
||||||
_input: PipelineData,
|
input: PipelineData,
|
||||||
) -> Result<PipelineData, ShellError> {
|
) -> Result<PipelineData, ShellError> {
|
||||||
let args: Vec<Value> = call.rest(engine_state, stack, 0)?;
|
let args: Vec<Value> = call.rest(engine_state, stack, 0)?;
|
||||||
let no_newline = call.has_flag("no-newline");
|
let no_newline = call.has_flag("no-newline");
|
||||||
let to_stderr = call.has_flag("stderr");
|
let to_stderr = call.has_flag("stderr");
|
||||||
|
|
||||||
for arg in args {
|
// This will allow for easy printing of pipelines as well
|
||||||
arg.into_pipeline_data()
|
if !args.is_empty() {
|
||||||
.print(engine_state, stack, no_newline, to_stderr)?;
|
for arg in args {
|
||||||
|
arg.into_pipeline_data()
|
||||||
|
.print(engine_state, stack, no_newline, to_stderr)?;
|
||||||
|
}
|
||||||
|
} else if !input.is_nothing() {
|
||||||
|
input.print(engine_state, stack, no_newline, to_stderr)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(PipelineData::empty())
|
Ok(PipelineData::empty())
|
||||||
|
@ -91,7 +91,7 @@ impl NushellPrompt {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn default_wrapped_custom_string(&self, str: String) -> String {
|
fn default_wrapped_custom_string(&self, str: String) -> String {
|
||||||
format!("({})", str)
|
format!("({str})")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -105,12 +105,14 @@ impl Prompt for NushellPrompt {
|
|||||||
if let Some(prompt_string) = &self.left_prompt_string {
|
if let Some(prompt_string) = &self.left_prompt_string {
|
||||||
prompt_string.replace('\n', "\r\n").into()
|
prompt_string.replace('\n', "\r\n").into()
|
||||||
} else {
|
} else {
|
||||||
let default = DefaultPrompt::new();
|
let default = DefaultPrompt::default();
|
||||||
default
|
let prompt = default
|
||||||
.render_prompt_left()
|
.render_prompt_left()
|
||||||
.to_string()
|
.to_string()
|
||||||
.replace('\n', "\r\n")
|
.replace('\n', "\r\n")
|
||||||
.into()
|
+ " ";
|
||||||
|
|
||||||
|
prompt.into()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -118,7 +120,7 @@ impl Prompt for NushellPrompt {
|
|||||||
if let Some(prompt_string) = &self.right_prompt_string {
|
if let Some(prompt_string) = &self.right_prompt_string {
|
||||||
prompt_string.replace('\n', "\r\n").into()
|
prompt_string.replace('\n', "\r\n").into()
|
||||||
} else {
|
} else {
|
||||||
let default = DefaultPrompt::new();
|
let default = DefaultPrompt::default();
|
||||||
default
|
default
|
||||||
.render_prompt_right()
|
.render_prompt_right()
|
||||||
.to_string()
|
.to_string()
|
||||||
@ -130,32 +132,36 @@ impl Prompt for NushellPrompt {
|
|||||||
fn render_prompt_indicator(&self, edit_mode: PromptEditMode) -> Cow<str> {
|
fn render_prompt_indicator(&self, edit_mode: PromptEditMode) -> Cow<str> {
|
||||||
match edit_mode {
|
match edit_mode {
|
||||||
PromptEditMode::Default => match &self.default_prompt_indicator {
|
PromptEditMode::Default => match &self.default_prompt_indicator {
|
||||||
Some(indicator) => indicator.as_str().into(),
|
Some(indicator) => indicator,
|
||||||
None => "〉".into(),
|
None => "> ",
|
||||||
},
|
}
|
||||||
|
.into(),
|
||||||
PromptEditMode::Emacs => match &self.default_prompt_indicator {
|
PromptEditMode::Emacs => match &self.default_prompt_indicator {
|
||||||
Some(indicator) => indicator.as_str().into(),
|
Some(indicator) => indicator,
|
||||||
None => "〉".into(),
|
None => "> ",
|
||||||
},
|
}
|
||||||
|
.into(),
|
||||||
PromptEditMode::Vi(vi_mode) => match vi_mode {
|
PromptEditMode::Vi(vi_mode) => match vi_mode {
|
||||||
PromptViMode::Normal => match &self.default_vi_normal_prompt_indicator {
|
PromptViMode::Normal => match &self.default_vi_normal_prompt_indicator {
|
||||||
Some(indicator) => indicator.as_str().into(),
|
Some(indicator) => indicator,
|
||||||
None => ": ".into(),
|
None => ": ",
|
||||||
},
|
},
|
||||||
PromptViMode::Insert => match &self.default_vi_insert_prompt_indicator {
|
PromptViMode::Insert => match &self.default_vi_insert_prompt_indicator {
|
||||||
Some(indicator) => indicator.as_str().into(),
|
Some(indicator) => indicator,
|
||||||
None => "〉".into(),
|
None => "> ",
|
||||||
},
|
},
|
||||||
},
|
}
|
||||||
|
.into(),
|
||||||
PromptEditMode::Custom(str) => self.default_wrapped_custom_string(str).into(),
|
PromptEditMode::Custom(str) => self.default_wrapped_custom_string(str).into(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn render_prompt_multiline_indicator(&self) -> Cow<str> {
|
fn render_prompt_multiline_indicator(&self) -> Cow<str> {
|
||||||
match &self.default_multiline_indicator {
|
match &self.default_multiline_indicator {
|
||||||
Some(indicator) => indicator.as_str().into(),
|
Some(indicator) => indicator,
|
||||||
None => "::: ".into(),
|
None => "::: ",
|
||||||
}
|
}
|
||||||
|
.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn render_prompt_history_search_indicator(
|
fn render_prompt_history_search_indicator(
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
use crate::util::report_error;
|
|
||||||
use crate::NushellPrompt;
|
use crate::NushellPrompt;
|
||||||
use log::info;
|
use log::trace;
|
||||||
use nu_engine::eval_subexpression;
|
use nu_engine::eval_subexpression;
|
||||||
|
use nu_protocol::report_error;
|
||||||
use nu_protocol::{
|
use nu_protocol::{
|
||||||
engine::{EngineState, Stack, StateWorkingSet},
|
engine::{EngineState, Stack, StateWorkingSet},
|
||||||
Config, PipelineData, Value,
|
Config, PipelineData, Value,
|
||||||
@ -39,41 +39,37 @@ fn get_prompt_string(
|
|||||||
// Use eval_subexpression to force a redirection of output, so we can use everything in prompt
|
// Use eval_subexpression to force a redirection of output, so we can use everything in prompt
|
||||||
let ret_val =
|
let ret_val =
|
||||||
eval_subexpression(engine_state, &mut stack, block, PipelineData::empty());
|
eval_subexpression(engine_state, &mut stack, block, PipelineData::empty());
|
||||||
info!(
|
trace!(
|
||||||
"get_prompt_string (block) {}:{}:{}",
|
"get_prompt_string (block) {}:{}:{}",
|
||||||
file!(),
|
file!(),
|
||||||
line!(),
|
line!(),
|
||||||
column!()
|
column!()
|
||||||
);
|
);
|
||||||
|
|
||||||
match ret_val {
|
ret_val
|
||||||
Ok(ret_val) => Some(ret_val),
|
.map_err(|err| {
|
||||||
Err(err) => {
|
|
||||||
let working_set = StateWorkingSet::new(engine_state);
|
let working_set = StateWorkingSet::new(engine_state);
|
||||||
report_error(&working_set, &err);
|
report_error(&working_set, &err);
|
||||||
None
|
})
|
||||||
}
|
.ok()
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Value::Block { val: block_id, .. } => {
|
Value::Block { val: block_id, .. } => {
|
||||||
let block = engine_state.get_block(block_id);
|
let block = engine_state.get_block(block_id);
|
||||||
// Use eval_subexpression to force a redirection of output, so we can use everything in prompt
|
// Use eval_subexpression to force a redirection of output, so we can use everything in prompt
|
||||||
let ret_val = eval_subexpression(engine_state, stack, block, PipelineData::empty());
|
let ret_val = eval_subexpression(engine_state, stack, block, PipelineData::empty());
|
||||||
info!(
|
trace!(
|
||||||
"get_prompt_string (block) {}:{}:{}",
|
"get_prompt_string (block) {}:{}:{}",
|
||||||
file!(),
|
file!(),
|
||||||
line!(),
|
line!(),
|
||||||
column!()
|
column!()
|
||||||
);
|
);
|
||||||
|
|
||||||
match ret_val {
|
ret_val
|
||||||
Ok(ret_val) => Some(ret_val),
|
.map_err(|err| {
|
||||||
Err(err) => {
|
|
||||||
let working_set = StateWorkingSet::new(engine_state);
|
let working_set = StateWorkingSet::new(engine_state);
|
||||||
report_error(&working_set, &err);
|
report_error(&working_set, &err);
|
||||||
None
|
})
|
||||||
}
|
.ok()
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Value::String { .. } => Some(PipelineData::Value(v.clone(), None)),
|
Value::String { .. } => Some(PipelineData::Value(v.clone(), None)),
|
||||||
_ => None,
|
_ => None,
|
||||||
@ -81,20 +77,17 @@ fn get_prompt_string(
|
|||||||
.and_then(|pipeline_data| {
|
.and_then(|pipeline_data| {
|
||||||
let output = pipeline_data.collect_string("", config).ok();
|
let output = pipeline_data.collect_string("", config).ok();
|
||||||
|
|
||||||
match output {
|
output.map(|mut x| {
|
||||||
Some(mut x) => {
|
// Just remove the very last newline.
|
||||||
// Just remove the very last newline.
|
if x.ends_with('\n') {
|
||||||
if x.ends_with('\n') {
|
x.pop();
|
||||||
x.pop();
|
|
||||||
}
|
|
||||||
|
|
||||||
if x.ends_with('\r') {
|
|
||||||
x.pop();
|
|
||||||
}
|
|
||||||
Some(x)
|
|
||||||
}
|
}
|
||||||
None => None,
|
|
||||||
}
|
if x.ends_with('\r') {
|
||||||
|
x.pop();
|
||||||
|
}
|
||||||
|
x
|
||||||
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -111,12 +104,12 @@ pub(crate) fn update_prompt<'prompt>(
|
|||||||
// Now that we have the prompt string lets ansify it.
|
// Now that we have the prompt string lets ansify it.
|
||||||
// <133 A><prompt><133 B><command><133 C><command output>
|
// <133 A><prompt><133 B><command><133 C><command output>
|
||||||
let left_prompt_string = if config.shell_integration {
|
let left_prompt_string = if config.shell_integration {
|
||||||
match left_prompt_string {
|
if let Some(prompt_string) = left_prompt_string {
|
||||||
Some(prompt_string) => Some(format!(
|
Some(format!(
|
||||||
"{}{}{}",
|
"{PRE_PROMPT_MARKER}{prompt_string}{POST_PROMPT_MARKER}"
|
||||||
PRE_PROMPT_MARKER, prompt_string, POST_PROMPT_MARKER
|
))
|
||||||
)),
|
} else {
|
||||||
None => left_prompt_string,
|
left_prompt_string
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
left_prompt_string
|
left_prompt_string
|
||||||
@ -148,7 +141,7 @@ pub(crate) fn update_prompt<'prompt>(
|
|||||||
);
|
);
|
||||||
|
|
||||||
let ret_val = nu_prompt as &dyn Prompt;
|
let ret_val = nu_prompt as &dyn Prompt;
|
||||||
info!("update_prompt {}:{}:{}", file!(), line!(), column!());
|
trace!("update_prompt {}:{}:{}", file!(), line!(), column!());
|
||||||
|
|
||||||
ret_val
|
ret_val
|
||||||
}
|
}
|
||||||
|
@ -7,8 +7,7 @@ use nu_parser::parse;
|
|||||||
use nu_protocol::{
|
use nu_protocol::{
|
||||||
create_menus,
|
create_menus,
|
||||||
engine::{EngineState, Stack, StateWorkingSet},
|
engine::{EngineState, Stack, StateWorkingSet},
|
||||||
extract_value, Config, IntoPipelineData, ParsedKeybinding, ParsedMenu, PipelineData,
|
extract_value, Config, ParsedKeybinding, ParsedMenu, PipelineData, ShellError, Span, Value,
|
||||||
ShellError, Span, Value,
|
|
||||||
};
|
};
|
||||||
use reedline::{
|
use reedline::{
|
||||||
default_emacs_keybindings, default_vi_insert_keybindings, default_vi_normal_keybindings,
|
default_emacs_keybindings, default_vi_insert_keybindings, default_vi_normal_keybindings,
|
||||||
@ -98,19 +97,18 @@ pub(crate) fn add_menus(
|
|||||||
{
|
{
|
||||||
let (block, _) = {
|
let (block, _) = {
|
||||||
let mut working_set = StateWorkingSet::new(&engine_state);
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
||||||
let (output, _) = parse(
|
let output = parse(
|
||||||
&mut working_set,
|
&mut working_set,
|
||||||
Some(name), // format!("entry #{}", entry_num)
|
Some(name), // format!("entry #{}", entry_num)
|
||||||
definition.as_bytes(),
|
definition.as_bytes(),
|
||||||
true,
|
true,
|
||||||
&[],
|
|
||||||
);
|
);
|
||||||
|
|
||||||
(output, working_set.render())
|
(output, working_set.render())
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut temp_stack = Stack::new();
|
let mut temp_stack = Stack::new();
|
||||||
let input = Value::nothing(Span::test_data()).into_pipeline_data();
|
let input = PipelineData::Empty;
|
||||||
let res = eval_block(&engine_state, &mut temp_stack, &block, input, false, false)?;
|
let res = eval_block(&engine_state, &mut temp_stack, &block, input, false, false)?;
|
||||||
|
|
||||||
if let PipelineData::Value(value, None) = res {
|
if let PipelineData::Value(value, None) = res {
|
||||||
@ -627,9 +625,12 @@ fn add_parsed_keybinding(
|
|||||||
"shift" => KeyModifiers::SHIFT,
|
"shift" => KeyModifiers::SHIFT,
|
||||||
"alt" => KeyModifiers::ALT,
|
"alt" => KeyModifiers::ALT,
|
||||||
"none" => KeyModifiers::NONE,
|
"none" => KeyModifiers::NONE,
|
||||||
"control | shift" => KeyModifiers::CONTROL | KeyModifiers::SHIFT,
|
"shift_alt" | "alt_shift" => KeyModifiers::SHIFT | KeyModifiers::ALT,
|
||||||
"control | alt" => KeyModifiers::CONTROL | KeyModifiers::ALT,
|
"control_shift" | "shift_control" => KeyModifiers::CONTROL | KeyModifiers::SHIFT,
|
||||||
"control | alt | shift" => KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SHIFT,
|
"control_alt" | "alt_control" => KeyModifiers::CONTROL | KeyModifiers::ALT,
|
||||||
|
"control_alt_shift" | "control_shift_alt" => {
|
||||||
|
KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SHIFT
|
||||||
|
}
|
||||||
_ => {
|
_ => {
|
||||||
return Err(ShellError::UnsupportedConfigValue(
|
return Err(ShellError::UnsupportedConfigValue(
|
||||||
"CONTROL, SHIFT, ALT or NONE".to_string(),
|
"CONTROL, SHIFT, ALT or NONE".to_string(),
|
||||||
@ -652,14 +653,15 @@ fn add_parsed_keybinding(
|
|||||||
let pos1 = char_iter.next();
|
let pos1 = char_iter.next();
|
||||||
let pos2 = char_iter.next();
|
let pos2 = char_iter.next();
|
||||||
|
|
||||||
let char = match (pos1, pos2) {
|
let char = if let (Some(char), None) = (pos1, pos2) {
|
||||||
(Some(char), None) => Ok(char),
|
char
|
||||||
_ => Err(ShellError::UnsupportedConfigValue(
|
} else {
|
||||||
|
return Err(ShellError::UnsupportedConfigValue(
|
||||||
"char_<CHAR: unicode codepoint>".to_string(),
|
"char_<CHAR: unicode codepoint>".to_string(),
|
||||||
c.to_string(),
|
c.to_string(),
|
||||||
keybinding.keycode.span()?,
|
keybinding.keycode.span()?,
|
||||||
)),
|
));
|
||||||
}?;
|
};
|
||||||
|
|
||||||
KeyCode::Char(char)
|
KeyCode::Char(char)
|
||||||
}
|
}
|
||||||
@ -680,10 +682,10 @@ fn add_parsed_keybinding(
|
|||||||
let fn_num: u8 = c[1..]
|
let fn_num: u8 = c[1..]
|
||||||
.parse()
|
.parse()
|
||||||
.ok()
|
.ok()
|
||||||
.filter(|num| matches!(num, 1..=12))
|
.filter(|num| matches!(num, 1..=20))
|
||||||
.ok_or(ShellError::UnsupportedConfigValue(
|
.ok_or(ShellError::UnsupportedConfigValue(
|
||||||
"(f1|f2|...|f12)".to_string(),
|
"(f1|f2|...|f20)".to_string(),
|
||||||
format!("unknown function key: {}", c),
|
format!("unknown function key: {c}"),
|
||||||
keybinding.keycode.span()?,
|
keybinding.keycode.span()?,
|
||||||
))?;
|
))?;
|
||||||
KeyCode::F(fn_num)
|
KeyCode::F(fn_num)
|
||||||
@ -990,7 +992,7 @@ mod test {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_send_event() {
|
fn test_send_event() {
|
||||||
let cols = vec!["send".to_string()];
|
let cols = vec!["send".to_string()];
|
||||||
let vals = vec![Value::string("Enter", Span::test_data())];
|
let vals = vec![Value::test_string("Enter")];
|
||||||
|
|
||||||
let span = Span::test_data();
|
let span = Span::test_data();
|
||||||
let b = EventType::try_from_columns(&cols, &vals, &span).unwrap();
|
let b = EventType::try_from_columns(&cols, &vals, &span).unwrap();
|
||||||
@ -1010,7 +1012,7 @@ mod test {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_edit_event() {
|
fn test_edit_event() {
|
||||||
let cols = vec!["edit".to_string()];
|
let cols = vec!["edit".to_string()];
|
||||||
let vals = vec![Value::string("Clear", Span::test_data())];
|
let vals = vec![Value::test_string("Clear")];
|
||||||
|
|
||||||
let span = Span::test_data();
|
let span = Span::test_data();
|
||||||
let b = EventType::try_from_columns(&cols, &vals, &span).unwrap();
|
let b = EventType::try_from_columns(&cols, &vals, &span).unwrap();
|
||||||
@ -1034,8 +1036,8 @@ mod test {
|
|||||||
fn test_send_menu() {
|
fn test_send_menu() {
|
||||||
let cols = vec!["send".to_string(), "name".to_string()];
|
let cols = vec!["send".to_string(), "name".to_string()];
|
||||||
let vals = vec![
|
let vals = vec![
|
||||||
Value::string("Menu", Span::test_data()),
|
Value::test_string("Menu"),
|
||||||
Value::string("history_menu", Span::test_data()),
|
Value::test_string("history_menu"),
|
||||||
];
|
];
|
||||||
|
|
||||||
let span = Span::test_data();
|
let span = Span::test_data();
|
||||||
@ -1061,8 +1063,8 @@ mod test {
|
|||||||
// Menu event
|
// Menu event
|
||||||
let cols = vec!["send".to_string(), "name".to_string()];
|
let cols = vec!["send".to_string(), "name".to_string()];
|
||||||
let vals = vec![
|
let vals = vec![
|
||||||
Value::string("Menu", Span::test_data()),
|
Value::test_string("Menu"),
|
||||||
Value::string("history_menu", Span::test_data()),
|
Value::test_string("history_menu"),
|
||||||
];
|
];
|
||||||
|
|
||||||
let menu_event = Value::Record {
|
let menu_event = Value::Record {
|
||||||
@ -1073,7 +1075,7 @@ mod test {
|
|||||||
|
|
||||||
// Enter event
|
// Enter event
|
||||||
let cols = vec!["send".to_string()];
|
let cols = vec!["send".to_string()];
|
||||||
let vals = vec![Value::string("Enter", Span::test_data())];
|
let vals = vec![Value::test_string("Enter")];
|
||||||
|
|
||||||
let enter_event = Value::Record {
|
let enter_event = Value::Record {
|
||||||
cols,
|
cols,
|
||||||
@ -1114,8 +1116,8 @@ mod test {
|
|||||||
// Menu event
|
// Menu event
|
||||||
let cols = vec!["send".to_string(), "name".to_string()];
|
let cols = vec!["send".to_string(), "name".to_string()];
|
||||||
let vals = vec![
|
let vals = vec![
|
||||||
Value::string("Menu", Span::test_data()),
|
Value::test_string("Menu"),
|
||||||
Value::string("history_menu", Span::test_data()),
|
Value::test_string("history_menu"),
|
||||||
];
|
];
|
||||||
|
|
||||||
let menu_event = Value::Record {
|
let menu_event = Value::Record {
|
||||||
@ -1126,7 +1128,7 @@ mod test {
|
|||||||
|
|
||||||
// Enter event
|
// Enter event
|
||||||
let cols = vec!["send".to_string()];
|
let cols = vec!["send".to_string()];
|
||||||
let vals = vec![Value::string("Enter", Span::test_data())];
|
let vals = vec![Value::test_string("Enter")];
|
||||||
|
|
||||||
let enter_event = Value::Record {
|
let enter_event = Value::Record {
|
||||||
cols,
|
cols,
|
||||||
@ -1154,7 +1156,7 @@ mod test {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_error() {
|
fn test_error() {
|
||||||
let cols = vec!["not_exist".to_string()];
|
let cols = vec!["not_exist".to_string()];
|
||||||
let vals = vec![Value::string("Enter", Span::test_data())];
|
let vals = vec![Value::test_string("Enter")];
|
||||||
|
|
||||||
let span = Span::test_data();
|
let span = Span::test_data();
|
||||||
let b = EventType::try_from_columns(&cols, &vals, &span);
|
let b = EventType::try_from_columns(&cols, &vals, &span);
|
||||||
|
File diff suppressed because it is too large
Load Diff
@ -6,9 +6,10 @@ use nu_protocol::ast::{Argument, Block, Expr, Expression, PipelineElement};
|
|||||||
use nu_protocol::engine::{EngineState, StateWorkingSet};
|
use nu_protocol::engine::{EngineState, StateWorkingSet};
|
||||||
use nu_protocol::{Config, Span};
|
use nu_protocol::{Config, Span};
|
||||||
use reedline::{Highlighter, StyledText};
|
use reedline::{Highlighter, StyledText};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
pub struct NuHighlighter {
|
pub struct NuHighlighter {
|
||||||
pub engine_state: EngineState,
|
pub engine_state: Arc<EngineState>,
|
||||||
pub config: Config,
|
pub config: Config,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -17,10 +18,7 @@ impl Highlighter for NuHighlighter {
|
|||||||
trace!("highlighting: {}", line);
|
trace!("highlighting: {}", line);
|
||||||
|
|
||||||
let mut working_set = StateWorkingSet::new(&self.engine_state);
|
let mut working_set = StateWorkingSet::new(&self.engine_state);
|
||||||
let block = {
|
let block = parse(&mut working_set, None, line.as_bytes(), false);
|
||||||
let (block, _) = parse(&mut working_set, None, line.as_bytes(), false, &[]);
|
|
||||||
block
|
|
||||||
};
|
|
||||||
let (shapes, global_span_offset) = {
|
let (shapes, global_span_offset) = {
|
||||||
let shapes = flatten_block(&working_set, &block);
|
let shapes = flatten_block(&working_set, &block);
|
||||||
(shapes, self.engine_state.next_span_start())
|
(shapes, self.engine_state.next_span_start())
|
||||||
@ -78,29 +76,28 @@ impl Highlighter for NuHighlighter {
|
|||||||
}};
|
}};
|
||||||
}
|
}
|
||||||
|
|
||||||
macro_rules! add_colored_token {
|
let mut add_colored_token = |shape: &FlatShape, text: String| {
|
||||||
($shape:expr, $text:expr) => {
|
output.push((get_shape_color(shape.to_string(), &self.config), text));
|
||||||
output.push((get_shape_color($shape.to_string(), &self.config), $text))
|
};
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
match shape.1 {
|
match shape.1 {
|
||||||
FlatShape::Garbage => add_colored_token!(shape.1, next_token),
|
FlatShape::Garbage => add_colored_token(&shape.1, next_token),
|
||||||
FlatShape::Nothing => add_colored_token!(shape.1, next_token),
|
FlatShape::Nothing => add_colored_token(&shape.1, next_token),
|
||||||
FlatShape::Binary => add_colored_token!(shape.1, next_token),
|
FlatShape::Binary => add_colored_token(&shape.1, next_token),
|
||||||
FlatShape::Bool => add_colored_token!(shape.1, next_token),
|
FlatShape::Bool => add_colored_token(&shape.1, next_token),
|
||||||
FlatShape::Int => add_colored_token!(shape.1, next_token),
|
FlatShape::Int => add_colored_token(&shape.1, next_token),
|
||||||
FlatShape::Float => add_colored_token!(shape.1, next_token),
|
FlatShape::Float => add_colored_token(&shape.1, next_token),
|
||||||
FlatShape::Range => add_colored_token!(shape.1, next_token),
|
FlatShape::Range => add_colored_token(&shape.1, next_token),
|
||||||
FlatShape::InternalCall => add_colored_token!(shape.1, next_token),
|
FlatShape::InternalCall(_) => add_colored_token(&shape.1, next_token),
|
||||||
FlatShape::External => add_colored_token!(shape.1, next_token),
|
FlatShape::External => add_colored_token(&shape.1, next_token),
|
||||||
FlatShape::ExternalArg => add_colored_token!(shape.1, next_token),
|
FlatShape::ExternalArg => add_colored_token(&shape.1, next_token),
|
||||||
FlatShape::Literal => add_colored_token!(shape.1, next_token),
|
FlatShape::Keyword => add_colored_token(&shape.1, next_token),
|
||||||
FlatShape::Operator => add_colored_token!(shape.1, next_token),
|
FlatShape::Literal => add_colored_token(&shape.1, next_token),
|
||||||
FlatShape::Signature => add_colored_token!(shape.1, next_token),
|
FlatShape::Operator => add_colored_token(&shape.1, next_token),
|
||||||
FlatShape::String => add_colored_token!(shape.1, next_token),
|
FlatShape::Signature => add_colored_token(&shape.1, next_token),
|
||||||
FlatShape::StringInterpolation => add_colored_token!(shape.1, next_token),
|
FlatShape::String => add_colored_token(&shape.1, next_token),
|
||||||
FlatShape::DateTime => add_colored_token!(shape.1, next_token),
|
FlatShape::StringInterpolation => add_colored_token(&shape.1, next_token),
|
||||||
|
FlatShape::DateTime => add_colored_token(&shape.1, next_token),
|
||||||
FlatShape::List => {
|
FlatShape::List => {
|
||||||
add_colored_token_with_bracket_highlight!(shape.1, shape.0, next_token)
|
add_colored_token_with_bracket_highlight!(shape.1, shape.0, next_token)
|
||||||
}
|
}
|
||||||
@ -114,17 +111,23 @@ impl Highlighter for NuHighlighter {
|
|||||||
FlatShape::Block => {
|
FlatShape::Block => {
|
||||||
add_colored_token_with_bracket_highlight!(shape.1, shape.0, next_token)
|
add_colored_token_with_bracket_highlight!(shape.1, shape.0, next_token)
|
||||||
}
|
}
|
||||||
|
FlatShape::Closure => {
|
||||||
|
add_colored_token_with_bracket_highlight!(shape.1, shape.0, next_token)
|
||||||
|
}
|
||||||
|
|
||||||
FlatShape::Filepath => add_colored_token!(shape.1, next_token),
|
FlatShape::Filepath => add_colored_token(&shape.1, next_token),
|
||||||
FlatShape::Directory => add_colored_token!(shape.1, next_token),
|
FlatShape::Directory => add_colored_token(&shape.1, next_token),
|
||||||
FlatShape::GlobPattern => add_colored_token!(shape.1, next_token),
|
FlatShape::GlobPattern => add_colored_token(&shape.1, next_token),
|
||||||
FlatShape::Variable => add_colored_token!(shape.1, next_token),
|
FlatShape::Variable(_) | FlatShape::VarDecl(_) => {
|
||||||
FlatShape::Flag => add_colored_token!(shape.1, next_token),
|
add_colored_token(&shape.1, next_token)
|
||||||
FlatShape::Pipe => add_colored_token!(shape.1, next_token),
|
}
|
||||||
FlatShape::And => add_colored_token!(shape.1, next_token),
|
FlatShape::Flag => add_colored_token(&shape.1, next_token),
|
||||||
FlatShape::Or => add_colored_token!(shape.1, next_token),
|
FlatShape::Pipe => add_colored_token(&shape.1, next_token),
|
||||||
FlatShape::Redirection => add_colored_token!(shape.1, next_token),
|
FlatShape::And => add_colored_token(&shape.1, next_token),
|
||||||
FlatShape::Custom(..) => add_colored_token!(shape.1, next_token),
|
FlatShape::Or => add_colored_token(&shape.1, next_token),
|
||||||
|
FlatShape::Redirection => add_colored_token(&shape.1, next_token),
|
||||||
|
FlatShape::Custom(..) => add_colored_token(&shape.1, next_token),
|
||||||
|
FlatShape::MatchPattern => add_colored_token(&shape.1, next_token),
|
||||||
}
|
}
|
||||||
last_seen_span = shape.0.end;
|
last_seen_span = shape.0.end;
|
||||||
}
|
}
|
||||||
@ -233,7 +236,9 @@ fn find_matching_block_end_in_block(
|
|||||||
PipelineElement::Expression(_, e)
|
PipelineElement::Expression(_, e)
|
||||||
| PipelineElement::Redirection(_, _, e)
|
| PipelineElement::Redirection(_, _, e)
|
||||||
| PipelineElement::And(_, e)
|
| PipelineElement::And(_, e)
|
||||||
| PipelineElement::Or(_, e) => {
|
| PipelineElement::Or(_, e)
|
||||||
|
| PipelineElement::SameTargetRedirection { cmd: (_, e), .. }
|
||||||
|
| PipelineElement::SeparateRedirection { out: (_, e), .. } => {
|
||||||
if e.span.contains(global_cursor_offset) {
|
if e.span.contains(global_cursor_offset) {
|
||||||
if let Some(pos) = find_matching_block_end_in_expr(
|
if let Some(pos) = find_matching_block_end_in_expr(
|
||||||
line,
|
line,
|
||||||
@ -306,6 +311,8 @@ fn find_matching_block_end_in_expr(
|
|||||||
Expr::ImportPattern(_) => None,
|
Expr::ImportPattern(_) => None,
|
||||||
Expr::Overlay(_) => None,
|
Expr::Overlay(_) => None,
|
||||||
Expr::Signature(_) => None,
|
Expr::Signature(_) => None,
|
||||||
|
Expr::MatchPattern(_) => None,
|
||||||
|
Expr::MatchBlock(_) => None,
|
||||||
Expr::Nothing => None,
|
Expr::Nothing => None,
|
||||||
Expr::Garbage => None,
|
Expr::Garbage => None,
|
||||||
|
|
||||||
@ -352,6 +359,7 @@ fn find_matching_block_end_in_expr(
|
|||||||
let opt_expr = match arg {
|
let opt_expr = match arg {
|
||||||
Argument::Named((_, _, opt_expr)) => opt_expr.as_ref(),
|
Argument::Named((_, _, opt_expr)) => opt_expr.as_ref(),
|
||||||
Argument::Positional(inner_expr) => Some(inner_expr),
|
Argument::Positional(inner_expr) => Some(inner_expr),
|
||||||
|
Argument::Unknown(inner_expr) => Some(inner_expr),
|
||||||
};
|
};
|
||||||
|
|
||||||
if let Some(inner_expr) = opt_expr {
|
if let Some(inner_expr) = opt_expr {
|
||||||
|
@ -1,15 +1,16 @@
|
|||||||
use crate::repl::eval_hook;
|
use nu_command::hook::eval_hook;
|
||||||
use nu_engine::eval_block;
|
use nu_engine::{eval_block, eval_block_with_early_return};
|
||||||
use nu_parser::{escape_quote_string, lex, parse, unescape_unquote_string, Token, TokenContents};
|
use nu_parser::{escape_quote_string, lex, parse, unescape_unquote_string, Token, TokenContents};
|
||||||
use nu_protocol::engine::StateWorkingSet;
|
use nu_protocol::engine::StateWorkingSet;
|
||||||
use nu_protocol::CliError;
|
|
||||||
use nu_protocol::{
|
use nu_protocol::{
|
||||||
engine::{EngineState, Stack},
|
engine::{EngineState, Stack},
|
||||||
print_if_stream, PipelineData, ShellError, Span, Value,
|
print_if_stream, PipelineData, ShellError, Span, Value,
|
||||||
};
|
};
|
||||||
|
use nu_protocol::{report_error, report_error_new};
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
use nu_utils::enable_vt_processing;
|
use nu_utils::enable_vt_processing;
|
||||||
use std::path::{Path, PathBuf};
|
use nu_utils::utils::perf;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
// This will collect environment variables from std::env and adds them to a stack.
|
// This will collect environment variables from std::env and adds them to a stack.
|
||||||
//
|
//
|
||||||
@ -43,7 +44,7 @@ fn gather_env_vars(
|
|||||||
report_error(
|
report_error(
|
||||||
&working_set,
|
&working_set,
|
||||||
&ShellError::GenericError(
|
&ShellError::GenericError(
|
||||||
format!("Environment variable was not captured: {}", env_str),
|
format!("Environment variable was not captured: {env_str}"),
|
||||||
"".to_string(),
|
"".to_string(),
|
||||||
None,
|
None,
|
||||||
Some(msg.into()),
|
Some(msg.into()),
|
||||||
@ -79,8 +80,7 @@ fn gather_env_vars(
|
|||||||
"".to_string(),
|
"".to_string(),
|
||||||
None,
|
None,
|
||||||
Some(format!(
|
Some(format!(
|
||||||
"Retrieving current directory failed: {:?} not a valid utf-8 path",
|
"Retrieving current directory failed: {init_cwd:?} not a valid utf-8 path"
|
||||||
init_cwd
|
|
||||||
)),
|
)),
|
||||||
Vec::new(),
|
Vec::new(),
|
||||||
),
|
),
|
||||||
@ -113,7 +113,8 @@ fn gather_env_vars(
|
|||||||
span,
|
span,
|
||||||
}) = parts.get(0)
|
}) = parts.get(0)
|
||||||
{
|
{
|
||||||
let bytes = engine_state.get_span_contents(span);
|
let mut working_set = StateWorkingSet::new(engine_state);
|
||||||
|
let bytes = working_set.get_span_contents(*span);
|
||||||
|
|
||||||
if bytes.len() < 2 {
|
if bytes.len() < 2 {
|
||||||
report_capture_error(
|
report_capture_error(
|
||||||
@ -125,9 +126,12 @@ fn gather_env_vars(
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
let (bytes, parse_error) = unescape_unquote_string(bytes, *span);
|
let (bytes, err) = unescape_unquote_string(bytes, *span);
|
||||||
|
if let Some(err) = err {
|
||||||
|
working_set.error(err);
|
||||||
|
}
|
||||||
|
|
||||||
if parse_error.is_some() {
|
if working_set.parse_errors.first().is_some() {
|
||||||
report_capture_error(
|
report_capture_error(
|
||||||
engine_state,
|
engine_state,
|
||||||
&String::from_utf8_lossy(contents),
|
&String::from_utf8_lossy(contents),
|
||||||
@ -153,7 +157,8 @@ fn gather_env_vars(
|
|||||||
span,
|
span,
|
||||||
}) = parts.get(2)
|
}) = parts.get(2)
|
||||||
{
|
{
|
||||||
let bytes = engine_state.get_span_contents(span);
|
let mut working_set = StateWorkingSet::new(engine_state);
|
||||||
|
let bytes = working_set.get_span_contents(*span);
|
||||||
|
|
||||||
if bytes.len() < 2 {
|
if bytes.len() < 2 {
|
||||||
report_capture_error(
|
report_capture_error(
|
||||||
@ -165,9 +170,12 @@ fn gather_env_vars(
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
let (bytes, parse_error) = unescape_unquote_string(bytes, *span);
|
let (bytes, err) = unescape_unquote_string(bytes, *span);
|
||||||
|
if let Some(err) = err {
|
||||||
|
working_set.error(err);
|
||||||
|
}
|
||||||
|
|
||||||
if parse_error.is_some() {
|
if working_set.parse_errors.first().is_some() {
|
||||||
report_capture_error(
|
report_capture_error(
|
||||||
engine_state,
|
engine_state,
|
||||||
&String::from_utf8_lossy(contents),
|
&String::from_utf8_lossy(contents),
|
||||||
@ -203,19 +211,21 @@ pub fn eval_source(
|
|||||||
source: &[u8],
|
source: &[u8],
|
||||||
fname: &str,
|
fname: &str,
|
||||||
input: PipelineData,
|
input: PipelineData,
|
||||||
|
allow_return: bool,
|
||||||
) -> bool {
|
) -> bool {
|
||||||
|
let start_time = std::time::Instant::now();
|
||||||
|
|
||||||
let (block, delta) = {
|
let (block, delta) = {
|
||||||
let mut working_set = StateWorkingSet::new(engine_state);
|
let mut working_set = StateWorkingSet::new(engine_state);
|
||||||
let (output, err) = parse(
|
let output = parse(
|
||||||
&mut working_set,
|
&mut working_set,
|
||||||
Some(fname), // format!("entry #{}", entry_num)
|
Some(fname), // format!("entry #{}", entry_num)
|
||||||
source,
|
source,
|
||||||
false,
|
false,
|
||||||
&[],
|
|
||||||
);
|
);
|
||||||
if let Some(err) = err {
|
if let Some(err) = working_set.parse_errors.first() {
|
||||||
set_last_exit_code(stack, 1);
|
set_last_exit_code(stack, 1);
|
||||||
report_error(&working_set, &err);
|
report_error(&working_set, err);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -228,7 +238,13 @@ pub fn eval_source(
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
match eval_block(engine_state, stack, &block, input, false, false) {
|
let b = if allow_return {
|
||||||
|
eval_block_with_early_return(engine_state, stack, &block, input, false, false)
|
||||||
|
} else {
|
||||||
|
eval_block(engine_state, stack, &block, input, false, false)
|
||||||
|
};
|
||||||
|
|
||||||
|
match b {
|
||||||
Ok(pipeline_data) => {
|
Ok(pipeline_data) => {
|
||||||
let config = engine_state.get_config();
|
let config = engine_state.get_config();
|
||||||
let result;
|
let result;
|
||||||
@ -282,6 +298,14 @@ pub fn eval_source(
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
perf(
|
||||||
|
&format!("eval_source {}", &fname),
|
||||||
|
start_time,
|
||||||
|
file!(),
|
||||||
|
line!(),
|
||||||
|
column!(),
|
||||||
|
engine_state.get_config().use_ansi_coloring,
|
||||||
|
);
|
||||||
|
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
@ -293,51 +317,6 @@ fn set_last_exit_code(stack: &mut Stack, exit_code: i64) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn report_error(
|
|
||||||
working_set: &StateWorkingSet,
|
|
||||||
error: &(dyn miette::Diagnostic + Send + Sync + 'static),
|
|
||||||
) {
|
|
||||||
eprintln!("Error: {:?}", CliError(error, working_set));
|
|
||||||
// reset vt processing, aka ansi because illbehaved externals can break it
|
|
||||||
#[cfg(windows)]
|
|
||||||
{
|
|
||||||
let _ = nu_utils::enable_vt_processing();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn report_error_new(
|
|
||||||
engine_state: &EngineState,
|
|
||||||
error: &(dyn miette::Diagnostic + Send + Sync + 'static),
|
|
||||||
) {
|
|
||||||
let working_set = StateWorkingSet::new(engine_state);
|
|
||||||
|
|
||||||
report_error(&working_set, error);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_init_cwd() -> PathBuf {
|
|
||||||
match std::env::current_dir() {
|
|
||||||
Ok(cwd) => cwd,
|
|
||||||
Err(_) => match std::env::var("PWD") {
|
|
||||||
Ok(cwd) => PathBuf::from(cwd),
|
|
||||||
Err(_) => match nu_path::home_dir() {
|
|
||||||
Some(cwd) => cwd,
|
|
||||||
None => PathBuf::new(),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_guaranteed_cwd(engine_state: &EngineState, stack: &Stack) -> PathBuf {
|
|
||||||
match nu_engine::env::current_dir(engine_state, stack) {
|
|
||||||
Ok(p) => p,
|
|
||||||
Err(e) => {
|
|
||||||
let working_set = StateWorkingSet::new(engine_state);
|
|
||||||
report_error(&working_set, &e);
|
|
||||||
get_init_cwd()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
@ -1,17 +1,24 @@
|
|||||||
use nu_parser::{parse, ParseError};
|
use nu_parser::parse;
|
||||||
use nu_protocol::engine::{EngineState, StateWorkingSet};
|
use nu_protocol::{
|
||||||
|
engine::{EngineState, StateWorkingSet},
|
||||||
|
ParseError,
|
||||||
|
};
|
||||||
use reedline::{ValidationResult, Validator};
|
use reedline::{ValidationResult, Validator};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
pub struct NuValidator {
|
pub struct NuValidator {
|
||||||
pub engine_state: EngineState,
|
pub engine_state: Arc<EngineState>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Validator for NuValidator {
|
impl Validator for NuValidator {
|
||||||
fn validate(&self, line: &str) -> ValidationResult {
|
fn validate(&self, line: &str) -> ValidationResult {
|
||||||
let mut working_set = StateWorkingSet::new(&self.engine_state);
|
let mut working_set = StateWorkingSet::new(&self.engine_state);
|
||||||
let (_, err) = parse(&mut working_set, None, line.as_bytes(), false, &[]);
|
parse(&mut working_set, None, line.as_bytes(), false);
|
||||||
|
|
||||||
if matches!(err, Some(ParseError::UnexpectedEof(..))) {
|
if matches!(
|
||||||
|
working_set.parse_errors.first(),
|
||||||
|
Some(ParseError::UnexpectedEof(..))
|
||||||
|
) {
|
||||||
ValidationResult::Incomplete
|
ValidationResult::Incomplete
|
||||||
} else {
|
} else {
|
||||||
ValidationResult::Complete
|
ValidationResult::Complete
|
||||||
|
@ -34,6 +34,26 @@ fn completer_strings() -> NuCompleter {
|
|||||||
NuCompleter::new(std::sync::Arc::new(engine), stack)
|
NuCompleter::new(std::sync::Arc::new(engine), stack)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[fixture]
|
||||||
|
fn extern_completer() -> NuCompleter {
|
||||||
|
// Create a new engine
|
||||||
|
let (dir, _, mut engine, mut stack) = new_engine();
|
||||||
|
|
||||||
|
// Add record value as example
|
||||||
|
let record = r#"
|
||||||
|
def animals [] { [ "cat", "dog", "eel" ] }
|
||||||
|
extern spam [
|
||||||
|
animal: string@animals
|
||||||
|
--foo (-f): string@animals
|
||||||
|
-b: string@animals
|
||||||
|
]
|
||||||
|
"#;
|
||||||
|
assert!(support::merge_input(record.as_bytes(), &mut engine, &mut stack, dir).is_ok());
|
||||||
|
|
||||||
|
// Instantiate a new completer
|
||||||
|
NuCompleter::new(std::sync::Arc::new(engine), stack)
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn variables_dollar_sign_with_varialblecompletion() {
|
fn variables_dollar_sign_with_varialblecompletion() {
|
||||||
let (_, _, engine, stack) = new_engine();
|
let (_, _, engine, stack) = new_engine();
|
||||||
@ -89,7 +109,7 @@ fn dotnu_completions() {
|
|||||||
// Create a new engine
|
// Create a new engine
|
||||||
let (_, _, engine, stack) = new_engine();
|
let (_, _, engine, stack) = new_engine();
|
||||||
|
|
||||||
// Instatiate a new completer
|
// Instantiate a new completer
|
||||||
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
|
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
|
||||||
|
|
||||||
// Test source completion
|
// Test source completion
|
||||||
@ -149,20 +169,20 @@ fn file_completions() {
|
|||||||
// Create a new engine
|
// Create a new engine
|
||||||
let (dir, dir_str, engine, stack) = new_engine();
|
let (dir, dir_str, engine, stack) = new_engine();
|
||||||
|
|
||||||
// Instatiate a new completer
|
// Instantiate a new completer
|
||||||
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
|
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
|
||||||
|
|
||||||
// Test completions for the current folder
|
// Test completions for the current folder
|
||||||
let target_dir = format!("cp {}", dir_str);
|
let target_dir = format!("cp {dir_str}");
|
||||||
let suggestions = completer.complete(&target_dir, target_dir.len());
|
let suggestions = completer.complete(&target_dir, target_dir.len());
|
||||||
|
|
||||||
// Create the expected values
|
// Create the expected values
|
||||||
let expected_paths: Vec<String> = vec![
|
let expected_paths: Vec<String> = vec![
|
||||||
|
folder(dir.join("another")),
|
||||||
|
file(dir.join("custom_completion.nu")),
|
||||||
file(dir.join("nushell")),
|
file(dir.join("nushell")),
|
||||||
folder(dir.join("test_a")),
|
folder(dir.join("test_a")),
|
||||||
folder(dir.join("test_b")),
|
folder(dir.join("test_b")),
|
||||||
folder(dir.join("another")),
|
|
||||||
file(dir.join("custom_completion.nu")),
|
|
||||||
file(dir.join(".hidden_file")),
|
file(dir.join(".hidden_file")),
|
||||||
folder(dir.join(".hidden_folder")),
|
folder(dir.join(".hidden_folder")),
|
||||||
];
|
];
|
||||||
@ -192,21 +212,21 @@ fn command_ls_with_filecompletion() {
|
|||||||
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
let expected_paths: Vec<String> = vec![
|
let expected_paths: Vec<String> = vec![
|
||||||
|
"another\\".to_string(),
|
||||||
|
"custom_completion.nu".to_string(),
|
||||||
"nushell".to_string(),
|
"nushell".to_string(),
|
||||||
"test_a\\".to_string(),
|
"test_a\\".to_string(),
|
||||||
"test_b\\".to_string(),
|
"test_b\\".to_string(),
|
||||||
"another\\".to_string(),
|
|
||||||
"custom_completion.nu".to_string(),
|
|
||||||
".hidden_file".to_string(),
|
".hidden_file".to_string(),
|
||||||
".hidden_folder\\".to_string(),
|
".hidden_folder\\".to_string(),
|
||||||
];
|
];
|
||||||
#[cfg(not(windows))]
|
#[cfg(not(windows))]
|
||||||
let expected_paths: Vec<String> = vec![
|
let expected_paths: Vec<String> = vec![
|
||||||
|
"another/".to_string(),
|
||||||
|
"custom_completion.nu".to_string(),
|
||||||
"nushell".to_string(),
|
"nushell".to_string(),
|
||||||
"test_a/".to_string(),
|
"test_a/".to_string(),
|
||||||
"test_b/".to_string(),
|
"test_b/".to_string(),
|
||||||
"another/".to_string(),
|
|
||||||
"custom_completion.nu".to_string(),
|
|
||||||
".hidden_file".to_string(),
|
".hidden_file".to_string(),
|
||||||
".hidden_folder/".to_string(),
|
".hidden_folder/".to_string(),
|
||||||
];
|
];
|
||||||
@ -224,21 +244,21 @@ fn command_open_with_filecompletion() {
|
|||||||
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
let expected_paths: Vec<String> = vec![
|
let expected_paths: Vec<String> = vec![
|
||||||
|
"another\\".to_string(),
|
||||||
|
"custom_completion.nu".to_string(),
|
||||||
"nushell".to_string(),
|
"nushell".to_string(),
|
||||||
"test_a\\".to_string(),
|
"test_a\\".to_string(),
|
||||||
"test_b\\".to_string(),
|
"test_b\\".to_string(),
|
||||||
"another\\".to_string(),
|
|
||||||
"custom_completion.nu".to_string(),
|
|
||||||
".hidden_file".to_string(),
|
".hidden_file".to_string(),
|
||||||
".hidden_folder\\".to_string(),
|
".hidden_folder\\".to_string(),
|
||||||
];
|
];
|
||||||
#[cfg(not(windows))]
|
#[cfg(not(windows))]
|
||||||
let expected_paths: Vec<String> = vec![
|
let expected_paths: Vec<String> = vec![
|
||||||
|
"another/".to_string(),
|
||||||
|
"custom_completion.nu".to_string(),
|
||||||
"nushell".to_string(),
|
"nushell".to_string(),
|
||||||
"test_a/".to_string(),
|
"test_a/".to_string(),
|
||||||
"test_b/".to_string(),
|
"test_b/".to_string(),
|
||||||
"another/".to_string(),
|
|
||||||
"custom_completion.nu".to_string(),
|
|
||||||
".hidden_file".to_string(),
|
".hidden_file".to_string(),
|
||||||
".hidden_folder/".to_string(),
|
".hidden_folder/".to_string(),
|
||||||
];
|
];
|
||||||
@ -257,21 +277,21 @@ fn command_rm_with_globcompletion() {
|
|||||||
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
let expected_paths: Vec<String> = vec![
|
let expected_paths: Vec<String> = vec![
|
||||||
|
"another\\".to_string(),
|
||||||
|
"custom_completion.nu".to_string(),
|
||||||
"nushell".to_string(),
|
"nushell".to_string(),
|
||||||
"test_a\\".to_string(),
|
"test_a\\".to_string(),
|
||||||
"test_b\\".to_string(),
|
"test_b\\".to_string(),
|
||||||
"another\\".to_string(),
|
|
||||||
"custom_completion.nu".to_string(),
|
|
||||||
".hidden_file".to_string(),
|
".hidden_file".to_string(),
|
||||||
".hidden_folder\\".to_string(),
|
".hidden_folder\\".to_string(),
|
||||||
];
|
];
|
||||||
#[cfg(not(windows))]
|
#[cfg(not(windows))]
|
||||||
let expected_paths: Vec<String> = vec![
|
let expected_paths: Vec<String> = vec![
|
||||||
|
"another/".to_string(),
|
||||||
|
"custom_completion.nu".to_string(),
|
||||||
"nushell".to_string(),
|
"nushell".to_string(),
|
||||||
"test_a/".to_string(),
|
"test_a/".to_string(),
|
||||||
"test_b/".to_string(),
|
"test_b/".to_string(),
|
||||||
"another/".to_string(),
|
|
||||||
"custom_completion.nu".to_string(),
|
|
||||||
".hidden_file".to_string(),
|
".hidden_file".to_string(),
|
||||||
".hidden_folder/".to_string(),
|
".hidden_folder/".to_string(),
|
||||||
];
|
];
|
||||||
@ -290,21 +310,21 @@ fn command_cp_with_globcompletion() {
|
|||||||
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
let expected_paths: Vec<String> = vec![
|
let expected_paths: Vec<String> = vec![
|
||||||
|
"another\\".to_string(),
|
||||||
|
"custom_completion.nu".to_string(),
|
||||||
"nushell".to_string(),
|
"nushell".to_string(),
|
||||||
"test_a\\".to_string(),
|
"test_a\\".to_string(),
|
||||||
"test_b\\".to_string(),
|
"test_b\\".to_string(),
|
||||||
"another\\".to_string(),
|
|
||||||
"custom_completion.nu".to_string(),
|
|
||||||
".hidden_file".to_string(),
|
".hidden_file".to_string(),
|
||||||
".hidden_folder\\".to_string(),
|
".hidden_folder\\".to_string(),
|
||||||
];
|
];
|
||||||
#[cfg(not(windows))]
|
#[cfg(not(windows))]
|
||||||
let expected_paths: Vec<String> = vec![
|
let expected_paths: Vec<String> = vec![
|
||||||
|
"another/".to_string(),
|
||||||
|
"custom_completion.nu".to_string(),
|
||||||
"nushell".to_string(),
|
"nushell".to_string(),
|
||||||
"test_a/".to_string(),
|
"test_a/".to_string(),
|
||||||
"test_b/".to_string(),
|
"test_b/".to_string(),
|
||||||
"another/".to_string(),
|
|
||||||
"custom_completion.nu".to_string(),
|
|
||||||
".hidden_file".to_string(),
|
".hidden_file".to_string(),
|
||||||
".hidden_folder/".to_string(),
|
".hidden_folder/".to_string(),
|
||||||
];
|
];
|
||||||
@ -323,21 +343,21 @@ fn command_save_with_filecompletion() {
|
|||||||
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
let expected_paths: Vec<String> = vec![
|
let expected_paths: Vec<String> = vec![
|
||||||
|
"another\\".to_string(),
|
||||||
|
"custom_completion.nu".to_string(),
|
||||||
"nushell".to_string(),
|
"nushell".to_string(),
|
||||||
"test_a\\".to_string(),
|
"test_a\\".to_string(),
|
||||||
"test_b\\".to_string(),
|
"test_b\\".to_string(),
|
||||||
"another\\".to_string(),
|
|
||||||
"custom_completion.nu".to_string(),
|
|
||||||
".hidden_file".to_string(),
|
".hidden_file".to_string(),
|
||||||
".hidden_folder\\".to_string(),
|
".hidden_folder\\".to_string(),
|
||||||
];
|
];
|
||||||
#[cfg(not(windows))]
|
#[cfg(not(windows))]
|
||||||
let expected_paths: Vec<String> = vec![
|
let expected_paths: Vec<String> = vec![
|
||||||
|
"another/".to_string(),
|
||||||
|
"custom_completion.nu".to_string(),
|
||||||
"nushell".to_string(),
|
"nushell".to_string(),
|
||||||
"test_a/".to_string(),
|
"test_a/".to_string(),
|
||||||
"test_b/".to_string(),
|
"test_b/".to_string(),
|
||||||
"another/".to_string(),
|
|
||||||
"custom_completion.nu".to_string(),
|
|
||||||
".hidden_file".to_string(),
|
".hidden_file".to_string(),
|
||||||
".hidden_folder/".to_string(),
|
".hidden_folder/".to_string(),
|
||||||
];
|
];
|
||||||
@ -356,21 +376,21 @@ fn command_touch_with_filecompletion() {
|
|||||||
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
let expected_paths: Vec<String> = vec![
|
let expected_paths: Vec<String> = vec![
|
||||||
|
"another\\".to_string(),
|
||||||
|
"custom_completion.nu".to_string(),
|
||||||
"nushell".to_string(),
|
"nushell".to_string(),
|
||||||
"test_a\\".to_string(),
|
"test_a\\".to_string(),
|
||||||
"test_b\\".to_string(),
|
"test_b\\".to_string(),
|
||||||
"another\\".to_string(),
|
|
||||||
"custom_completion.nu".to_string(),
|
|
||||||
".hidden_file".to_string(),
|
".hidden_file".to_string(),
|
||||||
".hidden_folder\\".to_string(),
|
".hidden_folder\\".to_string(),
|
||||||
];
|
];
|
||||||
#[cfg(not(windows))]
|
#[cfg(not(windows))]
|
||||||
let expected_paths: Vec<String> = vec![
|
let expected_paths: Vec<String> = vec![
|
||||||
|
"another/".to_string(),
|
||||||
|
"custom_completion.nu".to_string(),
|
||||||
"nushell".to_string(),
|
"nushell".to_string(),
|
||||||
"test_a/".to_string(),
|
"test_a/".to_string(),
|
||||||
"test_b/".to_string(),
|
"test_b/".to_string(),
|
||||||
"another/".to_string(),
|
|
||||||
"custom_completion.nu".to_string(),
|
|
||||||
".hidden_file".to_string(),
|
".hidden_file".to_string(),
|
||||||
".hidden_folder/".to_string(),
|
".hidden_folder/".to_string(),
|
||||||
];
|
];
|
||||||
@ -389,21 +409,21 @@ fn command_watch_with_filecompletion() {
|
|||||||
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
let expected_paths: Vec<String> = vec![
|
let expected_paths: Vec<String> = vec![
|
||||||
|
"another\\".to_string(),
|
||||||
|
"custom_completion.nu".to_string(),
|
||||||
"nushell".to_string(),
|
"nushell".to_string(),
|
||||||
"test_a\\".to_string(),
|
"test_a\\".to_string(),
|
||||||
"test_b\\".to_string(),
|
"test_b\\".to_string(),
|
||||||
"another\\".to_string(),
|
|
||||||
"custom_completion.nu".to_string(),
|
|
||||||
".hidden_file".to_string(),
|
".hidden_file".to_string(),
|
||||||
".hidden_folder\\".to_string(),
|
".hidden_folder\\".to_string(),
|
||||||
];
|
];
|
||||||
#[cfg(not(windows))]
|
#[cfg(not(windows))]
|
||||||
let expected_paths: Vec<String> = vec![
|
let expected_paths: Vec<String> = vec![
|
||||||
|
"another/".to_string(),
|
||||||
|
"custom_completion.nu".to_string(),
|
||||||
"nushell".to_string(),
|
"nushell".to_string(),
|
||||||
"test_a/".to_string(),
|
"test_a/".to_string(),
|
||||||
"test_b/".to_string(),
|
"test_b/".to_string(),
|
||||||
"another/".to_string(),
|
|
||||||
"custom_completion.nu".to_string(),
|
|
||||||
".hidden_file".to_string(),
|
".hidden_file".to_string(),
|
||||||
".hidden_folder/".to_string(),
|
".hidden_folder/".to_string(),
|
||||||
];
|
];
|
||||||
@ -424,6 +444,7 @@ fn file_completion_quoted() {
|
|||||||
"`te st.txt`".to_string(),
|
"`te st.txt`".to_string(),
|
||||||
"`te#st.txt`".to_string(),
|
"`te#st.txt`".to_string(),
|
||||||
"`te'st.txt`".to_string(),
|
"`te'st.txt`".to_string(),
|
||||||
|
"`te(st).txt`".to_string(),
|
||||||
];
|
];
|
||||||
|
|
||||||
match_suggestions(expected_paths, suggestions)
|
match_suggestions(expected_paths, suggestions)
|
||||||
@ -434,12 +455,12 @@ fn flag_completions() {
|
|||||||
// Create a new engine
|
// Create a new engine
|
||||||
let (_, _, engine, stack) = new_engine();
|
let (_, _, engine, stack) = new_engine();
|
||||||
|
|
||||||
// Instatiate a new completer
|
// Instantiate a new completer
|
||||||
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
|
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
|
||||||
// Test completions for the 'ls' flags
|
// Test completions for the 'ls' flags
|
||||||
let suggestions = completer.complete("ls -", 4);
|
let suggestions = completer.complete("ls -", 4);
|
||||||
|
|
||||||
assert_eq!(14, suggestions.len());
|
assert_eq!(16, suggestions.len());
|
||||||
|
|
||||||
let expected: Vec<String> = vec![
|
let expected: Vec<String> = vec![
|
||||||
"--all".into(),
|
"--all".into(),
|
||||||
@ -448,6 +469,7 @@ fn flag_completions() {
|
|||||||
"--full-paths".into(),
|
"--full-paths".into(),
|
||||||
"--help".into(),
|
"--help".into(),
|
||||||
"--long".into(),
|
"--long".into(),
|
||||||
|
"--mime-type".into(),
|
||||||
"--short-names".into(),
|
"--short-names".into(),
|
||||||
"-D".into(),
|
"-D".into(),
|
||||||
"-a".into(),
|
"-a".into(),
|
||||||
@ -455,6 +477,7 @@ fn flag_completions() {
|
|||||||
"-f".into(),
|
"-f".into(),
|
||||||
"-h".into(),
|
"-h".into(),
|
||||||
"-l".into(),
|
"-l".into(),
|
||||||
|
"-m".into(),
|
||||||
"-s".into(),
|
"-s".into(),
|
||||||
];
|
];
|
||||||
|
|
||||||
@ -467,18 +490,18 @@ fn folder_with_directorycompletions() {
|
|||||||
// Create a new engine
|
// Create a new engine
|
||||||
let (dir, dir_str, engine, stack) = new_engine();
|
let (dir, dir_str, engine, stack) = new_engine();
|
||||||
|
|
||||||
// Instatiate a new completer
|
// Instantiate a new completer
|
||||||
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
|
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
|
||||||
|
|
||||||
// Test completions for the current folder
|
// Test completions for the current folder
|
||||||
let target_dir = format!("cd {}", dir_str);
|
let target_dir = format!("cd {dir_str}");
|
||||||
let suggestions = completer.complete(&target_dir, target_dir.len());
|
let suggestions = completer.complete(&target_dir, target_dir.len());
|
||||||
|
|
||||||
// Create the expected values
|
// Create the expected values
|
||||||
let expected_paths: Vec<String> = vec![
|
let expected_paths: Vec<String> = vec![
|
||||||
|
folder(dir.join("another")),
|
||||||
folder(dir.join("test_a")),
|
folder(dir.join("test_a")),
|
||||||
folder(dir.join("test_b")),
|
folder(dir.join("test_b")),
|
||||||
folder(dir.join("another")),
|
|
||||||
folder(dir.join(".hidden_folder")),
|
folder(dir.join(".hidden_folder")),
|
||||||
];
|
];
|
||||||
|
|
||||||
@ -495,23 +518,28 @@ fn variables_completions() {
|
|||||||
let record = "let actor = { name: 'Tom Hardy', age: 44 }";
|
let record = "let actor = { name: 'Tom Hardy', age: 44 }";
|
||||||
assert!(support::merge_input(record.as_bytes(), &mut engine, &mut stack, dir).is_ok());
|
assert!(support::merge_input(record.as_bytes(), &mut engine, &mut stack, dir).is_ok());
|
||||||
|
|
||||||
// Instatiate a new completer
|
// Instantiate a new completer
|
||||||
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
|
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
|
||||||
|
|
||||||
// Test completions for $nu
|
// Test completions for $nu
|
||||||
let suggestions = completer.complete("$nu.", 4);
|
let suggestions = completer.complete("$nu.", 4);
|
||||||
|
|
||||||
assert_eq!(9, suggestions.len());
|
assert_eq!(14, suggestions.len());
|
||||||
|
|
||||||
let expected: Vec<String> = vec![
|
let expected: Vec<String> = vec![
|
||||||
"config-path".into(),
|
"config-path".into(),
|
||||||
|
"current-exe".into(),
|
||||||
|
"default-config-dir".into(),
|
||||||
"env-path".into(),
|
"env-path".into(),
|
||||||
"history-path".into(),
|
"history-path".into(),
|
||||||
"home-path".into(),
|
"home-path".into(),
|
||||||
|
"is-interactive".into(),
|
||||||
|
"is-login".into(),
|
||||||
"loginshell-path".into(),
|
"loginshell-path".into(),
|
||||||
"os-info".into(),
|
"os-info".into(),
|
||||||
"pid".into(),
|
"pid".into(),
|
||||||
"scope".into(),
|
"scope".into(),
|
||||||
|
"startup-time".into(),
|
||||||
"temp-path".into(),
|
"temp-path".into(),
|
||||||
];
|
];
|
||||||
|
|
||||||
@ -528,6 +556,100 @@ fn variables_completions() {
|
|||||||
// Match results
|
// Match results
|
||||||
match_suggestions(expected, suggestions);
|
match_suggestions(expected, suggestions);
|
||||||
|
|
||||||
|
// Test completions for $nu.os-info
|
||||||
|
let suggestions = completer.complete("$nu.os-info.", 12);
|
||||||
|
assert_eq!(4, suggestions.len());
|
||||||
|
let expected: Vec<String> = vec![
|
||||||
|
"arch".into(),
|
||||||
|
"family".into(),
|
||||||
|
"kernel_version".into(),
|
||||||
|
"name".into(),
|
||||||
|
];
|
||||||
|
// Match results
|
||||||
|
match_suggestions(expected, suggestions);
|
||||||
|
|
||||||
|
// Test completions for $nu.scope
|
||||||
|
let suggestions = completer.complete("$nu.scope.", 10);
|
||||||
|
assert_eq!(5, suggestions.len());
|
||||||
|
let expected: Vec<String> = vec![
|
||||||
|
"aliases".into(),
|
||||||
|
"commands".into(),
|
||||||
|
"engine_state".into(),
|
||||||
|
"modules".into(),
|
||||||
|
"vars".into(),
|
||||||
|
];
|
||||||
|
// Match results
|
||||||
|
match_suggestions(expected, suggestions);
|
||||||
|
|
||||||
|
// Test completions for $nu.scope.commands
|
||||||
|
let suggestions = completer.complete("$nu.scope.commands.", 19);
|
||||||
|
assert_eq!(15, suggestions.len());
|
||||||
|
let expected: Vec<String> = vec![
|
||||||
|
"category".into(),
|
||||||
|
"creates_scope".into(),
|
||||||
|
"examples".into(),
|
||||||
|
"extra_usage".into(),
|
||||||
|
"is_builtin".into(),
|
||||||
|
"is_custom".into(),
|
||||||
|
"is_extern".into(),
|
||||||
|
"is_keyword".into(),
|
||||||
|
"is_plugin".into(),
|
||||||
|
"is_sub".into(),
|
||||||
|
"module_name".into(),
|
||||||
|
"name".into(),
|
||||||
|
"search_terms".into(),
|
||||||
|
"signatures".into(),
|
||||||
|
"usage".into(),
|
||||||
|
];
|
||||||
|
// Match results
|
||||||
|
match_suggestions(expected, suggestions);
|
||||||
|
|
||||||
|
// Test completions for $nu.scope.commands.signatures
|
||||||
|
let suggestions = completer.complete("$nu.scope.commands.signatures.", 30);
|
||||||
|
assert_eq!(17, suggestions.len());
|
||||||
|
let expected: Vec<String> = vec![
|
||||||
|
"any".into(),
|
||||||
|
"binary".into(),
|
||||||
|
"bool".into(),
|
||||||
|
"datetime".into(),
|
||||||
|
"duration".into(),
|
||||||
|
"filesize".into(),
|
||||||
|
"int".into(),
|
||||||
|
"list<any>".into(),
|
||||||
|
"list<binary>".into(),
|
||||||
|
"list<number>".into(),
|
||||||
|
"list<string>".into(),
|
||||||
|
"nothing".into(),
|
||||||
|
"number".into(),
|
||||||
|
"range".into(),
|
||||||
|
"record".into(),
|
||||||
|
"string".into(),
|
||||||
|
"table".into(),
|
||||||
|
];
|
||||||
|
// Match results
|
||||||
|
match_suggestions(expected, suggestions);
|
||||||
|
|
||||||
|
// Test completions for $nu.scope.engine_state
|
||||||
|
let suggestions = completer.complete("$nu.scope.engine_state.", 23);
|
||||||
|
assert_eq!(6, suggestions.len());
|
||||||
|
let expected: Vec<String> = vec![
|
||||||
|
"num_blocks".into(),
|
||||||
|
"num_decls".into(),
|
||||||
|
"num_env_vars".into(),
|
||||||
|
"num_modules".into(),
|
||||||
|
"num_vars".into(),
|
||||||
|
"source_bytes".into(),
|
||||||
|
];
|
||||||
|
// Match results
|
||||||
|
match_suggestions(expected, suggestions);
|
||||||
|
|
||||||
|
// Test completions for $nu.scope.vars
|
||||||
|
let suggestions = completer.complete("$nu.scope.vars.", 15);
|
||||||
|
assert_eq!(3, suggestions.len());
|
||||||
|
let expected: Vec<String> = vec!["name".into(), "type".into(), "value".into()];
|
||||||
|
// Match results
|
||||||
|
match_suggestions(expected, suggestions);
|
||||||
|
|
||||||
// Test completions for custom var
|
// Test completions for custom var
|
||||||
let suggestions = completer.complete("$actor.", 7);
|
let suggestions = completer.complete("$actor.", 7);
|
||||||
|
|
||||||
@ -551,9 +673,12 @@ fn variables_completions() {
|
|||||||
// Test completions for $env
|
// Test completions for $env
|
||||||
let suggestions = completer.complete("$env.", 5);
|
let suggestions = completer.complete("$env.", 5);
|
||||||
|
|
||||||
assert_eq!(2, suggestions.len());
|
assert_eq!(3, suggestions.len());
|
||||||
|
|
||||||
let expected: Vec<String> = vec!["PWD".into(), "TEST".into()];
|
#[cfg(windows)]
|
||||||
|
let expected: Vec<String> = vec!["PWD".into(), "Path".into(), "TEST".into()];
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
let expected: Vec<String> = vec!["PATH".into(), "PWD".into(), "TEST".into()];
|
||||||
|
|
||||||
// Match results
|
// Match results
|
||||||
match_suggestions(expected, suggestions);
|
match_suggestions(expected, suggestions);
|
||||||
@ -634,8 +759,8 @@ fn run_external_completion(block: &str, input: &str) -> Vec<Suggestion> {
|
|||||||
let (dir, _, mut engine_state, mut stack) = new_engine();
|
let (dir, _, mut engine_state, mut stack) = new_engine();
|
||||||
let (_, delta) = {
|
let (_, delta) = {
|
||||||
let mut working_set = StateWorkingSet::new(&engine_state);
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
||||||
let (block, err) = parse(&mut working_set, None, block.as_bytes(), false, &[]);
|
let block = parse(&mut working_set, None, block.as_bytes(), false);
|
||||||
assert!(err.is_none());
|
assert!(working_set.parse_errors.is_empty());
|
||||||
|
|
||||||
(block, working_set.render())
|
(block, working_set.render())
|
||||||
};
|
};
|
||||||
@ -652,7 +777,7 @@ fn run_external_completion(block: &str, input: &str) -> Vec<Suggestion> {
|
|||||||
config.external_completer = Some(latest_block_id);
|
config.external_completer = Some(latest_block_id);
|
||||||
engine_state.set_config(&config);
|
engine_state.set_config(&config);
|
||||||
|
|
||||||
// Instatiate a new completer
|
// Instantiate a new completer
|
||||||
let mut completer = NuCompleter::new(std::sync::Arc::new(engine_state), stack);
|
let mut completer = NuCompleter::new(std::sync::Arc::new(engine_state), stack);
|
||||||
|
|
||||||
completer.complete(input, input.len())
|
completer.complete(input, input.len())
|
||||||
@ -669,21 +794,21 @@ fn unknown_command_completion() {
|
|||||||
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
let expected_paths: Vec<String> = vec![
|
let expected_paths: Vec<String> = vec![
|
||||||
|
"another\\".to_string(),
|
||||||
|
"custom_completion.nu".to_string(),
|
||||||
"nushell".to_string(),
|
"nushell".to_string(),
|
||||||
"test_a\\".to_string(),
|
"test_a\\".to_string(),
|
||||||
"test_b\\".to_string(),
|
"test_b\\".to_string(),
|
||||||
"another\\".to_string(),
|
|
||||||
"custom_completion.nu".to_string(),
|
|
||||||
".hidden_file".to_string(),
|
".hidden_file".to_string(),
|
||||||
".hidden_folder\\".to_string(),
|
".hidden_folder\\".to_string(),
|
||||||
];
|
];
|
||||||
#[cfg(not(windows))]
|
#[cfg(not(windows))]
|
||||||
let expected_paths: Vec<String> = vec![
|
let expected_paths: Vec<String> = vec![
|
||||||
|
"another/".to_string(),
|
||||||
|
"custom_completion.nu".to_string(),
|
||||||
"nushell".to_string(),
|
"nushell".to_string(),
|
||||||
"test_a/".to_string(),
|
"test_a/".to_string(),
|
||||||
"test_b/".to_string(),
|
"test_b/".to_string(),
|
||||||
"another/".to_string(),
|
|
||||||
"custom_completion.nu".to_string(),
|
|
||||||
".hidden_file".to_string(),
|
".hidden_file".to_string(),
|
||||||
".hidden_folder/".to_string(),
|
".hidden_folder/".to_string(),
|
||||||
];
|
];
|
||||||
@ -729,24 +854,113 @@ fn filecompletions_triggers_after_cursor() {
|
|||||||
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
let expected_paths: Vec<String> = vec![
|
let expected_paths: Vec<String> = vec![
|
||||||
|
"another\\".to_string(),
|
||||||
|
"custom_completion.nu".to_string(),
|
||||||
"nushell".to_string(),
|
"nushell".to_string(),
|
||||||
"test_a\\".to_string(),
|
"test_a\\".to_string(),
|
||||||
"test_b\\".to_string(),
|
"test_b\\".to_string(),
|
||||||
"another\\".to_string(),
|
|
||||||
"custom_completion.nu".to_string(),
|
|
||||||
".hidden_file".to_string(),
|
".hidden_file".to_string(),
|
||||||
".hidden_folder\\".to_string(),
|
".hidden_folder\\".to_string(),
|
||||||
];
|
];
|
||||||
#[cfg(not(windows))]
|
#[cfg(not(windows))]
|
||||||
let expected_paths: Vec<String> = vec![
|
let expected_paths: Vec<String> = vec![
|
||||||
|
"another/".to_string(),
|
||||||
|
"custom_completion.nu".to_string(),
|
||||||
"nushell".to_string(),
|
"nushell".to_string(),
|
||||||
"test_a/".to_string(),
|
"test_a/".to_string(),
|
||||||
"test_b/".to_string(),
|
"test_b/".to_string(),
|
||||||
"another/".to_string(),
|
|
||||||
"custom_completion.nu".to_string(),
|
|
||||||
".hidden_file".to_string(),
|
".hidden_file".to_string(),
|
||||||
".hidden_folder/".to_string(),
|
".hidden_folder/".to_string(),
|
||||||
];
|
];
|
||||||
|
|
||||||
match_suggestions(expected_paths, suggestions);
|
match_suggestions(expected_paths, suggestions);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
fn extern_custom_completion_positional(mut extern_completer: NuCompleter) {
|
||||||
|
let suggestions = extern_completer.complete("spam ", 5);
|
||||||
|
let expected: Vec<String> = vec!["cat".into(), "dog".into(), "eel".into()];
|
||||||
|
match_suggestions(expected, suggestions);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
fn extern_custom_completion_long_flag_1(mut extern_completer: NuCompleter) {
|
||||||
|
let suggestions = extern_completer.complete("spam --foo=", 11);
|
||||||
|
let expected: Vec<String> = vec!["cat".into(), "dog".into(), "eel".into()];
|
||||||
|
match_suggestions(expected, suggestions);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
fn extern_custom_completion_long_flag_2(mut extern_completer: NuCompleter) {
|
||||||
|
let suggestions = extern_completer.complete("spam --foo ", 11);
|
||||||
|
let expected: Vec<String> = vec!["cat".into(), "dog".into(), "eel".into()];
|
||||||
|
match_suggestions(expected, suggestions);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
fn extern_custom_completion_long_flag_short(mut extern_completer: NuCompleter) {
|
||||||
|
let suggestions = extern_completer.complete("spam -f ", 8);
|
||||||
|
let expected: Vec<String> = vec!["cat".into(), "dog".into(), "eel".into()];
|
||||||
|
match_suggestions(expected, suggestions);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
fn extern_custom_completion_short_flag(mut extern_completer: NuCompleter) {
|
||||||
|
let suggestions = extern_completer.complete("spam -b ", 8);
|
||||||
|
let expected: Vec<String> = vec!["cat".into(), "dog".into(), "eel".into()];
|
||||||
|
match_suggestions(expected, suggestions);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
fn extern_complete_flags(mut extern_completer: NuCompleter) {
|
||||||
|
let suggestions = extern_completer.complete("spam -", 6);
|
||||||
|
let expected: Vec<String> = vec!["--foo".into(), "-b".into(), "-f".into()];
|
||||||
|
match_suggestions(expected, suggestions);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[ignore = "was reverted, still needs fixing"]
|
||||||
|
#[rstest]
|
||||||
|
fn alias_offset_bug_7648() {
|
||||||
|
let (dir, _, mut engine, mut stack) = new_engine();
|
||||||
|
|
||||||
|
// Create an alias
|
||||||
|
let alias = r#"alias ea = ^$env.EDITOR /tmp/test.s"#;
|
||||||
|
assert!(support::merge_input(alias.as_bytes(), &mut engine, &mut stack, dir).is_ok());
|
||||||
|
|
||||||
|
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
|
||||||
|
|
||||||
|
// Issue #7648
|
||||||
|
// Nushell crashes when an alias name is shorter than the alias command
|
||||||
|
// and the alias command is a external command
|
||||||
|
// This happens because of offset is not correct.
|
||||||
|
// This crashes before PR #7779
|
||||||
|
let _suggestions = completer.complete("e", 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[ignore = "was reverted, still needs fixing"]
|
||||||
|
#[rstest]
|
||||||
|
fn alias_offset_bug_7754() {
|
||||||
|
let (dir, _, mut engine, mut stack) = new_engine();
|
||||||
|
|
||||||
|
// Create an alias
|
||||||
|
let alias = r#"alias ll = ls -l"#;
|
||||||
|
assert!(support::merge_input(alias.as_bytes(), &mut engine, &mut stack, dir).is_ok());
|
||||||
|
|
||||||
|
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
|
||||||
|
|
||||||
|
// Issue #7754
|
||||||
|
// Nushell crashes when an alias name is shorter than the alias command
|
||||||
|
// and the alias command contains pipes.
|
||||||
|
// This crashes before PR #7756
|
||||||
|
let _suggestions = completer.complete("ll -a | c", 9);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn get_path_env_var_8003() {
|
||||||
|
// Create a new engine
|
||||||
|
let (_, _, engine, _) = new_engine();
|
||||||
|
// Get the path env var in a platform agnostic way
|
||||||
|
let the_path = engine.get_path_env_var();
|
||||||
|
// Make sure it's not empty
|
||||||
|
assert!(the_path.is_some());
|
||||||
|
}
|
||||||
|
@ -43,6 +43,22 @@ pub fn new_engine() -> (PathBuf, String, EngineState, Stack) {
|
|||||||
span: nu_protocol::Span::new(0, dir_str.len()),
|
span: nu_protocol::Span::new(0, dir_str.len()),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
#[cfg(windows)]
|
||||||
|
stack.add_env_var(
|
||||||
|
"Path".to_string(),
|
||||||
|
Value::String {
|
||||||
|
val: "c:\\some\\path;c:\\some\\other\\path".to_string(),
|
||||||
|
span: nu_protocol::Span::new(0, dir_str.len()),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
stack.add_env_var(
|
||||||
|
"PATH".to_string(),
|
||||||
|
Value::String {
|
||||||
|
val: "/some/path:/some/other/path".to_string(),
|
||||||
|
span: nu_protocol::Span::new(0, dir_str.len()),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
// Merge environment into the permanent state
|
// Merge environment into the permanent state
|
||||||
let merge_result = engine_state.merge_env(&mut stack, &dir);
|
let merge_result = engine_state.merge_env(&mut stack, &dir);
|
||||||
@ -130,9 +146,9 @@ pub fn merge_input(
|
|||||||
let (block, delta) = {
|
let (block, delta) = {
|
||||||
let mut working_set = StateWorkingSet::new(engine_state);
|
let mut working_set = StateWorkingSet::new(engine_state);
|
||||||
|
|
||||||
let (block, err) = parse(&mut working_set, None, input, false, &[]);
|
let block = parse(&mut working_set, None, input, false);
|
||||||
|
|
||||||
assert!(err.is_none());
|
assert!(working_set.parse_errors.is_empty());
|
||||||
|
|
||||||
(block, working_set.render())
|
(block, working_set.render())
|
||||||
};
|
};
|
||||||
|
68
crates/nu-cmd-dataframe/Cargo.toml
Normal file
68
crates/nu-cmd-dataframe/Cargo.toml
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
[package]
|
||||||
|
authors = ["The Nushell Project Developers"]
|
||||||
|
description = "Nushell's dataframe commands based on polars."
|
||||||
|
edition = "2021"
|
||||||
|
license = "MIT"
|
||||||
|
name = "nu-cmd-dataframe"
|
||||||
|
repository = "https://github.com/nushell/nushell/tree/main/crates/nu-cmd-dataframe"
|
||||||
|
version = "0.81.0"
|
||||||
|
|
||||||
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.81.0" }
|
||||||
|
nu-engine = { path = "../nu-engine", version = "0.81.0" }
|
||||||
|
nu-parser = { path = "../nu-parser", version = "0.81.0" }
|
||||||
|
nu-protocol = { path = "../nu-protocol", version = "0.81.0" }
|
||||||
|
|
||||||
|
# Potential dependencies for extras
|
||||||
|
chrono = { version = "0.4", features = [
|
||||||
|
"std",
|
||||||
|
"unstable-locales",
|
||||||
|
], default-features = false }
|
||||||
|
fancy-regex = "0.11"
|
||||||
|
indexmap = { version = "1.7", features = ["serde-1"] }
|
||||||
|
num = { version = "0.4", optional = true }
|
||||||
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
|
sqlparser = { version = "0.33", features = ["serde"], optional = true }
|
||||||
|
|
||||||
|
[dependencies.polars]
|
||||||
|
features = [
|
||||||
|
"arg_where",
|
||||||
|
"checked_arithmetic",
|
||||||
|
"concat_str",
|
||||||
|
"cross_join",
|
||||||
|
"csv",
|
||||||
|
"cum_agg",
|
||||||
|
"default",
|
||||||
|
"dtype-categorical",
|
||||||
|
"dtype-datetime",
|
||||||
|
"dtype-struct",
|
||||||
|
"dynamic_groupby",
|
||||||
|
"ipc",
|
||||||
|
"is_in",
|
||||||
|
"json",
|
||||||
|
"lazy",
|
||||||
|
"object",
|
||||||
|
"parquet",
|
||||||
|
"random",
|
||||||
|
"rolling_window",
|
||||||
|
"rows",
|
||||||
|
"serde",
|
||||||
|
"serde-lazy",
|
||||||
|
"strings",
|
||||||
|
"strings",
|
||||||
|
"to_dummies",
|
||||||
|
]
|
||||||
|
optional = true
|
||||||
|
version = "0.29.0"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
dataframe = ["default"]
|
||||||
|
default = ["num", "polars", "sqlparser"]
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
nu-test-support = { path = "../nu-test-support", version = "0.81.0" }
|
21
crates/nu-cmd-dataframe/LICENSE
Normal file
21
crates/nu-cmd-dataframe/LICENSE
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2019 - 2023 The Nushell Project Developers
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
@ -12,11 +12,11 @@ pub struct AppendDF;
|
|||||||
|
|
||||||
impl Command for AppendDF {
|
impl Command for AppendDF {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"append"
|
"dfr append"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Appends a new dataframe"
|
"Appends a new dataframe."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -32,8 +32,8 @@ impl Command for AppendDF {
|
|||||||
vec![
|
vec![
|
||||||
Example {
|
Example {
|
||||||
description: "Appends a dataframe as new columns",
|
description: "Appends a dataframe as new columns",
|
||||||
example: r#"let a = ([[a b]; [1 2] [3 4]] | into df);
|
example: r#"let a = ([[a b]; [1 2] [3 4]] | dfr into-df);
|
||||||
$a | append $a"#,
|
$a | dfr append $a"#,
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![
|
NuDataFrame::try_from_columns(vec![
|
||||||
Column::new(
|
Column::new(
|
||||||
@ -59,8 +59,8 @@ impl Command for AppendDF {
|
|||||||
},
|
},
|
||||||
Example {
|
Example {
|
||||||
description: "Appends a dataframe merging at the end of columns",
|
description: "Appends a dataframe merging at the end of columns",
|
||||||
example: r#"let a = ([[a b]; [1 2] [3 4]] | into df);
|
example: r#"let a = ([[a b]; [1 2] [3 4]] | dfr into-df);
|
||||||
$a | append $a --col"#,
|
$a | dfr append $a --col"#,
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![
|
NuDataFrame::try_from_columns(vec![
|
||||||
Column::new(
|
Column::new(
|
@ -10,11 +10,11 @@ pub struct ColumnsDF;
|
|||||||
|
|
||||||
impl Command for ColumnsDF {
|
impl Command for ColumnsDF {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"columns"
|
"dfr columns"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Show dataframe columns"
|
"Show dataframe columns."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -27,12 +27,9 @@ impl Command for ColumnsDF {
|
|||||||
fn examples(&self) -> Vec<Example> {
|
fn examples(&self) -> Vec<Example> {
|
||||||
vec![Example {
|
vec![Example {
|
||||||
description: "Dataframe columns",
|
description: "Dataframe columns",
|
||||||
example: "[[a b]; [1 2] [3 4]] | into df | columns",
|
example: "[[a b]; [1 2] [3 4]] | dfr into-df | dfr columns",
|
||||||
result: Some(Value::List {
|
result: Some(Value::List {
|
||||||
vals: vec![
|
vals: vec![Value::test_string("a"), Value::test_string("b")],
|
||||||
Value::string("a", Span::test_data()),
|
|
||||||
Value::string("b", Span::test_data()),
|
|
||||||
],
|
|
||||||
span: Span::test_data(),
|
span: Span::test_data(),
|
||||||
}),
|
}),
|
||||||
}]
|
}]
|
@ -13,11 +13,11 @@ pub struct DropDF;
|
|||||||
|
|
||||||
impl Command for DropDF {
|
impl Command for DropDF {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"drop"
|
"dfr drop"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Creates a new dataframe by dropping the selected columns"
|
"Creates a new dataframe by dropping the selected columns."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -31,7 +31,7 @@ impl Command for DropDF {
|
|||||||
fn examples(&self) -> Vec<Example> {
|
fn examples(&self) -> Vec<Example> {
|
||||||
vec![Example {
|
vec![Example {
|
||||||
description: "drop column a",
|
description: "drop column a",
|
||||||
example: "[[a b]; [1 2] [3 4]] | into df | drop a",
|
example: "[[a b]; [1 2] [3 4]] | dfr into-df | dfr drop a",
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![Column::new(
|
NuDataFrame::try_from_columns(vec![Column::new(
|
||||||
"b".to_string(),
|
"b".to_string(),
|
||||||
@ -70,7 +70,7 @@ fn command(
|
|||||||
.ok_or_else(|| {
|
.ok_or_else(|| {
|
||||||
ShellError::GenericError(
|
ShellError::GenericError(
|
||||||
"Empty names list".into(),
|
"Empty names list".into(),
|
||||||
"No column names where found".into(),
|
"No column names were found".into(),
|
||||||
Some(col_span),
|
Some(col_span),
|
||||||
None,
|
None,
|
||||||
Vec::new(),
|
Vec::new(),
|
@ -14,11 +14,11 @@ pub struct DropDuplicates;
|
|||||||
|
|
||||||
impl Command for DropDuplicates {
|
impl Command for DropDuplicates {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"drop-duplicates"
|
"dfr drop-duplicates"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Drops duplicate values in dataframe"
|
"Drops duplicate values in dataframe."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -42,7 +42,7 @@ impl Command for DropDuplicates {
|
|||||||
fn examples(&self) -> Vec<Example> {
|
fn examples(&self) -> Vec<Example> {
|
||||||
vec![Example {
|
vec![Example {
|
||||||
description: "drop duplicates",
|
description: "drop duplicates",
|
||||||
example: "[[a b]; [1 2] [3 4] [1 2]] | into df | drop-duplicates",
|
example: "[[a b]; [1 2] [3 4] [1 2]] | dfr into-df | dfr drop-duplicates",
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![
|
NuDataFrame::try_from_columns(vec![
|
||||||
Column::new(
|
Column::new(
|
||||||
@ -97,7 +97,7 @@ fn command(
|
|||||||
};
|
};
|
||||||
|
|
||||||
df.as_ref()
|
df.as_ref()
|
||||||
.unique(subset_slice, keep_strategy)
|
.unique(subset_slice, keep_strategy, None)
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
ShellError::GenericError(
|
ShellError::GenericError(
|
||||||
"Error dropping duplicates".into(),
|
"Error dropping duplicates".into(),
|
@ -13,11 +13,11 @@ pub struct DropNulls;
|
|||||||
|
|
||||||
impl Command for DropNulls {
|
impl Command for DropNulls {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"drop-nulls"
|
"dfr drop-nulls"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Drops null values in dataframe"
|
"Drops null values in dataframe."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -36,10 +36,10 @@ impl Command for DropNulls {
|
|||||||
vec![
|
vec![
|
||||||
Example {
|
Example {
|
||||||
description: "drop null values in dataframe",
|
description: "drop null values in dataframe",
|
||||||
example: r#"let df = ([[a b]; [1 2] [3 0] [1 2]] | into df);
|
example: r#"let df = ([[a b]; [1 2] [3 0] [1 2]] | dfr into-df);
|
||||||
let res = ($df.b / $df.b);
|
let res = ($df.b / $df.b);
|
||||||
let a = ($df | with-column $res --name res);
|
let a = ($df | dfr with-column $res --name res);
|
||||||
$a | drop-nulls"#,
|
$a | dfr drop-nulls"#,
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![
|
NuDataFrame::try_from_columns(vec![
|
||||||
Column::new(
|
Column::new(
|
||||||
@ -61,8 +61,8 @@ impl Command for DropNulls {
|
|||||||
},
|
},
|
||||||
Example {
|
Example {
|
||||||
description: "drop null values in dataframe",
|
description: "drop null values in dataframe",
|
||||||
example: r#"let s = ([1 2 0 0 3 4] | into df);
|
example: r#"let s = ([1 2 0 0 3 4] | dfr into-df);
|
||||||
($s / $s) | drop-nulls"#,
|
($s / $s) | dfr drop-nulls"#,
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![Column::new(
|
NuDataFrame::try_from_columns(vec![Column::new(
|
||||||
"div_0_0".to_string(),
|
"div_0_0".to_string(),
|
@ -10,11 +10,11 @@ pub struct DataTypes;
|
|||||||
|
|
||||||
impl Command for DataTypes {
|
impl Command for DataTypes {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"dtypes"
|
"dfr dtypes"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Show dataframe data types"
|
"Show dataframe data types."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -27,7 +27,7 @@ impl Command for DataTypes {
|
|||||||
fn examples(&self) -> Vec<Example> {
|
fn examples(&self) -> Vec<Example> {
|
||||||
vec![Example {
|
vec![Example {
|
||||||
description: "Dataframe dtypes",
|
description: "Dataframe dtypes",
|
||||||
example: "[[a b]; [1 2] [3 4]] | into df | dtypes",
|
example: "[[a b]; [1 2] [3 4]] | dfr into-df | dfr dtypes",
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![
|
NuDataFrame::try_from_columns(vec![
|
||||||
Column::new(
|
Column::new(
|
@ -11,11 +11,11 @@ pub struct Dummies;
|
|||||||
|
|
||||||
impl Command for Dummies {
|
impl Command for Dummies {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"dummies"
|
"dfr dummies"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Creates a new dataframe with dummy variables"
|
"Creates a new dataframe with dummy variables."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -29,7 +29,7 @@ impl Command for Dummies {
|
|||||||
vec![
|
vec![
|
||||||
Example {
|
Example {
|
||||||
description: "Create new dataframe with dummy variables from a dataframe",
|
description: "Create new dataframe with dummy variables from a dataframe",
|
||||||
example: "[[a b]; [1 2] [3 4]] | into df | dummies",
|
example: "[[a b]; [1 2] [3 4]] | dfr into-df | dfr dummies",
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![
|
NuDataFrame::try_from_columns(vec![
|
||||||
Column::new(
|
Column::new(
|
||||||
@ -55,7 +55,7 @@ impl Command for Dummies {
|
|||||||
},
|
},
|
||||||
Example {
|
Example {
|
||||||
description: "Create new dataframe with dummy variables from a series",
|
description: "Create new dataframe with dummy variables from a series",
|
||||||
example: "[1 2 2 3 3] | into df | dummies",
|
example: "[1 2 2 3 3] | dfr into-df | dfr dummies",
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![
|
NuDataFrame::try_from_columns(vec![
|
||||||
Column::new(
|
Column::new(
|
||||||
@ -116,7 +116,7 @@ fn command(
|
|||||||
let df = NuDataFrame::try_from_pipeline(input, call.head)?;
|
let df = NuDataFrame::try_from_pipeline(input, call.head)?;
|
||||||
|
|
||||||
df.as_ref()
|
df.as_ref()
|
||||||
.to_dummies()
|
.to_dummies(None)
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
ShellError::GenericError(
|
ShellError::GenericError(
|
||||||
"Error calculating dummies".into(),
|
"Error calculating dummies".into(),
|
@ -15,11 +15,11 @@ pub struct FilterWith;
|
|||||||
|
|
||||||
impl Command for FilterWith {
|
impl Command for FilterWith {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"filter-with"
|
"dfr filter-with"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Filters dataframe using a mask or expression as reference"
|
"Filters dataframe using a mask or expression as reference."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -38,8 +38,8 @@ impl Command for FilterWith {
|
|||||||
vec![
|
vec![
|
||||||
Example {
|
Example {
|
||||||
description: "Filter dataframe using a bool mask",
|
description: "Filter dataframe using a bool mask",
|
||||||
example: r#"let mask = ([true false] | into df);
|
example: r#"let mask = ([true false] | dfr into-df);
|
||||||
[[a b]; [1 2] [3 4]] | into df | filter-with $mask"#,
|
[[a b]; [1 2] [3 4]] | dfr into-df | dfr filter-with $mask"#,
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![
|
NuDataFrame::try_from_columns(vec![
|
||||||
Column::new("a".to_string(), vec![Value::test_int(1)]),
|
Column::new("a".to_string(), vec![Value::test_int(1)]),
|
||||||
@ -51,7 +51,7 @@ impl Command for FilterWith {
|
|||||||
},
|
},
|
||||||
Example {
|
Example {
|
||||||
description: "Filter dataframe using an expression",
|
description: "Filter dataframe using an expression",
|
||||||
example: "[[a b]; [1 2] [3 4]] | into df | filter-with ((col a) > 1)",
|
example: "[[a b]; [1 2] [3 4]] | dfr into-df | dfr filter-with ((dfr col a) > 1)",
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![
|
NuDataFrame::try_from_columns(vec![
|
||||||
Column::new("a".to_string(), vec![Value::test_int(3)]),
|
Column::new("a".to_string(), vec![Value::test_int(3)]),
|
@ -11,7 +11,7 @@ pub struct FirstDF;
|
|||||||
|
|
||||||
impl Command for FirstDF {
|
impl Command for FirstDF {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"first"
|
"dfr first"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
@ -34,7 +34,7 @@ impl Command for FirstDF {
|
|||||||
vec![
|
vec![
|
||||||
Example {
|
Example {
|
||||||
description: "Return the first row of a dataframe",
|
description: "Return the first row of a dataframe",
|
||||||
example: "[[a b]; [1 2] [3 4]] | into df | first",
|
example: "[[a b]; [1 2] [3 4]] | dfr into-df | dfr first",
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![
|
NuDataFrame::try_from_columns(vec![
|
||||||
Column::new("a".to_string(), vec![Value::test_int(1)]),
|
Column::new("a".to_string(), vec![Value::test_int(1)]),
|
||||||
@ -46,7 +46,7 @@ impl Command for FirstDF {
|
|||||||
},
|
},
|
||||||
Example {
|
Example {
|
||||||
description: "Return the first two rows of a dataframe",
|
description: "Return the first two rows of a dataframe",
|
||||||
example: "[[a b]; [1 2] [3 4]] | into df | first 2",
|
example: "[[a b]; [1 2] [3 4]] | dfr into-df | dfr first 2",
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![
|
NuDataFrame::try_from_columns(vec![
|
||||||
Column::new(
|
Column::new(
|
@ -14,11 +14,11 @@ pub struct GetDF;
|
|||||||
|
|
||||||
impl Command for GetDF {
|
impl Command for GetDF {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"get"
|
"dfr get"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Creates dataframe with the selected columns"
|
"Creates dataframe with the selected columns."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -32,7 +32,7 @@ impl Command for GetDF {
|
|||||||
fn examples(&self) -> Vec<Example> {
|
fn examples(&self) -> Vec<Example> {
|
||||||
vec![Example {
|
vec![Example {
|
||||||
description: "Returns the selected column",
|
description: "Returns the selected column",
|
||||||
example: "[[a b]; [1 2] [3 4]] | into df | get a",
|
example: "[[a b]; [1 2] [3 4]] | dfr into-df | dfr get a",
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![Column::new(
|
NuDataFrame::try_from_columns(vec![Column::new(
|
||||||
"a".to_string(),
|
"a".to_string(),
|
||||||
@ -67,7 +67,7 @@ fn command(
|
|||||||
let df = NuDataFrame::try_from_pipeline(input, call.head)?;
|
let df = NuDataFrame::try_from_pipeline(input, call.head)?;
|
||||||
|
|
||||||
df.as_ref()
|
df.as_ref()
|
||||||
.select(&col_string)
|
.select(col_string)
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
ShellError::GenericError(
|
ShellError::GenericError(
|
||||||
"Error selecting columns".into(),
|
"Error selecting columns".into(),
|
@ -11,11 +11,11 @@ pub struct LastDF;
|
|||||||
|
|
||||||
impl Command for LastDF {
|
impl Command for LastDF {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"last"
|
"dfr last"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Creates new dataframe with tail rows or creates a last expression"
|
"Creates new dataframe with tail rows or creates a last expression."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -29,7 +29,7 @@ impl Command for LastDF {
|
|||||||
fn examples(&self) -> Vec<Example> {
|
fn examples(&self) -> Vec<Example> {
|
||||||
vec![Example {
|
vec![Example {
|
||||||
description: "Create new dataframe with last rows",
|
description: "Create new dataframe with last rows",
|
||||||
example: "[[a b]; [1 2] [3 4]] | into df | last 1",
|
example: "[[a b]; [1 2] [3 4]] | dfr into-df | dfr last 1",
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![
|
NuDataFrame::try_from_columns(vec![
|
||||||
Column::new("a".to_string(), vec![Value::test_int(3)]),
|
Column::new("a".to_string(), vec![Value::test_int(3)]),
|
@ -11,11 +11,11 @@ pub struct ListDF;
|
|||||||
|
|
||||||
impl Command for ListDF {
|
impl Command for ListDF {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"ls-df"
|
"dfr ls"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Lists stored dataframes"
|
"Lists stored dataframes."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -25,8 +25,8 @@ impl Command for ListDF {
|
|||||||
fn examples(&self) -> Vec<Example> {
|
fn examples(&self) -> Vec<Example> {
|
||||||
vec![Example {
|
vec![Example {
|
||||||
description: "Creates a new dataframe and shows it in the dataframe list",
|
description: "Creates a new dataframe and shows it in the dataframe list",
|
||||||
example: r#"let test = ([[a b];[1 2] [3 4]] | into df);
|
example: r#"let test = ([[a b];[1 2] [3 4]] | dfr into-df);
|
||||||
ls-df"#,
|
ls"#,
|
||||||
result: None,
|
result: None,
|
||||||
}]
|
}]
|
||||||
}
|
}
|
||||||
@ -51,9 +51,8 @@ impl Command for ListDF {
|
|||||||
|
|
||||||
let vals = vals
|
let vals = vals
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter_map(|(name, value)| match NuDataFrame::try_from_value(value) {
|
.filter_map(|(name, value)| {
|
||||||
Ok(df) => Some((name, df)),
|
NuDataFrame::try_from_value(value).ok().map(|df| (name, df))
|
||||||
Err(_) => None,
|
|
||||||
})
|
})
|
||||||
.map(|(name, df)| {
|
.map(|(name, df)| {
|
||||||
let name = Value::String {
|
let name = Value::String {
|
@ -15,11 +15,11 @@ pub struct MeltDF;
|
|||||||
|
|
||||||
impl Command for MeltDF {
|
impl Command for MeltDF {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"melt"
|
"dfr melt"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Unpivot a DataFrame from wide to long format"
|
"Unpivot a DataFrame from wide to long format."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -57,7 +57,7 @@ impl Command for MeltDF {
|
|||||||
vec![Example {
|
vec![Example {
|
||||||
description: "melt dataframe",
|
description: "melt dataframe",
|
||||||
example:
|
example:
|
||||||
"[[a b c d]; [x 1 4 a] [y 2 5 b] [z 3 6 c]] | into df | melt -c [b c] -v [a d]",
|
"[[a b c d]; [x 1 4 a] [y 2 5 b] [z 3 6 c]] | dfr into-df | dfr melt -c [b c] -v [a d]",
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![
|
NuDataFrame::try_from_columns(vec![
|
||||||
Column::new(
|
Column::new(
|
@ -24,12 +24,14 @@ mod take;
|
|||||||
mod to_arrow;
|
mod to_arrow;
|
||||||
mod to_csv;
|
mod to_csv;
|
||||||
mod to_df;
|
mod to_df;
|
||||||
|
mod to_json_lines;
|
||||||
mod to_nu;
|
mod to_nu;
|
||||||
mod to_parquet;
|
mod to_parquet;
|
||||||
mod with_column;
|
mod with_column;
|
||||||
|
|
||||||
use nu_protocol::engine::StateWorkingSet;
|
use nu_protocol::engine::StateWorkingSet;
|
||||||
|
|
||||||
|
pub use self::open::OpenDataFrame;
|
||||||
pub use append::AppendDF;
|
pub use append::AppendDF;
|
||||||
pub use columns::ColumnsDF;
|
pub use columns::ColumnsDF;
|
||||||
pub use drop::DropDF;
|
pub use drop::DropDF;
|
||||||
@ -43,7 +45,6 @@ pub use get::GetDF;
|
|||||||
pub use last::LastDF;
|
pub use last::LastDF;
|
||||||
pub use list::ListDF;
|
pub use list::ListDF;
|
||||||
pub use melt::MeltDF;
|
pub use melt::MeltDF;
|
||||||
pub use open::OpenDataFrame;
|
|
||||||
pub use query_df::QueryDf;
|
pub use query_df::QueryDf;
|
||||||
pub use rename::RenameDF;
|
pub use rename::RenameDF;
|
||||||
pub use sample::SampleDF;
|
pub use sample::SampleDF;
|
||||||
@ -56,6 +57,7 @@ pub use take::TakeDF;
|
|||||||
pub use to_arrow::ToArrow;
|
pub use to_arrow::ToArrow;
|
||||||
pub use to_csv::ToCSV;
|
pub use to_csv::ToCSV;
|
||||||
pub use to_df::ToDataFrame;
|
pub use to_df::ToDataFrame;
|
||||||
|
pub use to_json_lines::ToJsonLines;
|
||||||
pub use to_nu::ToNu;
|
pub use to_nu::ToNu;
|
||||||
pub use to_parquet::ToParquet;
|
pub use to_parquet::ToParquet;
|
||||||
pub use with_column::WithColumn;
|
pub use with_column::WithColumn;
|
||||||
@ -98,6 +100,7 @@ pub fn add_eager_decls(working_set: &mut StateWorkingSet) {
|
|||||||
ToDataFrame,
|
ToDataFrame,
|
||||||
ToNu,
|
ToNu,
|
||||||
ToParquet,
|
ToParquet,
|
||||||
|
ToJsonLines,
|
||||||
WithColumn
|
WithColumn
|
||||||
);
|
);
|
||||||
}
|
}
|
@ -9,8 +9,8 @@ use nu_protocol::{
|
|||||||
use std::{fs::File, io::BufReader, path::PathBuf};
|
use std::{fs::File, io::BufReader, path::PathBuf};
|
||||||
|
|
||||||
use polars::prelude::{
|
use polars::prelude::{
|
||||||
CsvEncoding, CsvReader, IpcReader, JsonReader, LazyCsvReader, LazyFrame, ParallelStrategy,
|
CsvEncoding, CsvReader, IpcReader, JsonFormat, JsonReader, LazyCsvReader, LazyFileListReader,
|
||||||
ParquetReader, ScanArgsIpc, ScanArgsParquet, SerReader,
|
LazyFrame, ParallelStrategy, ParquetReader, ScanArgsIpc, ScanArgsParquet, SerReader,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
@ -18,11 +18,11 @@ pub struct OpenDataFrame;
|
|||||||
|
|
||||||
impl Command for OpenDataFrame {
|
impl Command for OpenDataFrame {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"open-df"
|
"dfr open"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Opens csv, json, arrow, or parquet file to create dataframe"
|
"Opens CSV, JSON, JSON lines, arrow, or parquet file to create dataframe."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -76,7 +76,7 @@ impl Command for OpenDataFrame {
|
|||||||
fn examples(&self) -> Vec<Example> {
|
fn examples(&self) -> Vec<Example> {
|
||||||
vec![Example {
|
vec![Example {
|
||||||
description: "Takes a file name and creates a dataframe",
|
description: "Takes a file name and creates a dataframe",
|
||||||
example: "open test.csv",
|
example: "dfr open test.csv",
|
||||||
result: None,
|
result: None,
|
||||||
}]
|
}]
|
||||||
}
|
}
|
||||||
@ -103,14 +103,13 @@ fn command(
|
|||||||
|
|
||||||
let type_id = match &type_option {
|
let type_id = match &type_option {
|
||||||
Some(ref t) => Some((t.item.to_owned(), "Invalid type", t.span)),
|
Some(ref t) => Some((t.item.to_owned(), "Invalid type", t.span)),
|
||||||
None => match file.item.extension() {
|
None => file.item.extension().map(|e| {
|
||||||
Some(e) => Some((
|
(
|
||||||
e.to_string_lossy().into_owned(),
|
e.to_string_lossy().into_owned(),
|
||||||
"Invalid extension",
|
"Invalid extension",
|
||||||
file.span,
|
file.span,
|
||||||
)),
|
)
|
||||||
None => None,
|
}),
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
match type_id {
|
match type_id {
|
||||||
@ -119,11 +118,9 @@ fn command(
|
|||||||
"parquet" => from_parquet(engine_state, stack, call),
|
"parquet" => from_parquet(engine_state, stack, call),
|
||||||
"ipc" | "arrow" => from_ipc(engine_state, stack, call),
|
"ipc" | "arrow" => from_ipc(engine_state, stack, call),
|
||||||
"json" => from_json(engine_state, stack, call),
|
"json" => from_json(engine_state, stack, call),
|
||||||
|
"jsonl" => from_jsonl(engine_state, stack, call),
|
||||||
_ => Err(ShellError::FileNotFoundCustom(
|
_ => Err(ShellError::FileNotFoundCustom(
|
||||||
format!(
|
format!("{msg}. Supported values: csv, tsv, parquet, ipc, arrow, json"),
|
||||||
"{}. Supported values: csv, tsv, parquet, ipc, arrow, json",
|
|
||||||
msg
|
|
||||||
),
|
|
||||||
blamed,
|
blamed,
|
||||||
)),
|
)),
|
||||||
},
|
},
|
||||||
@ -149,13 +146,15 @@ fn from_parquet(
|
|||||||
rechunk: false,
|
rechunk: false,
|
||||||
row_count: None,
|
row_count: None,
|
||||||
low_memory: false,
|
low_memory: false,
|
||||||
|
cloud_options: None,
|
||||||
|
use_statistics: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
let df: NuLazyFrame = LazyFrame::scan_parquet(file, args)
|
let df: NuLazyFrame = LazyFrame::scan_parquet(file, args)
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
ShellError::GenericError(
|
ShellError::GenericError(
|
||||||
"Parquet reader error".into(),
|
"Parquet reader error".into(),
|
||||||
format!("{:?}", e),
|
format!("{e:?}"),
|
||||||
Some(call.head),
|
Some(call.head),
|
||||||
None,
|
None,
|
||||||
Vec::new(),
|
Vec::new(),
|
||||||
@ -189,7 +188,7 @@ fn from_parquet(
|
|||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
ShellError::GenericError(
|
ShellError::GenericError(
|
||||||
"Parquet reader error".into(),
|
"Parquet reader error".into(),
|
||||||
format!("{:?}", e),
|
format!("{e:?}"),
|
||||||
Some(call.head),
|
Some(call.head),
|
||||||
None,
|
None,
|
||||||
Vec::new(),
|
Vec::new(),
|
||||||
@ -220,7 +219,7 @@ fn from_ipc(
|
|||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
ShellError::GenericError(
|
ShellError::GenericError(
|
||||||
"IPC reader error".into(),
|
"IPC reader error".into(),
|
||||||
format!("{:?}", e),
|
format!("{e:?}"),
|
||||||
Some(call.head),
|
Some(call.head),
|
||||||
None,
|
None,
|
||||||
Vec::new(),
|
Vec::new(),
|
||||||
@ -254,7 +253,7 @@ fn from_ipc(
|
|||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
ShellError::GenericError(
|
ShellError::GenericError(
|
||||||
"IPC reader error".into(),
|
"IPC reader error".into(),
|
||||||
format!("{:?}", e),
|
format!("{e:?}"),
|
||||||
Some(call.head),
|
Some(call.head),
|
||||||
None,
|
None,
|
||||||
Vec::new(),
|
Vec::new(),
|
||||||
@ -290,7 +289,45 @@ fn from_json(
|
|||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
ShellError::GenericError(
|
ShellError::GenericError(
|
||||||
"Json reader error".into(),
|
"Json reader error".into(),
|
||||||
format!("{:?}", e),
|
format!("{e:?}"),
|
||||||
|
Some(call.head),
|
||||||
|
None,
|
||||||
|
Vec::new(),
|
||||||
|
)
|
||||||
|
})?
|
||||||
|
.into();
|
||||||
|
|
||||||
|
Ok(df.into_value(call.head))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_jsonl(
|
||||||
|
engine_state: &EngineState,
|
||||||
|
stack: &mut Stack,
|
||||||
|
call: &Call,
|
||||||
|
) -> Result<Value, ShellError> {
|
||||||
|
let infer_schema: Option<usize> = call.get_flag(engine_state, stack, "infer-schema")?;
|
||||||
|
let file: Spanned<PathBuf> = call.req(engine_state, stack, 0)?;
|
||||||
|
let file = File::open(&file.item).map_err(|e| {
|
||||||
|
ShellError::GenericError(
|
||||||
|
"Error opening file".into(),
|
||||||
|
e.to_string(),
|
||||||
|
Some(file.span),
|
||||||
|
None,
|
||||||
|
Vec::new(),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let buf_reader = BufReader::new(file);
|
||||||
|
let reader = JsonReader::new(buf_reader)
|
||||||
|
.with_json_format(JsonFormat::JsonLines)
|
||||||
|
.infer_schema_len(infer_schema);
|
||||||
|
|
||||||
|
let df: NuDataFrame = reader
|
||||||
|
.finish()
|
||||||
|
.map_err(|e| {
|
||||||
|
ShellError::GenericError(
|
||||||
|
"Json lines reader error".into(),
|
||||||
|
format!("{e:?}"),
|
||||||
Some(call.head),
|
Some(call.head),
|
||||||
None,
|
None,
|
||||||
Vec::new(),
|
Vec::new(),
|
||||||
@ -354,7 +391,7 @@ fn from_csv(
|
|||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
ShellError::GenericError(
|
ShellError::GenericError(
|
||||||
"Parquet reader error".into(),
|
"Parquet reader error".into(),
|
||||||
format!("{:?}", e),
|
format!("{e:?}"),
|
||||||
Some(call.head),
|
Some(call.head),
|
||||||
None,
|
None,
|
||||||
Vec::new(),
|
Vec::new(),
|
||||||
@ -420,7 +457,7 @@ fn from_csv(
|
|||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
ShellError::GenericError(
|
ShellError::GenericError(
|
||||||
"Parquet reader error".into(),
|
"Parquet reader error".into(),
|
||||||
format!("{:?}", e),
|
format!("{e:?}"),
|
||||||
Some(call.head),
|
Some(call.head),
|
||||||
None,
|
None,
|
||||||
Vec::new(),
|
Vec::new(),
|
@ -18,7 +18,7 @@ pub struct QueryDf;
|
|||||||
|
|
||||||
impl Command for QueryDf {
|
impl Command for QueryDf {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"query df"
|
"dfr query"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
@ -40,7 +40,7 @@ impl Command for QueryDf {
|
|||||||
fn examples(&self) -> Vec<Example> {
|
fn examples(&self) -> Vec<Example> {
|
||||||
vec![Example {
|
vec![Example {
|
||||||
description: "Query dataframe using SQL",
|
description: "Query dataframe using SQL",
|
||||||
example: "[[a b]; [1 2] [3 4]] | into df | query df 'select a from df'",
|
example: "[[a b]; [1 2] [3 4]] | dfr into-df | dfr query 'select a from df'",
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![Column::new(
|
NuDataFrame::try_from_columns(vec![Column::new(
|
||||||
"a".to_string(),
|
"a".to_string(),
|
@ -14,11 +14,11 @@ pub struct RenameDF;
|
|||||||
|
|
||||||
impl Command for RenameDF {
|
impl Command for RenameDF {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"rename"
|
"dfr rename"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Rename a dataframe column"
|
"Rename a dataframe column."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -42,7 +42,7 @@ impl Command for RenameDF {
|
|||||||
vec![
|
vec![
|
||||||
Example {
|
Example {
|
||||||
description: "Renames a series",
|
description: "Renames a series",
|
||||||
example: "[5 6 7 8] | into df | rename '0' new_name",
|
example: "[5 6 7 8] | dfr into-df | dfr rename '0' new_name",
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![Column::new(
|
NuDataFrame::try_from_columns(vec![Column::new(
|
||||||
"new_name".to_string(),
|
"new_name".to_string(),
|
||||||
@ -59,7 +59,7 @@ impl Command for RenameDF {
|
|||||||
},
|
},
|
||||||
Example {
|
Example {
|
||||||
description: "Renames a dataframe column",
|
description: "Renames a dataframe column",
|
||||||
example: "[[a b]; [1 2] [3 4]] | into df | rename a a_new",
|
example: "[[a b]; [1 2] [3 4]] | dfr into-df | dfr rename a a_new",
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![
|
NuDataFrame::try_from_columns(vec![
|
||||||
Column::new(
|
Column::new(
|
||||||
@ -77,7 +77,7 @@ impl Command for RenameDF {
|
|||||||
},
|
},
|
||||||
Example {
|
Example {
|
||||||
description: "Renames two dataframe columns",
|
description: "Renames two dataframe columns",
|
||||||
example: "[[a b]; [1 2] [3 4]] | into df | rename [a b] [a_new b_new]",
|
example: "[[a b]; [1 2] [3 4]] | dfr into-df | dfr rename [a b] [a_new b_new]",
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![
|
NuDataFrame::try_from_columns(vec![
|
||||||
Column::new(
|
Column::new(
|
||||||
@ -156,10 +156,10 @@ fn command_lazy(
|
|||||||
|
|
||||||
if columns.len() != new_names.len() {
|
if columns.len() != new_names.len() {
|
||||||
let value: Value = call.req(engine_state, stack, 1)?;
|
let value: Value = call.req(engine_state, stack, 1)?;
|
||||||
return Err(ShellError::IncompatibleParametersSingle(
|
return Err(ShellError::IncompatibleParametersSingle {
|
||||||
"New name list has different size to column list".into(),
|
msg: "New name list has different size to column list".into(),
|
||||||
value.span()?,
|
span: value.span()?,
|
||||||
));
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let lazy = lazy.into_polars();
|
let lazy = lazy.into_polars();
|
@ -12,11 +12,11 @@ pub struct SampleDF;
|
|||||||
|
|
||||||
impl Command for SampleDF {
|
impl Command for SampleDF {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"sample"
|
"dfr sample"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Create sample dataframe"
|
"Create sample dataframe."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -50,12 +50,12 @@ impl Command for SampleDF {
|
|||||||
vec![
|
vec![
|
||||||
Example {
|
Example {
|
||||||
description: "Sample rows from dataframe",
|
description: "Sample rows from dataframe",
|
||||||
example: "[[a b]; [1 2] [3 4]] | into df | sample -n 1",
|
example: "[[a b]; [1 2] [3 4]] | dfr into-df | dfr sample -n 1",
|
||||||
result: None, // No expected value because sampling is random
|
result: None, // No expected value because sampling is random
|
||||||
},
|
},
|
||||||
Example {
|
Example {
|
||||||
description: "Shows sample row using fraction and replace",
|
description: "Shows sample row using fraction and replace",
|
||||||
example: "[[a b]; [1 2] [3 4] [5 6]] | into df | sample -f 0.5 -e",
|
example: "[[a b]; [1 2] [3 4] [5 6]] | dfr into-df | dfr sample -f 0.5 -e",
|
||||||
result: None, // No expected value because sampling is random
|
result: None, // No expected value because sampling is random
|
||||||
},
|
},
|
||||||
]
|
]
|
@ -13,11 +13,11 @@ pub struct ShapeDF;
|
|||||||
|
|
||||||
impl Command for ShapeDF {
|
impl Command for ShapeDF {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"shape"
|
"dfr shape"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Shows column and row size for a dataframe"
|
"Shows column and row size for a dataframe."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -30,7 +30,7 @@ impl Command for ShapeDF {
|
|||||||
fn examples(&self) -> Vec<Example> {
|
fn examples(&self) -> Vec<Example> {
|
||||||
vec![Example {
|
vec![Example {
|
||||||
description: "Shows row and column shape",
|
description: "Shows row and column shape",
|
||||||
example: "[[a b]; [1 2] [3 4]] | into df | shape",
|
example: "[[a b]; [1 2] [3 4]] | dfr into-df | dfr shape",
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![
|
NuDataFrame::try_from_columns(vec![
|
||||||
Column::new("rows".to_string(), vec![Value::test_int(2)]),
|
Column::new("rows".to_string(), vec![Value::test_int(2)]),
|
@ -14,11 +14,11 @@ pub struct SliceDF;
|
|||||||
|
|
||||||
impl Command for SliceDF {
|
impl Command for SliceDF {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"slice"
|
"dfr slice"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Creates new dataframe from a slice of rows"
|
"Creates new dataframe from a slice of rows."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -33,7 +33,7 @@ impl Command for SliceDF {
|
|||||||
fn examples(&self) -> Vec<Example> {
|
fn examples(&self) -> Vec<Example> {
|
||||||
vec![Example {
|
vec![Example {
|
||||||
description: "Create new dataframe from a slice of the rows",
|
description: "Create new dataframe from a slice of the rows",
|
||||||
example: "[[a b]; [1 2] [3 4]] | into df | slice 0 1",
|
example: "[[a b]; [1 2] [3 4]] | dfr into-df | dfr slice 0 1",
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![
|
NuDataFrame::try_from_columns(vec![
|
||||||
Column::new("a".to_string(), vec![Value::test_int(1)]),
|
Column::new("a".to_string(), vec![Value::test_int(1)]),
|
@ -30,7 +30,7 @@ impl SQLContext {
|
|||||||
// Determine involved dataframe
|
// Determine involved dataframe
|
||||||
// Implicit join require some more work in query parsers, Explicit join are preferred for now.
|
// Implicit join require some more work in query parsers, Explicit join are preferred for now.
|
||||||
let tbl = select_stmt.from.get(0).ok_or_else(|| {
|
let tbl = select_stmt.from.get(0).ok_or_else(|| {
|
||||||
PolarsError::NotFound(ErrString::from("No table found in select statement"))
|
PolarsError::ComputeError(ErrString::from("No table found in select statement"))
|
||||||
})?;
|
})?;
|
||||||
let mut alias_map = HashMap::new();
|
let mut alias_map = HashMap::new();
|
||||||
let tbl_name = match &tbl.relation {
|
let tbl_name = match &tbl.relation {
|
||||||
@ -39,7 +39,9 @@ impl SQLContext {
|
|||||||
.0
|
.0
|
||||||
.get(0)
|
.get(0)
|
||||||
.ok_or_else(|| {
|
.ok_or_else(|| {
|
||||||
PolarsError::NotFound(ErrString::from("No table found in select statement"))
|
PolarsError::ComputeError(ErrString::from(
|
||||||
|
"No table found in select statement",
|
||||||
|
))
|
||||||
})?
|
})?
|
||||||
.value
|
.value
|
||||||
.to_string();
|
.to_string();
|
||||||
@ -77,15 +79,15 @@ impl SQLContext {
|
|||||||
Ok(match select_item {
|
Ok(match select_item {
|
||||||
SelectItem::UnnamedExpr(expr) => {
|
SelectItem::UnnamedExpr(expr) => {
|
||||||
let expr = parse_sql_expr(expr)?;
|
let expr = parse_sql_expr(expr)?;
|
||||||
raw_projection_before_alias.insert(format!("{:?}", expr), i);
|
raw_projection_before_alias.insert(format!("{expr:?}"), i);
|
||||||
expr
|
expr
|
||||||
}
|
}
|
||||||
SelectItem::ExprWithAlias { expr, alias } => {
|
SelectItem::ExprWithAlias { expr, alias } => {
|
||||||
let expr = parse_sql_expr(expr)?;
|
let expr = parse_sql_expr(expr)?;
|
||||||
raw_projection_before_alias.insert(format!("{:?}", expr), i);
|
raw_projection_before_alias.insert(format!("{expr:?}"), i);
|
||||||
expr.alias(&alias.value)
|
expr.alias(&alias.value)
|
||||||
}
|
}
|
||||||
SelectItem::QualifiedWildcard(_) | SelectItem::Wildcard => {
|
SelectItem::QualifiedWildcard(_, _) | SelectItem::Wildcard(_) => {
|
||||||
contain_wildcard = true;
|
contain_wildcard = true;
|
||||||
col("*")
|
col("*")
|
||||||
}
|
}
|
||||||
@ -133,7 +135,7 @@ impl SQLContext {
|
|||||||
// and its projections columns, keeping the original index
|
// and its projections columns, keeping the original index
|
||||||
let (exclude_expr, groupby_pos): (Vec<_>, Vec<_>) = group_by
|
let (exclude_expr, groupby_pos): (Vec<_>, Vec<_>) = group_by
|
||||||
.iter()
|
.iter()
|
||||||
.map(|expr| raw_projection_before_alias.get(&format!("{:?}", expr)))
|
.map(|expr| raw_projection_before_alias.get(&format!("{expr:?}")))
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.filter(|(_, proj_p)| proj_p.is_some())
|
.filter(|(_, proj_p)| proj_p.is_some())
|
||||||
.map(|(gb_p, proj_p)| (*proj_p.unwrap_or(&0), (*proj_p.unwrap_or(&0), gb_p)))
|
.map(|(gb_p, proj_p)| (*proj_p.unwrap_or(&0), (*proj_p.unwrap_or(&0), gb_p)))
|
||||||
@ -161,8 +163,8 @@ impl SQLContext {
|
|||||||
.collect()
|
.collect()
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
.schema()
|
.schema()
|
||||||
.get_index(shm_p)
|
.get_at_index(shm_p)
|
||||||
.unwrap_or((&"".to_string(), &DataType::Null))
|
.unwrap_or((&"".into(), &DataType::Null))
|
||||||
.0)
|
.0)
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
@ -173,7 +175,7 @@ impl SQLContext {
|
|||||||
|
|
||||||
pub fn execute(&self, query: &str) -> Result<LazyFrame, PolarsError> {
|
pub fn execute(&self, query: &str) -> Result<LazyFrame, PolarsError> {
|
||||||
let ast = Parser::parse_sql(&self.dialect, query)
|
let ast = Parser::parse_sql(&self.dialect, query)
|
||||||
.map_err(|e| PolarsError::ComputeError(format!("{:?}", e).into()))?;
|
.map_err(|e| PolarsError::ComputeError(format!("{e:?}").into()))?;
|
||||||
if ast.len() != 1 {
|
if ast.len() != 1 {
|
||||||
Err(PolarsError::ComputeError(
|
Err(PolarsError::ComputeError(
|
||||||
"One and only one statement at a time please".into(),
|
"One and only one statement at a time please".into(),
|
||||||
@ -181,7 +183,7 @@ impl SQLContext {
|
|||||||
} else {
|
} else {
|
||||||
let ast = ast
|
let ast = ast
|
||||||
.get(0)
|
.get(0)
|
||||||
.ok_or_else(|| PolarsError::NotFound(ErrString::from("No statement found")))?;
|
.ok_or_else(|| PolarsError::ComputeError(ErrString::from("No statement found")))?;
|
||||||
Ok(match ast {
|
Ok(match ast {
|
||||||
Statement::Query(query) => {
|
Statement::Query(query) => {
|
||||||
let rs = match &*query.body {
|
let rs = match &*query.body {
|
||||||
@ -196,7 +198,7 @@ impl SQLContext {
|
|||||||
Some(SqlExpr::Value(SQLValue::Number(nrow, _))) => {
|
Some(SqlExpr::Value(SQLValue::Number(nrow, _))) => {
|
||||||
let nrow = nrow.parse().map_err(|err| {
|
let nrow = nrow.parse().map_err(|err| {
|
||||||
PolarsError::ComputeError(
|
PolarsError::ComputeError(
|
||||||
format!("Conversion Error: {:?}", err).into(),
|
format!("Conversion Error: {err:?}").into(),
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
rs.limit(nrow)
|
rs.limit(nrow)
|
||||||
@ -211,7 +213,7 @@ impl SQLContext {
|
|||||||
}
|
}
|
||||||
_ => {
|
_ => {
|
||||||
return Err(PolarsError::ComputeError(
|
return Err(PolarsError::ComputeError(
|
||||||
format!("Statement type {:?} is not supported", ast).into(),
|
format!("Statement type {ast:?} is not supported").into(),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
})
|
})
|
@ -28,19 +28,20 @@ fn map_sql_polars_datatype(data_type: &SQLDataType) -> Result<DataType> {
|
|||||||
|
|
||||||
SQLDataType::Boolean => DataType::Boolean,
|
SQLDataType::Boolean => DataType::Boolean,
|
||||||
SQLDataType::Date => DataType::Date,
|
SQLDataType::Date => DataType::Date,
|
||||||
SQLDataType::Time => DataType::Time,
|
SQLDataType::Time(_, _) => DataType::Time,
|
||||||
SQLDataType::Timestamp => DataType::Datetime(TimeUnit::Milliseconds, None),
|
SQLDataType::Timestamp(_, _) => DataType::Datetime(TimeUnit::Microseconds, None),
|
||||||
SQLDataType::Interval => DataType::Duration(TimeUnit::Milliseconds),
|
SQLDataType::Interval => DataType::Duration(TimeUnit::Microseconds),
|
||||||
SQLDataType::Array(inner_type) => {
|
SQLDataType::Array(inner_type) => match inner_type {
|
||||||
DataType::List(Box::new(map_sql_polars_datatype(inner_type)?))
|
Some(inner_type) => DataType::List(Box::new(map_sql_polars_datatype(inner_type)?)),
|
||||||
}
|
None => {
|
||||||
|
return Err(PolarsError::ComputeError(
|
||||||
|
"SQL Datatype Array(None) was not supported in polars-sql yet!".into(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
},
|
||||||
_ => {
|
_ => {
|
||||||
return Err(PolarsError::ComputeError(
|
return Err(PolarsError::ComputeError(
|
||||||
format!(
|
format!("SQL Datatype {data_type:?} was not supported in polars-sql yet!").into(),
|
||||||
"SQL Datatype {:?} was not supported in polars-sql yet!",
|
|
||||||
data_type
|
|
||||||
)
|
|
||||||
.into(),
|
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@ -70,7 +71,7 @@ fn binary_op_(left: Expr, right: Expr, op: &SQLBinaryOperator) -> Result<Expr> {
|
|||||||
SQLBinaryOperator::Xor => left.xor(right),
|
SQLBinaryOperator::Xor => left.xor(right),
|
||||||
_ => {
|
_ => {
|
||||||
return Err(PolarsError::ComputeError(
|
return Err(PolarsError::ComputeError(
|
||||||
format!("SQL Operator {:?} was not supported in polars-sql yet!", op).into(),
|
format!("SQL Operator {op:?} was not supported in polars-sql yet!").into(),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@ -82,11 +83,11 @@ fn literal_expr(value: &SqlValue) -> Result<Expr> {
|
|||||||
// Check for existence of decimal separator dot
|
// Check for existence of decimal separator dot
|
||||||
if s.contains('.') {
|
if s.contains('.') {
|
||||||
s.parse::<f64>().map(lit).map_err(|_| {
|
s.parse::<f64>().map(lit).map_err(|_| {
|
||||||
PolarsError::ComputeError(format!("Can't parse literal {:?}", s).into())
|
PolarsError::ComputeError(format!("Can't parse literal {s:?}").into())
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
s.parse::<i64>().map(lit).map_err(|_| {
|
s.parse::<i64>().map(lit).map_err(|_| {
|
||||||
PolarsError::ComputeError(format!("Can't parse literal {:?}", s).into())
|
PolarsError::ComputeError(format!("Can't parse literal {s:?}").into())
|
||||||
})
|
})
|
||||||
}?
|
}?
|
||||||
}
|
}
|
||||||
@ -98,11 +99,7 @@ fn literal_expr(value: &SqlValue) -> Result<Expr> {
|
|||||||
SqlValue::Null => Expr::Literal(LiteralValue::Null),
|
SqlValue::Null => Expr::Literal(LiteralValue::Null),
|
||||||
_ => {
|
_ => {
|
||||||
return Err(PolarsError::ComputeError(
|
return Err(PolarsError::ComputeError(
|
||||||
format!(
|
format!("Parsing SQL Value {value:?} was not supported in polars-sql yet!").into(),
|
||||||
"Parsing SQL Value {:?} was not supported in polars-sql yet!",
|
|
||||||
value
|
|
||||||
)
|
|
||||||
.into(),
|
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@ -122,11 +119,7 @@ pub fn parse_sql_expr(expr: &SqlExpr) -> Result<Expr> {
|
|||||||
SqlExpr::Value(value) => literal_expr(value)?,
|
SqlExpr::Value(value) => literal_expr(value)?,
|
||||||
_ => {
|
_ => {
|
||||||
return Err(PolarsError::ComputeError(
|
return Err(PolarsError::ComputeError(
|
||||||
format!(
|
format!("Expression: {expr:?} was not supported in polars-sql yet!").into(),
|
||||||
"Expression: {:?} was not supported in polars-sql yet!",
|
|
||||||
expr
|
|
||||||
)
|
|
||||||
.into(),
|
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@ -180,8 +173,7 @@ fn parse_sql_function(sql_function: &SQLFunction) -> Result<Expr> {
|
|||||||
_ => {
|
_ => {
|
||||||
return Err(PolarsError::ComputeError(
|
return Err(PolarsError::ComputeError(
|
||||||
format!(
|
format!(
|
||||||
"Function {:?} with args {:?} was not supported in polars-sql yet!",
|
"Function {function_name:?} with args {args:?} was not supported in polars-sql yet!"
|
||||||
function_name, args
|
|
||||||
)
|
)
|
||||||
.into(),
|
.into(),
|
||||||
))
|
))
|
@ -19,7 +19,7 @@ pub struct Summary;
|
|||||||
|
|
||||||
impl Command for Summary {
|
impl Command for Summary {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"summary"
|
"dfr summary"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
@ -42,7 +42,7 @@ impl Command for Summary {
|
|||||||
fn examples(&self) -> Vec<Example> {
|
fn examples(&self) -> Vec<Example> {
|
||||||
vec![Example {
|
vec![Example {
|
||||||
description: "list dataframe descriptives",
|
description: "list dataframe descriptives",
|
||||||
example: "[[a b]; [1 1] [1 1]] | into df | summary",
|
example: "[[a b]; [1 1] [1 1]] | dfr into-df | dfr summary",
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![
|
NuDataFrame::try_from_columns(vec![
|
||||||
Column::new(
|
Column::new(
|
||||||
@ -185,22 +185,22 @@ fn command(
|
|||||||
.cast(&DataType::Float64)
|
.cast(&DataType::Float64)
|
||||||
.ok()
|
.ok()
|
||||||
.and_then(|ca| match ca.get(0) {
|
.and_then(|ca| match ca.get(0) {
|
||||||
AnyValue::Float64(v) => Some(v),
|
Ok(AnyValue::Float64(v)) => Some(v),
|
||||||
_ => None,
|
_ => None,
|
||||||
});
|
});
|
||||||
|
|
||||||
let mean = match col.mean_as_series().get(0) {
|
let mean = match col.mean_as_series().get(0) {
|
||||||
AnyValue::Float64(v) => Some(v),
|
Ok(AnyValue::Float64(v)) => Some(v),
|
||||||
_ => None,
|
_ => None,
|
||||||
};
|
};
|
||||||
|
|
||||||
let median = match col.median_as_series().get(0) {
|
let median = match col.median_as_series().get(0) {
|
||||||
AnyValue::Float64(v) => Some(v),
|
Ok(AnyValue::Float64(v)) => Some(v),
|
||||||
_ => None,
|
_ => None,
|
||||||
};
|
};
|
||||||
|
|
||||||
let std = match col.std_as_series(0).get(0) {
|
let std = match col.std_as_series(0).get(0) {
|
||||||
AnyValue::Float64(v) => Some(v),
|
Ok(AnyValue::Float64(v)) => Some(v),
|
||||||
_ => None,
|
_ => None,
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -209,7 +209,7 @@ fn command(
|
|||||||
.cast(&DataType::Float64)
|
.cast(&DataType::Float64)
|
||||||
.ok()
|
.ok()
|
||||||
.and_then(|ca| match ca.get(0) {
|
.and_then(|ca| match ca.get(0) {
|
||||||
AnyValue::Float64(v) => Some(v),
|
Ok(AnyValue::Float64(v)) => Some(v),
|
||||||
_ => None,
|
_ => None,
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -221,7 +221,7 @@ fn command(
|
|||||||
.ok()
|
.ok()
|
||||||
.and_then(|ca| ca.cast(&DataType::Float64).ok())
|
.and_then(|ca| ca.cast(&DataType::Float64).ok())
|
||||||
.and_then(|ca| match ca.get(0) {
|
.and_then(|ca| match ca.get(0) {
|
||||||
AnyValue::Float64(v) => Some(v),
|
Ok(AnyValue::Float64(v)) => Some(v),
|
||||||
_ => None,
|
_ => None,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@ -232,7 +232,7 @@ fn command(
|
|||||||
.cast(&DataType::Float64)
|
.cast(&DataType::Float64)
|
||||||
.ok()
|
.ok()
|
||||||
.and_then(|ca| match ca.get(0) {
|
.and_then(|ca| match ca.get(0) {
|
||||||
AnyValue::Float64(v) => Some(v),
|
Ok(AnyValue::Float64(v)) => Some(v),
|
||||||
_ => None,
|
_ => None,
|
||||||
});
|
});
|
||||||
|
|
@ -15,11 +15,11 @@ pub struct TakeDF;
|
|||||||
|
|
||||||
impl Command for TakeDF {
|
impl Command for TakeDF {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"take"
|
"dfr take"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Creates new dataframe using the given indices"
|
"Creates new dataframe using the given indices."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -38,9 +38,9 @@ impl Command for TakeDF {
|
|||||||
vec![
|
vec![
|
||||||
Example {
|
Example {
|
||||||
description: "Takes selected rows from dataframe",
|
description: "Takes selected rows from dataframe",
|
||||||
example: r#"let df = ([[a b]; [4 1] [5 2] [4 3]] | into df);
|
example: r#"let df = ([[a b]; [4 1] [5 2] [4 3]] | dfr into-df);
|
||||||
let indices = ([0 2] | into df);
|
let indices = ([0 2] | dfr into-df);
|
||||||
$df | take $indices"#,
|
$df | dfr take $indices"#,
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![
|
NuDataFrame::try_from_columns(vec![
|
||||||
Column::new(
|
Column::new(
|
||||||
@ -58,9 +58,9 @@ impl Command for TakeDF {
|
|||||||
},
|
},
|
||||||
Example {
|
Example {
|
||||||
description: "Takes selected rows from series",
|
description: "Takes selected rows from series",
|
||||||
example: r#"let series = ([4 1 5 2 4 3] | into df);
|
example: r#"let series = ([4 1 5 2 4 3] | dfr into-df);
|
||||||
let indices = ([0 2] | into df);
|
let indices = ([0 2] | dfr into-df);
|
||||||
$series | take $indices"#,
|
$series | dfr take $indices"#,
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![Column::new(
|
NuDataFrame::try_from_columns(vec![Column::new(
|
||||||
"0".to_string(),
|
"0".to_string(),
|
@ -15,11 +15,11 @@ pub struct ToArrow;
|
|||||||
|
|
||||||
impl Command for ToArrow {
|
impl Command for ToArrow {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"to arrow"
|
"dfr to-arrow"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Saves dataframe to arrow file"
|
"Saves dataframe to arrow file."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -33,7 +33,7 @@ impl Command for ToArrow {
|
|||||||
fn examples(&self) -> Vec<Example> {
|
fn examples(&self) -> Vec<Example> {
|
||||||
vec![Example {
|
vec![Example {
|
||||||
description: "Saves dataframe to arrow file",
|
description: "Saves dataframe to arrow file",
|
||||||
example: "[[a b]; [1 2] [3 4]] | into df | to arrow test.arrow",
|
example: "[[a b]; [1 2] [3 4]] | dfr into-df | dfr to-arrow test.arrow",
|
||||||
result: None,
|
result: None,
|
||||||
}]
|
}]
|
||||||
}
|
}
|
@ -15,11 +15,11 @@ pub struct ToCSV;
|
|||||||
|
|
||||||
impl Command for ToCSV {
|
impl Command for ToCSV {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"to csv"
|
"dfr to-csv"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Saves dataframe to csv file"
|
"Saves dataframe to CSV file."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -40,13 +40,13 @@ impl Command for ToCSV {
|
|||||||
fn examples(&self) -> Vec<Example> {
|
fn examples(&self) -> Vec<Example> {
|
||||||
vec![
|
vec![
|
||||||
Example {
|
Example {
|
||||||
description: "Saves dataframe to csv file",
|
description: "Saves dataframe to CSV file",
|
||||||
example: "[[a b]; [1 2] [3 4]] | into df | to csv test.csv",
|
example: "[[a b]; [1 2] [3 4]] | dfr into-df | dfr to-csv test.csv",
|
||||||
result: None,
|
result: None,
|
||||||
},
|
},
|
||||||
Example {
|
Example {
|
||||||
description: "Saves dataframe to csv file using other delimiter",
|
description: "Saves dataframe to CSV file using other delimiter",
|
||||||
example: "[[a b]; [1 2] [3 4]] | into df | to csv test.csv -d '|'",
|
example: "[[a b]; [1 2] [3 4]] | dfr into-df | dfr to-csv test.csv -d '|'",
|
||||||
result: None,
|
result: None,
|
||||||
},
|
},
|
||||||
]
|
]
|
@ -11,11 +11,11 @@ pub struct ToDataFrame;
|
|||||||
|
|
||||||
impl Command for ToDataFrame {
|
impl Command for ToDataFrame {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"into df"
|
"dfr into-df"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Converts a list, table or record into a dataframe"
|
"Converts a list, table or record into a dataframe."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -29,7 +29,7 @@ impl Command for ToDataFrame {
|
|||||||
vec![
|
vec![
|
||||||
Example {
|
Example {
|
||||||
description: "Takes a dictionary and creates a dataframe",
|
description: "Takes a dictionary and creates a dataframe",
|
||||||
example: "[[a b];[1 2] [3 4]] | into df",
|
example: "[[a b];[1 2] [3 4]] | dfr into-df",
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![
|
NuDataFrame::try_from_columns(vec![
|
||||||
Column::new(
|
Column::new(
|
||||||
@ -47,7 +47,7 @@ impl Command for ToDataFrame {
|
|||||||
},
|
},
|
||||||
Example {
|
Example {
|
||||||
description: "Takes a list of tables and creates a dataframe",
|
description: "Takes a list of tables and creates a dataframe",
|
||||||
example: "[[1 2 a] [3 4 b] [5 6 c]] | into df",
|
example: "[[1 2 a] [3 4 b] [5 6 c]] | dfr into-df",
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![
|
NuDataFrame::try_from_columns(vec![
|
||||||
Column::new(
|
Column::new(
|
||||||
@ -73,7 +73,7 @@ impl Command for ToDataFrame {
|
|||||||
},
|
},
|
||||||
Example {
|
Example {
|
||||||
description: "Takes a list and creates a dataframe",
|
description: "Takes a list and creates a dataframe",
|
||||||
example: "[a b c] | into df",
|
example: "[a b c] | dfr into-df",
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![Column::new(
|
NuDataFrame::try_from_columns(vec![Column::new(
|
||||||
"0".to_string(),
|
"0".to_string(),
|
||||||
@ -89,7 +89,7 @@ impl Command for ToDataFrame {
|
|||||||
},
|
},
|
||||||
Example {
|
Example {
|
||||||
description: "Takes a list of booleans and creates a dataframe",
|
description: "Takes a list of booleans and creates a dataframe",
|
||||||
example: "[true true false] | into df",
|
example: "[true true false] | dfr into-df",
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![Column::new(
|
NuDataFrame::try_from_columns(vec![Column::new(
|
||||||
"0".to_string(),
|
"0".to_string(),
|
97
crates/nu-cmd-dataframe/src/dataframe/eager/to_json_lines.rs
Normal file
97
crates/nu-cmd-dataframe/src/dataframe/eager/to_json_lines.rs
Normal file
@ -0,0 +1,97 @@
|
|||||||
|
use std::{fs::File, io::BufWriter, path::PathBuf};
|
||||||
|
|
||||||
|
use nu_engine::CallExt;
|
||||||
|
use nu_protocol::{
|
||||||
|
ast::Call,
|
||||||
|
engine::{Command, EngineState, Stack},
|
||||||
|
Category, Example, PipelineData, ShellError, Signature, Spanned, SyntaxShape, Type, Value,
|
||||||
|
};
|
||||||
|
use polars::prelude::{JsonWriter, SerWriter};
|
||||||
|
|
||||||
|
use super::super::values::NuDataFrame;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct ToJsonLines;
|
||||||
|
|
||||||
|
impl Command for ToJsonLines {
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
"dfr to-jsonl"
|
||||||
|
}
|
||||||
|
|
||||||
|
fn usage(&self) -> &str {
|
||||||
|
"Saves dataframe to a JSON lines file."
|
||||||
|
}
|
||||||
|
|
||||||
|
fn signature(&self) -> Signature {
|
||||||
|
Signature::build(self.name())
|
||||||
|
.required("file", SyntaxShape::Filepath, "file path to save dataframe")
|
||||||
|
.input_type(Type::Custom("dataframe".into()))
|
||||||
|
.output_type(Type::Any)
|
||||||
|
.category(Category::Custom("dataframe".into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn examples(&self) -> Vec<Example> {
|
||||||
|
vec![Example {
|
||||||
|
description: "Saves dataframe to JSON lines file",
|
||||||
|
example: "[[a b]; [1 2] [3 4]] | dfr into-df | dfr to-jsonl test.jsonl",
|
||||||
|
result: None,
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(
|
||||||
|
&self,
|
||||||
|
engine_state: &EngineState,
|
||||||
|
stack: &mut Stack,
|
||||||
|
call: &Call,
|
||||||
|
input: PipelineData,
|
||||||
|
) -> Result<PipelineData, ShellError> {
|
||||||
|
command(engine_state, stack, call, input)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn command(
|
||||||
|
engine_state: &EngineState,
|
||||||
|
stack: &mut Stack,
|
||||||
|
call: &Call,
|
||||||
|
input: PipelineData,
|
||||||
|
) -> Result<PipelineData, ShellError> {
|
||||||
|
let file_name: Spanned<PathBuf> = call.req(engine_state, stack, 0)?;
|
||||||
|
|
||||||
|
let mut df = NuDataFrame::try_from_pipeline(input, call.head)?;
|
||||||
|
|
||||||
|
let file = File::create(&file_name.item).map_err(|e| {
|
||||||
|
ShellError::GenericError(
|
||||||
|
"Error with file name".into(),
|
||||||
|
e.to_string(),
|
||||||
|
Some(file_name.span),
|
||||||
|
None,
|
||||||
|
Vec::new(),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let buf_writer = BufWriter::new(file);
|
||||||
|
|
||||||
|
JsonWriter::new(buf_writer)
|
||||||
|
.finish(df.as_mut())
|
||||||
|
.map_err(|e| {
|
||||||
|
ShellError::GenericError(
|
||||||
|
"Error saving file".into(),
|
||||||
|
e.to_string(),
|
||||||
|
Some(file_name.span),
|
||||||
|
None,
|
||||||
|
Vec::new(),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let file_value = Value::String {
|
||||||
|
val: format!("saved {:?}", &file_name.item),
|
||||||
|
span: file_name.span,
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(PipelineData::Value(
|
||||||
|
Value::List {
|
||||||
|
vals: vec![file_value],
|
||||||
|
span: call.head,
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
))
|
||||||
|
}
|
@ -12,11 +12,11 @@ pub struct ToNu;
|
|||||||
|
|
||||||
impl Command for ToNu {
|
impl Command for ToNu {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"into nu"
|
"dfr into-nu"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Converts a section of the dataframe into nushell Table"
|
"Converts a section of the dataframe into nushell Table."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -54,7 +54,7 @@ impl Command for ToNu {
|
|||||||
vec![
|
vec![
|
||||||
Example {
|
Example {
|
||||||
description: "Shows head rows from dataframe",
|
description: "Shows head rows from dataframe",
|
||||||
example: "[[a b]; [1 2] [3 4]] | into df | into nu",
|
example: "[[a b]; [1 2] [3 4]] | dfr into-df | dfr into-nu",
|
||||||
result: Some(Value::List {
|
result: Some(Value::List {
|
||||||
vals: vec![rec_1, rec_2],
|
vals: vec![rec_1, rec_2],
|
||||||
span: Span::test_data(),
|
span: Span::test_data(),
|
||||||
@ -62,7 +62,7 @@ impl Command for ToNu {
|
|||||||
},
|
},
|
||||||
Example {
|
Example {
|
||||||
description: "Shows tail rows from dataframe",
|
description: "Shows tail rows from dataframe",
|
||||||
example: "[[a b]; [1 2] [5 6] [3 4]] | into df | into nu -t -n 1",
|
example: "[[a b]; [1 2] [5 6] [3 4]] | dfr into-df | dfr into-nu -t -n 1",
|
||||||
result: Some(Value::List {
|
result: Some(Value::List {
|
||||||
vals: vec![rec_3],
|
vals: vec![rec_3],
|
||||||
span: Span::test_data(),
|
span: Span::test_data(),
|
@ -15,11 +15,11 @@ pub struct ToParquet;
|
|||||||
|
|
||||||
impl Command for ToParquet {
|
impl Command for ToParquet {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"to parquet"
|
"dfr to-parquet"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Saves dataframe to parquet file"
|
"Saves dataframe to parquet file."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -33,7 +33,7 @@ impl Command for ToParquet {
|
|||||||
fn examples(&self) -> Vec<Example> {
|
fn examples(&self) -> Vec<Example> {
|
||||||
vec![Example {
|
vec![Example {
|
||||||
description: "Saves dataframe to parquet file",
|
description: "Saves dataframe to parquet file",
|
||||||
example: "[[a b]; [1 2] [3 4]] | into df | to parquet test.parquet",
|
example: "[[a b]; [1 2] [3 4]] | dfr into-df | dfr to-parquet test.parquet",
|
||||||
result: None,
|
result: None,
|
||||||
}]
|
}]
|
||||||
}
|
}
|
@ -12,11 +12,11 @@ pub struct WithColumn;
|
|||||||
|
|
||||||
impl Command for WithColumn {
|
impl Command for WithColumn {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"with-column"
|
"dfr with-column"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Adds a series to the dataframe"
|
"Adds a series to the dataframe."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -37,8 +37,8 @@ impl Command for WithColumn {
|
|||||||
Example {
|
Example {
|
||||||
description: "Adds a series to the dataframe",
|
description: "Adds a series to the dataframe",
|
||||||
example: r#"[[a b]; [1 2] [3 4]]
|
example: r#"[[a b]; [1 2] [3 4]]
|
||||||
| into df
|
| dfr into-df
|
||||||
| with-column ([5 6] | into df) --name c"#,
|
| dfr with-column ([5 6] | dfr into-df) --name c"#,
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![
|
NuDataFrame::try_from_columns(vec![
|
||||||
Column::new(
|
Column::new(
|
||||||
@ -61,12 +61,12 @@ impl Command for WithColumn {
|
|||||||
Example {
|
Example {
|
||||||
description: "Adds a series to the dataframe",
|
description: "Adds a series to the dataframe",
|
||||||
example: r#"[[a b]; [1 2] [3 4]]
|
example: r#"[[a b]; [1 2] [3 4]]
|
||||||
| into lazy
|
| dfr into-lazy
|
||||||
| with-column [
|
| dfr with-column [
|
||||||
((col a) * 2 | as "c")
|
((dfr col a) * 2 | dfr as "c")
|
||||||
((col a) * 3 | as "d")
|
((dfr col a) * 3 | dfr as "d")
|
||||||
]
|
]
|
||||||
| collect"#,
|
| dfr collect"#,
|
||||||
result: Some(
|
result: Some(
|
||||||
NuDataFrame::try_from_columns(vec![
|
NuDataFrame::try_from_columns(vec![
|
||||||
Column::new(
|
Column::new(
|
||||||
@ -109,12 +109,12 @@ impl Command for WithColumn {
|
|||||||
let df = NuDataFrame::try_from_value(value)?;
|
let df = NuDataFrame::try_from_value(value)?;
|
||||||
command_eager(engine_state, stack, call, df)
|
command_eager(engine_state, stack, call, df)
|
||||||
} else {
|
} else {
|
||||||
Err(ShellError::CantConvert(
|
Err(ShellError::CantConvert {
|
||||||
"lazy or eager dataframe".into(),
|
to_type: "lazy or eager dataframe".into(),
|
||||||
value.get_type().to_string(),
|
from_type: value.get_type().to_string(),
|
||||||
value.span()?,
|
span: value.span()?,
|
||||||
None,
|
help: None,
|
||||||
))
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -12,11 +12,11 @@ pub struct ExprAlias;
|
|||||||
|
|
||||||
impl Command for ExprAlias {
|
impl Command for ExprAlias {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"as"
|
"dfr as"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn usage(&self) -> &str {
|
fn usage(&self) -> &str {
|
||||||
"Creates an alias expression"
|
"Creates an alias expression."
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(&self) -> Signature {
|
fn signature(&self) -> Signature {
|
||||||
@ -34,7 +34,7 @@ impl Command for ExprAlias {
|
|||||||
fn examples(&self) -> Vec<Example> {
|
fn examples(&self) -> Vec<Example> {
|
||||||
vec![Example {
|
vec![Example {
|
||||||
description: "Creates and alias expression",
|
description: "Creates and alias expression",
|
||||||
example: "col a | as new_a | into nu",
|
example: "dfr col a | dfr as new_a | dfr into-nu",
|
||||||
result: {
|
result: {
|
||||||
let cols = vec!["expr".into(), "value".into()];
|
let cols = vec!["expr".into(), "value".into()];
|
||||||
let expr = Value::test_string("column");
|
let expr = Value::test_string("column");
|
||||||
@ -59,6 +59,10 @@ impl Command for ExprAlias {
|
|||||||
}]
|
}]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn search_terms(&self) -> Vec<&str> {
|
||||||
|
vec!["aka", "abbr", "otherwise"]
|
||||||
|
}
|
||||||
|
|
||||||
fn run(
|
fn run(
|
||||||
&self,
|
&self,
|
||||||
engine_state: &EngineState,
|
engine_state: &EngineState,
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user