ghr-cli 0.7.8

A fast terminal dashboard for GitHub pull requests, issues, and notifications.
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
use std::io;
use std::path::{Path, PathBuf};
use std::process::Command;

use tokio::process::Command as TokioCommand;
use tracing::{debug, error};

use super::text::truncate_text;
use crate::config::{Config, github_repo_from_remote_url};
use crate::model::{PullRequestBranch, WorkItem};

#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct PrCheckoutResult {
    pub(super) command: String,
    pub(super) directory: PathBuf,
    pub(super) output: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct PrCheckoutPlan {
    pub(super) directory: PathBuf,
    pub(super) branch: Option<PullRequestBranch>,
}

pub(super) async fn run_pr_checkout(
    item: WorkItem,
    directory: PathBuf,
) -> std::result::Result<PrCheckoutResult, String> {
    let number = item
        .number
        .ok_or_else(|| "selected item has no pull request number".to_string())?;
    let args = pr_checkout_command_args(&item.repo, number);
    let command = pr_checkout_command_display(&args);
    debug!(
        command = %command,
        cwd = %directory.display(),
        "gh request started"
    );
    let output = TokioCommand::new("gh")
        .env("GH_PROMPT_DISABLED", "1")
        .current_dir(&directory)
        .args(&args)
        .output()
        .await
        .map_err(|error| {
            debug!(
                command = %command,
                cwd = %directory.display(),
                error = %error,
                "gh request failed to start"
            );
            error!(
                command = %command,
                cwd = %directory.display(),
                error = %error,
                "gh request failed to start"
            );
            if error.kind() == io::ErrorKind::NotFound {
                format!(
                    "GitHub CLI `gh` is required for local checkout. Install it, run `gh auth login`, then retry.\n\n{}\n\nTried: {command}",
                    checkout_directory_notice(&directory),
                )
            } else {
                format!(
                    "failed to run {command}: {error}\n\n{}",
                    checkout_directory_notice(&directory),
                )
            }
        })?;
    debug!(
        command = %command,
        cwd = %directory.display(),
        status = %output.status,
        success = output.status.success(),
        stdout_bytes = output.stdout.len(),
        stderr_bytes = output.stderr.len(),
        "gh request finished"
    );

    let output_text = command_output_text(&output.stdout, &output.stderr);
    if !output.status.success() {
        let detail = if output_text.is_empty() {
            "gh did not return any output".to_string()
        } else {
            output_text
        };
        error!(
            command = %command,
            cwd = %directory.display(),
            status = %output.status,
            message = %truncate_text(&detail, 900),
            stdout_bytes = output.stdout.len(),
            stderr_bytes = output.stderr.len(),
            "gh request returned failure"
        );
        return Err(format!(
            "{} failed.\n\n{}\n\n{}",
            command,
            checkout_directory_notice(&directory),
            truncate_text(&detail, 900),
        ));
    }

    let output = if output_text.is_empty() {
        "gh pr checkout completed successfully.".to_string()
    } else {
        truncate_text(&output_text, 900)
    };
    Ok(PrCheckoutResult {
        command,
        directory,
        output,
    })
}

pub(super) fn pr_checkout_command_args(repository: &str, number: u64) -> Vec<String> {
    vec![
        "pr".to_string(),
        "checkout".to_string(),
        number.to_string(),
        "--repo".to_string(),
        repository.to_string(),
    ]
}

pub(super) fn pr_checkout_command_display(args: &[String]) -> String {
    format!("gh {}", args.join(" "))
}

pub(super) fn command_output_text(stdout: &[u8], stderr: &[u8]) -> String {
    let stdout = String::from_utf8_lossy(stdout).trim().to_string();
    let stderr = String::from_utf8_lossy(stderr).trim().to_string();
    match (stdout.is_empty(), stderr.is_empty()) {
        (true, true) => String::new(),
        (false, true) => stdout,
        (true, false) => stderr,
        (false, false) => format!("{stdout}\n{stderr}"),
    }
}

