Passed
Pull Request — develop (#168)
by
unknown
02:28
created

gitman.git.get_hash()   A

Complexity

Conditions 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 5
nop 2
dl 0
loc 8
ccs 0
cts 0
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
"""Utilities to call Git commands."""
2
3 1
import logging
4 1
import os
5 1
import re
6
from contextlib import suppress
7 1
8 1
import shutil
9 1
10
from . import common, settings
11
from .exceptions import ShellError
12 1
from .shell import call
13
14
15 1
log = logging.getLogger(__name__)
16 1
17
18
def git(*args, **kwargs):
19 1
    return call('git', *args, **kwargs)
20
21 1
def gitsvn(*args, **kwargs):
22
    return call('git', 'svn', *args, **kwargs) 
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
23 1
24 1
def clone(type, repo, path, *, cache=settings.CACHE, sparse_paths=None, rev=None):
25 1
    """Clone a new Git repository."""
26
    log.debug("Creating a new repository...")
27 1
28 1
    if type == 'git-svn':
29 1
        # just the preperation for the svn deep clone / checkout here (clone will be made in update function to simplify source.py).
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (132/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
30
        os.makedirs(path)
31 1
        return
32
33
    assert type == 'git'
34 1
35
    name = repo.split('/')[-1]
36 1
    if name.endswith(".git"):
37 1
        name = name[:-4]
38 1
39 1
    reference = os.path.join(cache, name + ".reference")
40 1
    if not os.path.isdir(reference):
41 1
        git('clone', '--mirror', repo, reference)
42 1
43
    normpath = os.path.normpath(path)
44 1
    if sparse_paths:
45 1
        os.mkdir(normpath)
46
        git('-C', normpath, 'init')
47
        git('-C', normpath, 'config', 'core.sparseCheckout', 'true')
48 1
        git('-C', normpath, 'remote', 'add', '-f', 'origin', reference)
49
50 1
        with open("%s/%s/.git/info/sparse-checkout" %
51
                  (os.getcwd(), normpath), 'w') as fd:
52 1
            fd.writelines(sparse_paths)
53 1
        with open("%s/%s/.git/objects/info/alternates" %
54 1
                  (os.getcwd(), normpath), 'w') as fd:
55 1
            fd.write("%s/objects" % reference)
56
57 1
        # We use directly the revision requested here in order to respect,
58
        # that not all repos have `master` as their default branch
59
        git('-C', normpath, 'pull', 'origin', rev)
60 1
    else:
61
        git('clone', '--reference', reference, repo, os.path.normpath(path))
62 1
63
64 1
65
def is_sha(rev):
66 1
    """Heuristically determine whether a revision corresponds to a commit SHA.
67
68
    Any sequence of 7 to 40 hexadecimal digits will be recognized as a
69 1
    commit SHA. The minimum of 7 digits is not an arbitrary choice, it
70
    is the default length for short SHAs in Git.
71
    """
72 1
    return re.match('^[0-9a-f]{7,40}$', rev) is not None
73
74 1
75 1
def fetch(type, repo, path, rev=None):
0 ignored issues
show
Unused Code introduced by
The argument path seems to be unused.
Loading history...
76
    """Fetch the latest changes from the remote repository."""
77
    
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
78 1
    if type == 'git-svn':
79
        # deep clone happens in update function
80 1
        return
81 1
    
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
82 1
    assert type == 'git'
83 1
84
    git('remote', 'set-url', 'origin', repo)
85 1
    args = ['fetch', '--tags', '--force', '--prune', 'origin']
86
    if rev:
87
        if is_sha(rev):
88 1
            pass  # fetch only works with a SHA if already present locally
89
        elif '@' in rev:
90 1
            pass  # fetch doesn't work with rev-parse
91
        else:
92 1
            args.append(rev)
93 1
    git(*args)
94 1
95
96 1
def valid():
97 1
    """Confirm the current directory is a valid working tree."""
98 1
    log.debug("Checking for a valid working tree...")
99
100 1
    try:
101
        git('rev-parse', '--is-inside-work-tree', _show=False)
102 1
    except ShellError:
103
        return False
104
    else:
105 1
        return True
106
107 1
108
def changes(type, include_untracked=False, display_status=True, _show=False):
109
    """Determine if there are changes in the working tree."""
110 1
    status = False
111
112 1
    if type == 'git-svn':
113
        # ignore changes in case of git-svn
114
        return status
115 1
116
    assert type == 'git'
117 1
    
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
118
    try:
119
        # Refresh changes
120
        git('update-index', '-q', '--refresh', _show=False)
121 1
122
        # Check for uncommitted changes
123 1
        git('diff-index', '--quiet', 'HEAD', _show=_show)
124
125
        # Check for untracked files
126 1
        lines = git('ls-files', '--others', '--exclude-standard', _show=_show)
127
128 1
    except ShellError:
129 1
        status = True
130 1
131 1
    else:
132 1
        status = bool(lines) and include_untracked
133 1
134
    if status and display_status:
135 1
        with suppress(ShellError):
136
            lines = git('status', _show=True)
137
            common.show(*lines, color='git_changes')
138
139
    return status
140
141
142
def update(type, repo, path, *, clean=True, fetch=False, rev=None):  # pylint: disable=redefined-outer-name
0 ignored issues
show
Unused Code introduced by
The argument path seems to be unused.
Loading history...
143
 
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
144
    if type == 'git-svn':
145
        # make deep clone here for simplification of sources.py
146
        # and to realize consistent readonly clone (always forced)
147
        
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
148
        # completly empty current directory (remove also hidden content)
149
        for root, dirs, files in os.walk('.'):
150
            for f in files:
151
                os.unlink(os.path.join(root, f))
152
            for d in dirs:
153
                shutil.rmtree(os.path.join(root, d))
154
        
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
155
        # clone specified svn revision 
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
156
        gitsvn('clone', '-r', rev, repo, '.')
157
        return
158
159
    assert type == 'git'
160
161
    """Update the working tree to the specified revision."""
0 ignored issues
show
Unused Code introduced by
This string statement has no effect and could be removed.
Loading history...
162
    hide = {'_show': False, '_ignore': True}
163
164
    git('stash', **hide)
165
    if clean:
166
        git('clean', '--force', '-d', '-x', _show=False)
167
168
    rev = _get_sha_from_rev(rev)
169
    git('checkout', '--force', rev)
170
    git('branch', '--set-upstream-to', 'origin/' + rev, **hide)
171
172
    if fetch:
173
        # if `rev` was a branch it might be tracking something older
174
        git('pull', '--ff-only', '--no-rebase', **hide)
175
176
177
def get_url(type):
178
    """Get the current repository's URL."""
179
    if type == 'git-svn':
180
        return git('config', '--get', 'svn-remote.svn.url', _show=False)[0]
181
    
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
182
    assert type == 'git'
183
184
    return git('config', '--get', 'remote.origin.url', _show=False)[0]
185
186
187
def get_hash(type, _show=False):
188
    """Get the current working tree's hash."""
189
    if type == 'git-svn':
190
        return ''.join(filter(str.isdigit, gitsvn('info', _show=_show)[4]))
191
    
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
192
    assert type == 'git'
193
    
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
194
    return git('rev-parse', 'HEAD', _show=_show)[0]
195
196
def get_tag():
197
    """Get the current working tree's tag (if on a tag)."""
198
    return git('describe', '--tags', '--exact-match',
199
               _show=False, _ignore=True)[0]
200
201
def is_fetch_required(type, rev):
202
    if type == 'git-svn':
203
        return False
204
   
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
205
    assert type == 'git'
206
207
    return rev not in (get_branch(),
208
                        get_hash(type),
0 ignored issues
show
Coding Style introduced by
Wrong continued indentation (remove 1 space).
Loading history...
209
                        get_tag())
0 ignored issues
show
Coding Style introduced by
Wrong continued indentation (remove 1 space).
Loading history...
210
211
212
def get_branch():
213
    """Get the current working tree's branch."""
214
    return git('rev-parse', '--abbrev-ref', 'HEAD', _show=False)[0]
215
216
217
def _get_sha_from_rev(rev):
218
    """Get a rev-parse string's hash."""
219
    if '@{' in rev:  # TODO: use regex for this
220
        parts = rev.split('@')
221
        branch = parts[0]
222
        date = parts[1].strip("{}")
223
        git('checkout', '--force', branch, _show=False)
224
        rev = git('rev-list', '-n', '1', '--before={!r}'.format(date),
225
                  branch, _show=False)[0]
226
    return rev
227