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