Of course! Building a ledger-cli-like program is an excellent project for learning Rust. It touches on file I/O, parsing, data structures, error handling, decimal arithmetic (which is very important for finance!), and building a command-line interface.
Let's build a simplified version called rusty-ledger step-by-step. We'll implement two core commands:
bal: To show the final balance of all accounts.
reg: To show a register of all transactions.
Step 1: Project Setup and Dependencies
First, create a new Rust project and add the necessary dependencies.
cargo new rusty-ledger
cd rusty-ledger
Now, open your Cargo.toml and add the following crates:
clap: The gold standard for parsing command-line arguments in Rust.
chrono: For handling dates.
rust_decimal: Crucial! Never use floating-point numbers (f32, f64) for financial calculations due to precision errors. rust_decimal provides a decimal number implementation.
rust_decimal_macros: Provides a convenient macro for creating Decimals.
thiserror: A great crate for writing clean, boilerplate-free error types.
Your [dependencies] section in Cargo.toml should look like this:
[dependencies]
chrono = "0.4"
clap = { version = "4.4", features = ["derive"] }
rust_decimal = "1.33"
rust_decimal_macros = "1.33"
thiserror = "1.0"
Step 2: Defining the Core Data Structures
The foundation of any ledger is its data model. A ledger file consists of Transactions, and each transaction has multiple Postings.
Let's model this in src/main.rs.
// src/main.rs
use chrono::NaiveDate;
use rust_decimal::Decimal;
use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TransactionState {
Cleared, // *
Pending, // !
Unmarked, // No mark
}
#[derive(Debug, Clone)]
pub struct Posting {
pub account: String,
pub amount: Option<Decimal>, // Amount can be empty for balancing
pub currency: Option<String>,
}
#[derive(Debug, Clone)]
pub struct Transaction {
pub date: NaiveDate,
pub state: TransactionState,
pub payee: String,
pub postings: Vec<Posting>,
}
// Our main data structure for the whole ledger
#[derive(Debug, Clone)]
pub struct Ledger {
pub transactions: Vec<Transaction>,
}
Step 3: Creating a Parser
This is the most complex part. We need to read a text file and transform it into our Vec<Transaction>. We'll keep the parsing simple for this example. We'll support a format like this:
; A sample ledger file
2023-10-27 * Groceries Store
Expenses:Food:Groceries $150.25
Assets:Bank:Checking
2023-10-28 ! Invoice #123 - Client Work
Assets:Bank:Checking $2000.00
Income:Consulting
Notice a key feature of ledger-cli: if one posting amount is missing, it's automatically calculated to make the transaction balance to zero.
Let's create a custom error type and the parser logic.
// In src/main.rs, add our error type
use thiserror::Error;
#[derive(Error, Debug)]
pub enum ParseError {
#[error("Invalid date format on line: {0}")]
InvalidDate(String),
#[error("Transaction on line {0} does not balance to zero")]
UnbalancedTransaction(usize),
#[error("Could not parse amount on line: {0}")]
InvalidAmount(String),
#[error("A transaction must have at least two postings")]
NotEnoughPostings,
#[error("I/O Error")]
Io(#[from] std::io::Error),
}
// Now, let's implement the parser for our Ledger struct
impl Ledger {
pub fn from_str(content: &str) -> Result<Self, ParseError> {
let mut transactions = Vec::new();
let mut current_transaction: Option<Transaction> = None;
for (line_num, line) in content.lines().enumerate() {
let line = line.trim_end();
if line.starts_with(';') || line.is_empty() {
continue; // Skip comments and empty lines
}
// If the line starts with a date, it's a new transaction
if line.starts_with(char::is_numeric) {
// First, push the previous transaction if it exists
if let Some(mut tx) = current_transaction.take() {
Self::balance_transaction(&mut tx, line_num)?;
transactions.push(tx);
}
// Parse the new transaction header
let parts: Vec<&str> = line.split_whitespace().collect();
let date = NaiveDate::parse_from_str(parts[0], "%Y-%m-%d")
.or_else(|_| NaiveDate::parse_from_str(parts[0], "%Y/%m/%d"))
.map_err(|_| ParseError::InvalidDate(line.to_string()))?;
let (state, payee_start_index) = match parts.get(1) {
Some(&"*") => (TransactionState::Cleared, 2),
Some(&"!") => (TransactionState::Pending, 2),
_ => (TransactionState::Unmarked, 1),
};
let payee = parts[payee_start_index..].join(" ");
current_transaction = Some(Transaction {
date,
state,
payee,
postings: Vec::new(),
});
} else if line.starts_with(char::is_whitespace) {
// This is a posting line
if let Some(tx) = &mut current_transaction {
let line = line.trim();
let parts: Vec<&str> = line.split_whitespace().collect();
let account = parts[0].to_string();
// Find where the amount starts. It's usually after the account.
// This handles accounts with spaces like "Expenses:My Stuff"
let mut amount: Option<Decimal> = None;
let mut currency: Option<String> = None;
// A simple way to find amount: find what looks like a number
if let Some(first_numeric_part) = parts.iter().skip(1).find(|p| p.parse::<f64>().is_ok()) {
amount = Some(first_numeric_part.parse::<Decimal>().map_err(|_| ParseError::InvalidAmount(line.to_string()))?);
currency = Some("$".to_string()); // Hardcoding for now
}
tx.postings.push(Posting { account, amount, currency });
}
}
}
// Add the last transaction
if let Some(mut tx) = current_transaction.take() {
Self::balance_transaction(&mut tx, content.lines().count())?;
transactions.push(tx);
}
Ok(Ledger { transactions })
}
// This function calculates the missing amount in a transaction
fn balance_transaction(tx: &mut Transaction, line_num: usize) -> Result<(), ParseError> {
if tx.postings.len() < 2 {
return Err(ParseError::NotEnoughPostings);
}
let mut sum = Decimal::ZERO;
let mut missing_posting_index: Option<usize> = None;
for (i, p) in tx.postings.iter().enumerate() {
if let Some(amount) = p.amount {
sum += amount;
} else {
if missing_posting_index.is_some() {
// More than one posting is missing an amount
return Err(ParseError::UnbalancedTransaction(line_num));
}
missing_posting_index = Some(i);
}
}
if let Some(index) = missing_posting_index {
// Fill in the missing amount
tx.postings[index].amount = Some(-sum);
} else if !sum.is_zero() {
// All postings have amounts, but they don't sum to zero
return Err(ParseError::UnbalancedTransaction(line_num));
}
Ok(())
}
}
Note: This parser is basic. A production-ready one would use regular expressions or a more robust parsing library for amounts and currencies.
Step 4: The Command-Line Interface (CLI)
Let's use clap to define our commands bal and reg.
// In src/main.rs, add clap imports and definitions
use clap::{Parser, Subcommand};
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Cli {
/// The ledger file to process
#[arg(short, long, value_name = "FILE", default_value = "main.ledger")]
file: String,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Prints the balance of all accounts
Bal,
/// Prints all transactions in a register format
Reg,
}
// ... the rest of the structs and impls go here ...
Step 5: Implementing the Commands and the main Function
Now, let's tie it all together. The main function will parse the arguments, read the file, parse the ledger, and then execute the correct command.
// At the bottom of src/main.rs
fn main() {
let cli = Cli::parse();
let content = match std::fs::read_to_string(&cli.file) {
Ok(c) => c,
Err(e) => {
eprintln!("Error reading file '{}': {}", cli.file, e);
std::process::exit(1);
}
};
let ledger = match Ledger::from_str(&content) {
Ok(l) => l,
Err(e) => {
eprintln!("Error parsing ledger file: {}", e);
std::process::exit(1);
}
};
match &cli.command {
Commands::Bal => run_balance_report(&ledger),
Commands::Reg => run_register_report(&ledger),
}
}
fn run_balance_report(ledger: &Ledger) {
let mut balances: HashMap<String, Decimal> = HashMap::new();
for tx in &ledger.transactions {
for p in &tx.postings {
// We can unwrap here because the parser guarantees amounts exist.
let amount = p.amount.unwrap();
*balances.entry(p.account.clone()).or_insert(Decimal::ZERO) += amount;
}
}
let mut total = Decimal::ZERO;
let mut accounts: Vec<_> = balances.keys().collect();
accounts.sort();
// Simple formatting
for account in accounts {
let balance = balances.get(account).unwrap();
total += balance;
println!("{:>20} {}", format!("{:.2}", balance), account);
}
println!("--------------------");
println!("{:>20}", format!("{:.2}", total));
}
fn run_register_report(ledger: &Ledger) {
for tx in &ledger.transactions {
let state_char = match tx.state {
TransactionState::Cleared => '*',
TransactionState::Pending => '!',
TransactionState::Unmarked => ' ',
};
println!("{} {} {}", tx.date, state_char, tx.payee);
for p in &tx.postings {
let amount = p.amount.unwrap();
println!(" {:<30} {:>15.2}", p.account, amount);
}
println!(); // Blank line between transactions
}
}
Step 6: Running the Program
-
Create a ledger file named main.ledger in the root of your project directory with the sample content from Step 3.
main.ledger:
2023-10-27 * Groceries Store
Expenses:Food:Groceries $150.25
Assets:Bank:Checking
2023-10-28 ! Invoice #123 - Client Work
Assets:Bank:Checking $2000.00
Income:Consulting
-
Run the program with cargo run. By default, it runs the bal command.
cargo run -- bal
Output:
-150.25 Assets:Bank:Checking
1849.75 Expenses:Food:Groceries
-2000.00 Income:Consulting
--------------------
0.00
Wait, that's not right! Let's fix the balance report logic. The first posting should be +150.25 and the balancing Assets one should be -150.25. My sample data was backward. Let's fix main.ledger. Money comes out of the bank for expenses.
Corrected main.ledger:
2023-10-27 * Groceries Store
Expenses:Food:Groceries $150.25
Assets:Bank:Checking $-150.25
2023-10-28 ! Invoice #123 - Client Work
Assets:Bank:Checking $2000.00
Income:Consulting
Now, let's also remove the automatic balancing for the first transaction to test our balance_transaction function.
Final main.ledger for testing:
2023-10-27 * Groceries Store
Expenses:Food:Groceries $150.25
Assets:Bank:Checking
2023-10-28 ! Invoice #123 - Client Work
Assets:Bank:Checking $2000.00
Income:Consulting
Now, run cargo run -- bal again:
Correct Output:
1849.75 Assets:Bank:Checking
150.25 Expenses:Food:Groceries
-2000.00 Income:Consulting
--------------------
0.00
This looks correct! The bank has 150.25 = $1849.75. Expenses are positive, Income is negative (as a credit). This is standard double-entry accounting.
Future Improvements
This is a great starting point. Here's how you could expand it:
- More Robust Parsing: Use regular expressions (
regex crate) to handle various amount formats (e.g., -$1,000.00, 100 EUR).
- Sub-account Balances: The
bal command could aggregate balances. For example, the balance of Assets should be the sum of Assets:Bank:Checking and any other Assets:* accounts. This involves parsing the account names and building a tree-like structure.
- More Reports: Implement
print (to pretty-print the parsed file), csv, etc.
- Filtering: Add options to filter reports by date (
--begin, --end), by account, or by payee.
- Unit Tests: Write tests for your parser! It's the most critical and complex part. You can create test strings and assert that they parse into the correct
Ledger structs.
- Directives: Support other ledger directives like
account, commodity, apply tag, etc.
- Better Error Messages: Include line numbers in all your
ParseError variants to help users debug their ledger files.