Skip to content

Commit

Permalink
EnumType type for Click
Browse files Browse the repository at this point in the history
Code provided by skycaptain in pallets/click#605
  • Loading branch information
yawor committed Mar 10, 2018
1 parent 050fe3c commit 02f9933
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions miio/click_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import miio
import logging
import json
import re
from typing import Union
from functools import wraps
from functools import partial
Expand Down Expand Up @@ -55,6 +56,43 @@ def __call__(self, *args, **kwargs):
click.echo(click.style("Error: %s" % ex, fg='red', bold=True))


class EnumType(click.Choice):
def __init__(self, enumcls, casesensitive=True):

This comment has been minimized.

Copy link
@rytilahti

rytilahti Mar 10, 2018

Could you also add a link here to pallets/click#605 - maybe something similar gets into click at some point, and it'll be easier to check and to retire this at that point.

choices = enumcls.__members__

if not casesensitive:
choices = (_.lower() for _ in choices)

self._enumcls = enumcls
self._casesensitive = casesensitive

super().__init__(list(sorted(set(choices))))

def convert(self, value, param, ctx):
if not self._casesensitive:
value = value.lower()

value = super().convert(value, param, ctx)

if not self._casesensitive:
return next(_ for _ in self._enumcls if _.name.lower() == value.lower())
else:
return next(_ for _ in self._enumcls if _.name == value)

def get_metavar(self, param):
word = self._enumcls.__name__

# Stolen from jpvanhal/inflection
word = re.sub(r"([A-Z]+)([A-Z][a-z])", r'\1_\2', word)
word = re.sub(r"([a-z\d])([A-Z])", r'\1_\2', word)
word = word.replace("-", "_").lower().split("_")

if word[-1] == "enum":
word.pop()

return ("_".join(word)).upper()


class GlobalContextObject:
def __init__(self, debug: int=0, output: callable=None):
self.debug = debug
Expand Down Expand Up @@ -221,6 +259,7 @@ def wrap(*args, **kwargs):

def json_output(pretty=False):
indent = 2 if pretty else None

def decorator(func):
@wraps(func)
def wrap(*args, **kwargs):
Expand Down

0 comments on commit 02f9933

Please sign in to comment.