Skip to content

Instantly share code, notes, and snippets.

@ericdouglas
Created November 19, 2022 16:55
Show Gist options
  • Save ericdouglas/9212a94b675f7ec9ebccb07eb2eee4d8 to your computer and use it in GitHub Desktop.
Save ericdouglas/9212a94b675f7ec9ebccb07eb2eee4d8 to your computer and use it in GitHub Desktop.
quickreplace exercise program from programming rust v2 book
[package]
name = "quickreplace"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
text-colorizer = "1"
regex = "1"
#[derive(Debug)]
struct Arguments {
target: String,
replacement: String,
filename: String,
output: String,
}
use text_colorizer::*;
fn print_usage() {
eprintln!(
"{} - change occurrences of one string into another",
"quickreplace".green()
);
eprintln!("Usage: quickreplace <target> <replacement> <INPUT> <OUTPUT>")
}
use std::env;
fn parse_args() -> Arguments {
let args: Vec<String> = env::args().skip(1).collect();
if args.len() != 4 {
print_usage();
eprintln!(
"{} wrong number of arguments: expected 4, got {}.",
"Error:".red().bold(),
args.len()
);
std::process::exit(1);
}
Arguments {
target: args[0].clone(),
replacement: args[1].clone(),
filename: args[2].clone(),
output: args[3].clone(),
}
}
use regex::Regex;
fn replace(target: &str, replacement: &str, text: &str) -> Result<String, regex::Error> {
let regex = Regex::new(target)?;
Ok(regex.replace_all(text, replacement).to_string())
}
use std::fs;
fn main() {
let args = parse_args();
let data = match fs::read_to_string(&args.filename) {
Ok(v) => v,
Err(e) => {
eprintln!(
"{} failed to read from file '{}': {:?}",
"Error:".red().bold(),
args.filename,
e
);
std::process::exit(1);
}
};
let replaced_data = match replace(&args.target, &args.replacement, &data) {
Ok(v) => v,
Err(e) => {
eprintln!(
"{} failed to read from file '{}': {:?}",
"Error:".red().bold(),
args.filename,
e
);
std::process::exit(1);
}
};
match fs::write(&args.output, &replaced_data) {
Ok(_) => {}
Err(e) => {
eprintln!(
"{} failed to write to file '{}': {:?}",
"Error:".red().bold(),
args.filename,
e
);
std::process::exit(1);
}
}
println!("{:?}", args);
}
@mkohlhaas
Copy link

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment