Example #1
0
 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)
Example #2
0
 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)
 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()), fmt=fmt)
             self.assertEqual(dict(pl), dict(pl2))
             pl2 = plistlib.load(BytesIO(b.getvalue()))
             self.assertEqual(dict(pl), dict(pl2))
    def parse(self): 
        """
        Parse SystemVersion.plist and write version information to file
        """
        with codecs.open(os.path.join(self._output_dir, self._output_file), "a", encoding="utf-8") as of:
            of.write("="*10 + " " + self._name + " " + "="*10 + "\r\n")
            plist_file = os.path.join(self._input_dir, "private", "var", "db", "com.apple.xpc.launchd", self._data_file)
            of.write("Source File: {0}\r\n\r\n".format(plist_file))
            if self._os_version in ["mojave", "high_sierra", "sierra", "el_capitan", "yosemite"]:
                if os.path.isfile(plist_file):
                    try:
                        with open(plist_file, "rb") as pl:
                            plist = plistlib.load(pl)
                        for launchd_item in plist:
                            of.write("{0}: {1}\r\n".format(launchd_item, plist[launchd_item]))

                    except KeyError:
                        pass
                else:
                    logging.warning("File: {0} does not exist or cannot be found.\r\n".format(plist_file))
                    of.write("[WARNING] File: {0} does not exist or cannot be found.\r\n".format(plist_file))
                    print("[WARNING] File: {0} does not exist or cannot be found.".format(plist_file))
            elif self._os_version in ["mavericks", "mountain_lion", "lion", "snow_leopard"]:
                logging.info("This version of OSX is not supported by this plugin.")
                print("[INFO] This version of OSX is not supported by this plugin.")
                of.write("[INFO] This version of OSX is not supported by this plugin.\r\n")
            else:
                logging.warning("Not a known OSX version.")
                print("[WARNING] Not a known OSX version.")
            of.write("="*40 + "\r\n\r\n")
        of.close()
def read_plist_roi_file(fname, nOfRois=0, shape=None, debug=False):
    with open(fname, 'rb') as fp:
        pl = plistlib.load(fp)
        outrois = [None]*len(pl['Images'])
        nRois = 0
        for image in pl['Images']:
            points = image['ROIs'][0]['Point_px']
            outpoints = []
            try:
                imageHeight = image['ImageHeight']
            except KeyError:
                if shape is not None:
                    imageHeight = shape[1]
                else:
                    raise IndexError("The image height is not indicated in the xml file, pass it as input")
            imageIndex = image['ImageIndex']
            for point in points:
                if debug:
                    print(point,type(point))
                px = float(point.split(",")[0][1:])
                py = -float(point.split(",")[1][:-1])
                if debug:
                    print(px,py)
                outpoints.append([px,py])
            if debug:
                print(image['ImageIndex'],outpoints)
            if imageIndex < len(outrois):
                outrois[imageIndex] = pg.PolyLineROI(outpoints, closed=True).saveState()
            else:
                outrois[nRois] = pg.PolyLineROI(outpoints, closed=True).saveState()
            nRois += 1
            if nOfRois and nRois >= nOfRois:
                break

    return outrois, nRois
Example #6
0
    def __init__(self, config, log):
        super(Itunes, self).__init__(config, log)

        config.add({'itunes': {
            'library': '~/Music/iTunes/iTunes Library.xml'
        }})

        # Load the iTunes library, which has to be the .xml one (not the .itl)
        library_path = config['itunes']['library'].as_filename()

        try:
            self._log.debug(
                u'loading iTunes library from {0}'.format(library_path))
            with create_temporary_copy(library_path) as library_copy:
                if six.PY2:
                    raw_library = plistlib.readPlist(library_copy)
                else:
                    with open(library_copy, 'rb') as library_copy_f:
                        raw_library = plistlib.load(library_copy_f)
        except IOError as e:
            raise ConfigValueError(u'invalid iTunes library: ' + e.strerror)
        except Exception:
            # It's likely the user configured their '.itl' library (<> xml)
            if os.path.splitext(library_path)[1].lower() != '.xml':
                hint = u': please ensure that the configured path' \
                       u' points to the .XML library'
            else:
                hint = ''
            raise ConfigValueError(u'invalid iTunes library' + hint)

        # Make the iTunes library queryable using the path
        self.collection = {_norm_itunes_path(track['Location']): track
                           for track in raw_library['Tracks'].values()
                           if 'Location' in track}
Example #7
0
 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)
Example #8
0
 def parse(self):
     """
     Parse /Library/Preferences/SystemConfiguration/com.apple.Boot.plist
     """
     with codecs.open(os.path.join(self._output_dir, self._output_file), "a", encoding="utf-8") as of:
         of.write("="*10 + " " + self._name + " " + "="*10 + "\r\n")
         if self._os_version in ["mojave", "high_sierra", "sierra", "el_capitan", "yosemite", "mavericks",
                                 "mountain_lion", "lion", "snow_leopard"]:
             plist_file = os.path.join(self._input_dir, "Library", "Preferences", "SystemConfiguration",
                                       self._data_file)
             of.write("Source File: {0}\r\n\r\n".format(plist_file))
             if os.path.isfile(plist_file):
                 with open(plist_file, "rb") as pl:
                     plist = plistlib.load(pl)
                     try:
                         if "Kernel Flags" in plist:
                             of.write("Kernel Flags: {0}\r\n".format(plist["Kernel Flags"]))
                         of.write("\r\n")
                     except KeyError:
                         pass
             else:
                 logging.warning("File: {0} does not exist or cannot be found.\r\n".format(plist_file))
                 of.write("[WARNING] File: {0} does not exist or cannot be found.\r\n".format(plist_file))
                 print("[WARNING] File: {0} does not exist or cannot be found.\r\n".format(plist_file))
         else:
             logging.warning("Not a known OSX version.")
             print("[WARNING] Not a known OSX version.")
         of.write("="*40 + "\r\n\r\n")
     of.close()
