Test Failed
Push — master ( b164e3...65b0d8 )
by Nicolas
03:39
created

GlancesStdoutIssue.update()   C

Complexity

Conditions 11

Size

Total Lines 58
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 43
nop 3
dl 0
loc 58
rs 5.4
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like glances.outputs.glances_stdout_issue.GlancesStdoutIssue.update() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
# -*- coding: utf-8 -*-
2
#
3
# This file is part of Glances.
4
#
5
# Copyright (C) 2021 Nicolargo <[email protected]>
6
#
7
# Glances is free software; you can redistribute it and/or modify
8
# it under the terms of the GNU Lesser General Public License as published by
9
# the Free Software Foundation, either version 3 of the License, or
10
# (at your option) any later version.
11
#
12
# Glances is distributed in the hope that it will be useful,
13
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
# GNU Lesser General Public License for more details.
16
#
17
# You should have received a copy of the GNU Lesser General Public License
18
# along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20
"""Issue interface class."""
21
22
import os
23
import sys
24
import platform
25
import shutil
26
import time
27
28
from glances.timer import Counter
29
from glances import __version__, psutil_version
30
31
import psutil
32
import glances
33
34
try:
35
    TERMINAL_WIDTH = shutil.get_terminal_size(fallback=(79, 24)).columns
36
except:
37
    TERMINAL_WIDTH = 79
38
39
40
class colors:
41
    RED = '\033[91m'
42
    GREEN = '\033[92m'
43
    ORANGE = '\033[93m'
44
    BLUE = '\033[94m'
45
    NO = '\033[0m'
46
47
    def disable(self):
48
        self.RED = ''
49
        self.GREEN = ''
50
        self.BLUE = ''
51
        self.ORANGE = ''
52
        self.NO = ''
53
54
55
class GlancesStdoutIssue(object):
56
57
    """
58
    This class manages the Issue display.
59
    """
60
61
    def __init__(self, config=None, args=None):
62
        # Init
63
        self.config = config
64
        self.args = args
65
66
    def end(self):
67
        pass
68
69
    def print_version(self):
70
        sys.stdout.write('=' * TERMINAL_WIDTH + '\n')
71
        sys.stdout.write('Glances {} ({})\n'.format(
72
            colors.BLUE + __version__ + colors.NO,
73
            os.path.realpath(glances.__file__)))
74
        sys.stdout.write('Python {} ({})\n'.format(
75
            colors.BLUE + platform.python_version() + colors.NO,
76
            sys.executable))
77
        sys.stdout.write('PsUtil {} ({})\n'.format(
78
            colors.BLUE + psutil_version + colors.NO,
79
            os.path.realpath(psutil.__file__)))
80
        sys.stdout.write('=' * TERMINAL_WIDTH + '\n')
81
        sys.stdout.flush()
82
83
    def print_issue(self, plugin, result, message):
84
        sys.stdout.write('{}{}{}'.format(
85
            colors.BLUE + plugin, result, message))
86
        sys.stdout.write(colors.NO + '\n')
87
        sys.stdout.flush()
88
89
    def update(self,
90
               stats,
91
               duration=3):
92
        """Display issue
93
        """
94
        self.print_version()
95
96
        for plugin in sorted(stats._plugins):
97
            if stats._plugins[plugin].is_disabled():
98
                continue
99
            try:
100
                # Update the stats
101
                stats._plugins[plugin].update()
102
            except Exception as e:
103
                pass
104
105
        time.sleep(3)
106
107
        for plugin in sorted(stats._plugins):
108
            if stats._plugins[plugin].is_disabled():
109
                # If current plugin is disable
110
                # then continue to next plugin
111
                result = colors.NO + '[N/A]'.rjust(19 - len(plugin))
112
                message = colors.NO
113
                self.print_issue(plugin, result, message)
114
                continue
115
            # Start the counter
116
            counter = Counter()
117
            counter.reset()
118
            stat = None
119
            stat_error = None
120
            try:
121
                # Update the stats
122
                stats._plugins[plugin].update()
123
                # Get the stats
124
                stat = stats.get_plugin(plugin).get_export()
125
            except Exception as e:
126
                stat_error = e
127
            if stat_error is None:
128
                result = (colors.GREEN +
129
                          '[OK]   ' +
130
                          colors.BLUE +
131
                          ' {:.5f}s '.format(counter.get())).rjust(41 - len(plugin))
132
                if isinstance(stat, list) and len(stat) > 0 and 'key' in stat[0]:
133
                    key = 'key={} '.format(stat[0]['key'])
134
                    message = colors.ORANGE + key + colors.NO + str(stat)[0:TERMINAL_WIDTH-41-len(key)]
135
                else:
136
                    message = colors.NO + str(stat)[0:TERMINAL_WIDTH-41]
137
            else:
138
                result = (colors.RED +
139
                          '[ERROR]' +
140
                          colors.BLUE +
141
                          ' {:.5f}s '.format(counter.get())).rjust(41 - len(plugin))
142
                message = colors.NO + str(stat_error)[0:TERMINAL_WIDTH-41]
143
            self.print_issue(plugin, result, message)
144
145
        # Return True to exit directly (no refresh)
146
        return True
147