diffler 0.11.1

Terminal code review for AI coding agents
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
//! Provider-agnostic CI run/job/log acquisition, plus the host glue that picks a
//! provider for the repo and maps a normalized `RunDetail` onto the graph model.
//! Adapters (`providers/`) implement [`ForgeProvider`] over each forge (via
//! `gh`/`glab`/`curl` through the [`CommandRunner`] seam) and never touch the terminal.

mod detect;
mod error;
mod exec;
mod model;
mod provider;
mod providers;

pub use detect::{Detected, detect};
pub use error::{CiError, Result};
#[cfg(test)]
pub(crate) use exec::test_support;
pub use exec::{CommandRunner, RealRunner};
pub use model::{
    Annotation, AnnotationLevel, Artifact, Capabilities, CiJob, CiRun, DagSource, JobId, JobStatus,
    LogChunk, LogMode, LogStepMeta, PrComment, PullRequest, RunDetail, RunExtras, RunId,
    fmt_duration, ts_sort_key,
};
pub use provider::{
    ForgeProvider, NewPrComment, NewPrReview, NewPullRequest, ProviderKind, ReviewVerdict,
    capabilities_for,
};
pub use providers::{EtagCache, ForgejoProvider, GitHubProvider, GitLabProvider, YamlCache};

use std::path::Path;

use crate::config::CiConfig;
use crate::graph::{Edge, Model, Node, NodeId, NodeStatus, RankDir};

/// Detect the repo's CI provider: the configured `provider` (or auto), the
/// `origin` remote host (from `remote_url`), and config-file presence. A
/// configured GitLab `host` overrides remote detection for a self-hosted
/// instance.
pub fn detect_for_repo(
    repo_root: &Path,
    remote_url: Option<&str>,
    config: &CiConfig,
) -> Option<Detected> {
    let forced = match config.provider.as_str() {
        "github" => Some(ProviderKind::GitHub),
        "gitlab" => Some(ProviderKind::GitLab),
        "forgejo" | "codeberg" => Some(ProviderKind::Forgejo),
        _ => None,
    };
    let host = remote_url.and_then(parse_host);
    let mut detected = detect(repo_root, host.as_deref(), forced)?;
    if detected.kind == ProviderKind::GitLab && config.gitlab.host.is_some() {
        detected.host.clone_from(&config.gitlab.host);
    }
    if detected.kind == ProviderKind::Forgejo {
        if config.forgejo.host.is_some() {
            detected.host.clone_from(&config.forgejo.host);
        } else if detected.host.is_none() {
            detected.host = host;
        }
    }
    Some(detected)
}

/// Whether the forge CLI a provider drives is installed, so detection can
/// disable CI (hide the section, stop polling) instead of erroring on every
/// poll when `gh`/`glab` isn't on the host.
pub fn provider_available(detected: &Detected) -> bool {
    let cli = match detected.kind {
        ProviderKind::GitHub => "gh",
        ProviderKind::GitLab => "glab",
        ProviderKind::Forgejo => "curl",
    };
    std::env::var_os("PATH").is_some_and(|path| on_path(cli, &path))
}

/// Whether `program` resolves in one of `path`'s directories (with a `.exe`
/// fallback on Windows). Split from [`provider_available`] for testability.
pub(crate) fn on_path(program: &str, path: &std::ffi::OsStr) -> bool {
    std::env::split_paths(path)
        .any(|dir| dir.join(program).is_file() || dir.join(format!("{program}.exe")).is_file())
}

/// Pull the host out of a git remote URL: `git@host:owner/repo.git`,
/// `https://host/owner/repo`, or `ssh://git@host:port/owner/repo`.
fn parse_host(url: &str) -> Option<String> {
    if let Some(rest) = url.strip_prefix("git@") {
        return rest.split(':').next().map(str::to_owned);
    }
    let authority = url.split("://").nth(1)?.split('/').next()?;
    let host = authority.rsplit('@').next()?.split(':').next()?;
    (!host.is_empty()).then(|| host.to_owned())
}

/// Construct the provider for a detected forge. GitLab targets the detected host;
/// GitHub scopes the runs list to `branch` and carries every workflow YAML so
/// each run's DAG is built from its own workflow. A Forgejo detection with no
/// resolvable host (no `[ci.forgejo] host` and no parseable remote) passes
/// through as `None`, never guessed as `codeberg.org`. `detect_for_repo`
/// already returns `None` for that same no-signal case, so this keeps the
/// same fail-closed shape: the built provider errors on every call, keeping
/// the token off the wrong host.
pub fn build_provider(
    detected: &Detected,
    repo_root: &Path,
    branch: Option<&str>,
    remote_url: Option<&str>,
    yaml_cache: YamlCache,
    etags: EtagCache,
) -> Box<dyn ForgeProvider + Send> {
    match detected.kind {
        ProviderKind::GitHub => Box::new(GitHubProvider::new(
            Box::new(RealRunner),
            read_workflows(repo_root),
            branch.map(str::to_owned),
            yaml_cache,
            etags,
        )),
        ProviderKind::GitLab => Box::new(GitLabProvider::new(
            Box::new(RealRunner),
            detected.host.clone(),
            branch.map(str::to_owned),
        )),
        ProviderKind::Forgejo => Box::new(ForgejoProvider::new(
            Box::new(RealRunner),
            detected.host.clone(),
            remote_url.and_then(parse_owner_repo).unwrap_or_default(),
            forgejo_token(),
            branch.map(str::to_owned),
        )),
    }
}

