-
Notifications
You must be signed in to change notification settings - Fork 7
/
utils.go
85 lines (67 loc) · 1.78 KB
/
utils.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
package main
import (
"archive/tar"
"encoding/json"
"io"
"io/ioutil"
"os"
"path/filepath"
"github.com/rs/zerolog/log"
)
/*
UnTar takes a destination path and a reader; a tar reader loops over the tarfile
creating the file structure at 'dst' along the way, and writing any files
*/
func UnTar(dst string, r io.Reader) error {
tr := tar.NewReader(r)
for {
header, err := tr.Next()
switch {
// if no more files are found return
case err == io.EOF:
return nil
// return any other error
case err != nil:
return err
// if the header is nil, just skip it (not sure how this happens)
case header == nil:
continue
}
// the target location where the dir/file should be created
target := filepath.Join(dst, header.Name)
// the following switch could also be done using fi.Mode(), not sure if there
// a benefit of using one vs. the other.
// fi := header.FileInfo()
// check the file type
switch header.Typeflag {
// if its a dir and it doesn't exist create it
case tar.TypeDir:
if _, err := os.Stat(target); err != nil {
if err := os.MkdirAll(target, 0755); err != nil {
return err
}
}
// if it's a file create it
case tar.TypeReg:
f, err := os.OpenFile(target, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode))
if err != nil {
return err
}
// copy over contents
if _, err := io.Copy(f, tr); err != nil {
return err
}
// manually close here after each file operation; defering would cause each file close
// to wait until all operations have completed.
f.Close()
}
}
}
// ToJSON as name says
func ToJSON(files []*FileInfo, output string) {
rankingsJSON, _ := json.MarshalIndent(files, "", " ")
err := ioutil.WriteFile(output, rankingsJSON, 0644)
if err != nil {
log.Error().Msgf("%v", err)
}
}