setup.py 41.3 KB
Newer Older
1
#!/usr/bin/env python3
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Copyright 2017 Christoph Reiter <reiter.christoph@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301
# USA
18

19
import io
20 21
import os
import sys
22 23 24
import errno
import subprocess
import tarfile
25
import sysconfig
26
import tempfile
27 28
import posixpath

29 30
from email import parser

31 32 33 34 35
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

36
from distutils.core import Extension, Distribution, Command
37
from distutils.errors import DistutilsSetupError, DistutilsOptionError
38
from distutils.ccompiler import new_compiler
39
from distutils.sysconfig import get_python_lib, customize_compiler
40
from distutils import dir_util, log
41
from distutils.spawn import find_executable
42 43


44
PYGOBJECT_VERSION = "3.33.1"
45
GLIB_VERSION_REQUIRED = "2.48.0"
46 47 48 49
GI_VERSION_REQUIRED = "1.46.0"
PYCAIRO_VERSION_REQUIRED = "1.11.1"
LIBFFI_VERSION_REQUIRED = "3.0"

50 51 52 53
WITH_CAIRO = not bool(os.environ.get("PYGOBJECT_WITHOUT_PYCAIRO"))
"""Set PYGOBJECT_WITHOUT_PYCAIRO if you don't want to build with
cairo/pycairo support. Note that this option might get removed in the future.
"""
54

55

56
def is_dev_version():
Christoph Reiter's avatar
Christoph Reiter committed
57
    version = tuple(map(int, PYGOBJECT_VERSION.split(".")))
58 59 60
    return version[1] % 2 != 0


61 62 63 64 65 66 67 68
def get_command_class(name):
    # Returns the right class for either distutils or setuptools
    return Distribution({}).get_command_class(name)


def get_pycairo_pkg_config_name():
    return "py3cairo" if sys.version_info[0] == 3 else "pycairo"

69

70
def get_version_requirement(pkg_config_name):
71
    """Given a pkg-config module name gets the minimum version required"""
72

73 74 75 76 77 78 79 80
    versions = {
        "gobject-introspection-1.0": GI_VERSION_REQUIRED,
        "glib-2.0": GLIB_VERSION_REQUIRED,
        "gio-2.0": GLIB_VERSION_REQUIRED,
        get_pycairo_pkg_config_name(): PYCAIRO_VERSION_REQUIRED,
        "libffi": LIBFFI_VERSION_REQUIRED,
        "cairo": "0",
        "cairo-gobject": "0",
81
    }
82

83
    return versions[pkg_config_name]
84 85


86
def get_versions():
Christoph Reiter's avatar
Christoph Reiter committed
87
    version = PYGOBJECT_VERSION.split(".")
88
    assert len(version) == 3
89

90 91 92 93 94 95 96 97 98 99 100
    versions = {
        "PYGOBJECT_MAJOR_VERSION": version[0],
        "PYGOBJECT_MINOR_VERSION": version[1],
        "PYGOBJECT_MICRO_VERSION": version[2],
        "VERSION": ".".join(version),
    }
    return versions


def parse_pkg_info(conf_dir):
    """Returns an email.message.Message instance containing the content
101
    of the PKG-INFO file.
102 103
    """

104
    versions = get_versions()
105 106 107 108 109 110 111 112 113 114 115 116

    pkg_info = os.path.join(conf_dir, "PKG-INFO.in")
    with io.open(pkg_info, "r", encoding="utf-8") as h:
        text = h.read()
        for key, value in versions.items():
            text = text.replace("@%s@" % key, value)

    p = parser.Parser()
    message = p.parse(io.StringIO(text))
    return message


117 118 119 120 121 122 123 124 125 126 127 128 129
def pkg_config_get_install_hint():
    """Returns an installation hint for installing pkg-config or None"""

    if not sys.platform.startswith("linux"):
        return

    if find_executable("apt"):
        return "sudo apt install pkg-config"
    elif find_executable("dnf"):
        return "sudo dnf install pkg-config"


def pkg_config_get_package_install_hint(pkg_name):
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
    """Returns an installation hint for a pkg-config name or None"""

    if not sys.platform.startswith("linux"):
        return

    if find_executable("apt"):
        dev_packages = {
            "gobject-introspection-1.0": "libgirepository1.0-dev",
            "glib-2.0": "libglib2.0-dev",
            "gio-2.0": "libglib2.0-dev",
            "cairo": "libcairo2-dev",
            "cairo-gobject": "libcairo2-dev",
            "libffi": "libffi-dev",
        }
        if pkg_name in dev_packages:
            return "sudo apt install %s" % dev_packages[pkg_name]
    elif find_executable("dnf"):
        dev_packages = {
            "gobject-introspection-1.0": "gobject-introspection-devel",
            "glib-2.0": "glib2-devel",
            "gio-2.0": "glib2-devel",
            "cairo": "cairo-devel",
            "cairo-gobject": "cairo-gobject-devel",
            "libffi": "libffi-devel",
        }
        if pkg_name in dev_packages:
            return "sudo dnf install %s" % dev_packages[pkg_name]


class PkgConfigError(Exception):
    pass


163 164 165 166
class PkgConfigMissingError(PkgConfigError):
    pass


167 168 169 170 171 172 173
class PkgConfigMissingPackageError(PkgConfigError):
    pass


def _run_pkg_config(pkg_name, args, _cache={}):
    """Raises PkgConfigError"""

174 175 176 177 178 179 180
    command = tuple(["pkg-config"] + args)

    if command not in _cache:
        try:
            result = subprocess.check_output(command)
        except OSError as e:
            if e.errno == errno.ENOENT:
