{-|
hledger's built-in commands, and helpers for printing the commands list.

New built-in commands should be added in four places below:
the export list, the import list, builtinCommands, commandsListSections.

-}

-- Note: commands list rendering is intensely sensitive to change,
-- very easy to break in ways that tests currently do not catch.

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}

module Hledger.Cli.Commands (
   commands
  ,mainmode
  ,runUnitTests
  ,builtinCommands
  ,builtinCommandNames
  ,addonCommandNames
  ,knownAddonCommandNames
  ,findBuiltinCommand
  ,knownCommands
  ,CommandCategories(..)
  ,commandCategories
  ,printCommandsList
  ,tests_Hledger_Cli
  ,module Hledger.Cli.Commands.Accounts
  ,module Hledger.Cli.Commands.Activity
  ,module Hledger.Cli.Commands.Add
  ,module Hledger.Cli.Commands.Aregister
  ,module Hledger.Cli.Commands.Balance
  ,module Hledger.Cli.Commands.Balancesheet
  ,module Hledger.Cli.Commands.Balancesheetequity
  ,module Hledger.Cli.Commands.Cashflow
  ,module Hledger.Cli.Commands.Check
  ,module Hledger.Cli.Commands.Close
  ,module Hledger.Cli.Commands.Codes
  ,module Hledger.Cli.Commands.Commodities
  ,module Hledger.Cli.Commands.Descriptions
  ,module Hledger.Cli.Commands.Diff
  ,module Hledger.Cli.Commands.Files
  ,module Hledger.Cli.Commands.Get
  ,module Hledger.Cli.Commands.Help
  ,module Hledger.Cli.Commands.Holdings
  ,module Hledger.Cli.Commands.Import
  ,module Hledger.Cli.Commands.Incomestatement
  ,module Hledger.Cli.Commands.Init
  ,module Hledger.Cli.Commands.Notes
  ,module Hledger.Cli.Commands.Payees
  ,module Hledger.Cli.Commands.Prices
  ,module Hledger.Cli.Commands.Print
  ,module Hledger.Cli.Commands.Register
  ,module Hledger.Cli.Commands.Rewrite
  ,module Hledger.Cli.Commands.Roi
  ,module Hledger.Cli.Commands.Run
  ,module Hledger.Cli.Commands.Setup
  ,module Hledger.Cli.Commands.Stats
  ,module Hledger.Cli.Commands.Tags
  ,module Hledger.Cli.Commands.Transactions
) 
where

import Data.Char (isSpace, toLower)
import Data.Either (isRight)
import Data.List
import Data.List.Extra (groupSortOn, nubOrdOn, nubSort)
import Data.Text (Text)
import Data.Text qualified as T
import Data.Time.Calendar
import Safe (headErr, headMay, maximumDef)
import System.Console.CmdArgs.Explicit as C
import System.Environment (withArgs)
import System.FilePath (dropExtension, takeBaseName, takeExtension)
import Test.Tasty (defaultMain)
import Text.Megaparsec
import Text.Megaparsec.Char

