coip-cli 0.2.0

CLI for converting, importing, exporting, diffing, inspecting, querying, verifying, and benchmarking COI (.coi) IP databases
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//! Persistent user configuration (`~/.coip/config.toml`) and 4-tier database resolution:
//!
//! 1. Explicit CLI argument (`-d/--db <PATH|ALIAS>` or positional `<FILE|ALIAS>`)
//! 2. `COIP_DB` environment variable (path or alias)
//! 3. Bound default database in `~/.coip/config.toml` (overridable via `COIP_CONFIG`)
//! 4. Single `.coi`/`.coip` file auto-discovery in the current working directory

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::ops;

/// Default output format persisted in `~/.coip/config.toml`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum OutputFormat {
    Table,
    Json,
    #[serde(alias = "default")]
    Line,
}

impl OutputFormat {
    pub fn parse(raw: &str) -> Result<Self, String> {
        match raw.trim().to_ascii_lowercase().as_str() {
            "table" => Ok(Self::Table),
            "json" => Ok(Self::Json),
            "line" | "default" => Ok(Self::Line),
            other => Err(format!(
                "invalid --format '{other}': expected table | json | line"
            )),
        }
    }

    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Table => "table",
            Self::Json => "json",
            Self::Line => "line",
        }
    }
}

/// Persisted CLI configuration stored at `~/.coip/config.toml`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CoipConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_db: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_format: Option<OutputFormat>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_fields: Option<String>,
    #[serde(default)]
    pub dbs: BTreeMap<String, PathBuf>,
}

/// Resolve the path to the config file (`COIP_CONFIG` env var or `~/.coip/config.toml`).
pub fn config_path() -> Result<PathBuf, Box<dyn std::error::Error>> {
    if let Some(custom) = std::env::var_os("COIP_CONFIG")
        && !custom.is_empty()
    {
        return Ok(PathBuf::from(custom));
    }
    let home = home_dir().ok_or("cannot determine home directory (set COIP_CONFIG to override)")?;
    Ok(home.join(".coip").join("config.toml"))
}

fn home_dir() -> Option<PathBuf> {
    #[cfg(windows)]
    {
        if let Some(p) = std::env::var_os("USERPROFILE")
            && !p.is_empty()
        {
            return Some(PathBuf::from(p));
        }
        if let (Some(drive), Some(path)) =
            (std::env::var_os("HOMEDRIVE"), std::env::var_os("HOMEPATH"))
            && !drive.is_empty()
            && !path.is_empty()
        {
            let mut full = drive;
            full.push(path);
            return Some(PathBuf::from(full));
        }
        if let Some(p) = std::env::var_os("HOME")
            && !p.is_empty()
        {
            return Some(PathBuf::from(p));
        }
        None
    }
    #[cfg(not(windows))]
    {
        std::env::var_os("HOME")
            .filter(|v| !v.is_empty())
            .map(PathBuf::from)
    }
}

/// Load `~/.coip/config.toml`, returning an empty default config if the file does not exist.
pub fn load_config() -> Result<CoipConfig, Box<dyn std::error::Error>> {
    let path = config_path()?;
    if !path.exists() {
        return Ok(CoipConfig::default());
    }
    let text = std::fs::read_to_string(&path)
        .map_err(|e| format!("failed to read config '{}': {e}", path.display()))?;
    let cfg: CoipConfig = toml::from_str(&text)
        .map_err(|e| format!("failed to parse TOML config '{}': {e}", path.display()))?;
    Ok(cfg)
}

/// Persist `CoipConfig` to `~/.coip/config.toml` with self-documenting defaults & comments.
pub fn save_config(cfg: &CoipConfig) -> Result<PathBuf, Box<dyn std::error::Error>> {
    let path = config_path()?;
    if let Some(parent) = path.parent()
        && !parent.as_os_str().is_empty()
    {
        std::fs::create_dir_all(parent)?;
    }
    let rendered = render_config_toml(cfg);
    std::fs::write(&path, rendered)?;
    Ok(path)
}

/// Render `CoipConfig` into clean, self-documenting TOML always including
/// `default_format` (defaulting to `"table"`) and `default_fields` (defaulting to `""`).
pub fn render_config_toml(cfg: &CoipConfig) -> String {
    use std::fmt::Write as _;

    let mut out = String::new();
    if let Some(ref db) = cfg.default_db {
        let _ = writeln!(out, "default_db = {}", toml_string(db));
    }
    let fmt = cfg.default_format.unwrap_or(OutputFormat::Table);
    let _ = writeln!(
        out,
        "default_format = {}   # 可选: default | json | table",
        toml_string(fmt.as_str())
    );
    let fields = cfg.default_fields.as_deref().unwrap_or("");
    let _ = writeln!(
        out,
        "default_fields = {}        # 可选: 默认裁剪字段",
        toml_string(fields)
    );

    if !cfg.dbs.is_empty() {
        out.push_str("\n[dbs]\n");
        for (alias, path) in &cfg.dbs {
            let key = toml_key(alias);
            let val = toml_path_string(&path.to_string_lossy());
            let _ = writeln!(out, "{key} = {val}");
        }
    }
    out
}

