Passed
Branch v4.0-dev (e005f1)
by Emmanuel
05:49
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 0
CRAP Score 12

Importance

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