コード例 #1
0
 def writeToPlist(self):
     if self.lib_exists:
         libraryFile = open(self.filepath, 'rb+')
     else:
         libraryFile = open(self.filepath, 'wb')
     plistlib.dump(self.libraryData, libraryFile)
     libraryFile.close()
コード例 #2
0
ファイル: test_font.py プロジェクト: typesupply/defcon
 def test_delitem_glyph_dirty(self):
     for ufo in (u"TestExternalEditing.ufo", u"TestExternalEditing.ufoz"):
         path = getTestFontPath(ufo)
         path = makeTestFontCopy(path)
         font = Font(path)
         glyph = font["A"]
         glyph.dirty = True
         fileSystem = openTestFontAsFileSystem(path)
         glyphPath = fs.path.join("glyphs", "A_.glif")
         fileSystem.remove(glyphPath)
         contentsPath = fs.path.join("glyphs", "contents.plist")
         with fileSystem.open(contentsPath, "rb") as f:
             plist = load(f)
         del plist["A"]
         with fileSystem.open(contentsPath, "wb") as f:
             dump(plist, f)
         closeTestFontAsFileSystem(fileSystem, path)
         r = font.testForExternalChanges()
         self.assertEqual(r["deletedGlyphs"], ["A"])
         del font["A"]
         font.save()
         fileSystem = openTestFontAsFileSystem(path)
         self.assertFalse(fileSystem.exists(glyphPath))
         closeTestFontAsFileSystem(fileSystem, path)
         tearDownTestFontCopy(font.path)
コード例 #3
0
def customizeKeyBindingTemplate():
    # Key binding path
    path = "/Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Versions/A/Resources/IDETextKeyBindingSet.plist"

    # backup path
    backupPath = path.replace(
        os.path.basename(path), "IDETextKeyBindingSetBackup.plist")

    if not os.path.exists(backupPath):
        os.rename(path, backupPath)

    # add new key values
    f = open(backupPath, "rb")
    settings = plistlib.load(f)
    settings['customize'] = {
        "insert new line": "moveToEndOfLine:, insertNewline:",
        "delete line": "moveToEndOfLine:, deleteToBeginningOfLine:, deleteToEndOfParagraph:",
        "duplicate line": "selectLine:, copy:, moveToEndOfLine:, insertNewline:, paste:, deleteBackward:"

    }
    f.close()

    # write to file
    f2 = open(path, "wb+")
    plistlib.dump(settings, f2)
    f2.close()
コード例 #4
0
def writeCustomKeyBindingToXcode():
    ideKeyBindingPath = os.path.expanduser(
        "~/Library/Developer/Xcode/UserData/KeyBindings/Horidream.idekeybindings")
    # just like the object below
    customizedKeys = {'Menu Key Bindings': {'Key Bindings': [{'Action': 'execute:',
                                                              'Alternate': 'NO',
                                                              'CommandID': 'Xcode.IDEPlaygroundEditor.CmdDefinition.Execute',
                                                              'Group': 'Editor Menu for Playground',
                                                              'GroupID': 'Xcode.IDEPlaygroundEditor.MenuDefinition.Editor',
                                                              'GroupedAlternate': 'NO',
                                                              'Keyboard Shortcut': '~@p',
                                                              'Navigation': 'NO',
                                                              'Title': 'Execute Playground'}],
                                            'Version': 3},
                      'Text Key Bindings': {'Key Bindings': {"""$
""": ['moveToEndOfLine:',
                          'insertNewline:'],
                          '^$K': ['moveToEndOfLine:',
                                  'deleteToBeginningOfLine:',
                                  'deleteToEndOfParagraph:'],
                          '^~\uf701': ['selectLine:',
                                       'copy:',
                                       'moveToEndOfLine:',
                                       'insertNewline:',
                                       'paste:',
                                       'deleteBackward:']},
        'Version': 3}}
    with open(ideKeyBindingPath, "wb+") as f:
        plistlib.dump(customizedKeys, f)
コード例 #5
0
ファイル: __init__.py プロジェクト: lmregus/Portfolio
    def build_info_plist(self, contents_dir: str) -> None:
        """Construct the Info.plist file."""
        info_plist = {
            'CFBundleDevelopmentRegion': self.config.applehelp_dev_region,
            'CFBundleIdentifier': self.config.applehelp_bundle_id,
            'CFBundleInfoDictionaryVersion': '6.0',
            'CFBundlePackageType': 'BNDL',
            'CFBundleShortVersionString': self.config.release,
            'CFBundleSignature': 'hbwr',
            'CFBundleVersion': self.config.applehelp_bundle_version,
            'HPDBookAccessPath': '_access.html',
            'HPDBookIndexPath': 'search.helpindex',
            'HPDBookTitle': self.config.applehelp_title,
            'HPDBookType': '3',
            'HPDBookUsesExternalViewer': False,
        }

        if self.config.applehelp_icon is not None:
            info_plist['HPDBookIconPath'] = path.basename(self.config.applehelp_icon)

        if self.config.applehelp_kb_url is not None:
            info_plist['HPDBookKBProduct'] = self.config.applehelp_kb_product
            info_plist['HPDBookKBURL'] = self.config.applehelp_kb_url

        if self.config.applehelp_remote_url is not None:
            info_plist['HPDBookRemoteURL'] = self.config.applehelp_remote_url

        with open(path.join(contents_dir, 'Info.plist'), 'wb') as f:
            plistlib.dump(info_plist, f)
コード例 #6
0
def generatePlist(info_plist_root, app_title, ipd_url):
	"""
	根据读取到的Info.plist文件内容生成plist文件
	"""
	print(u"应用名 : %s" % info_plist_root["CFBundleDisplayName"])
	print(u"Bundle Id : %s" % info_plist_root["CFBundleIdentifier"])
	print(u"版本号 : %s" % info_plist_root["CFBundleShortVersionString"])
	print(u"应用标题 : %s" % app_title)
	print(u"ipa文件下载地址 : %s" % ipd_url)
	# 组装要生成的plist文件
	metadata_dict = {
		"bundle-identifier" : info_plist_root["CFBundleIdentifier"],
		"bundle-version" : info_plist_root["CFBundleShortVersionString"],
		"kind" : "software",
		"title" : app_title,
	}
	pl = dict (
		items = [
			dict(
				assets = [dict(kind = "software-package", url = ipd_url)],
				metadata = metadata_dict,
				)
		],
		)
	with open(info_plist_root["CFBundleDisplayName"] + ".plist", "wb") as fp:
		plistlib.dump(pl, fp)
コード例 #7
0
ファイル: __init__.py プロジェクト: faisalmemon/CaveJohnson
def set_plist_value_for_key(plistpath, value, key):
    data = load_plist(plistpath)
    data[key] = value
    print("Setting value `{}` for key `{}` in plist `{}`".format(value, key, plistpath))
    import plistlib
    with open(plistpath, "wb") as f:
        plistlib.dump(data, f)
コード例 #8
0
ファイル: convert.py プロジェクト: mansour2014/python-2
 def write(self, kind, extension):
     # If write comments-tmpreferences too
     comments = self._comments
     if comments:
         comment_name = 'Comments({})'.format(self._name) + PREF_EXT
         preference = generate_comments(self._scope, **comments)
     # Write work and/or test files to path(s)
     for definition, (file_path, file_name) in zip((self._definition, self._test_definition),
                                                   _combinator((self._path, self._test_path),
                                                               (self._file, self._test_file))):
         # Create dirs if they don't exist
         real_path = expanduser(file_path)
         makedirs(real_path, exist_ok=True)
         # Create full path to file
         full_path = join(real_path, file_name + extension)
         # Write out the property-list file
         with open(full_path, 'w+b') as file:
             plistlib.dump(definition, file)
             print('{} dictionary has been converted and placed:'.format(kind),
                   '\t{!r}'.format(full_path), sep='\n')
         if comments:
             full_path = join(real_path, comment_name)
             with open(full_path, 'w+b') as file:
                 plistlib.dump(preference, file)
                 print('Comments preference has been converted and placed:',
                       '\t{!r}'.format(full_path), sep='\n')
コード例 #9
0
ファイル: plist.py プロジェクト: benjamin99Tsai/taskr
 def __exit__(self, exc_type, exc_val, exc_tb):
     if 'w' in self.mode:
         with open(self.file_path, 'wb') as f:
             if six.PY3:
                 plistlib.dump(self.content_dict, f)
             else:
                 plistlib.writePlist(self.content_dict, f)
コード例 #10
0
ファイル: test_layerSet.py プロジェクト: typesupply/defcon
 def test_testForExternalChanges_change_layer_order(self):
     for ufo in (u"TestExternalEditing.ufo", u"TestExternalEditing.ufoz"):
         path = getTestFontPath(ufo)
         path = makeTestFontCopy(path)
         fileSystem = openTestFontAsFileSystem(path)
         fs.copy.copy_dir(fileSystem, "glyphs", fileSystem, "glyphs.test")
         with fileSystem.open(u"layercontents.plist", "rb") as f:
             contents = load(f)
         contents.append(("test", "glyphs.test"))
         with fileSystem.open(u"layercontents.plist", "wb") as f:
             dump(contents, f)
         closeTestFontAsFileSystem(fileSystem, path)
         font = Font(path)
         fileSystem = openTestFontAsFileSystem(path)
         with fileSystem.open(u"layercontents.plist", "rb") as f:
             contents = load(f)
         contents.reverse()
         with fileSystem.open(u"layercontents.plist", "wb") as f:
             dump(contents, f)
         closeTestFontAsFileSystem(fileSystem, path)
         reader = UFOReader(path)
         self.assertEqual(font.layers.testForExternalChanges(reader),
                          {"deleted": [], "added": [], "modified": {},
                           "defaultLayer": False, "order": True})
         tearDownTestFontCopy(font.path)
コード例 #11
0
ファイル: build_release.py プロジェクト: mehak/qutebrowser
def patch_mac_app():
    """Patch .app to use our Info.plist and save some space."""
    app_path = os.path.join('dist', 'qutebrowser.app')

    # Patch Info.plist - pyinstaller's options are too limiting
    plist_path = os.path.join(app_path, 'Contents', 'Info.plist')
    with open(plist_path, "rb") as f:
        plist_data = plistlib.load(f)
    plist_data.update(INFO_PLIST_UPDATES)
    with open(plist_path, "wb") as f:
        plistlib.dump(plist_data, f)

    # Replace some duplicate files by symlinks
    framework_path = os.path.join(app_path, 'Contents', 'Resources', 'PyQt5',
                                  'Qt', 'lib', 'QtWebEngineCore.framework')

    core_lib = os.path.join(framework_path, 'Versions', '5', 'QtWebEngineCore')
    os.remove(core_lib)
    core_target = os.path.join(*[os.pardir] * 7, 'MacOS', 'QtWebEngineCore')
    os.symlink(core_target, core_lib)

    framework_resource_path = os.path.join(framework_path, 'Resources')
    for name in os.listdir(framework_resource_path):
        file_path = os.path.join(framework_resource_path, name)
        target = os.path.join(*[os.pardir] * 5, name)
        if os.path.isdir(file_path):
            shutil.rmtree(file_path)
        else:
            os.remove(file_path)
        os.symlink(target, file_path)
