{-|
Checking assert directives: standing rules declared in the journal,
each a query which must match no rows, or some rows, of the equivalent balance report
(over the whole journal, or in every period of a period expression).
See the hledger manual's "assert directive" section, and doc/SPEC-assert.md.

The rows are calculated here by direct accumulation over the journal's postings,
replicating what @hledger bal -E QUERY@ would show, rather than by running the balance report,
which would make journal reading depend on the reports code.
-}

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}

module Hledger.Data.JournalChecks.Assert (
  journalCheckAsserts
)
where

import Control.Monad (mfilter)
import Data.Char (isAlphaNum)
import Data.HashMap.Strict qualified as HM
import Data.IntMap qualified as IM
#if !MIN_VERSION_base(4,20,0)
import Data.List (foldl')
#endif
import Data.List (sortBy, transpose)
import Data.Map.Strict qualified as M
import Data.Maybe (isNothing, mapMaybe)
import Safe (headMay, lastMay)
import Data.Ord (comparing)
import Data.Set qualified as S
import Data.Text (Text)
import Data.Text qualified as T
import Data.Time.Calendar (Day, addDays)
import Text.Printf (printf)
import Text.Megaparsec (SourcePos(..), unPos)

import Hledger.Data.AccountName (clipOrEllipsifyAccountName)
import Hledger.Data.Amount (maPlus, nullmixedamt, showMixedAmountOneLine)
import Hledger.Data.Dates (showDate, showDateSpan, spanContainsDate, spanEnd, spanIntersect, spanStart, spanValidDefaultsFrom)
import Hledger.Data.DayPartition (splitSpanToDateSpans)
import Hledger.Data.Errors (decorateExcerpt)
import Hledger.Data.Journal (filterPostingAmount, journalAccountType, journalDateSpan, journalPostings)
import Hledger.Data.Posting (hasAmount, postingDate, postingStripCosts)
import Hledger.Data.Types
import Hledger.Query
import Hledger.Utils (fitText)
import Text.DocLayout (realLength)

-- | Check the rules of all this journal's assert directives, in parse order,
-- returning an error message for the first failure.
-- The day is today's date, for resolving relative dates in queries.
journalCheckAsserts :: Day -> Journal -> Either String ()
journalCheckAsserts :: Day -> Journal -> Either FilePath ()
journalCheckAsserts Day
today Journal
j = (AssertDirective -> Either FilePath ())
-> [AssertDirective] -> Either FilePath ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Day
-> Journal
-> HashMap PostingAccounts Int
-> [(Int, Posting)]
-> DateSpan
-> AssertDirective
-> Either FilePath ()
checkAssert Day
today Journal
j HashMap PostingAccounts Int
acctids [(Int, Posting)]
numberedps DateSpan
jspan) ([AssertDirective] -> Either FilePath ())
-> [AssertDirective] -> Either FilePath ()
forall a b. (a -> b) -> a -> b
$ Journal -> [AssertDirective]
jasserts Journal
j
  where
    -- Calculated once, for all directives: the journal's postings in date order
    -- (stably, so same-day postings stay in parse order), each with its account number
    -- (see assertAccountQueriesEnabled), and the journal's date span.
    (HashMap PostingAccounts Int
acctids, [(Int, Posting)]
numberedps) = [Posting] -> (HashMap PostingAccounts Int, [(Int, Posting)])
numberPostingAccounts ([Posting] -> (HashMap PostingAccounts Int, [(Int, Posting)]))
-> [Posting] -> (HashMap PostingAccounts Int, [(Int, Posting)])
forall a b. (a -> b) -> a -> b
$ (Posting -> Posting -> Ordering) -> [Posting] -> [Posting]
forall a. (a -> a -> Ordering) -> [a] -> [a]
sortBy ((Posting -> Day) -> Posting -> Posting -> Ordering
forall a b. Ord a => (b -> a) -> b -> b -> Ordering
comparing Posting -> Day
postingDate) ([Posting] -> [Posting]) -> [Posting] -> [Posting]
forall a b. (a -> b) -> a -> b
$ Journal -> [Posting]
journalPostings Journal
j
    jspan :: DateSpan
jspan = Bool -> Journal -> DateSpan
journalDateSpan Bool
False Journal
j

-- | A posting's account names, as used by account query terms: its account,
-- and its original account (before aliasing or pivoting) if that is different.
type PostingAccounts = (AccountName, Maybe AccountName)

postingAccounts :: Posting -> PostingAccounts
postingAccounts :: Posting -> PostingAccounts
postingAccounts Posting
p = (Text
a, (Text -> Bool) -> Maybe Text -> Maybe Text
forall (m :: * -> *) a. MonadPlus m => (a -> Bool) -> m a -> m a
mfilter (Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
/= Text
a) (Maybe Text -> Maybe Text) -> Maybe Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ Posting -> Text
paccount (Posting -> Text) -> Maybe Posting -> Maybe Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Posting -> Maybe Posting
poriginal Posting
p) where a :: Text
a = Posting -> Text
paccount Posting
p

-- | Number the distinct account names of these postings, returning the numbering,
-- and the postings with their numbers (in the same order).
numberPostingAccounts :: [Posting] -> (HM.HashMap PostingAccounts Int, [(Int, Posting)])
numberPostingAccounts :: [Posting] -> (HashMap PostingAccounts Int, [(Int, Posting)])
numberPostingAccounts [Posting]
ps = (HashMap PostingAccounts Int
ids, [(Int, Posting)] -> [(Int, Posting)]
forall a. [a] -> [a]
reverse [(Int, Posting)]
numbered)
  where
    (HashMap PostingAccounts Int
ids, [(Int, Posting)]
numbered) = ((HashMap PostingAccounts Int, [(Int, Posting)])
 -> Posting -> (HashMap PostingAccounts Int, [(Int, Posting)]))
-> (HashMap PostingAccounts Int, [(Int, Posting)])
-> [Posting]
-> (HashMap PostingAccounts Int, [(Int, Posting)])
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' (HashMap PostingAccounts Int, [(Int, Posting)])
-> Posting -> (HashMap PostingAccounts Int, [(Int, Posting)])
number (HashMap PostingAccounts Int
forall k v. HashMap k v
HM.empty, []) [Posting]
ps
    number :: (HashMap PostingAccounts Int, [(Int, Posting)])
-> Posting -> (HashMap PostingAccounts Int, [(Int, Posting)])
number (HashMap PostingAccounts Int
m, [(Int, Posting)]
acc) Posting
p = case PostingAccounts -> HashMap PostingAccounts Int -> Maybe Int
forall k v. Hashable k => k -> HashMap k v -> Maybe v
HM.lookup PostingAccounts
k HashMap PostingAccounts Int
m of
      Just Int
i  -> (HashMap PostingAccounts Int
m, (Int
i, Posting
p) (Int, Posting) -> [(Int, Posting)] -> [(Int, Posting)]
forall a. a -> [a] -> [a]
: [(Int, Posting)]
acc)
      Maybe Int
Nothing -> let !i :: Int
i = HashMap PostingAccounts Int -> Int
forall k v. HashMap k v -> Int
HM.size HashMap PostingAccounts Int
m in (PostingAccounts
-> Int
-> HashMap PostingAccounts Int
-> HashMap PostingAccounts Int
forall k v. Hashable k => k -> v -> HashMap k v -> HashMap k v
HM.insert PostingAccounts
k Int
i HashMap PostingAccounts Int
m, (Int
i, Posting
p) (Int, Posting) -> [(Int, Posting)] -> [(Int, Posting)]
forall a. a -> [a] -> [a]
: [(Int, Posting)]
acc)
      where k :: PostingAccounts
k = Posting -> PostingAccounts
postingAccounts Posting
p

-- | What matched at a failing checkpoint, shown in the error message:
-- the matching rows (account, change, balance), or, when the query has no
-- change:/balance: terms and so is about which postings exist, the matching postings.
-- (At a failing checkpoint of a some rule, nothing matched.)
data Evidence = MatchedRows [(AccountName, MixedAmount, MixedAmount)] | MatchedPostings [Posting]

