{-|

The @files@ command lists the files read: the main and included data files,
and any rules or data files used to read them.

-}

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

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

import Data.Aeson (ToJSON(..), object, (.=))
import Data.List (mapAccumL, tails)
import Data.Maybe (fromMaybe)
import Data.Text qualified as T
import Safe (headMay)
import System.Console.CmdArgs.Explicit (flagNone)
import System.Directory (doesFileExist)
import System.FilePath (makeRelative, takeDirectory)

import Hledger
import Hledger.Cli.CliOptions
import Hledger.Cli.Utils (unsupportedOutputFormatError, writeOutputLazyText, writeOutputWithTitle)


-- | Command line options for this command.
filesmode :: Mode RawOpts
filesmode = String
-> [Flag RawOpts]
-> [(String, [Flag RawOpts])]
-> [Flag RawOpts]
-> ([Arg RawOpts], Maybe (Arg RawOpts))
-> Mode RawOpts
hledgerCommandMode
  $(embedFileRelative "Hledger/Cli/Commands/Files.txt")
  [[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"flat",String
"l"] (String -> RawOpts -> RawOpts
setboolopt String
"flat") String
"list/tree mode: show files as a flat list (default)"
  ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"tree",String
"t"] (String -> RawOpts -> RawOpts
setboolopt String
"tree") String
"list/tree mode: show files as a tree, indenting included files below the file that includes them"
  ,[String] -> Flag RawOpts
outputFormatFlag [String
"txt",String
"json"]
  ,Flag RawOpts
outputFileFlag
  ]
  [(String, [Flag RawOpts])]
cligeneralflagsgroups2
  [Flag RawOpts]
hiddenflags
  ([], Arg RawOpts -> Maybe (Arg RawOpts)
forall a. a -> Maybe a
Just (Arg RawOpts -> Maybe (Arg RawOpts))
-> Arg RawOpts -> Maybe (Arg RawOpts)
forall a b. (a -> b) -> a -> b
$ String -> Arg RawOpts
argsFlag String
"[REGEX]")

-- | One entry in the list of files read.
data FileEntry = FileEntry {
   FileEntry -> String
fePath      :: FilePath        -- ^ the file's path
  ,FileEntry -> String
feShortPath :: FilePath        -- ^ its path relative to its parent's directory, if it has a parent
  ,FileEntry -> Int
feDepth     :: Int             -- ^ its depth in the tree of files: 0 for a main file
  ,FileEntry -> Maybe String
feParent    :: Maybe FilePath  -- ^ the file which included it, or which it was used to read
  ,FileEntry -> Bool
feExists    :: Bool            -- ^ does it exist ? (Missing included files are recorded, not an error, when finding the files read.)
  }

instance ToJSON FileEntry where
  toJSON :: FileEntry -> Value
toJSON FileEntry
e = [Pair] -> Value
object
    [ Key
"path"   Key -> String -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= FileEntry -> String
fePath FileEntry
e
    , Key
"depth"  Key -> Int -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= FileEntry -> Int
feDepth FileEntry
e
    , Key
"parent" Key -> Maybe String -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= FileEntry -> Maybe String
feParent FileEntry
e
    , Key
"exists" Key -> Bool -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= FileEntry -> Bool
feExists FileEntry
e
    ]

-- | The files command.
files :: CliOpts -> Journal -> IO ()
files :: CliOpts -> Journal -> IO ()
files opts :: CliOpts
opts@CliOpts{rawopts_ :: CliOpts -> RawOpts
rawopts_=RawOpts
rawopts, reportspec_ :: CliOpts -> ReportSpec
reportspec_=ReportSpec
rspec} Journal
j = do
  let args :: [String]
args = String -> RawOpts -> [String]
listofstringopt String
"args" RawOpts
rawopts
  regex <- (String -> IO Regexp) -> Maybe String -> IO (Maybe Regexp)
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) -> Maybe a -> m (Maybe b)
mapM ((String -> IO Regexp)
-> (Regexp -> IO Regexp) -> Either String Regexp -> IO Regexp
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either String -> IO Regexp
forall a. HasCallStack => String -> IO a
forall (m :: * -> *) a.
(MonadFail m, HasCallStack) =>
String -> m a
fail Regexp -> IO Regexp
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either String Regexp -> IO Regexp)
-> (String -> Either String Regexp) -> String -> IO Regexp
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Either String Regexp
toRegex (Text -> Either String Regexp)
-> (String -> Text) -> String -> Either String Regexp
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Text
T.pack) (Maybe String -> IO (Maybe Regexp))
-> Maybe String -> IO (Maybe Regexp)
forall a b. (a -> b) -> a -> b
$ [String] -> Maybe String
forall a. [a] -> Maybe a
headMay [String]
args
  es <- mapM setExists $ fileEntries j
  let
    matches = (String -> Bool)
