91 lines
2.5 KiB
JavaScript
91 lines
2.5 KiB
JavaScript
|
const fs = require('fs').promises;
|
|||
|
const path = require('path');
|
|||
|
|
|||
|
/**
|
|||
|
* @function ensurePathEndsWithSlash
|
|||
|
* @description 确保路径以斜杠结尾
|
|||
|
* @param {string} pathValue - 要处理的路径
|
|||
|
* @returns {string} 处理后的路径
|
|||
|
*/
|
|||
|
function ensurePathEndsWithSlash(pathValue) {
|
|||
|
if (!pathValue) return pathValue;
|
|||
|
return pathValue.endsWith('/') ? pathValue : pathValue + '/';
|
|||
|
}
|
|||
|
|
|||
|
/**
|
|||
|
* @function validatePaths
|
|||
|
* @description 验证多个路径是否存在
|
|||
|
* @param {Object} paths - 要验证的路径对象
|
|||
|
* @returns {Object} 验证结果,包含每个路径的验证状态和错误信息
|
|||
|
*/
|
|||
|
async function validatePaths(paths) {
|
|||
|
const results = {};
|
|||
|
|
|||
|
// 首先验证工作路径
|
|||
|
if (!paths.workPath) {
|
|||
|
results.workPath = {
|
|||
|
valid: false,
|
|||
|
error: '工作路径不能为空'
|
|||
|
};
|
|||
|
return results;
|
|||
|
}
|
|||
|
|
|||
|
// 确保工作路径以斜杠结尾
|
|||
|
const workPath = ensurePathEndsWithSlash(paths.workPath);
|
|||
|
|
|||
|
try {
|
|||
|
// 检查工作路径是否存在
|
|||
|
await fs.access(workPath);
|
|||
|
results.workPath = {
|
|||
|
valid: true,
|
|||
|
normalizedPath: workPath
|
|||
|
};
|
|||
|
} catch (error) {
|
|||
|
results.workPath = {
|
|||
|
valid: false,
|
|||
|
error: error.code === 'ENOENT' ? '工作路径不存在' : '工作路径访问错误'
|
|||
|
};
|
|||
|
return results;
|
|||
|
}
|
|||
|
|
|||
|
// 验证模型路径和服务路径(相对于工作路径)
|
|||
|
const relativePaths = {
|
|||
|
modelsPath: paths.modelsPath,
|
|||
|
servicesPath: paths.servicesPath
|
|||
|
};
|
|||
|
|
|||
|
for (const [key, pathValue] of Object.entries(relativePaths)) {
|
|||
|
if (!pathValue) {
|
|||
|
results[key] = {
|
|||
|
valid: false,
|
|||
|
error: '路径不能为空'
|
|||
|
};
|
|||
|
continue;
|
|||
|
}
|
|||
|
|
|||
|
try {
|
|||
|
// 确保相对路径以斜杠结尾
|
|||
|
const normalizedPath = ensurePathEndsWithSlash(pathValue);
|
|||
|
// 拼接完整路径
|
|||
|
const fullPath = path.join(workPath, normalizedPath);
|
|||
|
// 检查路径是否存在
|
|||
|
await fs.access(fullPath);
|
|||
|
results[key] = {
|
|||
|
valid: true,
|
|||
|
normalizedPath: normalizedPath
|
|||
|
};
|
|||
|
} catch (error) {
|
|||
|
results[key] = {
|
|||
|
valid: false,
|
|||
|
error: error.code === 'ENOENT' ? '路径不存在' : '路径访问错误'
|
|||
|
};
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
return results;
|
|||
|
}
|
|||
|
|
|||
|
module.exports = {
|
|||
|
validatePaths,
|
|||
|
ensurePathEndsWithSlash
|
|||
|
};
|