Absolutely! While I can't generate a .zip file directly in this chat interface, I can provide you with the full directory structure and code to create a starting template for your ledger-like application in Rust.
You can copy this into a new project folder manually or via script. Here's how you'd do it:
📁 Folder Structure
rust-ledger/
├── Cargo.toml
├── src/
│ ├── main.rs
│ └── lib.rs
└── data/
└── example.ledger
🧾 1. Cargo.toml
[package]
name = "rust-ledger"
version = "0.1.0"
edition = "2021"
[dependencies]
chrono = { version = "0.4", features = ["serde"] }
rust_decimal = "1.23"
rust_decimal_macros = "1.23"
num-format = "0.5"
lazy_static = "0.6"
regex = "1.10"
nom = "7.1"
clap = { version = "4.0", features = ["derive"] }
rust_xlsxwriter = "0.19.0"
📄 2. src/main.rs
mod ledger;
use clap::{Parser, Subcommand};
use std::fs;
use ledger::{Ledger, Amount};
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Cli {
#[arg(short, long, value_name = "FILE", required = true)]
file: String,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
Balance,
Register,
Export {
#[arg(short, long, value_name = "DATE")]
start: Option<String>,
#[arg(short, long, value_name = "DATE")]
end: Option<String>,
#[arg(short, long, value_name = "FILE", required = true)]
output: String,
},
}
fn main() {
let cli = Cli::parse();
let content = fs::read_to_string(&cli.file)
.expect("Failed to read ledger file");
let mut ledger = Ledger::new();
ledger.parse_file(&content).expect("Failed to parse ledger file");
match cli.command {
Commands::Balance => ledger.print_balance(),
Commands::Register => ledger.print_register(),
Commands::Export { start, end, output } => {
let start_date = start.map(|s| parse_date(&s));
let end_date = end.map(|s| parse_date(&s));
ledger.export_to_excel(start_date, end_date, &output);
}
}
}
fn parse_date(s: &str) -> chrono::NaiveDate {
chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d")
.expect("Invalid date format, use YYYY-MM-DD")
}
📦 3. src/lib.rs
use chrono::{Date, Utc, NaiveDate};
use rust_decimal::Decimal;
use std::collections::{HashMap, HashSet};
use num_format::{Locale, ToFormattedString};
use regex::Regex;
use lazy_static::lazy_static;
use rust_decimal_macros::dec;
use rust_xlsxwriter::{Workbook, Format, Worksheet};
use nom::{
bytes::complete::{take_until, tag},
character::complete::{space0, space1, multispace0},
sequence::{tuple, preceded},
combinator::{map_res, opt},
multi::many1,
IResult,
};
// ===== Data Structures =====
#[derive(Debug, Clone)]
pub struct Amount {
pub value: Decimal,
pub commodity: String,
}
#[derive(Debug, Clone)]
pub struct Posting {
pub account: String,
pub amount: Option<Amount>,
}
#[derive(Debug, Clone)]
pub struct Transaction {
pub date: Date<Utc>,
pub description: String,
pub postings: Vec<Posting>,
}
#[derive(Debug)]
pub struct Ledger {
pub transactions: Vec<Transaction>,
}
// ===== Commodity Formatting Rules =====
#[derive(Debug, Clone)]
struct CommodityStyle {
precision: u32,
symbol: String,
is_prefix: bool,
locale: Locale,
}
lazy_static! {
static ref COMMODITY_STYLES: HashMap<String, CommodityStyle> = {
let mut m = HashMap::new();
m.insert("USD".to_string(), CommodityStyle {
precision: 2, symbol: "$".to_string(), is_prefix: true, locale: Locale::en,
});
m.insert("CAD".to_string(), CommodityStyle {
precision: 2, symbol: "C$".to_string(), is_prefix: true, locale: Locale::en,
});
m.insert("EUR".to_string(), CommodityStyle {
precision: 2, symbol: "€".to_string(), is_prefix: false, locale: Locale::en,
});
m.insert("JPY".to_string(), CommodityStyle {
precision: 0, symbol: "¥".to_string(), is_prefix: true, locale: Locale::en,
});
m.insert("BTC".to_string(), CommodityStyle {
precision: 8, symbol: "BTC".to_string(), is_prefix: false, locale: Locale::en,
});
m.insert("ETH".to_string(), CommodityStyle {
precision: 8, symbol: "ETH".to_string(), is_prefix: false, locale: Locale::en,
});
m.insert("DEFAULT".to_string(), CommodityStyle {
precision: 2, symbol: "".to_string(), is_prefix: false, locale: Locale::en,
});
m
};
}
// ===== Amount Display Implementation =====
impl std::fmt::Display for Amount {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let default_style = COMMODITY_STYLES.get("DEFAULT").unwrap();
let style = COMMODITY_STYLES.get(&self.commodity).unwrap_or(default_style);
let rounded_value = self.value.round_dp_with_strategy(
style.precision,
rust_decimal::RoundingStrategy::MidpointAwayFromZero,
);
let integer_part = rounded_value.trunc();
let fractional_part = (rounded_value - integer_part).abs();
let formatted_integer = integer_part.to_i128().unwrap_or(0).to_formatted_string(&style.locale);
let fractional_str = if style.precision > 0 {
let scale_factor = Decimal::from(10i64.pow(style.precision));
let fractional_digits = (fractional_part * scale_factor).to_u64().unwrap_or(0);
format!(".{:0width$}", fractional_digits, width = style.precision as usize)
} else {
String::new()
};
let formatted_number = format!("{}{}", formatted_integer, fractional_str);
let display_symbol = if style.symbol.is_empty() {
&self.commodity
} else {
&style.symbol
};
if style.is_prefix {
write!(f, "{}{}", display_symbol, formatted_number)
} else {
write!(f, "{} {}", formatted_number, display_symbol)
}
}
}
// ===== Parsing Logic =====
impl Amount {
pub fn from_string(input: &str) -> Result<Self, String> {
lazy_static! {
static ref AMOUNT_RE: Regex = Regex::new(
r"^\s*([\$€¥]?)\s*([-+]?[0-9,.]+)\s*([A-Z]{3,5})?\s*$"
).unwrap();
}
let caps = AMOUNT_RE.captures(input)
.ok_or_else(|| format!("Invalid amount format: {}", input))?;
let prefix = caps.get(1).map_or("", |m| m.as_str()).trim();
let number_str_raw = caps.get(2).map_or("", |m| m.as_str()).trim();
let suffix = caps.get(3).map_or("", |m| m.as_str()).trim();
if prefix.is_empty() && suffix.is_empty() {
return Err("Amount is missing a commodity/currency symbol".to_string());
}
let commodity = if !suffix.is_empty() {
suffix.to_string()
} else {
match prefix {
"$" => "USD".to_string(),
"€" => "EUR".to_string(),
"¥" => "JPY".to_string(),
_ => return Err(format!("Unknown currency symbol: {}", prefix)),
}
};
let clean_number_str = number_str_raw.replace(",", "");
let value = Decimal::from_str(&clean_number_str)
.map_err(|e| format!("Invalid number {}: {}", clean_number_str, e))?;
Ok(Amount { value, commodity })
}
}
// ===== Ledger Parsing =====
impl Ledger {
pub fn new() -> Self {
Ledger {
transactions: vec![],
}
}
pub fn parse_file(&mut self, content: &str) {
let lines: Vec<&str> = content.lines().collect();
let mut i = 0;
while i < lines.len() {
let line = lines[i].trim();
if line.is_empty() {
i += 1;
continue;
}
if let Ok((_, transaction)) = Self::parse_transaction(&lines[i..]) {
self.transactions.push(transaction);
i += 1; // Advance past parsed lines (this is simplistic!)
} else {
i += 1;
}
}
}
fn parse_transaction(input: &[&str]) -> IResult<&[&str], Transaction> {
let (input, (date_str, _, desc)) = tuple((
take_until(" "),
space1,
take_until("\n"),
))(input.get(0).unwrap_or(&""))?;
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)))?;
let mut postings = vec![];
let mut rest = &input[1..];
while rest.get(0).map_or(false, |line| !line.trim().is_empty()) {
if let Ok((remaining, posting)) = Self::parse_posting(rest[0]) {
postings.push(posting);
rest = remaining;
} else {
break;
}
}
Ok((
rest,
Transaction {
date,
description: desc.to_string(),
postings,
},
))
}
fn parse_posting(line: &str) -> IResult<&str, Posting> {
let (line, _) = multispace0(line)?;
let (line, account) = take_until(" ")(line)?;
let (line, _) = space1(line)?;
let (line, amount_str) = take_until("\n")(line)?;
let amount = if amount_str.trim().is_empty() {
None
} else {
Some(Amount::from_string(amount_str).map_err(|e| {
nom::Err::Failure(nom::error::Error::new(line, nom::error::ErrorKind::Verify))
})?)
};
Ok((
"",
Posting {
account: account.trim().to_string(),
amount,
},
))
}
pub fn print_balance(&self) {
let mut balances: HashMap<String, Decimal> = HashMap::new();
for tx in &self.transactions {
for posting in &tx.postings {
if let Some(ref amount) = posting.amount {
*balances.entry(posting.account.clone()).or_insert(dec!(0)) += amount.value;
}
}
}
println!("Account Balances:");
for (account, balance) in balances {
println!("{}: {}", account, balance);
}
}
pub fn print_register(&self) {
for tx in &self.transactions {
println!("{}", tx.date.format("%Y-%m-%d"));
println!("{}", tx.description);
for posting in &tx.postings {
if let Some(ref amount) = posting.amount {
println!(" {} {}", posting.account, amount);
} else {
println!(" {}", posting.account);
}
}
println!();
}
}
pub fn export_to_excel(
&self,
start_date: Option<NaiveDate>,
end_date: Option<NaiveDate>,
output_path: &str,
) {
let mut workbook = Workbook::new(output_path).expect("Failed to create Excel file");
let filtered_transactions = self
.transactions
.iter()
.filter(|t| {
let date = t.date.naive_utc();
match (start_date, end_date) {
(Some(s), Some(e)) => date >= s && date <= e,
(Some(s), None) => date >= s,
(None, Some(e)) => date <= e,
_ => true,
}
})
.collect::<Vec<_>>();
let accounts_with_transactions: HashSet<String> = filtered_transactions
.iter()
.flat_map(|t| t.postings.iter().map(|p| p.account.clone()))
.collect();
for account_name in accounts_with_transactions {
let mut worksheet = workbook.add_worksheet(Some(&account_name)).unwrap();
worksheet.set_column(0, 0, 12, None);
worksheet.set_column(1, 1, 30, None);
worksheet.set_column(2, 2, 20, None);
worksheet.set_column(3, 3, 10, None);
worksheet.set_column(4, 4, 15, None);
worksheet.write_string(0, 0, "Date", None).unwrap();
worksheet.write_string(0, 1, "Description", None).unwrap();
worksheet.write_string(0, 2, "Account", None).unwrap();
worksheet.write_string(0, 3, "Amount", None).unwrap();
worksheet.write_string(0, 4, "Commodity", None).unwrap();
let mut row = 1;
for transaction in &filtered_transactions {
for posting in &transaction.postings {
if let Some(ref amount) = posting.amount {
if posting.account == account_name {
let date_str = transaction.date.format("%Y-%m-%d").to_string();
worksheet.write_string(row, 0, &date_str, None).unwrap();
worksheet.write_string(row, 1, &transaction.description, None).unwrap();
worksheet.write_string(row, 2, &posting.account, None).unwrap();
worksheet.write_string(row, 3, &amount.value.to_string(), None).unwrap();
worksheet.write_string(row, 4, &amount.commodity, None).unwrap();
row += 1;
}
}
}
}
}
workbook.close().unwrap();
}
}
📝 4. data/example.ledger
2023-01-01 Opening Balances
Assets:Checking $1,000.00
Equity:Opening-Balance
2023-01-05 Paycheck
Income:Salary -$4,500.00
Assets:Checking $4,500.00
2023-01-06 Groceries
Expenses:Food $100.00
Assets:Checking -$100.00
✅ How to Use It
- Create a new project:
cargo new rust-ledger
cd rust-ledger
- Replace the contents of
Cargo.toml and src/*.rs with the above.
- Add an example ledger file in
data/example.ledger.
- Run:
cargo run -- -f data/example.ledger balance
Or export:
cargo run -- -f data/example.ledger export -o report.xlsx
Would you like me to also provide a bash or Python script that generates this structure automatically on your machine?