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

Support azd hooks out of azure.yaml, Part I of merging azd operation to hooks #4244

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 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
28 changes: 28 additions & 0 deletions cli/azd/cmd/hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cmd
import (
"context"
"fmt"
"path/filepath"

"github.com/azure/azure-dev/cli/azd/cmd/actions"
"github.com/azure/azure-dev/cli/azd/internal"
Expand Down Expand Up @@ -125,6 +126,22 @@ func (hra *hooksRunAction) Run(ctx context.Context) (*actions.ActionResult, erro
}
}

hooksDefinedAtInfraPath, err := ext.HooksFromFolderPath(
filepath.Join(hra.projectConfig.Path, hra.projectConfig.Infra.Path))
if err != nil {
return nil, fmt.Errorf("failed getting hooks from infra path, %w", err)
}
if len(hooksDefinedAtInfraPath) > 0 && len(hra.projectConfig.Hooks) > 0 {
return nil, fmt.Errorf(
"project hooks defined in both %s and azure.yaml configuration,"+
" please remove one of them",
filepath.Join(hra.projectConfig.Infra.Path, "azd.hooks.yaml"),
)
}
if hra.projectConfig.Hooks == nil {
hra.projectConfig.Hooks = hooksDefinedAtInfraPath
}

// Project level hooks
if err := hra.processHooks(
ctx,
Expand All @@ -146,6 +163,17 @@ func (hra *hooksRunAction) Run(ctx context.Context) (*actions.ActionResult, erro
// Service level hooks
for _, service := range stableServices {
skip := hra.flags.service != "" && service.Name != hra.flags.service
hooksDefinedAtServicePath, err := ext.HooksFromFolderPath(service.Path())
if err != nil {
return nil, err
}
if service.Hooks != nil && hooksDefinedAtServicePath != nil {
return nil, fmt.Errorf("service %s has hooks defined in both azd.hooks.yaml and azure.yaml, "+
"please remove one of them.", service.Name)
}
if service.Hooks == nil {
service.Hooks = hooksDefinedAtServicePath
}

if err := hra.processHooks(
ctx,
Expand Down
43 changes: 40 additions & 3 deletions cli/azd/cmd/middleware/hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"log"
"path/filepath"

"github.com/azure/azure-dev/cli/azd/cmd/actions"
"github.com/azure/azure-dev/cli/azd/pkg/environment"
Expand Down Expand Up @@ -74,7 +75,14 @@ func (m *HooksMiddleware) registerCommandHooks(
projectConfig *project.ProjectConfig,
next NextFn,
) (*actions.ActionResult, error) {
if len(projectConfig.Hooks) == 0 {

hooksDefinedAtInfraPath, err := ext.HooksFromFolderPath(
vhvb1989 marked this conversation as resolved.
Show resolved Hide resolved
filepath.Join(projectConfig.Path, projectConfig.Infra.Path))
if err != nil {
return nil, fmt.Errorf("failed getting hooks from infra path, %w", err)
}

if len(projectConfig.Hooks) == 0 && len(hooksDefinedAtInfraPath) == 0 {
log.Println(
"azd project is not available or does not contain any command hooks, skipping command hook registrations.",
)
Expand All @@ -86,6 +94,17 @@ func (m *HooksMiddleware) registerCommandHooks(
return nil, fmt.Errorf("failed getting environment manager, %w", err)
}

if len(hooksDefinedAtInfraPath) > 0 && len(projectConfig.Hooks) > 0 {
return nil, fmt.Errorf(
"project hooks defined in both %s and azure.yaml configuration,"+
" please remove one of them",
filepath.Join(projectConfig.Infra.Path, "azd.hooks.yaml"),
)
}
if projectConfig.Hooks == nil {
projectConfig.Hooks = hooksDefinedAtInfraPath
}

hooksManager := ext.NewHooksManager(projectConfig.Path)
hooksRunner := ext.NewHooksRunner(
hooksManager,
Expand Down Expand Up @@ -138,12 +157,30 @@ func (m *HooksMiddleware) registerServiceHooks(

for _, service := range stableServices {
serviceName := service.Name

hooksDefinedAtServicePath, err := ext.HooksFromFolderPath(service.Path())
if err != nil {
return fmt.Errorf("failed getting hooks from service path, %w", err)
}

// If the service hasn't configured any hooks we can continue on.
if len(service.Hooks) == 0 {
log.Printf("service '%s' does not require any command hooks.\n", serviceName)
if len(service.Hooks) == 0 && len(hooksDefinedAtServicePath) == 0 {
log.Printf("service '%s' does not require any hooks.\n", serviceName)
continue
}

if len(service.Hooks) > 0 && len(hooksDefinedAtServicePath) > 0 {
return fmt.Errorf(
"service '%s' has hooks defined in both azd.hooks.yaml and azure.yaml configuration,"+
" please remove one of them.",
serviceName)
}

// If the service has hooks defined in azd.hooks.yaml but not in azure.yaml
if len(service.Hooks) == 0 {
service.Hooks = hooksDefinedAtServicePath
}

serviceHooksManager := ext.NewHooksManager(service.Path())
serviceHooksRunner := ext.NewHooksRunner(
serviceHooksManager,
Expand Down
26 changes: 26 additions & 0 deletions cli/azd/pkg/ext/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"strings"

"github.com/azure/azure-dev/cli/azd/pkg/osutil"
"gopkg.in/yaml.v3"
)

// The type of hooks. Supported values are 'pre' and 'post'
Expand Down Expand Up @@ -218,3 +219,28 @@ func createTempScript(hookConfig *HookConfig) (string, error) {

return file.Name(), nil
}

// HooksFromFolderPath check if there is file named azd.hooks.yaml in the service path
// and return the hooks configuration.
func HooksFromFolderPath(servicePath string) (map[string]*HookConfig, error) {
hooksPath := filepath.Join(servicePath, "azd.hooks.yaml")
if _, err := os.Stat(hooksPath); os.IsNotExist(err) {
hooksPath = filepath.Join(servicePath, "azd.hooks.yml")
if _, err := os.Stat(hooksPath); os.IsNotExist(err) {
return nil, nil
}
}

hooksFile, err := os.ReadFile(hooksPath)
if err != nil {
return nil, fmt.Errorf("failed reading hooks from '%s', %w", hooksPath, err)
}

// open hooksPath into a byte array and unmarshal it into a map[string]*ext.HookConfig
hooks := make(map[string]*HookConfig)
if err := yaml.Unmarshal(hooksFile, &hooks); err != nil {
return nil, fmt.Errorf("failed unmarshalling hooks from '%s', %w", hooksPath, err)
}

return hooks, nil
}
110 changes: 110 additions & 0 deletions cli/azd/pkg/ext/models_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package ext

import (
"os"
"path/filepath"
"testing"

"github.com/azure/azure-dev/cli/azd/pkg/osutil"
"github.com/stretchr/testify/require"
)

func Test_HooksFromFolderPath(t *testing.T) {
t.Run("HooksFileExistsYaml", func(t *testing.T) {
tempDir := t.TempDir()
hooksPath := filepath.Join(tempDir, "azd.hooks.yaml")
hooksContent := []byte(`
pre-build:
shell: sh
run: ./pre-build.sh
post-build:
shell: pwsh
run: ./post-build.ps1
vhvb1989 marked this conversation as resolved.
Show resolved Hide resolved
`)

err := os.WriteFile(hooksPath, hooksContent, osutil.PermissionDirectory)
require.NoError(t, err)

expectedHooks := map[string]*HookConfig{
"pre-build": {
validated: false,
cwd: "",
Name: "",
Shell: ShellTypeBash,
Run: "./pre-build.sh",
ContinueOnError: false,
Interactive: false,
Windows: nil,
Posix: nil,
},
"post-build": {
validated: false,
cwd: "",
Name: "",
Shell: ShellTypePowershell,
Run: "./post-build.ps1",
ContinueOnError: false,
Interactive: false,
Windows: nil,
Posix: nil,
},
}

hooks, err := HooksFromFolderPath(tempDir)
require.NoError(t, err)
require.Equal(t, expectedHooks, hooks)
})

t.Run("HooksFileExistsYml", func(t *testing.T) {
tempDir := t.TempDir()
hooksPath := filepath.Join(tempDir, "azd.hooks.yml")
hooksContent := []byte(`
pre-build:
shell: sh
run: ./pre-build.sh
post-build:
shell: pwsh
run: ./post-build.ps1
`)

err := os.WriteFile(hooksPath, hooksContent, osutil.PermissionDirectory)
require.NoError(t, err)

expectedHooks := map[string]*HookConfig{
"pre-build": {
validated: false,
cwd: "",
Name: "",
Shell: ShellTypeBash,
Run: "./pre-build.sh",
ContinueOnError: false,
Interactive: false,
Windows: nil,
Posix: nil,
},
"post-build": {
validated: false,
cwd: "",
Name: "",
Shell: ShellTypePowershell,
Run: "./post-build.ps1",
ContinueOnError: false,
Interactive: false,
Windows: nil,
Posix: nil,
},
}

hooks, err := HooksFromFolderPath(tempDir)
require.NoError(t, err)
require.Equal(t, expectedHooks, hooks)
})

t.Run("NoHooksFile", func(t *testing.T) {
tempDir := t.TempDir()
hooks, err := HooksFromFolderPath(tempDir)
require.NoError(t, err)
var expectedHooks map[string]*HookConfig
require.Equal(t, expectedHooks, hooks)
})
}
2 changes: 1 addition & 1 deletion cli/azd/pkg/project/project.go
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ func Save(ctx context.Context, projectConfig *ProjectConfig, projectFilePath str
return fmt.Errorf("saving project file: %w", err)
}

projectConfig.Path = projectFilePath
projectConfig.Path = filepath.Dir(projectFilePath)

return nil
}
Loading