Documentation
¶
Index ¶
- type CodeBuilder
- func (w *CodeBuilder) Append(s string)
- func (w *CodeBuilder) FmtString() (string, error)
- func (w *CodeBuilder) Linef(format string, args ...any)
- func (w *CodeBuilder) Reset()
- func (w *CodeBuilder) SaveToFile(outFile string) (fmtErr error, err error)
- func (w *CodeBuilder) String() string
- func (w *CodeBuilder) Write(s string)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type CodeBuilder ¶
type CodeBuilder struct { // Indent is the indentation level (indentation is tabs). Indent int // contains filtered or unexported fields }
CodeBuilder is a wrapper around strings.Builder that simplifies building Go code.
The zero value is safely ready to use.
Example ¶
package main import ( "fmt" "github.com/refaktor/ryegen/binder/binderio" ) func main() { var cb binderio.CodeBuilder cb.Linef(`package main`) cb.Linef(``) cb.Linef(`import "fmt"`) cb.Linef(``) cb.Linef(`type FmtTest struct {`) cb.Indent++ cb.Linef(`A int`) cb.Linef(`BVeryLongName int`) cb.Linef(`CEvenMuchLongerNameThanB int`) cb.Indent-- cb.Linef(`}`) cb.Linef(``) cb.Linef(`func main() {`) cb.Indent++ for i := 0; i < 10; i++ { cb.Linef(`fmt.Println("Hello %v")`, i) } cb.Indent-- cb.Linef(`}`) code, err := cb.FmtString() if err != nil { panic(err) } fmt.Println(code) }
Output: package main import "fmt" type FmtTest struct { A int BVeryLongName int CEvenMuchLongerNameThanB int } func main() { fmt.Println("Hello 0") fmt.Println("Hello 1") fmt.Println("Hello 2") fmt.Println("Hello 3") fmt.Println("Hello 4") fmt.Println("Hello 5") fmt.Println("Hello 6") fmt.Println("Hello 7") fmt.Println("Hello 8") fmt.Println("Hello 9") }
func (*CodeBuilder) Append ¶
func (w *CodeBuilder) Append(s string)
Append writes the given string line by line with correct indentation.
func (*CodeBuilder) FmtString ¶
func (w *CodeBuilder) FmtString() (string, error)
FmtString attempts to format the current code as Go source code.
func (*CodeBuilder) Linef ¶
func (w *CodeBuilder) Linef(format string, args ...any)
Linef writes a single line, prepended by the current indentation.
Takes format and args like fmt.Printf.
func (*CodeBuilder) Reset ¶
func (w *CodeBuilder) Reset()
func (*CodeBuilder) SaveToFile ¶
func (w *CodeBuilder) SaveToFile(outFile string) (fmtErr error, err error)
SaveToFile attempts to format the current code as Go source code and write it to outFile.
If a formatting error occurs, it is returned in fmtErr and the function attempts to write the unformatted code instead. If a file IO error occurs, it is returned in err.
func (*CodeBuilder) String ¶
func (w *CodeBuilder) String() string
String returns the current code without applying any formatting.
func (*CodeBuilder) Write ¶
func (w *CodeBuilder) Write(s string)
Write appends a raw string to the internal strings.Builder.