{-|
Read extra CLI arguments from a hledger config file.
-}

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE TupleSections #-}

module Hledger.Cli.Conf (
   Conf
  ,SectionName
  ,CommandAlias
  ,CommandLine
  ,getConf
  ,getConf'
  ,nullconf
  ,confLookup
  ,confAliases
  ,ResolvedCommand(..)
  ,expandCommandAlias
  ,confFileIsTrusted
  ,activeConfFile
  ,activeLocalConfFile
  ,activeUserConfFile
  ,confFiles
  ,userConfFiles
  ,parseConf
)
where

import Control.Exception (handle)
import Control.Monad (void, forM, guard)
import Control.Monad.Identity (Identity)
import Data.Functor ((<&>))
import Data.Map qualified as M
import Data.Maybe (catMaybes)
import Data.Text (Text)
import Data.Text qualified as T (empty, lines, pack, unpack)
import Safe (headDef, headMay, lastDef)
import System.Directory (getHomeDirectory, getXdgDirectory, XdgDirectory (XdgConfig), doesFileExist, getCurrentDirectory)
import System.FilePath ((</>), takeDirectory)
import Text.Megaparsec as M
import Text.Megaparsec.Char
import Text.Printf (printf)

import Hledger (decorateExcerpt, error', strip, words', wordsmay, RawOpts, expandPath)
import Hledger.Read.Common
import Hledger.Utils.Parse
import Hledger.Utils.Debug
import Hledger.Data.RawOptions (collectopts)


-- | A hledger config file.
data Conf = Conf {
   Conf -> String
confFile :: FilePath
  ,Conf -> Text
confText :: Text
  ,Conf -> Int
confFormat :: Int
  ,Conf -> [ConfSection]
confSections :: [ConfSection]
} deriving (Conf -> Conf -> Bool
(Conf -> Conf -> Bool) -> (Conf -> Conf -> Bool) -> Eq Conf
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Conf -> Conf -> Bool
== :: Conf -> Conf -> Bool
$c/= :: Conf -> Conf -> Bool
/= :: Conf -> Conf -> Bool
Eq,Int -> Conf -> String -> String
[Conf] -> String -> String
Conf -> String
(Int -> Conf -> String -> String)
-> (Conf -> String) -> ([Conf] -> String -> String) -> Show Conf
forall a.
(Int -> a -> String -> String)
-> (a -> String) -> ([a] -> String -> String) -> Show a
$cshowsPrec :: Int -> Conf -> String -> String
showsPrec :: Int -> Conf -> String -> String
$cshow :: Conf -> String
show :: Conf -> String
$cshowList :: [Conf] -> String -> String
showList :: [Conf] -> String -> String
Show)

-- | One section in a hledger config file.
data ConfSection = ConfSection {
   ConfSection -> String
csName :: SectionName
  ,ConfSection -> [(Int, String)]
csArgs :: [(Int, Arg)]  -- ^ arguments, with the config file line number where each appeared
} deriving (ConfSection -> ConfSection -> Bool
(ConfSection -> ConfSection -> Bool)
-> (ConfSection -> ConfSection -> Bool) -> Eq ConfSection
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ConfSection -> ConfSection -> Bool
== :: ConfSection -> ConfSection -> Bool
$c/= :: ConfSection -> ConfSection -> Bool
/= :: ConfSection -> ConfSection -> Bool
Eq,Int -> ConfSection -> String -> String
[ConfSection] -> String -> String
ConfSection -> String
(Int -> ConfSection -> String -> String)
-> (ConfSection -> String)
-> ([ConfSection] -> String -> String)
-> Show ConfSection
forall a.
(Int -> a -> String -> String)
-> (a -> String) -> ([a] -> String -> String) -> Show a
$cshowsPrec :: Int -> ConfSection -> String -> String
showsPrec :: Int -> ConfSection -> String -> String
$cshow :: ConfSection -> String
show :: ConfSection -> String
$cshowList :: [ConfSection] -> String -> String
showList :: [ConfSection] -> String -> String
Show)

-- | The name of a config file section, with surrounding brackets and whitespace removed.
type SectionName = String

-- | A command line argument to be passed to CmdArgs.process.
-- It seems this should be a single command line argument (or flag or flag value).
-- If it contains spaces, those are treated as part of a single argument, as with CMD a "b c".
type Arg = String

-- | The name of a command alias (a custom command) defined in a config file.
type CommandAlias = String

-- | A command line (a command name followed by arguments), as a single string.
-- Eg the command line which a command alias expands to.
type CommandLine = String

nullconf :: Conf
nullconf = Conf {
   confFile :: String
confFile = String
""
  ,confText :: Text
confText = Text
T.empty
  ,confFormat :: Int
confFormat = Int
1
  ,confSections :: [ConfSection]
confSections = []
}

-- | The --conf or --no-conf or default config file specified by command line options.
data ConfFileSpec =
    SomeConfFile FilePath  -- ^ use config file specified with --conf
  | NoConfFile             -- ^ don't use any config file (--no-conf)
  | AutoConfFile           -- ^ use the config file found by directory search (default)
  deriving (ConfFileSpec -> ConfFileSpec -> Bool
(ConfFileSpec -> ConfFileSpec -> Bool)
-> (ConfFileSpec -> ConfFileSpec -> Bool) -> Eq ConfFileSpec
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ConfFileSpec -> ConfFileSpec -> Bool
== :: ConfFileSpec -> ConfFileSpec -> Bool
$c/= :: ConfFileSpec -> ConfFileSpec -> Bool
/= :: ConfFileSpec -> ConfFileSpec -> Bool
Eq,Int -> ConfFileSpec -> String -> String
[ConfFileSpec] -> String -> String
ConfFileSpec -> String
(Int -> ConfFileSpec -> String -> String)
-> (ConfFileSpec -> String)
-> ([ConfFileSpec] -> String -> String)
-> Show ConfFileSpec
forall a.
(Int -> a -> String -> String)
-> (a -> String) -> ([a] -> String -> String) -> Show a
$cshowsPrec :: Int -> ConfFileSpec -> String -> String
showsPrec :: Int -> ConfFileSpec -> String -> String
$cshow :: ConfFileSpec -> String
show :: ConfFileSpec -> String
$cshowList :: [ConfFileSpec] -> String -> String
showList :: [ConfFileSpec] -> String -> String
Show)

-- Get the conf file specification from options,
-- considering the rightmost --conf or --no-conf option if any.
confFileSpecFromRawOpts :: RawOpts -> ConfFileSpec
confFileSpecFromRawOpts :: RawOpts -> ConfFileSpec
confFileSpecFromRawOpts = ConfFileSpec -> [ConfFileSpec] -> ConfFileSpec
forall a. a -> [a] -> a
lastDef ConfFileSpec
AutoConfFile ([ConfFileSpec] -> ConfFileSpec)
-> (RawOpts -> [ConfFileSpec]) -> RawOpts -> ConfFileSpec
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((String, String) -> Maybe ConfFileSpec)
-> RawOpts -> [ConfFileSpec]
forall a. ((String, String) -> Maybe a) -> RawOpts -> [a]
collectopts (String, String) -> Maybe ConfFileSpec
cfsFromRawOpt
  where
    cfsFromRawOpt :: (String, String) -> Maybe ConfFileSpec
