import { getCurrentBranchName, getYamlConfigContent, updateYamlConfigContent, } from '@ones-open/cli-utils' import { CI_DEPLOY_RELATIVE_PATH } from '@ones-open/cli-utils' import type { ProjectCIDeployConfig } from '@ones-open/cli-utils' import type { CISettingCLIOptionsSchema } from '@ones-open/cli-utils' import { merge } from '@senojs/lodash' import inquirer from 'inquirer' import type { QuestionCollection } from 'inquirer' import { join } from 'path' import { cwd } from 'process' const defaultBranchNames = new Set(['default', 'master', 'main']) function isDefaultBranchName(branchName: string) { return defaultBranchNames.has(branchName) } function convertCIDeploymentBranchName(branchName: string) { if (isDefaultBranchName(branchName)) return 'default' return branchName } async function displayCIDeploymentPrompts(options: CISettingCLIOptionsSchema) { const { branchName } = options const defaultBranchName = (await getCurrentBranchName()) || 'default' const CIDeploymentPrompts: QuestionCollection<{ branchName: string }> = [ { type: 'input', name: 'branchName', message: 'Branch name:', default: defaultBranchName, validate: (rawInput) => { const input = rawInput?.trim() if (!input || input.length === 0) return 'Branch name is required' return true }, askAnswered: true, when: !branchName, }, ] return inquirer.prompt<{ branchName: string }>(CIDeploymentPrompts, { branchName: branchName || defaultBranchName, }) } async function getCIDeploymentConfigContent(dirPath?: string) { const CIDeploymentConfigPath = dirPath ? join(dirPath, CI_DEPLOY_RELATIVE_PATH) : join(cwd(), CI_DEPLOY_RELATIVE_PATH) const CIDeploymentConfigContent = await getYamlConfigContent( CIDeploymentConfigPath, { enableFileExistsCheck: true, }, ) return CIDeploymentConfigContent ?? {} } async function updateCIDeploymentConfig( content: ProjectCIDeployConfig, options: { cwd: string; strategy: 'merge' | 'replace' } = { cwd: cwd(), strategy: 'merge' }, ) { const { cwd, strategy } = options const configPath = join(cwd, CI_DEPLOY_RELATIVE_PATH) let tempContent = content if (strategy === 'merge') { try { const configContent = await getCIDeploymentConfigContent(cwd) tempContent = merge(configContent, tempContent) } catch (error) { if (error instanceof Error) { throw new Error( `Error: ${error.message} \nPlease make sure current working directory is root of project`, ) } } } await updateYamlConfigContent(configPath, tempContent) } export { convertCIDeploymentBranchName, displayCIDeploymentPrompts, getCIDeploymentConfigContent, updateCIDeploymentConfig, }