Example #9
0
	def populateTracker(self):
		# Check whether installed from Appstore first
		receipt = self.path + '/Contents/_MASReceipt'
		version = self.path + '/Contents/version.plist'
		if os.path.isdir(receipt) or os.path.isfile(version):
			self.tracker = Tracker.appstore
			return
		# Then check if app uses the Sparkle framework for updates
		plist = self.path + '/Contents/Info.plist'
		if os.path.isfile(plist):
			with open(plist, 'rb') as fp:
				try:
					pl = plistlib.load(fp)
					if 'SUFeedURL' in pl:
						self.updateURL = pl['SUFeedURL']
						self.tracker = Tracker.sparkle
						return
					elif 'SUFeedURLForFinal' in pl:
						self.updateURL = pl['SUFeedURLForFinal'] # Only seen this apply to iTerm however
						self.tracker = Tracker.sparkle
						return
				except:
					self.errorText = 'Something went wrong while reading Info.plist'
				finally:
					fp.close()
		# Failing everything else, indicate one should look at iusethis or google the app instead for updates
		self.tracker = Tracker.iusethis
Example #10
0
    def __init__(self):
        self.tracks = self.date = self.playlists = self.minor_version = None
        self.major_version = self.library_persistent_id = self.features = None
        self.show_content_ratings = self.application_version = None
        self.music_folder = None

        class attribdict(OrderedDict):
            """Force dict keys to be sutable class attribute names"""
            def __setitem__(self, key, value, **kwargs):
                super().__setitem__(key.lower().replace(' ', '_'), value,
                                    **kwargs)

        with open(self.library_path, 'rb') as f:
            library_data = plistlib.load(f, dict_type=attribdict)

        for key, val in library_data.items():
            if key == 'tracks':
                self.tracks = []
                Track = lambda self: object()
                for i_key in val.keys():
                    Track = namedtuple('Track', [k for k in val[i_key].keys()])
                    break
                # import pdb; pdb.set_trace()
                for track_id, track_data in val.items():
                    self.tracks.append(Track(*[i for i in track_data]))
            else:
                setattr(self, key, val)
Example #11
0
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)
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()
Example #13
0
 def index(self):
     path = str(self.path)
     index_path = None
     prefix = ''
     searched_files = ['index.html', 'index.htm', 'index.md', 'README.md']
     if os.path.isfile(path):
         index_path = path
     elif os.path.isdir(path):
         documents_dir = os.path.join(path, 'Contents', 'Resources', 'Documents')
         plist_path = os.path.join(path, 'Contents', 'Info.plist')
         if os.path.isdir(documents_dir) and os.path.isfile(plist_path):
             with open(plist_path, 'rb') as fd:
                 content = plistlib.load(fd)
             prefix = 'Contents/Resources/Documents/'
             if 'dashIndexFilePath' in content:
                 searched_files = [content['dashIndexFilePath']] + searched_files
         index_path = ''
         for index in searched_files:
             if os.path.isfile(os.path.join(path, prefix + index)):
                 index_path = prefix + index
                 break
         else:
             ldir = os.listdir(path)
             if len(ldir) == 1 and os.path.isfile(os.path.join(path, ldir[0])):
                 index_path = ldir[0]
     return index_path
Example #14
0
 def __init__(self, appdir, channelConfig, channelConfigDir):
     self.appdir = appdir
     self.channelConfig = channelConfig
     self.channelConfigDir = channelConfigDir
     
     infoplistfile = os.path.join(appdir, "Info.plist")
     self.infoPlist = plistlib.load(open(infoplistfile, "rb"))
Example #15
0
 def _add_itunes_library(self, path):
     """
     Read the iTunes music library index xml from the given path and use all songs in there
     instead of scanning all files in the given path.
     """
     print("Importing iTunes music library.")
     itunes_idx = os.path.join(path, "iTunes Music Library.xml")
     if not os.path.isfile(itunes_idx):
         itunes_idx = os.path.join(path, "iTunes Library.xml")
     with open(itunes_idx, "rb") as fp:
         library = plistlib.load(fp)
         tracks = library["Tracks"]
         print("iTunes library contains {:d} entries.".format(len(tracks)))
         music_folder = urllib.request.url2pathname(urllib.parse.urlparse(library["Music Folder"]).path)
         if music_folder.endswith(("/", "\\")):
             music_folder = music_folder[:-1]
         music_folder = os.path.split(music_folder)[0] + os.path.sep
     tracks = (
         Track.from_itunes(t, music_folder, path)
         for t in tracks.values()
         if t["Track Type"] == "File"
         and not t.get("Podcast")
         and t.get("Genre", "").lower() not in ("audio book", "audiobook")
         and "document" not in t.get("Kind", "")
     )
     amount_new = self.add_tracks(tracks)
     print("Added {:d} new tracks.".format(amount_new))
Example #16
0
 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)
Example #17
0
	def testWrite(self):
		writer = UFOWriter(self.dstDir, formatVersion=2)
		writer.setKerningGroupConversionRenameMaps(self.downConversionMapping)
		writer.writeKerning(self.kerning)
		writer.writeGroups(self.groups)
		# test groups
		path = os.path.join(self.dstDir, "groups.plist")
		with open(path, "rb") as f:
			writtenGroups = load(f)
		self.assertEqual(writtenGroups, self.expectedWrittenGroups)
		# test kerning
		path = os.path.join(self.dstDir, "kerning.plist")
		with open(path, "rb") as f:
			writtenKerning = load(f)
		self.assertEqual(writtenKerning, self.expectedWrittenKerning)
		self.tearDownUFO()