fn toml_string(s: &str) -> String {
    toml::Value::String(s.to_owned()).to_string()
}

fn toml_path_string(s: &str) -> String {
    // Prefer TOML single-quoted literal string for Windows paths containing `\` when safe.
    if s.contains('\\') && !s.contains('\'') && !s.chars().any(|c| c.is_control()) {
        format!("'{s}'")
    } else {
        toml_string(s)
    }
}

fn toml_key(k: &str) -> String {
    if !k.is_empty()
        && k.bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
    {
        k.to_owned()
    } else {
        toml_string(k)
    }
}

/// Canonicalize a file path cleanly (stripping Windows `\\?\` verbatim prefix for readability).
pub fn clean_canonical_path(path: &Path) -> Result<PathBuf, Box<dyn std::error::Error>> {
    let abs = std::fs::canonicalize(path)
        .map_err(|e| format!("cannot access '{}': {e}", path.display()))?;
    #[cfg(windows)]
    {
        if let Some(s) = abs.to_str() {
            if let Some(rest) = s.strip_prefix(r"\\?\UNC\") {
                return Ok(PathBuf::from(format!(r"\\{rest}")));
            }
            if let Some(rest) = s.strip_prefix(r"\\?\") {
                return Ok(PathBuf::from(rest));
            }
        }
    }
    Ok(abs)
}

/// Derive a short alias name from a `.coi`/`.coip` file path.
pub fn derive_alias(path: &Path) -> String {
    path.file_stem()
        .and_then(|s| s.to_str())
        .filter(|s| !s.is_empty())
        .unwrap_or("default")
        .to_owned()
}

/// Resolve a database path using the 4-tier precedence chain:
/// 1. `explicit` (CLI `-d/--db` or positional `<FILE|ALIAS>`)
/// 2. `COIP_DB` environment variable (path or alias)
/// 3. `cfg.default_db` in `~/.coip/config.toml`
/// 4. Single `.coi`/`.coip` file auto-discovered in the current directory
pub fn resolve_db_path(
    explicit: Option<&str>,
    cfg: &CoipConfig,
) -> Result<PathBuf, Box<dyn std::error::Error>> {
    // Tier 1: explicit CLI path or alias
    if let Some(spec) = explicit.map(str::trim).filter(|s| !s.is_empty()) {
        return resolve_spec(spec, cfg, "CLI argument");
    }

    // Tier 2: COIP_DB environment variable
    if let Ok(env_spec) = std::env::var("COIP_DB") {
        let trimmed = env_spec.trim();
        if !trimmed.is_empty() {
            return resolve_spec(trimmed, cfg, "COIP_DB");
        }
    }

    // Tier 3: Bound default_db in ~/.coip/config.toml
    if let Some(ref alias) = cfg.default_db {
        if let Some(path) = cfg.dbs.get(alias) {
            if !path.exists() {
                return Err(format!(
                    "bound default database '{alias}' points to missing file '{}'\n  Hint: re-bind with `coip bind <file>`",
                    path.display()
                )
                .into());
            }
            return Ok(path.clone());
        }
        return Err(format!(
            "config default_db '{alias}' is not found in bound databases\n  Hint: run `coip bind <file>`"
        )
        .into());
    }

    // Tier 4: Current working directory auto-discovery (only when unambiguous: exactly 1 .coi/.coip file)
    if let Ok(cwd) = std::env::current_dir()
        && let Ok(entries) = std::fs::read_dir(&cwd)
    {
        let mut found: Vec<PathBuf> = entries
            .flatten()
            .map(|e| e.path())
            .filter(|p| p.is_file() && is_coi_extension(p))
            .collect();
        found.sort();
        if found.len() == 1 {
            return Ok(found.pop().unwrap());
        }
        if found.len() > 1 {
            let names: Vec<String> = found
                .iter()
                .filter_map(|p| {
                    p.file_name()
                        .and_then(|n| n.to_str())
                        .map(ToOwned::to_owned)
                })
                .collect();
            return Err(format!(
                "multiple .coi/.coip files found in current directory ({}), please specify one or bind a default:\n  coip bind {}\n  coip query -d <file> <ip>",
                names.join(", "),
                names[0]
            )
            .into());
        }
    }

    Err(
        "no database specified and no default database bound.\n  Bind once:   coip bind <file.coi>\n  Or pass:     coip query -d <file.coi> <ip>\n  Or set env:  COIP_DB=<file.coi>"
            .into(),
    )
}

