-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.go
135 lines (111 loc) · 2.39 KB
/
file.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package main
import (
"bufio"
"crypto/md5"
"fmt"
"io"
"log"
"os"
"path"
"strings"
"github.com/modcloth/go-fileutils"
)
type File interface {
GetMd5() ([]byte, error)
GetDestination() (string, error)
GetFileName() string
IsCached(string) (bool, int)
AddToCache(string, int)
IncDup()
IncFail()
IncSuccess()
getDestpath() string
}
type FileObj struct {
destpath string
filename string
cache *Cache
}
func (f *FileObj) getDestpath() string {
return f.destpath
}
func (f *FileObj) IncDup() {
f.cache.duplicate++
}
func (f *FileObj) IncFail() {
f.cache.failure++
}
func (f *FileObj) IncSuccess() {
f.cache.success++
}
func (f *FileObj) IsCached(s string) (bool, int) {
return f.cache.IsCached(s)
}
func (f *FileObj) AddToCache(s string, index int) {
f.cache.Insert(s, index)
}
func (f *FileObj) GetFileName() string {
return f.filename
}
func (f *FileObj) GetMd5() (hash []byte, err error) {
fp, err := os.Open(f.filename)
if err != nil {
log.Printf("Error while attempting to open %s: %s\n", f.filename, err)
return
}
defer fp.Close()
reader := bufio.NewReader(fp)
// Calculate the MD5 using buffered IO
hasher := md5.New()
_, err = io.Copy(hasher, reader)
if err != nil {
return []byte{}, err
}
return hasher.Sum(nil), nil
}
func (f *FileObj) GetDestination() (string, error) {
return f.destpath, nil
}
func CheckDir(f File, directory string) error {
found, index := f.IsCached(directory)
if !found {
debug.Printf("Directory not in cache: %s", directory)
err := os.MkdirAll(directory, 0755)
if err != nil {
return err
}
f.AddToCache(directory, index)
}
return nil
}
func CopyFile(f File) error {
destdir, err := f.GetDestination()
if err != nil {
return err
}
// Verify our directory exists
if err := CheckDir(f, destdir); err != nil {
return err
}
// Reuse the filename extension
extention := path.Ext(f.GetFileName())
hash, err := f.GetMd5()
if err != nil {
return err
}
name := fmt.Sprintf("%X%s", hash, strings.ToLower(extention))
destination := path.Join(destdir, name)
// Only copy of the file does not already exist
if _, err := os.Stat(destination); os.IsNotExist(err) {
log.Printf("Copying file to: %s", destination)
if err = fileutils.Cp(f.GetFileName(), destination); err != nil {
f.IncFail()
return err
}
f.IncSuccess()
} else {
f.IncDup()
debug.Printf("File %s already exists\n", destination)
}
return nil
}