nbi 0.1.6

TUI for checking package name availability across npm, crates.io, PyPI, .dev domains and registering via GitHub
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
mod app;
mod cli;
mod config;
mod registry;
mod server;
mod ui;

use app::{App, InputMode, Screen};
use clap::Parser;
use cli::{Cli, Commands, PublishRegistry};
use crossterm::{
  event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind},
  execute,
  terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{backend::CrosstermBackend, Terminal};
use registry::RegistryType;
use std::{io, sync::Arc, time::Duration};
use tokio::sync::Mutex;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
  let cli = Cli::parse();

  match cli.command {
    None | Some(Commands::Tui) => run_tui().await,
    Some(Commands::Serve { port, open }) => server::start(port, open).await,
    Some(Commands::Check { name, json }) => run_check(&name, json).await,
    Some(Commands::Domain { name, tlds, json }) => run_domain_check(&name, &tlds, json).await,
    Some(Commands::Publish { registry }) => run_publish(registry).await,
  }
}

async fn run_tui() -> anyhow::Result<()> {
  // Setup terminal
  enable_raw_mode()?;
  let mut stdout = io::stdout();
  execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
  let backend = CrosstermBackend::new(stdout);
  let mut terminal = Terminal::new(backend)?;

  // Create app state
  let app = Arc::new(Mutex::new(App::new()));

  // Run the app
  let res = run_app(&mut terminal, app).await;

  // Restore terminal
  disable_raw_mode()?;
  execute!(
    terminal.backend_mut(),
    LeaveAlternateScreen,
    DisableMouseCapture
  )?;
  terminal.show_cursor()?;

  if let Err(err) = res {
    eprintln!("Error: {}", err);
  }

  Ok(())
}

async fn run_check(name: &str, json: bool) -> anyhow::Result<()> {
  let config = config::Config::load().unwrap_or_default();
  let results = registry::check_all(name, &config.registries).await;

  if json {
    println!("{}", serde_json::to_string_pretty(&results)?);
  } else {
    println!("Checking availability for: {}\n", name);
    for r in &results {
      let status = match r.available {
        Some(true) => "\x1b[32m✓ Available\x1b[0m",
        Some(false) => "\x1b[31m✗ Taken\x1b[0m",
        None => "\x1b[33m? Unknown\x1b[0m",
      };
      print!("  {:<12} {}", r.registry.to_string(), status);
      if let Some(ref err) = r.error {
        print!(" ({})", err);
      }
      println!();
    }
  }
  Ok(())
}

async fn run_domain_check(name: &str, tlds: &str, json: bool) -> anyhow::Result<()> {
  // Check if input is a full domain (contains a dot)
  let results = if name.contains('.') {
    // Full domain check - also check additional TLDs if specified
    let mut domains = vec![name.to_string()];
    
    // Parse the base name and add other TLDs
    if let Some(dot_pos) = name.rfind('.') {
      let base = &name[..dot_pos];
      for tld in tlds.split(',').map(|s| s.trim()) {
        let domain = format!("{}.{}", base, tld);
        if domain != name {
          domains.push(domain);
        }
      }
    }
    
    let mut results = Vec::new();
    for domain in &domains {
      results.push(registry::domain::check_full_domain(domain).await);
    }
    results
  } else {
    // Name + TLDs check
    let tld_list: Vec<&str> = tlds.split(',').map(|s| s.trim()).collect();
    registry::domain::check_multiple_tlds(name, &tld_list).await
  };

  if json {
    println!("{}", serde_json::to_string_pretty(&results)?);
  } else {
    println!("Checking domain availability for: {}\n", name);
    for r in &results {
      let status = match r.available {
        Some(true) => "\x1b[32m✓ Available\x1b[0m",
        Some(false) => "\x1b[31m✗ Taken\x1b[0m",
        None => "\x1b[33m? Unknown\x1b[0m",
      };
      println!("  {:<25} {}", r.name, status);
    }
  }
  Ok(())
}

