Skip to content

Environment variable name generation from command name is broken #1253

@gpakosz

Description

@gpakosz

When command names contain a - character, automatic environment variable name generation is broken

#!/usr/bin/env python3

import click

@click.group()
@click.option('--debug/--no-debug')
def cli(debug):
    click.echo('Debug mode is %s' % ('on' if debug else 'off'))

@click.command(name="greet-me")
@click.option('--username', show_envvar=True)
def greet(username):
    click.echo('Hello %s!' % username)

if __name__ == '__main__':
    cli.add_command(greet)
    cli(auto_envvar_prefix='GREETER')
$ pipenv run python ./test.py greet-me  --help
Loading .env environment variables…
Debug mode is off
Usage: test.py greet-me [OPTIONS]

Options:
  --username TEXT  [env var: GREETER_GREET-ME_USERNAME]
  --help           Show this message and exit.

This seems to be solved by changing core.py:329 to

       # If there is no envvar prefix yet, but the parent has one and
        # the command on this level has a name, we can expand the envvar
        # prefix automatically.
        if auto_envvar_prefix is None:
            if parent is not None \
               and parent.auto_envvar_prefix is not None and \
               self.info_name is not None:
                auto_envvar_prefix = '%s_%s' % (parent.auto_envvar_prefix,
                                           self.info_name.upper().replace("-", "_"))

I'm not opening a pull request though as I'm not familiar with click's codebase and

  • I'm not sure the modification above is general enough as there are other instances of <something>.name.upper() found in core.py
  • I'm not sure replacing - with _ covers all the tricky cases

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions