Completed
Pull Request — develop (#109)
by Jace
02:18
created

gitman.models.Source.__lt__()   A

Complexity

Conditions 1

Size

Total Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1
Metric Value
cc 1
dl 0
loc 2
ccs 2
cts 2
cp 1
crap 1
rs 10
1
"""Wrappers for the dependency configuration files."""
0 ignored issues
show
Bug introduced by
There seems to be a cyclic import (gitman.models -> gitman.models.config).

Cyclic imports may cause partly loaded modules to be returned. This might lead to unexpected runtime behavior which is hard to debug.

Loading history...
2
3 1
import os
4 1
import logging
5
6 1
import yorm
0 ignored issues
show
Configuration introduced by
The import yorm could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
7 1
from yorm.types import String, AttributeDictionary
0 ignored issues
show
Configuration introduced by
The import yorm.types could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
8
9 1
from .. import common
10 1
from .. import git
11 1
from .. import shell
12 1
from ..exceptions import InvalidConfig, InvalidRepository, UncommittedChanges
13
14
15 1
log = logging.getLogger(__name__)
16
17
18 1
@yorm.attr(dir=String)
19 1
@yorm.attr(repo=String)
20 1
@yorm.attr(link=String)
21 1
@yorm.attr(rev=String)
22 1
class Source(AttributeDictionary):
23
    """A dictionary of `git` and `ln` arguments."""
24
25 1
    DIRTY = '<dirty>'
26 1
    UNKNOWN = '<unknown>'
27
28 1
    def __init__(self, repo, name, rev='master', link=None):
29 1
        super().__init__()
30 1
        self.repo = repo
31 1
        self.dir = name
32 1
        self.rev = rev
33 1
        self.link = link
34 1
        if not self.repo:
35 1
            raise InvalidConfig("'repo' missing on {}".format(repr(self)))
36 1
        if not self.dir:
37 1
            raise InvalidConfig("'dir' missing on {}".format(repr(self)))
38
39 1
    def __repr__(self):
40 1
        return "<source {}>".format(self)
41
42 1
    def __str__(self):
43 1
        fmt = "'{r}' @ '{v}' in '{d}'"
44 1
        if self.link:
45 1
            fmt += " <- '{s}'"
46 1
        return fmt.format(r=self.repo, v=self.rev, d=self.dir, s=self.link)
47
48 1
    def __eq__(self, other):
49 1
        return self.dir == other.dir
50
51 1
    def __ne__(self, other):
52 1
        return self.dir != other.dir
53
54 1
    def __lt__(self, other):
55 1
        return self.dir < other.dir
56
57 1
    def update_files(self, force=False, fetch=False, clean=True):
58
        """Ensure the source matches the specified revision."""
59 1
        log.info("Updating source files...")
60
61
        # Enter the working tree
62 1
        if not os.path.exists(self.dir):
63 1
            log.debug("Creating a new repository...")
64 1
            git.clone(self.repo, self.dir)
65 1
        shell.cd(self.dir)
66
67
        # Check for uncommitted changes
68 1
        if not force:
69 1
            log.debug("Confirming there are no uncommitted changes...")
70 1
            if git.changes(include_untracked=clean):
71
                common.show()
72
                msg = "Uncommitted changes: {}".format(os.getcwd())
73
                raise UncommittedChanges(msg)
74
75
        # Fetch the desired revision
76 1
        if fetch or self.rev not in (git.get_branch(),
77
                                     git.get_hash(),
78
                                     git.get_tag()):
79 1
            git.fetch(self.repo, self.rev)
80
81
        # Update the working tree to the desired revision
82 1
        git.update(self.rev, fetch=fetch, clean=clean)
83
84 1
    def create_link(self, root, force=False):
85
        """Create a link from the target name to the current directory."""
86 1
        if self.link:
87 1
            log.info("Creating a symbolic link...")
88 1
            target = os.path.join(root, self.link)
89 1
            source = os.path.relpath(os.getcwd(), os.path.dirname(target))
90 1
            if os.path.islink(target):
91
                os.remove(target)
92 1
            elif os.path.exists(target):
93 1
                if force:
94 1
                    shell.rm(target)
95
                else:
96 1
                    common.show()
97 1
                    msg = "Preexisting link location: {}".format(target)
98 1
                    raise UncommittedChanges(msg)
99 1
            shell.ln(source, target)
100
101 1
    def identify(self, allow_dirty=True, allow_missing=True):
102
        """Get the path and current repository URL and hash."""
103 1
        if os.path.isdir(self.dir):
104
105 1
            shell.cd(self.dir)
106
107 1
            path = os.getcwd()
108 1
            url = git.get_url()
109 1
            if git.changes(display_status=not allow_dirty, _show=True):
110
                revision = self.DIRTY
111
                if not allow_dirty:
112
                    common.show()
113
                    msg = "Uncommitted changes: {}".format(os.getcwd())
114
                    raise UncommittedChanges(msg)
115
            else:
116 1
                revision = git.get_hash(_show=True)
117 1
            common.show(revision, log=False)
118
119 1
            return path, url, revision
120
121 1
        elif allow_missing:
122
123 1
            return os.getcwd(), '<missing>', self.UNKNOWN
124
125
        else:
126
127 1
            path = os.path.join(os.getcwd(), self.dir)
128 1
            msg = "Not a valid repository: {}".format(path)
129 1
            raise InvalidRepository(msg)
130
131 1
    def lock(self):
132
        """Return a locked version of the current source."""
133 1
        _, _, revision = self.identify(allow_missing=False)
134 1
        source = self.__class__(self.repo, self.dir, revision, self.link)
135
        return source
136