Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions doc/guh.txt
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,11 @@ cI Rerun CI jobs. Opens a picker (or use `[count]cI` to skip):
cM Merge PR. |guh-merge|
<Plug>(guh-merge)

gr Start a PR review. All the comments added after that will be treated
as part of this review and remain pending until the review is
submitted with <Plug>(guh-review).
<Plug>(guh-start-review)

cR Review PR (Approve / Comment / Request-changes / Toggle draft).
<Plug>(guh-review)

Expand Down
157 changes: 137 additions & 20 deletions lua/guh/gh.lua
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ function M.get_pr_data(prnum, repo, opts, on_result)
labels(first:20){ nodes{ name } }
number
reviewDecision
reviews(first:20){ nodes{ state body author{login} submittedAt } }
reviews(first:20){ nodes{ id state body author{login} submittedAt } }
title
url
reviewThreads(first:100){
Expand Down Expand Up @@ -473,6 +473,25 @@ local function gh_api(logname, method, endpoint, fields, cb)
end)
end

--- Starts a PR review
---
--- @param pr string
--- @param on_done fun(resp: table)
function M.start_review(pr, on_done)
vim.validate('pr', pr, 'string')
local query = [[
mutation($pullRequestId: ID!) {
addPullRequestReview(input: {pullRequestId: $pullRequestId}) {
pullRequestReview { id state body author{login} submittedAt }
}
}
]]
gh_api('review_start', 'POST', 'graphql', {
{ '-f', 'pullRequestId=' .. pr },
{ '-f', 'query=' .. query },
}, on_done)
end

--- Fetches the user's "Unread" notifications, and stores their thread-ids in the `b:guh.notifications`
--- map (for mark-as-read/done and opportunistic probe-skip), and returns the rendered lines.
---
Expand Down Expand Up @@ -536,8 +555,64 @@ function M.reply_to_comment(prnum, body, reply_to, repo, cb)
}, cb)
end

--- @param repo string "owner/repo"
function M.new_comment(pr, body, path, start_line, line, side, repo, cb)
--- Post a new comment associated with a pending review.
--- If no `review_id` is supplied, github will automatically start a new review
--- or use a pending one if it can find it.
---
--- @param pr_id string
--- @param review_id string?
--- @param body string
--- @param path string
--- @param start_line integer
--- @param line integer
--- @param side string?
--- @param repo string
--- @param cb fun(resp: table)
function M.new_review_comment(pr_id, review_id, body, path, start_line, line, side, repo, cb)
vim.validate('repo', repo, 'string')
local query = [[
mutation($pullRequestId: ID!, $body: String!, $path: String!, $line: Int!, $side: DiffSide!, $startLine: Int, $pullRequestReviewId: ID) {
addPullRequestReviewThread(input: {
pullRequestId: $pullRequestId,
body: $body,
path: $path,
line: $line,
side: $side,
startLine: $startLine,
pullRequestReviewId: $pullRequestReviewId
}) {
thread {
id
}
}
}
]]
local fields = {
{ '-f', 'pullRequestId=' .. pr_id },
{ '-f', 'body=' .. body },
{ '-f', 'path=' .. path },
{ '-F', 'startLine=' .. start_line },
{ '-F', 'line=' .. line },
{ '-f', 'side=' .. (side or 'RIGHT') },
{ '-f', 'query=' .. query },
}
if review_id then
table.insert(fields, { '-f', 'pullRequestReviewId=' .. review_id })
end
gh_api('post_review_comment', 'POST', 'graphql', fields, cb)
end

--- Post a single comment via api endpoint
---
--- @param pr PullRequest
--- @param body string
--- @param path string
--- @param start_line integer
--- @param line integer
--- @param side string?
--- @param repo string
--- @param cb fun(resp: table)
function M.new_single_comment(pr, body, path, start_line, line, side, repo, cb)
local commit_id = assert(pr.headRefOid)
vim.validate('repo', repo, 'string')
local fields = {
Expand Down Expand Up @@ -684,28 +759,70 @@ function M.merge_pr(id, repo, method, subject, body, admin, cb)
end)
end

