Statistics
| Branch: | Tag: | Revision:

root / devflow / utils.py @ 842df8ac

History | View | Annotate | Download (7.9 kB)

1
# Copyright (C) 2013 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
#
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
#
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
#
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
#
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

    
34
import os
35
import git
36
import sh
37
import re
38
from collections import namedtuple
39
from configobj import ConfigObj
40

    
41
from devflow import BRANCH_TYPES
42

    
43

    
44
def get_repository(path=None):
45
    """Load the repository from the current working dir."""
46
    if path is None:
47
        path = os.getcwd()
48
    try:
49
        return git.Repo(path)
50
    except git.InvalidGitRepositoryError:
51
        msg = "Cound not retrivie git information. Directory '%s'"\
52
              " is not a git repository!" % path
53
        raise RuntimeError(msg)
54

    
55

    
56
def get_config(path=None):
57
    """Load configuration file."""
58
    if path is None:
59
        toplevel = get_vcs_info().toplevel
60
        path = os.path.join(toplevel, "devflow.conf")
61

    
62
    config = ConfigObj(path)
63
    return config
64

    
65

    
66
def get_vcs_info():
67
    """Return current git HEAD commit information.
68

69
    Returns a tuple containing
70
        - branch name
71
        - commit id
72
        - commit count
73
        - git describe output
74
        - path of git toplevel directory
75

76
    """
77

    
78
    repo = get_repository()
79
    branch = repo.head.reference
80
    revid = get_commit_id(branch.commit, branch)
81
    revno = len(list(repo.iter_commits()))
82
    toplevel = repo.working_dir
83
    config = repo.config_reader()
84
    try:
85
        name = config.get_value("user", "name")
86
        email = config.get_value("user", "email")
87
    except Exception as e:
88
        raise ValueError("Can not read name/email from .gitconfig"
89
                         " file.: %s" % e)
90

    
91
    info = namedtuple("vcs_info", ["branch", "revid", "revno",
92
                                   "toplevel", "name", "email"])
93

    
94
    return info(branch=branch.name, revid=revid, revno=revno,
95
                toplevel=toplevel, name=name, email=email)
96

    
97

    
98
def get_commit_id(commit, current_branch):
99
    """Return the commit ID
100

101
    If the commit is a 'merge' commit, and one of the parents is a
102
    debian branch we return a compination of the parents commits.
103

104
    """
105
    def short_id(commit):
106
        return commit.hexsha[0:7]
107

    
108
    parents = commit.parents
109
    cur_br_name = current_branch.name
110
    if len(parents) == 1:
111
        return short_id(commit)
112
    elif len(parents) == 2:
113
        if cur_br_name.startswith("debian-") or cur_br_name == "debian":
114
            pr1, pr2 = parents
115
            return short_id(pr1) + "_" + short_id(pr2)
116
        else:
117
            return short_id(commit)
118
    else:
119
        raise RuntimeError("Commit %s has more than 2 parents!" % commit)
120

    
121

    
122
def get_debian_branch(branch):
123
    """Find the corresponding debian- branch"""
124
    distribution = get_distribution_codename()
125
    repo = get_repository()
126
    if branch == "master":
127
        deb_branch = "debian-" + distribution
128
    else:
129
        deb_branch = "-".join(["debian", branch, distribution])
130
    # Check if debian-branch exists (local or origin)
131
    if _get_branch(deb_branch):
132
        return deb_branch
133
    # Check without distribution
134
    deb_branch = re.sub("-" + distribution + "$", "", deb_branch)
135
    if _get_branch(deb_branch):
136
        return deb_branch
137
    branch_type = BRANCH_TYPES[get_branch_type(branch)]
138
    # If not try the default debian branch with distribution
139
    default_branch = branch_type.debian_branch + "-" + distribution
140
    if _get_branch(default_branch):
141
        repo.git.branch(deb_branch, default_branch)
142
        print "Created branch '%s' from '%s'" % (deb_branch, default_branch)
143
        return deb_branch
144
    # And without distribution
145
    default_branch = branch_type.debian_branch
146
    if _get_branch(default_branch):
147
        repo.git.branch(deb_branch, default_branch)
148
        print "Created branch '%s' from '%s'" % (deb_branch, default_branch)
149
        return deb_branch
150
    # If not try the debian branch
151
    repo.git.branch(deb_branch, default_branch)
152
    print "Created branch '%s' from 'debian'" % deb_branch
153
    return "debian"
154

    
155

    
156
def _get_branch(branch):
157
    repo = get_repository()
158
    if branch in repo.branches:
159
        return branch
160
    origin_branch = "origin/" + branch
161
    if origin_branch in repo.refs:
162
        print "Creating branch '%s' to track '%s'" % (branch, origin_branch)
163
        repo.git.branch(branch, origin_branch)
164
        return branch
165
    else:
166
        return None
167

    
168

    
169
def get_build_mode():
170
    """Determine the build mode"""
171
    # Get it from environment if exists
172
    mode = os.environ.get("DEVFLOW_BUILD_MODE", None)
173
    if mode is None:
174
        branch = get_branch_type(get_vcs_info().branch)
175
        try:
176
            br_type = BRANCH_TYPES[get_branch_type(branch)]
177
        except KeyError:
178
            allowed_branches = ", ".join(x for x in BRANCH_TYPES.keys())
179
            raise ValueError("Malformed branch name '%s', cannot classify as"
180
                             " one of %s" % (branch, allowed_branches))
181
        mode = "snapshot" if br_type.builds_snapshot else "release"
182
    return mode
183

    
184

    
185
def normalize_branch_name(branch_name):
186
    """Normalize branch name by removing debian- if exists"""
187
    brnorm = branch_name
188
    codename = get_distribution_codename()
189
    if brnorm == "debian":
190
        return "master"
191
    elif brnorm == codename:
192
        return "master"
193
    elif brnorm == "debian-%s" % codename:
194
        return "master"
195
    elif brnorm.startswith("debian-%s-" % codename):
196
        return brnorm.replace("debian-%s-" % codename, "", 1)
197
    elif brnorm.startswith("debian-"):
198
        return brnorm.replace("debian-", "", 1)
199
    return brnorm
200

    
201

    
202
def get_branch_type(branch_name):
203
    """Extract the type from a branch name"""
204
    branch_name = normalize_branch_name(branch_name)
205
    if "-" in branch_name:
206
        btypestr = branch_name.split("-")[0]
207
    else:
208
        btypestr = branch_name
209
    return btypestr
210

    
211

    
212
def version_to_tag(version):
213
    return version.replace("~", "")
214

    
215

    
216
def undebianize(branch):
217
    codename = get_distribution_codename()
218
    if branch == "debian":
219
        return "master"
220
    elif branch == codename:
221
        return "master"
222
    elif branch == "debian-%s" % codename:
223
        return "master"
224
    elif branch.startswith("debian-%s-" % codename):
225
        return branch.replace("debian-%s-" % codename, "", 1)
226
    elif branch.startswith("debian-"):
227
        return branch.replace("debian-", "")
228
    else:
229
        return branch
230

    
231

    
232
def get_distribution_codename():
233
    codename = sh.uname().lower()
234
    if codename == "linux":
235
        # lets try to be more specific using lsb_release
236
        try:
237
            output = sh.lsb_release("-c")  # pylint: disable=E1101
238
            _, codename = output.split("\t")
239
        except sh.CommandNotFound:
240
            pass
241
    codename = codename.strip()
242
    return codename