nbi 0.1.9

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
use super::{AvailabilityResult, RegistryType};
use reqwest::{header, StatusCode};
use serde::{Deserialize, Serialize};

const GITHUB_API_URL: &str = "https://api.github.com";

#[derive(Debug, Serialize)]
struct CreateRepoRequest {
  name: String,
  description: Option<String>,
  private: bool,
  auto_init: bool,
}

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct RepoResponse {
  pub id: u64,
  pub name: String,
  pub full_name: String,
  pub html_url: String,
}

#[derive(Debug, thiserror::Error)]
pub enum GitHubError {
  #[error("Authentication required: provide a GitHub personal access token")]
  AuthRequired,

  #[error("Repository name already exists")]
  RepoExists,

  #[error("Invalid repository name")]
  InvalidName,

  #[error("Rate limited")]
  RateLimited,

  #[error("API error: {0}")]
  ApiError(String),

  #[error("Network error: {0}")]
  NetworkError(#[from] reqwest::Error),
}

/// Check if a GitHub user or organization name is available
///
/// API: GET https://api.github.com/users/{username}
/// - 404: User/org not found (available)
/// - 200: User/org exists (not available)
pub async fn check_name(name: &str) -> AvailabilityResult {
  let url = format!("{}/users/{}", GITHUB_API_URL, name);

  let client = reqwest::Client::new();
  match client
    .get(&url)
    .header(header::USER_AGENT, "nbi/0.1.0")
    .header(header::ACCEPT, "application/vnd.github+json")
    .send()
    .await
  {
    Ok(response) => {
      let available = match response.status() {
        StatusCode::NOT_FOUND => Some(true),
        StatusCode::OK => Some(false),
        _ => None,
      };
      AvailabilityResult {
        registry: RegistryType::GitHub,
        name: name.to_string(),
        available,
        error: if available.is_none() {
          Some(format!("Unexpected status: {}", response.status()))
        } else {
          None
        },
      }
    }
    Err(e) => AvailabilityResult {
      registry: RegistryType::GitHub,
      name: name.to_string(),
      available: None,
      error: Some(e.to_string()),
    },
  }
}

/// Check if a GitHub repository name is available for the authenticated user
///
/// API: GET https://api.github.com/repos/{owner}/{repo}
/// - 404: Repository not found (available)
/// - 200: Repository exists (not available)
#[allow(dead_code)]
pub async fn check_repo(owner: &str, name: &str, token: &str) -> AvailabilityResult {
  let url = format!("{}/repos/{}/{}", GITHUB_API_URL, owner, name);

  let client = reqwest::Client::new();
  match client
    .get(&url)
    .header(header::USER_AGENT, "nbi/0.1.0")
    .header(header::AUTHORIZATION, format!("Bearer {}", token))
    .header(header::ACCEPT, "application/vnd.github+json")
    .send()
    .await
  {
    Ok(response) => {
      let available = match response.status() {
        StatusCode::NOT_FOUND => Some(true),
        StatusCode::OK => Some(false),
        _ => None,
      };
      AvailabilityResult {
        registry: RegistryType::GitHub,
        name: format!("{}/{}", owner, name),
        available,
        error: if available.is_none() {
          Some(format!("Unexpected status: {}", response.status()))
        } else {
          None
        },
      }
    }
    Err(e) => AvailabilityResult {
      registry: RegistryType::GitHub,
      name: format!("{}/{}", owner, name),
      available: None,
      error: Some(e.to_string()),
    },
  }
}

/// Create a new GitHub repository
///
/// API: POST https://api.github.com/user/repos
/// Required scope: public_repo (for public) or repo (for private)
pub async fn create_repo(
  name: &str,
  description: Option<&str>,
  private: bool,
  token: &str,
) -> Result<RepoResponse, GitHubError> {
  let url = format!("{}/user/repos", GITHUB_API_URL);

  let request = CreateRepoRequest {
    name: name.to_string(),
    description: description.map(String::from),
    private,
    auto_init: true, // Create with README to initialize
  };

  let client = reqwest::Client::new();
  let response = client
    .post(&url)
    .header(header::USER_AGENT, "nbi/0.1.0")
    .header(header::AUTHORIZATION, format!("Bearer {}", token))
    .header(header::ACCEPT, "application/vnd.github+json")
    .json(&request)
    .send()
    .await?;

  match response.status() {
    StatusCode::CREATED => {
      let repo: RepoResponse = response.json().await?;
      Ok(repo)
    }
    StatusCode::UNAUTHORIZED => Err(GitHubError::AuthRequired),
    StatusCode::UNPROCESSABLE_ENTITY => {
      let body = response.text().await.unwrap_or_default();
      if body.contains("name already exists") {
        Err(GitHubError::RepoExists)
      } else {
        Err(GitHubError::InvalidName)
      }
    }
    StatusCode::FORBIDDEN => Err(GitHubError::RateLimited),
    _ => {
      let body = response.text().await.unwrap_or_default();
      Err(GitHubError::ApiError(body))
    }
  }
}

/// Get authenticated user's username
pub async fn get_username(token: &str) -> Result<String, GitHubError> {
  let url = format!("{}/user", GITHUB_API_URL);

  let client = reqwest::Client::new();
  let response = client
    .get(&url)
    .header(header::USER_AGENT, "nbi/0.1.0")
    .header(header::AUTHORIZATION, format!("Bearer {}", token))
    .header(header::ACCEPT, "application/vnd.github+json")
    .send()
    .await?;

  if response.status() == StatusCode::UNAUTHORIZED {
    return Err(GitHubError::AuthRequired);
  }

  #[derive(Deserialize)]
  struct User {
    login: String,
  }

  let user: User = response.json().await?;
  Ok(user.login)
}

/// Registry type for manifest generation
#[derive(Debug, Clone, Copy)]
pub enum ManifestType {
  Npm,
  Crates,
  PyPi,
}

impl ManifestType {
  pub fn filename(&self) -> &'static str {
    match self {
      ManifestType::Npm => "package.json",
      ManifestType::Crates => "Cargo.toml",
      ManifestType::PyPi => "pyproject.toml",
    }
  }

