scanpypi 28 KB

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