181
                raise PkgConfigMissingError(
182
                    "%r not found.\nArguments: %r" % (command[0], command))
183
            raise PkgConfigError(e)
184
        except subprocess.CalledProcessError as e:
185 186 187 188 189 190
            try:
                subprocess.check_output(["pkg-config", "--exists", pkg_name])
            except (subprocess.CalledProcessError, OSError):
                raise PkgConfigMissingPackageError(e)
            else:
                raise PkgConfigError(e)
191 192 193 194
        else:
            _cache[command] = result

    return _cache[command]
195 196


197 198 199
def _run_pkg_config_or_exit(pkg_name, args):
    try:
        return _run_pkg_config(pkg_name, args)
200 201 202 203 204 205 206
    except PkgConfigMissingError as e:
        hint = pkg_config_get_install_hint()
        if hint:
            raise SystemExit(
                "%s\n\nTry installing it with: %r" % (e, hint))
        else:
            raise SystemExit(e)
207
    except PkgConfigMissingPackageError as e:
208
        hint = pkg_config_get_package_install_hint(pkg_name)
209 210 211 212 213 214 215 216 217 218 219
        if hint:
            raise SystemExit(
                "%s\n\nTry installing it with: %r" % (e, hint))
        else:
            raise SystemExit(e)
    except PkgConfigError as e:
        raise SystemExit(e)


def pkg_config_version_check(pkg_name, version):
    _run_pkg_config_or_exit(pkg_name, [
220 221
        "--print-errors",
        "--exists",
222
        '%s >= %s' % (pkg_name, version),
223
    ])
224 225


226 227 228
def pkg_config_parse(opt, pkg_name):
    ret = _run_pkg_config_or_exit(pkg_name, [opt, pkg_name])

229 230 231 232
    if sys.version_info[0] == 3:
        output = ret.decode()
    else:
        output = ret
233 234
    opt = opt[-2:]
    return [x.lstrip(opt) for x in output.split()]
235

236

237 238 239 240
def list_headers(d):
    return [os.path.join(d, e) for e in os.listdir(d) if e.endswith(".h")]


241 242 243 244 245 246
def filter_compiler_arguments(compiler, args):
    """Given a compiler instance and a list of compiler warning flags
    returns the list of supported flags.
    """

    if compiler.compiler_type == "msvc":
Chun-wei Fan's avatar
Chun-wei Fan committed
247
        # TODO, not much of need for now.
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
        return []

    extra = []

    def check_arguments(compiler, args):
        p = subprocess.Popen(
            [compiler.compiler[0]] + args + extra + ["-x", "c", "-E", "-"],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)
        stdout, stderr = p.communicate(b"int i;\n")
        if p.returncode != 0:
            text = stderr.decode("ascii", "replace")
            return False, [a for a in args if a in text]
        else:
            return True, []

    def check_argument(compiler, arg):
        return check_arguments(compiler, [arg])[0]

    # clang doesn't error out for unknown options, force it to
    if check_argument(compiler, '-Werror=unknown-warning-option'):
        extra += ['-Werror=unknown-warning-option']
    if check_argument(compiler, '-Werror=unused-command-line-argument'):
        extra += ['-Werror=unused-command-line-argument']

    # first try to remove all arguments contained in the error message
    supported = list(args)
    while 1:
        ok, maybe_unknown = check_arguments(compiler, supported)
        if ok:
            return supported
        elif not maybe_unknown:
            break
        for unknown in maybe_unknown:
            if not check_argument(compiler, unknown):
                supported.remove(unknown)

    # hm, didn't work, try each argument one by one
    supported = []
    for arg in args:
        if check_argument(compiler, arg):
            supported.append(arg)
    return supported


294 295 296 297 298 299 300 301 302 303 304
class sdist_gnome(Command):
    description = "Create a source tarball for GNOME"
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
305
        # Don't use PEP 440 pre-release versions for GNOME releases
Christoph Reiter's avatar
Christoph Reiter committed
306
        self.distribution.metadata.version = PYGOBJECT_VERSION
307

308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
        dist_dir = tempfile.mkdtemp()
        try:
            cmd = self.reinitialize_command("sdist")
            cmd.dist_dir = dist_dir
            cmd.ensure_finalized()
            cmd.run()

            base_name = self.distribution.get_fullname().lower()
            cmd.make_release_tree(base_name, cmd.filelist.files)
            try:
                self.make_archive(base_name, "xztar", base_dir=base_name)
            finally:
                dir_util.remove_tree(base_name)
        finally:
            dir_util.remove_tree(dist_dir)


325 326 327 328 329
du_sdist = get_command_class("sdist")


class distcheck(du_sdist):
    """Creates a tarball and does some additional sanity checks such as
330 331
    checking if the tarball includes all files, builds successfully and
    the tests suite passes.
332
    """
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352

    def _check_manifest(self):
        # make sure MANIFEST.in includes all tracked files
        assert self.get_archive_files()

        if subprocess.call(["git", "status"],
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE) != 0:
            return

        included_files = self.filelist.files
        assert included_files

        process = subprocess.Popen(
            ["git", "ls-tree", "-r", "HEAD", "--name-only"],
            stdout=subprocess.PIPE, universal_newlines=True)
        out, err = process.communicate()
        assert process.returncode == 0

        tracked_files = out.splitlines()
353 354 355
        tracked_files = [
            f for f in tracked_files
            if os.path.basename(f) not in [".gitignore"]]
