{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ViewPatterns #-}
module Hledger.Cli.Commands.Rewrite (
rewritemode
,rewrite
)
where
import Control.Monad (unless)
import Data.Either (partitionEithers)
import Data.Functor.Identity
import Data.List (dropWhileEnd, find, sortOn)
import Data.Map qualified as M
import Data.Maybe (isJust)
import Data.Text (Text)
import Data.Text qualified as T
import Hledger
import Hledger.Cli.CliOptions
import Hledger.Cli.Utils (writeOutput)
import Hledger.Cli.Commands.Print
import System.Console.CmdArgs.Explicit
import System.IO (hPutStr, stderr)
import Text.Megaparsec hiding (pos1)
import Text.Printf (printf)
import Data.Algorithm.DiffContext qualified as D
import Text.PrettyPrint (render, text)
rewritemode :: Mode RawOpts
rewritemode = String
-> [Flag RawOpts]
-> [(String, [Flag RawOpts])]
-> [Flag RawOpts]
-> ([Arg RawOpts], Maybe (Arg RawOpts))
-> Mode RawOpts
hledgerCommandMode
$(embedFileRelative "Hledger/Cli/Commands/Rewrite.txt")
[[String] -> Update RawOpts -> String -> String -> Flag RawOpts
forall a. [String] -> Update a -> String -> String -> Flag a
flagReq [String
"add-posting"] (\String
s RawOpts
opts -> RawOpts -> Either String RawOpts
forall a b. b -> Either a b
Right (RawOpts -> Either String RawOpts)
-> RawOpts -> Either String RawOpts
forall a b. (a -> b) -> a -> b
$ String -> String -> RawOpts -> RawOpts
setopt String
"add-posting" String
s RawOpts
opts) String
"'ACCT AMTEXPR'"
String
"add a posting to ACCT, which may be parenthesised. AMTEXPR is either a literal amount, or *N which means the transaction's first matched amount multiplied by N (a decimal number). Two spaces separate ACCT and AMTEXPR."
,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"diff"] (String -> RawOpts -> RawOpts
setboolopt String
"diff") String
"generate diff suitable as an input for patch tool"
,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"verbose-tags"] (String -> RawOpts -> RawOpts
setboolopt String
"verbose-tags") String
"add tags indicating generated/modified data"
,Flag RawOpts
layoutFlag
]
[(String, [Flag RawOpts])]
cligeneralflagsgroups1
[Flag RawOpts]
hiddenflags
([], Arg RawOpts -> Maybe (Arg RawOpts)
forall a. a -> Maybe a
Just (Arg RawOpts -> Maybe (Arg RawOpts))
-> Arg RawOpts -> Maybe (Arg RawOpts)
forall a b. (a -> b) -> a -> b
$ String -> Arg RawOpts
argsFlag String
"[QUERY] --add-posting \"ACCT AMTEXPR\" ...")
rewrite :: CliOpts -> Journal -> IO ()
rewrite opts :: CliOpts
opts@CliOpts{rawopts_ :: CliOpts -> RawOpts
rawopts_=RawOpts
rawopts,reportspec_ :: CliOpts -> ReportSpec
reportspec_=ReportSpec
rspec} j :: Journal
j@Journal{jtxns :: Journal -> [Transaction]
jtxns=[Transaction]
ts} = do
let
today :: Day
today = ReportSpec -> Day
_rsDay ReportSpec
rspec
verbosetags :: Bool
verbosetags = String -> RawOpts -> Bool
boolopt String
"verbose-tags" RawOpts
rawopts
modifiers :: [TransactionModifier]
modifiers = CliOpts -> TransactionModifier
transactionModifierFromOpts CliOpts
opts TransactionModifier
-> [TransactionModifier] -> [TransactionModifier]
forall a. a -> [a] -> [a]
: Journal -> [TransactionModifier]
jtxnmodifiers Journal
j
let j' :: Journal
j' = Journal
j{jtxns=either error' id $ modifyTransactions (journalAccountType j) (journalInheritedAccountTags j) mempty today verbosetags modifiers ts}
RawOpts -> CliOpts -> Journal -> Journal -> IO ()
printOrDiff RawOpts
rawopts CliOpts
opts{reportspec_=rspec{_rsQuery=Any}} Journal
j Journal
j'
transactionModifierFromOpts :: CliOpts -> TransactionModifier
transactionModifierFromOpts :: CliOpts -> TransactionModifier
transactionModifierFromOpts CliOpts{rawopts_ :: CliOpts -> RawOpts
rawopts_=RawOpts
rawopts} =
TransactionModifier{tmquerytxt :: Text
tmquerytxt=Text
q, tmpostingrules :: [TMPostingRule]
tmpostingrules=[TMPostingRule]
ps}
where
q :: Text
q = String -> Text
T.pack (String -> Text) -> ([String] -> String) -> [String] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [String] -> String
unwords ([String] -> String)
-> ([String] -> [String]) -> [String] -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (String -> String) -> [String] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map String -> String
quoteIfNeeded ([String] -> Text) -> [String] -> Text
forall a b. (a -> b) -> a -> b
$ String -> RawOpts -> [String]
listofstringopt String
"args" RawOpts
rawopts
ps :: [TMPostingRule]
ps = (String -> TMPostingRule) -> [String] -> [TMPostingRule]
forall a b. (a -> b) -> [a] -> [b]
map (Text -> TMPostingRule
parseposting (Text -> TMPostingRule)
-> (String -> Text) -> String -> TMPostingRule
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Text
T.pack) ([String] -> [TMPostingRule]) -> [String] -> [TMPostingRule]
forall a b. (a -> b) -> a -> b
$ String -> RawOpts -> [String]
listofstringopt String
"add-posting" RawOpts
rawopts
parseposting :: Text -> TMPostingRule
parseposting Text
t = (ParseErrorBundle Text HledgerParseErrorData -> TMPostingRule)
-> (TMPostingRule -> TMPostingRule)
-> Either
(ParseErrorBundle Text HledgerParseErrorData) TMPostingRule
-> TMPostingRule
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (String -> TMPostingRule
forall a. String -> a
error' (String -> TMPostingRule)
-> (ParseErrorBundle Text HledgerParseErrorData -> String)
-> ParseErrorBundle Text HledgerParseErrorData
-> TMPostingRule
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ParseErrorBundle Text HledgerParseErrorData -> String
forall s e.
(VisualStream s, TraversableStream s, ShowErrorComponent e) =>
ParseErrorBundle s e -> String
errorBundlePretty) TMPostingRule -> TMPostingRule
forall a. a -> a
id Either (ParseErrorBundle Text HledgerParseErrorData) TMPostingRule
ep
where
ep :: Either (ParseErrorBundle Text HledgerParseErrorData) TMPostingRule
ep = Identity
(Either
(ParseErrorBundle Text HledgerParseErrorData) TMPostingRule)
-> Either
(ParseErrorBundle Text HledgerParseErrorData) TMPostingRule
forall a. Identity a -> a
runIdentity (JournalParser Identity TMPostingRule
-> Text
-> Identity
(Either
(ParseErrorBundle Text HledgerParseErrorData) TMPostingRule)
forall (m :: * -> *) a.
Monad m =>
JournalParser m a
-> Text
-> m (Either (ParseErrorBundle Text HledgerParseErrorData) a)
runJournalParser (Maybe Year -> JournalParser Identity TMPostingRule
forall (m :: * -> *). Maybe Year -> JournalParser m TMPostingRule
tmpostingrulep Maybe Year
forall a. Maybe a
Nothing JournalParser Identity TMPostingRule
-> StateT Journal (ParsecT HledgerParseErrorData Text Identity) ()
-> JournalParser Identity TMPostingRule
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text Identity) a
-> StateT Journal (ParsecT HledgerParseErrorData Text Identity) b
-> StateT Journal (ParsecT HledgerParseErrorData Text Identity) a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* StateT Journal (ParsecT HledgerParseErrorData Text Identity) ()
forall e s (m :: * -> *). MonadParsec e s m => m ()
eof) Text
t')
t' :: Text
t' = Text
" " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
t Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"\n"
printOrDiff :: RawOpts -> (CliOpts -> Journal -> Journal -> IO ())
printOrDiff :: RawOpts -> CliOpts -> Journal -> Journal -> IO ()
printOrDiff RawOpts
opts
| String -> RawOpts -> Bool
boolopt String
"diff" RawOpts
opts = PostingLayout -> CliOpts -> Journal -> Journal -> IO ()
diffOutput (RawOpts -> PostingLayout
layoutFromRawOpts RawOpts
opts)
| Bool
otherwise = (Journal -> CliOpts -> Journal -> IO ())
-> CliOpts -> Journal -> Journal -> IO ()
forall a b c. (a -> b -> c) -> b -> a -> c
flip ((CliOpts -> Journal -> IO ())
-> Journal -> CliOpts -> Journal -> IO ()
forall a b. a -> b -> a
const CliOpts -> Journal -> IO ()
print')
diffContextLines :: Int
diffContextLines :: Int
diffContextLines = Int
3
type Edit = (Int, Int, [Text])
diffOutput :: PostingLayout -> CliOpts -> Journal -> Journal -> IO ()
diffOutput :: PostingLayout -> CliOpts -> Journal -> Journal -> IO ()
diffOutput PostingLayout
postinglayout CliOpts
opts Journal
j Journal
j' = do
Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ([Text] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Text]
unpatchable) (IO () -> IO ()) -> (String -> IO ()) -> String -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Handle -> String -> IO ()
hPutStr Handle
stderr (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ [Text] -> String
unpatchableWarning [Text]
unpatchable
CliOpts -> String -> IO ()
writeOutput CliOpts
opts (String -> IO ())
-> ([(String, [Edit])] -> String) -> [(String, [Edit])] -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> String
T.unpack (Text -> String)
-> ([(String, [Edit])] -> Text) -> [(String, [Edit])] -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((String, [Edit]) -> Text) -> [(String, [Edit])] -> Text
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (String, [Edit]) -> Text
fileDiff ([(String, [Edit])] -> IO ()) -> [(String, [Edit])] -> IO ()
forall a b. (a -> b) -> a -> b
$ Map String [Edit] -> [(String, [Edit])]
forall k a. Map k a -> [(k, a)]
M.toAscList Map String [Edit]
editsbyfile
where
changed :: [(Transaction, Transaction)]
changed = [(Bool -> Transaction -> Transaction
transactionWithMostlyOriginalPostings Bool
False Transaction
t, Bool -> Transaction -> Transaction
transactionWithMostlyOriginalPostings Bool
False Transaction
t')
| (Transaction
t, Transaction
t') <- [Transaction] -> [Transaction] -> [(Transaction, Transaction)]
forall a b. [a] -> [b] -> [(a, b)]
zip (Journal -> [Transaction]
jtxns Journal
j) (Journal -> [Transaction]
jtxns Journal
j'), Transaction
t Transaction -> Transaction -> Bool
forall a. Eq a => a -> a -> Bool
/= Transaction
t']
([(String, [Edit])]
edits, [Text]
unpatchable) = [Either (String, [Edit]) Text] -> ([(String, [Edit])], [Text])
forall a b. [Either a b] -> ([a], [b])
partitionEithers ([Either (String, [Edit]) Text] -> ([(String, [Edit])], [Text]))
-> [Either (String, [Edit]) Text] -> ([(String, [Edit])], [Text])
forall a b. (a -> b) -> a -> b
$ ((Transaction, Transaction) -> Either (String, [Edit]) Text)
-> [(Transaction, Transaction)] -> [Either (String, [Edit]) Text]
forall a b. (a -> b) -> [a] -> [b]
map (Transaction, Transaction) -> Either (String, [Edit]) Text
txnEdit [(Transaction, Transaction)]
changed
editsbyfile :: Map String [Edit]
editsbyfile = ([Edit] -> [Edit] -> [Edit])
-> [(String, [Edit])] -> Map String [Edit]
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith [Edit] -> [Edit] -> [Edit]
forall a. [a] -> [a] -> [a]
(++) [(String, [Edit])]
edits
txnEdit :: (Transaction, Transaction) -> Either (String, [Edit]) Text
txnEdit (Transaction
t, Transaction
t')
| Maybe Text -> Bool
forall a. Maybe a -> Bool
isJust (Maybe Text -> Bool) -> ([Tag] -> Maybe Text) -> [Tag] -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> [Tag] -> Maybe Text
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup Text
generatedTransactionTagName ([Tag] -> Bool) -> [Tag] -> Bool
forall a b. (a -> b) -> a -> b
$ Transaction -> [Tag]
ttags Transaction
t =
Text -> Either (String, [Edit]) Text
forall a b. b -> Either a b
Right Text
"generated by a periodic transaction rule"
| (SourcePos String
fp Pos
line Pos
_, SourcePos String
_ Pos
line' Pos
_) <- Transaction -> (SourcePos, SourcePos)
tsourcepos Transaction
t, Pos
line' Pos -> Pos -> Bool
forall a. Ord a => a -> a -> Bool
> Pos
line =
(String, [Edit]) -> Either (String, [Edit]) Text
forall a b. a -> Either a b
Left (String
fp, [(Pos -> Int
unPos Pos
line, Pos -> Int
unPos Pos
line', [Text]
newlines)])
| Bool
otherwise = Text -> Either (String, [Edit]) Text
forall a b. b -> Either a b
Right (Text -> Either (String, [Edit]) Text)
-> (String -> Text) -> String -> Either (String, [Edit]) Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Text
T.pack (String -> Either (String, [Edit]) Text)
-> String -> Either (String, [Edit]) Text
forall a b. (a -> b) -> a -> b
$ String
"read from " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> SourcePos -> String
sourceName ((SourcePos, SourcePos) -> SourcePos
forall a b. (a, b) -> a
fst ((SourcePos, SourcePos) -> SourcePos)
-> (SourcePos, SourcePos) -> SourcePos
forall a b. (a -> b) -> a -> b
$ Transaction -> (SourcePos, SourcePos)
tsourcepos Transaction
t)
where
newlines :: [Text]
newlines = (Text -> Bool) -> [Text] -> [Text]
forall a. (a -> Bool) -> [a] -> [a]
dropWhileEnd Text -> Bool
T.null ([Text] -> [Text]) -> (Text -> [Text]) -> Text -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> [Text]
T.lines (Text -> [Text]) -> Text -> [Text]
forall a b. (a -> b) -> a -> b
$ PostingLayout -> Transaction -> Text
showTransactionWithLayout PostingLayout
postinglayout Transaction
t'
fileDiff :: (String, [Edit]) -> Text
fileDiff (String
fp, [Edit]
es) = case JournalFile -> Text
jftext (JournalFile -> Text) -> Maybe JournalFile -> Maybe Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (JournalFile -> Bool) -> [JournalFile] -> Maybe JournalFile
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find ((String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
fp) (String -> Bool) -> (JournalFile -> String) -> JournalFile -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. JournalFile -> String
jfpath) (Journal -> [JournalFile]
jfiles Journal
j) of
Maybe Text
Nothing -> Text
""
Just Text
contents -> String -> [Text] -> [Text] -> Text
unifiedDiff String
fp [Text]
oldlines ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ [Edit] -> [Text] -> [Text]
applyEdits ((Edit -> Int) -> [Edit] -> [Edit]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn Edit -> Int
forall {a} {b} {c}. (a, b, c) -> a
first3 [Edit]
es) [Text]
oldlines
where oldlines :: [Text]
oldlines = Text -> [Text]
T.lines Text
contents
unpatchableWarning :: [Text] -> String
unpatchableWarning :: [Text] -> String
unpatchableWarning [Text]
reasons = [String] -> String
unlines ([String] -> String) -> [String] -> String
forall a b. (a -> b) -> a -> b
$
String -> Int -> String -> String
forall r. PrintfType r => String -> r
printf String
"warning: %d changed transaction%s not shown in the diff, having no journal entry to patch:"
Int
n (if Int
n Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== (Int
1::Int) then String
" is" else String
"s are" :: String)
String -> [String] -> [String]
forall a. a -> [a] -> [a]
: [String -> Int -> String -> String
forall r. PrintfType r => String -> r
printf String
" %d %s" Int
howmany String
reason | (String
reason, Int
howmany) <- Map String Int -> [(String, Int)]
forall k a. Map k a -> [(k, a)]
M.toAscList Map String Int
reasoncounts]
where
n :: Int
n = [Text] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Text]
reasons
reasoncounts :: Map String Int
reasoncounts = (Int -> Int -> Int) -> [(String, Int)] -> Map String Int
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith Int -> Int -> Int
forall a. Num a => a -> a -> a
(+) [(Text -> String
T.unpack Text
r, Int
1::Int) | Text
r <- [Text]
reasons]
applyEdits :: [Edit] -> [Text] -> [Text]
applyEdits :: [Edit] -> [Text] -> [Text]
applyEdits = Int -> [Edit] -> [Text] -> [Text]
forall {a}. Int -> [(Int, Int, [a])] -> [a] -> [a]
go Int
1
where
go :: Int -> [(Int, Int, [a])] -> [a] -> [a]
go Int
_ [] [a]
ls = [a]
ls
go Int
lineno ((Int
start, Int
end, [a]
new):[(Int, Int, [a])]
es) [a]
ls
| Int
start Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
lineno Bool -> Bool -> Bool
|| Int
end Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
start = Int -> [(Int, Int, [a])] -> [a] -> [a]
go Int
lineno [(Int, Int, [a])]
es [a]
ls
| Bool
otherwise = [a]
before [a] -> [a] -> [a]
forall a. Semigroup a => a -> a -> a
<> [a]
new [a] -> [a] -> [a]
forall a. Semigroup a => a -> a -> a
<> Int -> [(Int, Int, [a])] -> [a] -> [a]
go Int
end [(Int, Int, [a])]
es (Int -> [a] -> [a]
forall a. Int -> [a] -> [a]
drop (Int
endInt -> Int -> Int
forall a. Num a => a -> a -> a
-Int
start) [a]
rest)
where ([a]
before, [a]
rest) = Int -> [a] -> ([a], [a])
forall a. Int -> [a] -> ([a], [a])
splitAt (Int
startInt -> Int -> Int
forall a. Num a => a -> a -> a
-Int
lineno) [a]
ls
unifiedDiff :: FilePath -> [Text] -> [Text] -> Text
unifiedDiff :: String -> [Text] -> [Text] -> Text
unifiedDiff String
fp [Text]
old [Text]
new
| [Hunk (Numbered Text)] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Hunk (Numbered Text)]
hunks = Text
""
| Bool
otherwise = String -> Text
T.pack (String -> Text) -> (Doc -> String) -> Doc -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Doc -> String
render (Doc -> Text) -> Doc -> Text
forall a b. (a -> b) -> a -> b
$ Doc
-> Doc -> (Numbered Text -> Doc) -> [Hunk (Numbered Text)] -> Doc
forall c.
Doc
-> Doc -> (Numbered c -> Doc) -> ContextDiff (Numbered c) -> Doc
D.prettyContextDiff (String -> Doc
text String
fp) (String -> Doc
text String
fp) (String -> Doc
text (String -> Doc)
-> (Numbered Text -> String) -> Numbered Text -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> String
T.unpack (Text -> String)
-> (Numbered Text -> Text) -> Numbered Text -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Numbered Text -> Text
forall a. Numbered a -> a
D.unnumber) [Hunk (Numbered Text)]
hunks
where hunks :: [Hunk (Numbered Text)]
hunks = Maybe Int -> [Text] -> [Text] -> [Hunk (Numbered Text)]
forall a.
Eq a =>
Maybe Int -> [a] -> [a] -> ContextDiff (Numbered a)
D.getContextDiff (Int -> Maybe Int
forall a. a -> Maybe a
Just Int
diffContextLines) [Text]
old [Text]
new