⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 buildpkg.py

📁 Wxpython Implemented on Windows CE, Source code
💻 PY
📖 第 1 页 / 共 2 页
字号:
#!/usr/bin/env python

"""buildpkg.py -- Build OS X packages for Apple's Installer.app.

This is an experimental command-line tool for building packages to be
installed with the Mac OS X Installer.app application. 

It is much inspired by Apple's GUI tool called PackageMaker.app, that 
seems to be part of the OS X developer tools installed in the folder 
/Developer/Applications. But apparently there are other free tools to 
do the same thing which are also named PackageMaker like Brian Hill's 
one: 

  http://personalpages.tds.net/~brian_hill/packagemaker.html

Beware of the multi-package features of Installer.app (which are not 
yet supported here) that can potentially screw-up your installation 
and are discussed in these articles on Stepwise:

  http://www.stepwise.com/Articles/Technical/Packages/InstallerWoes.html
  http://www.stepwise.com/Articles/Technical/Packages/InstallerOnX.html

Beside using the PackageMaker class directly, by importing it inside 
another module, say, there are additional ways of using this module:
the top-level buildPackage() function provides a shortcut to the same 
feature and is also called when using this module from the command-
line.

    ****************************************************************
    NOTE: For now you should be able to run this even on a non-OS X 
          system and get something similar to a package, but without
          the real archive (needs pax) and bom files (needs mkbom) 
          inside! This is only for providing a chance for testing to 
          folks without OS X.
    ****************************************************************

TODO:
  - test pre-process and post-process scripts (Python ones?)
  - handle multi-volume packages (?)
  - integrate into distutils (?)

Dinu C. Gherman, 
gherman@europemail.com
November 2001

!! USE AT YOUR OWN RISK !!
"""

__version__ = 0.2
__license__ = "FreeBSD"


import os, sys, glob, fnmatch, shutil, string, copy, getopt
from os.path import basename, dirname, join, islink, isdir, isfile

Error = "buildpkg.Error"

PKG_INFO_FIELDS = """\
Title
Version
Description
DefaultLocation
DeleteWarning
NeedsAuthorization
DisableStop
UseUserMask
Application
Relocatable
Required
InstallOnly
RequiresReboot
RootVolumeOnly
LongFilenames
LibrarySubdirectory
AllowBackRev
OverwritePermissions
InstallFat\
"""

######################################################################
# Helpers
######################################################################

# Convenience class, as suggested by /F.

class GlobDirectoryWalker:
    "A forward iterator that traverses files in a directory tree."

    def __init__(self, directory, pattern="*"):
        self.stack = [directory]
        self.pattern = pattern
        self.files = []
        self.index = 0


    def __getitem__(self, index):
        while 1:
            try:
                file = self.files[self.index]
                self.index = self.index + 1
            except IndexError:
                # pop next directory from stack
                self.directory = self.stack.pop()
                self.files = os.listdir(self.directory)
                self.index = 0
            else:
                # got a filename
                fullname = join(self.directory, file)
                if isdir(fullname) and not islink(fullname):
                    self.stack.append(fullname)
                if fnmatch.fnmatch(file, self.pattern):
                    return fullname


######################################################################
# The real thing
######################################################################

class PackageMaker:
    """A class to generate packages for Mac OS X.

    This is intended to create OS X packages (with extension .pkg)
    containing archives of arbitrary files that the Installer.app 
    will be able to handle.

    As of now, PackageMaker instances need to be created with the 
    title, version and description of the package to be built. 
    The package is built after calling the instance method 
    build(root, **options). It has the same name as the constructor's 
    title argument plus a '.pkg' extension and is located in the same 
    parent folder that contains the root folder.

    E.g. this will create a package folder /my/space/distutils.pkg/:

      pm = PackageMaker("distutils", "1.0.2", "Python distutils.")
      pm.build("/my/space/distutils")
    """

    packageInfoDefaults = {
        'Title': None,
        'Version': None,
        'Description': '',
        'DefaultLocation': '/',
        'DeleteWarning': '',
        'NeedsAuthorization': 'NO',
        'DisableStop': 'NO',
        'UseUserMask': 'YES',
        'Application': 'NO',
        'Relocatable': 'YES',
        'Required': 'NO',
        'InstallOnly': 'NO',
        'RequiresReboot': 'NO',
        'RootVolumeOnly' : 'NO',
        'InstallFat': 'NO',
        'LongFilenames': 'YES',
        'LibrarySubdirectory': 'Standard',
        'AllowBackRev': 'YES',
        'OverwritePermissions': 'NO',
        }


    def __init__(self, title, version, desc):
        "Init. with mandatory title/version/description arguments."

        info = {"Title": title, "Version": version, "Description": desc}
        self.packageInfo = copy.deepcopy(self.packageInfoDefaults)
        self.packageInfo.update(info)
        
        # variables set later
        self.packageRootFolder = None
        self.packageResourceFolder = None
        self.sourceFolder = None
        self.resourceFolder = None


    def build(self, root, resources=None, **options):
        """Create a package for some given root folder.

        With no 'resources' argument set it is assumed to be the same 
        as the root directory. Option items replace the default ones 
        in the package info.
        """

        # set folder attributes
        self.sourceFolder = root
        if resources == None:
            self.resourceFolder = root
        else:
            self.resourceFolder = resources

        # replace default option settings with user ones if provided
        fields = self. packageInfoDefaults.keys()
        for k, v in options.items():
            if k in fields:
                self.packageInfo[k] = v
            elif not k in ["OutputDir"]:
                raise Error, "Unknown package option: %s" % k
        
        # Check where we should leave the output. Default is current directory
        outputdir = options.get("OutputDir", os.getcwd())
        packageName = self.packageInfo["Title"]
        self.PackageRootFolder = os.path.join(outputdir, packageName + ".pkg")
 
        # do what needs to be done
        self._makeFolders()
        self._addInfo()
        self._addBom()
        self._addArchive()
        self._addResources()
        self._addSizes()
        self._addLoc()


    def _makeFolders(self):
        "Create package folder structure."

        # Not sure if the package name should contain the version or not...
        # packageName = "%s-%s" % (self.packageInfo["Title"], 
        #                          self.packageInfo["Version"]) # ??

        contFolder = join(self.PackageRootFolder, "Contents")
        self.packageResourceFolder = join(contFolder, "Resources")
        os.mkdir(self.PackageRootFolder)
        os.mkdir(contFolder)
        os.mkdir(self.packageResourceFolder)

    def _addInfo(self):
        "Write .info file containing installing options."

        # Not sure if options in PKG_INFO_FIELDS are complete...

        info = ""
        for f in string.split(PKG_INFO_FIELDS, "\n"):
            if self.packageInfo.has_key(f):
                info = info + "%s %%(%s)s\n" % (f, f)
        info = info % self.packageInfo
        base = self.packageInfo["Title"] + ".info"
        path = join(self.packageResourceFolder, base)
        f = open(path, "w")
        f.write(info)


    def _addBom(self):

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -