Skip to content

Commit

Permalink
begin to parse cli
Browse files Browse the repository at this point in the history
  • Loading branch information
d2ci8xc5 committed Nov 24, 2019
1 parent 1c93988 commit 195d716
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 37 deletions.
11 changes: 1 addition & 10 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
shrust = "0.0.7" # Quick CLI command loop and registry
chrono = "0.4" # Date/Time
serde = { version = "1.0", features = ["derive"] } # Ser/Deser
serde_json = "1.0" # JSON
tempfile = "3" # Temporary files for testing
prettytable-rs = "^0.8" # Pretty print tables
46 changes: 34 additions & 12 deletions src/ledger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,24 @@ impl Ledger {
}

/// Add an account to the ledger
fn add_account(&mut self, acc: Account) -> bool {
// Only allow addition of unique accounts to ledger
pub fn add_account(&mut self, acc: Account) -> bool {
// Only allow addition of unique accounts (id and name are uuid) to ledger
for account in self.accounts.iter() {
if acc.id == account.id {
return false;
}
if acc.name == account.name {
return false;
}
}
self.accounts.push(acc);
return true;
}

// TODO: only allow added accounts to tx
// TODO: only allow added accounts to tx (collect)
/// Write a transaction to the ledger
fn add_transaction(&mut self, tx: Transaction) -> bool {
pub fn add_transaction(&mut self, tx: Transaction) -> bool {

// Only allow addition of unique txids to ledger
for transaction in self.transactions.iter() {
if tx.id == transaction.id {
Expand All @@ -47,18 +51,36 @@ impl Ledger {
}

/// Serialize ledger to disk
pub fn save(&self, file: &mut File) {
let serialized = serde_json::to_string(&self).unwrap();
write!(file, "{}", serialized).unwrap();
pub fn save(&self, file: &mut File) -> Result<(), &'static str>{
let serialized = match serde_json::to_string(&self) {
Ok(data) => data,
Err(reason) => return Err("Unable to serialize json"),
};

return match write!(file, "{}", serialized) {
Ok(()) => Ok(()),
Err(reason) => Err("Unable to write to file")
};
}

/// Serialize ledger from disk
pub fn load(&self, file: &mut File) -> Ledger {
file.seek(SeekFrom::Start(0)).unwrap();
pub fn load(&self, file: &mut File) -> Result<Ledger, &'static str> {
match file.seek(SeekFrom::Start(0)) {
Ok(ledger) => {},
Err(reason) => {return Err("Unable to start from 0th line in file");}
};

let mut buf = String::new();
file.read_to_string(&mut buf).unwrap();
let serde_ledger: Ledger = serde_json::from_str(&buf.to_string()).unwrap();
return serde_ledger;
match file.read_to_string(&mut buf) {
Ok(ledger) => {},
Err(reason) => {return Err("Unable to read ledger json string from file");}
};

return match serde_json::from_str(&buf.to_string()) {
Ok(serde_ledger) => Ok(serde_ledger),
Err(reason) => Err("Unable to parse string to ledger")

}
}
}

Expand Down
64 changes: 50 additions & 14 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use account::Account as acc;
use account::Account;
use std::io;
use std::io::prelude::*;
use std::fs::File;
use transaction::Transaction;

/// Initial greeting to the program
Expand All @@ -19,10 +20,10 @@ pub fn print_help() {
println!(
"\nsl\t\t: Save ledger state to disk\n\
ll\t\t: Load ledger state from disk\n\
ca\t\t: Create account\n\
ct\t\t: Create transaction\n\
la\t\t: Print account\n\
lt\t\t: Print transaction\n\
ca <name> <balance>\t\t: Create account\n\
ct <date> <name> <account_name> <amount> ...\t\t: Create transaction\n\
la [account_name]\t\t: Print account\n\
lt [transaction_name]\t\t: Print transaction\n\
quit\t\t: Exit ledger application saving ledger state to disk\n\
nsquit\t\t: Exit ledger application without saving ledger state to disk\n\
help\t\t: Print this help text\n\n\
Expand All @@ -36,9 +37,16 @@ pub fn print_help() {
pub fn run_loop() {
let mut next_txid = 0i32;
let mut next_accid = 0i32;
let db_path = "database/ledger.json";
let mut main_ledger = Ledger::new(Vec::new(), Vec::new());
let mut main_file = match File::open(db_path) {
Ok(file) => file,
Err(reason) => match File::create(db_path) {
Ok(file) => file,
Err(reason) => panic!("failed to create ledger json file"),
},
};

let main_ledger = Ledger::new(Vec::new(), Vec::new());
//let main_file;
print_header();
let input = io::stdin();

Expand All @@ -55,13 +63,43 @@ pub fn run_loop() {
print_help();
}
"sl" => { // Save ledger

match main_ledger.save(&mut main_file) {
Ok(ledger) => {},
Err(reason) => {
println!("{}", reason);
}
}
}
"ll" => { // Load ledger

match main_ledger.load(&mut main_file) {
Ok(ledger) => {},
Err(reason) => {
println!("{}", reason);
}
};
}
"cl" => { // Clear ledger
main_ledger = Ledger::new(Vec::new(), Vec::new());
}
"ca" => { // Create account
if args.len() != 3 {
println!("Invalid arguments: {} args given, 2 args required", args.len()-1);
}

let name : String = args[1].to_string();
let balance : i32 = match args[2].parse::<i32>() {
Ok(b) => b,
Err(b) => { println!("unable to parse balance (must be integer)"); continue; },
};

let account = match Account::new(next_accid.clone(), name, balance) {
Ok(acc) => acc,
Err(reason) => { println!("{}", reason); continue;}
};
if !main_ledger.add_account(account) {
println!("Unable to add account (is not unique)");
}
println!("Added account to ledger");
}
"ct" => { // Create transaction

Expand All @@ -73,16 +111,14 @@ pub fn run_loop() {

}
"quit" => { // Quit

main_ledger.save(&mut main_file);
break;
}
"nsquit" => { // No save quit

}
"" => {

break;
}
_ => {
println!("unknown command, type \"help\" for a list of availiable commands");
println!("Unknown command, type \"help\" for a list of availiable commands");
}
}
}
Expand Down

0 comments on commit 195d716

Please sign in to comment.