~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Martin Pool
  • Date: 2005-05-09 03:03:55 UTC
  • Revision ID: mbp@sourcefrog.net-20050509030355-ad6ab558d1362959
- Don't give an error if the trace file can't be opened

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
 
19
import os, types, re, time, errno
20
20
from stat import S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE
21
21
 
22
22
from errors import bailout, BzrError
23
23
from trace import mutter
 
24
import bzrlib
24
25
 
25
26
def make_readonly(filename):
26
27
    """Make a filename read-only."""
83
84
 
84
85
def uuid():
85
86
    """Return a new UUID"""
86
 
    
87
 
    ## XXX: Could alternatively read /proc/sys/kernel/random/uuid on
88
 
    ## Linux, but we need something portable for other systems;
89
 
    ## preferably an implementation in Python.
90
87
    try:
91
 
        return chomp(file('/proc/sys/kernel/random/uuid').readline())
 
88
        return file('/proc/sys/kernel/random/uuid').readline().rstrip('\n')
92
89
    except IOError:
93
90
        return chomp(os.popen('uuidgen').readline())
94
91
 
95
92
 
96
 
def chomp(s):
97
 
    if s and (s[-1] == '\n'):
98
 
        return s[:-1]
99
 
    else:
100
 
        return s
101
 
 
102
 
 
103
93
def sha_file(f):
104
94
    import sha
105
 
    ## TODO: Maybe read in chunks to handle big files
106
95
    if hasattr(f, 'tell'):
107
96
        assert f.tell() == 0
108
97
    s = sha.new()
109
 
    s.update(f.read())
 
98
    BUFSIZE = 128<<10
 
99
    while True:
 
100
        b = f.read(BUFSIZE)
 
101
        if not b:
 
102
            break
 
103
        s.update(b)
110
104
    return s.hexdigest()
111
105
 
112
106
 
128
122
            'sha1': s.hexdigest()}
129
123
 
130
124
 
131
 
 
132
 
def username():
133
 
    """Return email-style username.
134
 
 
135
 
    Something similar to 'Martin Pool <mbp@sourcefrog.net>'
136
 
 
137
 
    :todo: Check it's reasonably well-formed.
138
 
 
139
 
    :todo: Allow taking it from a dotfile to help people on windows
140
 
           who can't easily set variables.
141
 
 
142
 
    :todo: Cope without pwd module, which is only on unix. 
143
 
    """
144
 
    e = os.environ.get('BZREMAIL') or os.environ.get('EMAIL')
145
 
    if e: return e
146
 
 
 
125
def config_dir():
 
126
    """Return per-user configuration directory.
 
127
 
 
128
    By default this is ~/.bzr.conf/
 
129
    
 
130
    TODO: Global option --config-dir to override this.
 
131
    """
 
132
    return os.path.expanduser("~/.bzr.conf")
 
133
 
 
134
 
 
135
def _auto_user_id():
 
136
    """Calculate automatic user identification.
 
137
 
 
138
    Returns (realname, email).
 
139
 
 
140
    Only used when none is set in the environment or the id file.
 
141
 
 
142
    This previously used the FQDN as the default domain, but that can
 
143
    be very slow on machines where DNS is broken.  So now we simply
 
144
    use the hostname.
 
145
    """
147
146
    import socket
148
 
    
 
147
 
 
148
    # XXX: Any good way to get real user name on win32?
 
149
 
149
150
    try:
150
151
        import pwd
151
152
        uid = os.getuid()
152
153
        w = pwd.getpwuid(uid)
153
 
        gecos = w.pw_gecos
 
154
        gecos = w.pw_gecos.decode(bzrlib.user_encoding)
 
155
        username = w.pw_name.decode(bzrlib.user_encoding)
154
156
        comma = gecos.find(',')
155
157
        if comma == -1:
156
158
            realname = gecos
157
159
        else:
158
160
            realname = gecos[:comma]
159
 
        return '%s <%s@%s>' % (realname, w.pw_name, socket.getfqdn())
 
161
        if not realname:
 
162
            realname = username
 
163
 
160
164
    except ImportError:
161
 
        pass
162
 
 
163
 
    import getpass, socket
