blob: e0bdfba2556c68cdedbb274120d2eb1a52b981df [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001def release_dict():
2 """Return the output of lsb_release -ir as a dictionary"""
3 from subprocess import PIPE
4
5 try:
6 output, err = bb.process.run(['lsb_release', '-ir'], stderr=PIPE)
7 except bb.process.CmdError as exc:
8 return None
9
10 data = {}
11 for line in output.splitlines():
12 if line.startswith("-e"): line = line[3:]
13 try:
14 key, value = line.split(":\t", 1)
15 except ValueError:
16 continue
17 else:
18 data[key] = value
19 return data
20
21def release_dict_file():
22 """ Try to gather LSB release information manually when lsb_release tool is unavailable """
23 data = None
24 try:
25 if os.path.exists('/etc/lsb-release'):
26 data = {}
27 with open('/etc/lsb-release') as f:
28 for line in f:
29 key, value = line.split("=", 1)
30 data[key] = value.strip()
31 elif os.path.exists('/etc/redhat-release'):
32 data = {}
33 with open('/etc/redhat-release') as f:
34 distro = f.readline().strip()
35 import re
36 match = re.match(r'(.*) release (.*) \((.*)\)', distro)
37 if match:
38 data['DISTRIB_ID'] = match.group(1)
39 data['DISTRIB_RELEASE'] = match.group(2)
40 elif os.path.exists('/etc/os-release'):
41 data = {}
42 with open('/etc/os-release') as f:
43 for line in f:
44 if line.startswith('NAME='):
45 data['DISTRIB_ID'] = line[5:].rstrip().strip('"')
46 if line.startswith('VERSION_ID='):
47 data['DISTRIB_RELEASE'] = line[11:].rstrip().strip('"')
48 elif os.path.exists('/etc/SuSE-release'):
49 data = {}
50 data['DISTRIB_ID'] = 'SUSE LINUX'
51 with open('/etc/SuSE-release') as f:
52 for line in f:
53 if line.startswith('VERSION = '):
54 data['DISTRIB_RELEASE'] = line[10:].rstrip()
55 break
56
57 except IOError:
58 return None
59 return data
60
61def distro_identifier(adjust_hook=None):
62 """Return a distro identifier string based upon lsb_release -ri,
63 with optional adjustment via a hook"""
64
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050065 import re
66
Patrick Williamsc124f4f2015-09-15 14:41:29 -050067 lsb_data = release_dict()
68 if lsb_data:
69 distro_id, release = lsb_data['Distributor ID'], lsb_data['Release']
70 else:
71 lsb_data_file = release_dict_file()
72 if lsb_data_file:
73 distro_id, release = lsb_data_file['DISTRIB_ID'], lsb_data_file.get('DISTRIB_RELEASE', None)
74 else:
75 distro_id, release = None, None
76
77 if adjust_hook:
78 distro_id, release = adjust_hook(distro_id, release)
79 if not distro_id:
80 return "Unknown"
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050081 # Filter out any non-alphanumerics
82 distro_id = re.sub(r'\W', '', distro_id)
83
Patrick Williamsc124f4f2015-09-15 14:41:29 -050084 if release:
85 id_str = '{0}-{1}'.format(distro_id, release)
86 else:
87 id_str = distro_id
88 return id_str.replace(' ','-').replace('/','-')