Skip to content

Commit c7079e2

Browse files
committed
imp: add, close, import, rewrite: support --layout, like print
The other print-like commands — import, close, rewrite, add — can now also have their layout customised, like print.
1 parent 5c93ce8 commit c7079e2

13 files changed

Lines changed: 121 additions & 23 deletions

File tree

hledger/Hledger/Cli/Commands/Add.hs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -52,13 +52,16 @@ import Text.Printf
5252

5353
import Hledger
5454
import Hledger.Cli.CliOptions
55+
import Hledger.Cli.Commands.Print (layoutFlag, layoutFromRawOpts)
5556
import Hledger.Cli.Commands.Register (postingsReportAsText)
5657
import Hledger.Cli.Utils (journalSimilarTransaction)
5758

5859

5960
addmode = hledgerCommandMode
6061
$(embedFileRelative "Hledger/Cli/Commands/Add.txt")
61-
[flagNone ["no-new-accounts"] (setboolopt "no-new-accounts") "don't allow creating new accounts"]
62+
[flagNone ["no-new-accounts"] (setboolopt "no-new-accounts") "don't allow creating new accounts"
63+
,layoutFlag
64+
]
6265
[generalflagsgroup2]
6366
confflags
6467
([], Just $ argsFlag "[-f JOURNALFILE] [DATE [DESCRIPTION [ACCOUNT1 [ETC..]]]]]")
@@ -195,7 +198,7 @@ transactionWizard previnput state@AddState{..} stack@(currentStage : _) = case c
195198
previnput' = previnput{prevDescAndCmnt=Just descAndCommentString}
196199
when (isJust mbaset) . liftIO $ do
197200
hPutStrLn stderr "Using this similar transaction for defaults:"
198-
T.hPutStr stderr $ showTransaction (fromJust mbaset)
201+
T.hPutStr stderr $ showTransactionWithLayout (layoutFromRawOpts $ rawopts_ asOpts) (fromJust mbaset)
199202
transactionWizard previnput' state' ((GetPosting TxnData{txnDate=date, txnCode=code, txnDesc=desc, txnCmnt=comment} Nothing) : stack)
200203
Nothing ->
201204
transactionWizard previnput state (drop 1 stack)
@@ -280,7 +283,7 @@ transactionWizard previnput state@AddState{..} stack@(currentStage : _) = case c
280283
Nothing -> transactionWizard previnput state (drop 1 stack)
281284

282285
Confirm t -> do
283-
output . T.unpack $ showTransaction t
286+
output . T.unpack $ showTransactionWithLayout (layoutFromRawOpts $ rawopts_ asOpts) t
284287
y <- let def = "y" in
285288
retryMsg "Please enter y or n." $
286289
parser ((fmap (\c -> if c == '<' then Nothing else Just c)) . headMay . map toLower . strip) $
@@ -510,11 +513,12 @@ postingsAreBalanced j ps = isRight $ balanceSingleTransaction bopts nulltransact
510513
journalAddTransaction :: Journal -> CliOpts -> Transaction -> IO Journal
511514
journalAddTransaction j@Journal{jtxns=ts} opts t = do
512515
let f = journalFilePath j
513-
appendToJournalFileOrStdout f $ showTransaction t
516+
showtxn = showTransactionWithLayout (layoutFromRawOpts $ rawopts_ opts)
517+
appendToJournalFileOrStdout f $ showtxn t
514518
-- unelided shows all amounts explicitly, in case there's a price, cf #283
515519
when (debug_ opts > 0) $ do
516520
putStrLn $ printf "\nAdded transaction to %s:" f
517-
TL.putStrLn =<< registerFromString (showTransaction t)
521+
TL.putStrLn =<< registerFromString (showtxn t)
518522
return j{jtxns=ts++[t]}
519523

520524
-- | Append a string, typically one or more transactions, to a journal

hledger/Hledger/Cli/Commands/Add.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@ Add new transactions to a journal file, with interactive prompting.
55
```flags
66
Flags:
77
--no-new-accounts don't allow creating new accounts
8+
--layout=hledger1|COL how should posting amounts be aligned ?
9+
hledger1 - right-align amounts, as in hledger 1
10+
COL - align decimal marks at column COL
11+
(default: 53)
812
```
913

1014
Many hledger users edit their journals directly with a text editor, or generate them from CSV.

hledger/Hledger/Cli/Commands/Close.hs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ import Safe (lastDef, readMay, readDef)
2222
import System.FilePath (takeBaseName)
2323
import Data.Char (isDigit)
2424
import Hledger.Read.RulesReader (parseBalanceAssertionType)
25-
import Hledger.Cli.Commands.Print (roundFlag, amountStylesSetRoundingFromRawOpts)
25+
import Hledger.Cli.Commands.Print (roundFlag, amountStylesSetRoundingFromRawOpts, layoutFlag, layoutFromRawOpts)
2626

