All files / infrastructure/scripts/src/issue pick.ts

99.28% Statements 138/139
92.53% Branches 62/67
100% Functions 17/17
100% Lines 127/127

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299                                                                                1x   1x 1x   41x   1x   1x               1x 14x 14x   14x 14x 14x   14x 2x 2x     14x 14x 2x   14x 1x         1x     13x   12x             12x     1x         12x 12x             12x 12x   2x           2x 1x 1x     1x 1x 1x     11x   11x 11x   11x           1x         1x 17x 17x 17x   1x       1x 14x 14x 14x   1x       1x 17x 17x 17x     1x 9x 9x   2x 1x   1x 1x   1x     1x 8x     32x       8x         1x       8x     1x 8x 7x 1x 7x       1x 15x   14x 14x     1x 10x 10x 10x 1x       9x 1x   8x 10x 1x       7x   7x 7x 7x     1x 13x   13x 13x   13x 13x 3x 3x   10x     9x 9x     1x 28x 28x 14x 14x   13x 13x     14x 14x       14x 14x 13x   12x 10x   9x   8x   8x 8x   8x 8x 8x   1x 1x     7x        
import { autocomplete, confirm, select, text } from "@clack/prompts";
import { out, requireTerminal } from "../shared/adapters/io.ts";
import { orExit, type Cancellable } from "../shared/adapters/prompts.ts";
import type { Args } from "../shared/cli.ts";
import { optionValue } from "../shared/domain/cli.ts";
import { ExpectedError } from "../shared/errors.ts";
import {
    assignToMe,
    blockedBy,
    developBranch,
    isOnline,
    listIssues,
    listProjects,
    moveToInProgress,
    viewThread,
    type Issue,
    type Project,
} from "./adapters/gh.ts";
import { branchForIssue, checkout } from "./adapters/git.ts";
import { ISSUE_SCOPE_HINT, projectOptions, PROJECT_SCOPE_HINT } from "./adapters/prompts.ts";
import {
    areaFor,
    branchName,
    branchTypeFor,
    BRANCH_TYPES,
    isBranchType,
    slugify,
} from "./domain/branch.ts";
import { issueNumberFrom, type IssueThread } from "./domain/brief.ts";
import {
    blockedPickMessage,
    issueCountMessage,
    issueOptionMatches,
    issueOptions,
    issuePromptText,
    projectLoad,
    selectedProject,
} from "./domain/pick.ts";
import { issueSource } from "./domain/source.ts";
 
const CANCELLED = "Cancelled — still on the same branch.";
 
const TYPE_HINT = `--type=<${BRANCH_TYPES.join("|")}>`;
const NO_TERMINAL_HINT = `pass an issue number: pnpm issue:pick <number> [${TYPE_HINT}] [--project=<board>] [--title=<branch title>] [--force]`;
 
const or = <T>(value: Cancellable<T>): T => orExit(value, CANCELLED);
 
const BACK = Symbol("back to project list");
 
const NO_ARGS: Args = { flags: new Set(), positionals: [] };
 
interface Picked<T> {
    value: T | undefined;
    offline: boolean;
    only: boolean;
}
 
const pickProject = async (): Promise<Picked<Project>> => {
    const loading = out.spinner();
    loading.start("Asking gh what's available...");
 
    const live = listProjects();
    let projects = live;
    const offline = projectLoad(live, live.length > 0 || isOnline()) === "cache";
 
    if (offline) {
        loading.message("Reading cached projects...");
        projects = listProjects(true);
    }
 
    loading.stop("Ready.");
    if (offline)
        out.warn("gh is unreachable — showing cached projects and issues, which may be outdated.");
 
    if (projects.length === 0) {
        out.warn(
            offline
                ? "No cached projects to fall back to — run pick again once you're back online."
                : PROJECT_SCOPE_HINT,
        );
        return { value: undefined, offline, only: false };
    }
 
    if (projects.length === 1) return { value: projects[0], offline, only: true };
 
    const title = or(
        await select({
            message: "Project",
            options: projectOptions(projects),
        }),
    );
 
    return { value: selectedProject(projects, title), offline, only: false };
};
 
const pickIssue = async (
    project: Project,
    knownOffline: boolean,
    canGoBack: boolean,
): Promise<Issue | typeof BACK> => {
    const loading = out.spinner();
    loading.start(
        knownOffline
            ? `Reading cached issues for ${project.title}...`
            : `Reading ${project.title}...`,
    );
 
    let issues: Issue[];
    try {
        issues = listIssues(project.title, knownOffline);
    } catch {
        const failure = issueSource({
            knownOffline,
            requestFailed: true,
            online: !knownOffline && isOnline(),
        });
 
        if (failure === "auth-error") {
            loading.stop("Couldn't read issues.");
            throw new ExpectedError(ISSUE_SCOPE_HINT);
        }
 
        out.warn("gh is unreachable — showing cached issues, which may be outdated.");
        loading.message(`Reading cached issues for ${project.title}...`);
        issues = listIssues(project.title, true);
    }
 
    loading.stop(issueCountMessage(issues.length));
 
    const prompt = issuePromptText(issues.length);
    Iif (prompt.emptyWarning) out.warn(prompt.emptyWarning);
 
    return or(
        await autocomplete({
            message: prompt.message,
            placeholder: prompt.placeholder,
            maxItems: 12,
            options: issueOptions(canGoBack ? BACK : undefined, issues),
            filter: (search, { value }) => issueOptionMatches(BACK, value, search),
        }),
    );
};
 
