Building a ledger-cli clone in Rust is a great project! Ledger is a powerful double-entry accounting system, so you'll need to handle parsing transaction files, maintaining account balances, and generating reports.
use nom::{
bytes::complete::{tag, take_until},
character::complete::{digit1, space0, space1},
combinator::{map_res, opt},
sequence::{preceded, tuple},
IResult,
};
impl Ledger {
pub fn parse_transaction(input: &str) -> IResult<&str, Transaction> {
// Parse date (YYYY-MM-DD format)
let (input, date_str) = take_until(" ")(input)?;
let date = Date::parse_from_str(date_str, "%Y-%m-%d")
.map_err(|_| nom::Err::Error(nom::error::Error::new(input, nom::error::ErrorKind::Tag)))?;
// Parse description
let (input, _) = space1(input)?;
let (input, description) = take_until("\n")(input)?;
// Parse postings (simplified)
let mut postings = Vec::new();
// Implementation for parsing postings would go here
Ok((input, Transaction {
date,
description: description.to_string(),
postings,
}))
}
}
Main Application Structure
rust
use clap::{App, Arg, SubCommand};
use std::fs;
fn main() {
let matches = App::new("rust-ledger")
.version("0.1.0")
.about("A ledger-cli clone in Rust")
.arg(Arg::with_name("file")
.short("f")
.long("file")
.value_name("FILE")
.help("Ledger file to read")
.takes_value(true)
.required(true))
.subcommand(SubCommand::with_name("balance")
.about("Show account balances"))
.subcommand(SubCommand::with_name("register")
.about("Show transaction register"))
.get_matches();
let filename = matches.value_of("file").unwrap();
let content = fs::read_to_string(filename)
.expect("Failed to read ledger file");
let mut ledger = Ledger::new();
ledger.parse_file(&content).expect("Failed to parse ledger file");
match matches.subcommand() {
("balance", _) => ledger.print_balance(),
("register", _) => ledger.print_register(),
_ => println!("No subcommand specified"),
}
}
Key Dependencies
Add these to your Cargo.toml:
toml
[dependencies]
chrono = { version = "0.4", features = ["serde"] }
rust_decimal = "1.0"
nom = "7.0"
clap = "2.34"
Implementation Tips
For a full implementation, you'll want to focus on:
Robust parsing - Handle various date formats, currencies, and posting syntax
Balance validation - Ensure transactions balance (sum to zero)
Account hierarchy - Support nested accounts like "Assets:Checking"
Reporting - Balance sheets, income statements, registers
Filtering - Date ranges, account patterns, payee matching
Multiple commodities - Handle different currencies and stocks
The parsing is probably the most complex part. Consider using a more sophisticated parser generator or hand-writing a recursive descent parser for better error handling and flexibility.
Would you like me to elaborate on any particular aspect, like the transaction parsing logic or the reporting functionality?