UNPKG

@mesh-tech/mesh-cli

Version:

CLI for Mesh platform development utilities

90 lines (89 loc) 3.54 kB
import * as fs from "fs"; import * as path from "path"; import { logInfo } from "./log.js"; function findFileUpward(filename, startDir = process.cwd()) { let currentDir = startDir; const root = path.parse(currentDir).root; while (currentDir !== root) { const filePath = path.join(currentDir, filename); if (fs.existsSync(filePath)) { return filePath; } currentDir = path.dirname(currentDir); } return undefined; } export function detectContext(stageArg) { let tenant; let stage; const cwd = process.cwd(); if (fs.existsSync("Pulumi.yaml")) { const files = fs.readdirSync(".").filter((f) => f.startsWith("Pulumi.") && f.endsWith(".yaml") && f !== "Pulumi.yaml"); const configFile = files[0]; if (configFile) { const content = fs.readFileSync(configFile, "utf-8"); const tenantMatch = content.match(/^\s*mesh:tenant:\s*["']?([^"'\n]+)["']?/m); if (tenantMatch?.[1]) { tenant = tenantMatch[1].trim(); } const stageMatch = configFile.match(/Pulumi\.(.+)\.yaml/); if (stageMatch?.[1]) { stage = stageMatch[1]; } } } const sstConfigPath = findFileUpward("sst.config.ts"); let sstDir; if (sstConfigPath) { sstDir = path.dirname(sstConfigPath); const parentConfigPath = path.join(sstDir, "..", "config.ts"); if (fs.existsSync(parentConfigPath)) { const configContent = fs.readFileSync(parentConfigPath, "utf-8"); const tenantMatch = configContent.match(/tenant:\s*["']([^"']+)["']/); if (tenantMatch) { tenant = tenantMatch[1]; } } const sstStagePath = path.join(sstDir, ".sst", "stage"); if (fs.existsSync(sstStagePath)) { stage = fs.readFileSync(sstStagePath, "utf-8").trim(); } } if (!tenant) { const pathMatch = cwd.match(/tenants\/([^/]+)/); if (pathMatch) { tenant = pathMatch[1]; } } stage = stageArg || process.env.MESH_STAGE || process.env.SST_STAGE || stage || "dev"; tenant = process.env.MESH_TENANT || tenant || "mesh"; let platformEnv = stage; let platformEnvMap = {}; let defaultPlatformEnv; const configPath = sstDir ? path.join(sstDir, "..", "config.ts") : "../config.ts"; if (fs.existsSync(configPath)) { const configContent = fs.readFileSync(configPath, "utf-8"); const mapMatch = configContent.match(/platformEnvMap:\s*\{([^}]+)\}/); if (mapMatch?.[1]) { const entries = mapMatch[1].matchAll(/(\w+):\s*["']([^"']+)["']/g); for (const entry of entries) { const key = entry[1]; const value = entry[2]; if (key && value) { platformEnvMap[key] = value; } } } const defaultMatch = configContent.match(/defaultPlatformEnv:\s*["']([^"']+)["']/); if (defaultMatch?.[1]) { defaultPlatformEnv = defaultMatch[1]; } } const tenantPrefix = `${tenant}-`; const parsedEnv = stage.startsWith(tenantPrefix) ? stage.slice(tenantPrefix.length) : stage; platformEnv = platformEnvMap[parsedEnv] ?? platformEnvMap[stage] ?? defaultPlatformEnv ?? parsedEnv; logInfo(`Stage: ${stage}, Platform: ${platformEnv}, Tenant: ${tenant}`); return { tenant, stage, platformEnv }; }