1
0
dwelling-files/pkg/files/files.go

84 lines
1.8 KiB
Go
Raw Normal View History

2022-06-27 04:38:09 +04:00
package files
import (
"net/url"
"os"
"path/filepath"
2022-06-27 04:38:09 +04:00
"time"
)
const FileDateFormat = "2006-01-02 15:04:05 MST"
type DirStat struct {
2024-12-30 15:45:23 +04:00
Files int64
FilesSize string
FilesSizeUnit string
Directories int64
2022-06-27 04:38:09 +04:00
}
type DirEntry struct {
Name string
Link string
Datetime time.Time
Size string
2024-12-30 15:45:23 +04:00
SizeUnit string
2022-06-27 04:38:09 +04:00
}
2024-12-30 14:58:03 +04:00
// ScanDirectory returns entries of directory which is located by its relative
// path within a base directory.
//
// rel path should start/end with a / symbol.
func ScanDirectory(base, rel string) (entries []DirEntry, stats DirStat, err error) {
abs := base + rel
dir, err := os.ReadDir(abs)
if err != nil {
return
}
var dirEntries []DirEntry = make([]DirEntry, 0)
var fileEntries []DirEntry = make([]DirEntry, 0)
var totalFilesSize int64 = 0
for _, ent := range dir {
entry, _ := ent.Info()
2022-06-27 04:38:09 +04:00
var isDirLink bool
if entry.Mode().Type()&os.ModeSymlink != 0 {
2024-12-30 14:58:03 +04:00
if slp, err := filepath.EvalSymlinks(filepath.Join(abs, entry.Name())); err == nil {
lStat, _ := os.Lstat(slp)
isDirLink = lStat.IsDir()
}
}
if entry.IsDir() || isDirLink {
2022-06-27 04:38:09 +04:00
dirEntries = append(dirEntries, DirEntry{
2022-06-27 22:50:33 +04:00
Name: entry.Name(),
Link: url.PathEscape(entry.Name()) + "/",
Datetime: entry.ModTime(),
2022-06-27 04:38:09 +04:00
Size: "DIR",
})
stats.Directories++
} else {
2024-12-30 15:45:23 +04:00
sz, ui := convertFileSize(entry.Size())
2022-06-27 04:38:09 +04:00
fileEntries = append(fileEntries, DirEntry{
2022-06-27 22:50:33 +04:00
Name: entry.Name(),
2024-12-30 14:58:03 +04:00
Link: "/file" + rel + url.PathEscape(entry.Name()),
2022-06-27 22:50:33 +04:00
Datetime: entry.ModTime(),
2024-12-30 15:45:23 +04:00
Size: sz,
SizeUnit: ui,
2022-06-27 04:38:09 +04:00
})
2022-06-27 22:50:33 +04:00
totalFilesSize += entry.Size()
2022-06-27 04:38:09 +04:00
stats.Files++
}
}
2024-12-30 15:45:23 +04:00
stats.FilesSize, stats.FilesSizeUnit = convertFileSize(totalFilesSize)
2022-06-27 04:38:09 +04:00
entries = append(entries, dirEntries...)
entries = append(entries, fileEntries...)
return
}