コード例 #1
0
 def test_nondictroot(self):
     test1 = "abc"
     test2 = [1, 2, 3, "abc"]
     result1 = plistlib.readPlistFromBytes(plistlib.writePlistToBytes(test1))
     result2 = plistlib.readPlistFromBytes(plistlib.writePlistToBytes(test2))
     self.assertEqual(test1, result1)
     self.assertEqual(test2, result2)
コード例 #2
0
	def load_and_save_scopes(self):
		scopes = set()
		for x in os.walk(sublime.packages_path() + '/..'):
			for f in glob.glob(os.path.join(x[0], '*.tmLanguage')):
				for s in self.get_scopes_from(plistlib.readPlist(f)):
					scopes.add(s.strip())

		for x in os.walk(os.path.dirname(sublime.executable_path())):
			for f in glob.glob(os.path.join(x[0], '*.sublime-package')):
				input_zip = ZipFile(f)
				for name in input_zip.namelist():
					if name.endswith('.tmLanguage'):
						for s in self.get_scopes_from(plistlib.readPlistFromBytes(input_zip.read(name))):
							scopes.add(s.strip())

		for x in os.walk(sublime.packages_path() + '/..'):
			for f in glob.glob(os.path.join(x[0], '*.sublime-package')):
				input_zip = ZipFile(f)
				for name in input_zip.namelist():
					if name.endswith('.tmLanguage'):
						for s in self.get_scopes_from(plistlib.readPlistFromBytes(input_zip.read(name))):
							scopes.add(s.strip())
		names = list(scopes)
		scopes = dict()
		for name in names:
			value = name
			if value.startswith('source.'):
				value = value[7:]
			elif value.startswith('text.'):
				value = value[5:]
			scopes[name] = value
		self.settings.set('scopes', scopes)
		sublime.save_settings('smart-pieces.sublime-settings')
コード例 #3
0
ファイル: test_plistlib.py プロジェクト: ngocphu811/Python
 def test_nondictroot(self):
     test1 = "abc"
     test2 = [1, 2, 3, "abc"]
     result1 = plistlib.readPlistFromBytes(
         plistlib.writePlistToBytes(test1))
     result2 = plistlib.readPlistFromBytes(
         plistlib.writePlistToBytes(test2))
     self.assertEqual(test1, result1)
     self.assertEqual(test2, result2)
コード例 #4
0
def parse_header(xmlfile):
    with open(xmlfile, 'rb') as xmlfile_handle:
        #read the first word:
        ba = bytearray(xmlfile_handle.read(8))

        #Replacing this to be python2 friendly
        # #first 4 bytes: header length in long words
        # i = int.from_bytes(ba[:4], byteorder=sys.byteorder)
        # #second 4 bytes: header length in bytes
        # j = int.from_bytes(ba[4:], byteorder=sys.byteorder)

        big_endian = False if sys.byteorder == "little" else True
        i = from_bytes(ba[:4], big_endian=big_endian)
        j = from_bytes(ba[4:], big_endian=big_endian)

        #read in the next that-many bytes
        ba = bytearray(xmlfile_handle.read(j))

        #convert to string
        if sys.version_info[
                0] < 3:  #the readPlistFromBytes method doesn't exist in 2.7
            header_string = ba.decode("utf-8")
            header_dict = plistlib.readPlistFromString(header_string)
        else:
            header_dict = plistlib.readPlistFromBytes(ba)
        return i, j, header_dict
コード例 #5
0
    def test_interop_int(self):
        for testval in (-42, 0, 42, -(2**62), 2**62):
            v = NSArray.arrayWithObject_(testval)
            (
                data,
                error,
            ) = NSKeyedArchiver.archivedDataWithRootObject_requiringSecureCoding_error_(
                v, True, None)

            if data is None:
                self.fail("Cannot create archive: %s" % (error, ))

            with tempfile.NamedTemporaryFile() as fp:
                fp.write(data.bytes())
                fp.flush()

                converted = subprocess.check_output([self.progpath, fp.name])

            converted = readPlistFromBytes(converted)
            self.assertEqual(converted, [testval])

        testval = 2**64
        v = NSArray.arrayWithObject_(testval)
        data = NSKeyedArchiver.archivedDataWithRootObject_(v)

        with tempfile.NamedTemporaryFile() as fp:
            fp.write(data.bytes())
            fp.flush()

            self.assertRaises(
                subprocess.CalledProcessError,
                subprocess.check_output,
                [self.progpath, fp.name],
            )