Example #18
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--library',
                        help='Path to XML library file',
                        type=argparse.FileType('rb'),
                        default='./Library.xml')
    parser.add_argument('--db',
                        help='Path to SQLite DB file',
                        default='itunes.db')

    args = parser.parse_args()
    library = plistlib.load(args.library)

    tracks_table, tracks = process_tracks(library)
    playlists_table, playlist_itms_table, playlists = process_playlists(library)

    conn = sqlite3.connect(args.db)
    conn.execute(tracks_table)
    conn.execute(playlists_table)
    conn.execute(playlist_itms_table)

    for query in tracks + playlists:
        conn.execute(query[0], list(query[1]))

    conn.commit()
    conn.close()
Example #19
0
 def reload_lib(self):
     print("Parsing iTunes library...")
     with cd('~/Music/iTunes'):
         with open('iTunes Music Library.xml', 'rb') as f:
             save_time = strftime("%a, %d %b %y %I:%M:%S %p", localtime())
             self.lib = plistlib.load(f)
     pickle.dump((save_time, self.lib), open('saved_lib.pkl', 'wb'))
     print('done!')
 def __init__(self, libraryPath):
     # Load iTunes library file
     libraryFile = open(os.path.expanduser(libraryPath),'rb')
     self.libraryData = plistlib.load(libraryFile)
     libraryFile.close()
     self.tracks = dict()
     self.loadTracks()
     self.playlists = self.libraryData['Playlists']
    def load(self, full_file_path=''):
        file = self.__get_file(full_file_path) if full_file_path else self.__get_file()
        self.location = full_file_path if file is False else file

        if not file:
            return False

        with open(file, 'rb') as library:
            return plistlib.load(library)
Example #22
0
def main():
  f = open('/System/Library/Frameworks/AppKit.framework/Resources/StandardKeyBinding.dict', 'rb')
  # note: user customizations go in '~/Library/KeyBindings/DefaultKeyBinding.dict'.
  bindings = plistlib.load(f)

  for key, cmd in sorted(bindings.items(), key=lambda p: repr(p[1])):
    if cmd == 'noop:': continue
    desc = '+'.join(translate_key(c) for c in key)
    errFL('{:<48} {!r}', str(cmd), desc)
Example #23
0
def load_plist(plistpath):
    if not os.path.exists(plistpath):
        output = subprocess.check_output(["find", ".", "-name", "*.plist"]).decode('utf-8')
        print(output)
        raise Exception("No such plist exists.  Try one of the strings shown in the log.")

    import plistlib
    with open(plistpath, "rb") as f:
        data = plistlib.load(f)
    return data
 def __init__(self, filename):
     # Load Pitchfork BNM library file if it exists
     self.filepath = os.path.join(os.path.split(os.path.expanduser(__file__))[0],filename)
     self.libraryData = dict()
     self.lib_exists = False
     if os.path.isfile(self.filepath):
         self.lib_exists = True
         libraryFile = open(self.filepath,'rb')
         self.libraryData = plistlib.load(libraryFile)
         libraryFile.close()
Example #25
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)
Example #26
0
 def test_reloadLayers_change_layer_order(self):
     path = getTestFontPath(u"TestExternalEditing.ufo")
     path = makeTestFontCopy(path)
     shutil.copytree(os.path.join(path, "glyphs"),
                     os.path.join(path, "glyphs.test"))
     with open(os.path.join(path, "layercontents.plist"), "rb") as f:
         contents = load(f)
     contents.append(("test", "glyphs.test"))
     with open(os.path.join(path, "layercontents.plist"), "wb") as f:
         dump(contents, f)
     font = Font(path)
     with open(os.path.join(path, "layercontents.plist"), "rb") as f:
         contents = load(f)
     contents.reverse()
     with open(os.path.join(path, "layercontents.plist"), "wb") as f:
         dump(contents, f)
     font.reloadLayers(dict(order=True))
     self.assertEqual(font.layers.layerOrder, ["test", "public.default"])
     tearDownTestFontCopy(font.path)
    def check(self):
        plist_file_globs = {
            "**/*.tmLanguage",
            "**/*.tmPreferences",
            "**/*.tmSnippet",
            "**/*.tmTheme",
            "**/*.hidden-tmTheme",
        }

        for file_path in self.globs(*plist_file_globs):
            with self.file_context(file_path):
                with file_path.open('rb') as f:
                    try:
                        if sys.version_info < (3, 4):
                            plistlib.readPlist(f)
                        else:
                            plistlib.load(f)
                    except (ValueError, ExpatError) as e:
                        self.fail("Invalid Plist", exception=e)
Example #28
0
    def get_dict_from_recipe_name(recipe_name):
        recipes_directory = os.path.normpath(os.path.dirname(__file__) + "/../recipe/") + "/"

        # We get the required recipe
        recipe_path = recipes_directory + recipe_name

        # We get is as dict
        recipe_dict = plistlib.load(open(recipe_path, 'rb'), fmt=plistlib.FMT_XML)

        return recipe_dict
Example #29
0
def Mac_framework(in_path):
    retVal = None
    plist_path = os.path.join(in_path, 'Versions/Current/Resources/Info.plist')
    if os.path.exists(plist_path):
        with open(plist_path, 'rb') as fp:
            pl = plistlib.load(fp)
            version = pl.get('CFBundleGetInfoString').split(' ')[0]
            if version:
                retVal = (in_path, version, None)
    return retVal
Example #30
0
 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)