コード例 #12
0
ファイル: test_layerSet.py プロジェクト: typesupply/defcon
 def test_testForExternalChanges_remove_a_layer(self):
     for ufo in (u"TestExternalEditing.ufo", u"TestExternalEditing.ufoz"):
         path = getTestFontPath(ufo)
         path = makeTestFontCopy(path)
         fileSystem = openTestFontAsFileSystem(path)
         fs.copy.copy_dir(fileSystem, "glyphs", fileSystem, "glyphs.test")
         with fileSystem.open(u"layercontents.plist", "rb") as f:
             contents = load(f)
         contents.append(("test", "glyphs.test"))
         with fileSystem.open(u"layercontents.plist", "wb") as f:
             dump(contents, f)
         closeTestFontAsFileSystem(fileSystem, path)
         font = Font(path)
         fileSystem = openTestFontAsFileSystem(path)
         fileSystem.removetree(u"glyphs.test")
         with fileSystem.open(u"layercontents.plist", "rb") as f:
             contents = load(f)
         del contents[-1]
         with fileSystem.open(u"layercontents.plist", "wb") as f:
             dump(contents, f)
         closeTestFontAsFileSystem(fileSystem, path)
         reader = UFOReader(path)
         self.assertEqual(font.layers.testForExternalChanges(reader)["deleted"],
                          ["test"])
         tearDownTestFontCopy(font.path)
コード例 #13
0
ファイル: osx_package.py プロジェクト: headmin/zentral
 def set_plist_keys(self, filename, keyvals):
     with open(filename, "rb") as f:
         pl = plistlib.load(f)
     for key, val in keyvals:
         pl[key] = val
     with open(filename, "wb") as f:
         plistlib.dump(pl, f)
コード例 #14
0
ファイル: ios.py プロジェクト: michaelsproul/softkbdgen
    def update_plist(self, plist, f):
        plist["CFBundleName"] = self._project.target("ios")["bundleName"]
        plist["CFBundleDisplayName"] = self._project.target("ios")["bundleName"]
        plist["CFBundleIdentifier"] = self._project.target("ios")["packageId"]
        plist["CFBundleShortVersionString"] = self._project.version
        plist["CFBundleVersion"] = self._project.build

        plistlib.dump(plist, f)
コード例 #15
0
ファイル: test_plistlib.py プロジェクト: GoMADAO/Lessa-PLT
 def test_bytesio(self):
     for fmt in ALL_FORMATS:
         with self.subTest(fmt=fmt):
             b = BytesIO()
             pl = self._create(fmt=fmt)
             plistlib.dump(pl, b, fmt=fmt)
             pl2 = plistlib.load(BytesIO(b.getvalue()))
             self.assertEqual(dict(pl), dict(pl2))
コード例 #16
0
    def update_plist(self, plist, f):
        plist['CFBundleName'] = self._project.target('ios')['bundleName']
        plist['CFBundleDisplayName'] = self._project.target('ios')['bundleName']
        plist['CFBundleIdentifier'] = self._project.target('ios')['packageId']
        plist['CFBundleShortVersionString'] = self._project.version
        plist['CFBundleVersion'] = self._project.build

        plistlib.dump(plist, f)
コード例 #17
0
ファイル: settings.py プロジェクト: lastsecondsave/sublemon
def settings(scope, **custom_settings):
    shell_variables = []
    comment_index = 1

    def add_comment(variant, value):
        name = 'TM_COMMENT_{}_{}'.format(variant, comment_index)
        shell_variables.append({'name': name, 'value': value})

    def add_start_comment(value):
        add_comment('START', value + ' ')

    def add_end_comment(value):
        add_comment('END', ' ' + value)

    line_comments = custom_settings.pop('line_comment', [])
    if not isinstance(line_comments, list):
        line_comments = [line_comments]

    for line_comment in line_comments:
        add_start_comment(line_comment)
        comment_index += 1

    if 'block_comment' in custom_settings:
        block_comment = custom_settings.pop('block_comment')
        add_start_comment(block_comment[0])
        add_end_comment(block_comment[1])

    sublime_settings = {}

    if shell_variables:
        sublime_settings['shellVariables'] = shell_variables

    to_uppercase_pattern = re.compile(r'_[a-z]')

    for k, v in custom_settings.items():
        k = to_uppercase_pattern.sub(lambda m: m.group(0)[1].upper(), k)

        if isinstance(v, list):
            if k in ['increaseIndentPattern',
                     'decreaseIndentPattern',
                     'bracketIndentNextLinePattern',
                     'disableIndentNextLinePattern',
                     'unIndentedLinePattern']:
                v = '|'.join(v)
            elif k == 'symbolTransformation':
                v = ';'.join(v) + ';'

        sublime_settings[k] = v

    path = os.path.join(TARGET_DIRECTORY, scope + '.tmPreferences')
    path = os.path.abspath(path)

    with open(path, "wb") as pfile:
        plistlib.dump({'scope': scope, 'settings': sublime_settings}, pfile)

    print('Generated', path)
コード例 #18
0
def update_plist_mac(state):
	if check_startup() != state:
		try:
			with open(MAC_PLIST_LOCATION,'rb') as f:
				plist_info = plistlib.load(f)
			plist_info['RunAtLoad'] = state
			with open(MAC_PLIST_LOCATION,'wb') as f:
				plistlib.dump(plist_info, f)
		except FileNotFoundError:
			create_plist_mac(state)
コード例 #19
0
ファイル: test_UFO1.py プロジェクト: bitforks/ufoLib
	def setUp(self):
		self.dstDir = tempfile.mktemp()
		os.mkdir(self.dstDir)
		metaInfo = {
			"creator": "test",
			"formatVersion": 1
		}
		path = os.path.join(self.dstDir, "metainfo.plist")
		with open(path, "wb") as f:
			dump(metaInfo, f)
コード例 #20
0
ファイル: ipa_processor.py プロジェクト: guozanhua/iparepack
 def process(self):
     self.launch_script(os.path.join(os.path.dirname(__file__), 'process_script.py'))
     
     if self.channelConfigDir:
         channelProcessScript = os.path.join(self.channelConfigDir, "process_script.py")
         if (os.path.isfile(channelProcessScript)):
             self.launch_script(channelProcessScript)
     
     infoplistfile = os.path.join(self.appdir, "Info.plist")
     plistlib.dump(self.infoPlist, open(infoplistfile, "wb"), fmt = plistlib.FMT_BINARY)
コード例 #21
0
ファイル: __init__.py プロジェクト: ywzw2013/CaveJohnson
def reSignIPA(new_mobileprovision_path, certificate_name, out_ipa_name, ipa_path=None):
    if not ipa_path:
        ipa_path = os.environ["XCS_OUTPUT_DIR"] + "/" + os.environ["XCS_PRODUCT"]

    import plistlib

    # extract from mobileprovision
    entitlements = subprocess.check_output(["security", "cms", "-D", "-i", new_mobileprovision_path])
    entitlements = plistlib.loads(entitlements)

    info_plist = load_plist_ipa(ipa_path)

    if not entitlements["Entitlements"]["application-identifier"].endswith(info_plist["CFBundleIdentifier"]):
        print(
            "Entitlements application-identifier %s doesn't match info_plist identifier %s"
            % (entitlements["Entitlements"]["application-identifier"], info_plist["CFBundleIdentifier"])
        )

    # todo: resign frameworks

    import tempfile
    import zipfile

    tempdir = tempfile.mkdtemp()
    zip_file = zipfile.ZipFile(ipa_path)
    zip_file.extractall(tempdir)
    warning("Working in", tempdir)

    # calculate appname
    import re

    not_app = list(filter(lambda x: re.match("Payload/.*.app/$", x), zip_file.namelist()))[
        0
    ]  # like 'Payload/MyiOSApp.app/'
    appname = re.match("Payload/(.*).app/$", not_app).groups()[0] + ".app"
    payload_path = tempdir + "/Payload"

    app_path = payload_path + "/" + appname

    import shutil

    shutil.copyfile(new_mobileprovision_path, app_path + "/embedded.mobileprovision")

    # write entitlements to tempfile
    with open(tempdir + "/entitlements.plist", "wb") as fp:
        plistlib.dump(entitlements["Entitlements"], fp)
    warning("codesign begin")
    subprocess.check_call(
        ["codesign", "--entitlements", tempdir + "/entitlements.plist", "-f", "-s", certificate_name, app_path]
    )
    warning("codesign end")

    zipdir(payload_path, out_ipa_name)
    shutil.rmtree(tempdir)
    warning("done signing")
コード例 #22
0
ファイル: builder.py プロジェクト: apfelwerk/zentral-1
 def include_tls_server_certs(self):
     tls_server_certs_rel_path = "usr/local/zentral/tls_server_certs.crt"
     # copy crt in build dir
     shutil.copy(self.tls_server_certs,
                 self.get_root_path(tls_server_certs_rel_path))
     # add command line option
     with open(self.launchd_plist, "rb") as f:
         pl = plistlib.load(f)
     pl["ProgramArguments"].append("--tls_server_certs=/{}".format(tls_server_certs_rel_path))
     with open(self.launchd_plist, "wb") as f:
         plistlib.dump(pl, f)
コード例 #23
0
def create_plist_mac(filename,state):
	params = filename.split('--')
	plist_filename = [params[0].strip('" ')]
	for item in params[1:]:
		plist_filename.append('--{}'.format(item))
	plist_info = {'ProgramArguments': plist_filename,
		'ProcessType': 'Interactive', 'Label': MAC_APP_LABEL,
		'KeepAlive': False, 'RunAtLoad': state}
	os.makedirs(os.path.split(MAC_PLIST_LOCATION)[0],exist_ok=True)
	with open(MAC_PLIST_LOCATION,'wb') as f:
		plistlib.dump(plist_info,f)
コード例 #24
0
ファイル: builder.py プロジェクト: arubdesu/zentral
 def include_tls_server_certs(self, config_plist, tls_server_certs):
     tls_server_certs_rel_path = "usr/local/zentral/tls_server_certs.crt"
     # copy crt in build dir
     shutil.copy(tls_server_certs,
                 self.get_root_path(tls_server_certs_rel_path))
     # add config key
     with open(config_plist, "rb") as f:
         pl = plistlib.load(f)
     pl["ServerAuthRootsFile"] = "/{}".format(tls_server_certs_rel_path)
     with open(config_plist, "wb") as f:
         plistlib.dump(pl, f)
コード例 #25
0
ファイル: base.py プロジェクト: getsiphon/siphon-cli
    def set_info(self, k, v):
        """
        Set a value for a given key in an app's base project info.plist
        """
        info = self.get_info()

        with open(self.info, 'wb') as f:
            # Note that we have to write the entire contents to the file.
            # so we load the current data, add whatever we need to it then
            info[k] = v
            plistlib.dump(info, f)
コード例 #26
0
 def _change_build_version(self):
     """ set CFBundleVersion and CFBundleShortVersionString.
     """
     build_version_list = self._build_version.split('.')
     cf_bundle_short_version_string = '.'.join(build_version_list[:3])
     with open(self._plist_path, 'rb') as fp:
         plist_content = plistlib.load(fp)
         plist_content['CFBundleShortVersionString'] = cf_bundle_short_version_string
         plist_content['CFBundleVersion'] = self._build_version
     with open(self._plist_path, 'wb') as fp:
         plistlib.dump(plist_content, fp)
コード例 #27
0
ファイル: sdt.py プロジェクト: unixorn/sdt
 def writePlist(self, plistPath):
     try:
         p = plistlib.readPlist(sysrecord.plistPath)
         p["ipaddress"] = attr_
         plistlib.writePlist(p, sysrecord.plistPath)
     except:
         print("Failured to write plist: ")
     infoPlist = dict(dhcp=dict(
         ipaddress = self.offerIP,
         dhcpserverip = self.DHCPServerIdentifier))
     with open(plistPath, 'wb') as fp:
         plistlib.dump(infoPlist, fp)
