{-|

The @run@ command allows you to run multiple commands via REPL or from the supplied file(s).

-}

{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}

module Hledger.Cli.Commands.Run (
  runmode
 ,run
 ,replmode
 ,repl
 ,runOrReplStub
) where

import Data.List (isInfixOf)
import Data.List.NonEmpty qualified as NE
import Data.Map.Strict qualified as Map
import Data.Semigroup (sconcat)
import Data.Text qualified as T
import Data.Text.IO qualified as T
import Data.Text.Lazy qualified as TL
import System.Console.CmdArgs.Explicit as C ( Mode )
import Hledger
import Hledger.Cli.CliOptions
import Hledger.Utils.I18n qualified as I18n
import Hledger.Cli.Conf (CommandAlias, CommandLine, ResolvedCommand(..), expandCommandAlias, getConf, confAliases)

import Control.Exception
import Control.Concurrent.MVar
import Control.Monad (forM_, void, when, zipWithM_)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Extra (concatMapM, anyM)
import Data.IORef (IORef, modifyIORef, newIORef, readIORef, writeIORef)
import Data.Time.Clock.POSIX (POSIXTime, utcTimeToPOSIXSeconds)

import System.Exit (ExitCode(..), exitWith)
import System.Console.CmdArgs.Explicit (expandArgsAt, flagHelp, flagNames, flagNone, modeFlags, modeNames)
import System.IO (stdin, stderr, stdout, hClose, hIsTerminalDevice, hIsOpen, hPutStrLn, hFlush, openTempFile)
import System.IO.Unsafe (unsafePerformIO)
import System.Console.Haskeline

import Data.Maybe (isJust, fromMaybe, catMaybes)
import Safe (headMay)
import Hledger.Cli.DocFiles (runTldrForPage, runInfoForTopic, runManForTopic)
import Hledger.Cli.Utils (journalTransform, journalFileIsNewer, maybeFileModificationTime, writeOutputLazyText)
import Text.Printf (printf)
import System.FilePath (takeBaseName, getSearchPath)
import System.Directory (XdgDirectory(..), createDirectoryIfMissing, doesDirectoryExist, getModificationTime, getXdgDirectory, removeFile)
import System.Process (system)
import Hledger.Cli.Version (packageversion)
import Hledger.Write.Html (htmlAsLazyText, nl)
import Text.Blaze.Html5 ((!), (!?))
import Text.Blaze.Html5 qualified as H
import Text.Blaze.Html5.Attributes qualified as A

-- | Command line options for this command.
runmode :: Mode RawOpts
runmode = String
-> [Flag RawOpts]
-> [(String, [Flag RawOpts])]
-> [Flag RawOpts]
-> ([Arg RawOpts], Maybe (Arg RawOpts))
-> Mode RawOpts
hledgerCommandMode
  $(embedFileRelative "Hledger/Cli/Commands/Run.txt")
  (
  [[String] -> Flag RawOpts
outputFormatFlag [String
"html"]
  ,Flag RawOpts
outputFileFlag
  ,Flag RawOpts
outputViewFlag
  ])
  [(String, [Flag RawOpts])]
cligeneralflagsgroups1
  -- A hidden marker flag, inserted before run's first -- (see argsMarkRunCommands), letting run
  -- detect it was given inline commands rather than command files. Not for direct use.
  ([String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
runCommandsMarker] (String -> RawOpts -> RawOpts
setboolopt String
runCommandsMarker) String
"" Flag RawOpts -> [Flag RawOpts] -> [Flag RawOpts]
forall a. a -> [a] -> [a]
: [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
"[COMMANDS_FILE1 COMMANDS_FILE2 ...] OR [-- command1 args... -- command2 args... -- command3 args...]")

replmode :: Mode RawOpts
replmode = String
-> [Flag RawOpts]
-> [(String, [Flag RawOpts])]
-> [Flag RawOpts]
-> ([Arg RawOpts], Maybe (Arg RawOpts))
-> Mode RawOpts
hledgerCommandMode
  $(embedFileRelative "Hledger/Cli/Commands/Repl.txt")
  (
  [[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"no-watch"] (String -> RawOpts -> RawOpts
setboolopt String
"no-watch") String
"disable automatic reloading of changed input files, config aliases and addon commands"]
  )
  [(String, [Flag RawOpts])]
cligeneralflagsgroups1
  [Flag RawOpts]
hiddenflags
  ([], Maybe (Arg RawOpts)
forall a. Maybe a
Nothing)

-- | The fake run/repl command introduced to break circular dependency.
-- This module needs access to `findBuiltinCommand`, which is defined in Hledger.Cli.Commands
-- However, Hledger.Cli.Commands imports this module, which creates circular dependency.
-- We expose this do-nothing function so that it could be included in the list of all commands inside
-- Hledger.Cli.Commands and ensure that "run" is recognized as a valid command by the Hledger.Cli top-level
-- command line parser. That parser, however, would not call run'. It has a special case for "run", and
-- will call "run" (see below), passing it `findBuiltinCommand`, thus breaking circular dependency.
runOrReplStub :: CliOpts -> Journal -> IO ()
runOrReplStub :: CliOpts -> Journal -> IO ()
runOrReplStub CliOpts
_opts Journal
_j = () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()

-- | Default input files that would be used by commands if
--   there is no explicit alternative given
newtype DefaultRunJournal = DefaultRunJournal (NE.NonEmpty String) deriving (Int -> DefaultRunJournal -> String -> String
[DefaultRunJournal] -> String -> String
DefaultRunJournal -> String
(Int -> DefaultRunJournal -> String -> String)
-> (DefaultRunJournal -> String)
-> ([DefaultRunJournal] -> String -> String)
-> Show DefaultRunJournal
forall a.
(Int -> a -> String -> String)
-> (a -> String) -> ([a] -> String -> String) -> Show a
$cshowsPrec :: Int -> DefaultRunJournal -> String -> String
showsPrec :: Int -> DefaultRunJournal -> String -> String
$cshow :: DefaultRunJournal -> String
show :: DefaultRunJournal -> String
$cshowList :: [DefaultRunJournal] -> String -> String
showList :: [DefaultRunJournal] -> String -> String
Show)

-- | The actual run command.
run :: Maybe DefaultRunJournal -> (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())) -> [String] -> [(CommandAlias,CommandLine)] -> Bool -> CliOpts -> IO ()
run :: Maybe DefaultRunJournal
-> (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ()))
-> [String]
-> [(String, String)]
-> Bool
-> CliOpts
-> IO ()
run Maybe DefaultRunJournal
defaultJournalOverride String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())
findBuiltinCommand [String]
addons [(String, String)]
cmdaliases Bool
shellaliasesallowed cliopts :: CliOpts
cliopts@CliOpts{rawopts_ :: CliOpts -> RawOpts
rawopts_=RawOpts
rawopts} = do
  jpaths <- NonEmpty String -> DefaultRunJournal
DefaultRunJournal (NonEmpty String -> DefaultRunJournal)
-> IO (NonEmpty String) -> IO DefaultRunJournal
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe DefaultRunJournal -> CliOpts -> IO (NonEmpty String)
journalFilePathFromOptsOrDefault Maybe DefaultRunJournal
defaultJournalOverride CliOpts
cliopts
  let
    args = String -> [String] -> [String]
forall a. Show a => String -> a -> a
dbg1 String
"args" ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ String -> RawOpts -> [String]
listofstringopt String
"args" RawOpts
rawopts
    rungeneralopts = RawOpts -> [(String, String)]
generalRawOpts RawOpts
rawopts  -- general flags we will propagate to each command
    addonfileargs = (String -> [String]) -> [String] -> [String]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (\String
f -> [String
"-f", String
f]) ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ CliOpts -> [String]
file_ CliOpts
cliopts  -- the session's explicit -f files, to pass through to addons
  isTerminal <- isStdinTerminal
  -- With html output (-O html, -o FILE.html or --view), the commands' outputs are collected into one html page.
  let
    outputrequested = Maybe String -> Bool
forall a. Maybe a -> Bool
isJust (CliOpts -> Maybe String
output_file_ CliOpts
cliopts) Bool -> Bool -> Bool
|| Maybe String -> Bool
forall a. Maybe a -> Bool
isJust (CliOpts -> Maybe String
output_format_ CliOpts
cliopts) Bool -> Bool -> Bool
|| CliOpts -> Bool
viewRequested CliOpts
cliopts
    collecting = Bool
outputrequested Bool -> Bool -> Bool
&& CliOpts -> String
outputFormatFromOpts CliOpts
cliopts String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
"html"
  when (outputrequested && not collecting) $ error' "run can write only html output; use -O html, -o FILE.html or --view"  -- PARTIAL:
  mcollect <- if collecting then Just <$> newIORef [] else return Nothing
  if
    -- Inline commands (a -- was present, flagged by the marker): split and run them.
    | boolopt runCommandsMarker rawopts ->
        runFromArgs jpaths rungeneralopts addonfileargs findBuiltinCommand addons cmdaliases shellaliasesallowed mcollect args
    -- No arguments and stdin is not a terminal: read commands from stdin.
    | args == [] && not isTerminal -> do
        inputFiles <- journalFilePathFromOpts cliopts
        let journalFromStdin = (String -> Bool) -> [String] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
