aboutsummaryrefslogtreecommitdiff
path: root/fileop/fileop.go
blob: 1be3f2ecd966bf476256a4e58da7dd66c18eed4b (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
package fileop

import (
	"crypto/sha256"
	"fmt"
	"io"
	"os"
	"path/filepath"
)

type WalkMode int

const (
	Folder WalkMode = iota
	File
	FileFolder
)

func WalkFolder(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, _ := file.Stat()

			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 CalculateSHA256(r io.Reader) (string, error) {
	h := sha256.New()
	if _, err := io.Copy(h, r); err != nil {
		return "", err
	}

	shaString := fmt.Sprintf("%x", h.Sum(nil))

	return shaString, nil
}

type MoveCommand struct {
	Source      string
	Destination string
}

func Move() chan<- *MoveCommand {
	c := make(chan *MoveCommand)
	go func(chan *MoveCommand) {
		for cmd := range c {
			// TODO: add error handling
			err := os.Rename(cmd.Source, cmd.Destination)
			if err != nil {
				fmt.Println(err.Error())
			}
		}
	}(c)

	return c
}

func IsEmpty(name string) (bool, error) {
	f, err := os.Open(name)
	if err != nil {
		return false, err
	}
	defer f.Close()

	_, err = f.Readdirnames(1)
	if err == io.EOF {
		return true, nil
	}
	return false, err
}