gor-cli 0.1.0

A Rust CLI for GitHub — a 'gh' clone
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
//! Implementation of the `gor codespace` subcommand.
//!
//! Provides codespace listing and creation.

#![allow(clippy::print_stdout, clippy::option_if_let_else)]

use crate::cli::CodespaceCommand;
use crate::client::Client;
use crate::output::print_json;
use anyhow::Context;

/// Run the `gor codespace` subcommand.
///
/// # Errors
///
/// Returns an error if the command execution fails.
pub fn run(cmd: CodespaceCommand) -> anyhow::Result<()> {
    match cmd {
        CodespaceCommand::List {
            repo,
            json,
            hostname,
        } => list(repo.as_deref(), json, hostname.as_deref()),
        CodespaceCommand::Create {
            repo,
            branch,
            machine,
            hostname,
        } => create(
            &repo,
            branch.as_deref(),
            machine.as_deref(),
            hostname.as_deref(),
        ),
        CodespaceCommand::Delete {
            name,
            repo,
            yes,
            hostname,
        } => delete(&name, repo.as_deref(), yes, hostname.as_deref()),
        CodespaceCommand::Logs {
            name,
            repo,
            json,
            follow,
            hostname,
        } => logs(&name, repo.as_deref(), json, follow, hostname.as_deref()),
        CodespaceCommand::Ssh {
            name,
            repo,
            profile,
            config,
            hostname,
        } => ssh(
            &name,
            repo.as_deref(),
            profile.as_deref(),
            config,
            hostname.as_deref(),
        ),
        CodespaceCommand::Stop {
            name,
            repo,
            all,
            hostname,
        } => stop(name.as_deref(), repo.as_deref(), all, hostname.as_deref()),
        CodespaceCommand::Cp {
            name,
            paths,
            recursive,
            hostname,
        } => cp(&name, &paths, recursive, hostname.as_deref()),
        CodespaceCommand::Ports {
            name,
            json,
            hostname,
        } => ports(&name, json, hostname.as_deref()),
        CodespaceCommand::Rebuild {
            name,
            yes,
            hostname,
        } => rebuild(&name, yes, hostname.as_deref()),
    }
}

fn list(
    repo: Option<&str>,
    json: Option<Vec<String>>,
    hostname: Option<&str>,
) -> anyhow::Result<()> {
    let host = hostname.unwrap_or("github.com");
    let client = Client::new(host).context("failed to create HTTP client")?;

    let path = if let Some(r) = repo {
        format!("/user/codespaces?repository_id={r}")
    } else {
        "/user/codespaces".to_string()
    };

    let response = client.get(&path).context("failed to fetch codespaces")?;
    let status = response.status();
    if !status.is_success() {
        anyhow::bail!("failed to list codespaces: HTTP {status}");
    }

    let result: serde_json::Value = response.json().context("failed to parse response")?;
    let spaces: Vec<serde_json::Value> = result["codespaces"]
        .as_array()
        .map_or_else(Vec::new, Clone::clone);

    if let Some(fields) = json {
        let fields_ref: Option<&[String]> = if fields.is_empty() {
            None
        } else {
            Some(&fields)
        };
        print_json(&spaces, fields_ref);
        return Ok(());
    }

    if spaces.is_empty() {
        println!("No codespaces found.");
        return Ok(());
    }

    println!(
        "{:<24}  {:<20}  {:<15}  BRANCH",
        "NAME", "REPOSITORY", "STATE"
    );
    for s in &spaces {
        let name = s["name"].as_str().unwrap_or("");
        let repo_name = s["repository"]["full_name"].as_str().unwrap_or("");
        let state = s["state"].as_str().unwrap_or("");
        let branch = s["git_status"]["branch"].as_str().unwrap_or("");
        let name_truncated = crate::cmd::util::truncate(name, 24);
        let repo_truncated = crate::cmd::util::truncate(repo_name, 20);
        println!("{name_truncated:<24}  {repo_truncated:<20}  {state:<15}  {branch}");
    }

    Ok(())
}

