_sysinfo.py 2.5 KB

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