356 357 358 359 360 361 362 363 364 365

        diff = set(tracked_files) - set(included_files)
        assert not diff, (
            "Not all tracked files included in tarball, check MANIFEST.in",
            diff)

    def _check_dist(self):
        # make sure the tarball builds
        assert self.get_archive_files()

366 367
        distcheck_dir = os.path.abspath(
            os.path.join(self.dist_dir, "distcheck"))
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
        if os.path.exists(distcheck_dir):
            dir_util.remove_tree(distcheck_dir)
        self.mkpath(distcheck_dir)

        archive = self.get_archive_files()[0]
        tfile = tarfile.open(archive, "r:gz")
        tfile.extractall(distcheck_dir)
        tfile.close()

        name = self.distribution.get_fullname()
        extract_dir = os.path.join(distcheck_dir, name)

        old_pwd = os.getcwd()
        os.chdir(extract_dir)
        try:
            self.spawn([sys.executable, "setup.py", "build"])
            self.spawn([sys.executable, "setup.py", "install",
385 386 387 388 389
                        "--root",
                        os.path.join(distcheck_dir, "prefix"),
                        "--record",
                        os.path.join(distcheck_dir, "log.txt"),
                        ])
390
            self.spawn([sys.executable, "setup.py", "test"])
391 392 393
        finally:
            os.chdir(old_pwd)

394
    def run(self):
395 396 397 398 399
        du_sdist.run(self)
        self._check_manifest()
        self._check_dist()


400 401 402 403 404 405 406 407
class build_tests(Command):
    description = "build test libraries and extensions"
    user_options = [
        ("force", "f", "force a rebuild"),
    ]

    def initialize_options(self):
        self.build_temp = None
408
        self.build_base = None
409 410 411 412 413 414
        self.force = False

    def finalize_options(self):
        self.set_undefined_options(
            'build_ext',
            ('build_temp', 'build_temp'))
415 416 417
        self.set_undefined_options(
            'build',
            ('build_base', 'build_base'))
418

419 420 421
    def _newer_group(self, sources, *targets):
        assert targets

422 423 424 425 426
        from distutils.dep_util import newer_group

        if self.force:
            return True
        else:
427 428 429 430
            for target in targets:
                if not newer_group(sources, target):
                    return False
            return True
431 432

    def run(self):
433 434
        cmd = self.reinitialize_command("build_ext")
        cmd.inplace = True
435
        cmd.force = self.force
436 437 438
        cmd.ensure_finalized()
        cmd.run()

439 440 441 442 443 444 445 446
        gidatadir = pkg_config_parse(
            "--variable=gidatadir", "gobject-introspection-1.0")[0]
        g_ir_scanner = pkg_config_parse(
            "--variable=g_ir_scanner", "gobject-introspection-1.0")[0]
        g_ir_compiler = pkg_config_parse(
            "--variable=g_ir_compiler", "gobject-introspection-1.0")[0]

        script_dir = get_script_dir()
447
        gi_dir = os.path.join(script_dir, "gi")
448 449 450 451 452 453 454 455 456 457 458 459 460 461
        tests_dir = os.path.join(script_dir, "tests")
        gi_tests_dir = os.path.join(gidatadir, "tests")

        schema_xml = os.path.join(tests_dir, "org.gnome.test.gschema.xml")
        schema_bin = os.path.join(tests_dir, "gschemas.compiled")
        if self._newer_group([schema_xml], schema_bin):
            subprocess.check_call([
                "glib-compile-schemas",
                "--targetdir=%s" % tests_dir,
                "--schema-file=%s" % schema_xml,
            ])

        compiler = new_compiler()
        customize_compiler(compiler)
462

463 464
        if os.name == "nt":
            compiler.shared_lib_extension = ".dll"
465
        elif sys.platform == "darwin":
466 467 468 469 470
            compiler.shared_lib_extension = ".dylib"
            if "-bundle" in compiler.linker_so:
                compiler.linker_so = list(compiler.linker_so)
                i = compiler.linker_so.index("-bundle")
                compiler.linker_so[i] = "-dynamiclib"
471 472
        else:
            compiler.shared_lib_extension = ".so"
473

474 475 476 477 478
        if compiler.compiler_type == "msvc":
            g_ir_scanner_cmd = [sys.executable, g_ir_scanner]
        else:
            g_ir_scanner_cmd = [g_ir_scanner]

479
        def build_ext(ext):
480 481 482 483

            libname = compiler.shared_object_filename(ext.name)
            ext_paths = [os.path.join(tests_dir, libname)]
            if os.name == "nt":
484 485 486 487 488 489 490 491
                if compiler.compiler_type == "msvc":
                    # MSVC: Get rid of the 'lib' prefix and the .dll
                    #       suffix from libname, and append .lib so
                    #       that we get the right .lib filename to
                    #       pass to g-ir-scanner with --library
                    implibname = libname[3:libname.rfind(".dll")] + '.lib'
                else:
                    implibname = libname + ".a"
492
                ext_paths.append(os.path.join(tests_dir, implibname))
493

494
            if self._newer_group(ext.sources + ext.depends, *ext_paths):
495 496 497 498 499 500 501
                # MSVC: We need to define _GI_EXTERN explcitly so that
                #       symbols get exported properly
                if compiler.compiler_type == "msvc":
                    extra_defines = [('_GI_EXTERN',
                                      '__declspec(dllexport)extern')]
                else:
                    extra_defines = []
502 503 504
                objects = compiler.compile(
                    ext.sources,
                    output_dir=self.build_temp,
505
                    include_dirs=ext.include_dirs,
506
                    macros=ext.define_macros + extra_defines)
507

508
                if os.name == "nt":
