mirror of
https://github.com/beilunyang/moemail.git
synced 2026-08-21 16:22:48 +08:00
refactor(deploy): enhance environment variable handling in deployment scripts
This commit is contained in:
@@ -117,11 +117,11 @@ const updateDatabaseConfig = (dbId: string) => {
|
|||||||
"wrangler.email.json",
|
"wrangler.email.json",
|
||||||
"wrangler.cleanup.json",
|
"wrangler.cleanup.json",
|
||||||
];
|
];
|
||||||
|
|
||||||
for (const filename of configFiles) {
|
for (const filename of configFiles) {
|
||||||
const configPath = resolve(filename);
|
const configPath = resolve(filename);
|
||||||
if (!existsSync(configPath)) continue;
|
if (!existsSync(configPath)) continue;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const json = JSON.parse(readFileSync(configPath, "utf-8"));
|
const json = JSON.parse(readFileSync(configPath, "utf-8"));
|
||||||
if (json.d1_databases && json.d1_databases.length > 0) {
|
if (json.d1_databases && json.d1_databases.length > 0) {
|
||||||
@@ -140,7 +140,7 @@ const updateDatabaseConfig = (dbId: string) => {
|
|||||||
*/
|
*/
|
||||||
const updateKVConfig = (namespaceId: string) => {
|
const updateKVConfig = (namespaceId: string) => {
|
||||||
console.log(`📝 Updating KV namespace ID (${namespaceId}) in configurations...`);
|
console.log(`📝 Updating KV namespace ID (${namespaceId}) in configurations...`);
|
||||||
|
|
||||||
// KV命名空间只在主wrangler.json中使用
|
// KV命名空间只在主wrangler.json中使用
|
||||||
const wranglerPath = resolve("wrangler.json");
|
const wranglerPath = resolve("wrangler.json");
|
||||||
if (existsSync(wranglerPath)) {
|
if (existsSync(wranglerPath)) {
|
||||||
@@ -165,11 +165,11 @@ const checkAndCreateDatabase = async () => {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const database = await getDatabase();
|
const database = await getDatabase();
|
||||||
|
|
||||||
if (!database || !database.uuid) {
|
if (!database || !database.uuid) {
|
||||||
throw new Error('Database object is missing a valid UUID');
|
throw new Error('Database object is missing a valid UUID');
|
||||||
}
|
}
|
||||||
|
|
||||||
updateDatabaseConfig(database.uuid);
|
updateDatabaseConfig(database.uuid);
|
||||||
console.log(`✅ Database "${DATABASE_NAME}" already exists (ID: ${database.uuid})`);
|
console.log(`✅ Database "${DATABASE_NAME}" already exists (ID: ${database.uuid})`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -177,11 +177,11 @@ const checkAndCreateDatabase = async () => {
|
|||||||
console.log(`⚠️ Database not found, creating new database...`);
|
console.log(`⚠️ Database not found, creating new database...`);
|
||||||
try {
|
try {
|
||||||
const database = await createDatabase();
|
const database = await createDatabase();
|
||||||
|
|
||||||
if (!database || !database.uuid) {
|
if (!database || !database.uuid) {
|
||||||
throw new Error('Database object is missing a valid UUID');
|
throw new Error('Database object is missing a valid UUID');
|
||||||
}
|
}
|
||||||
|
|
||||||
updateDatabaseConfig(database.uuid);
|
updateDatabaseConfig(database.uuid);
|
||||||
console.log(`✅ Database "${DATABASE_NAME}" created successfully (ID: ${database.uuid})`);
|
console.log(`✅ Database "${DATABASE_NAME}" created successfully (ID: ${database.uuid})`);
|
||||||
} catch (createError) {
|
} catch (createError) {
|
||||||
@@ -259,7 +259,7 @@ const checkAndCreatePages = async () => {
|
|||||||
if (!CUSTOM_DOMAIN && pages.subdomain) {
|
if (!CUSTOM_DOMAIN && pages.subdomain) {
|
||||||
console.log("⚠️ CUSTOM_DOMAIN is empty, using pages default domain...");
|
console.log("⚠️ CUSTOM_DOMAIN is empty, using pages default domain...");
|
||||||
console.log("📝 Updating environment variables...");
|
console.log("📝 Updating environment variables...");
|
||||||
|
|
||||||
// 更新环境变量为默认的Pages域名
|
// 更新环境变量为默认的Pages域名
|
||||||
const appUrl = `https://${pages.subdomain}`;
|
const appUrl = `https://${pages.subdomain}`;
|
||||||
updateEnvVar("CUSTOM_DOMAIN", appUrl);
|
updateEnvVar("CUSTOM_DOMAIN", appUrl);
|
||||||
@@ -278,7 +278,7 @@ const pushPagesSecret = () => {
|
|||||||
console.log("🔐 Pushing environment secrets to Pages...");
|
console.log("🔐 Pushing environment secrets to Pages...");
|
||||||
|
|
||||||
// 定义运行时所需的环境变量列表
|
// 定义运行时所需的环境变量列表
|
||||||
const runtimeEnvVars = ['AUTH_GITHUB_ID', 'AUTH_GITHUB_SECRET', 'AUTH_SECRET'];
|
const runtimeEnvVars = ['AUTH_GITHUB_ID', 'AUTH_GITHUB_SECRET', 'AUTH_GOOGLE_ID', 'AUTH_GOOGLE_SECRET', 'AUTH_SECRET'];
|
||||||
|
|
||||||
// 兼容老的部署方式,如果这些环境变量不存在,则说明是老的部署方式,跳过推送
|
// 兼容老的部署方式,如果这些环境变量不存在,则说明是老的部署方式,跳过推送
|
||||||
for (const varName of runtimeEnvVars) {
|
for (const varName of runtimeEnvVars) {
|
||||||
@@ -287,17 +287,17 @@ const pushPagesSecret = () => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 确保.env文件存在
|
// 确保.env文件存在
|
||||||
if (!existsSync(resolve('.env'))) {
|
if (!existsSync(resolve('.env'))) {
|
||||||
setupEnvFile();
|
setupEnvFile();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 创建一个临时文件,只包含运行时所需的环境变量
|
// 创建一个临时文件,只包含运行时所需的环境变量
|
||||||
const envContent = readFileSync(resolve('.env'), 'utf-8');
|
const envContent = readFileSync(resolve('.env'), 'utf-8');
|
||||||
const runtimeEnvFile = resolve('.env.runtime');
|
const runtimeEnvFile = resolve('.env.runtime');
|
||||||
|
|
||||||
// 从.env文件中提取运行时变量
|
// 从.env文件中提取运行时变量
|
||||||
const runtimeEnvContent = envContent
|
const runtimeEnvContent = envContent
|
||||||
.split('\n')
|
.split('\n')
|
||||||
@@ -305,7 +305,7 @@ const pushPagesSecret = () => {
|
|||||||
const trimmedLine = line.trim();
|
const trimmedLine = line.trim();
|
||||||
// 跳过注释和空行
|
// 跳过注释和空行
|
||||||
if (!trimmedLine || trimmedLine.startsWith('#')) return false;
|
if (!trimmedLine || trimmedLine.startsWith('#')) return false;
|
||||||
|
|
||||||
// 检查是否为运行时所需的环境变量
|
// 检查是否为运行时所需的环境变量
|
||||||
for (const varName of runtimeEnvVars) {
|
for (const varName of runtimeEnvVars) {
|
||||||
if (line.startsWith(`${varName} =`) || line.startsWith(`${varName}=`)) {
|
if (line.startsWith(`${varName} =`) || line.startsWith(`${varName}=`)) {
|
||||||
@@ -315,16 +315,16 @@ const pushPagesSecret = () => {
|
|||||||
return false;
|
return false;
|
||||||
})
|
})
|
||||||
.join('\n');
|
.join('\n');
|
||||||
|
|
||||||
// 写入临时文件
|
// 写入临时文件
|
||||||
writeFileSync(runtimeEnvFile, runtimeEnvContent);
|
writeFileSync(runtimeEnvFile, runtimeEnvContent);
|
||||||
|
|
||||||
// 使用临时文件推送secrets
|
// 使用临时文件推送secrets
|
||||||
execSync(`pnpm dlx wrangler pages secret bulk ${runtimeEnvFile}`, { stdio: "inherit" });
|
execSync(`pnpm dlx wrangler pages secret bulk ${runtimeEnvFile}`, { stdio: "inherit" });
|
||||||
|
|
||||||
// 清理临时文件
|
// 清理临时文件
|
||||||
execSync(`rm ${runtimeEnvFile}`, { stdio: "inherit" });
|
execSync(`rm ${runtimeEnvFile}`, { stdio: "inherit" });
|
||||||
|
|
||||||
console.log("✅ Secrets pushed successfully");
|
console.log("✅ Secrets pushed successfully");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("❌ Failed to push secrets:", error);
|
console.error("❌ Failed to push secrets:", error);
|
||||||
@@ -381,14 +381,14 @@ const setupEnvFile = () => {
|
|||||||
console.log("📄 Setting up environment file...");
|
console.log("📄 Setting up environment file...");
|
||||||
const envFilePath = resolve(".env");
|
const envFilePath = resolve(".env");
|
||||||
const envExamplePath = resolve(".env.example");
|
const envExamplePath = resolve(".env.example");
|
||||||
|
|
||||||
// 如果.env文件不存在,则从.env.example复制创建
|
// 如果.env文件不存在,则从.env.example复制创建
|
||||||
if (!existsSync(envFilePath) && existsSync(envExamplePath)) {
|
if (!existsSync(envFilePath) && existsSync(envExamplePath)) {
|
||||||
console.log("⚠️ .env file does not exist, creating from example...");
|
console.log("⚠️ .env file does not exist, creating from example...");
|
||||||
|
|
||||||
// 从示例文件复制
|
// 从示例文件复制
|
||||||
let envContent = readFileSync(envExamplePath, "utf-8");
|
let envContent = readFileSync(envExamplePath, "utf-8");
|
||||||
|
|
||||||
// 填充当前的环境变量
|
// 填充当前的环境变量
|
||||||
const envVarMatches = envContent.match(/^([A-Z_]+)\s*=\s*".*?"/gm);
|
const envVarMatches = envContent.match(/^([A-Z_]+)\s*=\s*".*?"/gm);
|
||||||
if (envVarMatches) {
|
if (envVarMatches) {
|
||||||
@@ -400,7 +400,7 @@ const setupEnvFile = () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
writeFileSync(envFilePath, envContent);
|
writeFileSync(envFilePath, envContent);
|
||||||
console.log("✅ .env file created from example");
|
console.log("✅ .env file created from example");
|
||||||
} else if (existsSync(envFilePath)) {
|
} else if (existsSync(envFilePath)) {
|
||||||
@@ -417,22 +417,22 @@ const setupEnvFile = () => {
|
|||||||
const updateEnvVar = (name: string, value: string) => {
|
const updateEnvVar = (name: string, value: string) => {
|
||||||
// 首先更新进程环境变量
|
// 首先更新进程环境变量
|
||||||
process.env[name] = value;
|
process.env[name] = value;
|
||||||
|
|
||||||
// 然后尝试更新.env文件
|
// 然后尝试更新.env文件
|
||||||
const envFilePath = resolve(".env");
|
const envFilePath = resolve(".env");
|
||||||
if (!existsSync(envFilePath)) {
|
if (!existsSync(envFilePath)) {
|
||||||
setupEnvFile();
|
setupEnvFile();
|
||||||
}
|
}
|
||||||
|
|
||||||
let envContent = readFileSync(envFilePath, "utf-8");
|
let envContent = readFileSync(envFilePath, "utf-8");
|
||||||
const regex = new RegExp(`^${name}\\s*=\\s*".*?"`, "m");
|
const regex = new RegExp(`^${name}\\s*=\\s*".*?"`, "m");
|
||||||
|
|
||||||
if (envContent.match(regex)) {
|
if (envContent.match(regex)) {
|
||||||
envContent = envContent.replace(regex, `${name} = "${value}"`);
|
envContent = envContent.replace(regex, `${name} = "${value}"`);
|
||||||
} else {
|
} else {
|
||||||
envContent += `\n${name} = "${value}"`;
|
envContent += `\n${name} = "${value}"`;
|
||||||
}
|
}
|
||||||
|
|
||||||
writeFileSync(envFilePath, envContent);
|
writeFileSync(envFilePath, envContent);
|
||||||
console.log(`✅ Updated ${name} in .env file`);
|
console.log(`✅ Updated ${name} in .env file`);
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user