import * as fs from 'fs' import * as path from 'path' import { utils } from '../utils' import { FileSuffix } from '../type' import * as vscode from 'vscode' import { WINGED_DIRS } from '../consts' class FileManage { /** * 递归获取目录下的所有文件名 * @param dir 指定的目录 */ public getFileNamesByPath(dir: string): string[] { let fileNames: string[] = [] const files = fs.readdirSync(dir) files.forEach((file) => { const filePath = path.join(dir, file) const fileStat = fs.statSync(filePath) if (fileStat.isDirectory()) { fileNames = fileNames.concat(this.getFileNamesByPath(filePath)) } else { fileNames.push(file) } }) return fileNames } /** * 根据文件名查找指定目录下的文件绝对路径 * @param name */ public getFilePathByName(name: string, dir: string): string | null { const files = fs.readdirSync(dir) for (const file of files) { const filePath = path.join(dir, file) if (file === name) { return filePath } const fileStat = fs.statSync(filePath) if (fileStat.isDirectory()) { const res = this.getFilePathByName(name, filePath) if (res !== null) { return res } } } return null } /** * 将文件名转化成组件名 * @param fileName文件名 */ public getCompName(fileName: string) { return utils.pascalizeString(fileName.split('.')[0]) } /** * 将组件名转换成文件名 * @param compName 组件名称 */ public getFileName(compName: string, suffix: FileSuffix) { if (suffix === '.ts' || suffix === '.v.ts') return compName + suffix return utils.recoverPascal(compName).join('-') + suffix } /** * 拿到绝对路径下的文件名并转换成 CompName * @param uri 路径 * @param separator 路径分隔符 默认为 '/' */ public getCompNameByPath(uri: string, separator = '/') { if (process.platform === 'win32') { separator = '\\' } const tempArr = uri.split(separator) return this.getCompName(tempArr[tempArr.length - 1]) } /** * 校验名称是否为组件名 * @param compName 组件名称 */ public validateCompName(compName: string) { return utils.validatePascal(compName) } /** * 获取文件类型,采用split('.')处理 * @param filePath 文件路径 */ public getFileType(filePath: string) { return filePath.split('.')[1] } /** * 获取文件内容 */ public async readFile(filePath: string) { return (await vscode.workspace.fs.readFile(vscode.Uri.file(filePath))).toString() } /** * 获取工作区根目录 * windows下为'\\server\c$\folder\file.txt' * linux 下为 '/shares/c$/file.txt' */ public getRootPath() { if (vscode.workspace.workspaceFolders) { return vscode.workspace.workspaceFolders[0].uri.fsPath } return undefined } /** * 根据文件类型 获取文件 Dir * @param targetType 文件类型 */ public getDirByFileType = (targetType: 'html' | 'ts' | 'less' | 'v') => { let dir = '' switch (targetType) { case 'html': dir = WINGED_DIRS.VIEW_TPLS break case 'ts': dir = WINGED_DIRS.TS break case 'less': dir = WINGED_DIRS.LESS break case 'v': dir = WINGED_DIRS.V break } return dir } } export const fm = new FileManage()