-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | Core data types, parsers and functionality for the hledger accounting tools -- -- This is a reusable library containing hledger's core functionality. -- -- hledger is a cross-platform program for tracking money, time, or any -- other commodity, using double-entry accounting and a simple, editable -- file format. It is inspired by and largely compatible with ledger(1). -- hledger provides command-line, curses and web interfaces, and aims to -- be a reliable, practical tool for daily use. @package hledger-lib @version 1.13 -- | Basic color helpers for prettifying console output. module Hledger.Utils.Color -- | Wrap a string in ANSI codes to set and reset foreground colour. color :: ColorIntensity -> Color -> String -> String -- | Wrap a string in ANSI codes to set and reset background colour. bgColor :: ColorIntensity -> Color -> String -> String -- | ANSI's eight standard colors. They come in two intensities, which are -- controlled by ColorIntensity. Many terminals allow the colors -- of the standard palette to be customised, so that, for example, -- setSGR [ SetColor Foreground Vivid Green ] may not result in -- bright green characters. data Color Black :: Color Red :: Color Green :: Color Yellow :: Color Blue :: Color Magenta :: Color Cyan :: Color White :: Color -- | ANSI's standard colors come in two intensities data ColorIntensity Dull :: ColorIntensity Vivid :: ColorIntensity -- | UTF-8 aware string IO functions that will work across multiple -- platforms and GHC versions. Includes code from Text.Pandoc.UTF8 ((C) -- 2010 John MacFarlane). -- -- Example usage: -- -- import Prelude hiding -- (readFile,writeFile,appendFile,getContents,putStr,putStrLn) import -- UTF8IOCompat -- (readFile,writeFile,appendFile,getContents,putStr,putStrLn) import -- UTF8IOCompat -- (SystemString,fromSystemString,toSystemString,error',userError') -- -- 2013410 update: we now trust that current GHC versions & -- platforms do the right thing, so this file is a no-op and on its way -- to being removed. Not carefully tested. module Hledger.Utils.UTF8IOCompat -- | The readFile function reads a file and returns the contents of -- the file as a string. The file is read lazily, on demand, as with -- getContents. readFile :: FilePath -> IO String -- | The computation writeFile file str function writes the -- string str, to the file file. writeFile :: FilePath -> String -> IO () -- | The computation appendFile file str function appends -- the string str, to the file file. -- -- Note that writeFile and appendFile write a literal -- string to a file. To write a value of any printable type, as with -- print, use the show function to convert the value to a -- string first. -- --
-- main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]]) --appendFile :: FilePath -> String -> IO () -- | The getContents operation returns all user input as a single -- string, which is read lazily as it is needed (same as -- hGetContents stdin). getContents :: IO String -- | Computation hGetContents hdl returns the list of -- characters corresponding to the unread portion of the channel or file -- managed by hdl, which is put into an intermediate state, -- semi-closed. In this state, hdl is effectively closed, -- but items are read from hdl on demand and accumulated in a -- special list returned by hGetContents hdl. -- -- Any operation that fails because a handle is closed, also fails if a -- handle is semi-closed. The only exception is hClose. A -- semi-closed handle becomes closed: -- --
-- Journal -- a journal is read from one or more data files. It contains.. -- [Transaction] -- journal transactions (aka entries), which have date, cleared status, code, description and.. -- [Posting] -- multiple account postings, which have account name and amount -- [MarketPrice] -- historical market prices for commodities -- -- Ledger -- a ledger is derived from a journal, by applying a filter specification and doing some further processing. It contains.. -- Journal -- a filtered copy of the original journal, containing only the transactions and postings we are interested in -- [Account] -- all accounts, in tree order beginning with a "root" account", with their balances and sub/parent accounts ---- -- For more detailed documentation on each type, see the corresponding -- modules. module Hledger.Data.Types -- | A possibly incomplete date, whose missing parts will be filled from a -- reference date. A numeric year, month, and day of month, or the empty -- string for any of these. See the smartdate parser. type SmartDate = (String, String, String) data WhichDate PrimaryDate :: WhichDate SecondaryDate :: WhichDate data DateSpan DateSpan :: Maybe Day -> Maybe Day -> DateSpan type Year = Integer type Month = Int type Quarter = Int type YearWeek = Int type MonthWeek = Int type YearDay = Int type MonthDay = Int type WeekDay = Int data Period DayPeriod :: Day -> Period WeekPeriod :: Day -> Period MonthPeriod :: Year -> Month -> Period QuarterPeriod :: Year -> Quarter -> Period YearPeriod :: Year -> Period PeriodBetween :: Day -> Day -> Period PeriodFrom :: Day -> Period PeriodTo :: Day -> Period PeriodAll :: Period data Interval NoInterval :: Interval Days :: Int -> Interval Weeks :: Int -> Interval Months :: Int -> Interval Quarters :: Int -> Interval Years :: Int -> Interval DayOfMonth :: Int -> Interval WeekdayOfMonth :: Int -> Int -> Interval DayOfWeek :: Int -> Interval DayOfYear :: Int -> Int -> Interval type AccountName = Text data AccountType Asset :: AccountType Liability :: AccountType Equity :: AccountType Revenue :: AccountType Expense :: AccountType data AccountAlias BasicAlias :: AccountName -> AccountName -> AccountAlias RegexAlias :: Regexp -> Replacement -> AccountAlias data Side L :: Side R :: Side -- | The basic numeric type used in amounts. type Quantity = Decimal -- | An amount's price (none, per unit, or total) in another commodity. The -- price amount should always be positive. data Price NoPrice :: Price UnitPrice :: Amount -> Price TotalPrice :: Amount -> Price -- | Display style for an amount. data AmountStyle AmountStyle :: Side -> Bool -> !Int -> Maybe Char -> Maybe DigitGroupStyle -> AmountStyle -- | does the symbol appear on the left or the right ? [ascommodityside] :: AmountStyle -> Side -- | space between symbol and quantity ? [ascommodityspaced] :: AmountStyle -> Bool -- | number of digits displayed after the decimal point [asprecision] :: AmountStyle -> !Int -- | character used as decimal point: period or comma. Nothing means -- "unspecified, use default" [asdecimalpoint] :: AmountStyle -> Maybe Char -- | style for displaying digit groups, if any [asdigitgroups] :: AmountStyle -> Maybe DigitGroupStyle -- | A style for displaying digit groups in the integer part of a floating -- point number. It consists of the character used to separate groups -- (comma or period, whichever is not used as decimal point), and the -- size of each group, starting with the one nearest the decimal point. -- The last group size is assumed to repeat. Eg, comma between thousands -- is DigitGroups ',' [3]. data DigitGroupStyle DigitGroups :: Char -> [Int] -> DigitGroupStyle type CommoditySymbol = Text data Commodity Commodity :: CommoditySymbol -> Maybe AmountStyle -> Commodity [csymbol] :: Commodity -> CommoditySymbol [cformat] :: Commodity -> Maybe AmountStyle data Amount Amount :: CommoditySymbol -> Quantity -> Bool -> AmountStyle -> Price -> Amount [acommodity] :: Amount -> CommoditySymbol [aquantity] :: Amount -> Quantity -- | kludge: a flag marking this amount and posting as a multiplier in a -- TMPostingRule. In a regular Posting, should always be false. [aismultiplier] :: Amount -> Bool [astyle] :: Amount -> AmountStyle -- | the (fixed, transaction-specific) price for this amount, if any [aprice] :: Amount -> Price newtype MixedAmount Mixed :: [Amount] -> MixedAmount data PostingType RegularPosting :: PostingType VirtualPosting :: PostingType BalancedVirtualPosting :: PostingType type TagName = Text type TagValue = Text type Tag = (TagName, TagValue) " A tag name and (possibly empty) value." type DateTag = (TagName, Day) -- | The status of a transaction or posting, recorded with a status mark -- (nothing, !, or *). What these mean is ultimately user defined. data Status Unmarked :: Status Pending :: Status Cleared :: Status -- | The amount to compare an account's balance to, to verify that the -- history leading to a given point is correct or to set the account to a -- known value. data BalanceAssertion BalanceAssertion :: Amount -> Bool -> GenericSourcePos -> BalanceAssertion -- | the expected value of a particular commodity [baamount] :: BalanceAssertion -> Amount -- | whether the assertion is exclusive, and doesn't allow other -- commodities alongside baamount [baexact] :: BalanceAssertion -> Bool [baposition] :: BalanceAssertion -> GenericSourcePos data Posting Posting :: Maybe Day -> Maybe Day -> Status -> AccountName -> MixedAmount -> Text -> PostingType -> [Tag] -> Maybe BalanceAssertion -> Maybe Transaction -> Maybe Posting -> Posting -- | this posting's date, if different from the transaction's [pdate] :: Posting -> Maybe Day -- | this posting's secondary date, if different from the transaction's [pdate2] :: Posting -> Maybe Day [pstatus] :: Posting -> Status [paccount] :: Posting -> AccountName [pamount] :: Posting -> MixedAmount -- | this posting's comment lines, as a single non-indented multi-line -- string [pcomment] :: Posting -> Text [ptype] :: Posting -> PostingType -- | tag names and values, extracted from the comment [ptags] :: Posting -> [Tag] -- | optional: the expected balance in this commodity in the account after -- this posting [pbalanceassertion] :: Posting -> Maybe BalanceAssertion -- | this posting's parent transaction (co-recursive types). Tying this -- knot gets tedious, Maybe makes it easier/optional. [ptransaction] :: Posting -> Maybe Transaction -- | When this posting has been transformed in some way (eg its amount or -- price was inferred, or the account name was changed by a pivot or -- budget report), this references the original untransformed posting -- (which will have Nothing in this field). [porigin] :: Posting -> Maybe Posting -- | The position of parse errors (eg), like parsec's SourcePos but -- generic. data GenericSourcePos -- | file path, 1-based line number and 1-based column number. GenericSourcePos :: FilePath -> Int -> Int -> GenericSourcePos -- | file path, inclusive range of 1-based line numbers (first, last). JournalSourcePos :: FilePath -> (Int, Int) -> GenericSourcePos data Transaction Transaction :: Integer -> Text -> GenericSourcePos -> Day -> Maybe Day -> Status -> Text -> Text -> Text -> [Tag] -> [Posting] -> Transaction -- | this transaction's 1-based position in the transaction stream, or 0 -- when not available [tindex] :: Transaction -> Integer -- | any comment lines immediately preceding this transaction [tprecedingcomment] :: Transaction -> Text -- | the file position where the date starts [tsourcepos] :: Transaction -> GenericSourcePos [tdate] :: Transaction -> Day [tdate2] :: Transaction -> Maybe Day [tstatus] :: Transaction -> Status [tcode] :: Transaction -> Text [tdescription] :: Transaction -> Text -- | this transaction's comment lines, as a single non-indented multi-line -- string [tcomment] :: Transaction -> Text -- | tag names and values, extracted from the comment [ttags] :: Transaction -> [Tag] -- | this transaction's postings [tpostings] :: Transaction -> [Posting] -- | A transaction modifier rule. This has a query which matches postings -- in the journal, and a list of transformations to apply to those -- postings or their transactions. Currently there is one kind of -- transformation: the TMPostingRule, which adds a posting ("auto -- posting") to the transaction, optionally setting its amount to the -- matched posting's amount multiplied by a constant. data TransactionModifier TransactionModifier :: Text -> [TMPostingRule] -> TransactionModifier [tmquerytxt] :: TransactionModifier -> Text [tmpostingrules] :: TransactionModifier -> [TMPostingRule] nulltransactionmodifier :: TransactionModifier -- | A transaction modifier transformation, which adds an extra posting to -- the matched posting's transaction. Can be like a regular posting, or -- the amount can have the aismultiplier flag set, indicating that it's a -- multiplier for the matched posting's amount. type TMPostingRule = Posting -- | A periodic transaction rule, describing a transaction that recurs. data PeriodicTransaction PeriodicTransaction :: Text -> Interval -> DateSpan -> Status -> Text -> Text -> Text -> [Tag] -> [Posting] -> PeriodicTransaction -- | the period expression as written [ptperiodexpr] :: PeriodicTransaction -> Text -- | the interval at which this transaction recurs [ptinterval] :: PeriodicTransaction -> Interval -- | the (possibly unbounded) period during which this transaction recurs. -- Contains a whole number of intervals. [ptspan] :: PeriodicTransaction -> DateSpan -- | some of Transaction's fields [ptstatus] :: PeriodicTransaction -> Status [ptcode] :: PeriodicTransaction -> Text [ptdescription] :: PeriodicTransaction -> Text [ptcomment] :: PeriodicTransaction -> Text [pttags] :: PeriodicTransaction -> [Tag] [ptpostings] :: PeriodicTransaction -> [Posting] nullperiodictransaction :: PeriodicTransaction data TimeclockCode SetBalance :: TimeclockCode SetRequiredHours :: TimeclockCode In :: TimeclockCode Out :: TimeclockCode FinalOut :: TimeclockCode data TimeclockEntry TimeclockEntry :: GenericSourcePos -> TimeclockCode -> LocalTime -> AccountName -> Text -> TimeclockEntry [tlsourcepos] :: TimeclockEntry -> GenericSourcePos [tlcode] :: TimeclockEntry -> TimeclockCode [tldatetime] :: TimeclockEntry -> LocalTime [tlaccount] :: TimeclockEntry -> AccountName [tldescription] :: TimeclockEntry -> Text data MarketPrice MarketPrice :: Day -> CommoditySymbol -> Amount -> MarketPrice [mpdate] :: MarketPrice -> Day [mpcommodity] :: MarketPrice -> CommoditySymbol [mpamount] :: MarketPrice -> Amount -- | A Journal, containing transactions and various other things. The basic -- data model for hledger. -- -- This is used during parsing (as the type alias ParsedJournal), and -- then finalised/validated for use as a Journal. Some extra -- parsing-related fields are included for convenience, at least for now. -- In a ParsedJournal these are updated as parsing proceeds, in a Journal -- they represent the final state at end of parsing (used eg by the add -- command). data Journal Journal :: Maybe Year -> Maybe (CommoditySymbol, AmountStyle) -> [AccountName] -> [AccountAlias] -> [TimeclockEntry] -> [FilePath] -> [(AccountName, AccountDeclarationInfo)] -> Map AccountType [AccountName] -> Map CommoditySymbol Commodity -> Map CommoditySymbol AmountStyle -> [MarketPrice] -> [TransactionModifier] -> [PeriodicTransaction] -> [Transaction] -> Text -> [(FilePath, Text)] -> ClockTime -> Journal -- | the current default year, specified by the most recent Y directive (or -- current date) [jparsedefaultyear] :: Journal -> Maybe Year -- | the current default commodity and its format, specified by the most -- recent D directive [jparsedefaultcommodity] :: Journal -> Maybe (CommoditySymbol, AmountStyle) -- | the current stack of parent account names, specified by apply account -- directives [jparseparentaccounts] :: Journal -> [AccountName] -- | the current account name aliases in effect, specified by alias -- directives (& options ?) ,jparsetransactioncount :: Integer -- ^ -- the current count of transactions parsed so far (only journal format -- txns, currently) [jparsealiases] :: Journal -> [AccountAlias] -- | timeclock sessions which have not been clocked out [jparsetimeclockentries] :: Journal -> [TimeclockEntry] [jincludefilestack] :: Journal -> [FilePath] -- | Accounts declared by account directives, in parse order (after journal -- finalisation) [jdeclaredaccounts] :: Journal -> [(AccountName, AccountDeclarationInfo)] -- | Accounts whose type has been declared in account directives (usually 5 -- top-level accounts) [jdeclaredaccounttypes] :: Journal -> Map AccountType [AccountName] -- | commodities and formats declared by commodity directives [jcommodities] :: Journal -> Map CommoditySymbol Commodity -- | commodities and formats inferred from journal amounts TODO misnamed - -- jusedstyles [jinferredcommodities] :: Journal -> Map CommoditySymbol AmountStyle [jmarketprices] :: Journal -> [MarketPrice] [jtxnmodifiers] :: Journal -> [TransactionModifier] [jperiodictxns] :: Journal -> [PeriodicTransaction] [jtxns] :: Journal -> [Transaction] -- | any final trailing comments in the (main) journal file [jfinalcommentlines] :: Journal -> Text -- | the file path and raw text of the main and any included journal files. -- The main file is first, followed by any included files in the order -- encountered. [jfiles] :: Journal -> [(FilePath, Text)] -- | when this journal was last read from its file(s) [jlastreadtime] :: Journal -> ClockTime -- | A journal in the process of being parsed, not yet finalised. The data -- is partial, and list fields are in reverse order. type ParsedJournal = Journal -- | The id of a data format understood by hledger, eg journal or -- csv. The --output-format option selects one of these for -- output. type StorageFormat = String -- | Extra information about an account that can be derived from its -- account directive (and the other account directives). data AccountDeclarationInfo AccountDeclarationInfo :: Text -> [Tag] -> Int -> AccountDeclarationInfo -- | any comment lines following an account directive for this account [adicomment] :: AccountDeclarationInfo -> Text -- | tags extracted from the account comment, if any [aditags] :: AccountDeclarationInfo -> [Tag] -- | the order in which this account was declared, relative to other -- account declarations, during parsing (1..) [adideclarationorder] :: AccountDeclarationInfo -> Int nullaccountdeclarationinfo :: AccountDeclarationInfo -- | An account, with its balances, parent/subaccount relationships, etc. -- Only the name is required; the other fields are added when needed. data Account Account :: AccountName -> Maybe AccountDeclarationInfo -> [Account] -> Maybe Account -> Bool -> Int -> MixedAmount -> MixedAmount -> Account -- | this account's full name [aname] :: Account -> AccountName -- | optional extra info from account directives relationships in the tree [adeclarationinfo] :: Account -> Maybe AccountDeclarationInfo -- | this account's sub-accounts [asubs] :: Account -> [Account] -- | parent account [aparent] :: Account -> Maybe Account -- | used in the accounts report to label elidable parents balance -- information [aboring] :: Account -> Bool -- | the number of postings to this account [anumpostings] :: Account -> Int -- | this account's balance, excluding subaccounts [aebalance] :: Account -> MixedAmount -- | this account's balance, including subaccounts [aibalance] :: Account -> MixedAmount -- | Whether an account's balance is normally a positive number (in -- accounting terms, a debit balance) or a negative number (credit -- balance). Assets and expenses are normally positive (debit), while -- liabilities, equity and income are normally negative (credit). -- https://en.wikipedia.org/wiki/Normal_balance data NormalSign NormallyPositive :: NormalSign NormallyNegative :: NormalSign -- | A Ledger has the journal it derives from, and the accounts derived -- from that. Accounts are accessible both list-wise and tree-wise, since -- each one knows its parent and subs; the first account is the root of -- the tree and always exists. data Ledger Ledger :: Journal -> [Account] -> Ledger [ljournal] :: Ledger -> Journal [laccounts] :: Ledger -> [Account] instance GHC.Classes.Eq Hledger.Data.Types.NormalSign instance Data.Data.Data Hledger.Data.Types.NormalSign instance GHC.Show.Show Hledger.Data.Types.NormalSign instance GHC.Generics.Generic Hledger.Data.Types.Account instance Data.Data.Data Hledger.Data.Types.Account instance GHC.Generics.Generic Hledger.Data.Types.Journal instance Data.Data.Data Hledger.Data.Types.Journal instance GHC.Classes.Eq Hledger.Data.Types.Journal instance GHC.Generics.Generic Hledger.Data.Types.AccountDeclarationInfo instance Data.Data.Data Hledger.Data.Types.AccountDeclarationInfo instance GHC.Show.Show Hledger.Data.Types.AccountDeclarationInfo instance GHC.Classes.Eq Hledger.Data.Types.AccountDeclarationInfo instance GHC.Generics.Generic Hledger.Data.Types.MarketPrice instance Data.Data.Data Hledger.Data.Types.MarketPrice instance GHC.Classes.Ord Hledger.Data.Types.MarketPrice instance GHC.Classes.Eq Hledger.Data.Types.MarketPrice instance GHC.Generics.Generic Hledger.Data.Types.TimeclockEntry instance Data.Data.Data Hledger.Data.Types.TimeclockEntry instance GHC.Classes.Ord Hledger.Data.Types.TimeclockEntry instance GHC.Classes.Eq Hledger.Data.Types.TimeclockEntry instance GHC.Generics.Generic Hledger.Data.Types.TimeclockCode instance Data.Data.Data Hledger.Data.Types.TimeclockCode instance GHC.Classes.Ord Hledger.Data.Types.TimeclockCode instance GHC.Classes.Eq Hledger.Data.Types.TimeclockCode instance GHC.Generics.Generic Hledger.Data.Types.PeriodicTransaction instance Data.Data.Data Hledger.Data.Types.PeriodicTransaction instance GHC.Classes.Eq Hledger.Data.Types.PeriodicTransaction instance GHC.Show.Show Hledger.Data.Types.TransactionModifier instance GHC.Generics.Generic Hledger.Data.Types.TransactionModifier instance Data.Data.Data Hledger.Data.Types.TransactionModifier instance GHC.Classes.Eq Hledger.Data.Types.TransactionModifier instance GHC.Generics.Generic Hledger.Data.Types.Posting instance Data.Data.Data Hledger.Data.Types.Posting instance GHC.Show.Show Hledger.Data.Types.Transaction instance GHC.Generics.Generic Hledger.Data.Types.Transaction instance Data.Data.Data Hledger.Data.Types.Transaction instance GHC.Classes.Eq Hledger.Data.Types.Transaction instance GHC.Show.Show Hledger.Data.Types.BalanceAssertion instance GHC.Generics.Generic Hledger.Data.Types.BalanceAssertion instance Data.Data.Data Hledger.Data.Types.BalanceAssertion instance GHC.Classes.Eq Hledger.Data.Types.BalanceAssertion instance GHC.Generics.Generic Hledger.Data.Types.GenericSourcePos instance Data.Data.Data Hledger.Data.Types.GenericSourcePos instance GHC.Classes.Ord Hledger.Data.Types.GenericSourcePos instance GHC.Show.Show Hledger.Data.Types.GenericSourcePos instance GHC.Read.Read Hledger.Data.Types.GenericSourcePos instance GHC.Classes.Eq Hledger.Data.Types.GenericSourcePos instance GHC.Generics.Generic Hledger.Data.Types.Status instance Data.Data.Data Hledger.Data.Types.Status instance GHC.Enum.Enum Hledger.Data.Types.Status instance GHC.Enum.Bounded Hledger.Data.Types.Status instance GHC.Classes.Ord Hledger.Data.Types.Status instance GHC.Classes.Eq Hledger.Data.Types.Status instance GHC.Generics.Generic Hledger.Data.Types.PostingType instance Data.Data.Data Hledger.Data.Types.PostingType instance GHC.Show.Show Hledger.Data.Types.PostingType instance GHC.Classes.Eq Hledger.Data.Types.PostingType instance GHC.Show.Show Hledger.Data.Types.MixedAmount instance GHC.Generics.Generic Hledger.Data.Types.MixedAmount instance Data.Data.Data Hledger.Data.Types.MixedAmount instance GHC.Classes.Ord Hledger.Data.Types.MixedAmount instance GHC.Classes.Eq Hledger.Data.Types.MixedAmount instance GHC.Show.Show Hledger.Data.Types.Price instance GHC.Generics.Generic Hledger.Data.Types.Price instance Data.Data.Data Hledger.Data.Types.Price instance GHC.Classes.Ord Hledger.Data.Types.Price instance GHC.Classes.Eq Hledger.Data.Types.Price instance GHC.Show.Show Hledger.Data.Types.Amount instance GHC.Generics.Generic Hledger.Data.Types.Amount instance Data.Data.Data Hledger.Data.Types.Amount instance GHC.Classes.Ord Hledger.Data.Types.Amount instance GHC.Classes.Eq Hledger.Data.Types.Amount instance GHC.Generics.Generic Hledger.Data.Types.Commodity instance Data.Data.Data Hledger.Data.Types.Commodity instance GHC.Classes.Eq Hledger.Data.Types.Commodity instance GHC.Show.Show Hledger.Data.Types.Commodity instance GHC.Generics.Generic Hledger.Data.Types.AmountStyle instance Data.Data.Data Hledger.Data.Types.AmountStyle instance GHC.Read.Read Hledger.Data.Types.AmountStyle instance GHC.Classes.Ord Hledger.Data.Types.AmountStyle instance GHC.Classes.Eq Hledger.Data.Types.AmountStyle instance GHC.Generics.Generic Hledger.Data.Types.DigitGroupStyle instance Data.Data.Data Hledger.Data.Types.DigitGroupStyle instance GHC.Show.Show Hledger.Data.Types.DigitGroupStyle instance GHC.Read.Read Hledger.Data.Types.DigitGroupStyle instance GHC.Classes.Ord Hledger.Data.Types.DigitGroupStyle instance GHC.Classes.Eq Hledger.Data.Types.DigitGroupStyle instance GHC.Generics.Generic Hledger.Data.Types.Side instance Data.Data.Data Hledger.Data.Types.Side instance GHC.Classes.Ord Hledger.Data.Types.Side instance GHC.Read.Read Hledger.Data.Types.Side instance GHC.Show.Show Hledger.Data.Types.Side instance GHC.Classes.Eq Hledger.Data.Types.Side instance GHC.Generics.Generic Hledger.Data.Types.AccountAlias instance Data.Data.Data Hledger.Data.Types.AccountAlias instance GHC.Classes.Ord Hledger.Data.Types.AccountAlias instance GHC.Show.Show Hledger.Data.Types.AccountAlias instance GHC.Read.Read Hledger.Data.Types.AccountAlias instance GHC.Classes.Eq Hledger.Data.Types.AccountAlias instance GHC.Generics.Generic Hledger.Data.Types.AccountType instance Data.Data.Data Hledger.Data.Types.AccountType instance GHC.Classes.Ord Hledger.Data.Types.AccountType instance GHC.Classes.Eq Hledger.Data.Types.AccountType instance GHC.Show.Show Hledger.Data.Types.AccountType instance GHC.Generics.Generic Hledger.Data.Types.Interval instance Data.Data.Data Hledger.Data.Types.Interval instance GHC.Classes.Ord Hledger.Data.Types.Interval instance GHC.Show.Show Hledger.Data.Types.Interval instance GHC.Classes.Eq Hledger.Data.Types.Interval instance GHC.Generics.Generic Hledger.Data.Types.Period instance Data.Data.Data Hledger.Data.Types.Period instance GHC.Show.Show Hledger.Data.Types.Period instance GHC.Classes.Ord Hledger.Data.Types.Period instance GHC.Classes.Eq Hledger.Data.Types.Period instance GHC.Generics.Generic Hledger.Data.Types.DateSpan instance Data.Data.Data Hledger.Data.Types.DateSpan instance GHC.Classes.Ord Hledger.Data.Types.DateSpan instance GHC.Classes.Eq Hledger.Data.Types.DateSpan instance GHC.Show.Show Hledger.Data.Types.WhichDate instance GHC.Classes.Eq Hledger.Data.Types.WhichDate instance Data.Data.Data (Data.Decimal.DecimalRaw GHC.Integer.Type.Integer) instance Data.Data.Data System.Time.ClockTime instance GHC.Generics.Generic System.Time.ClockTime instance Control.DeepSeq.NFData Hledger.Data.Types.Journal instance Control.DeepSeq.NFData Hledger.Data.Types.AccountDeclarationInfo instance Control.DeepSeq.NFData Hledger.Data.Types.MarketPrice instance Control.DeepSeq.NFData Hledger.Data.Types.TimeclockEntry instance Control.DeepSeq.NFData Hledger.Data.Types.TimeclockCode instance Control.DeepSeq.NFData Hledger.Data.Types.PeriodicTransaction instance Control.DeepSeq.NFData Hledger.Data.Types.TransactionModifier instance Control.DeepSeq.NFData Hledger.Data.Types.Posting instance GHC.Classes.Eq Hledger.Data.Types.Posting instance GHC.Show.Show Hledger.Data.Types.Posting instance Control.DeepSeq.NFData Hledger.Data.Types.Transaction instance Control.DeepSeq.NFData Hledger.Data.Types.BalanceAssertion instance Control.DeepSeq.NFData Hledger.Data.Types.GenericSourcePos instance Control.DeepSeq.NFData Hledger.Data.Types.Status instance GHC.Show.Show Hledger.Data.Types.Status instance Control.DeepSeq.NFData Hledger.Data.Types.PostingType instance Control.DeepSeq.NFData Hledger.Data.Types.MixedAmount instance Control.DeepSeq.NFData Hledger.Data.Types.Price instance Control.DeepSeq.NFData Hledger.Data.Types.Amount instance Control.DeepSeq.NFData Hledger.Data.Types.Commodity instance Control.DeepSeq.NFData Hledger.Data.Types.AmountStyle instance GHC.Show.Show Hledger.Data.Types.AmountStyle instance Control.DeepSeq.NFData Hledger.Data.Types.DigitGroupStyle instance Text.Blaze.ToMarkup Hledger.Data.Types.Quantity instance Control.DeepSeq.NFData Hledger.Data.Types.Side instance Control.DeepSeq.NFData Hledger.Data.Types.AccountAlias instance Control.DeepSeq.NFData Hledger.Data.Types.AccountType instance Data.Default.Class.Default Hledger.Data.Types.Interval instance Control.DeepSeq.NFData Hledger.Data.Types.Interval instance Data.Default.Class.Default Hledger.Data.Types.Period instance Data.Default.Class.Default Hledger.Data.Types.DateSpan instance Control.DeepSeq.NFData Hledger.Data.Types.DateSpan instance Control.DeepSeq.NFData System.Time.ClockTime -- | Manipulate the time periods typically used for reports with Period, a -- richer abstraction than DateSpan. See also Types and Dates. module Hledger.Data.Period -- | Convert Periods to DateSpans. -- --
-- >>> periodAsDateSpan (MonthPeriod 2000 1) == DateSpan (Just $ fromGregorian 2000 1 1) (Just $ fromGregorian 2000 2 1) -- True --periodAsDateSpan :: Period -> DateSpan -- | Convert DateSpans to Periods. -- --
-- >>> dateSpanAsPeriod $ DateSpan (Just $ fromGregorian 2000 1 1) (Just $ fromGregorian 2000 2 1) -- MonthPeriod 2000 1 --dateSpanAsPeriod :: DateSpan -> Period -- | Convert PeriodBetweens to a more abstract period where possible. -- --
-- >>> simplifyPeriod $ PeriodBetween (fromGregorian 1 1 1) (fromGregorian 2 1 1) -- YearPeriod 1 -- -- >>> simplifyPeriod $ PeriodBetween (fromGregorian 2000 10 1) (fromGregorian 2001 1 1) -- QuarterPeriod 2000 4 -- -- >>> simplifyPeriod $ PeriodBetween (fromGregorian 2000 2 1) (fromGregorian 2000 3 1) -- MonthPeriod 2000 2 -- -- >>> simplifyPeriod $ PeriodBetween (fromGregorian 2016 7 25) (fromGregorian 2016 8 1) -- WeekPeriod 2016-07-25 -- -- >>> simplifyPeriod $ PeriodBetween (fromGregorian 2000 1 1) (fromGregorian 2000 1 2) -- DayPeriod 2000-01-01 -- -- >>> simplifyPeriod $ PeriodBetween (fromGregorian 2000 2 28) (fromGregorian 2000 3 1) -- PeriodBetween 2000-02-28 2000-03-01 -- -- >>> simplifyPeriod $ PeriodBetween (fromGregorian 2000 2 29) (fromGregorian 2000 3 1) -- DayPeriod 2000-02-29 -- -- >>> simplifyPeriod $ PeriodBetween (fromGregorian 2000 12 31) (fromGregorian 2001 1 1) -- DayPeriod 2000-12-31 --simplifyPeriod :: Period -> Period isLastDayOfMonth :: (Eq a1, Eq a2, Num a1, Num a2) => Integer -> a1 -> a2 -> Bool -- | Is this period a "standard" period, referencing a particular day, -- week, month, quarter, or year ? Periods of other durations, or -- infinite duration, or not starting on a standard period boundary, are -- not. isStandardPeriod :: Period -> Bool -- | Render a period as a compact display string suitable for user output. -- --
-- >>> showPeriod (WeekPeriod (fromGregorian 2016 7 25)) -- "2016/07/25w30" --showPeriod :: Period -> String -- | Like showPeriod, but if it's a month period show just the 3 letter -- month name abbreviation for the current locale. showPeriodMonthAbbrev :: Period -> String periodStart :: Period -> Maybe Day periodEnd :: Period -> Maybe Day -- | Move a standard period to the following period of same duration. -- Non-standard periods are unaffected. periodNext :: Period -> Period -- | Move a standard period to the preceding period of same duration. -- Non-standard periods are unaffected. periodPrevious :: Period -> Period -- | Move a standard period to the following period of same duration, -- staying within enclosing dates. Non-standard periods are unaffected. periodNextIn :: DateSpan -> Period -> Period -- | Move a standard period to the preceding period of same duration, -- staying within enclosing dates. Non-standard periods are unaffected. periodPreviousIn :: DateSpan -> Period -> Period -- | Move a standard period stepwise so that it encloses the given date. -- Non-standard periods are unaffected. periodMoveTo :: Day -> Period -> Period -- | Enlarge a standard period to the next larger enclosing standard -- period, if there is one. Eg, a day becomes the enclosing week. A week -- becomes whichever month the week's thursday falls into. A year becomes -- all (unlimited). Non-standard periods (arbitrary dates, or open-ended) -- are unaffected. periodGrow :: Period -> Period -- | Shrink a period to the next smaller standard period inside it, -- choosing the subperiod which contains today's date if possible, -- otherwise the first subperiod. It goes like this: unbounded periods -- and nonstandard periods (between two arbitrary dates) -> current -- year -> current quarter if it's in selected year, otherwise first -- quarter of selected year -> current month if it's in selected -- quarter, otherwise first month of selected quarter -> current week -- if it's in selected month, otherwise first week of selected month -- -> today if it's in selected week, otherwise first day of selected -- week, unless that's in previous month, in which case first day of -- month containing selected week. Shrinking a day has no effect. periodShrink :: Day -> Period -> Period mondayBefore :: Day -> Day yearMonthContainingWeekStarting :: Day -> (Integer, Int) quarterContainingMonth :: Integral a => a -> a firstMonthOfQuarter :: Num a => a -> a startOfFirstWeekInMonth :: Integer -> Int -> Day module Hledger.Utils.Parse -- | A parser of string to some type. type SimpleStringParser a = Parsec CustomErr String a -- | A parser of strict text to some type. type SimpleTextParser = Parsec CustomErr Text -- | A parser of text in some monad. type TextParser m a = ParsecT CustomErr Text m a -- | A parser of text in some monad, with a journal as state. type JournalParser m a = StateT Journal (ParsecT CustomErr Text m) a -- | A parser of text in some monad, with a journal as state, that can -- throw a "final" parse error that does not backtrack. type ErroringJournalParser m a = StateT Journal (ParsecT CustomErr Text (ExceptT FinalParseError m)) a -- | Backtracking choice, use this when alternatives share a prefix. -- Consumes no input if all choices fail. choice' :: [TextParser m a] -> TextParser m a -- | Backtracking choice, use this when alternatives share a prefix. -- Consumes no input if all choices fail. choiceInState :: [StateT s (ParsecT CustomErr Text m) a] -> StateT s (ParsecT CustomErr Text m) a surroundedBy :: Applicative m => m openclose -> m a -> m a parsewith :: Parsec e Text a -> Text -> Either (ParseErrorBundle Text e) a parsewithString :: Parsec e String a -> String -> Either (ParseErrorBundle String e) a -- | Run a stateful parser with some initial state on a text. See also: -- runTextParser, runJournalParser. parseWithState :: Monad m => st -> StateT st (ParsecT CustomErr Text m) a -> Text -> m (Either (ParseErrorBundle Text CustomErr) a) parseWithState' :: Stream s => st -> StateT st (ParsecT e s Identity) a -> s -> Either (ParseErrorBundle s e) a fromparse :: (Show t, Show (Token t), Show e) => Either (ParseErrorBundle t e) a -> a parseerror :: (Show t, Show (Token t), Show e) => ParseErrorBundle t e -> a showDateParseError :: (Show t, Show (Token t), Show e) => ParseErrorBundle t e -> String nonspace :: TextParser m Char isNonNewlineSpace :: Char -> Bool spacenonewline :: (Stream s, Char ~ Token s) => ParsecT CustomErr s m Char restofline :: TextParser m String eolof :: TextParser m () -- | A custom error type for the parser. The type is specialized to parsers -- of Text streams. data CustomErr -- | String formatting helpers, starting to get a bit out of control. module Hledger.Utils.String lowercase :: String -> String uppercase :: String -> String underline :: String -> String stripbrackets :: String -> String unbracket :: String -> String -- | Double-quote this string if it contains whitespace, single quotes or -- double-quotes, escaping the quotes as needed. quoteIfNeeded :: String -> String -- | Single-quote this string if it contains whitespace or double-quotes. -- No good for strings containing single quotes. singleQuoteIfNeeded :: String -> String escapeQuotes :: String -> String -- | Quote-aware version of words - don't split on spaces which are inside -- quotes. NB correctly handles "a'b" but not "'a'". Can raise -- an error if parsing fails. words' :: String -> [String] -- | Quote-aware version of unwords - single-quote strings which contain -- whitespace unwords' :: [String] -> String stripAnsi :: String -> String -- | Remove leading and trailing whitespace. strip :: String -> String -- | Remove leading whitespace. lstrip :: String -> String -- | Remove trailing whitespace. rstrip :: String -> String -- | Remove trailing newlines/carriage returns. chomp :: String -> String elideLeft :: Int -> String -> String elideRight :: Int -> String -> String -- | Clip and pad a string to a minimum & maximum width, andor -- leftright justify it. Works on multi-line strings too (but will -- rewrite non-unix line endings). formatString :: Bool -> Maybe Int -> Maybe Int -> String -> String -- | Join several multi-line strings as side-by-side rectangular strings of -- the same height, top-padded. Treats wide characters as double width. concatTopPadded :: [String] -> String -- | Join several multi-line strings as side-by-side rectangular strings of -- the same height, bottom-padded. Treats wide characters as double -- width. concatBottomPadded :: [String] -> String -- | Join multi-line strings horizontally, after compressing each of them -- to a single line with a comma and space between each original line. concatOneLine :: [String] -> String -- | Join strings vertically, left-aligned and right-padded. vConcatLeftAligned :: [String] -> String -- | Join strings vertically, right-aligned and left-padded. vConcatRightAligned :: [String] -> String -- | Convert a multi-line string to a rectangular string top-padded to the -- specified height. padtop :: Int -> String -> String -- | Convert a multi-line string to a rectangular string bottom-padded to -- the specified height. padbottom :: Int -> String -> String -- | Convert a multi-line string to a rectangular string left-padded to the -- specified width. Treats wide characters as double width. padleft :: Int -> String -> String -- | Convert a multi-line string to a rectangular string right-padded to -- the specified width. Treats wide characters as double width. padright :: Int -> String -> String -- | Clip a multi-line string to the specified width and height from the -- top left. cliptopleft :: Int -> Int -> String -> String -- | Clip and pad a multi-line string to fill the specified width and -- height. fitto :: Int -> Int -> String -> String -- | Get the designated render width of a character: 0 for a combining -- character, 1 for a regular character, 2 for a wide character. (Wide -- characters are rendered as exactly double width in apps and fonts that -- support it.) (From Pandoc.) charWidth :: Char -> Int -- | Calculate the render width of a string, considering wide characters -- (counted as double width), ANSI escape codes (not counted), and line -- breaks (in a multi-line string, the longest line determines the -- width). strWidth :: String -> Int -- | Double-width-character-aware string truncation. Take as many -- characters as possible from a string without exceeding the specified -- width. Eg takeWidth 3 "りんご" = "り". takeWidth :: Int -> String -> String -- | General-purpose wide-char-aware single-line string layout function. It -- can left- or right-pad a short string to a minimum width. It can left- -- or right-clip a long string to a maximum width, optionally inserting -- an ellipsis (the third argument). It clips and pads on the right when -- the fourth argument is true, otherwise on the left. It treats wide -- characters as double width. fitString :: Maybe Int -> Maybe Int -> Bool -> Bool -> String -> String -- | A version of fitString that works on multi-line strings, separate for -- now to avoid breakage. This will rewrite any line endings to unix -- newlines. fitStringMulti :: Maybe Int -> Maybe Int -> Bool -> Bool -> String -> String -- | Left-pad a string to the specified width. Treats wide characters as -- double width. Works on multi-line strings too (but will rewrite -- non-unix line endings). padLeftWide :: Int -> String -> String -- | Right-pad a string to the specified width. Treats wide characters as -- double width. Works on multi-line strings too (but will rewrite -- non-unix line endings). padRightWide :: Int -> String -> String -- | Debugging helpers module Hledger.Utils.Debug -- | Pretty print. Easier alias for pretty-show's pPrint. pprint :: Show a => a -> IO () -- | Pretty show. Easier alias for pretty-show's ppShow. pshow :: Show a => a -> String -- | Pretty trace. Easier alias for traceShowId + ppShow. ptrace :: Show a => a -> a -- | Trace (print to stderr) a showable value using a custom show function. traceWith :: (a -> String) -> a -> a -- | Global debug level, which controls the verbosity of debug output on -- the console. The default is 0 meaning no debug output. The -- --debug command line flag sets it to 1, or --debug=N -- sets it to a higher value (note: not --debug N for some -- reason). This uses unsafePerformIO and can be accessed from anywhere -- and before normal command-line processing. When running with :main in -- GHCI, you must touch and reload this module to see the effect of a new -- --debug option. After command-line processing, it is also available as -- the debug_ field of CliOpts. {--} {--} debugLevel :: Int -- | Pretty-print a label and a showable value to the console if the global -- debug level is at or above the specified level. At level 0, always -- prints. Otherwise, uses unsafePerformIO. ptraceAt :: Show a => Int -> String -> a -> a -- | Pretty-print a message and the showable value to the console, then -- return it. dbg0 :: Show a => String -> a -> a -- | Like dbg0, but also exit the program. Uses unsafePerformIO. dbgExit :: Show a => String -> a -> a -- | Pretty-print a message and the showable value to the console when the -- global debug level is >= 1, then return it. Uses unsafePerformIO. dbg1 :: Show a => String -> a -> a dbg2 :: Show a => String -> a -> a dbg3 :: Show a => String -> a -> a dbg4 :: Show a => String -> a -> a dbg5 :: Show a => String -> a -> a dbg6 :: Show a => String -> a -> a dbg7 :: Show a => String -> a -> a dbg8 :: Show a => String -> a -> a dbg9 :: Show a => String -> a -> a -- | Like ptraceAt, but convenient to insert in an IO monad (plus -- convenience aliases). XXX These have a bug; they should use traceIO, -- not trace, otherwise GHC can occasionally over-optimise (cf lpaste a -- few days ago where it killed/blocked a child thread). ptraceAtIO :: (MonadIO m, Show a) => Int -> String -> a -> m () dbg0IO :: (MonadIO m, Show a) => String -> a -> m () dbg1IO :: (MonadIO m, Show a) => String -> a -> m () dbg2IO :: (MonadIO m, Show a) => String -> a -> m () dbg3IO :: (MonadIO m, Show a) => String -> a -> m () dbg4IO :: (MonadIO m, Show a) => String -> a -> m () dbg5IO :: (MonadIO m, Show a) => String -> a -> m () dbg6IO :: (MonadIO m, Show a) => String -> a -> m () dbg7IO :: (MonadIO m, Show a) => String -> a -> m () dbg8IO :: (MonadIO m, Show a) => String -> a -> m () dbg9IO :: (MonadIO m, Show a) => String -> a -> m () -- | Log a message and a pretty-printed showable value to ./debug.log, then -- return it. Can fail, see plogAt. plog :: Show a => String -> a -> a -- | Log a message and a pretty-printed showable value to ./debug.log, if -- the global debug level is at or above the specified level. At level 0, -- always logs. Otherwise, uses unsafePerformIO. Tends to fail if called -- more than once, at least when built with -threaded (Exception: -- debug.log: openFile: resource busy (file is locked)). plogAt :: Show a => Int -> String -> a -> a -- | Print the provided label (if non-null) and current parser state -- (position and next input) to the console. (See also megaparsec's dbg.) traceParse :: String -> TextParser m () -- | Convenience alias for traceParseAt dbgparse :: Int -> String -> TextParser m () module Hledger.Utils.Test -- | Request a CallStack. -- -- NOTE: The implicit parameter ?callStack :: CallStack is an -- implementation detail and should not be considered part of the -- CallStack API, we may decide to change the implementation in -- the future. type HasCallStack = ?callStack :: CallStack -- | Run a test in a separate thread, return a future which can be used to -- block on its result. fork' :: () => Test a -> Test (Test a) -- | Run a test in a separate thread, not blocking for its result. fork :: () => Test a -> Test () -- | Explicitly skip this test skip :: Test () -- | Record a successful test at the current scope ok :: Test () -- | Log a showable value note' :: Show s => s -> Test () -- | Rerun all tests with the given seed rerun :: () => Int -> Test a -> IO () -- | Run all tests run :: () => Test a -> IO () -- | Rerun all tests with the given seed and whose scope starts with the -- given prefix rerunOnly :: () => Int -> Text -> Test a -> IO () -- | Run all tests whose scope starts with the given prefix runOnly :: () => Text -> Test a -> IO () -- | A test with a setup and teardown using :: () => IO r -> (r -> IO ()) -> (r -> Test a) -> Test a expectEq :: (Eq a, Show a, HasCallStack) => a -> a -> Test () expectLeftNoShow :: HasCallStack => Either e a -> Test () expectLeft :: (Show a, HasCallStack) => Either e a -> Test () expectRightNoShow :: HasCallStack => Either e a -> Test () expectRight :: (Show e, HasCallStack) => Either e a -> Test () expectJust :: HasCallStack => Maybe a -> Test () expect :: HasCallStack -> Bool -> Test () -- | Convenient alias for liftIO io :: () => IO a -> Test a -- | Generate a [Data.Map k v] of the given sizes. mapsOf :: Ord k => [Int] -> Test k -> Test v -> Test [Map k v] -- | Generate a Data.Map k v of the given size. mapOf :: Ord k => Int -> Test k -> Test v -> Test (Map k v) -- | Alias for liftA2 (,). pair :: () => Test a -> Test b -> Test (a, b) -- | Generate a list of lists of the given sizes, an alias for sizes -- `forM` \n -> listOf n gen listsOf :: () => [Int] -> Test a -> Test [[a]] -- | Alias for replicateM listOf :: () => Int -> Test a -> Test [a] -- | Sample uniformly from the given list of possibilities pick :: () => [a] -> Test a -- | Generate a random Double in the given range Note: word8' 0 -- 10 includes both 0 and 10. word8' :: Word8 -> Word8 -> Test Word8 -- | Generate a random Double in the given range Note: word' 0 -- 10 includes both 0 and 10. word' :: Word -> Word -> Test Word -- | Generate a random Double in the given range Note: double' 0 -- 1 includes both 0 and 1. double' :: Double -> Double -> Test Double -- | Generate a random Int in the given range Note: int' 0 -- 5 includes both 0 and 5 int' :: Int -> Int -> Test Int -- | Generate a random Word word :: Test Word -- | Generate a random Double double :: Test Double -- | Generate a random Int int :: Test Int word8 :: Test Word8 bool :: Test Bool -- | Generate a bounded random value. Inclusive on both sides. random' :: Random a => a -> a -> Test a -- | Generate a random value random :: Random a => Test a -- | Log a message note :: Text -> Test () -- | Label a test. Can be nested. A "." is placed between nested scopes, so -- scope "foo" . scope "bar" is equivalent to scope -- "foo.bar" scope :: () => Text -> Test a -> Test a -- | Record a failure at the current scope crash :: HasCallStack => Text -> Test a -- | Tests are values of type Test a, and Test forms a -- monad with access to: -- --
-- $1 -- £-50 -- EUR 3.44 -- GOOG 500 -- 1.5h -- 90 apples -- 0 ---- -- It may also have an assigned Price, representing this amount's -- per-unit or total cost in a different commodity. If present, this is -- rendered like so: -- --
-- EUR 2 @ $1.50 (unit price) -- EUR 2 @@ $3 (total price) ---- -- A MixedAmount is zero or more simple amounts, so can represent -- multiple commodities; this is the type most often used: -- --
-- 0 -- $50 + EUR 3 -- 16h + $13.55 + AAPL 500 + 6 oranges ---- -- When a mixed amount has been "normalised", it has no more than one -- amount in each commodity and no zero amounts; or it has just a single -- zero amount and no others. -- -- Limited arithmetic with simple and mixed amounts is supported, best -- used with similar amounts since it mostly ignores assigned prices and -- commodity exchange rates. module Hledger.Data.Amount -- | The empty simple amount. amount :: Amount -- | The empty simple amount. nullamt :: Amount -- | A temporary value for parsed transactions which had no amount -- specified. missingamt :: Amount num :: Quantity -> Amount usd :: DecimalRaw Integer -> Amount eur :: DecimalRaw Integer -> Amount gbp :: DecimalRaw Integer -> Amount hrs :: Quantity -> Amount at :: Amount -> Amount -> Amount (@@) :: Amount -> Amount -> Amount -- | Convert an amount to the specified commodity, ignoring and discarding -- any assigned prices and assuming an exchange rate of 1. amountWithCommodity :: CommoditySymbol -> Amount -> Amount -- | Convert an amount to the commodity of its assigned price, if any. -- Notes: -- --
-- What Ledger now does is that if an account name is too long, it will -- start abbreviating the first parts of the account name down to two -- letters in length. If this results in a string that is still too -- long, the front will be elided -- not the end. For example: -- -- Expenses:Cash ; OK, not too long -- Ex:Wednesday:Cash ; Expenses was abbreviated to fit -- Ex:We:Afternoon:Cash ; Expenses and Wednesday abbreviated -- ; Expenses:Wednesday:Afternoon:Lunch:Snack:Candy:Chocolate:Cash -- ..:Af:Lu:Sn:Ca:Ch:Cash ; Abbreviated and elided! --elideAccountName :: Int -> AccountName -> AccountName -- | Escape an AccountName for use within a regular expression. -- >>> putStr $ escapeName "First?!*? %)*!#" First?!#$*?$(*) -- !^ escapeName :: AccountName -> Regexp -- | "a:b:c" -> ["a","a:b","a:b:c"] expandAccountName :: AccountName -> [AccountName] -- | Sorted unique account names implied by these account names, ie these -- plus all their parent accounts up to the root. Eg: ["a:b:c","d:e"] -- -> ["a","a:b","a:b:c","d","d:e"] expandAccountNames :: [AccountName] -> [AccountName] -- | Is the first account a parent or other ancestor of (and not the same -- as) the second ? isAccountNamePrefixOf :: AccountName -> AccountName -> Bool isSubAccountNameOf :: AccountName -> AccountName -> Bool parentAccountName :: AccountName -> AccountName parentAccountNames :: AccountName -> [AccountName] -- | From a list of account names, select those which are direct -- subaccounts of the given account name. subAccountNamesFrom :: [AccountName] -> AccountName -> [AccountName] -- |
-- >>> parsedate "2008/02/03" -- 2008-02-03 --parsedate :: String -> Day showDate :: Day -> String -- | Render a datespan as a display string, abbreviating into a compact -- form if possible. showDateSpan :: DateSpan -> String -- | Like showDateSpan, but show month spans as just the abbreviated month -- name in the current locale. showDateSpanMonthAbbrev :: DateSpan -> String elapsedSeconds :: Fractional a => UTCTime -> UTCTime -> a prevday :: Day -> Day -- |
-- >>> let p = parsePeriodExpr (parsedate "2008/11/26") -- -- >>> p "from Aug to Oct" -- Right (NoInterval,DateSpan 2008/08/01-2008/09/30) -- -- >>> p "aug to oct" -- Right (NoInterval,DateSpan 2008/08/01-2008/09/30) -- -- >>> p "every 3 days in Aug" -- Right (Days 3,DateSpan 2008/08) -- -- >>> p "daily from aug" -- Right (Days 1,DateSpan 2008/08/01-) -- -- >>> p "every week to 2009" -- Right (Weeks 1,DateSpan -2008/12/31) -- -- >>> p "every 2nd day of month" -- Right (DayOfMonth 2,DateSpan -) -- -- >>> p "every 2nd day" -- Right (DayOfMonth 2,DateSpan -) -- -- >>> p "every 2nd day 2009-" -- Right (DayOfMonth 2,DateSpan 2009/01/01-) -- -- >>> p "every 29th Nov" -- Right (DayOfYear 11 29,DateSpan -) -- -- >>> p "every 29th nov -2009" -- Right (DayOfYear 11 29,DateSpan -2008/12/31) -- -- >>> p "every nov 29th" -- Right (DayOfYear 11 29,DateSpan -) -- -- >>> p "every Nov 29th 2009-" -- Right (DayOfYear 11 29,DateSpan 2009/01/01-) -- -- >>> p "every 11/29 from 2009" -- Right (DayOfYear 11 29,DateSpan 2009/01/01-) -- -- >>> p "every 2nd Thursday of month to 2009" -- Right (WeekdayOfMonth 2 4,DateSpan -2008/12/31) -- -- >>> p "every 1st monday of month to 2009" -- Right (WeekdayOfMonth 1 1,DateSpan -2008/12/31) -- -- >>> p "every tue" -- Right (DayOfWeek 2,DateSpan -) -- -- >>> p "every 2nd day of week" -- Right (DayOfWeek 2,DateSpan -) -- -- >>> p "every 2nd day of month" -- Right (DayOfMonth 2,DateSpan -) -- -- >>> p "every 2nd day" -- Right (DayOfMonth 2,DateSpan -) -- -- >>> p "every 2nd day 2009-" -- Right (DayOfMonth 2,DateSpan 2009/01/01-) -- -- >>> p "every 2nd day of month 2009-" -- Right (DayOfMonth 2,DateSpan 2009/01/01-) --periodexprp :: Day -> TextParser m (Interval, DateSpan) -- | Parse a period expression to an Interval and overall DateSpan using -- the provided reference date, or return a parse error. parsePeriodExpr :: Day -> Text -> Either (ParseErrorBundle Text CustomErr) (Interval, DateSpan) -- | Like parsePeriodExpr, but call error' on failure. parsePeriodExpr' :: Day -> Text -> (Interval, DateSpan) nulldatespan :: DateSpan -- | A datespan of zero length, that matches no date. emptydatespan :: DateSpan failIfInvalidYear :: Monad m => String -> m () failIfInvalidMonth :: Monad m => String -> m () failIfInvalidDay :: Monad m => String -> m () datesepchar :: TextParser m Char datesepchars :: [Char] isDateSepChar :: Char -> Bool spanStart :: DateSpan -> Maybe Day spanEnd :: DateSpan -> Maybe Day -- | Get overall span enclosing multiple sequentially ordered spans. spansSpan :: [DateSpan] -> DateSpan -- | Calculate the intersection of two datespans. -- -- For non-intersecting spans, gives an empty span beginning on the -- second's start date: >>> mkdatespan "2018-01-01" "2018-01-03" -- spanIntersect mkdatespan "2018-01-03" "2018-01-05" DateSpan -- 20180103-20180102 spanIntersect :: DateSpan -> DateSpan -> DateSpan -- | Calculate the intersection of a number of datespans. spansIntersect :: [DateSpan] -> DateSpan -- | Calculate the intersection of two DateSpans, adjusting the start date -- so the interval is preserved. -- --
-- >>> let intervalIntersect = spanIntervalIntersect (Days 3) -- -- >>> mkdatespan "2018-01-01" "2018-01-03" `intervalIntersect` mkdatespan "2018-01-01" "2018-01-05" -- DateSpan 2018/01/01-2018/01/02 -- -- >>> mkdatespan "2018-01-01" "2018-01-05" `intervalIntersect` mkdatespan "2018-01-02" "2018-01-05" -- DateSpan 2018/01/04 -- -- >>> mkdatespan "2018-01-01" "2018-01-05" `intervalIntersect` mkdatespan "2018-01-03" "2018-01-05" -- DateSpan 2018/01/04 -- -- >>> mkdatespan "2018-01-01" "2018-01-05" `intervalIntersect` mkdatespan "2018-01-04" "2018-01-05" -- DateSpan 2018/01/04 -- -- >>> mkdatespan "2018-01-01" "2018-01-05" `intervalIntersect` mkdatespan "2017-12-01" "2018-01-05" -- DateSpan 2018/01/01-2018/01/04 --spanIntervalIntersect :: Interval -> DateSpan -> DateSpan -> DateSpan -- | Fill any unspecified dates in the first span with the dates from the -- second one. Sort of a one-way spanIntersect. spanDefaultsFrom :: DateSpan -> DateSpan -> DateSpan -- | Calculate the union of two datespans. spanUnion :: DateSpan -> DateSpan -> DateSpan -- | Calculate the union of a number of datespans. spansUnion :: [DateSpan] -> DateSpan -- | Parse a date in any of the formats allowed in Ledger's period -- expressions, and some others. Assumes any text in the parse stream has -- been lowercased. Returns a SmartDate, to be converted to a full date -- later (see fixSmartDate). -- -- Examples: -- --
-- 2004 (start of year, which must have 4+ digits) -- 2004/10 (start of month, which must be 1-12) -- 2004/10/1 (exact date, day must be 1-31) -- 10/1 (month and day in current year) -- 21 (day in current month) -- october, oct (start of month in current year) -- yesterday, today, tomorrow (-1, 0, 1 days from today) -- last/this/next day/week/month/quarter/year (-1, 0, 1 periods from the current period) -- 20181201 (8 digit YYYYMMDD with valid year month and day) -- 201812 (6 digit YYYYMM with valid year and month) ---- -- Note malformed digit sequences might give surprising results: -- --
-- 201813 (6 digits with an invalid month is parsed as start of 6-digit year) -- 20181301 (8 digits with an invalid month is parsed as start of 8-digit year) -- 20181232 (8 digits with an invalid day gives an error) -- 201801012 (9+ digits beginning with a valid YYYYMMDD gives an error) ---- -- Eg: -- -- YYYYMMDD is parsed as year-month-date if those parts are valid (>=4 -- digits, 1-12, and 1-31 respectively): >>> parsewith -- (smartdate <* eof) "20181201" Right ("2018","12","01") -- -- YYYYMM is parsed as year-month-01 if year and month are valid: -- >>> parsewith (smartdate <* eof) "201804" Right -- ("2018","04","01") -- -- With an invalid month, it's parsed as a year: >>> parsewith -- (smartdate <* eof) "201813" Right ("201813","","") -- -- A 9+ digit number beginning with valid YYYYMMDD gives an error: -- >>> parsewith (smartdate <* eof) "201801012" Left (...) -- -- Big numbers not beginning with a valid YYYYMMDD are parsed as a year: -- >>> parsewith (smartdate <* eof) "201813012" Right -- ("201813012","","") smartdate :: TextParser m SmartDate -- | Split a DateSpan into consecutive whole spans of the specified -- interval which fully encompass the original span (and a little more -- when necessary). If no interval is specified, the original span is -- returned. If the original span is the null date span, ie unbounded, -- the null date span is returned. If the original span is empty, eg if -- the end date is <= the start date, no spans are returned. -- --
-- >>> let t i d1 d2 = splitSpan i $ mkdatespan d1 d2 -- -- >>> t NoInterval "2008/01/01" "2009/01/01" -- [DateSpan 2008] -- -- >>> t (Quarters 1) "2008/01/01" "2009/01/01" -- [DateSpan 2008q1,DateSpan 2008q2,DateSpan 2008q3,DateSpan 2008q4] -- -- >>> splitSpan (Quarters 1) nulldatespan -- [DateSpan -] -- -- >>> t (Days 1) "2008/01/01" "2008/01/01" -- an empty datespan -- [] -- -- >>> t (Quarters 1) "2008/01/01" "2008/01/01" -- [] -- -- >>> t (Months 1) "2008/01/01" "2008/04/01" -- [DateSpan 2008/01,DateSpan 2008/02,DateSpan 2008/03] -- -- >>> t (Months 2) "2008/01/01" "2008/04/01" -- [DateSpan 2008/01/01-2008/02/29,DateSpan 2008/03/01-2008/04/30] -- -- >>> t (Weeks 1) "2008/01/01" "2008/01/15" -- [DateSpan 2007/12/31w01,DateSpan 2008/01/07w02,DateSpan 2008/01/14w03] -- -- >>> t (Weeks 2) "2008/01/01" "2008/01/15" -- [DateSpan 2007/12/31-2008/01/13,DateSpan 2008/01/14-2008/01/27] -- -- >>> t (DayOfMonth 2) "2008/01/01" "2008/04/01" -- [DateSpan 2007/12/02-2008/01/01,DateSpan 2008/01/02-2008/02/01,DateSpan 2008/02/02-2008/03/01,DateSpan 2008/03/02-2008/04/01] -- -- >>> t (WeekdayOfMonth 2 4) "2011/01/01" "2011/02/15" -- [DateSpan 2010/12/09-2011/01/12,DateSpan 2011/01/13-2011/02/09,DateSpan 2011/02/10-2011/03/09] -- -- >>> t (DayOfWeek 2) "2011/01/01" "2011/01/15" -- [DateSpan 2010/12/28-2011/01/03,DateSpan 2011/01/04-2011/01/10,DateSpan 2011/01/11-2011/01/17] -- -- >>> t (DayOfYear 11 29) "2011/10/01" "2011/10/15" -- [DateSpan 2010/11/29-2011/11/28] -- -- >>> t (DayOfYear 11 29) "2011/12/01" "2012/12/15" -- [DateSpan 2011/11/29-2012/11/28,DateSpan 2012/11/29-2013/11/28] --splitSpan :: Interval -> DateSpan -> [DateSpan] -- | Convert a SmartDate to an absolute date using the provided reference -- date. -- --
-- >>> :set -XOverloadedStrings -- -- >>> let t = fixSmartDateStr (parsedate "2008/11/26") -- -- >>> t "0000-01-01" -- "0000/01/01" -- -- >>> t "1999-12-02" -- "1999/12/02" -- -- >>> t "1999.12.02" -- "1999/12/02" -- -- >>> t "1999/3/2" -- "1999/03/02" -- -- >>> t "19990302" -- "1999/03/02" -- -- >>> t "2008/2" -- "2008/02/01" -- -- >>> t "0020/2" -- "0020/02/01" -- -- >>> t "1000" -- "1000/01/01" -- -- >>> t "4/2" -- "2008/04/02" -- -- >>> t "2" -- "2008/11/02" -- -- >>> t "January" -- "2008/01/01" -- -- >>> t "feb" -- "2008/02/01" -- -- >>> t "today" -- "2008/11/26" -- -- >>> t "yesterday" -- "2008/11/25" -- -- >>> t "tomorrow" -- "2008/11/27" -- -- >>> t "this day" -- "2008/11/26" -- -- >>> t "last day" -- "2008/11/25" -- -- >>> t "next day" -- "2008/11/27" -- -- >>> t "this week" -- last monday -- "2008/11/24" -- -- >>> t "last week" -- previous monday -- "2008/11/17" -- -- >>> t "next week" -- next monday -- "2008/12/01" -- -- >>> t "this month" -- "2008/11/01" -- -- >>> t "last month" -- "2008/10/01" -- -- >>> t "next month" -- "2008/12/01" -- -- >>> t "this quarter" -- "2008/10/01" -- -- >>> t "last quarter" -- "2008/07/01" -- -- >>> t "next quarter" -- "2009/01/01" -- -- >>> t "this year" -- "2008/01/01" -- -- >>> t "last year" -- "2007/01/01" -- -- >>> t "next year" -- "2009/01/01" ---- -- t "last wed" "20081119" t "next friday" "20081128" t -- "next january" "20090101" fixSmartDate :: Day -> SmartDate -> Day -- | Convert a smart date string to an explicit yyyy/mm/dd string using the -- provided reference date, or raise an error. fixSmartDateStr :: Day -> Text -> String -- | A safe version of fixSmartDateStr. fixSmartDateStrEither :: Day -> Text -> Either (ParseErrorBundle Text CustomErr) String fixSmartDateStrEither' :: Day -> Text -> Either (ParseErrorBundle Text CustomErr) Day -- | Count the days in a DateSpan, or if it is open-ended return Nothing. daysInSpan :: DateSpan -> Maybe Integer maybePeriod :: Day -> Text -> Maybe (Interval, DateSpan) -- | Make a datespan from two valid date strings parseable by parsedate (or -- raise an error). Eg: mkdatespan "201111" "20111231". mkdatespan :: String -> String -> DateSpan instance GHC.Show.Show Hledger.Data.Types.DateSpan -- | A Posting represents a change (by some MixedAmount) of -- the balance in some Account. Each Transaction contains -- two or more postings which should add up to 0. Postings reference -- their parent transaction, so we can look up the date or description -- there. module Hledger.Data.Posting nullposting :: Posting posting :: Posting post :: AccountName -> Amount -> Posting nullsourcepos :: GenericSourcePos nullassertion :: BalanceAssertion assertion :: BalanceAssertion originalPosting :: Posting -> Posting -- | Get a posting's status. This is cleared or pending if those are -- explicitly set on the posting, otherwise the status of its parent -- transaction, or unmarked if there is no parent transaction. (Note the -- ambiguity, unmarked can mean "posting and transaction are both -- unmarked" or "posting is unmarked and don't know about the -- transaction". postingStatus :: Posting -> Status isReal :: Posting -> Bool isVirtual :: Posting -> Bool isBalancedVirtual :: Posting -> Bool isEmptyPosting :: Posting -> Bool isAssignment :: Posting -> Bool hasAmount :: Posting -> Bool -- | Tags for this posting including any inherited from its parent -- transaction. postingAllTags :: Posting -> [Tag] -- | Tags for this transaction including any from its postings. transactionAllTags :: Transaction -> [Tag] relatedPostings :: Posting -> [Posting] -- | Remove all prices of a posting removePrices :: Posting -> Posting -- | Get a posting's (primary) date - it's own primary date if specified, -- otherwise the parent transaction's primary date, or the null date if -- there is no parent transaction. postingDate :: Posting -> Day -- | Get a posting's secondary (secondary) date, which is the first of: -- posting's secondary date, transaction's secondary date, posting's -- primary date, transaction's primary date, or the null date if there is -- no parent transaction. postingDate2 :: Posting -> Day -- | Does this posting fall within the given date span ? isPostingInDateSpan :: DateSpan -> Posting -> Bool isPostingInDateSpan' :: WhichDate -> DateSpan -> Posting -> Bool -- | Get the minimal date span which contains all the postings, or the null -- date span if there are none. postingsDateSpan :: [Posting] -> DateSpan postingsDateSpan' :: WhichDate -> [Posting] -> DateSpan -- | Sorted unique account names referenced by these postings. accountNamesFromPostings :: [Posting] -> [AccountName] accountNamePostingType :: AccountName -> PostingType accountNameWithoutPostingType :: AccountName -> AccountName accountNameWithPostingType :: PostingType -> AccountName -> AccountName -- | Prefix one account name to another, preserving posting type indicators -- like concatAccountNames. joinAccountNames :: AccountName -> AccountName -> AccountName -- | Join account names into one. If any of them has () or [] posting type -- indicators, these (the first type encountered) will also be applied to -- the resulting account name. concatAccountNames :: [AccountName] -> AccountName -- | Rewrite an account name using all matching aliases from the given -- list, in sequence. Each alias sees the result of applying the previous -- aliases. accountNameApplyAliases :: [AccountAlias] -> AccountName -> AccountName -- | Memoising version of accountNameApplyAliases, maybe overkill. accountNameApplyAliasesMemo :: [AccountAlias] -> AccountName -> AccountName transactionPayee :: Transaction -> Text transactionNote :: Transaction -> Text -- | Parse a transaction's description into payee and note (aka narration) -- fields, assuming a convention of separating these with | (like -- Beancount). Ie, everything up to the first | is the payee, everything -- after it is the note. When there's no |, payee == note == description. payeeAndNoteFromDescription :: Text -> (Text, Text) sumPostings :: [Posting] -> MixedAmount showPosting :: Posting -> String showComment :: Text -> String tests_Posting :: Test () -- | A Transaction represents a movement of some commodity(ies) -- between two or more accounts. It consists of multiple account -- Postings which balance to zero, a date, and optional extras -- like description, cleared status, and tags. module Hledger.Data.Transaction nulltransaction :: Transaction -- | Ensure a transaction's postings refer back to it, so that eg -- relatedPostings works right. txnTieKnot :: Transaction -> Transaction -- | Ensure a transaction's postings do not refer back to it, so that eg -- recursiveSize and GHCI's :sprint work right. txnUntieKnot :: Transaction -> Transaction -- | Show an account name, clipped to the given width if any, and -- appropriately bracketed/parenthesised for the given posting type. showAccountName :: Maybe Int -> PostingType -> AccountName -> String hasRealPostings :: Transaction -> Bool realPostings :: Transaction -> [Posting] assignmentPostings :: Transaction -> [Posting] virtualPostings :: Transaction -> [Posting] balancedVirtualPostings :: Transaction -> [Posting] transactionsPostings :: [Transaction] -> [Posting] -- | Does this transaction appear balanced when rendered, optionally with -- the given commodity display styles ? More precisely: after converting -- amounts to cost using explicit transaction prices if any; and summing -- the real postings, and summing the balanced virtual postings; and -- applying the given display styles if any (maybe affecting decimal -- places); do both totals appear to be zero when rendered ? isTransactionBalanced :: Maybe (Map CommoditySymbol AmountStyle) -> Transaction -> Bool transactionDate2 :: Transaction -> Day -- | Get the sums of a transaction's real, virtual, and balanced virtual -- postings. transactionPostingBalances :: Transaction -> (MixedAmount, MixedAmount, MixedAmount) -- | Ensure this transaction is balanced, possibly inferring a missing -- amount or conversion price(s), or return an error message. Balancing -- is affected by commodity display precisions, so those can (optionally) -- be provided. -- -- this fails for example, if there are several missing amounts (possibly -- with balance assignments) balanceTransaction :: Maybe (Map CommoditySymbol AmountStyle) -> Transaction -> Either String Transaction -- | More general version of balanceTransaction that takes an update -- function balanceTransactionUpdate :: MonadError String m => (AccountName -> MixedAmount -> m ()) -> Maybe (Map CommoditySymbol AmountStyle) -> Transaction -> m Transaction -- | Render a journal transaction as text in the style of Ledger's print -- command. -- -- Ledger 2.x's standard format looks like this: -- --
-- yyyymmdd[ *][ CODE] description......... [ ; comment...............] -- account name 1..................... ...$amount1[ ; comment...............] -- account name 2..................... ..$-amount1[ ; comment...............] -- -- pcodewidth = no limit -- 10 -- mimicking ledger layout. -- pdescwidth = no limit -- 20 -- I don't remember what these mean, -- pacctwidth = 35 minimum, no maximum -- they were important at the time. -- pamtwidth = 11 -- pcommentwidth = no limit -- 22 ---- -- The output will be parseable journal syntax. To facilitate this, -- postings with explicit multi-commodity amounts are displayed as -- multiple similar postings, one per commodity. (Normally does not -- happen with this function). -- -- If there are multiple postings, all with explicit amounts, and the -- transaction appears obviously balanced (postings sum to 0, without -- needing to infer conversion prices), the last posting's amount will -- not be shown. showTransaction :: Transaction -> String -- | Like showTransaction, but does not change amounts' explicitness. -- Explicit amounts are shown and implicit amounts are not. The output -- will be parseable journal syntax. To facilitate this, postings with -- explicit multi-commodity amounts are displayed as multiple similar -- postings, one per commodity. Most often, this is the one you want to -- use. showTransactionUnelided :: Transaction -> String -- | Like showTransactionUnelided, but explicit multi-commodity amounts are -- shown on one line, comma-separated. In this case the output will not -- be parseable journal syntax. showTransactionUnelidedOneLineAmounts :: Transaction -> String -- | Render a posting, simply. Used in balance assertion errors. -- showPostingLine p = indent $ if pstatus p == Cleared then "* " else "" -- ++ -- XXX show ! showAccountName Nothing (ptype p) (paccount p) ++ " " -- ++ showMixedAmountOneLine (pamount p) ++ assertion where -- XXX -- extract, handle == assertion = maybe "" ((" = " ++) . -- showAmountWithZeroCommodity . baamount) $ pbalanceassertion p -- -- Render a posting, at the appropriate width for aligning with its -- siblings if any. Used by the rewrite command. showPostingLines :: Posting -> [String] sourceFilePath :: GenericSourcePos -> FilePath sourceFirstLine :: GenericSourcePos -> Int -- | Render source position in human-readable form. Keep in sync with -- Hledger.UI.ErrorScreen.hledgerparseerrorpositionp (temporary). XXX showGenericSourcePos :: GenericSourcePos -> String tests_Transaction :: Test () -- | A general query system for matching things (accounts, postings, -- transactions..) by various criteria, and a SimpleTextParser for query -- expressions. module Hledger.Query -- | A query is a composition of search criteria, which can be used to -- match postings, transactions, accounts and more. data Query -- | always match Any :: Query -- | never match None :: Query -- | negate this match Not :: Query -> Query -- | match if any of these match Or :: [Query] -> Query -- | match if all of these match And :: [Query] -> Query -- | match if code matches this regexp Code :: Regexp -> Query -- | match if description matches this regexp Desc :: Regexp -> Query -- | match postings whose account matches this regexp Acct :: Regexp -> Query -- | match if primary date in this date span Date :: DateSpan -> Query -- | match if secondary date in this date span Date2 :: DateSpan -> Query -- | match txns/postings with this status StatusQ :: Status -> Query -- | match if "realness" (involves a real non-virtual account ?) has this -- value Real :: Bool -> Query -- | match if the amount's numeric quantity is less thangreater -- thanequal to/unsignedly equal to some value Amt :: OrdPlus -> Quantity -> Query -- | match if the entire commodity symbol is matched by this regexp Sym :: Regexp -> Query -- | if true, show zero-amount postings/accounts which are usually not -- shown more of a query option than a query criteria ? Empty :: Bool -> Query -- | match if account depth is less than or equal to this value. Depth is -- sometimes used like a query (for filtering report data) and sometimes -- like a query option (for controlling display) Depth :: Int -> Query -- | match if a tag's name, and optionally its value, is matched by these -- respective regexps matching the regexp if provided, exists Tag :: Regexp -> Maybe Regexp -> Query -- | A query option changes a query's/report's behaviour and output in some -- way. data QueryOpt -- | show an account register focussed on this account QueryOptInAcctOnly :: AccountName -> QueryOpt -- | as above but include sub-accounts in the account register | -- QueryOptCostBasis -- ^ show amounts converted to cost where possible | -- QueryOptDate2 -- ^ show secondary dates instead of primary dates QueryOptInAcct :: AccountName -> QueryOpt -- | Convert a query expression containing zero or more space-separated -- terms to a query and zero or more query options. A query term is -- either: -- --
-- >>> _ptgen "monthly from 2017/1 to 2017/4" -- 2017/01/01 -- ; recur: monthly from 2017/1 to 2017/4 -- a $1.00 -- -- 2017/02/01 -- ; recur: monthly from 2017/1 to 2017/4 -- a $1.00 -- -- 2017/03/01 -- ; recur: monthly from 2017/1 to 2017/4 -- a $1.00 ---- --
-- >>> _ptgen "monthly from 2017/1 to 2017/5" -- 2017/01/01 -- ; recur: monthly from 2017/1 to 2017/5 -- a $1.00 -- -- 2017/02/01 -- ; recur: monthly from 2017/1 to 2017/5 -- a $1.00 -- -- 2017/03/01 -- ; recur: monthly from 2017/1 to 2017/5 -- a $1.00 -- -- 2017/04/01 -- ; recur: monthly from 2017/1 to 2017/5 -- a $1.00 ---- --
-- >>> _ptgen "every 2nd day of month from 2017/02 to 2017/04" -- 2017/01/02 -- ; recur: every 2nd day of month from 2017/02 to 2017/04 -- a $1.00 -- -- 2017/02/02 -- ; recur: every 2nd day of month from 2017/02 to 2017/04 -- a $1.00 -- -- 2017/03/02 -- ; recur: every 2nd day of month from 2017/02 to 2017/04 -- a $1.00 ---- --
-- >>> _ptgen "every 30th day of month from 2017/1 to 2017/5" -- 2016/12/30 -- ; recur: every 30th day of month from 2017/1 to 2017/5 -- a $1.00 -- -- 2017/01/30 -- ; recur: every 30th day of month from 2017/1 to 2017/5 -- a $1.00 -- -- 2017/02/28 -- ; recur: every 30th day of month from 2017/1 to 2017/5 -- a $1.00 -- -- 2017/03/30 -- ; recur: every 30th day of month from 2017/1 to 2017/5 -- a $1.00 -- -- 2017/04/30 -- ; recur: every 30th day of month from 2017/1 to 2017/5 -- a $1.00 ---- --
-- >>> _ptgen "every 2nd Thursday of month from 2017/1 to 2017/4" -- 2016/12/08 -- ; recur: every 2nd Thursday of month from 2017/1 to 2017/4 -- a $1.00 -- -- 2017/01/12 -- ; recur: every 2nd Thursday of month from 2017/1 to 2017/4 -- a $1.00 -- -- 2017/02/09 -- ; recur: every 2nd Thursday of month from 2017/1 to 2017/4 -- a $1.00 -- -- 2017/03/09 -- ; recur: every 2nd Thursday of month from 2017/1 to 2017/4 -- a $1.00 ---- --
-- >>> _ptgen "every nov 29th from 2017 to 2019" -- 2016/11/29 -- ; recur: every nov 29th from 2017 to 2019 -- a $1.00 -- -- 2017/11/29 -- ; recur: every nov 29th from 2017 to 2019 -- a $1.00 -- -- 2018/11/29 -- ; recur: every nov 29th from 2017 to 2019 -- a $1.00 ---- --
-- >>> _ptgen "2017/1" -- 2017/01/01 -- ; recur: 2017/1 -- a $1.00 ---- --
-- >>> _ptgen "" -- *** Exception: failed to parse... -- ... ---- --
-- >>> _ptgen "weekly from 2017" -- *** Exception: Unable to generate transactions according to "weekly from 2017" because 2017-01-01 is not a first day of the week ---- --
-- >>> _ptgen "monthly from 2017/5/4" -- *** Exception: Unable to generate transactions according to "monthly from 2017/5/4" because 2017-05-04 is not a first day of the month ---- --
-- >>> _ptgen "every quarter from 2017/1/2" -- *** Exception: Unable to generate transactions according to "every quarter from 2017/1/2" because 2017-01-02 is not a first day of the quarter ---- --
-- >>> _ptgen "yearly from 2017/1/14" -- *** Exception: Unable to generate transactions according to "yearly from 2017/1/14" because 2017-01-14 is not a first day of the year ---- --
-- >>> let reportperiod="daily from 2018/01/03" in let (i,s) = parsePeriodExpr' nulldate reportperiod in runPeriodicTransaction (nullperiodictransaction{ptperiodexpr=reportperiod, ptspan=s, ptinterval=i, ptpostings=["a" `post` usd 1]}) (DateSpan (Just $ parsedate "2018-01-01") (Just $ parsedate "2018-01-03"))
-- []
--
runPeriodicTransaction :: PeriodicTransaction -> DateSpan -> [Transaction]
-- | Check that this date span begins at a boundary of this interval, or
-- return an explanatory error message including the provided period
-- expression (from which the span and interval are derived).
checkPeriodicTransactionStartDate :: Interval -> DateSpan -> Text -> Maybe String
instance GHC.Show.Show Hledger.Data.Types.PeriodicTransaction
-- | A MarketPrice represents a historical exchange rate between two
-- commodities. (Ledger calls them historical prices.) For example,
-- prices published by a stock exchange or the foreign exchange market.
-- Some commands (balance, currently) can use this information to show
-- the market value of things at a given date.
module Hledger.Data.MarketPrice
-- | Get the string representation of an market price, based on its
-- commodity's display settings.
showMarketPrice :: MarketPrice -> String
-- | A Journal is a set of transactions, plus optional related data.
-- This is hledger's primary data object. It is usually parsed from a
-- journal file or other data format (see Hledger.Read).
module Hledger.Data.Journal
addMarketPrice :: MarketPrice -> Journal -> Journal
addTransactionModifier :: TransactionModifier -> Journal -> Journal
addPeriodicTransaction :: PeriodicTransaction -> Journal -> Journal
addTransaction :: Transaction -> Journal -> Journal
-- | Fill in any missing amounts and check that all journal transactions
-- balance and all balance assertions pass, or return an error message.
-- This is done after parsing all amounts and applying canonical
-- commodity styles, since balancing depends on display precision.
-- Reports only the first error encountered.
journalBalanceTransactions :: Bool -> Journal -> Either String Journal
-- | Choose and apply a consistent display format to the posting amounts in
-- each commodity. Each commodity's format is specified by a commodity
-- format directive, or otherwise inferred from posting amounts as in
-- hledger < 0.28.
journalApplyCommodityStyles :: Journal -> Journal
-- | Given a list of amounts in parse order, build a map from their
-- commodity names to standard commodity display formats.
commodityStylesFromAmounts :: [Amount] -> Map CommoditySymbol AmountStyle
-- | Get all the amount styles defined in this journal, either declared by
-- a commodity directive or inferred from amounts, as a map from symbol
-- to style. Styles declared by commodity directives take precedence, and
-- these also are guaranteed to know their decimal point character.
journalCommodityStyles :: Journal -> Map CommoditySymbol AmountStyle
-- | Convert all this journal's amounts to cost by applying their prices,
-- if any.
journalConvertAmountsToCost :: Journal -> Journal
-- | Reverse parsed data to normal order. This is used for post-parse
-- processing, since data is added to the head of the list during
-- parsing.
journalReverse :: Journal -> Journal
-- | Set this journal's last read time, ie when its files were last read.
journalSetLastReadTime :: ClockTime -> Journal -> Journal
-- | Apply the pivot transformation to all postings in a journal, replacing
-- their account name by their value for the given field or tag.
journalPivot :: Text -> Journal -> Journal
-- | Keep only transactions matching the query expression.
filterJournalTransactions :: Query -> Journal -> Journal
-- | Keep only postings matching the query expression. This can leave
-- unbalanced transactions.
filterJournalPostings :: Query -> Journal -> Journal
-- | Within each posting's amount, keep only the parts matching the query.
-- This can leave unbalanced transactions.
filterJournalAmounts :: Query -> Journal -> Journal
-- | Filter out all parts of this transaction's amounts which do not match
-- the query. This can leave the transaction unbalanced.
filterTransactionAmounts :: Query -> Transaction -> Transaction
filterTransactionPostings :: Query -> Transaction -> Transaction
-- | Filter out all parts of this posting's amount which do not match the
-- query.
filterPostingAmount :: Query -> Posting -> Posting
-- | Sorted unique account names posted to by this journal's transactions.
journalAccountNamesUsed :: Journal -> [AccountName]
-- | Sorted unique account names implied by this journal's transactions -
-- accounts posted to and all their implied parent accounts.
journalAccountNamesImplied :: Journal -> [AccountName]
-- | Sorted unique account names declared by account directives in this
-- journal.
journalAccountNamesDeclared :: Journal -> [AccountName]
-- | Sorted unique account names declared by account directives or posted
-- to by transactions in this journal.
journalAccountNamesDeclaredOrUsed :: Journal -> [AccountName]
-- | Sorted unique account names declared by account directives, or posted
-- to or implied as parents by transactions in this journal.
journalAccountNamesDeclaredOrImplied :: Journal -> [AccountName]
-- | Convenience/compatibility alias for
-- journalAccountNamesDeclaredOrImplied.
journalAccountNames :: Journal -> [AccountName]
-- | Get an ordered list of the amounts in this journal which will
-- influence amount style canonicalisation. These are:
--
--
-- >>> parseTest rawnumberp "1,234,567.89"
-- Right (WithSeparators ',' ["1","234","567"] (Just ('.',"89")))
--
-- >>> parseTest rawnumberp "1,000"
-- Left (AmbiguousNumber "1" ',' "000")
--
-- >>> parseTest rawnumberp "1 000"
-- Right (WithSeparators ' ' ["1","000"] Nothing)
--
rawnumberp :: TextParser m (Either AmbiguousNumber RawNumber)
multilinecommentp :: TextParser m ()
emptyorcommentlinep :: TextParser m ()
-- | Parse the text of a (possibly multiline) comment following a journal
-- item.
--
-- -- >>> rtp followingcommentp "" -- no comment -- Right "" -- -- >>> rtp followingcommentp ";" -- just a (empty) same-line comment. newline is added -- Right "\n" -- -- >>> rtp followingcommentp "; \n" -- Right "\n" -- -- >>> rtp followingcommentp ";\n ;\n" -- a same-line and a next-line comment -- Right "\n\n" -- -- >>> rtp followingcommentp "\n ;\n" -- just a next-line comment. Insert an empty same-line comment so the next-line comment doesn't become a same-line comment. -- Right "\n\n" --followingcommentp :: TextParser m Text -- | Parse a transaction comment and extract its tags. -- -- The first line of a transaction may be followed by comments, which -- begin with semicolons and extend to the end of the line. Transaction -- comments may span multiple lines, but comment lines below the -- transaction must be preceeded by leading whitespace. -- -- 200011 ; a transaction comment starting on the same line ... ; -- extending to the next line account1 $1 account2 -- -- Tags are name-value pairs. -- --
-- >>> let getTags (_,tags) = tags -- -- >>> let parseTags = fmap getTags . rtp transactioncommentp ---- --
-- >>> parseTags "; name1: val1, name2:all this is value2"
-- Right [("name1","val1"),("name2","all this is value2")]
--
--
-- A tag's name must be immediately followed by a colon, without
-- separating whitespace. The corresponding value consists of all the
-- text following the colon up until the next colon or newline, stripped
-- of leading and trailing whitespace.
transactioncommentp :: TextParser m (Text, [Tag])
-- | Parse a posting comment and extract its tags and dates.
--
-- Postings may be followed by comments, which begin with semicolons and
-- extend to the end of the line. Posting comments may span multiple
-- lines, but comment lines below the posting must be preceeded by
-- leading whitespace.
--
-- 200011 account1 $1 ; a posting comment starting on the same
-- line ... ; extending to the next line
--
-- account2 ; a posting comment beginning on the next line
--
-- Tags are name-value pairs.
--
-- -- >>> let getTags (_,tags,_,_) = tags -- -- >>> let parseTags = fmap getTags . rtp (postingcommentp Nothing) ---- --
-- >>> parseTags "; name1: val1, name2:all this is value2"
-- Right [("name1","val1"),("name2","all this is value2")]
--
--
-- A tag's name must be immediately followed by a colon, without
-- separating whitespace. The corresponding value consists of all the
-- text following the colon up until the next colon or newline, stripped
-- of leading and trailing whitespace.
--
-- Posting dates may be expressed with "date"/"date2" tags or with
-- bracketed date syntax. Posting dates will inherit their year from the
-- transaction date if the year is not specified. We throw parse errors
-- on invalid dates.
--
-- -- >>> let getDates (_,_,d1,d2) = (d1, d2) -- -- >>> let parseDates = fmap getDates . rtp (postingcommentp (Just 2000)) ---- --
-- >>> parseDates "; date: 1/2, date2: 1999/12/31" -- Right (Just 2000-01-02,Just 1999-12-31) -- -- >>> parseDates "; [1/2=1999/12/31]" -- Right (Just 2000-01-02,Just 1999-12-31) ---- -- Example: tags, date tags, and bracketed dates >>> rtp -- (postingcommentp (Just 2000)) "; a:b, date:34, [=56]" Right -- ("a:b, date:34, [=56]n",[("a","b"),("date","3/4")],Just -- 2000-03-04,Just 2000-05-06) -- -- Example: extraction of dates from date tags ignores trailing text -- >>> rtp (postingcommentp (Just 2000)) "; date:34=56" -- Right ("date:34=56n",[("date","34=56")],Just -- 2000-03-04,Nothing) postingcommentp :: Maybe Year -> TextParser m (Text, [Tag], Maybe Day, Maybe Day) -- | Parse Ledger-style bracketed posting dates ([DATE=DATE2]), as "date" -- and/or "date2" tags. Anything that looks like an attempt at this (a -- square-bracketed sequence of 0123456789/-.= containing at least one -- digit and one date separator) is also parsed, and will throw an -- appropriate error. -- -- The dates are parsed in full here so that errors are reported in the -- right position. A missing year in DATE can be inferred if a default -- date is provided. A missing year in DATE2 will be inferred from DATE. -- --
-- >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[2016/1/2=3/4]"
-- Right [("date",2016-01-02),("date2",2016-03-04)]
--
--
-- -- >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[1]" -- Left ...not a bracketed date... ---- --
-- >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[2016/1/32]" -- Left ...1:2:...well-formed but invalid date: 2016/1/32... ---- --
-- >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[1/31]" -- Left ...1:2:...partial date 1/31 found, but the current year is unknown... ---- --
-- >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[0123456789/-.=/-.=]" -- Left ...1:13:...expecting month or day... --bracketeddatetagsp :: Maybe Year -> TextParser m [(TagName, Day)] -- | Parse any text beginning with a non-whitespace character, until a -- double space or the end of input. singlespacedtextp :: TextParser m Text -- | Similar to singlespacedtextp, except that the text must only -- contain characters satisfying the given predicate. singlespacedtextsatisfyingp :: (Char -> Bool) -> TextParser m Text -- | Parse one non-newline whitespace character that is not followed by -- another one. singlespacep :: TextParser m () tests_Common :: Test () instance GHC.Classes.Eq Hledger.Read.Common.AmbiguousNumber instance GHC.Show.Show Hledger.Read.Common.AmbiguousNumber instance GHC.Classes.Eq Hledger.Read.Common.RawNumber instance GHC.Show.Show Hledger.Read.Common.RawNumber instance GHC.Classes.Eq Hledger.Read.Common.DigitGrp instance Data.Data.Data Hledger.Read.Common.InputOpts instance GHC.Show.Show Hledger.Read.Common.InputOpts instance GHC.Show.Show Hledger.Read.Common.DigitGrp instance GHC.Base.Semigroup Hledger.Read.Common.DigitGrp instance GHC.Base.Monoid Hledger.Read.Common.DigitGrp instance GHC.Show.Show Hledger.Read.Common.Reader instance Data.Default.Class.Default Hledger.Read.Common.InputOpts -- | A reader for the "timedot" file format. Example: -- --
-- #DATE -- Each dot represents 15m, spaces are ignored -- numbers with or without a following h represent hours -- numbers followed by m represent minutes -- -- # on 2/1, 1h was spent on FOSS haskell work, 0.25h on research, etc. -- 2/1 -- fos.haskell .... .. -- biz.research . -- inc.client1 .... .... .... .... .... .... -- -- 2/2 -- biz.research . -- inc.client1 .... .... .. --module Hledger.Read.TimedotReader reader :: Reader timedotfilep :: JournalParser m ParsedJournal -- | A reader for the timeclock file format generated by timeclock.el -- (http://www.emacswiki.org/emacs/TimeClock). Example: -- --
-- i 2007/03/10 12:26:00 hledger -- o 2007/03/10 17:26:02 ---- -- From timeclock.el 2.6: -- --
-- A timeclock contains data in the form of a single entry per line. -- Each entry has the form: -- -- CODE YYYYMMDD HH:MM:SS [COMMENT] -- -- CODE is one of: b, h, i, o or O. COMMENT is optional when the code is -- i, o or O. The meanings of the codes are: -- -- b Set the current time balance, or "time debt". Useful when -- archiving old log data, when a debt must be carried forward. -- The COMMENT here is the number of seconds of debt. -- -- h Set the required working time for the given day. This must -- be the first entry for that day. The COMMENT in this case is -- the number of hours in this workday. Floating point amounts -- are allowed. -- -- i Clock in. The COMMENT in this case should be the name of the -- project worked on. -- -- o Clock out. COMMENT is unnecessary, but can be used to provide -- a description of how the period went, for example. -- -- O Final clock out. Whatever project was being worked on, it is -- now finished. Useful for creating summary reports. --module Hledger.Read.TimeclockReader reader :: Reader timeclockfilep :: MonadIO m => JournalParser m ParsedJournal -- | A reader for hledger's journal file format -- (http://hledger.org/MANUAL.html#the-journal-file). hledger's -- journal format is a compatible subset of c++ ledger's -- (http://ledger-cli.org/3.0/doc/ledger3.html#Journal-Format), so -- this reader should handle many ledger files as well. Example: -- --
-- 2012/3/24 gift -- expenses:gifts $10 -- assets:cash ---- -- Journal format supports the include directive which can read files in -- other formats, so the other file format readers need to be importable -- here. Some low-level journal syntax parsers which those readers also -- use are therefore defined separately in Hledger.Read.Common, avoiding -- import cycles. module Hledger.Read.JournalReader reader :: Reader genericSourcePos :: SourcePos -> GenericSourcePos -- | Given a megaparsec ParsedJournal parser, input options, file path and -- file content: parse and post-process a Journal, or give an error. parseAndFinaliseJournal :: ErroringJournalParser IO ParsedJournal -> InputOpts -> FilePath -> Text -> ExceptT String IO Journal -- | Run a journal parser in some monad. See also: parseWithState. runJournalParser :: Monad m => JournalParser m a -> Text -> m (Either (ParseErrorBundle Text CustomErr) a) -- | Run a journal parser in some monad. See also: parseWithState. rjp :: Monad m => JournalParser m a -> Text -> m (Either (ParseErrorBundle Text CustomErr) a) getParentAccount :: JournalParser m AccountName -- | A journal parser. Accumulates and returns a ParsedJournal, -- which should be finalised/validated before use. -- --
-- >>> rejp (journalp <* eof) "2015/1/1\n a 0\n" -- Right (Right Journal with 1 transactions, 1 accounts) --journalp :: MonadIO m => ErroringJournalParser m ParsedJournal -- | Parse any journal directive and update the parse state accordingly. Cf -- http://hledger.org/manual.html#directives, -- http://ledger-cli.org/3.0/doc/ledger3.html#Command-Directives directivep :: MonadIO m => ErroringJournalParser m () defaultyeardirectivep :: JournalParser m () marketpricedirectivep :: JournalParser m MarketPrice -- | Parse a date and time in YYYYMMDD HH:MM[:SS][+-ZZZZ] format. -- Hyphen (-) and period (.) are also allowed as date separators. The -- year may be omitted if a default year has been set. Seconds are -- optional. The timezone is optional and ignored (the time is always -- interpreted as a local time). Leading zeroes may be omitted (except in -- a timezone). datetimep :: JournalParser m LocalTime -- | Parse a date in YYYYMMDD format. Hyphen (-) and period (.) are -- also allowed as separators. The year may be omitted if a default year -- has been set. Leading zeroes may be omitted. datep :: JournalParser m Day -- | Parse an account name (plus one following space if present), then -- apply any parent account prefix and/or account aliases currently in -- effect, in that order. (Ie first add the parent account prefix, then -- rewrite with aliases). modifiedaccountnamep :: JournalParser m AccountName postingp :: Maybe Year -> JournalParser m Posting statusp :: TextParser m Status emptyorcommentlinep :: TextParser m () -- | Parse the text of a (possibly multiline) comment following a journal -- item. -- --
-- >>> rtp followingcommentp "" -- no comment -- Right "" -- -- >>> rtp followingcommentp ";" -- just a (empty) same-line comment. newline is added -- Right "\n" -- -- >>> rtp followingcommentp "; \n" -- Right "\n" -- -- >>> rtp followingcommentp ";\n ;\n" -- a same-line and a next-line comment -- Right "\n\n" -- -- >>> rtp followingcommentp "\n ;\n" -- just a next-line comment. Insert an empty same-line comment so the next-line comment doesn't become a same-line comment. -- Right "\n\n" --followingcommentp :: TextParser m Text tests_JournalReader :: Test () -- | A reader for CSV data, using an extra rules file to help interpret the -- data. module Hledger.Read.CsvReader reader :: Reader type CsvRecord = [String] type CSV = [Record] type Record = [Field] type Field = String rulesFileFor :: FilePath -> FilePath -- | An error-throwing action that parses this file's content as CSV -- conversion rules, interpolating any included files first, and runs -- some extra validation checks. parseRulesFile :: FilePath -> ExceptT String IO CsvRules -- | An error-throwing action that parses this text as CSV conversion rules -- and runs some extra validation checks. The file path is for error -- messages. parseAndValidateCsvRules :: FilePath -> Text -> ExceptT String IO CsvRules -- | Inline all files referenced by include directives in this hledger CSV -- rules text, recursively. Included file paths may be relative to the -- directory of the provided file path. This is a cheap hack to avoid -- rewriting the CSV rules parser. expandIncludes :: FilePath -> Text -> IO Text transactionFromCsvRecord :: SourcePos -> CsvRules -> CsvRecord -> Transaction printCSV :: CSV -> String tests_CsvReader :: Test () instance GHC.Classes.Eq Hledger.Read.CsvReader.CsvRules instance GHC.Show.Show Hledger.Read.CsvReader.CsvRules instance GHC.Show.Show Hledger.Read.CsvReader.CSVError instance Text.Megaparsec.Error.ShowErrorComponent GHC.Base.String -- | This is the entry point to hledger's reading system, which can read -- Journals from various data formats. Use this module if you want to -- parse journal data or read journal files. Generally it should not be -- necessary to import modules below this one. module Hledger.Read -- | A file path optionally prefixed by a reader name and colon (journal:, -- csv:, timedot:, etc.). type PrefixedFilePath = FilePath -- | Read the default journal file specified by the environment, or raise -- an error. defaultJournal :: IO Journal -- | Get the default journal file path specified by the environment. Like -- ledger, we look first for the LEDGER_FILE environment variable, and if -- that does not exist, for the legacy LEDGER environment variable. If -- neither is set, or the value is blank, return the hard-coded default, -- which is .hledger.journal in the users's home directory (or -- in the current directory, if we cannot determine a home directory). defaultJournalPath :: IO String -- | Read a Journal from each specified file path and combine them into -- one. Or, return the first error message. -- -- Combining Journals means concatenating them, basically. The parse -- state resets at the start of each file, which means that directives -- & aliases do not affect subsequent sibling or parent files. They -- do affect included child files though. Also the final parse state -- saved in the Journal does span all files. readJournalFiles :: InputOpts -> [PrefixedFilePath] -> IO (Either String Journal) -- | Read a Journal from this file, or from stdin if the file path is -, or -- return an error message. The file path can have a READER: prefix. -- -- The reader (data format) to use is determined from (in priority -- order): the mformat_ specified in the input options, if any; -- the file path's READER: prefix, if any; a recognised file name -- extension. if none of these identify a known reader, all built-in -- readers are tried in turn. -- -- The input options can also configure balance assertion checking, -- automated posting generation, a rules file for converting CSV data, -- etc. readJournalFile :: InputOpts -> PrefixedFilePath -> IO (Either String Journal) -- | If the specified journal file does not exist (and is not "-"), give a -- helpful error and quit. requireJournalFileExists :: FilePath -> IO () -- | Ensure there is a journal file at the given path, creating an empty -- one if needed. ensureJournalFileExists :: FilePath -> IO () -- | If a filepath is prefixed by one of the reader names and a colon, -- split that off. Eg "csv:-" -> (Just "csv", "-"). splitReaderPrefix :: PrefixedFilePath -> (Maybe String, FilePath) -- |
-- readJournal iopts mfile txt ---- -- Read a Journal from some text, or return an error message. -- -- The reader (data format) is chosen based on a recognised file name -- extension in mfile (if provided). If it does not identify a -- known reader, all built-in readers are tried in turn (returning the -- first one's error message if none of them succeed). -- -- Input ioptions (iopts) specify CSV conversion rules file to -- help convert CSV data, enable or disable balance assertion checking -- and automated posting generation. readJournal :: InputOpts -> Maybe FilePath -> Text -> IO (Either String Journal) -- | Read a Journal from the given text trying all readers in turn, or -- throw an error. readJournal' :: Text -> IO Journal postingp :: Maybe Year -> JournalParser m Posting tests_Read :: Test () -- | Balance report, used by the balance command. module Hledger.Reports.BalanceReport -- | A simple balance report. It has: -- --