Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

import getpass 

import hashlib 

import sys 

import uuid 

 

import prettytable 

 

from keystoneclient import exceptions 

 

 

# Decorator for cli-args 

def arg(*args, **kwargs): 

    def _decorator(func): 

        # Because of the sematics of decorator composition if we just append 

        # to the options list positional options will appear to be backwards. 

        func.__dict__.setdefault('arguments', []).insert(0, (args, kwargs)) 

        return func 

    return _decorator 

 

 

def pretty_choice_list(l): 

    return ', '.join("'%s'" % i for i in l) 

 

 

def print_list(objs, fields, formatters={}, order_by=None): 

    pt = prettytable.PrettyTable([f for f in fields], 

                                 caching=False, print_empty=False) 

    pt.aligns = ['l' for f in fields] 

 

    for o in objs: 

        row = [] 

        for field in fields: 

34            if field in formatters: 

                row.append(formatters[field](o)) 

            else: 

                field_name = field.lower().replace(' ', '_') 

                data = getattr(o, field_name, '') 

                if data is None: 

                    data = '' 

                row.append(data) 

        pt.add_row(row) 

 

    if order_by is None: 

        order_by = fields[0] 

    print pt.get_string(sortby=order_by) 

 

 

def _word_wrap(string, max_length=0): 

    """wrap long strings to be no longer then max_length""" 

52    if max_length <= 0: 

        return string 

    return '\n'.join([string[i:i + max_length] for i in 

                     range(0, len(string), max_length)]) 

 

 

def print_dict(d, wrap=0): 

    """pretty table prints dictionaries. 

 

    Wrap values to max_length wrap if wrap>0 

    """ 

    pt = prettytable.PrettyTable(['Property', 'Value'], 

                                 caching=False, print_empty=False) 

    pt.aligns = ['l', 'l'] 

    for (prop, value) in d.iteritems(): 

        if value is None: 

            value = '' 

        value = _word_wrap(value, max_length=wrap) 

        pt.add_row([prop, value]) 

    print pt.get_string(sortby='Property') 

 

 

def find_resource(manager, name_or_id): 

    """Helper for the _find_* methods.""" 

    # first try to get entity as integer id 

    try: 

        if isinstance(name_or_id, int) or name_or_id.isdigit(): 

            return manager.get(int(name_or_id)) 

    except exceptions.NotFound: 

        pass 

 

    # now try to get entity as uuid 

    try: 

        uuid.UUID(str(name_or_id)) 

        return manager.get(name_or_id) 

    except (ValueError, exceptions.NotFound): 

        pass 

 

    # finally try to find entity by name 

    try: 

        return manager.find(name=name_or_id) 

    except exceptions.NotFound: 

        msg = ("No %s with a name or ID of '%s' exists." % 

               (manager.resource_class.__name__.lower(), name_or_id)) 

        raise exceptions.CommandError(msg) 

    except exceptions.NoUniqueMatch: 

        msg = ("Multiple %s matches found for '%s', use an ID to be more" 

               " specific." % (manager.resource_class.__name__.lower(), 

                               name_or_id)) 

        raise exc.CommandError(msg) 

 

 

def unauthenticated(f): 

    """Adds 'unauthenticated' attribute to decorated function. 

 

    Usage:: 

 

        @unauthenticated 

        def mymethod(f): 

            ... 

    """ 

    f.unauthenticated = True 

    return f 

 

 

def isunauthenticated(f): 

    """ 

    Checks to see if the function is marked as not requiring authentication 

    with the @unauthenticated decorator. Returns True if decorator is 

    set to True, False otherwise. 

    """ 

    return getattr(f, 'unauthenticated', False) 

 

 

def string_to_bool(arg): 

    if isinstance(arg, bool): 

        return arg 

 

    return arg.strip().lower() in ('t', 'true', 'yes', '1') 

 

 

def hash_signed_token(signed_text): 

    hash_ = hashlib.md5() 

    hash_.update(signed_text) 

    return hash_.hexdigest() 

 

 

def prompt_for_password(): 

    """ 

     Prompt user for password if not provided so the password 

     doesn't show up in the bash history. 

    """ 

    if not (hasattr(sys.stdin, 'isatty') and sys.stdin.isatty()): 

        # nothing to do 

        return 

 

    while True: 

        try: 

            new_passwd = getpass.getpass('New Password: ') 

            rep_passwd = getpass.getpass('Repeat New Password: ') 

            if new_passwd == rep_passwd: 

                return new_passwd 

        except EOFError: 

            return