コード例 #6
0
ファイル: dockutil.py プロジェクト: shaishasag/instl
def readPlist(plist_path):
    """returns a plist object read from a file path"""
    # get the unescaped path
    ###plist_path = path_as_string(plist_path)
    # get a tempfile path for exporting our defaults data
    export_fifo = tempfile.mktemp()
    # make a fifo for defaults export in a temp file
    os.mkfifo(export_fifo)
    # export to the fifo
    osx_version = getOsxVersion()
    if osx_version[1] >= 9:
        subprocess.Popen(['defaults', 'export', plist_path,
                          export_fifo]).communicate()
        # convert the export to xml
        plist_string = subprocess.Popen(
            ['plutil', '-convert', 'xml1', export_fifo, '-o', '-'],
            stdout=subprocess.PIPE).stdout.read()
    else:
        try:
            cmd = ['/usr/libexec/PlistBuddy', '-x', '-c', 'print', plist_path]
            proc = subprocess.Popen(cmd,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
            (plist_string, err) = proc.communicate()
        except Exception as e:
            raise e
    # parse the xml into a dictionary
    pl = plistlib.readPlistFromBytes(plist_string)
    return pl
コード例 #7
0
    def __init__(self, scheme_file, color_filter=None):
        """Initialize."""
        if color_filter is None:
            color_filter = self.filter
        self.legacy = not scheme_file.lower().endswith('.sublime-color-scheme')
        self.color_scheme = path.normpath(scheme_file)
        self.scheme_file = path.basename(self.color_scheme)
        if self.legacy:
            self.scheme_obj = color_filter(
                readPlistFromBytes(
                    re.sub(
                        br"^[\r\n\s]*<!--[\s\S]*?-->[\s\r\n]*|<!--[\s\S]*?-->", b'',
                        sublime.load_binary_resource(sublime_format_path(self.color_scheme))
                    )
                )
            )
        else:
            sublime.decode_value(
                sublime.load_resource(sublime_format_path(self.color_scheme)),
                preserve_lines=True
            )
        self.scheme_file = scheme_file
        self.matched = {}
        self.variables = {}

        self.parse_scheme()
コード例 #8
0
    def test_bytes_deprecated(self):
        pl = {
            'key': 42,
            'sub': {
                'key': 9,
                'alt': 'value',
                'data': b'buffer',
            }
        }
        with self.assertWarns(DeprecationWarning):
            data = plistlib.writePlistToBytes(pl)

        with self.assertWarns(DeprecationWarning):
            pl2 = plistlib.readPlistFromBytes(data)

        self.assertIsInstance(pl2, dict)
        self.assertEqual(
            pl2,
            dict(key=42,
                 sub=dict(
                     key=9,
                     alt='value',
                     data=plistlib.Data(b'buffer'),
                 )))

        with self.assertWarns(DeprecationWarning):
            data2 = plistlib.writePlistToBytes(pl2)
        self.assertEqual(data, data2)
コード例 #9
0
    def uploadToItunesConnect(self,archivePath,filename):
        ipaPath =  "%s/%s/%s.ipa" % (archivePath, filename, filename)
        print ("上传到ItunesConnect")
        altoolPath = "/Applications/Xcode.app/Contents/Applications/Application\ Loader.app/Contents/Frameworks/ITunesSoftwareService.framework/Versions/A/Support/altool"
        validateresult = os.popen ("%s --validate-app -f %s/ -u %s -p %s -t ios --output-format xml" % (
        altoolPath, ipaPath, DeveloperAccountName, DeveloperAccountPWD)).read ()
        uploadresult = os.popen ("%s --upload-app -f %s -u %s -p %s -t ios --output-format xml" % (
        altoolPath, ipaPath, DeveloperAccountName, DeveloperAccountPWD)).read ()

        # 处理plist文件
        pl = plistlib.readPlistFromBytes (str (uploadresult).encode ())

        print (pl["product-errors"])
        print ("输出成功")

        fp = open ("1.plist", 'w')
        fp.write (str (uploadresult))
        fp.close ()

        if ("success-message" in str (uploadresult)):
            print ("上传成功")
        elif ("product-errors" in str (uploadresult)):
            print ("上传失败 %s", uploadresult)
        else:
            print ("未知失败原因")
        return
コード例 #10
0
    def __init__(self, scheme_file, color_filter=None):
        """Initialize."""
        if color_filter is None:
            color_filter = self.filter
        self.color_scheme = path.normpath(scheme_file)
        self.scheme_file = path.basename(self.color_scheme)

        content = sublime.load_binary_resource(
            sublime_format_path(self.color_scheme))
        if scheme_file.lower().endswith(
            ('.tmtheme',
             '.hidden-tmtheme')) or IS_XML_RE.match(content) is not None:
            self.legacy = True
            self.convert_format(
                readPlistFromBytes(XML_COMMENT_RE.sub(b'', content)))
        else:
            self.legacy = False
            self.scheme_obj = sublime.decode_value(content.decode('utf-8'))
            if 'variables' not in self.scheme_obj:
                self.scheme_obj['variables'] = {}
            if GLOBAL_OPTIONS not in self.scheme_obj:
                self.scheme_obj[GLOBAL_OPTIONS] = {}
            if 'rules' not in self.scheme_obj:
                self.scheme_obj['rules'] = []
        self.overrides = []
        if NEW_SCHEMES:
            self.merge_overrides()
        self.scheme_obj = color_filter(self.scheme_obj)
        self.scheme_file = scheme_file
        self.matched = {}
        self.variables = {}

        self.parse_scheme()
コード例 #11
0
    def __init__(self, scheme_file, color_filter=None):
        """Initialize."""
        if color_filter is None:
            color_filter = self.filter
        self.color_scheme = scheme_file.replace('\\', '/')
        self.scheme_file = path.basename(self.color_scheme)

        if NEW_SCHEMES and scheme_file.endswith(('.sublime-color-scheme', '.hidden-color-scheme')):
            self.legacy = False
            self.scheme_obj = {
                'variables': {},
                GLOBAL_OPTIONS: {},
                'rules': []
            }
        else:
            try:
                content = sublime.load_binary_resource(sublime_format_path(self.color_scheme))
            except IOError:
                # Fallback if file was created manually and not yet found in resources
                with open(packages_path(self.color_scheme), 'rb') as f:
                    content = f.read()
            self.legacy = True
            self.convert_format(readPlistFromBytes(XML_COMMENT_RE.sub(b'', content)))
        self.overrides = []
        if NEW_SCHEMES:
            self.merge_overrides()
        self.scheme_file = scheme_file
        self.matched = {}
        self.variables = {}
        self.parse_scheme()
        self.scheme_obj = color_filter(self.scheme_obj)
        self.setup_matcher()
コード例 #12
0
    def test_bytes_deprecated(self):
        pl = {
            'key': 42,
            'sub': {
                'key': 9,
                'alt': 'value',
                'data': b'buffer',
            }
        }
        with self.assertWarns(DeprecationWarning):
            data = plistlib.writePlistToBytes(pl)

        with self.assertWarns(DeprecationWarning):
            pl2 = plistlib.readPlistFromBytes(data)

        self.assertIsInstance(pl2, plistlib._InternalDict)
        self.assertEqual(pl2, plistlib._InternalDict(
            key=42,
            sub=plistlib._InternalDict(
                key=9,
                alt='value',
                data=plistlib.Data(b'buffer'),
            )
        ))

        with self.assertWarns(DeprecationWarning):
            data2 = plistlib.writePlistToBytes(pl2)
        self.assertEqual(data, data2)
コード例 #13
0
def parse_header(xmlfile):
    """
    Opens the given file for binary read ('rb'), then grabs the first 8 bytes
    The first 4 bytes (1 long) of an orca data file are the total length in
    longs of the record
    The next 4 bytes (1 long) is the length of the header in bytes
    The header is then read in ...
    """
    with open(xmlfile, 'rb') as xmlfile_handle:
        #read the first word:
        ba = bytearray(xmlfile_handle.read(8))

        #Replacing this to be python2 friendly
        # #first 4 bytes: header length in long words
        # i = int.from_bytes(ba[:4], byteorder=sys.byteorder)
        # #second 4 bytes: header length in bytes
        # j = int.from_bytes(ba[4:], byteorder=sys.byteorder)

        big_endian = False if sys.byteorder == "little" else True
        i = from_bytes(ba[:4], big_endian=big_endian)
        j = from_bytes(ba[4:], big_endian=big_endian)

        #read in the next that-many bytes that occupy the plist header
        ba = bytearray(xmlfile_handle.read(j))

        #convert to string
        #the readPlistFromBytes method doesn't exist in 2.7
        if sys.version_info[0] < 3:
            header_string = ba.decode("utf-8")
            header_dict = plistlib.readPlistFromString(header_string)
        else:
            header_dict = plistlib.readPlistFromBytes(ba)
        return i, j, header_dict
コード例 #14
0
    def parse_scheme(self):
        HaxeColorScheme.styles = None
        HaxeColorScheme.color_map = None

        color_scheme = self.settings.get('color_scheme')

        try:
            if int(sublime.version()) >= 3000:
                b = sublime.load_binary_resource(color_scheme)
                pl = readPlistFromBytes(b)
            else:
                pl = readPlist(os.path.join(os.path.abspath(
                    sublime.packages_path() + '/..'), color_scheme))
        except:
            return

        def safe_update(fr, to):
            for k in fr.keys():
                if k not in to:
                    to[k] = fr[k]

        dct = {}
        for d in pl.settings:
            if 'settings' not in d:
                continue
            s = d['settings']
            if 'scope' not in d:
                safe_update(s, dct)
            else:
                scope = d['scope']
                scopes = [sc.strip() for sc in scope.split(',')]
                if 'text' in scopes or 'source' in scopes:
                    dct.update(d.settings)

        HaxeColorScheme.color_map = dct
コード例 #15
0
ファイル: theme_tweaker.py プロジェクト: hackur/ThemeTweaker
    def redo(self):
        """Redo last reverted change."""

        self._setup(noedit=True)

        if self.theme_valid:
            plist = re.sub(
                br"^[\r\n\s]*<!--[\s\S]*?-->[\s\r\n]*|<!--[\s\S]*?-->", b'',
                sublime.load_binary_resource(self.scheme_map["original"]))
            redo = self.scheme_map["redo"].split(";")
            if len(redo) == 0 or (len(redo) == 1 and redo[0] == ""):
                log("Nothing to redo!", status=True)
                return
            undo = self.scheme_map["undo"].split(";")
            undo.append(redo.pop())
            self.scheme_map["redo"] = ";".join(redo)
            self.scheme_map["undo"] = ";".join(undo)
            self.plist_file = ColorSchemeTweaker().tweak(
                readPlistFromBytes(plist), self.scheme_map["undo"])
            with open(self.scheme_clone, "wb") as f:
                f.write(writePlistToBytes(self.plist_file))
                self.p_settings["scheme_map"] = self.scheme_map
                self._save_tweak_settings()
        else:
            log("Theme has not been tweaked!", status=True)
コード例 #16
0
ファイル: test_plistlib.py プロジェクト: ngocphu811/Python
 def test_bytes(self):
     pl = self._create()
     data = plistlib.writePlistToBytes(pl)
     pl2 = plistlib.readPlistFromBytes(data)
     self.assertEqual(dict(pl), dict(pl2))
     data2 = plistlib.writePlistToBytes(pl2)
     self.assertEqual(data, data2)
コード例 #17
0
    def __init__(self,
                 scheme_file,
                 strip_trans=False,
                 ignore_gutter=False,
                 track_dark_background=False,
                 filter=None):
        if filter is None:
            filter = self.filter
        self.color_scheme = path.normpath(scheme_file)
        self.scheme_file = path.basename(self.color_scheme)
        if ST3:
            self.plist_file = filter(
                readPlistFromBytes(
                    sublime.load_binary_resource(
                        sublime_format_path(self.color_scheme))))
        else:
            self.plist_file = filter(
                readPlist(sublime.packages_path() +
                          self.color_scheme.replace('Packages', '')))
        self.scheme_file = scheme_file
        self.strip_trans = strip_trans
        self.ignore_gutter = ignore_gutter
        self.track_dark_background = track_dark_background
        self.dark_lumens = None
        self.matched = {}

        self.parse_scheme()
コード例 #18
0
    def test_interop_int(self):
        for testval in (-42, 0, 42, -2**62, 2**62):
            v = NSArray.arrayWithObject_(testval)
            data = NSKeyedArchiver.archivedDataWithRootObject_(v)

            with tempfile.NamedTemporaryFile() as fp:
                fp.write(data.bytes())
                fp.flush()

                converted = subprocess.check_output(
                    [self.progpath, 'keyed', fp.name])

            converted = readPlistFromBytes(converted)
            self.assertEqual(converted, [testval])

        testval = 2**64
        v = NSArray.arrayWithObject_(testval)
        data = NSKeyedArchiver.archivedDataWithRootObject_(v)

        with tempfile.NamedTemporaryFile() as fp:
            fp.write(data.bytes())
            fp.flush()

            self.assertRaises(subprocess.CalledProcessError,
                              subprocess.check_output,
                              [self.progpath, 'keyed', fp.name])
コード例 #19
0
ファイル: ColorSchemeEditor.py プロジェクト: 42iscool42/MCC
	def edit_plist_color_scheme(original_color_scheme):
		scheme_data = plistlib.readPlistFromBytes(sublime.load_binary_resource(original_color_scheme))
		if os.path.exists(sublime.packages_path() + "/MCC/ModifiedColorSchemes/" + scheme_data["name"] + ".tmTheme"):
			sublime.load_settings("Preferences.sublime-settings").set("color_scheme", "Packages/MCC/ModifiedColorSchemes/" + scheme_data["name"] + ".tmTheme")
			sublime.save_settings("Preferences.sublime-settings")
			return
		elif scheme_data["name"].find("(MCC)") > -1:
			return

		try:
			new_background_rgb = "#000000"
			if "background" in scheme_data["settings"][0]["settings"]:
				new_background_rgb = ColorSchemeEditor.change_color_by_one(scheme_data["settings"][0]["settings"]["background"])
			
			scheme_data = ColorSchemeEditor.add_mcc_scopes(scheme_data, False, new_background_rgb)

			if not os.path.exists(sublime.packages_path() + "/MCC/ModifiedColorSchemes/"):
				os.makedirs(sublime.packages_path() + "/MCC/ModifiedColorSchemes/")

			new_file_name = "/MCC/ModifiedColorSchemes/" + scheme_data["name"] + ".tmTheme"
			scheme_data["name"] = scheme_data["name"] + " (MCC)"
			plistlib.writePlist(scheme_data, sublime.packages_path() + new_file_name)

			sublime.load_settings("Preferences.sublime-settings").set("color_scheme", "Packages" + new_file_name)
			sublime.save_settings("Preferences.sublime-settings")
		except Exception as e:
			# sublime.error_message("MCC couldn't convert your current color scheme")
			print("Error on tmTheme conversion")
			print(e)
			sublime.active_window().run_command("show_panel", {"panel": "console", "toggle": True})
コード例 #20
0
    def __init__(self, scheme_file, color_filter=None):
        """Initialize."""
        if color_filter is None:
            color_filter = self.filter
        self.color_scheme = scheme_file.replace('\\', '/')
        self.scheme_file = path.basename(self.color_scheme)

        if NEW_SCHEMES and scheme_file.endswith(('.sublime-color-scheme', '.hidden-color-scheme')):
            self.legacy = False
            self.scheme_obj = {
                'variables': {},
                GLOBAL_OPTIONS: {},
                'rules': []
            }
        else:
            try:
                content = sublime.load_binary_resource(sublime_format_path(self.color_scheme))
            except IOError:
                # Fallback if file was created manually and not yet found in resources
                with open(packages_path(self.color_scheme), 'rb') as f:
                    content = f.read()
            self.legacy = True
            self.convert_format(readPlistFromBytes(XML_COMMENT_RE.sub(b'', content)))
        self.overrides = []
        if NEW_SCHEMES:
            self.merge_overrides()
        self.scheme_file = scheme_file
        self.matched = {}
        self.variables = {}
        self.parse_scheme()
        self.scheme_obj = color_filter(self.scheme_obj)
        self.setup_matcher()
コード例 #21
0
    def test_interop_int(self):
        for testval in (
                    -42,
                    0,
                    42,
                    -2**62,
                    2**62
                ):
            v = NSArray.arrayWithObject_(testval)
            data = NSKeyedArchiver.archivedDataWithRootObject_(v)

            with tempfile.NamedTemporaryFile() as fp:
                fp.write(data.bytes())
                fp.flush()

                converted = subprocess.check_output([self.progpath, 'keyed', fp.name])

            converted = readPlistFromBytes(converted)
            self.assertEqual(converted, [testval])

        testval = 2**64
        v = NSArray.arrayWithObject_(testval)
        data = NSKeyedArchiver.archivedDataWithRootObject_(v)

        with tempfile.NamedTemporaryFile() as fp:
            fp.write(data.bytes())
            fp.flush()

            self.assertRaises(subprocess.CalledProcessError, subprocess.check_output, [self.progpath, 'keyed', fp.name])
コード例 #22
0
def toggle():
    current_color_scheme = sublime.load_settings(
        "Preferences.sublime-settings").get("color_scheme").replace("\\", "/")
    packages_path = sublime.packages_path().replace("\\", "/")
    cache_path = sublime.cache_path().replace("\\", "/")
    package_name, theme_file, relative_path_to_theme_file = get_current_color_scheme_parts(
        current_color_scheme)

    current_theme = plistlib.readPlistFromBytes(
        sublime.load_binary_resource(current_color_scheme))
    non_cfml_settings = [
        row for row in current_theme["settings"]
        if "scope" not in row or not row["scope"].endswith("cfml")
    ]

    # if there are no cfml styles, then add them, else remove them (i.e. toggle)
    adding_styles = len(non_cfml_settings) == len(current_theme["settings"])
    if adding_styles:
        current_theme["settings"].extend(get_style_settings())
    else:
        current_theme["settings"] = non_cfml_settings

    if adding_styles or not is_installed_package(package_name):
        directory_exists = create_directory_if_not_exists(
            packages_path + "/" + relative_path_to_theme_file)
        if not directory_exists:
            return
        plistlib.writePlist(
            current_theme, packages_path + "/" + relative_path_to_theme_file +
            "/" + theme_file)
    else:
        remove_directory_if_exists(packages_path + "/" + package_name)
        remove_file_if_exists(cache_path + "/" + relative_path_to_theme_file +
                              "/" + theme_file + ".cache")
コード例 #23
0
    def __init__(self, scheme_file, color_filter=None):
        """Initialize."""
        if color_filter is None:
            color_filter = self.filter
        self.color_scheme = path.normpath(scheme_file)
        self.scheme_file = path.basename(self.color_scheme)

        if NEW_SCHEMES and scheme_file.endswith('.sublime-color-scheme'):
            self.legacy = False
            self.scheme_obj = {
                'variables': {},
                GLOBAL_OPTIONS: {},
                'rules': []
            }
        else:
            content = sublime.load_binary_resource(
                sublime_format_path(self.color_scheme))
            self.legacy = True
            self.convert_format(
                readPlistFromBytes(XML_COMMENT_RE.sub(b'', content)))
        self.overrides = []
        if NEW_SCHEMES:
            self.merge_overrides()
        self.scheme_obj = color_filter(self.scheme_obj)
        self.scheme_file = scheme_file
        self.matched = {}
        self.variables = {}

        self.parse_scheme()
コード例 #24
0
    def __init__(self, scheme_file, color_filter=None):
        """Initialize."""
        if color_filter is None:
            color_filter = self.filter
        self.legacy = not scheme_file.lower().endswith(
            '.sublime-color-scheme') if NEW_SCHEMES else True
        self.color_scheme = path.normpath(scheme_file)
        self.scheme_file = path.basename(self.color_scheme)
        if self.legacy:
            scheme_obj = readPlistFromBytes(
                re.sub(
                    br"^[\r\n\s]*<!--[\s\S]*?-->[\s\r\n]*|<!--[\s\S]*?-->",
                    b'',
                    sublime.load_binary_resource(
                        sublime_format_path(self.color_scheme))))
            self.convert_format(scheme_obj)
        else:
            self.scheme_obj = sublime.decode_value(
                sublime.load_resource(sublime_format_path(self.color_scheme)))
            if 'variables' not in self.scheme_obj:
                self.scheme_obj['variables'] = {}
            if GLOBAL_OPTIONS not in self.scheme_obj:
                self.scheme_obj[GLOBAL_OPTIONS] = {}
            if 'rules' not in self.scheme_obj:
                self.scheme_obj['rules'] = []
        self.overrides = []
        if NEW_SCHEMES:
            self.merge_overrides()
        self.scheme_obj = color_filter(self.scheme_obj)
        self.scheme_file = scheme_file
        self.matched = {}
        self.variables = {}

        self.parse_scheme()
コード例 #25
0
ファイル: Main.py プロジェクト: c0ns0le/NvUpdate
async def getLatest():
    os.chdir(os.path.dirname(os.path.abspath(__file__)))

    url = "https://gfe.nvidia.com/mac-update"

    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            webpage = await response.text()

    pl = webpage.encode("utf-8")
    plist = plistlib.readPlistFromBytes(pl)

    total_size = 0
    data = b""
    async with aiohttp.ClientSession() as downloader:
        async with downloader.get(url) as downloaded:
            assert downloaded.status == 200
            while True:
                chunk = await downloaded.content.read(4 * 1024)
                data += chunk
                total_size += len(chunk)
                if not chunk:
                    break

    name = "WebDriver-{}.pkg".format(plist["updates"][0]["version"])
    with open(name, 'wb') as package:
        package.write(data)

    print(
        "Version {} downloaded in the place where you ran this script. Exiting..."
        .format(plist["updates"][0]["version"]))
    print("Good day/night!")
    sys.exit(0)
コード例 #26
0
 def test_bytes(self):
     pl = self._create()
     data = plistlib.writePlistToBytes(pl)
     pl2 = plistlib.readPlistFromBytes(data)
     self.assertEqual(dict(pl), dict(pl2))
     data2 = plistlib.writePlistToBytes(pl2)
     self.assertEqual(data, data2)
コード例 #27
0
    def create_user_custom_theme(self, colors):
        if len(colors) == 0:
            return

        preferences = sublime.load_settings("Preferences.sublime-settings")
        preferences_cs = preferences.get('color_scheme')

        cs_base = os.path.basename(preferences_cs)

        if cs_base[0:15] != "CustomHighlight":
            new_cs_base = "CustomHighlight" + cs_base
        else:
            new_cs_base = cs_base

        custom_color_base = self._create_custom_color_scheme_directory()

        new_cs_absolute = os.path.join(custom_color_base, new_cs_base)
        new_cs = "Packages/" + self.new_color_scheme_path + "/" + new_cs_base
        try:
            package, resource = get_package_and_resource_name(preferences_cs)
            if VERSION > 3000:
                binary_data = get_binary_resource(package, resource)
                cs_plist = plistlib.readPlistFromBytes(binary_data)
            else:
                preferences_cs_absolute = os.path.join(sublime.packages_path(),
                                                       "..",
                                                       preferences_cs)
                cs_plist = plistlib.readPlist(preferences_cs_absolute)
        except:
            sublime.error_message("An error occured while reading color " +
                                  "scheme file. Please check the console "
                                  "for details.")
            raise
        updates_made, color_scheme = self._add_colors_to_scheme(cs_plist,
                                                                colors)

        if updates_made or preferences_cs != new_cs:
            plistlib.writePlist(color_scheme, new_cs_absolute)

        if preferences_cs != new_cs:
            if ColorSchemeManager.update_preferences:
                okay = sublime.ok_cancel_dialog("Would you like to change " +
                                                "your color scheme to '" +
                                                new_cs + "'? " + "This is " +
                                                "where the custom colors " +
                                                "are being saved. By " +
                                                "clicking cancel you will " +
                                                "not be reminded again in " +
                                                "this session. " +
                                                "To permanently disable " +
                                                "this prompt, set " +
                                                "'prompt_new_color_scheme' " +
                                                "to false in the settings")

                if okay:
                    preferences.set("color_scheme", new_cs)
                    sublime.save_settings("Preferences.sublime-settings")
                else:
                    ColorSchemeManager.update_preferences = False
コード例 #28
0
 def __init__(self, catalog, product_id):
     if (sys.version_info > (3, 0)):
         root = plistlib.readPlistFromBytes(catalog)
     else:
         root = plistlib.readPlistFromString(catalog)
     products = root['Products']
     self.date = root['IndexDate']
     self.product = products[product_id]
コード例 #29
0
def load_plist(relative_path):
    try:
        plist_data = plistlib.readPlistFromBytes(sublime.load_binary_resource(relative_path))
        print("CFML: loaded plist file - " + relative_path)
        return plist_data
    except:
        print("CFML: unable to load plist file - " + relative_path)
        return None
コード例 #30
0
ファイル: syntax.py プロジェクト: kaiser101/Packages
def get_hidden_tmlanguage_metadata(path):
    tree = plistlib.readPlistFromBytes(path.read_bytes())

    return {
        'name': path.stem,  # `name` key is ignored
        'hidden': True,  # `hidden` key is ignored
        'scope': tree.get('scopeName'),
    }
コード例 #31
0
ファイル: syntax.py プロジェクト: kaiser101/Packages
def get_tmlanguage_metadata(path):
    tree = plistlib.readPlistFromBytes(path.read_bytes())

    return {
        'name': tree.get('name') or path.stem,
        'hidden': tree.get('hidden', False),
        'scope': tree.get('scopeName'),
    }
コード例 #32
0
ファイル: MsSQLKit.py プロジェクト: pepone42/MsSQLKit
def apply_theme(view):
    theme_settings = sublime.load_resource(view.settings().get('color_scheme'))
    theme = readPlistFromBytes(theme_settings.encode("utf-8"))
    mskit.applyTheme(view.settings().get('font_face'),
                     view.settings().get('font_size'),
                     theme["settings"][0]["settings"]["background"][:7],
                     theme["settings"][0]["settings"]["foreground"][:7],
                     theme["settings"][0]["settings"]["selection"][:7])
コード例 #33
0
    def infoPlistFrom(self, buffer):
        info = {}
        try:
            info = plistlib.readPlistFromBytes(buffer)
        except:
            pass

        return info
コード例 #34
0
	def modify_color_scheme(l,s,read_original = False):
		prefs = sublime.load_settings("Preferences.sublime-settings")
		read_original = read_original and prefs.has("original_color_scheme")
		if read_original and prefs.get('color_scheme').find('/Colorcoder/') == -1:
			read_original = False
		if prefs.get('original_color_scheme').find('/\(Colorcoded\)/') != -1:
			print("original theme already colorcoded, abort")
			return
		global modification_running
		if modification_running:
			return
		modification_running = True
		name = prefs.get("original_color_scheme") if read_original else sublime.active_window().active_view().settings().get('color_scheme')
		try:
			cs = plistlib.readPlistFromBytes(sublime.load_binary_resource(name))

			tokenclr = "#000000"
			for rule in cs["settings"]:
				if "scope" not in rule and "name" not in rule:
					bgc = rule["settings"]["background"]
					r = int(bgc[1:3],16)
					g = int(bgc[3:5],16)
					b = int(bgc[5:7],16)
					if b>0:
						b = b-1
					elif g>0:
						g = g-1
					elif r>0:
						r = r-1
					else:
						rule["settings"]["background"] = "#000001"
					tokenclr =  "#%02x%02x%02x" % (r,g,b)
					break

			cs["name"] = cs["name"] + " (Colorcoded)"

			for x in range(0,256):
				cs["settings"].append(dict(
					scope="cc0x%x" % x,
					settings=dict(
						foreground="#"+''.join(map(lambda c: "%02x" % int(256*c),colorsys.hls_to_rgb(x/256., l, s))),
						background=tokenclr
					)
				))

			newname = "/%s (Colorcoded).tmTheme" % re.search("/([^/]+).tmTheme$", name).group(1)
			plistlib.writePlist(cs,"%s%s" % (colorshemeemodifier.get_save_dir(),newname))

			prefs.set("original_color_scheme", name)
			prefs.set("color_scheme","Packages%s%s" % (colorshemeemodifier.get_relative_save_dir(), newname))
			sublime.save_settings("Preferences.sublime-settings")
		except Exception as e:
			sublime.error_message("Colorcoder was not able to parse the colorscheme\nCheck the console for the actual error message.")
			sublime.active_window().run_command("show_panel", {"panel": "console", "toggle": True})
			print(e)

		finally:
			modification_running = False
コード例 #35
0
def convert(fname):
    if fname.startswith('Packages/'):
        s = sublime.load_resource(fname)
    else:
        with open(fname, 'r', encoding='utf-8') as f:
            s = f.read()
    l = plistlib.readPlistFromBytes(s.encode("utf-8"))

    if "repository" in l:
        repository = l["repository"]
    else:
        repository = {}

    # normalize the repository values into being a list of patterns
    for key, value in repository.items():
        if "begin" in value or "match" in value:
            repository[key] = [value]
        else:
            repository[key] = value["patterns"]

    contexts = {"main": make_context(l["patterns"], repository)}

    for key, value in repository.items():
        assert (key != "main")

        contexts[key] = make_context(value, repository)

    syn = {}

    if "comment" in l:
        comment = format_comment(l["comment"])
        if len(comment) > 0:
            syn["comment"] = comment

    if "name" in l:
        syn["name"] = l["name"]

    if "scopeName" in l:
        syn["scope"] = l["scopeName"]

    if "fileTypes" in l:
        syn["file_extensions"] = l["fileTypes"]

    if "firstLineMatch" in l:
        syn["first_line_match"] = l["firstLineMatch"]

    if "hideFromUser" in l:
        syn["hidden"] = l["hideFromUser"]

    if "hidden" in l:
        syn["hidden"] = l["hidden"]
    elif fname.endswith('.hidden-tmLanguage'):
        syn["hidden"] = True

    syn["contexts"] = contexts

    return syn
コード例 #36
0
ファイル: scheme_lum.py プロジェクト: marcos0x/Sublime-Text-3
def scheme_lums(scheme_file):
    color_scheme = os.path.normpath(scheme_file)
    scheme_file = os.path.basename(color_scheme)
    plist_file = readPlistFromBytes(
        sublime.load_binary_resource(sublime_format_path(color_scheme)))

    color_settings = plist_file["settings"][0]["settings"]
    rgba = RGBA(color_settings.get("background", '#FFFFFF'))
    return rgba.luminance()
コード例 #37
0
def load_plist(relative_path):
    try:
        plist_data = plistlib.readPlistFromBytes(
            sublime.load_binary_resource(relative_path))
        print("CFML: loaded plist file - " + relative_path)
        return plist_data
    except:
        print("CFML: unable to load plist file - " + relative_path)
        return None
コード例 #38
0
    def load_scheme(self):
        color_scheme_removed_comments = re.sub(r"<!--.+-->", '', self.color_scheme)
        plist_file = plistlib.readPlistFromBytes(bytes(color_scheme_removed_comments, 'UTF-8'))

        for rule in plist_file["settings"]:
            if rule.get('settings', {}).get('caret', None):
                self.general_colors = rule.get('settings', {})
            for setting in ['foreground', 'background']:
                c = rule.get('settings', {}).get(setting, None)
                c and self.schemecolors.add(c)
コード例 #39
0
    def __init__(self, scheme_file):
        """Initialize."""

        self.plist_file = readPlistFromBytes(
            re_strip_xml_comments.sub(
                b'', sublime.load_binary_resource(scheme_file)))
        self.text = ''
        self.colors = OrderedDict()
        self.scheme_file = scheme_file
        self.gen_css()
コード例 #40
0
def _available_services():
    '''
    Return a dictionary of all available services on the system
    '''
    available_services = dict()
    for launch_dir in _launchd_paths():
        for root, dirs, files in os.walk(launch_dir):
            for file_name in files:

                # Must be a plist file
                if not file_name.endswith('.plist'):
                    continue

                # Follow symbolic links of files in _launchd_paths
                file_path = os.path.join(root, file_name)
                true_path = os.path.realpath(file_path)

                # ignore broken symlinks
                if not os.path.exists(true_path):
                    continue

                try:
                    # This assumes most of the plist files
                    # will be already in XML format
                    with salt.utils.fopen(file_path):
                        plist = plistlib.readPlist(true_path)

                except Exception:
                    # If plistlib is unable to read the file we'll need to use
                    # the system provided plutil program to do the conversion
                    cmd = '/usr/bin/plutil -convert xml1 -o - -- "{0}"'.format(
                        true_path)
                    plist_xml = __salt__['cmd.run'](cmd,
                                                    output_loglevel='quiet')
                    if six.PY2:
                        plist = plistlib.readPlistFromString(plist_xml)
                    else:
                        plist = plistlib.readPlistFromBytes(
                            salt.utils.to_bytes(plist_xml))

                try:
                    available_services[plist.Label.lower()] = {
                        'file_name': file_name,
                        'file_path': true_path,
                        'plist': plist
                    }
                except AttributeError:
                    # Handle malformed plist files
                    available_services[os.path.basename(file_name).lower()] = {
                        'file_name': file_name,
                        'file_path': true_path,
                        'plist': plist
                    }

    return available_services
コード例 #41
0
ファイル: convert_syntax.py プロジェクト: 52M/st3-zh_CN
def convert(fname):
    if fname.startswith('Packages/'):
        s = sublime.load_resource(fname)
    else:
        with open(fname, 'r', encoding='utf-8') as f:
            s = f.read()
    l = plistlib.readPlistFromBytes(s.encode("utf-8"))

    if "repository" in l:
        repository = l["repository"]
    else:
        repository = {}

    # normalize the repository values into being a list of patterns
    for key, value in repository.items():
        if "begin" in value or "match" in value:
            repository[key] = [value]
        else:
            repository[key] = value["patterns"]

    contexts = {"main": make_context(l["patterns"], repository)}

    for key, value in repository.items():
        assert(key != "main")

        contexts[key] = make_context(value, repository)

    syn = {}

    if "comment" in l:
        comment = format_comment(l["comment"])
        if len(comment) > 0:
            syn["comment"] = comment

    if "name" in l:
        syn["name"] = l["name"]

    if "scopeName" in l:
        syn["scope"] = l["scopeName"]

    if "fileTypes" in l:
        syn["file_extensions"] = l["fileTypes"]

    if "firstLineMatch" in l:
        syn["first_line_match"] = l["firstLineMatch"]

    if "hideFromUser" in l:
        syn["hidden"] = l["hideFromUser"]

    if "hidden" in l:
        syn["hidden"] = l["hidden"]

    syn["contexts"] = contexts

    return syn
コード例 #42
0
    def parse_scheme(self):
        if sublime is None or \
                sublime.active_window() is None or \
                sublime.active_window().active_view() is None:
            return

        if self.settings is None:
            self.settings = sublime.load_settings(
                'Preferences.sublime-settings')
            self.settings.add_on_change('color_scheme',
                                        lambda: self.parse_scheme())

        color_scheme = self.settings.get(
            'color_scheme', 'Packages/Color Scheme - Default/Monokai.tmTheme')

        if self.color_scheme == color_scheme and self.color_map is not None:
            return

        self.color_scheme = color_scheme
        self.styles = None
        self.color_map = None

        try:
            if int(sublime.version()) >= 3000:
                b = sublime.load_binary_resource(color_scheme)
                pl = readPlistFromBytes(b)
            else:
                pl = readPlist(
                    os.path.join(
                        os.path.abspath(sublime.packages_path() + '/..'),
                        color_scheme))
        except:
            print(traceback.print_exc())
            return

        def safe_update(fr, to):
            for k in fr.keys():
                if k not in to:
                    to[k] = fr[k]

        dct = {}
        for d in pl.settings:
            if 'settings' not in d:
                continue
            s = d['settings']
            if 'scope' not in d:
                safe_update(s, dct)
            else:
                scope = d['scope']
                scopes = [sc.strip() for sc in scope.split(',')]
                if 'text' in scopes or 'source' in scopes:
                    dct.update(d.settings)

        self.color_map = dct
コード例 #43
0
    def create_user_custom_theme(self, colors):
        if len(colors) == 0:
            return

        preferences = sublime.load_settings("Preferences.sublime-settings")
        preferences_cs = preferences.get('color_scheme')

        cs_base = os.path.basename(preferences_cs)

        if cs_base[0:15] != "CustomHighlight":
            new_cs_base = "CustomHighlight" + cs_base
        else:
            new_cs_base = cs_base

        custom_color_base = self._create_custom_color_scheme_directory()

        new_cs_absolute = os.path.join(custom_color_base, new_cs_base)
        new_cs = "Packages/" + self.new_color_scheme_path + "/" + new_cs_base
        try:
            package, resource = get_package_and_resource_name(preferences_cs)
            if VERSION > 3000:
                binary_data = get_binary_resource(package, resource)
                cs_plist = plistlib.readPlistFromBytes(binary_data)
            else:
                preferences_cs_absolute = os.path.join(sublime.packages_path(),
                                                       "..", preferences_cs)
                cs_plist = plistlib.readPlist(preferences_cs_absolute)
        except:
            sublime.error_message("An error occured while reading color " +
                                  "scheme file. Please check the console "
                                  "for details.")
            raise
        updates_made, color_scheme = self._add_colors_to_scheme(
            cs_plist, colors)

        if updates_made or preferences_cs != new_cs:
            plistlib.writePlist(color_scheme, new_cs_absolute)

        if preferences_cs != new_cs:
            if ColorSchemeManager.update_preferences:
                okay = sublime.ok_cancel_dialog("Would you like to change " +
                                                "your color scheme to '" +
                                                new_cs + "'? " + "This is " +
                                                "where the custom colors " +
                                                "are being saved. By " +
                                                "clicking cancel you will " +
                                                "not be reminded again in " +
                                                "this session")

                if okay:
                    preferences.set("color_scheme", new_cs)
                    sublime.save_settings("Preferences.sublime-settings")
                else:
                    ColorSchemeManager.update_preferences = False
コード例 #44
0
    def load_scheme(self):
        color_scheme_removed_comments = re.sub(r"<!--.+-->", '',
                                               self.color_scheme)
        plist_file = plistlib.readPlistFromBytes(
            bytes(color_scheme_removed_comments, 'UTF-8'))

        for rule in plist_file["settings"]:
            if rule.get('settings', {}).get('caret', None):
                self.general_colors = rule.get('settings', {})
            for setting in ['foreground', 'background']:
                c = rule.get('settings', {}).get(setting, None)
                c and self.schemecolors.add(c)
コード例 #45
0
ファイル: scheme_lum.py プロジェクト: marcos0x/Sublime-Text-3
def scheme_lums(scheme_file):
    color_scheme = os.path.normpath(scheme_file)
    scheme_file = os.path.basename(color_scheme)
    plist_file = readPlistFromBytes(
        sublime.load_binary_resource(
            sublime_format_path(color_scheme)
        )
    )

    color_settings = plist_file["settings"][0]["settings"]
    rgba = RGBA(color_settings.get("background", '#FFFFFF'))
    return rgba.luminance()
コード例 #46
0
def get_background():
    bgclr = '#000000'
    global STV
    if STV >= 3150:
        style = get_style()
        bgclr = style.get('background')
    else:
        cschm = prefs.get('color_scheme')
        cstxt = str(sublime.load_resource(cschm))
        treep = plistlib.readPlistFromBytes(cstxt.encode())
        bgclr = treep['settings'][0]['settings']['background']
    return bgclr
コード例 #47
0
    def parse_scheme(self):
        if sublime is None or \
                sublime.active_window() is None or \
                sublime.active_window().active_view() is None:
            return

        if self.settings is None:
            self.settings = sublime.load_settings(
                'Preferences.sublime-settings')
            self.settings.add_on_change(
                'color_scheme', lambda: self.parse_scheme())

        color_scheme = self.settings.get(
            'color_scheme', 'Packages/Color Scheme - Default/Monokai.tmTheme')

        if self.color_scheme == color_scheme and self.color_map is not None:
            return

        self.color_scheme = color_scheme
        self.styles = None
        self.color_map = None

        try:
            if int(sublime.version()) >= 3000:
                b = sublime.load_binary_resource(color_scheme)
                pl = readPlistFromBytes(b)
            else:
                pl = readPlist(os.path.join(os.path.abspath(
                    sublime.packages_path() + '/..'), color_scheme))
        except:
            print(traceback.print_exc())
            return

        def safe_update(fr, to):
            for k in fr.keys():
                if k not in to:
                    to[k] = fr[k]

        dct = {}
        for d in pl.settings:
            if 'settings' not in d:
                continue
            s = d['settings']
            if 'scope' not in d:
                safe_update(s, dct)
            else:
                scope = d['scope']
                scopes = [sc.strip() for sc in scope.split(',')]
                if 'text' in scopes or 'source' in scopes:
                    dct.update(d.settings)

        self.color_map = dct
コード例 #48
0
ファイル: mac_service.py プロジェクト: bryson/salt
def _available_services():
    '''
    Return a dictionary of all available services on the system
    '''
    available_services = dict()
    for launch_dir in _launchd_paths():
        for root, dirs, files in os.walk(launch_dir):
            for file_name in files:

                # Must be a plist file
                if not file_name.endswith('.plist'):
                    continue

                # Follow symbolic links of files in _launchd_paths
                file_path = os.path.join(root, file_name)
                true_path = os.path.realpath(file_path)

                # ignore broken symlinks
                if not os.path.exists(true_path):
                    continue

                try:
                    # This assumes most of the plist files
                    # will be already in XML format
                    with salt.utils.fopen(file_path):
                        plist = plistlib.readPlist(true_path)

                except Exception:
                    # If plistlib is unable to read the file we'll need to use
                    # the system provided plutil program to do the conversion
                    cmd = '/usr/bin/plutil -convert xml1 -o - -- "{0}"'.format(
                        true_path)
                    plist_xml = __salt__['cmd.run'](cmd, output_loglevel='quiet')
                    if six.PY2:
                        plist = plistlib.readPlistFromString(plist_xml)
                    else:
                        plist = plistlib.readPlistFromBytes(
                            salt.utils.to_bytes(plist_xml))

                try:
                    available_services[plist.Label.lower()] = {
                        'file_name': file_name,
                        'file_path': true_path,
                        'plist': plist}
                except AttributeError:
                    # Handle malformed plist files
                    available_services[os.path.basename(file_name).lower()] = {
                        'file_name': file_name,
                        'file_path': true_path,
                        'plist': plist}

    return available_services
コード例 #49
0
ファイル: convert_syntax.py プロジェクト: 52M/st3-zh_CN
def build_scope_map():
    syntax_by_scope = {}
    for f in sublime.find_resources("*.tmLanguage"):
        try:
            s = sublime.load_resource(f)
            l = plistlib.readPlistFromBytes(s.encode("utf-8"))
            if "scopeName" in l:
                fname = os.path.splitext(f)[0] + ".sublime-syntax"
                syntax_by_scope[l["scopeName"]] = os.path.basename(fname)
        except:
            pass

    return syntax_by_scope
コード例 #50
0
    def test_interop_string(self):
        for testval in (b"hello world".decode("utf-8"), "goodbye moon"):
            v = NSArray.arrayWithObject_(testval)
            data = NSKeyedArchiver.archivedDataWithRootObject_(v)

            with tempfile.NamedTemporaryFile() as fp:
                fp.write(data.bytes())
                fp.flush()

                converted = subprocess.check_output([self.progpath, "keyed", fp.name])

            converted = readPlistFromBytes(converted)
            self.assertEqual(converted, [testval])
コード例 #51
0
    def test_interop_float(self):
        for testval in (-4.5, 0, 5.5e10):
            v = NSArray.arrayWithObject_(testval)
            data = NSKeyedArchiver.archivedDataWithRootObject_(v)

            with tempfile.NamedTemporaryFile() as fp:
                fp.write(data.bytes())
                fp.flush()

                converted = subprocess.check_output([self.progpath, "keyed", fp.name])

            converted = readPlistFromBytes(converted)
            self.assertEqual(converted, [testval])
コード例 #52
0
    def test_interop_dict(self):
        for testval in ({"a": "b", "c": 42},):

            data = NSArchiver.archivedDataWithRootObject_(testval)

            with tempfile.NamedTemporaryFile() as fp:
                fp.write(data.bytes())
                fp.flush()

                converted = subprocess.check_output([self.progpath, "plain", fp.name])

            converted = readPlistFromBytes(converted)
            self.assertEqual(converted, testval)
コード例 #53
0
    def __init__(self, scheme_file):
        """Initialize."""

        self.plist_file = readPlistFromBytes(
            re_strip_xml_comments.sub(
                b'',
                sublime.load_binary_resource(scheme_file)
            )
        )
        self.text = ''
        self.colors = OrderedDict()
        self.scheme_file = scheme_file
        self.gen_css()
コード例 #54
0
ファイル: loaders.py プロジェクト: MattDMo/PackageDev
    def parse(self, *args, **kwargs):
        # Note: I hate Plist and XML. And it doesn't help a bit that parsing
        # plist files is a REAL PITA.
        text = get_text(self.view)

        # Parsing will fail if `<?xml version="1.0" encoding="UTF-8"?>` encoding is in the first
        # line, so strip it.
        # XXX: Find a better way to fix this misbehaviour of xml stuff in Python
        #      (I mean, plistliv even "writes" that line)
        if text.startswith('<?xml version="1.0" encoding="UTF-8"?>'):
            text = text[38:]

        # See https://github.com/SublimeText/AAAPackageDev/issues/34
        if ST2 and isinstance(text, unicode):  # NOQA
            text = text.encode('utf-8')

        if use_plistlib:
            try:
                # This will try `from xml.parsers.expat import ParserCreate`
                # but since it is already tried above it should succeed.
                if ST2:
                    data = plistlib.readPlistFromString(text)
                else:
                    data = plistlib.readPlistFromBytes(text.encode('utf-8'))
            except ExpatError as e:
                self.output.write_line(self.debug_base
                                       % (self.file_path,
                                          ErrorString(e.code),
                                          e.lineno,
                                          e.offset)
                                       )
            # except BaseException as e:
            #     # Whatever could happen here ...
            #     self.output.write_line(self.debug_base % (self.file_path, str(e), 0, 0))
            else:
                return data
        else:
            # falling back to plist_parser
            from xml.sax._exceptions import SAXReaderNotAvailable
            try:
                data = plist_parser.parse_string(text)
            except plist_parser.PropertyListParseError as e:
                self.output.write_line(self.debug_base % (self.file_path, str(e), 0, 0))
            except SAXReaderNotAvailable:
                # https://github.com/SublimeText/AAAPackageDev/issues/48
                self.output.write_line("Unable to parse Property List because of missing XML "
                                       "parsers in your Python environment.\n"
                                       "Please use Sublime Text 3 or reinstall Python 2.6 "
                                       "on your system.")
            else:
                return data
コード例 #55
0
ファイル: file.py プロジェクト: NiksonX/GitSavvy
def determine_syntax_files():
    syntax_files = sublime.find_resources("*.tmLanguage")
    for syntax_file in syntax_files:
        try:
            # Use `sublime.load_resource`, in case Package is `*.sublime-package`.
            resource = sublime.load_resource(syntax_file)
            plist = readPlistFromBytes(bytearray(resource, encoding="utf-8"))
            for extension in plist["fileTypes"]:
                if extension not in syntax_file_map:
                    syntax_file_map[extension] = []
                extension_list = syntax_file_map[extension]
                extension_list.append(syntax_file)
        except:
            continue
コード例 #56
0
ファイル: iresign.py プロジェクト: xuda/iResign-1
    def read_plist_from_string(data):
        """
        Parse a given data and return a plist object. If a given data has a
        binary signature it will be striped before parsing.
        """
        data = data.decode('latin1')

        # strip binary signature if exists
        beg, end = '<?xml', '</plist>'
        beg, end = data.index(beg), data.index(end) + len(end)
        data = data[beg: end]

        data = data.encode('latin1')
        return plistlib.readPlistFromBytes(data)
コード例 #57
0
ファイル: loaders.py プロジェクト: Adarma/AAAPackageDev
    def parse(self, *args, **kwargs):
        # Note: I hate Plist and XML. And it doesn't help a bit that parsing
        # plist files is a REAL PITA.
        text = get_text(self.view)

        # Parsing will fail if `<?xml version="1.0" encoding="UTF-8"?>` encoding is in the first
        # line, so strip it.
        # XXX: Find a better way to fix this misbehaviour of xml stuff in Python
        #      (I mean, plistliv even "writes" that line)
        if text.startswith('<?xml version="1.0" encoding="UTF-8"?>'):
            text = text[38:]

        # See https://github.com/SublimeText/AAAPackageDev/issues/34
        if ST2 and isinstance(text, unicode):
            text = text.encode('utf-8')

        try:
            from xml.parsers.expat import ExpatError, ErrorString
        except ImportError:
            # xml.parsers.expat is not available on certain Linux dists, use plist_parser then.
            # See https://github.com/SublimeText/AAAPackageDev/issues/19
            import plist_parser
            print("[AAAPackageDev] Using plist_parser")

            try:
                data = plist_parser.parse_string(text)
            except plist_parser.PropertyListParseError as e:
                self.output.write_line(self.debug_base % (self.file_path, str(e), 0, 0))
            else:
                return data
        else:
            try:
                # This will try `from xml.parsers.expat import ParserCreate`
                # but since it is already tried above it should succeed.
                if ST2:
                    data = plistlib.readPlistFromString(text)
                else:
                    data = plistlib.readPlistFromBytes(text.encode('utf-8'))
            except ExpatError as e:
                self.output.write_line(self.debug_base
                                       % (self.file_path,
                                          ErrorString(e.code),
                                          e.lineno,
                                          e.offset)
                                       )
            except BaseException as e:
                # Whatever could happen here ...
                self.output.write_line(self.debug_base % (self.file_path, str(e), 0, 0))
            else:
                return data
コード例 #58
0
ファイル: consumer.py プロジェクト: dave-shawley/rejected
    def _load_plist_value(value):
        """Deserialize a plist string returning the native Python data type
        for the value.

        :param str value: The pickle string
        :rtype: dict

        """
        if hasattr(plistlib, 'loads'):
            return plistlib.loads(value)
        try:
            return plistlib.readPlistFromString(value)
        except AttributeError:
            return plistlib.readPlistFromBytes(value)
コード例 #59
0
    def test_interop_seq(self):
        for testval in (["a", "b", 3], ("a", "b", 3)):

            data = NSArchiver.archivedDataWithRootObject_(testval)

            with tempfile.NamedTemporaryFile() as fp:
                fp.write(data.bytes())
                fp.flush()

                converted = subprocess.check_output([self.progpath, "plain", fp.name])

            converted = readPlistFromBytes(converted)
            self.assertIs(type(converted), list)
            self.assertEqual(converted, list(testval))