github.com/alibaba/ilogtail/pkg@v0.0.0-20250526110833-c53b480d046c/helper/path_helper.go (about) 1 // Copyright 2021 iLogtail Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package helper 16 17 import ( 18 "os" 19 "path/filepath" 20 "runtime" 21 "sort" 22 "strings" 23 ) 24 25 var windowsSystemDrive = mustGetWindowsSystemDrive() 26 27 // mustGetWindowsSystemDrive try to find the system drive on Windows. 28 func mustGetWindowsSystemDrive() string { 29 if runtime.GOOS != "windows" { 30 return "" 31 } 32 var systemDrive = os.Getenv("SYSTEMDRIVE") 33 if systemDrive == "" { 34 systemDrive = filepath.VolumeName(os.Getenv("SYSTEMROOT")) 35 } 36 if systemDrive == "" { 37 systemDrive = "C:" 38 } 39 return systemDrive 40 } 41 42 // NormalizeWindowsPath returns the normal path in heterogeneous platform. 43 // parses the root path with windows system driver. 44 func NormalizeWindowsPath(path string) string { 45 if runtime.GOOS == "windows" { 46 // parses the root path with windows system driver. 47 if strings.HasPrefix(path, "/") { 48 path = filepath.FromSlash(path) 49 return windowsSystemDrive + path 50 } 51 } 52 return path 53 } 54 55 func GetFileListByPrefix(dirPath, prefix string, needDir bool, num int) ([]string, error) { 56 stat, err := os.Stat(dirPath) 57 if err != nil { 58 return nil, err 59 } 60 if !stat.IsDir() { 61 return []string{dirPath}, nil 62 } 63 64 dir, err := os.Open(dirPath) //nolint:gosec 65 if err != nil { 66 return nil, err 67 } 68 fis, err := dir.Readdir(0) 69 if err != nil { 70 return nil, err 71 } 72 73 files := make([]string, 0, len(fis)) 74 for _, fi := range fis { 75 if !fi.IsDir() && strings.HasPrefix(fi.Name(), prefix) { 76 if needDir { 77 files = append(files, filepath.Join(dirPath, fi.Name())) 78 } else { 79 files = append(files, fi.Name()) 80 } 81 } 82 83 } 84 if num == 0 || num > len(files) { 85 num = len(files) 86 } 87 sort.Strings(files) 88 return files[0:num], nil 89 }