typebridge-cli 0.3.2

Standalone CLI for typewriter generation, drift checks, and watch mode
Documentation
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
//! # typebridge-cli
//!
//! Standalone CLI for typewriter type synchronization.
//!
//! This crate provides the `typewriter` and `cargo-typewriter` command-line tools
//! for generating, checking, and watching cross-language type definitions.
//!
//! ## Installation
//!
//! ### Pre-built Binary
//!
//! ```bash
//! cargo install typebridge-cli
//! ```
//!
//! ### As Cargo Plugin
//!
//! After installing, run via cargo:
//!
//! ```bash
//! cargo install typebridge-cli
//! cargo typewriter --help
//! ```
//!
//! ## Commands
//!
//! ### `typewriter generate`
//!
//! Generate type files from Rust source definitions.
//!
//! ```bash
//! # Generate from a single file
//! typewriter generate src/models.rs
//!
//! # Generate from all Rust files in the project
//! typewriter generate --all
//!
//! # Generate only TypeScript and Python
//! typewriter generate --all --lang typescript,python
//!
//! # Show unified diffs for changed files
//! typewriter generate --all --diff
//! ```
//!
//! ### `typewriter check`
//!
//! Check if generated files are in sync with Rust source.
//!
//! ```bash
//! # Check all types
//! typewriter check
//!
//! # Check with CI exit code (non-zero on drift)
//! typewriter check --ci
//!
//! # Output as JSON
//! typewriter check --json
//!
//! # Write JSON report to file
//! typewriter check --json-out drift-report.json
//!
//! # Check specific languages
//! typewriter check --lang typescript,python
//! ```
//!
//! ### `typewriter watch`
//!
//! Watch Rust files and regenerate types on save.
//!
//! ```bash
//! # Watch src directory (default)
//! typewriter watch
//!
//! # Watch custom directory
//! typewriter watch src/models/
//!
//! # Watch with specific languages
//! typewriter watch --lang typescript,python
//!
//! # Set debounce interval (milliseconds)
//! typewriter watch --debounce-ms 100
//! ```
//!
//! ## Exit Codes
//!
//! | Code | Meaning |
//! |------|---------|
//! | 0 | Success (no drift for `check --ci`) |
//! | 1 | Error or drift detected (for `check --ci`) |
//!
//! ## Configuration
//!
//! The CLI respects `typewriter.toml` in the project root for output directories,
//! file naming styles, and other configuration options. See the main typewriter
//! documentation for configuration details.

use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use colored::Colorize;
use notify::{Event, RecommendedWatcher, RecursiveMode, Watcher};
use similar::TextDiff;
use std::collections::{BTreeMap, BTreeSet};
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::sync::mpsc;
use std::time::{Duration, Instant};
use typewriter_engine::LanguageTarget;
use typewriter_engine::drift::{self, DriftStatus};
use typewriter_engine::emit;
use typewriter_engine::plugin_registry;
use typewriter_engine::{parse_languages, project, scan};

#[derive(Parser, Debug)]
#[command(
    name = "typewriter",
    about = "Generate and verify cross-language types"
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Generate type files from Rust source definitions.
    Generate {
        /// Generate from a single Rust source file.
        file: Option<PathBuf>,
        /// Generate from all Rust files in project root.
        #[arg(long)]
        all: bool,
        /// Restrict generation to languages (comma-separated).
        #[arg(long, value_delimiter = ',')]
        lang: Vec<String>,
        /// Show unified diffs for changed files.
        #[arg(long)]
        diff: bool,
    },
    /// Check if generated files are in sync with Rust source.
    Check {
        /// Exit with code 1 if drift is detected.
        #[arg(long)]
        ci: bool,
        /// Print structured JSON drift report to stdout.
        #[arg(long)]
        json: bool,
        /// Write structured JSON drift report to a file.
        #[arg(long)]
        json_out: Option<PathBuf>,
        /// Restrict check to languages (comma-separated).
        #[arg(long, value_delimiter = ',')]
        lang: Vec<String>,
    },
    /// Watch Rust files and regenerate on save.
    Watch {
        /// Directory to watch recursively (default: ./src).
        path: Option<PathBuf>,
        /// Restrict generation to languages (comma-separated).
        #[arg(long, value_delimiter = ',')]
        lang: Vec<String>,
        /// Debounce interval for filesystem events.
        #[arg(long, default_value_t = 50)]
        debounce_ms: u64,
    },
    /// Manage typewriter plugins.
    Plugin {
        #[command(subcommand)]
        action: PluginAction,
    },
}

#[derive(Subcommand, Debug)]
enum PluginAction {
    /// List all loaded plugins.
    List,
    /// Validate a plugin shared library.
    Validate {
        /// Path to the plugin shared library.
        path: PathBuf,
    },
    /// Show info about a specific loaded plugin.
    Info {
        /// Plugin language ID (e.g. "ruby", "php", "dart").
        name: String,
    },
}

