Test Failed
Push — develop ( 45c3c4...3a1e18 )
by Nicolas
05:03 queued 16s
created

glances.outputs.glances_stdout_api_doc   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 176
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 115
dl 0
loc 176
rs 10
c 0
b 0
f 0
wmc 15

6 Functions

Rating   Name   Duplication   Size   Complexity  
A printtab() 0 2 1
B print_plugin() 0 46 6
A print_tldr() 0 29 1
A print_plugins_list() 0 13 1
A print_init_api() 0 12 1
A print_plugins() 0 4 2

3 Methods

Rating   Name   Duplication   Size   Complexity  
A GlancesStdoutApiDoc.end() 0 2 1
A GlancesStdoutApiDoc.update() 0 20 1
A GlancesStdoutApiDoc.__init__() 0 3 1
1
#
2
# This file is part of Glances.
3
#
4
# SPDX-FileCopyrightText: 2025 Nicolas Hennion <[email protected]>
5
#
6
# SPDX-License-Identifier: LGPL-3.0-only
7
#
8
9
"""Generate Glances Python API documentation."""
10
11
from pprint import pformat
12
13
from glances import api
14
15
APIDOC_HEADER = """\
16
.. _api:
17
18
Python API documentation
19
========================
20
21
This documentation describes the Glances Python API.
22
23
Note: This API is only available in Glances 4.4.0 or higher.
24
25
"""
26
27
28
def printtab(s, indent='    '):
29
    print(indent + s.replace('\n', '\n' + indent))
30
31
32
def print_tldr(gl):
33
    """Print the TL;DR section of the API documentation."""
34
    sub_title = 'TL;DR'
35
    print(sub_title)
36
    print('-' * len(sub_title))
37
    print('')
38
    print('You can access the Glances API by importing the `glances.api` module and creating an')
39
    print('instance of the `GlancesAPI` class. This instance provides access to all Glances plugins')
40
    print('and their fields. For example, to access the CPU plugin and its total field, you can')
41
    print('use the following code:')
42
    print('')
43
    print('.. code-block:: python')
44
    print('')
45
    printtab('>>> from glances import api')
46
    printtab('>>> gl = api.GlancesAPI()')
47
    printtab('>>> gl.cpu')
48
    printtab(f'{pformat(gl.cpu.stats)}')
49
    printtab('>>> gl.cpu["total"]')
50
    printtab(f'{gl.cpu["total"]}')
51
    print('')
52
    print('If the stats return a list of items (like network interfaces or processes), you can')
53
    print('access them by their name:')
54
    print('')
55
    print('.. code-block:: python')
56
    print('')
57
    printtab(f'{gl.network.keys()}')
58
    printtab(f'>>> gl.network["{gl.network.keys()[0]}"]')
59
    printtab(f'{pformat(gl.network[gl.network.keys()[0]])}')
60
    print('')
61
62
63
def print_init_api(gl):
64
    sub_title = 'Init Glances Python API'
65
    print(sub_title)
66
    print('-' * len(sub_title))
67
    print('')
68
    print('Init the Glances API:')
69
    print('')
70
    print('.. code-block:: python')
71
    print('')
72
    printtab('>>> from glances import api')
73
    printtab('>>> gl = api.GlancesAPI()')
74
    print('')
75
76
77
def print_plugins_list(gl):
78
    sub_title = 'Get Glances plugins list'
79
    print(sub_title)
80
    print('-' * len(sub_title))
81
    print('')
82
    print('Get the plugins list:')
83
    print('')
84
    print('.. code-block:: python')
85
    print('')
86
    printtab('>>> gl.plugins()')
87
    printtab(f'{gl.plugins()}')
88
    print('```')
89
    print('')
90
91
92
def print_plugin(gl, plugin):
93
    """Print the details of a single plugin."""
94
    sub_title = f'Glances {plugin}'
95
    print(sub_title)
96
    print('-' * len(sub_title))
97
    print('')
98
99
    stats_obj = gl.__getattr__(plugin)
100
101
    print(f'{plugin.capitalize()} stats:')
102
    print('')
103
    print('.. code-block:: python')
104
    print('')
105
    printtab(f'>>> gl.{plugin}')
106
    printtab(f'Return a {type(stats_obj)} object')
107
    if len(stats_obj.keys()) > 0 and isinstance(stats_obj[stats_obj.keys()[0]], dict):
108
        printtab(f'>>> gl.{plugin}')
109
        printtab(f'Return a dict of dict with key=<{stats_obj[stats_obj.keys()[0]]["key"]}>')
110
        printtab(f'>>> gl.{plugin}.keys()')
111
        printtab(f'{stats_obj.keys()}')
112
        printtab(f'>>> gl.{plugin}["{stats_obj.keys()[0]}"]')
113
        printtab(f'{pformat(stats_obj[stats_obj.keys()[0]])}')
114
    else:
115
        printtab(f'>>> gl.{plugin}')
116
        printtab(f'{pformat(stats_obj.stats)}')
117
        if len(stats_obj.keys()) > 0:
118
            printtab(f'>>> gl.{plugin}.keys()')
119
            printtab(f'{stats_obj.keys()}')
120
            printtab(f'>>> gl.{plugin}["{stats_obj.keys()[0]}"]')
121
            printtab(f'{pformat(stats_obj[stats_obj.keys()[0]])}')
122
    print('')
123
124
    if stats_obj.fields_description is not None:
125
        print(f'{plugin.capitalize()} fields description:')
126
        print('')
127
        for field, description in stats_obj.fields_description.items():
128
            print(f'* {field}: {description["description"]}')
129
        print('')
130
131
    print(f'{plugin.capitalize()} limits:')
132
    print('')
133
    print('.. code-block:: python')
134
    print('')
135
    printtab(f'>>> gl.{plugin}.limits')
136
    printtab(f'{pformat(gl.__getattr__(plugin).limits)}')
137
    print('')
138
139
140
def print_plugins(gl):
141
    """Print the details of all plugins."""
142
    for plugin in gl.plugins():
143
        print_plugin(gl, plugin)
144
145
146
class GlancesStdoutApiDoc:
147
    """This class manages the fields description display."""
148
149
    def __init__(self, config=None, args=None):
150
        # Init
151
        self.gl = api.GlancesAPI()
152
153
    def end(self):
154
        pass
155
156
    def update(self, stats, duration=1):
157
        """Display issue"""
158
159
        # Display header
160
        print(APIDOC_HEADER)
161
162
        # Display TL;DR section
163
        print_tldr(self.gl)
164
165
        # Init the API
166
        print_init_api(self.gl)
167
168
        # Display plugins list
169
        print_plugins_list(self.gl)
170
171
        # Loop over plugins
172
        print_plugins(self.gl)
173
174
        # Return True to exit directly (no refresh)
175
        return True
176