ledger_parser/
lib.rs

1//! Rust library for parsing [Ledger-cli](https://www.ledger-cli.org/) input files.
2//!
3//! Only a subset of the ledger-cli's file format is implemented.
4//!
5//! Supported elements:
6//!
7//! - Line comments (starting with: ``; # % | *``)
8//!
9//! - Inline comments (starting with ``;``)
10//!
11//! - Transaction headers with format (minimum two spaces or one tab between `DESC` and `NOTE`):
12//!
13//!   ```ledger-cli,ignore
14//!   DATE[=EDATE] [*|!] [(CODE)] DESC  [; NOTE]
15//!   ```
16//!
17//! - Transaction postings with format (minimum two spaces or one tab between `ACCOUNT` and `AMOUNT`):
18//!
19//!   ```ledger-cli,ignore
20//!     ACCOUNT  [AMOUNT] [= BALANCE] [; NOTE]
21//!   ```
22//!
23//!     - Virtual accounts are supported
24//!
25//! - `AMOUNT` can be combined with lot and commodity prices ({}, {{}}, @, @@)
26//!
27//! - Commodity prices with format:
28//!
29//!   ```ledger-cli,ignore
30//!   P DATE SYMBOL PRICE
31//!   ```
32//! - Command directives: `include`
33
34mod model;
35pub use model::*;
36
37mod serializer;
38pub use serializer::*;
39
40mod parser;
41
42use std::fmt;
43
44#[derive(Clone, Debug, PartialEq, Eq)]
45pub enum ParseError {
46    String(String),
47}
48
49impl fmt::Display for ParseError {
50    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
51        match *self {
52            ParseError::String(ref err) => err.fmt(f),
53        }
54    }
55}
56
57impl std::error::Error for ParseError {
58    fn description(&self) -> &str {
59        match *self {
60            ParseError::String(ref err) => err,
61        }
62    }
63}
64
65/// Parses ledger-cli source to AST tree.
66///
67/// # Examples
68///
69/// ```
70/// let result = ledger_parser::parse(r#"; Example 1
71/// 2018-10-01=2018-10-14 ! (123) Description
72///   ; Transaction comment
73///   TEST:Account 123  $1.20
74///   ; Posting comment
75///   TEST:Account 345  -$1.20"#);
76/// ```
77pub fn parse(input: &str) -> Result<Ledger, ParseError> {
78    input.parse()
79}