-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathdata.go
127 lines (106 loc) · 2.4 KB
/
data.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
// Copyright 2017 Debpkg authors. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package debpkg
import (
"bytes"
"crypto/md5"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/xor-gate/debpkg/internal/targzip"
)
type data struct {
md5sums string
tgz *targzip.TarGzip
dirs []string
}
func (d *data) addDirectory(dirpath string) error {
dirpath = filepath.Clean(dirpath)
if os.PathSeparator != '/' {
dirpath = strings.Replace(dirpath, string(os.PathSeparator), "/", -1)
}
d.addParentDirectories(dirpath)
for _, addedDir := range d.dirs {
if addedDir == dirpath {
return nil
}
}
if dirpath == "." {
return nil
}
if err := d.tgz.AddDirectory(dirpath); err != nil {
return err
}
d.dirs = append(d.dirs, dirpath)
return nil
}
func (d *data) addParentDirectories(filename string) {
dirname := filepath.Dir(filename)
if dirname == "." {
return
}
if os.PathSeparator != '/' {
dirname = strings.Replace(dirname, string(os.PathSeparator), "/", -1)
}
dirs := strings.Split(dirname, "/")
current := "/"
for _, dir := range dirs {
if len(dir) > 0 {
current += dir + "/"
d.addDirectory(current)
}
}
}
func (d *data) addToMD5sums(md5 []byte, dest string) {
dest = strings.TrimPrefix(dest, "/")
d.md5sums += fmt.Sprintf("%x %s\n", md5, dest)
}
func (d *data) addFileString(contents, dest string) error {
d.addParentDirectories(dest)
if err := d.tgz.AddFileFromBuffer(dest, []byte(contents), 0); err != nil {
return err
}
md5, err := computeMd5(bytes.NewBufferString(contents))
if err != nil {
return err
}
d.addToMD5sums(md5, dest)
return nil
}
func (d *data) addFile(filename string, dest ...string) error {
var destfilename string
if len(dest) > 0 && len(dest[0]) > 0 {
destfilename = dest[0]
} else {
destfilename = filename
}
d.addParentDirectories(destfilename)
//
if err := d.tgz.AddFile(filename, dest...); err != nil {
return err
}
fd, err := os.Open(filename)
if err != nil {
return err
}
md5, err := computeMd5(fd)
if err != nil {
fd.Close()
return err
}
d.addToMD5sums(md5, destfilename)
fd.Close()
return nil
}
// computeMd5 from the os filedescriptor
func computeMd5(fd io.Reader) (data []byte, err error) {
var result []byte
hash := md5.New()
if _, err := io.Copy(hash, fd); err != nil {
return result, err
}
return hash.Sum(result), nil
}