Passed
Pull Request — master (#73)
by macartur
01:41
created

UsersAPI.search()   A

Complexity

Conditions 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
dl 0
loc 8
rs 9.4285
1
"""Translate cli commands to non-cli code."""
2
import logging
3
import os
4
import re
5
6
from kytos.utils.users import UsersManager
7
8
log = logging.getLogger(__name__)
9
10
11
class UsersAPI:
12
    """An API for the command-line interface.
13
14
    Use the config file only for required options. Static methods are called
15
    by the parser and they instantiate an object of this class to fulfill the
16
    request.
17
    """
18
19
    user_manager = UsersManager()
20
21
    @classmethod
22
    def create(cls, args):
23
        """Create a new User in Napps server."""
24
        result = cls.user_manager.register()
25
        print(result)
26
27
    @classmethod
28
    def list(cls, args):
29
        """List all registered users in Napps server."""
30
        users = cls.user_manager.get_users()
31
        cls.print_users(users)
32
33
    @classmethod
34
    def print_users(cls, users):
35
        """Print all required fields from a user list."""
36
        if not users:
37
            print('No Users found.')
38
            return
39
40
        enabled_w = 8
41
        username_w = max(len('Username'),
42
                         max(len(n['username']) for n in users))
43
        firstname_w = max(len('First Name'),
44
                          max(len(n['first_name']) for n in users))
45
        email_w = max(len('Email'),
46
                      max(len(n['email']) for n in users))
47
        term_w = os.popen('stty size', 'r').read().split()[1]
48
        remaining = int(term_w) - enabled_w - username_w - enabled_w
49
        email_w = min(email_w, remaining)
50
        widths = (enabled_w, username_w, firstname_w, email_w)
51
52
        header = '\n{:^%d} | {:^%d} | {:^%d} | {:^%d}' % widths
53
        row = '{:^%d} | {:<%d} | {:<%d} | {:^%d}' % widths
54
        print(header.format('Enabled', 'Username', 'First Name', 'Email'))
55
        print('=+='.join('=' * w for w in widths))
56
        for user in users:
57
            enabled = 'True' if user['enabled'] else 'False'
58
            print(row.format(enabled, user['username'],
59
                             user['first_name'], user['email']))
60
61
    @classmethod
62
    def show(cls, args):
63
        """Show detailed information about a specific user in Napps server."""
64
        user = cls.user_manager.get_user_by_username(args['<username>'])
65
66
        if not user:
67
            print('No user found.')
68
            return
69
70
        for field in cls.user_manager.attributes:
71
            if field != 'password':
72
                print("{}='{}'".format(field, user[field]))
73
74
    @classmethod
75
    def search(cls, args):
76
        """Search for Users in NApps server matching a pattern."""
77
        safe_shell_pat = re.escape(args['<pattern>']).replace(r'\*', '.*')
78
        pat_str = '.*{}.*'.format(safe_shell_pat)
79
        pattern = re.compile(pat_str, re.IGNORECASE)
80
        remote_json = cls.user_manager.search(pattern)
81
        cls.print_users(remote_json)
82