1203 lines · 52.7 KB · Python
RawDownload
# Python MSI Generator# (C) 2003 Martin v. Loewis# See "FOO" in comments refers to MSDN sections with the title FOO.import msilib, schema, sequence, os, glob, time, refrom msilib import Feature, CAB, Directory, Dialog, Binary, add_dataimport uisamplefrom win32com.client import constantsfrom distutils.spawn import find_executablefrom uuids import product_codes # Settings can be overridden in config.py below# 0 for official python.org releases# 1 for intermediate releases by anybody, with# a new product code for every package.snapshot = 1# 1 means that file extension is px, not py,# and binaries start with xtestpackage = 0# Location of build treesrcdir = os.path.abspath("../..")# Text to be displayed as the version in dialogs etc.# goes into file name and ProductCode. Defaults to# current_version.day for Snapshot, current_version otherwisefull_current_version = None# Is Tcl available at all?have_tcl = True# Where is sqlite3.dll located, relative to srcdir?sqlite_dir = "../sqlite-source-3.3.4" try:    from config import *except ImportError:    pass # Extract current version from Include/patchlevel.hlines = open(srcdir + "/Include/patchlevel.h").readlines()major = minor = micro = level = serial = Nonelevels = {    'PY_RELEASE_LEVEL_ALPHA':0xA,    'PY_RELEASE_LEVEL_BETA': 0xB,    'PY_RELEASE_LEVEL_GAMMA':0xC,    'PY_RELEASE_LEVEL_FINAL':0xF    }for l in lines:    if not l.startswith("#define"):        continue    l = l.split()    if len(l) != 3:        continue    _, name, value = l    if name == 'PY_MAJOR_VERSION': major = value    if name == 'PY_MINOR_VERSION': minor = value    if name == 'PY_MICRO_VERSION': micro = value    if name == 'PY_RELEASE_LEVEL': level = levels[value]    if name == 'PY_RELEASE_SERIAL': serial = value short_version = major+"."+minor# See PC/make_versioninfo.cFIELD3 = 1000*int(micro) + 10*level + int(serial)current_version = "%s.%d" % (short_version, FIELD3) # This should never change. The UpgradeCode of this package can be# used in the Upgrade table of future packages to make the future# package replace this one. See "UpgradeCode Property".upgrade_code_snapshot='{92A24481-3ECB-40FC-8836-04B7966EC0D5}'upgrade_code='{65E6DE48-A358-434D-AA4F-4AF72DB4718F}' if snapshot:    current_version = "%s.%s.%s" % (major, minor, int(time.time()/3600/24))    product_code = msilib.gen_uuid()else:    product_code = product_codes[current_version] if full_current_version is None:    full_current_version = current_version extensions = [    'bz2.pyd',    'pyexpat.pyd',    'select.pyd',    'unicodedata.pyd',    'winsound.pyd',    '_elementtree.pyd',    '_bsddb.pyd',    '_socket.pyd',    '_ssl.pyd',    '_testcapi.pyd',    '_tkinter.pyd',    '_msi.pyd',    '_ctypes.pyd',    '_ctypes_test.pyd',    '_sqlite3.pyd',    '_hashlib.pyd'] # Well-known component UUIDs# These are needed for SharedDLLs reference counter; if# a different UUID was used for each incarnation of, say,# python24.dll, an upgrade would set the reference counter# from 1 to 2 (due to what I consider a bug in MSI)# Using the same UUID is fine since these files are versioned,# so Installer will always keep the newest version.msvcr71_uuid = "{8666C8DD-D0B4-4B42-928E-A69E32FA5D4D}"pythondll_uuid = {    "24":"{9B81E618-2301-4035-AC77-75D9ABEB7301}",    "25":"{2e41b118-38bd-4c1b-a840-6977efd1b911}"    } [major+minor] # Build the mingw import library, libpythonXY.a# This requires 'nm' and 'dlltool' executables on your PATHdef build_mingw_lib(lib_file, def_file, dll_file, mingw_lib):    warning = "WARNING: %s - libpythonXX.a not built"    nm = find_executable('nm')    dlltool = find_executable('dlltool')     if not nm or not dlltool:        print warning % "nm and/or dlltool were not found"        return False     nm_command = '%s -Cs %s' % (nm, lib_file)    dlltool_command = "%s --dllname %s --def %s --output-lib %s" % \        (dlltool, dll_file, def_file, mingw_lib)    export_match = re.compile(r"^_imp__(.*) in python\d+\.dll").match     f = open(def_file,'w')    print >>f, "LIBRARY %s" % dll_file    print >>f, "EXPORTS"     nm_pipe = os.popen(nm_command)    for line in nm_pipe.readlines():        m = export_match(line)        if m:            print >>f, m.group(1)    f.close()    exit = nm_pipe.close()     if exit:        print warning % "nm did not run successfully"        return False     if os.system(dlltool_command) != 0:        print warning % "dlltool did not run successfully"        return False     return True # Target files (.def and .a) go in PCBuild directorylib_file = os.path.join(srcdir, "PCBuild", "python%s%s.lib" % (major, minor))def_file = os.path.join(srcdir, "PCBuild", "python%s%s.def" % (major, minor))dll_file = "python%s%s.dll" % (major, minor)mingw_lib = os.path.join(srcdir, "PCBuild", "libpython%s%s.a" % (major, minor)) have_mingw = build_mingw_lib(lib_file, def_file, dll_file, mingw_lib) # Determine the target architechturedll_path = os.path.join(srcdir, "PCBuild", dll_file)msilib.set_arch_from_file(dll_path)if msilib.pe_type(dll_path) != msilib.pe_type("msisupport.dll"):    raise SystemError, "msisupport.dll for incorrect architecture" if testpackage:    ext = 'px'    testprefix = 'x'else:    ext = 'py'    testprefix = '' if msilib.Win64:    SystemFolderName = "[SystemFolder64]"else:    SystemFolderName = "[SystemFolder]" msilib.reset() # condition in which to install pythonxy.dll in system32:# a) it is Windows 9x or# b) it is NT, the user is privileged, and has chosen per-machine installationsys32cond = "(Windows9x or (Privileged and ALLUSERS))" def build_database():    """Generate an empty database, with just the schema and the    Summary information stream."""    if snapshot:        uc = upgrade_code_snapshot    else:        uc = upgrade_code    # schema represents the installer 2.0 database schema.    # sequence is the set of standard sequences    # (ui/execute, admin/advt/install)    db = msilib.init_database("python-%s%s.msi" % (full_current_version, msilib.arch_ext),                  schema, ProductName="Python "+full_current_version,                  ProductCode=product_code,                  ProductVersion=current_version,                  Manufacturer=u"Martin v. L\xf6wis")    # The default sequencing of the RemoveExistingProducts action causes    # removal of files that got just installed. Place it after    # InstallInitialize, so we first uninstall everything, but still roll    # back in case the installation is interrupted    msilib.change_sequence(sequence.InstallExecuteSequence,                           "RemoveExistingProducts", 1510)    msilib.add_tables(db, sequence)    # We cannot set ALLUSERS in the property table, as this cannot be    # reset if the user choses a per-user installation. Instead, we    # maintain WhichUsers, which can be "ALL" or "JUSTME". The UI manages    # this property, and when the execution starts, ALLUSERS is set    # accordingly.    add_data(db, "Property", [("UpgradeCode", uc),                              ("WhichUsers", "ALL"),                              ("ProductLine", "Python%s%s" % (major, minor)),                             ])    db.Commit()    return db def remove_old_versions(db):    "Fill the upgrade table."    start = "%s.%s.0" % (major, minor)    # This requests that feature selection states of an older    # installation should be forwarded into this one. Upgrading    # requires that both the old and the new installation are    # either both per-machine or per-user.    migrate_features = 1    # See "Upgrade Table". We remove releases with the same major and    # minor version. For an snapshot, we remove all earlier snapshots. For    # a release, we remove all snapshots, and all earlier releases.    if snapshot:        add_data(db, "Upgrade",            [(upgrade_code_snapshot, start,              current_version,              None,                     # Ignore language              migrate_features,              None,                     # Migrate ALL features              "REMOVEOLDSNAPSHOT")])        props = "REMOVEOLDSNAPSHOT"    else:        add_data(db, "Upgrade",            [(upgrade_code, start, current_version,              None, migrate_features, None, "REMOVEOLDVERSION"),             (upgrade_code_snapshot, start, "%s.%d.0" % (major, int(minor)+1),              None, migrate_features, None, "REMOVEOLDSNAPSHOT")])        props = "REMOVEOLDSNAPSHOT;REMOVEOLDVERSION"    # Installer collects the product codes of the earlier releases in    # these properties. In order to allow modification of the properties,    # they must be declared as secure. See "SecureCustomProperties Property"    add_data(db, "Property", [("SecureCustomProperties", props)]) class PyDialog(Dialog):    """Dialog class with a fixed layout: controls at the top, then a ruler,    then a list of buttons: back, next, cancel. Optionally a bitmap at the    left."""    def __init__(self, *args, **kw):        """Dialog(database, name, x, y, w, h, attributes, title, first,        default, cancel, bitmap=true)"""        Dialog.__init__(self, *args)        ruler = self.h - 36        bmwidth = 152*ruler/328        if kw.get("bitmap", True):            self.bitmap("Bitmap", 0, 0, bmwidth, ruler, "PythonWin")        self.line("BottomLine", 0, ruler, self.w, 0)     def title(self, title):        "Set the title text of the dialog at the top."        # name, x, y, w, h, flags=Visible|Enabled|Transparent|NoPrefix,        # text, in VerdanaBold10        self.text("Title", 135, 10, 220, 60, 0x30003,                  r"{\VerdanaBold10}%s" % title)     def back(self, title, next, name = "Back", active = 1):        """Add a back button with a given title, the tab-next button,        its name in the Control table, possibly initially disabled.         Return the button, so that events can be associated"""        if active:            flags = 3 # Visible|Enabled        else:            flags = 1 # Visible        return self.pushbutton(name, 180, self.h-27 , 56, 17, flags, title, next)     def cancel(self, title, next, name = "Cancel", active = 1):        """Add a cancel button with a given title, the tab-next button,        its name in the Control table, possibly initially disabled.         Return the button, so that events can be associated"""        if active:            flags = 3 # Visible|Enabled        else:            flags = 1 # Visible        return self.pushbutton(name, 304, self.h-27, 56, 17, flags, title, next)     def next(self, title, next, name = "Next", active = 1):        """Add a Next button with a given title, the tab-next button,        its name in the Control table, possibly initially disabled.         Return the button, so that events can be associated"""        if active:            flags = 3 # Visible|Enabled        else:            flags = 1 # Visible        return self.pushbutton(name, 236, self.h-27, 56, 17, flags, title, next)     def xbutton(self, name, title, next, xpos):        """Add a button with a given title, the tab-next button,        its name in the Control table, giving its x position; the        y-position is aligned with the other buttons.         Return the button, so that events can be associated"""        return self.pushbutton(name, int(self.w*xpos - 28), self.h-27, 56, 17, 3, title, next) def add_ui(db):    x = y = 50    w = 370    h = 300    title = "[ProductName] Setup"     # see "Dialog Style Bits"    modal = 3      # visible | modal    modeless = 1   # visible    track_disk_space = 32     add_data(db, 'ActionText', uisample.ActionText)    add_data(db, 'UIText', uisample.UIText)     # Bitmaps    if not os.path.exists(srcdir+r"\PC\python_icon.exe"):        raise "Run icons.mak in PC directory"    add_data(db, "Binary",             [("PythonWin", msilib.Binary(srcdir+r"\PCbuild\installer.bmp")), # 152x328 pixels              ("py.ico",msilib.Binary(srcdir+r"\PC\py.ico")),             ])    add_data(db, "Icon",             [("python_icon.exe", msilib.Binary(srcdir+r"\PC\python_icon.exe"))])     # Scripts    # CheckDir sets TargetExists if TARGETDIR exists.    # UpdateEditIDLE sets the REGISTRY.tcl component into    # the installed/uninstalled state according to both the    # Extensions and TclTk features.    if os.system("nmake /nologo /c /f msisupport.mak") != 0:        raise "'nmake /f msisupport.mak' failed"    add_data(db, "Binary", [("Script", msilib.Binary("msisupport.dll"))])    # See "Custom Action Type 1"    if msilib.Win64:        CheckDir = "CheckDir"        UpdateEditIDLE = "UpdateEditIDLE"    else:        CheckDir =  "_CheckDir@4"        UpdateEditIDLE = "_UpdateEditIDLE@4"    add_data(db, "CustomAction",        [("CheckDir", 1, "Script", CheckDir)])    if have_tcl:        add_data(db, "CustomAction",        [("UpdateEditIDLE", 1, "Script", UpdateEditIDLE)])     # UI customization properties    add_data(db, "Property",             # See "DefaultUIFont Property"             [("DefaultUIFont", "DlgFont8"),              # See "ErrorDialog Style Bit"              ("ErrorDialog", "ErrorDlg"),              ("Progress1", "Install"),   # modified in maintenance type dlg              ("Progress2", "installs"),              ("MaintenanceForm_Action", "Repair")])     # Fonts, see "TextStyle Table"    add_data(db, "TextStyle",             [("DlgFont8", "Tahoma", 9, None, 0),              ("DlgFontBold8", "Tahoma", 8, None, 1), #bold              ("VerdanaBold10", "Verdana", 10, None, 1),              ("VerdanaRed9", "Verdana", 9, 255, 0),             ])     compileargs = r'-Wi "[TARGETDIR]Lib\compileall.py" -f -x bad_coding|badsyntax|site-packages "[TARGETDIR]Lib"'    # See "CustomAction Table"    add_data(db, "CustomAction", [        # msidbCustomActionTypeFirstSequence + msidbCustomActionTypeTextData + msidbCustomActionTypeProperty        # See "Custom Action Type 51",        # "Custom Action Execution Scheduling Options"        ("InitialTargetDir", 307, "TARGETDIR",         "[WindowsVolume]Python%s%s" % (major, minor)),        ("SetDLLDirToTarget", 307, "DLLDIR", "[TARGETDIR]"),        ("SetDLLDirToSystem32", 307, "DLLDIR", SystemFolderName),        # msidbCustomActionTypeExe + msidbCustomActionTypeSourceFile        # See "Custom Action Type 18"        ("CompilePyc", 18, "python.exe", compileargs),        ("CompilePyo", 18, "python.exe", "-O "+compileargs),        ])     # UI Sequences, see "InstallUISequence Table", "Using a Sequence Table"    # Numbers indicate sequence; see sequence.py for how these action integrate    add_data(db, "InstallUISequence",             [("PrepareDlg", "Not Privileged or Windows9x or Installed", 140),              ("WhichUsersDlg", "Privileged and not Windows9x and not Installed", 141),              ("InitialTargetDir", 'TARGETDIR=""', 750),              # In the user interface, assume all-users installation if privileged.              ("SetDLLDirToSystem32", 'DLLDIR="" and ' + sys32cond, 751),              ("SetDLLDirToTarget", 'DLLDIR="" and not ' + sys32cond, 752),              ("SelectDirectoryDlg", "Not Installed", 1230),              # XXX no support for resume installations yet              #("ResumeDlg", "Installed AND (RESUME OR Preselected)", 1240),              ("MaintenanceTypeDlg", "Installed AND NOT RESUME AND NOT Preselected", 1250),              ("ProgressDlg", None, 1280)])    add_data(db, "AdminUISequence",             [("InitialTargetDir", 'TARGETDIR=""', 750),              ("SetDLLDirToTarget", 'DLLDIR=""', 751),             ])     # Execute Sequences    add_data(db, "InstallExecuteSequence",            [("InitialTargetDir", 'TARGETDIR=""', 750),             ("SetDLLDirToSystem32", 'DLLDIR="" and ' + sys32cond, 751),             ("SetDLLDirToTarget", 'DLLDIR="" and not ' + sys32cond, 752),             ("UpdateEditIDLE", None, 1050),             ("CompilePyc", "COMPILEALL", 6800),             ("CompilePyo", "COMPILEALL", 6801),            ])    add_data(db, "AdminExecuteSequence",            [("InitialTargetDir", 'TARGETDIR=""', 750),             ("SetDLLDirToTarget", 'DLLDIR=""', 751),             ("CompilePyc", "COMPILEALL", 6800),             ("CompilePyo", "COMPILEALL", 6801),            ])     #####################################################################    # Standard dialogs: FatalError, UserExit, ExitDialog    fatal=PyDialog(db, "FatalError", x, y, w, h, modal, title,                 "Finish", "Finish", "Finish")    fatal.title("[ProductName] Installer ended prematurely")    fatal.back("< Back", "Finish", active = 0)    fatal.cancel("Cancel", "Back", active = 0)    fatal.text("Description1", 135, 70, 220, 80, 0x30003,               "[ProductName] setup ended prematurely because of an error.  Your system has not been modified.  To install this program at a later time, please run the installation again.")    fatal.text("Description2", 135, 155, 220, 20, 0x30003,               "Click the Finish button to exit the Installer.")    c=fatal.next("Finish", "Cancel", name="Finish")    # See "ControlEvent Table". Parameters are the event, the parameter    # to the action, and optionally the condition for the event, and the order    # of events.    c.event("EndDialog", "Exit")     user_exit=PyDialog(db, "UserExit", x, y, w, h, modal, title,                 "Finish", "Finish", "Finish")    user_exit.title("[ProductName] Installer was interrupted")    user_exit.back("< Back", "Finish", active = 0)    user_exit.cancel("Cancel", "Back", active = 0)    user_exit.text("Description1", 135, 70, 220, 80, 0x30003,               "[ProductName] setup was interrupted.  Your system has not been modified.  "               "To install this program at a later time, please run the installation again.")    user_exit.text("Description2", 135, 155, 220, 20, 0x30003,               "Click the Finish button to exit the Installer.")    c = user_exit.next("Finish", "Cancel", name="Finish")    c.event("EndDialog", "Exit")     exit_dialog = PyDialog(db, "ExitDialog", x, y, w, h, modal, title,                         "Finish", "Finish", "Finish")    exit_dialog.title("Completing the [ProductName] Installer")    exit_dialog.back("< Back", "Finish", active = 0)    exit_dialog.cancel("Cancel", "Back", active = 0)    exit_dialog.text("Acknowledgements", 135, 95, 220, 120, 0x30003,      "Special Windows thanks to:\n"      "    Mark Hammond, without whose years of freely \n"      "    shared Windows expertise, Python for Windows \n"      "    would still be Python for DOS.")     c = exit_dialog.text("warning", 135, 200, 220, 40, 0x30003,            "{\\VerdanaRed9}Warning: Python 2.5.x is the last "            "Python release for Windows 9x.")    c.condition("Hide", "NOT Version9X")     exit_dialog.text("Description", 135, 235, 220, 20, 0x30003,               "Click the Finish button to exit the Installer.")    c = exit_dialog.next("Finish", "Cancel", name="Finish")    c.event("EndDialog", "Return")     #####################################################################    # Required dialog: FilesInUse, ErrorDlg    inuse = PyDialog(db, "FilesInUse",                     x, y, w, h,                     19,                # KeepModeless|Modal|Visible                     title,                     "Retry", "Retry", "Retry", bitmap=False)    inuse.text("Title", 15, 6, 200, 15, 0x30003,               r"{\DlgFontBold8}Files in Use")    inuse.text("Description", 20, 23, 280, 20, 0x30003,               "Some files that need to be updated are currently in use.")    inuse.text("Text", 20, 55, 330, 50, 3,               "The following applications are using files that need to be updated by this setup. Close these applications and then click Retry to continue the installation or Cancel to exit it.")    inuse.control("List", "ListBox", 20, 107, 330, 130, 7, "FileInUseProcess",                  None, None, None)    c=inuse.back("Exit", "Ignore", name="Exit")    c.event("EndDialog", "Exit")    c=inuse.next("Ignore", "Retry", name="Ignore")    c.event("EndDialog", "Ignore")    c=inuse.cancel("Retry", "Exit", name="Retry")    c.event("EndDialog","Retry")      # See "Error Dialog". See "ICE20" for the required names of the controls.    error = Dialog(db, "ErrorDlg",                   50, 10, 330, 101,                   65543,       # Error|Minimize|Modal|Visible                   title,

Lines 1–500 of 1203.