/// The status vocabulary GitHub and Forgejo Actions share on `conclusion`
/// (Forgejo mirrors GitHub's Actions REST shape here). `None` means the run
/// hasn't concluded, so the caller falls back to its own in-progress/queued
/// status strings, which the two forges do not report identically.
pub(crate) fn map_conclusion(conclusion: Option<&str>) -> Option<JobStatus> {
    match conclusion? {
        "success" => Some(JobStatus::Ok),
        "failure" | "timed_out" | "startup_failure" => Some(JobStatus::Failed),
        "skipped" => Some(JobStatus::Skipped),
        "cancelled" => Some(JobStatus::Neutral),
        _ => None,
    }
}

/// `owner/name` from a git remote URL: `git@host:owner/name.git` or
/// `https://host/owner/name(.git)`. Extra path segments are dropped.
fn parse_owner_repo(url: &str) -> Option<String> {
    let path = if let Some(rest) = url.strip_prefix("git@") {
        rest.split_once(':').map(|(_, p)| p)?
    } else {
        url.split("://").nth(1)?.split_once('/').map(|(_, p)| p)?
    };
    let path = path.strip_suffix(".git").unwrap_or(path);
    let mut segments = path.split('/');
    let owner = segments.next()?;
    let name = segments.next()?;
    (!owner.is_empty() && !name.is_empty()).then(|| format!("{owner}/{name}"))
}

/// A Forgejo PAT for private repos; public repos need none.
fn forgejo_token() -> Option<String> {
    std::env::var("FORGEJO_TOKEN")
        .or_else(|_| std::env::var("CODEBERG_TOKEN"))
        .ok()
}

/// Every `.github/workflows/*.{yml,yaml}` body, for per-run DAG matching.
fn read_workflows(repo_root: &Path) -> Vec<String> {
    let dir = repo_root.join(".github/workflows");
    let Ok(entries) = std::fs::read_dir(&dir) else {
        return Vec::new();
    };
    entries
        .flatten()
        .filter(|e| {
            e.path()
                .extension()
                .and_then(|x| x.to_str())
                .is_some_and(|x| x == "yml" || x == "yaml")
        })
        .filter_map(|e| std::fs::read_to_string(e.path()).ok())
        .collect()
}

/// Map a run's jobs + dependency edges onto a graph model (top-down layered).
pub fn to_model(detail: &RunDetail) -> Model {
    let mut model = Model::new(RankDir::TopDown);
    model.nodes = detail
        .jobs
        .iter()
        .map(|job| Node {
            id: NodeId::new(job.id.0.clone()),
            label: match job.duration_secs {
                Some(secs) => format!("{}  {}", job.name, fmt_duration(secs)),
                None => job.name.clone(),
            },
            status: node_status(job.status),
            group: None,
            foldable: None,
        })
        .collect();
    model.edges = detail
        .jobs
        .iter()
        .flat_map(|job| {
            let to = job.id.0.clone();
            job.needs.iter().map(move |dep| Edge {
                from: NodeId::new(dep.0.clone()),
                to: NodeId::new(to.clone()),
                label: None,
            })
        })
        .collect();
    model
}

