Merge "Fail correctly if can't create output files"

This commit is contained in:
Zuul 2019-08-30 01:36:56 +00:00 committed by Gerrit Code Review
commit a1566837cf
2 changed files with 29 additions and 16 deletions

View File

@ -23,6 +23,7 @@ except AttributeError:
import csv
import datetime
import errno
import getpass
import glob
import hashlib
@ -1939,3 +1940,26 @@ def reset_cmdline():
return
sys.stdout.write(run_command(['reset', '-I']))
sys.stdout.flush()
def safe_write(path, data):
'''Write to disk and exit safely if can not write correctly.'''
log = logging.getLogger(__name__ + ".safe_write")
if os.path.exists(path):
log.warning(
"The output file %s will be overriden",
path
)
try:
with os.fdopen(os.open(path,
os.O_CREAT | os.O_TRUNC | os.O_WRONLY, 0o666),
'w') as f:
f.write(data)
except OSError as error:
if error.errno != errno.EEXIST:
msg = _('The output file %(file)s can not be '
'created. Error: %(msg)') % {'file': path,
'msg': error.message}
raise oscexc.CommandError(msg)

View File

@ -460,10 +460,8 @@ class PrepareImageFiles(command.Command):
moving it to backup.")
shutil.move(parsed_args.output_env_file,
parsed_args.output_env_file + ".backup")
with os.fdopen(os.open(parsed_args.output_env_file,
os.O_CREAT | os.O_TRUNC | os.O_WRONLY, 0o666),
'w') as f:
f.write(build_env_file(params, self.app.command_options))
utils.safe_write(parsed_args.output_env_file,
build_env_file(params, self.app.command_options))
result = prepare_data[output_images_file]
result_str = yaml.safe_dump({'container_images': result},
@ -471,10 +469,7 @@ class PrepareImageFiles(command.Command):
sys.stdout.write(result_str)
if parsed_args.output_images_file:
with os.fdopen(os.open(parsed_args.output_images_file,
os.O_CREAT | os.O_TRUNC | os.O_WRONLY, 0o666),
'w') as f:
f.write(result_str)
utils.safe_write(parsed_args.output_images_file, result_str)
class DiscoverImageTag(command.Command):
@ -729,10 +724,7 @@ class TripleOImagePrepareDefault(command.Command):
moving it to backup.")
shutil.move(parsed_args.output_env_file,
parsed_args.output_env_file + ".backup")
with os.fdopen(os.open(parsed_args.output_env_file,
os.O_CREAT | os.O_TRUNC | os.O_WRONLY, 0o666),
'w') as f:
f.write(build_env_file(params, self.app.command_options))
utils.safe_write(parsed_args.output_env_file, env_data)
class TripleOImagePrepare(command.Command):
@ -829,9 +821,6 @@ class TripleOImagePrepare(command.Command):
moving it to backup.")
shutil.move(parsed_args.output_env_file,
parsed_args.output_env_file + ".backup")
with os.fdopen(os.open(parsed_args.output_env_file,
os.O_CREAT | os.O_TRUNC | os.O_WRONLY, 0o666),
'w') as f:
f.write(build_env_file(params, self.app.command_options))
utils.safe_write(parsed_args.output_env_file, env_data)
else:
self.app.stdout.write(env_data)