如何筛选GitHub PR评论中指定用户的最新评论?
从GitHub Issue评论中筛选指定用户的最新评论
我通过以下curl命令获取指定PR的Issue评论列表:
curl -sH "Accept: application/vnd.github+json" -H "Authorization: token XXXXXXXXXX" https://api.github.com/repos/org/repo/issues/12/comments
返回的JSON格式示例如下:
[ { "id": 1, "node_id": "MDEyOklzc3VlQ29tbWVudDE=", "url": "https://api.github.com/repos/octocat/Hello-World/issues/comments/1", "html_url": "https://github.com/octocat/Hello-World/issues/1347#issuecomment-1", "body": "Me too", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "created_at": "2011-04-14T16:00:49Z", "updated_at": "2011-04-14T16:00:49Z", "issue_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347", "author_association": "COLLABORATOR" } ]
我知道可以通过管道输出到jq '.[-1].user.login'获取最后一条评论的作者用户名,但如何从所有匹配user.login=foobar的评论中获取最新的那条?
可以通过jq的过滤、排序和取值组合实现,具体命令如下:
按评论创建时间筛选最新评论
curl -sH "Accept: application/vnd.github+json" -H "Authorization: token XXXXXXXXXX" https://api.github.com/repos/org/repo/issues/12/comments | jq '[.[] | select(.user.login == "foobar")] | sort_by(.created_at) | last'
按评论更新时间筛选最新评论(若评论有编辑场景)
curl -sH "Accept: application/vnd.github+json" -H "Authorization: token XXXXXXXXXX" https://api.github.com/repos/org/repo/issues/12/comments | jq '[.[] | select(.user.login == "foobar")] | sort_by(.updated_at) | last'
命令解释
[.[] | select(.user.login == "foobar")]:先遍历所有评论,筛选出用户登录名为foobar的评论,重新组成数组sort_by(.created_at):按评论的创建时间升序排序(若用updated_at则按更新时间排序)last:取排序后的最后一个元素,即最新的那条评论
如果只需要获取该评论的特定字段,可在末尾追加字段路径,例如:
# 获取最新评论的内容 ... | jq '[.[] | select(.user.login == "foobar")] | sort_by(.created_at) | last.body' # 获取最新评论的作者登录名 ... | jq '[.[] | select(.user.login == "foobar")] | sort_by(.created_at) | last.user.login'
内容的提问来源于stack exchange,提问作者pkaramol
相关产品推荐
相关产品推荐

