1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
|
# Copyright 2004 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Header: /local/data/ulm/cvs/history/var/cvsroot/gentoo-src/portage/portage/util/fs.py,v 1.2 2005/07/13 05:51:35 ferringb Exp $
cvs_id_string="$Id: fs.py,v 1.2 2005/07/13 05:51:35 ferringb Exp $"[5:-2]
import os
try:
#XXX: This should get renamed to bsd_chflags, I think.
import chflags
bsd_chflags = chflags
except SystemExit, e:
raise
except:
# XXX: This should get renamed to bsd_chflags, I think.
bsd_chflags = None
def grabfile(myfilename, compat_level=0):
"""This function grabs the lines in a file, normalizes whitespace and returns lines in a list; if a line
begins with a #, it is ignored, as are empty lines"""
try:
myfile=open(myfilename,"r")
except IOError:
return []
mylines=myfile.readlines()
myfile.close()
newlines=[]
for x in mylines:
#the split/join thing removes leading and trailing whitespace, and converts any whitespace in the line
#into single spaces.
myline = ' '.join(x.split())
if not len(myline):
continue
if myline[0]=="#":
# Check if we have a compat-level string. BC-integration data.
# '##COMPAT==>N<==' 'some string attached to it'
mylinetest = myline.split("<==", 1)
if len(mylinetest) == 2:
myline_potential = mylinetest[1]
mylinetest = mylinetest[0].split("##COMPAT==>")
if len(mylinetest) == 2:
if compat_level >= int(mylinetest[1]):
# It's a compat line, and the key matches.
newlines.append(myline_potential)
continue
else:
continue
newlines.append(myline)
return newlines
def grab_multiple(basename, locations, handler, all_must_exist=0):
mylist = []
for x in locations:
mylist.append(handler(x+"/"+basename))
return mylist
def grabdict(myfilename,juststrings=0,empty=0):
"""This function grabs the lines in a file, normalizes whitespace and returns lines in a dictionary"""
newdict={}
try:
myfile=open(myfilename,"r")
except IOError,e:
return newdict
mylines=myfile.readlines()
myfile.close()
for x in mylines:
#the split/join thing removes leading and trailing whitespace, and converts any whitespace in the line
#into single spaces.
if x[0] == "#":
continue
myline = x.split()
if len(myline)<2 and empty==0:
continue
if len(myline)<1 and empty==1:
continue
if juststrings:
newdict[myline[0]]=" ".join( myline[1:] )
else:
newdict[myline[0]]=myline[1:]
return newdict
def grabints(myfilename):
newdict={}
try:
myfile=open(myfilename,"r")
except IOError:
return newdict
mylines=myfile.readlines()
myfile.close()
for x in mylines:
#the split/join thing removes leading and trailing whitespace, and converts any whitespace in the line
#into single spaces.
myline=x.split()
if len(myline)!=2:
continue
newdict[myline[0]]=int(myline[1])
return newdict
def writeints(mydict,myfilename):
try:
myfile=open(myfilename,"w")
except IOError:
return 0
for x in mydict.keys():
myfile.write(x+" "+`mydict[x]`+"\n")
myfile.close()
return 1
def writedict(mydict,myfilename,writekey=1):
"""Writes out a dict to a file; writekey=0 mode doesn't write out
the key and assumes all values are strings, not lists."""
try:
myfile=open(myfilename,"w")
except IOError:
writemsg("Failed to open file for writedict(): "+str(myfilename)+"\n")
return 0
if not writekey:
for x in mydict.values():
myfile.write(x+"\n")
else:
for x in mydict.keys():
myfile.write(x+" ")
for y in mydict[x]:
myfile.write(y+" ")
myfile.write("\n")
myfile.close()
return 1
def getconfig(mycfg,tolerant=0,allow_sourcing=False):
import shlex, string
mykeys={}
try:
f=open(mycfg,'r')
except IOError:
return None
try:
lex=shlex.shlex(f)
lex.wordchars=string.digits+string.letters+"~!@#$%*_\:;?,./-+{}"
lex.quotes="\"'"
if allow_sourcing:
lex.source="source"
while 1:
key=lex.get_token()
if (key==''):
#normal end of file
break;
equ=lex.get_token()
if (equ==''):
#unexpected end of file
#lex.error_leader(self.filename,lex.lineno)
if not tolerant:
writemsg("!!! Unexpected end of config file: variable "+str(key)+"\n")
raise Exception("ParseError: Unexpected EOF: "+str(mycfg)+": on/before line "+str(lex.lineno))
else:
return mykeys
elif (equ!='='):
#invalid token
#lex.error_leader(self.filename,lex.lineno)
if not tolerant:
writemsg("!!! Invalid token (not \"=\") "+str(equ)+"\n")
raise Exception("ParseError: Invalid token (not '='): "+str(mycfg)+": line "+str(lex.lineno))
else:
return mykeys
val=lex.get_token()
if (val==''):
#unexpected end of file
#lex.error_leader(self.filename,lex.lineno)
if not tolerant:
writemsg("!!! Unexpected end of config file: variable "+str(key)+"\n")
raise portage_exception.CorruptionError("ParseError: Unexpected EOF: "+str(mycfg)+": line "+str(lex.lineno))
else:
return mykeys
mykeys[key]=varexpand(val,mykeys)
except SystemExit, e:
raise
except Exception, e:
raise e.__class__, str(e)+" in "+mycfg
return mykeys
#cache expansions of constant strings
cexpand={}
def varexpand(mystring,mydict={}):
"""
new variable expansion code. Removes quotes, handles \n, etc.
This code is used by the configfile code, as well as others (parser)
This would be a good bunch of code to port to C.
"""
mystring=" "+mystring
if mystring in cexpand:
return cexpand[mystring]
numvars=0
#in single, double quotes
insing=0
indoub=0
pos=1
newstring=" "
while (pos<len(mystring)):
if (mystring[pos]=="'") and (mystring[pos-1]!="\\"):
if (indoub):
newstring=newstring+"'"
else:
insing=not insing
pos=pos+1
continue
elif (mystring[pos]=='"') and (mystring[pos-1]!="\\"):
if (insing):
newstring=newstring+'"'
else:
indoub=not indoub
pos=pos+1
continue
if (not insing):
#expansion time
if (mystring[pos]=="\n"):
#convert newlines to spaces
newstring=newstring+" "
pos=pos+1
elif (mystring[pos]=="\\"):
#backslash expansion time
if (pos+1>=len(mystring)):
newstring=newstring+mystring[pos]
break
else:
a=mystring[pos+1]
pos=pos+2
if a=='a':
newstring=newstring+chr(007)
elif a=='b':
newstring=newstring+chr(010)
elif a=='e':
newstring=newstring+chr(033)
elif (a=='f') or (a=='n'):
newstring=newstring+chr(012)
elif a=='r':
newstring=newstring+chr(015)
elif a=='t':
newstring=newstring+chr(011)
elif a=='v':
newstring=newstring+chr(013)
elif a!='\n':
#remove backslash only, as bash does: this takes care of \\ and \' and \" as well
newstring=newstring+mystring[pos-1:pos]
continue
elif (mystring[pos]=="$") and (mystring[pos-1]!="\\"):
pos=pos+1
if mystring[pos]=="{":
pos=pos+1
braced=True
else:
braced=False
myvstart=pos
validchars=string.ascii_letters+string.digits+"_"
while mystring[pos] in validchars:
if (pos+1)>=len(mystring):
if braced:
cexpand[mystring]=""
return ""
else:
pos=pos+1
break
pos=pos+1
myvarname=mystring[myvstart:pos]
if braced:
if mystring[pos]!="}":
cexpand[mystring]=""
return ""
else:
pos=pos+1
if len(myvarname)==0:
cexpand[mystring]=""
return ""
numvars=numvars+1
if mydict.has_key(myvarname):
newstring=newstring+mydict[myvarname]
else:
newstring=newstring+mystring[pos]
pos=pos+1
else:
newstring=newstring+mystring[pos]
pos=pos+1
if numvars==0:
cexpand[mystring]=newstring[1:]
return newstring[1:]
def pickle_write(data,filename,debug=0):
import cPickle,os
try:
myf=open(filename,"w")
cPickle.dump(data,myf,cPickle.HIGHEST_PROTOCOL)
myf.close()
writemsg("Wrote pickle: "+str(filename)+"\n",1)
os.chown(myefn,uid,portage_gid)
os.chmod(myefn,0664)
except SystemExit, e:
raise
except Exception, e:
return 0
return 1
def pickle_read(filename,default=None,debug=0):
import cPickle,os
if not os.access(filename, os.R_OK):
writemsg("pickle_read(): File not readable. '"+filename+"'\n",1)
return default
data = None
try:
myf = open(filename)
mypickle = cPickle.Unpickler(myf)
mypickle.find_global = None
data = mypickle.load()
myf.close()
del mypickle,myf
writemsg("pickle_read(): Loaded pickle. '"+filename+"'\n",1)
except SystemExit, e:
raise
except Exception, e:
writemsg("!!! Failed to load pickle: "+str(e)+"\n",1)
data = default
return data
# throw this out.
def movefile(src,dest,newmtime=None,sstat=None,mysettings=None):
"""moves a file from src to dest, preserving all permissions and attributes; mtime will
be preserved even when moving across filesystems. Returns true on success and false on
failure. Move is atomic."""
#print "movefile("+str(src)+","+str(dest)+","+str(newmtime)+","+str(sstat)+")"
from portage.spawn import selinux_capable
import stat, shutil, os.path
if selinux_capable:
import selinux
from portage.os_data import lchown
try:
if not sstat:
sstat=os.lstat(src)
if bsd_chflags:
sflags=bsd_chflags.lgetflags(src)
if sflags < 0:
# Problem getting flags...
print "!!! Couldn't get flags for "+dest+"\n"
return None
except SystemExit, e:
raise
except Exception, e:
print "!!! Stating source file failed... movefile()"
print "!!!",e
return None
destexists=1
try:
dstat=os.lstat(dest)
except SystemExit, e:
raise
except:
dstat=os.lstat(os.path.dirname(dest))
destexists=0
if bsd_chflags:
# Check that we can actually unset schg etc flags...
# Clear the flags on source and destination; we'll reinstate them after merging
if(destexists):
if bsd_chflags.lchflags(dest, 0) < 0:
print "!!! Couldn't clear flags on file being merged: \n"
# We might have an immutable flag on the parent dir; save and clear.
pflags=bsd_chflags.lgetflags(os.path.dirname(dest))
bsd_chflags.lchflags(os.path.dirname(dest), 0)
# Don't bother checking the return value here; if it fails then the next line will catch it.
bsd_chflags.lchflags(src, 0)
if bsd_chflags.lhasproblems(src)>0 or (destexists and bsd_chflags.lhasproblems(dest)>0) or bsd_chflags.lhasproblems(os.path.dirname(dest))>0:
# This is bad: we can't merge the file with these flags set.
print "!!! Can't merge file "+dest+" because of flags set\n"
return None
if destexists:
if stat.S_ISLNK(dstat.st_mode):
try:
os.unlink(dest)
destexists=0
except SystemExit, e:
raise
except Exception, e:
pass
if stat.S_ISLNK(sstat.st_mode):
try:
target=os.readlink(src)
if mysettings and mysettings["D"]:
if target.find(mysettings["D"])==0:
target=target[len(mysettings["D"]):]
if destexists and not stat.S_ISDIR(dstat.st_mode):
os.unlink(dest)
if selinux_capable:
sid = selinux.get_lsid(src)
selinux.secure_symlink(target,dest,sid)
else:
os.symlink(target,dest)
lchown(dest,sstat.st_uid, sstat.st_gid)
if bsd_chflags:
# Restore the flags we saved before moving
if bsd_chflags.lchflags(dest, sflags) < 0 or bsd_chflags.lchflags(os.path.dirname(dest), pflags) < 0:
writemsg("!!! Couldn't restore flags ("+str(flags)+") on " + dest+":\n")
writemsg("!!! %s\n" % str(e))
return None
return os.lstat(dest).st_mtime
except SystemExit, e:
raise
except Exception, e:
print "!!! failed to properly create symlink:"
print "!!!",dest,"->",target
print "!!!",e
return None
renamefailed=1
if sstat.st_dev == dstat.st_dev or selinux_capable:
try:
if selinux_capable:
ret=selinux.secure_rename(src,dest)
else:
ret=os.rename(src,dest)
renamefailed=0
except SystemExit, e:
raise
except Exception, e:
import errno
if e[0]!=errno.EXDEV:
# Some random error.
print "!!! Failed to move",src,"to",dest
print "!!!",e
return None
# Invalid cross-device-link 'bind' mounted or actually Cross-Device
if renamefailed:
didcopy=0
if stat.S_ISREG(sstat.st_mode):
try: # For safety copy then move it over.
if selinux_capable:
selinux.secure_copy(src,dest+"#new")
selinux.secure_rename(dest+"#new",dest)
else:
shutil.copyfile(src,dest+"#new")
os.rename(dest+"#new",dest)
didcopy=1
except SystemExit, e:
raise
except Exception, e:
print '!!! copy',src,'->',dest,'failed.'
print "!!!",e
return None
else:
#we don't yet handle special, so we need to fall back to /bin/mv
if selinux_capable:
a=portage_exec.spawn_get_output(MOVE_BINARY+" -c -f '%s' '%s'" % (src,dest))
else:
a=portage_exec.spawn_get_output(MOVE_BINARY+" -f '%s' '%s'" % (src,dest))
if a[0]!=0:
print "!!! Failed to move special file:"
print "!!! '"+src+"' to '"+dest+"'"
print "!!!",a
return None # failure
try:
if didcopy:
lchown(dest,sstat.st_uid, sstat.st_gid)
os.chmod(dest, stat.S_IMODE(sstat.st_mode)) # Sticky is reset on chown
os.unlink(src)
except SystemExit, e:
os.unlink(src)
except SystemExit, e:
raise
except Exception, e:
print "!!! Failed to chown/chmod/unlink in movefile()"
print "!!!",dest
print "!!!",e
return None
if newmtime:
os.utime(dest,(newmtime,newmtime))
else:
os.utime(dest, (sstat.st_atime, sstat.st_mtime))
newmtime=sstat.st_mtime
if bsd_chflags:
# Restore the flags we saved before moving
if bsd_chflags.lchflags(dest, sflags) < 0 or bsd_chflags.lchflags(os.path.dirname(dest), pflags) < 0:
writemsg("!!! Couldn't restore flags ("+str(sflags)+") on " + dest+":\n")
return None
return newmtime
def abssymlink(symlink):
"""
This reads symlinks, resolving the relative symlinks, and returning the absolute.
"""
import os.path
mylink=os.readlink(symlink)
if mylink[0] != '/':
mydir=os.path.dirname(symlink)
mylink=mydir+"/"+mylink
return os.path.normpath(mylink)
def normpath(mypath):
newpath = os.path.normpath(mypath)
if len(newpath) > 1:
if newpath[:2] == "//":
return newpath[1:]
return newpath
|