SanitizeName sanitizes a string for use as an identifier, file name, or similar context. It provides configurable behavior through the SanitizeOptions parameter.
(name string, opts *SanitizeOptions)
| 74 | // SanitizeName sanitizes a string for use as an identifier, file name, or similar context. |
| 75 | // It provides configurable behavior through the SanitizeOptions parameter. |
| 76 | func SanitizeName(name string, opts *SanitizeOptions) string { |
| 77 | logSanitizeInput(name, opts) |
| 78 | |
| 79 | // Handle nil options |
| 80 | if opts == nil { |
| 81 | opts = &SanitizeOptions{} |
| 82 | } |
| 83 | |
| 84 | result := normalizeSanitizeSeparators(strings.ToLower(name), opts) |
| 85 | result = applySanitizePattern(result, buildSanitizePreservePattern(opts), len(opts.PreserveSpecialChars) > 0) |
| 86 | |
| 87 | // Consolidate multiple consecutive hyphens into a single hyphen |
| 88 | result = multipleHyphens.ReplaceAllString(result, "-") |
| 89 | |
| 90 | // Optionally trim leading/trailing hyphens |
| 91 | if opts.TrimHyphens { |
| 92 | result = strings.Trim(result, "-") |
| 93 | } |
| 94 | |
| 95 | // Return default value if result is empty |
| 96 | if result == "" && opts.DefaultValue != "" { |
| 97 | sanitizeLog.Printf("Sanitized name is empty, using default: %q", opts.DefaultValue) |
| 98 | return opts.DefaultValue |
| 99 | } |
| 100 | |
| 101 | sanitizeLog.Printf("Sanitized name result: %q", result) |
| 102 | return result |
| 103 | } |
| 104 | |
| 105 | // logSanitizeInput logs input parameters when debug logging is enabled. |
| 106 | func logSanitizeInput(name string, opts *SanitizeOptions) { |