コード例 #28
0
ファイル: ios.py プロジェクト: michaelsproul/softkbdgen
    def update_kbd_plist(self, plist, layout, f):
        bundle_id = "%s.%s" % (self._project.target("ios")["packageId"], layout.internal_name.replace("_", "-"))

        plist["CFBundleName"] = layout.display_names["en"]
        plist["CFBundleDisplayName"] = layout.display_names["en"]
        plist["NSExtension"]["NSExtensionAttributes"]["PrimaryLanguage"] = layout.locale
        plist["NSExtension"]["NSExtensionPrincipalClass"] = "${PRODUCT_MODULE_NAME}.%s" % layout.internal_name
        plist["CFBundleIdentifier"] = bundle_id
        plist["CFBundleShortVersionString"] = self._project.version
        plist["CFBundleVersion"] = self._project.build

        plistlib.dump(plist, f)
コード例 #29
0
    def test_io(self):
        pl = self._create()
        with open(support.TESTFN, 'wb') as fp:
            plistlib.dump(pl, fp)

        with open(support.TESTFN, 'rb') as fp:
            pl2 = plistlib.load(fp)

        self.assertEqual(dict(pl), dict(pl2))

        self.assertRaises(AttributeError, plistlib.dump, pl, 'filename')
        self.assertRaises(AttributeError, plistlib.load, 'filename')
コード例 #30
0
def plist_dump_node(self, obj, node): # pylint: disable=unused-argument
    """Dump an object's plist representation to an output node.

    :param obj: object to dump
    :type obj: :class:`object`
    :param node: node to which to write the plist
    :type node: :class:`waflib.Node.Node`
    """
    with open(node.abspath(), 'wb') as out_file:
        plistlib.dump( # plistlib.dump is Python >= 3.4
            obj, out_file,
            sort_keys=False, # Keep our own order.
        )
コード例 #31
0
def write_plist(fname, plist):
    with open(fname, "wb") as f:
        plistlib.dump(plist, f)
コード例 #32
0
import plistlib
import os

# Expects the text file available at https://www2.census.gov/geo/docs/reference/state.txt
fips_path = os.getcwd() + "/state.txt"
dump_path = os.getcwd() + "/states.plist"
statesDict = {}

with open(fips_path, 'r') as file:
    _ = file.readline()

    for line in file:
        separated = line.split('|')

        stateCode = separated[0]
        if stateCode[0] == "0":
            stateCode = stateCode[1]

        statesDict[stateCode] = separated[2]

with open(dump_path, 'wb') as dump:
    plistlib.dump(statesDict, dump)
コード例 #33
0
ファイル: dock.py プロジェクト: CircleOnCircles/elite
def build(app_layout, other_layout, dock_plist_path=None, perform_normalise=True):
    if not dock_plist_path:
        dock_plist_path = get_dock_plist_path()

    if perform_normalise:
        app_layout, other_layout = normalise(app_layout, other_layout)

    # Store the plist contents
    with open(dock_plist_path, 'rb') as fp:
        dock_plist = plistlib.load(fp)

    # Please note that we must set _CFURLStringType to 0 (instead of the usual 15 value)
    # for items we want the Dock to setup correctly for us.  By setting this value to 0,
    # the Dock will take the data we've provided and rebuild the item in the correct format.

    persistent_apps = []
    for app_path in app_layout:
        app_label = os.path.basename(app_path)[:-4]
        persistent_apps.append({
            'GUID': generate_uuid(),
            'tile-data': {
                'file-data': {
                    '_CFURLString': app_path,
                    '_CFURLStringType': 0
                },
                'file-label': app_label
            },
            'tile-type': 'file-tile'
        })

    persistent_others = []
    for other in other_layout:
        # The current item is a directory
        if 'path' in other:
            other_path = other['path']
            other_label = os.path.basename(other['path'])

            persistent_others.append({
                'GUID': generate_uuid(),
                'tile-data': {
                    'file-data': {
                        '_CFURLString': other_path,
                        '_CFURLStringType': 0
                    },
                    'file-label': other_label,
                    'file-type': 2,
                    'arrangement': ARRANGEMENT_MAPPING.lookup(other['arrangement']),
                    'displayas': DISPLAY_AS_MAPPING.lookup(other['display_as']),
                    'showas': SHOW_AS_MAPPING.lookup(other['show_as'])
                },
                'tile-type': 'directory-tile'
            })

        # The current item is a URL
        else:
            persistent_others.append({
                'GUID': generate_uuid(),
                'tile-data': {
                    'label': other['label'],
                    'url': {
                        '_CFURLString': other['url'],
                        '_CFURLStringType': 15
                    }
                },
                'tile-type': 'url-tile'
            })

    dock_plist['persistent-apps'] = persistent_apps
    dock_plist['persistent-others'] = persistent_others

    # Update the Dock plist file with the new layout
    with open(dock_plist_path, 'wb') as fp:
        plistlib.dump(dock_plist, fp)
コード例 #34
0
    def build_helpbook(self):
        # type: () -> None
        contents_dir = path.join(self.bundle_path, 'Contents')
        resources_dir = path.join(contents_dir, 'Resources')
        language_dir = path.join(resources_dir,
                                 self.config.applehelp_locale + '.lproj')

        for d in [contents_dir, resources_dir, language_dir]:
            ensuredir(d)

        # Construct the Info.plist file
        toc = self.config.master_doc + self.out_suffix

        info_plist = {
            'CFBundleDevelopmentRegion': self.config.applehelp_dev_region,
            'CFBundleIdentifier': self.config.applehelp_bundle_id,
            'CFBundleInfoDictionaryVersion': '6.0',
            'CFBundlePackageType': 'BNDL',
            'CFBundleShortVersionString': self.config.release,
            'CFBundleSignature': 'hbwr',
            'CFBundleVersion': self.config.applehelp_bundle_version,
            'HPDBookAccessPath': '_access.html',
            'HPDBookIndexPath': 'search.helpindex',
            'HPDBookTitle': self.config.applehelp_title,
            'HPDBookType': '3',
            'HPDBookUsesExternalViewer': False,
        }

        if self.config.applehelp_icon is not None:
            info_plist['HPDBookIconPath'] \
                = path.basename(self.config.applehelp_icon)

        if self.config.applehelp_kb_url is not None:
            info_plist['HPDBookKBProduct'] = self.config.applehelp_kb_product
            info_plist['HPDBookKBURL'] = self.config.applehelp_kb_url

        if self.config.applehelp_remote_url is not None:
            info_plist['HPDBookRemoteURL'] = self.config.applehelp_remote_url

        logger.info(bold(__('writing Info.plist... ')), nonl=True)
        with open(path.join(contents_dir, 'Info.plist'), 'wb') as fb:
            plistlib.dump(info_plist, fb)
        logger.info(__('done'))

        # Copy the icon, if one is supplied
        if self.config.applehelp_icon:
            logger.info(bold(__('copying icon... ')), nonl=True)

            try:
                copyfile(path.join(self.srcdir, self.config.applehelp_icon),
                         path.join(resources_dir, info_plist['HPDBookIconPath']))

                logger.info(__('done'))
            except Exception as err:
                logger.warning(__('cannot copy icon file %r: %s'),
                               path.join(self.srcdir, self.config.applehelp_icon), err)
                del info_plist['HPDBookIconPath']

        # Build the access page
        logger.info(bold(__('building access page...')), nonl=True)
        with open(path.join(language_dir, '_access.html'), 'w') as ft:
            ft.write(access_page_template % {
                'toc': html.escape(toc, quote=True),
                'title': html.escape(self.config.applehelp_title)
            })
        logger.info(__('done'))

        # Generate the help index
        logger.info(bold(__('generating help index... ')), nonl=True)

        args = [
            self.config.applehelp_indexer_path,
            '-Cf',
            path.join(language_dir, 'search.helpindex'),
            language_dir
        ]

        if self.config.applehelp_index_anchors is not None:
            args.append('-a')

        if self.config.applehelp_min_term_length is not None:
            args += ['-m', '%s' % self.config.applehelp_min_term_length]

        if self.config.applehelp_stopwords is not None:
            args += ['-s', self.config.applehelp_stopwords]

        if self.config.applehelp_locale is not None:
            args += ['-l', self.config.applehelp_locale]

        if self.config.applehelp_disable_external_tools:
            logger.info(__('skipping'))

            logger.warning(__('you will need to index this help book with:\n  %s'),
                           ' '.join([pipes.quote(arg) for arg in args]))
        else:
            try:
                p = subprocess.Popen(args,
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.STDOUT)

                output = p.communicate()[0]

                if p.returncode != 0:
                    raise AppleHelpIndexerFailed(output)
                else:
                    logger.info(__('done'))
            except OSError:
                raise AppleHelpIndexerFailed(__('Command not found: %s') % args[0])

        # If we've been asked to, sign the bundle
        if self.config.applehelp_codesign_identity:
            logger.info(bold(__('signing help book... ')), nonl=True)

            args = [
                self.config.applehelp_codesign_path,
                '-s', self.config.applehelp_codesign_identity,
                '-f'
            ]

            args += self.config.applehelp_codesign_flags

            args.append(self.bundle_path)

            if self.config.applehelp_disable_external_tools:
                logger.info(__('skipping'))
                logger.warning(__('you will need to sign this help book with:\n  %s'),
                               ' '.join([pipes.quote(arg) for arg in args]))
            else:
                try:
                    p = subprocess.Popen(args,
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.STDOUT)

                    output = p.communicate()[0]

                    if p.returncode != 0:
                        raise AppleHelpCodeSigningFailed(output)
                    else:
                        logger.info(__('done'))
                except OSError:
                    raise AppleHelpCodeSigningFailed(__('Command not found: %s') % args[0])