"-") ([String] -> Bool) -> [String] -> Bool
forall a b. (a -> b) -> a -> b
$ (String -> String) -> [String] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map ((Maybe StorageFormat, String) -> String
forall a b. (a, b) -> b
snd ((Maybe StorageFormat, String) -> String)
-> (String -> (Maybe StorageFormat, String)) -> String -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> (Maybe StorageFormat, String)
splitReaderPrefix) ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ NonEmpty String -> [String]
forall a. NonEmpty a -> [a]
NE.toList NonEmpty String
inputFiles
        if journalFromStdin
        then error' "'run' can't read commands from stdin, as one of the input files was stdin as well"
        -- watch is False: run never reloads changed files, in any of its modes
        -- (unlike repl). Its other modes don't, since they don't go through runREPL.
        else runREPL jpaths rungeneralopts addonfileargs findBuiltinCommand addons cmdaliases shellaliasesallowed mcollect Nothing Nothing False
    -- Otherwise the arguments are files to read commands from.
    | otherwise ->
        runFromFiles jpaths rungeneralopts addonfileargs findBuiltinCommand addons cmdaliases shellaliasesallowed mcollect args
  forM_ mcollect $ \IORef [(String, Maybe Text)]
ref -> do
    sections <- [(String, Maybe Text)] -> [(String, Maybe Text)]
forall a. [a] -> [a]
reverse ([(String, Maybe Text)] -> [(String, Maybe Text)])
-> IO [(String, Maybe Text)] -> IO [(String, Maybe Text)]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IORef [(String, Maybe Text)] -> IO [(String, Maybe Text)]
forall a. IORef a -> IO a
readIORef IORef [(String, Maybe Text)]
ref
    let tr = Translations -> Text -> Text
I18n.tr (ReportOpts -> Translations
translations_ (ReportOpts -> Translations) -> ReportOpts -> Translations
forall a b. (a -> b) -> a -> b
$ ReportSpec -> ReportOpts
_rsReportOpts (ReportSpec -> ReportOpts) -> ReportSpec -> ReportOpts
forall a b. (a -> b) -> a -> b
$ CliOpts -> ReportSpec
reportspec_ CliOpts
cliopts)
    writeOutputLazyText cliopts $ runPageHtml (tr "Show:", tr "Titles", tr "Charts", tr "All") sections

-- | The actual repl command. mconfinfo is the active config file and the raw options
-- needed to re-read it, used to auto-reload command aliases when the config file changes.
-- mrescanAddons is an action that re-scans PATH for addon commands, used to auto-reload the
-- addon command list when PATH's contents change.
repl :: (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())) -> [String] -> [(CommandAlias,CommandLine)] -> Bool -> Maybe (FilePath, RawOpts) -> Maybe (IO [String]) -> CliOpts -> IO ()
repl :: (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ()))
-> [String]
-> [(String, String)]
-> Bool
-> Maybe (String, RawOpts)
-> Maybe (IO [String])
-> CliOpts
-> IO ()
repl String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())
findBuiltinCommand [String]
addons [(String, String)]
cmdaliases Bool
shellaliasesallowed Maybe (String, RawOpts)
mconfinfo Maybe (IO [String])
mrescanAddons CliOpts
cliopts = do
  jpaths <- NonEmpty String -> DefaultRunJournal
DefaultRunJournal (NonEmpty String -> DefaultRunJournal)
-> IO (NonEmpty String) -> IO DefaultRunJournal
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe DefaultRunJournal -> CliOpts -> IO (NonEmpty String)
journalFilePathFromOptsOrDefault Maybe DefaultRunJournal
forall a. Maybe a
Nothing CliOpts
cliopts
  let watch = Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ String -> RawOpts -> Bool
boolopt String
"no-watch" (RawOpts -> Bool) -> RawOpts -> Bool
forall a b. (a -> b) -> a -> b
$ CliOpts -> RawOpts
rawopts_ CliOpts
cliopts  -- reload changed files/aliases/addons unless --no-watch
      addonfileargs = (String -> [String]) -> [String] -> [String]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (\String
f -> [String
"-f", String
f]) ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ CliOpts -> [String]
file_ CliOpts
cliopts  -- the session's explicit -f files, to pass through to addons
  runREPL jpaths (generalRawOpts $ rawopts_ cliopts) addonfileargs findBuiltinCommand addons cmdaliases shellaliasesallowed Nothing mconfinfo mrescanAddons watch

-- | Run commands from files given to "run".
runFromFiles :: DefaultRunJournal -> [(String,String)] -> [String] -> (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())) -> [String] -> [(CommandAlias,CommandLine)] -> Bool -> Maybe RunSections -> [String] -> IO ()
runFromFiles :: DefaultRunJournal
-> [(String, String)]
-> [String]
-> (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ()))
-> [String]
-> [(String, String)]
-> Bool
-> Maybe (IORef [(String, Maybe Text)])
-> [String]
-> IO ()
runFromFiles DefaultRunJournal
defaultJournalOverride [(String, String)]
rungeneralopts [String]
addonfileargs String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())
findBuiltinCommand [String]
addons [(String, String)]
cmdaliases Bool
shellaliasesallowed Maybe (IORef [(String, Maybe Text)])
mcollect [String]
inputfiles = do
  String -> [String] -> IO ()
forall (m :: * -> *) a. (MonadIO m, Show a) => String -> a -> m ()
dbg1IO String
"inputfiles" [String]
inputfiles
  -- read commands from all the inputfiles
  commands <- (((String -> IO [String]) -> [String] -> IO [String])
-> [String] -> (String -> IO [String]) -> IO [String]
forall a b c. (a -> b -> c) -> b -> a -> c
flip (String -> IO [String]) -> [String] -> IO [String]
forall (m :: * -> *) a b. Monad m => (a -> m [b]) -> [a] -> m [b]
concatMapM) [String]
inputfiles ((String -> IO [String]) -> IO [String])
-> (String -> IO [String]) -> IO [String]
forall a b. (a -> b) -> a -> b
$ \String
f -> do
    String -> String -> IO ()
forall (m :: * -> *) a. (MonadIO m, Show a) => String -> a -> m ()
dbg1IO String
"reading commands" String
f
    String -> [String]
lines (String -> [String]) -> (Text -> String) -> Text -> [String]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> String
T.unpack (Text -> [String]) -> IO Text -> IO [String]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> String -> IO Text
T.readFile String
f

  forM_ commands (runCommand defaultJournalOverride rungeneralopts addonfileargs findBuiltinCommand addons cmdaliases shellaliasesallowed mcollect . parseCommand)

-- | Run commands from command line arguments given to "run".
runFromArgs :: DefaultRunJournal -> [(String,String)] -> [String] -> (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())) -> [String] -> [(CommandAlias,CommandLine)] -> Bool -> Maybe RunSections -> [String] -> IO ()
runFromArgs :: DefaultRunJournal
-> [(String, String)]
-> [String]
-> (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ()))
-> [String]
-> [(String, String)]
-> Bool
-> Maybe (IORef [(String, Maybe Text)])
-> [String]
-> IO ()
runFromArgs DefaultRunJournal
defaultJournalOverride [(String, String)]
rungeneralopts [String]
addonfileargs String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())
findBuiltinCommand [String]
addons [(String, String)]
cmdaliases Bool
shellaliasesallowed Maybe (IORef [(String, Maybe Text)])
mcollect [String]
args = do
  -- read commands from all the inputfiles
  let commands :: [[String]]
commands = String -> [[String]] -> [[String]]
forall a. Show a => String -> a -> a
dbg1 String
"commands from args" ([[String]] -> [[String]]) -> [[String]] -> [[String]]
forall a b. (a -> b) -> a -> b
$ String -> [String] -> [[String]]
forall a. Eq a => a -> [a] -> [[a]]
splitAtElement String
"--" [String]
args
  [[String]] -> ([String] -> IO ()) -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ [[String]]
commands (DefaultRunJournal
-> [(String, String)]
-> [String]
-> (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ()))
-> [String]
-> [(String, String)]
-> Bool
-> Maybe (IORef [(String, Maybe Text)])
-> [String]
-> IO ()
runCommand DefaultRunJournal
defaultJournalOverride [(String, String)]
rungeneralopts [String]
addonfileargs String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())
findBuiltinCommand [String]
addons [(String, String)]
cmdaliases Bool
shellaliasesallowed Maybe (IORef [(String, Maybe Text)])
mcollect)

-- When commands are passed on the command line, shell will parse them for us
-- When commands are read from file, we need to split the line into command and arguments
parseCommand :: String -> [String]
parseCommand :: String -> [String]
parseCommand String
line =
  case String -> Either String [String]
wordsEither String
line' of
    -- # begins a comment, ignore everything after #
    Right [String]
