fallow-cli 3.26.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
use std::collections::BTreeSet;
use std::path::Path;
use std::process::ExitCode;

use fallow_config::OutputFormat;
use serde::Serialize;
use serde_json::Value;

use crate::api::try_api_agent;
use crate::error::emit_error_with_style;

use super::{
    ApplyResult, CiProvider, PlannedReconcile, ReconcileOptions, apply_provider_reconcile,
    emit_ci_command_json, github_create_json, github_token, gitlab_create_json,
    load_provider_state, read_envelope, require_target, url_encode_path_segment,
    validate_envelope_review_scope,
};

#[derive(Clone, Copy)]
pub(super) struct PostReviewInput<'a> {
    pub provider: CiProvider,
    pub target: Option<&'a str>,
    pub envelope: &'a Path,
    pub repo: Option<&'a str>,
    pub project_id: Option<&'a str>,
    pub api_url: Option<&'a str>,
    pub dry_run: bool,
}

#[derive(Debug, Default, Serialize)]
struct PostReviewResult {
    action: &'static str,
    provider: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    target: Option<String>,
    dry_run: bool,
    comments_total: usize,
    comments_posted: usize,
    comments_skipped: usize,
    summary_posted: bool,
    summary_updated: bool,
    stale_fingerprints: usize,
    resolution_comments_posted: usize,
    threads_resolved: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    apply_hint: Option<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    apply_errors: Vec<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    failed_fingerprints: Vec<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    unapplied_fingerprints: Vec<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    post_errors: Vec<String>,
}

pub(super) fn post_review(
    input: PostReviewInput<'_>,
    output: OutputFormat,
    json_style: crate::json_style::JsonStyle,
) -> ExitCode {
    let envelope = match read_envelope(input.envelope) {
        Ok(value) => value,
        Err(e) => return emit_error_with_style(&e, 2, output, json_style),
    };
    let review_id = match validate_envelope_review_scope(&envelope) {
        Ok(review_id) => review_id,
        Err(error) => return emit_error_with_style(&error, 2, output, json_style),
    };
    let opts = ReconcileOptions {
        repo: input.repo,
        project_id: input.project_id,
        api_url: input.api_url,
        dry_run: input.dry_run,
        review_id: review_id.as_ref(),
    };
    let provider_state = match load_provider_state(input.provider, input.target, opts) {
        Ok(state) => state,
        Err(e) => {
            return emit_error_with_style(&e, crate::api::NETWORK_EXIT_CODE, output, json_style);
        }
    };
    let current = envelope_fingerprints(&envelope);
    let planned = PlannedReconcile::new(&current, &provider_state);

    let mut result = match input.provider {
        CiProvider::Github => post_github_review(input, &envelope, &provider_state.fingerprints),
        CiProvider::Gitlab => post_gitlab_review(input, &envelope, &provider_state.fingerprints),
    };
    if !result.post_errors.is_empty() {
        // A failed inline-comment post cancels the whole reconcile pass, so no
        // stale thread is resolved in this run. That is a separate defect from
        // the per-fingerprint isolation inside the apply loops, and it is not
        // addressed here.
        return emit_post_review_result(&result, output, json_style);
    }

    let applied = if input.dry_run {
        ApplyResult::default()
    } else {
        apply_provider_reconcile(input.provider, &planned, input.target, opts)
    };
    attach_reconcile_result(&mut result, &planned.plan.stale, applied);
    emit_post_review_result(&result, output, json_style)
}

fn post_github_review(
    input: PostReviewInput<'_>,
    envelope: &Value,
    existing_fingerprints: &BTreeSet<String>,
) -> PostReviewResult {
    let pr = match require_target("GitHub pull request", input.target) {
        Ok(pr) => pr,
        Err(e) => return result_with_error(input, e),
    };
    let repo = match github_repo(input.repo) {
        Ok(repo) => repo,
        Err(e) => return result_with_error(input, e),
    };
    let token = match github_token() {
        Ok(token) => token,
        Err(e) => return result_with_error(input, e),
    };
    let api = input
        .api_url
        .unwrap_or("https://api.github.com")
        .trim_end_matches('/');
    let agent = match try_api_agent() {
        Ok(agent) => agent,
        Err(e) => return result_with_error(input, e.to_string()),
    };
    let comments = new_comments(envelope, existing_fingerprints);
    let mut result = base_result(input, "github", comments.len());
    if envelope_comments_len(envelope) == 0 {
        result.action = "skip";
        return result;
    }
    result.comments_skipped = envelope_comments_len(envelope).saturating_sub(comments.len());
    if comments.is_empty() {
        result.action = "skip";
        return result;
    }
    if input.dry_run {
        result.action = "post_review";
        result.comments_posted = comments.len();
        return result;
    }
    let payload = github_review_payload(envelope, &comments);
    let url = format!("{api}/repos/{repo}/pulls/{pr}/reviews");
    match github_create_json(&agent, &url, &token, &payload)
        .and_then(|value| validate_github_review_response(&value))
    {
        Ok(()) => {
            result.action = "post_review";
            result.comments_posted = comments.len();
        }
        Err(e) => result.post_errors.push(e),
    }
    result
}

