CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
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 | /**
* Block J17 — Multi-template issue selector.
*
* Scans `.github/ISSUE_TEMPLATE/` (plus `.gluecron/ISSUE_TEMPLATE/`) on the
* default branch for `*.md` files, parses their YAML-frontmatter metadata
* (`name`, `about`, `title`, `labels`), and exposes the list to the
* new-issue flow so users can pick which template to start from.
*
* The frontmatter parser is purpose-built for this narrow shape — it's not a
* full YAML parser. All helpers are pure; `listIssueTemplates` wraps them
* with git I/O and returns `[]` on any failure.
*/
import { getBlob, getDefaultBranch, getTree } from "../git/repository";
import type { GitTreeEntry } from "../git/repository";
export const TEMPLATE_DIRS = [
".github/ISSUE_TEMPLATE",
".github/issue_template",
".gluecron/ISSUE_TEMPLATE",
".gluecron/issue_template",
];
const MAX_TEMPLATE_BYTES = 32 * 1024;
const MAX_TEMPLATES = 20;
export interface IssueTemplateMeta {
name: string | null;
about: string | null;
title: string | null;
labels: string[];
assignees: string[];
}
export interface IssueTemplate {
slug: string;
path: string;
name: string;
about: string | null;
title: string | null;
labels: string[];
assignees: string[];
body: string;
}
// ---------------------------------------------------------------------------
// Pure frontmatter parser
// ---------------------------------------------------------------------------
/**
* Extract `---\n<frontmatter>\n---\n<body>` from a template file.
* Returns `{meta: null, body: content}` if no frontmatter is present.
*/
export function splitFrontmatter(content: string): {
frontmatter: string | null;
body: string;
} {
if (!content.startsWith("---")) {
return { frontmatter: null, body: content };
}
const rest = content.slice(3);
// Frontmatter ends at the first "\n---" on its own line.
const match = rest.match(/\n---[\s]*\n/);
if (!match || match.index === undefined) {
return { frontmatter: null, body: content };
}
const frontmatter = rest.slice(0, match.index).replace(/^\n/, "");
const body = rest.slice(match.index + match[0].length);
return { frontmatter, body };
}
function unquote(raw: string): string {
const v = raw.trim();
if (!v) return "";
if (
(v.startsWith('"') && v.endsWith('"')) ||
(v.startsWith("'") && v.endsWith("'"))
) {
return v.slice(1, -1);
}
return v;
}
function parseList(raw: string): string[] {
const v = raw.trim();
if (!v) return [];
// Flow-list: [a, "b", c]
if (v.startsWith("[") && v.endsWith("]")) {
return v
.slice(1, -1)
.split(",")
.map((s) => unquote(s.trim()))
.filter(Boolean);
}
// Comma-separated fallback
return v
.split(",")
.map((s) => unquote(s.trim()))
.filter(Boolean);
}
/**
* Pure: parse the tiny subset of YAML that issue-template frontmatter uses.
* Supports flat `key: value` pairs, block-scalar values on continuation lines
* (not common here) are flattened into a single line, and YAML block-list
* values (`labels:\n - bug\n - triage`).
*/
export function parseFrontmatterMeta(text: string): IssueTemplateMeta {
const meta: IssueTemplateMeta = {
name: null,
about: null,
title: null,
labels: [],
assignees: [],
};
if (!text) return meta;
const lines = text.replace(/\r\n?/g, "\n").split("\n");
let i = 0;
while (i < lines.length) {
const line = lines[i];
if (!line.trim() || line.trim().startsWith("#")) {
i++;
continue;
}
const colonIdx = line.indexOf(":");
if (colonIdx <= 0 || /^\s/.test(line)) {
i++;
continue;
}
const key = line.slice(0, colonIdx).trim().toLowerCase();
const rest = line.slice(colonIdx + 1).trim();
if (rest === "" || rest === ">" || rest === "|") {
// Block list? Peek at next indented `- ` lines.
const items: string[] = [];
i++;
while (i < lines.length && /^\s+-\s?/.test(lines[i])) {
items.push(unquote(lines[i].replace(/^\s+-\s?/, "")));
i++;
}
if (key === "labels") meta.labels = items.filter(Boolean);
else if (key === "assignees") meta.assignees = items.filter(Boolean);
continue;
}
if (key === "name") meta.name = unquote(rest);
else if (key === "about") meta.about = unquote(rest);
else if (key === "title") meta.title = unquote(rest);
else if (key === "labels") meta.labels = parseList(rest);
else if (key === "assignees") meta.assignees = parseList(rest);
i++;
}
return meta;
}
/** Pure: derive a URL-safe slug from the filename and fall back to the meta name. */
export function slugFromFilename(filename: string): string {
const base = filename.replace(/\.(md|yml|yaml)$/i, "");
return base
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 64);
}
/** Pure: merge filename + parsed meta + body into a single template row. */
export function buildTemplateFromFile(
filename: string,
content: string,
dirPath: string
): IssueTemplate {
const { frontmatter, body } = splitFrontmatter(content);
const meta = frontmatter
? parseFrontmatterMeta(frontmatter)
: {
name: null,
about: null,
title: null,
labels: [],
assignees: [],
};
const slug = slugFromFilename(filename);
return {
slug,
path: dirPath ? `${dirPath}/${filename}` : filename,
name: meta.name || filename.replace(/\.(md|yml|yaml)$/i, ""),
about: meta.about,
title: meta.title,
labels: meta.labels,
assignees: meta.assignees,
body: body.trim(),
};
}
// ---------------------------------------------------------------------------
// Git-layer wrapper
// ---------------------------------------------------------------------------
async function safeTree(
owner: string,
repo: string,
ref: string,
treePath: string
): Promise<GitTreeEntry[]> {
try {
return await getTree(owner, repo, ref, treePath);
} catch {
return [];
}
}
/**
* Scan the template directories and return a de-duplicated list of issue
* templates in the order they appear on disk (alphabetised by path).
* Silently swallows all git failures.
*/
export async function listIssueTemplates(
owner: string,
repo: string
): Promise<IssueTemplate[]> {
try {
const ref = (await getDefaultBranch(owner, repo)) || "HEAD";
const seenSlugs = new Set<string>();
const out: IssueTemplate[] = [];
for (const dir of TEMPLATE_DIRS) {
const entries = await safeTree(owner, repo, ref, dir);
if (!entries.length) continue;
const files = entries
.filter(
(e) =>
e.type === "blob" &&
/\.(md|markdown)$/i.test(e.name) &&
!/^config\./i.test(e.name)
)
.sort((a, b) => a.name.localeCompare(b.name));
for (const f of files) {
if (out.length >= MAX_TEMPLATES) break;
const fullPath = `${dir}/${f.name}`;
let blob: Awaited<ReturnType<typeof getBlob>> | null = null;
try {
blob = await getBlob(owner, repo, ref, fullPath);
} catch {
blob = null;
}
if (!blob || blob.isBinary || !blob.content) continue;
const content =
blob.content.length > MAX_TEMPLATE_BYTES
? blob.content.slice(0, MAX_TEMPLATE_BYTES)
: blob.content;
const template = buildTemplateFromFile(f.name, content, dir);
if (seenSlugs.has(template.slug)) continue;
seenSlugs.add(template.slug);
out.push(template);
}
if (out.length >= MAX_TEMPLATES) break;
}
return out;
} catch (err) {
console.error("[issue-templates] listIssueTemplates failed:", err);
return [];
}
}
/** Find a template by slug from a prefetched list. Pure. */
export function findTemplateBySlug(
templates: IssueTemplate[],
slug: string | null | undefined
): IssueTemplate | null {
if (!slug) return null;
return templates.find((t) => t.slug === slug) || null;
}
export const __internal = {
splitFrontmatter,
parseFrontmatterMeta,
slugFromFilename,
buildTemplateFromFile,
findTemplateBySlug,
TEMPLATE_DIRS,
MAX_TEMPLATE_BYTES,
MAX_TEMPLATES,
};
|