/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Martin Pool
  • Date: 2005-09-13 08:19:01 UTC
  • Revision ID: mbp@sourcefrog.net-20050913081901-9b8d449d97e9f23d
- split sha_strings into osutils

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Bazaar-NG -- distributed version control
 
2
 
 
3
# Copyright (C) 2005 by Canonical Ltd
 
4
 
 
5
# This program is free software; you can redistribute it and/or modify
 
6
# it under the terms of the GNU General Public License as published by
 
7
# the Free Software Foundation; either version 2 of the License, or
 
8
# (at your option) any later version.
 
9
 
 
10
# This program is distributed in the hope that it will be useful,
 
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
13
# GNU General Public License for more details.
 
14
 
 
15
# You should have received a copy of the GNU General Public License
 
16
# along with this program; if not, write to the Free Software
 
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
18
 
 
19
import os, types, re, time, errno, sys
 
20
from cStringIO import StringIO
 
21
 
 
22
from stat import S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE
 
23
 
 
24
from bzrlib.errors import BzrError
 
25
from bzrlib.trace import mutter
 
26
import bzrlib
 
27
 
 
28
def make_readonly(filename):
 
29
    """Make a filename read-only."""
 
30
    # TODO: probably needs to be fixed for windows
 
31
    mod = os.stat(filename).st_mode
 
32
    mod = mod & 0777555
 
33
    os.chmod(filename, mod)
 
34
 
 
35
 
 
36
def make_writable(filename):
 
37
    mod = os.stat(filename).st_mode
 
38
    mod = mod | 0200
 
39
    os.chmod(filename, mod)
 
40
 
 
41
 
 
42
_QUOTE_RE = None
 
43
 
 
44
 
 
45
def quotefn(f):
 
46
    """Return a quoted filename filename
 
47
 
 
48
    This previously used backslash quoting, but that works poorly on
 
49
    Windows."""
 
50
    # TODO: I'm not really sure this is the best format either.x
 
51
    global _QUOTE_RE
 
52
    if _QUOTE_RE == None:
 
53
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/_~-])')
 
54
        
 
55
    if _QUOTE_RE.search(f):
 
56
        return '"' + f + '"'
 
57
    else:
 
58
        return f
 
59
 
 
60
 
 
61
def file_kind(f):
 
62
    mode = os.lstat(f)[ST_MODE]
 
63
    if S_ISREG(mode):
 
64
        return 'file'
 
65
    elif S_ISDIR(mode):
 
66
        return 'directory'
 
67
    elif S_ISLNK(mode):
 
68
        return 'symlink'
 
69
    else:
 
70
        raise BzrError("can't handle file kind with mode %o of %r" % (mode, f))
 
71
 
 
72
 
 
73
def kind_marker(kind):
 
74
    if kind == 'file':
 
75
        return ''
 
76
    elif kind == 'directory':
 
77
        return '/'
 
78
    elif kind == 'symlink':
 
79
        return '@'
 
80
    else:
 
81
        raise BzrError('invalid file kind %r' % kind)
 
82
 
 
83
 
 
84
 
 
85
def backup_file(fn):
 
86
    """Copy a file to a backup.
 
87
 
 
88
    Backups are named in GNU-style, with a ~ suffix.
 
89
 
 
90
    If the file is already a backup, it's not copied.
 
91
    """
 
92
    import os
 
93
    if fn[-1] == '~':
 
94
        return
 
95
    bfn = fn + '~'
 
96
 
 
97
    inf = file(fn, 'rb')
 
98
    try:
 
99
        content = inf.read()
 
100
    finally:
 
101
        inf.close()
 
102
    
 
103
    outf = file(bfn, 'wb')
 
104
    try:
 
105
        outf.write(content)
 
106
    finally:
 
107
        outf.close()
 
108
 
 
109
def rename(path_from, path_to):
 
110
    """Basically the same as os.rename() just special for win32"""
 
111
    if sys.platform == 'win32':
 
112
        try:
 
113
            os.remove(path_to)
 
114
        except OSError, e:
 
115
            if e.errno != e.ENOENT:
 
116
                raise
 
117
    os.rename(path_from, path_to)
 
118
 
 
119
 
 
120
 
 
121
 
 
122
 
 
123
def isdir(f):
 
124
    """True if f is an accessible directory."""
 
125
    try:
 
126
        return S_ISDIR(os.lstat(f)[ST_MODE])
 