fn delete(name: &str, repo: Option<&str>, yes: bool, hostname: Option<&str>) -> anyhow::Result<()> {
    let host = hostname.unwrap_or("github.com");
    let client = Client::new(host).context("failed to create HTTP client")?;

    if !yes {
        use std::io::Write;
        let prompt = if let Some(r) = repo {
            format!("Are you sure you want to delete codespace '{name}' in repo '{r}'?")
        } else {
            format!("Are you sure you want to delete codespace '{name}'?")
        };
        print!("{prompt} [y/N] ");
        std::io::stdout().flush().ok();

        let mut input = String::new();
        std::io::stdin()
            .read_line(&mut input)
            .context("failed to read input")?;
        let input = input.trim().to_lowercase();
        if input != "y" && input != "yes" {
            println!("Cancelled.");
            return Ok(());
        }
    }

    let path = format!("/user/codespaces/{name}");

    let response = client
        .request("DELETE", &path, &[], None)
        .context("failed to delete codespace")?;

    let status = response.status();
    if !status.is_success() {
        anyhow::bail!("failed to delete codespace '{name}': HTTP {status}");
    }

    println!("Codespace '{name}' deleted.");
    Ok(())
}

fn create(
    repo: &str,
    branch: Option<&str>,
    machine: Option<&str>,
    hostname: Option<&str>,
) -> anyhow::Result<()> {
    let host = hostname.unwrap_or("github.com");
    let client = Client::new(host).context("failed to create HTTP client")?;

    let mut body_map = serde_json::Map::new();
    body_map.insert(
        "repository_id".to_string(),
        serde_json::Value::String(repo.to_string()),
    );

    if let Some(b) = branch {
        body_map.insert("git_status".to_string(), serde_json::json!({"branch": b}));
    }

    if let Some(m) = machine {
        body_map.insert(
            "machine".to_string(),
            serde_json::Value::String(m.to_string()),
        );
    }

    let body_value = serde_json::Value::Object(body_map);
    let body_bytes = serde_json::to_vec(&body_value).context("failed to serialize body")?;

    let response = client
        .request("POST", "/user/codespaces", &[], Some(body_bytes))
        .context("failed to create codespace")?;

    let status = response.status();
    if !status.is_success() {
        let err_body: serde_json::Value = response.json().unwrap_or_default();
        let msg = err_body["message"].as_str().unwrap_or("create failed");
        anyhow::bail!("failed to create codespace: {msg}");
    }

    let result: serde_json::Value = response.json().context("failed to parse response")?;
    let name = result["name"].as_str().unwrap_or("");
    println!("Codespace '{name}' created.");
    Ok(())
}

fn logs(
    name: &str,
    _repo: Option<&str>,
    json: Option<Vec<String>>,
    follow: bool,
    hostname: Option<&str>,
) -> anyhow::Result<()> {
    let host = hostname.unwrap_or("github.com");
    let client = Client::new(host).context("failed to create HTTP client")?;

    let path = format!("/user/codespaces/{name}/logs");

    let response = client
        .get(&path)
        .context("failed to fetch codespace logs")?;
    let status = response.status();
    if !status.is_success() {
        anyhow::bail!("failed to fetch logs for '{name}': HTTP {status}");
    }

    let body = response.text().context("failed to read response")?;

    if let Some(fields) = json {
        let parsed: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
        let fields_ref: Option<&[String]> = if fields.is_empty() {
            None
        } else {
            Some(&fields)
        };
        print_json(&parsed, fields_ref);
        return Ok(());
    }

    if follow {
        println!("Logs for codespace '{name}':");
    }
    println!("{body}");

    if follow {
        tracing::warn!("log following is not yet implemented");
    }

    Ok(())
}

