Example #1
0
    def __init__(self, project_path=None):
        if not os.path.isabs(project_path):
            project_path = os.path.join(os.getcwd(), project_path)
        self.project_path = project_path
        self.root = None

        if project_path and os.path.exists(project_path):
            try:
                doc = xml.dom.minidom.parse(project_path)
                # Get the first app-bundle tag and ignore any others.
                self.root = utils.node_get_element_by_tag_name(doc, "app-bundle")
            except:
                print "Could not load project %s:" % (project_path)
                raise

        # The directory the project file is in (as opposed to
        # project_path which is the path including the filename).
        self.project_dir, tail = os.path.split(project_path)

        plist_path = self.get_plist_path()
        try:
            plist = Plist.fromFile(plist_path)
        except EnvironmentError, e:
            if e.errno == errno.ENOENT:
                print "Info.plist file not found: " + plist_path
                sys.exit(1)
            else:
                raise
Example #2
0
def makeMpkgPlist(path):

    vers = getFullVersion()
    major, minor = map(int, getVersion().split('.', 2))

    pl = Plist(
        CFBundleGetInfoString="Python %s" % (vers, ),
        CFBundleIdentifier='org.python.Python',
        CFBundleName='Python',
        CFBundleShortVersionString=vers,
        IFMajorVersion=major,
        IFMinorVersion=minor,
        IFPkgFlagComponentDirectory="Contents/Packages",
        IFPkgFlagPackageList=[
            dict(IFPkgFlagPackageLocation='%s-%s.pkg' %
                 (item['name'], getVersion()),
                 IFPkgFlagPackageSelection='selected')
            for item in pkg_recipes()
        ],
        IFPkgFormatVersion=0.10000000149011612,
        IFPkgFlagBackgroundScaling="proportional",
        IFPkgFlagBackgroundAlignment="left",
        IFPkgFlagAuthorizationAction="RootAuthorization",
    )

    writePlist(pl, path)
