rustledger-plugin 0.13.0

Beancount plugin system with 20 native plugins and WASM support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
//! Beancount compatibility layer for Python plugins.
//!
//! This module provides the Python code that creates a beancount-compatible
//! environment for running Python plugins. It defines the `beancount.core.data`
//! namedtuples and provides serialization/deserialization functions.

/// Python compatibility layer code.
///
/// This code is executed in the Python runtime before loading user plugins.
/// It provides:
/// - `beancount.core.data` namedtuples (Transaction, Posting, Amount, etc.)
/// - JSON serialization/deserialization for directives
/// - Plugin execution wrapper
pub const BEANCOUNT_COMPAT_PY: &str = r#"
"""
Beancount compatibility layer for rustledger Python plugins.

This module provides the beancount.core.data API expected by Python plugins,
using rustledger's JSON-serialized directive format.
"""

import json
import sys
from collections import namedtuple
from datetime import date
from decimal import Decimal, InvalidOperation


# =============================================================================
# Core beancount.core.data types
# =============================================================================

Transaction = namedtuple('Transaction', [
    'meta', 'date', 'flag', 'payee', 'narration', 'tags', 'links', 'postings'
])

Posting = namedtuple('Posting', [
    'account', 'units', 'cost', 'price', 'flag', 'meta'
])

Amount = namedtuple('Amount', ['number', 'currency'])

Balance = namedtuple('Balance', [
    'meta', 'date', 'account', 'amount', 'tolerance', 'diff_amount'
])

Open = namedtuple('Open', [
    'meta', 'date', 'account', 'currencies', 'booking'
])

Close = namedtuple('Close', ['meta', 'date', 'account'])

Commodity = namedtuple('Commodity', ['meta', 'date', 'currency'])

Pad = namedtuple('Pad', ['meta', 'date', 'account', 'source_account'])

Event = namedtuple('Event', ['meta', 'date', 'type', 'description'])

Note = namedtuple('Note', ['meta', 'date', 'account', 'comment'])

Document = namedtuple('Document', [
    'meta', 'date', 'account', 'filename', 'tags', 'links'
])

Price = namedtuple('Price', ['meta', 'date', 'currency', 'amount'])

Query = namedtuple('Query', ['meta', 'date', 'name', 'query_string'])

Custom = namedtuple('Custom', ['meta', 'date', 'type', 'values'])


# =============================================================================
# Cost types
# =============================================================================

Cost = namedtuple('Cost', ['number', 'currency', 'date', 'label'])

CostSpec = namedtuple('CostSpec', [
    'number_per', 'number_total', 'currency', 'date', 'label', 'merge'
])


# =============================================================================
# Helper types
# =============================================================================

TxnPosting = namedtuple('TxnPosting', ['txn', 'posting'])


# =============================================================================
# Validation error
# =============================================================================

class ValidationError:
    """A validation error from a plugin."""

    def __init__(self, source, message, entry):
        self.source = source
        self.message = message
        self.entry = entry

    def __repr__(self):
        return f"ValidationError({self.message!r})"


# =============================================================================
# Deserialization helpers
# =============================================================================

def _parse_date(s):
    """Parse a date string (YYYY-MM-DD) to a date object."""
    if s is None:
        return None
    if isinstance(s, date):
        return s
    parts = s.split('-')
    return date(int(parts[0]), int(parts[1]), int(parts[2]))


def _parse_decimal(s):
    """Parse a decimal string to Decimal."""
    if s is None:
        return None
    if isinstance(s, (int, float)):
        return Decimal(str(s))
    if isinstance(s, Decimal):
        return s
    try:
        return Decimal(s)
    except InvalidOperation:
        return Decimal(0)


def _parse_amount(d):
    """Parse an amount dict to Amount namedtuple."""
    if d is None:
        return None
    return Amount(
        number=_parse_decimal(d.get('number')),
        currency=d.get('currency', '')
    )


def _parse_cost(d):
    """Parse a cost dict to Cost namedtuple."""
    if d is None:
        return None
    return Cost(
        number=_parse_decimal(d.get('number')),
        currency=d.get('currency', ''),
        date=_parse_date(d.get('date')),
        label=d.get('label')
    )


def _parse_cost_spec(d):
    """Parse a cost spec dict to CostSpec namedtuple."""
    if d is None:
        return None
    return CostSpec(
        number_per=_parse_decimal(d.get('number_per')),
        number_total=_parse_decimal(d.get('number_total')),
        currency=d.get('currency', ''),
        date=_parse_date(d.get('date')),
        label=d.get('label'),
        merge=d.get('merge', False)
    )


def _parse_posting(d):
    """Parse a posting dict to Posting namedtuple."""
    if d is None:
        return None
    return Posting(
        account=d.get('account', ''),
        units=_parse_amount(d.get('units')),
        cost=_parse_cost_spec(d.get('cost')),
        price=_parse_amount(d.get('price')),
        flag=d.get('flag'),
        meta=d.get('meta', {})
    )


def _parse_meta(d):
    """Parse metadata dict."""
    if d is None:
        return {}
    return dict(d)


def _dict_to_directive(d):
    """Convert a dict to the appropriate directive namedtuple."""
    dtype = d.get('type', '')
    meta = _parse_meta(d.get('meta'))
    date_val = _parse_date(d.get('date'))

    if dtype == 'transaction':
        postings = [_parse_posting(p) for p in d.get('postings', [])]
        return Transaction(
            meta=meta,
            date=date_val,
            flag=d.get('flag', '*'),
            payee=d.get('payee'),
            narration=d.get('narration', ''),
            tags=frozenset(d.get('tags', [])),
            links=frozenset(d.get('links', [])),
            postings=postings
        )
    elif dtype == 'balance':
        return Balance(
            meta=meta,
            date=date_val,
            account=d.get('account', ''),
            amount=_parse_amount(d.get('amount')),
            tolerance=_parse_decimal(d.get('tolerance')),
            diff_amount=_parse_amount(d.get('diff_amount'))
        )
    elif dtype == 'open':
        return Open(
            meta=meta,
            date=date_val,
            account=d.get('account', ''),
            currencies=frozenset(d.get('currencies', [])),
            booking=d.get('booking')
        )
    elif dtype == 'close':
        return Close(
            meta=meta,
            date=date_val,
            account=d.get('account', '')
        )
    elif dtype == 'commodity':
        return Commodity(
            meta=meta,
            date=date_val,
            currency=d.get('currency', '')
        )
    elif dtype == 'pad':
        return Pad(
            meta=meta,
            date=date_val,
            account=d.get('account', ''),
            source_account=d.get('source_account', '')
        )
    elif dtype == 'event':
        return Event(
            meta=meta,
            date=date_val,
            type=d.get('event_type', ''),
            description=d.get('description', '')
        )
    elif dtype == 'note':
        return Note(
            meta=meta,
            date=date_val,
            account=d.get('account', ''),
            comment=d.get('comment', '')
        )
    elif dtype == 'document':
        return Document(
            meta=meta,
            date=date_val,
            account=d.get('account', ''),
            filename=d.get('filename', ''),
            tags=frozenset(d.get('tags', [])),
            links=frozenset(d.get('links', []))
        )
    elif dtype == 'price':
        return Price(
            meta=meta,
            date=date_val,
            currency=d.get('currency', ''),
            amount=_parse_amount(d.get('amount'))
        )
    elif dtype == 'query':
        return Query(
            meta=meta,
            date=date_val,
            name=d.get('name', ''),
            query_string=d.get('query_string', '')
        )
    elif dtype == 'custom':
        return Custom(
            meta=meta,
            date=date_val,
            type=d.get('custom_type', ''),
            values=d.get('values', [])
        )
    else:
        # Return as-is for unknown types
        return d


# =============================================================================
# Serialization helpers
# =============================================================================

def _serialize_date(d):
    """Serialize a date to ISO string."""
    if d is None:
        return None
    if isinstance(d, str):
        return d
    return d.isoformat()


def _serialize_decimal(d):
    """Serialize a Decimal to string."""
    if d is None:
        return None
    return str(d)


def _serialize_amount(a):
    """Serialize an Amount to dict."""
    if a is None:
        return None
    return {
        'number': _serialize_decimal(a.number),
        'currency': a.currency
    }


def _serialize_cost(c):
    """Serialize a Cost to dict."""
    if c is None:
        return None
    return {
        'number': _serialize_decimal(c.number),
        'currency': c.currency,
        'date': _serialize_date(c.date),
        'label': c.label
    }


def _serialize_cost_spec(c):
    """Serialize a CostSpec to dict (matches Rust CostData format)."""
    if c is None:
        return None
    # Handle both Cost and CostSpec namedtuples
    if hasattr(c, 'number_per'):
        # CostSpec
        return {
            'number_per': _serialize_decimal(c.number_per),
            'number_total': _serialize_decimal(c.number_total) if hasattr(c, 'number_total') else None,
            'currency': c.currency if c.currency else None,
            'date': _serialize_date(c.date),
            'label': c.label,
            'merge': c.merge if hasattr(c, 'merge') else False
        }
    else:
        # Cost (convert to CostSpec format)
        return {
            'number_per': _serialize_decimal(c.number),
            'number_total': None,
            'currency': c.currency if c.currency else None,
            'date': _serialize_date(c.date),
            'label': c.label,
            'merge': False
        }


def _serialize_posting(p):
    """Serialize a Posting to dict."""
    if p is None:
        return None
    return {
        'account': p.account,
        'units': _serialize_amount(p.units),
        'cost': _serialize_cost_spec(p.cost),
        'price': _serialize_amount(p.price),
        'flag': p.flag,
        'metadata': list(p.meta.items()) if p.meta else []
    }


