Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

project: Add support for Java functions #4208

Merged
merged 6 commits into from
Aug 16, 2024
Merged
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
83 changes: 78 additions & 5 deletions cli/azd/pkg/project/framework_service_maven.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package project

import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
Expand Down Expand Up @@ -95,16 +96,36 @@ func (m *mavenProject) Package(
buildOutput *ServiceBuildResult,
progress *async.Progress[ServiceProgress],
) (*ServicePackageResult, error) {
packageDest, err := os.MkdirTemp("", "azd")
if err != nil {
return nil, fmt.Errorf("creating staging directory: %w", err)
}

progress.SetProgress(NewServiceProgress("Packaging maven project"))
if err := m.mavenCli.Package(ctx, serviceConfig.Path()); err != nil {
return nil, err
}

if serviceConfig.Host == AzureFunctionTarget {
if serviceConfig.OutputPath != "" {
// If the 'dist' property is specified, we use it directly.
return &ServicePackageResult{
Build: buildOutput,
PackagePath: filepath.Join(serviceConfig.Path(), serviceConfig.OutputPath),
}, nil
}

funcAppDir, err := m.funcAppDir(ctx, serviceConfig)
if err != nil {
return nil, err
}

return &ServicePackageResult{
Build: buildOutput,
PackagePath: funcAppDir,
}, nil
}

packageDest, err := os.MkdirTemp("", "azd")
if err != nil {
return nil, fmt.Errorf("creating staging directory: %w", err)
}

packageSrcPath := buildOutput.BuildOutputPath
if packageSrcPath == "" {
packageSrcPath = serviceConfig.Path()
Expand Down Expand Up @@ -153,6 +174,58 @@ func (m *mavenProject) Package(
}, nil
}

// funcAppDir returns the directory of the function app packaged by azure-functions-maven-plugin for the given service.
//
// The app is typically packaged under target/azure-functions.
func (m *mavenProject) funcAppDir(ctx context.Context, svc *ServiceConfig) (string, error) {
weikanglim marked this conversation as resolved.
Show resolved Hide resolved
svcPath := svc.Path()
// The staging directory for azure-functions-maven-plugin is target/azure-functions.
// It isn't configurable, but this may change in the future: https://github.com/microsoft/azure-maven-plugins/issues/1968
functionsStagingRel := filepath.Join("target", "azure-functions")
functionsStagingDir := filepath.Join(svcPath, functionsStagingRel)

// A conventional azure-functions-maven-plugin project will have the property 'functionAppName' in pom.xml,
// with its property value is passed to azure-functions-maven-plugin as 'appName'.
appName, err := m.mavenCli.GetProperty(ctx, "functionAppName", svcPath)
if err != nil && !errors.Is(err, maven.ErrPropertyNotFound) {
return "", fmt.Errorf("getting 'functionAppName' maven property: %w", err)
}

if appName != "" {
funcDir := filepath.Join(functionsStagingDir, appName)
if _, err := os.Stat(funcDir); err == nil {
return funcDir, nil
} else if !errors.Is(err, os.ErrNotExist) {
return "", fmt.Errorf("checking for function app staging directory: %w", err)
}
}

entries, err := os.ReadDir(functionsStagingDir)
if err != nil {
return "", fmt.Errorf("reading azure-functions directory: %w", err)
}
weikanglim marked this conversation as resolved.
Show resolved Hide resolved

dirs := make([]string, 0, len(entries))
for _, entry := range entries {
if entry.IsDir() {
dirs = append(dirs, entry.Name())
}
}

if len(dirs) == 1 {
return filepath.Join(functionsStagingDir, dirs[0]), nil
}

for i := range dirs {
dirs[i] = filepath.Join(functionsStagingRel, dirs[i])
}

return "", fmt.Errorf(
//nolint:lll
"multiple staging directories found: %s. Specify 'dist' in azure.yaml to select a specific directory",
strings.Join(dirs, ", "))
}

func isSupportedJavaArchive(archiveFile string) bool {
ext := strings.ToLower(filepath.Ext(archiveFile))
return ext == ".jar" || ext == ".war" || ext == ".ear"
Expand Down
141 changes: 140 additions & 1 deletion cli/azd/pkg/project/framework_service_maven_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ func Test_MavenProject(t *testing.T) {
})
}

