refactor: migrate issue provider logic to task manager interface and implement GitHub/GitLab providers
This commit is contained in:
208
lib/task-managers/github.ts
Normal file
208
lib/task-managers/github.ts
Normal file
@@ -0,0 +1,208 @@
|
||||
/**
|
||||
* GitHubProvider — IssueProvider implementation using gh CLI.
|
||||
*
|
||||
* Wraps gh commands for label management, issue operations, and PR checks.
|
||||
* ensureLabel is idempotent — catches "already exists" errors gracefully.
|
||||
*
|
||||
* Note: gh CLI JSON output uses different field names than GitLab:
|
||||
* number (not iid), body (not description), url (not web_url),
|
||||
* labels are objects with { name } (not plain strings).
|
||||
*/
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { writeFile, unlink } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import {
|
||||
type TaskManager,
|
||||
type Issue,
|
||||
type StateLabel,
|
||||
STATE_LABELS,
|
||||
LABEL_COLORS,
|
||||
} from "./task-manager.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
export type GitHubProviderOptions = {
|
||||
repoPath: string;
|
||||
};
|
||||
|
||||
type GhIssue = {
|
||||
number: number;
|
||||
title: string;
|
||||
body: string;
|
||||
labels: Array<{ name: string }>;
|
||||
state: string;
|
||||
url: string;
|
||||
};
|
||||
|
||||
/** Convert gh JSON issue to the common Issue type. */
|
||||
function toIssue(gh: GhIssue): Issue {
|
||||
return {
|
||||
iid: gh.number,
|
||||
title: gh.title,
|
||||
description: gh.body ?? "",
|
||||
labels: gh.labels.map((l) => l.name),
|
||||
state: gh.state,
|
||||
web_url: gh.url,
|
||||
};
|
||||
}
|
||||
|
||||
export class GitHubProvider implements TaskManager {
|
||||
private repoPath: string;
|
||||
|
||||
constructor(opts: GitHubProviderOptions) {
|
||||
this.repoPath = opts.repoPath;
|
||||
}
|
||||
|
||||
private async gh(args: string[]): Promise<string> {
|
||||
const { stdout } = await execFileAsync("gh", args, {
|
||||
cwd: this.repoPath,
|
||||
timeout: 30_000,
|
||||
});
|
||||
return stdout.trim();
|
||||
}
|
||||
|
||||
async ensureLabel(name: string, color: string): Promise<void> {
|
||||
// gh expects color without # prefix
|
||||
const hex = color.replace(/^#/, "");
|
||||
try {
|
||||
await this.gh(["label", "create", name, "--color", hex]);
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message ?? "";
|
||||
if (msg.includes("already exists")) {
|
||||
return;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async ensureAllStateLabels(): Promise<void> {
|
||||
for (const label of STATE_LABELS) {
|
||||
await this.ensureLabel(label, LABEL_COLORS[label]);
|
||||
}
|
||||
}
|
||||
|
||||
async createIssue(
|
||||
title: string,
|
||||
description: string,
|
||||
label: StateLabel,
|
||||
assignees?: string[],
|
||||
): Promise<Issue> {
|
||||
// Write description to temp file to preserve newlines
|
||||
const tempFile = join(tmpdir(), `devclaw-issue-${Date.now()}.md`);
|
||||
await writeFile(tempFile, description, "utf-8");
|
||||
|
||||
try {
|
||||
const args = [
|
||||
"issue", "create",
|
||||
"--title", title,
|
||||
"--body-file", tempFile,
|
||||
"--label", label,
|
||||
];
|
||||
if (assignees && assignees.length > 0) {
|
||||
args.push("--assignee", assignees.join(","));
|
||||
}
|
||||
// gh issue create returns the URL of the created issue
|
||||
const url = await this.gh(args);
|
||||
// Extract issue number from URL (e.g., https://github.com/owner/repo/issues/42)
|
||||
const match = url.match(/\/issues\/(\d+)$/);
|
||||
if (!match) {
|
||||
throw new Error(`Failed to parse issue number from created issue URL: ${url}`);
|
||||
}
|
||||
const issueId = parseInt(match[1], 10);
|
||||
// Fetch the full issue details
|
||||
return this.getIssue(issueId);
|
||||
} finally {
|
||||
// Clean up temp file
|
||||
try {
|
||||
await unlink(tempFile);
|
||||
} catch {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async listIssuesByLabel(label: StateLabel): Promise<Issue[]> {
|
||||
try {
|
||||
const raw = await this.gh([
|
||||
"issue", "list",
|
||||
"--label", label,
|
||||
"--state", "open",
|
||||
"--json", "number,title,body,labels,state,url",
|
||||
]);
|
||||
const issues = JSON.parse(raw) as GhIssue[];
|
||||
return issues.map(toIssue);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async getIssue(issueId: number): Promise<Issue> {
|
||||
const raw = await this.gh([
|
||||
"issue", "view", String(issueId),
|
||||
"--json", "number,title,body,labels,state,url",
|
||||
]);
|
||||
return toIssue(JSON.parse(raw) as GhIssue);
|
||||
}
|
||||
|
||||
async transitionLabel(
|
||||
issueId: number,
|
||||
from: StateLabel,
|
||||
to: StateLabel,
|
||||
): Promise<void> {
|
||||
await this.gh([
|
||||
"issue", "edit", String(issueId),
|
||||
"--remove-label", from,
|
||||
"--add-label", to,
|
||||
]);
|
||||
}
|
||||
|
||||
async closeIssue(issueId: number): Promise<void> {
|
||||
await this.gh(["issue", "close", String(issueId)]);
|
||||
}
|
||||
|
||||
async reopenIssue(issueId: number): Promise<void> {
|
||||
await this.gh(["issue", "reopen", String(issueId)]);
|
||||
}
|
||||
|
||||
hasStateLabel(issue: Issue, expected: StateLabel): boolean {
|
||||
return issue.labels.includes(expected);
|
||||
}
|
||||
|
||||
getCurrentStateLabel(issue: Issue): StateLabel | null {
|
||||
for (const label of STATE_LABELS) {
|
||||
if (issue.labels.includes(label)) {
|
||||
return label;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async hasMergedMR(issueId: number): Promise<boolean> {
|
||||
try {
|
||||
const raw = await this.gh([
|
||||
"pr", "list",
|
||||
"--state", "merged",
|
||||
"--json", "title,body",
|
||||
]);
|
||||
const prs = JSON.parse(raw) as Array<{ title: string; body: string }>;
|
||||
const pattern = `#${issueId}`;
|
||||
return prs.some(
|
||||
(pr) =>
|
||||
pr.title.includes(pattern) || (pr.body ?? "").includes(pattern),
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async healthCheck(): Promise<boolean> {
|
||||
try {
|
||||
await this.gh(["auth", "status"]);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
171
lib/task-managers/gitlab.ts
Normal file
171
lib/task-managers/gitlab.ts
Normal file
@@ -0,0 +1,171 @@
|
||||
/**
|
||||
* GitLabProvider — IssueProvider implementation using glab CLI.
|
||||
*
|
||||
* Wraps glab commands for label management, issue operations, and MR checks.
|
||||
* ensureLabel is idempotent — catches "already exists" errors gracefully.
|
||||
*/
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { writeFile, unlink } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import {
|
||||
type TaskManager,
|
||||
type Issue,
|
||||
type StateLabel,
|
||||
STATE_LABELS,
|
||||
LABEL_COLORS,
|
||||
} from "./task-manager.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
export type GitLabProviderOptions = {
|
||||
repoPath: string;
|
||||
};
|
||||
|
||||
export class GitLabProvider implements TaskManager {
|
||||
private repoPath: string;
|
||||
|
||||
constructor(opts: GitLabProviderOptions) {
|
||||
this.repoPath = opts.repoPath;
|
||||
}
|
||||
|
||||
private async glab(args: string[]): Promise<string> {
|
||||
const { stdout } = await execFileAsync("glab", args, {
|
||||
cwd: this.repoPath,
|
||||
timeout: 30_000,
|
||||
});
|
||||
return stdout.trim();
|
||||
}
|
||||
|
||||
async ensureLabel(name: string, color: string): Promise<void> {
|
||||
try {
|
||||
await this.glab(["label", "create", "--name", name, "--color", color]);
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message ?? "";
|
||||
// Idempotent: ignore "already exists" errors
|
||||
if (msg.includes("already exists") || msg.includes("409")) {
|
||||
return;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async ensureAllStateLabels(): Promise<void> {
|
||||
for (const label of STATE_LABELS) {
|
||||
await this.ensureLabel(label, LABEL_COLORS[label]);
|
||||
}
|
||||
}
|
||||
|
||||
async createIssue(
|
||||
title: string,
|
||||
description: string,
|
||||
label: StateLabel,
|
||||
assignees?: string[],
|
||||
): Promise<Issue> {
|
||||
// Write description to temp file to preserve newlines
|
||||
const tempFile = join(tmpdir(), `devclaw-issue-${Date.now()}.md`);
|
||||
await writeFile(tempFile, description, "utf-8");
|
||||
|
||||
try {
|
||||
// Use shell to read file content into description
|
||||
const { exec } = await import("node:child_process");
|
||||
const { promisify } = await import("node:util");
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
let cmd = `glab issue create --title "${title.replace(/"/g, '\\"')}" --description "$(cat ${tempFile})" --label "${label}" --output json`;
|
||||
if (assignees && assignees.length > 0) {
|
||||
cmd += ` --assignee "${assignees.join(",")}"`;
|
||||
}
|
||||
|
||||
const { stdout } = await execAsync(cmd, {
|
||||
cwd: this.repoPath,
|
||||
timeout: 30_000,
|
||||
});
|
||||
return JSON.parse(stdout.trim()) as Issue;
|
||||
} finally {
|
||||
// Clean up temp file
|
||||
try {
|
||||
await unlink(tempFile);
|
||||
} catch {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async listIssuesByLabel(label: StateLabel): Promise<Issue[]> {
|
||||
try {
|
||||
const raw = await this.glab([
|
||||
"issue", "list", "--label", label, "--output", "json",
|
||||
]);
|
||||
return JSON.parse(raw) as Issue[];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async getIssue(issueId: number): Promise<Issue> {
|
||||
const raw = await this.glab([
|
||||
"issue", "view", String(issueId), "--output", "json",
|
||||
]);
|
||||
return JSON.parse(raw) as Issue;
|
||||
}
|
||||
|
||||
async transitionLabel(
|
||||
issueId: number,
|
||||
from: StateLabel,
|
||||
to: StateLabel,
|
||||
): Promise<void> {
|
||||
await this.glab([
|
||||
"issue", "update", String(issueId),
|
||||
"--unlabel", from,
|
||||
"--label", to,
|
||||
]);
|
||||
}
|
||||
|
||||
async closeIssue(issueId: number): Promise<void> {
|
||||
await this.glab(["issue", "close", String(issueId)]);
|
||||
}
|
||||
|
||||
async reopenIssue(issueId: number): Promise<void> {
|
||||
await this.glab(["issue", "reopen", String(issueId)]);
|
||||
}
|
||||
|
||||
hasStateLabel(issue: Issue, expected: StateLabel): boolean {
|
||||
return issue.labels.includes(expected);
|
||||
}
|
||||
|
||||
getCurrentStateLabel(issue: Issue): StateLabel | null {
|
||||
for (const label of STATE_LABELS) {
|
||||
if (issue.labels.includes(label)) {
|
||||
return label;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async hasMergedMR(issueId: number): Promise<boolean> {
|
||||
try {
|
||||
const raw = await this.glab([
|
||||
"mr", "list", "--output", "json", "--state", "merged",
|
||||
]);
|
||||
const mrs = JSON.parse(raw) as Array<{ title: string; description: string }>;
|
||||
const pattern = `#${issueId}`;
|
||||
return mrs.some(
|
||||
(mr) =>
|
||||
mr.title.includes(pattern) || (mr.description ?? "").includes(pattern),
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async healthCheck(): Promise<boolean> {
|
||||
try {
|
||||
await this.glab(["auth", "status"]);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
59
lib/task-managers/index.ts
Normal file
59
lib/task-managers/index.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Provider factory — creates the appropriate IssueProvider for a repository.
|
||||
*
|
||||
* Auto-detects provider from git remote URL:
|
||||
* - github.com → GitHubProvider (gh CLI)
|
||||
* - Everything else → GitLabProvider (glab CLI)
|
||||
*
|
||||
* Can be overridden with explicit `provider` option.
|
||||
*/
|
||||
import { execFileSync } from "node:child_process";
|
||||
import type { TaskManager } from "./task-manager.js";
|
||||
import { GitLabProvider } from "./gitlab.js";
|
||||
import { GitHubProvider } from "./github.js";
|
||||
import { resolveRepoPath } from "../utils.js";
|
||||
|
||||
export type ProviderOptions = {
|
||||
provider?: "gitlab" | "github";
|
||||
repo?: string;
|
||||
repoPath?: string;
|
||||
};
|
||||
|
||||
function detectProvider(repoPath: string): "gitlab" | "github" {
|
||||
try {
|
||||
const url = execFileSync("git", ["remote", "get-url", "origin"], {
|
||||
cwd: repoPath,
|
||||
timeout: 5_000,
|
||||
}).toString().trim();
|
||||
|
||||
if (url.includes("github.com")) return "github";
|
||||
return "gitlab";
|
||||
} catch {
|
||||
return "gitlab";
|
||||
}
|
||||
}
|
||||
|
||||
export type ProviderWithType = {
|
||||
provider: TaskManager;
|
||||
type: "github" | "gitlab";
|
||||
};
|
||||
|
||||
export function createProvider(opts: ProviderOptions): ProviderWithType {
|
||||
const repoPath = opts.repoPath ?? (opts.repo ? resolveRepoPath(opts.repo) : null);
|
||||
if (!repoPath) {
|
||||
throw new Error("Either repoPath or repo must be provided to createProvider");
|
||||
}
|
||||
|
||||
const type = opts.provider ?? detectProvider(repoPath);
|
||||
|
||||
if (type === "github") {
|
||||
return {
|
||||
provider: new GitHubProvider({ repoPath }),
|
||||
type: "github",
|
||||
};
|
||||
}
|
||||
return {
|
||||
provider: new GitLabProvider({ repoPath }),
|
||||
type: "gitlab",
|
||||
};
|
||||
}
|
||||
86
lib/task-managers/task-manager.ts
Normal file
86
lib/task-managers/task-manager.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* TaskManager — Abstract interface for issue tracker operations.
|
||||
*
|
||||
* GitHub (via gh CLI) and GitLab (via glab CLI) are the current implementations.
|
||||
* Future providers: Jira (via API).
|
||||
*
|
||||
* All DevClaw tools operate through this interface, making it possible
|
||||
* to swap issue trackers without changing tool logic.
|
||||
*/
|
||||
|
||||
export const STATE_LABELS = [
|
||||
"Planning",
|
||||
"To Do",
|
||||
"Doing",
|
||||
"To Test",
|
||||
"Testing",
|
||||
"Done",
|
||||
"To Improve",
|
||||
"Refining",
|
||||
] as const;
|
||||
|
||||
export type StateLabel = (typeof STATE_LABELS)[number];
|
||||
|
||||
export const LABEL_COLORS: Record<StateLabel, string> = {
|
||||
Planning: "#6699cc",
|
||||
"To Do": "#428bca",
|
||||
Doing: "#f0ad4e",
|
||||
"To Test": "#5bc0de",
|
||||
Testing: "#9b59b6",
|
||||
Done: "#5cb85c",
|
||||
"To Improve": "#d9534f",
|
||||
Refining: "#f39c12",
|
||||
};
|
||||
|
||||
export type Issue = {
|
||||
iid: number;
|
||||
title: string;
|
||||
description: string;
|
||||
labels: string[];
|
||||
state: string;
|
||||
web_url: string;
|
||||
};
|
||||
|
||||
export interface TaskManager {
|
||||
/** Create a label if it doesn't exist (idempotent). */
|
||||
ensureLabel(name: string, color: string): Promise<void>;
|
||||
|
||||
/** Create all 8 state labels (idempotent). */
|
||||
ensureAllStateLabels(): Promise<void>;
|
||||
|
||||
/** Create a new issue. */
|
||||
createIssue(title: string, description: string, label: StateLabel, assignees?: string[]): Promise<Issue>;
|
||||
|
||||
/** List issues with a specific state label. */
|
||||
listIssuesByLabel(label: StateLabel): Promise<Issue[]>;
|
||||
|
||||
/** Fetch a single issue by ID. */
|
||||
getIssue(issueId: number): Promise<Issue>;
|
||||
|
||||
/** Transition an issue from one state label to another (atomic unlabel + label). */
|
||||
transitionLabel(issueId: number, from: StateLabel, to: StateLabel): Promise<void>;
|
||||
|
||||
/** Close an issue. */
|
||||
closeIssue(issueId: number): Promise<void>;
|
||||
|
||||
/** Reopen an issue. */
|
||||
reopenIssue(issueId: number): Promise<void>;
|
||||
|
||||
/** Check if an issue has a specific state label. */
|
||||
hasStateLabel(issue: Issue, expected: StateLabel): boolean;
|
||||
|
||||
/** Get the current state label of an issue. */
|
||||
getCurrentStateLabel(issue: Issue): StateLabel | null;
|
||||
|
||||
/** Check if any merged MR/PR exists for a specific issue. */
|
||||
hasMergedMR(issueId: number): Promise<boolean>;
|
||||
|
||||
/** Verify the task manager is working (CLI available, auth valid, repo accessible). */
|
||||
healthCheck(): Promise<boolean>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compatibility alias for backward compatibility.
|
||||
* @deprecated Use TaskManager instead.
|
||||
*/
|
||||
export type IssueProvider = TaskManager;
|
||||
Reference in New Issue
Block a user