fn resolve_spec(
    spec: &str,
    cfg: &CoipConfig,
    source: &str,
) -> Result<PathBuf, Box<dyn std::error::Error>> {
    // Prefer an exact bound alias match first when no path separator exists and file doesn't exist literally
    let as_path = PathBuf::from(spec);
    if as_path.is_file() {
        return Ok(as_path);
    }
    if let Some(mapped) = cfg.dbs.get(spec) {
        if !mapped.exists() {
            return Err(format!(
                "database alias '{spec}' (from {source}) points to missing file '{}'",
                mapped.display()
            )
            .into());
        }
        return Ok(mapped.clone());
    }
    Err(format!(
        "database '{spec}' (from {source}) not found as a file or bound alias\n  Hint: run `coip bind` to view bound aliases"
    )
    .into())
}

fn is_coi_extension(path: &Path) -> bool {
    path.extension()
        .and_then(|s| s.to_str())
        .is_some_and(|e| e.eq_ignore_ascii_case("coi") || e.eq_ignore_ascii_case("coip"))
}

/// Options for `coip bind`.
pub struct BindArgs {
    pub file: Option<PathBuf>,
    pub name: Option<String>,
    pub use_alias: Option<String>,
    pub remove: Option<String>,
    pub unset: bool,
    pub format: Option<String>,
    pub fields: Option<String>,
}