fn ssh(
    name: &str,
    _repo: Option<&str>,
    _profile: Option<&str>,
    config: bool,
    hostname: Option<&str>,
) -> anyhow::Result<()> {
    let host = hostname.unwrap_or("github.com");
    let client = Client::new(host).context("failed to create HTTP client")?;

    let path = format!("/user/codespaces/{name}");

    let response = client
        .get(&path)
        .context("failed to fetch codespace details")?;
    let status = response.status();
    if !status.is_success() {
        anyhow::bail!("failed to fetch codespace '{name}': HTTP {status}");
    }

    let cs: serde_json::Value = response.json().context("failed to parse response")?;
    let state = cs["state"].as_str().unwrap_or("unknown");

    if state != "Available" {
        anyhow::bail!("codespace '{name}' is not available (state: {state})");
    }

    // Fetch SSH connection details
    let ssh_path = format!("/user/codespaces/{name}");
    let ssh_response = client
        .get(&ssh_path)
        .context("failed to fetch SSH details")?;
    let ssh_details: serde_json::Value =
        ssh_response.json().context("failed to parse SSH details")?;

    if config {
        let connection = ssh_details.get("connection").and_then(|c| c.as_object());
        if let Some(conn) = connection {
            println!("Host {name}");
            if let Some(hostname) = conn.get("host").and_then(|v| v.as_str()) {
                println!("  HostName {hostname}");
            }
            if let Some(port) = conn.get("port") {
                println!("  Port {port}");
            }
            if let Some(user) = conn.get("user").and_then(|v| v.as_str()) {
                println!("  User {user}");
            }
        } else {
            println!("# No SSH connection details available for '{name}'");
        }
        return Ok(());
    }

    anyhow::bail!("SSH connection is not yet implemented; use --config to view connection details");
}