func Test_MavenProject_Package(t *testing.T) {
func Test_MavenProject_AppService_Package(t *testing.T) {
type args struct {
// service config to be packaged.
svc *ServiceConfig
Expand Down Expand Up @@ -319,6 +319,145 @@ func Test_MavenProject_Package(t *testing.T) {
}
}

func Test_MavenProject_FuncApp_Package(t *testing.T) {
tempDir := t.TempDir()

ostest.Chdir(t, tempDir)

err := os.WriteFile(getMvnwCmd(), nil, osutil.PermissionExecutableFile)
require.NoError(t, err)

mockContext := mocks.NewMockContext(context.Background())
mockContext.CommandRunner.
When(func(args exec.RunArgs, command string) bool {
return strings.Contains(command, getMvnwCmd()+" package")
}).
RespondFn(func(args exec.RunArgs) (exec.RunResult, error) {
return exec.NewRunResult(0, "", ""), nil
})

// mvnFuncAppNameProperty is the value of the maven property that holds the function app name.
mvnFuncAppNameProperty := ""
mockContext.CommandRunner.
When(func(args exec.RunArgs, command string) bool {
return strings.Contains(command, getMvnwCmd()+" help:evaluate -Dexpression=functionAppName")
}).
RespondFn(func(args exec.RunArgs) (exec.RunResult, error) {
if len(mvnFuncAppNameProperty) == 0 {
return exec.NewRunResult(0, "", ""), maven.ErrPropertyNotFound
}

return exec.NewRunResult(0, mvnFuncAppNameProperty, ""), nil
})

env := environment.New("test")
mavenCli := maven.NewCli(mockContext.CommandRunner)
javaCli := javac.NewCli(mockContext.CommandRunner)

serviceConfig := createTestServiceConfig("./src/api", AzureFunctionTarget, ServiceLanguageJava)
err = os.MkdirAll(serviceConfig.Path(), osutil.PermissionDirectory)
require.NoError(t, err)

mavenProject := NewMavenProject(env, mavenCli, javaCli)

t.Run("uses maven property functionAppName", func(t *testing.T) {
mvnFuncAppNameProperty = "my-function-app"
var svc ServiceConfig = *serviceConfig

err = os.RemoveAll(filepath.Join(svc.Path(), "target", "azure-functions"))
require.NoError(t, err)

err = os.MkdirAll(
filepath.Join(svc.Path(), "target", "azure-functions", mvnFuncAppNameProperty),
osutil.PermissionDirectory)
require.NoError(t, err)

result, err := logProgress(t, func(progress *async.Progress[ServiceProgress]) (*ServicePackageResult, error) {
return mavenProject.Package(
*mockContext.Context,
&svc,
&ServiceBuildResult{
BuildOutputPath: svc.Path(),
},
progress,
)
})

require.NoError(t, err)
require.NotNil(t, result)
require.Equal(t, result.PackagePath, filepath.Join(svc.Path(), "target", "azure-functions", mvnFuncAppNameProperty))
})

t.Run("uses target/azure-functions when maven property functionAppName not available", func(t *testing.T) {
mvnFuncAppNameProperty = ""
var svc ServiceConfig = *serviceConfig

err = os.RemoveAll(filepath.Join(svc.Path(), "target", "azure-functions"))
require.NoError(t, err)

err = os.MkdirAll(
filepath.Join(svc.Path(), "target", "azure-functions", "any"),
osutil.PermissionDirectory)
require.NoError(t, err)

result, err := logProgress(t, func(progress *async.Progress[ServiceProgress]) (*ServicePackageResult, error) {
return mavenProject.Package(
*mockContext.Context,
&svc,
&ServiceBuildResult{
BuildOutputPath: svc.Path(),
},
progress,
)
})

// returns single staging directory
require.NoError(t, err)
require.NotNil(t, result)
require.Equal(t, result.PackagePath, filepath.Join(svc.Path(), "target", "azure-functions", "any"))

// errors when multiple staging directories are found
err = os.MkdirAll(
filepath.Join(svc.Path(), "target", "azure-functions", "any2"),
osutil.PermissionDirectory)
require.NoError(t, err)

_, err = logProgress(t, func(progress *async.Progress[ServiceProgress]) (*ServicePackageResult, error) {
return mavenProject.Package(
*mockContext.Context,
&svc,
&ServiceBuildResult{
BuildOutputPath: svc.Path(),
},
progress,
)
})
require.Error(t, err)
require.ErrorContains(t, err, "multiple staging directories")
})

t.Run("uses dist specified", func(t *testing.T) {
mvnFuncAppNameProperty = ""
var svc ServiceConfig = *serviceConfig

svc.OutputPath = "my-custom-dir"
result, err := logProgress(t, func(progress *async.Progress[ServiceProgress]) (*ServicePackageResult, error) {
return mavenProject.Package(
*mockContext.Context,
&svc,
&ServiceBuildResult{
BuildOutputPath: svc.Path(),
},
progress,
)
})

require.NoError(t, err)
require.NotNil(t, result)
require.Equal(t, result.PackagePath, filepath.Join(svc.Path(), svc.OutputPath))
})
}

func getMvnwCmd() string {
if runtime.GOOS == "windows" {
return "mvnw.cmd"
Expand Down
25 changes: 25 additions & 0 deletions cli/azd/pkg/tools/maven/maven.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"os"
"path/filepath"
"regexp"
"strings"
"sync"

osexec "os/exec"
Expand Down Expand Up @@ -212,6 +213,30 @@ func (cli *Cli) ResolveDependencies(ctx context.Context, projectPath string) err
return nil
}

var ErrPropertyNotFound = errors.New("property not found")

func (cli *Cli) GetProperty(ctx context.Context, propertyPath string, projectPath string) (string, error) {
weikanglim marked this conversation as resolved.
Show resolved Hide resolved
weikanglim marked this conversation as resolved.
Show resolved Hide resolved
mvnCmd, err := cli.mvnCmd()
if err != nil {
return "", err
}
runArgs := exec.NewRunArgs(mvnCmd,
"help:evaluate",
// cspell: disable-next-line Dexpression and DforceStdout are maven command line arguments
"-Dexpression="+propertyPath, "-q", "-DforceStdout").WithCwd(projectPath)
res, err := cli.commandRunner.Run(ctx, runArgs)
if err != nil {
return "", fmt.Errorf("mvn help:evaluate on project '%s' failed: %w", projectPath, err)
}

result := strings.TrimSpace(res.Stdout)
if result == "null object or invalid expression" {
return "", ErrPropertyNotFound
}

return result, nil
}

func NewCli(commandRunner exec.CommandRunner) *Cli {
return &Cli{
commandRunner: commandRunner,
Expand Down
Loading