509 510 511 512 513 514
                    if compiler.compiler_type == "msvc":
                        postargs = ["-implib:%s" %
                                    os.path.join(tests_dir, implibname)]
                    else:
                        postargs = ["-Wl,--out-implib=%s" %
                                    os.path.join(tests_dir, implibname)]
515 516 517
                else:
                    postargs = []

518 519
                compiler.link_shared_object(
                    objects,
520 521
                    compiler.shared_object_filename(ext.name),
                    output_dir=tests_dir,
522
                    libraries=ext.libraries,
523 524 525 526
                    library_dirs=ext.library_dirs,
                    extra_postargs=postargs)

            return ext_paths
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544

        ext = Extension(
            name='libgimarshallingtests',
            sources=[
                os.path.join(gi_tests_dir, "gimarshallingtests.c"),
                os.path.join(tests_dir, "gimarshallingtestsextra.c"),
            ],
            include_dirs=[
                gi_tests_dir,
                tests_dir,
            ],
            depends=[
                os.path.join(gi_tests_dir, "gimarshallingtests.h"),
                os.path.join(tests_dir, "gimarshallingtestsextra.h"),
            ],
        )
        add_ext_pkg_config_dep(ext, compiler.compiler_type, "glib-2.0")
        add_ext_pkg_config_dep(ext, compiler.compiler_type, "gio-2.0")
545
        ext_paths = build_ext(ext)
546

547 548 549 550 551 552
        # We want to always use POSIX-style paths for g-ir-compiler
        # because it expects the input .gir file and .typelib file to use
        # POSIX-style paths, otherwise it fails
        gir_path = posixpath.join(
            tests_dir, "GIMarshallingTests-1.0.gir")
        typelib_path = posixpath.join(
553 554
            tests_dir, "GIMarshallingTests-1.0.typelib")

555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
        gimarshal_g_ir_scanner_cmd = g_ir_scanner_cmd + [
            "--no-libtool",
            "--include=Gio-2.0",
            "--namespace=GIMarshallingTests",
            "--nsversion=1.0",
            "--symbol-prefix=gi_marshalling_tests",
            "--warn-all",
            "--warn-error",
            "--library-path=%s" % tests_dir,
            "--library=gimarshallingtests",
            "--pkg=glib-2.0",
            "--pkg=gio-2.0",
            "--cflags-begin",
            "-I%s" % gi_tests_dir,
            "--cflags-end",
            "--output=%s" % gir_path,
        ]

573
        if self._newer_group(ext_paths, gir_path):
574 575
            subprocess.check_call(gimarshal_g_ir_scanner_cmd +
                                  ext.sources + ext.depends)
576 577 578 579 580 581 582 583

        if self._newer_group([gir_path], typelib_path):
            subprocess.check_call([
                g_ir_compiler,
                gir_path,
                "--output=%s" % typelib_path,
            ])

584 585 586 587
        regress_macros = []
        if not WITH_CAIRO:
            regress_macros.append(("_GI_DISABLE_CAIRO", "1"))

588 589 590 591
        ext = Extension(
            name='libregress',
            sources=[
                os.path.join(gi_tests_dir, "regress.c"),
592
                os.path.join(tests_dir, "regressextra.c"),
593 594 595 596 597 598
            ],
            include_dirs=[
                gi_tests_dir,
            ],
            depends=[
                os.path.join(gi_tests_dir, "regress.h"),
599
                os.path.join(tests_dir, "regressextra.h"),
600
            ],
601
            define_macros=regress_macros,
602 603 604
        )
        add_ext_pkg_config_dep(ext, compiler.compiler_type, "glib-2.0")
        add_ext_pkg_config_dep(ext, compiler.compiler_type, "gio-2.0")
605 606 607 608
        if WITH_CAIRO:
            add_ext_pkg_config_dep(ext, compiler.compiler_type, "cairo")
            add_ext_pkg_config_dep(
                ext, compiler.compiler_type, "cairo-gobject")
609
        ext_paths = build_ext(ext)
610

611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
        # We want to always use POSIX-style paths for g-ir-compiler
        # because it expects the input .gir file and .typelib file to use
        # POSIX-style paths, otherwise it fails
        gir_path = posixpath.join(tests_dir, "Regress-1.0.gir")
        typelib_path = posixpath.join(tests_dir, "Regress-1.0.typelib")
        regress_g_ir_scanner_cmd = g_ir_scanner_cmd + [
            "--no-libtool",
            "--include=Gio-2.0",
            "--namespace=Regress",
            "--nsversion=1.0",
            "--warn-all",
            "--warn-error",
            "--library-path=%s" % tests_dir,
            "--library=regress",
            "--pkg=glib-2.0",
            "--pkg=gio-2.0"]
627

