github-issue-autocomplete.ts 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. // Requires GitHub CLI (`gh`) and a GitHub repository checkout.
  2. // Preloads the latest open issues once per session, then filters them locally for fast `#...` completion.
  3. import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
  4. import {
  5. type AutocompleteItem,
  6. type AutocompleteProvider,
  7. type AutocompleteSuggestions,
  8. fuzzyFilter,
  9. } from "@earendil-works/pi-tui";
  10. type GitHubIssue = {
  11. number: number;
  12. title: string;
  13. state: string;
  14. };
  15. type RepoResolution = { ok: true; repo: string } | { ok: false; error: string };
  16. const MAX_ISSUES = 100;
  17. const MAX_SUGGESTIONS = 20;
  18. function extractIssueToken(textBeforeCursor: string): string | undefined {
  19. const match = textBeforeCursor.match(/(?:^|[ \t])#([^\s#]*)$/);
  20. return match?.[1];
  21. }
  22. function parseGitHubRepo(remoteUrl: string): string | undefined {
  23. const sshMatch = remoteUrl.match(/^git@github\.com:([^/]+\/[^/]+?)(?:\.git)?$/);
  24. if (sshMatch) {
  25. return sshMatch[1];
  26. }
  27. const httpsMatch = remoteUrl.match(/^https?:\/\/github\.com\/([^/]+\/[^/]+?)(?:\.git)?$/);
  28. if (httpsMatch) {
  29. return httpsMatch[1];
  30. }
  31. return undefined;
  32. }
  33. async function resolveGitHubRepo(pi: ExtensionAPI, cwd: string): Promise<RepoResolution> {
  34. const result = await pi.exec("git", ["remote", "-v"], { cwd, timeout: 5_000 });
  35. if (result.code !== 0) {
  36. return { ok: false, error: "github-issue-autocomplete: cwd is not a git repository" };
  37. }
  38. for (const line of result.stdout.split("\n")) {
  39. const columns = line.trim().split(/\s+/);
  40. const remoteUrl = columns[1];
  41. if (!remoteUrl) {
  42. continue;
  43. }
  44. const repo = parseGitHubRepo(remoteUrl);
  45. if (repo) {
  46. return { ok: true, repo };
  47. }
  48. }
  49. return { ok: false, error: "github-issue-autocomplete: cwd is not a GitHub repository" };
  50. }
  51. function formatIssueItem(issue: GitHubIssue): AutocompleteItem {
  52. return {
  53. value: `#${issue.number}`,
  54. label: `#${issue.number}`,
  55. description: `[${issue.state.toLowerCase()}] ${issue.title}`,
  56. };
  57. }
  58. function filterIssues(issues: GitHubIssue[], query: string): AutocompleteItem[] {
  59. if (!query.trim()) {
  60. return issues.slice(0, MAX_SUGGESTIONS).map(formatIssueItem);
  61. }
  62. if (/^\d+$/.test(query)) {
  63. const numericMatches = issues
  64. .filter((issue) => String(issue.number).startsWith(query))
  65. .slice(0, MAX_SUGGESTIONS)
  66. .map(formatIssueItem);
  67. if (numericMatches.length > 0) {
  68. return numericMatches;
  69. }
  70. }
  71. return fuzzyFilter(issues, query, (issue) => `${issue.number} ${issue.title}`)
  72. .slice(0, MAX_SUGGESTIONS)
  73. .map(formatIssueItem);
  74. }
  75. function createIssueAutocompleteProvider(
  76. current: AutocompleteProvider,
  77. getIssues: () => Promise<GitHubIssue[] | undefined>,
  78. ): AutocompleteProvider {
  79. return {
  80. async getSuggestions(lines, cursorLine, cursorCol, options): Promise<AutocompleteSuggestions | null> {
  81. const currentLine = lines[cursorLine] ?? "";
  82. const textBeforeCursor = currentLine.slice(0, cursorCol);
  83. const token = extractIssueToken(textBeforeCursor);
  84. if (token === undefined) {
  85. return current.getSuggestions(lines, cursorLine, cursorCol, options);
  86. }
  87. const issues = await getIssues();
  88. if (options.signal.aborted || !issues || issues.length === 0) {
  89. return current.getSuggestions(lines, cursorLine, cursorCol, options);
  90. }
  91. const suggestions = filterIssues(issues, token);
  92. if (suggestions.length === 0) {
  93. return current.getSuggestions(lines, cursorLine, cursorCol, options);
  94. }
  95. return {
  96. items: suggestions,
  97. prefix: `#${token}`,
  98. };
  99. },
  100. applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
  101. return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
  102. },
  103. shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
  104. return current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true;
  105. },
  106. };
  107. }
  108. export default function (pi: ExtensionAPI): void {
  109. pi.on("session_start", async (_event, ctx) => {
  110. const resolvedRepo = await resolveGitHubRepo(pi, ctx.cwd);
  111. if (!resolvedRepo.ok) {
  112. ctx.ui.notify(resolvedRepo.error, "error");
  113. return;
  114. }
  115. const repo = resolvedRepo.repo;
  116. let issuesPromise: Promise<GitHubIssue[] | undefined> | undefined;
  117. let loadErrorShown = false;
  118. const getIssues = async (): Promise<GitHubIssue[] | undefined> => {
  119. issuesPromise ||= (async () => {
  120. const result = await pi.exec(
  121. "gh",
  122. [
  123. "issue",
  124. "list",
  125. "--repo",
  126. repo,
  127. "--state",
  128. "open",
  129. "--limit",
  130. String(MAX_ISSUES),
  131. "--json",
  132. "number,title,state",
  133. ],
  134. { cwd: ctx.cwd, timeout: 5_000 },
  135. );
  136. if (result.code !== 0) {
  137. if (!loadErrorShown) {
  138. loadErrorShown = true;
  139. const details = result.stderr.trim() || `exit code ${result.code}`;
  140. ctx.ui.notify(`github-issue-autocomplete: failed to load issues: ${details}`, "error");
  141. }
  142. return undefined;
  143. }
  144. try {
  145. return JSON.parse(result.stdout) as GitHubIssue[];
  146. } catch {
  147. if (!loadErrorShown) {
  148. loadErrorShown = true;
  149. ctx.ui.notify("github-issue-autocomplete: failed to parse gh issue list output", "error");
  150. }
  151. return undefined;
  152. }
  153. })();
  154. return issuesPromise;
  155. };
  156. void getIssues();
  157. ctx.ui.addAutocompleteProvider((current) => createIssueAutocompleteProvider(current, getIssues));
  158. });
  159. }