@ui18n/cli
Version:
🌍 UI18n CLI工具 - 强大的国际化命令行工具
226 lines • 6.55 kB
JavaScript
import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync, statSync } from 'fs';
import { join, dirname, extname, relative, resolve } from 'path';
import { glob } from 'glob';
/**
* 文件系统工具类
*/
export class FileUtils {
/**
* 读取文件内容
*/
static readFile(filePath) {
try {
return readFileSync(filePath, 'utf-8');
}
catch (error) {
throw new Error(`读取文件失败: ${filePath} - ${error}`);
}
}
/**
* 写入文件内容
*/
static writeFile(filePath, content) {
try {
// 确保目录存在
const dir = dirname(filePath);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
writeFileSync(filePath, content, 'utf-8');
}
catch (error) {
throw new Error(`写入文件失败: ${filePath} - ${error}`);
}
}
/**
* 检查文件是否存在
*/
static exists(filePath) {
return existsSync(filePath);
}
/**
* 确保目录存在
*/
static ensureDir(dirPath) {
if (!existsSync(dirPath)) {
mkdirSync(dirPath, { recursive: true });
}
}
/**
* 获取文件扩展名
*/
static getExtension(filePath) {
return extname(filePath);
}
/**
* 获取相对路径
*/
static getRelativePath(from, to) {
return relative(from, to);
}
/**
* 解析绝对路径
*/
static resolvePath(...paths) {
return resolve(...paths);
}
/**
* 查找文件
*/
static async findFiles(pattern, options) {
try {
return await glob(pattern, {
cwd: options?.cwd || process.cwd(),
ignore: options?.ignore || ['node_modules/**', 'dist/**', 'build/**']
});
}
catch (error) {
throw new Error(`查找文件失败: ${pattern} - ${error}`);
}
}
/**
* 递归读取目录
*/
static readDirRecursive(dirPath, options) {
const files = [];
const extensions = options?.extensions || [];
const ignore = options?.ignore || ['node_modules', 'dist', 'build', '.git'];
function traverse(currentPath) {
try {
const items = readdirSync(currentPath);
for (const item of items) {
const fullPath = join(currentPath, item);
const stat = statSync(fullPath);
if (stat.isDirectory()) {
// 检查是否应该忽略此目录
if (!ignore.some(pattern => item.includes(pattern))) {
traverse(fullPath);
}
}
else if (stat.isFile()) {
// 检查文件扩展名
if (extensions.length === 0 || extensions.includes(extname(item))) {
files.push(fullPath);
}
}
}
}
catch (error) {
// 忽略无法访问的目录
}
}
if (existsSync(dirPath)) {
traverse(dirPath);
}
return files;
}
/**
* 读取JSON文件
*/
static readJSON(filePath) {
try {
const content = this.readFile(filePath);
return JSON.parse(content);
}
catch (error) {
throw new Error(`读取JSON文件失败: ${filePath} - ${error}`);
}
}
/**
* 写入JSON文件
*/
static writeJSON(filePath, data, indent = 2) {
try {
const content = JSON.stringify(data, null, indent);
this.writeFile(filePath, content);
}
catch (error) {
throw new Error(`写入JSON文件失败: ${filePath} - ${error}`);
}
}
/**
* 获取文件大小
*/
static getFileSize(filePath) {
try {
const stat = statSync(filePath);
return stat.size;
}
catch (error) {
throw new Error(`获取文件大小失败: ${filePath} - ${error}`);
}
}
/**
* 格式化文件大小
*/
static formatFileSize(bytes) {
const units = ['B', 'KB', 'MB', 'GB'];
let size = bytes;
let unitIndex = 0;
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex++;
}
return `${size.toFixed(1)} ${units[unitIndex]}`;
}
/**
* 检查是否为支持的源代码文件
*/
static isSourceFile(filePath) {
const sourceExtensions = [
'.js', '.jsx', '.ts', '.tsx',
'.vue', '.svelte',
'.html', '.htm',
'.json'
];
const ext = extname(filePath).toLowerCase();
return sourceExtensions.includes(ext);
}
/**
* 检查是否为配置文件
*/
static isConfigFile(filePath) {
const configFiles = [
'package.json',
'tsconfig.json',
'ui18n.config.js',
'ui18n.config.json',
'.ui18nrc',
'.ui18nrc.json',
'.ui18nrc.js'
];
const fileName = filePath.split(/[/\\]/).pop() || '';
return configFiles.includes(fileName);
}
/**
* 创建备份文件
*/
static createBackup(filePath) {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const backupPath = `${filePath}.backup.${timestamp}`;
try {
const content = this.readFile(filePath);
this.writeFile(backupPath, content);
return backupPath;
}
catch (error) {
throw new Error(`创建备份文件失败: ${filePath} - ${error}`);
}
}
/**
* 恢复备份文件
*/
static restoreBackup(backupPath) {
const originalPath = backupPath.replace(/\.backup\.\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z$/, '');
try {
const content = this.readFile(backupPath);
this.writeFile(originalPath, content);
return originalPath;
}
catch (error) {
throw new Error(`恢复备份文件失败: ${backupPath} - ${error}`);
}
}
}
export default FileUtils;
//# sourceMappingURL=file-utils.js.map