--- Submits a PR review.
--- @param id integer
--- @param repo string "owner/name"
--- @param action 'approve'|'request-changes'|'comment'
--- Adds a PR review.
--- @param pr_id string
--- @param action 'APPROVE'|'REQUEST_CHANGES'|'COMMENT'
--- @param body? string review body (required for `request-changes` and `comment`).
--- @param cb fun(ok: boolean, stderr: string)
function M.review_pr(id, repo, action, body, cb)
vim.validate('id', id, 'number')
vim.validate('repo', repo, 'string')
--- @param cb fun(resp: table)
function M.review_pr(pr_id, action, body, cb)
vim.validate('pr_id', pr_id, 'string')
vim.validate('action', action, function(a)
return a == 'approve' or a == 'request-changes' or a == 'comment'
end, "'approve'|'request-changes'|'comment'")
return a == 'APPROVE' or a == 'REQUEST_CHANGES' or a == 'COMMENT'
end, "'APPROVE'|'REQUEST_CHANGES'|'COMMENT'")
vim.validate('body', body, 'string', true)
local flag = action == 'approve' and '--approve' or action == 'request-changes' and '--request-changes' or '--comment'
local cmd = M.cmd(repo, 'pr', 'review', tostring(id), flag)
local query = [[
mutation($pullRequestId: ID!, $event: PullRequestReviewEvent!, $body: String) {
addPullRequestReview(input: {
pullRequestId: $pullRequestId,
event: $event,
body: $body
}) {
pullRequestReview {
id
state
}
}
}
]]
local fields = {
{ '-f', 'pullRequestId=' .. pr_id },
{ '-f', 'event=' .. action },
{ '-f', 'query=' .. query },
}
if body and body ~= '' then
table.insert(cmd, '--body')
table.insert(cmd, body)
table.insert(fields, { '-f', 'body=' .. body })
end
util.system(cmd, nil, function(r)
cb(r.code == 0, r.stderr or '')
end)
gh_api('submit_review', 'POST', 'graphql', fields, cb)
end

--- Submits a pending PR review.
--- @param review_id string
--- @param action 'APPROVE'|'REQUEST_CHANGES'|'COMMENT'
--- @param body? string review body (required for `request-changes` and `comment`).
--- @param cb fun(resp: table)
function M.review_pending_pr(review_id, action, body, cb)
vim.validate('review_id', review_id, 'string')
vim.validate('action', action, function(a)
return a == 'APPROVE' or a == 'REQUEST_CHANGES' or a == 'COMMENT'
end, "'APPROVE'|'REQUEST_CHANGES'|'COMMENT'")
vim.validate('body', body, 'string', true)
local query = [[
mutation($reviewId: ID!, $action: PullRequestReviewEvent!, $body: String) {
submitPullRequestReview(input: {pullRequestReviewId: $reviewId, event: $action, body: $body}) {
pullRequestReview {
id
state
}
}
}
]]
local fields = {
{ '-f', 'reviewId=' .. review_id },
{ '-f', 'body=' .. body },
{ '-f', 'action=' .. action },
{ '-f', 'query=' .. query },
}
gh_api('submit_pending_review', 'POST', 'graphql', fields, cb)
end

local cached_user --[[@type string?]]
Expand Down
73 changes: 64 additions & 9 deletions lua/guh/pr.lua
Original file line number Diff line number Diff line change
Expand Up @@ -456,15 +456,35 @@ local function toggle_draft(id, repo, is_draft)
end)
end

--- check if there is a pending review
---
--- @param reviews table
--- @return string?
local function pending_review_id(reviews)
local user = gh.get_user()
local _, pending_review = next(vim.tbl_filter(function(review)
return (review['state'] == 'PENDING') and (review['author']['login'] == user)
end, reviews))
if pending_review then
return pending_review['id']
else
return nil
end
end

--- Performs the "review PR" action. Shows a vim.ui.select picker unless `[count]` was given.
---
--- Each action opens an editable `guh://<owner>/<repo>/review/<id>` buffer for the (optional) body.
function M.review_pr()
local _, id, repo = require_pr()
local pr, _ = state.get_pr_data(repo, id)
if not pr then
return util.msg(('PR #%s not found'):format(id), vim.log.levels.ERROR)
end

--- @async
local function do_action(label)
local gh_action = label:lower()
local gh_action, _ = label:upper():gsub('-', '_')
local heading = ('%s PR #%s'):format(label, id)
-- Prefill ":+1:" in the Approve body, so the user can Approve without writing a comment. #64
local content = label == 'Approve' and { ':+1:' } or { '' }
Expand All @@ -473,12 +493,15 @@ function M.review_pr()
return
end
local done = util.progress(('%s…'):format(heading))
local ok, stderr = async.await(5, gh.review_pr, id, repo, gh_action, vim.trim(input))
if ok then
done('success')
local body = vim.trim(input)
local review_id = pending_review_id(pr.reviews)
local resp
if review_id then
resp = async.await(4, gh.review_pending_pr, review_id, gh_action, body)
else
done('failed', vim.trim(stderr))
resp = async.await(4, gh.review_pr, pr.node_id, gh_action, body)
end
done(resp['errors'] and 'failed' or 'success', util.gh_errors(resp))
end

