From 1f240fa69000739f7785344224c230876d3235b6 Mon Sep 17 00:00:00 2001 From: xianyunleo Date: Fri, 1 Dec 2023 19:22:12 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=8D=E6=9E=84=E9=83=A8=E5=88=86Util?= =?UTF-8?q?=EF=BC=9B=E7=BD=91=E7=AB=99=E6=8C=89=E5=88=9B=E5=BB=BA=E6=97=B6?= =?UTF-8?q?=E9=97=B4=E6=8E=92=E5=BA=8F=EF=BC=8C=E6=94=AF=E6=8C=81=E5=88=86?= =?UTF-8?q?=E9=A1=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/App.js | 66 +++++----- src/main/core/Database.js | 21 +-- src/main/core/Env/Env.js | 20 +-- src/main/core/Env/EnvMacOS.js | 10 +- src/main/core/Nginx.js | 68 ++++++---- src/main/core/ServerControl.js | 2 +- src/main/core/php/Php.js | 6 +- src/main/core/php/extension/Extension.js | 10 +- src/main/core/php/extension/Installer.js | 24 ++-- src/main/core/software/CommonInstall.js | 21 ++- src/main/core/software/Installer.js | 16 +-- src/main/core/software/LocalInstall.js | 4 +- src/main/core/software/Software.js | 14 +- src/main/core/software/SoftwareExtend.js | 31 ++--- src/main/core/software/SoftwareInit.js | 72 +++++------ src/main/core/website/NginxWebsite.js | 25 ++-- src/main/core/website/Website.js | 47 ++++--- src/main/utils/DirUtil.js | 91 +++++++++++++ src/main/utils/Directory.js | 120 ------------------ src/main/utils/DirectoryInfo.js | 0 src/main/utils/FileUtil.js | 63 ++++----- src/main/utils/FsUtil.js | 14 +- src/main/utils/Hosts.js | 12 +- src/main/utils/Native.js | 4 +- src/renderer/App.vue | 12 +- src/renderer/components/Settings/EnvVar.vue | 27 ++-- .../components/Software/PhpExtManager.vue | 10 +- .../ToolPage/MysqlResetPwdModal.vue | 10 +- src/renderer/components/UserPwdModal.vue | 2 +- .../components/WebSite/AddWebSiteModal.vue | 15 ++- .../WebSite/EditWebSite/BasicSetting.vue | 55 ++++---- .../WebSite/EditWebSite/RewriteSetting.vue | 22 ++-- src/renderer/store/index.js | 2 +- src/renderer/views/Website.vue | 35 +++-- 34 files changed, 460 insertions(+), 491 deletions(-) create mode 100644 src/main/utils/DirUtil.js delete mode 100644 src/main/utils/Directory.js delete mode 100644 src/main/utils/DirectoryInfo.js diff --git a/src/main/App.js b/src/main/App.js index ac0d298f..8a6ca32c 100644 --- a/src/main/App.js +++ b/src/main/App.js @@ -9,14 +9,14 @@ import { InitFiles_DIR_NAME, TEMP_DIR_NAME } from '@/main/utils/constant' -import Directory from '@/main/utils/Directory' +import DirUtil from '@/main/utils/DirUtil' import FileUtil from '@/main/utils/FileUtil' import Path from '@/main/utils/Path' import child_process from 'child_process' -import fs from 'fs' import Software from "@/main/core/software/Software"; import GetPath from "@/shared/utils/GetPath"; import LocalInstall from "@/main/core/software/LocalInstall"; +import FsUtil from '@/main/utils/FsUtil' const app = electronRequire('app'); @@ -112,8 +112,8 @@ export default class App { return path.join(this.getDir(), `extra/${process.platform}`); } - static initFileExists() { - return FileUtil.Exists(this.getInitFilePath()); + static async initFileExists() { + return await FileUtil.Exists(this.getInitFilePath()); } static async init() { @@ -123,34 +123,34 @@ export default class App { let initFile = this.getInitFilePath(); - if (!FileUtil.Exists(initFile)) { + if (!await FileUtil.Exists(initFile)) { return; } - const softwareDirExists = Software.DirExists(); + const softwareDirExists = await Software.DirExists(); if (isMacOS && !isDev) { - if (!Directory.Exists(MAC_USER_CORE_DIR)) { - Directory.CreateDirectory(MAC_USER_CORE_DIR); + if (!await DirUtil.Exists(MAC_USER_CORE_DIR)) { + await DirUtil.Create(MAC_USER_CORE_DIR); } await this.updateMacCoreSubDir(['Library']); } - this.moveInitFiles(["downloads", "www"]); - this.createCoreSubDir(["software", "database", "bin",`${TEMP_DIR_NAME}/php`]); + await this.moveInitFiles(["downloads", "www"]); + await this.createCoreSubDir(["software", "database", "bin",`${TEMP_DIR_NAME}/php`]); if (!softwareDirExists) { //目录不存在说明是第一次安装,不是覆盖安装 - const files = Directory.GetFiles(GetPath.getDownloadsDir()); + const files = await DirUtil.GetFiles(GetPath.getDownloadsDir()); await LocalInstall.installMultiple(files) } - FileUtil.Delete(initFile); + await FileUtil.Delete(initFile); } - static deleteInitFile(){ + static async deleteInitFile() { let initFile = this.getInitFilePath(); - if (FileUtil.Exists(initFile)) { - FileUtil.Delete(initFile); + if (await FileUtil.Exists(initFile)) { + await FileUtil.Delete(initFile); } } @@ -169,15 +169,15 @@ export default class App { let corePath = this.getCoreDir(); for (const dir of dirs) { let source = Path.Join(corePath, dir); - if (!Directory.Exists(source)) { + if (!await DirUtil.Exists(source)) { continue; } let target = Path.Join(MAC_USER_CORE_DIR, dir); - if (!Directory.Exists(target)) { - Directory.CreateDirectory(target); + if (!await DirUtil.Exists(target)) { + await DirUtil.Create(target); } child_process.execSync(`rsync -a ${source}/* ${target}`); - await Directory.Delete(source); + await DirUtil.Delete(source); } } @@ -185,11 +185,11 @@ export default class App { * 创建目录,如果目录不存在的情况下 * @param dirs */ - static createCoreSubDir(dirs) { + static async createCoreSubDir(dirs) { for (const dir of dirs) { let p = path.join(this.getUserCoreDir(), dir); - if (!Directory.Exists(p)) { - Directory.CreateDirectory(p); + if (!await DirUtil.Exists(p)) { + await DirUtil.Create(p); } } } @@ -198,24 +198,20 @@ export default class App { * 将initFiles目录下的文件(文件夹)移动到用户操作的核心目录 * @param files */ - static moveInitFiles(files = []) { - let initFilesPath = Path.Join(this.getCoreDir(),InitFiles_DIR_NAME); + static async moveInitFiles(files = []) { + let initFilesPath = Path.Join(this.getCoreDir(), InitFiles_DIR_NAME); for (const file of files) { - let source = Path.Join(initFilesPath, file); - if(!fs.existsSync(source)){ - continue; - } - let target = Path.Join(this.getUserCoreDir(), file); - if (!fs.existsSync(target)) { - fs.renameSync(source, target); + const source = Path.Join(initFilesPath, file); + const target = Path.Join(this.getUserCoreDir(), file); + + if (await FsUtil.Exists(target)) { + FsUtil.Remove(source, { force: true, recursive: true }) //不捕捉错误 } else { - let options = {force: true, recursive: true}; - fs.rm(source, options, err => { - console.log(`Error moveInitFiles fs.rm ${source}\r${err}`); - }); + await FsUtil.Rename(source, target) } } } + static exit() { app.exit(); } diff --git a/src/main/core/Database.js b/src/main/core/Database.js index 3733897a..a5a9421d 100644 --- a/src/main/core/Database.js +++ b/src/main/core/Database.js @@ -9,18 +9,6 @@ import TcpProcess from "@/main/utils/TcpProcess"; import { isWindows } from '@/main/utils/utils' export default class Database { - - /** - * - * @param version {string} - * @returns {Promise} - */ - static async initMySQL(version) { - //mysql user的密码在mysql data目录 - await Database.initMySQLData(version); - await Database.resetMySQLPassword(version); - } - /** * * @param version {string} @@ -52,14 +40,15 @@ export default class Database { } let mysqlPath = GetPath.getMysqlDir(version); let resetPwdPath = path.join(mysqlPath, 'reset-pwd.txt'); - FileUtil.WriteAllText(resetPwdPath, resetCommand); + await FileUtil.WriteAll(resetPwdPath, resetCommand); let confFilePath = this.getMySQLConfFilePath(version); - let portMatch = FileUtil.ReadAllText(confFilePath).match(/\[mysqld].*?port\s*=\s*(\d+)/s); + let confText = await FileUtil.ReadAll(confFilePath) + let portMatch = confText.match(/\[mysqld].*?port\s*=\s*(\d+)/s) let port = portMatch ? portMatch[1] : 3306; let oldPid = await TcpProcess.getPidByPort(port); - if(oldPid){ + if (oldPid) { await ProcessExtend.kill(oldPid); } @@ -79,7 +68,7 @@ export default class Database { } await sleep(100); await ProcessExtend.kill(childProcess.pid); - FileUtil.Delete(resetPwdPath); + await FileUtil.Delete(resetPwdPath); } static getMySQLConfFilePath(version) { diff --git a/src/main/core/Env/Env.js b/src/main/core/Env/Env.js index 21e79cf8..e7875a5e 100644 --- a/src/main/core/Env/Env.js +++ b/src/main/core/Env/Env.js @@ -11,10 +11,10 @@ export default class Env { * @param targetPath * @param binName */ - static createBinFile(targetPath, binName) { + static async createBinFile(targetPath, binName) { let binDirPath = GetPath.getBinDir(); let path = Path.Join(binDirPath, this.getBinFileName(binName)); - this.deleteBinFile(binName); + await this.deleteBinFile(binName); if (isWindows) { let text; if (binName === 'composer') { @@ -22,7 +22,7 @@ export default class Env { } else { text = `@echo off\r\n"${targetPath}" %*` } - FileUtil.WriteAllText(path, text); + await FileUtil.WriteAll(path, text); } else { if (binName === 'php') { this.createOtherBinFile(targetPath, 'phpize', 'phpize'); @@ -38,22 +38,22 @@ export default class Env { FileUtil.CreateSymbolicLink(path, targetOtherFilePath); } - static deleteBinFile(binName) { + static async deleteBinFile(binName) { let path = Path.Join(GetPath.getBinDir(), this.getBinFileName(binName)); - if (FileUtil.Exists(path)) { - FileUtil.Delete(path); + if (await FileUtil.Exists(path)) { + await FileUtil.Delete(path); } if (!isWindows) { if (binName === 'php') { - this.deleteOtherBinFile('phpize'); + await this.deleteOtherBinFile('phpize'); } } } - static deleteOtherBinFile(otherBinName) { + static async deleteOtherBinFile(otherBinName) { let path = Path.Join(GetPath.getBinDir(), this.getBinFileName(otherBinName)); - if (FileUtil.Exists(path)) { - FileUtil.Delete(path); + if (await FileUtil.Exists(path)) { + await FileUtil.Delete(path); } } diff --git a/src/main/core/Env/EnvMacOS.js b/src/main/core/Env/EnvMacOS.js index e2e521a6..06642c11 100644 --- a/src/main/core/Env/EnvMacOS.js +++ b/src/main/core/Env/EnvMacOS.js @@ -21,8 +21,8 @@ export default class EnvMacOS { let userName = OS.getUserName(); let text; - if (!FileUtil.Exists(envFilePath)) { - FileUtil.WriteAllText(envFilePath, '') + if (!await FileUtil.Exists(envFilePath)) { + await FileUtil.WriteAll(envFilePath, '') } if (!await FsUtil.CanReadWrite(envFilePath)) { @@ -30,7 +30,7 @@ export default class EnvMacOS { await Command.sudoExec(`chown ${userName}:staff ${envFilePath}`) } - text = FileUtil.ReadAllText(envFilePath); + text = await FileUtil.ReadAll(envFilePath); if (enable) { let binPath = GetPath.getBinDir(); @@ -39,11 +39,11 @@ export default class EnvMacOS { if (text.slice(-1) !== '\n') { appendText = `\n${appendText}` } - await FileUtil.AppendAllText(envFilePath, appendText); + await FileUtil.Append(envFilePath, appendText); } else { let regx = new RegExp(`export\\s+PATH.+${APP_NAME}.+`, 'g'); text = text.replaceAll(regx, ''); - FileUtil.WriteAllText(envFilePath, text); + await FileUtil.WriteAll(envFilePath, text); } } diff --git a/src/main/core/Nginx.js b/src/main/core/Nginx.js index 81e4d0b3..51dae93f 100644 --- a/src/main/core/Nginx.js +++ b/src/main/core/Nginx.js @@ -1,7 +1,7 @@ import path from "path"; import GetPath from "@/shared/utils/GetPath"; import NginxWebsite from "@/main/core/website/NginxWebsite"; -import Directory from "@/main/utils/Directory"; +import DirUtil from "@/main/utils/DirUtil"; import FileUtil from "@/main/utils/FileUtil"; import Path from "@/main/utils/Path"; import { isWindows } from '@/main/utils/utils' @@ -14,22 +14,31 @@ export default class Nginx { */ static async getWebsiteList(search) { let vhostsPath = GetPath.getNginxVhostsDir(); - if (!Directory.Exists(vhostsPath)) { + if (!await DirUtil.Exists(vhostsPath)) { return []; } - let files = Directory.GetFiles(vhostsPath, search); - return await Promise.all(files.map(async path => { - let confName = Path.GetBaseName(path); - let webSite = new NginxWebsite(confName); - return webSite.getBasicInfo(); - })); + + const files = await DirUtil.GetFiles(vhostsPath, search, true) + //根据创建时间倒序 + files.sort((a,b)=>{ + return b.stats.birthtimeMs - a.stats.birthtimeMs + }) + + const mapFn = async (file) => { + let confName = Path.GetBaseName(file.path) + const website = new NginxWebsite(confName) + await website.init() + return website.getBasicInfo() + } + + return await Promise.all(files.map(mapFn)) } /** * 添加网站 * @param websiteInfo {WebsiteItem} */ - static addWebsite(websiteInfo) { + static async addWebsite(websiteInfo) { let serverName = websiteInfo.serverName; let serverNameStr = websiteInfo.extraServerName ? `${serverName} ${websiteInfo.extraServerName}` : serverName; let confName = this.getWebsiteConfName(websiteInfo.serverName, websiteInfo.port); @@ -99,37 +108,40 @@ export default class Nginx { } - FileUtil.WriteAllText(confPath, confText); + await FileUtil.WriteAll(confPath, confText); - let website = new NginxWebsite(confName); + const website = new NginxWebsite(confName); + await website.init(); website.setPHPVersion(websiteInfo.phpVersion); - website.setExtraInfo({syncHosts: websiteInfo.syncHosts}); - website.save(); + website.setExtraInfo({ syncHosts: websiteInfo.syncHosts }); + await website.save(); //创建URL重写文件 let rewritePath = Nginx.getWebsiteRewriteConfPath(confName); - if (!FileUtil.Exists(rewritePath)) { - FileUtil.WriteAllText(rewritePath, ''); + if (!await FileUtil.Exists(rewritePath)) { + await FileUtil.WriteAll(rewritePath, ''); } } - static delWebsite(confName) { + static async delWebsite(confName) { let confPath = this.getWebsiteConfPath(confName); - if (FileUtil.Exists(confPath)) { - FileUtil.Delete(confPath); + if (await FileUtil.Exists(confPath)) { + await FileUtil.Delete(confPath); } let rewritePath = this.getWebsiteRewriteConfPath(confName); - if (FileUtil.Exists(rewritePath)) { - FileUtil.Delete(rewritePath); + if (await FileUtil.Exists(rewritePath)) { + await FileUtil.Delete(rewritePath); } } + + static async websiteExists(serverName, port) { const vhostsPath = GetPath.getNginxVhostsDir() - const files = Directory.GetFiles(vhostsPath) + const files = await DirUtil.GetFiles(vhostsPath) const filterArr = await files.filterAsync(async (path) => { - let confText = FileUtil.ReadAllText(path) + let confText = await FileUtil.ReadAll(path) const serverNames = this.getAllServerName(confText) return serverNames.includes(serverName) && this.getPortByConfPath(path) === port }) @@ -162,12 +174,12 @@ export default class Nginx { * 获取URL重写规则列表 * @returns {Promise} */ - static getRewriteRuleList() { + static async getRewriteRuleList() { let rewritePath = GetPath.getNginxRewriteDir(); - if (!Directory.Exists(rewritePath)) { + if (!await DirUtil.Exists(rewritePath)) { return []; } - let files = Directory.GetFiles(rewritePath, '.conf'); + let files = await DirUtil.GetFiles(rewritePath, '.conf'); return files.map(name => { return Path.GetFileNameWithoutExtension(name); }); @@ -178,12 +190,12 @@ export default class Nginx { * @param ruleName {string} * @returns {string} */ - static getRewriteByRule(ruleName) { + static async getRewriteByRule(ruleName) { let rewritePath = path.join(GetPath.getNginxRewriteDir(), `${ruleName}.conf`) - if (!FileUtil.Exists(rewritePath)) { + if (!await FileUtil.Exists(rewritePath)) { return ''; } - return FileUtil.ReadAllText(rewritePath); + return await FileUtil.ReadAll(rewritePath); } /** diff --git a/src/main/core/ServerControl.js b/src/main/core/ServerControl.js index 06486c80..a2821c55 100644 --- a/src/main/core/ServerControl.js +++ b/src/main/core/ServerControl.js @@ -27,7 +27,7 @@ export default class ServerControl { options = { cwd: workPath, shell: true } //使用shell,childProcess返回的pid是shell的pid } - if (!FileUtil.Exists(serverProcessPath)) { + if (!await FileUtil.Exists(serverProcessPath)) { throw new Error(`${serverProcessPath} 文件不存在!`); } diff --git a/src/main/core/php/Php.js b/src/main/core/php/Php.js index 713990c8..83cab78c 100644 --- a/src/main/core/php/Php.js +++ b/src/main/core/php/Php.js @@ -1,4 +1,4 @@ -import Directory from "@/main/utils/Directory"; +import DirUtil from "@/main/utils/DirUtil"; import Path from "@/main/utils/Path"; import GetPath from "@/shared/utils/GetPath"; import { APP_NAME } from '@/shared/utils/constant' @@ -53,13 +53,13 @@ pm.max_spare_servers = 3 * @param phpVersion * @returns {string} */ - static getExtensionDir(phpVersion) { + static async getExtensionDir(phpVersion) { if (isWindows) { let phpDir = GetPath.getPhpDir(phpVersion); return `${Path.Join(phpDir, 'ext')}`; } else { let phpDir = GetPath.getPhpDir(phpVersion); - let dirs = Directory.GetDirectories(`${Path.Join(phpDir, 'lib/php/extensions')}`, 'no-debug-non-zts'); + let dirs = await DirUtil.GetDirectories(`${Path.Join(phpDir, 'lib/php/extensions')}`, 'no-debug-non-zts'); return dirs[0]; } } diff --git a/src/main/core/php/extension/Extension.js b/src/main/core/php/extension/Extension.js index dfb85d25..8260e128 100644 --- a/src/main/core/php/extension/Extension.js +++ b/src/main/core/php/extension/Extension.js @@ -5,14 +5,14 @@ import { isWindows } from '@/main/utils/utils' import GetPath from '@/shared/utils/GetPath' export default class Extension { - static async getList(phpVersion) { + static async getList(phpVersion) { let list = this.getSimpleList(); - let extDir = Php.getExtensionDir(phpVersion); + let extDir = await Php.getExtensionDir(phpVersion); let newList = await Promise.all( list.map(async item => { - let isInstalled = FileUtil.Exists(Path.Join(extDir,item.extFileName)); + let isInstalled = await FileUtil.Exists(Path.Join(extDir,item.extFileName)); return Object.assign({isInstalled},item); }) ); @@ -53,8 +53,8 @@ export default class Extension { return this.getSimpleList().find(item => item.nam == extName)?.needX64Brew; } - static isInstalledX64Brew() { - return FileUtil.Exists('/usr/local/homebrew/bin/brew'); + static async isInstalledX64Brew() { + return await FileUtil.Exists('/usr/local/homebrew/bin/brew'); } static getSimpleListForWindows(){ diff --git a/src/main/core/php/extension/Installer.js b/src/main/core/php/extension/Installer.js index c168084c..fdcf2f46 100644 --- a/src/main/core/php/extension/Installer.js +++ b/src/main/core/php/extension/Installer.js @@ -3,7 +3,7 @@ import Path from '@/main/utils/Path' import GetPath from '@/shared/utils/GetPath' import child_process from 'child_process' import fs from 'fs' -import Directory from '@/main/utils/Directory' +import DirUtil from '@/main/utils/DirUtil' import fixPath from 'fix-path' import Extension from './Extension' import Php from '@/main/core/php/Php' @@ -24,24 +24,24 @@ export default class Installer { /** * - * @returns {string} command + * @returns {Promise} command */ - install() { + async install() { if (isMacOS) { fixPath(); } let commandStr; let phpExtDlDir = Path.Join(GetPath.getDownloadsDir(), 'phpExt'); - if(!Directory.Exists(phpExtDlDir)){ - Directory.CreateDirectory(phpExtDlDir); + if (!await DirUtil.Exists(phpExtDlDir)) { + await DirUtil.Create(phpExtDlDir); } let phpDir = GetPath.getPhpDir(this.phpVersion); const scriptPath = Extension.getInstallScriptPath(this.extName); if (isWindows) { let extFileName = Extension.getFileName(this.extName); - let phpExtDir = Php.getExtensionDir(this.phpVersion); + let phpExtDir = await Php.getExtensionDir(this.phpVersion); let dlFileName = this.getDownloadFileName(); commandStr = ` powershell.exe -ExecutionPolicy Bypass -File "${scriptPath}"`; commandStr += ` ${phpExtDlDir} ${phpDir} ${this.extVersion} ${this.extName} ${extFileName} ${phpExtDir} ${dlFileName}`; @@ -53,24 +53,20 @@ export default class Installer { let childProcess = child_process.exec(commandStr); childProcess.stderr.on('data', (data) => { - if (isDev) console.log('phpExt:stderr',data.toString()) - this.eventEmitter.emit('phpExt:stderr',data.toString()) + this.eventEmitter.emit('phpExt:stderr', data.toString()) }); childProcess.stdout.on('data', (data) => { - if(isDev) console.log('phpExt:stdout',data.toString()) - this.eventEmitter.emit('phpExt:stdout',data.toString()) + this.eventEmitter.emit('phpExt:stdout', data.toString()) }); - childProcess.on('exit', (code,signal) => { - this.eventEmitter.emit('phpExt:exit',code,signal) + childProcess.on('exit', (code, signal) => { + this.eventEmitter.emit('phpExt:exit', code, signal) }); this.eventEmitter.on('phpExt:stop', () => { childProcess.kill(); }) - - if (isDev) console.log("install command:\n", commandStr); return commandStr; } diff --git a/src/main/core/software/CommonInstall.js b/src/main/core/software/CommonInstall.js index 32a0b925..a1325b5c 100644 --- a/src/main/core/software/CommonInstall.js +++ b/src/main/core/software/CommonInstall.js @@ -1,14 +1,12 @@ import SoftwareExtend from "@/main/core/software/SoftwareExtend"; import SoftwareInit from "@/main/core/software/SoftwareInit"; -import Directory from "@/main/utils/Directory"; -import GetPath from "@/shared/utils/GetPath"; -import Database from "@/main/core/Database"; +import DirUtil from "@/main/utils/DirUtil"; import { extract7z, extractTar, extractZip } from '@/main/utils/extract' export default class CommonInstall { static async extract(filePath, dest) { - if (!Directory.Exists(dest)) { - Directory.CreateDirectory(dest); + if (!await DirUtil.Exists(dest)) { + await DirUtil.Create(dest); } if (filePath.endsWith('.zip')) { await extractZip(filePath, dest) @@ -21,16 +19,13 @@ export default class CommonInstall { static async configure(dirName) { if (dirName.match(/^mysql-[.\d]+$/)) { - let version = SoftwareExtend.getMysqlVersion(dirName); - await SoftwareInit.initMySQLConf(version); - if (!Directory.Exists(GetPath.getMysqlDataDir(version))) { - await Database.initMySQL(version); - } + const version = SoftwareExtend.getMysqlVersion(dirName) + await SoftwareInit.initMySQL(version) } else if (dirName.match(/^php-[.\d]+$/)) { - let version = SoftwareExtend.getPHPVersion(dirName); - await SoftwareInit.initPHP(version); + const version = SoftwareExtend.getPHPVersion(dirName) + await SoftwareInit.initPHP(version) } else if (dirName.match(/^nginx$/)) { - await SoftwareInit.initNginx(); + await SoftwareInit.initNginx() } } } diff --git a/src/main/core/software/Installer.js b/src/main/core/software/Installer.js index bcce75ec..31697b50 100644 --- a/src/main/core/software/Installer.js +++ b/src/main/core/software/Installer.js @@ -4,7 +4,7 @@ import path from 'path' import { EnumSoftwareInstallStatus } from '@/shared/utils/enum' import Software from '@/main/core/software/Software' import { DOWNLOAD_URL } from '@/shared/utils/constant' -import Directory from '@/main/utils/Directory' +import DirUtil from '@/main/utils/DirUtil' import got from 'got' import { pipeline } from 'stream/promises' import fs from 'fs' @@ -36,12 +36,12 @@ export default class Installer extends EventEmitter { } async install() { - if (!Directory.Exists(GetPath.getDownloadsDir())) { - Directory.CreateDirectory(GetPath.getDownloadsDir()); + if (!await DirUtil.Exists(GetPath.getDownloadsDir())) { + await DirUtil.Create(GetPath.getDownloadsDir()); } - if(FileUtil.Exists(this.tempFilePath)){ - FileUtil.Delete(this.tempFilePath); + if(await FileUtil.Exists(this.tempFilePath)){ + await FileUtil.Delete(this.tempFilePath); } try { @@ -95,7 +95,7 @@ export default class Installer extends EventEmitter { }); await pipeline(responseStream, writeStream,{signal: this.dlAbortController.signal}); - FileUtil.Move(this.tempFilePath, this.filePath); + await FileUtil.Move(this.tempFilePath, this.filePath); this.changeStatus(EnumSoftwareInstallStatus.Downloaded); } @@ -122,8 +122,8 @@ export default class Installer extends EventEmitter { */ static async uninstall(item) { let path = Software.getPath(item); - await Directory.Delete(path); - return !Directory.Exists(path); + await DirUtil.Delete(path); + return !await DirUtil.Exists(path); } getFileName() { diff --git a/src/main/core/software/LocalInstall.js b/src/main/core/software/LocalInstall.js index e2bd1e12..76c7d9f5 100644 --- a/src/main/core/software/LocalInstall.js +++ b/src/main/core/software/LocalInstall.js @@ -16,7 +16,9 @@ export default class LocalInstall { const dest = await this.getDestPath(dirName) if (!dest) return await CommonInstall.extract(filePath, dest) - if (deleteSrc) FileUtil.Delete(filePath) + if (deleteSrc){ + await FileUtil.Delete(filePath) + } await CommonInstall.configure(dirName) } diff --git a/src/main/core/software/Software.js b/src/main/core/software/Software.js index 3da48b74..db179813 100644 --- a/src/main/core/software/Software.js +++ b/src/main/core/software/Software.js @@ -2,14 +2,14 @@ import App from "@/main/App"; import path from "path"; import {EnumSoftwareType} from "@/shared/utils/enum"; import GetPath from "@/shared/utils/GetPath"; -import Directory from "@/main/utils/Directory"; +import DirUtil from "@/main/utils/DirUtil"; import FileUtil from "@/main/utils/FileUtil"; export default class Software { static #list; - static DirExists() { - return Directory.Exists(GetPath.getSoftwareDir()); + static async DirExists() { + return await DirUtil.Exists(GetPath.getSoftwareDir()); } /** @@ -32,8 +32,8 @@ export default class Software { let list try { - if (FileUtil.Exists(softConfigPath)) { - list = JSON.parse(FileUtil.ReadAllText(softConfigPath)) + if (await FileUtil.Exists(softConfigPath)) { + list = JSON.parse(await FileUtil.ReadAll(softConfigPath)) } else { list = [] } @@ -54,9 +54,9 @@ export default class Software { * @param item {SoftwareItem} * @returns {boolean} */ - static IsInstalled(item) { + static async IsInstalled(item) { let path = Software.getPath(item); - return Directory.Exists(path); + return await DirUtil.Exists(path); } /** diff --git a/src/main/core/software/SoftwareExtend.js b/src/main/core/software/SoftwareExtend.js index 06ad9a80..76b471fb 100644 --- a/src/main/core/software/SoftwareExtend.js +++ b/src/main/core/software/SoftwareExtend.js @@ -1,5 +1,5 @@ import GetPath from "@/shared/utils/GetPath"; -import Directory from "@/main/utils/Directory"; +import DirUtil from "@/main/utils/DirUtil"; import Path from "@/main/utils/Path"; import FileUtil from "@/main/utils/FileUtil"; @@ -11,13 +11,13 @@ export default class SoftwareExtend { */ static async getNginxRequirePhpList() { let nginxVhostsPath = GetPath.getNginxVhostsDir(); - let vhosts = Directory.GetFiles(nginxVhostsPath, '.conf'); + let vhosts = await DirUtil.GetFiles(nginxVhostsPath, '.conf'); if (!vhosts || vhosts.length === 0) { return []; } //获取所有网站PHP版本数组,并发读文件并匹配PHP版本 let phpVersionList = await Promise.all(vhosts.map(async confPath => { - let text = FileUtil.ReadAllText(confPath); + let text = await FileUtil.ReadAll(confPath); let matches = text.match(/php-(\S+?)\.conf/); return matches ? matches[1] : null; })); @@ -27,40 +27,31 @@ export default class SoftwareExtend { return phpVersionList; } - - /** - * - * @returns {*[]|{name: string, version: string}[]} - */ - static getPHPList() { + static async getPHPList() { let path = GetPath.getPhpTypeDir(); - if (!Directory.Exists(path)) { + if (!await DirUtil.Exists(path)) { return []; } - let list = Directory.GetDirectories(path, 'php-'); + let list = await DirUtil.GetDirectories(path, 'php-'); return list.map(path => { let name = Path.GetBaseName(path); let version = SoftwareExtend.getPHPVersion(name); - return {version, name}; + return { version, name }; }); } - /** - * - * @returns {*[]|{name: string, version: string}[]} - */ - static getMySQLList() { + static async getMySQLList() { let path = GetPath.getServerTypeDir(); - if (!Directory.Exists(path)) { + if (!await DirUtil.Exists(path)) { return []; } - let list = Directory.GetDirectories(path, 'mysql-'); + let list = await DirUtil.GetDirectories(path, 'mysql-'); return list.map(path => { let name = Path.GetBaseName(path); let version = SoftwareExtend.getMysqlVersion(name); - return {version, name}; + return { version, name }; }); } diff --git a/src/main/core/software/SoftwareInit.js b/src/main/core/software/SoftwareInit.js index 48ac9611..6f197993 100644 --- a/src/main/core/software/SoftwareInit.js +++ b/src/main/core/software/SoftwareInit.js @@ -2,7 +2,7 @@ import GetPath from "@/shared/utils/GetPath"; import FileUtil from "@/main/utils/FileUtil"; import Path from "@/main/utils/Path"; import SoftwareExtend from "@/main/core/software/SoftwareExtend"; -import Directory from "@/main/utils/Directory"; +import DirUtil from "@/main/utils/DirUtil"; import Php from "@/main/core/php/Php"; import Database from "@/main/core/Database"; import {isWindows } from '@/main/utils/utils' @@ -14,19 +14,18 @@ export default class SoftwareInit{ this.initAllPHP(), this.initAllMySQL() ]); - await this.initMySQL(); } static async initNginx() { try { let path = Path.Join(GetPath.getNginxConfDir(), 'nginx.conf'); - let text = FileUtil.ReadAllText(path); + let text = await FileUtil.ReadAll(path); let pattern = /root.+/g; let wwwPath = Path.Join(GetPath.getNginxDir(), 'html').replaceSlash(); let replaceStr = `root ${wwwPath};`; text = text.replaceAll(pattern, replaceStr); - FileUtil.WriteAllText(path, text); + await FileUtil.WriteAll(path, text); await this.initNginxLocalhostConf(); await this.initNginxPhpmyadminConf(); @@ -37,31 +36,30 @@ export default class SoftwareInit{ static async initNginxLocalhostConf() { let path = Path.Join(GetPath.getNginxVhostsDir(), 'localhost_80.conf'); - if (FileUtil.Exists(path)) { - let text = FileUtil.ReadAllText(path); + if (await FileUtil.Exists(path)) { + let text = await FileUtil.ReadAll(path); let pattern = /root.+/g; let rootPath = Path.Join(GetPath.getWebsiteDir(), 'localhost').replaceSlash(); let replaceStr = `root ${rootPath};`; text = text.replaceAll(pattern, replaceStr); - FileUtil.WriteAllText(path, text); + await FileUtil.WriteAll(path, text); } } static async initNginxPhpmyadminConf() { let path = Path.Join(GetPath.getNginxVhostsDir(), 'localhost_888.conf'); - if (FileUtil.Exists(path)) { - let text = FileUtil.ReadAllText(path); + if (await FileUtil.Exists(path)) { + let text = await FileUtil.ReadAll(path); let pattern = /root.+/g; let rootPath = Path.Join(GetPath.getToolTypeDir(), 'phpMyAdmin').replaceSlash(); let replaceStr = `root ${rootPath};`; text = text.replaceAll(pattern, replaceStr); - FileUtil.WriteAllText(path, text); + await FileUtil.WriteAll(path, text); } } static async initAllPHP() { - let phpList = SoftwareExtend.getPHPList() - + const phpList = await SoftwareExtend.getPHPList() for (const item of phpList) { await this.initPHP(item.version); } @@ -77,8 +75,8 @@ export default class SoftwareInit{ static async createPHPFpmConf(version) { let phpDirPath = GetPath.getPhpDir(version); let confPath = Path.Join(phpDirPath, 'etc/php-fpm.conf') - if (!FileUtil.Exists(confPath)) { - FileUtil.WriteAllText(confPath, Php.getFpmConfText(version)) + if (!await FileUtil.Exists(confPath)) { + await FileUtil.WriteAll(confPath, Php.getFpmConfText(version)) } } @@ -88,11 +86,11 @@ export default class SoftwareInit{ let confDirPath = isWindows ? phpDirPath : Path.Join(phpDirPath, 'etc'); let confPath = Path.Join(confDirPath, 'php.ini'); - if (!FileUtil.Exists(confPath)) { - FileUtil.Copy(Path.Join(confDirPath, 'php.ini-development'), confPath); + if (!await FileUtil.Exists(confPath)) { + await FileUtil.Copy(Path.Join(confDirPath, 'php.ini-development'), confPath); } - let text = FileUtil.ReadAllText(confPath); + let text = await FileUtil.ReadAll(confPath); text = text.replace(/(?<=\n);?.?max_execution_time\s*=.*/, 'max_execution_time = 300'); text = text.replace(/(?<=\n);?.?memory_limit\s*=.*/, 'memory_limit = 512M'); @@ -117,7 +115,7 @@ export default class SoftwareInit{ } } else { //非Windows系统 - let extDir = Php.getExtensionDir(version) + let extDir = await Php.getExtensionDir(version) //仅替换第一个 text = text.replace(/(?<=\n);?.?extension_dir\s*=.*/, `extension_dir = "${extDir}"`); } @@ -131,17 +129,29 @@ export default class SoftwareInit{ let replaceSessionStr = `session.save_path = "${phpTempPath.replaceSlash()}"`; text = text.replaceAll(sessionPattern, replaceSessionStr); - FileUtil.WriteAllText(confPath, text); + await FileUtil.WriteAll(confPath, text); } catch (error) { throw new Error(`初始化PHP配置失败!${error.message}`); } } static async initAllMySQL() { - let mysqlList = SoftwareExtend.getMySQLList(); - + const mysqlList = await SoftwareExtend.getMySQLList(); for (const item of mysqlList) { - await this.initMySQLConf(item.version); + await this.initMySQL(item.version); + } + } + + /** + * 初始化MySQL data目录和重置密码 + * @returns {Promise} + */ + static async initMySQL(version) { + await this.initMySQLConf(version) + if (!await DirUtil.Exists(GetPath.getMysqlDataDir(version))) { + //如果mysql data目录不存在,初始化生成data目录,并重置密码 + await Database.initMySQLData(version) + await Database.resetMySQLPassword(version) } } @@ -149,7 +159,7 @@ export default class SoftwareInit{ try { let mysqlDir = GetPath.getMysqlDir(version); let confPath = isWindows ? Path.Join(mysqlDir, 'my.ini') : Path.Join(mysqlDir, 'my.cnf'); - let text = FileUtil.ReadAllText(confPath); + let text = await FileUtil.ReadAll(confPath); let mysqlPath = GetPath.getMysqlDir(version); //(?<=\n)basedir\s*=\s*.+ @@ -169,25 +179,11 @@ export default class SoftwareInit{ let replaceLogStr = `log-error = "${logPath.replaceSlash()}"`; text = text.replaceAll(logPattern, replaceLogStr); - FileUtil.WriteAllText(confPath, text); + await FileUtil.WriteAll(confPath, text); } catch (error) { throw new Error(`初始化MySQL配置失败!${error.message}`); } } - /** - * 初始化MySQL data目录和重置密码,todo:和initMySQLConf合一个方法 - * @returns {Promise} - */ - static async initMySQL() { - let mysqlList = SoftwareExtend.getMySQLList(); - for (const item of mysqlList) { - let version = item.version; - if (!Directory.Exists(GetPath.getMysqlDataDir(version))) { - //如果mysql data目录不存在,初始化生成data目录,并重置密码 - await Database.initMySQL(version); - } - } - } } diff --git a/src/main/core/website/NginxWebsite.js b/src/main/core/website/NginxWebsite.js index 53d59863..9aedf9dd 100644 --- a/src/main/core/website/NginxWebsite.js +++ b/src/main/core/website/NginxWebsite.js @@ -21,10 +21,13 @@ export default class NginxWebsite { * @param confName 配置文件名,带扩展名 */ constructor(confName) { - this.confName = confName; - this.serverName = Path.GetFileNameWithoutExtension(confName).split('_')[0]; - this.confPath = Nginx.getWebsiteConfPath(confName); - this.confText = FileUtil.ReadAllText(this.confPath); + this.confName = confName + } + + async init() { + this.serverName = Path.GetFileNameWithoutExtension(this.confName).split('_')[0] + this.confPath = Nginx.getWebsiteConfPath(this.confName) + this.confText = await FileUtil.ReadAll(this.confPath) } getBasicInfo() { @@ -47,9 +50,9 @@ export default class NginxWebsite { return allServerName[1] ?? null } - static getRewrite(confName) { + static async getRewrite(confName) { let rewritePath = Nginx.getWebsiteRewriteConfPath(confName); - return FileUtil.ReadAllText(rewritePath); + return await FileUtil.ReadAll(rewritePath); } getPort() { @@ -101,12 +104,12 @@ export default class NginxWebsite { this.confText = text; this.setPHPVersion(websiteInfo.phpVersion); this.setExtraInfo({ syncHosts: websiteInfo.syncHosts, note: websiteInfo.note }); - FileUtil.WriteAllText(this.confPath, this.confText); + await FileUtil.WriteAll(this.confPath, this.confText); } - static saveRewrite(confName, content) { + static async saveRewrite(confName, content) { let rewritePath = Nginx.getWebsiteRewriteConfPath(confName); - FileUtil.WriteAllText(rewritePath, content); + await FileUtil.WriteAll(rewritePath, content); } /** @@ -131,7 +134,7 @@ export default class NginxWebsite { this.confText = this.confText.replace(/(?<=#EXTRA_INFO_START[\s\S]{0,9}#).*(?=[\s\S]{0,9}#EXTRA_INFO_END)/, extraStr); } - save() { - FileUtil.WriteAllText(this.confPath, this.confText); + async save() { + await FileUtil.WriteAll(this.confPath, this.confText); } } diff --git a/src/main/core/website/Website.js b/src/main/core/website/Website.js index 651271f8..23ec4aa5 100644 --- a/src/main/core/website/Website.js +++ b/src/main/core/website/Website.js @@ -1,7 +1,7 @@ import Nginx from "@/main/core/Nginx"; import NginxWebsite from "@/main/core/website/NginxWebsite"; import FileUtil from "@/main/utils/FileUtil"; -import Directory from "@/main/utils/Directory"; +import DirUtil from "@/main/utils/DirUtil"; export default class Website { /** @@ -13,31 +13,28 @@ export default class Website { throw new Error(`${websiteInfo.serverName}:${websiteInfo.port}\n已经存在,不能重复!`) } - if (!FileUtil.Exists(websiteInfo.rootPath)) { - try { - Directory.CreateDirectory(websiteInfo.rootPath) - } catch { - throw new Error('创建根目录失败!'); - } + if (!await FileUtil.Exists(websiteInfo.rootPath)) { + await DirUtil.Create(websiteInfo.rootPath) } - Nginx.addWebsite(websiteInfo); + await Nginx.addWebsite(websiteInfo); } - static delete(confName) { - Nginx.delWebsite(confName); + static async delete(confName) { + await Nginx.delWebsite(confName); } static async getList(search) { return await Nginx.getWebsiteList(search); } - static getBasicInfo(confName) { - let webSite = new NginxWebsite(confName); - return webSite.getBasicInfo(); + static async getBasicInfo(confName) { + const website = new NginxWebsite(confName); + await website.init() + return website.getBasicInfo(); } - static getRewrite(confName) { - return NginxWebsite.getRewrite(confName); + static async getRewrite(confName) { + return await NginxWebsite.getRewrite(confName); } static getConfPath(confName) { @@ -52,22 +49,22 @@ export default class Website { * 获取URL重写规则列表 * @returns {Promise} */ - static getRewriteRuleList() { - return Nginx.getRewriteRuleList(); + static async getRewriteRuleList() { + return await Nginx.getRewriteRuleList(); } - static getRewriteByRule(ruleName) { - return Nginx.getRewriteByRule(ruleName); + static async getRewriteByRule(ruleName) { + return await Nginx.getRewriteByRule(ruleName); } static async saveBasicInfo(confName, websiteInfo) { - let webSite = new NginxWebsite(confName); - await webSite.setBasicInfo(websiteInfo); - webSite.save(); + const website = new NginxWebsite(confName); + await website.init() + await website.setBasicInfo(websiteInfo); + await website.save(); } - static saveRewrite(confName, content) { - NginxWebsite.saveRewrite(confName, content); + static async saveRewrite(confName, content) { + await NginxWebsite.saveRewrite(confName, content); } - } diff --git a/src/main/utils/DirUtil.js b/src/main/utils/DirUtil.js new file mode 100644 index 00000000..06d88b41 --- /dev/null +++ b/src/main/utils/DirUtil.js @@ -0,0 +1,91 @@ +import fsPromises from 'fs/promises' +import nodePath from 'path' +import FsUtil from '@/main/utils/FsUtil' + +const FileTypeEnum = { + File: 0, + Directory: 1 +} +export default class DirUtil { + /** + * 创建目录和子目录 + * @param path {string} + * @param options + * @returns {Promise} + */ + static async Create(path, options = { recursive: true }) { + return await fsPromises.mkdir(path, options) + } + + static async Delete(path, options = { recursive: true, force: true }) { + return await FsUtil.Remove(path, options) + } + + /** + * 判断目录是否存在 + * @param path {string} + * @returns {Promise} + */ + static async Exists(path) { + return await FsUtil.Exists(path) + } + + /** + * 获取指定目录中的所有目录路径或包含对象 + * @param path {string} + * @param filter {string|RegExp} + * @param withStats {boolean} + * @returns {Promise} + */ + static async GetDirectories(path, filter = null, withStats = false) { + return await this.GetAll(path, FileTypeEnum.Directory, filter, withStats) + } + + /** + * 获取指定目录中的所有文件路径或包含对象 + * @param path {string} + * @param filter {string|RegExp} + * @param withStats {boolean} + * @returns {Promise} + */ + static async GetFiles(path, filter = null, withStats = false) { + return await this.GetAll(path, FileTypeEnum.File, filter, withStats) + } + + /** + * @param path {string} + * @param fileType {FileTypeEnum} + * @param filter {string|RegExp} + * @param withStats {boolean} true时,返回的数组将包含对象 + * @returns {Promise} + */ + static async GetAll(path, fileType = '', filter = null, withStats = false) { + let direntArr = await fsPromises.readdir(path, { withFileTypes: true }) + let list = direntArr.filter((dirent) => { + if (fileType === FileTypeEnum.File && !dirent.isFile()) { + return false + } else if (fileType === FileTypeEnum.Directory && !dirent.isDirectory()) { + return false + } + + if (filter) { + if (filter instanceof RegExp) { + if (!filter.test(dirent.name)) return false + } else { + if (!dirent.name.includes(filter)) return false + } + } + return true + }) + + const mapFn = async (dirent) => { + const itemPath = nodePath.join(path, dirent.name) + if (withStats) { + const stats = await fsPromises.lstat(itemPath) + return { path: itemPath, stats } + } + return itemPath + } + return await Promise.all(list.map(mapFn)) + } +} diff --git a/src/main/utils/Directory.js b/src/main/utils/Directory.js deleted file mode 100644 index 3a02fd3a..00000000 --- a/src/main/utils/Directory.js +++ /dev/null @@ -1,120 +0,0 @@ -import fs from 'fs' -import fsPromises from 'fs/promises' -import nodePath from 'path' - -const FileTypeEnum = { - File: 0, - Directory: 1 -} -export default class Directory { - /** - * 创建目录和子目录 - * @param path {string} - * @returns {string|undefined} - */ - static CreateDirectory(path) { - const options = { - recursive: true - } - return fs.mkdirSync(path, options) - } - - /** - * 创建目录符号链接 - * @param path {string} - * @param pathToTarget {string} - * @returns {undefined} - */ - static CreateSymbolicLink(path, pathToTarget) { - return fs.symlinkSync(pathToTarget, path) - } - - /** - * 删除目录 - * @param path {string} - * @param options {object} - * @returns {Promise} - */ - static async Delete(path, options = { recursive: true, force: true }) { - return await fsPromises.rm(path, options) - } - - /** - * 判断目录是否存在 - * @param path {string} - * @returns {boolean} - */ - static Exists(path) { - return fs.existsSync(path) && fs.lstatSync(path).isDirectory() - } - - /** - * 将现有目录移动到新目录 - * @param source {string} - * @param dest {string} - * @returns {undefined} - */ - static Move(source, dest) { - return fs.renameSync(source, dest) - } - - /** - * 将现有目录复制到新目录 - * @param source {string} - * @param dest {string} - * @param options {object} - * @returns {void} - */ - static Copy(source, dest, options) { - return fs.cpSync(source, dest, options) - } - - /** - * 获取指定目录中的所有目录名(包含其路径) - * @param path {string} - * @param search {string|RegExp} - * @returns {string[]} - */ - static GetDirectories(path, search = null) { - return this.GetAll(path, FileTypeEnum.Directory, search) - } - - /** - * 获取指定目录中的所有文件名(包含其路径) - * @param path {string} - * @param search {string|RegExp} - * @returns {string[]} - */ - static GetFiles(path, search = null) { - return this.GetAll(path, FileTypeEnum.File, search) - } - - /** - * 获取指定目录中的所有文件名(包含其路径) - * @param path {string} - * @param fileType {FileTypeEnum} - * @param search {string|RegExp} - * @returns {string[]} - */ - static GetAll(path, fileType = '', search = null) { - let dirents = fs.readdirSync(path, { withFileTypes: true }) - let list = [] - for (const dirent of dirents) { - if (fileType === FileTypeEnum.File && !dirent.isFile()) { - continue - } else if (fileType === FileTypeEnum.Directory && !dirent.isDirectory()) { - continue - } - - if (search) { - if (search instanceof RegExp) { - if (dirent.name.search(search) === -1) continue - } else { - if (!dirent.name.includes(search)) continue - } - } - list.push(nodePath.join(path, dirent.name)) - } - return list - } -} diff --git a/src/main/utils/DirectoryInfo.js b/src/main/utils/DirectoryInfo.js deleted file mode 100644 index e69de29b..00000000 diff --git a/src/main/utils/FileUtil.js b/src/main/utils/FileUtil.js index 27a092ce..94bf8633 100644 --- a/src/main/utils/FileUtil.js +++ b/src/main/utils/FileUtil.js @@ -1,7 +1,8 @@ import fs from 'fs' import fsPromises from 'fs/promises' -export default class FileUtil { +import FsUtil from '@/main/utils/FsUtil' +export default class FileUtil { /** * 创建文件符号链接 * @param path {string} 符号链接的路径 @@ -12,74 +13,62 @@ export default class FileUtil { return fs.symlinkSync(pathToTarget, path); } - /** - * 删除文件 - * @param path {string} - * @returns {undefined} - */ - static Delete(path) { - return fs.rmSync(path); + static async Delete(path, options = { force: true }) { + return await FsUtil.Remove(path, options) } /** * 判断文件是否存在 * @param path {string} - * @returns {boolean} + * @returns {Promise} */ - static Exists(path) { - return fs.existsSync(path) && !fs.lstatSync(path).isDirectory(); + static async Exists(path) { + return await FsUtil.Exists(path) } /** * 将文件移动到新位置,如果文件存在,则覆盖 - * @param sourcePath {string} - * @param destPath {string} - * @returns {boolean} + * @param oldPath {string} + * @param newPath {string} + * @returns {Promise} */ - static Move(sourcePath, destPath) { - return fs.renameSync(sourcePath, destPath); + static async Move(oldPath, newPath) { + return await FsUtil.Rename(oldPath, newPath) } - /** - * 将现有文件复制到新文件 - * @param source {string} - * @param dest {string} - * @param options {object} - * @returns {void} - */ - static Copy(source, dest, options={}) { - return fs.cpSync(source, dest, options); + static async Copy(source, dest, options = { force: true }) { + return await FsUtil.Copy(source, dest, options) } /** * 读取文件的全部内容 * @param path {string} * @param encoding {string|null} - * @returns {string|Buffer} + * @returns {Promise} */ - static ReadAllText(path, encoding = 'utf8') { - return fs.readFileSync(path, {encoding: encoding}); + static async ReadAll(path, encoding = 'utf8') { + return await fsPromises.readFile(path, { encoding }) } /** - * 创建一个新文件,将字符串写入该文件,如果文件已经存在,则会覆盖该文件。 + * 创建一个新文件,将数据写入该文件,如果文件已经存在,则会覆盖该文件。 * @param path {string} - * @param contents {string} + * @param data * @param encoding {string|null} - * @returns {undefined} + * @returns {Promise} */ - static WriteAllText(path, contents, encoding = 'utf8') { - return fs.writeFileSync(path, contents, {encoding: encoding}); + static async WriteAll(path, data, encoding = 'utf8') { + return await fsPromises.writeFile(path, data, { encoding: encoding }); } /** - * 将字符串追加到文件,如果文件不存在,则会创建该文件。 + * 将数据追加到文件,如果文件不存在,则会创建该文件。 * @param path {string} - * @param contents {string} + * @param data * @param options * @returns {Promise} */ - static async AppendAllText(path, contents, options = { encoding: 'utf8' }) { - return await fsPromises.appendFile(path, contents, options) + static async Append(path, data, options = { encoding: 'utf8' }) { + return await fsPromises.appendFile(path, data, options) } } diff --git a/src/main/utils/FsUtil.js b/src/main/utils/FsUtil.js index 6bb9da49..974190be 100644 --- a/src/main/utils/FsUtil.js +++ b/src/main/utils/FsUtil.js @@ -10,13 +10,25 @@ export default class FsUtil { */ static async Exists(path) { try { - await fsPromises.access(path, constants.F_OK) + await fsPromises.access(path) return true } catch { return false } } + static async Copy(source, dest, options = {}) { + return await fsPromises.cp(source, dest, options) + } + + static async Rename(oldPath, newPath) { + return await fsPromises.rename(oldPath, newPath) + } + + static async Remove(path, options = {}) { + return await fsPromises.rm(path, options) + } + /** * * @param path {string} diff --git a/src/main/utils/Hosts.js b/src/main/utils/Hosts.js index e6d14e62..c3e3ba4a 100644 --- a/src/main/utils/Hosts.js +++ b/src/main/utils/Hosts.js @@ -10,7 +10,7 @@ export default class Hosts { */ static async add(domain) { let path = GetPath.getHostsPath(); - let text = FileUtil.ReadAllText(path); + let text = await FileUtil.ReadAll(path); let domainRegx = this.getDomainRegExp(domain); if (text.match(domainRegx)) { @@ -22,10 +22,10 @@ export default class Hosts { appendText += `127.0.0.1 ${domain}${EOL}`; - if (FileUtil.Exists(path) && !await FsUtil.CanReadWrite(path)) { + if (await FileUtil.Exists(path) && !await FsUtil.CanReadWrite(path)) { await FsUtil.ChmodReadWrite(path) } - await FileUtil.AppendAllText(path, appendText); + await FileUtil.Append(path, appendText); } /** @@ -34,16 +34,16 @@ export default class Hosts { */ static async delete(domain) { let path = GetPath.getHostsPath(); - if (!FileUtil.Exists(path)) { + if (!await FileUtil.Exists(path)) { return; } if (!await FsUtil.CanReadWrite(path)) { await FsUtil.ChmodReadWrite(path) } - let text = FileUtil.ReadAllText(path); + let text = await FileUtil.ReadAll(path); let domainRegx = this.getDomainRegExp(domain); text = text.replaceAll(domainRegx, ''); - FileUtil.WriteAllText(path, text); + await FileUtil.WriteAll(path, text); } static getDomainRegExp(domain) { diff --git a/src/main/utils/Native.js b/src/main/utils/Native.js index e573efc2..7b1f6fe3 100644 --- a/src/main/utils/Native.js +++ b/src/main/utils/Native.js @@ -36,7 +36,7 @@ export default class Native { fixPath() //mac下修复环境变量不识别的问题 } try { - if (!FileUtil.Exists(filePath)) { + if (!await FileUtil.Exists(filePath)) { throw new Error(`${filePath} 文件不存在`) } @@ -85,7 +85,7 @@ export default class Native { static async openHosts() { let path = GetPath.getHostsPath() - if (FileUtil.Exists(path) && !await FsUtil.CanReadWrite(path)) { + if (await FileUtil.Exists(path) && !await FsUtil.CanReadWrite(path)) { await FsUtil.ChmodReadWrite(path) } await Native.openTextFile(path) diff --git a/src/renderer/App.vue b/src/renderer/App.vue index 89b773bf..2a3f9286 100644 --- a/src/renderer/App.vue +++ b/src/renderer/App.vue @@ -31,7 +31,7 @@ import UserPwdModal from "@/renderer/components/UserPwdModal.vue"; import Software from "@/main/core/software/Software"; import Service from "@/main/utils/Service"; import {message} from "ant-design-vue"; -import Directory from "@/main/utils/Directory"; +import DirUtil from "@/main/utils/DirUtil"; import {MAC_USER_CORE_DIR} from "@/main/utils/constant"; import ConfigProvider from "@/renderer/components/Theme/ConfigProvider.vue"; import TrayManage from '@/main/TrayManage' @@ -52,7 +52,7 @@ provide('GlobalProvide', { serverReactive }); (async () => { try { - if (App.initFileExists() && !isDev) { + if (await App.initFileExists() && !isDev) { await initOrUpdate() } @@ -74,7 +74,7 @@ provide('GlobalProvide', { serverReactive }); async function initOrUpdate() { //存在initFile文件的情况下,判断是第一次安装,还是覆盖安装 - if (!Software.DirExists()) { //目录不存在说明是第一次安装 + if (!await Software.DirExists()) { //目录不存在说明是第一次安装 if (isMacOS) { //调用设置(electron-store)会自动创建USER_CORE_DIR,为了捕捉创建失败的错误,先提前写好创建文件夹的代码。 await macCreateUserCoreDir() @@ -111,8 +111,8 @@ async function winInit() { async function macCreateUserCoreDir() { try { - if (!Directory.Exists(MAC_USER_CORE_DIR)) { - Directory.CreateDirectory(MAC_USER_CORE_DIR); + if (!await DirUtil.Exists(MAC_USER_CORE_DIR)) { + await DirUtil.Create(MAC_USER_CORE_DIR); } } catch (error) { await MessageBox.error(error.message ?? error, t('errorOccurredDuring', [t('initializing')])); @@ -124,7 +124,7 @@ async function update() { try { store.loading = true; await App.update(); - App.deleteInitFile(); + await App.deleteInitFile(); store.loading = false; } catch (error) { await MessageBox.error(error.message ?? error, t('errorOccurredDuring', [t('update')])); diff --git a/src/renderer/components/Settings/EnvVar.vue b/src/renderer/components/Settings/EnvVar.vue index 83984856..6449e9f5 100644 --- a/src/renderer/components/Settings/EnvVar.vue +++ b/src/renderer/components/Settings/EnvVar.vue @@ -27,6 +27,7 @@