├── .build.yml ├── .gitignore ├── COPYING ├── Makefile ├── README.md ├── README.srht.html ├── demo ├── ijq.gif └── ijq.tape ├── go.mod ├── go.sum ├── history.go ├── history_test.go ├── ijq.1.scd ├── main.go ├── main_test.go └── testdata └── caterror /.build.yml: -------------------------------------------------------------------------------- 1 | image: alpine/edge 2 | oauth: git.sr.ht/OBJECTS:RW git.sr.ht/REPOSITORIES:RW git.sr.ht/PROFILE:RO 3 | packages: 4 | - git 5 | - go 6 | - make 7 | - musl-dev 8 | - scdoc 9 | - hut 10 | sources: 11 | - https://git.sr.ht/~gpanders/ijq 12 | environment: 13 | GIT_SSH_COMMAND: ssh -o StrictHostKeyChecking=no 14 | triggers: 15 | - action: email 16 | condition: failure 17 | to: Gregory Anders 18 | tasks: 19 | - setup: | 20 | echo 'cd ijq' >> ~/.buildenv 21 | - test: | 22 | make test 23 | - update-readme: | 24 | hut git update --readme README.srht.html 25 | - nopr: | 26 | # Don't run on GitHub PRs 27 | [ "$BUILD_SUBMITTER" = 'git.sr.ht' ] || complete-build 28 | - build: | 29 | tag=$(git describe --exact-match 2>/dev/null || true) 30 | if [ -z "$tag" ]; then 31 | echo "Current commit is not a tag; not building anything" 32 | exit 0 33 | fi 34 | 35 | version=$(echo "$tag" | tr -d 'v') 36 | mkdir ijq-"$version" 37 | 38 | build() { 39 | os="$1" 40 | arch="$2" 41 | make GOOS="$os" GOARCH="$arch" clean all 42 | cp ijq ijq.1 COPYING ijq-"$version"/ 43 | 44 | if [ "$os" = windows ]; then 45 | mv ijq-"$version"/ijq{,.exe} 46 | fi 47 | 48 | tar czf ijq-"$version"-"$os"-"$arch".tar.gz ijq-"$version" 49 | hut git artifact upload --rev "$tag" ijq-"$version"-"$os"-"$arch".tar.gz 50 | } 51 | 52 | build darwin amd64 53 | build darwin arm64 54 | build linux amd64 55 | build windows amd64 56 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ijq 2 | ijq.1 3 | cover.out -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 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 | prefix = /usr/local 2 | 3 | # Support upper case PREFIX 4 | ifneq ($(PREFIX),) 5 | prefix := $(PREFIX) 6 | endif 7 | 8 | bindir = $(prefix)/bin 9 | mandir = $(prefix)/share/man 10 | 11 | SRCS = main.go history.go 12 | 13 | VERSION = 1.1.2 14 | 15 | .PHONY: all 16 | all: ijq docs 17 | 18 | .PHONY: docs 19 | docs: ijq.1 20 | 21 | ijq: $(SRCS) 22 | go build -ldflags="-s -w -X main.Version=$(VERSION)" -o $@ 23 | 24 | %.1: %.1.scd 25 | scdoc < $< > $@ 26 | 27 | .PHONY: test 28 | test: 29 | go test -v -coverprofile=./cover.out . 30 | 31 | .PHONY: viewcover 32 | viewcover: 33 | go tool cover -html=./cover.out 34 | 35 | .PHONY: install 36 | install: ijq ijq.1 37 | install -d $(DESTDIR)$(bindir) $(DESTDIR)$(mandir)/man1 38 | install -m 0755 ijq $(DESTDIR)$(bindir) 39 | install -m 0644 ijq.1 $(DESTDIR)$(mandir)/man1 40 | 41 | .PHONY: uninstall 42 | uninstall: 43 | rm $(DESTDIR)$(bindir)/ijq $(DESTDIR)$(mandir)/man1/ijq.1 44 | 45 | .PHONY: clean 46 | clean: 47 | rm -f ijq ijq.1 48 | 49 | demo/ijq.gif: demo/ijq.tape 50 | vhs < $< 51 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ijq 2 | === 3 | 4 | Interactive `jq` tool. Like [jqplay] for the commandline. 5 | 6 | [jqplay]: https://jqplay.org 7 | 8 | Demo 9 | ---- 10 | 11 | ![Demo](./demo/ijq.gif) 12 | 13 | Installation 14 | ------------ 15 | 16 | ### Install from package manager 17 | 18 | [![Packaging status](https://repology.org/badge/vertical-allrepos/ijq.svg?exclude_unsupported=1)](https://repology.org/project/ijq/versions) 19 | 20 | ### Build from source 21 | 22 | Install [go]. To install `ijq` under `/usr/local/bin/` simply run 23 | 24 | make install 25 | 26 | from the root of the project. To install to another location, set the `PREFIX` 27 | variable, e.g. 28 | 29 | make PREFIX=~/.local install 30 | 31 | To generate the man page you will also need to have [scdoc] installed. 32 | 33 | [go]: https://golang.org/dl/ 34 | [scdoc]: https://sr.ht/~sircmpwn/scdoc 35 | 36 | Usage 37 | ----- 38 | 39 | ijq uses [jq] under the hood, so make sure you have that installed first. 40 | 41 | Read from a file: 42 | 43 | ijq file.json 44 | 45 | Read from stdin: 46 | 47 | curl -s https://api.github.com/users/gpanders | ijq 48 | 49 | Press `Return` to close `ijq` and print the current filtered output to stdout. 50 | This will also print the current filter to stderr. This allows you to save the 51 | filter for re-use with `jq` in the future: 52 | 53 | ijq file.json 2>filter.jq 54 | 55 | # Same output as above 56 | jq -f filter.jq file.json 57 | 58 | Pressing `Return` also saves the filter to a history file 59 | (`$XDG_DATA_HOME/ijq/history` by default). You can browse the history by 60 | deleting everything in the filter field. Change the history file used with the 61 | `-H` option, or specify an empty string to disable history entirely (i.e. `-H 62 | ''`). 63 | 64 | If `$XDG_DATA_HOME` is undefined, then the directory used is [platform 65 | dependent][xdg]. 66 | 67 | Use `Shift` plus the arrow keys to move between the different windows. When 68 | either of the input or output views have focus, you can use the arrow keys to 69 | scroll up and down. Vi keys also work, i.e. you can use `j`/`k` to scroll up or 70 | down, `g` to move to the top of the view, `G` to jump to the bottom of the 71 | view, and `Ctrl-F`/`Ctrl-B` to scroll up or down a page at a time. 72 | 73 | Use `Ctrl-C` to exit `ijq` immediately, discarding all filters and state. 74 | 75 | You can configure the colors by setting the `JQ_COLORS` environment variable. 76 | See the [jq documentation][colors] for more details. 77 | 78 | [jq]: https://jqlang.github.io/jq/ 79 | [colors]: https://jqlang.github.io/jq/manual/#colors 80 | [xdg]: https://github.com/kyoh86/xdg#xdg-base-directory 81 | 82 | Contributing 83 | ------------ 84 | 85 | Bugs can be reported on the [issue tracker][issues]. PRs are accepted on 86 | [GitHub][github] or [Codeberg][codeberg]. 87 | 88 | [issues]: https://codeberg.org/gpanders/ijq/issues 89 | [github]: https://github.com/gpanders/ijq 90 | [codeberg]: https://codeberg.org/gpanders/ijq 91 | 92 | Note for Packagers 93 | ------------------ 94 | 95 | Subscribe to release announcements on [Codeberg][codeberg] to be notified of 96 | new releases, or subscribe to the [RSS 97 | feed](https://codeberg.org/gpanders/ijq/releases.rss). 98 | 99 | Similar Work 100 | ------------ 101 | 102 | - [jqplay] 103 | - [vim-jqplay] 104 | 105 | [vim-jqplay]: https://github.com/bfrg/vim-jqplay 106 | 107 | License 108 | ------- 109 | 110 | [GPLv3](https://www.gnu.org/licenses/gpl-3.0.en.html) 111 | -------------------------------------------------------------------------------- /README.srht.html: -------------------------------------------------------------------------------- 1 |

