本文整理汇总了Python中zeroinstall.support.basedir.save_cache_path函数的典型用法代码示例。如果您正苦于以下问题:Python save_cache_path函数的具体用法?Python save_cache_path怎么用?Python save_cache_path使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了save_cache_path函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testList
def testList(self):
iface_cache = self.config.iface_cache
self.assertEqual([], iface_cache.list_all_interfaces())
iface_dir = basedir.save_cache_path(config_site, 'interfaces')
open(os.path.join(iface_dir, 'http%3a%2f%2ffoo'), 'w').close()
self.assertEqual(['http://foo'],
iface_cache.list_all_interfaces())
示例2: do_exec_binding
def do_exec_binding(self, binding, iface):
assert iface is not None
name = binding.name
if '/' in name or name.startswith('.') or "'" in name:
raise SafeException("Invalid <executable> name '%s'" % name)
exec_dir = basedir.save_cache_path(namespaces.config_site, namespaces.config_prog, 'executables', name)
exec_path = os.path.join(exec_dir, name + ".exe" if os.name == "nt" else name)
if not self._checked_runenv:
self._check_runenv()
if not os.path.exists(exec_path):
if os.name == "nt":
# Copy runenv.cli.template to ~/.cache/0install.net/injector/executables/$name/$name
import shutil
shutil.copyfile(os.environ['ZEROINSTALL_CLI_TEMPLATE'], exec_path)
else:
# Symlink ~/.cache/0install.net/injector/executables/$name/$name to runenv.py
os.symlink('../../runenv.py', exec_path)
os.chmod(exec_dir, 0o500)
if binding.in_path:
path = os.environ["PATH"] = exec_dir + os.pathsep + os.environ["PATH"]
logger.info("PATH=%s", path)
else:
os.environ[name] = exec_path
logger.info("%s=%s", name, exec_path)
args = self.build_command(iface, binding.command)
if os.name == "nt":
os.environ["0install-runenv-file-" + name + ".exe"] = args[0]
os.environ["0install-runenv-args-" + name + ".exe"] = support.windows_args_escape(args[1:])
else:
import json
os.environ["0install-runenv-" + name] = json.dumps(args)
示例3: cache_iface
def cache_iface(self, name, data):
cached_ifaces = basedir.save_cache_path('0install.net',
'interfaces')
f = open(os.path.join(cached_ifaces, model.escape(name)), 'w')
f.write(data)
f.close()
示例4: testTimes
def testTimes(self):
iface_cache = self.config.iface_cache
with tempfile.TemporaryFile() as stream:
stream.write(data.thomas_key)
stream.seek(0)
gpg.import_key(stream)
upstream_dir = basedir.save_cache_path(config_site, 'interfaces')
cached = os.path.join(upstream_dir, model.escape('http://foo'))
with open(cached, 'wb') as stream:
stream.write(data.foo_signed_xml)
signed = iface_cache._get_signature_date('http://foo')
assert signed == None
trust.trust_db.trust_key(
'92429807C9853C0744A68B9AAE07828059A53CC1')
signed = iface_cache._get_signature_date('http://foo')
self.assertEqual(1154850229, signed)
with open(cached, 'w+b') as stream:
stream.seek(0)
stream.write(b'Hello')
# When the signature is invalid, we just return None.
# This is because versions < 0.22 used to corrupt the signatue
# by adding an attribute to the XML
signed = iface_cache._get_signature_date('http://foo')
assert signed == None
示例5: do_exec_binding
def do_exec_binding(self, binding, iface):
assert iface is not None
name = binding.name
if '/' in name or name.startswith('.') or "'" in name:
raise SafeException("Invalid <executable> name '%s'" % name)
exec_dir = basedir.save_cache_path(namespaces.config_site, namespaces.config_prog, 'executables', name)
exec_path = os.path.join(exec_dir, name)
if not self._checked_runenv:
self._check_runenv()
if not os.path.exists(exec_path):
# Symlink ~/.cache/0install.net/injector/executables/$name/$name to runenv.py
os.symlink('../../runenv.py', exec_path)
os.chmod(exec_dir, 0o500)
if binding.in_path:
path = os.environ["PATH"] = exec_dir + os.pathsep + os.environ["PATH"]
info("PATH=%s", path)
else:
os.environ[name] = exec_path
info("%s=%s", name, exec_path)
import json
args = self.build_command(iface, binding.command)
os.environ["0install-runenv-" + name] = json.dumps(args)
示例6: testXMLupdate
def testXMLupdate(self):
iface_cache = self.config.iface_cache
trust.trust_db.trust_key(
'92429807C9853C0744A68B9AAE07828059A53CC1')
with tempfile.TemporaryFile() as stream:
stream.write(data.thomas_key)
stream.seek(0)
gpg.import_key(stream)
iface = iface_cache.get_interface('http://foo')
with tempfile.TemporaryFile() as src:
src.write(data.foo_signed_xml)
src.seek(0)
pending = PendingFeed(iface.uri, src)
assert iface_cache.update_feed_if_trusted(iface.uri, pending.sigs, pending.new_xml)
iface_cache.__init__()
feed = iface_cache.get_feed('http://foo')
assert feed.last_modified == 1154850229
# mtimes are unreliable because copying often changes them -
# check that we extract the time from the signature when upgrading
upstream_dir = basedir.save_cache_path(config_site, 'interfaces')
cached = os.path.join(upstream_dir, model.escape(feed.url))
os.utime(cached, None)
iface_cache.__init__()
feed = iface_cache.get_feed('http://foo')
assert feed.last_modified > 1154850229
with tempfile.TemporaryFile() as src:
src.write(data.new_foo_signed_xml)
src.seek(0)
pending = PendingFeed(feed.url, src)
old_stdout = sys.stdout
sys.stdout = StringIO()
try:
assert iface_cache.update_feed_if_trusted(feed.url, pending.sigs, pending.new_xml, dry_run = True)
finally:
sys.stdout = old_stdout
assert iface_cache.update_feed_if_trusted(feed.url, pending.sigs, pending.new_xml)
# Can't 'update' to an older copy
with tempfile.TemporaryFile() as src:
src.write(data.foo_signed_xml)
src.seek(0)
try:
pending = PendingFeed(feed.url, src)
assert iface_cache.update_feed_if_trusted(feed.url, pending.sigs, pending.new_xml)
assert 0
except model.SafeException:
pass
示例7: _import_new_feed
def _import_new_feed(self, feed_url, new_xml, modified_time):
"""Write new_xml into the cache.
@param feed_url: the URL for the feed being updated
@param new_xml: the data to write
@param modified_time: when new_xml was modified
@raises ReplayAttack: if the new mtime is older than the current one
"""
assert modified_time
assert isinstance(new_xml, bytes), repr(new_xml)
upstream_dir = basedir.save_cache_path(config_site, 'interfaces')
cached = os.path.join(upstream_dir, escape(feed_url))
old_modified = None
if os.path.exists(cached):
with open(cached, 'rb') as stream:
old_xml = stream.read()
if old_xml == new_xml:
logger.debug(_("No change"))
# Update in-memory copy, in case someone else updated the disk copy
self.get_feed(feed_url, force = True)
return
old_modified = int(os.stat(cached).st_mtime)
# Do we need to write this temporary file now?
try:
with open(cached + '.new', 'wb') as stream:
stream.write(new_xml)
os.utime(cached + '.new', (modified_time, modified_time))
new_mtime = reader.check_readable(feed_url, cached + '.new')
assert new_mtime == modified_time
old_modified = self._get_signature_date(feed_url) or old_modified
if old_modified:
if new_mtime < old_modified:
raise ReplayAttack(_("New feed's modification time is "
"before old version!\nInterface: %(iface)s\nOld time: %(old_time)s\nNew time: %(new_time)s\n"
"Refusing update.")
% {'iface': feed_url, 'old_time': _pretty_time(old_modified), 'new_time': _pretty_time(new_mtime)})
if new_mtime == old_modified:
# You used to have to update the modification time manually.
# Now it comes from the signature, this check isn't useful
# and often causes problems when the stored format changes
# (e.g., when we stopped writing last-modified attributes)
pass
#raise SafeException("Interface has changed, but modification time "
# "hasn't! Refusing update.")
except:
os.unlink(cached + '.new')
raise
portable_rename(cached + '.new', cached)
logger.debug(_("Saved as %s") % cached)
self.get_feed(feed_url, force = True)
示例8: mark_as_checking
def mark_as_checking(self, url):
"""Touch a 'last_check_attempt_timestamp' file for this feed.
If url is a local path, nothing happens.
This prevents us from repeatedly trying to download a failing feed many
times in a short period."""
if os.path.isabs(url):
return
feeds_dir = basedir.save_cache_path(config_site, config_prog, 'last-check-attempt')
timestamp_path = os.path.join(feeds_dir, model._pretty_escape(url))
fd = os.open(timestamp_path, os.O_WRONLY | os.O_CREAT, 0644)
os.close(fd)
os.utime(timestamp_path, None) # In case file already exists
示例9: download_and_add_icon
def download_and_add_icon():
stream = dl.tempfile
yield dl.downloaded
try:
tasks.check(dl.downloaded)
if dl.unmodified: return
stream.seek(0)
import shutil
icons_cache = basedir.save_cache_path(config_site, 'interface_icons')
icon_file = file(os.path.join(icons_cache, escape(interface.uri)), 'w')
shutil.copyfileobj(stream, icon_file)
except Exception as ex:
self.handler.report_error(ex)
示例10: __init__
def __init__(self, cache_leaf, source, format):
"""Maintain a cache file (e.g. ~/.cache/0install.net/injector/$name).
If the size or mtime of $source has changed, or the cache
format version if different, reset the cache first."""
self.cache_leaf = cache_leaf
self.source = source
self.format = format
self.cache_dir = basedir.save_cache_path(namespaces.config_site,
namespaces.config_prog)
self.cached_for = {} # Attributes of source when cache was created
try:
self._load_cache()
except Exception as ex:
logger.info(_("Failed to load cache (%s). Flushing..."), ex)
self.flush()
示例11: import_feed
def import_feed(self, url, contents):
"""contents can be a path or an Element."""
iface_cache = self.config.iface_cache
iface_cache.get_interface(url)
if isinstance(contents, qdom.Element):
feed = model.ZeroInstallFeed(contents)
else:
feed = reader.load_feed(contents)
iface_cache._feeds[url] = feed
xml = qdom.to_UTF8(feed.feed_element)
upstream_dir = basedir.save_cache_path(namespaces.config_site, "interfaces")
cached = os.path.join(upstream_dir, model.escape(url))
with open(cached, "wb") as stream:
stream.write(xml)
return feed
示例12: download_and_add_icon
def download_and_add_icon():
stream = dl.tempfile
try:
yield dl.downloaded
tasks.check(dl.downloaded)
if dl.unmodified: return
stream.seek(0)
import shutil, tempfile
icons_cache = basedir.save_cache_path(config_site, 'interface_icons')
tmp_file = tempfile.NamedTemporaryFile(dir = icons_cache, delete = False)
shutil.copyfileobj(stream, tmp_file)
tmp_file.close()
icon_file = os.path.join(icons_cache, escape(interface.uri))
portable_rename(tmp_file.name, icon_file)
finally:
stream.close()
示例13: _check_runenv
def _check_runenv(self):
# Create the runenv.py helper script under ~/.cache if missing or out-of-date
main_dir = basedir.save_cache_path(namespaces.config_site, namespaces.config_prog)
runenv = os.path.join(main_dir, 'runenv.py')
expected_contents = "#!%s\nfrom zeroinstall.injector import _runenv; _runenv.main()\n" % sys.executable
actual_contents = None
if os.path.exists(runenv):
with open(runenv) as s:
actual_contents = s.read()
if actual_contents != expected_contents:
import tempfile
tmp = tempfile.NamedTemporaryFile('w', dir = main_dir, delete = False)
info("Updating %s", runenv)
tmp.write(expected_contents)
tmp.close()
os.chmod(tmp.name, 0555)
os.rename(tmp.name, runenv)
self._checked_runenv = True
示例14: _import_new_feed
def _import_new_feed(self, feed_url, new_xml, modified_time, dry_run):
"""Write new_xml into the cache.
@param feed_url: the URL for the feed being updated
@type feed_url: str
@param new_xml: the data to write
@type new_xml: str
@param modified_time: when new_xml was modified
@type modified_time: int
@type dry_run: bool
@raises ReplayAttack: if the new mtime is older than the current one"""
assert modified_time
assert isinstance(new_xml, bytes), repr(new_xml)
upstream_dir = basedir.save_cache_path(config_site, "interfaces")
cached = os.path.join(upstream_dir, escape(feed_url))
old_modified = None
if os.path.exists(cached):
with open(cached, "rb") as stream:
old_xml = stream.read()
if old_xml == new_xml:
logger.debug(_("No change"))
# Update in-memory copy, in case someone else updated the disk copy
self.get_feed(feed_url, force=True)
return
old_modified = int(os.stat(cached).st_mtime)
if dry_run:
print(_("[dry-run] would cache feed {url} as {cached}").format(url=feed_url, cached=cached))
from io import BytesIO
from zeroinstall.injector import qdom
root = qdom.parse(BytesIO(new_xml), filter_for_version=True)
feed = model.ZeroInstallFeed(root)
reader.update_user_feed_overrides(feed)
self._feeds[feed_url] = feed
return
# Do we need to write this temporary file now?
try:
with open(cached + ".new", "wb") as stream:
stream.write(new_xml)
os.utime(cached + ".new", (modified_time, modified_time))
new_mtime = reader.check_readable(feed_url, cached + ".new")
assert new_mtime == modified_time
old_modified = self._get_signature_date(feed_url) or old_modified
if old_modified:
if new_mtime < old_modified:
raise ReplayAttack(
_(
"New feed's modification time is "
"before old version!\nInterface: %(iface)s\nOld time: %(old_time)s\nNew time: %(new_time)s\n"
"Refusing update."
)
% {
"iface": feed_url,
"old_time": _pretty_time(old_modified),
"new_time": _pretty_time(new_mtime),
}
)
if new_mtime == old_modified:
# You used to have to update the modification time manually.
# Now it comes from the signature, this check isn't useful
# and often causes problems when the stored format changes
# (e.g., when we stopped writing last-modified attributes)
pass
# raise SafeException("Interface has changed, but modification time "
# "hasn't! Refusing update.")
except:
os.unlink(cached + ".new")
raise
portable_rename(cached + ".new", cached)
logger.debug(_("Saved as %s") % cached)
self.get_feed(feed_url, force=True)
示例15: testBinding
def testBinding(self):
local_impl = os.path.dirname(os.path.abspath(__file__))
tmp = tempfile.NamedTemporaryFile(mode = 'wt')
tmp.write(
"""<?xml version="1.0" ?>
<interface
main='testdriver.py'
xmlns="http://zero-install.sourceforge.net/2004/injector/interface">
<name>Bar</name>
<summary>Bar</summary>
<description>Bar</description>
<group>
<requires interface='%s'>
<environment name='FOO_PATH' insert='.'/>
<environment name='BAR_PATH' insert='.' default='/a:/b'/>
<environment name='NO_PATH' value='val'/>
<environment name='XDG_DATA_DIRS' insert='.'/>
</requires>
<environment name='SELF_GROUP' insert='group' mode='replace'/>
<implementation version='1.0' id='%s'>
<environment name='SELF_IMPL' insert='impl' mode='replace'/>
</implementation>
</group>
</interface>""" % (foo_iface_uri, local_impl))
tmp.flush()
self.cache_iface(foo_iface_uri,
"""<?xml version="1.0" ?>
<interface last-modified="0"
uri="%s"
xmlns="http://zero-install.sourceforge.net/2004/injector/interface">
<name>Foo</name>
<summary>Foo</summary>
<description>Foo</description>
<implementation version='1.0' id='sha1=123'/>
</interface>""" % foo_iface_uri)
cached_impl = basedir.save_cache_path('0install.net',
'implementations',
'sha1=123')
driver = Driver(requirements = Requirements(tmp.name), config = self.config)
self.config.network_use = model.network_offline
os.environ['FOO_PATH'] = "old"
old, sys.stdout = sys.stdout, StringIO()
try:
download_and_execute(driver, ['Hello'])
finally:
sys.stdout = old
self.assertEqual(cached_impl + '/.:old',
os.environ['FOO_PATH'])
self.assertEqual(cached_impl + '/.:/a:/b',
os.environ['BAR_PATH'])
self.assertEqual('val', os.environ['NO_PATH'])
self.assertEqual(os.path.join(local_impl, 'group'), os.environ['SELF_GROUP'])
self.assertEqual(os.path.join(local_impl, 'impl'), os.environ['SELF_IMPL'])
del os.environ['FOO_PATH']
if 'XDG_DATA_DIRS' in os.environ:
del os.environ['XDG_DATA_DIRS']
os.environ['BAR_PATH'] = '/old'
old, sys.stdout = sys.stdout, StringIO()
try:
download_and_execute(driver, ['Hello'])
finally:
sys.stdout = old
self.assertEqual(cached_impl + '/.',
os.environ['FOO_PATH'])
self.assertEqual(cached_impl + '/.:/old',
os.environ['BAR_PATH'])
self.assertEqual(cached_impl + '/.:/usr/local/share:/usr/share',
os.environ['XDG_DATA_DIRS'])