コード例 #35
0
ファイル: setup.py プロジェクト: wygulmage/kitty
def package(args, for_bundle=False, sh_launcher=False):
    ddir = args.prefix
    if for_bundle or sh_launcher:
        args.libdir_name = 'lib'
    libdir = os.path.join(ddir, args.libdir_name.strip('/'), 'kitty')
    if os.path.exists(libdir):
        shutil.rmtree(libdir)
    os.makedirs(os.path.join(libdir, 'logo'))
    build_terminfo = runpy.run_path('build-terminfo', run_name='import_build')
    for x in (libdir, os.path.join(ddir, 'share')):
        odir = os.path.join(x, 'terminfo')
        safe_makedirs(odir)
        build_terminfo['compile_terminfo'](odir)
    shutil.copy2('__main__.py', libdir)
    shutil.copy2('logo/kitty.rgba', os.path.join(libdir, 'logo'))
    shutil.copy2('logo/kitty.png', os.path.join(libdir, 'logo'))
    shutil.copy2('logo/beam-cursor.png', os.path.join(libdir, 'logo'))
    shutil.copy2('logo/[email protected]', os.path.join(libdir, 'logo'))

    def src_ignore(parent, entries):
        return [
            x for x in entries
            if '.' in x and x.rpartition('.')[2] not in ('py', 'so', 'glsl')
        ]

    shutil.copytree('kitty', os.path.join(libdir, 'kitty'), ignore=src_ignore)
    shutil.copytree('kittens',
                    os.path.join(libdir, 'kittens'),
                    ignore=src_ignore)
    compile_python(libdir)
    for root, dirs, files in os.walk(libdir):
        for f in files:
            path = os.path.join(root, f)
            os.chmod(path, 0o755 if f.endswith('.so') else 0o644)
    shutil.copy2('kitty/launcher/kitty',
                 os.path.join(libdir, 'kitty', 'launcher'))
    launcher_dir = os.path.join(ddir, 'bin')
    safe_makedirs(launcher_dir)
    build_linux_launcher(args, launcher_dir, for_bundle, sh_launcher,
                         args.for_freeze)
    if not is_macos:  # {{{ linux desktop gunk
        copy_man_pages(ddir)
        copy_html_docs(ddir)
        icdir = os.path.join(ddir, 'share', 'icons', 'hicolor', '256x256',
                             'apps')
        safe_makedirs(icdir)
        shutil.copy2('logo/kitty.png', icdir)
        deskdir = os.path.join(ddir, 'share', 'applications')
        safe_makedirs(deskdir)
        with open(os.path.join(deskdir, 'kitty.desktop'), 'w') as f:
            f.write('''\
[Desktop Entry]
Version=1.0
Type=Application
Name=kitty
GenericName=Terminal emulator
Comment=A fast, feature full, GPU based terminal emulator
TryExec=kitty
Exec=kitty
Icon=kitty
Categories=System;TerminalEmulator;
''')
    # }}}

    if for_bundle or sh_launcher:  # macOS bundle gunk {{{
        import plistlib
        logo_dir = os.path.abspath(os.path.join('logo', appname + '.iconset'))
        os.chdir(ddir)
        os.mkdir('Contents')
        os.chdir('Contents')
        VERSION = '.'.join(map(str, version))
        pl = dict(
            CFBundleDevelopmentRegion='English',
            CFBundleDisplayName=appname,
            CFBundleName=appname,
            CFBundleIdentifier='net.kovidgoyal.' + appname,
            CFBundleVersion=VERSION,
            CFBundleShortVersionString=VERSION,
            CFBundlePackageType='APPL',
            CFBundleSignature='????',
            CFBundleExecutable=appname,
            LSMinimumSystemVersion='10.12.0',
            LSRequiresNativeExecution=True,
            NSAppleScriptEnabled=False,
            # Needed for dark mode in Mojave when linking against older SDKs
            NSRequiresAquaSystemAppearance='NO',
            NSHumanReadableCopyright=time.strftime(
                'Copyright %Y, Kovid Goyal'),
            CFBundleGetInfoString=
            'kitty, an OpenGL based terminal emulator https://sw.kovidgoyal.net/kitty',
            CFBundleIconFile=appname + '.icns',
            NSHighResolutionCapable=True,
            NSSupportsAutomaticGraphicsSwitching=True,
            LSApplicationCategoryType='public.app-category.utilities',
            LSEnvironment={'KITTY_LAUNCHED_BY_LAUNCH_SERVICES': '1'},
            NSServices=[
                {
                    'NSMenuItem': {
                        'default': 'New ' + appname + ' Tab Here'
                    },
                    'NSMessage': 'openTab',
                    'NSRequiredContext': {
                        'NSTextContent': 'FilePath'
                    },
                    'NSSendTypes':
                    ['NSFilenamesPboardType', 'public.plain-text'],
                },
                {
                    'NSMenuItem': {
                        'default': 'New ' + appname + ' Window Here'
                    },
                    'NSMessage': 'openOSWindow',
                    'NSRequiredContext': {
                        'NSTextContent': 'FilePath'
                    },
                    'NSSendTypes':
                    ['NSFilenamesPboardType', 'public.plain-text'],
                },
            ],
        )
        with open('Info.plist', 'wb') as fp:
            plistlib.dump(pl, fp)
        os.rename('../share', 'Resources')
        os.rename('../bin', 'MacOS')
        os.rename('../lib', 'Frameworks')
        if not os.path.exists(logo_dir):
            raise SystemExit(
                'The kitty logo has not been generated, you need to run logo/make.py'
            )
        subprocess.check_call([
            'iconutil', '-c', 'icns', logo_dir, '-o',
            os.path.join(
                'Resources',
                os.path.basename(logo_dir).partition('.')[0] + '.icns')
        ])
コード例 #36
0
ファイル: write_info_tag.py プロジェクト: Das701/Chastotomer
fname = sys.argv[1] + ".plist"

# The second argument is the key to replace
key = sys.argv[2]

# The third argument is the value of the key
val = sys.argv[3]

# Handle boolean values
if val.lower() == "true":
  val = True
elif val.lower() == "false":
  val = False


if sys.version_info >= (3, 4, 0):
  # Use the new API if python 3.4 is used
  with open( fname, 'rb' ) as plist_file:
    pl = plistlib.load( plist_file )

  pl[key] = val

  with open( fname, 'wb' ) as plist_file:
    pl = plistlib.dump( pl, plist_file )

else:
  # Use the old API otherwise (supports python 2.7 as well)
  pl = plistlib.readPlist( fname )
  pl[key] = val
  plistlib.writePlist( pl, fname )
コード例 #37
0
 def save(self):
     with open(self.file, 'wb') as f:
         plistlib.dump(self.plist, f)
コード例 #38
0
#!/usr/bin/env python3

import os
import plistlib

print("Writing Reposado Config...")

with open('/reposado/code/preferences.plist', 'rb') as f:
    plist = plistlib.loads(f.read())

for key in [e for e in os.environ if e.startswith('REPOSADO_')]:
    val = os.environ[key]
    pkey = key.replace('REPOSADO_', '')
    print("Applying {} = {}".format(pkey, val))
    plist[pkey] = val

with open('/reposado/code/preferences.plist', 'wb') as f:
    plistlib.dump(plist, f)
コード例 #39
0
ファイル: create_appbundle.py プロジェクト: mrclary/py2app
def create_appbundle(
    destdir: typing.Union[str, os.PathLike[str]],
    name: str,
    *,
    progress: progress.Progress,
    extension: str = ".app",
    platform: str = "MacOS",
    copy: typing.Callable[[str, str], None] = mergecopy,
    mergetree: typing.Callable[[
        str, str, typing.Callable[[str], bool], typing.Callable[[str, str],
                                                                None]
    ], None, ] = mergetree,
    condition: typing.Callable[[str], bool] = skipscm,
    plist: typing.Optional[typing.Dict[str, typing.Any]] = None,
    arch: typing.Optional[str] = None,
    use_old_sdk: bool = False,
    redirect_stdout: bool = False,
) -> typing.Tuple[str, typing.Dict[str, typing.Any]]:
    destpath = make_path(destdir)

    if plist is None:
        plist = {}

    kw = apptemplate.plist_template.infoPlistDict(
        plist.get("CFBundleExecutable", name), plist)
    app = destpath / (kw["CFBundleName"] + extension)
    if app.exists():
        # Remove any existing build artifacts to ensure that
        # we're getting a clean build
        shutil.rmtree(app)

    contents = app / "Contents"
    resources = contents / "Resources"
    platdir = contents / platform
    dirs = [contents, resources, platdir]
    plist = {}
    plist.update(kw)
    plistPath = contents / "Info.plist"
    for d in dirs:
        progress.trace(f"Create {d}")
        d.mkdir(parents=True, exist_ok=True)

    with open(plistPath, "wb") as stream:
        progress.trace(f"Write {plistPath}")
        plistlib.dump(plist, stream)

    srcmain = apptemplate.setup.main(arch=arch,
                                     redirect_asl=redirect_stdout,
                                     use_old_sdk=use_old_sdk)
    destmain = os.path.join(platdir, kw["CFBundleExecutable"])

    (contents / "PkgInfo").write_text(kw["CFBundlePackageType"] +
                                      kw["CFBundleSignature"])

    progress.trace(f"Copy {srcmain!r} -> {destmain!r}")
    copy(srcmain, destmain)
    make_exec(destmain)

    # XXX: Below here some pathlib.Path instances are converted
    # back to strings for compatibility with other code.
    # This will be changed when that legacy code has been updated.
    with importlib.resources.path(apptemplate.__name__, "lib") as p:
        mergetree(
            str(p),
            str(resources),
            condition,
            copy,
        )
    return str(app), plist
コード例 #40
0
def main():

    config = parse_config(projectpath)

    today = datetime.date.today()

    CFBundleGetInfoString = config['BUNDLE_NAME'] + " v" + config[
        'FULL_VER_STR'] + " " + config['PLUG_COPYRIGHT_STR']
    CFBundleVersion = config['FULL_VER_STR']

    print("update_version.py - setting version to " + config['FULL_VER_STR'])
    print("Updating plist version info...")

    plistpath = scriptpath + "/resources/IPlugInstrument-VST2-Info.plist"
    with open(plistpath, 'rb') as fp:
        vst2 = plistlib.load(fp)
    vst2['CFBundleGetInfoString'] = CFBundleGetInfoString
    vst2['CFBundleVersion'] = CFBundleVersion
    vst2['CFBundleShortVersionString'] = CFBundleVersion
    with open(plistpath, 'wb') as fp:
        plistlib.dump(vst2, fp)
    replacestrs(plistpath, "//Apple//", "//Apple Computer//")

    plistpath = scriptpath + "/resources/IPlugInstrument-AU-Info.plist"
    with open(plistpath, 'rb') as fp:
        au = plistlib.load(fp)
    au['CFBundleGetInfoString'] = CFBundleGetInfoString
    au['CFBundleVersion'] = CFBundleVersion
    au['CFBundleShortVersionString'] = CFBundleVersion
    with open(plistpath, 'wb') as fp:
        plistlib.dump(au, fp)
    replacestrs(plistpath, "//Apple//", "//Apple Computer//")

    plistpath = scriptpath + "/resources/IPlugInstrument-VST3-Info.plist"
    with open(plistpath, 'rb') as fp:
        vst3 = plistlib.load(fp)
    vst3['CFBundleGetInfoString'] = CFBundleGetInfoString
    vst3['CFBundleVersion'] = CFBundleVersion
    vst3['CFBundleShortVersionString'] = CFBundleVersion
    with open(plistpath, 'wb') as fp:
        plistlib.dump(vst3, fp)
    replacestrs(plistpath, "//Apple//", "//Apple Computer//")

    plistpath = scriptpath + "/resources/IPlugInstrument-macOS-Info.plist"
    with open(plistpath, 'rb') as fp:
        app = plistlib.load(fp)
    app['CFBundleGetInfoString'] = CFBundleGetInfoString
    app['CFBundleVersion'] = CFBundleVersion
    app['CFBundleShortVersionString'] = CFBundleVersion
    plistlib.writePlist(app, plistpath)
    replacestrs(plistpath, "//Apple//", "//Apple Computer//")

    plistpath = scriptpath + "/resources/IPlugInstrument-AAX-Info.plist"
    with open(plistpath, 'rb') as fp:
        aax = plistlib.load(fp)
    aax['CFBundleGetInfoString'] = CFBundleGetInfoString
    aax['CFBundleVersion'] = CFBundleVersion
    aax['CFBundleShortVersionString'] = CFBundleVersion
    with open(plistpath, 'wb') as fp:
        plistlib.dump(aax, fp)
    replacestrs(plistpath, "//Apple//", "//Apple Computer//")

    print("Updating Mac Installer version info...")

    plistpath = scriptpath + "/installer/IPlugInstrument.pkgproj"
    with open(plistpath, 'rb') as fp:
        installer = plistlib.load(fp)

    for x in range(0, 5):
        installer['PACKAGES'][x]['PACKAGE_SETTINGS']['VERSION'] = config[
            'FULL_VER_STR']

    with open(plistpath, 'wb') as fp:
        plistlib.dump(installer, fp)
    replacestrs(plistpath, "//Apple//", "//Apple Computer//")

    print("Updating Windows Installer version info...")

    for line in fileinput.input(scriptpath + "/installer/IPlugInstrument.iss",
                                inplace=1):
        if "AppVersion" in line:
            line = "AppVersion=" + config['FULL_VER_STR'] + "\n"
        sys.stdout.write(line)