ijq has moved to Codeberg

2 | -------------------------------------------------------------------------------- /demo/ijq.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gpanders/ijq/5f748d40029f0b3c87e2d4a487fc3a73041e1af1/demo/ijq.gif -------------------------------------------------------------------------------- /demo/ijq.tape: -------------------------------------------------------------------------------- 1 | Output demo/ijq.gif 2 | Set Height 1080 3 | Set Width 1920 4 | 5 | Hide 6 | Type "make ijq && clear" 7 | Enter 8 | Type "curl https://dummyjson.com/comments | ./ijq" 9 | Enter 10 | Sleep 2 11 | Show 12 | 13 | Sleep 2 14 | 15 | Type@0.4 "comments[] | select(.user.id < 60)" 16 | 17 | Sleep 2 18 | 19 | Type@0.4 " | {id, body}" 20 | 21 | Sleep 3 22 | 23 | Up 24 | 25 | Sleep 1 26 | 27 | Down @0.2 10 28 | 29 | Sleep 1 30 | 31 | Tab 32 | 33 | Sleep 1 34 | 35 | Down@0.2 20 36 | 37 | Sleep 2 38 | 39 | Up@0.2 10 40 | 41 | Sleep 6 42 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module codeberg.org/gpanders/ijq 2 | 3 | go 1.18 4 | 5 | require ( 6 | github.com/gdamore/tcell/v2 v2.7.1 7 | github.com/kyoh86/xdg v1.2.0 8 | github.com/rivo/tview v0.0.0-20241103174730-c76f7879f592 9 | github.com/stretchr/testify v1.7.0 10 | golang.org/x/term v0.17.0 11 | ) 12 | 13 | require ( 14 | github.com/davecgh/go-spew v1.1.0 // indirect 15 | github.com/gdamore/encoding v1.0.0 // indirect 16 | github.com/lucasb-eyer/go-colorful v1.2.0 // indirect 17 | github.com/mattn/go-runewidth v0.0.15 // indirect 18 | github.com/pmezard/go-difflib v1.0.0 // indirect 19 | github.com/rivo/uniseg v0.4.7 // indirect 20 | golang.org/x/sys v0.17.0 // indirect 21 | golang.org/x/text v0.14.0 // indirect 22 | gopkg.in/yaml.v3 v3.0.1 // indirect 23 | ) 24 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= 2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/gdamore/encoding v1.0.0 h1:+7OoQ1Bc6eTm5niUzBa0Ctsh6JbMW6Ra+YNuAtDBdko= 4 | github.com/gdamore/encoding v1.0.0/go.mod h1:alR0ol34c49FCSBLjhosxzcPHQbf2trDkoo5dl+VrEg= 5 | github.com/gdamore/tcell/v2 v2.7.1 h1:TiCcmpWHiAU7F0rA2I3S2Y4mmLmO9KHxJ7E1QhYzQbc= 6 | github.com/gdamore/tcell/v2 v2.7.1/go.mod h1:dSXtXTSK0VsW1biw65DZLZ2NKr7j0qP/0J7ONmsraWg= 7 | github.com/kyoh86/xdg v1.2.0 h1:CERuT/ShdTDj+A2UaX3hQ3mOV369+Sj+wyn2nIRIIkI= 8 | github.com/kyoh86/xdg v1.2.0/go.mod h1:/mg8zwu1+qe76oTFUBnyS7rJzk7LLC0VGEzJyJ19DHs= 9 | github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= 10 | github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= 11 | github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= 12 | github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= 13 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 14 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 15 | github.com/rivo/tview v0.0.0-20241103174730-c76f7879f592 h1:YIJ+B1hePP6AgynC5TcqpO0H9k3SSoZa2BGyL6vDUzM= 16 | github.com/rivo/tview v0.0.0-20241103174730-c76f7879f592/go.mod h1:02iFIz7K/A9jGCvrizLPvoqr4cEIx7q54RH5Qudkrss= 17 | github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= 18 | github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= 19 | github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= 20 | github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= 21 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 22 | github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= 23 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 24 | github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= 25 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 26 | golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= 27 | golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= 28 | golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= 29 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 30 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= 31 | golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= 32 | golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= 33 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 34 | golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 35 | golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 36 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 37 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 38 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 39 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 40 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 41 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 42 | golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y= 43 | golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 44 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 45 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 46 | golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= 47 | golang.org/x/term v0.17.0 h1:mkTF7LCd6WGJNL3K1Ad7kwxNfYAW6a8a8QqtMblp/4U= 48 | golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= 49 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 50 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 51 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= 52 | golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= 53 | golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= 54 | golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= 55 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 56 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 57 | golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= 58 | golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= 59 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 60 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 61 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 62 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 63 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 64 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 65 | -------------------------------------------------------------------------------- /history.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 Gregory Anders 2 | // Copyright (C) 2021 Herby Gillot 3 | // 4 | // SPDX-License-Identifier: GPL-3.0-or-later 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | 19 | package main 20 | 21 | import ( 22 | "bufio" 23 | "bytes" 24 | "errors" 25 | "fmt" 26 | "os" 27 | "path/filepath" 28 | "strings" 29 | ) 30 | 31 | type history struct { 32 | path string 33 | Items []string 34 | } 35 | 36 | func (h *history) Init(path string) error { 37 | h.path = path 38 | 39 | filebytes, err := os.ReadFile(path) 40 | if err != nil { 41 | // If the history file doesn't exist, then 42 | // return an empty history. 43 | if errors.Is(err, os.ErrNotExist) { 44 | return nil 45 | } else { 46 | return fmt.Errorf("error retrieving history: %w", err) 47 | } 48 | } 49 | 50 | scanner := bufio.NewScanner(bytes.NewReader(filebytes)) 51 | for scanner.Scan() { 52 | h.Items = append(h.Items, scanner.Text()) 53 | } 54 | 55 | if err := scanner.Err(); err != nil { 56 | return fmt.Errorf( 57 | "error retrieving history: %w", err, 58 | ) 59 | } 60 | 61 | return nil 62 | } 63 | 64 | func (h *history) Add(expression string) error { 65 | expression = strings.TrimSpace(expression) 66 | if expression == "" { 67 | return nil 68 | } 69 | 70 | if h.path == "" { 71 | return nil 72 | } 73 | 74 | // Don't continue with adding the expression if it is saved in history 75 | // already. 76 | if contains(h.Items, expression) { 77 | return nil 78 | } 79 | 80 | h.Items = append(h.Items, expression) 81 | 82 | file, err := h.openFile() 83 | if err != nil { 84 | return fmt.Errorf("error opening history for writing: %w", err) 85 | } 86 | 87 | fmt.Fprintln(file, expression) 88 | 89 | if err = file.Close(); err != nil { 90 | return fmt.Errorf("error closing history file: %w", err) 91 | } 92 | 93 | return nil 94 | } 95 | 96 | func (h *history) openFile() (*os.File, error) { 97 | err := os.MkdirAll(filepath.Dir(h.path), os.ModePerm) 98 | if err != nil { 99 | return nil, err 100 | } 101 | 102 | f, err := os.OpenFile(h.path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) 103 | if err != nil { 104 | return nil, err 105 | } 106 | 107 | return f, nil 108 | } 109 | 110 | func contains(arr []string, elem string) bool { 111 | for _, v := range arr { 112 | if elem == v { 113 | return true 114 | } 115 | } 116 | 117 | return false 118 | } 119 | -------------------------------------------------------------------------------- /history_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 Gregory Anders 2 | // Copyright (C) 2021 Herby Gillot 3 | // 4 | // SPDX-License-Identifier: GPL-3.0-or-later 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | 19 | package main 20 | 21 | import ( 22 | "io/ioutil" 23 | "math/rand" 24 | "os" 25 | "path" 26 | "strconv" 27 | "testing" 28 | "time" 29 | 30 | "github.com/stretchr/testify/assert" 31 | ) 32 | 33 | func randomFilename(namebase string) string { 34 | random := rand.New(rand.NewSource(time.Now().UnixNano())) 35 | if namebase == "" { 36 | namebase = "file" 37 | } 38 | 39 | return namebase + "." + strconv.Itoa(random.Int()) 40 | } 41 | 42 | func makeHistoryFilename() string { 43 | return randomFilename("./history") 44 | } 45 | 46 | func TestHistoryAddNoFilename(t *testing.T) { 47 | var h history 48 | err := h.Add("foo") 49 | assert.NoError(t, err) 50 | assert.Nil(t, err) 51 | assert.Empty(t, h.Items) 52 | } 53 | 54 | func TestHistoryAddEmptyString(t *testing.T) { 55 | histfile := makeHistoryFilename() 56 | var h history 57 | h.Init(histfile) 58 | err := h.Add("") 59 | assert.NoError(t, err) 60 | assert.Nil(t, err) 61 | assert.NoFileExists(t, histfile) 62 | } 63 | 64 | func TestContains(t *testing.T) { 65 | things := []string{"one", "two", "three"} 66 | 67 | assert.True(t, contains(things, "one")) 68 | assert.True(t, contains(things, "two")) 69 | assert.True(t, contains(things, "three")) 70 | assert.False(t, contains(things, "four")) 71 | } 72 | 73 | func TestHistoryAdd(t *testing.T) { 74 | histFile := makeHistoryFilename() 75 | 76 | before := "one\ntwo\n" 77 | after := "one\ntwo\nthree\n" 78 | 79 | err := ioutil.WriteFile(histFile, []byte(before), 0644) 80 | assert.NoError(t, err) 81 | 82 | var h history 83 | h.Init(histFile) 84 | 85 | err = h.Add("three") 86 | assert.NoError(t, err) 87 | 88 | contents, err := ioutil.ReadFile(histFile) 89 | assert.NoError(t, err) 90 | assert.Equal(t, []byte(after), contents) 91 | 92 | assert.NoError(t, os.Remove(histFile)) 93 | } 94 | 95 | func TestHistoryAddRepeating(t *testing.T) { 96 | histFile := makeHistoryFilename() 97 | 98 | contents := "one\ntwo\n" 99 | 100 | err := ioutil.WriteFile(histFile, []byte(contents), 0644) 101 | assert.NoError(t, err) 102 | 103 | var h history 104 | h.Init(histFile) 105 | 106 | err = h.Add("one") 107 | assert.NoError(t, err) 108 | 109 | retrieved, err := ioutil.ReadFile(histFile) 110 | assert.NoError(t, err) 111 | assert.Equal(t, []byte(contents), retrieved) 112 | 113 | assert.NoError(t, os.Remove(histFile)) 114 | } 115 | 116 | func TestHistoryWithinSubDir(t *testing.T) { 117 | rootDir := "./testdata/myroot" 118 | 119 | histFile := path.Join(rootDir, "myhistory") 120 | 121 | var h history 122 | h.Init(histFile) 123 | 124 | err := h.Add("one") 125 | assert.NoError(t, err) 126 | assert.FileExists(t, histFile) 127 | 128 | assert.NoError(t, os.RemoveAll(rootDir)) 129 | } 130 | 131 | func TestHistoryGetMissingFile(t *testing.T) { 132 | historyFile := "./this.does.not.exist" 133 | 134 | var h history 135 | h.Init(historyFile) 136 | assert.NoFileExists(t, historyFile) 137 | } 138 | 139 | func TestHistory(t *testing.T) { 140 | histFile := makeHistoryFilename() 141 | 142 | var h history 143 | h.Init(histFile) 144 | 145 | var err error 146 | 147 | err = h.Add("one") 148 | assert.NoError(t, err) 149 | err = h.Add("two") 150 | assert.NoError(t, err) 151 | err = h.Add("three") 152 | assert.NoError(t, err) 153 | 154 | assert.NoError(t, err) 155 | 156 | assert.Equal( 157 | t, 158 | h.Items, 159 | []string{"one", "two", "three"}, 160 | ) 161 | 162 | // Add new after Get 163 | err = h.Add("four") 164 | assert.NoError(t, err) 165 | 166 | assert.Equal( 167 | t, 168 | h.Items, 169 | []string{"one", "two", "three", "four"}, 170 | ) 171 | 172 | // Attempt to add item already in history 173 | err = h.Add("one") 174 | assert.NoError(t, err) 175 | 176 | assert.Equal( 177 | t, 178 | h.Items, 179 | []string{"one", "two", "three", "four"}, 180 | ) 181 | 182 | assert.NoError(t, os.Remove(histFile)) 183 | } 184 | -------------------------------------------------------------------------------- /ijq.1.scd: -------------------------------------------------------------------------------- 1 | ijq(1) 2 | 3 | # NAME 4 | 5 | ijq - interactive jq 6 | 7 | # SYNOPSIS 8 | 9 | *ijq* [*-cnsrRMSV*] [*-f* _file_] [_filter_] [_files ..._] 10 | 11 | # DESCRIPTION 12 | 13 | *ijq* is a near drop-in replacement for *jq* that allows you to interactively 14 | see the results of your filter as you construct it. 15 | 16 | *ijq* contains two panes and an input field: the left pane is the original, 17 | unmodified input data and the right pane contains the filtered output. When you 18 | are finished, press Return or Ctrl-C to exit. The filtered output will be 19 | written to standard output and the filter itself will be written to standard 20 | error. 21 | 22 | *ijq* maintains a history of used filters, unless disabled with the *-H* option. 23 | Delete all text in the filter field to browse any available history. 24 | 25 | If _files_ is omitted then *ijq* reads data from standard input. 26 | 27 | All of the options mirror their counterparts in *jq*. The options are: 28 | 29 | *-c* 30 | Use compact instead of pretty-printed output. 31 | 32 | *-n* 33 | Don't read any input. Useful for using *ijq* as a calculator or to 34 | construct JSON data from scratch. 35 | 36 | *-s* 37 | Read all input into a single array and apply the given filter to it. 38 | 39 | *-r* 40 | If the filter output is a string it will be written directly to standard 41 | output rather than being formatted as a JSON string with quotes. Useful 42 | for using *ijq* in a pipeline with other programs that expect normal 43 | string input. 44 | 45 | *-R* 46 | Don't parse the input as JSON, instead passing each line of input to the 47 | filter as a string. If combined with *-s* then the entire input is 48 | passed to the filter as a single long string. 49 | 50 | *-M* 51 | Disable colored output. 52 | 53 | *-S* 54 | Output the fields of each object with the fields in sorted order. 55 | 56 | *-f* _file_ 57 | Read the filter from _file_. When this option is used, all positional 58 | arguments (if any) are interpreted as input files. 59 | 60 | *-H* _file_ 61 | Specify the path to store history. If set to '' (-H ''), then history 62 | will not be captured. 63 | 64 | # KEY BINDINGS 65 | 66 | *Shift + Up*, *Shift + Left* 67 | Focus the input (left) viewing pane. 68 | 69 | *Shift + Right* 70 | Focus the output (right) viewing pane. 71 | 72 | *Shift + Down* 73 | Focus the text input field. 74 | 75 | *Tab* 76 | When the text input field has focus, navigate between the autocompletion 77 | list. When one of the viewing panes has focus, toggle between the 78 | different views. 79 | 80 | *Shift-Tab* 81 | Like *Tab*, but moves in the opposite direction. 82 | 83 | *Ctrl-A* 84 | When the text input field has focus, move the cursor to the beginning of 85 | the input. When one of the viewing panes has focus, set the column 86 | offset to 0. 87 | 88 | *Ctrl-E* 89 | When the text input field has focus, move the cursor to the end of the 90 | input. When one of the viewing panes has focus, set the column offset to 91 | view the longest visible line. 92 | 93 | *Ctrl-F* 94 | When the text input field has focus, move the cursor one character 95 | forward. When one of the viewing panes has focus, scroll down one page. 96 | 97 | *Ctrl-B* 98 | When the text input field has focus, move the cursor one character 99 | backward. When one of the viewing panes has focus, scroll up one page. 100 | 101 | *Ctrl-D* 102 | When the text input field has focus, delete the character under the 103 | cursor. When one of the viewing panes has focus, scroll down one half 104 | page. 105 | 106 | *Ctrl-U* 107 | When the text input field has focus, delete all of the text from the 108 | cursor to the beginning of the field. When one of the viewing panes has 109 | focus, scroll up one half page. 110 | 111 | *u*, *d*, *f*, *b* 112 | When one of the viewing panes has focus, scroll a half/full page 113 | up/down. 114 | 115 | *Left*, *Down*, *Up*, *Right* 116 | *h*, *j*, *k*, *l* 117 | When one of the viewing panes has focus, move the view 118 | left/down/up/right. 119 | 120 | *Return* 121 | Close *ijq*. Write the contents of the output pane to stdout and the 122 | current input filter to stderr. The current input filter is also saved 123 | to the history file. 124 | 125 | *Ctrl-C* 126 | Exit *ijq* immediately, discarding all state. 127 | 128 | # DEMO 129 | 130 | See https://asciinema.org/a/496932 for a demo. 131 | 132 | # SEE ALSO 133 | 134 | jq(1) 135 | 136 | # AUTHOR 137 | 138 | Gregory Anders 139 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 Gregory Anders 2 | // Copyright (C) 2021 Herby Gillot 3 | // 4 | // SPDX-License-Identifier: GPL-3.0-or-later 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | 19 | package main 20 | 21 | import ( 22 | "bytes" 23 | "context" 24 | "encoding/json" 25 | "flag" 26 | "fmt" 27 | "io" 28 | "log" 29 | "os" 30 | "os/exec" 31 | "path/filepath" 32 | "strings" 33 | "sync" 34 | 35 | "github.com/gdamore/tcell/v2" 36 | "github.com/kyoh86/xdg" 37 | "github.com/rivo/tview" 38 | "golang.org/x/term" 39 | ) 40 | 41 | const defaultCommand string = "jq" 42 | 43 | // Special characters that, if present in a JSON key, need to be quoted in the 44 | // jq filter 45 | const specialChars string = ".-:$/" 46 | 47 | const alphabet string = "abcdefghijklmnopqrstuvwxyz" 48 | 49 | var Version string 50 | 51 | type Options struct { 52 | compact bool 53 | command string 54 | nullInput bool 55 | slurp bool 56 | rawOutput bool 57 | rawInput bool 58 | monochrome bool 59 | sortKeys bool 60 | historyFile string 61 | forceColor bool 62 | } 63 | 64 | // Convert the Options struct to a string slice of option flags that gets 65 | // passed to jq. 66 | func (o *Options) ToSlice() []string { 67 | opts := []string{} 68 | 69 | if o.compact { 70 | opts = append(opts, "-c") 71 | } 72 | 73 | if o.nullInput { 74 | opts = append(opts, "-n") 75 | } 76 | 77 | if o.slurp { 78 | opts = append(opts, "-s") 79 | } 80 | 81 | if o.rawOutput { 82 | opts = append(opts, "-r") 83 | } 84 | 85 | if o.rawInput { 86 | opts = append(opts, "-R") 87 | } 88 | 89 | if o.monochrome { 90 | opts = append(opts, "-M") 91 | } 92 | 93 | if o.forceColor { 94 | opts = append(opts, "-C") 95 | } 96 | 97 | if o.sortKeys { 98 | opts = append(opts, "-S") 99 | } 100 | 101 | return opts 102 | } 103 | 104 | type Document struct { 105 | input string 106 | filter string 107 | options Options 108 | ctx context.Context 109 | } 110 | 111 | func (d Document) WithFilter(filter string) Document { 112 | return Document{input: d.input, filter: filter, options: d.options, ctx: context.Background()} 113 | } 114 | 115 | func (d *Document) ReadFrom(r io.Reader) (n int64, err error) { 116 | var buf bytes.Buffer 117 | n, err = buf.ReadFrom(r) 118 | d.input = buf.String() 119 | return n, err 120 | } 121 | 122 | func (d Document) WriteTo(w io.Writer) (n int64, err error) { 123 | opts := d.options 124 | if p, ok := w.(*pane); ok { 125 | // Writer is a pane, so set options accordingly 126 | opts.forceColor = true 127 | opts.monochrome = false 128 | opts.compact = false 129 | opts.rawOutput = false 130 | w = tview.ANSIWriter(p) 131 | 132 | // Mark the pane as dirty so the text view is cleared before 133 | // new output is written. 134 | p.dirty = true 135 | } 136 | 137 | args := append(opts.ToSlice(), d.filter) 138 | cmd := exec.CommandContext(d.ctx, d.options.command, args...) 139 | 140 | var b bytes.Buffer 141 | cmd.Stdin = strings.NewReader(d.input) 142 | cmd.Stdout = w 143 | cmd.Stderr = &b 144 | 145 | err = cmd.Run() 146 | 147 | if err != nil { 148 | if exiterr, ok := err.(*exec.ExitError); ok { 149 | exiterr.Stderr = b.Bytes() 150 | } 151 | return 0, err 152 | } 153 | 154 | return 0, nil 155 | } 156 | 157 | type pane struct { 158 | tv *tview.TextView 159 | dirty bool 160 | } 161 | 162 | func (pane *pane) Write(p []byte) (n int, err error) { 163 | if pane.dirty { 164 | pane.tv.Clear() 165 | pane.dirty = false 166 | } 167 | 168 | return pane.tv.Write(p) 169 | } 170 | 171 | func parseArgs() (Options, string, []string) { 172 | flag.Usage = func() { 173 | fmt.Fprintf(os.Stderr, "ijq - interactive jq\n\n") 174 | fmt.Fprintf(os.Stderr, "Usage: ijq [-cnsrRMSV] [-f file] [filter] [files ...]\n\n") 175 | fmt.Fprintf(os.Stderr, "Options:\n") 176 | flag.PrintDefaults() 177 | } 178 | 179 | options := Options{} 180 | flag.BoolVar(&options.compact, "c", false, "compact instead of pretty-printed output") 181 | flag.BoolVar(&options.nullInput, "n", false, "use ```null` as the single input value") 182 | flag.BoolVar(&options.slurp, "s", false, "read (slurp) all inputs into an array; apply filter to it") 183 | flag.BoolVar(&options.rawOutput, "r", false, "output raw strings, not JSON texts") 184 | flag.BoolVar(&options.rawInput, "R", false, "read raw strings, not JSON texts") 185 | flag.BoolVar(&options.forceColor, "C", false, "force colorized JSON, even if writing to a pipe or file") 186 | flag.BoolVar(&options.monochrome, "M", false, "monochrome (don't colorize JSON)") 187 | flag.BoolVar(&options.sortKeys, "S", false, "sort keys of objects on output") 188 | 189 | flag.StringVar( 190 | &options.command, 191 | "jqbin", 192 | defaultCommand, 193 | "name of or path to jq binary to use", 194 | ) 195 | 196 | flag.StringVar( 197 | &options.historyFile, 198 | "H", 199 | filepath.Join(xdg.DataHome(), "ijq", "history"), 200 | "set path to history file. Set to '' to disable history.", 201 | ) 202 | 203 | filterFile := flag.String("f", "", "read initial filter from `filename`") 204 | version := flag.Bool("V", false, "print version and exit") 205 | 206 | flag.Parse() 207 | 208 | if *version { 209 | fmt.Println("ijq " + Version) 210 | os.Exit(0) 211 | } 212 | 213 | filter := "." 214 | args := flag.Args() 215 | 216 | stdinIsTty := term.IsTerminal(int(os.Stdin.Fd())) 217 | 218 | if *filterFile != "" { 219 | contents, err := os.ReadFile(*filterFile) 220 | if err != nil { 221 | log.Fatalln(err) 222 | } 223 | 224 | filter = string(contents) 225 | } else if len(args) > 1 || (len(args) > 0 && (!stdinIsTty || options.nullInput)) { 226 | filter = args[0] 227 | args = args[1:] 228 | } else if len(args) == 0 && stdinIsTty && !options.nullInput { 229 | flag.Usage() 230 | os.Exit(1) 231 | } 232 | 233 | return options, filter, args 234 | } 235 | 236 | func scrollHalfPage(tv *tview.TextView, up bool) { 237 | _, _, _, height := tv.GetInnerRect() 238 | row, col := tv.GetScrollOffset() 239 | if up { 240 | tv.ScrollTo(row-height/2, col) 241 | } else { 242 | tv.ScrollTo(row+height/2, col) 243 | } 244 | } 245 | 246 | func scrollHorizontally(tv *tview.TextView, end bool) { 247 | if end { 248 | text := tv.GetText(true) 249 | _, _, width, height := tv.GetInnerRect() 250 | row, _ := tv.GetScrollOffset() 251 | maxLen := 0 252 | for i, line := range strings.Split(text, "\n") { 253 | if i < row { 254 | continue 255 | } 256 | 257 | if i > row+height { 258 | break 259 | } 260 | 261 | if length := len(line); length > maxLen { 262 | maxLen = length 263 | } 264 | } 265 | 266 | if maxLen > width { 267 | tv.ScrollTo(row, maxLen-width) 268 | } 269 | } else { 270 | row, _ := tv.GetScrollOffset() 271 | tv.ScrollTo(row, 0) 272 | } 273 | } 274 | 275 | func updateScrollIndicator(name string, lineCount int, tv *tview.TextView) { 276 | row, _ := tv.GetScrollOffset() 277 | if row <= 0 { 278 | tv.SetTitle(fmt.Sprintf("%s (Top)", name)) 279 | return 280 | } 281 | 282 | _, _, _, height := tv.GetInnerRect() 283 | if row+height >= lineCount { 284 | tv.SetTitle(fmt.Sprintf("%s (Bot)", name)) 285 | return 286 | } 287 | 288 | percent := row * 100 / lineCount 289 | tv.SetTitle(fmt.Sprintf("%s (%d%%)", name, percent)) 290 | } 291 | 292 | func createApp(doc Document) *tview.Application { 293 | app := tview.NewApplication() 294 | 295 | // tview uses colors for a dark background by default, so reset some of 296 | // the styles to simply use the colors from the terminal to better 297 | // support light color themes 298 | tview.Styles.PrimaryTextColor = tcell.ColorDefault 299 | tview.Styles.PrimitiveBackgroundColor = tcell.ColorDefault 300 | tview.Styles.BorderColor = tcell.ColorDefault 301 | tview.Styles.TitleColor = tcell.ColorDefault 302 | tview.Styles.GraphicsColor = tcell.ColorDefault 303 | 304 | inputView := tview.NewTextView() 305 | inputView.SetDynamicColors(true).SetWrap(false).SetBorder(true) 306 | inputPane := pane{tv: inputView} 307 | 308 | outputView := tview.NewTextView() 309 | outputView.SetDynamicColors(true).SetWrap(false).SetBorder(true) 310 | outputPane := pane{tv: outputView} 311 | 312 | errorView := tview.NewTextView() 313 | errorView.SetDynamicColors(false).SetTitle("Error").SetBorder(true) 314 | 315 | var filterHistory history 316 | filterHistory.Init(doc.options.historyFile) 317 | 318 | var ( 319 | mutex sync.Mutex 320 | cancel context.CancelFunc 321 | ) 322 | cond := sync.NewCond(&mutex) 323 | 324 | // Initialize pending to true so that the output pane will update with the initial filter 325 | pending := true 326 | 327 | filterMap := make(map[string][]string) 328 | filterInput := tview.NewInputField() 329 | filterInput. 330 | SetText(doc.filter). 331 | SetFieldBackgroundColor(tcell.ColorDefault). 332 | SetFieldTextColor(tcell.ColorDefault). 333 | SetChangedFunc(func(text string) { 334 | errorView.Clear() 335 | filterInput.SetFieldTextColor(tcell.ColorDefault) 336 | 337 | if text == doc.filter { 338 | return 339 | } 340 | 341 | cancel() 342 | 343 | mutex.Lock() 344 | defer mutex.Unlock() 345 | 346 | doc = doc.WithFilter(text) 347 | pending = true 348 | cond.Signal() 349 | }). 350 | SetDoneFunc(func(key tcell.Key) { 351 | switch key { 352 | case tcell.KeyEnter: 353 | app.Stop() 354 | 355 | fmt.Fprintln(os.Stderr, doc.filter) 356 | 357 | // Enable or disable colors depending on if 358 | // stdout is a tty, respecting options set by 359 | // the user 360 | isTty := term.IsTerminal(int(os.Stdout.Fd())) 361 | if !isTty && !doc.options.forceColor { 362 | doc.options.monochrome = true 363 | } else if isTty && !doc.options.monochrome { 364 | doc.options.forceColor = true 365 | } 366 | 367 | filterHistory.Add(doc.filter) 368 | 369 | if _, err := doc.WriteTo(os.Stdout); err != nil { 370 | log.Fatalln(err) 371 | } 372 | } 373 | }). 374 | SetAutocompleteFunc(func(text string) []string { 375 | if text == "" { 376 | return filterHistory.Items 377 | } 378 | 379 | if pos := strings.LastIndexByte(text, '.'); pos != -1 { 380 | prefix := text[0:pos] 381 | trimmed := strings.TrimSpace(prefix) 382 | 383 | mutex.Lock() 384 | candidates, ok := filterMap[trimmed] 385 | mutex.Unlock() 386 | if ok { 387 | cur := text[pos+1:] 388 | var entries []string 389 | for _, c := range candidates { 390 | key := c[pos+1:] 391 | if strings.HasPrefix(key, cur) { 392 | entries = append(entries, c) 393 | } 394 | } 395 | 396 | return entries 397 | } 398 | 399 | go func() { 400 | var filt string 401 | if prefix != "" { 402 | p, _ := strings.CutSuffix(trimmed, "|") 403 | filt = p + "| keys" 404 | } else { 405 | filt = "keys" 406 | } 407 | 408 | var buf bytes.Buffer 409 | _, err := doc.WithFilter("[" + filt + "] | unique | first").WriteTo(&buf) 410 | if err != nil { 411 | return 412 | } 413 | 414 | var keys []string 415 | if err := json.Unmarshal(buf.Bytes(), &keys); err != nil { 416 | return 417 | } 418 | 419 | entries := keys[:0] 420 | for _, k := range keys { 421 | first := strings.ToLower(string(k[0])) 422 | if strings.ContainsAny(k, specialChars) || !strings.Contains(alphabet, first) { 423 | k = `"` + k + `"` 424 | } 425 | entries = append(entries, prefix+"."+k) 426 | } 427 | 428 | mutex.Lock() 429 | filterMap[trimmed] = entries 430 | mutex.Unlock() 431 | 432 | filterInput.Autocomplete() 433 | 434 | app.Draw() 435 | }() 436 | } 437 | 438 | return nil 439 | }). 440 | SetAutocompleteUseTags(false). 441 | SetAutocompleteStyles(tcell.ColorBlack, tcell.StyleDefault.Background(tcell.ColorBlack), tcell.StyleDefault.Reverse(true)). 442 | SetTitle("Filter"). 443 | SetBorder(true) 444 | 445 | // Initialize the initial line counts to some large number. If the 446 | // input is small, this will be updated to the correct value before it 447 | // is ever displayed in the UI. But for large inputs (which will take 448 | // longer to calculate the correct value), this is a better initial 449 | // guess. 450 | inputLineCount := 10000 451 | outputLineCount := 10000 452 | 453 | // Process document with empty filter to populate input view 454 | go func() { 455 | _, err := doc.WithFilter(".").WriteTo(&inputPane) 456 | if err != nil { 457 | log.Fatalf("Error while running jq on input: %s\n", err) 458 | } 459 | 460 | inputLineCount = strings.Count(inputView.GetText(false), "\n") 461 | }() 462 | 463 | // Create a cancellable context when writing to the output view. If the 464 | // filter input changes, the context is cancelled and the process is 465 | // killed. 466 | doc.ctx, cancel = context.WithCancel(context.Background()) 467 | 468 | go func() { 469 | for { 470 | cond.L.Lock() 471 | for !pending { 472 | cond.Wait() 473 | } 474 | 475 | d := doc 476 | pending = false 477 | cond.L.Unlock() 478 | 479 | // Re-initialize the cancellable context 480 | d.ctx, cancel = context.WithCancel(context.Background()) 481 | 482 | _, err := d.WriteTo(&outputPane) 483 | if err != nil { 484 | if exitErr, ok := err.(*exec.ExitError); ok { 485 | if code := exitErr.ExitCode(); code != -1 { 486 | app.QueueUpdate(func() { 487 | filterInput.SetFieldTextColor(tcell.ColorMaroon) 488 | fmt.Fprint(tview.ANSIWriter(errorView), string(exitErr.Stderr)) 489 | }) 490 | } 491 | } 492 | } else { 493 | outputLineCount = strings.Count(outputView.GetText(false), "\n") 494 | } 495 | 496 | app.Draw() 497 | } 498 | }() 499 | 500 | grid := tview.NewGrid(). 501 | SetRows(0, 3, 4). 502 | SetColumns(0). 503 | AddItem(tview.NewFlex(). 504 | AddItem(inputView, 0, 1, false). 505 | AddItem(outputView, 0, 1, false), 0, 0, 1, 1, 0, 0, false). 506 | AddItem(tview.NewFlex(). 507 | AddItem(tview.NewBox(), 0, 1, false). 508 | AddItem(filterInput, 0, 4, true). 509 | AddItem(tview.NewBox(), 0, 1, false), 1, 0, 1, 1, 0, 0, true). 510 | AddItem(tview.NewFlex(). 511 | AddItem(tview.NewBox(), 0, 1, false). 512 | AddItem(errorView, 0, 4, false). 513 | AddItem(tview.NewBox(), 0, 1, false), 2, 0, 1, 1, 0, 0, false) 514 | 515 | app.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey { 516 | shift := event.Modifiers()&tcell.ModShift != 0 517 | focused := app.GetFocus() 518 | 519 | switch key := event.Key(); key { 520 | case tcell.KeyCtrlN: 521 | return tcell.NewEventKey(tcell.KeyDown, ' ', tcell.ModNone) 522 | case tcell.KeyCtrlP: 523 | return tcell.NewEventKey(tcell.KeyUp, ' ', tcell.ModNone) 524 | case tcell.KeyCtrlV: 525 | return tcell.NewEventKey(tcell.KeyPgDn, ' ', tcell.ModNone) 526 | case tcell.KeyCtrlA: 527 | if tv, ok := focused.(*tview.TextView); ok { 528 | scrollHorizontally(tv, false) 529 | return nil 530 | } 531 | case tcell.KeyCtrlE: 532 | if tv, ok := focused.(*tview.TextView); ok { 533 | scrollHorizontally(tv, true) 534 | return nil 535 | } 536 | case tcell.KeyCtrlU: 537 | if tv, ok := focused.(*tview.TextView); ok { 538 | scrollHalfPage(tv, true) 539 | return nil 540 | } 541 | case tcell.KeyCtrlD: 542 | if tv, ok := focused.(*tview.TextView); ok { 543 | scrollHalfPage(tv, false) 544 | return nil 545 | } 546 | case tcell.KeyCtrlF: 547 | if filterInput.HasFocus() { 548 | return tcell.NewEventKey(tcell.KeyRight, ' ', tcell.ModNone) 549 | } 550 | case tcell.KeyCtrlB: 551 | if filterInput.HasFocus() { 552 | return tcell.NewEventKey(tcell.KeyLeft, ' ', tcell.ModNone) 553 | } 554 | case tcell.KeyUp: 555 | if shift && filterInput.HasFocus() { 556 | app.SetFocus(inputView) 557 | return nil 558 | } 559 | case tcell.KeyLeft: 560 | if shift { 561 | app.SetFocus(inputView) 562 | return nil 563 | } 564 | case tcell.KeyRight: 565 | if shift { 566 | app.SetFocus(outputView) 567 | return nil 568 | } 569 | case tcell.KeyDown: 570 | if shift { 571 | app.SetFocus(filterInput) 572 | return nil 573 | } 574 | case tcell.KeyTab: 575 | if inputView.HasFocus() { 576 | app.SetFocus(outputView) 577 | return nil 578 | } else if outputView.HasFocus() { 579 | app.SetFocus(filterInput) 580 | return nil 581 | } else if filterInput.HasFocus() { 582 | return tcell.NewEventKey(tcell.KeyDown, ' ', tcell.ModNone) 583 | } 584 | case tcell.KeyBacktab: 585 | if inputView.HasFocus() { 586 | app.SetFocus(filterInput) 587 | return nil 588 | } else if outputView.HasFocus() { 589 | app.SetFocus(inputView) 590 | return nil 591 | } else if filterInput.HasFocus() { 592 | return tcell.NewEventKey(tcell.KeyUp, ' ', tcell.ModNone) 593 | } 594 | } 595 | 596 | if tv, ok := focused.(*tview.TextView); ok { 597 | switch ru := event.Rune(); ru { 598 | case '0': 599 | scrollHorizontally(tv, false) 600 | return nil 601 | case '$': 602 | scrollHorizontally(tv, true) 603 | return nil 604 | case 'd': 605 | scrollHalfPage(tv, false) 606 | return nil 607 | case 'u': 608 | scrollHalfPage(tv, true) 609 | return nil 610 | case 'b': 611 | return tcell.NewEventKey(tcell.KeyCtrlB, ' ', tcell.ModNone) 612 | case 'f': 613 | return tcell.NewEventKey(tcell.KeyCtrlF, ' ', tcell.ModNone) 614 | case 'v': 615 | if event.Modifiers()&tcell.ModAlt != 0 { 616 | return tcell.NewEventKey(tcell.KeyPgUp, ' ', tcell.ModNone) 617 | } 618 | case 'G': 619 | // tview handles G natively but does not 620 | // redraw, so the scroll indicator doesn't 621 | // update. So we handle G ourselves and force a 622 | // redraw 623 | tv.ScrollToEnd() 624 | app.ForceDraw() 625 | } 626 | } 627 | 628 | return event 629 | }) 630 | 631 | app.SetBeforeDrawFunc(func(screen tcell.Screen) bool { 632 | // Start a synchronized update 633 | tty, ok := screen.Tty() 634 | if ok { 635 | tty.Write([]byte("\x1b[?2026h")) 636 | } 637 | 638 | updateScrollIndicator("Input", inputLineCount, inputView) 639 | updateScrollIndicator("Output", outputLineCount, outputView) 640 | 641 | return false 642 | }) 643 | 644 | app.SetAfterDrawFunc(func(screen tcell.Screen) { 645 | // Finish a synchronized update 646 | tty, ok := screen.Tty() 647 | if ok { 648 | tty.Write([]byte("\x1b[?2026l")) 649 | } 650 | }) 651 | 652 | app.SetRoot(grid, true).EnableMouse(true).SetFocus(grid) 653 | 654 | return app 655 | } 656 | 657 | func main() { 658 | // Remove log prefix 659 | log.SetFlags(0) 660 | 661 | options, filter, args := parseArgs() 662 | 663 | if _, err := exec.LookPath(options.command); err != nil { 664 | log.Fatalf("%s is not installed or could not be found: %s\n", options.command, err) 665 | } 666 | 667 | doc := Document{filter: filter, options: options} 668 | 669 | if !options.nullInput { 670 | var in io.Reader = os.Stdin 671 | if len(args) > 0 { 672 | var files []io.Reader 673 | for _, fname := range args { 674 | f, err := os.Open(fname) 675 | if err != nil { 676 | log.Fatalln(err) 677 | } 678 | 679 | defer f.Close() 680 | 681 | files = append(files, f) 682 | } 683 | 684 | in = io.MultiReader(files...) 685 | } 686 | 687 | if _, err := doc.ReadFrom(in); err != nil { 688 | log.Fatalln(err) 689 | } 690 | } 691 | 692 | app := createApp(doc) 693 | if err := app.Run(); err != nil { 694 | log.Fatalln(err) 695 | } 696 | } 697 | -------------------------------------------------------------------------------- /main_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 Gregory Anders 2 | // Copyright (C) 2021 Herby Gillot 3 | // 4 | // SPDX-License-Identifier: GPL-3.0-or-later 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | 19 | package main 20 | 21 | import ( 22 | "bytes" 23 | "context" 24 | "os/exec" 25 | "strings" 26 | "testing" 27 | 28 | "github.com/stretchr/testify/assert" 29 | ) 30 | 31 | func TestOptionsToSlice(t *testing.T) { 32 | opt := &Options{} 33 | 34 | opt.compact = true 35 | assert.Contains(t, opt.ToSlice(), "-c") 36 | opt.compact = false 37 | assert.NotContains(t, opt.ToSlice(), "-c") 38 | 39 | opt.nullInput = true 40 | assert.Contains(t, opt.ToSlice(), "-n") 41 | opt.nullInput = false 42 | assert.NotContains(t, opt.ToSlice(), "-n") 43 | 44 | opt.slurp = true 45 | assert.Contains(t, opt.ToSlice(), "-s") 46 | opt.slurp = false 47 | assert.NotContains(t, opt.ToSlice(), "-s") 48 | 49 | opt.rawOutput = true 50 | assert.Contains(t, opt.ToSlice(), "-r") 51 | opt.rawOutput = false 52 | assert.NotContains(t, opt.ToSlice(), "-r") 53 | 54 | opt.rawInput = true 55 | assert.Contains(t, opt.ToSlice(), "-R") 56 | opt.rawInput = false 57 | assert.NotContains(t, opt.ToSlice(), "-R") 58 | 59 | opt.monochrome = true 60 | assert.Contains(t, opt.ToSlice(), "-M") 61 | opt.monochrome = false 62 | assert.NotContains(t, opt.ToSlice(), "-M") 63 | 64 | opt.forceColor = true 65 | assert.Contains(t, opt.ToSlice(), "-C") 66 | opt.forceColor = false 67 | assert.NotContains(t, opt.ToSlice(), "-C") 68 | 69 | opt.sortKeys = true 70 | assert.Contains(t, opt.ToSlice(), "-S") 71 | opt.sortKeys = false 72 | assert.NotContains(t, opt.ToSlice(), "-S") 73 | } 74 | 75 | func TestDocumentReadFrom(t *testing.T) { 76 | testMsg := "hello world" 77 | testReader := strings.NewReader(testMsg) 78 | 79 | doc := &Document{} 80 | 81 | readCount, err := doc.ReadFrom(testReader) 82 | assert.NoError(t, err) 83 | assert.Equal(t, len(testMsg), int(readCount)) 84 | } 85 | 86 | func TestDocumentWriteTo(t *testing.T) { 87 | testMsg := "hello world" 88 | testReader := strings.NewReader(testMsg) 89 | 90 | doc := &Document{ 91 | filter: "-", 92 | options: Options{ 93 | command: "cat", 94 | }, 95 | ctx: context.Background(), 96 | } 97 | 98 | readCount, err := doc.ReadFrom(testReader) 99 | assert.NoError(t, err) 100 | assert.Equal(t, len(testMsg), int(readCount)) 101 | 102 | buffer := bytes.Buffer{} 103 | 104 | writeCount, err := doc.WriteTo(&buffer) 105 | assert.NoError(t, err) 106 | assert.Equal(t, 0, int(writeCount)) 107 | 108 | assert.Equal(t, testMsg, buffer.String()) 109 | } 110 | 111 | func TestDocumentExecError(t *testing.T) { 112 | testMsg := "hello world" 113 | testReader := strings.NewReader(testMsg) 114 | 115 | doc := &Document{ 116 | options: Options{ 117 | command: "./testdata/caterror", 118 | }, 119 | ctx: context.Background(), 120 | } 121 | 122 | readCount, err := doc.ReadFrom(testReader) 123 | assert.NoError(t, err) 124 | assert.Equal(t, len(testMsg), int(readCount)) 125 | 126 | buffer := bytes.Buffer{} 127 | 128 | writeCount, err := doc.WriteTo(&buffer) 129 | assert.Error(t, err) 130 | assert.Equal(t, 0, int(writeCount)) 131 | 132 | exiterr, ok := err.(*exec.ExitError) 133 | assert.True(t, ok) 134 | assert.NotNil(t, exiterr) 135 | assert.Equal(t, testMsg, string(exiterr.Stderr)) 136 | 137 | assert.Empty(t, buffer.String()) 138 | } 139 | -------------------------------------------------------------------------------- /testdata/caterror: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # Ignore all flags specified, and just cat with non-zero exit code. 3 | cat >&2 4 | exit 1 5 | --------------------------------------------------------------------------------