Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
134 changes: 111 additions & 23 deletions commands/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,18 +167,36 @@ func buildCodeOnlyArchive(dir string, ff *common.FuncFileV20180708, shape string
if err := validateCodeOnlyBuildTooling(dir, ff); err != nil {
return "", err
}
if err := buildCodeOnlyProject(dir, ff, shape); err != nil {
return "", err
}
archivePath := filepath.Join(dir, fmt.Sprintf("%s.%s.zip", ff.Name, ff.Version))
if err := createCodeOnlyZipArchive(dir, archivePath, ff, shape); err != nil {
return "", err
}
return archivePath, nil
}

func buildCodeOnlyProject(dir string, ff *common.FuncFileV20180708, shape string) error {
baseRuntime := detectCodeOnlyBaseRuntime(dir, ff)
switch {
case strings.HasPrefix(baseRuntime, "java"):
return buildJavaCodeOnlyProject(dir, ff)
case strings.HasPrefix(baseRuntime, "python"):
return buildPythonCodeOnlyProject(dir, ff)
case strings.HasPrefix(baseRuntime, "node"):
return buildNodeCodeOnlyProject(dir, ff)
case strings.HasPrefix(baseRuntime, "go"):
return buildGoCodeOnlyProject(dir, shape)
}
return nil
}

func validateCodeOnlyBuildTooling(dir string, ff *common.FuncFileV20180708) error {
baseRuntime := detectCodeOnlyBaseRuntime(dir, ff)
switch {
case strings.HasPrefix(baseRuntime, "java"):
if _, err := exec.LookPath("mvn"); err != nil {
if _, err := findFirstTool("mvn"); err != nil {
return fmt.Errorf("%s runtime selected, but Maven was not found in PATH. Install Maven and rerun `fn build`, or choose a different runtime", buildRuntimeDisplayName(baseRuntime))
}
case strings.HasPrefix(baseRuntime, "python"):
Expand All @@ -197,6 +215,78 @@ func validateCodeOnlyBuildTooling(dir string, ff *common.FuncFileV20180708) erro
return nil
}

func buildJavaCodeOnlyProject(dir string, ff *common.FuncFileV20180708) error {
baseRuntime := detectCodeOnlyBaseRuntime(dir, ff)
if !strings.HasPrefix(baseRuntime, "java") {
return nil
}

mvnBin, err := findFirstTool("mvn")
if err != nil {
return fmt.Errorf("%s runtime selected, but Maven was not found in PATH. Install Maven and rerun `fn build`, or choose a different runtime", buildRuntimeDisplayName(baseRuntime))
}
cmd := exec.Command(mvnBin, "package")
cmd.Dir = dir
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("java code-only build failed while running `mvn package`: %w", err)
}
return nil
}

func buildPythonCodeOnlyProject(dir string, ff *common.FuncFileV20180708) error {
baseRuntime := detectCodeOnlyBaseRuntime(dir, ff)
if !strings.HasPrefix(baseRuntime, "python") {
return nil
}

pythonBin, err := findFirstTool("python3", "python")
if err != nil {
return fmt.Errorf("Python runtime selected, but Python was not found in PATH. Install Python and rerun `fn build`, or choose a different runtime")
}
targetDir := filepath.Join(dir, "python")
if common.Exists(filepath.Join(dir, "requirements.txt")) {
cmd := exec.Command(pythonBin, "-m", "pip", "install", "--target", targetDir, "--no-cache-dir", "-r", "requirements.txt")
cmd.Dir = dir
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("python code-only build failed while installing requirements: %w", err)
}
}
if common.Exists(filepath.Join(dir, "setup.py")) {
cmd := exec.Command(pythonBin, "-m", "pip", "install", "--target", targetDir, "--no-cache-dir", ".")
cmd.Dir = dir
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("python code-only build failed while installing the local package: %w", err)
}
}
return nil
}

func buildNodeCodeOnlyProject(dir string, ff *common.FuncFileV20180708) error {
baseRuntime := detectCodeOnlyBaseRuntime(dir, ff)
if !strings.HasPrefix(baseRuntime, "node") || !common.Exists(filepath.Join(dir, "package.json")) || common.Exists(filepath.Join(dir, "node_modules")) {
return nil
}

npmBin, err := findFirstTool("npm")
if err != nil {
return fmt.Errorf("node.js code-only build requires npm to install @fnproject/fdk dependencies")
}
cmd := exec.Command(npmBin, "install", "--omit=dev")
cmd.Dir = dir
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("node.js code-only build failed while running `npm install --omit=dev`: %w", err)
}
return nil
}