164
 
    return '<%s@%s>' % (getpass.getuser(), socket.getfqdn())
 
165
        import getpass
 
166
        realname = username = getpass.getuser().decode(bzrlib.user_encoding)
 
167
 
 
168
    return realname, (username + '@' + socket.gethostname())
 
169
 
 
170
 
 
171
def _get_user_id():
 
172
    """Return the full user id from a file or environment variable.
 
173
 
 
174
    TODO: Allow taking this from a file in the branch directory too
 
175
    for per-branch ids."""
 
176
    v = os.environ.get('BZREMAIL')
 
177
    if v:
 
178
        return v.decode(bzrlib.user_encoding)
 
179
    
 
180
    try:
 
181
        return (open(os.path.join(config_dir(), "email"))
 
182
                .read()
 
183
                .decode(bzrlib.user_encoding)
 
184
                .rstrip("\r\n"))
 
185
    except IOError, e:
 
186
        if e.errno != errno.ENOENT:
 
187
            raise e
 
188
 
 
189
    v = os.environ.get('EMAIL')
 
190
    if v:
 
191
        return v.decode(bzrlib.user_encoding)
 
192
    else:    
 
193
        return None
 
194
 
 
195
 
 
196
def username():
 
197
    """Return email-style username.
 
198
 
 
199
    Something similar to 'Martin Pool <mbp@sourcefrog.net>'
 
200
 
 
201
    TODO: Check it's reasonably well-formed.
 
202
    """
 
203
    v = _get_user_id()
 
204
    if v:
 
205
        return v
 
206
    
 
207
    name, email = _auto_user_id()
 
208
    if name:
 
209
        return '%s <%s>' % (name, email)
 
210
    else:
 
211
        return email
165
212
 
166
213
 
167
214
_EMAIL_RE = re.compile(r'[\w+.-]+@[\w+.-]+')
168
215
def user_email():
169
216
    """Return just the email component of a username."""
170
 
    e = os.environ.get('BZREMAIL') or os.environ.get('EMAIL')
 
217
    e = _get_user_id()
171
218
    if e:
172
219
        m = _EMAIL_RE.search(e)
173
220
        if not m:
174
 
            bailout('%r is not a reasonable email address' % e)
 
221
            bailout("%r doesn't seem to contain a reasonable email address" % e)
175
222
        return m.group(0)
176
223
 
177
 
 
178
 
    import getpass, socket
179
 
    return '%s@%s' % (getpass.getuser(), socket.getfqdn())
180
 
 
 
224
    return _auto_user_id()[1]
181
225
    
182
226
 
183
227
 
184
228
def compare_files(a, b):
185
229
    """Returns true if equal in contents"""
186
 
    # TODO: don't read the whole thing in one go.
187
230
    BUFSIZE = 4096
188
231
    while True:
189
232
        ai = a.read(BUFSIZE)
268
311
    BzrError: ("sorry, '..' not allowed in path", [])
269
312
    """
270
313
    assert isinstance(p, types.StringTypes)
271
 
    ps = [f for f in p.split('/') if (f != '.' and f != '')]
 
314
 
 
315
    # split on either delimiter because people might use either on
 
316
    # Windows
 
317
    ps = re.split(r'[\\/]', p)
 
318
 
 
319
    rps = []
272
320
    for f in ps:
273
321
        if f == '..':
274
322
            bailout("sorry, %r not allowed in path" % f)
275
 
    return ps
 
323
        elif (f == '.') or (f == ''):
 
324
            pass
 
325
        else:
 
326
            rps.append(f)
 
327
    return rps
276
328
 
277
329
def joinpath(p):
278
330
    assert isinstance(p, list)
279
331
    for f in p:
280
332
        if (f == '..') or (f == None) or (f == ''):
281
333
            bailout("sorry, %r not allowed in path" % f)
282
 
    return '/'.join(p)
 
334
    return os.path.join(*p)
283
335
 
284
336
 
285
337
def appendpath(p1, p2):
286
338
    if p1 == '':
287
339
        return p2
288
340
    else:
289
 
        return p1 + '/' + p2
 
341
        return os.path.join(p1, p2)
290
342
    
291
343
 
292
344
def extern_command(cmd, ignore_errors = False):