aptu-core 0.2.21

Core library for Aptu - OSS issue triage with AI assistance
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
// SPDX-License-Identifier: Apache-2.0

//! Release-related GitHub operations.
//!
//! Provides functions for fetching PRs between git tags and parsing tag references.

use anyhow::{Context, Result};
use percent_encoding::{NON_ALPHANUMERIC, percent_encode};
use std::collections::HashSet;
use tracing::{debug, instrument};

use crate::ai::types::PrSummary;

#[derive(serde::Deserialize)]
struct RefResponse {
    object: RefObject,
}

#[derive(serde::Deserialize)]
struct RefObject {
    sha: String,
    #[serde(rename = "type")]
    r#type: String,
}

#[derive(serde::Deserialize)]
struct TagObject {
    object: GitObject,
}

#[derive(serde::Deserialize)]
struct GitObject {
    sha: String,
}

/// Fetch merged PRs between two git references.
///
/// # Arguments
///
/// * `client` - Octocrab GitHub client
/// * `owner` - Repository owner
/// * `repo` - Repository name
/// * `from_ref` - Starting reference (tag or commit)
/// * `to_ref` - Ending reference (tag or commit)
///
/// # Returns
///
/// Vector of `PrSummary` for merged PRs between the references.
#[instrument(skip(client))]
pub async fn fetch_prs_between_refs(
    client: &octocrab::Octocrab,
    owner: &str,
    repo: &str,
    from_ref: &str,
    to_ref: &str,
) -> Result<Vec<PrSummary>> {
    // Get the commit SHAs for the references
    let from_sha = resolve_ref_to_sha(client, owner, repo, from_ref).await?;
    let to_sha = resolve_ref_to_sha(client, owner, repo, to_ref).await?;

    // Fetch all commits between refs upfront using Compare API with pagination
    let commit_shas = fetch_commits_between_refs(client, owner, repo, &from_sha, &to_sha).await?;

    // Fetch all merged PRs
    let mut prs = Vec::new();
    let mut page = 1u32;

    loop {
        let pulls = client
            .pulls(owner, repo)
            .list()
            .state(octocrab::params::State::Closed)
            .per_page(100)
            .page(page)
            .send()
            .await
            .context("Failed to fetch PRs from GitHub")?;

        if pulls.items.is_empty() {
            break;
        }

        for pr in &pulls.items {
            // Only include merged PRs
            if pr.merged_at.is_none() {
                continue;
            }

            // Check if PR is between the two refs using local HashSet lookup
            if let Some(merge_commit) = &pr.merge_commit_sha
                && commit_shas.contains(merge_commit)
            {
                prs.push(PrSummary {
                    number: pr.number,
                    title: pr.title.clone().unwrap_or_default(),
                    body: pr.body.clone().unwrap_or_default(),
                    author: pr
                        .user
                        .as_ref()
                        .map_or_else(|| "unknown".to_string(), |u| u.login.clone()),
                    merged_at: pr.merged_at.map(|dt| dt.to_rfc3339()),
                });
            }
        }

        // Check if there are more pages
        if pulls.items.len() < 100 {
            break;
        }

        page += 1;
    }

    Ok(prs)
}

/// Resolve a git reference (tag or commit) to its SHA.
///
/// # Arguments
///
/// * `client` - Octocrab GitHub client
/// * `owner` - Repository owner
/// * `repo` - Repository name
/// * `ref_name` - Reference name (tag or commit SHA)
///
/// # Returns
///
/// The commit SHA for the reference.
#[instrument(skip(client))]
async fn resolve_ref_to_sha(
    client: &octocrab::Octocrab,
    owner: &str,
    repo: &str,
    ref_name: &str,
) -> Result<String> {
    // Try to resolve as a tag using GraphQL first
    match super::graphql::resolve_tag_to_commit_sha(client, owner, repo, ref_name).await? {
        Some(sha) => Ok(sha),
        None => {
            // If GraphQL returns None, try REST API as fallback
            // This handles cases where tags are recreated and GraphQL cache is stale
            match resolve_tag_via_rest(client, owner, repo, ref_name).await {
                Ok(sha) => Ok(sha),
                Err(e) => {
                    // If both GraphQL and REST API fail, assume it's a commit SHA
                    debug!(
                        error = ?e,
                        tag = %ref_name,
                        "REST API fallback failed, treating input as literal SHA"
                    );
                    Ok(ref_name.to_string())
                }
            }
        }
    }
}