2727
defclosedesc = "closing balances"
2828
defopendesc = "opening balances"
@@ -48,6 +48,7 @@ closemode = hledgerCommandMode
4848
,flagReq ["open-desc"] (\s opts -> Right $ setopt "open-desc" s opts) "DESC" "set opening transaction's description"
4949
,flagReq ["open-acct"] (\s opts -> Right $ setopt "open-acct" s opts) "ACCT" "set opening transaction's source account"
5050
,roundFlag
51+
,layoutFlag
5152
]
5253
cligeneralflagsgroups1
5354
(hiddenflags
@@ -264,6 +265,8 @@ close CliOpts{rawopts_=rawopts, reportspec_=rspec0} j = do
264265
-- print them
265266
-- allow user-specified rounding with --round, like print
266267
let styles = amountStylesSetRoundingFromRawOpts rawopts $ journalCommodityStyles j
267-
maybe (pure ()) (T.putStr . showTransaction . styleAmounts styles) mclosetxn
268-
maybe (pure ()) (T.putStr . showTransaction . styleAmounts styles) mopentxn
268+
postinglayout = layoutFromRawOpts rawopts
269+
showtxn = showTransactionWithLayout postinglayout . styleAmounts styles
270+
maybe (pure ()) (T.putStr . showtxn) mclosetxn
271+
maybe (pure ()) (T.putStr . showtxn) mopentxn
269272

hledger/Hledger/Cli/Commands/Close.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,10 @@ Flags:
3535
(can unbalance transactions)
3636
all - also round cost amounts to precision
3737
(can unbalance transactions)
38+
--layout=hledger1|COL how should posting amounts be aligned ?
39+
hledger1 - right-align amounts, as in hledger 1
40+
COL - align decimal marks at column COL
41+
(default: 53)
3842
```
3943

4044
`close` has six modes, selected by choosing one of the mode flags:

hledger/Hledger/Cli/Commands/Import.hs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,15 @@ import Text.Printf
1818
import Hledger
1919
import Hledger.Cli.CliOptions
2020
import Hledger.Cli.Commands.Add (journalAddTransaction)
21+
import Hledger.Cli.Commands.Print (layoutFlag, layoutFromRawOpts)
2122
import System.IO (stderr)
2223
import System.FilePath (takeFileName)
2324

2425
importmode = hledgerCommandMode
2526
$(embedFileRelative "Hledger/Cli/Commands/Import.txt")
2627
[flagNone ["catchup"] (setboolopt "catchup") "just mark all transactions as already imported"
2728
,flagNone ["dry-run"] (setboolopt "dry-run") "just show the transactions to be imported"
29+
,layoutFlag
2830
]
2931
cligeneralflagsgroups1
3032
hiddenflags
@@ -37,6 +39,7 @@ importcmd opts@CliOpts{rawopts_=rawopts,inputopts_=iopts} j = do
3739
inputstr = intercalate ", " $ map (quoteIfNeeded.takeFileName) inputfiles
3840
catchup = boolopt "catchup" rawopts
3941
dryrun = boolopt "dry-run" rawopts
42+
postinglayout = layoutFromRawOpts rawopts
4043
combinedStyles =
4144
let
4245
maybeInputStyles = commodity_styles_ . balancingopts_ $ iopts
@@ -75,7 +78,7 @@ importcmd opts@CliOpts{rawopts_=rawopts,inputopts_=iopts} j = do
7578
then do
7679
-- show txns to be imported
7780
hPrintf stderr "would import %d new transactions from %s:\n\n" (length newts) inputstr
78-
mapM_ (T.putStr . showTransaction) newts
81+
mapM_ (T.putStr . showTransactionWithLayout postinglayout) newts
7982

8083
-- then check the whole journal with them added, if in strict mode
8184
when (strict_ iopts) $ strictChecks

hledger/Hledger/Cli/Commands/Import.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ Import new transactions from one or more data files to the main journal.
66
Flags:
77
--catchup just mark all transactions as already imported
88
--dry-run just show the transactions to be imported
9+
--layout=hledger1|COL how should posting amounts be aligned ?
10+
hledger1 - right-align amounts, as in hledger 1
11+
COL - align decimal marks at column COL
12+
(default: 53)
913
```
1014

1115
This command detects new transactions in one or more data files specified as arguments,

hledger/Hledger/Cli/Commands/Print.md

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -106,12 +106,7 @@ If you want to change the default, put something like this in `~/.hledger.conf`:
106106
--layout=hledger1
107107
```
108108

109-
Other print-like commands (close, import, rewrite, add..) use print's default layout.
110-
But they don't have a --layout option for customisation, currently.
111-
If you need that, you could pipe them through print. Eg:
112-
```
113-
hledger import *.rules --dry | hledger -I -f- print --layout 40
114-
```
109+
Other print-like commands (close, import, rewrite, add) also accept `--layout`.
115110

116111
### print amount style
117112

hledger/Hledger/Cli/Commands/Rewrite.hs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ rewritemode = hledgerCommandMode
3333
"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."
3434
,flagNone ["diff"] (setboolopt "diff") "generate diff suitable as an input for patch tool"
3535
,flagNone ["verbose-tags"] (setboolopt "verbose-tags") "add tags indicating generated/modified data"
36+
,layoutFlag
3637
]
3738
cligeneralflagsgroups1
3839
hiddenflags
@@ -67,13 +68,13 @@ transactionModifierFromOpts CliOpts{rawopts_=rawopts} =
6768

6869
printOrDiff :: RawOpts -> (CliOpts -> Journal -> Journal -> IO ())
6970
printOrDiff opts
70-
| boolopt "diff" opts = const diffOutput
71+
| boolopt "diff" opts = const (diffOutput (layoutFromRawOpts opts))
7172
| otherwise = flip (const print')
7273

73-
diffOutput :: Journal -> Journal -> IO ()
74-
diffOutput j j' = do
74+
diffOutput :: PostingLayout -> Journal -> Journal -> IO ()
75+
diffOutput postinglayout j j' = do
7576
let changed = [(transactionWithMostlyOriginalPostings t, transactionWithMostlyOriginalPostings t') | (t, t') <- zip (jtxns j) (jtxns j'), t /= t']
76-
T.putStr $ renderPatch $ map (uncurry $ diffTxn j) changed
77+
T.putStr $ renderPatch $ map (uncurry $ diffTxn postinglayout j) changed
7778

7879
type Chunk = (SourcePos, [DiffLine Text])
7980

@@ -125,8 +126,8 @@ renderPatch = go Nothing . sortOn fst where
125126
Add s -> "+" <> s <> "\n"
126127
Ctx s -> " " <> s <> "\n"
127128

128-
diffTxn :: Journal -> Transaction -> Transaction -> Chunk
129-
diffTxn j t t' = case tsourcepos t of
129+
diffTxn :: PostingLayout -> Journal -> Transaction -> Transaction -> Chunk
130+
diffTxn postinglayout j t t' = case tsourcepos t of
130131
(pos1@(SourcePos fp line col), pos2) | pos1 == pos2 -> (SourcePos fp (line <> mkPos 1) col, diffs) where
131132
-- TODO: use range and produce two chunks: one removes part of
132133
-- original file, other adds transaction to new file with
@@ -140,7 +141,7 @@ diffTxn j t t' = case tsourcepos t of
140141
diffs = map mapDiff $ D.getDiff source changed'
141142
source | Just contents <- lookup fp $ jfiles j = drop (unPos line-1) . take (unPos line' - 1) $ T.lines contents
142143
| otherwise = []
143-
changed = T.lines $ showTransaction t'
144+
changed = T.lines $ showTransactionWithLayout postinglayout t'
144145
changed' | null changed = changed
145146
| T.null $ last changed = init changed
146147
| otherwise = changed

hledger/Hledger/Cli/Commands/Rewrite.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,11 @@ Flags:
1515
patch tool
1616
--verbose-tags add tags indicating generated/modified
1717
data
18+
--layout=hledger1|COL how should posting amounts be aligned ?
19+
hledger1 - right-align amounts, as in
20+
hledger 1
21+
COL - align decimal marks at column
22+
COL (default: 53)
1823
```
1924

2025
This is a start at a generic rewriter of transaction entries.

hledger/test/add.test

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,23 @@ $ cp add-2478.j add-2478.$$.j; hledger -f add-2478.$$.j add >/dev/null 2>&1; rm
283283
$ printf '2025-01-01\n (a) 1\n' >t$$.j; hledger -f t$$.j add 2>&1; rm -f t$$.j
284284
> /^ +\(a\) +4 = 5/
285285

286+
# ** 21. add supports --layout, controlling the layout of appended transactions.
287+
<
288+
2026-01-01
289+
290+
a
291+
100
292+
b
293+
294+
.
295+
296+
$ printf '' >t$$.j; hledger -f t$$.j add 2026-01-01 --layout=hledger1 >/dev/null 2>&1; cat t$$.j; rm -f t$$.j
297+
298+
2026-01-01
299+
a 100
300+
b -100
301+
>=
302+
286303
# ** . shouldn't add decimals if there aren't any
287304
# printf '\n\na\n1\nb\n' | hledger -f /dev/null add
288305
# <

0 commit comments

Comments
 (0)