gitcraft 0.1.123

A template project for GitHub-related utilities.
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
406
407
408
409
410
use std::collections::HashMap;
use std::io::{self, Write};
use std::path::PathBuf;

use anyhow::{Result, anyhow};
use colored::*;
use regex::Regex;

use crate::utils::cache::CacheManager;
use crate::utils::file;
use crate::utils::progress;
use crate::utils::remote::Fetcher;

use super::{
    SPDX_CACHE_NAME, SPDX_LICENSE_DETAILS_BASE_URL, SPDX_LICENSE_LIST_URL,
    ensure_spdx_license_cache,
};

// Command to add licenses
#[derive(clap::Args, Debug, Clone)]
pub struct AddArgs {
    /// License IDs to add (e.g., mit, apache-2.0)
    #[arg(value_name = "LICENSE")]
    pub licenses: Vec<String>,

    /// Directory to save the license file
    #[arg(long, value_name = "DIR")]
    pub dir: Option<PathBuf>,

    /// Force overwrite existing license file
    #[arg(long)]
    pub force: bool,

    /// Download all available licenses
    #[arg(long)]
    pub all: bool,

    /// Interactive mode for filling placeholders
    #[arg(long, short = 'i')]
    pub interactive: bool,

    /// update the cache
    #[arg(long)]
    pub update_cache: bool,

    /// Additional parameters for license placeholders (key=value format)
    #[arg(long = "param", value_name = "KEY=VALUE", num_args = 0.., action = clap::ArgAction::Append)]
    pub params: Vec<String>,

    /// Output file names for the licenses (in order of licenses)
    #[arg(short = 'o', long, value_name = "OUTPUT", num_args = 1.., requires = "licenses")]
    pub output: Vec<String>,
}

impl super::Runnable for AddArgs {
    fn run(&self) -> Result<()> {
        // Determine the directory to use
        let dir = match &self.dir {
            Some(d) => d.clone(),
            None => file::find_repo_root().unwrap_or_else(|_| PathBuf::from(".")),
        };

        // if update_cache is set, update the license cache
        if self.update_cache {
            let cache_manager = CacheManager::new()?;
            cache_manager.clear_cache(SPDX_CACHE_NAME)?;
        }

        // Parse parameters into a HashMap
        let mut placeholder_params = HashMap::new();
        for param in &self.params {
            if let Some((key, value)) = param.split_once('=') {
                placeholder_params.insert(key.trim().to_lowercase(), value.trim().to_string());
            } else {
                return Err(anyhow!(
                    "Invalid parameter format: '{}'. Use KEY=VALUE",
                    param
                ));
            }
        }

        let config = LicenseDownloadConfig {
            dir_path: Some(&dir),
            force: self.force,
            interactive: self.interactive,
            placeholder_params: &placeholder_params,
            update_cache: self.update_cache,
        };

        if self.all {
            download_all_licenses(&config)?;
        } else if self.licenses.is_empty() {
            return Err(anyhow!(
                "At least one license ID is required (or use --all)"
            ));
        } else {
            if !self.output.is_empty() {
                if self.output.len() != self.licenses.len() {
                    return Err(anyhow!(
                        "Number of output files must match number of licenses"
                    ));
                }

                for (license_id, output_name) in self.licenses.iter().zip(self.output.iter()) {
                    if let Err(e) =
                        download_single_license(license_id, &config, Some(output_name.clone()))
                    {
                        eprintln!(
                            "{}",
                            format!("Failed to download {}: {}", license_id, e).red()
                        );
                    }
                }
            } else {
                for license_id in &self.licenses {
                    if let Err(e) = download_single_license(license_id, &config, None) {
                        eprintln!(
                            "{}",
                            format!("Failed to download {}: {}", license_id, e).red()
                        );
                    }
                }
            }
        }

        Ok(())
    }
}

// Helper functions

// ------------ HANDLE DOWNLOADS ------------
pub struct LicenseDownloadConfig<'a> {
    pub dir_path: Option<&'a PathBuf>,
    pub force: bool,
    pub interactive: bool,
    pub placeholder_params: &'a HashMap<String, String>,
    pub update_cache: bool,
}