func createCodeOnlyZipArchive(dir, archivePath string, ff *common.FuncFileV20180708, shape string) error {
archiveFile, err := os.CreateTemp(dir, "."+filepath.Base(archivePath)+"-*")
if err != nil {
Expand Down Expand Up @@ -325,19 +415,6 @@ func addNodeCodeOnlyArchiveContents(zipWriter *zip.Writer, dir string, ff *commo
}
packageJSON := filepath.Join(dir, "package.json")
nodeModulesDir := filepath.Join(dir, "node_modules")
if common.Exists(packageJSON) && !common.Exists(nodeModulesDir) {
npmBin, err := findFirstTool("npm")
if err != nil {
return fmt.Errorf("node.js code-only build requires npm to install @fnproject/fdk dependencies")
}
npmInstall := exec.Command(npmBin, "install", "--omit=dev")
npmInstall.Dir = dir
npmInstall.Stdout = os.Stdout
npmInstall.Stderr = os.Stderr
if err := npmInstall.Run(); err != nil {
return err
}
}
if err := addDirectoryToZip(zipWriter, functionDir, "function"); err != nil {
return err
}
Expand Down Expand Up @@ -571,9 +648,6 @@ func addGoCodeOnlyArchiveContents(zipWriter *zip.Writer, dir string, ff *common.
architectures := codeOnlyGoTargetArchitectures(shape)
if len(architectures) == 1 {
binaryPath := filepath.Join(dir, "func")
if err := buildGoCodeOnlyBinary(dir, binaryPath, architectures[0]); err != nil {
return err
}
if err := addFileToZip(zipWriter, binaryPath, "func"); err != nil {
return err
}
Expand All @@ -592,9 +666,6 @@ func addGoCodeOnlyArchiveContents(zipWriter *zip.Writer, dir string, ff *common.
return err
}
binaryPath := filepath.Join(archDir, "func")
if err := buildGoCodeOnlyBinary(dir, binaryPath, arch); err != nil {
return err
}
if err := addFileToZip(zipWriter, binaryPath, filepath.ToSlash(filepath.Join(segment, "func"))); err != nil {
return err
}
Expand All @@ -608,6 +679,23 @@ func addGoCodeOnlyArchiveContents(zipWriter *zip.Writer, dir string, ff *common.
return nil
}

func buildGoCodeOnlyProject(dir, shape string) error {
architectures := codeOnlyGoTargetArchitectures(shape)
for _, arch := range architectures {
binaryPath := filepath.Join(dir, "func")
if len(architectures) > 1 {
binaryPath = filepath.Join(dir, goCodeOnlyArchiveSegment(arch), "func")
if err := os.MkdirAll(filepath.Dir(binaryPath), 0755); err != nil {
return err
}
}
if err := buildGoCodeOnlyBinary(dir, binaryPath, arch); err != nil {
return fmt.Errorf("go code-only build failed for %s: %w", arch, err)
}
}
return nil
}

func codeOnlyGoTargetArchitectures(shape string) []string {
if shape == "" {
switch runtime.GOARCH {
Expand All @@ -634,9 +722,9 @@ func goCodeOnlyArchiveSegment(arch string) string {
func buildGoCodeOnlyBinary(dir, outputPath, arch string) error {
goBin := resolveGoBinary()
env := withEnvOverrides(os.Environ(), map[string]string{
"GOOS": "linux",
"GOARCH": arch,
"GOFLAGS": "-mod=mod",
"GOOS": "linux",
"GOARCH": arch,
"GOFLAGS": "-mod=mod",
"GOTOOLCHAIN": "go1.24.0+auto",
})

Expand Down
163 changes: 163 additions & 0 deletions commands/build_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package commands

import (
"archive/zip"
"bytes"
"os"
"path/filepath"
Expand All @@ -10,6 +11,168 @@ import (
"github.com/fnproject/cli/common"
)

func useFakeTool(t *testing.T, name, script string) {
useFakeTools(t, map[string]string{name: script})
}

func useFakeTools(t *testing.T, scripts map[string]string) {
t.Helper()
binDir := t.TempDir()
for name, script := range scripts {
toolPath := filepath.Join(binDir, name)
if err := os.WriteFile(toolPath, []byte("#!/bin/sh\n"+script+"\n"), 0755); err != nil {
t.Fatalf("write fake %s executable: %v", name, err)
}
}
t.Setenv("PATH", binDir+":/usr/bin:/bin")
}

func useFakeMaven(t *testing.T, script string) {
useFakeTool(t, "mvn", script)
}

func TestBuildCodeOnlyArchiveRunsMavenPackageForJava(t *testing.T) {
dir := t.TempDir()
useFakeMaven(t, `
[ "$1" = "package" ] || exit 1
printf '%s' "$1" > maven-argument
mkdir -p target
printf 'jar-from-maven' > target/function.jar`)

archivePath, err := buildCodeOnlyArchive(dir, &common.FuncFileV20180708{
Name: "example",
Version: "0.0.1",
Runtime: "java",
}, "GENERIC_X86")
if err != nil {
t.Fatalf("buildCodeOnlyArchive returned error: %v", err)
}

argument, err := os.ReadFile(filepath.Join(dir, "maven-argument"))
if err != nil {
t.Fatalf("read Maven argument: %v", err)
}
if string(argument) != "package" {
t.Fatalf("Maven argument = %q, want package", argument)
}

reader, err := zip.OpenReader(archivePath)
if err != nil {
t.Fatalf("open archive: %v", err)
}
defer reader.Close()
if len(reader.File) != 1 || reader.File[0].Name != "main.jar" {
t.Fatalf("archive entries = %v, want only main.jar", reader.File)
}
}

func TestBuildCodeOnlyArchiveReturnsMavenPackageFailure(t *testing.T) {
dir := t.TempDir()
useFakeMaven(t, "exit 42")

_, err := buildCodeOnlyArchive(dir, &common.FuncFileV20180708{
Name: "example",
Version: "0.0.1",
Runtime: "java",
}, "GENERIC_X86")
if err == nil || !strings.Contains(err.Error(), "java code-only build failed while running `mvn package`") {
t.Fatalf("error = %v, want Maven package failure", err)
}
if _, err := os.Stat(filepath.Join(dir, "example.0.0.1.zip")); !os.IsNotExist(err) {
t.Fatalf("archive exists after Maven failure; stat error = %v", err)
}
}

func TestBuildCodeOnlyArchiveInstallsPythonRequirements(t *testing.T) {
dir := t.TempDir()
if err := os.MkdirAll(filepath.Join(dir, "function"), 0755); err != nil {
t.Fatalf("create function directory: %v", err)
}
if err := os.WriteFile(filepath.Join(dir, "function", "hello_world.py"), []byte("def handler(): pass"), 0600); err != nil {
t.Fatalf("write function: %v", err)
}
if err := os.WriteFile(filepath.Join(dir, "requirements.txt"), []byte("example==1.0"), 0600); err != nil {
t.Fatalf("write requirements: %v", err)
}
useFakeTool(t, "python3", `
[ "$1" = "-m" ] && [ "$2" = "pip" ] && [ "$3" = "install" ] || exit 1
mkdir -p python
printf 'installed' > python/dependency.py`)

archivePath, err := buildCodeOnlyArchive(dir, &common.FuncFileV20180708{
Name: "example",
Version: "0.0.1",
Runtime: "python312.ol9",
}, "GENERIC_X86")
if err != nil {
t.Fatalf("buildCodeOnlyArchive returned error: %v", err)
}

reader, err := zip.OpenReader(archivePath)
if err != nil {
t.Fatalf("open archive: %v", err)
}
defer reader.Close()
entries := make([]string, 0, len(reader.File))
for _, file := range reader.File {
entries = append(entries, file.Name)
}
if !containsString(entries, "python/dependency.py") {
t.Fatalf("archive entries = %v, want installed Python dependency", entries)
}
}

func TestBuildCodeOnlyArchiveInstallsNodeDependencies(t *testing.T) {
dir := t.TempDir()
if err := os.MkdirAll(filepath.Join(dir, "function"), 0755); err != nil {
t.Fatalf("create function directory: %v", err)
}
if err := os.WriteFile(filepath.Join(dir, "function", "func.js"), []byte("module.exports = () => {};"), 0600); err != nil {
t.Fatalf("write function: %v", err)
}
if err := os.WriteFile(filepath.Join(dir, "package.json"), []byte(`{"dependencies":{}}`), 0600); err != nil {
t.Fatalf("write package.json: %v", err)
}
useFakeTools(t, map[string]string{
"node": "exit 0",
"npm": `
[ "$1" = "install" ] && [ "$2" = "--omit=dev" ] || exit 1
mkdir -p node_modules/example
printf 'installed' > node_modules/example/index.js`,
})

archivePath, err := buildCodeOnlyArchive(dir, &common.FuncFileV20180708{
Name: "example",
Version: "0.0.1",
Runtime: "node24.ol9",
}, "GENERIC_X86")
if err != nil {
t.Fatalf("buildCodeOnlyArchive returned error: %v", err)
}

reader, err := zip.OpenReader(archivePath)
if err != nil {
t.Fatalf("open archive: %v", err)
}
defer reader.Close()
entries := make([]string, 0, len(reader.File))
for _, file := range reader.File {
entries = append(entries, file.Name)
}
if !containsString(entries, "node_modules/example/index.js") {
t.Fatalf("archive entries = %v, want installed Node dependency", entries)
}
}

func containsString(values []string, target string) bool {
for _, value := range values {
if value == target {
return true
}
}
return false
}

func TestCreateCodeOnlyZipArchiveDoesNotLeaveEmptyArchiveOnFailure(t *testing.T) {
dir := t.TempDir()
archivePath := filepath.Join(dir, "example.0.0.1.zip")
Expand Down
Loading