Browse Source

makepanda: Code formatting

rdb 5 years ago
parent
commit
2b84bfc145
6 changed files with 650 additions and 506 deletions
  1. 1 1
      makepanda/getversion.py
  2. 122 81
      makepanda/installpanda.py
  3. 147 68
      makepanda/makepackage.py
  4. 282 281
      makepanda/makepanda.py
  5. 96 70
      makepanda/makepandacore.py
  6. 2 5
      makepanda/makewheel.py

+ 1 - 1
makepanda/getversion.py

@@ -4,8 +4,8 @@
 # and returns it on the command-line.  This is useful for the
 # automated scripts that build the Panda3D releases.
 
-from makepandacore import ParsePandaVersion, GetMetadataValue
 import sys
+from makepandacore import GetMetadataValue
 
 version = GetMetadataValue('version')
 

+ 122 - 81
makepanda/installpanda.py

@@ -8,17 +8,18 @@
 #
 ########################################################################
 
-import os, sys, platform
+import os
+import sys
 from distutils.sysconfig import get_python_lib
 from optparse import OptionParser
 from makepandacore import *
 
 
 MIME_INFO = (
-  ("egg", "model/x-egg", "EGG model file", "pview"),
-  ("bam", "model/x-bam", "Panda3D binary model file", "pview"),
-  ("egg.pz", "model/x-compressed-egg", "Compressed EGG model file", "pview"),
-  ("bam.pz", "model/x-compressed-bam", "Compressed Panda3D binary model file", "pview"),
+    ("egg", "model/x-egg", "EGG model file", "pview"),
+    ("bam", "model/x-bam", "Panda3D binary model file", "pview"),
+    ("egg.pz", "model/x-compressed-egg", "Compressed EGG model file", "pview"),
+    ("bam.pz", "model/x-compressed-bam", "Compressed Panda3D binary model file", "pview"),
 )
 
 APP_INFO = (
@@ -46,6 +47,7 @@ def WriteApplicationsFile(fname, appinfo, mimeinfo):
         fhandle.write("\n\n")
     fhandle.close()
 
+
 def WriteMimeXMLFile(fname, info):
     fhandle = open(fname, "w")
     fhandle.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
@@ -58,6 +60,7 @@ def WriteMimeXMLFile(fname, info):
     fhandle.write("</mime-info>\n")
     fhandle.close()
 
+
 def WriteMimeFile(fname, info):
     fhandle = open(fname, "w")
     for ext, mime, desc, app in info:
@@ -68,6 +71,7 @@ def WriteMimeFile(fname, info):
         fhandle.write("\n")
     fhandle.close()
 
+
 def WriteKeysFile(fname, info):
     fhandle = open(fname, "w")
     for ext, mime, desc, app in info:
@@ -80,6 +84,7 @@ def WriteKeysFile(fname, info):
         fhandle.write("\n")
     fhandle.close()
 
+
 def GetDebLibDir():
     """ Returns the lib dir according to the debian system. """
     # We're on Debian or Ubuntu, which use multiarch directories.
@@ -94,6 +99,7 @@ def GetDebLibDir():
 
     return "lib"
 
+
 def GetRPMLibDir():
     """ Returns the lib dir according to the rpm system. """
     handle = os.popen("rpm -E '%_lib'")
@@ -105,11 +111,12 @@ def GetRPMLibDir():
     else:
         return "lib"
 
+
 def GetLibDir():
-    """ Returns the directory to install architecture-dependent
+    """Returns the directory to install architecture-dependent
     libraries in, relative to the prefix directory.  This may be
     something like "lib" or "lib64" or in some cases, something
-    similar to "lib/x86_64-linux-gnu". """
+    similar to "lib/x86_64-linux-gnu"."""
 
     if sys.platform in ("darwin", "win32", "cygwin"):
         return "lib"
@@ -142,128 +149,160 @@ def GetLibDir():
     return "lib"
 
 def InstallPanda(destdir="", prefix="/usr", outputdir="built", libdir=GetLibDir(), python_versions=[]):
-    if (not prefix.startswith("/")):
+    if not prefix.startswith("/"):
         prefix = "/" + prefix
     libdir = prefix + "/" + libdir
 
+    dest_prefix = destdir + prefix
+    dest_libdir = destdir + libdir
+
     # Create the directory structure that we will be putting our files in.
     # Don't use os.makedirs or mkdir -p; neither properly set permissions for
     # created intermediate directories.
-    MakeDirectory(destdir+prefix+"/bin", mode=0o755, recursive=True)
-    MakeDirectory(destdir+prefix+"/include", mode=0o755)
-    MakeDirectory(destdir+prefix+"/include/panda3d", mode=0o755)
-    MakeDirectory(destdir+prefix+"/share", mode=0o755)
-    MakeDirectory(destdir+prefix+"/share/panda3d", mode=0o755)
-    MakeDirectory(destdir+prefix+"/share/mime-info", mode=0o755)
-    MakeDirectory(destdir+prefix+"/share/mime", mode=0o755)
-    MakeDirectory(destdir+prefix+"/share/mime/packages", mode=0o755)
-    MakeDirectory(destdir+prefix+"/share/application-registry", mode=0o755)
-    MakeDirectory(destdir+prefix+"/share/applications", mode=0o755)
-    MakeDirectory(destdir+libdir+"/panda3d", mode=0o755, recursive=True)
+    MakeDirectory(dest_prefix + "/bin", mode=0o755, recursive=True)
+    MakeDirectory(dest_prefix + "/include", mode=0o755)
+    MakeDirectory(dest_prefix + "/include/panda3d", mode=0o755)
+    MakeDirectory(dest_prefix + "/share", mode=0o755)
+    MakeDirectory(dest_prefix + "/share/panda3d", mode=0o755)
+    MakeDirectory(dest_prefix + "/share/mime-info", mode=0o755)
+    MakeDirectory(dest_prefix + "/share/mime", mode=0o755)
+    MakeDirectory(dest_prefix + "/share/mime/packages", mode=0o755)
+    MakeDirectory(dest_prefix + "/share/application-registry", mode=0o755)
+    MakeDirectory(dest_prefix + "/share/applications", mode=0o755)
+    MakeDirectory(dest_libdir + "/panda3d", mode=0o755, recursive=True)
 
     for python_version in python_versions:
-        MakeDirectory(destdir+python_version["purelib"], mode=0o755, recursive=True)
-        MakeDirectory(destdir+python_version["platlib"]+"/panda3d", mode=0o755, recursive=True)
+        MakeDirectory(destdir + python_version["purelib"], mode=0o755, recursive=True)
+        MakeDirectory(destdir + python_version["platlib"] + "/panda3d", mode=0o755, recursive=True)
 
-    if (sys.platform.startswith("freebsd")):
-        MakeDirectory(destdir+prefix+"/etc", mode=0o755)
-        MakeDirectory(destdir+"/usr/local/libdata/ldconfig", mode=0o755, recursive=True)
+    if sys.platform.startswith("freebsd"):
+        MakeDirectory(dest_prefix + "/etc", mode=0o755)
+        MakeDirectory(destdir + "/usr/local/libdata/ldconfig", mode=0o755, recursive=True)
     else:
-        MakeDirectory(destdir+"/etc/ld.so.conf.d", mode=0o755, recursive=True)
+        MakeDirectory(destdir + "/etc/ld.so.conf.d", mode=0o755, recursive=True)
 
     # Write the Config.prc file.
-    Configrc = ReadFile(outputdir+"/etc/Config.prc")
-    Configrc = Configrc.replace("model-path    $THIS_PRC_DIR/..", "model-path    "+prefix+"/share/panda3d")
-    if (sys.platform.startswith("freebsd")):
-        WriteFile(destdir+prefix+"/etc/Config.prc", Configrc)
-        oscmd("cp "+outputdir+"/etc/Confauto.prc "+destdir+prefix+"/etc/Confauto.prc")
+    Configrc = ReadFile(outputdir + "/etc/Config.prc")
+    Configrc = Configrc.replace("model-path    $THIS_PRC_DIR/..", "model-path    " + prefix + "/share/panda3d")
+    if sys.platform.startswith("freebsd"):
+        WriteFile(dest_prefix + "/etc/Config.prc", Configrc)
+        oscmd(f"cp {outputdir}/etc/Confauto.prc {dest_prefix}/etc/Confauto.prc")
     else:
         WriteFile(destdir+"/etc/Config.prc", Configrc)
-        oscmd("cp "+outputdir+"/etc/Confauto.prc "+destdir+"/etc/Confauto.prc")
-
-    oscmd("cp -R "+outputdir+"/include/*        "+destdir+prefix+"/include/panda3d/")
-    oscmd("cp -R "+outputdir+"/pandac           "+destdir+prefix+"/share/panda3d/")
-    oscmd("cp -R "+outputdir+"/models           "+destdir+prefix+"/share/panda3d/")
-    if os.path.isdir("samples"):             oscmd("cp -R samples               "+destdir+prefix+"/share/panda3d/")
-    if os.path.isdir(outputdir+"/direct"):   oscmd("cp -R "+outputdir+"/direct           "+destdir+prefix+"/share/panda3d/")
-    if os.path.isdir(outputdir+"/Pmw"):      oscmd("cp -R "+outputdir+"/Pmw     "+destdir+prefix+"/share/panda3d/")
-    if os.path.isdir(outputdir+"/plugins"):  oscmd("cp -R "+outputdir+"/plugins "+destdir+prefix+"/share/panda3d/")
+        oscmd(f"cp {outputdir}/etc/Confauto.prc {destdir}/etc/Confauto.prc")
+
+    oscmd(f"cp -R {outputdir}/include/* {dest_prefix}/include/panda3d/")
+    oscmd(f"cp -R {outputdir}/pandac {dest_prefix}/share/panda3d/")
+    oscmd(f"cp -R {outputdir}/models {dest_prefix}/share/panda3d/")
+    if os.path.isdir("samples"):
+        oscmd(f"cp -R samples {dest_prefix}/share/panda3d/")
+    if os.path.isdir(outputdir + "/direct"):
+        oscmd(f"cp -R {outputdir}/direct {dest_prefix}/share/panda3d/")
+    if os.path.isdir(outputdir + "/Pmw"):
+        oscmd(f"cp -R {outputdir}/Pmw {dest_prefix}/share/panda3d/")
+    if os.path.isdir(outputdir + "/plugins"):
+        oscmd(f"cp -R {outputdir}/plugins {dest_prefix}/share/panda3d/")
 
     for python_version in python_versions:
         for base in os.listdir(outputdir + "/panda3d"):
             suffix = python_version["ext_suffix"]
             platlib = python_version["platlib"]
             if base.endswith(".py") or (base.endswith(suffix) and '.' not in base[:-len(suffix)]):
-                oscmd("cp "+outputdir+"/panda3d/"+base+" "+destdir+platlib+"/panda3d/"+base)
+                oscmd(f"cp {outputdir}/panda3d/{base} {destdir}{platlib}/panda3d/{base}")
 
-    WriteMimeFile(destdir+prefix+"/share/mime-info/panda3d.mime", MIME_INFO)
-    WriteKeysFile(destdir+prefix+"/share/mime-info/panda3d.keys", MIME_INFO)
-    WriteMimeXMLFile(destdir+prefix+"/share/mime/packages/panda3d.xml", MIME_INFO)
-    WriteApplicationsFile(destdir+prefix+"/share/application-registry/panda3d.applications", APP_INFO, MIME_INFO)
-    if os.path.isfile(outputdir+"/bin/pview"):
-        oscmd("cp makepanda/pview.desktop "+destdir+prefix+"/share/applications/pview.desktop")
+    WriteMimeFile(dest_prefix + "/share/mime-info/panda3d.mime", MIME_INFO)
+    WriteKeysFile(dest_prefix + "/share/mime-info/panda3d.keys", MIME_INFO)
+    WriteMimeXMLFile(dest_prefix + "/share/mime/packages/panda3d.xml", MIME_INFO)
+    WriteApplicationsFile(dest_prefix + "/share/application-registry/panda3d.applications", APP_INFO, MIME_INFO)
+    if os.path.isfile(outputdir + "/bin/pview"):
+        oscmd(f"cp makepanda/pview.desktop {dest_prefix}/share/applications/pview.desktop")
 
-    oscmd("cp doc/ReleaseNotes                  "+destdir+prefix+"/share/panda3d/ReleaseNotes")
+    oscmd(f"cp doc/ReleaseNotes {dest_prefix}/share/panda3d/ReleaseNotes")
 
     for python_version in python_versions:
-        pth_file = python_version["purelib"] + "/panda3d.pth"
-        oscmd("echo '"+prefix+"/share/panda3d' > "+destdir+pth_file)
+        oscmd(f"echo '{prefix}/share/panda3d' > {destdir}{python_version['purelib']}/panda3d.pth")
 
-        if os.path.isdir(outputdir+"/panda3d.dist-info"):
-            oscmd("cp -R "+outputdir+"/panda3d.dist-info "+destdir+python_version["platlib"])
+        if os.path.isdir(outputdir + "/panda3d.dist-info"):
+            oscmd(f"cp -R {outputdir}/panda3d.dist-info {destdir}{python_version['platlib']}")
 
-    if (sys.platform.startswith("freebsd")):
-        oscmd("echo '"+libdir+"/panda3d'>    "+destdir+"/usr/local/libdata/ldconfig/panda3d")
+    if sys.platform.startswith("freebsd"):
+        oscmd(f"echo '{libdir}/panda3d' > {destdir}/usr/local/libdata/ldconfig/panda3d")
     else:
-        oscmd("echo '"+libdir+"/panda3d'>    "+destdir+"/etc/ld.so.conf.d/panda3d.conf")
+        oscmd(f"echo '{libdir}/panda3d' > {destdir}/etc/ld.so.conf.d/panda3d.conf")
 
-    for base in os.listdir(outputdir+"/lib"):
+    for base in os.listdir(outputdir + "/lib"):
         if not base.endswith(".a"):
             # We really need to specify -R in order not to follow symlinks on non-GNU
-            oscmd("cp -R -P "+outputdir+"/lib/"+base+" "+destdir+libdir+"/panda3d/"+base)
+            oscmd(f"cp -R -P {outputdir}/lib/{base} {dest_libdir}/panda3d/{base}")
 
-    for base in os.listdir(outputdir+"/bin"):
+    for base in os.listdir(outputdir + "/bin"):
         if not base.startswith("deploy-stub"):
-            oscmd("cp -R -P "+outputdir+"/bin/"+base+" "+destdir+prefix+"/bin/"+base)
+            oscmd(f"cp -R -P {outputdir}/bin/{base} {dest_prefix}/bin/{base}")
 
-    DeleteVCS(destdir+prefix+"/share/panda3d")
-    DeleteBuildFiles(destdir+prefix+"/share/panda3d")
-    DeleteEmptyDirs(destdir+prefix+"/share/panda3d")
-    DeleteVCS(destdir+prefix+"/include/panda3d")
-    DeleteBuildFiles(destdir+prefix+"/include/panda3d")
-    DeleteEmptyDirs(destdir+prefix+"/include/panda3d")
+    DeleteVCS(dest_prefix + "/share/panda3d")
+    DeleteBuildFiles(dest_prefix + "/share/panda3d")
+    DeleteEmptyDirs(dest_prefix + "/share/panda3d")
+    DeleteVCS(dest_prefix + "/include/panda3d")
+    DeleteBuildFiles(dest_prefix + "/include/panda3d")
+    DeleteEmptyDirs(dest_prefix + "/include/panda3d")
 
     # Change permissions on include directory.
-    os.chmod(destdir + prefix + "/include/panda3d", 0o755)
-    for root, dirs, files in os.walk(destdir + prefix + "/include/panda3d"):
+    os.chmod(dest_prefix + "/include/panda3d", 0o755)
+    for root, dirs, files in os.walk(dest_prefix + "/include/panda3d"):
         for basename in dirs:
             os.chmod(os.path.join(root, basename), 0o755)
         for basename in files:
             os.chmod(os.path.join(root, basename), 0o644)
 
     # rpmlint doesn't like this file, for some reason.
-    if (os.path.isfile(destdir+prefix+"/share/panda3d/direct/leveleditor/copyfiles.pl")):
-        os.remove(destdir+prefix+"/share/panda3d/direct/leveleditor/copyfiles.pl")
+    if os.path.isfile(dest_prefix + "/share/panda3d/direct/leveleditor/copyfiles.pl"):
+        os.remove(dest_prefix + "/share/panda3d/direct/leveleditor/copyfiles.pl")
+
 
-if (__name__ == "__main__"):
-    if (sys.platform.startswith("win") or sys.platform == "darwin"):
+if __name__ == "__main__":
+    if sys.platform.startswith("win") or sys.platform == "darwin":
         exit("This script is not supported on Windows or Mac OS X at the moment!")
 
     destdir = os.environ.get("DESTDIR", "/")
 
     parser = OptionParser()
-    parser.add_option('', '--outputdir', dest = 'outputdir', help = 'Makepanda\'s output directory (default: built)', default = 'built')
-    parser.add_option('', '--destdir', dest = 'destdir', help = 'Destination directory [default=%s]' % destdir, default = destdir)
-    parser.add_option('', '--prefix', dest = 'prefix', help = 'Prefix [default=/usr/local]', default = '/usr/local')
-    parser.add_option('', '--verbose', dest = 'verbose', help = 'Print commands that are executed [default=no]', action = 'store_true', default = False)
+    parser.add_option(
+        '',
+        '--outputdir',
+        dest='outputdir',
+        help='Makepanda\'s output directory (default: built)',
+        default='built',
+    )
+    parser.add_option(
+        '',
+        '--destdir',
+        dest='destdir',
+        help='Destination directory [default=%s]' % destdir,
+        default=destdir,
+    )
+    parser.add_option(
+        '',
+        '--prefix',
+        dest='prefix',
+        help='Prefix [default=/usr/local]',
+        default='/usr/local',
+    )
+    parser.add_option(
+        '',
+        '--verbose',
+        dest='verbose',
+        help='Print commands that are executed [default=no]',
+        action='store_true',
+        default=False,
+    )
     (options, args) = parser.parse_args()
 
     destdir = options.destdir
-    if (destdir.endswith("/")):
+    if destdir.endswith("/"):
         destdir = destdir[:-1]
-    if (destdir == "/"):
+    if destdir == "/":
         destdir = ""
-    if (destdir != "" and not os.path.isdir(destdir)):
+    if destdir != "" and not os.path.isdir(destdir):
         exit("Directory '%s' does not exist!" % destdir)
 
     SetOutputDir(options.outputdir)
@@ -272,10 +311,12 @@ if (__name__ == "__main__"):
         SetVerbose(True)
 
     print("Installing Panda3D SDK into " + destdir + options.prefix)
-    InstallPanda(destdir=destdir,
-                 prefix=options.prefix,
-                 outputdir=options.outputdir,
-                 python_versions=ReadPythonVersionInfoFile())
+    InstallPanda(
+        destdir=destdir,
+        prefix=options.prefix,
+        outputdir=options.outputdir,
+        python_versions=ReadPythonVersionInfoFile(),
+    )
     print("Installation finished!")
 
     if not destdir:

+ 147 - 68
makepanda/makepackage.py

@@ -1,13 +1,13 @@
 #!/usr/bin/env python
 
-from makepandacore import *
-from installpanda import *
 import sys
 import os
 import shutil
 import glob
 import re
 import subprocess
+from makepandacore import *
+from installpanda import *
 
 
 INSTALLER_DEB_FILE = """
@@ -61,8 +61,8 @@ This package contains the SDK for development with Panda3D.
 /usr/%_lib/panda3d
 /usr/include/panda3d
 """
-INSTALLER_SPEC_FILE_PVIEW = \
-"""/usr/share/applications/pview.desktop
+INSTALLER_SPEC_FILE_PVIEW = """\
+/usr/share/applications/pview.desktop
 /usr/share/mime-info/panda3d.mime
 /usr/share/mime-info/panda3d.keys
 /usr/share/mime/packages/panda3d.xml
@@ -70,7 +70,8 @@ INSTALLER_SPEC_FILE_PVIEW = \
 """
 
 # plist file for Mac OSX
-Info_plist = """<?xml version="1.0" encoding="UTF-8"?>
+Info_plist = """\
+<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
 <plist version="1.0">
 <dict>
@@ -114,17 +115,18 @@ deps: {DEPENDS}
 
 # Since we're adding a bunch of install scripts to the macOS intaller, we'll
 # put the platform-checking code in some variables to reduce repetition.
-MACOS_SCRIPT_PREFIX = \
-"""#!/bin/bash
+MACOS_SCRIPT_PREFIX = """\
+#!/bin/bash
 IFS=.
 read -a version_info <<< "`sw_vers -productVersion`"
 if (( ${version_info[0]} == 10 && ${version_info[1]} < 15 )); then
 """
 
-MACOS_SCRIPT_POSTFIX = \
-"""fi
+MACOS_SCRIPT_POSTFIX = """\
+fi
 """
 
+
 def MakeInstallerNSIS(version, file, title, installdir, compressor="lzma", **kwargs):
     outputdir = GetOutputDir()
 
@@ -138,30 +140,32 @@ def MakeInstallerNSIS(version, file, title, installdir, compressor="lzma", **kwa
     else:
         regview = '32'
 
-    print("Building "+title+" installer at %s" % (file))
+    print("Building " + title + " installer at %s" % (file))
     if compressor != "lzma":
         print("Note: you are using zlib, which is faster, but lzma gives better compression.")
     if os.path.exists("nsis-output.exe"):
         os.remove("nsis-output.exe")
-    WriteFile(outputdir+"/tmp/__init__.py", "")
+    WriteFile(outputdir + "/tmp/__init__.py", "")
 
     nsis_defs = {
         'COMPRESSOR': compressor,
-        'TITLE'     : title,
+        'TITLE': title,
         'INSTALLDIR': installdir,
-        'OUTFILE'   : '..\\' + file,
-        'BUILT'     : '..\\' + outputdir,
-        'SOURCE'    : '..',
-        'REGVIEW'   : regview,
-        'MAJOR_VER' : '.'.join(version.split('.')[:2]),
+        'OUTFILE': '..\\' + file,
+        'BUILT': '..\\' + outputdir,
+        'SOURCE': '..',
+        'REGVIEW': regview,
+        'MAJOR_VER': '.'.join(version.split('.')[:2]),
     }
 
     # Are we shipping a version of Python?
     if os.path.isfile(os.path.join(outputdir, "python", "python.exe")):
-        py_dlls = glob.glob(os.path.join(outputdir, "python", "python[0-9][0-9].dll")) \
-                + glob.glob(os.path.join(outputdir, "python", "python[0-9][0-9]_d.dll")) \
-                + glob.glob(os.path.join(outputdir, "python", "python[0-9][0-9][0-9].dll")) \
-                + glob.glob(os.path.join(outputdir, "python", "python[0-9][0-9][0-9]_d.dll"))
+        py_dlls = (
+            glob.glob(os.path.join(outputdir, "python", "python[0-9][0-9].dll"))
+            + glob.glob(os.path.join(outputdir, "python", "python[0-9][0-9]_d.dll"))
+            + glob.glob(os.path.join(outputdir, "python", "python[0-9][0-9][0-9].dll"))
+            + glob.glob(os.path.join(outputdir, "python", "python[0-9][0-9][0-9]_d.dll"))
+        )
         assert py_dlls
         py_dll = os.path.basename(py_dlls[0])
         py_dllver = py_dll.strip(".DHLNOPTY_dhlnopty")
@@ -189,6 +193,7 @@ def MakeDebugSymbolArchive(zipname, dirname):
     outputdir = GetOutputDir()
 
     import zipfile
+
     zip = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED)
 
     for fn in glob.glob(os.path.join(outputdir, 'bin', '*.pdb')):
@@ -248,24 +253,32 @@ def MakeInstallerLinux(version, debversion=None, rpmrelease=1,
     if dpkg_present:
         # Invoke installpanda.py to install it into a temporary dir
         lib_dir = GetDebLibDir()
-        InstallPanda(destdir="targetroot", prefix="/usr",
-                        outputdir=outputdir, libdir=lib_dir,
-                        python_versions=install_python_versions)
+        InstallPanda(
+            destdir="targetroot",
+            prefix="/usr",
+            outputdir=outputdir,
+            libdir=lib_dir,
+            python_versions=install_python_versions,
+        )
         oscmd("chmod -R 755 targetroot/usr/share/panda3d")
         oscmd("mkdir -m 0755 -p targetroot/usr/share/man/man1")
         oscmd("install -m 0644 doc/man/*.1 targetroot/usr/share/man/man1/")
 
-        oscmd("dpkg --print-architecture > "+outputdir+"/tmp/architecture.txt")
-        pkg_arch = ReadFile(outputdir+"/tmp/architecture.txt").strip()
+        oscmd("dpkg --print-architecture > " + outputdir + "/tmp/architecture.txt")
+        pkg_arch = ReadFile(outputdir + "/tmp/architecture.txt").strip()
         txt = INSTALLER_DEB_FILE[1:]
-        txt = txt.replace("VERSION", debversion).replace("ARCH", pkg_arch).replace("MAJOR", major_version)
+        txt = (
+            txt.replace("VERSION", debversion)
+            .replace("ARCH", pkg_arch)
+            .replace("MAJOR", major_version)
+        )
         txt = txt.replace("INSTSIZE", str(GetDirectorySize("targetroot") // 1024))
 
         oscmd("mkdir -m 0755 -p targetroot/DEBIAN")
         oscmd("cd targetroot && (find usr -type f -exec md5sum {} ;) > DEBIAN/md5sums")
         oscmd("cd targetroot && (find etc -type f -exec md5sum {} ;) >> DEBIAN/md5sums")
-        WriteFile("targetroot/DEBIAN/conffiles","/etc/Config.prc\n")
-        WriteFile("targetroot/DEBIAN/postinst","#!/bin/sh\necho running ldconfig\nldconfig\n")
+        WriteFile("targetroot/DEBIAN/conffiles", "/etc/Config.prc\n")
+        WriteFile("targetroot/DEBIAN/postinst", "#!/bin/sh\necho running ldconfig\nldconfig\n")
         oscmd("cp targetroot/DEBIAN/postinst targetroot/DEBIAN/postrm")
 
         # Determine the package name and the locations that
@@ -289,12 +302,12 @@ def MakeInstallerLinux(version, debversion=None, rpmrelease=1,
         pkg_dir = "debian/panda3d" + major_version
 
         # Generate a symbols file so that other packages can know which symbols we export.
-        oscmd("cd targetroot && dpkg-gensymbols -q -ODEBIAN/symbols -v%(pkg_version)s -p%(pkg_name)s -e%(lib_pattern)s" % locals())
+        oscmd(f"cd targetroot && dpkg-gensymbols -q -ODEBIAN/symbols -v{pkg_version} -p{pkg_name} -e{lib_pattern}")
 
         # Library dependencies are required, binary dependencies are recommended.
         # We explicitly exclude libphysx-extras since we don't want to depend on PhysX.
-        oscmd("cd targetroot && LD_LIBRARY_PATH=usr/%(lib_dir)s/panda3d %(dpkg_shlibdeps)s -Tdebian/substvars_dep --ignore-missing-info -x%(pkg_name)s -xlibphysx-extras %(lib_pattern)s" % locals())
-        oscmd("cd targetroot && LD_LIBRARY_PATH=usr/%(lib_dir)s/panda3d %(dpkg_shlibdeps)s -Tdebian/substvars_rec --ignore-missing-info -x%(pkg_name)s %(bin_pattern)s" % locals())
+        oscmd(f"cd targetroot && LD_LIBRARY_PATH=usr/{lib_dir}/panda3d {dpkg_shlibdeps} -Tdebian/substvars_dep --ignore-missing-info -x{pkg_name} -xlibphysx-extras {lib_pattern}")
+        oscmd(f"cd targetroot && LD_LIBRARY_PATH=usr/{lib_dir}/panda3d {dpkg_shlibdeps} -Tdebian/substvars_rec --ignore-missing-info -x{pkg_name} {bin_pattern}")
 
         # Parse the substvars files generated by dpkg-shlibdeps.
         depends = ReadFile("targetroot/debian/substvars_dep").replace("shlibs:Depends=", "").strip()
@@ -324,13 +337,17 @@ def MakeInstallerLinux(version, debversion=None, rpmrelease=1,
 
     elif rpmbuild_present:
         # Invoke installpanda.py to install it into a temporary dir
-        InstallPanda(destdir="targetroot", prefix="/usr",
-                        outputdir=outputdir, libdir=GetRPMLibDir(),
-                        python_versions=install_python_versions)
+        InstallPanda(
+            destdir="targetroot",
+            prefix="/usr",
+            outputdir=outputdir,
+            libdir=GetRPMLibDir(),
+            python_versions=install_python_versions,
+        )
         oscmd("chmod -R 755 targetroot/usr/share/panda3d")
 
-        oscmd("rpm -E '%_target_cpu' > "+outputdir+"/tmp/architecture.txt")
-        arch = ReadFile(outputdir+"/tmp/architecture.txt").strip()
+        oscmd("rpm -E '%_target_cpu' > " + outputdir + "/tmp/architecture.txt")
+        arch = ReadFile(outputdir + "/tmp/architecture.txt").strip()
         pandasource = os.path.abspath(os.getcwd())
 
         txt = INSTALLER_SPEC_FILE[1:]
@@ -378,9 +395,12 @@ def MakeInstallerOSX(version, python_versions=[], installdir=None, **kwargs):
         dmg_name += "-py" + python_versions[0]["version"]
     dmg_name += ".dmg"
 
-    if (os.path.isfile(dmg_name)): oscmd("rm -f %s" % dmg_name)
-    if (os.path.exists("dstroot")): oscmd("rm -rf dstroot")
-    if (os.path.exists("Panda3D-rw.dmg")): oscmd('rm -f Panda3D-rw.dmg')
+    if os.path.isfile(dmg_name):
+        oscmd("rm -f %s" % dmg_name)
+    if os.path.exists("dstroot"):
+        oscmd("rm -rf dstroot")
+    if os.path.exists("Panda3D-rw.dmg"):
+        oscmd('rm -f Panda3D-rw.dmg')
 
     oscmd("mkdir -p                       dstroot/base/%s/lib" % installdir)
     oscmd("mkdir -p                       dstroot/base/%s/etc" % installdir)
@@ -389,15 +409,15 @@ def MakeInstallerOSX(version, python_versions=[], installdir=None, **kwargs):
     oscmd("cp -R %s/models                dstroot/base/%s/models" % (outputdir, installdir))
     oscmd("cp -R doc/LICENSE              dstroot/base/%s/LICENSE" % installdir)
     oscmd("cp -R doc/ReleaseNotes         dstroot/base/%s/ReleaseNotes" % installdir)
-    if os.path.isdir(outputdir+"/Frameworks") and os.listdir(outputdir+"/Frameworks"):
+    if os.path.isdir(outputdir + "/Frameworks") and os.listdir(outputdir + "/Frameworks"):
         oscmd("cp -R %s/Frameworks            dstroot/base/%s/Frameworks" % (outputdir, installdir))
-    if os.path.isdir(outputdir+"/plugins"):
+    if os.path.isdir(outputdir + "/plugins"):
         oscmd("cp -R %s/plugins           dstroot/base/%s/plugins" % (outputdir, installdir))
 
     # Libraries that shouldn't be in base, but are instead in other modules.
     no_base_libs = ['libp3ffmpeg', 'libp3fmod_audio', 'libfmodex', 'libfmodexL']
 
-    for base in os.listdir(outputdir+"/lib"):
+    for base in os.listdir(outputdir + "/lib"):
         if not base.endswith(".a") and base.split('.')[0] not in no_base_libs:
             libname = ("dstroot/base/%s/lib/" % installdir) + base
             # We really need to specify -R in order not to follow symlinks
@@ -412,7 +432,7 @@ def MakeInstallerOSX(version, python_versions=[], installdir=None, **kwargs):
     oscmd("mkdir -m 0755 -p dstroot/tools/usr/local/share/man/man1")
     oscmd("install -m 0644 doc/man/*.1 dstroot/tools/usr/local/share/man/man1/")
 
-    for base in os.listdir(outputdir+"/bin"):
+    for base in os.listdir(outputdir + "/bin"):
         if not base.startswith("deploy-stub"):
             binname = ("dstroot/tools/%s/bin/" % installdir) + base
             # OSX needs the -R argument to copy symbolic links correctly, it doesn't have -d. How weird.
@@ -436,7 +456,7 @@ def MakeInstallerOSX(version, python_versions=[], installdir=None, **kwargs):
         if os.path.isdir(outputdir + "/panda3d.dist-info"):
             oscmd("cp -R %s/panda3d.dist-info dstroot/pythoncode/%s/panda3d.dist-info" % (outputdir, installdir))
 
-        for base in os.listdir(outputdir+"/panda3d"):
+        for base in os.listdir(outputdir + "/panda3d"):
             if base.endswith('.py'):
                 libname = ("dstroot/pythoncode/%s/panda3d/" % installdir) + base
                 oscmd("cp -R " + outputdir + "/panda3d/" + base + " " + libname)
@@ -519,8 +539,10 @@ def MakeInstallerOSX(version, python_versions=[], installdir=None, **kwargs):
     # if they're running macOS 10.14 or less. We also remove the old
     # installation.
     script_components = set()
+
     def write_script(component, phase, contents):
-        if installdir == "/Developer/Panda3D": return
+        if installdir == "/Developer/Panda3D":
+            return
 
         script_components.add(component)
         oscmd("mkdir -p dstroot/scripts/%s" % component)
@@ -565,9 +587,12 @@ def MakeInstallerOSX(version, python_versions=[], installdir=None, **kwargs):
         pkgs.append("pythoncode")
     for version_info in python_versions:
         pkgs.append("pybindings" + version_info["version"])
-    if not PkgSkip("FFMPEG"):    pkgs.append("ffmpeg")
-    #if not PkgSkip("OPENAL"):    pkgs.append("openal")
-    if not PkgSkip("FMODEX"):    pkgs.append("fmodex")
+    if not PkgSkip("FFMPEG"):
+        pkgs.append("ffmpeg")
+    #if not PkgSkip("OPENAL"):
+    #    pkgs.append("openal")
+    if not PkgSkip("FMODEX"):
+        pkgs.append("fmodex")
 
     for pkg in pkgs:
         identifier = "org.panda3d.panda3d.%s.pkg" % pkg
@@ -584,7 +609,7 @@ def MakeInstallerOSX(version, python_versions=[], installdir=None, **kwargs):
             pkg_scripts = ''
 
         if os.path.exists("/usr/bin/pkgbuild"):
-            cmd = '/usr/bin/pkgbuild --identifier ' + identifier + ' --version ' + version + ' --root dstroot/' + pkg + '/ dstroot/Panda3D/Panda3D.mpkg/Contents/Packages/' + pkg + '.pkg' + pkg_scripts
+            cmd = f'/usr/bin/pkgbuild --identifier {identifier} --version {version} --root dstroot/{pkg}/ dstroot/Panda3D/Panda3D.mpkg/Contents/Packages/{pkg}.pkg {pkg_scripts}'
         else:
             exit("pkgbuild could not be found!")
         oscmd(cmd)
@@ -620,7 +645,7 @@ def MakeInstallerOSX(version, python_versions=[], installdir=None, **kwargs):
     dist.write('        <line choice="base"/>\n')
     if python_versions:
         dist.write('        <line choice="pythoncode">\n')
-        for version_info in sorted(python_versions, key=lambda info:info["version"], reverse=True):
+        for version_info in sorted(python_versions, key=lambda info: info["version"], reverse=True):
             dist.write('            <line choice="pybindings%s"/>\n' % (version_info["version"]))
         dist.write('        </line>\n')
     dist.write('        <line choice="tools"/>\n')
@@ -700,7 +725,12 @@ def MakeInstallerFreeBSD(version, python_versions=[], **kwargs):
     oscmd("mkdir targetroot")
 
     # Invoke installpanda.py to install it into a temporary dir
-    InstallPanda(destdir="targetroot", prefix="/usr/local", outputdir=outputdir, python_versions=python_versions)
+    InstallPanda(
+        destdir="targetroot",
+        prefix="/usr/local",
+        outputdir=outputdir,
+        python_versions=python_versions,
+    )
 
     if not os.path.exists("/usr/sbin/pkg"):
         exit("Cannot create an installer without pkg")
@@ -894,7 +924,10 @@ def MakeInstallerAndroid(version, **kwargs):
 
     # And now make a site-packages directory containing our direct/panda3d/pandac modules.
     for tree in "panda3d", "direct", "pandac":
-        copy_python_tree(os.path.join(outputdir, tree), os.path.join(stdlib_target, "site-packages", tree))
+        copy_python_tree(
+            os.path.join(outputdir, tree),
+            os.path.join(stdlib_target, "site-packages", tree),
+        )
 
     # Copy the models and config files to the virtual assets filesystem.
     oscmd("mkdir apkroot/assets")
@@ -981,13 +1014,57 @@ if __name__ == "__main__":
     version = GetMetadataValue('version')
 
     parser = OptionParser()
-    parser.add_option('', '--version', dest='version', help='Panda3D version number (default: %s)' % (version), default=version)
-    parser.add_option('', '--debversion', dest='debversion', help='Version number for .deb file', default=None)
-    parser.add_option('', '--rpmrelease', dest='rpmrelease', help='Release number for .rpm file', default='1')
-    parser.add_option('', '--outputdir', dest='outputdir', help='Makepanda\'s output directory (default: built)', default='built')
-    parser.add_option('', '--verbose', dest='verbose', help='Enable verbose output', action='store_true', default=False)
-    parser.add_option('', '--lzma', dest='compressor', help='Use LZMA compression', action='store_const', const='lzma', default='zlib')
-    parser.add_option('', '--installdir', dest='installdir', help='Where on the system the installer should put the SDK (Windows, macOS)')
+    parser.add_option(
+        '',
+        '--version',
+        dest='version',
+        help='Panda3D version number (default: %s)' % (version),
+        default=version,
+    )
+    parser.add_option(
+        '',
+        '--debversion',
+        dest='debversion',
+        help='Version number for .deb file',
+        default=None,
+    )
+    parser.add_option(
+        '',
+        '--rpmrelease',
+        dest='rpmrelease',
+        help='Release number for .rpm file',
+        default='1',
+    )
+    parser.add_option(
+        '',
+        '--outputdir',
+        dest='outputdir',
+        help='Makepanda\'s output directory (default: built)',
+        default='built',
+    )
+    parser.add_option(
+        '',
+        '--verbose',
+        dest='verbose',
+        help='Enable verbose output',
+        action='store_true',
+        default=False,
+    )
+    parser.add_option(
+        '',
+        '--lzma',
+        dest='compressor',
+        help='Use LZMA compression',
+        action='store_const',
+        const='lzma',
+        default='zlib',
+    )
+    parser.add_option(
+        '',
+        '--installdir',
+        dest='installdir',
+        help='Where on the system the installer should put the SDK (Windows, macOS)',
+    )
     (options, args) = parser.parse_args()
 
     SetVerbose(options.verbose)
@@ -1014,11 +1091,13 @@ if __name__ == "__main__":
     if not match:
         exit("version requires three digits")
 
-    MakeInstaller(version=match.group(),
-                  outputdir=options.outputdir,
-                  optimize=GetOptimize(),
-                  compressor=options.compressor,
-                  debversion=options.debversion,
-                  rpmrelease=options.rpmrelease,
-                  python_versions=ReadPythonVersionInfoFile(),
-                  installdir=options.installdir)
+    MakeInstaller(
+        version=match.group(),
+        outputdir=options.outputdir,
+        optimize=GetOptimize(),
+        compressor=options.compressor,
+        debversion=options.debversion,
+        rpmrelease=options.rpmrelease,
+        python_versions=ReadPythonVersionInfoFile(),
+        installdir=options.installdir,
+    )

File diff suppressed because it is too large
+ 282 - 281
makepanda/makepanda.py


+ 96 - 70
makepanda/makepandacore.py

@@ -5,12 +5,22 @@
 ##
 ########################################################################
 
-import sys,os,time,stat,string,re,getopt,fnmatch,threading,signal,shutil,platform,glob,getpass,signal
-import subprocess
+import configparser
 from distutils import sysconfig
+import fnmatch
+import getpass
+import glob
+import os
 import pickle
+import platform
+import re
+import shutil
+import signal
+import subprocess
+import sys
+import threading
 import _thread as thread
-import configparser
+import time
 
 SUFFIX_INC = [".cxx",".cpp",".c",".h",".I",".yxx",".lxx",".mm",".rc",".r"]
 SUFFIX_DLL = [".dll",".dlo",".dle",".dli",".dlm",".mll",".exe",".pyd",".ocx"]
@@ -172,14 +182,15 @@ THREADS = {}
 HAVE_COLORS = False
 SETF = ""
 try:
-  import curses
-  curses.setupterm()
-  SETF = curses.tigetstr("setf")
-  if (SETF == None):
-    SETF = curses.tigetstr("setaf")
-  assert SETF != None
-  HAVE_COLORS = sys.stdout.isatty()
-except: pass
+    import curses
+    curses.setupterm()
+    SETF = curses.tigetstr("setf")
+    if SETF is None:
+        SETF = curses.tigetstr("setaf")
+    assert SETF is not None
+    HAVE_COLORS = sys.stdout.isatty()
+except:
+    pass
 
 def DisableColors():
     global HAVE_COLORS
@@ -188,20 +199,20 @@ def DisableColors():
 def GetColor(color = None):
     if not HAVE_COLORS:
         return ""
-    if color != None:
+    if color is not None:
         color = color.lower()
 
-    if (color == "blue"):
+    if color == "blue":
         token = curses.tparm(SETF, 1)
-    elif (color == "green"):
+    elif color == "green":
         token = curses.tparm(SETF, 2)
-    elif (color == "cyan"):
+    elif color == "cyan":
         token = curses.tparm(SETF, 3)
-    elif (color == "red"):
+    elif color == "red":
         token = curses.tparm(SETF, 4)
-    elif (color == "magenta"):
+    elif color == "magenta":
         token = curses.tparm(SETF, 5)
-    elif (color == "yellow"):
+    elif color == "yellow":
         token = curses.tparm(SETF, 6)
     else:
         token = curses.tparm(curses.tigetstr("sgr0"))
@@ -235,9 +246,9 @@ def ProgressOutput(progress, msg, target = None):
     if thisthread is MAINTHREAD:
         if progress is None:
             prefix = ""
-        elif (progress >= 100.0):
+        elif progress >= 100.0:
             prefix = "%s[%s%d%%%s] " % (GetColor("yellow"), GetColor("cyan"), progress, GetColor("yellow"))
-        elif (progress < 10.0):
+        elif progress < 10.0:
             prefix = "%s[%s  %d%%%s] " % (GetColor("yellow"), GetColor("cyan"), progress, GetColor("yellow"))
         else:
             prefix = "%s[%s %d%%%s] " % (GetColor("yellow"), GetColor("cyan"), progress, GetColor("yellow"))
@@ -245,7 +256,7 @@ def ProgressOutput(progress, msg, target = None):
         global THREADS
 
         ident = thread.get_ident()
-        if (ident not in THREADS):
+        if ident not in THREADS:
             THREADS[ident] = len(THREADS) + 1
         prefix = "%s[%sT%d%s] " % (GetColor("yellow"), GetColor("cyan"), THREADS[ident], GetColor("yellow"))
 
@@ -261,7 +272,7 @@ def ProgressOutput(progress, msg, target = None):
 def exit(msg = ""):
     sys.stdout.flush()
     sys.stderr.flush()
-    if (threading.currentThread() == MAINTHREAD):
+    if threading.currentThread() == MAINTHREAD:
         SaveDependencyCache()
         print("Elapsed Time: " + PrettyTime(time.time() - STARTTIME))
         print(msg)
@@ -355,7 +366,7 @@ def SetTarget(target, arch=None):
 
     if target == 'windows':
         if arch == 'i386':
-             arch = 'x86'
+            arch = 'x86'
         elif arch == 'amd64':
             arch = 'x64'
 
@@ -644,7 +655,7 @@ def oscmd(cmd, ignoreError = False, cwd=None):
 ########################################################################
 
 def GetDirectoryContents(dir, filters="*", skip=[]):
-    if (type(filters)==str):
+    if isinstance(filters, str):
         filters = [filters]
     actual = {}
     files = os.listdir(dir)
@@ -665,7 +676,8 @@ def GetDirectorySize(dir):
         for file in files:
             try:
                 size += os.path.getsize(os.path.join(path, file))
-            except: pass
+            except:
+                pass
     return size
 
 ########################################################################
@@ -683,8 +695,10 @@ TIMESTAMPCACHE = {}
 def GetTimestamp(path):
     if path in TIMESTAMPCACHE:
         return TIMESTAMPCACHE[path]
-    try: date = os.path.getmtime(path)
-    except: date = 0
+    try:
+        date = os.path.getmtime(path)
+    except:
+        date = 0
     TIMESTAMPCACHE[path] = date
     return date
 
@@ -773,22 +787,24 @@ def NeedsBuild(files, others):
 
 CXXINCLUDECACHE = {}
 
-global CxxIncludeRegex
 CxxIncludeRegex = re.compile('^[ \t]*[#][ \t]*include[ \t]+"([^"]+)"[ \t\r\n]*$')
 
 def CxxGetIncludes(path):
     date = GetTimestamp(path)
-    if (path in CXXINCLUDECACHE):
+    if path in CXXINCLUDECACHE:
         cached = CXXINCLUDECACHE[path]
-        if (cached[0]==date): return cached[1]
-    try: sfile = open(path, 'r')
+        if cached[0] == date:
+            return cached[1]
+    try:
+        sfile = open(path, 'r')
     except:
         exit("Cannot open source file \""+path+"\" for reading.")
+
     include = []
     try:
         for line in sfile:
             match = CxxIncludeRegex.match(line,0)
-            if (match):
+            if match:
                 incname = match.group(1)
                 include.append(incname)
     except:
@@ -801,7 +817,6 @@ def CxxGetIncludes(path):
 
 JAVAIMPORTCACHE = {}
 
-global JavaImportRegex
 JavaImportRegex = re.compile('[ \t\r\n;]import[ \t]+([a-zA-Z][^;]+)[ \t\r\n]*;')
 
 def JavaGetImports(path):
@@ -842,10 +857,11 @@ def SaveDependencyCache():
     global DCACHE_BACKED_UP
     if not DCACHE_BACKED_UP:
         try:
-            if (os.path.exists(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"))):
+            if os.path.exists(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache")):
                 os.rename(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"),
                           os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache-backup"))
-        except: pass
+        except:
+            pass
         DCACHE_BACKED_UP = True
 
     try:
@@ -942,24 +958,24 @@ def JavaFindClasses(impspec, clspath):
 ##
 ########################################################################
 
-global CxxIgnoreHeader
-global CxxDependencyCache
 CxxIgnoreHeader = {}
 CxxDependencyCache = {}
 
 def CxxCalcDependencies(srcfile, ipath, ignore):
-    if (srcfile in CxxDependencyCache):
+    if srcfile in CxxDependencyCache:
         return CxxDependencyCache[srcfile]
-    if (ignore.count(srcfile)): return []
+    if ignore.count(srcfile):
+        return []
     dep = {}
     dep[srcfile] = 1
     includes = CxxGetIncludes(srcfile)
     for include in includes:
         header = CxxFindHeader(srcfile, include, ipath)
-        if (header!=0):
-            if (ignore.count(header)==0):
+        if header != 0:
+            if ignore.count(header) == 0:
                 hdeps = CxxCalcDependencies(header, ipath, [srcfile]+ignore)
-                for x in hdeps: dep[x] = 1
+                for x in hdeps:
+                    dep[x] = 1
     result = list(dep.keys())
     CxxDependencyCache[srcfile] = result
     return result
@@ -999,11 +1015,13 @@ def TryRegistryKey(path):
     try:
         key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path, 0, winreg.KEY_READ)
         return key
-    except: pass
+    except:
+        pass
     try:
         key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path, 0, winreg.KEY_READ | 256)
         return key
-    except: pass
+    except:
+        pass
     return 0
 
 def ListRegistryKeys(path):
@@ -1015,7 +1033,8 @@ def ListRegistryKeys(path):
             while (1):
                 result.append(winreg.EnumKey(key, index))
                 index = index + 1
-        except: pass
+        except:
+            pass
         winreg.CloseKey(key)
     return result
 
@@ -1028,7 +1047,8 @@ def ListRegistryValues(path):
             while (1):
                 result.append(winreg.EnumValue(key, index)[0])
                 index = index + 1
-        except: pass
+        except:
+            pass
         winreg.CloseKey(key)
     return result
 
@@ -1040,7 +1060,8 @@ def GetRegistryKey(path, subkey, override64=True):
     if (key != 0):
         try:
             k1, k2 = winreg.QueryValueEx(key, subkey)
-        except: pass
+        except:
+            pass
         winreg.CloseKey(key)
     return k1
 
@@ -1270,7 +1291,7 @@ def GetThirdpartyBase():
     thirdparty directory.  This is useful when wanting to use a single
     system-wide thirdparty directory, for instance on a build machine."""
     global THIRDPARTYBASE
-    if (THIRDPARTYBASE != None):
+    if (THIRDPARTYBASE is not None):
         return THIRDPARTYBASE
 
     THIRDPARTYBASE = "thirdparty"
@@ -1283,7 +1304,7 @@ def GetThirdpartyDir():
     """Returns the thirdparty directory for the target platform,
     ie. thirdparty/win-libs-vc10/.  May return None in the future."""
     global THIRDPARTYDIR
-    if THIRDPARTYDIR != None:
+    if THIRDPARTYDIR is not None:
         return THIRDPARTYDIR
 
     base = GetThirdpartyBase()
@@ -1466,10 +1487,10 @@ def PkgConfigHavePkg(pkgname, tool = "pkg-config"):
     if (tool == "pkg-config"):
         handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --modversion " + pkgname)
     else:
-        return bool(LocateBinary(tool) != None)
+        return bool(LocateBinary(tool) is not None)
     result = handle.read().strip()
     returnval = handle.close()
-    if returnval != None and returnval != 0:
+    if returnval is not None and returnval != 0:
         return False
     return bool(len(result) > 0)
 
@@ -1637,21 +1658,21 @@ def SmartPkgEnable(pkg, pkgconfig = None, libs = None, incs = None, defs = None,
     global PKG_LIST_ALL
     if (pkg in PkgListGet() and PkgSkip(pkg)):
         return
-    if (target_pkg == "" or target_pkg == None):
+    if (target_pkg == "" or target_pkg is None):
         target_pkg = pkg
     if (pkgconfig == ""):
         pkgconfig = None
     if (framework == ""):
         framework = None
-    if (libs == None or libs == ""):
+    if (libs is None or libs == ""):
         libs = ()
     elif (isinstance(libs, str)):
         libs = (libs, )
-    if (incs == None or incs == ""):
+    if (incs is None or incs == ""):
         incs = ()
     elif (isinstance(incs, str)):
         incs = (incs, )
-    if (defs == None or defs == "" or len(defs) == 0):
+    if (defs is None or defs == "" or len(defs) == 0):
         defs = {}
     elif (isinstance(incs, str)):
         defs = {defs : ""}
@@ -1693,7 +1714,7 @@ def SmartPkgEnable(pkg, pkgconfig = None, libs = None, incs = None, defs = None,
                 lpath.append(py_lib_dir)
 
         # TODO: check for a .pc file in the lib/pkgconfig/ dir
-        if (tool != None and os.path.isfile(os.path.join(pkg_dir, "bin", tool))):
+        if (tool is not None and os.path.isfile(os.path.join(pkg_dir, "bin", tool))):
             tool = os.path.join(pkg_dir, "bin", tool)
             for i in PkgConfigGetLibs(None, tool):
                 if i.startswith('-l'):
@@ -1739,7 +1760,7 @@ def SmartPkgEnable(pkg, pkgconfig = None, libs = None, incs = None, defs = None,
             DefSymbol(target_pkg, d, v)
         return
 
-    elif not custom_loc and GetHost() == "darwin" and framework != None:
+    elif not custom_loc and GetHost() == "darwin" and framework is not None:
         prefix = SDK["MACOSX"]
         if (os.path.isdir(prefix + "/Library/Frameworks/%s.framework" % framework) or
             os.path.isdir(prefix + "/System/Library/Frameworks/%s.framework" % framework) or
@@ -1753,7 +1774,7 @@ def SmartPkgEnable(pkg, pkgconfig = None, libs = None, incs = None, defs = None,
         elif VERBOSE:
             print(ColorText("cyan", "Couldn't find the framework %s" % (framework)))
 
-    elif not custom_loc and LocateBinary(tool) != None and (tool != "pkg-config" or pkgconfig != None):
+    elif not custom_loc and LocateBinary(tool) is not None and (tool != "pkg-config" or pkgconfig is not None):
         if (isinstance(pkgconfig, str) or tool != "pkg-config"):
             if (PkgConfigHavePkg(pkgconfig, tool)):
                 return PkgConfigEnable(target_pkg, pkgconfig, tool)
@@ -2902,7 +2923,7 @@ def SetupBuildEnvironment(compiler):
                     print("Ignoring non-existent library directory %s" % (libdir))
 
         returnval = handle.close()
-        if returnval != None and returnval != 0:
+        if returnval is not None and returnval != 0:
             Warn("%s failed" % (cmd))
             SYS_LIB_DIRS += [SDK.get("SYSROOT", "") + "/usr/lib"]
 
@@ -3149,7 +3170,8 @@ def ParsePandaVersion(fn):
                 f.close()
                 return match.group(1) + "." + match.group(2) + "." + match.group(3)
         f.close()
-    except: pass
+    except:
+        pass
     return "0.0.0"
 
 ##########################################################################################
@@ -3203,7 +3225,7 @@ def GenerateResourceFile(**kwargs):
         kwargs["commaversion"] = kwargs["dotversion"].replace(".", ",")
 
     rcdata = ""
-    if not "noinclude" in kwargs:
+    if "noinclude" not in kwargs:
         rcdata += "#define APSTUDIO_READONLY_SYMBOLS\n"
         rcdata += "#include \"winresrc.h\"\n"
         rcdata += "#undef APSTUDIO_READONLY_SYMBOLS\n"
@@ -3530,19 +3552,23 @@ TARGET_LIST = []
 TARGET_TABLE = {}
 
 def TargetAdd(target, dummy=0, opts=[], input=[], dep=[], ipath=None, winrc=None, pyabi=None):
-    if (dummy != 0):
-        exit("Syntax error in TargetAdd "+target)
-    if ipath is None: ipath = opts
-    if not ipath: ipath = []
-    if (type(input) == str): input = [input]
-    if (type(dep) == str): dep = [dep]
+    if dummy != 0:
+        exit("Syntax error in TargetAdd " + target)
+    if ipath is None:
+        ipath = opts
+    if not ipath:
+        ipath = []
+    if isinstance(input, str):
+        input = [input]
+    if isinstance(dep, str):
+        dep = [dep]
 
     if target.endswith(".pyd") and not pyabi:
         raise RuntimeError("Use PyTargetAdd to build .pyd targets")
 
     full = FindLocation(target, [OUTPUTDIR + "/include"], pyabi=pyabi)
 
-    if (full not in TARGET_TABLE):
+    if full not in TARGET_TABLE:
         t = Target()
         t.name = full
         t.inputs = []
@@ -3563,10 +3589,10 @@ def TargetAdd(target, dummy=0, opts=[], input=[], dep=[], ipath=None, winrc=None
         t.inputs.append(fullinput)
         # Don't re-link a library or binary if just its dependency dlls have been altered.
         # This should work out fine in most cases, and often reduces recompilation time.
-        if (os.path.splitext(x)[-1] not in SUFFIX_DLL):
+        if os.path.splitext(x)[-1] not in SUFFIX_DLL:
             t.deps[fullinput] = 1
             (base,suffix) = os.path.splitext(x)
-            if (SUFFIX_INC.count(suffix)):
+            if SUFFIX_INC.count(suffix):
                 for d in CxxCalcDependencies(fullinput, ipath, []):
                     t.deps[d] = 1
             elif suffix == '.java':

+ 2 - 5
makepanda/makewheel.py

@@ -1,22 +1,19 @@
 """
 Generates a wheel (.whl) file from the output of makepanda.
 """
-from __future__ import print_function, unicode_literals
-from distutils.util import get_platform
 import json
-
 import sys
 import os
 from os.path import join
-import shutil
 import zipfile
 import hashlib
 import tempfile
 import subprocess
+from distutils.util import get_platform
 from distutils.sysconfig import get_config_var
 from optparse import OptionParser
-from makepandacore import ColorText, LocateBinary, GetExtensionSuffix, SetVerbose, GetVerbose, GetMetadataValue
 from base64 import urlsafe_b64encode
+from makepandacore import LocateBinary, GetExtensionSuffix, SetVerbose, GetVerbose, GetMetadataValue
 
 
 def get_abi_tag():

Some files were not shown because too many files changed in this diff