diff options
| author | Lukasz Kasprzak <lukas@labunix.xyz> | 2026-09-11 14:47:10 +0200 |
|---|---|---|
| committer | Lukasz Kasprzak <lukas@labunix.xyz> | 2026-09-11 15:01:57 +0200 |
| commit | 42b02c47be9b285099203e44a2570636d4ca6f03 (patch) | |
| tree | 82bcb9e19bd886f36e1ca7b2d94a204c988f1fd1 | |
| download | krino-42b02c47be9b285099203e44a2570636d4ca6f03.tar.gz krino-42b02c47be9b285099203e44a2570636d4ca6f03.zip | |
krino: foundation — sexp reader, config language, init/new/check
36 files changed, 4456 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1a6b9a9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +/krino +/dist/ +# personal configs and test data kept next to the code; never committed +/local/ +/.superpowers/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..8b5fb8b --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,5 @@ +# Changelog + +## Unreleased + +- Initial development: config language, `krino init`, `krino new`, `krino check`. @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<https://www.gnu.org/licenses/why-not-lgpl.html>. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..9dfc7d4 --- /dev/null +++ b/Makefile @@ -0,0 +1,55 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# Works with GNU make and BSD make. + +DESTDIR ?= +PREFIX ?= $(HOME)/.local +BINDIR = $(DESTDIR)$(PREFIX)/bin +BIN = krino +VERSION != git describe --tags --always --dirty 2>/dev/null || echo dev +LDFLAGS = -s -w -X main.version=$(VERSION) + +.PHONY: all help build install uninstall test vet fmt ci install-hooks clean + +all: build + +help: ## show this help + @grep -E '^[a-z-]+:.*## ' Makefile | \ + awk 'BEGIN {FS = ":.*## "}; {printf " %-10s %s\n", $$1, $$2}' + @echo " version: $(VERSION) prefix: $(PREFIX)" + +build: ## build ./krino; Go fetches module dependencies itself + CGO_ENABLED=0 go build -trimpath -ldflags "$(LDFLAGS)" -o $(BIN) ./cmd/krino + +install: build ## install to $(PREFIX)/bin + mkdir -p $(BINDIR) + rm -f $(BINDIR)/$(BIN) + install -m 755 $(BIN) $(BINDIR)/$(BIN) + +uninstall: ## remove the installed binary + rm -f $(BINDIR)/$(BIN) + +test: ## run the tests + go test ./... + +vet: ## go vet + go vet ./... + +fmt: ## gofmt the tree + gofmt -w . + +ci: ## the gate: gofmt, vet, tests, dependencies, no personal data staged + @test -z "$$(gofmt -l .)" || { echo "gofmt needed:"; gofmt -l .; exit 1; } + go vet ./... + GOOS=freebsd CGO_ENABLED=0 go vet ./... + GOOS=openbsd CGO_ENABLED=0 go vet ./... + go test ./... + @deps=$$(go list -deps ./... | grep -E '^[a-z0-9-]+\.[a-z]+/' | grep -vE '^golang\.org/x/(term|text|sys)(/|$$)' || true); \ + test -z "$$deps" || { echo "unexpected dependencies:"; echo "$$deps"; exit 1; } + @scripts/leak-check + @echo "ci ok" + +install-hooks: ## install the pre-commit hook that runs the leak check + install -m 755 scripts/hooks/pre-commit "$$(git rev-parse --git-path hooks)/pre-commit" + +clean: ## remove build output + rm -f $(BIN) diff --git a/cmd/krino/check.go b/cmd/krino/check.go new file mode 100644 index 0000000..fcd507d --- /dev/null +++ b/cmd/krino/check.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package main + +import ( + "fmt" + "io" + "os" + + "krino/internal/config" + "krino/internal/xdg" +) + +func init() { commands["check"] = cmdCheck } + +// cmdCheck validates the configuration and lists each directory's rules. +func cmdCheck(g *globals, args []string, stdout, stderr io.Writer) int { + fs := flagSet("check", g) + if code, ok := parse(fs, args, stdout, stderr); !ok { + return code + } + cfg, errs := config.Load(mainFile(g), fs.Args()...) + if len(errs) > 0 { + printDiags(stderr, errs) + return 2 + } + fmt.Fprintf(stdout, "config: %s\n", xdg.Abbrev(cfg.Main.File)) + if len(cfg.Dirs) == 0 { + fmt.Fprintln(stdout, "no directories included; add one with: krino new NAME PATH") + } + for _, d := range cfg.Dirs { + fmt.Fprintf(stdout, "\n%s %s\n", d.Name, xdg.Abbrev(d.Path)) + if fi, err := os.Stat(d.Path); err != nil || !fi.IsDir() { + fmt.Fprintf(stdout, " warning: %s is not a directory right now; it will be skipped\n", xdg.Abbrev(d.Path)) + } + if len(d.Rules) == 0 { + fmt.Fprintln(stdout, " no rules yet") + } + for i, r := range d.Rules { + fmt.Fprintf(stdout, " %2d %-16s %s\n", i+1, r.Name, describeActions(r)) + } + } + return 0 +} diff --git a/cmd/krino/commands_test.go b/cmd/krino/commands_test.go new file mode 100644 index 0000000..68a2174 --- /dev/null +++ b/cmd/krino/commands_test.go @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// home gives each test its own HOME with an empty XDG config. +func home(t *testing.T) string { + t.Helper() + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("XDG_CONFIG_HOME", "") + return h +} + +func TestInitNewCheck(t *testing.T) { + h := home(t) + if err := os.Mkdir(filepath.Join(h, "dl"), 0o755); err != nil { + t.Fatal(err) + } + code, out, errOut := runCLI(t, "init") + if code != 0 || !strings.Contains(out, "created ~/.config/krino/krino.conf") { + t.Fatalf("init: %d %q %q", code, out, errOut) + } + code, out, _ = runCLI(t, "check") + if code != 0 || !strings.Contains(out, "no directories included") { + t.Fatalf("check, empty: %d %q", code, out) + } + code, out, errOut = runCLI(t, "new", "dl", "~/dl") + if code != 0 || !strings.Contains(out, "created ~/.config/krino/dirs/dl.conf") { + t.Fatalf("new: %d %q %q", code, out, errOut) + } + conf := filepath.Join(h, ".config", "krino", "dirs", "dl.conf") + rules := "(path \"~/dl\")\n(rule \"pdfs\" (when (type pdf)) (move \"PDF\") (stop))\n" + if err := os.WriteFile(conf, []byte(rules), 0o644); err != nil { + t.Fatal(err) + } + code, out, errOut = runCLI(t, "check") + if code != 0 || !strings.Contains(out, "dl ~/dl") || !strings.Contains(out, "pdfs") || + !strings.Contains(out, "move PDF, stop") { + t.Fatalf("check: %d %q %q", code, out, errOut) + } + if err := os.WriteFile(conf, []byte(`(path "~/dl") (rule "x" (move PDF))`), 0o644); err != nil { + t.Fatal(err) + } + code, _, errOut = runCLI(t, "check") + want := `~/.config/krino/dirs/dl.conf:1:31: rule "x": move takes a string: write (move "PDF")` + if code != 2 || !strings.Contains(errOut, want) || !strings.Contains(errOut, "1 problem found") { + t.Fatalf("check, broken: %d %q", code, errOut) + } +} + +// TestConfigFlagExpandsTilde is item B: -c=~/... is not expanded by the +// shell (the ~ comes after =), so krino must expand it itself. +func TestConfigFlagExpandsTilde(t *testing.T) { + h := home(t) + cwd := t.TempDir() + t.Chdir(cwd) + code, out, errOut := runCLI(t, "-c=~/k/krino.conf", "init") + if code != 0 { + t.Fatalf("init: %d %q %q", code, out, errOut) + } + want := filepath.Join(h, "k", "krino.conf") + if _, err := os.Stat(want); err != nil { + t.Fatalf("%s not created: %v", want, err) + } + if _, err := os.Lstat(filepath.Join(cwd, "~")); !os.IsNotExist(err) { + t.Fatalf(`"~" created in the current directory: %v`, err) + } +} + +func TestConfigFlag(t *testing.T) { + h := home(t) + conf := filepath.Join(h, "elsewhere", "krino.conf") + if code, _, errOut := runCLI(t, "init", "-c", conf); code != 0 { + t.Fatalf("init -c: %q", errOut) + } + for _, args := range [][]string{{"-c", conf, "check"}, {"check", "-c", conf}} { + if code, out, errOut := runCLI(t, args...); code != 0 || !strings.Contains(out, "config: ~/elsewhere/krino.conf") { + t.Errorf("%v: %d %q %q", args, code, out, errOut) + } + } +} + +func TestCommandErrors(t *testing.T) { + home(t) + tests := []struct { + args []string + want string + }{ + {[]string{"check"}, "not found; create it with: krino init"}, + {[]string{"new", "onlyname"}, "usage: krino new NAME PATH"}, + {[]string{"init", "extra"}, "init takes no arguments"}, + } + for _, tt := range tests { + if code, _, errOut := runCLI(t, tt.args...); code != 2 || !strings.Contains(errOut, tt.want) { + t.Errorf("%v: %d %q, want %q", tt.args, code, errOut, tt.want) + } + } +} diff --git a/cmd/krino/common.go b/cmd/krino/common.go new file mode 100644 index 0000000..ea1e83d --- /dev/null +++ b/cmd/krino/common.go @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package main + +import ( + "fmt" + "io" + "strings" + + "krino/internal/config" + "krino/internal/xdg" +) + +// mainFile is -c FILE, or the default krino.conf. +func mainFile(g *globals) string { + if g.conf != "" { + return xdg.Expand(g.conf) + } + return config.DefaultFile() +} + +// usageError reports a command-line mistake and returns exit status 2. +func usageError(stderr io.Writer, msg string) int { + fmt.Fprintf(stderr, "krino: %s\nrun 'krino -h' for help\n", msg) + return 2 +} + +// printDiags prints config problems with ~ for the home directory, then a count. +func printDiags(stderr io.Writer, errs []*config.Diag) { + for _, e := range errs { + d := *e + d.File = xdg.Abbrev(d.File) + fmt.Fprintln(stderr, &d) + } + if len(errs) == 1 { + fmt.Fprintln(stderr, "krino: 1 problem found") + } else { + fmt.Fprintf(stderr, "krino: %d problems found\n", len(errs)) + } +} + +// describeActions renders a rule's actions briefly, as in: move PDF, stop. +func describeActions(r *config.Rule) string { + var parts []string + for _, a := range r.Actions { + if a.Arg == "" { + parts = append(parts, a.Kind.String()) + } else { + parts = append(parts, a.Kind.String()+" "+a.Arg) + } + } + if r.Stop { + parts = append(parts, "stop") + } + return strings.Join(parts, ", ") +} diff --git a/cmd/krino/init.go b/cmd/krino/init.go new file mode 100644 index 0000000..2122ff8 --- /dev/null +++ b/cmd/krino/init.go @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package main + +import ( + "fmt" + "io" + + "krino/internal/config" + "krino/internal/xdg" +) + +func init() { commands["init"] = cmdInit } + +// cmdInit creates the config directory with a commented krino.conf and +// template.conf. +func cmdInit(g *globals, args []string, stdout, stderr io.Writer) int { + fs := flagSet("init", g) + if code, ok := parse(fs, args, stdout, stderr); !ok { + return code + } + if fs.NArg() != 0 { + return usageError(stderr, "init takes no arguments") + } + created, err := config.Init(mainFile(g)) + if err != nil { + fmt.Fprintf(stderr, "krino: %v\n", err) + return 2 + } + for _, f := range created { + fmt.Fprintf(stdout, "created %s\n", xdg.Abbrev(f)) + } + fmt.Fprintln(stdout, "next: krino new NAME PATH, for example: krino new downloads ~/Downloads") + return 0 +} diff --git a/cmd/krino/main.go b/cmd/krino/main.go new file mode 100644 index 0000000..0048098 --- /dev/null +++ b/cmd/krino/main.go @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +// Command krino sorts files in configured directories by rules. +package main + +import ( + "errors" + "flag" + "fmt" + "io" + "os" +) + +// version is stamped by the Makefile with -ldflags "-X main.version=...". +var version = "dev" + +const usage = `usage: krino [-y | -n] [-v] [--json] [-c FILE] [NAME...] + krino init + krino new NAME PATH + krino check [NAME...] + krino explain FILE + krino log [-n N] + krino undo [RUN] + +Sort the files in the directories listed in krino.conf by their rules. + + -y apply without asking + -n dry run: show the plan, change nothing + -v also list unmatched, ignored and busy files + --json with -n: print the plan as JSON + -c FILE use FILE instead of ~/.config/krino/krino.conf + -h, --help show this help + --version print the version +` + +// globals holds the flags that may appear before or after a subcommand. +type globals struct { + yes, dry, verbose, json bool + conf string +} + +// command is a subcommand: it gets the parsed globals and its own arguments. +type command func(g *globals, args []string, stdout, stderr io.Writer) int + +// commands maps subcommand names to their functions; each cmd file adds itself. +var commands = map[string]command{} + +func main() { + os.Exit(run(os.Args[1:], os.Stdout, os.Stderr)) +} + +// run is main without the process exit, so tests can drive it. +func run(args []string, stdout, stderr io.Writer) int { + g := &globals{} + fs := flagSet("krino", g) + fs.BoolVar(&g.yes, "y", false, "") + fs.BoolVar(&g.dry, "n", false, "") + fs.BoolVar(&g.verbose, "v", false, "") + fs.BoolVar(&g.json, "json", false, "") + showVersion := fs.Bool("version", false, "") + if code, ok := parse(fs, args, stdout, stderr); !ok { + return code + } + if *showVersion { + fmt.Fprintf(stdout, "krino %s\n", version) + return 0 + } + rest := fs.Args() + if len(rest) > 0 { + if cmd, ok := commands[rest[0]]; ok { + return cmd(g, rest[1:], stdout, stderr) + } + } + return cmdSort(g, rest, stdout, stderr) +} + +// flagSet returns a silent flag set with -c bound to g, shared by every command. +func flagSet(name string, g *globals) *flag.FlagSet { + fs := flag.NewFlagSet(name, flag.ContinueOnError) + fs.SetOutput(io.Discard) + fs.StringVar(&g.conf, "c", g.conf, "") + return fs +} + +// parse parses args into fs. On -h it prints the usage and returns (0, false); +// on a bad flag it reports it and returns (2, false). +func parse(fs *flag.FlagSet, args []string, stdout, stderr io.Writer) (int, bool) { + err := fs.Parse(args) + switch { + case err == nil: + return 0, true + case errors.Is(err, flag.ErrHelp): + fmt.Fprint(stdout, usage) + return 0, false + default: + fmt.Fprintf(stderr, "krino: %v\nrun 'krino -h' for help\n", err) + return 2, false + } +} + +// cmdSort plans and applies the included directories. It arrives in plan 3. +func cmdSort(g *globals, names []string, stdout, stderr io.Writer) int { + fmt.Fprintln(stderr, "krino: sorting is not implemented yet; try 'krino check'") + return 2 +} diff --git a/cmd/krino/main_test.go b/cmd/krino/main_test.go new file mode 100644 index 0000000..1caab6b --- /dev/null +++ b/cmd/krino/main_test.go @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package main + +import ( + "bytes" + "strings" + "testing" + + "krino/internal/config" +) + +// runCLI drives run() and returns its exit code and output. +func runCLI(t *testing.T, args ...string) (int, string, string) { + t.Helper() + var out, errb bytes.Buffer + code := run(args, &out, &errb) + return code, out.String(), errb.String() +} + +func TestVersion(t *testing.T) { + code, out, _ := runCLI(t, "--version") + if code != 0 || out != "krino dev\n" { + t.Fatalf("got %d %q, want 0 %q", code, out, "krino dev\n") + } +} + +func TestHelp(t *testing.T) { + for _, arg := range []string{"-h", "--help"} { + code, out, _ := runCLI(t, arg) + if code != 0 || !strings.HasPrefix(out, "usage: krino") { + t.Errorf("%s: got %d %q", arg, code, out) + } + } +} + +func TestBadFlag(t *testing.T) { + code, _, errOut := runCLI(t, "--bogus") + if code != 2 || !strings.Contains(errOut, "flag provided but not defined: -bogus") { + t.Fatalf("got %d %q", code, errOut) + } +} + +// TestCommandsAreReserved is item E: every subcommand name must also be a +// reserved directory name, so a directory can never shadow a command. +func TestCommandsAreReserved(t *testing.T) { + for name := range commands { + if !config.Reserved[name] { + t.Errorf("command %q is not in config.Reserved", name) + } + } +} + +func TestSortNotYet(t *testing.T) { + code, _, errOut := runCLI(t) + if code != 2 || !strings.Contains(errOut, "not implemented yet") { + t.Fatalf("got %d %q", code, errOut) + } +} diff --git a/cmd/krino/new.go b/cmd/krino/new.go new file mode 100644 index 0000000..1cd89a6 --- /dev/null +++ b/cmd/krino/new.go @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package main + +import ( + "fmt" + "io" + + "krino/internal/config" + "krino/internal/xdg" +) + +func init() { commands["new"] = cmdNew } + +// cmdNew creates dirs/NAME.conf from the template and includes it. +func cmdNew(g *globals, args []string, stdout, stderr io.Writer) int { + fs := flagSet("new", g) + if code, ok := parse(fs, args, stdout, stderr); !ok { + return code + } + if fs.NArg() != 2 { + return usageError(stderr, "usage: krino new NAME PATH") + } + name := fs.Arg(0) + file, err := config.NewDir(mainFile(g), name, fs.Arg(1)) + if err != nil { + fmt.Fprintf(stderr, "krino: %v\n", err) + return 2 + } + fmt.Fprintf(stdout, "created %s and added %q to include\n", xdg.Abbrev(file), name) + fmt.Fprintf(stdout, "edit its rules, then check them with: krino check %s\n", name) + return 0 +} diff --git a/docs/design.md b/docs/design.md new file mode 100644 index 0000000..ed77e8c --- /dev/null +++ b/docs/design.md @@ -0,0 +1,626 @@ +# krino design + +Status: draft for review, 2026-09-11. Target release: **0.0.1**. + +krino (from Greek κρίνω, "to separate, to judge, to decide") sorts files in +chosen directories by rules. A rule tests a file's type, name, path, size, +age, text content or duplicate status, combined with `and` / `or` / `not`, +and applies actions: copy, move, rename, delete. krino shows what it will do, +lets you approve all of it or file by file, logs every step, and can undo a +run. + +It grew out of an earlier Python prototype; the lessons that shaped it are +in §16. + +--- + +## 1. Scope + +**0.0.1 is:** the engine and a command-line interface. + +- per-directory rule files, a main file listing which directories run, a + template for new ones +- conditions with `and` / `or` / `not` over type, name, path, content, size, + age, duplicates +- actions copy, move, rename, delete (to Trash by default), chained +- plan, review, approve all or per file, `-y` to skip review +- a log of every step, and `krino undo` +- placeholders in destinations and new names +- builds for Linux, FreeBSD and OpenBSD + +**Not in 0.0.1:** the GUI (a separate project after 0.0.1, see §12), watch +mode, OCR, EXIF dates, macOS and Windows, a content cache, a shell-command +action, looking inside archives. + +## 2. Terms + +| Term | Meaning | +|---|---| +| directory | a configured directory krino sorts, e.g. `~/downloads`; one config file each | +| root | that directory's path | +| rule | a named condition plus actions | +| test | one leaf of a condition, e.g. `(type pdf)` | +| chain | the ordered actions krino will perform on one file | +| plan | every chain for one directory, computed before anything changes | +| run | one invocation of krino that applied at least one step, across all the directories it processed; has an id; the unit of undo | + +## 3. Files and locations + +``` +$XDG_CONFIG_HOME/krino/ default ~/.config/krino + krino.conf main file: which directories run, defaults, log path + template.conf copied by `krino new` + dirs/<name>.conf one per directory +$XDG_STATE_HOME/krino/ default ~/.local/state/krino + krino.log the log (§9) + <name>.lock per-directory lock while a run is active +``` + +`krino init` creates the config directory with a commented `krino.conf` and +`template.conf` (both embedded in the binary). It refuses if krino.conf +exists and keeps an existing template.conf. +`krino new NAME PATH` copies `template.conf` to `dirs/NAME.conf`, fills in +the path, and appends NAME to `include` in `krino.conf`, keeping its comments. + +Generated files begin with `;; -*- mode: lisp -*-` and `;; vim: set ft=lisp :` +so editors apply Lisp highlighting and parenthesis matching. + +## 4. Config language + +### 4.1 Syntax + +The files are s-expressions (see `docs/sexp-primer.md` for a tutorial). + +- **List:** `(` items separated by whitespace `)` +- **String:** `"..."`. A backslash escapes only `"` and `\`; any other + backslash is kept literally, so `"\bacme\b"` is the regex `\bacme\b`. + Strings may span lines. +- **Symbol:** any other run of characters except whitespace, `(`, `)`, `"`, `;`. +- **Comment:** `;` to end of line. +- Encoding UTF-8. No other syntax: no quote characters, no dotted pairs, + no block comments. + +The reader records the byte offset, line and column of every list and atom. +krino edits a file by splicing text at those offsets (`krino new` inserts a +name into `include`), so everything else, comments and layout included, +stays byte for byte. A printer for generated forms arrives with the GUI. +Errors report `file:line:col`. An unclosed list is reported where it opened, +described by its first atoms: `"(" never closed: (rule "acme" ...)`. + +Paths, keywords, regexes and rule names must be strings. Settings values, +type names, operators, sizes and durations are symbols. + +### 4.2 `krino.conf` + +```lisp +(include "downloads" "documents") ; dirs/<name>.conf, run in this order +(log "~/.local/state/krino/krino.log") ; optional +(defaults ; optional; any setting from 4.4 + (min-age 5m)) +``` + +### 4.3 `dirs/<name>.conf` + +```lisp +(path "~/downloads") ; required +(recursive no) ; any setting from 4.4 +(ignore "*.part" "*.aria2" ".*") ; may repeat; patterns accumulate in order + +(rule "acme" + (when (type document) + (or (content "acme ltd" "0000000000") + (name "\bacme\b")) + (not (name "^draft"))) + (move "Work/Acme/{mtime:%Y}") + (stop)) +``` + +Top-level forms may appear in any order, except that rules are evaluated in +the order written. + +### 4.4 Settings + +Each setting can appear in `(defaults ...)`, at the top of a directory file, +or (where marked) inside a rule. The most specific wins: rule, then +directory, then defaults, then built-in. + +| Setting | Values | Built-in | In a rule | +|---|---|---|---| +| `case` | `ignore` \| `strict` | `ignore` | yes | +| `fold` | `yes` \| `no`. Strip diacritics before comparing: ą→a, ł→l, é→e, ü→u, and so on for all Latin letters | `yes` | yes | +| `recursive` | `yes` \| `no` | `no` | | +| `max-depth` | integer, 1 = root only | unlimited | | +| `min-age` | duration. Skip files modified more recently | `2m` | | +| `max-read` | size. No content extraction above this file size | `50M` | | +| `busy` | suffixes. Skip `f` when `f<suffix>` exists beside it | `".part" ".aria2" ".crdownload"` | | +| `on-conflict` | `suffix` \| `skip` \| `overwrite` (§7.4) | `suffix` | yes | + +Durations: integer plus `s m h d w`. Sizes: integer plus optional `K M G T` +(powers of 1024). + +### 4.5 Rules + +```lisp +(rule NAME ITEM...) +``` + +Items, in any order except that actions run in the order written: + +| Item | Meaning | +|---|---| +| `(when COND...)` | the condition. Several conditions means all must hold. A rule without `when` matches every file. An empty `(when)` is an error. | +| `(case ...)` `(fold ...)` `(on-conflict ...)` | rule-level settings | +| `(copy DEST)` | copy the file into directory DEST | +| `(move DEST)` | move the file into directory DEST | +| `(rename NAME)` | rename in place; NAME must not contain `/` | +| `(delete)` | move to Trash | +| `(delete permanent)` | unlink; cannot be undone | +| `(stop)` | once this rule matches, evaluate no further rules for this file | + +A rule with only `(stop)` is an exclusion: files it matches receive no +actions from later rules. + +`DEST` is a directory: relative paths are relative to the root, `~` expands, +absolute paths are allowed. It is created if missing. `DEST` and `NAME` take +placeholders (§7.3). + +## 5. Conditions + +### 5.1 Operators + +`(and C...)`, `(or C...)`, `(not C)`. `and` and `or` take one or more +arguments; `not` exactly one. + +### 5.2 Tests + +| Test | True when | +|---|---| +| `(type T...)` | the name ends in `.T` for any T, case-insensitively. T may be a group (§A) or a multi-part suffix like `tar.gz`. | +| `(name "RE"...)` | the file name matches any regex | +| `(path "RE"...)` | the path relative to the root matches any regex | +| `(content "KW"...)` | the extracted text contains any keyword (§6) | +| `(size OP SIZE)` | OP is `> >= < <= =` | +| `(age OP DURATION)` | age by modification time | +| `(duplicate)` | another scanned file has identical content, and this one is not the original (§5.5) | +| `(duplicate "DIR"...)` | the same, also comparing against files under those directories | +| `(matched)` | an earlier rule matched this file | + +Regexes use Go's RE2 syntax: POSIX ERE plus `\d \w \s \b`, non-greedy +quantifiers, and inline flags `(?i)` `(?-i)`; no backreferences or lookaround. + +### 5.3 Case and diacritics + +`case` and `fold` apply to `name`, `path` and `content`, in both the file's +data and the pattern. `type` is always case-insensitive. A regex can +override `case` locally with `(?i)` or `(?-i)`. Folding decomposes letters +(Unicode NFD), drops combining marks, and maps the letters that do not +decompose (ł ø đ ħ ß æ œ and their capitals) to ASCII. + +### 5.4 Evaluation + +1. Every test sees **the original file**: name, path, size, mtime and + content as they were when scanning. Actions from earlier rules do not + change what later rules see. +2. Rules are evaluated in order. A matching rule adds its actions to the + file's chain. `(stop)` on a matching rule ends evaluation for that file. +3. Tests have no side effects, so `and` / `or` evaluate their arguments + cheapest first: `type`, `name`, `path`, `size`, `age`, `matched`, then + `duplicate`, then `content`. Content is extracted at most once per file, + and only if evaluation reaches a `content` test. +4. If a file's text cannot be extracted, `content` is false and the plan + shows a warning naming the rule that wanted it. + +### 5.5 Duplicates + +Candidates are the scanned files plus, for `(duplicate "DIR"...)`, every +regular file under those directories (symlinks skipped). Files are grouped +by size. Only groups of two or more are hashed: first the first and last +64 KiB, then SHA-256 of the whole file. Empty files are never duplicates. + +The **original** in each group is, in order of preference: a file under one +of the given DIRs, then the oldest by mtime, then the shortest name, then +the name that sorts first. `(duplicate)` is true for every other scanned +file in the group. + +## 6. Content extraction + +| Format | Method | +|---|---| +| text | known text extensions, or detected from the first 8 KiB: valid UTF-8, or UTF-16 with a BOM, and no NUL bytes | +| pdf | `pdftotext -q -enc UTF-8 FILE -`, 30 s timeout | +| docx xlsx pptx odt ods odp epub | zip plus streaming XML, Go standard library | +| html xml | tags removed, entities decoded | +| doc | `antiword`, else `catdoc` | +| xls / ppt | `xls2csv` / `catppt` (both from catdoc) | +| anything else | no content | + +External tools are optional. Each is looked up once per run; `krino check` +lists which were found. Files above `max-read` are not extracted. Tools run +without a shell, get absolute paths only (so a name starting with `-` is +never read as an option), and are killed at the timeout. + +Before matching, text and keywords are normalised the same way: case (if +`ignore`), fold (if `yes`), and runs of whitespace collapsed to one space, +so a keyword split across lines in a PDF still matches. Matching is +substring: `"acme"` matches `"acmeco"`. Words hyphenated across lines in a +PDF are not rejoined. + +## 7. Actions + +### 7.1 Chains + +A file's chain is the actions of every matching rule, in rule order, and +within a rule in the order written. The executor tracks the file's current +path: + +- `copy` leaves the file where it is; +- `rename` changes its name, `move` its directory; later steps use the new path; +- `delete` ends the chain. Steps after it appear in the plan as + "skipped: deleted by rule X". + +The plan warns when a chain moves a file more than once; that is usually a +missing `(stop)`. + +### 7.2 How each action is carried out + +- **move:** `rename(2)` when source and destination are on the same + filesystem. Otherwise: copy to a temporary file in the destination + directory, fsync, rename into place, then remove the source. If any step + fails the source is untouched and the temporary file removed. +- **copy:** to a temporary file in the destination, then rename into place. + Mode and mtime are preserved. +- **rename:** `rename(2)` within the same directory. +- **delete:** into the freedesktop.org Trash in `$XDG_DATA_HOME/Trash` + (`files/` plus a `.trashinfo` in `info/`). A file on a different + filesystem from the Trash is not trashed: the step fails with a message + suggesting `(delete permanent)` or a move. The Trash layout is the same on + Linux, FreeBSD and OpenBSD. +- **delete permanent:** `unlink(2)`. + +Before each step the executor checks that the source still exists with the +size and mtime recorded in the plan. If not, the step fails as "changed +since plan" and the rest of that file's chain is skipped. + +### 7.3 Placeholders + +| Placeholder | Value | +|---|---| +| `{name}` | the current file name | +| `{stem}` | the name without its last extension | +| `{ext}` | the last extension with its dot, e.g. `.pdf`; empty if none | +| `{1}` … `{9}` | capture groups of the first `name` test that matched in this rule | +| `{mtime:FMT}` | the file's modification time | +| `{now:FMT}` | the start of the run | +| `{{` `}}` | literal braces | + +FMT is a strftime subset: `%Y %m %d %H %M %S %j %%`. + +Captures come from the first `name` test, not inside a `not`, that was true +while evaluating this rule. Tests of equal cost keep their written order, so +"first" is well defined. `krino check` rejects a rule that uses `{N}` unless +every such `name` test in it has at least N groups, and a rule that uses +`{N}` with no `name` test at all. + +### 7.4 Conflicts + +When the target already exists: + +- `suffix` (default): use `stem_1.ext`, `stem_2.ext`, ... +- `skip`: skip this step; the chain continues from the file's current path +- `overwrite`: move the existing target to Trash first (logged, so undo + restores it), then proceed + +A `copy` whose target has identical content is skipped as "already there", +whatever the policy, so a backup rule can run every time. + +Conflicts between files in the same plan are resolved when planning, so the +plan shows final names. The executor re-checks at execution time; if the +name has to change, the log records the actual name. + +## 8. Plan, review, approval + +### 8.1 What is scanned + +- The root, recursively if `recursive yes`, to `max-depth`. +- Symlinks are never followed; symlinked files are skipped. +- `ignore` patterns use gitignore semantics: `*`, `**`, `?`, `[...]`; a + leading `/` anchors to the root; a trailing `/` matches directories only; + `!` re-includes; a pattern without `/` matches at any depth; the last + matching pattern wins. Ignored directories are not descended into. +- Always ignored: every rule `DEST` that lies inside the root, the Trash, and + the config directory. For a `DEST` with placeholders, the part before the + first placeholder is ignored: `Work/Acme/{mtime:%Y}` ignores `Work/Acme/`. +- Skipped as busy: files newer than `min-age`, or with a `busy` sibling. + +### 8.2 Display + +One directory at a time: + +``` +krino: downloads ~/downloads +266 scanned · 41 to act on · 2 warnings + + # file actions rule + 1 scan001.pdf move → Work/Acme/2026/ acme content "acme ltd" + 2 fv_123.pdf copy → ~/backup/invoices/2026/ backup content "invoice" + move → Work/Acme/2026/ acme name \bacme\b + 3 IMG_2031.JPG rename → 2026-09-01_IMG_2031.JPG photos type image + move → Photos/2026/ + 4 setup-1.2.deb DELETE permanently old-pkgs age 94d + 5 report (1).pdf trash (duplicate of Work/report.pdf) refiled + +warnings + brochure.doc content unreadable: antiword/catdoc not installed (rule acme) + big.pdf content unreadable: 120M > max-read 50M +not acted on: 3 busy · 12 ignored · 210 unmatched (-v lists them) + +[a] apply all [c] choose per file [s] skip this directory [q] quit +``` + +- Colours use the terminal's ANSI palette, only on a terminal, and never + when `NO_COLOR` is set. Permanent deletes are always marked in capitals. +- A plan taller than the terminal is shown through `$PAGER` (default + `less -FRX`) and the prompt follows when the pager exits. +- Keys are read one at a time without Enter. +- `[s]` applies nothing in this directory and moves on to the next one. + `[q]` stops krino; directories already applied in this run stay applied + and can be undone with `krino undo`. + +### 8.3 Choosing per file + +``` +[2/41] fv_123.pdf + copy → ~/backup/invoices/2026/ + move → Work/Acme/2026/ + [y] yes [n] no [a] yes to this and all remaining [d] done, apply chosen so far [q] quit, apply nothing +``` + +Approval is per file: the whole chain or none of it. + +### 8.4 Modes + +- default: plan, review, approve. +- `-y`: print the plan and apply everything. +- `-n`: print the plan and exit. `-n --json` prints it as JSON. +- If stdin is not a terminal and neither `-y` nor `-n` is given, krino + refuses rather than guess. + +## 9. Log + +Append-only, `$XDG_STATE_HOME/krino/krino.log`, one line per event, +tab-separated: + +``` +time run dir file step action status rule src dst size mtime detail +``` + +- `time`: RFC 3339 with offset. `run`: e.g. `20260911T100203-4f2a`. +- `action`: `run-start`, `mkdir`, `copy`, `move`, `rename`, `trash`, + `delete`, `displace` (a target trashed by `overwrite`), `run-end`, and the + `undo-` forms of each. +- `status`: `ok`, `failed`, `skipped`, `declined`. +- `size` and `mtime` describe the file at `dst` after the step, so undo can + tell whether it has been touched since. +- Fields are escaped: `\t`, `\n`, `\\`, and `\xNN` for control bytes and + bytes that are not valid UTF-8. Every file name round-trips exactly, and + the file stays readable with `grep` and `awk`. + +Dry runs are not logged. Files never acted on (unmatched, ignored, busy) are +not logged; declined files are. + +## 10. Undo + +- `krino log` lists recent runs: id, time, directories, counts. +- `krino undo` reverses the most recent run that has not been undone, in + every directory it touched; `krino undo RUN` a specific one. Undo runs + cannot themselves be undone. +- Undo builds a plan like any other, shown and approved the same way + (`-y` and `-n` apply). + +Reversals, last step first within each file: + +| Step | Reversal | Refused when | +|---|---|---| +| move, rename | move `dst` back to `src` | `dst` missing or changed (size/mtime), or `src` now exists | +| copy | move `dst` to Trash | `dst` missing or changed | +| trash | restore from Trash, remove the `.trashinfo` | the Trash entry is gone, or `src` now exists | +| displace | restore the displaced target from Trash | as above | +| mkdir | remove the directory if empty | not empty | +| delete permanent | none; reported as not undoable | always | + +If a reversal is refused, the earlier steps of that file's chain are not +reversed either, so no file is left half undone. Undo runs are logged like +any other run. + +## 11. Command line + +``` +krino [-y | -n] [-v] [--json] [-c FILE] [NAME...] + plan and apply every included directory, or only the named ones +krino init create ~/.config/krino with krino.conf and template.conf +krino new NAME PATH create dirs/NAME.conf from the template and include it +krino check [NAME...] validate config, list rules and available extractors +krino explain FILE evaluate every rule against FILE, show each test's result +krino log [-n N] list recent runs +krino undo [RUN] reverse a run (default: the last one) + +-y apply without asking +-n dry run: show the plan, change nothing +-v also list unmatched, ignored and busy files; full match reasons +--json with -n: the plan as JSON (format unstable before 1.0) +-c FILE use FILE instead of ~/.config/krino/krino.conf +-h, --help help +--version print "krino 0.0.1" +``` + +Exit status: 0 success, including nothing to do and everything declined; +1 one or more steps failed; 2 usage or config error; 130 interrupted. + +A config error anywhere stops the whole run before any scanning: krino never +acts on a config it only partly understood. Ctrl-C during apply finishes the +current step, logs it, and stops. A second krino on the same directory waits +for the lock, or fails immediately with `-y` (so a cron job never piles up). + +## 12. Architecture + +One binary, frontends kept thin. Everything the GUI will need lives in the +engine and returns data. + +``` +cmd/krino/ flags, subcommands, exit codes +internal/sexp/ reader: syntax tree with positions and byte offsets +internal/config/ syntax tree → typed config; validation; embedded template and defaults +internal/cond/ condition tree: compile, cost ordering, evaluation, explain trace +internal/scan/ walking, gitignore matcher, busy detection +internal/extract/ text extraction and normalisation +internal/dup/ duplicate index +internal/plan/ files × rules → chains; placeholders; conflicts; JSON +internal/apply/ executing approved steps; cross-filesystem moves +internal/trash/ freedesktop.org Trash +internal/journal/ log writer and reader, run ids, undo planning +internal/engine/ the facade: Load, Check, Plan, Apply, Explain, Runs, PlanUndo, NewDir, Init +internal/tui/ terminal rendering, pager, key prompts +``` + +Rules for the GUI to come: + +1. Every operation is an `engine` call that returns data. The CLI only + renders it. +2. `Apply` takes a plan plus the set of approved files. The CLI's `a` and `c` + and a GUI's checkboxes are the same call. +3. The reader records byte offsets, so a GUI can replace one form's text and + leave the rest of the file, comments included, untouched. +4. `Explain` returns the condition tree with each test's value. +5. Log and undo are in the engine. + +## 13. Performance + +- The walk uses `os.ReadDir` and prunes ignored directories. +- Files are evaluated by a pool of `GOMAXPROCS` workers. `pdftotext` and the + other tools run in parallel within that bound. +- Cheap tests first; content only when reached; content at most once. +- Keywords are normalised once at load time; matching is `strings.Contains` + per keyword on normalised text. Aho-Corasick only if a benchmark shows + keyword matching matters next to extraction. +- Duplicates: stat-only grouping, partial hash, then full hash. +- Measured before release on a real downloads directory of a few hundred + files, about half of them PDFs, and reported in the release notes. Goal: a + full plan with content rules in under 2 s on a 4-core laptop. `make bench` + runs the Go benchmarks on generated trees. + +## 14. Build, dependencies, release + +- Go 1.24 or newer. `CGO_ENABLED=0`: static binaries. +- Go dependencies: `golang.org/x/term` (key-at-a-time input) and + `golang.org/x/text` (Unicode normalisation for `fold`). Everything else is + the standard library, including the s-expression reader and the gitignore + matcher. +- `make` builds; Go downloads the module dependencies itself. It then checks + for the optional extractors and prints what is missing. +- `make deps` installs the extractors with the system package manager, + asking for privileges: `apt-get install poppler-utils catdoc antiword` + (Debian, Devuan), `pkg install poppler-utils antiword` (FreeBSD; catdoc is + left out because it pulls in tcl/tk), `pkg_add poppler-utils catdoc antiword` + (OpenBSD). Plain `make` never asks for privileges. +- Targets: `help build install uninstall test vet fmt lint ci bench cross + release deps install-hooks`. `install` puts the binary in + `$PREFIX/bin` (default `~/.local`), man pages in `$PREFIX/share/man`, + examples in `$PREFIX/share/doc/krino/examples`. +- `make cross`: linux/amd64, linux/arm64, freebsd/amd64, openbsd/amd64. +- `make release VERSION=0.0.1`: runs `ci` and `cross`, writes tarballs and + `SHA256SUMS` into `dist/`, and creates the annotated tag **`v0.0.1`** (the + `v` is required for `go install ...@v0.0.1`). It never pushes. +- Version stamped with `-ldflags -X main.version=...`. +- `scripts/leak-check` keeps personal data out of the repository. `make ci` + runs it, and so does the pre-commit hook that `make install-hooks` + installs. It checks the staged files against built-in patterns (the + current user's home directory, email addresses) and against a private + pattern list whose path is set with `git config krino.leakpatterns FILE`. + The list lives outside the repository, so the secrets it names are never + published either. Without it, only the built-in patterns run. +- `/local/` is ignored by git: a place for personal configs and test data + next to the code. + +Repository contents for 0.0.1: `README.md` (60-second quickstart), +`LICENSE`, `CHANGELOG.md`, `Makefile`, `go.mod`, `cmd/`, `internal/`, `scripts/`, +`man/krino.1`, `man/krino.conf.5`, `docs/design.md`, +`docs/sexp-primer.md`, `examples/` (by type, invoices by tax number with +placeholder numbers, screenshots by date, cleaning up old installers), +`testdata/`. + +## 15. Testing + +- **Unit tests** per package, table-driven. +- **sexp:** positions and offsets (every list's offsets point at its own + parentheses), error positions, and a fuzz target for the reader. +- **gitignore:** an oracle test that builds trees and compares every + path against `git check-ignore --no-index` (skipped if git is absent). +- **Conditions:** truth tables; a property test that random condition trees + give the same result with and without cost reordering. +- **Extraction:** small fixtures in `testdata/` for each format; PDF and + legacy-format tests skip when the tool is missing. +- **Plan, apply, undo:** in temporary directories: build a tree, plan, + apply, check; undo; check the tree is identical to the start (paths, + contents, modes, mtimes). A cross-filesystem move test runs when a tmpfs is + available on a different device, and skips otherwise. +- **Trash:** with `XDG_DATA_HOME` pointed at a temporary directory. +- **CLI:** golden files for plan rendering without colour; exit codes. +- **Parity check before release:** run `krino -n` beside the prototype's + dry run over the same real directory, and explain every difference. The + rules and the results stay outside the repository. + +`make ci` is the gate: gofmt, vet, tests, the leak check, man page lint. + +## 16. Lessons from the prototype + +krino replaces a Python prototype that sorted a downloads folder by +keyword. Its defects shaped these decisions: + +| Prototype | krino | +|---|---| +| filename keywords were substrings, so a short keyword matched inside unrelated words (`"art"` matched `start.pdf`) | name tests are regexes, e.g. `\bart\b` | +| `.doc` and `.xls` content was never read (the libraries do not support those formats) | antiword or catdoc, or a warning | +| code files were listed as supported, but their content was never read | any text file is read | +| the rules lived in the repository beside the code | rules live in `~/.config/krino`, never in the repository (§14 leak check) | +| it installed Python packages with `pip --break-system-packages` | a static binary; system packages via `make deps` | + +## 17. Decisions and why + +| Decision | Why | +|---|---| +| Config in one central place | target directories stay clean; one place to back up; the tool never sorts its own config | +| Every matching rule runs, `(stop)` to end | chains like copy-then-move need it; `stop` gives first-match behaviour where wanted | +| Tests see the original file | the plan is fully known before approval, and files can be evaluated in parallel | +| s-expressions, not TOML, YAML or INI | conditions are the core of the config; in sexp they are structure rather than a string in a second language. No nested quoting (TOML's `'''` around single-quoted regexes), no precedence, actions in written order. YAML turns `*` and `!` in ignore patterns into syntax; INI has no standard escaping | +| `pdftotext` rather than a Go PDF library | best text quality of the open tools, fast, packaged on all three systems | +| Delete to Trash by default | recoverable, and undo can restore it | +| A new repository rather than the prototype's | the prototype's history holds personal data; the prototype keeps working until krino reaches parity | +| Personal configuration never enters the repository | rules hold private data; the leak check enforces it on every commit and in `make ci` | + +## 18. Settled before implementation + +1. **Hosting: local only for now.** The module path is `krino`. When a + remote is chosen, `go mod edit -module <path>` and one `sed` over the + `"krino/internal/...` imports rename it; nothing else depends on it. + `go install ...@v0.0.1` works only after that. +2. **License: GPL-3.0-or-later.** Full text in `LICENSE`; every source file + carries `// SPDX-License-Identifier: GPL-3.0-or-later`. + +## Appendix A: type groups + +| Group | Extensions | +|---|---| +| `image` | jpg jpeg png gif webp bmp tif tiff heic heif avif svg ico raw cr2 nef arw dng | +| `video` | mp4 mkv webm mov avi m4v mpg mpeg wmv flv 3gp | +| `audio` | mp3 flac ogg opus m4a aac wav wma aiff | +| `archive` | zip tar gz tgz bz2 tbz2 xz txz zst 7z rar lz lzma cpio | +| `document` | pdf doc docx odt rtf txt md tex | +| `spreadsheet` | xls xlsx ods csv tsv | +| `presentation` | ppt pptx odp | +| `ebook` | epub mobi azw azw3 fb2 djvu | +| `code` | go c h cpp hpp py sh js ts rs java rb pl lua html css json yaml yml toml xml sql | +| `text` | txt md log csv tsv json yaml yml toml xml ini conf | +| `package` | deb rpm apk appimage exe msi flatpak snap | +| `font` | ttf otf woff woff2 | + +Groups overlap; a file can belong to several. diff --git a/docs/sexp-primer.md b/docs/sexp-primer.md new file mode 100644 index 0000000..c72c1e1 --- /dev/null +++ b/docs/sexp-primer.md @@ -0,0 +1,300 @@ +# S-expressions: a primer for krino + +krino's configuration is written in **s-expressions**, the notation Lisp has +used since 1958. You do not need to know any Lisp to write a krino config. This +page teaches exactly the part of the notation krino uses, where it comes from, +and how to read a rule at a glance. It ends with exercises and a reading list. + +## 1. Two kinds of thing + +Everything in an s-expression is one of two things. + +An **atom** is a single word or value: + +```lisp +pdf ; a symbol: a bare word +30d ; also a symbol, krino reads it as "30 days" +"acme ltd" ; a string: anything in double quotes +``` + +A **list** is a pair of parentheses holding atoms or other lists, separated by +spaces: + +```lisp +(type pdf docx) +(move "Work/2026") +(when (type pdf) (size > 10M)) +``` + +That is the whole grammar. There are no commas, no semicolons between items, +no operators with special spelling, no indentation rules. Whitespace and line +breaks only separate things; you can lay a list out on one line or twenty. + +A `;` starts a comment that runs to the end of the line. By convention `;;` +begins a comment on its own line and `;` a comment after code. + +## 2. The first element says what to do + +In every list, the **first element names the operation** and the rest are +what it operates on: + +```lisp +(type pdf docx) ; operation: type arguments: pdf, docx +(move "Photos") ; operation: move argument: "Photos" +(and A B C) ; operation: and arguments: A, B, C +``` + +This is **prefix notation**: the operator comes before its operands. Ordinary +arithmetic is *infix* (`3 + 4`, operator in the middle). Prefix writes it +`(+ 3 4)`. + +Because the parentheses mark exactly where each list ends, an operator can +take any number of arguments. `(+ 1 2 3 4)` adds four numbers; `(and A B C)` +requires three conditions; `(type pdf docx odt)` accepts three extensions. +Infix cannot do that without repeating the operator: `1 + 2 + 3 + 4`. + +## 3. Where prefix notation comes from + +The Polish logician **Jan Łukasiewicz** introduced prefix notation in 1924, to +write logic without any parentheses at all: "I came upon the idea of a +parenthesis-free notation in 1924." It became known as **Polish notation**. + +The trick works when every operator takes a fixed number of operands. Then +the order alone determines the grouping: + +| Infix | Polish (prefix) | Reverse Polish (postfix) | +|-------------------|-----------------|--------------------------| +| `3 + 4` | `+ 3 4` | `3 4 +` | +| `(3 + 4) × 5` | `× + 3 4 5` | `3 4 + 5 ×` | +| `3 + (4 × 5)` | `+ 3 × 4 5` | `3 4 5 × +` | + +**Reverse Polish notation** puts the operator *after* its operands. It is how +stack calculators and the Unix `dc` calculator work. You can try it now: + +```sh +echo '3 4 + 5 * p' | dc # (3 + 4) × 5, prints 35 +echo '3 4 5 * + p' | dc # 3 + (4 × 5), prints 23 +``` + +(`p` tells `dc` to print the top of its stack.) + +Lisp's s-expressions are Polish notation **with the parentheses kept**. That +costs a few brackets and buys two things: operators may take any number of +arguments, and you can always see at a glance where an expression ends. + +## 4. Nesting + +A list can contain lists, to any depth. Read nested lists from the outside +in: the outer operation first, then each argument in turn. + +```lisp +(or (type image) (size > 10M)) +``` + +"**or** of two things: the file is an image; the file is bigger than 10 MB." + +```lisp +(and (type document) + (or (content "acme ltd") (name "\bacme\b")) + (not (name "^draft"))) +``` + +"**and** of three things: +1. the file is a document; +2. **or** of two things: its text mentions *acme ltd*; its name contains the word *acme*; +3. **not**: its name starts with *draft*." + +There is no precedence to remember. In infix, `A and B or C` could mean +`(A and B) or C` or `A and (B or C)`, and you have to know the rule. In an +s-expression you must write one or the other: + +```lisp +(or (and A B) C) ; (A and B) or C +(and A (or B C)) ; A and (B or C) +``` + +## 5. What a krino config looks like + +A krino config file is a sequence of lists. Each top-level list is a +**form**, and the first word of the form says what it sets: + +```lisp +;; ~/.config/krino/dirs/downloads.conf +(path "~/downloads") +(ignore "*.part" "*.aria2" ".*") + +(rule "acme" + (when (type document) + (or (content "acme ltd" "0000000000") + (name "\bacme\b"))) + (move "Work/Acme/{mtime:%Y}") + (stop)) +``` + +`(rule "acme" ...)` is a form whose first argument is the rule's name and +whose remaining arguments are more lists: `when` holds the condition, +`move` and `stop` are actions. The whole rule is itself just a list. + +Two krino conventions to know: + +- **`when` with several conditions means all of them.** The rule above + could have been written `(when (and (type document) (or ...)))`; the `and` + is implied. You need `and` only inside an `or` or a `not`. +- **Tests that take several arguments mean "any of them".** `(type pdf docx)` + is true for a PDF *or* a DOCX. `(content "a" "b")` is true if the text + contains *a* or *b*. For "all of", combine tests: `(content "a") (content "b")`. + +### Symbols or strings? + +Bare words (`pdf`, `yes`, `strict`, `>`, `30d`) are **symbols**. Paths, +keywords, rule names and regular expressions go in **double quotes**. If a +value could contain a space, a parenthesis, a `;` or a `"`, quote it. + +Inside a string, a backslash escapes only `"` and `\`. Every other backslash +is kept as written, so regular expressions need no doubling: + +```lisp +(name "\bacme\b") ; the regex \bacme\b, exactly as written +(content "say \"hello\"") ; the text: say "hello" +``` + +## 6. Translating ordinary logic + +| You mean | You write | +|--------------------------------------------------------|----------------------------------------------------| +| PDFs | `(type pdf)` | +| PDFs or Word files | `(type pdf docx)` | +| PDFs over 10 MB | `(type pdf) (size > 10M)` | +| images or anything over 1 GB | `(or (type image) (size > 1G))` | +| mentions "invoice" but not "draft" | `(content "invoice") (not (content "draft"))` | +| name starts with `IMG_`, in strict case | `(name "^IMG_")` plus `(case strict)` on the rule | +| a document, and either the name or the text says acme | `(type document) (or (name "acme") (content "acme"))` | + +(The left column of conditions all go inside `(when ...)`.) + +## 7. Common mistakes + +**Unbalanced parentheses.** Every `(` needs a `)`. krino reports the line +where an unclosed list *opened*, which is usually the rule that is broken: + +``` +downloads.conf:12:1: "(" never closed: (rule "acme" ...) +``` + +Count from the inside out, or let your editor do it (see below). + +**`not` takes exactly one condition.** To negate several, wrap them: +`(not (or A B))` means "neither A nor B". + +**A bare word where a string is needed.** `(move Work/Acme)` is a symbol with +a slash in it, which krino rejects for a path; write `(move "Work/Acme")`. + +**Forgetting the implied `and` is only at the top of `when`.** Inside `or`, +each argument is a separate alternative: +`(or (type pdf) (size > 1M))` is "PDF, or big", never "big PDF". + +## 8. Editor help + +Any editor with a Lisp mode matches parentheses and indents s-expressions. +krino's generated files start with lines that switch it on: + +```lisp +;; -*- mode: lisp -*- +;; vim: set ft=lisp : +``` + +In **vim**: `%` jumps between matching parentheses; `:set showmatch` flashes +the partner of each `)` you type; `=` re-indents a selection using Lisp rules. +In **Emacs**: `C-M-f` / `C-M-b` move over a whole list; `C-M-q` re-indents it. + +## 9. Exercises + +1. Write `(2 + 3) × 4` as an s-expression, in Polish notation, and as a `dc` + command. Check the `dc` one in your shell. +2. Write the condition: "videos or audio files older than a year". +3. Write the condition: "spreadsheets that mention *budget* but not *draft*". +4. Find the mistake: `(when (and (type pdf) (content "invoice"))` +5. Do these mean the same? `(or (and A B) C)` and `(and A (or B C))` +6. Write a rule named `screenshots` that moves PNG files whose name starts + with `Screenshot` into `Pictures/Screenshots`, and stops. + +### Answers + +1. `(* (+ 2 3) 4)`; `* + 2 3 4`; `echo '2 3 + 4 * p' | dc` prints `20`. +2. `(when (type video audio) (age > 365d))`. One `type` with two groups + already means "either". +3. `(when (type spreadsheet) (content "budget") (not (content "draft")))` +4. One `)` is missing at the end: the `when` list is never closed. Count: + `(when` opens 1, `(and` 2, `(type` 3 closes to 2, `(content` 3 closes to + 2, and the final `)` closes `and`, leaving `when` open. +5. No. Take A false, C true: the first is true (because of C), the second is + false (because A is false). +6. ```lisp + (rule "screenshots" + (when (type png) (name "^Screenshot")) + (move "Pictures/Screenshots") + (stop)) + ``` + +## 10. Further reading + +All links checked on 2026-09-11. + +**Start here** + +- Paul Graham, *The Roots of Lisp* (2002). A short essay that rebuilds Lisp + from seven primitive operators; the clearest explanation of why + s-expressions are both code and data. + <https://www.paulgraham.com/rootsoflisp.html> +- Wikipedia, *S-expression* and *Polish notation*. + <https://en.wikipedia.org/wiki/S-expression>, + <https://en.wikipedia.org/wiki/Polish_notation> +- *Learn X in Y minutes: Scheme*. One page of syntax. + <https://learnxinyminutes.com/scheme/> + +**Learn to think in s-expressions** + +- Daniel P. Friedman and Matthias Felleisen, *The Little Schemer*, 4th ed., + MIT Press, 1995, ISBN 978-0-262-56099-3. Written entirely as questions and + answers; the gentlest route. +- Matthias Felleisen, Robert Bruce Findler, Matthew Flatt, Shriram + Krishnamurthi, *How to Design Programs*, 2nd ed. A free beginner course. + <https://htdp.org/> +- Harold Abelson and Gerald Jay Sussman, *Structure and Interpretation of + Computer Programs*, 2nd ed. Chapter 1 is enough for this purpose. Free HTML + edition: <https://sarabander.github.io/sicp/> +- Robert J. Chassell, *An Introduction to Programming in Emacs Lisp*. Also + available as `info eintr` where Emacs is installed. + <https://www.gnu.org/software/emacs/manual/html_node/eintr/> +- Peter Seibel, *Practical Common Lisp* (2005). Chapter 3 builds a small + database out of s-expressions, close in spirit to a krino config. + <https://gigamonkeys.com/book/> +- Daniel Higginbotham, *Clojure for the Brave and True*. A modern Lisp. + <https://www.braveclojure.com/> + +**Try it interactively** + +- GNU Guile (Scheme). Debian: `guile-3.0`; OpenBSD: `guile3`; FreeBSD: + `pkg search guile`. <https://www.gnu.org/software/guile/manual/> +- Racket. Debian: `racket`; OpenBSD: `racket-minimal`. + <https://docs.racket-lang.org/guide/> +- `dc(1)` for reverse Polish notation: `man dc`. + +**Build one** + +The fastest way to understand a notation is to write a parser for it. + +- Daniel Holden, *Build Your Own Lisp*. A Lisp in C, parser included. + <https://buildyourownlisp.com/> +- *mal: Make a Lisp*. A step-by-step guide with implementations in dozens of + languages, Go among them. <https://github.com/kanaka/mal> + +**Original sources** + +- John McCarthy, "Recursive Functions of Symbolic Expressions and Their + Computation by Machine, Part I", *Communications of the ACM*, 1960. The + paper that defined s-expressions. + <http://www-formal.stanford.edu/jmc/recursive.html> +- R. Rivest and D. Eastlake 3rd, RFC 9804, *Simple Public Key Infrastructure + (SPKI) S-Expressions* (2025). S-expressions specified as a data format. + <https://www.rfc-editor.org/rfc/rfc9804> @@ -0,0 +1,3 @@ +module krino + +go 1.24 diff --git a/internal/config/diag.go b/internal/config/diag.go new file mode 100644 index 0000000..5cee428 --- /dev/null +++ b/internal/config/diag.go @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +// Package config reads krino's configuration: the main file krino.conf and +// one file per directory under dirs/. It checks everything it reads and +// reports every problem with its position. +package config + +import ( + "fmt" + + "krino/internal/sexp" +) + +// Diag is one problem in a config file. +type Diag struct { + File string + Pos sexp.Pos + Msg string +} + +func (d *Diag) Error() string { + if d.Pos.Line == 0 { + return fmt.Sprintf("%s: %s", d.File, d.Msg) + } + return fmt.Sprintf("%s:%d:%d: %s", d.File, d.Pos.Line, d.Pos.Col, d.Msg) +} + +// diags collects the problems found in one file. +type diags struct { + file string + list []*Diag +} + +// at records a problem at n's position; a nil n means the whole file. +func (d *diags) at(n *sexp.Node, format string, args ...any) { + var pos sexp.Pos + if n != nil { + pos = n.Pos + } + d.list = append(d.list, &Diag{File: d.file, Pos: pos, Msg: fmt.Sprintf(format, args...)}) +} diff --git a/internal/config/dir.go b/internal/config/dir.go new file mode 100644 index 0000000..74c538a --- /dev/null +++ b/internal/config/dir.go @@ -0,0 +1,243 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package config + +import ( + "fmt" + "path/filepath" + "strings" + + "krino/internal/sexp" + "krino/internal/xdg" +) + +// Dir is one directory's config, dirs/<name>.conf. +type Dir struct { + Name string + File string + Path string // absolute and cleaned + PathText string // as written in the file + Settings Settings + Ignore []string // gitignore patterns, in order + Rules []*Rule +} + +// Rule is a named condition with the actions it performs. +type Rule struct { + Name string + Pos sexp.Pos + When []*sexp.Node // the conditions, all of which must hold + HasWhen bool // false: the rule matches every file + Settings Settings // only case, fold and on-conflict + Actions []Action // in the order written + Stop bool +} + +// ActionKind is what an action does. +type ActionKind int + +const ( + Copy ActionKind = iota + Move + Rename + Delete // to the Trash + DeletePermanent // unlink +) + +func (k ActionKind) String() string { + switch k { + case Copy: + return "copy" + case Move: + return "move" + case Rename: + return "rename" + case Delete: + return "delete" + case DeletePermanent: + return "delete permanent" + } + return fmt.Sprintf("ActionKind(%d)", int(k)) +} + +// Action is one step of a rule. +type Action struct { + Kind ActionKind + Arg string // the directory of copy and move, the new name of rename + Pos sexp.Pos +} + +// ParseDir reads the text of dirs/<name>.conf. +func ParseDir(name, file string, src []byte) (*Dir, []*Diag) { + dir := &Dir{Name: name, File: file} + nodes, err := sexp.Parse(file, src) + if err != nil { + return dir, []*Diag{fromSyntax(err)} + } + d := &diags{file: file} + var pathNode *sexp.Node + seen := map[string]*sexp.Node{} + rules := map[string]*Rule{} + for _, n := range nodes { + switch head := n.Head(); { + case head == "": + d.at(n, "expected a form like (rule ...), got %s", n) + case head == "path": + if pathNode != nil { + d.at(n, "path given twice (first at line %d)", pathNode.Pos.Line) + continue + } + pathNode = n + dir.parsePath(n, d) + case head == "ignore": + for _, a := range n.Args() { + if a.Kind != sexp.String { + d.at(a, `ignore takes patterns in quotes, like "*.part"; got %s`, a) + continue + } + dir.Ignore = append(dir.Ignore, a.Text) + } + case head == "rule": + r := parseRule(n, d) + if r == nil { + continue + } + if first, ok := rules[r.Name]; ok { + d.at(n, "rule %q defined twice (first at line %d)", r.Name, first.Pos.Line) + continue + } + rules[r.Name] = r + dir.Rules = append(dir.Rules, r) + case isSetting(head): + dir.Settings.parse(n, d, seen) + default: + d.at(n, "unknown form (%s ...); a directory file has path, ignore, rule and settings like (recursive yes)", head) + } + } + if pathNode == nil { + d.at(nil, "no (path ...): say which directory this file sorts") + } + return dir, d.list +} + +func (dir *Dir) parsePath(n *sexp.Node, d *diags) { + args := n.Args() + if len(args) == 1 && args[0].Kind == sexp.Symbol { + d.at(args[0], "path must be a string: write (path %s)", sexp.Quote(args[0].Text)) + return + } + if len(args) != 1 || args[0].Kind != sexp.String { + d.at(n, `path takes one directory in quotes, like (path "~/downloads")`) + return + } + p := xdg.Expand(args[0].Text) + if !filepath.IsAbs(p) { + d.at(args[0], "path must be absolute or start with ~, not %s", sexp.Quote(args[0].Text)) + return + } + dir.Path = filepath.Clean(p) + dir.PathText = args[0].Text +} + +var actionHeads = map[string]bool{"copy": true, "move": true, "rename": true, "delete": true} + +// parseRule reads (rule "NAME" ITEM...); nil if it has no usable name. +func parseRule(n *sexp.Node, d *diags) *Rule { + args := n.Args() + if len(args) == 0 || args[0].Kind != sexp.String || args[0].Text == "" { + d.at(n, `rule needs a name in quotes first, like (rule "invoices" ...)`) + return nil + } + r := &Rule{Name: args[0].Text, Pos: n.Pos} + seen := map[string]*sexp.Node{} + var whenNode *sexp.Node + triedAction, deleted := false, false + errorCount := len(d.list) + for _, item := range args[1:] { + switch head := item.Head(); { + case head == "": + d.at(item, "rule %q: expected a form like (when ...) or (move ...), got %s", r.Name, item) + case head == "when": + if whenNode != nil { + d.at(item, "rule %q: when given twice (first at line %d)", r.Name, whenNode.Pos.Line) + continue + } + whenNode = item + r.HasWhen = true + r.When = item.Args() + if len(r.When) == 0 { + d.at(item, "rule %q: (when) needs a condition; leave it out to match every file", r.Name) + } + for _, c := range r.When { + if c.Kind != sexp.List { + d.at(c, "rule %q: a condition is a form like (type pdf), not %s", r.Name, c) + } + } + case head == "stop": + if len(item.Args()) != 0 { + d.at(item, "rule %q: stop takes nothing: write (stop)", r.Name) + continue + } + r.Stop = true + case isSetting(head): + if !ruleSettings[head] { + d.at(item, "rule %q: %s cannot be set in a rule, only case, fold and on-conflict", r.Name, head) + continue + } + r.Settings.parse(item, d, seen) + case actionHeads[head]: + triedAction = true + a, ok := parseAction(r.Name, item, d) + if !ok { + continue + } + if deleted { + d.at(item, "rule %q: %s after delete would never run", r.Name, item) + continue + } + deleted = a.Kind == Delete || a.Kind == DeletePermanent + r.Actions = append(r.Actions, a) + default: + d.at(item, "rule %q: unknown form (%s ...); a rule has when, copy, move, rename, delete, stop, case, fold and on-conflict", r.Name, head) + triedAction = true + } + } + if !triedAction && !r.Stop && len(d.list) == errorCount { + d.at(n, `rule %q does nothing: give it an action like (move "Somewhere") or (stop)`, r.Name) + } + return r +} + +// parseAction reads one of copy, move, rename or delete. +func parseAction(rule string, n *sexp.Node, d *diags) (Action, bool) { + head, args := n.Head(), n.Args() + a := Action{Pos: n.Pos} + if head == "delete" { + switch { + case len(args) == 0: + a.Kind = Delete + case len(args) == 1 && args[0].Kind == sexp.Symbol && args[0].Text == "permanent": + a.Kind = DeletePermanent + default: + d.at(n, "rule %q: write (delete) for the Trash or (delete permanent)", rule) + return a, false + } + return a, true + } + if len(args) == 1 && args[0].Kind == sexp.Symbol { + d.at(args[0], "rule %q: %s takes a string: write (%s %s)", rule, head, head, sexp.Quote(args[0].Text)) + return a, false + } + what := map[string]string{"copy": "directory", "move": "directory", "rename": "new name"}[head] + if len(args) != 1 || args[0].Kind != sexp.String || args[0].Text == "" { + d.at(n, "rule %q: %s takes one %s in quotes", rule, head, what) + return a, false + } + a.Kind = map[string]ActionKind{"copy": Copy, "move": Move, "rename": Rename}[head] + a.Arg = args[0].Text + if a.Kind == Rename && strings.Contains(a.Arg, "/") { + d.at(args[0], "rule %q: rename gives a new name, not a path; use move to change directory", rule) + return a, false + } + return a, true +} diff --git a/internal/config/dir_test.go b/internal/config/dir_test.go new file mode 100644 index 0000000..7ddfa2a --- /dev/null +++ b/internal/config/dir_test.go @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package config + +import ( + "reflect" + "testing" +) + +const fullDir = `;; -*- mode: lisp -*- +(path "~/downloads") +(recursive yes) +(ignore "*.part" "*.aria2") +(ignore ".*") + +(rule "acme" + (when (type document) + (or (content "acme ltd") (name "\bacme\b"))) + (move "Work/Acme/{mtime:%Y}") + (stop)) + +(rule "photos" + (case strict) + (when (type image)) + (rename "{mtime:%Y-%m-%d}_{stem}{ext}") + (move "Photos")) + +(rule "old" (when (type package) (age > 30d)) (delete permanent)) +(rule "keep" (when (name "^important")) (stop)) +(rule "all" (copy "~/backup")) +` + +func kinds(r *Rule) []ActionKind { + var k []ActionKind + for _, a := range r.Actions { + k = append(k, a.Kind) + } + return k +} + +func TestParseDir(t *testing.T) { + t.Setenv("HOME", "/home/u") + dir, errs := ParseDir("downloads", "downloads.conf", []byte(fullDir)) + if len(errs) > 0 { + t.Fatal(errs) + } + if dir.Name != "downloads" || dir.Path != "/home/u/downloads" || dir.PathText != "~/downloads" { + t.Errorf("dir = %+v", dir) + } + if !reflect.DeepEqual(dir.Ignore, []string{"*.part", "*.aria2", ".*"}) { + t.Errorf("Ignore = %q", dir.Ignore) + } + if !dir.Settings.Over(Builtin()).Recursive { + t.Error("recursive not set") + } + if len(dir.Rules) != 5 { + t.Fatalf("got %d rules", len(dir.Rules)) + } + acme := dir.Rules[0] + if acme.Name != "acme" || !acme.Stop || !acme.HasWhen || len(acme.When) != 2 || acme.When[1].Head() != "or" { + t.Errorf("acme = %+v", acme) + } + if len(acme.Actions) != 1 || acme.Actions[0].Kind != Move || acme.Actions[0].Arg != "Work/Acme/{mtime:%Y}" { + t.Errorf("acme actions = %+v", acme.Actions) + } + photos := dir.Rules[1] + if photos.Settings.Over(Builtin()).Case != CaseStrict { + t.Error("photos: case strict not set") + } + if got := kinds(photos); !reflect.DeepEqual(got, []ActionKind{Rename, Move}) { + t.Errorf("photos actions = %v", got) + } + if got := kinds(dir.Rules[2]); !reflect.DeepEqual(got, []ActionKind{DeletePermanent}) { + t.Errorf("old actions = %v", got) + } + if keep := dir.Rules[3]; !keep.Stop || len(keep.Actions) != 0 { + t.Errorf("keep = %+v", keep) + } + if all := dir.Rules[4]; all.HasWhen || all.When != nil || all.Actions[0].Arg != "~/backup" { + t.Errorf("all = %+v", all) + } +} + +func TestActionKindString(t *testing.T) { + want := map[ActionKind]string{Copy: "copy", Move: "move", Rename: "rename", Delete: "delete", DeletePermanent: "delete permanent"} + for k, s := range want { + if k.String() != s { + t.Errorf("%d.String() = %q, want %q", k, k.String(), s) + } + } +} + +func TestParseDirErrors(t *testing.T) { + tests := []struct{ src, want string }{ + {``, `d.conf: no (path ...): say which directory this file sorts`}, + {`(path ~/x)`, `d.conf:1:7: path must be a string: write (path "~/x")`}, + {`(path "rel")`, `d.conf:1:7: path must be absolute or start with ~, not "rel"`}, + {`(path "/a") (path "/b")`, `d.conf:1:13: path given twice (first at line 1)`}, + {`(path "/a") (ignore part)`, `d.conf:1:21: ignore takes patterns in quotes, like "*.part"; got part`}, + {`(path "/a") (rule x (stop))`, `d.conf:1:13: rule needs a name in quotes first, like (rule "invoices" ...)`}, + {`(path "/a") (rule "x" (stop)) (rule "x" (stop))`, `d.conf:1:31: rule "x" defined twice (first at line 1)`}, + {`(path "/a") (rule "x" (when (type pdf)))`, `d.conf:1:13: rule "x" does nothing: give it an action like (move "Somewhere") or (stop)`}, + {`(path "/a") (rule "x" (when) (stop))`, `d.conf:1:23: rule "x": (when) needs a condition; leave it out to match every file`}, + {`(path "/a") (rule "x" (when pdf) (stop))`, `d.conf:1:29: rule "x": a condition is a form like (type pdf), not pdf`}, + {`(path "/a") (rule "x" (when (a)) (when (b)) (stop))`, `d.conf:1:34: rule "x": when given twice (first at line 1)`}, + {`(path "/a") (rule "x" (recursive yes) (stop))`, `d.conf:1:23: rule "x": recursive cannot be set in a rule, only case, fold and on-conflict`}, + {`(path "/a") (rule "x" (move Work))`, `d.conf:1:29: rule "x": move takes a string: write (move "Work")`}, + {`(path "/a") (rule "x" (move))`, `d.conf:1:23: rule "x": move takes one directory in quotes`}, + {`(path "/a") (rule "x" (rename "a/b"))`, `d.conf:1:31: rule "x": rename gives a new name, not a path; use move to change directory`}, + {`(path "/a") (rule "x" (delete forever))`, `d.conf:1:23: rule "x": write (delete) for the Trash or (delete permanent)`}, + {`(path "/a") (rule "x" (delete) (move "y"))`, `d.conf:1:32: rule "x": (move "y") after delete would never run`}, + {`(path "/a") (rule "x" (stop now))`, `d.conf:1:23: rule "x": stop takes nothing: write (stop)`}, + {`(path "/a") (rule "x" (fly "y"))`, `d.conf:1:23: rule "x": unknown form (fly ...); a rule has when, copy, move, rename, delete, stop, case, fold and on-conflict`}, + {`(path "/a") (sort "x")`, `d.conf:1:13: unknown form (sort ...); a directory file has path, ignore, rule and settings like (recursive yes)`}, + } + for _, tt := range tests { + _, errs := ParseDir("d", "d.conf", []byte(tt.src)) + if len(errs) != 1 || errs[0].Error() != tt.want { + t.Errorf("%s:\n got %v\n want %s", tt.src, errs, tt.want) + } + } +} diff --git a/internal/config/load.go b/internal/config/load.go new file mode 100644 index 0000000..f6eaeae --- /dev/null +++ b/internal/config/load.go @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package config + +import ( + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + + "krino/internal/sexp" + "krino/internal/xdg" +) + +// Config is the whole configuration: the main file and the directories it +// includes. +type Config struct { + Main *Main + Dirs []*Dir +} + +// DefaultFile is krino.conf in the XDG config directory. +func DefaultFile() string { + return filepath.Join(xdg.ConfigHome(), "krino", "krino.conf") +} + +// DirFile is where directory name's config lives, beside the main file. +func DirFile(mainFile, name string) string { + return filepath.Join(filepath.Dir(mainFile), "dirs", name+".conf") +} + +// Load reads the main file and the files of the directories it includes. +// With names, only those directories are read, and each must be included. +// The Config is nil only when the main file itself cannot be read. +func Load(mainFile string, names ...string) (*Config, []*Diag) { + src, err := os.ReadFile(mainFile) + if errors.Is(err, fs.ErrNotExist) { + return nil, []*Diag{{File: mainFile, Msg: "not found; create it with: krino init"}} + } + if err != nil { + return nil, []*Diag{{File: mainFile, Msg: err.Error()}} + } + m, errs := ParseMain(mainFile, src) + cfg := &Config{Main: m} + if _, perr := sexp.Parse(mainFile, src); perr != nil { + // krino.conf itself is unreadable: report just that, and load none + // of the directories, so a syntax error never also produces + // "NAME is not in include" for names the caller asked for. + return cfg, errs + } + want := m.Include + if len(names) > 0 { + want = nil + for _, n := range names { + if _, ok := m.IncludePos[n]; !ok { + errs = append(errs, &Diag{File: mainFile, Msg: fmt.Sprintf("%q is not in include", n)}) + continue + } + want = append(want, n) + } + } + for _, name := range want { + file := DirFile(mainFile, name) + src, err := os.ReadFile(file) + if err != nil { + msg := err.Error() + if errors.Is(err, fs.ErrNotExist) { + msg = fmt.Sprintf("included %q, but %s does not exist; create it with: krino new %s PATH", name, file, name) + } + errs = append(errs, &Diag{File: mainFile, Pos: m.IncludePos[name], Msg: msg}) + continue + } + dir, derrs := ParseDir(name, file, src) + errs = append(errs, derrs...) + cfg.Dirs = append(cfg.Dirs, dir) + } + return cfg, errs +} + +// Resolved is the settings that apply in dir: built-in, then the main +// file's defaults, then the directory's own. +func (c *Config) Resolved(dir *Dir) Resolved { + return dir.Settings.Over(c.Main.Defaults.Over(Builtin())) +} + +// LogFile is the main file's (log ...), or the default under XDG_STATE_HOME. +func (c *Config) LogFile() string { + if c.Main.Log != "" { + return c.Main.Log + } + return filepath.Join(xdg.StateHome(), "krino", "krino.log") +} diff --git a/internal/config/load_test.go b/internal/config/load_test.go new file mode 100644 index 0000000..be72fc0 --- /dev/null +++ b/internal/config/load_test.go @@ -0,0 +1,106 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package config + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// writeFiles creates each file under root, making directories as needed. +func writeFiles(t *testing.T, root string, files map[string]string) { + t.Helper() + for name, body := range files { + p := filepath.Join(root, name) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } +} + +func TestLoad(t *testing.T) { + root := t.TempDir() + writeFiles(t, root, map[string]string{ + "krino.conf": `(include "a" "b") (defaults (min-age 5m))`, + "dirs/a.conf": `(path "/tmp/a") (min-age 1m) (rule "r" (stop))`, + "dirs/b.conf": `(path "/tmp/b") (rule "r" (stop))`, + }) + main := filepath.Join(root, "krino.conf") + cfg, errs := Load(main) + if len(errs) > 0 { + t.Fatal(errs) + } + if len(cfg.Dirs) != 2 || cfg.Dirs[0].Name != "a" || cfg.Dirs[1].Path != "/tmp/b" { + t.Fatalf("dirs = %+v", cfg.Dirs) + } + if got := cfg.Resolved(cfg.Dirs[0]).MinAge; got != time.Minute { + t.Errorf("a min-age = %v, want the directory's 1m", got) + } + if got := cfg.Resolved(cfg.Dirs[1]).MinAge; got != 5*time.Minute { + t.Errorf("b min-age = %v, want the default 5m", got) + } + cfg, errs = Load(main, "b") + if len(errs) > 0 || len(cfg.Dirs) != 1 || cfg.Dirs[0].Name != "b" { + t.Fatalf("Load(b) = %+v, %v", cfg, errs) + } +} + +func TestLoadErrors(t *testing.T) { + root := t.TempDir() + main := filepath.Join(root, "krino.conf") + cfg, errs := Load(main) + if cfg != nil || len(errs) != 1 || errs[0].Error() != main+": not found; create it with: krino init" { + t.Fatalf("missing main file: %v", errs) + } + writeFiles(t, root, map[string]string{"krino.conf": "(include \"gone\")\n"}) + _, errs = Load(main) + want := fmt.Sprintf(`%s:1:10: included "gone", but %s does not exist; create it with: krino new gone PATH`, + main, filepath.Join(root, "dirs", "gone.conf")) + if len(errs) != 1 || errs[0].Error() != want { + t.Fatalf("missing dir file:\n got %v\n want %s", errs, want) + } + _, errs = Load(main, "other") + if len(errs) != 1 || !strings.HasSuffix(errs[0].Error(), `: "other" is not in include`) { + t.Fatalf("unknown name: %v", errs) + } +} + +// TestLoadSyntaxErrorStopsAtOneDiag is item C: a krino.conf that fails to +// parse must report only the syntax error, not also "not in include" for +// names the caller asked for. +func TestLoadSyntaxErrorStopsAtOneDiag(t *testing.T) { + root := t.TempDir() + writeFiles(t, root, map[string]string{"krino.conf": `(include "dl"`}) + main := filepath.Join(root, "krino.conf") + _, errs := Load(main, "dl") + if len(errs) != 1 { + t.Fatalf("errs = %v, want exactly one diag", errs) + } + want := fmt.Sprintf(`%s:1:1: "(" never closed: (include "dl")`, main) + if errs[0].Error() != want { + t.Fatalf("got %s\nwant %s", errs[0], want) + } +} + +func TestDefaultFileAndLogFile(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", "/conf") + t.Setenv("XDG_STATE_HOME", "/state") + if got := DefaultFile(); got != "/conf/krino/krino.conf" { + t.Errorf("DefaultFile() = %q", got) + } + c := &Config{Main: &Main{}} + if got := c.LogFile(); got != "/state/krino/krino.log" { + t.Errorf("LogFile() = %q", got) + } + c.Main.Log = "/x.log" + if got := c.LogFile(); got != "/x.log" { + t.Errorf("LogFile() = %q", got) + } +} diff --git a/internal/config/main.go b/internal/config/main.go new file mode 100644 index 0000000..ee6c3df --- /dev/null +++ b/internal/config/main.go @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package config + +import ( + "errors" + "path/filepath" + "regexp" + + "krino/internal/sexp" + "krino/internal/xdg" +) + +// Main is krino.conf. +type Main struct { + File string + Include []string // directory names, in run order + IncludePos map[string]sexp.Pos // where each name is written + // IncludeNode is the (include ...) form, kept so krino new can splice a + // name into it; nil when the file has none. + IncludeNode *sexp.Node + Log string // absolute; empty means the default + Defaults Settings +} + +// nameRE is what a directory name may look like: it becomes a file name. +var nameRE = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`) + +// ParseMain reads the text of krino.conf. +func ParseMain(file string, src []byte) (*Main, []*Diag) { + m := &Main{File: file, IncludePos: map[string]sexp.Pos{}} + nodes, err := sexp.Parse(file, src) + if err != nil { + return m, []*Diag{fromSyntax(err)} + } + d := &diags{file: file} + seen := map[string]*sexp.Node{} + for _, n := range nodes { + head := n.Head() + if head == "" { + d.at(n, "expected a form like (include ...), got %s", n) + continue + } + if head == "include" || head == "log" || head == "defaults" { + if first, ok := seen[head]; ok { + d.at(n, "%s given twice (first at line %d)", head, first.Pos.Line) + continue + } + seen[head] = n + } + switch head { + case "include": + m.IncludeNode = n + for _, a := range n.Args() { + switch _, dup := m.IncludePos[a.Text]; { + case a.Kind != sexp.String: + d.at(a, `include takes directory names in quotes, like "downloads"; got %s`, a) + case !nameRE.MatchString(a.Text): + d.at(a, "bad directory name %q: use letters, digits, '.', '_' and '-'", a.Text) + case Reserved[a.Text]: + d.at(a, "%q is a krino command; choose another name", a.Text) + case dup: + d.at(a, "%q included twice", a.Text) + default: + m.Include = append(m.Include, a.Text) + m.IncludePos[a.Text] = a.Pos + } + } + case "log": + args := n.Args() + if len(args) != 1 || args[0].Kind != sexp.String { + d.at(n, `log takes one path in quotes, like (log "~/.local/state/krino/krino.log")`) + continue + } + p := xdg.Expand(args[0].Text) + if !filepath.IsAbs(p) { + d.at(args[0], "log path must be absolute or start with ~") + continue + } + m.Log = filepath.Clean(p) + case "defaults": + dseen := map[string]*sexp.Node{} + for _, a := range n.Args() { + if !isSetting(a.Head()) { + d.at(a, "defaults holds settings like (min-age 2m); got %s", a) + continue + } + m.Defaults.parse(a, d, dseen) + } + default: + d.at(n, "unknown form (%s ...); krino.conf has include, log and defaults", head) + } + } + return m, d.list +} + +// fromSyntax turns a reader error into a Diag. +func fromSyntax(err error) *Diag { + var se *sexp.Error + if errors.As(err, &se) { + return &Diag{File: se.File, Pos: se.Pos, Msg: se.Msg} + } + return &Diag{Msg: err.Error()} +} diff --git a/internal/config/main_test.go b/internal/config/main_test.go new file mode 100644 index 0000000..a82dfcd --- /dev/null +++ b/internal/config/main_test.go @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package config + +import ( + "reflect" + "testing" + "time" +) + +func TestParseMain(t *testing.T) { + t.Setenv("HOME", "/home/u") + src := `;; comment +(include "downloads" "docs") +(log "~/state/krino.log") +(defaults (min-age 5m) (case strict)) +` + m, errs := ParseMain("krino.conf", []byte(src)) + if len(errs) > 0 { + t.Fatal(errs) + } + if !reflect.DeepEqual(m.Include, []string{"downloads", "docs"}) { + t.Errorf("Include = %q", m.Include) + } + if m.IncludePos["docs"].Line != 2 { + t.Errorf("docs at %+v", m.IncludePos["docs"]) + } + if m.Log != "/home/u/state/krino.log" { + t.Errorf("Log = %q", m.Log) + } + if r := m.Defaults.Over(Builtin()); r.MinAge != 5*time.Minute || r.Case != CaseStrict { + t.Errorf("defaults = %+v", r) + } + if m.IncludeNode == nil || src[m.IncludeNode.End.Offset-1] != ')' { + t.Errorf("IncludeNode = %+v", m.IncludeNode) + } +} + +func TestParseMainEmptyInclude(t *testing.T) { + m, errs := ParseMain("k", []byte("(include)")) + if len(errs) > 0 || len(m.Include) != 0 || m.IncludeNode == nil { + t.Fatalf("m = %+v, errs = %v", m, errs) + } +} + +func TestParseMainErrors(t *testing.T) { + tests := []struct{ src, want string }{ + {`(include downloads)`, `k:1:10: include takes directory names in quotes, like "downloads"; got downloads`}, + {`(include "a/b")`, `k:1:10: bad directory name "a/b": use letters, digits, '.', '_' and '-'`}, + {`(include "check")`, `k:1:10: "check" is a krino command; choose another name`}, + {`(include "a" "a")`, `k:1:14: "a" included twice`}, + {`(include "a") (include "b")`, `k:1:15: include given twice (first at line 1)`}, + {`(log)`, `k:1:1: log takes one path in quotes, like (log "~/.local/state/krino/krino.log")`}, + {`(log "rel/x")`, `k:1:6: log path must be absolute or start with ~`}, + {`(defaults (recursive maybe))`, `k:1:22: recursive is yes or no, not maybe`}, + {`(defaults (rule "x"))`, `k:1:11: defaults holds settings like (min-age 2m); got (rule "x")`}, + {`(inlcude "a")`, `k:1:1: unknown form (inlcude ...); krino.conf has include, log and defaults`}, + {`include`, `k:1:1: expected a form like (include ...), got include`}, + {`(include "a"`, `k:1:1: "(" never closed: (include "a")`}, + } + for _, tt := range tests { + _, errs := ParseMain("k", []byte(tt.src)) + if len(errs) != 1 || errs[0].Error() != tt.want { + t.Errorf("%s:\n got %v\n want %s", tt.src, errs, tt.want) + } + } +} diff --git a/internal/config/settings.go b/internal/config/settings.go new file mode 100644 index 0000000..97355a5 --- /dev/null +++ b/internal/config/settings.go @@ -0,0 +1,204 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package config + +import ( + "slices" + "time" + + "krino/internal/sexp" +) + +// CaseMode says whether name, path and content matching ignores case. +type CaseMode int + +const ( + CaseIgnore CaseMode = iota + CaseStrict +) + +// Conflict is what to do when an action's target already exists. +type Conflict int + +const ( + ConflictSuffix Conflict = iota + ConflictSkip + ConflictOverwrite +) + +// Settings holds what one level of config sets; nil means not set there. +type Settings struct { + Case *CaseMode + Fold *bool + Recursive *bool + MaxDepth *int + MinAge *time.Duration + MaxRead *int64 + Busy *[]string + OnConflict *Conflict +} + +// Resolved is a complete set of settings. +type Resolved struct { + Case CaseMode + Fold bool + Recursive bool + MaxDepth int // 0 means unlimited + MinAge time.Duration + MaxRead int64 + Busy []string + OnConflict Conflict +} + +// Builtin is what applies when nothing is set. +func Builtin() Resolved { + return Resolved{ + Case: CaseIgnore, + Fold: true, + MinAge: 2 * time.Minute, + MaxRead: 50 << 20, + Busy: []string{".part", ".aria2", ".crdownload"}, + OnConflict: ConflictSuffix, + } +} + +// Over returns base with every setting that s sets replaced. +func (s Settings) Over(base Resolved) Resolved { + r := base + if s.Case != nil { + r.Case = *s.Case + } + if s.Fold != nil { + r.Fold = *s.Fold + } + if s.Recursive != nil { + r.Recursive = *s.Recursive + } + if s.MaxDepth != nil { + r.MaxDepth = *s.MaxDepth + } + if s.MinAge != nil { + r.MinAge = *s.MinAge + } + if s.MaxRead != nil { + r.MaxRead = *s.MaxRead + } + if s.Busy != nil { + r.Busy = *s.Busy + } + if s.OnConflict != nil { + r.OnConflict = *s.OnConflict + } + return r +} + +var settingNames = []string{"case", "fold", "recursive", "max-depth", "min-age", "max-read", "busy", "on-conflict"} + +// ruleSettings are the settings a rule may override. +var ruleSettings = map[string]bool{"case": true, "fold": true, "on-conflict": true} + +func isSetting(name string) bool { return slices.Contains(settingNames, name) } + +var settingHint = map[string]string{ + "case": "(case ignore) or (case strict)", + "fold": "(fold yes) or (fold no)", + "recursive": "(recursive yes) or (recursive no)", + "max-depth": "a number, like (max-depth 3)", + "min-age": "a duration, like (min-age 2m)", + "max-read": "a size, like (max-read 50M)", + "on-conflict": "(on-conflict suffix), skip or overwrite", +} + +// parse reads the setting form n into s, reporting problems to d. seen +// catches a setting given twice at the same level. +func (s *Settings) parse(n *sexp.Node, d *diags, seen map[string]*sexp.Node) { + name := n.Head() + if first, ok := seen[name]; ok { + d.at(n, "%s set twice (first at line %d)", name, first.Pos.Line) + return + } + seen[name] = n + args := n.Args() + if name == "busy" { + list := []string{} + for _, a := range args { + if a.Kind != sexp.String { + d.at(a, `busy takes strings, like ".part"; got %s`, a) + continue + } + list = append(list, a.Text) + } + s.Busy = &list + return + } + if len(args) == 1 && args[0].Kind == sexp.String { + d.at(args[0], "%s values are bare words: write (%s %s)", name, name, args[0].Text) + return + } + if len(args) != 1 || args[0].Kind != sexp.Symbol { + d.at(n, "%s takes one value: %s", name, settingHint[name]) + return + } + v, at := args[0].Text, args[0] + switch name { + case "case": + switch v { + case "ignore": + c := CaseIgnore + s.Case = &c + case "strict": + c := CaseStrict + s.Case = &c + default: + d.at(at, "case is ignore or strict, not %s", v) + } + case "fold", "recursive": + b, ok := yesNo(v) + if !ok { + d.at(at, "%s is yes or no, not %s", name, v) + } else if name == "fold" { + s.Fold = &b + } else { + s.Recursive = &b + } + case "max-depth": + depth, err := parseCount(v) + if err != nil || depth < 1 || depth > 1<<20 { + d.at(at, "max-depth is a whole number from 1, not %s", v) + return + } + i := int(depth) + s.MaxDepth = &i + case "min-age": + dur, err := ParseDuration(v) + if err != nil { + d.at(at, "min-age: %v", err) + return + } + s.MinAge = &dur + case "max-read": + size, err := ParseSize(v) + if err != nil { + d.at(at, "max-read: %v", err) + return + } + s.MaxRead = &size + case "on-conflict": + c, ok := map[string]Conflict{"suffix": ConflictSuffix, "skip": ConflictSkip, "overwrite": ConflictOverwrite}[v] + if !ok { + d.at(at, "on-conflict is suffix, skip or overwrite, not %s", v) + return + } + s.OnConflict = &c + } +} + +func yesNo(v string) (bool, bool) { + switch v { + case "yes": + return true, true + case "no": + return false, true + } + return false, false +} diff --git a/internal/config/settings_test.go b/internal/config/settings_test.go new file mode 100644 index 0000000..e46c880 --- /dev/null +++ b/internal/config/settings_test.go @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package config + +import ( + "reflect" + "testing" + "time" + + "krino/internal/sexp" +) + +func parseSettings(t *testing.T, src string) (Settings, []*Diag) { + t.Helper() + nodes, err := sexp.Parse("s.conf", []byte(src)) + if err != nil { + t.Fatal(err) + } + var s Settings + d := &diags{file: "s.conf"} + seen := map[string]*sexp.Node{} + for _, n := range nodes { + s.parse(n, d, seen) + } + return s, d.list +} + +func TestSettingsResolve(t *testing.T) { + s, errs := parseSettings(t, `(case strict) (fold no) (recursive yes) (max-depth 3) + (min-age 5m) (max-read 1G) (busy ".tmp") (on-conflict skip)`) + if len(errs) > 0 { + t.Fatal(errs) + } + want := Resolved{Case: CaseStrict, Fold: false, Recursive: true, MaxDepth: 3, + MinAge: 5 * time.Minute, MaxRead: 1 << 30, Busy: []string{".tmp"}, OnConflict: ConflictSkip} + if got := s.Over(Builtin()); !reflect.DeepEqual(got, want) { + t.Fatalf("got %+v\nwant %+v", got, want) + } +} + +func TestBuiltin(t *testing.T) { + want := Resolved{Case: CaseIgnore, Fold: true, MinAge: 2 * time.Minute, MaxRead: 50 << 20, + Busy: []string{".part", ".aria2", ".crdownload"}, OnConflict: ConflictSuffix} + if got := Builtin(); !reflect.DeepEqual(got, want) { + t.Fatalf("got %+v\nwant %+v", got, want) + } +} + +func TestSettingsLayering(t *testing.T) { + defaults, _ := parseSettings(t, `(min-age 5m) (fold no)`) + dir, _ := parseSettings(t, `(fold yes)`) + got := dir.Over(defaults.Over(Builtin())) + if got.MinAge != 5*time.Minute || !got.Fold || got.MaxRead != 50<<20 { + t.Fatalf("got %+v", got) + } +} + +func TestBusyEmptyDisables(t *testing.T) { + s, errs := parseSettings(t, `(busy)`) + if len(errs) > 0 || s.Busy == nil { + t.Fatalf("errs %v, busy %v", errs, s.Busy) + } + if got := s.Over(Builtin()).Busy; len(got) != 0 { + t.Fatalf("busy = %v, want none", got) + } +} + +func TestSettingErrors(t *testing.T) { + tests := []struct{ src, want string }{ + {`(case loud)`, `s.conf:1:7: case is ignore or strict, not loud`}, + {`(case "ignore")`, `s.conf:1:7: case values are bare words: write (case ignore)`}, + {`(fold)`, `s.conf:1:1: fold takes one value: (fold yes) or (fold no)`}, + {`(max-depth 0)`, `s.conf:1:12: max-depth is a whole number from 1, not 0`}, + {`(min-age soon)`, `s.conf:1:10: min-age: bad duration "soon": want a whole number followed by s, m, h, d or w, like 30d`}, + {`(max-read 5m)`, `s.conf:1:11: max-read: bad size "5m": want a whole number with an optional K, M, G or T, like 50M`}, + {`(busy part)`, `s.conf:1:7: busy takes strings, like ".part"; got part`}, + {`(fold yes) (fold no)`, `s.conf:1:12: fold set twice (first at line 1)`}, + } + for _, tt := range tests { + _, errs := parseSettings(t, tt.src) + if len(errs) != 1 || errs[0].Error() != tt.want { + t.Errorf("%s:\n got %v\n want %s", tt.src, errs, tt.want) + } + } +} diff --git a/internal/config/skel.go b/internal/config/skel.go new file mode 100644 index 0000000..65d9f95 --- /dev/null +++ b/internal/config/skel.go @@ -0,0 +1,186 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package config + +import ( + "bytes" + _ "embed" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + + "krino/internal/sexp" + "krino/internal/xdg" +) + +//go:embed skel/krino.conf +var skelMain []byte + +//go:embed skel/template.conf +var skelTemplate []byte + +// Reserved are subcommand names; a directory with one of them could not be +// run by name. +var Reserved = map[string]bool{"init": true, "new": true, "check": true, "explain": true, "log": true, "undo": true} + +// Init creates the directory holding mainFile with a commented krino.conf and +// template.conf, and a dirs/ directory. It never overwrites krino.conf, and +// keeps an existing template.conf. It returns the files it created. +func Init(mainFile string) ([]string, error) { + dir := filepath.Dir(mainFile) + if err := os.MkdirAll(dir, 0o755); err != nil { + return nil, err + } + if err := writeNew(mainFile, skelMain); errors.Is(err, fs.ErrExist) { + return nil, fmt.Errorf("%s already exists; krino init leaves it alone", mainFile) + } else if err != nil { + return nil, err + } + created := []string{mainFile} + if err := os.MkdirAll(filepath.Join(dir, "dirs"), 0o755); err != nil { + return created, err + } + tmpl := filepath.Join(dir, "template.conf") + switch err := writeNew(tmpl, skelTemplate); { + case err == nil: + created = append(created, tmpl) + case !errors.Is(err, fs.ErrExist): + return created, err + } + return created, nil +} + +// NewDir creates dirs/<name>.conf from template.conf with the path filled +// in, and adds name to include in mainFile without changing anything else +// there. It returns the new file's path. +func NewDir(mainFile, name, path string) (string, error) { + if !nameRE.MatchString(name) { + return "", fmt.Errorf("bad directory name %q: use letters, digits, '.', '_' and '-'", name) + } + if Reserved[name] { + return "", fmt.Errorf("%q is a krino command; choose another name", name) + } + abs, err := filepath.Abs(xdg.Expand(path)) + if err != nil { + return "", err + } + if fi, err := os.Stat(abs); err != nil || !fi.IsDir() { + return "", fmt.Errorf("%s is not a directory", abs) + } + src, err := os.ReadFile(mainFile) + if errors.Is(err, fs.ErrNotExist) { + return "", fmt.Errorf("%s not found; create it with: krino init", mainFile) + } else if err != nil { + return "", err + } + m, errs := ParseMain(mainFile, src) + if len(errs) > 0 { + return "", fmt.Errorf("fix %s first: %v", mainFile, errs[0]) + } + if _, ok := m.IncludePos[name]; ok { + return "", fmt.Errorf("%q is already included", name) + } + tmplPath := filepath.Join(filepath.Dir(mainFile), "template.conf") + tmpl, err := os.ReadFile(tmplPath) + if errors.Is(err, fs.ErrNotExist) { + tmpl, err = skelTemplate, nil + } + if err != nil { + return "", err + } + file := DirFile(mainFile, name) + body := bytes.ReplaceAll(tmpl, []byte(`"@PATH@"`), []byte(sexp.Quote(xdg.Abbrev(abs)))) + newDir, derrs := ParseDir(name, file, body) + if len(derrs) > 0 { + return "", fmt.Errorf("template.conf is broken: %v", derrs[0]) + } + if newDir.Path != abs { + return "", fmt.Errorf("%s must contain (path \"@PATH@\")", tmplPath) + } + newMain := addInclude(src, m, name) + if _, errs := ParseMain(mainFile, newMain); len(errs) > 0 { + return "", fmt.Errorf("could not add %q to include: %v", name, errs[0]) + } + if err := os.MkdirAll(filepath.Dir(file), 0o755); err != nil { + return "", err + } + if err := writeNew(file, body); errors.Is(err, fs.ErrExist) { + return "", fmt.Errorf("%s already exists", file) + } else if err != nil { + return "", err + } + if err := replaceFile(mainFile, newMain); err != nil { + os.Remove(file) + return "", err + } + return file, nil +} + +// addInclude inserts name after the last element of the (include ...) form, +// or appends an include form when there is none. +func addInclude(src []byte, m *Main, name string) []byte { + ins := " " + sexp.Quote(name) + if m.IncludeNode == nil { + out := bytes.Clone(src) + if len(out) > 0 && out[len(out)-1] != '\n' { + out = append(out, '\n') + } + return append(out, "(include"+ins+")\n"...) + } + kids := m.IncludeNode.Children + at := kids[len(kids)-1].End.Offset + out := make([]byte, 0, len(src)+len(ins)) + out = append(out, src[:at]...) + out = append(out, ins...) + return append(out, src[at:]...) +} + +// writeNew creates path holding data, failing if it already exists. +func writeNew(path string, data []byte) error { + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644) + if err != nil { + return err + } + if _, err := f.Write(data); err != nil { + f.Close() + os.Remove(path) + return err + } + return f.Close() +} + +// replaceFile atomically replaces the file at path, keeping its permissions. +// A symlink is followed and its target replaced, so dotfile links survive. +func replaceFile(path string, data []byte) error { + real, err := filepath.EvalSymlinks(path) + if err != nil { + return err + } + fi, err := os.Stat(real) + if err != nil { + return err + } + tmp, err := os.CreateTemp(filepath.Dir(real), ".krino-*") + if err != nil { + return err + } + defer os.Remove(tmp.Name()) + if _, err := tmp.Write(data); err != nil { + tmp.Close() + return err + } + if err := tmp.Chmod(fi.Mode().Perm()); err != nil { + tmp.Close() + return err + } + if err := tmp.Sync(); err != nil { + tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + return os.Rename(tmp.Name(), real) +} diff --git a/internal/config/skel/krino.conf b/internal/config/skel/krino.conf new file mode 100644 index 0000000..48780ea --- /dev/null +++ b/internal/config/skel/krino.conf @@ -0,0 +1,22 @@ +;; -*- mode: lisp -*- +;; vim: set ft=lisp : +;; +;; krino's main configuration. The syntax is explained in +;; docs/sexp-primer.md; every form is described in krino.conf(5). + +;; The directories to sort, in this order. Each NAME has its rules in +;; dirs/NAME.conf. Add one with: krino new NAME PATH +(include) + +;; Where the log goes. Remove the ";; " to change it. +;; (log "~/.local/state/krino/krino.log") + +;; Defaults for every directory; a directory's own file can override them. +;; (defaults +;; (case ignore) ; ignore | strict +;; (fold yes) ; yes: "spolka" matches "spółka" +;; (recursive no) +;; (min-age 2m) ; skip files modified in the last 2 minutes +;; (max-read 50M) ; no content extraction above this size +;; (busy ".part" ".aria2" ".crdownload") +;; (on-conflict suffix)) ; suffix | skip | overwrite diff --git a/internal/config/skel/template.conf b/internal/config/skel/template.conf new file mode 100644 index 0000000..867b681 --- /dev/null +++ b/internal/config/skel/template.conf @@ -0,0 +1,37 @@ +;; -*- mode: lisp -*- +;; vim: set ft=lisp : +;; +;; krino rules for one directory. The syntax is explained in +;; docs/sexp-primer.md; every form is described in krino.conf(5). + +(path "@PATH@") + +;; Settings for this directory; each overrides the defaults in krino.conf. +;; Remove the ";; " to use one. +;; (recursive no) ; yes: also sort files in subdirectories +;; (max-depth 3) ; with recursive: how deep to go +;; (case ignore) ; ignore | strict +;; (fold yes) ; yes: "spolka" matches "spółka" +;; (min-age 2m) ; skip files modified in the last 2 minutes +;; (max-read 50M) ; no content extraction above this size +;; (on-conflict suffix) ; suffix | skip | overwrite + +;; Files and directories to leave alone, in .gitignore syntax. +(ignore "*.part" "*.crdownload" "*.aria2" ".*") + +;; Rules run top to bottom. Every rule that matches a file adds its actions +;; to that file; (stop) ends the search for it. Some examples: + +;; (rule "invoices" +;; (when (type pdf) +;; (content "invoice" "faktura")) +;; (move "Invoices/{mtime:%Y}") +;; (stop)) + +;; (rule "images" +;; (when (type image)) +;; (move "Images")) + +;; (rule "old-packages" +;; (when (type package) (age > 30d)) +;; (delete)) diff --git a/internal/config/skel_test.go b/internal/config/skel_test.go new file mode 100644 index 0000000..476af65 --- /dev/null +++ b/internal/config/skel_test.go @@ -0,0 +1,264 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package config + +import ( + "bytes" + "errors" + "io/fs" + "os" + "path/filepath" + "strings" + "testing" +) + +// uncomment turns the commented examples in a skeleton into live forms. +func uncomment(src []byte) []byte { + lines := strings.Split(string(src), "\n") + for i, l := range lines { + if strings.HasPrefix(l, ";; (") || strings.HasPrefix(l, ";; ") { + lines[i] = l[3:] + } + } + return []byte(strings.Join(lines, "\n")) +} + +func TestSkeletonsParse(t *testing.T) { + tmpl := bytes.ReplaceAll(skelTemplate, []byte("@PATH@"), []byte("/tmp")) + for name, src := range map[string][]byte{"plain": tmpl, "uncommented": uncomment(tmpl)} { + if _, errs := ParseDir("x", "template.conf", src); len(errs) > 0 { + t.Errorf("template.conf, %s: %v", name, errs) + } + } + for name, src := range map[string][]byte{"plain": skelMain, "uncommented": uncomment(skelMain)} { + if _, errs := ParseMain("krino.conf", src); len(errs) > 0 { + t.Errorf("krino.conf, %s: %v", name, errs) + } + } +} + +func TestInitAndNew(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + target := filepath.Join(home, "downloads") + if err := os.Mkdir(target, 0o755); err != nil { + t.Fatal(err) + } + main := filepath.Join(home, ".config", "krino", "krino.conf") + created, err := Init(main) + if err != nil || len(created) != 2 { + t.Fatalf("Init = %v, %v", created, err) + } + if _, err := Init(main); err == nil || err.Error() != main+" already exists; krino init leaves it alone" { + t.Fatalf("second Init: %v", err) + } + if cfg, errs := Load(main); len(errs) > 0 || len(cfg.Dirs) != 0 { + t.Fatalf("fresh config: %v", errs) + } + file, err := NewDir(main, "downloads", target) + if err != nil { + t.Fatal(err) + } + cfg, errs := Load(main) + if len(errs) > 0 || len(cfg.Dirs) != 1 { + t.Fatalf("after NewDir: %v", errs) + } + if d := cfg.Dirs[0]; d.Path != target || d.PathText != "~/downloads" || d.File != file { + t.Fatalf("dir = %+v", d) + } +} + +// TestInitRefusedLeavesDirsAbsent is item D: a refused init (krino.conf +// already exists) must not create dirs/ either. +func TestInitRefusedLeavesDirsAbsent(t *testing.T) { + root := t.TempDir() + main := filepath.Join(root, "krino.conf") + if err := os.WriteFile(main, []byte("(include)\n"), 0o644); err != nil { + t.Fatal(err) + } + if _, err := Init(main); err == nil || err.Error() != main+" already exists; krino init leaves it alone" { + t.Fatalf("Init = %v, want already-exists", err) + } + if _, err := os.Stat(filepath.Join(root, "dirs")); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("dirs/ created by a refused init: %v", err) + } +} + +func TestInitKeepsTemplate(t *testing.T) { + root := t.TempDir() + writeFiles(t, root, map[string]string{"template.conf": ";; mine\n(path \"@PATH@\")\n"}) + created, err := Init(filepath.Join(root, "krino.conf")) + if err != nil || len(created) != 1 { + t.Fatalf("Init = %v, %v", created, err) + } + if got, _ := os.ReadFile(filepath.Join(root, "template.conf")); string(got) != ";; mine\n(path \"@PATH@\")\n" { + t.Fatalf("template overwritten: %q", got) + } +} + +func TestNewDirKeepsTheRestOfTheFile(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + orig := ";; my notes\n(include \"a\" ; first\n)\n(defaults (min-age 5m)) ; tail\n" + writeFiles(t, home, map[string]string{"dirs/a.conf": `(path "~/a")`, "a/.keep": "", "b/.keep": ""}) + main := filepath.Join(home, "krino.conf") + if err := os.WriteFile(main, []byte(orig), 0o600); err != nil { + t.Fatal(err) + } + if _, err := NewDir(main, "b", "~/b"); err != nil { + t.Fatal(err) + } + got, _ := os.ReadFile(main) + want := ";; my notes\n(include \"a\" \"b\" ; first\n)\n(defaults (min-age 5m)) ; tail\n" + if string(got) != want { + t.Fatalf("got\n%s\nwant\n%s", got, want) + } + if fi, _ := os.Stat(main); fi.Mode().Perm() != 0o600 { + t.Errorf("mode = %v, want 0600 kept", fi.Mode().Perm()) + } +} + +func TestNewDirAppendsInclude(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + writeFiles(t, home, map[string]string{"krino.conf": `(log "/x.log")`, "b/.keep": ""}) + main := filepath.Join(home, "krino.conf") + if _, err := NewDir(main, "b", "~/b"); err != nil { + t.Fatal(err) + } + if got, _ := os.ReadFile(main); string(got) != "(log \"/x.log\")\n(include \"b\")\n" { + t.Fatalf("got %q", got) + } +} + +func TestNewDirFollowsSymlink(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + writeFiles(t, home, map[string]string{"dotfiles/krino.conf": "(include)\n", "x/.keep": ""}) + confDir := filepath.Join(home, "conf") + if err := os.Mkdir(confDir, 0o755); err != nil { + t.Fatal(err) + } + main := filepath.Join(confDir, "krino.conf") + if err := os.Symlink(filepath.Join(home, "dotfiles", "krino.conf"), main); err != nil { + t.Fatal(err) + } + if _, err := NewDir(main, "x", "~/x"); err != nil { + t.Fatal(err) + } + if fi, _ := os.Lstat(main); fi.Mode()&os.ModeSymlink == 0 { + t.Fatal("krino.conf symlink was replaced by a regular file") + } + if got, _ := os.ReadFile(filepath.Join(home, "dotfiles", "krino.conf")); string(got) != "(include \"x\")\n" { + t.Fatalf("link target = %q", got) + } +} + +// TestNewDirTemplateMissingPlaceholder is item A: a template.conf without +// "@PATH@" must not silently keep its own path. +func TestNewDirTemplateMissingPlaceholder(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + writeFiles(t, home, map[string]string{ + "template.conf": "(path \"/somewhere/else\")\n", + "b/.keep": "", + }) + main := filepath.Join(home, "krino.conf") + orig := "(include)\n" + if err := os.WriteFile(main, []byte(orig), 0o644); err != nil { + t.Fatal(err) + } + tmplPath := filepath.Join(home, "template.conf") + want := tmplPath + ` must contain (path "@PATH@")` + if _, err := NewDir(main, "b", "~/b"); err == nil || err.Error() != want { + t.Fatalf("NewDir = %v, want %s", err, want) + } + if _, err := os.Stat(filepath.Join(home, "dirs", "b.conf")); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("dirs/b.conf created: %v", err) + } + if got, _ := os.ReadFile(main); string(got) != orig { + t.Fatalf("krino.conf changed: %q", got) + } +} + +// TestNewDirFileAlreadyExists is item I.1: a stray dirs/NAME.conf that was +// never included must refuse, leaving krino.conf untouched. +func TestNewDirFileAlreadyExists(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + orig := "(include)\n" + writeFiles(t, home, map[string]string{"dirs/b.conf": "stale\n", "b/.keep": ""}) + main := filepath.Join(home, "krino.conf") + if err := os.WriteFile(main, []byte(orig), 0o644); err != nil { + t.Fatal(err) + } + want := filepath.Join(home, "dirs", "b.conf") + " already exists" + if _, err := NewDir(main, "b", "~/b"); err == nil || err.Error() != want { + t.Fatalf("NewDir = %v, want %s", err, want) + } + if got, _ := os.ReadFile(main); string(got) != orig { + t.Fatalf("krino.conf changed: %q", got) + } +} + +// TestNewDirRollsBackWhenConfigDirReadOnly is item I.2: if dirs/NAME.conf +// can be written but krino.conf cannot be replaced, the new file must be +// rolled back and krino.conf left untouched. +func TestNewDirRollsBackWhenConfigDirReadOnly(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root ignores read-only permissions") + } + home := t.TempDir() + t.Setenv("HOME", home) + writeFiles(t, home, map[string]string{"b/.keep": ""}) + confDir := filepath.Join(home, "conf") + if err := os.Mkdir(confDir, 0o755); err != nil { + t.Fatal(err) + } + main := filepath.Join(confDir, "krino.conf") + orig := "(include)\n" + if err := os.WriteFile(main, []byte(orig), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(filepath.Join(confDir, "dirs"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Chmod(confDir, 0o500); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.Chmod(confDir, 0o755) }) + if _, err := NewDir(main, "b", "~/b"); err == nil { + t.Fatal("NewDir succeeded, want an error from the read-only config directory") + } + if _, err := os.Stat(filepath.Join(confDir, "dirs", "b.conf")); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("dirs/b.conf not rolled back: %v", err) + } + if got, _ := os.ReadFile(main); string(got) != orig { + t.Fatalf("krino.conf changed: %q", got) + } +} + +func TestNewDirErrors(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + writeFiles(t, home, map[string]string{ + "krino.conf": `(include "a")`, "dirs/a.conf": `(path "~")`, "x/.keep": "", "f": "", + }) + main := filepath.Join(home, "krino.conf") + tests := []struct{ name, path, want string }{ + {"a/b", "~/x", `bad directory name "a/b": use letters, digits, '.', '_' and '-'`}, + {"check", "~/x", `"check" is a krino command; choose another name`}, + {"b", "~/f", filepath.Join(home, "f") + " is not a directory"}, + {"b", "~/missing", filepath.Join(home, "missing") + " is not a directory"}, + {"a", "~/x", `"a" is already included`}, + } + for _, tt := range tests { + if _, err := NewDir(main, tt.name, tt.path); err == nil || err.Error() != tt.want { + t.Errorf("NewDir(%q, %q) = %v, want %s", tt.name, tt.path, err, tt.want) + } + } + if _, err := NewDir(filepath.Join(home, "none.conf"), "b", "~/x"); err == nil || + !strings.HasSuffix(err.Error(), "not found; create it with: krino init") { + t.Errorf("missing main file: %v", err) + } +} diff --git a/internal/config/units.go b/internal/config/units.go new file mode 100644 index 0000000..ea61dee --- /dev/null +++ b/internal/config/units.go @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package config + +import ( + "errors" + "fmt" + "math" + "strconv" + "time" +) + +// ParseSize reads a size: a whole number with an optional K, M, G or T +// suffix, in powers of 1024. +func ParseSize(s string) (int64, error) { + num, mult := s, int64(1) + if n := len(s); n > 0 { + switch s[n-1] { + case 'K': + mult = 1 << 10 + case 'M': + mult = 1 << 20 + case 'G': + mult = 1 << 30 + case 'T': + mult = 1 << 40 + } + if mult > 1 { + num = s[:n-1] + } + } + v, err := parseCount(num) + if err != nil || v > math.MaxInt64/mult { + return 0, fmt.Errorf("bad size %q: want a whole number with an optional K, M, G or T, like 50M", s) + } + return v * mult, nil +} + +var durationUnits = map[byte]time.Duration{ + 's': time.Second, 'm': time.Minute, 'h': time.Hour, 'd': 24 * time.Hour, 'w': 7 * 24 * time.Hour, +} + +// ParseDuration reads a duration: a whole number followed by s, m, h, d or w. +func ParseDuration(s string) (time.Duration, error) { + bad := fmt.Errorf("bad duration %q: want a whole number followed by s, m, h, d or w, like 30d", s) + if len(s) < 2 { + return 0, bad + } + unit, ok := durationUnits[s[len(s)-1]] + if !ok { + return 0, bad + } + v, err := parseCount(s[:len(s)-1]) + if err != nil || v > int64(math.MaxInt64/unit) { + return 0, bad + } + return time.Duration(v) * unit, nil +} + +// parseCount reads a non-empty run of ASCII digits. +func parseCount(s string) (int64, error) { + if s == "" { + return 0, errors.New("empty number") + } + for _, c := range s { + if c < '0' || c > '9' { + return 0, errors.New("not a whole number") + } + } + return strconv.ParseInt(s, 10, 64) +} diff --git a/internal/config/units_test.go b/internal/config/units_test.go new file mode 100644 index 0000000..e502f97 --- /dev/null +++ b/internal/config/units_test.go @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package config + +import ( + "testing" + "time" +) + +func TestParseSize(t *testing.T) { + good := map[string]int64{"0": 0, "512": 512, "1K": 1024, "50M": 50 << 20, "2G": 2 << 30, "1T": 1 << 40} + for in, want := range good { + if got, err := ParseSize(in); err != nil || got != want { + t.Errorf("ParseSize(%q) = %d, %v; want %d", in, got, err, want) + } + } + for _, in := range []string{"", "M", "1.5M", "-1", "1Q", "1k", "99999999999T", " 1"} { + if _, err := ParseSize(in); err == nil { + t.Errorf("ParseSize(%q) accepted", in) + } + } +} + +func TestParseDuration(t *testing.T) { + good := map[string]time.Duration{ + "0s": 0, "90s": 90 * time.Second, "2m": 2 * time.Minute, "3h": 3 * time.Hour, + "30d": 30 * 24 * time.Hour, "1w": 7 * 24 * time.Hour, + } + for in, want := range good { + if got, err := ParseDuration(in); err != nil || got != want { + t.Errorf("ParseDuration(%q) = %v, %v; want %v", in, got, err, want) + } + } + for _, in := range []string{"", "2", "m", "-1d", "1.5h", "2M", "99999999999999999999d", "9999999999999w"} { + if _, err := ParseDuration(in); err == nil { + t.Errorf("ParseDuration(%q) accepted", in) + } + } +} diff --git a/internal/sexp/fuzz_test.go b/internal/sexp/fuzz_test.go new file mode 100644 index 0000000..01d436b --- /dev/null +++ b/internal/sexp/fuzz_test.go @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package sexp + +import "testing" + +// FuzzParse checks that Parse never panics and that every node it returns +// spans valid bytes, with lists pointing at their own parentheses. +func FuzzParse(f *testing.F) { + for _, s := range []string{`(a "b" (c))`, `"\"`, `(((`, `)`, "; x\n(y)", `("ł" x)`, "\xff", `"\\"`} { + f.Add([]byte(s)) + } + f.Fuzz(func(t *testing.T, src []byte) { + nodes, err := Parse("f", src) + if err != nil { + return + } + walk(nodes, func(n *Node) { + if n.Pos.Offset < 0 || n.End.Offset > len(src) || n.Pos.Offset >= n.End.Offset { + t.Fatalf("bad span %d..%d in %q", n.Pos.Offset, n.End.Offset, src) + } + if n.Kind == List && (src[n.Pos.Offset] != '(' || src[n.End.Offset-1] != ')') { + t.Fatalf("list %d..%d does not span its parens in %q", n.Pos.Offset, n.End.Offset, src) + } + }) + }) +} diff --git a/internal/sexp/sexp.go b/internal/sexp/sexp.go new file mode 100644 index 0000000..6e14a1f --- /dev/null +++ b/internal/sexp/sexp.go @@ -0,0 +1,263 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +// Package sexp reads the s-expression syntax of krino's config files: lists, +// symbols, strings and ; comments. Nodes record positions and byte offsets, +// so callers can report errors precisely and splice edits into the text. +package sexp + +import ( + "fmt" + "strings" + "unicode" + "unicode/utf8" +) + +// Kind is the kind of a Node. +type Kind int + +const ( + List Kind = iota + Symbol + String +) + +func (k Kind) String() string { + switch k { + case List: + return "list" + case Symbol: + return "symbol" + case String: + return "string" + } + return fmt.Sprintf("Kind(%d)", int(k)) +} + +// Pos is a position in a source file. Line and Col count from 1, and Col +// counts characters; Offset counts bytes from 0. +type Pos struct { + Offset, Line, Col int +} + +// Node is a list, a symbol or a string. +type Node struct { + Kind Kind + Pos Pos // the "(" of a list, the first character of an atom + End Pos // just past the node's last byte + Text string // a symbol's name or a string's decoded value + Children []*Node // a list's elements +} + +// Head is the name of the symbol a list starts with, or "". +func (n *Node) Head() string { + if n.Kind == List && len(n.Children) > 0 && n.Children[0].Kind == Symbol { + return n.Children[0].Text + } + return "" +} + +// Args are a list's elements after the first. +func (n *Node) Args() []*Node { + if n.Kind != List || len(n.Children) == 0 { + return nil + } + return n.Children[1:] +} + +// String renders n briefly for messages: atoms in full, a list by at most its +// first two atoms, as in (rule "acme" ...). +func (n *Node) String() string { + switch n.Kind { + case Symbol: + return n.Text + case String: + return Quote(n.Text) + } + var b strings.Builder + b.WriteByte('(') + shown := 0 + for _, c := range n.Children { + if c.Kind == List || shown == 2 { + break + } + if shown > 0 { + b.WriteByte(' ') + } + b.WriteString(c.String()) + shown++ + } + if shown < len(n.Children) { + if shown > 0 { + b.WriteByte(' ') + } + b.WriteString("...") + } + b.WriteByte(')') + return b.String() +} + +var quoter = strings.NewReplacer(`\`, `\\`, `"`, `\"`) + +// Quote encodes s as a config string, escaping only " and \. +func Quote(s string) string { + return `"` + quoter.Replace(s) + `"` +} + +// Error is a syntax error. +type Error struct { + File string + Pos Pos + Msg string +} + +func (e *Error) Error() string { + return fmt.Sprintf("%s:%d:%d: %s", e.File, e.Pos.Line, e.Pos.Col, e.Msg) +} + +// Parse reads every top-level form in src. file names the source in errors, +// and every error is an *Error. +func Parse(file string, src []byte) ([]*Node, error) { + p := &parser{file: file, src: src, pos: Pos{Line: 1, Col: 1}} + if err := p.checkUTF8(); err != nil { + return nil, err + } + if len(src) >= 3 && src[0] == 0xEF && src[1] == 0xBB && src[2] == 0xBF { + p.pos.Offset = 3 // a leading BOM is invisible: skip it, offsets stay into src + } + var top, stack []*Node + add := func(n *Node) { + if len(stack) == 0 { + top = append(top, n) + return + } + parent := stack[len(stack)-1] + parent.Children = append(parent.Children, n) + } + for { + p.skipSpace() + if p.eof() { + break + } + start := p.pos + switch p.src[p.pos.Offset] { + case '(': + p.next() + n := &Node{Kind: List, Pos: start} + add(n) + stack = append(stack, n) + case ')': + if len(stack) == 0 { + return nil, p.errorf(start, `unexpected ")"`) + } + p.next() + stack[len(stack)-1].End = p.pos + stack = stack[:len(stack)-1] + case '"': + n, err := p.str() + if err != nil { + return nil, err + } + add(n) + default: + add(p.symbol()) + } + } + if len(stack) > 0 { + return nil, p.errorf(stack[0].Pos, `"(" never closed: %s`, stack[0]) + } + return top, nil +} + +type parser struct { + file string + src []byte + pos Pos +} + +func (p *parser) eof() bool { return p.pos.Offset >= len(p.src) } + +func (p *parser) peek() rune { + r, _ := utf8.DecodeRune(p.src[p.pos.Offset:]) + return r +} + +// next moves past one character and returns it. +func (p *parser) next() rune { + r, size := utf8.DecodeRune(p.src[p.pos.Offset:]) + p.pos.Offset += size + if r == '\n' { + p.pos.Line++ + p.pos.Col = 1 + } else { + p.pos.Col++ + } + return r +} + +func (p *parser) errorf(at Pos, format string, args ...any) *Error { + return &Error{File: p.file, Pos: at, Msg: fmt.Sprintf(format, args...)} +} + +// checkUTF8 rejects invalid UTF-8 up front, so the parser can assume it. +func (p *parser) checkUTF8() error { + for !p.eof() { + if r, size := utf8.DecodeRune(p.src[p.pos.Offset:]); r == utf8.RuneError && size == 1 { + return p.errorf(p.pos, "invalid UTF-8") + } + p.next() + } + p.pos = Pos{Line: 1, Col: 1} + return nil +} + +// skipSpace moves past whitespace and comments. +func (p *parser) skipSpace() { + for !p.eof() { + switch r := p.peek(); { + case r == ';': + for !p.eof() && p.peek() != '\n' { + p.next() + } + case unicode.IsSpace(r): + p.next() + default: + return + } + } +} + +// str reads a string. A backslash escapes only " and \; any other backslash +// is kept, so regular expressions need no doubling. +func (p *parser) str() (*Node, error) { + start := p.pos + p.next() // the opening quote + var b strings.Builder + for { + if p.eof() { + return nil, p.errorf(start, "string never closed") + } + r := p.next() + switch r { + case '"': + return &Node{Kind: String, Pos: start, End: p.pos, Text: b.String()}, nil + case '\\': + if !p.eof() && (p.peek() == '"' || p.peek() == '\\') { + r = p.next() + } + } + b.WriteRune(r) + } +} + +// symbol reads everything up to whitespace, a parenthesis, a quote or a +// comment. +func (p *parser) symbol() *Node { + start := p.pos + for !p.eof() { + if r := p.peek(); unicode.IsSpace(r) || r == '(' || r == ')' || r == '"' || r == ';' { + break + } + p.next() + } + return &Node{Kind: Symbol, Pos: start, End: p.pos, Text: string(p.src[start.Offset:p.pos.Offset])} +} diff --git a/internal/sexp/sexp_test.go b/internal/sexp/sexp_test.go new file mode 100644 index 0000000..b0e0e4e --- /dev/null +++ b/internal/sexp/sexp_test.go @@ -0,0 +1,183 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package sexp + +import "testing" + +func mustParse(t *testing.T, src string) []*Node { + t.Helper() + nodes, err := Parse("t.conf", []byte(src)) + if err != nil { + t.Fatalf("Parse(%q): %v", src, err) + } + return nodes +} + +// walk calls fn for every node, depth first. +func walk(nodes []*Node, fn func(*Node)) { + for _, n := range nodes { + fn(n) + walk(n.Children, fn) + } +} + +func TestAtoms(t *testing.T) { + tests := []struct { + src string + kind Kind + text string + }{ + {`pdf`, Symbol, "pdf"}, + {`30d`, Symbol, "30d"}, + {`>=`, Symbol, ">="}, + {`"acme ltd"`, String, "acme ltd"}, + {`"say \"hi\""`, String, `say "hi"`}, + {`"\bacme\b"`, String, `\bacme\b`}, + {`"a\\b"`, String, `a\b`}, + {`"a\\\\b"`, String, `a\\b`}, + {"\"two\nlines\"", String, "two\nlines"}, + {`"spółka"`, String, "spółka"}, + {`""`, String, ""}, + } + for _, tt := range tests { + nodes := mustParse(t, tt.src) + if len(nodes) != 1 || nodes[0].Kind != tt.kind || nodes[0].Text != tt.text { + t.Errorf("Parse(%q) = %+v, want one %v %q", tt.src, nodes, tt.kind, tt.text) + } + } +} + +func TestListStructure(t *testing.T) { + nodes := mustParse(t, `(when (type pdf) (content "x" "y"))`) + if len(nodes) != 1 { + t.Fatalf("got %d nodes", len(nodes)) + } + w := nodes[0] + if w.Kind != List || w.Head() != "when" || len(w.Args()) != 2 { + t.Fatalf("when = %+v", w) + } + c := w.Args()[1] + if c.Head() != "content" || len(c.Args()) != 2 || c.Args()[1].Text != "y" { + t.Fatalf("content = %+v", c) + } + if got := mustParse(t, `("x" y)`)[0].Head(); got != "" { + t.Errorf("Head of a list starting with a string = %q, want empty", got) + } +} + +func TestPositions(t *testing.T) { + src := "; comment\n(path \"~/d\")\n (ignore \"*.part\")\n" + nodes := mustParse(t, src) + if len(nodes) != 2 { + t.Fatalf("got %d nodes", len(nodes)) + } + checks := []struct { + name string + got, want Pos + }{ + {"path start", nodes[0].Pos, Pos{Offset: 10, Line: 2, Col: 1}}, + {"path end", nodes[0].End, Pos{Offset: 22, Line: 2, Col: 13}}, + {"string start", nodes[0].Args()[0].Pos, Pos{Offset: 16, Line: 2, Col: 7}}, + {"string end", nodes[0].Args()[0].End, Pos{Offset: 21, Line: 2, Col: 12}}, + {"ignore start", nodes[1].Pos, Pos{Offset: 25, Line: 3, Col: 3}}, + } + for _, c := range checks { + if c.got != c.want { + t.Errorf("%s = %+v, want %+v", c.name, c.got, c.want) + } + } +} + +func TestColumnsCountCharacters(t *testing.T) { + x := mustParse(t, `("ł" x)`)[0].Children[1] + if want := (Pos{Offset: 6, Line: 1, Col: 6}); x.Pos != want { + t.Fatalf("x at %+v, want %+v", x.Pos, want) + } +} + +// TestBOMIsSkipped is item G: a leading UTF-8 byte-order mark must not +// become a visible symbol, and byte offsets after it must stay offsets into +// the original source. +func TestBOMIsSkipped(t *testing.T) { + src := "\xEF\xBB\xBF(a)" + nodes := mustParse(t, src) + if len(nodes) != 1 { + t.Fatalf("got %d nodes, want 1", len(nodes)) + } + n := nodes[0] + want := Pos{Offset: 3, Line: 1, Col: 1} + if n.Pos != want { + t.Errorf("Pos = %+v, want %+v", n.Pos, want) + } + if n.End.Offset != 6 { + t.Errorf("End.Offset = %d, want 6", n.End.Offset) + } +} + +func TestListOffsetsPointAtParens(t *testing.T) { + src := "(rule \"a\"\n (when (or (type pdf) (name \"x\")))\n (stop)) (b)" + walk(mustParse(t, src), func(n *Node) { + if n.Kind == List && (src[n.Pos.Offset] != '(' || src[n.End.Offset-1] != ')') { + t.Errorf("list %s spans %d..%d", n, n.Pos.Offset, n.End.Offset) + } + }) +} + +func TestComments(t *testing.T) { + nodes := mustParse(t, "(a ; x ) y\n b) ; c") + if len(nodes) != 1 || len(nodes[0].Children) != 2 || nodes[0].Children[1].Text != "b" { + t.Fatalf("got %+v, want (a b)", nodes) + } + if n := mustParse(t, ""); n != nil { + t.Errorf("empty source gave %+v", n) + } + if n := mustParse(t, "; only a comment\n"); n != nil { + t.Errorf("comment-only source gave %+v", n) + } +} + +func TestNodeString(t *testing.T) { + tests := map[string]string{ + `(rule "acme" (when x) (stop))`: `(rule "acme" ...)`, + `(stop)`: `(stop)`, + `(type pdf docx odt)`: `(type pdf ...)`, + `(a b)`: `(a b)`, + `()`: `()`, + `((a) b)`: `(...)`, + `sym`: `sym`, + `"a\"b"`: `"a\"b"`, + } + for src, want := range tests { + if got := mustParse(t, src)[0].String(); got != want { + t.Errorf("String of %s = %s, want %s", src, got, want) + } + } +} + +func TestQuoteRoundTrip(t *testing.T) { + for _, v := range []string{"plain", `a"b`, `a\b`, `\bacme\b`, `x\"y`, "~/My Files"} { + n := mustParse(t, Quote(v)) + if len(n) != 1 || n[0].Kind != String || n[0].Text != v { + t.Errorf("Quote(%q) = %s does not read back", v, Quote(v)) + } + } +} + +func TestErrors(t *testing.T) { + tests := []struct{ src, want string }{ + {`(a (b)`, `t.conf:1:1: "(" never closed: (a ...)`}, + {"(rule \"acme\"\n (when (type pdf)", `t.conf:1:1: "(" never closed: (rule "acme" ...)`}, + {`a)`, `t.conf:1:2: unexpected ")"`}, + {"(a\n \"abc", `t.conf:2:3: string never closed`}, + {"ok \xff", `t.conf:1:4: invalid UTF-8`}, + } + for _, tt := range tests { + _, err := Parse("t.conf", []byte(tt.src)) + if err == nil || err.Error() != tt.want { + t.Errorf("Parse(%q) error = %v, want %s", tt.src, err, tt.want) + } + if _, ok := err.(*Error); err != nil && !ok { + t.Errorf("Parse(%q) error is %T, want *Error", tt.src, err) + } + } +} diff --git a/internal/xdg/xdg.go b/internal/xdg/xdg.go new file mode 100644 index 0000000..ed34838 --- /dev/null +++ b/internal/xdg/xdg.go @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +// Package xdg resolves the XDG base directories and expands ~ in paths. +package xdg + +import ( + "os" + "path/filepath" + "strings" +) + +// ConfigHome is $XDG_CONFIG_HOME, or ~/.config. +func ConfigHome() string { return base("XDG_CONFIG_HOME", ".config") } + +// StateHome is $XDG_STATE_HOME, or ~/.local/state. +func StateHome() string { return base("XDG_STATE_HOME", filepath.Join(".local", "state")) } + +// DataHome is $XDG_DATA_HOME, or ~/.local/share. +func DataHome() string { return base("XDG_DATA_HOME", filepath.Join(".local", "share")) } + +// base follows the XDG rule that a relative value is invalid and ignored. +func base(env, fallback string) string { + if v := os.Getenv(env); filepath.IsAbs(v) { + return filepath.Clean(v) + } + return filepath.Join(Home(), fallback) +} + +// Home is the user's home directory, or "/" when it is unknown. +func Home() string { + if h, err := os.UserHomeDir(); err == nil && h != "" { + return filepath.Clean(h) + } + return "/" +} + +// Expand replaces a leading "~" or "~/" with the home directory. +// "~user" is left alone. +func Expand(p string) string { + if p == "~" { + return Home() + } + if strings.HasPrefix(p, "~/") { + return filepath.Join(Home(), p[2:]) + } + return p +} + +// Abbrev replaces a leading home directory with "~", for display and for +// paths written into config files. +func Abbrev(p string) string { + h := Home() + if p == h { + return "~" + } + if h != "/" && strings.HasPrefix(p, h+"/") { + return "~/" + p[len(h)+1:] + } + return p +} diff --git a/internal/xdg/xdg_test.go b/internal/xdg/xdg_test.go new file mode 100644 index 0000000..7c7de87 --- /dev/null +++ b/internal/xdg/xdg_test.go @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package xdg + +import "testing" + +func TestBaseDirs(t *testing.T) { + t.Setenv("HOME", "/home/u") + t.Setenv("XDG_CONFIG_HOME", "") + t.Setenv("XDG_STATE_HOME", "relative/ignored") + t.Setenv("XDG_DATA_HOME", "/data/") + if got := ConfigHome(); got != "/home/u/.config" { + t.Errorf("ConfigHome() = %q", got) + } + if got := StateHome(); got != "/home/u/.local/state" { + t.Errorf("StateHome() = %q, a relative value must be ignored", got) + } + if got := DataHome(); got != "/data" { + t.Errorf("DataHome() = %q", got) + } +} + +// TestHomeTrailingSlash is item H: Home() must clean its result, or a +// trailing slash from $HOME breaks Abbrev's prefix check. +func TestHomeTrailingSlash(t *testing.T) { + t.Setenv("HOME", "/home/u/") + if got := Abbrev("/home/u/x"); got != "~/x" { + t.Errorf("Abbrev(/home/u/x) = %q, want ~/x", got) + } + if got := Expand("~/x"); got != "/home/u/x" { + t.Errorf("Expand(~/x) = %q, want /home/u/x", got) + } +} + +func TestExpandAbbrev(t *testing.T) { + t.Setenv("HOME", "/home/u") + expand := map[string]string{ + "~": "/home/u", + "~/d/x": "/home/u/d/x", + "~other/x": "~other/x", + "/abs": "/abs", + "rel/x": "rel/x", + } + for in, want := range expand { + if got := Expand(in); got != want { + t.Errorf("Expand(%q) = %q, want %q", in, got, want) + } + } + abbrev := map[string]string{ + "/home/u": "~", + "/home/u/d/x": "~/d/x", + "/home/ux/y": "/home/ux/y", + "/etc": "/etc", + } + for in, want := range abbrev { + if got := Abbrev(in); got != want { + t.Errorf("Abbrev(%q) = %q, want %q", in, got, want) + } + } +} diff --git a/scripts/hooks/pre-commit b/scripts/hooks/pre-commit new file mode 100755 index 0000000..ec9f507 --- /dev/null +++ b/scripts/hooks/pre-commit @@ -0,0 +1,4 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-3.0-or-later +# Installed by `make install-hooks`: refuse commits that carry personal data. +exec "$(git rev-parse --show-toplevel)/scripts/leak-check" diff --git a/scripts/leak-check b/scripts/leak-check new file mode 100755 index 0000000..fbbd5d5 --- /dev/null +++ b/scripts/leak-check @@ -0,0 +1,70 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-3.0-or-later +# +# leak-check: refuse personal data in the files git would commit. +# +# Scans every staged file (the index, not the working tree), and the names +# of staged files against the private list, for: +# - the current user's home directory, e.g. /home/alice; +# - email addresses (LICENSE is exempt); +# - a private pattern list: one extended regular expression per line, +# blank lines and lines starting with # ignored, matched ignoring case. +# Its path is set per clone with: git config krino.leakpatterns FILE +# Keep that file outside the repository so the list is never published. +# +# A line matching the regex in `git config krino.leakallow` is never +# reported (for example a public contact address in the README). +# +# Prints file:line for each hit, never the matched text, so a hit on a +# private pattern does not echo the secret. Exits 0 when clean, 1 when +# something matched, 2 when the private list is configured but missing. + +set -eu + +cd "$(git rev-parse --show-toplevel)" + +allow=$(git config --get krino.leakallow || true) +hits=0 + +# check LABEL GREP-ARGS...: report staged lines that match, as file:line. +check() { + label=$1 + shift + out=$(git grep --cached -n -I "$@" | { if [ -n "$allow" ]; then grep -v -E -i -e "$allow"; else cat; fi; } | cut -d: -f1,2 || true) + if [ -n "$out" ]; then + printf 'leak-check: %s:\n%s\n' "$label" "$out" | sed '2,$s/^/ /' >&2 + hits=1 + fi +} + +home=${HOME%/} # a HOME of / becomes empty and is skipped +if [ -n "$home" ]; then + check "your home directory ($home)" -F -e "$home" -- . +fi + +check "an email address" -E -e '[[:alnum:]._%+-]+@[[:alnum:].-]+\.[[:alpha:]]{2,}' -- . ':(exclude)LICENSE' + +list=$(git config --type=path --get krino.leakpatterns || true) +if [ -z "$list" ]; then + echo "leak-check: no private pattern list (git config krino.leakpatterns FILE); built-in checks only" >&2 +elif [ ! -r "$list" ]; then + echo "leak-check: private pattern list $list is configured but cannot be read" >&2 + exit 2 +else + patterns=$(mktemp) + trap 'rm -f "$patterns"' EXIT + grep -v -e '^[[:space:]]*#' -e '^[[:space:]]*$' "$list" > "$patterns" || true + if [ -s "$patterns" ]; then + check "a private pattern from $list" -i -E -f "$patterns" -- . + named=$(git ls-files --cached | grep -i -E -f "$patterns" || true) + if [ -n "$named" ]; then + printf 'leak-check: a file name matching a private pattern:\n%s\n' "$named" | sed '2,$s/^/ /' >&2 + hits=1 + fi + fi +fi + +if [ "$hits" -ne 0 ]; then + echo "leak-check: remove the data above before committing; for a false positive, narrow the pattern or set krino.leakallow" >&2 + exit 1 +fi |
