//! Description domain — repository description file read/write (used by GitWeb).

use std::path::PathBuf;

use crate::{GitDomain, GitError, GitResult};

impl GitDomain {
    /// Path to the description file.
    fn description_path(&self) -> PathBuf {
        PathBuf::from(self.repo().path()).join("description")
    }

    /// Read the repository description.
    /// Returns "Unnamed repository" if the file does not exist.
    pub fn description_get(&self) -> GitResult<String> {
        let path = self.description_path();
        if !path.exists() {
            return Ok("Unnamed repository".to_string());
        }
        let content =
            std::fs::read_to_string(&path).map_err(|e| GitError::IoError(e.to_string()))?;
        Ok(content.trim().to_string())
    }

    /// Write the repository description.
    pub fn description_set(&self, description: &str) -> GitResult<()> {
        let path = self.description_path();
        std::fs::write(&path, description.trim()).map_err(|e| GitError::IoError(e.to_string()))
    }

    pub fn description_exists(&self) -> bool {
        self.description_path().exists()
    }

    /// Reset description to the default "Unnamed repository".
    pub fn description_reset(&self) -> GitResult<()> {
        self.description_set("Unnamed repository")
    }
}
