scanpypi 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. #!/usr/bin/env python
  2. """
  3. Utility for building Buildroot packages for existing PyPI packages
  4. Any package built by scanpypi should be manually checked for
  5. errors.
  6. """
  7. from __future__ import print_function
  8. from __future__ import absolute_import
  9. import argparse
  10. import json
  11. import six.moves.urllib.request
  12. import six.moves.urllib.error
  13. import six.moves.urllib.parse
  14. import sys
  15. import os
  16. import shutil
  17. import tarfile
  18. import zipfile
  19. import errno
  20. import hashlib
  21. import re
  22. import textwrap
  23. import tempfile
  24. import imp
  25. from functools import wraps
  26. from six.moves import map
  27. from six.moves import zip
  28. from six.moves import input
  29. if six.PY2:
  30. import StringIO
  31. else:
  32. import io
  33. BUF_SIZE = 65536
  34. try:
  35. import spdx_lookup as liclookup
  36. except ImportError:
  37. # spdx_lookup is not installed
  38. print('spdx_lookup module is not installed. This can lead to an '
  39. 'inaccurate licence detection. Please install it via\n'
  40. 'pip install spdx_lookup')
  41. liclookup = None
  42. def setup_decorator(func, method):
  43. """
  44. Decorator for distutils.core.setup and setuptools.setup.
  45. Puts the arguments with which setup is called as a dict
  46. Add key 'method' which should be either 'setuptools' or 'distutils'.
  47. Keyword arguments:
  48. func -- either setuptools.setup or distutils.core.setup
  49. method -- either 'setuptools' or 'distutils'
  50. """
  51. @wraps(func)
  52. def closure(*args, **kwargs):
  53. # Any python packages calls its setup function to be installed.
  54. # Argument 'name' of this setup function is the package's name
  55. BuildrootPackage.setup_args[kwargs['name']] = kwargs
  56. BuildrootPackage.setup_args[kwargs['name']]['method'] = method
  57. return closure
  58. # monkey patch
  59. import setuptools # noqa E402
  60. setuptools.setup = setup_decorator(setuptools.setup, 'setuptools')
  61. import distutils # noqa E402
  62. distutils.core.setup = setup_decorator(setuptools.setup, 'distutils')
  63. def find_file_upper_case(filenames, path='./'):
  64. """
  65. List generator:
  66. Recursively find files that matches one of the specified filenames.
  67. Returns a relative path starting with path argument.
  68. Keyword arguments:
  69. filenames -- List of filenames to be found
  70. path -- Path to the directory to search
  71. """
  72. for root, dirs, files in os.walk(path):
  73. for file in files:
  74. if file.upper() in filenames:
  75. yield (os.path.join(root, file))
  76. def pkg_buildroot_name(pkg_name):
  77. """
  78. Returns the Buildroot package name for the PyPI package pkg_name.
  79. Remove all non alphanumeric characters except -
  80. Also lowers the name and adds 'python-' suffix
  81. Keyword arguments:
  82. pkg_name -- String to rename
  83. """
  84. name = re.sub('[^\w-]', '', pkg_name.lower())
  85. prefix = 'python-'
  86. pattern = re.compile('^(?!' + prefix + ')(.+?)$')
  87. name = pattern.sub(r'python-\1', name)
  88. return name
  89. class DownloadFailed(Exception):
  90. pass
  91. class BuildrootPackage():
  92. """This class's methods are not meant to be used individually please
  93. use them in the correct order:
  94. __init__
  95. download_package
  96. extract_package
  97. load_module
  98. get_requirements
  99. create_package_mk
  100. create_hash_file
  101. create_config_in
  102. """
  103. setup_args = {}
  104. def __init__(self, real_name, pkg_folder):
  105. self.real_name = real_name
  106. self.buildroot_name = pkg_buildroot_name(self.real_name)
  107. self.pkg_dir = os.path.join(pkg_folder, self.buildroot_name)
  108. self.mk_name = self.buildroot_name.upper().replace('-', '_')
  109. self.as_string = None
  110. self.md5_sum = None
  111. self.metadata = None
  112. self.metadata_name = None
  113. self.metadata_url = None
  114. self.pkg_req = None
  115. self.setup_metadata = None
  116. self.tmp_extract = None
  117. self.used_url = None
  118. self.filename = None
  119. self.url = None
  120. self.version = None
  121. self.license_files = []
  122. def fetch_package_info(self):
  123. """
  124. Fetch a package's metadata from the python package index
  125. """
  126. self.metadata_url = 'https://pypi.org/pypi/{pkg}/json'.format(
  127. pkg=self.real_name)
  128. try:
  129. pkg_json = six.moves.urllib.request.urlopen(self.metadata_url).read().decode()
  130. except six.moves.urllib.error.HTTPError as error:
  131. print('ERROR:', error.getcode(), error.msg, file=sys.stderr)
  132. print('ERROR: Could not find package {pkg}.\n'
  133. 'Check syntax inside the python package index:\n'
  134. 'https://pypi.python.org/pypi/ '
  135. .format(pkg=self.real_name))
  136. raise
  137. except six.moves.urllib.error.URLError:
  138. print('ERROR: Could not find package {pkg}.\n'
  139. 'Check syntax inside the python package index:\n'
  140. 'https://pypi.python.org/pypi/ '
  141. .format(pkg=self.real_name))
  142. raise
  143. self.metadata = json.loads(pkg_json)
  144. self.version = self.metadata['info']['version']
  145. self.metadata_name = self.metadata['info']['name']
  146. def download_package(self):
  147. """
  148. Download a package using metadata from pypi
  149. """
  150. download = None
  151. try:
  152. self.metadata['urls'][0]['filename']
  153. except IndexError:
  154. print(
  155. 'Non-conventional package, ',
  156. 'please check carefully after creation')
  157. self.metadata['urls'] = [{
  158. 'packagetype': 'sdist',
  159. 'url': self.metadata['info']['download_url'],
  160. 'digests': None}]
  161. # In this case, we can't get the name of the downloaded file
  162. # from the pypi api, so we need to find it, this should work
  163. urlpath = six.moves.urllib.parse.urlparse(
  164. self.metadata['info']['download_url']).path
  165. # urlparse().path give something like
  166. # /path/to/file-version.tar.gz
  167. # We use basename to remove /path/to
  168. self.metadata['urls'][0]['filename'] = os.path.basename(urlpath)
  169. for download_url in self.metadata['urls']:
  170. if 'bdist' in download_url['packagetype']:
  171. continue
  172. try:
  173. print('Downloading package {pkg} from {url}...'.format(
  174. pkg=self.real_name, url=download_url['url']))
  175. download = six.moves.urllib.request.urlopen(download_url['url'])
  176. except six.moves.urllib.error.HTTPError as http_error:
  177. download = http_error
  178. else:
  179. self.used_url = download_url
  180. self.as_string = download.read()
  181. if not download_url['digests']['md5']:
  182. break
  183. self.md5_sum = hashlib.md5(self.as_string).hexdigest()
  184. if self.md5_sum == download_url['digests']['md5']:
  185. break
  186. if download is None:
  187. raise DownloadFailed('Failed to download package {pkg}: '
  188. 'No source archive available'
  189. .format(pkg=self.real_name))
  190. elif download.__class__ == six.moves.urllib.error.HTTPError:
  191. raise download
  192. self.filename = self.used_url['filename']
  193. self.url = self.used_url['url']
  194. def extract_package(self, tmp_path):
  195. """
  196. Extract the package contents into a directrory
  197. Keyword arguments:
  198. tmp_path -- directory where you want the package to be extracted
  199. """
  200. if six.PY2:
  201. as_file = StringIO.StringIO(self.as_string)
  202. else:
  203. as_file = io.BytesIO(self.as_string)
  204. if self.filename[-3:] == 'zip':
  205. with zipfile.ZipFile(as_file) as as_zipfile:
  206. tmp_pkg = os.path.join(tmp_path, self.buildroot_name)
  207. try:
  208. os.makedirs(tmp_pkg)
  209. except OSError as exception:
  210. if exception.errno != errno.EEXIST:
  211. print("ERROR: ", exception.message, file=sys.stderr)
  212. return None, None
  213. print('WARNING:', exception.message, file=sys.stderr)
  214. print('Removing {pkg}...'.format(pkg=tmp_pkg))
  215. shutil.rmtree(tmp_pkg)
  216. os.makedirs(tmp_pkg)
  217. as_zipfile.extractall(tmp_pkg)
  218. else:
  219. with tarfile.open(fileobj=as_file) as as_tarfile:
  220. tmp_pkg = os.path.join(tmp_path, self.buildroot_name)
  221. try:
  222. os.makedirs(tmp_pkg)
  223. except OSError as exception:
  224. if exception.errno != errno.EEXIST:
  225. print("ERROR: ", exception.message, file=sys.stderr)
  226. return None, None
  227. print('WARNING:', exception.message, file=sys.stderr)
  228. print('Removing {pkg}...'.format(pkg=tmp_pkg))
  229. shutil.rmtree(tmp_pkg)
  230. os.makedirs(tmp_pkg)
  231. as_tarfile.extractall(tmp_pkg)
  232. tmp_extract = '{folder}/{name}-{version}'
  233. self.tmp_extract = tmp_extract.format(
  234. folder=tmp_pkg,
  235. name=self.metadata_name,
  236. version=self.version)
  237. def load_setup(self):
  238. """
  239. Loads the corresponding setup and store its metadata
  240. """
  241. current_dir = os.getcwd()
  242. os.chdir(self.tmp_extract)
  243. sys.path.append(self.tmp_extract)
  244. s_file, s_path, s_desc = imp.find_module('setup', [self.tmp_extract])
  245. setup = imp.load_module('setup', s_file, s_path, s_desc)
  246. try:
  247. self.setup_metadata = self.setup_args[self.metadata_name]
  248. except KeyError:
  249. # This means setup was not called which most likely mean that it is
  250. # called through the if __name__ == '__main__' directive.
  251. # In this case, we can only pray that it is called through a
  252. # function called main() in setup.py.
  253. setup.main() # Will raise AttributeError if not found
  254. self.setup_metadata = self.setup_args[self.metadata_name]
  255. # Here we must remove the module the hard way.
  256. # We must do this because of a very specific case: if a package calls
  257. # setup from the __main__ but does not come with a 'main()' function,
  258. # for some reason setup.main() will successfully call the main
  259. # function of a previous package...
  260. sys.modules.pop('setup', None)
  261. del setup
  262. os.chdir(current_dir)
  263. sys.path.remove(self.tmp_extract)
  264. def get_requirements(self, pkg_folder):
  265. """
  266. Retrieve dependencies from the metadata found in the setup.py script of
  267. a pypi package.
  268. Keyword Arguments:
  269. pkg_folder -- location of the already created packages
  270. """
  271. if 'install_requires' not in self.setup_metadata:
  272. self.pkg_req = None
  273. return set()
  274. self.pkg_req = self.setup_metadata['install_requires']
  275. self.pkg_req = [re.sub('([-.\w]+).*', r'\1', req)
  276. for req in self.pkg_req]
  277. # get rid of commented lines and also strip the package strings
  278. self.pkg_req = [item.strip() for item in self.pkg_req
  279. if len(item) > 0 and item[0] != '#']
  280. req_not_found = self.pkg_req
  281. self.pkg_req = list(map(pkg_buildroot_name, self.pkg_req))
  282. pkg_tuples = list(zip(req_not_found, self.pkg_req))
  283. # pkg_tuples is a list of tuples that looks like
  284. # ('werkzeug','python-werkzeug') because I need both when checking if
  285. # dependencies already exist or are already in the download list
  286. req_not_found = set(
  287. pkg[0] for pkg in pkg_tuples
  288. if not os.path.isdir(pkg[1])
  289. )
  290. return req_not_found
  291. def __create_mk_header(self):
  292. """
  293. Create the header of the <package_name>.mk file
  294. """
  295. header = ['#' * 80 + '\n']
  296. header.append('#\n')
  297. header.append('# {name}\n'.format(name=self.buildroot_name))
  298. header.append('#\n')
  299. header.append('#' * 80 + '\n')
  300. header.append('\n')
  301. return header
  302. def __create_mk_download_info(self):
  303. """
  304. Create the lines refering to the download information of the
  305. <package_name>.mk file
  306. """
  307. lines = []
  308. version_line = '{name}_VERSION = {version}\n'.format(
  309. name=self.mk_name,
  310. version=self.version)
  311. lines.append(version_line)
  312. targz = self.filename.replace(
  313. self.version,
  314. '$({name}_VERSION)'.format(name=self.mk_name))
  315. targz_line = '{name}_SOURCE = {filename}\n'.format(
  316. name=self.mk_name,
  317. filename=targz)
  318. lines.append(targz_line)
  319. if self.filename not in self.url:
  320. # Sometimes the filename is in the url, sometimes it's not
  321. site_url = self.url
  322. else:
  323. site_url = self.url[:self.url.find(self.filename)]
  324. site_line = '{name}_SITE = {url}'.format(name=self.mk_name,
  325. url=site_url)
  326. site_line = site_line.rstrip('/') + '\n'
  327. lines.append(site_line)
  328. return lines
  329. def __create_mk_setup(self):
  330. """
  331. Create the line refering to the setup method of the package of the
  332. <package_name>.mk file
  333. There are two things you can use to make an installer
  334. for a python package: distutils or setuptools
  335. distutils comes with python but does not support dependencies.
  336. distutils is mostly still there for backward support.
  337. setuptools is what smart people use,
  338. but it is not shipped with python :(
  339. """
  340. lines = []
  341. setup_type_line = '{name}_SETUP_TYPE = {method}\n'.format(
  342. name=self.mk_name,
  343. method=self.setup_metadata['method'])
  344. lines.append(setup_type_line)
  345. return lines
  346. def __get_license_names(self, license_files):
  347. """
  348. Try to determine the related license name.
  349. There are two possibilities. Either the scripts tries to
  350. get license name from package's metadata or, if spdx_lookup
  351. package is available, the script compares license files with
  352. SPDX database.
  353. """
  354. license_line = ''
  355. if liclookup is None:
  356. license_dict = {
  357. 'Apache Software License': 'Apache-2.0',
  358. 'BSD License': 'BSD',
  359. 'European Union Public Licence 1.0': 'EUPL-1.0',
  360. 'European Union Public Licence 1.1': 'EUPL-1.1',
  361. "GNU General Public License": "GPL",
  362. "GNU General Public License v2": "GPL-2.0",
  363. "GNU General Public License v2 or later": "GPL-2.0+",
  364. "GNU General Public License v3": "GPL-3.0",
  365. "GNU General Public License v3 or later": "GPL-3.0+",
  366. "GNU Lesser General Public License v2": "LGPL-2.1",
  367. "GNU Lesser General Public License v2 or later": "LGPL-2.1+",
  368. "GNU Lesser General Public License v3": "LGPL-3.0",
  369. "GNU Lesser General Public License v3 or later": "LGPL-3.0+",
  370. "GNU Library or Lesser General Public License": "LGPL-2.0",
  371. "ISC License": "ISC",
  372. "MIT License": "MIT",
  373. "Mozilla Public License 1.0": "MPL-1.0",
  374. "Mozilla Public License 1.1": "MPL-1.1",
  375. "Mozilla Public License 2.0": "MPL-2.0",
  376. "Zope Public License": "ZPL"
  377. }
  378. regexp = re.compile('^License :* *.* *:+ (.*)( \(.*\))?$')
  379. classifiers_licenses = [regexp.sub(r"\1", lic)
  380. for lic in self.metadata['info']['classifiers']
  381. if regexp.match(lic)]
  382. licenses = [license_dict[x] if x in license_dict else x for x in classifiers_licenses]
  383. if not len(licenses):
  384. print('WARNING: License has been set to "{license}". It is most'
  385. ' likely wrong, please change it if need be'.format(
  386. license=', '.join(licenses)))
  387. licenses = [self.metadata['info']['license']]
  388. license_line = '{name}_LICENSE = {license}\n'.format(
  389. name=self.mk_name,
  390. license=', '.join(licenses))
  391. else:
  392. license_names = []
  393. for license_file in license_files:
  394. with open(license_file) as lic_file:
  395. match = liclookup.match(lic_file.read())
  396. if match is not None and match.confidence >= 90.0:
  397. license_names.append(match.license.id)
  398. if len(license_names) > 0:
  399. license_line = ('{name}_LICENSE ='
  400. ' {names}\n'.format(
  401. name=self.mk_name,
  402. names=', '.join(license_names)))
  403. return license_line
  404. def __create_mk_license(self):
  405. """
  406. Create the lines referring to the package's license informations of the
  407. <package_name>.mk file
  408. The license's files are found by searching the package (case insensitive)
  409. for files named license, license.txt etc. If more than one license file
  410. is found, the user is asked to select which ones he wants to use.
  411. """
  412. lines = []
  413. filenames = ['LICENCE', 'LICENSE', 'LICENSE.RST', 'LICENSE.TXT',
  414. 'COPYING', 'COPYING.TXT']
  415. self.license_files = list(find_file_upper_case(filenames, self.tmp_extract))
  416. lines.append(self.__get_license_names(self.license_files))
  417. license_files = [license.replace(self.tmp_extract, '')[1:]
  418. for license in self.license_files]
  419. if len(license_files) > 0:
  420. if len(license_files) > 1:
  421. print('More than one file found for license:',
  422. ', '.join(license_files))
  423. license_files = [filename
  424. for index, filename in enumerate(license_files)]
  425. license_file_line = ('{name}_LICENSE_FILES ='
  426. ' {files}\n'.format(
  427. name=self.mk_name,
  428. files=' '.join(license_files)))
  429. lines.append(license_file_line)
  430. else:
  431. print('WARNING: No license file found,'
  432. ' please specify it manually afterwards')
  433. license_file_line = '# No license file found\n'
  434. return lines
  435. def __create_mk_requirements(self):
  436. """
  437. Create the lines referring to the dependencies of the of the
  438. <package_name>.mk file
  439. Keyword Arguments:
  440. pkg_name -- name of the package
  441. pkg_req -- dependencies of the package
  442. """
  443. lines = []
  444. dependencies_line = ('{name}_DEPENDENCIES ='
  445. ' {reqs}\n'.format(
  446. name=self.mk_name,
  447. reqs=' '.join(self.pkg_req)))
  448. lines.append(dependencies_line)
  449. return lines
  450. def create_package_mk(self):
  451. """
  452. Create the lines corresponding to the <package_name>.mk file
  453. """
  454. pkg_mk = '{name}.mk'.format(name=self.buildroot_name)
  455. path_to_mk = os.path.join(self.pkg_dir, pkg_mk)
  456. print('Creating {file}...'.format(file=path_to_mk))
  457. lines = self.__create_mk_header()
  458. lines += self.__create_mk_download_info()
  459. lines += self.__create_mk_setup()
  460. lines += self.__create_mk_license()
  461. lines.append('\n')
  462. lines.append('$(eval $(python-package))')
  463. lines.append('\n')
  464. with open(path_to_mk, 'w') as mk_file:
  465. mk_file.writelines(lines)
  466. def create_hash_file(self):
  467. """
  468. Create the lines corresponding to the <package_name>.hash files
  469. """
  470. pkg_hash = '{name}.hash'.format(name=self.buildroot_name)
  471. path_to_hash = os.path.join(self.pkg_dir, pkg_hash)
  472. print('Creating {filename}...'.format(filename=path_to_hash))
  473. lines = []
  474. if self.used_url['digests']['md5'] and self.used_url['digests']['sha256']:
  475. hash_header = '# md5, sha256 from {url}\n'.format(
  476. url=self.metadata_url)
  477. lines.append(hash_header)
  478. hash_line = '{method}\t{digest} {filename}\n'.format(
  479. method='md5',
  480. digest=self.used_url['digests']['md5'],
  481. filename=self.filename)
  482. lines.append(hash_line)
  483. hash_line = '{method}\t{digest} {filename}\n'.format(
  484. method='sha256',
  485. digest=self.used_url['digests']['sha256'],
  486. filename=self.filename)
  487. lines.append(hash_line)
  488. if self.license_files:
  489. lines.append('# Locally computed sha256 checksums\n')
  490. for license_file in self.license_files:
  491. sha256 = hashlib.sha256()
  492. with open(license_file, 'rb') as lic_f:
  493. while True:
  494. data = lic_f.read(BUF_SIZE)
  495. if not data:
  496. break
  497. sha256.update(data)
  498. hash_line = '{method}\t{digest} {filename}\n'.format(
  499. method='sha256',
  500. digest=sha256.hexdigest(),
  501. filename=license_file.replace(self.tmp_extract, '')[1:])
  502. lines.append(hash_line)
  503. with open(path_to_hash, 'w') as hash_file:
  504. hash_file.writelines(lines)
  505. def create_config_in(self):
  506. """
  507. Creates the Config.in file of a package
  508. """
  509. path_to_config = os.path.join(self.pkg_dir, 'Config.in')
  510. print('Creating {file}...'.format(file=path_to_config))
  511. lines = []
  512. config_line = 'config BR2_PACKAGE_{name}\n'.format(
  513. name=self.mk_name)
  514. lines.append(config_line)
  515. bool_line = '\tbool "{name}"\n'.format(name=self.buildroot_name)
  516. lines.append(bool_line)
  517. if self.pkg_req:
  518. for dep in self.pkg_req:
  519. dep_line = '\tselect BR2_PACKAGE_{req} # runtime\n'.format(
  520. req=dep.upper().replace('-', '_'))
  521. lines.append(dep_line)
  522. lines.append('\thelp\n')
  523. help_lines = textwrap.wrap(self.metadata['info']['summary'], 62,
  524. initial_indent='\t ',
  525. subsequent_indent='\t ')
  526. # make sure a help text is terminated with a full stop
  527. if help_lines[-1][-1] != '.':
  528. help_lines[-1] += '.'
  529. # \t + two spaces is 3 char long
  530. help_lines.append('')
  531. help_lines.append('\t ' + self.metadata['info']['home_page'])
  532. help_lines = [x + '\n' for x in help_lines]
  533. lines += help_lines
  534. with open(path_to_config, 'w') as config_file:
  535. config_file.writelines(lines)
  536. def main():
  537. # Building the parser
  538. parser = argparse.ArgumentParser(
  539. description="Creates buildroot packages from the metadata of "
  540. "an existing PyPI packages and include it "
  541. "in menuconfig")
  542. parser.add_argument("packages",
  543. help="list of packages to be created",
  544. nargs='+')
  545. parser.add_argument("-o", "--output",
  546. help="""
  547. Output directory for packages.
  548. Default is ./package
  549. """,
  550. default='./package')
  551. args = parser.parse_args()
  552. packages = list(set(args.packages))
  553. # tmp_path is where we'll extract the files later
  554. tmp_prefix = 'scanpypi-'
  555. pkg_folder = args.output
  556. tmp_path = tempfile.mkdtemp(prefix=tmp_prefix)
  557. try:
  558. for real_pkg_name in packages:
  559. package = BuildrootPackage(real_pkg_name, pkg_folder)
  560. print('buildroot package name for {}:'.format(package.real_name),
  561. package.buildroot_name)
  562. # First we download the package
  563. # Most of the info we need can only be found inside the package
  564. print('Package:', package.buildroot_name)
  565. print('Fetching package', package.real_name)
  566. try:
  567. package.fetch_package_info()
  568. except (six.moves.urllib.error.URLError, six.moves.urllib.error.HTTPError):
  569. continue
  570. if package.metadata_name.lower() == 'setuptools':
  571. # setuptools imports itself, that does not work very well
  572. # with the monkey path at the begining
  573. print('Error: setuptools cannot be built using scanPyPI')
  574. continue
  575. try:
  576. package.download_package()
  577. except six.moves.urllib.error.HTTPError as error:
  578. print('Error: {code} {reason}'.format(code=error.code,
  579. reason=error.reason))
  580. print('Error downloading package :', package.buildroot_name)
  581. print()
  582. continue
  583. # extract the tarball
  584. try:
  585. package.extract_package(tmp_path)
  586. except (tarfile.ReadError, zipfile.BadZipfile):
  587. print('Error extracting package {}'.format(package.real_name))
  588. print()
  589. continue
  590. # Loading the package install info from the package
  591. try:
  592. package.load_setup()
  593. except ImportError as err:
  594. if 'buildutils' in err.message:
  595. print('This package needs buildutils')
  596. else:
  597. raise
  598. continue
  599. except AttributeError as error:
  600. print('Error: Could not install package {pkg}: {error}'.format(
  601. pkg=package.real_name, error=error))
  602. continue
  603. # Package requirement are an argument of the setup function
  604. req_not_found = package.get_requirements(pkg_folder)
  605. req_not_found = req_not_found.difference(packages)
  606. packages += req_not_found
  607. if req_not_found:
  608. print('Added packages \'{pkgs}\' as dependencies of {pkg}'
  609. .format(pkgs=", ".join(req_not_found),
  610. pkg=package.buildroot_name))
  611. print('Checking if package {name} already exists...'.format(
  612. name=package.pkg_dir))
  613. try:
  614. os.makedirs(package.pkg_dir)
  615. except OSError as exception:
  616. if exception.errno != errno.EEXIST:
  617. print("ERROR: ", exception.message, file=sys.stderr)
  618. continue
  619. print('Error: Package {name} already exists'
  620. .format(name=package.pkg_dir))
  621. del_pkg = input(
  622. 'Do you want to delete existing package ? [y/N]')
  623. if del_pkg.lower() == 'y':
  624. shutil.rmtree(package.pkg_dir)
  625. os.makedirs(package.pkg_dir)
  626. else:
  627. continue
  628. package.create_package_mk()
  629. package.create_hash_file()
  630. package.create_config_in()
  631. print()
  632. # printing an empty line for visual confort
  633. finally:
  634. shutil.rmtree(tmp_path)
  635. if __name__ == "__main__":
  636. main()