Example #31
0
    def test_icon_file(self):
        resource_dir = os.path.join(
            self.app_dir, "dist", "SimpleApp.app", "Contents", "Resources"
        )

        with open(os.path.join(resource_dir, "..", "Info.plist"), "rb") as fp:
            if hasattr(plistlib, "load"):
                pl = plistlib.load(fp)
            else:
                pl = plistlib.readPlist(fp)

        self.assertEqual(pl["CFBundleIconFile"], "main.icns")

        src_file = os.path.join(self.app_dir, "main.icns")
        dst_file = os.path.join(resource_dir, "main.icns")
        self.assertTrue(os.path.exists(dst_file))

        self.assertContentsEqual(src_file, dst_file)

        if "--alias" in self.py2app_args:
            self.assertTrue(os.path.islink(dst_file))
Example #32
0
    def GetTopLevel(self, file_object):
        """Returns the deserialized content of a plist as a dictionary object.

    Args:
      file_object (dfvfs.FileIO): a file-like object to parse.

    Returns:
      dict[str, object]: contents of the plist.

    Raises:
      UnableToParseFile: when the file cannot be parsed.
    """
        try:
            return plistlib.load(file_object)

        except (AttributeError, LookupError, binascii.Error, expat.ExpatError,
                plistlib.InvalidFileException) as exception:
            # LookupError will be raised in cases where the plist is an XML file
            # that contains an unsupported encoding.
            raise errors.UnableToParseFile(
                'Unable to parse plist with error: {0!s}'.format(exception))
Example #33
0
def platform_release(release):
    if OSX:
        SYSTEMVERSION_PLIST = "/System/Library/CoreServices/SystemVersion.plist"
        try:
            import plistlib
            if PYTHON2:
                pl = plistlib.readPlist(
                    '/System/Library/CoreServices/SystemVersion.plist')  #pylint: disable=deprecated-method
            else:
                with open(SYSTEMVERSION_PLIST, "rb") as f:
                    pl = plistlib.load(f)  #@UndefinedVariable
            return pl['ProductUserVisibleVersion']
        except Exception as e:
            get_util_logger().debug("platform_release(%s)",
                                    release,
                                    exc_info=True)
            get_util_logger().warn(
                "Warning: failed to get release information")
            get_util_logger().warn(" from '%s':", SYSTEMVERSION_PLIST)
            get_util_logger().warn(" %s", e)
    return release
Example #34
0
def installer_packages():
    """
    quick and dirty dump of packages on InstallerPackages
    """
    vol = '/Volumes/InstallerPackages/munkipkg_projects'
    import glob
    g = os.path.join(vol, '*/payload/*.app')
    info = {}
    for path in glob.glob(g):
        name = os.path.splitext(os.path.basename(path))[0]
        directory = path.split('/payload')[0]
        folder = os.path.basename(directory)
        pkgs = []
        for pkg in glob.glob(os.path.join(directory, 'build/*.pkg')):
            pkgs.append(os.path.basename(pkg))
        plist = os.path.join(directory, 'build-info.plist')
        with open(plist, 'rb') as f:
            b_info = plistlib.load(f)
        info[name] = {'pkgs': pkgs, 'folder': folder,
                      'build': b_info, 'name': name}
    pprint.pprint(info)
Example #35
0
def generate_contents(args):
    input_dir = os.path.expanduser(args.input)
    copy_resources(input_dir, os.path.join(args.output, 'images'))
    with open(os.path.join(input_dir, 'contents.xml'), 'rb') as fp:
        data = plistlib.load(fp)

    canvas = data['canvas']
    mind_maps = canvas['mindMaps']
    for main_node in mind_maps:
        prev_week, week_num, quarter = get_current_week()
        generator = Generator(
            main_node, {
                'previous_week': prev_week,
                'current_week': week_num,
                'current_quarter': quarter,
                'output_dir': args.output,
                'prefix': args.prefix,
                'author': args.author,
                'logging': args.verbose,
            })
        generator.generate()
Example #36
0
 def _parse_json_or_plist_file(self, file_path):
     """Parse the file. Start with plist, then JSON."""
     try:
         with open(file_path, "rb") as f:
             data = plistlib.load(f)
         self.type = "plist"
         self.file_path = file_path
         return data
     except Exception:
         log_err(f"WARNING: Could not read {file_path} - expected if using .json config")
         pass
     try:
         with open(file_path, "rb") as f:
             data = json.load(f)
             self.type = "json"
             self.file_path = file_path
             return data
     except Exception:
         log_err(f"WARNING: Could not read {file_path} - expected if using .plist config")
         pass
     return {}
Example #37
0
File: utils.py Project: synsa/vorta
def get_sorted_wifis(profile):
    """Get SSIDs from OS and merge with settings in DB."""

    from vorta.models import WifiSettingModel

    if sys.platform == 'darwin':
        plist_path = '/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist'

        try:
            plist_file = open(plist_path, 'rb')
            wifis = plistlib.load(plist_file).get('KnownNetworks')
        except xml.parsers.expat.ExpatError:
            logger.error('Unable to parse list of Wifi networks.')
            return

        if wifis is not None:
            for wifi in wifis.values():
                timestamp = wifi.get('LastConnected', None)
                ssid = wifi['SSIDString']
                db_wifi, created = WifiSettingModel.get_or_create(
                    ssid=ssid,
                    profile=profile.id,
                    defaults={
                        'last_connected': timestamp,
                        'allowed': True
                    })

                # update last connected time
                if not created and db_wifi.last_connected != timestamp:
                    db_wifi.last_connected = timestamp
                    db_wifi.save()

            # remove Wifis that were deleted in the system.
            deleted_wifis = WifiSettingModel.select() \
                .where(WifiSettingModel.ssid.not_in([w['SSIDString'] for w in wifis.values()]))
            for wifi in deleted_wifis:
                wifi.delete_instance()

    return WifiSettingModel.select() \
        .where(WifiSettingModel.profile == profile.id).order_by(-WifiSettingModel.last_connected)