/// Resolve a tag to its commit SHA using the REST API.
///
/// # Arguments
///
/// * `client` - Octocrab GitHub client
/// * `owner` - Repository owner
/// * `repo` - Repository name
/// * `tag_name` - Tag name to resolve
///
/// # Returns
///
/// The commit SHA for the tag, or an error if the tag doesn't exist.
#[instrument(skip(client))]
async fn resolve_tag_via_rest(
    client: &octocrab::Octocrab,
    owner: &str,
    repo: &str,
    tag_name: &str,
) -> Result<String> {
    // URL-encode the tag name to handle special characters like '/', '?', '+', etc.
    let encoded_tag = percent_encode(tag_name.as_bytes(), NON_ALPHANUMERIC).to_string();
    let route = format!("/repos/{owner}/{repo}/git/refs/tags/{encoded_tag}");

    let response: RefResponse = client
        .get::<RefResponse, &str, ()>(&route, None::<&()>)
        .await
        .context(format!("Failed to resolve tag {tag_name} via REST API"))?;

    // Check if this is an annotated tag (type == "tag") or a lightweight tag (type == "commit")
    if response.object.r#type == "tag" {
        // For annotated tags, we need to dereference to get the commit SHA
        // Make a second REST call to get the tag object and extract the commit SHA
        let tag_route = format!("/repos/{owner}/{repo}/git/tags/{}", response.object.sha);
        let tag_obj: TagObject = client
            .get::<TagObject, &str, ()>(&tag_route, None::<&()>)
            .await
            .context(format!(
                "Failed to dereference annotated tag {tag_name} to commit SHA"
            ))?;

        Ok(tag_obj.object.sha)
    } else {
        // For lightweight tags, the SHA is already the commit SHA
        Ok(response.object.sha)
    }
}

/// Fetch all commits between two references using GitHub Compare API with pagination.
///
/// # Arguments
///
/// * `client` - Octocrab GitHub client
/// * `owner` - Repository owner
/// * `repo` - Repository name
/// * `from_sha` - Starting commit SHA
/// * `to_sha` - Ending commit SHA
///
/// # Returns
///
/// `HashSet` of commit SHAs between the two references.
#[instrument(skip(client))]
async fn fetch_commits_between_refs(
    client: &octocrab::Octocrab,
    owner: &str,
    repo: &str,
    from_sha: &str,
    to_sha: &str,
) -> Result<HashSet<String>> {
    #[derive(serde::Deserialize)]
    struct CompareResponse {
        commits: Vec<CommitInfo>,
    }

    #[derive(serde::Deserialize)]
    struct CommitInfo {
        sha: String,
    }

    let mut commit_shas = HashSet::new();
    let mut page = 1u32;

    loop {
        // Use GitHub Compare API to get commits between two refs with pagination
        // GET /repos/{owner}/{repo}/compare/{base}...{head}?per_page=100&page={page}
        let route =
            format!("/repos/{owner}/{repo}/compare/{from_sha}...{to_sha}?per_page=100&page={page}");

        let comparison: CompareResponse = client
            .get(&route, None::<&()>)
            .await
            .context("Failed to compare commits")?;

        let count = comparison.commits.len();
        commit_shas.extend(comparison.commits.into_iter().map(|c| c.sha));

        // Check if there are more pages
        if count < 100 {
            break;
        }

        page += 1;
    }

    Ok(commit_shas)
}

/// Get the latest tag in a repository.
///
/// # Arguments
///
/// * `client` - Octocrab GitHub client
/// * `owner` - Repository owner
/// * `repo` - Repository name
///
/// # Returns
///
/// The latest tag name and its SHA, or None if no releases exist.
#[instrument(skip(client))]
pub async fn get_latest_tag(
    client: &octocrab::Octocrab,
    owner: &str,
    repo: &str,
) -> Result<Option<(String, String)>> {
    let releases = client
        .repos(owner, repo)
        .releases()
        .list()
        .per_page(1)
        .send()
        .await
        .context("Failed to fetch releases from GitHub")?;

    if releases.items.is_empty() {
        return Ok(None);
    }

    let latest = &releases.items[0];
    let tag_name = latest.tag_name.clone();

    // Get the commit SHA for the tag using GraphQL
    match super::graphql::resolve_tag_to_commit_sha(client, owner, repo, &tag_name).await? {
        Some(sha) => Ok(Some((tag_name, sha))),
        None => anyhow::bail!("Failed to resolve tag {tag_name} to commit SHA"),
    }
}