-- Menu item 4 toggles "Draft"/"Ready".
Expand Down Expand Up @@ -1012,21 +1035,27 @@ local function new_comment(pr_id, repo, line1, line2)
end
util.hl_flash(buf, line1 - 1, line2 - 1)
util.run_async(function()
local pr, err = await_get_pr_data(pr_id, repo, nil)
local pr = state.get_pr_data(repo, pr_id)
if not pr then
return util.msg(err or ('PR #%s not found'):format(pr_id), vim.log.levels.ERROR)
return util.msg(('PR #%s not found'):format(pr_id), vim.log.levels.ERROR)
end
local range = info.start_line == info.end_line and tostring(info.end_line)
or ('%d..%d'):format(info.start_line, info.end_line)
local title = ('Comment on %s:%s'):format(info.file, range)
-- Defer, in case get_pr_data() returned synchronously (cache hit).
-- Defer, to leave any fast-event/textlock context.
async.await(vim.schedule)
local input = await_edit_comment('comment', pr_id, { '' }, { title = title })
if not input then
return
end
local progress = util.new_progress_report('Sending comment...', vim.api.nvim_get_current_buf())
local resp = async.await(8, gh.new_comment, pr, input, info.file, info.start_line, info.end_line, info.side, repo)
local review_id = pending_review_id(pr.reviews)
local resp
if review_id then
resp = async.await(9, gh.new_review_comment, pr.node_id, review_id, input, info.file, info.start_line, info.end_line, info.side, repo)
else
resp = async.await(8, gh.new_single_comment, pr, input, info.file, info.start_line, info.end_line, info.side, repo)
end
if resp['errors'] == nil then
progress('success', nil, 'Comment sent.')
M.refresh({ feat = 'pr', id = pr_id, repo = repo })
Expand Down Expand Up @@ -1089,6 +1118,32 @@ function M.comment(args)
new_comment(id, repo, args.line1, args.line2)
end


--- Start a PR review
---
--- @return string?
function M.start_review()
local _, id, repo = resolve_pr()
local pr_buf = state.get_buf('pr', repo, id, false)
local pr_data = state.get_pr_data(repo, id)
if not pr_data or not pr_data.node_id then
return util.msg(('Empty pr_data or node_id for PR #%s'):format(id), vim.log.levels.ERROR)
end
vim.schedule(function()
gh.start_review(pr_data.node_id, function(resp)
local review = vim.tbl_get(resp, 'data', 'addPullRequestReview', 'pullRequestReview')
if review == nil then
return util.msg(('Failed start a review for PR #%s'):format(id), vim.log.levels.ERROR)
else
local reviews = pr_data.reviews
table.insert(reviews, review)
state.set_b_key(assert(pr_buf), {'guh', 'pr_data', 'reviews'}, reviews)
return util.msg(('Started a review for PR#%s'):format(id), vim.log.levels.INFO)
end
end)
end)
end

--- Runs `gh pr edit <id>` (or `gh issue edit <id>`) in a :terminal.
function M.edit_pr()
local feat, id, repo = resolve_pr()
Expand Down
1 change: 1 addition & 0 deletions lua/guh/util.lua
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,7 @@ function M.set_default_keymaps(buf)
M.map_default(buf, 'n', 'c:', '<Plug>(guh-edit)', 'Edit PR/issue properties (`gh pr edit`, `gh issue edit`)')
M.map_default(buf, 'n', 'cM', '<Plug>(guh-merge)', 'Merge PR')
M.map_default(buf, 'n', 'cV', '<Plug>(guh-notif-read)', 'Mark PR/issue notification as read')
M.map_default(buf, 'n', 'gr', '<Plug>(guh-start-review)', 'Start PR Review')
M.map_default(buf, 'n', 'cR', '<Plug>(guh-review)', 'Review PR (approve/request-changes/comment)')

-- Cursor-relative actions:
Expand Down
3 changes: 3 additions & 0 deletions plugin/guh.lua
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,9 @@ end, opts)
vim.keymap.set('n', '<Plug>(guh-notif-read)', function()
require('guh.pr').set_read()
end, opts)
vim.keymap.set('n', '<Plug>(guh-start-review)', function()
require('guh.pr').start_review()
end, opts)
vim.keymap.set('n', '<Plug>(guh-review)', function()
require('guh.pr').review_pr()
end, opts)
Expand Down