Add dict wrapper

Dict wrapper is used for string format method using
postponed keys resolving.
With this class, format will not fail in case if key not found,
and leaves the unknown key in the string 'as is'.
This behaviour is required as a workaround for strings with
bash-like variables like ${SOMEVAR} to not fail the format because
of 'unknown key: SOMEVAR'.
Returning the 'format' instead of 'replace' is required to use
the escaping of the '{{' '}}' in the string to get '{' '}'.

Change-Id: I1c2bbb083a544eb366c7b00eb1002cc4da652c33
This commit is contained in:
Oleksii Butenko 2017-08-29 12:51:47 +03:00
parent 88a5d02b3d
commit 8e7d469595
2 changed files with 27 additions and 11 deletions

View File

@ -12,10 +12,11 @@
# License for the specific language governing permissions and limitations
# under the License.
from copy import deepcopy
import os
from devops.helpers.helpers import format_data
from devops.helpers import subprocess_runner
from devops import logger
@ -78,21 +79,17 @@ def generate_cloud_image_settings(cloud_image_settings_path, meta_data_path,
" - sudo route add default gw "
"{gateway} {interface_name}")
# FIXME this hack should be rewrited!
# Workaround to be able pass bash-style variables ${}
fmt_user_data_content = deepcopy(user_data_content)
for _key in data_context.keys():
_repl = "{{{0}}}".format(_key)
fmt_user_data_content = \
fmt_user_data_content.replace(_repl, data_context[_key])
fmt_user_data = format_data(user_data_content, data_context)
logger.debug("user_data contains next data: \n{}".format(fmt_user_data))
with open(user_data_path, 'w') as f:
f.write(fmt_user_data_content)
logger.debug(
"user_data contains next data:\n{}".format(fmt_user_data_content))
f.write(fmt_user_data)
# Generate cloud_ISO
cmd = "genisoimage -output {} " \
"-volid cidata -joliet " \
"-rock {} {}".format(cloud_image_settings_path,
user_data_path,
meta_data_path)
subprocess_runner.Subprocess.check_call(cmd)

View File

@ -18,6 +18,7 @@ import functools
import os
import signal
import socket
import string
import time
import warnings
# noinspection PyPep8Naming
@ -424,3 +425,21 @@ def utc_to_local(t):
t = t.replace(tzinfo=tz.tzutc())
# convert to local timezone
return t.astimezone(tz.tzlocal())
def format_data(data_content, data_context):
"""Dict wrapper.
Dict wrapper that returns key name
in case of key missing in the dictionary
"""
class temp_dict(dict):
def __init__(self, kw):
self.__dict = kw
def __getitem__(self, key):
return self.__dict.get(key, '{' + str(key) + '}')
return string.Formatter().vformat(data_content, [], temp_dict(
data_context))