Example #38
0
 def make_component_property_list(self):
     """Use pkgutil --analyze to build a component property list; then
     turn off package relocation"""
     self.component_plist = os.path.join(self.tmproot, "component.plist")
     try:
         p = subprocess.Popen(
             (
                 "/usr/bin/pkgbuild",
                 "--analyze",
                 "--root",
                 self.tmp_pkgroot,
                 self.component_plist,
             ),
             stdout=subprocess.PIPE,
             stderr=subprocess.PIPE,
             text=True,
         )
         (_, err) = p.communicate()
     except OSError as e:
         raise PackagerError(
             f"pkgbuild execution failed with error code {e.errno}: {e.strerror}"
         )
     if p.returncode != 0:
         raise PackagerError(
             f"pkgbuild failed with exit code {p.returncode}: "
             f"{' '.join(str(err).split())}")
     try:
         with open(self.component_plist, "rb") as f:
             plist = plistlib.load(f)
     except BaseException:
         raise PackagerError(f"Couldn't read {self.component_plist}")
     # plist is an array of dicts, iterate through
     for bundle in plist:
         if bundle.get("BundleIsRelocatable"):
             bundle["BundleIsRelocatable"] = False
     try:
         with open(self.component_plist, "wb") as f:
             plist = plistlib.dump(plist, f)
     except BaseException:
         raise PackagerError(f"Couldn't write {self.component_plist}")
Example #39
0
def patch_mac_app():
    """Patch .app to copy missing data and link some libs.

    See https://github.com/pyinstaller/pyinstaller/issues/2276
    """
    app_path = os.path.join('dist', 'qutebrowser.app')
    qtwe_core_dir = os.path.join('.tox', 'pyinstaller', 'lib', 'python3.6',
                                 'site-packages', 'PyQt5', 'Qt', 'lib',
                                 'QtWebEngineCore.framework')
    # Copy QtWebEngineProcess.app
    proc_app = 'QtWebEngineProcess.app'
    shutil.copytree(os.path.join(qtwe_core_dir, 'Helpers', proc_app),
                    os.path.join(app_path, 'Contents', 'MacOS', proc_app))
    # Copy resources
    for f in glob.glob(os.path.join(qtwe_core_dir, 'Resources', '*')):
        dest = os.path.join(app_path, 'Contents', 'Resources')
        if os.path.isdir(f):
            dir_dest = os.path.join(dest, os.path.basename(f))
            print("Copying directory {} to {}".format(f, dir_dest))
            shutil.copytree(f, dir_dest)
        else:
            print("Copying {} to {}".format(f, dest))
            shutil.copy(f, dest)
    # Link dependencies
    for lib in [
            'QtCore', 'QtWebEngineCore', 'QtQuick', 'QtQml', 'QtNetwork',
            'QtGui', 'QtWebChannel', 'QtPositioning'
    ]:
        dest = os.path.join(app_path, lib + '.framework', 'Versions', '5')
        os.makedirs(dest)
        os.symlink(
            os.path.join(os.pardir, os.pardir, os.pardir, 'Contents', 'MacOS',
                         lib), os.path.join(dest, lib))
    # 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)
Example #40
0
def get_finder_tags():
    """parses com.apple.finder.plist to get list of Finder tags and associated colors
    returns: dict in form {tag_name: color_id}"""

    # TODO: Is it possible to get a race condition where Finder is writing at same time
    # this code is trying to open the plist file?  If so, what happens?
    plist_files = [
        pathlib.Path(
            str(pathlib.Path.home()) +
            "/Library/SyncedPreferences/com.apple.finder.plist"),
        # On Monterey the SyncedPreferences/com.apple.finder.plist does not exist
        # it might be in this one but I can't verify until I can get access to Monterey
        # pathlib.Path(
        # str(pathlib.Path.home()) + "/Library/Preferences/com.apple.finder.plist"
        # ),
    ]
    tags = {}

    for plist_file in plist_files:
        try:
            with open(plist_file, "rb") as fp:
                pl = plistlib.load(fp)
                try:
                    finder_tags = pl["values"]["FinderTagDict"]["value"][
                        "FinderTags"]
                    for tag in finder_tags:
                        try:
                            name = tag["n"]
                            color = tag["l"]
                        except KeyError:
                            # color will not be present if no color
                            color = 0
                        tags[name] = color
                    break
                except Exception as e:
                    pass
        except Exception as e:
            pass

    return tags
Example #41
0
    def parse(self, input):
        """Read a .stringsdict file into a dictionary, and convert it to translation units."""

        if isinstance(input, (bytes, str)):
            plist = plistlib.loads(input, dict_type=OrderedDict)
        elif input is not None:
            plist = plistlib.load(input, dict_type=OrderedDict)
        else:
            plist = {}

        for key, outer in plist.items():
            if not isinstance(outer, dict):
                raise ValueError(f"{key} is not a dict")
            for innerkey, value in outer.items():
                if innerkey == "NSStringLocalizedFormatKey":
                    u = self.UnitClass()
                    u.set_unitid(u.IdClass([("key", key)]))
                    u.target = str(value)
                    self.addunit(u)
                elif isinstance(value, dict):
                    spec_type = value.get("NSStringFormatSpecTypeKey", "")
                    if spec_type and spec_type != "NSStringPluralRuleType":
                        raise ValueError(
                            f"{innerkey} in {key} is not of NSStringPluralRuleType"
                        )

                    plural_tags = self.target_plural_tags
                    plural_strings = [
                        value.get(tag, "") for tag in plural_tags
                    ]

                    u = self.UnitClass()
                    u.set_unitid(u.IdClass([("key", key), ("key", innerkey)]))
                    u.target = multistring(plural_strings)
                    u.format_value_type = value.get(
                        "NSStringFormatValueTypeKey", "")
                    self.addunit(u)
                else:
                    raise ValueError(f"Unexpected key {innerkey} in {key}")