cfsFromRawOpt (String
"conf",String
f)    = ConfFileSpec -> Maybe ConfFileSpec
forall a. a -> Maybe a
Just (ConfFileSpec -> Maybe ConfFileSpec)
-> ConfFileSpec -> Maybe ConfFileSpec
forall a b. (a -> b) -> a -> b
$ String -> ConfFileSpec
SomeConfFile String
f
    cfsFromRawOpt (String
"no-conf",String
_) = ConfFileSpec -> Maybe ConfFileSpec
forall a. a -> Maybe a
Just (ConfFileSpec -> Maybe ConfFileSpec)
-> ConfFileSpec -> Maybe ConfFileSpec
forall a b. (a -> b) -> a -> b
$ ConfFileSpec
NoConfFile
    cfsFromRawOpt (String, String)
_             = Maybe ConfFileSpec
forall a. Maybe a
Nothing

-- config reading

-- | Fetch all the arguments/options defined in a section with this name, if it exists.
-- This should be "general" for the unnamed first section, or a hledger command name.
confLookup :: SectionName -> Conf -> [Arg]
confLookup :: String -> Conf -> [String]
confLookup String
cmd Conf{[ConfSection]
confSections :: Conf -> [ConfSection]
confSections :: [ConfSection]
confSections} =
  [String]
-> ([(Int, String)] -> [String])
-> Maybe [(Int, String)]
-> [String]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] (((Int, String) -> [String]) -> [(Int, String)] -> [String]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (((Int, String) -> [String]) -> [(Int, String)] -> [String])
-> ((Int, String) -> [String]) -> [(Int, String)] -> [String]
forall a b. (a -> b) -> a -> b
$ String -> [String]
words' (String -> [String])
-> ((Int, String) -> String) -> (Int, String) -> [String]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Int, String) -> String
forall a b. (a, b) -> b
snd) (Maybe [(Int, String)] -> [String])
-> Maybe [(Int, String)] -> [String]
forall a b. (a -> b) -> a -> b
$  -- XXX PARTIAL
  String -> Map String [(Int, String)] -> Maybe [(Int, String)]
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup String
cmd (Map String [(Int, String)] -> Maybe [(Int, String)])
-> Map String [(Int, String)] -> Maybe [(Int, String)]
forall a b. (a -> b) -> a -> b
$
  [(String, [(Int, String)])] -> Map String [(Int, String)]
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList [(String
csName,[(Int, String)]
csArgs) | ConfSection{String
csName :: ConfSection -> String
csName :: String
csName,[(Int, String)]
csArgs :: ConfSection -> [(Int, String)]
csArgs :: [(Int, String)]
csArgs} <- [ConfSection]
confSections]

-- | Get the command aliases (custom commands) defined in this config file,
-- in order of definition. They are defined git-style in an @[alias]@
-- section, like @NAME = CMDLINE@; a value may continue on following, more-indented lines.
-- If a name is defined more than once, the last definition should win (callers can rely
-- on the ordering here). An [alias] section line without an @=@ raises a usage error.
-- (In practice it won't, since readConfFile validates with confAliasesE first.)
confAliases :: Conf -> [(CommandAlias, CommandLine)]
confAliases :: Conf -> [(String, String)]
confAliases = (String -> [(String, String)])
-> ([(String, String)] -> [(String, String)])
-> Either String [(String, String)]
-> [(String, String)]
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either String -> [(String, String)]
forall a. String -> a
error' [(String, String)] -> [(String, String)]
forall a. a -> a
id (Either String [(String, String)] -> [(String, String)])
-> (Conf -> Either String [(String, String)])
-> Conf
-> [(String, String)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Conf -> Either String [(String, String)]
confAliasesE

-- | Like confAliases, but return a (pretty, multiline) error message
-- if a bad alias definition is found.
confAliasesE :: Conf -> Either String [(CommandAlias, CommandLine)]
confAliasesE :: Conf -> Either String [(String, String)]
confAliasesE conf :: Conf
conf@Conf{[ConfSection]
confSections :: Conf -> [ConfSection]
confSections :: [ConfSection]
confSections} = [[(String, String)]] -> [(String, String)]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat ([[(String, String)]] -> [(String, String)])
-> Either String [[(String, String)]]
-> Either String [(String, String)]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (ConfSection -> Either String [(String, String)])
-> [ConfSection] -> Either String [[(String, String)]]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM ConfSection -> Either String [(String, String)]
sectionaliases [ConfSection]
confSections
  where
    sectionaliases :: ConfSection -> Either String [(String, String)]
sectionaliases ConfSection{String
csName :: ConfSection -> String
csName :: String
csName, [(Int, String)]
csArgs :: ConfSection -> [(Int, String)]
csArgs :: [(Int, String)]
csArgs}
      | String
csName String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
"alias" = ((Int, String) -> Either String (String, String))
-> [(Int, String)] -> Either String [(String, String)]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM (Int, String) -> Either String (String, String)
aliasline [(Int, String)]
csArgs
      | Bool
otherwise = [(String, String)] -> Either String [(String, String)]
forall a b. b -> Either a b
Right []
    aliasline :: (Int, String) -> Either String (String, String)
aliasline (Int
lnum, String
l) = case (Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
==Char
'=') String
l of
      (String
name, Char
'=':String
cmdline) | 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 -> Bool) -> String -> Bool
forall a b. (a -> b) -> a -> b
$ String -> String
strip String
name -> (String, String) -> Either String (String, String)
forall a b. b -> Either a b
Right (String -> String
strip String
name, String -> String
strip String
cmdline)
      (String, String)
_ -> String -> Either String (String, String)
forall a b. a -> Either a b
Left (String -> Either String (String, String))
-> String -> Either String (String, String)
forall a b. (a -> b) -> a -> b
$ Conf -> Int -> String -> String -> String
confErrorAt Conf
conf Int
lnum String
l
           String
"an [alias] section line should look like: NAME = COMMAND [ARGS..]"

-- | Check that each argument line in this config file can be parsed as command line
-- arguments (eg, quotes must be balanced); return a pretty, multiline error message if not.
confArgsE :: Conf -> Either String ()
confArgsE :: Conf -> Either String ()
confArgsE conf :: Conf
conf@Conf{[ConfSection]
confSections :: Conf -> [ConfSection]
confSections :: [ConfSection]
confSections} =
  ((Int, String) -> Either String ())
-> [(Int, String)] -> Either String ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Int, String) -> Either String ()
argline [(Int, String)
lnuma | ConfSection{[(Int, String)]
csArgs :: ConfSection -> [(Int, String)]
csArgs :: [(Int, String)]
csArgs} <- [ConfSection]
confSections, (Int, String)
lnuma <- [(Int, String)]
csArgs]
  where
    argline :: (Int, String) -> Either String ()
