Passed
Push — master ( 0fd795...73442f )
by Emmanuel
14:19
created

plugins._add_plugin_from_dir()   A

Complexity

Conditions 3

Size

Total Lines 18
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 15
nop 2
dl 0
loc 18
ccs 15
cts 15
cp 1
crap 3
rs 9.65
c 0
b 0
f 0
1
"""Module used by setup.py to find plugins to load with click"""
2
3 1
import re
4 1
import subprocess
5 1
from os import listdir, path
6
7
8 1
def add_plugins():
9
    """Read the plugins directory, get the subfolders from it and look for .py files"""
10
11 1
    if path.isdir('plugins') is False:
12 1
        return []
13
14 1
    _remove_plugins()
15 1
    folders = _get_subfolders('plugins')
16
17 1
    plugins = []
18 1
    for folder in folders:
19 1
        plugins = _add_plugin_from_dir(plugins, 'plugins/{}/'.format(folder))
20
21 1
    return sorted(plugins)
22
23
24 1
def _add_plugin_from_dir(plugins: list, full_path: str):
25 1
    files = _get_files_from_folder(full_path)
26 1
    if len(files) is 0:
27 1
        print('  -> No plugin found in "{}"'.format(full_path))
28 1
        return plugins
29
30 1
    plugin_name = full_path.strip('/').split('/')[1]
31 1
    try:
32 1
        cmd_install = ['pip', 'install', '-e', full_path]
33 1
        subprocess.check_call(cmd_install, stdout=subprocess.DEVNULL)
34 1
    except Exception as error:
35 1
        msg = 'Problem installing {} (Reason: {})'.format(plugin_name[:-3], error)
36 1
        raise TypeError(msg)
37
38 1
    print('  -> Plugin "{}" added'.format(plugin_name))
39 1
    plugins.append(plugin_name)
40
41 1
    return plugins
42
43
44 1
def _get_files_from_folder(full_path: str):
45 1
    files = listdir(full_path)
46
47 1
    return [filename for filename in files if filename == 'setup.py']
48
49
50 1
def _get_subfolders(directory: str):
51 1
    subfolders = listdir(directory)
52
53 1
    return [folder for folder in subfolders if path.isdir('{}/{}'.format(directory, folder))]
54
55
56 1
def _remove_plugins():
57 1
    cmd = ['pip', 'freeze']
58 1
    res = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
59 1
    regex = re.compile('.*stakkr([0-9a-z]+).*$', re.IGNORECASE)
60
61 1
    for line in res.stdout:
62 1
        plugin = re.search(regex, line.decode())
63 1
        if plugin is None:
64 1
            continue
65
66 1
        plugin_name = 'Stakkr{}'.format(plugin.group(1))
67 1
        print('  -> Cleaning "{}"'.format(plugin_name))
68
        subprocess.check_call(['pip', 'uninstall', '-y', plugin_name], stdout=subprocess.DEVNULL)
69