scanpypi 27 KB

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