File: dunepackaging.py

package info (click to toggle)
dune-common 2.11.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 6,048 kB
  • sloc: cpp: 54,403; python: 4,136; sh: 1,657; makefile: 17
file content (266 lines) | stat: -rwxr-xr-x 9,897 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
#!/usr/bin/env python3
# SPDX-FileCopyrightInfo: Copyright © DUNE Project contributors, see file LICENSE.md in module root
# SPDX-License-Identifier: LicenseRef-GPL-2.0-only-with-DUNE-exception

import sys, os, io, getopt, re, shutil
try:
    import skbuild
except ImportError:
    print("skbuild needed for packaging, run 'pip install scikit-build'")
    sys.exit(0)
try:
    import requests
except ImportError:
    print("'requests' package needed, run 'pip install requests'")
    sys.exit(0)

import importlib, subprocess
import email.utils
from datetime import date

# make sure that 'metadata' is taken from the current `dune-common` folder
# and not some installed version which might be different from the one I'm
# packaging (by mistake). The path to `packagemetadata.py` needs to be
# added to the python path (to work here) and to the environment so that a
# later call to `python setup.py` also works.
here = os.path.dirname(os.path.abspath(__file__))
mods = os.path.join(here, "..", "python", "dune")
sys.path.append(mods)
pythonpath  = mods + ":" + os.environ.get('PYTHONPATH','.')
os.environ['PYTHONPATH'] = pythonpath
try:
    from packagemetadata import metaData, Data
except ImportError:
    # not calling from within a dune-common source module so use installed
    # version after all
    from dune.packagemetadata import metaData, Data

