main
Raw Download raw file
 1// Package sanitize provides utilities for creating filesystem-safe names.
 2package sanitize
 3
 4import (
 5	"strings"
 6	"unicode"
 7)
 8
 9// forbiddenChars contains characters that are not allowed in filenames.
10// This covers Windows (/ \ : * ? " < > |) and Unix (/) restrictions.
11const forbiddenChars = `/\:*?"<>|`
12
13// Filename removes or replaces characters that are unsafe for filenames.
14// It replaces forbidden characters with underscores and collapses multiple
15// underscores into one.
16func Filename(name string) string {
17	var b strings.Builder
18	b.Grow(len(name))
19
20	lastWasUnderscore := false
21	for _, r := range name {
22		if strings.ContainsRune(forbiddenChars, r) || unicode.IsControl(r) {
23			if !lastWasUnderscore {
24				b.WriteRune('_')
25				lastWasUnderscore = true
26			}
27			continue
28		}
29		b.WriteRune(r)
30		lastWasUnderscore = r == '_'
31	}
32
33	result := strings.TrimSpace(b.String())
34	result = strings.Trim(result, "_")
35	return result
36}