""" Parse folder structure. Used to parse the folder structure stored in the direct delivery asset_type. An example of this: {upc(0,6)}/{upc(6,3)}/{upc} Note this logic is taken from: https://github.com/theorchard/common/blob/master/src/ParseFileName.php It should be abstracted from here and put into a common microservice """ import re def split_folder_structure_string(folder_str): """Split string based on pattern used in folder structure. Args: folder_str (string): folder structure found in the asset_type table Returns: split_list (list): list of location parsed from the folder structure """ pattern = '({(?:[^{}]+(?:"[^"]*"|\'[^\']*\')?)+})' split_list = re.split(pattern, folder_str) split_list = list(filter(None, split_list)) return split_list def is_variable(folder_str): """Determine if a string contains a variable, denoted by brackets. Args: folder_str (string): string that could possibly represent a variable Returns: boolean: whether the string is in the format of a variable """ pattern = '{.*}$' matches = re.search(pattern, folder_str) if matches is not None: return True else: return False def process_string(original_str, variables_dict): """Compose a new string with variables inserted. Args: original_str (string): string to insert variables into variables_dict (dict): dict of variables to insert i.e. {'asset_id': 12345, 'upc': 1234567890} Returns: return_str (string): new string with the variables inserted """ breakdown = split_folder_structure_string(original_str) return_str = '' for tmp_str in breakdown: if is_variable(tmp_str): tmp_str = tmp_str.strip('{') tmp_str = tmp_str.strip('}') len_vars = '0' if '(' in tmp_str: var_name, len_vars = tmp_str.split('(') else: var_name = tmp_str var_value = str(variables_dict[var_name]) if (len(len_vars) == 0): return_str += var_value else: len_vars = len_vars.strip(')') len_vars_arr = len_vars.split(',') if (len(len_vars_arr) == 1): new_val = '%0' + len_vars_arr[0] + 's' return_str += new_val % (var_value) else: var_start = int(len_vars_arr[0]) var_end = int(len_vars_arr[0]) + int(len_vars_arr[1]) return_str += var_value[var_start:var_end] else: return_str += tmp_str return return_str