浏览文件
fold.go
52 行 · 1.7 KB历史下载| 1 | package reversesshfs |
| 2 | |
| 3 | import ( |
| 4 | "strings" |
| 5 | "unicode" |
| 6 | |
| 7 | "golang.org/x/text/cases" |
| 8 | "golang.org/x/text/unicode/norm" |
| 9 | ) |
| 10 | |
| 11 | // FoldName is s as a case-insensitive or normalization-insensitive file system compares it, or wider: |
| 12 | // two names such a file system takes as one entry have the same FoldName. |
| 13 | // |
| 14 | // It drops the default-ignorable code points (HFS+ and the casefold feature of ext4, f2fs and tmpfs ignore |
| 15 | // them; git's utf8.c has HFS+'s list), canonically decomposes (APFS, HFS+ and casefold ignore |
| 16 | // normalization) and fully case-folds (APFS folds "ß" as "ss"). Dotless "ı" is "i", as in NTFS's |
| 17 | // upcase table. Names that differ only in these ways are the same name here, even where the |
| 18 | // host's file system keeps them apart: that only makes more paths protected. |
| 19 | // |
| 20 | // Not covered: a code point the file system's Unicode tables know and Go's do not (the kernel's are older), |
| 21 | // and a volume with a customized NTFS upcase table. On Windows the protection does not rest on this |
| 22 | // alone: handles are checked by their normalized names. |
| 23 | func FoldName(s string) string { |
| 24 | if isPlainASCII(s) { |
| 25 | return strings.ToLower(s) |
| 26 | } |
| 27 | s = strings.Map(foldRune, s) |
| 28 | s = norm.NFD.String(cases.Fold().String(norm.NFD.String(s))) |
| 29 | return strings.Map(foldRune, s) |
| 30 | } |
| 31 | |
| 32 | func isPlainASCII(s string) bool { |
| 33 | for i := 0; i < len(s); i++ { |
| 34 | if s[i] >= 0x80 { |
| 35 | return false |
| 36 | } |
| 37 | } |
| 38 | return true |
| 39 | } |
| 40 | |
| 41 | // foldRune drops what is ignorable in a name, and maps dotless i. |
| 42 | func foldRune(r rune) rune { |
| 43 | switch { |
| 44 | case r == 'ı': |
| 45 | return 'i' |
| 46 | case r < 0x80: |
| 47 | return r |
| 48 | case unicode.Is(unicode.Cf, r), unicode.Is(unicode.Variation_Selector, r), unicode.Is(unicode.Other_Default_Ignorable_Code_Point, r): |
| 49 | return -1 |
| 50 | } |
| 51 | return r |
| 52 | } |