fn post_gitlab_review(
    input: PostReviewInput<'_>,
    envelope: &Value,
    existing_fingerprints: &BTreeSet<String>,
) -> PostReviewResult {
    let mr = match require_target("GitLab merge request", input.target) {
        Ok(mr) => mr,
        Err(e) => return result_with_error(input, e),
    };
    let project_id = match gitlab_project_id(input.project_id) {
        Ok(project_id) => project_id,
        Err(e) => return result_with_error(input, e),
    };
    let token = match gitlab_token() {
        Ok(token) => token,
        Err(e) => return result_with_error(input, e),
    };
    let api = gitlab_api_url(input.api_url);
    let encoded_project = url_encode_path_segment(&project_id);
    let agent = match try_api_agent() {
        Ok(agent) => agent,
        Err(e) => return result_with_error(input, e.to_string()),
    };
    let comments = new_comments(envelope, existing_fingerprints);
    let mut result = base_result(input, "gitlab", comments.len());
    if envelope_comments_len(envelope) == 0 {
        result.action = "skip";
        return result;
    }
    result.comments_skipped = envelope_comments_len(envelope).saturating_sub(comments.len());
    if comments.is_empty() {
        result.action = "skip";
        return result;
    }
    result.action = "post_review";
    if input.dry_run {
        result.comments_posted = comments.len();
        return result;
    }
    for comment in &comments {
        match post_gitlab_inline_comment(&agent, &api, &encoded_project, mr, &token, comment) {
            Ok(()) => result.comments_posted += 1,
            Err(e) => result.post_errors.push(e),
        }
    }
    result
}

fn github_review_payload(envelope: &Value, comments: &[Value]) -> Value {
    let comments = comments
        .iter()
        .map(|comment| {
            serde_json::json!({
                "path": comment.get("path").cloned().unwrap_or(Value::Null),
                "line": comment.get("line").cloned().unwrap_or(Value::Null),
                "side": comment.get("side").cloned().unwrap_or(Value::Null),
                "body": comment.get("body").cloned().unwrap_or(Value::Null),
            })
        })
        .collect::<Vec<_>>();
    serde_json::json!({
        "event": envelope.get("event").and_then(Value::as_str).unwrap_or("COMMENT"),
        "body": envelope.get("body").and_then(Value::as_str).unwrap_or(""),
        "comments": comments,
    })
}

fn post_gitlab_inline_comment(
    agent: &ureq::Agent,
    api: &str,
    encoded_project: &str,
    mr: &str,
    token: &str,
    comment: &Value,
) -> Result<(), String> {
    let position = comment.get("position").cloned().unwrap_or(Value::Null);
    let body = comment
        .get("body")
        .and_then(Value::as_str)
        .unwrap_or("")
        .to_owned();
    if position.get("base_sha").and_then(Value::as_str).is_some()
        && position.get("head_sha").and_then(Value::as_str).is_some()
    {
        let payload = serde_json::json!({ "body": body, "position": position });
        let url = format!("{api}/projects/{encoded_project}/merge_requests/{mr}/discussions");
        return gitlab_create_json(agent, &url, token, &payload)
            .and_then(|value| validate_gitlab_discussion_response(&value));
    }
    let path = position
        .get("new_path")
        .and_then(Value::as_str)
        .unwrap_or("unknown");
    let line = position
        .get("new_line")
        .and_then(Value::as_u64)
        .unwrap_or(1);
    let fallback_body = format!("Warning: **{path}:{line}**\n\n{body}");
    let payload = serde_json::json!({ "body": fallback_body });
    let url = format!("{api}/projects/{encoded_project}/merge_requests/{mr}/discussions");
    gitlab_create_json(agent, &url, token, &payload)
        .and_then(|value| validate_gitlab_discussion_response(&value))
}

fn validate_github_review_response(value: &Value) -> Result<(), String> {
    value
        .get("id")
        .and_then(Value::as_u64)
        .map(|_| ())
        .ok_or_else(|| {
            format!("GitHub review response did not confirm a numeric review id: {value}")
        })
}

fn validate_gitlab_discussion_response(value: &Value) -> Result<(), String> {
    value
        .get("id")
        .and_then(Value::as_str)
        .filter(|id| !id.is_empty())
        .map(|_| ())
        .ok_or_else(|| {
            format!("GitLab discussion response did not confirm a discussion id: {value}")
        })
}

