aptu-core 0.2.22

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
// SPDX-License-Identifier: Apache-2.0

//! GitHub integration module.
//!
//! Provides authentication and API client functionality for GitHub.

use anyhow::{Context, Result};
use tracing::debug;

pub mod auth;
pub mod graphql;
pub mod issues;
pub mod pulls;
pub mod ratelimit;
pub mod releases;

/// OAuth Client ID for Aptu CLI (safe to embed per RFC 8252).
///
/// This is a public client ID for native/CLI applications. Per OAuth 2.0 for
/// Native Apps (RFC 8252), client credentials in native apps cannot be kept
/// confidential and are safe to embed in source code.
pub const OAUTH_CLIENT_ID: &str = "Ov23lifiYQrh6Ga7Hpyr";

/// Keyring service name for storing credentials.
#[cfg(feature = "keyring")]
pub const KEYRING_SERVICE: &str = "aptu";

/// Keyring username for the GitHub token.
#[cfg(feature = "keyring")]
pub const KEYRING_USER: &str = "github_token";

/// Discriminator for GitHub reference type (issue or pull request).
#[derive(Debug, Clone, Copy)]
pub enum ReferenceKind {
    /// Issue reference with display name and URL path segment.
    Issue,
    /// Pull request reference with display name and URL path segment.
    Pull,
}

impl ReferenceKind {
    /// Returns the display name for this reference kind.
    #[must_use]
    pub fn display_name(&self) -> &'static str {
        match self {
            ReferenceKind::Issue => "issue",
            ReferenceKind::Pull => "pull request",
        }
    }

    /// Returns the URL path segment for this reference kind.
    #[must_use]
    pub fn url_segment(&self) -> &'static str {
        match self {
            ReferenceKind::Issue => "issues",
            ReferenceKind::Pull => "pull",
        }
    }
}

/// Parses an owner/repo string to extract owner and repo.
///
/// Validates format: exactly one `/`, non-empty parts.
///
/// # Errors
///
/// Returns an error if the format is invalid.
pub fn parse_owner_repo(s: &str) -> Result<(String, String)> {
    let parts: Vec<&str> = s.split('/').collect();
    if parts.len() != 2 || parts[0].is_empty() || parts[1].is_empty() {
        anyhow::bail!(
            "Invalid owner/repo format.\n\
             Expected: owner/repo\n\
             Got: {s}"
        );
    }
    Ok((parts[0].to_string(), parts[1].to_string()))
}

/// Parse full URL format: <https://github.com/owner/repo/issues/123>
fn parse_url_ref(kind: ReferenceKind, input: &str) -> Result<(String, String, u64)> {
    // Remove trailing fragments and query params
    let clean_url = input.split('#').next().unwrap_or(input);
    let clean_url = clean_url.split('?').next().unwrap_or(clean_url);

    // Parse the URL path
    let parts: Vec<&str> = clean_url.trim_end_matches('/').split('/').collect();

    // Expected: ["https:", "", "github.com", "owner", "repo", "issues/pull", "123"]
    if parts.len() < 7 {
        anyhow::bail!(
            "Invalid GitHub {} URL format.\n\
             Expected: https://github.com/owner/repo/{}/123\n\
             Got: {input}",
            kind.display_name(),
            kind.url_segment()
        );
    }

    // Verify it's a github.com URL
    if !parts[2].contains("github.com") {
        anyhow::bail!(
            "URL must be a GitHub {} URL.\n\
             Expected: https://github.com/owner/repo/{}/123\n\
             Got: {input}",
            kind.display_name(),
            kind.url_segment()
        );
    }

    // Verify it's the correct path segment
    if parts[5] != kind.url_segment() {
        anyhow::bail!(
            "URL must point to a GitHub {}.\n\
             Expected: https://github.com/owner/repo/{}/123\n\
             Got: {input}",
            kind.display_name(),
            kind.url_segment()
        );
    }

    let owner = parts[3].to_string();
    let repo = parts[4].to_string();
    let number: u64 = parts[6].parse().with_context(|| {
        format!(
            "Invalid {} number '{}' in URL.\n\
             Expected a numeric {} number.",
            kind.display_name(),
            parts[6],
            kind.display_name()
        )
    })?;

    debug!(owner = %owner, repo = %repo, number = number, "Parsed {} URL", kind.display_name());
    Ok((owner, repo, number))
}

