hledger-0.22/0000755000000000000000000000000012252750510011234 5ustar0000000000000000hledger-0.22/Setup.hs0000644000000000000000000000005612252750510012671 0ustar0000000000000000import Distribution.Simple main = defaultMain hledger-0.22/hledger.cabal0000644000000000000000000001344512252750510013641 0ustar0000000000000000name: hledger -- also in cpp-options below version: 0.22 stability: beta category: Finance synopsis: The main command-line interface for the hledger accounting tool. description: hledger is a library and set of user tools for working with financial data (or anything that can be tracked in a double-entry accounting ledger.) It is a haskell port and friendly fork of John Wiegley's Ledger. hledger provides command-line, curses and web interfaces, and aims to be a reliable, practical tool for daily use. license: GPL license-file: LICENSE author: Simon Michael maintainer: Simon Michael homepage: http://hledger.org bug-reports: http://hledger.org/bugs tested-with: GHC==7.4.2, GHC==7.6.3 cabal-version: >= 1.10 build-type: Simple -- data-dir: data -- data-files: extra-tmp-files: extra-source-files: tests/suite.hs -- Cabal-Version: >= 1.9.2 -- Test-Suite test-hledger -- type: exitcode-stdio-1.0 -- main-is: test-hledger.hs -- build-depends: base source-repository head type: git location: https://github.com/simonmichael/hledger flag threaded Description: Build with support for multithreaded execution Default: True library cpp-options: -DVERSION="0.22" ghc-options: -W -- should be the same as below exposed-modules: Hledger.Cli Hledger.Cli.Main Hledger.Cli.Options Hledger.Cli.Tests Hledger.Cli.Utils Hledger.Cli.Version Hledger.Cli.Add Hledger.Cli.Balance Hledger.Cli.Balancesheet Hledger.Cli.Cashflow Hledger.Cli.Histogram Hledger.Cli.Incomestatement Hledger.Cli.Print Hledger.Cli.Register Hledger.Cli.Stats -- should be the same as below build-depends: hledger-lib == 0.22 ,base >= 4.3 && < 5 -- ,cabal-file-th ,containers ,cmdargs >= 0.10 && < 0.11 ,data-pprint >= 0.2.1 && < 0.3 ,directory ,filepath ,haskeline >= 0.6 && <= 0.8 ,HUnit ,mtl ,old-locale ,old-time ,parsec ,process ,regexpr >= 0.5.1 ,safe >= 0.2 ,shakespeare-text == 1.0.* ,split >= 0.1 && < 0.3 ,text >= 0.11 && < 1.1 ,tabular >= 0.2 && < 0.3 ,time ,utf8-string >= 0.3.5 && < 0.4 default-language: Haskell2010 -- should depend on the above to avoid double compilation but this is -- still too complicated as of 2011/6/1 because: -- - breaks haddock, http://hackage.haskell.org/trac/hackage/ticket/656 -- - library and executable must have different hs-source-dirs -- - the exe may need to list all the lib's dependencies -- - how it works seems ghc version dependent -- leksah is reported to have this working, http://hackage.haskell.org/packages/archive/leksah/0.10.0.4/leksah.cabal executable hledger main-is: hledger-cli.hs -- should be the same as above other-modules: Hledger.Cli Hledger.Cli.Main Hledger.Cli.Options Hledger.Cli.Tests Hledger.Cli.Utils Hledger.Cli.Version Hledger.Cli.Add Hledger.Cli.Balance Hledger.Cli.Balancesheet Hledger.Cli.Cashflow Hledger.Cli.Histogram Hledger.Cli.Incomestatement Hledger.Cli.Print Hledger.Cli.Register Hledger.Cli.Stats cpp-options: -DVERSION="0.22" ghc-options: -W if flag(threaded) ghc-options: -threaded -- should be the same as above build-depends: hledger-lib == 0.22 ,base >= 4.3 && < 5 ,containers ,cmdargs >= 0.10 && < 0.11 ,data-pprint >= 0.2.1 && < 0.3 ,directory ,filepath ,haskeline >= 0.6 && <= 0.8 ,HUnit ,mtl ,old-locale ,old-time ,parsec ,process ,regexpr >= 0.5.1 ,safe >= 0.2 ,shakespeare-text == 1.0.* ,split >= 0.1 && < 0.3 ,tabular >= 0.2 && < 0.3 ,text >= 0.11 && < 1.1 ,time ,utf8-string >= 0.3.5 && < 0.4 default-language: Haskell2010 test-suite tests type: exitcode-stdio-1.0 main-is: tests/suite.hs ghc-options: -Wall build-depends: hledger-lib , hledger , base >= 4.3 && < 5 , cmdargs , containers , csv , data-pprint >= 0.2.1 && < 0.3 , directory , filepath , haskeline , HUnit , mtl , old-locale , old-time , parsec , pretty-show , process , regex-compat-tdfa , regexpr , safe , shakespeare-text , split ,tabular >= 0.2 && < 0.3 , test-framework , test-framework-hunit , text , time , transformers default-language: Haskell2010 hledger-0.22/LICENSE0000644000000000000000000010451312252750510012245 0ustar0000000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. 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. Copyright (C) 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 . 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: Copyright (C) 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 . 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 . hledger-0.22/hledger-cli.hs0000644000000000000000000000022312252750510013744 0ustar0000000000000000#!/usr/bin/env runhaskell -- the hledger command-line executable; see Hledger/Cli/Main.hs module Main (main) where import Hledger.Cli.Main (main) hledger-0.22/Hledger/0000755000000000000000000000000012252750510012606 5ustar0000000000000000hledger-0.22/Hledger/Cli.hs0000644000000000000000000003270212252750510013655 0ustar0000000000000000{-| Hledger.Cli re-exports the options, utilities and commands provided by the hledger command-line program. This module also aggregates the built-in unit tests defined throughout hledger and hledger-lib, and adds some more which are easier to define here. -} module Hledger.Cli ( module Hledger.Cli.Add, module Hledger.Cli.Balance, module Hledger.Cli.Balancesheet, module Hledger.Cli.Cashflow, module Hledger.Cli.Histogram, module Hledger.Cli.Incomestatement, module Hledger.Cli.Print, module Hledger.Cli.Register, module Hledger.Cli.Stats, module Hledger.Cli.Options, module Hledger.Cli.Utils, module Hledger.Cli.Version, tests_Hledger_Cli ) where import Data.Time.Calendar import Test.HUnit import Hledger import Hledger.Cli.Add import Hledger.Cli.Balance import Hledger.Cli.Balancesheet import Hledger.Cli.Cashflow import Hledger.Cli.Histogram import Hledger.Cli.Incomestatement import Hledger.Cli.Print import Hledger.Cli.Register import Hledger.Cli.Stats import Hledger.Cli.Options import Hledger.Cli.Utils import Hledger.Cli.Version tests_Hledger_Cli :: Test tests_Hledger_Cli = TestList [ tests_Hledger -- ,tests_Hledger_Cli_Add -- ,tests_Hledger_Cli_Balance ,tests_Hledger_Cli_Balancesheet ,tests_Hledger_Cli_Cashflow -- ,tests_Hledger_Cli_Histogram ,tests_Hledger_Cli_Incomestatement ,tests_Hledger_Cli_Options -- ,tests_Hledger_Cli_Print ,tests_Hledger_Cli_Register -- ,tests_Hledger_Cli_Stats ,"account directive" ~: let sameParse str1 str2 = do j1 <- readJournal Nothing Nothing Nothing str1 >>= either error' return j2 <- readJournal Nothing Nothing Nothing str2 >>= either error' return j1 `is` j2{filereadtime=filereadtime j1, files=files j1, jContext=jContext j1} in TestList [ "account directive 1" ~: sameParse "2008/12/07 One\n test:from $-1\n test:to $1\n" "!account test\n2008/12/07 One\n from $-1\n to $1\n" ,"account directive 2" ~: sameParse "2008/12/07 One\n test:foo:from $-1\n test:foo:to $1\n" "!account test\n!account foo\n2008/12/07 One\n from $-1\n to $1\n" ,"account directive 3" ~: sameParse "2008/12/07 One\n test:from $-1\n test:to $1\n" "!account test\n!account foo\n!end\n2008/12/07 One\n from $-1\n to $1\n" ,"account directive 4" ~: sameParse ("2008/12/07 One\n alpha $-1\n beta $1\n" ++ "!account outer\n2008/12/07 Two\n aigh $-2\n bee $2\n" ++ "!account inner\n2008/12/07 Three\n gamma $-3\n delta $3\n" ++ "!end\n2008/12/07 Four\n why $-4\n zed $4\n" ++ "!end\n2008/12/07 Five\n foo $-5\n bar $5\n" ) ("2008/12/07 One\n alpha $-1\n beta $1\n" ++ "2008/12/07 Two\n outer:aigh $-2\n outer:bee $2\n" ++ "2008/12/07 Three\n outer:inner:gamma $-3\n outer:inner:delta $3\n" ++ "2008/12/07 Four\n outer:why $-4\n outer:zed $4\n" ++ "2008/12/07 Five\n foo $-5\n bar $5\n" ) ,"account directive should preserve \"virtual\" posting type" ~: do j <- readJournal Nothing Nothing Nothing "!account test\n2008/12/07 One\n (from) $-1\n (to) $1\n" >>= either error' return let p = head $ tpostings $ head $ jtxns j assertBool "" $ (paccount p) == "test:from" assertBool "" $ (ptype p) == VirtualPosting ] ,"account aliases" ~: do j <- readJournal Nothing Nothing Nothing "!alias expenses = equity:draw:personal\n1/1\n (expenses:food) 1\n" >>= either error' return let p = head $ tpostings $ head $ jtxns j assertBool "" $ paccount p == "equity:draw:personal:food" ,"ledgerAccountNames" ~: ledgerAccountNames ledger7 `is` ["assets","assets:cash","assets:checking","assets:saving","equity","equity:opening balances", "expenses","expenses:food","expenses:food:dining","expenses:phone","expenses:vacation", "liabilities","liabilities:credit cards","liabilities:credit cards:discover"] -- ,"journalCanonicaliseAmounts" ~: -- "use the greatest precision" ~: -- (map asprecision $ journalAmountAndPriceCommodities $ journalCanonicaliseAmounts $ journalWithAmounts ["1","2.00"]) `is` [2,2] -- don't know what this should do -- ,"elideAccountName" ~: do -- (elideAccountName 50 "aaaaaaaaaaaaaaaaaaaa:aaaaaaaaaaaaaaaaaaaa:aaaaaaaaaaaaaaaaaaaa" -- `is` "aa:aaaaaaaaaaaaaaaaaaaa:aaaaaaaaaaaaaaaaaaaa") -- (elideAccountName 20 "aaaaaaaaaaaaaaaaaaaa:aaaaaaaaaaaaaaaaaaaa:aaaaaaaaaaaaaaaaaaaa" -- `is` "aa:aa:aaaaaaaaaaaaaa") ,"default year" ~: do j <- readJournal Nothing Nothing Nothing defaultyear_journal_str >>= either error' return tdate (head $ jtxns j) `is` fromGregorian 2009 1 1 return () ,"show dollars" ~: showAmount (usd 1) ~?= "$1.00" ,"show hours" ~: showAmount (hrs 1) ~?= "1.0h" ] -- fixtures/test data -- date1 = parsedate "2008/11/26" -- t1 = LocalTime date1 midday {- samplejournal = readJournal' sample_journal_str sample_journal_str = unlines ["; A sample journal file." ,";" ,"; Sets up this account tree:" ,"; assets" ,"; bank" ,"; checking" ,"; saving" ,"; cash" ,"; expenses" ,"; food" ,"; supplies" ,"; income" ,"; gifts" ,"; salary" ,"; liabilities" ,"; debts" ,"" ,"2008/01/01 income" ," assets:bank:checking $1" ," income:salary" ,"" ,"2008/06/01 gift" ," assets:bank:checking $1" ," income:gifts" ,"" ,"2008/06/02 save" ," assets:bank:saving $1" ," assets:bank:checking" ,"" ,"2008/06/03 * eat & shop" ," expenses:food $1" ," expenses:supplies $1" ," assets:cash" ,"" ,"2008/12/31 * pay off" ," liabilities:debts $1" ," assets:bank:checking" ,"" ,"" ,";final comment" ] -} defaultyear_journal_str = unlines ["Y2009" ,"" ,"01/01 A" ," a $1" ," b" ] -- write_sample_journal = writeFile "sample.journal" sample_journal_str -- entry2_str = unlines -- ["2007/01/27 * joes diner" -- ," expenses:food:dining $10.00" -- ," expenses:gifts $10.00" -- ," assets:checking $-20.00" -- ,"" -- ] -- entry3_str = unlines -- ["2007/01/01 * opening balance" -- ," assets:cash $4.82" -- ," equity:opening balances" -- ,"" -- ,"2007/01/01 * opening balance" -- ," assets:cash $4.82" -- ," equity:opening balances" -- ,"" -- ,"2007/01/28 coopportunity" -- ," expenses:food:groceries $47.18" -- ," assets:checking" -- ,"" -- ] -- periodic_entry1_str = unlines -- ["~ monthly from 2007/2/2" -- ," assets:saving $200.00" -- ," assets:checking" -- ,"" -- ] -- periodic_entry2_str = unlines -- ["~ monthly from 2007/2/2" -- ," assets:saving $200.00 ;auto savings" -- ," assets:checking" -- ,"" -- ] -- periodic_entry3_str = unlines -- ["~ monthly from 2007/01/01" -- ," assets:cash $4.82" -- ," equity:opening balances" -- ,"" -- ,"~ monthly from 2007/01/01" -- ," assets:cash $4.82" -- ," equity:opening balances" -- ,"" -- ] -- journal1_str = unlines -- ["" -- ,"2007/01/27 * joes diner" -- ," expenses:food:dining $10.00" -- ," expenses:gifts $10.00" -- ," assets:checking $-20.00" -- ,"" -- ,"" -- ,"2007/01/28 coopportunity" -- ," expenses:food:groceries $47.18" -- ," assets:checking $-47.18" -- ,"" -- ,"" -- ] -- journal2_str = unlines -- [";comment" -- ,"2007/01/27 * joes diner" -- ," expenses:food:dining $10.00" -- ," assets:checking $-47.18" -- ,"" -- ] -- journal3_str = unlines -- ["2007/01/27 * joes diner" -- ," expenses:food:dining $10.00" -- ,";intra-entry comment" -- ," assets:checking $-47.18" -- ,"" -- ] -- journal4_str = unlines -- ["!include \"somefile\"" -- ,"2007/01/27 * joes diner" -- ," expenses:food:dining $10.00" -- ," assets:checking $-47.18" -- ,"" -- ] -- journal5_str = "" -- journal6_str = unlines -- ["~ monthly from 2007/1/21" -- ," expenses:entertainment $16.23 ;netflix" -- ," assets:checking" -- ,"" -- ,"; 2007/01/01 * opening balance" -- ,"; assets:saving $200.04" -- ,"; equity:opening balances " -- ,"" -- ] -- journal7_str = unlines -- ["2007/01/01 * opening balance" -- ," assets:cash $4.82" -- ," equity:opening balances " -- ,"" -- ,"2007/01/01 * opening balance" -- ," income:interest $-4.82" -- ," equity:opening balances " -- ,"" -- ,"2007/01/02 * ayres suites" -- ," expenses:vacation $179.92" -- ," assets:checking " -- ,"" -- ,"2007/01/02 * auto transfer to savings" -- ," assets:saving $200.00" -- ," assets:checking " -- ,"" -- ,"2007/01/03 * poquito mas" -- ," expenses:food:dining $4.82" -- ," assets:cash " -- ,"" -- ,"2007/01/03 * verizon" -- ," expenses:phone $95.11" -- ," assets:checking " -- ,"" -- ,"2007/01/03 * discover" -- ," liabilities:credit cards:discover $80.00" -- ," assets:checking " -- ,"" -- ,"2007/01/04 * blue cross" -- ," expenses:health:insurance $90.00" -- ," assets:checking " -- ,"" -- ,"2007/01/05 * village market liquor" -- ," expenses:food:dining $6.48" -- ," assets:checking " -- ,"" -- ] journal7 = nulljournal {jtxns = [ txnTieKnot $ Transaction { tdate=parsedate "2007/01/01", tdate2=Nothing, tstatus=False, tcode="*", tdescription="opening balance", tcomment="", ttags=[], tpostings= ["assets:cash" `post` usd 4.82 ,"equity:opening balances" `post` usd (-4.82) ], tpreceding_comment_lines="" } , txnTieKnot $ Transaction { tdate=parsedate "2007/02/01", tdate2=Nothing, tstatus=False, tcode="*", tdescription="ayres suites", tcomment="", ttags=[], tpostings= ["expenses:vacation" `post` usd 179.92 ,"assets:checking" `post` usd (-179.92) ], tpreceding_comment_lines="" } , txnTieKnot $ Transaction { tdate=parsedate "2007/01/02", tdate2=Nothing, tstatus=False, tcode="*", tdescription="auto transfer to savings", tcomment="", ttags=[], tpostings= ["assets:saving" `post` usd 200 ,"assets:checking" `post` usd (-200) ], tpreceding_comment_lines="" } , txnTieKnot $ Transaction { tdate=parsedate "2007/01/03", tdate2=Nothing, tstatus=False, tcode="*", tdescription="poquito mas", tcomment="", ttags=[], tpostings= ["expenses:food:dining" `post` usd 4.82 ,"assets:cash" `post` usd (-4.82) ], tpreceding_comment_lines="" } , txnTieKnot $ Transaction { tdate=parsedate "2007/01/03", tdate2=Nothing, tstatus=False, tcode="*", tdescription="verizon", tcomment="", ttags=[], tpostings= ["expenses:phone" `post` usd 95.11 ,"assets:checking" `post` usd (-95.11) ], tpreceding_comment_lines="" } , txnTieKnot $ Transaction { tdate=parsedate "2007/01/03", tdate2=Nothing, tstatus=False, tcode="*", tdescription="discover", tcomment="", ttags=[], tpostings= ["liabilities:credit cards:discover" `post` usd 80 ,"assets:checking" `post` usd (-80) ], tpreceding_comment_lines="" } ] } ledger7 = ledgerFromJournal Any journal7 hledger-0.22/Hledger/Cli/0000755000000000000000000000000012252750510013315 5ustar0000000000000000hledger-0.22/Hledger/Cli/Incomestatement.hs0000644000000000000000000000223212252750510017007 0ustar0000000000000000{-# LANGUAGE QuasiQuotes, TemplateHaskell, OverloadedStrings, NoCPP #-} {-| The @incomestatement@ command prints a simple income statement (profit & loss) report. -} module Hledger.Cli.Incomestatement ( incomestatement ,tests_Hledger_Cli_Incomestatement ) where import qualified Data.Text.Lazy.IO as LT import Test.HUnit import Text.Shakespeare.Text import Hledger import Hledger.Cli.Options import Hledger.Cli.Balance -- | Print a simple income statement. incomestatement :: CliOpts -> Journal -> IO () incomestatement CliOpts{reportopts_=ropts} j = do d <- getCurrentDay let q = queryFromOpts d ropts incomereport@(_,income) = balanceReport ropts (And [q, journalIncomeAccountQuery j]) j expensereport@(_,expenses) = balanceReport ropts (And [q, journalExpenseAccountQuery j]) j total = income + expenses LT.putStr $ [lt|Income Statement Revenues: #{unlines $ balanceReportAsText ropts incomereport} Expenses: #{unlines $ balanceReportAsText ropts expensereport} Total: -------------------- #{padleft 20 $ showMixedAmountWithoutPrice total} |] tests_Hledger_Cli_Incomestatement :: Test tests_Hledger_Cli_Incomestatement = TestList [ ] hledger-0.22/Hledger/Cli/Register.hs0000644000000000000000000000711412252750510015440 0ustar0000000000000000{-| A ledger-compatible @register@ command. -} module Hledger.Cli.Register ( register ,postingsReportAsText -- ,showPostingWithBalanceForVty ,tests_Hledger_Cli_Register ) where import Data.List import Data.Maybe import Test.HUnit import Text.Printf import Hledger import Prelude hiding (putStr) import Hledger.Utils.UTF8IOCompat (putStr) import Hledger.Cli.Options -- | Print a (posting) register report. register :: CliOpts -> Journal -> IO () register opts@CliOpts{reportopts_=ropts} j = do d <- getCurrentDay putStr $ postingsReportAsText opts $ postingsReport ropts (queryFromOpts d ropts) j -- | Render a register report as plain text suitable for console output. postingsReportAsText :: CliOpts -> PostingsReport -> String postingsReportAsText opts = unlines . map (postingsReportItemAsText opts) . snd tests_postingsReportAsText = [ "postingsReportAsText" ~: do -- "unicode in register layout" ~: do j <- readJournal' "2009/01/01 * медвежья шкура\n расходы:покупки 100\n актив:наличные\n" let opts = defreportopts (postingsReportAsText defcliopts $ postingsReport opts (queryFromOpts (parsedate "2008/11/26") opts) j) `is` unlines ["2009/01/01 медвежья шкура расходы:покупки 100 100" ," актив:наличные -100 0"] ] -- | Render one register report line item as plain text. Layout is like so: -- @ -- <----------------------------- width (default: 80) ----------------------------> -- date (10) description (50%) account (50%) amount (12) balance (12) -- DDDDDDDDDD dddddddddddddddddddd aaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA -- -- date and description are shown for the first posting of a transaction only. -- @ postingsReportItemAsText :: CliOpts -> PostingsReportItem -> String postingsReportItemAsText opts (mdate, mdesc, p, b) = concatTopPadded [date, " ", desc, " ", acct, " ", amt, " ", bal] where totalwidth = case widthFromOpts opts of Left _ -> defaultWidth -- shouldn't happen Right (TotalWidth (Width w)) -> w Right (TotalWidth Auto) -> defaultWidth -- XXX Right (FieldWidths _) -> defaultWidth -- XXX datewidth = 10 amtwidth = 12 balwidth = 12 remaining = totalwidth - (datewidth + 1 + 2 + amtwidth + 2 + balwidth) (descwidth, acctwidth) | even r = (r', r') | otherwise = (r', r'+1) where r = remaining - 2 r' = r `div` 2 date = maybe (replicate datewidth ' ') (printf ("%-"++show datewidth++"s") . showDate) mdate desc = maybe (replicate descwidth ' ') (printf ("%-"++show descwidth++"s") . take descwidth . elideRight descwidth) mdesc acct = printf ("%-"++(show acctwidth)++"s") a where a = bracket $ elideAccountName awidth $ paccount p (bracket, awidth) = case ptype p of BalancedVirtualPosting -> (\s -> "["++s++"]", acctwidth-2) VirtualPosting -> (\s -> "("++s++")", acctwidth-2) _ -> (id,acctwidth) amt = padleft amtwidth $ showMixedAmountWithoutPrice $ pamount p bal = padleft balwidth $ showMixedAmountWithoutPrice b -- XXX -- showPostingWithBalanceForVty showtxninfo p b = postingsReportItemAsText defreportopts $ mkpostingsReportItem showtxninfo p b tests_Hledger_Cli_Register :: Test tests_Hledger_Cli_Register = TestList tests_postingsReportAsText hledger-0.22/Hledger/Cli/Tests.hs0000644000000000000000000000317412252750510014760 0ustar0000000000000000-- {-# OPTIONS_GHC -F -pgmF htfpp #-} {-# LANGUAGE CPP #-} {- | A simple test runner for hledger's built-in unit tests. -} module Hledger.Cli.Tests where import Control.Monad import System.Exit import Test.HUnit import Hledger import Hledger.Cli #ifdef TESTS import Test.Framework import {-@ HTF_TESTS @-} Hledger.Read.JournalReader -- | Run HTF unit tests and exit with success or failure. test' :: CliOpts -> IO () test' _opts = htfMain htf_importedTests #else -- | Run HUnit unit tests and exit with success or failure. test' :: CliOpts -> IO () test' opts = do results <- runTests opts if errors results > 0 || failures results > 0 then exitFailure else exitWith ExitSuccess -- | Run all or just the matched unit tests and return their HUnit result counts. runTests :: CliOpts -> IO Counts runTests = liftM (fst . flip (,) 0) . runTestTT . flatTests -- | Run all or just the matched unit tests until the first failure or -- error, returning the name of the problem test if any. runTestsTillFailure :: CliOpts -> IO (Maybe String) runTestsTillFailure _ = undefined -- do -- let ts = flatTests opts -- results = liftM (fst . flip (,) 0) $ runTestTT $ -- firstproblem = find (\counts -> ) -- | All or pattern-matched tests, as a flat list to show simple names. flatTests opts = TestList $ filter (matchesAccount (queryFromOpts nulldate $ reportopts_ opts) . testName) $ flattenTests tests_Hledger_Cli -- | All or pattern-matched tests, in the original suites to show hierarchical names. hierarchicalTests opts = filterTests (matchesAccount (queryFromOpts nulldate $ reportopts_ opts) . testName) tests_Hledger_Cli #endif hledger-0.22/Hledger/Cli/Add.hs0000644000000000000000000004145212252750510014347 0ustar0000000000000000{-# LANGUAGE ScopedTypeVariables, DeriveDataTypeable #-} {-| A history-aware add command to help with data entry. Note: this might not be sensible, but add has some aspirations of being both user-friendly and pipeable/scriptable and for this reason informational messages are mostly written to stderr rather than stdout. -} module Hledger.Cli.Add where import Control.Exception as E import Control.Monad import Control.Monad.Trans (liftIO) import Data.Char (toUpper, toLower) import Data.List import Data.Maybe import Data.Typeable (Typeable) import Safe (headDef, tailDef, headMay) import System.Console.Haskeline (InputT, runInputT, defaultSettings, setComplete, getInputLine) import System.Console.Haskeline.Completion import System.IO ( stderr, hPutStr, hPutStrLn ) import System.IO.Error import Text.ParserCombinators.Parsec import Text.Printf import qualified Data.Set as Set import Hledger import Prelude hiding (putStr, putStrLn, appendFile) import Hledger.Utils.UTF8IOCompat (putStr, putStrLn, appendFile) import Hledger.Cli.Options import Hledger.Cli.Register (postingsReportAsText) -- | Read multiple transactions from the console, prompting for each -- field, and append them to the journal file. If the journal came -- from stdin, this command has no effect. add :: CliOpts -> Journal -> IO () add opts j | f == "-" = return () | otherwise = do hPutStr stderr $ unlines [ "Adding transactions to journal file "++f ,"Provide field values at the prompts, or press enter to accept defaults." ,"Use readline keys to edit, use tab key to complete account names." ,"A code (in parentheses) may be entered following transaction dates." ,"A comment may be entered following descriptions or amounts." ,"If you make a mistake, enter < at any prompt to restart the transaction." ,"To complete a transaction, enter . when prompted." ,"To quit, press control-d or control-c." ] today <- showDate `fmap` getCurrentDay let args = words' $ query_ $ reportopts_ opts (defdate, moredefs) = headTailDef today args getAndAddTransactionsLoop j opts defdate moredefs `E.catch` (\e -> unless (isEOFError e) $ ioError e) where f = journalFilePath j -- | Loop reading transactions from the console, prompting for, -- validating, displaying and appending each one to the journal file, -- until end of input or ctrl-c (then raise an EOF exception). -- If provided, command-line arguments are used as defaults for the -- first transaction; otherwise defaults come from the most similar -- recent transaction in the journal. getAndAddTransactionsLoop :: Journal -> CliOpts -> String -> [String] -> IO () getAndAddTransactionsLoop j opts defdate moredefs = do hPrintf stderr "\nStarting a new transaction.\n" t <- getTransaction j opts defdate moredefs j' <- journalAddTransaction j opts t hPrintf stderr "Added to the journal.\n" let defdate' = showDate $ tdate t getAndAddTransactionsLoop j' opts defdate' [] -- | Read a single transaction from the console, with history-aware prompting, -- allowing the user to restart and confirm at the end. -- A default date, and zero or more defaults for subsequent fields, are provided. getTransaction :: Journal -> CliOpts -> String -> [String] -> IO Transaction getTransaction j opts defdate moredefs = do mt <- getTransactionOrRestart j opts defdate moredefs let restart = do hPrintf stderr "\nRestarting this transaction.\n" getTransaction j opts defdate moredefs case mt of Nothing -> restart Just t -> do hPrintf stderr "\nTransaction entered:\n%s" (show t) yn <- runInteractionDefault $ askFor "Accept this transaction" (Just "y") (Just $ \s -> map toLower s `elem` ["<","y","yes","n","no"]) case headMay $ map toLower yn of Just 'y' -> return t _ -> restart -- | Read a single transaction from the console, with history-aware prompting, -- or return nothing indicating that the user wants to restart entering this transaction. -- A default date, and zero or more defaults for subsequent fields, are provided. getTransactionOrRestart :: Journal -> CliOpts -> String -> [String] -> IO (Maybe Transaction) getTransactionOrRestart j opts defdate moredefs = do let dateandcodep = do {d <- smartdate; c <- optionMaybe code; many spacenonewline; eof; return (d, fromMaybe "" c)} datecodestr <- runInteractionDefault $ askFor "date" (Just defdate) (Just $ \s -> null s || s == "." || isRight (parseWithCtx nullctx dateandcodep $ lowercase s)) when (datecodestr == ".") $ ioError $ mkIOError eofErrorType "" Nothing Nothing today <- getCurrentDay let (sdate,code) = fromparse $ parseWithCtx nullctx dateandcodep datecodestr defday = fixSmartDate today $ fromparse $ (parse smartdate "" . lowercase) defdate datestr = showDate $ fixSmartDate defday sdate let (defdesc, moredefs') = headTailDef "" moredefs desc <- runInteractionDefault $ askFor "description" (Just defdesc) Nothing if desc == "<" then return Nothing else do let (description,comment) = (strip a, strip $ dropWhile (==';') b) where (a,b) = break (==';') desc getPostingsForTransactionWithHistory j opts datestr code description comment moredefs' data RestartEntryException = RestartEntryException deriving (Typeable,Show) instance Exception RestartEntryException -- | Information used as the basis for suggested account names, amounts etc. in add prompt. data PostingsState = PostingsState { psJournal :: Journal ,psAccept :: AccountName -> Bool ,psSuggestHistoricalAmount :: Bool ,psHistory :: Maybe [Posting] } -- | Loop reading postings from the console, until a valid balanced -- set of postings has been entered, then return the final transaction, -- or nothing indicating that the user wants to restart entering this transaction. getPostingsForTransactionWithHistory :: Journal -> CliOpts -> String -> String -> String -> String -> [String] -> IO (Maybe Transaction) getPostingsForTransactionWithHistory j opts datestr code description comment defargs = do today <- getCurrentDay let historymatches = transactionsSimilarTo j (queryFromOpts today $ reportopts_ opts) description bestmatch | not (null defargs) || null historymatches = Nothing | otherwise = Just $ snd $ head historymatches bestmatchpostings = maybe Nothing (Just . tpostings) bestmatch date = fixSmartDate today $ fromparse $ (parse smartdate "" . lowercase) datestr accept x = x == "." || (not . null) x && if no_new_accounts_ opts then x `elem` existingaccts else True existingaccts = journalAccountNames j getvalidpostings = do ps <- getPostingsLoop (PostingsState j accept True bestmatchpostings) [] defargs let t = nulltransaction{tdate=date ,tstatus=False ,tcode=code ,tdescription=description ,tcomment=comment ,tpostings=ps } either retry (return . Just) $ balanceTransaction Nothing t -- imprecise balancing where retry msg = liftIO (hPutStrLn stderr $ "\n" ++ (capitalize msg) ++ "please re-enter.") >> getvalidpostings when (isJust bestmatch) $ liftIO $ hPrintf stderr "\nUsing this existing transaction for defaults:\n%s" (show $ fromJust bestmatch) getvalidpostings `E.catch` \(_::RestartEntryException) -> return Nothing -- | Read postings from the command line until . is entered, generating -- useful defaults based on historical context and postings entered so far. getPostingsLoop :: PostingsState -> [Posting] -> [String] -> IO [Posting] getPostingsLoop st enteredps defargs = do let bestmatch | isNothing historicalps = Nothing | n <= length ps = Just $ ps !! (n-1) | otherwise = Nothing where Just ps = historicalps bestmatchacct = maybe Nothing (Just . showacctname) bestmatch defacct = maybe bestmatchacct Just $ headMay defargs defargs' = tailDef [] defargs ordot | null enteredps || length enteredrealps == 1 = "" :: String | otherwise = " (or . to complete this transaction)" account <- runInteraction j $ askFor (printf "account %d%s" n ordot) defacct (Just accept) when (account=="<") $ throwIO RestartEntryException if account=="." then if null enteredps then do hPutStrLn stderr $ "\nPlease enter some postings first." getPostingsLoop st enteredps defargs else return enteredps else do let defacctused = Just account == defacct historicalps' = if defacctused then historicalps else Nothing bestmatch' | isNothing historicalps' = Nothing | n <= length ps = Just $ ps !! (n-1) | otherwise = Nothing where Just ps = historicalps' defamountstr | isJust commandlineamt = commandlineamt | isJust bestmatch' && suggesthistorical = Just historicalamountstr | n > 1 = Just balancingamountstr | otherwise = Nothing where commandlineamt = headMay defargs' historicalamountstr = showMixedAmountWithPrecision p $ pamount $ fromJust bestmatch' balancingamountstr = showMixedAmountWithPrecision p $ negate $ sum $ map pamount enteredrealps -- what should this be ? -- 1 maxprecision (show all decimal places or none) ? -- 2 maxprecisionwithpoint (show all decimal places or .0 - avoids some but not all confusion with thousands separators) ? -- 3 canonical precision for this commodity in the journal ? -- 4 maximum precision entered so far in this transaction ? -- 5 3 or 4, whichever would show the most decimal places ? -- I think 1 or 4, whichever would show the most decimal places p = maxprecisionwithpoint defargs'' = tailDef [] defargs' amt <- runInteractionDefault $ askFor (printf "amount %d" n) defamountstr validateamount when (amt=="<") $ throwIO RestartEntryException let (amountstr,comment) = (strip a, strip $ dropWhile (==';') b) where (a,b) = break (==';') amt let a = fromparse $ runParser (amountp <|> return missingamt) ctx "" amountstr a' = fromparse $ runParser (amountp <|> return missingamt) nullctx "" amountstr wasdefamtused = Just (showAmount a) == defamountstr defcommodityadded | acommodity a == acommodity a' = Nothing | otherwise = Just $ acommodity a p = nullposting{paccount=stripbrackets account ,pamount=mixed a ,pcomment=comment ,ptype=postingtype account } st' = if wasdefamtused then st else st{psHistory=historicalps', psSuggestHistoricalAmount=False} when (isJust defcommodityadded) $ liftIO $ hPutStrLn stderr $ printf "using default commodity (%s)" (fromJust defcommodityadded) getPostingsLoop st' (enteredps ++ [p]) defargs'' where j = psJournal st historicalps = psHistory st ctx = jContext j accept = psAccept st suggesthistorical = psSuggestHistoricalAmount st n = length enteredps + 1 enteredrealps = filter isReal enteredps showacctname p = showAccountName Nothing (ptype p) $ paccount p postingtype ('[':_) = BalancedVirtualPosting postingtype ('(':_) = VirtualPosting postingtype _ = RegularPosting validateamount = Just $ \s -> (null s && not (null enteredrealps)) || s == "<" || (isRight (runParser (amountp >> many spacenonewline >> optional (char ';' >> many anyChar) >> eof) ctx "" s) && s /= ".") -- | Prompt for and read a string value, optionally with a default value -- and a validator. A validator causes the prompt to repeat until the -- input is valid. May also raise an EOF exception if control-d or control-c is pressed. askFor :: String -> Maybe String -> Maybe (String -> Bool) -> InputT IO String askFor prompt def validator = do l <- fmap (maybe eofErr id) $ getInputLine $ prompt ++ " ? " ++ maybe "" showdef def ++ ": " let input = if null l then fromMaybe l def else l case validator of Just valid -> if valid input then return input else askFor prompt def validator Nothing -> return input where showdef "" = "" showdef s = "[" ++ s ++ "]" eofErr = E.throw $ mkIOError eofErrorType "end of input" Nothing Nothing -- | Append this transaction to the journal's file, and to the journal's -- transaction list. journalAddTransaction :: Journal -> CliOpts -> Transaction -> IO Journal journalAddTransaction j@Journal{jtxns=ts} opts t = do let f = journalFilePath j appendToJournalFileOrStdout f $ showTransaction t when (debug_ opts > 0) $ do putStrLn $ printf "\nAdded transaction to %s:" f putStrLn =<< registerFromString (show t) return j{jtxns=ts++[t]} -- | Append a string, typically one or more transactions, to a journal -- file, or if the file is "-", dump it to stdout. Tries to avoid -- excess whitespace. appendToJournalFileOrStdout :: FilePath -> String -> IO () appendToJournalFileOrStdout f s | f == "-" = putStr s' | otherwise = appendFile f s' where s' = "\n" ++ ensureOneNewlineTerminated s -- | Replace a string's 0 or more terminating newlines with exactly one. ensureOneNewlineTerminated :: String -> String ensureOneNewlineTerminated = (++"\n") . reverse . dropWhile (=='\n') . reverse -- | Convert a string of journal data into a register report. registerFromString :: String -> IO String registerFromString s = do d <- getCurrentDay j <- readJournal' s return $ postingsReportAsText opts $ postingsReport ropts (queryFromOpts d ropts) j where ropts = defreportopts{empty_=True} opts = defcliopts{reportopts_=ropts} -- | Return a similarity measure, from 0 to 1, for two strings. -- This is Simon White's letter pairs algorithm from -- http://www.catalysoft.com/articles/StrikeAMatch.html -- with a modification for short strings. compareStrings :: String -> String -> Double compareStrings "" "" = 1 compareStrings (_:[]) "" = 0 compareStrings "" (_:[]) = 0 compareStrings (a:[]) (b:[]) = if toUpper a == toUpper b then 1 else 0 compareStrings s1 s2 = 2.0 * fromIntegral i / fromIntegral u where i = length $ intersect pairs1 pairs2 u = length pairs1 + length pairs2 pairs1 = wordLetterPairs $ uppercase s1 pairs2 = wordLetterPairs $ uppercase s2 wordLetterPairs = concatMap letterPairs . words letterPairs (a:b:rest) = [a,b] : letterPairs (b:rest) letterPairs _ = [] compareDescriptions :: [Char] -> [Char] -> Double compareDescriptions s t = compareStrings s' t' where s' = simplify s t' = simplify t simplify = filter (not . (`elem` "0123456789")) transactionsSimilarTo :: Journal -> Query -> String -> [(Double,Transaction)] transactionsSimilarTo j q s = sortBy compareRelevanceAndRecency $ filter ((> threshold).fst) [(compareDescriptions s $ tdescription t, t) | t <- ts] where compareRelevanceAndRecency (n1,t1) (n2,t2) = compare (n2,tdate t2) (n1,tdate t1) ts = filter (q `matchesTransaction`) $ jtxns j threshold = 0 runInteraction :: Journal -> InputT IO a -> IO a runInteraction j m = do let cc = completionCache j runInputT (setComplete (accountCompletion cc) defaultSettings) m runInteractionDefault :: InputT IO a -> IO a runInteractionDefault m = do runInputT (setComplete noCompletion defaultSettings) m -- A precomputed list of all accounts previously entered into the journal. type CompletionCache = [AccountName] completionCache :: Journal -> CompletionCache completionCache j = -- Only keep unique account names. Set.toList $ Set.fromList [paccount p | t <- jtxns j, p <- tpostings t] accountCompletion :: CompletionCache -> CompletionFunc IO accountCompletion cc = completeWord Nothing "" -- don't break words on whitespace, since account names -- can contain spaces. $ \s -> return $ map simpleCompletion $ filter (s `isPrefixOf`) cc capitalize :: String -> String capitalize "" = "" capitalize (c:cs) = toUpper c : cs headTailDef :: a -> [a] -> (a,[a]) headTailDef defhead as = (headDef defhead as, tailDef [] as) hledger-0.22/Hledger/Cli/Options.hs0000644000000000000000000006704612252750510015321 0ustar0000000000000000{-# LANGUAGE TemplateHaskell, ScopedTypeVariables, DeriveDataTypeable #-} {-| Command-line options for the hledger program, and related utilities. -} module Hledger.Cli.Options ( -- * cmdargs modes & flags -- | These tell cmdargs how to parse the command line arguments. -- There's one mode for each internal subcommand, plus a main mode. mainmode, activitymode, addmode, balancemode, balancesheetmode, cashflowmode, incomestatementmode, printmode, registermode, statsmode, testmode, convertmode, defCommandMode, argsFlag, helpflags, inputflags, reportflags, generalflagsgroup1, generalflagsgroup2, generalflagsgroup3, -- * raw options -- | To allow the cmdargs modes to be reused and extended by other -- packages (eg, add-ons which want to mimic the standard hledger -- options), we parse the command-line arguments to a simple -- association list, not a fixed ADT. RawOpts, inRawOpts, boolopt, intopt, maybeintopt, stringopt, maybestringopt, listofstringopt, setopt, setboolopt, -- * CLI options -- | Raw options are converted to a more convenient, -- package-specific options structure. This is the \"opts\" used -- throughout hledger CLI code. CliOpts(..), defcliopts, -- * CLI option accessors -- | Some options require more processing. Possibly these should be merged into argsToCliOpts. aliasesFromOpts, formatFromOpts, journalFilePathFromOpts, rulesFilePathFromOpts, OutputWidth(..), Width(..), defaultWidth, defaultWidthWithFlag, widthFromOpts, -- * utilities getHledgerAddonCommands, argsToCliOpts, moveFlagsAfterCommand, decodeRawOpts, checkCliOpts, rawOptsToCliOpts, optserror, showModeHelp, debugArgs, getCliOpts, -- * tests tests_Hledger_Cli_Options ) where import qualified Control.Exception as C -- import Control.Monad (filterM) import Control.Monad (when) import Data.Char (isDigit) import Data.List import Data.List.Split import Data.Maybe import Data.Time.Calendar import Safe import System.Console.CmdArgs import System.Console.CmdArgs.Explicit import System.Console.CmdArgs.Text import System.Directory import System.Environment import System.Exit import Test.HUnit import Text.ParserCombinators.Parsec as P import Text.Printf import Hledger import Hledger.Data.FormatStrings as Format import Hledger.Cli.Version -- -- 1. cmdargs mode and flag (option) definitions for the hledger CLI, -- can be reused by other packages as well. -- -- | Our cmdargs modes parse arguments into an association list for better reuse. type RawOpts = [(String,String)] -- common flags and flag groups -- | Common help flags: --help, --debug, --version... helpflags = [ flagNone ["help","h","?"] (setboolopt "help") "Display general help or (with --help after COMMAND) command help." -- ,flagNone ["browse-args"] (setboolopt "browse-args") "use a web UI to select options and build up a command line" ,flagOpt "1" ["debug"] (\s opts -> Right $ setopt "debug" s opts) "N" "Show debug output (optional argument sets debug level)" ,flagNone ["version"] (setboolopt "version") "Print version information" ] -- | Common input-related flags: --file, --rules-file, --alias... inputflags = [ flagReq ["file","f"] (\s opts -> Right $ setopt "file" s opts) "FILE" "use a different journal file; - means stdin" ,flagReq ["rules-file"] (\s opts -> Right $ setopt "rules-file" s opts) "RULESFILE" "conversion rules for CSV (default: FILE.rules)" ,flagReq ["alias"] (\s opts -> Right $ setopt "alias" s opts) "ACCT=ALIAS" "convert ACCT's name to ALIAS" ] -- | Common report-related flags: --period, --cost, --display etc. reportflags = [ flagReq ["begin","b"] (\s opts -> Right $ setopt "begin" s opts) "DATE" "report on transactions on or after this date" ,flagReq ["end","e"] (\s opts -> Right $ setopt "end" s opts) "DATE" "report on transactions before this date" ,flagReq ["period","p"] (\s opts -> Right $ setopt "period" s opts) "PERIODEXP" "report on transactions during the specified period and/or with the specified reporting interval" ,flagNone ["daily","D"] (\opts -> setboolopt "daily" opts) "report by day" ,flagNone ["weekly","W"] (\opts -> setboolopt "weekly" opts) "report by week" ,flagNone ["monthly","M"] (\opts -> setboolopt "monthly" opts) "report by month" ,flagNone ["quarterly","Q"] (\opts -> setboolopt "quarterly" opts) "report by quarter" ,flagNone ["yearly","Y"] (\opts -> setboolopt "yearly" opts) "report by year" ,flagNone ["cleared","C"] (\opts -> setboolopt "cleared" opts) "report only on cleared transactions" ,flagNone ["uncleared","U"] (\opts -> setboolopt "uncleared" opts) "report only on uncleared transactions" ,flagNone ["cost","B"] (\opts -> setboolopt "cost" opts) "report cost of commodities" ,flagReq ["depth"] (\s opts -> Right $ setopt "depth" s opts) "N" "hide accounts/transactions deeper than this" ,flagReq ["display","d"] (\s opts -> Right $ setopt "display" s opts) "DISPLAYEXP" "show only transactions matching the expression, which is 'dOP[DATE]' where OP is <, <=, =, >=, >" ,flagNone ["date2","aux-date","effective"] (\opts -> setboolopt "date2" opts) "use transactions' secondary dates, if any" ,flagNone ["empty","E"] (\opts -> setboolopt "empty" opts) "show empty/zero things which are normally elided" ,flagNone ["real","R"] (\opts -> setboolopt "real" opts) "report only on real (non-virtual) transactions" ] argsFlag desc = flagArg (\s opts -> Right $ setopt "args" s opts) desc generalflagstitle = "\nGeneral flags" generalflagsgroup1 = (generalflagstitle, inputflags ++ reportflags ++ helpflags) generalflagsgroup2 = (generalflagstitle, inputflags ++ helpflags) generalflagsgroup3 = (generalflagstitle, helpflags) -- cmdargs modes -- | A basic mode template. defMode :: Mode RawOpts defMode = Mode { modeNames = [] ,modeHelp = "" ,modeHelpSuffix = [] ,modeValue = [] ,modeCheck = Right ,modeReform = const Nothing ,modeExpandAt = True ,modeGroupFlags = Group { groupNamed = [] ,groupUnnamed = [ flagNone ["help","h","?"] (setboolopt "help") "Display command help." ] ,groupHidden = [] } ,modeArgs = ([], Nothing) ,modeGroupModes = toGroup [] } -- | A basic subcommand mode with the given command name(s). defCommandMode names = defMode { modeNames=names ,modeValue=[("command", headDef "" names)] ,modeArgs = ([], Just $ argsFlag "[PATTERNS]") } -- | A basic subcommand mode suitable for an add-on command. defAddonCommandMode addon = defMode { modeNames = [addon] ,modeHelp = printf "run %s-%s" progname addon ,modeValue=[("command",addon)] ,modeGroupFlags = Group { groupUnnamed = [] ,groupHidden = [] ,groupNamed = [generalflagsgroup1] } ,modeArgs = ([], Just $ argsFlag "[ARGS]") } -- | Add command aliases to the command's help string. withAliases :: String -> [String] -> String s `withAliases` [] = s s `withAliases` (a:[]) = s ++ " (alias: " ++ a ++ ")" s `withAliases` as = s ++ " (aliases: " ++ intercalate ", " as ++ ")" -- | The top-level cmdargs mode for hledger. mainmode addons = defMode { modeNames = [progname] ,modeHelp = unlines [ "run the specified hledger command. Commands:" ] ,modeHelpSuffix = [""] ,modeArgs = ([], Just $ argsFlag "[ARGS]") ,modeGroupModes = Group { -- modes (commands) in named groups: groupNamed = [ ("Adding data", [ addmode ]) ,("\nBasic reports", [ printmode ,balancemode ,registermode -- ,transactionsmode ]) ,("\nMore reports", [ activitymode ,incomestatementmode ,balancesheetmode ,cashflowmode ,statsmode ]) ,("\nMiscellaneous", [ testmode ]) ] ++ case addons of [] -> [] cs -> [("\nAdd-on commands found", map defAddonCommandMode cs)] -- modes in the unnamed group, shown first without a heading: ,groupUnnamed = [ ] -- modes handled but not shown ,groupHidden = [ convertmode ] } ,modeGroupFlags = Group { -- flags in named groups: groupNamed = [generalflagsgroup3] -- flags in the unnamed group, shown last without a heading: ,groupUnnamed = [] -- flags accepted but not shown in the help: ,groupHidden = inputflags -- included here so they'll not raise a confusing error if present with no COMMAND } } -- help_postscript = [ -- -- "DATES can be Y/M/D or smart dates like \"last month\"." -- -- ,"PATTERNS are regular" -- -- ,"expressions which filter by account name. Prefix a pattern with desc: to" -- -- ,"filter by transaction description instead, prefix with not: to negate it." -- -- ,"When using both, not: comes last." -- ] -- visible subcommand modes addmode = (defCommandMode ["add"]) { modeHelp = "prompt for new transaction entries and add them to the journal" ,modeHelpSuffix = ["Defaults come from previous similar transactions; use query patterns to restrict these."] ,modeGroupFlags = Group { groupUnnamed = [ flagNone ["no-new-accounts"] (\opts -> setboolopt "no-new-accounts" opts) "don't allow creating new accounts" ] ,groupHidden = [] ,groupNamed = [generalflagsgroup2] } } balancemode = (defCommandMode $ ["balance"] ++ aliases) { modeHelp = "show matched accounts and their balances" `withAliases` aliases ,modeGroupFlags = Group { groupUnnamed = [ flagNone ["cumulative"] (\opts -> setboolopt "cumulative" opts) "with a reporting interval, show accumulated totals starting from 0" ,flagNone ["historical","H"] (\opts -> setboolopt "historical" opts) "with a reporting interval, show accurate historical ending balances" ,flagNone ["flat"] (\opts -> setboolopt "flat" opts) "show full account names, unindented" ,flagReq ["drop"] (\s opts -> Right $ setopt "drop" s opts) "N" "with --flat, omit this many leading account name components" ,flagReq ["format"] (\s opts -> Right $ setopt "format" s opts) "FORMATSTR" "use this custom line format" ,flagNone ["no-elide"] (\opts -> setboolopt "no-elide" opts) "no eliding at all, stronger than --empty" ,flagNone ["no-total"] (\opts -> setboolopt "no-total" opts) "don't show the final total" ] ,groupHidden = [] ,groupNamed = [generalflagsgroup1] } } where aliases = ["b","bal"] printmode = (defCommandMode $ ["print"] ++ aliases) { modeHelp = "show matched journal entries" `withAliases` aliases ,modeGroupFlags = Group { groupUnnamed = [] ,groupHidden = [] ,groupNamed = [generalflagsgroup1] } } where aliases = ["p"] registermode = (defCommandMode $ ["register"] ++ aliases) { modeHelp = "show matched postings and running total" `withAliases` aliases ,modeGroupFlags = Group { groupUnnamed = [ flagOpt (show defaultWidthWithFlag) ["width","w"] (\s opts -> Right $ setopt "width" s opts) "N" "increase or set the output width (default: 80)" ,flagNone ["average","A"] (\opts -> setboolopt "average" opts) "show the running average instead of the running total" ,flagNone ["related","r"] (\opts -> setboolopt "related" opts) "show the other postings in the transactions of those that would have been shown" ] ,groupHidden = [] ,groupNamed = [generalflagsgroup1] } } where aliases = ["r","reg"] -- transactionsmode = (defCommandMode ["transactions"]) { -- modeHelp = "show matched transactions and balance in some account(s)" -- ,modeGroupFlags = Group { -- groupUnnamed = [] -- ,groupHidden = [] -- ,groupNamed = [generalflagsgroup1] -- } -- } activitymode = (defCommandMode ["activity"]) { modeHelp = "show a barchart of transactions per interval" ,modeHelpSuffix = ["The default interval is daily."] ,modeGroupFlags = Group { groupUnnamed = [] ,groupHidden = [] ,groupNamed = [generalflagsgroup1] } } incomestatementmode = (defCommandMode $ ["incomestatement"]++aliases) { modeHelp = "show a simple income statement" `withAliases` aliases ,modeGroupFlags = Group { groupUnnamed = [] ,groupHidden = [] ,groupNamed = [generalflagsgroup1] } } where aliases = ["is","pl"] balancesheetmode = (defCommandMode $ ["balancesheet"]++aliases) { modeHelp = "show a simple balance sheet" `withAliases` aliases ,modeGroupFlags = Group { groupUnnamed = [] ,groupHidden = [] ,groupNamed = [generalflagsgroup1] } } where aliases = ["bs"] cashflowmode = (defCommandMode ["cashflow","cf"]) { modeHelp = "show a simple cashflow statement" `withAliases` ["cf"] ,modeGroupFlags = Group { groupUnnamed = [] ,groupHidden = [] ,groupNamed = [generalflagsgroup1] } } statsmode = (defCommandMode $ ["stats"] ++ aliases) { modeHelp = "show quick statistics for a journal" `withAliases` aliases ,modeGroupFlags = Group { groupUnnamed = [] ,groupHidden = [] ,groupNamed = [generalflagsgroup1] } } where aliases = ["s"] testmode = (defCommandMode ["test"]) { modeHelp = "run self-tests, or just the ones matching REGEXPS" ,modeArgs = ([], Just $ argsFlag "[REGEXPS]") ,modeGroupFlags = Group { groupUnnamed = [] ,groupHidden = [] ,groupNamed = [generalflagsgroup3] } } -- hidden commands convertmode = (defCommandMode ["convert"]) { modeValue = [("command","convert")] ,modeHelp = "convert is no longer needed, just use -f FILE.csv" ,modeArgs = ([], Just $ argsFlag "[CSVFILE]") ,modeGroupFlags = Group { groupUnnamed = [] ,groupHidden = helpflags ,groupNamed = [] } } -- -- 2. A package-specific data structure holding options used in this -- package and above, parsed from RawOpts. This represents the -- command-line options that were provided, with all parsing -- completed, but before adding defaults or derived values (XXX add) -- -- | Command line options. Used in the @hledger@ package and above. data CliOpts = CliOpts { rawopts_ :: RawOpts ,command_ :: String ,file_ :: Maybe FilePath ,rules_file_ :: Maybe FilePath ,alias_ :: [String] ,debug_ :: Int -- ^ debug level, set by @--debug[=N]@. See also 'Hledger.Utils.debugLevel'. ,no_new_accounts_ :: Bool -- add ,width_ :: Maybe String -- register ,reportopts_ :: ReportOpts } deriving (Show, Data, Typeable) defcliopts = CliOpts def def def def def def def def def instance Default CliOpts where def = defcliopts -- | Parse raw option string values to the desired final data types. -- Any relative smart dates will be converted to fixed dates based on -- today's date. Parsing failures will raise an error. rawOptsToCliOpts :: RawOpts -> IO CliOpts rawOptsToCliOpts rawopts = do d <- getCurrentDay return defcliopts { rawopts_ = rawopts ,command_ = stringopt "command" rawopts ,file_ = maybestringopt "file" rawopts ,rules_file_ = maybestringopt "rules-file" rawopts ,alias_ = map stripquotes $ listofstringopt "alias" rawopts ,debug_ = intopt "debug" rawopts ,no_new_accounts_ = boolopt "no-new-accounts" rawopts -- add ,width_ = maybestringopt "width" rawopts -- register ,reportopts_ = defreportopts { begin_ = maybesmartdateopt d "begin" rawopts ,end_ = maybesmartdateopt d "end" rawopts ,period_ = maybeperiodopt d rawopts ,cleared_ = boolopt "cleared" rawopts ,uncleared_ = boolopt "uncleared" rawopts ,cost_ = boolopt "cost" rawopts ,depth_ = maybeintopt "depth" rawopts ,display_ = maybedisplayopt d rawopts ,date2_ = boolopt "date2" rawopts ,empty_ = boolopt "empty" rawopts ,no_elide_ = boolopt "no-elide" rawopts ,real_ = boolopt "real" rawopts ,balancetype_ = balancetypeopt rawopts -- balance ,flat_ = boolopt "flat" rawopts -- balance ,drop_ = intopt "drop" rawopts -- balance ,no_total_ = boolopt "no-total" rawopts -- balance ,daily_ = boolopt "daily" rawopts ,weekly_ = boolopt "weekly" rawopts ,monthly_ = boolopt "monthly" rawopts ,quarterly_ = boolopt "quarterly" rawopts ,yearly_ = boolopt "yearly" rawopts ,format_ = maybestringopt "format" rawopts ,average_ = boolopt "average" rawopts -- register ,related_ = boolopt "related" rawopts -- register ,query_ = unwords $ listofstringopt "args" rawopts } } -- | Parse hledger CLI options from these command line arguments and -- add-on command names, or raise any error. argsToCliOpts :: [String] -> [String] -> IO CliOpts argsToCliOpts args addons = do let args' = moveFlagsAfterCommand args cmdargsopts = System.Console.CmdArgs.Explicit.processValue (mainmode addons) args' cmdargsopts' = decodeRawOpts cmdargsopts rawOptsToCliOpts cmdargsopts' >>= checkCliOpts -- | A hacky workaround for cmdargs not accepting flags before the -- subcommand name: try to detect and move such flags after the -- command. This allows the user to put them in either position. -- The order of options is not preserved, but this should be ok. -- -- Since we're not parsing flags as precisely as cmdargs here, this is -- imperfect. We make a decent effort to: -- - move all no-argument help and input flags -- - move all required-argument help and input flags along with their values, space-separated or not -- - not confuse things further or cause misleading errors. moveFlagsAfterCommand :: [String] -> [String] moveFlagsAfterCommand args = move args where move (f:a:as) | isMovableNoArgFlag f = (move $ a:as) ++ [f] move (f:v:a:as) | isMovableReqArgFlag f = (move $ a:as) ++ [f,v] move (fv:a:as) | isMovableReqArgFlagAndValue fv = (move $ a:as) ++ [fv] move ("--debug":v:a:as) | not (null v) && all isDigit v = (move $ a:as) ++ ["--debug",v] move ("--debug":a:as) = (move $ a:as) ++ ["--debug"] move (fv@('-':'-':'d':'e':'b':'u':'g':'=':_):a:as) = (move $ a:as) ++ [fv] move as = as isMovableNoArgFlag a = "-" `isPrefixOf` a && dropWhile (=='-') a `elem` noargflagstomove isMovableReqArgFlag a = "-" `isPrefixOf` a && dropWhile (=='-') a `elem` reqargflagstomove isMovableReqArgFlagAndValue ('-':'-':a:as) = case break (== '=') (a:as) of (f:fs,_) -> (f:fs) `elem` reqargflagstomove _ -> False isMovableReqArgFlagAndValue ('-':f:_:_) = [f] `elem` reqargflagstomove isMovableReqArgFlagAndValue _ = False noargflagstomove = concatMap flagNames $ filter ((==FlagNone).flagInfo) flagstomove reqargflagstomove = concatMap flagNames $ filter ((==FlagReq ).flagInfo) flagstomove flagstomove = inputflags ++ helpflags -- | Convert possibly encoded option values to regular unicode strings. decodeRawOpts = map (\(name,val) -> (name, fromSystemString val)) -- | Do final validation of processed opts, raising an error if there is trouble. checkCliOpts :: CliOpts -> IO CliOpts -- or pure.. checkCliOpts opts@CliOpts{reportopts_=ropts} = do case formatFromOpts ropts of Left err -> optserror $ "could not parse format option: "++err Right _ -> return () case widthFromOpts opts of Left err -> optserror $ "could not parse width option: "++err Right _ -> return () return opts -- -- utils -- -- | Get the unique suffixes (without hledger-) of hledger-* executables -- found in the current user's PATH, or the empty list if there is any -- problem. getHledgerAddonCommands :: IO [String] getHledgerAddonCommands = map (drop (length progname + 1)) `fmap` getHledgerExesInPath -- | Get the unique names of hledger-*{,.hs} executables found in the current -- user's PATH, or the empty list if there is any problem. getHledgerExesInPath :: IO [String] getHledgerExesInPath = do pathdirs <- splitOn ":" `fmap` getEnvSafe "PATH" pathfiles <- concat `fmap` mapM getDirectoryContentsSafe pathdirs let hledgernamed = nub $ sort $ filter isHledgerNamed pathfiles -- hledgerexes <- filterM isExecutable hledgernamed return hledgernamed -- isExecutable f = getPermissions f >>= (return . executable) isHledgerNamed = isRight . parsewith (do string progname char '-' many1 (letter <|> char '-') optional $ (string ".hs" <|> string ".lhs") eof ) getEnvSafe v = getEnv v `C.catch` (\(_::C.IOException) -> return "") getDirectoryContentsSafe d = getDirectoryContents d `C.catch` (\(_::C.IOException) -> return []) -- | Raise an error, showing the specified message plus a hint about --help. optserror = error' . (++ " (run with --help for usage)") setopt name val = (++ [(name,singleQuoteIfNeeded val)]) setboolopt name = (++ [(name,"")]) -- | Is the named option present ? inRawOpts :: String -> RawOpts -> Bool inRawOpts name = isJust . lookup name boolopt = inRawOpts maybestringopt name = maybe Nothing (Just . stripquotes) . lookup name stringopt name = fromMaybe "" . maybestringopt name listofstringopt name rawopts = [v | (k,v) <- rawopts, k==name] maybeintopt :: String -> RawOpts -> Maybe Int maybeintopt name rawopts = let ms = maybestringopt name rawopts in case ms of Nothing -> Nothing Just s -> Just $ readDef (optserror $ "could not parse "++name++" number: "++s) s intopt name = fromMaybe 0 . maybeintopt name maybesmartdateopt :: Day -> String -> RawOpts -> Maybe Day maybesmartdateopt d name rawopts = case maybestringopt name rawopts of Nothing -> Nothing Just s -> either (\e -> optserror $ "could not parse "++name++" date: "++show e) Just $ fixSmartDateStrEither' d s maybedisplayopt :: Day -> RawOpts -> Maybe DisplayExp maybedisplayopt d rawopts = maybe Nothing (Just . regexReplaceBy "\\[.+?\\]" fixbracketeddatestr) $ maybestringopt "display" rawopts where fixbracketeddatestr "" = "" fixbracketeddatestr s = "[" ++ fixSmartDateStr d (init $ tail s) ++ "]" maybeperiodopt :: Day -> RawOpts -> Maybe (Interval,DateSpan) maybeperiodopt d rawopts = case maybestringopt "period" rawopts of Nothing -> Nothing Just s -> either (\e -> optserror $ "could not parse period option: "++show e) Just $ parsePeriodExpr d s balancetypeopt :: RawOpts -> BalanceType balancetypeopt rawopts | length [o | o <- ["cumulative","historical"], isset o] > 1 = optserror "please specify at most one of --cumulative and --historical" | isset "cumulative" = CumulativeBalance | isset "historical" = HistoricalBalance | otherwise = PeriodBalance where isset = flip boolopt rawopts -- | Parse the format option if provided, possibly returning an error, -- otherwise get the default value. formatFromOpts :: ReportOpts -> Either String [FormatString] formatFromOpts = maybe (Right defaultBalanceFormatString) parseFormatString . format_ -- | Default line format for balance report: "%20(total) %2(depth_spacer)%-(account)" defaultBalanceFormatString :: [FormatString] defaultBalanceFormatString = [ FormatField False (Just 20) Nothing TotalField , FormatLiteral " " , FormatField True (Just 2) Nothing DepthSpacerField , FormatField True Nothing Nothing AccountField ] -- | Output width configuration (for register). data OutputWidth = TotalWidth Width -- ^ specify the overall width | FieldWidths [Width] -- ^ specify each field's width deriving Show -- | A width value. data Width = Width Int -- ^ set width to exactly this number of characters | Auto -- ^ set width automatically from available space deriving Show -- | Default width of hledger console output. defaultWidth = 80 -- | Width of hledger console output when the -w flag is used with no value. defaultWidthWithFlag = 120 -- | Parse the width option if provided, possibly returning an error, -- otherwise get the default value. widthFromOpts :: CliOpts -> Either String OutputWidth widthFromOpts CliOpts{width_=Nothing} = Right $ TotalWidth $ Width defaultWidth widthFromOpts CliOpts{width_=Just ""} = Right $ TotalWidth $ Width defaultWidthWithFlag widthFromOpts CliOpts{width_=Just s} = parseWidth s parseWidth :: String -> Either String OutputWidth parseWidth s = case (runParser outputwidthp () "(unknown)") s of Left e -> Left $ show e Right x -> Right x outputwidthp :: GenParser Char st OutputWidth outputwidthp = try (do w <- widthp ws <- many1 (char ',' >> widthp) return $ FieldWidths $ w:ws) <|> TotalWidth `fmap` widthp widthp :: GenParser Char st Width widthp = (string "auto" >> return Auto) <|> (Width . read) `fmap` many1 digit -- | Get the account name aliases from options, if any. aliasesFromOpts :: CliOpts -> [(AccountName,AccountName)] aliasesFromOpts = map parseAlias . alias_ where -- similar to ledgerAlias parseAlias :: String -> (AccountName,AccountName) parseAlias s = (accountNameWithoutPostingType $ strip orig ,accountNameWithoutPostingType $ strip alias') where (orig, alias) = break (=='=') s alias' = case alias of ('=':rest) -> rest _ -> orig -- | Get the (tilde-expanded, absolute) journal file path from -- 1. options, 2. an environment variable, or 3. the default. journalFilePathFromOpts :: CliOpts -> IO String journalFilePathFromOpts opts = do f <- defaultJournalPath d <- getCurrentDirectory expandPath d $ fromMaybe f $ file_ opts -- | Get the (tilde-expanded) rules file path from options, if any. rulesFilePathFromOpts :: CliOpts -> IO (Maybe FilePath) rulesFilePathFromOpts opts = do d <- getCurrentDirectory maybe (return Nothing) (fmap Just . expandPath d) $ rules_file_ opts -- | Get a mode's help message as a nicely wrapped string. showModeHelp :: Mode a -> String showModeHelp = (showText defaultWrap :: [Text] -> String) . (helpText [] HelpFormatDefault :: Mode a -> [Text]) -- not used: -- | Print debug info about arguments and options if --debug is present. debugArgs :: [String] -> CliOpts -> IO () debugArgs args opts = when ("--debug" `elem` args) $ do progname <- getProgName putStrLn $ "running: " ++ progname putStrLn $ "raw args: " ++ show args putStrLn $ "processed opts:\n" ++ show opts d <- getCurrentDay putStrLn $ "search query: " ++ (show $ queryFromOpts d $ reportopts_ opts) -- not used: -- | Parse hledger CLI options from the command line using the given -- cmdargs mode, and either return them or, if a help flag is present, -- print the mode help and exit the program. getCliOpts :: Mode RawOpts -> IO CliOpts getCliOpts mode = do args <- getArgs let rawopts = decodeRawOpts $ processValue mode args opts <- rawOptsToCliOpts rawopts >>= checkCliOpts debugArgs args opts -- if any (`elem` args) ["--help","-h","-?"] when ("help" `inRawOpts` rawopts_ opts) $ putStr (showModeHelp mode) >> exitSuccess return opts tests_Hledger_Cli_Options = TestList [ ] hledger-0.22/Hledger/Cli/Cashflow.hs0000644000000000000000000000265212252750510015424 0ustar0000000000000000{-# LANGUAGE QuasiQuotes, RecordWildCards, NoCPP #-} {-| The @cashflow@ command prints a simplified cashflow statement. It just shows the change in all "cash" accounts for the period (without the traditional segmentation into operating, investing, and financing cash flows.) -} module Hledger.Cli.Cashflow ( cashflow ,tests_Hledger_Cli_Cashflow ) where import qualified Data.Text.Lazy.IO as LT import Test.HUnit import Text.Shakespeare.Text import Hledger import Hledger.Cli.Options import Hledger.Cli.Balance -- | Print a simple cashflow statement. cashflow :: CliOpts -> Journal -> IO () cashflow CliOpts{reportopts_=ropts} j = do -- let lines = case formatFromOpts ropts of Left err, Right ... d <- getCurrentDay let q = queryFromOpts d ropts cashreport@(_,total) = balanceReport ropts (And [q, journalCashAccountQuery j]) j -- operatingreport@(_,operating) = balanceReport ropts (And [q, journalOperatingAccountMatcher j]) j -- investingreport@(_,investing) = balanceReport ropts (And [q, journalInvestingAccountMatcher j]) j -- financingreport@(_,financing) = balanceReport ropts (And [q, journalFinancingAccountMatcher j]) j -- total = operating + investing + financing LT.putStr $ [lt|Cashflow Statement Cash flows: #{unlines $ balanceReportAsText ropts cashreport} Total: -------------------- #{padleft 20 $ showMixedAmountWithoutPrice total} |] tests_Hledger_Cli_Cashflow = TestList [ ] hledger-0.22/Hledger/Cli/Utils.hs0000644000000000000000000001610512252750510014754 0ustar0000000000000000{-# LANGUAGE ScopedTypeVariables, CPP #-} {-| Utilities for top-level modules and ghci. See also Hledger.Read and Hledger.Utils. -} module Hledger.Cli.Utils ( withJournalDo, journalReload, journalReloadIfChanged, journalFileIsNewer, journalSpecifiedFileIsNewer, fileModificationTime, openBrowserOn, writeFileWithBackup, writeFileWithBackupIfChanged, readFileStrictly, Test(TestList), ) where import Control.Exception as C import Data.List import Data.Maybe import Safe (readMay) import System.Console.CmdArgs import System.Directory (getModificationTime, getDirectoryContents, copyFile) import System.Exit import System.FilePath ((), splitFileName, takeDirectory) import System.Info (os) import System.Process (readProcessWithExitCode) import System.Time (ClockTime, getClockTime, diffClockTimes, TimeDiff(TimeDiff)) import Test.HUnit import Text.Printf -- kludge - adapt to whichever directory version is installed, or when -- cabal macros aren't available, assume the new directory #ifdef MIN_VERSION_directory #if MIN_VERSION_directory(1,2,0) #define directory_1_2 #endif #else #define directory_1_2 #endif #ifdef directory_1_2 import System.Time (ClockTime(TOD)) import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds) #endif import Hledger.Cli.Options import Hledger.Data import Hledger.Read import Hledger.Utils -- | Parse the user's specified journal file and run a hledger command on -- it, or throw an error. withJournalDo :: CliOpts -> (CliOpts -> Journal -> IO ()) -> IO () withJournalDo opts cmd = do -- We kludgily read the file before parsing to grab the full text, unless -- it's stdin, or it doesn't exist and we are adding. We read it strictly -- to let the add command work. rulespath <- rulesFilePathFromOpts opts journalpath <- journalFilePathFromOpts opts ej <- readJournalFile Nothing rulespath journalpath either error' (cmd opts . journalApplyAliases (aliasesFromOpts opts)) ej -- -- | Get a journal from the given string and options, or throw an error. -- readJournalWithOpts :: CliOpts -> String -> IO Journal -- readJournalWithOpts opts s = readJournal Nothing Nothing Nothing s >>= either error' return -- | Re-read a journal from its data file, or return an error string. journalReload :: Journal -> IO (Either String Journal) journalReload j = readJournalFile Nothing Nothing $ journalFilePath j -- | Re-read a journal from its data file mostly, only if the file has -- changed since last read (or if there is no file, ie data read from -- stdin). The provided options are mostly ignored. Return a journal or -- the error message while reading it, and a flag indicating whether it -- was re-read or not. journalReloadIfChanged :: CliOpts -> Journal -> IO (Either String Journal, Bool) journalReloadIfChanged _ j = do let maybeChangedFilename f = do newer <- journalSpecifiedFileIsNewer j f return $ if newer then Just f else Nothing changedfiles <- catMaybes `fmap` mapM maybeChangedFilename (journalFilePaths j) if not $ null changedfiles then do whenLoud $ printf "%s has changed, reloading\n" (head changedfiles) jE <- journalReload j return (jE, True) else return (Right j, False) -- | Has the journal's main data file changed since the journal was last -- read ? journalFileIsNewer :: Journal -> IO Bool journalFileIsNewer j@Journal{filereadtime=tread} = do tmod <- fileModificationTime $ journalFilePath j return $ diffClockTimes tmod tread > (TimeDiff 0 0 0 0 0 0 0) -- | Has the specified file (presumably one of journal's data files) -- changed since journal was last read ? journalSpecifiedFileIsNewer :: Journal -> FilePath -> IO Bool journalSpecifiedFileIsNewer Journal{filereadtime=tread} f = do tmod <- fileModificationTime f return $ diffClockTimes tmod tread > (TimeDiff 0 0 0 0 0 0 0) -- | Get the last modified time of the specified file, or if it does not -- exist or there is some other error, the current time. fileModificationTime :: FilePath -> IO ClockTime fileModificationTime f | null f = getClockTime | otherwise = (do #ifdef directory_1_2 utc <- getModificationTime f let nom = utcTimeToPOSIXSeconds utc let clo = TOD (read $ takeWhile (`elem` "0123456789") $ show nom) 0 -- XXX read #else clo <- getModificationTime f #endif return clo ) `C.catch` \(_::C.IOException) -> getClockTime -- | Attempt to open a web browser on the given url, all platforms. openBrowserOn :: String -> IO ExitCode openBrowserOn u = trybrowsers browsers u where trybrowsers (b:bs) u = do (e,_,_) <- readProcessWithExitCode b [u] "" case e of ExitSuccess -> return ExitSuccess ExitFailure _ -> trybrowsers bs u trybrowsers [] u = do putStrLn $ printf "Could not start a web browser (tried: %s)" $ intercalate ", " browsers putStrLn $ printf "Please open your browser and visit %s" u return $ ExitFailure 127 browsers | os=="darwin" = ["open"] | os=="mingw32" = ["c:/Program Files/Mozilla Firefox/firefox.exe"] | otherwise = ["sensible-browser","gnome-www-browser","firefox"] -- jeffz: write a ffi binding for it using the Win32 package as a basis -- start by adding System/Win32/Shell.hsc and follow the style of any -- other module in that directory for types, headers, error handling and -- what not. -- ::ShellExecute(NULL, "open", "www.somepage.com", NULL, NULL, SW_SHOWNORMAL); -- | Back up this file with a (incrementing) numbered suffix then -- overwrite it with this new text, or give an error, but only if the text -- is different from the current file contents, and return a flag -- indicating whether we did anything. writeFileWithBackupIfChanged :: FilePath -> String -> IO Bool writeFileWithBackupIfChanged f t = do s <- readFile' f if t == s then return False else backUpFile f >> writeFile f t >> return True -- | Back up this file with a (incrementing) numbered suffix, then -- overwrite it with this new text, or give an error. writeFileWithBackup :: FilePath -> String -> IO () writeFileWithBackup f t = backUpFile f >> writeFile f t readFileStrictly :: FilePath -> IO String readFileStrictly f = readFile' f >>= \s -> C.evaluate (length s) >> return s -- | Back up this file with a (incrementing) numbered suffix, or give an error. backUpFile :: FilePath -> IO () backUpFile fp = do fs <- safeGetDirectoryContents $ takeDirectory $ fp let (d,f) = splitFileName fp versions = catMaybes $ map (f `backupNumber`) fs next = maximum (0:versions) + 1 f' = printf "%s.%d" f next copyFile fp (d f') safeGetDirectoryContents :: FilePath -> IO [FilePath] safeGetDirectoryContents "" = getDirectoryContents "." safeGetDirectoryContents fp = getDirectoryContents fp -- | Does the second file represent a backup of the first, and if so which version is it ? backupNumber :: FilePath -> FilePath -> Maybe Int backupNumber f g = case regexMatch ("^" ++ f ++ "\\.([0-9]+)$") g of Just (_, ((_,suffix):_)) -> readMay suffix _ -> Nothing hledger-0.22/Hledger/Cli/Stats.hs0000644000000000000000000001001612252750510014745 0ustar0000000000000000{-| Print some statistics for the journal. -} module Hledger.Cli.Stats where import Data.List import Data.Maybe import Data.Ord import Data.Time.Calendar import Text.Printf import qualified Data.Map as Map import Hledger import Hledger.Cli.Options import Prelude hiding (putStr) import Hledger.Utils.UTF8IOCompat (putStr) -- like Register.summarisePostings -- | Print various statistics for the journal. stats :: CliOpts -> Journal -> IO () stats CliOpts{reportopts_=reportopts_} j = do d <- getCurrentDay let q = queryFromOpts d reportopts_ l = ledgerFromJournal q j reportspan = (ledgerDateSpan l) `orDatesFrom` (queryDateSpan False q) intervalspans = splitSpan (intervalFromOpts reportopts_) reportspan showstats = showLedgerStats l d s = intercalate "\n" $ map showstats intervalspans putStr s showLedgerStats :: Ledger -> Day -> DateSpan -> String showLedgerStats l today span = unlines $ map (\(label,value) -> concatBottomPadded [printf fmt1 label, value]) stats where fmt1 = "%-" ++ show w1 ++ "s: " -- fmt2 = "%-" ++ show w2 ++ "s" w1 = maximum $ map (length . fst) stats -- w2 = maximum $ map (length . show . snd) stats stats = [ ("Main journal file" :: String, path) -- ++ " (from " ++ source ++ ")") ,("Included journal files", unlines $ reverse $ -- cf journalAddFile drop 1 $ journalFilePaths j) ,("Transactions span", printf "%s to %s (%d days)" (start span) (end span) days) ,("Last transaction", maybe "none" show lastdate ++ showelapsed lastelapsed) ,("Transactions", printf "%d (%0.1f per day)" tnum txnrate) ,("Transactions last 30 days", printf "%d (%0.1f per day)" tnum30 txnrate30) ,("Transactions last 7 days", printf "%d (%0.1f per day)" tnum7 txnrate7) ,("Payees/descriptions", show $ length $ nub $ map tdescription ts) ,("Accounts", printf "%d (depth %d)" acctnum acctdepth) ,("Commodities", printf "%s (%s)" (show $ length cs) (intercalate ", " cs)) -- Transactions this month : %(monthtxns)s (last month in the same period: %(lastmonthtxns)s) -- Uncleared transactions : %(uncleared)s -- Days since reconciliation : %(reconcileelapsed)s -- Days since last transaction : %(recentelapsed)s ] where j = ljournal l path = journalFilePath j ts = sortBy (comparing tdate) $ filter (spanContainsDate span . tdate) $ jtxns j as = nub $ map paccount $ concatMap tpostings ts cs = Map.keys $ canonicalStyles $ concatMap amounts $ map pamount $ concatMap tpostings ts lastdate | null ts = Nothing | otherwise = Just $ tdate $ last ts lastelapsed = maybe Nothing (Just . diffDays today) lastdate showelapsed Nothing = "" showelapsed (Just days) = printf " (%d %s)" days' direction where days' = abs days direction | days >= 0 = "days ago" :: String | otherwise = "days from now" tnum = length ts start (DateSpan (Just d) _) = show d start _ = "" end (DateSpan _ (Just d)) = show d end _ = "" days = fromMaybe 0 $ daysInSpan span txnrate | days==0 = 0 | otherwise = fromIntegral tnum / fromIntegral days :: Double tnum30 = length $ filter withinlast30 ts withinlast30 t = d >= addDays (-30) today && (d<=today) where d = tdate t txnrate30 = fromIntegral tnum30 / 30 :: Double tnum7 = length $ filter withinlast7 ts withinlast7 t = d >= addDays (-7) today && (d<=today) where d = tdate t txnrate7 = fromIntegral tnum7 / 7 :: Double acctnum = length as acctdepth | null as = 0 | otherwise = maximum $ map accountNameLevel as hledger-0.22/Hledger/Cli/Balancesheet.hs0000644000000000000000000000260712252750510016234 0ustar0000000000000000{-# LANGUAGE QuasiQuotes, RecordWildCards, NoCPP #-} {-| The @balancesheet@ command prints a simple balance sheet. -} module Hledger.Cli.Balancesheet ( balancesheet ,tests_Hledger_Cli_Balancesheet ) where import qualified Data.Text.Lazy.IO as LT import Test.HUnit import Text.Shakespeare.Text import Hledger import Hledger.Cli.Options import Hledger.Cli.Balance -- | Print a simple balance sheet. balancesheet :: CliOpts -> Journal -> IO () balancesheet CliOpts{reportopts_=ropts} j = do -- let lines = case formatFromOpts ropts of Left err, Right ... d <- getCurrentDay let q = queryFromOpts d (withoutBeginDate ropts) assetreport@(_,assets) = balanceReport ropts (And [q, journalAssetAccountQuery j]) j liabilityreport@(_,liabilities) = balanceReport ropts (And [q, journalLiabilityAccountQuery j]) j total = assets + liabilities LT.putStr $ [lt|Balance Sheet Assets: #{unlines $ balanceReportAsText ropts assetreport} Liabilities: #{unlines $ balanceReportAsText ropts liabilityreport} Total: -------------------- #{padleft 20 $ showMixedAmountWithoutPrice total} |] withoutBeginDate :: ReportOpts -> ReportOpts withoutBeginDate ropts@ReportOpts{..} = ropts{begin_=Nothing, period_=p} where p = case period_ of Nothing -> Nothing Just (i, DateSpan _ e) -> Just (i, DateSpan Nothing e) tests_Hledger_Cli_Balancesheet = TestList [ ] hledger-0.22/Hledger/Cli/Print.hs0000644000000000000000000000377312252750510014757 0ustar0000000000000000{-| A ledger-compatible @print@ command. -} module Hledger.Cli.Print ( print' ,showTransactions ,tests_Hledger_Cli_Print ) where import Data.List import Test.HUnit import Hledger import Prelude hiding (putStr) import Hledger.Utils.UTF8IOCompat (putStr) import Hledger.Cli.Options -- | Print journal transactions in standard format. print' :: CliOpts -> Journal -> IO () print' CliOpts{reportopts_=ropts} j = do d <- getCurrentDay putStr $ showTransactions ropts (queryFromOpts d ropts) j showTransactions :: ReportOpts -> Query -> Journal -> String showTransactions opts q j = entriesReportAsText opts q $ entriesReport opts q j tests_showTransactions = [ "showTransactions" ~: do -- "print expenses" ~: do let opts = defreportopts{query_="expenses"} d <- getCurrentDay showTransactions opts (queryFromOpts d opts) samplejournal `is` unlines ["2008/06/03 * eat & shop" ," expenses:food $1" ," expenses:supplies $1" ," assets:cash $-2" ,"" ] -- , "print report with depth arg" ~: do let opts = defreportopts{depth_=Just 2} d <- getCurrentDay showTransactions opts (queryFromOpts d opts) samplejournal `is` unlines ["2008/01/01 income" ," assets:bank:checking $1" ," income:salary $-1" ,"" ,"2008/06/01 gift" ," assets:bank:checking $1" ," income:gifts $-1" ,"" ,"2008/06/03 * eat & shop" ," expenses:food $1" ," expenses:supplies $1" ," assets:cash $-2" ,"" ,"2008/12/31 * pay off" ," liabilities:debts $1" ," assets:bank:checking $-1" ,"" ] ] entriesReportAsText :: ReportOpts -> Query -> EntriesReport -> String entriesReportAsText _ _ items = concatMap showTransactionUnelided items tests_Hledger_Cli_Print = TestList tests_showTransactionshledger-0.22/Hledger/Cli/Balance.hs0000644000000000000000000003634512252750510015211 0ustar0000000000000000{-| A ledger-compatible @balance@ command, with additional support for multi-column reports. Here is a description/specification for the balance command. See also "Hledger.Reports" -> \"Balance reports\". /Basic balance report/ With no reporting interval (@--monthly@ etc.), hledger's balance command emulates ledger's, showing accounts indented according to hierarchy, along with their total amount posted (including subaccounts). Here's an example. With @data/sample.journal@, which defines the following account tree: @ assets bank checking saving cash expenses food supplies income gifts salary liabilities debts @ the basic @balance@ command gives this output: @ $ hledger -f sample.journal balance $-1 assets $1 bank:saving $-2 cash $2 expenses $1 food $1 supplies $-2 income $-1 gifts $-1 salary $1 liabilities:debts -------------------- 0 @ Subaccounts are displayed indented below their parent. Only the account leaf name (the final part) is shown. (With @--flat@, account names are shown in full and unindented.) Each account's \"balance\" is the sum of postings in that account and any subaccounts during the report period. When the report period includes all transactions, this is equivalent to the account's current balance. The overall total of the highest-level displayed accounts is shown below the line. (The @--no-total/-N@ flag prevents this.) /Eliding and omitting/ Accounts which have a zero balance, and no non-zero subaccount balances, are normally omitted from the report. (The @--empty/-E@ flag forces such accounts to be displayed.) Eg, above @checking@ is omitted because it has a zero balance and no subaccounts. Accounts which have a single subaccount also being displayed, with the same balance, are normally elided into the subaccount's line. (The @--no-elide@ flag prevents this.) Eg, above @bank@ is elided to @bank:saving@ because it has only a single displayed subaccount (@saving@) and their balance is the same ($1). Similarly, @liabilities@ is elided to @liabilities:debts@. /Date limiting/ The default report period is that of the whole journal, including all known transactions. The @--begin\/-b@, @--end\/-e@, @--period\/-p@ options or @date:@/@date2:@ patterns can be used to report only on transactions before and/or after specified dates. /Depth limiting/ The @--depth@ option can be used to limit the depth of the balance report. Eg, to see just the top level accounts (still including their subaccount balances): @ $ hledger -f sample.journal balance --depth 1 $-1 assets $2 expenses $-2 income $1 liabilities -------------------- 0 @ /Account limiting/ With one or more account pattern arguments, the report is restricted to accounts whose name matches one of the patterns, plus their parents and subaccounts. Eg, adding the pattern @o@ to the first example gives: @ $ hledger -f sample.journal balance o $1 expenses:food $-2 income $-1 gifts $-1 salary -------------------- $-1 @ * The @o@ pattern matched @food@ and @income@, so they are shown. * @food@'s parent (@expenses@) is shown even though the pattern didn't match it, to clarify the hierarchy. The usual eliding rules cause it to be elided here. * @income@'s subaccounts are also shown. /Multi-column balance report/ hledger's balance command will show multiple columns when a reporting interval is specified (eg with @--monthly@), one column for each sub-period. There are three kinds of multi-column balance report, indicated by the heading: * A \"period balance\" (or \"flow\") report (the default) shows the change of account balance in each period, which is equivalent to the sum of postings in each period. Here, checking's balance increased by 10 in Feb: > Change of balance (flow): > > Jan Feb Mar > assets:checking 20 10 -5 * A \"cumulative balance\" report (with @--cumulative@) shows the accumulated ending balance across periods, starting from zero at the report's start date. Here, 30 is the sum of checking postings during Jan and Feb: > Ending balance (cumulative): > > Jan Feb Mar > assets:checking 20 30 25 * A \"historical balance\" report (with @--historical/-H@) also shows ending balances, but it includes the starting balance from any postings before the report start date. Here, 130 is the balance from all checking postings at the end of Feb, including pre-Jan postings which created a starting balance of 100: > Ending balance (historical): > > Jan Feb Mar > assets:checking 120 130 125 /Eliding and omitting, 2/ Here's a (imperfect?) specification for the eliding/omitting behaviour: * Each account is normally displayed on its own line. * An account less deep than the report's max depth, with just one interesting subaccount, and the same balance as the subaccount, is non-interesting, and prefixed to the subaccount's line, unless @--no-elide@ is in effect. * An account with a zero inclusive balance and less than two interesting subaccounts is not displayed at all, unless @--empty@ is in effect. * Multi-column balance reports show full account names with no eliding (like @--flat@). Accounts (and periods) are omitted as described below. /Which accounts to show in balance reports/ By default: * single-column: accounts with non-zero balance in report period. (With @--flat@: accounts with non-zero balance and postings.) * periodic: accounts with postings and non-zero period balance in any period * cumulative: accounts with non-zero cumulative balance in any period * historical: accounts with non-zero historical balance in any period With @-E/--empty@: * single-column: accounts with postings in report period * periodic: accounts with postings in report period * cumulative: accounts with postings in report period * historical: accounts with non-zero starting balance + accounts with postings in report period /Which periods (columns) to show in balance reports/ An empty period/column is one where no report account has any postings. A zero period/column is one where no report account has a non-zero period balance. Currently, by default: * single-column: N/A * periodic: all periods within the overall report period, except for leading and trailing empty periods * cumulative: all periods within the overall report period, except for leading and trailing empty periods * historical: all periods within the overall report period, except for leading and trailing empty periods With @-E/--empty@: * single-column: N/A * periodic: all periods within the overall report period * cumulative: all periods within the overall report period * historical: all periods within the overall report period /What to show in empty cells/ An empty periodic balance report cell is one which has no corresponding postings. An empty cumulative/historical balance report cell is one which has no correponding or prior postings, ie the account doesn't exist yet. Currently, empty cells show 0. -} module Hledger.Cli.Balance ( balance ,balanceReportAsText ,periodBalanceReportAsText ,cumulativeBalanceReportAsText ,historicalBalanceReportAsText ,tests_Hledger_Cli_Balance ) where import Data.List import Data.Maybe import Test.HUnit import Text.Tabular import Text.Tabular.AsciiArt import Hledger import Prelude hiding (putStr) import Hledger.Utils.UTF8IOCompat (putStr) import Hledger.Data.FormatStrings import Hledger.Cli.Options -- | Print a balance report. balance :: CliOpts -> Journal -> IO () balance CliOpts{reportopts_=ropts} j = do d <- getCurrentDay let output = case formatFromOpts ropts of Left err -> [err] Right _ -> case (intervalFromOpts ropts, balancetype_ ropts) of (NoInterval,_) -> balanceReportAsText ropts $ balanceReport ropts (queryFromOpts d ropts) j (_,PeriodBalance) -> periodBalanceReportAsText ropts $ periodBalanceReport ropts (queryFromOpts d ropts) j (_,CumulativeBalance) -> cumulativeBalanceReportAsText ropts $ cumulativeOrHistoricalBalanceReport ropts (queryFromOpts d ropts) j (_,HistoricalBalance) -> historicalBalanceReportAsText ropts $ cumulativeOrHistoricalBalanceReport ropts (queryFromOpts d ropts) j putStr $ unlines output -- | Render an old-style single-column balance report as plain text. balanceReportAsText :: ReportOpts -> BalanceReport -> [String] balanceReportAsText opts ((items, total)) = concat lines ++ t where lines = case formatFromOpts opts of Right f -> map (balanceReportItemAsText opts f) items Left err -> [[err]] t = if no_total_ opts then [] else ["--------------------" -- TODO: This must use the format somehow ,padleft 20 $ showMixedAmountWithoutPrice total ] tests_balanceReportAsText = [ "balanceReportAsText" ~: do -- "unicode in balance layout" ~: do j <- readJournal' "2009/01/01 * медвежья шкура\n расходы:покупки 100\n актив:наличные\n" let opts = defreportopts balanceReportAsText opts (balanceReport opts (queryFromOpts (parsedate "2008/11/26") opts) j) `is` [" -100 актив:наличные" ," 100 расходы:покупки" ,"--------------------" ," 0" ] ] {- This implementation turned out to be a bit convoluted but implements the following algorithm for formatting: - If there is a single amount, print it with the account name directly: - Otherwise, only print the account name on the last line. a USD 1 ; Account 'a' has a single amount EUR -1 b USD -1 ; Account 'b' has two amounts. The account name is printed on the last line. -} -- | Render one balance report line item as plain text suitable for console output. balanceReportItemAsText :: ReportOpts -> [FormatString] -> BalanceReportItem -> [String] balanceReportItemAsText opts format (_, accountName, depth, Mixed amounts) = -- 'amounts' could contain several quantities of the same commodity with different price. -- In order to combine them into single value (which is expected) we take the first price and -- use it for the whole mixed amount. This could be suboptimal. XXX let Mixed normAmounts = normaliseMixedAmountPreservingFirstPrice (Mixed amounts) in case normAmounts of [] -> [] [a] -> [formatBalanceReportItem opts (Just accountName) depth a format] (as) -> multiline as where multiline :: [Amount] -> [String] multiline [] = [] multiline [a] = [formatBalanceReportItem opts (Just accountName) depth a format] multiline (a:as) = (formatBalanceReportItem opts Nothing depth a format) : multiline as formatBalanceReportItem :: ReportOpts -> Maybe AccountName -> Int -> Amount -> [FormatString] -> String formatBalanceReportItem _ _ _ _ [] = "" formatBalanceReportItem opts accountName depth amount (fmt:fmts) = s ++ (formatBalanceReportItem opts accountName depth amount fmts) where s = case fmt of FormatLiteral l -> l FormatField ljust min max field -> formatField opts accountName depth amount ljust min max field formatField :: ReportOpts -> Maybe AccountName -> Int -> Amount -> Bool -> Maybe Int -> Maybe Int -> HledgerFormatField -> String formatField opts accountName depth total ljust min max field = case field of AccountField -> formatValue ljust min max $ maybe "" (accountNameDrop (drop_ opts)) accountName DepthSpacerField -> case min of Just m -> formatValue ljust Nothing max $ replicate (depth * m) ' ' Nothing -> formatValue ljust Nothing max $ replicate depth ' ' TotalField -> formatValue ljust min max $ showAmountWithoutPrice total _ -> "" -- | Render a multi-column period balance report as plain text suitable for console output. periodBalanceReportAsText :: ReportOpts -> MultiBalanceReport -> [String] periodBalanceReportAsText opts (MultiBalanceReport (colspans, items, coltotals)) = (["Change of balance (flow):"] ++) $ trimborder $ lines $ render id ((" "++) . showDateSpan) showMixedAmountWithoutPrice $ Table (Group NoLine $ map (Header . padright acctswidth) accts) (Group NoLine $ map Header colspans) (map snd items') +----+ totalrow where trimborder = ("":) . (++[""]) . drop 1 . init . map (drop 1 . init) items' | empty_ opts = items | otherwise = items -- dbg "2" $ filter (any (not . isZeroMixedAmount) . snd) $ dbg "1" items accts = map renderacct items' renderacct ((a,a',_i),_) | flat_ opts = a | otherwise = a' -- replicate i ' ' ++ acctswidth = maximum $ map length $ accts totalrow | no_total_ opts = row "" [] | otherwise = row "" coltotals -- | Render a multi-column cumulative balance report as plain text suitable for console output. cumulativeBalanceReportAsText :: ReportOpts -> MultiBalanceReport -> [String] cumulativeBalanceReportAsText opts (MultiBalanceReport (colspans, items, coltotals)) = (["Ending balance (cumulative):"] ++) $ trimborder $ lines $ render id ((" "++) . maybe "" (showDate . prevday) . spanEnd) showMixedAmountWithoutPrice $ addtotalrow $ Table (Group NoLine $ map (Header . padright acctswidth) accts) (Group NoLine $ map Header colspans) (map snd items) where trimborder = ("":) . (++[""]) . drop 1 . init . map (drop 1 . init) accts = map renderacct items renderacct ((a,a',_),_) | flat_ opts = a | otherwise = a' -- replicate i ' ' ++ acctswidth = maximum $ map length $ accts addtotalrow | no_total_ opts = id | otherwise = (+----+ row "" coltotals) -- | Render a multi-column historical balance report as plain text suitable for console output. historicalBalanceReportAsText :: ReportOpts -> MultiBalanceReport -> [String] historicalBalanceReportAsText opts (MultiBalanceReport (colspans, items, coltotals)) = (["Ending balance (historical):"] ++) $ trimborder $ lines $ render id ((" "++) . maybe "" (showDate . prevday) . spanEnd) showMixedAmountWithoutPrice $ addtotalrow $ Table (Group NoLine $ map (Header . padright acctswidth) accts) (Group NoLine $ map Header colspans) (map snd items) where trimborder = ("":) . (++[""]) . drop 1 . init . map (drop 1 . init) accts = map renderacct items renderacct ((a,a',_),_) | flat_ opts = a | otherwise = a' -- replicate i ' ' ++ acctswidth = maximum $ map length $ accts addtotalrow | no_total_ opts = id | otherwise = (+----+ row "" coltotals) tests_Hledger_Cli_Balance = TestList tests_balanceReportAsText hledger-0.22/Hledger/Cli/Main.hs0000644000000000000000000001670012252750510014541 0ustar0000000000000000{-| hledger - a ledger-compatible accounting tool. Copyright (c) 2007-2011 Simon Michael Released under GPL version 3 or later. hledger is a partial haskell clone of John Wiegley's "ledger". It generates ledger-compatible register & balance reports from a plain text journal, and demonstrates a functional implementation of ledger. For more information, see http:\/\/hledger.org . This module provides the main function for the hledger command-line executable. It is exposed here so that it can be imported by eg benchmark scripts. You can use the command line: > $ hledger --help or ghci: > $ ghci hledger > > j <- readJournalFile Nothing Nothing "data/sample.journal" > > register [] ["income","expenses"] j > 2008/01/01 income income:salary $-1 $-1 > 2008/06/01 gift income:gifts $-1 $-2 > 2008/06/03 eat & shop expenses:food $1 $-1 > expenses:supplies $1 0 > > balance [Depth "1"] [] l > $-1 assets > $2 expenses > $-2 income > $1 liabilities > > l <- myLedger See "Hledger.Data.Ledger" for more examples. -} module Hledger.Cli.Main where import Control.Monad import Data.List import Safe import System.Console.CmdArgs.Explicit (modeHelp) -- import System.Console.CmdArgs.Helper import System.Environment import System.Exit import System.Process import Text.Printf import Hledger (ensureJournalFileExists) import Hledger.Cli.Add import Hledger.Cli.Balance import Hledger.Cli.Balancesheet import Hledger.Cli.Cashflow import Hledger.Cli.Histogram import Hledger.Cli.Incomestatement import Hledger.Cli.Print import Hledger.Cli.Register import Hledger.Cli.Stats import Hledger.Cli.Options import Hledger.Cli.Tests import Hledger.Cli.Utils import Hledger.Cli.Version import Hledger.Utils import Hledger.Reports import Hledger.Data.Dates main :: IO () main = do -- Choose and run the appropriate internal or external command based -- on the raw command-line arguments, cmdarg's interpretation of -- same, and hledger-* executables in the user's PATH. A somewhat -- complex mishmash of cmdargs and custom processing, hence all the -- debugging support and tests. See also Hledger.Cli.Options and -- command-line.test. -- some preliminary (imperfect) argument parsing to supplement cmdargs args <- getArgs let args' = moveFlagsAfterCommand args isFlag = ("-" `isPrefixOf`) isNonEmptyNonFlag s = not (isFlag s) && not (null s) rawcmd = headDef "" $ takeWhile isNonEmptyNonFlag args' isNullCommand = null rawcmd (argsbeforecmd, argsaftercmd') = break (==rawcmd) args argsaftercmd = drop 1 argsaftercmd' when (debugLevel > 0) $ do printf "running: %s\n" prognameandversion printf "raw args: %s\n" (show args) printf "raw args rearranged for cmdargs: %s\n" (show args') printf "raw command might be: %s\n" (show rawcmd) printf "raw args before command: %s\n" (show argsbeforecmd) printf "raw args after command: %s\n" (show argsaftercmd) -- search PATH for add-ons addons <- getHledgerAddonCommands -- parse arguments with cmdargs opts <- argsToCliOpts args addons -- select an action and run it. let cmd = command_ opts -- the full matched internal or external command name, if any isInternalCommand = not (null cmd) && not (cmd `elem` addons) -- probably isExternalCommand = not (null cmd) && cmd `elem` addons -- probably isBadCommand = not (null rawcmd) && null cmd hasHelp args = any (`elem` args) ["--help","-h","-?"] hasVersion = ("--version" `elem`) mainmode' = mainmode addons generalHelp = putStr $ showModeHelp mainmode' version = putStrLn prognameandversion badCommandError = error' ("command "++rawcmd++" is not recognized, run with no command to see a list") >> exitFailure f `orShowHelp` mode = if hasHelp args then putStr (showModeHelp mode) else f when (debug_ opts > 0) $ do putStrLn $ "processed opts:\n" ++ ppShow opts putStrLn $ "command matched: " ++ show cmd putStrLn $ "isNullCommand: " ++ show isNullCommand putStrLn $ "isInternalCommand: " ++ show isInternalCommand putStrLn $ "isExternalCommand: " ++ show isExternalCommand putStrLn $ "isBadCommand: " ++ show isBadCommand d <- getCurrentDay putStrLn $ "date span from opts: " ++ (show $ dateSpanFromOpts d $ reportopts_ opts) putStrLn $ "interval from opts: " ++ (show $ intervalFromOpts $ reportopts_ opts) putStrLn $ "query from opts & args: " ++ (show $ queryFromOpts d $ reportopts_ opts) let dbg s = if debug_ opts > 0 then trace s else id runHledgerCommand -- high priority flags and situations. --help should be highest priority. | hasHelp argsbeforecmd = dbg "--help before command, showing general help" generalHelp | not (hasHelp argsaftercmd) && (hasVersion argsbeforecmd || (hasVersion argsaftercmd && isInternalCommand)) = version -- \| (null externalcmd) && "binary-filename" `inRawOpts` rawopts = putStrLn $ binaryfilename progname -- \| "--browse-args" `elem` args = System.Console.CmdArgs.Helper.execute "cmdargs-browser" mainmode' args >>= (putStr . show) | isNullCommand = dbg "no command, showing general help" generalHelp | isBadCommand = badCommandError -- internal commands | cmd == "activity" = withJournalDo opts histogram `orShowHelp` activitymode | cmd == "add" = (journalFilePathFromOpts opts >>= ensureJournalFileExists >> withJournalDo opts add) `orShowHelp` addmode | cmd == "balance" = withJournalDo opts balance `orShowHelp` balancemode | cmd == "balancesheet" = withJournalDo opts balancesheet `orShowHelp` balancesheetmode | cmd == "cashflow" = withJournalDo opts cashflow `orShowHelp` cashflowmode | cmd == "incomestatement" = withJournalDo opts incomestatement `orShowHelp` incomestatementmode | cmd == "print" = withJournalDo opts print' `orShowHelp` printmode | cmd == "register" = withJournalDo opts register `orShowHelp` registermode | cmd == "stats" = withJournalDo opts stats `orShowHelp` statsmode | cmd == "test" = test' opts `orShowHelp` testmode -- an external command | isExternalCommand = do let shellcmd = printf "%s-%s %s" progname cmd (unwords' argsaftercmd) when (debug_ opts > 0) $ do printf "external command selected: %s\n" cmd printf "external command arguments: %s\n" (show argsaftercmd) printf "running shell command: %s\n" (show shellcmd) system shellcmd >>= exitWith -- deprecated commands | cmd == "convert" = error' (modeHelp convertmode) >> exitFailure -- shouldn't reach here | otherwise = optserror ("could not understand the arguments "++show args) >> exitFailure runHledgerCommand -- tests_runHledgerCommand = [ -- -- "runHledgerCommand" ~: do -- -- let opts = defreportopts{query_="expenses"} -- -- d <- getCurrentDay -- -- runHledgerCommand addons opts@CliOpts{command_=cmd} args -- ] hledger-0.22/Hledger/Cli/Histogram.hs0000644000000000000000000000307412252750510015612 0ustar0000000000000000{-| Print a histogram report. -} module Hledger.Cli.Histogram where import Data.List import Data.Maybe import Data.Ord import Text.Printf import Hledger.Cli.Options import Hledger.Data import Hledger.Reports import Hledger.Query import Prelude hiding (putStr) import Hledger.Utils.UTF8IOCompat (putStr) barchar = '*' -- | Print a histogram of some statistic per reporting interval, such as -- number of postings per day. histogram :: CliOpts -> Journal -> IO () histogram CliOpts{reportopts_=ropts} j = do d <- getCurrentDay putStr $ showHistogram ropts (queryFromOpts d ropts) j showHistogram :: ReportOpts -> Query -> Journal -> String showHistogram opts q j = concatMap (printDayWith countBar) spanps where i = intervalFromOpts opts interval | i == NoInterval = Days 1 | otherwise = i span = queryDateSpan (date2_ opts) q `orDatesFrom` journalDateSpan j spans = filter (DateSpan Nothing Nothing /=) $ splitSpan interval span spanps = [(s, filter (isPostingInDateSpan s) ps) | s <- spans] -- same as Register -- should count transactions, not postings ? -- ps = sortBy (comparing postingDate) $ filterempties $ filter matchapats $ filterdepth $ journalPostings j ps = sortBy (comparing postingDate) $ filterempties $ filter (q `matchesPosting`) $ journalPostings j filterempties | queryEmpty q = id | otherwise = filter (not . isZeroMixedAmount . pamount) printDayWith f (DateSpan b _, ts) = printf "%s %s\n" (show $ fromJust b) (f ts) countBar ps = replicate (length ps) barchar hledger-0.22/Hledger/Cli/Version.hs0000644000000000000000000000455512252750510015307 0ustar0000000000000000{-# LANGUAGE CPP, TemplateHaskell #-} {- Version number-related utilities. See also the Makefile. -} module Hledger.Cli.Version ( progname, version, prognameandversion, binaryfilename ) where import System.Info (os, arch) import Text.Printf import Hledger.Utils -- package name and version from the cabal file progname, version, prognameandversion :: String progname = "hledger" #ifdef VERSION version = VERSION #else version = "" #endif prognameandversion = progname ++ " " ++ version -- developer build version strings include PATCHLEVEL (number of -- patches since the last tag). If defined, it must be a number. patchlevel :: String #ifdef PATCHLEVEL patchlevel = "." ++ show (PATCHLEVEL :: Int) #else patchlevel = "" #endif -- the package version plus patchlevel if specified buildversion :: String buildversion = version ++ patchlevel -- | Given a program name, return a precise platform-specific executable -- name suitable for naming downloadable binaries. Can raise an error if -- the version and patch level was not defined correctly at build time. binaryfilename :: String -> String binaryfilename progname = prettify $ splitAtElement '.' buildversion where prettify (major:minor:bugfix:patches:[]) = printf "%s-%s.%s%s%s-%s-%s%s" progname major minor bugfix' patches' os' arch suffix where bugfix' | bugfix `elem` ["0"{-,"98","99"-}] = "" | otherwise = '.' : bugfix patches' | patches/="0" = '+' : patches | otherwise = "" (os',suffix) | os == "darwin" = ("mac","" :: String) | os == "mingw32" = ("windows",".exe") | otherwise = (os,"") prettify (major:minor:bugfix:[]) = prettify [major,minor,bugfix,"0"] prettify (major:minor:[]) = prettify [major,minor,"0","0"] prettify (major:[]) = prettify [major,"0","0","0"] prettify [] = error' "VERSION is empty, please fix" prettify _ = error' "VERSION has too many components, please fix" hledger-0.22/tests/0000755000000000000000000000000012252750510012376 5ustar0000000000000000hledger-0.22/tests/suite.hs0000644000000000000000000000033312252750510014062 0ustar0000000000000000import Hledger.Cli (tests_Hledger_Cli) import Test.Framework.Providers.HUnit (hUnitTestToTests) import Test.Framework.Runners.Console (defaultMain) main :: IO () main = defaultMain $ hUnitTestToTests tests_Hledger_Cli