2
1

scanpypi 26 KB

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