wget.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. # ex:ts=4:sw=4:sts=4:et
  2. # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
  3. """
  4. BitBake 'Fetch' implementations
  5. Classes for obtaining upstream sources for the
  6. BitBake build tools.
  7. """
  8. # Copyright (C) 2003, 2004 Chris Larson
  9. #
  10. # SPDX-License-Identifier: GPL-2.0-only
  11. #
  12. # This program is free software; you can redistribute it and/or modify
  13. # it under the terms of the GNU General Public License version 2 as
  14. # published by the Free Software Foundation.
  15. #
  16. # This program is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU General Public License along
  22. # with this program; if not, write to the Free Software Foundation, Inc.,
  23. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  24. #
  25. # Based on functions from the base bb module, Copyright 2003 Holger Schurig
  26. import re
  27. import tempfile
  28. import subprocess
  29. import os
  30. import logging
  31. import errno
  32. import bb
  33. import bb.progress
  34. import socket
  35. import http.client
  36. import urllib.request, urllib.parse, urllib.error
  37. from bb.fetch2 import FetchMethod
  38. from bb.fetch2 import FetchError
  39. from bb.fetch2 import logger
  40. from bb.fetch2 import runfetchcmd
  41. from bb.fetch2 import FetchConnectionCache
  42. from bb.utils import export_proxies
  43. from bs4 import BeautifulSoup
  44. from bs4 import SoupStrainer
  45. class WgetProgressHandler(bb.progress.LineFilterProgressHandler):
  46. """
  47. Extract progress information from wget output.
  48. Note: relies on --progress=dot (with -v or without -q/-nv) being
  49. specified on the wget command line.
  50. """
  51. def __init__(self, d):
  52. super(WgetProgressHandler, self).__init__(d)
  53. # Send an initial progress event so the bar gets shown
  54. self._fire_progress(0)
  55. def writeline(self, line):
  56. percs = re.findall(r'(\d+)%\s+([\d.]+[A-Z])', line)
  57. if percs:
  58. progress = int(percs[-1][0])
  59. rate = percs[-1][1] + '/s'
  60. self.update(progress, rate)
  61. return False
  62. return True
  63. class Wget(FetchMethod):
  64. """Class to fetch urls via 'wget'"""
  65. def supports(self, ud, d):
  66. """
  67. Check to see if a given url can be fetched with wget.
  68. """
  69. return ud.type in ['http', 'https', 'ftp']
  70. def recommends_checksum(self, urldata):
  71. return True
  72. def urldata_init(self, ud, d):
  73. if 'protocol' in ud.parm:
  74. if ud.parm['protocol'] == 'git':
  75. raise bb.fetch2.ParameterError("Invalid protocol - if you wish to fetch from a git repository using http, you need to instead use the git:// prefix with protocol=http", ud.url)
  76. if 'downloadfilename' in ud.parm:
  77. ud.basename = ud.parm['downloadfilename']
  78. else:
  79. ud.basename = os.path.basename(ud.path)
  80. ud.localfile = d.expand(urllib.parse.unquote(ud.basename))
  81. if not ud.localfile:
  82. ud.localfile = d.expand(urllib.parse.unquote(ud.host + ud.path).replace("/", "."))
  83. self.basecmd = d.getVar("FETCHCMD_wget") or "/usr/bin/env wget -t 2 -T 30 --passive-ftp --no-check-certificate"
  84. def _runwget(self, ud, d, command, quiet, workdir=None):
  85. progresshandler = WgetProgressHandler(d)
  86. logger.debug(2, "Fetching %s using command '%s'" % (ud.url, command))
  87. bb.fetch2.check_network_access(d, command, ud.url)
  88. runfetchcmd(command + ' --progress=dot -v', d, quiet, log=progresshandler, workdir=workdir)
  89. def download(self, ud, d):
  90. """Fetch urls"""
  91. fetchcmd = self.basecmd
  92. if 'downloadfilename' in ud.parm:
  93. dldir = d.getVar("DL_DIR")
  94. bb.utils.mkdirhier(os.path.dirname(dldir + os.sep + ud.localfile))
  95. fetchcmd += " -O " + dldir + os.sep + ud.localfile
  96. if ud.user and ud.pswd:
  97. fetchcmd += " --user=%s --password=%s --auth-no-challenge" % (ud.user, ud.pswd)
  98. uri = ud.url.split(";")[0]
  99. if os.path.exists(ud.localpath):
  100. # file exists, but we didnt complete it.. trying again..
  101. fetchcmd += d.expand(" -c -P ${DL_DIR} '%s'" % uri)
  102. else:
  103. fetchcmd += d.expand(" -P ${DL_DIR} '%s'" % uri)
  104. self._runwget(ud, d, fetchcmd, False)
  105. # Sanity check since wget can pretend it succeed when it didn't
  106. # Also, this used to happen if sourceforge sent us to the mirror page
  107. if not os.path.exists(ud.localpath):
  108. raise FetchError("The fetch command returned success for url %s but %s doesn't exist?!" % (uri, ud.localpath), uri)
  109. if os.path.getsize(ud.localpath) == 0:
  110. os.remove(ud.localpath)
  111. raise FetchError("The fetch of %s resulted in a zero size file?! Deleting and failing since this isn't right." % (uri), uri)
  112. return True
  113. def checkstatus(self, fetch, ud, d, try_again=True):
  114. class HTTPConnectionCache(http.client.HTTPConnection):
  115. if fetch.connection_cache:
  116. def connect(self):
  117. """Connect to the host and port specified in __init__."""
  118. sock = fetch.connection_cache.get_connection(self.host, self.port)
  119. if sock:
  120. self.sock = sock
  121. else:
  122. self.sock = socket.create_connection((self.host, self.port),
  123. self.timeout, self.source_address)
  124. fetch.connection_cache.add_connection(self.host, self.port, self.sock)
  125. if self._tunnel_host:
  126. self._tunnel()
  127. class CacheHTTPHandler(urllib.request.HTTPHandler):
  128. def http_open(self, req):
  129. return self.do_open(HTTPConnectionCache, req)
  130. def do_open(self, http_class, req):
  131. """Return an addinfourl object for the request, using http_class.
  132. http_class must implement the HTTPConnection API from httplib.
  133. The addinfourl return value is a file-like object. It also
  134. has methods and attributes including:
  135. - info(): return a mimetools.Message object for the headers
  136. - geturl(): return the original request URL
  137. - code: HTTP status code
  138. """
  139. host = req.host
  140. if not host:
  141. raise urllib.error.URLError('no host given')
  142. h = http_class(host, timeout=req.timeout) # will parse host:port
  143. h.set_debuglevel(self._debuglevel)
  144. headers = dict(req.unredirected_hdrs)
  145. headers.update(dict((k, v) for k, v in list(req.headers.items())
  146. if k not in headers))
  147. # We want to make an HTTP/1.1 request, but the addinfourl
  148. # class isn't prepared to deal with a persistent connection.
  149. # It will try to read all remaining data from the socket,
  150. # which will block while the server waits for the next request.
  151. # So make sure the connection gets closed after the (only)
  152. # request.
  153. # Don't close connection when connection_cache is enabled,
  154. if fetch.connection_cache is None:
  155. headers["Connection"] = "close"
  156. else:
  157. headers["Connection"] = "Keep-Alive" # Works for HTTP/1.0
  158. headers = dict(
  159. (name.title(), val) for name, val in list(headers.items()))
  160. if req._tunnel_host:
  161. tunnel_headers = {}
  162. proxy_auth_hdr = "Proxy-Authorization"
  163. if proxy_auth_hdr in headers:
  164. tunnel_headers[proxy_auth_hdr] = headers[proxy_auth_hdr]
  165. # Proxy-Authorization should not be sent to origin
  166. # server.
  167. del headers[proxy_auth_hdr]
  168. h.set_tunnel(req._tunnel_host, headers=tunnel_headers)
  169. try:
  170. h.request(req.get_method(), req.selector, req.data, headers)
  171. except socket.error as err: # XXX what error?
  172. # Don't close connection when cache is enabled.
  173. # Instead, try to detect connections that are no longer
  174. # usable (for example, closed unexpectedly) and remove
  175. # them from the cache.
  176. if fetch.connection_cache is None:
  177. h.close()
  178. elif isinstance(err, OSError) and err.errno == errno.EBADF:
  179. # This happens when the server closes the connection despite the Keep-Alive.
  180. # Apparently urllib then uses the file descriptor, expecting it to be
  181. # connected, when in reality the connection is already gone.
  182. # We let the request fail and expect it to be
  183. # tried once more ("try_again" in check_status()),
  184. # with the dead connection removed from the cache.
  185. # If it still fails, we give up, which can happend for bad
  186. # HTTP proxy settings.
  187. fetch.connection_cache.remove_connection(h.host, h.port)
  188. raise urllib.error.URLError(err)
  189. else:
  190. try:
  191. r = h.getresponse(buffering=True)
  192. except TypeError: # buffering kw not supported
  193. r = h.getresponse()
  194. # Pick apart the HTTPResponse object to get the addinfourl
  195. # object initialized properly.
  196. # Wrap the HTTPResponse object in socket's file object adapter
  197. # for Windows. That adapter calls recv(), so delegate recv()
  198. # to read(). This weird wrapping allows the returned object to
  199. # have readline() and readlines() methods.
  200. # XXX It might be better to extract the read buffering code
  201. # out of socket._fileobject() and into a base class.
  202. r.recv = r.read
  203. # no data, just have to read
  204. r.read()
  205. class fp_dummy(object):
  206. def read(self):
  207. return ""
  208. def readline(self):
  209. return ""
  210. def close(self):
  211. pass
  212. closed = False
  213. resp = urllib.response.addinfourl(fp_dummy(), r.msg, req.get_full_url())
  214. resp.code = r.status
  215. resp.msg = r.reason
  216. # Close connection when server request it.
  217. if fetch.connection_cache is not None:
  218. if 'Connection' in r.msg and r.msg['Connection'] == 'close':
  219. fetch.connection_cache.remove_connection(h.host, h.port)
  220. return resp
  221. class HTTPMethodFallback(urllib.request.BaseHandler):
  222. """
  223. Fallback to GET if HEAD is not allowed (405 HTTP error)
  224. """
  225. def http_error_405(self, req, fp, code, msg, headers):
  226. fp.read()
  227. fp.close()
  228. newheaders = dict((k, v) for k, v in list(req.headers.items())
  229. if k.lower() not in ("content-length", "content-type"))
  230. return self.parent.open(urllib.request.Request(req.get_full_url(),
  231. headers=newheaders,
  232. origin_req_host=req.origin_req_host,
  233. unverifiable=True))
  234. # Some servers (e.g. GitHub archives, hosted on Amazon S3) return 403
  235. # Forbidden when they actually mean 405 Method Not Allowed.
  236. http_error_403 = http_error_405
  237. class FixedHTTPRedirectHandler(urllib.request.HTTPRedirectHandler):
  238. """
  239. urllib2.HTTPRedirectHandler resets the method to GET on redirect,
  240. when we want to follow redirects using the original method.
  241. """
  242. def redirect_request(self, req, fp, code, msg, headers, newurl):
  243. newreq = urllib.request.HTTPRedirectHandler.redirect_request(self, req, fp, code, msg, headers, newurl)
  244. newreq.get_method = req.get_method
  245. return newreq
  246. exported_proxies = export_proxies(d)
  247. handlers = [FixedHTTPRedirectHandler, HTTPMethodFallback]
  248. if exported_proxies:
  249. handlers.append(urllib.request.ProxyHandler())
  250. handlers.append(CacheHTTPHandler())
  251. # Since Python 2.7.9 ssl cert validation is enabled by default
  252. # see PEP-0476, this causes verification errors on some https servers
  253. # so disable by default.
  254. import ssl
  255. if hasattr(ssl, '_create_unverified_context'):
  256. handlers.append(urllib.request.HTTPSHandler(context=ssl._create_unverified_context()))
  257. opener = urllib.request.build_opener(*handlers)
  258. try:
  259. uri = ud.url.split(";")[0]
  260. r = urllib.request.Request(uri)
  261. r.get_method = lambda: "HEAD"
  262. # Some servers (FusionForge, as used on Alioth) require that the
  263. # optional Accept header is set.
  264. r.add_header("Accept", "*/*")
  265. def add_basic_auth(login_str, request):
  266. '''Adds Basic auth to http request, pass in login:password as string'''
  267. import base64
  268. encodeuser = base64.b64encode(login_str.encode('utf-8')).decode("utf-8")
  269. authheader = "Basic %s" % encodeuser
  270. r.add_header("Authorization", authheader)
  271. if ud.user and ud.pswd:
  272. add_basic_auth(ud.user + ':' + ud.pswd, r)
  273. try:
  274. import netrc
  275. n = netrc.netrc()
  276. login, unused, password = n.authenticators(urllib.parse.urlparse(uri).hostname)
  277. add_basic_auth("%s:%s" % (login, password), r)
  278. except (TypeError, ImportError, IOError, netrc.NetrcParseError):
  279. pass
  280. with opener.open(r) as response:
  281. pass
  282. except urllib.error.URLError as e:
  283. if try_again:
  284. logger.debug(2, "checkstatus: trying again")
  285. return self.checkstatus(fetch, ud, d, False)
  286. else:
  287. # debug for now to avoid spamming the logs in e.g. remote sstate searches
  288. logger.debug(2, "checkstatus() urlopen failed: %s" % e)
  289. return False
  290. return True
  291. def _parse_path(self, regex, s):
  292. """
  293. Find and group name, version and archive type in the given string s
  294. """
  295. m = regex.search(s)
  296. if m:
  297. pname = ''
  298. pver = ''
  299. ptype = ''
  300. mdict = m.groupdict()
  301. if 'name' in mdict.keys():
  302. pname = mdict['name']
  303. if 'pver' in mdict.keys():
  304. pver = mdict['pver']
  305. if 'type' in mdict.keys():
  306. ptype = mdict['type']
  307. bb.debug(3, "_parse_path: %s, %s, %s" % (pname, pver, ptype))
  308. return (pname, pver, ptype)
  309. return None
  310. def _modelate_version(self, version):
  311. if version[0] in ['.', '-']:
  312. if version[1].isdigit():
  313. version = version[1] + version[0] + version[2:len(version)]
  314. else:
  315. version = version[1:len(version)]
  316. version = re.sub('-', '.', version)
  317. version = re.sub('_', '.', version)
  318. version = re.sub('(rc)+', '.1000.', version)
  319. version = re.sub('(beta)+', '.100.', version)
  320. version = re.sub('(alpha)+', '.10.', version)
  321. if version[0] == 'v':
  322. version = version[1:len(version)]
  323. return version
  324. def _vercmp(self, old, new):
  325. """
  326. Check whether 'new' is newer than 'old' version. We use existing vercmp() for the
  327. purpose. PE is cleared in comparison as it's not for build, and PR is cleared too
  328. for simplicity as it's somehow difficult to get from various upstream format
  329. """
  330. (oldpn, oldpv, oldsuffix) = old
  331. (newpn, newpv, newsuffix) = new
  332. # Check for a new suffix type that we have never heard of before
  333. if newsuffix:
  334. m = self.suffix_regex_comp.search(newsuffix)
  335. if not m:
  336. bb.warn("%s has a possible unknown suffix: %s" % (newpn, newsuffix))
  337. return False
  338. # Not our package so ignore it
  339. if oldpn != newpn:
  340. return False
  341. oldpv = self._modelate_version(oldpv)
  342. newpv = self._modelate_version(newpv)
  343. return bb.utils.vercmp(("0", oldpv, ""), ("0", newpv, ""))
  344. def _fetch_index(self, uri, ud, d):
  345. """
  346. Run fetch checkstatus to get directory information
  347. """
  348. f = tempfile.NamedTemporaryFile()
  349. with tempfile.TemporaryDirectory(prefix="wget-index-") as workdir, tempfile.NamedTemporaryFile(dir=workdir, prefix="wget-listing-") as f:
  350. agent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.12) Gecko/20101027 Ubuntu/9.10 (karmic) Firefox/3.6.12"
  351. fetchcmd = self.basecmd
  352. fetchcmd += " -O " + f.name + " --user-agent='" + agent + "' '" + uri + "'"
  353. try:
  354. self._runwget(ud, d, fetchcmd, True, workdir=workdir)
  355. fetchresult = f.read()
  356. except bb.fetch2.BBFetchException:
  357. fetchresult = ""
  358. return fetchresult
  359. def _check_latest_version(self, url, package, package_regex, current_version, ud, d):
  360. """
  361. Return the latest version of a package inside a given directory path
  362. If error or no version, return ""
  363. """
  364. valid = 0
  365. version = ['', '', '']
  366. bb.debug(3, "VersionURL: %s" % (url))
  367. soup = BeautifulSoup(self._fetch_index(url, ud, d), "html.parser", parse_only=SoupStrainer("a"))
  368. if not soup:
  369. bb.debug(3, "*** %s NO SOUP" % (url))
  370. return ""
  371. for line in soup.find_all('a', href=True):
  372. bb.debug(3, "line['href'] = '%s'" % (line['href']))
  373. bb.debug(3, "line = '%s'" % (str(line)))
  374. newver = self._parse_path(package_regex, line['href'])
  375. if not newver:
  376. newver = self._parse_path(package_regex, str(line))
  377. if newver:
  378. bb.debug(3, "Upstream version found: %s" % newver[1])
  379. if valid == 0:
  380. version = newver
  381. valid = 1
  382. elif self._vercmp(version, newver) < 0:
  383. version = newver
  384. pupver = re.sub('_', '.', version[1])
  385. bb.debug(3, "*** %s -> UpstreamVersion = %s (CurrentVersion = %s)" %
  386. (package, pupver or "N/A", current_version[1]))
  387. if valid:
  388. return pupver
  389. return ""
  390. def _check_latest_version_by_dir(self, dirver, package, package_regex, current_version, ud, d):
  391. """
  392. Scan every directory in order to get upstream version.
  393. """
  394. version_dir = ['', '', '']
  395. version = ['', '', '']
  396. dirver_regex = re.compile(r"(?P<pfx>\D*)(?P<ver>(\d+[\.\-_])+(\d+))")
  397. s = dirver_regex.search(dirver)
  398. if s:
  399. version_dir[1] = s.group('ver')
  400. else:
  401. version_dir[1] = dirver
  402. dirs_uri = bb.fetch.encodeurl([ud.type, ud.host,
  403. ud.path.split(dirver)[0], ud.user, ud.pswd, {}])
  404. bb.debug(3, "DirURL: %s, %s" % (dirs_uri, package))
  405. soup = BeautifulSoup(self._fetch_index(dirs_uri, ud, d), "html.parser", parse_only=SoupStrainer("a"))
  406. if not soup:
  407. return version[1]
  408. for line in soup.find_all('a', href=True):
  409. s = dirver_regex.search(line['href'].strip("/"))
  410. if s:
  411. sver = s.group('ver')
  412. # When prefix is part of the version directory it need to
  413. # ensure that only version directory is used so remove previous
  414. # directories if exists.
  415. #
  416. # Example: pfx = '/dir1/dir2/v' and version = '2.5' the expected
  417. # result is v2.5.
  418. spfx = s.group('pfx').split('/')[-1]
  419. version_dir_new = ['', sver, '']
  420. if self._vercmp(version_dir, version_dir_new) <= 0:
  421. dirver_new = spfx + sver
  422. path = ud.path.replace(dirver, dirver_new, True) \
  423. .split(package)[0]
  424. uri = bb.fetch.encodeurl([ud.type, ud.host, path,
  425. ud.user, ud.pswd, {}])
  426. pupver = self._check_latest_version(uri,
  427. package, package_regex, current_version, ud, d)
  428. if pupver:
  429. version[1] = pupver
  430. version_dir = version_dir_new
  431. return version[1]
  432. def _init_regexes(self, package, ud, d):
  433. """
  434. Match as many patterns as possible such as:
  435. gnome-common-2.20.0.tar.gz (most common format)
  436. gtk+-2.90.1.tar.gz
  437. xf86-input-synaptics-12.6.9.tar.gz
  438. dri2proto-2.3.tar.gz
  439. blktool_4.orig.tar.gz
  440. libid3tag-0.15.1b.tar.gz
  441. unzip552.tar.gz
  442. icu4c-3_6-src.tgz
  443. genext2fs_1.3.orig.tar.gz
  444. gst-fluendo-mp3
  445. """
  446. # match most patterns which uses "-" as separator to version digits
  447. pn_prefix1 = r"[a-zA-Z][a-zA-Z0-9]*([-_][a-zA-Z]\w+)*\+?[-_]"
  448. # a loose pattern such as for unzip552.tar.gz
  449. pn_prefix2 = r"[a-zA-Z]+"
  450. # a loose pattern such as for 80325-quicky-0.4.tar.gz
  451. pn_prefix3 = r"[0-9]+[-]?[a-zA-Z]+"
  452. # Save the Package Name (pn) Regex for use later
  453. pn_regex = r"(%s|%s|%s)" % (pn_prefix1, pn_prefix2, pn_prefix3)
  454. # match version
  455. pver_regex = r"(([A-Z]*\d+[a-zA-Z]*[\.\-_]*)+)"
  456. # match arch
  457. parch_regex = "-source|_all_"
  458. # src.rpm extension was added only for rpm package. Can be removed if the rpm
  459. # packaged will always be considered as having to be manually upgraded
  460. psuffix_regex = r"(tar\.gz|tgz|tar\.bz2|zip|xz|tar\.lz|rpm|bz2|orig\.tar\.gz|tar\.xz|src\.tar\.gz|src\.tgz|svnr\d+\.tar\.bz2|stable\.tar\.gz|src\.rpm)"
  461. # match name, version and archive type of a package
  462. package_regex_comp = re.compile(r"(?P<name>%s?\.?v?)(?P<pver>%s)(?P<arch>%s)?[\.-](?P<type>%s$)"
  463. % (pn_regex, pver_regex, parch_regex, psuffix_regex))
  464. self.suffix_regex_comp = re.compile(psuffix_regex)
  465. # compile regex, can be specific by package or generic regex
  466. pn_regex = d.getVar('UPSTREAM_CHECK_REGEX')
  467. if pn_regex:
  468. package_custom_regex_comp = re.compile(pn_regex)
  469. else:
  470. version = self._parse_path(package_regex_comp, package)
  471. if version:
  472. package_custom_regex_comp = re.compile(
  473. r"(?P<name>%s)(?P<pver>%s)(?P<arch>%s)?[\.-](?P<type>%s)" %
  474. (re.escape(version[0]), pver_regex, parch_regex, psuffix_regex))
  475. else:
  476. package_custom_regex_comp = None
  477. return package_custom_regex_comp
  478. def latest_versionstring(self, ud, d):
  479. """
  480. Manipulate the URL and try to obtain the latest package version
  481. sanity check to ensure same name and type.
  482. """
  483. package = ud.path.split("/")[-1]
  484. current_version = ['', d.getVar('PV'), '']
  485. """possible to have no version in pkg name, such as spectrum-fw"""
  486. if not re.search(r"\d+", package):
  487. current_version[1] = re.sub('_', '.', current_version[1])
  488. current_version[1] = re.sub('-', '.', current_version[1])
  489. return (current_version[1], '')
  490. package_regex = self._init_regexes(package, ud, d)
  491. if package_regex is None:
  492. bb.warn("latest_versionstring: package %s don't match pattern" % (package))
  493. return ('', '')
  494. bb.debug(3, "latest_versionstring, regex: %s" % (package_regex.pattern))
  495. uri = ""
  496. regex_uri = d.getVar("UPSTREAM_CHECK_URI")
  497. if not regex_uri:
  498. path = ud.path.split(package)[0]
  499. # search for version matches on folders inside the path, like:
  500. # "5.7" in http://download.gnome.org/sources/${PN}/5.7/${PN}-${PV}.tar.gz
  501. dirver_regex = re.compile(r"(?P<dirver>[^/]*(\d+\.)*\d+([-_]r\d+)*)/")
  502. m = dirver_regex.search(path)
  503. if m:
  504. pn = d.getVar('PN')
  505. dirver = m.group('dirver')
  506. dirver_pn_regex = re.compile(r"%s\d?" % (re.escape(pn)))
  507. if not dirver_pn_regex.search(dirver):
  508. return (self._check_latest_version_by_dir(dirver,
  509. package, package_regex, current_version, ud, d), '')
  510. uri = bb.fetch.encodeurl([ud.type, ud.host, path, ud.user, ud.pswd, {}])
  511. else:
  512. uri = regex_uri
  513. return (self._check_latest_version(uri, package, package_regex,
  514. current_version, ud, d), '')