{-|

The @files@ command lists included files.

-}

{-# LANGUAGE TemplateHaskell #-}

module Hledger.Cli.Commands.Files (
  filesmode
 ,files
) where

import qualified Data.Text as T
import Safe (headMay)

import Hledger
import Hledger.Cli.CliOptions


-- | Command line options for this command.
filesmode :: Mode RawOpts
filesmode = CommandDoc
-> [Flag RawOpts]
-> [(CommandDoc, [Flag RawOpts])]
-> [Flag RawOpts]
-> ([Arg RawOpts], Maybe (Arg RawOpts))
-> Mode RawOpts
hledgerCommandMode
  $(embedFileRelative "Hledger/Cli/Commands/Files.txt")
  []
  [(CommandDoc, [Flag RawOpts])
generalflagsgroup2]
  []
  ([], forall a. a -> Maybe a
Just forall a b. (a -> b) -> a -> b
$ CommandDoc -> Arg RawOpts
argsFlag CommandDoc
"[REGEX]")

-- | The files command.
files :: CliOpts -> Journal -> IO ()
files :: CliOpts -> Journal -> IO ()
files CliOpts{rawopts_ :: CliOpts -> RawOpts
rawopts_=RawOpts
rawopts} Journal
j = do
  let args :: [CommandDoc]
args = CommandDoc -> RawOpts -> [CommandDoc]
listofstringopt CommandDoc
"args" RawOpts
rawopts
  Maybe Regexp
regex <- forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either forall (m :: * -> *) a. MonadFail m => CommandDoc -> m a
fail forall (f :: * -> *) a. Applicative f => a -> f a
pure forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Either CommandDoc Regexp
toRegex forall b c a. (b -> c) -> (a -> b) -> a -> c
. CommandDoc -> Text
T.pack) forall a b. (a -> b) -> a -> b
$ forall a. [a] -> Maybe a
headMay [CommandDoc]
args
  let fs :: [CommandDoc]
fs = forall b a. b -> (a -> b) -> Maybe a -> b
maybe forall a. a -> a
id (forall a. (a -> Bool) -> [a] -> [a]
filter forall b c a. (b -> c) -> (a -> b) -> a -> c
. Regexp -> CommandDoc -> Bool
regexMatch) Maybe Regexp
regex
              forall a b. (a -> b) -> a -> b
$ forall a b. (a -> b) -> [a] -> [b]
map forall a b. (a, b) -> a
fst
              forall a b. (a -> b) -> a -> b
$ Journal -> [(CommandDoc, Text)]
jfiles Journal
j
  forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ CommandDoc -> IO ()
putStrLn [CommandDoc]
fs