_sysinfo.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. """
  2. Utilities for getting information about Jupyter and the system it's running in.
  3. """
  4. # Copyright (c) Jupyter Development Team.
  5. # Distributed under the terms of the Modified BSD License.
  6. import os
  7. import platform
  8. import subprocess
  9. import sys
  10. import jupyter_server
  11. def pkg_commit_hash(pkg_path):
  12. """Get short form of commit hash given directory `pkg_path`
  13. We get the commit hash from git if it's a repo.
  14. If this fail, we return a not-found placeholder tuple
  15. Parameters
  16. ----------
  17. pkg_path : str
  18. directory containing package
  19. only used for getting commit from active repo
  20. Returns
  21. -------
  22. hash_from : str
  23. Where we got the hash from - description
  24. hash_str : str
  25. short form of hash
  26. """
  27. # maybe we are in a repository, check for a .git folder
  28. p = os.path
  29. cur_path = None
  30. par_path = pkg_path
  31. while cur_path != par_path:
  32. cur_path = par_path
  33. if p.exists(p.join(cur_path, ".git")):
  34. try:
  35. proc = subprocess.Popen(
  36. ["git", "rev-parse", "--short", "HEAD"], # noqa: S607
  37. stdout=subprocess.PIPE,
  38. stderr=subprocess.PIPE,
  39. cwd=pkg_path,
  40. )
  41. repo_commit, _ = proc.communicate()
  42. except OSError:
  43. repo_commit = None
  44. if repo_commit:
  45. return "repository", repo_commit.strip().decode("ascii")
  46. else:
  47. return "", ""
  48. par_path = p.dirname(par_path)
  49. return "", ""
  50. def pkg_info(pkg_path):
  51. """Return dict describing the context of this package
  52. Parameters
  53. ----------
  54. pkg_path : str
  55. path containing __init__.py for package
  56. Returns
  57. -------
  58. context : dict
  59. with named parameters of interest
  60. """
  61. src, hsh = pkg_commit_hash(pkg_path)
  62. return {
  63. "jupyter_server_version": jupyter_server.__version__,
  64. "jupyter_server_path": pkg_path,
  65. "commit_source": src,
  66. "commit_hash": hsh,
  67. "sys_version": sys.version,
  68. "sys_executable": sys.executable,
  69. "sys_platform": sys.platform,
  70. "platform": platform.platform(),
  71. "os_name": os.name,
  72. }
  73. def get_sys_info():
  74. """Return useful information about the system as a dict."""
  75. p = os.path
  76. path = p.realpath(p.dirname(p.abspath(p.join(jupyter_server.__file__))))
  77. return pkg_info(path)