コード例 #41
0
ファイル: pyinstaller_helper.py プロジェクト: zxc135781/urh
    urh_debug_cmd = cmd + [
        "--name=urh_debug", "--workpath", "./urh_debug_build",
        os.path.join(urh_path, "src/urh/main.py")
    ]

    cli_cmd = cmd + [
        "--workpath", "./urh_cli_build",
        os.path.join(urh_path, "src/urh/cli/urh_cli.py")
    ]

    os.makedirs("./pyinstaller")
    if sys.platform == "darwin":
        run_pyinstaller(
            urh_cmd, env=["DYLD_LIBRARY_PATH=src/urh/dev/native/lib/shared"])

        import plistlib
        with open("pyinstaller/urh.app/Contents/Info.plist", "rb") as f:
            p = plistlib.load(f)
        p["NSHighResolutionCapable"] = True
        with open("pyinstaller/urh.app/Contents/Info.plist", "wb") as f:
            plistlib.dump(p, f)

    else:
        for cmd in [urh_cmd, cli_cmd, urh_debug_cmd]:
            run_pyinstaller(cmd)

        shutil.copy("./pyinstaller/urh_cli/urh_cli.exe",
                    "./pyinstaller/urh/urh_cli.exe")
        shutil.copy("./pyinstaller/urh_debug/urh_debug.exe",
                    "./pyinstaller/urh/urh_debug.exe")
コード例 #42
0
ファイル: macos.py プロジェクト: KaasKop97/Tautulli
def set_startup():
    if plexpy.MAC_SYS_TRAY_ICON:
        plexpy.MAC_SYS_TRAY_ICON.change_tray_icons()

    if plexpy.INSTALL_TYPE == 'macos':
        if plexpy.CONFIG.LAUNCH_STARTUP:
            try:
                subprocess.Popen([
                    'osascript', '-e', 'tell application "System Events"',
                    '-e', 'get the name of every login item', '-e',
                    'if not exists login item "Tautulli" then '
                    'make login item at end with properties '
                    '{path:"/Applications/Tautulli.app", hidden:false}', '-e',
                    'end tell'
                ])
                logger.info("Added Tautulli to MacOS login items.")
                return True
            except OSError as e:
                logger.error("Failed to add Tautulli to MacOS login items: %s",
                             e)
                return False

        else:
            try:
                subprocess.Popen([
                    'osascript', '-e', 'tell application "System Events"',
                    '-e', 'get the name of every login item', '-e',
                    'if exists login item "Tautulli" then '
                    'delete login item "Tautulli"', '-e', 'end tell'
                ])
                logger.info("Removed Tautulli from MacOS login items.")
                return True
            except OSError as e:
                logger.error(
                    "Failed to remove Tautulli from MacOS login items: %s", e)
                return False

    else:
        launch_agents = os.path.join(os.path.expanduser('~'),
                                     'Library/LaunchAgents')
        plist_file = 'com.Tautulli.Tautulli.plist'
        plist_file_path = os.path.join(launch_agents, plist_file)

        exe = sys.executable
        if plexpy.FROZEN:
            args = [exe]
        else:
            args = [exe, plexpy.FULL_PATH]

        plist_dict = {
            'Label': common.PRODUCT,
            'ProgramArguments': args,
            'RunAtLoad': True
        }

        if plexpy.CONFIG.LAUNCH_STARTUP:
            if not os.path.exists(launch_agents):
                try:
                    os.makedirs(launch_agents)
                except OSError:
                    return False

            with open(plist_file_path, 'wb') as f:
                try:
                    plistlib.dump(plist_dict, f)
                except AttributeError:
                    plistlib.writePlist(plist_dict, f)
                except OSError as e:
                    logger.error(
                        "Failed to create MacOS system startup plist file: %s",
                        e)
                    return False

            logger.info(
                "Added Tautulli to MacOS system startup launch agents.")
            return True

        else:
            try:
                if os.path.isfile(plist_file_path):
                    os.remove(plist_file_path)
                    logger.info(
                        "Removed Tautulli from MacOS system startup launch agents."
                    )
                return True
            except OSError as e:
                logger.error(
                    "Failed to delete MacOS system startup plist file: %s", e)
                return False
コード例 #43
0
def plistWrite(obj, path):
    with open(path, 'wb') as f:
        return plistlib.dump(obj, f)
コード例 #44
0
ファイル: util.py プロジェクト: tandav/make_automator_app
def write_plist(value, path):
    with open(path, 'wb') as fd:
        plistlib.dump(value, fd)
コード例 #45
0
ファイル: tweak_info_plist.py プロジェクト: soitun/brave-core
def Main():
    parser = argparse.ArgumentParser(usage='%(prog)s [options]')
    parser.add_argument('--plist', dest='plist_path', action='store',
        required=True, help='The path of the plist to tweak.')
    parser.add_argument('--output', dest='plist_output', action='store',
        default=None, help='If specified, the path to output ' + \
        'the tweaked plist, rather than overwriting the input.')
    parser.add_argument('--brave_channel', dest='brave_channel', action='store',
        default=None, help='Channel (beta, dev, nightly)')
    parser.add_argument('--brave_product_dir_name', dest='brave_product_dir_name',
        action='store', default=None,
        help='Product directory name')
    parser.add_argument('--brave_eddsa_key', dest='brave_eddsa_key', action='store',
        default=None, help='Public EdDSA key for update')
    parser.add_argument('--brave_version', dest='brave_version', action='store',
        default=None, help='brave version string')
    parser.add_argument('--format', choices=('binary1', 'xml1', 'json'),
        default='xml1', help='Format to use when writing property list '
            '(default: %(default)s)')
    parser.add_argument('--skip_signing', dest='skip_signing', action='store_true')
    args = parser.parse_args()

    # Read the plist into its parsed format. Convert the file to 'xml1' as
    # plistlib only supports that format in Python 2.7.
    with tempfile.NamedTemporaryFile() as temp_info_plist:
        if sys.version_info.major == 2:
            retcode = _ConvertPlist(args.plist_path, temp_info_plist.name, 'xml1')
            if retcode != 0:
                return retcode
            plist = plistlib.readPlist(temp_info_plist.name)
        else:
            with open(args.plist_path, 'rb') as f:
                plist = plistlib.load(f)

    output_path = args.plist_path
    if args.plist_output is not None:
        output_path = args.plist_output

    if args.skip_signing and args.brave_channel != "":
        plist['KSChannelID'] = args.brave_channel
    elif 'KSChannelID' in plist:
        # 'KSChannelID' is set at _modify_plists() of modification.py only
        # during signing
        del plist['KSChannelID']

    plist['CrProductDirName'] = args.brave_product_dir_name

    if args.brave_eddsa_key:
        plist['SUPublicEDKey'] = args.brave_eddsa_key

    _OverrideVersionKey(plist, args.brave_version)

    # Explicitly disable profiling
    plist['SUEnableSystemProfiling'] = False

    # Now that all keys have been mutated, rewrite the file.
    # Convert Info.plist to the format requested by the --format flag. Any
    # format would work on Mac but iOS requires specific format.
    if sys.version_info.major == 2:
        with tempfile.NamedTemporaryFile() as temp_info_plist:
            plistlib.writePlist(plist, temp_info_plist.name)
            return _ConvertPlist(temp_info_plist.name, output_path, args.format)
    with open(output_path, 'wb') as f:
        plist_format = {'binary1': plistlib.FMT_BINARY, 'xml1': plistlib.FMT_XML}
        plistlib.dump(plist, f, fmt=plist_format[args.format])
コード例 #46
0
                "pygame",
                "wx",
                "sphinx",
                "jinja2",
            ]
        )
    )
)

# fix the icon
path = os.path.join(os.path.dirname(__file__), "dist", "%s.app" % appName, "Contents", "Info.plist")
with open(path, "rb") as f:
    appPlist = plistlib.load(f)
appPlist["CFBundleIconFile"] = iconFile
with open(path, "wb") as f:
    plistlib.dump(appPlist, f)


# get relevant paths
drawBotRoot = os.path.dirname(os.path.abspath(__file__))
distLocation = os.path.join(drawBotRoot, "dist")
appLocation = os.path.join(distLocation, "%s.app" % appName)
resourcesPath = os.path.join(appLocation, "Contents", "Resources")
imgLocation = os.path.join(distLocation, "img_%s" % appName)
existingDmgLocation = os.path.join(distLocation, "%s.dmg" % appName)
dmgLocation = os.path.join(distLocation, appName)
pythonVersion = "python%s.%i" % (sys.version_info[0], sys.version_info[1])
pythonLibPath = os.path.join(resourcesPath, "lib", pythonVersion)
appToolsRoot = os.path.join(drawBotRoot, "app")

