fallow-cli 3.30.0

CLI for fallow, codebase intelligence for TypeScript and JavaScript
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
use std::fmt::Write as _;
use std::path::Path;
use std::process::{Command, ExitCode};

use colored::Colorize as _;
use fallow_config::{FallowConfig, OutputFormat, ProductionAnalysis, ResolvedConfig};
use fallow_engine::changed_files::clear_ambient_git_env;

use crate::api::{
    NETWORK_EXIT_CODE, ParsedErrorEnvelope, actionable_error_hint, api_url, response_message_suffix,
};
use crate::coverage::{
    COVERAGE_UPLOAD_AUTH_REJECTED_EXIT_CODE as EXIT_AUTH_REJECTED,
    COVERAGE_UPLOAD_PAYLOAD_TOO_LARGE_EXIT_CODE as EXIT_PAYLOAD_TOO_LARGE,
    COVERAGE_UPLOAD_SERVER_ERROR_EXIT_CODE as EXIT_SERVER_ERROR,
    COVERAGE_UPLOAD_VALIDATION_EXIT_CODE as EXIT_VALIDATION,
};

pub(super) const GIT_SHA_MAX_LEN: usize = 64;

/// Outcome of a git-SHA keyed upload (`upload-inventory` and
/// `upload-static-findings`). Each variant carries its exit code class, and
/// the CLI dispatch changes transient errors to a warning when the user
/// opts in.
#[derive(Debug)]
pub(super) enum UploadError {
    /// User-fixable input error (missing key, unresolvable project-id,
    /// analysis/config failure, ...).
    Validation(String),
    /// The payload exceeds the server cap; the user must scope the upload.
    PayloadTooLarge(String),
    /// 401 / 403: auth rejected, the user needs to rotate or scope the key.
    AuthRejected(String),
    /// 5xx, timeout, transport failure; transient.
    ServerError(String),
    /// Transport-level failure before response (DNS, TLS, connect).
    Network(String),
}

impl UploadError {
    pub(super) fn into_exit(self, log_prefix: &str, ignore_upload_errors: bool) -> ExitCode {
        let soft_fail =
            ignore_upload_errors && matches!(&self, Self::ServerError(_) | Self::Network(_));
        let (code, body) = match self {
            Self::Validation(m) => (EXIT_VALIDATION, m),
            Self::PayloadTooLarge(m) => (EXIT_PAYLOAD_TOO_LARGE, m),
            Self::AuthRejected(m) => (EXIT_AUTH_REJECTED, m),
            Self::ServerError(m) => (EXIT_SERVER_ERROR, m),
            Self::Network(m) => (NETWORK_EXIT_CODE, m),
        };
        let severity = if soft_fail {
            "warning".yellow().bold()
        } else {
            "error".red().bold()
        };
        eprintln!("{log_prefix}: {severity}: {body}");
        if soft_fail {
            eprintln!("  -> --ignore-upload-errors set, continuing with exit 0");
            return ExitCode::SUCCESS;
        }
        ExitCode::from(code)
    }
}

/// Reject a dirty working tree for a git-SHA keyed upload, unless the run is
/// a dry run or the user passed `--allow-dirty`.
///
/// `working_copy_subject` completes the warning sentence, for example
/// `"the inventory comes"`.
pub(super) fn enforce_clean_worktree(
    log_prefix: &str,
    command: &str,
    working_copy_subject: &str,
    dry_run: bool,
    allow_dirty: bool,
    root: &Path,
) -> Result<(), UploadError> {
    if dry_run || !dirty_worktree(root) {
        return Ok(());
    }
    if allow_dirty {
        eprintln!(
            "{log_prefix}: {}: working tree has uncommitted changes. Proceeding because --allow-dirty was set, but {working_copy_subject} from the working copy and may not match the uploaded git SHA.",
            "warning".yellow().bold(),
        );
        return Ok(());
    }
    Err(UploadError::Validation(format!(
        "working tree has uncommitted changes. `{command}` is keyed to a git SHA, so uploading the working copy would drift from that commit. Commit or stash first, or pass --allow-dirty to intentionally upload the working copy."
    )))
}

