Skip to content

Instantly share code, notes, and snippets.

@simonmichael
Last active October 6, 2019 21:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simonmichael/b2abecc13b95abcb5f9fbf3f99debc91 to your computer and use it in GitHub Desktop.
Save simonmichael/b2abecc13b95abcb5f9fbf3f99debc91 to your computer and use it in GitHub Desktop.
hledger script, prototyping print --location
#!/usr/bin/env stack
{- stack runghc --verbosity info
--package hledger-lib
--package hledger
--package here
--package text
-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
import Data.String.Here
import Data.Text (pack)
import Text.Printf
import Hledger
import Hledger.Cli
------------------------------------------------------------------------------
cmdmode = hledgerCommandMode
[here| print-location
Like print, but adds tags showing the file path and location of transactions.
FLAGS
|]
[]
[generalflagsgroup1]
[]
([], Just $ argsFlag "[QUERY]")
------------------------------------------------------------------------------
main :: IO ()
main = do
opts <- getHledgerCliOpts cmdmode
withJournalDo opts $ \j ->
print' opts j{jtxns = map addLocationTag $ jtxns j}
addLocationTag :: Transaction -> Transaction
addLocationTag t = t{tcomment = tcomment t `commentAddTagNextLine` loctag}
where
loctag = ("location", pack $ showGenericSourcePosLine $ tsourcepos t)
-- Like showGenericSourcePos in Hledger.Data.Transaction, but show just the starting line number.
showGenericSourcePosLine :: GenericSourcePos -> String
showGenericSourcePosLine (GenericSourcePos f line _) = printf "%s:%d" f line
showGenericSourcePosLine (JournalSourcePos f (startline, _)) = printf "%s:%d" f startline
{-
$ hledger print-location -f examples/sample.journal desc:eat
2008/06/03 * eat & shop
; location: /Users/simon/src/hledger/examples/sample.journal:30
expenses:food $1
expenses:supplies $1
assets:cash
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment