-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathfile.go
64 lines (53 loc) · 1.46 KB
/
file.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
package golang
import (
"fmt"
"strings"
"projectforge.dev/projectforge/app/file"
"projectforge.dev/projectforge/app/lib/filesystem"
"projectforge.dev/projectforge/app/util"
)
type File struct {
Package string `json:"package,omitempty"`
Path []string `json:"path,omitempty"`
Name string `json:"name"`
Imports Imports `json:"imports"`
Blocks Blocks `json:"blocks"`
}
func NewFile(pkg string, path []string, fn string) *File {
return &File{Package: pkg, Path: path, Name: fn}
}
func (f *File) AddImport(i ...*Import) {
f.Imports = f.Imports.Add(i...)
}
func (f *File) AddBlocks(b ...*Block) {
f.Blocks = append(f.Blocks, b...)
}
func (f *File) Render(addHeader bool, linebreak string) (*file.File, error) {
var content []string
add := func(s string, args ...any) {
content = append(content, fmt.Sprintf(s+linebreak, args...))
}
if addHeader {
if f.Package == "" {
content = append(content, fmt.Sprintf("// %s", file.HeaderContent))
} else {
content = append(content, fmt.Sprintf("// Package %s - %s", f.Package, file.HeaderContent))
}
}
add("package %s", f.Package)
if len(f.Imports) > 0 {
add(f.Imports.Render(linebreak))
}
for _, b := range f.Blocks {
x, err := b.Render(linebreak)
if err != nil {
return nil, err
}
add(x)
}
n := f.Name
if !strings.HasSuffix(f.Name, util.ExtGo) {
n += util.ExtGo
}
return &file.File{Path: f.Path, Name: n, Mode: filesystem.DefaultMode, Content: strings.Join(content, linebreak)}, nil
}