scanpypi 27 KB

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