628
        if self._newer_group(ext_paths, gir_path):
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
            if WITH_CAIRO:
                regress_g_ir_scanner_cmd += ["--include=cairo-1.0"]
                # MSVC: We don't normally have the pkg-config files for
                # cairo and cairo-gobject, so use --extra-library
                # instead of --pkg to pass those to the linker, so that
                # g-ir-scanner won't fail due to linker errors
                if compiler.compiler_type == "msvc":
                    regress_g_ir_scanner_cmd += [
                        "--extra-library=cairo",
                        "--extra-library=cairo-gobject"]

                else:
                    regress_g_ir_scanner_cmd += [
                        "--pkg=cairo",
                        "--pkg=cairo-gobject"]
            else:
                regress_g_ir_scanner_cmd += ["-D_GI_DISABLE_CAIRO"]

            regress_g_ir_scanner_cmd += ["--output=%s" % gir_path]

            subprocess.check_call(regress_g_ir_scanner_cmd +
                                  ext.sources + ext.depends)
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667

        if self._newer_group([gir_path], typelib_path):
            subprocess.check_call([
                g_ir_compiler,
                gir_path,
                "--output=%s" % typelib_path,
            ])

        ext = Extension(
            name='tests.testhelper',
            sources=[
                os.path.join(tests_dir, "testhelpermodule.c"),
                os.path.join(tests_dir, "test-floating.c"),
                os.path.join(tests_dir, "test-thread.c"),
                os.path.join(tests_dir, "test-unknown.c"),
            ],
            include_dirs=[
668
                gi_dir,
669 670
                tests_dir,
            ],
671
            depends=list_headers(gi_dir) + list_headers(tests_dir),
672
            define_macros=[("PY_SSIZE_T_CLEAN", None)],
673 674 675
        )
        add_ext_pkg_config_dep(ext, compiler.compiler_type, "glib-2.0")
        add_ext_pkg_config_dep(ext, compiler.compiler_type, "gio-2.0")
676
        add_ext_compiler_flags(ext, compiler)
677 678

        dist = Distribution({"ext_modules": [ext]})
679 680 681 682 683

        build_cmd = dist.get_command_obj("build")
        build_cmd.build_base = os.path.join(self.build_base, "pygobject_tests")
        build_cmd.ensure_finalized()

684 685
        cmd = dist.get_command_obj("build_ext")
        cmd.inplace = True
686
        cmd.force = self.force
687 688 689 690
        cmd.ensure_finalized()
        cmd.run()


691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
def get_suppression_files_for_prefix(prefix):
    """Returns a list of valgrind suppression files for a given prefix"""

    # Most specific first (/usr/share/doc is Fedora, /usr/lib is Debian)
    # Take the first one found
    major = str(sys.version_info[0])
    minor = str(sys.version_info[1])
    pyfiles = []
    pyfiles.append(
        os.path.join(
            prefix, "share", "doc", "python%s%s" % (major, minor),
            "valgrind-python.supp"))
    pyfiles.append(
        os.path.join(prefix, "lib", "valgrind", "python%s.supp" % major))
    pyfiles.append(
        os.path.join(
            prefix, "share", "doc", "python%s-devel" % major,
            "valgrind-python.supp"))
    pyfiles.append(os.path.join(prefix, "lib", "valgrind", "python.supp"))

    files = []
    for f in pyfiles:
        if os.path.isfile(f):
            files.append(f)
            break

    files.append(os.path.join(
        prefix, "share", "glib-2.0", "valgrind", "glib.supp"))
    return [f for f in files if os.path.isfile(f)]


def get_real_prefix():
    """Returns the base Python prefix, even in a virtualenv/venv"""

    return getattr(sys, "base_prefix", getattr(sys, "real_prefix", sys.prefix))


def get_suppression_files():
    """Returns a list of valgrind suppression files"""

    prefixes = [
        sys.prefix,
        get_real_prefix(),
        pkg_config_parse("--variable=prefix", "glib-2.0")[0],
    ]

    files = []
    for prefix in prefixes:
        files.extend(get_suppression_files_for_prefix(prefix))
740 741

    files.append(os.path.join(get_script_dir(), "tests", "valgrind.supp"))
742 743 744
    return sorted(set(files))


745
class test(Command):
746 747 748
    user_options = [
        ("valgrind", None, "run tests under valgrind"),
        ("valgrind-log-file=", None, "save logs instead of printing them"),
749
        ("gdb", None, "run tests under gdb"),
750
        ("no-capture", "s", "don't capture test output"),
751
    ]
752 753

    def initialize_options(self):
754 755
        self.valgrind = None
        self.valgrind_log_file = None
756
        self.gdb = None
757
        self.no_capture = None
758 759

    def finalize_options(self):
760 761 762
        self.valgrind = bool(self.valgrind)
        if self.valgrind_log_file and not self.valgrind:
            raise DistutilsOptionError("valgrind not enabled")
763
        self.gdb = bool(self.gdb)
764
        self.no_capture = bool(self.no_capture)
765 766 767 768 769 770

    def run(self):
        cmd = self.reinitialize_command("build_tests")
        cmd.ensure_finalized()
        cmd.run()

771 772
        env = os.environ.copy()
        env.pop("MSYSTEM", None)
773

774 775 776
        if self.no_capture:
            env["PYGI_TEST_VERBOSE"] = "1"

777 778 779 780
        env["MALLOC_PERTURB_"] = "85"
        env["MALLOC_CHECK_"] = "3"
        env["G_SLICE"] = "debug-blocks"

781 782
        pre_args = []

783 784 785 786 787
        if self.valgrind:
            env["G_SLICE"] = "always-malloc"
            env["G_DEBUG"] = "gc-friendly"
            env["PYTHONMALLOC"] = "malloc"

788
            pre_args += [
789 790 791 792 793 794
                "valgrind", "--leak-check=full", "--show-possibly-lost=no",
                "--num-callers=20", "--child-silent-after-fork=yes",
            ] + ["--suppressions=" + f for f in get_suppression_files()]

            if self.valgrind_log_file:
                pre_args += ["--log-file=" + self.valgrind_log_file]
795 796 797 798

        if self.gdb:
            env["PYGI_TEST_GDB"] = "1"
            pre_args += ["gdb", "--args"]
799 800 801 802

        if pre_args:
            log.info(" ".join(pre_args))

803
        tests_dir = os.path.join(get_script_dir(), "tests")
