Allow passing a selections document in place of a feed
[zeroinstall/zeroinstall-limyreth.git] / zeroinstall / injector / reader.py
blob01c0af8a7ea3961b8438068bc1c86e36ff69744f
1 """
2 Parses an XML feed into a Python representation. You should probably use L{iface_cache.iface_cache} rather than the functions here.
3 """
5 # Copyright (C) 2009, Thomas Leonard
6 # See the README file for details, or visit http://0install.net.
8 from zeroinstall import _
9 import os
10 from logging import debug, info, warn
12 from zeroinstall.support import basedir
13 from zeroinstall.injector import qdom, distro
14 from zeroinstall.injector.namespaces import config_site, config_prog, XMLNS_IFACE
15 from zeroinstall.injector.model import Interface, InvalidInterface, ZeroInstallFeed, escape, Feed, stability_levels
16 from zeroinstall.injector import model
18 def update_from_cache(interface):
19 """Read a cached interface and any native feeds or user overrides.
20 @param interface: the interface object to update
21 @type interface: L{model.Interface}
22 @return: True if cached version and user overrides loaded OK.
23 False if upstream not cached. Local interfaces (starting with /) are
24 always considered to be cached, although they are not actually stored in the cache.
25 Internal: use L{iface_cache.IfaceCache.get_interface} instread.
26 @rtype: bool"""
27 interface.reset()
28 from zeroinstall.injector.iface_cache import iface_cache
30 # Add the distribution package manager's version, if any
31 path = basedir.load_first_data(config_site, 'native_feeds', model._pretty_escape(interface.uri))
32 if path:
33 # Resolve any symlinks
34 info(_("Adding native packager feed '%s'"), path)
35 interface.extra_feeds.append(Feed(os.path.realpath(path), None, False))
37 update_user_overrides(interface)
39 main_feed = iface_cache.get_feed(interface.uri, force = True)
40 if main_feed:
41 update_user_feed_overrides(main_feed)
43 return main_feed is not None
45 def load_feed_from_cache(url, selections_ok = False):
46 """Load a feed. If the feed is remote, load from the cache. If local, load it directly.
47 @return: the feed, or None if it's remote and not cached."""
48 try:
49 if os.path.isabs(url):
50 debug(_("Loading local feed file '%s'"), url)
51 return load_feed(url, local = True, selections_ok = selections_ok)
52 else:
53 cached = basedir.load_first_cache(config_site, 'interfaces', escape(url))
54 if cached:
55 debug(_("Loading cached information for %(interface)s from %(cached)s"), {'interface': url, 'cached': cached})
56 return load_feed(cached, local = False)
57 else:
58 return None
59 except InvalidInterface, ex:
60 ex.feed_url = url
61 raise
63 def update_user_feed_overrides(feed):
64 """Update a feed with user-supplied information.
65 Sets last_checked and user_stability ratings.
66 @param feed: feed to update
67 @since 0.49
68 """
69 user = basedir.load_first_config(config_site, config_prog,
70 'feeds', model._pretty_escape(feed.url))
71 if user is None:
72 # For files saved by 0launch < 0.49
73 user = basedir.load_first_config(config_site, config_prog,
74 'user_overrides', escape(feed.url))
75 if not user:
76 return
78 try:
79 root = qdom.parse(file(user))
80 except Exception, ex:
81 warn(_("Error reading '%(user)s': %(exception)s"), {'user': user, 'exception': ex})
82 raise
84 last_checked = root.getAttribute('last-checked')
85 if last_checked:
86 feed.last_checked = int(last_checked)
88 for item in root.childNodes:
89 if item.uri != XMLNS_IFACE: continue
90 if item.name == 'implementation':
91 id = item.getAttribute('id')
92 assert id is not None
93 impl = feed.implementations.get(id, None)
94 if not impl:
95 debug(_("Ignoring user-override for unknown implementation %(id)s in %(interface)s"), {'id': id, 'interface': feed})
96 continue
98 user_stability = item.getAttribute('user-stability')
99 if user_stability:
100 impl.user_stability = stability_levels[str(user_stability)]
102 def update_user_overrides(interface):
103 """Update an interface with user-supplied information.
104 Sets preferred stability and updates extra_feeds.
105 @param interface: the interface object to update
106 @type interface: L{model.Interface}
108 user = basedir.load_first_config(config_site, config_prog,
109 'interfaces', model._pretty_escape(interface.uri))
110 if user is None:
111 # For files saved by 0launch < 0.49
112 user = basedir.load_first_config(config_site, config_prog,
113 'user_overrides', escape(interface.uri))
114 if not user:
115 return
117 try:
118 root = qdom.parse(file(user))
119 except Exception, ex:
120 warn(_("Error reading '%(user)s': %(exception)s"), {'user': user, 'exception': ex})
121 raise
123 stability_policy = root.getAttribute('stability-policy')
124 if stability_policy:
125 interface.set_stability_policy(stability_levels[str(stability_policy)])
127 for item in root.childNodes:
128 if item.uri != XMLNS_IFACE: continue
129 if item.name == 'feed':
130 feed_src = item.getAttribute('src')
131 if not feed_src:
132 raise InvalidInterface(_('Missing "src" attribute in <feed>'))
133 interface.extra_feeds.append(Feed(feed_src, item.getAttribute('arch'), True, langs = item.getAttribute('langs')))
135 def check_readable(feed_url, source):
136 """Test whether a feed file is valid.
137 @param feed_url: the feed's expected URL
138 @type feed_url: str
139 @param source: the name of the file to test
140 @type source: str
141 @return: the modification time in src (usually just the mtime of the file)
142 @rtype: int
143 @raise InvalidInterface: If the source's syntax is incorrect,
145 try:
146 feed = load_feed(source, local = False)
148 if feed.url != feed_url:
149 raise InvalidInterface(_("Incorrect URL used for feed.\n\n"
150 "%(feed_url)s is given in the feed, but\n"
151 "%(interface_uri)s was requested") %
152 {'feed_url': feed.url, 'interface_uri': feed_url})
153 return feed.last_modified
154 except InvalidInterface, ex:
155 info(_("Error loading feed:\n"
156 "Interface URI: %(uri)s\n"
157 "Local file: %(source)s\n"
158 "%(exception)s") %
159 {'uri': feed_url, 'source': source, 'exception': ex})
160 raise InvalidInterface(_("Error loading feed '%(uri)s':\n\n%(exception)s") % {'uri': feed_url, 'exception': ex})
162 def update(interface, source, local = False):
163 """Read in information about an interface.
164 Deprecated.
165 @param interface: the interface object to update
166 @type interface: L{model.Interface}
167 @param source: the name of the file to read
168 @type source: str
169 @param local: use file's mtime for last-modified, and uri attribute is ignored
170 @raise InvalidInterface: if the source's syntax is incorrect
171 @return: the new feed (since 0.32)
172 @see: L{update_from_cache}, which calls this"""
173 assert isinstance(interface, Interface)
175 feed = load_feed(source, local)
177 if not local:
178 if feed.url != interface.uri:
179 raise InvalidInterface(_("Incorrect URL used for feed.\n\n"
180 "%(feed_url)s is given in the feed, but\n"
181 "%(interface_uri)s was requested") %
182 {'feed_url': feed.url, 'interface_uri': interface.uri})
184 # Hack.
185 from zeroinstall.injector.iface_cache import iface_cache
186 iface_cache._feeds[unicode(interface.uri)] = feed
188 return feed
190 def load_feed(source, local = False, selections_ok = False):
191 """Load a feed from a local file.
192 @param source: the name of the file to read
193 @type source: str
194 @param local: this is a local feed
195 @type local: bool
196 @param selections_ok: if it turns out to be a local selections document, return that instead
197 @type selections_ok: bool
198 @raise InvalidInterface: if the source's syntax is incorrect
199 @return: the new feed
200 @since: 0.48
201 @see: L{iface_cache.iface_cache}, which uses this to load the feeds"""
202 try:
203 root = qdom.parse(file(source))
204 except IOError, ex:
205 if ex.errno == 2:
206 raise InvalidInterface(_("Feed not found. Perhaps this is a local feed that no longer exists? You can remove it from the list of feeds in that case."), ex)
207 raise InvalidInterface(_("Can't read file"), ex)
208 except Exception, ex:
209 raise InvalidInterface(_("Invalid XML"), ex)
211 if local:
212 if selections_ok and root.uri == XMLNS_IFACE and root.name == 'selections':
213 from zeroinstall.injector import selections
214 return selections.Selections(root)
215 local_path = source
216 else:
217 local_path = None
218 feed = ZeroInstallFeed(root, local_path)
219 feed.last_modified = int(os.stat(source).st_mtime)
220 return feed