forked from bwplotka/mimic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfiles.go
64 lines (51 loc) · 1.68 KB
/
files.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
// Copyright (c) bwplotka/mimic Authors
// Licensed under the Apache License 2.0.
package mimic
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
)
// FilePool is a struct for storing and managing files to be generated as part of generation.
type FilePool struct {
Logger log.Logger
path []string
m map[string]string
}
// Add adds a file to the file pool at the current path. The file is identified by filename.
// Content of the file is passed via an io.Reader.
//
// If the file with the given name has already been added at this path the code will `panic`.
// NOTE: See mimic/encoding for different marshallers to use as io.Reader.
func (f *FilePool) Add(fileName string, r io.Reader) {
if filepath.Base(fileName) != fileName {
Panicf("")
}
b, err := ioutil.ReadAll(r)
if err != nil {
Panicf("failed to output: %s", err)
}
output := filepath.Join(append(f.path, fileName)...)
// Check whether we have already written something into this file.
if _, ok := f.m[output]; ok {
Panicf("filename clash: %s", output)
}
f.m[output] = string(b)
}
func (f *FilePool) write(outputDir string) {
for file, contents := range f.m {
out := filepath.Join(outputDir, file)
if err := os.MkdirAll(filepath.Dir(out), 0755); err != nil {
PanicErr(fmt.Errorf("create directory %s: %w", filepath.Dir(out), err))
}
// TODO(https://github.com/bwplotka/mimic/issues/11): Diff the things if something is already here and remove.
_ = level.Debug(f.Logger).Log("msg", "writing file", "file", out)
if err := ioutil.WriteFile(out, []byte(contents), 0755); err != nil {
PanicErr(fmt.Errorf("write file to %s: %w", out, err))
}
}
}