use clap::Parser;
use std::collections::HashSet;
use std::fs;
use std::io::{self, Write};
use std::path::PathBuf;
use std::sync::OnceLock;
#[derive(Parser)]
#[command(name = "licensectl", version, about = "License management CLI")]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(clap::Subcommand)]
enum Commands {
Add {
name: String,
url: String,
},
List,
Init {
name: String,
#[arg(short, long)]
force: bool,
#[arg(short, long)]
output: Option<PathBuf>,
},
Delete {
name: String,
},
}
fn config_dir() -> Result<PathBuf, String> {
dirs::config_dir()
.map(|dir| dir.join("licensectl"))
.ok_or_else(|| "Could not determine config directory".to_string())
}
fn is_valid_name(name: &str) -> bool {
!name.is_empty()
&& name != "."
&& name != ".."
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
}
fn find_placeholders(content: &str) -> Vec<String> {
let mut seen = HashSet::new();
let mut placeholders = Vec::new();
let mut chars = content.char_indices();
while let Some((i, _)) = chars.find(|&(_, c)| c == '{') {
let rest = &content[i..];
if let Some(stripped) = rest.strip_prefix("{{")
&& let Some(end) = stripped.find("}}")
{
let var = &stripped[..end];
if !var.is_empty() && seen.insert(var.to_string()) {
placeholders.push(var.to_string());
}
}
}
placeholders
}
fn normalize_imported(content: &str) -> Result<(String, Vec<String>), String> {
let mut result = String::with_capacity(content.len());
let mut warnings = Vec::new();
let mut rest = content;
while let Some(pos) = rest.find(['[', '<']) {
let (open, close) = match rest.as_bytes()[pos] {
b'[' => ('[', ']'),
b'<' => ('<', '>'),
_ => unreachable!(),
};
let tail = &rest[pos + 1..];
if let Some(end) = tail.find(close) {
let inner = &tail[..end];
let bracket = format!("{}{}{}", open, inner, close);
result.push_str(&rest[..pos]);
if !inner.is_empty() && !inner.chars().any(char::is_whitespace) {
result.push_str("{{");
result.push_str(inner);
result.push_str("}}");
} else if !inner.is_empty() {
if confirm(&format!("Is \"{}\" a placeholder?", bracket))? {
let default_name = inner.replace(char::is_whitespace, "_");
let name = prompt(&format!("Name for \"{}\"", bracket), Some(&default_name))?;
result.push_str("{{");
result.push_str(&name);
result.push_str("}}");
} else {
result.push_str(&bracket);
warnings.push(format!("\"{}\" left unchanged.", bracket));
}
} else {
result.push_str(&bracket);
}
rest = &tail[end + 1..];
} else {
result.push_str(&rest[..pos]);
result.push(open);
rest = tail;
}
}
result.push_str(rest);
Ok((result, warnings))
}
fn prompt(label: &str, default: Option<&str>) -> Result<String, String> {
match default {
Some(d) => print!("{} [{}]: ", label, d),
None => print!("{}: ", label),
}
io::stdout()
.flush()
.map_err(|e| format!("Failed to flush stdout: {}", e))?;
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.map_err(|e| format!("Failed to read input: {}", e))?;
let trimmed = input.trim();
Ok(if trimmed.is_empty() {
default.unwrap_or_default().to_string()
} else {
trimmed.to_string()
})
}
fn confirm(prompt: &str) -> Result<bool, String> {
print!("{} [y/N] ", prompt);
io::stdout()
.flush()
.map_err(|e| format!("Failed to flush stdout: {}", e))?;
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.map_err(|e| format!("Failed to read input: {}", e))?;
Ok(input.trim().eq_ignore_ascii_case("y"))
}
fn current_year() -> i64 {
let secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or_default();
let days_from_epoch = (secs / 86_400) as i64;
let z = days_from_epoch + 719_468;
let era = (if z >= 0 { z } else { z - 146_096 }) / 146_097;
let doe = z - era * 146_097;
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
if m <= 2 { y + 1 } else { y }
}
fn git_user_name() -> Option<String> {
static CACHE: OnceLock<Option<String>> = OnceLock::new();
CACHE
.get_or_init(|| {
let out = std::process::Command::new("git")
.args(["config", "--get", "user.name"])
.output()
.ok()?;
if out.status.success() {
let name = String::from_utf8_lossy(&out.stdout).trim().to_string();
if name.is_empty() { None } else { Some(name) }
} else {
None
}
})
.clone()
}
fn default_for(var: &str) -> Option<String> {
let lower = var.to_ascii_lowercase();
if lower.contains("year") {
return Some(current_year().to_string());
}
if ["name", "author", "holder", "owner", "copyright"]
.iter()
.any(|key| lower.contains(key))
{
return git_user_name();
}
None
}
fn prompt_values(placeholders: &[String]) -> Result<Vec<(String, String)>, String> {
let mut values = Vec::new();
for var in placeholders {
let default = default_for(var);
let value = match &default {
Some(d) => prompt(&format!("Value for \"{}\"", var), Some(d))?,
None => prompt(&format!("Value for \"{}\"", var), None)?,
};
values.push((var.clone(), value));
}
Ok(values)
}
fn render(content: &str, values: &[(String, String)]) -> String {
let mut result = content.to_string();
for (var, val) in values {
result = result.replace(&format!("{{{{{}}}}}", var), val);
}
result
}
fn invalid_name_error(name: &str) -> String {
format!(
"Invalid license name '{}': only letters, digits, '.', '_' and '-' are allowed",
name
)
}
fn cmd_add(name: &str, url: &str) -> Result<(), String> {
if !is_valid_name(name) {
return Err(invalid_name_error(name));
}
let licenses_dir = config_dir()?.join("licenses");
fs::create_dir_all(&licenses_dir)
.map_err(|e| format!("Failed to create licenses directory: {}", e))?;
let license_path = licenses_dir.join(name);
let body = reqwest::blocking::get(url)
.map_err(|e| format!("Failed to fetch {}: {}", url, e))?
.error_for_status()
.map_err(|e| format!("Failed to fetch {}: {}", url, e))?
.text()
.map_err(|e| format!("Failed to read response body from {}: {}", url, e))?;
let (body, warnings) = normalize_imported(&body)?;
for warning in &warnings {
eprintln!("Warning: {}", warning);
}
if license_path.exists() && !confirm(&format!("License '{}' already exists. Replace?", name))? {
println!("Aborted.");
return Ok(());
}
fs::write(&license_path, body).map_err(|e| format!("Failed to write license file: {}", e))?;
println!("License '{}' saved to {}", name, license_path.display());
Ok(())
}
fn cmd_list() -> Result<(), String> {
let licenses_dir = config_dir()?.join("licenses");
if !licenses_dir.exists() {
println!("No licenses registered.");
return Ok(());
}
let entries = fs::read_dir(&licenses_dir)
.map_err(|e| format!("Failed to read licenses directory: {}", e))?;
let mut names: Vec<String> = entries
.flatten()
.filter(|entry| entry.file_type().map(|t| t.is_file()).unwrap_or(false))
.filter_map(|entry| entry.file_name().to_str().map(String::from))
.collect();
if names.is_empty() {
println!("No licenses registered.");
return Ok(());
}
names.sort();
for name in names {
let placeholders = match fs::read_to_string(licenses_dir.join(&name)) {
Ok(content) => find_placeholders(&content),
Err(e) => {
eprintln!("Warning: could not read '{}': {}", name, e);
Vec::new()
}
};
if placeholders.is_empty() {
println!("{}", name);
} else {
println!("{} (needs: {})", name, placeholders.join(", "));
}
}
Ok(())
}
fn cmd_init(name: &str, force: bool, output: Option<PathBuf>) -> Result<(), String> {
if !is_valid_name(name) {
return Err(invalid_name_error(name));
}
let license_path = config_dir()?.join("licenses").join(name);
if !license_path.exists() {
return Err(format!(
"License '{}' not found. Add it first with: licensectl add {} <url>",
name, name
));
}
let content = fs::read_to_string(&license_path)
.map_err(|e| format!("Failed to read license file: {}", e))?;
let placeholders = find_placeholders(&content);
let final_content = if placeholders.is_empty() {
content
} else {
println!(
"This license has {} placeholder(s) to fill in.",
placeholders.len()
);
let values = prompt_values(&placeholders)?;
render(&content, &values)
};
let dest = match output {
Some(path) => {
if path.is_dir() {
path.join("LICENSE")
} else {
path
}
}
None => std::env::current_dir()
.map_err(|e| format!("Failed to get current directory: {}", e))?
.join("LICENSE"),
};
if dest.exists()
&& !force
&& !confirm(&format!("{} already exists. Overwrite?", dest.display()))?
{
println!("Aborted.");
return Ok(());
}
fs::write(&dest, &final_content).map_err(|e| format!("Failed to write LICENSE file: {}", e))?;
println!("Created LICENSE from '{}'", name);
Ok(())
}
fn cmd_delete(name: &str) -> Result<(), String> {
if !is_valid_name(name) {
return Err(invalid_name_error(name));
}
let license_path = config_dir()?.join("licenses").join(name);
if !license_path.exists() {
return Err(format!("License '{}' not found.", name));
}
if !confirm(&format!("Delete license '{}'?", name))? {
println!("Aborted.");
return Ok(());
}
fs::remove_file(&license_path).map_err(|e| format!("Failed to delete license file: {}", e))?;
println!("Deleted license '{}'", name);
Ok(())
}
fn main() {
let cli = Cli::parse();
let result = match cli.command {
Commands::Add { name, url } => cmd_add(&name, &url),
Commands::List => cmd_list(),
Commands::Init {
name,
force,
output,
} => cmd_init(&name, force, output),
Commands::Delete { name } => cmd_delete(&name),
};
if let Err(e) = result {
eprintln!("Error: {}", e);
std::process::exit(1);
}
}