ws -> (String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
takeWhile (Bool -> Bool
not(Bool -> Bool) -> (String -> Bool) -> String -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((Char -> Maybe Char
forall a. a -> Maybe a
Just Char
'#')Maybe Char -> Maybe Char -> Bool
forall a. Eq a => a -> a -> Bool
==) (Maybe Char -> Bool) -> (String -> Maybe Char) -> String -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Maybe Char
forall a. [a] -> Maybe a
headMay) [String]
ws
    Left String
err -> String -> [String]
forall a. String -> a
error' (String -> [String]) -> String -> [String]
forall a b. (a -> b) -> a -> b
$ String
"could not parse this command line:\n" String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
err
  where line' :: String
line' = String -> String
strip String
line

-- | Interpret the common backslash escape sequences \n, \t, \r and \\ in a string,
-- so the run/repl echo command can print newlines, tabs etc. An unrecognised escape
-- is left as written (its backslash is kept).
unescape :: String -> String
unescape :: String -> String
unescape (Char
'\\':Char
c:String
cs) = case Char
c of
  Char
'n'  -> Char
'\n' Char -> String -> String
forall a. a -> [a] -> [a]
: String -> String
unescape String
cs
  Char
't'  -> Char
'\t' Char -> String -> String
forall a. a -> [a] -> [a]
: String -> String
unescape String
cs
  Char
'r'  -> Char
'\r' Char -> String -> String
forall a. a -> [a] -> [a]
: String -> String
unescape String
cs
  Char
'\\' -> Char
'\\' Char -> String -> String
forall a. a -> [a] -> [a]
: String -> String
unescape String
cs
  Char
_    -> Char
'\\' Char -> String -> String
forall a. a -> [a] -> [a]
: Char
c Char -> String -> String
forall a. a -> [a] -> [a]
: String -> String
unescape String
cs
unescape (Char
c:String
cs)      = Char
c Char -> String -> String
forall a. a -> [a] -> [a]
: String -> String
unescape String
cs
unescape []          = []

-- | Run an action that writes a file, with a temporary part file in hledger's cache directory
-- (created readable only by the user, and deleted afterwards), and return what it wrote.
withPartFile :: (FilePath -> IO ()) -> IO TL.Text
withPartFile :: (String -> IO ()) -> IO Text
withPartFile String -> IO ()
act = do
  d <- XdgDirectory -> String -> IO String
getXdgDirectory XdgDirectory
XdgCache String
"hledger"
  createDirectoryIfMissing True d
  (part, h) <- openTempFile d "part"
  hClose h
  (act part >> TL.fromStrict <$> T.readFile part) `finally` removeFile part

-- | An html page showing run's collected sections: a heading for each echo,
-- and for each command, its command line and its output (html as is, text preformatted),
-- in a collapsible section (open). Each section's SVG ids get a suffix, so that charts
-- don't share eg a hatch pattern (which browsers won't draw from a hidden chart).
-- Links at the top, with the given labels, show more or less detail: just the sections' titles (all folded),
-- the charts (the sections open, as at first), or all (with the report details shown too).
runPageHtml :: (T.Text, T.Text, T.Text, T.Text) -> [(String, Maybe TL.Text)] -> TL.Text
runPageHtml :: (Text, Text, Text, Text) -> [(String, Maybe Text)] -> Text
runPageHtml (Text
showlabel, Text
titleslabel, Text
chartslabel, Text
alllabel) [(String, Maybe Text)]
sections = Html -> Text
htmlAsLazyText (Html -> Text) -> Html -> Text
forall a b. (a -> b) -> a -> b
$ do
  Html
H.docType
  Html -> Html
H.html (Html -> Html) -> Attribute -> Html -> Html
forall h. Attributable h => h -> Attribute -> h
! AttributeValue -> Attribute
A.lang AttributeValue
"en" (Html -> Html) -> Html -> Html
forall a b. (a -> b) -> a -> b
$ do
    Html
H.meta Html -> Attribute -> Html
forall h. Attributable h => h -> Attribute -> h
! AttributeValue -> Attribute
A.charset AttributeValue
"utf-8"
    Html
H.meta Html -> Attribute -> Html
forall h. Attributable h => h -> Attribute -> h
! AttributeValue -> Attribute
A.name AttributeValue
"viewport" Html -> Attribute -> Html
forall h. Attributable h => h -> Attribute -> h
! AttributeValue -> Attribute
A.content AttributeValue
"width=device-width,initial-scale=1"
    Html
nl
    Html -> Html
H.title Html
"hledger run"
    Html
nl
    Html -> Html
H.style (Html -> Html) -> Html -> Html
forall a b. (a -> b) -> a -> b
$ Text -> Html
H.preEscapedText (Text -> Html) -> Text -> Html
forall a b. (a -> b) -> a -> b
$ [Text] -> Text
T.unlines ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ Text
"" Text -> [Text] -> [Text]
forall a. a -> [a] -> [a]
:
      [ Text
"body{margin:0 auto;max-width:980px;padding:24px 16px 48px;background:#f3f2ee;color:#0b0b0b;font:15px/1.5 system-ui,-apple-system,\"Segoe UI\",sans-serif}"
      , Text
"h2{margin:24px 0 8px;font-size:18px;font-weight:650}"
      , Text
".hledger-run-show{margin:0 0 8px;text-align:right;font-size:13px;color:#898781}"
      , Text
".hledger-run-show a{margin-left:10px;color:#52514e}.hledger-run-show a.current{color:#0b0b0b;font-weight:600;text-decoration:none}"
      , Text
"details.hledger-run{margin:0 0 8px;background:#fcfcfb;border:1px solid #e1e0d9;border-radius:8px}"
      , Text
"details.hledger-run>summary{padding:10px 14px;cursor:pointer;color:#52514e;font:13px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}"
      , Text
"details.hledger-run>div{padding:8px 14px 14px;border-top:1px solid #e1e0d9;overflow-x:auto}"
      , Text
"details.hledger-run table{font-size:13px;font-variant-numeric:tabular-nums}"
      , Text
"details.hledger-run svg{max-width:100%;height:auto}"
      ]
    Html
nl
    Html -> Html
H.p (Html -> Html) -> Attribute -> Html -> Html
forall h. Attributable h => h -> Attribute -> h
! AttributeValue -> Attribute
A.class_ AttributeValue
"hledger-run-show" (Html -> Html) -> Html -> Html
forall a b. (a -> b) -> a -> b
$ do
      Text -> Html
forall a. ToMarkup a => a -> Html
H.toHtml Text
showlabel
      [(Int, Text)] -> ((Int, Text) -> Html) -> Html
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ ([Int] -> [Text] -> [(Int, Text)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 :: Int ..] [Text
titleslabel, Text
chartslabel, Text
alllabel]) (((Int, Text) -> Html) -> Html) -> ((Int, Text) -> Html) -> Html
forall a b. (a -> b) -> a -> b
$ \(Int
n, Text
l) ->
        Html -> Html
H.a (Html -> Html) -> Attribute -> Html -> Html
forall h. Attributable h => h -> Attribute -> h
! AttributeValue -> Attribute
A.href AttributeValue
"#" (Html -> Html) -> Attribute -> Html -> Html
forall h. Attributable h => h -> Attribute -> h
! Tag -> AttributeValue -> Attribute
H.dataAttribute Tag
"level" (Int -> AttributeValue
forall a. ToValue a => a -> AttributeValue
H.toValue Int
n) (Html -> Html) -> (Bool, Attribute) -> Html -> Html
forall h. Attributable h => h -> (Bool, Attribute) -> h
!? (Int
n Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
1, AttributeValue -> Attribute
A.class_ AttributeValue
"current") (Html -> Html) -> Html -> Html
forall a b. (a -> b) -> a -> b
$ Text -> Html
forall a. ToMarkup a => a -> Html
H.toHtml Text
l
    Html
nl
    -- level 0: sections folded; 1: sections open (as at first); 2: report details open too.
    -- Report details are closed first, and the page laid out (by reading its height) before the sections are toggled
    -- (otherwise Safari leaves the space of report details closed along with their section, when it is reopened).
    Html -> Html
H.script (Html -> Html) -> Html -> Html
forall a b. (a -> b) -> a -> b
$ Text -> Html
H.preEscapedText (Text -> Html) -> Text -> Html
forall a b. (a -> b) -> a -> b
$ [Text] -> Text
T.concat
      [ Text
"document.querySelectorAll('.hledger-run-show a').forEach(a => a.onclick = e => { e.preventDefault();"
      , Text
" const level = +a.dataset.level, details = document.querySelectorAll('details.hledger-details');"
      , Text
" if (level < 2) details.forEach(d => d.open = false);"
      , Text
" void document.body.offsetHeight;"
      , Text
" document.querySelectorAll('details.hledger-run').forEach(d => d.open = level > 0);"
      , Text
" if (level > 1) details.forEach(d => d.open = true);"
      , Text
" document.querySelectorAll('.hledger-run-show a').forEach(b => b.classList.toggle('current', b === a)); });"
      ]
    Html
nl
    (Int -> (String, Maybe Text) -> Html)
-> [Int] -> [(String, Maybe Text)] -> Html
forall (m :: * -> *) a b c.
Applicative m =>
(a -> b -> m c) -> [a] -> [b] -> m ()
zipWithM_ Int -> (String, Maybe Text) -> Html
forall {p}. Show p => p -> (String, Maybe Text) -> Html
section [Int
1 :: Int ..] [(String, Maybe Text)]
sections
  Html
nl
  where
    section :: p -> (String, Maybe Text) -> Html
section p
_ (String
heading, Maybe Text
Nothing) = Html -> Html
H.h2 (String -> Html
forall a. ToMarkup a => a -> Html
H.toHtml String
heading) Html -> Html -> Html
forall a b. MarkupM a -> MarkupM b -> MarkupM b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Html
nl
    section p
n (String
cmd, Just Text
out) = do
      Html -> Html
