1# Copyright (C) 2009 Chris Larson <clarson@kergoth.com>
2# Released under the MIT license (see COPYING.MIT for the terms)
3#
4# gitver.bbclass provides a GITVER variable which is a (fairly) sane version,
5# for use in ${PV}, extracted from the ${S} git checkout, assuming it is one.
6# This is most useful in concert with srctree.bbclass.
7
8def git_drop_tag_prefix(version):
9    import re
10    if re.match("v\d", version):
11        return version[1:]
12    else:
13        return version
14
15GIT_TAGADJUST = "git_drop_tag_prefix(version)"
16GITVER = "${@get_git_pv(d, tagadjust=lambda version:${GIT_TAGADJUST})}"
17GITSHA = "${@get_git_hash(d)}"
18
19def gitrev_run(cmd, path):
20    (output, error) = bb.process.run(cmd, cwd=path)
21    return output.rstrip()
22
23def get_git_pv(d, tagadjust=None):
24    import os
25
26    srcdir = d.getVar("EXTERNALSRC") or d.getVar("S")
27    gitdir = os.path.abspath(os.path.join(srcdir, ".git"))
28    try:
29        ver = gitrev_run("git describe --tags", gitdir)
30    except:
31        try:
32            ver = gitrev_run("git rev-parse --short HEAD", gitdir)
33            if ver:
34                return "0.0+%s" % ver
35            else:
36                return "0.0"
37
38        except Exception as exc:
39            raise bb.parse.SkipRecipe(str(exc))
40
41    if ver and tagadjust:
42        ver = tagadjust(ver)
43    return ver
44
45def get_git_hash(d):
46    import os
47
48    srcdir = d.getVar("EXTERNALSRC") or d.getVar("S")
49    gitdir = os.path.abspath(os.path.join(srcdir, ".git"))
50    try:
51        rev = gitrev_run("git rev-list HEAD -1", gitdir)
52        return rev[:7]
53    except Exception as exc:
54        bb.fatal(str(exc))
55
56def mark_recipe_dependencies(path, d):
57    from bb.parse import mark_dependency
58
59    gitdir = os.path.join(path, ".git")
60
61    # Force the recipe to be reparsed so the version gets bumped
62    # if the active branch is switched, or if the branch changes.
63    mark_dependency(d, os.path.join(gitdir, "HEAD"))
64
65    # Force a reparse if anything in the index changes.
66    mark_dependency(d, os.path.join(gitdir, "index"))
67
68    try:
69        ref = gitrev_run("git symbolic-ref -q HEAD", gitdir)
70    except bb.process.CmdError:
71        pass
72    else:
73        if ref:
74            mark_dependency(d, os.path.join(gitdir, ref))
75
76    # Catch new tags.
77    tagdir = os.path.join(gitdir, "refs", "tags")
78    if os.path.exists(tagdir):
79        mark_dependency(d, tagdir)
80
81python () {
82    srcdir = d.getVar("EXTERNALSRC") or d.getVar("S")
83    mark_recipe_dependencies(srcdir, d)
84}
85