import Hledger
import Hledger.Cli.CliOptions
import Hledger.Cli.Conf (CommandAlias, CommandLine, confAliases, getConf')
import Hledger.Cli.Commands.Accounts
import Hledger.Cli.Commands.Activity
import Hledger.Cli.Commands.Add
import Hledger.Cli.Commands.Aregister
import Hledger.Cli.Commands.Balance
import Hledger.Cli.Commands.Balancesheet
import Hledger.Cli.Commands.Balancesheetequity
import Hledger.Cli.Commands.Cashflow
import Hledger.Cli.Commands.Check
import Hledger.Cli.Commands.Close
import Hledger.Cli.Commands.Codes
import Hledger.Cli.Commands.Commodities
import Hledger.Cli.Commands.Descriptions
import Hledger.Cli.Commands.Diff
import Hledger.Cli.Commands.Files
import Hledger.Cli.Commands.Get
import Hledger.Cli.Commands.Help
import Hledger.Cli.Commands.Holdings
import Hledger.Cli.Commands.Import
import Hledger.Cli.Commands.Incomestatement
import Hledger.Cli.Commands.Init
import Hledger.Cli.Commands.Notes
import Hledger.Cli.Commands.Payees
import Hledger.Cli.Commands.Prices
import Hledger.Cli.Commands.Print
import Hledger.Cli.Commands.Register
import Hledger.Cli.Commands.Rewrite
import Hledger.Cli.Commands.Roi
import Hledger.Cli.Commands.Run
import Hledger.Cli.Commands.Setup
import Hledger.Cli.Commands.Stats
import Hledger.Cli.Commands.Tags
import Hledger.Cli.Commands.Transactions
import Hledger.Cli.Utils (tests_Cli_Utils, openBrowserOn)
import Hledger.Cli.Commands.Quickref (showQuickref)
import Hledger.Cli.DocFiles (runTldrForPage)
import Data.Functor ((<&>), void)

-- | The cmdargs subcommand mode (for command-line parsing)
-- and IO action (for doing the command's work) for each builtin command.
-- Command actions take parsed CLI options and a (lazy) finalised journal.
builtinCommands :: [(Mode RawOpts, CliOpts -> Journal -> IO ())]
builtinCommands :: [(Mode RawOpts, CliOpts -> Journal -> IO ())]
builtinCommands = [
   (Mode RawOpts
accountsmode           , CliOpts -> Journal -> IO ()
accounts)
  ,(Mode RawOpts
activitymode           , CliOpts -> Journal -> IO ()
activity)
  ,(Mode RawOpts
addmode                , CliOpts -> Journal -> IO ()
add)
  ,(Mode RawOpts
aregistermode          , CliOpts -> Journal -> IO ()
aregister)
  ,(Mode RawOpts
balancemode            , CliOpts -> Journal -> IO ()
balance)
  ,(Mode RawOpts
balancesheetequitymode , CliOpts -> Journal -> IO ()
balancesheetequity)
  ,(Mode RawOpts
balancesheetmode       , CliOpts -> Journal -> IO ()
balancesheet)
  ,(Mode RawOpts
cashflowmode           , CliOpts -> Journal -> IO ()
cashflow)
  ,(Mode RawOpts
checkmode              , CliOpts -> Journal -> IO ()
check)
  ,(Mode RawOpts
closemode              , CliOpts -> Journal -> IO ()
close)
  ,(Mode RawOpts
codesmode              , CliOpts -> Journal -> IO ()
codes)
  ,(Mode RawOpts
commoditiesmode        , CliOpts -> Journal -> IO ()
commodities)
  ,(Mode RawOpts
descriptionsmode       , CliOpts -> Journal -> IO ()
descriptions)
  ,(Mode RawOpts
diffmode               , CliOpts -> Journal -> IO ()
diff)
  ,(Mode RawOpts
filesmode              , CliOpts -> Journal -> IO ()
files)
  ,(Mode RawOpts
getmode                , CliOpts -> Journal -> IO ()
getcmd)
  ,(Mode RawOpts
helpmode               , CliOpts -> Journal -> IO ()
help)
  ,(Mode RawOpts
holdingsmode           , CliOpts -> Journal -> IO ()
holdings)
  ,(Mode RawOpts
importmode             , CliOpts -> Journal -> IO ()
importcmd)
  ,(Mode RawOpts
incomestatementmode    , CliOpts -> Journal -> IO ()
incomestatement)
  ,(Mode RawOpts
initmode               , CliOpts -> Journal -> IO ()
initcmd)
  ,(Mode RawOpts
notesmode              , CliOpts -> Journal -> IO ()
notes)
  ,(Mode RawOpts
payeesmode             , CliOpts -> Journal -> IO ()
payees)
  ,(Mode RawOpts
pricesmode             , CliOpts -> Journal -> IO ()
prices)
  ,(Mode RawOpts
printmode              , CliOpts -> Journal -> IO ()
print')
  ,(Mode RawOpts
registermode           , CliOpts -> Journal -> IO ()
register)
  ,(Mode RawOpts
rewritemode            , CliOpts -> Journal -> IO ()
rewrite)
  ,(Mode RawOpts
roimode                , CliOpts -> Journal -> IO ()
roi)
  ,(Mode RawOpts
runmode                , CliOpts -> Journal -> IO ()
runOrReplStub)
  ,(Mode RawOpts
replmode               , CliOpts -> Journal -> IO ()
runOrReplStub)
  ,(Mode RawOpts
setupmode              , CliOpts -> Journal -> IO ()
setup)
  ,(Mode RawOpts
statsmode              , CliOpts -> Journal -> IO ()
stats)
  ,(Mode RawOpts
tagsmode               , CliOpts -> Journal -> IO ()
tags)
  ,(Mode RawOpts
transactionsmode       , CliOpts -> Journal -> IO ()
transactions)
  ]

-- | The overall cmdargs mode describing hledger's command-line options and subcommands.
-- The names of known addons are provided so they too can be recognised as commands.
mainmode :: [String] -> Mode RawOpts
mainmode [String]
addons = Mode RawOpts
defMode {
  modeNames = [progname ++ " [COMMAND]"]
 ,modeArgs = ([], Just $ argsFlag "[ARGS]")
 ,modeHelp = unlines ["hledger's main command line interface. Run with no ARGS to see a quick reference, or `hledger help commands` to list commands."]
 ,modeGroupModes = Group {
    -- subcommands in the unnamed group, shown first:
    groupUnnamed = [
     ]
    -- subcommands in named groups:
   ,groupNamed = [
     ]
    -- subcommands handled but not shown in the help:
   ,groupHidden = map fst builtinCommands ++ map addonCommandMode addons
   }
 ,modeGroupFlags = Group {
     -- flags in named groups: (keep synced with Hledger.Cli.CliOptions.highlightHelp)
     groupNamed = cligeneralflagsgroups1
     -- flags in the unnamed group, shown last: (keep synced with dropUnsupportedOpts)
    ,groupUnnamed = confflags
     -- other flags handled but not shown in help:
    ,groupHidden = hiddenflagsformainmode
    }
 ,modeHelpSuffix = []
 }

-- | The help command: show some part of hledger's documentation, dispatching on
-- its first argument to a subtopic. Recognised subtopics are: quickref (the quick
-- reference card), commands (the commands list), usage [CMD] (command-line usage,
-- general or for CMD), manual [TOPIC] (the manual, optionally at TOPIC),
-- examples [CMD..] (brief tldr examples), and home/install/relnotes/docs/support/sponsor
-- (open the corresponding hledger.org page in a web browser).
-- With no argument it shows the quickref card; any other first argument is
-- treated as a manual topic.
help :: CliOpts -> Journal -> IO ()
help :: CliOpts -> Journal -> IO ()
help CliOpts
opts Journal
_
  -- With -l, always list matching manual topics, bypassing the special
  -- subcommands (commands, usage, examples, install, etc). A leading "manual"
  -- argument is the (now implicit) subcommand name, so it's consumed rather than
  -- treated as a topic; thus `help -l manual` behaves like `help manual -l`.
  | String -> RawOpts -> Bool
boolopt String
"help-l" (CliOpts -> RawOpts
rawopts_ CliOpts
opts) = CliOpts -> Maybe String -> IO ()
manual CliOpts
opts (Maybe String -> IO ()) -> Maybe String -> IO ()
forall a b. (a -> b) -> a -> b
$ [String] -> Maybe String
forall a. [a] -> Maybe a
headMay ([String] -> Maybe String) -> [String] -> Maybe String
forall a b. (a -> b) -> a -> b
$ case [String]
args of
      String
"manual":[String]
rest -> [String]
rest
      [String]
_             -> [String]
args
  | Bool
otherwise = case [String]
args of
    []              -> IO ()
showQuickref
    String
"quickref":[String]
_    -> IO ()
showQuickref
    String
"commands":[String]
_    -> CliOpts -> Journal -> IO ()
commands CliOpts
opts Journal
nulljournal
    String
"usage":[String]
rest    ->
      let usagemode :: Mode RawOpts
usagemode = case [String]
rest of
            String
c:[String]
_ | Just (Mode RawOpts
m,CliOpts -> Journal -> IO ()
_) <- String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())
findBuiltinCommand String
c -> Mode RawOpts
m
            [String]
_                                        -> [String] -> Mode RawOpts
mainmode []
      in String -> IO ()
runPager (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ Mode RawOpts -> String
forall a. Mode a -> String
showModeUsage Mode RawOpts
usagemode String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"\n"
    String
"manual":[String]
rest   -> CliOpts -> Maybe String -> IO ()
manual CliOpts
opts ([String] -> Maybe String
forall a. [a] -> Maybe a
headMay [String]
rest)
    String
"examples":[String]
rest -> (String -> IO ()) -> [String] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ String -> IO ()
runTldrForPage ([String] -> IO ()) -> [String] -> IO ()
forall a b. (a -> b) -> a -> b
$
                         if [String] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [String]
rest then [String
"hledger"] else (String -> String) -> [String] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map (String
"hledger-"String -> String -> String
forall a. Semigroup a => a -> a -> a
<>) [String]
rest
    String
"home":[String]
_        -> IO ExitCode -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (IO ExitCode -> IO ()) -> IO ExitCode -> IO ()
forall a b. (a -> b) -> a -> b
$ String -> IO ExitCode
openBrowserOn String
"https://hledger.org"
    String
"install":[String]
_     -> IO ExitCode -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (IO ExitCode -> IO ()) -> IO ExitCode -> IO ()
forall a b. (a -> b) -> a -> b
$ String -> IO ExitCode
openBrowserOn String
"https://hledger.org/install.html"
    String
"relnotes":[String]
_    -> IO ExitCode -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (IO ExitCode -> IO ()) -> IO ExitCode -> IO ()
forall a b. (a -> b) -> a -> b
$ String -> IO ExitCode
openBrowserOn String
"https://hledger.org/relnotes.html"
    String
"docs":[String]
_        -> IO ExitCode -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (IO ExitCode -> IO ()) -> IO ExitCode -> IO ()
forall a b. (a -> b) -> a -> b
$ String -> IO ExitCode
openBrowserOn String
"https://hledger.org/doc.html"
    String
"support":[String]
_     -> IO ExitCode -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (IO ExitCode -> IO ()) -> IO ExitCode -> IO ()
forall a b. (a -> b) -> a -> b
$ String -> IO ExitCode
openBrowserOn String
"https://hledger.org/support.html"
    String
"sponsor":[String]
_     -> IO ExitCode -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (IO ExitCode -> IO ()) -> IO ExitCode -> IO ()
forall a b. (a -> b) -> a -> b
$ String -> IO ExitCode
openBrowserOn String
"https://hledger.org/sponsor.html"
    [String]
_               -> CliOpts -> Maybe String -> IO ()
manual CliOpts
opts ([String] -> Maybe String
forall a. [a] -> Maybe a
headMay [String]
args)
  where
    args :: [String]
args = String -> RawOpts -> [String]
listofstringopt String
"args" (CliOpts -> RawOpts
rawopts_ CliOpts
opts)

-- figlet -f FONTNAME hledger, then escape backslashes
_banner_slant :: [String]
_banner_slant = Int -> [String] -> [String]
forall a. Int -> [a] -> [a]
drop Int
1 [String
""
    -----------------------------------------80-------------------------------------
  ,String
"    __    __         __               "
  ,String
"   / /_  / /__  ____/ /___ ____  _____"
  ,String
"  / __ \\/ / _ \\/ __  / __ `/ _ \\/ ___/"
  ,String
" / / / / /  __/ /_/ / /_/ /  __/ /    "
  ,String
"/_/ /_/_/\\___/\\__,_/\\__, /\\___/_/     "
  ,String
"                   /____/             "
  ]

_banner_smslant :: [String]
_banner_smslant = Int -> [String] -> [String]
forall a. Int -> [a] -> [a]
drop Int
1 [String
""
  ,String
"   __   __       __            "
  ,String
"  / /  / /__ ___/ /__ ____ ____"
  ,String
" / _ \\/ / -_) _  / _ `/ -_) __/"
  ,String
"/_//_/_/\\__/\\_,_/\\_, /\\__/_/   "
  ,String
"                /___/          "
  ]

_banner_speed :: [String]
_banner_speed = Int -> [String] -> [String]
forall a. Int -> [a] -> [a]
drop Int
1 [String
""
  ,String
"______ ______    _________                    "
  ,String
"___  /____  /__________  /______ _____________"
  ,String
"__  __ \\_  /_  _ \\  __  /__  __ `/  _ \\_  ___/"
  ,String
"_  / / /  / /  __/ /_/ / _  /_/ //  __/  /    "
  ,String
"/_/ /_//_/  \\___/\\__,_/  _\\__, / \\___//_/     "
  ,String
"                         /____/               "
  ]

-- accent and gradientStr, used for the commands list and REPL banners, are in Hledger.Utils.IO.

-- | The three categories of command which the commands list can show:
-- the commands built in to hledger, the addon commands installed in PATH,
-- and the command aliases defined in the config file.
data CommandCategories = CommandCategories {
   CommandCategories -> Bool
showbuiltins_ :: Bool
  ,CommandCategories -> Bool
showaddons_   :: Bool
  ,CommandCategories -> Bool
showaliases_  :: Bool
  }

-- | Which command categories are selected by the --builtins, --addons and
-- --aliases flags in these options. Each of those flags limits the commands
-- list to one category; with none of them, all categories are shown.
commandCategories :: RawOpts -> CommandCategories
commandCategories :: RawOpts -> CommandCategories
commandCategories RawOpts
rawopts
  | Bool -> Bool
not (Bool
builtins Bool -> Bool -> Bool
|| Bool
addons Bool -> Bool -> Bool
|| Bool
cmdaliases) = Bool -> Bool -> Bool -> CommandCategories
CommandCategories Bool
True Bool
True Bool
True
  | Bool
otherwise                              = Bool -> Bool -> Bool -> CommandCategories
CommandCategories Bool
builtins Bool
addons Bool
cmdaliases
  where
    builtins :: Bool
builtins   = String -> RawOpts -> Bool
boolopt String
"builtins" RawOpts
rawopts
    addons :: Bool
addons     = String -> RawOpts -> Bool
boolopt String
"addons"   RawOpts
rawopts
    cmdaliases :: Bool
cmdaliases = String -> RawOpts -> Bool
boolopt String
"aliases"  RawOpts
rawopts

-- | The builtin and known addon commands, with their standard abbreviation and
-- short description, in the sections and order in which the commands list shows them.
-- Each command line has the format
--
--  COMMAND (ABBREV) DESCRIPTION
--
-- prefixed with a space for a builtin command, or a + for a known addon command
-- (which is shown only when hledger-COMMAND is found in $PATH at runtime).
-- Each section is sorted alphabetically, except that setup comes first in MAINTENANCE.
--
-- Keep synced with builtinCommands above, the command docs (Commands/\*.md),
-- commands.m4, and hledger.m4.md -> Commands.
--
-- TODO: generate more of this automatically.
--
commandsListSections :: [(String, [String])]
commandsListSections :: [(String, [String])]
commandsListSections = [
    -----------------------------------------80-------------------------------------
  (String
"USER INTERFACES",
  [String
" help (h)                 show documentation and examples"
  ,String
" repl                     run multiple commands from an interactive prompt"
  ,String
" run                      run multiple commands from a file or command line"
  ,String
"+ui                       run a terminal UI"
  ,String
"+web                      run a web UI"
  ])
    -----------------------------------------80-------------------------------------
 ,(String
"ENTERING DATA",
  [String
" add                      add transactions using terminal prompts"
  ,String
" get                      fetch transaction and price data for import"
  ,String
"+iadd                     add transactions using a TUI (hledger-iadd)"
  ,String
" import                   add new transactions from other files, eg CSV files"
  ])
    -----------------------------------------80-------------------------------------
 ,(String
"REPORTS",
  [String
" accounts (acc)           account names"
  ,String
" activity                 transaction or posting counts, as a bar chart"
  ,String
" aregister (areg)         an account's transactions & running balance"
  ,String
" balance (bal)            balance changes, end balances, gains, budgets & more"
  ,String
" balancesheet (bs)        assets, liabilities and net worth"
  ,String
" balancesheetequity (bse) assets, liabilities and equity"
  ,String
"+bar                      simple balance/change bar charts for hledger 1"        -- hledger-bar
  ,String
" cashflow (cf)            changes in liquid assets"
  ,String
" codes                    transaction codes"
  ,String
" commodities (comm)       commodity/currency symbols"
  ,String
" descriptions (desc)      transaction descriptions"
  ,String
" files                    input files used"
  ,String
" holdings                 investment holdings and performance"
  ,String
" incomestatement (is)     revenues and expenses"
  ,String
" notes                    the note part of transaction descriptions"
  ,String
" payees                   the payee part of transaction descriptions"
  ,String
"+plot                     advanced matplotlib charts, as gui/svg/png/pdf"        -- hledger-utils
  ,String
" prices                   market prices"
  ,String
" print                    transaction entries, or a whole exported journal"
  ,String
" register (reg)           matched postings & running total, across accounts"
  ,String
" roi                      return on investments"
  ,String
" stats                    journal statistics"
  ,String
" tags                     tag names"
  ,String
" transactions (tx)        transactions, in compact one-line format"
  ])
    -----------------------------------------80-------------------------------------
 ,(String
"MAINTENANCE",
  [String
" setup                    check your hledger installation"
  ,String
" init                     create starter journal files"
  ,String
" check                    check that your journal is valid"
  ,String
"+check-tagfiles           check that files referenced in tag values exist"       -- hledger-check-tagfiles
  ,String
" diff                     compare an account's transactions in two journals"
  ,String
"+edit                     edit matched transactions with $EDITOR"                -- hledger-utils
  ,String
"+git                      simple version control of the journal with git"        -- hledger-git
  ,String
"+jj                       simple version control of the journal with jj"         -- hledger-jj
  ])
    -----------------------------------------80-------------------------------------
 ,(String
"GENERATING DATA",
  [String
" close                    generate transactions to zero/restore/assert balances"
  ,String
"+interest                 generate transactions transferring accrued interest"   -- hledger-interest
  ,String
" rewrite                  generate postings by rule, like print --auto"
  ])
    -----------------------------------------80-------------------------------------
 ]

-- | The canonical command names in the sections above, in the order they occur.
-- With a true argument, only the known addon command names.
commandsListCommandNames :: Bool -> [String]
commandsListCommandNames :: Bool -> [String]
commandsListCommandNames Bool
addonsonly =
  [ String
cmdname
  | (String
_, [String]
cmds)      <- [(String, [String])]
commandsListSections
  , Char
prefixchar:String
cmd <- [String]
cmds
  , Char
prefixchar Char -> String -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` Char
'+'Char -> String -> String
forall a. a -> [a] -> [a]
:[Char
' '|Bool -> Bool
not Bool
addonsonly]
  , String
cmdname:[String]
_      <- [String -> [String]
words String
cmd]
  ]

-- | Render the commands list, showing the selected categories of command:
-- the builtin commands and installed known addon commands from the sections above,
-- then the other installed addons, then the config file's command aliases.
-- A section with no commands to show is omitted.
commandsList :: CommandCategories -> [String] -> [(CommandAlias,CommandLine)] -> [String]
commandsList :: CommandCategories -> [String] -> [(String, String)] -> [String]
commandsList CommandCategories
cats [String]
installedaddons [(String, String)]
cmdaliases =
  -- A one-line title heading, in the quickref style.
  String -> String
titleLine String
"HLEDGER COMMANDS"
  String -> [String] -> [String]
forall a. a -> [a] -> [a]
: ((String, [String]) -> [String])
-> [(String, [String])] -> [String]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (String, [String]) -> [String]
forall {t :: * -> *}. Foldable t => (String, t String) -> [String]
rendersection [(String, [String])]
commandsListSections
  [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ [String]
otheraddonssection
  [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ [String]
aliasessection
  where
    rendersection :: (String, t String) -> [String]
rendersection (String
heading, t String
cmds) = case (String -> [String]) -> t String -> [String]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap String -> [String]
selectcommand t String
cmds of
      []    -> []
      [String]
cmds' -> String -> String
bold' String
heading String -> [String] -> [String]
forall a. a -> [a] -> [a]
: [String]
cmds'

    -- Keep a command line only if it is in a selected category, replacing the
    -- category prefix with a space; a known addon must also be installed.
    selectcommand :: String -> [String]
selectcommand (Char
prefixchar:String
cmd) = case Char
prefixchar of
      Char
' ' | CommandCategories -> Bool
showbuiltins_ CommandCategories
cats                    -> [Char
' 'Char -> String -> String
forall a. a -> [a] -> [a]
:String
cmd]
      Char
'+' | CommandCategories -> Bool
showaddons_ CommandCategories
cats, String -> Bool
isinstalled String
cmdname -> [Char
' 'Char -> String -> String
forall a. a -> [a] -> [a]
:String
cmd]
      Char
_                                           -> []
      where cmdname :: String
cmdname = (Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
takeWhile (Bool -> Bool
not(Bool -> Bool) -> (Char -> Bool) -> Char -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
.Char -> Bool
isSpace) String
cmd
    selectcommand [] = []

    isinstalled :: String -> Bool
isinstalled String
cmdname
      | String
cmdname String -> [String] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [String]
installedaddons = Bool
True
      | Bool
otherwise = (Bool -> String) -> Bool -> Bool
forall a. (a -> String) -> a -> a
dbg9With (String -> Bool -> String
forall a b. a -> b -> a
const (String -> Bool -> String) -> String -> Bool -> String
forall a b. (a -> b) -> a -> b
$ String
"hiding uninstalled addon: " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
cmdname) Bool
False

    -- The installed addons which have no slot above, listed in columns.
    -- The heading is always shown, since this is the catch-all addons section.
    otheraddonssection :: [String]
otheraddonssection
      | Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ CommandCategories -> Bool
showaddons_ CommandCategories
cats = []
      | Bool
otherwise = String -> String
bold' String
"OTHER ADDONS" String -> [String] -> [String]
forall a. a -> [a] -> [a]
: (String -> String) -> [String] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map (Char
' 'Char -> String -> String
forall a. a -> [a] -> [a]
:) (String -> [String]
lines (String -> [String]) -> String -> [String]
forall a b. (a -> b) -> a -> b
$ Int -> [String] -> String
multicol Int
79 [String]
otheraddons)
      where otheraddons :: [String]
otheraddons = [String]
installedaddons [String] -> [String] -> [String]
forall a. Eq a => [a] -> [a] -> [a]
\\ [String]
knownAddonCommandNames

    -- The command aliases (custom commands) defined in the config file, if any.
    aliasessection :: [String]
aliasessection
      | Bool -> Bool
not (CommandCategories -> Bool
showaliases_ CommandCategories
cats) Bool -> Bool -> Bool
|| [(String, String)] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [(String, String)]
cmdaliases = []
      | Bool
otherwise = String -> String
bold' String
"ALIASES" String -> [String] -> [String]
forall a. a -> [a] -> [a]
:
          [String
" " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Int -> String -> String
padright Int
aliasw String
a String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" = " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
def | (String
a,String
def) <- [(String, String)]
cmdaliases]
      where
        aliasw :: Int
aliasw = Int -> [Int] -> Int
forall a. Ord a => a -> [a] -> a
maximumDef Int
0 ([Int] -> Int) -> [Int] -> Int
forall a b. (a -> b) -> a -> b
$ ((String, String) -> Int) -> [(String, String)] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (String -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length(String -> Int)
-> ((String, String) -> String) -> (String, String) -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
.(String, String) -> String
forall a b. (a, b) -> a
fst) [(String, String)]
cmdaliases
        padright :: Int -> String -> String
padright Int
w String
s = String
s String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Int -> Char -> String
forall a. Int -> a -> [a]
replicate (Int
w Int -> Int -> Int
forall a. Num a => a -> a -> a
- String -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length String
s) Char
' '

-- | Display the commands list, limited to the categories selected by
-- --builtins/--addons/--aliases. Only the selected categories are looked up:
-- the addons in PATH, and the command aliases in the config file.
commands :: CliOpts -> Journal -> IO ()
commands :: CliOpts -> Journal -> IO ()
commands CliOpts
opts Journal
_ = do
  installedaddons <- if CommandCategories -> Bool
showaddons_ CommandCategories
cats then IO [String]
addonCommandNames else [String] -> IO [String]
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return []
  cmdaliases <-
    if not $ showaliases_ cats then return [] else do
      (conf,_) <- getConf' $ rawopts_ opts
      -- show each alias's effective (last) definition
      return $ reverse $ nubOrdOn fst $ reverse $ confAliases conf
  printCommandsList cats installedaddons cmdaliases
  where
    cats :: CommandCategories
cats = RawOpts -> CommandCategories
commandCategories (RawOpts -> CommandCategories) -> RawOpts -> CommandCategories
forall a b. (a -> b) -> a -> b
$ CliOpts -> RawOpts
rawopts_ CliOpts
opts

{- | Print the commands list, with a pager if appropriate:
the selected categories of command, customised with the addons
installed in PATH and the command aliases defined in the config file.
-}
printCommandsList :: CommandCategories -> [String] -> [(CommandAlias,CommandLine)] -> IO ()
printCommandsList :: CommandCategories -> [String] -> [(String, String)] -> IO ()
printCommandsList CommandCategories
cats [String]
installedaddons [(String, String)]
cmdaliases =
  Int -> IO () -> IO ()
forall a b. a -> b -> b
seq ([String] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ([String] -> Int) -> [String] -> Int
forall a b. (a -> b) -> a -> b
$ String -> [String] -> [String]
forall a. Show a => String -> a -> a
dbg8 String
"uninstalledknownaddons" ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ [String]
knownaddons [String] -> [String] -> [String]
forall a. Eq a => [a] -> [a] -> [a]
\\ [String]
installedaddons) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ -- for debug output
    Int -> IO () -> IO ()
forall a b. a -> b -> b
seq ([String] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ([String] -> Int) -> [String] -> Int
forall a b. (a -> b) -> a -> b
$ String -> [String] -> [String]
forall a. Show a => String -> a -> a
dbg8 String
"installedknownaddons" ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ [String]
knownaddons [String] -> [String] -> [String]
forall a. Eq a => [a] -> [a] -> [a]
`intersect` [String]
installedaddons) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
      Int -> IO () -> IO ()
forall a b. a -> b -> b
seq ([String] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ([String] -> Int) -> [String] -> Int
forall a b. (a -> b) -> a -> b
$ String -> [String] -> [String]
forall a. Show a => String -> a -> a
dbg8 String
"installedunknownaddons" ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ [String]
installedaddons [String] -> [String] -> [String]
forall a. Eq a => [a] -> [a] -> [a]
\\ [String]
knownaddons) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
        String -> IO ()
runPager (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ [String] -> String
unlines ([String] -> String) -> [String] -> String
forall a b. (a -> b) -> a -> b
$ CommandCategories -> [String] -> [(String, String)] -> [String]
commandsList CommandCategories
cats [String]
installedaddons [(String, String)]
cmdaliases
  where
    knownaddons :: [String]
knownaddons = [String]
knownAddonCommandNames

-- | Canonical names of all commands which have a slot in the commands list, in alphabetical order.
-- These include the builtin commands and the known addon commands.
knownCommands :: [String]
knownCommands :: [String]
knownCommands = [String] -> [String]
forall a. Ord a => [a] -> [a]
nubSort ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ Bool -> [String]
commandsListCommandNames Bool
False

-- | All names and aliases of the builtin commands.
builtinCommandNames :: [String]
builtinCommandNames :: [String]
builtinCommandNames = ((Mode RawOpts, CliOpts -> Journal -> IO ()) -> [String])
-> [(Mode RawOpts, CliOpts -> Journal -> IO ())] -> [String]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (Mode RawOpts -> [String]
forall a. Mode a -> [String]
modeNames (Mode RawOpts -> [String])
-> ((Mode RawOpts, CliOpts -> Journal -> IO ()) -> Mode RawOpts)
-> (Mode RawOpts, CliOpts -> Journal -> IO ())
-> [String]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Mode RawOpts, CliOpts -> Journal -> IO ()) -> Mode RawOpts
forall a b. (a, b) -> a
fst) [(Mode RawOpts, CliOpts -> Journal -> IO ())]
builtinCommands

-- | Look up a builtin command's mode and action by exact command name or alias.
findBuiltinCommand :: String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ()) 
findBuiltinCommand :: String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())
findBuiltinCommand String
cmdname = ((Mode RawOpts, CliOpts -> Journal -> IO ()) -> Bool)
-> [(Mode RawOpts, CliOpts -> Journal -> IO ())]
-> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find (String -> [String] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
elem String
cmdname ([String] -> Bool)
-> ((Mode RawOpts, CliOpts -> Journal -> IO ()) -> [String])
-> (Mode RawOpts, CliOpts -> Journal -> IO ())
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Mode RawOpts -> [String]
forall a. Mode a -> [String]
modeNames (Mode RawOpts -> [String])
-> ((Mode RawOpts, CliOpts -> Journal -> IO ()) -> Mode RawOpts)
-> (Mode RawOpts, CliOpts -> Journal -> IO ())
-> [String]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Mode RawOpts, CliOpts -> Journal -> IO ()) -> Mode RawOpts
forall a b. (a, b) -> a
fst) [(Mode RawOpts, CliOpts -> Journal -> IO ())]
builtinCommands 

{- | Canonical names of the known addon commands which have a slot in the commands list,
in alphabetical order.
-}
knownAddonCommandNames :: [String]
knownAddonCommandNames :: [String]
knownAddonCommandNames = [String] -> [String]
forall a. Ord a => [a] -> [a]
nubSort ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ Bool -> [String]
commandsListCommandNames Bool
True

-- Search PATH for names of addon commands, that aren't shadowed by builtin commands.
addonCommandNames :: IO [String]
addonCommandNames :: IO [String]
addonCommandNames = IO [String]
installedAddonCommandNames IO [String] -> ([String] -> [String]) -> IO [String]
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> (String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (String -> Bool) -> String -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (String -> [String] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [String]
builtinCommandNames) (String -> Bool) -> (String -> String) -> String -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> String
dropExtension)

-- | Get the sorted unique canonical names of hledger addon commands
-- found in the current user's PATH. These are used in command line
-- parsing and to display the commands list.
--
-- Canonical addon names are the filenames of hledger-* executables in
-- PATH, without the "hledger-" prefix, and without the file extension
-- except when it's needed for disambiguation (see below).
--
-- When there are exactly two versions of an executable (same base
-- name, different extensions) that look like a source and compiled
-- pair (one has .exe, .com, or no extension), the source version will
-- be excluded (even if it happens to be newer). When there are three
-- or more versions (or two versions that don't look like a
-- source/compiled pair), they are all included, with file extensions
-- intact.
--
installedAddonCommandNames :: IO [String]
installedAddonCommandNames :: IO [String]
installedAddonCommandNames = do
  -- past bug generator
  as1 <- IO [String]
hledgerExecutablesInPath                     -- ["hledger-check","hledger-check-dates","hledger-check-dates.hs","hledger-check.hs","hledger-check.py"]
  let as2 = (String -> String) -> [String] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map String -> String
forall a. [a] -> [a]
stripPrognamePrefix [String]
as1               -- ["check","check-dates","check-dates.hs","check.hs","check.py"]
  let as3 = (String -> String) -> [String] -> [[String]]
forall b a. Ord b => (a -> b) -> [a] -> [[a]]
groupSortOn String -> String
takeBaseName [String]
as2              -- [["check","check.hs","check.py"],["check-dates","check-dates.hs"]]
  let as4 = ([String] -> [String]) -> [[String]] -> [String]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap [String] -> [String]
dropRedundantSourceVersion [[String]]
as3  -- ["check","check.hs","check.py","check-dates"]
  return as4

stripPrognamePrefix :: [a] -> [a]
stripPrognamePrefix = Int -> [a] -> [a]
forall a. Int -> [a] -> [a]
drop (String -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length String
progname Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)

dropRedundantSourceVersion :: [String] -> [String]
dropRedundantSourceVersion [String
f,String
g]
  | (Char -> Char) -> String -> String
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower (String -> String
takeExtension String
f) String -> [String] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [String]
compiledExts = [String
f]
  | (Char -> Char) -> String -> String
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower (String -> String
takeExtension String
g) String -> [String] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [String]
compiledExts = [String
g]
dropRedundantSourceVersion [String]
fs = [String]
fs

compiledExts :: [String]
compiledExts = [String
"",String
".com",String
".exe"]

-- | Get the sorted unique filenames of all hledger-* executables in
-- the current user's PATH. 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.
-- We do not currently filter out non-file objects or files without execute permission.
hledgerExecutablesInPath :: IO [String]
hledgerExecutablesInPath :: IO [String]
hledgerExecutablesInPath = (String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
filter String -> Bool
isHledgerExeName ([String] -> [String]) -> IO [String] -> IO [String]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO [String]
likelyExecutablesInPath

isHledgerExeName :: String -> Bool
isHledgerExeName :: String -> Bool
isHledgerExeName = Either (ParseErrorBundle Text HledgerParseErrorData) () -> Bool
forall a b. Either a b -> Bool
isRight (Either (ParseErrorBundle Text HledgerParseErrorData) () -> Bool)
-> (String
    -> Either (ParseErrorBundle Text HledgerParseErrorData) ())
-> String
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Parsec HledgerParseErrorData Text ()
-> Text -> Either (ParseErrorBundle Text HledgerParseErrorData) ()
forall e a.
Parsec e Text a -> Text -> Either (ParseErrorBundle Text e) a
parsewith Parsec HledgerParseErrorData Text ()
forall {m :: * -> *}. ParsecT HledgerParseErrorData Text m ()
hledgerexenamep (Text -> Either (ParseErrorBundle Text HledgerParseErrorData) ())
-> (String -> Text)
-> String
-> Either (ParseErrorBundle Text HledgerParseErrorData) ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Text
T.pack
 where
  hledgerexenamep :: ParsecT HledgerParseErrorData Text m ()
hledgerexenamep = do
    _ <- Tokens Text -> ParsecT HledgerParseErrorData Text m (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string (Tokens Text -> ParsecT HledgerParseErrorData Text m (Tokens Text))
-> Tokens Text
-> ParsecT HledgerParseErrorData Text m (Tokens Text)
forall a b. (a -> b) -> a -> b
$ String -> Text
T.pack String
progname
    _ <- char '-'
    _ <- some $ noneOf ['.']
    optional (string "." >> choice' (map (string . T.pack) addonExtensions))
    eof

-- stripAddonExtension :: String -> String
-- stripAddonExtension = regexReplace re "" where re = "\\.(" ++ intercalate "|" addonExtensions ++ ")$"

addonExtensions :: [String]
addonExtensions :: [String]
addonExtensions =
  [String
"bat"
  ,String
"com"
  ,String
"exe"
  ,String
"hs"
  ,String
"js"
  ,String
"lhs"
  ,String
"lua"
  ,String
"php"
  ,String
"pl"
  ,String
"py"
  ,String
"rb"
  ,String
"rkt"
  ,String
"sh"
  ,String
"osh"
  ,String
"ysh"
  ]

-- | Run the hledger and hledger-lib packages' unit tests (for --test),
-- or just those whose names match the given tasty pattern, if it is non-empty.
-- Defined here for easy access to other modules' tests.
-- They run in a single thread: they take only milliseconds, and running them in parallel
-- occasionally crashes or hangs on aarch64 macOS, apparently from a GHC runtime bug
-- (seen with GHC 9.12 and 9.14; https://gitlab.haskell.org/ghc/ghc/-/issues/28001).
runUnitTests :: String -> IO ()
runUnitTests :: String -> IO ()
runUnitTests String
pat =
  [String] -> IO () -> IO ()
forall a. [String] -> IO a -> IO a
withArgs (String
"--num-threads=1" String -> [String] -> [String]
forall a. a -> [a] -> [a]
: [String
"--pattern=" String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
pat | Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ String -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
pat]) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
    TestTree -> IO ()
Test.Tasty.defaultMain (TestTree -> IO ()) -> TestTree -> IO ()
forall a b. (a -> b) -> a -> b
$ String -> [TestTree] -> TestTree
testGroup String
"hledger" [
       TestTree
tests_Hledger
      ,TestTree
tests_Hledger_Cli
      ]

-- All unit tests for Hledger.Cli, defined here rather than
-- Hledger.Cli so runUnitTests can use them.
tests_Hledger_Cli :: TestTree
tests_Hledger_Cli = String -> [TestTree] -> TestTree
testGroup String
"Hledger.Cli" [
   TestTree
tests_Cli_Utils
  ,TestTree
tests_Commands
  ]

tests_Commands :: TestTree
tests_Commands = String -> [TestTree] -> TestTree
testGroup String
"Commands" [
   TestTree
tests_Balance
  ,TestTree
tests_Register
  ,TestTree
tests_Aregister
  ,TestTree
tests_Init

  -- some more tests easiest to define here:

  ,String -> [TestTree] -> TestTree
testGroup String
"apply account directive" [
     String -> IO () -> TestTree
testCase String
"works" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ do
        let
          ignoresourcepos :: Journal -> Journal
ignoresourcepos Journal
j = Journal
j{jtxns=map (\Transaction
t -> Transaction
t{tsourcepos=nullsourcepospair}) (jtxns j), jitems=[]}
          sameParse :: Text -> Text -> IO ()
sameParse Text
str1 Text
str2 = do
            j1 <- Journal -> Journal
ignoresourcepos (Journal -> Journal) -> IO Journal -> IO Journal
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Text -> IO Journal
readJournal'' Text
str1  -- PARTIAL:
            j2 <- ignoresourcepos <$> readJournal'' str2  -- PARTIAL:
            j1 @?= j2{jlastreadtime=jlastreadtime j1, jfiles=jfiles j1} --, jparsestate=jparsestate j1}
        Text -> Text -> IO ()
sameParse
           (Text
"2008/12/07 One\n  alpha  $-1\n  beta  $1\n" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>
            Text
"apply account outer\n2008/12/07 Two\n  aigh  $-2\n  bee  $2\n" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>
            Text
"apply account inner\n2008/12/07 Three\n  gamma  $-3\n  delta  $3\n" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>
            Text
"end apply account\n2008/12/07 Four\n  why  $-4\n  zed  $4\n" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>
            Text
"end apply account\n2008/12/07 Five\n  foo  $-5\n  bar  $5\n"
           )
           (Text
"2008/12/07 One\n  alpha  $-1\n  beta  $1\n" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>
            Text
"2008/12/07 Two\n  outer:aigh  $-2\n  outer:bee  $2\n" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>
            Text
"2008/12/07 Three\n  outer:inner:gamma  $-3\n  outer:inner:delta  $3\n" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>
            Text
"2008/12/07 Four\n  outer:why  $-4\n  outer:zed  $4\n" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>
            Text
"2008/12/07 Five\n  foo  $-5\n  bar  $5\n"
           )

    ,String -> IO () -> TestTree
testCase String
"preserves \"virtual\" posting type" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ do
      j <- Text -> IO Journal
readJournal'' Text
"apply account test\n2008/12/07 One\n  (from)  $-1\n  (to)  $1\n"  -- PARTIAL:
      let p = [Posting] -> Posting
forall a. HasCallStack => [a] -> a
headErr ([Posting] -> Posting) -> [Posting] -> Posting
forall a b. (a -> b) -> a -> b
$ Transaction -> [Posting]
tpostings (Transaction -> [Posting]) -> Transaction -> [Posting]
forall a b. (a -> b) -> a -> b
$ [Transaction] -> Transaction
forall a. HasCallStack => [a] -> a
headErr ([Transaction] -> Transaction) -> [Transaction] -> Transaction
forall a b. (a -> b) -> a -> b
$ Journal -> [Transaction]
jtxns Journal
j  -- PARTIAL headErrs succeed because txns & postings provided
      paccount p @?= "test:from"
      preal p @?= VirtualPosting
    ]

  ,String -> IO () -> TestTree
testCase String
"alias directive" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ do
    j <- Text -> IO Journal
readJournal'' Text
"!alias expenses = equity:draw:personal\n1/1\n (expenses:food)  1\n"  -- PARTIAL:
    let p = [Posting] -> Posting
forall a. HasCallStack => [a] -> a
headErr ([Posting] -> Posting) -> [Posting] -> Posting
forall a b. (a -> b) -> a -> b
$ Transaction -> [Posting]
tpostings (Transaction -> [Posting]) -> Transaction -> [Posting]
forall a b. (a -> b) -> a -> b
$ [Transaction] -> Transaction
forall a. HasCallStack => [a] -> a
headErr ([Transaction] -> Transaction) -> [Transaction] -> Transaction
forall a b. (a -> b) -> a -> b
$ Journal -> [Transaction]
jtxns Journal
j  -- PARTIAL headErrs succeed because txns & postings provided
    paccount p @?= "equity:draw:personal:food"

  ,String -> IO () -> TestTree
testCase String
"Y default year directive" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ do
    j <- Text -> IO Journal
readJournal'' Text
defaultyear_journal_txt  -- PARTIAL:
    tdate (headErr $ jtxns j) @?= fromGregorian 2009 1 1  -- PARTIAL headErr succeeds because defaultyear_journal_txt has a txn

  ,String -> IO () -> TestTree
testCase String
"ledgerAccountNames" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$
    (Ledger -> [Text]
ledgerAccountNames Ledger
ledger7)
    [Text] -> [Text] -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?=
    [Text
"assets",Text
"assets:cash",Text
"assets:checking",Text
"assets:saving",Text
"equity",Text
"equity:opening balances",
     Text
"expenses",Text
"expenses:food",Text
"expenses:food:dining",Text
"expenses:phone",Text
"expenses:vacation",
     Text
"liabilities",Text
"liabilities:credit cards",Text
"liabilities:credit cards:discover"]

  -- ,testCase "journalCanonicaliseAmounts" ~:
  --  "use the greatest precision" ~:
  --   (map asprecision $ journalAmountAndPriceCommodities $ journalCanonicaliseAmounts $ journalWithAmounts ["1","2.00"]) @?= [2,2]

  -- don't know what this should do
  -- ,testCase "elideAccountName" ~: do
  --    (elideAccountName 50 "aaaaaaaaaaaaaaaaaaaa:aaaaaaaaaaaaaaaaaaaa:aaaaaaaaaaaaaaaaaaaa"
  --     @?= "aa:aaaaaaaaaaaaaaaaaaaa:aaaaaaaaaaaaaaaaaaaa")
  --    (elideAccountName 20 "aaaaaaaaaaaaaaaaaaaa:aaaaaaaaaaaaaaaaaaaa:aaaaaaaaaaaaaaaaaaaa"
  --     @?= "aa:aa:aaaaaaaaaaaaaa")

  ,String -> IO () -> TestTree
testCase String
"show dollars" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ Amount -> String
showAmount (DecimalRaw Integer -> Amount
usd DecimalRaw Integer
1) String -> String -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= String
"$1.00"

  ,String -> IO () -> TestTree
testCase String
"show hours" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ Amount -> String
showAmount (DecimalRaw Integer -> Amount
hrs DecimalRaw Integer
1) String -> String -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= String
"1.00h"

  ]

-- test data

-- date1 = fromGregorian 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_txt :: Text
defaultyear_journal_txt :: Text
defaultyear_journal_txt = [Text] -> Text
T.unlines
 [Text
"Y2009"
 ,Text
""
 ,Text
"01/01 A"
 ,Text
"    a  $1"
 ,Text
"    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 :: Journal
journal7 = Journal
nulljournal {jtxns =
          [
           txnTieKnot Transaction {
             tindex=0,
             tsourcepos=nullsourcepospair,
             tdate=fromGregorian 2007 01 01,
             tdate2=Nothing,
             tstatus=Unmarked,
             tcode="*",
             tdescription="opening balance",
             tcomment="",
             ttags=[],
             tpostings=
                 ["assets:cash" `post` usd 4.82
                 ,"equity:opening balances" `post` usd (-4.82)
                 ],
             tprecedingcomment=""
           }
          ,
           txnTieKnot Transaction {
             tindex=0,
             tsourcepos=nullsourcepospair,
             tdate=fromGregorian 2007 02 01,
             tdate2=Nothing,
             tstatus=Unmarked,
             tcode="*",
             tdescription="ayres suites",
             tcomment="",
             ttags=[],
             tpostings=
                 ["expenses:vacation" `post` usd 179.92
                 ,"assets:checking" `post` usd (-179.92)
                 ],
             tprecedingcomment=""
           }
          ,
           txnTieKnot Transaction {
             tindex=0,
             tsourcepos=nullsourcepospair,
             tdate=fromGregorian 2007 01 02,
             tdate2=Nothing,
             tstatus=Unmarked,
             tcode="*",
             tdescription="auto transfer to savings",
             tcomment="",
             ttags=[],
             tpostings=
                 ["assets:saving" `post` usd 200
                 ,"assets:checking" `post` usd (-200)
                 ],
             tprecedingcomment=""
           }
          ,
           txnTieKnot Transaction {
             tindex=0,
             tsourcepos=nullsourcepospair,
             tdate=fromGregorian 2007 01 03,
             tdate2=Nothing,
             tstatus=Unmarked,
             tcode="*",
             tdescription="poquito mas",
             tcomment="",
             ttags=[],
             tpostings=
                 ["expenses:food:dining" `post` usd 4.82
                 ,"assets:cash" `post` usd (-4.82)
                 ],
             tprecedingcomment=""
           }
          ,
           txnTieKnot Transaction {
             tindex=0,
             tsourcepos=nullsourcepospair,
             tdate=fromGregorian 2007 01 03,
             tdate2=Nothing,
             tstatus=Unmarked,
             tcode="*",
             tdescription="verizon",
             tcomment="",
             ttags=[],
             tpostings=
                 ["expenses:phone" `post` usd 95.11
                 ,"assets:checking" `post` usd (-95.11)
                 ],
             tprecedingcomment=""
           }
          ,
           txnTieKnot Transaction {
             tindex=0,
             tsourcepos=nullsourcepospair,
             tdate=fromGregorian 2007 01 03,
             tdate2=Nothing,
             tstatus=Unmarked,
             tcode="*",
             tdescription="discover",
             tcomment="",
             ttags=[],
             tpostings=
                 ["liabilities:credit cards:discover" `post` usd 80
                 ,"assets:checking" `post` usd (-80)
                 ],
             tprecedingcomment=""
           }
          ]
         }

ledger7 :: Ledger
ledger7 :: Ledger
ledger7 = Query -> Journal -> Ledger
ledgerFromJournal Query
Any Journal
journal7