127
    except OSError:
 
128
        return False
 
129
 
 
130
 
 
131
 
 
132
def isfile(f):
 
133
    """True if f is a regular file."""
 
134
    try:
 
135
        return S_ISREG(os.lstat(f)[ST_MODE])
 
136
    except OSError:
 
137
        return False
 
138
 
 
139
 
 
140
def is_inside(dir, fname):
 
141
    """True if fname is inside dir.
 
142
    
 
143
    The parameters should typically be passed to os.path.normpath first, so
 
144
    that . and .. and repeated slashes are eliminated, and the separators
 
145
    are canonical for the platform.
 
146
    
 
147
    The empty string as a dir name is taken as top-of-tree and matches 
 
148
    everything.
 
149
    
 
150
    >>> is_inside('src', 'src/foo.c')
 
151
    True
 
152
    >>> is_inside('src', 'srccontrol')
 
153
    False
 
154
    >>> is_inside('src', 'src/a/a/a/foo.c')
 
155
    True
 
156
    >>> is_inside('foo.c', 'foo.c')
 
157
    True
 
158
    >>> is_inside('foo.c', '')
 
159
    False
 
160
    >>> is_inside('', 'foo.c')
 
161
    True
 
162
    """
 
163
    # XXX: Most callers of this can actually do something smarter by 
 
164
    # looking at the inventory
 
165
    if dir == fname:
 
166
        return True
 
167
    
 
168
    if dir == '':
 
169
        return True
 
170
    
 
171
    if dir[-1] != os.sep:
 
172
        dir += os.sep
 
173
    
 
174
    return fname.startswith(dir)
 
175
 
 
176
 
 
177
def is_inside_any(dir_list, fname):
 
178
    """True if fname is inside any of given dirs."""
 
179
    for dirname in dir_list:
 
180
        if is_inside(dirname, fname):
 
181
            return True
 
182
    else:
 
183
        return False
 
184
 
 
185
 
 
186
def pumpfile(fromfile, tofile):
 
187
    """Copy contents of one file to another."""
 
188
    tofile.write(fromfile.read())
 
189
 
 
190
 
 
191
def uuid():
 
192
    """Return a new UUID"""
 
193
    try:
 
194
        return file('/proc/sys/kernel/random/uuid').readline().rstrip('\n')
 
195
    except IOError:
 
196
        return chomp(os.popen('uuidgen').readline())
 
197
 
 
198
 
 
199
def sha_file(f):
 
200
    import sha
 
201
    if hasattr(f, 'tell'):
 
202
        assert f.tell() == 0
 
203
    s = sha.new()
 
204
    BUFSIZE = 128<<10
 
205
    while True:
 
206
        b = f.read(BUFSIZE)
 
207
        if not b:
 
208
            break
 
209
        s.update(b)
 
210
    return s.hexdigest()
 
211
 
 
212
 
 
213
 
 
214
def sha_strings(strings):
 
215
    """Return the sha-1 of concatenation of strings"""
 
216
    s = sha.new()
 
217
    map(s.update, strings)
 
218
    return s.hexdigest()
 
219
 
 
220
 
 
221
def sha_string(f):
 
222
    import sha
 
223
    s = sha.new()
 
224
    s.update(f)
 
225
    return s.hexdigest()
 
226
 
 
227
 
 
228
 
 
229
def fingerprint_file(f):
 
230
    import sha
 
231
    s = sha.new()
 
232
    b = f.read()
 
233
    s.update(b)
 
234
    size = len(b)
 
235
    return {'size': size,
 
236
            'sha1': s.hexdigest()}
 
237
 
 
238
 
 
239
def config_dir():
 
240
    """Return per-user configuration directory.
 
241
 
 
242
    By default this is ~/.bzr.conf/
 
243
    
 
244
    TODO: Global option --config-dir to override this.
 
245
    """
 
246
    return os.path.expanduser("~/.bzr.conf")
 
247
 
 
248
 
 
249
def _auto_user_id():
 
250
    """Calculate automatic user identification.
 
251
 
 
252
    Returns (realname, email).
 
253
 
 
254
    Only used when none is set in the environment or the id file.
 
255
 
 
256
    This previously used the FQDN as the default domain, but that can
 
257
    be very slow on machines where DNS is broken.  So now we simply
 
258
    use the hostname.
 
259
    """
 
260
    import socket
 
261
 
 
262
    # XXX: Any good way to get real user name on win32?
 