-- | A failing checkpoint: its span, how many rows or postings matched there,
-- and the first of them (as many as the error message may still show).
data Failure = Failure !DateSpan !Int Evidence

-- | Keep only the first n items of some evidence.
takeEvidence :: Int -> Evidence -> Evidence
takeEvidence :: Int -> Evidence -> Evidence
takeEvidence Int
n (MatchedRows [(Text, MixedAmount, MixedAmount)]
rows)   = [(Text, MixedAmount, MixedAmount)] -> Evidence
MatchedRows ([(Text, MixedAmount, MixedAmount)] -> Evidence)
-> [(Text, MixedAmount, MixedAmount)] -> Evidence
forall a b. (a -> b) -> a -> b
$ Int
-> [(Text, MixedAmount, MixedAmount)]
-> [(Text, MixedAmount, MixedAmount)]
forall a. Int -> [a] -> [a]
take Int
n [(Text, MixedAmount, MixedAmount)]
rows
takeEvidence Int
n (MatchedPostings [Posting]
ps) = [Posting] -> Evidence
MatchedPostings ([Posting] -> Evidence) -> [Posting] -> Evidence
forall a b. (a -> b) -> a -> b
$ Int -> [Posting] -> [Posting]
forall a. Int -> [a] -> [a]
take Int
n [Posting]
ps

-- | How many items some evidence has.
evidenceSize :: Evidence -> Int
evidenceSize :: Evidence -> Int
evidenceSize (MatchedRows [(Text, MixedAmount, MixedAmount)]
rows)   = [(Text, MixedAmount, MixedAmount)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(Text, MixedAmount, MixedAmount)]
rows
evidenceSize (MatchedPostings [Posting]
ps) = [Posting] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Posting]
ps

-- | Evaluate some evidence fully, so that it doesn't keep the checking state of its checkpoint alive.
forceEvidence :: Evidence -> ()
forceEvidence :: Evidence -> ()
forceEvidence (MatchedPostings [Posting]
ps) = [Posting] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Posting]
ps Int -> () -> ()
forall a b. a -> b -> b
`seq` ()
forceEvidence (MatchedRows [(Text, MixedAmount, MixedAmount)]
rows)   = ((Text, MixedAmount, MixedAmount) -> () -> ())
-> () -> [(Text, MixedAmount, MixedAmount)] -> ()
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr (\(Text
a, MixedAmount
chg, MixedAmount
bal) ()
r -> Text
a Text -> () -> ()
forall a b. a -> b -> b
`seq` MixedAmount
chg MixedAmount -> () -> ()
forall a b. a -> b -> b
`seq` MixedAmount
bal MixedAmount -> () -> ()
forall a b. a -> b -> b
`seq` ()
r) () [(Text, MixedAmount, MixedAmount)]
rows

-- | An account's running balance, and its matching-amount counts (see 'assertCountingEnabled').
data RunningBalance = RunningBalance !MixedAmount ![Int]

-- | Matching-amount counts: an optimisation for periodic rules with balance: terms.
-- These rules re-test an account's balance in each period where it changes, and a balance: term
-- matches a balance if any one of its single-commodity amounts does, so a balance holding many
-- commodities (dozens, or even hundreds) is costly to re-test. Instead, each running balance
-- keeps, for each balance: term, a count of its amounts which match; a posting changes only the
-- amounts in its own commodities, so only those are re-tested to update the counts, and the term
-- matches the balance when its count is above zero. This makes the cost per posting independent
-- of how many commodities the balance holds. (The error message's rows are still calculated
-- directly, see evidenceAt.)
--
-- The one rule for this code: with the counts, balanceMatches must give exactly what testing the
-- whole balance would. To disable the optimisation, eg while investigating a wrong result, set
-- this to False: balances are then re-tested in full, which is slower but simpler.
-- The code it enables is marked "matching-amount counts" in checkAssert.
assertCountingEnabled :: Bool
assertCountingEnabled :: Bool
assertCountingEnabled = Bool
True

-- | Per-account queries: an optimisation for selecting each rule's postings.
-- Each rule's query is tested against every posting in the journal, and its account terms
-- (acct:, type:, depth:) are regular expression matches against the posting's account name,
-- which cost much more than the rest. But postings share a few account names, so instead,
-- for each distinct account name the query is partially evaluated (see 'postingQueryForAccount'),
-- leaving a smaller query (usually just "match all" or "match none") to test against that
-- account's postings. This makes selecting postings several times cheaper.
--
-- The one rule for this code: the per-account query must match exactly the postings
-- the whole query would. To disable the optimisation, eg while investigating a wrong result,
-- set this to False: each posting is then tested with the whole query.
assertAccountQueriesEnabled :: Bool
assertAccountQueriesEnabled :: Bool
assertAccountQueriesEnabled = Bool
True

-- A possible further optimisation, if many rules become common: each rule still scans all
-- of the journal's postings, so with 100 rules (on a large journal, measured 2026-11-10)
-- a bal report took about 3.5 times as long. Grouping the postings by account once, for
-- all rules, would let each rule visit only the accounts its per-account query doesn't
-- rule out (merging their postings by date), so that a rule about a few accounts would
-- cost almost nothing. Rules about many accounts would cost about the same as now.

-- | Check one assert directive's rule, given the journal's account numbering (see 'numberPostingAccounts'),
-- its postings in date order with their account numbers, and its date span.
-- Each checkpoint is the balance report @bal -E -b START -e END QUERY@: its rows are the
-- accounts (clipped to the query's depth) with postings matching the query in the period,
-- plus, when the query has balance: terms, the accounts with earlier postings (whose change
-- may be zero); each row has its change in the period and its balance at the period end.
-- All checkpoints are checked, so that a failure can report every failing checkpoint, and what matched there.
checkAssert :: Day -> Journal -> HM.HashMap PostingAccounts Int -> [(Int, Posting)] -> DateSpan -> AssertDirective -> Either String ()
checkAssert :: Day
-> Journal
-> HashMap PostingAccounts Int
-> [(Int, Posting)]
-> DateSpan
-> AssertDirective
-> Either FilePath ()
checkAssert Day
today Journal
j HashMap PostingAccounts Int
acctids [(Int, Posting)]
numberedps DateSpan
jspan ad :: AssertDirective
ad@AssertDirective{adQuantifier :: AssertDirective -> AssertQuantifier
adQuantifier=AssertQuantifier
quant, adPeriod :: AssertDirective -> Maybe (Interval, DateSpan)
adPeriod=Maybe (Interval, DateSpan)
mperiod, adQueryText :: AssertDirective -> Text
adQueryText=Text
querytxt, adSkips :: AssertDirective -> [DateSpan]
adSkips=[DateSpan]
skips} = do
  (rowq, otherq) <- (FilePath -> Either FilePath (Query, Query))
-> ((Query, Query) -> Either FilePath (Query, Query))
-> Either FilePath (Query, Query)
-> Either FilePath (Query, Query)
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (FilePath -> Either FilePath (Query, Query)
forall a b. a -> Either a b
Left (FilePath -> Either FilePath (Query, Query))
-> (FilePath -> FilePath)
-> FilePath
-> Either FilePath (Query, Query)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (AssertDirective -> FilePath
errorPrefix AssertDirective
ad FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<>)) (Query, Query) -> Either FilePath (Query, Query)
forall a b. b -> Either a b
Right (Either FilePath (Query, Query) -> Either FilePath (Query, Query))
-> Either FilePath (Query, Query) -> Either FilePath (Query, Query)
forall a b. (a -> b) -> a -> b
$ Query -> Either FilePath (Query, Query)
querySplitRowTerms (Query -> Either FilePath (Query, Query))
-> ((Query, [QueryOpt]) -> Query)
-> (Query, [QueryOpt])
-> Either FilePath (Query, Query)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Query, [QueryOpt]) -> Query
forall a b. (a, b) -> a
fst ((Query, [QueryOpt]) -> Either FilePath (Query, Query))
-> Either FilePath (Query, [QueryOpt])
-> Either FilePath (Query, Query)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< Day -> Text -> Either FilePath (Query, [QueryOpt])
parseQuery Day
today Text
querytxt
  let
    -- As in the balance report, date: terms don't select postings; they set the report period,
    -- intersected with the period expression's span if any. (date2: terms are ignored, as in bal without --date2.)
    datespan = Bool -> Query -> DateSpan
