module Hledger.Cli.Main where
import Control.Monad
import Data.List
import Safe
import System.Environment
import System.Exit
import System.Process
import Text.Printf
import Hledger.Cli.Add
import Hledger.Cli.Balance
import Hledger.Cli.Convert
import Hledger.Cli.Histogram
import Hledger.Cli.Print
import Hledger.Cli.Register
import Hledger.Cli.Stats
import Hledger.Cli.Options
import Hledger.Cli.Tests
import Hledger.Cli.Utils
import Hledger.Cli.Version
import Hledger.Utils
main :: IO ()
main = do
args <- getArgs
addons <- getHledgerAddonCommands
opts <- getHledgerCliOpts addons
when (debug_ opts) $ printf "%s\n" progversion >> printf "opts: %s\n" (show opts)
run' opts addons args
where
run' opts@CliOpts{command_=cmd} addons args
| "version" `in_` (rawopts_ opts) = putStrLn progversion
| "binary-filename" `in_` (rawopts_ opts) = putStrLn $ binaryfilename progname
| null cmd = putStr $ showModeHelp mainmode'
| cmd `isPrefixOf` "add" = showModeHelpOr addmode $ withJournalDo opts add
| cmd `isPrefixOf` "convert" = showModeHelpOr convertmode $ convert opts
| cmd `isPrefixOf` "test" = showModeHelpOr testmode $ runtests opts
| any (cmd `isPrefixOf`) ["accounts","balance"] = showModeHelpOr accountsmode $ withJournalDo opts balance
| any (cmd `isPrefixOf`) ["entries","print"] = showModeHelpOr entriesmode $ withJournalDo opts print'
| any (cmd `isPrefixOf`) ["postings","register"] = showModeHelpOr postingsmode $ withJournalDo opts register
| any (cmd `isPrefixOf`) ["activity","histogram"] = showModeHelpOr activitymode $ withJournalDo opts histogram
| cmd `isPrefixOf` "stats" = showModeHelpOr statsmode $ withJournalDo opts stats
| not (null matchedaddon) = system shellcmd >>= exitWith
| otherwise = optserror ("command "++cmd++" is not recognized") >> exitFailure
where
mainmode' = mainmode addons
showModeHelpOr mode f | "help" `in_` (rawopts_ opts) = putStr $ showModeHelp mode
| otherwise = f
matchedaddon = headDef "" $ filter (cmd `isPrefixOf`) addons
shellcmd = printf "%s-%s %s" progname matchedaddon (unwords' args)