| 1 |
# Copyright 2011, VMware, Inc. |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or |
| 12 |
# implied. |
| 13 |
# See the License for the specific language governing permissions and |
| 14 |
# limitations under the License. |
| 15 |
|
| 16 |
import os |
| 17 |
import tempfile |
| 18 |
|
| 19 |
|
| 20 |
def replace_file(file_name, data, file_mode=0o644): |
| 21 |
"""Replaces the contents of file_name with data in a safe manner. |
| 22 |
|
| 23 |
First write to a temp file and then rename. Since POSIX renames are |
| 24 |
atomic, the file is unlikely to be corrupted by competing writes. |
| 25 |
|
| 26 |
We create the tempfile on the same device to ensure that it can be renamed. |
| 27 |
|
| 28 |
:param file_name: Path to the file to replace. |
| 29 |
:param data: The data to write to the file. |
| 30 |
:param file_mode: The mode to use for the replaced file. |
| 31 |
:returns: None. |
| 32 |
""" |
| 33 |
|
| 34 |
base_dir = os.path.dirname(os.path.abspath(file_name)) |
| 35 |
with tempfile.NamedTemporaryFile('w+', |
| 36 |
dir=base_dir, |
| 37 |
delete=False) as tmp_file: |
| 38 |
tmp_file.write(data) |
| 39 |
os.chmod(tmp_file.name, file_mode) |
| 40 |
os.rename(tmp_file.name, file_name) |