Example #42
0
 def test_delitem_glyph_not_dirty(self):
     for ufo in (u"TestExternalEditing.ufo", u"TestExternalEditing.ufoz"):
         path = getTestFontPath(ufo)
         path = makeTestFontCopy(path)
         font = Font(path)
         font["A"]  # glyph = font["A"]
         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()
         self.assertFalse(os.path.exists(glyphPath))
         tearDownTestFontCopy(font.path)
Example #43
0
    def get_version_info(self):
        # 先从 project 获取,如果失败(失败定义:不全是 数字 和 '.' 组成),从 plist 获取
        def valid_version(main_version: str):
            """
            如果由 . 和 数字组成,就是合法的;如果全部由数字组成,也是合法的
            """
            return ('.' in main_version and main_version.replace(
                '.', '').isdigit()) or main_version.isdigit()

        # 主包的主工程版本号读取
        main_version = self.release_build_config.buildSettings[
            'MARKETING_VERSION']
        if main_version and valid_version(main_version):
            plist_path = self.__get_info_plist_path()
            print("转向从 plist 读取版本号: {}".format(plist_path))
            plist = None
            with open(plist_path, 'rb') as rbf:
                plist = plistlib.load(rbf)
            if plist:
                return main_version + '.' + plist['CFBundleVersion'].split(
                    '.')[-1]
        return ''
Example #44
0
 def __installDocset(self, docset, refresh):
     extract_location = self.docsetFolder
     docset.stats = 'Preparing to install: This might take a while.'
     refresh()
     zip = ZipFile(docset.zipPath, mode='r')
     ll = [name for name in zip.namelist() if '.docset' in name]
     if len(ll) > 0:
         n = ll[0]
         m = os.path.join(self.docsetFolder, n)
         docset.stats = 'Preparing to extract'
         refresh()
         l = zip.infolist()
         zip.extractall(path=extract_location,
                        members=self.track_progress(l, docset, len(l),
                                                    refresh))
         zip.close()
         os.remove(docset.zipPath)
         plistpath = os.path.join(m, self.plistPath)
         name = docset.name
         image = ''
         with open(plistpath, 'rb') as f:
             pp = plistlib.load(f)
             if 'CFBundleName' in pp.keys():
                 name = pp['CFBundleName']
             if 'CFBundleIdentifier' in pp.keys():
                 image = pp['CFBundleIdentifier']
         dbManager = DBManager.DBManager()
         dbManager.DocsetInstalled(name, m, 'transfer', image, 0.0)
         if docset in self.__installingDocsets:
             self.__installingDocsets.remove(docset)
         docset.status = 'Cleaning up...'
         refresh()
         cleanup_path = os.path.join(self.docsetFolder, '__MACOSX')
         if os.path.exists(cleanup_path):
             shutil.rmtree(cleanup_path)
         docset.status = 'Installed'
         refresh()
     else:
         raise Exception('Unknown docset structure')
Example #45
0
def findcommonTracks(filenames,file):
    tracknameSet=[]
    for filename in filenames:
        trackname=set()
        with open(filename,'rb') as fp:
            p=plistlib.load(fp)
        tracks=p["Tracks"]
        for trackId, track in tracks.items():
            try:
                 trackname.add(track['Name'])
            except:
                pass
        tracknameSet.append(trackname)
    #set.intersection找到多个集合中公共的元素
    commonTracks=set.intersection(*tracknameSet)

    if len(commonTracks)>0:
        with open(file,'w+') as f:
            for name in commonTracks:
                f.write("%s\n"%name)
    else:
        print("no common Tracks!")
Example #46
0
def gen_image(file_name, export_path):
    # 检查文件是否存在
    plist = file_name + '.plist'
    if not os.path.exists(plist):
        print('plist文件【%s】不存在!请检查' % plist)
        return

    png = file_name + '.png'
    if not os.path.exists(png):
        print('png文件【%s】不存在!请检查' % plist)
        return

    # 检查导出目录
    if not os.path.exists(export_path):
        try:
            os.mkdir(export_path)
        except Exception as e:
            print(e)
            return

    # 使用plistlib库加载 plist 文件
    lp = plistlib.load(open(plist, 'rb'))
    # 加载 png 图片文件
    img = Image.open(file_name + '.png')

    # 读取所有小图数据
    if not 'frames' in lp:
        print(">>>>>>>>>>>>>>>>>>>>>>>")
        print(file_name)
        print("<<<<<<<<<<<<<<<<<<<<<<<<<<")
        return

    frames = lp['frames']
    # print(frames)
    for key in frames:
        # print(key)
        # print(frames[key])
        item = get_frame(frames[key])
        export_image(img, os.path.join(export_path, key), item)
Example #47
0
def load_configs(configfile='/Users/codar/qccodar_files/qccodar.plist'):
    if Path(configfile).is_file():
        plistfile = Path(configfile)
    else:
        plistfile = Path(__file__).parent.resolve() / 'config' / 'qccodar.plist'

    try:
        with open(plistfile, 'rb') as fp:
            qccodar_values = load(fp)
    except:
        print(f'Plist {plistfile} not found. Using default settings.')
        qccodar_values = dict(
            qc_doa_half_power_width=dict(doa_half_power_width_max=50.0),
            qc_doa_peak_power=dict(doa_peak_power_min=5.0),
            qc_monopole_snr=dict(monopole_snr_min=5.0),
            qc_loop_snr=dict(loop_snr_min=5.0),
            qc_radialshort_velocity_count=dict(radialshort_velocity_count_min=2.0),
            metric_concatenation = dict(numfiles=3, sample_interval=30.0),
            weighted_shorts=dict(numdegrees=3,weight_parameter='MP', table_type='LLUV RDL7'),
            merge=dict(css_interval_minutes=30.0,number_of_css=5.0,shorts_minute_filter = '*00')
         )
    return qccodar_values