pub(super) fn checkout_directory_notice(directory: &Path) -> String {
    format!("Checkout runs from {}.", directory.display())
}

pub(super) fn resolve_pr_checkout_directory(
    config: &Config,
    repository: &str,
) -> std::result::Result<PathBuf, String> {
    if let Some(repo) = config
        .repos
        .iter()
        .find(|repo| repo.repo.eq_ignore_ascii_case(repository))
        && let Some(local_dir) = repo.local_dir.as_deref().map(str::trim)
        && !local_dir.is_empty()
    {
        let directory = expand_user_path(local_dir);
        ensure_directory_tracks_configured_repo(&directory, repository, repo.remote.as_deref()).map_err(|error| {
            format!(
                "Configured local_dir for {repository} cannot be used.\n\n{error}\n\nSet [[repos]].local_dir and [[repos]].remote to a checkout remote that points at {repository}."
            )
        })?;
        return Ok(directory);
    }

    let cwd = std::env::current_dir().map_err(|error| {
        format!(
            "Could not inspect the current working directory for {repository}: {error}\n\nSet [[repos]].local_dir for this repository."
        )
    })?;
    ensure_directory_tracks_repo(&cwd, repository).map_err(|error| {
        format!(
            "No local checkout found for {repository}.\n\n{error}\n\nLaunch ghr inside a checkout whose git remote points at {repository}, or set [[repos]].local_dir for this repository."
        )
    })?;
    Ok(cwd)
}

pub(super) fn configured_local_dir_for_repo(config: &Config, repository: &str) -> Option<PathBuf> {
    config
        .repos
        .iter()
        .find(|repo| repo.repo.eq_ignore_ascii_case(repository))
        .and_then(|repo| repo.local_dir.as_deref())
        .map(str::trim)
        .filter(|local_dir| !local_dir.is_empty())
        .map(expand_user_path)
}

fn expand_user_path(value: &str) -> PathBuf {
    if value == "~" {
        return home_dir().unwrap_or_else(|| PathBuf::from(value));
    }
    if let Some(rest) = value.strip_prefix("~/")
        && let Some(home) = home_dir()
    {
        return home.join(rest);
    }
    PathBuf::from(value)
}

fn home_dir() -> Option<PathBuf> {
    std::env::var_os("HOME")
        .filter(|home| !home.is_empty())
        .map(PathBuf::from)
        .or_else(::dirs::home_dir)
}

pub(super) fn ensure_directory_tracks_repo(
    directory: &Path,
    repository: &str,
) -> std::result::Result<(), String> {
    if !directory.is_dir() {
        return Err(format!("{} is not a directory.", directory.display()));
    }
    let remotes = git_remotes_for_directory(directory)?;
    if remotes
        .iter()
        .any(|(_, repo)| repo.eq_ignore_ascii_case(repository))
    {
        return Ok(());
    }

    let remote_list = if remotes.is_empty() {
        "no GitHub remotes found".to_string()
    } else {
        remotes
            .iter()
            .map(|(remote, repo)| format!("{remote} -> {repo}"))
            .collect::<Vec<_>>()
            .join(", ")
    };
    Err(format!(
        "{} does not track {repository}; found {remote_list}.",
        directory.display()
    ))
}

pub(super) fn ensure_directory_tracks_configured_repo(
    directory: &Path,
    repository: &str,
    remote: Option<&str>,
) -> std::result::Result<(), String> {
    let Some(remote) = remote.map(str::trim).filter(|remote| !remote.is_empty()) else {
        return ensure_directory_tracks_repo(directory, repository);
    };
    if !directory.is_dir() {
        return Err(format!("{} is not a directory.", directory.display()));
    }
    match git_remote_repo(directory, remote) {
        Some(repo) if repo.eq_ignore_ascii_case(repository) => Ok(()),
        Some(repo) => Err(format!(
            "{} remote {remote} points at {repo}, expected {repository}.",
            directory.display()
        )),
        None => Err(format!(
            "{} has no GitHub remote named {remote}.",
            directory.display()
        )),
    }
}