fn download_single_license(
    id: &str,
    config: &LicenseDownloadConfig,
    output_filename: Option<String>,
) -> Result<()> {
    let fetcher = Fetcher::new();

    let mut cache_manager = CacheManager::new()?;

    let license_cache = ensure_spdx_license_cache(&mut cache_manager, config.update_cache)?;

    let normalized_id = {
        let id_lower = id.to_lowercase();
        license_cache
            .entries
            .iter()
            .find(|(k, _)| k.to_lowercase() == id_lower)
            .map(|(key, _)| key.clone())
            .ok_or_else(|| {
                anyhow!(
                    "License '{}' not found in SPDX cache. Please check the license ID.",
                    id
                )
            })?
    };

    let details_url = format!("{}/{}.json", SPDX_LICENSE_DETAILS_BASE_URL, normalized_id);
    let pb = progress::spinner(&format!("Fetching license details: {}", id));

    let license_details = fetcher.fetch_json(&details_url).map_err(|e| {
        anyhow!(
            "Failed to fetch license '{}'. This might not be a valid SPDX license ID. Error: {}",
            id,
            e
        )
    })?;

    pb.set_message("Processing license text");

    let license_text = license_details
        .get("licenseText")
        .and_then(|t| t.as_str())
        .ok_or_else(|| anyhow!("License text not found in SPDX data"))?;

    pb.finish_and_clear();

    let processed_text =
        process_placeholders(license_text, config.interactive, config.placeholder_params)?;

    let dest_filename = output_filename.unwrap_or_else(|| "LICENSE".to_string());
    let dest_path: PathBuf = match config.dir_path {
        Some(dir) => dir.join(dest_filename),
        None => PathBuf::from(&dest_filename),
    };

    file::save_file(&processed_text, &dest_path, config.force)?;

    Ok(())
}

fn download_all_licenses(config: &LicenseDownloadConfig) -> Result<()> {
    let fetcher = Fetcher::new();

    let pb = progress::spinner("Fetching SPDX license list...");
    let licenses_data = fetcher.fetch_json(SPDX_LICENSE_LIST_URL)?;
    pb.set_message("Parsing license list...");

    let licenses = licenses_data
        .get("licenses")
        .and_then(|l| l.as_array())
        .ok_or_else(|| anyhow!("Failed to parse SPDX licenses list"))?;

    pb.finish_and_clear();

    let active_licenses: Vec<_> = licenses
        .iter()
        .filter(|license| {
            !license
                .get("isDeprecatedLicenseId")
                .and_then(|d| d.as_bool())
                .unwrap_or(false)
        })
        .collect();

    println!(
        "Found {} active licenses. Downloading...",
        active_licenses.len()
    );

    for license in active_licenses {
        let license_id = license
            .get("licenseId")
            .and_then(|id| id.as_str())
            .ok_or_else(|| anyhow!("License ID not found"))?;

        if let Err(e) = download_single_license(license_id, config, Some(license_id.to_string())) {
            eprintln!(
                "{}",
                format!("⚠️  Failed to download {}: {}", license_id, e).red()
            );
        }
    }

    Ok(())
}

// ------------ HANDLE PLACEHOLDERS ------------

