ferrero-opentext/Python-Version/scripts/shared/common.py

40 lines
1 KiB
Python

import re
def sanitize_box_item_name(name):
"""
Sanitize a string to be a valid Box folder or file name.
Box Constraints:
- No non-printable ASCII
- No "/" or "\\"
- No leading or trailing whitespace
- No "." or ".." as the exact name
Args:
name (str): The original name
Returns:
str: Sanitized name
"""
if not name:
return "Untitled"
# 1. Replace invalid path characters
safe_name = name.replace('/', '_').replace('\\', '_')
# 2. Remove non-printable characters (keep only space through tilde)
# This regex matches anything NOT in the range \x20 (space) to \x7E (~)
safe_name = re.sub(r'[^\x20-\x7E]', '', safe_name)
# 3. Strip leading/trailing whitespace
safe_name = safe_name.strip()
# 4. Handle empty string after sanitization
if not safe_name:
return "Untitled_Item"
# 5. Handle reserved names
if safe_name in ['.', '..']:
return "_{}_".format(safe_name)
return safe_name