argline (Int
lnum, String
l) = case String -> Maybe [String]
wordsmay String
l of
      Just [String]
_  -> () -> Either String ()
forall a b. b -> Either a b
Right ()
      Maybe [String]
Nothing -> String -> Either String ()
forall a b. a -> Either a b
Left (String -> Either String ()) -> String -> Either String ()
forall a b. (a -> b) -> a -> b
$ Conf -> Int -> String -> String -> String
confErrorAt Conf
conf Int
lnum String
l (String -> String) -> String -> String
forall a b. (a -> b) -> a -> b
$
        String
"this config file line has an unmatched quote (' or \")."

-- | Make a pretty, multiline error message about a problem on the given line
-- of this config file: file path and line number, an excerpt showing the line
-- as written (or the given fallback text), and an explanation.
confErrorAt :: Conf -> Int -> String -> String -> String
confErrorAt :: Conf -> Int -> String -> String -> String
confErrorAt Conf{String
confFile :: Conf -> String
confFile :: String
confFile, Text
confText :: Conf -> Text
confText :: Text
confText} Int
lnum String
fallbacktxt String
explanation =
  String -> String -> Int -> String -> String -> String
forall r. PrintfType r => String -> r
printf String
"%s:%d:\n%s%s" String
confFile Int
lnum (Text -> String
T.unpack Text
excerpt) String
explanation
  where
    excerpt :: Text
excerpt = Int -> Maybe (Int, Maybe Int) -> Text -> Text
decorateExcerpt Int
lnum Maybe (Int, Maybe Int)
forall a. Maybe a
Nothing (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$ (Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> String -> Text
T.pack String
"\n") (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$
      Text -> [Text] -> Text
forall a. a -> [a] -> a
headDef (String -> Text
T.pack String
fallbacktxt) ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ Int -> [Text] -> [Text]
forall a. Int -> [a] -> [a]
drop (Int
lnumInt -> Int -> Int
forall a. Num a => a -> a -> a
-Int
1) ([Text] -> [Text]) -> [Text] -> [Text]
forall a b. (a -> b) -> a -> b
$ Text -> [Text]
T.lines Text
confText

-- | The result of resolving a command name that may be a command alias.
data ResolvedCommand
  = HledgerCommand String [Arg]  -- ^ a resolved hledger command name, and arguments to prepend
  | ShellCommand String          -- ^ a shell command line (from a !-prefixed alias, ! stripped)
  deriving (ResolvedCommand -> ResolvedCommand -> Bool
(ResolvedCommand -> ResolvedCommand -> Bool)
-> (ResolvedCommand -> ResolvedCommand -> Bool)
-> Eq ResolvedCommand
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ResolvedCommand -> ResolvedCommand -> Bool
== :: ResolvedCommand -> ResolvedCommand -> Bool
$c/= :: ResolvedCommand -> ResolvedCommand -> Bool
/= :: ResolvedCommand -> ResolvedCommand -> Bool
Eq,Int -> ResolvedCommand -> String -> String
[ResolvedCommand] -> String -> String
ResolvedCommand -> String
(Int -> ResolvedCommand -> String -> String)
-> (ResolvedCommand -> String)
-> ([ResolvedCommand] -> String -> String)
-> Show ResolvedCommand
forall a.
(Int -> a -> String -> String)
-> (a -> String) -> ([a] -> String -> String) -> Show a
$cshowsPrec :: Int -> ResolvedCommand -> String -> String
showsPrec :: Int -> ResolvedCommand -> String -> String
$cshow :: ResolvedCommand -> String
show :: ResolvedCommand -> String
$cshowList :: [ResolvedCommand] -> String -> String
showList :: [ResolvedCommand] -> String -> String
Show)

-- | Resolve a command name which may be a command alias, to either a real hledger command
-- (with any arguments to prepend) or a shell command line (for a @!@-prefixed alias).
-- Aliases can refer to other aliases; a name that is an exact builtin command name (per the
-- given predicate), or already seen during this expansion (a self-reference or cycle), stops
-- the recursion. If a name is defined more than once, the first definition in the given list
-- wins (callers wanting the config file's last-definition-wins behaviour should pass
-- @reverse (confAliases conf)@). This does not enforce the shell-alias trust policy; callers do.
expandCommandAlias :: (String -> Bool) -> [(CommandAlias, CommandLine)] -> String -> ResolvedCommand
expandCommandAlias :: (String -> Bool) -> [(String, String)] -> String -> ResolvedCommand
expandCommandAlias String -> Bool
isbuiltincmd [(String, String)]
cmdaliases = [String] -> String -> ResolvedCommand
go []
  where
    go :: [String] -> String -> ResolvedCommand
go [String]
seen String
name
      | String
name String -> [String] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [String]
seen
      , Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ String -> Bool
isbuiltincmd String
name
      , Just String
cmdline <- String -> [(String, String)] -> Maybe String
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup String
name [(String, String)]
cmdaliases =
          case String -> String
strip String
cmdline of
            Char
'!':String
shellcmd -> String -> ResolvedCommand
ShellCommand (String -> String
strip String
shellcmd)
            String
hledgercmd   -> case String -> [String]
words' String
hledgercmd of
              (String
realcmd:[String]
defargs) -> case [String] -> String -> ResolvedCommand
go (String
nameString -> [String] -> [String]
forall a. a -> [a] -> [a]
:[String]
seen) String
realcmd of
                HledgerCommand String
realcmd' [String]
defargs' -> String -> [String] -> ResolvedCommand
HledgerCommand String
realcmd' ([String]
defargs' [String] -> [String] -> [String]
forall a. Semigroup a => a -> a -> a
<> [String]
defargs)
                ShellCommand String
shellcmd            -> String -> ResolvedCommand
ShellCommand ([String] -> String
unwords ([String] -> String) -> [String] -> String
forall a b. (a -> b) -> a -> b
$ String
shellcmd String -> [String] -> [String]
forall a. a -> [a] -> [a]
: [String]
defargs)
              [] -> String -> [String] -> ResolvedCommand
HledgerCommand String
name []
      | Bool
otherwise = String -> [String] -> ResolvedCommand
HledgerCommand String
name []

-- | Is the active config file trusted enough to run its @!@-prefixed shell command aliases?
-- True if the config file was given explicitly with --conf, or is a user-level config file
-- (~/.hledger.conf or the XDG hledger.conf). False for a config file found automatically in the
-- current directory or a parent (which could come from an untrusted downloaded/shared directory),
-- or when there is no config file.
confFileIsTrusted :: RawOpts -> Maybe FilePath -> IO Bool
confFileIsTrusted :: RawOpts -> Maybe String -> IO Bool
confFileIsTrusted RawOpts
_ Maybe String
Nothing = Bool -> IO Bool
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False
confFileIsTrusted RawOpts
rawopts (Just String
f) =
  case RawOpts -> ConfFileSpec
confFileSpecFromRawOpts RawOpts
rawopts of
    SomeConfFile String
_ -> Bool -> IO Bool
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True
    ConfFileSpec
_              -> (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] -> Bool) -> IO [String] -> IO Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO [String]
userConfFiles