queryDateSpan Bool
False Query
otherq

    -- The postings selected by the other non-row query terms, prepared as the balance report would:
    -- amounts limited to the parts matching amt:/cur: terms, and costs stripped. Still in date order,
    -- and generated lazily. Each is paired with a copy whose account name is clipped to the depth: terms'
    -- depth: the copies are what is checked, the originals are what an error message shows.
    depthspec = Query -> DepthSpec
queryDepth Query
otherq
    postingq  = (Query -> Bool) -> Query -> Query
filterQuery (Bool -> Bool
not (Bool -> Bool) -> (Query -> Bool) -> Query -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Query -> Bool
queryIsDateOrDate2) (Query -> Query) -> Query -> Query
forall a b. (a -> b) -> a -> b
$ (Query -> Bool) -> Query -> Query
filterQuery (Bool -> Bool
not (Bool -> Bool) -> (Query -> Bool) -> Query -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Query -> Bool
queryIsDepth) Query
otherq
    amtq      = (Query -> Bool) -> Query -> Query
filterQuery Query -> Bool
queryIsAmtOrCur Query
postingq
    atype = Journal -> Text -> Maybe AccountType
journalAccountType Journal
j
    selected (Int
i, Posting
p)
      | Bool
assertAccountQueriesEnabled = (Text -> Maybe AccountType) -> Query -> Posting -> Bool
matchesPostingExtra Text -> Maybe AccountType
atype (Query -> Int -> IntMap Query -> Query
forall a. a -> Int -> IntMap a -> a
IM.findWithDefault Query
postingq Int
i IntMap Query
queriesbyaccount) Posting
p
      | Bool
otherwise                   = (Text -> Maybe AccountType) -> Query -> Posting -> Bool
matchesPostingExtra Text -> Maybe AccountType
atype Query
postingq Posting
p
    -- The posting query, partially evaluated for each account (lazily, when first needed).
    queriesbyaccount = [(Int, Query)] -> IntMap Query
forall a. [(Int, a)] -> IntMap a
IM.fromList [(Int
i, (Text -> Maybe AccountType) -> Text -> Maybe Text -> Query -> Query
postingQueryForAccount Text -> Maybe AccountType
atype Text
a Maybe Text
morig Query
postingq) | ((Text
a, Maybe Text
morig), Int
i) <- HashMap PostingAccounts Int -> [(PostingAccounts, Int)]
forall k v. HashMap k v -> [(k, v)]
HM.toList HashMap PostingAccounts Int
acctids]
    prepare Posting
p = do
      p' <- if Query -> Bool
queryIsNull Query
amtq then Posting -> Maybe Posting
forall a. a -> Maybe a
Just Posting
p else Query -> Posting -> Maybe Posting
filterPostingAmount Query
amtq Posting
p
      Just $ postingStripCosts p'
    ps = [ (Posting
p, Posting
p{paccount = clipOrEllipsifyAccountName depthspec $ paccount p})
         | Posting
p <- (Posting -> Bool) -> [Posting] -> [Posting]
forall a. (a -> Bool) -> [a] -> [a]
filter Posting -> Bool
hasAmount ([Posting] -> [Posting]) -> [Posting] -> [Posting]
forall a b. (a -> b) -> a -> b
$ ((Int, Posting) -> Maybe Posting) -> [(Int, Posting)] -> [Posting]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe (Posting -> Maybe Posting
prepare (Posting -> Maybe Posting)
-> ((Int, Posting) -> Posting) -> (Int, Posting) -> Maybe Posting
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Int, Posting) -> Posting
forall a b. (a, b) -> b
snd) ([(Int, Posting)] -> [Posting]) -> [(Int, Posting)] -> [Posting]
forall a b. (a -> b) -> a -> b
$ ((Int, Posting) -> Bool) -> [(Int, Posting)] -> [(Int, Posting)]
forall a. (a -> Bool) -> [a] -> [a]
filter (Int, Posting) -> Bool
selected [(Int, Posting)]
numberedps ]

    hasrowterms = Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ Query -> Bool
queryIsNull Query
rowq
    hasbalanceq = Query -> Bool
queryHasBalance Query
rowq
    haschangeq  = Query -> Bool
queryHasChange Query
rowq
    passes Bool
anymatched = case AssertQuantifier
quant of
      AssertQuantifier
AssertNone -> Bool -> Bool
not Bool
anymatched
      AssertQuantifier
AssertSome -> Bool
anymatched
    before Maybe Day
mend (a
_, Posting
p)    = Bool -> (Day -> Bool) -> Maybe Day -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
True (Posting -> Day
postingDate Posting
p Day -> Day -> Bool
forall a. Ord a => a -> a -> Bool
<) Maybe Day
mend
    onOrAfter Maybe Day
mstart (a
_, Posting
p) = Bool -> (Day -> Bool) -> Maybe Day -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
True (Posting -> Day
postingDate Posting
p Day -> Day -> Bool
forall a. Ord a => a -> a -> Bool
>=) Maybe Day
mstart

    -- A period's changes by account.
    addPosting Map Text MixedAmount
m Posting
p = (MixedAmount -> MixedAmount -> MixedAmount)
-> Text
-> MixedAmount
-> Map Text MixedAmount
-> Map Text MixedAmount
forall k a. Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
M.insertWith ((MixedAmount -> MixedAmount -> MixedAmount)
-> MixedAmount -> MixedAmount -> MixedAmount
forall a b c. (a -> b -> c) -> b -> a -> c
flip MixedAmount -> MixedAmount -> MixedAmount
maPlus) (Posting -> Text
paccount Posting
p) (Posting -> MixedAmount
pamount Posting
p) Map Text MixedAmount
m
    amountsOf = (Map Text MixedAmount -> Posting -> Map Text MixedAmount)
-> Map Text MixedAmount -> [Posting] -> Map Text MixedAmount
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' Map Text MixedAmount -> Posting -> Map Text MixedAmount
addPosting Map Text MixedAmount
forall k a. Map k a
M.empty

    -- The change: and balance: terms, as amount comparisons, each with whether it is negated.
    -- (They are combined by AND, see querySplitRowTerms.)
    changeterms  = [(Bool
neg, OrdPlus -> Quantity -> Maybe Text -> Query
Amt OrdPlus
o Quantity
n Maybe Text
mc) | (Bool
neg, Change OrdPlus
o Quantity
n Maybe Text
mc)  <- Query -> [(Bool, Query)]
signedRowTerms Query
rowq]
    balanceterms = [(Bool
neg, OrdPlus -> Quantity -> Maybe Text -> Query
Amt OrdPlus
o Quantity
n Maybe Text
mc) | (Bool
neg, Balance OrdPlus
o Quantity
n Maybe Text
mc) <- Query -> [(Bool, Query)]
signedRowTerms Query
rowq]
    changeMatches MixedAmount
chg = [Bool] -> Bool
forall (t :: * -> *). Foldable t => t Bool -> Bool
and [Bool
neg Bool -> Bool -> Bool
forall a. Eq a => a -> a -> Bool
/= Query -> MixedAmount -> Bool
matchesMixedAmount Query
t MixedAmount
chg | (Bool
neg, Query
t) <- [(Bool, Query)]
changeterms]
    zerochangematches = MixedAmount -> Bool
changeMatches MixedAmount
nullmixedamt

    -- Running balances by account. With assertCountingEnabled, these also have the matching-amount counts.
    addPostingRunning Map Text RunningBalance