fn node_status(status: JobStatus) -> NodeStatus {
    match status {
        JobStatus::Ok => NodeStatus::Ok,
        JobStatus::Failed => NodeStatus::Failed,
        JobStatus::Running => NodeStatus::Running,
        JobStatus::Queued => NodeStatus::Queued,
        JobStatus::Skipped => NodeStatus::Skipped,
        JobStatus::Neutral => NodeStatus::Neutral,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use super::{CiJob, CiRun, JobId, RunId};

    #[test]
    fn on_path_finds_files_in_listed_dirs_only() {
        let dir = std::ffi::OsString::from(env!("CARGO_MANIFEST_DIR"));
        assert!(on_path("Cargo.toml", &dir), "a file in the dir resolves");
        assert!(!on_path("definitely-not-a-binary-xyz", &dir));
    }

    fn run() -> CiRun {
        CiRun {
            id: RunId("1".into()),
            name: "CI".into(),
            title: String::new(),
            branch: "main".into(),
            commit: "abc".into(),
            author: String::new(),
            created: None,
            status: JobStatus::Running,
            url: None,
            remote: None,
        }
    }

    #[test]
    fn forced_forgejo_targets_the_remote_host_not_codeberg() {
        let dir = tempfile::tempdir().expect("tempdir");
        let mut config = CiConfig {
            provider: "forgejo".to_owned(),
            ..CiConfig::default()
        };
        let detected =
            detect_for_repo(dir.path(), Some("git@git.example.com:me/repo.git"), &config)
                .expect("detected");
        assert_eq!(detected.kind, ProviderKind::Forgejo);
        assert_eq!(detected.host.as_deref(), Some("git.example.com"));

        config.forgejo.host = Some("forge.corp.io".to_owned());
        let detected =
            detect_for_repo(dir.path(), Some("git@git.example.com:me/repo.git"), &config)
                .expect("detected");
        assert_eq!(detected.host.as_deref(), Some("forge.corp.io"));
    }

    #[tokio::test]
    async fn forced_forgejo_with_no_resolvable_host_fails_closed() {
        // no remote, no config host: build_provider must not fall back to a
        // hardcoded default host (that would risk sending the token elsewhere)
        let dir = tempfile::tempdir().expect("tempdir");
        let config = CiConfig {
            provider: "forgejo".to_owned(),
            ..CiConfig::default()
        };
        let detected = detect_for_repo(dir.path(), None, &config).expect("detected");
        assert_eq!(detected.host, None);

        let provider = build_provider(
            &detected,
            dir.path(),
            None,
            None,
            YamlCache::default(),
            EtagCache::default(),
        );
        let err = provider.list_runs(1).await.expect_err("no host to target");
        assert!(matches!(err, CiError::NotFound(_)), "{err:?}");
    }

    #[test]
    fn map_conclusion_covers_the_shared_actions_vocabulary() {
        assert_eq!(map_conclusion(Some("success")), Some(JobStatus::Ok));
        assert_eq!(map_conclusion(Some("failure")), Some(JobStatus::Failed));
        assert_eq!(map_conclusion(Some("timed_out")), Some(JobStatus::Failed));
        assert_eq!(map_conclusion(Some("skipped")), Some(JobStatus::Skipped));
        assert_eq!(map_conclusion(Some("cancelled")), Some(JobStatus::Neutral));
        assert_eq!(
            map_conclusion(None),
            None,
            "no conclusion yet: not classified"
        );
        assert_eq!(
            map_conclusion(Some("neutral")),
            None,
            "an unrecognized value falls back to the forge's own status strings"
        );
    }

    #[test]
    fn parse_owner_repo_handles_common_url_shapes() {
        assert_eq!(
            parse_owner_repo("git@codeberg.org:acme/widgets.git").as_deref(),
            Some("acme/widgets")
        );
        assert_eq!(
            parse_owner_repo("https://codeberg.org/acme/widgets").as_deref(),
            Some("acme/widgets")
        );
        assert_eq!(
            parse_owner_repo("ssh://git@codeberg.org:2222/acme/widgets.git").as_deref(),
            Some("acme/widgets")
        );
        assert_eq!(parse_owner_repo("https://codeberg.org/"), None);
    }

    #[test]
    fn parse_host_handles_scp_https_and_ssh_urls() {
        assert_eq!(
            parse_host("git@github.com:o/r.git").as_deref(),
            Some("github.com")
        );
        assert_eq!(
            parse_host("https://gitlab.com/o/r").as_deref(),
            Some("gitlab.com")
        );
        assert_eq!(
            parse_host("ssh://git@git.example.com:2222/o/r.git").as_deref(),
            Some("git.example.com")
        );
        assert_eq!(parse_host("not a url"), None);
    }

    #[test]
    fn maps_jobs_and_needs_to_nodes_and_edges() {
        let detail = RunDetail {
            run: run(),
            jobs: vec![
                CiJob {
                    id: JobId("lint".into()),
                    name: "lint".into(),
                    status: JobStatus::Ok,
                    duration_secs: None,
                    needs: vec![],
                },
                CiJob {
                    id: JobId("test".into()),
                    name: "test".into(),
                    status: JobStatus::Running,
                    duration_secs: None,
                    needs: vec![JobId("lint".into())],
                },
            ],
        };
        let model = to_model(&detail);
        let ids: Vec<&str> = model.nodes.iter().map(|n| n.id.0.as_str()).collect();
        assert_eq!(ids, ["lint", "test"]);
        assert_eq!(model.nodes[0].status, NodeStatus::Ok);
        let edges: Vec<(&str, &str)> = model
            .edges
            .iter()
            .map(|e| (e.from.0.as_str(), e.to.0.as_str()))
            .collect();
        assert_eq!(edges, [("lint", "test")]);
    }

    #[test]
    fn a_node_wears_the_time_its_job_spent() {
        let detail = RunDetail {
            run: run(),
            jobs: vec![
                CiJob {
                    id: JobId("lint".into()),
                    name: "lint".into(),
                    status: JobStatus::Ok,
                    duration_secs: Some(73),
                    needs: vec![],
                },
                CiJob {
                    id: JobId("queued".into()),
                    name: "queued".into(),
                    status: JobStatus::Queued,
                    duration_secs: None,
                    needs: vec![],
                },
            ],
        };
        let model = to_model(&detail);
        assert_eq!(model.nodes[0].label, "lint  1m13s");
        assert_eq!(
            model.nodes[1].label, "queued",
            "a job that has not started says nothing about time"
        );
    }
}