infinitered / gluegun

A delightful toolkit for building TypeScript-powered command-line apps.
MIT License
2.95k stars 147 forks source link

If a plugin is installed globally, will it be picked up? #728

Open blake-mealey opened 3 years ago

blake-mealey commented 3 years ago

I'm considering using plugins to extend functionality of my Gluegun CLI, but it seems like the intended use case is for a user to install both my CLI and my plugin into a package, then run the local CLI. However that doesn't make sense for my CLI which is intended to be installed globally. If I install the CLI and plugin globally, will the plugin be picked up? I can't find the answer in your docs. Thanks!

cogwizzle commented 2 years ago

This is a feature that I feel like I would like to have as well.

cogwizzle commented 2 years ago

So after doing some digging this is actually currently possible. It requires a bit of work.

Inside of the main cli file you will find a line that reads

.plugins('./node_modules', { matching: 'mycli-*', hidden: true})

This line is loading information from the local node_modules directory. You repeat this function and then load from additional locations. You can get your global node_modules location by running the following code.

const { promisify } = require('util')
const path = require('path')
const exec = promisify(require('child_process').exec)

  const globalModules = path.resolve(
    (await exec('npm config get prefix')).stdout.replace('\n', '').trim() +
      (process.platform !== 'win32' ? '/lib' : '') +
      '/node_modules'
  )

Now that you have the globalModules directory you cann add it to your configuration like this.

.plugins(globalModules, {
      matching: 'mycli-*',
      hidden: false
    })

I hope this helps you. It took me reading through the codebase a bit starting at runtime and working my way back to figure out where this could be configured.

cogwizzle commented 2 years ago

One quick note about my solution above is that it is a bit slow with figuring out the global node modules directory so there may be a faster way to do it. It slightly slows down the start-up of your CLI.

jamonholmgren commented 2 years ago

That's a pretty good solution, @cogwizzle. Biggest issue of course is the CLI startup time. Additionally, if they installed something globally using yarn or pnpm, that won't pick those up. It's a bit of a sticky problem given the nonstandard location of these global packages, so not something I have a great solution for at the moment.