kcl-lang.io/kpm@v0.8.7-0.20240520061008-9fc4c5efc8c7/pkg/path/path_windows.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  		'<': true, '>': true, ':': true, '"': true, '|': true, '?': true, '*': true, '\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  	volumeName := filepath.VolumeName(path)
    39  	// Only sanitize the part of the path after the volume name
    40  	sanitized := sanitizePath(path[len(volumeName):], func(r rune, invalidChars map[rune]bool) rune {
    41  		if _, ok := invalidChars[r]; ok {
    42  			return '_'
    43  		}
    44  		return r
    45  	}, NeedToSanitize)
    46  
    47  	return volumeName + sanitized
    48  }