-> (Regexp -> String -> Bool) -> Maybe Regexp -> String -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Bool -> String -> Bool
forall a b. a -> b -> a
const Bool
True) Regexp -> String -> Bool
regexMatch Maybe Regexp
regex (String -> Bool) -> (FileEntry -> String) -> FileEntry -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FileEntry -> String
fePath
    matched = (FileEntry -> Bool) -> [FileEntry] -> [FileEntry]
forall a. (a -> Bool) -> [a] -> [a]
filter FileEntry -> Bool
matches [FileEntry]
es
    -- text output shows only existing files, and warns about missing ones
    existing = (FileEntry -> Bool) -> [FileEntry] -> [FileEntry]
forall a. (a -> Bool) -> [a] -> [a]
filter FileEntry -> Bool
feExists [FileEntry]
es
    warnMissing = (FileEntry -> IO ()) -> [FileEntry] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (String -> IO ()
forall (m :: * -> *). MonadIO m => String -> m ()
warnIO (String -> IO ()) -> (FileEntry -> String) -> FileEntry -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (String
"file not found: " String -> String -> String
forall a. Semigroup a => a -> a -> a
<>) (String -> String) -> (FileEntry -> String) -> FileEntry -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FileEntry -> String
fePath) ([FileEntry] -> IO ()) -> [FileEntry] -> IO ()
forall a b. (a -> b) -> a -> b
$ (FileEntry -> Bool) -> [FileEntry] -> [FileEntry]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (FileEntry -> Bool) -> FileEntry -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FileEntry -> Bool
feExists) [FileEntry]
matched
  case outputFormatFromOpts opts of
    String
"json" -> CliOpts -> Text -> IO ()
writeOutputLazyText CliOpts
opts (Text -> IO ()) -> Text -> IO ()
forall a b. (a -> b) -> a -> b
$ [FileEntry] -> Text
forall a. ToJSON a => a -> Text
toJsonText [FileEntry]
matched
    String
"txt"
      | ReportOpts -> Bool
tree_ (ReportOpts -> Bool) -> ReportOpts -> Bool
forall a b. (a -> b) -> a -> b
$ ReportSpec -> ReportOpts
_rsReportOpts ReportSpec
rspec -> do
          IO ()
warnMissing
          -- show each file whose subtree has a match, keeping the tree visible
          [String] -> IO ()
writeLines [ Int -> Char -> String
forall a. Int -> a -> [a]
replicate (Int
2 Int -> Int -> Int
forall a. Num a => a -> a -> a
* FileEntry -> Int
feDepth FileEntry
e) Char
' ' String -> String -> String
forall a. [a] -> [a] -> [a]
++ FileEntry -> String
feShortPath FileEntry
e
                     | FileEntry
e:[FileEntry]
rest <- [FileEntry] -> [[FileEntry]]
forall a. [a] -> [[a]]
tails [FileEntry]
existing
                     , (FileEntry -> Bool) -> [FileEntry] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any FileEntry -> Bool
matches ([FileEntry] -> Bool) -> [FileEntry] -> Bool
forall a b. (a -> b) -> a -> b
$ FileEntry
e FileEntry -> [FileEntry] -> [FileEntry]
forall a. a -> [a] -> [a]
: (FileEntry -> Bool) -> [FileEntry] -> [FileEntry]
forall a. (a -> Bool) -> [a] -> [a]
takeWhile ((Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> FileEntry -> Int
feDepth FileEntry
e) (Int -> Bool) -> (FileEntry -> Int) -> FileEntry -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FileEntry -> Int
feDepth) [FileEntry]
rest
                     ]
      | Bool
otherwise -> do
          IO ()
warnMissing
          [String] -> IO ()