H.details (Html -> Html) -> Attribute -> Html -> Html
forall h. Attributable h => h -> Attribute -> h
! AttributeValue -> Attribute
A.class_ AttributeValue
"hledger-run" (Html -> Html) -> Attribute -> Html -> Html
forall h. Attributable h => h -> Attribute -> h
! AttributeValue -> Attribute
A.open AttributeValue
"" (Html -> Html) -> Html -> Html
forall a b. (a -> b) -> a -> b
$ do
        Html -> Html
H.summary (Html -> Html) -> Html -> Html
forall a b. (a -> b) -> a -> b
$ String -> Html
forall a. ToMarkup a => a -> Html
H.toHtml (String
"hledger " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
cmd)
        Html -> Html
H.div (Html -> Html) -> Html -> Html
forall a b. (a -> b) -> a -> b
$ do
          Html
nl
          if | Text -> Bool
TL.null (Text -> Text
TL.strip Text
out) -> Html -> Html
H.p Html
"(no output)"
             | Text
"<" Text -> Text -> Bool
`TL.isPrefixOf` Text -> Text
TL.stripStart Text
out -> Text -> Html
H.preEscapedLazyText (Text -> Html) -> Text -> Html
forall a b. (a -> b) -> a -> b
$ Text -> Text
uniqueIds Text
out
             | Bool
otherwise -> Html -> Html
H.pre (Html -> Html) -> Html -> Html
forall a b. (a -> b) -> a -> b
$ Text -> Html
H.lazyText Text
out
          Html
nl
      Html
nl
      where
        uniqueIds :: Text -> Text
uniqueIds = HasCallStack => Text -> Text -> Text -> Text
Text -> Text -> Text -> Text
TL.replace Text
"hledger-chart-hatch" (Text
"hledger-chart-hatch-" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
suffix) (Text -> Text) -> (Text -> Text) -> Text -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. HasCallStack => Text -> Text -> Text -> Text
Text -> Text -> Text -> Text
TL.replace Text
"hledger-chart-clip-" (Text
"hledger-chart-clip-" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
suffix Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"-")
        suffix :: Text
suffix = String -> Text
TL.pack (p -> String
forall a. Show a => a -> String
show p
n)

-- | Run a shell command, and if it fails, exit with its exit code; on success just return,
-- so a sequence of run/repl commands can continue. Flushes stdout first, so that our own
-- buffered output (eg echo's) appears before the subprocess's output.
runShellCommandOrExit :: String -> IO ()
runShellCommandOrExit :: String -> IO ()
runShellCommandOrExit String
shcmd = do
  Handle -> IO ()
hFlush Handle
stdout
  ec <- String -> IO ExitCode
system String
shcmd
  when (ec /= ExitSuccess) $ exitWith ec

-- | The sections of an html page being collected by run: for each command, its command line and its output
-- (or for an echo, just its text), most recent first.
type RunSections = IORef [(String, Maybe TL.Text)]

-- | Take a single command line (from file, or REPL, or "--"-surrounded block of the args), and run it.
-- addonfileargs are -f options (the session's explicit input files) to pass through to addon commands.
-- With mcollect, a builtin command's output is collected as a section of an html page instead of being printed
-- (and so is an echo's text, as a heading).
runCommand :: DefaultRunJournal -> [(String,String)] -> [String] -> (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())) -> [String] -> [(CommandAlias,CommandLine)] -> Bool -> Maybe RunSections -> [String] -> IO ()
runCommand :: DefaultRunJournal
-> [(String, String)]
-> [String]
-> (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ()))
-> [String]
-> [(String, String)]
-> Bool
-> Maybe (IORef [(String, Maybe Text)])
-> [String]
-> IO ()
runCommand DefaultRunJournal
defaultJournalOverride [(String, String)]
rungeneralopts [String]
addonfileargs String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())
findBuiltinCommand [String]
addons [(String, String)]
cmdaliases Bool
shellaliasesallowed Maybe (IORef [(String, Maybe Text)])
mcollect [String]
cmdline = do
  String -> [String] -> IO ()
forall (m :: * -> *) a. (MonadIO m, Show a) => String -> a -> m ()
dbg1IO String
"runCommand for" [String]
cmdline
  case [String]
cmdline of
    String
"echo":[String]
args | Just IORef [(String, Maybe Text)]
ref <- Maybe (IORef [(String, Maybe Text)])
mcollect -> IORef [(String, Maybe Text)]
-> ([(String, Maybe Text)] -> [(String, Maybe Text)]) -> IO ()
forall a. IORef a -> (a -> a) -> IO ()
modifyIORef IORef [(String, Maybe Text)]
ref ((String -> String
unescape (String -> String) -> String -> String
forall a b. (a -> b) -> a -> b
$ [String] -> String
unwords [String]
args, Maybe Text
forall a. Maybe a
Nothing) (String, Maybe Text)
-> [(String, Maybe Text)] -> [(String, Maybe Text)]
forall a. a -> [a] -> [a]
:)
                | Bool
otherwise -> String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String -> String
unescape (String -> String) -> String -> String
forall a b. (a -> b) -> a -> b
$ [String] -> String
unwords [String]
args
    String
cmdname0:[String]
args0 ->
      -- The command may be a command alias defined in the config file; expand it.
      case (String -> Bool) -> [(String, String)] -> String -> ResolvedCommand
expandCommandAlias (Maybe (Mode RawOpts, CliOpts -> Journal -> IO ()) -> Bool
forall a. Maybe a -> Bool
isJust (Maybe (Mode RawOpts, CliOpts -> Journal -> IO ()) -> Bool)
-> (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ()))
-> String
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())
findBuiltinCommand) [(String, String)]
cmdaliases String
cmdname0 of
       -- A !-prefixed shell command alias: run it (if allowed), with any arguments appended.
       ShellCommand String
shcmd
         | Bool
shellaliasesallowed -> String -> IO ()
runShellCommandOrExit ([String] -> String
unwords ([String] -> String) -> [String] -> String
forall a b. (a -> b) -> a -> b
$ String
shcmd String -> [String] -> [String]
forall a. a -> [a] -> [a]
: (String -> String) -> [String] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map String -> String
quoteForCommandLine [String]
args0)
         | Bool
otherwise -> String -> IO ()
forall a. String -> a
error' (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String
"the command alias '" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
cmdname0
             String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"' runs a shell command, which is only allowed from your user config file or a --conf file"
       -- Otherwise an hledger command, with the alias's arguments preceding this line's own arguments.
       HledgerCommand String
cmdname [String]
defargs ->
        let
          -- Mark run's inline commands (see argsMarkRunCommands), after alias expansion, so it
          -- works whether "run ... -- ..." was typed directly or reached via a command alias
          -- (or a nested run in a commands file).
          args :: [String]
args = (if String
cmdname String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
"run" then [String] -> [String]
argsMarkRunCommands else [String] -> [String]
forall a. a -> a
id) ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ [String]
defargs [String] -> [String] -> [String]
forall a. Semigroup a => a -> a -> a
<> [String]
args0
          aliasnote :: String
aliasnote = if String
cmdname String -> String -> Bool
forall a. Eq a => a -> a -> Bool
/= String
cmdname0 then String
" (expanded from the " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
cmdname0 String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" command alias)" else String
""
        in
        case String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())
findBuiltinCommand String
cmdname of
        Just (Mode RawOpts
cmdmode,CliOpts -> Journal -> IO ()
cmdaction) -> do
              -- Even though expandArgsAt is done by the Cli.hs, it stops at the first '--', so we need
              -- to do it here as well to make sure that each command can use @ARGFILEs
              args' <- [String] -> [String]
replaceNumericFlags ([String] -> [String]) -> IO [String] -> IO [String]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [String] -> IO [String]
expandArgsAt [String]
args
              dbg1IO "runCommand final args" (cmdname,args')
              -- Propagate run/repl's general flags to this command, letting its own flags take precedence
              opts0 <- insertRawOpts rungeneralopts =<< getHledgerCliOpts' cmdmode args'
              -- When collecting an html page, write this command's output to a part file, as html if it can produce that
              -- (otherwise its usual text, shown preformatted), and add it to the page.
              let
                collect CliOpts -> IO ()
act = case Maybe (IORef [(String, Maybe Text)])
mcollect of
                  Maybe (IORef [(String, Maybe Text)])
Nothing  -> CliOpts -> IO ()
act CliOpts
opts0
                  Just IORef [(String, Maybe Text)]
ref -> do
                    out <- (String -> IO ()) -> IO Text
withPartFile ((String -> IO ()) -> IO Text) -> (String -> IO ()) -> IO Text
forall a b. (a -> b) -> a -> b
$ \String
part -> CliOpts -> IO ()
act CliOpts
opts0{output_file_ = Just part, output_format_ = if supportsHtml then Just "html" else Nothing}
                    modifyIORef ref ((unwords $ map quoteForCommandLine cmdline, Just out) :)
                supportsHtml = (Flag RawOpts -> Bool) -> [Flag RawOpts] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\Flag RawOpts
f -> String
"output-format" String -> [String] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` Flag RawOpts -> [String]
forall a. Flag a -> [String]
flagNames Flag RawOpts
f Bool -> Bool -> Bool
&& String
"html" String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isInfixOf` Flag RawOpts -> String
forall a. Flag a -> String
flagHelp Flag RawOpts
f) ([Flag RawOpts] -> Bool) -> [Flag RawOpts] -> Bool
forall a b. (a -> b) -> a -> b
$ Mode RawOpts -> [Flag RawOpts]
forall a. Mode a -> [Flag a]
modeFlags Mode RawOpts
cmdmode
                opts = CliOpts
