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

gitman.Source.update_files()   B

Complexity

Conditions 6

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

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