travelagent 1.11.1

Agent-first TUI code review tool
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
use std::collections::HashMap;

use travelagent_core::error::TrvError;
use travelagent_core::forge::{ForgeType, PrId};

#[derive(Debug)]
pub enum ForgeTarget {
    /// PR specified by number -- need to detect forge from git remote
    ByNumber(u64),
    /// PR specified by full URL
    ByUrl {
        forge_type: ForgeType,
        pr_id: PrId,
        /// Custom host for self-hosted forges (None for github.com/gitlab.com)
        host: Option<String>,
    },
}

/// Parse the CLI pr argument into a ForgeTarget
pub fn parse_pr_arg(
    arg: &str,
    forge_hosts: Option<&HashMap<String, String>>,
) -> Result<ForgeTarget, TrvError> {
    // Try as number first
    if let Ok(num) = arg.parse::<u64>() {
        return Ok(ForgeTarget::ByNumber(num));
    }

    // Try as a forge URL (GitLab merge_requests pattern, then GitHub pull pattern)
    if let Some(target) = parse_forge_url(arg, forge_hosts) {
        return Ok(target);
    }

    Err(TrvError::ForgeApi(format!(
        "Cannot parse '{arg}' as a PR number or URL"
    )))
}

/// Parse a forge URL generically. Tries GitLab `/-/merge_requests/N` first,
/// then GitHub `/pull/N`, using `forge_hosts` config or heuristic to confirm.
fn parse_forge_url(
    url: &str,
    forge_hosts: Option<&HashMap<String, String>>,
) -> Option<ForgeTarget> {
    let without_scheme = url
        .strip_prefix("https://")
        .or_else(|| url.strip_prefix("http://"))?;
    let first_slash = without_scheme.find('/')?;
    let host = &without_scheme[..first_slash];
    let path = &without_scheme[first_slash + 1..];

    // Try GitLab pattern: GROUP/REPO/-/merge_requests/NUMBER
    if let Some(mr_idx) = path.find("/-/merge_requests/") {
        let path_before = &path[..mr_idx];
        let number_str = &path[mr_idx + "/-/merge_requests/".len()..];
        let number: u64 = number_str.split('/').next()?.parse().ok()?;
        let segments: Vec<&str> = path_before.split('/').collect();
        if segments.len() < 2 {
            return None;
        }
        let repo = segments.last()?.to_string();
        let owner = segments[..segments.len() - 1].join("/");
        let custom_host = if host == "gitlab.com" {
            None
        } else {
            Some(host.to_string())
        };
        return Some(ForgeTarget::ByUrl {
            forge_type: ForgeType::GitLab,
            pr_id: PrId {
                owner,
                repo,
                number,
            },
            host: custom_host,
        });
    }

    // Try GitHub pattern: OWNER/REPO/pull/NUMBER
    let parts: Vec<&str> = path.split('/').collect();
    if parts.len() >= 4 && parts[2] == "pull" {
        let number: u64 = parts[3].parse().ok()?;
        // Verify host is actually GitHub (via config map or heuristic)
        let forge_type = detect_forge_type(host, forge_hosts);
        if forge_type != ForgeType::GitHub {
            return None;
        }
        let custom_host = if host == "github.com" {
            None
        } else {
            Some(host.to_string())
        };
        return Some(ForgeTarget::ByUrl {
            forge_type: ForgeType::GitHub,
            pr_id: PrId {
                owner: parts[0].to_string(),
                repo: parts[1].to_string(),
                number,
            },
            host: custom_host,
        });
    }

    None
}

/// Detect forge type and owner/repo from the current git remote.
///
/// Returns (forge_type, owner, repo, optional_custom_host).
pub fn detect_forge_from_remote(
    forge_hosts: Option<&HashMap<String, String>>,
) -> Result<(ForgeType, String, String, Option<String>), TrvError> {
    let output = std::process::Command::new("git")
        .args(["remote", "get-url", "origin"])
        .output()
        .map_err(|e| TrvError::ForgeApi(format!("Failed to run git: {e}")))?;

    if !output.status.success() {
        return Err(TrvError::ForgeApi(
            "No git remote 'origin' found. Run from a git repository or specify a PR URL."
                .to_string(),
        ));
    }

    let url = String::from_utf8_lossy(&output.stdout).trim().to_string();
    parse_remote_url(&url, forge_hosts)
}

