├── .github └── workflows │ ├── main.yml │ └── scripts │ └── check-cargo-lock.sh ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── Makefile ├── README.md ├── build.nu ├── examples ├── config │ └── default.nuon └── demo.gif ├── nupm.nuon ├── rust-toolchain.toml ├── scripts └── deps.nu └── src ├── app.rs ├── config ├── mod.rs └── parsing.rs ├── edit.rs ├── handler.rs ├── lib.rs ├── main.rs ├── navigation.rs ├── nu ├── cell_path.rs ├── mod.rs ├── strings.rs └── value.rs ├── tui ├── event.rs └── mod.rs └── ui.rs /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | on: 2 | pull_request: 3 | push: 4 | branches: 5 | - main 6 | 7 | name: continuous-integration 8 | 9 | jobs: 10 | fmt-check-clippy: 11 | runs-on: ubuntu-20.04 12 | 13 | steps: 14 | - uses: actions/checkout@v3 15 | 16 | - name: Setup Rust toolchain 17 | uses: actions-rust-lang/setup-rust-toolchain@v1.5.0 18 | with: 19 | rustflags: "" 20 | 21 | - run: make check 22 | 23 | - name: Check Cargo.lock 24 | run: make lock 25 | 26 | tests: 27 | strategy: 28 | fail-fast: true 29 | matrix: 30 | platform: [windows-latest, macos-latest, ubuntu-20.04] 31 | 32 | runs-on: ${{ matrix.platform }} 33 | 34 | steps: 35 | - uses: actions/checkout@v3 36 | 37 | - name: Setup Rust toolchain 38 | uses: actions-rust-lang/setup-rust-toolchain@v1.5.0 39 | with: 40 | rustflags: "" 41 | 42 | - run: make test 43 | -------------------------------------------------------------------------------- /.github/workflows/scripts/check-cargo-lock.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | [[ -n "$(git status --short Cargo.lock)" ]] && exit 1 4 | 5 | exit 0 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | debug/ 4 | target/ 5 | 6 | # These are backup files generated by rustfmt 7 | **/*.rs.bk 8 | 9 | # MSVC Windows builds of rustc generate these, which store debugging information 10 | *.pdb 11 | 12 | 13 | # Added by cargo 14 | 15 | /target 16 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [[bin]] 2 | bench = false 3 | name = "nu_plugin_explore" 4 | 5 | [dependencies] 6 | anyhow = "1.0.97" 7 | crossterm = { version = "0.28.1", features = ["use-dev-tty"] } 8 | nuon = "0.102.0" 9 | nu-plugin = "0.102.0" 10 | nu-protocol = "0.102.0" 11 | ratatui = "0.29.0" 12 | url = "2.5.4" 13 | 14 | [lib] 15 | bench = false 16 | 17 | [package] 18 | edition = "2021" 19 | name = "nu_plugin_explore" 20 | version = "0.102.0" 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | CLIPPY_OPTIONS="-D warnings" 2 | 3 | .PHONY: fmt-check fmt check lock clippy test doc build register install clean 4 | DEFAULT: fmt-check check lock clippy test 5 | 6 | fmt-check: 7 | cargo fmt --all --verbose -- --check --verbose 8 | fmt: 9 | cargo fmt --all --verbose 10 | 11 | check: 12 | cargo check --workspace --lib --tests 13 | 14 | lock: check 15 | ./.github/workflows/scripts/check-cargo-lock.sh 16 | 17 | clippy: 18 | cargo clippy --workspace -- "${CLIPPY_OPTIONS}" 19 | 20 | test: 21 | cargo test --workspace 22 | 23 | doc: 24 | cargo doc --document-private-items --no-deps --open 25 | 26 | build: 27 | cargo build --release 28 | 29 | register: 30 | nu --commands "register target/release/nu_plugin_explore" 31 | 32 | install: 33 | cargo install --path . 34 | nu --commands "register ${CARGO_HOME}/bin/nu_plugin_explore" 35 | 36 | clean: 37 | cargo clean 38 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # nu_plugin_explore 2 | A fast *interactive explorer* tool for *structured data* inspired by [`nu-explore`] 3 | 4 | # table of content 5 | - [*introduction*](#introduction) 6 | - [*the idea behind an explorer*](#the-idea-behind-an-explorer) 7 | - [*why not `nu-explore`?*](#why-not-nu-explore) 8 | - [*installation*](#installation) 9 | - [*using `nupm install` (recommended)*](#using-nupm-install-recommended) 10 | - [*building from source*](#building-from-source) 11 | - [*usage*](#usage) 12 | - [*demo*](#demo) 13 | - [*configuration*](#configuration) 14 | - [*default configuration*](#default-configuration) 15 | - [*an example*](#an-example) 16 | - [*some convenience*](#-some-convenience) 17 | - [*see the documentation locally*](#see-the-documentation-locally) 18 | - [*troubleshooting*](#troubleshooting) 19 | - [*contributing*](#contributing) 20 | - [*TODO*](#todo) 21 | - [*features*](#features) 22 | - [*internal*](#internal) 23 | 24 | # introduction 25 | ## the idea behind an *explorer* 26 | i think having an *interactive explorer* for *structured data* is a requirement for a shell like 27 | [Nushell]! 28 | the ability to 29 | - traverse the data with a few quick key bindings 30 | - peek the data at any level 31 | - edit the data on the fly (COMING SOON) 32 | - all while being configurable 33 | 34 | will come very handy in a day-to-day basis for me at least :) 35 | 36 | ## why not `nu-explore`? 37 | - it's a bit too complex for what it does to me 38 | - the bindings are not configurable 39 | - the code was really hard to wrap my head around 40 | - i wanted to have fun learning about [Nushell] plugins and TUI applications in Rust 41 | 42 | so here we are... LET'S GO :muscle: 43 | 44 | # installation 45 | > **Important** 46 | > if you are using bleeding-edge versions of Nushell, please make sure the 47 | > Nushell dependencies are the same as your Nushell install by running 48 | > ```nushell 49 | > use scripts/deps.nu; deps --current 50 | > ``` 51 | 52 | ## using `nupm install` (recommended) 53 | - download [nushell/nupm](https://github.com/nushell/nupm) 54 | - load the `nupm` module 55 | ```nushell 56 | use /path/to/nupm/ 57 | ``` 58 | - run the install process 59 | ```nushell 60 | nupm install --path . 61 | ``` 62 | ## building from source 63 | - build the plugin 64 | ```shell 65 | make build 66 | ``` 67 | - register the plugin in [Nushell] 68 | ```nushell 69 | make register 70 | ``` 71 | - do not forget to restart [Nushell] 72 | 73 | > **Note** 74 | > alternatively, you can use directly `make install` 75 | 76 | # usage 77 | - get some help 78 | ```nushell 79 | help nu_plugin_explore 80 | ``` 81 | - run the command 82 | ```nushell 83 | open Cargo.toml | nu_plugin_explore 84 | ``` 85 | 86 | ## demo 87 | ![simple demo](examples/demo.gif) 88 | 89 | # configuration 90 | ## default configuration 91 | you can find it in [`default.nuon`](./examples/config/default.nuon). 92 | 93 | you can copy-paste it in your `config.nu` and set `$env.config.plugins.explore` to it: 94 | ```nushell 95 | $env.config.plugins.explore = { 96 | # content of the default config 97 | } 98 | ``` 99 | alternately, you can copy-paste the default config file to `$nu.default-config-dir` and add the following line to your `config.nu` 100 | ```nushell 101 | $env.config.plugins.explore = (open ($nu.default-config-dir | path join "nu_plugin_explore.nu")) 102 | ``` 103 | 104 | ## an example 105 | if you do not like the Vim bindings by default you can replace the navigation part with 106 | ```nushell 107 | $env.config.plugins.explore.keybindings.navigation = { 108 | left: 'left', 109 | down: 'down', 110 | up: 'up', 111 | right: 'right', 112 | } 113 | ``` 114 | and voila :yum: 115 | 116 | # see the documentation locally 117 | ```nushell 118 | cargo doc --document-private-items --no-deps --open 119 | ``` 120 | 121 | # troubleshooting 122 | in case you get some weird error or behaviour, before filing any issue, the 123 | easiest is to make sure the plugin is compiled with the same revision as the 124 | Nushell you are using! 125 | ```nushell 126 | use scripts/deps.nu; deps --current 127 | ``` 128 | and then you can come back to the [*installation*](#installation) section. 129 | 130 | > **Note** 131 | > of course, this will not work if the version of Nushell you are using is too 132 | > old, because then the state of `nu_plugin_explore` will be too recent for 133 | > everything to compile properly... 134 | 135 | # contributing 136 | in order to help, you can have a look at 137 | - the [todo](#todo) list down below, there might be unticked tasks to tackle 138 | - the issues and bugs in the [issue tracker](https://github.com/amtoine/nu_plugin_explore/issues) 139 | - the `FIXME` and `TODO` comments in the source base 140 | 141 | # TODO 142 | ## features 143 | - [x] support non-character bindings 144 | - [ ] when going into a file or URL, open it 145 | - [x] give different colors to names and type 146 | - [x] show true tables as such 147 | - [x] get the config from `$env.config` => can parse configuration from CLI 148 | - [x] add check for the config to make sure it's valid 149 | - [x] support for editing cells in INSERT mode 150 | - [x] string cells 151 | - [x] other simple cells 152 | - [x] all the cells 153 | - [x] detect if a string is of a particular type, path, URL, ... 154 | 155 | ## internal 156 | - [x] add tests... 157 | - [x] to `navigation.rs` to make sure the navigation in the data is ok 158 | - [x] to `app.rs` to make sure the application state machine works 159 | - [x] to `parsing.rs` to make sure the parsing of the config works 160 | - [x] to `tui.rs` to make sure the rendering works as intended 161 | - [ ] get rid of the `.clone`s 162 | - [ ] handle errors properly (`.unwrap`s and `panic!`s) 163 | - [ ] restrict the visibility of objects when possible 164 | - [ ] write better error messages when some test fails 165 | 166 | [Nushell]: https://nushell.sh 167 | [nushell/nushell]: https://github.com/nushell/nushell 168 | [`nu-explore`]: https://crates.io/crates/nu-explore 169 | 170 | [`nu-plugin`]: https://crates.io/crates/nu-plugin 171 | [`nu-protocol`]: https://crates.io/crates/nu-protocol 172 | [crates.io]: https://crates.io 173 | -------------------------------------------------------------------------------- /build.nu: -------------------------------------------------------------------------------- 1 | use std log 2 | 3 | 4 | def main [package_file: path] { 5 | let repo_root = $package_file | path dirname 6 | let install_root = $env.NUPM_HOME | path join "plugins" 7 | 8 | let name = open ($repo_root | path join "Cargo.toml") | get package.name 9 | 10 | cargo install --path $repo_root --root $install_root 11 | plugin add ($install_root | path join "bin" $name) 12 | 13 | log info "do not forget to restart Nushell for the plugin to be fully available!" 14 | } 15 | -------------------------------------------------------------------------------- /examples/config/default.nuon: -------------------------------------------------------------------------------- 1 | { 2 | show_cell_path: true, # whether or not to show the current cell path above the status bar 3 | show_table_header: true, # whether or not to show the table header in "table" layout 4 | show_hints: true, # whether or not to show the hints with keybindings 5 | layout: "table", # the layout of the data, either "table" or "compact" 6 | margin: 10, # the number of lines to keep between the cursor and the top / bottom 7 | number: false, # show line numbers 8 | relativenumber: false, # show line numbers, relative to the current one (overrides number) 9 | 10 | # "reset" is used instead of "black" in a dark terminal because, when the terminal is actually 11 | # black, "black" is not really black which is ugly, whereas "reset" is really black. 12 | colors: { 13 | normal: { # the colors for a normal row 14 | name: { 15 | background: reset, 16 | foreground: green, 17 | }, 18 | data: { 19 | background: reset, 20 | foreground: white, 21 | }, 22 | shape: { 23 | background: reset, 24 | foreground: blue, 25 | }, 26 | }, 27 | selected: { # the colors for the row under the cursor 28 | background: white, 29 | foreground: black, 30 | }, 31 | selected_modifier: "bold", # a modifier to apply onto the row under the cursor 32 | selected_symbol: "", # the symbol to show to the left of the row under the cursor 33 | status_bar: { 34 | normal: { # the colors for the status bar in NORMAL mode 35 | background: black, 36 | foreground: white, 37 | }, 38 | insert: { # the colors for the status bar in INSERT mode 39 | background: black, 40 | foreground: lightyellow, 41 | }, 42 | peek: { # the colors for the status bar in PEEKING mode 43 | background: black, 44 | foreground: lightgreen, 45 | } 46 | bottom: { # the colors for the status bar in BOTTOM mode 47 | background: black, 48 | foreground: lightmagenta, 49 | } 50 | } 51 | editor: { # the colors when editing a cell 52 | frame: { 53 | background: black, 54 | foreground: lightcyan, 55 | }, 56 | buffer: { 57 | background: reset, 58 | foreground: white, 59 | }, 60 | }, 61 | warning: { 62 | foreground: red, 63 | background: yellow, 64 | }, 65 | line_numbers: { 66 | normal: { 67 | background: reset, 68 | foreground: white, 69 | }, 70 | selected: { 71 | background: white, 72 | foreground: black, 73 | }, 74 | }, 75 | } 76 | keybindings: { 77 | quit: 'q', # quit `explore` 78 | insert: 'i', # go to INSERT mode to modify the data 79 | normal: "escape", # go back to NORMAL mode to navigate through the data 80 | navigation: { # only in NORMAL mode 81 | left: 'h', # go back one level in the data 82 | down: 'j', # go one row down in the current level 83 | up: 'k', # go one row up in the current level 84 | right: 'l', # go one level deeper in the data or hit the bottom 85 | half_page_down: "", # go one half page up in the data 86 | half_page_up: "", # go one half page down in the data 87 | goto_top: 'g', # go to the top of the data, i.e. the first element or the first key 88 | goto_bottom: 'G', # go to the bottom of the data, i.e. the last element or the last key 89 | goto_line: 'g', # go at a particular line in the data 90 | }, 91 | peek: 'p', # go to PEEKING mode to peek a value 92 | peeking: { # only in PEEKING mode 93 | all: 'a', # peek the whole data, from the top level 94 | cell_path: 'c', # peek the cell path under the cursor 95 | under: 'p', # peek only what's under the cursor 96 | view: 'v', # peek the current view, i.e. what is visible 97 | }, 98 | transpose: 't', # transpose the data if it's a table or a record, this is an *involution* 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /examples/demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amtoine/nu_plugin_explore/fa5ab698463489bfc782077915f636661712a217/examples/demo.gif -------------------------------------------------------------------------------- /nupm.nuon: -------------------------------------------------------------------------------- 1 | { 2 | name: nu_plugin_explore, 3 | version: "0.102.0", 4 | description: "A fast structured data explorer for Nushell.", 5 | license: LICENSE, 6 | type: custom 7 | } 8 | -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | profile = "default" 3 | channel = "1.82" 4 | -------------------------------------------------------------------------------- /scripts/deps.nu: -------------------------------------------------------------------------------- 1 | const NUSHELL_REMOTE = "https://github.com/nushell/nushell" 2 | const PKGS = [ "nuon", "nu-protocol", "nu-plugin" ] 3 | 4 | # setup Nushell dependencies 5 | # 6 | # > **Note** 7 | # > options are shown in inverse order of precedence 8 | export def main [ 9 | --rev: string, # a Nushell revision 10 | --tag: string, # a Nushell tag 11 | --current, # use the current Nushell version 12 | ] { 13 | let opts = if $current { 14 | if (version).commit_hash != null { 15 | print $"using current revision of Nushell: (version | get commit_hash)" 16 | [ --rev (version).commit_hash ] 17 | } else { 18 | print $"using current version of Nushell: (version | get version)" 19 | [ --tag (version).version ] 20 | } 21 | } else { 22 | if $tag != null { 23 | print $"using user version: ($tag)" 24 | [ --tag $tag ] 25 | } else if $rev != null { 26 | print $"using user revision: ($rev)" 27 | [ --rev $rev ] 28 | } else { 29 | error make --unspanned { msg: "please give either `--rev` or `--tag`" } 30 | } 31 | } 32 | 33 | let dependencies = open Cargo.toml | get dependencies 34 | for pkg in $PKGS { 35 | if $pkg in $dependencies { 36 | cargo remove $pkg 37 | } 38 | } 39 | 40 | for pkg in $PKGS { 41 | cargo add $pkg --git $NUSHELL_REMOTE ...$opts 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/app.rs: -------------------------------------------------------------------------------- 1 | //! the higher level application 2 | use nu_protocol::{ 3 | ast::{CellPath, PathMember}, 4 | Span, Value, 5 | }; 6 | 7 | use crate::{config::Config, edit::Editor}; 8 | 9 | /// the mode in which the application is 10 | #[derive(Clone, Debug, PartialEq, Default)] 11 | pub enum Mode { 12 | /// the *navigation* mode, where the user can move around in the data 13 | #[default] 14 | Normal, 15 | /// lets the user edit cells of the structured data 16 | Insert, 17 | /// lets the user *peek* data out of the application, to be reused later 18 | Peeking, 19 | /// indicates that the user has arrived to the very bottom of the nested data, i.e. there is 20 | /// nothing more to the right 21 | Bottom, 22 | /// waits for more keys to perform an action, e.g. jumping to a line or motion repetition that 23 | /// both require to enter a number before the actual action 24 | Waiting(usize), 25 | } 26 | 27 | impl std::fmt::Display for Mode { 28 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 29 | let repr = match self { 30 | Self::Normal => "NORMAL", 31 | Self::Insert => "INSERT", 32 | Self::Peeking => "PEEKING", 33 | Self::Bottom => "BOTTOM", 34 | Self::Waiting(_) => "WAITING", 35 | }; 36 | write!(f, "{}", repr) 37 | } 38 | } 39 | 40 | #[derive(Clone)] 41 | /// the complete state of the application 42 | pub struct App { 43 | /// the full current path in the data 44 | pub position: CellPath, 45 | /// used for rendering 46 | pub rendering_tops: Vec, 47 | /// the current [`Mode`] 48 | pub mode: Mode, 49 | /// the editor to modify the cells of the data 50 | pub editor: Editor, 51 | /// the value that is being explored 52 | pub value: Value, 53 | /// the configuration for the app 54 | pub config: Config, 55 | } 56 | 57 | impl Default for App { 58 | fn default() -> Self { 59 | Self { 60 | position: CellPath { members: vec![] }, 61 | rendering_tops: vec![], 62 | mode: Mode::default(), 63 | editor: Editor::default(), 64 | value: Value::default(), 65 | config: Config::default(), 66 | } 67 | } 68 | } 69 | 70 | impl App { 71 | /// Handles the tick event of the terminal. 72 | pub fn tick(&self) {} 73 | 74 | pub(super) fn from_value(value: Value) -> Self { 75 | let mut app = Self::default(); 76 | 77 | match &value { 78 | Value::List { vals, .. } => app.position.members.push(PathMember::Int { 79 | val: 0, 80 | span: Span::unknown(), 81 | optional: vals.is_empty(), 82 | }), 83 | Value::Record { val: rec, .. } => { 84 | let cols = rec.columns().cloned().collect::>(); 85 | 86 | app.position.members.push(PathMember::String { 87 | val: cols.first().unwrap_or(&"".to_string()).into(), 88 | span: Span::unknown(), 89 | optional: cols.is_empty(), 90 | }) 91 | } 92 | _ => {} 93 | } 94 | 95 | app.value = value; 96 | 97 | app 98 | } 99 | 100 | pub fn is_at_bottom(&self) -> bool { 101 | matches!(self.mode, Mode::Bottom) 102 | } 103 | 104 | pub fn hit_bottom(&mut self) { 105 | self.mode = Mode::Bottom; 106 | } 107 | 108 | pub(super) fn enter_editor(&mut self) { 109 | let value = self.value_under_cursor(None); 110 | 111 | self.mode = Mode::Insert; 112 | self.editor = Editor::from_value(&value); 113 | } 114 | 115 | pub(crate) fn value_under_cursor(&self, alternate_cursor: Option) -> Value { 116 | self.value 117 | .clone() 118 | .follow_cell_path( 119 | &alternate_cursor.unwrap_or(self.position.clone()).members, 120 | false, 121 | ) 122 | .unwrap_or_else(|_| { 123 | panic!( 124 | "unexpected error when following {:?} in {}", 125 | self.position.members, 126 | self.value 127 | .to_expanded_string(" ", &nu_protocol::Config::default()) 128 | ) 129 | }) 130 | } 131 | 132 | pub(crate) fn with_config(&self, config: Config) -> Self { 133 | let mut app = self.clone(); 134 | app.config = config; 135 | app 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /src/config/parsing.rs: -------------------------------------------------------------------------------- 1 | //! utilities to parse a [`Value`](https://docs.rs/nu-protocol/0.83.1/nu_protocol/enum.Value.html) 2 | //! into a configuration 3 | use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; 4 | use ratatui::style::{Color, Modifier}; 5 | 6 | use nu_protocol::LabeledError; 7 | use nu_protocol::{ast::PathMember, Span, Value}; 8 | 9 | use super::{BgFgColorConfig, Layout}; 10 | 11 | /// return an *invalid field* error 12 | /// 13 | /// # Example 14 | /// ```text 15 | /// invalid_field(&["foo"], Some(span)) 16 | /// ``` 17 | /// would give an error like 18 | /// ```nushell 19 | /// Error: × invalid config 20 | /// ╭─[entry #3:1:1] 21 | /// 1 │ explore {foo: 123} 22 | /// · ─────┬──── 23 | /// · ╰── `$.foo` is not a valid config field 24 | /// ╰──── 25 | /// ``` 26 | pub fn invalid_field(cell_path: &[&str], span: Span) -> LabeledError { 27 | LabeledError::new("invalid config").with_label( 28 | format!("`$.{}` is not a valid config field", cell_path.join("."),), 29 | span, 30 | ) 31 | } 32 | 33 | /// return an *invalid type* error 34 | /// 35 | /// # Example 36 | /// ```text 37 | /// invalid_type(&some_int, &["layout"], "string"), 38 | /// ``` 39 | /// would give an error like 40 | /// ```nushell 41 | /// Error: × invalid config 42 | /// ╭─[entry #7:1:1] 43 | /// 1 │ explore {layout: 123} 44 | /// · ─┬─ 45 | /// · ╰── `$.layout` should be a string, found int 46 | /// ╰──── 47 | /// ``` 48 | pub fn invalid_type(value: &Value, cell_path: &[&str], expected: &str) -> LabeledError { 49 | LabeledError::new("invalid config").with_label( 50 | format!( 51 | "`$.{}` should be a {expected}, found {}", 52 | cell_path.join("."), 53 | value.get_type() 54 | ), 55 | value.span(), 56 | ) 57 | } 58 | 59 | fn u8_out_of_range(value: i64, cell_path: &[&str], span: Span) -> LabeledError { 60 | LabeledError::new("invalid config").with_label( 61 | format!( 62 | "`$.{}` should be an integer between 0 and 255, found {}", 63 | cell_path.join("."), 64 | value 65 | ), 66 | span, 67 | ) 68 | } 69 | 70 | pub fn positive_integer(value: i64, cell_path: &[&str], span: Span) -> LabeledError { 71 | LabeledError::new("invalid config").with_label( 72 | format!( 73 | "`$.{}` should be a positive integer, found {}", 74 | cell_path.join("."), 75 | value 76 | ), 77 | span, 78 | ) 79 | } 80 | 81 | /// try to parse a bool in the *value* at the given *cell path* 82 | pub fn try_bool(value: &Value, cell_path: &[&str]) -> Result, LabeledError> { 83 | match follow_cell_path(value, cell_path) { 84 | Some(Value::Bool { val, .. }) => Ok(Some(val)), 85 | Some(x) => Err(invalid_type(&x, cell_path, "bool")), 86 | _ => Ok(None), 87 | } 88 | } 89 | 90 | /// try to parse a string in the *value* at the given *cell path* 91 | pub fn try_string(value: &Value, cell_path: &[&str]) -> Result, LabeledError> { 92 | match follow_cell_path(value, cell_path) { 93 | Some(Value::String { val, .. }) => Ok(Some(val)), 94 | Some(x) => Err(invalid_type(&x, cell_path, "string")), 95 | _ => Ok(None), 96 | } 97 | } 98 | 99 | /// try to parse an integer in the *value* at the given *cell path* 100 | pub fn try_int(value: &Value, cell_path: &[&str]) -> Result, LabeledError> { 101 | match follow_cell_path(value, cell_path) { 102 | Some(Value::Int { val, .. }) => Ok(Some(val)), 103 | Some(x) => Err(invalid_type(&x, cell_path, "int")), 104 | _ => Ok(None), 105 | } 106 | } 107 | 108 | /// try to parse an ANSI modifier in the *value* at the given *cell path* 109 | pub fn try_modifier(value: &Value, cell_path: &[&str]) -> Result, LabeledError> { 110 | match follow_cell_path(value, cell_path) { 111 | Some(Value::Nothing { .. }) => Ok(Some(Modifier::empty())), 112 | Some(Value::String { val, .. }) => match val.as_str() { 113 | "" => Ok(Some(Modifier::empty())), 114 | "bold" => Ok(Some(Modifier::BOLD)), 115 | "italic" => Ok(Some(Modifier::ITALIC)), 116 | "underline" => Ok(Some(Modifier::UNDERLINED)), 117 | "blink" => Ok(Some(Modifier::SLOW_BLINK)), 118 | x => Err(LabeledError::new( 119 | "invalid config").with_label( 120 | format!( 121 | r#"`$.{}` should be the empty string, one of [italic, bold, underline, blink] or null, found {}"#, 122 | cell_path.join("."), 123 | x 124 | ), 125 | value.span() 126 | )), 127 | }, 128 | Some(x) => Err(invalid_type(&x, cell_path, "string or null")), 129 | _ => Ok(None), 130 | } 131 | } 132 | 133 | /// try to parse a color in the *value* at the given *cell path* 134 | fn try_color(value: &Value, cell_path: &[&str]) -> Result, LabeledError> { 135 | match follow_cell_path(value, cell_path) { 136 | Some(Value::String { val, .. }) => match val.as_str() { 137 | "reset" => Ok(Some(Color::Reset)), 138 | "black" => Ok(Some(Color::Black)), 139 | "red" => Ok(Some(Color::Red)), 140 | "green" => Ok(Some(Color::Green)), 141 | "yellow" => Ok(Some(Color::Yellow)), 142 | "blue" => Ok(Some(Color::Blue)), 143 | "magenta" => Ok(Some(Color::Magenta)), 144 | "cyan" => Ok(Some(Color::Cyan)), 145 | "gray" => Ok(Some(Color::Gray)), 146 | "darkgray" => Ok(Some(Color::DarkGray)), 147 | "lightred" => Ok(Some(Color::LightRed)), 148 | "lightgreen" => Ok(Some(Color::LightGreen)), 149 | "lightyellow" => Ok(Some(Color::LightYellow)), 150 | "lightblue" => Ok(Some(Color::LightBlue)), 151 | "lightmagenta" => Ok(Some(Color::LightMagenta)), 152 | "lightcyan" => Ok(Some(Color::LightCyan)), 153 | "white" => Ok(Some(Color::White)), 154 | x => Err(LabeledError::new( 155 | "invalid config").with_label( 156 | format!( 157 | r#"`$.{}` should be a u8, a list of three u8s or one of [black, red, green, yellow, blue, magenta, cyan, gray, darkgray, lightred, lightgreen, lightyellow, lightblue, lightmagenta, lightcyan, white] , found {}"#, 158 | cell_path.join("."), 159 | x 160 | ), 161 | value.span() 162 | )), 163 | }, 164 | Some(Value::Int { val, .. }) => { 165 | if !(0..=255).contains(&val) { 166 | // FIXME: use a real span? 167 | return Err(u8_out_of_range(val, cell_path, Span::unknown())); 168 | } 169 | 170 | Ok(Some(Color::Rgb(val as u8, val as u8, val as u8))) 171 | } 172 | Some(Value::List { vals, .. }) => { 173 | if vals.len() != 3 { 174 | return Err(LabeledError::new( 175 | "invalid config").with_label( 176 | format!("`$.{}` is not a valid config field, expected a list of three u8, found {} items", cell_path.join("."), vals.len()), 177 | // FIXME: use a real span? 178 | Span::unknown(), 179 | )); 180 | } 181 | 182 | let mut channels: Vec = vec![]; 183 | 184 | for (i, val) in vals.iter().enumerate() { 185 | let mut cell_path = cell_path.to_vec().clone(); 186 | 187 | let tail = format!("{}", i); 188 | cell_path.push(&tail); 189 | 190 | match val { 191 | Value::Int { val: x, .. } => { 192 | if (*x < 0) | (*x > 255) { 193 | return Err(u8_out_of_range(*x, &cell_path, val.span())); 194 | } 195 | 196 | channels.push(*x as u8); 197 | } 198 | x => { 199 | return Err(invalid_type(x, &cell_path, "u8")); 200 | } 201 | } 202 | } 203 | 204 | Ok(Some(Color::Rgb(channels[0], channels[1], channels[2]))) 205 | } 206 | Some(x) => Err(invalid_type(&x, cell_path, "string, u8 or [u8, u8, u8]")), 207 | _ => Ok(None), 208 | } 209 | } 210 | 211 | /// try to parse a background / foreground color pair in the *value* at the given *cell path* 212 | pub fn try_fg_bg_colors( 213 | value: &Value, 214 | cell_path: &[&str], 215 | default: &BgFgColorConfig, 216 | ) -> Result, LabeledError> { 217 | let cell = match follow_cell_path(value, cell_path) { 218 | Some(c) => c, 219 | None => return Ok(None), 220 | }; 221 | 222 | let columns = match &cell { 223 | Value::Record { val: rec, .. } => rec.columns().collect::>(), 224 | x => return Err(invalid_type(x, cell_path, "record")), 225 | }; 226 | 227 | let mut colors: BgFgColorConfig = default.clone(); 228 | 229 | for column in columns { 230 | match column.as_str() { 231 | "background" => { 232 | let mut cell_path = cell_path.to_vec(); 233 | cell_path.push("background"); 234 | if let Some(val) = try_color(value, &cell_path)? { 235 | colors.background = val 236 | } 237 | } 238 | "foreground" => { 239 | let mut cell_path = cell_path.to_vec(); 240 | cell_path.push("foreground"); 241 | if let Some(val) = try_color(value, &cell_path)? { 242 | colors.foreground = val 243 | } 244 | } 245 | x => { 246 | let mut cell_path = cell_path.to_vec(); 247 | cell_path.push(x); 248 | return Err(invalid_field(&cell_path, cell.span())); 249 | } 250 | } 251 | } 252 | 253 | Ok(Some(colors)) 254 | } 255 | 256 | /// try to parse a key in the *value* at the given *cell path* 257 | pub fn try_key(value: &Value, cell_path: &[&str]) -> Result, LabeledError> { 258 | match follow_cell_path(value, cell_path) { 259 | Some(Value::String { val, .. }) => match val.as_str() { 260 | "up" => Ok(Some(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE))), 261 | "down" => Ok(Some(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE))), 262 | "left" => Ok(Some(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE))), 263 | "right" => Ok(Some(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE))), 264 | "escape" => Ok(Some(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE))), 265 | x => { 266 | if x.len() != 1 { 267 | if x.len() == 5 268 | && (x.starts_with("') 270 | { 271 | #[allow(clippy::iter_nth_zero)] 272 | return Ok(Some(KeyEvent::new( 273 | // NOTE: this `unwrap` cannot fail because the length of `x` is `5` 274 | KeyCode::Char(x.to_string().chars().nth(3).unwrap()), 275 | KeyModifiers::CONTROL, 276 | ))); 277 | } 278 | 279 | return Err(LabeledError::new( 280 | "invalid config") 281 | .with_label(format!( 282 | r#"`$.{}` should be a character, possibly inside '' or '', or one of [up, down, left, right, escape] , found {}"#, 283 | cell_path.join("."), 284 | x 285 | ), 286 | value.span() 287 | )); 288 | } 289 | 290 | #[allow(clippy::iter_nth_zero)] 291 | Ok(Some(KeyEvent::new( 292 | // NOTE: this `unwrap` cannot fail because the length of `x` is `1` 293 | KeyCode::Char(x.to_string().chars().nth(0).unwrap()), 294 | KeyModifiers::NONE, 295 | ))) 296 | } 297 | }, 298 | Some(x) => Err(invalid_type(&x, cell_path, "string")), 299 | _ => Ok(None), 300 | } 301 | } 302 | 303 | /// try to parse a layout in the *value* at the given *cell path* 304 | pub fn try_layout(value: &Value, cell_path: &[&str]) -> Result, LabeledError> { 305 | match follow_cell_path(value, cell_path) { 306 | Some(Value::String { val, .. }) => match val.as_str() { 307 | "table" => Ok(Some(Layout::Table)), 308 | "compact" => Ok(Some(Layout::Compact)), 309 | x => Err(LabeledError::new("invalid config").with_label( 310 | format!( 311 | r#"`$.{}` should be one of [table, compact] , found {}"#, 312 | cell_path.join("."), 313 | x 314 | ), 315 | value.span(), 316 | )), 317 | }, 318 | Some(x) => Err(invalid_type(&x, cell_path, "string")), 319 | _ => Ok(None), 320 | } 321 | } 322 | 323 | /// follow a cell path into a Value, giving the resulting Value if it exists 324 | /// 325 | /// # Example 326 | /// ```text 327 | /// follow_cell_path(&value, &["foo", "bar", "baz"]).unwrap() 328 | /// ``` 329 | /// would give `123` in a Nushell structure such as 330 | /// ```nushell 331 | /// { 332 | /// foo: { 333 | /// bar: { 334 | /// baz: 123 335 | /// } 336 | /// } 337 | /// } 338 | /// ``` 339 | pub fn follow_cell_path(value: &Value, cell_path: &[&str]) -> Option { 340 | let cell_path = cell_path 341 | .iter() 342 | .map(|cp| PathMember::String { 343 | val: cp.to_string(), 344 | span: Span::unknown(), 345 | optional: false, 346 | }) 347 | .collect::>(); 348 | 349 | value.clone().follow_cell_path(&cell_path, false).ok() 350 | } 351 | 352 | // TODO: add proper assert error messages 353 | #[cfg(test)] 354 | mod tests { 355 | use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; 356 | use nu_protocol::LabeledError; 357 | use nu_protocol::{record, Record, Value}; 358 | use ratatui::style::{Color, Modifier}; 359 | 360 | use super::{ 361 | follow_cell_path, try_bool, try_color, try_fg_bg_colors, try_int, try_key, try_layout, 362 | try_modifier, try_string, 363 | }; 364 | use crate::config::{BgFgColorConfig, Layout}; 365 | 366 | #[test] 367 | fn follow_str_cell_path() { 368 | let inner_record_a = Value::test_int(1); 369 | let inner_record_b = Value::test_int(2); 370 | let record = Value::test_record(record! { 371 | "a" => inner_record_a.clone(), 372 | "b" => inner_record_b.clone(), 373 | }); 374 | let string = Value::test_string("some string"); 375 | let int = Value::test_int(123); 376 | 377 | let value = Value::test_record(record! { 378 | "r" => record.clone(), 379 | "s" => string.clone(), 380 | "i" => int.clone(), 381 | }); 382 | 383 | assert_eq!(follow_cell_path(&value, &[]), Some(value.clone())); 384 | assert_eq!(follow_cell_path(&value, &["r"]), Some(record)); 385 | assert_eq!(follow_cell_path(&value, &["s"]), Some(string)); 386 | assert_eq!(follow_cell_path(&value, &["i"]), Some(int)); 387 | assert_eq!(follow_cell_path(&value, &["x"]), None); 388 | assert_eq!(follow_cell_path(&value, &["r", "a"]), Some(inner_record_a)); 389 | assert_eq!(follow_cell_path(&value, &["r", "b"]), Some(inner_record_b)); 390 | assert_eq!(follow_cell_path(&value, &["r", "x"]), None); 391 | } 392 | 393 | fn test_tried_error( 394 | result: Result, LabeledError>, 395 | cell_path: &str, 396 | expected: &str, 397 | ) { 398 | assert!(result.is_err()); 399 | let err = result.err().unwrap(); 400 | assert_eq!(err.labels.len(), 1); 401 | assert_eq!(err.msg, "invalid config"); 402 | assert_eq!( 403 | err.labels[0].text, 404 | format!("`$.{}` {}", cell_path, expected) 405 | ); 406 | } 407 | 408 | #[test] 409 | fn trying_bool() { 410 | test_tried_error( 411 | try_bool(&Value::test_string("not a bool"), &[]), 412 | "", 413 | "should be a bool, found string", 414 | ); 415 | test_tried_error( 416 | try_bool(&Value::test_int(123), &[]), 417 | "", 418 | "should be a bool, found int", 419 | ); 420 | 421 | assert_eq!(try_bool(&Value::test_bool(true), &[]), Ok(Some(true))); 422 | assert_eq!(try_bool(&Value::test_bool(false), &[]), Ok(Some(false))); 423 | assert_eq!(try_bool(&Value::test_nothing(), &["x"]), Ok(None)); 424 | } 425 | 426 | #[test] 427 | fn trying_string() { 428 | test_tried_error( 429 | try_string(&Value::test_bool(true), &[]), 430 | "", 431 | "should be a string, found bool", 432 | ); 433 | test_tried_error( 434 | try_string(&Value::test_int(123), &[]), 435 | "", 436 | "should be a string, found int", 437 | ); 438 | 439 | assert_eq!( 440 | try_string(&Value::test_string("my string"), &[]), 441 | Ok(Some("my string".to_string())) 442 | ); 443 | assert_eq!( 444 | try_string(&Value::test_string("my string"), &["x"]), 445 | Ok(None) 446 | ); 447 | } 448 | 449 | #[test] 450 | fn trying_int() { 451 | test_tried_error( 452 | try_int(&Value::test_bool(true), &[]), 453 | "", 454 | "should be a int, found bool", 455 | ); 456 | test_tried_error( 457 | try_int(&Value::test_string("my string"), &[]), 458 | "", 459 | "should be a int, found string", 460 | ); 461 | 462 | assert_eq!(try_int(&Value::test_int(123), &[]), Ok(Some(123))); 463 | assert_eq!(try_int(&Value::test_int(-123), &[]), Ok(Some(-123))); 464 | assert_eq!(try_int(&Value::test_int(123), &["x"]), Ok(None)); 465 | } 466 | 467 | #[test] 468 | fn trying_key() { 469 | test_tried_error( 470 | try_key(&Value::test_bool(true), &[]), 471 | "", 472 | "should be a string, found bool", 473 | ); 474 | test_tried_error( 475 | try_key(&Value::test_int(123), &[]), 476 | "", 477 | "should be a string, found int", 478 | ); 479 | test_tried_error( 480 | try_key(&Value::test_string("enter"), &[]), 481 | "", 482 | "should be a character, possibly inside '' or '', or one of [up, down, left, right, escape] , found enter", 483 | ); 484 | 485 | let cases = vec![ 486 | ("up", KeyEvent::new(KeyCode::Up, KeyModifiers::NONE)), 487 | ("down", KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)), 488 | ("left", KeyEvent::new(KeyCode::Left, KeyModifiers::NONE)), 489 | ("right", KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)), 490 | ("escape", KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)), 491 | ("a", KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE)), 492 | ("b", KeyEvent::new(KeyCode::Char('b'), KeyModifiers::NONE)), 493 | ("x", KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE)), 494 | ("x", KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE)), 495 | ( 496 | "", 497 | KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL), 498 | ), 499 | ]; 500 | 501 | for (input, expected) in cases { 502 | assert_eq!(try_key(&Value::test_string(input), &[]), Ok(Some(expected))); 503 | } 504 | } 505 | 506 | #[test] 507 | fn trying_layout() { 508 | test_tried_error( 509 | try_layout(&Value::test_bool(true), &[]), 510 | "", 511 | "should be a string, found bool", 512 | ); 513 | test_tried_error( 514 | try_layout(&Value::test_int(123), &[]), 515 | "", 516 | "should be a string, found int", 517 | ); 518 | test_tried_error( 519 | try_layout(&Value::test_string("collapsed"), &[]), 520 | "", 521 | "should be one of [table, compact] , found collapsed", 522 | ); 523 | 524 | let cases = vec![("table", Layout::Table), ("compact", Layout::Compact)]; 525 | 526 | for (input, expected) in cases { 527 | assert_eq!( 528 | try_layout(&Value::test_string(input), &[]), 529 | Ok(Some(expected)) 530 | ); 531 | } 532 | } 533 | 534 | #[test] 535 | fn trying_modifier() { 536 | test_tried_error( 537 | try_modifier(&Value::test_bool(true), &[]), 538 | "", 539 | "should be a string or null, found bool", 540 | ); 541 | test_tried_error( 542 | try_modifier(&Value::test_int(123), &[]), 543 | "", 544 | "should be a string or null, found int", 545 | ); 546 | test_tried_error( 547 | try_modifier(&Value::test_string("x"), &[]), 548 | "", 549 | "should be the empty string, one of [italic, bold, underline, blink] or null, found x", 550 | ); 551 | 552 | assert_eq!( 553 | try_modifier(&Value::test_nothing(), &[]), 554 | Ok(Some(Modifier::empty())) 555 | ); 556 | 557 | let cases = vec![ 558 | ("", Modifier::empty()), 559 | ("italic", Modifier::ITALIC), 560 | ("bold", Modifier::BOLD), 561 | ("underline", Modifier::UNDERLINED), 562 | ("blink", Modifier::SLOW_BLINK), 563 | ]; 564 | 565 | for (input, expected) in cases { 566 | assert_eq!( 567 | try_modifier(&Value::test_string(input), &[]), 568 | Ok(Some(expected)) 569 | ); 570 | } 571 | } 572 | 573 | #[test] 574 | fn trying_color() { 575 | test_tried_error( 576 | try_color(&Value::test_bool(true), &[]), 577 | "", 578 | "should be a string, u8 or [u8, u8, u8], found bool", 579 | ); 580 | test_tried_error( 581 | try_color(&Value::test_int(-1), &[]), 582 | "", 583 | "should be an integer between 0 and 255, found -1", 584 | ); 585 | test_tried_error( 586 | try_color(&Value::test_int(256), &[]), 587 | "", 588 | "should be an integer between 0 and 255, found 256", 589 | ); 590 | test_tried_error( 591 | try_color(&Value::test_list(vec![]), &[]), 592 | "", 593 | "is not a valid config field, expected a list of three u8, found 0 items", 594 | ); 595 | test_tried_error( 596 | try_color(&Value::test_list(vec![Value::test_int(1)]), &[]), 597 | "", 598 | "is not a valid config field, expected a list of three u8, found 1 items", 599 | ); 600 | test_tried_error( 601 | try_color( 602 | &Value::test_list(vec![Value::test_int(1), Value::test_int(2)]), 603 | &[], 604 | ), 605 | "", 606 | "is not a valid config field, expected a list of three u8, found 2 items", 607 | ); 608 | test_tried_error( 609 | try_color(&Value::test_string("x"), &[]), 610 | "", 611 | "should be a u8, a list of three u8s or one of [black, red, green, yellow, blue, magenta, cyan, gray, darkgray, lightred, lightgreen, lightyellow, lightblue, lightmagenta, lightcyan, white] , found x", 612 | ); 613 | 614 | let cases = vec![ 615 | (Value::test_string("black"), Color::Black), 616 | (Value::test_string("red"), Color::Red), 617 | (Value::test_string("green"), Color::Green), 618 | (Value::test_string("blue"), Color::Blue), 619 | (Value::test_int(123), Color::Rgb(123, 123, 123)), 620 | ( 621 | Value::test_list(vec![ 622 | Value::test_int(1), 623 | Value::test_int(2), 624 | Value::test_int(3), 625 | ]), 626 | Color::Rgb(1, 2, 3), 627 | ), 628 | ]; 629 | 630 | for (input, expected) in cases { 631 | assert_eq!(try_color(&input, &[]), Ok(Some(expected))); 632 | } 633 | } 634 | 635 | #[test] 636 | fn trying_fg_bg_colors() { 637 | let default_color = BgFgColorConfig { 638 | background: Color::Reset, 639 | foreground: Color::Reset, 640 | }; 641 | 642 | test_tried_error( 643 | try_fg_bg_colors(&Value::test_bool(true), &[], &default_color), 644 | "", 645 | "should be a record, found bool", 646 | ); 647 | test_tried_error( 648 | try_fg_bg_colors(&Value::test_int(123), &[], &default_color), 649 | "", 650 | "should be a record, found int", 651 | ); 652 | test_tried_error( 653 | try_fg_bg_colors(&Value::test_string("x"), &[], &default_color), 654 | "", 655 | "should be a record, found string", 656 | ); 657 | test_tried_error( 658 | try_fg_bg_colors( 659 | &Value::test_record(record! { 660 | "x" => Value::test_nothing(), 661 | }), 662 | &[], 663 | &default_color, 664 | ), 665 | "x", 666 | "is not a valid config field", 667 | ); 668 | 669 | let cases = vec![ 670 | (vec![], vec![], default_color.clone()), 671 | ( 672 | vec!["foreground"], 673 | vec![Value::test_string("green")], 674 | BgFgColorConfig { 675 | foreground: Color::Green, 676 | background: Color::Reset, 677 | }, 678 | ), 679 | ( 680 | vec!["background"], 681 | vec![Value::test_string("blue")], 682 | BgFgColorConfig { 683 | foreground: Color::Reset, 684 | background: Color::Blue, 685 | }, 686 | ), 687 | ( 688 | vec!["foreground", "background"], 689 | vec![Value::test_string("green"), Value::test_string("blue")], 690 | BgFgColorConfig { 691 | foreground: Color::Green, 692 | background: Color::Blue, 693 | }, 694 | ), 695 | ]; 696 | 697 | for (cols, vals, expected) in cases { 698 | let mut rec = Record::new(); 699 | cols.iter().zip(vals).for_each(|(col, val)| { 700 | rec.push(*col, val); 701 | }); 702 | assert_eq!( 703 | try_fg_bg_colors(&Value::test_record(rec), &[], &default_color), 704 | Ok(Some(expected)) 705 | ); 706 | } 707 | } 708 | } 709 | -------------------------------------------------------------------------------- /src/edit.rs: -------------------------------------------------------------------------------- 1 | use crossterm::event::KeyCode; 2 | use ratatui::{ 3 | layout::Position, prelude::Rect, style::Style, widgets::{Block, Borders, Clear, Paragraph, Wrap}, Frame 4 | }; 5 | 6 | use nu_protocol::{engine::EngineState, Span, Value}; 7 | use nuon::{from_nuon, to_nuon, ToStyle}; 8 | 9 | use crate::config::Config; 10 | 11 | #[derive(Default, Clone)] 12 | pub struct Editor { 13 | buffer: String, 14 | cursor_position: (usize, usize), 15 | width: usize, 16 | } 17 | 18 | #[derive(Debug, PartialEq)] 19 | pub enum EditorTransition { 20 | Continue, 21 | Quit, 22 | Value(Value), 23 | } 24 | 25 | impl Editor { 26 | /// set the width of the editor 27 | /// 28 | /// this method removes the frame on the left and the right if any 29 | pub(super) fn set_width(&mut self, width: usize) { 30 | self.width = width - 2; 31 | } 32 | 33 | pub(super) fn from_value(value: &Value) -> Self { 34 | let engine_state = EngineState::new(); 35 | Self { 36 | // NOTE: `value` should be a valid [`Value`] and thus the conversion should never fail 37 | buffer: to_nuon(&engine_state, value, ToStyle::Raw, None, true).unwrap(), 38 | cursor_position: (0, 0), 39 | width: 0, 40 | } 41 | } 42 | 43 | fn position(&self) -> usize { 44 | let (x, y) = self.cursor_position; 45 | y * self.width + x 46 | } 47 | 48 | fn move_cursor_left(&mut self) { 49 | let position = self 50 | .position() 51 | .saturating_sub(1) 52 | .clamp(0, self.buffer.len()); 53 | 54 | self.cursor_position = (position % self.width, position / self.width); 55 | } 56 | 57 | fn move_cursor_right(&mut self) { 58 | let position = self 59 | .position() 60 | .saturating_add(1) 61 | .clamp(0, self.buffer.len()); 62 | 63 | self.cursor_position = (position % self.width, position / self.width); 64 | } 65 | 66 | fn move_cursor_up(&mut self) { 67 | let (x, y) = self.cursor_position; 68 | let y = y.saturating_sub(1).clamp(0, self.buffer.len() / self.width); 69 | 70 | self.cursor_position = (x, y); 71 | } 72 | 73 | fn move_cursor_down(&mut self) { 74 | let (x, y) = self.cursor_position; 75 | let y = y.saturating_add(1).clamp(0, self.buffer.len() / self.width); 76 | 77 | self.cursor_position = (x, y); 78 | 79 | if self.position() > self.buffer.len() { 80 | self.cursor_position = ( 81 | self.buffer.len() % self.width, 82 | self.buffer.len() / self.width, 83 | ); 84 | } 85 | } 86 | 87 | fn enter_char(&mut self, c: char) { 88 | self.buffer.insert(self.position(), c); 89 | self.move_cursor_right(); 90 | } 91 | 92 | fn delete_char(&mut self, offset: i32) { 93 | let position = (self.position() as i32 + offset) as usize; 94 | 95 | // NOTE: work on the chars and do not use remove which works on bytes 96 | self.buffer = self 97 | .buffer 98 | .chars() 99 | .take(position) 100 | .chain(self.buffer.chars().skip(position + 1)) 101 | .collect(); 102 | } 103 | 104 | fn delete_char_before_cursor(&mut self) { 105 | let is_not_cursor_leftmost = self.position() != 0; 106 | 107 | if is_not_cursor_leftmost { 108 | self.delete_char(-1); 109 | self.move_cursor_left(); 110 | } 111 | } 112 | 113 | fn delete_char_under_cursor(&mut self) { 114 | self.delete_char(0); 115 | } 116 | 117 | pub(super) fn handle_key(&mut self, key: &KeyCode) -> Result { 118 | match key { 119 | KeyCode::Left => self.move_cursor_left(), 120 | KeyCode::Right => self.move_cursor_right(), 121 | KeyCode::Up => self.move_cursor_up(), 122 | KeyCode::Down => self.move_cursor_down(), 123 | KeyCode::Char(c) => self.enter_char(*c), 124 | KeyCode::Backspace => self.delete_char_before_cursor(), 125 | KeyCode::Delete => self.delete_char_under_cursor(), 126 | KeyCode::Enter => match from_nuon(&self.buffer, Some(Span::unknown())) { 127 | Ok(val) => return Ok(EditorTransition::Value(val)), 128 | Err(err) => return Err(format!("could not convert back from NUON: {}", err)), 129 | }, 130 | KeyCode::Esc => return Ok(EditorTransition::Quit), 131 | _ => {} 132 | } 133 | 134 | Ok(EditorTransition::Continue) 135 | } 136 | 137 | pub(super) fn render(&self, frame: &mut Frame, config: &Config) { 138 | let title = "Editor"; 139 | 140 | let block = Paragraph::new(self.buffer.as_str()) 141 | .style( 142 | Style::default() 143 | .fg(config.colors.editor.buffer.foreground) 144 | .bg(config.colors.editor.buffer.background), 145 | ) 146 | .block( 147 | Block::default().borders(Borders::ALL).title(title).style( 148 | Style::default() 149 | .fg(config.colors.editor.frame.foreground) 150 | .bg(config.colors.editor.frame.background), 151 | ), 152 | ); 153 | 154 | let height = if self.buffer.is_empty() { 155 | 1 156 | } else if (self.buffer.len() % self.width) == 0 { 157 | self.buffer.len() / self.width 158 | } else { 159 | self.buffer.len() / self.width + 1 160 | } as u16; 161 | let area = Rect { 162 | x: (frame.area().width - (self.width as u16 + 2)) / 2, 163 | y: frame.area().height - (height + 2) - 2, 164 | width: self.width as u16 + 2, 165 | height: height + 2, 166 | }; 167 | 168 | frame.render_widget(Clear, area); //this clears out the background 169 | frame.render_widget(block.wrap(Wrap { trim: false }), area); 170 | 171 | let (x, y) = self.cursor_position; 172 | frame.set_cursor_position(Position::new(area.x + 1 + (x as u16), area.y + 1 + (y as u16))) 173 | } 174 | } 175 | 176 | #[cfg(test)] 177 | mod tests { 178 | use crossterm::event::KeyCode; 179 | use nu_protocol::Value; 180 | 181 | use super::{Editor, EditorTransition}; 182 | 183 | #[test] 184 | fn edit_cells() { 185 | let mut editor = Editor::default(); 186 | editor.set_width(10 + 2); 187 | editor.buffer = r#""""#.to_string(); 188 | 189 | // NOTE: for the NUON conversion to work, the test string buffer needs to be wrapped in 190 | // parentheses. 191 | // in order not to make the strokes clunky, the quotes are added in the for loop below and 192 | // are implicite in the strokes below. 193 | let strokes = vec![ 194 | ( 195 | KeyCode::Enter, 196 | "", 197 | Ok(EditorTransition::Value(Value::test_string(""))), 198 | ), 199 | (KeyCode::Right, "", Ok(EditorTransition::Continue)), 200 | (KeyCode::Char('a'), "a", Ok(EditorTransition::Continue)), 201 | (KeyCode::Char('b'), "ab", Ok(EditorTransition::Continue)), 202 | (KeyCode::Char('c'), "abc", Ok(EditorTransition::Continue)), 203 | (KeyCode::Char('d'), "abcd", Ok(EditorTransition::Continue)), 204 | (KeyCode::Char('e'), "abcde", Ok(EditorTransition::Continue)), 205 | (KeyCode::Left, "abcde", Ok(EditorTransition::Continue)), 206 | (KeyCode::Char('f'), "abcdfe", Ok(EditorTransition::Continue)), 207 | (KeyCode::Left, "abcdfe", Ok(EditorTransition::Continue)), 208 | (KeyCode::Left, "abcdfe", Ok(EditorTransition::Continue)), 209 | ( 210 | KeyCode::Char('g'), 211 | "abcgdfe", 212 | Ok(EditorTransition::Continue), 213 | ), 214 | (KeyCode::Right, "abcgdfe", Ok(EditorTransition::Continue)), 215 | (KeyCode::Right, "abcgdfe", Ok(EditorTransition::Continue)), 216 | (KeyCode::Right, "abcgdfe", Ok(EditorTransition::Continue)), 217 | (KeyCode::Up, "abcgdfe", Ok(EditorTransition::Continue)), 218 | (KeyCode::Down, "abcgdfe", Ok(EditorTransition::Continue)), 219 | ( 220 | KeyCode::Char('h'), 221 | "abcgdfeh", 222 | Ok(EditorTransition::Continue), 223 | ), 224 | ( 225 | KeyCode::Char('i'), 226 | "abcgdfehi", 227 | Ok(EditorTransition::Continue), 228 | ), 229 | ( 230 | KeyCode::Char('j'), 231 | "abcgdfehij", 232 | Ok(EditorTransition::Continue), 233 | ), 234 | ( 235 | KeyCode::Char('k'), 236 | "abcgdfehijk", 237 | Ok(EditorTransition::Continue), 238 | ), 239 | ( 240 | KeyCode::Char('l'), 241 | "abcgdfehijkl", 242 | Ok(EditorTransition::Continue), 243 | ), 244 | (KeyCode::Up, "abcgdfehijkl", Ok(EditorTransition::Continue)), 245 | ( 246 | KeyCode::Char('m'), 247 | "abmcgdfehijkl", 248 | Ok(EditorTransition::Continue), 249 | ), 250 | ( 251 | KeyCode::Down, 252 | "abmcgdfehijkl", 253 | Ok(EditorTransition::Continue), 254 | ), 255 | ( 256 | KeyCode::Left, 257 | "abmcgdfehijkl", 258 | Ok(EditorTransition::Continue), 259 | ), 260 | ( 261 | KeyCode::Char('n'), 262 | "abmcgdfehijknl", 263 | Ok(EditorTransition::Continue), 264 | ), 265 | ( 266 | KeyCode::Left, 267 | "abmcgdfehijknl", 268 | Ok(EditorTransition::Continue), 269 | ), 270 | ( 271 | KeyCode::Left, 272 | "abmcgdfehijknl", 273 | Ok(EditorTransition::Continue), 274 | ), 275 | ( 276 | KeyCode::Left, 277 | "abmcgdfehijknl", 278 | Ok(EditorTransition::Continue), 279 | ), 280 | ( 281 | KeyCode::Left, 282 | "abmcgdfehijknl", 283 | Ok(EditorTransition::Continue), 284 | ), 285 | ( 286 | KeyCode::Left, 287 | "abmcgdfehijknl", 288 | Ok(EditorTransition::Continue), 289 | ), 290 | ( 291 | KeyCode::Char('o'), 292 | "abmcgdfeohijknl", 293 | Ok(EditorTransition::Continue), 294 | ), 295 | ( 296 | KeyCode::Right, 297 | "abmcgdfeohijknl", 298 | Ok(EditorTransition::Continue), 299 | ), 300 | ( 301 | KeyCode::Right, 302 | "abmcgdfeohijknl", 303 | Ok(EditorTransition::Continue), 304 | ), 305 | ( 306 | KeyCode::Enter, 307 | "abmcgdfeohijknl", 308 | Ok(EditorTransition::Value(Value::test_string( 309 | "abmcgdfeohijknl", 310 | ))), 311 | ), 312 | ( 313 | KeyCode::Right, 314 | "abmcgdfeohijknl", 315 | Ok(EditorTransition::Continue), 316 | ), 317 | ( 318 | KeyCode::Right, 319 | "abmcgdfeohijknl", 320 | Ok(EditorTransition::Continue), 321 | ), 322 | ( 323 | KeyCode::Char('p'), 324 | "abmcgdfeohijkpnl", 325 | Ok(EditorTransition::Continue), 326 | ), 327 | ( 328 | KeyCode::Backspace, 329 | "abmcgdfeohijknl", 330 | Ok(EditorTransition::Continue), 331 | ), 332 | ( 333 | KeyCode::Backspace, 334 | "abmcgdfeohijnl", 335 | Ok(EditorTransition::Continue), 336 | ), 337 | ( 338 | KeyCode::Backspace, 339 | "abmcgdfeohinl", 340 | Ok(EditorTransition::Continue), 341 | ), 342 | (KeyCode::Up, "abmcgdfeohinl", Ok(EditorTransition::Continue)), 343 | ( 344 | KeyCode::Delete, 345 | "amcgdfeohinl", 346 | Ok(EditorTransition::Continue), 347 | ), 348 | ( 349 | KeyCode::Delete, 350 | "acgdfeohinl", 351 | Ok(EditorTransition::Continue), 352 | ), 353 | ( 354 | KeyCode::Delete, 355 | "agdfeohinl", 356 | Ok(EditorTransition::Continue), 357 | ), 358 | (KeyCode::Esc, "agdfeohinl", Ok(EditorTransition::Quit)), 359 | ( 360 | KeyCode::Enter, 361 | "agdfeohinl", 362 | Ok(EditorTransition::Value(Value::test_string("agdfeohinl"))), 363 | ), 364 | ]; 365 | 366 | for (key, expected_buffer, expected) in strokes { 367 | let result = editor.handle_key(&key); 368 | 369 | assert_eq!(result, expected); 370 | assert_eq!(editor.buffer, format!(r#""{}""#, expected_buffer)); 371 | } 372 | } 373 | } 374 | -------------------------------------------------------------------------------- /src/handler.rs: -------------------------------------------------------------------------------- 1 | use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; 2 | 3 | use nu_protocol::{ 4 | ast::{CellPath, PathMember}, 5 | ShellError, Span, Value, 6 | }; 7 | 8 | use crate::{ 9 | app::{App, Mode}, 10 | edit::EditorTransition, 11 | navigation::Direction, 12 | nu::value::transpose, 13 | }; 14 | 15 | /// the result of a state transition 16 | #[derive(Debug, PartialEq)] 17 | pub enum TransitionResult { 18 | Quit, 19 | Continue, 20 | Return(Value), 21 | Mutate(Value, CellPath), 22 | Error(String), 23 | } 24 | 25 | impl TransitionResult { 26 | #[cfg(test)] 27 | fn is_quit(&self) -> bool { 28 | matches!(self, Self::Quit | Self::Return(_)) 29 | } 30 | } 31 | 32 | impl App { 33 | /// Handles the key events and updates the state of [`App`]. 34 | #[allow(clippy::collapsible_if)] 35 | pub fn handle_key_events( 36 | &mut self, 37 | key_event: KeyEvent, 38 | half_page: usize, 39 | ) -> Result { 40 | let config = &self.config; 41 | 42 | match self.mode { 43 | Mode::Normal => { 44 | if key_event.code.ge(&KeyCode::Char('0')) && key_event.code.le(&KeyCode::Char('9')) 45 | { 46 | self.mode = Mode::Waiting(match key_event.code { 47 | KeyCode::Char('0') => 0, 48 | KeyCode::Char('1') => 1, 49 | KeyCode::Char('2') => 2, 50 | KeyCode::Char('3') => 3, 51 | KeyCode::Char('4') => 4, 52 | KeyCode::Char('5') => 5, 53 | KeyCode::Char('6') => 6, 54 | KeyCode::Char('7') => 7, 55 | KeyCode::Char('8') => 8, 56 | KeyCode::Char('9') => 9, 57 | _ => unreachable!(), 58 | }); 59 | return Ok(TransitionResult::Continue); 60 | } else if key_event == config.keybindings.navigation.half_page_down { 61 | // TODO: add a margin to the bottom 62 | self.go_up_or_down_in_data(Direction::Down(half_page)); 63 | return Ok(TransitionResult::Continue); 64 | } else if key_event == config.keybindings.navigation.half_page_up { 65 | // TODO: add a margin to the top 66 | self.go_up_or_down_in_data(Direction::Up(half_page)); 67 | return Ok(TransitionResult::Continue); 68 | } else if key_event == config.keybindings.navigation.goto_bottom { 69 | self.go_up_or_down_in_data(Direction::Bottom); 70 | return Ok(TransitionResult::Continue); 71 | } else if key_event == config.keybindings.navigation.goto_top { 72 | self.go_up_or_down_in_data(Direction::Top); 73 | return Ok(TransitionResult::Continue); 74 | } else if key_event == config.keybindings.quit { 75 | return Ok(TransitionResult::Quit); 76 | } else if key_event == config.keybindings.insert { 77 | self.enter_editor(); 78 | return Ok(TransitionResult::Continue); 79 | } else if key_event == config.keybindings.peek { 80 | self.mode = Mode::Peeking; 81 | return Ok(TransitionResult::Continue); 82 | } else if key_event == config.keybindings.navigation.down { 83 | self.go_up_or_down_in_data(Direction::Down(1)); 84 | return Ok(TransitionResult::Continue); 85 | } else if key_event == config.keybindings.navigation.up { 86 | self.go_up_or_down_in_data(Direction::Up(1)); 87 | return Ok(TransitionResult::Continue); 88 | } else if key_event == config.keybindings.navigation.right { 89 | self.go_deeper_in_data(); 90 | return Ok(TransitionResult::Continue); 91 | } else if key_event == config.keybindings.navigation.left { 92 | self.go_back_in_data(); 93 | return Ok(TransitionResult::Continue); 94 | } else if key_event == config.keybindings.transpose { 95 | let mut path = self.position.clone(); 96 | path.members.pop(); 97 | 98 | let view = self.value_under_cursor(Some(path.clone())); 99 | let transpose = transpose(&view); 100 | 101 | if transpose != view { 102 | match &transpose { 103 | Value::Record { val: rec, .. } => { 104 | let cols = rec.columns().cloned().collect::>(); 105 | 106 | // NOTE: app.position.members should never be empty by construction 107 | *self.position.members.last_mut().unwrap() = PathMember::String { 108 | val: cols.first().unwrap_or(&"".to_string()).to_string(), 109 | span: Span::unknown(), 110 | optional: cols.is_empty(), 111 | }; 112 | } 113 | _ => { 114 | // NOTE: app.position.members should never be empty by construction 115 | *self.position.members.last_mut().unwrap() = PathMember::Int { 116 | val: 0, 117 | span: Span::unknown(), 118 | optional: false, 119 | }; 120 | } 121 | } 122 | return Ok(TransitionResult::Mutate(transpose, path)); 123 | } 124 | 125 | return Ok(TransitionResult::Continue); 126 | } 127 | } 128 | Mode::Waiting(n) => { 129 | if key_event.code.ge(&KeyCode::Char('0')) && key_event.code.le(&KeyCode::Char('9')) 130 | { 131 | let u = match key_event.code { 132 | KeyCode::Char('0') => 0, 133 | KeyCode::Char('1') => 1, 134 | KeyCode::Char('2') => 2, 135 | KeyCode::Char('3') => 3, 136 | KeyCode::Char('4') => 4, 137 | KeyCode::Char('5') => 5, 138 | KeyCode::Char('6') => 6, 139 | KeyCode::Char('7') => 7, 140 | KeyCode::Char('8') => 8, 141 | KeyCode::Char('9') => 9, 142 | _ => unreachable!(), 143 | }; 144 | self.mode = Mode::Waiting(n * 10 + u); 145 | return Ok(TransitionResult::Continue); 146 | } else if key_event.code == KeyCode::Esc { 147 | self.mode = Mode::Normal; 148 | return Ok(TransitionResult::Continue); 149 | } else if key_event == config.keybindings.navigation.down { 150 | self.mode = Mode::Normal; 151 | self.go_up_or_down_in_data(Direction::Down(n)); 152 | return Ok(TransitionResult::Continue); 153 | } else if key_event == config.keybindings.navigation.up { 154 | self.mode = Mode::Normal; 155 | self.go_up_or_down_in_data(Direction::Up(n)); 156 | return Ok(TransitionResult::Continue); 157 | } else if key_event == config.keybindings.navigation.goto_line { 158 | self.mode = Mode::Normal; 159 | self.go_up_or_down_in_data(Direction::At(n.saturating_sub(1))); 160 | return Ok(TransitionResult::Continue); 161 | } 162 | } 163 | Mode::Insert => { 164 | if key_event == config.keybindings.normal { 165 | self.mode = Mode::Normal; 166 | return Ok(TransitionResult::Continue); 167 | } 168 | 169 | match self.editor.handle_key(&key_event.code) { 170 | Ok(EditorTransition::Value(v)) => { 171 | self.mode = Mode::Normal; 172 | return Ok(TransitionResult::Mutate(v, self.position.clone())); 173 | } 174 | Ok(EditorTransition::Quit) => { 175 | self.mode = Mode::Normal; 176 | return Ok(TransitionResult::Continue); 177 | } 178 | Ok(EditorTransition::Continue) => return Ok(TransitionResult::Continue), 179 | Err(err) => return Ok(TransitionResult::Error(err)), 180 | } 181 | } 182 | Mode::Peeking => { 183 | if key_event == config.keybindings.quit { 184 | return Ok(TransitionResult::Quit); 185 | } else if key_event == config.keybindings.normal { 186 | self.mode = Mode::Normal; 187 | return Ok(TransitionResult::Continue); 188 | } else if key_event == config.keybindings.peeking.all { 189 | return Ok(TransitionResult::Return(self.value.clone())); 190 | } else if key_event == config.keybindings.peeking.view { 191 | self.position.members.pop(); 192 | return Ok(TransitionResult::Return(self.value_under_cursor(None))); 193 | } else if key_event == config.keybindings.peeking.under { 194 | return Ok(TransitionResult::Return(self.value_under_cursor(None))); 195 | } else if key_event == config.keybindings.peeking.cell_path { 196 | return Ok(TransitionResult::Return(Value::cell_path( 197 | self.position.clone(), 198 | Span::unknown(), 199 | ))); 200 | } 201 | } 202 | Mode::Bottom => { 203 | if key_event == config.keybindings.quit { 204 | return Ok(TransitionResult::Quit); 205 | } else if key_event == config.keybindings.navigation.left { 206 | self.mode = Mode::Normal; 207 | return Ok(TransitionResult::Continue); 208 | } else if key_event == config.keybindings.peek { 209 | return Ok(TransitionResult::Return(self.value_under_cursor(None))); 210 | } 211 | } 212 | } 213 | 214 | Ok(TransitionResult::Continue) 215 | } 216 | } 217 | 218 | /// represent a [`KeyEvent`] as a simple string 219 | pub fn repr_key(key: &KeyEvent) -> String { 220 | let code = match key.code { 221 | KeyCode::Char(c) => c.to_string(), 222 | KeyCode::Left => char::from_u32(0x2190).unwrap().into(), 223 | KeyCode::Up => char::from_u32(0x2191).unwrap().into(), 224 | KeyCode::Right => char::from_u32(0x2192).unwrap().into(), 225 | KeyCode::Down => char::from_u32(0x2193).unwrap().into(), 226 | KeyCode::Esc => "".into(), 227 | KeyCode::Enter => char::from_u32(0x23ce).unwrap().into(), 228 | KeyCode::Backspace => char::from_u32(0x232b).unwrap().into(), 229 | KeyCode::Delete => char::from_u32(0x2326).unwrap().into(), 230 | _ => "??".into(), 231 | }; 232 | 233 | match key.modifiers { 234 | KeyModifiers::NONE => code, 235 | KeyModifiers::CONTROL => format!("", code), 236 | _ => "??".into(), 237 | } 238 | } 239 | 240 | #[cfg(test)] 241 | mod tests { 242 | use crossterm::event::KeyEvent; 243 | use nu_protocol::{ 244 | ast::{CellPath, PathMember}, 245 | record, Span, Value, 246 | }; 247 | 248 | use super::{repr_key, App, TransitionResult}; 249 | use crate::{ 250 | app::Mode, 251 | config::Config, 252 | nu::cell_path::{to_path_member_vec, PM}, 253 | }; 254 | 255 | /// { 256 | /// l: ["my", "list", "elements"], 257 | /// r: {a: 1, b: 2}, 258 | /// s: "some string", 259 | /// i: 123, 260 | /// } 261 | fn test_value() -> Value { 262 | Value::test_record(record! { 263 | "l" => Value::test_list(vec![ 264 | Value::test_string("my"), 265 | Value::test_string("list"), 266 | Value::test_string("elements"), 267 | ]), 268 | "r" => Value::test_record(record! { 269 | "a" => Value::test_int(1), 270 | "b" => Value::test_int(2), 271 | } 272 | ), 273 | "s" => Value::test_string("some string"), 274 | "i" => Value::test_int(123), 275 | }) 276 | } 277 | 278 | #[test] 279 | fn switch_modes() { 280 | let mut app = App::from_value(Value::test_string("foo")); 281 | let keybindings = app.config.clone().keybindings; 282 | 283 | assert!(app.mode == Mode::Normal); 284 | 285 | // INSERT -> PEEKING: not allowed 286 | // PEEKING -> INSERT: not allowed 287 | let transitions = vec![ 288 | (keybindings.normal, Mode::Normal), 289 | (keybindings.insert, Mode::Insert), 290 | (keybindings.normal, Mode::Normal), 291 | (keybindings.peek, Mode::Peeking), 292 | (keybindings.normal, Mode::Normal), 293 | ]; 294 | 295 | for (key, expected_mode) in transitions { 296 | let mode = app.mode.clone(); 297 | 298 | let result = app.handle_key_events(key, 0).unwrap(); 299 | 300 | assert!( 301 | !result.is_quit(), 302 | "unexpected exit after pressing {} in {}", 303 | repr_key(&key), 304 | mode, 305 | ); 306 | assert!( 307 | app.mode == expected_mode, 308 | "expected to be in {} after pressing {} in {}, found {}", 309 | expected_mode, 310 | repr_key(&key), 311 | mode, 312 | app.mode 313 | ); 314 | } 315 | } 316 | 317 | #[test] 318 | fn quit() { 319 | let mut app = App::from_value(test_value()); 320 | let keybindings = app.config.clone().keybindings; 321 | 322 | let transitions = vec![ 323 | (keybindings.insert, false), 324 | (keybindings.quit, false), 325 | (keybindings.normal, false), 326 | (keybindings.quit, true), 327 | (keybindings.peek, false), 328 | (keybindings.quit, true), 329 | ]; 330 | 331 | for (key, exit) in transitions { 332 | let mode = app.mode.clone(); 333 | 334 | // NOTE: yeah this is a bit clunky... 335 | if app.mode == Mode::Insert { 336 | app.editor.set_width(10); 337 | } 338 | 339 | let result = app.handle_key_events(key, 0).unwrap(); 340 | 341 | if exit { 342 | assert!( 343 | result.is_quit(), 344 | "expected to quit after pressing {} in {} mode", 345 | repr_key(&key), 346 | mode 347 | ); 348 | } else { 349 | assert!( 350 | !result.is_quit(), 351 | "expected NOT to quit after pressing {} in {} mode", 352 | repr_key(&key), 353 | mode 354 | ); 355 | } 356 | } 357 | } 358 | 359 | fn repr_path_member_vec(members: &[PathMember]) -> String { 360 | format!( 361 | "$.{}", 362 | members 363 | .iter() 364 | .map(|m| { 365 | match m { 366 | PathMember::Int { val, .. } => val.to_string(), 367 | PathMember::String { val, .. } => val.to_string(), 368 | } 369 | }) 370 | .collect::>() 371 | .join(".") 372 | ) 373 | } 374 | 375 | #[test] 376 | fn navigate_the_data() { 377 | let mut app = App::from_value(test_value()); 378 | let nav = app.config.clone().keybindings.navigation; 379 | 380 | assert!(!app.is_at_bottom()); 381 | assert_eq!(app.position.members, to_path_member_vec(&[PM::S("l")])); 382 | 383 | let transitions = vec![ 384 | (nav.up, vec![PM::S("l")], false), 385 | (nav.down, vec![PM::S("r")], false), 386 | (nav.left, vec![PM::S("r")], false), 387 | (nav.right, vec![PM::S("r"), PM::S("a")], false), 388 | (nav.right, vec![PM::S("r"), PM::S("a")], true), 389 | (nav.up, vec![PM::S("r"), PM::S("a")], true), 390 | (nav.down, vec![PM::S("r"), PM::S("a")], true), 391 | (nav.left, vec![PM::S("r"), PM::S("a")], false), 392 | (nav.down, vec![PM::S("r"), PM::S("b")], false), 393 | (nav.right, vec![PM::S("r"), PM::S("b")], true), 394 | (nav.up, vec![PM::S("r"), PM::S("b")], true), 395 | (nav.down, vec![PM::S("r"), PM::S("b")], true), 396 | (nav.left, vec![PM::S("r"), PM::S("b")], false), 397 | (nav.up, vec![PM::S("r"), PM::S("a")], false), 398 | (nav.up, vec![PM::S("r"), PM::S("a")], false), 399 | (nav.left, vec![PM::S("r")], false), 400 | (nav.down, vec![PM::S("s")], false), 401 | (nav.left, vec![PM::S("s")], false), 402 | (nav.right, vec![PM::S("s")], true), 403 | (nav.up, vec![PM::S("s")], true), 404 | (nav.down, vec![PM::S("s")], true), 405 | (nav.left, vec![PM::S("s")], false), 406 | (nav.down, vec![PM::S("i")], false), 407 | (nav.left, vec![PM::S("i")], false), 408 | (nav.right, vec![PM::S("i")], true), 409 | (nav.up, vec![PM::S("i")], true), 410 | (nav.down, vec![PM::S("i")], true), 411 | (nav.left, vec![PM::S("i")], false), 412 | (nav.up, vec![PM::S("s")], false), 413 | (nav.up, vec![PM::S("r")], false), 414 | (nav.up, vec![PM::S("l")], false), 415 | (nav.left, vec![PM::S("l")], false), 416 | (nav.right, vec![PM::S("l"), PM::I(0)], false), 417 | (nav.right, vec![PM::S("l"), PM::I(0)], true), 418 | (nav.up, vec![PM::S("l"), PM::I(0)], true), 419 | (nav.down, vec![PM::S("l"), PM::I(0)], true), 420 | (nav.left, vec![PM::S("l"), PM::I(0)], false), 421 | (nav.down, vec![PM::S("l"), PM::I(1)], false), 422 | (nav.right, vec![PM::S("l"), PM::I(1)], true), 423 | (nav.up, vec![PM::S("l"), PM::I(1)], true), 424 | (nav.down, vec![PM::S("l"), PM::I(1)], true), 425 | (nav.left, vec![PM::S("l"), PM::I(1)], false), 426 | (nav.down, vec![PM::S("l"), PM::I(2)], false), 427 | (nav.right, vec![PM::S("l"), PM::I(2)], true), 428 | (nav.up, vec![PM::S("l"), PM::I(2)], true), 429 | (nav.down, vec![PM::S("l"), PM::I(2)], true), 430 | (nav.left, vec![PM::S("l"), PM::I(2)], false), 431 | (nav.up, vec![PM::S("l"), PM::I(1)], false), 432 | (nav.up, vec![PM::S("l"), PM::I(0)], false), 433 | (nav.up, vec![PM::S("l"), PM::I(0)], false), 434 | (nav.left, vec![PM::S("l")], false), 435 | ]; 436 | 437 | for (key, cell_path, bottom) in transitions { 438 | let expected = to_path_member_vec(&cell_path); 439 | app.handle_key_events(key, 0).unwrap(); 440 | 441 | if bottom { 442 | assert!( 443 | app.is_at_bottom(), 444 | "expected to be at the bottom after pressing {}", 445 | repr_key(&key) 446 | ); 447 | } else { 448 | assert!( 449 | !app.is_at_bottom(), 450 | "expected NOT to be at the bottom after pressing {}", 451 | repr_key(&key) 452 | ); 453 | } 454 | assert_eq!( 455 | app.position.members, 456 | expected, 457 | "expected to be at {:?}, found {:?}", 458 | repr_path_member_vec(&expected), 459 | repr_path_member_vec(&app.position.members) 460 | ); 461 | } 462 | } 463 | 464 | fn run_peeking_scenario( 465 | transitions: Vec<(KeyEvent, bool, Option)>, 466 | config: Config, 467 | value: Value, 468 | ) { 469 | let mut app = App::from_value(value).with_config(config); 470 | 471 | for (key, exit, expected) in transitions { 472 | let mode = app.mode.clone(); 473 | 474 | let result = app.handle_key_events(key, 0).unwrap(); 475 | 476 | if exit { 477 | assert!( 478 | result.is_quit(), 479 | "expected to peek some data after pressing {} in {} mode", 480 | repr_key(&key), 481 | mode 482 | ); 483 | } else { 484 | assert!( 485 | !result.is_quit(), 486 | "expected NOT to peek some data after pressing {} in {} mode", 487 | repr_key(&key), 488 | mode 489 | ); 490 | } 491 | 492 | match expected { 493 | Some(value) => match result { 494 | TransitionResult::Return(val) => { 495 | assert_eq!( 496 | value, 497 | val, 498 | "unexpected data after pressing {} in {} mode", 499 | repr_key(&key), 500 | mode 501 | ) 502 | } 503 | _ => panic!( 504 | "did expect output data after pressing {} in {} mode", 505 | repr_key(&key), 506 | mode 507 | ), 508 | }, 509 | None => { 510 | if let TransitionResult::Return(_) = result { 511 | panic!( 512 | "did NOT expect output data after pressing {} in {} mode", 513 | repr_key(&key), 514 | mode 515 | ) 516 | } 517 | } 518 | } 519 | } 520 | } 521 | 522 | #[test] 523 | fn peek_data() { 524 | let config = Config::default(); 525 | let keybindings = config.clone().keybindings; 526 | 527 | let value = test_value(); 528 | 529 | let peek_all_from_top = vec![ 530 | (keybindings.peek, false, None), 531 | (keybindings.peeking.all, true, Some(value.clone())), 532 | ]; 533 | run_peeking_scenario(peek_all_from_top, config.clone(), value.clone()); 534 | 535 | let peek_current_from_top = vec![ 536 | (keybindings.peek, false, None), 537 | (keybindings.peeking.view, true, Some(value.clone())), 538 | ]; 539 | run_peeking_scenario(peek_current_from_top, config.clone(), value.clone()); 540 | 541 | let go_in_the_data_and_peek_all_and_current = vec![ 542 | (keybindings.navigation.down, false, None), 543 | (keybindings.navigation.right, false, None), // on {r: {a: 1, b: 2}} 544 | (keybindings.peek, false, None), 545 | (keybindings.peeking.all, true, Some(value.clone())), 546 | ( 547 | keybindings.peeking.view, 548 | true, 549 | Some(Value::test_record(record! { 550 | "a" => Value::test_int(1), 551 | "b" => Value::test_int(2), 552 | })), 553 | ), 554 | ]; 555 | run_peeking_scenario( 556 | go_in_the_data_and_peek_all_and_current, 557 | config.clone(), 558 | value.clone(), 559 | ); 560 | 561 | let go_in_the_data_and_peek_under = vec![ 562 | (keybindings.navigation.down, false, None), 563 | (keybindings.navigation.right, false, None), // on {r: {a: 1, b: 2}} 564 | (keybindings.peek, false, None), 565 | (keybindings.peeking.all, true, Some(value.clone())), 566 | (keybindings.peeking.under, true, Some(Value::test_int(1))), 567 | ]; 568 | run_peeking_scenario(go_in_the_data_and_peek_under, config.clone(), value.clone()); 569 | 570 | let go_in_the_data_and_peek_cell_path = vec![ 571 | (keybindings.navigation.down, false, None), // on {r: {a: 1, b: 2}} 572 | (keybindings.navigation.right, false, None), // on {a: 1} 573 | (keybindings.peek, false, None), 574 | ( 575 | keybindings.peeking.cell_path, 576 | true, 577 | Some(Value::test_cell_path(CellPath { 578 | members: vec![ 579 | PathMember::String { 580 | val: "r".into(), 581 | span: Span::test_data(), 582 | optional: false, 583 | }, 584 | PathMember::String { 585 | val: "a".into(), 586 | span: Span::test_data(), 587 | optional: false, 588 | }, 589 | ], 590 | })), 591 | ), 592 | ]; 593 | run_peeking_scenario( 594 | go_in_the_data_and_peek_cell_path, 595 | config.clone(), 596 | value.clone(), 597 | ); 598 | 599 | let peek_at_the_bottom = vec![ 600 | (keybindings.navigation.right, false, None), // on l: ["my", "list", "elements"], 601 | (keybindings.navigation.right, false, None), // on "my" 602 | (keybindings.peek, true, Some(Value::test_string("my"))), 603 | ]; 604 | run_peeking_scenario(peek_at_the_bottom, config.clone(), value); 605 | } 606 | 607 | #[test] 608 | fn transpose_the_data() { 609 | let mut app = App::from_value(Value::test_record(record!( 610 | "a" => Value::test_int(1), 611 | "b" => Value::test_int(2), 612 | "c" => Value::test_int(3), 613 | ))); 614 | let kmap = app.config.clone().keybindings; 615 | 616 | assert!(!app.is_at_bottom()); 617 | assert_eq!(app.position.members, to_path_member_vec(&[PM::S("a")])); 618 | 619 | let transitions = vec![ 620 | (kmap.navigation.down, vec![PM::S("b")]), 621 | (kmap.transpose, vec![PM::I(0)]), 622 | (kmap.navigation.down, vec![PM::I(1)]), 623 | (kmap.transpose, vec![PM::S("a")]), 624 | ]; 625 | 626 | for (key, cell_path) in transitions { 627 | let expected = to_path_member_vec(&cell_path); 628 | if let TransitionResult::Mutate(cell, path) = app.handle_key_events(key, 0).unwrap() { 629 | app.value = crate::nu::value::mutate_value_cell(&app.value, &path, &cell).unwrap() 630 | } 631 | 632 | assert!( 633 | !app.is_at_bottom(), 634 | "expected NOT to be at the bottom after pressing {}", 635 | repr_key(&key) 636 | ); 637 | 638 | assert_eq!( 639 | app.position.members, 640 | expected, 641 | "expected to be at {:?}, found {:?}", 642 | repr_path_member_vec(&expected), 643 | repr_path_member_vec(&app.position.members) 644 | ); 645 | } 646 | } 647 | } 648 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![doc = include_str!("../README.md")] 2 | mod app; 3 | mod config; 4 | mod edit; 5 | mod handler; 6 | mod navigation; 7 | mod nu; 8 | mod tui; 9 | mod ui; 10 | 11 | use anyhow::Result; 12 | use crossterm::event::KeyEventKind; 13 | use ratatui::backend::CrosstermBackend; 14 | use ratatui::Terminal; 15 | use std::io; 16 | 17 | use nu_protocol::{Span, Value}; 18 | 19 | use app::{App, Mode}; 20 | use config::Config; 21 | use handler::TransitionResult; 22 | use tui::{ 23 | event::{Event, EventHandler}, 24 | Tui, 25 | }; 26 | 27 | pub fn explore(config: &Value, input: Value) -> Result { 28 | let mut tui = Tui::new( 29 | Terminal::new(CrosstermBackend::new(io::stderr()))?, 30 | EventHandler::new(250), 31 | ); 32 | tui.init()?; 33 | 34 | let mut app = App::from_value(input).with_config(Config::from_value(config)?); 35 | 36 | loop { 37 | if app.mode == Mode::Insert { 38 | app.editor.set_width(tui.size()?.width as usize) 39 | } 40 | 41 | tui.draw(&mut app, None)?; 42 | 43 | match tui.events.next()? { 44 | Event::Tick => app.tick(), 45 | Event::Key(key_event) => { 46 | if key_event.kind == KeyEventKind::Press { 47 | match app.handle_key_events(key_event, (tui.size()?.height as usize - 5) / 2)? { 48 | TransitionResult::Quit => break, 49 | TransitionResult::Continue => {} 50 | TransitionResult::Mutate(cell, path) => { 51 | app.value = 52 | crate::nu::value::mutate_value_cell(&app.value, &path, &cell) 53 | .unwrap() 54 | } 55 | TransitionResult::Error(error) => { 56 | tui.draw(&mut app, Some(&error))?; 57 | loop { 58 | if let Event::Key(_) = tui.events.next()? { 59 | break; 60 | } 61 | } 62 | } 63 | TransitionResult::Return(value) => { 64 | tui.exit()?; 65 | return Ok(value); 66 | } 67 | } 68 | } 69 | } 70 | Event::Mouse(_) => {} 71 | Event::Resize(_, _) => {} 72 | } 73 | } 74 | 75 | tui.exit()?; 76 | 77 | Ok(Value::nothing(Span::unknown())) 78 | } 79 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | use std::io::IsTerminal; 2 | 3 | use nu_plugin::{ 4 | serve_plugin, EngineInterface, EvaluatedCall, MsgPackSerializer, Plugin, PluginCommand, 5 | SimplePluginCommand, 6 | }; 7 | use nu_plugin_explore::explore; 8 | use nu_protocol::{Example, LabeledError, Record, Signature, Span, Type, Value}; 9 | 10 | struct ExplorePlugin; 11 | 12 | impl Plugin for ExplorePlugin { 13 | fn commands(&self) -> Vec>> { 14 | vec![Box::new(Explore)] 15 | } 16 | 17 | fn version(&self) -> String { 18 | env!("CARGO_PKG_VERSION").into() 19 | } 20 | } 21 | 22 | struct Explore; 23 | 24 | impl SimplePluginCommand for Explore { 25 | type Plugin = ExplorePlugin; 26 | 27 | fn name(&self) -> &str { 28 | "nu_plugin_explore" 29 | } 30 | 31 | fn description(&self) -> &str { 32 | "interactively explore Nushell structured data" 33 | } 34 | 35 | fn signature(&self) -> Signature { 36 | Signature::build(PluginCommand::name(self)).input_output_type(Type::Any, Type::Any) 37 | } 38 | 39 | fn search_terms(&self) -> Vec<&str> { 40 | vec!["plugin", "explore"] 41 | } 42 | 43 | fn examples(&self) -> Vec { 44 | vec![ 45 | Example { 46 | example: "open Cargo.toml | nu_plugin_explore", 47 | description: "explore the Cargo.toml file of this project", 48 | result: None, 49 | }, 50 | Example { 51 | example: r#"$env.config.plugins.explore = { show_cell_path: false, layout: "compact" } 52 | $nu | nu_plugin_explore"#, 53 | description: "explore `$nu` and set some config options", 54 | result: None, 55 | }, 56 | ] 57 | } 58 | 59 | fn run( 60 | &self, 61 | _plugin: &ExplorePlugin, 62 | engine: &EngineInterface, 63 | call: &EvaluatedCall, 64 | input: &Value, 65 | ) -> Result { 66 | let config = engine.get_config()?; 67 | 68 | let default_config = Value::record(Record::new(), Span::unknown()); 69 | let config = config.plugins.get("explore").unwrap_or(&default_config); 70 | 71 | if !std::io::stdin().is_terminal() { 72 | return Err(LabeledError::new("Can't start nu_plugin_explore") 73 | .with_label("must run in a terminal", call.head) 74 | .with_help( 75 | "ensure that you are running in a terminal, and that the plugin is not \ 76 | communicating over stdio", 77 | )); 78 | } 79 | 80 | let foreground = engine.enter_foreground()?; 81 | 82 | let value = explore(config, input.clone()).map_err(|err| { 83 | match err.downcast_ref::() { 84 | Some(err) => err.clone(), 85 | None => LabeledError::new("unexpected internal error").with_label( 86 | "could not transform error into ShellError, there was another kind of crash...", 87 | call.head, 88 | ), 89 | } 90 | })?; 91 | 92 | foreground.leave()?; 93 | 94 | Ok(value) 95 | } 96 | } 97 | 98 | fn main() { 99 | serve_plugin(&ExplorePlugin, MsgPackSerializer {}) 100 | } 101 | -------------------------------------------------------------------------------- /src/navigation.rs: -------------------------------------------------------------------------------- 1 | //! navigate in the data in all directions 2 | use nu_protocol::{ast::PathMember, Span, Value}; 3 | 4 | use crate::app::{App, Mode}; 5 | 6 | /// specify a vertical direction in which to go in the data 7 | pub enum Direction { 8 | /// go down in the data 9 | Down(usize), 10 | /// go up in the data 11 | Up(usize), 12 | /// go to the top of the data, i.e. the first element or the first key 13 | Top, 14 | /// go to the bottom of the data, i.e. the last element or the last key 15 | Bottom, 16 | /// go at a particular line in the data 17 | At(usize), 18 | } 19 | 20 | impl App { 21 | /// go up or down in the data 22 | /// 23 | /// depending on the direction (see [`Direction`]), this function will 24 | /// - early return if the user is already at the bottom => this is to avoid the confusing following 25 | /// situation: you are at the bottom of the data, looking at one item in a list, without this early 26 | /// return, you'd be able to scroll the list without seeing it as a whole... confusing, right? 27 | /// - cycle the list indices or the record column names => the index / column will wrap around 28 | /// 29 | /// > :bulb: **Note** 30 | /// > this function will only modify the last element of the state's *cell path* either by 31 | /// > - not doing anything 32 | /// > - poping the last element to know where we are and then pushing back the new element 33 | pub(super) fn go_up_or_down_in_data(&mut self, direction: Direction) { 34 | if self.is_at_bottom() { 35 | return; 36 | } 37 | 38 | // NOTE: this should never fail by construction 39 | let current = self.position.members.pop().unwrap(); 40 | 41 | match self.value_under_cursor(None) { 42 | Value::List { vals, .. } => { 43 | let new = match current { 44 | PathMember::Int { 45 | val, 46 | span, 47 | optional, 48 | } => PathMember::Int { 49 | val: if vals.is_empty() { 50 | val 51 | } else { 52 | match direction { 53 | Direction::Up(step) => val.saturating_sub(step).max(0), 54 | Direction::Down(step) => { 55 | val.saturating_add(step).min(vals.len() - 1) 56 | } 57 | Direction::Top => 0, 58 | Direction::Bottom => vals.len() - 1, 59 | Direction::At(id) => id.min(vals.len() - 1), 60 | } 61 | }, 62 | span, 63 | optional, 64 | }, 65 | _ => panic!("current should be an integer path member"), 66 | }; 67 | self.position.members.push(new); 68 | } 69 | Value::Record { val: rec, .. } => { 70 | let new = match current { 71 | PathMember::String { 72 | val, 73 | span, 74 | optional, 75 | } => { 76 | let cols = rec.columns().collect::>(); 77 | 78 | PathMember::String { 79 | val: if cols.is_empty() { 80 | "".into() 81 | } else { 82 | // NOTE: this should never fail 83 | let index = rec.columns().position(|x| x == &val).unwrap(); 84 | let new_index = match direction { 85 | Direction::Up(step) => index.saturating_sub(step).max(0), 86 | Direction::Down(step) => { 87 | index.saturating_add(step).min(cols.len() - 1) 88 | } 89 | Direction::Top => 0, 90 | Direction::Bottom => cols.len() - 1, 91 | Direction::At(id) => id.min(cols.len() - 1), 92 | }; 93 | 94 | cols[new_index].to_string() 95 | }, 96 | span, 97 | optional, 98 | } 99 | } 100 | _ => panic!("current should be an string path member"), 101 | }; 102 | self.position.members.push(new); 103 | } 104 | _ => {} 105 | } 106 | } 107 | 108 | /// go one level deeper in the data 109 | /// 110 | /// > :bulb: **Note** 111 | /// > this function will 112 | /// > - push a new *cell path* member to the state if there is more depth ahead 113 | /// > - mark the state as *at the bottom* if the value at the new depth is of a simple type 114 | pub(super) fn go_deeper_in_data(&mut self) { 115 | match self.value_under_cursor(None) { 116 | Value::List { vals, .. } => self.position.members.push(PathMember::Int { 117 | val: 0, 118 | span: Span::unknown(), 119 | optional: vals.is_empty(), 120 | }), 121 | Value::Record { val: rec, .. } => { 122 | let cols = rec.columns().cloned().collect::>(); 123 | 124 | self.position.members.push(PathMember::String { 125 | val: cols.first().unwrap_or(&"".to_string()).into(), 126 | span: Span::unknown(), 127 | optional: cols.is_empty(), 128 | }) 129 | } 130 | _ => self.hit_bottom(), 131 | } 132 | 133 | self.rendering_tops.push(0); 134 | } 135 | 136 | /// pop one level of depth from the data 137 | /// 138 | /// > :bulb: **Note** 139 | /// > - the state is always marked as *not at the bottom* 140 | /// > - the state *cell path* can have it's last member popped if possible 141 | pub(super) fn go_back_in_data(&mut self) { 142 | if !self.is_at_bottom() & (self.position.members.len() > 1) { 143 | self.position.members.pop(); 144 | } 145 | self.mode = Mode::Normal; 146 | self.rendering_tops.pop(); 147 | } 148 | } 149 | 150 | // TODO: add proper assert error messages 151 | #[cfg(test)] 152 | mod tests { 153 | use super::Direction; 154 | use crate::app::App; 155 | use nu_protocol::{ast::PathMember, record, Span, Value}; 156 | 157 | fn test_string_pathmember(val: impl Into) -> PathMember { 158 | PathMember::String { 159 | val: val.into(), 160 | span: Span::test_data(), 161 | optional: false, 162 | } 163 | } 164 | 165 | fn test_int_pathmember(val: usize) -> PathMember { 166 | PathMember::Int { 167 | val, 168 | span: Span::test_data(), 169 | optional: false, 170 | } 171 | } 172 | 173 | #[test] 174 | fn go_up_and_down_in_list() { 175 | let value = Value::test_list(vec![ 176 | Value::test_nothing(), 177 | Value::test_nothing(), 178 | Value::test_nothing(), 179 | ]); 180 | let mut app = App::from_value(value); 181 | 182 | let sequence = vec![ 183 | (Direction::Down(1), 1), 184 | (Direction::Down(1), 2), 185 | (Direction::Down(1), 2), 186 | (Direction::Up(1), 1), 187 | (Direction::Up(1), 0), 188 | (Direction::Up(1), 0), 189 | (Direction::Top, 0), 190 | (Direction::Bottom, 2), 191 | (Direction::Bottom, 2), 192 | (Direction::Top, 0), 193 | (Direction::At(0), 0), 194 | (Direction::At(1), 1), 195 | (Direction::At(2), 2), 196 | ]; 197 | for (direction, id) in sequence { 198 | app.go_up_or_down_in_data(direction); 199 | let expected = vec![test_int_pathmember(id)]; 200 | assert_eq!(app.position.members, expected); 201 | } 202 | } 203 | 204 | #[test] 205 | fn go_up_and_down_in_record() { 206 | let value = Value::test_record(record! { 207 | "a" => Value::test_nothing(), 208 | "b" => Value::test_nothing(), 209 | "c" => Value::test_nothing(), 210 | }); 211 | let mut app = App::from_value(value); 212 | 213 | let sequence = vec![ 214 | (Direction::Down(1), "b"), 215 | (Direction::Down(1), "c"), 216 | (Direction::Down(1), "c"), 217 | (Direction::Up(1), "b"), 218 | (Direction::Up(1), "a"), 219 | (Direction::Up(1), "a"), 220 | (Direction::Top, "a"), 221 | (Direction::Bottom, "c"), 222 | (Direction::Bottom, "c"), 223 | (Direction::Top, "a"), 224 | (Direction::At(0), "a"), 225 | (Direction::At(1), "b"), 226 | (Direction::At(2), "c"), 227 | ]; 228 | for (direction, id) in sequence { 229 | app.go_up_or_down_in_data(direction); 230 | let expected = vec![test_string_pathmember(id)]; 231 | assert_eq!(app.position.members, expected); 232 | } 233 | } 234 | 235 | #[test] 236 | fn go_deeper() { 237 | let value = Value::test_list(vec![Value::test_record(record! { 238 | "a" => Value::test_list(vec![Value::test_nothing()]), 239 | })]); 240 | let mut app = App::from_value(value); 241 | 242 | let mut expected = vec![test_int_pathmember(0)]; 243 | assert_eq!(app.position.members, expected); 244 | 245 | app.go_deeper_in_data(); 246 | expected.push(test_string_pathmember("a")); 247 | assert_eq!(app.position.members, expected); 248 | 249 | app.go_deeper_in_data(); 250 | expected.push(test_int_pathmember(0)); 251 | assert_eq!(app.position.members, expected); 252 | } 253 | 254 | #[test] 255 | fn hit_bottom() { 256 | let value = Value::test_nothing(); 257 | let mut app = App::from_value(value); 258 | 259 | assert!(!app.is_at_bottom()); 260 | 261 | app.go_deeper_in_data(); 262 | assert!(app.is_at_bottom()); 263 | } 264 | 265 | #[test] 266 | fn go_back() { 267 | let value = Value::test_list(vec![Value::test_record(record! { 268 | "a" => Value::test_list(vec![Value::test_nothing()]), 269 | })]); 270 | let mut app = App::from_value(value); 271 | app.position.members = vec![ 272 | test_int_pathmember(0), 273 | test_string_pathmember("a"), 274 | test_int_pathmember(0), 275 | ]; 276 | app.hit_bottom(); 277 | 278 | let mut expected = app.position.members.clone(); 279 | 280 | app.go_back_in_data(); 281 | assert_eq!(app.position.members, expected); 282 | 283 | app.go_back_in_data(); 284 | expected.pop(); 285 | assert_eq!(app.position.members, expected); 286 | 287 | app.go_back_in_data(); 288 | expected.pop(); 289 | assert_eq!(app.position.members, expected); 290 | 291 | app.go_back_in_data(); 292 | assert_eq!(app.position.members, expected); 293 | } 294 | } 295 | -------------------------------------------------------------------------------- /src/nu/cell_path.rs: -------------------------------------------------------------------------------- 1 | use nu_protocol::{ast::PathMember, Span}; 2 | 3 | /// a simplified [`PathMember`] that can be put in a single vector, without being too long 4 | pub(crate) enum PM<'a> { 5 | // the [`PathMember::String`] variant 6 | S(&'a str), 7 | // the [`PathMember::Int`] variant 8 | I(usize), 9 | } 10 | 11 | pub(crate) fn to_path_member_vec(cell_path: &[PM]) -> Vec { 12 | cell_path 13 | .iter() 14 | .map(|x| match *x { 15 | PM::S(val) => PathMember::String { 16 | val: val.into(), 17 | span: Span::test_data(), 18 | optional: false, 19 | }, 20 | PM::I(val) => PathMember::Int { 21 | val, 22 | span: Span::test_data(), 23 | optional: false, 24 | }, 25 | }) 26 | .collect::>() 27 | } 28 | 29 | impl<'a> PM<'a> { 30 | pub(crate) fn as_cell_path(members: &[Self]) -> String { 31 | format!( 32 | "$.{}", 33 | members 34 | .iter() 35 | .map(|m| { 36 | match m { 37 | Self::I(val) => val.to_string(), 38 | Self::S(val) => val.to_string(), 39 | } 40 | }) 41 | .collect::>() 42 | .join(".") 43 | ) 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/nu/mod.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | pub(super) mod cell_path; 3 | pub(super) mod strings; 4 | pub(super) mod value; 5 | -------------------------------------------------------------------------------- /src/nu/strings.rs: -------------------------------------------------------------------------------- 1 | #[derive(Debug, PartialEq)] 2 | pub(crate) enum SpecialString { 3 | Url, 4 | Path, 5 | } 6 | 7 | impl std::fmt::Display for SpecialString { 8 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 9 | let repr = match self { 10 | Self::Url => "url".to_string(), 11 | Self::Path => "path".to_string(), 12 | }; 13 | write!(f, "{}", repr) 14 | } 15 | } 16 | 17 | impl SpecialString { 18 | pub(crate) fn parse(input: &str) -> Option { 19 | if let Ok(url) = url::Url::parse(input) { 20 | if url.scheme() == "file" { 21 | Some(Self::Path) 22 | } else { 23 | Some(Self::Url) 24 | } 25 | } else if input.contains('\n') { 26 | None 27 | } else if input.contains('/') { 28 | Some(Self::Path) 29 | } else { 30 | None 31 | } 32 | } 33 | } 34 | 35 | #[cfg(test)] 36 | mod special_strings_tests { 37 | use super::SpecialString; 38 | 39 | #[test] 40 | fn parse_strings() { 41 | let cases = vec![ 42 | ("foo", None), 43 | ("https://google.com", Some(SpecialString::Url)), 44 | ("file:///some/file", Some(SpecialString::Path)), 45 | ("/path/to/something", Some(SpecialString::Path)), 46 | ("relative/path/", Some(SpecialString::Path)), 47 | ("./relative/path/", Some(SpecialString::Path)), 48 | ("../../relative/path/", Some(SpecialString::Path)), 49 | ("file:", Some(SpecialString::Path)), 50 | ("normal string with a / inside", Some(SpecialString::Path)), 51 | ("normal string with \na / inside", None), 52 | ]; 53 | 54 | for (input, expected) in cases { 55 | let actual = SpecialString::parse(input); 56 | assert_eq!( 57 | actual, expected, 58 | "expected {expected:#?} on input {input}, found {actual:#?}", 59 | ); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/nu/value.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | use nu_protocol::{ 4 | ast::{CellPath, PathMember}, 5 | record, Record, Span, Type, Value, 6 | }; 7 | 8 | #[derive(Debug, PartialEq)] 9 | pub(crate) enum Table { 10 | /// value is a list but with no items in it 11 | Empty, 12 | /// row at index {0} should be a record but is a {1} 13 | RowNotARecord(usize, Type), 14 | /// row at index {0} should have same length as first row, {2}, but has 15 | /// length {1} 16 | RowIncompatibleLen(usize, usize, usize), 17 | /// row at index {0} and subkey {1} has type {2} but was expected to have 18 | /// the same type as first row {3} 19 | RowIncompatibleType(usize, String, Type, Type), 20 | /// row at index {0} contains an invalid key {1} but expected one of {2} 21 | RowInvalidKey(usize, String, Vec), 22 | /// value is a valid table 23 | IsValid, 24 | /// valis is not even a list 25 | NotAList, 26 | } 27 | 28 | impl Table { 29 | pub(crate) fn to_msg(&self) -> Option { 30 | match self { 31 | Table::Empty => None, 32 | Table::RowNotARecord(i, t) => Some(format!("row $.{} is not a record: {}", i, t)), 33 | Table::RowIncompatibleLen(i, l, e) => Some(format!( 34 | "row $.{} has incompatible length with first row: expected {} found {}", 35 | i, e, l 36 | )), 37 | Table::RowIncompatibleType(i, k, t, e) => Some(format!( 38 | "cell $.{}.{} has incompatible type with first row: expected {} found {}", 39 | i, k, e, t 40 | )), 41 | Table::RowInvalidKey(i, k, ks) => Some(format!( 42 | "row $.{} does not contain key '{}': list of keys {:?}", 43 | i, k, ks 44 | )), 45 | Table::NotAList => None, 46 | Table::IsValid => None, 47 | } 48 | } 49 | } 50 | 51 | /// mutate the input `value`, changing the _value_ at `cell_path` into the `cell` argument 52 | /// 53 | /// > **Note** 54 | /// > returns [`None`] if the `cell_path` is not valid in `value`. 55 | pub(crate) fn mutate_value_cell( 56 | value: &Value, 57 | cell_path: &CellPath, 58 | cell: &Value, 59 | ) -> Option { 60 | if cell_path.members.is_empty() { 61 | return Some(cell.clone()); 62 | } 63 | 64 | if value 65 | .clone() 66 | .follow_cell_path(&cell_path.members, false) 67 | .is_err() 68 | { 69 | return None; 70 | } 71 | 72 | let mut cell_path = cell_path.clone(); 73 | 74 | // NOTE: `cell_path.members` cannot be empty because the last branch of the match bellot 75 | // does not call `aux` recursively 76 | let first = cell_path.members.first().unwrap(); 77 | 78 | let res = match value { 79 | Value::List { vals, .. } => { 80 | let id = match first { 81 | PathMember::Int { val, .. } => *val, 82 | _ => unreachable!(), 83 | }; 84 | cell_path.members.remove(0); 85 | 86 | let mut vals = vals.clone(); 87 | vals[id] = mutate_value_cell(&vals[id], &cell_path, cell).unwrap(); 88 | 89 | Value::list(vals, Span::unknown()) 90 | } 91 | Value::Record { val: rec, .. } => { 92 | let col = match first { 93 | PathMember::String { val, .. } => val.clone(), 94 | _ => unreachable!(), 95 | }; 96 | cell_path.members.remove(0); 97 | 98 | let id = rec.columns().position(|x| *x == col).unwrap_or(0); 99 | 100 | let cols = rec.columns().cloned().collect(); 101 | let vals = rec 102 | .values() 103 | .cloned() 104 | .enumerate() 105 | .map(|(i, v)| { 106 | if i == id { 107 | mutate_value_cell(&v, &cell_path, cell).unwrap() 108 | } else { 109 | v 110 | } 111 | }) 112 | .collect(); 113 | 114 | Value::record( 115 | // NOTE: this cannot fail because `cols` and `vals` have the same length by 116 | // contruction, they have been constructed by iterating over `rec.columns()` 117 | // and `rec.values()` respectively, both of which have the same length 118 | Record::from_raw_cols_vals(cols, vals, Span::unknown(), Span::unknown()).unwrap(), 119 | Span::unknown(), 120 | ) 121 | } 122 | _ => cell.clone(), 123 | }; 124 | 125 | Some(res) 126 | } 127 | 128 | pub(crate) fn is_table(value: &Value) -> Table { 129 | match value { 130 | Value::List { vals, .. } => { 131 | if vals.is_empty() { 132 | return Table::Empty; 133 | } 134 | 135 | // extract the columns of each row as hashmaps for easier access 136 | let mut rows = Vec::new(); 137 | for (i, val) in vals.iter().enumerate() { 138 | match val.get_type() { 139 | Type::Record(fields) => rows.push( 140 | Vec::from(fields) 141 | .into_iter() 142 | .collect::>(), 143 | ), 144 | t => return Table::RowNotARecord(i, t), 145 | }; 146 | } 147 | 148 | // check the number of columns for each row 149 | let n = rows[0].keys().len(); 150 | for (i, row) in rows.iter().skip(1).enumerate() { 151 | if row.keys().len() != n { 152 | return Table::RowIncompatibleLen(i + 1, row.keys().len(), n); 153 | } 154 | } 155 | 156 | // check the actual types for each column 157 | // - if a row has a null, it doesn't count as "not a table" 158 | // - if two rows are numeric, then the check can continue 159 | for (key, val) in rows[0].iter() { 160 | let mut ty = val; 161 | 162 | for (i, row) in rows.iter().skip(1).enumerate() { 163 | match row.get(key) { 164 | Some(v) => match ty { 165 | Type::Nothing => ty = v, 166 | _ => { 167 | if !matches!(v, Type::Nothing) { 168 | if v.is_numeric() && ty.is_numeric() { 169 | } else if (!v.is_numeric() && ty.is_numeric()) 170 | | (v.is_numeric() && !ty.is_numeric()) 171 | // NOTE: this might need a bit more work to include more 172 | // tables 173 | | (v != ty) 174 | { 175 | return Table::RowIncompatibleType( 176 | i + 1, 177 | key.clone(), 178 | v.clone(), 179 | ty.clone(), 180 | ); 181 | } 182 | } 183 | } 184 | }, 185 | None => { 186 | let mut keys = row.keys().cloned().collect::>(); 187 | keys.sort(); 188 | return Table::RowInvalidKey(i + 1, key.clone(), keys); 189 | } 190 | } 191 | } 192 | } 193 | 194 | Table::IsValid 195 | } 196 | _ => Table::NotAList, 197 | } 198 | } 199 | 200 | /// this effectively implements the following idempotent `transpose` command written in Nushell 201 | /// ```nushell 202 | /// alias "core transpose" = transpose 203 | /// 204 | /// def transpose []: [table -> any, record -> table] { 205 | /// let data = $in 206 | /// 207 | /// if ($data | columns) == (seq 1 ($data | columns | length) | into string) { 208 | /// if ($data | columns | length) == 2 { 209 | /// return ($data | core transpose --header-row | into record) 210 | /// } else { 211 | /// return ($data | core transpose --header-row) 212 | /// } 213 | /// } 214 | /// 215 | /// $data | core transpose | rename --block { 216 | /// ($in | str replace "column" "" | into int) + 1 | into string 217 | /// } 218 | /// } 219 | /// 220 | /// #[test] 221 | /// def transposition [] { 222 | /// use std assert 223 | /// 224 | /// assert equal (ls | transpose explore | transpose) (ls) 225 | /// assert equal (open Cargo.toml | transpose | transpose) (open Cargo.toml) 226 | /// } 227 | /// ``` 228 | // WARNING: some _unwraps_ haven't been proven to be safe in this function 229 | pub(crate) fn transpose(value: &Value) -> Value { 230 | if matches!(is_table(value), Table::IsValid) { 231 | let value_rows = match value { 232 | Value::List { vals, .. } => vals, 233 | _ => return value.clone(), 234 | }; 235 | 236 | // NOTE: because `value` is a valid table, it's first row is guaranteed to be a record 237 | let first_row = value_rows[0].as_record().unwrap(); 238 | 239 | let full_columns = (1..=(first_row.len())) 240 | .map(|i| format!("{i}")) 241 | .collect::>(); 242 | 243 | if first_row.columns().cloned().collect::>() == full_columns { 244 | if first_row.len() == 2 { 245 | let cols: Vec = value_rows 246 | .iter() 247 | .map(|row| row.get_data_by_key("1").unwrap().as_str().unwrap().into()) 248 | .collect(); 249 | 250 | let vals: Vec = value_rows 251 | .iter() 252 | .map(|row| row.get_data_by_key("2").unwrap()) 253 | .collect(); 254 | 255 | return Value::record( 256 | // NOTE: `cols` and `value_rows` have the same length by contruction 257 | // because they have been created by iterating over `value_rows` 258 | Record::from_raw_cols_vals(cols, vals, Span::unknown(), Span::unknown()) 259 | .unwrap(), 260 | Span::unknown(), 261 | ); 262 | } else { 263 | let mut rows = vec![]; 264 | let cols: Vec = value_rows 265 | .iter() 266 | .map(|v| v.get_data_by_key("1").unwrap().as_str().unwrap().into()) 267 | .collect(); 268 | 269 | for i in 0..(first_row.len() - 1) { 270 | rows.push(Value::record( 271 | // NOTE: `cols` and `value_rows` have the same length by contruction 272 | // because `cols` has been created by iterating over `value_rows` 273 | Record::from_raw_cols_vals( 274 | cols.clone(), 275 | value_rows 276 | .iter() 277 | .map(|v| v.get_data_by_key(&format!("{}", i + 2)).unwrap()) 278 | .collect(), 279 | Span::unknown(), 280 | Span::unknown(), 281 | ) 282 | .unwrap(), 283 | Span::unknown(), 284 | )); 285 | } 286 | 287 | return Value::list(rows, Span::unknown()); 288 | } 289 | } 290 | 291 | let mut rows = vec![]; 292 | for col in value_rows[0].columns() { 293 | let mut cols = vec!["1".into()]; 294 | let mut vs = vec![Value::string(col, Span::unknown())]; 295 | 296 | for (i, v) in value_rows.iter().enumerate() { 297 | cols.push(format!("{}", i + 2)); 298 | vs.push(v.get_data_by_key(col).unwrap()); 299 | } 300 | 301 | rows.push(Value::record( 302 | // NOTE: `cols` and `vs` have the same length by construction 303 | Record::from_raw_cols_vals(cols, vs, Span::unknown(), Span::unknown()).unwrap(), 304 | Span::unknown(), 305 | )); 306 | } 307 | 308 | return Value::list(rows, Span::unknown()); 309 | } 310 | 311 | match value { 312 | Value::Record { val: rec, .. } => { 313 | let mut rows = vec![]; 314 | for (col, val) in rec.iter() { 315 | rows.push(Value::record( 316 | record! { 317 | "1" => Value::string(col, Span::unknown()), 318 | "2" => val.clone(), 319 | }, 320 | Span::unknown(), 321 | )); 322 | } 323 | 324 | Value::list(rows, Span::unknown()) 325 | } 326 | _ => value.clone(), 327 | } 328 | } 329 | 330 | #[cfg(test)] 331 | mod tests { 332 | use super::{is_table, mutate_value_cell}; 333 | use crate::nu::{ 334 | cell_path::{to_path_member_vec, PM}, 335 | value::{transpose, Table}, 336 | }; 337 | use nu_protocol::{ast::CellPath, record, Config, Type, Value}; 338 | 339 | fn default_value_repr(value: &Value) -> String { 340 | value.to_expanded_string(" ", &Config::default()) 341 | } 342 | 343 | #[test] 344 | fn value_mutation() { 345 | let list = Value::test_list(vec![ 346 | Value::test_int(1), 347 | Value::test_int(2), 348 | Value::test_int(3), 349 | ]); 350 | let record = Value::test_record(record! { 351 | "a" => Value::test_int(1), 352 | "b" => Value::test_int(2), 353 | "c" => Value::test_int(3), 354 | }); 355 | 356 | let cases = vec![ 357 | // simple value -> simple value 358 | ( 359 | Value::test_string("foo"), 360 | vec![], 361 | Value::test_string("bar"), 362 | Some(Value::test_string("bar")), 363 | ), 364 | // list -> simple value 365 | ( 366 | list.clone(), 367 | vec![], 368 | Value::test_nothing(), 369 | Some(Value::test_nothing()), 370 | ), 371 | // record -> simple value 372 | ( 373 | record.clone(), 374 | vec![], 375 | Value::test_nothing(), 376 | Some(Value::test_nothing()), 377 | ), 378 | // mutate a list element with simple value 379 | ( 380 | list.clone(), 381 | vec![PM::I(0)], 382 | Value::test_int(0), 383 | Some(Value::test_list(vec![ 384 | Value::test_int(0), 385 | Value::test_int(2), 386 | Value::test_int(3), 387 | ])), 388 | ), 389 | // mutate a list element with complex value 390 | ( 391 | list.clone(), 392 | vec![PM::I(1)], 393 | record.clone(), 394 | Some(Value::test_list(vec![ 395 | Value::test_int(1), 396 | record.clone(), 397 | Value::test_int(3), 398 | ])), 399 | ), 400 | // invalid list index 401 | (list.clone(), vec![PM::I(5)], Value::test_int(0), None), 402 | // mutate a record field with a simple value 403 | ( 404 | record.clone(), 405 | vec![PM::S("a")], 406 | Value::test_nothing(), 407 | Some(Value::test_record(record! { 408 | "a" => Value::test_nothing(), 409 | "b" => Value::test_int(2), 410 | "c" => Value::test_int(3), 411 | })), 412 | ), 413 | // mutate a record field with a complex value 414 | ( 415 | record.clone(), 416 | vec![PM::S("c")], 417 | list.clone(), 418 | Some(Value::test_record(record! { 419 | "a" => Value::test_int(1), 420 | "b" => Value::test_int(2), 421 | "c" => list.clone(), 422 | })), 423 | ), 424 | // mutate a deeply-nested list element 425 | ( 426 | Value::test_list(vec![Value::test_list(vec![Value::test_list(vec![ 427 | Value::test_string("foo"), 428 | ])])]), 429 | vec![PM::I(0), PM::I(0), PM::I(0)], 430 | Value::test_string("bar"), 431 | Some(Value::test_list(vec![Value::test_list(vec![ 432 | Value::test_list(vec![Value::test_string("bar")]), 433 | ])])), 434 | ), 435 | // mutate a deeply-nested record field 436 | ( 437 | Value::test_record(record! { 438 | "a" => Value::test_record(record! { 439 | "b" => Value::test_record(record! { 440 | "c" => Value::test_string("foo"), 441 | }), 442 | }), 443 | }), 444 | vec![PM::S("a"), PM::S("b"), PM::S("c")], 445 | Value::test_string("bar"), 446 | Some(Value::test_record(record! { 447 | "a" => Value::test_record(record! { 448 | "b" => Value::test_record(record! { 449 | "c" => Value::test_string("bar"), 450 | }), 451 | }), 452 | })), 453 | ), 454 | // try to mutate bad cell path 455 | ( 456 | Value::test_record(record! { 457 | "a" => Value::test_record(record! { 458 | "b" => Value::test_record(record! { 459 | "c" => Value::test_string("foo"), 460 | }), 461 | }), 462 | }), 463 | vec![PM::S("a"), PM::I(0), PM::S("c")], 464 | Value::test_string("bar"), 465 | None, 466 | ), 467 | ]; 468 | 469 | for (value, members, cell, expected) in cases { 470 | let cell_path = CellPath { 471 | members: to_path_member_vec(&members), 472 | }; 473 | 474 | let result = mutate_value_cell(&value, &cell_path, &cell); 475 | assert_eq!( 476 | result, 477 | expected, 478 | "mutating {} at {:?} with {} should give {}, found {}", 479 | default_value_repr(&value), 480 | PM::as_cell_path(&members), 481 | default_value_repr(&cell), 482 | default_value_repr(&match expected.clone() { 483 | Some(v) => v, 484 | None => Value::test_nothing(), 485 | }), 486 | default_value_repr(&match result.clone() { 487 | Some(v) => v, 488 | None => Value::test_nothing(), 489 | }), 490 | ); 491 | } 492 | } 493 | 494 | #[test] 495 | fn is_a_table() { 496 | let simple_table = Value::test_list(vec![ 497 | Value::test_record(record! { 498 | "a" => Value::test_string("foo"), 499 | "b" => Value::test_int(1), 500 | }), 501 | Value::test_record(record! { 502 | "a" => Value::test_string("bar"), 503 | "b" => Value::test_int(2), 504 | }), 505 | ]); 506 | let table_with_out_of_order_columns = Value::test_list(vec![ 507 | Value::test_record(record! { 508 | "b" => Value::test_int(1), 509 | "a" => Value::test_string("foo"), 510 | }), 511 | Value::test_record(record! { 512 | "a" => Value::test_string("bar"), 513 | "b" => Value::test_int(2), 514 | }), 515 | ]); 516 | let table_with_nulls = Value::test_list(vec![ 517 | Value::test_record(record! { 518 | "a" => Value::test_nothing(), 519 | "b" => Value::test_int(1), 520 | }), 521 | Value::test_record(record! { 522 | "a" => Value::test_string("bar"), 523 | "b" => Value::test_int(2), 524 | }), 525 | ]); 526 | let table_with_number_colum = Value::test_list(vec![ 527 | Value::test_record(record! { 528 | "a" => Value::test_string("foo"), 529 | "b" => Value::test_int(1), 530 | }), 531 | Value::test_record(record! { 532 | "a" => Value::test_string("bar"), 533 | "b" => Value::test_float(2.34), 534 | }), 535 | ]); 536 | for table in [ 537 | simple_table, 538 | table_with_out_of_order_columns, 539 | table_with_nulls, 540 | table_with_number_colum, 541 | ] { 542 | assert_eq!( 543 | is_table(&table), 544 | Table::IsValid, 545 | "{} should be a table", 546 | default_value_repr(&table) 547 | ); 548 | } 549 | 550 | let not_a_table_missing_field = ( 551 | Value::test_list(vec![ 552 | Value::test_record(record! { 553 | "a" => Value::test_string("a"), 554 | }), 555 | Value::test_record(record! { 556 | "a" => Value::test_string("a"), 557 | "b" => Value::test_int(1), 558 | }), 559 | ]), 560 | Table::RowIncompatibleLen(1, 2, 1), 561 | ); 562 | let not_a_table_incompatible_types = ( 563 | Value::test_list(vec![ 564 | Value::test_record(record! { 565 | "a" => Value::test_string("a"), 566 | "b" => Value::test_int(1), 567 | }), 568 | Value::test_record(record! { 569 | "a" => Value::test_string("a"), 570 | "b" => Value::test_list(vec![Value::test_int(1)]), 571 | }), 572 | ]), 573 | Table::RowIncompatibleType( 574 | 1, 575 | "b".to_string(), 576 | Type::List(Box::new(Type::Int)), 577 | Type::Int, 578 | ), 579 | ); 580 | let not_a_table_row_not_record = ( 581 | Value::test_list(vec![ 582 | Value::test_record(record! { 583 | "a" => Value::test_string("a"), 584 | "b" => Value::test_int(1), 585 | }), 586 | Value::test_int(0), 587 | ]), 588 | Table::RowNotARecord(1, Type::Int), 589 | ); 590 | let not_a_table_row_invalid_key = ( 591 | Value::test_list(vec![ 592 | Value::test_record(record! { 593 | "a" => Value::test_string("a"), 594 | "b" => Value::test_int(1), 595 | }), 596 | Value::test_record(record! { 597 | "a" => Value::test_string("a"), 598 | "c" => Value::test_int(2), 599 | }), 600 | ]), 601 | Table::RowInvalidKey(1, "b".into(), vec!["a".into(), "c".into()]), 602 | ); 603 | for (not_a_table, expected) in [ 604 | not_a_table_missing_field, 605 | not_a_table_incompatible_types, 606 | not_a_table_row_not_record, 607 | not_a_table_row_invalid_key, 608 | ] { 609 | assert_eq!( 610 | is_table(¬_a_table), 611 | expected, 612 | "{} should not be a table", 613 | default_value_repr(¬_a_table) 614 | ); 615 | } 616 | 617 | assert_eq!(is_table(&Value::test_int(0)), Table::NotAList); 618 | assert_eq!(is_table(&Value::test_list(vec![])), Table::Empty); 619 | } 620 | 621 | #[test] 622 | fn transposition() { 623 | let record = Value::test_record(record! { 624 | "a" => Value::test_int(1), 625 | "b" => Value::test_int(2), 626 | }); 627 | let expected = Value::test_list(vec![ 628 | Value::test_record(record! { 629 | "1" => Value::test_string("a"), 630 | "2" => Value::test_int(1), 631 | }), 632 | Value::test_record(record! { 633 | "1" => Value::test_string("b"), 634 | "2" => Value::test_int(2), 635 | }), 636 | ]); 637 | let result = transpose(&record); 638 | assert_eq!( 639 | result, 640 | expected, 641 | "transposing {} should give {}, found {}", 642 | default_value_repr(&record), 643 | default_value_repr(&expected), 644 | default_value_repr(&result) 645 | ); 646 | // make sure `transpose` is an *involution* 647 | let result = transpose(&expected); 648 | assert_eq!( 649 | result, 650 | record, 651 | "transposing {} should give {}, found {}", 652 | default_value_repr(&expected), 653 | default_value_repr(&record), 654 | default_value_repr(&result) 655 | ); 656 | 657 | let table = Value::test_list(vec![ 658 | Value::test_record(record! { 659 | "a" => Value::test_int(1), 660 | "b" => Value::test_int(2), 661 | }), 662 | Value::test_record(record! { 663 | "a" => Value::test_int(3), 664 | "b" => Value::test_int(4), 665 | }), 666 | ]); 667 | let expected = Value::test_list(vec![ 668 | Value::test_record(record! { 669 | "1" => Value::test_string("a"), 670 | "2" => Value::test_int(1), 671 | "3" => Value::test_int(3), 672 | }), 673 | Value::test_record(record! { 674 | "1" => Value::test_string("b"), 675 | "2" => Value::test_int(2), 676 | "3" => Value::test_int(4), 677 | }), 678 | ]); 679 | let result = transpose(&table); 680 | assert_eq!( 681 | result, 682 | expected, 683 | "transposing {} should give {}, found {}", 684 | default_value_repr(&table), 685 | default_value_repr(&expected), 686 | default_value_repr(&result) 687 | ); 688 | // make sure `transpose` is an *involution* 689 | let result = transpose(&expected); 690 | assert_eq!( 691 | result, 692 | table, 693 | "transposing {} should give {}, found {}", 694 | default_value_repr(&expected), 695 | default_value_repr(&table), 696 | default_value_repr(&result) 697 | ); 698 | 699 | assert_eq!( 700 | transpose(&Value::test_string("foo")), 701 | Value::test_string("foo") 702 | ); 703 | 704 | assert_eq!( 705 | transpose(&Value::test_list(vec![ 706 | Value::test_int(1), 707 | Value::test_int(2) 708 | ])), 709 | Value::test_list(vec![Value::test_int(1), Value::test_int(2)]) 710 | ); 711 | } 712 | } 713 | -------------------------------------------------------------------------------- /src/tui/event.rs: -------------------------------------------------------------------------------- 1 | use anyhow::Result; 2 | use crossterm::event::{self, Event as CrosstermEvent, KeyEvent, MouseEvent}; 3 | use std::sync::mpsc; 4 | use std::thread; 5 | use std::time::{Duration, Instant}; 6 | 7 | /// Terminal events. 8 | #[derive(Clone, Copy, Debug)] 9 | pub enum Event { 10 | /// Terminal tick. 11 | Tick, 12 | /// Key press. 13 | Key(KeyEvent), 14 | /// Mouse click/scroll. 15 | #[allow(dead_code)] 16 | Mouse(MouseEvent), 17 | /// Terminal resize. 18 | #[allow(dead_code)] 19 | Resize(u16, u16), 20 | } 21 | 22 | /// Terminal event handler. 23 | #[derive(Debug)] 24 | #[allow(dead_code)] 25 | pub struct EventHandler { 26 | /// Event sender channel. 27 | sender: mpsc::Sender, 28 | /// Event receiver channel. 29 | receiver: mpsc::Receiver, 30 | /// Event handler thread. 31 | handler: thread::JoinHandle<()>, 32 | } 33 | 34 | impl EventHandler { 35 | /// Constructs a new instance of [`EventHandler`]. 36 | pub fn new(tick_rate: u64) -> Self { 37 | let tick_rate = Duration::from_millis(tick_rate); 38 | let (sender, receiver) = mpsc::channel(); 39 | let handler = { 40 | let sender = sender.clone(); 41 | thread::spawn(move || { 42 | let mut last_tick = Instant::now(); 43 | loop { 44 | let timeout = tick_rate 45 | .checked_sub(last_tick.elapsed()) 46 | .unwrap_or(tick_rate); 47 | 48 | if event::poll(timeout).expect("no events available") { 49 | let result = match event::read().expect("unable to read event") { 50 | CrosstermEvent::Key(e) => sender.send(Event::Key(e)), 51 | CrosstermEvent::Mouse(e) => sender.send(Event::Mouse(e)), 52 | CrosstermEvent::Resize(w, h) => sender.send(Event::Resize(w, h)), 53 | _ => Ok(()), 54 | }; 55 | if result.is_err() { 56 | break; 57 | } 58 | } 59 | 60 | if last_tick.elapsed() >= tick_rate { 61 | if sender.send(Event::Tick).is_err() { 62 | break; 63 | } 64 | last_tick = Instant::now(); 65 | } 66 | } 67 | }) 68 | }; 69 | Self { 70 | sender, 71 | receiver, 72 | handler, 73 | } 74 | } 75 | 76 | /// Receive the next event from the handler thread. 77 | /// 78 | /// This function will always block the current thread if 79 | /// there is no data available and it's possible for more data to be sent. 80 | pub fn next(&self) -> Result { 81 | Ok(self.receiver.recv()?) 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/tui/mod.rs: -------------------------------------------------------------------------------- 1 | use anyhow::Result; 2 | use crossterm::event::{DisableMouseCapture, EnableMouseCapture}; 3 | use crossterm::terminal::{self, EnterAlternateScreen, LeaveAlternateScreen}; 4 | use ratatui::backend::Backend; 5 | use ratatui::prelude::Rect; 6 | use ratatui::Terminal; 7 | use std::io; 8 | use std::panic; 9 | 10 | pub(crate) mod event; 11 | 12 | use crate::{app::App, ui}; 13 | use event::EventHandler; 14 | 15 | /// Representation of a terminal user interface. 16 | /// 17 | /// It is responsible for setting up the terminal, 18 | /// initializing the interface and handling the draw events. 19 | #[derive(Debug)] 20 | pub struct Tui { 21 | /// Interface to the Terminal. 22 | terminal: Terminal, 23 | /// Terminal event handler. 24 | pub events: EventHandler, 25 | } 26 | 27 | impl Tui { 28 | /// Constructs a new instance of [`Tui`]. 29 | pub fn new(terminal: Terminal, events: EventHandler) -> Self { 30 | Self { terminal, events } 31 | } 32 | 33 | /// Initializes the terminal interface. 34 | /// 35 | /// It enables the raw mode and sets terminal properties. 36 | pub fn init(&mut self) -> Result<()> { 37 | terminal::enable_raw_mode()?; 38 | crossterm::execute!(io::stderr(), EnterAlternateScreen, EnableMouseCapture)?; 39 | 40 | // Define a custom panic hook to reset the terminal properties. 41 | // This way, you won't have your terminal messed up if an unexpected error happens. 42 | let panic_hook = panic::take_hook(); 43 | panic::set_hook(Box::new(move |panic| { 44 | Self::reset().expect("failed to reset the terminal"); 45 | panic_hook(panic); 46 | })); 47 | 48 | self.terminal.hide_cursor()?; 49 | self.terminal.clear()?; 50 | Ok(()) 51 | } 52 | 53 | /// [`Draw`] the terminal interface by [`rendering`] the widgets. 54 | /// 55 | /// [`Draw`]: tui::Terminal::draw 56 | /// [`rendering`]: crate::ui:render 57 | pub fn draw(&mut self, app: &mut App, error: Option<&str>) -> Result<()> { 58 | self.terminal 59 | .draw(|frame| ui::render_ui(frame, app, error))?; 60 | Ok(()) 61 | } 62 | 63 | /// Resets the terminal interface. 64 | /// 65 | /// This function is also used for the panic hook to revert 66 | /// the terminal properties if unexpected errors occur. 67 | fn reset() -> Result<()> { 68 | terminal::disable_raw_mode()?; 69 | crossterm::execute!(io::stderr(), LeaveAlternateScreen, DisableMouseCapture)?; 70 | Ok(()) 71 | } 72 | 73 | /// Exits the terminal interface. 74 | /// 75 | /// It disables the raw mode and reverts back the terminal properties. 76 | pub fn exit(&mut self) -> Result<()> { 77 | Self::reset()?; 78 | self.terminal.show_cursor()?; 79 | Ok(()) 80 | } 81 | 82 | pub fn size(&self) -> Result { 83 | let size = self.terminal.size()?; 84 | Ok(Rect::new(0,0,size.width,size.height)) 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/ui.rs: -------------------------------------------------------------------------------- 1 | //! the module responsible for rendering the TUI 2 | use crate::{ 3 | config::Layout, 4 | handler::repr_key, 5 | nu::{strings::SpecialString, value::is_table}, 6 | }; 7 | 8 | use super::{App, Mode}; 9 | use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; 10 | use nu_protocol::ast::{CellPath, PathMember}; 11 | use nu_protocol::{Record, Type, Value}; 12 | use ratatui::{ 13 | prelude::{Alignment, Constraint, Rect}, 14 | style::{Color, Modifier, Style}, 15 | text::{Line, Span}, 16 | widgets::{ 17 | Block, Borders, Cell, List, ListItem, ListState, Paragraph, Row, Table, TableState, Wrap, 18 | }, 19 | Frame, 20 | }; 21 | 22 | /// render the whole ui 23 | pub(super) fn render_ui(frame: &mut Frame, app: &mut App, error: Option<&str>) { 24 | render_data(frame, app); 25 | if app.config.show_cell_path { 26 | render_cell_path(frame, app); 27 | } 28 | 29 | match error { 30 | Some(err) => render_error(frame, err), 31 | None => { 32 | render_status_bar(frame, app); 33 | 34 | if app.mode == Mode::Insert { 35 | app.editor.render(frame, &app.config); 36 | } 37 | } 38 | } 39 | } 40 | 41 | pub(super) fn render_error(frame: &mut Frame, error: &str) { 42 | let bottom_two_lines = Rect::new(0, frame.area().height - 2, frame.area().width, 2); 43 | 44 | let lines = vec![ 45 | Line::from(Span::styled( 46 | format!("Err: {error}"), 47 | Style::default().fg(Color::Red), 48 | )), 49 | Line::from(Span::styled( 50 | "Press any key to continue exploring the data.", 51 | Style::default().fg(Color::Blue), 52 | )), 53 | ]; 54 | 55 | frame.render_widget( 56 | Paragraph::new(lines).alignment(Alignment::Left), 57 | bottom_two_lines, 58 | ); 59 | } 60 | 61 | /// a common representation for an explore row 62 | #[derive(Clone, Debug, PartialEq)] 63 | struct DataRowRepr { 64 | name: Option, 65 | shape: String, 66 | data: String, 67 | } 68 | 69 | impl DataRowRepr { 70 | #[cfg(test)] 71 | fn unnamed(data: impl Into, shape: impl Into) -> Self { 72 | Self { 73 | name: None, 74 | shape: shape.into(), 75 | data: data.into(), 76 | } 77 | } 78 | 79 | #[cfg(test)] 80 | fn named(name: impl Into, data: impl Into, shape: impl Into) -> Self { 81 | Self { 82 | name: Some(name.into()), 83 | shape: shape.into(), 84 | data: data.into(), 85 | } 86 | } 87 | } 88 | 89 | /// compute the preview representation of a list 90 | /// 91 | /// > see the tests for detailed examples 92 | fn repr_list(vals: &[Value]) -> DataRowRepr { 93 | let data = match vals.len() { 94 | 0 => "[]".into(), 95 | 1 => "[1 item]".into(), 96 | x => format!("[{} items]", x), 97 | }; 98 | 99 | DataRowRepr { 100 | name: None, 101 | shape: "list".into(), 102 | data, 103 | } 104 | } 105 | 106 | /// compute the preview representation of a record 107 | /// 108 | /// > see the tests for detailed examples 109 | fn repr_record(cols: &[String]) -> DataRowRepr { 110 | let data = match cols.len() { 111 | 0 => "{}".into(), 112 | 1 => "{1 field}".into(), 113 | x => format!("{{{} fields}}", x), 114 | }; 115 | 116 | DataRowRepr { 117 | name: None, 118 | shape: "record".into(), 119 | data, 120 | } 121 | } 122 | 123 | /// compute the preview representation of a simple value 124 | /// 125 | /// > see the tests for detailed examples 126 | fn repr_simple_value(value: &Value) -> DataRowRepr { 127 | let shape = match value { 128 | Value::String { val, .. } => match SpecialString::parse(val) { 129 | Some(x) => x.to_string(), 130 | None => value.get_type().to_string(), 131 | }, 132 | x => x.get_type().to_string(), 133 | }; 134 | DataRowRepr { 135 | name: None, 136 | shape, 137 | // FIXME: use a real config 138 | data: value.to_expanded_string(" ", &nu_protocol::Config::default()), 139 | } 140 | } 141 | 142 | /// compute the preview representation of a value 143 | /// 144 | /// > see the tests for detailed examples 145 | fn repr_value(value: &Value) -> DataRowRepr { 146 | match value { 147 | Value::List { vals, .. } => repr_list(vals), 148 | Value::Record { val: rec, .. } => repr_record(&rec.columns().cloned().collect::>()), 149 | x => repr_simple_value(x), 150 | } 151 | } 152 | 153 | /// compute the row / item representation of a complete Nushell Value 154 | /// 155 | /// > see the tests for detailed examples 156 | fn repr_data(data: &Value) -> Vec { 157 | match data { 158 | Value::List { vals, .. } => { 159 | if vals.is_empty() { 160 | vec![DataRowRepr { 161 | name: None, 162 | shape: "list".into(), 163 | data: "[]".into(), 164 | }] 165 | } else { 166 | vals.iter().map(repr_value).collect::>() 167 | } 168 | } 169 | Value::Record { val: rec, .. } => { 170 | if rec.columns().collect::>().is_empty() { 171 | vec![DataRowRepr { 172 | name: None, 173 | shape: "record".into(), 174 | data: "{}".into(), 175 | }] 176 | } else { 177 | rec.iter() 178 | .map(|(col, val)| { 179 | let mut repr = repr_value(val); 180 | repr.name = Some(col.to_string()); 181 | repr 182 | }) 183 | .collect::>() 184 | } 185 | } 186 | value => vec![repr_simple_value(value)], 187 | } 188 | } 189 | 190 | /// compute the representation of a complete Nushell table 191 | /// 192 | /// > see the tests for detailed examples 193 | fn repr_table(table: &[Record]) -> (Vec, Vec, Vec>) { 194 | let mut shapes = vec![Type::Nothing; table[0].len()]; 195 | 196 | let mut rows = vec![vec![]; table.len()]; 197 | 198 | for (i, row) in table.iter().enumerate() { 199 | for (j, col) in table[0].columns().enumerate() { 200 | // NOTE: because `table` is a valid table, this should always be a `Some` 201 | let val = row.get(col).unwrap(); 202 | 203 | let cell_type = val.get_type(); 204 | if !matches!(cell_type, Type::Nothing) { 205 | if shapes[j].is_numeric() && cell_type.is_numeric() && (shapes[j] != cell_type) { 206 | shapes[j] = Type::Number; 207 | } else { 208 | shapes[j] = cell_type; 209 | } 210 | } 211 | 212 | rows[i].push(repr_value(val).data); 213 | } 214 | } 215 | 216 | ( 217 | table[0].columns().cloned().collect::>(), 218 | shapes.iter().map(|s| s.to_string()).collect(), 219 | rows, 220 | ) 221 | } 222 | 223 | /// render the whole data 224 | /// 225 | /// the layout can be changed from [`crate::config::Config::layout`]. 226 | /// 227 | /// the data will be rendered on top of the bar, and on top of the cell path in case 228 | /// [`crate::config::Config::show_cell_path`] is set to `true`. 229 | fn render_data(frame: &mut Frame, app: &mut App) { 230 | let config = &app.config; 231 | 232 | let mut data_path = app.position.members.clone(); 233 | let current = if !app.is_at_bottom() { 234 | data_path.pop() 235 | } else { 236 | None 237 | }; 238 | 239 | let value = app.value_under_cursor(Some(CellPath { members: data_path })); 240 | 241 | let table_type = is_table(&value); 242 | let is_a_table = matches!(table_type, crate::nu::value::Table::IsValid); 243 | 244 | let mut data_frame_height = if config.show_cell_path { 245 | frame.area().height - 2 246 | } else { 247 | frame.area().height - 1 248 | }; 249 | if !is_a_table { 250 | if let Some(msg) = table_type.to_msg() { 251 | data_frame_height -= 1; 252 | frame.render_widget( 253 | Paragraph::new(msg).alignment(Alignment::Right).style( 254 | Style::default() 255 | .bg(config.colors.warning.background) 256 | .fg(config.colors.warning.foreground), 257 | ), 258 | Rect::new(0, data_frame_height, frame.area().width, 1), 259 | ); 260 | } 261 | } 262 | 263 | let normal_name_style = Style::default() 264 | .fg(config.colors.normal.name.foreground) 265 | .bg(config.colors.normal.name.background); 266 | let normal_data_style = Style::default() 267 | .fg(config.colors.normal.data.foreground) 268 | .bg(config.colors.normal.data.background); 269 | let normal_shape_style = Style::default() 270 | .fg(config.colors.normal.shape.foreground) 271 | .bg(config.colors.normal.shape.background); 272 | let highlight_style = Style::default() 273 | .fg(config.colors.selected.foreground) 274 | .bg(config.colors.selected.background) 275 | .add_modifier(config.colors.selected_modifier); 276 | 277 | let selected = match current { 278 | Some(PathMember::Int { val, .. }) => val, 279 | Some(PathMember::String { val, .. }) => { 280 | value.columns().position(|x| x == &val).unwrap_or(0) 281 | } 282 | None => 0, 283 | }; 284 | 285 | let show_line_numbers = (config.number || config.relativenumber) 286 | && matches!(value, Value::List { .. } | Value::Record { .. }); 287 | let nb_lines = match value.clone() { 288 | // NOTE: it's annoying that `vals` cant' be cloned 289 | Value::List { vals, .. } => vals.len(), 290 | Value::Record { val, .. } => val.columns().len(), 291 | _ => 0, 292 | }; 293 | let line_numbers_width = if show_line_numbers { 294 | format!("{}", nb_lines).len() as u16 295 | } else { 296 | 0 297 | }; 298 | 299 | let rect_without_bottom_bar = 300 | Rect::new(line_numbers_width, 0, frame.area().width, data_frame_height); 301 | 302 | let height = data_frame_height as i32 - 3; // 3: border x 2 + header 303 | let cursor = selected as i32; 304 | let top = *app.rendering_tops.last().unwrap_or(&0); 305 | let margin = config.margin as i32; 306 | 307 | if cursor >= top + height - margin { 308 | app.rendering_tops.pop(); 309 | app.rendering_tops.push( 310 | (cursor - height + margin + 1) 311 | .min(nb_lines as i32 - height) 312 | .max(0), 313 | ); 314 | } else if cursor <= top + margin { 315 | app.rendering_tops.pop(); 316 | app.rendering_tops 317 | .push((cursor - margin).min(nb_lines as i32 - height).max(0)); 318 | } 319 | 320 | let margin_offset = *app.rendering_tops.last().unwrap_or(&0) as usize; 321 | 322 | if show_line_numbers { 323 | let rect_lines_without_bottom_bar = Rect::new(0, 0, line_numbers_width, data_frame_height); 324 | 325 | let normal_line_style = Style::default() 326 | .fg(config.colors.line_numbers.normal.foreground) 327 | .bg(config.colors.line_numbers.normal.background); 328 | let highlight_line_style = Style::default() 329 | .fg(config.colors.line_numbers.selected.foreground) 330 | .bg(config.colors.line_numbers.selected.background); 331 | 332 | let mut line_numbers = vec![]; 333 | // add the lines at the top 334 | for i in (1..(selected + 1 - margin_offset)).rev() { 335 | let i = if config.relativenumber { 336 | i 337 | } else { 338 | selected + 1 - i 339 | }; 340 | line_numbers.push(i); 341 | } 342 | // add selected line 343 | line_numbers.push(selected + 1); 344 | // add the lines at the top 345 | for i in 1..(margin_offset as i32 + height - selected as i32) { 346 | if selected as i32 + 1 + i > nb_lines as i32 { 347 | break; 348 | } 349 | 350 | let i = if config.relativenumber { 351 | i 352 | } else { 353 | selected as i32 + 1 + i 354 | }; 355 | line_numbers.push(i as usize); 356 | } 357 | 358 | let mut lines = if app.config.layout == Layout::Compact && !is_a_table { 359 | vec![] 360 | } else { 361 | vec![ListItem::new(Line::from("")); 2] 362 | }; 363 | for i in line_numbers { 364 | lines.push(ListItem::new(Line::from(Span::styled( 365 | format!("{}", i), 366 | normal_line_style, 367 | )))); 368 | } 369 | 370 | let mut offset = selected - margin_offset; 371 | if app.config.layout == Layout::Table || is_a_table { 372 | offset += 2; 373 | } 374 | 375 | frame.render_stateful_widget( 376 | List::new(lines).highlight_style(highlight_line_style), 377 | rect_lines_without_bottom_bar, 378 | &mut ListState::default().with_selected(Some(offset)), 379 | ); 380 | } 381 | 382 | if is_a_table { 383 | let (columns, shapes, cells) = match value { 384 | Value::List { vals, .. } => { 385 | let recs = vals 386 | .iter() 387 | .map(|v| v.as_record().unwrap().clone()) 388 | .collect::>(); 389 | repr_table(&recs) 390 | } 391 | _ => panic!("value is a table but is not a list"), 392 | }; 393 | 394 | let header = columns 395 | .iter() 396 | .zip(shapes) 397 | .map(|(c, s)| { 398 | let spans = vec![ 399 | Span::styled(c, normal_name_style), 400 | " (".into(), 401 | Span::styled(s, normal_shape_style), 402 | ")".into(), 403 | ]; 404 | 405 | Cell::from(Line::from(spans)) 406 | }) 407 | .collect::>(); 408 | 409 | let widths = header 410 | .iter() 411 | // FIXME: use an appropriate constraint here 412 | .map(|_| Constraint::Min(25)) 413 | .collect::>(); 414 | 415 | let header = Row::new(header).height(1); 416 | 417 | let rows: Vec = cells 418 | .iter() 419 | .map(|r| Row::new(r.iter().cloned().map(Cell::from).collect::>())) 420 | .collect(); 421 | 422 | let table = Table::new(rows, widths) 423 | .header(header) 424 | .block(Block::default().borders(Borders::ALL)) 425 | .row_highlight_style(highlight_style) 426 | .highlight_symbol(config.colors.selected_symbol.clone()); 427 | 428 | frame.render_stateful_widget( 429 | table, 430 | rect_without_bottom_bar, 431 | &mut TableState::default() 432 | .with_selected(Some(selected)) 433 | .with_offset(margin_offset), 434 | ); 435 | 436 | return; 437 | } 438 | 439 | match config.layout { 440 | Layout::Compact => { 441 | let items: Vec = repr_data(&value) 442 | .iter() 443 | .cloned() 444 | .map(|row| { 445 | let mut spans = vec![]; 446 | if let Some(name) = row.name { 447 | spans.push(Span::styled(name, normal_name_style)); 448 | spans.push(": ".into()); 449 | } 450 | spans.push("(".into()); 451 | spans.push(Span::styled(row.shape, normal_shape_style)); 452 | spans.push(") ".into()); 453 | spans.push(Span::styled(row.data, normal_data_style)); 454 | 455 | ListItem::new(Line::from(spans)) 456 | }) 457 | .collect(); 458 | 459 | let items = List::new(items) 460 | .highlight_style(highlight_style) 461 | .highlight_symbol(&config.colors.selected_symbol); 462 | 463 | let selected = if app.is_at_bottom() { 464 | None 465 | } else { 466 | Some(selected) 467 | }; 468 | 469 | frame.render_stateful_widget( 470 | items, 471 | rect_without_bottom_bar, 472 | &mut ListState::default() 473 | .with_selected(selected) 474 | .with_offset(margin_offset), 475 | ) 476 | } 477 | Layout::Table => { 478 | let (header, rows, constraints) = match value { 479 | Value::List { .. } => { 480 | let header = Row::new(vec![ 481 | Cell::from("item") 482 | .style(normal_data_style.add_modifier(Modifier::REVERSED)), 483 | Cell::from("shape") 484 | .style(normal_shape_style.add_modifier(Modifier::REVERSED)), 485 | ]); 486 | let rows: Vec = repr_data(&value) 487 | .iter() 488 | .cloned() 489 | .map(|row| { 490 | let data_style = match row.data.as_str() { 491 | "record" | "list" => normal_data_style.add_modifier(Modifier::DIM), 492 | _ => normal_data_style, 493 | }; 494 | 495 | Row::new(vec![ 496 | Cell::from(row.data).style(data_style), 497 | Cell::from(row.shape).style(normal_shape_style), 498 | ]) 499 | }) 500 | .collect(); 501 | 502 | let constraints = vec![Constraint::Percentage(90), Constraint::Percentage(10)]; 503 | 504 | (header, rows, constraints) 505 | } 506 | Value::Record { .. } => { 507 | let header = Row::new(vec![ 508 | Cell::from("key").style(normal_name_style.add_modifier(Modifier::REVERSED)), 509 | Cell::from("field") 510 | .style(normal_data_style.add_modifier(Modifier::REVERSED)), 511 | Cell::from("shape") 512 | .style(normal_shape_style.add_modifier(Modifier::REVERSED)), 513 | ]); 514 | 515 | let rows: Vec = repr_data(&value) 516 | .iter() 517 | .cloned() 518 | .map(|row| { 519 | let data_style = match row.data.as_str() { 520 | "record" | "list" => normal_data_style.add_modifier(Modifier::DIM), 521 | _ => normal_data_style, 522 | }; 523 | 524 | Row::new(vec![ 525 | Cell::from(row.name.unwrap_or("".into())).style(normal_name_style), 526 | Cell::from(row.data).style(data_style), 527 | Cell::from(row.shape).style(normal_shape_style), 528 | ]) 529 | }) 530 | .collect(); 531 | 532 | let constraints = vec![ 533 | Constraint::Percentage(20), 534 | Constraint::Percentage(70), 535 | Constraint::Percentage(10), 536 | ]; 537 | 538 | (header, rows, constraints) 539 | } 540 | v => { 541 | let repr = repr_simple_value(&v); 542 | let spans = vec![ 543 | Span::styled(repr.data, normal_data_style), 544 | " is of shape ".into(), 545 | Span::styled(repr.shape, normal_shape_style), 546 | ]; 547 | 548 | frame.render_widget( 549 | Paragraph::new(Line::from(spans)) 550 | .block(Block::default().borders(Borders::ALL)) 551 | .wrap(Wrap { trim: false }), 552 | rect_without_bottom_bar, 553 | ); 554 | return; 555 | } 556 | }; 557 | 558 | let table = if config.show_table_header { 559 | Table::new(rows, constraints).header(header.height(1)) 560 | } else { 561 | Table::new(rows, constraints) 562 | } 563 | .block(Block::default().borders(Borders::ALL)) 564 | .row_highlight_style(highlight_style) 565 | .highlight_symbol(config.colors.selected_symbol.clone()); 566 | 567 | frame.render_stateful_widget( 568 | table, 569 | rect_without_bottom_bar, 570 | &mut TableState::default() 571 | .with_selected(Some(selected)) 572 | .with_offset(margin_offset), 573 | ) 574 | } 575 | } 576 | } 577 | 578 | /// render the cell path just above the status bar 579 | /// 580 | /// this line can be removed through config, see [`crate::config::Config::show_cell_path`] 581 | /// 582 | /// # Examples 583 | /// > :bulb: **Note** 584 | /// > the `...` are here to signify that the bar might be truncated and the `||` at the start and 585 | /// > the end of the lines are just to represent the borders of the terminal but will not appear in 586 | /// > the TUI. 587 | /// 588 | /// - at the beginning 589 | /// ```text 590 | /// ||cell path: $. ...|| 591 | /// ``` 592 | /// - after some navigation, might look like 593 | /// ```text 594 | /// ||cell path: $.foo.bar.2.baz ...|| 595 | /// ``` 596 | fn render_cell_path(frame: &mut Frame, app: &App) { 597 | let next_to_bottom_bar_rect = Rect::new(0, frame.area().height - 2, frame.area().width, 1); 598 | let cell_path = format!( 599 | "cell path: $.{}", 600 | app.position 601 | .members 602 | .iter() 603 | .map(|m| { 604 | match m { 605 | PathMember::Int { val, .. } => val.to_string(), 606 | PathMember::String { val, .. } => val.to_string(), 607 | } 608 | }) 609 | .collect::>() 610 | .join(".") 611 | ); 612 | 613 | frame.render_widget( 614 | Paragraph::new(cell_path).alignment(Alignment::Left), 615 | next_to_bottom_bar_rect, 616 | ); 617 | } 618 | 619 | /// render the status bar at the bottom 620 | /// 621 | /// the bar takes the last line of the TUI only and renders, from left to right 622 | /// - the current mode 623 | /// - hints about next bindings to press and actions to do 624 | /// 625 | /// the color depending of the mode is completely configurable! 626 | /// 627 | /// # Examples 628 | /// > :bulb: **Note** 629 | /// > - the `...` are here to signify that the bar might be truncated and the `||` at the start and 630 | /// > the end of the lines are just to represent the borders of the terminal but will not appear in 631 | /// > the TUI. 632 | /// > - these examples use the default bindings 633 | /// 634 | /// - in NORMAL mode 635 | /// ```text 636 | /// ||NORMAL ... i to INSERT | hjkl to move around | p to peek | q to quit|| 637 | /// ``` 638 | /// - in INSERT mode 639 | /// ```text 640 | /// ||INSERT ... to NORMAL|| 641 | /// ``` 642 | /// - in PEEKING mode 643 | /// ```text 644 | /// ||PEEKING ... to NORMAL | a to peek all | c to peek current view | u to peek under cursor | q to quit|| 645 | /// ``` 646 | fn render_status_bar(frame: &mut Frame, app: &App) { 647 | let config = &app.config; 648 | let bottom_bar_rect = Rect::new(0, frame.area().height - 1, frame.area().width, 1); 649 | 650 | let bg_style = match app.mode { 651 | Mode::Normal | Mode::Waiting(_) => { 652 | Style::default().bg(config.colors.status_bar.normal.background) 653 | } 654 | Mode::Insert => Style::default().bg(config.colors.status_bar.insert.background), 655 | Mode::Peeking => Style::default().bg(config.colors.status_bar.peek.background), 656 | Mode::Bottom => Style::default().bg(config.colors.status_bar.bottom.background), 657 | }; 658 | 659 | let style = match app.mode { 660 | Mode::Normal | Mode::Waiting(_) => bg_style.fg(config.colors.status_bar.normal.foreground), 661 | Mode::Insert => bg_style.fg(config.colors.status_bar.insert.foreground), 662 | Mode::Peeking => bg_style.fg(config.colors.status_bar.peek.foreground), 663 | Mode::Bottom => bg_style.fg(config.colors.status_bar.bottom.foreground), 664 | }; 665 | 666 | frame.render_widget( 667 | Paragraph::new(Line::from(Span::styled( 668 | format!(" {} ", app.mode), 669 | style.add_modifier(Modifier::REVERSED), 670 | ))) 671 | .alignment(Alignment::Left) 672 | .style(bg_style), 673 | bottom_bar_rect, 674 | ); 675 | 676 | if app.config.show_hints || matches!(app.mode, Mode::Waiting(..)) { 677 | let hints = match app.mode { 678 | Mode::Normal => format!( 679 | "{} to {} | {}{}{}{} to move around | {} to peek | {} to transpose | {} to quit", 680 | repr_key(&config.keybindings.insert), 681 | Mode::Insert, 682 | repr_key(&config.keybindings.navigation.left), 683 | repr_key(&config.keybindings.navigation.down), 684 | repr_key(&config.keybindings.navigation.up), 685 | repr_key(&config.keybindings.navigation.right), 686 | repr_key(&config.keybindings.peek), 687 | repr_key(&config.keybindings.transpose), 688 | repr_key(&config.keybindings.quit), 689 | ), 690 | Mode::Waiting(n) => { 691 | if app.config.show_hints { 692 | format!( 693 | "{} to quit | will run next motion {} times", 694 | repr_key(&KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)), 695 | n 696 | ) 697 | } else { 698 | format!("{}", n) 699 | } 700 | }, 701 | Mode::Insert => format!( 702 | "{} to quit | {}{}{}{} to move the cursor | {}{} to delete characters | {} to confirm", 703 | repr_key(&KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)), 704 | repr_key(&KeyEvent::new(KeyCode::Left, KeyModifiers::NONE)), 705 | repr_key(&KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)), 706 | repr_key(&KeyEvent::new(KeyCode::Up, KeyModifiers::NONE)), 707 | repr_key(&KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)), 708 | repr_key(&KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE)), 709 | repr_key(&KeyEvent::new(KeyCode::Delete, KeyModifiers::NONE)), 710 | repr_key(&KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)), 711 | ), 712 | Mode::Peeking => format!( 713 | "{} to {} | {} to peek all | {} to peek current view | {} to peek under cursor | {} to peek the cell path", 714 | repr_key(&config.keybindings.normal), 715 | Mode::Normal, 716 | repr_key(&config.keybindings.peeking.all), 717 | repr_key(&config.keybindings.peeking.view), 718 | repr_key(&config.keybindings.peeking.under), 719 | repr_key(&config.keybindings.peeking.cell_path), 720 | ), 721 | Mode::Bottom => format!( 722 | "{} to {} | {} to peek | {} to quit", 723 | repr_key(&config.keybindings.navigation.left), 724 | Mode::Normal, 725 | repr_key(&config.keybindings.peek), 726 | repr_key(&config.keybindings.quit), 727 | ), 728 | }; 729 | frame.render_widget( 730 | Paragraph::new(Line::from(Span::styled(hints, style))).alignment(Alignment::Right), 731 | bottom_bar_rect, 732 | ); 733 | } 734 | } 735 | 736 | // TODO: add proper assert error messages 737 | #[cfg(test)] 738 | mod tests { 739 | use nu_protocol::{record, Value}; 740 | 741 | use super::{repr_data, repr_list, repr_record, repr_simple_value, repr_table, DataRowRepr}; 742 | 743 | #[test] 744 | fn simple_value() { 745 | #[rustfmt::skip] 746 | let cases = vec![ 747 | (Value::test_string("foo"), DataRowRepr::unnamed("foo", "string")), 748 | (Value::test_int(1), DataRowRepr::unnamed("1", "int")), 749 | (Value::test_bool(true), DataRowRepr::unnamed("true", "bool")), 750 | (Value::test_nothing(), DataRowRepr::unnamed("", "nothing")), 751 | (Value::test_string("foo"), DataRowRepr::unnamed("foo", "string")), 752 | ]; 753 | 754 | for (value, expected) in cases { 755 | assert_eq!(repr_simple_value(&value), expected); 756 | } 757 | } 758 | 759 | #[test] 760 | fn list() { 761 | let list = vec![ 762 | Value::test_string("a"), 763 | Value::test_int(1), 764 | Value::test_bool(false), 765 | ]; 766 | 767 | #[rustfmt::skip] 768 | let cases = vec![ 769 | (list, DataRowRepr::unnamed("[3 items]", "list")), 770 | (vec![], DataRowRepr::unnamed("[]", "list")), 771 | (vec![Value::test_nothing()], DataRowRepr::unnamed("[1 item]", "list")), 772 | ]; 773 | 774 | for (list, expected) in cases { 775 | assert_eq!(repr_list(&list), expected); 776 | } 777 | } 778 | 779 | #[test] 780 | fn record() { 781 | #[rustfmt::skip] 782 | let cases = vec![ 783 | (vec!["a", "b", "c"], DataRowRepr::unnamed("{3 fields}", "record")), 784 | (vec![], DataRowRepr::unnamed("{}", "record")), 785 | (vec!["a"], DataRowRepr::unnamed("{1 field}", "record")), 786 | ]; 787 | 788 | for (record, expected) in cases { 789 | assert_eq!( 790 | repr_record( 791 | &record 792 | .iter() 793 | .map(|x| x.to_string()) 794 | .collect::>() 795 | ), 796 | expected 797 | ); 798 | } 799 | } 800 | 801 | #[ignore = "repr_value is just a direct wrapper around repr_list, repr_record and repr_simple_value"] 802 | #[test] 803 | fn value() {} 804 | 805 | #[test] 806 | fn data() { 807 | let data = Value::test_record(record! { 808 | "l" => Value::test_list(vec![ 809 | Value::test_string("my"), 810 | Value::test_string("list"), 811 | Value::test_string("elements"), 812 | ]), 813 | "r" => Value::test_record(record! { 814 | "a" => Value::test_int(1), 815 | "b" => Value::test_int(2), 816 | }), 817 | "s" => Value::test_string("some string"), 818 | "i" => Value::test_int(123), 819 | }); 820 | 821 | let result = repr_data(&data); 822 | let expected: Vec = vec![ 823 | DataRowRepr::named("l", "[3 items]", "list"), 824 | DataRowRepr::named("r", "{2 fields}", "record"), 825 | DataRowRepr::named("s", "some string", "string"), 826 | DataRowRepr::named("i", "123", "int"), 827 | ]; 828 | assert_eq!(result, expected); 829 | } 830 | 831 | #[test] 832 | fn repr_simple_table() { 833 | let table = vec![ 834 | record! { 835 | "a" => Value::test_string("x"), 836 | "b" => Value::test_int(1), 837 | }, 838 | record! { 839 | "a" => Value::test_string("y"), 840 | "b" => Value::test_int(2), 841 | }, 842 | ]; 843 | 844 | let expected = ( 845 | vec!["a".into(), "b".into()], 846 | vec!["string".into(), "int".into()], 847 | vec![vec!["x".into(), "1".into()], vec!["y".into(), "2".into()]], 848 | ); 849 | 850 | assert_eq!(repr_table(&table), expected); 851 | } 852 | 853 | #[test] 854 | fn repr_table_with_empty_column() { 855 | let table = vec![ 856 | record! { 857 | "a" => Value::test_nothing(), 858 | "b" => Value::test_int(1), 859 | }, 860 | record! { 861 | "a" => Value::test_nothing(), 862 | "b" => Value::test_int(2), 863 | }, 864 | ]; 865 | 866 | let expected = ( 867 | vec!["a".into(), "b".into()], 868 | vec!["nothing".into(), "int".into()], 869 | vec![vec!["".into(), "1".into()], vec!["".into(), "2".into()]], 870 | ); 871 | 872 | assert_eq!(repr_table(&table), expected); 873 | } 874 | 875 | #[test] 876 | fn repr_table_with_shuffled_columns() { 877 | let table = vec![ 878 | record! { 879 | "b" => Value::test_int(1), 880 | "a" => Value::test_string("x"), 881 | }, 882 | record! { 883 | "a" => Value::test_string("y"), 884 | "b" => Value::test_int(2), 885 | }, 886 | ]; 887 | 888 | let expected = ( 889 | vec!["b".into(), "a".into()], 890 | vec!["int".into(), "string".into()], 891 | vec![vec!["1".into(), "x".into()], vec!["2".into(), "y".into()]], 892 | ); 893 | 894 | assert_eq!(repr_table(&table), expected); 895 | } 896 | 897 | #[test] 898 | fn repr_table_with_holes() { 899 | let table = vec![ 900 | record! { 901 | "a" => Value::test_string("x"), 902 | "b" => Value::test_nothing(), 903 | }, 904 | record! { 905 | "a" => Value::test_nothing(), 906 | "b" => Value::test_int(2), 907 | }, 908 | ]; 909 | 910 | let expected = ( 911 | vec!["a".into(), "b".into()], 912 | vec!["string".into(), "int".into()], 913 | vec![vec!["x".into(), "".into()], vec!["".into(), "2".into()]], 914 | ); 915 | 916 | assert_eq!(repr_table(&table), expected); 917 | } 918 | 919 | #[test] 920 | fn repr_table_with_mixed_numeric_types() { 921 | let table = vec![ 922 | record! { 923 | "a" => Value::test_string("x"), 924 | "b" => Value::test_int(1), 925 | }, 926 | record! { 927 | "a" => Value::test_string("y"), 928 | "b" => Value::test_float(2.34), 929 | }, 930 | ]; 931 | 932 | let expected = ( 933 | vec!["a".into(), "b".into()], 934 | vec!["string".into(), "number".into()], 935 | vec![ 936 | vec!["x".into(), "1".into()], 937 | vec!["y".into(), "2.34".into()], 938 | ], 939 | ); 940 | 941 | assert_eq!(repr_table(&table), expected); 942 | } 943 | } 944 | --------------------------------------------------------------------------------