Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(core): support generator function as command action #819

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 22 additions & 3 deletions packages/core/src/command/command.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Awaitable, coerce, Dict, isNullable, Logger, remove, Schema } from '@koishijs/utils'
import { Awaitable, coerce, Dict, isNullable, isGeneratorFunction, Logger, remove, Schema } from '@koishijs/utils'
import { segment } from '@satorijs/core'
import { Disposable } from 'cordis'
import { Context } from '../context'
Expand Down Expand Up @@ -26,8 +26,10 @@ export namespace Command {
options?: Dict
}

export type Plain = void | string | segment

export type Action<U extends User.Field = never, G extends Channel.Field = never, A extends any[] = any[], O extends {} = {}>
= (argv: Argv<U, G, A, O>, ...args: A) => Awaitable<void | string | segment>
= (argv: Argv<U, G, A, O>, ...args: A) => Awaitable<Plain> | Generator<Plain, Plain, string[]> | AsyncGenerator<Plain, Plain, string[]>

export type Usage<U extends User.Field = never, G extends Channel.Field = never>
= string | ((session: Session<U, G>) => Awaitable<string>)
Expand Down Expand Up @@ -246,7 +248,24 @@ export class Command<U extends User.Field = never, G extends Channel.Field = nev

let index = 0
const queue: Next.Queue = this._actions.map(action => async () => {
return await action.call(this, argv, ...args)
if (isGeneratorFunction<Command.Plain, Command.Plain, string[]>(action)) {
const result = action.call(this, argv, ...args)
let ids: string[] = []
while (true) {
const effect = await result.next(ids)
ids = []
// return
if (effect.done) {
return effect.value
}
// yield
if (!isNullable(effect.value)) {
ids = await argv.session.send(effect.value)
}
}
} else {
return action.call(this, argv, ...args) as Command.Plain
}
})

queue.push(fallback)
Expand Down
35 changes: 34 additions & 1 deletion packages/core/tests/command.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { App, Command, Logger, Next } from 'koishi'
import { sleep } from '@koishijs/utils'
import { inspect } from 'util'
import { expect, use } from 'chai'
import shape from 'chai-shape'
Expand Down Expand Up @@ -175,12 +176,14 @@ describe('Command API', () => {
})
})

describe('Execute Commands', () => {
describe('Execute Commands', async () => {
const app = new App()
app.plugin(mock)
const session = app.mock.session({})
const client = app.mock.client('123')
const warn = jest.spyOn(logger, 'warn')
const next = jest.fn(Next.compose)
await app.start()

let command: Command
beforeEach(() => {
Expand Down Expand Up @@ -290,6 +293,36 @@ describe('Command API', () => {
expect(warn.mock.calls).to.have.length(0)
expect(next.mock.calls).to.have.length(0)
})

it('generator 1 (sync)', async () => {
command.action(function* () {
yield '1'
yield '2'
return '3'
})
await client.shouldReply('test', ['1', '2', '3'])
})

it('generator 2 (sync without yield)', async () => {
command.action(function* () { return '1' })
await client.shouldReply('test', '1')
})

it('generator 3 (sync without return)', async () => {
command.action(function* () { yield '1' })
await client.shouldReply('test', '1')
})

it('generator 4 (async)', async () => {
command.action(async function* () {
yield '1'
yield '2'
await sleep(100)
yield '3'
return '4'
})
await client.shouldReply('test', ['1', '2', '3', '4'])
})
})

describe('Bypass Middleware', async () => {
Expand Down
4 changes: 4 additions & 0 deletions packages/utils/src/misc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ export function isInteger(source: any) {
return typeof source === 'number' && Math.floor(source) === source
}

export function isGeneratorFunction<T = unknown, TReturn = any, TNext = unknown>(fn: any): fn is (...args: any[]) => Generator<T, TReturn, TNext> | AsyncGenerator<T, TReturn, TNext> {
return ['GeneratorFunction', 'AsyncGeneratorFunction'].includes(fn.constructor.name)
}

export async function sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms))
}
Expand Down