Browse code

update to miniver 0.7.0 (#290)

Bas Nijholt authored on 01/09/2020 10:08:44 • GitHub committed on 01/09/2020 10:08:44
Showing 1 changed files
... ...
@@ -3,8 +3,8 @@
3 3
 import os
4 4
 import subprocess
5 5
 from collections import namedtuple
6
-from distutils.command.build_py import build_py as build_py_orig
7 6
 
7
+from setuptools.command.build_py import build_py as build_py_orig
8 8
 from setuptools.command.sdist import sdist as sdist_orig
9 9
 
10 10
 Version = namedtuple("Version", ("release", "dev", "labels"))
... ...
@@ -15,6 +15,13 @@ __all__ = []
15 15
 package_root = os.path.dirname(os.path.realpath(__file__))
16 16
 package_name = os.path.basename(package_root)
17 17
 distr_root = os.path.dirname(package_root)
18
+# If the package is inside a "src" directory the
19
+# distribution root is 1 level up.
20
+if os.path.split(distr_root)[1] == "src":
21
+    _package_root_inside_src = True
22
+    distr_root = os.path.dirname(distr_root)
23
+else:
24
+    _package_root_inside_src = False
18 25
 
19 26
 STATIC_VERSION_FILE = "_static_version.py"
20 27
 
... ...
@@ -189,7 +196,11 @@ class _build_py(build_py_orig):
189 196
 class _sdist(sdist_orig):
190 197
     def make_release_tree(self, base_dir, files):
191 198
         super().make_release_tree(base_dir, files)
192
-        _write_version(os.path.join(base_dir, package_name, STATIC_VERSION_FILE))
199
+        if _package_root_inside_src:
200
+            p = os.path.join("src", package_name)
201
+        else:
202
+            p = package_name
203
+        _write_version(os.path.join(base_dir, p, STATIC_VERSION_FILE))
193 204
 
194 205
 
195 206
 cmdclass = dict(sdist=_sdist, build_py=_build_py)
Browse code

run pre-commit run --all

Bas Nijholt authored on 11/12/2019 14:00:39
Showing 1 changed files
... ...
@@ -1,4 +1,3 @@
1
-# -*- coding: utf-8 -*-
2 1
 # This file is part of 'miniver': https://github.com/jbweston/miniver
3 2
 #
4 3
 import os
Browse code

fix all flake8 issues and run pre-commit filters

Bas Nijholt authored on 08/05/2019 02:26:15
Showing 1 changed files
... ...
@@ -8,7 +8,7 @@ from distutils.command.build_py import build_py as build_py_orig
8 8
 
9 9
 from setuptools.command.sdist import sdist as sdist_orig
10 10
 
11
-Version = namedtuple('Version', ('release', 'dev', 'labels'))
11
+Version = namedtuple("Version", ("release", "dev", "labels"))
12 12
 
13 13
 # No public API
14 14
 __all__ = []
... ...
@@ -17,12 +17,12 @@ package_root = os.path.dirname(os.path.realpath(__file__))
17 17
 package_name = os.path.basename(package_root)
18 18
 distr_root = os.path.dirname(package_root)
19 19
 
20
-STATIC_VERSION_FILE = '_static_version.py'
20
+STATIC_VERSION_FILE = "_static_version.py"
21 21
 
22 22
 
23 23
 def get_version(version_file=STATIC_VERSION_FILE):
24 24
     version_info = get_static_version_info(version_file)
25
-    version = version_info['version']
25
+    version = version_info["version"]
26 26
     if version == "__use_git__":
27 27
         version = get_version_from_git()
28 28
         if not version:
... ...
@@ -36,13 +36,13 @@ def get_version(version_file=STATIC_VERSION_FILE):
36 36
 
37 37
 def get_static_version_info(version_file=STATIC_VERSION_FILE):
38 38
     version_info = {}
39
-    with open(os.path.join(package_root, version_file), 'rb') as f:
39
+    with open(os.path.join(package_root, version_file), "rb") as f:
40 40
         exec(f.read(), {}, version_info)
41 41
     return version_info
42 42
 
43 43
 
44 44
 def version_is_from_git(version_file=STATIC_VERSION_FILE):
45
-    return get_static_version_info(version_file)['version'] == '__use_git__'
45
+    return get_static_version_info(version_file)["version"] == "__use_git__"
46 46
 
47 47
 
48 48
 def pep440_format(version_info):
... ...
@@ -50,13 +50,13 @@ def pep440_format(version_info):
50 50
 
51 51
     version_parts = [release]
52 52
     if dev:
53
-        if release.endswith('-dev') or release.endswith('.dev'):
53
+        if release.endswith("-dev") or release.endswith(".dev"):
54 54
             version_parts.append(dev)
55 55
         else:  # prefer PEP440 over strict adhesion to semver
56
-            version_parts.append(f'.dev{dev}')
56
+            version_parts.append(f".dev{dev}")
57 57
 
58 58
     if labels:
59
-        version_parts.append('+')
59
+        version_parts.append("+")
60 60
         version_parts.append(".".join(labels))
61 61
 
62 62
     return "".join(version_parts)
... ...
@@ -64,15 +64,17 @@ def pep440_format(version_info):
64 64
 
65 65
 def get_version_from_git():
66 66
     try:
67
-        p = subprocess.Popen(['git', 'rev-parse', '--show-toplevel'],
68
-                             cwd=distr_root,
69
-                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
67
+        p = subprocess.Popen(
68
+            ["git", "rev-parse", "--show-toplevel"],
69
+            cwd=distr_root,
70
+            stdout=subprocess.PIPE,
71
+            stderr=subprocess.PIPE,
72
+        )
70 73
     except OSError:
71 74
         return
72 75
     if p.wait() != 0:
73 76
         return
74
-    if not os.path.samefile(p.communicate()[0].decode().rstrip('\n'),
75
-                            distr_root):
77
+    if not os.path.samefile(p.communicate()[0].decode().rstrip("\n"), distr_root):
76 78
         # The top-level directory of the current Git repository is not the same
77 79
         # as the root directory of the distribution: do not extract the
78 80
         # version from Git.
... ...
@@ -81,12 +83,14 @@ def get_version_from_git():
81 83
     # git describe --first-parent does not take into account tags from branches
82 84
     # that were merged-in. The '--long' flag gets us the 'dev' version and
83 85
     # git hash, '--always' returns the git hash even if there are no tags.
84
-    for opts in [['--first-parent'], []]:
86
+    for opts in [["--first-parent"], []]:
85 87
         try:
86 88
             p = subprocess.Popen(
87
-                ['git', 'describe', '--long', '--always'] + opts,
89
+                ["git", "describe", "--long", "--always"] + opts,
88 90
                 cwd=distr_root,
89
-                stdout=subprocess.PIPE, stderr=subprocess.PIPE)
91
+                stdout=subprocess.PIPE,
92
+                stderr=subprocess.PIPE,
93
+            )
90 94
         except OSError:
91 95
             return
92 96
         if p.wait() == 0:
... ...
@@ -97,17 +101,17 @@ def get_version_from_git():
97 101
     description = (
98 102
         p.communicate()[0]
99 103
         .decode()
100
-        .strip('v')  # Tags can have a leading 'v', but the version should not
101
-        .rstrip('\n')
102
-        .rsplit('-', 2)  # Split the latest tag, commits since tag, and hash
104
+        .strip("v")  # Tags can have a leading 'v', but the version should not
105
+        .rstrip("\n")
106
+        .rsplit("-", 2)  # Split the latest tag, commits since tag, and hash
103 107
     )
104 108
 
105 109
     try:
106 110
         release, dev, git = description
107 111
     except ValueError:  # No tags, only the git hash
108 112
         # prepend 'g' to match with format returned by 'git describe'
109
-        git = 'g{}'.format(*description)
110
-        release = 'unknown'
113
+        git = "g{}".format(*description)
114
+        release = "unknown"
111 115
         dev = None
112 116
 
113 117
     labels = []
... ...
@@ -117,12 +121,12 @@ def get_version_from_git():
117 121
         labels.append(git)
118 122
 
119 123
     try:
120
-        p = subprocess.Popen(['git', 'diff', '--quiet'], cwd=distr_root)
124
+        p = subprocess.Popen(["git", "diff", "--quiet"], cwd=distr_root)
121 125
     except OSError:
122
-        labels.append('confused')  # This should never happen.
126
+        labels.append("confused")  # This should never happen.
123 127
     else:
124 128
         if p.wait() == 1:
125
-            labels.append('dirty')
129
+            labels.append("dirty")
126 130
 
127 131
     return Version(release, dev, labels)
128 132
 
... ...
@@ -134,25 +138,25 @@ def get_version_from_git():
134 138
 #       if it is not tagged.
135 139
 def get_version_from_git_archive(version_info):
136 140
     try:
137
-        refnames = version_info['refnames']
138
-        git_hash = version_info['git_hash']
141
+        refnames = version_info["refnames"]
142
+        git_hash = version_info["git_hash"]
139 143
     except KeyError:
140 144
         # These fields are not present if we are running from an sdist.
141 145
         # Execution should never reach here, though
142 146
         return None
143 147
 
144
-    if git_hash.startswith('$Format') or refnames.startswith('$Format'):
148
+    if git_hash.startswith("$Format") or refnames.startswith("$Format"):
145 149
         # variables not expanded during 'git archive'
146 150
         return None
147 151
 
148
-    VTAG = 'tag: v'
152
+    VTAG = "tag: v"
149 153
     refs = {r.strip() for r in refnames.split(",")}
150
-    version_tags = {r[len(VTAG):] for r in refs if r.startswith(VTAG)}
154
+    version_tags = {r[len(VTAG) :] for r in refs if r.startswith(VTAG)}
151 155
     if version_tags:
152 156
         release, *_ = sorted(version_tags)  # prefer e.g. "2.0" over "2.0rc1"
153 157
         return Version(release, dev=None, labels=None)
154 158
     else:
155
-        return Version('unknown', dev=None, labels=[f'g{git_hash}'])
159
+        return Version("unknown", dev=None, labels=[f"g{git_hash}"])
156 160
 
157 161
 
158 162
 __version__ = get_version()
... ...
@@ -162,6 +166,7 @@ __version__ = get_version()
162 166
 # which can be used from setup.py. The 'package_name' and
163 167
 # '__version__' module globals are used (but not modified).
164 168
 
169
+
165 170
 def _write_version(fname):
166 171
     # This could be a hard link, so try to delete it first.  Is there any way
167 172
     # to do this atomically together with opening?
... ...
@@ -169,23 +174,23 @@ def _write_version(fname):
169 174
         os.remove(fname)
170 175
     except OSError:
171 176
         pass
172
-    with open(fname, 'w') as f:
173
-        f.write("# This file has been created by setup.py.\n"
174
-                "version = '{}'\n".format(__version__))
177
+    with open(fname, "w") as f:
178
+        f.write(
179
+            "# This file has been created by setup.py.\n"
180
+            "version = '{}'\n".format(__version__)
181
+        )
175 182
 
176 183
 
177 184
 class _build_py(build_py_orig):
178 185
     def run(self):
179 186
         super().run()
180
-        _write_version(os.path.join(self.build_lib, package_name,
181
-                                    STATIC_VERSION_FILE))
187
+        _write_version(os.path.join(self.build_lib, package_name, STATIC_VERSION_FILE))
182 188
 
183 189
 
184 190
 class _sdist(sdist_orig):
185 191
     def make_release_tree(self, base_dir, files):
186 192
         super().make_release_tree(base_dir, files)
187
-        _write_version(os.path.join(base_dir, package_name,
188
-                                    STATIC_VERSION_FILE))
193
+        _write_version(os.path.join(base_dir, package_name, STATIC_VERSION_FILE))
189 194
 
190 195
 
191 196
 cmdclass = dict(sdist=_sdist, build_py=_build_py)
Browse code

fix import order and style

Bas Nijholt authored on 07/05/2019 23:42:40
Showing 1 changed files
... ...
@@ -1,11 +1,11 @@
1 1
 # -*- coding: utf-8 -*-
2 2
 # This file is part of 'miniver': https://github.com/jbweston/miniver
3 3
 #
4
-from collections import namedtuple
5 4
 import os
6 5
 import subprocess
7
-
6
+from collections import namedtuple
8 7
 from distutils.command.build_py import build_py as build_py_orig
8
+
9 9
 from setuptools.command.sdist import sdist as sdist_orig
10 10
 
11 11
 Version = namedtuple('Version', ('release', 'dev', 'labels'))
... ...
@@ -53,7 +53,7 @@ def pep440_format(version_info):
53 53
         if release.endswith('-dev') or release.endswith('.dev'):
54 54
             version_parts.append(dev)
55 55
         else:  # prefer PEP440 over strict adhesion to semver
56
-            version_parts.append('.dev{}'.format(dev))
56
+            version_parts.append(f'.dev{dev}')
57 57
 
58 58
     if labels:
59 59
         version_parts.append('+')
... ...
@@ -146,13 +146,13 @@ def get_version_from_git_archive(version_info):
146 146
         return None
147 147
 
148 148
     VTAG = 'tag: v'
149
-    refs = set(r.strip() for r in refnames.split(","))
150
-    version_tags = set(r[len(VTAG):] for r in refs if r.startswith(VTAG))
149
+    refs = {r.strip() for r in refnames.split(",")}
150
+    version_tags = {r[len(VTAG):] for r in refs if r.startswith(VTAG)}
151 151
     if version_tags:
152 152
         release, *_ = sorted(version_tags)  # prefer e.g. "2.0" over "2.0rc1"
153 153
         return Version(release, dev=None, labels=None)
154 154
     else:
155
-        return Version('unknown', dev=None, labels=['g{}'.format(git_hash)])
155
+        return Version('unknown', dev=None, labels=[f'g{git_hash}'])
156 156
 
157 157
 
158 158
 __version__ = get_version()
Browse code

update to the latest miniver

Bas Nijholt authored on 15/10/2018 14:03:58
Showing 1 changed files
1 1
new file mode 100644
... ...
@@ -0,0 +1,191 @@
1
+# -*- coding: utf-8 -*-
2
+# This file is part of 'miniver': https://github.com/jbweston/miniver
3
+#
4
+from collections import namedtuple
5
+import os
6
+import subprocess
7
+
8
+from distutils.command.build_py import build_py as build_py_orig
9
+from setuptools.command.sdist import sdist as sdist_orig
10
+
11
+Version = namedtuple('Version', ('release', 'dev', 'labels'))
12
+
13
+# No public API
14
+__all__ = []
15
+
16
+package_root = os.path.dirname(os.path.realpath(__file__))
17
+package_name = os.path.basename(package_root)
18
+distr_root = os.path.dirname(package_root)
19
+
20
+STATIC_VERSION_FILE = '_static_version.py'
21
+
22
+
23
+def get_version(version_file=STATIC_VERSION_FILE):
24
+    version_info = get_static_version_info(version_file)
25
+    version = version_info['version']
26
+    if version == "__use_git__":
27
+        version = get_version_from_git()
28
+        if not version:
29
+            version = get_version_from_git_archive(version_info)
30
+        if not version:
31
+            version = Version("unknown", None, None)
32
+        return pep440_format(version)
33
+    else:
34
+        return version
35
+
36
+
37
+def get_static_version_info(version_file=STATIC_VERSION_FILE):
38
+    version_info = {}
39
+    with open(os.path.join(package_root, version_file), 'rb') as f:
40
+        exec(f.read(), {}, version_info)
41
+    return version_info
42
+
43
+
44
+def version_is_from_git(version_file=STATIC_VERSION_FILE):
45
+    return get_static_version_info(version_file)['version'] == '__use_git__'
46
+
47
+
48
+def pep440_format(version_info):
49
+    release, dev, labels = version_info
50
+
51
+    version_parts = [release]
52
+    if dev:
53
+        if release.endswith('-dev') or release.endswith('.dev'):
54
+            version_parts.append(dev)
55
+        else:  # prefer PEP440 over strict adhesion to semver
56
+            version_parts.append('.dev{}'.format(dev))
57
+
58
+    if labels:
59
+        version_parts.append('+')
60
+        version_parts.append(".".join(labels))
61
+
62
+    return "".join(version_parts)
63
+
64
+
65
+def get_version_from_git():
66
+    try:
67
+        p = subprocess.Popen(['git', 'rev-parse', '--show-toplevel'],
68
+                             cwd=distr_root,
69
+                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
70
+    except OSError:
71
+        return
72
+    if p.wait() != 0:
73
+        return
74
+    if not os.path.samefile(p.communicate()[0].decode().rstrip('\n'),
75
+                            distr_root):
76
+        # The top-level directory of the current Git repository is not the same
77
+        # as the root directory of the distribution: do not extract the
78
+        # version from Git.
79
+        return
80
+
81
+    # git describe --first-parent does not take into account tags from branches
82
+    # that were merged-in. The '--long' flag gets us the 'dev' version and
83
+    # git hash, '--always' returns the git hash even if there are no tags.
84
+    for opts in [['--first-parent'], []]:
85
+        try:
86
+            p = subprocess.Popen(
87
+                ['git', 'describe', '--long', '--always'] + opts,
88
+                cwd=distr_root,
89
+                stdout=subprocess.PIPE, stderr=subprocess.PIPE)
90
+        except OSError:
91
+            return
92
+        if p.wait() == 0:
93
+            break
94
+    else:
95
+        return
96
+
97
+    description = (
98
+        p.communicate()[0]
99
+        .decode()
100
+        .strip('v')  # Tags can have a leading 'v', but the version should not
101
+        .rstrip('\n')
102
+        .rsplit('-', 2)  # Split the latest tag, commits since tag, and hash
103
+    )
104
+
105
+    try:
106
+        release, dev, git = description
107
+    except ValueError:  # No tags, only the git hash
108
+        # prepend 'g' to match with format returned by 'git describe'
109
+        git = 'g{}'.format(*description)
110
+        release = 'unknown'
111
+        dev = None
112
+
113
+    labels = []
114
+    if dev == "0":
115
+        dev = None
116
+    else:
117
+        labels.append(git)
118
+
119
+    try:
120
+        p = subprocess.Popen(['git', 'diff', '--quiet'], cwd=distr_root)
121
+    except OSError:
122
+        labels.append('confused')  # This should never happen.
123
+    else:
124
+        if p.wait() == 1:
125
+            labels.append('dirty')
126
+
127
+    return Version(release, dev, labels)
128
+
129
+
130
+# TODO: change this logic when there is a git pretty-format
131
+#       that gives the same output as 'git describe'.
132
+#       Currently we can only tell the tag the current commit is
133
+#       pointing to, or its hash (with no version info)
134
+#       if it is not tagged.
135
+def get_version_from_git_archive(version_info):
136
+    try:
137
+        refnames = version_info['refnames']
138
+        git_hash = version_info['git_hash']
139
+    except KeyError:
140
+        # These fields are not present if we are running from an sdist.
141
+        # Execution should never reach here, though
142
+        return None
143
+
144
+    if git_hash.startswith('$Format') or refnames.startswith('$Format'):
145
+        # variables not expanded during 'git archive'
146
+        return None
147
+
148
+    VTAG = 'tag: v'
149
+    refs = set(r.strip() for r in refnames.split(","))
150
+    version_tags = set(r[len(VTAG):] for r in refs if r.startswith(VTAG))
151
+    if version_tags:
152
+        release, *_ = sorted(version_tags)  # prefer e.g. "2.0" over "2.0rc1"
153
+        return Version(release, dev=None, labels=None)
154
+    else:
155
+        return Version('unknown', dev=None, labels=['g{}'.format(git_hash)])
156
+
157
+
158
+__version__ = get_version()
159
+
160
+
161
+# The following section defines a module global 'cmdclass',
162
+# which can be used from setup.py. The 'package_name' and
163
+# '__version__' module globals are used (but not modified).
164
+
165
+def _write_version(fname):
166
+    # This could be a hard link, so try to delete it first.  Is there any way
167
+    # to do this atomically together with opening?
168
+    try:
169
+        os.remove(fname)
170
+    except OSError:
171
+        pass
172
+    with open(fname, 'w') as f:
173
+        f.write("# This file has been created by setup.py.\n"
174
+                "version = '{}'\n".format(__version__))
175
+
176
+
177
+class _build_py(build_py_orig):
178
+    def run(self):
179
+        super().run()
180
+        _write_version(os.path.join(self.build_lib, package_name,
181
+                                    STATIC_VERSION_FILE))
182
+
183
+
184
+class _sdist(sdist_orig):
185
+    def make_release_tree(self, base_dir, files):
186
+        super().make_release_tree(base_dir, files)
187
+        _write_version(os.path.join(base_dir, package_name,
188
+                                    STATIC_VERSION_FILE))
189
+
190
+
191
+cmdclass = dict(sdist=_sdist, build_py=_build_py)
Browse code

modify filenames and version-module import from setup.py

Remove usage of deprecated 'imp' module in favour of 'importlib'.
Also remove the package name from as many places as possible.

Joseph Weston authored on 21/02/2018 10:06:07
Showing 1 changed files
1 1
deleted file mode 100644
... ...
@@ -1,109 +0,0 @@
1
-import sys
2
-import subprocess
3
-import os
4
-
5
-# No public API
6
-__all__ = []
7
-
8
-package_root = os.path.dirname(os.path.realpath(__file__))
9
-distr_root = os.path.dirname(package_root)
10
-
11
-STATIC_VERSION_FILE = '_adaptive_version.py'
12
-
13
-version = None
14
-
15
-def get_version(version_file=STATIC_VERSION_FILE):
16
-    version_info = {}
17
-    with open(os.path.join(package_root, version_file), 'rb') as f:
18
-        exec(f.read(), {}, version_info)
19
-    version = version_info['version']
20
-    version_is_from_git = (version == "__use_git__")
21
-    if version_is_from_git:
22
-        version = get_version_from_git()
23
-        if not version:
24
-            version = get_version_from_git_archive(version_info)
25
-        if not version:
26
-            version = "unknown"
27
-    return version
28
-
29
-
30
-def get_version_from_git():
31
-    try:
32
-        p = subprocess.Popen(['git', 'rev-parse', '--show-toplevel'],
33
-                             cwd=distr_root,
34
-                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
35
-    except OSError:
36
-        return
37
-    if p.wait() != 0:
38
-        return
39
-    if not os.path.samefile(p.communicate()[0].decode().rstrip('\n'),
40
-                            distr_root):
41
-        # The top-level directory of the current Git repository is not the same
42
-        # as the root directory of the Kwant distribution: do not extract the
43
-        # version from Git.
44
-        return
45
-
46
-    # git describe --first-parent does not take into account tags from branches
47
-    # that were merged-in.
48
-    for opts in [['--first-parent'], []]:
49
-        try:
50
-            p = subprocess.Popen(['git', 'describe', '--long'] + opts,
51
-                                 cwd=distr_root,
52
-                                 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
53
-        except OSError:
54
-            return
55
-        if p.wait() == 0:
56
-            break
57
-    else:
58
-        return
59
-    description = p.communicate()[0].decode().strip('v').rstrip('\n')
60
-
61
-    release, dev, git = description.rsplit('-', 2)
62
-    version = [release]
63
-    labels = []
64
-    if dev != "0":
65
-        version.append(".dev{}".format(dev))
66
-        labels.append(git)
67
-
68
-    try:
69
-        p = subprocess.Popen(['git', 'diff', '--quiet'], cwd=distr_root)
70
-    except OSError:
71
-        labels.append('confused') # This should never happen.
72
-    else:
73
-        if p.wait() == 1:
74
-            labels.append('dirty')
75
-
76
-    if labels:
77
-        version.append('+')
78
-        version.append(".".join(labels))
79
-
80
-    return "".join(version)
81
-
82
-
83
-# TODO: change this logic when there is a git pretty-format
84
-#       that gives the same output as 'git describe'.
85
-#       Currently we return just the tag if a tagged version
86
-#       was archived, or 'unknown-g<git hash>' otherwise.
87
-def get_version_from_git_archive(version_info):
88
-    try:
89
-        refnames = version_info['refnames']
90
-        git_hash = version_info['git_hash']
91
-    except KeyError:
92
-        # These fields are not present if we are running from an sdist.
93
-        # Execution should never reach here, though
94
-        return None
95
-
96
-    if git_hash.startswith('$Format') or refnames.startswith('$Format'):
97
-        # variables not expanded during 'git archive'
98
-        return None
99
-
100
-    TAG = 'tag: v'
101
-    refs = set(r.strip() for r in refnames.split(","))
102
-    tags = set(r[len(TAG):] for r in refs if r.startswith(TAG))
103
-    if tags:
104
-        release, *_ = sorted(tags)  # prefer e.g. "2.0" over "2.0rc1"
105
-        return release
106
-    else:
107
-        return f'unknown+g{git_hash}'
108
-
109
-version = get_version()
Browse code

add functionality to get version from git

We want a single source of truth for versioning; we choose
git tags.

Joseph Weston authored on 20/02/2018 14:51:52
Showing 1 changed files
1 1
new file mode 100644
... ...
@@ -0,0 +1,109 @@
1
+import sys
2
+import subprocess
3
+import os
4
+
5
+# No public API
6
+__all__ = []
7
+
8
+package_root = os.path.dirname(os.path.realpath(__file__))
9
+distr_root = os.path.dirname(package_root)
10
+
11
+STATIC_VERSION_FILE = '_adaptive_version.py'
12
+
13
+version = None
14
+
15
+def get_version(version_file=STATIC_VERSION_FILE):
16
+    version_info = {}
17
+    with open(os.path.join(package_root, version_file), 'rb') as f:
18
+        exec(f.read(), {}, version_info)
19
+    version = version_info['version']
20
+    version_is_from_git = (version == "__use_git__")
21
+    if version_is_from_git:
22
+        version = get_version_from_git()
23
+        if not version:
24
+            version = get_version_from_git_archive(version_info)
25
+        if not version:
26
+            version = "unknown"
27
+    return version
28
+
29
+
30
+def get_version_from_git():
31
+    try:
32
+        p = subprocess.Popen(['git', 'rev-parse', '--show-toplevel'],
33
+                             cwd=distr_root,
34
+                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
35
+    except OSError:
36
+        return
37
+    if p.wait() != 0:
38
+        return
39
+    if not os.path.samefile(p.communicate()[0].decode().rstrip('\n'),
40
+                            distr_root):
41
+        # The top-level directory of the current Git repository is not the same
42
+        # as the root directory of the Kwant distribution: do not extract the
43
+        # version from Git.
44
+        return
45
+
46
+    # git describe --first-parent does not take into account tags from branches
47
+    # that were merged-in.
48
+    for opts in [['--first-parent'], []]:
49
+        try:
50
+            p = subprocess.Popen(['git', 'describe', '--long'] + opts,
51
+                                 cwd=distr_root,
52
+                                 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
53
+        except OSError:
54
+            return
55
+        if p.wait() == 0:
56
+            break
57
+    else:
58
+        return
59
+    description = p.communicate()[0].decode().strip('v').rstrip('\n')
60
+
61
+    release, dev, git = description.rsplit('-', 2)
62
+    version = [release]
63
+    labels = []
64
+    if dev != "0":
65
+        version.append(".dev{}".format(dev))
66
+        labels.append(git)
67
+
68
+    try:
69
+        p = subprocess.Popen(['git', 'diff', '--quiet'], cwd=distr_root)
70
+    except OSError:
71
+        labels.append('confused') # This should never happen.
72
+    else:
73
+        if p.wait() == 1:
74
+            labels.append('dirty')
75
+
76
+    if labels:
77
+        version.append('+')
78
+        version.append(".".join(labels))
79
+
80
+    return "".join(version)
81
+
82
+
83
+# TODO: change this logic when there is a git pretty-format
84
+#       that gives the same output as 'git describe'.
85
+#       Currently we return just the tag if a tagged version
86
+#       was archived, or 'unknown-g<git hash>' otherwise.
87
+def get_version_from_git_archive(version_info):
88
+    try:
89
+        refnames = version_info['refnames']
90
+        git_hash = version_info['git_hash']
91
+    except KeyError:
92
+        # These fields are not present if we are running from an sdist.
93
+        # Execution should never reach here, though
94
+        return None
95
+
96
+    if git_hash.startswith('$Format') or refnames.startswith('$Format'):
97
+        # variables not expanded during 'git archive'
98
+        return None
99
+
100
+    TAG = 'tag: v'
101
+    refs = set(r.strip() for r in refnames.split(","))
102
+    tags = set(r[len(TAG):] for r in refs if r.startswith(TAG))
103
+    if tags:
104
+        release, *_ = sorted(tags)  # prefer e.g. "2.0" over "2.0rc1"
105
+        return release
106
+    else:
107
+        return f'unknown+g{git_hash}'
108
+
109
+version = get_version()