Example #48
0
def deserialize(stream_or_string, **options):
    """
    Deserialize any string or stream like object into a Python data structure.

    :param stream_or_string: stream or string to deserialize.
    :param options: options given to lower plist module.

    :returns: Deserialized data structure.
    """
    try:
        if not isinstance(stream_or_string, (bytes, str)):
            log.trace("Using plistlib.load to deserialize.")
            return plistlib.load(stream_or_string, **options)

        if isinstance(stream_or_string, str):
            log.trace("Need to encode plist string.")
            stream_or_string = stream_or_string.encode("utf-8")

        log.trace("Using plistlib.loads to deserialize.")
        return plistlib.loads(stream_or_string, **options)
    except Exception as error:  # pylint: disable=broad-except
        raise DeserializationError(error)
Example #49
0
def get_sdk_level():
    sdk = get_sdk()

    if not sdk:
        return None

    if sdk == "/":
        return get_os_level()

    sdk = sdk.rstrip("/")
    sdkname = os.path.basename(sdk)
    assert sdkname.startswith("MacOSX")
    assert sdkname.endswith(".sdk")
    if sdkname == "MacOSX.sdk":
        try:
            with open(os.path.join(sdk, "SDKSettings.plist"), "rb") as fp:
                pl = plistlib.load(fp)
            return pl["Version"]
        except Exception:
            raise SystemExit("Cannot determine SDK version")
    else:
        return sdkname[6:-4]
Example #50
0
    def parseCompat(self):
        """
        Parse SystemVersionCompat.plist and return ProductVersion
        """
        plist_file = os.path.join(self._input_dir,
                                  "System", "Library", "CoreServices", self._compat_file)
        if not os.path.isfile(plist_file):
            logging.warning("%s does not exist", self._compat_file)
            print("[WARNING] {0} does not exist".format(self._compat_file))
            return "NONE"

        with open(plist_file, "rb") as plist:
            plist_loaded = plistlib.load(plist)
        plist.close()

        try:
            if "ProductVersion" in plist_loaded:
                product_version = "{0}".format(plist_loaded["ProductVersion"])
                return product_version
        except KeyError:
            logging.warning("[ERROR] ProductVersion key does not exist in %s", self._compat_file)
            return "NONE"
Example #51
0
def check_buildid(firm_bundle):
    with open(f'{firm_bundle}/Info.json') as f:
        bundle_data = json.load(f)

    if len(bundle_data['files']) == 1:
        buildid = None

    if not os.path.isfile('work/tmp/IPSW_BuildManifest/BuildManifest.plist'):
        buildid = None
    else:
        with open('work/tmp/IPSW_BuildManifest/BuildManifest.plist') as f:
            bm_data = plistlib.load(f)
            ipsw_buildid = bm_data['BuildIdentities']['Info']['BuildNumber']

        for x in range(0, len(bundle_data['files']['ramdisk'])):
            if bundle_data['files']['ramdisk'][x]['buildid']:
                if bundle_data['files']['ramdisk'][x]['buildid'].lower(
                ) == ipsw_buildid.lower():
                    buildid = ipsw_buildid
                    break

    return buildid
Example #52
0
def export_iphoto(args):

    with open(path.join(args.input, XML_FILENAME), 'rb') as fp:
        data = plistlib.load(fp)
        masters = data.get('Master Image List')

    ignored_albums = IGNORED_ALBUMS
    if not args.all:
        ignored_albums.append('allPhotosAlbum')

    albums = [
        a for a in data['List of Albums'] if a['GUID'] not in IGNORED_ALBUMS
    ]

    for album in tqdm(albums):
        album_directory = path.join(args.output, slugify(album['AlbumName']))
        makedirs(album_directory, exist_ok=True)

        for photo_key in album['KeyList']:
            master_element = masters.get(photo_key, None)

            if master_element is None:
                print(photo_key, 'not in Masters')
                continue

            image_path = master_element.get('ImagePath').split('Masters/')[-1]
            if image_path.startswith('/'):
                continue
            image_filename = path.basename(image_path)

            full_source_path = path.join(args.input, 'Masters', image_path)
            full_dest_path = path.join(
                album_directory,
                slugify_filename(photo_key + '__' + image_filename))

            try:
                copyfile(full_source_path, full_dest_path)
            except FileNotFoundError:
                pass
Example #53
0
def maybe_sign_artifact(inst, artifact, project, arch):
    if not project.fingerprint:
        return
    base = project.base
    privkey = path.join(base, f"{project.fingerprint}.rsa")
    pubkey = path.join(base, f"{project.fingerprint}.plist")
    # XXX: this is not cooperative, and should be okay because
    # it's a small amount of data
    with open(pubkey, "rb") as pkf:
        pkeydata = PUBKEY_VALIDATOR.validate(plistlib.load(pkf))
    signed_by = pkeydata["signature-by"]
    env_extra = {"XBPS_ARCH": arch}
    check_call_logged([
        "xbps-rindex", "--signedby", signed_by, "--privkey", privkey, "-s",
        path.dirname(artifact)
    ],
                      env_extra=env_extra)
    check_call_logged([
        "xbps-rindex", "--signedby", signed_by, "--privkey", privkey, "-S",
        artifact
    ],
                      env_extra=env_extra)