const assign = (issue: number): void => {
    try {
        assignToMe(issue);
        out.success(`#${issue} assigned to you.`);
    } catch {
        out.warn(`Couldn't assign #${issue} to you — the branch is still yours.`);
    }
};
 
const moveToBoard = (project: Project, issue: Issue): void => {
    try {
        moveToInProgress(project, issue);
        out.success(`#${issue.number} moved to In Progress.`);
    } catch {
        out.warn(`Couldn't move #${issue.number} to In Progress — the branch is still yours.`);
    }
};
 
const claim = (branch: string, issue: Issue, project: Project | undefined): void => {
    assign(issue.number);
    if (project) moveToBoard(project, issue);
    out.end(branch);
};
 
const resumeBranch = async (project: Project, issue: Issue): Promise<boolean> => {
    const existing = branchForIssue(issue.number);
    if (!existing) return false;
 
    if (!or(await confirm({ message: `Branch ${existing} already exists — check it out?` })))
        return false;
 
    checkout(existing);
    claim(existing, issue, project);
 
    return true;
};
 
const promptBranch = async (issue: Issue): Promise<string> => {
    const type = or(
        await select({
            message: "Branch type",
            options: BRANCH_TYPES.map((value) => ({ value, label: value })),
        }),
    );
 
    const title = or(
        await text({
            message: "Branch title",
            initialValue: issue.title,
            validate: (value) =>
                slugify(value ?? "") ? undefined : "Needs at least one letter or digit.",
        }),
    );
 
    return branchName(type, areaFor(issue.labels), issue.number, title);
};
 
const boardFor = (title: string): Project | undefined => {
    const project = listProjects().find((candidate) => candidate.title === title);
    if (!project)
        out.warn(`No open board called "${title}" — the issue stays in its board column.`);
    return project;
};
 
/** Only a new branch is checked: resuming one means the work already started. */
const refuseIfBlocked = (issue: number, flags: ReadonlySet<string>): void => {
    if (flags.has("force")) return;
 
    const message = blockedPickMessage(issue, blockedBy(issue));
    if (message) throw new ExpectedError(message);
};
 
const newBranch = (thread: IssueThread, flags: ReadonlySet<string>): string => {
    const { number, labels } = thread;
    const type = optionValue(flags, "type") ?? branchTypeFor(labels);
    if (!type) {
        throw new ExpectedError(
            `#${number} is labelled ${labels.join(", ") || "nothing"}, which names no branch type — pass ${TYPE_HINT}.`,
        );
    }
    if (!isBranchType(type))
        throw new ExpectedError(`"${type}" isn't a branch type — pass ${TYPE_HINT}.`);
 
    const title = optionValue(flags, "title") ?? thread.title;
    if (!slugify(title))
        throw new ExpectedError(
            `"${title}" has no letter or digit to slug — pass --title=<branch title>.`,
        );
 
    refuseIfBlocked(number, flags);
 
    const branch = branchName(type, areaFor(labels), number, title);
    developBranch(number, branch);
    return branch;
};
 
const pickByNumber = (number: number, flags: ReadonlySet<string>): void => {
    out.begin(`🌱 Pick #${number}`);
 
    const thread = viewThread(number);
    const board = optionValue(flags, "project") ?? thread.boards[0]?.title;
 
    let branch = branchForIssue(number);
    if (branch) {
        checkout(branch);
        out.info(`Resumed the existing branch for #${number}.`);
    } else {
        branch = newBranch(thread, flags);
    }
 
    const issue: Issue = { number, title: thread.title, url: thread.url, labels: thread.labels };
    claim(branch, issue, board ? boardFor(board) : undefined);
};
 
export const pick = async ({ positionals, flags }: Args = NO_ARGS): Promise<void> => {
    const [requested] = positionals;
    if (requested) {
        const number = issueNumberFrom(requested);
        if (!number) throw new ExpectedError(`"${requested}" isn't an issue number or URL.`);
 
        pickByNumber(number, flags);
        return;
    }
 
    requireTerminal(NO_TERMINAL_HINT);
    out.begin("🌱 Pick an issue");
 
    // Choosing "← Back to project list" must re-run `pickProject`, not cancel the command.
    /* eslint-disable no-await-in-loop -- each prompt waits on the answer to the one before it */
    for (;;) {
        const { value: project, offline, only } = await pickProject();
        if (!project) return;
 
        const issue = await pickIssue(project, offline, !only);
        if (issue === BACK) continue;
 
        if (await resumeBranch(project, issue)) return;
 
        refuseIfBlocked(issue.number, flags);
 
        const branch = await promptBranch(issue);
        out.note(issue.url, branch);
 
        try {
            developBranch(issue.number, branch);
            claim(branch, issue, project);
        } catch (error) {
            out.error("gh issue develop failed.");
            throw error;
        }
 
        return;
    }
    /* eslint-enable no-await-in-loop */
};