378a90b43c70977046e2cbd740ffc92cea34a850
[sdc/sdc-distribution-client.git] /
1 from __future__ import with_statement
2 import os
3 import re
4 import sys
5 import pytz
6 import subprocess
7
8 _systemconfig_tz = re.compile(r'^Time Zone: (.*)$(?m)')
9
10
11 def _tz_from_env(tzenv):
12     if tzenv[0] == ':':
13         tzenv = tzenv[1:]
14
15     # TZ specifies a file
16     if os.path.exists(tzenv):
17         with open(tzenv, 'rb') as tzfile:
18             return pytz.tzfile.build_tzinfo('local', tzfile)
19
20     # TZ specifies a zoneinfo zone.
21     try:
22         tz = pytz.timezone(tzenv)
23         # That worked, so we return this:
24         return tz
25     except pytz.UnknownTimeZoneError:
26         raise pytz.UnknownTimeZoneError(
27             "tzlocal() does not support non-zoneinfo timezones like %s. \n"
28             "Please use a timezone in the form of Continent/City")
29
30
31 def _get_localzone(_root='/'):
32     """Tries to find the local timezone configuration.
33     This method prefers finding the timezone name and passing that to pytz,
34     over passing in the localtime file, as in the later case the zoneinfo
35     name is unknown.
36     The parameter _root makes the function look for files like /etc/localtime
37     beneath the _root directory. This is primarily used by the tests.
38     In normal usage you call the function without parameters.
39     """
40
41     tzenv = os.environ.get('TZ')
42     if tzenv:
43         return _tz_from_env(tzenv)
44
45     # This is actually a pretty reliable way to test for the local time
46     # zone on operating systems like OS X.  On OS X especially this is the
47     # only one that actually works.
48     try:
49         link_dst = os.readlink('/etc/localtime')
50     except OSError:
51         pass
52     else:
53         pos = link_dst.find('/zoneinfo/')
54         if pos >= 0:
55             zone_name = link_dst[pos + 10:]
56             try:
57                 return pytz.timezone(zone_name)
58             except pytz.UnknownTimeZoneError:
59                 pass
60
61     # If we are on OS X now we are pretty sure that the rest of the
62     # code will fail and just fall through until it hits the reading
63     # of /etc/localtime and using it without name.  At this point we
64     # can invoke systemconfig which internally invokes ICU.  ICU itself
65     # does the same thing we do (readlink + compare file contents) but
66     # since it knows where the zone files are that should be a bit
67     # better than reimplementing the logic here.
68     if sys.platform == 'darwin':
69         c = subprocess.Popen(['systemsetup', '-gettimezone'],
70                              stdout=subprocess.PIPE)
71         sys_result = c.communicate()[0]
72         c.wait()
73         tz_match = _systemconfig_tz.search(sys_result)
74         if tz_match is not None:
75             zone_name = tz_match.group(1)
76             try:
77                 return pytz.timezone(zone_name)
78             except pytz.UnknownTimeZoneError:
79                 pass
80
81     # Now look for distribution specific configuration files
82     # that contain the timezone name.
83     tzpath = os.path.join(_root, 'etc/timezone')
84     if os.path.exists(tzpath):
85         with open(tzpath, 'rb') as tzfile:
86             data = tzfile.read()
87
88             # Issue #3 in tzlocal was that /etc/timezone was a zoneinfo file.
89             # That's a misconfiguration, but we need to handle it gracefully:
90             if data[:5] != 'TZif2':
91                 etctz = data.strip().decode()
92                 # Get rid of host definitions and comments:
93                 if ' ' in etctz:
94                     etctz, dummy = etctz.split(' ', 1)
95                 if '#' in etctz:
96                     etctz, dummy = etctz.split('#', 1)
97                 return pytz.timezone(etctz.replace(' ', '_'))
98
99     # CentOS has a ZONE setting in /etc/sysconfig/clock,
100     # OpenSUSE has a TIMEZONE setting in /etc/sysconfig/clock and
101     # Gentoo has a TIMEZONE setting in /etc/conf.d/clock
102     # We look through these files for a timezone:
103     zone_re = re.compile('\s*ZONE\s*=\s*\"')
104     timezone_re = re.compile('\s*TIMEZONE\s*=\s*\"')
105     end_re = re.compile('\"')
106
107     for filename in ('etc/sysconfig/clock', 'etc/conf.d/clock'):
108         tzpath = os.path.join(_root, filename)
109         if not os.path.exists(tzpath):
110             continue
111         with open(tzpath, 'rt') as tzfile:
112             data = tzfile.readlines()
113
114         for line in data:
115             # Look for the ZONE= setting.
116             match = zone_re.match(line)
117             if match is None:
118                 # No ZONE= setting. Look for the TIMEZONE= setting.
119                 match = timezone_re.match(line)
120             if match is not None:
121                 # Some setting existed
122                 line = line[match.end():]
123                 etctz = line[:end_re.search(line).start()]
124
125                 # We found a timezone
126                 return pytz.timezone(etctz.replace(' ', '_'))
127
128     # No explicit setting existed. Use localtime
129     for filename in ('etc/localtime', 'usr/local/etc/localtime'):
130         tzpath = os.path.join(_root, filename)
131
132         if not os.path.exists(tzpath):
133             continue
134
135         with open(tzpath, 'rb') as tzfile:
136             return pytz.tzfile.build_tzinfo('local', tzfile)
137
138     raise pytz.UnknownTimeZoneError('Can not find any timezone configuration')