/
writer.go
69 lines (59 loc) · 2.3 KB
/
writer.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
// Copyright 2016-2018, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tfgen
import (
"bufio"
"fmt"
"io"
"os"
"github.com/pulumi/pulumi/sdk/v2/go/common/util/contract"
"github.com/spf13/afero"
)
// genWriter adds some convenient helpers atop a buffered writer.
type genWriter struct {
tool string // the name of the code-generator.
f io.Closer // the file being written to.
w io.Writer
}
func newGenWriter(tool string, fs afero.Fs, file string) (*genWriter, error) {
f, err := fs.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return nil, err
}
return &genWriter{tool: tool, f: f, w: bufio.NewWriter(f)}, nil
}
// Close flushes and closes the underlying writer.
func (g *genWriter) Close() error {
return g.f.Close()
}
// WriteString writes the provided string to the underlying buffer _without_ formatting it.
func (g *genWriter) WriteString(msg string) {
_, err := g.w.Write([]byte(msg))
contract.IgnoreError(err)
}
// Writefmt wraps the bufio.Writer.WriteString function, but also performs fmt.Sprintf-style formatting.
func (g *genWriter) Writefmt(msg string, args ...interface{}) {
_, err := fmt.Fprintf(g.w, msg, args...)
contract.IgnoreError(err)
}
// Writefmtln wraps the bufio.Writer.WriteString function, performing fmt.Sprintf-style formatting and appending \n.
func (g *genWriter) Writefmtln(msg string, args ...interface{}) {
g.Writefmt(msg+"\n", args...)
}
// EmitHeaderWarning emits the standard "WARNING" into a generated file, prefixed by commentChars.
func (g *genWriter) EmitHeaderWarning(commentChars string) {
g.Writefmtln("%s *** WARNING: this file was generated by %v. ***", commentChars, g.tool)
g.Writefmtln("%s *** Do not edit by hand unless you're certain you know what you are doing! ***", commentChars)
g.Writefmtln("")
}