kcl-lang.io/kpm@v0.8.7-0.20240520061008-9fc4c5efc8c7/pkg/path/path_unix.go (about)

     1  //go:build !windows
     2  // +build !windows
     3  
     4  package path
     5  
     6  import (
     7  	"path/filepath"
     8  	"strings"
     9  )
    10  
    11  var NeedToSanitize map[rune]bool
    12  
    13  func init() {
    14  	NeedToSanitize = map[rune]bool{
    15  		'\x00': true,
    16  	}
    17  }
    18  
    19  // sanitizePath cleans a path string by removing or replacing invalid Windows file name characters.
    20  func sanitizePath(path string, sanitize sanitizer, toSanitize map[rune]bool) string {
    21  	// replace all slashes with backslashes
    22  	path = filepath.FromSlash(path)
    23  
    24  	// replace all invalid characters
    25  	return strings.Map(func(r rune) rune {
    26  		if _, isInvalid := toSanitize[r]; isInvalid {
    27  			return sanitize(r, toSanitize)
    28  		}
    29  		return r
    30  	}, path)
    31  }
    32  
    33  // sanitizer defined how to handle and replace invalid file name characters.
    34  type sanitizer func(rune, map[rune]bool) rune
    35  
    36  // SanitizePath replaces invalid characters in a Windows path with a placeholder.
    37  func SanitizePath(path string) string {
    38  	return sanitizePath(path, func(r rune, invalidChars map[rune]bool) rune {
    39  		if _, ok := invalidChars[r]; ok {
    40  			return '_'
    41  		}
    42  		return r
    43  	}, NeedToSanitize)
    44  }