m Posting
p = Text
-> RunningBalance
-> Map Text RunningBalance
-> Map Text RunningBalance
forall k a. Ord k => k -> a -> Map k a -> Map k a
M.insert (Posting -> Text
paccount Posting
p) (MixedAmount -> [Int] -> RunningBalance
RunningBalance MixedAmount
bal' [Int]
counts') Map Text RunningBalance
m
      where
        RunningBalance MixedAmount
bal [Int]
counts = RunningBalance -> Text -> Map Text RunningBalance -> RunningBalance
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault (MixedAmount -> [Int] -> RunningBalance
RunningBalance MixedAmount
nullmixedamt ([Int] -> RunningBalance) -> [Int] -> RunningBalance
forall a b. (a -> b) -> a -> b
$ ((Bool, Query) -> Int) -> [(Bool, Query)] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (Int -> (Bool, Query) -> Int
forall a b. a -> b -> a
const Int
0) [(Bool, Query)]
balanceterms) (Posting -> Text
paccount Posting
p) Map Text RunningBalance
m
        bal' :: MixedAmount
bal'    = MixedAmount
bal MixedAmount -> MixedAmount -> MixedAmount
`maPlus` Posting -> MixedAmount
pamount Posting
p
        counts' :: [Int]
counts' | Bool
assertCountingEnabled = MixedAmount -> MixedAmount -> MixedAmount -> [Int] -> [Int]
updateMatchCounts MixedAmount
bal MixedAmount
bal' (Posting -> MixedAmount
pamount Posting
p) [Int]
counts
                | Bool
otherwise             = [Int]
counts
    -- Does this running balance match the balance: terms ?
    balanceMatches (RunningBalance bal :: MixedAmount
bal@(Mixed Map MixedAmountKey Amount
amts) [Int]
counts)
      | Bool
assertCountingEnabled Bool -> Bool -> Bool
&& Bool -> Bool
not (Map MixedAmountKey Amount -> Bool
forall k a. Map k a -> Bool
M.null Map MixedAmountKey Amount
amts) = [Bool] -> Bool
forall (t :: * -> *). Foldable t => t Bool -> Bool
and [Bool
neg Bool -> Bool -> Bool
forall a. Eq a => a -> a -> Bool
/= (Int
c Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0) | ((Bool
neg, Query
_), Int
c) <- [(Bool, Query)] -> [Int] -> [((Bool, Query), Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip [(Bool, Query)]
balanceterms [Int]
counts]
      | Bool
otherwise = [Bool] -> Bool
forall (t :: * -> *). Foldable t => t Bool -> Bool
and [Bool
neg Bool -> Bool -> Bool
forall a. Eq a => a -> a -> Bool
/= Query -> MixedAmount -> Bool
matchesMixedAmount Query
t MixedAmount
bal | (Bool
neg, Query
t) <- [(Bool, Query)]
balanceterms]

    --- matching-amount counts (see assertCountingEnabled)
    -- Update an account's matching-amount counts, given its balance before and after a posting, and the
    -- posting's amount: only the amounts in the posting's commodities have changed, so only they are re-tested.
    updateMatchCounts MixedAmount
bal MixedAmount
bal' (Mixed Map MixedAmountKey Amount
pamts) [Int]
counts = [Int] -> [Int]
forall {t :: * -> *} {a}. Foldable t => t a -> t a
forceElems ([Int] -> [Int]) -> [Int] -> [Int]
forall a b. (a -> b) -> a -> b
$ (Int -> Int -> Int) -> [Int] -> [Int] -> [Int]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith Int -> Int -> Int
forall a. Num a => a -> a -> a
(+) [Int]
counts
      [ [Int] -> Int
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Bool -> Int
forall a. Enum a => a -> Int
fromEnum (MixedAmount -> MixedAmountKey -> Bool
matchesIn MixedAmount
bal' MixedAmountKey
k) Int -> Int -> Int
forall a. Num a => a -> a -> a
- Bool -> Int
forall a. Enum a => a -> Int
fromEnum (MixedAmount -> MixedAmountKey -> Bool
matchesIn MixedAmount
bal MixedAmountKey
k) | MixedAmountKey
k <- Map MixedAmountKey Amount -> [MixedAmountKey]
forall k a. Map k a -> [k]
M.keys Map MixedAmountKey Amount
pamts]
      | (Bool
_, Query
t) <- [(Bool, Query)]
balanceterms
      , let matchesIn :: MixedAmount -> MixedAmountKey -> Bool
matchesIn (Mixed Map MixedAmountKey Amount
amts) MixedAmountKey
k = Bool -> (Amount -> Bool) -> Maybe Amount -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False (Query -> Amount -> Bool
matchesAmount Query
t) (Maybe Amount -> Bool) -> Maybe Amount -> Bool
forall a b. (a -> b) -> a -> b
$ MixedAmountKey -> Map MixedAmountKey Amount -> Maybe Amount
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup MixedAmountKey
k Map MixedAmountKey Amount
amts ]
      where forceElems :: t a -> t a
forceElems t a
xs = (a -> t a -> t a) -> t a -> t a -> t a
forall a b. (a -> b -> b) -> b -> t a -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr a -> t a -> t a
forall a b. a -> b -> b
seq t a
xs t a
xs
    --- end of matching-amount counts

    -- The checkpoints: the whole journal within the date: span, or each period of the period expression.
    checkpoints = case Maybe (Interval, DateSpan)
mperiod of
      Maybe (Interval, DateSpan)
Nothing -> [DateSpan
datespan]
      Just (Interval
interval, DateSpan
spn) ->
        -- The periods, as the balance report would calculate them: from the period expression's span
        -- and the date: terms' span, with open ends filled from the journal's span,
        -- and adjusted to interval boundaries unless a start date was specified.
        let requestedspan :: DateSpan
requestedspan = DateSpan
spn DateSpan -> DateSpan -> DateSpan
`spanIntersect` DateSpan
datespan
        in Bool -> Interval -> DateSpan -> [DateSpan]
splitSpanToDateSpans (Maybe Day -> Bool
forall a. Maybe a -> Bool
isNothing (Maybe Day -> Bool) -> Maybe Day -> Bool
forall a b. (a -> b) -> a -> b
$ DateSpan -> Maybe Day
spanStart DateSpan
requestedspan) Interval
interval (DateSpan -> [DateSpan]) -> DateSpan -> [DateSpan]
forall a b. (a -> b) -> a -> b
$
           DateSpan
