mirror of
https://gitee.com/mirrors/AllinSSL.git
synced 2026-03-11 09:11:10 +08:00
【新增】插件git同步模块,用于同步项目内容,加速项目开发
【调整】前端暗色问题
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
export const DEFAULT_PLUGIN_NAME = 'vite-plugin-turborepo-deploy';
|
||||
export const DEFAULT_COMMIT_SEPARATOR = '/** 提交分隔符 **/';
|
||||
export const DEFAULT_GIT_MAX_SCAN_COUNT = 50;
|
||||
export const DEFAULT_LOG_LEVEL = 'info';
|
||||
|
||||
// Add other constants as needed
|
||||
@@ -0,0 +1,242 @@
|
||||
import type { AutoCommitConfig } from "../types";
|
||||
import type { Logger } from "./logger";
|
||||
import simpleGit, { SimpleGit, SimpleGitOptions } from "simple-git";
|
||||
import fs from "fs-extra";
|
||||
import path from "path";
|
||||
import { createError } from "./utils";
|
||||
|
||||
const DEFAULT_COMMIT_SEPARATOR = "/** 提交分隔符 **/";
|
||||
const DEFAULT_MAX_SCAN_COUNT = 50;
|
||||
const DEFAULT_GIT_DIR = ".sync-git";
|
||||
|
||||
/**
|
||||
* 执行自动提交操作
|
||||
*
|
||||
* @param config 自动提交配置
|
||||
* @param workspaceRoot 工作区根目录
|
||||
* @param logger 日志记录器
|
||||
* @param sharedCommitMessagesHolder 共享提交信息的容器
|
||||
*/
|
||||
export async function performAutoCommit(
|
||||
config: AutoCommitConfig,
|
||||
workspaceRoot: string,
|
||||
logger: Logger,
|
||||
sharedCommitMessagesHolder: { current: string[] | null },
|
||||
): Promise<void> {
|
||||
logger.info("开始自动提交操作...");
|
||||
|
||||
// 重置共享提交信息(如果启用)
|
||||
const enableSharedCommits = config.enableSharedCommits !== false;
|
||||
if (enableSharedCommits) {
|
||||
sharedCommitMessagesHolder.current = null;
|
||||
logger.info("已重置共享提交信息缓冲区");
|
||||
}
|
||||
|
||||
// 确保.sync-git目录存在
|
||||
const syncGitDir = path.resolve(workspaceRoot, DEFAULT_GIT_DIR);
|
||||
|
||||
for (const project of config.projects) {
|
||||
// 计算Git项目的绝对路径,targetDir现在是相对于.sync-git目录的
|
||||
const projectDir = path.resolve(syncGitDir, project.targetDir);
|
||||
const projectName = project.projectName || project.targetDir;
|
||||
|
||||
logger.info(`处理自动提交项目: ${projectName} (路径: ${projectDir})`);
|
||||
|
||||
try {
|
||||
// 确保目录存在并且是Git仓库
|
||||
if (!fs.existsSync(projectDir)) {
|
||||
logger.warn(`项目目录 ${projectDir} 不存在,跳过此项目`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const gitOptions: Partial<SimpleGitOptions> = {
|
||||
baseDir: projectDir,
|
||||
binary: "git",
|
||||
maxConcurrentProcesses: 6,
|
||||
};
|
||||
|
||||
const git: SimpleGit = simpleGit(gitOptions);
|
||||
|
||||
if (!(await git.checkIsRepo())) {
|
||||
logger.warn(`${projectDir} 不是有效的Git仓库,跳过此项目`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 如果指定了分支,切换到该分支
|
||||
if (project.branch) {
|
||||
const currentBranch = (await git.branchLocal()).current;
|
||||
if (currentBranch !== project.branch) {
|
||||
logger.info(`切换到分支 ${project.branch}...`);
|
||||
await git.checkout(project.branch);
|
||||
}
|
||||
}
|
||||
|
||||
// 执行自动提交
|
||||
await handleProjectAutoCommit(
|
||||
git,
|
||||
project,
|
||||
projectName,
|
||||
logger,
|
||||
sharedCommitMessagesHolder,
|
||||
enableSharedCommits,
|
||||
config.insertSeparator !== false,
|
||||
);
|
||||
} catch (error: any) {
|
||||
logger.error(
|
||||
`处理项目 ${projectName} 自动提交时出错: ${error.message}`,
|
||||
error,
|
||||
);
|
||||
// 软错误,继续执行下一个项目
|
||||
}
|
||||
}
|
||||
|
||||
logger.info("自动提交操作完成");
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理单个项目的自动提交
|
||||
*/
|
||||
async function handleProjectAutoCommit(
|
||||
git: SimpleGit,
|
||||
project: AutoCommitConfig["projects"][0],
|
||||
projectName: string,
|
||||
logger: Logger,
|
||||
sharedCommitMessagesHolder: { current: string[] | null },
|
||||
enableSharedCommits: boolean,
|
||||
insertSeparator: boolean,
|
||||
) {
|
||||
let commitsToProcess: string[] = [];
|
||||
|
||||
const useSharedCommits = enableSharedCommits && project.useSharedCommits;
|
||||
|
||||
if (useSharedCommits && sharedCommitMessagesHolder.current) {
|
||||
logger.info(`[${projectName}] 使用共享提交信息`);
|
||||
commitsToProcess = [...sharedCommitMessagesHolder.current];
|
||||
} else {
|
||||
if (!project.watchAuthor) {
|
||||
logger.warn(
|
||||
`[${projectName}] 未定义watchAuthor且未使用共享提交,跳过自动提交`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info(`[${projectName}] 扫描 ${project.watchAuthor} 的提交...`);
|
||||
|
||||
const log = await git.log({
|
||||
"--author": project.watchAuthor,
|
||||
"--max-count": project.maxScanCount || DEFAULT_MAX_SCAN_COUNT,
|
||||
"--pretty": "%H %s", // hash和主题
|
||||
});
|
||||
|
||||
const separator = project.commitSeparator || DEFAULT_COMMIT_SEPARATOR;
|
||||
let foundSeparator = false;
|
||||
let tempCommits: string[] = [];
|
||||
|
||||
for (const commit of log.all) {
|
||||
if (commit.message.includes(separator)) {
|
||||
logger.info(`[${projectName}] 找到提交分隔符: "${commit.message}"`);
|
||||
foundSeparator = true;
|
||||
break;
|
||||
}
|
||||
tempCommits.unshift(`[${commit.hash.substring(0, 7)}] ${commit.message}`); // 添加到开头以保持顺序
|
||||
}
|
||||
|
||||
if (foundSeparator) {
|
||||
commitsToProcess = tempCommits; // 分隔符之后的提交(已反转并正确排序)
|
||||
} else if (log.all.length > 0) {
|
||||
// 模式2:没有分隔符,取作者的最新提交
|
||||
const latestCommit = log.all[0];
|
||||
commitsToProcess = [
|
||||
`[${latestCommit.hash.substring(0, 7)}] ${latestCommit.message}`,
|
||||
];
|
||||
logger.info(
|
||||
`[${projectName}] 未找到分隔符。使用 ${project.watchAuthor} 的最新提交: ${commitsToProcess[0]}`,
|
||||
);
|
||||
}
|
||||
|
||||
// 为共享提交缓冲区填充数据(如果启用且是非共享提交消费者)
|
||||
if (
|
||||
enableSharedCommits &&
|
||||
commitsToProcess.length > 0 &&
|
||||
!sharedCommitMessagesHolder.current &&
|
||||
!project.useSharedCommits
|
||||
) {
|
||||
logger.info(
|
||||
`[${projectName}] 将 ${commitsToProcess.length} 条提交存入共享缓冲区`,
|
||||
);
|
||||
sharedCommitMessagesHolder.current = [...commitsToProcess];
|
||||
}
|
||||
}
|
||||
|
||||
if (commitsToProcess.length === 0) {
|
||||
logger.info(`[${projectName}] 没有要处理的新提交`);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info(`[${projectName}] 准备提交 ${commitsToProcess.length} 个更改`);
|
||||
|
||||
// 检查工作区状态
|
||||
const status = await git.status();
|
||||
if (!status.isClean()) {
|
||||
logger.info(`[${projectName}] 工作目录有未提交的更改,暂存所有更改`);
|
||||
await git.add("./*");
|
||||
} else {
|
||||
logger.info(
|
||||
`[${projectName}] 工作目录干净,没有本地更改需要提交。这是正常的,将继续处理同步提交信息`,
|
||||
);
|
||||
}
|
||||
|
||||
// 创建提交信息
|
||||
const commitMessageBody = commitsToProcess
|
||||
.map((msg, idx) => `${idx + 1}. ${msg}`)
|
||||
.join("\n");
|
||||
|
||||
const finalCommitMessage = (
|
||||
project.message ||
|
||||
`[自动合并] 包含 ${commitsToProcess.length} 次提交:\n\n${commitMessageBody}\n\n${project.commitSeparator || DEFAULT_COMMIT_SEPARATOR}`
|
||||
).replace("N", commitsToProcess.length.toString());
|
||||
|
||||
logger.info(`[${projectName}] 提交信息:\n${finalCommitMessage}`);
|
||||
await git.commit(finalCommitMessage);
|
||||
|
||||
if (project.push) {
|
||||
const branch = project.branch || (await git.branchLocal()).current;
|
||||
logger.info(`[${projectName}] 推送到 origin ${branch}...`);
|
||||
await git.push("origin", branch);
|
||||
}
|
||||
|
||||
// 插入新的分隔符提交(如果配置启用)
|
||||
if (insertSeparator) {
|
||||
const separatorCommitMessage =
|
||||
project.commitSeparator || DEFAULT_COMMIT_SEPARATOR;
|
||||
logger.info(
|
||||
`[${projectName}] 插入新的分隔符提交: "${separatorCommitMessage}"`,
|
||||
);
|
||||
await git.commit(separatorCommitMessage, ["--allow-empty"]);
|
||||
|
||||
if (project.push) {
|
||||
const branch = project.branch || (await git.branchLocal()).current;
|
||||
logger.info(`[${projectName}] 推送分隔符提交到 origin ${branch}...`);
|
||||
await git.push("origin", branch);
|
||||
}
|
||||
|
||||
// 处理重复分隔符
|
||||
const logAfter = await git.log({ "--max-count": "2", "--pretty": "%s" });
|
||||
if (
|
||||
logAfter.all.length === 2 &&
|
||||
logAfter.all[0].message === separatorCommitMessage &&
|
||||
logAfter.all[1].message === separatorCommitMessage
|
||||
) {
|
||||
logger.info(`[${projectName}] 检测到重复分隔符,正在清理...`);
|
||||
await git.reset(["--hard", "HEAD~1"]);
|
||||
|
||||
if (project.push) {
|
||||
const branch = project.branch || (await git.branchLocal()).current;
|
||||
logger.warn(`[${projectName}] 强制推送以修复远程重复分隔符`);
|
||||
await git.push("origin", branch, ["--force"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.info(`[${projectName}] 自动提交处理完成`);
|
||||
}
|
||||
160
frontend/plugin/vite-plugin-turborepo-deploy/src/core/config.ts
Normal file
160
frontend/plugin/vite-plugin-turborepo-deploy/src/core/config.ts
Normal file
@@ -0,0 +1,160 @@
|
||||
import type { ResolvedConfig } from 'vite';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
TurborepoDeployConfig,
|
||||
VitePluginTurborepoDeployOptions,
|
||||
LocalSyncConfig as LocalSyncConfigType,
|
||||
GitProjectConfig as GitProjectConfigType,
|
||||
GitProjectAutoCommitConfig as GitProjectAutoCommitConfigType,
|
||||
AutoCommitConfig as AutoCommitConfigType,
|
||||
} from "../types";
|
||||
import { createLogger, Logger } from "./logger";
|
||||
import path from "path";
|
||||
|
||||
// 通用的自动提交项目配置模式
|
||||
const AutoCommitProjectSchema = z.object({
|
||||
targetDir: z
|
||||
.string()
|
||||
.min(1, { message: "AutoCommit project targetDir cannot be empty" }),
|
||||
projectName: z.string().optional(),
|
||||
watchAuthor: z.string().optional(),
|
||||
maxScanCount: z.number().int().positive().optional().default(50),
|
||||
commitSeparator: z.string().optional().default("/** 提交分隔符 **/"),
|
||||
message: z.string().optional(),
|
||||
push: z.boolean().optional().default(false),
|
||||
useSharedCommits: z.boolean().optional().default(false),
|
||||
branch: z.string().optional(),
|
||||
});
|
||||
|
||||
// AutoCommit配置模式
|
||||
const AutoCommitConfigSchema = z
|
||||
.object({
|
||||
projects: z.array(AutoCommitProjectSchema),
|
||||
insertSeparator: z.boolean().optional().default(true),
|
||||
enableSharedCommits: z.boolean().optional().default(true),
|
||||
})
|
||||
.refine(
|
||||
(data) => {
|
||||
// 确保至少有一个项目不使用共享提交信息(作为源),或禁用了共享
|
||||
if (data.enableSharedCommits) {
|
||||
const hasSourceProject = data.projects.some(
|
||||
(project) => !project.useSharedCommits && project.watchAuthor,
|
||||
);
|
||||
return hasSourceProject;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
{
|
||||
message:
|
||||
"When enableSharedCommits is true, at least one project must not use shared commits and have a watchAuthor defined",
|
||||
path: ["projects"],
|
||||
},
|
||||
);
|
||||
|
||||
// Git项目配置模式
|
||||
const GitProjectConfigSchema = z.object({
|
||||
repo: z.string().url({ message: "Invalid Git repository URL" }),
|
||||
branch: z.string().min(1, { message: "Git branch cannot be empty" }),
|
||||
targetDir: z.string().min(1, { message: "Git targetDir cannot be empty" }),
|
||||
projectName: z.string().optional(),
|
||||
updateIfExists: z.boolean().optional().default(true),
|
||||
discardChanges: z.boolean().optional().default(false),
|
||||
});
|
||||
|
||||
// 本地同步配置模式
|
||||
const LocalSyncConfigSchema = z.object({
|
||||
source: z.string().min(1, { message: "LocalSync source cannot be empty" }),
|
||||
target: z.union([
|
||||
z.string().min(1, { message: "LocalSync target cannot be empty" }),
|
||||
z
|
||||
.array(
|
||||
z
|
||||
.string()
|
||||
.min(1, { message: "LocalSync target items cannot be empty" }),
|
||||
)
|
||||
.nonempty({ message: "LocalSync targets array cannot be empty" }),
|
||||
]),
|
||||
mode: z
|
||||
.enum(["copy", "mirror", "incremental"])
|
||||
.optional()
|
||||
.default("incremental"),
|
||||
clearTarget: z.boolean().optional().default(false),
|
||||
addOnly: z.boolean().optional().default(false),
|
||||
exclude: z.array(z.string()).optional(),
|
||||
excludeDirs: z.array(z.string()).optional(),
|
||||
excludeFiles: z.array(z.string()).optional(),
|
||||
});
|
||||
|
||||
// 插件主配置模式
|
||||
const TurborepoDeployConfigSchema = z
|
||||
.object({
|
||||
localSync: z.array(LocalSyncConfigSchema).optional(),
|
||||
gitProjects: z.array(GitProjectConfigSchema).optional(),
|
||||
autoCommit: AutoCommitConfigSchema.optional(),
|
||||
logger: z
|
||||
.object({
|
||||
level: z.enum(["error", "warn", "info", "verbose"]).optional(),
|
||||
writeToFile: z.boolean().optional(),
|
||||
logDir: z.string().optional(),
|
||||
})
|
||||
.optional(),
|
||||
})
|
||||
.refine(
|
||||
(data) => {
|
||||
// 确保至少配置了一个任务
|
||||
if (
|
||||
Object.keys(data).length > 0 &&
|
||||
!data.localSync &&
|
||||
!data.gitProjects &&
|
||||
!data.autoCommit
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
{
|
||||
message:
|
||||
"Plugin configured but no tasks (localSync, gitProjects, or autoCommit) are defined.",
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* 加载并验证插件配置
|
||||
*
|
||||
* @param options 用户提供的配置选项
|
||||
* @param workspaceRoot 工作区根目录
|
||||
* @returns 验证并处理后的配置对象
|
||||
*/
|
||||
export function loadConfig(
|
||||
options: VitePluginTurborepoDeployOptions | undefined,
|
||||
workspaceRoot: string,
|
||||
): TurborepoDeployConfig {
|
||||
if (!options || Object.keys(options).length === 0) {
|
||||
return {} as TurborepoDeployConfig; // 返回空对象,插件将在buildEnd中跳过
|
||||
}
|
||||
|
||||
try {
|
||||
const parsedConfig = TurborepoDeployConfigSchema.parse(options);
|
||||
|
||||
// 验证自动提交配置中的路径
|
||||
if (parsedConfig.autoCommit) {
|
||||
for (const project of parsedConfig.autoCommit.projects) {
|
||||
// 所有项目路径现在都是相对于 .sync-git 目录的
|
||||
if (path.isAbsolute(project.targetDir)) {
|
||||
throw new Error(
|
||||
`AutoCommit 项目路径 '${project.targetDir}' 不应是绝对路径。请使用相对于 .sync-git 目录的路径。`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return parsedConfig as TurborepoDeployConfig;
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
throw new Error(
|
||||
`Configuration validation failed: ${error.errors.map((e) => `${e.path.join(".")}: ${e.message}`).join(", ")}`,
|
||||
);
|
||||
}
|
||||
throw new Error("Unknown error while parsing plugin configuration.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
import type { GitProjectConfig } from '../types';
|
||||
import type { Logger } from "./logger";
|
||||
import simpleGit, { SimpleGit, SimpleGitOptions } from 'simple-git';
|
||||
import fs from 'fs-extra';
|
||||
import path from 'path';
|
||||
|
||||
// 默认的Git项目存放目录
|
||||
const DEFAULT_GIT_DIR = '.sync-git';
|
||||
|
||||
/**
|
||||
* 检查仓库是否具有未提交的更改
|
||||
* @param git SimpleGit实例
|
||||
* @param logger 日志记录器
|
||||
* @returns 是否有未提交的更改
|
||||
*/
|
||||
async function hasUncommittedChanges(git: SimpleGit, logger: Logger): Promise<boolean> {
|
||||
try {
|
||||
// 检查仓库是否为空
|
||||
const hasFiles = await git.raw(['ls-files']).then(output => !!output.trim());
|
||||
if (!hasFiles) {
|
||||
// 空仓库没有未提交的更改
|
||||
return false;
|
||||
}
|
||||
|
||||
// 获取状态
|
||||
const status = await git.status();
|
||||
|
||||
// 检查是否有未跟踪的文件
|
||||
const hasUntracked = status.not_added.length > 0;
|
||||
|
||||
// 检查是否有已修改但未暂存的文件
|
||||
const hasModified = status.modified.length > 0;
|
||||
|
||||
// 检查是否有已暂存的更改
|
||||
const hasStaged = status.staged.length > 0;
|
||||
|
||||
// 检查是否有已删除但未暂存的文件
|
||||
const hasDeleted = status.deleted.length > 0;
|
||||
|
||||
// 检查是否有冲突的文件
|
||||
const hasConflicted = status.conflicted.length > 0;
|
||||
|
||||
return hasUntracked || hasModified || hasStaged || hasDeleted || hasConflicted || !status.isClean();
|
||||
} catch (error: any) {
|
||||
logger.warn(`检查未提交更改时出错: ${error.message},将假设没有未提交更改`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全地丢弃工作区中的所有更改
|
||||
* @param git SimpleGit实例
|
||||
* @param projectName 项目名称
|
||||
* @param logger 日志记录器
|
||||
*/
|
||||
async function safelyDiscardChanges(git: SimpleGit, projectName: string, logger: Logger): Promise<void> {
|
||||
try {
|
||||
// 检查仓库是否为空或是否有已跟踪的文件
|
||||
const trackedFiles = await git.raw(['ls-files']);
|
||||
if (!trackedFiles.trim()) {
|
||||
logger.info(`${projectName}: 仓库为空或没有已跟踪的文件,跳过丢弃更改操作`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 获取具体的更改状态
|
||||
const status = await git.status();
|
||||
|
||||
if (status.modified.length > 0 || status.deleted.length > 0) {
|
||||
logger.info(`${projectName}: 丢弃已修改或已删除但未暂存的文件更改`);
|
||||
await git.checkout(['--', '.']);
|
||||
}
|
||||
|
||||
if (status.staged.length > 0) {
|
||||
logger.info(`${projectName}: 丢弃已暂存的更改`);
|
||||
await git.reset(['HEAD', '--', '.']);
|
||||
if (status.staged.length > 0) {
|
||||
await git.checkout(['--', '.']);
|
||||
}
|
||||
}
|
||||
|
||||
if (status.not_added.length > 0) {
|
||||
logger.info(`${projectName}: 删除未跟踪的文件`);
|
||||
await git.clean('fd');
|
||||
}
|
||||
|
||||
logger.info(`${projectName}: 已丢弃所有本地更改`);
|
||||
} catch (error: any) {
|
||||
logger.warn(`${projectName}: 丢弃更改时出错: ${error.message},尝试继续操作`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新Git项目,在编译前执行
|
||||
* 所有Git项目都存放在workspaceRoot/.sync-git目录下
|
||||
*
|
||||
* @param configs Git项目配置数组
|
||||
* @param workspaceRoot 工作区根目录
|
||||
* @param logger 日志记录器
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
export async function updateGitProjects(
|
||||
configs: GitProjectConfig[],
|
||||
workspaceRoot: string,
|
||||
logger: Logger,
|
||||
): Promise<void> {
|
||||
logger.info("开始Git项目初始化...");
|
||||
|
||||
// 确保.sync-git目录存在
|
||||
const syncGitDir = path.resolve(workspaceRoot, DEFAULT_GIT_DIR);
|
||||
await fs.ensureDir(syncGitDir);
|
||||
logger.info(`Git项目根目录: ${syncGitDir}`);
|
||||
|
||||
// 检查是否所有Git项目都已准备就绪的标志
|
||||
let allProjectsReady = true;
|
||||
|
||||
for (const config of configs) {
|
||||
// 构建Git项目路径,放在.sync-git目录下
|
||||
const relativeProjectDir = config.targetDir;
|
||||
const absoluteProjectDir = path.resolve(syncGitDir, relativeProjectDir);
|
||||
const projectName = config.projectName || config.targetDir;
|
||||
|
||||
logger.info(
|
||||
`处理Git项目: ${projectName} (仓库: ${config.repo}, 分支: ${config.branch})`,
|
||||
);
|
||||
|
||||
const gitOptions: Partial<SimpleGitOptions> = {
|
||||
baseDir: absoluteProjectDir,
|
||||
binary: "git",
|
||||
maxConcurrentProcesses: 6,
|
||||
};
|
||||
|
||||
try {
|
||||
// 检查项目目录是否存在
|
||||
const dirExists = await fs.pathExists(absoluteProjectDir);
|
||||
if (!dirExists) {
|
||||
logger.info(`项目目录不存在: ${absoluteProjectDir},将创建并克隆仓库`);
|
||||
await fs.ensureDir(absoluteProjectDir);
|
||||
}
|
||||
|
||||
const git: SimpleGit = simpleGit(gitOptions);
|
||||
|
||||
// 检查是否为Git仓库
|
||||
const isRepo = dirExists && (await git.checkIsRepo().catch(() => false));
|
||||
|
||||
if (!isRepo) {
|
||||
logger.info(`正在克隆 ${config.repo} 到 ${absoluteProjectDir}...`);
|
||||
// 确保父目录存在
|
||||
await fs.ensureDir(path.dirname(absoluteProjectDir));
|
||||
// 克隆仓库
|
||||
await simpleGit(path.dirname(absoluteProjectDir)).clone(
|
||||
config.repo,
|
||||
path.basename(absoluteProjectDir),
|
||||
[`--branch=${config.branch}`],
|
||||
);
|
||||
logger.info(`克隆成功。`);
|
||||
} else {
|
||||
if (config.updateIfExists !== false) {
|
||||
logger.info(`正在获取并拉取 ${projectName} 的更新...`);
|
||||
await git.fetch();
|
||||
|
||||
// 提前获取当前分支信息
|
||||
const branchInfo = await git.branchLocal();
|
||||
const currentBranch = branchInfo.current;
|
||||
logger.info(`${projectName}: 当前分支 ${currentBranch}`);
|
||||
|
||||
// 检查是否有未提交的更改
|
||||
const uncommittedChanges = await hasUncommittedChanges(git, logger);
|
||||
|
||||
if (uncommittedChanges) {
|
||||
if (config.discardChanges) {
|
||||
logger.warn(
|
||||
`${projectName}: 检测到未提交的更改,根据配置将丢弃所有本地修改...`,
|
||||
);
|
||||
// 安全地丢弃所有更改
|
||||
await safelyDiscardChanges(git, projectName, logger);
|
||||
} else {
|
||||
logger.warn(
|
||||
`${projectName}: 检测到未提交的更改。如需自动丢弃这些更改,请设置 discardChanges: true`,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
logger.info(`${projectName}: 没有检测到未提交的更改,继续操作...`);
|
||||
}
|
||||
|
||||
// 检查当前分支是否为目标分支
|
||||
if (currentBranch !== config.branch) {
|
||||
logger.info(
|
||||
`${projectName}: 需要从分支 ${currentBranch} 切换到分支 ${config.branch}...`,
|
||||
);
|
||||
try {
|
||||
await git.checkout(config.branch);
|
||||
logger.info(`${projectName}: 成功切换到分支 ${config.branch}`);
|
||||
} catch (checkoutError: any) {
|
||||
if (config.discardChanges) {
|
||||
logger.warn(
|
||||
`${projectName}: 切换分支失败: ${checkoutError.message},尝试强制切换...`,
|
||||
);
|
||||
await git.checkout(["-f", config.branch]);
|
||||
logger.info(
|
||||
`${projectName}: 成功强制切换到分支 ${config.branch}`,
|
||||
);
|
||||
} else {
|
||||
throw checkoutError;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
logger.info(
|
||||
`${projectName}: 已经在目标分支 ${config.branch} 上,无需切换`,
|
||||
);
|
||||
}
|
||||
|
||||
// 执行拉取操作
|
||||
logger.info(`${projectName}: 从远程拉取最新更改...`);
|
||||
try {
|
||||
await git.pull("origin", config.branch, { "--rebase": "true" });
|
||||
logger.info(`${projectName}: 成功更新分支 ${config.branch}。`);
|
||||
} catch (pullError: any) {
|
||||
if (
|
||||
(pullError.message.includes("You have unstaged changes") ||
|
||||
pullError.message.includes(
|
||||
"Your local changes to the following files would be overwritten",
|
||||
)) &&
|
||||
config.discardChanges
|
||||
) {
|
||||
logger.warn(
|
||||
`拉取失败 (${pullError.message}),尝试丢弃更改后重新拉取...`,
|
||||
);
|
||||
|
||||
// 尝试中止可能进行中的变基
|
||||
try {
|
||||
await git.rebase(["--abort"]);
|
||||
} catch (e) {
|
||||
// 忽略错误,因为可能没有正在进行的变基
|
||||
}
|
||||
|
||||
// 安全地丢弃所有更改
|
||||
await safelyDiscardChanges(git, projectName, logger);
|
||||
|
||||
// 重新尝试拉取
|
||||
await git.pull("origin", config.branch, { "--rebase": "true" });
|
||||
logger.info(`丢弃更改后成功更新 ${projectName}。`);
|
||||
} else {
|
||||
throw pullError;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
logger.info(
|
||||
`项目 ${projectName} 已存在且 updateIfExists 为 false,跳过更新。`,
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
logger.error(
|
||||
`处理Git项目 ${projectName} 时出错: ${error.message}`,
|
||||
error,
|
||||
);
|
||||
// 标记有项目未准备就绪
|
||||
allProjectsReady = false;
|
||||
// 编译前阶段出错,中止编译流程
|
||||
throw new Error(
|
||||
`Git项目 ${projectName} 初始化失败,编译中止: ${error.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (allProjectsReady) {
|
||||
logger.info("所有Git项目初始化完成,可以开始编译。");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,476 @@
|
||||
import type { LocalSyncConfig } from '../types';
|
||||
import type { Logger } from "./logger";
|
||||
import fs from 'fs-extra';
|
||||
import path from 'path';
|
||||
import picomatch from 'picomatch'; // For glob matching if not using regex directly
|
||||
import os from "os";
|
||||
import { exec as execCallback } from "child_process";
|
||||
|
||||
// 使用Promise包装exec函数,不依赖util.promisify
|
||||
const exec = (command: string): Promise<{ stdout: string; stderr: string }> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
execCallback(command, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve({ stdout, stderr });
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// 缓存已创建的临时压缩文件
|
||||
interface CompressionCache {
|
||||
[sourcePathKey: string]: {
|
||||
zipFile: string; // 压缩文件路径
|
||||
excludeOptions: string; // 排除选项字符串
|
||||
expiry: number; // 过期时间戳
|
||||
};
|
||||
}
|
||||
|
||||
// 全局压缩缓存对象
|
||||
const compressionCache: CompressionCache = {};
|
||||
|
||||
// 缓存过期时间(毫秒)
|
||||
const CACHE_TTL = 5 * 60 * 1000; // 5分钟
|
||||
|
||||
/**
|
||||
* 处理源路径,将'/'特殊字符解释为工作区根目录
|
||||
* @param sourcePath 原始配置的源路径
|
||||
* @param workspaceRoot 工作区根目录
|
||||
* @returns 处理后的实际源路径
|
||||
*/
|
||||
function resolveSourcePath(sourcePath: string, workspaceRoot: string): string {
|
||||
// 如果源路径是'/',则将其解释为工作区根目录
|
||||
if (sourcePath === "/") {
|
||||
return workspaceRoot;
|
||||
}
|
||||
// 否则正常解析路径
|
||||
return path.resolve(workspaceRoot, sourcePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建临时目录用于压缩操作
|
||||
* @returns 临时目录路径
|
||||
*/
|
||||
async function createTempDir(): Promise<string> {
|
||||
const tempDir = path.join(os.tmpdir(), `turborepo-deploy-${Date.now()}`);
|
||||
await fs.ensureDir(tempDir);
|
||||
return tempDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成排除选项字符串
|
||||
* @param config 同步配置
|
||||
* @param sourcePath 源路径
|
||||
* @param targetPath 目标路径
|
||||
* @param tempDir 临时目录
|
||||
* @returns 排除选项字符串
|
||||
*/
|
||||
function generateExcludeOptions(
|
||||
config: LocalSyncConfig,
|
||||
sourcePath: string,
|
||||
targetPath: string,
|
||||
tempDir: string,
|
||||
): string {
|
||||
let excludeOptions = "";
|
||||
|
||||
// 处理排除目录
|
||||
if (config.excludeDirs && config.excludeDirs.length > 0) {
|
||||
const excludeDirsFormatted = config.excludeDirs
|
||||
.map((dir) => {
|
||||
// 移除通配符,获取基本目录名
|
||||
const baseDirName = dir.replace(/^\*\*\//, "");
|
||||
return `-x "*${baseDirName}*"`;
|
||||
})
|
||||
.join(" ");
|
||||
excludeOptions += ` ${excludeDirsFormatted}`;
|
||||
}
|
||||
|
||||
// 处理排除文件
|
||||
if (config.excludeFiles && config.excludeFiles.length > 0) {
|
||||
const excludeFilesFormatted = config.excludeFiles
|
||||
.map((file) => {
|
||||
return `-x "*${file.replace(/^\*\*\//, "")}*"`;
|
||||
})
|
||||
.join(" ");
|
||||
excludeOptions += ` ${excludeFilesFormatted}`;
|
||||
}
|
||||
|
||||
// 处理正则排除
|
||||
if (config.exclude && config.exclude.length > 0) {
|
||||
const excludeRegexFormatted = config.exclude
|
||||
.map((pattern) => {
|
||||
return `-x "*${pattern}*"`;
|
||||
})
|
||||
.join(" ");
|
||||
excludeOptions += ` ${excludeRegexFormatted}`;
|
||||
}
|
||||
|
||||
// 始终排除目标路径,避免递归
|
||||
const relativeTargetPath = path.relative(sourcePath, targetPath);
|
||||
if (relativeTargetPath) {
|
||||
excludeOptions += ` -x "*${relativeTargetPath}*"`;
|
||||
}
|
||||
|
||||
// 排除所有.sync-git目录
|
||||
excludeOptions += ` -x "*.sync-git*"`;
|
||||
|
||||
// 排除临时目录
|
||||
excludeOptions += ` -x "*${path.basename(tempDir)}*"`;
|
||||
|
||||
return excludeOptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取缓存键
|
||||
* @param sourcePath 源路径
|
||||
* @param config 同步配置
|
||||
* @returns 缓存键
|
||||
*/
|
||||
function getCacheKey(sourcePath: string, config: LocalSyncConfig): string {
|
||||
// 使用源路径和排除规则作为缓存键
|
||||
return `${sourcePath}_${JSON.stringify({
|
||||
excludeDirs: config.excludeDirs || [],
|
||||
excludeFiles: config.excludeFiles || [],
|
||||
exclude: config.exclude || [],
|
||||
})}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理过期缓存
|
||||
*/
|
||||
function cleanExpiredCache(): void {
|
||||
const now = Date.now();
|
||||
for (const key in compressionCache) {
|
||||
if (compressionCache[key].expiry < now) {
|
||||
// 尝试删除过期的缓存文件
|
||||
try {
|
||||
if (fs.existsSync(compressionCache[key].zipFile)) {
|
||||
fs.unlinkSync(compressionCache[key].zipFile);
|
||||
}
|
||||
} catch (e) {
|
||||
// 忽略删除错误
|
||||
}
|
||||
delete compressionCache[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用压缩方式处理源目录到子目录的复制,支持缓存
|
||||
* @param sourcePath 源路径
|
||||
* @param targetPath 目标路径
|
||||
* @param config 同步配置
|
||||
* @param logger 日志记录器
|
||||
*/
|
||||
async function syncViaCompression(
|
||||
sourcePath: string,
|
||||
targetPath: string,
|
||||
config: LocalSyncConfig,
|
||||
logger: Logger,
|
||||
): Promise<void> {
|
||||
logger.info(`目标路径是源路径的子目录或相同路径,使用压缩方案同步...`);
|
||||
|
||||
// 清理过期缓存
|
||||
cleanExpiredCache();
|
||||
|
||||
// 获取缓存键
|
||||
const cacheKey = getCacheKey(sourcePath, config);
|
||||
|
||||
// 创建临时目录(可能不需要,取决于是否有缓存)
|
||||
let tempDir: string | null = null;
|
||||
let tempZipFile: string;
|
||||
let needToCreateZip = true;
|
||||
|
||||
// 检查缓存
|
||||
if (compressionCache[cacheKey]) {
|
||||
// 使用缓存的压缩文件
|
||||
logger.info(`找到源路径 ${sourcePath} 的缓存压缩文件,跳过压缩步骤`);
|
||||
tempZipFile = compressionCache[cacheKey].zipFile;
|
||||
needToCreateZip = false;
|
||||
} else {
|
||||
// 创建新的临时目录和压缩文件
|
||||
tempDir = await createTempDir();
|
||||
tempZipFile = path.join(tempDir, "source.zip");
|
||||
}
|
||||
|
||||
try {
|
||||
if (needToCreateZip) {
|
||||
// 需要创建新的压缩文件
|
||||
const excludeOptions = generateExcludeOptions(
|
||||
config,
|
||||
sourcePath,
|
||||
targetPath,
|
||||
tempDir!,
|
||||
);
|
||||
|
||||
// 压缩源目录内容到临时文件
|
||||
logger.info(`压缩源目录 ${sourcePath} 到临时文件 ${tempZipFile}...`);
|
||||
const zipCmd = `cd "${sourcePath}" && zip -r "${tempZipFile}" .${excludeOptions}`;
|
||||
logger.verbose(`执行命令: ${zipCmd}`);
|
||||
await exec(zipCmd);
|
||||
|
||||
// 将新创建的压缩文件加入缓存
|
||||
compressionCache[cacheKey] = {
|
||||
zipFile: tempZipFile,
|
||||
excludeOptions: excludeOptions,
|
||||
expiry: Date.now() + CACHE_TTL,
|
||||
};
|
||||
logger.verbose(
|
||||
`已将压缩文件添加到缓存,缓存键: ${cacheKey.substring(0, 30)}...`,
|
||||
);
|
||||
}
|
||||
|
||||
// 清空目标目录(如果配置了clearTarget)
|
||||
if (config.clearTarget) {
|
||||
logger.info(`清空目标目录 ${targetPath}...`);
|
||||
await fs.emptyDir(targetPath);
|
||||
}
|
||||
await fs.ensureDir(targetPath);
|
||||
|
||||
// 解压缩到目标目录
|
||||
logger.info(`解压临时文件到目标目录 ${targetPath}...`);
|
||||
const unzipCmd = `unzip -o "${tempZipFile}" -d "${targetPath}"`;
|
||||
logger.verbose(`执行命令: ${unzipCmd}`);
|
||||
await exec(unzipCmd);
|
||||
|
||||
logger.info(`成功通过压缩方案同步 ${sourcePath} 到 ${targetPath}`);
|
||||
} catch (error: any) {
|
||||
logger.error(`压缩同步过程出错: ${error.message}`, error);
|
||||
|
||||
// 发生错误时,从缓存中移除该条目
|
||||
if (compressionCache[cacheKey]) {
|
||||
delete compressionCache[cacheKey];
|
||||
}
|
||||
|
||||
throw error;
|
||||
} finally {
|
||||
// 只清理我们在这次调用中创建的临时目录
|
||||
// 缓存的临时文件会在过期后或进程结束时清理
|
||||
if (tempDir && needToCreateZip) {
|
||||
try {
|
||||
// 只移除临时目录,不移除压缩文件(已添加到缓存)
|
||||
const tempDirFiles = await fs.readdir(tempDir);
|
||||
for (const file of tempDirFiles) {
|
||||
if (file !== path.basename(tempZipFile)) {
|
||||
await fs.remove(path.join(tempDir, file));
|
||||
}
|
||||
}
|
||||
} catch (cleanupError) {
|
||||
logger.warn(`清理临时文件失败: ${cleanupError}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function performLocalSync(
|
||||
configs: LocalSyncConfig[],
|
||||
workspaceRoot: string,
|
||||
logger: Logger,
|
||||
): Promise<void> {
|
||||
logger.info("开始本地文件同步...");
|
||||
|
||||
for (const config of configs) {
|
||||
// 使用新的源路径解析函数
|
||||
const sourcePath = resolveSourcePath(config.source, workspaceRoot);
|
||||
|
||||
// 输出实际的源路径,方便调试
|
||||
if (config.source === "/") {
|
||||
logger.info(`源路径 '/' 被解析为工作区根目录: ${sourcePath}`);
|
||||
}
|
||||
|
||||
// 检查源路径是否存在
|
||||
if (!(await fs.pathExists(sourcePath))) {
|
||||
logger.warn(`源路径 ${sourcePath} 不存在。跳过此同步任务。`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 将所有目标统一处理为数组
|
||||
const targets = Array.isArray(config.target)
|
||||
? config.target
|
||||
: [config.target];
|
||||
|
||||
logger.info(`为源路径 ${sourcePath} 处理 ${targets.length} 个目标`);
|
||||
|
||||
// 对每个目标路径执行同步
|
||||
for (const target of targets) {
|
||||
const targetPath = path.resolve(workspaceRoot, target);
|
||||
|
||||
// 检查目标路径是否是源路径的子目录或相同目录
|
||||
const isSubdirectory =
|
||||
targetPath.startsWith(sourcePath + path.sep) ||
|
||||
targetPath === sourcePath;
|
||||
|
||||
logger.info(
|
||||
`正在同步 ${sourcePath} 到 ${targetPath} (模式: ${config.mode || "incremental"})`,
|
||||
);
|
||||
|
||||
try {
|
||||
// 如果目标是源的子目录,使用压缩方案
|
||||
if (isSubdirectory) {
|
||||
logger.info(
|
||||
`目标路径 ${targetPath} 是源路径 ${sourcePath} 的子目录或相同目录,使用压缩同步方案。`,
|
||||
);
|
||||
await syncViaCompression(sourcePath, targetPath, config, logger);
|
||||
logger.info(`成功同步 ${config.source} 到 ${target}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 以下是原来的同步逻辑,处理非子目录的情况
|
||||
if (config.clearTarget) {
|
||||
logger.info(`正在清空目标目录 ${targetPath}...`);
|
||||
await fs.emptyDir(targetPath);
|
||||
}
|
||||
|
||||
await fs.ensureDir(path.dirname(targetPath)); // 确保目标父目录存在
|
||||
|
||||
const options: fs.CopyOptions = {
|
||||
overwrite: config.mode !== "copy" && !config.addOnly, // 镜像和增量模式时覆盖
|
||||
errorOnExist: false, // 避免在copy模式时出错
|
||||
filter: (src, dest) => {
|
||||
if (config.addOnly && fs.existsSync(dest)) {
|
||||
logger.verbose(`跳过 ${src} 因为它已存在于目标中 (仅添加模式)`);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 获取相对于源路径的相对路径
|
||||
const relativeSrc = path.relative(sourcePath, src);
|
||||
|
||||
// 如果是根目录的情况,需要特殊处理以匹配排除规则
|
||||
if (config.source === "/" && relativeSrc) {
|
||||
// 检查是否匹配任何排除目录
|
||||
const firstSegment = relativeSrc.split(path.sep)[0];
|
||||
|
||||
// 检查顶级目录是否在排除列表中
|
||||
if (
|
||||
config.excludeDirs?.some((dir) => {
|
||||
// 去掉可能的通配符前缀,获取基本目录名
|
||||
const baseDirName = dir.replace(/^\*\*\//, "");
|
||||
return (
|
||||
firstSegment === baseDirName ||
|
||||
picomatch.isMatch(relativeSrc, dir)
|
||||
);
|
||||
})
|
||||
) {
|
||||
logger.verbose(
|
||||
`排除目录 ${relativeSrc} 因为匹配 'excludeDirs' glob/正则`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 正则排除(文件和目录)
|
||||
if (
|
||||
config.exclude?.some((pattern) =>
|
||||
new RegExp(pattern).test(relativeSrc),
|
||||
)
|
||||
) {
|
||||
logger.verbose(`排除 ${relativeSrc} 因为匹配 'exclude' 正则`);
|
||||
return false;
|
||||
}
|
||||
|
||||
const stats = fs.statSync(src);
|
||||
if (stats.isDirectory()) {
|
||||
if (
|
||||
config.excludeDirs?.some((pattern) =>
|
||||
picomatch.isMatch(relativeSrc, pattern),
|
||||
)
|
||||
) {
|
||||
logger.verbose(
|
||||
`排除目录 ${relativeSrc} 因为匹配 'excludeDirs' glob/正则`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
if (
|
||||
config.excludeFiles?.some((pattern) =>
|
||||
picomatch.isMatch(relativeSrc, pattern),
|
||||
)
|
||||
) {
|
||||
logger.verbose(
|
||||
`排除文件 ${relativeSrc} 因为匹配 'excludeFiles' glob/正则`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
},
|
||||
};
|
||||
|
||||
if (config.mode === "mirror") {
|
||||
// 对于镜像模式,fs-extra的copySync/copy不会删除多余的文件
|
||||
logger.info(
|
||||
`正在镜像同步 ${sourcePath} 到 ${targetPath}。注意:真正的镜像可能需要目标为空或由'clearTarget'处理`,
|
||||
);
|
||||
|
||||
// 实现真正的镜像模式
|
||||
if (!config.clearTarget) {
|
||||
// 如果未使用clearTarget,我们需要自己实现镜像逻辑
|
||||
// 1. 获取目标中的所有文件
|
||||
const targetFiles = await getAllFiles(targetPath);
|
||||
|
||||
// 2. 复制源到目标
|
||||
await fs.copy(sourcePath, targetPath, options);
|
||||
|
||||
// 3. 重新获取所有源文件(现在已复制到目标)
|
||||
const sourceFiles = await getAllFiles(sourcePath);
|
||||
const sourceRelativePaths = sourceFiles.map((file) =>
|
||||
path.relative(sourcePath, file),
|
||||
);
|
||||
|
||||
// 4. 删除目标中不在源中的文件
|
||||
for (const targetFile of targetFiles) {
|
||||
const relativePath = path.relative(targetPath, targetFile);
|
||||
if (
|
||||
!sourceRelativePaths.includes(relativePath) &&
|
||||
fs.statSync(targetFile).isFile()
|
||||
) {
|
||||
logger.verbose(`删除目标中多余的文件: ${targetFile}`);
|
||||
await fs.remove(targetFile);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 如果使用了clearTarget,直接复制即可
|
||||
await fs.copy(sourcePath, targetPath, options);
|
||||
}
|
||||
} else {
|
||||
// 复制或增量模式
|
||||
await fs.copy(sourcePath, targetPath, options);
|
||||
}
|
||||
|
||||
logger.info(`成功同步 ${config.source} 到 ${target}`);
|
||||
} catch (error: any) {
|
||||
logger.error(
|
||||
`从 ${sourcePath} 同步到 ${targetPath} 时出错: ${error.message}`,
|
||||
error,
|
||||
);
|
||||
// 软错误:继续执行其他任务
|
||||
}
|
||||
}
|
||||
}
|
||||
logger.info("本地文件同步完成");
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归获取目录中的所有文件路径
|
||||
* @param dir 要扫描的目录
|
||||
* @returns 文件路径数组
|
||||
*/
|
||||
async function getAllFiles(dir: string): Promise<string[]> {
|
||||
let results: string[] = [];
|
||||
if (!fs.existsSync(dir)) return results;
|
||||
|
||||
const list = await fs.readdir(dir);
|
||||
for (const file of list) {
|
||||
const filePath = path.join(dir, file);
|
||||
const stat = await fs.stat(filePath);
|
||||
if (stat.isDirectory()) {
|
||||
const subFiles = await getAllFiles(filePath);
|
||||
results = results.concat(subFiles);
|
||||
} else {
|
||||
results.push(filePath);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
105
frontend/plugin/vite-plugin-turborepo-deploy/src/core/logger.ts
Normal file
105
frontend/plugin/vite-plugin-turborepo-deploy/src/core/logger.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
import chalk from "chalk";
|
||||
import fs from "fs-extra";
|
||||
import path from "path";
|
||||
|
||||
export type LogLevel = "error" | "warn" | "info" | "verbose";
|
||||
|
||||
export interface Logger {
|
||||
error: (message: string, error?: Error) => void;
|
||||
warn: (message: string) => void;
|
||||
info: (message: string) => void;
|
||||
verbose: (message: string) => void;
|
||||
setLogLevel: (level: LogLevel) => void;
|
||||
}
|
||||
|
||||
const LogLevelOrder: Record<LogLevel, number> = {
|
||||
error: 0,
|
||||
warn: 1,
|
||||
info: 2,
|
||||
verbose: 3,
|
||||
};
|
||||
|
||||
/**
|
||||
* 创建日志记录器
|
||||
*
|
||||
* @param workspaceRoot 工作区根目录
|
||||
* @param initialLevel 初始日志级别
|
||||
* @param writeToFile 是否写入日志文件
|
||||
* @param logDir 日志目录路径
|
||||
* @returns 日志记录器实例
|
||||
*/
|
||||
export function createLogger(
|
||||
workspaceRoot: string,
|
||||
initialLevel: LogLevel = "info",
|
||||
writeToFile: boolean = true,
|
||||
logDir: string = ".sync-log",
|
||||
): Logger {
|
||||
let currentLogLevel = initialLevel;
|
||||
const pluginName = chalk.cyan("[vite-plugin-turborepo-deploy]");
|
||||
|
||||
// 确保日志目录存在
|
||||
const logDirPath = path.isAbsolute(logDir)
|
||||
? logDir
|
||||
: path.resolve(workspaceRoot, logDir);
|
||||
if (writeToFile) {
|
||||
fs.ensureDirSync(logDirPath);
|
||||
}
|
||||
|
||||
// 创建日志文件名(按日期)
|
||||
const today = new Date();
|
||||
const dateStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;
|
||||
const logFilePath = path.join(logDirPath, `${dateStr}_deploy.log`);
|
||||
|
||||
const log = (level: LogLevel, message: string, error?: Error) => {
|
||||
if (LogLevelOrder[level] <= LogLevelOrder[currentLogLevel]) {
|
||||
// 控制台输出
|
||||
let formattedMessage = `${pluginName} `;
|
||||
if (level === "error") formattedMessage += chalk.red(`ERROR: ${message}`);
|
||||
else if (level === "warn")
|
||||
formattedMessage += chalk.yellow(`WARN: ${message}`);
|
||||
else if (level === "info") formattedMessage += chalk.green(message);
|
||||
else formattedMessage += chalk.dim(message);
|
||||
|
||||
console.log(formattedMessage);
|
||||
if (
|
||||
error &&
|
||||
(level === "error" ||
|
||||
LogLevelOrder.verbose <= LogLevelOrder[currentLogLevel])
|
||||
) {
|
||||
console.error(error);
|
||||
}
|
||||
|
||||
// 文件日志
|
||||
if (writeToFile) {
|
||||
try {
|
||||
const timestamp = new Date().toISOString();
|
||||
let logEntry = `[${timestamp}] [${level.toUpperCase()}] ${message}\n`;
|
||||
|
||||
if (
|
||||
error &&
|
||||
(level === "error" ||
|
||||
LogLevelOrder.verbose <= LogLevelOrder[currentLogLevel])
|
||||
) {
|
||||
logEntry += `[${timestamp}] [${level.toUpperCase()}] Error details: ${error.stack || error.message}\n`;
|
||||
}
|
||||
|
||||
fs.appendFileSync(logFilePath, logEntry);
|
||||
} catch (e) {
|
||||
console.error(
|
||||
`${pluginName} ${chalk.red(`ERROR: Failed to write to log file: ${e instanceof Error ? e.message : "Unknown error"}`)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
error: (message, error) => log("error", message, error),
|
||||
warn: (message) => log("warn", message),
|
||||
info: (message) => log("info", message),
|
||||
verbose: (message) => log("verbose", message),
|
||||
setLogLevel: (level: LogLevel) => {
|
||||
currentLogLevel = level;
|
||||
},
|
||||
};
|
||||
}
|
||||
130
frontend/plugin/vite-plugin-turborepo-deploy/src/core/utils.ts
Normal file
130
frontend/plugin/vite-plugin-turborepo-deploy/src/core/utils.ts
Normal file
@@ -0,0 +1,130 @@
|
||||
// plugin/vite-plugin-turborepo-deploy/src/core/utils.ts
|
||||
|
||||
import path from "path";
|
||||
import fs from "fs-extra";
|
||||
|
||||
/**
|
||||
* 检测并获取 Turborepo 工作区根目录
|
||||
* 通过查找 turbo.json 或 package.json 中的 workspaces 配置来确定
|
||||
*
|
||||
* @param startDir 开始搜索的目录(通常是 Vite 项目根目录)
|
||||
* @returns 工作区根目录的绝对路径,如果未找到则返回 startDir
|
||||
*/
|
||||
export function findWorkspaceRoot(startDir: string): string {
|
||||
let currentDir = startDir;
|
||||
|
||||
// 限制向上查找的层级,避免无限循环
|
||||
const maxLevels = 10;
|
||||
let level = 0;
|
||||
|
||||
while (level < maxLevels) {
|
||||
// 检查 turbo.json 是否存在(Turborepo 项目标志)
|
||||
if (fs.existsSync(path.join(currentDir, "turbo.json"))) {
|
||||
return currentDir;
|
||||
}
|
||||
|
||||
// 检查 package.json 中的 workspaces 配置(pnpm/yarn/npm workspace)
|
||||
const packageJsonPath = path.join(currentDir, "package.json");
|
||||
if (fs.existsSync(packageJsonPath)) {
|
||||
try {
|
||||
const packageJson = fs.readJSONSync(packageJsonPath);
|
||||
if (packageJson.workspaces || packageJson.pnpm?.workspaces) {
|
||||
return currentDir;
|
||||
}
|
||||
} catch (error) {
|
||||
// 如果读取出错,继续向上查找
|
||||
}
|
||||
}
|
||||
|
||||
// 检查 pnpm-workspace.yaml(pnpm workspace)
|
||||
if (fs.existsSync(path.join(currentDir, "pnpm-workspace.yaml"))) {
|
||||
return currentDir;
|
||||
}
|
||||
|
||||
// 向上一级目录继续搜索
|
||||
const parentDir = path.dirname(currentDir);
|
||||
if (parentDir === currentDir) {
|
||||
// 已经到达根目录,停止搜索
|
||||
break;
|
||||
}
|
||||
|
||||
currentDir = parentDir;
|
||||
level++;
|
||||
}
|
||||
|
||||
// 未找到工作区根目录,返回原始目录
|
||||
return startDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析相对于工作区根目录的路径
|
||||
* @param viteRoot Vite项目的根目录
|
||||
* @param relativePath 要解析的相对路径
|
||||
* @returns 绝对路径
|
||||
*/
|
||||
export function resolvePath(viteRoot: string, relativePath: string): string {
|
||||
const workspaceRoot = findWorkspaceRoot(viteRoot);
|
||||
return path.resolve(workspaceRoot, relativePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建带有时间戳的错误对象,可以标记为关键错误
|
||||
* @param message 错误消息
|
||||
* @param isCritical 是否为关键错误(会中断整个流程)
|
||||
* @returns 带有附加属性的Error对象
|
||||
*/
|
||||
export function createError(
|
||||
message: string,
|
||||
isCritical = false,
|
||||
): Error & { isCritical: boolean; timestamp: Date } {
|
||||
const error = new Error(message) as Error & {
|
||||
isCritical: boolean;
|
||||
timestamp: Date;
|
||||
};
|
||||
error.isCritical = isCritical;
|
||||
error.timestamp = new Date();
|
||||
return error;
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保目录存在,如果不存在则创建
|
||||
* @param dirPath 目录路径
|
||||
*/
|
||||
export async function ensureDirectoryExists(dirPath: string): Promise<void> {
|
||||
await fs.ensureDir(dirPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化日期为YYYY-MM-DD格式
|
||||
* @param date 日期对象
|
||||
* @returns 格式化的日期字符串
|
||||
*/
|
||||
export function formatDate(date: Date): string {
|
||||
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查路径是否为绝对路径
|
||||
* @param filePath 文件路径
|
||||
* @returns 是否为绝对路径
|
||||
*/
|
||||
export function isAbsolutePath(filePath: string): boolean {
|
||||
return path.isAbsolute(filePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全地删除文件,如果文件不存在则忽略错误
|
||||
* @param filePath 文件路径
|
||||
*/
|
||||
export async function safeRemoveFile(filePath: string): Promise<void> {
|
||||
try {
|
||||
await fs.remove(filePath);
|
||||
} catch (error) {
|
||||
// 如果文件不存在,忽略错误
|
||||
if (error instanceof Error && error.message === "ENOENT") {
|
||||
// 将未知类型的 error 转换为正确的类型或处理可能不存在的 code 属性
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
118
frontend/plugin/vite-plugin-turborepo-deploy/src/index.ts
Normal file
118
frontend/plugin/vite-plugin-turborepo-deploy/src/index.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
import type { Plugin, ResolvedConfig } from 'vite';
|
||||
import { VitePluginTurborepoDeployOptions, TurborepoDeployConfig } from './types';
|
||||
import { loadConfig } from "./core/config";
|
||||
import { createLogger } from "./core/logger";
|
||||
import { performLocalSync } from "./core/localSync";
|
||||
import { updateGitProjects } from "./core/gitHandler";
|
||||
import { performAutoCommit } from "./core/autoCommitHandler";
|
||||
import { findWorkspaceRoot } from "./core/utils";
|
||||
import path from "path";
|
||||
|
||||
export default function turborepoDeploy(
|
||||
options?: VitePluginTurborepoDeployOptions,
|
||||
): Plugin {
|
||||
let viteConfig: ResolvedConfig;
|
||||
let pluginConfig: TurborepoDeployConfig;
|
||||
let logger: ReturnType<typeof createLogger>;
|
||||
let workspaceRoot: string;
|
||||
|
||||
// 共享提交信息的状态容器
|
||||
const sharedCommitMessagesHolder = { current: null as string[] | null };
|
||||
|
||||
return {
|
||||
name: "vite-plugin-turborepo-deploy",
|
||||
apply: "build", // 仅在构建过程中应用
|
||||
|
||||
// 配置解析时钩子
|
||||
configResolved(resolvedConfig) {
|
||||
viteConfig = resolvedConfig;
|
||||
|
||||
// 获取工作区根目录
|
||||
workspaceRoot = findWorkspaceRoot(viteConfig.root);
|
||||
const isWorkspace = workspaceRoot !== viteConfig.root;
|
||||
|
||||
// 创建日志记录器,基于工作区根目录
|
||||
const logDir = options?.logger?.logDir || ".sync-log";
|
||||
const logPath = path.isAbsolute(logDir)
|
||||
? logDir
|
||||
: path.resolve(workspaceRoot, logDir);
|
||||
|
||||
logger = createLogger(
|
||||
workspaceRoot,
|
||||
options?.logger?.level || "info",
|
||||
options?.logger?.writeToFile !== false, // 默认为true
|
||||
logPath,
|
||||
);
|
||||
|
||||
logger.info(
|
||||
`检测到${isWorkspace ? "Turborepo工作区," : ""}根目录: ${workspaceRoot}`,
|
||||
);
|
||||
|
||||
try {
|
||||
// 加载配置,使用工作区根目录
|
||||
pluginConfig = loadConfig(options, workspaceRoot);
|
||||
logger.info("Turborepo Deploy 插件已配置。");
|
||||
} catch (error: any) {
|
||||
logger.error(`配置错误: ${error.message}`);
|
||||
throw error; // 配置无效时停止构建
|
||||
}
|
||||
},
|
||||
|
||||
// 关闭构建时钩子:执行所有任务
|
||||
async closeBundle() {
|
||||
if (Object.keys(pluginConfig).length === 0) {
|
||||
logger.info("未配置部署任务。");
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info("开始执行部署任务...");
|
||||
|
||||
try {
|
||||
// 1. 首先执行Git项目管理
|
||||
if (pluginConfig.gitProjects && pluginConfig.gitProjects.length > 0) {
|
||||
logger.info("开始执行Git项目管理...");
|
||||
try {
|
||||
await updateGitProjects(
|
||||
pluginConfig.gitProjects,
|
||||
workspaceRoot,
|
||||
logger,
|
||||
);
|
||||
logger.info("Git项目初始化任务成功完成。");
|
||||
} catch (e: any) {
|
||||
logger.error(`Git项目初始化错误: ${e.message}`, e);
|
||||
// Git项目管理失败必须终止后续任务
|
||||
throw e;
|
||||
}
|
||||
} else {
|
||||
logger.info("未配置Git项目,跳过Git项目初始化阶段。");
|
||||
}
|
||||
|
||||
// 2. 执行本地文件同步
|
||||
if (pluginConfig.localSync && pluginConfig.localSync.length > 0) {
|
||||
logger.info("开始执行本地文件同步...");
|
||||
await performLocalSync(pluginConfig.localSync, workspaceRoot, logger);
|
||||
logger.info("本地文件同步任务完成。");
|
||||
}
|
||||
|
||||
// 3. 执行自动提交(重置共享提交信息)
|
||||
if (pluginConfig.autoCommit) {
|
||||
logger.info("开始执行智能自动提交...");
|
||||
sharedCommitMessagesHolder.current = null; // 重置共享提交信息
|
||||
await performAutoCommit(
|
||||
pluginConfig.autoCommit,
|
||||
workspaceRoot,
|
||||
logger,
|
||||
sharedCommitMessagesHolder,
|
||||
);
|
||||
logger.info("智能自动提交任务完成。");
|
||||
}
|
||||
|
||||
logger.info("所有部署任务成功完成。");
|
||||
} catch (e: any) {
|
||||
logger.error(`部署错误: ${e.message}`, e);
|
||||
// 关键错误终止整个流程
|
||||
throw e;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
246
frontend/plugin/vite-plugin-turborepo-deploy/src/types.ts
Normal file
246
frontend/plugin/vite-plugin-turborepo-deploy/src/types.ts
Normal file
@@ -0,0 +1,246 @@
|
||||
/**
|
||||
* Configuration for individual Git project auto-commit behavior.
|
||||
* @deprecated This interface is deprecated and will be removed in a future version. Use AutoCommitConfig instead.
|
||||
*/
|
||||
export interface GitProjectAutoCommitConfig {
|
||||
/**
|
||||
* Whether to enable auto-commit for this project.
|
||||
* @default false
|
||||
*/
|
||||
enabled?: boolean;
|
||||
/**
|
||||
* The Git author username to watch for commits.
|
||||
* Required if `useSharedCommits` is false or if this project is intended as a source for shared commits.
|
||||
*/
|
||||
watchAuthor?: string;
|
||||
/**
|
||||
* Maximum number of recent commits to scan.
|
||||
* @default 50
|
||||
*/
|
||||
maxScanCount?: number;
|
||||
/**
|
||||
* Special marker string to identify commit segment points.
|
||||
* @default "/** 提交分隔符 **\/"
|
||||
*/
|
||||
commitSeparator?: string;
|
||||
/**
|
||||
* Template for the auto-generated commit message.
|
||||
* (Optional, a default will be provided if not set)
|
||||
*/
|
||||
message?: string;
|
||||
/**
|
||||
* Whether to push to the remote repository after committing.
|
||||
* @default false
|
||||
*/
|
||||
push?: boolean;
|
||||
/**
|
||||
* Whether to attempt using shared commit information from a previous project.
|
||||
* If true and shared info is available, `watchAuthor`, `maxScanCount`, etc., might be skipped for this project.
|
||||
* If shared info is not available, it will fall back to its own scanning logic if configured.
|
||||
* @default false
|
||||
*/
|
||||
useSharedCommits?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration for managing a single Git project.
|
||||
*/
|
||||
export interface GitProjectConfig {
|
||||
/**
|
||||
* The repository URL (SSH or HTTPS).
|
||||
*/
|
||||
repo: string;
|
||||
/**
|
||||
* The target branch to checkout and operate on.
|
||||
*/
|
||||
branch: string;
|
||||
/**
|
||||
* Directory to store the cloned/updated project.
|
||||
* Note: All Git projects will be placed under the `.sync-git` directory in workspace root.
|
||||
* This path is relative to the `.sync-git` directory, not to the workspace root directly.
|
||||
* For example, if targetDir is 'api', the actual location will be '<workspace_root>/.sync-git/api'.
|
||||
*/
|
||||
targetDir: string;
|
||||
/**
|
||||
* Optional: A name for the project, used for logging and potentially as an identifier for shared commits.
|
||||
*/
|
||||
projectName?: string;
|
||||
/**
|
||||
* Whether to update the project if it already exists.
|
||||
* @default true
|
||||
*/
|
||||
updateIfExists?: boolean;
|
||||
/**
|
||||
* Whether to discard all uncommitted changes before pulling.
|
||||
* If true, runs git checkout -- . && git clean -fd to remove all local changes.
|
||||
* Use with caution, as this will permanently delete local changes.
|
||||
* @default false
|
||||
*/
|
||||
discardChanges?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration for the auto-commit module which operates independently.
|
||||
*/
|
||||
export interface AutoCommitConfig {
|
||||
/**
|
||||
* Git projects to run auto-commit operations on
|
||||
*/
|
||||
projects: Array<{
|
||||
/**
|
||||
* Directory of the git project (relative to workspace root)
|
||||
*/
|
||||
targetDir: string;
|
||||
/**
|
||||
* Optional: A name for the project, used for logging and as identifier for shared commits.
|
||||
* If not provided, targetDir will be used as the project name.
|
||||
*/
|
||||
projectName?: string;
|
||||
/**
|
||||
* The Git author username to watch for commits.
|
||||
* Required if `useSharedCommits` is false or if this project is intended as a source for shared commits.
|
||||
*/
|
||||
watchAuthor?: string;
|
||||
/**
|
||||
* Maximum number of recent commits to scan.
|
||||
* @default 50
|
||||
*/
|
||||
maxScanCount?: number;
|
||||
/**
|
||||
* Special marker string to identify commit segment points.
|
||||
* @default "/** 提交分隔符 **\/"
|
||||
*/
|
||||
commitSeparator?: string;
|
||||
/**
|
||||
* Template for the auto-generated commit message.
|
||||
* (Optional, a default will be provided if not set)
|
||||
*/
|
||||
message?: string;
|
||||
/**
|
||||
* Whether to push to the remote repository after committing.
|
||||
* @default false
|
||||
*/
|
||||
push?: boolean;
|
||||
/**
|
||||
* Whether to attempt using shared commit information from a previous project.
|
||||
* @default false
|
||||
*/
|
||||
useSharedCommits?: boolean;
|
||||
/**
|
||||
* Target branch to perform auto-commit on.
|
||||
* If not specified, the current branch will be used.
|
||||
*/
|
||||
branch?: string;
|
||||
}>;
|
||||
/**
|
||||
* Whether to insert commit separator after auto-commit
|
||||
* @default true
|
||||
*/
|
||||
insertSeparator?: boolean;
|
||||
/**
|
||||
* Whether to enable shared commit buffer across projects
|
||||
* @default true
|
||||
*/
|
||||
enableSharedCommits?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration for a single local file/directory synchronization task.
|
||||
*/
|
||||
export interface LocalSyncConfig {
|
||||
/**
|
||||
* Source directory/file (relative to workspace root).
|
||||
*/
|
||||
source: string;
|
||||
/**
|
||||
* Target directory/file (relative to workspace root).
|
||||
* Can be a single path or an array of paths for distribution to multiple targets.
|
||||
*/
|
||||
target: string | string[];
|
||||
/**
|
||||
* Synchronization mode.
|
||||
* - `copy`: Simple copy, doesn\'t handle existing files in target.
|
||||
* - `mirror`: Mirror sync, deletes files in target not present in source.
|
||||
* - `incremental`: Incremental update, only overwrites changed files.
|
||||
* @default \'incremental\'
|
||||
*/
|
||||
mode?: "copy" | "mirror" | "incremental";
|
||||
/**
|
||||
* Whether to clear the target directory before synchronization.
|
||||
* @default false
|
||||
*/
|
||||
clearTarget?: boolean;
|
||||
/**
|
||||
* If true, only adds files/directories from source that do not exist in target.
|
||||
* Does not modify or delete existing files in target.
|
||||
* @default false
|
||||
*/
|
||||
addOnly?: boolean;
|
||||
/**
|
||||
* Array of regular expressions to exclude files/directories.
|
||||
*/
|
||||
exclude?: string[];
|
||||
/**
|
||||
* Array of glob patterns or regular expressions for directories to exclude.
|
||||
*/
|
||||
excludeDirs?: string[];
|
||||
/**
|
||||
* Array of glob patterns or regular expressions for files to exclude.
|
||||
*/
|
||||
excludeFiles?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration for the logger.
|
||||
*/
|
||||
export interface LoggerConfig {
|
||||
/**
|
||||
* The log level to use.
|
||||
* - `error`: Only log errors.
|
||||
* - `warn`: Log errors, warnings, and info messages.
|
||||
* - `verbose`: Log all messages including debug information.
|
||||
* @default 'info'
|
||||
*/
|
||||
level?: "error" | "warn" | "info" | "verbose";
|
||||
|
||||
/**
|
||||
* Whether to write logs to file.
|
||||
* @default true
|
||||
*/
|
||||
writeToFile?: boolean;
|
||||
|
||||
/**
|
||||
* Directory to store log files, relative to workspace root.
|
||||
* @default '.sync-log'
|
||||
*/
|
||||
logDir?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Main configuration for the Turborepo Deploy Vite plugin.
|
||||
*/
|
||||
export interface TurborepoDeployConfig {
|
||||
/**
|
||||
* Configuration for local file/directory synchronization tasks.
|
||||
* 在编译后执行。
|
||||
*/
|
||||
localSync?: Array<LocalSyncConfig>;
|
||||
/**
|
||||
* Configuration for Git project management (clone/update).
|
||||
* 在编译前执行。
|
||||
*/
|
||||
gitProjects?: Array<GitProjectConfig>;
|
||||
/**
|
||||
* Configuration for auto-commit functionality.
|
||||
* This runs separately after build.
|
||||
* 在编译后执行。
|
||||
*/
|
||||
autoCommit?: AutoCommitConfig;
|
||||
/**
|
||||
* Logger configuration.
|
||||
*/
|
||||
logger?: LoggerConfig;
|
||||
}
|
||||
|
||||
// Utility type for the plugin itself
|
||||
export interface VitePluginTurborepoDeployOptions extends TurborepoDeployConfig {}
|
||||
Reference in New Issue
Block a user