scanpypi 27 KB

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