forked from pki-io/admin
/
helpers.go
126 lines (111 loc) · 2.26 KB
/
helpers.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
// ThreatSpec package main
package main
import (
"archive/tar"
"bytes"
"compress/gzip"
"encoding/hex"
"fmt"
"github.com/pki-io/core/crypto"
"io/ioutil"
"os"
"strconv"
"strings"
"time"
)
func NewID() string {
idBytes, _ := crypto.RandomBytes(16)
return hex.EncodeToString(idBytes)
}
func ParseTags(tagString string) []string {
tags := strings.Split(tagString, ",")
for i, e := range tags {
tags[i] = strings.TrimSpace(strings.ToLower(e))
}
return tags
}
func ArgInt(arg interface{}, def interface{}) int {
switch t := arg.(type) {
case string:
argInt, err := strconv.ParseInt(arg.(string), 10, 64)
fmt.Println(err)
return int(argInt)
case nil:
return def.(int)
case bool:
return def.(int)
default:
// Never gets to the next line
fmt.Println(t)
return 0
}
}
func ArgString(arg interface{}, def interface{}) string {
switch t := arg.(type) {
case string:
return arg.(string)
case nil:
return def.(string)
case bool:
return def.(string)
default:
// Never gets to the next line
fmt.Println(t)
return ""
}
}
func ArgBool(arg interface{}, def interface{}) bool {
switch t := arg.(type) {
case string:
return arg.(string) == "true"
case bool:
return arg.(bool)
default:
fmt.Println(t)
return false
}
}
type ExportFile struct {
Name string
Mode int64
Owner int64
Group int64
Content []byte
}
func TarGZ(files []ExportFile) ([]byte, error) {
tarBuffer := new(bytes.Buffer)
tarWriter := tar.NewWriter(tarBuffer)
for _, file := range files {
header := &tar.Header{
Name: file.Name,
Mode: int64(file.Mode),
Size: int64(len(file.Content)),
ModTime: time.Now(),
}
if err := tarWriter.WriteHeader(header); err != nil {
return nil, err
}
if _, err := tarWriter.Write(file.Content); err != nil {
return nil, err
}
}
if err := tarWriter.Close(); err != nil {
return nil, err
}
zipBuffer := new(bytes.Buffer)
zipWriter := gzip.NewWriter(zipBuffer)
zipWriter.Write(tarBuffer.Bytes())
zipWriter.Close()
return zipBuffer.Bytes(), nil
}
func Export(files []ExportFile, outFile string) {
tarGz, err := TarGZ(files)
fmt.Println(err)
if outFile == "-" {
os.Stdout.Write(tarGz)
} else {
// Write to file
err := ioutil.WriteFile(outFile, tarGz, 0600)
fmt.Println(err)
}
}