pub fn run() -> Result<i32> {
    run_with_args(std::env::args_os())
}

pub fn run_with_args<I, T>(args: I) -> Result<i32>
where
    I: IntoIterator<Item = T>,
    T: Into<OsString> + Clone,
{
    let cli = Cli::try_parse_from(args).map_err(|err| anyhow::anyhow!(err.to_string()))?;

    match cli.command {
        Commands::Generate {
            file,
            all,
            lang,
            diff,
        } => cmd_generate(file, all, lang, diff),
        Commands::Check {
            ci,
            json,
            json_out,
            lang,
        } => cmd_check(ci, json, json_out, lang),
        Commands::Watch {
            path,
            lang,
            debounce_ms,
        } => cmd_watch(path, lang, debounce_ms),
        Commands::Plugin { action } => cmd_plugin(action),
    }
}

/// Extract only the built-in Language values from a list of LanguageTargets.
fn extract_builtin_filter(targets: &[LanguageTarget]) -> Vec<typewriter_engine::Language> {
    targets
        .iter()
        .filter_map(|t| match t {
            LanguageTarget::BuiltIn(lang) => Some(*lang),
            LanguageTarget::Plugin(_) => None,
        })
        .collect()
}

fn cmd_generate(file: Option<PathBuf>, all: bool, lang: Vec<String>, diff: bool) -> Result<i32> {
    if all == file.is_some() {
        anyhow::bail!("use exactly one input mode: either `generate <file>` or `generate --all`");
    }

    let cwd = std::env::current_dir()?;
    let project_root = project::discover_project_root(&cwd)?;
    let config = project::load_config(&project_root).unwrap_or_default();
    let lang_targets = parse_languages(&lang)?;
    let lang_filter = extract_builtin_filter(&lang_targets);
    let registry = plugin_registry::build_registry_from_config(&config).unwrap_or_default();

    let specs = if all {
        scan::scan_project(&project_root)?
    } else {
        let source = resolve_input_path(file.expect("validated"), &cwd);
        scan::scan_file(&source)?
    };

    let rendered = emit::render_specs_deduped_with_plugins(
        &specs, &project_root, &config, &lang_filter, false, Some(&registry),
    )?;

    let started = Instant::now();
    let mut updated = 0usize;
    let mut created = 0usize;
    let mut unchanged = 0usize;

    let mut before_contents = BTreeMap::new();
    for file in &rendered {
        if let Ok(existing) = std::fs::read_to_string(&file.output_path) {
            before_contents.insert(file.output_path.clone(), existing);
        }
    }

    emit::write_generated_files(&rendered)?;

    for file in &rendered {
        let rel = rel_path(&project_root, &file.output_path);
        match before_contents.get(&file.output_path) {
            None => {
                created += 1;
                eprintln!(
                    "{} {} [{}]",
                    "Created".green(),
                    rel,
                    file.language_label
                );
                if diff {
                    print_diff(&project_root, &file.output_path, "", &file.content);
                }
            }
            Some(existing) if existing == &file.content => {
                unchanged += 1;
                eprintln!(
                    "{} {} [{}]",
                    "Unchanged".bright_black(),
                    rel,
                    file.language_label
                );
            }
            Some(existing) => {
                updated += 1;
                eprintln!(
                    "{} {} [{}]",
                    "Updated".yellow(),
                    rel,
                    file.language_label
                );
                if diff {
                    print_diff(&project_root, &file.output_path, existing, &file.content);
                }
            }
        }
    }

    eprintln!(
        "{} in {}ms (created: {}, updated: {}, unchanged: {})",
        "Generation complete".bold(),
        started.elapsed().as_millis(),
        created,
        updated,
        unchanged
    );

    Ok(0)
}

fn cmd_check(ci: bool, json: bool, json_out: Option<PathBuf>, lang: Vec<String>) -> Result<i32> {
    let cwd = std::env::current_dir()?;
    let project_root = project::discover_project_root(&cwd)?;
    let config = project::load_config(&project_root).unwrap_or_default();
    let lang_targets = parse_languages(&lang)?;
    let lang_filter = extract_builtin_filter(&lang_targets);
    let registry = plugin_registry::build_registry_from_config(&config).unwrap_or_default();

    let specs = scan::scan_project(&project_root)?;
    let rendered = emit::render_specs_deduped_with_plugins(
        &specs, &project_root, &config, &lang_filter, false, Some(&registry),
    )?;

    let report = drift::build_drift_report(&rendered, &project_root, &config, &lang_filter)?;

    if !json {
        print_human_report(&report);
    } else {
        let output = serde_json::to_string_pretty(&report)?;
        println!("{}", output);
    }

    if let Some(path) = json_out {
        let full = resolve_input_path(path, &cwd);
        if let Some(parent) = full.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(&full, serde_json::to_string_pretty(&report)?)
            .with_context(|| format!("failed to write json report to {}", full.display()))?;
        eprintln!("{} {}", "Wrote JSON report: ".green(), full.display());
    }

    if ci && drift::has_drift(&report.summary) {
        eprintln!("{} drift detected in CI mode", "Error:".red().bold());
        return Ok(1);
    }

    Ok(0)
}

