Completed
Push — develop ( 51e53a...40e7fd )
by Jace
15s queued 11s
created

gitman.models.source.Source.identify()   B

Complexity

Conditions 8

Size

Total Lines 42
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 8

Importance

Changes 0
Metric Value
cc 8
eloc 31
nop 4
dl 0
loc 42
ccs 7
cts 7
cp 1
crap 8
rs 7.2693
c 0
b 0
f 0
1 1
import os
2 1
from dataclasses import dataclass, field
3 1
from typing import List, Optional
4
5 1
import log
6 1
7
from .. import common, exceptions, git, shell
8 1
9
10
@dataclass
11 1
class Source:
12
    """A dictionary of `git` and `ln` arguments."""
13
14 1
    name: Optional[str]
15 1
    type: str
16 1
    repo: str
17 1
    sparse_paths: List[str] = field(default_factory=list)
18 1
    rev: str = 'master'
19 1
    link: Optional[str] = None
20
    scripts: List[str] = field(default_factory=list)
21
22 1
    DIRTY = '<dirty>'
23 1
    UNKNOWN = '<unknown>'
24
25 1
    def __post_init__(self):
26 1
        if self.name is None:
27 1
            self.name = self._infer_name(self.repo)
28 1
        self.type = self.type or 'git'
29 1
30 1
    def __repr__(self):
31 1
        return "<source {}>".format(self)
32
33 1
    def __str__(self):
34 1
        pattern = "['{t}'] '{r}' @ '{v}' in '{d}'"
35 1
        if self.link:
36 1
            pattern += " <- '{s}'"
37
        return pattern.format(
38 1
            t=self.type, r=self.repo, v=self.rev, d=self.name, s=self.link
39 1
        )
40
41 1
    def __eq__(self, other):
42 1
        return self.name == other.name
43 1
44 1
    def __ne__(self, other):
45 1
        return self.name != other.name
46
47 1
    def __lt__(self, other):
48 1
        return self.name < other.name
49
50 1
    def update_files(
51 1
        self,
52
        force=False,
53 1
        force_interactive=False,
54 1
        fetch=False,
55
        clean=True,
56 1
        skip_changes=False,
57
    ):
58 1
        """Ensure the source matches the specified revision."""
59
        log.info("Updating source files...")
60
61 1
        # Clone the repository if needed
62 1
        assert self.name
63
        if not os.path.exists(self.name):
64
            git.clone(
65 1
                self.type,
66 1
                self.repo,
67 1
                self.name,
68
                sparse_paths=self.sparse_paths,
69
                rev=self.rev,
70 1
            )
71 1
72 1
        # Enter the working tree
73
        shell.cd(self.name)
74
        if not git.valid():
75
            if force:
76
                git.rebuild(self.type, self.repo)
77 1
                fetch = True
78
            else:
79
                raise self._invalid_repository
80 1
81
        # Check for uncommitted changes
82
        if not force:
83 1
            log.debug("Confirming there are no uncommitted changes...")
84
            if skip_changes:
85 1
                if git.changes(
86
                    self.type, include_untracked=clean, display_status=False
87 1
                ):
88 1
                    common.show(
89
                        f'Skipped update due to uncommitted changes in {os.getcwd()}',
90 1
                        color='git_changes',
91
                    )
92 1
                    return
93
            elif force_interactive:
94
                if git.changes(
95
                    self.type, include_untracked=clean, display_status=False
96 1
                ):
97 1
                    common.show(
98
                        f'Uncommitted changes found in {os.getcwd()}',
99 1
                        color='git_changes',
100 1
                    )
101 1
102 1
                    while True:
103 1
                        yn_input = str(
104
                            input("Do you want to overwrite? (Y/N)[Y]: ")
105 1
                        ).rstrip('\r\n')
106 1
107
                        if yn_input.lower() == "y" or not yn_input:
108 1
                            break
109
110 1
                        if yn_input.lower() == "n":
111 1
                            common.show(
112
                                f'Skipped update in {os.getcwd()}', color='git_changes'
113
                            )
114 1
                            return
115 1
116
            else:
117
                if git.changes(self.type, include_untracked=clean):
118
                    raise exceptions.UncommittedChanges(
119 1
                        f'Uncommitted changes in {os.getcwd()}'
120 1
                    )
121 1
122 1
        # Fetch the desired revision
123
        if fetch or git.is_fetch_required(self.type, self.rev):
124
            git.fetch(self.type, self.repo, self.name, rev=self.rev)
125 1
126 1
        # Update the working tree to the desired revision
