aboutsummaryrefslogtreecommitdiff
path: root/storage/storage_fs.go
blob: 16bf8e82150fae603d9431d74610e5ac37475284 (plain)
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package storage

import (
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"porg/pipe"
)

type FileSystem struct {
}

func NewFileSystem() *FileSystem {
	return &FileSystem{}
}

func (fs *FileSystem) Get(path string) (io.Reader, error) {
	return os.Open(path)
}

func (fs *FileSystem) Walk(folder string, walkMode WalkMode) <-chan string {
	c := make(chan string)

	go func(folder string, c chan string) {
		filepath.Walk(folder, func(path string, info os.FileInfo, err error) error {
			file, _ := os.Open(path)
			defer file.Close()
			fileInfo, err := file.Stat()
			if err != nil {
				fmt.Println("@@@@ ", err.Error())
				return nil
			}

			switch walkMode {
			case Folder:
				if fileInfo.IsDir() {
					c <- path
				}
			case File:
				if !fileInfo.IsDir() {
					c <- path
				}
			case FileFolder:
				c <- path
			}
			return nil
		})
		close(c)

	}(folder, c)

	return c
}

func (fs *FileSystem) Put(path string, f io.Reader) error {
	fo, err := os.Create(path)
	if err != nil {
		return err
	}

	if _, err := io.Copy(fo, f); err != nil {
		return err
	}

	return nil
}

func (fs *FileSystem) List(path string) ([]string, error) {
	files, err := ioutil.ReadDir(path)
	if err != err {
		return nil, err
	}

	findPath := func(f os.FileInfo) string {
		return path + "/" + f.Name()
	}
	return pipe.Map(findPath, files), nil
}

func (fs *FileSystem) Move(src string, dst string) error {
	return os.Rename(src, dst)
}

func (fs *FileSystem) Copy(src string, dst string) error {
	in, err := os.Open(src)
	if err != nil {
		return err
	}
	defer in.Close()

	out, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer out.Close()

	_, err = io.Copy(out, in)
	if err != nil {
		return err
	}
	return out.Close()
}

func (fs *FileSystem) Exists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if errors.Is(err, os.ErrNotExist) {
		return false, nil
	}
	return false, err
}

func (fs *FileSystem) Mkdir(path string) error {
	return os.MkdirAll(path, 0777)
}