pub(super) fn format_upload_error_message(
    command: &str,
    status: u16,
    body: &str,
    code: Option<&str>,
    envelope: &ParsedErrorEnvelope,
) -> String {
    if let Some(code) = code
        && let Some(hint) = actionable_error_hint(command, code)
    {
        return format!("{hint} (HTTP {status}, code {code})");
    }
    let body_suffix = response_message_suffix(body, envelope);
    format!("{command} request failed with HTTP {status}{body_suffix}")
}

pub(super) fn format_count(n: usize) -> String {
    let mut s = n.to_string();
    let mut i = s.len();
    while i > 3 {
        i -= 3;
        s.insert(i, ',');
    }
    s
}

/// Endpoint URL for dry-run output. The project id stays unencoded so the
/// user reads it as typed.
pub(super) fn display_endpoint_url(
    override_endpoint: Option<&str>,
    project_id: &str,
    path_suffix: &str,
) -> String {
    let base = override_endpoint.map_or_else(
        || {
            std::env::var("FALLOW_API_URL")
                .ok()
                .filter(|v| !v.trim().is_empty())
                .map_or_else(
                    || "https://api.fallow.cloud".to_owned(),
                    |v| v.trim().trim_end_matches('/').to_owned(),
                )
        },
        |v| v.trim().trim_end_matches('/').to_owned(),
    );
    format!("{base}/v1/coverage/{project_id}/{path_suffix}")
}

pub(super) fn to_posix_string(path: &Path) -> String {
    path.to_string_lossy().replace('\\', "/")
}

pub(super) fn resolve_project_id(
    explicit_project_id: Option<&str>,
    root: &Path,
) -> Result<String, String> {
    if let Some(explicit) = explicit_project_id {
        return validate_project_id(explicit.trim()).map(str::to_owned);
    }
    if let Ok(github_repo) = std::env::var("GITHUB_REPOSITORY") {
        let trimmed = github_repo.trim();
        if !trimmed.is_empty() {
            return validate_project_id(trimmed).map(str::to_owned);
        }
    }
    if let Ok(gitlab_path) = std::env::var("CI_PROJECT_PATH") {
        let trimmed = gitlab_path.trim();
        if !trimmed.is_empty() {
            return validate_project_id(trimmed).map(str::to_owned);
        }
    }
    if let Some(from_remote) = git_origin_project_id(root) {
        return Ok(from_remote);
    }
    Err(
        "could not determine project id. Pass --project-id <project-id>, or set \
         $GITHUB_REPOSITORY / $CI_PROJECT_PATH, or ensure `git remote get-url origin` \
         returns a recognizable URL."
            .to_owned(),
    )
}

/// Validate the project identifier used as the `{repo}` URL segment.
///
/// The server accepts any non-empty string without path-traversal, whether
/// bare (`fallow-cloud-api`) or slash-scoped (`acme/widgets`). Keep validation
/// minimal: reject only what the server or filesystem would reject (empty,
/// `..`).
pub(super) fn validate_project_id(id: &str) -> Result<&str, String> {
    if id.is_empty() {
        return Err("project id is empty".to_owned());
    }
    if id.contains("..") {
        return Err("project id must not contain '..' path segments".to_owned());
    }
    Ok(id)
}

fn git_origin_project_id(root: &Path) -> Option<String> {
    let mut command = Command::new("git");
    command
        .args(["remote", "get-url", "origin"])
        .current_dir(root);
    clear_ambient_git_env(&mut command);
    let output = command.output().ok()?;
    if !output.status.success() {
        return None;
    }
    let url = String::from_utf8_lossy(&output.stdout).trim().to_string();
    parse_git_remote_to_project_id(&url)
}

/// Parse common git remote URL shapes into `owner/repo`. Covers HTTPS
/// (`https://github.com/owner/repo(.git)?`), SSH
/// (`git@github.com:owner/repo(.git)?`), and `ssh://` / `git://` variants.
pub(super) fn parse_git_remote_to_project_id(url: &str) -> Option<String> {
    let stripped_suffix = url.trim().trim_end_matches(".git");
    if let Some((_, path)) = stripped_suffix.split_once(':')
        && let Some(project_id) = take_last_two_segments(path)
    {
        return Some(project_id);
    }
    if let Some(path_part) = stripped_suffix.split("://").nth(1)
        && let Some((_, tail)) = path_part.split_once('/')
        && let Some(project_id) = take_last_two_segments(tail)
    {
        return Some(project_id);
    }
    None
}

