gitpoulpi-hosting 1.1.0

Hosting and issue-tracker API clients (GitHub, GitLab, Gitea/Forgejo, Azure DevOps, Bitbucket, Gerrit, Jira, Trello, Linear, YouTrack, Redmine, local Markdown issues): project listing, clone helpers, SSH key generation and upload, remote-URL provider matching.
Documentation
//! The Gerrit conversation against recorded answers: messages, votes and
//! comments as one timeline, the window cursor, posting and replying, and
//! what Gerrit cannot do (edit, delete, issues, internal notes).

use std::sync::Arc;

use serde_json::{json, Value};

use crate::client::{client_for, HostingClient};
use crate::conversation::{
    EventKind, IdentityKind, ItemKey, ItemKind, MarkupFlavor, PageCursor, TimelineEntry,
    TimelineOpts, TokenSource,
};
use crate::http::{Method, RecordedTransport};
use crate::integration::{Integration, IntegrationKind};
use crate::review::model::{DiffSide, ReviewState};
use crate::Error;

fn block_on<F: std::future::Future>(f: F) -> F::Output {
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap()
        .block_on(f)
}

fn client(t: &Arc<RecordedTransport>) -> Box<dyn HostingClient> {
    let mut i = Integration::new("gr", IntegrationKind::Gerrit, "http://127.0.0.1:8081/");
    i.account = "admin".into();
    client_for(
        i,
        "http-pass".into(),
        t.clone(),
        &crate::trust::TrustGate::for_tests(),
    )
    .unwrap()
}

fn gerrit(json: impl std::fmt::Display) -> String {
    format!(")]}}'\n{json}")
}

const ME: &str = r#"{"_account_id":1000000,"name":"Administrator","username":"admin"}"#;

fn pr() -> ItemKey {
    ItemKey::pull_request(7)
}

fn change(messages: Value) -> String {
    gerrit(json!({
        "_number": 7, "project": "sandbox", "branch": "master", "subject": "Add a main",
        "status": "MERGED", "created": "2026-10-15 06:29:50.000000000",
        "updated": "2026-10-15 09:00:00.000000000",
        "owner": { "_account_id": 5, "name": "Olga", "username": "olga" },
        "current_revision": "bbb", "hashtags": ["retry"],
        "revisions": {
            "aaa": { "_number": 1, "created": "2026-10-15 06:29:50.000000000",
                     "commit": { "message": "Add a main\n\nFirst try.\n\nChange-Id: I1\n", "parents": [] } },
            "bbb": { "_number": 2, "created": "2026-10-15 07:00:00.000000000",
                     "commit": { "message": "Add a main\n\nSecond try.\n\nChange-Id: I1\n", "parents": [] } }
        },
        "labels": { "Code-Review": { "values": {}, "all": [
            { "_account_id": 9, "value": -1, "username": "bob", "date": "2026-10-15 07:11:00.000000000" },
            { "_account_id": 1000000, "value": 2, "username": "admin", "date": "2026-10-15 08:00:00.000000000" } ] } },
        "messages": messages
    }))
}

fn messages() -> Value {
    json!([
        { "id": "m1", "author": { "_account_id": 5, "username": "olga" },
          "date": "2026-10-15 06:30:00.000000000", "message": "Uploaded patch set 1.",
          "tag": "autogenerated:gerrit:newPatchSet", "_revision_number": 1 },
        { "id": "m2", "author": { "_account_id": 9, "username": "bob" },
          "date": "2026-10-15 07:11:00.000000000", "message": "Patch Set 2: Code-Review-1\n\n(1 comment)",
          "_revision_number": 2 },
        { "id": "m3", "author": { "_account_id": 9, "username": "bob", "name": "Bob B" },
          "date": "2026-10-15 07:20:00.000000000",
          "message": "Patch Set 2:\n\n(2 comments)\n\nPlease add a test.", "_revision_number": 2 },
        { "id": "m4", "author": { "_account_id": 1000000, "username": "admin" },
          "date": "2026-10-15 09:00:00.000000000",
          "message": "Change has been successfully merged by Administrator",
          "tag": "autogenerated:gerrit:merged", "_revision_number": 2 }
    ])
}

fn comments() -> String {
    gerrit(
        r#"{"src/main.rs":[
          {"id":"c1","patch_set":2,"line":3,"message":"Why hello?","updated":"2026-10-15 07:12:00.000000000",
           "author":{"_account_id":9,"username":"bob"},"unresolved":true},
          {"id":"c2","patch_set":2,"line":3,"in_reply_to":"c1","message":"Because.","updated":"2026-10-15 07:13:00.000000000",
           "author":{"_account_id":5,"username":"olga"},"unresolved":false}],
         "/PATCHSET_LEVEL":[
          {"id":"c6","patch_set":2,"message":"General remark","updated":"2026-10-15 07:16:00.000000000",
           "author":{"_account_id":9,"username":"bob"}}]}"#,
    )
}

