UNPKG

@mesh-tech/mesh-cli

Version:

CLI for Mesh platform development utilities

77 lines (76 loc) 2.75 kB
import { execFileSync } from "node:child_process"; import * as crypto from "node:crypto"; import * as path from "node:path"; export const NUM_PORT_BLOCKS = 64; export const PORT_BLOCK_BASE = 40000; export const PORT_BLOCK_SIZE = 40; export const PORT_BLOCK_SERVICE_SUBRANGE = 24; export function sanitizeSlug(name) { const s = name .toLowerCase() .replace(/[^a-z0-9]+/g, "-") .replace(/^-+|-+$/g, ""); return s || "wt"; } export function worktreeHash(worktreeRoot) { return crypto.createHash("sha256").update(worktreeRoot).digest("hex").slice(0, 4); } export function portBlockFor(hash, isPrimary) { if (isPrimary) return 0; const n = parseInt(hash, 16); return 1 + (n % (NUM_PORT_BLOCKS - 1)); } export function blockBasePort(block) { return PORT_BLOCK_BASE + block * PORT_BLOCK_SIZE; } export function withAppScopedPortBlock(wt, appRoot) { if (wt.isPrimary) return wt; const appHash = worktreeHash(`${wt.worktreeRoot}#${path.resolve(appRoot)}`); return { ...wt, portBlock: portBlockFor(appHash, false) }; } export const STACK_SLUG_MAX = 16; export function worktreeStackName(baseName, wt) { if (!wt.token) return baseName; const cappedSlug = wt.slug.slice(0, STACK_SLUG_MAX).replace(/-+$/, ""); return `${baseName}-${cappedSlug}-${wt.hash}`; } export function stackNeedsWorktreeIsolation(stackName, wt) { return !!wt.token && !stackName.endsWith(`-${wt.hash}`); } const defaultGitRunner = (args, cwd) => execFileSync("git", args, { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }).trim(); export function resolveWorktreeIdentity(cwd = process.cwd(), gitRunner = defaultGitRunner) { let worktreeRoot; let isPrimary = true; try { worktreeRoot = path.resolve(gitRunner(["rev-parse", "--show-toplevel"], cwd)); const commonDir = gitRunner(["rev-parse", "--git-common-dir"], cwd); const primaryRoot = path.resolve(path.dirname(path.resolve(cwd, commonDir))); isPrimary = worktreeRoot === primaryRoot; } catch { return { worktreeRoot: path.resolve(cwd), isPrimary: true, slug: sanitizeSlug(path.basename(path.resolve(cwd))), hash: worktreeHash(path.resolve(cwd)), token: "", portBlock: 0, taskQueueSuffix: "", }; } const slug = sanitizeSlug(path.basename(worktreeRoot)); const hash = worktreeHash(worktreeRoot); const token = isPrimary ? "" : `${slug}-${hash}`; return { worktreeRoot, isPrimary, slug, hash, token, portBlock: portBlockFor(hash, isPrimary), taskQueueSuffix: token ? `-${token}` : "", }; }