use super::normalization::normalize_content;
use super::write::apply_shebang_chmod;
use crate::core::backend::GeneratedFile;
use crate::core::config::{Language, ResolvedCrateConfig};
use crate::core::ir::ApiSurface;
use anyhow::Context as _;
use base64::Engine;
use std::path::Path;
use tracing::debug;
pub fn scaffold(
api: &ApiSurface,
config: &ResolvedCrateConfig,
languages: &[Language],
) -> anyhow::Result<Vec<GeneratedFile>> {
crate::scaffold::scaffold(api, config, languages)
}
pub fn readme(
api: &ApiSurface,
config: &ResolvedCrateConfig,
languages: &[Language],
) -> anyhow::Result<Vec<GeneratedFile>> {
crate::readme::generate_readmes(api, config, languages)
}
pub fn write_scaffold_files(files: &[GeneratedFile], base_dir: &Path) -> anyhow::Result<usize> {
write_scaffold_files_with_overwrite(files, base_dir, false)
}
pub fn write_scaffold_files_with_overwrite(
files: &[GeneratedFile],
base_dir: &Path,
overwrite: bool,
) -> anyhow::Result<usize> {
let mut count = 0;
for file in files {
let full_path = base_dir.join(&file.path);
let can_skip = !overwrite && !file.generated_header && full_path.exists();
if can_skip {
debug!(" skipped (already exists): {}", full_path.display());
continue;
}
if let Some(parent) = full_path.parent() {
std::fs::create_dir_all(parent)
.with_context(|| format!("failed to create directory {}", parent.display()))?;
}
let is_jar_file = full_path.extension().is_some_and(|ext| ext == "jar");
if is_jar_file {
let binary_content = base64::engine::general_purpose::STANDARD
.decode(&file.content)
.with_context(|| format!("failed to decode base64 for {}", full_path.display()))?;
if let Ok(existing) = std::fs::read(&full_path) {
if existing == binary_content {
debug!(" unchanged: {}", full_path.display());
continue;
}
}
std::fs::write(&full_path, &binary_content)
.with_context(|| format!("failed to write binary file {}", full_path.display()))?;
count += 1;
debug!(" wrote (binary): {}", full_path.display());
continue;
}
let normalized = normalize_content(&full_path, &file.content);
if let Ok(existing) = std::fs::read_to_string(&full_path) {
let existing_body = crate::core::hash::strip_hash_line(&existing);
let normalized_body = crate::core::hash::strip_hash_line(&normalized);
if existing_body == normalized_body {
apply_shebang_chmod(&full_path, &normalized)?;
debug!(" unchanged: {}", full_path.display());
continue;
}
}
std::fs::write(&full_path, &normalized)
.with_context(|| format!("failed to write generated file {}", full_path.display()))?;
apply_shebang_chmod(&full_path, &normalized)?;
count += 1;
debug!(" wrote: {}", full_path.display());
}
Ok(count)
}