---@class GhPrGithub ---@field pr_data PrData? local GhPrGithub = {} ---@param repo_owner string ---@param repo_name string ---@param pr_number integer ---@return string local function construct_gh_comments_url(repo_owner, repo_name, pr_number) local comment_url = { "https://api.github.com/repos/", repo_owner, "/", repo_name, "/pulls/", pr_number, "/comments", } return table.concat(comment_url, "") end ---Fetches PR data from GitHub using gh CLI ---Populates M.pr_data with PR information GhPrGithub.get_pr_data = function() local cmd = "gh pr view --json number,url,headRepositoryOwner,headRepository,state" local res = vim.fn.system(cmd) local pr_result = vim.json.decode(res) local pr_number = pr_result['number'] local repo_name = pr_result['headRepository']['name'] local repo_owner = pr_result['headRepositoryOwner']['login'] GhPrGithub.pr_data = { number = pr_number, repo_name = repo_name, repo_owner = repo_owner, state = pr_result['state'], url = pr_result['url'], comments_url = construct_gh_comments_url(repo_owner, repo_name, pr_number) } end ---Fetches PR comments from GitHub API ---@param callback fun(comments_data: table?, fp_comments: table?) GhPrGithub.get_pr_comments = function(callback) if GhPrGithub.pr_data == nil then GhPrGithub.get_pr_data() end local utils = require('gh-pr-comments.utils') utils.http_get(GhPrGithub.pr_data.comments_url, function(body, err) if err then utils.err_notify("HTTP error: " .. err) callback(nil, nil) return end local res_json = vim.json.decode(body) local comments_data = {} for _, comment in pairs(res_json) do local fp = comment['path'] ---@type Comment local c_data = { body = comment['body'], created_at = comment['created_at'], diff_hunk = comment['diff_hunk'], line = comment['line'], original_line = comment['original_line'], updated_at = comment['updated_at'], user_login = comment['user']['login'], } if comments_data[fp] ~= nil then comments_data[fp][#comments_data[fp] + 1] = c_data else comments_data[fp] = { c_data } end end local fp_comments = {} -- ensure comments are sorted by line numbers in ascending order for fp, items in pairs(comments_data) do fp_comments[fp] = { len = #items } table.sort(items, function(a, b) return a.line < b.line end) end callback(comments_data, fp_comments) end) end return GhPrGithub