gitprint 0.4.0

Convert git repositories into beautifully formatted, printer-friendly PDFs
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
//! GitHub REST API v3 client.
//!
//! All functions operate on public data and work without authentication.
//! Set `GITHUB_TOKEN` in the environment for higher rate limits (5 000/hr vs 60/hr)
//! and access to private repositories.

use anyhow::{Context, bail};
use serde::Deserialize;

const API_BASE: &str = "https://api.github.com";
const VERSION: &str = env!("CARGO_PKG_VERSION");

// ── Response types ─────────────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
pub struct GitHubUser {
    pub login: String,
    pub name: Option<String>,
    pub bio: Option<String>,
    pub location: Option<String>,
    pub company: Option<String>,
    pub blog: Option<String>,
    pub email: Option<String>,
    pub public_repos: u64,
    pub followers: u64,
    pub following: u64,
    pub created_at: String,
    pub html_url: String,
}

#[derive(Debug, Deserialize, Clone)]
pub struct GitHubRepo {
    pub name: String,
    pub full_name: String,
    pub html_url: String,
    pub description: Option<String>,
    pub language: Option<String>,
    pub stargazers_count: u64,
    pub forks_count: u64,
    pub pushed_at: Option<String>,
    pub updated_at: Option<String>,
    pub fork: bool,
    #[serde(default)]
    pub open_issues_count: u64,
    #[serde(default)]
    pub size: u64, // in KB
    #[serde(default)]
    pub created_at: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct GitHubEvent {
    #[serde(rename = "type")]
    pub kind: String,
    pub repo: EventRepo,
    pub payload: serde_json::Value,
    pub created_at: String,
}

#[derive(Debug, Deserialize)]
pub struct EventRepo {
    pub name: String,
}

#[derive(Debug, Deserialize)]
pub struct CommitDetail {
    pub sha: String,
    pub html_url: String,
    pub commit: CommitInfo,
    #[serde(default)]
    pub files: Vec<CommitFile>,
}

#[derive(Debug, Deserialize)]
pub struct CommitInfo {
    pub message: String,
    pub author: CommitAuthor,
}

#[derive(Debug, Deserialize)]
pub struct CommitAuthor {
    pub name: String,
    pub date: String,
}

#[derive(Debug, Deserialize)]
pub struct CommitFile {
    pub filename: String,
    pub status: String,
    pub additions: u64,
    pub deletions: u64,
    pub patch: Option<String>,
}

// ── Client helpers ──────────────────────────────────────────────────────────────

pub(crate) fn build_client() -> anyhow::Result<reqwest::Client> {
    reqwest::Client::builder()
        .user_agent(format!("gitprint/{VERSION}"))
        .build()
        .context("failed to build HTTP client")
}

fn auth_header(token: Option<&str>) -> Option<String> {
    token.map(|t| format!("Bearer {t}"))
}

pub(crate) async fn get_json<T: for<'de> Deserialize<'de>>(
    client: &reqwest::Client,
    url: &str,
    token: Option<&str>,
) -> anyhow::Result<T> {
    let mut req = client
        .get(url)
        .header("Accept", "application/vnd.github+json");
    if let Some(auth) = auth_header(token) {
        req = req.header("Authorization", auth);
    }
    let resp = req.send().await.with_context(|| format!("GET {url}"))?;
    let status = resp.status();
    if status == reqwest::StatusCode::NOT_FOUND {
        bail!("not found: {url}");
    }
    if status == reqwest::StatusCode::FORBIDDEN || status == reqwest::StatusCode::TOO_MANY_REQUESTS
    {
        bail!(
            "GitHub API rate limit exceeded. Set GITHUB_TOKEN to increase limits:\n  \
             export GITHUB_TOKEN=ghp_your_token_here"
        );
    }
    if !status.is_success() {
        bail!("GitHub API error {status}: {url}");
    }
    resp.json::<T>()
        .await
        .with_context(|| format!("parsing response from {url}"))
}

// ── Public API functions ────────────────────────────────────────────────────────

/// Fetch a user's public profile.
pub async fn get_user(username: &str, token: Option<&str>) -> anyhow::Result<GitHubUser> {
    let client = build_client()?;
    let url = format!("{API_BASE}/users/{username}");
    get_json::<GitHubUser>(&client, &url, token)
        .await
        .with_context(|| format!("fetching user '{username}'"))
}

/// Wrapper for the GitHub search/repositories response.
#[derive(Debug, Deserialize)]
struct SearchReposResponse {
    items: Vec<GitHubRepo>,
}

/// Fetch a user's top starred repositories via the Search API.
///
/// Uses `/search/repositories` because `/users/{u}/repos` does not support `sort=stars`.
pub async fn get_user_starred_repos(
    username: &str,
    limit: usize,
    token: Option<&str>,
) -> anyhow::Result<Vec<GitHubRepo>> {
    let client = build_client()?;
    let per_page = limit.min(100);
    let url = format!(
        "{API_BASE}/search/repositories?q=user:{username}+fork:false&sort=stars&order=desc&per_page={per_page}"
    );
    get_json::<SearchReposResponse>(&client, &url, token)
        .await
        .map(|r| r.items)
        .with_context(|| format!("fetching starred repos for '{username}'"))
}

/// Fetch a user's own repositories sorted by `sort` (`pushed` or `updated`).
///
/// `limit` is capped at 100 (GitHub's maximum per-page).
/// Only returns repos the user owns directly (`type=owner`).
pub async fn get_user_repos(
    username: &str,
    sort: &str,
    limit: usize,
    token: Option<&str>,
) -> anyhow::Result<Vec<GitHubRepo>> {
    let client = build_client()?;
    let per_page = limit.min(100);
    let url = format!(
        "{API_BASE}/users/{username}/repos?type=owner&sort={sort}&direction=desc&per_page={per_page}"
    );
    get_json::<Vec<GitHubRepo>>(&client, &url, token)
        .await
        .with_context(|| format!("fetching repos for '{username}' (sort={sort})"))
}

/// Fetch a user's recent public events (max 100, GitHub returns up to 90 days).
pub async fn get_user_events(
    username: &str,
    limit: usize,
    token: Option<&str>,
) -> anyhow::Result<Vec<GitHubEvent>> {
    let client = build_client()?;
    let per_page = limit.min(100);
    let url = format!("{API_BASE}/users/{username}/events/public?per_page={per_page}");
    get_json::<Vec<GitHubEvent>>(&client, &url, token)
        .await
        .with_context(|| format!("fetching events for '{username}'"))
}

/// Response envelope for the commits search endpoint.
#[derive(Deserialize)]
struct CommitSearchResponse {
    items: Vec<CommitSearchItem>,
}

#[derive(Deserialize)]
struct CommitSearchItem {
    sha: String,
    repository: CommitSearchRepo,
    commit: CommitSearchMeta,
}

#[derive(Deserialize)]
struct CommitSearchRepo {
    full_name: String,
}

#[derive(Deserialize)]
struct CommitSearchMeta {
    message: String,
}

/// Search for the `limit` most recent public commits authored by `username` across all repos.
///
/// Uses `GET /search/commits?q=author:{username}` (stable since GitHub API v3 2022+).
/// Returns `(owner/repo, sha, first-line-of-message)` tuples, newest first.
/// Returns an empty Vec on error so the caller can degrade gracefully.
pub async fn search_user_commits(
    username: &str,
    limit: usize,
    token: Option<&str>,
) -> anyhow::Result<Vec<(String, String, String)>> {
    let client = build_client()?;
    let per_page = limit.min(100);
    let url = format!(
        "{API_BASE}/search/commits?q=author:{username}&sort=committer-date&order=desc&per_page={per_page}"
    );
    get_json::<CommitSearchResponse>(&client, &url, token)
        .await
        .map(|r| {
            r.items
                .into_iter()
                .map(|item| {
                    let msg = item
                        .commit
                        .message
                        .lines()
                        .next()
                        .unwrap_or(&item.commit.message)
                        .to_string();
                    (item.repository.full_name, item.sha, msg)
                })
                .collect()
        })
        .with_context(|| format!("searching commits by '{username}'"))
}

/// Fetch a single commit with its file patches.
pub async fn get_commit_detail(
    owner_repo: &str,
    sha: &str,
    token: Option<&str>,
) -> anyhow::Result<CommitDetail> {
    let client = build_client()?;
    let url = format!("{API_BASE}/repos/{owner_repo}/commits/{sha}");
    get_json::<CommitDetail>(&client, &url, token)
        .await
        .with_context(|| format!("fetching commit {sha} in {owner_repo}"))
}

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

