Skip to content

Commit 1e770b3

Browse files
committed
Fix: Go scaffolding uses correct module name (knative#2769)
* Fix: Go scaffolding uses correct module name Using incorrect name works for a functions with flat structure -- no sub-packages. When sub-packages are used we need to refer the user module by its true name. Signed-off-by: Matej Vašek <[email protected]> * fixup tests Signed-off-by: Matej Vašek <[email protected]> --------- Signed-off-by: Matej Vašek <[email protected]>
1 parent 630d9cd commit 1e770b3

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

pkg/scaffolding/scaffold.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
package scaffolding
22

33
import (
4+
"bytes"
45
"fmt"
56
"os"
67
"path/filepath"
8+
"regexp"
79

810
"knative.dev/func/pkg/filesystem"
911
)
@@ -48,6 +50,33 @@ func Write(out, src, runtime, invoke string, fs filesystem.Filesystem) (err erro
4850
return ScaffoldingError{"filesystem copy failed", err}
4951
}
5052

53+
// Not my proudest moment
54+
if runtime == "go" {
55+
var data []byte
56+
data, err = os.ReadFile(filepath.Join(src, "go.mod"))
57+
if err != nil {
58+
return fmt.Errorf("cannot read go.mod: %w", err)
59+
}
60+
r := regexp.MustCompile(`module\s+(\w+)`)
61+
matches := r.FindSubmatch(data)
62+
if len(matches) != 2 {
63+
return fmt.Errorf("cannot parse go.mod")
64+
}
65+
moduleName := string(matches[1])
66+
for _, n := range []string{"go.mod", "main.go"} {
67+
p := filepath.Join(out, n)
68+
data, err = os.ReadFile(p)
69+
if err != nil {
70+
return fmt.Errorf("cannot read scaffolding file: %w", err)
71+
}
72+
data = bytes.ReplaceAll(data, []byte("function"), []byte(moduleName))
73+
err = os.WriteFile(p, data, 0644)
74+
if err != nil {
75+
return fmt.Errorf("cannot patch scaffolding code: %w", err)
76+
}
77+
}
78+
}
79+
5180
// Copy the certs from the filesystem to the build directory
5281
if _, err := fs.Stat("certs"); err != nil {
5382
return ScaffoldingError{"certs directory not found in filesystem", err}

pkg/scaffolding/scaffold_test.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,11 @@ func New() *F { return nil }
8282
t.Fatal(err)
8383
}
8484

85+
err = os.WriteFile(filepath.Join(root, "go.mod"), []byte("module foo"), 0644)
86+
if err != nil {
87+
t.Fatal(err)
88+
}
89+
8590
// The output destination for the scaffolding
8691
out := filepath.Join(root, "out")
8792

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module s
2+
3+
go 1.22

0 commit comments

Comments
 (0)