def test_keysort_bytesio(self):
pl = collections.OrderedDict()
pl['b'] = 1
pl['a'] = 2
pl['c'] = 3
for fmt in ALL_FORMATS:
for sort_keys in (False, True):
with self.subTest(fmt=fmt, sort_keys=sort_keys):
b = BytesIO()
plistlib.dump(pl, b, fmt=fmt, sort_keys=sort_keys)
pl2 = plistlib.load(BytesIO(b.getvalue()),
dict_type=collections.OrderedDict)
self.assertEqual(dict(pl), dict(pl2))
if sort_keys:
self.assertEqual(list(pl2.keys()), ['a', 'b', 'c'])
else:
self.assertEqual(list(pl2.keys()), ['b', 'a', 'c'])
python类load()的实例源码
def _mac_ver_xml():
fn = '/System/Library/CoreServices/SystemVersion.plist'
if not os.path.exists(fn):
return None
try:
import plistlib
except ImportError:
return None
with open(fn, 'rb') as f:
pl = plistlib.load(f)
release = pl['ProductVersion']
versioninfo = ('', '', '')
machine = os.uname().machine
if machine in ('ppc', 'Power Macintosh'):
# Canonical name
machine = 'PowerPC'
return release, versioninfo, machine
def test_keysort_bytesio(self):
pl = collections.OrderedDict()
pl['b'] = 1
pl['a'] = 2
pl['c'] = 3
for fmt in ALL_FORMATS:
for sort_keys in (False, True):
with self.subTest(fmt=fmt, sort_keys=sort_keys):
b = BytesIO()
plistlib.dump(pl, b, fmt=fmt, sort_keys=sort_keys)
pl2 = plistlib.load(BytesIO(b.getvalue()),
dict_type=collections.OrderedDict)
self.assertEqual(dict(pl), dict(pl2))
if sort_keys:
self.assertEqual(list(pl2.keys()), ['a', 'b', 'c'])
else:
self.assertEqual(list(pl2.keys()), ['b', 'a', 'c'])
def _mac_ver_xml():
fn = '/System/Library/CoreServices/SystemVersion.plist'
if not os.path.exists(fn):
return None
try:
import plistlib
except ImportError:
return None
with open(fn, 'rb') as f:
pl = plistlib.load(f)
release = pl['ProductVersion']
versioninfo = ('', '', '')
machine = os.uname().machine
if machine in ('ppc', 'Power Macintosh'):
# Canonical name
machine = 'PowerPC'
return release, versioninfo, machine
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))
def set_application_binary(self, binary: str = None) -> None:
"""
Sets the binary that will be patched.
If a binary is not defined, the applications Info.plist is parsed
and the CFBundleIdentifier key read.
:param binary:
:return:
"""
if binary is not None:
click.secho('Using user provided binary name of: {0}'.format(binary))
self.app_binary = os.path.join(self.app_folder, binary)
return
with open(os.path.join(self.app_folder, 'Info.plist'), 'rb') as f:
info_plist = plistlib.load(f)
# print the bundle identifier
click.secho('Bundle identifier is: {0}'.format(info_plist['CFBundleIdentifier']),
fg='green', bold=True)
self.app_binary = os.path.join(self.app_folder, info_plist['CFBundleExecutable'])
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')
def __get_plist_values(info_plist_path, key):
"""
??Plist?value
:param info_plist_path: Info.plist ???
:param key: ?????key
:return: key???value
"""
with open(info_plist_path, 'rb') as fp:
plist = plistlib.load(fp)
return plist.get(key)
def set_info(self, k, v):
"""
Set a value for a given key in an app's base project info.plist
"""
info = self.get_info()
with open(self.info, 'wb') as f:
# Note that we have to write the entire contents to the file.
# so we load the current data, add whatever we need to it then
info[k] = v
plistlib.dump(info, f)
def get_info(self, k=None):
"""
Get the value for a key in the an app's base project info.plist
"""
info = None
with open(self.info, 'rb') as f:
info = plistlib.load(f)
if k:
return info.get(k)
else:
return info
def test_io(self):
pl = self._create()
with open(support.TESTFN, 'wb') as fp:
plistlib.dump(pl, fp)
with open(support.TESTFN, 'rb') as fp:
pl2 = plistlib.load(fp)
self.assertEqual(dict(pl), dict(pl2))
self.assertRaises(AttributeError, plistlib.dump, pl, 'filename')
self.assertRaises(AttributeError, plistlib.load, 'filename')
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 test_io(self):
pl = self._create()
with open(support.TESTFN, 'wb') as fp:
plistlib.dump(pl, fp)
with open(support.TESTFN, 'rb') as fp:
pl2 = plistlib.load(fp)
self.assertEqual(dict(pl), dict(pl2))
self.assertRaises(AttributeError, plistlib.dump, pl, 'filename')
self.assertRaises(AttributeError, plistlib.load, 'filename')
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 _validate_read_data_types_metainfo_plist(self):
metainfo_plist_path = os.path.join(self.ufopath, 'metainfo.plist')
res = Result(metainfo_plist_path)
ss = StdStreamer(metainfo_plist_path)
try:
meta_dict = load(metainfo_plist_path)
if 'formatVersion' in meta_dict.keys():
if isinstance(meta_dict['formatVersion'], int):
res.test_failed = False
ss.stream_result(res)
else:
res.test_failed = True
res.exit_failure = True # early exit if fails
res.test_long_stdstream_string = metainfo_plist_path + " 'formatVersion' value must be specified as" \
" an integer"
ss.stream_result(res)
else:
res.test_failed = True
res.exit_failure = True # early exit if fails
res.test_long_stdstream_string = "Failed to read the 'formatVersion' value in " + metainfo_plist_path
ss.stream_result(res)
except Exception as e:
res.test_failed = True
res.exit_failure = True # early exit if fails
res.test_long_stdstream_string = "Failed to read the 'formatVersion' value in " \
"the file " + metainfo_plist_path + ". Error: " + str(e)
ss.stream_result(res)
def _validate_read_load_glyphsdirs_layercontents_plist(self):
layercontents_plist_path = os.path.join(self.ufopath, 'layercontents.plist')
res = Result(layercontents_plist_path)
ss = StdStreamer(layercontents_plist_path)
try:
# loads as [ ['layername1', 'glyphsdir1'], ['layername2', 'glyphsdir2'] ]
self.ufo_glyphs_dir_list = load(layercontents_plist_path)
res.test_failed = False
ss.stream_result(res)
except Exception as e:
res.test_failed = True
res.exit_failure = True
res.test_long_stdstream_string = "Failed to read " + layercontents_plist_path + ". Error: " + str(e)
ss.stream_result(res)
check_resource_file_validity.py 文件源码
项目:st_package_reviewer
作者: packagecontrol
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def check(self):
plist_file_globs = {
"**/*.tmLanguage",
"**/*.tmPreferences",
"**/*.tmSnippet",
"**/*.tmTheme",
}
for file_path in self.globs(*plist_file_globs):
with self.file_context(file_path):
with file_path.open('rb') as f:
try:
plistlib.load(f)
except (ValueError, ExpatError) as e:
self.fail("Invalid Plist", exception=e)
def __init__(self):
# ????????? ???? ?? ???????????
if isfile('/usr/local/bin/terminal-notifier'):
self.notifier = True
else:
self.notifier = False
# ????? ?????? ?? parser.py
self.session = Session()
# ?????????? ??????
self.root_dir = dirname(abspath(__file__))
# ????????? ? ??????
# ??????? ??? ?????? ? ????? ?? ????????
chdir(self.root_dir)
# ????? ????????
self.plugins_dir = join(self.root_dir, 'plugins')
# ????? ????????
self.configs_dir = join(self.root_dir, 'configs')
# ????? ??????
self.icons_dir = join(self.root_dir, 'icons')
# ?????, ???? ????? ???????????? ??????????? ???????
self.series_dir = join(environ['HOME'], 'Movies', '???????')
# ????????? ??????? ? ????? ??????
self.name = self.__class__.__name__
# ????????? ? ????? ????????
chdir(self.configs_dir)
# ????????? ??? ??????? ???????? ???????
self.config_path = join(self.configs_dir, '%s.plist' % self.name)
# ???? ??? - ?????? ?????? ? ????? ???????????, ??????? ???? ????????????
if not isfile(self.config_path):
dump({'old_links': [''], 'subscriptions': [''], 'quality': '720p', 'excluding': ['']},
open(self.config_path, 'wb'))
exit(0)
self.settings = AttrDict(load(open(self.config_path, 'rb')))
# ???? ????? ???????? ?? ?????????? ???? ??? ???, ??????? ??
if not isdir(self.series_dir):
mkdir(self.series_dir)
chdir(self.series_dir)
def _change_build_version(self):
""" set CFBundleVersion and CFBundleShortVersionString.
"""
build_version_list = self._build_version.split('.')
cf_bundle_short_version_string = '.'.join(build_version_list[:3])
with open(self._plist_path, 'rb') as fp:
plist_content = plistlib.load(fp)
plist_content['CFBundleShortVersionString'] = cf_bundle_short_version_string
plist_content['CFBundleVersion'] = self._build_version
with open(self._plist_path, 'wb') as fp:
plistlib.dump(plist_content, fp)