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
//! Implementation of the `gor gist` subcommand.
//!
//! Provides gist listing and creation commands.

#![allow(clippy::print_stdout)]

use crate::cli::GistCommand;
use crate::client::Client;
use crate::output::print_json;
use anyhow::Context;
use std::fs;

/// Run the `gor gist` subcommand.
///
/// # Errors
///
/// Returns an error if the command execution fails.
pub fn run(cmd: GistCommand) -> anyhow::Result<()> {
    match cmd {
        GistCommand::List {
            public,
            secret,
            user,
            limit,
            json,
            hostname,
        } => list(
            public,
            secret,
            user.as_deref(),
            limit,
            json,
            hostname.as_deref(),
        ),
        GistCommand::Create {
            files,
            desc,
            public,
            filename,
            web,
            hostname,
        } => create(
            &files,
            desc.as_deref(),
            public,
            filename.as_deref(),
            web,
            hostname.as_deref(),
        ),
        GistCommand::View {
            gist_id,
            raw,
            filename,
            web,
            json,
            hostname,
        } => view(
            &gist_id,
            raw,
            filename.as_deref(),
            web,
            json,
            hostname.as_deref(),
        ),
        GistCommand::Edit {
            gist_id,
            desc,
            add,
            filename,
            hostname,
        } => edit(
            &gist_id,
            desc.as_deref(),
            &add,
            filename.as_deref(),
            hostname.as_deref(),
        ),
        GistCommand::Delete { gist_id, hostname } => delete(&gist_id, hostname.as_deref()),
    }
}

/// Execute `gor gist list`.
///
/// Lists gists for the authenticated user or a specific user.
///
/// # Errors
///
/// Returns an error if the API request fails.
fn list(
    public: bool,
    secret: bool,
    user: Option<&str>,
    limit: u32,
    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 = user.map_or_else(
        || format!("/gists?per_page={}", limit.min(100)),
        |u| format!("/users/{u}/gists?per_page={}", limit.min(100)),
    );

    let response = client.get(&path).context("failed to fetch gists")?;

    let status = response.status();
    if !status.is_success() {
        anyhow::bail!("failed to list gists: HTTP {status}");
    }

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

    // Filter by visibility
    gists.retain(|g| {
        let is_public = g["public"].as_bool().unwrap_or(false);
        if public && !secret {
            is_public
        } else if secret && !public {
            !is_public
        } else {
            true
        }
    });

    gists.truncate(limit as usize);

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

    print_gist_table(&gists);
    Ok(())
}

/// Execute `gor gist create`.
///
/// Creates a new gist from one or more files.
///
/// # Errors
///
/// Returns an error if the file cannot be read or the API request fails.
fn create(
    files: &[String],
    desc: Option<&str>,
    public: bool,
    filename: Option<&str>,
    web: bool,
    hostname: Option<&str>,
) -> anyhow::Result<()> {
    if files.is_empty() {
        anyhow::bail!("no files specified for gist creation");
    }

    let host = hostname.unwrap_or("github.com");
    let client = Client::new(host).context("failed to create HTTP client")?;

    let mut files_map = serde_json::Map::new();
    for (i, file) in files.iter().enumerate() {
        let content =
            fs::read_to_string(file).with_context(|| format!("failed to read file: {file}"))?;
        let gist_filename = if files.len() == 1 {
            filename.unwrap_or(file).to_string()
        } else {
            file.clone()
        };
        let file_entry = serde_json::json!({ "content": content });
        files_map.insert(gist_filename, file_entry);
        if files.len() > 1 && i == 0 {
            // Only the first file gets the custom filename
        }
    }

    let mut body_map = serde_json::Map::new();
    body_map.insert("public".to_string(), serde_json::Value::Bool(public));
    body_map.insert("files".to_string(), serde_json::Value::Object(files_map));
    if let Some(d) = desc {
        body_map.insert(
            "description".to_string(),
            serde_json::Value::String(d.to_string()),
        );
    }

    let body_value = serde_json::Value::Object(body_map);
    let response = client
        .post("/gists", &body_value)
        .context("failed to create gist")?;

    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("creation failed");
        anyhow::bail!("failed to create gist: {msg}");
    }

    let gist: serde_json::Value = response.json().context("failed to parse gist response")?;
    let gist_url = gist["html_url"].as_str().unwrap_or("");

    if web && !gist_url.is_empty() {
        open_in_browser(gist_url);
    }

    println!("{gist_url}");
    Ok(())
}

