1import { alchemyLabelKeys } from "../Labels.ts";
2
3export const lastSegment = (value: string) => {
4 const trimmed = value.replace(/\/+$/, "");
5 const parts = trimmed.split("/");
6 return parts[parts.length - 1] || trimmed;
7};
8
9export const instanceIdOf = (value: string) => lastSegment(value);
10
11export const encodeDescription = (
12 labels: Record<string, string>,
13 description: string | undefined,
14): string => {
15 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
16 return description ? `${marker}\n${description}` : marker;
17};
18
19export const parseDescription = (
20 description: string | undefined,
21): {
22 labels: Record<string, string>;
23 description: string | undefined;
24} => {
25 if (!description?.startsWith("[alchemy ")) {
26 return { labels: {}, description };
27 }
28 const end = description.indexOf("]");
29 if (end < 0) return { labels: {}, description };
30 const labels: Record<string, string> = {};
31 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
32 const eq = part.indexOf("=");
33 if (eq > 0) {
34 labels[part.slice(0, eq)] = part.slice(eq + 1);
35 }
36 }
37 const rest = description.slice(end + 1).replace(/^\n/, "");
38 return { labels, description: rest.length > 0 ? rest : undefined };
39};
40
41export const hasOwnershipMarker = (description: string | undefined) =>
42 Object.keys(parseDescription(description).labels).some((key) =>
43 key.startsWith("alchemy-"),
44 );
45
46export const matchesOwnership = (
47 description: string | undefined,
48 labels: Record<string, string>,
49) =>
50 parseDescription(description).labels[alchemyLabelKeys.id] ===
51 labels[alchemyLabelKeys.id];