/// Copy files between a local machine and a codespace.
///
/// The last path in `paths` is the destination, all others are sources.
/// Use the `remote:` prefix for codespace paths.
///
/// # Errors
///
/// Returns an error if the codespace is not running, the paths are invalid,
/// or the transfer fails.
fn cp(name: &str, paths: &[String], recursive: bool, hostname: Option<&str>) -> anyhow::Result<()> {
    let host = hostname.unwrap_or("github.com");
    let client = Client::new(host).context("failed to create HTTP client")?;

    if paths.len() < 2 {
        anyhow::bail!("at least two paths are required: source and destination");
    }

    let dest = paths
        .last()
        .ok_or_else(|| anyhow::anyhow!("paths is empty"))?;
    let sources = &paths[..paths.len() - 1];

    let dest_is_remote = dest.starts_with("remote:");
    let any_source_remote = sources.iter().any(|p| p.starts_with("remote:"));

    if dest_is_remote && any_source_remote {
        anyhow::bail!("copying between two remote paths is not supported");
    }

    // Fetch codespace details to verify it's running and get connection info.
    let cs_path = format!("/user/codespaces/{name}");
    let response = client
        .get(&cs_path)
        .context("failed to fetch codespace details")?;
    let status = response.status();
    if !status.is_success() {
        anyhow::bail!("failed to fetch codespace '{name}': HTTP {status}");
    }

    let cs: serde_json::Value = response
        .json()
        .context("failed to parse codespace response")?;
    let state = cs["state"].as_str().unwrap_or("unknown");

    if state != "Available" {
        anyhow::bail!(
            "codespace '{name}' is not available (state: {state}). Start the codespace first."
        );
    }

    if dest_is_remote {
        // Upload: local → remote via SCP
        let connection = cs["connection"]
            .as_object()
            .ok_or_else(|| anyhow::anyhow!("no SSH connection details available for '{name}'"))?;

        let ssh_host = connection["host"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("missing SSH host"))?;
        let ssh_port = connection["port"]
            .as_u64()
            .ok_or_else(|| anyhow::anyhow!("missing SSH port"))?;
        let ssh_user = connection["user"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("missing SSH user"))?;

        let remote_path = dest
            .strip_prefix("remote:")
            .ok_or_else(|| anyhow::anyhow!("invalid remote path"))?;

        for source in sources {
            if source.starts_with("remote:") {
                anyhow::bail!("cannot mix remote sources with remote destination");
            }

            tracing::info!("Uploading {source} to {name}:{remote_path}...");

            let mut cmd = std::process::Command::new("scp");
            cmd.arg("-P")
                .arg(ssh_port.to_string())
                .arg("-o")
                .arg("LogLevel=ERROR");
            if recursive {
                cmd.arg("-r");
            }
            cmd.arg(source);
            cmd.arg(format!("{ssh_user}@{ssh_host}:{remote_path}"));

            let output = cmd
                .output()
                .context("failed to run scp; is it installed?")?;

            if !output.status.success() {
                let stderr = String::from_utf8_lossy(&output.stderr);
                anyhow::bail!("scp failed for '{source}': {stderr}");
            }

            tracing::info!("✓ Uploaded {source}");
        }
    } else if any_source_remote {
        // Download: remote → local via export API
        for source in sources {
            let remote_path = source
                .strip_prefix("remote:")
                .ok_or_else(|| anyhow::anyhow!("invalid remote path: {source}"))?;

            tracing::info!("Downloading {remote_path} from {name}...");

            // Start an export operation
            let export_body = serde_json::json!({"path": remote_path});
            let export_response = client
                .post(&format!("/user/codespaces/{name}/exports"), &export_body)
                .context("failed to start export")?;

            if !export_response.status().is_success() {
                let err_body: serde_json::Value = export_response.json().unwrap_or_default();
                let msg = err_body["message"].as_str().unwrap_or("export failed");
                anyhow::bail!("failed to export '{remote_path}': {msg}");
            }

            let export_result: serde_json::Value = export_response
                .json()
                .context("failed to parse export response")?;

            // The export API returns a download URL in the `url` field
            let download_url = export_result["url"]
                .as_str()
                .ok_or_else(|| anyhow::anyhow!("no download URL in export response"))?;

            // Download the file
            let file_response = client
                .get_absolute(download_url)
                .context("failed to download exported file")?;

            if !file_response.status().is_success() {
                anyhow::bail!("failed to download file: HTTP {}", file_response.status());
            }

            let bytes = file_response
                .bytes()
                .context("failed to read downloaded file")?;

            // Determine local path: if dest is a directory, use the filename
            let local_path = if dest.ends_with('/') || dest.ends_with(std::path::MAIN_SEPARATOR_STR)
            {
                let filename = std::path::Path::new(remote_path)
                    .file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or("file");
                std::path::Path::new(dest).join(filename)
            } else {
                std::path::PathBuf::from(dest)
            };

            if let Some(parent) = local_path.parent() {
                std::fs::create_dir_all(parent).context("failed to create parent directory")?;
            }

            std::fs::write(&local_path, &bytes).context("failed to write file")?;

            tracing::info!("✓ Downloaded to {}", local_path.display());
        }
    } else {
        // Local to local copy — not supported by this command
        anyhow::bail!(
            "at least one path must use the 'remote:' prefix to specify a codespace path"
        );
    }

    Ok(())
}