async fn run_publish(registry: PublishRegistry) -> anyhow::Result<()> {
  match registry {
    PublishRegistry::Npm { path } => {
      println!("Publishing to npm from: {}", path);
      let status = std::process::Command::new("npm")
        .args(["publish"])
        .current_dir(&path)
        .status()?;
      if !status.success() {
        anyhow::bail!("npm publish failed");
      }
    }
    PublishRegistry::Crates { path } => {
      println!("Publishing to crates.io from: {}", path);
      let status = std::process::Command::new("cargo")
        .args(["publish"])
        .current_dir(&path)
        .status()?;
      if !status.success() {
        anyhow::bail!("cargo publish failed");
      }
    }
    PublishRegistry::Pypi { path } => {
      println!("Publishing to PyPI from: {}", path);
      // Build
      let build = std::process::Command::new("python")
        .args(["-m", "build"])
        .current_dir(&path)
        .status()?;
      if !build.success() {
        anyhow::bail!("python build failed");
      }
      // Upload
      let upload = std::process::Command::new("python")
        .args(["-m", "twine", "upload", "dist/*"])
        .current_dir(&path)
        .status()?;
      if !upload.success() {
        anyhow::bail!("twine upload failed");
      }
    }
  }
  println!("✓ Published successfully!");
  Ok(())
}

async fn run_app(
  terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
  app: Arc<Mutex<App>>,
) -> anyhow::Result<()> {
  loop {
    // Draw UI
    {
      let app_guard = app.lock().await;
      terminal.draw(|f| {
        ui::render(f, &app_guard);
        if app_guard.show_help {
          ui::render_help(f);
        }
      })?;
    }

    // Handle input with timeout for async operations
    if event::poll(Duration::from_millis(100))? {
      if let Event::Key(key) = event::read()? {
        if key.kind != KeyEventKind::Press {
          continue;
        }

        let mut app_guard = app.lock().await;

        // Global shortcuts
        match key.code {
          KeyCode::Char('q') if !matches!(app_guard.input_mode, InputMode::Editing) => {
            app_guard.should_quit = true;
          }
          KeyCode::Esc => {
            if app_guard.show_help {
              app_guard.show_help = false;
            } else if app_guard.input_mode == InputMode::Editing {
              app_guard.input_mode = InputMode::Normal;
            } else {
              app_guard.should_quit = true;
            }
          }
          KeyCode::Char('?') if app_guard.input_mode != InputMode::Editing => {
            app_guard.show_help = !app_guard.show_help;
          }
          KeyCode::Tab => {
            app_guard.toggle_screen();
          }
          KeyCode::Char('1') if app_guard.input_mode != InputMode::Editing => {
            app_guard.screen = Screen::Search;
          }
          KeyCode::Char('2') if app_guard.input_mode != InputMode::Editing => {
            app_guard.screen = Screen::Register;
          }
          KeyCode::Char('3') if app_guard.input_mode != InputMode::Editing => {
            app_guard.screen = Screen::Settings;
          }
          _ => {
            // Screen-specific handling
            match app_guard.screen {
              Screen::Search => {
                handle_search_input(&mut app_guard, key.code, Arc::clone(&app)).await;
              }
              Screen::Register => {
                handle_register_input(&mut app_guard, key.code).await;
              }
              Screen::Settings => {
                handle_settings_input(&mut app_guard, key.code);
              }
            }
          }
        }

        if app_guard.should_quit {
          break;
        }
      }
    }
  }

  Ok(())
}