opts0
              let
                rawopts      = CliOpts -> RawOpts
rawopts_ CliOpts
opts
                mmodecmdname = [String] -> Maybe String
forall a. [a] -> Maybe a
headMay ([String] -> Maybe String) -> [String] -> Maybe String
forall a b. (a -> b) -> a -> b
$ Mode RawOpts -> [String]
forall a. Mode a -> [String]
modeNames Mode RawOpts
cmdmode
                helpFlag     = String -> RawOpts -> Bool
boolopt String
"help"     RawOpts
rawopts
                examplesFlag = String -> RawOpts -> Bool
boolopt String
"examples" RawOpts
rawopts
                infoFlag     = String -> RawOpts -> Bool
boolopt String
"info"     RawOpts
rawopts
                manFlag      = String -> RawOpts -> Bool
boolopt String
"man"      RawOpts
rawopts
              if
                | helpFlag     -> runPager $ showModeUsage cmdmode ++ "\n"
                | examplesFlag -> runTldrForPage $ maybe "hledger" (("hledger-"<>)) mmodecmdname
                | infoFlag  -> runInfoForTopic "hledger" mmodecmdname
                | manFlag   -> runManForTopic "hledger"  mmodecmdname
                | cmdname `elem` journalIgnoringCommandNames ->
                  -- help/setup never read the journal, as at the CLI
                  cmdaction opts nulljournal
                | cmdname `elem` journalCreatingCommandNames ->
                  -- add and import can create a nonexistent journal file, as they do at the CLI
                  withPossibleRunJournal defaultJournalOverride opts (cmdaction opts)
                | otherwise -> do
                  withJournalCached (Just defaultJournalOverride) opts $ \(Journal
j,DefaultRunJournal
jpaths) -> do
                    if String
cmdname String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
"run" -- allow "run" to call "run"
                      then Maybe DefaultRunJournal
-> (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ()))
-> [String]
-> [(String, String)]
-> Bool
-> CliOpts
-> IO ()
run (DefaultRunJournal -> Maybe DefaultRunJournal
forall a. a -> Maybe a
Just DefaultRunJournal
jpaths) String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())
findBuiltinCommand [String]
addons [(String, String)]
cmdaliases Bool
shellaliasesallowed CliOpts
opts
                      else (CliOpts -> IO ()) -> IO ()
collect ((CliOpts -> IO ()) -> IO ()) -> (CliOpts -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \CliOpts
o -> CliOpts -> Journal -> IO ()
cmdaction CliOpts
o Journal
j
        Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())
Nothing | 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]
addons ->
          -- Pass the session's explicit input files to the addon, so it uses the same journal
          -- (as the CLI does by forwarding its -f options to addons).
          String -> IO ()
runShellCommandOrExit (String -> String -> String -> String -> String
forall r. PrintfType r => String -> r
printf String
"%s-%s %s" String
progname String
cmdname ([String] -> String
unwords ([String] -> String) -> [String] -> String
forall a b. (a -> b) -> a -> b
$ (String -> String) -> [String] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map String -> String
quoteForCommandLine ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ [String]
addonfileargs [String] -> [String] -> [String]
forall a. Semigroup a => a -> a -> a
<> [String]
args))
        Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())
Nothing ->
          String -> IO ()
forall a. String -> a
error' (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String
"Unrecognized command" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
aliasnote String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
": " String -> String -> String
forall a. [a] -> [a] -> [a]
++ [String] -> String
unwords (String
cmdnameString -> [String] -> [String]
forall a. a -> [a] -> [a]
:[String]
args)
    [] -> () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()

-- | Run an interactive REPL. mconfinfo is the active config file and the raw options
-- needed to re-read it, used to auto-reload command aliases when the config file changes.
-- mrescanAddons is an action that re-scans PATH for addon commands, used to auto-reload the
-- addon command list when PATH's contents change. Either being Nothing disables that reload
-- (eg for a non-interactive "run").
-- watch enables the automatic reloading of changed files/aliases/addons (disabled by --no-watch).
runREPL :: DefaultRunJournal -> [(String,String)] -> [String] -> (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())) -> [String] -> [(CommandAlias,CommandLine)] -> Bool -> Maybe RunSections -> Maybe (FilePath, RawOpts) -> Maybe (IO [String]) -> Bool -> IO ()
runREPL :: DefaultRunJournal
-> [(String, String)]
-> [String]
-> (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ()))
-> [String]
-> [(String, String)]
-> Bool
-> Maybe (IORef [(String, Maybe Text)])
-> Maybe (String, RawOpts)
-> Maybe (IO [String])
-> Bool
-> IO ()
runREPL defaultJournalOverride :: DefaultRunJournal
defaultJournalOverride@(DefaultRunJournal NonEmpty String
jpaths) [(String, String)]
rungeneralopts [String]
addonfileargs String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())
findBuiltinCommand [String]
addons [(String, String)]
cmdaliases Bool
shellaliasesallowed Maybe (IORef [(String, Maybe Text)])
mcollect Maybe (String, RawOpts)
mconfinfo Maybe (IO [String])
mrescanAddons Bool
watch = do
  isTerminal <- IO Bool
isStdinTerminal
  -- Mutable alias and addon state, so these can be reloaded when their sources change on disk.
  confmtime0 <- maybe (return 0) (fmap (fromMaybe 0) . maybeFileModificationTime . fst) mconfinfo
  aliasesRef <- newIORef (confmtime0, cmdaliases)
  pathmtime0 <- maybe (return 0) (const maxSearchPathMtime) mrescanAddons
  addonsRef  <- newIORef (pathmtime0, addons)
  if not isTerminal
    then runInputT defaultSettings (loop aliasesRef addonsRef False "")
    else do
      -- Show a startup banner: the program name and version and a usage hint,
      -- coloured with a gradient like the commands list when supported.
      -- w <- fromMaybe 80 <$> getTerminalWidth
      -- The interactive prompt is coloured only in terminals that fully emulate one.
      -- Emacs's M-x shell (comint) advertises xterm but mishandles the cursor movement
      -- haskeline uses to redraw a prompt containing escape codes, garbling the display;
      -- there we use a plain prompt (the banner above is fine, being plain putStrLn output).
      emacs <- insideEmacsNotVterm
      let
        grad String -> String
intensity Int
row String
s = (String -> String) -> Int -> Int -> Int -> Int -> String -> String
gradientStr String -> String
intensity Int
2 (String -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length String
s) Int
row Int
0 String
s
        fpath = (Maybe StorageFormat, String) -> String
forall a b. (a, b) -> b
snd ((Maybe StorageFormat, String) -> String)
-> (Maybe StorageFormat, String) -> String
forall a b. (a -> b) -> a -> b
$ String -> (Maybe StorageFormat, String)
splitReaderPrefix (String -> (Maybe StorageFormat, String))
-> String -> (Maybe StorageFormat, String)
forall a b. (a -> b) -> a -> b
$ NonEmpty String -> String
forall a. NonEmpty a -> a
NE.head NonEmpty String
jpaths
                  --------------------------------------80----------------------------------------
        title  =  String
progname String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
packageversion
        hint   = String
"Ready for hledger or !shell commands. For help: h or h -h. To exit: q or ctrl-d."
        promptbase = String -> String
takeBaseName String
fpath String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"> "
        prompt = if Bool
emacs then String
promptbase else String -> String
stxMarkEscapes (String -> String) -> String -> String
forall a b. (a -> b) -> a -> b
$ (String -> String) -> Int -> String -> String
grad String -> String
faint' Int
2 String
promptbase
      -- putStrLn $ grad faint' 0 $ replicate w '-'
      putStrLn $ grad bold' 1 title
      putStrLn $ faint' hint
      -- Then run the REPL loop.
      runInputT defaultSettings (loop aliasesRef addonsRef True prompt)

  where
  loop :: IORef (POSIXTime,[(CommandAlias,CommandLine)]) -> IORef (POSIXTime,[String]) -> Bool -> String -> InputT IO ()
  loop :: IORef (POSIXTime, [(String, String)])
-> IORef (POSIXTime, [String]) -> Bool -> String -> InputT IO ()
loop IORef (POSIXTime, [(String, String)])
aliasesRef IORef (POSIXTime, [String])
addonsRef Bool
interactive String
prompt = do
    minput <- String -> InputT IO (Maybe String)
forall (m :: * -> *).
(MonadIO m, MonadMask m) =>
String -> InputT m (Maybe String)
getInputLine String
prompt
    case minput of
      Maybe String
Nothing -> () -> InputT IO ()
forall a. a -> InputT IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
      Just String
"q" -> () -> InputT IO ()
forall a. a -> InputT IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
      Just String
"quit" -> () -> InputT IO ()
forall a. a -> InputT IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
      Just String
"exit" -> () -> InputT IO ()
forall a. a -> InputT IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
      Just String
input -> do
        -- Reload any changed input files, config aliases or addon commands, then run the command.
        -- All are guarded by the handlers below (interactively), so a control-C during any of them
        -- returns to the prompt rather than exiting the REPL.
        let action :: IO ()
action = do
              Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