/// Execute `coip bind`: bind/switch/remove/inspect default database and output preferences.
pub fn cmd_bind(args: BindArgs) -> Result<(), Box<dyn std::error::Error>> {
    let mut cfg = load_config()?;
    let mut modified = false;

    if let Some(ref file) = args.file {
        let abs = clean_canonical_path(file)?;
        if !abs.is_file() {
            return Err(format!("'{}' is not a file", abs.display()).into());
        }
        if !ops::is_coi_file(&abs)? {
            return Err(format!(
                "'{}' is not a valid COI database (missing \"COI\\0\" header)",
                abs.display()
            )
            .into());
        }
        let alias = args
            .name
            .as_deref()
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .map(ToOwned::to_owned)
            .unwrap_or_else(|| derive_alias(&abs));
        if alias.contains(['/', '\\', ':', ' ']) {
            return Err(format!("invalid alias name '{alias}'").into());
        }
        cfg.dbs.insert(alias.clone(), abs.clone());
        cfg.default_db = Some(alias.clone());
        modified = true;
        println!("Bound [{alias}] -> {} (set as default)", abs.display());
    }

    if let Some(ref alias) = args.use_alias {
        if !cfg.dbs.contains_key(alias) {
            return Err(format!(
                "unknown database alias '{alias}' (run `coip bind` to list bound databases)"
            )
            .into());
        }
        cfg.default_db = Some(alias.clone());
        modified = true;
        println!(
            "Switched default database -> [{alias}] ({})",
            cfg.dbs[alias].display()
        );
    }

    if let Some(ref alias) = args.remove {
        if cfg.dbs.remove(alias).is_none() {
            return Err(format!("unknown database alias '{alias}'").into());
        }
        if cfg.default_db.as_deref() == Some(alias.as_str()) {
            cfg.default_db = None;
        }
        modified = true;
        println!("Removed database alias [{alias}]");
    }

    if args.unset {
        cfg.default_db = None;
        modified = true;
        println!("Cleared default database binding");
    }

    if let Some(ref fmt_str) = args.format {
        let fmt = OutputFormat::parse(fmt_str)?;
        cfg.default_format = Some(fmt);
        modified = true;
        println!("Set default output format -> {}", fmt.as_str());
    }

    if let Some(ref fields_str) = args.fields {
        let trimmed = fields_str.trim();
        if trimmed.is_empty() {
            cfg.default_fields = None;
            println!("Cleared default projection fields");
        } else {
            cfg.default_fields = Some(trimmed.to_owned());
            println!("Set default projection fields -> {trimmed}");
        }
        modified = true;
    }

    if modified {
        let saved = save_config(&cfg)?;
        println!("Saved config: {}", saved.display());
        return Ok(());
    }

    // No mutating flags passed: show current config status
    let path = config_path()?;
    println!("Config file: {}", path.display());
    println!(
        "Default DB:  {}",
        cfg.default_db.as_deref().unwrap_or("(none)")
    );
    println!(
        "Default fmt: {}",
        cfg.default_format
            .map(OutputFormat::as_str)
            .unwrap_or("table")
    );
    println!(
        "Default flds:{}",
        cfg.default_fields
            .as_deref()
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .map(|s| format!(" {s}"))
            .unwrap_or_else(|| " (all)".into())
    );
    if let Ok(env_db) = std::env::var("COIP_DB")
        && !env_db.trim().is_empty()
    {
        println!("COIP_DB env: {env_db} (takes precedence over config)");
    }
    if cfg.dbs.is_empty() {
        println!("\nNo bound databases yet. Bind one with:\n  coip bind <file.coi>");
    } else {
        println!("\nBound databases ({}):", cfg.dbs.len());
        for (alias, p) in &cfg.dbs {
            let marker = if cfg.default_db.as_deref() == Some(alias.as_str()) {
                "*"
            } else {
                " "
            };
            let status = if p.is_file() { "" } else { " [MISSING]" };
            println!("  {marker} {alias:<16} {}{status}", p.display());
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_output_format_parse() {
        assert_eq!(OutputFormat::parse("table").unwrap(), OutputFormat::Table);
        assert_eq!(OutputFormat::parse("JSON").unwrap(), OutputFormat::Json);
        assert_eq!(OutputFormat::parse("line").unwrap(), OutputFormat::Line);
        assert!(OutputFormat::parse("xml").is_err());
    }

    #[test]
    fn test_resolve_alias_and_explicit_file() {
        let sample = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("..")
            .join("..")
            .join("test-vectors")
            .join("minimal_dual_stack.coi");
        let mut cfg = CoipConfig::default();
        cfg.dbs.insert("min".into(), sample.clone());
        cfg.default_db = Some("min".into());

        // Explicit alias resolves
        assert_eq!(resolve_db_path(Some("min"), &cfg).unwrap(), sample);
        // Explicit path resolves
        assert_eq!(
            resolve_db_path(Some(sample.to_str().unwrap()), &cfg).unwrap(),
            sample
        );
        // Default DB resolves when explicit is None (assuming COIP_DB not set)
        if std::env::var("COIP_DB")
            .map(|s| s.trim().is_empty())
            .unwrap_or(true)
        {
            assert_eq!(resolve_db_path(None, &cfg).unwrap(), sample);
        }
    }

    #[test]
    fn test_toml_config_roundtrip_with_comments_and_windows_paths() {
        let raw = r#"
# User-edited coip config
default_db = "geo"
default_format = "table"
default_fields = "country.iso_code,location.time_zone"

[dbs]
geo = 'C:\Users\Administrator\zixun\coip\geo.coip'
asn = "/data/GeoIP2-ASN.coi"
"#;
        let parsed: CoipConfig = toml::from_str(raw).unwrap();
        assert_eq!(parsed.default_db.as_deref(), Some("geo"));
        assert_eq!(parsed.default_format, Some(OutputFormat::Table));
        assert_eq!(
            parsed.default_fields.as_deref(),
            Some("country.iso_code,location.time_zone")
        );
        assert_eq!(
            parsed.dbs.get("geo"),
            Some(&PathBuf::from(
                r"C:\Users\Administrator\zixun\coip\geo.coip"
            ))
        );

        let serialized = render_config_toml(&parsed);
        assert!(
            serialized.contains(r#"default_format = "table"   # 可选: default | json | table"#)
        );
        assert!(serialized.contains("# 可选: 默认裁剪字段"));
        let reparsed: CoipConfig = toml::from_str(&serialized).unwrap();
        assert_eq!(reparsed.default_db, parsed.default_db);
        assert_eq!(reparsed.default_format, parsed.default_format);
        assert_eq!(reparsed.default_fields, parsed.default_fields);
        assert_eq!(reparsed.dbs, parsed.dbs);

        // Binding with only a file (no --format / --fields) still writes default_format="table" and default_fields=""
        let mut minimal = CoipConfig {
            default_db: Some("geo".into()),
            ..Default::default()
        };
        minimal
            .dbs
            .insert("geo".into(), PathBuf::from(r"C:\data\geo.coip"));
        let min_toml = render_config_toml(&minimal);
        assert!(min_toml.contains(r#"default_format = "table"   # 可选: default | json | table"#));
        assert!(min_toml.contains(r#"default_fields = ""        # 可选: 默认裁剪字段"#));
        let min_reparsed: CoipConfig = toml::from_str(&min_toml).unwrap();
        assert_eq!(min_reparsed.default_format, Some(OutputFormat::Table));
        assert_eq!(min_reparsed.default_fields.as_deref(), Some(""));
    }
}