fn drafts() -> String {
    gerrit(
        r#"{"src/main.rs":[
          {"id":"d1","patch_set":2,"line":3,"in_reply_to":"c2","message":"Unsent","updated":"2026-10-15 08:30:00.000000000"}]}"#,
    )
}

fn fixture(messages: Value) -> Arc<RecordedTransport> {
    Arc::new(
        RecordedTransport::new()
            .on("/a/accounts/self", 200, &gerrit(ME))
            .on("/drafts", 200, &drafts())
            .on("/comments", 200, &comments())
            .on("/review", 200, &gerrit("{}"))
            .on("/a/changes/sandbox~7?", 200, &change(messages)),
    )
}

#[test]
fn a_change_becomes_one_timeline_of_events_messages_votes_and_threads() {
    let t = fixture(messages());
    let page = block_on(client(&t).item_timeline("sandbox", &pr(), None, &TimelineOpts::default()))
        .unwrap();
    let h = &page.header;
    assert_eq!(h.reference, "#7");
    assert_eq!(h.state_label, "merged");
    assert!(!h.open);
    assert_eq!(h.author.display, "Olga");
    assert_eq!(h.body.text, "Second try.");
    assert_eq!(h.labels, ["retry"]);
    assert_eq!(h.web_url, "http://127.0.0.1:8081/c/sandbox/+/7");
    assert_eq!(page.older, None);

    let shape: Vec<&str> = page
        .entries
        .iter()
        .map(|e| match e {
            TimelineEntry::Comment(_) => "comment",
            TimelineEntry::Review(_) => "review",
            TimelineEntry::Thread(_) => "thread",
            TimelineEntry::Event(_) => "event",
        })
        .collect();
    // push, bob's vote, thread (07:12), patch-set comment (07:16), bob's
    // message (07:20), admin's vote (08:00), merge. The vote-only message
    // is not repeated as a comment and the draft is not part of it.
    assert_eq!(
        shape,
        ["event", "review", "thread", "comment", "comment", "review", "event"]
    );
    assert!(matches!(
        &page.entries[0],
        TimelineEntry::Event(e) if e.kind == EventKind::CommitsPushed {
            count: 1,
            head: Some("aaa".into())
        }
    ));
    let TimelineEntry::Review(vote) = &page.entries[1] else {
        panic!()
    };
    assert_eq!(vote.state, ReviewState::ChangesRequested);
    let TimelineEntry::Thread(thread) = &page.entries[2] else {
        panic!()
    };
    assert_eq!(
        (thread.path.as_str(), thread.line),
        ("src/main.rs", Some(3))
    );
    assert_eq!(thread.side, DiffSide::New);
    assert_eq!(thread.comments.len(), 2, "the draft reply is left out");
    assert!(thread.resolved && thread.resolvable);
    assert!(thread.id.starts_with("c2|2|"), "{}", thread.id);
    let TimelineEntry::Comment(bob) = &page.entries[4] else {
        panic!()
    };
    assert_eq!(bob.body.text, "Please add a test.");
    assert_eq!(bob.author.display, "Bob B");
    assert_eq!(bob.body.flavor, MarkupFlavor::PlainText);
    assert_eq!((bob.can_edit, bob.can_delete), (Some(false), Some(false)));
    assert!(matches!(
        &page.entries[6],
        TimelineEntry::Event(e) if e.kind == EventKind::Merged
    ));
}

#[test]
fn events_can_be_left_out() {
    let t = fixture(messages());
    let page =
        block_on(client(&t).item_timeline("sandbox", &pr(), None, &TimelineOpts { events: false }))
            .unwrap();
    assert!(page
        .entries
        .iter()
        .all(|e| !matches!(e, TimelineEntry::Event(_))));
    assert_eq!(page.entries.len(), 5);
}

#[test]
fn the_newest_window_is_cut_from_the_whole_and_older_is_an_index() {
    let many: Vec<Value> = (0..305)
        .map(|i| {
            json!({ "id": format!("m{i}"), "author": { "_account_id": 9, "username": "bob" },
                    "date": format!("2026-10-16 {:02}:{:02}:00.000000000", i / 60, i % 60),
                    "message": format!("remark {i}"), "_revision_number": 2 })
        })
        .collect();
    let t = fixture(Value::Array(many));
    let c = client(&t);
    let first =
        block_on(c.item_timeline("sandbox", &pr(), None, &TimelineOpts { events: false })).unwrap();
    assert_eq!(first.entries.len(), 300);
    // 305 messages + 2 votes + thread + patch-set comment = 309 entries.
    assert_eq!(first.total_hint, Some(309));
    assert_eq!(first.older, Some(PageCursor("9".into())));
    let TimelineEntry::Comment(newest) = first.entries.last().unwrap() else {
        panic!()
    };
    assert_eq!(newest.id, "m304");
    let second = block_on(c.item_timeline(
        "sandbox",
        &pr(),
        first.older.as_ref(),
        &TimelineOpts { events: false },
    ))
    .unwrap();
    assert_eq!(second.entries.len(), 9);
    assert_eq!(second.older, None);
    assert!(matches!(
        block_on(c.item_timeline(
            "sandbox",
            &pr(),
            Some(&PageCursor("x".into())),
            &TimelineOpts::default()
        )),
        Err(Error::Api { status: 422, .. })
    ));
}