/// Parse short form: owner/repo#123
fn parse_short_ref(kind: ReferenceKind, input: &str) -> Result<(String, String, u64)> {
    if let Some(hash_pos) = input.find('#') {
        let owner_repo_part = &input[..hash_pos];
        let number_part = &input[hash_pos + 1..];

        let (owner, repo) = parse_owner_repo(owner_repo_part)?;
        let number: u64 = number_part.parse().with_context(|| {
            format!(
                "Invalid {} number '{number_part}' in short form.\n\
                 Expected: owner/repo#123\n\
                 Got: {input}",
                kind.display_name()
            )
        })?;

        debug!(owner = %owner, repo = %repo, number = number, "Parsed short-form {} reference", kind.display_name());
        return Ok((owner, repo, number));
    }
    anyhow::bail!("Not a short form reference")
}

/// Parse bare number: `123` (requires `repo_context`)
fn parse_bare_ref(
    kind: ReferenceKind,
    input: &str,
    repo_context: Option<&str>,
) -> Result<(String, String, u64)> {
    if let Ok(number) = input.parse::<u64>() {
        let repo_context = repo_context.ok_or_else(|| {
            anyhow::anyhow!(
                "Bare {} number requires repository context.\n\
                 Use one of:\n\
                 - Full URL: https://github.com/owner/repo/{}/123\n\
                 - Short form: owner/repo#123\n\
                 - Bare number with --repo flag: 123 --repo owner/repo\n\
                 Got: {input}",
                kind.display_name(),
                kind.url_segment()
            )
        })?;

        let (owner, repo) = parse_owner_repo(repo_context)?;
        debug!(owner = %owner, repo = %repo, number = number, "Parsed bare {} number", kind.display_name());
        return Ok((owner, repo, number));
    }
    anyhow::bail!("Not a bare number reference")
}

