feat: add cli args
--filename-format formats the filename
--out is the output directory or file
Diff
Cargo.toml | 2 ++
src/cli.rs | 15 +++++++++++++++
src/main.rs | 45 ++++++++++++++++++++++++++++++++++++++-------
3 files changed, 55 insertions(+), 7 deletions(-)
@@ -7,4 +7,6 @@ edition = "2021"
[dependencies]
chrono = "0.4.31"
clap = { version = "4.4.11", features = ["derive"] }
screenshots = "0.8.6"
serde = { version = "1.0.193", features = ["derive"] }
@@ -0,0 +1,15 @@
use clap::Parser;
#[derive(Parser, Debug)]
pub struct Args {
#[arg(long, default_value = "screenshot-%Y-%m-%d_%H-%M-%S.png")]
pub filename_format: Option<String>,
#[arg(short, long)]
pub out: String,
}
@@ -1,11 +1,18 @@
use std::path::PathBuf;
use chrono::{DateTime, Local, Utc};
use clap::Parser;
use screenshots::{image::ImageBuffer, Screen};
mod cli;
fn main() {
capture_all();
let args = cli::Args::parse();
capture_all(args.out, args.filename_format.unwrap_or_default());
}
fn capture_all() {
fn capture_all(out_dir: String, filename_format: String) {
let mut screens = Screen::all().unwrap_or_else(|err| {
eprintln!("there was an error retrieving screens: {:?}", err);
vec![]
@@ -40,12 +47,14 @@ fn capture_all() {
});
if !img.is_empty() {
let filename: DateTime<Local> = Utc::now().with_timezone(&Local);
let timestamp: DateTime<Local> = Utc::now().with_timezone(&Local);
match img.save(format!(
"target/{}.png",
filename.format("%Y-%m-%d_%H-%M-%S")
)) {
let mut path = PathBuf::from(out_dir);
if path.is_dir() {
path = path.join(timestamp.format(&filename_format).to_string());
}
match img.save(generate_filename(&path)) {
Ok(_) => println!("screenshot saved successfully!"),
Err(err) => println!("there was an error saving the image: {:?}", err),
}
@@ -63,3 +72,25 @@ impl std::fmt::Display for ImageDimensions {
f.write_fmt(format_args!("({}, {})", self.x, self.y))
}
}
fn generate_filename(filename: &PathBuf) -> PathBuf {
let mut index = 0;
let mut new_filename = filename.clone();
let extension = filename
.extension()
.map(|ext| format!(".{}", ext.to_string_lossy()))
.unwrap_or_default();
while new_filename.exists() {
index += 1;
new_filename.set_file_name(format!(
"{}_{}{}",
filename.file_stem().unwrap().to_string_lossy(),
index,
extension
));
}
new_filename
}