Example #3
0
    def py2app(self):
        """ Generates PList settings and sets values for setuptools.setup() arg.

        Sets:
            - execute script
            - require package
            - plist file
            - app icon.(not yet)
        """
        from plistlib import Plist
        self.setup_args['app'] = ['music_controller/__main__.py']
        self.setup_args['setup_requires'].append('py2app')
        plist = Plist.fromFile('osx/Info.plist')
        plist.update ( dict(
                CFBundleShortVersionString = version.__version__+':'+get_rev(),
                NSHumanReadableCopyright = u"Copyright 2012 mei raka",
                ))
        if not 'options' in self.setup_args:
            self.setup_args['options'] = {}
        if not 'py2app' in self.setup_args['options']:
            self.setup_args['options']['py2app'] = {}
        self.setup_args['options']['py2app'] = dict(
                plist=plist
                )

        # add lang
        '''
Example #4
0
    def __init__(self, project_path=None):
        if not os.path.isabs(project_path):
            project_path = os.path.join(os.getcwd(), project_path)
        self.project_path = project_path
        self.root = None

        if project_path and os.path.exists(project_path):
            try:
                doc = xml.dom.minidom.parse(project_path)
                # Get the first app-bundle tag and ignore any others.
                self.root = utils.node_get_element_by_tag_name(
                    doc, "app-bundle")
            except:
                print "Could not load project %s:" % (project_path)
                raise

        # The directory the project file is in (as opposed to
        # project_path which is the path including the filename).
        self.project_dir, tail = os.path.split(project_path)

        plist_path = self.get_plist_path()
        try:
            plist = Plist.fromFile(plist_path)
        except EnvironmentError, e:
            if e.errno == errno.ENOENT:
                print "Info.plist file not found: " + plist_path
                sys.exit(1)
            else:
                raise
Example #5
0
 def test_f_get_name(self):
     try:
         plist_path = self.goodproject.get_plist_path()
     except KeyError:
         self.fail("Goodproject didn't set the default prefix")
     try:
         plist = Plist.fromFile(plist_path)
         name = plist.CFBundleExecutable
     except IOError:
         self.fail("Path problem " + plist_path)
     pname = self.goodproject.get_name()
     self.failUnlessEqual(pname, name, "Bad Name %s" % pname)
Example #6
0
 def test_f_get_name(self):
     try:
         plist_path = self.goodproject.get_plist_path()
     except KeyError:
         self.fail("Goodproject didn't set the default prefix")
     try:
         plist = Plist.fromFile(plist_path)
         name = plist.CFBundleExecutable
     except IOError:
         self.fail("Path problem " + plist_path)
     pname = self.goodproject.get_name()
     self.failUnlessEqual(pname, name, "Bad Name %s" % pname)
Example #7
0
def main(httpbase=HTTPBASE, upload=True):
    plist = Plist.fromFile(os.path.join(PLISTDIR, plat + '.plist'))

    print 'Querying package information'
    spl = runsetup('--name --version --url --description').read().split(
        '\n')[:-1]
    name, version, url = spl[:3]
    description = '\n'.join(spl[3:])

    print 'Building dumb distribution for %s-%s' % (name, version)
    runsetup('bdist_dumb').read()

    hash = md5.md5()
    fn = '%s-%s.%s.tar.gz' % (name, version, plat)
    print 'Calculating MD5 hash for', fn
    f = file(os.path.join('dist', fn), 'rb')
    while 1:
        s = f.read(1024)
        if not s:
            break
        hash.update(s)
    f.close()
    hash = hash.hexdigest()

    if upload:
        print 'Uploading', fn
        os.system(UPLOADCMD % os.path.join('dist', fn))

    for pkg in plist.Packages:
        if pkg.Name == name and pkg.Flavor == 'binary':
            print 'Existing package metadata found'
            break
    else:
        print 'Creating new package metadata'
        pkg = {
            'Flavor': 'binary',
            'Install-test': '\nimport %s\n\t\t\t' % (name, ),
            'Prerequisites': [],
        }
        plist.Packages.append(pkg)
    pkg['Name'] = name
    pkg['Version'] = version
    pkg['MD5Sum'] = hash
    pkg['Download-URL'] = httpbase + fn
    if url:
        pkg['Home-page'] = url
    if description and not pkg.get('Description', None):
        pkg['Description'] = '\n%s\n\t\t\t' % (description, )
    print 'Writing out new plist'
    plist.write(os.path.join(PLISTDIR, plat + '.plist'))
Example #8
0
 def _writePlistInfo(self):
     """
     Writes the Info.plist file in the Contests directory.
     """
     pl = Plist(
         CFBundleExecutable=self.executable,
         CFBundleGetInfoString='%s-1.0.0' % self.name,
         CFBundleIconFile=basename(self.icns),
         CFBundleIdentifier='com.%s' % self.name,
         CFBundlePackageType='APPL',
         CFBundleVersion='1.0.0',
         CFBundleShortVersionString='1.0.0',
     )
     writePlist(pl, join(self.contents_dir, 'Info.plist'))
Example #9
0
 def handle_about_dlog(self):
     global mufsim_version
     if platform.system() == 'Darwin' and not mufsim_version:
         if "MufSim.app/Contents/Resources" in os.getcwd():
             from plistlib import Plist
             plist = Plist.fromFile(os.path.join('..', 'Info.plist'))
             mufsim_version = plist['CFBundleShortVersionString']
     if mufsim_version is None:
         mufsim_version = ""
     showinfo(
         "About MufSimulator",
         "MufSimulator %s\nCopyright 2016\nRevar Desmera" % mufsim_version,
         parent=self.root,
     )
Example #10
0
def main(httpbase=HTTPBASE, upload=True):
    plist = Plist.fromFile(os.path.join(PLISTDIR, plat+'.plist'))

    print 'Querying package information'
    spl = runsetup('--name --version --url --description').read().split('\n')[:-1]
    name, version, url = spl[:3]
    description = '\n'.join(spl[3:])

    print 'Building dumb distribution for %s-%s' % (name, version)
    runsetup('bdist_dumb').read()

    hash = md5.md5()
    fn = '%s-%s.%s.tar.gz' % (name, version, plat)
    print 'Calculating MD5 hash for', fn
    f = file(os.path.join('dist', fn), 'rb')
    while 1:
        s = f.read(1024)
        if not s:
            break
        hash.update(s)
    f.close()
    hash = hash.hexdigest()

    if upload:
        print 'Uploading', fn 
        os.system(UPLOADCMD % os.path.join('dist', fn))

    for pkg in plist.Packages:
        if pkg.Name == name and pkg.Flavor == 'binary':
            print 'Existing package metadata found'
            break
    else:
        print 'Creating new package metadata'
        pkg = {
            'Flavor':'binary',
            'Install-test':'\nimport %s\n\t\t\t' % (name,),
            'Prerequisites':[],
        }
        plist.Packages.append(pkg)
    pkg['Name'] = name
    pkg['Version'] = version
    pkg['MD5Sum'] = hash
    pkg['Download-URL'] = httpbase + fn
    if url:
        pkg['Home-page'] = url
    if description and not pkg.get('Description', None):
        pkg['Description'] = '\n%s\n\t\t\t' % (description,)
    print 'Writing out new plist'
    plist.write(os.path.join(PLISTDIR, plat+'.plist'))
Example #11
0
def generate_plist(plist_file):
    """Read plist from file and set CFBundleVersion to HEAD commit hash"""

    version = git('git', 'describe', '--abbrev=0', '--tags')
    commit_hash = git('git', 'rev-parse', '--short', 'HEAD')

    if version is None or commit_hash is None:
        sys.exit(-1)

    plist = Plist.fromFile(plist_file)
    plist.update(dict(
        CFBundleShortVersionString=version,
        CFBundleVersion=commit_hash,
    ))
    return plist
Example #12
0
    def __init__(self, project):
        self.project = project

        self.project_dir = project.get_project_dir()

        plist_path = self.project.get_plist_path()
        self.plist = Plist.fromFile(plist_path)

        # List of paths that should be recursively searched for
        # binaries that are used to find library dependencies.
        self.binary_paths = []

        # Create the bundle in a temporary location first and move it
        # to the final destination when done.
        dest = project.get_meta().dest
        self.bundle_path = os.path.join(dest, "." + project.get_name() + ".app")
Example #13
0
 def __init__(self, testxml, path):
     doc = xml.dom.minidom.parseString(testxml)
     self.root = utils.node_get_element_by_tag_name(doc, "app-bundle")
     assert self.root != None
     dir, tail = os.path.split(path)
     self.project_dir = os.path.join(os.getcwd(), dir)
     self.project_path = os.path.join(self.project_dir, tail)
     try:
         plist_path = os.path.join(self.project_dir, "test.plist")
         plist = Plist.fromFile(plist_path)
     except EnvironmentError, e:
         if e.errno == errno.ENOENT:
             print "Info.plist file not found: " + plist_path
             sys.exit(1)
         else:
             raise
Example #14
0
    def __init__(self, project):
        self.project = project

        self.project_dir = project.get_project_dir()

        plist_path = self.project.get_plist_path()
        self.plist = Plist.fromFile(plist_path)

        # List of paths that should be recursively searched for
        # binaries that are used to find library dependencies.
        self.binary_paths = []

        # Create the bundle in a temporary location first and move it
        # to the final destination when done.
        dest = project.get_meta().dest
        self.bundle_path = os.path.join(dest, "." + project.get_name() + ".app")
Example #15
0
def generate_plist(plist_file):
    """Read plist from file and set CFBundleVersion to HEAD commit hash"""

    version = git('git', 'describe', '--abbrev=0', '--tags')
    commit_hash = git('git', 'rev-parse', '--short', 'HEAD')

    if version is None or commit_hash is None:
        sys.exit(-1)

    plist = Plist.fromFile(plist_file)
    plist.update(
        dict(
            CFBundleShortVersionString=version,
            CFBundleVersion=commit_hash,
        ))
    return plist
 def __init__(self, testxml, path):
     doc = xml.dom.minidom.parseString(testxml)
     self.root = utils.node_get_element_by_tag_name(doc, "app-bundle")
     assert self.root != None
     dir, tail = os.path.split(path)
     self.project_dir = os.path.join(os.getcwd(), dir)
     self.project_path = os.path.join(self.project_dir, tail)
     try:
         plist_path = os.path.join(self.project_dir, "test.plist")
         plist = Plist.fromFile(plist_path)
     except EnvironmentError, e:
         if e.errno == errno.ENOENT:
             print "Info.plist file not found: " + plist_path
             sys.exit(1)
         else:
             raise
Example #17
0
    def make_app_bundle(self):
        plist_path = os.path.join(self.bundle_skeleton_dir, 'Contents',
                                  'Info.plist')
        app_name = 'Unknown'
        plist = None
        if os.path.exists(plist_path):
            plist = Plist.fromFile(plist_path)
            app_name = plist['CFBundleExecutable']
        else:
            print 'Warning: no Contents/Info.plist in .app skeleton'

        self.bundle_app_dir = os.path.join(self.bundle_output_dir,
                                           app_name + '.app')
        self.bundle_contents_dir = os.path.join(self.bundle_app_dir,
                                                'Contents')
        self.bundle_res_dir = os.path.join(self.bundle_contents_dir,
                                           'Resources')
        self.bundle_macos_dir = os.path.join(self.bundle_contents_dir, 'MacOS')

        # Create the .app tree, copying the skeleton
        shutil.rmtree(self.bundle_app_dir, ignore_errors=True)
        shutil.copytree(self.bundle_skeleton_dir, self.bundle_app_dir)
        if not os.path.exists(self.bundle_contents_dir):
            os.makedirs(self.bundle_contents_dir)
        if not os.path.exists(self.bundle_res_dir):
            os.makedirs(self.bundle_res_dir)
        if not os.path.exists(self.bundle_macos_dir):
            os.makedirs(self.bundle_macos_dir)

        # Generate the PkgInfo
        pkginfo_path = os.path.join(self.bundle_contents_dir, 'PkgInfo')
        if not os.path.exists(pkginfo_path) and not plist == None:
            fp = open(pkginfo_path, 'w')
            fp.write(plist['CFBundlePackageType'])
            fp.write(plist['CFBundleSignature'])
            fp.close()

        # Run solitary against the installation to collect files
        files = ''
        for file in self.bundle_from_build:
            files = files + ' "%s"' % os.path.join(self.prefix, file)

        run_shell ('mono --debug ../../solitary/Solitary.exe '
         '--mono-prefix="%s" --root="%s" --out="%s" %s' % \
         (self.prefix, self.prefix, self.bundle_res_dir, files))
        self.configure_gtk()
        self.configure_gdk_pixbuf()
Example #18
0
    def make_app_bundle(self):
        plist_path = os.path.join(
            self.bundle_skeleton_dir, 'Contents', 'Info.plist')
        app_name = 'Unknown'
        plist = None
        if os.path.exists(plist_path):
            plist = Plist.fromFile(plist_path)
            app_name = plist['CFBundleExecutable']
        else:
            print 'Warning: no Contents/Info.plist in .app skeleton'

        self.bundle_app_dir = os.path.join(
            self.bundle_output_dir, app_name + '.app')
        self.bundle_contents_dir = os.path.join(
            self.bundle_app_dir, 'Contents')
        self.bundle_res_dir = os.path.join(
            self.bundle_contents_dir, 'Resources')
        self.bundle_macos_dir = os.path.join(self.bundle_contents_dir, 'MacOS')

        # Create the .app tree, copying the skeleton
        shutil.rmtree(self.bundle_app_dir, ignore_errors=True)
        shutil.copytree(self.bundle_skeleton_dir, self.bundle_app_dir)
        if not os.path.exists(self.bundle_contents_dir):
            os.makedirs(self.bundle_contents_dir)
        if not os.path.exists(self.bundle_res_dir):
            os.makedirs(self.bundle_res_dir)
        if not os.path.exists(self.bundle_macos_dir):
            os.makedirs(self.bundle_macos_dir)

        # Generate the PkgInfo
        pkginfo_path = os.path.join(self.bundle_contents_dir, 'PkgInfo')
        if not os.path.exists(pkginfo_path) and not plist is None:
            fp = open(pkginfo_path, 'w')
            fp.write(plist['CFBundlePackageType'])
            fp.write(plist['CFBundleSignature'])
            fp.close()

        # Run solitary against the installation to collect files
        files = ''
        for file in self.bundle_from_build:
            files = files + ' "%s"' % os.path.join(self.prefix, file)

        run_shell('mono --debug ../../solitary/Solitary.exe '
                  '--mono-prefix="%s" --root="%s" --out="%s" %s' %
                  (self.prefix, self.prefix, self.bundle_res_dir, files))
        self.configure_gtk()
        self.configure_gdk_pixbuf()
Example #19
0
    def make_app_bundle(self):
        plist_path = os.path.join(self.bundle_skeleton_dir, "Contents", "Info.plist")
        app_name = "Unknown"
        plist = None
        if os.path.exists(plist_path):
            plist = Plist.fromFile(plist_path)
            app_name = plist["CFBundleExecutable"]
        else:
            print "Warning: no Contents/Info.plist in .app skeleton"

        self.bundle_app_dir = os.path.join(self.bundle_output_dir, app_name + ".app")
        self.bundle_contents_dir = os.path.join(self.bundle_app_dir, "Contents")
        self.bundle_res_dir = os.path.join(self.bundle_contents_dir, "Resources")
        self.bundle_macos_dir = os.path.join(self.bundle_contents_dir, "MacOS")

        # Create the .app tree, copying the skeleton
        shutil.rmtree(self.bundle_app_dir, ignore_errors=True)
        shutil.copytree(self.bundle_skeleton_dir, self.bundle_app_dir)
        if not os.path.exists(self.bundle_contents_dir):
            os.makedirs(self.bundle_contents_dir)
        if not os.path.exists(self.bundle_res_dir):
            os.makedirs(self.bundle_res_dir)
        if not os.path.exists(self.bundle_macos_dir):
            os.makedirs(self.bundle_macos_dir)

        # Generate the PkgInfo
        pkginfo_path = os.path.join(self.bundle_contents_dir, "PkgInfo")
        if not os.path.exists(pkginfo_path) and not plist == None:
            fp = open(pkginfo_path, "w")
            fp.write(plist["CFBundlePackageType"])
            fp.write(plist["CFBundleSignature"])
            fp.close()

            # Run solitary against the installation to collect files
        files = ""
        for file in self.bundle_from_build:
            files = files + ' "%s"' % os.path.join(self.prefix, file)

        run_shell(
            "mono --debug ../../solitary/Solitary.exe "
            '--mono-prefix="%s" --root="%s" --out="%s" %s' % (self.prefix, self.prefix, self.bundle_res_dir, files)
        )
        self.configure_gtk()
        self.configure_gdk_pixbuf()
Example #20
0
def buildInstaller():

    # Zap all compiled files
    for dirpath, _, filenames in os.walk(os.path.join(WORKDIR, '_root')):
        for fn in filenames:
            if fn.endswith('.pyc') or fn.endswith('.pyo'):
                os.unlink(os.path.join(dirpath, fn))

    outdir = os.path.join(WORKDIR, 'installer')
    if os.path.exists(outdir):
        shutil.rmtree(outdir)
    os.mkdir(outdir)

    pkgroot = os.path.join(outdir, 'Python.mpkg', 'Contents')
    pkgcontents = os.path.join(pkgroot, 'Packages')
    os.makedirs(pkgcontents)
    for recipe in pkg_recipes():
        packageFromRecipe(pkgcontents, recipe)

    rsrcDir = os.path.join(pkgroot, 'Resources')

    fn = os.path.join(pkgroot, 'PkgInfo')
    fp = open(fn, 'w')
    fp.write('pmkrpkg1')
    fp.close()

    os.mkdir(rsrcDir)

    makeMpkgPlist(os.path.join(pkgroot, 'Info.plist'))
    pl = Plist(
        IFPkgDescriptionTitle="Python",
        IFPkgDescriptionVersion=getVersion(),
    )

    writePlist(pl, os.path.join(pkgroot, 'Resources', 'Description.plist'))
    for fn in os.listdir('resources'):
        if fn == '.svn': continue
        if fn.endswith('.jpg'):
            shutil.copy(os.path.join('resources', fn),
                        os.path.join(rsrcDir, fn))
        else:
            patchFile(os.path.join('resources', fn), os.path.join(rsrcDir, fn))

    shutil.copy("../../LICENSE", os.path.join(rsrcDir, 'License.txt'))
Example #21
0
 def _get_macos_ver_info_from_plist(self):
     """Retrive Mac OS system information from
         /System/Library/CoreServices/SystemVersion.plist
     as suggested here:
         http://tinyurl.com/9ssrn
     """
     plist_path = "/System/Library/CoreServices/SystemVersion.plist"
     if not exists(plist_path):
         return
     try:
         from plistlib import Plist
     except ImportError:
         return
     plist = Plist.fromFile(plist_path)
     return {
         "os_ver": plist["ProductVersion"],
         "os_build": plist["ProductBuildVersion"],
         "os_name": plist["ProductName"],
     }
Example #22
0
 def _get_macos_ver_info_from_plist(self):
     """Retrive Mac OS system information from
         /System/Library/CoreServices/SystemVersion.plist
     as suggested here:
         http://tinyurl.com/9ssrn
     """
     plist_path = "/System/Library/CoreServices/SystemVersion.plist"
     if not exists(plist_path):
         return
     try:
         from plistlib import Plist
     except ImportError:
         return
     plist = Plist.fromFile(plist_path)
     return {
         "os_ver": plist["ProductVersion"],
         "os_build": plist["ProductBuildVersion"],
         "os_name": plist["ProductName"],
     }
Example #23
0
    def __init__(self, project):
        self.project = project

        self.project_dir = project.get_project_dir()

        plist_path = self.project.get_plist_path()
        self.plist = Plist.fromFile(plist_path)

        # List of paths that should be recursively searched for
        # binaries that are used to find library dependencies.
        self.binaries_to_copy = []
        self.copied_binaries = []
        #List of frameworks moved into the bundle which need to be set
        #up for private use.
        self.frameworks = []

        # Create the bundle in a temporary location first and move it
        # to the final destination when done.
        self.meta = project.get_meta()
        self.bundle_path = os.path.join(self.meta.dest, "." + project.get_bundle_name() + ".app")
Example #24
0
    def __init__(self, project):
        self.project = project

        self.project_dir = project.get_project_dir()

        plist_path = self.project.get_plist_path()
        self.plist = Plist.fromFile(plist_path)

        # List of paths that should be recursively searched for
        # binaries that are used to find library dependencies.
        self.binaries_to_copy = []
        self.copied_binaries = []
        #List of frameworks moved into the bundle which need to be set
        #up for private use.
        self.frameworks = []

        # Create the bundle in a temporary location first and move it
        # to the final destination when done.
        self.meta = project.get_meta()
        self.bundle_path = os.path.join(
            self.meta.dest, "." + project.get_bundle_name() + ".app")
def buildApp(trunkDir,
             releaseDir,
             version="DEV",
             appName="Numenta Vision Toolkit"):

    print "Building application..."
    print "trunkDir: %s" % trunkDir
    print "releaseDir: %s" % releaseDir

    # Special incantation to import py2app checked in to svn
    py2appdir = "external/darwin86/lib/python%s/site-packages-py2app" % \
                pythonVersion
    py2appdir = os.path.join(trunkDir, py2appdir)
    import site
    site.addsitedir(py2appdir)

    # Make sure we get nupic and external packages from the right place.
    sitePackagesDir = os.path.join(
        releaseDir, "lib/python%s/site-packages" % pythonVersion)
    sys.path.insert(0, sitePackagesDir)

    visionDir = os.path.join(releaseDir, "share/vision")
    origDir = os.getcwd()

    os.chdir(visionDir)
    if os.path.exists("dist"):
        print "Removing previous installation"
        shutil.rmtree("dist")

    src = os.path.join(sitePackagesDir, "PIL")
    dest = os.path.join(sitePackagesDir, "Image")
    if not os.path.exists(dest):
        print "Linking %s to %s" % (dest, src)
        os.symlink(src, dest)

    from setuptools import setup
    import py2app.recipes
    # the matplotlib recipe adds a bad dependency on pytz.zoneinfo
    del py2app.recipes.matplotlib

    assert (len(sys.argv) == 1)
    sys.argv.append("py2app")

    from plistlib import Plist
    licenseText = """
Copyright (C) 2009 Numenta Inc. All rights reserved.

This copy of the software is a development version
and is not authorized for any release or use outside of
the Numenta engineering team.
"""

    licenseFile = os.path.join(visionDir, "LICENSE")
    if os.path.exists(licenseFile):
        licenseText = open(licenseFile).read()

    # To appear properly in quicklook,
    # license paragraph should be unwrapped.
    # \n-><space>, but \n\n should remain unchanged
    licenseText = licenseText.replace("\n\n", "XXX")
    licenseText = licenseText.replace("\n", " ")
    licenseText = licenseText.replace("XXX", "\n\n")

    plistFile = os.path.join(visionDir, "Info.plist")
    if os.path.exists(plistFile):
        plist = Plist.fromFile(plistFile)
    else:
        print "File '%s' not found" % plistFile
        plist = dict()
    plist.update(
        dict(CFBundleVersion=version,
             CFBundleShortVersionString=version,
             CFBundleName=appName,
             NSHumanReadableCopyright=licenseText))

    print "Running setup..."
    setup(
        app=["RunVisionToolkit.py"],
        setup_requires=["py2app"],
        options=dict(py2app=dict(
            includes=[],
            packages=[
                'nupic',  # problem finding image files in site-packages.zip
                #'matplotlib', # problem finding data files in site-packages.zip
                'curses',  # seg fault in site-packages.zip
                'opencv',  # import error
                'enthought',
                'wx',  # bus error when dragging files
            ],
            plist=plist,
            iconfile="demo.icns")))
    print "Done with base app creation"

    app = os.path.join(visionDir, "dist", "%s.app" % appName)

    appResources = os.path.join(app, "Contents/Resources")

    # Copy the base networks
    networkDir = os.path.join(appResources, "networks", "toolkit")
    if not os.path.exists(networkDir):
        os.makedirs(networkDir)
    networkNames = [
        f for f in os.listdir("networks/toolkit") if f.endswith('.xml.gz')
    ]
    for name in networkNames:
        shutil.copy("networks/toolkit/%s" % name,
                    os.path.join(networkDir, name))

    # Copy the tutorial projects
    projectDir = os.path.join(appResources, "projects")
    if not os.path.exists(projectDir):
        os.makedirs(projectDir)
    projectNames = [f for f in os.listdir("projects") if f.endswith('.tgz')]
    for name in projectNames:
        shutil.copy("projects/%s" % name, os.path.join(projectDir, name))

    # # Copy the help files
    # helpDir = os.path.join(appResources, "VisionToolkitHelp")
    # if not os.path.exists(helpDir):
    #   os.makedirs(helpDir)
    # helpNames = [f for f in os.listdir("VisionToolkitHelp")
    #              if not f.startswith('.')]
    # for name in helpNames:
    #   shutil.copy("VisionToolkitHelp/%s" % name, os.path.join(helpDir, name))

    # py2app doesn't copy the plugins, currently
    libDir = os.path.join(appResources, "lib")
    assert (os.path.exists(libDir))
    srcLibDir = os.path.abspath("../../lib")
    shutil.copy(os.path.join(srcLibDir, "libBasicPlugin.dylib"), libDir)
    shutil.copy(os.path.join(srcLibDir, "libLearningPlugin.dylib"), libDir)

    # Used by the about box
    # XXX need a new icon
    if os.path.exists("demo.ico"):
        shutil.copy("demo.ico", os.path.join(appResources, "demo.ico"))
    else:
        print "Warning: file 'demo.ico' not found"

    # Used by the license checker and the about box
    if os.path.exists("LICENSE"):
        shutil.copy("LICENSE", os.path.join(appResources, "LICENSE"))
    else:
        print "Warning: file 'LICENSE' not found"

    # Also used by the about box
    versionFile = os.path.join(appResources, ".version")
    assert not os.path.exists(versionFile)
    open(versionFile, "w").write(version)

    # buildinfo not currently used by the about box but we put it
    # in for identification
    buildinfoFile = os.path.join(releaseDir, ".buildinfo")
    if os.path.exists(buildinfoFile):
        shutil.copy(buildinfoFile, os.path.join(appResources, ".buildinfo"))
    else:
        print "Warning: file '.buildinfo' not found"

    # We create a bin dir so that nupic can find its root directory,
    # which it needs to find the libraries.
    binDir = os.path.join(appResources, "bin")
    if not os.path.exists(binDir):
        os.mkdir(binDir)

    # extract test data if not already extracted


#   if not os.path.exists("data/nta4_test"):
#     os.chdir("data")
#     rc = os.system("tar xzf nta4_test.tar.gz")
#     if rc != 0:
#       raise Exception("tar xzf nta4_test.tar.gz failed")
#     os.chdir("..")

# extract distractor data if not already extracted
#   if not os.path.exists("data/distractors"):
#     os.chdir("data")
#     rc = os.system("tar xzf distractors.tar.gz")
#     if rc != 0:
#       raise Exception("tar xzf distractors.tar.gz failed")
#     os.chdir("..")

# Copy the license if it exists. This is not part of data_files in the setup
# above because it may not exist if we're not installing from an official
# demo release
#   licenseFile = os.path.join(visionDir, "demo_license.cfg")
#   if not os.path.exists(licenseFile):
#     print "WARNING: demo license file %s does not exist -- skipping" % licenseFile
#   else:
#     shutil.copy(licenseFile, appResources)

#   dataDir = os.path.join(appResources, "data")
#   try:
#     os.makedirs(dataDir)
#   except:
#     pass
#   shutil.copytree("data/nta4_test", os.path.join(dataDir, "nta4_test"))
#   shutil.copytree("data/distractors", os.path.join(dataDir, "distractors"))
    print "Done creating image"

    # Manual clean up of a bunch of stuff we don't need
    os.chdir(app)
    os.system("du -skh .")
    rc = os.system("find . -name \*.pyc -o -name \*.pyo| xargs rm")
    assert (rc == 0)
    rc = os.system("rm -rf Contents/Resources/lib/python%s/wx/tools" %
                   pythonVersion)
    assert (rc == 0)
    os.system("du -skh .")

    os.chdir(origDir)

    print "Created application in %s" % app
    return app
Example #26
0
    return [(x,y) for (x,y) in l if f(y[0])]

# ----- build the app bundle
mainfile = os.path.join('Tribler','Player','swarmplayer.py')

setup(
    setup_requires=['py2app'],
    name='SwarmPlayer',
    app=[mainfile],
    options={ 'py2app': {
        'argv_emulation': True,
        'includes': includeModules,
        'excludes': ["Tkinter","Tkconstants","tcl"],
        'iconfile': 'Tribler/Player/Build/Mac/tribler.icns',
        'plist': Plist.fromFile('Tribler/Player/Build/Mac/Info.plist'),
        'optimize': 2*int(not __debug__),
        'resources':
            [("Tribler/Lang", ["Tribler/Lang/english.lang"]),
             "Tribler/binary-LICENSE.txt", 
             "Tribler/readme.txt",
             "Tribler/Images/swarmplayer.ico",
             "Tribler/Player/Build/Mac/TriblerDoc.icns",
           ]
           # add images
           + includedir( "Tribler/Images" )

           # add VLC plugins
           + includedir( "macbinaries/vlc_plugins" )

           # add ffmpeg binary
Example #27
0
from distutils.core import setup
import py2app
from plistlib import Plist
import os

name = 'ASDictionary'
version = '0.11.0'

os.system('''
sdp -fa %s.sdef;
Rez %sScripting.r -o %s.rsrc -useDF
''' % ((name, ) * 3))

setup(app=[name + ".py"],
      data_files=["MainMenu.nib"],
      options=dict(py2app=dict(plist=Plist(
          NSAppleScriptEnabled=True,
          CFBundleVersion=version,
          CFBundleShortVersionString=version,
          NSHumanReadableCopyright="(C) 2005-2008 HAS",
          CFBundleIdentifier="net.sourceforge.appscript.asdictionary",
          CFBundleDocumentTypes=[
              dict(
                  CFBundleTypeExtensions=["*"],
                  CFBundleTypeName="public.item",
                  CFBundleTypeRole="Viewer",
              ),
          ]),
                               resources=[name + '.icns', name + '.rsrc'],
                               iconfile=name + '.icns')))
def buildApp(trunkDir, releaseDir, version="DEV", appName="Numenta People Tracking Demo"):
  
  print "Building application..."
  print "trunkDir: %s" % trunkDir
  print "releaseDir: %s" % releaseDir

  # Special incantation to import py2app checked in to svn
  py2appdir = "external/darwin86/lib/python%s/site-packages-py2app" % pythonVersion
  py2appdir = os.path.join(trunkDir, py2appdir)
  import site
  site.addsitedir(py2appdir)

  # Make sure we get nupic and external packages from the right place. 
  sitePackagesDir = os.path.join(releaseDir, "lib/python%s/site-packages" %
                                 pythonVersion)
  sys.path.insert(0, sitePackagesDir)

  videoDir = os.path.join(releaseDir, "share", "projects", "video")
  origDir = os.getcwd()


  os.chdir(videoDir)
  if os.path.exists("dist"):
    print "Removing previous installation"
    shutil.rmtree("dist")

  src = os.path.join(sitePackagesDir, "PIL")
  dest = os.path.join(sitePackagesDir, "Image")
  if not os.path.exists(dest):
    print "Linking %s to %s" % (dest, src)
    os.symlink(src, dest)

  from setuptools import setup
  import py2app.recipes
  # the matplotlib recipe adds a bad dependency on pytz.zoneinfo
  del py2app.recipes.matplotlib

  assert(len(sys.argv) == 1)
  sys.argv.append("py2app")

  from plistlib import Plist
  licenseText = """
Copyright (C) 2009 Numenta Inc. All rights reserved.

This copy of the software is a development version
and is not authorized for any release or use outside of
the Numenta engineering team.
"""

  licenseFile = os.path.join(videoDir, "LICENSE")
  if os.path.exists(licenseFile):
    licenseText = open(licenseFile).read()

  # To appear properly in quicklook, 
  # license paragraph should be unwrapped. 
  # \n-><space>, but \n\n should remain unchanged
  licenseText = licenseText.replace("\n\n", "XXX")
  licenseText = licenseText.replace("\n", " ")
  licenseText = licenseText.replace("XXX", "\n\n")

  plistFile = os.path.join(videoDir, "Info.plist")
  if os.path.exists(plistFile):
    plist = Plist.fromFile(plistFile)
  else:
    print "File '%s' not found" % plistFile
    plist = dict()
  plist.update(dict(CFBundleVersion=version,
                    CFBundleShortVersionString=version,
                    CFBundleName=appName, 
                    NSHumanReadableCopyright=licenseText))



  print "Running setup..."
  setup(
    app=["RunPeopleTrackingDemo.pyw"], 
    setup_requires=["py2app"],
    options=dict(
      py2app=dict(
        includes=['csv', # needed by vitamind; not picked up by py2app
],
        # py2app will try to include these packages in site-packages.zip
        # but they don't work there. By listing them explicitly, they 
        # are installed as regular python packages
        packages=['nupic',  # problem finding image files in site-packages.zip
                  # TODO: other demo apps require matplotlib. 
                  # 'matplotlib', # problem finding data files in site-packages.zip
                  'curses',  # seg fault in site-packages.zip
                  'opencv',  # import error
                  # TODO: other demo apps require enthought
                  # 'enthought',
                  'wx',      # bus error when dragging files
                  'vitamind', # not found when in site-packages
                  ],  
        excludes=['matplotlib'], # not needed by PTD but found by py2app
        plist=plist,
        iconfile="demo.icns"
      )
    )
  )
  print "Done with base app creation"

  app = os.path.join(videoDir, "dist", "%s.app" % appName)

  appResources=os.path.join(app, "Contents/Resources")

  # A bunch of files are not copied by py2app because they aren't in 
  # python modules

  topLevelDirFilesToCopy = [".buildinfo"]
  for file in topLevelDirFilesToCopy:
    src = os.path.join(releaseDir, file)
    try:
      shutil.copy(src, appResources)
    except:
      print "%s not found" % src

  videoDirFilesToCopy = ["demo.ico", "LICENSE", "demo_license.cfg", "samples", "images", 
                          "PeopleTrackingCore.py", "PeopleTrackingDemo.py", 
                          "PeopleTrackingGui.py", "SamplesScrolledPanel.py"]
  for file in videoDirFilesToCopy:
    src = os.path.join(videoDir, file)
    try:
      if os.path.isdir(src):
        shutil.copytree(src, os.path.join(appResources, file))
      else:
        shutil.copy(src, appResources)
    except:
      print "%s not found" % src



  libDirFilesToCopy = ["libBasicPlugin.dylib", "libLearningPlugin.dylib", "ffmpeg"]
  # we are in share/examples/video
  srcLibDir = os.path.abspath("../../../lib")
  libDir = os.path.join(appResources, "lib")
  assert(os.path.exists(libDir))
  for f in libDirFilesToCopy:
    src = os.path.join(srcLibDir, f)
    if os.path.isdir(src):
      shutil.copytree(src, os.path.join(libDir, f))
    else:
      shutil.copy(src, libDir)
  
  # The About dialog gets its version string from a file called ".version"
  versionFile = os.path.join(appResources, ".version")
  assert not os.path.exists(versionFile)
  open(versionFile, "w").write(version)

  # We create a bin dir so that nupic can find its root directory, 
  # which it needs to find the libraries. 
  binDir = os.path.join(appResources, "bin")
  if not os.path.exists(binDir):
    os.mkdir(binDir)


  # Manual clean up of a bunch of stuff we don't need
  os.chdir(app)
  os.system("du -skh .")
  rc = os.system("find . -name \*.pyc -o -name \*.pyo| xargs rm")
  assert(rc == 0)
  rc = os.system("rm -rf Contents/Resources/lib/python%s/wx/tools" %
                 pythonVersion)
  assert(rc == 0)
  os.system("du -skh .")

  os.chdir(origDir)

  print "Created application in %s" % app
  return app
Example #29
0
def main(builder=None):
    if builder is None:
        builder = AppBuilder(verbosity=1)
    shortopts = "b:n:r:f:e:m:c:p:lx:i:hvqa"
    longopts = (
        "builddir=",
        "name=",
        "resource=",
        "file=",
        "executable=",
        "mainprogram=",
        "creator=",
        "nib=",
        "plist=",
        "link",
        "link-exec",
        "help",
        "verbose",
        "quiet",
        "argv",
        "standalone",
        "exclude=",
        "include=",
        "package=",
        "strip",
        "iconfile=",
        "lib=",
        "python=",
        "semi-standalone",
        "bundle-id=",
        "destroot=no-zipimport",
    )
    try:
        options, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
    except getopt.error:
        usage()

    for opt, arg in options:
        if opt in ("-b", "--builddir"):
            builder.builddir = arg
        elif opt in ("-n", "--name"):
            builder.name = arg
        elif opt in ("-r", "--resource"):
            builder.resources.append(os.path.normpath(arg))
        elif opt in ("-f", "--file"):
            srcdst = arg.split(":")
            if len(srcdst) != 2:
                usage("-f or --file argument must be two paths, separated by a colon")
            builder.files.append(srcdst)
        elif opt in ("-e", "--executable"):
            builder.executable = arg
        elif opt in ("-m", "--mainprogram"):
            builder.mainprogram = arg
        elif opt in ("-a", "--argv"):
            builder.argv_emulation = 1
        elif opt in ("-c", "--creator"):
            builder.creator = arg
        elif opt == "--bundle-id":
            builder.bundle_id = arg
        elif opt == "--iconfile":
            builder.iconfile = arg
        elif opt == "--lib":
            builder.libs.append(os.path.normpath(arg))
        elif opt == "--nib":
            builder.nibname = arg
        elif opt in ("-p", "--plist"):
            builder.plist = Plist.fromFile(arg)
        elif opt in ("-l", "--link"):
            builder.symlink = 1
        elif opt == "--link-exec":
            builder.symlink_exec = 1
        elif opt in ("-h", "--help"):
            usage()
        elif opt in ("-v", "--verbose"):
            builder.verbosity += 1
        elif opt in ("-q", "--quiet"):
            builder.verbosity -= 1
        elif opt == "--standalone":
            builder.standalone = 1
        elif opt == "--semi-standalone":
            builder.semi_standalone = 1
        elif opt == "--python":
            builder.python = arg
        elif opt in ("-x", "--exclude"):
            builder.excludeModules.append(arg)
        elif opt in ("-i", "--include"):
            builder.includeModules.append(arg)
        elif opt == "--package":
            builder.includePackages.append(arg)
        elif opt == "--strip":
            builder.strip = 1
        elif opt == "--destroot":
            builder.destroot = arg
        elif opt == "--no-zipimport":
            builder.use_zipimport = False

    if len(args) != 1:
        usage("Must specify one command ('build', 'report' or 'help')")
    command = args[0]
    if command == "build":
        builder.setup()
        builder.build()
    elif command == "report":
        builder.setup()
        builder.report()
    elif command == "help":
        usage()
    else:
        usage("Unknown command '%s'" % command)
    return
Example #30
0
def main(builder=None):
    if builder is None:
        builder = AppBuilder(verbosity=1)

    shortopts = "b:n:r:f:e:m:c:p:lx:i:hvqa"
    longopts = ("builddir=", "name=", "resource=", "file=", "executable=",
                "mainprogram=", "creator=", "nib=", "plist=", "link",
                "link-exec", "help", "verbose", "quiet", "argv", "standalone",
                "exclude=", "include=", "package=", "strip", "iconfile=",
                "lib=", "python=", "semi-standalone", "bundle-id=",
                "destroot=")

    try:
        options, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
    except getopt.error:
        usage()

    for opt, arg in options:
        if opt in ('-b', '--builddir'):
            builder.builddir = arg
        elif opt in ('-n', '--name'):
            builder.name = arg
        elif opt in ('-r', '--resource'):
            builder.resources.append(os.path.normpath(arg))
        elif opt in ('-f', '--file'):
            srcdst = arg.split(':')
            if len(srcdst) != 2:
                usage("-f or --file argument must be two paths, "
                      "separated by a colon")
            builder.files.append(srcdst)
        elif opt in ('-e', '--executable'):
            builder.executable = arg
        elif opt in ('-m', '--mainprogram'):
            builder.mainprogram = arg
        elif opt in ('-a', '--argv'):
            builder.argv_emulation = 1
        elif opt in ('-c', '--creator'):
            builder.creator = arg
        elif opt == '--bundle-id':
            builder.bundle_id = arg
        elif opt == '--iconfile':
            builder.iconfile = arg
        elif opt == "--lib":
            builder.libs.append(os.path.normpath(arg))
        elif opt == "--nib":
            builder.nibname = arg
        elif opt in ('-p', '--plist'):
            builder.plist = Plist.fromFile(arg)
        elif opt in ('-l', '--link'):
            builder.symlink = 1
        elif opt == '--link-exec':
            builder.symlink_exec = 1
        elif opt in ('-h', '--help'):
            usage()
        elif opt in ('-v', '--verbose'):
            builder.verbosity += 1
        elif opt in ('-q', '--quiet'):
            builder.verbosity -= 1
        elif opt == '--standalone':
            builder.standalone = 1
        elif opt == '--semi-standalone':
            builder.semi_standalone = 1
        elif opt == '--python':
            builder.python = arg
        elif opt in ('-x', '--exclude'):
            builder.excludeModules.append(arg)
        elif opt in ('-i', '--include'):
            builder.includeModules.append(arg)
        elif opt == '--package':
            builder.includePackages.append(arg)
        elif opt == '--strip':
            builder.strip = 1
        elif opt == '--destroot':
            builder.destroot = arg

    if len(args) != 1:
        usage("Must specify one command ('build', 'report' or 'help')")
    command = args[0]

    if command == "build":
        builder.setup()
        builder.build()
    elif command == "report":
        builder.setup()
        builder.report()
    elif command == "help":
        usage()
    else:
        usage("Unknown command '%s'" % command)
Example #31
0
    ("../Resources", [r"includes/alarmclock.eot"]),
    ("../Resources", [r"includes/alarmclock.svg"]),
    ("../Resources", [r"includes/alarmclock.ttf"]),
    ("../Resources", [r"includes/alarmclock.woff"]),
    ("../Resources", [r"includes/artisan.tpl"]),
    ("../Resources", [r"includes/bigtext.js"]),
    ("../Resources", [r"includes/sorttable.js"]),
    ("../Resources", [r"includes/report-template.htm"]),
    ("../Resources", [r"includes/roast-template.htm"]),
    ("../Resources", [r"includes/ranking-template.htm"]),
    ("../Resources", [r"includes/Humor-Sans.ttf"]),
    ("../Resources", [r"includes/jquery-1.11.1.min.js"]),
    ("../Resources", [r"includes/Machines"]),
  ]
  
plist = Plist.fromFile('Info.plist')
plist.update({ 'CFBundleDisplayName': 'Artisan',
                    'CFBundleGetInfoString': 'Artisan, Roast Logger',
                    'CFBundleIdentifier': 'com.google.code.p.Artisan',
                    'CFBundleShortVersionString': VERSION,
                    'CFBundleVersion': 'Artisan ' + VERSION,
                    'LSMinimumSystemVersion': '10.10',
                    'LSMultipleInstancesProhibited': 'false',
                    'LSPrefersPPC': False,
                    'LSArchitecturePriority': 'x86_64',
                    'NSHumanReadableCopyright': LICENSE,
                    'NSHighResolutionCapable': True,
                })
                
OPTIONS = {
    'strip':True,
def buildApp(trunkDir, releaseDir, version="DEV", appName="Numenta Vision4 Demo"):
  
  print "Building application..."
  print "trunkDir: %s" % trunkDir
  print "releaseDir: %s" % releaseDir

  # Special incantation to import py2app checked in to svn
  py2appdir = "external/darwin86/lib/python%s/site-packages-py2app" % \
              pythonVersion
  py2appdir = os.path.join(trunkDir, py2appdir)
  import site
  site.addsitedir(py2appdir)

  # Make sure we get nupic and external packages from the right place. 
  sitePackagesDir = os.path.join(releaseDir, "lib/python%s/site-packages" %
                                 pythonVersion)
  sys.path.insert(0, sitePackagesDir)

  visionDir = os.path.join(releaseDir, "share", "vision")
  origDir = os.getcwd()


  os.chdir(visionDir)
  if os.path.exists("dist"):
    print "Removing previous installation"
    shutil.rmtree("dist")

  src = os.path.join(sitePackagesDir, "PIL")
  dest = os.path.join(sitePackagesDir, "Image")
  if not os.path.exists(dest):
    print "Linking %s to %s" % (dest, src)
    os.symlink(src, dest)

  from setuptools import setup
  import py2app.recipes
  # the matplotlib recipe adds a bad dependency on pytz.zoneinfo
  del py2app.recipes.matplotlib

  assert(len(sys.argv) == 1)
  sys.argv.append("py2app")

  from plistlib import Plist
  licenseText = """
Copyright (C) 2009 Numenta Inc. All rights reserved.

This copy of the software is a development version
and is not authorized for any release or use outside of
the Numenta engineering team.
"""

  licenseFile = os.path.join(visionDir, "LICENSE")
  if os.path.exists(licenseFile):
    licenseText = open(licenseFile).read()

  # To appear properly in quicklook, 
  # license paragraph should be unwrapped. 
  # \n-><space>, but \n\n should remain unchanged
  licenseText = licenseText.replace("\n\n", "XXX")
  licenseText = licenseText.replace("\n", " ")
  licenseText = licenseText.replace("XXX", "\n\n")

  plistFile = os.path.join(visionDir, "Info.plist")
  if os.path.exists(plistFile):
    plist = Plist.fromFile(plistFile)
  else:
    print "File '%s' not found" % plistFile
    plist = dict()
  plist.update(dict(CFBundleVersion=version,
                    CFBundleShortVersionString=version,
                    CFBundleName=appName, 
                    NSHumanReadableCopyright=licenseText))



  print "Running setup..."
  setup(
    app=["RunDemo.py"], 
    setup_requires=["py2app"],
    # data_files=['networks/nta4.xml.gz', 'data/nta4_test'], -- doesn't create the subdirs
    options=dict(
      py2app=dict(
        includes=[],
        packages=['nupic',  # problem finding image files in site-packages.zip
                  'matplotlib', # problem finding data files in site-packages.zip
                  'curses',  # seg fault in site-packages.zip
                  'opencv',  # import error
                  'enthought',
                  'wx',      # bus error when dragging files
                  ],  
        plist=plist,
        iconfile="demo.icns"
      )
    )
  )
  print "Done with base app creation"

  app = os.path.join(visionDir, "dist", "%s.app" % appName)

  appResources=os.path.join(app, "Contents/Resources")

  networkDir = os.path.join(appResources, "networks")
  if not os.path.exists(networkDir):
    os.mkdir(networkDir)
  shutil.copy("networks/nta4.xml.gz", os.path.join(networkDir, "nta4.xml.gz"))

  # py2app doesn't copy the plugins, currently
  libDir = os.path.join(appResources, "lib")
  assert(os.path.exists(libDir))
  srcLibDir = os.path.abspath("../../lib")
  shutil.copy(os.path.join(srcLibDir, "libBasicPlugin.dylib"), libDir)
  shutil.copy(os.path.join(srcLibDir, "libLearningPlugin.dylib"), libDir)
  
  # # py2app doesn't find out about Demo.py. 
  # demoDest = os.path.join(appResources, "RunDemo.py")
  # if not os.path.exists(demoDest):
  #   shutil.copy("RunDemo.py", demoDest)
  # else:
  #   raise Exception("RunDemo.py not found")

  # Used by the about box
  if os.path.exists("demo.ico"):
    shutil.copy("demo.ico", os.path.join(appResources, "demo.ico"))
  else:
    print "Warning: file 'demo.ico' not found"


  # Used by the license checker and the about box
  if os.path.exists("LICENSE"):
    shutil.copy("LICENSE", os.path.join(appResources, "LICENSE"))
  else:
    print "Warning: file 'LICENSE' not found"

  # Also used by the about box
  versionFile = os.path.join(appResources, ".version")
  assert not os.path.exists(versionFile)
  open(versionFile, "w").write(version)

  # Used by help
  if os.path.exists("help.html"):
    shutil.copy("help.html", os.path.join(appResources, "help.html"))
  else:
    print "Warning: file help.html does not exist"


  # buildinfo not currently used by the about box but we put it
  # in for identification
  buildinfoFile = os.path.join(releaseDir, ".buildinfo")
  if os.path.exists(buildinfoFile):
    shutil.copy(buildinfoFile, os.path.join(appResources, ".buildinfo"))
  else:
    print "Warning: file '.buildinfo' not found"

  # We create a bin dir so that nupic can find its root directory, 
  # which it needs to find the libraries. 
  binDir = os.path.join(appResources, "bin")
  if not os.path.exists(binDir):
    os.mkdir(binDir)

  # extract test data if not already extracted
  if not os.path.exists("data/nta4_test"):
    os.chdir("data")
    rc = os.system("tar xzf nta4_test.tar.gz")
    if rc != 0:
      raise Exception("tar xzf nta4_test.tar.gz failed")
    os.chdir("..")

  # extract distractor data if not already extracted
  if not os.path.exists("data/distractors"):
    os.chdir("data")
    rc = os.system("tar xzf distractors.tar.gz")
    if rc != 0:
      raise Exception("tar xzf distractors.tar.gz failed")
    os.chdir("..")

  # Copy the license if it exists. This is not part of data_files in the setup
  # above because it may not exist if we're not installing from an official
  # demo release
  licenseFile = os.path.join(visionDir, "demo_license.cfg")
  if not os.path.exists(licenseFile):
    print "WARNING: demo license file %s does not exist -- skipping" % licenseFile
  else:
    shutil.copy(licenseFile, appResources)

  dataDir = os.path.join(appResources, "data")
  try:
    os.makedirs(dataDir)
  except:
    pass
  shutil.copytree("data/nta4_test", os.path.join(dataDir, "nta4_test"))
  shutil.copytree("data/distractors", os.path.join(dataDir, "distractors"))
  print "Done creating image"

  # Manual clean up of a bunch of stuff we don't need
  os.chdir(app)
  os.system("du -skh .")
  rc = os.system("find . -name \*.pyc -o -name \*.pyo| xargs rm")
  assert(rc == 0)
  rc = os.system("rm -rf Contents/Resources/lib/python%s/wx/tools" %
                 pythonVersion)
  assert(rc == 0)
  os.system("du -skh .")

  os.chdir(origDir)
  
  


  print "Created application in %s" % app
  return app
Example #33
0
# modules to include into bundle
includeModules=["encodings.hex_codec","encodings.utf_8","encodings.latin_1","xml.sax", "email.iterators"]

# ----- build the app bundle
mainfile = os.path.join(LIBRARYNAME,'Transport','SwarmEngine.py')

setup(
    setup_requires=['py2app'],
    name='SwarmPlayer',
    app=[mainfile],
    options={ 'py2app': {
        'argv_emulation': True,
        'includes': includeModules,
        'excludes': ["Tkinter","Tkconstants","tcl"],
        'iconfile': LIBRARYNAME+'/Player/Build/Mac/tribler.icns',
        'plist': Plist.fromFile(LIBRARYNAME+'/Transport/Build/Mac/Info.plist'),
        'resources':
            [LIBRARYNAME+"/readme.txt",
             LIBRARYNAME+"/Images/SwarmPlayerIcon.ico",
             LIBRARYNAME+"/Player/Build/Mac/TriblerDoc.icns",
           ]
        # add images
        + includedir( LIBRARYNAME+"/Images" )

        # add Web UI files
        + includedir( LIBRARYNAME+"/WebUI" )
    } }
)


Example #34
0
setup(
    setup_requires=['py2app'],
    name='SwarmPlayer',
    app=[mainfile],
    options={
        'py2app': {
            'argv_emulation':
            True,
            'includes':
            includeModules,
            'excludes': ["Tkinter", "Tkconstants", "tcl"],
            'iconfile':
            'Tribler/Player/Build/Mac/tribler.icns',
            'plist':
            Plist.fromFile('Tribler/Player/Build/Mac/Info.plist'),
            'optimize':
            2 * int(not __debug__),
            'resources': [
                ("Tribler/Lang", ["Tribler/Lang/english.lang"]),
                "Tribler/binary-LICENSE.txt",
                "Tribler/readme.txt",
                "Tribler/Images/swarmplayer.ico",
                "Tribler/Player/Build/Mac/TriblerDoc.icns",
            ]
            # add images
            + includedir("Tribler/Images")

            # add VLC plugins
            + includedir("macbinaries/vlc_plugins")
Example #35
0
                     'dest_base': "agent-manager",
                     'uac_info': "requireAdministrator", # The manager needs to be administrator to stop/start the service
                     'icon_resources': [(1, r"packaging\datadog-agent\win32\install_files\dd_agent_win_256.ico")],
                     }],
        'data_files': [
            ("Microsoft.VC90.CRT", glob(r'C:\Python27\redist\*.*')),
            ('jmxfetch', [r'checks\libs\%s' % JMX_FETCH_JAR_NAME]),
            ('gohai', [r'gohai\gohai.exe'])
        ],
    }

elif sys.platform == 'darwin':
    app_name = 'Datadog Agent'

    from plistlib import Plist
    plist = Plist.fromFile(os.path.dirname(os.path.realpath(__file__)) + '/packaging/Info.plist')
    plist.update(dict(
        CFBundleGetInfoString="{0}, Copyright (c) 2009-{1}, Datadog Inc.".format(
            get_version(), date.today().year),
        CFBundleVersion=get_version()
    ))

    extra_args = {
        'app': ['gui.py'],
        'data_files': [
            'images',
            'status.html',
        ],
        'options': {
            'py2app': {
                'optimize': 0,
Example #36
0
from Tribler.Main.vwxGUI.updateXRC import main as updateXRC

updateXRC( [os.path.abspath(os.path.dirname(sys.argv[0]))+"/vwxGUI"] )

# ----- build the app bundle

setup(
    setup_requires=['py2app'],
    name='Tribler',
    app=['tribler.py'],
    options={ 'py2app': {
        'argv_emulation': True,
        'includes': includeModules,
        'excludes': ["Tkinter","Tkconstants","tcl"],
        'iconfile': 'mac/tribler.icns',
        'plist': Plist.fromFile('mac/Info.plist'),
        'optimize': 2*int(not __debug__),
        'resources':
            [("Lang", ["Lang/english.lang"]),
             "superpeer.txt",
             "category.conf",
             "binary-LICENSE.txt", 
             "readme.txt",
             "tribler.ico",
             "torrenticon.ico",
             "mac/TriblerDoc.icns",
             ("lib", ["mac/build/lib/ffmpeg"],
           )]
           # add images
           + includedir( "icons" )
           + includedir( "Tribler/vwxGUI/images" )
Example #37
0
def write(dct, path):
    p = Plist()
    p.update(dct)
    p.write(path)
Example #38
0
class BundleBuilder(Defaults):
    """BundleBuilder is a barebones class for assembling bundles. It
    knows nothing about executables or icons, it only copies files
    and creates the PkgInfo and Info.plist files.
    """

    # (Note that Defaults.__init__ (deep)copies these values to
    # instance variables. Mutable defaults are therefore safe.)

    # Name of the bundle, with or without extension.
    name = None

    # The property list ("plist")
    plist = Plist(CFBundleDevelopmentRegion="English",
                  CFBundleInfoDictionaryVersion="6.0")

    # The type of the bundle.
    type = "BNDL"
    # The creator code of the bundle.
    creator = None

    # the CFBundleIdentifier (this is used for the preferences file name)
    bundle_id = None

    # List of files that have to be copied to <bundle>/Contents/Resources.
    resources = []

    # List of (src, dest) tuples; dest should be a path relative to the bundle
    # (eg. "Contents/Resources/MyStuff/SomeFile.ext).
    files = []

    # List of shared libraries (dylibs, Frameworks) to bundle with the app
    # will be placed in Contents/Frameworks
    libs = []

    # Directory where the bundle will be assembled.
    builddir = "build"

    # Make symlinks instead copying files. This is handy during debugging, but
    # makes the bundle non-distributable.
    symlink = 0

    # Verbosity level.
    verbosity = 1

    # Destination root directory
    destroot = ""

    def setup(self):
        # XXX rethink self.name munging, this is brittle.
        self.name, ext = os.path.splitext(self.name)
        if not ext:
            ext = ".bundle"
        bundleextension = ext
        # misc (derived) attributes
        self.bundlepath = pathjoin(self.builddir, self.name + bundleextension)

        plist = self.plist
        plist.CFBundleName = self.name
        plist.CFBundlePackageType = self.type
        if self.creator is None:
            if hasattr(plist, "CFBundleSignature"):
                self.creator = plist.CFBundleSignature
            else:
                self.creator = "????"
        plist.CFBundleSignature = self.creator
        if self.bundle_id:
            plist.CFBundleIdentifier = self.bundle_id
        elif not hasattr(plist, "CFBundleIdentifier"):
            plist.CFBundleIdentifier = self.name

    def build(self):
        """Build the bundle."""
        builddir = self.builddir
        if builddir and not os.path.exists(builddir):
            os.mkdir(builddir)
        self.message("Building %s" % repr(self.bundlepath), 1)
        if os.path.exists(self.bundlepath):
            shutil.rmtree(self.bundlepath)
        if os.path.exists(self.bundlepath + '~'):
            shutil.rmtree(self.bundlepath + '~')
        bp = self.bundlepath

        # Create the app bundle in a temporary location and then
        # rename the completed bundle. This way the Finder will
        # never see an incomplete bundle (where it might pick up
        # and cache the wrong meta data)
        self.bundlepath = bp + '~'
        try:
            os.mkdir(self.bundlepath)
            self.preProcess()
            self._copyFiles()
            self._addMetaFiles()
            self.postProcess()
            os.rename(self.bundlepath, bp)
        finally:
            self.bundlepath = bp
        self.message("Done.", 1)

    def preProcess(self):
        """Hook for subclasses."""
        pass

    def postProcess(self):
        """Hook for subclasses."""
        pass

    def _addMetaFiles(self):
        contents = pathjoin(self.bundlepath, "Contents")
        makedirs(contents)
        #
        # Write Contents/PkgInfo
        assert len(self.type) == len(self.creator) == 4, \
                "type and creator must be 4-byte strings."
        pkginfo = pathjoin(contents, "PkgInfo")
        f = open(pkginfo, "wb")
        f.write(self.type + self.creator)
        f.close()
        #
        # Write Contents/Info.plist
        infoplist = pathjoin(contents, "Info.plist")
        self.plist.write(infoplist)

    def _copyFiles(self):
        files = self.files[:]
        for path in self.resources:
            files.append(
                (path, pathjoin("Contents", "Resources",
                                os.path.basename(path))))
        for path in self.libs:
            files.append((path,
                          pathjoin("Contents", "Frameworks",
                                   os.path.basename(path))))
        if self.symlink:
            self.message("Making symbolic links", 1)
            msg = "Making symlink from"
        else:
            self.message("Copying files", 1)
            msg = "Copying"
        files.sort()
        for src, dst in files:
            if os.path.isdir(src):
                self.message("%s %s/ to %s/" % (msg, src, dst), 2)
            else:
                self.message("%s %s to %s" % (msg, src, dst), 2)
            dst = pathjoin(self.bundlepath, dst)
            if self.symlink:
                symlink(src, dst, mkdirs=1)
            else:
                copy(src, dst, mkdirs=1)

    def message(self, msg, level=0):
        if level <= self.verbosity:
            indent = ""
            if level > 1:
                indent = (level - 1) * "  "
            sys.stderr.write(indent + msg + "\n")

    def report(self):
        # XXX something decent
        pass
Example #39
0
def main(builder = None):
    if builder is None:
        builder = AppBuilder(verbosity=1)
    shortopts = 'b:n:r:f:e:m:c:p:lx:i:hvqa'
    longopts = ('builddir=', 'name=', 'resource=', 'file=', 'executable=', 'mainprogram=', 'creator=', 'nib=', 'plist=', 'link', 'link-exec', 'help', 'verbose', 'quiet', 'argv', 'standalone', 'exclude=', 'include=', 'package=', 'strip', 'iconfile=', 'lib=', 'python=', 'semi-standalone', 'bundle-id=', 'destroot=no-zipimport')
    try:
        options, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
    except getopt.error:
        usage()

    for opt, arg in options:
        if opt in ('-b', '--builddir'):
            builder.builddir = arg
        elif opt in ('-n', '--name'):
            builder.name = arg
        elif opt in ('-r', '--resource'):
            builder.resources.append(os.path.normpath(arg))
        elif opt in ('-f', '--file'):
            srcdst = arg.split(':')
            if len(srcdst) != 2:
                usage('-f or --file argument must be two paths, separated by a colon')
            builder.files.append(srcdst)
        elif opt in ('-e', '--executable'):
            builder.executable = arg
        elif opt in ('-m', '--mainprogram'):
            builder.mainprogram = arg
        elif opt in ('-a', '--argv'):
            builder.argv_emulation = 1
        elif opt in ('-c', '--creator'):
            builder.creator = arg
        elif opt == '--bundle-id':
            builder.bundle_id = arg
        elif opt == '--iconfile':
            builder.iconfile = arg
        elif opt == '--lib':
            builder.libs.append(os.path.normpath(arg))
        elif opt == '--nib':
            builder.nibname = arg
        elif opt in ('-p', '--plist'):
            builder.plist = Plist.fromFile(arg)
        elif opt in ('-l', '--link'):
            builder.symlink = 1
        elif opt == '--link-exec':
            builder.symlink_exec = 1
        elif opt in ('-h', '--help'):
            usage()
        elif opt in ('-v', '--verbose'):
            builder.verbosity += 1
        elif opt in ('-q', '--quiet'):
            builder.verbosity -= 1
        elif opt == '--standalone':
            builder.standalone = 1
        elif opt == '--semi-standalone':
            builder.semi_standalone = 1
        elif opt == '--python':
            builder.python = arg
        elif opt in ('-x', '--exclude'):
            builder.excludeModules.append(arg)
        elif opt in ('-i', '--include'):
            builder.includeModules.append(arg)
        elif opt == '--package':
            builder.includePackages.append(arg)
        elif opt == '--strip':
            builder.strip = 1
        elif opt == '--destroot':
            builder.destroot = arg
        elif opt == '--no-zipimport':
            builder.use_zipimport = False

    if len(args) != 1:
        usage("Must specify one command ('build', 'report' or 'help')")
    command = args[0]
    if command == 'build':
        builder.setup()
        builder.build()
    elif command == 'report':
        builder.setup()
        builder.report()
    elif command == 'help':
        usage()
    else:
        usage("Unknown command '%s'" % command)
    return
Example #40
0
    return [(x,y) for (x,y) in l if f(y[0])]

# ----- build the app bundle
mainfile = os.path.join(LIBRARYNAME,'Player','swarmplayer.py')

setup(
    setup_requires=['py2app'],
    name='SwarmPlayer',
    app=[mainfile],
    options={ 'py2app': {
        'argv_emulation': True,
        'includes': includeModules,
        'excludes': ["Tkinter","Tkconstants","tcl"],
        'iconfile': LIBRARYNAME+'/Player/Build/Mac/tribler.icns',
        'plist': Plist.fromFile(LIBRARYNAME+'/Player/Build/Mac/Info.plist'),
        'optimize': 2*int(not __debug__),
        'resources':
            [(LIBRARYNAME+"/Lang", [LIBRARYNAME+"/Lang/english.lang"]),
             LIBRARYNAME+"/binary-LICENSE.txt", 
             LIBRARYNAME+"/readme.txt",
             LIBRARYNAME+"/Images/SwarmPlayerIcon.ico",
             LIBRARYNAME+"/Player/Build/Mac/TriblerDoc.icns",
           ]
           # add images
           + includedir( LIBRARYNAME+"/Images" )

           # add VLC plugins
           + includedir( "macbinaries/vlc_plugins" )

           # add ffmpeg binary
Example #41
0
mainfile = os.path.join(LIBRARYNAME, 'Main', 'tribler.py')
setup(
    setup_requires=['py2app'],
    name='Tribler',
    app=[mainfile],
    options={
        'py2app': {
            'argv_emulation':
            True,
            'includes':
            includeModules,
            'excludes': ["Tkinter", "Tkconstants", "tcl"],
            'iconfile':
            LIBRARYNAME + '/Main/Build/Mac/tribler.icns',
            'plist':
            Plist.fromFile(LIBRARYNAME + '/Main/Build/Mac/Info.plist'),
            'optimize':
            0 if __debug__ else 2,
            'resources': [
                (LIBRARYNAME + "/Lang", [LIBRARYNAME + "/Lang/english.lang"]),
                (LIBRARYNAME + "/Category",
                 [LIBRARYNAME + "/Category/category.conf"]),
                (LIBRARYNAME + "/Core/Tag",
                 [LIBRARYNAME + "/Core/Tag/stop_snowball.filter"]),
                (LIBRARYNAME + "/Core/DecentralizedTracking/pymdht/core", [
                    LIBRARYNAME +
                    "/Core/DecentralizedTracking/pymdht/core/bootstrap.main"
                ]),
                (LIBRARYNAME + "/Core/DecentralizedTracking/pymdht/core", [
                    LIBRARYNAME +
                    "/Core/DecentralizedTracking/pymdht/core/bootstrap.backup"
Example #42
0
def main(builder=None):
    if builder is None:
        builder = AppBuilder(verbosity=1)

    shortopts = "b:n:r:f:e:m:c:p:lx:i:hvqa"
    longopts = ("builddir=", "name=", "resource=", "file=", "executable=",
        "mainprogram=", "creator=", "nib=", "plist=", "link",
        "link-exec", "help", "verbose", "quiet", "argv", "standalone",
        "exclude=", "include=", "package=", "strip", "iconfile=",
        "lib=", "python=", "semi-standalone", "bundle-id=", "destroot=")

    try:
        options, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
    except getopt.error:
        usage()

    for opt, arg in options:
        if opt in ('-b', '--builddir'):
            builder.builddir = arg
        elif opt in ('-n', '--name'):
            builder.name = arg
        elif opt in ('-r', '--resource'):
            builder.resources.append(os.path.normpath(arg))
        elif opt in ('-f', '--file'):
            srcdst = arg.split(':')
            if len(srcdst) != 2:
                usage("-f or --file argument must be two paths, "
                      "separated by a colon")
            builder.files.append(srcdst)
        elif opt in ('-e', '--executable'):
            builder.executable = arg
        elif opt in ('-m', '--mainprogram'):
            builder.mainprogram = arg
        elif opt in ('-a', '--argv'):
            builder.argv_emulation = 1
        elif opt in ('-c', '--creator'):
            builder.creator = arg
        elif opt == '--bundle-id':
            builder.bundle_id = arg
        elif opt == '--iconfile':
            builder.iconfile = arg
        elif opt == "--lib":
            builder.libs.append(os.path.normpath(arg))
        elif opt == "--nib":
            builder.nibname = arg
        elif opt in ('-p', '--plist'):
            builder.plist = Plist.fromFile(arg)
        elif opt in ('-l', '--link'):
            builder.symlink = 1
        elif opt == '--link-exec':
            builder.symlink_exec = 1
        elif opt in ('-h', '--help'):
            usage()
        elif opt in ('-v', '--verbose'):
            builder.verbosity += 1
        elif opt in ('-q', '--quiet'):
            builder.verbosity -= 1
        elif opt == '--standalone':
            builder.standalone = 1
        elif opt == '--semi-standalone':
            builder.semi_standalone = 1
        elif opt == '--python':
            builder.python = arg
        elif opt in ('-x', '--exclude'):
            builder.excludeModules.append(arg)
        elif opt in ('-i', '--include'):
            builder.includeModules.append(arg)
        elif opt == '--package':
            builder.includePackages.append(arg)
        elif opt == '--strip':
            builder.strip = 1
        elif opt == '--destroot':
            builder.destroot = arg

    if len(args) != 1:
        usage("Must specify one command ('build', 'report' or 'help')")
    command = args[0]

    if command == "build":
        builder.setup()
        builder.build()
    elif command == "report":
        builder.setup()
        builder.report()
    elif command == "help":
        usage()
    else:
        usage("Unknown command '%s'" % command)
Example #43
0
    def setup_general_page(self):
        page = gtk.VBox(False, 12)
        page.set_border_width(18)

        plist_path = self.project.get_plist_path()

        # FIXME: Should probably make it possible to do this in
        # project directly.
        project_dir, tail = os.path.split(self.project.get_project_path())
        print project_dir, plist_path
        p = re.compile("^\${project}")
        plist_path = p.sub(project_dir, plist_path)

        p = re.compile("^\${project}")
        plist_path = p.sub(project_dir, plist_path)

        print "a%sb" % (plist_path)

        plist = Plist.fromFile(plist_path)

        group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)

        hbox = gtk.HBox(False, 6)
        label = gtk.Label("Application Name:")
        label.set_alignment(1, 0.5)
        group.add_widget(label)
        hbox.pack_start(label, False, False, 0)
        entry = gtk.Entry()
        entry.set_text(plist.CFBundleExecutable)
        self.application_name_entry = entry
        hbox.pack_start(entry, True, True, 0)
        page.pack_start(hbox, False, False, 0)

        hbox = gtk.HBox(False, 6)
        label = gtk.Label("Prefix:")
        label.set_alignment(1, 0.5)
        group.add_widget(label)
        hbox.pack_start(label, False, False, 0)
        entry = gtk.Entry()
        entry.set_text(self.project.get_prefix())
        self.prefix_entry = entry
        hbox.pack_start(entry, True, True, 0)
        button = gtk.FileChooserButton("Choose Prefix")
        button.set_mode = gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER
        self.prefix_button = button
        hbox.pack_start(button, True, True, 0)
        page.pack_start(hbox, False, False, 0)

        hbox = gtk.HBox(False, 6)
        label = gtk.Label("Executable:")
        label.set_alignment(1, 0.5)
        group.add_widget(label)
        hbox.pack_start(label, False, False, 0)
        entry = gtk.Entry()
        entry.set_text(self.project.get_main_binary().source)
        self.executable_entry = entry
        hbox.pack_start(entry, True, True, 0)
        button = gtk.FileChooserButton("Choose Executable")
        self.executable_button = button
        hbox.pack_start(button, True, True, 0)
        page.pack_start(hbox, False, False, 0)

        self.general_page = page
        self.append_page(page, gtk.Label("General"))
def main():
    if not sys.argv[1:]:
        print HELP_TEXT
        return
    
    scripts = []
    data_files = []
    packages = []
    args = []
    plist = {}
    iconfile = None
    parsing_options = True
    next_is_option = False
    cmd_options = get_cmd_options()
    is_make_setup = False
    for fn in sys.argv[1:]:
        if parsing_options:
            if next_is_option:
                args.append(fn)
                next_is_option = False
                continue
            elif fn == '--make-setup':
                is_make_setup = True
                continue
            elif fn.startswith('-'):
                args.append(fn)
                if fn in cmd_options:
                    next_is_option = True
                continue
            parsing_options = False
        if not is_make_setup:
            fn = os.path.abspath(fn)
        if fn.endswith('.py'):
            if scripts:
                data_files.append(fn)
            else:
                scripts.append(fn)
        elif os.path.basename(fn) == 'Info.plist':
            plist = Plist.fromFile(fn)
        elif fn.endswith('.icns') and not iconfile:
            iconfile = os.path.abspath(fn)
        elif os.path.isdir(fn):
            sys.path.insert(0, [os.path.dirname(fn)])
            try:
                path = imp.find_module(os.path.basename(fn))[0]
            except ImportError:
                path = ''
            del sys.path[0]
            if os.path.realpath(path) == os.path.realpath(fn):
                packages.append(os.path.basename(fn))
            else:
                data_files.append(fn)
        else:
            data_files.append(fn)

    options = dict(
        packages=packages,
        plist=plist,
        iconfile=iconfile,
        argv_emulation=True,
    )
    for k,v in options.items():
        if not v:
            del options[k]
    if is_make_setup:
        make_setup(args, scripts, data_files, options)
    else:
        build(args, scripts, data_files, options)
Example #45
0
def main():
    if not sys.argv[1:]:
        print HELP_TEXT
        return
    
    scripts = []
    data_files = []
    packages = []
    args = []
    plist = {}
    iconfile = None
    parsing_options = True
    next_is_option = False
    cmd_options = get_cmd_options()
    is_make_setup = False
    for fn in sys.argv[1:]:
        if parsing_options:
            if next_is_option:
                args.append(fn)
                next_is_option = False
                continue
            elif fn == '--make-setup':
                is_make_setup = True
                continue
            elif fn.startswith('-'):
                args.append(fn)
                if fn in cmd_options:
                    next_is_option = True
                continue
            parsing_options = False
        if not is_make_setup:
            fn = os.path.abspath(fn)
        if fn.endswith('.py'):
            if scripts:
                data_files.append(fn)
            else:
                scripts.append(fn)
        elif os.path.basename(fn) == 'Info.plist':
            plist = Plist.fromFile(fn)
        elif fn.endswith('.icns') and not iconfile:
            iconfile = os.path.abspath(fn)
        elif os.path.isdir(fn):
            sys.path.insert(0, [os.path.dirname(fn)])
            try:
                path = imp.find_module(os.path.basename(fn))[0]
            except ImportError:
                path = ''
            del sys.path[0]
            if os.path.realpath(path) == os.path.realpath(fn):
                packages.append(os.path.basename(fn))
            else:
                data_files.append(fn)
        else:
            data_files.append(fn)

    options = dict(
        packages=packages,
        plist=plist,
        iconfile=iconfile,
        argv_emulation=True,
    )
    for k,v in options.items():
        if not v:
            del options[k]
    if is_make_setup:
        make_setup(args, scripts, data_files, options)
    else:
        build(args, scripts, data_files, options)
import sys

from lib.util import print_error
from lib.version import ELECTRUM_VERSION as version


name = "Electrum-XVG"
mainscript = 'electrum-xvg'

if sys.version_info[:3] < (2, 6, 0):
    print_error("Error: " + name + " requires Python version >= 2.6.0...")
    sys.exit(1)

if sys.platform == 'darwin':
    from plistlib import Plist
    plist = Plist.fromFile('Info.plist')
    plist.update(dict(CFBundleIconFile='electrum.icns'))

    shutil.copy(mainscript, mainscript + '.py')
    mainscript += '.py'
    extra_options = dict(
        setup_requires=['py2app'],
        app=[mainscript],
        options=dict(py2app=dict(argv_emulation=False,
                                 includes=['PyQt4.QtCore', 'PyQt4.QtGui', 'PyQt4.QtWebKit', 'PyQt4.QtNetwork', 'sip'],
                                 packages=['lib', 'gui', 'plugins'],
                                 iconfile='electrum.icns',
                                 plist=plist,
                                 resources=["icons"])),
    )
elif sys.platform == 'win32':
Example #47
0
    return [(x,y) for (x,y) in l if f(y[0])]

# ----- build the app bundle
mainfile = os.path.join(LIBRARYNAME,'Player','swarmplayer.py')

setup(
    setup_requires=['py2app'],
    name='SwarmPlayer',
    app=[mainfile],
    options={ 'py2app': {
        'argv_emulation': True,
        'includes': includeModules,
        'excludes': ["Tkinter","Tkconstants","tcl"],
        'iconfile': LIBRARYNAME+'/Player/Build/Mac/tribler.icns',
        'plist': Plist.fromFile(LIBRARYNAME+'/Player/Build/Mac/Info.plist'),
        'optimize': 2*int(not __debug__),
        'resources':
            [(LIBRARYNAME+"/Lang", [LIBRARYNAME+"/Lang/english.lang"]),
             LIBRARYNAME+"/binary-LICENSE.txt", 
             LIBRARYNAME+"/readme.txt",
             LIBRARYNAME+"/Images/SwarmPlayerIcon.ico",
             LIBRARYNAME+"/Player/Build/Mac/TriblerDoc.icns",
           ]
           # add images
           + includedir( LIBRARYNAME+"/Images" )

           # add VLC plugins
           + includedir( "vlc" )

           # add ffmpeg binary
    return [(x,y) for (x,y) in l if f(y[0])]

# ----- build the app bundle

mainfile = os.path.join(LIBRARYNAME,'Main','tribler.py')
setup(
    setup_requires=['py2app'],
    name='Tribler',
    app=[mainfile],
    options={ 'py2app': {
        'argv_emulation': True,
        'includes': includeModules,
        'excludes': ["Tkinter","Tkconstants","tcl"],
        'iconfile': LIBRARYNAME+'/Main/Build/Mac/tribler.icns',
        'plist': Plist.fromFile(LIBRARYNAME+'/Main/Build/Mac/Info.plist'),
        'optimize': 2*int(not __debug__),
        'resources':
            [(LIBRARYNAME+"/Lang", [LIBRARYNAME+"/Lang/english.lang"]),
             (LIBRARYNAME+"/Core", [LIBRARYNAME+"/Core/superpeer.txt"]),
             (LIBRARYNAME+"/Category", [LIBRARYNAME+"/Category/category.conf"]),
             (LIBRARYNAME+"/Core/Tag", [LIBRARYNAME+"/Core/Tag/stop_snowball.filter"]),
             LIBRARYNAME+"/readme.txt",
             LIBRARYNAME+"/Main/Build/Mac/TriblerDoc.icns",
           ]
           # add images
           + includedir( LIBRARYNAME+"/Images" )
           + includedir( LIBRARYNAME+"/Video/Images" )
           + includedir( LIBRARYNAME+"/Main/vwxGUI/images" )

           # add GUI elements
Example #49
0
def main(builder = None):
    if builder is None:
        builder = AppBuilder(verbosity=1)
    shortopts = 'b:n:r:f:e:m:c:p:lx:i:hvqa'
    longopts = ('builddir=', 'name=', 'resource=', 'file=', 'executable=', 'mainprogram=', 'creator=', 'nib=', 'plist=', 'link', 'link-exec', 'help', 'verbose', 'quiet', 'argv', 'standalone', 'exclude=', 'include=', 'package=', 'strip', 'iconfile=', 'lib=', 'python=', 'semi-standalone', 'bundle-id=', 'destroot=no-zipimport')
    try:
        options, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
    except getopt.error:
        usage()

    for opt, arg in options:
        if opt in ('-b', '--builddir'):
            builder.builddir = arg
        elif opt in ('-n', '--name'):
            builder.name = arg
        elif opt in ('-r', '--resource'):
            builder.resources.append(os.path.normpath(arg))
        elif opt in ('-f', '--file'):
            srcdst = arg.split(':')
            if len(srcdst) != 2:
                usage('-f or --file argument must be two paths, separated by a colon')
            builder.files.append(srcdst)
        elif opt in ('-e', '--executable'):
            builder.executable = arg
        elif opt in ('-m', '--mainprogram'):
            builder.mainprogram = arg
        elif opt in ('-a', '--argv'):
            builder.argv_emulation = 1
        elif opt in ('-c', '--creator'):
            builder.creator = arg
        elif opt == '--bundle-id':
            builder.bundle_id = arg
        elif opt == '--iconfile':
            builder.iconfile = arg
        elif opt == '--lib':
            builder.libs.append(os.path.normpath(arg))
        elif opt == '--nib':
            builder.nibname = arg
        elif opt in ('-p', '--plist'):
            builder.plist = Plist.fromFile(arg)
        elif opt in ('-l', '--link'):
            builder.symlink = 1
        elif opt == '--link-exec':
            builder.symlink_exec = 1
        elif opt in ('-h', '--help'):
            usage()
        elif opt in ('-v', '--verbose'):
            builder.verbosity += 1
        elif opt in ('-q', '--quiet'):
            builder.verbosity -= 1
        elif opt == '--standalone':
            builder.standalone = 1
        elif opt == '--semi-standalone':
            builder.semi_standalone = 1
        elif opt == '--python':
            builder.python = arg
        elif opt in ('-x', '--exclude'):
            builder.excludeModules.append(arg)
        elif opt in ('-i', '--include'):
            builder.includeModules.append(arg)
        elif opt == '--package':
            builder.includePackages.append(arg)
        elif opt == '--strip':
            builder.strip = 1
        elif opt == '--destroot':
            builder.destroot = arg
        elif opt == '--no-zipimport':
            builder.use_zipimport = False

    if len(args) != 1:
        usage("Must specify one command ('build', 'report' or 'help')")
    command = args[0]
    if command == 'build':
        builder.setup()
        builder.build()
    elif command == 'report':
        builder.setup()
        builder.report()
    elif command == 'help':
        usage()
    else:
        usage("Unknown command '%s'" % command)
    return
Example #50
0
def packageFromRecipe(targetDir, recipe):
    curdir = os.getcwd()
    try:
        # The major version (such as 2.5) is included in the package name
        # because having two version of python installed at the same time is
        # common.
        pkgname = '%s-%s' % (recipe['name'], getVersion())
        srcdir = recipe.get('source')
        pkgroot = recipe.get('topdir', srcdir)
        postflight = recipe.get('postflight')
        readme = textwrap.dedent(recipe['readme'])
        isRequired = recipe.get('required', True)

        print "- building package %s" % (pkgname, )

        # Substitute some variables
        textvars = dict(
            VER=getVersion(),
            FULLVER=getFullVersion(),
        )
        readme = readme % textvars

        if pkgroot is not None:
            pkgroot = pkgroot % textvars
        else:
            pkgroot = '/'

        if srcdir is not None:
            srcdir = os.path.join(WORKDIR, '_root', srcdir[1:])
            srcdir = srcdir % textvars

        if postflight is not None:
            postflight = os.path.abspath(postflight)

        packageContents = os.path.join(targetDir, pkgname + '.pkg', 'Contents')
        os.makedirs(packageContents)

        if srcdir is not None:
            os.chdir(srcdir)
            runCommand(
                "pax -wf %s . 2>&1" %
                (shellQuote(os.path.join(packageContents, 'Archive.pax')), ))
            runCommand(
                "gzip -9 %s 2>&1" %
                (shellQuote(os.path.join(packageContents, 'Archive.pax')), ))
            runCommand(
                "mkbom . %s 2>&1" %
                (shellQuote(os.path.join(packageContents, 'Archive.bom')), ))

        fn = os.path.join(packageContents, 'PkgInfo')
        fp = open(fn, 'w')
        fp.write('pmkrpkg1')
        fp.close()

        rsrcDir = os.path.join(packageContents, "Resources")
        os.mkdir(rsrcDir)
        fp = open(os.path.join(rsrcDir, 'ReadMe.txt'), 'w')
        fp.write(readme)
        fp.close()

        if postflight is not None:
            patchScript(postflight, os.path.join(rsrcDir, 'postflight'))

        vers = getFullVersion()
        major, minor = map(int, getVersion().split('.', 2))
        pl = Plist(
            CFBundleGetInfoString="Python.%s %s" % (
                pkgname,
                vers,
            ),
            CFBundleIdentifier='org.python.Python.%s' % (pkgname, ),
            CFBundleName='Python.%s' % (pkgname, ),
            CFBundleShortVersionString=vers,
            IFMajorVersion=major,
            IFMinorVersion=minor,
            IFPkgFormatVersion=0.10000000149011612,
            IFPkgFlagAllowBackRev=False,
            IFPkgFlagAuthorizationAction="RootAuthorization",
            IFPkgFlagDefaultLocation=pkgroot,
            IFPkgFlagFollowLinks=True,
            IFPkgFlagInstallFat=True,
            IFPkgFlagIsRequired=isRequired,
            IFPkgFlagOverwritePermissions=False,
            IFPkgFlagRelocatable=False,
            IFPkgFlagRestartAction="NoRestart",
            IFPkgFlagRootVolumeOnly=True,
            IFPkgFlagUpdateInstalledLangauges=False,
        )
        writePlist(pl, os.path.join(packageContents, 'Info.plist'))

        pl = Plist(
            IFPkgDescriptionDescription=readme,
            IFPkgDescriptionTitle=recipe.get('long_name',
                                             "Python.%s" % (pkgname, )),
            IFPkgDescriptionVersion=vers,
        )
        writePlist(
            pl, os.path.join(packageContents, 'Resources',
                             'Description.plist'))

    finally:
        os.chdir(curdir)
Example #51
0
class BundleBuilder(Defaults):
    """BundleBuilder is a barebones class for assembling bundles. It
    knows nothing about executables or icons, it only copies files
    and creates the PkgInfo and Info.plist files.
    """
    name = None
    plist = Plist(CFBundleDevelopmentRegion='English', CFBundleInfoDictionaryVersion='6.0')
    type = 'BNDL'
    creator = None
    bundle_id = None
    resources = []
    files = []
    libs = []
    builddir = 'build'
    symlink = 0
    verbosity = 1
    destroot = ''

    def setup(self):
        self.name, ext = os.path.splitext(self.name)
        if not ext:
            ext = '.bundle'
        bundleextension = ext
        self.bundlepath = pathjoin(self.builddir, self.name + bundleextension)
        plist = self.plist
        plist.CFBundleName = self.name
        plist.CFBundlePackageType = self.type
        if self.creator is None:
            if hasattr(plist, 'CFBundleSignature'):
                self.creator = plist.CFBundleSignature
            else:
                self.creator = '????'
        plist.CFBundleSignature = self.creator
        if self.bundle_id:
            plist.CFBundleIdentifier = self.bundle_id
        elif not hasattr(plist, 'CFBundleIdentifier'):
            plist.CFBundleIdentifier = self.name
        return

    def build(self):
        """Build the bundle."""
        builddir = self.builddir
        if builddir and not os.path.exists(builddir):
            os.mkdir(builddir)
        self.message('Building %s' % repr(self.bundlepath), 1)
        if os.path.exists(self.bundlepath):
            shutil.rmtree(self.bundlepath)
        if os.path.exists(self.bundlepath + '~'):
            shutil.rmtree(self.bundlepath + '~')
        bp = self.bundlepath
        self.bundlepath = bp + '~'
        try:
            os.mkdir(self.bundlepath)
            self.preProcess()
            self._copyFiles()
            self._addMetaFiles()
            self.postProcess()
            os.rename(self.bundlepath, bp)
        finally:
            self.bundlepath = bp

        self.message('Done.', 1)

    def preProcess(self):
        """Hook for subclasses."""
        pass

    def postProcess(self):
        """Hook for subclasses."""
        pass

    def _addMetaFiles(self):
        contents = pathjoin(self.bundlepath, 'Contents')
        makedirs(contents)
        raise len(self.type) == len(self.creator) == 4 or AssertionError('type and creator must be 4-byte strings.')
        pkginfo = pathjoin(contents, 'PkgInfo')
        f = open(pkginfo, 'wb')
        f.write(self.type + self.creator)
        f.close()
        infoplist = pathjoin(contents, 'Info.plist')
        self.plist.write(infoplist)

    def _copyFiles(self):
        files = self.files[:]
        for path in self.resources:
            files.append((path, pathjoin('Contents', 'Resources', os.path.basename(path))))

        for path in self.libs:
            files.append((path, pathjoin('Contents', 'Frameworks', os.path.basename(path))))

        if self.symlink:
            self.message('Making symbolic links', 1)
            msg = 'Making symlink from'
        else:
            self.message('Copying files', 1)
            msg = 'Copying'
        files.sort()
        for src, dst in files:
            if os.path.isdir(src):
                self.message('%s %s/ to %s/' % (msg, src, dst), 2)
            else:
                self.message('%s %s to %s' % (msg, src, dst), 2)
            dst = pathjoin(self.bundlepath, dst)
            if self.symlink:
                symlink(src, dst, mkdirs=1)
            else:
                copy(src, dst, mkdirs=1)

    def message(self, msg, level = 0):
        if level <= self.verbosity:
            indent = ''
            if level > 1:
                indent = (level - 1) * '  '
            sys.stderr.write(indent + msg + '\n')

    def report(self):
        pass
Example #52
0
                     'uac_info': "requireAdministrator", # The manager needs to be administrator to stop/start the service
                     'icon_resources': [(1, r"packaging\datadog-agent\win32\install_files\dd_agent_win_256.ico")],
                     }],
        'data_files': [
            ("Microsoft.VC90.CRT", glob(r'C:\Python27\redist\*.*')),
            ('jmxfetch', [r'checks\libs\%s' % JMX_FETCH_JAR_NAME]),
            ('gohai', [r'gohai\gohai.exe']),
            ('', [where()]),  # CA certificates bundled with `requests`
        ],
    }

elif sys.platform == 'darwin':
    app_name = 'Datadog Agent'

    from plistlib import Plist
    plist = Plist.fromFile(os.path.dirname(os.path.realpath(__file__)) + '/packaging/Info.plist')
    plist.update(dict(
        CFBundleGetInfoString="{0}, Copyright (c) 2009-{1}, Datadog Inc.".format(
            get_version(), date.today().year),
        CFBundleVersion=get_version()
    ))

    extra_args = {
        'app': ['gui.py'],
        'data_files': [
            'images',
            'status.html',
        ],
        'options': {
            'py2app': {
                'optimize': 0,
Example #53
0
s = "%s %sScripting.r -o %s.rsrc -useDF;" % (RezPath, name, name)
print s
os.system(s)

#######

setup(name=name,
      version=version,
      app=[name + '.py'],
      options={
          'py2app': {
              'plist':
              Plist(LSUIElement=int(hide),
                    NSAppleScriptEnabled=True,
                    CFBundleIdentifier=bundle,
                    CFBundleName=name,
                    CFBundleDisplayName=name,
                    CFBundleVersion=version,
                    CFBundleShortVersionString=version,
                    CFBundleSignature=creator,
                    CFBundlePackageType="APPL",
                    CFBundleIconFile=name + '.icns',
                    NSHumanReadableCopyright=shortCopyright,
                    CFBundleGetInfoString=longCopyright),
              'iconfile':
              './+icons/appicon.icns',
              'resources': [name + '.rsrc', './+icons/appicon.icns']
          }
      })
Example #54
0
# firmware file name
qd_include = QDir(os.path.dirname(os.path.realpath(__file__)) + "/includes/")
firmware_files = qd_include.entryInfoList(["tonino-*.hex"],QDir.Files | QDir.Readable,QDir.SortFlags(QDir.Name | QDir.Reversed))
tiny_firmware_files = qd_include.entryInfoList(["tinyTonino-*.hex"],QDir.Files | QDir.Readable,QDir.SortFlags(QDir.Name | QDir.Reversed))
if len(firmware_files) + len(tiny_firmware_files) > 0:
    if len(firmware_files) > 0:
        firmware_name = str(firmware_files[0].fileName())
        DATA_FILES = DATA_FILES + [("../Resources", [r"includes/" + firmware_name])]
    if len(tiny_firmware_files) > 0:
        tiny_firmware_name = str(tiny_firmware_files[0].fileName())
        DATA_FILES = DATA_FILES + [("../Resources", [r"includes/" + tiny_firmware_name])]
else:
    print("firmware *.hex missing!")
    quit()
  
plist = Plist.fromFile('conf/Info.plist')
plist.update({ 'CFBundleDisplayName': 'Tonino',
                    'CFBundleGetInfoString': 'Tonino, Roast Color Analyzer',
                    'CFBundleIdentifier': 'com.tonino',
                    'CFBundleShortVersionString': VERSION,
                    'CFBundleVersion': 'Tonino ' + VERSION,
                    'LSMinimumSystemVersion': '10.10',
                    'LSMultipleInstancesProhibited': 'false',
                    'LSPrefersPPC': False,
                    'LSArchitecturePriority': 'x86_64',
                    'NSHumanReadableCopyright': LICENSE,
                })
  
OPTIONS = {
    'strip':True,
    'argv_emulation': False,
Example #55
0
fullVersStr = __version__
shortVersStr = fullVersStr

inclModules = (
    #    "FileDialog",
)
# packages to include recursively
inclPackages = (
    #    "RO",
)

plist = Plist(
    CFBundleName=appName,
    CFBundleShortVersionString=shortVersStr,
    CFBundleGetInfoString="%s %s" % (appName, fullVersStr),
    CFBundleExecutable=appName,
    LSMinimumSystemVersion="10.6.0",
    LSArchitecturePriority=("i386", )  # force 32-bit mode;
    # this is needed for Tcl/TK 8.5.11 to run on MacOS X 10.9;
    # I'm stuck with 8.5.11 due to a crashing bug in Tcl/Tk 8.5.12 - 8.5.15.1
)

setup(
    app=[mainProg],
    setup_requires=["py2app"],
    options=dict(py2app=dict(
        plist=plist,
        # iconfile = iconFile,
        # includes = inclModules,
        # packages = inclPackages,
    )),
)
Example #56
0
# ----- build the app bundle
mainfile = os.path.join(LIBRARYNAME, 'Transport', 'SwarmEngine.py')

setup(
    setup_requires=['py2app'],
    name='SwarmPlayer',
    app=[mainfile],
    options={
        'py2app': {
            'argv_emulation':
            True,
            'includes':
            includeModules,
            'excludes': ["Tkinter", "Tkconstants", "tcl"],
            'iconfile':
            LIBRARYNAME + '/Player/Build/Mac/tribler.icns',
            'plist':
            Plist.fromFile(LIBRARYNAME + '/Transport/Build/Mac/Info.plist'),
            'resources': [
                LIBRARYNAME + "/readme.txt",
                LIBRARYNAME + "/Images/SwarmPlayerIcon.ico",
                LIBRARYNAME + "/Player/Build/Mac/TriblerDoc.icns",
            ]
            # add images
            + includedir(LIBRARYNAME + "/Images")

            # add Web UI files
            + includedir(LIBRARYNAME + "/WebUI")
        }
    })
Example #57
0
--

To build, cd to this directory and run:

	python setup.py py2app

"""

from distutils.core import setup, Extension
import py2app
from plistlib import Plist

version = '0.4.0'

setup(app=["ASTranslate.py"],
      data_files=["MainMenu.nib", "ASTranslateDocument.nib"],
      options=dict(py2app=dict(plist=Plist(
          NSAppleScriptEnabled=True,
          CFBundleIdentifier="net.sourceforge.appscript.astranslate",
          CFBundleVersion=version,
          CFBundleShortVersionString=version,
          NSHumanReadableCopyright="(C) 2007-2008 HAS",
          CFBundleDocumentTypes=[
              dict(CFBundleTypeExtensions=[],
                   CFBundleTypeName="Text File",
                   CFBundleTypeRole="Editor",
                   NSDocumentClass="ASTranslateDocument")
          ]),
                               resources=['ASTranslate.icns'],
                               iconfile='ASTranslate.icns')))