Completed
Push — develop ( a3b333...e4fb95 )
by Jace
10s
created

clone()   B

Complexity

Conditions 6

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 6

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 6
dl 0
loc 29
ccs 19
cts 19
cp 1
crap 6
rs 7.5384
c 2
b 0
f 0
1
"""Utilities to call Git commands."""
2
3 1
import os
4 1
import logging
5 1
from contextlib import suppress
6
7 1
from . import common, settings
8 1
from .shell import call
9 1
from .exceptions import ShellError
10
11
12 1
log = logging.getLogger(__name__)
13
14
15 1
def git(*args, **kwargs):
16 1
    return call('git', *args, **kwargs)
17
18
19 1
def clone(repo, path, *, cache=settings.CACHE, sparse_paths=None, rev=None):
20
    """Clone a new Git repository."""
21 1
    log.debug("Creating a new repository...")
22
23 1
    name = repo.split('/')[-1]
24 1
    if name.endswith(".git"):
25 1
        name = name[:-4]
26
27 1
    reference = os.path.join(cache, name + ".reference")
28 1
    if not os.path.isdir(reference):
29 1
        git('clone', '--mirror', repo, reference)
30
31 1
    normpath = os.path.normpath(path)
32
    if sparse_paths:
33
        os.mkdir(normpath)
34 1
        git('-C', normpath, 'init')
35
        git('-C', normpath, 'config', 'core.sparseCheckout', 'true')
36 1
        git('-C', normpath, 'remote', 'add', '-f', 'origin', reference)
37 1
38 1
        with open("%s/%s/.git/info/sparse-checkout" % (os.getcwd(), normpath), 'w') as fd:
39 1
            fd.writelines(sparse_paths)
40 1
        with open("%s/%s/.git/objects/info/alternates" % (os.getcwd(), normpath), 'w') as fd:
41 1
            fd.write("%s/objects" % reference)
42 1
43
        # We use directly the revision requested here in order to respect,
44 1
        # that not all repos have `master` as their default branch
45 1
        git('-C', normpath, 'pull', 'origin', rev)
46
    else:
47
        git('clone', '--reference', reference, repo, os.path.normpath(path))
48 1
49
50 1
def fetch(repo, rev=None):
51
    """Fetch the latest changes from the remote repository."""
52 1
    git('remote', 'set-url', 'origin', repo)
53 1
    args = ['fetch', '--tags', '--force', '--prune', 'origin']
54 1
    if rev:
55 1
        if len(rev) == 40:
56
            pass  # fetch only works with a SHA if already present locally
57 1
        elif '@' in rev:
58
            pass  # fetch doesn't work with rev-parse
59
        else:
60 1
            args.append(rev)
61
    git(*args)
62 1
63
64 1
def valid():
65
    """Confirm the current directory is a valid working tree."""
66 1
    log.debug("Checking for a valid working tree...")
67
68
    try:
69 1
        git('rev-parse', '--is-inside-work-tree', _show=False)
70
    except ShellError:
71
        return False
72 1
    else:
73
        return True
74 1
75 1
76
def changes(include_untracked=False, display_status=True, _show=False):
77
    """Determine if there are changes in the working tree."""
78 1
    status = False
79
80 1
    try:
81 1
        # Refresh changes
82 1
        git('update-index', '-q', '--refresh', _show=False)
83 1
84
        # Check for uncommitted changes
85 1
        git('diff-index', '--quiet', 'HEAD', _show=_show)
86
87
        # Check for untracked files
88 1
        lines = git('ls-files', '--others', '--exclude-standard', _show=_show)
89
90 1
    except ShellError:
91
        status = True
92 1
93 1
    else:
94 1
        status = bool(lines) and include_untracked
95
96 1
    if status and display_status:
97 1
        with suppress(ShellError):
98 1
            lines = git('status', _show=True)
99
            common.show(*lines, color='git_changes')
100 1
101
    return status
102 1
103
104
def update(rev, *, clean=True, fetch=False):  # pylint: disable=redefined-outer-name
105 1
    """Update the working tree to the specified revision."""
106
    hide = {'_show': False, '_ignore': True}
107 1
108
    git('stash', **hide)
109
    if clean:
110 1
        git('clean', '--force', '-d', '-x', _show=False)
111
112 1
    rev = _get_sha_from_rev(rev)
113
    git('checkout', '--force', rev)
114
    git('branch', '--set-upstream-to', 'origin/' + rev, **hide)
115 1
116
    if fetch:
117 1
        # if `rev` was a branch it might be tracking something older
118
        git('pull', '--ff-only', '--no-rebase', **hide)
119
120
121 1
def get_url():
122
    """Get the current repository's URL."""
123 1
    return git('config', '--get', 'remote.origin.url', _show=False)[0]
124
125
126 1
def get_hash(_show=False):
127
    """Get the current working tree's hash."""
128 1
    return git('rev-parse', 'HEAD', _show=_show)[0]
129 1
130 1
131 1
def get_tag():
132 1
    """Get the current working tree's tag (if on a tag)."""
133 1
    return git('describe', '--tags', '--exact-match',
134
               _show=False, _ignore=True)[0]
135 1
136
137
def get_branch():
138
    """Get the current working tree's branch."""
139
    return git('rev-parse', '--abbrev-ref', 'HEAD', _show=False)[0]
140
141
142
def _get_sha_from_rev(rev):
143
    """Get a rev-parse string's hash."""
144
    if '@{' in rev:  # TODO: use regex for this
145
        parts = rev.split('@')
146
        branch = parts[0]
147
        date = parts[1].strip("{}")
148
        git('checkout', '--force', branch, _show=False)
149
        rev = git('rev-list', '-n', '1', '--before={!r}'.format(date),
150
                  branch, _show=False)[0]
151
    return rev
152