Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

4.6 KB
Raw Blame
import { dispatchIssueWrite } from "../../sync/dispatch-issue-write";
import { canSyncTask } from "../../sync/eligibility";
import { eq } from "drizzle-orm";
import db from "../../../database";
import { externalLinkTable } from "../../../database/schema";
import type { GitlabConfig } from "../config";
import { createGitlabClient } from "./gitlab-api";

const namedColorToHex: Record<string, string> = {
  red: "EF4444",
  orange: "F97316",
  amber: "F59E0B",
  yellow: "EAB308",
  lime: "84CC16",
  green: "22C55E",
  emerald: "10B981",
  teal: "14B8A6",
  cyan: "0092B8",
  sky: "00A6F4",
  blue: "155DFC",
  indigo: "6366F1",
  violet: "8B5CF6",
  purple: "A855F7",
  fuchsia: "C800DE",
  pink: "EC4899",
  rose: "F43F5E",
  gray: "6B7280",
  slate: "64748B",
  zinc: "71717A",
  neutral: "737373",
  stone: "78716C",
};

function toHexColor(color: string): string {
  const lower = color.toLowerCase().replace(/^#/, "");
  if (namedColorToHex[lower]) {
    return namedColorToHex[lower];
  }
  if (/^[0-9a-f]{6}$/i.test(lower)) {
    return lower;
  }
  if (/^[0-9a-f]{3}$/i.test(lower)) {
    const [r, g, b] = lower.split("");
    return `${r}${r}${g}${g}${b}${b}`;
  }
  return "6B7280";
}

async function getGitlabIssueContext(taskId: string) {
  const externalLinks = await db.query.externalLinkTable.findMany({
    where: eq(externalLinkTable.taskId, taskId),
    with: {
      integration: true,
    },
  });

  // Called from label controllers, bypassing the registry's isActive filter.
  const externalLink = externalLinks.find(
    (link) =>
      link.resourceType === "issue" &&
      link.integration?.type === "gitlab" &&
      link.integration.isActive === true,
  );

  if (!externalLink?.integration) {
    return null;
  }

  if (!(await canSyncTask(taskId, externalLink.integration.id))) return null;

  let config: GitlabConfig;
  try {
    config = JSON.parse(externalLink.integration.config) as GitlabConfig;
  } catch {
    return null;
  }

  if (!config.accessToken || !config.baseUrl) {
    return null;
  }

  const issueIid = Number.parseInt(externalLink.externalId, 10);
  if (Number.isNaN(issueIid)) {
    console.warn("Invalid GitLab issue externalId for label sync", {
      externalLinkId: externalLink.id,
      externalId: externalLink.externalId,
      taskId,
    });
    return null;
  }

  return {
    externalLink,
    expectedConfig: externalLink.integration.config,
    client: createGitlabClient(config),
    config,
    issueIid,
  };
}

function containsTaskFieldLabel(labelName: string) {
  // GitLab interprets add_labels/remove_labels as comma-separated names.
  return labelName.split(",").some((name) => {
    const label = name.trim();
    return label.startsWith("priority:") || label.startsWith("status:");
  });
}

export async function syncLabelToGitlab(
  taskId: string,
  labelName: string,
  labelColor: string,
) {
  // These labels drive task fields on the webhook return path. Ordinary label
  // permissions must not grant the ability to update status or priority.
  if (containsTaskFieldLabel(labelName)) return;
  const ctx = await getGitlabIssueContext(taskId);
  if (!ctx) return;

  const { client, config, issueIid } = ctx;

  const labels = await client.listLabels(config.projectPath);

  if (!labels.some((l) => l.name === labelName)) {
    try {
      const created = await dispatchIssueWrite(
        ctx.externalLink,
        ctx.expectedConfig,
        () =>
          client.createLabel(
            config.projectPath,
            labelName,
            toHexColor(labelColor),
          ),
      );
      if (!created) return;
    } catch (error) {
      console.error(`Failed to create label "${labelName}" in GitLab:`, error);
      return;
    }
  }

  try {
    const issue = await client.getIssue(config.projectPath, issueIid);
    if (issue.labels?.includes(labelName)) {
      return;
    }
    await dispatchIssueWrite(ctx.externalLink, ctx.expectedConfig, () =>
      client.updateIssue(config.projectPath, issueIid, {
        add_labels: labelName,
      }),
    );
  } catch (error) {
    console.error(`Failed to add label "${labelName}" to GitLab issue:`, error);
  }
}

export async function removeLabelFromGitlab(taskId: string, labelName: string) {
  if (containsTaskFieldLabel(labelName)) return;
  const ctx = await getGitlabIssueContext(taskId);
  if (!ctx) return;

  const { client, config, issueIid } = ctx;

  try {
    await dispatchIssueWrite(ctx.externalLink, ctx.expectedConfig, () =>
      client.updateIssue(config.projectPath, issueIid, {
        remove_labels: labelName,
      }),
    );
  } catch (error) {
    console.error(
      `Failed to remove label "${labelName}" from GitLab issue:`,
      error,
    );
  }
}