writeLines ([String] -> IO ()) -> [String] -> IO ()
forall a b. (a -> b) -> a -> b
$ (FileEntry -> String) -> [FileEntry] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map FileEntry -> String
fePath ([FileEntry] -> [String]) -> [FileEntry] -> [String]
forall a b. (a -> b) -> a -> b
$ (FileEntry -> Bool) -> [FileEntry] -> [FileEntry]
forall a. (a -> Bool) -> [a] -> [a]
filter FileEntry -> Bool
matches [FileEntry]
existing
    String
fmt -> String -> IO ()
exitWithErrorMessage (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String -> String
unsupportedOutputFormatError String
fmt
  where
    writeLines :: [String] -> IO ()
writeLines = CliOpts -> Text -> IO ()
writeOutputWithTitle CliOpts
opts (Text -> IO ()) -> ([String] -> Text) -> [String] -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Text] -> Text
T.unlines ([Text] -> Text) -> ([String] -> [Text]) -> [String] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (String -> Text) -> [String] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map String -> Text
T.pack
    setExists :: FileEntry -> IO FileEntry
setExists FileEntry
e = do
      exists <- if FileEntry -> String
fePath FileEntry
e String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
"-" then Bool -> IO Bool
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True else String -> IO Bool
doesFileExist (String -> IO Bool) -> String -> IO Bool
forall a b. (a -> b) -> a -> b
$ FileEntry -> String
fePath FileEntry
e
      return e{feExists=exists}

-- | The journal's files in the order they were read, each followed by any auxiliary files
-- used to read it (eg a CSV file's rules file, or a rules file's included rules files and data file),
-- which appear one level deeper in the tree. (Whether they exist is checked later.)
fileEntries :: Journal -> [FileEntry]
fileEntries :: Journal -> [FileEntry]
fileEntries Journal
j = ([String], [FileEntry]) -> [FileEntry]
forall a b. (a, b) -> b
snd (([String], [FileEntry]) -> [FileEntry])
-> ([String], [FileEntry]) -> [FileEntry]
forall a b. (a -> b) -> a -> b
$ ([String] -> (String, Int) -> ([String], FileEntry))
-> [String] -> [(String, Int)] -> ([String], [FileEntry])
forall (t :: * -> *) s a b.
Traversable t =>
(s -> a -> (s, b)) -> s -> t a -> (s, t b)
mapAccumL [String] -> (String, Int) -> ([String], FileEntry)
entry [] [(String, Int)]
filesanddepths
  where
    filesanddepths :: [(String, Int)]
filesanddepths = [[(String, Int)]] -> [(String, Int)]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat
      [ (JournalFile -> String
jfpath JournalFile
jf, JournalFile -> Int
jfdepth JournalFile
jf) (String, Int) -> [(String, Int)] -> [(String, Int)]
forall a. a -> [a] -> [a]
: [(String
a, JournalFile -> Int
jfdepth JournalFile
jf Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) | String
a <- [String] -> Maybe [String] -> [String]
forall a. a -> Maybe a -> a
fromMaybe [] (Maybe [String] -> [String]) -> Maybe [String] -> [String]
forall a b. (a -> b) -> a -> b
$ String -> [(String, [String])] -> Maybe [String]
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup (JournalFile -> String
jfpath JournalFile
jf) (Journal -> [(String, [String])]
jauxfiles Journal
j)]
      | JournalFile
jf <- Journal -> [JournalFile]
jfiles Journal
j ]
    -- the accumulator is the chain of parent files' paths, most recent first
    entry :: [String] -> (String, Int) -> ([String], FileEntry)
entry [String]
parents0 (String
f, Int
d) = (String
f String -> [String] -> [String]
forall a. a -> [a] -> [a]
: [String]
parents, String -> String -> Int -> Maybe String -> Bool -> FileEntry
FileEntry String
f String
shortpath Int
d Maybe String
mparent Bool
True)
      where
        parents :: [String]
parents = Int -> [String] -> [String]
forall a. Int -> [a] -> [a]
drop ([String] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [String]
parents0 Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
d) [String]
parents0
        mparent :: Maybe String
mparent = [String] -> Maybe String
forall a. [a] -> Maybe a
headMay [String]
parents
        -- For a file included by a literal path, this is the path as written in the include directive.
        shortpath :: String
shortpath = String -> (String -> String) -> Maybe String -> String
forall b a. b -> (a -> b) -> Maybe a -> b
maybe String
f (\String
p -> String -> String -> String
makeRelative (String -> String
takeDirectory String
p) String
f) Maybe String
mparent