Debian Codegraph @

Hledger/Cli/Commands/Add.hs

raw
1 {-|
2 A history-aware, tab-completing interactive add command to help with data entry.
3 -}
4
5 {-# OPTIONS_GHC -fno-warn-missing-signatures -fno-warn-unused-do-bind #-}
6 {-# LANGUAGE FlexibleContexts #-}
7 {-# LANGUAGE LambdaCase #-}
8 {-# LANGUAGE OverloadedStrings #-}
9 {-# LANGUAGE PackageImports #-}
10 {-# LANGUAGE RecordWildCards #-}
11 {-# LANGUAGE ScopedTypeVariables #-}
12 {-# LANGUAGE TemplateHaskell #-}
13 {-# LANGUAGE TypeOperators #-}
14
15 module Hledger.Cli.Commands.Add (
16 addmode
17 ,add
18 ,appendToJournalFileOrStdout
19 ,journalAddTransaction
20 )
21 where
22
23 import Control.Exception as E
24 import Control.Monad (when)
25 import Control.Monad.Trans.Class
26 import Control.Monad.State.Strict (evalState, evalStateT)
27 import Control.Monad.Trans (liftIO)
28 import Data.Char (toUpper, toLower)
29 import Data.Either (isRight)
30 import Data.Functor.Identity (Identity(..))
31 import Data.List (isPrefixOf, nub)
32 import Data.Maybe (fromJust, fromMaybe, isJust)
33 import Data.Text (Text)
34 import Data.Text qualified as T
35 import Data.Text.IO qualified as T
36 import Data.Text.Lazy qualified as TL
37 import Data.Text.Lazy.IO qualified as TL
38 import Data.Time.Calendar (Day, toGregorian)
39 import Data.Time.Format (formatTime, defaultTimeLocale)
40 import Lens.Micro ((^.))
41 import Safe (headDef, headMay, atMay, lastMay)
42 import System.Console.CmdArgs.Explicit (flagNone)
43 import System.Console.Haskeline (runInputT, defaultSettings, setComplete)
44 import System.Console.Haskeline.Completion (CompletionFunc, completeWord, isFinished, noCompletion, simpleCompletion)
45 import System.Console.Wizard (Wizard, defaultTo, line, output, outputLn, retryMsg, linePrewritten, nonEmpty, parser, run)
46 import System.Console.Wizard.Haskeline
47 import System.IO ( stderr, hPutStr, hPutStrLn )
48 import Text.Megaparsec
49 import Text.Megaparsec.Char
50 import Text.Printf
51
52 import Hledger
53 import Hledger.Cli.CliOptions
54 import Hledger.Cli.Commands.Register (postingsReportAsText)
55 import Hledger.Cli.Utils (journalSimilarTransaction)
56
57
58 addmode = hledgerCommandMode
59 $(embedFileRelative "Hledger/Cli/Commands/Add.txt")
60 [flagNone ["no-new-accounts"] (setboolopt "no-new-accounts") "don't allow creating new accounts"]
61 [generalflagsgroup2]
62 confflags
63 ([], Just $ argsFlag "[-f JOURNALFILE] [DATE [DESCRIPTION [ACCOUNT1 [ETC..]]]]]")
64
65 data AddState = AddState {
66 asOpts :: CliOpts -- ^ command line options
67 ,asArgs :: [String] -- ^ command line arguments remaining to be used as defaults
68 ,asToday :: Day -- ^ today's date
69 ,asDefDate :: Day -- ^ the default date to use for the next transaction
70 ,asJournal :: Journal -- ^ the journal we are adding to
71 ,asSimilarTransaction :: Maybe Transaction -- ^ the old transaction most similar to the new one being entered
72 ,asPostings :: [Posting] -- ^ the new postings entered so far
73 } deriving (Show)
74
75 defAddState = AddState {
76 asOpts = defcliopts
77 ,asArgs = []
78 ,asToday = nulldate
79 ,asDefDate = nulldate
80 ,asJournal = nulljournal
81 ,asSimilarTransaction = Nothing
82 ,asPostings = []
83 }
84
85 data AddStep =
86 GetDate
87 | GetDescription (Day, Text)
88 | GetPosting TxnData (Maybe Posting)
89 | GetAccount TxnData
90 | GetAmount TxnData String
91 | Confirm Transaction
92
93 data TxnData = TxnData {
94 txnDate :: Day
95 , txnCode :: Text
96 , txnDesc :: Text
97 , txnCmnt :: Text
98 } deriving (Show)
99
100 type Comment = (Text, [Tag], Maybe Day, Maybe Day)
101
102 data PrevInput = PrevInput {
103 prevDateAndCode :: Maybe String
104 , prevDescAndCmnt :: Maybe String
105 , prevAccount :: [String]
106 , prevAmountAndCmnt :: [String]
107 } deriving (Show)
108
109 data RestartTransactionException = RestartTransactionException deriving (Show)
110 instance Exception RestartTransactionException
111
112 -- data ShowHelpException = ShowHelpException deriving (Show)
113 -- instance Exception ShowHelpException
114
115 -- | Read multiple transactions from the console, prompting for each
116 -- field, and append them to the journal file. If the journal came
117 -- from stdin, this command has no effect.
118 add :: CliOpts -> Journal -> IO ()
119 add opts j
120 | journalFilePath j == "-" = return ()
121 | otherwise = do
122 hPutStrLn stderr $ "Adding transactions to journal file " <> journalFilePath j
123 showHelp
124 let today = opts^.rsDay
125 state = defAddState{asOpts=opts
126 ,asArgs=listofstringopt "args" $ rawopts_ opts
127 ,asToday=today
128 ,asDefDate=today
129 ,asJournal=j
130 }
131 addTransactionsLoop state `E.catch` (\(_::UnexpectedEOF) -> putStr "")
132
133 showHelp = hPutStr stderr $ unlines [
134 "Any command line arguments will be used as defaults."
135 ,"Use tab key to complete, readline keys to edit, enter to accept defaults."
136 ,"An optional (CODE) may follow transaction dates."
137 ,"An optional ; COMMENT may follow descriptions or amounts."
138 ,"If you make a mistake, enter < at any prompt to go one step backward."
139 ,"To end a transaction, enter . when prompted."
140 ,"To quit, enter . at a date prompt or press control-d or control-c."
141 ]
142
143 -- | Loop reading transactions from the console, prompting, validating
144 -- and appending each one to the journal file, until end of input or
145 -- ctrl-c (then raise an EOF exception). If provided, command-line
146 -- arguments are used as defaults; otherwise defaults come from the
147 -- most similar recent transaction in the journal.
148 addTransactionsLoop :: AddState -> IO ()
149 addTransactionsLoop state@AddState{..} = (do
150 let defaultPrevInput = PrevInput{prevDateAndCode=Nothing, prevDescAndCmnt=Nothing, prevAccount=[], prevAmountAndCmnt=[]}
151 mt <- runInputT (setComplete noCompletion defaultSettings) (System.Console.Wizard.run $ haskeline $ transactionWizard defaultPrevInput state [])
152 case mt of
153 Nothing -> error' "Could not interpret the input, restarting" -- caught below causing a restart, I believe -- PARTIAL:
154 Just t -> do
155 j <- if debug_ asOpts > 0
156 then do hPutStrLn stderr "Skipping journal add due to debug mode."
157 return asJournal
158 else do j' <- journalAddTransaction asJournal asOpts t
159 hPutStrLn stderr "Saved."
160 return j'
161 hPutStrLn stderr "Starting the next transaction (. or ctrl-D/ctrl-C to quit)"
162 addTransactionsLoop state{asJournal=j, asDefDate=tdate t}
163 )
164 `E.catch` (\(_::RestartTransactionException) ->
165 hPutStrLn stderr "Restarting this transaction." >> addTransactionsLoop state)
166
167 -- | Interact with the user to get a Transaction.
168 transactionWizard :: PrevInput -> AddState -> [AddStep] -> Wizard Haskeline Transaction
169 transactionWizard previnput state [] = transactionWizard previnput state [GetDate]
170 transactionWizard previnput state@AddState{..} stack@(currentStage : _) = case currentStage of
171 GetDate -> dateWizard previnput state >>= \case
172 Just (efd, code) -> do
173 let
174 date = fromEFDay efd
175 state' = state{ asArgs = drop 1 asArgs
176 , asDefDate = date
177 }
178 dateAndCodeString = formatTime defaultTimeLocale yyyymmddFormat date
179 ++ T.unpack (if T.null code then "" else " (" <> code <> ")")
180 yyyymmddFormat = "%Y-%m-%d"
181 transactionWizard previnput{prevDateAndCode=Just dateAndCodeString} state' (GetDescription (date, code) : stack)
182 Nothing ->
183 transactionWizard previnput state stack
184
185 GetDescription (date, code) -> descriptionWizard previnput state >>= \case
186 Just (desc, comment) -> do
187 let mbaset = journalSimilarTransaction asOpts asJournal desc
188 state' = state
189 { asArgs = drop 1 asArgs
190 , asPostings = []
191 , asSimilarTransaction = mbaset
192 }
193 descAndCommentString = T.unpack $ desc <> (if T.null comment then "" else " ; " <> comment)
194 previnput' = previnput{prevDescAndCmnt=Just descAndCommentString}
195 when (isJust mbaset) . liftIO $ do
196 hPutStrLn stderr "Using this similar transaction for defaults:"
197 T.hPutStr stderr $ showTransaction (fromJust mbaset)
198 transactionWizard previnput' state' ((GetPosting TxnData{txnDate=date, txnCode=code, txnDesc=desc, txnCmnt=comment} Nothing) : stack)
199 Nothing ->
200 transactionWizard previnput state (drop 1 stack)
201
202 GetPosting txndata@TxnData{..} p -> case (asPostings, p) of
203 ([], Nothing) ->
204 transactionWizard previnput state (GetAccount txndata : stack)
205 (_, Just _) ->
206 transactionWizard previnput state (GetAccount txndata : stack)
207 (_, Nothing) -> do
208 let t = nulltransaction{tdate=txnDate
209 ,tstatus=Unmarked
210 ,tcode=txnCode
211 ,tdescription=txnDesc
212 ,tcomment=txnCmnt
213 ,tpostings=asPostings
214 }
215 bopts = balancingopts_ (inputopts_ asOpts)
216 case balanceTransactionInJournal t asJournal bopts of
217 Right t' ->
218 transactionWizard previnput state (Confirm t' : stack)
219 Left err -> do
220 liftIO (hPutStrLn stderr $ "\n" ++ (capitalize err) ++ ", please re-enter.")
221 let notFirstEnterPost stage = case stage of
222 GetPosting _ Nothing -> False
223 _ -> True
224 transactionWizard previnput state{asPostings=[]} (dropWhile notFirstEnterPost stack)
225
226 GetAccount txndata -> accountWizard previnput state >>= \case
227 Just account
228 | account `elem` [".", ""] ->
229 case (asPostings, postingsAreBalanced asPostings) of
230 ([],_) -> liftIO (hPutStrLn stderr "Please enter some postings first.") >> transactionWizard previnput state stack
231 (_,False) -> liftIO (hPutStrLn stderr "Please enter more postings to balance the transaction.") >> transactionWizard previnput state stack
232 (_,True) -> transactionWizard previnput state (GetPosting txndata Nothing : stack)
233 | otherwise -> do
234 let prevAccount' = replaceNthOrAppend (length asPostings) account (prevAccount previnput)
235 transactionWizard previnput{prevAccount=prevAccount'} state{asArgs=drop 1 asArgs} (GetAmount txndata account : stack)
236 Nothing -> do
237 let notPrevAmountAndNotGetDesc stage = case stage of
238 GetAmount _ _ -> False
239 GetDescription _ -> False
240 _ -> True
241 transactionWizard previnput state{asPostings=init asPostings} (dropWhile notPrevAmountAndNotGetDesc stack)
242
243 GetAmount txndata account -> amountWizard previnput state >>= \case
244 Just (mamt, assertion, (comment, tags, pdate1, pdate2)) -> do
245 let mixedamt = maybe missingmixedamt mixedAmount mamt
246 p = nullposting{paccount=T.pack $ stripbrackets account
247 ,pamount=mixedamt
248 ,pcomment=T.dropAround isNewline comment
249 ,ptype=accountNamePostingType $ T.pack account
250 ,pbalanceassertion = assertion
251 ,pdate=pdate1
252 ,pdate2=pdate2
253 ,ptags=tags
254 }
255 amountAndCommentString = showMixedAmountOneLine mixedamt ++ T.unpack (if T.null comment then "" else " ;" <> comment)
256 prevAmountAndCmnt' = replaceNthOrAppend (length asPostings) amountAndCommentString (prevAmountAndCmnt previnput)
257 state' = state{asPostings=asPostings++[p], asArgs=drop 1 asArgs}
258 -- Include a dummy posting to balance the unfinished transation in assertion checking
259 dummytxn = nulltransaction{tpostings = asPostings ++ [p, post "" missingamt]
260 ,tdate = txnDate txndata
261 ,tdescription = txnDesc txndata }
262 bopts = balancingopts_ (inputopts_ asOpts)
263 balanceassignment = mixedamt==missingmixedamt && isJust assertion
264 etxn
265 -- If the new posting is doing a balance assignment,
266 -- don't attempt to balance the transaction or check assertions yet
267 | balanceassignment = Right dummytxn
268 -- Otherwise, balance the transaction in context of the whole journal,
269 -- maybe filling its balance assignments if any,
270 -- and maybe checking all the journal's balance assertions.
271 | otherwise = balanceTransactionInJournal dummytxn asJournal bopts
272
273 case etxn of
274 Left err -> do
275 liftIO (hPutStrLn stderr err)
276 transactionWizard previnput state (GetAmount txndata account : stack)
277 Right _ ->
278 transactionWizard previnput{prevAmountAndCmnt=prevAmountAndCmnt'} state' (GetPosting txndata (Just posting) : stack)
279 Nothing -> transactionWizard previnput state (drop 1 stack)
280
281 Confirm t -> do
282 output . T.unpack $ showTransaction t
283 y <- let def = "y" in
284 retryMsg "Please enter y or n." $
285 parser ((fmap (\c -> if c == '<' then Nothing else Just c)) . headMay . map toLower . strip) $
286 defaultTo' def $ nonEmpty $
287 line $ green' $ printf "Save this transaction to the journal ?%s: " (showDefault def)
288 case y of
289 Just 'y' -> return t
290 Just _ -> throw RestartTransactionException
291 Nothing -> transactionWizard previnput state (drop 2 stack)
292 where
293 replaceNthOrAppend n newElem xs = take n xs ++ [newElem] ++ drop (n + 1) xs
294
295 -- | Interact with the user to get a transaction date (accepting smart dates), maybe followed by a " (CODE)".
296 -- Returns the date and the code, or nothing if the input was "<".
297 dateWizard :: PrevInput -> AddState -> Wizard Haskeline (Maybe (EFDay, Text))
298 dateWizard PrevInput{..} AddState{..} = do
299 let def = headDef (T.unpack $ showDate asDefDate) asArgs
300 retryMsg "A valid hledger smart date is required. Eg: 2022-08-30, 8/30, 30, yesterday." $
301 parser (parseSmartDateAndCode asToday) $
302 withCompletion (dateCompleter def) $
303 defaultTo' def $ nonEmpty $
304 maybeExit $
305 -- maybeShowHelp $
306 linePrewritten (green' $ printf "Date%s: " (showDefault def)) (fromMaybe "" prevDateAndCode) ""
307 where
308 parseSmartDateAndCode refdate s = if s == "<" then return Nothing else either (const Nothing) (\(d,c) -> return $ Just (fixSmartDate refdate d, c)) edc
309 where
310 edc = runParser (dateandcodep <* eof) "" $ T.pack $ lowercase s
311 dateandcodep :: SimpleTextParser (SmartDate, Text)
312 dateandcodep = do
313 d <- smartdate
314 c <- optional codep
315 skipNonNewlineSpaces
316 eof
317 return (d, fromMaybe "" c)
318 -- defday = fixSmartDate today $ fromparse $ (parse smartdate "" . lowercase) defdate
319 -- datestr = showDate $ fixSmartDate defday smtdate
320
321 -- | Interact with the user to get a transaction description, maybe followed by a "; COMMENT".
322 -- Returns the possibly empty description and comment, or nothing if the input is "<".
323 descriptionWizard :: PrevInput -> AddState -> Wizard Haskeline (Maybe (Text, Text))
324 descriptionWizard PrevInput{..} AddState{..} = do
325 let def = headDef "" asArgs
326 s <- withCompletion (descriptionCompleter asJournal def) $
327 defaultTo' def $ nonEmpty $
328 linePrewritten (green' $ printf "Description%s: " (showDefault def)) (fromMaybe "" prevDescAndCmnt) ""
329 if s == "<"
330 then return Nothing
331 else do
332 let (desc,comment) = (T.pack $ strip a, T.pack $ strip $ dropWhile (==';') b) where (a,b) = break (==';') s
333 return $ Just (desc, comment)
334
335 -- | Interact with the user to get an account name, possibly enclosed in "()" or "[]".
336 -- Returns the account name, or nothing if the input is "<".
337 accountWizard :: PrevInput -> AddState -> Wizard Haskeline (Maybe String)
338 accountWizard PrevInput{..} AddState{..} = do
339 let pnum = length asPostings + 1
340 historicalp = fmap ((!! (pnum - 1)) . (++ (repeat nullposting)) . tpostings) asSimilarTransaction
341 historicalacct = case historicalp of Just p -> showAccountName Nothing (ptype p) (paccount p)
342 Nothing -> ""
343 def = headDef (T.unpack historicalacct) asArgs
344 endmsg | canfinish && null def = " (or . or enter to finish this transaction)"
345 | canfinish = " (or . to finish this transaction)"
346 | otherwise = ""
347 retryMsg "A valid hledger account name is required. Eg: assets:cash, expenses:food:eating out." $
348 parser (parseAccountOrDotOrNull def canfinish) $
349 withCompletion (accountCompleter asJournal def) $
350 defaultTo' def $ -- nonEmpty $
351 linePrewritten (green' $ printf "Account %d%s%s: " pnum (endmsg::String) (showDefault def)) (fromMaybe "" $ prevAccount `atMay` length asPostings) ""
352 where
353 canfinish = not (null asPostings) && postingsAreBalanced asPostings
354 parseAccountOrDotOrNull :: String -> Bool -> String -> Maybe (Maybe String)
355 parseAccountOrDotOrNull _ _ "<" = dbg' $ Just Nothing
356 parseAccountOrDotOrNull _ _ "." = dbg' $ Just $ Just "." -- . always signals end of txn
357 parseAccountOrDotOrNull "" True "" = dbg' $ Just $ Just "" -- when there's no default and txn is balanced, "" also signals end of txn
358 parseAccountOrDotOrNull def@(_:_) _ "" = dbg' $ Just $ Just def -- when there's a default, "" means use that
359 parseAccountOrDotOrNull _ _ s = dbg' $ fmap (Just . T.unpack) $
360 either (const Nothing) validateAccount $
361 flip evalState asJournal $ runParserT (accountnamep <* eof) "" (T.pack s) -- otherwise, try to parse the input as an accountname
362 where
363 validateAccount :: Text -> Maybe Text
364 validateAccount t | no_new_accounts_ asOpts && notElem t (journalAccountNamesDeclaredOrImplied asJournal) = Nothing
365 | otherwise = Just t
366 dbg' = id -- strace
367
368 -- | Interact with the user to get an amount and/or a balance assertion, maybe followed by a "; COMMENT".
369 -- Returns the amount, balance assertion, and/or comment, or nothing if the input is "<".
370 amountWizard :: PrevInput -> AddState -> Wizard Haskeline (Maybe (Maybe Amount, Maybe BalanceAssertion, Comment))
371 amountWizard previnput@PrevInput{..} state@AddState{..} = do
372 let pnum = length asPostings + 1
373 (mhistoricalp,followedhistoricalsofar) =
374 case asSimilarTransaction of
375 Nothing -> (Nothing,False)
376 Just Transaction{tpostings=ps} ->
377 ( if length ps >= pnum then Just (ps !! (pnum-1)) else Nothing
378 , all sameamount $ zip asPostings ps
379 )
380 where
381 sameamount (p1,p2) = mixedAmountUnstyled (pamount p1) == mixedAmountUnstyled (pamount p2)
382 def | (d:_) <- asArgs = d
383 | Just hp <- mhistoricalp, followedhistoricalsofar = showamt $ pamount hp
384 | pnum > 1 && not (mixedAmountLooksZero balancingamt) = showamt balancingamtfirstcommodity
385 | otherwise = ""
386 retryMsg "A valid hledger amount is required. Eg: 1, $2, 3 EUR, \"4 red apples\"." $
387 parser' parseAmountAndComment $
388 withCompletion (amountCompleter def) $
389 defaultTo' def $
390 nonEmpty $
391 linePrewritten (green' $ printf "Amount %d%s: " pnum (showDefault def)) (fromMaybe "" $ prevAmountAndCmnt `atMay` length asPostings) ""
392 where
393 -- Custom parser that combines with Wizard to use IO via outputLn
394 parser' f a = a >>= \input ->
395 case f input of
396 Left err -> do
397 outputLn (customErrorBundlePretty err)
398 amountWizard previnput state
399 Right res -> pure res
400 parseAmountAndComment s =
401 if s == "<" then Right Nothing else
402 Just <$> runParser
403 (evalStateT (amountandcommentp <* eof) nodefcommodityj)
404 ""
405 (T.pack s)
406 nodefcommodityj = asJournal{jparsedefaultcommodity=Nothing}
407 amountandcommentp :: JournalParser Identity (Maybe Amount, Maybe BalanceAssertion, Comment)
408 amountandcommentp = do
409 mamt <- optional amountp
410 lift skipNonNewlineSpaces
411 massertion <- optional balanceassertionp
412 com <- T.pack <$> fromMaybe "" `fmap` optional (char ';' >> many anySingle)
413 case rtp (postingcommentp (let (y,_,_) = toGregorian asDefDate in Just y)) (T.cons ';' com) of
414 Left err -> fail $ customErrorBundlePretty err
415 -- Keep our original comment string from the user to add to the journal
416 Right (_, tags, date1', date2') -> return $ (mamt, massertion, (com, tags, date1', date2'))
417 balancingamt = maNegate . sumPostings $ filter isReal asPostings
418 balancingamtfirstcommodity = mixed . take 1 $ amounts balancingamt
419 showamt = wbUnpack . showMixedAmountB defaultFmt . mixedAmountSetPrecision
420 -- what should this be ?
421 -- 1 maxprecision (show all decimal places or none) ?
422 -- 2 maxprecisionwithpoint (show all decimal places or .0 - avoids some but not all confusion with thousands separators) ?
423 -- 3 canonical precision for this commodity in the journal ?
424 -- 4 maximum precision entered so far in this transaction ?
425 -- 5 3 or 4, whichever would show the most decimal places ?
426 -- I think 1 or 4, whichever would show the most decimal places
427 NaturalPrecision
428 --
429 -- let -- (amt,comment) = (strip a, strip $ dropWhile (==';') b) where (a,b) = break (==';') amtcmt
430 -- a = fromparse $ runParser (amountp <|> return missingamt) (jparsestate asJournal) "" amt
431 -- awithoutjps = fromparse $ runParser (amountp <|> return missingamt) mempty "" amt
432 -- defamtaccepted = Just (showAmount a) == mdefamt
433 -- as2 = if defamtaccepted then as1 else as1{asHistoricalPostings=Nothing}
434 -- mdefaultcommodityapplied = if acommodity a == acommodity awithoutjps then Nothing else Just $ acommodity a
435 -- when (isJust mdefaultcommodityapplied) $
436 -- liftIO $ hPutStrLn stderr $ printf "using default commodity (%s)" (fromJust mdefaultcommodityapplied)
437
438 -- Completion helpers
439
440 dateCompleter :: String -> CompletionFunc IO
441 dateCompleter = completer ["today","tomorrow","yesterday"]
442
443 -- Offer payees declared, payees used, or full descriptions used.
444 descriptionCompleter :: Journal -> String -> CompletionFunc IO
445 descriptionCompleter j = completer (map T.unpack $ nub $ journalPayeesDeclaredOrUsed j ++ journalDescriptions j)
446
447 accountCompleter :: Journal -> String -> CompletionFunc IO
448 accountCompleter j = completer (map T.unpack $ journalAccountNamesDeclaredOrImplied j)
449
450 amountCompleter :: String -> CompletionFunc IO
451 amountCompleter = completer []
452
453 -- | Generate a haskeline completion function from the given
454 -- completions and default, that case insensitively completes with
455 -- prefix matches, or infix matches above a minimum length, or
456 -- completes the null string with the default.
457 completer :: [String] -> String -> CompletionFunc IO
458 completer completions def = completeWord Nothing "" completionsFor
459 where
460 simpleCompletion' s = (simpleCompletion s){isFinished=False}
461 completionsFor "" = return [simpleCompletion' def]
462 completionsFor i = return (map simpleCompletion' ciprefixmatches)
463 where
464 ciprefixmatches = [c | c <- completions, i `isPrefixOf` c]
465 -- mixed-case completions require haskeline > 0.7.1.2
466 -- ciprefixmatches = [c | c <- completions, lowercase i `isPrefixOf` lowercase c]
467
468 --------------------------------------------------------------------------------
469
470 -- utilities
471
472 maybeExit = parser (\s -> if s == "." then throw UnexpectedEOF else Just s)
473
474 -- maybeShowHelp :: Wizard Haskeline String -> Wizard Haskeline String
475 -- maybeShowHelp wizard = maybe (liftIO showHelp >> wizard) return $
476 -- parser (\s -> if s=="?" then Nothing else Just s) wizard
477
478 defaultTo' = flip defaultTo
479
480 withCompletion f = withSettings (setComplete f defaultSettings)
481
482 showDefault "" = ""
483 showDefault s = " [" ++ s ++ "]"
484
485 -- | Balance and check a transaction with awareness of the whole journal it will be added to.
486 -- This means add it to the journal, balance it, calculate any balance assignments in it,
487 -- then maybe check all the journal's balance assertions,
488 -- then return the now fully balanced and checked transaction, or an error message.
489 balanceTransactionInJournal :: Transaction -> Journal -> BalancingOpts -> Either String Transaction
490 balanceTransactionInJournal t j bopts = do
491 -- Add the transaction at the end of the journal, as the add command will.
492 let j' = j{jtxns = jtxns j ++ [t]}
493 -- Try to balance and check the whole journal, and specifically the new transaction.
494 Journal{jtxns=ts} <- journalBalanceTransactions bopts j'
495 -- Extract the balanced & checked transaction.
496 maybe
497 (Left "balanceTransactionInJournal: unexpected empty journal") -- should not happen
498 Right
499 (lastMay ts)
500
501 postingsAreBalanced :: [Posting] -> Bool
502 postingsAreBalanced ps = isRight $ balanceSingleTransaction defbalancingopts nulltransaction{tpostings = ps}
503
504 -- | Append this transaction to the journal's file and transaction list.
505 journalAddTransaction :: Journal -> CliOpts -> Transaction -> IO Journal
506 journalAddTransaction j@Journal{jtxns=ts} opts t = do
507 let f = journalFilePath j
508 appendToJournalFileOrStdout f $ showTransaction t
509 -- unelided shows all amounts explicitly, in case there's a price, cf #283
510 when (debug_ opts > 0) $ do
511 putStrLn $ printf "\nAdded transaction to %s:" f
512 TL.putStrLn =<< registerFromString (showTransaction t)
513 return j{jtxns=ts++[t]}
514
515 -- | Append a string, typically one or more transactions, to a journal
516 -- file, or if the file is "-", dump it to stdout. Tries to avoid
517 -- excess whitespace.
518 --
519 -- XXX This writes unix line endings (\n), some at least,
520 -- even if the file uses dos line endings (\r\n), which could leave
521 -- mixed line endings in the file. See also writeFileWithBackupIfChanged.
522 --
523 appendToJournalFileOrStdout :: FilePath -> Text -> IO ()
524 appendToJournalFileOrStdout f s
525 | f == "-" = T.putStr s'
526 | otherwise = do
527 ensureJournalFileExists f
528 appendFile f $ T.unpack s'
529 where s' = "\n" <> ensureOneNewlineTerminated s
530
531 -- | Replace a string's 0 or more terminating newlines with exactly one.
532 ensureOneNewlineTerminated :: Text -> Text
533 ensureOneNewlineTerminated = (<>"\n") . T.dropWhileEnd (=='\n')
534
535 -- | Convert a string of journal data into a register report.
536 registerFromString :: T.Text -> IO TL.Text
537 registerFromString s = do
538 j <- readJournal'' s
539 return . postingsReportAsText opts $ postingsReport rspec j
540 where
541 ropts = defreportopts{empty_=True}
542 rspec = defreportspec{_rsReportOpts=ropts}
543 opts = defcliopts{reportspec_=rspec}
544
545 capitalize :: String -> String
546 capitalize "" = ""
547 capitalize (c:cs) = toUpper c : cs