Test Failed
Push — master ( ee826a...d9056e )
by Nicolas
03:09
created

GlancesStdout.update()   D

Complexity

Conditions 13

Size

Total Lines 38
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
eloc 25
nop 3
dl 0
loc 38
rs 4.2
c 0
b 0
f 0

How to fix   Complexity   

Complexity

Complex classes like glances.outputs.glances_stdout.GlancesStdout.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
# SPDX-FileCopyrightText: 2024 Nicolas Hennion <[email protected]>
6
#
7
# SPDX-License-Identifier: LGPL-3.0-only
8
#
9
10
"""Stdout interface class."""
11
12
import time
13
14
from glances.logger import logger
15
from glances.globals import printandflush
16
17
18
class GlancesStdout(object):
19
    """This class manages the Stdout display."""
20
21
    def __init__(self, config=None, args=None):
22
        # Init
23
        self.config = config
24
        self.args = args
25
26
        # Build the list of plugin and/or plugin.attribute to display
27
        self.plugins_list = self.build_list()
28
29
    def build_list(self):
30
        """Return a list of tuples taken from self.args.stdout
31
32
        :return: A list of tuples. Example [(plugin, key, attribute), ... ]
33
        """
34
        ret = []
35
        for p in self.args.stdout.split(','):
36
            pka = p.split('.')
37
            if len(pka) == 1:
38
                # Only plugin name is provided
39
                new = (pka[0], None, None)
40
            elif len(pka) == 2:
41
                # Plugin name and attribute is provided
42
                new = (pka[0], None, pka[1])
43
            elif len(pka) == 3:
44
                # Plugin name, key and attribute are provided
45
                new = (pka[0], pka[1], pka[2])
46
            ret.append(new)
0 ignored issues
show
introduced by
The variable new does not seem to be defined for all execution paths.
Loading history...
47
        return ret
48
49
    def end(self):
50
        pass
51
52
    def update(self, stats, duration=3):
53
        """Display stats to stdout.
54
55
        Refresh every duration second.
56
        """
57
        for plugin, key, attribute in self.plugins_list:
58
            # Check if the plugin exist and is enable
59
            if plugin in stats.getPluginsList() and stats.get_plugin(plugin).is_enabled():
60
                stat = stats.get_plugin(plugin).get_export()
61
            else:
62
                continue
63
            # Display stats
64
            if attribute is not None:
65
                # With attribute
66
                if isinstance(stat, dict):
67
                    try:
68
                        printandflush("{}.{}: {}".format(plugin, attribute, stat[attribute]))
69
                    except KeyError as err:
70
                        logger.error("Can not display stat {}.{} ({})".format(plugin, attribute, err))
71
                elif isinstance(stat, list):
72
                    for i in stat:
73
                        if key is None:
74
                            i_key = i[i['key']]
75
                        elif str(key) == str(i[i['key']]):
76
                            i_key = key
77
                        else:
78
                            continue
79
                        try:
80
                            printandflush("{}.{}.{}: {}".format(plugin, i_key, attribute, i[attribute]))
81
                        except KeyError as err:
82
                            logger.error("Can not display stat {}.{} ({})".format(plugin, attribute, err))
83
            else:
84
                # Without attribute
85
                printandflush("{}: {}".format(plugin, stat))
86
87
        # Wait until next refresh
88
        if duration > 0:
89
            time.sleep(duration)
90