pkger/pkging/stdos/file.go

107 lines
1.7 KiB
Go
Raw Normal View History

2019-09-03 18:29:28 +03:00
package stdos
2019-09-01 00:00:24 +03:00
import (
"net/http"
"os"
2019-09-05 19:22:35 +03:00
"path"
2019-09-01 00:00:24 +03:00
"github.com/markbates/pkger/here"
2019-09-02 01:02:45 +03:00
"github.com/markbates/pkger/pkging"
2019-09-01 00:00:24 +03:00
)
2019-09-02 01:02:45 +03:00
var _ pkging.File = &File{}
2019-09-01 00:00:24 +03:00
type File struct {
*os.File
2019-09-02 01:02:45 +03:00
info *pkging.FileInfo
her here.Info
path pkging.Path
2019-09-03 18:29:28 +03:00
pkging pkging.Pkger
2019-09-01 00:00:24 +03:00
}
2019-09-03 18:29:28 +03:00
func NewFile(fx pkging.Pkger, osf *os.File) (*File, error) {
2019-09-20 17:56:26 +03:00
name := osf.Name()
pt, err := fx.Parse(name)
2019-09-01 00:00:24 +03:00
if err != nil {
return nil, err
}
2019-09-01 04:13:35 +03:00
info, err := osf.Stat()
2019-09-01 00:00:24 +03:00
if err != nil {
return nil, err
}
f := &File{
2019-09-02 01:02:45 +03:00
File: osf,
path: pt,
pkging: fx,
2019-09-01 00:00:24 +03:00
}
2019-09-02 01:02:45 +03:00
f.info = pkging.WithName(pt.Name, info)
2019-09-01 00:00:24 +03:00
her, err := here.Package(pt.Pkg)
if err != nil {
return nil, err
}
f.her = her
return f, nil
}
func (f *File) Close() error {
return f.File.Close()
}
2019-09-01 23:18:39 +03:00
func (f *File) Abs() (string, error) {
2019-09-02 01:02:45 +03:00
return f.pkging.AbsPath(f.path)
2019-09-01 00:00:24 +03:00
}
func (f *File) Info() here.Info {
return f.her
}
func (f *File) Name() string {
return f.info.Name()
}
2019-09-05 19:22:35 +03:00
type HTTP struct {
pkging.File
osf *os.File
}
func (f *HTTP) Readdir(count int) ([]os.FileInfo, error) {
osinfos, err := f.osf.Readdir(count)
if err != nil {
return nil, err
}
infos := make([]os.FileInfo, len(osinfos))
for i, info := range osinfos {
infos[i] = pkging.WithName(info.Name(), info)
}
return infos, err
}
2019-09-01 00:00:24 +03:00
func (f *File) Open(name string) (http.File, error) {
2019-09-05 19:22:35 +03:00
fp := path.Join(f.Path().Name, name)
f2, err := f.pkging.Open(fp)
if err != nil {
return nil, err
}
return &HTTP{File: f2, osf: f.File}, nil
2019-09-01 00:00:24 +03:00
}
2019-09-02 01:02:45 +03:00
func (f *File) Path() pkging.Path {
2019-09-01 00:00:24 +03:00
return f.path
}
func (f *File) Stat() (os.FileInfo, error) {
2019-09-01 23:18:39 +03:00
if f.info != nil {
return f.info, nil
}
2019-09-20 17:56:26 +03:00
nf, err := NewFile(f.pkging, f.File)
2019-09-01 23:18:39 +03:00
if err != nil {
return nil, err
2019-09-01 00:00:24 +03:00
}
2019-09-20 17:56:26 +03:00
(*f) = *nf
return f.info, nil
2019-09-01 00:00:24 +03:00
}