github.com/mweagle/Sparta@v1.15.0/archetype/codecommit.go (about)

     1  package archetype
     2  
     3  import (
     4  	"context"
     5  	"reflect"
     6  	"runtime"
     7  
     8  	awsLambdaEvents "github.com/aws/aws-lambda-go/events"
     9  	sparta "github.com/mweagle/Sparta"
    10  	gocf "github.com/mweagle/go-cloudformation"
    11  	"github.com/pkg/errors"
    12  )
    13  
    14  // CodeCommitReactor represents a lambda function that responds to CodeCommit events
    15  type CodeCommitReactor interface {
    16  	// OnCodeCommitEvent when an SNS event occurs. Check the codeCommitEvent field
    17  	// for the specific event
    18  	OnCodeCommitEvent(ctx context.Context, codeCommitEvent awsLambdaEvents.CodeCommitEvent) (interface{}, error)
    19  }
    20  
    21  // CodeCommitReactorFunc is a free function that adapts a CodeCommitReactor
    22  // compliant signature into a function that exposes an OnEvent
    23  // function
    24  type CodeCommitReactorFunc func(ctx context.Context,
    25  	codeCommitEvent awsLambdaEvents.CodeCommitEvent) (interface{}, error)
    26  
    27  // OnCodeCommitEvent satisfies the CodeCommitReactor interface
    28  func (reactorFunc CodeCommitReactorFunc) OnCodeCommitEvent(ctx context.Context,
    29  	codeCommitEvent awsLambdaEvents.CodeCommitEvent) (interface{}, error) {
    30  	return reactorFunc(ctx, codeCommitEvent)
    31  }
    32  
    33  // ReactorName provides the name of the reactor func
    34  func (reactorFunc CodeCommitReactorFunc) ReactorName() string {
    35  	return runtime.FuncForPC(reflect.ValueOf(reactorFunc).Pointer()).Name()
    36  }
    37  
    38  // NewCodeCommitReactor returns an SNS reactor lambda function
    39  func NewCodeCommitReactor(reactor CodeCommitReactor,
    40  	repositoryName gocf.Stringable,
    41  	branches []string,
    42  	events []string,
    43  	additionalLambdaPermissions []sparta.IAMRolePrivilege) (*sparta.LambdaAWSInfo, error) {
    44  
    45  	reactorLambda := func(ctx context.Context, codeCommitEvent awsLambdaEvents.CodeCommitEvent) (interface{}, error) {
    46  		return reactor.OnCodeCommitEvent(ctx, codeCommitEvent)
    47  	}
    48  
    49  	lambdaFn, lambdaFnErr := sparta.NewAWSLambda(reactorName(reactor),
    50  		reactorLambda,
    51  		sparta.IAMRoleDefinition{})
    52  	if lambdaFnErr != nil {
    53  		return nil, errors.Wrapf(lambdaFnErr, "attempting to create reactor")
    54  	}
    55  
    56  	lambdaFn.Permissions = append(lambdaFn.Permissions, sparta.CodeCommitPermission{
    57  		BasePermission: sparta.BasePermission{
    58  			SourceArn: repositoryName,
    59  		},
    60  		RepositoryName: repositoryName.String(),
    61  		Branches:       branches,
    62  		Events:         events,
    63  	})
    64  	if len(additionalLambdaPermissions) != 0 {
    65  		lambdaFn.RoleDefinition.Privileges = additionalLambdaPermissions
    66  	}
    67  	return lambdaFn, nil
    68  }