Passed
Pull Request — master (#73)
by macartur
02:17 queued 25s
created

UsersAPI.print_users()   D

Complexity

Conditions 8

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
c 1
b 0
f 0
dl 0
loc 27
rs 4
1
"""Translate cli commands to non-cli code."""
2
import logging
3
import os
4
5
from kytos.utils.users import UsersManager
6
7
log = logging.getLogger(__name__)
8
9
10
class UsersAPI:
11
    """An API for the command-line interface.
12
13
    Use the config file only for required options. Static methods are called
14
    by the parser and they instantiate an object of this class to fulfill the
15
    request.
16
    """
17
18
    user_manager = UsersManager()
19
20
    @classmethod
21
    def create(cls, args):
22
        """Create a new User in Napps server."""
23
        result = cls.user_manager.register()
24
        print(result)
25
26
    @classmethod
27
    def print_users(cls, users):
28
        """Print all required fields from a user list."""
29
        if not users:
30
            print('No Users found.')
31
            return
32
33
        enabled_w = 8
34
        username_w = max(len('Username'),
35
                         max(len(n['username']) for n in users))
36
        firstname_w = max(len('First Name'),
37
                          max(len(n['first_name']) for n in users))
38
        email_w = max(len('Email'),
39
                      max(len(n['email']) for n in users))
40
        term_w = os.popen('stty size', 'r').read().split()[1]
41
        remaining = int(term_w) - enabled_w - username_w - enabled_w
42
        email_w = min(email_w, remaining)
43
        widths = (enabled_w, username_w, firstname_w, email_w)
44
45
        header = '\n{:^%d} | {:^%d} | {:^%d} | {:^%d}' % widths
46
        row = '{:^%d} | {:<%d} | {:<%d} | {:^%d}' % widths
47
        print(header.format('Enabled', 'Username', 'First Name', 'Email'))
48
        print('=+='.join('=' * w for w in widths))
49
        for user in users:
50
            enabled = 'True' if user['enabled'] else 'False'
51
            print(row.format(enabled, user['username'],
52
                             user['first_name'], user['email']))
53