/// Parse a git remote URL into (forge_type, owner, repo, optional_custom_host).
pub fn parse_remote_url(
    url: &str,
    forge_hosts: Option<&HashMap<String, String>>,
) -> Result<(ForgeType, String, String, Option<String>), TrvError> {
    // SSH: git@github.com:owner/repo.git
    if let Some(rest) = url.strip_prefix("git@") {
        let colon_idx = rest
            .find(':')
            .ok_or_else(|| TrvError::ForgeApi("Invalid SSH URL format".to_string()))?;
        let host = &rest[..colon_idx];
        let path = rest[colon_idx + 1..].trim_end_matches(".git");
        let (owner, repo) = split_owner_repo(path)?;
        let forge_type = detect_forge_type(host, forge_hosts);
        let custom_host = if host != "github.com" && host != "gitlab.com" {
            Some(host.to_string())
        } else {
            None
        };
        return Ok((forge_type, owner, repo, custom_host));
    }

    // HTTPS: https://github.com/owner/repo.git
    if url.starts_with("https://") || url.starts_with("http://") {
        let without_scheme = url
            .split("://")
            .nth(1)
            .ok_or_else(|| TrvError::ForgeApi("Invalid URL format".to_string()))?;
        let slash_idx = without_scheme
            .find('/')
            .ok_or_else(|| TrvError::ForgeApi("Invalid URL format: no path".to_string()))?;
        let host = &without_scheme[..slash_idx];
        let path = without_scheme[slash_idx + 1..].trim_end_matches(".git");
        let (owner, repo) = split_owner_repo(path)?;
        let forge_type = detect_forge_type(host, forge_hosts);
        let custom_host = if host != "github.com" && host != "gitlab.com" {
            Some(host.to_string())
        } else {
            None
        };
        return Ok((forge_type, owner, repo, custom_host));
    }

    Err(TrvError::ForgeApi(format!(
        "Cannot parse remote URL: {url}"
    )))
}

fn split_owner_repo(path: &str) -> Result<(String, String), TrvError> {
    let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
    if segments.len() < 2 {
        return Err(TrvError::ForgeApi(format!(
            "Cannot parse owner/repo from: {path}"
        )));
    }
    let repo = segments
        .last()
        .expect("segments.len() >= 2 checked above")
        .to_string();
    let owner = segments[..segments.len() - 1].join("/");
    Ok((owner, repo))
}