  pub fn generate_content(&self, name: &str, description: &str) -> String {
    match self {
      ManifestType::Npm => format!(
        r#"{{
  "name": "{}",
  "version": "0.0.1",
  "description": "{}",
  "main": "index.js",
  "scripts": {{
    "test": "echo \"Error: no test specified\" && exit 1"
  }},
  "keywords": [],
  "author": "",
  "license": "MIT"
}}
"#,
        name, description
      ),
      ManifestType::Crates => format!(
        r#"[package]
name = "{}"
version = "0.0.1"
edition = "2021"
description = "{}"
license = "MIT"

[dependencies]
"#,
        name, description
      ),
      ManifestType::PyPi => format!(
        r#"[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"

[project]
name = "{}"
version = "0.0.1"
description = "{}"
readme = "README.md"
license = {{text = "MIT"}}
requires-python = ">=3.8"
classifiers = [
    "Programming Language :: Python :: 3",
    "License :: OSI Approved :: MIT License",
    "Operating System :: OS Independent",
]

[project.urls]
Homepage = "https://github.com/OWNER/{}"
"#,
        name, description, name
      ),
    }
  }
}

#[derive(Debug, Serialize)]
struct CreateFileRequest {
  message: String,
  content: String,
  #[serde(skip_serializing_if = "Option::is_none")]
  branch: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct FileContent {
  pub sha: String,
}

/// Check if a file exists in a repository
pub async fn check_file_exists(
  owner: &str,
  repo: &str,
  path: &str,
  token: &str,
) -> Result<Option<String>, GitHubError> {
  let url = format!("{}/repos/{}/{}/contents/{}", GITHUB_API_URL, owner, repo, path);

  let client = reqwest::Client::new();
  let response = client
    .get(&url)
    .header(header::USER_AGENT, "nbi/0.1.0")
    .header(header::AUTHORIZATION, format!("Bearer {}", token))
    .header(header::ACCEPT, "application/vnd.github+json")
    .send()
    .await?;

  match response.status() {
    StatusCode::OK => {
      let file: FileContent = response.json().await?;
      Ok(Some(file.sha))
    }
    StatusCode::NOT_FOUND => Ok(None),
    StatusCode::UNAUTHORIZED => Err(GitHubError::AuthRequired),
    _ => {
      let body = response.text().await.unwrap_or_default();
      Err(GitHubError::ApiError(body))
    }
  }
}

/// Create or update a file in a repository
pub async fn create_or_update_file(
  owner: &str,
  repo: &str,
  path: &str,
  content: &str,
  message: &str,
  token: &str,
) -> Result<(), GitHubError> {
  use base64::{Engine as _, engine::general_purpose::STANDARD};
  
  let url = format!("{}/repos/{}/{}/contents/{}", GITHUB_API_URL, owner, repo, path);
  let encoded_content = STANDARD.encode(content);

  let request = CreateFileRequest {
    message: message.to_string(),
    content: encoded_content,
    branch: None,
  };

  let client = reqwest::Client::new();
  let response = client
    .put(&url)
    .header(header::USER_AGENT, "nbi/0.1.0")
    .header(header::AUTHORIZATION, format!("Bearer {}", token))
    .header(header::ACCEPT, "application/vnd.github+json")
    .json(&request)
    .send()
    .await?;

  match response.status() {
    StatusCode::CREATED | StatusCode::OK => Ok(()),
    StatusCode::UNAUTHORIZED => Err(GitHubError::AuthRequired),
    StatusCode::UNPROCESSABLE_ENTITY => {
      let body = response.text().await.unwrap_or_default();
      Err(GitHubError::ApiError(format!("File operation failed: {}", body)))
    }
    _ => {
      let body = response.text().await.unwrap_or_default();
      Err(GitHubError::ApiError(body))
    }
  }
}

/// Create a repository with manifest file for the specified registry
pub async fn create_repo_with_manifest(
  name: &str,
  manifest_type: ManifestType,
  token: &str,
) -> Result<RepoResponse, GitHubError> {
  let description = format!("Reserved package name for {}", manifest_type.filename());
  
  // First create the repo
  let repo = create_repo(name, Some(&description), false, token).await?;
  
  // Get username for the owner
  let username = get_username(token).await?;
  
  // Wait a moment for GitHub to initialize the repo
  tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
  
  // Add manifest file
  let manifest_content = manifest_type.generate_content(name, &description);
  create_or_update_file(
    &username,
    name,
    manifest_type.filename(),
    &manifest_content,
    &format!("Add {} for package reservation", manifest_type.filename()),
    token,
  ).await?;
  
  Ok(repo)
}

/// Add manifest to existing repository if it doesn't exist
pub async fn add_manifest_if_missing(
  owner: &str,
  repo: &str,
  manifest_type: ManifestType,
  token: &str,
) -> Result<bool, GitHubError> {
  let filename = manifest_type.filename();
  
  // Check if file already exists
  if check_file_exists(owner, repo, filename, token).await?.is_some() {
    return Ok(false); // File already exists
  }
  
  // Create the manifest file
  let description = format!("Reserved package name for {}", filename);
  let content = manifest_type.generate_content(repo, &description);
  
  create_or_update_file(
    owner,
    repo,
    filename,
    &content,
    &format!("Add {} for package reservation", filename),
    token,
  ).await?;
  
  Ok(true) // File was created
}