use chrono::{Datelike, Local};
use serde::Serialize;
use std::time::{SystemTime, UNIX_EPOCH};
use crate::ProjectConfig;
use crate::ProjectType;
#[derive(Debug, Clone, Serialize)]
pub struct TemplateVariables {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
pub version: String,
pub edition: String,
pub author: Author,
pub license: String,
pub project: ProjectFlags,
pub git: GitConfig,
pub date: DateInfo,
pub template: TemplateFlags,
}
#[derive(Debug, Clone, Serialize)]
pub struct Author {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct ProjectFlags {
pub is_binary: bool,
pub is_library: bool,
}
#[derive(Debug, Clone, Serialize)]
pub struct GitConfig {
pub initialize: bool,
pub create_commit: bool,
}
#[derive(Debug, Clone, Serialize)]
pub struct DateInfo {
pub year: u32,
pub iso_date: String,
pub timestamp: u64,
}
#[derive(Debug, Clone, Serialize)]
pub struct TemplateFlags {
pub is_minimal: bool,
pub is_extended: bool,
}
impl TemplateVariables {
pub fn from_config(config: &ProjectConfig) -> Self {
let now = Local::now();
let year = now.year() as u32;
let iso_date = now.format("%Y-%m-%d").to_string();
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let is_binary = matches!(config.project_type, ProjectType::Binary);
let is_library = matches!(config.project_type, ProjectType::Library);
let is_extended = true;
let is_minimal = !is_extended;
let author_name = "Your Name".to_string();
let author_email = Some("your.email@example.com".to_string());
Self {
name: config.name.clone(),
description: None, version: "0.1.0".to_string(),
edition: config.edition.clone(),
author: Author {
name: author_name,
email: author_email,
},
license: config.license.clone(),
project: ProjectFlags {
is_binary,
is_library,
},
git: GitConfig {
initialize: config.git,
create_commit: config.git,
},
date: DateInfo {
year,
iso_date,
timestamp,
},
template: TemplateFlags {
is_minimal,
is_extended,
},
}
}
#[cfg(test)]
pub fn default_test_variables() -> Self {
let (year, iso_date) = if cfg!(miri) {
(2023, "2023-04-01".to_string())
} else {
let now = Local::now();
(now.year() as u32, now.format("%Y-%m-%d").to_string())
};
Self {
name: "test-project".to_string(),
description: Some("A test project".to_string()),
version: "0.1.0".to_string(),
edition: "2021".to_string(),
author: Author {
name: "Test Author".to_string(),
email: Some("test@example.com".to_string()),
},
license: "MIT".to_string(),
project: ProjectFlags {
is_binary: true,
is_library: false,
},
git: GitConfig {
initialize: true,
create_commit: true,
},
date: DateInfo {
year,
iso_date,
timestamp: 1619712000, },
template: TemplateFlags {
is_minimal: false,
is_extended: true,
},
}
}
}