Statistics
| Branch: | Tag: | Revision:

root / devflow / utils.py @ 6b88d711

History | View | Annotate | Download (7.5 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
    name = config.get_value("user", "name")
85
    email = config.get_value("user", "email")
86

    
87
    info = namedtuple("vcs_info", ["branch", "revid", "revno",
88
                                   "toplevel", "name", "email"])
89

    
90
    return info(branch=branch.name, revid=revid, revno=revno,
91
                toplevel=toplevel, name=name, email=email)
92

    
93

    
94
def get_commit_id(commit, current_branch):
95
    """Return the commit ID
96

97
    If the commit is a 'merge' commit, and one of the parents is a
98
    debian branch we return a compination of the parents commits.
99

100
    """
101
    def short_id(commit):
102
        return commit.hexsha[0:7]
103

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

    
117

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

    
151

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

    
164

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

    
180

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

    
197

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

    
207

    
208
def version_to_tag(version):
209
    return version.replace("~", "")
210

    
211

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

    
227

    
228
def get_distribution_codename():
229
    output = sh.lsb_release("-c")
230
    _, codename = output.split("\t")
231
    codename = codename.strip()
232
    return codename