requestedspan DateSpan -> DateSpan -> DateSpan
`spanValidDefaultsFrom` DateSpan
jspan

    -- Check each checkpoint in turn, returning the failing ones, each with the number of matches there,
    -- and the first of them, until the error message has as many as it will show (so that a rule
    -- failing in many periods doesn't accumulate all of their matches).
    -- Postings before the first checkpoint count in the balances only, and postings after the last are ignored.
    -- With balance: terms, this maintains the running balances, and the set of accounts whose
    -- balance matches the balance: terms, updating only the accounts posted to in each period.
    -- Each period's rows are the accounts with postings in it, plus, with balance: terms, the
    -- accounts with earlier postings, whose change is zero. Without change:/balance: terms every
    -- row matches, so it's just whether the period has any postings.
    -- Checkpoints in the periods of skip subdirectives are skipped, but their postings still count in the balances.
    checkPeriods Int
_ Map Text RunningBalance
_ Set Text
_ [(Posting, Posting)]
_ [] = []
    checkPeriods !Int
want !Map Text RunningBalance
balances !Set Text
matching [(Posting, Posting)]
remaining (DateSpan
sp:[DateSpan]
sps)
      | DateSpan -> Bool
isSkipped DateSpan
sp Bool -> Bool -> Bool
|| Bool -> Bool
passes Bool
anyrowmatches = Int -> [Failure]
rest Int
want
      | Bool
otherwise            = let !failure :: Failure
failure = DateSpan -> Int -> Evidence -> Failure
Failure DateSpan
sp Int
nmatched Evidence
kept  -- evaluated now, not when the message reads it
                               in Evidence -> ()
forceEvidence Evidence
kept () -> [Failure] -> [Failure]
forall a b. a -> b -> b
`seq` (Failure
failure Failure -> [Failure] -> [Failure]
forall a. a -> [a] -> [a]
: Int -> [Failure]
rest (Int
want Int -> Int -> Int
forall a. Num a => a -> a -> a
- Evidence -> Int
evidenceSize Evidence
kept))
      where
        rest :: Int -> [Failure]
rest Int
w        = Int
-> Map Text RunningBalance
-> Set Text
-> [(Posting, Posting)]
-> [DateSpan]
-> [Failure]
checkPeriods Int
w Map Text RunningBalance
balances' Set Text
matching' [(Posting, Posting)]
later [DateSpan]
sps
        kept :: Evidence
kept          = Int -> Evidence -> Evidence
takeEvidence Int
want Evidence
evidence
        ([(Posting, Posting)]
upto, [(Posting, Posting)]
later) = ((Posting, Posting) -> Bool)
-> [(Posting, Posting)]
-> ([(Posting, Posting)], [(Posting, Posting)])
forall a. (a -> Bool) -> [a] -> ([a], [a])
span (Maybe Day -> (Posting, Posting) -> Bool
forall {a}. Maybe Day -> (a, Posting) -> Bool
before (Maybe Day -> (Posting, Posting) -> Bool)
-> Maybe Day -> (Posting, Posting) -> Bool
forall a b. (a -> b) -> a -> b
$ DateSpan -> Maybe Day
spanEnd DateSpan
sp) [(Posting, Posting)]
remaining
        now :: [(Posting, Posting)]
now           = ((Posting, Posting) -> Bool)
-> [(Posting, Posting)] -> [(Posting, Posting)]
forall a. (a -> Bool) -> [a] -> [a]
dropWhile (Bool -> Bool
not (Bool -> Bool)
-> ((Posting, Posting) -> Bool) -> (Posting, Posting) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Maybe Day -> (Posting, Posting) -> Bool
forall {a}. Maybe Day -> (a, Posting) -> Bool
onOrAfter (DateSpan -> Maybe Day
spanStart DateSpan
sp)) [(Posting, Posting)]
upto
        changes :: Map Text MixedAmount
changes       = [Posting] -> Map Text MixedAmount
amountsOf ([Posting] -> Map Text MixedAmount)
-> [Posting] -> Map Text MixedAmount
forall a b. (a -> b) -> a -> b
$ ((Posting, Posting) -> Posting)
-> [(Posting, Posting)] -> [Posting]
forall a b. (a -> b) -> [a] -> [b]
map (Posting, Posting) -> Posting
forall a b. (a, b) -> b
snd [(Posting, Posting)]
now
        (Map Text RunningBalance
balances', Set Text
matching')
          | Bool
hasbalanceq = (Map Text RunningBalance
bals, (Set Text -> Text -> Set Text) -> Set Text -> Set Text -> Set Text
forall b a. (b -> a -> b) -> b -> Set a -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' Set Text -> Text -> Set Text
upd Set Text
matching (Set Text -> Set Text) -> Set Text -> Set Text
forall a b. (a -> b) -> a -> b
$ [Text] -> Set Text
forall a. Ord a => [a] -> Set a
S.fromList ([Text] -> Set Text) -> [Text] -> Set Text
forall a b. (a -> b) -> a -> b
$ ((Posting, Posting) -> Text) -> [(Posting, Posting)] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Posting -> Text
paccount (Posting -> Text)
-> ((Posting, Posting) -> Posting) -> (Posting, Posting) -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Posting, Posting) -> Posting
forall a b. (a, b) -> b
snd) [(Posting, Posting)]
upto)
          | Bool
otherwise   = (Map Text RunningBalance
balances, Set Text
matching)
          where
            bals :: Map Text RunningBalance
bals = (Map Text RunningBalance -> Posting -> Map Text RunningBalance)
-> Map Text RunningBalance -> [Posting] -> Map Text RunningBalance
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' Map Text RunningBalance -> Posting -> Map Text RunningBalance
addPostingRunning Map Text RunningBalance
balances ([Posting] -> Map Text RunningBalance)
-> [Posting] -> Map Text RunningBalance
forall a b. (a -> b) -> a -> b
$ ((Posting, Posting) -> Posting)
-> [(Posting, Posting)] -> [Posting]
forall a b. (a -> b) -> [a] -> [b]
map (Posting, Posting) -> Posting
forall a b. (a, b) -> b
snd [(Posting, Posting)]
upto
            upd :: Set Text -> Text -> Set Text
upd Set Text
s Text
a = if Bool -> (RunningBalance -> Bool) -> Maybe RunningBalance -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False RunningBalance -> Bool
balanceMatches (Text -> Map Text RunningBalance -> Maybe RunningBalance
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup Text
a Map Text RunningBalance
bals) then Text -> Set Text -> Set Text
forall a. Ord a => a -> Set a -> Set a
S.insert Text
a Set Text
s else Text -> Set Text -> Set Text
forall a. Ord a => a -> Set a -> Set a
S.delete Text
a Set Text
s
        anyrowmatches :: Bool
anyrowmatches
          | Bool -> Bool
not Bool
hasrowterms = Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ [(Posting, Posting)] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [(Posting, Posting)]
now
          | Bool -> Bool
not Bool
hasbalanceq = (MixedAmount -> Bool) -> Map Text MixedAmount -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any MixedAmount -> Bool
changeMatches Map Text MixedAmount
changes
          | Bool -> Bool
not Bool
haschangeq  = Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ Set Text -> Bool
forall a. Set a -> Bool
S.null Set Text
matching'
          | Bool
otherwise       = ((Text, MixedAmount) -> Bool) -> [(Text, MixedAmount)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\(Text
a, MixedAmount
chg) -> Text
a Text -> Set Text -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.member` Set Text
matching' Bool -> Bool -> Bool
&& MixedAmount -> Bool
changeMatches MixedAmount
chg) (Map Text MixedAmount -> [(Text, MixedAmount)]
forall k a. Map k a -> [(k, a)]
M.toList Map Text MixedAmount
changes)
                              Bool -> Bool -> Bool
|| (Bool
zerochangematches Bool -> Bool -> Bool
&& (Text -> Bool) -> [Text] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Text -> Map Text MixedAmount -> Bool
forall k a. Ord k => k -> Map k a -> Bool
`M.notMember` Map Text MixedAmount
changes) (Set Text -> [Text]
forall a. Set a -> [a]
S.toList Set Text
matching'))
        -- What matched here, for the error message, and how many (counted without listing them).
        nmatched :: Int
nmatched
          | Bool -> Bool
not Bool
hasrowterms = [(Posting, Posting)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(Posting, Posting)]
now
          | Bool -> Bool
not Bool
hasbalanceq = [MixedAmount] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ([MixedAmount] -> Int) -> [MixedAmount] -> Int
forall a b. (a -> b) -> a -> b
$ (MixedAmount -> Bool) -> [MixedAmount] -> [MixedAmount]
forall a. (a -> Bool) -> [a] -> [a]
filter MixedAmount -> Bool
changeMatches ([MixedAmount] -> [MixedAmount]) -> [MixedAmount] -> [MixedAmount]
forall a b. (a -> b) -> a -> b
$ Map Text MixedAmount -> [MixedAmount]
forall k a. Map k a -> [a]
M.elems Map Text MixedAmount
changes
          | Bool -> Bool
not Bool
haschangeq  = Set Text -> Int
forall a. Set a -> Int
S.size Set Text
matching'
          | Bool
otherwise       = [()] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [() | (Text
a, MixedAmount
chg) <- Map Text MixedAmount -> [(Text, MixedAmount)]
forall k a. Map k a -> [(k, a)]
M.toList Map Text MixedAmount
changes, Text
a Text -> Set Text -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.member` Set Text
matching', MixedAmount -> Bool
changeMatches MixedAmount
chg]
                              Int -> Int -> Int