pub(super) fn take_last_two_segments(path: &str) -> Option<String> {
    let mut parts: Vec<&str> = path
        .trim_end_matches('/')
        .split('/')
        .filter(|segment| !segment.trim().is_empty())
        .collect();
    if parts.len() < 2 {
        return None;
    }
    let repo = parts.pop()?.trim();
    let owner = parts.pop()?.trim();
    (!owner.is_empty() && !repo.is_empty()).then(|| format!("{owner}/{repo}"))
}

pub(super) fn resolve_api_key(explicit: Option<&str>) -> Result<String, String> {
    if let Some(explicit) = explicit {
        let trimmed = explicit.trim();
        if !trimmed.is_empty() {
            return Ok(trimmed.to_owned());
        }
    }
    if let Ok(from_env) = std::env::var("FALLOW_API_KEY") {
        let trimmed = from_env.trim();
        if !trimmed.is_empty() {
            return Ok(trimmed.to_owned());
        }
    }
    Err(
        "no API key. Set $FALLOW_API_KEY or pass --api-key <KEY>. Generate at \
         https://fallow.cloud/settings#api-keys."
            .to_owned(),
    )
}

pub(super) fn endpoint_url(
    override_endpoint: Option<&str>,
    project_id: &str,
    path_suffix: &str,
) -> String {
    let path = format!(
        "/v1/coverage/{}/{path_suffix}",
        url_encode_path_segment(project_id)
    );
    match override_endpoint {
        Some(base) => format!("{}{path}", base.trim().trim_end_matches('/')),
        None => api_url(&path),
    }
}

/// URL-encode a single URL path segment (RFC 3986 unreserved set).
///
/// Project IDs can be bare (`fallow-cloud-api`) or slash-scoped
/// (`acme/widgets`), but the server receives them as a single percent-encoded
/// segment under `/v1/coverage/{repo}/...`, so `/` must be encoded too.
#[expect(
    clippy::expect_used,
    reason = "formatting percent-encoded bytes into String is infallible"
)]
pub fn url_encode_path_segment(value: &str) -> String {
    let mut out = String::with_capacity(value.len());
    for byte in value.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
                out.push(byte as char);
            }
            _ => {
                write!(out, "%{byte:02X}").expect("writing to String never fails");
            }
        }
    }
    out
}

/// Build the dashboard URL for a repository page.
///
/// The dashboard serves a repository at `/repo/{repo}`, and the project id is a
/// single route segment, so a slash-scoped id such as `owner/my-service` must be
/// percent-encoded (`owner%2Fmy-service`) or the link resolves to a 404.
pub(super) fn dashboard_repo_url(project_id: &str) -> String {
    format!(
        "https://fallow.cloud/repo/{}",
        url_encode_path_segment(project_id)
    )
}

pub(super) fn resolve_git_sha(
    explicit_git_sha: Option<&str>,
    root: &Path,
) -> Result<String, String> {
    let sha = if let Some(explicit) = explicit_git_sha {
        explicit.trim().to_owned()
    } else {
        fallow_engine::repo_refs::head_sha(root)
            .map_err(|err| {
                format!("could not resolve git SHA: {err}. Pass --git-sha <sha> explicitly.")
            })?
            .ok_or_else(|| {
                "`git rev-parse HEAD` failed. Pass --git-sha <sha> explicitly.".to_owned()
            })?
    };

    if sha.is_empty() {
        return Err("git sha is empty".to_owned());
    }
    if sha.len() > GIT_SHA_MAX_LEN {
        return Err(format!(
            "git sha is {} chars, server limit is {}",
            sha.len(),
            GIT_SHA_MAX_LEN
        ));
    }
    if !sha
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
    {
        return Err(format!(
            "git sha '{sha}' contains characters outside [A-Za-z0-9._-]"
        ));
    }
    Ok(sha)
}

pub(super) fn dirty_worktree(root: &Path) -> bool {
    let mut command = Command::new("git");
    command.args(["status", "--porcelain"]).current_dir(root);
    clear_ambient_git_env(&mut command);
    let Ok(output) = command.output() else {
        return false;
    };
    if !output.status.success() {
        return false;
    }
    output.stdout.iter().any(|b| !b.is_ascii_whitespace())
}

