use crate::github::types::{header_separator, repo_separator, summary_separator, CommitInfo};
use anyhow::{Context, Result};
use std::{fs::File, io::Write, path::Path, sync::Mutex};
pub struct SafeFileWriter {
inner: Mutex<File>,
}
impl SafeFileWriter {
pub fn new(filename: &Path) -> Result<Self> {
let file = File::create(filename)
.with_context(|| format!("creating output file: {}", filename.display()))?;
Ok(Self {
inner: Mutex::new(file),
})
}
pub fn write_header(&self, username: &str, since: &str, until: &str) {
let header = format!(
"GitHub Contributions for {username}\nPeriod: {since} to {until}\n{}\n",
header_separator()
);
self.write_str(&header);
}
pub fn write_repo(
&self,
username: &str,
repo_name: &str,
commits: &[CommitInfo],
readme_content: Option<&str>,
) {
let mut output = String::new();
output.push_str(&format!(
"\nRepository: {username}/{repo_name}\n{}\n",
repo_separator(username, repo_name)
));
if let Some(readme) = readme_content {
output.push('\n');
for line in readme.lines() {
output.push_str(&format!(" {line}\n"));
}
output.push('\n');
}
output.push_str("\n Commits:\n");
for commit in commits {
output.push_str(&format_commit_entry(commit));
}
self.write_str(&output);
}
pub fn write_summary(&self, total_commits: usize, repo_count: usize) {
let summary = format!(
"\n{}\nSummary:\n{}\nTotal commits: {total_commits}\nRepositories with commits: {repo_count}\n",
header_separator(),
summary_separator()
);
self.write_str(&summary);
}
fn write_str(&self, content: &str) {
let mut file = self.inner.lock().expect("writer mutex poisoned");
let _ = file.write_all(content.as_bytes());
let _ = file.flush();
}
}
fn format_commit_entry(commit: &CommitInfo) -> String {
let mut entry = String::new();
entry.push_str(&format!(" Date: {}\n", commit.date));
entry.push_str(&format!(" {}\n", commit.subject));
if !commit.body.is_empty() {
for line in commit.body.lines() {
if line.is_empty() {
entry.push('\n');
} else {
entry.push_str(&format!(" {line}\n"));
}
}
}
entry.push('\n');
entry
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats_commit_entry() {
let commit = CommitInfo {
date: "2026-01-15 10:30:00".to_string(),
subject: "feat: add stuff".to_string(),
body: String::new(),
};
let entry = format_commit_entry(&commit);
assert!(entry.contains(" Date: 2026-01-15 10:30:00\n"));
assert!(entry.contains(" feat: add stuff\n"));
}
}