-- | Try to read a hledger config from a config file specified by --conf,
-- or the first config file found in any of several default file paths.
-- If --no-conf was used, or if no file was specified or found, this returns a null Conf.
-- If a specified file, or the first file found, can not be read or parsed, this returns an error message.
-- Otherwise this returns the parsed Conf, and the file path.
getConf :: RawOpts -> IO (Either String (Conf, Maybe FilePath))
getConf :: RawOpts -> IO (Either String (Conf, Maybe String))
getConf RawOpts
rawopts = do
  -- As in Cli.hs, conf debug output always goes to stderr;
  -- that's ok as conf is a hledger cli feature for now.
  case RawOpts -> ConfFileSpec
confFileSpecFromRawOpts RawOpts
rawopts of
    ConfFileSpec
NoConfFile     -> Either String (Conf, Maybe String)
-> IO (Either String (Conf, Maybe String))
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either String (Conf, Maybe String)
 -> IO (Either String (Conf, Maybe String)))
-> Either String (Conf, Maybe String)
-> IO (Either String (Conf, Maybe String))
forall a b. (a -> b) -> a -> b
$ (Conf, Maybe String) -> Either String (Conf, Maybe String)
forall a b. b -> Either a b
Right ((Conf, Maybe String) -> Either String (Conf, Maybe String))
-> (Conf, Maybe String) -> Either String (Conf, Maybe String)
forall a b. (a -> b) -> a -> b
$ String -> (Conf, Maybe String) -> (Conf, Maybe String)
forall a. String -> a -> a
dbg1Msg String
"ignoring config files" (Conf
nullconf, Maybe String
forall a. Maybe a
Nothing)
    SomeConfFile String
f -> IO String
getCurrentDirectory IO String -> (String -> IO String) -> IO String
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (String -> String -> IO String) -> String -> String -> IO String
forall a b c. (a -> b -> c) -> b -> a -> c
flip String -> String -> IO String
expandPath String
f IO String
-> (String -> IO (Either String (Conf, Maybe String)))
-> IO (Either String (Conf, Maybe String))
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= String -> IO (Either String (Conf, Maybe String))
readConfFile (String -> IO (Either String (Conf, Maybe String)))
-> (String -> String)
-> String
-> IO (Either String (Conf, Maybe String))
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> String -> String
forall a. Show a => String -> a -> a
dbg1 String
"using specified config file"
    ConfFileSpec
AutoConfFile   -> do
      fs <- IO [String]
confFiles
      case fs of
        String
f:[String]
_ -> String -> [String] -> IO ()
forall (m :: * -> *) a. (MonadIO m, Show a) => String -> a -> m ()
dbg8IO String
"found config files" [String]
fs IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> String -> String -> IO ()
forall (m :: * -> *) a. (MonadIO m, Show a) => String -> a -> m ()
dbg1IO String
"using nearest config file" String
f IO ()
-> IO (Either String (Conf, Maybe String))
-> IO (Either String (Conf, Maybe String))
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> String -> IO (Either String (Conf, Maybe String))
readConfFile String
f
        []  -> Either String (Conf, Maybe String)
-> IO (Either String (Conf, Maybe String))
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either String (Conf, Maybe String)
 -> IO (Either String (Conf, Maybe String)))
-> Either String (Conf, Maybe String)
-> IO (Either String (Conf, Maybe String))
forall a b. (a -> b) -> a -> b
$ (Conf, Maybe String) -> Either String (Conf, Maybe String)
forall a b. b -> Either a b
Right ((Conf, Maybe String) -> Either String (Conf, Maybe String))
-> (Conf, Maybe String) -> Either String (Conf, Maybe String)
forall a b. (a -> b) -> a -> b
$ String -> (Conf, Maybe String) -> (Conf, Maybe String)
forall a. String -> a -> a
dbg1Msg String
"no config file found" (Conf
nullconf, Maybe String
forall a. Maybe a
Nothing)

-- | Like getConf but throws an error on failure.
getConf' :: RawOpts -> IO (Conf, Maybe FilePath)
getConf' :: RawOpts -> IO (Conf, Maybe String)
getConf' RawOpts
rawopts = RawOpts -> IO (Either String (Conf, Maybe String))
getConf RawOpts
rawopts IO (Either String (Conf, Maybe String))
-> (Either String (Conf, Maybe String) -> IO (Conf, Maybe String))
-> IO (Conf, Maybe String)
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (String -> IO (Conf, Maybe String))
-> ((Conf, Maybe String) -> IO (Conf, Maybe String))
-> Either String (Conf, Maybe String)
-> IO (Conf, Maybe String)
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either String -> IO (Conf, Maybe String)
forall a. String -> a
error' (Conf, Maybe String) -> IO (Conf, Maybe String)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return

-- | Read this config file and parse its contents, or return an error message.
readConfFile :: FilePath -> IO (Either String (Conf, Maybe FilePath))
readConfFile :: String -> IO (Either String (Conf, Maybe String))
readConfFile String
f = (IOError -> IO (Either String (Conf, Maybe String)))
-> IO (Either String (Conf, Maybe String))
-> IO (Either String (Conf, Maybe String))
forall e a. Exception e => (e -> IO a) -> IO a -> IO a
handle (\(IOError
e::IOError) -> Either String (Conf, Maybe String)
-> IO (Either String (Conf, Maybe String))
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either String (Conf, Maybe String)
 -> IO (Either String (Conf, Maybe String)))
-> Either String (Conf, Maybe String)
-> IO (Either String (Conf, Maybe String))
forall a b. (a -> b) -> a -> b
$ String -> Either String (Conf, Maybe String)
forall a b. a -> Either a b
Left (String -> Either String (Conf, Maybe String))
-> String -> Either String (Conf, Maybe String)
forall a b. (a -> b) -> a -> b
$ IOError -> String
forall a. Show a => a -> String
show IOError
e) (IO (Either String (Conf, Maybe String))
 -> IO (Either String (Conf, Maybe String)))
-> IO (Either String (Conf, Maybe String))
-> IO (Either String (Conf, Maybe String))
forall a b. (a -> b) -> a -> b
$ do
  -- avoid GHC 9.10.1's ugly stack trace when calling readFile on a nonexistent file
  exists <- String -> IO Bool
doesFileExist String
f
  case exists of
    Bool
False -> Either String (Conf, Maybe String)
-> IO (Either String (Conf, Maybe String))
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either String (Conf, Maybe String)
 -> IO (Either String (Conf, Maybe String)))
