hledger-0.26/0000755000000000000000000000000012550610443011241 5ustar0000000000000000hledger-0.26/CHANGES0000644000000000000000000004142012550610443012235 0ustar0000000000000000User-visible changes in hledger and hledger-lib. 0.26 (2015/7/12) Account aliases: - Account aliases are once again non-regular-expression-based, by default. (#252) The regex account aliases added in 0.24 trip up people switching between hledger and Ledger. (Also they are currently slow). This change makes the old non-regex aliases the default; they are unsurprising, useful, and pretty close in functionality to Ledger's. The new regex aliases are still available; they must be enclosed in forward slashes. (Ledger effectively ignores these.) Journal format: - We now parse, and also print, journal entries with no postings, as proposed on the mail lists. These are not well-formed General Journal entries/transactions, but here is my rationale: - Ledger and beancount parse them - if they are parsed, they should be printed - they provide a convenient way to record (and report) non-transaction events - they permit more gradual introduction and learning of the concepts. So eg a beginner can keep a simple journal before learning about accounts and postings. - Trailing whitespace after a `comment` directive is now ignored. Command-line interface: - The -f/file option may now be used multiple times. This is equivalent to concatenating the input files before running hledger. The add command adds entries to the first file specified. Queries: - real: (no argument) is now a synonym for real:1 - tag: now matches tag names with a regular expression, like most other queries - empty: is no longer supported, as it overlaps a bit confusingly with amt:0. The --empty flag is still available. - You can now match on pending status (#250) A transaction/posting status of ! (pending) was effectively equivalent to * (cleared). Now it's a separate state, not matched by --cleared. The new Ledger-compatible --pending flag matches it, and so does --uncleared. The relevant search query terms are now status:*, status:! and status: (the old status:1 and status:0 spellings are deprecated). Since we interpret --uncleared and status: as "any state except cleared", it's not currently possible to match things which are neither cleared nor pending. activity: - activity no longer excludes 0-amount postings by default. add: - Don't show quotes around the journal file path in the "Creating..." message, for consistency with the subsequent "Adding..." message. balancesheet: - Accounts beginning with "debt" or now also recognised as liabilities. print: - We now limit the display precision of inferred prices. (#262) When a transaction posts to two commodities without specifying the conversion price, we generate a price which makes it balance (cf http://hledger.org/manual.html#prices). The print command showed this with full precision (so that manual calculations with the displayed numbers would look right), but this sometimes meant we showed 255 digits (when there are multiple postings in the commodity being priced, and the averaged unit price is an irrational number). In this case we now set the price's display precision to the sum of the (max) display precisions of the commodities involved. An example: hledgerdev -f- print <<< 1/1 c C 10.00 c C 11.00 d D -320.00 >>> 2015/01/01 c C 10.00 @ D 15.2381 c C 11.00 @ D 15.2381 d D -320.00 >>>=0 There might still be cases where this will show more price decimal places than necessary. - We now show inferred unit prices with at least 2 decimal places. When inferring prices, if the commodities involved have low display precisions, we don't do a good job of rendering accurate-looking unit prices. Eg if the journal doesn't use any decimal places, any inferred unit prices are also displayed with no decimal places, which makes them look wrong to the user. Now, we always give inferred unit prices a minimum display precision of 2, which helps a bit. register: - Postings with no amounts could give a runtime error in some obscure case, now fixed. stats: - stats now supports -o/--outputfile, like register/balance/print. - An O(n^2) performance slowdown has been fixed, it's now much faster on large journals. +--------------------------------------++--------+--------+ | || 0.25 | 0.26 | +======================================++========+========+ | -f data/100x100x10.journal stats || 0.10 | 0.16 | | -f data/1000x1000x10.journal stats || 0.45 | 0.21 | | -f data/10000x1000x10.journal stats || 58.92 | 2.16 | +--------------------------------------++--------+--------+ Miscellaneous: - The June 30 day span was not being rendered correctly; fixed. (#272) - The bench script invoked by "cabal bench" or "stack bench" now runs some simple benchmarks. You can get more accurate benchmark times by running with --criterion. This will usually give much the same numbers and takes much longer. Or with --simplebench, it benchmarks whatever commands are configured in bench/default.bench. This mode uses the first "hledger" executable in $PATH. - The deprecated shakespeare-text dependency has been removed more thoroughly. 0.25.1 (2015/4/29) - timelog: support the description field (#247) 0.25 (2015/4/7) - GHC 7.10 compatibility (#239) - build with terminfo support on POSIX systems by default On non-windows systems, we now build with terminfo support by default, useful for detecting terminal width and other things. This requires the C curses dev libaries, which makes POSIX installation slightly harder; if it causes problems you can disable terminfo support with the new `curses` cabal flag, eg: cabal install -f-curses ... (or cabal might try this automatically, I'm not sure). - register: use the full terminal width, respect COLUMNS, allow column width adjustment On POSIX systems, register now uses the full terminal width by default. Specifically, the output width is set from: 1. a --width option 2. or a COLUMNS environment variable (NB: not the same as a bash shell var) 3. or on POSIX (non-windows) systems, the current terminal width 4. or the default, 80 characters. Also, register's --width option now accepts an optional description column width following the overall width (--width WIDTH[,DESCWIDTH]). This also sets the account column width, since the available space (WIDTH-41) is divided up between these two columns. Here's a diagram: <--------------------------------- width (W) ----------------------------------> date (10) description (D) account (W-41-D) amount (12) balance (12) DDDDDDDDDD dddddddddddddddddddd aaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA Examples: $ hledger reg # use terminal width on posix $ hledger reg -w 100 # width 100, equal description/account widths $ hledger reg -w 100,40 # width 100, wider description $ hledger reg -w $COLUMNS,100 # terminal width and set description width - balance: new -T/--row-total and -A/--average options In multicolumn balance reports, -T/--row-total now shows a row totals column and -A/--average shows a row averages column. This helps eg to see monthly average expenses (hledger bal ^expenses -MA). NB our use of -T deviates from Ledger's UI, where -T sets a custom final total expression. - balance: -N is now short for --no-total - balance: fix partially-visible totals row with --no-total A periodic (not using --cumulative or --historical) balance report with --no-total now hides the totals row properly. - journal, csv: comment lines can also start with * As in Ledger. This means you can embed emacs org/outline-mode nodes in your journal file and manipulate it like an outline. 0.24.1 (2015/3/15) - journal: fix balance accumulation across assertions (#195) A sequence of balance assertions asserting first one commodity, then another, then the first again, was not working. - timelog: show hours with two decimal places instead of one (#237) - in weekly reports, simplify week 52's heading like the others - disallow trailing garbage in a number of parsers Trailing garbage is no longer ignored when parsing the following: balance --format option, register --width option, hledger-rewrite options, hledger add's inputs, CSV amounts, posting amounts, posting dates in tags. - allow utf8-string-1 (fpco/stackage/#426) 0.24 (2014/12/25) General: - fix redundant compilation when cabal installing the hledger packages - switch to Decimal for representing amounts (#118) - report interval headings (eg in balance, register reports) are shown compactly when possible - general speedups Journal format: - detect decimal point and digit groups more robustly (#196) - check that transaction dates are followed by whitespace or newline - check that dates use a consistent separator character - balance assertions now are specific to a single commodity, like Ledger (#195) - support multi-line comments using "comment", "end comment" directives, like Ledger CSV format: - reading CSV data from stdin now works better - the rules file include directive is now relative to the current file's directory (#198) - the original order of same-day transactions is now usually preserved (if the records appear to be in reverse date order, we reverse them before finally sorting by transaction date) - CSV output is now built in to the balance, print, and register commands, controlled by -O/--output-format (and -o/--output-file, see below) CLI: - the --width and --debug options now require their argument (#149) - when an option is repeated, the last value takes precedence (#219). This is helpful eg for customising your reporting command aliases on the fly. - smart dates (used in -p/-b/-e/date:/date2:) now must use a consistent separator character, and must be parseable to the end - output destination and format selection is now built in to the balance, print and register commands, controlled by -o/--output-file and -O/--output-format options. Notes: - -o - means stdout - an output file name suffix matching a supported format will also set the output format, unless overridden by --output-format - commands' supported output formats are listed in their command-line help. Two formats are currently available: txt (the default) and csv. - balance assertions can be disabled with --ignore-assertions Account aliases: - all matching account aliases are now applied, not just one directive and one option - account aliases now match by case insensitive regular expressions matching anywhere in the account name - account aliases can replace multiple occurrences of the pattern within an account name - an account alias replacement pattern can reference matched groups with \N Queries: - date:/date2: with a malformed date now reports an error instead of being ignored - amt: now supports >= or <= - clarify status: docs and behaviour; "*" is no longer a synonym for "1" (fixes #227) balance: - fix: in tree mode, --drop is ignored instead of showing empty account names - a depth limit of 0 now shows summary items with account name "...", instead of an empty report (#206) - in multicolumn balance reports, -E now also shows posting-less accounts with a non-zero balance during the period (in addition to showing leading & trailing empty columns) - in multicolumn reports, multi-commodity amounts are rendered on one line for better layout (#186) - multicolumn reports' title now includes the report span register: - runs faster with large output - supports date2:, and date:/date2: combined with --date2, better (fixes #201, #221, #222) - a depth limit of 0 now shows summary items (see balance) - -A/--average now implies -E/--empty - postings with multi-commodity amounts are now top-aligned, like Ledger Extra commands: - hledger-equity: fix end date in title; print closing entry too - hledger-check-dates: added 0.23.3 (2014/9/12) - allow text 1.2+ (#207) 0.23.2 (2014/5/8) - register: also fix date sorting of postings (#184) 0.23.1 (2014/5/7) - register: fix a refactoring-related regression that the tests missed: if transactions were not ordered by date in the journal, register could include postings before the report start date in the output. (#184) - add: don't apply a default commodity to amounts on entry (#138) - cli: options before the add-on command name are now also passed to it (#182) - csv: allow the first name in a fields list to be empty (#178) - csv: don't validate fields count in skipped lines (#177) 0.23 (2014/5/1) Journal format: - A # (hash) in column 0 is now also supported for starting a top-level journal comment, like Ledger. - The "too many missing amounts" error now reminds about the 2-space rule. - Fix: . (period) is no longer parsed as a valid amount. - Fix: default commodity directives no longer limit the maximum display precision (#169). - Fix: + before an amount is no longer parsed as part of the commodity (#181). CLI: - Command-line help cleanups, layout improvements. - Descriptions are shown for known add-ons in the command list. - Command aliases have been simplified. - Add-ons can now have any of these file extensions: none, hs, lhs, pl, py, rb, rkt, sh, bat, com, exe. - Add-ons are displayed without their file extensions when possible. - Add-ons with the same name as a built-in command or alias are ignored. - Fix: add-on detection and invocation now works on windows. - Fix: add-ons with digits in the name are now found. - Fix: add-on arguments containing a single quote now work. - Fix: when -- is used to hide add-on options from the main program, it is no longer passed through as an add-on argument. Queries: - The currency/commodity query prefix (sym:) has been renamed to cur:. - Currency/commodity queries are applied more strongly in register and balance reports, filtering out unwanted currencies entirely. Eg hledger balance cur:'\$' now reports only the dollar amounts even if there are multi-currency transactions or postings. - Amount queries like amt:N, amt:N, where N is not 0, now do an unsigned comparison of the amount and N. That is, they compare the absolute magnitude. To do a signed comparison instead, write N with its sign (eg amt:+N, amt:<+N, amt:>-N). - Fix: amount queries no longer give false positives on multi-commodity amounts. accounts: - An accounts command has been added, similar to Ledger's, for listing account names in flat or hierarchical mode. add: - Tab completion now works at all prompts, and will insert the default if the input area is empty. - Account and amount defaults are more robust and useful. - Transactions may also be completed by the enter key, when there are no more default postings. - Input prompts are displayed in a different colour when supported. balance: - Balance reports in flat mode now always show exclusive (subaccount-excluding) balances. - Balance reports in flat mode with --depth now aggregate deeper accounts at the depth limit instead of excluding them. - Multicolumn reports in flat mode now support --drop. - Multicolumn balance reports can now show the account hierarchy with --tree. - Multicolumn report start/end dates are adjusted to encompass the displayed report periods, so the first and last periods are "full" and comparable to the others. - Fix: zero-balance leaf accounts below a non-zero-balance parent are no longer always shown (#170). - Fix: multicolumn reports now support --date2 (cf #174). balancesheet, cashflow, incomestatement: - These commands now support --flat and --drop. print: - Tag queries (tag:) will now match a transaction if any of its postings match. register: - The --display option has been dropped. To see an accurate running total which includes the prior starting balance, use --historical/-H (like balance). - With a report interval, report start/end dates are adjusted to encompass the displayed periods, so the first and last periods are "full" and comparable to the others. - Fix: --date2 now works with report intervals (fixes #174). Miscellaneous: - Default report dates now derive from the secondary dates when --date2 is in effect. - Default report dates now notice any posting dates outside the transaction dates' span. - Debug output improvements. - New add-on example: extra/hledger-rewrite.hs, adds postings to matched entries. - Compatible with GHC 7.2 (#155) - GHC 7.8, shakespeare 2 0.22.2 (2014/4/16) - display years before 1000 with four digits, not three - avoid pretty-show to build with GHC < 7.4 - allow text 1.1, drop data-pprint to build with GHC 7.8.x 0.22.1 (2014/1/6) and older: see http://hledger.org/release-notes or doc/CHANGES.md. hledger-0.26/hledger.cabal0000644000000000000000000001714412550610443013646 0ustar0000000000000000name: hledger version: 0.26 stability: stable category: Finance, Console 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.8.4, GHC==7.10.1 cabal-version: >= 1.10 build-type: Simple -- data-dir: data -- data-files: extra-tmp-files: extra-source-files: test/test.hs CHANGES source-repository head type: git location: https://github.com/simonmichael/hledger flag threaded Description: Build with support for multithreaded execution Default: True flag curses Description: On POSIX systems, enable curses support for auto-detecting terminal width. Default: True flag old-locale description: A compatibility flag, set automatically by cabal. If false then depend on time >= 1.5, if true then depend on time < 1.5 together with old-locale. default: False library cpp-options: -DVERSION="0.26" ghc-options: -Wall -fno-warn-unused-do-bind -fno-warn-name-shadowing -fno-warn-missing-signatures ghc-options: -fno-warn-type-defaults -fno-warn-orphans default-language: Haskell2010 exposed-modules: Hledger.Cli Hledger.Cli.Main Hledger.Cli.Options Hledger.Cli.Tests Hledger.Cli.Utils Hledger.Cli.Version Hledger.Cli.Add Hledger.Cli.Accounts Hledger.Cli.Balance Hledger.Cli.Balancesheet Hledger.Cli.Cashflow Hledger.Cli.Histogram Hledger.Cli.Incomestatement Hledger.Cli.Print Hledger.Cli.Register Hledger.Cli.Stats build-depends: hledger-lib == 0.26 ,base >= 4.3 && < 5 ,base-compat >= 0.8.1 -- ,cabal-file-th ,containers ,unordered-containers ,cmdargs >= 0.10 && < 0.11 ,csv -- ,data-pprint >= 0.2.1 && < 0.3 ,directory ,filepath ,haskeline >= 0.6 && <= 0.8 ,HUnit ,mtl ,mtl-compat ,old-time ,parsec >= 3 ,process ,regex-tdfa ,safe >= 0.2 ,split >= 0.1 && < 0.3 ,text >= 0.11 ,tabular >= 0.2 && < 0.3 ,utf8-string >= 0.3.5 && < 1.1 ,wizards == 1.0.* if impl(ghc >= 7.10) -- ghc 7.10 requires shakespeare 2.0.2.2+ build-depends: shakespeare >= 2.0.2.2 && < 2.1 else -- for older ghcs, allow shakespeare 1.x (which also requires shakespeare-text) -- http://www.yesodweb.com/blog/2014/04/consolidation-progress build-depends: shakespeare >= 1.0 && < 2.1 ,shakespeare-text >= 1.0 && < 1.2 if flag(old-locale) build-depends: time < 1.5, old-locale else build-depends: time >= 1.5 if impl(ghc >= 7.4) build-depends: pretty-show >= 1.6.4 if !os(windows) && flag(curses) build-depends: terminfo executable hledger main-is: hledger-cli.hs hs-source-dirs: app default-language: Haskell2010 cpp-options: -DVERSION="0.26" ghc-options: -Wall -fno-warn-unused-do-bind -fno-warn-name-shadowing -fno-warn-missing-signatures ghc-options: -fno-warn-type-defaults -fno-warn-orphans if flag(threaded) ghc-options: -threaded -- same as above: build-depends: hledger-lib == 0.26 ,hledger == 0.26 ,base >= 4.3 && < 5 ,base-compat >= 0.8.1 ,containers ,unordered-containers ,cmdargs >= 0.10 && < 0.11 ,csv -- ,data-pprint >= 0.2.1 && < 0.3 ,directory ,filepath ,haskeline >= 0.6 && <= 0.8 ,HUnit ,mtl ,mtl-compat ,old-time ,parsec >= 3 ,process ,regex-tdfa ,safe >= 0.2 ,split >= 0.1 && < 0.3 ,tabular >= 0.2 && < 0.3 ,text >= 0.11 ,utf8-string >= 0.3.5 && < 1.1 ,wizards == 1.0.* -- as above if impl(ghc >= 7.10) build-depends: shakespeare >= 2.0.2.2 && < 2.1 else build-depends: shakespeare >= 1.0 && < 2.1 ,shakespeare-text >= 1.0 && < 1.2 if flag(old-locale) build-depends: time < 1.5, old-locale else build-depends: time >= 1.5 if impl(ghc >= 7.4) build-depends: pretty-show >= 1.6.4 test-suite test type: exitcode-stdio-1.0 main-is: test.hs hs-source-dirs: test default-language: Haskell2010 ghc-options: -Wall -fno-warn-unused-do-bind -fno-warn-name-shadowing -fno-warn-missing-signatures ghc-options: -fno-warn-type-defaults -fno-warn-orphans -- same as above: build-depends: hledger-lib , hledger , base >= 4.3 && < 5 , base-compat >= 0.8.1 , cmdargs , containers , csv -- , data-pprint >= 0.2.1 && < 0.3 , directory , filepath , haskeline , HUnit , mtl , mtl-compat , old-time , parsec >= 3 , process , regex-tdfa , safe , split ,tabular >= 0.2 && < 0.3 , test-framework , test-framework-hunit , text , transformers , wizards == 1.0.* -- as above if impl(ghc >= 7.10) build-depends: shakespeare >= 2.0.2.2 && < 2.1 else build-depends: shakespeare >= 1.0 && < 2.1 ,shakespeare-text >= 1.0 && < 1.2 if impl(ghc >= 7.4) build-depends: pretty-show >= 1.6.4 if flag(old-locale) build-depends: time < 1.5, old-locale else build-depends: time >= 1.5 benchmark bench type: exitcode-stdio-1.0 hs-source-dirs: bench main-is: bench.hs ghc-options: -Wall -fno-warn-unused-do-bind -fno-warn-name-shadowing -fno-warn-missing-signatures ghc-options: -fno-warn-type-defaults -fno-warn-orphans default-language: Haskell2010 build-depends: hledger-lib, hledger, base >= 4.3 && < 5, base-compat >= 0.8.1, criterion, html, tabular >= 0.2 && < 0.3, timeit, process, filepath, directory if flag(old-locale) build-depends: time < 1.5, old-locale else build-depends: time >= 1.5 hledger-0.26/LICENSE0000644000000000000000000010451312550610443012252 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.26/Setup.hs0000644000000000000000000000005612550610443012676 0ustar0000000000000000import Distribution.Simple main = defaultMain hledger-0.26/app/0000755000000000000000000000000012550610443012021 5ustar0000000000000000hledger-0.26/app/hledger-cli.hs0000644000000000000000000000022312550610443014531 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.26/bench/0000755000000000000000000000000012550610443012320 5ustar0000000000000000hledger-0.26/bench/bench.hs0000644000000000000000000000535312550610443013741 0ustar0000000000000000-- bench -- By default, show approximate times for some standard hledger operations on a sample journal. -- With --criterion, show accurate times (slow). -- With --simplebench, show approximate times for the commands in default.bench, using the first hledger executable on $PATH. import Criterion.Main (defaultMainWith, defaultConfig, bench, nfIO) import SimpleBench (defaultMain) import System.Directory (getCurrentDirectory) import System.Environment (getArgs, withArgs) import System.Info (os) import System.Process (readProcess) import System.TimeIt (timeItT) import Text.Printf import Hledger.Cli -- sample journal file to use for benchmarks inputfile = "bench/10000x1000x10.journal" outputfile = "/dev/null" -- hide output of benchmarked commands (XXX unixism) -- outputfile = "-" -- show output of benchmarked commands main = do -- withArgs ["--simplebench"] $ do -- withArgs ["--criterion"] $ do args <- getArgs if "--criterion" `elem` args then withArgs [] benchWithCriterion else if "--simplebench" `elem` args then benchWithSimplebench else benchWithTimeit benchWithTimeit = do getCurrentDirectory >>= printf "Benchmarking hledger in %s with timeit\n" let opts = defcliopts{output_file_=Just outputfile} (t0,j) <- timeit ("read "++inputfile) $ either error id <$> readJournalFile Nothing Nothing True inputfile (t1,_) <- timeit ("print") $ print' opts j (t2,_) <- timeit ("register") $ register opts j (t3,_) <- timeit ("balance") $ balance opts j (t4,_) <- timeit ("stats") $ stats opts j printf "Total: %0.2fs\n" (sum [t0,t1,t2,t3,t4]) timeit :: String -> IO a -> IO (Double, a) timeit name action = do printf "%s%s" name (replicate (40 - length name) ' ') (t,a) <- timeItT action printf "[%.2fs]\n" t return (t,a) benchWithCriterion = do getCurrentDirectory >>= printf "Benchmarking hledger in %s with criterion\n" let opts = defcliopts{output_file_=Just "/dev/null"} j <- either error id <$> readJournalFile Nothing Nothing True inputfile Criterion.Main.defaultMainWith defaultConfig $ [ bench ("read "++inputfile) $ nfIO $ (either error const <$> readJournalFile Nothing Nothing True inputfile), bench ("print") $ nfIO $ print' opts j, bench ("register") $ nfIO $ register opts j, bench ("balance") $ nfIO $ balance opts j, bench ("stats") $ nfIO $ stats opts j ] benchWithSimplebench = do let whichcmd = if os == "mingw32" then "where" else "which" exe <- init <$> readProcess whichcmd ["hledger"] "" pwd <- getCurrentDirectory printf "Benchmarking %s in %s with simplebench and shell\n" exe pwd flip withArgs SimpleBench.defaultMain [ "-fbench/default.bench" ,"-v" ,"hledger" ] hledger-0.26/Hledger/0000755000000000000000000000000012550610443012613 5ustar0000000000000000hledger-0.26/Hledger/Cli.hs0000644000000000000000000003414612550610443013666 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.Accounts, 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, module Hledger, module System.Console.CmdArgs.Explicit ) where import Data.Time.Calendar import System.Console.CmdArgs.Explicit import Test.HUnit import Hledger import Hledger.Cli.Accounts 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 ignoresourcepos j = j{jtxns=map (\t -> t{tsourcepos=nullsourcepos}) (jtxns j)} in let sameParse str1 str2 = do j1 <- readJournal Nothing Nothing True Nothing str1 >>= either error' (return . ignoresourcepos) j2 <- readJournal Nothing Nothing True Nothing str2 >>= either error' (return . ignoresourcepos) 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 True 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 True 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 True 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.00h" ] -- 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 :: String 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 :: Journal journal7 = nulljournal {jtxns = [ txnTieKnot Transaction { tsourcepos=nullsourcepos, tdate=parsedate "2007/01/01", tdate2=Nothing, tstatus=Uncleared, 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 { tsourcepos=nullsourcepos, tdate=parsedate "2007/02/01", tdate2=Nothing, tstatus=Uncleared, tcode="*", tdescription="ayres suites", tcomment="", ttags=[], tpostings= ["expenses:vacation" `post` usd 179.92 ,"assets:checking" `post` usd (-179.92) ], tpreceding_comment_lines="" } , txnTieKnot Transaction { tsourcepos=nullsourcepos, tdate=parsedate "2007/01/02", tdate2=Nothing, tstatus=Uncleared, tcode="*", tdescription="auto transfer to savings", tcomment="", ttags=[], tpostings= ["assets:saving" `post` usd 200 ,"assets:checking" `post` usd (-200) ], tpreceding_comment_lines="" } , txnTieKnot Transaction { tsourcepos=nullsourcepos, tdate=parsedate "2007/01/03", tdate2=Nothing, tstatus=Uncleared, 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 { tsourcepos=nullsourcepos, tdate=parsedate "2007/01/03", tdate2=Nothing, tstatus=Uncleared, tcode="*", tdescription="verizon", tcomment="", ttags=[], tpostings= ["expenses:phone" `post` usd 95.11 ,"assets:checking" `post` usd (-95.11) ], tpreceding_comment_lines="" } , txnTieKnot Transaction { tsourcepos=nullsourcepos, tdate=parsedate "2007/01/03", tdate2=Nothing, tstatus=Uncleared, tcode="*", tdescription="discover", tcomment="", ttags=[], tpostings= ["liabilities:credit cards:discover" `post` usd 80 ,"assets:checking" `post` usd (-80) ], tpreceding_comment_lines="" } ] } ledger7 :: Ledger ledger7 = ledgerFromJournal Any journal7 hledger-0.26/Hledger/Cli/0000755000000000000000000000000012550610443013322 5ustar0000000000000000hledger-0.26/Hledger/Cli/Accounts.hs0000644000000000000000000000440612550610443015441 0ustar0000000000000000{-| The @accounts@ command lists account names: - in flat mode (default), it lists the full names of accounts posted to by matched postings, clipped to the specified depth, possibly with leading components dropped. - in tree mode, it shows the indented short names of accounts posted to by matched postings, and their parents, to the specified depth. -} module Hledger.Cli.Accounts ( accountsmode ,accounts ,tests_Hledger_Cli_Accounts ) where import Data.List import System.Console.CmdArgs.Explicit as C import Test.HUnit import Hledger import Prelude hiding (putStrLn) import Hledger.Utils.UTF8IOCompat (putStrLn) import Hledger.Cli.Options -- | Command line options for this command. accountsmode = (defCommandMode $ ["accounts"] ++ aliases) { modeHelp = "show account names" `withAliases` aliases ,modeHelpSuffix = [ "This command lists the accounts referenced by matched postings (and in tree mode, their parents as well). The accounts can be depth-clipped (--depth N) or have their leading parts trimmed (--drop N)." ] ,modeGroupFlags = C.Group { groupUnnamed = [ flagNone ["tree"] (\opts -> setboolopt "tree" opts) "show short account names, as a tree" ,flagNone ["flat"] (\opts -> setboolopt "flat" opts) "show full account names, as a list (default)" ,flagReq ["drop"] (\s opts -> Right $ setopt "drop" s opts) "N" "flat mode: omit N leading account name parts" ] ,groupHidden = [] ,groupNamed = [generalflagsgroup1] } } where aliases = [] -- | The accounts command. accounts :: CliOpts -> Journal -> IO () accounts CliOpts{reportopts_=ropts} j = do d <- getCurrentDay let q = queryFromOpts d ropts nodepthq = dbg1 "nodepthq" $ filterQuery (not . queryIsDepth) q depth = dbg1 "depth" $ queryDepth $ filterQuery queryIsDepth q ps = dbg1 "ps" $ journalPostings $ filterJournalPostings nodepthq j as = dbg1 "as" $ nub $ filter (not . null) $ map (clipAccountName depth) $ sort $ map paccount ps as' | tree_ ropts = expandAccountNames as | otherwise = as render a | tree_ ropts = replicate (2 * (accountNameLevel a - 1)) ' ' ++ accountLeafName a | otherwise = maybeAccountNameDrop ropts a mapM_ (putStrLn . render) as' tests_Hledger_Cli_Accounts = TestList [] hledger-0.26/Hledger/Cli/Add.hs0000644000000000000000000004661212550610443014357 0ustar0000000000000000{-| A history-aware add command to help with data entry. |-} {-# OPTIONS_GHC -fno-warn-missing-signatures -fno-warn-unused-do-bind #-} {-# LANGUAGE CPP, ScopedTypeVariables, DeriveDataTypeable, RecordWildCards, TypeOperators, FlexibleContexts #-} module Hledger.Cli.Add where import Prelude () import Prelude.Compat import Control.Exception as E import Control.Monad import Control.Monad.Trans (liftIO) import Data.Char (toUpper, toLower) import Data.List.Compat import Data.Maybe import Data.Time.Calendar (Day) import Data.Typeable (Typeable) import Safe (headDef, headMay) import System.Console.CmdArgs.Explicit import System.Console.Haskeline (runInputT, defaultSettings, setComplete) import System.Console.Haskeline.Completion import System.Console.Wizard import System.Console.Wizard.Haskeline import System.IO ( stderr, hPutStr, hPutStrLn ) import Text.Parsec import Text.Printf import Hledger import Hledger.Cli.Options import Hledger.Cli.Register (postingsReportAsText) addmode = (defCommandMode ["add"]) { modeHelp = "prompt for transactions 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] } } -- | State used while entering transactions. data EntryState = EntryState { esOpts :: CliOpts -- ^ command line options ,esArgs :: [String] -- ^ command line arguments remaining to be used as defaults ,esToday :: Day -- ^ today's date ,esDefDate :: Day -- ^ the default date for next transaction ,esJournal :: Journal -- ^ the journal we are adding to ,esSimilarTransaction :: Maybe Transaction -- ^ the most similar historical txn ,esPostings :: [Posting] -- ^ postings entered so far in the current txn } deriving (Show,Typeable) defEntryState = EntryState { esOpts = defcliopts ,esArgs = [] ,esToday = nulldate ,esDefDate = nulldate ,esJournal = nulljournal ,esSimilarTransaction = Nothing ,esPostings = [] } data RestartTransactionException = RestartTransactionException deriving (Typeable,Show) instance Exception RestartTransactionException -- data ShowHelpException = ShowHelpException deriving (Typeable,Show) -- instance Exception ShowHelpException -- | 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 | journalFilePath j == "-" = return () | otherwise = do hPrintf stderr "Adding transactions to journal file %s\n" (journalFilePath j) showHelp today <- getCurrentDay let es = defEntryState{esOpts=opts ,esArgs=map stripquotes $ listofstringopt "args" $ rawopts_ opts ,esToday=today ,esDefDate=today ,esJournal=j } getAndAddTransactions es `E.catch` (\(_::UnexpectedEOF) -> putStr "") showHelp = hPutStr stderr $ unlines [ "Any command line arguments will be used as defaults." ,"Use tab key to complete, readline keys to edit, enter to accept defaults." ,"An optional (CODE) may follow transaction dates." ,"An optional ; COMMENT may follow descriptions or amounts." ,"If you make a mistake, enter < at any prompt to restart the transaction." ,"To end a transaction, enter . when prompted." ,"To quit, enter . at a date prompt or press control-d or control-c." ] -- | Loop reading transactions from the console, prompting, validating -- 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; otherwise defaults come from the -- most similar recent transaction in the journal. getAndAddTransactions :: EntryState -> IO () getAndAddTransactions es@EntryState{..} = (do mt <- runInputT (setComplete noCompletion defaultSettings) (run $ haskeline $ confirmedTransactionWizard es) case mt of Nothing -> fail "urk ?" Just t -> do j <- if debug_ esOpts > 0 then do hPrintf stderr "Skipping journal add due to debug mode.\n" return esJournal else do j' <- journalAddTransaction esJournal esOpts t hPrintf stderr "Saved.\n" return j' hPrintf stderr "Starting the next transaction (. or ctrl-D/ctrl-C to quit)\n" getAndAddTransactions es{esJournal=j, esDefDate=tdate t} ) `E.catch` (\(_::RestartTransactionException) -> hPrintf stderr "Restarting this transaction.\n" >> getAndAddTransactions es) -- confirmedTransactionWizard :: (ArbitraryIO :<: b, OutputLn :<: b, Line :<: b) => EntryState -> Wizard b Transaction -- confirmedTransactionWizard :: EntryState -> Wizard Haskeline Transaction confirmedTransactionWizard es@EntryState{..} = do t <- transactionWizard es -- liftIO $ hPrintf stderr {- "Transaction entered:\n%s" -} (show t) output $ show t y <- let def = "y" in retryMsg "Please enter y or n." $ parser ((fmap ('y' ==)) . headMay . map toLower . strip) $ defaultTo' def $ nonEmpty $ maybeRestartTransaction $ line $ green $ printf "Save this transaction to the journal ?%s: " (showDefault def) if y then return t else throw RestartTransactionException transactionWizard es@EntryState{..} = do (date,code) <- dateAndCodeWizard es let es1@EntryState{esArgs=args1} = es{esArgs=drop 1 esArgs, esDefDate=date} (desc,comment) <- descriptionAndCommentWizard es1 let mbaset = similarTransaction es1 desc when (isJust mbaset) $ liftIO $ hPrintf stderr "Using this similar transaction for defaults:\n%s" (show $ fromJust mbaset) let es2 = es1{esArgs=drop 1 args1, esSimilarTransaction=mbaset} balancedPostingsWizard = do ps <- postingsWizard es2{esPostings=[]} let t = nulltransaction{tdate=date ,tstatus=Uncleared ,tcode=code ,tdescription=desc ,tcomment=comment ,tpostings=ps } case balanceTransaction Nothing t of -- imprecise balancing (?) Right t' -> return t' Left err -> liftIO (hPutStrLn stderr $ "\n" ++ (capitalize err) ++ "please re-enter.") >> balancedPostingsWizard balancedPostingsWizard -- Identify the closest recent match for this description in past transactions. similarTransaction :: EntryState -> String -> Maybe Transaction similarTransaction EntryState{..} desc = let q = queryFromOptsOnly esToday $ reportopts_ esOpts historymatches = transactionsSimilarTo esJournal q desc bestmatch | null historymatches = Nothing | otherwise = Just $ snd $ head historymatches in bestmatch dateAndCodeWizard EntryState{..} = do let def = headDef (showDate esDefDate) esArgs retryMsg "A valid hledger smart date is required. Eg: 2014/2/14, 14, yesterday." $ parser (parseSmartDateAndCode esToday) $ withCompletion (dateCompleter def) $ defaultTo' def $ nonEmpty $ maybeExit $ maybeRestartTransaction $ -- maybeShowHelp $ line $ green $ printf "Date%s: " (showDefault def) where parseSmartDateAndCode refdate s = either (const Nothing) (\(d,c) -> return (fixSmartDate refdate d, c)) edc where edc = runParser (dateandcodep <* eof) nullctx "" $ lowercase s dateandcodep :: Stream [Char] m t => ParsecT [Char] JournalContext m (SmartDate, String) dateandcodep = do d <- smartdate c <- optionMaybe codep many spacenonewline eof return (d, fromMaybe "" c) -- defday = fixSmartDate today $ fromparse $ (parse smartdate "" . lowercase) defdate -- datestr = showDate $ fixSmartDate defday smtdate descriptionAndCommentWizard EntryState{..} = do let def = headDef "" esArgs s <- withCompletion (descriptionCompleter esJournal def) $ defaultTo' def $ nonEmpty $ maybeRestartTransaction $ line $ green $ printf "Description%s: " (showDefault def) let (desc,comment) = (strip a, strip $ dropWhile (==';') b) where (a,b) = break (==';') s return (desc,comment) postingsWizard es@EntryState{..} = do mp <- postingWizard es case mp of Nothing -> return esPostings Just p -> postingsWizard es{esArgs=drop 2 esArgs, esPostings=esPostings++[p]} postingWizard es@EntryState{..} = do acct <- accountWizard es if acct `elem` [".",""] then case (esPostings, postingsBalanced esPostings) of ([],_) -> liftIO (hPutStrLn stderr "Please enter some postings first.") >> postingWizard es (_,False) -> liftIO (hPutStrLn stderr "Please enter more postings to balance the transaction.") >> postingWizard es (_,True) -> return Nothing -- no more postings, end of transaction else do let es1 = es{esArgs=drop 1 esArgs} (amt,comment) <- amountAndCommentWizard es1 return $ Just nullposting{paccount=stripbrackets acct ,pamount=Mixed [amt] ,pcomment=comment ,ptype=accountNamePostingType acct } postingsBalanced :: [Posting] -> Bool postingsBalanced ps = isRight $ balanceTransaction Nothing nulltransaction{tpostings=ps} accountWizard EntryState{..} = do let pnum = length esPostings + 1 historicalp = maybe Nothing (Just . (!! (pnum-1)) . (++ (repeat nullposting)) . tpostings) esSimilarTransaction historicalacct = case historicalp of Just p -> showAccountName Nothing (ptype p) (paccount p) Nothing -> "" def = headDef historicalacct esArgs endmsg | canfinish && null def = " (or . or enter to finish this transaction)" | canfinish = " (or . to finish this transaction)" | otherwise = "" retryMsg "A valid hledger account name is required. Eg: assets:cash, expenses:food:eating out." $ parser (parseAccountOrDotOrNull def canfinish) $ withCompletion (accountCompleter esJournal def) $ defaultTo' def $ -- nonEmpty $ maybeRestartTransaction $ line $ green $ printf "Account %d%s%s: " pnum (endmsg::String) (showDefault def) where canfinish = not (null esPostings) && postingsBalanced esPostings parseAccountOrDotOrNull _ _ "." = dbg1 $ Just "." -- . always signals end of txn parseAccountOrDotOrNull "" True "" = dbg1 $ Just "" -- when there's no default and txn is balanced, "" also signals end of txn parseAccountOrDotOrNull def@(_:_) _ "" = dbg1 $ Just def -- when there's a default, "" means use that parseAccountOrDotOrNull _ _ s = dbg1 $ either (const Nothing) validateAccount $ runParser (accountnamep <* eof) (jContext esJournal) "" s -- otherwise, try to parse the input as an accountname dbg1 = id -- strace validateAccount s | no_new_accounts_ esOpts && not (s `elem` journalAccountNames esJournal) = Nothing | otherwise = Just s amountAndCommentWizard EntryState{..} = do let pnum = length esPostings + 1 (mhistoricalp,followedhistoricalsofar) = case esSimilarTransaction of Nothing -> (Nothing,False) Just Transaction{tpostings=ps} -> (if length ps >= pnum then Just (ps !! (pnum-1)) else Nothing ,all (\(a,b) -> pamount a == pamount b) $ zip esPostings ps) def = case (esArgs, mhistoricalp, followedhistoricalsofar) of (d:_,_,_) -> d (_,Just hp,True) -> showamt $ pamount hp _ | pnum > 1 && not (isZeroMixedAmount balancingamt) -> showamt balancingamt _ -> "" retryMsg "A valid hledger amount is required. Eg: 1, $2, 3 EUR, \"4 red apples\"." $ parser parseAmountAndComment $ withCompletion (amountCompleter def) $ defaultTo' def $ nonEmpty $ maybeRestartTransaction $ line $ green $ printf "Amount %d%s: " pnum (showDefault def) where parseAmountAndComment = either (const Nothing) Just . runParser (amountandcommentp <* eof) nodefcommodityctx "" nodefcommodityctx = (jContext esJournal){ctxDefaultCommodityAndStyle=Nothing} amountandcommentp :: Stream [Char] m t => ParsecT [Char] JournalContext m (Amount, String) amountandcommentp = do a <- amountp many spacenonewline c <- fromMaybe "" `fmap` optionMaybe (char ';' >> many anyChar) -- eof return (a,c) balancingamt = negate $ sum $ map pamount realps where realps = filter isReal esPostings showamt = showMixedAmountWithPrecision -- 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 maxprecisionwithpoint -- -- let -- (amt,comment) = (strip a, strip $ dropWhile (==';') b) where (a,b) = break (==';') amtcmt -- a = fromparse $ runParser (amountp <|> return missingamt) (jContext esJournal) "" amt -- awithoutctx = fromparse $ runParser (amountp <|> return missingamt) nullctx "" amt -- defamtaccepted = Just (showAmount a) == mdefamt -- es2 = if defamtaccepted then es1 else es1{esHistoricalPostings=Nothing} -- mdefaultcommodityapplied = if acommodity a == acommodity awithoutctx then Nothing else Just $ acommodity a -- when (isJust mdefaultcommodityapplied) $ -- liftIO $ hPutStrLn stderr $ printf "using default commodity (%s)" (fromJust mdefaultcommodityapplied) maybeExit = parser (\s -> if s=="." then throw UnexpectedEOF else Just s) maybeRestartTransaction = parser (\s -> if s=="<" then throw RestartTransactionException else Just s) -- maybeShowHelp :: Wizard Haskeline String -> Wizard Haskeline String -- maybeShowHelp wizard = maybe (liftIO showHelp >> wizard) return $ -- parser (\s -> if s=="?" then Nothing else Just s) wizard -- Completion helpers dateCompleter :: String -> CompletionFunc IO dateCompleter = completer ["today","tomorrow","yesterday"] descriptionCompleter :: Journal -> String -> CompletionFunc IO descriptionCompleter j = completer (journalDescriptions j) accountCompleter :: Journal -> String -> CompletionFunc IO accountCompleter j = completer (journalAccountNamesUsed j) amountCompleter :: String -> CompletionFunc IO amountCompleter = completer [] -- | Generate a haskeline completion function from the given -- completions and default, that case insensitively completes with -- prefix matches, or infix matches above a minimum length, or -- completes the null string with the default. completer :: [String] -> String -> CompletionFunc IO completer completions def = completeWord Nothing "" completionsFor where simpleCompletion' s = (simpleCompletion s){isFinished=False} completionsFor "" = return [simpleCompletion' def] completionsFor i = return (map simpleCompletion' ciprefixmatches) where ciprefixmatches = [c | c <- completions, i `isPrefixOf` c] -- mixed-case completions require haskeline > 0.7.1.2 -- ciprefixmatches = [c | c <- completions, lowercase i `isPrefixOf` lowercase c] -------------------------------------------------------------------------------- -- utilities defaultTo' = flip defaultTo withCompletion f = withSettings (setComplete f defaultSettings) green s = "\ESC[1;32m\STX"++s++"\ESC[0m\STX" showDefault "" = "" showDefault s = " [" ++ s ++ "]" -- | Append this transaction to the journal's file and 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} capitalize :: String -> String capitalize "" = "" capitalize (c:cs) = toUpper c : cs -- Find the most similar and recent transactions matching the given transaction description and report query. -- Transactions are listed with their "relevancy" score, most relevant first. transactionsSimilarTo :: Journal -> Query -> String -> [(Double,Transaction)] transactionsSimilarTo j q desc = sortBy compareRelevanceAndRecency $ filter ((> threshold).fst) [(compareDescriptions desc $ 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 compareDescriptions :: [Char] -> [Char] -> Double compareDescriptions s t = compareStrings s' t' where s' = simplify s t' = simplify t simplify = filter (not . (`elem` "0123456789")) -- | 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 _ = [] hledger-0.26/Hledger/Cli/Balance.hs0000644000000000000000000005143112550610443015207 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 ( balancemode ,balance ,balanceReportAsText ,periodBalanceReportAsText ,cumulativeBalanceReportAsText ,historicalBalanceReportAsText ,tests_Hledger_Cli_Balance ) where import System.Console.CmdArgs.Explicit as C import Text.CSV import Test.HUnit import Text.Printf (printf) import Text.Tabular as T import Text.Tabular.AsciiArt import Hledger import Hledger.Data.OutputFormat import Hledger.Cli.Options import Hledger.Cli.Utils -- | Command line options for this command. balancemode = (defCommandMode $ ["balance"] ++ aliases) { -- also accept but don't show the common bal alias modeHelp = "show accounts and balances" `withAliases` aliases ,modeGroupFlags = C.Group { groupUnnamed = [ flagNone ["tree"] (\opts -> setboolopt "tree" opts) "show accounts as a tree (default in simple reports)" ,flagNone ["flat"] (\opts -> setboolopt "flat" opts) "show accounts as a list (default in multicolumn mode)" ,flagReq ["drop"] (\s opts -> Right $ setopt "drop" s opts) "N" "flat mode: omit N leading account name parts" ,flagReq ["format"] (\s opts -> Right $ setopt "format" s opts) "FORMATSTR" "tree mode: use this custom line format" ,flagNone ["no-elide"] (\opts -> setboolopt "no-elide" opts) "tree mode: don't squash boring parent accounts" ,flagNone ["historical","H"] (\opts -> setboolopt "historical" opts) "multicolumn mode: show historical ending balances" ,flagNone ["cumulative"] (\opts -> setboolopt "cumulative" opts) "multicolumn mode: show accumulated ending balances" ,flagNone ["average","A"] (\opts -> setboolopt "average" opts) "multicolumn mode: show a row average column" ,flagNone ["row-total","T"] (\opts -> setboolopt "row-total" opts) "multicolumn mode: show a row total column" ,flagNone ["no-total","N"] (\opts -> setboolopt "no-total" opts) "don't show the final total row" ] ++ outputflags ,groupHidden = [] ,groupNamed = [generalflagsgroup1] } } where aliases = ["bal"] -- | The balance command, prints a balance report. balance :: CliOpts -> Journal -> IO () balance opts@CliOpts{reportopts_=ropts} j = do d <- getCurrentDay case lineFormatFromOpts ropts of Left err -> error' $ unlines [err] Right _ -> do let format = outputFormatFromOpts opts interval = intervalFromOpts ropts baltype = balancetype_ ropts case interval of NoInterval -> do let report = balanceReport ropts (queryFromOpts d ropts) j render = case format of "csv" -> \ropts r -> (++ "\n") $ printCSV $ balanceReportAsCsv ropts r _ -> balanceReportAsText writeOutput opts $ render ropts report _ -> do let report = multiBalanceReport ropts (queryFromOpts d ropts) j render = case format of "csv" -> \ropts r -> (++ "\n") $ printCSV $ multiBalanceReportAsCsv ropts r _ -> case baltype of PeriodBalance -> periodBalanceReportAsText CumulativeBalance -> cumulativeBalanceReportAsText HistoricalBalance -> historicalBalanceReportAsText writeOutput opts $ render ropts report -- single-column balance reports -- | Render a single-column balance report as CSV. balanceReportAsCsv :: ReportOpts -> BalanceReport -> CSV balanceReportAsCsv opts (items, total) = ["account","balance"] : [[a, showMixedAmountWithoutPrice b] | ((a, _, _), b) <- items] ++ if no_total_ opts then [] else [["total", showMixedAmountOneLineWithoutPrice total]] -- | Render a single-column balance report as plain text. balanceReportAsText :: ReportOpts -> BalanceReport -> String balanceReportAsText opts ((items, total)) = unlines $ concat lines ++ t where lines = case lineFormatFromOpts 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` unlines [" -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 -> [OutputFormat] -> 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 = normaliseMixedAmountSquashPricesForDisplay (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 -> [OutputFormat] -> 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 "" (maybeAccountNameDrop 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 _ -> "" -- multi-column balance reports -- | Render a multi-column balance report as CSV. multiBalanceReportAsCsv :: ReportOpts -> MultiBalanceReport -> CSV multiBalanceReportAsCsv opts (MultiBalanceReport (colspans, items, (coltotals,tot,avg))) = ("account" : "short account" : "indent" : map showDateSpan colspans ++ (if row_total_ opts then ["total"] else []) ++ (if average_ opts then ["average"] else []) ) : [a : a' : show i : map showMixedAmountOneLineWithoutPrice (amts ++ (if row_total_ opts then [rowtot] else []) ++ (if average_ opts then [rowavg] else [])) | ((a,a',i), amts, rowtot, rowavg) <- items] ++ if no_total_ opts then [] else [["totals", "", ""] ++ map showMixedAmountOneLineWithoutPrice ( coltotals ++ (if row_total_ opts then [tot] else []) ++ (if average_ opts then [avg] else []) )] -- | Render a multi-column period balance report as plain text suitable for console output. periodBalanceReportAsText :: ReportOpts -> MultiBalanceReport -> String periodBalanceReportAsText opts r@(MultiBalanceReport (colspans, items, (coltotals,tot,avg))) = unlines $ ([printf "Balance changes in %s:" (showDateSpan $ multiBalanceReportSpan r)] ++) $ trimborder $ lines $ render id (" "++) showMixedAmountOneLineWithoutPrice $ addtotalrow $ Table (T.Group NoLine $ map (Header . padright acctswidth) accts) (T.Group NoLine $ map Header colheadings) (map rowvals items') where trimborder = ("":) . (++[""]) . drop 1 . init . map (drop 1 . init) colheadings = map showDateSpan colspans ++ (if row_total_ opts then [" Total"] else []) ++ (if average_ opts then ["Average"] else []) items' | empty_ opts = items | otherwise = items -- dbg1 "2" $ filter (any (not . isZeroMixedAmount) . snd) $ dbg1 "1" items accts = map renderacct items' renderacct ((a,a',i),_,_,_) | tree_ opts = replicate ((i-1)*2) ' ' ++ a' | otherwise = maybeAccountNameDrop opts a acctswidth = maximum $ map length $ accts rowvals (_,as,rowtot,rowavg) = as ++ (if row_total_ opts then [rowtot] else []) ++ (if average_ opts then [rowavg] else []) addtotalrow | no_total_ opts = id | otherwise = (+----+ (row "" $ coltotals ++ (if row_total_ opts then [tot] else []) ++ (if average_ opts then [avg] else []) )) -- | Render a multi-column cumulative balance report as plain text suitable for console output. cumulativeBalanceReportAsText :: ReportOpts -> MultiBalanceReport -> String cumulativeBalanceReportAsText opts r@(MultiBalanceReport (colspans, items, (coltotals,tot,avg))) = unlines $ ([printf "Ending balances (cumulative) in %s:" (showDateSpan $ multiBalanceReportSpan r)] ++) $ trimborder $ lines $ render id (" "++) showMixedAmountOneLineWithoutPrice $ addtotalrow $ Table (T.Group NoLine $ map (Header . padright acctswidth) accts) (T.Group NoLine $ map Header colheadings) (map rowvals items) where trimborder = ("":) . (++[""]) . drop 1 . init . map (drop 1 . init) colheadings = map (maybe "" (showDate . prevday) . spanEnd) colspans ++ (if row_total_ opts then [" Total"] else []) ++ (if average_ opts then ["Average"] else []) accts = map renderacct items renderacct ((a,a',i),_,_,_) | tree_ opts = replicate ((i-1)*2) ' ' ++ a' | otherwise = maybeAccountNameDrop opts a acctswidth = maximum $ map length $ accts rowvals (_,as,rowtot,rowavg) = as ++ (if row_total_ opts then [rowtot] else []) ++ (if average_ opts then [rowavg] else []) addtotalrow | no_total_ opts = id | otherwise = (+----+ (row "" $ coltotals ++ (if row_total_ opts then [tot] else []) ++ (if average_ opts then [avg] else []) )) -- | Render a multi-column historical balance report as plain text suitable for console output. historicalBalanceReportAsText :: ReportOpts -> MultiBalanceReport -> String historicalBalanceReportAsText opts r@(MultiBalanceReport (colspans, items, (coltotals,tot,avg))) = unlines $ ([printf "Ending balances (historical) in %s:" (showDateSpan $ multiBalanceReportSpan r)] ++) $ trimborder $ lines $ render id (" "++) showMixedAmountOneLineWithoutPrice $ addtotalrow $ Table (T.Group NoLine $ map (Header . padright acctswidth) accts) (T.Group NoLine $ map Header colheadings) (map rowvals items) where trimborder = ("":) . (++[""]) . drop 1 . init . map (drop 1 . init) colheadings = map (maybe "" (showDate . prevday) . spanEnd) colspans ++ (if row_total_ opts then [" Total"] else []) ++ (if average_ opts then ["Average"] else []) accts = map renderacct items renderacct ((a,a',i),_,_,_) | tree_ opts = replicate ((i-1)*2) ' ' ++ a' | otherwise = maybeAccountNameDrop opts a acctswidth = maximum $ map length $ accts rowvals (_,as,rowtot,rowavg) = as ++ (if row_total_ opts then [rowtot] else []) ++ (if average_ opts then [rowavg] else []) addtotalrow | no_total_ opts = id | otherwise = (+----+ (row "" $ coltotals ++ (if row_total_ opts then [tot] else []) ++ (if average_ opts then [avg] else []) )) -- | Figure out the overall date span of a multicolumn balance report. multiBalanceReportSpan :: MultiBalanceReport -> DateSpan multiBalanceReportSpan (MultiBalanceReport ([], _, _)) = DateSpan Nothing Nothing multiBalanceReportSpan (MultiBalanceReport (colspans, _, _)) = DateSpan (spanStart $ head colspans) (spanEnd $ last colspans) tests_Hledger_Cli_Balance = TestList tests_balanceReportAsText hledger-0.26/Hledger/Cli/Balancesheet.hs0000644000000000000000000000372512550610443016243 0ustar0000000000000000{-# LANGUAGE QuasiQuotes, RecordWildCards, NoCPP #-} {-| The @balancesheet@ command prints a simple balance sheet. -} module Hledger.Cli.Balancesheet ( balancesheetmode ,balancesheet ,tests_Hledger_Cli_Balancesheet ) where import qualified Data.Text.Lazy.IO as LT import System.Console.CmdArgs.Explicit import Test.HUnit import Text.Shakespeare.Text import Hledger import Hledger.Cli.Options import Hledger.Cli.Balance balancesheetmode :: Mode RawOpts balancesheetmode = (defCommandMode $ ["balancesheet"]++aliases) { modeHelp = "show a balance sheet" `withAliases` aliases ,modeGroupFlags = Group { groupUnnamed = [ flagNone ["flat"] (\opts -> setboolopt "flat" opts) "show accounts as a list" ,flagReq ["drop"] (\s opts -> Right $ setopt "drop" s opts) "N" "flat mode: omit N leading account name parts" ] ,groupHidden = [] ,groupNamed = [generalflagsgroup1] } } where aliases = ["bs"] -- | Print a simple balance sheet. balancesheet :: CliOpts -> Journal -> IO () balancesheet CliOpts{reportopts_=ropts} j = do -- let lines = case lineFormatFromOpts 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: #{balanceReportAsText ropts assetreport} Liabilities: #{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 :: Test tests_Hledger_Cli_Balancesheet = TestList [ ] hledger-0.26/Hledger/Cli/Cashflow.hs0000644000000000000000000000372312550610443015431 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 ( cashflowmode ,cashflow ,tests_Hledger_Cli_Cashflow ) where import qualified Data.Text.Lazy.IO as LT import System.Console.CmdArgs.Explicit import Test.HUnit import Text.Shakespeare.Text import Hledger import Hledger.Cli.Options import Hledger.Cli.Balance cashflowmode :: Mode RawOpts cashflowmode = (defCommandMode ["cashflow","cf"]) { modeHelp = "show a cashflow statement" `withAliases` ["cf"] ,modeGroupFlags = Group { groupUnnamed = [ flagNone ["flat"] (\opts -> setboolopt "flat" opts) "show accounts as a list" ,flagReq ["drop"] (\s opts -> Right $ setopt "drop" s opts) "N" "flat mode: omit N leading account name parts" ] ,groupHidden = [] ,groupNamed = [generalflagsgroup1] } } -- | Print a simple cashflow statement. cashflow :: CliOpts -> Journal -> IO () cashflow CliOpts{reportopts_=ropts} j = do -- let lines = case lineFormatFromOpts 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: #{balanceReportAsText ropts cashreport} Total: -------------------- #{padleft 20 $ showMixedAmountWithoutPrice total} |] tests_Hledger_Cli_Cashflow :: Test tests_Hledger_Cli_Cashflow = TestList [ ] hledger-0.26/Hledger/Cli/Histogram.hs0000644000000000000000000000352412550610443015617 0ustar0000000000000000{-| Print a histogram report. (The "activity" command). -} module Hledger.Cli.Histogram where import Data.List import Data.Maybe import Data.Ord import System.Console.CmdArgs.Explicit import Text.Printf import Hledger import Hledger.Cli.Options import Prelude hiding (putStr) import Hledger.Utils.UTF8IOCompat (putStr) activitymode :: Mode RawOpts activitymode = (defCommandMode $ ["activity"] ++ aliases) { modeHelp = "show an ascii barchart of posting counts per interval (default: daily)" `withAliases` aliases ,modeHelpSuffix = [] ,modeGroupFlags = Group { groupUnnamed = [] ,groupHidden = [] ,groupNamed = [generalflagsgroup1] } } where aliases = [] barchar :: Char 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 `spanDefaultsFrom` journalDateSpan (date2_ opts) 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) $ filter (q `matchesPosting`) $ journalPostings j printDayWith f (DateSpan b _, ps) = printf "%s %s\n" (show $ fromJust b) (f ps) countBar ps = replicate (length ps) barchar hledger-0.26/Hledger/Cli/Incomestatement.hs0000644000000000000000000000331612550610443017020 0ustar0000000000000000{-# LANGUAGE QuasiQuotes, TemplateHaskell, OverloadedStrings, NoCPP #-} {-| The @incomestatement@ command prints a simple income statement (profit & loss) report. -} module Hledger.Cli.Incomestatement ( incomestatementmode ,incomestatement ,tests_Hledger_Cli_Incomestatement ) where import qualified Data.Text.Lazy.IO as LT import System.Console.CmdArgs.Explicit import Test.HUnit import Text.Shakespeare.Text import Hledger import Hledger.Cli.Options import Hledger.Cli.Balance incomestatementmode :: Mode RawOpts incomestatementmode = (defCommandMode $ ["incomestatement"]++aliases) { modeHelp = "show an income statement" `withAliases` aliases ,modeGroupFlags = Group { groupUnnamed = [ flagNone ["flat"] (\opts -> setboolopt "flat" opts) "show accounts as a list" ,flagReq ["drop"] (\s opts -> Right $ setopt "drop" s opts) "N" "flat mode: omit N leading account name parts" ] ,groupHidden = [] ,groupNamed = [generalflagsgroup1] } } where aliases = ["is"] -- | 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: #{balanceReportAsText ropts incomereport} Expenses: #{balanceReportAsText ropts expensereport} Total: -------------------- #{padleft 20 $ showMixedAmountWithoutPrice total} |] tests_Hledger_Cli_Incomestatement :: Test tests_Hledger_Cli_Incomestatement = TestList [ ] hledger-0.26/Hledger/Cli/Main.hs0000644000000000000000000003044112550610443014544 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.Char (isDigit) import Data.List import Safe import System.Console.CmdArgs.Explicit as C import System.Environment import System.Exit import System.FilePath import System.Process import Text.Printf import Hledger (ensureJournalFileExists) import Hledger.Cli.Add import Hledger.Cli.Accounts 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.Data.Dates (getCurrentDay) import Hledger.Data.RawOptions (RawOpts, optserror) import Hledger.Reports.ReportOptions (dateSpanFromOpts, intervalFromOpts, queryFromOpts) import Hledger.Utils -- | The overall cmdargs mode describing command-line options for hledger. mainmode addons = defMode { modeNames = [progname] ,modeHelp = unlines [] ,modeHelpSuffix = [""] ,modeArgs = ([], Just $ argsFlag "[ARGS]") ,modeGroupModes = Group { -- modes (commands) in named groups: groupNamed = [ ("Data entry commands", [ addmode ]) ,("\nReporting commands", [ printmode ,accountsmode ,balancemode ,registermode ,incomestatementmode ,balancesheetmode ,cashflowmode ,activitymode ,statsmode ]) ] ++ case addons of [] -> [] cs -> [("\nAdd-on commands", map defAddonCommandMode cs)] -- modes in the unnamed group, shown first without a heading: ,groupUnnamed = [ ] -- modes handled but not shown ,groupHidden = [ testmode ,oldconvertmode ] } ,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 = detailedversionflag : inputflags -- included here so they'll not raise a confusing error if present with no COMMAND } } oldconvertmode = (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 = [] } } builtinCommands :: [Mode RawOpts] builtinCommands = let gs = modeGroupModes $ mainmode [] in concatMap snd (groupNamed gs) ++ groupUnnamed gs ++ groupHidden gs builtinCommandNames :: [String] builtinCommandNames = concatMap modeNames builtinCommands -- | 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 = 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 -- | Let's go. 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' dbgIO :: Show a => String -> a -> IO () dbgIO = tracePrettyAtIO 2 dbgIO "running" prognameandversion dbgIO "raw args" args dbgIO "raw args rearranged for cmdargs" args' dbgIO "raw command is probably" rawcmd dbgIO "raw args before command" argsbeforecmd dbgIO "raw args after command" argsaftercmd -- Search PATH for add-ons, excluding any that match built-in names. -- The precise addon names (including file extension) are used for command -- parsing, and the display names are used for displaying the commands list. (addonPreciseNames', addonDisplayNames') <- hledgerAddons let addonPreciseNames = filter (not . (`elem` builtinCommandNames) . dropExtension) addonPreciseNames' let addonDisplayNames = filter (not . (`elem` builtinCommandNames)) addonDisplayNames' -- parse arguments with cmdargs opts <- argsToCliOpts args addonPreciseNames -- select an action and run it. let cmd = command_ opts -- the full matched internal or external command name, if any isInternalCommand = cmd `elem` builtinCommandNames -- not (null cmd) && not (cmd `elem` addons) isExternalCommand = not (null cmd) && cmd `elem` addonPreciseNames -- probably isBadCommand = not (null rawcmd) && null cmd hasHelp args = any (`elem` args) ["--help","-h","-?"] hasVersion = ("--version" `elem`) hasDetailedVersion = ("--version+" `elem`) generalHelp = putStr $ showModeHelp $ mainmode addonDisplayNames 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 dbgIO "processed opts" opts dbgIO "command matched" cmd dbgIO "isNullCommand" isNullCommand dbgIO "isInternalCommand" isInternalCommand dbgIO "isExternalCommand" isExternalCommand dbgIO "isBadCommand" isBadCommand d <- getCurrentDay dbgIO "date span from opts" (dateSpanFromOpts d $ reportopts_ opts) dbgIO "interval from opts" (intervalFromOpts $ reportopts_ opts) dbgIO "query from opts & args" (queryFromOpts d $ reportopts_ opts) let runHledgerCommand -- high priority flags and situations. --help should be highest priority. | hasHelp argsbeforecmd = dbgIO "" "--help before command, showing general help" >> generalHelp | not (hasHelp argsaftercmd) && (hasVersion argsbeforecmd || (hasVersion argsaftercmd && isInternalCommand)) = putStrLn prognameandversion | not (hasHelp argsaftercmd) && (hasDetailedVersion argsbeforecmd || (hasDetailedVersion argsaftercmd && isInternalCommand)) = putStrLn prognameanddetailedversion -- \| (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 = dbgIO "" "no command, showing general help" >> generalHelp | isBadCommand = badCommandError -- internal commands | cmd == "activity" = withJournalDo opts histogram `orShowHelp` activitymode | cmd == "add" = (journalFilePathFromOpts opts >>= (ensureJournalFileExists . head) >> withJournalDo opts add) `orShowHelp` addmode | cmd == "accounts" = withJournalDo opts accounts `orShowHelp` accountsmode | 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 externalargs = argsbeforecmd ++ filter (not.(=="--")) argsaftercmd let shellcmd = printf "%s-%s %s" progname cmd (unwords' externalargs) :: String dbgIO "external command selected" cmd dbgIO "external command arguments" (map quoteIfNeeded externalargs) dbgIO "running shell command" shellcmd system shellcmd >>= exitWith -- deprecated commands | cmd == "convert" = error' (modeHelp oldconvertmode) >> 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.26/Hledger/Cli/Options.hs0000644000000000000000000005410312550610443015314 0ustar0000000000000000{-# LANGUAGE CPP, ScopedTypeVariables, DeriveDataTypeable, FlexibleContexts #-} {-| Common cmdargs modes and flags, a command-line options type, and related utilities used by hledger commands. -} module Hledger.Cli.Options ( -- * cmdargs flags & modes helpflags, detailedversionflag, inputflags, reportflags, outputflags, generalflagsgroup1, generalflagsgroup2, generalflagsgroup3, defMode, defCommandMode, defAddonCommandMode, argsFlag, showModeHelp, withAliases, -- * CLI options CliOpts(..), defcliopts, getCliOpts, decodeRawOpts, rawOptsToCliOpts, checkCliOpts, outputFormats, defaultOutputFormat, -- possibly these should move into argsToCliOpts -- * CLI option accessors -- | These do the extra processing required for some options. aliasesFromOpts, journalFilePathFromOpts, rulesFilePathFromOpts, outputFileFromOpts, outputFormatFromOpts, defaultWidth, widthFromOpts, -- | For register: registerWidthsFromOpts, maybeAccountNameDrop, -- | For balance: lineFormatFromOpts, -- * Other utils hledgerAddons, -- * Tests tests_Hledger_Cli_Options ) where import Prelude () import Prelude.Compat import qualified Control.Exception as C import Control.Monad (when) import Data.List.Compat import Data.List.Split (splitOneOf) import Data.Maybe import Safe import System.Console.CmdArgs import System.Console.CmdArgs.Explicit import System.Console.CmdArgs.Text #ifndef mingw32_HOST_OS import System.Console.Terminfo #endif import System.Directory import System.Environment import System.Exit (exitSuccess) import System.FilePath import Test.HUnit import Text.Parsec import Hledger import Hledger.Data.OutputFormat as OutputFormat import Hledger.Cli.Version -- common cmdargs flags -- | Common help flags: --help, --debug, --version... helpflags :: [Flag RawOpts] helpflags = [ flagNone ["help","h"] (setboolopt "help") "show general help or (after command) command help" -- ,flagNone ["browse-args"] (setboolopt "browse-args") "use a web UI to select options and build up a command line" ,flagReq ["debug"] (\s opts -> Right $ setopt "debug" s opts) "N" "show debug output if N is 1-9 (default: 0)" ,flagNone ["version"] (setboolopt "version") "show version information" ] -- | A hidden flag, just for the hledger executable. detailedversionflag :: Flag RawOpts detailedversionflag = flagNone ["version+"] (setboolopt "version+") "show version information with extra detail" -- | Common input-related flags: --file, --rules-file, --alias... inputflags :: [Flag RawOpts] inputflags = [ flagReq ["file","f"] (\s opts -> Right $ setopt "file" s opts) "FILE" "use a different input file. For stdin, use -" ,flagReq ["rules-file"] (\s opts -> Right $ setopt "rules-file" s opts) "RFILE" "CSV conversion rules file (default: FILE.rules)" ,flagReq ["alias"] (\s opts -> Right $ setopt "alias" s opts) "OLD=NEW" "display accounts named OLD as NEW" ,flagNone ["ignore-assertions"] (setboolopt "ignore-assertions") "ignore any balance assertions in the journal" ] -- | Common report-related flags: --period, --cost, etc. reportflags :: [Flag RawOpts] reportflags = [ flagReq ["begin","b"] (\s opts -> Right $ setopt "begin" s opts) "DATE" "include postings/txns on or after this date" ,flagReq ["end","e"] (\s opts -> Right $ setopt "end" s opts) "DATE" "include postings/txns before this date" ,flagNone ["daily","D"] (setboolopt "daily") "multiperiod/multicolumn report by day" ,flagNone ["weekly","W"] (setboolopt "weekly") "multiperiod/multicolumn report by week" ,flagNone ["monthly","M"] (setboolopt "monthly") "multiperiod/multicolumn report by month" ,flagNone ["quarterly","Q"] (setboolopt "quarterly") "multiperiod/multicolumn report by quarter" ,flagNone ["yearly","Y"] (setboolopt "yearly") "multiperiod/multicolumn report by year" ,flagReq ["period","p"] (\s opts -> Right $ setopt "period" s opts) "PERIODEXP" "set start date, end date, and/or reporting interval all at once (overrides the flags above)" ,flagNone ["date2","aux-date"] (setboolopt "date2") "use postings/txns' secondary dates instead" ,flagNone ["cleared","C"] (setboolopt "cleared") "include only cleared postings/txns" ,flagNone ["pending"] (setboolopt "pending") "include only pending postings/txns" ,flagNone ["uncleared","U"] (setboolopt "uncleared") "include only uncleared (and pending) postings/txns" ,flagNone ["real","R"] (setboolopt "real") "include only non-virtual postings" ,flagReq ["depth"] (\s opts -> Right $ setopt "depth" s opts) "N" "hide accounts/postings deeper than N" ,flagNone ["empty","E"] (setboolopt "empty") "show empty/zero things which are normally omitted" ,flagNone ["cost","B"] (setboolopt "cost") "show amounts in their cost price's commodity" ] -- | Common output-related flags: --output-file, --output-format... outputflags = [ flagReq ["output-file","o"] (\s opts -> Right $ setopt "output-file" s opts) "FILE[.FMT]" "write output to FILE instead of stdout. A recognised FMT suffix influences the format." ,flagReq ["output-format","O"] (\s opts -> Right $ setopt "output-format" s opts) "FMT" "select the output format. Supported formats: txt, csv." ] argsFlag :: FlagHelp -> Arg RawOpts argsFlag desc = flagArg (\s opts -> Right $ setopt "args" s opts) desc generalflagstitle :: String generalflagstitle = "\nGeneral flags" generalflagsgroup1, generalflagsgroup2, generalflagsgroup3 :: (String, [Flag RawOpts]) generalflagsgroup1 = (generalflagstitle, inputflags ++ reportflags ++ helpflags) generalflagsgroup2 = (generalflagstitle, inputflags ++ helpflags) generalflagsgroup3 = (generalflagstitle, helpflags) -- cmdargs mode constructors -- | 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") "Show command help." ] ,groupHidden = [] } ,modeArgs = ([], Nothing) ,modeGroupModes = toGroup [] } -- | A basic subcommand mode with the given command name(s). defCommandMode :: [Name] -> Mode RawOpts defCommandMode names = defMode { modeNames=names ,modeValue=[("command", headDef "" names)] ,modeArgs = ([], Just $ argsFlag "[PATTERNS]") } -- | A basic subcommand mode suitable for an add-on command. defAddonCommandMode :: Name -> Mode RawOpts defAddonCommandMode addon = defMode { modeNames = [addon] ,modeHelp = fromMaybe "" $ lookup (stripAddonExtension addon) standardAddonsHelp ,modeValue=[("command",addon)] ,modeGroupFlags = Group { groupUnnamed = [] ,groupHidden = [] ,groupNamed = [generalflagsgroup1] } ,modeArgs = ([], Just $ argsFlag "[ARGS]") } -- | Built-in descriptions for some of the known external addons, -- since we don't currently have any way to ask them. standardAddonsHelp :: [(String,String)] standardAddonsHelp = [ ("chart", "generate simple balance pie charts") ,("interest", "generate interest transaction entries") ,("irr", "calculate internal rate of return") ,("vty", "start the curses-style interface") ,("web", "start the web interface") ,("accounts", "list account names") ,("balance-csv", "output a balance report as CSV") ,("equity", "show a transaction entry zeroing all accounts") ,("print-unique", "print only transactions with unique descriptions") ,("register-csv", "output a register report as CSV") ,("rewrite", "add specified postings to matched transaction entries") ,("addon", "dummy add-on command for testing") ,("addon2", "dummy add-on command for testing") ,("addon3", "dummy add-on command for testing") ,("addon4", "dummy add-on command for testing") ,("addon5", "dummy add-on command for testing") ,("addon6", "dummy add-on command for testing") ,("addon7", "dummy add-on command for testing") ,("addon8", "dummy add-on command for testing") ,("addon9", "dummy add-on command for testing") ] -- | 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]) -- | Add command aliases to the command's help string. withAliases :: String -> [String] -> String s `withAliases` [] = s s `withAliases` as = s ++ " (" ++ intercalate ", " as ++ ")" -- s `withAliases` (a:[]) = s ++ " (alias: " ++ a ++ ")" -- s `withAliases` as = s ++ " (aliases: " ++ intercalate ", " as ++ ")" -- 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." -- ] -- CliOpts -- | Command line options, used in the @hledger@ package and above. -- This is the \"opts\" used throughout hledger CLI code. -- representing the options that arguments that were provided at -- startup on the command-line. data CliOpts = CliOpts { rawopts_ :: RawOpts ,command_ :: String ,file_ :: [FilePath] ,rules_file_ :: Maybe FilePath ,output_file_ :: Maybe FilePath ,output_format_ :: Maybe String ,alias_ :: [String] ,ignore_assertions_ :: Bool ,debug_ :: Int -- ^ debug level, set by @--debug[=N]@. See also 'Hledger.Utils.debugLevel'. ,no_new_accounts_ :: Bool -- add ,width_ :: Maybe String -- ^ the --width value provided, if any ,available_width_ :: Int -- ^ estimated usable screen width, based on -- 1. the COLUMNS env var, if set -- 2. the width reported by the terminal, if supported -- 3. the default (80) ,reportopts_ :: ReportOpts } deriving (Show, Data, Typeable) instance Default CliOpts where def = defcliopts defcliopts :: CliOpts defcliopts = CliOpts def def def def def def def def def def def defaultWidth def -- | Convert possibly encoded option values to regular unicode strings. decodeRawOpts :: RawOpts -> RawOpts decodeRawOpts = map (\(name',val) -> (name', fromSystemString val)) -- | Default width for hledger console output, when not otherwise specified. defaultWidth :: Int defaultWidth = 80 -- | 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. -- Also records the terminal width, if supported. rawOptsToCliOpts :: RawOpts -> IO CliOpts rawOptsToCliOpts rawopts = do ropts <- rawOptsToReportOpts rawopts mcolumns <- readMay <$> getEnvSafe "COLUMNS" mtermwidth <- #ifdef mingw32_HOST_OS return Nothing #else setupTermFromEnv >>= return . flip getCapability termColumns -- XXX Throws a SetupTermError if the terminfo database could not be read, should catch #endif let availablewidth = head $ catMaybes [mcolumns, mtermwidth, Just defaultWidth] return defcliopts { rawopts_ = rawopts ,command_ = stringopt "command" rawopts ,file_ = map stripquotes $ listofstringopt "file" rawopts ,rules_file_ = maybestringopt "rules-file" rawopts ,output_file_ = maybestringopt "output-file" rawopts ,output_format_ = maybestringopt "output-format" rawopts ,alias_ = map stripquotes $ listofstringopt "alias" rawopts ,debug_ = intopt "debug" rawopts ,ignore_assertions_ = boolopt "ignore-assertions" rawopts ,no_new_accounts_ = boolopt "no-new-accounts" rawopts -- add ,width_ = maybestringopt "width" rawopts ,available_width_ = availablewidth ,reportopts_ = ropts } -- | 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 lineFormatFromOpts ropts of Left err -> optserror $ "could not parse format option: "++err Right _ -> return () -- XXX check registerWidthsFromOpts opts return opts -- Currently only used by some extras/ scripts: -- | 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 where -- | 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) -- CliOpts accessors -- | Get the account name aliases from options, if any. aliasesFromOpts :: CliOpts -> [AccountAlias] aliasesFromOpts = map (\a -> fromparse $ runParser accountaliasp () ("--alias "++quoteIfNeeded a) a) . alias_ -- | Get the (tilde-expanded, absolute) journal file path from -- 1. options, 2. an environment variable, or 3. the default. -- Actually, returns one or more file paths. There will be more -- than one if multiple -f options were provided. journalFilePathFromOpts :: CliOpts -> IO [String] journalFilePathFromOpts opts = do f <- defaultJournalPath d <- getCurrentDirectory mapM (expandPath d) $ ifEmpty (file_ opts) [f] where ifEmpty [] d = d ifEmpty l _ = l -- | Get the expanded, absolute output file path from options, -- or the default (-, meaning stdout). outputFileFromOpts :: CliOpts -> IO FilePath outputFileFromOpts opts = do d <- getCurrentDirectory case output_file_ opts of Just p -> expandPath d p Nothing -> return "-" defaultOutputFormat = "txt" outputFormats = [defaultOutputFormat] ++ ["csv" ] -- | Get the output format from the --output-format option, -- otherwise from a recognised file extension in the --output-file option, -- otherwise the default (txt). outputFormatFromOpts :: CliOpts -> String outputFormatFromOpts opts = case output_format_ opts of Just f -> f Nothing -> case filePathExtension <$> output_file_ opts of Just ext | ext `elem` outputFormats -> ext _ -> defaultOutputFormat -- -- | Get the file name without its last extension, from a file path. -- filePathBaseFileName :: FilePath -> String -- filePathBaseFileName = fst . splitExtension . snd . splitFileName -- | Get the last file extension, without the dot, from a file path. -- May return the null string. filePathExtension :: FilePath -> String filePathExtension = dropWhile (=='.') . snd . splitExtension . snd . splitFileName -- | 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 the width in characters to use for console output. -- This comes from the --width option, or the COLUMNS environment -- variable, or (on posix platforms) the current terminal width, or 80. -- Will raise a parse error for a malformed --width argument. widthFromOpts :: CliOpts -> Int widthFromOpts CliOpts{width_=Nothing, available_width_=w} = w widthFromOpts CliOpts{width_=Just s} = case runParser (read `fmap` many1 digit <* eof) () "(unknown)" s of Left e -> optserror $ "could not parse width option: "++show e Right w -> w -- for register: -- | Get the width in characters to use for the register command's console output, -- and also the description column width if specified (following the main width, comma-separated). -- The widths will be as follows: -- @ -- no --width flag - overall width is the available width (COLUMNS, or posix terminal width, or 80); description width is unspecified (auto) -- --width W - overall width is W, description width is auto -- --width W,D - overall width is W, description width is D -- @ -- Will raise a parse error for a malformed --width argument. registerWidthsFromOpts :: CliOpts -> (Int, Maybe Int) registerWidthsFromOpts CliOpts{width_=Nothing, available_width_=w} = (w, Nothing) registerWidthsFromOpts CliOpts{width_=Just s} = case runParser registerwidthp () "(unknown)" s of Left e -> optserror $ "could not parse width option: "++show e Right ws -> ws where registerwidthp :: Stream [Char] m t => ParsecT [Char] st m (Int, Maybe Int) registerwidthp = do totalwidth <- read `fmap` many1 digit descwidth <- optionMaybe (char ',' >> read `fmap` many1 digit) eof return (totalwidth, descwidth) -- | Drop leading components of accounts names as specified by --drop, but only in --flat mode. maybeAccountNameDrop :: ReportOpts -> AccountName -> AccountName maybeAccountNameDrop opts a | tree_ opts = a | otherwise = accountNameDrop (drop_ opts) a -- for balance, currently: -- | Parse the format option if provided, possibly returning an error, -- otherwise get the default value. lineFormatFromOpts :: ReportOpts -> Either String [OutputFormat] lineFormatFromOpts = maybe (Right defaultBalanceLineFormat) parseStringFormat . format_ -- | Default line format for balance report: "%20(total) %2(depth_spacer)%-(account)" defaultBalanceLineFormat :: [OutputFormat] defaultBalanceLineFormat = [ FormatField False (Just 20) Nothing TotalField , FormatLiteral " " , FormatField True (Just 2) Nothing DepthSpacerField , FormatField True Nothing Nothing AccountField ] -- Other utils -- | Get the sorted unique precise names and display names of hledger -- add-ons found in the current user's PATH. The precise names are the -- add-on's filename with the "hledger-" prefix removed. The display -- names have the file extension removed also, except when it's needed -- for disambiguation. -- -- -- Also when there are exactly two similar names, one with the .hs or -- -- .lhs extension and the other with the .exe extension or no -- -- extension - presumably source and compiled versions of a haskell -- -- script - we exclude the source version. -- -- This function can return add-on names which shadow built-in command -- names, but hledger will ignore these. -- hledgerAddons :: IO ([String],[String]) hledgerAddons = do exes <- hledgerExecutablesInPath let precisenames = -- concatMap dropRedundant $ -- groupBy (\a b -> dropExtension a == dropExtension b) $ map stripprefix exes let displaynames = concatMap stripext $ groupBy (\a b -> dropExtension a == dropExtension b) precisenames return (precisenames, displaynames) where stripprefix = drop (length progname + 1) -- dropRedundant [f,f2] | takeExtension f `elem` ["",".exe"] && takeExtension f2 `elem` [".hs",".lhs"] = [f] -- dropRedundant fs = fs stripext [f] = [dropExtension f] stripext fs = fs -- | Get the sorted unique filenames of all hledger-* executables in -- the current user's PATH. Currently these are: files in any of the -- PATH directories, named hledger-*, with either no extension (and no -- periods in the name) or one of the addonExtensions. Limitations: -- we do not currently check that the file is really a file (not eg a -- directory) or whether it has execute permission. hledgerExecutablesInPath :: IO [String] hledgerExecutablesInPath = do pathdirs <- splitOneOf "[:;]" `fmap` getEnvSafe "PATH" pathfiles <- concat `fmap` mapM getDirectoryContentsSafe pathdirs return $ nub $ sort $ filter isHledgerExeName pathfiles -- XXX should exclude directories and files without execute permission. -- These will do a stat for each hledger-*, probably ok. -- But they need paths, not just filenames -- hledgerexes <- filterM doesFileExist hledgernamed -- hledgerexes' <- filterM isExecutable hledgerexes -- return hledgerexes -- isExecutable f = getPermissions f >>= (return . executable) isHledgerExeName :: String -> Bool isHledgerExeName = isRight . parsewith hledgerexenamep where hledgerexenamep = do _ <- string progname _ <- char '-' _ <- many1 (noneOf ".") optional (string "." >> choice' (map string addonExtensions)) eof stripAddonExtension :: String -> String stripAddonExtension = regexReplace re "" where re = "\\.(" ++ intercalate "|" addonExtensions ++ ")$" addonExtensions :: [String] addonExtensions = ["bat" ,"com" ,"exe" ,"hs" ,"lhs" ,"pl" ,"py" ,"rb" ,"rkt" ,"sh" -- ,"" ] getEnvSafe :: String -> IO String getEnvSafe v = getEnv v `C.catch` (\(_::C.IOException) -> return "") -- XXX should catch only isDoesNotExistError e getDirectoryContentsSafe :: FilePath -> IO [String] getDirectoryContentsSafe d = (filter (not . (`elem` [".",".."])) `fmap` getDirectoryContents d) `C.catch` (\(_::C.IOException) -> return []) -- 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) -- tests tests_Hledger_Cli_Options :: Test tests_Hledger_Cli_Options = TestList [ ] hledger-0.26/Hledger/Cli/Print.hs0000644000000000000000000000726212550610443014761 0ustar0000000000000000{-| A ledger-compatible @print@ command. -} module Hledger.Cli.Print ( printmode ,print' ,tests_Hledger_Cli_Print ) where import Data.List import System.Console.CmdArgs.Explicit import Test.HUnit import Text.CSV import Hledger import Hledger.Cli.Options import Hledger.Cli.Utils printmode = (defCommandMode $ ["print"] ++ aliases) { modeHelp = "show transaction entries" `withAliases` aliases ,modeGroupFlags = Group { groupUnnamed = outputflags ,groupHidden = [] ,groupNamed = [generalflagsgroup1] } } where aliases = [] -- | Print journal transactions in standard format. print' :: CliOpts -> Journal -> IO () print' opts@CliOpts{reportopts_=ropts} j = do d <- getCurrentDay let q = queryFromOpts d ropts fmt = outputFormatFromOpts opts (render, ropts') = case fmt of "csv" -> ((++"\n") . printCSV . entriesReportAsCsv, ropts{accountlistmode_=ALFlat}) _ -> (entriesReportAsText, ropts) writeOutput opts $ render $ entriesReport ropts' q j entriesReportAsText :: EntriesReport -> String entriesReportAsText items = concatMap showTransactionUnelided items -- XXX -- 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" -- ,"" -- ] -- ] entriesReportAsCsv :: EntriesReport -> CSV entriesReportAsCsv items = concat $ ([["nth","date","date2","status","code","description","comment","account","amount","commodity","credit","debit","status","posting-comment"]]:).snd $ mapAccumL (\n e -> (n + 1, transactionToCSV n e)) 0 items transactionToCSV :: Integer -> Transaction -> CSV transactionToCSV n t = map (\p -> show n:date:date2:status:code:description:comment:p) (concatMap postingToCSV $ tpostings t) where description = tdescription t date = showDate (tdate t) date2 = maybe "" showDate (tdate2 t) status = show $ tstatus t code = tcode t comment = chomp $ strip $ tcomment t postingToCSV :: Posting -> CSV postingToCSV p = map (\(a@(Amount {aquantity=q,acommodity=c})) -> let a_ = a{acommodity=""} in let amount = showAmount a_ in let commodity = c in let credit = if q < 0 then showAmount $ negate a_ else "" in let debit = if q > 0 then showAmount a_ else "" in account:amount:commodity:credit:debit:status:comment:[]) amounts where Mixed amounts = pamount p status = show $ pstatus p account = showAccountName Nothing (ptype p) (paccount p) comment = chomp $ strip $ pcomment p tests_Hledger_Cli_Print = TestList [] -- tests_showTransactions hledger-0.26/Hledger/Cli/Register.hs0000644000000000000000000001546612550610443015456 0ustar0000000000000000{-# LANGUAGE CPP #-} {-| A ledger-compatible @register@ command. -} module Hledger.Cli.Register ( registermode ,register ,postingsReportAsText -- ,showPostingWithBalanceForVty ,tests_Hledger_Cli_Register ) where import Data.List import Data.Maybe import System.Console.CmdArgs.Explicit import Text.CSV import Test.HUnit import Text.Printf import Hledger import Hledger.Cli.Options import Hledger.Cli.Utils registermode = (defCommandMode $ ["register"] ++ aliases) { modeHelp = "show postings and running total" `withAliases` aliases ,modeGroupFlags = Group { groupUnnamed = [ flagNone ["historical","H"] (\opts -> setboolopt "historical" opts) "include prior postings in the running total" ,flagNone ["average","A"] (\opts -> setboolopt "average" opts) "show a running average instead of the running total (implies --empty)" ,flagNone ["related","r"] (\opts -> setboolopt "related" opts) "show postings' siblings instead" ,flagReq ["width","w"] (\s opts -> Right $ setopt "width" s opts) "N" (unlines ["set output width (default:" #ifdef mingw32_HOST_OS ,(show defaultWidth) #else ,"terminal width" #endif ,"or COLUMNS. -wN,M sets description width as well)" ]) ] ++ outputflags ,groupHidden = [] ,groupNamed = [generalflagsgroup1] } } where aliases = ["reg"] -- | Print a (posting) register report. register :: CliOpts -> Journal -> IO () register opts@CliOpts{reportopts_=ropts} j = do d <- getCurrentDay let fmt = outputFormatFromOpts opts render | fmt=="csv" = const ((++"\n") . printCSV . postingsReportAsCsv) | otherwise = postingsReportAsText writeOutput opts $ render opts $ postingsReport ropts (queryFromOpts d ropts) j postingsReportAsCsv :: PostingsReport -> CSV postingsReportAsCsv (_,is) = ["date","description","account","amount","running total or balance"] : map postingsReportItemAsCsvRecord is postingsReportItemAsCsvRecord :: PostingsReportItem -> Record postingsReportItemAsCsvRecord (_, _, _, p, b) = [date,desc,acct,amt,bal] where date = showDate $ postingDate p desc = maybe "" tdescription $ ptransaction p acct = bracket $ paccount p where bracket = case ptype p of BalancedVirtualPosting -> (\s -> "["++s++"]") VirtualPosting -> (\s -> "("++s++")") _ -> id amt = showMixedAmountOneLineWithoutPrice $ pamount p bal = showMixedAmountOneLineWithoutPrice b -- | 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 (specified, terminal width, or 80) --------------------> -- date (10) description account amount (12) balance (12) -- DDDDDDDDDD dddddddddddddddddddd aaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA -- @ -- If description's width is specified, account will use the remaining space. -- Otherwise, description and account divide up the space equally. -- -- With a reporting interval, the layout is like so: -- @ -- <---------------- width (specified, terminal width, or 80) --------------------> -- date (21) account amount (12) balance (12) -- DDDDDDDDDDDDDDDDDDDDD aaaaaaaaaaaaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA -- @ -- -- date and description are shown for the first posting of a transaction only. -- postingsReportItemAsText :: CliOpts -> PostingsReportItem -> String postingsReportItemAsText opts (mdate, menddate, mdesc, p, b) = intercalate "\n" $ [printf ("%-"++datew++"s %-"++descw++"s %-"++acctw++"s %"++amtw++"s %"++balw++"s") date desc acct amtfirstline balfirstline] ++ [printf (spacer ++ "%"++amtw++"s %"++balw++"s") a b | (a,b) <- zip amtrest balrest ] where -- calculate widths (totalwidth,mdescwidth) = registerWidthsFromOpts opts amtwidth = 12 balwidth = 12 (datewidth, date) = case (mdate,menddate) of (Just _, Just _) -> (21, showDateSpan (DateSpan mdate menddate)) (Nothing, Just _) -> (21, "") (Just d, Nothing) -> (10, showDate d) _ -> (10, "") remaining = totalwidth - (datewidth + 1 + 2 + amtwidth + 2 + balwidth) (descwidth, acctwidth) | hasinterval = (0, remaining - 2) | otherwise = (w, remaining - 2 - w) where hasinterval = isJust menddate w = fromMaybe ((remaining - 2) `div` 2) mdescwidth [datew,descw,acctw,amtw,balw] = map show [datewidth,descwidth,acctwidth,amtwidth,balwidth] -- gather content desc = maybe "" (take descwidth . elideRight descwidth) mdesc acct = parenthesise $ elideAccountName awidth $ paccount p where (parenthesise, awidth) = case ptype p of BalancedVirtualPosting -> (\s -> "["++s++"]", acctwidth-2) VirtualPosting -> (\s -> "("++s++")", acctwidth-2) _ -> (id,acctwidth) amt = showMixedAmountWithoutPrice $ pamount p bal = showMixedAmountWithoutPrice b -- alternate behaviour, show null amounts as 0 instead of blank -- amt = if null amt' then "0" else amt' -- bal = if null bal' then "0" else bal' (amtlines, ballines) = (lines amt, lines bal) (amtlen, ballen) = (length amtlines, length ballines) numlines = max 1 (max amtlen ballen) (amtfirstline:amtrest) = take numlines $ amtlines ++ repeat "" -- posting amount is top-aligned (balfirstline:balrest) = take numlines $ replicate (numlines - ballen) "" ++ ballines -- balance amount is bottom-aligned spacer = replicate (totalwidth - (amtwidth + 2 + balwidth)) ' ' -- 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.26/Hledger/Cli/Stats.hs0000644000000000000000000001106112550610443014753 0ustar0000000000000000{-| Print some statistics for the journal. -} module Hledger.Cli.Stats ( statsmode ,stats ) where import Data.List import Data.Maybe import Data.Ord import Data.HashSet (size, fromList) import Data.Text (pack) import Data.Time.Calendar import System.Console.CmdArgs.Explicit import Text.Printf import qualified Data.Map as Map import Hledger import Hledger.Cli.Options import Prelude hiding (putStr) import Hledger.Cli.Utils (writeOutput) statsmode = (defCommandMode $ ["stats"] ++ aliases) { modeHelp = "show some journal statistics" `withAliases` aliases ,modeGroupFlags = Group { groupUnnamed = [ flagReq ["output-file","o"] (\s opts -> Right $ setopt "output-file" s opts) "FILE[.FMT]" "write output to FILE instead of stdout. A recognised FMT suffix influences the format." ] ,groupHidden = [] ,groupNamed = [generalflagsgroup1] } } where aliases = [] -- like Register.summarisePostings -- | Print various statistics for the journal. stats :: CliOpts -> Journal -> IO () stats opts@CliOpts{reportopts_=reportopts_} j = do d <- getCurrentDay let q = queryFromOpts d reportopts_ l = ledgerFromJournal q j reportspan = (ledgerDateSpan l) `spanDefaultsFrom` (queryDateSpan False q) intervalspans = splitSpan (intervalFromOpts reportopts_) reportspan showstats = showLedgerStats l d s = intercalate "\n" $ map showstats intervalspans writeOutput opts 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 $ 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 $ size $ fromList $ map (pack . 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.26/Hledger/Cli/Tests.hs0000644000000000000000000000364512550610443014770 0ustar0000000000000000-- {-# OPTIONS_GHC -F -pgmF htfpp #-} {-# LANGUAGE CPP #-} {- | A simple test runner for hledger's built-in unit tests. -} module Hledger.Cli.Tests ( testmode ,test' ) 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 testmode = (defCommandMode ["test"]) { modeHelp = "run built-in self-tests" ,modeArgs = ([], Just $ argsFlag "[REGEXPS]") ,modeGroupFlags = Group { groupUnnamed = [] ,groupHidden = [] ,groupNamed = [generalflagsgroup3] } } -- | 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.26/Hledger/Cli/Utils.hs0000644000000000000000000001673212550610443014767 0ustar0000000000000000{-# LANGUAGE ScopedTypeVariables, CPP #-} {-| Utilities for top-level modules and ghci. See also Hledger.Read and Hledger.Utils. -} module Hledger.Cli.Utils ( withJournalDo, writeOutput, 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 import Text.Regex.TDFA ((=~)) -- 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 <- readJournalFiles Nothing rulespath (not $ ignore_assertions_ opts) journalpath either error' (cmd opts . journalApplyAliases (aliasesFromOpts opts)) ej -- | Write some output to stdout or to a file selected by --output-file. writeOutput :: CliOpts -> String -> IO () writeOutput opts s = do f <- outputFileFromOpts opts (if f == "-" then putStr else writeFile f) s -- -- | 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 True $ 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 ? -- XXX nasty regex types intruding, add a simpler api to Hledger.Utils.Regex backupNumber :: FilePath -> FilePath -> Maybe Int backupNumber f g = case g =~ ("^" ++ f ++ "\\.([0-9]+)$") of (_::FilePath, _::FilePath, _::FilePath, [ext::FilePath]) -> readMay ext _ -> Nothing hledger-0.26/Hledger/Cli/Version.hs0000644000000000000000000000507512550610443015312 0ustar0000000000000000{-# LANGUAGE CPP, TemplateHaskell #-} {- Version number-related utilities. See also the Makefile. -} module Hledger.Cli.Version ( progname, version, prognameandversion, prognameanddetailedversion, binaryfilename ) where import System.Info (os, arch) import Text.Printf import Hledger.Data.Types (numberRepresentation) import Hledger.Utils -- package name and version from the cabal file progname, version, prognameandversion, prognameanddetailedversion :: String progname = "hledger" #ifdef VERSION version = VERSION #else version = "dev build" #endif prognameandversion = progname ++ " " ++ version prognameanddetailedversion = printf "%s %s, using %s" progname version numberRepresentation -- 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.26/test/0000755000000000000000000000000012550610443012220 5ustar0000000000000000hledger-0.26/test/test.hs0000644000000000000000000000033312550610443013532 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