source: anuga_core/source/anuga/utilities/system_tools.py @ 5079

Last change on this file since 5079 was 5072, checked in by ole, 17 years ago

Implemented function to obtain path for a python package and refactored two
unit tests to use it when reading in data files. This now works no matter
what the current working directory is.

File size: 6.9 KB
Line 
1"""Implementation of tools to do with system administration made as platform independent as possible.
2
3
4"""
5
6import sys
7import os
8
9def get_user_name():
10    """Get user name provide by operating system
11    """
12
13    if sys.platform == 'win32':
14        #user = os.getenv('USERPROFILE')
15        user = os.getenv('USERNAME')
16    else:
17        user = os.getenv('LOGNAME')
18
19
20    return user   
21
22def get_host_name():
23    """Get host name provide by operating system
24    """
25
26    if sys.platform == 'win32':
27        host = os.getenv('COMPUTERNAME')
28    else:
29        host = os.uname()[1]
30
31
32    return host   
33
34def get_revision_number():
35    """Get the version number of the SVN
36    NOTE: This requires that the command svn is on the system PATH
37    (simply aliasing svn to the binary will not work)
38    """
39
40    # Create dummy info
41    #info = 'Revision: Version info could not be obtained.'
42    #info += 'A command line version of svn must be availbable '
43    #info += 'on the system PATH, access to the subversion '
44    #info += 'repository is necessary and the output must '
45    #info += 'contain a line starting with "Revision:"'
46   
47
48    #FIXME (Ole): Change this so that svn info is attempted first.
49    # If that fails, try to read a stored file with that same info (this would be created by e.g. the release script). Failing that, throw an exception.
50
51    #FIXME (Ole): Move this and store_version_info to utilities
52
53
54    try:
55        from anuga.stored_version_info import version_info
56    except:
57        msg = 'No version info stored and command "svn" is not '
58        msg += 'recognised on the system PATH.\n\n'
59        msg += 'If ANUGA has been installed from a distribution e.g. as '
60        msg += 'obtained from SourceForge,\n'
61        msg += 'the version info should be '
62        msg += 'available in the automatically generated file '
63        msg += 'stored_version_info.py\n'
64        msg += 'in the anuga root directory.\n'
65        msg += 'If run from a Subversion sandpit, '
66        msg += 'ANUGA will try to obtain the version info '
67        msg += 'by using the command: "svn info".\n'
68        msg += 'In this case, make sure svn is accessible on the system path. '
69        msg += 'Simply aliasing svn to the binary will not work. '
70        msg += 'Good luck!'
71
72        # No file available - try using Subversion
73        try:
74            # The null stuff is so this section fails quitly.
75            # This could cause the svn info command to fail due to
76            # the redirection being bad on some platforms.
77            # If that occurs then change this code.
78            if sys.platform[0:3] == 'win':
79                fid = os.popen('svn info 2> null')
80            else:
81                fid = os.popen('svn info 2>/dev/null')
82       
83        except:
84            raise Exception(msg)
85        else:
86            #print 'Got version from svn'           
87            version_info = fid.read()
88           
89            if version_info == '':
90                raise Exception(msg)   
91    else:
92        pass
93        #print 'Got version from file'
94
95           
96    for line in version_info.split('\n'):
97        if line.startswith('Revision:'):
98            break
99
100    fields = line.split(':')
101    msg = 'Keyword "Revision" was not found anywhere in text: %s' %version_info
102    assert fields[0].startswith('Revision'), msg           
103
104    try:
105        revision_number = int(fields[1])
106    except:
107        msg = 'Revision number must be an integer. I got %s' %fields[1]
108        msg += 'Check that the command svn is on the system path' 
109        raise Exception(msg)               
110       
111    return revision_number
112
113
114def store_version_info(destination_path='.', verbose=False):
115    """Obtain current version from Subversion and store it.
116   
117    Title: store_version_info()
118
119    Author: Ole Nielsen (Ole.Nielsen@ga.gov.au)
120
121    CreationDate: January 2006
122
123    Description:
124        This function obtains current version from Subversion and stores it
125        is a Python file named 'stored_version_info.py' for use with
126        get_version_info()
127
128        If svn is not available on the system PATH, an Exception is thrown
129    """
130
131    # Note (Ole): This function should not be unit tested as it will only
132    # work when running out of the sandpit. End users downloading the
133    # ANUGA distribution would see a failure.
134    #
135    # FIXME: This function should really only be used by developers (
136    # (e.g. for creating new ANUGA releases), so maybe it should move
137    # to somewhere else.
138   
139    import config
140
141    try:
142        fid = os.popen('svn info')
143    except:
144        msg = 'Command "svn" is not recognised on the system PATH'
145        raise Exception(msg)
146    else:   
147        txt = fid.read()
148        fid.close()
149
150
151        # Determine absolute filename
152        if destination_path[-1] != os.sep:
153            destination_path += os.sep
154           
155        filename = destination_path + config.version_filename
156
157        fid = open(filename, 'w')
158
159        docstring = 'Stored version info.\n\n'
160        docstring += 'This file provides the version for distributions '
161        docstring += 'that are not accessing Subversion directly.\n'
162        docstring += 'The file is automatically generated and should not '
163        docstring += 'be modified manually.\n'
164        fid.write('"""%s"""\n\n' %docstring)
165       
166        fid.write('version_info = """\n%s"""' %txt)
167        fid.close()
168
169
170        if verbose is True:
171            print 'Version info stored to %s' %filename
172
173def safe_crc(string):
174    """64 bit safe crc computation.
175
176       See Guido's 64 bit fix at http://bugs.python.org/issue1202           
177    """
178
179    from zlib import crc32
180    import os
181
182    x = crc32(string)
183       
184    if os.name == 'posix' and os.uname()[4] == 'x86_64':
185        crcval = x - ((x & 0x80000000) << 1)
186    else:
187        crcval = x
188       
189    return crcval
190
191
192def compute_checksum(filename, max_length=2**20):
193    """Compute the CRC32 checksum for specified file
194
195    Optional parameter max_length sets the maximum number
196    of bytes used to limit time used with large files.
197    Default = 2**20 (1MB)
198    """
199
200    fid = open(filename, 'rb') # Use binary for portability
201    crcval = safe_crc(fid.read(max_length))
202    fid.close()
203
204    return crcval
205
206def get_pathname_from_package(package):
207    """Get pathname of given package (provided as string)
208
209    This is useful for reading files residing in the same directory as
210    a particular module. Typically, this is required in unit tests depending
211    on external files.
212
213    The given module must start from a directory on the pythonpath
214    and be importable using the import statement.
215
216    Example
217    path = get_pathname_from_package('anuga.utilities')
218
219    """
220
221    exec('import %s as x' %package)
222
223    path = x.__path__[0]
224   
225    return path
226
227    # Alternative approach that has been used at times
228    #try:
229    #    # When unit test is run from current dir
230    #    p1 = read_polygon('mainland_only.csv')
231    #except:
232    #    # When unit test is run from ANUGA root dir
233    #    from os.path import join, split
234    #    dir, tail = split(__file__)
235    #    path = join(dir, 'mainland_only.csv')
236    #    p1 = read_polygon(path)
237       
238           
239
240
Note: See TracBrowser for help on using the repository browser.