I can't directly generate a zip file for you, but I can provide you with a complete project structure and all the code we've discussed so far. You can then create the files and directories yourself to get started.
Here's a complete starting template for your Rust ledger application with currency formatting:
Project Structure
rust-ledger/
├── Cargo.toml
├── src/
│ ├── main.rs
│ ├── ledger.rs
│ ├── amount.rs
│ └── cli.rs
1. Cargo.toml
[package]
name = "rust-ledger"
version = "0.1.0"
edition = "2021"
[dependencies]
chrono = { version = "0.4", features = ["serde", "clock"] }
rust_decimal = "1.0"
rust_decimal_macros = "1.0"
num-format = "0.4.0"
lazy_static = "1.4.0"
regex = "1.5"
clap = { version = "4.0", features = ["derive"] }
xlsxwriter = "0.5"
2. src/main.rs
mod ledger;
mod amount;
mod cli;
use cli::build_cli;
use ledger::Ledger;
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let matches = build_cli().get_matches();
// Handle file input
let filename = matches.get_one::<String>("file").unwrap();
let content = std::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");
// Handle subcommands
match matches.subcommand() {
Some(("balance", _)) => ledger.print_balance(),
Some(("register", _)) => ledger.print_register(),
Some(("export", export_matches)) => {
let start_date = chrono::NaiveDate::parse_from_str(
export_matches.get_one::<String>("start").unwrap(),
"%Y-%m-%d"
).expect("Invalid start date (use YYYY-MM-DD)");
let end_date = chrono::NaiveDate::parse_from_str(
export_matches.get_one::<String>("end").unwrap(),
"%Y-%m-%d"
).expect("Invalid end date (use YYYY-MM-DD)");
let output_path = export_matches.get_one::<String>("output").unwrap();
ledger.export_to_excel(start_date, end_date, output_path)?;
}
_ => println!("No subcommand specified"),
}
Ok(())
}
3. src/ledger.rs
use chrono::{Date, Utc, NaiveDate};
use rust_decimal::Decimal;
use std::collections::HashMap;
use xlsxwriter::{Workbook, Format, FormatAlign, Error as XlsxError};
use std::error::Error;
use crate::amount::Amount;
#[derive(Debug, Clone)]
pub struct Account {
pub name: String,
pub balance: Decimal,
}
#[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>,
pub accounts: HashMap<String, Account>,
}
impl Ledger {
pub fn new() -> Self {
Ledger {
transactions: Vec::new(),
accounts: HashMap::new(),
}
}
pub fn parse_file(&mut self, content: &str) -> Result<(), String> {
// Placeholder for actual parsing logic
// This would parse the content and populate self.transactions
Ok(())
}
pub fn print_balance(&self) {
println!("Printing balance...");
// Implement balance printing logic
}
pub fn print_register(&self) {
println!("Printing register...");
// Implement register printing logic
}
pub fn export_to_excel(
&self,
start_date: NaiveDate,
end_date: NaiveDate,
output_path: &str,
) -> Result<(), Box<dyn Error>> {
// Create Excel workbook and worksheet
let workbook = Workbook::new(output_path)?;
let worksheet = workbook.add_worksheet(Some("Transactions"))?;
// Define formatting for headers, dates, and currency
let header_format = workbook.add_format()?
.set_bold()
.set_align(FormatAlign::Center)
.set_border(1);
let date_format = workbook.add_format()?
.set_num_format("yyyy-mm-dd");
let currency_format = workbook.add_format()?
.set_num_format("$#,##0.00")
.set_align(FormatAlign::Right);
// Write headers
let headers = vec!["Date", "Description", "Account", "Amount", "Commodity"];
for (col_idx, header) in headers.iter().enumerate() {
worksheet.write_string(0, col_idx as u16, header, Some(&header_format))?;
}
// Iterate over filtered transactions and write rows
let mut row_idx = 1;
for transaction in &self.transactions {
let tx_date = transaction.date.naive_utc();
if tx_date < start_date || tx_date > end_date {
continue;
}
for posting in &transaction.postings {
if let Some(amount) = &posting.amount {
// Write Date
worksheet.write_datetime(
row_idx,
0,
&transaction.date.and_hms(0, 0, 0),
Some(&date_format),
)?;
// Write Description
worksheet.write_string(row_idx, 1, &transaction.description, None)?;
// Write Account
worksheet.write_string(row_idx, 2, &posting.account, None)?;
// Write Amount
let amount_f64 = amount.value.to_f64().ok_or_else(|| {
format!("Amount too large for Excel: {}", amount.value)
})?;
if amount.commodity == "USD" {
worksheet.write_number(row_idx, 3, amount_f64, Some(¤cy_format))?;
} else {
worksheet.write_number(row_idx, 3, amount_f64, None)?;
}
// Write Commodity
worksheet.write_string(row_idx, 4, &amount.commodity, None)?;
row_idx += 1;
}
}
}
// Auto-adjust column widths
worksheet.set_column(0, 0, 12.0)?;
worksheet.set_column(1, 1, 30.0)?;
worksheet.set_column(2, 2, 25.0)?;
worksheet.set_column(3, 3, 15.0)?;
// Save and close the workbook
workbook.close()?;
println!("Exported {} transactions to {}", row_idx - 1, output_path);
Ok(())
}
}
4. src/amount.rs
use rust_decimal::Decimal;
use std::collections::HashMap;
use lazy_static::lazy_static;
use num_format::{Locale, ToFormattedString};
use std::str::FromStr;
use std::fmt;
use regex::Regex;
use rust_decimal_macros::dec;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Amount {
pub value: Decimal,
pub commodity: String,
}
#[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
};
}
impl fmt::Display for Amount {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> 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)
}
}
}
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 or ambiguous 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 })
}
}
5. src/cli.rs
use clap::{Command, Arg};
pub fn build_cli() -> Command {
Command::new("rust-ledger")
.version("0.1.0")
.about("A ledger-cli clone in Rust")
.arg(Arg::new("file")
.short('f')
.long("file")
.value_name("FILE")
.help("Ledger file to read")
.required(true))
.subcommand(Command::new("balance")
.about("Show account balances"))
.subcommand(Command::new("register")
.about("Show transaction register"))
.subcommand(Command::new("export")
.about("Export transactions to Excel")
.arg(Arg::new("start")
.long("start")
.value_name("DATE")
.help("Start date (YYYY-MM-DD)")
.required(true))
.arg(Arg::new("end")
.long("end")
.value_name("DATE")
.help("End date (YYYY-MM-DD)")
.required(true))
.arg(Arg::new("output")
.short('o')
.long("output")
.value_name("FILE")
.help("Output Excel file path")
.required(true)))
}
How to Use This Template
-
Create a new Rust project:
cargo new rust-ledger
cd rust-ledger
-
Replace the contents of Cargo.toml with the one provided above.
-
Create the src directory structure and files as shown above.
-
Copy the code into the respective files.
-
Build and run the project:
cargo build
cargo run -- -f your_ledger_file.dat balance
This template provides a solid foundation for your ledger application with:
- Basic CLI structure using
clap
- Ledger data structures
- Currency formatting and parsing
- Excel export functionality
You can now extend this template by implementing the actual parsing logic for ledger files, adding more commands, and enhancing the reporting features.