-> Either String (Conf, Maybe String)
-> IO (Either String (Conf, Maybe String))
forall a b. (a -> b) -> a -> b
$ String -> Either String (Conf, Maybe String)
forall a b. a -> Either a b
Left (String -> Either String (Conf, Maybe String))
-> String -> Either String (Conf, Maybe String)
forall a b. (a -> b) -> a -> b
$ String
f String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" does not exist"
    Bool
True -> do
      txt <- String -> IO String
readFile String
f IO String -> (String -> Text) -> IO Text
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> String -> Text
T.pack
      case parseConf f txt of
        Left ParseErrorBundle Text HledgerParseErrorData
err -> Either String (Conf, Maybe String)
-> IO (Either String (Conf, Maybe String))
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either String (Conf, Maybe String)
 -> IO (Either String (Conf, Maybe String)))
-> Either String (Conf, Maybe String)
-> IO (Either String (Conf, Maybe String))
forall a b. (a -> b) -> a -> b
$ String -> Either String (Conf, Maybe String)
forall a b. a -> Either a b
Left (String -> Either String (Conf, Maybe String))
-> String -> Either String (Conf, Maybe String)
forall a b. (a -> b) -> a -> b
$ ParseErrorBundle Text HledgerParseErrorData -> String
customErrorBundlePretty ParseErrorBundle Text HledgerParseErrorData
err
        Right [ConfSection]
cs -> do
          let conf :: Conf
conf = Conf
nullconf{
                 confFile     = f
                ,confText     = txt
                ,confFormat   = 1
                ,confSections = cs
                }
          -- validate the config now, so problems are reported promptly:
          -- argument lines must be parseable as command line arguments,
          -- and command alias definitions must be well formed
          Either String (Conf, Maybe String)
-> IO (Either String (Conf, Maybe String))
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either String (Conf, Maybe String)
 -> IO (Either String (Conf, Maybe String)))
-> Either String (Conf, Maybe String)
-> IO (Either String (Conf, Maybe String))
forall a b. (a -> b) -> a -> b
$ (Conf
conf, String -> Maybe String
forall a. a -> Maybe a
Just String
f) (Conf, Maybe String)
-> Either String [(String, String)]
-> Either String (Conf, Maybe String)
forall a b. a -> Either String b -> Either String a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ (Conf -> Either String ()
confArgsE Conf
conf Either String ()
-> Either String [(String, String)]
-> Either String [(String, String)]
forall a b. Either String a -> Either String b -> Either String b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Conf -> Either String [(String, String)]
confAliasesE Conf
conf)

-- -- | Like readConf, but throw an error on failure.
-- readConfFile' :: FilePath -> IO (Conf, Maybe FilePath)
-- readConfFile' f = readConfFile f >>= either (error' . show) return

-- | Get the highest precedence config file, based on the current directory.
activeConfFile :: IO (Maybe FilePath)
activeConfFile :: IO (Maybe String)
activeConfFile = [String] -> Maybe String
forall a. [a] -> Maybe a
headMay ([String] -> Maybe String) -> IO [String] -> IO (Maybe String)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO [String]
confFiles

-- | Get the highest precedence local config file: 
-- a config file in the current directory or above, that is not a user-wide config file.
activeLocalConfFile :: IO (Maybe FilePath)
activeLocalConfFile :: IO (Maybe String)
activeLocalConfFile = do
  ufs <- IO [String]
userConfFiles
  mf <- headMay <$> confFiles
  return $ case mf of
    Just String
f | String
f String -> [String] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [String]
ufs -> String -> Maybe String
forall a. a -> Maybe a
Just String
f
    Maybe String
_ -> Maybe String
forall a. Maybe a
Nothing

-- | Get the highest precedence user-wide config file, based on the current directory.
-- (This may not be the active config file.)
activeUserConfFile :: IO (Maybe FilePath)
activeUserConfFile :: IO (Maybe String)
activeUserConfFile = [String] -> Maybe String
forall a. [a] -> Maybe a
headMay ([String] -> Maybe String) -> IO [String] -> IO (Maybe String)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO [String]
userConfFiles

-- | Get the possibleConfFiles which exist, based on the current directory.
confFiles :: IO [FilePath]
confFiles :: IO [String]
confFiles = IO [String]
possibleConfFiles IO [String] -> ([String] -> IO [String]) -> IO [String]
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= [String] -> IO [String]
existingFiles

-- | Get the possibleUserConfFiles which exist, based on the current directory.
userConfFiles :: IO [FilePath]
userConfFiles :: IO [String]
userConfFiles = IO [String]
possibleUserConfFiles IO [String] -> ([String] -> IO [String]) -> IO [String]
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= [String] -> IO [String]
existingFiles

-- | Filter a list of paths to just the existing files.
existingFiles :: [FilePath] -> IO [FilePath]
existingFiles :: [String] -> IO [String]
existingFiles [String]
fs =
  ([Maybe String] -> [String]) -> IO [Maybe String] -> IO [String]
