File: buffer.go

package info (click to toggle)
incus 6.0.5-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 25,788 kB
  • sloc: sh: 16,313; ansic: 3,121; python: 457; makefile: 337; ruby: 51; sql: 50; lisp: 6
file content (40 lines) | stat: -rw-r--r-- 741 bytes parent folder | download | duplicates (3)
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
package file

import (
	"bytes"
	"fmt"
	"go/format"
)

// Buffer for accumulating source code output.
type Buffer struct {
	buf *bytes.Buffer
}

// Create a new source code text buffer.
func newBuffer() *Buffer {
	return &Buffer{
		buf: bytes.NewBuffer(nil),
	}
}

// L accumulates a single line of source code.
func (b *Buffer) L(format string, a ...any) {
	fmt.Fprintf(b.buf, format, a...)
	b.N()
}

// N accumulates a single new line.
func (b *Buffer) N() {
	fmt.Fprint(b.buf, "\n")
}

// Returns the source code to add to the target file.
func (b *Buffer) code() ([]byte, error) {
	code, err := format.Source(b.buf.Bytes())
	if err != nil {
		return nil, fmt.Errorf("Can't format generated source code: %w", err)
	}

	return code, nil
}