    #[test]
    fn auth_header_some() {
        assert_eq!(auth_header(Some("tok")), Some("Bearer tok".to_string()));
    }

    #[test]
    fn auth_header_none() {
        assert_eq!(auth_header(None), None);
    }

    #[tokio::test]
    async fn parses_user_response() -> anyhow::Result<()> {
        let server = MockServer::start();
        server.mock(|when, then| {
            when.method(GET).path("/users/alice");
            then.status(200).json_body(serde_json::json!({
                "login": "alice", "name": "Alice", "bio": null, "location": null,
                "company": null, "blog": null, "email": null, "public_repos": 10,
                "followers": 42, "following": 5, "created_at": "2020-01-01T00:00:00Z",
                "html_url": "https://github.com/alice"
            }));
        });

        let client = build_client()?;
        let user: GitHubUser =
            get_json(&client, &format!("{}/users/alice", server.base_url()), None).await?;
        assert_eq!(user.login, "alice");
        assert_eq!(user.public_repos, 10);
        assert_eq!(user.followers, 42);
        Ok(())
    }

    #[tokio::test]
    async fn parses_repo_list_response() -> anyhow::Result<()> {
        let server = MockServer::start();
        server.mock(|when, then| {
            when.method(GET).path("/users/alice/repos");
            then.status(200).json_body(serde_json::json!([{
                "name": "myrepo", "full_name": "alice/myrepo",
                "html_url": "https://github.com/alice/myrepo", "description": null,
                "language": "Rust", "stargazers_count": 7, "forks_count": 1,
                "pushed_at": "2024-03-01T00:00:00Z", "updated_at": "2024-03-01T00:00:00Z",
                "fork": false
            }]));
        });

        let client = build_client()?;
        let repos: Vec<GitHubRepo> = get_json(
            &client,
            &format!("{}/users/alice/repos", server.base_url()),
            None,
        )
        .await?;
        assert_eq!(repos.len(), 1);
        assert_eq!(repos[0].name, "myrepo");
        assert_eq!(repos[0].stargazers_count, 7);
        Ok(())
    }