263
 
 
264
    try:
 
265
        import pwd
 
266
        uid = os.getuid()
 
267
        w = pwd.getpwuid(uid)
 
268
        gecos = w.pw_gecos.decode(bzrlib.user_encoding)
 
269
        username = w.pw_name.decode(bzrlib.user_encoding)
 
270
        comma = gecos.find(',')
 
271
        if comma == -1:
 
272
            realname = gecos
 
273
        else:
 
274
            realname = gecos[:comma]
 
275
        if not realname:
 
276
            realname = username
 
277
 
 
278
    except ImportError:
 
279
        import getpass
 
280
        realname = username = getpass.getuser().decode(bzrlib.user_encoding)
 
281
 
 
282
    return realname, (username + '@' + socket.gethostname())
 
283
 
 
284
 
 
285
def _get_user_id(branch):
 
286
    """Return the full user id from a file or environment variable.
 
287
 
 
288
    e.g. "John Hacker <jhacker@foo.org>"
 
289
 
 
290
    branch
 
291
        A branch to use for a per-branch configuration, or None.
 
292
 
 
293
    The following are searched in order:
 
294
 
 
295
    1. $BZREMAIL
 
296
    2. .bzr/email for this branch.
 
297
    3. ~/.bzr.conf/email
 
298
    4. $EMAIL
 
299
    """
 
300
    v = os.environ.get('BZREMAIL')
 
301
    if v:
 
302
        return v.decode(bzrlib.user_encoding)
 
303
 
 
304
    if branch:
 
305
        try:
 
306
            return (branch.controlfile("email", "r") 
 
307
                    .read()
 
308
                    .decode(bzrlib.user_encoding)
 
309
                    .rstrip("\r\n"))
 
310
        except IOError, e:
 
311
            if e.errno != errno.ENOENT:
 
312
                raise
 
313
        except BzrError, e:
 
314
            pass
 
315
    
 
316
    try:
 
317
        return (open(os.path.join(config_dir(), "email"))
 
318
                .read()
 
319
                .decode(bzrlib.user_encoding)
 
320
                .rstrip("\r\n"))
 
321
    except IOError, e:
 
322
        if e.errno != errno.ENOENT:
 
323
            raise e
 
324
 
 
325
    v = os.environ.get('EMAIL')
 
326
    if v:
 
327
        return v.decode(bzrlib.user_encoding)
 
328
    else:    
 
329
        return None
 
330
 
 
331
 
 
332
def username(branch):
 
333
    """Return email-style username.
 
334
 
 
335
    Something similar to 'Martin Pool <mbp@sourcefrog.net>'
 
336
 
 
337
    TODO: Check it's reasonably well-formed.
 
338
    """
 
339
    v = _get_user_id(branch)
 
340
    if v:
 
341
        return v
 
342
    
 
343
    name, email = _auto_user_id()
 
344
    if name:
 
345
        return '%s <%s>' % (name, email)
 
346
    else:
 
347
        return email
 
348
 
 
349
 
 
350
def user_email(branch):
 
351
    """Return just the email component of a username."""
 
352
    e = _get_user_id(branch)
 
353
    if e:
 
354
        m = re.search(r'[\w+.-]+@[\w+.-]+', e)
 
355
        if not m:
 
356
            raise BzrError("%r doesn't seem to contain a reasonable email address" % e)
 
357
        return m.group(0)
 
358
 
 
359
    return _auto_user_id()[1]
 
360
    
 
361
 
 
362
 
 
363
def compare_files(a, b):
 
364
    """Returns true if equal in contents"""
 
365
    BUFSIZE = 4096
 
366
    while True:
 
367
        ai = a.read(BUFSIZE)
 
368
        bi = b.read(BUFSIZE)
 
369
        if ai != bi:
 
370
            return False
 
371
        if ai == '':
 
372
            return True
 
373
 
 
374
 
 
375
 
 
376
def local_time_offset(t=None):
 
377
    """Return offset of local zone from GMT, either at present or at time t."""
 
378
    # python2.3 localtime() can't take None
 
379
    if t == None:
 
380
        t = time.time()
 
381
        
 
382
    if time.localtime(t).tm_isdst and time.daylight:
 
383
        return -time.altzone
 
384
    else:
 
385
        return -time.timezone
 
386
 
 
387
    
 
388
def format_date(t, offset=0, timezone='original'):
 
389
    ## TODO: Perhaps a global option to use either universal or local time?
 