async fn handle_search_input(app: &mut App, key: KeyCode, app_arc: Arc<Mutex<App>>) {
  // Disable input while searching
  if app.is_searching {
    return;
  }

  match app.input_mode {
    InputMode::Normal => match key {
      KeyCode::Char('i') | KeyCode::Char('e') | KeyCode::Enter => {
        app.input_mode = InputMode::Editing;
      }
      KeyCode::Up => app.select_previous(),
      KeyCode::Down => app.select_next(),
      _ => {}
    },
    InputMode::Editing => match key {
      KeyCode::Enter => {
        if !app.search_input.is_empty() {
          let name = app.search_input.clone();
          let settings = app.config.registries.clone();
          app.is_searching = true;

          // Spawn search in background
          let app_clone = Arc::clone(&app_arc);
          tokio::spawn(async move {
            let results = registry::check_all(&name, &settings).await;
            let mut app_guard = app_clone.lock().await;
            app_guard.search_results = results;
            app_guard.is_searching = false;
          });
        }
      }
      KeyCode::Char(c) => {
        app.search_input.push(c);
      }
      KeyCode::Backspace => {
        app.search_input.pop();
      }
      _ => {}
    },
  }
}

fn handle_settings_input(app: &mut App, key: KeyCode) {
  match key {
    KeyCode::Up => {
      if app.selected_setting > 0 {
        app.selected_setting -= 1;
      }
    }
    KeyCode::Down => {
      if app.selected_setting < app.registry_count() - 1 {
        app.selected_setting += 1;
      }
    }
    KeyCode::Enter | KeyCode::Char(' ') => {
      app.toggle_selected_registry();
    }
    _ => {}
  }
}