fn attach_reconcile_result(result: &mut PostReviewResult, stale: &[String], applied: ApplyResult) {
    result.stale_fingerprints = stale.len();
    result.resolution_comments_posted = applied.resolution_comments_posted;
    result.threads_resolved = applied.threads_resolved;
    result.apply_hint = applied.hint();
    result.failed_fingerprints = applied.failed_fingerprints.into_iter().collect();
    result.unapplied_fingerprints = applied.unapplied_fingerprints.into_iter().collect();
    result.apply_errors = applied.errors;
}

fn new_comments(envelope: &Value, existing: &BTreeSet<String>) -> Vec<Value> {
    envelope
        .get("comments")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter(|comment| {
            comment
                .get("fingerprint")
                .and_then(Value::as_str)
                .is_none_or(|fingerprint| !existing.contains(fingerprint))
        })
        .cloned()
        .collect()
}

fn envelope_comments_len(envelope: &Value) -> usize {
    envelope
        .get("comments")
        .and_then(Value::as_array)
        .map_or(0, Vec::len)
}

fn envelope_fingerprints(envelope: &Value) -> BTreeSet<String> {
    envelope
        .get("comments")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter_map(|comment| comment.get("fingerprint").and_then(Value::as_str))
        .filter(|fingerprint| !fingerprint.trim().is_empty())
        .map(str::to_owned)
        .collect()
}

fn base_result(
    input: PostReviewInput<'_>,
    provider: &'static str,
    comments_total: usize,
) -> PostReviewResult {
    PostReviewResult {
        action: "skip",
        provider,
        target: input.target.map(str::to_owned),
        dry_run: input.dry_run,
        comments_total,
        ..PostReviewResult::default()
    }
}

fn result_with_error(input: PostReviewInput<'_>, error: String) -> PostReviewResult {
    let mut result = base_result(
        input,
        match input.provider {
            CiProvider::Github => "github",
            CiProvider::Gitlab => "gitlab",
        },
        0,
    );
    result.post_errors.push(error);
    result
}

fn emit_post_review_result(
    result: &PostReviewResult,
    output: OutputFormat,
    json_style: crate::json_style::JsonStyle,
) -> ExitCode {
    emit_ci_command_json(result, "review post result", output, json_style)
}

fn github_repo(explicit: Option<&str>) -> Result<String, String> {
    explicit
        .map(str::to_owned)
        .or_else(|| std::env::var("GH_REPO").ok())
        .or_else(|| std::env::var("GITHUB_REPOSITORY").ok())
        .ok_or_else(|| {
            "GitHub review posting requires --repo, GH_REPO, or GITHUB_REPOSITORY".to_owned()
        })
}

fn gitlab_project_id(explicit: Option<&str>) -> Result<String, String> {
    explicit
        .map(str::to_owned)
        .or_else(|| std::env::var("CI_PROJECT_ID").ok())
        .ok_or_else(|| "GitLab review posting requires --project-id or CI_PROJECT_ID".to_owned())
}

fn gitlab_token() -> Result<String, String> {
    std::env::var("GITLAB_TOKEN")
        .map_err(|_| "GitLab review posting requires GITLAB_TOKEN".to_owned())
}

fn gitlab_api_url(explicit: Option<&str>) -> String {
    explicit
        .map(str::to_owned)
        .or_else(|| std::env::var("CI_API_V4_URL").ok())
        .unwrap_or_else(|| "https://gitlab.com/api/v4".to_owned())
        .trim_end_matches('/')
        .to_owned()
}

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

    fn envelope() -> Value {
        serde_json::json!({
            "event": "COMMENT",
            "body": "body",
            "comments": [
                { "path": "src/a.ts", "line": 1, "side": "RIGHT", "body": "A", "fingerprint": "a" },
                { "path": "src/b.ts", "line": 2, "side": "RIGHT", "body": "B", "fingerprint": "b" }
            ]
        })
    }

    #[test]
    fn new_comments_filters_existing_fingerprints() {
        let existing = BTreeSet::from(["a".to_owned()]);

        let comments = new_comments(&envelope(), &existing);

        assert_eq!(comments.len(), 1);
        assert_eq!(comments[0]["fingerprint"], "b");
    }

    #[test]
    fn github_review_payload_keeps_retryable_input_body() {
        let comments = new_comments(&envelope(), &BTreeSet::new());

        let payload = github_review_payload(&envelope(), &comments);

        assert_eq!(payload["event"], "COMMENT");
        assert_eq!(payload["comments"][0]["path"], "src/a.ts");
        assert_eq!(payload["comments"][0]["side"], "RIGHT");
    }

    #[test]
    fn create_response_validation_requires_provider_identity() {
        assert!(validate_github_review_response(&serde_json::json!({})).is_err());
        assert!(validate_gitlab_discussion_response(&serde_json::json!({})).is_err());
        assert!(validate_github_review_response(&serde_json::json!({ "id": 7 })).is_ok());
        assert!(
            validate_gitlab_discussion_response(&serde_json::json!({ "id": "thread-7" })).is_ok()
        );
    }
}