/
testfile.go
104 lines (81 loc) · 2.04 KB
/
testfile.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package test
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"github.com/danielbaenabird/fyne/v2"
"github.com/danielbaenabird/fyne/v2/storage"
)
type file struct {
*os.File
path string
}
type directory struct {
fyne.URI
}
// Declare conformity to the ListableURI interface
var _ fyne.ListableURI = (*directory)(nil)
func (f *file) Open() (io.ReadCloser, error) {
return os.Open(f.path)
}
func (f *file) Save() (io.WriteCloser, error) {
return os.Open(f.path)
}
func (f *file) ReadOnly() bool {
return true
}
func (f *file) Name() string {
return filepath.Base(f.path)
}
func (f *file) URI() fyne.URI {
return storage.NewURI("file://" + f.path)
}
func openFile(uri fyne.URI, create bool) (*file, error) {
if uri.Scheme() != "file" {
return nil, fmt.Errorf("unsupported URL protocol")
}
path := uri.String()[7:]
f, err := os.Open(path)
if err != nil && create {
f, err = os.Create(path)
}
return &file{File: f, path: path}, err
}
func (d *testDriver) FileReaderForURI(uri fyne.URI) (fyne.URIReadCloser, error) {
return openFile(uri, false)
}
func (d *testDriver) FileWriterForURI(uri fyne.URI) (fyne.URIWriteCloser, error) {
return openFile(uri, true)
}
func (d *testDriver) ListerForURI(uri fyne.URI) (fyne.ListableURI, error) {
if uri.Scheme() != "file" {
return nil, fmt.Errorf("unsupported URL protocol")
}
path := uri.String()[len(uri.Scheme())+3 : len(uri.String())]
s, err := os.Stat(path)
if err != nil {
return nil, err
}
if !s.IsDir() {
return nil, fmt.Errorf("path '%s' is not a directory, cannot convert to listable URI", path)
}
return &directory{URI: uri}, nil
}
func (d *directory) List() ([]fyne.URI, error) {
if d.Scheme() != "file" {
return nil, fmt.Errorf("unsupported URL protocol")
}
path := d.String()[len(d.Scheme())+3 : len(d.String())]
files, err := ioutil.ReadDir(path)
if err != nil {
return nil, err
}
urilist := []fyne.URI{}
for _, f := range files {
uri := storage.NewURI("file://" + filepath.Join(path, f.Name()))
urilist = append(urilist, uri)
}
return urilist, nil
}