/// Execute `gor gist view`.
///
/// Views a gist's content and metadata.
///
/// # Errors
///
/// Returns an error if the API request fails.
fn view(
    gist_id: &str,
    raw: bool,
    filename: Option<&str>,
    web: bool,
    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!("/gists/{gist_id}");
    let response = client.get(&path).context("failed to fetch gist")?;

    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("view failed");
        anyhow::bail!("failed to view gist: {msg}");
    }

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

    // --web / -w: open in browser
    if web {
        if let Some(url) = gist["html_url"].as_str() {
            open_in_browser(url);
            return Ok(());
        }
    }

    // --raw: output raw content of a specific file
    if raw {
        let files = gist["files"]
            .as_object()
            .ok_or_else(|| anyhow::anyhow!("gist has no files"))?;

        let selected = if let Some(name) = filename {
            files
                .get(name)
                .ok_or_else(|| anyhow::anyhow!("file '{name}' not found in gist"))?
        } else {
            files
                .values()
                .next()
                .ok_or_else(|| anyhow::anyhow!("gist has no files"))?
        };

        let content = selected["content"].as_str().unwrap_or("");
        print!("{content}");
        return Ok(());
    }

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

    // Default: print description and files
    let description = gist["description"].as_str().unwrap_or("No description");
    println!("Description: {description}");
    println!("Files:");

    let files = gist["files"]
        .as_object()
        .ok_or_else(|| anyhow::anyhow!("gist has no files"))?;
    for (name, file_info) in files {
        let language = file_info["language"].as_str().unwrap_or("Unknown");
        let content = file_info["content"].as_str().unwrap_or("");
        println!("\n  {name} ({language}):");
        for line in content.lines() {
            println!("    {line}");
        }
    }

    Ok(())
}

/// Execute `gor gist edit`.
///
/// Edits an existing gist by updating its description, adding files, or renaming files.
///
/// # Errors
///
/// Returns an error if the API request fails.
fn edit(
    gist_id: &str,
    desc: Option<&str>,
    add: &[String],
    filename: 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();

    if let Some(d) = desc {
        body_map.insert(
            "description".to_string(),
            serde_json::Value::String(d.to_string()),
        );
    }

    // Handle --add: add files from file paths or inline content
    if !add.is_empty() {
        let mut files_map = serde_json::Map::new();
        for entry in add {
            if let Some((key, value)) = entry.split_once('=') {
                // If the value looks like a file path, read it
                let content = fs::read_to_string(value).unwrap_or_else(|_| value.to_string());
                files_map.insert(key.to_string(), serde_json::json!({"content": content}));
            } else {
                let content = fs::read_to_string(entry)
                    .with_context(|| format!("failed to read file: {entry}"))?;
                files_map.insert(entry.clone(), serde_json::json!({"content": content}));
            }
        }
        body_map.insert("files".to_string(), serde_json::Value::Object(files_map));
    }

    // Handle --filename: rename a file (old:new)
    if let Some(fn_rename) = filename {
        if let Some((old_name, new_name)) = fn_rename.split_once(':') {
            let mut files_map = serde_json::Map::new();
            let mut new_file_map = serde_json::Map::new();
            new_file_map.insert(
                "filename".to_string(),
                serde_json::Value::String(new_name.to_string()),
            );
            files_map.insert(
                old_name.to_string(),
                serde_json::Value::Object(new_file_map),
            );
            body_map.insert("files".to_string(), serde_json::Value::Object(files_map));
        } else {
            anyhow::bail!("invalid rename format: '{fn_rename}' (expected old:new)");
        }
    }

    let body_value = serde_json::Value::Object(body_map);
    let body_bytes = serde_json::to_vec(&body_value).context("failed to serialize body")?;
    let path = format!("/gists/{gist_id}");
    let response = client
        .request("PATCH", &path, &[], Some(body_bytes))
        .context("failed to edit gist")?;

    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("edit failed");
        anyhow::bail!("failed to edit gist: {msg}");
    }

    let gist: serde_json::Value = response.json().context("failed to parse gist response")?;
    let gist_url = gist["html_url"].as_str().unwrap_or("");
    println!("{gist_url}");
    Ok(())
}

