Revision 71714516 lib/utils.py
b/lib/utils.py | ||
---|---|---|
959 | 959 |
|
960 | 960 |
def WriteFile(file_name, fn=None, data=None, |
961 | 961 |
mode=None, uid=-1, gid=-1, |
962 |
atime=None, mtime=None, |
|
963 |
check_abspath=True, dry_run=False, backup=False): |
|
962 |
atime=None, mtime=None, close=True, |
|
963 |
check_abspath=True, dry_run=False, backup=False, |
|
964 |
prewrite=None, postwrite=None): |
|
964 | 965 |
"""(Over)write a file atomically. |
965 | 966 |
|
966 | 967 |
The file_name and either fn (a function taking one argument, the |
... | ... | |
974 | 975 |
exception, an existing target file should be unmodified and the |
975 | 976 |
temporary file should be removed. |
976 | 977 |
|
978 |
Args: |
|
979 |
file_name: New filename |
|
980 |
fn: Content writing function, called with file descriptor as parameter |
|
981 |
data: Content as string |
|
982 |
mode: File mode |
|
983 |
uid: Owner |
|
984 |
gid: Group |
|
985 |
atime: Access time |
|
986 |
mtime: Modification time |
|
987 |
close: Whether to close file after writing it |
|
988 |
prewrite: Function object called before writing content |
|
989 |
postwrite: Function object called after writing content |
|
990 |
|
|
991 |
Returns: |
|
992 |
None if "close" parameter evaluates to True, otherwise file descriptor. |
|
993 |
|
|
977 | 994 |
""" |
978 | 995 |
if check_abspath and not os.path.isabs(file_name): |
979 | 996 |
raise errors.ProgrammerError("Path passed to WriteFile is not" |
... | ... | |
998 | 1015 |
os.chown(new_name, uid, gid) |
999 | 1016 |
if mode: |
1000 | 1017 |
os.chmod(new_name, mode) |
1018 |
if callable(prewrite): |
|
1019 |
prewrite(fd) |
|
1001 | 1020 |
if data is not None: |
1002 | 1021 |
os.write(fd, data) |
1003 | 1022 |
else: |
1004 | 1023 |
fn(fd) |
1024 |
if callable(postwrite): |
|
1025 |
postwrite(fd) |
|
1005 | 1026 |
os.fsync(fd) |
1006 | 1027 |
if atime is not None and mtime is not None: |
1007 | 1028 |
os.utime(new_name, (atime, mtime)) |
1008 | 1029 |
if not dry_run: |
1009 | 1030 |
os.rename(new_name, file_name) |
1010 | 1031 |
finally: |
1011 |
os.close(fd) |
|
1032 |
if close: |
|
1033 |
os.close(fd) |
|
1034 |
result = None |
|
1035 |
else: |
|
1036 |
result = fd |
|
1012 | 1037 |
RemoveFile(new_name) |
1013 | 1038 |
|
1039 |
return result |
|
1040 |
|
|
1014 | 1041 |
|
1015 | 1042 |
def all(seq, pred=bool): |
1016 | 1043 |
"Returns True if pred(x) is True for every element in the iterable" |
Also available in: Unified diff