fn process_placeholders(
    license_text: &str,
    interactive: bool,
    placeholder_params: &HashMap<String, String>,
) -> Result<String> {
    let square_bracket_re = Regex::new(r"\[([^\]]+)\]")?;
    let angle_bracket_re = Regex::new(r"<([^>]+)>")?;

    // Collect all unique placeholders
    let mut placeholders = std::collections::HashSet::new();
    for caps in square_bracket_re.captures_iter(license_text) {
        if let Some(m) = caps.get(1) {
            placeholders.insert(m.as_str().to_string());
        }
    }
    for caps in angle_bracket_re.captures_iter(license_text) {
        if let Some(m) = caps.get(1) {
            placeholders.insert(m.as_str().to_string());
        }
    }

    if placeholders.is_empty() {
        println!("{}", "✓ No placeholders found in license text.".green());

        // Warn about unused parameters when no placeholders exist
        if !placeholder_params.is_empty() {
            println!(
                "{} {} parameter(s) provided but no placeholders found:",
                "".yellow(),
                placeholder_params.len()
            );
            for (key, _) in placeholder_params {
                println!("  - {}", key);
            }
        }

        return Ok(license_text.to_string());
    } else if !interactive && placeholder_params.is_empty() {
        println!(
            "{} License contains placeholders. Use --interactive or --param PLACEHOLDER=VALUE to fill them.",
            "".yellow()
        );
    }

    // Prepare normalized params for matching
    let normalized_params: HashMap<String, &String> = placeholder_params
        .iter()
        .map(|(k, v)| (normalize_placeholder_key(k), v))
        .collect();

    // Track which parameters are actually used
    let mut used_params = std::collections::HashSet::new();
    let mut unfilled_placeholders = Vec::new();

    let mut result = license_text.to_string();
    for ph in &placeholders {
        let norm_ph = normalize_placeholder_key(ph);

        let replacement = if let Some(val) = normalized_params.get(&norm_ph) {
            used_params.insert(norm_ph.clone());
            val.to_string()
        } else if interactive {
            let user_input = prompt_for_placeholder(ph);
            if user_input == format!("[{}]", ph) {
                unfilled_placeholders.push(ph.clone());
            }
            user_input
        } else {
            // Keep original placeholder and track as unfilled
            unfilled_placeholders.push(ph.clone());
            format!("[{}]", ph)
        };

        // Replace both [placeholder] and <placeholder>
        result = square_bracket_re
            .replace_all(&result, |caps: &regex::Captures| {
                if normalize_placeholder_key(&caps[1]) == norm_ph {
                    replacement.clone()
                } else {
                    caps[0].to_string()
                }
            })
            .to_string();
        result = angle_bracket_re
            .replace_all(&result, |caps: &regex::Captures| {
                if normalize_placeholder_key(&caps[1]) == norm_ph {
                    replacement.clone()
                } else {
                    caps[0].to_string()
                }
            })
            .to_string();
    }

    // Warning for unused parameters
    let unused_params: Vec<&String> = placeholder_params
        .keys()
        .filter(|k| !used_params.contains(&normalize_placeholder_key(k)))
        .collect();

    if !unused_params.is_empty() {
        println!(
            "{} Warning: {} unused parameter(s):",
            "".yellow(),
            unused_params.len()
        );
        for param in unused_params {
            println!("  - {}", param);
        }
        println!("  Double-check parameter names match placeholders in the license.");
    }

    // Warning for unfilled placeholders
    if !unfilled_placeholders.is_empty() {
        println!(
            "{} Warning: {} placeholder(s) remain unfilled:",
            "".yellow(),
            unfilled_placeholders.len()
        );
        for ph in &unfilled_placeholders {
            println!("  - [{}]", ph);
        }
        println!("  Use --interactive or --param to provide values for these placeholders.");
    }

    // Summary message for user verification
    let filled_count = placeholders.len() - unfilled_placeholders.len();
    if filled_count > 0 {
        println!(
            "{} Filled {} out of {} placeholder(s).",
            "".green(),
            filled_count,
            placeholders.len()
        );
        println!(
            "{} Please carefully review the license text above for any missed or incorrect placeholders.",
            "".yellow()
        );
    }

    Ok(result)
}

fn normalize_placeholder_key(s: &str) -> String {
    s.trim().to_lowercase().replace(' ', "-")
}

fn prompt_for_placeholder(placeholder_content: &str) -> String {
    print!("Enter value for '{}': ", placeholder_content);
    let _ = io::stdout().flush();
    let mut input = String::new();
    if io::stdin().read_line(&mut input).is_ok() {
        let input = input.trim();
        if !input.is_empty() {
            input.to_string()
        } else {
            format!("[{}]", placeholder_content)
        }
    } else {
        format!("[{}]", placeholder_content)
    }
}