-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathio.go
136 lines (115 loc) · 2.43 KB
/
io.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
136
package gryphon
import (
"archive/zip"
"fmt"
"io"
"io/ioutil"
"os"
"strings"
)
// ReadFile is used to read a given file and return its data as a string.
func ReadFile(filename string) (string, error) {
f, err := os.Open(filename)
if err != nil {
return "", err
}
defer f.Close()
b, err := ioutil.ReadAll(f)
if err != nil {
return "", err
}
return string(b), nil
}
// WriteFile is used to write data into a given file.
func WriteFile(filename, data string) error {
file, err := os.Create(filename)
if err != nil {
return err
}
defer file.Close()
_, err = io.WriteString(file, data)
if err != nil {
return err
}
return nil
}
// FilesPattern is used to return data mapped to files
// where their filenames match a given pattern.
func FilesPattern(directory, pattern string) (map[string]string, error) {
out_map := map[string]string{}
files, err := os.ReadDir(directory)
if err != nil {
return nil, err
}
for _, f := range files {
fl, err := ReadFile(f.Name())
if err != nil {
return nil, err
}
if strings.Contains(fl, pattern) {
out_map[f.Name()], err = ReadFile(f.Name())
if err != nil {
return nil, err
}
}
}
return out_map, nil
}
// CopyFile copies a file from one directory to another.
func CopyFile(src, dst string) error {
sourceFileStat, err := os.Stat(src)
if err != nil {
return err
}
if !sourceFileStat.Mode().IsRegular() {
return fmt.Errorf("%s is not a regular file", src)
}
source, err := os.Open(src)
if err != nil {
return err
}
defer source.Close()
destination, err := os.Create(dst)
if err != nil {
return err
}
defer destination.Close()
_, err = io.Copy(destination, source)
return err
}
// MakeZip packs a list of given files within a zip archive.
func MakeZip(zip_file string, files []string) error {
newZipFile, err := os.Create(zip_file)
if err != nil {
return err
}
defer newZipFile.Close()
zipWriter := zip.NewWriter(newZipFile)
defer zipWriter.Close()
for _, file := range files {
fileToZip, err := os.Open(file)
if err != nil {
return err
}
defer fileToZip.Close()
info, err := fileToZip.Stat()
if err != nil {
return err
}
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
header.Name = file
header.Method = zip.Deflate
writer, err := zipWriter.CreateHeader(header)
if err != nil {
return err
}
_, err = io.Copy(writer, fileToZip)
if err != nil {
return err
}
}
return nil
}