390
    ## Or perhaps just let people set $TZ?
 
391
    assert isinstance(t, float)
 
392
    
 
393
    if timezone == 'utc':
 
394
        tt = time.gmtime(t)
 
395
        offset = 0
 
396
    elif timezone == 'original':
 
397
        if offset == None:
 
398
            offset = 0
 
399
        tt = time.gmtime(t + offset)
 
400
    elif timezone == 'local':
 
401
        tt = time.localtime(t)
 
402
        offset = local_time_offset(t)
 
403
    else:
 
404
        raise BzrError("unsupported timezone format %r" % timezone,
 
405
                       ['options are "utc", "original", "local"'])
 
406
 
 
407
    return (time.strftime("%a %Y-%m-%d %H:%M:%S", tt)
 
408
            + ' %+03d%02d' % (offset / 3600, (offset / 60) % 60))
 
409
 
 
410
 
 
411
def compact_date(when):
 
412
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
 
413
    
 
414
 
 
415
 
 
416
def filesize(f):
 
417
    """Return size of given open file."""
 
418
    return os.fstat(f.fileno())[ST_SIZE]
 
419
 
 
420
 
 
421
if hasattr(os, 'urandom'): # python 2.4 and later
 
422
    rand_bytes = os.urandom
 
423
elif sys.platform == 'linux2':
 
424
    rand_bytes = file('/dev/urandom', 'rb').read
 
425
else:
 
426
    # not well seeded, but better than nothing
 
427
    def rand_bytes(n):
 
428
        import random
 
429
        s = ''
 
430
        while n:
 
431
            s += chr(random.randint(0, 255))
 
432
            n -= 1
 
433
        return s
 
434
 
 
435
 
 
436
## TODO: We could later have path objects that remember their list
 
437
## decomposition (might be too tricksy though.)
 
438
 
 
439
def splitpath(p):
 
440
    """Turn string into list of parts.
 
441
 
 
442
    >>> splitpath('a')
 
443
    ['a']
 
444
    >>> splitpath('a/b')
 
445
    ['a', 'b']
 
446
    >>> splitpath('a/./b')
 
447
    ['a', 'b']
 
448
    >>> splitpath('a/.b')
 
449
    ['a', '.b']
 
450
    >>> splitpath('a/../b')
 
451
    Traceback (most recent call last):
 
452
    ...
 
453
    BzrError: sorry, '..' not allowed in path
 
454
    """
 
455
    assert isinstance(p, types.StringTypes)
 
456
 
 
457
    # split on either delimiter because people might use either on
 
458
    # Windows
 
459
    ps = re.split(r'[\\/]', p)
 
460
 
 
461
    rps = []
 
462
    for f in ps:
 
463
        if f == '..':
 
464
            raise BzrError("sorry, %r not allowed in path" % f)
 
465
        elif (f == '.') or (f == ''):
 
466
            pass
 
467
        else:
 
468
            rps.append(f)
 
469
    return rps
 
470
 
 
471
def joinpath(p):
 
472
    assert isinstance(p, list)
 
473
    for f in p:
 
474
        if (f == '..') or (f == None) or (f == ''):
 
475
            raise BzrError("sorry, %r not allowed in path" % f)
 
476
    return os.path.join(*p)
 
477
 
 
478
 
 
479
def appendpath(p1, p2):
 
480
    if p1 == '':
 
481
        return p2
 
482
    else:
 
483
        return os.path.join(p1, p2)
 
484
    
 
485
 
 
486
def extern_command(cmd, ignore_errors = False):
 
487
    mutter('external command: %s' % `cmd`)
 
488
    if os.system(cmd):
 
489
        if not ignore_errors:
 
490
            raise BzrError('command failed')
 
491
 
 
492
 
 
493
def _read_config_value(name):
 
494
    """Read a config value from the file ~/.bzr.conf/<name>
 
495
    Return None if the file does not exist"""
 
496
    try:
 
497
        f = file(os.path.join(config_dir(), name), "r")
 
498
        return f.read().decode(bzrlib.user_encoding).rstrip("\r\n")
 
499
    except IOError, e:
 
500
        if e.errno == errno.ENOENT:
 
501
            return None
 
502
        raise
 
503
 
 
504
 
 
505
 
 
506
def split_lines(s):
 
507
    """Split s into lines, but without removing the newline characters."""
 
508
    return StringIO(s).readlines()
 
509