fn detect_forge_type(host: &str, forge_hosts: Option<&HashMap<String, String>>) -> ForgeType {
    // Check config map first
    if let Some(map) = forge_hosts
        && let Some(forge_str) = map.get(host)
    {
        return match forge_str.as_str() {
            "github" => ForgeType::GitHub,
            _ => ForgeType::GitLab,
        };
    }
    // Fall back to heuristic
    if host == "github.com" || host.contains("github") {
        ForgeType::GitHub
    } else {
        // Default to GitLab for self-hosted (most common case)
        ForgeType::GitLab
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // --- parse_pr_arg tests ---

    #[test]
    fn parse_pr_arg_number() {
        let target = parse_pr_arg("123", None).unwrap();
        match target {
            ForgeTarget::ByNumber(n) => assert_eq!(n, 123),
            _ => panic!("Expected ByNumber"),
        }
    }

    #[test]
    fn parse_pr_arg_github_url() {
        let target = parse_pr_arg("https://github.com/octocat/hello-world/pull/42", None).unwrap();
        match target {
            ForgeTarget::ByUrl {
                forge_type,
                pr_id,
                host,
            } => {
                assert_eq!(forge_type, ForgeType::GitHub);
                assert_eq!(pr_id.owner, "octocat");
                assert_eq!(pr_id.repo, "hello-world");
                assert_eq!(pr_id.number, 42);
                assert!(host.is_none());
            }
            _ => panic!("Expected ByUrl"),
        }
    }

    #[test]
    fn parse_pr_arg_gitlab_url() {
        let target =
            parse_pr_arg("https://gitlab.com/group/repo/-/merge_requests/99", None).unwrap();
        match target {
            ForgeTarget::ByUrl {
                forge_type,
                pr_id,
                host,
            } => {
                assert_eq!(forge_type, ForgeType::GitLab);
                assert_eq!(pr_id.owner, "group");
                assert_eq!(pr_id.repo, "repo");
                assert_eq!(pr_id.number, 99);
                assert!(host.is_none());
            }
            _ => panic!("Expected ByUrl"),
        }
    }

    #[test]
    fn parse_pr_arg_invalid() {
        let result = parse_pr_arg("not-a-url-or-number", None);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Cannot parse"));
    }

    // --- GitHub URL parsing ---

    #[test]
    fn parse_github_url_basic() {
        let target = parse_forge_url("https://github.com/owner/repo/pull/1", None).unwrap();
        match target {
            ForgeTarget::ByUrl { pr_id, .. } => {
                assert_eq!(pr_id.owner, "owner");
                assert_eq!(pr_id.repo, "repo");
                assert_eq!(pr_id.number, 1);
            }
            _ => panic!("Expected ByUrl"),
        }
    }

    #[test]
    fn parse_github_url_with_trailing_path() {
        let target = parse_forge_url("https://github.com/owner/repo/pull/42/files", None).unwrap();
        match target {
            ForgeTarget::ByUrl { pr_id, .. } => assert_eq!(pr_id.number, 42),
            _ => panic!("Expected ByUrl"),
        }
    }

    #[test]
    fn parse_github_url_not_a_pull() {
        assert!(parse_forge_url("https://github.com/owner/repo/issues/1", None).is_none());
    }

    #[test]
    fn parse_github_url_not_github() {
        // gitlab.com host with /pull/ pattern should not match as GitHub
        assert!(parse_forge_url("https://gitlab.com/owner/repo/pull/1", None).is_none());
    }

    // --- GitLab URL parsing ---

    #[test]
    fn parse_gitlab_url_basic() {
        let target =
            parse_forge_url("https://gitlab.com/group/repo/-/merge_requests/5", None).unwrap();
        match target {
            ForgeTarget::ByUrl {
                forge_type, pr_id, ..
            } => {
                assert_eq!(forge_type, ForgeType::GitLab);
                assert_eq!(pr_id.owner, "group");
                assert_eq!(pr_id.repo, "repo");
                assert_eq!(pr_id.number, 5);
            }
            _ => panic!("Expected ByUrl"),
        }
    }

    #[test]
    fn parse_gitlab_url_nested_groups() {
        let target = parse_forge_url(
            "https://gitlab.acme.com/data/project/repo/-/merge_requests/77",
            None,
        )
        .unwrap();
        match target {
            ForgeTarget::ByUrl { pr_id, host, .. } => {
                assert_eq!(pr_id.owner, "data/project");
                assert_eq!(pr_id.repo, "repo");
                assert_eq!(pr_id.number, 77);
                assert_eq!(host, Some("gitlab.acme.com".to_string()));
            }
            _ => panic!("Expected ByUrl"),
        }
    }

    #[test]
    fn parse_gitlab_url_http() {
        let target = parse_forge_url(
            "http://gitlab.example.com/org/project/-/merge_requests/3",
            None,
        )
        .unwrap();
        match target {
            ForgeTarget::ByUrl { pr_id, .. } => {
                assert_eq!(pr_id.owner, "org");
                assert_eq!(pr_id.repo, "project");
                assert_eq!(pr_id.number, 3);
            }
            _ => panic!("Expected ByUrl"),
        }
    }

    #[test]
    fn parse_gitlab_url_not_mr() {
        assert!(parse_forge_url("https://gitlab.com/group/repo/-/issues/1", None).is_none());
    }

    // --- Self-hosted URL parsing (Fix 2 & 3) ---

    #[test]
    fn parse_self_hosted_github_pull_url() {
        let mut hosts = HashMap::new();
        hosts.insert("code.mycompany.com".to_string(), "github".to_string());
        let target = parse_forge_url(
            "https://code.mycompany.com/team/project/pull/55",
            Some(&hosts),
        )
        .unwrap();
        match target {
            ForgeTarget::ByUrl {
                forge_type,
                pr_id,
                host,
            } => {
                assert_eq!(forge_type, ForgeType::GitHub);
                assert_eq!(pr_id.owner, "team");
                assert_eq!(pr_id.repo, "project");
                assert_eq!(pr_id.number, 55);
                assert_eq!(host, Some("code.mycompany.com".to_string()));
            }
            _ => panic!("Expected ByUrl"),
        }
    }

    #[test]
    fn parse_self_hosted_gitlab_mr_url() {
        let target = parse_forge_url(
            "https://git.internal.io/ops/infra/-/merge_requests/12",
            None,
        )
        .unwrap();
        match target {
            ForgeTarget::ByUrl {
                forge_type,
                pr_id,
                host,
            } => {
                assert_eq!(forge_type, ForgeType::GitLab);
                assert_eq!(pr_id.owner, "ops");
                assert_eq!(pr_id.repo, "infra");
                assert_eq!(pr_id.number, 12);
                assert_eq!(host, Some("git.internal.io".to_string()));
            }
            _ => panic!("Expected ByUrl"),
        }
    }

    // --- Remote URL parsing ---

    #[test]
    fn parse_remote_url_github_ssh() {
        let (forge, owner, repo, host) =
            parse_remote_url("git@github.com:octocat/hello-world.git", None).unwrap();
        assert_eq!(forge, ForgeType::GitHub);
        assert_eq!(owner, "octocat");
        assert_eq!(repo, "hello-world");
        assert!(host.is_none());
    }

    #[test]
    fn parse_remote_url_github_https() {
        let (forge, owner, repo, host) =
            parse_remote_url("https://github.com/octocat/hello-world.git", None).unwrap();
        assert_eq!(forge, ForgeType::GitHub);
        assert_eq!(owner, "octocat");
        assert_eq!(repo, "hello-world");
        assert!(host.is_none());
    }

    #[test]
    fn parse_remote_url_github_https_no_git_suffix() {
        let (forge, owner, repo, _) =
            parse_remote_url("https://github.com/octocat/hello-world", None).unwrap();
        assert_eq!(forge, ForgeType::GitHub);
        assert_eq!(owner, "octocat");
        assert_eq!(repo, "hello-world");
    }

    #[test]
    fn parse_remote_url_gitlab_ssh() {
        let (forge, owner, repo, host) =
            parse_remote_url("git@gitlab.com:group/project.git", None).unwrap();
        assert_eq!(forge, ForgeType::GitLab);
        assert_eq!(owner, "group");
        assert_eq!(repo, "project");
        assert!(host.is_none());
    }

    #[test]
    fn parse_remote_url_gitlab_https() {
        let (forge, owner, repo, host) =
            parse_remote_url("https://gitlab.com/group/project.git", None).unwrap();
        assert_eq!(forge, ForgeType::GitLab);
        assert_eq!(owner, "group");
        assert_eq!(repo, "project");
        assert!(host.is_none());
    }

    #[test]
    fn parse_remote_url_custom_gitlab_ssh() {
        let (forge, owner, repo, host) =
            parse_remote_url("git@gitlab.acme.com:data/project/repo.git", None).unwrap();
        assert_eq!(forge, ForgeType::GitLab);
        assert_eq!(owner, "data/project");
        assert_eq!(repo, "repo");
        assert_eq!(host, Some("gitlab.acme.com".to_string()));
    }

    #[test]
    fn parse_remote_url_custom_gitlab_https() {
        let (forge, owner, repo, host) =
            parse_remote_url("https://gitlab.acme.com/data/project/repo.git", None).unwrap();
        assert_eq!(forge, ForgeType::GitLab);
        assert_eq!(owner, "data/project");
        assert_eq!(repo, "repo");
        assert_eq!(host, Some("gitlab.acme.com".to_string()));
    }

    #[test]
    fn parse_remote_url_invalid() {
        let result = parse_remote_url("svn://example.com/repo", None);
        assert!(result.is_err());
    }

    // --- detect_forge_type ---

    #[test]
    fn detect_forge_type_github() {
        assert_eq!(detect_forge_type("github.com", None), ForgeType::GitHub);
    }

    #[test]
    fn detect_forge_type_github_enterprise() {
        assert_eq!(
            detect_forge_type("github.mycompany.com", None),
            ForgeType::GitHub
        );
    }

    #[test]
    fn detect_forge_type_gitlab() {
        assert_eq!(detect_forge_type("gitlab.com", None), ForgeType::GitLab);
    }

    #[test]
    fn detect_forge_type_custom_defaults_to_gitlab() {
        assert_eq!(
            detect_forge_type("code.example.com", None),
            ForgeType::GitLab
        );
    }

    // --- forge_hosts config override (Fix 1) ---

    #[test]
    fn forge_hosts_map_overrides_heuristic() {
        let mut hosts = HashMap::new();
        hosts.insert("code.example.com".to_string(), "github".to_string());
        // Without map, code.example.com defaults to GitLab
        assert_eq!(
            detect_forge_type("code.example.com", None),
            ForgeType::GitLab
        );
        // With map, it should be GitHub
        assert_eq!(
            detect_forge_type("code.example.com", Some(&hosts)),
            ForgeType::GitHub
        );
    }

    #[test]
    fn forge_hosts_map_used_in_remote_url_parsing() {
        let mut hosts = HashMap::new();
        hosts.insert("code.internal.io".to_string(), "github".to_string());
        let (forge, owner, repo, host) =
            parse_remote_url("git@code.internal.io:team/app.git", Some(&hosts)).unwrap();
        assert_eq!(forge, ForgeType::GitHub);
        assert_eq!(owner, "team");
        assert_eq!(repo, "app");
        assert_eq!(host, Some("code.internal.io".to_string()));
    }
}