summaryrefslogtreecommitdiff
path: root/hacking/report.py
blob: 9c5d52d6ddf9e4b79a02d02222f40a203f14aae3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
#!/usr/bin/env python
# PYTHON_ARGCOMPLETE_OK
"""A tool to aggregate data about Ansible source and testing into a sqlite DB for reporting."""

from __future__ import (absolute_import, print_function)

import argparse
import json
import os
import sqlite3
import sys
import yaml

DATABASE_PATH = os.path.expanduser('~/.ansible/report.db')
BASE_PATH = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) + '/'
ANSIBLE_PATH = os.path.join(BASE_PATH, 'lib')
ANSIBLE_TEST_PATH = os.path.join(BASE_PATH, 'test/lib')

if ANSIBLE_PATH not in sys.path:
    sys.path.insert(0, ANSIBLE_PATH)

if ANSIBLE_TEST_PATH not in sys.path:
    sys.path.insert(0, ANSIBLE_TEST_PATH)

from ansible.module_utils.urls import open_url
from ansible.parsing.plugin_docs import read_docstring

from ansible_test._internal.target import walk_integration_targets


def main():
    os.chdir(BASE_PATH)

    args = parse_args()
    args.func()


def parse_args():
    try:
        import argcomplete
    except ImportError:
        argcomplete = None

    parser = argparse.ArgumentParser()

    subparsers = parser.add_subparsers(metavar='COMMAND')
    subparsers.required = True  # work-around for python 3 bug which makes subparsers optional

    populate = subparsers.add_parser('populate',
                                     help='populate report database')

    populate.set_defaults(func=populate_database)

    query = subparsers.add_parser('query',
                                  help='query report database')

    query.set_defaults(func=query_database)

    if argcomplete:
        argcomplete.autocomplete(parser)

    args = parser.parse_args()

    return args


def query_database():
    if not os.path.exists(DATABASE_PATH):
        sys.exit('error: Database not found. Did you run `report.py populate` first?')

    os.execvp('sqlite3', ('sqlite3', DATABASE_PATH))


def populate_database():
    populate_modules()
    populate_coverage()
    populate_integration_targets()


def populate_modules():
    module_dir = os.path.join(BASE_PATH, 'lib/ansible/modules/')

    modules_rows = []
    module_statuses_rows = []

    for root, dir_names, file_names in os.walk(module_dir):
        for file_name in file_names:
            module, extension = os.path.splitext(file_name)

            if module == '__init__' or extension != '.py':
                continue

            if module.startswith('_'):
                module = module[1:]

            namespace = os.path.join(root.replace(module_dir, '')).replace('/', '.')

            path = os.path.join(root, file_name)

            result = read_docstring(path)

            metadata = result['metadata']
            doc = result['doc']

            if not metadata:
                if module == 'async_wrapper':
                    continue

                raise Exception('no metadata for: %s' % path)

            modules_rows.append(dict(
                module=module,
                namespace=namespace,
                path=path.replace(BASE_PATH, ''),
                supported_by=metadata['supported_by'],
                version_added=str(doc.get('version_added', '')) if doc else '',
            ))

            for status in metadata['status']:
                module_statuses_rows.append(dict(
                    module=module,
                    status=status,
                ))

    populate_data(dict(
        modules=dict(
            rows=modules_rows,
            schema=(
                ('module', 'TEXT'),
                ('namespace', 'TEXT'),
                ('path', 'TEXT'),
                ('supported_by', 'TEXT'),
                ('version_added', 'TEXT'),
            )),
        module_statuses=dict(
            rows=module_statuses_rows,
            schema=(
                ('module', 'TEXT'),
                ('status', 'TEXT'),
            )),
    ))


def populate_coverage():
    response = open_url('https://codecov.io/api/gh/ansible/ansible/tree/devel/?src=extension')
    data = json.load(response)
    files = data['commit']['report']['files']
    coverage_rows = []

    for path, data in files.items():
        report = data['t']
        coverage_rows.append(dict(
            path=path,
            coverage=float(report['c']),
            lines=report['n'],
            hit=report['h'],
            partial=report['p'],
            missed=report['m'],
        ))

    populate_data(dict(
        coverage=dict(
            rows=coverage_rows,
            schema=(
                ('path', 'TEXT'),
                ('coverage', 'REAL'),
                ('lines', 'INTEGER'),
                ('hit', 'INTEGER'),
                ('partial', 'INTEGER'),
                ('missed', 'INTEGER'),
            )),
    ))


def populate_integration_targets():
    targets = list(walk_integration_targets())

    integration_targets_rows = [dict(
        target=target.name,
        type=target.type,
        path=target.path,
        script_path=target.script_path,
    ) for target in targets]

    integration_target_aliases_rows = [dict(
        target=target.name,
        alias=alias,
    ) for target in targets for alias in target.aliases]

    integration_target_modules_rows = [dict(
        target=target.name,
        module=module,
    ) for target in targets for module in target.modules]

    populate_data(dict(
        integration_targets=dict(
            rows=integration_targets_rows,
            schema=(
                ('target', 'TEXT'),
                ('type', 'TEXT'),
                ('path', 'TEXT'),
                ('script_path', 'TEXT'),
            )),
        integration_target_aliases=dict(
            rows=integration_target_aliases_rows,
            schema=(
                ('target', 'TEXT'),
                ('alias', 'TEXT'),
            )),
        integration_target_modules=dict(
            rows=integration_target_modules_rows,
            schema=(
                ('target', 'TEXT'),
                ('module', 'TEXT'),
            )),
    ))


def create_table(cursor, name, columns):
    schema = ', '.join('%s %s' % column for column in columns)

    cursor.execute('DROP TABLE IF EXISTS %s' % name)
    cursor.execute('CREATE TABLE %s (%s)' % (name, schema))


def populate_table(cursor, rows, name, columns):
    create_table(cursor, name, columns)

    values = ', '.join([':%s' % column[0] for column in columns])

    for row in rows:
        cursor.execute('INSERT INTO %s VALUES (%s)' % (name, values), row)


def populate_data(data):
    connection = sqlite3.connect(DATABASE_PATH)
    cursor = connection.cursor()

    for table in data:
        populate_table(cursor, data[table]['rows'], table, data[table]['schema'])

    connection.commit()
    connection.close()


if __name__ == '__main__':
    main()