summaryrefslogtreecommitdiff
path: root/alot/utils/booleanaction.py
blob: 9a8e87924452a8494c5273e647882c08f31a7661 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Copyright (C) 2011-2012  Patrick Totzke <patricktotzke@gmail.com>
# This file is released under the GNU GPL, version 3 or a later revision.
# For further details see the COPYING file
"""
This defines the ConfigureAction for argparse found here:
http://code.google.com/p/argparse/issues/detail?id=2#c6

We use it to set booelan arguments for command parameters
to False using a `--no-` prefix.
"""
import argparse
import re


TRUEISH = ['1', 't', 'true', 'yes', 'on']
FALSISH = ['0', 'f', 'false', 'no', 'off']

def boolean(string):
    string = string.lower()
    if string in FALSISH:
        return False
    elif string in TRUEISH:
        return True
    else:
        raise ValueError()


class BooleanAction(argparse.Action):
    def __init__(self, *args, **kwargs):
        kwargs['type'] = boolean
        kwargs['choices'] = TRUEISH + FALSISH
        kwargs['metavar'] = 'BOOL'
        argparse.Action.__init__(self, *args, **kwargs)