804
        sys.exit(subprocess.call(pre_args + [
805 806
            sys.executable,
            os.path.join(tests_dir, "runtests.py"),
807
        ], env=env))
808 809


810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
class quality(Command):
    description = "run code quality tests"
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        status = subprocess.call([
            sys.executable, "-m", "flake8",
        ], cwd=get_script_dir())
        if status != 0:
            raise SystemExit(status)


828 829 830 831 832 833
def get_script_dir():
    return os.path.dirname(os.path.realpath(__file__))


def get_pycairo_include_dir():
    """Returns the best guess at where to find the pycairo headers.
834 835
    A bit convoluted because we have to deal with multiple pycairo
    versions.
836

837
    Raises if pycairo isn't found or it's too old.
838 839
    """

840
    pkg_config_name = get_pycairo_pkg_config_name()
841
    min_version = get_version_requirement(pkg_config_name)
842
    min_version_info = tuple(int(p) for p in min_version.split("."))
843

844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
    def check_path(include_dir):
        log.info("pycairo: trying include directory: %r" % include_dir)
        header_path = os.path.join(include_dir, "%s.h" % pkg_config_name)
        if os.path.exists(header_path):
            log.info("pycairo: found %r" % header_path)
            return True
        log.info("pycairo: header file (%r) not found" % header_path)
        return False

    def find_path(paths):
        for p in reversed(paths):
            if check_path(p):
                return p

    def find_new_api():
        log.info("pycairo: new API")
        import cairo

862
        if cairo.version_info < min_version_info:
863
            raise DistutilsSetupError(
864 865
                "pycairo >= %s required, %s found." % (
                    min_version, ".".join(map(str, cairo.version_info))))
866 867 868 869 870 871 872 873

        if hasattr(cairo, "get_include"):
            return [cairo.get_include()]
        log.info("pycairo: no get_include()")
        return []

    def find_old_api():
        log.info("pycairo: old API")
874 875 876 877 878 879 880 881 882 883

        import cairo

        if cairo.version_info < min_version_info:
            raise DistutilsSetupError(
                "pycairo >= %s required, %s found." % (
                    min_version, ".".join(map(str, cairo.version_info))))

        location = os.path.dirname(os.path.abspath(cairo.__path__[0]))
        log.info("pycairo: found %r" % location)
884 885 886 887 888 889 890 891 892 893 894

        def samefile(src, dst):
            # Python 2 on Windows doesn't have os.path.samefile, so we have to
            # provide a fallback
            if hasattr(os.path, "samefile"):
                return os.path.samefile(src, dst)
            os.stat(src)
            os.stat(dst)
            return (os.path.normcase(os.path.abspath(src)) ==
                    os.path.normcase(os.path.abspath(dst)))

895
        def get_sys_path(location, name):
896 897 898 899 900 901 902 903 904 905
            # Returns the sysconfig path for a distribution, or None
            for scheme in sysconfig.get_scheme_names():
                for path_type in ["platlib", "purelib"]:
                    path = sysconfig.get_path(path_type, scheme)
                    try:
                        if samefile(path, location):
                            return sysconfig.get_path(name, scheme)
                    except EnvironmentError:
                        pass

906
        data_path = get_sys_path(location, "data") or sys.prefix
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
        return [os.path.join(data_path, "include", "pycairo")]

    def find_pkg_config():
        log.info("pycairo: pkg-config")
        pkg_config_version_check(pkg_config_name, min_version)
        return pkg_config_parse("--cflags-only-I", pkg_config_name)

    # First the new get_include() API added in >1.15.6
    include_dir = find_path(find_new_api())
    if include_dir is not None:
        return include_dir

    # Then try to find it in the data prefix based on the module path.
    # This works with many virtualenv/userdir setups, but not all apparently,
    # see https://gitlab.gnome.org/GNOME/pygobject/issues/150
    include_dir = find_path(find_old_api())
    if include_dir is not None:
        return include_dir

    # Finally, fall back to pkg-config
    include_dir = find_path(find_pkg_config())
    if include_dir is not None:
        return include_dir

    raise DistutilsSetupError("Could not find pycairo headers")
932 933 934 935 936 937 938 939 940 941 942 943 944 945


def add_ext_pkg_config_dep(ext, compiler_type, name):
    msvc_libraries = {
        "glib-2.0": ["glib-2.0"],
        "gio-2.0": ["gio-2.0", "gobject-2.0", "glib-2.0"],
        "gobject-introspection-1.0":
            ["girepository-1.0", "gobject-2.0", "glib-2.0"],
        "cairo": ["cairo"],
        "cairo-gobject":
            ["cairo-gobject", "cairo", "gobject-2.0", "glib-2.0"],
        "libffi": ["ffi"],
    }

946 947 948 949 950
    def add(target, new):
        for entry in new:
            if entry not in target:
                target.append(entry)

951 952 953
    fallback_libs = msvc_libraries[name]
    if compiler_type == "msvc":
        # assume that INCLUDE and LIB contains the right paths
954
        add(ext.libraries, fallback_libs)
955
    else:
956
        min_version = get_version_requirement(name)
957
        pkg_config_version_check(name, min_version)
958 959 960
        add(ext.include_dirs, pkg_config_parse("--cflags-only-I", name))
        add(ext.library_dirs, pkg_config_parse("--libs-only-L", name))
        add(ext.libraries, pkg_config_parse("--libs-only-l", name))
961 962