watch (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
                IO ()
refreshStaleJournals
                Maybe (String, RawOpts)
-> IORef (POSIXTime, [(String, String)]) -> IO ()
refreshStaleAliases Maybe (String, RawOpts)
mconfinfo IORef (POSIXTime, [(String, String)])
aliasesRef
                Maybe (IO [String]) -> IORef (POSIXTime, [String]) -> IO ()
refreshStaleAddons Maybe (IO [String])
mrescanAddons IORef (POSIXTime, [String])
addonsRef
              (_, cmdaliases') <- IORef (POSIXTime, [(String, String)])
-> IO (POSIXTime, [(String, String)])
forall a. IORef a -> IO a
readIORef IORef (POSIXTime, [(String, String)])
aliasesRef
              (_, addons')     <- readIORef addonsRef
              case strip input of
                String
"!"       -> () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()           -- a bare !, do nothing
                Char
'!':String
shcmd -> Handle -> IO ()
hFlush Handle
stdout IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> IO ExitCode -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (String -> IO ExitCode
system String
shcmd)  -- !SHELLCMD, run the rest as a shell command
                -- h is a short alias for the help command.
                String
_         -> DefaultRunJournal
-> [(String, String)]
-> [String]
-> (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ()))
-> [String]
-> [(String, String)]
-> Bool
-> Maybe (IORef [(String, Maybe Text)])
-> [String]
-> IO ()
runCommand DefaultRunJournal
defaultJournalOverride [(String, String)]
rungeneralopts [String]
addonfileargs String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())
findBuiltinCommand [String]
addons' [(String, String)]
cmdaliases' Bool
shellaliasesallowed Maybe (IORef [(String, Maybe Text)])
mcollect ([String] -> IO ()) -> [String] -> IO ()
forall a b. (a -> b) -> a -> b
$
                             case String -> [String]
parseCommand String
input of
                               String
"h":[String]
rest -> String
"help"String -> [String] -> [String]
forall a. a -> [a] -> [a]
:[String]
rest
                               [String]
cmd      -> [String]
cmd
        IO () -> InputT IO ()
forall a. IO a -> InputT IO a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT IO ()) -> IO () -> InputT IO ()
forall a b. (a -> b) -> a -> b
$ if Bool
interactive
          then IO ()
action IO () -> [Handler ()] -> IO ()
forall a. IO a -> [Handler a] -> IO a
`catches`
                  [(ErrorCall -> IO ()) -> Handler ()
forall a e. Exception e => (e -> IO a) -> Handler a
Handler (\(ErrorCall
e::ErrorCall) -> String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String -> String
rstrip (String -> String) -> String -> String
forall a b. (a -> b) -> a -> b
$ ErrorCall -> String
forall a. Show a => a -> String
show ErrorCall
e)
                  ,(IOError -> IO ()) -> Handler ()
forall a e. Exception e => (e -> IO a) -> Handler a
Handler (\(IOError
e::IOError)   -> String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String -> String
rstrip (String -> String) -> String -> String
forall a b. (a -> b) -> a -> b
$ IOError -> String
forall a. Show a => a -> String
show IOError
e)
                  ,(ExitCode -> IO ()) -> Handler ()
forall a e. Exception e => (e -> IO a) -> Handler a
Handler (\(ExitCode
_::ExitCode)  -> () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ())
                  ,(AsyncException -> IO ()) -> Handler ()
forall a e. Exception e => (e -> IO a) -> Handler a
Handler (\AsyncException
UserInterrupt  -> Handle -> String -> IO ()
hPutStrLn Handle
stderr String
"(interrupted)")
                  ]
          else IO ()
action
        IORef (POSIXTime, [(String, String)])
-> IORef (POSIXTime, [String]) -> Bool -> String -> InputT IO ()
loop IORef (POSIXTime, [(String, String)])
aliasesRef IORef (POSIXTime, [String])
addonsRef Bool
interactive String
prompt

isStdinTerminal :: IO Bool
isStdinTerminal = do
  op <- Handle -> IO Bool
hIsOpen Handle
stdin
  if op then hIsTerminalDevice stdin else return False

-- | Mark any ANSI escape sequences (eg SGR colour/style codes) in a string as zero-width
-- for haskeline, by appending a \STX character to each. Haskeline treats text between
-- \ESC and \STX as zero-width; without this, escape codes in the prompt make it
-- miscalculate the prompt's width, garbling the display.
stxMarkEscapes :: String -> String
stxMarkEscapes :: String -> String
stxMarkEscapes (Char
'\ESC':String
cs) =
  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
'm') String
cs of  -- SGR escape sequences end with 'm'
    (String
code, Char
'm':String
rest) -> Char
'\ESC' Char -> String -> String
forall a. a -> [a] -> [a]
: String
code String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"m\STX" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String -> String
stxMarkEscapes String
rest
    (String, String)
_                -> Char
'\ESC' Char -> String -> String
forall a. a -> [a] -> [a]
: String
cs  -- unterminated escape sequence, leave as is
stxMarkEscapes (Char
c:String
cs) = Char
c Char -> String -> String
forall a. a -> [a] -> [a]
: String -> String
stxMarkEscapes String
cs
stxMarkEscapes String
""     = String
""

-- | Cache of all journals that have been read by commands given to "run",
-- keyed by the fully-expanded filename.
journalCache :: MVar (Map.Map (InputOpts,PrefixedFilePath) Journal)
journalCache :: MVar (Map (InputOpts, String) Journal)
journalCache = IO (MVar (Map (InputOpts, String) Journal))
-> MVar (Map (InputOpts, String) Journal)
forall a. IO a -> a
unsafePerformIO (IO (MVar (Map (InputOpts, String) Journal))
 -> MVar (Map (InputOpts, String) Journal))
