Skip to content

Commit

Permalink
✨ Feature: add plugin running && error logs
Browse files Browse the repository at this point in the history
  • Loading branch information
Molunerfinn committed May 2, 2020
1 parent daa7508 commit 6adc070
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 51 deletions.
86 changes: 48 additions & 38 deletions src/core/Lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { EventEmitter } from 'events'
import PicGo from './PicGo'
import { Plugin } from '../utils/interfaces'
import { handleUrlEncode } from '../utils/common'
import LifecyclePlugins from '../lib/LifecyclePlugins'

class Lifecycle extends EventEmitter {
configPath: string
Expand All @@ -22,11 +23,11 @@ class Lifecycle extends EventEmitter {
this.ctx.output = []

// lifecycle main
await this.beforeTransform(this.ctx)
await this.doTransform(this.ctx)
await this.beforeUpload(this.ctx)
await this.doUpload(this.ctx)
await this.afterUpload(this.ctx)
await this.beforeTransform()
await this.doTransform()
await this.beforeUpload()
await this.doUpload()
await this.afterUpload()
return this.ctx
} catch (e) {
this.ctx.log.warn('failed')
Expand All @@ -38,71 +39,80 @@ class Lifecycle extends EventEmitter {
}
}
}
private async beforeTransform (ctx: PicGo): Promise<PicGo> {
private async beforeTransform (): Promise<PicGo> {
this.ctx.emit('uploadProgress', 0)
this.ctx.emit('beforeTransform', ctx)
this.ctx.emit('beforeTransform', this.ctx)
this.ctx.log.info('Before transform')
await this.handlePlugins(ctx.helper.beforeTransformPlugins.getList(), ctx)
return ctx
await this.handlePlugins(this.ctx.helper.beforeTransformPlugins)
return this.ctx
}
private async doTransform (ctx: PicGo): Promise<PicGo> {
private async doTransform (): Promise<PicGo> {
this.ctx.emit('uploadProgress', 30)
this.ctx.log.info('Transforming...')
let type = ctx.getConfig('picBed.transformer') || 'path'
let type = this.ctx.getConfig('picBed.transformer') || 'path'
let transformer = this.ctx.helper.transformer.get(type)
if (!transformer) {
transformer = this.ctx.helper.transformer.get('path')
ctx.log.warn(`Can't find transformer - ${type}, swtich to default transformer - path`)
this.ctx.log.warn(`Can't find transformer - ${type}, swtich to default transformer - path`)
}
await transformer.handle(ctx)
return ctx
await transformer.handle(this.ctx)
return this.ctx
}
private async beforeUpload (ctx: PicGo): Promise<PicGo> {
private async beforeUpload (): Promise<PicGo> {
this.ctx.emit('uploadProgress', 60)
this.ctx.log.info('Before upload')
this.ctx.emit('beforeUpload', ctx)
await this.handlePlugins(ctx.helper.beforeUploadPlugins.getList(), ctx)
return ctx
this.ctx.emit('beforeUpload', this.ctx)
await this.handlePlugins(this.ctx.helper.beforeUploadPlugins)
return this.ctx
}
private async doUpload (ctx: PicGo): Promise<PicGo> {
private async doUpload (): Promise<PicGo> {
this.ctx.log.info('Uploading...')
let type = ctx.getConfig('picBed.uploader') || ctx.getConfig('picBed.current') || 'smms'
let type = this.ctx.getConfig('picBed.uploader') || this.ctx.getConfig('picBed.current') || 'smms'
let uploader = this.ctx.helper.uploader.get(type)
if (!uploader) {
type = 'smms'
uploader = this.ctx.helper.uploader.get('smms')
ctx.log.warn(`Can't find uploader - ${type}, swtich to default uploader - smms`)
this.ctx.log.warn(`Can't find uploader - ${type}, swtich to default uploader - smms`)
}
await uploader.handle(ctx)
for (let i in ctx.output) {
ctx.output[i].type = type
await uploader.handle(this.ctx)
for (let i in this.ctx.output) {
this.ctx.output[i].type = type
}
return ctx
return this.ctx
}
private async afterUpload (ctx: PicGo): Promise<PicGo> {
this.ctx.emit('afterUpload', ctx)
private async afterUpload (): Promise<PicGo> {
this.ctx.emit('afterUpload', this.ctx)
this.ctx.emit('uploadProgress', 100)
await this.handlePlugins(ctx.helper.afterUploadPlugins.getList(), ctx)
await this.handlePlugins(this.ctx.helper.afterUploadPlugins)
let msg = ''
let length = ctx.output.length
let length = this.ctx.output.length
for (let i = 0; i < length; i++) {
msg += handleUrlEncode(ctx.output[i].imgUrl)
msg += handleUrlEncode(this.ctx.output[i].imgUrl)
if (i !== length - 1) {
msg += '\n'
}
delete ctx.output[i].base64Image
delete ctx.output[i].buffer
delete this.ctx.output[i].base64Image
delete this.ctx.output[i].buffer
}
this.ctx.emit('finished', ctx)
this.ctx.emit('finished', this.ctx)
this.ctx.log.success(`\n${msg}`)
return ctx
return this.ctx
}

private async handlePlugins (plugins: Plugin[], ctx: PicGo): Promise<PicGo> {
await Promise.all(plugins.map(async (plugin: Plugin) => {
await plugin.handle(ctx)
private async handlePlugins (lifeCyclePlugins: LifecyclePlugins): Promise<PicGo> {
const plugins = lifeCyclePlugins.getList()
const pluginNames = lifeCyclePlugins.getIdList()
const lifeCycleName = lifeCyclePlugins.getName()
await Promise.all(plugins.map(async (plugin: Plugin, index: number) => {
try {
this.ctx.log.info(`${lifeCycleName}: ${pluginNames[index]} running`)
await plugin.handle(this.ctx)
} catch (e) {
this.ctx.log.error(`${lifeCycleName}: ${pluginNames[index]} error`)
throw e
}
}))
return ctx
return this.ctx
}
}

Expand Down
10 changes: 7 additions & 3 deletions src/lib/LifecyclePlugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import { Plugin } from '../utils/interfaces'

class LifecyclePlugins {
static currentPlugin: string | null
list: Map<string, Plugin>
pluginIdMap: Map<string, string[]>
name: string
private list: Map<string, Plugin>
private pluginIdMap: Map<string, string[]>
private name: string

constructor (name: string) {
this.name = name
Expand Down Expand Up @@ -35,6 +35,10 @@ class LifecyclePlugins {
}
}

getName (): string {
return this.name
}

get (id: string): Plugin {
return this.list.get(id)
}
Expand Down
18 changes: 8 additions & 10 deletions src/lib/Logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ class Logger {
[ILogType.error]: 'red'
}
private ctx: PicGo
// private logger: Console
private logLevel: string
private logPath: string
constructor (ctx: PicGo) {
Expand All @@ -28,13 +27,13 @@ class Logger {
// if configPath is invalid then this.ctx.config === undefined
// if not then check config.silent
if (this.ctx.getConfig() === undefined || !this.ctx.getConfig('silent')) {
let log = chalk[this.level[type]](`[PicGo ${type.toUpperCase()}]: `)
console.log(log, ...msg)
const logHeader = chalk[this.level[type]](`[PicGo ${type.toUpperCase()}]:`)
console.log(logHeader, ...msg)
this.logLevel = this.ctx.getConfig('settings.logLevel')
const logPath = this.checkLogPathChange()
// The incoming logPath is a value
// lock the path with a closure
setTimeout(() => {
// The incoming logPath is a value
// lock the path with a closure
this.handleWriteLog(logPath, type, ...msg)
}, 0)
} else {
Expand All @@ -50,7 +49,7 @@ class Logger {
return logPath
}

protected handleWriteLog (logPath: string, type: string, ...msg: ILogArgvTypeWithError[]): void {
private handleWriteLog (logPath: string, type: string, ...msg: ILogArgvTypeWithError[]): void {
try {
if (this.checkLogLevel(type, this.logLevel)) {
let log = `${dayjs().format('YYYY-MM-DD HH:mm:ss')} [PicGo ${type.toUpperCase()}] `
Expand All @@ -62,16 +61,15 @@ class Logger {
}
})
log += '\n'
fs.appendFile(logPath, log, (err: Error) => {
if (err) console.log(err)
})
// A synchronized approach to avoid log msg sequence errors
fs.appendFileSync(logPath, log)
}
} catch (e) {
console.log(e)
}
}

protected checkLogLevel (type: string, level: undefined | string | string[]): boolean {
private checkLogLevel (type: string, level: undefined | string | string[]): boolean {
if (level === undefined || level === 'all') {
return true
}
Expand Down

0 comments on commit 6adc070

Please sign in to comment.