@theholocron/holocron-plugin-github 5.0.0-alpha.502 → 5.0.0-alpha.504

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -30,6 +30,11 @@ export declare const resolveDeployToken: import("@theholocron/cli").FeatureResol
30
30
  export declare const resolveUserSyncToken: import("@theholocron/cli").FeatureResolver;
31
31
  /** Resolves the org-level token (`HOLOCRON_ORG_TOKEN`, keyring key `github.org`). */
32
32
  export declare const resolveOrgToken: import("@theholocron/cli").FeatureResolver;
33
+ /** The area declaration the plugin is handed from `repo.labels`. */
34
+ interface AreaConfig {
35
+ areas?: Record<string, string[]>;
36
+ scopes?: Record<string, string>;
37
+ }
33
38
  interface CiOptions {
34
39
  repo: string;
35
40
  }
@@ -333,6 +338,7 @@ export declare class GitHubSource implements Source {
333
338
  removeWorkflowFile(name: string): Promise<void>;
334
339
  writeRepoFile(path: string, contents: string): Promise<void>;
335
340
  syncLabels(canonical: ReadonlyArray<LabelDef>, stale: ReadonlyArray<string>): Promise<string>;
341
+ ensureLabels(labels: ReadonlyArray<LabelDef>): Promise<string>;
336
342
  syncProperties(values: Record<string, string | string[]>): Promise<string>;
337
343
  getOrgPropertyValues(name: string): Promise<string[] | undefined>;
338
344
  addOrgPropertyValues(name: string, values: string[]): Promise<string[]>;
@@ -430,6 +436,8 @@ export interface GitHubPluginOptions extends ResolveTokenInput {
430
436
  /** Label that marks an issue as in review. */
431
437
  inReview: string;
432
438
  };
439
+ /** `repo.labels` (the area map), handed in by the loader for the `issue-types` probe. */
440
+ areaLabels?: AreaConfig;
433
441
  /** Override base URL for tests. Defaults to https://api.github.com. */
434
442
  baseUrl?: string;
435
443
  /** Override `fetch` for tests. Defaults to global `fetch`. */
@@ -463,6 +471,7 @@ export declare function createPlugin(options: GitHubPluginOptions): {
463
471
  name: string;
464
472
  probes: {
465
473
  token: import("@theholocron/cli").Probe;
474
+ "issue-types": import("@theholocron/cli").Probe;
466
475
  connection: import("@theholocron/cli").Probe;
467
476
  };
468
477
  capabilities: {
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from "node:module";
2
- import { AuthError, MissingTokenError, ProviderApiError, connectionProbe, createFeatureResolver, pickByCreation, readKeysLimited, reportProgress, tokenExpectations } from "@theholocron/cli";
2
+ import { AuthError, MissingTokenError, ProviderApiError, areaLabelsForFiles, areaLabelsForTitle, connectionProbe, createFeatureResolver, pickByCreation, readKeysLimited, reportProgress, tokenExpectations } from "@theholocron/cli";
3
3
  import { createGitHubClient, createGitHubClient as createGitHubClient$1 } from "@theholocron/github-client";
4
4
  import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
5
5
  import { dirname, join } from "node:path";
@@ -262,6 +262,43 @@ function createFieldSetter(client, repo) {
262
262
  }
263
263
  };
264
264
  }
265
+ // src/capabilities/issue-kind.ts
266
+ /** The Type name of each kind. */
267
+ const KIND_TYPE_NAMES = {
268
+ bug: "Bug",
269
+ feature: "Feature",
270
+ task: "Task"
271
+ };
272
+ /** The kind each label names where there is no Type. */
273
+ const LABEL_KINDS = {
274
+ bug: "bug",
275
+ enhancement: "feature",
276
+ chore: "task"
277
+ };
278
+ const TYPE_KINDS = new Map(Object.entries(KIND_TYPE_NAMES).map(([kind, name]) => [name.toLowerCase(), kind]));
279
+ /** The kind of an issue: its Type, else the one kind its labels name (two different ones name none). */
280
+ function kindOfIssue(issue) {
281
+ const typed = TYPE_KINDS.get(issue.type?.name?.toLowerCase() ?? "");
282
+ if (typed) return typed;
283
+ const named = new Set(issue.labels.flatMap((l) => LABEL_KINDS[l.name.toLowerCase()] ?? []));
284
+ return named.size === 1 ? [...named][0] : void 0;
285
+ }
286
+ /** Whether the issue's Type is already the kind's. */
287
+ function hasKindType(issue, kind) {
288
+ return issue.type?.name?.toLowerCase() === KIND_TYPE_NAMES[kind].toLowerCase();
289
+ }
290
+ /** Sets the Type of issue `number`; a refusal is returned as a `dropped` line, anything else (a rate limit) is thrown. */
291
+ async function writeKind(client, repo, number, kind) {
292
+ const name = KIND_TYPE_NAMES[kind];
293
+ try {
294
+ await client.issues.updateIssue(repo, number, { type: name });
295
+ return;
296
+ } catch (err) {
297
+ const why = fieldRefusal(err);
298
+ if (why === void 0) throw err;
299
+ return `kind ${name} (${why})`;
300
+ }
301
+ }
265
302
  // src/capabilities/issue-priority.ts
266
303
  /** The Priority field's option for each level. */
267
304
  const PRIORITY_OPTION_NAMES = {
@@ -392,6 +429,7 @@ async function readIssues(client, repo, selector, info) {
392
429
  const { labels, priority } = splitLabels(issue.labels.map((l) => l.name));
393
430
  const body = issue.body?.replace(MARKER, "").trimEnd();
394
431
  const migratedFrom = issue.body ? MARKER.exec(issue.body)?.[1] : void 0;
432
+ const kind = kindOfIssue(issue);
395
433
  records.push({
396
434
  key: `#${issue.number}`,
397
435
  url: issue.html_url,
@@ -401,6 +439,7 @@ async function readIssues(client, repo, selector, info) {
401
439
  closed: issue.state === "closed",
402
440
  ...priority ? { priority } : {},
403
441
  labels: labels.filter((l) => !l.toLowerCase().startsWith("status:")),
442
+ ...kind ? { kind } : {},
404
443
  ...issue.assignee ? { assignee: {
405
444
  id: issue.assignee.login,
406
445
  displayName: issue.assignee.name ?? issue.assignee.login,
@@ -457,6 +496,8 @@ async function importIssues(client, repo, records, options = {}) {
457
496
  const number = await createFromRecord(client, repo, record, options);
458
497
  const field = await priority.set(number, record.priority, { isNew: true });
459
498
  if (field.note) dropped.push(field.note);
499
+ const kindNote = record.kind ? await writeKind(client, repo, number, record.kind) : void 0;
500
+ if (kindNote) dropped.push(kindNote);
460
501
  results.push({
461
502
  source: record.key,
462
503
  key: `#${number}`,
@@ -569,6 +610,8 @@ async function create(client, repo, record, options, priority) {
569
610
  const number = await createFromRecord(client, repo, record, options);
570
611
  const field = await priority.set(number, record.priority, { isNew: true });
571
612
  if (field.note) dropped.push(field.note);
613
+ const kindNote = record.kind ? await writeKind(client, repo, number, record.kind) : void 0;
614
+ if (kindNote) dropped.push(kindNote);
572
615
  return {
573
616
  source: record.key,
574
617
  key: `#${number}`,
@@ -608,6 +651,9 @@ async function update(client, repo, issue, record, options, priority) {
608
651
  }
609
652
  const field = await priority.set(issue.number, record.priority, { dryRun: options.dryRun });
610
653
  if (field.changed) changes.push("priority field");
654
+ const kindWrong = record.kind !== void 0 && !hasKindType(issue, record.kind);
655
+ if (kindWrong) changes.push("kind");
656
+ const kindNote = kindWrong && !options.dryRun ? await writeKind(client, repo, issue.number, record.kind) : void 0;
611
657
  const comments = await client.issues.listComments(repo, issue.number);
612
658
  const seen = new Set(comments.map((c) => COMMENT_HEADER.exec(c.body)?.[1]));
613
659
  const missing = record.comments.filter((c) => !seen.has(c.createdAt));
@@ -622,7 +668,11 @@ async function update(client, repo, issue, record, options, priority) {
622
668
  created: false,
623
669
  updated: changes.length > 0,
624
670
  changes,
625
- dropped: [...droppedFor(record), ...field.note ? [field.note] : []]
671
+ dropped: [
672
+ ...droppedFor(record),
673
+ ...field.note ? [field.note] : [],
674
+ ...kindNote ? [kindNote] : []
675
+ ]
626
676
  };
627
677
  }
628
678
  // src/capabilities/issues-update.ts
@@ -2007,6 +2057,25 @@ async function syncLabels(client, repo, canonical, stale) {
2007
2057
  }
2008
2058
  return `${created} created, ${updated} updated, ${deleted} deleted`;
2009
2059
  }
2060
+ /**
2061
+ * Make the labels a repo lacks and change nothing else: an existing label (found without regard to case) keeps its
2062
+ * colour and description, and nothing is deleted. Used for the `area:<name>` family, which is not in the canonical set.
2063
+ */
2064
+ async function ensureLabels(client, repo, labels) {
2065
+ const existing = await client.labels.listLabels(repo);
2066
+ const have = new Set(existing.map((l) => l.name.toLowerCase()));
2067
+ let created = 0;
2068
+ for (const label of labels) {
2069
+ if (have.has(label.name.toLowerCase())) continue;
2070
+ await client.labels.createLabel(repo, {
2071
+ name: label.name,
2072
+ color: label.color,
2073
+ description: label.description
2074
+ });
2075
+ created++;
2076
+ }
2077
+ return `${created} created, ${labels.length - created} already there`;
2078
+ }
2010
2079
  // src/capabilities/property-fix-hints.ts
2011
2080
  /** GitHub's wording when a custom property value is not one the organization's definition allows. */
2012
2081
  const NOT_ALLOWED = /Value '([^']+)' is not allowed for property '([^']+)'/g;
@@ -2638,6 +2707,9 @@ var GitHubSource = class {
2638
2707
  async syncLabels(canonical, stale) {
2639
2708
  return syncLabels(this.client, this.repo, canonical, stale);
2640
2709
  }
2710
+ async ensureLabels(labels) {
2711
+ return ensureLabels(this.client, this.repo, labels);
2712
+ }
2641
2713
  async syncProperties(values) {
2642
2714
  return syncProperties(this.client, this.repo, values, this.orgClient ?? this.client);
2643
2715
  }
@@ -2800,6 +2872,599 @@ async function ensureDir(path) {
2800
2872
  throw err;
2801
2873
  }
2802
2874
  }
2875
+ // src/probes/issue-types/github-api.ts
2876
+ const PAGE = 100;
2877
+ const PROJECTS_OF = `query($ids: [ID!]!) { nodes(ids: $ids) { ... on Issue { id projectItems(first: 20) { nodes { project { id } } } } } }`;
2878
+ const ADD_ITEM = `mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }`;
2879
+ function toItem(issue) {
2880
+ return {
2881
+ number: issue.number,
2882
+ title: issue.title,
2883
+ state: issue.state,
2884
+ labels: issue.labels.map((l) => l.name),
2885
+ type: issue.type?.name ?? null,
2886
+ milestone: issue.milestone ?? null,
2887
+ nodeId: issue.node_id ?? "",
2888
+ isPullRequest: issue.pull_request !== void 0,
2889
+ createdAt: issue.created_at ?? ""
2890
+ };
2891
+ }
2892
+ /**
2893
+ * The backfill's reads and writes over the GitHub client. `client` reads and writes issues (the `github.issues` token);
2894
+ * `orgClient` reads and writes the organization's projects (the `github.org` token). Each method is the one call, or the
2895
+ * fixed few, its name says, so the probe's logic is tested against a fake of {@link BackfillApi} and this stays thin.
2896
+ */
2897
+ function createBackfillApi(client, orgClient, repo) {
2898
+ const org = repo.split("/")[0];
2899
+ const projects = new GitHubProjects(orgClient.graphql, { repo });
2900
+ let fieldList;
2901
+ const fields = async () => fieldList ??= client.issueFields.list(org);
2902
+ return {
2903
+ async list(page) {
2904
+ return (await client.issues.listIssues(repo, {
2905
+ state: "all",
2906
+ sort: "created",
2907
+ direction: "asc",
2908
+ per_page: PAGE,
2909
+ page
2910
+ })).map(toItem);
2911
+ },
2912
+ async get(number) {
2913
+ return toItem(await client.issues.getIssue(repo, number));
2914
+ },
2915
+ async parent(number) {
2916
+ const parent = await client.issues.getParent(repo, number);
2917
+ return parent ? {
2918
+ number: parent.number,
2919
+ milestone: parent.milestone?.number ?? null
2920
+ } : null;
2921
+ },
2922
+ async labelNames() {
2923
+ return new Set((await client.labels.listLabels(repo)).map((l) => l.name.toLowerCase()));
2924
+ },
2925
+ async milestoneNumber(title) {
2926
+ return (await client.issues.listMilestones(repo, { state: "all" })).find((m) => m.title.toLowerCase() === title.toLowerCase())?.number;
2927
+ },
2928
+ async projectId(title) {
2929
+ return (await projects.find(org, title))?.id;
2930
+ },
2931
+ async projectsOf(nodeIds) {
2932
+ const data = await orgClient.graphql.query(PROJECTS_OF, { ids: nodeIds });
2933
+ const out = /* @__PURE__ */ new Map();
2934
+ for (const node of data.nodes) if (node?.id) out.set(node.id, (node.projectItems?.nodes ?? []).map((i) => i.project.id));
2935
+ return out;
2936
+ },
2937
+ async fieldNames() {
2938
+ try {
2939
+ return new Set((await fields()).map((f) => f.name.toLowerCase()));
2940
+ } catch (err) {
2941
+ const why = fieldRefusal(err);
2942
+ if (why === void 0) throw err;
2943
+ return why;
2944
+ }
2945
+ },
2946
+ async fieldValues(number) {
2947
+ const byId = new Map((await fields()).map((f) => [f.id, f.name.toLowerCase()]));
2948
+ const values = await client.issueFields.values(repo, number);
2949
+ return new Set(values.map((v) => v.issue_field_name?.toLowerCase() ?? byId.get(v.issue_field_id) ?? ""));
2950
+ },
2951
+ async files(number) {
2952
+ return (await client.pulls.listFiles(repo, number)).map((f) => f.filename);
2953
+ },
2954
+ async setType(number, type) {
2955
+ await client.issues.updateIssue(repo, number, { type });
2956
+ },
2957
+ async addLabels(number, labels) {
2958
+ await client.issues.addLabels(repo, number, labels);
2959
+ },
2960
+ async setMilestone(number, milestone) {
2961
+ await client.issues.updateIssue(repo, number, { milestone });
2962
+ },
2963
+ async addToProject(projectId, nodeId) {
2964
+ await orgClient.graphql.query(ADD_ITEM, {
2965
+ project: projectId,
2966
+ content: nodeId
2967
+ });
2968
+ }
2969
+ };
2970
+ }
2971
+ // src/probes/issue-types/gather.ts
2972
+ /** Whether a day (`YYYY-MM-DD`) is before the start of the window. */
2973
+ const before = (item, since) => since !== void 0 && item.createdAt.slice(0, 10) < since;
2974
+ /** The issues named by `--issues`, past the cursor, at most `limit` of them. */
2975
+ async function named(api, options, isRateLimited) {
2976
+ const numbers = [...new Set(options.issues)].sort((a, b) => a - b).filter((n) => n > options.after);
2977
+ const out = {
2978
+ items: [],
2979
+ more: numbers.length > options.limit,
2980
+ rateLimited: false,
2981
+ pullRequestsSkipped: 0
2982
+ };
2983
+ for (const number of numbers.slice(0, options.limit)) try {
2984
+ const item = await api.get(number);
2985
+ if (item.isPullRequest && !options.pullRequests) out.pullRequestsSkipped++;
2986
+ else out.items.push(item);
2987
+ } catch (err) {
2988
+ if (!isRateLimited(err)) throw err;
2989
+ return {
2990
+ ...out,
2991
+ more: true,
2992
+ rateLimited: true
2993
+ };
2994
+ }
2995
+ return out;
2996
+ }
2997
+ /**
2998
+ * The items one run looks at: with `--issues` those numbers, otherwise every issue of the repository oldest first, a
2999
+ * page at a time, past the `--after` cursor and on or after `--since`, until `--limit` are kept. Issue numbers rise with
3000
+ * creation, so the last number read is a cursor the next run can resume from. A rate limit ends the read with what it has.
3001
+ */
3002
+ async function gather(api, options, isRateLimited) {
3003
+ if (options.issues) return named(api, options, isRateLimited);
3004
+ const out = {
3005
+ items: [],
3006
+ more: false,
3007
+ rateLimited: false,
3008
+ pullRequestsSkipped: 0
3009
+ };
3010
+ try {
3011
+ for (let page = 1;; page++) {
3012
+ const batch = await api.list(page);
3013
+ if (batch.length === 0) return out;
3014
+ for (const item of batch) {
3015
+ if (item.number <= options.after || before(item, options.since)) continue;
3016
+ if (item.isPullRequest && !options.pullRequests) {
3017
+ out.pullRequestsSkipped++;
3018
+ continue;
3019
+ }
3020
+ if (out.items.length >= options.limit) return {
3021
+ ...out,
3022
+ more: true
3023
+ };
3024
+ out.items.push(item);
3025
+ }
3026
+ }
3027
+ } catch (err) {
3028
+ if (!isRateLimited(err)) throw err;
3029
+ return {
3030
+ ...out,
3031
+ more: true,
3032
+ rateLimited: true
3033
+ };
3034
+ }
3035
+ }
3036
+ // src/probes/issue-types/plan-type.ts
3037
+ /** The kind labels and the Type each one means (spec `tech-github-area-labels`, decision 3). */
3038
+ const KIND_TYPES = {
3039
+ bug: "Bug",
3040
+ enhancement: "Feature",
3041
+ chore: "Task"
3042
+ };
3043
+ /**
3044
+ * The Type an issue gets from its kind labels. One that has a Type keeps it, whatever its labels say; one with exactly
3045
+ * one of `bug`, `enhancement` and `chore` gets that label's Type; one with two or more is `ambiguous` and left for a
3046
+ * person (the spec's rule: the probe never picks between two kinds); one with none has no source.
3047
+ */
3048
+ function planType(item) {
3049
+ if (item.type) return { skip: "typed" };
3050
+ const kinds = [...new Set(item.labels.map((l) => l.toLowerCase()).filter((l) => l in KIND_TYPES))];
3051
+ if (kinds.length === 0) return { skip: "no-kind-label" };
3052
+ if (kinds.length > 1) return {
3053
+ skip: "ambiguous",
3054
+ labels: kinds
3055
+ };
3056
+ return { set: KIND_TYPES[kinds[0]] };
3057
+ }
3058
+ // src/probes/issue-types/report.ts
3059
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
3060
+ const GROUPS = [
3061
+ ["project", "a project"],
3062
+ ["milestone", "a milestone"],
3063
+ ["priority", "a Priority"],
3064
+ ["effort", "an Effort"]
3065
+ ];
3066
+ /** The command the maintainer runs to continue, from the cursor. */
3067
+ function resumeCommand(options, cursor) {
3068
+ const flags = ["--after", String(cursor)];
3069
+ if (options.issues) flags.push("--issues", options.issues.join(","));
3070
+ if (options.since) flags.push("--since", options.since);
3071
+ flags.push("--limit", String(options.limit));
3072
+ if (options.milestone) flags.push("--milestone", options.milestone);
3073
+ if (options.project) flags.push("--project", options.project);
3074
+ if (options.pullRequests) flags.push("--pull-requests");
3075
+ return `holocron probe github issue-types -- ${flags.join(" ")}`;
3076
+ }
3077
+ /** Prints the counts, what was left for a person, the lists of what is still missing and how to go on. */
3078
+ function reportBackfill(ctx, input) {
3079
+ const { tally, options, dryRun, more, rateLimited, fields } = input;
3080
+ const verb = dryRun ? "would be set" : "set";
3081
+ ctx.say({
3082
+ status: "heading",
3083
+ label: "Backfill"
3084
+ });
3085
+ const passed = tally.pullRequestsSkipped;
3086
+ ctx.say({
3087
+ status: "info",
3088
+ label: "summary",
3089
+ detail: `read ${plural(tally.examined, "item")}` + (tally.pullRequestsRead > 0 ? ` (${plural(tally.pullRequestsRead, "pull request")})` : "") + `; ${dryRun ? "would change" : "changed"} ${tally.changed}; passed over ${plural(passed, "pull request")}${passed > 0 ? " (give --pull-requests to include them)" : ""}; ${plural(tally.failed, "failure")}` + (more ? `; ${rateLimited ? "stopped by GitHub's rate limit" : `stopped at the limit of ${options.limit}`}, more remain` : "; the window is finished")
3090
+ });
3091
+ const types = Object.entries(tally.typeSet).map(([name, n]) => `${name} ${n}`).join(", ");
3092
+ ctx.say({
3093
+ status: "info",
3094
+ label: "Type",
3095
+ detail: `${types || "none"} ${verb}; ${tally.typed} already typed, ${tally.noKind} with no kind label, ${tally.ambiguous.length} with two kind labels`
3096
+ });
3097
+ for (const a of tally.ambiguous) ctx.say({
3098
+ status: "info",
3099
+ label: `#${a.number}`,
3100
+ detail: `has ${a.labels.join(" and ")}: left for a person to choose`
3101
+ });
3102
+ ctx.say({
3103
+ status: "info",
3104
+ label: "area labels",
3105
+ detail: `added to ${plural(tally.areaLabelsAdded, "item")}`
3106
+ });
3107
+ for (const label of tally.missingAreaLabels) ctx.say({
3108
+ status: "info",
3109
+ label,
3110
+ detail: "wanted but the repository has no such label: run `holocron setup` first"
3111
+ });
3112
+ ctx.say({
3113
+ status: "info",
3114
+ label: "milestone",
3115
+ detail: `${verb} on ${tally.milestoneSet.parent + tally.milestoneSet.explicit} (${tally.milestoneSet.parent} from a parent, ${tally.milestoneSet.explicit} from --milestone)`
3116
+ });
3117
+ ctx.say({
3118
+ status: "info",
3119
+ label: "project",
3120
+ detail: `${plural(tally.projectSet, "issue")} ${dryRun ? "would be added" : "added"} from --project`
3121
+ });
3122
+ ctx.say({
3123
+ status: "heading",
3124
+ label: `Still lacking, among the ${plural(tally.examined, "item")} read${dryRun ? ", after the changes above" : ""}`
3125
+ });
3126
+ if (tally.skippedFields !== void 0) ctx.say({
3127
+ status: "fail",
3128
+ label: "Priority, Effort",
3129
+ detail: `NOT checked, so the lists below are incomplete: the token (github.issues) was refused reading the organization issue fields (${tally.skippedFields})`
3130
+ });
3131
+ for (const [group, noun] of GROUPS) {
3132
+ if (!(group === "project" || group === "milestone" || fields.includes(group))) continue;
3133
+ const items = tally.lacking[group];
3134
+ ctx.say({
3135
+ status: "info",
3136
+ label: `without ${noun}`,
3137
+ detail: `${items.length} of ${plural(tally.examined, "item")} read`
3138
+ });
3139
+ for (const item of items) ctx.say({
3140
+ status: "info",
3141
+ label: `#${item.number}`,
3142
+ detail: `${item.state}: ${item.title}`
3143
+ });
3144
+ }
3145
+ if (more && tally.last !== void 0) ctx.say({
3146
+ status: "info",
3147
+ label: "resume",
3148
+ detail: `${rateLimited ? "GitHub's rate limit stopped the run" : "the limit was reached"}; to continue: ${resumeCommand(options, tally.last)}`
3149
+ });
3150
+ else if (more) ctx.say({
3151
+ status: "info",
3152
+ label: "resume",
3153
+ detail: "GitHub's rate limit stopped the run before it finished one item; run it again later"
3154
+ });
3155
+ else ctx.say({
3156
+ status: "info",
3157
+ label: "resume",
3158
+ detail: "the window is finished"
3159
+ });
3160
+ }
3161
+ // src/probes/issue-types/backfill.ts
3162
+ /** The numbers the report is made of. */
3163
+ const emptyTally = () => ({
3164
+ examined: 0,
3165
+ pullRequestsSkipped: 0,
3166
+ typeSet: {},
3167
+ typed: 0,
3168
+ noKind: 0,
3169
+ ambiguous: [],
3170
+ areaLabelsAdded: 0,
3171
+ missingAreaLabels: /* @__PURE__ */ new Set(),
3172
+ milestoneSet: {
3173
+ parent: 0,
3174
+ explicit: 0
3175
+ },
3176
+ projectSet: 0,
3177
+ lacking: {
3178
+ project: [],
3179
+ milestone: [],
3180
+ priority: [],
3181
+ effort: []
3182
+ },
3183
+ failed: 0,
3184
+ changed: 0,
3185
+ pullRequestsRead: 0,
3186
+ last: void 0,
3187
+ skippedFields: void 0
3188
+ });
3189
+ /** How many changes the tally holds, to tell whether one item added any. */
3190
+ const changes = (t) => Object.values(t.typeSet).reduce((a, b) => a + b, 0) + t.areaLabelsAdded + t.milestoneSet.parent + t.milestoneSet.explicit + t.projectSet;
3191
+ /** How an issue is named in a row. */
3192
+ const labelOf = (item) => `#${item.number}`;
3193
+ /** Reads what the run needs before it starts: labels, the named milestone and project, the organization's issue fields. Says why and returns nothing when a name does not exist. */
3194
+ async function prepare(run, tally) {
3195
+ const { api, ctx, options } = run;
3196
+ const setup = {
3197
+ labelNames: await api.labelNames(),
3198
+ fields: []
3199
+ };
3200
+ if (options.milestone !== void 0) {
3201
+ setup.milestone = await api.milestoneNumber(options.milestone);
3202
+ if (setup.milestone === void 0) {
3203
+ ctx.say({
3204
+ status: "fail",
3205
+ label: "milestone",
3206
+ detail: `${options.milestone} is not a milestone of this repository`
3207
+ });
3208
+ return;
3209
+ }
3210
+ }
3211
+ if (options.project !== void 0) {
3212
+ setup.projectId = await api.projectId(options.project);
3213
+ if (setup.projectId === void 0) {
3214
+ ctx.say({
3215
+ status: "fail",
3216
+ label: "project",
3217
+ detail: `${options.project} is not a project of this organization`
3218
+ });
3219
+ return;
3220
+ }
3221
+ }
3222
+ const names = await api.fieldNames();
3223
+ if (typeof names === "string") tally.skippedFields = names;
3224
+ else setup.fields = ["priority", "effort"].filter((f) => names.has(f));
3225
+ return setup;
3226
+ }
3227
+ /** Does one issue or pull request; throws for a rate limit or a failed request, which the caller tells apart. */
3228
+ async function handle(run, setup, tally, item, projects) {
3229
+ const { api, ctx, areas, options } = run;
3230
+ const n = item.number;
3231
+ const wanted = item.isPullRequest ? areaLabelsForFiles(await api.files(n), areas.areas) : areaLabelsForTitle(item.title, areas.scopes);
3232
+ const have = new Set(item.labels.map((l) => l.toLowerCase()));
3233
+ const add = [];
3234
+ for (const label of wanted) {
3235
+ if (have.has(label.toLowerCase())) continue;
3236
+ if (setup.labelNames.has(label.toLowerCase())) add.push(label);
3237
+ else tally.missingAreaLabels.add(label);
3238
+ }
3239
+ if (add.length > 0) {
3240
+ await ctx.write(`add ${add.join(", ")} to ${labelOf(item)}`, () => api.addLabels(n, add));
3241
+ tally.areaLabelsAdded++;
3242
+ }
3243
+ if (item.isPullRequest) return;
3244
+ const type = planType(item);
3245
+ if ("set" in type) {
3246
+ await ctx.write(`set Type ${type.set} on ${labelOf(item)}`, () => api.setType(n, type.set));
3247
+ tally.typeSet[type.set] = (tally.typeSet[type.set] ?? 0) + 1;
3248
+ } else if (type.skip === "typed") tally.typed++;
3249
+ else if (type.skip === "no-kind-label") tally.noKind++;
3250
+ else tally.ambiguous.push({
3251
+ number: n,
3252
+ labels: type.labels
3253
+ });
3254
+ let milestone = item.milestone !== null;
3255
+ if (!milestone) {
3256
+ const parent = await api.parent(n);
3257
+ const fromParent = parent?.milestone;
3258
+ const target = fromParent ?? setup.milestone;
3259
+ if (target !== void 0) {
3260
+ const source = typeof fromParent === "number" ? "parent" : "explicit";
3261
+ const why = source === "parent" ? `from its parent #${parent?.number}` : `from --milestone ${options.milestone}`;
3262
+ await ctx.write(`set milestone on ${labelOf(item)} ${why}`, () => api.setMilestone(n, target));
3263
+ tally.milestoneSet[source]++;
3264
+ milestone = true;
3265
+ }
3266
+ }
3267
+ if (!milestone) tally.lacking.milestone.push(item);
3268
+ let onProject = projects.length > 0;
3269
+ if (!onProject && setup.projectId !== void 0) {
3270
+ const id = setup.projectId;
3271
+ await ctx.write(`add ${labelOf(item)} to project ${options.project}`, () => api.addToProject(id, item.nodeId));
3272
+ tally.projectSet++;
3273
+ onProject = true;
3274
+ }
3275
+ if (!onProject) tally.lacking.project.push(item);
3276
+ if (setup.fields.length > 0) {
3277
+ const values = await api.fieldValues(n);
3278
+ for (const field of setup.fields) if (!values.has(field)) tally.lacking[field].push(item);
3279
+ }
3280
+ }
3281
+ /**
3282
+ * The backfill of `holocron probe github issue-types` (spec `tech-github-area-labels`, rollout item 5): reads a window of
3283
+ * issues, and for each adds what it can derive and nothing else.
3284
+ *
3285
+ * - **Type** from the kind labels (`bug`, `enhancement`, `chore`); one that has a Type keeps it, one with two kind labels
3286
+ * is listed and left.
3287
+ * - **Area labels** from the title's scope, or, for a pull request with `--pull-requests`, from its changed files; only
3288
+ * added, and only when the label exists (`holocron setup` makes them).
3289
+ * - **Milestone** from the issue's parent, else `--milestone` for an issue in the window named by `--issues` or `--since`.
3290
+ * - **Project** from `--project` for such an issue that is on no project.
3291
+ *
3292
+ * Nothing is overwritten and no label is removed. Priority and Effort are never set, only listed when missing. Every
3293
+ * change goes through `ctx.write`, so `--dry-run` says `would ...` and writes nothing. A rate limit ends the run with the
3294
+ * cursor to resume from; any other failure is a row for that issue and the run goes on.
3295
+ */
3296
+ async function runBackfill(run) {
3297
+ const { ctx, api, options } = run;
3298
+ const tally = emptyTally();
3299
+ const setup = await prepare(run, tally);
3300
+ if (!setup) return;
3301
+ const read = await gather(api, options, run.isRateLimited);
3302
+ tally.pullRequestsSkipped = read.pullRequestsSkipped;
3303
+ const projects = /* @__PURE__ */ new Map();
3304
+ const ids = read.items.filter((i) => !i.isPullRequest).map((i) => i.nodeId);
3305
+ try {
3306
+ for (let at = 0; at < ids.length; at += 100) for (const [id, found] of await api.projectsOf(ids.slice(at, at + 100))) projects.set(id, found);
3307
+ } catch (err) {
3308
+ if (!run.isRateLimited(err)) throw err;
3309
+ read.rateLimited = true;
3310
+ read.more = true;
3311
+ read.items.length = 0;
3312
+ }
3313
+ let stopped = read.rateLimited;
3314
+ for (const item of read.items) {
3315
+ const before = changes(tally);
3316
+ try {
3317
+ await handle(run, setup, tally, item, projects.get(item.nodeId) ?? []);
3318
+ if (changes(tally) > before) tally.changed++;
3319
+ } catch (err) {
3320
+ if (run.isRateLimited(err)) {
3321
+ stopped = true;
3322
+ break;
3323
+ }
3324
+ ctx.say({
3325
+ status: "fail",
3326
+ label: labelOf(item),
3327
+ detail: errorMessage(err)
3328
+ });
3329
+ tally.failed++;
3330
+ }
3331
+ tally.examined++;
3332
+ if (item.isPullRequest) tally.pullRequestsRead++;
3333
+ tally.last = item.number;
3334
+ }
3335
+ reportBackfill(ctx, {
3336
+ tally,
3337
+ options,
3338
+ dryRun: ctx.dryRun,
3339
+ more: read.more || stopped,
3340
+ rateLimited: stopped,
3341
+ fields: setup.fields
3342
+ });
3343
+ }
3344
+ const VALUED = [
3345
+ "--issues",
3346
+ "--since",
3347
+ "--after",
3348
+ "--limit",
3349
+ "--milestone",
3350
+ "--project"
3351
+ ];
3352
+ const INTEGER = /^\d+$/;
3353
+ const DAY = /^\d{4}-\d{2}-\d{2}$/;
3354
+ const MAX_RANGE = 1e3;
3355
+ /** `12,15,20-23` to `[12, 15, 20, 21, 22, 23]`, or `undefined` for text that is not such a list. */
3356
+ function numbersOf(text) {
3357
+ const out = [];
3358
+ for (const part of text.split(",")) {
3359
+ const [from, to, ...rest] = part.trim().split("-");
3360
+ if (rest.length > 0 || !INTEGER.test(from)) return void 0;
3361
+ const end = to === void 0 ? Number(from) : INTEGER.test(to) ? Number(to) : -1;
3362
+ if (end < Number(from) || end - Number(from) > MAX_RANGE) return void 0;
3363
+ for (let n = Number(from); n <= end; n++) out.push(n);
3364
+ }
3365
+ return out;
3366
+ }
3367
+ /** The words after `issue-types`, read into options, or the one thing wrong with them. */
3368
+ function parseArgs(args) {
3369
+ const options = {
3370
+ after: 0,
3371
+ limit: 100,
3372
+ pullRequests: false
3373
+ };
3374
+ for (let i = 0; i < args.length; i++) {
3375
+ const flag = args[i];
3376
+ if (flag === "--pull-requests") {
3377
+ options.pullRequests = true;
3378
+ continue;
3379
+ }
3380
+ if (!VALUED.includes(flag)) return {
3381
+ ok: false,
3382
+ message: `unknown argument ${flag}`
3383
+ };
3384
+ const value = args[++i];
3385
+ if (value === void 0 || value.startsWith("--")) return {
3386
+ ok: false,
3387
+ message: `${flag} needs a value`
3388
+ };
3389
+ if (flag === "--issues") {
3390
+ const issues = numbersOf(value);
3391
+ if (!issues) return {
3392
+ ok: false,
3393
+ message: `--issues takes numbers and ranges such as 12,15,20-25, not ${value}`
3394
+ };
3395
+ options.issues = issues;
3396
+ } else if (flag === "--since") {
3397
+ if (!DAY.test(value)) return {
3398
+ ok: false,
3399
+ message: `--since takes a day as YYYY-MM-DD, not ${value}`
3400
+ };
3401
+ options.since = value;
3402
+ } else if (flag === "--after") {
3403
+ if (!INTEGER.test(value)) return {
3404
+ ok: false,
3405
+ message: `--after takes a whole number, not ${value}`
3406
+ };
3407
+ options.after = Number(value);
3408
+ } else if (flag === "--limit") {
3409
+ if (!INTEGER.test(value) || Number(value) < 1) return {
3410
+ ok: false,
3411
+ message: `--limit takes a whole number of at least 1, not ${value}`
3412
+ };
3413
+ options.limit = Number(value);
3414
+ } else if (flag === "--milestone") options.milestone = value;
3415
+ else options.project = value;
3416
+ }
3417
+ if ((options.milestone || options.project) && !options.issues && !options.since) return {
3418
+ ok: false,
3419
+ message: "--milestone and --project need a window to apply to: name it with --issues or --since"
3420
+ };
3421
+ return {
3422
+ ok: true,
3423
+ options
3424
+ };
3425
+ }
3426
+ // src/probes/issue-types/issue-types.ts
3427
+ /**
3428
+ * `holocron probe github issue-types`: the one-time backfill of spec `tech-github-area-labels` (rollout item 5), a writer
3429
+ * the maintainer runs. It sets the Type of an issue from its kind labels, adds `area:<name>` labels, fills a milestone
3430
+ * and a project where a source exists, and ends with the list of every issue it read that still lacks a project, a
3431
+ * milestone, a Priority or an Effort. See `backfill.ts` for the rules. Run it with `--dry-run` first.
3432
+ *
3433
+ * Not verified against the live API: writing an issue's Type, adding an issue to a project, and the endpoints that read an
3434
+ * issue's field values and parent.
3435
+ */
3436
+ function issueTypesProbe(ctx) {
3437
+ return {
3438
+ summary: "Backfill issues: set Type from the kind labels, add area labels, fill milestone and project where a source exists, and list what still lacks a project, milestone, Priority or Effort. Never overwrites a value. Run with --dry-run first.",
3439
+ writes: true,
3440
+ async run(probe) {
3441
+ const parsed = parseArgs(probe.args ?? []);
3442
+ if (!parsed.ok) {
3443
+ probe.say({
3444
+ status: "fail",
3445
+ label: "arguments",
3446
+ detail: parsed.message
3447
+ });
3448
+ return;
3449
+ }
3450
+ try {
3451
+ await runBackfill({
3452
+ ctx: probe,
3453
+ api: ctx.makeApi(),
3454
+ options: parsed.options,
3455
+ areas: ctx.areas,
3456
+ isRateLimited
3457
+ });
3458
+ } catch (err) {
3459
+ probe.say({
3460
+ status: "fail",
3461
+ label: "issue-types",
3462
+ detail: errorMessage(err)
3463
+ });
3464
+ }
3465
+ }
3466
+ };
3467
+ }
2803
3468
  // src/probes/token/expectations.ts
2804
3469
  /** The same rules in every layer that runs the workflow: a laptop (`local` inherits `dev`) and CI. */
2805
3470
  function everywhere(rules) {
@@ -3314,6 +3979,10 @@ function createPlugin(options) {
3314
3979
  resolve: (envName) => TOKEN_RESOLVERS[envName]?.(options),
3315
3980
  tokenNames: Object.keys(TOKEN_RESOLVERS)
3316
3981
  }),
3982
+ "issue-types": issueTypesProbe({
3983
+ makeApi: () => createBackfillApi(makeCtx(resolveIssuesToken).client, makeCtx(resolveOrgToken).client, options.repo),
3984
+ areas: options.areaLabels ?? {}
3985
+ }),
3317
3986
  connection: connectionProbe({
3318
3987
  provider: "GitHub",
3319
3988
  url: options.baseUrl ?? "https://api.github.com",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/holocron-plugin-github",
3
- "version": "5.0.0-alpha.502",
3
+ "version": "5.0.0-alpha.504",
4
4
  "description": "Holocron plugin for GitHub. Implements source, ci, secrets, environments, and issues capabilities against the GitHub REST API.",
5
5
  "keywords": [
6
6
  "ci",
@@ -44,21 +44,21 @@
44
44
  "tsx": "4.23.15",
45
45
  "typescript": "^5.9.3",
46
46
  "vitest": "^5.1.0",
47
- "@theholocron/cli": "5.0.0-alpha.502",
48
- "@theholocron/fs-utils": "^1.17.0-alpha.5",
49
- "@theholocron/github-client": "^1.58.0-alpha.45",
50
47
  "@theholocron/eslint-config": "^8.9.0-alpha.21",
51
- "@theholocron/http-client": "^1.58.0-alpha.45",
48
+ "@theholocron/cli": "5.0.0-alpha.504",
49
+ "@theholocron/fs-utils": "^1.17.0-alpha.5",
50
+ "@theholocron/http-client": "^1.58.0-alpha.46",
52
51
  "@theholocron/tsconfig": "^8.9.0-alpha.21",
53
52
  "@theholocron/tsdown-config": "^8.9.0-alpha.21",
54
53
  "@theholocron/misc-utils": "^1.17.0-alpha.5",
54
+ "@theholocron/github-client": "^1.58.0-alpha.46",
55
55
  "@theholocron/vitest-config": "^8.9.0-alpha.21"
56
56
  },
57
57
  "peerDependencies": {
58
58
  "@theholocron/fs-utils": "^1.16.0",
59
59
  "@theholocron/github-client": "^1.58.0",
60
60
  "@theholocron/misc-utils": "^1.16.0",
61
- "@theholocron/cli": "5.0.0-alpha.502"
61
+ "@theholocron/cli": "5.0.0-alpha.504"
62
62
  },
63
63
  "engines": {
64
64
  "node": ">=22"