-> IO (MVar (Map (InputOpts, String) Journal))
-> MVar (Map (InputOpts, String) Journal)
forall a b. (a -> b) -> a -> b
$ Map (InputOpts, String) Journal
-> IO (MVar (Map (InputOpts, String) Journal))
forall a. a -> IO (MVar a)
newMVar Map (InputOpts, String) Journal
forall k a. Map k a
Map.empty
{-# NOINLINE journalCache #-}

-- | Cache of stdin contents, so that we can re-read it if InputOptions change
stdinCache :: MVar (Maybe T.Text)
stdinCache :: MVar (Maybe Text)
stdinCache = IO (MVar (Maybe Text)) -> MVar (Maybe Text)
forall a. IO a -> a
unsafePerformIO (IO (MVar (Maybe Text)) -> MVar (Maybe Text))
-> IO (MVar (Maybe Text)) -> MVar (Maybe Text)
forall a b. (a -> b) -> a -> b
$ Maybe Text -> IO (MVar (Maybe Text))
forall a. a -> IO (MVar a)
newMVar Maybe Text
forall a. Maybe a
Nothing
{-# NOINLINE stdinCache #-}

-- | A changed file F is being reloaded: print a "(reloading F)" notice, read the new value
-- with the given action (catching synchronous errors so an async exception such as a control-C
-- still propagates), then either apply it with onSuccess, or on failure print
-- "could not reload F, keeping previous THING" and run onKeepPrevious. Shared by the journal-data
-- and config-alias reloads to keep their notices and error handling identical.
reloadChanged :: FilePath -> String -> IO (Either String a) -> (a -> IO ()) -> IO () -> IO ()
reloadChanged :: forall a.
String
-> String -> IO (Either String a) -> (a -> IO ()) -> IO () -> IO ()
reloadChanged String
fp String
thing IO (Either String a)
readNew a -> IO ()
onSuccess IO ()
onKeepPrevious = do
  Handle -> String -> IO ()
hPutStrLn Handle
stderr (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String
"(reloading " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
fp String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
")"
  Handle -> IO ()
hFlush Handle
stderr
  enew <- IO (Either String a)
readNew IO (Either String a)
-> [Handler (Either String a)] -> IO (Either String a)
forall a. IO a -> [Handler a] -> IO a
`catches`
            [(IOError -> IO (Either String a)) -> Handler (Either String a)
forall a e. Exception e => (e -> IO a) -> Handler a
Handler (\(IOError
e::IOError)   -> Either String a -> IO (Either String a)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either String a -> IO (Either String a))
-> Either String a -> IO (Either String a)
forall a b. (a -> b) -> a -> b
$ String -> Either String a
forall a b. a -> Either a b
Left (String -> Either String a) -> String -> Either String a
forall a b. (a -> b) -> a -> b
$ IOError -> String
forall a. Show a => a -> String
show IOError
e)
            ,(ErrorCall -> IO (Either String a)) -> Handler (Either String a)
forall a e. Exception e => (e -> IO a) -> Handler a
Handler (\(ErrorCall
e::ErrorCall) -> Either String a -> IO (Either String a)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either String a -> IO (Either String a))
-> Either String a -> IO (Either String a)
forall a b. (a -> b) -> a -> b
$ String -> Either String a
forall a b. a -> Either a b
Left (String -> Either String a) -> String -> Either String a
forall a b. (a -> b) -> a -> b
$ ErrorCall -> String
forall a. Show a => a -> String
show ErrorCall
e)]
  case enew of
    Right a
new -> a -> IO ()
onSuccess a
new
    Left String
err  -> do
      Handle -> String -> IO ()
hPutStrLn Handle
stderr (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String
"could not reload " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
fp String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
", keeping previous " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
thing String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
":\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
err
      IO ()
onKeepPrevious

-- | Re-read any cached journals whose files (main or included) have changed on
-- disk since they were last read, updating the cache in place. Called at the top
-- of each REPL loop iteration so that commands see the latest file contents.
-- Prints a visible notice on stderr for each reload, and, if a changed file no
-- longer parses, keeps the previous version and prints the error.
refreshStaleJournals :: IO ()
refreshStaleJournals :: IO ()
refreshStaleJournals = do
  cache <- MVar (Map (InputOpts, String) Journal)
-> IO (Map (InputOpts, String) Journal)
forall a. MVar a -> IO a
readMVar MVar (Map (InputOpts, String) Journal)
journalCache
  forM_ (Map.toList cache) $ \((InputOpts
iopts,String
fp), Journal
j) -> do
    changed <- (String -> IO Bool) -> [String] -> IO Bool
forall (m :: * -> *) a. Monad m => (a -> m Bool) -> [a] -> m Bool
anyM (Journal -> String -> IO Bool
journalFileIsNewer Journal
j) (Journal -> [String]
journalAllFilePaths Journal
j)
    when changed $
      reloadChanged fp "version" (runExceptT $ readJournalFile iopts fp)
        (\Journal
j' -> MVar (Map (InputOpts, String) Journal)
-> (Map (InputOpts, String) Journal
    -> IO (Map (InputOpts, String) Journal))
-> IO ()
forall a. MVar a -> (a -> IO a) -> IO ()
modifyMVar_ MVar (Map (InputOpts, String) Journal)
journalCache ((Map (InputOpts, String) Journal
  -> IO (Map (InputOpts, String) Journal))
 -> IO ())
-> (Map (InputOpts, String) Journal
    -> IO (Map (InputOpts, String) Journal))
-> IO ()
forall a b. (a -> b) -> a -> b
$ Map (InputOpts, String) Journal
-> IO (Map (InputOpts, String) Journal)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Map (InputOpts, String) Journal
 -> IO (Map (InputOpts, String) Journal))
-> (Map (InputOpts, String) Journal
    -> Map (InputOpts, String) Journal)
-> Map (InputOpts, String) Journal
-> IO (Map (InputOpts, String) Journal)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (InputOpts, String)
-> Journal
-> Map (InputOpts, String) Journal
-> Map (InputOpts, String) Journal
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert (InputOpts
iopts,String
fp) Journal
j')
        -- On failure advance the cached journal's read time past its current files, so we report
        -- the error once and stay quiet until a file changes again.
        (do newest <- maximum . (jlastreadtime j :) . catMaybes <$> mapM maybeFileModificationTime (journalAllFilePaths j)
            modifyMVar_ journalCache $ return . Map.adjust (journalSetLastReadTime newest) (iopts,fp))

-- | If the config file has changed on disk since its command aliases were last read,
-- re-read them into the given ref. Prints a "(reloading CONFFILE)" notice before reading and,
-- if the file no longer parses, keeps the previous aliases and prints the error - consistent
-- with the journal data reload.
refreshStaleAliases :: Maybe (FilePath, RawOpts) -> IORef (POSIXTime,[(CommandAlias,CommandLine)]) -> IO ()
refreshStaleAliases :: Maybe (String, RawOpts)
-> IORef (POSIXTime, [(String, String)]) -> IO ()
refreshStaleAliases Maybe (String, RawOpts)
Nothing IORef (POSIXTime, [(String, String)])
_ = () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
refreshStaleAliases (Just (String
conffile, RawOpts
rawopts)) IORef (POSIXTime, [(String, String)])
ref = do
  mmtime <- String -> IO (Maybe POSIXTime)
maybeFileModificationTime String
conffile
  case mmtime of
    Maybe POSIXTime
Nothing    -> () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()  -- config file no longer exists; keep current aliases
    Just POSIXTime
mtime -> do
      (lastseen, oldaliases) <- IORef (POSIXTime, [(String, String)])
-> IO (POSIXTime, [(String, String)])
forall a. IORef a -> IO a
readIORef IORef (POSIXTime, [(String, String)])
ref
      when (mtime > lastseen) $
        reloadChanged conffile "aliases" readAliases
          (\[(String, String)]
as -> IORef (POSIXTime, [(String, String)])
-> (POSIXTime, [(String, String)]) -> IO ()
forall a. IORef a -> a -> IO ()
writeIORef IORef (POSIXTime, [(String, String)])
ref (POSIXTime
mtime, [(String, String)]
as))
          -- On failure advance the marker but keep the old aliases, so we report the error once
          -- and stay quiet until the file changes again.
          (writeIORef ref (mtime, oldaliases))
  where
    -- Re-read the config file's command aliases, forcing them so any error in a malformed
    -- [alias] line is raised here (and caught by reloadChanged) rather than later during expansion.
    readAliases :: IO (Either String [(String, String)])
readAliases = do
      econf <- RawOpts -> IO (Either String (Conf, Maybe String))
getConf RawOpts
rawopts
      case econf of
        Left String
e          -> Either String [(String, String)]
-> IO (Either String [(String, String)])
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either String [(String, String)]
 -> IO (Either String [(String, String)]))
-> Either String [(String, String)]
-> IO (Either String [(String, String)])
forall a b. (a -> b) -> a -> b
$ String -> Either String [(String, String)]
forall a b. a -> Either a b
Left String
e
        Right (Conf
conf, Maybe String
_) -> do
          let as :: [(String, String)]
as = [(String, String)] -> [(String, String)]
forall a. [a] -> [a]
reverse ([(String, String)] -> [(String, String)])
-> [(String, String)] -> [(String, String)]
forall a b. (a -> b) -> a -> b
$ Conf -> [(String, String)]
confAliases Conf
conf
          ((String, String) -> IO (String, String))
-> [(String, String)] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (String, String) -> IO (String, String)
forall a. a -> IO a
evaluate [(String, String)]
as
          Either String [(String, String)]
-> IO (Either String [(String, String)])
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either String [(String, String)]
 -> IO (Either String [(String, String)]))
-> Either String [(String, String)]
-> IO (Either String [(String, String)])
forall a b. (a -> b) -> a -> b
$ [(String, String)] -> Either String [(String, String)]
forall a b. b -> Either a b
Right [(String, String)]
as

