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.

67 lines
2.2 KiB

4 years ago
  1. //! This module contains an abstraction for gitignore files
  2. use crate::errors::*;
  3. use crate::helpers::git_dir;
  4. use log::trace;
  5. use std::fs::OpenOptions;
  6. use std::path::PathBuf;
  7. /// An abstraction of the gitignore file
  8. #[derive(Debug, Default)]
  9. pub struct Gitignore {
  10. /// The path to the gitignore
  11. path: PathBuf,
  12. }
  13. impl Gitignore {
  14. /// Create a new Gitignore struct from a git root folder path
  15. ///
  16. /// The given `path` must be a valid path to an existing git root folder
  17. pub fn from_path(path: &PathBuf) -> Self {
  18. trace!("Creating gitignore file object for path {}", path.to_string_lossy());
  19. Gitignore { path: path.clone() }
  20. }
  21. /// Return a new `Gitignore` object from the default location
  22. ///
  23. /// This function gets the default .gitignore in the git root folder for the current working
  24. /// directory
  25. ///
  26. /// # Errors
  27. ///
  28. /// - `ErrorKind::NoGitRootFound` when there was .gitignore file found at the default location
  29. ///
  30. pub fn from_default_path() -> Result<Self> {
  31. let mut path = git_dir()?.ok_or(ErrorKind::NoGitRootFound)?;
  32. path.push(".gitignore");
  33. Ok(Self::from_path(&path))
  34. }
  35. /// Append a line to the file
  36. pub fn add_line(&self, line: &str) -> Result<()> {
  37. use std::io::prelude::*;
  38. let mut file = OpenOptions::new()
  39. .write(true)
  40. .append(true)
  41. .create(true)
  42. .open(&self.path)
  43. .chain_err(|| "Error while opening gitignore file")?;
  44. writeln!(file, "{}", line).chain_err(|| "Error while writing line to gitignore")?;
  45. Ok(())
  46. }
  47. /// Reads the contents of the gitignore file and adds them to buf
  48. pub fn contents(&self, buf: &mut String) -> Result<()> {
  49. use std::io::prelude::*;
  50. let mut file = OpenOptions::new()
  51. .read(true)
  52. .open(&self.path)
  53. .chain_err(|| "Error while opening gitignore file")?;
  54. file.read_to_string(buf)?;
  55. Ok(())
  56. }
  57. }
  58. impl std::fmt::Display for Gitignore {
  59. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
  60. write!(f, "gitignore file {}", self.path.to_string_lossy())
  61. }
  62. }