963
def add_ext_compiler_flags(ext, compiler, _cache={}):
Chun-wei Fan's avatar
Chun-wei Fan committed
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
    if compiler.compiler_type == "msvc":
        # MSVC: Just force-include msvc_recommended_pragmas.h so that
        #       we can look out for compiler warnings that we really
        #       want to look out for, and filter out those that don't
        #       really matter to us.
        ext.extra_compile_args += ['-FImsvc_recommended_pragmas.h']
    else:
        cache_key = compiler.compiler[0]
        if cache_key not in _cache:

            args = [
                "-Wall",
                "-Warray-bounds",
                "-Wcast-align",
                "-Wduplicated-branches",
                "-Wextra",
                "-Wformat=2",
                "-Wformat-nonliteral",
                "-Wformat-security",
                "-Wimplicit-function-declaration",
                "-Winit-self",
                "-Wjump-misses-init",
                "-Wlogical-op",
                "-Wmissing-declarations",
                "-Wmissing-format-attribute",
                "-Wmissing-include-dirs",
                "-Wmissing-noreturn",
                "-Wmissing-prototypes",
                "-Wnested-externs",
                "-Wnull-dereference",
                "-Wold-style-definition",
                "-Wpacked",
                "-Wpointer-arith",
                "-Wrestrict",
                "-Wreturn-type",
                "-Wshadow",
                "-Wsign-compare",
                "-Wstrict-aliasing",
                "-Wstrict-prototypes",
1003
                "-Wswitch-default",
Chun-wei Fan's avatar
Chun-wei Fan committed
1004 1005 1006 1007 1008
                "-Wundef",
                "-Wunused-but-set-variable",
                "-Wwrite-strings",
            ]

1009 1010 1011 1012 1013
            if sys.version_info[0] == 2:
                args += [
                    "-Wdeclaration-after-statement",
                ]

1014
            args += [
Chun-wei Fan's avatar
Chun-wei Fan committed
1015 1016 1017 1018 1019 1020 1021
                "-Wno-incompatible-pointer-types-discards-qualifiers",
                "-Wno-missing-field-initializers",
                "-Wno-unused-parameter",
                "-Wno-discarded-qualifiers",
                "-Wno-sign-conversion",
                "-Wno-cast-function-type",
                "-Wno-int-conversion",
1022 1023
            ]

Chun-wei Fan's avatar
Chun-wei Fan committed
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
            # silence clang for unused gcc CFLAGS added by Debian
            args += [
                "-Wno-unused-command-line-argument",
            ]

            args += [
                "-fno-strict-aliasing",
                "-fvisibility=hidden",
            ]

            # force GCC to use colors
            if hasattr(sys.stdout, "isatty") and sys.stdout.isatty():
                args.append("-fdiagnostics-color")

            _cache[cache_key] = filter_compiler_arguments(compiler, args)

        ext.extra_compile_args += _cache[cache_key]
1041 1042


1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
du_build_ext = get_command_class("build_ext")


class build_ext(du_build_ext):

    def initialize_options(self):
        du_build_ext.initialize_options(self)
        self.compiler_type = None

    def finalize_options(self):
        du_build_ext.finalize_options(self)
        self.compiler_type = new_compiler(compiler=self.compiler).compiler_type

    def _write_config_h(self):
1057
        script_dir = get_script_dir()
1058
        target = os.path.join(script_dir, "config.h")
1059 1060
        versions = get_versions()
        content = u"""
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
/* Configuration header created by setup.py - do not edit */
#ifndef _CONFIG_H
#define _CONFIG_H 1

#define PYGOBJECT_MAJOR_VERSION %(PYGOBJECT_MAJOR_VERSION)s
#define PYGOBJECT_MINOR_VERSION %(PYGOBJECT_MINOR_VERSION)s
#define PYGOBJECT_MICRO_VERSION %(PYGOBJECT_MICRO_VERSION)s
#define VERSION "%(VERSION)s"

#endif /* _CONFIG_H */
1071 1072
""" % versions

1073 1074 1075 1076 1077 1078
        try:
            with io.open(target, 'r', encoding="utf-8") as h:
                if h.read() == content:
                    return
        except EnvironmentError:
            pass
1079 1080 1081

        with io.open(target, 'w', encoding="utf-8") as h:
            h.write(content)
1082

1083 1084 1085
    def _setup_extensions(self):
        ext = {e.name: e for e in self.extensions}

1086 1087 1088
        compiler = new_compiler(compiler=self.compiler)
        customize_compiler(compiler)

1089
        def add_dependency(ext, name):
1090
            add_ext_pkg_config_dep(ext, compiler.compiler_type, name)
1091

1092
        def add_pycairo(ext):
1093
            ext.include_dirs += [get_pycairo_include_dir()]
1094

1095 1096 1097 1098 1099
        gi_ext = ext["gi._gi"]
        add_dependency(gi_ext, "glib-2.0")
        add_dependency(gi_ext, "gio-2.0")
        add_dependency(gi_ext, "gobject-introspection-1.0")
        add_dependency(gi_ext, "libffi")
1100
        add_ext_compiler_flags(gi_ext, compiler)
1101

1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
        if WITH_CAIRO:
            gi_cairo_ext = ext["gi._gi_cairo"]
            add_dependency(gi_cairo_ext, "glib-2.0")
            add_dependency(gi_cairo_ext, "gio-2.0")
            add_dependency(gi_cairo_ext, "gobject-introspection-1.0")
            add_dependency(gi_cairo_ext, "libffi")
            add_dependency(gi_cairo_ext, "cairo")
            add_dependency(gi_cairo_ext, "cairo-gobject")
            add_pycairo(gi_cairo_ext)
            add_ext_compiler_flags(gi_cairo_ext, compiler)
1112 1113

    def run(self):
1114 1115 1116 1117 1118
        self._write_config_h()
        self._setup_extensions()
        du_build_ext.run(self)


