Writing Tasks

Registering Tasks

Running the task generator not only generates the correct files you need to author a task, it also registers the task for you.

Hooks

Tasks are registered via a hook inside the hooks/register-tasks.ts file. Hooks are a decoupled way plugins make the CLI aware of tasks. Hooks are run early after the CLI is invoked, and allow arbitrary code to be run. In the case of tasks, we use the hooks mechanism to register tasks within the system, which are subsequently run during task invocation.

The example below demonstrates registering the demo task that was previously created in the last section.

import { Hook } from '@oclif/config';
import { getPluginName, RegisterTaskArgs } from '@checkup/core';
import DemoTask from '../tasks/demo-task';
const hook: Hook<RegisterTaskArgs> = async function ({ context, tasks }: RegisterTaskArgs) {
let pluginName = getPluginName(__dirname);
tasks.registerTask(new DemoTask(pluginName, context));
};
export default hook;

If tasks are not registered in the register-tasks hook, they won't be run.

Once a task is registered, it can subsequently be run by the CLI.

Authoring Tasks

Tasks are classes that encapsulate the gathering of data. They implement the following interface:

export interface Task {
taskName: TaskName;
taskDisplayName: TaskName;
config: TaskConfig;
category: string;
group?: string;
readonly fullyQualifiedTaskName: string;
readonly enabled: boolean;
run: () => Promise<TaskResult>;
}

Taking our demo task example, here's an example of that task.

import { BaseTask, Task, TaskResult } from '@checkup/core';
export default class DemoTask extends BaseTask implements Task {
taskName = 'demo';
taskDisplayName = 'Demo';
category = 'best practices';
async run(): Promise<TaskResult> {
// implement data gathering...
return this.toJson([]);
}
}

When invoked, the CLI will run the task's run method, which is expected to perform the data gathering operation, and return the result.

Checkup contains some utilities to help you format your data into the required schema, which will be detailed in the next section.