use crate::errors::*;
use crate::helpers::git_dir;
use log::trace;
use std::fs::OpenOptions;
use std::path::PathBuf;
#[derive(Debug, Default)]
pub struct Gitignore {
path: PathBuf,
}
impl Gitignore {
pub fn from_path(path: &PathBuf) -> Self {
trace!("Creating gitignore file object for path {}", path.to_string_lossy());
Gitignore { path: path.clone() }
}
pub fn from_default_path() -> Result<Self> {
let mut path = git_dir()?.ok_or(ErrorKind::NoGitRootFound)?;
path.push(".gitignore");
Ok(Self::from_path(&path))
}
pub fn add_line(&self, line: &str) -> Result<()> {
use std::io::prelude::*;
let mut file = OpenOptions::new()
.write(true)
.append(true)
.create(true)
.open(&self.path)
.chain_err(|| "Error while opening gitignore file")?;
writeln!(file, "{}", line).chain_err(|| "Error while writing line to gitignore")?;
Ok(())
}
pub fn contents(&self, buf: &mut String) -> Result<()> {
use std::io::prelude::*;
let mut file = OpenOptions::new()
.read(true)
.open(&self.path)
.chain_err(|| "Error while opening gitignore file")?;
file.read_to_string(buf)?;
Ok(())
}
}
impl std::fmt::Display for Gitignore {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
write!(f, "gitignore file {}", self.path.to_string_lossy())
}
}