Example #54
0
def _get_plist_dict(info_plist_path: str) -> Dict[str, Any]:
    """Returns dictionary from XCFramework Info.plist file content.

  Args:
    info_plist_path: XCFramework Info.plist file path to read from.
  Returns:
    Dictionary of parsed Info.plist contents.
  Raises:
    ValueError - if file does not contain XCFrameworkFormatVersion key.
  """
    with open(info_plist_path, "rb") as info_plist_file:
        info_plist_dict = plistlib.load(info_plist_file)
        if "XCFrameworkFormatVersion" not in info_plist_dict:
            raise ValueError(f"""
Info.plist file does not contain key: 'XCFrameworkFormatVersion'. Contents:

{info_plist_dict}

Is it an XCFramework Info.plist file?
""")

        return info_plist_dict
Example #55
0
    def __init__(self, project):
        self.project = project

        self.project_dir = project.get_project_dir()

        plist_path = self.project.get_plist_path()
        with open(plist_path, "rb") as f:
            self.plist = plistlib.load(f)

        # 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 #56
0
def airpod_info(device_id: str) -> tuple:
    """
    Get airpod info with a given address (MAC)

    Args:
        device_id (str): MAC address of the AirPod to search

    Returns:
        tuble: productlabel, productid, vendorid
    """
    with open("/Library/Preferences/com.apple.Bluetooth.plist", "rb") as f:
        pl = plistlib.load(f)
    devices: dict = pl.get("DeviceCache")
    ret: tuple = tuple()
    for d, v in devices.items():
        if device_id in d:
            product_id: str = v.get("ProductID")
            product_label: str = AIRPD_PRODUCT_INDX.get(product_id)
            vendor_id: str = v.get("VendorID")
            ret: tuple = (product_label, product_id, vendor_id)
            break
    return ret
Example #57
0
    def create_plist(self):
        """Create the Contents/Info.plist file"""
        # Use custom plist if supplied, otherwise create a simple default.
        if self.custom_info_plist:
            with open(self.custom_info_plist, "rb") as fp:
                contents = plistlib.load(fp)
        else:
            contents = {
                "CFBundleIconFile": "icon.icns",
                "CFBundleDevelopmentRegion": "English",
                "CFBundleIdentifier": self.bundle_name,
            }

        # Ensure CFBundleExecutable is set correctly
        contents["CFBundleExecutable"] = self.bundle_executable

        # add custom items to the plist file
        for key, value in self.plist_items:
            contents[key] = value

        with open(os.path.join(self.contentsDir, "Info.plist"), "wb") as fp:
            plistlib.dump(contents, fp)
Example #58
0
def read_plist_roi_file(fname, nOfRois=0, shape=None, debug=False):
    with open(fname, 'rb') as fp:
        pl = plistlib.load(fp)
        outrois = [None] * len(pl['Images'])
        nRois = 0
        for image in pl['Images']:
            points = image['ROIs'][0]['Point_px']
            outpoints = []
            try:
                imageHeight = image['ImageHeight']
            except KeyError:
                if shape is not None:
                    imageHeight = shape[1]
                else:
                    raise IndexError(
                        "The image height is not indicated in the xml file, pass it as input"
                    )
            imageIndex = image['ImageIndex']
            for point in points:
                if debug:
                    print(point, type(point))
                px = float(point.split(",")[0][1:])
                py = -float(point.split(",")[1][:-1])
                if debug:
                    print(px, py)
                outpoints.append([px, py])
            if debug:
                print(image['ImageIndex'], outpoints)
            if imageIndex < len(outrois):
                outrois[imageIndex] = pg.PolyLineROI(outpoints,
                                                     closed=True).saveState()
            else:
                outrois[nRois] = pg.PolyLineROI(outpoints,
                                                closed=True).saveState()
            nRois += 1
            if nOfRois and nRois >= nOfRois:
                break

    return outrois, nRois
Example #59
0
def analyze_app(path):
    results = {}
    infoPlistPath = path / 'Info.plist'
    with open(str(infoPlistPath.resolve()), 'rb') as infoPlistFile:
        infoPlist = plistlib.load(infoPlistFile)

    bundle_id = infoPlist['CFBundleIdentifier']
    app_name = infoPlist.get(
        'CFBundleDisplayName',
        infoPlist.get('CFBundleName', infoPlist['CFBundleIdentifier']))
    print(f'analyzing {app_name} at {path.name}')
    results['app_name'] = app_name
    results['bundle_id'] = bundle_id
    results['sdk'] = infoPlist.get('DTSDKName')
    results['deployment_target'] = infoPlist.get('MinimumOSVersion')
    results['uses_swift'] = app_uses_swift(path)
    executable = find_executable_in(path)
    results['executable'] = executable.name
    classes = class_dump(executable)
    results['percentage_swift'] = percentage_classes_in_swift(classes)
    results['main_binary_uses_swift'] = results['percentage_swift'] > 0
    return results
Example #60
0
def set_processor_name(new_name: str, backup: bool = True):
    """ Changes the processor name """
    system_info_path = _get_localized_folder(
        SYSTEM_CPU_INFO) + f'{CPU_INFO_NAME}'
    if not system_info_path:
        print(
            f'Could not determine which .lproj folder to use in {SYSTEM_CPU_INFO}.'
        )
        print(f'Please make change your processor name manually')
        return

    if backup and not os.path.exists(f'{RESOURCES}{CPU_INFO_NAME}.backup'):
        shutil.copyfile(system_info_path, f'{RESOURCES}{CPU_INFO_NAME}.backup')

    with open(system_info_path, 'rb') as file:
        system_info = plistlib.load(file)
        system_info['UnknownCPUKind'] = new_name

    with open(system_info_path, 'wb') as file:
        plistlib.dump(system_info, file)

    print('Processor name updated !')