githubdw 0.2.1

Local SQLite data warehouse for GitHub repositories: sync PRs, reviews, and issues; query, metrics, fulltext search, and MCP server
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
//! Pull-request fetching: GraphQL query text and typed parsing of responses.

use serde_json::Value;

use crate::error::{Error, Result};

/// GraphQL query for a repository's pull requests with nested reviews,
/// review-thread comments, conversation comments, files, and check runs.
/// `page_size` tunes the outer page: large repos with heavy PRs can overflow
/// GitHub's response stream at 25, so the syncer degrades adaptively.
pub fn repository_pull_requests_query(page_size: u32) -> String {
    REPOSITORY_PULL_REQUESTS_QUERY_TEMPLATE.replace("{PAGE_SIZE}", &page_size.to_string())
}

const REPOSITORY_PULL_REQUESTS_QUERY_TEMPLATE: &str = r#"
query($owner: String!, $name: String!, $cursor: String) {
  rateLimit { limit cost remaining resetAt }
  repository(owner: $owner, name: $name) {
    nameWithOwner
    primaryLanguage { name }
    isFork
    isPrivate
    defaultBranchRef { name }
    createdAt
    pullRequests(first: {PAGE_SIZE}, after: $cursor,
                 orderBy: {field: UPDATED_AT, direction: DESC}) {
      pageInfo { hasNextPage endCursor }
      nodes {
        number title body state isDraft
        createdAt updatedAt mergedAt closedAt
        baseRefName headRefName
        additions deletions changedFiles
        author { login __typename }
        mergedBy { login __typename }
        reviews(first: 50) {
          nodes {
            id state body submittedAt
            author { login __typename }
          }
        }
        reviewThreads(first: 50) {
          nodes {
            comments(first: 50) {
              nodes {
                id body path line createdAt
                author { login __typename }
                replyTo { id }
              }
            }
          }
        }
        comments(first: 50) {
          nodes {
            id body createdAt
            author { login __typename }
          }
        }
        files(first: 100) {
          nodes { path changeType additions deletions }
        }
        commits(last: 1) {
          nodes {
            commit {
              oid
              checkSuites(first: 10) {
                nodes {
                  checkRuns(first: 20) {
                    nodes { id name status conclusion startedAt completedAt }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
"#;

/// An actor reference from GraphQL (`author { login __typename }`).
#[derive(Debug, Clone, PartialEq)]
pub struct ActorReference {
    pub login: String,
    pub type_name: String,
}

impl ActorReference {
    fn from_value(value: &Value) -> Option<Self> {
        let login = value.get("login")?.as_str()?.to_string();
        let type_name = value
            .get("__typename")
            .and_then(Value::as_str)
            .unwrap_or("User")
            .to_string();
        Some(Self { login, type_name })
    }
}

/// Repository metadata from the query header.
#[derive(Debug, Clone)]
pub struct RepositoryMetadata {
    pub name_with_owner: String,
    pub primary_language: Option<String>,
    pub is_fork: bool,
    pub is_private: bool,
    pub default_branch: Option<String>,
    pub created_at: Option<String>,
}

/// One parsed pull request with all nested collections.
#[derive(Debug, Clone)]
pub struct PullRequestData {
    pub number: i64,
    pub title: Option<String>,
    pub body: Option<String>,
    pub state: String,
    pub is_draft: bool,
    pub created_at: String,
    pub updated_at: Option<String>,
    pub merged_at: Option<String>,
    pub closed_at: Option<String>,
    pub base_ref: Option<String>,
    pub head_ref: Option<String>,
    pub additions: i64,
    pub deletions: i64,
    pub changed_files: i64,
    pub author: Option<ActorReference>,
    pub merged_by: Option<ActorReference>,
    pub reviews: Vec<ReviewData>,
    pub review_comments: Vec<ReviewCommentData>,
    pub conversation_comments: Vec<ConversationCommentData>,
    pub files: Vec<FileDiffData>,
    pub head_sha: Option<String>,
    pub check_runs: Vec<CheckRunData>,
}

#[derive(Debug, Clone)]
pub struct ReviewData {
    pub id: String,
    pub state: String,
    pub body: Option<String>,
    pub submitted_at: Option<String>,
    pub author: Option<ActorReference>,
}

#[derive(Debug, Clone)]
pub struct ReviewCommentData {
    pub id: String,
    pub body: Option<String>,
    pub path: Option<String>,
    pub line: Option<i64>,
    pub created_at: String,
    pub author: Option<ActorReference>,
    pub in_reply_to: Option<String>,
}

#[derive(Debug, Clone)]
pub struct ConversationCommentData {
    pub id: String,
    pub body: Option<String>,
    pub created_at: String,
    pub author: Option<ActorReference>,
}

#[derive(Debug, Clone)]
pub struct FileDiffData {
    pub path: String,
    pub change_type: String,
    pub additions: i64,
    pub deletions: i64,
}

#[derive(Debug, Clone)]
pub struct CheckRunData {
    pub id: String,
    pub name: String,
    pub status: String,
    pub conclusion: Option<String>,
    pub started_at: Option<String>,
    pub completed_at: Option<String>,
}

/// One page of PR results.
#[derive(Debug)]
pub struct PullRequestPage {
    pub repository: RepositoryMetadata,
    pub pull_requests: Vec<PullRequestData>,
    pub has_next_page: bool,
    pub end_cursor: Option<String>,
}

fn string_field(value: &Value, field: &str) -> Option<String> {
    value.get(field).and_then(Value::as_str).map(str::to_string)
}

fn integer_field(value: &Value, field: &str) -> i64 {
    value.get(field).and_then(Value::as_i64).unwrap_or(0)
}

fn nodes<'a>(value: &'a Value, collection: &str) -> Vec<&'a Value> {
    value
        .get(collection)
        .and_then(|c| c.get("nodes"))
        .and_then(Value::as_array)
        .map(|array| array.iter().collect())
        .unwrap_or_default()
}

/// Parse one page of the repository pull-requests query response (`data` value).
pub fn parse_pull_request_page(data: &Value) -> Result<PullRequestPage> {
    let repository = data
        .get("repository")
        .filter(|value| !value.is_null())
        .ok_or_else(|| Error::GitHubApi("repository not found in response".into()))?;

    let metadata = RepositoryMetadata {
        name_with_owner: string_field(repository, "nameWithOwner")
            .ok_or_else(|| Error::GitHubApi("repository.nameWithOwner missing".into()))?,
        primary_language: repository
            .get("primaryLanguage")
            .and_then(|language| language.get("name"))
            .and_then(Value::as_str)
            .map(str::to_string),
        is_fork: repository
            .get("isFork")
            .and_then(Value::as_bool)
            .unwrap_or(false),
        is_private: repository
            .get("isPrivate")
            .and_then(Value::as_bool)
            .unwrap_or(false),
        default_branch: repository
            .get("defaultBranchRef")
            .and_then(|reference| reference.get("name"))
            .and_then(Value::as_str)
            .map(str::to_string),
        created_at: string_field(repository, "createdAt"),
    };

    let pull_requests_value = repository
        .get("pullRequests")
        .ok_or_else(|| Error::GitHubApi("repository.pullRequests missing".into()))?;

    let page_info = pull_requests_value.get("pageInfo");
    let has_next_page = page_info
        .and_then(|info| info.get("hasNextPage"))
        .and_then(Value::as_bool)
        .unwrap_or(false);
    let end_cursor = page_info
        .and_then(|info| info.get("endCursor"))
        .and_then(Value::as_str)
        .map(str::to_string);

    let mut pull_requests = Vec::new();
    for node in nodes(repository, "pullRequests") {
        pull_requests.push(parse_pull_request(node)?);
    }

    Ok(PullRequestPage {
        repository: metadata,
        pull_requests,
        has_next_page,
        end_cursor,
    })
}

fn parse_pull_request(node: &Value) -> Result<PullRequestData> {
    let number = node
        .get("number")
        .and_then(Value::as_i64)
        .ok_or_else(|| Error::GitHubApi("pull request number missing".into()))?;
    let created_at = string_field(node, "createdAt")
        .ok_or_else(|| Error::GitHubApi(format!("PR #{number} has no createdAt")))?;

    let reviews = nodes(node, "reviews")
        .into_iter()
        .filter_map(|review| {
            Some(ReviewData {
                id: string_field(review, "id")?,
                state: string_field(review, "state").unwrap_or_else(|| "COMMENTED".into()),
                body: string_field(review, "body").filter(|body| !body.is_empty()),
                submitted_at: string_field(review, "submittedAt"),
                author: review.get("author").and_then(ActorReference::from_value),
            })
        })
        .collect();

    let mut review_comments = Vec::new();
    for thread in nodes(node, "reviewThreads") {
        for comment in nodes(thread, "comments") {
            let Some(id) = string_field(comment, "id") else {
                continue;
            };
            let Some(created) = string_field(comment, "createdAt") else {
                continue;
            };
            review_comments.push(ReviewCommentData {
                id,
                body: string_field(comment, "body"),
                path: string_field(comment, "path"),
                line: comment.get("line").and_then(Value::as_i64),
                created_at: created,
                author: comment.get("author").and_then(ActorReference::from_value),
                in_reply_to: comment
                    .get("replyTo")
                    .and_then(|reply| reply.get("id"))
                    .and_then(Value::as_str)
                    .map(str::to_string),
            });
        }
    }

    let conversation_comments = nodes(node, "comments")
        .into_iter()
        .filter_map(|comment| {
            Some(ConversationCommentData {
                id: string_field(comment, "id")?,
                body: string_field(comment, "body"),
                created_at: string_field(comment, "createdAt")?,
                author: comment.get("author").and_then(ActorReference::from_value),
            })
        })
        .collect();

    let files = nodes(node, "files")
        .into_iter()
        .filter_map(|file| {
            Some(FileDiffData {
                path: string_field(file, "path")?,
                change_type: string_field(file, "changeType").unwrap_or_else(|| "MODIFIED".into()),
                additions: integer_field(file, "additions"),
                deletions: integer_field(file, "deletions"),
            })
        })
        .collect();

    let mut head_sha = None;
    let mut check_runs = Vec::new();
    for commit_node in nodes(node, "commits") {
        let Some(commit) = commit_node.get("commit") else {
            continue;
        };
        head_sha = string_field(commit, "oid");
        for suite in nodes(commit, "checkSuites") {
            for check in nodes(suite, "checkRuns") {
                let Some(id) = string_field(check, "id") else {
                    continue;
                };
                check_runs.push(CheckRunData {
                    id,
                    name: string_field(check, "name").unwrap_or_default(),
                    status: string_field(check, "status").unwrap_or_else(|| "COMPLETED".into()),
                    conclusion: string_field(check, "conclusion"),
                    started_at: string_field(check, "startedAt"),
                    completed_at: string_field(check, "completedAt"),
                });
            }
        }
    }

    Ok(PullRequestData {
        number,
        title: string_field(node, "title"),
        body: string_field(node, "body"),
        state: string_field(node, "state").unwrap_or_else(|| "OPEN".into()),
        is_draft: node
            .get("isDraft")
            .and_then(Value::as_bool)
            .unwrap_or(false),
        created_at,
        updated_at: string_field(node, "updatedAt"),
        merged_at: string_field(node, "mergedAt"),
        closed_at: string_field(node, "closedAt"),
        base_ref: string_field(node, "baseRefName"),
        head_ref: string_field(node, "headRefName"),
        additions: integer_field(node, "additions"),
        deletions: integer_field(node, "deletions"),
        changed_files: integer_field(node, "changedFiles"),
        author: node.get("author").and_then(ActorReference::from_value),
        merged_by: node.get("mergedBy").and_then(ActorReference::from_value),
        reviews,
        review_comments,
        conversation_comments,
        files,
        head_sha,
        check_runs,
    })
}

/// Parse the REST `/repos/{owner}/{name}/pulls/{number}/files` response into
/// (path, previous_path, patch) tuples for patch backfill.
pub fn parse_rest_file_patches(value: &Value) -> Vec<(String, Option<String>, Option<String>)> {
    let Some(files) = value.as_array() else {
        return Vec::new();
    };
    files
        .iter()
        .filter_map(|file| {
            let path = string_field(file, "filename")?;
            let previous_path = string_field(file, "previous_filename");
            let patch = string_field(file, "patch");
            Some((path, previous_path, patch))
        })
        .collect()
}

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

    fn sample_page() -> Value {
        json!({
            "repository": {
                "nameWithOwner": "octocat/hello",
                "primaryLanguage": {"name": "Rust"},
                "isFork": false,
                "isPrivate": false,
                "defaultBranchRef": {"name": "main"},
                "createdAt": "2020-01-01T00:00:00Z",
                "pullRequests": {
                    "pageInfo": {"hasNextPage": true, "endCursor": "CURSOR1"},
                    "nodes": [{
                        "number": 7,
                        "title": "Add rate limiter",
                        "body": "Implements client-side pacing",
                        "state": "MERGED",
                        "isDraft": false,
                        "createdAt": "2026-01-05T18:00:00Z",
                        "updatedAt": "2026-01-06T09:00:00Z",
                        "mergedAt": "2026-01-06T09:00:00Z",
                        "closedAt": "2026-01-06T09:00:00Z",
                        "baseRefName": "main",
                        "headRefName": "feature/rate-limit",
                        "additions": 120,
                        "deletions": 4,
                        "changedFiles": 3,
                        "author": {"login": "octocat", "__typename": "User"},
                        "mergedBy": {"login": "hubot", "__typename": "User"},
                        "reviews": {"nodes": [{
                            "id": "REV1", "state": "APPROVED", "body": "LGTM",
                            "submittedAt": "2026-01-06T08:00:00Z",
                            "author": {"login": "hubot", "__typename": "User"}
                        }]},
                        "reviewThreads": {"nodes": [{
                            "comments": {"nodes": [{
                                "id": "RC1", "body": "nit: rename",
                                "path": "src/lib.rs", "line": 10,
                                "createdAt": "2026-01-05T20:00:00Z",
                                "author": {"login": "hubot", "__typename": "User"},
                                "replyTo": null
                            }]}
                        }]},
                        "comments": {"nodes": [{
                            "id": "IC1", "body": "Looks good overall",
                            "createdAt": "2026-01-05T19:00:00Z",
                            "author": {"login": "dependabot[bot]", "__typename": "Bot"}
                        }]},
                        "files": {"nodes": [{
                            "path": "src/lib.rs", "changeType": "MODIFIED",
                            "additions": 100, "deletions": 2
                        }]},
                        "commits": {"nodes": [{
                            "commit": {
                                "oid": "abc123",
                                "checkSuites": {"nodes": [{
                                    "checkRuns": {"nodes": [{
                                        "id": "CHK1", "name": "build",
                                        "status": "COMPLETED", "conclusion": "SUCCESS",
                                        "startedAt": "2026-01-05T18:05:00Z",
                                        "completedAt": "2026-01-05T18:10:00Z"
                                    }]}
                                }]}
                            }
                        }]}
                    }]
                }
            }
        })
    }

    #[test]
    fn parses_full_page() {
        let page = parse_pull_request_page(&sample_page()).expect("parse page");
        assert_eq!(page.repository.name_with_owner, "octocat/hello");
        assert_eq!(page.repository.primary_language.as_deref(), Some("Rust"));
        assert!(page.has_next_page);
        assert_eq!(page.end_cursor.as_deref(), Some("CURSOR1"));
        assert_eq!(page.pull_requests.len(), 1);

        let pull_request = &page.pull_requests[0];
        assert_eq!(pull_request.number, 7);
        assert_eq!(pull_request.state, "MERGED");
        assert_eq!(pull_request.author.as_ref().unwrap().login, "octocat");
        assert_eq!(pull_request.reviews.len(), 1);
        assert_eq!(pull_request.reviews[0].state, "APPROVED");
        assert_eq!(pull_request.review_comments.len(), 1);
        assert_eq!(
            pull_request.review_comments[0].path.as_deref(),
            Some("src/lib.rs")
        );
        assert_eq!(pull_request.conversation_comments.len(), 1);
        assert_eq!(
            pull_request.conversation_comments[0]
                .author
                .as_ref()
                .unwrap()
                .type_name,
            "Bot"
        );
        assert_eq!(pull_request.files.len(), 1);
        assert_eq!(pull_request.head_sha.as_deref(), Some("abc123"));
        assert_eq!(pull_request.check_runs.len(), 1);
        assert_eq!(
            pull_request.check_runs[0].conclusion.as_deref(),
            Some("SUCCESS")
        );
    }

    #[test]
    fn parses_rest_file_patches() {
        let value = json!([
            {"filename": "src/lib.rs", "patch": "@@ -1 +1 @@"},
            {"filename": "renamed.rs", "previous_filename": "old.rs", "patch": null}
        ]);
        let patches = parse_rest_file_patches(&value);
        assert_eq!(patches.len(), 2);
        assert_eq!(patches[0].0, "src/lib.rs");
        assert_eq!(patches[0].2.as_deref(), Some("@@ -1 +1 @@"));
        assert_eq!(patches[1].1.as_deref(), Some("old.rs"));
    }
}