unjs / citty

🌆 Elegant CLI Builder
Other
697 stars 23 forks source link

CLI Plugins #130

Open pi0 opened 4 months ago

pi0 commented 4 months ago

inspired from https://github.com/unjs/citty/issues/98#issuecomment-2011718215 by @jgoux

With plugins, we can allow them to intercept to different hooks but also preserve their context. We can extend to more hooks if needed.

Example:

const telemetryPlugin = defineCittyPlugin(() => {
  const telemetry = new TelemetryClient();

  return {
    name: 'telemetry',
    async setup() {
      telemetry.init();
      await telemetry.captureEvent(`$command:${ctx.cmd.meta.name}:start`); 
    },
    async cleanup() {
      await telemetry.captureEvent(`$command:${ctx.cmd.meta.name}:end`);
      telemetry.flush();
    }
  }
})

defineCommand({
  meta: {
    name: "hello",
    version: "1.0.0",
    description: "My Awesome CLI App",
  },
  plugins: [telemetryPlugin],
  run({ args }) {
    console.log(`${args.friendly ? "Hi" : "Greetings"} ${args.name}!`);
  },
})
jgoux commented 4 months ago

Sounds good to me! 👍