def _directive_to_dict(entry):
    """Convert a directive namedtuple to a dict."""
    if isinstance(entry, Transaction):
        return {
            'type': 'transaction',
            'metadata': list(entry.meta.items()) if entry.meta else [],
            'date': _serialize_date(entry.date),
            'flag': entry.flag,
            'payee': entry.payee,
            'narration': entry.narration,
            'tags': list(entry.tags) if entry.tags else [],
            'links': list(entry.links) if entry.links else [],
            'postings': [_serialize_posting(p) for p in entry.postings]
        }
    elif isinstance(entry, Balance):
        return {
            'type': 'balance',
            'metadata': list(entry.meta.items()) if entry.meta else [],
            'date': _serialize_date(entry.date),
            'account': entry.account,
            'amount': _serialize_amount(entry.amount),
            'tolerance': _serialize_decimal(entry.tolerance),
            'diff_amount': _serialize_amount(entry.diff_amount)
        }
    elif isinstance(entry, Open):
        return {
            'type': 'open',
            'metadata': list(entry.meta.items()) if entry.meta else [],
            'date': _serialize_date(entry.date),
            'account': entry.account,
            'currencies': list(entry.currencies) if entry.currencies else [],
            'booking': entry.booking
        }
    elif isinstance(entry, Close):
        return {
            'type': 'close',
            'metadata': list(entry.meta.items()) if entry.meta else [],
            'date': _serialize_date(entry.date),
            'account': entry.account
        }
    elif isinstance(entry, Commodity):
        return {
            'type': 'commodity',
            'metadata': list(entry.meta.items()) if entry.meta else [],
            'date': _serialize_date(entry.date),
            'currency': entry.currency
        }
    elif isinstance(entry, Pad):
        return {
            'type': 'pad',
            'metadata': list(entry.meta.items()) if entry.meta else [],
            'date': _serialize_date(entry.date),
            'account': entry.account,
            'source_account': entry.source_account
        }
    elif isinstance(entry, Event):
        return {
            'type': 'event',
            'metadata': list(entry.meta.items()) if entry.meta else [],
            'date': _serialize_date(entry.date),
            'event_type': entry.type,
            'description': entry.description
        }
    elif isinstance(entry, Note):
        return {
            'type': 'note',
            'metadata': list(entry.meta.items()) if entry.meta else [],
            'date': _serialize_date(entry.date),
            'account': entry.account,
            'comment': entry.comment
        }
    elif isinstance(entry, Document):
        return {
            'type': 'document',
            'metadata': list(entry.meta.items()) if entry.meta else [],
            'date': _serialize_date(entry.date),
            'account': entry.account,
            'filename': entry.filename,
            'tags': list(entry.tags) if entry.tags else [],
            'links': list(entry.links) if entry.links else []
        }
    elif isinstance(entry, Price):
        return {
            'type': 'price',
            'metadata': list(entry.meta.items()) if entry.meta else [],
            'date': _serialize_date(entry.date),
            'currency': entry.currency,
            'amount': _serialize_amount(entry.amount)
        }
    elif isinstance(entry, Query):
        return {
            'type': 'query',
            'metadata': list(entry.meta.items()) if entry.meta else [],
            'date': _serialize_date(entry.date),
            'name': entry.name,
            'query_string': entry.query_string
        }
    elif isinstance(entry, Custom):
        return {
            'type': 'custom',
            'metadata': list(entry.meta.items()) if entry.meta else [],
            'date': _serialize_date(entry.date),
            'custom_type': entry.type,
            'values': entry.values
        }
    else:
        # Return as-is for unknown types
        return entry


# =============================================================================
# Public API
# =============================================================================

def deserialize_entries(json_str):
    """Convert JSON string to list of Python directive objects."""
    data = json.loads(json_str)
    return [_dict_to_directive(d) for d in data]


def serialize_entries(entries):
    """Convert list of Python directive objects to JSON string."""
    return json.dumps([_directive_to_dict(e) for e in entries], default=str)


def serialize_errors(errors):
    """Convert list of errors to JSON string."""
    error_list = []
    for e in errors:
        if isinstance(e, ValidationError):
            error_list.append({
                'message': str(e.message),
                'source_file': e.source.get('filename') if e.source else None,
                'line_number': e.source.get('lineno') if e.source else None,
            })
        else:
            error_list.append({
                'message': str(e),
                'source_file': None,
                'line_number': None,
            })
    return json.dumps(error_list)