/// Get the tag immediately before a target tag in chronological order by commit date.
///
/// This function finds the previous tag by:
/// 1. Fetching all tags via REST API
/// 2. Resolving each tag to its commit SHA and timestamp
/// 3. Sorting by commit timestamp (chronological order)
/// 4. Finding the tag immediately before the target tag
///
/// This approach ensures correct tag ordering even when tags are recreated
/// (deleted and recreated), which would break sorting by release creation date.
///
/// # Arguments
///
/// * `client` - Octocrab GitHub client
/// * `owner` - Repository owner
/// * `repo` - Repository name
/// * `target_tag` - The tag to find the predecessor for
///
/// # Returns
///
/// The previous tag name and its SHA, or None if no previous tag exists.
#[instrument(skip(client))]
pub async fn get_previous_tag(
    client: &octocrab::Octocrab,
    owner: &str,
    repo: &str,
    target_tag: &str,
) -> Result<Option<(String, String)>> {
    #[derive(serde::Deserialize)]
    struct TagInfo {
        name: String,
        commit: CommitRef,
    }

    #[derive(serde::Deserialize)]
    struct CommitRef {
        sha: String,
    }

    #[derive(serde::Deserialize)]
    struct CommitDetail {
        commit: CommitData,
    }

    #[derive(serde::Deserialize)]
    struct CommitData {
        author: CommitAuthor,
    }

    #[derive(serde::Deserialize)]
    struct CommitAuthor {
        date: String,
    }

    // Fetch all tags via REST API with pagination
    let mut all_tags = Vec::new();
    let mut page = 1u32;

    loop {
        let route = format!("/repos/{owner}/{repo}/tags?per_page=100&page={page}");
        let tags: Vec<TagInfo> = client
            .get(&route, None::<&()>)
            .await
            .context("Failed to fetch tags from GitHub")?;

        if tags.is_empty() {
            break;
        }

        all_tags.extend(tags);

        if all_tags.len() < (page as usize * 100) {
            break;
        }

        page += 1;
    }

    if all_tags.is_empty() {
        return Ok(None);
    }

    // Resolve each tag to its commit timestamp
    let mut tags_with_timestamps = Vec::new();

    for tag in all_tags {
        // Get commit details to extract timestamp
        let commit_route = format!("/repos/{owner}/{repo}/commits/{}", tag.commit.sha);
        match client
            .get::<CommitDetail, &str, ()>(&commit_route, None::<&()>)
            .await
        {
            Ok(commit_detail) => {
                tags_with_timestamps.push((
                    tag.name.clone(),
                    tag.commit.sha.clone(),
                    commit_detail.commit.author.date.clone(),
                ));
            }
            Err(e) => {
                debug!(
                    tag = %tag.name,
                    error = ?e,
                    "Failed to resolve tag to commit timestamp, skipping"
                );
            }
        }
    }

    // Sort by commit timestamp (chronological order)
    tags_with_timestamps.sort_by(|a, b| a.2.cmp(&b.2));

    // Find the target tag and return the previous one
    for i in 0..tags_with_timestamps.len() {
        if tags_with_timestamps[i].0 == target_tag {
            if i > 0 {
                let prev = &tags_with_timestamps[i - 1];
                return Ok(Some((prev.0.clone(), prev.1.clone())));
            }
            // Target tag is the first (oldest) tag
            return Ok(None);
        }
    }

    // Target tag not found
    debug!(target_tag = %target_tag, "Target tag not found in repository");
    Ok(None)
}