コード例 #47
0
# Iterate
print(datetime.datetime.now().date())
for weightAbat in weightAbats:
	displayString = "\n{:s}  Evaluating wbat = {:f}".format(str(datetime.datetime.now().time()), weightAbat)
	print(displayString)
	print('-'*len(displayString), flush=True)

	# Erase any previous configuration file and create a new one from the template
	shutil.copyfile('config.template.plist', 'config.plist')

	# Set the triggerDelay in the configuration file
	with open('config.plist', 'rb') as configFileHandle:
		configFileDict = plistlib.load(configFileHandle, fmt=plistlib.FMT_XML)
		configFileDict['decision']['algorithm']['WeightedProductModel']['wbat'] = weightAbat
	with open('config.plist', 'wb') as configFileHandle:
		plistlib.dump(configFileDict, configFileHandle, fmt=plistlib.FMT_XML)

	# Run parallel simulations with 01parallelSimulate
	process = subprocess.Popen(['./01simulateParallel.py', '--overwrite'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

	# Show subprocess output
	for line in iter(process.stdout.readline, b''):
		sys.stdout.buffer.write(line)
		sys.stdout.flush()

	# Add details of the simulation set to the description
	descriptionFile = os.path.join(simulationDir, simulationDescription)
	subprocess.check_output("./descriptionGenerator.py -t {:s} -c config.plist >> {:s} ".format(descriptionTemplate, descriptionFile), shell=True)

	# Store simulation set and cleanup
	shutil.move(simulationDir, os.path.join(simulationSetDir, "{:s}_wbat_{:f}".format(simulationDir, weightAbat)))
コード例 #48
0
ファイル: plist_parser.py プロジェクト: tmsblgh/codechecker
def parse_plist_file(path, source_root=None, allow_plist_update=True):
    """
    Parse the reports from a plist file.
    One plist file can contain multiple reports.
    """
    LOG.debug("Parsing plist: %s", path)

    reports = []
    files = []
    try:
        plist = None
        with open(path, 'rb') as plist_file_obj:
            plist = parse_plist(plist_file_obj)

        if not plist:
            LOG.error("Failed to parse plist %s", path)
            return files, reports

        files = plist['files']

        diag_changed = False
        for diag in plist['diagnostics']:

            available_keys = list(diag.keys())

            main_section = {}
            for key in available_keys:
                # Skip path it is handled separately.
                if key != 'path':
                    main_section.update({key: diag[key]})

            # We need to extend information for plist files generated
            # by older clang version (before 3.7).
            main_section['check_name'] = get_checker_name(diag, path)

            # We need to extend information for plist files generated
            # by older clang version (before 3.8).
            file_path = files[diag['location']['file']]
            if source_root:
                file_path = os.path.join(source_root, file_path.lstrip('/'))

            report_hash = diag.get('issue_hash_content_of_line_in_context')

            if not report_hash:
                # Generate hash value if it is missing from the report.
                report_hash = get_report_hash(diag, file_path,
                                              HashType.PATH_SENSITIVE)

                main_section['issue_hash_content_of_line_in_context'] = \
                    report_hash

            if 'issue_hash_content_of_line_in_context' not in diag:
                # If the report hash was not in the plist, we set it in the
                # diagnostic section for later update.
                diag['issue_hash_content_of_line_in_context'] = report_hash
                diag_changed = True

            bug_path_items = [item for item in diag['path']]

            report = Report(main_section, bug_path_items, files)
            reports.append(report)

        if diag_changed and allow_plist_update:
            # If the diagnostic section has changed we update the plist file.
            # This way the client will always send a plist file where the
            # report hash field is filled.
            plistlib.dump(plist, path)
    except IndexError as iex:
        LOG.warning('Indexing error during processing plist file %s', path)
        LOG.warning(type(iex))
        LOG.warning(repr(iex))
        _, _, exc_traceback = sys.exc_info()
        traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
    except Exception as ex:
        LOG.warning('Error during processing reports from the plist file: %s',
                    path)
        traceback.print_exc()
        LOG.warning(type(ex))
        LOG.warning(ex)
    finally:
        return files, reports
コード例 #49
0
    def set_smbios(self):
        spoofed_model = self.model
        # TODO: Set check as global variable
        if self.model in ModelArray.MacBookAir61:
            print("- Spoofing to MacBookAir6,1")
            spoofed_model = "MacBookAir6,1"
            spoofed_board = "Mac-35C1E88140C3E6CF"
        elif self.model in ModelArray.MacBookAir62:
            print("- Spoofing to MacBookAir6,2")
            spoofed_model = "MacBookAir6,2"
            spoofed_board = "Mac-7DF21CB3ED6977E5"
        elif self.model in ModelArray.MacBookPro111:
            print("- Spoofing to MacBookPro11,1")
            spoofed_model = "MacBookPro11,1"
            spoofed_board = "Mac-189A3D4F975D5FFC"
        elif self.model in ModelArray.MacBookPro113:
            print("- Spoofing to MacBookPro11,3")
            spoofed_model = "MacBookPro11,3"
            spoofed_board = "Mac-2BD1B31983FE1663"
        elif self.model in ModelArray.Macmini71:
            print("- Spoofing to Macmini7,1")
            spoofed_model = "Macmini7,1"
            spoofed_board = "Mac-35C5E08120C7EEAF"
        elif self.model in ModelArray.iMacPro11:
            print("- Spoofing to iMacPro1,1")
            spoofed_model = "iMacPro1,1"
            spoofed_board = "Mac-7BA5B2D9E42DDD94"
        elif self.model in ModelArray.iMac151:
            # Check for upgraded GPUs on iMacs
            if self.constants.drm_support is True:
                print("- Spoofing to iMacPro1,1")
                spoofed_model = "iMacPro1,1"
                spoofed_board = "Mac-7BA5B2D9E42DDD94"
            else:
                print("- Spoofing to iMac15,1")
                spoofed_model = "iMac15,1"
                spoofed_board = "Mac-42FD25EABCABB274"
        elif self.model in ModelArray.iMac144:
            print("- Spoofing to iMac14,4")
            spoofed_model = "iMac14,4"
            spoofed_board = "Mac-81E3E92DD6088272"
        elif self.model in ModelArray.MacPro71:
            print("- Spoofing to MacPro7,1")
            spoofed_model = "MacPro7,1"
            spoofed_board = "Mac-27AD2F918AE68F61"
        self.spoofed_model = spoofed_model
        self.spoofed_board = spoofed_board
        self.config["#Revision"]["Spoofed-Model"] = self.spoofed_model

        # Setup menu
        def minimal_serial_patch(self):
            self.config["PlatformInfo"]["PlatformNVRAM"][
                "BID"] = self.spoofed_board
            self.config["PlatformInfo"]["SMBIOS"][
                "BoardProduct"] = self.spoofed_board
            self.config["PlatformInfo"]["UpdateNVRAM"] = True

        def moderate_serial_patch(self):
            self.config["PlatformInfo"]["Automatic"] = True
            self.config["PlatformInfo"]["UpdateDataHub"] = True
            self.config["PlatformInfo"]["UpdateNVRAM"] = True
            self.config["UEFI"]["ProtocolOverrides"]["DataHub"] = True
            self.config["PlatformInfo"]["Generic"][
                "SystemProductName"] = self.spoofed_model

        def adanced_serial_patch(self):
            macserial_output = subprocess.run(
                [self.constants.macserial_path] +
                f"-g -m {self.spoofed_model} -n 1".split(),
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT)
            macserial_output = macserial_output.stdout.decode().strip().split(
                " | ")
            self.config["PlatformInfo"]["Automatic"] = True
            self.config["PlatformInfo"]["UpdateDataHub"] = True
            self.config["PlatformInfo"]["UpdateNVRAM"] = True
            self.config["UEFI"]["ProtocolOverrides"]["DataHub"] = True
            self.config["PlatformInfo"]["Generic"]["ROM"] = binascii.unhexlify(
                "0016CB445566")
            self.config["PlatformInfo"]["Generic"][
                "SystemProductName"] = self.spoofed_model
            self.config["PlatformInfo"]["Generic"][
                "SystemSerialNumber"] = macserial_output[0]
            self.config["PlatformInfo"]["Generic"]["MLB"] = macserial_output[1]
            self.config["PlatformInfo"]["Generic"]["SystemUUID"] = str(
                uuid.uuid4()).upper()

        if self.constants.serial_settings == "Moderate":
            print("- Using Moderate SMBIOS patching")
            moderate_serial_patch(self)
        elif self.constants.serial_settings == "Advanced":
            print("- Using Advanced SMBIOS patching")
            adanced_serial_patch(self)
        else:
            print("- Using Minimal SMBIOS patching")
            self.spoofed_model = self.model
            minimal_serial_patch(self)

        # USB Map Patching
        new_map_ls = Path(
            self.constants.map_contents_folder) / Path("Info.plist")
        map_config = plistlib.load(Path(new_map_ls).open("rb"))

        for model_controller in ModelArray.ControllerTypes:
            model_patch = f"{self.model}{model_controller}"
            try:
                # Avoid erroring out when specific identity not found
                map_config["IOKitPersonalities_x86_64"][model_patch][
                    "model"] = self.spoofed_model
            except KeyError:
                continue

        plistlib.dump(map_config, Path(new_map_ls).open("wb"), sort_keys=True)

        if self.model == "MacBookPro9,1":
            new_agdp_ls = Path(
                self.constants.agdp_contents_folder) / Path("Info.plist")
            new_agpm_ls = Path(
                self.constants.agpm_contents_folder) / Path("Info.plist")
            new_amc_ls = Path(
                self.constants.amc_contents_folder) / Path("Info.plist")

            agdp_config = plistlib.load(Path(new_agdp_ls).open("rb"))
            agpm_config = plistlib.load(Path(new_agpm_ls).open("rb"))
            amc_config = plistlib.load(Path(new_amc_ls).open("rb"))

            agdp_config["IOKitPersonalities"]["AppleGraphicsDevicePolicy"][
                "ConfigMap"][
                    self.spoofed_board] = agdp_config["IOKitPersonalities"][
                        "AppleGraphicsDevicePolicy"]["ConfigMap"].pop(
                            self.model)
            agpm_config["IOKitPersonalities"]["AGPM"]["Machines"][
                self.spoofed_board] = agpm_config["IOKitPersonalities"][
                    "AGPM"]["Machines"].pop(self.model)
            amc_config["IOKitPersonalities"]["AppleMuxControl"]["ConfigMap"][
                self.spoofed_board] = amc_config["IOKitPersonalities"][
                    "AppleMuxControl"]["ConfigMap"].pop(self.model)

            plistlib.dump(agdp_config,
                          Path(new_agdp_ls).open("wb"),
                          sort_keys=True)
            plistlib.dump(agpm_config,
                          Path(new_agpm_ls).open("wb"),
                          sort_keys=True)
            plistlib.dump(amc_config,
                          Path(new_amc_ls).open("wb"),
                          sort_keys=True)

        if self.model in ["MacBookPro8,2", "MacBookPro8,3"]:
            print("- Disabling unsupported TeraScale 2 dGPU")
            self.config["NVRAM"]["Add"][
                "FA4CE28D-B62F-4C99-9CC3-6815686E30F9"][
                    "gpu-power-prefs"] = binascii.unhexlify("01000000")
            self.config["NVRAM"]["Delete"][
                "FA4CE28D-B62F-4C99-9CC3-6815686E30F9"] += ["gpu-power-prefs"]
            self.config["DeviceProperties"]["Add"][
                "PciRoot(0x0)/Pci(0x1,0x0)/Pci(0x0,0x0)"] = {
                    "name": binascii.unhexlify("23646973706C6179"),
                    "IOName": "#display",
                    "class-code": binascii.unhexlify("FFFFFFFF")
                }
コード例 #50
0
    def assemble(self):
        if _check_path_overlap(self.name) and os.path.isdir(self.name):
            _rmtree(self.name)
        logger.info("Building BUNDLE %s", self.tocbasename)

        # Create a minimal Mac bundle structure
        os.makedirs(os.path.join(self.name, "Contents", "MacOS"))
        os.makedirs(os.path.join(self.name, "Contents", "Resources"))
        os.makedirs(os.path.join(self.name, "Contents", "Frameworks"))

        # Copy icns icon to Resources directory.
        if os.path.exists(self.icon):
            shutil.copy(self.icon,
                        os.path.join(self.name, 'Contents', 'Resources'))
        else:
            logger.warning("icon not found %s", self.icon)

        # Key/values for a minimal Info.plist file
        info_plist_dict = {
            "CFBundleDisplayName": self.appname,
            "CFBundleName": self.appname,

            # Required by 'codesign' utility.
            # The value for CFBundleIdentifier is used as the default unique
            # name of your program for Code Signing purposes.
            # It even identifies the APP for access to restricted OS X areas
            # like Keychain.
            #
            # The identifier used for signing must be globally unique. The usal
            # form for this identifier is a hierarchical name in reverse DNS
            # notation, starting with the toplevel domain, followed by the
            # company name, followed by the department within the company, and
            # ending with the product name. Usually in the form:
            #   com.mycompany.department.appname
            # Cli option --osx-bundle-identifier sets this value.
            "CFBundleIdentifier": self.bundle_identifier,
            "CFBundleExecutable": os.path.basename(self.exename),
            "CFBundleIconFile": os.path.basename(self.icon),
            "CFBundleInfoDictionaryVersion": "6.0",
            "CFBundlePackageType": "APPL",
            "CFBundleShortVersionString": self.version,
        }

        # Set some default values.
        # But they still can be overwritten by the user.
        if self.console:
            # Setting EXE console=True implies LSBackgroundOnly=True.
            info_plist_dict['LSBackgroundOnly'] = True
        else:
            # Let's use high resolution by default.
            info_plist_dict['NSHighResolutionCapable'] = True

        # Merge info_plist settings from spec file
        if isinstance(self.info_plist, dict) and self.info_plist:
            info_plist_dict.update(self.info_plist)

        plist_filename = os.path.join(self.name, "Contents", "Info.plist")
        with open(plist_filename, "wb") as plist_fh:
            plistlib.dump(info_plist_dict, plist_fh)

        links = []
        _QT_BASE_PATH = {'PySide2', 'PySide6', 'PyQt5', 'PySide6'}
        for inm, fnm, typ in self.toc:
            # Adjust name for extensions, if applicable
            inm, fnm, typ = add_suffix_to_extension(inm, fnm, typ)
            # Copy files from cache. This ensures that are used files with relative
            # paths to dynamic library dependencies (@executable_path)
            base_path = inm.split('/', 1)[0]
            if typ in ('EXTENSION', 'BINARY'):
                fnm = checkCache(fnm,
                                 strip=self.strip,
                                 upx=self.upx,
                                 upx_exclude=self.upx_exclude,
                                 dist_nm=inm,
                                 target_arch=self.target_arch,
                                 codesign_identity=self.codesign_identity,
                                 entitlements_file=self.entitlements_file)
            # Add most data files to a list for symlinking later.
            if typ == 'DATA' and base_path not in _QT_BASE_PATH:
                links.append((inm, fnm))
            else:
                tofnm = os.path.join(self.name, "Contents", "MacOS", inm)
                todir = os.path.dirname(tofnm)
                if not os.path.exists(todir):
                    os.makedirs(todir)
                if os.path.isdir(fnm):
                    # beacuse shutil.copy2() is the default copy function
                    # for shutil.copytree, this will also copy file metadata
                    shutil.copytree(fnm, tofnm)
                else:
                    shutil.copy(fnm, tofnm)

        logger.info('Moving BUNDLE data files to Resource directory')

        # Mac OS X Code Signing does not work when .app bundle contains
        # data files in dir ./Contents/MacOS.
        #
        # Put all data files in ./Resources and create symlinks in ./MacOS.
        bin_dir = os.path.join(self.name, 'Contents', 'MacOS')
        res_dir = os.path.join(self.name, 'Contents', 'Resources')
        for inm, fnm in links:
            tofnm = os.path.join(res_dir, inm)
            todir = os.path.dirname(tofnm)
            if not os.path.exists(todir):
                os.makedirs(todir)
            if os.path.isdir(fnm):
                # beacuse shutil.copy2() is the default copy function
                # for shutil.copytree, this will also copy file metadata
                shutil.copytree(fnm, tofnm)
            else:
                shutil.copy(fnm, tofnm)
            base_path = os.path.split(inm)[0]
            if base_path:
                if not os.path.exists(os.path.join(bin_dir, inm)):
                    path = ''
                    for part in iter(base_path.split(os.path.sep)):
                        # Build path from previous path and the next part of the base path
                        path = os.path.join(path, part)
                        try:
                            relative_source_path = os.path.relpath(
                                os.path.join(res_dir, path),
                                os.path.split(os.path.join(bin_dir, path))[0])
                            dest_path = os.path.join(bin_dir, path)
                            os.symlink(relative_source_path, dest_path)
                            break
                        except FileExistsError:
                            pass
                    if not os.path.exists(os.path.join(bin_dir, inm)):
                        relative_source_path = os.path.relpath(
                            os.path.join(res_dir, inm),
                            os.path.split(os.path.join(bin_dir, inm))[0])
                        dest_path = os.path.join(bin_dir, inm)
                        os.symlink(relative_source_path, dest_path)
            else:  # If path is empty, e.g., a top level file, try to just symlink the file
                os.symlink(
                    os.path.relpath(
                        os.path.join(res_dir, inm),
                        os.path.split(os.path.join(bin_dir, inm))[0]),
                    os.path.join(bin_dir, inm))

        # Sign the bundle
        logger.info('Signing the BUNDLE...')
        try:
            osxutils.sign_binary(self.name,
                                 self.codesign_identity,
                                 self.entitlements_file,
                                 deep=True)
        except Exception as e:
            logger.warning("Error while signing the bundle: %s", e)
            logger.warning("You will need to sign the bundle manually!")

        logger.info("Building BUNDLE %s completed successfully.",
                    self.tocbasename)
コード例 #51
0
def main():
  config = parse_config(projectpath)
  xcconfig = parse_xcconfig(os.path.join(os.getcwd(), IPLUG2_ROOT +  '/common-mac.xcconfig'))

  CFBundleGetInfoString = config['BUNDLE_NAME'] + " v" + config['FULL_VER_STR'] + " " + config['PLUG_COPYRIGHT_STR']
  CFBundleVersion = config['FULL_VER_STR']
  CFBundlePackageType = "BNDL"
  CSResourcesFileMapped = True
  LSMinimumSystemVersion = xcconfig['DEPLOYMENT_TARGET']

  print("Copying resources ...")

  if config['PLUG_SHARED_RESOURCES']:
    dst = os.path.expanduser("~") + "/Music/" + config['BUNDLE_NAME'] + "/Resources"
  else:
    dst = os.environ["TARGET_BUILD_DIR"] + os.environ["UNLOCALIZED_RESOURCES_FOLDER_PATH"]

  if os.path.exists(dst) == False:
    os.makedirs(dst + "/", 0o0755 )

  if os.path.exists(projectpath + "/resources/img/"):
    imgs = os.listdir(projectpath + "/resources/img/")
    for img in imgs:
      print("copying " + img + " to " + dst)
      shutil.copy(projectpath + "/resources/img/" + img, dst)

  if os.path.exists(projectpath + "/resources/fonts/"):
    fonts = os.listdir(projectpath + "/resources/fonts/")
    for font in fonts:
      print("copying " + font + " to " + dst)
      shutil.copy(projectpath + "/resources/fonts/" + font, dst)

  print("Processing Info.plist files...")

# VST3

  plistpath = projectpath + "/resources/" + config['BUNDLE_NAME'] + "-VST3-Info.plist"
  with open(plistpath, 'rb') as fp:
    vst3 = plistlib.load(fp)
  vst3['CFBundleExecutable'] = config['BUNDLE_NAME']
  vst3['CFBundleGetInfoString'] = CFBundleGetInfoString
  vst3['CFBundleIdentifier'] = config['BUNDLE_DOMAIN'] + "." + config['BUNDLE_MFR'] + ".vst3." + config['BUNDLE_NAME'] + ""
  vst3['CFBundleName'] = config['BUNDLE_NAME']
  vst3['CFBundleVersion'] = CFBundleVersion
  vst3['CFBundleShortVersionString'] = CFBundleVersion
  vst3['LSMinimumSystemVersion'] = LSMinimumSystemVersion
  vst3['CFBundlePackageType'] = CFBundlePackageType
  vst3['CFBundleSignature'] = config['PLUG_UNIQUE_ID']
  vst3['CSResourcesFileMapped'] = CSResourcesFileMapped

  with open(plistpath, 'wb') as fp:
    plistlib.dump(vst3, fp)
# VST2

  plistpath = projectpath + "/resources/" + config['BUNDLE_NAME'] + "-VST2-Info.plist"
  with open(plistpath, 'rb') as fp:
    vst2 = plistlib.load(fp)
  vst2['CFBundleExecutable'] = config['BUNDLE_NAME']
  vst2['CFBundleGetInfoString'] = CFBundleGetInfoString
  vst2['CFBundleIdentifier'] = config['BUNDLE_DOMAIN'] + "." + config['BUNDLE_MFR'] + ".vst." + config['BUNDLE_NAME'] + ""
  vst2['CFBundleName'] = config['BUNDLE_NAME']
  vst2['CFBundleVersion'] = CFBundleVersion
  vst2['CFBundleShortVersionString'] = CFBundleVersion
  vst2['LSMinimumSystemVersion'] = LSMinimumSystemVersion
  vst2['CFBundlePackageType'] = CFBundlePackageType
  vst2['CFBundleSignature'] = config['PLUG_UNIQUE_ID']
  vst2['CSResourcesFileMapped'] = CSResourcesFileMapped

  with open(plistpath, 'wb') as fp:
    plistlib.dump(vst2, fp)
# AUDIOUNIT v2

  plistpath = projectpath + "/resources/" + config['BUNDLE_NAME'] + "-AU-Info.plist"
  with open(plistpath, 'rb') as fp:
    auv2 = plistlib.load(fp)
  auv2['CFBundleExecutable'] = config['BUNDLE_NAME']
  auv2['CFBundleGetInfoString'] = CFBundleGetInfoString
  auv2['CFBundleIdentifier'] = config['BUNDLE_DOMAIN'] + "." + config['BUNDLE_MFR'] + ".audiounit." + config['BUNDLE_NAME'] + ""
  auv2['CFBundleName'] = config['BUNDLE_NAME']
  auv2['CFBundleVersion'] = CFBundleVersion
  auv2['CFBundleShortVersionString'] = CFBundleVersion
  auv2['LSMinimumSystemVersion'] = LSMinimumSystemVersion
  auv2['CFBundlePackageType'] = CFBundlePackageType
  auv2['CFBundleSignature'] = config['PLUG_UNIQUE_ID']
  auv2['CSResourcesFileMapped'] = CSResourcesFileMapped

  if config['PLUG_TYPE'] == 0:
    if config['PLUG_DOES_MIDI_IN']:
      COMPONENT_TYPE = kAudioUnitType_MusicEffect
    else:
      COMPONENT_TYPE = kAudioUnitType_Effect
  elif config['PLUG_TYPE'] == 1:
    COMPONENT_TYPE = kAudioUnitType_MusicDevice
  elif config['PLUG_TYPE'] == 2:
    COMPONENT_TYPE = kAudioUnitType_MIDIProcessor

  auv2['AudioUnit Version'] = config['PLUG_VERSION_HEX']
  auv2['AudioComponents'] = [{}]
  auv2['AudioComponents'][0]['description'] = config['PLUG_NAME']
  auv2['AudioComponents'][0]['factoryFunction'] = config['AUV2_FACTORY']
  auv2['AudioComponents'][0]['manufacturer'] = config['PLUG_MFR_ID']
  auv2['AudioComponents'][0]['name'] = config['PLUG_MFR'] + ": " + config['PLUG_NAME']
  auv2['AudioComponents'][0]['subtype'] = config['PLUG_UNIQUE_ID']
  auv2['AudioComponents'][0]['type'] = COMPONENT_TYPE
  auv2['AudioComponents'][0]['version'] = config['PLUG_VERSION_INT']
  auv2['AudioComponents'][0]['sandboxSafe'] = True

  with open(plistpath, 'wb') as fp:
    plistlib.dump(auv2, fp)
# AUDIOUNIT v3

  if config['PLUG_HAS_UI']:
    NSEXTENSIONPOINTIDENTIFIER  = "com.apple.AudioUnit-UI"
  else:
    NSEXTENSIONPOINTIDENTIFIER  = "com.apple.AudioUnit"

  plistpath = projectpath + "/resources/" + config['BUNDLE_NAME'] + "-macOS-AUv3-Info.plist"
  with open(plistpath, 'rb') as fp:
    auv3 = plistlib.load(fp)
  auv3['CFBundleExecutable'] = config['BUNDLE_NAME']
  auv3['CFBundleGetInfoString'] = CFBundleGetInfoString
  auv3['CFBundleIdentifier'] = config['BUNDLE_DOMAIN'] + "." + config['BUNDLE_MFR'] + ".app." + config['BUNDLE_NAME'] + ".AUv3"
  auv3['CFBundleName'] = config['BUNDLE_NAME']
  auv3['CFBundleVersion'] = CFBundleVersion
  auv3['CFBundleShortVersionString'] = CFBundleVersion
  auv3['LSMinimumSystemVersion'] = "10.12.0"
  auv3['CFBundlePackageType'] = "XPC!"
  auv3['NSExtension'] = dict(
  NSExtensionAttributes = dict(
                               AudioComponentBundle = "com.AcmeInc.app." + config['BUNDLE_NAME'] + ".AUv3Framework",
                               AudioComponents = [{}]),
#                               NSExtensionServiceRoleType = "NSExtensionServiceRoleTypeEditor",
  NSExtensionPointIdentifier = NSEXTENSIONPOINTIDENTIFIER,
  NSExtensionPrincipalClass = "IPlugAUViewController_vIPlugCocoaUI"
                             )
  auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'] = [{}]
  auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0]['description'] = config['PLUG_NAME']
  auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0]['manufacturer'] = config['PLUG_MFR_ID']
  auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0]['name'] = config['PLUG_MFR'] + ": " + config['PLUG_NAME']
  auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0]['subtype'] = config['PLUG_UNIQUE_ID']
  auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0]['type'] = COMPONENT_TYPE
  auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0]['version'] = config['PLUG_VERSION_INT']
  auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0]['sandboxSafe'] = True
  auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0]['tags'] = [{}]

  if config['PLUG_TYPE'] == 1:
    auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0]['tags'][0] = "Synth"
  else:
    auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0]['tags'][0] = "Effects"

  with open(plistpath, 'wb') as fp:
    plistlib.dump(auv3, fp)
