licensectl 0.1.1

A CLI to fetch, store, and apply open-source license templates with interactive placeholder fill-in
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
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 a license to the registry
    Add {
        /// Name for the license (e.g. MIT)
        name: String,
        /// URL to fetch the license text from
        url: String,
    },
    /// List all registered licenses
    List,
    /// Initialize a project with a license from the registry
    Init {
        /// Name of the license (e.g. MIT)
        name: String,
        /// Overwrite an existing LICENSE file without prompting
        #[arg(short, long)]
        force: bool,
        /// Path to write the license to (defaults to ./LICENSE)
        #[arg(short, long)]
        output: Option<PathBuf>,
    },
    /// Delete a license from the registry
    Delete {
        /// Name of the license to 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);
    }
}