From cb5bfc303cd7c637b0099081a1130af8830bad26 Mon Sep 17 00:00:00 2001 From: Jonathan Van Eenwyk Date: Mon, 10 Aug 2020 09:47:13 -0700 Subject: [PATCH] Sanitize dut_id for use in output file name Sometimes the DUT id may contain characters that aren't appropriate for file names. Sanitize the dut_id, so that we can safely use any ID. --- openhtf/output/callbacks/__init__.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/openhtf/output/callbacks/__init__.py b/openhtf/output/callbacks/__init__.py index d29ce4531..5a08ef3da 100644 --- a/openhtf/output/callbacks/__init__.py +++ b/openhtf/output/callbacks/__init__.py @@ -22,6 +22,8 @@ import collections import contextlib +import os +import re import shutil import tempfile @@ -90,6 +92,8 @@ def create_file_name(self, test_record): record_dict = data.convert_to_base_types( test_record, ignore_keys=('code_info', 'phases', 'log_records')) if self._pattern_formattable: + record_dict['dut_id'] = self._get_valid_filename(record_dict['dut_id']) + return util.format_string(self.filename_pattern, record_dict) else: raise ValueError( @@ -122,3 +126,9 @@ def __call__(self, test_record): else: raise TypeError('Expected string or iterable but got {}.'.format( type(serialized_record))) + + @staticmethod + def _get_valid_filename(s): + # Reference: https://stackoverflow.com/a/46801075 + s = str(s).strip().replace(' ', '_') + return re.sub(r'(?u)[^-\w.]', '_', s)