fn cmd_watch(path: Option<PathBuf>, lang: Vec<String>, debounce_ms: u64) -> Result<i32> {
    let cwd = std::env::current_dir()?;
    let project_root = project::discover_project_root(&cwd)?;
    let watch_root = resolve_input_path(path.unwrap_or_else(|| PathBuf::from("src")), &cwd);
    let config = project::load_config(&project_root).unwrap_or_default();
    let lang_targets = parse_languages(&lang)?;
    let lang_filter = extract_builtin_filter(&lang_targets);
    let registry = plugin_registry::build_registry_from_config(&config).unwrap_or_default();

    let (tx, rx) = mpsc::channel();
    let mut watcher = RecommendedWatcher::new(
        move |result| {
            let _ = tx.send(result);
        },
        notify::Config::default(),
    )?;

    watcher.watch(&watch_root, RecursiveMode::Recursive)?;

    eprintln!(
        "{} {} (debounce={}ms)",
        "Watching".green().bold(),
        watch_root.display(),
        debounce_ms
    );

    loop {
        let first = match rx.recv() {
            Ok(event) => event,
            Err(err) => {
                eprintln!("{} watcher channel closed: {}", "Error:".red(), err);
                return Ok(1);
            }
        };

        let mut changed_files = BTreeSet::new();
        collect_changed_rust_files(first, &mut changed_files);

        while let Ok(event) = rx.recv_timeout(Duration::from_millis(debounce_ms)) {
            collect_changed_rust_files(event, &mut changed_files);
        }

        if changed_files.is_empty() {
            continue;
        }

        let batch_started = Instant::now();
        let mut specs = Vec::new();

        for changed in &changed_files {
            eprintln!("{} {}", "Changed:".cyan(), rel_path(&project_root, changed));
            if changed.exists() {
                match scan::scan_file(changed) {
                    Ok(mut found) => specs.append(&mut found),
                    Err(err) => eprintln!("{} {}", "Scan error:".red(), err),
                }
            }
        }

        if specs.is_empty() {
            continue;
        }

        let mut names: Vec<_> = specs
            .iter()
            .map(|s| s.type_def.name().to_string())
            .collect();
        names.sort();
        names.dedup();
        for name in names {
            eprintln!("{} {}", "Detected TypeWriter type:".blue(), name);
        }

        let rendered = emit::render_specs_deduped_with_plugins(
            &specs, &project_root, &config, &lang_filter, false, Some(&registry),
        )?;

        let mut updated = 0usize;
        for file in rendered {
            let before = std::fs::read_to_string(&file.output_path).ok();
            emit::write_generated_files(std::slice::from_ref(&file))?;

            let changed = before.map(|c| c != file.content).unwrap_or(true);
            if changed {
                updated += 1;
            }

            eprintln!(
                "{} {} [{}]",
                "Regenerated".green(),
                rel_path(&project_root, &file.output_path),
                file.language_label
            );
        }

        eprintln!(
            "{} {} file(s) in {}ms",
            "Done".bold(),
            updated,
            batch_started.elapsed().as_millis()
        );
    }
}