#[cfg(test)]
pub(super) fn load_resolved_config(root: &Path) -> Result<ResolvedConfig, String> {
    load_resolved_config_with_options(root, false)
}

pub(super) fn load_resolved_config_with_options(
    root: &Path,
    allow_remote_extends: bool,
) -> Result<ResolvedConfig, String> {
    let user_config = match FallowConfig::find_and_load_with_options(
        root,
        fallow_config::ConfigLoadOptions {
            allow_remote_extends,
        },
    ) {
        Ok(Some((config, _path))) => Some(config),
        Ok(None) => None,
        Err(e) => return Err(format!("config load failed: {e}")),
    };
    let mut config = user_config.unwrap_or_default();
    // The upload pipeline runs dead-code analysis, and resolve() reads only
    // the global production flag, so flatten per-analysis production first
    // like the engine and core call sites do.
    config.production = config
        .production
        .for_analysis(ProductionAnalysis::DeadCode)
        .into();
    let threads = std::thread::available_parallelism().map_or(1, std::num::NonZero::get);
    Ok(config.resolve(
        root.to_path_buf(),
        OutputFormat::Human,
        threads,
        /* no_cache */ true,
        /* quiet */ true,
        /* cache_max_size_mb */ None,
    ))
}

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

    #[test]
    fn into_exit_maps_variants_and_soft_fails_transient_when_opted_in() {
        let exit = |err: UploadError, ignore: bool| err.into_exit("fallow coverage test", ignore);
        assert_eq!(
            exit(UploadError::Validation("v".to_owned()), false),
            ExitCode::from(EXIT_VALIDATION)
        );
        assert_eq!(
            exit(UploadError::PayloadTooLarge("p".to_owned()), false),
            ExitCode::from(EXIT_PAYLOAD_TOO_LARGE)
        );
        assert_eq!(
            exit(UploadError::AuthRejected("a".to_owned()), false),
            ExitCode::from(EXIT_AUTH_REJECTED)
        );
        assert_eq!(
            exit(UploadError::ServerError("s".to_owned()), false),
            ExitCode::from(EXIT_SERVER_ERROR)
        );
        assert_eq!(
            exit(UploadError::Network("n".to_owned()), false),
            ExitCode::from(NETWORK_EXIT_CODE)
        );

        // With --ignore-upload-errors, only transient (server/network) failures
        // change to exit 0; auth rejection and payload size stay fatal.
        assert_eq!(
            exit(UploadError::ServerError("s".to_owned()), true),
            ExitCode::SUCCESS
        );
        assert_eq!(
            exit(UploadError::Network("n".to_owned()), true),
            ExitCode::SUCCESS
        );
        assert_eq!(
            exit(UploadError::AuthRejected("a".to_owned()), true),
            ExitCode::from(EXIT_AUTH_REJECTED)
        );
        assert_eq!(
            exit(UploadError::PayloadTooLarge("p".to_owned()), true),
            ExitCode::from(EXIT_PAYLOAD_TOO_LARGE)
        );
    }

    fn enforce(dry_run: bool, allow_dirty: bool, root: &Path) -> Result<(), UploadError> {
        enforce_clean_worktree(
            "fallow coverage upload-inventory",
            "upload-inventory",
            "the inventory comes",
            dry_run,
            allow_dirty,
            root,
        )
    }

    #[test]
    fn dirty_worktree_is_rejected_by_default() {
        let repo = create_dirty_git_repo();
        let err = enforce(false, false, repo.path())
            .expect_err("dirty repo should fail without --allow-dirty");
        let UploadError::Validation(message) = err else {
            panic!("expected validation error, got {err:?}");
        };
        assert!(message.contains("working tree has uncommitted changes"));
        assert!(message.contains("`upload-inventory` is keyed to a git SHA"));
        assert!(message.contains("--allow-dirty"));
    }

    #[test]
    fn dirty_worktree_is_allowed_with_explicit_opt_in() {
        let repo = create_dirty_git_repo();
        assert!(enforce(false, true, repo.path()).is_ok());
    }

    #[test]
    fn dry_run_skips_dirty_worktree_validation() {
        let repo = create_dirty_git_repo();
        assert!(enforce(true, false, repo.path()).is_ok());
    }

    fn create_dirty_git_repo() -> TempDir {
        let dir = tempfile::tempdir().expect("create temp repo");
        run_git(dir.path(), &["init", "-q"]);
        run_git(dir.path(), &["config", "commit.gpgsign", "false"]);
        run_git(dir.path(), &["config", "user.email", "review@example.com"]);
        run_git(dir.path(), &["config", "user.name", "Reviewer"]);
        std::fs::write(dir.path().join("a.js"), "function committed() {}\n")
            .expect("write committed file");
        run_git(dir.path(), &["add", "a.js"]);
        run_git(dir.path(), &["commit", "-qm", "init"]);
        std::fs::write(
            dir.path().join("a.js"),
            "function committed() {}\nfunction dirty() {}\n",
        )
        .expect("write dirty file");
        dir
    }

    fn run_git(root: &Path, args: &[&str]) {
        let status = fallow_engine::changed_files::clear_ambient_git_env(&mut Command::new("git"))
            .args(args)
            .current_dir(root)
            .status()
            .expect("run git");
        assert!(status.success(), "git {args:?} failed");
    }

    #[test]
    fn resolve_git_sha_validates_explicit_value() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        assert_eq!(resolve_git_sha(Some("abcdef1"), root).unwrap(), "abcdef1");
        assert!(resolve_git_sha(Some(""), root).is_err(), "empty sha");
        assert!(
            resolve_git_sha(Some(&"a".repeat(GIT_SHA_MAX_LEN + 1)), root).is_err(),
            "over-length sha"
        );
        assert!(
            resolve_git_sha(Some("bad sha!"), root).is_err(),
            "illegal characters"
        );
    }

    #[test]
    fn format_count_groups_thousands() {
        assert_eq!(format_count(0), "0");
        assert_eq!(format_count(999), "999");
        assert_eq!(format_count(1_000), "1,000");
        assert_eq!(format_count(14_280), "14,280");
        assert_eq!(format_count(1_234_567), "1,234,567");
    }

    #[test]
    fn display_endpoint_url_uses_override_unencoded() {
        let url = display_endpoint_url(Some("http://127.0.0.1:3000/"), "a/b", "static-findings");
        assert_eq!(url, "http://127.0.0.1:3000/v1/coverage/a/b/static-findings");
    }

    #[test]
    fn to_posix_string_normalizes_windows_separators() {
        let p = Path::new("src\\foo\\bar.ts");
        assert_eq!(to_posix_string(p), "src/foo/bar.ts");
    }

    #[test]
    fn load_resolved_config_flattens_per_analysis_production() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join(".fallowrc.json"),
            r#"{"production": {"deadCode": true}}"#,
        )
        .unwrap();

        let resolved = load_resolved_config_with_options(dir.path(), false).unwrap();
        assert!(
            resolved.production,
            "per-analysis deadCode production must survive resolve"
        );
    }

    #[test]
    fn parse_git_remote_https_with_dot_git() {
        assert_eq!(
            parse_git_remote_to_project_id("https://github.com/fallow-rs/fallow.git"),
            Some("fallow-rs/fallow".to_owned())
        );
    }

    #[test]
    fn parse_git_remote_https_without_dot_git() {
        assert_eq!(
            parse_git_remote_to_project_id("https://gitlab.com/acme/widgets"),
            Some("acme/widgets".to_owned())
        );
    }

    #[test]
    fn parse_git_remote_ssh_colon_shape() {
        assert_eq!(
            parse_git_remote_to_project_id("git@github.com:fallow-rs/fallow.git"),
            Some("fallow-rs/fallow".to_owned())
        );
    }

    #[test]
    fn parse_git_remote_ssh_scheme_shape() {
        assert_eq!(
            parse_git_remote_to_project_id("ssh://git@github.com/fallow-rs/fallow.git"),
            Some("fallow-rs/fallow".to_owned())
        );
    }

    #[test]
    fn parse_git_remote_nested_group_uses_last_two_segments() {
        assert_eq!(
            parse_git_remote_to_project_id("https://gitlab.com/acme/team/widgets.git"),
            Some("team/widgets".to_owned())
        );
        assert_eq!(
            parse_git_remote_to_project_id("ssh://git@gitlab.com/group/subgroup/repo.git"),
            Some("subgroup/repo".to_owned())
        );
    }

    #[test]
    fn parse_git_remote_rejects_incomplete_urls() {
        assert_eq!(parse_git_remote_to_project_id("https://example.com/"), None);
        assert_eq!(parse_git_remote_to_project_id(""), None);
        assert_eq!(parse_git_remote_to_project_id("not-a-remote"), None);
        assert_eq!(parse_git_remote_to_project_id("git@github.com:owner"), None);
        assert_eq!(parse_git_remote_to_project_id("https://github.com"), None);
        assert_eq!(parse_git_remote_to_project_id("not a remote"), None);
    }

    #[test]
    fn take_last_two_segments_needs_two_nonempty_segments() {
        assert_eq!(take_last_two_segments("widgets"), None);
        assert_eq!(
            take_last_two_segments("acme/widgets"),
            Some("acme/widgets".to_owned())
        );
        // Trailing slashes and empty interior segments are ignored.
        assert_eq!(
            take_last_two_segments("group/acme/widgets/"),
            Some("acme/widgets".to_owned())
        );
    }

    #[test]
    fn validate_project_id_accepts_owner_repo_and_bare() {
        assert!(validate_project_id("fallow-rs/fallow").is_ok());
        assert!(validate_project_id("fallow-cloud-api").is_ok());
    }

    #[test]
    fn validate_project_id_rejects_path_traversal_and_empty() {
        assert!(validate_project_id("../etc/passwd").is_err());
        assert!(validate_project_id("acme/../secret").is_err());
        assert!(validate_project_id("").is_err());
    }

    #[test]
    fn dashboard_repo_url_targets_the_repo_route() {
        assert_eq!(
            dashboard_repo_url("my-service"),
            "https://fallow.cloud/repo/my-service"
        );
    }

    #[test]
    fn dashboard_repo_url_encodes_a_slash_scoped_project_id() {
        assert_eq!(
            dashboard_repo_url("owner/my-service"),
            "https://fallow.cloud/repo/owner%2Fmy-service"
        );
    }

    #[test]
    fn url_encode_path_segment_passthrough_for_unreserved_chars() {
        assert_eq!(
            url_encode_path_segment("abc-123_foo.bar~"),
            "abc-123_foo.bar~"
        );
        assert_eq!(url_encode_path_segment("a-b_c.d~e"), "a-b_c.d~e");
    }

    #[test]
    fn url_encode_path_segment_encodes_reserved_bytes() {
        assert_eq!(url_encode_path_segment("/"), "%2F");
        assert_eq!(url_encode_path_segment("@"), "%40");
        assert_eq!(url_encode_path_segment("a b"), "a%20b");
        assert_eq!(
            url_encode_path_segment("fallow-rs/fallow"),
            "fallow-rs%2Ffallow"
        );
        assert_eq!(url_encode_path_segment("a/b@c"), "a%2Fb%40c");
    }

    #[test]
    fn url_encode_path_segment_empty_string_returns_empty() {
        assert_eq!(url_encode_path_segment(""), "");
    }

    #[test]
    fn url_encode_path_segment_percent_encodes_utf8() {
        assert_eq!(url_encode_path_segment("caf\u{e9}"), "caf%C3%A9");
    }

    #[test]
    fn endpoint_url_uses_override_and_encodes_project_id() {
        assert_eq!(
            endpoint_url(Some("http://127.0.0.1:3000"), "a/b", "inventory"),
            "http://127.0.0.1:3000/v1/coverage/a%2Fb/inventory"
        );
        assert_eq!(
            endpoint_url(Some("http://127.0.0.1:3000/"), "a/b", "static-findings"),
            "http://127.0.0.1:3000/v1/coverage/a%2Fb/static-findings"
        );
        assert_eq!(
            endpoint_url(Some("http://localhost:3000"), "owner/repo", "source-maps"),
            "http://localhost:3000/v1/coverage/owner%2Frepo/source-maps"
        );
    }

    #[test]
    fn resolve_api_key_trims_explicit_value() {
        assert_eq!(
            resolve_api_key(Some("  fallow_key_123  ")).unwrap(),
            "fallow_key_123"
        );
    }
}