-
Notifications
You must be signed in to change notification settings - Fork 9
/
src.go
61 lines (49 loc) · 1.8 KB
/
src.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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package golang
import (
"bytes"
"context"
"fmt"
"go/format"
"io"
"path/filepath"
"text/template"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/fnfs"
"namespacelabs.dev/foundation/internal/gosupport"
)
func generateGoSource(ctx context.Context, fsfs fnfs.ReadWriteFS, filePath string, imports *gosupport.GoImports, t *template.Template, data interface{}) error {
return fnfs.WriteWorkspaceFile(ctx, console.Stdout(ctx), fsfs, filePath, func(w io.Writer) error {
var body bytes.Buffer
if err := t.Execute(&body, data); err != nil {
return fnerrors.InternalError("failed to apply template: %w", err)
}
var src bytes.Buffer
fmt.Fprintln(&src, "// This file was automatically generated by Namespace.")
fmt.Fprintln(&src, "// DO NOT EDIT. To update, re-run `ns generate`.")
if imports != nil {
fmt.Fprintf(&src, "\npackage %s\n\n", filepath.Base(imports.PkgName))
if imports := imports.ImportMap(); len(imports) > 0 {
fmt.Fprintf(&src, "import (\n")
for _, imp := range imports {
fmt.Fprintf(&src, "%s %q\n", imp.Rename, imp.TypeURL)
}
fmt.Fprintf(&src, ")\n\n")
}
}
if _, err := body.WriteTo(&src); err != nil {
return err
}
formatted, err := format.Source(src.Bytes())
if err != nil {
fmt.Fprintln(console.Debug(ctx), "The input sources were:")
fmt.Fprintln(console.Debug(ctx), src.String())
return fnerrors.InternalError("failed to format generated Go file %s\nwith code:\n%s\nerr: %w", filePath, src.String(), err)
}
_, err = w.Write(formatted)
return err
})
}