~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Martin Pool
  • Date: 2005-04-15 01:31:21 UTC
  • Revision ID: mbp@sourcefrog.net-20050415013121-b18f1be12a735066
- Doc cleanups from Magnus Therning

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, types
20
 
from stat import S_ISREG, S_ISDIR, ST_MODE, ST_SIZE
 
19
import os, types, re, time, errno
 
20
from stat import S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE
21
21
 
22
 
from errors import bailout
 
22
from errors import bailout, BzrError
 
23
from trace import mutter
 
24
import bzrlib
23
25
 
24
26
def make_readonly(filename):
25
27
    """Make a filename read-only."""
51
53
        return 'file'
52
54
    elif S_ISDIR(mode):
53
55
        return 'directory'
 
56
    elif S_ISLNK(mode):
 
57
        return 'symlink'
54
58
    else:
55
 
        bailout("can't handle file kind of %r" % fp)
 
59
        raise BzrError("can't handle file kind with mode %o of %r" % (mode, f)) 
56
60
 
57
61
 
58
62
 
84
88
    ## XXX: Could alternatively read /proc/sys/kernel/random/uuid on
85
89
    ## Linux, but we need something portable for other systems;
86
90
    ## preferably an implementation in Python.
87
 
    bailout('uuids not allowed!')
88
 
    return chomp(os.popen('uuidgen').readline())
 
91
    try:
 
92
        return chomp(file('/proc/sys/kernel/random/uuid').readline())
 
93
    except IOError:
 
94
        return chomp(os.popen('uuidgen').readline())
 
95
 
89
96
 
90
97
def chomp(s):
91
98
    if s and (s[-1] == '\n'):
112
119
 
113
120
 
114
121
 
115
 
def username():
116
 
    """Return email-style username.
117
 
 
118
 
    Something similar to 'Martin Pool <mbp@sourcefrog.net>'
119
 
 
120
 
    :todo: Check it's reasonably well-formed.
121
 
 
122
 
    :todo: Allow taking it from a dotfile to help people on windows
123
 
           who can't easily set variables.
124
 
 
125
 
    :todo: Cope without pwd module, which is only on unix. 
 
122
def fingerprint_file(f):
 
123
    import sha
 
124
    s = sha.new()
 
125
    b = f.read()
 
126
    s.update(b)
 
127
    size = len(b)
 
128
    return {'size': size,
 
129
            'sha1': s.hexdigest()}
 
130
 
 
131
 
 
132
def _auto_user_id():
 
133
    """Calculate automatic user identification.
 
134
 
 
135
    Returns (realname, email).
 
136
 
 
137
    Only used when none is set in the environment or the id file.
 
138
 
 
139
    This previously used the FQDN as the default domain, but that can
 
140
    be very slow on machines where DNS is broken.  So now we simply
 
141
    use the hostname.
126
142
    """
127
 
    e = os.environ.get('BZREMAIL') or os.environ.get('EMAIL')
128
 
    if e: return e
129
 
 
130
143
    import socket
131
 
    
 
144
 
 
145
    # XXX: Any good way to get real user name on win32?
 
146
 
132
147
    try:
133
148
        import pwd
134
149
        uid = os.getuid()
135
150
        w = pwd.getpwuid(uid)
136
 
        realname, junk = w.pw_gecos.split(',', 1)
137
 
        return '%s <%s@%s>' % (realname, w.pw_name, socket.getfqdn())
 
151
        gecos = w.pw_gecos.decode(bzrlib.user_encoding)
 
152
        username = w.pw_name.decode(bzrlib.user_encoding)
 
153
        comma = gecos.find(',')
 
154
        if comma == -1:
 
155
            realname = gecos
 
156
        else:
 
157
            realname = gecos[:comma]
 
158
 
138
159
    except ImportError:
139
 
        pass
140
 
 
141
 
    import getpass, socket
142
 
    return '<%s@%s>' % (getpass.getuser(), socket.getfqdn())
143
 
 
144
 
 
 
160
        realname = ''
 
161
        import getpass
 
162
        username = getpass.getuser().decode(bzrlib.user_encoding)
 
163
 
 
164
    return realname, (username + '@' + os.gethostname())
 
165
 
 
166
 
 
167
def _get_user_id():
 
168
    v = os.environ.get('BZREMAIL')
 
169
    if v:
 
170
        return v.decode(bzrlib.user_encoding)
 
171
    
 
172
    try:
 
173
        return (open(os.path.expanduser("~/.bzr.email"))
 
174
                .read()
 
175
                .decode(bzrlib.user_encoding)
 
176
                .rstrip("\r\n"))
 
177
    except OSError, e:
 
178
        if e.errno != ENOENT:
 
179
            raise e
 
180
 
 
181
    v = os.environ.get('EMAIL')
 
182
    if v:
 
183
        return v.decode(bzrlib.user_encoding)
 
184
    else:    
 
185
        return None
 
186
 
 
187
 
 
188
def username():
 
189
    """Return email-style username.
 
