Skip to content

Commit

Permalink
Merge pull request #4 from DemwE/development
Browse files Browse the repository at this point in the history
Save to file
  • Loading branch information
DemwE authored Aug 10, 2023
2 parents c1ba39f + ef58148 commit 93c82ef
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 7 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "rgen"
version = "1.1.0"
version = "1.2.0"
authors = ["Mateusz Czarnecki (DemwE)"]
description = "A simple CLI tool for generating random passwords."
edition = "2021"
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@
- Optionally include special characters in generated passwords.
- Set the desired length of the passwords.
- Generate a specified number of passwords.
- Save generated passwords to a file.

3 changes: 3 additions & 0 deletions src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,7 @@ pub struct RgenArgs {
/// Raw output
#[clap(short, long)]
pub raw: bool,
/// Save to file
#[clap(short = 'S', long = "Save")]
pub save: Option<String>,
}
33 changes: 27 additions & 6 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ mod args;
use clap::Parser;
use args::RgenArgs;
use rand::Rng;
use std::fs::File;
use std::io::{Write, BufWriter};

fn main() {
// Parse the command line arguments
Expand All @@ -20,17 +22,36 @@ fn main() {
let count = args.count.unwrap_or(1); // Use 1 as the default value
let length = args.length.unwrap_or(16); // Use 16 as the default value

let file_path = args.save.clone();
let mut writer: Option<BufWriter<File>> = None;

if let Some(file_path) = &file_path {
let file = File::create(file_path).expect("Failed to create the output file");
writer = Some(BufWriter::new(file));
}

for _ in 0..count {
let password: String = (0..length)
.map(|_| available_characters.chars().nth(rng.gen_range(0..available_characters.len())).unwrap())
.collect();

if args.raw {
println!("{}", password);
continue;
}
else {
println!("Generated password: {}", password);
if let Some(ref mut writer) = writer {
if args.raw {
writeln!(writer, "{}", password).expect("Failed to write to file");
} else {
writeln!(writer, "Generated password: {}", password).expect("Failed to write to file");
}
} else {
if args.raw {
println!("{}", password);
} else {
println!("Generated password: {}", password);
}
}
}

if let Some(ref mut writer) = writer {
writer.flush().expect("Failed to flush the file");
println!("Passwords saved to: {}", file_path.unwrap());
}
}

0 comments on commit 93c82ef

Please sign in to comment.