async fn handle_register_input(app: &mut App, key: KeyCode) {
  match key {
    KeyCode::Up => app.select_previous(),
    KeyCode::Down => app.select_next(),
    KeyCode::Enter => {
      // Extract needed values before mutable operations
      let selected_idx = app.selected_registry;
      let selected_registry = app
        .search_results
        .iter()
        .filter(|r| r.available == Some(true))
        .nth(selected_idx)
        .map(|r| r.registry);

      let token = app.config.get_github_token();
      let name = app.search_input.clone();

      if let Some(reg_type) = selected_registry {
        match reg_type {
          RegistryType::GitHub => {
            if let Some(token) = token {
              app.is_registering = true;
              app.register_status = Some("Creating GitHub repository...".to_string());

              match registry::github::create_repo(&name, None, false, &token).await {
                Ok(repo) => {
                  app.register_status = Some(format!("Success! Created: {}", repo.html_url));
                }
                Err(e) => {
                  app.register_status = Some(format!("Error: {}", e));
                }
              }
              app.is_registering = false;
            } else {
              app.register_status =
                Some("Error: Set GITHUB_TOKEN environment variable".to_string());
            }
          }
          RegistryType::Npm => {
            if let Some(token) = token {
              app.is_registering = true;
              app.register_status = Some(format!(
                "Creating GitHub repo with package.json for '{}'...",
                name
              ));

              match registry::github::create_repo_with_manifest(
                &name,
                registry::github::ManifestType::Npm,
                &token,
              ).await {
                Ok(repo) => {
                  app.register_status = Some(format!(
                    "Success! {} - Run 'npm publish' to claim the name",
                    repo.html_url
                  ));
                }
                Err(registry::github::GitHubError::RepoExists) => {
                  // Try to add manifest to existing repo
                  app.register_status = Some("Repo exists, checking for package.json...".to_string());
                  let username = registry::github::get_username(&token).await.unwrap_or_default();
                  match registry::github::add_manifest_if_missing(
                    &username,
                    &name,
                    registry::github::ManifestType::Npm,
                    &token,
                  ).await {
                    Ok(true) => {
                      app.register_status = Some(format!(
                        "Added package.json to existing repo. Run 'npm publish' to claim."
                      ));
                    }
                    Ok(false) => {
                      app.register_status = Some("package.json already exists in repo.".to_string());
                    }
                    Err(e) => {
                      app.register_status = Some(format!("Error adding manifest: {}", e));
                    }
                  }
                }
                Err(e) => {
                  app.register_status = Some(format!("Error: {}", e));
                }
              }
              app.is_registering = false;
            } else {
              app.register_status =
                Some("Error: Set GITHUB_TOKEN environment variable".to_string());
            }
          }
          RegistryType::Crates => {
            if let Some(token) = token {
              app.is_registering = true;
              app.register_status = Some(format!(
                "Creating GitHub repo with Cargo.toml for '{}'...",
                name
              ));

              match registry::github::create_repo_with_manifest(
                &name,
                registry::github::ManifestType::Crates,
                &token,
              ).await {
                Ok(repo) => {
                  app.register_status = Some(format!(
                    "Success! {} - Run 'cargo publish' to claim the name",
                    repo.html_url
                  ));
                }
                Err(registry::github::GitHubError::RepoExists) => {
                  app.register_status = Some("Repo exists, checking for Cargo.toml...".to_string());
                  let username = registry::github::get_username(&token).await.unwrap_or_default();
                  match registry::github::add_manifest_if_missing(
                    &username,
                    &name,
                    registry::github::ManifestType::Crates,
                    &token,
                  ).await {
                    Ok(true) => {
                      app.register_status = Some(format!(
                        "Added Cargo.toml to existing repo. Run 'cargo publish' to claim."
                      ));
                    }
                    Ok(false) => {
                      app.register_status = Some("Cargo.toml already exists in repo.".to_string());
                    }
                    Err(e) => {
                      app.register_status = Some(format!("Error adding manifest: {}", e));
                    }
                  }
                }
                Err(e) => {
                  app.register_status = Some(format!("Error: {}", e));
                }
              }
              app.is_registering = false;
            } else {
              app.register_status =
                Some("Error: Set GITHUB_TOKEN environment variable".to_string());
            }
          }
          RegistryType::PyPi => {
            if let Some(token) = token {
              app.is_registering = true;
              app.register_status = Some(format!(
                "Creating GitHub repo with pyproject.toml for '{}'...",
                name
              ));

              match registry::github::create_repo_with_manifest(
                &name,
                registry::github::ManifestType::PyPi,
                &token,
              ).await {
                Ok(repo) => {
                  app.register_status = Some(format!(
                    "Success! {} - Run 'twine upload' to claim the name",
                    repo.html_url
                  ));
                }
                Err(registry::github::GitHubError::RepoExists) => {
                  app.register_status = Some("Repo exists, checking for pyproject.toml...".to_string());
                  let username = registry::github::get_username(&token).await.unwrap_or_default();
                  match registry::github::add_manifest_if_missing(
                    &username,
                    &name,
                    registry::github::ManifestType::PyPi,
                    &token,
                  ).await {
                    Ok(true) => {
                      app.register_status = Some(format!(
                        "Added pyproject.toml to existing repo. Run 'twine upload' to claim."
                      ));
                    }
                    Ok(false) => {
                      app.register_status = Some("pyproject.toml already exists in repo.".to_string());
                    }
                    Err(e) => {
                      app.register_status = Some(format!("Error adding manifest: {}", e));
                    }
                  }
                }
                Err(e) => {
                  app.register_status = Some(format!("Error: {}", e));
                }
              }
              app.is_registering = false;
            } else {
              app.register_status =
                Some("Error: Set GITHUB_TOKEN environment variable".to_string());
            }
          }
          RegistryType::Brew => {
            app.register_status = Some(
              "Homebrew: Create a formula and submit PR to homebrew-core".to_string(),
            );
          }
          RegistryType::Flatpak => {
            app.register_status =
              Some("Flatpak: Submit your app to flathub.org/apps/submit".to_string());
          }
          RegistryType::Debian => {
            app.register_status =
              Some("Debian: Follow ITP process at wiki.debian.org/ITP".to_string());
          }
          RegistryType::DevDomain => {
            app.register_status = Some(
              "Domain registration requires a registrar (e.g., Google Domains, Namecheap)"
                .to_string(),
            );
          }
        }
      }
    }
    _ => {}
  }
}