/// Get the root (oldest) commit in a repository.
///
/// Uses the GitHub API compare endpoint with the empty tree SHA to fetch all commits
/// in reverse chronological order, then returns the oldest (last) commit.
///
/// # Arguments
///
/// * `client` - Octocrab GitHub client
/// * `owner` - Repository owner
/// * `repo` - Repository name
///
/// # Returns
///
/// The SHA of the root commit.
#[instrument(skip(client))]
pub async fn get_root_commit(
    client: &octocrab::Octocrab,
    owner: &str,
    repo: &str,
) -> Result<String> {
    // Empty tree SHA - represents the initial state before any commits
    const EMPTY_TREE_SHA: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";

    // Use compare endpoint to get all commits from empty tree to HEAD
    // This returns commits in chronological order (oldest first)
    // GET /repos/{owner}/{repo}/compare/{base}...{head}
    let route = format!("/repos/{owner}/{repo}/compare/{EMPTY_TREE_SHA}...HEAD");

    #[derive(serde::Deserialize)]
    struct CompareResponse {
        commits: Vec<CommitInfo>,
    }

    #[derive(serde::Deserialize)]
    struct CommitInfo {
        sha: String,
    }

    let comparison: CompareResponse = client
        .get(&route, None::<&()>)
        .await
        .context("Failed to fetch commits from GitHub")?;

    if comparison.commits.is_empty() {
        anyhow::bail!("Repository has no commits");
    }

    // The first commit in the list is the oldest (root) commit
    let root_commit = &comparison.commits[0];
    Ok(root_commit.sha.clone())
}

/// Parse a tag reference to extract the version.
///
/// Handles common tag formats like v1.0.0, 1.0.0, release-1.0.0, etc.
///
/// # Arguments
///
/// * `tag` - The tag name to parse
///
/// # Returns
///
/// The version string extracted from the tag.
#[must_use]
pub fn parse_tag_reference(tag: &str) -> String {
    // Remove common prefixes (check longer prefixes first)
    let version = tag
        .strip_prefix("release-")
        .or_else(|| tag.strip_prefix("v-"))
        .or_else(|| tag.strip_prefix('v'))
        .unwrap_or(tag);

    version.to_string()
}

/// Post release notes to GitHub.
///
/// Creates or updates a release on GitHub with the provided body.
/// If the release already exists, it will be updated. Otherwise, a new release is created.
///
/// # Arguments
///
/// * `client` - Octocrab GitHub client
/// * `owner` - Repository owner
/// * `repo` - Repository name
/// * `tag` - The tag name for the release
/// * `body` - The release notes body
///
/// # Returns
///
/// The URL of the created or updated release.
#[instrument(skip(client))]
pub async fn post_release_notes(
    client: &octocrab::Octocrab,
    owner: &str,
    repo: &str,
    tag: &str,
    body: &str,
) -> Result<String> {
    let repo_handle = client.repos(owner, repo);
    let releases = repo_handle.releases();

    // Try to get existing release by tag
    if let Ok(existing_release) = releases.get_by_tag(tag).await {
        // Update existing release
        let updated = releases
            .update(existing_release.id.0)
            .body(body)
            .send()
            .await
            .context(format!("Failed to update release for tag {tag}"))?;

        Ok(updated.html_url.to_string())
    } else {
        // Create new release
        let created = releases
            .create(tag)
            .body(body)
            .send()
            .await
            .context(format!("Failed to create release for tag {tag}"))?;

        Ok(created.html_url.to_string())
    }
}

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

    #[test]
    fn test_parse_tag_reference_v_prefix() {
        assert_eq!(parse_tag_reference("v1.0.0"), "1.0.0");
    }

    #[test]
    fn test_parse_tag_reference_release_prefix() {
        assert_eq!(parse_tag_reference("release-1.0.0"), "1.0.0");
    }

    #[test]
    fn test_parse_tag_reference_v_dash_prefix() {
        assert_eq!(parse_tag_reference("v-1.0.0"), "1.0.0");
    }

    #[test]
    fn test_parse_tag_reference_no_prefix() {
        assert_eq!(parse_tag_reference("1.0.0"), "1.0.0");
    }

    // Unit tests for get_previous_tag edge cases
    // Note: Full integration tests would require mocking GitHub API responses
    // These tests verify the logic for finding previous tags

    #[test]
    fn test_get_previous_tag_logic_no_tags() {
        // When there are no tags, get_previous_tag should return None
        // This is tested via integration tests with mocked API responses
    }

    #[test]
    fn test_get_previous_tag_logic_single_tag() {
        // When there is only one tag and it's the target, no previous tag exists
        // This is tested via integration tests with mocked API responses
    }

    #[test]
    fn test_get_previous_tag_logic_multiple_tags() {
        // When there are multiple tags, get_previous_tag should return the one
        // immediately before the target tag in chronological order
        // This is tested via integration tests with mocked API responses
    }

    #[test]
    fn test_get_previous_tag_logic_recreated_tag() {
        // When a tag is recreated (deleted and recreated), sorting by commit
        // timestamp (not release creation date) should return the correct previous tag
        // This is tested via integration tests with mocked API responses
    }
}