# AAX

  plistpath = projectpath + "/resources/" + config['BUNDLE_NAME'] + "-AAX-Info.plist"
  with open(plistpath, 'rb') as fp:
    aax = plistlib.load(fp)
  aax['CFBundleExecutable'] = config['BUNDLE_NAME']
  aax['CFBundleGetInfoString'] = CFBundleGetInfoString
  aax['CFBundleIdentifier'] = config['BUNDLE_DOMAIN'] + "." + config['BUNDLE_MFR'] + ".aax." + config['BUNDLE_NAME'] + ""
  aax['CFBundleName'] = config['BUNDLE_NAME']
  aax['CFBundleVersion'] = CFBundleVersion
  aax['CFBundleShortVersionString'] = CFBundleVersion
  aax['LSMinimumSystemVersion'] = LSMinimumSystemVersion
  aax['CSResourcesFileMapped'] = CSResourcesFileMapped

  with open(plistpath, 'wb') as fp:
    plistlib.dump(aax, fp)
# APP

  plistpath = projectpath + "/resources/" + config['BUNDLE_NAME'] + "-macOS-Info.plist"
  with open(plistpath, 'rb') as fp:
    macOSapp = plistlib.load(fp)
  macOSapp['CFBundleExecutable'] = config['BUNDLE_NAME']
  macOSapp['CFBundleGetInfoString'] = CFBundleGetInfoString
  macOSapp['CFBundleIdentifier'] = config['BUNDLE_DOMAIN'] + "." + config['BUNDLE_MFR'] + ".app." + config['BUNDLE_NAME'] + ""
  macOSapp['CFBundleName'] = config['BUNDLE_NAME']
  macOSapp['CFBundleVersion'] = CFBundleVersion
  macOSapp['CFBundleShortVersionString'] = CFBundleVersion
  macOSapp['LSMinimumSystemVersion'] = LSMinimumSystemVersion
  macOSapp['CFBundlePackageType'] = CFBundlePackageType
  macOSapp['CFBundleSignature'] = config['PLUG_UNIQUE_ID']
  macOSapp['CSResourcesFileMapped'] = CSResourcesFileMapped
  macOSapp['NSPrincipalClass'] = "SWELLApplication"
  macOSapp['NSMainNibFile'] = config['BUNDLE_NAME'] + "-macOS-MainMenu"
  macOSapp['LSApplicationCategoryType'] = "public.app-category.music"
  macOSapp['CFBundleIconFile'] = config['BUNDLE_NAME'] + ".icns"
  macOSapp['NSMicrophoneUsageDescription'] = 	"This app needs mic access to process audio."

  with open(plistpath, 'wb') as fp:
    plistlib.dump(macOSapp, fp)