pub(super) fn current_git_branch_for_directory(
    directory: &Path,
) -> std::result::Result<String, String> {
    let output = Command::new("git")
        .arg("-C")
        .arg(directory)
        .args(["symbolic-ref", "--quiet", "--short", "HEAD"])
        .output()
        .map_err(|error| {
            format!(
                "failed to inspect current git branch in {}: {error}",
                directory.display()
            )
        })?;
    let branch = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if output.status.success() && !branch.is_empty() {
        return Ok(branch);
    }

    let detail = command_output_text(&output.stdout, &output.stderr);
    let detail = if detail.is_empty() {
        "detached HEAD or no branch is checked out".to_string()
    } else {
        detail
    };
    Err(format!(
        "cannot create PR from {}: {detail}",
        directory.display()
    ))
}

pub(super) fn resolve_pull_request_head_ref(
    directory: &Path,
    repository: &str,
    branch: &str,
) -> String {
    let Some(remote) = current_branch_push_remote(directory)
        .or_else(|| configured_branch_remote(directory, branch, "pushRemote"))
        .or_else(|| git_config_value(directory, "remote.pushDefault"))
        .or_else(|| configured_branch_remote(directory, branch, "remote"))
    else {
        return branch.to_string();
    };

    if remote == "." {
        return branch.to_string();
    }

    let Some(head_repo) = git_remote_repo(directory, &remote) else {
        return branch.to_string();
    };
    pull_request_head_ref(repository, &head_repo, branch)
}

fn pull_request_head_ref(base_repo: &str, head_repo: &str, branch: &str) -> String {
    if head_repo.eq_ignore_ascii_case(base_repo) {
        return branch.to_string();
    }

    head_repo
        .split_once('/')
        .map(|(owner, _)| format!("{owner}:{branch}"))
        .unwrap_or_else(|| branch.to_string())
}

fn current_branch_push_remote(directory: &Path) -> Option<String> {
    let output = Command::new("git")
        .arg("-C")
        .arg(directory)
        .args([
            "rev-parse",
            "--abbrev-ref",
            "--symbolic-full-name",
            "@{push}",
        ])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let push_ref = String::from_utf8(output.stdout).ok()?;
    push_ref
        .trim()
        .split_once('/')
        .map(|(remote, _)| remote.trim().to_string())
        .filter(|remote| !remote.is_empty())
}

fn configured_branch_remote(directory: &Path, branch: &str, key: &str) -> Option<String> {
    git_config_value(directory, &format!("branch.{branch}.{key}"))
}

fn git_config_value(directory: &Path, key: &str) -> Option<String> {
    let output = Command::new("git")
        .arg("-C")
        .arg(directory)
        .args(["config", "--get", key])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    String::from_utf8(output.stdout)
        .ok()
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty())
}

fn git_remotes_for_directory(
    directory: &Path,
) -> std::result::Result<Vec<(String, String)>, String> {
    let output = Command::new("git")
        .arg("-C")
        .arg(directory)
        .arg("remote")
        .output()
        .map_err(|error| {
            format!(
                "failed to run git remote in {}: {error}",
                directory.display()
            )
        })?;
    if !output.status.success() {
        return Err(format!(
            "{} is not a usable git checkout: {}",
            directory.display(),
            command_output_text(&output.stdout, &output.stderr)
        ));
    }

    let mut remotes = Vec::new();
    let names = String::from_utf8_lossy(&output.stdout);
    for remote in names
        .lines()
        .map(str::trim)
        .filter(|remote| !remote.is_empty())
    {
        if let Some(repo) = git_remote_repo(directory, remote) {
            remotes.push((remote.to_string(), repo));
        }
    }
    Ok(remotes)
}

fn git_remote_repo(directory: &Path, remote: &str) -> Option<String> {
    let output = Command::new("git")
        .arg("-C")
        .arg(directory)
        .args(["remote", "get-url", remote])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let url = String::from_utf8(output.stdout).ok()?;
    github_repo_from_remote_url(url.trim())
}