Created
April 7, 2022 17:40
-
-
Save Headline/2d8e7da35c3d6cba4cf085bc3ceea24a to your computer and use it in GitHub Desktop.
Used for concatenating all code in a dir into a single output for homework submission
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::{env, fs}; | |
use std::fs::File; | |
use std::io::Read; | |
use std::path::PathBuf; | |
use std::process::exit; | |
fn output_help() { | |
println!("Usage: catall [OPTIONS] <directory>\n"); | |
println!("Concatenates all files within a directory to output"); | |
println!("Options:"); | |
println!("\t -t (Prepend fine contents with file name)"); | |
} | |
fn main() { | |
let mut args : Vec<String> = env::args().collect(); | |
let mut prepend_file_name = false; | |
if let Some(index) = args.iter().position(|x| *x == "-t") { | |
args.remove(index); | |
prepend_file_name = true; | |
} | |
if args.len() == 1 { | |
output_help(); | |
exit(0); | |
} | |
let path = args.get(1).unwrap(); | |
let mut out = String::new(); | |
walk(PathBuf::from(path), prepend_file_name, &mut out); | |
print!("{}", out); | |
} | |
fn walk(path : PathBuf, prepend_file_name : bool, output : &mut String) { | |
let dirs = match fs::read_dir(path) { | |
Ok(dir) => dir, | |
Err(e) => { | |
println!("{}", e); | |
exit(1); | |
} | |
}; | |
for dir in dirs { | |
if let Err(e) = dir { | |
println!("{}", e); | |
exit(1); | |
} | |
let new_path = dir.unwrap().path(); | |
if new_path.is_dir() { | |
walk(new_path, prepend_file_name, output); | |
} | |
else { | |
let file = File::open(&new_path); | |
match file { | |
Ok(mut file) => { | |
let path = new_path.as_os_str().to_str().unwrap().to_owned(); | |
output.push_str(&format!("// {}\n", path)); | |
let mut str = String::new(); | |
file.read_to_string(&mut str).unwrap(); | |
output.push_str(&format!("{}\n", str)); | |
} | |
Err(e) => { | |
println!("{}", e) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment