feat: add issue create and comment (task 0004)
Introduce the first mutations, along with the shared machinery the later
issue and PR mutation slices reuse.
- `issue create` with --title/--body/--body-file/--assignee/--label/
--milestone/--fields, emitting `issue: { number, title, state, url }`
- `issue comment <n>`, echoing the created comment from the POST response
with the body cleaned and truncated at 800 chars
- body-source resolution (--body vs --body-file), label and milestone
name->ID lookup, repeatable flags, and the `joined`/`selectExtraFields`
field extractors
Label lookup pages until exhausted, since a repo with more labels than one
page would otherwise fail to resolve a valid name. The end-to-end tier seeds
a mixed-case label and milestone and passes both in a different case, so the
case-insensitive lookup is verified against live Gitea rather than only
against fixtures.
This commit was merged in pull request #3.
This commit is contained in:
74
src/body-source.ts
Normal file
74
src/body-source.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { isAbsolute, resolve } from "node:path";
|
||||
import type { CliDeps } from "./deps.js";
|
||||
import { axiError } from "./errors.js";
|
||||
import { flagValue } from "./flags.js";
|
||||
|
||||
/**
|
||||
* Resolve the body text a mutation should send from its `--body`/`--body-file`
|
||||
* flags. Shared by every command that accepts a body (issue create, issue
|
||||
* comment, and the edit/close commands that follow).
|
||||
*
|
||||
* The two flags are mutually exclusive: accepting both and picking a winner
|
||||
* would silently discard text the caller meant to send.
|
||||
*/
|
||||
export function resolveBodySource(
|
||||
deps: CliDeps,
|
||||
flags: Record<string, string | true>,
|
||||
command: string,
|
||||
): string | undefined {
|
||||
const body = flagValue(flags, "--body");
|
||||
const path = flagValue(flags, "--body-file");
|
||||
|
||||
if (body !== undefined && path !== undefined) {
|
||||
throw axiError(
|
||||
"Flags --body and --body-file are mutually exclusive",
|
||||
"VALIDATION_ERROR",
|
||||
bodyFlagSuggestion(command),
|
||||
);
|
||||
}
|
||||
if (body !== undefined) {
|
||||
return body;
|
||||
}
|
||||
if (path !== undefined) {
|
||||
return readBodyFile(deps, path, command);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** As {@link resolveBodySource}, for the commands where a body is mandatory. */
|
||||
export function requireBodySource(
|
||||
deps: CliDeps,
|
||||
flags: Record<string, string | true>,
|
||||
command: string,
|
||||
): string {
|
||||
const body = resolveBodySource(deps, flags, command);
|
||||
if (body === undefined) {
|
||||
throw axiError(
|
||||
`${command} requires --body <text> or --body-file <path>`,
|
||||
"VALIDATION_ERROR",
|
||||
bodyFlagSuggestion(command),
|
||||
);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
function bodyFlagSuggestion(command: string): string[] {
|
||||
return [
|
||||
`Run \`gitea-axi ${command} --body <text>\` or \`gitea-axi ${command} --body-file <path>\``,
|
||||
];
|
||||
}
|
||||
|
||||
function readBodyFile(deps: CliDeps, path: string, command: string): string {
|
||||
const absolute = isAbsolute(path) ? path : resolve(deps.cwd, path);
|
||||
try {
|
||||
return readFileSync(absolute, "utf8");
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error);
|
||||
throw axiError(
|
||||
`Cannot read --body-file ${path}: ${reason}`,
|
||||
"VALIDATION_ERROR",
|
||||
bodyFlagSuggestion(command),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -12,8 +12,10 @@ const DESCRIPTION = "Agent-ergonomic CLI for Gitea issues and pull requests";
|
||||
const TOP_LEVEL_HELP = `usage: gitea-axi <command> [flags]
|
||||
|
||||
commands:
|
||||
issue list List issues in the current repository
|
||||
issue view Show a single issue's details
|
||||
issue list List issues in the current repository
|
||||
issue view Show a single issue's details
|
||||
issue create Create an issue
|
||||
issue comment Post a comment on an issue or pull request
|
||||
|
||||
global flags:
|
||||
-R, --repo <OWNER/NAME> Override the repository detected from the git origin remote
|
||||
|
||||
@@ -1,15 +1,25 @@
|
||||
import type { Comment, Issue } from "gitea-js";
|
||||
import type { Comment, CreateIssueOption, Issue } from "gitea-js";
|
||||
import {
|
||||
BODY_TRUNCATE_LIMIT,
|
||||
COMMENT_TRUNCATE_LIMIT,
|
||||
truncateBody,
|
||||
} from "../body.js";
|
||||
import { requireBodySource, resolveBodySource } from "../body-source.js";
|
||||
import { createClient } from "../client.js";
|
||||
import { resolveRepoContext, type RepoContext } from "../context.js";
|
||||
import type { CliDeps } from "../deps.js";
|
||||
import { axiError, classifyHttpError } from "../errors.js";
|
||||
import { extractRow, lowercased, pluck, relativeTimeField, type FieldDef } from "../fields.js";
|
||||
import { parseFlags } from "../flags.js";
|
||||
import {
|
||||
extractRow,
|
||||
joined,
|
||||
lowercased,
|
||||
pluck,
|
||||
relativeTimeField,
|
||||
selectExtraFields,
|
||||
type FieldDef,
|
||||
} from "../fields.js";
|
||||
import { flagValue, parseFlags } from "../flags.js";
|
||||
import { resolveLabelIds, resolveMilestoneId } from "../lookup.js";
|
||||
import { formatCountLine, renderDetail, renderList, type DetailBlock } from "../render.js";
|
||||
import { relativeTime } from "../time.js";
|
||||
import { suggestCommand } from "../suggestions.js";
|
||||
@@ -17,12 +27,49 @@ import { suggestCommand } from "../suggestions.js";
|
||||
export const ISSUE_HELP = `usage: gitea-axi issue <command> [flags]
|
||||
|
||||
commands:
|
||||
list List issues in the current repository
|
||||
view Show a single issue's details
|
||||
list List issues in the current repository
|
||||
view Show a single issue's details
|
||||
create Create an issue
|
||||
comment Post a comment on an issue or pull request
|
||||
|
||||
Run \`gitea-axi issue <command> --help\` for the flags of a command.
|
||||
`;
|
||||
|
||||
export const ISSUE_CREATE_HELP = `usage: gitea-axi issue create --title <text> [flags]
|
||||
|
||||
Create an issue in the current repository.
|
||||
|
||||
flags:
|
||||
--title <text> Issue title (required)
|
||||
--body <text> Issue body
|
||||
--body-file <path> Read the issue body from a file (mutually exclusive with --body)
|
||||
--assignee <login> Assign the issue to a user
|
||||
--label <name> Apply a label by name (repeatable, case-insensitive)
|
||||
--milestone <name> Assign a milestone by name (case-insensitive)
|
||||
--fields <a,b,c> Append extra fields: labels, assignees, milestone, body
|
||||
--help Show this help
|
||||
|
||||
global flags:
|
||||
-R, --repo <OWNER/NAME> Override the repository detected from the git origin remote
|
||||
--login <name> Select a tea login profile by name
|
||||
`;
|
||||
|
||||
export const ISSUE_COMMENT_HELP = `usage: gitea-axi issue comment <number> [flags]
|
||||
|
||||
Post a comment on an issue. Pull request numbers are accepted — issues and pull
|
||||
requests share the comment endpoint.
|
||||
|
||||
flags:
|
||||
--body <text> Comment body (required unless --body-file is given)
|
||||
--body-file <path> Read the comment body from a file (mutually exclusive with --body)
|
||||
--full Echo the posted body in full, without truncating it at 800 chars
|
||||
--help Show this help
|
||||
|
||||
global flags:
|
||||
-R, --repo <OWNER/NAME> Override the repository detected from the git origin remote
|
||||
--login <name> Select a tea login profile by name
|
||||
`;
|
||||
|
||||
export const ISSUE_VIEW_HELP = `usage: gitea-axi issue view <number> [flags]
|
||||
|
||||
Show a single issue. Pull request numbers are rejected — use \`pr view\` instead.
|
||||
@@ -167,11 +214,8 @@ async function issueList(deps: CliDeps, args: string[]): Promise<string> {
|
||||
});
|
||||
}
|
||||
|
||||
const ISSUE_VIEW_HELP_SUGGESTION = [
|
||||
"Run `gitea-axi issue view --help` to see available flags",
|
||||
];
|
||||
|
||||
function parseIssueNumber(positionals: string[], command: string): number {
|
||||
const helpSuggestion = [`Run \`gitea-axi ${command} --help\` to see available flags`];
|
||||
if (positionals.length === 0) {
|
||||
throw axiError(`${command} requires an issue number`, "VALIDATION_ERROR", [
|
||||
`Run \`gitea-axi ${command} <number>\``,
|
||||
@@ -181,7 +225,7 @@ function parseIssueNumber(positionals: string[], command: string): number {
|
||||
throw axiError(
|
||||
`Unexpected argument: ${positionals[1]}`,
|
||||
"VALIDATION_ERROR",
|
||||
ISSUE_VIEW_HELP_SUGGESTION,
|
||||
helpSuggestion,
|
||||
);
|
||||
}
|
||||
const raw = positionals[0]!;
|
||||
@@ -190,7 +234,7 @@ function parseIssueNumber(positionals: string[], command: string): number {
|
||||
throw axiError(
|
||||
`Invalid issue number: ${raw} (expected a positive integer)`,
|
||||
"VALIDATION_ERROR",
|
||||
ISSUE_VIEW_HELP_SUGGESTION,
|
||||
helpSuggestion,
|
||||
);
|
||||
}
|
||||
return number;
|
||||
@@ -313,6 +357,155 @@ async function issueView(deps: CliDeps, args: string[]): Promise<string> {
|
||||
});
|
||||
}
|
||||
|
||||
const ISSUE_CREATE_HELP_SUGGESTION = [
|
||||
"Run `gitea-axi issue create --help` to see available flags",
|
||||
];
|
||||
|
||||
// Default create output, per the spec: number, title, state, url (= html_url).
|
||||
const ISSUE_CREATE_FIELDS: FieldDef<Issue>[] = [
|
||||
pluck("number"),
|
||||
pluck("title"),
|
||||
lowercased("state"),
|
||||
pluck("url", "html_url"),
|
||||
];
|
||||
|
||||
// Appended to the defaults on request via `--fields`, never replacing them.
|
||||
const ISSUE_CREATE_EXTRA_FIELDS: Record<string, FieldDef<Issue>> = {
|
||||
labels: joined("labels", "labels", "name"),
|
||||
assignees: joined("assignees", "assignees", "login"),
|
||||
milestone: pluck("milestone", "milestone.title"),
|
||||
body: pluck("body"),
|
||||
};
|
||||
|
||||
async function issueCreate(deps: CliDeps, args: string[]): Promise<string> {
|
||||
if (args.includes("--help")) {
|
||||
return ISSUE_CREATE_HELP;
|
||||
}
|
||||
const { flags, lists, positionals } = parseFlags(
|
||||
args,
|
||||
{
|
||||
"--title": { takesValue: true },
|
||||
"--body": { takesValue: true },
|
||||
"--body-file": { takesValue: true },
|
||||
"--assignee": { takesValue: true },
|
||||
"--label": { takesValue: true, repeatable: true },
|
||||
"--milestone": { takesValue: true },
|
||||
"--fields": { takesValue: true },
|
||||
},
|
||||
"issue create",
|
||||
);
|
||||
if (positionals.length > 0) {
|
||||
throw axiError(
|
||||
`Unexpected argument: ${positionals[0]}`,
|
||||
"VALIDATION_ERROR",
|
||||
ISSUE_CREATE_HELP_SUGGESTION,
|
||||
);
|
||||
}
|
||||
|
||||
// Everything that can fail on the caller's own input is settled before any
|
||||
// request goes out, so a rejected invocation never half-creates an issue.
|
||||
const title = flagValue(flags, "--title");
|
||||
if (title === undefined) {
|
||||
throw axiError("issue create requires --title <text>", "VALIDATION_ERROR", [
|
||||
"Run `gitea-axi issue create --title <text>`",
|
||||
]);
|
||||
}
|
||||
const body = resolveBodySource(deps, flags, "issue create");
|
||||
const extraFields = selectExtraFields(
|
||||
flagValue(flags, "--fields"),
|
||||
ISSUE_CREATE_EXTRA_FIELDS,
|
||||
"issue create",
|
||||
);
|
||||
const assignee = flagValue(flags, "--assignee");
|
||||
const milestoneName = flagValue(flags, "--milestone");
|
||||
const labelNames = lists["--label"] ?? [];
|
||||
|
||||
const context = await resolveRepoContext(deps);
|
||||
const api = createClient(context);
|
||||
|
||||
const payload: CreateIssueOption = { title };
|
||||
if (body !== undefined) {
|
||||
payload.body = body;
|
||||
}
|
||||
if (assignee !== undefined) {
|
||||
payload.assignees = [assignee];
|
||||
}
|
||||
const labelIds = await resolveLabelIds(api, context, labelNames);
|
||||
if (labelIds.length > 0) {
|
||||
payload.labels = labelIds;
|
||||
}
|
||||
if (milestoneName !== undefined) {
|
||||
payload.milestone = await resolveMilestoneId(api, context, milestoneName);
|
||||
}
|
||||
|
||||
let issue: Issue;
|
||||
try {
|
||||
const response = await api.repos.issueCreateIssue(context.owner, context.name, payload);
|
||||
issue = response.data;
|
||||
} catch (error) {
|
||||
throw classifyHttpError(error);
|
||||
}
|
||||
|
||||
const item = extractRow(issue, [...ISSUE_CREATE_FIELDS, ...extraFields], { now: new Date() });
|
||||
return renderDetail({
|
||||
noun: "issue",
|
||||
item,
|
||||
help: [
|
||||
suggestCommand(context, `issue view ${issue.number}`, "to see the issue in full"),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
async function issueComment(deps: CliDeps, args: string[]): Promise<string> {
|
||||
if (args.includes("--help")) {
|
||||
return ISSUE_COMMENT_HELP;
|
||||
}
|
||||
const { flags, positionals } = parseFlags(
|
||||
args,
|
||||
{
|
||||
"--body": { takesValue: true },
|
||||
"--body-file": { takesValue: true },
|
||||
"--full": { takesValue: false },
|
||||
},
|
||||
"issue comment",
|
||||
);
|
||||
const number = parseIssueNumber(positionals, "issue comment");
|
||||
const body = requireBodySource(deps, flags, "issue comment");
|
||||
const full = flags["--full"] === true;
|
||||
|
||||
// No type guard here: issues and pull requests genuinely share this endpoint,
|
||||
// so a PR number is a valid target and is never fetched to be checked.
|
||||
const context = await resolveRepoContext(deps);
|
||||
const api = createClient(context);
|
||||
let comment: Comment;
|
||||
try {
|
||||
const response = await api.repos.issueCreateComment(context.owner, context.name, number, {
|
||||
body,
|
||||
});
|
||||
comment = response.data;
|
||||
} catch (error) {
|
||||
throw classifyHttpError(error);
|
||||
}
|
||||
|
||||
const raw = comment.body ?? "";
|
||||
const item = {
|
||||
// The issue the comment was posted to — the comment's own id is not output.
|
||||
number,
|
||||
author: comment.user?.login ?? "",
|
||||
created: relativeTime(comment.created_at, new Date()),
|
||||
body: full ? raw : truncateBody(raw, COMMENT_TRUNCATE_LIMIT, context.host),
|
||||
};
|
||||
|
||||
// Gitea marks a comment posted on a pull request with `pull_request_url`. Only
|
||||
// an issue target gets the `issue view` suggestion: `issue view` type-guards
|
||||
// pull requests, so suggesting it after commenting on one would hand back a
|
||||
// command that is guaranteed to fail.
|
||||
const help = comment.pull_request_url
|
||||
? [suggestCommand(context, "issue comment --help", "to see all issue comment flags")]
|
||||
: [suggestCommand(context, `issue view ${number} --comments`, "to see the full thread")];
|
||||
return renderDetail({ noun: "comment", item, help });
|
||||
}
|
||||
|
||||
export function issueCommand(deps: CliDeps) {
|
||||
return async (args: string[]): Promise<string> => {
|
||||
const [subcommand, ...rest] = args;
|
||||
@@ -325,6 +518,12 @@ export function issueCommand(deps: CliDeps) {
|
||||
if (subcommand === "view") {
|
||||
return issueView(deps, rest);
|
||||
}
|
||||
if (subcommand === "create") {
|
||||
return issueCreate(deps, rest);
|
||||
}
|
||||
if (subcommand === "comment") {
|
||||
return issueComment(deps, rest);
|
||||
}
|
||||
throw axiError(`Unknown issue command: ${subcommand}`, "VALIDATION_ERROR", [
|
||||
"Run `gitea-axi issue --help` to see available issue commands",
|
||||
]);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { axiError } from "./errors.js";
|
||||
import { relativeTime } from "./time.js";
|
||||
|
||||
export interface ExtractContext {
|
||||
@@ -31,6 +32,26 @@ export function lowercased<T>(name: string, path: string = name): FieldDef<T> {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Join a field holding an array of objects (labels, assignees) into a single
|
||||
* string of each element's `key` property.
|
||||
*/
|
||||
export function joined<T>(name: string, path: string, key: string): FieldDef<T> {
|
||||
return {
|
||||
name,
|
||||
extract: (raw) => {
|
||||
const value = pluckPath(raw, path);
|
||||
if (!Array.isArray(value)) {
|
||||
return "";
|
||||
}
|
||||
return value
|
||||
.map((item) => pluckPath(item, key))
|
||||
.filter((item): item is string => typeof item === "string" && item.length > 0)
|
||||
.join(", ");
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function relativeTimeField<T>(name: string, path: string): FieldDef<T> {
|
||||
return {
|
||||
name,
|
||||
@@ -41,6 +62,48 @@ export function relativeTimeField<T>(name: string, path: string): FieldDef<T> {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a comma-separated `--fields` value against the extra fields a command
|
||||
* offers on top of its defaults. Unknown names are a `VALIDATION_ERROR` naming
|
||||
* what is available, since a silently ignored field would look like a command
|
||||
* that returned nothing for it.
|
||||
*/
|
||||
export function selectExtraFields<T>(
|
||||
value: string | undefined,
|
||||
registry: Record<string, FieldDef<T>>,
|
||||
command: string,
|
||||
): FieldDef<T>[] {
|
||||
if (value === undefined) {
|
||||
return [];
|
||||
}
|
||||
const available = Object.keys(registry);
|
||||
const suggestion = [
|
||||
`Run \`gitea-axi ${command} --fields <a,b,c>\` with any of: ${available.join(", ")}`,
|
||||
];
|
||||
const selected: FieldDef<T>[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const raw of value.split(",")) {
|
||||
const name = raw.trim();
|
||||
if (!name) {
|
||||
continue;
|
||||
}
|
||||
const field = registry[name];
|
||||
if (!field) {
|
||||
throw axiError(
|
||||
`Unknown --fields name: ${name} (available: ${available.join(", ")})`,
|
||||
"VALIDATION_ERROR",
|
||||
suggestion,
|
||||
);
|
||||
}
|
||||
if (seen.has(name)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(name);
|
||||
selected.push(field);
|
||||
}
|
||||
return selected;
|
||||
}
|
||||
|
||||
export function extractRow<T>(
|
||||
raw: T,
|
||||
fields: FieldDef<T>[],
|
||||
|
||||
41
src/flags.ts
41
src/flags.ts
@@ -1,12 +1,22 @@
|
||||
import { axiError } from "./errors.js";
|
||||
|
||||
export interface FlagSpec {
|
||||
/** Flag names (e.g. "--state") mapped to whether they take a value. */
|
||||
[name: string]: { takesValue: boolean };
|
||||
/** Flag names (e.g. "--state") mapped to how they are parsed. */
|
||||
[name: string]: {
|
||||
takesValue: boolean;
|
||||
/** Accumulate every occurrence into `lists` instead of `flags` (e.g. `--label`). */
|
||||
repeatable?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ParsedFlags {
|
||||
/** Single-valued flags: the value, or `true` for a bare switch. */
|
||||
flags: Record<string, string | true>;
|
||||
/**
|
||||
* Values of each repeatable flag in argv order. Every repeatable flag in the
|
||||
* spec is present, holding an empty array when it was not passed.
|
||||
*/
|
||||
lists: Record<string, string[]>;
|
||||
positionals: string[];
|
||||
}
|
||||
|
||||
@@ -15,6 +25,19 @@ export interface SplitFlag {
|
||||
inlineValue?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a value-taking flag. `parseFlags` rejects such a flag without a value,
|
||||
* so anything present here is a string; the `true` case only arises for bare
|
||||
* switches, which callers never read through this helper.
|
||||
*/
|
||||
export function flagValue(
|
||||
flags: Record<string, string | true>,
|
||||
name: string,
|
||||
): string | undefined {
|
||||
const value = flags[name];
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
/** Split "--flag=value" into name and inline value; "--flag" has none. */
|
||||
export function splitFlag(arg: string): SplitFlag {
|
||||
const equals = arg.indexOf("=");
|
||||
@@ -53,6 +76,12 @@ export function parseFlags(
|
||||
helpCommand: string,
|
||||
): ParsedFlags {
|
||||
const flags: Record<string, string | true> = {};
|
||||
const lists: Record<string, string[]> = {};
|
||||
for (const [name, entry] of Object.entries(spec)) {
|
||||
if (entry.repeatable) {
|
||||
lists[name] = [];
|
||||
}
|
||||
}
|
||||
const positionals: string[] = [];
|
||||
const helpSuggestion = [`Run \`gitea-axi ${helpCommand} --help\` to see available flags`];
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
@@ -74,8 +103,12 @@ export function parseFlags(
|
||||
continue;
|
||||
}
|
||||
const consumed = consumeFlagValue(args, i, flag, helpSuggestion);
|
||||
flags[flag.name] = consumed.value;
|
||||
if (entry.repeatable) {
|
||||
lists[flag.name]!.push(consumed.value);
|
||||
} else {
|
||||
flags[flag.name] = consumed.value;
|
||||
}
|
||||
i = consumed.lastIndex;
|
||||
}
|
||||
return { flags, positionals };
|
||||
return { flags, lists, positionals };
|
||||
}
|
||||
|
||||
109
src/lookup.ts
Normal file
109
src/lookup.ts
Normal file
@@ -0,0 +1,109 @@
|
||||
import type { Label } from "gitea-js";
|
||||
import type { GiteaClient } from "./client.js";
|
||||
import type { RepoContext } from "./context.js";
|
||||
import { axiError, classifyHttpError } from "./errors.js";
|
||||
|
||||
/**
|
||||
* Name→ID resolution for the Gitea endpoints that only accept numeric ids.
|
||||
* Shared by every command that takes a `--label` or `--milestone` name.
|
||||
*/
|
||||
|
||||
const LABEL_PAGE_SIZE = 50;
|
||||
/** Guard against an unbounded loop if a server ignores paging and always returns a full page. */
|
||||
const LABEL_PAGE_LIMIT = 20;
|
||||
|
||||
/** Fetch every label in the repository, paging until the API runs out. */
|
||||
async function listAllLabels(api: GiteaClient, context: RepoContext): Promise<Label[]> {
|
||||
const labels: Label[] = [];
|
||||
for (let page = 1; page <= LABEL_PAGE_LIMIT; page++) {
|
||||
let batch: Label[];
|
||||
try {
|
||||
const response = await api.repos.issueListLabels(context.owner, context.name, {
|
||||
page,
|
||||
limit: LABEL_PAGE_SIZE,
|
||||
});
|
||||
batch = response.data ?? [];
|
||||
} catch (error) {
|
||||
throw classifyHttpError(error);
|
||||
}
|
||||
labels.push(...batch);
|
||||
if (batch.length < LABEL_PAGE_SIZE) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return labels;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve label names to their ids, case-insensitively. Every name must exist:
|
||||
* creating an issue while silently dropping a label the caller asked for would
|
||||
* misreport what was created.
|
||||
*/
|
||||
export async function resolveLabelIds(
|
||||
api: GiteaClient,
|
||||
context: RepoContext,
|
||||
names: string[],
|
||||
): Promise<number[]> {
|
||||
if (names.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const labels = await listAllLabels(api, context);
|
||||
const byName = new Map<string, number>();
|
||||
for (const label of labels) {
|
||||
if (label.name === undefined || label.id === undefined) {
|
||||
continue;
|
||||
}
|
||||
const key = label.name.toLowerCase();
|
||||
// First match wins, so a duplicate name resolves deterministically.
|
||||
if (!byName.has(key)) {
|
||||
byName.set(key, label.id);
|
||||
}
|
||||
}
|
||||
|
||||
const ids: number[] = [];
|
||||
for (const name of names) {
|
||||
const id = byName.get(name.toLowerCase());
|
||||
if (id === undefined) {
|
||||
const available = labels
|
||||
.map((label) => label.name)
|
||||
.filter((label): label is string => Boolean(label));
|
||||
throw axiError(
|
||||
`Label "${name}" not found in ${context.owner}/${context.name}` +
|
||||
(available.length > 0 ? ` (available: ${available.join(", ")})` : ""),
|
||||
"VALIDATION_ERROR",
|
||||
);
|
||||
}
|
||||
ids.push(id);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/** Resolve a milestone name to its id via the name-filtered milestone query. */
|
||||
export async function resolveMilestoneId(
|
||||
api: GiteaClient,
|
||||
context: RepoContext,
|
||||
name: string,
|
||||
): Promise<number> {
|
||||
let milestones;
|
||||
try {
|
||||
const response = await api.repos.issueGetMilestonesList(context.owner, context.name, {
|
||||
name,
|
||||
});
|
||||
milestones = response.data ?? [];
|
||||
} catch (error) {
|
||||
throw classifyHttpError(error);
|
||||
}
|
||||
// The `name` query only narrows the candidates — the title is re-checked here
|
||||
// so that neither the caller's casing nor a looser server-side match (Gitea
|
||||
// filters with a LIKE) can resolve to a milestone the caller did not name.
|
||||
const match = milestones.find(
|
||||
(milestone) => milestone.title?.toLowerCase() === name.toLowerCase(),
|
||||
);
|
||||
if (!match?.id) {
|
||||
throw axiError(
|
||||
`Milestone "${name}" not found in ${context.owner}/${context.name}`,
|
||||
"VALIDATION_ERROR",
|
||||
);
|
||||
}
|
||||
return match.id;
|
||||
}
|
||||
Reference in New Issue
Block a user