forall a. Num a => a -> a -> a
+ (if Bool
zerochangematches then Set Text -> Int
forall a. Set a -> Int
S.size Set Text
matching' Int -> Int -> Int
forall a. Num a => a -> a -> a
- [Text] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ((Text -> Bool) -> [Text] -> [Text]
forall a. (a -> Bool) -> [a] -> [a]
filter (Text -> Set Text -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.member` Set Text
matching') ([Text] -> [Text]) -> [Text] -> [Text]
forall a b. (a -> b) -> a -> b
$ Map Text MixedAmount -> [Text]
forall k a. Map k a -> [k]
M.keys Map Text MixedAmount
changes) else Int
0)
        evidence :: Evidence
evidence
          | Bool -> Bool
not Bool
hasrowterms = [Posting] -> Evidence
MatchedPostings ([Posting] -> Evidence) -> [Posting] -> Evidence
forall a b. (a -> b) -> a -> b
$ ((Posting, Posting) -> Posting)
-> [(Posting, Posting)] -> [Posting]
forall a b. (a -> b) -> [a] -> [b]
map (Posting, Posting) -> Posting
forall a b. (a, b) -> a
fst [(Posting, Posting)]
now
          | Bool
hasbalanceq     = [(Text, MixedAmount, MixedAmount)] -> Evidence
MatchedRows [ (Text
a, MixedAmount
chg, MixedAmount
bal) | Text
a <- Set Text -> [Text]
forall a. Set a -> [a]
S.toAscList Set Text
matching'
                                          , let chg :: MixedAmount
chg = MixedAmount -> Text -> Map Text MixedAmount -> MixedAmount
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault MixedAmount
nullmixedamt Text
a Map Text MixedAmount
changes, MixedAmount -> Bool
changeMatches MixedAmount
chg
                                          , Just (RunningBalance MixedAmount
bal [Int]
_) <- [Text -> Map Text RunningBalance -> Maybe RunningBalance
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup Text
a Map Text RunningBalance
balances'] ]
          | Bool
otherwise       = [(Text, MixedAmount, MixedAmount)] -> Evidence
MatchedRows [ (Text
a, MixedAmount
chg, MixedAmount
nullmixedamt) | (Text
a, MixedAmount
chg) <- Map Text MixedAmount -> [(Text, MixedAmount)]
forall k a. Map k a -> [(k, a)]
M.toAscList Map Text MixedAmount
changes, MixedAmount -> Bool
changeMatches MixedAmount
chg ]

    -- Is this checkpoint skipped, because a skipped date is among the dates it examines ?
    -- A rule with balance: and no change: terms examines the period's last day (where the balance is tested);
    -- any other rule examines the whole period.
    isSkipped DateSpan
sp
      | [DateSpan] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [DateSpan]
skips = Bool
False
      | Bool
hasbalanceq Bool -> Bool -> Bool
&& Bool -> Bool
not Bool
haschangeq = Bool -> (Day -> Bool) -> Maybe Day -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False (\Day
e -> (DateSpan -> Bool) -> [DateSpan] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (DateSpan -> Day -> Bool
`spanContainsDate` Integer -> Day -> Day
addDays (-Integer
1) Day
e) [DateSpan]
skips) (Maybe Day -> Bool) -> Maybe Day -> Bool
forall a b. (a -> b) -> a -> b
$ DateSpan -> Maybe Day
spanEnd DateSpan
sp
      | Bool
otherwise = (DateSpan -> Bool) -> [DateSpan] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (DateSpan -> DateSpan -> Bool
spansOverlap DateSpan
sp) [DateSpan]
skips
    spansOverlap DateSpan
a DateSpan
b = case (DateSpan -> Maybe Day
spanStart DateSpan
i, DateSpan -> Maybe Day
spanEnd DateSpan
i) of
      (Just Day
s, Just Day
e) -> Day
s Day -> Day -> Bool
forall a. Ord a => a -> a -> Bool
< Day
e
      (Maybe Day, Maybe Day)
_                -> Bool
True
      where i :: DateSpan
i = DateSpan
a DateSpan -> DateSpan -> DateSpan
`spanIntersect` DateSpan
b

  case checkPeriods maxMatchesShown M.empty S.empty ps checkpoints of
    []       -> () -> Either FilePath ()
forall a b. b -> Either a b
Right ()
    [Failure]
failures -> FilePath -> Either FilePath ()
forall a b. a -> Either a b
Left (FilePath -> Either FilePath ()) -> FilePath -> Either FilePath ()
forall a b. (a -> b) -> a -> b
$ AssertDirective -> Query -> Int -> [Failure] -> FilePath
assertFailureMessage AssertDirective
ad Query
rowq ([DateSpan] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ([DateSpan] -> Int) -> [DateSpan] -> Int
forall a b. (a -> b) -> a -> b
$ (DateSpan -> Bool) -> [DateSpan] -> [DateSpan]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (DateSpan -> Bool) -> DateSpan -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. DateSpan -> Bool
isSkipped) [DateSpan]
checkpoints) [Failure]
failures

-- | The change: and balance: terms of a row query (see 'querySplitRowTerms'), each with whether it is negated.
signedRowTerms :: Query -> [(Bool, Query)]
signedRowTerms :: Query -> [(Bool, Query)]
signedRowTerms (And [Query]
qs) = (Query -> [(Bool, Query)]) -> [Query] -> [(Bool, Query)]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Query -> [(Bool, Query)]
signedRowTerms [Query]
qs
signedRowTerms (Not Query
q)  = [(Bool -> Bool
not Bool
neg, Query
t) | (Bool
neg, Query
t) <- Query -> [(Bool, Query)]
signedRowTerms Query
q]
signedRowTerms Query
q        = [(Bool
False, Query
q) | Query -> Bool
queryIsRowTerm Query
q]

-- | The first line(s) of an assert directive error: file position and excerpt.
errorPrefix :: AssertDirective -> String
errorPrefix :: AssertDirective -> FilePath
errorPrefix AssertDirective{adSourcePos :: AssertDirective -> SourcePos
adSourcePos=SourcePos FilePath
f Pos
l Pos
_, adSourceText :: AssertDirective -> Text
adSourceText=Text
txt} =
  FilePath -> FilePath -> Int -> Text -> FilePath
forall r. PrintfType r => FilePath -> r
printf FilePath
"%s:%d:\n%s\n" FilePath
f (Pos -> Int
unPos Pos
l) (Int -> Maybe (Int, Maybe Int) -> Text -> Text
decorateExcerpt (Pos -> Int
unPos Pos
l) Maybe (Int, Maybe Int)
forall a. Maybe a
Nothing (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$ Text
txt Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"\n")

-- | Explain an assert directive's failure, given its row query, its number of checkpoints, and the
-- failing checkpoints with what matched there: where it failed, which rows (changes, balances, or both)
-- or postings matched, up to a limit, or that none did, and the equivalent report command
-- (a balance report for rows, a register for postings), covering all the failing checkpoints.
assertFailureMessage :: AssertDirective -> Query -> Int -> [Failure] -> String
assertFailureMessage :: AssertDirective -> Query -> Int -> [Failure] -> FilePath
assertFailureMessage ad :: AssertDirective
ad@AssertDirective{adQuantifier :: AssertDirective -> AssertQuantifier
adQuantifier=AssertQuantifier
quant, adPeriod :: AssertDirective -> Maybe (Interval, DateSpan)
adPeriod=Maybe (Interval, DateSpan)
mperiod, adPeriodText :: AssertDirective -> Text
adPeriodText=Text
periodtxt, adQueryText :: AssertDirective -> Text
adQueryText=Text
querytxt}
                     Query
rowq Int
ncheckpoints [Failure]
failures =
  AssertDirective -> FilePath
errorPrefix AssertDirective
ad FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> Text -> FilePath
T.unpack ([Text] -> Text
T.unlines ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ [Text]
explanation [Text] -> [Text] -> [Text]
forall a. Semigroup a => a -> a -> a
<> [Text
reportline])
  where
    maxperiodsshown :: Int
maxperiodsshown = Int
5
    hasrowterms :: Bool
hasrowterms = Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ Query -> Bool
queryIsNull Query
rowq
    periodic :: Bool
periodic = Int
ncheckpoints Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1
    nfailed :: Int
nfailed = [Failure] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Failure]
failures

    -- What the matches are called, and the matches as table rows, from all failing checkpoints.
    -- Rows get a period column when there are several checkpoints (postings have their date).
    noun :: Text
noun | Bool
hasrowterms = Text
rowsnoun
         | Bool
otherwise   = Text
"postings"
    (Text
rowsnoun, MixedAmount -> MixedAmount -> [Text]
amountcells) = case (Query -> Bool
queryHasChange Query
rowq, Query -> Bool
queryHasBalance Query
rowq) of
      (Bool
True, Bool
False) -> (Text
"changes",  \MixedAmount
chg MixedAmount
_   -> [MixedAmount -> Text
showamt MixedAmount
chg])
      (Bool
False, Bool
_)    -> (Text
"balances", \MixedAmount
_ MixedAmount
bal   -> [MixedAmount -> Text
showamt MixedAmount
bal])
      (Bool
True, Bool
True)  -> (Text
"accounts", \MixedAmount
chg MixedAmount
bal -> [MixedAmount -> Text
showamt MixedAmount
chg, MixedAmount -> Text
showamt MixedAmount
bal])
    showamt :: MixedAmount -> Text
showamt = FilePath -> Text
T.pack (FilePath -> Text)
-> (MixedAmount -> FilePath) -> MixedAmount -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. MixedAmount -> FilePath
showMixedAmountOneLine
    tablerows :: [[Text]]
tablerows = ((Failure -> [[Text]]) -> [Failure] -> [[Text]])
-> [Failure] -> (Failure -> [[Text]]) -> [[Text]]
forall a b c. (a -> b -> c) -> b -> a -> c
flip (Failure -> [[Text]]) -> [Failure] -> [[Text]]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap [Failure]
failures ((Failure -> [[Text]]) -> [[Text]])
-> (Failure -> [[Text]]) -> [[Text]]
forall a b. (a -> b) -> a -> b
$ \(Failure DateSpan
sp Int
_ Evidence
ev) -> case Evidence
ev of
      MatchedRows [(Text, MixedAmount, MixedAmount)]
rows   -> [(if Bool
periodic then DateSpan -> Text
periodLabel DateSpan
sp else Text
"") Text -> [Text] -> [Text]
forall a. a -> [a] -> [a]
: Text
a Text -> [Text] -> [Text]
forall a. a -> [a] -> [a]
: MixedAmount -> MixedAmount -> [Text]
amountcells MixedAmount
chg MixedAmount
bal | (Text
a, MixedAmount
chg, MixedAmount
bal) <- [(Text, MixedAmount, MixedAmount)]
rows]
      MatchedPostings [Posting]
ps -> [ [Day -> Text
showDate (Day -> Text) -> Day -> Text
forall a b. (a -> b) -> a -> b
$ Posting -> Day
postingDate Posting
p, Maybe Int -> Maybe Int -> Bool -> Bool -> Text -> Text
fitText Maybe Int
forall a. Maybe a
Nothing (Int -> Maybe Int
forall a. a -> Maybe a
Just Int
30) Bool
True Bool
True Text
desc, Posting -> Text
paccount Posting
p, MixedAmount -> Text
showamt (MixedAmount -> Text) -> MixedAmount -> Text
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p]
                            | Posting
p <- [Posting]
ps, let desc :: Text
desc = Text -> (Transaction -> Text) -> Maybe Transaction -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" Transaction -> Text
tdescription (Maybe Transaction -> Text) -> Maybe Transaction -> Text
forall a b. (a -> b) -> a -> b
$ Posting -> Maybe Transaction
ptransaction Posting
p ]
    matchlines :: [Text]
matchlines = [Bool] -> [[Text]] -> [Text]
alignColumns (if Bool
hasrowterms then [Bool
False, Bool
False, Bool
True, Bool
True] else [Bool
False, Bool
False, Bool
False, Bool
True]) [[Text]]
tablerows
    nhidden :: Int
nhidden = [Int] -> Int
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Int
n | Failure DateSpan
_ Int
n Evidence
_ <- [Failure]
failures] Int -> Int -> Int
forall a. Num a => a -> a -> a
- [Text] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Text]
matchlines

    explanation :: [Text]
explanation = case AssertQuantifier
quant of
      AssertQuantifier
AssertNone ->
        (Text
"This assert directive failed " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
wherefailed Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
".")
        Text -> [Text] -> [Text]
forall a. a -> [a] -> [a]
: (Text
"These " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
noun Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" matched" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> (if Text
noun Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"accounts" then Text
" (change, balance)" else Text
"") Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
":")
        Text -> [Text] -> [Text]
forall a. a -> [a] -> [a]
: (Text -> Text) -> [Text] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Text
"  " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>) [Text]
matchlines
        [Text] -> [Text] -> [Text]
forall a. Semigroup a => a -> a -> a
<> [Text
"  ...and " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> FilePath -> Text
T.pack (Int -> FilePath
forall a. Show a => a -> FilePath
show Int
nhidden) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" more." | Int
nhidden Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0]
      AssertQuantifier
AssertSome
        | Bool
periodic  -> [Text
"This assert directive failed " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
wherefailed Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
".",
                        Text
"No " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
noun Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" matched in " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> (if Int
nfailed Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
1 then Text
"that period." else Text
"those periods.")]
        | Bool
otherwise -> [Text
"This assert directive failed " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
wherefailed Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
": no " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
noun Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" matched."]
    reportline :: Text
reportline = (if Int
nhidden Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0 then Text
"To see them all: " else Text
"To see the report: ") Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
reportcmd

    -- Where it failed: over the whole journal (or the date: terms' span), in its one period, or in some of its periods.
    wherefailed :: Text
wherefailed = case (Maybe (Interval, DateSpan)
mperiod, [Failure]
failures) of
      (Maybe (Interval, DateSpan)
Nothing, [Failure (DateSpan Maybe EFDay
Nothing Maybe EFDay
Nothing) Int
_ Evidence
_]) -> Text
"(checked over the whole journal)"
      (Maybe (Interval, DateSpan)
Nothing, [Failure DateSpan
sp Int
_ Evidence
_])                         -> Text
"(checked over the period " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> DateSpan -> Text
showDateSpan DateSpan
sp Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
")"
      (Maybe (Interval, DateSpan)
_, [Failure DateSpan
sp Int
_ Evidence
_]) | Bool -> Bool
not Bool
periodic                -> if DateSpan -> Bool
isOneDay DateSpan
sp then Text
"on " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> DateSpan -> Text
periodLabel DateSpan
sp else Text
"for the period " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> DateSpan -> Text
periodLabel DateSpan
sp
      (Maybe (Interval, DateSpan), [Failure])
_ -> Text
"in " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> FilePath -> Text
T.pack (Int -> FilePath
forall a. Show a => a -> FilePath
show Int
nfailed) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" of " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> FilePath -> Text
T.pack (Int -> FilePath
forall a. Show a => a -> FilePath
show Int
ncheckpoints) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" periods: "
           Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text -> [Text] -> Text
T.intercalate Text
", " ((Failure -> Text) -> [Failure] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Failure -> Text
failureLabel ([Failure] -> [Text]) -> [Failure] -> [Text]
forall a b. (a -> b) -> a -> b
$ Int -> [Failure] -> [Failure]
forall a. Int -> [a] -> [a]
take Int
maxperiodsshown [Failure]
failures)
           Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> (if Int
nfailed Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
maxperiodsshown then Text
" and " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> FilePath -> Text
T.pack (Int -> FilePath
forall a. Show a => a -> FilePath
show (Int -> FilePath) -> Int -> FilePath
forall a b. (a -> b) -> a -> b
$ Int
nfailed Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
maxperiodsshown) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" more" else Text
"")

    -- The report command, covering the failing checkpoints: from the start of the first to the end of the last.
    -- It has -I, since reading the journal would otherwise fail on this rule again.
    -- For a balance report covering several periods, it has the period expression's report interval
    -- (from its text; -b and -e override its dates), and leaves out the change:/balance: terms,
    -- since in a multi-period report those test each row's total, not each period.
    reportcmd :: Text
reportcmd = [Text] -> Text
T.unwords ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ [Text
"hledger"] [Text] -> [Text] -> [Text]
forall a. Semigroup a => a -> a -> a
<> [Text]
cmd [Text] -> [Text] -> [Text]
forall a. Semigroup a => a -> a -> a
<> [Text]
periodflags [Text] -> [Text] -> [Text]
forall a. Semigroup a => a -> a -> a
<> (Text -> Text) -> [Text] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Text
shellQuote [Text]
queryterms
    -- With balance: terms, -H makes bal show the balances which were tested, not the period's changes.
    cmd :: [Text]
cmd | Bool
hasrowterms = [Text
"bal", Text
"-I", Text
"-E"] [Text] -> [Text] -> [Text]
forall a. Semigroup a => a -> a -> a
<> [Text
"-H" | Query -> Bool
queryHasBalance Query
rowq]
        | Bool
otherwise   = [Text
"reg", Text
"-I"]
    multiperiod :: Bool
multiperiod = Bool
hasrowterms Bool -> Bool -> Bool
&& Int
nfailed Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1
    periodflags :: [Text]
periodflags = case Maybe (Interval, DateSpan)
mperiod of
      Maybe (Interval, DateSpan)
Nothing -> []
      Just (Interval, DateSpan)
_  -> [Text
"-p " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text -> Text
shellQuote Text
periodtxt | Bool
multiperiod]
                 [Text] -> [Text] -> [Text]
forall a. Semigroup a => a -> a -> a
<> Text -> Maybe Day -> [Text]
dateflag Text
"-b" (DateSpan -> Maybe Day
spanStart (DateSpan -> Maybe Day)
-> (Failure -> DateSpan) -> Failure -> Maybe Day
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Failure -> DateSpan
failureSpan (Failure -> Maybe Day) -> Maybe Failure -> Maybe Day
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< [Failure] -> Maybe Failure
forall a. [a] -> Maybe a
headMay [Failure]
failures)
                 [Text] -> [Text] -> [Text]
forall a. Semigroup a => a -> a -> a
<> Text -> Maybe Day -> [Text]
dateflag Text
"-e" (DateSpan -> Maybe Day
spanEnd (DateSpan -> Maybe Day)
-> (Failure -> DateSpan) -> Failure -> Maybe Day
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Failure -> DateSpan
failureSpan (Failure -> Maybe Day) -> Maybe Failure -> Maybe Day
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< [Failure] -> Maybe Failure
forall a. [a] -> Maybe a
lastMay [Failure]
failures)
    queryterms :: [Text]
queryterms = (Text -> Bool) -> [Text] -> [Text]
forall a. (a -> Bool) -> [a] -> [a]
filter (\Text
t -> Bool -> Bool
not (Text -> Bool
T.null Text
t) Bool -> Bool -> Bool
&& Bool -> Bool
not (Bool
multiperiod Bool -> Bool -> Bool
&& Text -> Bool
isRowTermText Text
t)) ([Text] -> [Text]) -> [Text] -> [Text]
forall a b. (a -> b) -> a -> b
$ [Text] -> Text -> [Text]
words'' [Text]
queryprefixes Text
querytxt
    isRowTermText :: Text -> Bool
isRowTermText Text
t = (Text -> Bool) -> [Text] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Text -> Text -> Bool
`T.isPrefixOf` Text -> Text
stripNots Text
t) [Text
"change:", Text
"balance:"]
    stripNots :: Text -> Text
stripNots Text
t = Text -> (Text -> Text) -> Maybe Text -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
t Text -> Text
stripNots (Maybe Text -> Text) -> Maybe Text -> Text
forall a b. (a -> b) -> a -> b
$ Text -> Text -> Maybe Text
T.stripPrefix Text
"not:" Text
t
    dateflag :: Text -> Maybe Day -> [Text]
dateflag Text
flag = [Text] -> (Day -> [Text]) -> Maybe Day -> [Text]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] (\Day
d -> [Text
flag, Day -> Text
showDate Day
d])
    failureSpan :: Failure -> DateSpan
failureSpan (Failure DateSpan
sp Int
_ Evidence
_) = DateSpan
sp
    failureLabel :: Failure -> Text
failureLabel = DateSpan -> Text
periodLabel (DateSpan -> Text) -> (Failure -> DateSpan) -> Failure -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Failure -> DateSpan
failureSpan

-- | The most matches an assert rule's error message shows.
maxMatchesShown :: Int
maxMatchesShown :: Int
maxMatchesShown = Int
10

-- | How a checkpoint is shown in an error message: as a date if it's one day, otherwise as a period.
periodLabel :: DateSpan -> Text
periodLabel :: DateSpan -> Text
periodLabel DateSpan
sp
  | DateSpan -> Bool
isOneDay DateSpan
sp = Text -> (Day -> Text) -> Maybe Day -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" Day -> Text
showDate (Maybe Day -> Text) -> Maybe Day -> Text
forall a b. (a -> b) -> a -> b
$ DateSpan -> Maybe Day
spanStart DateSpan
sp
  | Bool
otherwise   = DateSpan -> Text
showDateSpan DateSpan
sp

isOneDay :: DateSpan -> Bool
isOneDay :: DateSpan -> Bool
isOneDay DateSpan
sp = case (DateSpan -> Maybe Day
spanStart DateSpan
sp, DateSpan -> Maybe Day
spanEnd DateSpan
sp) of
  (Just Day
s, Just Day
e) -> Integer -> Day -> Day
addDays Integer
1 Day
s Day -> Day -> Bool
forall a. Eq a => a -> a -> Bool
== Day
e
  (Maybe Day, Maybe Day)
_                -> Bool
False

-- | Lay out a table as lines of text, with two spaces between columns,
-- each column left- or right-aligned (if its flag is true) to its widest cell.
-- Columns which are empty in every row are left out.
alignColumns :: [Bool] -> [[Text]] -> [Text]
alignColumns :: [Bool] -> [[Text]] -> [Text]
alignColumns [Bool]
rightaligns [[Text]]
rows = (Text -> Text) -> [Text] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Text
T.stripEnd ([Text] -> [Text]) -> [Text] -> [Text]
forall a b. (a -> b) -> a -> b
$ ([Text] -> Text) -> [[Text]] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Text -> [Text] -> Text
T.intercalate Text
"  ") ([[Text]] -> [Text]) -> [[Text]] -> [Text]
forall a b. (a -> b) -> a -> b
$ [[Text]] -> [[Text]]
forall a. [[a]] -> [[a]]
transpose
  [(Text -> Text) -> [Text] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Bool -> Int -> Text -> Text
pad Bool
right (Int -> Text -> Text) -> Int -> Text -> Text
forall a b. (a -> b) -> a -> b
$ (Int -> Int -> Int) -> Int -> [Int] -> Int
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
0 ([Int] -> Int) -> [Int] -> Int
forall a b. (a -> b) -> a -> b
$ (Text -> Int) -> [Text] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Int
forall a. HasChars a => a -> Int
realLength [Text]
col) [Text]
col | (Bool
right, [Text]
col) <- [Bool] -> [[Text]] -> [(Bool, [Text])]
forall a b. [a] -> [b] -> [(a, b)]
zip [Bool]
rightaligns ([[Text]] -> [(Bool, [Text])]) -> [[Text]] -> [(Bool, [Text])]
forall a b. (a -> b) -> a -> b
$ [[Text]] -> [[Text]]
forall a. [[a]] -> [[a]]
transpose [[Text]]
rows, (Text -> Bool) -> [Text] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Bool -> Bool
not (Bool -> Bool) -> (Text -> Bool) -> Text -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Bool
T.null) [Text]
col]
  where pad :: Bool -> Int -> Text -> Text
pad Bool
right Int
w = Maybe Int -> Maybe Int -> Bool -> Bool -> Text -> Text
fitText (Int -> Maybe Int
forall a. a -> Maybe a
Just Int
w) Maybe Int
forall a. Maybe a
Nothing Bool
False (Bool -> Bool
not Bool
right)

-- | Quote a query term for a shell command line, if needed.
shellQuote :: Text -> Text
shellQuote :: Text -> Text
shellQuote Text
t
  | Bool -> Bool
not (Text -> Bool
T.null Text
t) Bool -> Bool -> Bool
&& (Char -> Bool) -> Text -> Bool
T.all Char -> Bool
safe Text
t = Text
t
  | Bool
otherwise = Text
"'" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> HasCallStack => Text -> Text -> Text -> Text
Text -> Text -> Text -> Text
T.replace Text
"'" Text
"'\\''" Text
t Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"'"
  where safe :: Char -> Bool
safe Char
c = Char -> Bool
isAlphaNum Char
c Bool -> Bool -> Bool
|| Char
c Char -> FilePath -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` (FilePath
":._-/+=@,%" :: String)