feat: add "or" and "not" matchers

This commit is contained in:
wancat committed 2024-03-07 00:42:49 +08:00
1 parent e83d913852
commit e5f5590a67
4 files changed
+49 -1

No files matched your search

+11 -1
View File
@@ -1,24 +1,34 @@
/* eslint-disable max-classes-per-file */
import { Command } from '../command.js'
import { PwdMatcher } from './pwdMatcher.js'
import { CommandMatcher } from './commandMatcher.js'
import { ErrorMatcher } from './errorMatcher.js'
import { Matcher } from './matcher.js'
import { OutputMatcher } from './outputMatcher.js'
import { OrMatcher } from './orMatcher.js'
import { NotMatcher } from './notMatcher.js'
export interface ICondition {
command?: string
output?: string
error?: string
pwd?: string
or?: ICondition[]
not?: ICondition
}
export class Condition {
private matchers: Matcher[] = []
constructor({ command, output, error, pwd }: ICondition) {
constructor({ command, output, error, pwd, or, not }: ICondition) {
if (command) this.matchers.push(new CommandMatcher(command))
if (output) this.matchers.push(new OutputMatcher(output))
if (pwd) this.matchers.push(new PwdMatcher(pwd))
if (or) {
const conditions = or.map((condition) => new Condition(condition))
this.matchers.push(new OrMatcher(conditions))
}
if (not) this.matchers.push(new NotMatcher(new Condition(not)))
this.matchers.push(new ErrorMatcher(error)) // always check unexpected error
}
+10
View File
@@ -0,0 +1,10 @@
import { Command } from '../command.js'
import { Matcher } from './matcher.js'
export class NotMatcher implements Matcher {
constructor(private condition: Matcher) {}
match(command: Partial<Command>): boolean {
return !this.condition.match(command)
}
}
+10
View File
@@ -0,0 +1,10 @@
import { Command } from '../command.js'
import { Matcher } from './matcher.js'
export class OrMatcher implements Matcher {
constructor(private conditions: Matcher[]) {}
match(command: Partial<Command>): boolean {
return this.conditions.some((condition) => condition.match(command))
}
}
+18
View File
@@ -62,3 +62,21 @@ test('condition match command', () => {
condition.match({ command: 'echo start', error: 'permission denied' })
).toBe(false)
})
test('condition with OR', () => {
const condition = new Condition({
or: [{ command: '^echo start$' }, { command: '^echo hello$' }],
})
expect(condition.match({ command: 'echo start' })).toBe(true)
expect(condition.match({ command: 'echo hello' })).toBe(true)
expect(condition.match({ command: 'echo start1' })).toBe(false)
})
test('condition with NOT', () => {
const condition = new Condition({
not: { command: '^echo start$' },
})
expect(condition.match({ command: 'echo start' })).toBe(false)
expect(condition.match({ command: 'echo hello' })).toBe(true)
})