scanpypi 26 KB

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