pkg.re/essentialkaos/ek.10@v12.41.0+incompatible/fmtc/lscolors/lscolors.go (about) 1 // Package lscolors provides methods for colorizing file names based on colors from dircolors 2 package lscolors 3 4 // ////////////////////////////////////////////////////////////////////////////////// // 5 // // 6 // Copyright (c) 2022 ESSENTIAL KAOS // 7 // Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0> // 8 // // 9 // ////////////////////////////////////////////////////////////////////////////////// // 10 11 import ( 12 "os" 13 "path" 14 "strings" 15 ) 16 17 // ////////////////////////////////////////////////////////////////////////////////// // 18 19 // colorMap is map ext -> ANSI color code 20 var colorMap map[string]string 21 22 // initialized is initialization flag 23 var initialized bool 24 25 // ////////////////////////////////////////////////////////////////////////////////// // 26 27 // Colorize return file name with ANSI color tags 28 func Colorize(file string) string { 29 if !initialized { 30 initialize() 31 } 32 33 if len(colorMap) == 0 { 34 return file 35 } 36 37 for glob, color := range colorMap { 38 isMatch, _ := path.Match(glob, file) 39 40 if isMatch { 41 return "\033[" + color + "m" + file + "\033[0m" 42 } 43 } 44 45 return file 46 } 47 48 // ////////////////////////////////////////////////////////////////////////////////// // 49 50 // initialize builds color map 51 func initialize() { 52 initialized = true 53 54 lsColors := os.Getenv("LS_COLORS") 55 56 if lsColors == "" { 57 return 58 } 59 60 colorMap = make(map[string]string) 61 62 for _, key := range strings.Split(lsColors, ":") { 63 if !strings.HasPrefix(key, "*") || !strings.ContainsRune(key, '=') { 64 continue 65 } 66 67 sepIndex := strings.IndexRune(key, '=') 68 69 colorMap[key[:sepIndex]] = key[sepIndex+1:] 70 } 71 }