#[test]
fn a_post_is_a_change_message_found_again_for_its_id_and_date() {
    let mut mine = messages();
    mine.as_array_mut().unwrap().push(json!(
        { "id": "m9", "author": { "_account_id": 1000000, "username": "admin" },
          "date": "2026-10-15 09:30:00.000000000",
          "message": "Patch Set 2:\n\nPlease rebase", "_revision_number": 2 }));
    let t = fixture(mine);
    let c = client(&t);
    let made = block_on(c.post_item_comment("sandbox", &pr(), "Please rebase", false)).unwrap();
    assert_eq!(made.id, "m9");
    assert_eq!(made.created_at, "2026-10-15T09:30:00Z");
    assert_eq!(made.author.login, "admin");
    let posts: Vec<_> = t
        .requests()
        .into_iter()
        .filter(|r| r.method == Method::Post)
        .collect();
    assert_eq!(posts.len(), 1);
    assert_eq!(
        posts[0].url,
        "http://127.0.0.1:8081/a/changes/sandbox~7/revisions/current/review"
    );
    assert_eq!(
        serde_json::from_str::<Value>(posts[0].body.as_deref().unwrap()).unwrap(),
        json!({ "message": "Please rebase" })
    );
}

#[test]
fn a_reply_answers_the_thread_on_its_patch_set() {
    let t = fixture(messages());
    let c = client(&t);
    let made =
        block_on(c.reply_in_discussion("sandbox", &pr(), "c2|2|0|n|3|src/main.rs", "Thanks"))
            .unwrap();
    assert_eq!(made.in_reply_to.as_deref(), Some("c2"));
    assert_eq!(
        made.discussion_id.as_deref(),
        Some("c2|2|0|n|3|src/main.rs")
    );
    let post = t
        .requests()
        .into_iter()
        .find(|r| r.method == Method::Post)
        .unwrap();
    assert_eq!(
        post.url,
        "http://127.0.0.1:8081/a/changes/sandbox~7/revisions/2/review"
    );
    assert_eq!(
        serde_json::from_str::<Value>(post.body.as_deref().unwrap()).unwrap(),
        json!({ "comments": { "src/main.rs": [
            { "in_reply_to": "c2", "message": "Thanks", "unresolved": false, "line": 3 }
        ]}})
    );
}

#[test]
fn what_gerrit_cannot_do_is_unsupported_or_refused_before_any_request() {
    let t = Arc::new(RecordedTransport::new());
    let c = client(&t);
    assert!(matches!(
        block_on(c.edit_item_comment("sandbox", &pr(), "m9", "x")),
        Err(Error::Unsupported(_))
    ));
    assert!(matches!(
        block_on(c.delete_item_comment("sandbox", &pr(), "m9")),
        Err(Error::Unsupported(_))
    ));
    assert!(matches!(
        block_on(c.item_timeline(
            "sandbox",
            &ItemKey::issue(7),
            None,
            &TimelineOpts::default()
        )),
        Err(Error::Unsupported(_))
    ));
    for result in [
        block_on(c.post_item_comment("sandbox", &pr(), "x", true)),
        block_on(c.post_item_comment("sandbox", &pr(), "  ", false)),
        block_on(c.reply_in_discussion("sandbox", &pr(), "garbage", "x")),
    ] {
        assert!(matches!(result, Err(Error::Api { status: 422, .. })));
    }
    assert!(t.requests().is_empty());
}

#[test]
fn capabilities_say_no_edit_no_delete_and_no_issues() {
    let t = Arc::new(RecordedTransport::new());
    let c = client(&t);
    let caps = c.conversation_caps(ItemKind::PullRequest);
    assert!(caps.read && caps.comment && caps.reply_in_thread && caps.resolve);
    assert!(!caps.edit_own && !caps.delete_own);
    assert!(!caps.internal_notes && !caps.reactions);
    assert_eq!(caps.write_flavor, MarkupFlavor::PlainText);
    let issue = c.conversation_caps(ItemKind::Issue);
    assert!(!issue.read && !issue.comment);
}

#[test]
fn the_identity_is_the_account_the_credentials_belong_to() {
    let t = Arc::new(RecordedTransport::new().on("/a/accounts/self", 200, &gerrit(ME)));
    let who = block_on(client(&t).posting_identity("sandbox")).unwrap();
    assert_eq!(who.login.as_deref(), Some("admin"));
    assert_eq!(who.kind, IdentityKind::PersonalToken);
    assert_eq!(who.source, TokenSource::Profile { id: "gr".into() });
    let t = Arc::new(RecordedTransport::new().on("/a/accounts/self", 401, "Unauthorized"));
    assert!(matches!(
        block_on(client(&t).posting_identity("sandbox")),
        Err(Error::Unauthorized { .. })
    ));
}