common.rs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #![allow(dead_code)]
  2. use std::{fs, io};
  3. /// This can be changed to modify all the tool metadata all at once
  4. pub const VERSION: &'static str = "0.0";
  5. pub const AUTHOR: &'static str = "Getty Ritter <rrecutils@infinitenegativeutility.com>";
  6. // pub fn with_input_file<R>(spec: Option<&str>, f: impl FnOnce(&dyn io::Write) -> R) -> io::Result<R> {
  7. // match spec.unwrap_or("-") {
  8. // "-" => f(&io::BufReader::new(io::stdout())),
  9. // path => f(&io::BufReader::new(fs::File::open(path)?)),
  10. // }
  11. // }
  12. /// If this doesn't name a path, or if the path is `"-"`, then return
  13. /// a buffered reader from stdin; otherwise, attempt to open the file
  14. /// named by the path and return a buffered reader around it
  15. pub fn input_from_spec<'a>(spec: Option<&'a str>) -> io::Result<io::BufReader<Box<dyn io::Read>>> {
  16. match spec.unwrap_or("-") {
  17. "-" => Ok(io::BufReader::new(Box::new(io::stdin()))),
  18. path => {
  19. let f = fs::File::open(path)?;
  20. Ok(io::BufReader::new(Box::new(f)))
  21. }
  22. }
  23. }
  24. pub fn with_output_file<R>(
  25. spec: Option<&str>,
  26. f: impl FnOnce(&mut dyn io::Write) -> R,
  27. ) -> io::Result<R> {
  28. Ok(match spec.unwrap_or("-") {
  29. "-" => f(&mut io::stdout()),
  30. path => f(&mut fs::File::open(path)?),
  31. })
  32. }
  33. /// If this doesn't name a path, or if the path is `"-"`, then return
  34. /// a buffered writer to stdout; otherwise, attempt to open the file
  35. /// named by the path and return a writer around it
  36. pub fn output_from_spec<'a>(spec: Option<&'a str>) -> io::Result<Box<dyn io::Write>> {
  37. match spec.unwrap_or("-") {
  38. "-" => Ok(Box::new(io::stdout())),
  39. path => Ok(Box::new(fs::File::open(path)?)),
  40. }
  41. }