Files
bj_power/bj_power_wms/internal/backup/browse.go
T

77 lines
1.9 KiB
Go

package backup
import (
"os"
"path/filepath"
"strings"
"golang.org/x/sys/windows"
)
// DriveInfo 盘符信息(Windows)。
type DriveInfo struct {
Letter string `json:"letter"`
Path string `json:"path"`
}
// ListDrives 列出本机所有盘符(Windows)。
func ListDrives() ([]DriveInfo, error) {
mask, err := windows.GetLogicalDrives()
if err != nil {
return nil, err
}
out := make([]DriveInfo, 0)
for i := 0; i < 26; i++ {
if mask&(1<<uint(i)) != 0 {
letter := string(rune('A' + i))
out = append(out, DriveInfo{Letter: letter, Path: letter + ":\\"})
}
}
return out, nil
}
// DirEntry 目录浏览项(仅目录)。
type DirEntry struct {
Name string `json:"name"`
Path string `json:"path"`
}
// isHiddenOrSystem 判断 Windows 隐藏/系统目录(不暴露系统目录与隐藏目录)。
func isHiddenOrSystem(path string) bool {
p, err := windows.UTF16PtrFromString(path)
if err != nil {
return false
}
attr, err := windows.GetFileAttributes(p)
if err != nil {
return false
}
return attr&windows.FILE_ATTRIBUTE_HIDDEN != 0 || attr&windows.FILE_ATTRIBUTE_SYSTEM != 0
}
// ListDir 列出给定目录的一级子目录(只返回目录,不返回文件、不回显文件名)。
// path 经 filepath.Clean 规范化;过滤隐藏/系统目录。接口 admin-only,只读目录、无写操作。
func ListDir(path string) ([]DirEntry, error) {
if strings.TrimSpace(path) == "" {
return nil, nil
}
clean := filepath.Clean(path)
entries, err := os.ReadDir(clean)
if err != nil {
return nil, err
}
out := make([]DirEntry, 0, len(entries))
for _, e := range entries {
if !e.IsDir() {
continue
}
name := e.Name()
if strings.HasPrefix(name, ".") || isHiddenOrSystem(filepath.Join(clean, name)) {
continue
}
full := filepath.Join(clean, name)
out = append(out, DirEntry{Name: name, Path: full})
}
return out, nil
}