-- | If a PATH directory has changed since the addon command list was last scanned,
-- re-scan for addon commands with the given action and update the ref. Prints a
-- "(reloaded addons)" notice only when the set of addon commands actually changed
-- (a PATH directory's mtime can change without affecting which hledger-* executables exist).
refreshStaleAddons :: Maybe (IO [String]) -> IORef (POSIXTime,[String]) -> IO ()
refreshStaleAddons :: Maybe (IO [String]) -> IORef (POSIXTime, [String]) -> IO ()
refreshStaleAddons Maybe (IO [String])
Nothing IORef (POSIXTime, [String])
_ = () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
refreshStaleAddons (Just IO [String]
rescan) IORef (POSIXTime, [String])
ref = do
  mtime <- IO POSIXTime
maxSearchPathMtime
  (lastseen, oldaddons) <- readIORef ref
  when (mtime > lastseen) $ do
    newaddons <- rescan
    writeIORef ref (mtime, newaddons)
    when (newaddons /= oldaddons) $ hPutStrLn stderr "(reloaded addons)"

-- | The most recent modification time among the existing directories on the PATH.
-- A directory's mtime changes when entries are added or removed, so this detects when
-- the set of installed addon commands may have changed.
maxSearchPathMtime :: IO POSIXTime
maxSearchPathMtime :: IO POSIXTime
maxSearchPathMtime = do
  dirs <- IO [String]
getSearchPath
  mtimes <- mapM maybeDirModificationTime dirs
  return $ maximum (0 : catMaybes mtimes)

-- | The last modified time of the specified directory, if it exists.
maybeDirModificationTime :: FilePath -> IO (Maybe POSIXTime)
maybeDirModificationTime :: String -> IO (Maybe POSIXTime)
maybeDirModificationTime String
d = do
  exists <- String -> IO Bool
doesDirectoryExist String
d
  if exists then Just . utcTimeToPOSIXSeconds <$> getModificationTime d else return Nothing

-- | Get the journal(s) to read: the command's own -f files if any, else the run/repl session's
-- journal(s) (defaultJournalOverride), else the default journal path. The path need not exist -
-- like add/import at the CLI, we let commands create it or report the error, rather than requiring
-- it up front (which would stop run/repl starting when there is no journal yet).
journalFilePathFromOptsOrDefault :: Maybe DefaultRunJournal -> CliOpts -> IO (NE.NonEmpty PrefixedFilePath)
journalFilePathFromOptsOrDefault :: Maybe DefaultRunJournal -> CliOpts -> IO (NonEmpty String)
journalFilePathFromOptsOrDefault Maybe DefaultRunJournal
defaultJournalOverride CliOpts
cliopts = do
  mbjournalpaths <- CliOpts -> IO (Maybe (NonEmpty String))
journalFilePathFromOptsNoDefault CliOpts
cliopts
  case mbjournalpaths of
    Just NonEmpty String
journalpaths -> NonEmpty String -> IO (NonEmpty String)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return NonEmpty String
journalpaths  -- the command's own -f files
    Maybe (NonEmpty String)
Nothing -> case Maybe DefaultRunJournal
defaultJournalOverride of
      Just (DefaultRunJournal NonEmpty String
defaultFiles) -> NonEmpty String -> IO (NonEmpty String)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return NonEmpty String
defaultFiles  -- the journal(s) given to run/repl
      Maybe DefaultRunJournal
Nothing -> [String] -> NonEmpty String
forall a. HasCallStack => [a] -> NonEmpty a
NE.fromList ([String] -> NonEmpty String)
-> (String -> [String]) -> String -> NonEmpty String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> [String]
forall a. a -> [a]
forall (f :: * -> *) a. Applicative f => a -> f a
pure (String -> NonEmpty String) -> IO String -> IO (NonEmpty String)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO String
defaultJournalPath  -- the default journal path (need not exist)

-- | Like withJournalCached, but tolerates a nonexistent first journal file (providing an empty
-- journal with that path set), so add and import can create it - as they do at the CLI. Does not
-- cache, since these commands write to the file.
withPossibleRunJournal :: DefaultRunJournal -> CliOpts -> (Journal -> IO ()) -> IO ()
withPossibleRunJournal :: DefaultRunJournal -> CliOpts -> (Journal -> IO ()) -> IO ()
withPossibleRunJournal DefaultRunJournal
defaultJournalOverride CliOpts
cliopts Journal -> IO ()
cmd = do
  journalpaths <- Maybe DefaultRunJournal -> CliOpts -> IO (NonEmpty String)
journalFilePathFromOptsOrDefault (DefaultRunJournal -> Maybe DefaultRunJournal
forall a. a -> Maybe a
Just DefaultRunJournal
defaultJournalOverride) CliOpts
cliopts
  ej <- runExceptT $ journalTransform cliopts <$> readPossibleJournalFiles (inputopts_ cliopts) (NE.toList journalpaths)
  either error' cmd ej

-- | Similar to `withJournal`, but caches all the journals it reads.
-- When reading from stdin, also caches the stdin contents so that we could reprocess
-- it if a read with different InputOptions is requested.
withJournalCached :: Maybe DefaultRunJournal -> CliOpts -> ((Journal, DefaultRunJournal) -> IO ()) -> IO ()
withJournalCached :: Maybe DefaultRunJournal
-> CliOpts -> ((Journal, DefaultRunJournal) -> IO ()) -> IO ()
withJournalCached Maybe DefaultRunJournal
defaultJournalOverride CliOpts
cliopts (Journal, DefaultRunJournal) -> IO ()
cmd = do
  journalpaths <- Maybe DefaultRunJournal -> CliOpts -> IO (NonEmpty String)
journalFilePathFromOptsOrDefault Maybe DefaultRunJournal
defaultJournalOverride CliOpts
cliopts
  j <- readFiles journalpaths
  cmd (j,DefaultRunJournal journalpaths)
  where
    readFiles :: NonEmpty String -> IO Journal
readFiles NonEmpty String
journalpaths =
      CliOpts -> Journal -> Journal
journalTransform CliOpts
cliopts (Journal -> Journal)
-> (NonEmpty Journal -> Journal) -> NonEmpty Journal -> Journal
forall b c a. (b -> c) -> (a -> b) -> a -> c
. NonEmpty Journal -> Journal
forall a. Semigroup a => NonEmpty a -> a
sconcat (NonEmpty Journal -> Journal)
-> IO (NonEmpty Journal) -> IO Journal
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (String -> IO Journal) -> NonEmpty String -> IO (NonEmpty Journal)
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) -> NonEmpty a -> m (NonEmpty b)
mapM (InputOpts -> String -> IO Journal
readAndCacheJournalFile (CliOpts -> InputOpts
inputopts_ CliOpts
cliopts)) NonEmpty String
journalpaths
    -- | Read a journal file, caching it (and InputOptions used to read it) if it has not been seen before.
    -- If the same file is requested with different InputOptions, we read it anew and cache
    -- it separately.
    readAndCacheJournalFile :: InputOpts -> PrefixedFilePath -> IO Journal
    readAndCacheJournalFile :: InputOpts -> String -> IO Journal
readAndCacheJournalFile InputOpts
iopts String
fp = do
      MVar (Map (InputOpts, String) Journal)
-> (Map (InputOpts, String) Journal
    -> IO (Map (InputOpts, String) Journal, Journal))
-> IO Journal
forall a b. MVar a -> (a -> IO (a, b)) -> IO b
modifyMVar MVar (Map (InputOpts, String) Journal)
journalCache ((Map (InputOpts, String) Journal
  -> IO (Map (InputOpts, String) Journal, Journal))
 -> IO Journal)
-> (Map (InputOpts, String) Journal
    -> IO (Map (InputOpts, String) Journal, Journal))
-> IO Journal
forall a b. (a -> b) -> a -> b
$ \Map (InputOpts, String) Journal
cache ->
        case (InputOpts, String)
-> Map (InputOpts, String) Journal -> Maybe Journal
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup (InputOpts
ioptsWithoutReportSpan,String
fp) Map (InputOpts, String) Journal
cache of
          Just Journal
journal -> do
            String -> InputOpts -> IO ()
forall (m :: * -> *) a. (MonadIO m, Show a) => String -> a -> m ()
dbg1IO (String
"readAndCacheJournalFile using cache for "String -> String -> String
forall a. [a] -> [a] -> [a]
++String
fp) InputOpts
iopts
            (Map (InputOpts, String) Journal, Journal)
-> IO (Map (InputOpts, String) Journal, Journal)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Map (InputOpts, String) Journal
cache, Journal
journal)
          Maybe Journal
Nothing -> do
            String -> InputOpts -> IO ()
forall (m :: * -> *) a. (MonadIO m, Show a) => String -> a -> m ()
dbg1IO (String
"readAndCacheJournalFile reading and caching "String -> String -> String
forall a. [a] -> [a] -> [a]
++String
fp) InputOpts
iopts
            journal <- ExceptT String IO Journal -> IO (Either String Journal)
forall e (m :: * -> *) a. ExceptT e m a -> m (Either e a)
runExceptT (ExceptT String IO Journal -> IO (Either String Journal))
-> ExceptT String IO Journal -> IO (Either String Journal)
forall a b. (a -> b) -> a -> b
$ if String -> Bool
isStdin String
fp then ExceptT String IO Journal
readStdin else InputOpts -> String -> ExceptT String IO Journal
readJournalFile InputOpts
iopts String
fp
            either error' (\Journal
j -> (Map (InputOpts, String) Journal, Journal)
-> IO (Map (InputOpts, String) Journal, Journal)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ((InputOpts, String)
-> Journal
-> Map (InputOpts, String) Journal
-> Map (InputOpts, String) Journal
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert (InputOpts
ioptsWithoutReportSpan,String
fp) Journal
j Map (InputOpts, String) Journal
cache, Journal
j)) journal
      where
        -- InputOptions contain reportspan_ that is used to calculate forecast period,
        -- that is used by journalFinalise to insert forecast transactions.
        -- For the purposes of caching, we want to ignore it whenever
        -- --forecast is not used, or when explicit dates are requested.
        ioptsWithoutReportSpan :: InputOpts
ioptsWithoutReportSpan = InputOpts
iopts{ reportspan_ = forecastreportspan }
          where
            forecastreportspan :: DateSpan
forecastreportspan = case InputOpts -> Maybe DateSpan
forecast_ InputOpts
iopts of
              Maybe DateSpan
Nothing           -> DateSpan
emptydatespan
              -- This could be better if we had access to the journal (as we
              -- could use 'forecastPeriod') or to the journal end date (as
              -- forecast transactions are never generated before journal end
              -- unless specifically requested).
              Just DateSpan
forecastspan -> DateSpan
forecastspan DateSpan -> DateSpan -> DateSpan
`spanValidDefaultsFrom` InputOpts -> DateSpan
reportspan_ InputOpts
iopts
        -- Read stdin, or if we read it already, use a cache
        -- readStdin :: InputOpts -> ExceptT String IO Journal
        readStdin :: ExceptT String IO Journal
readStdin = do
          stdinContent <- IO Text -> ExceptT String IO Text
forall a. IO a -> ExceptT String IO a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO Text -> ExceptT String IO Text)
-> IO Text -> ExceptT String IO Text
forall a b. (a -> b) -> a -> b
$ MVar (Maybe Text)
-> (Maybe Text -> IO (Maybe Text, Text)) -> IO Text
forall a b. MVar a -> (a -> IO (a, b)) -> IO b
modifyMVar MVar (Maybe Text)
stdinCache ((Maybe Text -> IO (Maybe Text, Text)) -> IO Text)
-> (Maybe Text -> IO (Maybe Text, Text)) -> IO Text
forall a b. (a -> b) -> a -> b
$ \Maybe Text
cache ->
            case Maybe Text
cache of
              Just Text
cached -> do
                String -> String -> IO ()
forall (m :: * -> *) a. (MonadIO m, Show a) => String -> a -> m ()
dbg1IO String
"readStdin using cached stdin" String
"-"
                (Maybe Text, Text) -> IO (Maybe Text, Text)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe Text
cache, Text
cached)
              Maybe Text
Nothing -> do
                String -> String -> IO ()
forall (m :: * -> *) a. (MonadIO m, Show a) => String -> a -> m ()
dbg1IO String
"readStdin reading and caching stdin" String
"-"
                stdinContent <- String -> IO Text
readFileOrStdinPortably String
"-"
                return (Just stdinContent, stdinContent)
          hndl <- liftIO $ textToHandle stdinContent
          readJournal iopts Nothing hndl