| 1 |
{-| |
| 2 |
|
| 3 |
The @run@ command allows you to run multiple commands via REPL or from the supplied file(s). |
| 4 |
|
| 5 |
-} |
| 6 |
|
| 7 |
{-# LANGUAGE MultiWayIf #-} |
| 8 |
{-# LANGUAGE OverloadedStrings #-} |
| 9 |
{-# LANGUAGE ScopedTypeVariables #-} |
| 10 |
{-# LANGUAGE TemplateHaskell #-} |
| 11 |
|
| 12 |
module Hledger.Cli.Commands.Run ( |
| 13 |
runmode |
| 14 |
,run |
| 15 |
,replmode |
| 16 |
,repl |
| 17 |
,runOrReplStub |
| 18 |
) where |
| 19 |
|
| 20 |
import Data.List.NonEmpty qualified as NE |
| 21 |
import Data.Map.Strict qualified as Map |
| 22 |
import Data.Semigroup (sconcat) |
| 23 |
import Data.Text qualified as T |
| 24 |
import Data.Text.IO qualified as T |
| 25 |
import System.Console.CmdArgs.Explicit as C ( Mode ) |
| 26 |
import Hledger |
| 27 |
import Hledger.Cli.CliOptions |
| 28 |
|
| 29 |
import Control.Exception |
| 30 |
import Control.Concurrent.MVar |
| 31 |
import Control.Monad (forM_) |
| 32 |
import Control.Monad.IO.Class (liftIO) |
| 33 |
import Control.Monad.Extra (concatMapM) |
| 34 |
|
| 35 |
import System.Exit (ExitCode, exitWith) |
| 36 |
import System.Console.CmdArgs.Explicit (expandArgsAt, modeNames) |
| 37 |
import System.IO (stdin, hIsTerminalDevice, hIsOpen) |
| 38 |
import System.IO.Unsafe (unsafePerformIO) |
| 39 |
import System.Console.Haskeline |
| 40 |
|
| 41 |
import Safe (headMay) |
| 42 |
import Hledger.Cli.DocFiles (runTldrForPage, runInfoForTopic, runManForTopic) |
| 43 |
import Hledger.Cli.Utils (journalTransform) |
| 44 |
import Text.Printf (printf) |
| 45 |
import System.Process (system) |
| 46 |
|
| 47 |
-- | Command line options for this command. |
| 48 |
runmode = hledgerCommandMode |
| 49 |
$(embedFileRelative "Hledger/Cli/Commands/Run.txt") |
| 50 |
( |
| 51 |
[] |
| 52 |
) |
| 53 |
cligeneralflagsgroups1 |
| 54 |
hiddenflags |
| 55 |
([], Just $ argsFlag "[COMMANDS_FILE1 COMMANDS_FILE2 ...] OR [-- command1 args... -- command2 args... -- command3 args...]") |
| 56 |
|
| 57 |
replmode = hledgerCommandMode |
| 58 |
$(embedFileRelative "Hledger/Cli/Commands/Repl.txt") |
| 59 |
( |
| 60 |
[] |
| 61 |
) |
| 62 |
cligeneralflagsgroups1 |
| 63 |
hiddenflags |
| 64 |
([], Nothing) |
| 65 |
|
| 66 |
-- | The fake run/repl command introduced to break circular dependency. |
| 67 |
-- This module needs access to `findBuiltinCommand`, which is defined in Hledger.Cli.Commands |
| 68 |
-- However, Hledger.Cli.Commands imports this module, which creates circular dependency. |
| 69 |
-- We expose this do-nothing function so that it could be included in the list of all commands inside |
| 70 |
-- Hledger.Cli.Commands and ensure that "run" is recognized as a valid command by the Hledger.Cli top-level |
| 71 |
-- command line parser. That parser, however, would not call run'. It has a special case for "run", and |
| 72 |
-- will call "run" (see below), passing it `findBuiltinCommand`, thus breaking circular dependency. |
| 73 |
runOrReplStub :: CliOpts -> Journal -> IO () |
| 74 |
runOrReplStub _opts _j = return () |
| 75 |
|
| 76 |
-- | Default input files that would be used by commands if |
| 77 |
-- there is no explicit alternative given |
| 78 |
newtype DefaultRunJournal = DefaultRunJournal (NE.NonEmpty String) deriving (Show) |
| 79 |
|
| 80 |
-- | The actual run command. |
| 81 |
run :: Maybe DefaultRunJournal -> (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())) -> [String] -> CliOpts -> IO () |
| 82 |
run defaultJournalOverride findBuiltinCommand addons cliopts@CliOpts{rawopts_=rawopts} = do |
| 83 |
jpaths <- DefaultRunJournal <$> journalFilePathFromOptsOrDefault defaultJournalOverride cliopts |
| 84 |
let args = dbg1 "args" $ listofstringopt "args" rawopts |
| 85 |
isTerminal <- isStdinTerminal |
| 86 |
if args == [] && not isTerminal |
| 87 |
then do |
| 88 |
inputFiles <- journalFilePathFromOpts cliopts |
| 89 |
let journalFromStdin = any (== "-") $ map (snd . splitReaderPrefix) $ NE.toList inputFiles |
| 90 |
if journalFromStdin |
| 91 |
then error' "'run' can't read commands from stdin, as one of the input files was stdin as well" |
| 92 |
else runREPL jpaths findBuiltinCommand addons |
| 93 |
else do |
| 94 |
-- Check if arguments start with "--". |
| 95 |
-- If not, assume that they are files with commands |
| 96 |
case args of |
| 97 |
"--":_ -> runFromArgs jpaths findBuiltinCommand addons args |
| 98 |
_ -> runFromFiles jpaths findBuiltinCommand addons args |
| 99 |
|
| 100 |
-- | The actual repl command. |
| 101 |
repl :: (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())) -> [String] -> CliOpts -> IO () |
| 102 |
repl findBuiltinCommand addons cliopts = do |
| 103 |
jpaths <- DefaultRunJournal <$> journalFilePathFromOptsOrDefault Nothing cliopts |
| 104 |
runREPL jpaths findBuiltinCommand addons |
| 105 |
|
| 106 |
-- | Run commands from files given to "run". |
| 107 |
runFromFiles :: DefaultRunJournal -> (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())) -> [String] -> [String] -> IO () |
| 108 |
runFromFiles defaultJournalOverride findBuiltinCommand addons inputfiles = do |
| 109 |
dbg1IO "inputfiles" inputfiles |
| 110 |
-- read commands from all the inputfiles |
| 111 |
commands <- (flip concatMapM) inputfiles $ \f -> do |
| 112 |
dbg1IO "reading commands" f |
| 113 |
lines . T.unpack <$> T.readFile f |
| 114 |
|
| 115 |
forM_ commands (runCommand defaultJournalOverride findBuiltinCommand addons . parseCommand) |
| 116 |
|
| 117 |
-- | Run commands from command line arguments given to "run". |
| 118 |
runFromArgs :: DefaultRunJournal -> (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())) -> [String] -> [String] -> IO () |
| 119 |
runFromArgs defaultJournalOverride findBuiltinCommand addons args = do |
| 120 |
-- read commands from all the inputfiles |
| 121 |
let commands = dbg1 "commands from args" $ splitAtElement "--" args |
| 122 |
forM_ commands (runCommand defaultJournalOverride findBuiltinCommand addons) |
| 123 |
|
| 124 |
-- When commands are passed on the command line, shell will parse them for us |
| 125 |
-- When commands are read from file, we need to split the line into command and arguments |
| 126 |
parseCommand :: String -> [String] |
| 127 |
parseCommand line = |
| 128 |
-- # begins a comment, ignore everything after # |
| 129 |
takeWhile (not. ((Just '#')==) . headMay) $ words' (strip line) |
| 130 |
|
| 131 |
-- | Take a single command line (from file, or REPL, or "--"-surrounded block of the args), and run it. |
| 132 |
runCommand :: DefaultRunJournal -> (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())) -> [String] -> [String] -> IO () |
| 133 |
runCommand defaultJournalOverride findBuiltinCommand addons cmdline = do |
| 134 |
dbg1IO "runCommand for" cmdline |
| 135 |
case cmdline of |
| 136 |
"echo":args -> putStrLn $ unwords $ args |
| 137 |
cmdname:args -> |
| 138 |
case findBuiltinCommand cmdname of |
| 139 |
Just (cmdmode,cmdaction) -> do |
| 140 |
-- Even though expandArgsAt is done by the Cli.hs, it stops at the first '--', so we need |
| 141 |
-- to do it here as well to make sure that each command can use @ARGFILEs |
| 142 |
args' <- replaceNumericFlags <$> expandArgsAt args |
| 143 |
dbg1IO "runCommand final args" (cmdname,args') |
| 144 |
opts <- getHledgerCliOpts' cmdmode args' |
| 145 |
let |
| 146 |
rawopts = rawopts_ opts |
| 147 |
mmodecmdname = headMay $ modeNames cmdmode |
| 148 |
helpFlag = boolopt "help" rawopts |
| 149 |
tldrFlag = boolopt "tldr" rawopts |
| 150 |
infoFlag = boolopt "info" rawopts |
| 151 |
manFlag = boolopt "man" rawopts |
| 152 |
if |
| 153 |
| helpFlag -> runPager $ showModeUsage cmdmode ++ "\n" |
| 154 |
| tldrFlag -> runTldrForPage $ maybe "hledger" (("hledger-"<>)) mmodecmdname |
| 155 |
| infoFlag -> runInfoForTopic "hledger" mmodecmdname |
| 156 |
| manFlag -> runManForTopic "hledger" mmodecmdname |
| 157 |
| otherwise -> do |
| 158 |
withJournalCached (Just defaultJournalOverride) opts $ \(j,jpaths) -> do |
| 159 |
if cmdname == "run" -- allow "run" to call "run" |
| 160 |
then run (Just jpaths) findBuiltinCommand addons opts |
| 161 |
else cmdaction opts j |
| 162 |
Nothing | cmdname `elem` addons -> |
| 163 |
system (printf "%s-%s %s" progname cmdname (unwords $ map quoteForCommandLine args)) >>= exitWith |
| 164 |
Nothing -> |
| 165 |
error' $ "Unrecognized command: " ++ unwords (cmdname:args) |
| 166 |
[] -> return () |
| 167 |
|
| 168 |
-- | Run an interactive REPL. |
| 169 |
runREPL :: DefaultRunJournal -> (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())) -> [String] -> IO () |
| 170 |
runREPL defaultJournalOverride findBuiltinCommand addons = do |
| 171 |
isTerminal <- isStdinTerminal |
| 172 |
if not isTerminal |
| 173 |
then runInputT defaultSettings (loop False "") |
| 174 |
else do |
| 175 |
putStrLn "Enter hledger commands. To exit, enter 'quit' or 'exit', or send EOF." |
| 176 |
runInputT defaultSettings (loop True "% ") |
| 177 |
where |
| 178 |
loop :: Bool -> String -> InputT IO () |
| 179 |
loop interactive prompt = do |
| 180 |
minput <- getInputLine prompt |
| 181 |
case minput of |
| 182 |
Nothing -> return () |
| 183 |
Just "quit" -> return () |
| 184 |
Just "exit" -> return () |
| 185 |
Just input -> do |
| 186 |
let cmd = runCommand defaultJournalOverride findBuiltinCommand addons $ argsAddDoubleDash $ parseCommand input |
| 187 |
liftIO $ if interactive |
| 188 |
then cmd `catches` |
| 189 |
[Handler (\(e::ErrorCall) -> putStrLn $ rstrip $ show e) |
| 190 |
,Handler (\(e::IOError) -> putStrLn $ rstrip $ show e) |
| 191 |
,Handler (\(_::ExitCode) -> return ()) |
| 192 |
,Handler (\UserInterrupt -> return ()) |
| 193 |
] |
| 194 |
else cmd |
| 195 |
loop interactive prompt |
| 196 |
|
| 197 |
isStdinTerminal = do |
| 198 |
op <- hIsOpen stdin |
| 199 |
if op then hIsTerminalDevice stdin else return False |
| 200 |
|
| 201 |
-- | Cache of all journals that have been read by commands given to "run", |
| 202 |
-- keyed by the fully-expanded filename. |
| 203 |
journalCache :: MVar (Map.Map (InputOpts,PrefixedFilePath) Journal) |
| 204 |
journalCache = unsafePerformIO $ newMVar Map.empty |
| 205 |
{-# NOINLINE journalCache #-} |
| 206 |
|
| 207 |
-- | Cache of stdin contents, so that we can re-read it if InputOptions change |
| 208 |
stdinCache :: MVar (Maybe T.Text) |
| 209 |
stdinCache = unsafePerformIO $ newMVar Nothing |
| 210 |
{-# NOINLINE stdinCache #-} |
| 211 |
|
| 212 |
-- | Get the journal(s) to read, either from the defaultJournalOverride or from the cliopts |
| 213 |
journalFilePathFromOptsOrDefault :: Maybe DefaultRunJournal -> CliOpts -> IO (NE.NonEmpty PrefixedFilePath) |
| 214 |
journalFilePathFromOptsOrDefault defaultJournalOverride cliopts = do |
| 215 |
case defaultJournalOverride of |
| 216 |
Nothing -> journalFilePathFromOpts cliopts |
| 217 |
Just (DefaultRunJournal defaultFiles) -> do |
| 218 |
mbjournalpaths <- journalFilePathFromOptsNoDefault cliopts |
| 219 |
case mbjournalpaths of |
| 220 |
Nothing -> return defaultFiles -- use the journal(s) given to the "run" itself |
| 221 |
Just journalpaths -> return journalpaths |
| 222 |
|
| 223 |
-- | Similar to `withJournal`, but caches all the journals it reads. |
| 224 |
-- When reading from stdin, also caches the stdin contents so that we could reprocess |
| 225 |
-- it if a read with different InputOptions is requested. |
| 226 |
withJournalCached :: Maybe DefaultRunJournal -> CliOpts -> ((Journal, DefaultRunJournal) -> IO ()) -> IO () |
| 227 |
withJournalCached defaultJournalOverride cliopts cmd = do |
| 228 |
journalpaths <- journalFilePathFromOptsOrDefault defaultJournalOverride cliopts |
| 229 |
j <- readFiles journalpaths |
| 230 |
cmd (j,DefaultRunJournal journalpaths) |
| 231 |
where |
| 232 |
readFiles journalpaths = |
| 233 |
journalTransform cliopts . sconcat <$> mapM (readAndCacheJournalFile (inputopts_ cliopts)) journalpaths |
| 234 |
-- | Read a journal file, caching it (and InputOptions used to read it) if it has not been seen before. |
| 235 |
-- If the same file is requested with different InputOptions, we read it anew and cache |
| 236 |
-- it separately. |
| 237 |
readAndCacheJournalFile :: InputOpts -> PrefixedFilePath -> IO Journal |
| 238 |
readAndCacheJournalFile iopts fp = do |
| 239 |
modifyMVar journalCache $ \cache -> |
| 240 |
case Map.lookup (ioptsWithoutReportSpan,fp) cache of |
| 241 |
Just journal -> do |
| 242 |
dbg1IO ("readAndCacheJournalFile using cache for "++fp) iopts |
| 243 |
return (cache, journal) |
| 244 |
Nothing -> do |
| 245 |
dbg1IO ("readAndCacheJournalFile reading and caching "++fp) iopts |
| 246 |
journal <- runExceptT $ if isStdin fp then readStdin else readJournalFile iopts fp |
| 247 |
either error' (\j -> return (Map.insert (ioptsWithoutReportSpan,fp) j cache, j)) journal |
| 248 |
where |
| 249 |
-- InputOptions contain reportspan_ that is used to calculate forecast period, |
| 250 |
-- that is used by journalFinalise to insert forecast transactions. |
| 251 |
-- For the purposes of caching, we want to ignore it whenever |
| 252 |
-- --forecast is not used, or when explicit dates are requested. |
| 253 |
ioptsWithoutReportSpan = iopts{ reportspan_ = forecastreportspan } |
| 254 |
where |
| 255 |
forecastreportspan = case forecast_ iopts of |
| 256 |
Nothing -> emptydatespan |
| 257 |
-- This could be better if we had access to the journal (as we |
| 258 |
-- could use 'forecastPeriod') or to the journal end date (as |
| 259 |
-- forecast transactions are never generated before journal end |
| 260 |
-- unless specifically requested). |
| 261 |
Just forecastspan -> forecastspan `spanValidDefaultsFrom` reportspan_ iopts |
| 262 |
-- Read stdin, or if we read it already, use a cache |
| 263 |
-- readStdin :: InputOpts -> ExceptT String IO Journal |
| 264 |
readStdin = do |
| 265 |
stdinContent <- liftIO $ modifyMVar stdinCache $ \cache -> |
| 266 |
case cache of |
| 267 |
Just cached -> do |
| 268 |
dbg1IO "readStdin using cached stdin" "-" |
| 269 |
return (cache, cached) |
| 270 |
Nothing -> do |
| 271 |
dbg1IO "readStdin reading and caching stdin" "-" |
| 272 |
stdinContent <- readFileOrStdinPortably "-" |
| 273 |
return (Just stdinContent, stdinContent) |
| 274 |
hndl <- liftIO $ textToHandle stdinContent |
| 275 |
readJournal iopts Nothing hndl |