190
 
 
191
    Something similar to 'Martin Pool <mbp@sourcefrog.net>'
 
192
 
 
193
    TODO: Check it's reasonably well-formed.
 
194
 
 
195
    TODO: Allow taking it from a dotfile to help people on windows
 
196
           who can't easily set variables.
 
197
    """
 
198
    v = _get_user_id()
 
199
    if v:
 
200
        return v
 
201
    
 
202
    name, email = _auto_user_id()
 
203
    if name:
 
204
        return '%s <%s>' % (name, email)
 
205
    else:
 
206
        return email
 
207
 
 
208
 
 
209
_EMAIL_RE = re.compile(r'[\w+.-]+@[\w+.-]+')
145
210
def user_email():
146
211
    """Return just the email component of a username."""
147
 
    e = os.environ.get('BZREMAIL') or os.environ.get('EMAIL')
 
212
    e = _get_user_id()
148
213
    if e:
149
 
        import re
150
 
        m = re.search(r'[\w+.-]+@[\w+.-]+', e)
 
214
        m = _EMAIL_RE.search(e)
151
215
        if not m:
152
 
            bailout('%r is not a reasonable email address' % e)
 
216
            bailout("%r doesn't seem to contain a reasonable email address" % e)
153
217
        return m.group(0)
154
218
 
155
 
 
156
 
    import getpass, socket
157
 
    return '%s@%s' % (getpass.getuser(), socket.getfqdn())
158
 
 
 
219
    return _auto_user_id()[1]
159
220
    
160
221
 
161
222
 
162
223
def compare_files(a, b):
163
224
    """Returns true if equal in contents"""
164
225
    # TODO: don't read the whole thing in one go.
165
 
    result = a.read() == b.read()
166
 
    return result
167
 
 
168
 
 
169
 
 
170
 
def format_date(t, inutc=False):
 
226
    BUFSIZE = 4096
 
227
    while True:
 
228
        ai = a.read(BUFSIZE)
 
229
        bi = b.read(BUFSIZE)
 
230
        if ai != bi:
 
231
            return False
 
232
        if ai == '':
 
233
            return True
 
234
 
 
235
 
 
236
 
 
237
def local_time_offset(t=None):
 
238
    """Return offset of local zone from GMT, either at present or at time t."""
 
239
    # python2.3 localtime() can't take None
 
240
    if t == None:
 
241
        t = time.time()
 
242
        
 
243
    if time.localtime(t).tm_isdst and time.daylight:
 
244
        return -time.altzone
 
245
    else:
 
246
        return -time.timezone
 
247
 
 
248
    
 
249
def format_date(t, offset=0, timezone='original'):
171
250
    ## TODO: Perhaps a global option to use either universal or local time?
172
251
    ## Or perhaps just let people set $TZ?
173
 
    import time
174
 
    
175
252
    assert isinstance(t, float)
176
253
    
177
 
    if inutc:
 
254
    if timezone == 'utc':
178
255
        tt = time.gmtime(t)
179
 
        zonename = 'UTC'
180
256
        offset = 0
181
 
    else:
 
257
    elif timezone == 'original':
 
258
        if offset == None:
 
259
            offset = 0
 
260
        tt = time.gmtime(t + offset)
 
261
    elif timezone == 'local':
182
262
        tt = time.localtime(t)
183
 
        if time.daylight:
184
 
            zonename = time.tzname[1]
185
 
            offset = - time.altzone
186
 
        else:
187
 
            zonename = time.tzname[0]
188
 
            offset = - time.timezone
189
 
            
 
263
        offset = local_time_offset(t)
 
264
    else:
 
265
        bailout("unsupported timezone format %r",
 
266
                ['options are "utc", "original", "local"'])
 
267
 
190
268
    return (time.strftime("%a %Y-%m-%d %H:%M:%S", tt)
191
 
            + ' ' + zonename + ' '
192
 
            + '%+03d%02d' % (offset / 3600, (offset / 60) % 60))
 
269
            + ' %+03d%02d' % (offset / 3600, (offset / 60) % 60))
193
270
 
194
271
 
195
272
def compact_date(when):
230
307
    BzrError: ("sorry, '..' not allowed in path", [])
231
308
    """
232
309
    assert isinstance(p, types.StringTypes)
233
 
    ps = [f for f in p.split('/') if f != '.']
 
310
    ps = [f for f in p.split('/') if (f != '.' and f != '')]
234
311
    for f in ps:
235
312
        if f == '..':
236
313
            bailout("sorry, %r not allowed in path" % f)
239
316
def joinpath(p):
240
317
    assert isinstance(p, list)
241
318
    for f in p:
242
 
        if (f == '..') or (f is None) or (f == ''):
 
319
        if (f == '..') or (f == None) or (f == ''):
243
320
            bailout("sorry, %r not allowed in path" % f)
244
321
    return '/'.join(p)
245
322