From 314c771784b329b679c1fe79d443549cc178e1e5 Mon Sep 17 00:00:00 2001 From: Andrey Antukh Date: Thu, 19 Nov 2026 18:46:49 +0000 Subject: [PATCH] :wrench: Add create-issue shortcut with Issue Type in gh.py Create an issue and assign its Issue Type in one command instead of the manual create-then-mutate flow. The type name is case-insensitive and the command prints the issue number, URL, title and type as JSON. Add unit tests for the full flow, labels, invalid types, gh failures and the CLI output, and update the gh, creating-issues and create-issue skill documentation. AI-assisted-by: hy4-flash-free --- .agents/skills/create-issue/SKILL.md | 5 + .serena/memories/critical-info.md | 2 +- .serena/memories/scripts/gh.md | 20 +++ .serena/memories/workflow/creating-issues.md | 2 + scripts/gh.py | 143 +++++++++++++++++++ scripts/test_gh.py | 143 +++++++++++++++++++ 6 files changed, 314 insertions(+), 1 deletion(-) diff --git a/.agents/skills/create-issue/SKILL.md b/.agents/skills/create-issue/SKILL.md index 0d85f19981..76bf8ad336 100644 --- a/.agents/skills/create-issue/SKILL.md +++ b/.agents/skills/create-issue/SKILL.md @@ -29,3 +29,8 @@ right flow. Everything else (title derivation, metadata policy, body templates, Issue Type IDs, create/verify/cleanup commands) lives in the memory — go to the matching section there. + +For the creation step, `python3 scripts/gh.py create-issue --type +--title "..." --body-file ` creates the issue and sets its Issue Type in +one command (see `mem:scripts/gh`). Title derivation, body templates and +verification still follow `mem:workflow/creating-issues`. diff --git a/.serena/memories/critical-info.md b/.serena/memories/critical-info.md index 19c74e4d98..ce3284686a 100644 --- a/.serena/memories/critical-info.md +++ b/.serena/memories/critical-info.md @@ -59,7 +59,7 @@ The memory is structured in a way that you can get the critical information abou - `scripts/paren-repair` — Fix mismatched delimiters in Clojure/CLJS files and reformat with cljfmt. Run before lint checks when LLM edits break parens. See `mem:scripts/paren-repair`. - `scripts/psql` — PostgreSQL client wrapper with devenv defaults. Companion: `scripts/db-schema` for DDL dumps. See `mem:scripts/psql`. - `scripts/taiga.py` — Fetch public issues, user stories, and tasks from the Penpot Taiga project without authentication. See `mem:scripts/taiga`. -- `scripts/gh.py` — GitHub operations helper: list milestone issues, fetch PR details, compare against CHANGES.md. Requires `gh` CLI. See `mem:scripts/gh`. +- `scripts/gh.py` — GitHub operations helper: list milestone issues, fetch PR details, compare against CHANGES.md, create issues with their Issue Type in one command. Requires `gh` CLI. See `mem:scripts/gh`. - `scripts/coverage-summary.mjs` — Renders an lcov file as a markdown table grouped by source area, for `$GITHUB_STEP_SUMMARY` (`--title`, `--lcov`, optional `--note`, `--unloaded`). Used by the backend, common and frontend test workflows; module coverage commands are in `mem:backend/testing`, `mem:common/testing`, `mem:frontend/testing`. - `scripts/coverage-comment.mjs` — Keeps one PR comment (``) with the coverage table of Backend, Common, Frontend and Render WASM, in the format of the Vitest Coverage Report Action (status, metric, %, covered/total, changed-file coverage, run/commit footer). Each test job updates its own project: the data of all three lives base64-encoded in a hidden `coverage-data` block, and the job re-reads after `SETTLE_MS` and rewrites if a concurrent job dropped its data; extra report comments from simultaneous creates are merged and deleted. Targets (`THRESHOLDS`, per project and metric, status colour only, never fail CI) are on lines only: 70 Backend, 70 Common, 50 Frontend, 40 Render WASM; other metrics get the blue dot. Statements are Clojure forms for Backend/Common (`--emma-xml`) and llvm regions for Render WASM (`--llvm-json`). Shared lcov parsing: `scripts/coverage-lcov.mjs`. The test workflows run it only for PRs from branches of this repo (job-level `pull-requests: write`, `continue-on-error`): fork PRs get a read-only token, so they only get the run-page summary. A fork-safe `workflow_run` commenter would run only from the default branch's copy of the workflow. - `scripts/project-anomalies.py` — Main-board anomaly check for a milestone (`check` writes `tmp/-ANOMALIES.md`). Bulk resolution via `scripts/gh.py`. See `mem:scripts/project-anomalies`. diff --git a/.serena/memories/scripts/gh.md b/.serena/memories/scripts/gh.md index d9775f3d82..014a63ce8c 100644 --- a/.serena/memories/scripts/gh.md +++ b/.serena/memories/scripts/gh.md @@ -10,6 +10,7 @@ repository via GraphQL and REST APIs through the authenticated `gh` CLI. - Fetching PR details by number or by milestone. - Comparing milestone issues against CHANGES.md to find missing entries. - Explicitly linking a GitHub issue to a pull request. +- Creating an issue with its Issue Type set in a single command. - Listing or inspecting GitHub Security Advisories (GHSA). - Fetching issue comments (the `## Breaking change note` markdown for the changelog). @@ -104,6 +105,25 @@ python3 scripts/gh.py link-issue The command resolves both node IDs and calls `addCloseIssueReferences`. It trusts the successful mutation instead of re-querying, because GitHub does not reliably report mutation-created links through `closedByPullRequestsReferences(userLinkedOnly: true)`. It is safe to rerun and works for merged PRs. It does not guarantee the issue stays open: adding `Closes #N` to the body of an already-merged PR closed the issue immediately when tried (#12896 / PR #12067, 2026-11-09). JSON goes to stdout; progress and errors go to stderr; a missing issue/PR or a failed mutation exits non-zero. +### `create-issue` + +Create an issue and set its Issue Type in one command. `gh issue create` cannot set the type, so the script runs `gh issue create` (always with `--project Main` by default) and then two GraphQL calls: one to get the issue's node ID and one `updateIssue` mutation to set the type. The issue number is parsed from the URL returned by `gh issue create`. + +```bash +python3 scripts/gh.py create-issue \ + --type task \ + --title "Expand backend email tests" \ + --body-file /tmp/issue-body.md + +# Optional label (comma-separated); no --milestone (set it later if needed) +python3 scripts/gh.py create-issue --type bug --title "..." \ + --body-file /tmp/issue-body.md --label "breaking change" +``` + +`--type` is a name from the Issue Type table in `mem:workflow/creating-issues` (`bug`, `enhancement`, `feature`, `task`, `question`, `docs`, `epic`); it is case-insensitive and the ID mapping lives in `ISSUE_TYPE_IDS` in `scripts/gh.py`. The command prints JSON with `number`, `url`, `title` and `issue_type` to stdout, and progress to stderr. If the type assignment fails after creation, the issue is left in place and the error reports its number and URL so it can be fixed by hand. This shortcut does not replace the workflow in `mem:workflow/creating-issues`: title derivation, body templates and verification still follow that memory. + +**Output**: JSON object on stdout; progress and errors on stderr. A bad type, a `gh` failure, or a type that was not applied exits non-zero. + ### `advisories` List or inspect GitHub Security Advisories for the repository. diff --git a/.serena/memories/workflow/creating-issues.md b/.serena/memories/workflow/creating-issues.md index 2275cc9d8d..00ce75edd5 100644 --- a/.serena/memories/workflow/creating-issues.md +++ b/.serena/memories/workflow/creating-issues.md @@ -123,6 +123,8 @@ gh issue create \ Output: `https://github.com/penpot/penpot/issues/` +**Shortcut:** `python3 scripts/gh.py create-issue --type --title "..." --body-file /tmp/issue-body.md` does the creation and the Issue Type assignment in one command (see `mem:scripts/gh`). Title derivation, body templates and verification in this memory still apply. + ## Setting the Issue Type `gh issue create` can't set Issue Type directly. Use GraphQL after creation. diff --git a/scripts/gh.py b/scripts/gh.py index a94c5be8fb..17824885ef 100755 --- a/scripts/gh.py +++ b/scripts/gh.py @@ -11,6 +11,7 @@ Subcommands: prs Fetch details for one or more PRs (by number or milestone) advisories List or inspect GitHub security advisories link-issue Explicitly link a GitHub issue to a pull request + create-issue Create an issue and set its Issue Type in one command Usage: python3 scripts/gh.py issues (default: state=closed) @@ -34,6 +35,8 @@ Usage: python3 scripts/gh.py advisories --patched-version 2.19.1 (filter by patched version) python3 scripts/gh.py advisories GHSA-xvj6-fh9w-gjw7 (single advisory detail) python3 scripts/gh.py link-issue 11235 11243 + python3 scripts/gh.py create-issue --type task \ + --title "Expand backend email tests" --body-file /tmp/issue-body.md Prerequisites: - gh CLI authenticated (gh auth status) @@ -132,6 +135,126 @@ def run_gh_rest(path: str) -> Any: fail_gh(err.stderr) +# ───────────────────────────────────────────── +# Subcommand: create-issue +# ───────────────────────────────────────────── + +# Issue Type node IDs in penpot/penpot. ``gh issue create`` cannot set the +# Issue Type, so it is assigned with a follow-up GraphQL mutation. +ISSUE_TYPE_IDS = { + "bug": "IT_kwDOAcyBPM4AX5Nb", + "enhancement": "IT_kwDOAcyBPM4B_IQN", + "feature": "IT_kwDOAcyBPM4AX5Nf", + "task": "IT_kwDOAcyBPM4AX5NY", + "question": "IT_kwDOAcyBPM4B_IQj", + "docs": "IT_kwDOAcyBPM4B_IQz", + "epic": "IT_kwDOAcyBPM4CEMzF", +} + +ISSUE_URL_RE = re.compile(r"/issues/(\d+)") + +GQL_ISSUE_NODE_ID_QUERY = """\ +query($owner: String!, $repo: String!, $issueNumber: Int!) { + repository(owner: $owner, name: $repo) { + issue(number: $issueNumber) { id } + } +} +""" + +GQL_UPDATE_ISSUE_TYPE = """\ +mutation($issueId: ID!, $issueTypeId: ID!) { + updateIssue(input: {id: $issueId, issueTypeId: $issueTypeId}) { + issue { number issueType { name } } + } +} +""" + + +def create_issue( + title: str, + body_file: str, + issue_type: str, + labels: str | None = None, + project: str = "Main", +) -> dict: + """Create an issue and assign its Issue Type in one sequence of calls. + + ``gh issue create`` returns the issue URL, so the number is parsed from + it. The Issue Type is then set through GraphQL: a failure at that point + leaves the issue in place and reports its number and URL for a manual fix. + """ + issue_type = issue_type.lower() + type_id = ISSUE_TYPE_IDS.get(issue_type) + if not type_id: + raise ValueError(f"unknown issue type: {issue_type}") + if not title.strip(): + raise ValueError("issue title must not be empty") + + cmd = [ + "gh", "issue", "create", + "--repo", REPO, + "--title", title, + "--project", project, + "--body-file", body_file, + ] + if labels: + cmd += ["--label", labels] + stdout = run_gh_command(cmd) + url = stdout.strip().splitlines()[-1].strip() + match = ISSUE_URL_RE.search(url) + if not match: + raise RuntimeError( + f"could not read issue number from gh output: {url!r};" + " check whether the issue was created" + ) + number = int(match.group(1)) + + node_data = run_gh_graphql( + GQL_ISSUE_NODE_ID_QUERY, + {"owner": OWNER, "repo": REPO_NAME, "issueNumber": number}, + ) + issue = (node_data.get("repository") or {}).get("issue") or {} + if not issue.get("id"): + raise RuntimeError( + f"issue #{number} was created ({url}) but was not found in {REPO};" + f" set the {issue_type} type manually" + ) + + mutation_data = run_gh_graphql( + GQL_UPDATE_ISSUE_TYPE, + {"issueId": issue["id"], "issueTypeId": type_id}, + ) + updated = (mutation_data.get("updateIssue") or {}).get("issue") or {} + type_name = (updated.get("issueType") or {}).get("name") + if str(type_name).lower() != issue_type.lower(): + raise RuntimeError( + f"issue #{number} was created ({url}) but its type is" + f" {type_name!r} instead of {issue_type!r}; set it manually" + ) + + return { + "number": number, + "url": url, + "title": title, + "issue_type": issue_type, + } + + +def cmd_create_issue(args: argparse.Namespace) -> None: + """Handle the ``create-issue`` subcommand.""" + print(f"Creating issue of type {args.type}...", file=sys.stderr) + try: + result = create_issue( + args.title, args.body_file, args.type, labels=args.label + ) + except (ValueError, RuntimeError, GhCommandFailed) as error: + print(f"ERROR: {error}", file=sys.stderr) + sys.exit(1) + + print(f"Created issue #{result['number']}: {result['url']}", file=sys.stderr) + print(json.dumps(result, indent=2)) + + # ───────────────────────────────────────────── # Subcommand: link-issue # ───────────────────────────────────────────── @@ -1146,6 +1269,26 @@ def main() -> None: p_link.add_argument("pr_number", type=int, help="Pull request number") p_link.set_defaults(func=cmd_link_issue) + # --- create-issue --- + p_create = sub.add_parser( + "create-issue", + help="Create an issue and set its Issue Type in one command", + ) + p_create.add_argument( + "--type", required=True, type=str.lower, + choices=sorted(ISSUE_TYPE_IDS), + help="Issue Type, e.g. 'task' or 'bug' (case-insensitive)", + ) + p_create.add_argument("--title", required=True, help="Issue title") + p_create.add_argument( + "--body-file", required=True, + help="Path to the file holding the Markdown body", + ) + p_create.add_argument( + "--label", help="Comma-separated labels to add, e.g. 'breaking change'" + ) + p_create.set_defaults(func=cmd_create_issue) + # --- issue (by-number lookup) --- p_issue = sub.add_parser( "issue", help="Fetch details for one or more issues by number (batched)" diff --git a/scripts/test_gh.py b/scripts/test_gh.py index b703b389eb..6907838d97 100644 --- a/scripts/test_gh.py +++ b/scripts/test_gh.py @@ -36,6 +36,149 @@ def load_gh(): gh = load_gh() +class CreateIssueTests(unittest.TestCase): + def setUp(self): + self.url = "https://github.com/penpot/penpot/issues/13202" + self.create_response = self.url + "\n" + self.node_response = {"repository": {"issue": {"id": "issue-node-id"}}} + self.mutation_response = { + "updateIssue": { + "issue": {"number": 13202, "issueType": {"name": "Task"}} + } + } + + @patch.object(gh, "run_gh_graphql") + @patch.object(gh, "run_gh_command") + def test_create_issue_sets_type_and_returns_result(self, run_command, run_graphql): + run_command.return_value = self.create_response + run_graphql.side_effect = [self.node_response, self.mutation_response] + + result = gh.create_issue("A title", "/tmp/body.md", "task") + + self.assertEqual( + result, + { + "number": 13202, + "url": self.url, + "title": "A title", + "issue_type": "task", + }, + ) + self.assertEqual( + run_command.call_args.args[0], + [ + "gh", "issue", "create", + "--repo", "penpot/penpot", + "--title", "A title", + "--project", "Main", + "--body-file", "/tmp/body.md", + ], + ) + self.assertEqual(run_graphql.call_count, 2) + self.assertEqual( + run_graphql.call_args_list[1].args[1], + { + "issueId": "issue-node-id", + "issueTypeId": "IT_kwDOAcyBPM4AX5NY", + }, + ) + + @patch.object(gh, "run_gh_graphql") + @patch.object(gh, "run_gh_command") + def test_create_issue_passes_labels(self, run_command, run_graphql): + run_command.return_value = self.create_response + run_graphql.side_effect = [ + self.node_response, + {"updateIssue": {"issue": {"number": 13202, "issueType": {"name": "Bug"}}}}, + ] + + gh.create_issue("T", "/tmp/body.md", "bug", labels="breaking change") + + self.assertIn("breaking change", run_command.call_args.args[0]) + self.assertIn( + "IT_kwDOAcyBPM4AX5Nb", + run_graphql.call_args_list[1].args[1].values(), + ) + + @patch.object(gh, "run_gh_graphql") + @patch.object(gh, "run_gh_command") + def test_create_issue_accepts_mixed_case_type(self, run_command, run_graphql): + run_command.return_value = self.create_response + run_graphql.side_effect = [self.node_response, self.mutation_response] + + result = gh.create_issue("T", "/tmp/body.md", "Task") + + self.assertEqual(result["issue_type"], "task") + self.assertEqual( + run_graphql.call_args_list[1].args[1]["issueTypeId"], + "IT_kwDOAcyBPM4AX5NY", + ) + + @patch.object(gh, "run_gh_command") + def test_create_issue_rejects_unknown_type(self, run_command): + with self.assertRaisesRegex(ValueError, "unknown issue type"): + gh.create_issue("T", "/tmp/body.md", "nope") + run_command.assert_not_called() + + @patch.object(gh, "run_gh_command", return_value="created") + def test_create_issue_fails_when_url_has_no_number(self, _run_command): + with self.assertRaisesRegex(RuntimeError, "could not read issue number"): + gh.create_issue("T", "/tmp/body.md", "task") + + @patch.object(gh, "run_gh_graphql") + @patch.object(gh, "run_gh_command") + def test_create_issue_reports_when_type_was_not_set(self, run_command, run_graphql): + run_command.return_value = self.create_response + run_graphql.side_effect = [ + self.node_response, + {"updateIssue": {"issue": {"number": 13202, "issueType": None}}}, + ] + + with self.assertRaisesRegex(RuntimeError, "set it manually"): + gh.create_issue("T", "/tmp/body.md", "task") + + @patch.object(gh, "run_gh_command", side_effect=gh.GhCommandFailed("boom")) + def test_create_issue_propagates_gh_failure(self, _run_command): + with self.assertRaises(gh.GhCommandFailed): + gh.create_issue("T", "/tmp/body.md", "task") + + @patch.object(gh, "create_issue") + def test_cmd_create_issue_outputs_result(self, create_issue): + expected = { + "number": 13202, + "url": self.url, + "title": "T", + "issue_type": "task", + } + create_issue.return_value = expected + args = types.SimpleNamespace( + type="task", title="T", body_file="/tmp/body.md", label=None + ) + stdout = io.StringIO() + stderr = io.StringIO() + + with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): + gh.cmd_create_issue(args) + + self.assertEqual(json.loads(stdout.getvalue()), expected) + self.assertIn("Created issue #13202", stderr.getvalue()) + create_issue.assert_called_once_with("T", "/tmp/body.md", "task", labels=None) + + @patch.object(gh, "create_issue", side_effect=gh.GhCommandFailed("boom")) + def test_cmd_create_issue_exits_on_error(self, _create_issue): + args = types.SimpleNamespace( + type="task", title="T", body_file="/tmp/body.md", label=None + ) + stderr = io.StringIO() + + with contextlib.redirect_stderr(stderr): + with self.assertRaises(SystemExit) as error: + gh.cmd_create_issue(args) + + self.assertEqual(error.exception.code, 1) + self.assertIn("boom", stderr.getvalue()) + + class LinkIssueTests(unittest.TestCase): def setUp(self): self.target_response = {