127 1
        git.update(
128 1
            self.type, self.repo, self.name, fetch=fetch, clean=clean, rev=self.rev
129 1
        )
130 1
131 1
    def create_link(self, root, force=False):
132 1
        """Create a link from the target name to the current directory."""
133
        if not self.link:
134 1
            return
135 1
136
        log.info("Creating a symbolic link...")
137
138 1
        target = os.path.join(root, self.link)
139
        source = os.path.relpath(os.getcwd(), os.path.dirname(target))
140 1
141
        if os.path.islink(target):
142 1
            os.remove(target)
143
        elif os.path.exists(target):
144 1
            if force:
145 1
                shell.rm(target)
146 1
            else:
147
                msg = "Preexisting link location at {}".format(target)
148 1
                raise exceptions.UncommittedChanges(msg)
149 1
150 1
        shell.ln(source, target)
151 1
152 1
    def run_scripts(self, force=False):
153 1
        log.info("Running install scripts...")
154
155
        # Enter the working tree
156
        shell.cd(self.name)
157
        if not git.valid():
158
            raise self._invalid_repository
159 1
160 1
        # Check for scripts
161 1
        if not self.scripts or not self.scripts[0]:
162 1
            common.show("(no scripts to run)", color='shell_info')
163
            common.newline()
164 1
            return
165
166 1
        # Run all scripts
167
        for script in self.scripts:
168
            try:
169
                lines = shell.call(script, _shell=True)
170 1
            except exceptions.ShellError as exc:
171
                common.show(*exc.output, color='shell_error')
172 1
                cmd = exc.program
173
                if force:
174 1
                    log.debug("Ignored error from call to '%s'", cmd)
175 1
                else:
176 1
                    msg = "Command '{}' failed in {}".format(cmd, os.getcwd())
177
                    raise exceptions.ScriptFailure(msg)
178 1
            else:
179
                common.show(*lines, color='shell_output')
180 1
        common.newline()
181
182 1
    def identify(self, allow_dirty=True, allow_missing=True, skip_changes=False):
183 1
        """Get the path and current repository URL and hash."""
184 1
        assert self.name
185
        if os.path.isdir(self.name):
186 1
187
            shell.cd(self.name)
188 1
            if not git.valid():
189 1
                raise self._invalid_repository
190 1
191
            path = os.getcwd()
192
            url = git.get_url(self.type)
193
            if git.changes(
194
                self.type,
195
                display_status=not allow_dirty and not skip_changes,
196
                _show=not skip_changes,
197
            ):
198
199
                if allow_dirty:
200
                    common.show(self.DIRTY, color='git_dirty', log=False)
201
                    common.newline()
202
                    return path, url, self.DIRTY
203
204
                if skip_changes:
205
                    msg = ("Skipped lock due to uncommitted changes " "in {}").format(
206
                        os.getcwd()
207
                    )
208
                    common.show(msg, color='git_changes')
209
                    common.newline()
210
                    return path, url, self.DIRTY
211
212
                msg = "Uncommitted changes in {}".format(os.getcwd())
213
                raise exceptions.UncommittedChanges(msg)
214
215
            rev = git.get_hash(self.type, _show=True)
216
            common.show(rev, color='git_rev', log=False)
217
            common.newline()
218
            return path, url, rev
219
220
        if allow_missing:
221
            return os.getcwd(), '<missing>', self.UNKNOWN
222
223
        raise self._invalid_repository
224
225
    def lock(self, rev=None, allow_dirty=False, skip_changes=False):
226
        """Create a locked source object.
227
228
        Return a locked version of the current source if not dirty
229
        otherwise None.
230
        """
231
232
        if rev is None:
233
            _, _, rev = self.identify(
234
                allow_dirty=allow_dirty, allow_missing=False, skip_changes=skip_changes
235
            )
236
237
        if rev == self.DIRTY:
238
            return None
239
240
        source = self.__class__(
241
            type=self.type,
242
            repo=self.repo,
243
            name=self.name,
244
            rev=rev,
245
            link=self.link,
246
            scripts=self.scripts,
247
            sparse_paths=self.sparse_paths,
248
        )
249
        return source
250
251
    @property
252
    def _invalid_repository(self):
253
        assert self.name
254
        path = os.path.join(os.getcwd(), self.name)
255
        msg = """
256
257
            Not a valid repository: {}
258
            During install you can rebuild a repo with a missing .git directory using the --force option
259
            """.format(
260
            path
261
        )
262
        return exceptions.InvalidRepository(msg)
263
264
    @staticmethod
265
    def _infer_name(repo):
266
        filename = repo.split('/')[-1]
267
        name = filename.split('.')[0]
268
        return name
269