Debian Codegraph @

Hledger/Cli/Commands/Rewrite.hs

raw
1 {-# LANGUAGE CPP #-}
2 {-# LANGUAGE DeriveTraversable #-}
3 {-# LANGUAGE LambdaCase #-}
4 {-# LANGUAGE OverloadedStrings #-}
5 {-# LANGUAGE TemplateHaskell #-}
6 {-# LANGUAGE ViewPatterns #-}
7
8 module Hledger.Cli.Commands.Rewrite (
9 rewritemode
10 ,rewrite
11 )
12 where
13
14 import Data.Functor.Identity
15 import Data.List (sortOn)
16 #if !MIN_VERSION_base(4,20,0)
17 import Data.List (foldl')
18 #endif
19 import Data.Text (Text)
20 import Data.Text qualified as T
21 import Data.Text.IO qualified as T
22 import Hledger
23 import Hledger.Cli.CliOptions
24 import Hledger.Cli.Commands.Print
25 import System.Console.CmdArgs.Explicit
26 import Text.Printf
27 import Text.Megaparsec hiding (pos1)
28 import Data.Algorithm.Diff qualified as D
29
30 rewritemode = hledgerCommandMode
31 $(embedFileRelative "Hledger/Cli/Commands/Rewrite.txt")
32 [flagReq ["add-posting"] (\s opts -> Right $ setopt "add-posting" s opts) "'ACCT AMTEXPR'"
33 "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."
34 ,flagNone ["diff"] (setboolopt "diff") "generate diff suitable as an input for patch tool"
35 ]
36 cligeneralflagsgroups1
37 hiddenflags
38 ([], Just $ argsFlag "[QUERY] --add-posting \"ACCT AMTEXPR\" ...")
39
40 -- TODO regex matching and interpolating matched name in replacement
41 -- TODO interpolating match groups in replacement
42 -- TODO allow using this on unbalanced entries, eg to rewrite while editing
43
44 rewrite opts@CliOpts{rawopts_=rawopts,reportspec_=rspec} j@Journal{jtxns=ts} = do
45 -- rewrite matched transactions
46 let
47 today = _rsDay rspec
48 verbosetags = boolopt "verbose-tags" rawopts
49 modifiers = transactionModifierFromOpts opts : jtxnmodifiers j
50 let j' = j{jtxns=either error' id $ modifyTransactions (journalAccountType j) (journalInheritedAccountTags j) mempty today verbosetags modifiers ts} -- PARTIAL:
51 -- run the print command, showing all transactions, or show diffs
52 printOrDiff rawopts opts{reportspec_=rspec{_rsQuery=Any}} j j'
53
54 -- | Build a 'TransactionModifier' from any query arguments and --add-posting flags
55 -- provided on the command line, or throw a parse error.
56 transactionModifierFromOpts :: CliOpts -> TransactionModifier
57 transactionModifierFromOpts CliOpts{rawopts_=rawopts} =
58 TransactionModifier{tmquerytxt=q, tmpostingrules=ps}
59 where
60 q = T.pack . unwords . map quoteIfNeeded $ listofstringopt "args" rawopts
61 ps = map (parseposting . T.pack) $ listofstringopt "add-posting" rawopts
62 parseposting t = either (error' . errorBundlePretty) id ep -- PARTIAL:
63 where
64 ep = runIdentity (runJournalParser (tmpostingrulep Nothing <* eof) t')
65 t' = " " <> t <> "\n" -- inject space and newline for proper parsing
66
67 printOrDiff :: RawOpts -> (CliOpts -> Journal -> Journal -> IO ())
68 printOrDiff opts
69 | boolopt "diff" opts = const diffOutput
70 | otherwise = flip (const print')
71
72 diffOutput :: Journal -> Journal -> IO ()
73 diffOutput j j' = do
74 let changed = [(transactionWithMostlyOriginalPostings t, transactionWithMostlyOriginalPostings t') | (t, t') <- zip (jtxns j) (jtxns j'), t /= t']
75 T.putStr $ renderPatch $ map (uncurry $ diffTxn j) changed
76
77 type Chunk = (SourcePos, [DiffLine Text])
78
79 -- XXX doctests, update needed:
80 -- >>> putStr $ renderPatch [(GenericSourcePos "a" 1 1, [D.First "x", D.Second "y"])]
81 -- --- a
82 -- +++ a
83 -- @@ -1,1 +1,1 @@
84 -- -x
85 -- +y
86 -- >>> putStr $ renderPatch [(GenericSourcePos "a" 1 1, [D.Both "x" "x", D.Second "y"]), (GenericSourcePos "a" 5 1, [D.Second "z"])]
87 -- --- a
88 -- +++ a
89 -- @@ -1,1 +1,2 @@
90 -- x
91 -- +y
92 -- @@ -5,0 +6,1 @@
93 -- +z
94 -- >>> putStr $ renderPatch [(GenericSourcePos "a" 1 1, [D.Both "x" "x", D.Second "y"]), (GenericSourcePos "b" 5 1, [D.Second "z"])]
95 -- --- a
96 -- +++ a
97 -- @@ -1,1 +1,2 @@
98 -- x
99 -- +y
100 -- --- b
101 -- +++ b
102 -- @@ -5,0 +5,1 @@
103 -- +z
104 -- | Render list of changed lines as a unified diff
105 renderPatch :: [Chunk] -> Text
106 renderPatch = go Nothing . sortOn fst where
107 go _ [] = ""
108 go Nothing cs@((SourcePos fp _ _, _):_) = fileHeader fp <> go (Just (fp, 0)) cs
109 go (Just (fp, _)) cs@((SourcePos fp' _ _, _):_) | fp /= fp' = go Nothing cs
110 go (Just (fp, offs)) ((SourcePos _ lineno _, diffs):cs) = chunkHeader <> chnk <> go (Just (fp, offs + adds - dels)) cs
111 where
112 chunkHeader = T.pack $ printf "@@ -%d,%d +%d,%d @@\n" (unPos lineno) dels (unPos lineno+offs) adds
113 (dels, adds) = foldl' countDiff (0, 0) diffs
114 chnk = foldMap renderLine diffs
115 fileHeader fp = "--- " <> T.pack fp <> "\n+++ " <> T.pack fp <> "\n"
116
117 countDiff (dels, adds) = \case
118 Del _ -> (dels + 1, adds)
119 Add _ -> (dels , adds + 1)
120 Ctx _ -> (dels + 1, adds + 1)
121
122 renderLine = \case
123 Del s -> "-" <> s <> "\n"
124 Add s -> "+" <> s <> "\n"
125 Ctx s -> " " <> s <> "\n"
126
127 diffTxn :: Journal -> Transaction -> Transaction -> Chunk
128 diffTxn j t t' = case tsourcepos t of
129 (pos1@(SourcePos fp line col), pos2) | pos1 == pos2 -> (SourcePos fp (line <> mkPos 1) col, diffs) where
130 -- TODO: use range and produce two chunks: one removes part of
131 -- original file, other adds transaction to new file with
132 -- suffix .ledger (generated). I.e. move transaction from one file to another.
133 diffs :: [DiffLine Text]
134 diffs = concatMap (traverse showPostingLines . mapDiff) $ D.getDiff (tpostings t) (tpostings t')
135 (pos1@(SourcePos fp line _), SourcePos _ line' _) -> (pos1, diffs) where
136 -- We do diff for original lines vs generated ones. Often leads
137 -- to big diff because of re-format effect.
138 diffs :: [DiffLine Text]
139 diffs = map mapDiff $ D.getDiff source changed'
140 source | Just contents <- lookup fp $ jfiles j = drop (unPos line-1) . take (unPos line' - 1) $ T.lines contents
141 | otherwise = []
142 changed = T.lines $ showTransaction t'
143 changed' | null changed = changed
144 | T.null $ last changed = init changed
145 | otherwise = changed
146
147 data DiffLine a = Del a | Add a | Ctx a
148 deriving (Show, Functor, Foldable, Traversable)
149
150 mapDiff :: D.Diff a -> DiffLine a
151 mapDiff = \case
152 D.First x -> Del x
153 D.Second x -> Add x
154 D.Both x _ -> Ctx x