1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
class install_pkgconfig(Command):
    description = "install .pc file"
    user_options = []

    def initialize_options(self):
        self.install_base = None
        self.install_platbase = None
        self.install_data = None
        self.compiler_type = None
        self.outfiles = []

    def finalize_options(self):
        self.set_undefined_options(
            'install',
            ('install_base', 'install_base'),
            ('install_data', 'install_data'),
            ('install_platbase', 'install_platbase'),
        )

        self.set_undefined_options(
            'build_ext',
            ('compiler_type', 'compiler_type'),
        )

    def get_outputs(self):
        return self.outfiles

    def get_inputs(self):
        return []

    def run(self):
        cmd = self.distribution.get_command_obj("bdist_wheel", create=False)
        if cmd is not None:
            log.warn(
                "Python wheels and pkg-config is not compatible. "
                "No pkg-config file will be included in the wheel. Install "
                "from source if you need one.")
            return

        if self.compiler_type == "msvc":
            return

        script_dir = get_script_dir()
        pkgconfig_in = os.path.join(script_dir, "pygobject-3.0.pc.in")
        with io.open(pkgconfig_in, "r", encoding="utf-8") as h:
            content = h.read()

        config = {
            "prefix": self.install_base,
            "exec_prefix": self.install_platbase,
            "includedir": "${prefix}/include",
            "datarootdir": "${prefix}/share",
            "datadir": "${datarootdir}",
Christoph Reiter's avatar
Christoph Reiter committed
1172
            "VERSION": PYGOBJECT_VERSION,
1173 1174 1175 1176
        }
        for key, value in config.items():
            content = content.replace("@%s@" % key, value)

1177 1178
        libdir = os.path.dirname(get_python_lib(True, True, self.install_data))
        pkgconfig_dir = os.path.join(libdir, "pkgconfig")
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
        self.mkpath(pkgconfig_dir)
        target = os.path.join(pkgconfig_dir, "pygobject-3.0.pc")
        with io.open(target, "w", encoding="utf-8") as h:
            h.write(content)
        self.outfiles.append(target)


du_install = get_command_class("install")


class install(du_install):

    sub_commands = du_install.sub_commands + [
        ("install_pkgconfig", lambda self: True),
    ]


1196
def main():
1197
    script_dir = get_script_dir()
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
    pkginfo = parse_pkg_info(script_dir)
    gi_dir = os.path.join(script_dir, "gi")

    sources = [
        os.path.join("gi", n) for n in os.listdir(gi_dir)
        if os.path.splitext(n)[-1] == ".c"
    ]
    cairo_sources = [os.path.join("gi", "pygi-foreign-cairo.c")]
    for s in cairo_sources:
        sources.remove(s)

1209 1210 1211 1212
    readme = os.path.join(script_dir, "README.rst")
    with io.open(readme, encoding="utf-8") as h:
        long_description = h.read()

1213 1214 1215
    ext_modules = []
    install_requires = []

1216 1217
    gi_ext = Extension(
        name='gi._gi',
1218
        sources=sorted(sources),
1219
        include_dirs=[script_dir, gi_dir],
1220
        depends=list_headers(script_dir) + list_headers(gi_dir),
1221
        define_macros=[("PY_SSIZE_T_CLEAN", None)],
1222
    )
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
    ext_modules.append(gi_ext)

    if WITH_CAIRO:
        gi_cairo_ext = Extension(
            name='gi._gi_cairo',
            sources=cairo_sources,
            include_dirs=[script_dir, gi_dir],
            depends=list_headers(script_dir) + list_headers(gi_dir),
            define_macros=[("PY_SSIZE_T_CLEAN", None)],
        )
        ext_modules.append(gi_cairo_ext)
        install_requires.append(
            "pycairo>=%s" % get_version_requirement(
                get_pycairo_pkg_config_name()))
1237

1238 1239 1240 1241
    version = pkginfo["Version"]
    if is_dev_version():
        # This makes it a PEP 440 pre-release and pip will only install it from
        # PyPI in case --pre is passed.
1242
        version += ".dev0"
1243

1244 1245
    setup(
        name=pkginfo["Name"],
1246
        version=version,
1247 1248 1249 1250 1251 1252 1253
        description=pkginfo["Summary"],
        url=pkginfo["Home-page"],
        author=pkginfo["Author"],
        author_email=pkginfo["Author-email"],
        maintainer=pkginfo["Maintainer"],
        maintainer_email=pkginfo["Maintainer-email"],
        license=pkginfo["License"],
1254
        long_description=long_description,
1255 1256
        platforms=pkginfo.get_all("Platform"),
        classifiers=pkginfo.get_all("Classifier"),
1257 1258 1259 1260 1261 1262
        packages=[
            "pygtkcompat",
            "gi",
            "gi.repository",
            "gi.overrides",
        ],
1263
        ext_modules=ext_modules,
1264 1265 1266
        cmdclass={
            "build_ext": build_ext,
            "distcheck": distcheck,
1267
            "sdist_gnome": sdist_gnome,
1268 1269
            "build_tests": build_tests,
            "test": test,
1270
            "quality": quality,
1271 1272
            "install": install,
            "install_pkgconfig": install_pkgconfig,
1273
        },
1274
        install_requires=install_requires,
1275 1276
        python_requires=(
            '>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, <4'),
1277 1278 1279
        data_files=[
            ('include/pygobject-3.0', ['gi/pygobject.h']),
        ],
1280
        zip_safe=False,
1281 1282 1283 1284 1285
    )


if __name__ == "__main__":
    main()