check_python_dependencies.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. #!/usr/bin/env python
  2. #
  3. # SPDX-FileCopyrightText: 2018-2022 Espressif Systems (Shanghai) CO LTD
  4. # SPDX-License-Identifier: Apache-2.0
  5. import argparse
  6. import os
  7. import re
  8. import sys
  9. try:
  10. import pkg_resources
  11. except ImportError:
  12. print('pkg_resources cannot be imported. The most common cause is a missing pip or setuptools package. '
  13. 'If you\'ve installed a custom Python then these packages are provided separately and have to be installed as well. '
  14. 'Please refer to the Get Started section of the ESP-IDF Programming Guide for setting up the required packages.')
  15. sys.exit(1)
  16. try:
  17. from typing import Set
  18. except ImportError:
  19. # This is a script run during the early phase of setting up the environment. So try to avoid failure caused by
  20. # Python version incompatibility. The supported Python version is checked elsewhere.
  21. pass
  22. PYTHON_PACKAGE_RE = re.compile(r'[^<>=~]+')
  23. if __name__ == '__main__':
  24. parser = argparse.ArgumentParser(description='ESP-IDF Python package dependency checker')
  25. parser.add_argument('--requirements', '-r',
  26. help='Path to a requirements file (can be used multiple times)',
  27. action='append', default=[])
  28. parser.add_argument('--constraints', '-c', default=[],
  29. help='Path to a constraints file (can be used multiple times)',
  30. action='append')
  31. args = parser.parse_args()
  32. required_set = set()
  33. for req_path in args.requirements:
  34. with open(req_path) as f:
  35. required_set |= set(i for i in map(str.strip, f.readlines()) if len(i) > 0 and not i.startswith('#'))
  36. constr_dict = {} # for example package_name -> package_name==1.0
  37. for const_path in args.constraints:
  38. with open(const_path) as f:
  39. for con in [i for i in map(str.strip, f.readlines()) if len(i) > 0 and not i.startswith('#')]:
  40. if con.startswith('file://'):
  41. con = os.path.basename(con)
  42. elif con.startswith('--only-binary'):
  43. continue
  44. elif con.startswith('-e') and '#egg=' in con: # version control URLs, take the egg= part at the end only
  45. con_m = re.search(r'#egg=([^\s]+)', con)
  46. if not con_m:
  47. print('Malformed input. Cannot find name in {}'.format(con))
  48. sys.exit(1)
  49. con = con_m[1]
  50. name_m = PYTHON_PACKAGE_RE.search(con)
  51. if not name_m:
  52. print('Malformed input. Cannot find name in {}'.format(con))
  53. sys.exit(1)
  54. constr_dict[name_m[0]] = con
  55. not_satisfied = [] # in string form which will be printed
  56. # already_checked set is used in order to avoid circular checks which would cause looping.
  57. already_checked = set() # type: Set[pkg_resources.Requirement]
  58. # required_set contains package names in string form without version constraints. If the package has a constraint
  59. # specification (package name + version requirement) then use that instead. new_req_list is used to store
  60. # requirements to be checked on each level of breath-first-search of the package dependency tree. The initial
  61. # version is the direct dependencies deduced from the requirements arguments of the script.
  62. new_req_list = [pkg_resources.Requirement.parse(constr_dict.get(i, i)) for i in required_set]
  63. while new_req_list:
  64. req_list = new_req_list
  65. new_req_list = []
  66. already_checked.update(req_list)
  67. for requirement in req_list: # check one level of the dependency tree
  68. try:
  69. dependency_requirements = set(pkg_resources.get_distribution(requirement).requires())
  70. # dependency_requirements are the direct dependencies of "requirement". They belong to the next level
  71. # of the dependency tree. They will be checked only if they haven't been already. Note that the
  72. # version is taken into account as well because packages can have different requirements for a given
  73. # Python package. The dependencies need to be checked for all of them because they can be different.
  74. new_req_list.extend(dependency_requirements - already_checked)
  75. except pkg_resources.ResolutionError as e:
  76. not_satisfied.append(' - '.join([str(requirement), str(e)]))
  77. except IndexError:
  78. # If the requirement is not installed because of a marker (requirement.marker), for example different
  79. # operating system or python version, then pkg_resources.get_distribution() will fail with IndexError.
  80. # We could avoid this by checking packaging.markers.Marker(requirement.marker).evaluate() but it would
  81. # add dependency on packaging.
  82. pass
  83. if len(not_satisfied) > 0:
  84. print('The following Python requirements are not satisfied:')
  85. print(os.linesep.join(not_satisfied))
  86. if 'IDF_PYTHON_ENV_PATH' in os.environ:
  87. # We are running inside a private virtual environment under IDF_TOOLS_PATH,
  88. # ask the user to run install.bat again.
  89. install_script = 'install.bat' if sys.platform == 'win32' else 'install.sh'
  90. print('To install the missing packages, please run "{}"'.format(install_script))
  91. else:
  92. print('Please follow the instructions found in the "Set up the tools" section of '
  93. 'ESP-IDF Getting Started Guide.')
  94. print('Diagnostic information:')
  95. idf_python_env_path = os.environ.get('IDF_PYTHON_ENV_PATH')
  96. print(' IDF_PYTHON_ENV_PATH: {}'.format(idf_python_env_path or '(not set)'))
  97. print(' Python interpreter used: {}'.format(sys.executable))
  98. if not idf_python_env_path or idf_python_env_path not in sys.executable:
  99. print(' Warning: python interpreter not running from IDF_PYTHON_ENV_PATH')
  100. print(' PATH: {}'.format(os.getenv('PATH')))
  101. sys.exit(1)
  102. print('Python requirements are satisfied.')