/// Parses a GitHub reference (issue or PR) in multiple formats.
///
/// Supports:
/// - Full URL: `https://github.com/owner/repo/issues/123` or `https://github.com/owner/repo/pull/123`
/// - Short form: `owner/repo#123`
/// - Bare number: `123` (requires `repo_context`)
///
/// # Arguments
///
/// * `kind` - The type of reference (Issue or Pull)
/// * `input` - The reference to parse
/// * `repo_context` - Optional repository context for bare numbers (e.g., "owner/repo")
///
/// # Errors
///
/// Returns an error if the format is invalid or bare number is used without context.
pub fn parse_github_reference(
    kind: ReferenceKind,
    input: &str,
    repo_context: Option<&str>,
) -> Result<(String, String, u64)> {
    let input = input.trim();

    // Try full URL first
    if input.starts_with("https://") || input.starts_with("http://") {
        return parse_url_ref(kind, input);
    }

    // Try short form: owner/repo#123
    if input.contains('#') {
        return parse_short_ref(kind, input);
    }

    // Try bare number: 123 (requires repo_context)
    if input.parse::<u64>().is_ok() {
        return parse_bare_ref(kind, input, repo_context);
    }

    // If we get here, it's an invalid format
    anyhow::bail!(
        "Invalid {} reference format.\n\
         Expected one of:\n\
         - Full URL: https://github.com/owner/repo/{}/123\n\
         - Short form: owner/repo#123\n\
         - Bare number with --repo flag: 123 --repo owner/repo\n\
         Got: {input}",
        kind.display_name(),
        kind.url_segment()
    );
}

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

    #[test]
    fn test_parse_owner_repo_valid() {
        let (owner, repo) = parse_owner_repo("octocat/Hello-World").unwrap();
        assert_eq!(owner, "octocat");
        assert_eq!(repo, "Hello-World");
    }

    #[test]
    fn test_parse_owner_repo_invalid_no_slash() {
        assert!(parse_owner_repo("octocat").is_err());
    }

    #[test]
    fn test_parse_owner_repo_invalid_empty_owner() {
        assert!(parse_owner_repo("/repo").is_err());
    }

    #[test]
    fn test_parse_owner_repo_invalid_empty_repo() {
        assert!(parse_owner_repo("owner/").is_err());
    }

    #[test]
    fn test_parse_github_reference_issue_full_url() {
        let (owner, repo, number) = parse_github_reference(
            ReferenceKind::Issue,
            "https://github.com/octocat/Hello-World/issues/123",
            None,
        )
        .unwrap();
        assert_eq!(owner, "octocat");
        assert_eq!(repo, "Hello-World");
        assert_eq!(number, 123);
    }

    #[test]
    fn test_parse_github_reference_issue_full_url_with_query() {
        let (owner, repo, number) = parse_github_reference(
            ReferenceKind::Issue,
            "https://github.com/octocat/Hello-World/issues/123?foo=bar",
            None,
        )
        .unwrap();
        assert_eq!(owner, "octocat");
        assert_eq!(repo, "Hello-World");
        assert_eq!(number, 123);
    }

    #[test]
    fn test_parse_github_reference_issue_full_url_with_fragment() {
        let (owner, repo, number) = parse_github_reference(
            ReferenceKind::Issue,
            "https://github.com/octocat/Hello-World/issues/123#comment-456",
            None,
        )
        .unwrap();
        assert_eq!(owner, "octocat");
        assert_eq!(repo, "Hello-World");
        assert_eq!(number, 123);
    }

    #[test]
    fn test_parse_github_reference_issue_short_form() {
        let (owner, repo, number) =
            parse_github_reference(ReferenceKind::Issue, "octocat/Hello-World#123", None).unwrap();
        assert_eq!(owner, "octocat");
        assert_eq!(repo, "Hello-World");
        assert_eq!(number, 123);
    }

    #[test]
    fn test_parse_github_reference_issue_bare_number() {
        let (owner, repo, number) =
            parse_github_reference(ReferenceKind::Issue, "123", Some("octocat/Hello-World"))
                .unwrap();
        assert_eq!(owner, "octocat");
        assert_eq!(repo, "Hello-World");
        assert_eq!(number, 123);
    }

    #[test]
    fn test_parse_github_reference_issue_bare_number_no_context() {
        assert!(parse_github_reference(ReferenceKind::Issue, "123", None).is_err());
    }

    #[test]
    fn test_parse_github_reference_pull_full_url() {
        let (owner, repo, number) = parse_github_reference(
            ReferenceKind::Pull,
            "https://github.com/octocat/Hello-World/pull/456",
            None,
        )
        .unwrap();
        assert_eq!(owner, "octocat");
        assert_eq!(repo, "Hello-World");
        assert_eq!(number, 456);
    }

    #[test]
    fn test_parse_github_reference_pull_short_form() {
        let (owner, repo, number) =
            parse_github_reference(ReferenceKind::Pull, "octocat/Hello-World#456", None).unwrap();
        assert_eq!(owner, "octocat");
        assert_eq!(repo, "Hello-World");
        assert_eq!(number, 456);
    }

    #[test]
    fn test_parse_github_reference_pull_bare_number() {
        let (owner, repo, number) =
            parse_github_reference(ReferenceKind::Pull, "456", Some("octocat/Hello-World"))
                .unwrap();
        assert_eq!(owner, "octocat");
        assert_eq!(repo, "Hello-World");
        assert_eq!(number, 456);
    }

    #[test]
    fn test_parse_github_reference_issue_wrong_kind_url() {
        // Try to parse a PR URL as an issue
        assert!(
            parse_github_reference(
                ReferenceKind::Issue,
                "https://github.com/octocat/Hello-World/pull/123",
                None
            )
            .is_err()
        );
    }

    #[test]
    fn test_parse_github_reference_pull_wrong_kind_url() {
        // Try to parse an issue URL as a PR
        assert!(
            parse_github_reference(
                ReferenceKind::Pull,
                "https://github.com/octocat/Hello-World/issues/123",
                None
            )
            .is_err()
        );
    }

    #[test]
    fn test_parse_github_reference_invalid_url() {
        assert!(
            parse_github_reference(
                ReferenceKind::Issue,
                "https://github.com/octocat/Hello-World/invalid/123",
                None
            )
            .is_err()
        );
    }

    #[test]
    fn test_parse_github_reference_not_github_url() {
        assert!(
            parse_github_reference(
                ReferenceKind::Issue,
                "https://gitlab.com/octocat/Hello-World/issues/123",
                None
            )
            .is_err()
        );
    }
}