-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEmbeddedSource.go
More file actions
85 lines (81 loc) · 2.2 KB
/
EmbeddedSource.go
File metadata and controls
85 lines (81 loc) · 2.2 KB
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 EmbeddedSource
import (
"crypto/sha512"
"embed"
"encoding/hex"
"io/fs"
"os"
"path/filepath"
)
type EmbeddedSource struct {
Fs embed.FS
cachedlistfiles []string
}
func (es *EmbeddedSource) FilesList() (filenames []string, err error) {
if len(es.cachedlistfiles) > 0 {
// es.cachedlistfiles is already defined from a previous function-call
filenames = es.cachedlistfiles
return filenames, err
}
walk_err := fs.WalkDir(es.Fs, ".", func(a_file_path string, a_file_info fs.DirEntry, parent_err error) error {
if parent_err != nil {
return parent_err
}
// skip any directories entries, we just want to add files
if a_file_info.IsDir() {
return nil
}
filenames = append(filenames, a_file_path)
return nil
})
if walk_err != nil {
filenames = []string{}
err = walk_err
return filenames, err
}
// save filenames into es.cachedlistfiles to optimize future function-calls
es.cachedlistfiles = filenames
return filenames, err
}
func (es *EmbeddedSource) FileSha512(filename string) (sha512_as_hex string, err error) {
file_contents, err := es.Fs.ReadFile(filename)
if err != nil {
sha512_as_hex = ""
return sha512_as_hex, err
}
hasher := sha512.New()
hasher.Write(file_contents)
sha512_as_hex = hex.EncodeToString(hasher.Sum(nil))
return sha512_as_hex, err
}
func (es *EmbeddedSource) FileRead(filename string) (file_contents []byte, err error) {
file_contents, err = es.Fs.ReadFile(filename)
return file_contents, err
}
func (es *EmbeddedSource) FilesExtract(destination_dir string) (err error) {
// create destination_dir
if err := os.MkdirAll(destination_dir, 0777); err != nil {
return err
}
// create files inside destination_dir
filenames, err := es.FilesList()
if err != nil {
return err
}
for _, a_filename := range filenames {
a_dest_filepath := filepath.Join(destination_dir, a_filename)
a_file_content, err := es.FileRead(a_filename)
if err != nil {
return err
}
err = os.WriteFile(a_dest_filepath, a_file_content, 0644)
if err != nil {
return err
}
}
return err // err is nil
}
func (es *EmbeddedSource) FileInfo(filename string) (fileInfo fs.FileInfo, err error) {
fileInfo, err = fs.Stat(es.Fs, filename)
return fileInfo, err
}