fn cmd_plugin(action: PluginAction) -> Result<i32> {
    let cwd = std::env::current_dir()?;
    let project_root = project::discover_project_root(&cwd).unwrap_or(cwd);
    let config = project::load_config(&project_root).unwrap_or_default();
    let registry = plugin_registry::build_registry_from_config(&config)?;

    match action {
        PluginAction::List => {
            let plugins = registry.list();
            if plugins.is_empty() {
                eprintln!("{}", "No plugins loaded.".bright_black());
                eprintln!(
                    "  Install plugins to {} or configure [plugins] in typewriter.toml",
                    "~/.typewriter/plugins/"
                );
            } else {
                eprintln!(
                    "{} {} plugin(s) loaded:\n",
                    "Plugins:".bold(),
                    plugins.len()
                );
                for p in &plugins {
                    eprintln!(
                        "  {} {} v{}",
                        "".green(),
                        p.language_name.bold(),
                        p.version
                    );
                    eprintln!("    Language ID:  {}", p.language_id);
                    eprintln!("    Extension:    .{}", p.file_extension);
                    eprintln!("    Output dir:   {}", p.default_output_dir);
                    if let Some(path) = &p.source_path {
                        eprintln!("    Loaded from:  {}", path.display());
                    }
                    eprintln!();
                }
            }
            Ok(0)
        }
        PluginAction::Validate { path } => {
            eprintln!("Validating plugin: {}...", path.display());
            let mut test_registry = typewriter_engine::PluginRegistry::new();
            match test_registry.load_plugin(&path) {
                Ok(()) => {
                    let plugins = test_registry.list();
                    if let Some(p) = plugins.first() {
                        eprintln!(
                            "{} Plugin is valid!",
                            "".green().bold()
                        );
                        eprintln!("  Name:       {}", p.language_name);
                        eprintln!("  Language:   {}", p.language_id);
                        eprintln!("  Version:    {}", p.version);
                        eprintln!("  Extension:  .{}", p.file_extension);
                    }
                    Ok(0)
                }
                Err(err) => {
                    eprintln!(
                        "{} Plugin validation failed: {}",
                        "".red().bold(),
                        err
                    );
                    Ok(1)
                }
            }
        }
        PluginAction::Info { name } => {
            let plugins = registry.list();
            if let Some(p) = plugins.iter().find(|p| p.language_id == name) {
                eprintln!("{} {}", "Plugin:".bold(), p.language_name);
                eprintln!("  Language ID:  {}", p.language_id);
                eprintln!("  Version:      {}", p.version);
                eprintln!("  Extension:    .{}", p.file_extension);
                eprintln!("  Output dir:   {}", p.default_output_dir);
                if let Some(path) = &p.source_path {
                    eprintln!("  Loaded from:  {}", path.display());
                }
                Ok(0)
            } else {
                eprintln!(
                    "{} No plugin found with language ID '{}'",
                    "Error:".red().bold(),
                    name
                );
                Ok(1)
            }
        }
    }
}

fn print_human_report(report: &drift::DriftReport) {
    for entry in &report.entries {
        let symbol = match entry.status {
            DriftStatus::UpToDate => "OK".green(),
            DriftStatus::OutOfSync => "DRIFT".yellow(),
            DriftStatus::Missing => "MISSING".red(),
            DriftStatus::Orphaned => "ORPHAN".magenta(),
        };

        eprintln!(
            "{} {} [{}] - {}",
            symbol, entry.output_path, entry.language, entry.reason
        );
    }

    eprintln!(
        "{} up_to_date={}, out_of_sync={}, missing={}, orphaned={}",
        "Summary:".bold(),
        report.summary.up_to_date,
        report.summary.out_of_sync,
        report.summary.missing,
        report.summary.orphaned
    );
}

fn print_diff(project_root: &Path, path: &Path, before: &str, after: &str) {
    let rel = rel_path(project_root, path);
    let diff = TextDiff::from_lines(before, after)
        .unified_diff()
        .context_radius(3)
        .header(&format!("a/{}", rel), &format!("b/{}", rel))
        .to_string();

    if !diff.trim().is_empty() {
        println!("{}", diff);
    }
}

fn collect_changed_rust_files(event: Result<Event, notify::Error>, files: &mut BTreeSet<PathBuf>) {
    let event = match event {
        Ok(event) => event,
        Err(err) => {
            eprintln!("{} {}", "Watch error:".red(), err);
            return;
        }
    };

    for path in event.paths {
        if path.extension().map(|ext| ext == "rs").unwrap_or(false) {
            files.insert(path);
        }
    }
}

fn rel_path(root: &Path, path: &Path) -> String {
    path.strip_prefix(root)
        .unwrap_or(path)
        .display()
        .to_string()
}

fn resolve_input_path(path: PathBuf, cwd: &Path) -> PathBuf {
    if path.is_absolute() {
        path
    } else {
        cwd.join(path)
    }
}

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

    #[test]
    fn rejects_invalid_generate_mode() {
        let err = run_with_args(["typewriter", "generate"]).unwrap_err();
        assert!(err.to_string().contains("use exactly one input mode"));
    }

    #[test]
    fn parses_comma_separated_langs() {
        let parsed = parse_languages(&["typescript,python".to_string()]).unwrap();
        assert_eq!(
            parsed,
            vec![
                LanguageTarget::BuiltIn(typewriter_engine::Language::TypeScript),
                LanguageTarget::BuiltIn(typewriter_engine::Language::Python),
            ]
        );
    }

    #[test]
    fn parses_plugin_languages() {
        let parsed = parse_languages(&["ruby,php".to_string()]).unwrap();
        assert_eq!(
            parsed,
            vec![
                LanguageTarget::Plugin("ruby".to_string()),
                LanguageTarget::Plugin("php".to_string()),
            ]
        );
    }
}