2
1

scanpypi 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0-or-later AND MIT
  3. """
  4. Utility for building Buildroot packages for existing PyPI packages
  5. Any package built by scanpypi should be manually checked for
  6. errors.
  7. """
  8. import argparse
  9. import json
  10. import sys
  11. import os
  12. import shutil
  13. import tarfile
  14. import zipfile
  15. import errno
  16. import hashlib
  17. import re
  18. import textwrap
  19. import tempfile
  20. import traceback
  21. import importlib
  22. import importlib.metadata
  23. import six.moves.urllib.request
  24. import six.moves.urllib.error
  25. import six.moves.urllib.parse
  26. from six.moves import map
  27. from six.moves import zip
  28. from six.moves import input
  29. if six.PY2:
  30. import StringIO
  31. else:
  32. import io
  33. BUF_SIZE = 65536
  34. try:
  35. import spdx_lookup as liclookup
  36. except ImportError:
  37. # spdx_lookup is not installed
  38. print('spdx_lookup module is not installed. This can lead to an '
  39. 'inaccurate licence detection. Please install it via\n'
  40. 'pip install spdx_lookup')
  41. liclookup = None
  42. def toml_load(f):
  43. with open(f, 'rb') as fh:
  44. ex = None
  45. # Try standard library tomllib first
  46. try:
  47. from tomllib import load
  48. return load(fh)
  49. except ImportError:
  50. pass
  51. # Try regular tomli next
  52. try:
  53. from tomli import load
  54. return load(fh)
  55. except ImportError as e:
  56. ex = e
  57. # Try pip's vendored tomli
  58. try:
  59. from pip._vendor.tomli import load
  60. try:
  61. return load(fh)
  62. except TypeError:
  63. # Fallback to handle older version
  64. try:
  65. fh.seek(0)
  66. w = io.TextIOWrapper(fh, encoding="utf8", newline="")
  67. return load(w)
  68. finally:
  69. w.detach()
  70. except ImportError:
  71. pass
  72. # Try regular toml last
  73. try:
  74. from toml import load
  75. fh.seek(0)
  76. w = io.TextIOWrapper(fh, encoding="utf8", newline="")
  77. try:
  78. return load(w)
  79. finally:
  80. w.detach()
  81. except ImportError:
  82. pass
  83. print('This package needs tomli')
  84. raise ex
  85. def find_file_upper_case(filenames, path='./'):
  86. """
  87. List generator:
  88. Recursively find files that matches one of the specified filenames.
  89. Returns a relative path starting with path argument.
  90. Keyword arguments:
  91. filenames -- List of filenames to be found
  92. path -- Path to the directory to search
  93. """
  94. for root, dirs, files in os.walk(path):
  95. for file in files:
  96. if file.upper() in filenames:
  97. yield (os.path.join(root, file))
  98. def pkg_buildroot_name(pkg_name):
  99. """
  100. Returns the Buildroot package name for the PyPI package pkg_name.
  101. Remove all non alphanumeric characters except -
  102. Also lowers the name and adds 'python-' suffix
  103. Keyword arguments:
  104. pkg_name -- String to rename
  105. """
  106. name = re.sub(r'[^\w-]', '', pkg_name.lower())
  107. name = name.replace('_', '-')
  108. prefix = 'python-'
  109. pattern = re.compile(r'^(?!' + prefix + ')(.+?)$')
  110. name = pattern.sub(r'python-\1', name)
  111. return name
  112. class DownloadFailed(Exception):
  113. pass
  114. # Copied and adapted from
  115. # https://github.com/pypa/pyproject-hooks/blob/v1.1.0/src/pyproject_hooks/_in_process/_in_process.py
  116. # SPDX-License-Identifier: MIT
  117. class BackendUnavailable(Exception):
  118. """Raised if we cannot import the backend"""
  119. def __init__(self, message, traceback=None):
  120. super().__init__(message)
  121. self.message = message
  122. self.traceback = traceback
  123. class BackendPathFinder:
  124. """Implements the MetaPathFinder interface to locate modules in ``backend-path``.
  125. Since the environment provided by the frontend can contain all sorts of
  126. MetaPathFinders, the only way to ensure the backend is loaded from the
  127. right place is to prepend our own.
  128. """
  129. def __init__(self, backend_path, backend_module):
  130. self.backend_path = backend_path
  131. self.backend_module = backend_module
  132. self.backend_parent, _, _ = backend_module.partition(".")
  133. def find_spec(self, fullname, _path, _target=None):
  134. if "." in fullname:
  135. # Rely on importlib to find nested modules based on parent's path
  136. return None
  137. # Ignore other items in _path or sys.path and use backend_path instead:
  138. spec = importlib.machinery.PathFinder.find_spec(fullname, path=self.backend_path)
  139. if spec is None and fullname == self.backend_parent:
  140. # According to the spec, the backend MUST be loaded from backend-path.
  141. # Therefore, we can halt the import machinery and raise a clean error.
  142. msg = f"Cannot find module {self.backend_module!r} in {self.backend_path!r}"
  143. raise BackendUnavailable(msg)
  144. return spec
  145. class BuildrootPackage():
  146. """This class's methods are not meant to be used individually please
  147. use them in the correct order:
  148. __init__
  149. download_package
  150. extract_package
  151. load_module
  152. get_requirements
  153. create_package_mk
  154. create_hash_file
  155. create_config_in
  156. """
  157. setup_args = {}
  158. def __init__(self, real_name, pkg_folder):
  159. self.real_name = real_name
  160. self.buildroot_name = pkg_buildroot_name(self.real_name)
  161. self.pkg_dir = os.path.join(pkg_folder, self.buildroot_name)
  162. self.mk_name = self.buildroot_name.upper().replace('-', '_')
  163. self.as_string = None
  164. self.md5_sum = None
  165. self.metadata = None
  166. self.metadata_name = None
  167. self.metadata_url = None
  168. self.pkg_req = None
  169. self.setup_metadata = None
  170. self.backend_path = None
  171. self.build_backend = None
  172. self.tmp_extract = None
  173. self.used_url = None
  174. self.filename = None
  175. self.url = None
  176. self.version = None
  177. self.license_files = []
  178. def fetch_package_info(self):
  179. """
  180. Fetch a package's metadata from the python package index
  181. """
  182. self.metadata_url = 'https://pypi.org/pypi/{pkg}/json'.format(
  183. pkg=self.real_name)
  184. try:
  185. pkg_json = six.moves.urllib.request.urlopen(self.metadata_url).read().decode()
  186. except six.moves.urllib.error.HTTPError as error:
  187. print('ERROR:', error.getcode(), error.msg, file=sys.stderr)
  188. print('ERROR: Could not find package {pkg}.\n'
  189. 'Check syntax inside the python package index:\n'
  190. 'https://pypi.python.org/pypi/ '
  191. .format(pkg=self.real_name))
  192. raise
  193. except six.moves.urllib.error.URLError:
  194. print('ERROR: Could not find package {pkg}.\n'
  195. 'Check syntax inside the python package index:\n'
  196. 'https://pypi.python.org/pypi/ '
  197. .format(pkg=self.real_name))
  198. raise
  199. self.metadata = json.loads(pkg_json)
  200. self.version = self.metadata['info']['version']
  201. self.metadata_name = self.metadata['info']['name']
  202. def download_package(self):
  203. """
  204. Download a package using metadata from pypi
  205. """
  206. download = None
  207. try:
  208. self.metadata['urls'][0]['filename']
  209. except IndexError:
  210. print(
  211. 'Non-conventional package, ',
  212. 'please check carefully after creation')
  213. self.metadata['urls'] = [{
  214. 'packagetype': 'sdist',
  215. 'url': self.metadata['info']['download_url'],
  216. 'digests': None}]
  217. # In this case, we can't get the name of the downloaded file
  218. # from the pypi api, so we need to find it, this should work
  219. urlpath = six.moves.urllib.parse.urlparse(
  220. self.metadata['info']['download_url']).path
  221. # urlparse().path give something like
  222. # /path/to/file-version.tar.gz
  223. # We use basename to remove /path/to
  224. self.metadata['urls'][0]['filename'] = os.path.basename(urlpath)
  225. for download_url in self.metadata['urls']:
  226. if 'bdist' in download_url['packagetype']:
  227. continue
  228. try:
  229. print('Downloading package {pkg} from {url}...'.format(
  230. pkg=self.real_name, url=download_url['url']))
  231. download = six.moves.urllib.request.urlopen(download_url['url'])
  232. except six.moves.urllib.error.HTTPError as http_error:
  233. download = http_error
  234. else:
  235. self.used_url = download_url
  236. self.as_string = download.read()
  237. if not download_url['digests']['md5']:
  238. break
  239. self.md5_sum = hashlib.md5(self.as_string).hexdigest()
  240. if self.md5_sum == download_url['digests']['md5']:
  241. break
  242. if download is None:
  243. raise DownloadFailed('Failed to download package {pkg}: '
  244. 'No source archive available'
  245. .format(pkg=self.real_name))
  246. elif download.__class__ == six.moves.urllib.error.HTTPError:
  247. raise download
  248. self.filename = self.used_url['filename']
  249. self.url = self.used_url['url']
  250. def check_archive(self, members):
  251. """
  252. Check archive content before extracting
  253. Keyword arguments:
  254. members -- list of archive members
  255. """
  256. # Protect against https://github.com/snyk/zip-slip-vulnerability
  257. # Older python versions do not validate that the extracted files are
  258. # inside the target directory. Detect and error out on evil paths
  259. evil = [e for e in members if os.path.relpath(e).startswith(('/', '..'))]
  260. if evil:
  261. print('ERROR: Refusing to extract {} with suspicious members {}'.format(
  262. self.filename, evil))
  263. sys.exit(1)
  264. def extract_package(self, tmp_path):
  265. """
  266. Extract the package content into a directory
  267. Keyword arguments:
  268. tmp_path -- directory where you want the package to be extracted
  269. """
  270. if six.PY2:
  271. as_file = StringIO.StringIO(self.as_string)
  272. else:
  273. as_file = io.BytesIO(self.as_string)
  274. if self.filename[-3:] == 'zip':
  275. with zipfile.ZipFile(as_file) as as_zipfile:
  276. tmp_pkg = os.path.join(tmp_path, self.buildroot_name)
  277. try:
  278. os.makedirs(tmp_pkg)
  279. except OSError as exception:
  280. if exception.errno != errno.EEXIST:
  281. print("ERROR: ", exception.strerror, file=sys.stderr)
  282. return
  283. print('WARNING:', exception.strerror, file=sys.stderr)
  284. print('Removing {pkg}...'.format(pkg=tmp_pkg))
  285. shutil.rmtree(tmp_pkg)
  286. os.makedirs(tmp_pkg)
  287. self.check_archive(as_zipfile.namelist())
  288. as_zipfile.extractall(tmp_pkg)
  289. pkg_filename = self.filename.split(".zip")[0]
  290. else:
  291. with tarfile.open(fileobj=as_file) as as_tarfile:
  292. tmp_pkg = os.path.join(tmp_path, self.buildroot_name)
  293. try:
  294. os.makedirs(tmp_pkg)
  295. except OSError as exception:
  296. if exception.errno != errno.EEXIST:
  297. print("ERROR: ", exception.strerror, file=sys.stderr)
  298. return
  299. print('WARNING:', exception.strerror, file=sys.stderr)
  300. print('Removing {pkg}...'.format(pkg=tmp_pkg))
  301. shutil.rmtree(tmp_pkg)
  302. os.makedirs(tmp_pkg)
  303. self.check_archive(as_tarfile.getnames())
  304. as_tarfile.extractall(tmp_pkg)
  305. pkg_filename = self.filename.split(".tar")[0]
  306. tmp_extract = '{folder}/{name}'
  307. self.tmp_extract = tmp_extract.format(
  308. folder=tmp_pkg,
  309. name=pkg_filename)
  310. def load_metadata(self):
  311. """
  312. Loads the corresponding setup and store its metadata
  313. """
  314. current_dir = os.getcwd()
  315. os.chdir(self.tmp_extract)
  316. try:
  317. mod_path, _, obj_path = self.build_backend.partition(":")
  318. path_finder = None
  319. if self.backend_path:
  320. path_finder = BackendPathFinder(self.backend_path, mod_path)
  321. sys.meta_path.insert(0, path_finder)
  322. try:
  323. build_backend = importlib.import_module(self.build_backend)
  324. except ImportError:
  325. msg = f"Cannot import {mod_path!r}"
  326. raise BackendUnavailable(msg, traceback.format_exc())
  327. if obj_path:
  328. for path_part in obj_path.split("."):
  329. build_backend = getattr(build_backend, path_part)
  330. if path_finder:
  331. sys.meta_path.remove(path_finder)
  332. prepare_metadata_for_build_wheel = getattr(
  333. build_backend, 'prepare_metadata_for_build_wheel'
  334. )
  335. metadata = prepare_metadata_for_build_wheel(self.tmp_extract)
  336. try:
  337. dist = importlib.metadata.Distribution.at(metadata)
  338. self.metadata_name = dist.name
  339. if dist.requires:
  340. self.setup_metadata['install_requires'] = dist.requires
  341. finally:
  342. shutil.rmtree(metadata)
  343. finally:
  344. os.chdir(current_dir)
  345. def load_pyproject(self):
  346. """
  347. Loads the corresponding pyproject.toml and store its metadata
  348. """
  349. current_dir = os.getcwd()
  350. os.chdir(self.tmp_extract)
  351. try:
  352. pyproject_data = toml_load('pyproject.toml')
  353. self.setup_metadata = pyproject_data.get('project', {})
  354. self.metadata_name = self.setup_metadata.get('name', self.real_name)
  355. build_system = pyproject_data.get('build-system', {})
  356. build_backend = build_system.get('build-backend', None)
  357. self.backend_path = build_system.get('backend-path', None)
  358. if build_backend:
  359. self.build_backend = build_backend
  360. if build_backend == 'flit_core.buildapi':
  361. self.setup_metadata['method'] = 'flit'
  362. elif build_backend == 'setuptools.build_meta':
  363. self.setup_metadata['method'] = 'setuptools'
  364. else:
  365. if self.backend_path:
  366. self.setup_metadata['method'] = 'pep517'
  367. else:
  368. self.setup_metadata['method'] = 'unknown'
  369. else:
  370. self.build_backend = 'setuptools.build_meta'
  371. self.setup_metadata = {'method': 'setuptools'}
  372. except FileNotFoundError:
  373. self.build_backend = 'setuptools.build_meta'
  374. self.setup_metadata = {'method': 'setuptools'}
  375. finally:
  376. os.chdir(current_dir)
  377. def get_requirements(self, pkg_folder):
  378. """
  379. Retrieve dependencies from the metadata found in the setup.py script of
  380. a pypi package.
  381. Keyword Arguments:
  382. pkg_folder -- location of the already created packages
  383. """
  384. if 'install_requires' not in self.setup_metadata:
  385. self.pkg_req = None
  386. return set()
  387. self.pkg_req = set()
  388. extra_re = re.compile(r'''extra\s*==\s*("([^"]+)"|'([^']+)')''')
  389. for req in self.setup_metadata['install_requires']:
  390. if not extra_re.search(req):
  391. self.pkg_req.add(req)
  392. self.pkg_req = [re.sub(r'([-.\w]+).*', r'\1', req)
  393. for req in self.pkg_req]
  394. # get rid of commented lines and also strip the package strings
  395. self.pkg_req = {item.strip() for item in self.pkg_req
  396. if len(item) > 0 and item[0] != '#'}
  397. req_not_found = self.pkg_req
  398. self.pkg_req = list(map(pkg_buildroot_name, self.pkg_req))
  399. pkg_tuples = list(zip(req_not_found, self.pkg_req))
  400. # pkg_tuples is a list of tuples that looks like
  401. # ('werkzeug','python-werkzeug') because I need both when checking if
  402. # dependencies already exist or are already in the download list
  403. req_not_found = set(
  404. pkg[0] for pkg in pkg_tuples
  405. if not os.path.isdir(pkg[1])
  406. )
  407. return req_not_found
  408. def __create_mk_header(self):
  409. """
  410. Create the header of the <package_name>.mk file
  411. """
  412. header = ['#' * 80 + '\n']
  413. header.append('#\n')
  414. header.append('# {name}\n'.format(name=self.buildroot_name))
  415. header.append('#\n')
  416. header.append('#' * 80 + '\n')
  417. header.append('\n')
  418. return header
  419. def __create_mk_download_info(self):
  420. """
  421. Create the lines referring to the download information of the
  422. <package_name>.mk file
  423. """
  424. lines = []
  425. version_line = '{name}_VERSION = {version}\n'.format(
  426. name=self.mk_name,
  427. version=self.version)
  428. lines.append(version_line)
  429. if self.buildroot_name != self.real_name:
  430. targz = self.filename.replace(
  431. self.version,
  432. '$({name}_VERSION)'.format(name=self.mk_name))
  433. targz_line = '{name}_SOURCE = {filename}\n'.format(
  434. name=self.mk_name,
  435. filename=targz)
  436. lines.append(targz_line)
  437. if self.filename not in self.url:
  438. # Sometimes the filename is in the url, sometimes it's not
  439. site_url = self.url
  440. else:
  441. site_url = self.url[:self.url.find(self.filename)]
  442. site_line = '{name}_SITE = {url}'.format(name=self.mk_name,
  443. url=site_url)
  444. site_line = site_line.rstrip('/') + '\n'
  445. lines.append(site_line)
  446. return lines
  447. def __create_mk_setup(self):
  448. """
  449. Create the line referring to the setup method of the package of the
  450. <package_name>.mk file
  451. There are two things you can use to make an installer
  452. for a python package: distutils or setuptools
  453. distutils comes with python but does not support dependencies.
  454. distutils is mostly still there for backward support.
  455. setuptools is what smart people use,
  456. but it is not shipped with python :(
  457. """
  458. lines = []
  459. setup_type_line = '{name}_SETUP_TYPE = {method}\n'.format(
  460. name=self.mk_name,
  461. method=self.setup_metadata['method'])
  462. lines.append(setup_type_line)
  463. return lines
  464. def __get_license_names(self, license_files):
  465. """
  466. Try to determine the related license name.
  467. There are two possibilities. Either the script tries to
  468. get license name from package's metadata or, if spdx_lookup
  469. package is available, the script compares license files with
  470. SPDX database.
  471. """
  472. license_line = ''
  473. if liclookup is None:
  474. license_dict = {
  475. 'Apache Software License': 'Apache-2.0',
  476. 'BSD License': 'FIXME: please specify the exact BSD version',
  477. 'European Union Public Licence 1.0': 'EUPL-1.0',
  478. 'European Union Public Licence 1.1': 'EUPL-1.1',
  479. "GNU General Public License": "GPL",
  480. "GNU General Public License v2": "GPL-2.0",
  481. "GNU General Public License v2 or later": "GPL-2.0+",
  482. "GNU General Public License v3": "GPL-3.0",
  483. "GNU General Public License v3 or later": "GPL-3.0+",
  484. "GNU Lesser General Public License v2": "LGPL-2.1",
  485. "GNU Lesser General Public License v2 or later": "LGPL-2.1+",
  486. "GNU Lesser General Public License v3": "LGPL-3.0",
  487. "GNU Lesser General Public License v3 or later": "LGPL-3.0+",
  488. "GNU Library or Lesser General Public License": "LGPL-2.0",
  489. "ISC License": "ISC",
  490. "MIT License": "MIT",
  491. "Mozilla Public License 1.0": "MPL-1.0",
  492. "Mozilla Public License 1.1": "MPL-1.1",
  493. "Mozilla Public License 2.0": "MPL-2.0",
  494. "Zope Public License": "ZPL"
  495. }
  496. regexp = re.compile(r'^License :* *.* *:+ (.*)( \(.*\))?$')
  497. classifiers_licenses = [regexp.sub(r"\1", lic)
  498. for lic in self.metadata['info']['classifiers']
  499. if regexp.match(lic)]
  500. licenses = [license_dict[x] if x in license_dict else x for x in classifiers_licenses]
  501. if not len(licenses):
  502. print('WARNING: License has been set to "{license}". It is most'
  503. ' likely wrong, please change it if need be'.format(
  504. license=', '.join(licenses)))
  505. licenses = [self.metadata['info']['license']]
  506. licenses = set(licenses)
  507. license_line = '{name}_LICENSE = {license}\n'.format(
  508. name=self.mk_name,
  509. license=', '.join(licenses))
  510. else:
  511. license_names = []
  512. for license_file in license_files:
  513. with open(license_file) as lic_file:
  514. match = liclookup.match(lic_file.read())
  515. if match is not None and match.confidence >= 90.0:
  516. license_names.append(match.license.id)
  517. else:
  518. license_names.append("FIXME: license id couldn't be detected")
  519. license_names = set(license_names)
  520. if len(license_names) > 0:
  521. license_line = ('{name}_LICENSE ='
  522. ' {names}\n'.format(
  523. name=self.mk_name,
  524. names=', '.join(license_names)))
  525. return license_line
  526. def __create_mk_license(self):
  527. """
  528. Create the lines referring to the package's license information of the
  529. <package_name>.mk file
  530. The license's files are found by searching the package (case insensitive)
  531. for files named license, license.txt etc. If more than one license file
  532. is found, the user is asked to select which ones he wants to use.
  533. """
  534. lines = []
  535. filenames = ['LICENCE', 'LICENSE', 'LICENSE.MD', 'LICENSE.RST',
  536. 'LICENCE.TXT', 'LICENSE.TXT', 'COPYING', 'COPYING.TXT']
  537. self.license_files = list(find_file_upper_case(filenames, self.tmp_extract))
  538. lines.append(self.__get_license_names(self.license_files))
  539. license_files = [license.replace(self.tmp_extract, '')[1:]
  540. for license in self.license_files]
  541. if len(license_files) > 0:
  542. if len(license_files) > 1:
  543. print('More than one file found for license:',
  544. ', '.join(license_files))
  545. license_files = [filename
  546. for index, filename in enumerate(license_files)]
  547. license_file_line = ('{name}_LICENSE_FILES ='
  548. ' {files}\n'.format(
  549. name=self.mk_name,
  550. files=' '.join(license_files)))
  551. lines.append(license_file_line)
  552. else:
  553. print('WARNING: No license file found,'
  554. ' please specify it manually afterwards')
  555. license_file_line = '# No license file found\n'
  556. return lines
  557. def __create_mk_requirements(self):
  558. """
  559. Create the lines referring to the dependencies of the of the
  560. <package_name>.mk file
  561. Keyword Arguments:
  562. pkg_name -- name of the package
  563. pkg_req -- dependencies of the package
  564. """
  565. lines = []
  566. dependencies_line = ('{name}_DEPENDENCIES ='
  567. ' {reqs}\n'.format(
  568. name=self.mk_name,
  569. reqs=' '.join(self.pkg_req)))
  570. lines.append(dependencies_line)
  571. return lines
  572. def create_package_mk(self):
  573. """
  574. Create the lines corresponding to the <package_name>.mk file
  575. """
  576. pkg_mk = '{name}.mk'.format(name=self.buildroot_name)
  577. path_to_mk = os.path.join(self.pkg_dir, pkg_mk)
  578. print('Creating {file}...'.format(file=path_to_mk))
  579. lines = self.__create_mk_header()
  580. lines += self.__create_mk_download_info()
  581. lines += self.__create_mk_setup()
  582. lines += self.__create_mk_license()
  583. lines.append('\n')
  584. lines.append('$(eval $(python-package))')
  585. lines.append('\n')
  586. with open(path_to_mk, 'w') as mk_file:
  587. mk_file.writelines(lines)
  588. def create_hash_file(self):
  589. """
  590. Create the lines corresponding to the <package_name>.hash files
  591. """
  592. pkg_hash = '{name}.hash'.format(name=self.buildroot_name)
  593. path_to_hash = os.path.join(self.pkg_dir, pkg_hash)
  594. print('Creating {filename}...'.format(filename=path_to_hash))
  595. lines = []
  596. if self.used_url['digests']['md5'] and self.used_url['digests']['sha256']:
  597. hash_header = '# md5, sha256 from {url}\n'.format(
  598. url=self.metadata_url)
  599. lines.append(hash_header)
  600. hash_line = '{method} {digest} {filename}\n'.format(
  601. method='md5',
  602. digest=self.used_url['digests']['md5'],
  603. filename=self.filename)
  604. lines.append(hash_line)
  605. hash_line = '{method} {digest} {filename}\n'.format(
  606. method='sha256',
  607. digest=self.used_url['digests']['sha256'],
  608. filename=self.filename)
  609. lines.append(hash_line)
  610. if self.license_files:
  611. lines.append('# Locally computed sha256 checksums\n')
  612. for license_file in self.license_files:
  613. sha256 = hashlib.sha256()
  614. with open(license_file, 'rb') as lic_f:
  615. while True:
  616. data = lic_f.read(BUF_SIZE)
  617. if not data:
  618. break
  619. sha256.update(data)
  620. hash_line = '{method} {digest} {filename}\n'.format(
  621. method='sha256',
  622. digest=sha256.hexdigest(),
  623. filename=license_file.replace(self.tmp_extract, '')[1:])
  624. lines.append(hash_line)
  625. with open(path_to_hash, 'w') as hash_file:
  626. hash_file.writelines(lines)
  627. def create_config_in(self):
  628. """
  629. Creates the Config.in file of a package
  630. """
  631. path_to_config = os.path.join(self.pkg_dir, 'Config.in')
  632. print('Creating {file}...'.format(file=path_to_config))
  633. lines = []
  634. config_line = 'config BR2_PACKAGE_{name}\n'.format(
  635. name=self.mk_name)
  636. lines.append(config_line)
  637. bool_line = '\tbool "{name}"\n'.format(name=self.buildroot_name)
  638. lines.append(bool_line)
  639. if self.pkg_req:
  640. self.pkg_req.sort()
  641. for dep in self.pkg_req:
  642. dep_line = '\tselect BR2_PACKAGE_{req} # runtime\n'.format(
  643. req=dep.upper().replace('-', '_'))
  644. lines.append(dep_line)
  645. lines.append('\thelp\n')
  646. md_info = self.metadata['info']
  647. help_lines = textwrap.wrap(md_info['summary'], 62,
  648. initial_indent='\t ',
  649. subsequent_indent='\t ')
  650. # make sure a help text is terminated with a full stop
  651. if help_lines[-1][-1] != '.':
  652. help_lines[-1] += '.'
  653. home_page = md_info.get('home_page', None)
  654. if not home_page:
  655. project_urls = md_info.get('project_urls', None)
  656. if project_urls:
  657. home_page = project_urls.get('Homepage', None)
  658. if home_page:
  659. # \t + two spaces is 3 char long
  660. help_lines.append('')
  661. help_lines.append('\t ' + home_page)
  662. help_lines = [x + '\n' for x in help_lines]
  663. lines += help_lines
  664. with open(path_to_config, 'w') as config_file:
  665. config_file.writelines(lines)
  666. def main():
  667. # Building the parser
  668. parser = argparse.ArgumentParser(
  669. description="Creates buildroot packages from the metadata of "
  670. "an existing PyPI packages and include it "
  671. "in menuconfig")
  672. parser.add_argument("packages",
  673. help="list of packages to be created",
  674. nargs='+')
  675. parser.add_argument("-o", "--output",
  676. help="""
  677. Output directory for packages.
  678. Default is ./package
  679. """,
  680. default='./package')
  681. args = parser.parse_args()
  682. packages = list(set(args.packages))
  683. # tmp_path is where we'll extract the files later
  684. tmp_prefix = 'scanpypi-'
  685. pkg_folder = args.output
  686. tmp_path = tempfile.mkdtemp(prefix=tmp_prefix)
  687. try:
  688. for real_pkg_name in packages:
  689. package = BuildrootPackage(real_pkg_name, pkg_folder)
  690. print('buildroot package name for {}:'.format(package.real_name),
  691. package.buildroot_name)
  692. # First we download the package
  693. # Most of the info we need can only be found inside the package
  694. print('Package:', package.buildroot_name)
  695. print('Fetching package', package.real_name)
  696. try:
  697. package.fetch_package_info()
  698. except (six.moves.urllib.error.URLError, six.moves.urllib.error.HTTPError):
  699. continue
  700. try:
  701. package.download_package()
  702. except six.moves.urllib.error.HTTPError as error:
  703. print('Error: {code} {reason}'.format(code=error.code,
  704. reason=error.reason))
  705. print('Error downloading package :', package.buildroot_name)
  706. print()
  707. continue
  708. # extract the tarball
  709. try:
  710. package.extract_package(tmp_path)
  711. except (tarfile.ReadError, zipfile.BadZipfile):
  712. print('Error extracting package {}'.format(package.real_name))
  713. print()
  714. continue
  715. # Loading the package install info from the package
  716. package.load_pyproject()
  717. try:
  718. package.load_metadata()
  719. except ImportError as err:
  720. if 'buildutils' in str(err):
  721. print('This package needs buildutils')
  722. continue
  723. else:
  724. raise
  725. except (AttributeError, KeyError) as error:
  726. print('Error: Could not install package {pkg}: {error}'.format(
  727. pkg=package.real_name, error=error))
  728. continue
  729. # Package requirement are an argument of the setup function
  730. req_not_found = package.get_requirements(pkg_folder)
  731. req_not_found = req_not_found.difference(packages)
  732. packages += req_not_found
  733. if req_not_found:
  734. print('Added packages \'{pkgs}\' as dependencies of {pkg}'
  735. .format(pkgs=", ".join(req_not_found),
  736. pkg=package.buildroot_name))
  737. print('Checking if package {name} already exists...'.format(
  738. name=package.pkg_dir))
  739. try:
  740. os.makedirs(package.pkg_dir)
  741. except OSError as exception:
  742. if exception.errno != errno.EEXIST:
  743. print("ERROR: ", exception.message, file=sys.stderr)
  744. continue
  745. print('Error: Package {name} already exists'
  746. .format(name=package.pkg_dir))
  747. del_pkg = input(
  748. 'Do you want to delete existing package ? [y/N]')
  749. if del_pkg.lower() == 'y':
  750. shutil.rmtree(package.pkg_dir)
  751. os.makedirs(package.pkg_dir)
  752. else:
  753. continue
  754. package.create_package_mk()
  755. package.create_hash_file()
  756. package.create_config_in()
  757. print("NOTE: Remember to also make an update to the DEVELOPERS file")
  758. print(" and include an entry for the pkg in packages/Config.in")
  759. print()
  760. # printing an empty line for visual comfort
  761. finally:
  762. shutil.rmtree(tmp_path)
  763. if __name__ == "__main__":
  764. main()