forall a b. (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap [Maybe String] -> [String]
forall a. [Maybe a] -> [a]
catMaybes (IO [Maybe String] -> IO [String])
-> IO [Maybe String] -> IO [String]
forall a b. (a -> b) -> a -> b
$ [String] -> (String -> IO (Maybe String)) -> IO [Maybe String]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
t a -> (a -> m b) -> m (t b)
forM [String]
fs ((String -> IO (Maybe String)) -> IO [Maybe String])
-> (String -> IO (Maybe String)) -> IO [Maybe String]
forall a b. (a -> b) -> a -> b
$ \String
f -> do
    exists <- String -> IO Bool
doesFileExist String
f
    return $ if exists then Just f else Nothing

-- | Get the possible paths for a hledger config file, highest precedence first:
-- hledger.conf in the current directory, 
-- hledger.conf in any parent directory, 
-- .hledger.conf in the home directory,
-- or hledger.conf in the XdgConfig directory.
possibleConfFiles :: IO [FilePath]
possibleConfFiles :: IO [String]
possibleConfFiles = do
  ds   <- IO [String]
possibleConfDirs
  home <- getHomeDirectory
  return $ dbg8 "possible config file paths" $
    flip map ds $ \String
d -> String
d String -> String -> String
</> if String
dString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
home then String
".hledger.conf" else String
"hledger.conf"

-- | Like possibleConfFiles, but consider only user-wide hledger config files:
-- .hledger.conf in the home directory,
-- or hledger.conf in the XdgConfig directory.
possibleUserConfFiles :: IO [FilePath]
possibleUserConfFiles :: IO [String]
possibleUserConfFiles = do
  home <- IO String
getHomeDirectory
  xdgc <- getXdgDirectory XdgConfig "hledger"
  let ds = [String
home,String
xdgc]
  return $ dbg8 "possible user config file paths" $
    flip map ds $ \String
d -> String
d String -> String -> String
</> if String
dString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
home then String
".hledger.conf" else String
"hledger.conf"

-- | Get the directories where a hledger config file could be, highest precedence first:
-- the current directory, any parent directory, the home directory, or the XdgConfig directory.
possibleConfDirs :: IO [FilePath]
possibleConfDirs :: IO [String]
possibleConfDirs = do
  xdgc <- XdgDirectory -> String -> IO String
getXdgDirectory XdgDirectory
XdgConfig String
"hledger"
  home <- getHomeDirectory
  here <- getCurrentDirectory
  dirs <- getDirsUpToRoot here
  let dirs2 = if String
home String -> [String] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [String]
dirs then [String]
dirs else [String]
dirs [String] -> [String] -> [String]
forall a. Semigroup a => a -> a -> a
<> [String
home]
  let dirs3 = if String
xdgc String -> [String] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [String]
dirs2 then [String]
dirs2 else [String]
dirs2 [String] -> [String] -> [String]
forall a. Semigroup a => a -> a -> a
<> [String
xdgc]
  return $ dbg8 "searching config dirs" dirs3

-- | Get this directory and all of its parents up to /.
getDirsUpToRoot :: FilePath -> IO [FilePath]
getDirsUpToRoot :: String -> IO [String]
getDirsUpToRoot String
dir = [String] -> IO [String]
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ([String] -> IO [String]) -> [String] -> IO [String]
forall a b. (a -> b) -> a -> b
$ [String] -> String -> [String]
go [] String
dir
  where
    go :: [String] -> String -> [String]
go [String]
seen String
d = if
      | String
d String -> [String] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [String]
seen Bool -> Bool -> Bool
|| [String] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [String]
seen Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
100 -> []  -- just in case
      | String
dString -> String -> Bool
forall a. Eq a => a -> a -> Bool
==String
"/"    -> [String
d]
      | Bool
otherwise -> String
d String -> [String] -> [String]
forall a. a -> [a] -> [a]
: [String] -> String -> [String]
go (String
dString -> [String] -> [String]
forall a. a -> [a] -> [a]
:[String]
seen) (String -> String
takeDirectory String
d)

-- config file parsing

parseConf :: FilePath -> Text -> Either (ParseErrorBundle Text HledgerParseErrorData) [ConfSection]
parseConf :: String
-> Text
-> Either
     (ParseErrorBundle Text HledgerParseErrorData) [ConfSection]
parseConf = Parsec HledgerParseErrorData Text [ConfSection]
-> String
-> Text
-> Either
     (ParseErrorBundle Text HledgerParseErrorData) [ConfSection]
forall e s a.
Parsec e s a -> String -> s -> Either (ParseErrorBundle s e) a
runParser Parsec HledgerParseErrorData Text [ConfSection]
confp

dp :: String -> TextParser m ()
dp :: forall (m :: * -> *). String -> TextParser m ()
dp = TextParser m () -> String -> TextParser m ()
forall a b. a -> b -> a
const (TextParser m () -> String -> TextParser m ())
-> TextParser m () -> String -> TextParser m ()
forall a b. (a -> b) -> a -> b
$ () -> TextParser m ()
forall a. a -> ParsecT HledgerParseErrorData Text m a
forall (m :: * -> *) a. Monad m => a -> m a
return ()  -- no-op
-- dp = dbgparse 0  -- trace parse state at this --debug level

-- get the config file line number at the current parse position
sourceLineNumberp :: TextParser Identity Int
sourceLineNumberp :: TextParser Identity Int
sourceLineNumberp = Pos -> Int
unPos (Pos -> Int) -> (SourcePos -> Pos) -> SourcePos -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SourcePos -> Pos
sourceLine (SourcePos -> Int)
-> ParsecT HledgerParseErrorData Text Identity SourcePos
-> TextParser Identity Int
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ParsecT HledgerParseErrorData Text Identity SourcePos
forall s e (m :: * -> *).
(TraversableStream s, MonadParsec e s m) =>
m SourcePos
getSourcePos

whitespacep, commentlinesp, restoflinep :: TextParser Identity ()
whitespacep :: TextParser Identity ()
whitespacep   = ParsecT HledgerParseErrorData Text Identity String
-> TextParser Identity ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (ParsecT HledgerParseErrorData Text Identity String
 -> TextParser Identity ())
-> ParsecT HledgerParseErrorData Text Identity String
-> TextParser Identity ()
forall a b. (a -> b) -> a -> b
$ {- dp "whitespacep"   >> -} ParsecT HledgerParseErrorData Text Identity Char
-> ParsecT HledgerParseErrorData Text Identity String
forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
many ParsecT HledgerParseErrorData Text Identity Char
forall s (m :: * -> *).
(Stream s, Char ~ Token s) =>
ParsecT HledgerParseErrorData s m Char
spacenonewline
-- Uses try so that a non-empty, non-comment line (possibly indented) is left for
-- another parser instead of failing here after consuming its leading whitespace.
commentlinesp :: TextParser Identity ()
commentlinesp = ParsecT HledgerParseErrorData Text Identity [()]
-> TextParser Identity ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (ParsecT HledgerParseErrorData Text Identity [()]
 -> TextParser Identity ())
-> ParsecT HledgerParseErrorData Text Identity [()]
-> TextParser Identity ()
forall a b. (a -> b) -> a -> b
$ {- dp "commentlinesp" >> -} TextParser Identity ()
-> ParsecT HledgerParseErrorData Text Identity [()]
forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
many (TextParser Identity () -> TextParser Identity ()
forall a.
ParsecT HledgerParseErrorData Text Identity a
-> ParsecT HledgerParseErrorData Text Identity a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try (TextParser Identity () -> TextParser Identity ())
-> TextParser Identity () -> TextParser Identity ()
forall a b. (a -> b) -> a -> b
$ String -> TextParser Identity ()
forall (m :: * -> *). String -> TextParser m ()
emptyorcommentlinep2 String
"#")
restoflinep :: TextParser Identity ()
restoflinep   = TextParser Identity () -> TextParser Identity ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (TextParser Identity () -> TextParser Identity ())
-> TextParser Identity () -> TextParser Identity ()
forall a b. (a -> b) -> a -> b
$ {- dp "restoflinep"   >> -} TextParser Identity ()
whitespacep TextParser Identity ()
-> TextParser Identity () -> TextParser Identity ()
forall a b.
ParsecT HledgerParseErrorData Text Identity a
-> ParsecT HledgerParseErrorData Text Identity b
-> ParsecT HledgerParseErrorData Text Identity b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> String -> TextParser Identity ()
forall (m :: * -> *). String -> TextParser m ()
emptyorcommentlinep2 String
"#"

confp :: TextParser Identity [ConfSection]  -- a monadic TextParser to allow reusing other hledger parsers
confp :: Parsec HledgerParseErrorData Text [ConfSection]
confp = do
  String -> TextParser Identity ()
forall (m :: * -> *). String -> TextParser m ()
dp String
"confp"
  TextParser Identity ()
commentlinesp
  genas <- ParsecT HledgerParseErrorData Text Identity (Int, String)
-> ParsecT HledgerParseErrorData Text Identity [(Int, String)]
forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
many ParsecT HledgerParseErrorData Text Identity (Int, String)
arglinep
  let s = String -> [(Int, String)] -> ConfSection
ConfSection String
"general" [(Int, String)]
genas
  ss <- many $ do
    (n, ma) <- sectionstartp
    -- In an [alias] section, a NAME = ... value can span more-indented lines; parse each
    -- alias as one logical (joined) line. Other sections keep one argument per line.
    as <- if n == "alias" then many aliasdefp else many arglinep
    return $ ConfSection n (maybe as (:as) ma)
  whitespacep  -- tolerate trailing whitespace with no final newline (a blank last line)
  eof
  return $ s:ss

-- parse a section name and possibly arguments written on the same line
sectionstartp :: TextParser Identity (String, Maybe (Int, Arg))
sectionstartp :: TextParser Identity (String, Maybe (Int, String))
sectionstartp = do
  String -> TextParser Identity ()
forall (m :: * -> *). String -> TextParser m ()
dp String
"sectionstartp"
  TextParser Identity () -> TextParser Identity ()
forall a.
ParsecT HledgerParseErrorData Text Identity a
-> ParsecT HledgerParseErrorData Text Identity a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try (TextParser Identity ()
whitespacep TextParser Identity ()
-> ParsecT HledgerParseErrorData Text Identity Char
-> TextParser Identity ()
forall a b.
ParsecT HledgerParseErrorData Text Identity a
-> ParsecT HledgerParseErrorData Text Identity b
-> ParsecT HledgerParseErrorData Text Identity a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* ParsecT HledgerParseErrorData Text Identity Char
-> ParsecT HledgerParseErrorData Text Identity Char
forall a.
ParsecT HledgerParseErrorData Text Identity a
-> ParsecT HledgerParseErrorData Text Identity a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
lookAhead (Token Text
-> ParsecT HledgerParseErrorData Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'['))  -- ignore any leading whitespace before the [
  Token Text
-> ParsecT HledgerParseErrorData Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'['
  n <- (String -> String)
-> ParsecT HledgerParseErrorData Text Identity String
-> ParsecT HledgerParseErrorData Text Identity String
forall a b.
(a -> b)
-> ParsecT HledgerParseErrorData Text Identity a
-> ParsecT HledgerParseErrorData Text Identity b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap String -> String
strip (ParsecT HledgerParseErrorData Text Identity String
 -> ParsecT HledgerParseErrorData Text Identity String)
-> ParsecT HledgerParseErrorData Text Identity String
-> ParsecT HledgerParseErrorData Text Identity String
forall a b. (a -> b) -> a -> b
$ ParsecT HledgerParseErrorData Text Identity Char
-> ParsecT HledgerParseErrorData Text Identity String
forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
some (ParsecT HledgerParseErrorData Text Identity Char
 -> ParsecT HledgerParseErrorData Text Identity String)
-> ParsecT HledgerParseErrorData Text Identity Char
-> ParsecT HledgerParseErrorData Text Identity String
forall a b. (a -> b) -> a -> b
$ [Token Text]
-> ParsecT HledgerParseErrorData Text Identity (Token Text)
forall (f :: * -> *) e s (m :: * -> *).
(Foldable f, MonadParsec e s m) =>
f (Token s) -> m (Token s)
noneOf String
[Token Text]
"]#\n"
  char ']'
  -- dp "sectionstartp2"
  whitespacep
  -- dp "sectionstartp3"
  lnum <- sourceLineNumberp
  ma <- fmap (fmap strip) $ optional argtextp
  -- dp "sectionstartp4"
  restoflinep
  -- dp "sectionstartp5"
  commentlinesp
  -- dp "sectionstartp6"
  return (n, (lnum,) <$> ma)

-- | Parse config argument-line text up to an unquoted '#' (which starts a comment) or end of line,
-- keeping any '#' that appears inside single or double quotes (so quoted arguments can contain '#').
argtextp :: TextParser Identity String
argtextp :: ParsecT HledgerParseErrorData Text Identity String
argtextp = ([String] -> String)
-> ParsecT HledgerParseErrorData Text Identity [String]
-> ParsecT HledgerParseErrorData Text Identity String
forall a b.
(a -> b)
-> ParsecT HledgerParseErrorData Text Identity a
-> ParsecT HledgerParseErrorData Text Identity b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap [String] -> String
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat (ParsecT HledgerParseErrorData Text Identity [String]
 -> ParsecT HledgerParseErrorData Text Identity String)
-> ParsecT HledgerParseErrorData Text Identity [String]
-> ParsecT HledgerParseErrorData Text Identity String
forall a b. (a -> b) -> a -> b
$ ParsecT HledgerParseErrorData Text Identity String
-> ParsecT HledgerParseErrorData Text Identity [String]
forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
some (ParsecT HledgerParseErrorData Text Identity String
 -> ParsecT HledgerParseErrorData Text Identity [String])
-> ParsecT HledgerParseErrorData Text Identity String
-> ParsecT HledgerParseErrorData Text Identity [String]
forall a b. (a -> b) -> a -> b
$
      Char -> ParsecT HledgerParseErrorData Text Identity String
forall {s} {m :: * -> *} {e}.
(Token s ~ Char, MonadParsec e s m) =>
Char -> m String
quotedspanp Char
'\'' ParsecT HledgerParseErrorData Text Identity String
-> ParsecT HledgerParseErrorData Text Identity String
-> ParsecT HledgerParseErrorData Text Identity String
forall a.
ParsecT HledgerParseErrorData Text Identity a
-> ParsecT HledgerParseErrorData Text Identity a
-> ParsecT HledgerParseErrorData Text Identity a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Char -> ParsecT HledgerParseErrorData Text Identity String
forall {s} {m :: * -> *} {e}.
(Token s ~ Char, MonadParsec e s m) =>
Char -> m String
quotedspanp Char
'"' ParsecT HledgerParseErrorData Text Identity String
-> ParsecT HledgerParseErrorData Text Identity String
-> ParsecT HledgerParseErrorData Text Identity String
forall a.
ParsecT HledgerParseErrorData Text Identity a
-> ParsecT HledgerParseErrorData Text Identity a
-> ParsecT HledgerParseErrorData Text Identity a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> ParsecT HledgerParseErrorData Text Identity Char
-> ParsecT HledgerParseErrorData Text Identity String
forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
some ([Token Text]
-> ParsecT HledgerParseErrorData Text Identity (Token Text)
forall (f :: * -> *) e s (m :: * -> *).
(Foldable f, MonadParsec e s m) =>
f (Token s) -> m (Token s)
noneOf String
[Token Text]
"'\"#\n")
  where
    quotedspanp :: Char -> m String
quotedspanp Char
q = do
      _  <- Token s -> m (Token s)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token s
q
      s  <- many (noneOf [q,'\n'])
      qc <- optional (char q)
      return $ q : s ++ maybe "" pure qc

-- Uses try so that an indented section header ([..]) is left for sectionstartp
-- rather than failing here after consuming its leading whitespace.
arglinep :: TextParser Identity (Int, Arg)
arglinep :: ParsecT HledgerParseErrorData Text Identity (Int, String)
arglinep = ParsecT HledgerParseErrorData Text Identity (Int, String)
-> ParsecT HledgerParseErrorData Text Identity (Int, String)
forall a.
ParsecT HledgerParseErrorData Text Identity a
-> ParsecT HledgerParseErrorData Text Identity a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try (ParsecT HledgerParseErrorData Text Identity (Int, String)
 -> ParsecT HledgerParseErrorData Text Identity (Int, String))
-> ParsecT HledgerParseErrorData Text Identity (Int, String)
-> ParsecT HledgerParseErrorData Text Identity (Int, String)
forall a b. (a -> b) -> a -> b
$ do
  String -> TextParser Identity ()
forall (m :: * -> *). String -> TextParser m ()
dp String
"arglinep"
  TextParser Identity ()
whitespacep  -- ignore any leading whitespace
  -- dp "arglinep2"
  ParsecT HledgerParseErrorData Text Identity Char
-> TextParser Identity ()
forall a.
ParsecT HledgerParseErrorData Text Identity a
-> TextParser Identity ()
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m ()
notFollowedBy (ParsecT HledgerParseErrorData Text Identity Char
 -> TextParser Identity ())
-> ParsecT HledgerParseErrorData Text Identity Char
-> TextParser Identity ()
forall a b. (a -> b) -> a -> b
$ Token Text
-> ParsecT HledgerParseErrorData Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'['  -- an indented section header is not an argument line
  -- dp "arglinep3"
  lnum <- TextParser Identity Int
sourceLineNumberp
  a <- argtextp
  -- dp "arglinep4"
  restoflinep <|> whitespacep  -- whitespace / same-line comment, possibly with no newline
  commentlinesp
  return (lnum, strip a)

-- | Parse one alias definition in an [alias] section: a "NAME = ..." line, plus any
-- following lines indented more than it, joined (whitespace-normalised) into one logical line.
-- Blank and comment lines are skipped; a line indented no more than the NAME line, a section
-- header, or end of file ends the definition. This is what lets an alias's command line span
-- several indented lines.
aliasdefp :: TextParser Identity (Int, Arg)
aliasdefp :: ParsecT HledgerParseErrorData Text Identity (Int, String)
aliasdefp = ParsecT HledgerParseErrorData Text Identity (Int, String)
-> ParsecT HledgerParseErrorData Text Identity (Int, String)
forall a.
ParsecT HledgerParseErrorData Text Identity a
-> ParsecT HledgerParseErrorData Text Identity a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try (ParsecT HledgerParseErrorData Text Identity (Int, String)
 -> ParsecT HledgerParseErrorData Text Identity (Int, String))
-> ParsecT HledgerParseErrorData Text Identity (Int, String)
-> ParsecT HledgerParseErrorData Text Identity (Int, String)
forall a b. (a -> b) -> a -> b
$ do
  TextParser Identity ()
whitespacep  -- ignore any leading whitespace
  ParsecT HledgerParseErrorData Text Identity Char
-> TextParser Identity ()
forall a.
ParsecT HledgerParseErrorData Text Identity a
-> TextParser Identity ()
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m ()
notFollowedBy (ParsecT HledgerParseErrorData Text Identity Char
 -> TextParser Identity ())
-> ParsecT HledgerParseErrorData Text Identity Char
-> TextParser Identity ()
forall a b. (a -> b) -> a -> b
$ Token Text
-> ParsecT HledgerParseErrorData Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'['  -- an indented section header is not an alias definition
  lnum <- TextParser Identity Int
sourceLineNumberp
  ref  <- indentcolp  -- the column of this alias's NAME
  first <- argtextp
  restoflinep <|> whitespacep
  conts <- many (continuationp ref)
  commentlinesp  -- consume trailing blank/comment lines before the next definition or header
  return (lnum, strip $ unwords $ strip first : conts)
  where
    -- a line indented more than ref (the NAME column), continuing the alias's command line
    continuationp :: Int -> ParsecT HledgerParseErrorData Text Identity String
continuationp Int
ref = ParsecT HledgerParseErrorData Text Identity String
-> ParsecT HledgerParseErrorData Text Identity String
forall a.
ParsecT HledgerParseErrorData Text Identity a
-> ParsecT HledgerParseErrorData Text Identity a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try (ParsecT HledgerParseErrorData Text Identity String
 -> ParsecT HledgerParseErrorData Text Identity String)
-> ParsecT HledgerParseErrorData Text Identity String
-> ParsecT HledgerParseErrorData Text Identity String
forall a b. (a -> b) -> a -> b
$ do
      TextParser Identity ()
commentlinesp  -- skip any blank/comment lines within the indented block
      TextParser Identity ()
whitespacep
      col <- TextParser Identity Int
indentcolp
      guard $ col > ref
      notFollowedBy $ char '['  -- a section header ends the definition even if indented
      s <- argtextp
      restoflinep <|> whitespacep
      return $ strip s

-- the column (1-based) at the current parse position, used to compare indentation
indentcolp :: TextParser Identity Int
indentcolp :: TextParser Identity Int
indentcolp = Pos -> Int
unPos (Pos -> Int) -> (SourcePos -> Pos) -> SourcePos -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SourcePos -> Pos
sourceColumn (SourcePos -> Int)
-> ParsecT HledgerParseErrorData Text Identity SourcePos
-> TextParser Identity Int
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ParsecT HledgerParseErrorData Text Identity SourcePos
forall s e (m :: * -> *).
(TraversableStream s, MonadParsec e s m) =>
m SourcePos
getSourcePos


-- initialiseAndParseJournal :: ErroringJournalParser IO ParsedJournal -> InputOpts
--                           -> FilePath -> Text -> ExceptT String IO Journal
-- initialiseAndParseJournal parser iopts f txt =
--     prettyParseErrors $ runParserT (evalStateT parser initJournal) f txt
--   where
--     y = first3 . toGregorian $ _ioDay iopts
--     initJournal = nulljournal{jparsedefaultyear = Just y, jparseincludefilestack = [f]}
--     -- Flatten parse errors and final parse errors, and output each as a pretty String.
--     prettyParseErrors :: ExceptT FinalParseError IO (Either (ParseErrorBundle Text HledgerParseErrorData) a)
--                       -> ExceptT String IO a
--     prettyParseErrors = withExceptT customErrorBundlePretty . liftEither
--                     <=< withExceptT (finalErrorBundlePretty . attachSource f txt)