blob: 5a7ea444f87b093f38c230c314e67e1c1db60a3f [file] [log] [blame]
Scott Bakerbcbd4cc2018-03-07 13:50:21 -08001
2# Copyright 2017-present Open Networking Foundation
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16"""
17 xosutil/autoversion_setup.py
18
19 This module exports a function, setup_with_auto_version(), that will automatically generate a version.py file
20 dynamically from the version option passed to the setup function. It does this without having to modify the
21 source copy of version.py.
22
23 It also automatically searches for VERSION files in the directory of the caller and its parent hierarchy, and will
24 automatically load the version number from the VERSION file, if one is detected.
25"""
26
27import os
28from setuptools import setup
29
30from setuptools.command.sdist import sdist
31from setuptools.command.build_py import build_py
32
33import inspect
34from autodiscover_version import autodiscover_version
35
36class SdistCommand(sdist):
37 def copy_file(self, infile, outfile, *args, **kwargs):
38 if kwargs.get("dry_run"):
39 return (outfile, 1)
40 if (os.path.split(outfile)[1] == "version.py"):
41 open(outfile, "w").write("# do not edit. Autogenerated file.\n" \
42 "__version__ = '%s'\n" % self.distribution.metadata.version)
43 return (outfile, 1)
44 else:
45 return sdist.copy_file(self, infile, outfile, *args, **kwargs)
46
47class BuildPyCommand(build_py):
48 def copy_file(self, infile, outfile, *args, **kwargs):
49 if kwargs.get("dry_run"):
50 return (outfile, 1)
51 if (os.path.split(outfile)[1] == "version.py"):
52 open(outfile, "w").write("# do not edit. Autogenerated file.\n" \
53 "__version__ = '%s'\n" % self.distribution.metadata.version)
54 return (outfile, 1)
55 else:
56 return build_py.copy_file(self, infile, outfile, *args, **kwargs)
57
58def setup_with_auto_version(*args, **kwargs):
59 # Learn the module that called this function, so we can search for any VERSION files in it.
60 frame = inspect.stack()[1]
61 caller_module = inspect.getmodule(frame[0])
62
63 # Search for a VERSION file and extract the version number from it.
64 version = autodiscover_version(caller_filename = caller_module.__file__)
65 if version:
66 kwargs["version"] = version
67
68 cmdclass = kwargs.get("cmdclass", {}).copy()
69 cmdclass.update( {"sdist": SdistCommand,
70 "build_py": BuildPyCommand} )
71 kwargs["cmdclass"] = cmdclass
72
73 return setup(*args, **kwargs)
74