コード例 #52
0
ファイル: genpkgproj.py プロジェクト: djsperka/habit2-src
# If pkg file name provided, use it. If not, create one.
pkgName = "habit-installer"
if argsdict['pkg_file_basename'] is not None:
    pkgName = argsdict['pkg_file_basename']
    if isVerbose:
        print('pkg_file_basename: ', argsdict['pkg_file_basename'])
    set_pkg_file_basename(pl, argsdict['pkg_file_basename'])
else:
    if isVerbose:
        print('Warning: using default package name=', pkgName)

# display title for installer
displayTitle = "Habit"
if argsdict['display_title'] is not None:
    displayTitle = argsdict['display_title']
    if isVerbose:
        print('display_title: ', argsdict['display_title'])
else:
    if isVerbose:
        print('Warning: using default display title=', displayTitle)
set_display_title(pl, displayTitle)

# Set DIST-VERSION, STIM-VERSION
# TODO: Assert presence, or rely on parser?
# I rely on parser now

set_versions(pl, argsdict['dist_version'], argsdict['stim_version'])

with open(argsdict['output'], 'wb') as fpout:
    plistlib.dump(pl, fpout)
コード例 #53
0
def plist_write(output_path, data):
    with open(output_path, "wb") as fp:
        if hasattr(plistlib, "dump"):
            plistlib.dump(data, fp)
        else:
            plistlib.writePlist(data, fp)
コード例 #54
0
version_from_file = get_version()  # vX.X.X
version = version_from_file[1:]  # X.X.X

# Read Info.plist into a plist object
try:
    # Python 3
    with open(args.info_plist[0], 'rb') as fp:
        plist = plistlib.load(fp)
except AttributeError:
    # Python 2
    plist = plistlib.readPlist(args.info_plist[0])

# Change version number
plist['CFBundleShortVersionString'] = version

# Add copyright string
plist['NSHumanReadableCopyright'] = u"Copyright © 2021  Jonathan Gagne"

# Enable retina display resolution
plist['NSHighResolutionCapable'] = True

# Write the modified plist back to the Info.plist file
if hasattr(plistlib, 'dump'):
    # Python 3
    plist['NSRequiresAquaSystemAppearance'] = True  # DISABLE dark mode
    with open(args.info_plist[0], 'wb') as fp:
        plistlib.dump(plist, fp)
else:
    # Python 2
    plistlib.writePlist(plist, args.info_plist[0])
コード例 #55
0
 def save(self, path: pathlib.Path):
     with path.open('wb') as fd:
         plistlib.dump(self.dict(), fd)
コード例 #56
0
ファイル: main.py プロジェクト: sycomix/unicron
 def _savePrefs(self, sender):
     with open(self.prefsFolder + self.prefsFile, 'wb') as fp:
         plistlib.dump(self.prefs, fp)
コード例 #57
0
def main():
  if(len(sys.argv) == 2):
     if(sys.argv[1] == "app"):
       print("Copying resources ...")
     
       dst = os.environ["TARGET_BUILD_DIR"] + "/" + os.environ["UNLOCALIZED_RESOURCES_FOLDER_PATH"]
          
       if os.path.exists(projectpath + "/resources/img/"):
         imgs = os.listdir(projectpath + "/resources/img/")
         for img in imgs:
           print("copying " + img + " to " + dst)
           shutil.copy(projectpath + "/resources/img/" + img, dst)
     
       if os.path.exists(projectpath + "/resources/fonts/"):
         fonts = os.listdir(projectpath + "/resources/fonts/")
         for font in fonts:
           print("copying " + font + " to " + dst)
           shutil.copy(projectpath + "/resources/fonts/" + font, dst)
           
  config = parse_config(projectpath)
  xcconfig = parse_xcconfig(os.path.join(os.getcwd(), IPLUG2_ROOT +  '/common-ios.xcconfig'))

  CFBundleGetInfoString = config['BUNDLE_NAME'] + " v" + config['FULL_VER_STR'] + " " + config['PLUG_COPYRIGHT_STR']
  CFBundleVersion = config['FULL_VER_STR']
  CFBundlePackageType = "BNDL"
  CSResourcesFileMapped = True
  LSMinimumSystemVersion = xcconfig['DEPLOYMENT_TARGET']

  print("Processing Info.plist files...")

# AUDIOUNIT v3

  if config['PLUG_TYPE'] == 0:
    if config['PLUG_DOES_MIDI_IN']:
      COMPONENT_TYPE = kAudioUnitType_MusicEffect
    else:
      COMPONENT_TYPE = kAudioUnitType_Effect
  elif config['PLUG_TYPE'] == 1:
    COMPONENT_TYPE = kAudioUnitType_MusicDevice
  elif config['PLUG_TYPE'] == 2:
    COMPONENT_TYPE = kAudioUnitType_MIDIProcessor

  if config['PLUG_HAS_UI'] == 1:
    NSEXTENSIONPOINTIDENTIFIER  = "com.apple.AudioUnit-UI"
  else:
    NSEXTENSIONPOINTIDENTIFIER  = "com.apple.AudioUnit"

  plistpath = projectpath + "/resources/" + config['BUNDLE_NAME'] + "-iOS-AUv3-Info.plist"
  
  NSEXTENSIONATTRDICT = dict(
    NSExtensionAttributes = dict(AudioComponents = [{}]),
    NSExtensionPointIdentifier = NSEXTENSIONPOINTIDENTIFIER
  )
  with open(plistpath, 'rb') as fp:
    auv3 = plistlib.load(fp)
  auv3['CFBundleExecutable'] = config['BUNDLE_NAME'] + "AppExtension"
  auv3['CFBundleIdentifier'] = "$(PRODUCT_BUNDLE_IDENTIFIER)"
  auv3['CFBundleName'] = config['BUNDLE_NAME'] + "AppExtension"
  auv3['CFBundleDisplayName'] = config['BUNDLE_NAME'] + "AppExtension"
  auv3['CFBundleVersion'] = CFBundleVersion
  auv3['CFBundleShortVersionString'] = CFBundleVersion
  auv3['CFBundlePackageType'] = "XPC!"
  auv3['NSExtension'] = NSEXTENSIONATTRDICT
  auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'] = [{}]
  auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0]['description'] = config['PLUG_NAME']
  auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0]['manufacturer'] = config['PLUG_MFR_ID']
  auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0]['name'] = config['PLUG_MFR'] + ": " + config['PLUG_NAME']
  auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0]['subtype'] = config['PLUG_UNIQUE_ID']
  auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0]['type'] = COMPONENT_TYPE
  auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0]['version'] = config['PLUG_VERSION_INT']
  auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0]['sandboxSafe'] = True
  auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0]['tags'] = ["",""]

  if config['PLUG_TYPE'] == 1:
    auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0]['tags'][0] = "Synth"
  else:
    auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0]['tags'][0] = "Effects"
    
  if config['PLUG_HAS_UI'] == 1:
    auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0]['tags'][1] = "size:{" + str(config['PLUG_WIDTH']) + "," + str(config['PLUG_HEIGHT']) + "}"
    auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0]['factoryFunction'] = "IPlugAUViewController_vIPlugDrumSynth"
    auv3['NSExtension']['NSExtensionMainStoryboard'] = config['BUNDLE_NAME'] + "-iOS-MainInterface"
  else:
    auv3['NSExtension']['NSExtensionPrincipalClass'] = "IPlugAUViewController_vIPlugDrumSynth"


  with open(plistpath, 'wb') as fp:
    plistlib.dump(auv3, fp)
# Standalone APP

  plistpath = projectpath + "/resources/" + config['BUNDLE_NAME'] + "-iOS-Info.plist"
  with open(plistpath, 'rb') as fp:
    iOSapp = plistlib.load(fp)
  iOSapp['CFBundleExecutable'] = config['BUNDLE_NAME']
  iOSapp['CFBundleIdentifier'] = "$(PRODUCT_BUNDLE_IDENTIFIER)"
  iOSapp['CFBundleName'] = config['BUNDLE_NAME']
  iOSapp['CFBundleVersion'] = CFBundleVersion
  iOSapp['CFBundleShortVersionString'] = CFBundleVersion
  iOSapp['CFBundlePackageType'] = "APPL"
  iOSapp['LSApplicationCategoryType'] = "public.app-category.music"

  with open(plistpath, 'wb') as fp:
    plistlib.dump(iOSapp, fp)
コード例 #58
0
def write_content(path, content: dict):
    if not path or not content:
        return

    with open(path, 'wb') as fp:
        plistlib.dump(content, fp)
コード例 #59
0
 def write(self):
     """ 修改文件内容 """
     with open(self.path, mode='wb') as f:
         plistlib.dump(self.content, f)
コード例 #60
0
#!/usr/bin/env python3

# adjust version for packages

import os, sys
import plistlib

if len(sys.argv) < 4:
    print('Usage: %s <version> <infile.pkgproj> <outfile.pkgproj>',
          file=sys.stderr)
    sys.exit(1)

version = sys.argv[1]

with open(sys.argv[2], 'rb') as infile:

    dict = plistlib.load(infile)

    for n in range(0, len(dict['PACKAGES'])):
        dict['PACKAGES'][n]['PACKAGE_SETTINGS']['VERSION'] = version

    with open(sys.argv[3], 'wb') as fp:
        plistlib.dump(dict, fp)