aboutsummaryrefslogtreecommitdiff
path: root/cleantools/clmgr.py
blob: cad6b95a4058ee73658dfec876379625e8777e4b (plain) (blame)
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
#!/usr/bin/env python3
import os

import click
from git import Repo
from setuptools_scm import get_version
import shutil

from . import settings

__all__ = ['Library', 'main']

class Library():
    """A Clean library"""
    def __init__(self, path):
        self.path = Library.get_path(path)

    def upgrade(self):
        repo = Repo(self.path)
        old_sha = repo.head.commit.hexsha
        repo.remotes.origin.pull()
        new_sha = repo.head.commit.hexsha
        return old_sha != new_sha

    def remove(self):
        shutil.rmtree(self.path)

    @staticmethod
    def get_path(lib):
        """Get the path of a library in the installation dir"""
        install_dir = settings.read()['General']['install_dir']
        for path in settings.get_search_paths():
            if os.path.isdir(os.path.join(path, lib):
                return os.path.join(path, lib)
        raise ValueError('\'%s\': no such library' % lib)

    @staticmethod
    def clone(repo, local_dir):
        """New library by cloning a repo to the installation dir"""
        install_dir = settings.read()['General']['install_dir']
        settings.make_install_dir(install_dir)
        Repo.clone_from(repo, os.path.join(install_dir, local_dir)
        return Library(local_dir)

@click.group()
def cli():
    pass

@cli.command('version')
def cli_version():
    """Print clmgr's version."""
    print(get_version())

@cli.command('init')
@click.argument('install_dir', type=click.Path(),
        metavar='install_dir', default='~/.clmgr')
def cli_init(install_dir):
    """Initialise the installation directory."""
    settings.init(install_dir)

@cli.command('install')
@click.option('--abs/--github',
        help='Use an absolute path (default: use GitHub)')
@click.argument('repo', metavar='repo')
@click.argument('local_dir', metavar='local_dir', required=False)
def cli_install(abs, repo, local_dir):
    """Clone a repository.

    If local_dir is empty, the last part of repo will be used.
    
    Examples:
    
    \b
        clmgr install username/MyLibrary (local_dir will be MyLibrary)
        clmgr install --abs /var/git/my-library LocalName"""
    if local_dir == None:
        local_dir = list(filter(lambda x: len(x)>0, repo.split(os.sep)))[-1]
        click.secho('No local_dir given, using \'%s\'' % local_dir, 
                err=True, fg='yellow')
    
    if abs:
        Library.clone(repo, local_dir)
    else:
        Library.clone('https://github.com/' + repo, local_dir)

    click.secho('%s installed as %s.' % (repo, local_dir), fg='green')

@cli.command('upgrade')
@click.argument('library')
def cli_upgrade(library):
    """Upgrade an installed library."""
    if Library(library).upgrade():
        click.secho('%s upgraded.' % library, fg='green')
    else:
        click.secho('%s is already the newest version.' % library, fg='yellow')

@cli.command('remove')
@click.argument('library')
def cli_remove(library):
    """Remove an installed library."""
    Library(library).remove()
    click.secho('%s removed.' % library, fg='green')

@cli.command('echo')
@click.option('--indent/--no-indent', help='Indent hierarchically')
@click.argument('what', metavar='what', default='')
def cli_echo(indent, what):
    """Give information about settings.
    
    Examples:
    
    \b
        clmgr echo
        clmgr echo --indent
        clmgr echo General.install_dir

    Magic examples:

    \b
        clmgr echo search_path"""
    if what == 'search_path':
        click.echo('\n'.join(settings.get_search_paths()))
    else:
        settings_path = what.split('.')
        config = dict(settings.read())
        for name in [p for p in settings_path if p != '']:
            try:
                config = dict(config[name])
            except KeyError:
                click.echo('No setting \'%s\'' % name, err=True)
                return
        settings.print_config(config, indent_step=2 if indent else 0)

def main():
    cli()

if __name__ == '__main__':
    main()