48"""@type message: str""" 49ifex: 50try: 51message+="\n\n(exact error: %s)"%ex 52except: 53# Some Python messages have type str but contain UTF-8 sequences. 54# (e.g. IOException). Adding these to a Unicode 'message' (e.g. 55# after gettext translation) will cause an error. 56importcodecs 57decoder=codecs.lookup('utf-8') 58decex=decoder.decode(str(ex),errors='replace')[0] 59message+="\n\n(exact error: %s)"%decex 60 61SafeException.__init__(self,message)
74"""Split an arch into an (os, machine) tuple. Either or both parts may be None. 75 @type arch: str""" 76ifnotarch: 77returnNone,None 78elif'-'notinarch: 79raiseSafeException(_("Malformed arch '%s'")%arch) 80else: 81osys,machine=arch.split('-',1) 82ifosys=='*':osys=None 83ifmachine=='*':machine=None 84returnosys,machine
109"""A stability rating. Each implementation has an upstream stability rating and, 110 optionally, a user-set rating.""" 111__slots__=['level','name','description']
244"""A Restriction limits the allowed implementations of an Interface.""" 245__slots__=[] 246 247reason=_("Incompatible with user-specified requirements") 248
250"""Called by the L{solver.Solver} to check whether a particular implementation is acceptable. 251 @return: False if this implementation is not a possibility 252 @rtype: bool""" 253raiseNotImplementedError(_("Abstract"))
267"""@param version: the required version number 268 @see: L{parse_version}; use this to pre-process the version number""" 269assertnotisinstance(version,str),"Not parsed: "+version 270self.version=version
285"""@param before: chosen versions must be earlier than this 286 @param not_before: versions must be at least this high 287 @see: L{parse_version}; use this to pre-process the versions""" 288self.before=before 289self.not_before=not_before
319"""Constructor. 320 @param expr: the expression, in the form "2.6..!3 | 3.2.2.." 321 @type expr: str""" 322self.expr=expr 323self._test_fn=versions.parse_version_expression(expr)
353"""A restriction that can only be satisfied by an implementation 354 from the given distribution. 355 For example, a MacPorts Python library requires us to select the MacPorts 356 version of Python too. 357 @since: 1.15""" 358distros=None 359
384"""Indicate the chosen implementation using an environment variable.""" 385__slots__=['name','insert','default','mode','value'] 386 387PREPEND='prepend' 388APPEND='append' 389REPLACE='replace' 390
414"""Calculate the new value of the environment variable after applying this binding. 415 @param path: the path to the selected implementation 416 @param old_value: the current value of the environment variable 417 @return: the new value for the environment variable""" 418 419ifself.insertisnotNone: 420extra=os.path.join(path,self.insert) 421else: 422assertself.valueisnotNone 423extra=self.value 424 425ifself.mode==EnvironmentBinding.REPLACE: 426returnextra 427 428ifold_valueisNone: 429old_value=self.defaultordefaults.get(self.name,None) 430ifold_valueisNone: 431returnextra 432ifself.mode==EnvironmentBinding.PREPEND: 433returnextra+self.separator+old_value 434else: 435returnold_value+self.separator+extra
438"""Create a DOM element for this binding. 439 @param doc: document to use to create the element 440 @return: the new element 441 """ 442env_elem=doc.createElementNS(XMLNS_IFACE,'environment') 443env_elem.setAttributeNS(None,'name',self.name) 444ifself.modeisnotNone: 445env_elem.setAttributeNS(None,'mode',self.mode) 446ifself.insertisnotNone: 447env_elem.setAttributeNS(None,'insert',self.insert) 448else: 449env_elem.setAttributeNS(None,'value',self.value) 450ifself.default: 451env_elem.setAttributeNS(None,'default',self.default) 452ifself.separator: 453env_elem.setAttributeNS(None,'separator',self.separator) 454returnenv_elem
457"""Make the chosen command available in $PATH. 458 @ivar in_path: True to add the named command to $PATH, False to store in named variable 459 @type in_path: bool 460 """ 461__slots__=['qdom'] 462
484"""Make the chosen implementation available by overlaying it onto another part of the file-system. 485 This is to support legacy programs which use hard-coded paths.""" 486__slots__=['src','mount_point'] 487
498"""Create a DOM element for this binding. 499 @param doc: document to use to create the element 500 @return: the new element 501 """ 502env_elem=doc.createElementNS(XMLNS_IFACE,'overlay') 503ifself.srcisnotNone: 504env_elem.setAttributeNS(None,'src',self.src) 505ifself.mount_pointisnotNone: 506env_elem.setAttributeNS(None,'mount-point',self.mount_point) 507returnenv_elem
510"""An interface's feeds are other interfaces whose implementations can also be 511 used as implementations of this interface.""" 512__slots__=['uri','os','machine','user_override','langs','site_package']
514self.uri=uri 515# This indicates whether the feed comes from the user's overrides 516# file. If true, writer.py will write it when saving. 517self.user_override=user_override 518self.os,self.machine=_split_arch(arch) 519self.langs=langs 520self.site_package=site_package
529"""A Dependency indicates that an Implementation requires some additional 530 code to function. This is an abstract base class. 531 @ivar qdom: the XML element for this Dependency (since 0launch 0.51) 532 @type qdom: L{qdom.Element} 533 @ivar metadata: any extra attributes from the XML element 534 @type metadata: {str: str} 535 """ 536__slots__=['qdom'] 537 538Essential="essential"# Must select a version of the dependency 539Recommended="recommended"# Prefer to select a version 540Restricts="restricts"# Just adds restrictions without expressing any opinion 541
556"""A Dependency that restricts the possible choices of a Zero Install interface. 557 @ivar interface: the interface required by this dependency 558 @type interface: str 559 @ivar restrictions: a list of constraints on acceptable implementations 560 @type restrictions: [L{Restriction}] 561 @since: 1.10 562 """ 563__slots__=['interface','restrictions'] 564
584"""A Dependency on a Zero Install interface. 585 @ivar interface: the interface required by this dependency 586 @type interface: str 587 @ivar restrictions: a list of constraints on acceptable implementations 588 @type restrictions: [L{Restriction}] 589 @ivar bindings: how to make the choice of implementation known 590 @type bindings: [L{Binding}] 591 @since: 0.28 592 """ 593__slots__=['bindings'] 594
632"""A DownloadSource provides a way to fetch an implementation.""" 633__slots__=['implementation','url','size','extract','start_offset','type','dest'] 634
682"""Get an implementation by following a series of steps. 683 @ivar size: the combined download sizes from all the steps 684 @type size: int 685 @ivar steps: the sequence of steps which must be performed 686 @type steps: [L{RetrievalMethod}]""" 687__slots__=['steps'] 688
695"""A package that is installed using the distribution's tools (including PackageKit). 696 @ivar install: a function to call to install this package 697 @type install: (L{handler.Handler}) -> L{tasks.Blocker} 698 @ivar package_id: the package name, in a form recognised by the distribution's tools 699 @type package_id: str 700 @ivar size: the download size in bytes 701 @type size: int 702 @ivar needs_confirmation: whether the user should be asked to confirm before calling install() 703 @type needs_confirmation: bool""" 704 705__slots__=['package_id','size','install','needs_confirmation'] 706
723"""@param qdom: the <command> element 724 @type qdom: L{zeroinstall.injector.qdom.Element} 725 @param local_dir: the directory containing the feed (for relative dependencies), or None if not local""" 726assertqdom.name=='command','not <command>: %s'%qdom 727self.qdom=qdom 728self._local_dir=local_dir 729self._depends=None 730self._bindings=None
778"""An Implementation is a package which implements an Interface. 779 @ivar download_sources: list of methods of getting this implementation 780 @type download_sources: [L{RetrievalMethod}] 781 @ivar feed: the feed owning this implementation (since 0.32) 782 @type feed: [L{ZeroInstallFeed}] 783 @ivar bindings: how to tell this component where it itself is located (since 0.31) 784 @type bindings: [Binding] 785 @ivar upstream_stability: the stability reported by the packager 786 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged] 787 @ivar user_stability: the stability as set by the user 788 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged | preferred] 789 @ivar langs: natural languages supported by this package 790 @type langs: str 791 @ivar requires: interfaces this package depends on 792 @type requires: [L{Dependency}] 793 @ivar commands: ways to execute as a program 794 @type commands: {str: Command} 795 @ivar metadata: extra metadata from the feed 796 @type metadata: {"[URI ]localName": str} 797 @ivar id: a unique identifier for this Implementation 798 @ivar version: a parsed version number 799 @ivar released: release date 800 @ivar local_path: the directory containing this local implementation, or None if it isn't local (id isn't a path) 801 @type local_path: str | None 802 @ivar requires_root_install: whether the user will need admin rights to use this 803 @type requires_root_install: bool 804 """ 805 806# Note: user_stability shouldn't really be here 807 808__slots__=['upstream_stability','user_stability','langs', 809'requires','metadata','download_sources','commands', 810'id','feed','version','released','bindings','machine'] 811
842"""Newer versions come first 843 @type other: L{Implementation} 844 @rtype: int""" 845d=cmp(other.version,self.version) 846ifd:returnd 847# If the version number is the same, just give a stable sort order, and 848# ensure that two different implementations don't compare equal. 849d=cmp(other.feed.url,self.feed.url) 850ifd:returnd 851returncmp(other.id,self.id)
904"""Is this Implementation available locally? 905 (a local implementation, an installed distribution package, or a cached ZeroInstallImplementation) 906 @rtype: bool 907 @since: 0.53""" 908raiseNotImplementedError("abstract")
911"""An implementation provided by the distribution. Information such as the version 912 comes from the package manager. 913 @ivar package_implementation: the <package-implementation> element that generated this impl (since 1.7) 914 @type package_implementation: L{qdom.Element} 915 @since: 0.28""" 916__slots__=['distro','installed','package_implementation','distro_name'] 917
950"""An implementation where all the information comes from Zero Install. 951 @ivar digests: a list of "algorith=value" or "algorith_value" strings (since 0.45) 952 @type digests: [str] 953 @since: 0.28""" 954__slots__=['os','size','digests','local_path'] 955 956distro_name='0install' 957
959"""id can be a local path (string starting with /) or a manifest hash (eg "sha1=XXX") 960 @type feed: L{ZeroInstallFeed} 961 @type id: str 962 @type local_path: str""" 963assertnotid.startswith('package:'),id 964Implementation.__init__(self,feed,id) 965self.size=None 966self.os=None 967self.digests=[] 968self.local_path=local_path
1000"""An Interface represents some contract of behaviour.1001 @ivar uri: the URI for this interface.1002 @ivar stability_policy: user's configured policy.1003 Implementations at this level or higher are preferred.1004 Lower levels are used only if there is no other choice.1005 """1006__slots__=['uri','stability_policy','extra_feeds']10071008implementations=property(lambdaself:self._main_feed.implementations)1009name=property(lambdaself:self._main_feed.name)1010description=property(lambdaself:self._main_feed.description)1011summary=property(lambdaself:self._main_feed.summary)1012last_modified=property(lambdaself:self._main_feed.last_modified)1013feeds=property(lambdaself:self.extra_feeds+self._main_feed.feeds)1014metadata=property(lambdaself:self._main_feed.metadata)10151016last_checked=property(lambdaself:self._main_feed.last_checked)1017
1080"""Add each attribute of item to a copy of attrs and return the copy.1081 @type attrs: {str: str}1082 @type item: L{qdom.Element}1083 @rtype: {str: str}"""1084new=attrs.copy()1085forainitem.attrs:1086new[str(a)]=item.attrs[a]1087returnnew
1102"""A feed lists available implementations of an interface.1103 @ivar url: the URL for this feed1104 @ivar implementations: Implementations in this feed, indexed by ID1105 @type implementations: {str: L{Implementation}}1106 @ivar name: human-friendly name1107 @ivar summaries: short textual description (in various languages, since 0.49)1108 @type summaries: {str: str}1109 @ivar descriptions: long textual description (in various languages, since 0.49)1110 @type descriptions: {str: str}1111 @ivar last_modified: timestamp on signature1112 @ivar last_checked: time feed was last successfully downloaded and updated1113 @ivar local_path: the path of this local feed, or None if remote (since 1.7)1114 @type local_path: str | None1115 @ivar feeds: list of <feed> elements in this feed1116 @type feeds: [L{Feed}]1117 @ivar feed_for: interfaces for which this could be a feed1118 @type feed_for: set(str)1119 @ivar metadata: extra elements we didn't understand1120 """1121# _main is deprecated1122__slots__=['url','implementations','name','descriptions','first_description','summaries','first_summary','_package_implementations',1123'last_checked','last_modified','feeds','feed_for','metadata','local_path']1124
1126"""Create a feed object from a DOM.1127 @param feed_element: the root element of a feed file1128 @type feed_element: L{qdom.Element}1129 @param local_path: the pathname of this local feed, or None for remote feeds1130 @type local_path: str | None"""1131self.local_path=local_path1132self.implementations={}1133self.name=None1134self.summaries={}# { lang: str }1135self.first_summary=None1136self.descriptions={}# { lang: str }1137self.first_description=None1138self.last_modified=None1139self.feeds=[]1140self.feed_for=set()1141self.metadata=[]1142self.last_checked=None1143self._package_implementations=[]11441145ifdistroisnotNone:1146importwarnings1147warnings.warn("distro argument is now ignored",DeprecationWarning,2)11481149iffeed_elementisNone:1150return# XXX subclass?11511152iffeed_element.namenotin('interface','feed'):1153raiseSafeException("Root element should be <interface>, not <%s>"%feed_element.name)1154assertfeed_element.uri==XMLNS_IFACE,"Wrong namespace on root element: %s"%feed_element.uri11551156main=feed_element.getAttribute('main')1157#if main: warn("Setting 'main' on the root element is deprecated. Put it on a <group> instead")11581159iflocal_path:1160self.url=local_path1161local_dir=os.path.dirname(local_path)1162else:1163assertlocal_pathisNone1164self.url=feed_element.getAttribute('uri')1165ifnotself.url:1166raiseInvalidInterface(_("<interface> uri attribute missing"))1167local_dir=None# Can't have relative paths11681169min_injector_version=feed_element.getAttribute('min-injector-version')1170ifmin_injector_version:1171ifparse_version(min_injector_version)>parse_version(version):1172raiseInvalidInterface(_("This feed requires version %(min_version)s or later of "1173"Zero Install, but I am only version %(version)s. "1174"You can get a newer version from http://0install.net")%1175{'min_version':min_injector_version,'version':version})11761177forxinfeed_element.childNodes:1178ifx.uri!=XMLNS_IFACE:1179self.metadata.append(x)1180continue1181ifx.name=='name':1182self.name=x.content1183elifx.name=='description':1184ifself.first_description==None:1185self.first_description=x.content1186self.descriptions[x.attrs.get("http://www.w3.org/XML/1998/namespace lang",'en')]=x.content1187elifx.name=='summary':1188ifself.first_summary==None:1189self.first_summary=x.content1190self.summaries[x.attrs.get("http://www.w3.org/XML/1998/namespace lang",'en')]=x.content1191elifx.name=='feed-for':1192feed_iface=x.getAttribute('interface')1193ifnotfeed_iface:1194raiseInvalidInterface(_('Missing "interface" attribute in <feed-for>'))1195self.feed_for.add(feed_iface)1196# Bug report from a Debian/stable user that --feed gets the wrong value.1197# Can't reproduce (even in a Debian/stable chroot), but add some logging here1198# in case it happens again.1199logger.debug(_("Is feed-for %s"),feed_iface)1200elifx.name=='feed':1201feed_src=x.getAttribute('src')1202ifnotfeed_src:1203raiseInvalidInterface(_('Missing "src" attribute in <feed>'))1204iffeed_src.startswith('http:')orfeed_src.startswith('https:')orlocal_path:1205iffeed_src.startswith('.'):1206feed_src=os.path.abspath(os.path.join(local_dir,feed_src))12071208langs=x.getAttribute('langs')1209iflangs:langs=langs.replace('_','-')1210self.feeds.append(Feed(feed_src,x.getAttribute('arch'),False,langs=langs))1211else:1212raiseInvalidInterface(_("Invalid feed URL '%s'")%feed_src)1213else:1214self.metadata.append(x)12151216ifnotself.name:1217raiseInvalidInterface(_("Missing <name> in feed"))1218ifnotself.summary:1219raiseInvalidInterface(_("Missing <summary> in feed"))12201221defprocess_group(group,group_attrs,base_depends,base_bindings,base_commands):1222foritemingroup.childNodes:1223ifitem.uri!=XMLNS_IFACE:continue12241225ifitem.namenotin('group','implementation','package-implementation'):1226continue12271228# We've found a group or implementation. Scan for dependencies,1229# bindings and commands. Doing this here means that:1230# - We can share the code for groups and implementations here.1231# - The order doesn't matter, because these get processed first.1232# A side-effect is that the document root cannot contain1233# these.12341235depends=base_depends[:]1236bindings=base_bindings[:]1237commands=base_commands.copy()12381239forattr,commandin[('main','run'),1240('self-test','test')]:1241value=item.attrs.get(attr,None)1242ifvalueisnotNone:1243commands[command]=Command(qdom.Element(XMLNS_IFACE,'command',{'name':command,'path':value}),None)12441245forchildinitem.childNodes:1246ifchild.uri!=XMLNS_IFACE:continue1247ifchild.namein_dependency_names:1248dep=process_depends(child,local_dir)1249depends.append(dep)1250elifchild.name=='command':1251command_name=child.attrs.get('name',None)1252ifnotcommand_name:1253raiseInvalidInterface('Missing name for <command>')1254commands[command_name]=Command(child,local_dir)1255elifchild.nameinbinding_names:1256bindings.append(process_binding(child))12571258compile_command=item.attrs.get('http://zero-install.sourceforge.net/2006/namespaces/0compile command')1259ifcompile_commandisnotNone:1260commands['compile']=Command(qdom.Element(XMLNS_IFACE,'command',{'name':'compile','shell-command':compile_command}),None)12611262item_attrs=_merge_attrs(group_attrs,item)12631264ifitem.name=='group':1265process_group(item,item_attrs,depends,bindings,commands)1266elifitem.name=='implementation':1267process_impl(item,item_attrs,depends,bindings,commands)1268elifitem.name=='package-implementation':1269self._package_implementations.append((item,item_attrs,depends))1270else:1271assert0
12721273defprocess_impl(item,item_attrs,depends,bindings,commands):1274id=item.getAttribute('id')1275ifidisNone:1276raiseInvalidInterface(_("Missing 'id' attribute on %s")%item)1277local_path=item_attrs.get('local-path')1278iflocal_dirandlocal_path:1279abs_local_path=os.path.abspath(os.path.join(local_dir,local_path))1280impl=ZeroInstallImplementation(self,id,abs_local_path)1281eliflocal_dirand(id.startswith('/')orid.startswith('.')):1282# For old feeds1283id=os.path.abspath(os.path.join(local_dir,id))1284impl=ZeroInstallImplementation(self,id,id)1285else:1286impl=ZeroInstallImplementation(self,id,None)1287if'='inid:1288# In older feeds, the ID was the (single) digest1289impl.digests.append(id)1290ifidinself.implementations:1291logger.warning(_("Duplicate ID '%(id)s' in feed '%(feed)s'"),{'id':id,'feed':self})1292self.implementations[id]=impl12931294impl.metadata=item_attrs1295try:1296version_mod=item_attrs.get('version-modifier',None)1297ifversion_mod:1298item_attrs['version']+=version_mod1299delitem_attrs['version-modifier']1300version=item_attrs['version']1301exceptKeyError:1302raiseInvalidInterface(_("Missing version attribute"))1303impl.version=parse_version(version)13041305impl.commands=commands13061307impl.released=item_attrs.get('released',None)1308impl.langs=item_attrs.get('langs','').replace('_','-')13091310size=item.getAttribute('size')1311ifsize:1312impl.size=int(size)1313impl.arch=item_attrs.get('arch',None)1314try:1315stability=stability_levels[str(item_attrs['stability'])]1316exceptKeyError:1317stab=str(item_attrs['stability'])1318ifstab!=stab.lower():1319raiseInvalidInterface(_('Stability "%s" invalid - use lower case!')%item_attrs.stability)1320raiseInvalidInterface(_('Stability "%s" invalid')%item_attrs['stability'])1321ifstability>=preferred:1322raiseInvalidInterface(_("Upstream can't set stability to preferred!"))1323impl.upstream_stability=stability13241325impl.bindings=bindings1326impl.requires=depends13271328defextract_file_source(elem):1329url=elem.getAttribute('href')1330ifnoturl:1331raiseInvalidInterface(_("Missing href attribute on <file>"))1332dest=elem.getAttribute('dest')1333ifnotdest:1334raiseInvalidInterface(_("Missing dest attribute on <file>"))1335size=elem.getAttribute('size')1336ifnotsize:1337raiseInvalidInterface(_("Missing size attribute on <file>"))1338returnFileSource(url,dest,int(size))
13391340foreleminitem.childNodes:1341ifelem.uri!=XMLNS_IFACE:continue1342ifelem.name=='archive':1343url=elem.getAttribute('href')1344ifnoturl:1345raiseInvalidInterface(_("Missing href attribute on <archive>"))1346size=elem.getAttribute('size')1347ifnotsize:1348raiseInvalidInterface(_("Missing size attribute on <archive>"))1349impl.add_download_source(url=url,size=int(size),1350extract=elem.getAttribute('extract'),1351start_offset=_get_long(elem,'start-offset'),1352type=elem.getAttribute('type'),1353dest=elem.getAttribute('dest'))1354elifelem.name=='file':1355impl.download_sources.append(extract_file_source(elem))13561357elifelem.name=='manifest-digest':1358foraname,avalueinelem.attrs.items():1359if' 'notinaname:1360impl.digests.append(zerostore.format_algorithm_digest_pair(aname,avalue))1361elifelem.name=='recipe':1362recipe=Recipe()1363forrecipe_stepinelem.childNodes:1364ifrecipe_step.uri==XMLNS_IFACEandrecipe_step.name=='archive':1365url=recipe_step.getAttribute('href')1366ifnoturl:1367raiseInvalidInterface(_("Missing href attribute on <archive>"))1368size=recipe_step.getAttribute('size')1369ifnotsize:1370raiseInvalidInterface(_("Missing size attribute on <archive>"))1371recipe.steps.append(DownloadSource(None,url=url,size=int(size),1372extract=recipe_step.getAttribute('extract'),1373start_offset=_get_long(recipe_step,'start-offset'),1374type=recipe_step.getAttribute('type'),1375dest=recipe_step.getAttribute('dest')))1376elifrecipe_step.name=='file':1377recipe.steps.append(extract_file_source(recipe_step))1378elifrecipe_step.uri==XMLNS_IFACEandrecipe_step.name=='rename':1379source=recipe_step.getAttribute('source')1380ifnotsource:1381raiseInvalidInterface(_("Missing source attribute on <rename>"))1382dest=recipe_step.getAttribute('dest')1383ifnotdest:1384raiseInvalidInterface(_("Missing dest attribute on <rename>"))1385recipe.steps.append(RenameStep(source=source,dest=dest))1386elifrecipe_step.uri==XMLNS_IFACEandrecipe_step.name=='remove':1387path=recipe_step.getAttribute('path')1388ifnotpath:1389raiseInvalidInterface(_("Missing path attribute on <remove>"))1390recipe.steps.append(RemoveStep(path=path))1391else:1392logger.info(_("Unknown step '%s' in recipe; skipping recipe"),recipe_step.name)1393break1394else:1395impl.download_sources.append(recipe)13961397root_attrs={'stability':'testing'}1398root_commands={}1399ifmain:1400logger.info("Note: @main on document element is deprecated in %s",self)1401root_commands['run']=Command(qdom.Element(XMLNS_IFACE,'command',{'path':main,'name':'run'}),None)1402process_group(feed_element,root_attrs,[],[],root_commands)1403
1405"""Does this feed contain any <pacakge-implementation> elements?1406 i.e. is it worth asking the package manager for more information?1407 @return: the URL of the virtual feed, or None1408 @rtype: str1409 @since: 0.49"""1410ifself._package_implementations:1411return"distribution:"+self.url1412returnNone
1415"""Find the best <pacakge-implementation> element(s) for the given distribution.1416 @param distro: the distribution to use to rate them1417 @type distro: L{distro.Distribution}1418 @return: a list of tuples for the best ranked elements1419 @rtype: [str]1420 @since: 0.49"""1421best_score=01422best_impls=[]14231424foritem,item_attrs,dependsinself._package_implementations:1425distro_names=item_attrs.get('distributions','')1426score_this_item=max(1427distro.get_score(distro_name)ifdistro_nameelse0.51428fordistro_nameindistro_names.split(' '))1429ifscore_this_item>best_score:1430best_score=score_this_item1431best_impls=[]1432ifscore_this_item==best_score:1433best_impls.append((item,item_attrs,depends))1434returnbest_impls
1457"""Return a list of interface metadata elements with this name and namespace URI.1458 @type uri: str1459 @type name: str"""1460return[mforminself.metadataifm.name==nameandm.uri==uri]
1471"""Return the URI of the interface that replaced the one with the URI of this feed's URL.1472 This is the value of the feed's <replaced-by interface'...'/> element.1473 @return: the new URI, or None if it hasn't been replaced1474 @rtype: str | None1475 @since: 1.7"""1476forchildinself.metadata:1477ifchild.uri==XMLNS_IFACEandchild.name=='replaced-by':1478new_uri=child.getAttribute('interface')1479ifnew_uriand(new_uri.startswith('http:')ornew_uri.startswith('https:')orself.local_path):1480returnnew_uri1481returnNone
1484"""Temporary class used during API transition."""1485last_modified=None1486name='-'1487last_checked=property(lambdaself:None)1488implementations=property(lambdaself:{})1489feeds=property(lambdaself:[])1490summary=property(lambdaself:'-')1491description=property(lambdaself:'')
1501# (note: delete these two lines when generating epydoc)15021503# These could be replaced by urllib.parse.quote, except that1504# it uses upper-case escapes and we use lower-case ones...1505-defunescape(uri):
1506"""Convert each %20 to a space, etc.1507 @type uri: str1508 @rtype: str"""1509uri=uri.replace('#','/')1510if'%'notinuri:returnuri1511returnre.sub(b'%[0-9a-fA-F][0-9a-fA-F]',1512lambdamatch:bytes([int(match.group(0)[1:],16)]),1513uri.encode('ascii')).decode('utf-8')
1516"""Convert each space to %20, etc1517 @type uri: str1518 @rtype: str"""1519returnre.sub(b'[^-_.a-zA-Z0-9]',1520lambdamatch:('%%%02x'%ord(match.group(0))).encode('ascii'),1521uri.encode('utf-8')).decode('ascii')
1524"""Convert each space to %20, etc1525 : is preserved and / becomes #. This makes for nicer strings,1526 and may replace L{escape} everywhere in future.1527 @type uri: str1528 @rtype: str"""1529ifos.name=="posix":1530# Only preserve : on Posix systems1531preserveRegex=b'[^-_.a-zA-Z0-9:/]'1532else:1533# Other OSes may not allow the : character in file names1534preserveRegex=b'[^-_.a-zA-Z0-9/]'1535returnre.sub(preserveRegex,1536lambdamatch:('%%%02x'%ord(match.group(0))).encode('ascii'),1537uri.encode('utf-8')).decode('ascii').replace('/','#')
1542"""Convert each %20 to a space, etc.1543 @type uri: str1544 @rtype: str"""1545uri=uri.replace('#','/')1546if'%'notinuri:returnuri1547returnre.sub('%[0-9a-fA-F][0-9a-fA-F]',1548lambdamatch:chr(int(match.group(0)[1:],16)),1549uri).decode('utf-8')
1552"""Convert each space to %20, etc1553 @type uri: str1554 @rtype: str"""1555returnre.sub('[^-_.a-zA-Z0-9]',1556lambdamatch:'%%%02x'%ord(match.group(0)),1557uri.encode('utf-8'))
1560"""Convert each space to %20, etc1561 : is preserved and / becomes #. This makes for nicer strings,1562 and may replace L{escape} everywhere in future.1563 @type uri: str1564 @rtype: str"""1565ifos.name=="posix":1566# Only preserve : on Posix systems1567preserveRegex='[^-_.a-zA-Z0-9:/]'1568else:1569# Other OSes may not allow the : character in file names1570preserveRegex='[^-_.a-zA-Z0-9/]'1571returnre.sub(preserveRegex,1572lambdamatch:'%%%02x'%ord(match.group(0)),1573uri.encode('utf-8')).replace('/','#')
1576"""Convert an interface URI to a list of path components.1577 e.g. "http://example.com/foo.xml" becomes ["http", "example.com", "foo.xml"], while1578 "file:///root/feed.xml" becomes ["file", "root__feed.xml"]1579 The number of components is determined by the scheme (three for http, two for file).1580 Uses L{support.escaping.underscore_escape} to escape each component.1581 @type uri: str1582 @rtype: [str]"""1583ifuri.startswith('http://')oruri.startswith('https://'):1584scheme,rest=uri.split('://',1)1585parts=rest.split('/',1)1586else:1587assertos.path.isabs(uri),uri1588scheme='file'1589parts=[uri[1:]]15901591return[scheme]+[escaping.underscore_escape(part)forpartinparts]
1594"""If uri is a relative path, convert to an absolute one.1595 A "file:///foo" URI is converted to "/foo".1596 An "alias:prog" URI expands to the URI in the 0alias script1597 Otherwise, return it unmodified.1598 @type uri: str1599 @rtype: str1600 @raise SafeException: if uri isn't valid"""1601ifuri.startswith('http://')oruri.startswith('https://'):1602ifuri.count("/")<3:1603raiseSafeException(_("Missing / after hostname in URI '%s'")%uri)1604returnuri1605elifuri.startswith('file:///'):1606path=uri[7:]1607elifuri.startswith('file:'):1608ifuri[5]=='/':1609raiseSafeException(_('Use file:///path for absolute paths, not {uri}').format(uri=uri))1610path=os.path.abspath(uri[5:])1611elifuri.startswith('alias:'):1612fromzeroinstallimportalias1613alias_prog=uri[6:]1614ifnotos.path.isabs(alias_prog):1615full_path=support.find_in_path(alias_prog)1616ifnotfull_path:1617raisealias.NotAnAliasScript("Not found in $PATH: "+alias_prog)1618else:1619full_path=alias_prog1620returnalias.parse_script(full_path).uri1621else:1622path=os.path.realpath(uri)16231624ifos.path.isfile(path):1625returnpath16261627if'/'notinuri:1628alias_path=support.find_in_path(uri)1629ifalias_pathisnotNone:1630fromzeroinstallimportalias1631try:1632alias.parse_script(alias_path)1633exceptalias.NotAnAliasScript:1634pass1635else:1636raiseSafeException(_("Bad interface name '{uri}'.\n"1637"(hint: try 'alias:{uri}' instead)".format(uri=uri)))16381639raiseSafeException(_("Bad interface name '%(uri)s'.\n"1640"(doesn't start with 'http:', and "1641"doesn't exist as a local file '%(interface_uri)s' either)")%1642{'uri':uri,'interface_uri':path})