Skip to content

Commit

Permalink
细节优化
Browse files Browse the repository at this point in the history
  • Loading branch information
TimeRainStarSky committed May 18, 2024
1 parent fbe5849 commit 21eea14
Show file tree
Hide file tree
Showing 4 changed files with 78 additions and 73 deletions.
24 changes: 14 additions & 10 deletions lib/bot.js
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,11 @@ export default class Yunzai extends EventEmitter {
return String(data)
}

StringOrBuffer(data, base64) {
const string = String(data)
return string.includes("\ufffd") ? (base64 ? `base64://${data.toString("base64")}` : data) : string
}

getCircularReplacer() {
const _this_ = this, ancestors = []
return function (key, value) {
Expand All @@ -261,9 +266,7 @@ export default class Yunzai extends EventEmitter {
if (value instanceof Error)
return value.stack
if (value.type == "Buffer" && Array.isArray(value.data)) try {
const buffer = Buffer.from(value)
const string = String(buffer)
return string.includes("\ufffd") ? `base64://${buffer.toString("base64")}` : string
return _this_.StringOrBuffer(Buffer.from(value), true)
} catch {}
break
default:
Expand All @@ -287,10 +290,8 @@ export default class Yunzai extends EventEmitter {
case "object":
if (data instanceof Error)
return data.stack
if (Buffer.isBuffer(data)) {
const string = String(data)
return string.includes("\ufffd") ? `base64://${data.toString("base64")}` : string
}
if (Buffer.isBuffer(data))
return this.StringOrBuffer(data, true)
}

try {
Expand Down Expand Up @@ -397,10 +398,13 @@ export default class Yunzai extends EventEmitter {
return new Promise(resolve => {
if (!opts.quiet) this.makeLog("mark", `${logger.cyan(cmd)}`, "执行命令")
const start_time = Date.now()
exec(cmd, opts, (error, stdout, stderr) => {
resolve({ error, stdout, stderr })
exec(cmd, { encoding: "buffer", ...opts }, (error, stdout, stderr) => {
const raw = { stdout, stderr }
stdout = String(stdout).trim()
stderr = String(stderr).trim()
resolve({ error, stdout, stderr, raw })
if (opts.quiet) return
this.makeLog("mark", `${logger.cyan(cmd)} ${logger.green(`[完成${this.getTimeDiff(start_time)}]`)} ${stdout?`\n${this.String(stdout).trim()}`:""}${stderr?logger.red(`\n${this.String(stderr).trim()}`):""}`, "执行命令")
this.makeLog("mark", `${logger.cyan(cmd)} ${logger.green(`[完成${this.getTimeDiff(start_time)}]`)} ${stdout?`\n${stdout}`:""}${stderr?logger.red(`\n${stderr}`):""}`, "执行命令")
if (error) this.makeLog("error", error, "执行命令")
})
})
Expand Down
39 changes: 16 additions & 23 deletions plugins/other/install.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,47 +74,40 @@ export class install extends plugin {
await this.reply(`${name} 插件已安装`)
return false
}
await this.runInstall(name, list[name], path)
this.restart()
return this.runInstall(name, list[name], path)
}

async runInstall(name, url, path) {
logger.mark(`${this.e.logFnc} 开始安装 ${name} 插件`)
await this.reply(`开始安装 ${name} 插件`)

const cm = `git clone --depth 1 --single-branch "${url}" "${path}"`
insing = true
const ret = await Bot.exec(cm)
const ret = await Bot.exec(`git clone --depth 1 --single-branch "${url}" "${path}"`)
if (await Bot.fsStat(`${path}/package.json`))
await Bot.exec("pnpm install")
await Bot.exec("pnpm install --force")
insing = false

if (ret.error) {
logger.mark(`${this.e.logFnc} 插件安装失败 ${name}`)
this.gitErr(ret.error, ret.stdout)
logger.mark(`${this.e.logFnc} ${name} 插件安装错误`)
this.gitErr(name, Bot.String(ret.error).trim(), ret.stdout)
return false
}
return this.restart()
}

async gitErr(err, stdout) {
let msg = "安装失败!"
let errMsg = err.toString()
stdout = stdout.toString()

if (errMsg.includes('Timed out')) {
const remote = errMsg.match(/'(.+?)'/g)[0].replace(/'/g, '')
return this.reply(`${msg}\n连接超时:${remote}`)
}

if (/Failed to connect|unable to access/g.test(errMsg)) {
const remote = errMsg.match(/'(.+?)'/g)[0].replace(/'/g, '')
return this.reply(`${msg}\n连接失败:${remote}`)
}
gitErrUrl(error) {
return error.replace(/(Cloning into|正克隆到)\s*'.+?'/g, "").match(/'(.+?)'/g)[0].replace(/'(.+?)'/, "$1")
}

await this.reply([errMsg, stdout])
async gitErr(name, error, stdout) {
if (/unable to access|无法访问/.test(error))
await this.reply(`远程仓库连接错误:${this.gitErrUrl(error)}`)
else if (/not found|未找到|does not (exist|appear)|不存在|Authentication failed|鉴权失败/.test(error))
await this.reply(`远程仓库地址错误:${this.gitErrUrl(error)}`)
else await this.reply(`${name} 插件安装错误\n${error}\n${stdout}`)
}

restart() {
new Restart(this.e).restart()
return new Restart(this.e).restart()
}
}
2 changes: 1 addition & 1 deletion plugins/other/sendLog.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export class sendLog extends plugin {
}

async getLog(logFile) {
let log = await fs.readFile(logFile, "utf-8")
let log = await fs.readFile(logFile, "utf8")
log = log.split("\n")

if (this.keyWord) {
Expand Down
86 changes: 47 additions & 39 deletions plugins/other/update.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import cfg from "../../lib/config/config.js"
import lodash from "lodash"
import fs from "node:fs/promises"
import { Restart } from "./restart.js"

Expand Down Expand Up @@ -74,7 +73,7 @@ export class update extends plugin {
await this.runUpdate(plugin)

if (this.isPkgUp)
await this.exec("pnpm install")
await this.exec("pnpm install --force")
if (this.isUp)
this.restart()
uping = false
Expand All @@ -97,7 +96,7 @@ export class update extends plugin {

if (this.e.msg.includes("强制")) {
type = "强制更新"
cm = `git reset --hard ${await this.getRemoteBranch(plugin)} && git pull --rebase`
cm = `git reset --hard ${await this.getRemoteBranch(true, plugin)} && git pull --rebase`
}
this.oldCommitId = await this.getCommitId(plugin)

Expand All @@ -106,8 +105,7 @@ export class update extends plugin {
await this.reply(`开始${type} ${this.typeName}`)
const ret = await this.exec(cm, plugin)

ret.stdout = lodash.trim(String(ret.stdout))
if (ret.error && !await this.gitErr(plugin, ret.stdout, lodash.trim(Bot.String(ret.error)))) {
if (ret.error && !await this.gitErr(plugin, ret.stdout, Bot.String(ret.error).trim())) {
logger.mark(`${this.e.logFnc} 更新失败 ${this.typeName}`)
return false
}
Expand All @@ -128,39 +126,55 @@ export class update extends plugin {
return true
}

async getCommitId(plugin) {
const cm = await this.exec("git rev-parse --short HEAD", plugin)
return lodash.trim(String(cm.stdout))
async getCommitId(...args) {
return (await this.exec("git rev-parse --short HEAD", ...args)).stdout
}

async getTime(plugin) {
const cm = await this.exec('git log -1 --pretty=%cd --date=format:"%F %T"', plugin)
return lodash.trim(String(cm.stdout))
async getTime(...args) {
return (await this.exec('git log -1 --pretty=%cd --date=format:"%F %T"', ...args)).stdout
}

async getBranch(plugin) {
const cm = await this.exec("git branch --show-current", plugin)
return lodash.trim(String(cm.stdout))
async getBranch(...args) {
return (await this.exec("git branch --show-current", ...args)).stdout
}

async getRemote(branch, plugin) {
const cm = await this.exec(`git config branch.${branch}.remote`, plugin)
return lodash.trim(String(cm.stdout))
async getRemote(branch, ...args) {
return (await this.exec(`git config branch.${branch}.remote`, ...args)).stdout
}

async getRemoteBranch(plugin) {
const branch = await this.getBranch(plugin)
if (!branch) return ""
const remote = await this.getRemote(branch, plugin)
if (!remote) return ""
return `${remote}/${branch}`
async getRemoteBranch(string, ...args) {
const branch = await this.getBranch(...args)
if (!branch && string) return ""
const remote = await this.getRemote(branch, ...args)
if (!remote && string) return ""
return string ? `${remote}/${branch}` : { remote, branch }
}

async getRemoteUrl(branch, hide, ...args) {
if (branch) {
const url = (await this.exec(`git config remote.${branch}.url`, ...args)).stdout
return hide ? url.replace(/\/\/([^@]+)@/, "//") : url
}

const ret = await this.exec("git config -l", ...args)
const urls = {}
for (const i of ret.stdout.match(/remote\..*?\.url=.+/g) || []) {
const branch = i.replace(/remote\.(.*?)\.url=.+/g, "$1")
const url = i.replace(/remote\..*?\.url=/g, "")
urls[branch] = (hide ? url.replace(/\/\/([^@]+)@/, "//") : url)
}
return urls
}

gitErrUrl(error) {
return error.match(/'(.+?)'/g)[0].replace(/'(.+?)'/, "$1")
}

async gitErr(plugin, stdout, error) {
if (/unable to access|无法访问/.test(error))
await this.reply(`远程仓库连接错误:${error.match(/'(.+?)'/g)[0].replace(/'(.+?)'/, "$1")}`)
else if (/Authentication failed|鉴权失败|not found|未找到/.test(error))
await this.reply(`远程仓库地址错误:${error.match(/'(.+?)'/g)[0].replace(/'(.+?)'/, "$1")}`)
await this.reply(`远程仓库连接错误:${this.gitErrUrl(error)}`)
else if (/not found|未找到|does not (exist|appear)|不存在|Authentication failed|鉴权失败/.test(error))
await this.reply(`远程仓库地址错误:${this.gitErrUrl(error)}`)
else if (/be overwritten by merge|被合并操作覆盖/.test(error) || /Merge conflict|合并冲突/.test(stdout))
await this.reply(`${error}\n${stdout}\n若修改过文件请手动更新,否则发送 #强制更新${plugin}`)
else if (/divergent branches|偏离的分支/.test(error)) {
Expand All @@ -186,7 +200,7 @@ export class update extends plugin {
}

if (this.isPkgUp)
await Bot.exec("pnpm install")
await Bot.exec("pnpm install --force")
if (this.isUp)
this.restart()
uping = false
Expand All @@ -198,9 +212,9 @@ export class update extends plugin {

async getLog(plugin = "") {
let cm = await this.exec('git log -100 --pretty="%h||[%cd] %s" --date=format:"%F %T"', plugin)
if (cm.error) return this.reply(cm.error.stack)
if (cm.error) return this.reply(Bot.String(cm.error))

const logAll = String(cm.stdout).trim().split("\n")
const logAll = cm.stdout.split("\n")
if (!logAll.length) return false

let log = []
Expand All @@ -210,19 +224,13 @@ export class update extends plugin {
if (str[1].includes("Merge branch")) continue
log.push(str[1])
}
let line = log.length
log = log.join("\n\n")

if (log.length <= 0) return ""

cm = await this.exec("git config -l", plugin)
const end = String(cm.stdout).match(/remote\..*\.url=.+/g).join("\n\n").replace(/remote\..*\.url=/g, "").replace(/\/\/([^@]+)@/, "//")
if (cm.error) {
logger.error(cm.error)
await this.reply(String(cm.error))
}
const msg = [`${plugin || "TRSS-Yunzai"} 更新日志,共${log.length}条`, log.join("\n\n")]
const end = await this.getRemoteUrl((await this.getRemoteBranch(false, plugin)).remote, true, plugin)
if (end) msg.push(end)

return Bot.makeForwardArray([`${plugin || "TRSS-Yunzai"} 更新日志,共${line}条`, log, end])
return Bot.makeForwardArray(msg)
}

async updateLog() {
Expand Down

0 comments on commit 21eea14

Please sign in to comment.