Skip to content

Commit

Permalink
🐛 Fix(type): type error in index.d.ts
Browse files Browse the repository at this point in the history
1. fix type error in index.d.ts
2. refactor picgo.addPlugin -> picgo.pluginLoader.registerPlugin

ISSUES CLOSED: #69
  • Loading branch information
Molunerfinn committed Feb 9, 2021
1 parent 7b5a024 commit f617658
Show file tree
Hide file tree
Showing 33 changed files with 219 additions and 176 deletions.
3 changes: 2 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ module.exports = {
],
'@typescript-eslint/prefer-nullish-coalescing': 0,
'@typescript-eslint/return-await': 0,
'@typescript-eslint/no-floating-promises': 0
'@typescript-eslint/no-floating-promises': 0,
'@typescript-eslint/no-non-null-assertion': 0
}
}
22 changes: 10 additions & 12 deletions src/core/Lifecycle.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
import { EventEmitter } from 'events'
import PicGo from './PicGo'
import { IPlugin, Undefinable } from '../types'
import { ILifecyclePlugins, IPicGo, IPlugin, Undefinable } from '../types'
import { handleUrlEncode } from '../utils/common'
import LifecyclePlugins from '../lib/LifecyclePlugins'
import { IBuildInEvent } from '../utils/enum'

