blob: ddfe71b6b5e701d991ce692f204d882141d19627 [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
65 lsb_data = release_dict()
66 if lsb_data:
67 distro_id, release = lsb_data['Distributor ID'], lsb_data['Release']
68 else:
69 lsb_data_file = release_dict_file()
70 if lsb_data_file:
71 distro_id, release = lsb_data_file['DISTRIB_ID'], lsb_data_file.get('DISTRIB_RELEASE', None)
72 else:
73 distro_id, release = None, None
74
75 if adjust_hook:
76 distro_id, release = adjust_hook(distro_id, release)
77 if not distro_id:
78 return "Unknown"
79 if release:
80 id_str = '{0}-{1}'.format(distro_id, release)
81 else:
82 id_str = distro_id
83 return id_str.replace(' ','-').replace('/','-')