A cli program to easily handle .gitignore files
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

40 lines
1.3 KiB

4 years ago
  1. //! This module contains an abstraction for gitignore files
  2. use crate::errors::*;
  3. use log::trace;
  4. use std::fs::OpenOptions;
  5. use std::path::PathBuf;
  6. /// An abstraction of the gitignore file
  7. #[derive(Debug, Default)]
  8. pub struct Gitignore {
  9. /// The path to the gitignore
  10. path: PathBuf,
  11. }
  12. impl Gitignore {
  13. /// Create a new Gitignore struct from a git root folder path
  14. ///
  15. /// The given `path` must be a valid path to an existing git root folder
  16. pub fn from_path(path: &PathBuf) -> Self {
  17. trace!("Creating gitignore file object for path {}", path.to_string_lossy());
  18. Gitignore { path: path.clone() }
  19. }
  20. /// Append a line to the file
  21. pub fn add_line(&self, line: &str) -> Result<()> {
  22. use std::io::prelude::*;
  23. let mut file = OpenOptions::new()
  24. .write(true)
  25. .append(true)
  26. .create(true)
  27. .open(&self.path)
  28. .chain_err(|| "Error while opening gitignore file")?;
  29. writeln!(file, "{}", line).chain_err(|| "Error while writing line to gitignore")?;
  30. Ok(())
  31. }
  32. }
  33. impl std::fmt::Display for Gitignore {
  34. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
  35. write!(f, "gitignore file {}", self.path.to_string_lossy())
  36. }
  37. }