forked from fthaler/environment
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgetenv
executable file
·87 lines (69 loc) · 2.8 KB
/
getenv
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/env python3
DEFAULT_SYSTEM_NAME = "default"
def get_current_dir() -> str:
import os
return os.path.dirname(os.path.realpath(__file__))
def get_supported_systems() -> [str]:
"""Return a list of systems where support is availabl
Scan the available env. files and filter the names with the pattern env.SYSTEMNAME.(compiler).(whatever).postfix
"""
import os
import re
pattern = re.compile(r'\Aenv\.(?P<name>[\w\-._]+)\.((cray|gnu|gcc|pgi|clang)\.((\w-_)+\.)*)\w+$')
ls = os.listdir(get_current_dir())
filtered = set()
for f in ls:
m = pattern.match(f)
if m:
filtered.add(m.group('name'))
return list(filtered)
def match_system(hostname: str) -> str:
""""Match a hostname with the supported system.
Fit the longest prefix with the supported system.
A host with the name keschln-0001 should fit to keschln-0001 if available, otherwise it should fit to kesch.
"""
import platform
hostname = platform.node()
systems = get_supported_systems()
bestfit = ''
for s in systems:
if hostname.startswith(s):
if len(s) > len(bestfit):
bestfit = s
if bestfit == '':
return DEFAULT_SYSTEM_NAME
return bestfit
def find_environment(system_name: str, environment: str) -> str:
"""Find the system with the associated environment.
If multiple environments are available, select the one with the least specifiers."""
import os
files = os.listdir(get_current_dir())
if system_name == DEFAULT_SYSTEM_NAME:
environment = ''
prefix = "env.{system}".format(system=system_name)
if environment != '':
prefix = "{prefix}.{environment}".format(prefix=prefix, environment=environment)
filtered = [x for x in files if x.startswith(prefix)]
if len(filtered) == 0:
raise ValueError("Environment with the prefix {} not found!".format(prefix))
filtered.sort(key=len)
return "{cd}/{file}".format(cd=get_current_dir(), file=filtered[0])
if __name__ == "__main__":
import platform
import argparse
hostname = platform.node()
system = match_system(hostname)
parser = argparse.ArgumentParser(description="Get system environment")
parser.add_argument("-l", "--list", action="store_true",
help="List supported systems.")
parser.add_argument("-e", "--environment", type=str, default="gnu",
help="Environment (i.e. gnu, gnu.4.9.3, cray, etc...)")
args = parser.parse_args()
if args.list:
print("Hostname: {}".format(hostname))
print("Supported Systems:")
for x in get_supported_systems():
print("- {}".format(x))
print("Matched with: {}".format(system))
exit(0)
print(find_environment(system, args.environment))