scanpypi 32 KB

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