def run_plugin(plugin_func, entries_json, options_json, config=None):
    """
    Execute a beancount plugin function.

    Args:
        plugin_func: The plugin function to call
        entries_json: JSON-serialized directives
        options_json: JSON-serialized options dict
        config: Optional plugin config string

    Returns:
        Tuple of (serialized_entries, serialized_errors)
    """
    entries = deserialize_entries(entries_json)
    options = json.loads(options_json) if options_json else {}

    try:
        if config is not None:
            new_entries, errors = plugin_func(entries, options, config)
        else:
            new_entries, errors = plugin_func(entries, options)
    except Exception as e:
        # Return original entries with the exception as an error
        error = ValidationError(None, f"Plugin error: {e}", None)
        return serialize_entries(entries), serialize_errors([error])

    return serialize_entries(new_entries), serialize_errors(errors or [])


# =============================================================================
# Create fake beancount module hierarchy
# =============================================================================

class FakeModule:
    """A fake module for namespace purposes."""
    pass


# Create beancount.core.data module
_beancount = FakeModule()
_beancount.core = FakeModule()
_beancount.core.data = FakeModule()

# Populate beancount.core.data with our types
_beancount.core.data.Transaction = Transaction
_beancount.core.data.Posting = Posting
_beancount.core.data.Amount = Amount
_beancount.core.data.Balance = Balance
_beancount.core.data.Open = Open
_beancount.core.data.Close = Close
_beancount.core.data.Commodity = Commodity
_beancount.core.data.Pad = Pad
_beancount.core.data.Event = Event
_beancount.core.data.Note = Note
_beancount.core.data.Document = Document
_beancount.core.data.Price = Price
_beancount.core.data.Query = Query
_beancount.core.data.Custom = Custom
_beancount.core.data.Cost = Cost
_beancount.core.data.CostSpec = CostSpec
_beancount.core.data.TxnPosting = TxnPosting

def new_metadata(filename, lineno, kvlist=None):
    """Create a new metadata dictionary."""
    meta = {'filename': filename, 'lineno': lineno}
    if kvlist:
        meta.update(kvlist)
    return meta

_beancount.core.data.new_metadata = new_metadata

# Create beancount.core.amount module
_beancount.core.amount = FakeModule()
_beancount.core.amount.Amount = Amount

# Create beancount.core.getters module
_beancount.core.getters = FakeModule()

def get_account_open_close(entries):
    """Get a mapping of account name to Open/Close directives.

    This is a simplified version of beancount.core.getters.get_account_open_close
    that returns a dict mapping account names to (open, close) tuples.
    """
    open_close_map = {}
    for entry in entries:
        if isinstance(entry, Open):
            account = entry.account
            if account not in open_close_map:
                open_close_map[account] = (entry, None)
            else:
                # Update the open entry
                open_close_map[account] = (entry, open_close_map[account][1])
        elif isinstance(entry, Close):
            account = entry.account
            if account not in open_close_map:
                open_close_map[account] = (None, entry)
            else:
                # Update the close entry
                open_close_map[account] = (open_close_map[account][0], entry)
    return open_close_map

_beancount.core.getters.get_account_open_close = get_account_open_close

# Create beancount.core.flags module
_beancount.core.flags = FakeModule()
_beancount.core.flags.FLAG_OKAY = '*'
_beancount.core.flags.FLAG_WARNING = '!'
_beancount.core.flags.FLAG_PADDING = 'P'
_beancount.core.flags.FLAG_SUMMARIZE = 'S'
_beancount.core.flags.FLAG_TRANSFER = 'T'
_beancount.core.flags.FLAG_CONVERSIONS = 'C'
_beancount.core.flags.FLAG_UNREALIZED = 'U'
_beancount.core.flags.FLAG_RETURNS = 'R'
_beancount.core.flags.FLAG_MERGING = 'M'

# Install in sys.modules so imports work
sys.modules['beancount'] = _beancount
sys.modules['beancount.core'] = _beancount.core
sys.modules['beancount.core.data'] = _beancount.core.data
sys.modules['beancount.core.amount'] = _beancount.core.amount
sys.modules['beancount.core.getters'] = _beancount.core.getters
sys.modules['beancount.core.flags'] = _beancount.core.flags

# Export for direct use
__all__ = [
    'Transaction', 'Posting', 'Amount', 'Balance', 'Open', 'Close',
    'Commodity', 'Pad', 'Event', 'Note', 'Document', 'Price', 'Query',
    'Custom', 'Cost', 'CostSpec', 'TxnPosting', 'ValidationError',
    'deserialize_entries', 'serialize_entries', 'serialize_errors',
    'run_plugin',
]
"#;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_compat_code_is_valid_python_syntax() {
        // Basic check that the Python code is non-empty and contains expected content
        assert!(BEANCOUNT_COMPAT_PY.contains("Transaction = namedtuple"));
        assert!(BEANCOUNT_COMPAT_PY.contains("def run_plugin"));
        assert!(BEANCOUNT_COMPAT_PY.contains("beancount.core.data"));
    }
}