Skip to content

Commit

Permalink
feat(lib): write output to file
Browse files Browse the repository at this point in the history
  • Loading branch information
apogeeoak committed Jan 9, 2024
1 parent c25714f commit 8053777
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 14 deletions.
1 change: 1 addition & 0 deletions collection.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
title = "Title"
output_file = "local/collection-output.md"

[[collections]]
label = "Items"
Expand Down
13 changes: 13 additions & 0 deletions docs/release-notes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Release Notes

## v0.2.2

Added write output file.

## v0.2.1

Added wait for user.

## v0.1.1

Initial release.
21 changes: 18 additions & 3 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,20 @@ use std::fs;

use collection::Collection;

// Struct containing the processed configuration.
#[derive(Debug)]
pub struct Config {
pub title: String,
// Defaults to "collection.txt".
pub output_file: String,
pub collections: Vec<Collection>,
}

// Top level struct to hold entire input configuration.
#[derive(Debug, Deserialize)]
pub struct Config {
pub struct ConfigInput {
pub title: String,
pub output_file: Option<String>,
pub collections: Vec<Collection>,
}

Expand All @@ -19,8 +29,13 @@ impl Config {

let contents = fs::read_to_string(filename).map_err(|err| format!("Unable to read file '{}'. Error: {}", filename, err))?;

let input: Config = toml::from_str(&contents).map_err(|err| format!("Unable to load data from '{}'. Error: {}", filename, err))?;
let input: ConfigInput =
toml::from_str(&contents).map_err(|err| format!("Unable to load data from '{}'. Error: {}", filename, err))?;

Ok(input)
Ok(Config {
title: input.title,
output_file: input.output_file.unwrap_or("collection.txt".to_string()),
collections: input.collections,
})
}
}
38 changes: 27 additions & 11 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use crate::{config::Config, library::format::Row};
use rand::prelude::*;
use std::error::Error;
use std::fs;
use std::io::{stdin, stdout, Write};
use std::path::Path;

mod config;
mod library;
Expand All @@ -10,13 +12,13 @@ pub fn main() -> Result<(), Box<dyn Error>> {
// Read configuration.
let mut config = Config::read()?;

// Print title.
println!("\n{}\n", config.title);

shuffle_items(&mut config);

print_labels(&config);
print_items(&config);
// Format output.
let output = format!("{}\n\n{}\n{}", config.title, format_labels(&config), format_items(&config));

println!("\n{}", output);
write_to_file(config.output_file, output);

wait_for_user();

Expand All @@ -31,27 +33,41 @@ fn shuffle_items(config: &mut Config) {
}
}

fn print_labels(config: &Config) {
fn format_labels(config: &Config) -> String {
let labels = config.collections.iter().map(|c| Row { output: &c.label, width: c.width.into() });
let widths = config.collections.iter().map(|c| c.width.into());
println!("{}", library::format::row(labels));
println!("{}", library::format::divider(widths, None));

format!("{}\n{}", library::format::row(labels), library::format::divider(widths, None))
}

fn print_items(config: &Config) {
fn format_items(config: &Config) -> String {
let mut builder = String::new();
let string_empty = String::new();
let length = config.collections.iter().map(|c| c.items.len()).max().unwrap_or(0);
for index in 0..length {
let items = config.collections.iter().map(|c| Row {
output: c.items.get(index).unwrap_or(&string_empty),
width: c.width.into(),
});
println!("{}", library::format::row(items));
builder.push_str(&library::format::row(items));
builder.push('\n');
}
builder
}

fn wait_for_user() {
print!("\nPress <enter> to exit: ");
print!("Press <enter> to exit: ");
stdout().flush().expect("Error writing output.");
stdin().read_line(&mut String::new()).expect("Error reading input.");
}

fn write_to_file<P, C>(path: P, contents: C)
where
P: AsRef<Path>,
C: AsRef<[u8]>,
{
if let Some(parent) = path.as_ref().parent() {
fs::create_dir_all(parent).expect("Error creating parent directories.");
}
fs::write(path, contents).expect("Error writing output to file.");
}

0 comments on commit 8053777

Please # to comment.