Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Don't move issues back & forth in project, reduce API calls for project automation (#765)

Madison Swain-Bowden8522ab6dbc6b
diff --git a/automations/python/issues_with_prs.py b/automations/python/issues_with_prs.py
index 49df53ad9..91c29a5a5 100755
--- a/automations/python/issues_with_prs.py
+++ b/automations/python/issues_with_prs.py
@@ -2,9 +2,10 @@
import argparse
import logging
import sys
+from typing import Literal
import requests
-from github import Github, GithubException, Issue, ProjectCard, ProjectColumn
+from github import Github, ProjectCard, ProjectColumn
from shared.data import get_data
from shared.github import get_access_token, get_client
from shared.log import configure_logger
@@ -13,6 +14,36 @@ from shared.project import get_org_project, get_project_column
log = logging.getLogger(__name__)
+CLOSED = "closed"
+OPEN = "open"
+IssueState = Literal[CLOSED, OPEN]
+# Unique identifier of repo + issue
+RepoIssue = tuple[str, str]
+
+LINKED_PR_QUERY = """
+{
+ repository(owner: "%s", name: "%s") {
+ pullRequests(first: 100, states:%s,
+ orderBy:{field:UPDATED_AT, direction:DESC}) {
+ nodes {
+ number
+ title
+ closingIssuesReferences (first: 50) {
+ edges {
+ node {
+ number
+ title
+ state
+ }
+ }
+ }
+ }
+ }
+ }
+}
+"""
+
+
# region argparse
parser = argparse.ArgumentParser(
description="Move issues to the correct columns in projects",
@@ -46,7 +77,8 @@ parser.add_argument(
dest="linked_pr_state",
metavar="linked-pr-state",
type=str,
- default="open",
+ default=OPEN,
+ choices=[OPEN, CLOSED],
help="filter issues by this state of their linked PRs",
)
@@ -78,12 +110,33 @@ def run_query(
)
+def get_pulls_with_linked_issues(
+ org_handle: str, repo_name: str, state: IssueState
+) -> dict[str, str]:
+ """
+ Query all the pull requests with issues of a linked state.
+
+ This uses the GraphQL API since the REST API doesn't support querying for linked
+ issues.
+
+ :return: a dict of issue numbers to issue titles
+ """
+ results = run_query(LINKED_PR_QUERY % (org_handle, repo_name, state.upper()))
+ pulls = results["repository"]["pullRequests"]["nodes"]
+ log.info(f"Found {len(pulls)} {state} PRs in {org_handle}/{repo_name}")
+ return {
+ issue["node"]["number"]: issue["node"]["title"]
+ for pull in pulls
+ for issue in pull["closingIssuesReferences"]["edges"]
+ }
+
+
def get_open_issues_with_prs(
gh: Github,
org_handle: str,
repo_names: list[str],
linked_pr_state: str,
-) -> set[tuple[str, str]]:
+) -> set[RepoIssue]:
"""
Retrieve open issues with linked PRs.
@@ -100,41 +153,20 @@ def get_open_issues_with_prs(
f"Looking for {linked_pr_state} PRs in {org_handle}/{repo_name} "
f"with linked issues"
)
- results = run_query(
- """
-{
- repository(owner: "%s", name: "%s") {
- pullRequests(first: 100, states:%s,
- orderBy:{field:UPDATED_AT, direction:DESC}) {
- nodes {
- number
- title
- closingIssuesReferences (first: 50) {
- edges {
- node {
- number
- title
- state
- }
- }
- }
- }
- }
- }
-}
- """
- % (org_handle, repo_name, linked_pr_state.upper())
- )
- pulls = results["repository"]["pullRequests"]["nodes"]
- log.info(f"Found {len(pulls)} PRs in {org_handle}/{repo_name}")
- issues = {
- issue["node"]["number"]: issue["node"]["title"]
- for pull in pulls
- for issue in pull["closingIssuesReferences"]["edges"]
- }
+ issues = get_pulls_with_linked_issues(org_handle, repo_name, linked_pr_state)
+ # In the case where we're querying for closed PRs, we'll also need to consider
+ # open PRs - if there's an issue with both an open PR and a closed PR, we should
+ # not take any action on it
+ open_issues = {}
+ if linked_pr_state == CLOSED:
+ open_issues = get_pulls_with_linked_issues(org_handle, repo_name, OPEN)
+
log.info(f"Found {len(issues)} issues")
for number, title in issues.items():
log.info(f"• #{number: >5} | {title}")
+ if linked_pr_state == CLOSED and number in open_issues:
+ log.info(f"{' ' * 11}(skipped because there's an open PR)")
+ continue
all_issues.add((repo_name, number))
log.info(
@@ -144,7 +176,7 @@ def get_open_issues_with_prs(
return all_issues
-def get_issue_cards(col: ProjectColumn) -> list[tuple[ProjectCard, Issue]]:
+def get_issue_cards(col: ProjectColumn) -> list[tuple[ProjectCard, RepoIssue]]:
"""
Get all cards linked to issues in the given column.
@@ -157,13 +189,17 @@ def get_issue_cards(col: ProjectColumn) -> list[tuple[ProjectCard, Issue]]:
cards = col.get_cards(archived_state="not archived")
issue_cards = []
for card in cards:
- issue = card.get_content()
- if issue is None:
- continue
+ # Example URL: https://api.github.com/repos/api-playground/project-test/issues/3
+ # See: https://docs.github.com/en/rest/projects/cards?apiVersion=2022-11-28
+ url = card.content_url
try:
- issue.as_pull_request()
- except GithubException:
- issue_cards.append((card, issue))
+ url_parts = url.split("/")
+ # Repo + issue
+ issue = (url_parts[-3], url_parts[-1])
+ except Exception:
+ log.debug(f"Could not decode card with content_url: {url}")
+ continue
+ issue_cards.append((card, issue))
return issue_cards
@@ -207,7 +243,7 @@ def main():
cards_to_move = []
for issue_card, issue in issue_cards:
- if (issue.repository.name, issue.number) in issues_with_prs:
+ if issue in issues_with_prs:
cards_to_move.append((issue_card, issue))
log.info(f"Found {len(cards_to_move)} cards to move")