/// Execute `gor gist delete`.
///
/// Deletes a gist by ID.
///
/// # Errors
///
/// Returns an error if the API request fails.
fn delete(gist_id: &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 path = format!("/gists/{gist_id}");
    let response = client
        .request("DELETE", &path, &[], None)
        .context("failed to delete gist")?;

    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("delete failed");
        anyhow::bail!("failed to delete gist: {msg}");
    }

    println!("Gist '{gist_id}' deleted.");
    Ok(())
}

/// Print a formatted gist list table.
fn print_gist_table(gists: &[serde_json::Value]) {
    if gists.is_empty() {
        println!("No gists found.");
        return;
    }

    let id_width = 16;
    let desc_width = 40;
    let files_width = 8;
    let date_width = 16;

    println!(
        "{:<id_width$}  {:<desc_width$}  {:>files_width$}  {:>date_width$}",
        "ID", "DESCRIPTION", "FILES", "UPDATED",
    );

    for gist in gists {
        let gist_id = gist["id"].as_str().unwrap_or("");
        let description = gist["description"].as_str().unwrap_or("");
        let file_count = gist["files"].as_object().map_or(0, serde_json::Map::len);
        let updated = gist["updated_at"]
            .as_str()
            .map_or_else(|| "".to_string(), crate::output::format_date);

        let desc_truncated = crate::cmd::util::truncate(description, desc_width);

        println!(
            "{gist_id:<id_width$}  {desc_truncated:<desc_width$}  {file_count:>files_width$}  {updated:>date_width$}",
        );
    }
}

/// Open a URL in the default browser.
fn open_in_browser(url: &str) {
    #[cfg(target_os = "linux")]
    {
        let _ = std::process::Command::new("xdg-open").arg(url).spawn();
    }
    #[cfg(target_os = "macos")]
    {
        let _ = std::process::Command::new("open").arg(url).spawn();
    }
    #[cfg(target_os = "windows")]
    {
        let _ = std::process::Command::new("cmd")
            .args(["/c", "start", url])
            .spawn();
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        println!("Open {url} in your browser");
    }
}

#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn print_gist_table_basic() {
        let gists = vec![json!({
            "id": "abc123",
            "description": "My first gist",
            "files": { "hello.py": { "filename": "hello.py" } },
            "updated_at": "2024-01-15T10:30:00Z",
            "public": false
        })];
        print_gist_table(&gists);
    }

    #[test]
    fn print_gist_table_empty() {
        let gists: Vec<serde_json::Value> = vec![];
        print_gist_table(&gists);
    }

    #[test]
    fn print_gist_table_multiple() {
        let gists = vec![
            json!({
                "id": "abc123",
                "description": "My first gist",
                "files": { "hello.py": {} },
                "updated_at": "2024-01-15T10:30:00Z",
                "public": true
            }),
            json!({
                "id": "def456",
                "description": null,
                "files": { "a.rs": {}, "b.rs": {}, "c.rs": {} },
                "updated_at": "2024-03-01T00:00:00Z",
                "public": false
            }),
        ];
        print_gist_table(&gists);
    }

    #[test]
    fn open_in_browser_does_not_panic() {
        open_in_browser("https://gist.github.com/abc123");
    }
}