This is basically identical to the `click` implementation, so please DRY it up.