/// List forwarded ports for a codespace.
///
/// # Errors
///
/// Returns an error if the codespace is not running or the API request fails.
fn ports(name: &str, json: Option<Vec<String>>, hostname: Option<&str>) -> anyhow::Result<()> {
    let host = hostname.unwrap_or("github.com");
    let client = Client::new(host).context("failed to create HTTP client")?;

    let path = format!("/user/codespaces/{name}/ports");
    let response = client
        .get(&path)
        .context("failed to fetch codespace ports")?;
    let status = response.status();
    if !status.is_success() {
        anyhow::bail!("failed to fetch ports for '{name}': HTTP {status}");
    }

    let ports: Vec<serde_json::Value> =
        response.json().context("failed to parse ports response")?;

    if let Some(fields) = json {
        let fields_ref: Option<&[String]> = if fields.is_empty() {
            None
        } else {
            Some(&fields)
        };
        print_json(&ports, fields_ref);
        return Ok(());
    }

    if ports.is_empty() {
        println!("No forwarded ports for codespace '{name}'.");
        return Ok(());
    }

    println!("{:<24}  {:<12}  {:<12}", "LABEL", "PORT", "VISIBILITY");
    for p in &ports {
        let label = p["label"].as_str().unwrap_or("");
        let source_port = p["source_port"]
            .as_u64()
            .map_or_else(|| "".to_string(), |v| v.to_string());
        let visibility = p["visibility"].as_str().unwrap_or("");
        let label_truncated = crate::cmd::util::truncate(label, 24);
        println!("{label_truncated:<24}  {source_port:<12}  {visibility:<12}");
    }

    Ok(())
}

/// Rebuild a codespace from its devcontainer configuration.
///
/// # Errors
///
/// Returns an error if the codespace is not running, the user cancels,
/// or the API request fails.
fn rebuild(name: &str, yes: bool, hostname: Option<&str>) -> anyhow::Result<()> {
    let host = hostname.unwrap_or("github.com");
    let client = Client::new(host).context("failed to create HTTP client")?;

    if !yes {
        use std::io::Write;
        print!("Are you sure you want to rebuild codespace '{name}'? [y/N] ");
        std::io::stdout().flush().ok();

        let mut input = String::new();
        std::io::stdin()
            .read_line(&mut input)
            .context("failed to read input")?;
        let input = input.trim().to_lowercase();
        if input != "y" && input != "yes" {
            println!("Cancelled.");
            return Ok(());
        }
    }

    let path = format!("/user/codespaces/{name}/rebuild");
    let response = client
        .request("POST", &path, &[], None)
        .context("failed to trigger rebuild")?;

    let status = response.status();
    if !status.is_success() {
        let err_body: serde_json::Value = response.json().unwrap_or_default();
        let msg = err_body["message"].as_str().unwrap_or("rebuild failed");
        anyhow::bail!("failed to rebuild codespace '{name}': {msg}");
    }

    println!("Codespace '{name}' rebuild started.");
    Ok(())
}

fn stop(
    name: Option<&str>,
    _repo: Option<&str>,
    all: bool,
    hostname: Option<&str>,
) -> anyhow::Result<()> {
    let host = hostname.unwrap_or("github.com");
    let client = Client::new(host).context("failed to create HTTP client")?;

    if all {
        // List all codespaces and stop each one
        let response = client
            .get("/user/codespaces")
            .context("failed to list codespaces")?;
        let result: serde_json::Value = response.json().context("failed to parse response")?;
        let spaces: Vec<serde_json::Value> = result["codespaces"]
            .as_array()
            .map_or_else(Vec::new, Clone::clone);

        let mut stopped = 0u32;
        for s in &spaces {
            let cs_name = s["name"].as_str().unwrap_or("");
            let cs_state = s["state"].as_str().unwrap_or("");
            if cs_state == "Shutdown" || cs_state == "Deleted" {
                continue;
            }
            let stop_path = format!("/user/codespaces/{cs_name}/stop");
            let resp = client
                .request("POST", &stop_path, &[], None)
                .context("failed to stop codespace")?;
            if resp.status().is_success() {
                stopped += 1;
            }
        }
        println!("Stopped {stopped} codespace(s).");
        return Ok(());
    }

    let cs_name = name.ok_or_else(|| anyhow::anyhow!("codespace name is required"))?;
    let path = format!("/user/codespaces/{cs_name}/stop");

    let response = client
        .request("POST", &path, &[], None)
        .context("failed to stop codespace")?;

    let status = response.status();
    if !status.is_success() {
        anyhow::bail!("failed to stop codespace '{cs_name}': HTTP {status}");
    }

    println!("Codespace '{cs_name}' stopped.");
    Ok(())
}