use super::{config::ConfigFile, frontmatter::parse_frontmatter};
use std::{fs, path::Path};
pub fn copy_markdown_file(
dest_dir: &str,
file: &Path,
frontmatter_config: Option<&ConfigFile>,
) -> Result<(), Box<dyn std::error::Error>> {
let file_content = fs::read_to_string(&file)?;
let (content, data) = parse_frontmatter(&file_content)?;
let mut merged_data = data;
if let Some(config) = frontmatter_config {
merged_data.extend(config.other.clone());
}
if !merged_data.contains_key("title") {
println!("No title found in the frontmatter of {:?}", file);
return Ok(());
}
let title = merged_data["title"].as_str().unwrap_or("Untitled");
let updated_content = format!("# {}\n{}", title, content);
let new_file_content = format!(
"---\n{}---\n{}",
serde_yaml::to_string(&merged_data)?,
updated_content
);
let output_file_path = Path::new(dest_dir).join(file.file_name().unwrap());
fs::write(output_file_path, new_file_content)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use std::io::Write;
use tempfile::tempdir;
#[test]
fn test_copy_markdown_file() {
let temp_dir = tempdir().unwrap();
let temp_file_path = temp_dir.path().join("test.md");
let mut temp_file = fs::File::create(&temp_file_path).unwrap();
let content = r#"---
title: "Test Title"
description: "Test Description"
---
This is a test markdown file.
"#;
temp_file.write_all(content.as_bytes()).unwrap();
let dest_dir = tempdir().unwrap();
let result = copy_markdown_file(dest_dir.path().to_str().unwrap(), &temp_file_path, None);
assert!(result.is_ok());
let copied_file_path = dest_dir.path().join("test.md");
assert!(copied_file_path.exists());
let copied_content = fs::read_to_string(copied_file_path).unwrap();
assert!(copied_content.contains("# Test Title"));
assert!(copied_content.contains("This is a test markdown file."));
}
}