1"""GitHub utility functions for feature-branch PR state checks."""

2

3 from __future__ import annotations

4

5 import json

6 import subprocess

7

8

9 def is_pr_merged(branch: str, pr_url: str | None = None) -> bool:

10 """Check whether a PR for the given branch or URL has been merged.

11

12 Args:

13 branch: Branch name to look up (used when pr_url is None)

14 pr_url: PR URL to check directly (preferred over branch name)

15

16 Returns:

17 True if the PR exists and state is MERGED, False otherwise (including

18 errors, missing gh CLI, timeouts, and unauthenticated states).

19 """

20 ref = pr_url or branch

21 if not ref:

22 return False

23 try:

24 result = subprocess.run(

25 ["gh", "pr", "view", ref, "--json", "state,mergedAt"],

26 capture_output=True,

27 text=True,

28 timeout=30,

29 )

30 if result.returncode != 0:

31 return False

32 data = json.loads(result.stdout)

33 return data.get("state") == "MERGED"

34 except FileNotFoundError:

35 return False

36 except subprocess.TimeoutExpired:

37 return False

38 except json.JSONDecodeError:

39 return False