def main(argv):

    repositories = ["gitlab", "testpypi", "pypi"]
    def usage():
        return 'usage: dunepackaging.py [--upload <'+"|".join(repositories)+'> | -c | --clean | --version <version> | --onlysdist | --bdist_conda | --getversion]'

    try:
        opts, args = getopt.getopt(argv, "hc", ["upload=", "clean", "version=", "onlysdist", "bdist_conda", "getversion"])
    except getopt.GetoptError:
        print(usage())
        sys.exit(2)

    upload = False
    repository = "gitlab"
    clean = False
    version = None
    onlysdist = False
    bdistconda = False
    for opt, arg in opts:
        if opt == '-h':
            print(usage())
            sys.exit(2)
        elif opt in ("--upload"):
            upload = True
            if arg != '':
                repository = arg
                if repository not in repositories:
                    print("Specified repository must be one of: " + " ".join(repositories))
                    sys.exit(2)
        elif opt in ("-c", "--clean"):
            clean = True
        elif opt in ("--version"):
            version = arg
        elif opt in ("--onlysdist"):
            onlysdist = True
        elif opt in ("--bdist_conda"):
            onlysdist  = True
            bdistconda = True
        elif opt in ("--getversion"):
            print(Data().version)
            sys.exit(0)

    # Remove generated files
    def removeFiles():
        import glob
        files = ['MANIFEST', 'dist', '_skbuild', '__pycache__']
        print("Remove generated files: " + ", ".join(files))
        remove = ['rm', '-rf'] + files
        subprocess.call(remove)
        # checkout setup.py and pyproject.toml
        checkout = ['git', 'checkout', 'setup.py', 'pyproject.toml']
        subprocess.call(checkout)

    if clean:
        removeFiles()
        sys.exit(0)

    data, cmake_flags = metaData(version, dependencyCheck=False)

    if version is None:
        version = data.version

    # Generate setup.py
    print("Generate setup.py")
    f = open("setup.py", "w")
    f.write("""#
# DO NOT MODIFY THIS FILE!
# This file is autogenerated by the `dunepackaging.py` script and
# only used for the pypi dune packages. This file will not be included in
# the build directory.
#
# See https://www.dune-project.org/dev/adding_python/ for docs on
# Python packaging for Dune modules.
#
""")
    f.write("import os, sys\n")
    if data.name == 'dune-common':
        f.write("here = os.path.dirname(os.path.abspath(__file__))\n")
        f.write("mods = os.path.join(here, \"python\", \"dune\")\n")
        f.write("sys.path.append(mods)\n\n")
    f.write("try:\n")
    f.write("    from dune.packagemetadata import metaData\n")
    f.write("except ImportError:\n")
    f.write("    from packagemetadata import metaData\n")
    f.write("from skbuild import setup\n")

    f.write("setup(**metaData('"+version+"')[1])\n")
    f.close()

    # Generate pyproject.toml
    print("Generate pyproject.toml")
    f = open("pyproject.toml", "w")
    f.write("""#
# DO NOT MODIFY THIS FILE!
# This file is autogenerated by the `dunepackaging.py` script and
# only used for the pypi dune packages. This file will not be included in
# the build directory.
#
# See https://www.dune-project.org/dev/adding_python/ for docs on
# Python packaging for Dune modules.
#
# This is uses the `Python-Requires` field in the `dune.modules` file to
# populate the `requires` entry. Additional packages needed for the package
# build should be added in the `dune.modules`. These packages will then also be
# included in the package install from source.
#
""")
    requires = data.asPythonRequirementString(data.depends + data.python_requires)
    requires = list(set(requires)) # make requirements unique
    minimal = ["pip", "setuptools", "wheel", "scikit-build", "cmake>=3.16", "ninja", "requests"]
    requires += [r for r in minimal if not any([a.startswith(r) for a in requires])]
    requires.sort()
    f.write("[build-system]\n")
    f.write("requires = "+requires.__str__()+"\n")
    f.write("build-backend = 'setuptools.build_meta'\n")
    f.close()

    # Create source distribution and upload to repository
    python = sys.executable
    if upload or onlysdist:
        print("Remove dist")
        remove = ['rm', '-rf', 'dist']
        subprocess.call(remove)

        # check if we have scikit-build
        import importlib
        if importlib.util.find_spec("skbuild") is None:
            print("Please install the pip package 'scikit-build' to build the source distribution.")
            sys.exit(2)

        # append hash of current git commit to README
        shutil.copy('README.md', 'tmp_README.md')
        githash = ['git', 'rev-parse', 'HEAD']
        hash = subprocess.check_output(githash, encoding='UTF-8')
        with open("README.md", "a") as f:
            f.write("\n\ngit-" + hash)

        print("Create source distribution")
        # make sure setup.py/pyproject.toml are tracked by git so that
        # they get added to the package by scikit
        gitadd = ['git', 'add', 'setup.py', 'pyproject.toml']
        subprocess.call(gitadd)
        # run sdist
        build = [python, 'setup.py', 'sdist']
        subprocess.call(build, stdout=subprocess.DEVNULL)
        # undo the above git add
        gitreset = ['git', 'reset', 'setup.py', 'pyproject.toml']
        subprocess.call(gitreset)

        # restore README.md
        shutil.move('tmp_README.md', 'README.md')

        if not onlysdist:
            # check if we have twine
            import importlib
            if importlib.util.find_spec("twine") is None:
                print("Please install the pip package 'twine' to upload the source distribution.")
                sys.exit(2)

            twine = [python, '-m', 'twine', 'upload']
            twine += ['--repository', repository]
            twine += ['dist/*']
            subprocess.call(twine)

            removeFiles()

        # create conda package meta.yaml (experimental)
        if bdistconda:
            import hashlib
            remove = ['rm', '-rf', 'dist/'+data.name]
            subprocess.call(remove)
            mkdir  = ['mkdir', 'dist/'+data.name ]
            subprocess.call(mkdir)

            print("Create bdist_conda (experimental)")
            distfile = 'dist/'+data.name+'-'+version+'.tar.gz'
            datahash = ''
            with open(distfile, "rb") as include:
                source = include.read()
                datahash = hashlib.sha256( source ).hexdigest()

            print("Generate ",'dist/'+data.name+'/meta.yaml')
            f = open('dist/'+data.name+'/meta.yaml', "w")
            f.write('{% set name = "' + data.name + '" %}\n')
            f.write('{% set version = "' + version + '" %}\n')
            f.write('{% set hash = "' + datahash + '" %}\n\n')
            f.write('package:\n')
            f.write('  name: "{{ name|lower }}"\n')
            f.write('  version: "{{ version }}"\n\n')
            f.write('source:\n')
            f.write('  path: ../{{ name }}-{{ version }}/\n')
            f.write('  sha256: {{ hash }}\n\n')
            f.write('build:\n')
            f.write('  number: 1\n')
            if 'TMPDIR' in os.environ:
                f.write('  script_env:\n')
                f.write('    - TMPDIR=' + os.environ['TMPDIR'] +'\n')
            f.write('  script: "{{ PYTHON }} -m pip install . --no-deps --ignore-installed -vv "\n\n')
            f.write('requirements:\n')

            requirements = ['pip', 'python', 'mkl', 'tbb', 'intel-openmp',
                            'libgcc-ng', 'libstdcxx-ng', 'gmp', 'scikit-build',
                            'mpi4py', 'matplotlib', 'numpy', 'scipy', 'ufl']

            for dep in data.depends:
                requirements += [dep[0]]

            f.write('  host:\n')
            for dep in requirements:
                f.write('    - ' + dep + '\n')

            f.write('\n')
            f.write('  run:\n')
            for dep in requirements:
                f.write('    - ' + dep + '\n')

            f.write('\n')
            f.write('test:\n')
            f.write('  imports:\n')
            f.write('    - ' + data.name.replace('-','.') + '\n\n')
            f.write('about:\n')
            f.write('  home: '+data.url+'\n')
            f.write('  license: GPLv2 with linking exception.\n')
            f.write('  license_family: GPL\n')
            f.write('  summary: '+data.description+'\n')
            f.close()

if __name__ == "__main__":
    main(sys.argv[1:])