You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.8 KiB

import AppClass from '../../../lib/src/lifecycle/AppClass.ts'
import {Service} from '../../../di/src/decorator/Service.ts'
import {Collection} from '../../../lib/src/collection/Collection.ts'
import {Directive} from '../directive/Directive.ts'
import {Logging} from '../../../lib/src/service/logging/Logging.ts'
/**
* Error thrown when a directive registered with the same keyword as
* an existing directive.
* @extends Error
*/
export class DuplicateCLIDirectiveError extends Error {
constructor(keyword: string) {
super(`A CLI directive with the keyword "${keyword}" already exists.`)
}
}
/**
* Service for registering and managing CLI directives.
* @extends AppClass
*/
@Service()
export class CLIService extends AppClass {
protected directives: Collection<Directive> = new Collection<Directive>()
constructor(
protected readonly logger: Logging,
) { super() }
/**
* Find a registered directive using its keyword, if one exists.
* @param {string} keyword
* @return Directive | undefined
*/
public get_directive_by_keyword(keyword: string): Directive | undefined {
return this.directives.firstWhere('keyword', '=', keyword)
}
/**
* Get a collection of all registered directives.
* @return Collection<Directive>
*/
public get_directives() {
return this.directives.clone()
}
/**
* Register a directive with the service.
* @param {Directive} directive
*/
public register_directive(directive: Directive) {
if ( this.get_directive_by_keyword(directive.keyword) ) {
throw new DuplicateCLIDirectiveError(directive.keyword)
}
this.logger.verbose(`Registering CLI directive with keyword: ${directive.keyword}`)
this.directives.push(directive)
}
}