~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: mbp at sourcefrog
  • Date: 2005-03-09 06:49:00 UTC
  • Revision ID: mbp@sourcefrog.net-20050309064900-74935ffb7350b24b
import more files from baz

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
# along with this program; if not, write to the Free Software
17
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
18
 
19
 
import os, types, re, time
20
 
from stat import S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE
 
19
import os, types, re, time, types
 
20
from stat import S_ISREG, S_ISDIR, ST_MODE, ST_SIZE
21
21
 
22
 
from errors import bailout, BzrError
23
 
from trace import mutter
 
22
from errors import bailout
24
23
 
25
24
def make_readonly(filename):
26
25
    """Make a filename read-only."""
52
51
        return 'file'
53
52
    elif S_ISDIR(mode):
54
53
        return 'directory'
55
 
    elif S_ISLNK(mode):
56
 
        return 'symlink'
57
54
    else:
58
 
        raise BzrError("can't handle file kind with mode %o of %r" % (mode, f)) 
 
55
        bailout("can't handle file kind of %r" % fp)
59
56
 
60
57
 
61
58
 
87
84
    ## XXX: Could alternatively read /proc/sys/kernel/random/uuid on
88
85
    ## Linux, but we need something portable for other systems;
89
86
    ## preferably an implementation in Python.
90
 
    try:
91
 
        return chomp(file('/proc/sys/kernel/random/uuid').readline())
92
 
    except IOError:
93
 
        return chomp(os.popen('uuidgen').readline())
94
 
 
 
87
    bailout('uuids not allowed!')
 
88
    return chomp(os.popen('uuidgen').readline())
95
89
 
96
90
def chomp(s):
97
91
    if s and (s[-1] == '\n'):
118
112
 
119
113
 
120
114
 
121
 
def fingerprint_file(f):
122
 
    import sha
123
 
    s = sha.new()
124
 
    b = f.read()
125
 
    s.update(b)
126
 
    size = len(b)
127
 
    return {'size': size,
128
 
            'sha1': s.hexdigest()}
129
 
 
130
 
 
131
 
 
132
115
def username():
133
116
    """Return email-style username.
134
117
 
150
133
        import pwd
151
134
        uid = os.getuid()
152
135
        w = pwd.getpwuid(uid)
153
 
        gecos = w.pw_gecos
154
 
        comma = gecos.find(',')
155
 
        if comma == -1:
156
 
            realname = gecos
157
 
        else:
158
 
            realname = gecos[:comma]
 
136
        realname, junk = w.pw_gecos.split(',', 1)
159
137
        return '%s <%s@%s>' % (realname, w.pw_name, socket.getfqdn())
160
138
    except ImportError:
161
139
        pass
164
142
    return '<%s@%s>' % (getpass.getuser(), socket.getfqdn())
165
143
 
166
144
 
167
 
_EMAIL_RE = re.compile(r'[\w+.-]+@[\w+.-]+')
168
145
def user_email():
169
146
    """Return just the email component of a username."""
170
147
    e = os.environ.get('BZREMAIL') or os.environ.get('EMAIL')
171
148
    if e:
172
 
        m = _EMAIL_RE.search(e)
 
149
        import re
 
150
        m = re.search(r'[\w+.-]+@[\w+.-]+', e)
173
151
        if not m:
174
152
            bailout('%r is not a reasonable email address' % e)
175
153
        return m.group(0)
184
162
def compare_files(a, b):
185
163
    """Returns true if equal in contents"""
186
164
    # TODO: don't read the whole thing in one go.
187
 
    BUFSIZE = 4096
188
 
    while True:
189
 
        ai = a.read(BUFSIZE)
190
 
        bi = b.read(BUFSIZE)
191
 
        if ai != bi:
192
 
            return False
193
 
        if ai == '':
194
 
            return True
195
 
 
196
 
 
197
 
 
198
 
def local_time_offset(t=None):
199
 
    """Return offset of local zone from GMT, either at present or at time t."""
200
 
    # python2.3 localtime() can't take None
201
 
    if t == None:
202
 
        t = time.time()
203
 
        
204
 
    if time.localtime(t).tm_isdst and time.daylight:
 
165
    result = a.read() == b.read()
 
166
    return result
 
167
 
 
168
 
 
169
 
 
170
def local_time_offset():
 
171
    if time.daylight:
205
172
        return -time.altzone
206
173
    else:
207
174
        return -time.timezone
210
177
def format_date(t, offset=0, timezone='original'):
211
178
    ## TODO: Perhaps a global option to use either universal or local time?
212
179
    ## Or perhaps just let people set $TZ?
 
180
    import time
 
181
    
213
182
    assert isinstance(t, float)
214
183
    
215
184
    if timezone == 'utc':
216
185
        tt = time.gmtime(t)
217
186
        offset = 0
218
187
    elif timezone == 'original':
219
 
        if offset == None:
220
 
            offset = 0
221
 
        tt = time.gmtime(t + offset)
222
 
    elif timezone == 'local':
 
188
        tt = time.gmtime(t - offset)
 
189
    else:
 
190
        assert timezone == 'local'
223
191
        tt = time.localtime(t)
224
 
        offset = local_time_offset(t)
225
 
    else:
226
 
        bailout("unsupported timezone format %r",
227
 
                ['options are "utc", "original", "local"'])
 
192
        offset = local_time_offset()
228
193
 
229
194
    return (time.strftime("%a %Y-%m-%d %H:%M:%S", tt)
230
195
            + ' %+03d%02d' % (offset / 3600, (offset / 60) % 60))
268
233
    BzrError: ("sorry, '..' not allowed in path", [])
269
234
    """
270
235
    assert isinstance(p, types.StringTypes)
271
 
    ps = [f for f in p.split('/') if (f != '.' and f != '')]
 
236
    ps = [f for f in p.split('/') if f != '.']
272
237
    for f in ps:
273
238
        if f == '..':
274
239
            bailout("sorry, %r not allowed in path" % f)
277
242
def joinpath(p):
278
243
    assert isinstance(p, list)
279
244
    for f in p:
280
 
        if (f == '..') or (f == None) or (f == ''):
 
245
        if (f == '..') or (f is None) or (f == ''):
281
246
            bailout("sorry, %r not allowed in path" % f)
282
247
    return '/'.join(p)
283
248