class Lifecycle extends EventEmitter {
ctx: PicGo
private ctx: IPicGo

constructor (ctx: PicGo) {
constructor (ctx: IPicGo) {
super()
this.ctx = ctx
}

async start (input: any[]): Promise<PicGo> {
async start (input: any[]): Promise<IPicGo> {
try {
// images input
if (!Array.isArray(input)) {
Expand Down Expand Up @@ -41,15 +39,15 @@ class Lifecycle extends EventEmitter {
}
}

private async beforeTransform (): Promise<PicGo> {
private async beforeTransform (): Promise<IPicGo> {
this.ctx.emit(IBuildInEvent.UPLOAD_PROGRESS, 0)
this.ctx.emit(IBuildInEvent.BEFORE_TRANSFORM, this.ctx)
this.ctx.log.info('Before transform')
await this.handlePlugins(this.ctx.helper.beforeTransformPlugins)
return this.ctx
}

private async doTransform (): Promise<PicGo> {
private async doTransform (): Promise<IPicGo> {
this.ctx.emit(IBuildInEvent.UPLOAD_PROGRESS, 30)
this.ctx.log.info('Transforming...')
const type = this.ctx.getConfig<Undefinable<string>>('picBed.transformer') || 'path'
Expand All @@ -62,15 +60,15 @@ class Lifecycle extends EventEmitter {
return this.ctx
}

private async beforeUpload (): Promise<PicGo> {
private async beforeUpload (): Promise<IPicGo> {
this.ctx.emit(IBuildInEvent.UPLOAD_PROGRESS, 60)
this.ctx.log.info('Before upload')
this.ctx.emit(IBuildInEvent.BEFORE_UPLOAD, this.ctx)
await this.handlePlugins(this.ctx.helper.beforeUploadPlugins)
return this.ctx
}

private async doUpload (): Promise<PicGo> {
private async doUpload (): Promise<IPicGo> {
this.ctx.log.info('Uploading...')
let type = this.ctx.getConfig<Undefinable<string>>('picBed.uploader') || this.ctx.getConfig<Undefinable<string>>('picBed.current') || 'smms'
let uploader = this.ctx.helper.uploader.get(type)
Expand All @@ -86,7 +84,7 @@ class Lifecycle extends EventEmitter {
return this.ctx
}

private async afterUpload (): Promise<PicGo> {
private async afterUpload (): Promise<IPicGo> {
this.ctx.emit(IBuildInEvent.AFTER_UPLOAD, this.ctx)
this.ctx.emit(IBuildInEvent.UPLOAD_PROGRESS, 100)
await this.handlePlugins(this.ctx.helper.afterUploadPlugins)
Expand All @@ -105,7 +103,7 @@ class Lifecycle extends EventEmitter {
return this.ctx
}

private async handlePlugins (lifeCyclePlugins: LifecyclePlugins): Promise<PicGo> {
private async handlePlugins (lifeCyclePlugins: ILifecyclePlugins): Promise<IPicGo> {
const plugins = lifeCyclePlugins.getList()
const pluginNames = lifeCyclePlugins.getIdList()
const lifeCycleName = lifeCyclePlugins.getName()
Expand Down
18 changes: 1 addition & 17 deletions src/core/PicGo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import uploaders from '../plugins/uploader'
import transformers from '../plugins/transformer'
import PluginLoader from '../lib/PluginLoader'
import { get, set, unset } from 'lodash'
import { IHelper, IImgInfo, IConfig, IPicGo, IStringKeyMap, IPicGoPlugin } from '../types'
import { IHelper, IImgInfo, IConfig, IPicGo, IStringKeyMap } from '../types'
import getClipboardImage from '../utils/getClipboardImage'
import Request from '../lib/Request'
import DB from '../utils/db'
Expand Down Expand Up @@ -150,22 +150,6 @@ class PicGo extends EventEmitter implements IPicGo {
unset(this.getConfig(key), propName)
}

/**
* for node project adding a plugin by a simple way
*/
addPlugin (name: string, plugin: IPicGoPlugin): void {
if (!name || !plugin || (typeof plugin !== 'function')) {
this.log.warn('Please provide valid plugin')
return
}
try {
plugin(this).register()
} catch (e) {
this.log.warn('Please provide valid plugin')
this.log.error(e)
}
}

// for v1.5.0+
get request (): RequestPromiseAPI {
// TODO: replace request with got: https://github.com/sindresorhus/got
Expand Down
11 changes: 5 additions & 6 deletions src/lib/Commander.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
import PicGo from '../core/PicGo'
import program, { CommanderStatic } from 'commander'
import inquirer, { Inquirer } from 'inquirer'
import { IPlugin } from '../types'
import { IPlugin, ICommander, IPicGo } from '../types'
import commanders from '../plugins/commander'
import { version } from '../../package.json'

class Commander {
list: {
class Commander implements ICommander {
private list: {
[propName: string]: IPlugin
}

program: CommanderStatic
inquirer: Inquirer
private readonly ctx: PicGo
private readonly ctx: IPicGo

constructor (ctx: PicGo) {
constructor (ctx: IPicGo) {
this.list = {}
this.program = program
this.inquirer = inquirer
Expand Down
4 changes: 2 additions & 2 deletions src/lib/LifecyclePlugins.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { IPlugin } from '../types'
import { IPlugin, ILifecyclePlugins } from '../types'

class LifecyclePlugins {
class LifecyclePlugins implements ILifecyclePlugins {
static currentPlugin: string | null
private readonly list: Map<string, IPlugin>
private readonly pluginIdMap: Map<string, string[]>
Expand Down
8 changes: 4 additions & 4 deletions src/lib/Logger.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import chalk from 'chalk'
import PicGo from '../core/PicGo'
import dayjs from 'dayjs'
import fs from 'fs-extra'
import path from 'path'
Expand All @@ -10,7 +9,8 @@ import {
ILogArgvTypeWithError,
Undefinable,
ILogColor,
ILogger
ILogger,
IPicGo
} from '../types'

class Logger implements ILogger {
Expand All @@ -21,10 +21,10 @@ class Logger implements ILogger {
[ILogType.error]: 'red'
}

private readonly ctx: PicGo
private readonly ctx: IPicGo
private logLevel!: string
private logPath!: string
constructor (ctx: PicGo) {
constructor (ctx: IPicGo) {
this.ctx = ctx
}

Expand Down
10 changes: 5 additions & 5 deletions src/lib/PluginHandler.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import PicGo from '../core/PicGo'
import spawn from 'cross-spawn'
import {
IResult,
IProcessEnv,
IPluginProcessResult,
IPluginHandler,
IPluginHandlerOptions,
Undefinable
Undefinable,
IPicGo
} from '../types'
import { IBuildInEvent } from '../utils/enum'
import { getProcessPluginName, getNormalPluginName } from '../utils/common'

class PluginHandler implements IPluginHandler {
// Thanks to feflow -> https://github.com/feflow/feflow/blob/master/lib/internal/install/plugin.js
private readonly ctx: PicGo
constructor (ctx: PicGo) {
private readonly ctx: IPicGo
constructor (ctx: IPicGo) {
this.ctx = ctx
}

Expand Down Expand Up @@ -191,7 +191,7 @@ class PluginHandler implements IPluginHandler {
* @param ctx
* @param nameOrPath
*/
const handlePluginNameProcess = (ctx: PicGo, nameOrPath: string): IPluginProcessResult => {
const handlePluginNameProcess = (ctx: IPicGo, nameOrPath: string): IPluginProcessResult => {
const res = {
success: false,
fullName: '',
Expand Down
75 changes: 49 additions & 26 deletions src/lib/PluginLoader.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
import PicGo from '../core/PicGo'
import fs from 'fs-extra'
import path from 'path'
import resolve from 'resolve'
import { IBuildInEvent } from '../utils/enum'
import { IPicGo, IPicGoPlugin, IPluginLoader, IPicGoPluginInterface } from '../types/index'

/**
* Local plugin loader, file system is required
*/
class PluginLoader {
ctx: PicGo
class PluginLoader implements IPluginLoader {
private readonly ctx: IPicGo
private list: string[] = []
private readonly fullList: Set<string> = new Set()
constructor (ctx: PicGo) {
private readonly pluginMap: Map<string, IPicGoPluginInterface> = new Map()
constructor (ctx: IPicGo) {
this.ctx = ctx
this.init()
}

init (): void {
private init (): void {
const packagePath = path.join(this.ctx.baseDir, 'package.json')
if (!fs.existsSync(packagePath)) {
const pkg = {
Expand All @@ -30,7 +31,7 @@ class PluginLoader {
}

// get plugin entry
resolvePlugin (ctx: PicGo, name: string): string {
private resolvePlugin (ctx: IPicGo, name: string): string {
try {
return resolve.sync(name, { basedir: ctx.baseDir })
} catch (err) {
Expand Down Expand Up @@ -60,28 +61,45 @@ class PluginLoader {
return true
}

registerPlugin (name: string): void {
registerPlugin (name: string, plugin?: IPicGoPlugin): void {
if (!name || typeof name !== 'string') {
this.ctx.log.warn('Please provide valid plugin')
return
}
this.fullList.add(name)
if (this.ctx.getConfig(`picgoPlugins.${name}`) === true || (this.ctx.getConfig(`picgoPlugins.${name}`) === undefined)) {
try {
try {
// register local plugin
if (!plugin) {
if (this.ctx.getConfig(`picgoPlugins.${name}`) === true || (this.ctx.getConfig(`picgoPlugins.${name}`) === undefined)) {
this.list.push(name)
this.ctx.setCurrentPluginName(name)
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this.getPlugin(name)!.register()
const plugin = `picgoPlugins[${name}]`
this.ctx.saveConfig(
{
[plugin]: true
}
)
}
} else {
// register provided plugin
// && won't write config to files
this.list.push(name)
this.ctx.setCurrentPluginName(name)
this.getPlugin(name).register()
const plugin = `picgoPlugins[${name}]`
this.ctx.saveConfig(
{
[plugin]: true
}
)
} catch (e) {
this.list = this.list.filter((item: string) => item !== name)
this.fullList.delete(name)
this.ctx.log.error(e)
this.ctx.emit(IBuildInEvent.NOTIFICATION, {
title: `Plugin ${name} Load Error`,
body: e
})
const pluginInterface = plugin(this.ctx)
this.pluginMap.set(name, pluginInterface)
plugin(this.ctx).register()
}
} catch (e) {
this.pluginMap.delete(name)
this.list = this.list.filter((item: string) => item !== name)
this.fullList.delete(name)
this.ctx.log.error(e)
this.ctx.emit(IBuildInEvent.NOTIFICATION, {
title: `Plugin ${name} Load Error`,
body: e
})
}
}

Expand All @@ -98,10 +116,15 @@ class PluginLoader {
}

// get plugin by name
getPlugin (name: string): any {
getPlugin (name: string): IPicGoPluginInterface | undefined {
if (this.pluginMap.has(name)) {
return this.pluginMap.get(name)
}
const pluginDir = path.join(this.ctx.baseDir, 'node_modules/')
// eslint-disable-next-line @typescript-eslint/no-var-requires
return require(pluginDir + name)(this.ctx)
const plugin = require(pluginDir + name)(this.ctx)
this.pluginMap.set(name, plugin)
return plugin
}

/**
Expand Down
11 changes: 5 additions & 6 deletions src/lib/Request.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import PicGo from '../core/PicGo'
import request, { RequestPromiseOptions, RequestPromiseAPI } from 'request-promise-native'
import { Undefinable, IConfigChangePayload, IConfig } from '../types'
import { IPicGo, Undefinable, IConfigChangePayload, IConfig } from '../types'
import { CONFIG_CHANGE } from '../utils/buildInEvent'
import { eventBus } from '../utils/eventBus'

class Request {
private readonly ctx: PicGo
private readonly ctx: IPicGo
private proxy: Undefinable<string> = ''
options: RequestPromiseOptions = {}
constructor (ctx: PicGo) {
constructor (ctx: IPicGo) {
this.ctx = ctx
this.init()
eventBus.on(CONFIG_CHANGE, (data: IConfigChangePayload<string | IConfig['picBed']>) => {
Expand All @@ -25,10 +24,10 @@ class Request {
})
}

init (): void {
private init (): void {
const proxy = this.ctx.getConfig<Undefinable<string>>('picBed.proxy')
if (proxy) {
this.options.proxy = proxy
this.proxy = proxy
}
}

Expand Down
6 changes: 3 additions & 3 deletions src/plugins/commander/config.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import PicGo from '../../core/PicGo'
import { IPlugin } from '../../types'
import { IPicGo, IPlugin } from '../../types'

const config: IPlugin = {
handle: (ctx: PicGo) => {
handle: (ctx: IPicGo) => {
const cmd = ctx.cmd
cmd.program
.option('-c, --config <path>', 'set config path')
// will handle in `bin/picgo`
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/plugins/commander/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import PicGo from '../../core/PicGo'
import pluginHandler from './pluginHandler'
import config from './config'
import upload from './upload'
import setting from './setting'
import use from './use'
import proxy from './proxy'
import init from './init'
import { IPicGo } from '../../types'

export default (ctx: PicGo): void => {
export default (ctx: IPicGo): void => {
ctx.cmd.register('pluginHandler', pluginHandler)
ctx.cmd.register('config', config)
ctx.cmd.register('setting', setting)
Expand Down
Loading

0 comments on commit f617658

Please sign in to comment.