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

gitman.update()   A

Complexity

Conditions 3

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3
Metric Value
cc 3
dl 0
loc 15
ccs 10
cts 10
cp 1
crap 3
rs 9.4285
1
"""Utilities to call Git commands."""
2
3 1
import os
4 1
import logging
5
6 1
from . import common
7 1
from .shell import call
8 1
from .exceptions import ShellError
9
10
11 1
log = logging.getLogger(__name__)
12
13
14 1
def git(*args, **kwargs):
15 1
    return call('git', *args, **kwargs)
16
17
18 1
def clone(repo, path, *, cache=None):
19
    """Clone a new Git repository."""
20 1
    cache = cache or os.path.expanduser("~/.gitcache")
21
22 1
    name = repo.split('/')[-1]
23 1
    if name.endswith(".git"):
24 1
        name = name[:-4]
25
26 1
    reference = os.path.join(cache, name + ".reference")
27 1
    if not os.path.isdir(reference):
28 1
        git('clone', '--mirror', repo, reference)
29
30 1
    git('clone', '--reference', reference, repo, path)
31
32
33 1
def fetch(repo, rev=None):
34
    """Fetch the latest changes from the remote repository."""
35 1
    git('remote', 'rm', 'origin', _show=False, _ignore=True)
36 1
    git('remote', 'add', 'origin', repo)
37 1
    args = ['fetch', '--tags', '--force', '--prune', 'origin']
38 1
    if rev:
39 1
        if len(rev) == 40:
40 1
            pass  # fetch only works with a SHA if already present locally
41 1
        elif '@' in rev:
42 1
            pass  # fetch doesn't work with rev-parse
43
        else:
44 1
            args.append(rev)
45 1
    git(*args)
0 ignored issues
show
Coding Style introduced by
Usage of * or ** arguments should usually be done with care.

Generally, there is nothing wrong with usage of * or ** arguments. For readability of the code base, we suggest to not over-use these language constructs though.

For more information, we can recommend this blog post from Ned Batchelder including its comments which also touches this aspect.

Loading history...
46
47
48 1
def changes(include_untracked=False, display_status=True, _show=False):
49
    """Determine if there are changes in the working tree."""
50 1
    status = False
51
52 1
    try:
53
        # refresh changes
54 1
        git('update-index', '-q', '--refresh', _show=False)
55
56
        # check for uncommitted changes
57 1
        git('diff-index', '--quiet', 'HEAD', _show=_show)
58
59
        # check for untracked files
60 1
        output = git('ls-files', '--others', '--exclude-standard',
61
                     _show=_show, _capture=True)
62
63 1
    except ShellError:
64 1
        status = True
65
66
    else:
67 1
        status = bool(output.splitlines()) and include_untracked
68
69 1
    if status and display_status:
70 1
        for line in git('status', _show=True, _capture=True).splitlines():
71 1
            common.show(line)
72
73 1
    return status
74
75
76 1
def update(rev, *, clean=True, fetch=False):  # pylint: disable=redefined-outer-name
77
    """Update the working tree to the specified revision."""
78 1
    hide = {'_show': False, '_ignore': True}
79
80 1
    git('stash', **hide)
0 ignored issues
show
Coding Style introduced by
Usage of * or ** arguments should usually be done with care.

Generally, there is nothing wrong with usage of * or ** arguments. For readability of the code base, we suggest to not over-use these language constructs though.

For more information, we can recommend this blog post from Ned Batchelder including its comments which also touches this aspect.

Loading history...
81 1
    if clean:
82 1
        git('clean', '--force', '-d', '-x', _show=False)
83
84 1
    rev = _get_sha_from_rev(rev)
85 1
    git('checkout', '--force', rev)
86 1
    git('branch', '--set-upstream-to', 'origin/' + rev, **hide)
0 ignored issues
show
Coding Style introduced by
Usage of * or ** arguments should usually be done with care.

Generally, there is nothing wrong with usage of * or ** arguments. For readability of the code base, we suggest to not over-use these language constructs though.

For more information, we can recommend this blog post from Ned Batchelder including its comments which also touches this aspect.

Loading history...
87
88 1
    if fetch:
89
        # if `rev` was a branch it might be tracking something older
90 1
        git('pull', '--ff-only', '--no-rebase', **hide)
0 ignored issues
show
Coding Style introduced by
Usage of * or ** arguments should usually be done with care.

Generally, there is nothing wrong with usage of * or ** arguments. For readability of the code base, we suggest to not over-use these language constructs though.

For more information, we can recommend this blog post from Ned Batchelder including its comments which also touches this aspect.

Loading history...
91
92
93 1
def get_url():
94
    """Get the current repository's URL."""
95 1
    return git('config', '--get', 'remote.origin.url',
96
               _show=False, _capture=True)
97
98
99 1
def get_hash(_show=False):
100
    """Get the current working tree's hash."""
101 1
    return git('rev-parse', 'HEAD', _show=_show, _capture=True)
102
103
104 1
def get_tag():
105
    """Get the current working tree's tag (if on a tag)."""
106 1
    return git('describe', '--tags', '--exact-match',
107
               _show=False, _ignore=True, _capture=True)
108
109
110 1
def get_branch():
111
    """Get the current working tree's branch."""
112 1
    return git('rev-parse', '--abbrev-ref', 'HEAD',
113
               _show=False, _capture=True)
114
115
116 1
def _get_sha_from_rev(rev):
117
    """Get a rev-parse string's hash."""
118 1
    if '@{' in rev:  # TODO: use regex for this
119 1
        parts = rev.split('@')
120 1
        branch = parts[0]
121 1
        date = parts[1].strip("{}")
122 1
        git('checkout', '--force', branch, _show=False)
123 1
        rev = git('rev-list', '-n', '1', '--before={!r}'.format(date),
124
                  branch, _show=False, _capture=True)
125
    return rev
126