    #[tokio::test]
    async fn parses_event_list_response() -> anyhow::Result<()> {
        let server = MockServer::start();
        server.mock(|when, then| {
            when.method(GET).path("/users/alice/events/public");
            then.status(200).json_body(serde_json::json!([{
                "type": "PushEvent",
                "repo": { "name": "alice/myrepo" },
                "payload": { "ref": "refs/heads/main", "commits": [] },
                "created_at": "2024-03-01T12:00:00Z"
            }]));
        });

        let client = build_client()?;
        let events: Vec<GitHubEvent> = get_json(
            &client,
            &format!("{}/users/alice/events/public", server.base_url()),
            None,
        )
        .await?;
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].kind, "PushEvent");
        assert_eq!(events[0].repo.name, "alice/myrepo");
        Ok(())
    }

    #[tokio::test]
    async fn parses_commit_detail_response() -> anyhow::Result<()> {
        let server = MockServer::start();
        let sha = "abc1234abc1234abc1234abc1234abc1234abc1234";
        server.mock(|when, then| {
            when.method(GET)
                .path(format!("/repos/alice/myrepo/commits/{sha}"));
            then.status(200).json_body(serde_json::json!({
                "sha": sha,
                "html_url": "https://github.com/alice/myrepo/commit/abc1234",
                "commit": {
                    "message": "fix: handle edge case",
                    "author": { "name": "Alice", "date": "2024-03-01T12:00:00Z" }
                },
                "files": [{
                    "filename": "src/lib.rs", "status": "modified",
                    "additions": 5, "deletions": 2, "patch": "+added line\n-removed line"
                }]
            }));
        });

        let client = build_client()?;
        let detail: CommitDetail = get_json(
            &client,
            &format!("{}/repos/alice/myrepo/commits/{sha}", server.base_url()),
            None,
        )
        .await?;
        assert_eq!(detail.sha, sha);
        assert_eq!(detail.commit.message, "fix: handle edge case");
        assert_eq!(detail.files[0].additions, 5);
        Ok(())
    }

    #[tokio::test]
    async fn rate_limit_error_is_surfaced() {
        let server = MockServer::start();
        server.mock(|when, then| {
            when.method(GET).path("/users/alice");
            then.status(403);
        });

        let client = build_client().unwrap();
        let err =
            get_json::<GitHubUser>(&client, &format!("{}/users/alice", server.base_url()), None)
                .await
                .unwrap_err();
        assert!(err.to_string().contains("rate limit"), "got: {err}");
    }
}