id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
1,100
pborman/uuid
uuid.go
Variant
func (uuid UUID) Variant() Variant { if len(uuid) != 16 { return Invalid } switch { case (uuid[8] & 0xc0) == 0x80: return RFC4122 case (uuid[8] & 0xe0) == 0xc0: return Microsoft case (uuid[8] & 0xe0) == 0xe0: return Future default: return Reserved } }
go
func (uuid UUID) Variant() Variant { if len(uuid) != 16 { return Invalid } switch { case (uuid[8] & 0xc0) == 0x80: return RFC4122 case (uuid[8] & 0xe0) == 0xc0: return Microsoft case (uuid[8] & 0xe0) == 0xe0: return Future default: return Reserved } }
[ "func", "(", "uuid", "UUID", ")", "Variant", "(", ")", "Variant", "{", "if", "len", "(", "uuid", ")", "!=", "16", "{", "return", "Invalid", "\n", "}", "\n", "switch", "{", "case", "(", "uuid", "[", "8", "]", "&", "0xc0", ")", "==", "0x80", ":",...
// Variant returns the variant encoded in uuid. It returns Invalid if // uuid is invalid.
[ "Variant", "returns", "the", "variant", "encoded", "in", "uuid", ".", "It", "returns", "Invalid", "if", "uuid", "is", "invalid", "." ]
8b1b92947f46224e3b97bb1a3a5b0382be00d31e
https://github.com/pborman/uuid/blob/8b1b92947f46224e3b97bb1a3a5b0382be00d31e/uuid.go#L129-L143
1,101
pborman/uuid
uuid.go
Version
func (uuid UUID) Version() (Version, bool) { if len(uuid) != 16 { return 0, false } return Version(uuid[6] >> 4), true }
go
func (uuid UUID) Version() (Version, bool) { if len(uuid) != 16 { return 0, false } return Version(uuid[6] >> 4), true }
[ "func", "(", "uuid", "UUID", ")", "Version", "(", ")", "(", "Version", ",", "bool", ")", "{", "if", "len", "(", "uuid", ")", "!=", "16", "{", "return", "0", ",", "false", "\n", "}", "\n", "return", "Version", "(", "uuid", "[", "6", "]", ">>", ...
// Version returns the version of uuid. It returns false if uuid is not // valid.
[ "Version", "returns", "the", "version", "of", "uuid", ".", "It", "returns", "false", "if", "uuid", "is", "not", "valid", "." ]
8b1b92947f46224e3b97bb1a3a5b0382be00d31e
https://github.com/pborman/uuid/blob/8b1b92947f46224e3b97bb1a3a5b0382be00d31e/uuid.go#L147-L152
1,102
pborman/uuid
version1.go
NewUUID
func NewUUID() UUID { gu, err := guuid.NewUUID() if err == nil { return UUID(gu[:]) } return nil }
go
func NewUUID() UUID { gu, err := guuid.NewUUID() if err == nil { return UUID(gu[:]) } return nil }
[ "func", "NewUUID", "(", ")", "UUID", "{", "gu", ",", "err", ":=", "guuid", ".", "NewUUID", "(", ")", "\n", "if", "err", "==", "nil", "{", "return", "UUID", "(", "gu", "[", ":", "]", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// NewUUID returns a Version 1 UUID based on the current NodeID and clock // sequence, and the current time. If the NodeID has not been set by SetNodeID // or SetNodeInterface then it will be set automatically. If the NodeID cannot // be set NewUUID returns nil. If clock sequence has not been set by // SetClockSequence then it will be set automatically. If GetTime fails to // return the current NewUUID returns nil.
[ "NewUUID", "returns", "a", "Version", "1", "UUID", "based", "on", "the", "current", "NodeID", "and", "clock", "sequence", "and", "the", "current", "time", ".", "If", "the", "NodeID", "has", "not", "been", "set", "by", "SetNodeID", "or", "SetNodeInterface", ...
8b1b92947f46224e3b97bb1a3a5b0382be00d31e
https://github.com/pborman/uuid/blob/8b1b92947f46224e3b97bb1a3a5b0382be00d31e/version1.go#L17-L23
1,103
graphql-go/relay
array_connection.go
OffsetToCursor
func OffsetToCursor(offset int) ConnectionCursor { str := fmt.Sprintf("%v%v", PREFIX, offset) return ConnectionCursor(base64.StdEncoding.EncodeToString([]byte(str))) }
go
func OffsetToCursor(offset int) ConnectionCursor { str := fmt.Sprintf("%v%v", PREFIX, offset) return ConnectionCursor(base64.StdEncoding.EncodeToString([]byte(str))) }
[ "func", "OffsetToCursor", "(", "offset", "int", ")", "ConnectionCursor", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "PREFIX", ",", "offset", ")", "\n", "return", "ConnectionCursor", "(", "base64", ".", "StdEncoding", ".", "EncodeToString"...
// Creates the cursor string from an offset
[ "Creates", "the", "cursor", "string", "from", "an", "offset" ]
54350098cfe5942bc76186efa1f29ca286f6d54d
https://github.com/graphql-go/relay/blob/54350098cfe5942bc76186efa1f29ca286f6d54d/array_connection.go#L120-L123
1,104
graphql-go/relay
array_connection.go
CursorToOffset
func CursorToOffset(cursor ConnectionCursor) (int, error) { str := "" b, err := base64.StdEncoding.DecodeString(string(cursor)) if err == nil { str = string(b) } str = strings.Replace(str, PREFIX, "", -1) offset, err := strconv.Atoi(str) if err != nil { return 0, errors.New("Invalid cursor") } return offset, nil }
go
func CursorToOffset(cursor ConnectionCursor) (int, error) { str := "" b, err := base64.StdEncoding.DecodeString(string(cursor)) if err == nil { str = string(b) } str = strings.Replace(str, PREFIX, "", -1) offset, err := strconv.Atoi(str) if err != nil { return 0, errors.New("Invalid cursor") } return offset, nil }
[ "func", "CursorToOffset", "(", "cursor", "ConnectionCursor", ")", "(", "int", ",", "error", ")", "{", "str", ":=", "\"", "\"", "\n", "b", ",", "err", ":=", "base64", ".", "StdEncoding", ".", "DecodeString", "(", "string", "(", "cursor", ")", ")", "\n",...
// Re-derives the offset from the cursor string.
[ "Re", "-", "derives", "the", "offset", "from", "the", "cursor", "string", "." ]
54350098cfe5942bc76186efa1f29ca286f6d54d
https://github.com/graphql-go/relay/blob/54350098cfe5942bc76186efa1f29ca286f6d54d/array_connection.go#L126-L138
1,105
graphql-go/relay
array_connection.go
CursorForObjectInConnection
func CursorForObjectInConnection(data []interface{}, object interface{}) ConnectionCursor { offset := -1 for i, d := range data { // TODO: better object comparison if reflect.DeepEqual(d, object) { offset = i break } } if offset == -1 { return "" } return OffsetToCursor(offset) }
go
func CursorForObjectInConnection(data []interface{}, object interface{}) ConnectionCursor { offset := -1 for i, d := range data { // TODO: better object comparison if reflect.DeepEqual(d, object) { offset = i break } } if offset == -1 { return "" } return OffsetToCursor(offset) }
[ "func", "CursorForObjectInConnection", "(", "data", "[", "]", "interface", "{", "}", ",", "object", "interface", "{", "}", ")", "ConnectionCursor", "{", "offset", ":=", "-", "1", "\n", "for", "i", ",", "d", ":=", "range", "data", "{", "// TODO: better obje...
// Return the cursor associated with an object in an array.
[ "Return", "the", "cursor", "associated", "with", "an", "object", "in", "an", "array", "." ]
54350098cfe5942bc76186efa1f29ca286f6d54d
https://github.com/graphql-go/relay/blob/54350098cfe5942bc76186efa1f29ca286f6d54d/array_connection.go#L141-L154
1,106
gin-gonic/autotls
autotls.go
Run
func Run(r http.Handler, domain ...string) error { return http.Serve(autocert.NewListener(domain...), r) }
go
func Run(r http.Handler, domain ...string) error { return http.Serve(autocert.NewListener(domain...), r) }
[ "func", "Run", "(", "r", "http", ".", "Handler", ",", "domain", "...", "string", ")", "error", "{", "return", "http", ".", "Serve", "(", "autocert", ".", "NewListener", "(", "domain", "...", ")", ",", "r", ")", "\n", "}" ]
// Run support 1-line LetsEncrypt HTTPS servers
[ "Run", "support", "1", "-", "line", "LetsEncrypt", "HTTPS", "servers" ]
fb31fc47f5213049be0224126050a7bdf804bc3e
https://github.com/gin-gonic/autotls/blob/fb31fc47f5213049be0224126050a7bdf804bc3e/autotls.go#L10-L12
1,107
gin-gonic/autotls
autotls.go
RunWithManager
func RunWithManager(r http.Handler, m *autocert.Manager) error { s := &http.Server{ Addr: ":https", TLSConfig: m.TLSConfig(), Handler: r, } go http.ListenAndServe(":http", m.HTTPHandler(nil)) return s.ListenAndServeTLS("", "") }
go
func RunWithManager(r http.Handler, m *autocert.Manager) error { s := &http.Server{ Addr: ":https", TLSConfig: m.TLSConfig(), Handler: r, } go http.ListenAndServe(":http", m.HTTPHandler(nil)) return s.ListenAndServeTLS("", "") }
[ "func", "RunWithManager", "(", "r", "http", ".", "Handler", ",", "m", "*", "autocert", ".", "Manager", ")", "error", "{", "s", ":=", "&", "http", ".", "Server", "{", "Addr", ":", "\"", "\"", ",", "TLSConfig", ":", "m", ".", "TLSConfig", "(", ")", ...
// RunWithManager support custom autocert manager
[ "RunWithManager", "support", "custom", "autocert", "manager" ]
fb31fc47f5213049be0224126050a7bdf804bc3e
https://github.com/gin-gonic/autotls/blob/fb31fc47f5213049be0224126050a7bdf804bc3e/autotls.go#L15-L25
1,108
mitchellh/panicwrap
panicwrap.go
trackPanic
func trackPanic(r io.Reader, w io.Writer, dur time.Duration, result chan<- string) { defer close(result) var panicTimer <-chan time.Time panicBuf := new(bytes.Buffer) panicHeaders := [][]byte{ []byte("panic:"), []byte("fatal error: fault"), } panicType := -1 tempBuf := make([]byte, 2048) for { var buf []byte var n int if panicTimer == nil && panicBuf.Len() > 0 { // We're not tracking a panic but the buffer length is // greater than 0. We need to clear out that buffer, but // look for another panic along the way. // First, remove the previous panic header so we don't loop w.Write(panicBuf.Next(len(panicHeaders[panicType]))) // Next, assume that this is our new buffer to inspect n = panicBuf.Len() buf = make([]byte, n) copy(buf, panicBuf.Bytes()) panicBuf.Reset() } else { var err error buf = tempBuf n, err = r.Read(buf) if n <= 0 && err == io.EOF { if panicBuf.Len() > 0 { // We were tracking a panic, assume it was a panic // and return that as the result. result <- panicBuf.String() } return } } if panicTimer != nil { // We're tracking what we think is a panic right now. // If the timer ended, then it is not a panic. isPanic := true select { case <-panicTimer: isPanic = false default: } // No matter what, buffer the text some more. panicBuf.Write(buf[0:n]) if !isPanic { // It isn't a panic, stop tracking. Clean-up will happen // on the next iteration. panicTimer = nil } continue } panicType = -1 flushIdx := n for i, header := range panicHeaders { idx := bytes.Index(buf[0:n], header) if idx >= 0 { panicType = i flushIdx = idx break } } // Flush to stderr what isn't a panic w.Write(buf[0:flushIdx]) if panicType == -1 { // Not a panic so just continue along continue } // We have a panic header. Write we assume is a panic os far. panicBuf.Write(buf[flushIdx:n]) panicTimer = time.After(dur) } }
go
func trackPanic(r io.Reader, w io.Writer, dur time.Duration, result chan<- string) { defer close(result) var panicTimer <-chan time.Time panicBuf := new(bytes.Buffer) panicHeaders := [][]byte{ []byte("panic:"), []byte("fatal error: fault"), } panicType := -1 tempBuf := make([]byte, 2048) for { var buf []byte var n int if panicTimer == nil && panicBuf.Len() > 0 { // We're not tracking a panic but the buffer length is // greater than 0. We need to clear out that buffer, but // look for another panic along the way. // First, remove the previous panic header so we don't loop w.Write(panicBuf.Next(len(panicHeaders[panicType]))) // Next, assume that this is our new buffer to inspect n = panicBuf.Len() buf = make([]byte, n) copy(buf, panicBuf.Bytes()) panicBuf.Reset() } else { var err error buf = tempBuf n, err = r.Read(buf) if n <= 0 && err == io.EOF { if panicBuf.Len() > 0 { // We were tracking a panic, assume it was a panic // and return that as the result. result <- panicBuf.String() } return } } if panicTimer != nil { // We're tracking what we think is a panic right now. // If the timer ended, then it is not a panic. isPanic := true select { case <-panicTimer: isPanic = false default: } // No matter what, buffer the text some more. panicBuf.Write(buf[0:n]) if !isPanic { // It isn't a panic, stop tracking. Clean-up will happen // on the next iteration. panicTimer = nil } continue } panicType = -1 flushIdx := n for i, header := range panicHeaders { idx := bytes.Index(buf[0:n], header) if idx >= 0 { panicType = i flushIdx = idx break } } // Flush to stderr what isn't a panic w.Write(buf[0:flushIdx]) if panicType == -1 { // Not a panic so just continue along continue } // We have a panic header. Write we assume is a panic os far. panicBuf.Write(buf[flushIdx:n]) panicTimer = time.After(dur) } }
[ "func", "trackPanic", "(", "r", "io", ".", "Reader", ",", "w", "io", ".", "Writer", ",", "dur", "time", ".", "Duration", ",", "result", "chan", "<-", "string", ")", "{", "defer", "close", "(", "result", ")", "\n\n", "var", "panicTimer", "<-", "chan",...
// trackPanic monitors the given reader for a panic. If a panic is detected, // it is outputted on the result channel. This will close the channel once // it is complete.
[ "trackPanic", "monitors", "the", "given", "reader", "for", "a", "panic", ".", "If", "a", "panic", "is", "detected", "it", "is", "outputted", "on", "the", "result", "channel", ".", "This", "will", "close", "the", "channel", "once", "it", "is", "complete", ...
f67bf3f3d291520d92b87846f7c9f4e27caaa7db
https://github.com/mitchellh/panicwrap/blob/f67bf3f3d291520d92b87846f7c9f4e27caaa7db/panicwrap.go#L268-L357
1,109
mweagle/Sparta
decorator/versioning.go
LambdaVersioningDecorator
func LambdaVersioningDecorator() sparta.TemplateDecoratorHookFunc { return func(serviceName string, lambdaResourceName string, lambdaResource gocf.LambdaFunction, resourceMetadata map[string]interface{}, S3Bucket string, S3Key string, buildID string, template *gocf.Template, context map[string]interface{}, logger *logrus.Logger) error { lambdaResName := sparta.CloudFormationResourceName("LambdaVersion", buildID, time.Now().UTC().String()) versionResource := &gocf.LambdaVersion{ FunctionName: gocf.GetAtt(lambdaResourceName, "Arn").String(), } lambdaVersionRes := template.AddResource(lambdaResName, versionResource) lambdaVersionRes.DeletionPolicy = "Retain" // That's it... return nil } }
go
func LambdaVersioningDecorator() sparta.TemplateDecoratorHookFunc { return func(serviceName string, lambdaResourceName string, lambdaResource gocf.LambdaFunction, resourceMetadata map[string]interface{}, S3Bucket string, S3Key string, buildID string, template *gocf.Template, context map[string]interface{}, logger *logrus.Logger) error { lambdaResName := sparta.CloudFormationResourceName("LambdaVersion", buildID, time.Now().UTC().String()) versionResource := &gocf.LambdaVersion{ FunctionName: gocf.GetAtt(lambdaResourceName, "Arn").String(), } lambdaVersionRes := template.AddResource(lambdaResName, versionResource) lambdaVersionRes.DeletionPolicy = "Retain" // That's it... return nil } }
[ "func", "LambdaVersioningDecorator", "(", ")", "sparta", ".", "TemplateDecoratorHookFunc", "{", "return", "func", "(", "serviceName", "string", ",", "lambdaResourceName", "string", ",", "lambdaResource", "gocf", ".", "LambdaFunction", ",", "resourceMetadata", "map", "...
// LambdaVersioningDecorator returns a TemplateDecorator // that is responsible for including a versioning resource // with the given lambda function
[ "LambdaVersioningDecorator", "returns", "a", "TemplateDecorator", "that", "is", "responsible", "for", "including", "a", "versioning", "resource", "with", "the", "given", "lambda", "function" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/decorator/versioning.go#L14-L37
1,110
mweagle/Sparta
aws/iam/builder/build.go
Ref
func (iamRes *IAMResourceBuilder) Ref(resName string, delimiter ...string) *IAMResourceBuilder { iamRes.resourceParts = append(iamRes.resourceParts, gocf.Ref(resName)) for _, eachDelimiter := range delimiter { iamRes.resourceParts = append(iamRes.resourceParts, gocf.String(eachDelimiter)) } return iamRes }
go
func (iamRes *IAMResourceBuilder) Ref(resName string, delimiter ...string) *IAMResourceBuilder { iamRes.resourceParts = append(iamRes.resourceParts, gocf.Ref(resName)) for _, eachDelimiter := range delimiter { iamRes.resourceParts = append(iamRes.resourceParts, gocf.String(eachDelimiter)) } return iamRes }
[ "func", "(", "iamRes", "*", "IAMResourceBuilder", ")", "Ref", "(", "resName", "string", ",", "delimiter", "...", "string", ")", "*", "IAMResourceBuilder", "{", "iamRes", ".", "resourceParts", "=", "append", "(", "iamRes", ".", "resourceParts", ",", "gocf", "...
// Ref inserts a go-cloudformation Ref entry
[ "Ref", "inserts", "a", "go", "-", "cloudformation", "Ref", "entry" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/iam/builder/build.go#L25-L33
1,111
mweagle/Sparta
aws/iam/builder/build.go
Attr
func (iamRes *IAMResourceBuilder) Attr(resName string, propName string, delimiter ...string) *IAMResourceBuilder { iamRes.resourceParts = append(iamRes.resourceParts, gocf.GetAtt(resName, propName)) for _, eachDelimiter := range delimiter { iamRes.resourceParts = append(iamRes.resourceParts, gocf.String(eachDelimiter)) } return iamRes }
go
func (iamRes *IAMResourceBuilder) Attr(resName string, propName string, delimiter ...string) *IAMResourceBuilder { iamRes.resourceParts = append(iamRes.resourceParts, gocf.GetAtt(resName, propName)) for _, eachDelimiter := range delimiter { iamRes.resourceParts = append(iamRes.resourceParts, gocf.String(eachDelimiter)) } return iamRes }
[ "func", "(", "iamRes", "*", "IAMResourceBuilder", ")", "Attr", "(", "resName", "string", ",", "propName", "string", ",", "delimiter", "...", "string", ")", "*", "IAMResourceBuilder", "{", "iamRes", ".", "resourceParts", "=", "append", "(", "iamRes", ".", "re...
// Attr inserts a go-cloudformation GetAtt entry
[ "Attr", "inserts", "a", "go", "-", "cloudformation", "GetAtt", "entry" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/iam/builder/build.go#L36-L44
1,112
mweagle/Sparta
aws/iam/builder/build.go
Literal
func (iamRes *IAMResourceBuilder) Literal(arnPart string) *IAMResourceBuilder { iamRes.resourceParts = append(iamRes.resourceParts, gocf.String(arnPart)) return iamRes }
go
func (iamRes *IAMResourceBuilder) Literal(arnPart string) *IAMResourceBuilder { iamRes.resourceParts = append(iamRes.resourceParts, gocf.String(arnPart)) return iamRes }
[ "func", "(", "iamRes", "*", "IAMResourceBuilder", ")", "Literal", "(", "arnPart", "string", ")", "*", "IAMResourceBuilder", "{", "iamRes", ".", "resourceParts", "=", "append", "(", "iamRes", ".", "resourceParts", ",", "gocf", ".", "String", "(", "arnPart", "...
// Literal inserts a string literal into the ARN being constructed
[ "Literal", "inserts", "a", "string", "literal", "into", "the", "ARN", "being", "constructed" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/iam/builder/build.go#L124-L128
1,113
mweagle/Sparta
aws/iam/builder/build.go
ToPrivilege
func (iamRes *IAMResourceBuilder) ToPrivilege() sparta.IAMRolePrivilege { return sparta.IAMRolePrivilege{ Actions: iamRes.builder.apiCalls, Resource: gocf.Join("", iamRes.resourceParts...), } }
go
func (iamRes *IAMResourceBuilder) ToPrivilege() sparta.IAMRolePrivilege { return sparta.IAMRolePrivilege{ Actions: iamRes.builder.apiCalls, Resource: gocf.Join("", iamRes.resourceParts...), } }
[ "func", "(", "iamRes", "*", "IAMResourceBuilder", ")", "ToPrivilege", "(", ")", "sparta", ".", "IAMRolePrivilege", "{", "return", "sparta", ".", "IAMRolePrivilege", "{", "Actions", ":", "iamRes", ".", "builder", ".", "apiCalls", ",", "Resource", ":", "gocf", ...
// ToPrivilege returns a legacy sparta.IAMRolePrivilege type for this // entry
[ "ToPrivilege", "returns", "a", "legacy", "sparta", ".", "IAMRolePrivilege", "type", "for", "this", "entry" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/iam/builder/build.go#L141-L146
1,114
mweagle/Sparta
aws/iam/builder/build.go
ForResource
func (iamRes *IAMBuilder) ForResource() *IAMResourceBuilder { return &IAMResourceBuilder{ builder: iamRes, resourceParts: make([]gocf.Stringable, 0), } }
go
func (iamRes *IAMBuilder) ForResource() *IAMResourceBuilder { return &IAMResourceBuilder{ builder: iamRes, resourceParts: make([]gocf.Stringable, 0), } }
[ "func", "(", "iamRes", "*", "IAMBuilder", ")", "ForResource", "(", ")", "*", "IAMResourceBuilder", "{", "return", "&", "IAMResourceBuilder", "{", "builder", ":", "iamRes", ",", "resourceParts", ":", "make", "(", "[", "]", "gocf", ".", "Stringable", ",", "0...
// ForResource returns the IAMPrivilegeBuilder instance // which can be finalized into an IAMRolePrivilege
[ "ForResource", "returns", "the", "IAMPrivilegeBuilder", "instance", "which", "can", "be", "finalized", "into", "an", "IAMRolePrivilege" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/iam/builder/build.go#L158-L163
1,115
mweagle/Sparta
aws/iam/builder/build.go
ForFederatedPrincipals
func (iamRes *IAMBuilder) ForFederatedPrincipals(principals ...string) *IAMPrincipalBuilder { stringablePrincipals := make([]gocf.Stringable, len(principals)) for index, eachPrincipal := range principals { stringablePrincipals[index] = gocf.String(eachPrincipal) } return &IAMPrincipalBuilder{ builder: iamRes, principal: &gocf.IAMPrincipal{ Federated: gocf.StringList(stringablePrincipals...), }, } }
go
func (iamRes *IAMBuilder) ForFederatedPrincipals(principals ...string) *IAMPrincipalBuilder { stringablePrincipals := make([]gocf.Stringable, len(principals)) for index, eachPrincipal := range principals { stringablePrincipals[index] = gocf.String(eachPrincipal) } return &IAMPrincipalBuilder{ builder: iamRes, principal: &gocf.IAMPrincipal{ Federated: gocf.StringList(stringablePrincipals...), }, } }
[ "func", "(", "iamRes", "*", "IAMBuilder", ")", "ForFederatedPrincipals", "(", "principals", "...", "string", ")", "*", "IAMPrincipalBuilder", "{", "stringablePrincipals", ":=", "make", "(", "[", "]", "gocf", ".", "Stringable", ",", "len", "(", "principals", ")...
// ForFederatedPrincipals returns the IAMPrincipalBuilder instance // which can be finalized into an IAMRolePrivilege
[ "ForFederatedPrincipals", "returns", "the", "IAMPrincipalBuilder", "instance", "which", "can", "be", "finalized", "into", "an", "IAMRolePrivilege" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/iam/builder/build.go#L205-L217
1,116
mweagle/Sparta
aws/iam/builder/build.go
ToPrivilege
func (iampb *IAMPrincipalBuilder) ToPrivilege() sparta.IAMRolePrivilege { privilege := sparta.IAMRolePrivilege{ Actions: iampb.builder.apiCalls, Principal: iampb.principal, } if iampb.builder.condition != nil { privilege.Condition = iampb.builder.condition } return privilege }
go
func (iampb *IAMPrincipalBuilder) ToPrivilege() sparta.IAMRolePrivilege { privilege := sparta.IAMRolePrivilege{ Actions: iampb.builder.apiCalls, Principal: iampb.principal, } if iampb.builder.condition != nil { privilege.Condition = iampb.builder.condition } return privilege }
[ "func", "(", "iampb", "*", "IAMPrincipalBuilder", ")", "ToPrivilege", "(", ")", "sparta", ".", "IAMRolePrivilege", "{", "privilege", ":=", "sparta", ".", "IAMRolePrivilege", "{", "Actions", ":", "iampb", ".", "builder", ".", "apiCalls", ",", "Principal", ":", ...
// ToPrivilege returns a legacy sparta.IAMRolePrivilege type for this // IAMPrincipalBuilder entry
[ "ToPrivilege", "returns", "a", "legacy", "sparta", ".", "IAMRolePrivilege", "type", "for", "this", "IAMPrincipalBuilder", "entry" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/iam/builder/build.go#L234-L243
1,117
mweagle/Sparta
aws/iam/builder/build.go
Deny
func Deny(apiCalls ...string) *IAMBuilder { builder := IAMBuilder{ apiCalls: apiCalls, effect: "Deny", } return &builder }
go
func Deny(apiCalls ...string) *IAMBuilder { builder := IAMBuilder{ apiCalls: apiCalls, effect: "Deny", } return &builder }
[ "func", "Deny", "(", "apiCalls", "...", "string", ")", "*", "IAMBuilder", "{", "builder", ":=", "IAMBuilder", "{", "apiCalls", ":", "apiCalls", ",", "effect", ":", "\"", "\"", ",", "}", "\n", "return", "&", "builder", "\n", "}" ]
// Deny creates a IAMPrivilegeBuilder instance Denying the supplied API calls
[ "Deny", "creates", "a", "IAMPrivilegeBuilder", "instance", "Denying", "the", "supplied", "API", "calls" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/iam/builder/build.go#L264-L270
1,118
mweagle/Sparta
cloudformation_resources.go
resourceOutputs
func resourceOutputs(resourceName string, resource gocf.ResourceProperties, logger *logrus.Logger) ([]string, error) { outputProps := []string{} switch typedResource := resource.(type) { case gocf.IAMRole: // NOP case *gocf.DynamoDBTable: if typedResource.StreamSpecification != nil { outputProps = append(outputProps, "StreamArn") } case gocf.DynamoDBTable: if typedResource.StreamSpecification != nil { outputProps = append(outputProps, "StreamArn") } case gocf.KinesisStream, *gocf.KinesisStream: outputProps = append(outputProps, "Arn") case gocf.Route53RecordSet, *gocf.Route53RecordSet: // NOP case gocf.S3Bucket, *gocf.S3Bucket: outputProps = append(outputProps, "DomainName", "WebsiteURL") case gocf.SNSTopic, *gocf.SNSTopic: outputProps = append(outputProps, "TopicName") case gocf.SQSQueue, *gocf.SQSQueue: outputProps = append(outputProps, "Arn", "QueueName") default: logger.WithFields(logrus.Fields{ "ResourceType": fmt.Sprintf("%T", typedResource), }).Warn("Discovery information for dependency not yet implemented") } return outputProps, nil }
go
func resourceOutputs(resourceName string, resource gocf.ResourceProperties, logger *logrus.Logger) ([]string, error) { outputProps := []string{} switch typedResource := resource.(type) { case gocf.IAMRole: // NOP case *gocf.DynamoDBTable: if typedResource.StreamSpecification != nil { outputProps = append(outputProps, "StreamArn") } case gocf.DynamoDBTable: if typedResource.StreamSpecification != nil { outputProps = append(outputProps, "StreamArn") } case gocf.KinesisStream, *gocf.KinesisStream: outputProps = append(outputProps, "Arn") case gocf.Route53RecordSet, *gocf.Route53RecordSet: // NOP case gocf.S3Bucket, *gocf.S3Bucket: outputProps = append(outputProps, "DomainName", "WebsiteURL") case gocf.SNSTopic, *gocf.SNSTopic: outputProps = append(outputProps, "TopicName") case gocf.SQSQueue, *gocf.SQSQueue: outputProps = append(outputProps, "Arn", "QueueName") default: logger.WithFields(logrus.Fields{ "ResourceType": fmt.Sprintf("%T", typedResource), }).Warn("Discovery information for dependency not yet implemented") } return outputProps, nil }
[ "func", "resourceOutputs", "(", "resourceName", "string", ",", "resource", "gocf", ".", "ResourceProperties", ",", "logger", "*", "logrus", ".", "Logger", ")", "(", "[", "]", "string", ",", "error", ")", "{", "outputProps", ":=", "[", "]", "string", "{", ...
// resourceOutputs is responsible for returning the conditional // set of CloudFormation outputs for a given resource type.
[ "resourceOutputs", "is", "responsible", "for", "returning", "the", "conditional", "set", "of", "CloudFormation", "outputs", "for", "a", "given", "resource", "type", "." ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/cloudformation_resources.go#L15-L52
1,119
mweagle/Sparta
aws/cloudformation/resources/helloworldresource.go
Create
func (command HelloWorldResource) Create(awsSession *session.Session, event *CloudFormationLambdaEvent, logger *logrus.Logger) (map[string]interface{}, error) { requestPropsErr := json.Unmarshal(event.ResourceProperties, &command) if requestPropsErr != nil { return nil, requestPropsErr } logger.Info("create: Hello ", command.Message.Literal) return map[string]interface{}{ "Resource": "Created message: " + command.Message.Literal, }, nil }
go
func (command HelloWorldResource) Create(awsSession *session.Session, event *CloudFormationLambdaEvent, logger *logrus.Logger) (map[string]interface{}, error) { requestPropsErr := json.Unmarshal(event.ResourceProperties, &command) if requestPropsErr != nil { return nil, requestPropsErr } logger.Info("create: Hello ", command.Message.Literal) return map[string]interface{}{ "Resource": "Created message: " + command.Message.Literal, }, nil }
[ "func", "(", "command", "HelloWorldResource", ")", "Create", "(", "awsSession", "*", "session", ".", "Session", ",", "event", "*", "CloudFormationLambdaEvent", ",", "logger", "*", "logrus", ".", "Logger", ")", "(", "map", "[", "string", "]", "interface", "{"...
// Create implements resource create
[ "Create", "implements", "resource", "create" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/cloudformation/resources/helloworldresource.go#L29-L41
1,120
mweagle/Sparta
s3site_build.go
NewS3Site
func NewS3Site(resources string) (*S3Site, error) { // We'll ensure its valid during the build step, since // there could be a go:generate command in the source that // actually builds it. site := &S3Site{ resources: resources, UserManifestData: map[string]interface{}{}, } return site, nil }
go
func NewS3Site(resources string) (*S3Site, error) { // We'll ensure its valid during the build step, since // there could be a go:generate command in the source that // actually builds it. site := &S3Site{ resources: resources, UserManifestData: map[string]interface{}{}, } return site, nil }
[ "func", "NewS3Site", "(", "resources", "string", ")", "(", "*", "S3Site", ",", "error", ")", "{", "// We'll ensure its valid during the build step, since", "// there could be a go:generate command in the source that", "// actually builds it.", "site", ":=", "&", "S3Site", "{"...
// NewS3Site returns a new S3Site pointer initialized with the // static resources at the supplied path. If resources is a directory, // the contents will be recursively archived and used to populate // the new S3 bucket.
[ "NewS3Site", "returns", "a", "new", "S3Site", "pointer", "initialized", "with", "the", "static", "resources", "at", "the", "supplied", "path", ".", "If", "resources", "is", "a", "directory", "the", "contents", "will", "be", "recursively", "archived", "and", "u...
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/s3site_build.go#L258-L267
1,121
mweagle/Sparta
decorator/log_aggregator.go
DecorateService
func (lad *LogAggregatorDecorator) DecorateService(context map[string]interface{}, serviceName string, template *gocf.Template, S3Bucket string, S3Key string, buildID string, awsSession *session.Session, noop bool, logger *logrus.Logger) error { // Create the Kinesis Stream template.AddResource(lad.kinesisStreamResourceName, lad.kinesisResource) // Create the IAM role putRecordPriv := spartaIAMBuilder.Allow("kinesis:PutRecord"). ForResource(). Attr(lad.kinesisStreamResourceName, "Arn"). ToPolicyStatement() passRolePriv := spartaIAMBuilder.Allow("iam:PassRole"). ForResource(). Literal("arn:aws:iam::"). AccountID(":"). Literal("role/"). Literal(lad.iamRoleNameResourceName). ToPolicyStatement() statements := make([]spartaIAM.PolicyStatement, 0) statements = append(statements, putRecordPriv, passRolePriv, ) iamPolicyList := gocf.IAMRolePolicyList{} iamPolicyList = append(iamPolicyList, gocf.IAMRolePolicy{ PolicyDocument: sparta.ArbitraryJSONObject{ "Version": "2012-10-17", "Statement": statements, }, PolicyName: gocf.String("LogAggregatorPolicy"), }, ) iamLogAggregatorRole := &gocf.IAMRole{ RoleName: gocf.String(lad.iamRoleNameResourceName), AssumeRolePolicyDocument: LogAggregatorAssumePolicyDocument, Policies: &iamPolicyList, } template.AddResource(lad.iamRoleNameResourceName, iamLogAggregatorRole) return nil }
go
func (lad *LogAggregatorDecorator) DecorateService(context map[string]interface{}, serviceName string, template *gocf.Template, S3Bucket string, S3Key string, buildID string, awsSession *session.Session, noop bool, logger *logrus.Logger) error { // Create the Kinesis Stream template.AddResource(lad.kinesisStreamResourceName, lad.kinesisResource) // Create the IAM role putRecordPriv := spartaIAMBuilder.Allow("kinesis:PutRecord"). ForResource(). Attr(lad.kinesisStreamResourceName, "Arn"). ToPolicyStatement() passRolePriv := spartaIAMBuilder.Allow("iam:PassRole"). ForResource(). Literal("arn:aws:iam::"). AccountID(":"). Literal("role/"). Literal(lad.iamRoleNameResourceName). ToPolicyStatement() statements := make([]spartaIAM.PolicyStatement, 0) statements = append(statements, putRecordPriv, passRolePriv, ) iamPolicyList := gocf.IAMRolePolicyList{} iamPolicyList = append(iamPolicyList, gocf.IAMRolePolicy{ PolicyDocument: sparta.ArbitraryJSONObject{ "Version": "2012-10-17", "Statement": statements, }, PolicyName: gocf.String("LogAggregatorPolicy"), }, ) iamLogAggregatorRole := &gocf.IAMRole{ RoleName: gocf.String(lad.iamRoleNameResourceName), AssumeRolePolicyDocument: LogAggregatorAssumePolicyDocument, Policies: &iamPolicyList, } template.AddResource(lad.iamRoleNameResourceName, iamLogAggregatorRole) return nil }
[ "func", "(", "lad", "*", "LogAggregatorDecorator", ")", "DecorateService", "(", "context", "map", "[", "string", "]", "interface", "{", "}", ",", "serviceName", "string", ",", "template", "*", "gocf", ".", "Template", ",", "S3Bucket", "string", ",", "S3Key",...
// DecorateService annotates the service with the Kinesis hook
[ "DecorateService", "annotates", "the", "service", "with", "the", "Kinesis", "hook" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/decorator/log_aggregator.go#L82-L131
1,122
mweagle/Sparta
decorator/log_aggregator.go
DecorateTemplate
func (lad *LogAggregatorDecorator) DecorateTemplate(serviceName string, lambdaResourceName string, lambdaResource gocf.LambdaFunction, resourceMetadata map[string]interface{}, S3Bucket string, S3Key string, buildID string, template *gocf.Template, context map[string]interface{}, logger *logrus.Logger) error { // The relay function should consume the stream if lad.logRelay.LogicalResourceName() == lambdaResourceName { // Need to add a Lambda EventSourceMapping eventSourceMappingResourceName := sparta.CloudFormationResourceName("LogAggregator", "EventSourceMapping", lambdaResourceName) template.AddResource(eventSourceMappingResourceName, &gocf.LambdaEventSourceMapping{ StartingPosition: gocf.String(lad.kinesisMapping.StartingPosition), BatchSize: gocf.Integer(lad.kinesisMapping.BatchSize), EventSourceArn: gocf.GetAtt(lad.kinesisStreamResourceName, "Arn"), FunctionName: gocf.GetAtt(lambdaResourceName, "Arn"), }) } else { // The other functions should publish their logs to the stream subscriptionName := logAggregatorResName(fmt.Sprintf("Lambda%s", lambdaResourceName)) subscriptionFilterRes := &gocf.LogsSubscriptionFilter{ DestinationArn: gocf.GetAtt(lad.kinesisStreamResourceName, "Arn"), RoleArn: gocf.GetAtt(lad.iamRoleNameResourceName, "Arn"), LogGroupName: gocf.Join("", gocf.String("/aws/lambda/"), gocf.Ref(lambdaResourceName)), FilterPattern: gocf.String("{$.level = info || $.level = warning || $.level = error }"), } template.AddResource(subscriptionName, subscriptionFilterRes) } return nil }
go
func (lad *LogAggregatorDecorator) DecorateTemplate(serviceName string, lambdaResourceName string, lambdaResource gocf.LambdaFunction, resourceMetadata map[string]interface{}, S3Bucket string, S3Key string, buildID string, template *gocf.Template, context map[string]interface{}, logger *logrus.Logger) error { // The relay function should consume the stream if lad.logRelay.LogicalResourceName() == lambdaResourceName { // Need to add a Lambda EventSourceMapping eventSourceMappingResourceName := sparta.CloudFormationResourceName("LogAggregator", "EventSourceMapping", lambdaResourceName) template.AddResource(eventSourceMappingResourceName, &gocf.LambdaEventSourceMapping{ StartingPosition: gocf.String(lad.kinesisMapping.StartingPosition), BatchSize: gocf.Integer(lad.kinesisMapping.BatchSize), EventSourceArn: gocf.GetAtt(lad.kinesisStreamResourceName, "Arn"), FunctionName: gocf.GetAtt(lambdaResourceName, "Arn"), }) } else { // The other functions should publish their logs to the stream subscriptionName := logAggregatorResName(fmt.Sprintf("Lambda%s", lambdaResourceName)) subscriptionFilterRes := &gocf.LogsSubscriptionFilter{ DestinationArn: gocf.GetAtt(lad.kinesisStreamResourceName, "Arn"), RoleArn: gocf.GetAtt(lad.iamRoleNameResourceName, "Arn"), LogGroupName: gocf.Join("", gocf.String("/aws/lambda/"), gocf.Ref(lambdaResourceName)), FilterPattern: gocf.String("{$.level = info || $.level = warning || $.level = error }"), } template.AddResource(subscriptionName, subscriptionFilterRes) } return nil }
[ "func", "(", "lad", "*", "LogAggregatorDecorator", ")", "DecorateTemplate", "(", "serviceName", "string", ",", "lambdaResourceName", "string", ",", "lambdaResource", "gocf", ".", "LambdaFunction", ",", "resourceMetadata", "map", "[", "string", "]", "interface", "{",...
// DecorateTemplate annotates the lambda with the log forwarding sink info
[ "DecorateTemplate", "annotates", "the", "lambda", "with", "the", "log", "forwarding", "sink", "info" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/decorator/log_aggregator.go#L134-L172
1,123
mweagle/Sparta
decorator/log_aggregator.go
NewLogAggregatorDecorator
func NewLogAggregatorDecorator( kinesisResource *gocf.KinesisStream, kinesisMapping *sparta.EventSourceMapping, relay *sparta.LambdaAWSInfo) *LogAggregatorDecorator { return &LogAggregatorDecorator{ kinesisStreamResourceName: logAggregatorResName("Kinesis"), kinesisResource: kinesisResource, kinesisMapping: kinesisMapping, iamRoleNameResourceName: logAggregatorResName("IAMRole"), logRelay: relay, } }
go
func NewLogAggregatorDecorator( kinesisResource *gocf.KinesisStream, kinesisMapping *sparta.EventSourceMapping, relay *sparta.LambdaAWSInfo) *LogAggregatorDecorator { return &LogAggregatorDecorator{ kinesisStreamResourceName: logAggregatorResName("Kinesis"), kinesisResource: kinesisResource, kinesisMapping: kinesisMapping, iamRoleNameResourceName: logAggregatorResName("IAMRole"), logRelay: relay, } }
[ "func", "NewLogAggregatorDecorator", "(", "kinesisResource", "*", "gocf", ".", "KinesisStream", ",", "kinesisMapping", "*", "sparta", ".", "EventSourceMapping", ",", "relay", "*", "sparta", ".", "LambdaAWSInfo", ")", "*", "LogAggregatorDecorator", "{", "return", "&"...
// NewLogAggregatorDecorator returns a ServiceDecoratorHook that registers a Kinesis // stream lambda log aggregator
[ "NewLogAggregatorDecorator", "returns", "a", "ServiceDecoratorHook", "that", "registers", "a", "Kinesis", "stream", "lambda", "log", "aggregator" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/decorator/log_aggregator.go#L176-L188
1,124
mweagle/Sparta
archetype/rest/rest.go
StatusCodes
func (mh *MethodHandler) StatusCodes(codes ...int) *MethodHandler { if mh.statusCodes == nil { mh.statusCodes = make([]int, 0) } mh.statusCodes = append(mh.statusCodes, codes...) return mh }
go
func (mh *MethodHandler) StatusCodes(codes ...int) *MethodHandler { if mh.statusCodes == nil { mh.statusCodes = make([]int, 0) } mh.statusCodes = append(mh.statusCodes, codes...) return mh }
[ "func", "(", "mh", "*", "MethodHandler", ")", "StatusCodes", "(", "codes", "...", "int", ")", "*", "MethodHandler", "{", "if", "mh", ".", "statusCodes", "==", "nil", "{", "mh", ".", "statusCodes", "=", "make", "(", "[", "]", "int", ",", "0", ")", "...
// StatusCodes is a fluent builder to append additional HTTP status codes // for the given MethodHandler. It's primarily used to disamgiguate // input from the NewMethodHandler constructor
[ "StatusCodes", "is", "a", "fluent", "builder", "to", "append", "additional", "HTTP", "status", "codes", "for", "the", "given", "MethodHandler", ".", "It", "s", "primarily", "used", "to", "disamgiguate", "input", "from", "the", "NewMethodHandler", "constructor" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/archetype/rest/rest.go#L41-L47
1,125
mweagle/Sparta
archetype/rest/rest.go
Options
func (mh *MethodHandler) Options(options *sparta.LambdaFunctionOptions) *MethodHandler { mh.options = options return mh }
go
func (mh *MethodHandler) Options(options *sparta.LambdaFunctionOptions) *MethodHandler { mh.options = options return mh }
[ "func", "(", "mh", "*", "MethodHandler", ")", "Options", "(", "options", "*", "sparta", ".", "LambdaFunctionOptions", ")", "*", "MethodHandler", "{", "mh", ".", "options", "=", "options", "\n", "return", "mh", "\n", "}" ]
// Options is a fluent builder that allows customizing the lambda execution // options for the given function
[ "Options", "is", "a", "fluent", "builder", "that", "allows", "customizing", "the", "lambda", "execution", "options", "for", "the", "given", "function" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/archetype/rest/rest.go#L51-L54
1,126
mweagle/Sparta
archetype/rest/rest.go
Privileges
func (mh *MethodHandler) Privileges(privileges ...sparta.IAMRolePrivilege) *MethodHandler { if mh.privileges == nil { mh.privileges = make([]sparta.IAMRolePrivilege, 0) } mh.privileges = append(mh.privileges, privileges...) return mh }
go
func (mh *MethodHandler) Privileges(privileges ...sparta.IAMRolePrivilege) *MethodHandler { if mh.privileges == nil { mh.privileges = make([]sparta.IAMRolePrivilege, 0) } mh.privileges = append(mh.privileges, privileges...) return mh }
[ "func", "(", "mh", "*", "MethodHandler", ")", "Privileges", "(", "privileges", "...", "sparta", ".", "IAMRolePrivilege", ")", "*", "MethodHandler", "{", "if", "mh", ".", "privileges", "==", "nil", "{", "mh", ".", "privileges", "=", "make", "(", "[", "]",...
// Privileges is the fluent builder to associated IAM privileges with this // HTTP handler
[ "Privileges", "is", "the", "fluent", "builder", "to", "associated", "IAM", "privileges", "with", "this", "HTTP", "handler" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/archetype/rest/rest.go#L58-L64
1,127
mweagle/Sparta
archetype/rest/rest.go
Headers
func (mh *MethodHandler) Headers(headerNames ...string) *MethodHandler { if mh.headers == nil { mh.headers = make([]string, 0) } mh.headers = append(mh.headers, headerNames...) return mh }
go
func (mh *MethodHandler) Headers(headerNames ...string) *MethodHandler { if mh.headers == nil { mh.headers = make([]string, 0) } mh.headers = append(mh.headers, headerNames...) return mh }
[ "func", "(", "mh", "*", "MethodHandler", ")", "Headers", "(", "headerNames", "...", "string", ")", "*", "MethodHandler", "{", "if", "mh", ".", "headers", "==", "nil", "{", "mh", ".", "headers", "=", "make", "(", "[", "]", "string", ",", "0", ")", "...
// Headers is the fluent builder that defines what headers this method returns
[ "Headers", "is", "the", "fluent", "builder", "that", "defines", "what", "headers", "this", "method", "returns" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/archetype/rest/rest.go#L67-L73
1,128
mweagle/Sparta
archetype/rest/rest.go
NewMethodHandler
func NewMethodHandler(handler interface{}, defaultCode int) *MethodHandler { return &MethodHandler{ DefaultCode: defaultCode, Handler: handler, } }
go
func NewMethodHandler(handler interface{}, defaultCode int) *MethodHandler { return &MethodHandler{ DefaultCode: defaultCode, Handler: handler, } }
[ "func", "NewMethodHandler", "(", "handler", "interface", "{", "}", ",", "defaultCode", "int", ")", "*", "MethodHandler", "{", "return", "&", "MethodHandler", "{", "DefaultCode", ":", "defaultCode", ",", "Handler", ":", "handler", ",", "}", "\n", "}" ]
// NewMethodHandler is a constructor function to return a new MethodHandler // pointer instance.
[ "NewMethodHandler", "is", "a", "constructor", "function", "to", "return", "a", "new", "MethodHandler", "pointer", "instance", "." ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/archetype/rest/rest.go#L77-L82
1,129
mweagle/Sparta
docker/docker.go
BuildDockerImageWithFlags
func BuildDockerImageWithFlags(serviceName string, dockerFilepath string, dockerTags map[string]string, buildTags string, linkFlags string, logger *logrus.Logger) error { // BEGIN DOCKER PRECONDITIONS // Ensure that serviceName and tags are lowercase to make Docker happy var dockerErrors []string for eachKey, eachValue := range dockerTags { if eachKey != strings.ToLower(eachKey) || eachValue != strings.ToLower(eachValue) { dockerErrors = append(dockerErrors, fmt.Sprintf("--tag %s:%s MUST be lower case", eachKey, eachValue)) } } if len(dockerErrors) > 0 { return errors.Errorf("Docker build errors: %s", strings.Join(dockerErrors[:], ", ")) } // BEGIN Informational - output the docker version... dockerVersionCmd := exec.Command("docker", "-v") dockerVersionCmdErr := system.RunOSCommand(dockerVersionCmd, logger) if dockerVersionCmdErr != nil { return errors.Wrapf(dockerVersionCmdErr, "Attempting to get docker version") } // END Informational - output the docker version... // END DOCKER PRECONDITIONS // Compile this binary for minimal Docker size // https://blog.codeship.com/building-minimal-docker-containers-for-go-applications/ currentTime := time.Now().UnixNano() executableOutput := fmt.Sprintf("%s-%d-docker.lambda.amd64", serviceName, currentTime) buildErr := system.BuildGoBinary(serviceName, executableOutput, false, fmt.Sprintf("%d", currentTime), buildTags, linkFlags, false, logger) if buildErr != nil { return errors.Wrapf(buildErr, "Attempting to build Docker binary") } defer func() { removeErr := os.Remove(executableOutput) if removeErr != nil { logger.WithFields(logrus.Fields{ "Path": executableOutput, "Error": removeErr, }).Warn("Failed to delete temporary Docker binary") } }() // ARG SPARTA_DOCKER_BINARY reference s.t. we can supply the binary // name to the build.. // We need to build the static binary s.t. we can add it to the Docker container... // Build the image... dockerArgs := []string{ "build", "--build-arg", fmt.Sprintf("%s=%s", BinaryNameArgument, executableOutput), } if dockerFilepath != "" { dockerArgs = append(dockerArgs, "--file", dockerFilepath) } // Add the latest tag // dockerArgs = append(dockerArgs, "--tag", fmt.Sprintf("sparta/%s:latest", serviceName)) logger.WithFields(logrus.Fields{ "Tags": dockerTags, }).Info("Creating Docker image") for eachKey, eachValue := range dockerTags { dockerArgs = append(dockerArgs, "--tag", fmt.Sprintf("%s:%s", strings.ToLower(eachKey), strings.ToLower(eachValue))) } dockerArgs = append(dockerArgs, ".") dockerCmd := exec.Command("docker", dockerArgs...) return system.RunOSCommand(dockerCmd, logger) }
go
func BuildDockerImageWithFlags(serviceName string, dockerFilepath string, dockerTags map[string]string, buildTags string, linkFlags string, logger *logrus.Logger) error { // BEGIN DOCKER PRECONDITIONS // Ensure that serviceName and tags are lowercase to make Docker happy var dockerErrors []string for eachKey, eachValue := range dockerTags { if eachKey != strings.ToLower(eachKey) || eachValue != strings.ToLower(eachValue) { dockerErrors = append(dockerErrors, fmt.Sprintf("--tag %s:%s MUST be lower case", eachKey, eachValue)) } } if len(dockerErrors) > 0 { return errors.Errorf("Docker build errors: %s", strings.Join(dockerErrors[:], ", ")) } // BEGIN Informational - output the docker version... dockerVersionCmd := exec.Command("docker", "-v") dockerVersionCmdErr := system.RunOSCommand(dockerVersionCmd, logger) if dockerVersionCmdErr != nil { return errors.Wrapf(dockerVersionCmdErr, "Attempting to get docker version") } // END Informational - output the docker version... // END DOCKER PRECONDITIONS // Compile this binary for minimal Docker size // https://blog.codeship.com/building-minimal-docker-containers-for-go-applications/ currentTime := time.Now().UnixNano() executableOutput := fmt.Sprintf("%s-%d-docker.lambda.amd64", serviceName, currentTime) buildErr := system.BuildGoBinary(serviceName, executableOutput, false, fmt.Sprintf("%d", currentTime), buildTags, linkFlags, false, logger) if buildErr != nil { return errors.Wrapf(buildErr, "Attempting to build Docker binary") } defer func() { removeErr := os.Remove(executableOutput) if removeErr != nil { logger.WithFields(logrus.Fields{ "Path": executableOutput, "Error": removeErr, }).Warn("Failed to delete temporary Docker binary") } }() // ARG SPARTA_DOCKER_BINARY reference s.t. we can supply the binary // name to the build.. // We need to build the static binary s.t. we can add it to the Docker container... // Build the image... dockerArgs := []string{ "build", "--build-arg", fmt.Sprintf("%s=%s", BinaryNameArgument, executableOutput), } if dockerFilepath != "" { dockerArgs = append(dockerArgs, "--file", dockerFilepath) } // Add the latest tag // dockerArgs = append(dockerArgs, "--tag", fmt.Sprintf("sparta/%s:latest", serviceName)) logger.WithFields(logrus.Fields{ "Tags": dockerTags, }).Info("Creating Docker image") for eachKey, eachValue := range dockerTags { dockerArgs = append(dockerArgs, "--tag", fmt.Sprintf("%s:%s", strings.ToLower(eachKey), strings.ToLower(eachValue))) } dockerArgs = append(dockerArgs, ".") dockerCmd := exec.Command("docker", dockerArgs...) return system.RunOSCommand(dockerCmd, logger) }
[ "func", "BuildDockerImageWithFlags", "(", "serviceName", "string", ",", "dockerFilepath", "string", ",", "dockerTags", "map", "[", "string", "]", "string", ",", "buildTags", "string", ",", "linkFlags", "string", ",", "logger", "*", "logrus", ".", "Logger", ")", ...
// BuildDockerImageWithFlags is an extended version of BuildDockerImage that includes // support for build time tags
[ "BuildDockerImageWithFlags", "is", "an", "extended", "version", "of", "BuildDockerImage", "that", "includes", "support", "for", "build", "time", "tags" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/docker/docker.go#L32-L115
1,130
mweagle/Sparta
docker/docker.go
BuildDockerImage
func BuildDockerImage(serviceName string, dockerFilepath string, tags map[string]string, logger *logrus.Logger) error { return BuildDockerImageWithFlags(serviceName, dockerFilepath, tags, "", "", logger) }
go
func BuildDockerImage(serviceName string, dockerFilepath string, tags map[string]string, logger *logrus.Logger) error { return BuildDockerImageWithFlags(serviceName, dockerFilepath, tags, "", "", logger) }
[ "func", "BuildDockerImage", "(", "serviceName", "string", ",", "dockerFilepath", "string", ",", "tags", "map", "[", "string", "]", "string", ",", "logger", "*", "logrus", ".", "Logger", ")", "error", "{", "return", "BuildDockerImageWithFlags", "(", "serviceName"...
// BuildDockerImage creates the smallest docker image for this Golang binary // using the serviceName as the image name and including the supplied tags
[ "BuildDockerImage", "creates", "the", "smallest", "docker", "image", "for", "this", "Golang", "binary", "using", "the", "serviceName", "as", "the", "image", "name", "and", "including", "the", "supplied", "tags" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/docker/docker.go#L119-L130
1,131
mweagle/Sparta
docker/docker.go
PushDockerImageToECR
func PushDockerImageToECR(localImageTag string, ecrRepoName string, awsSession *session.Session, logger *logrus.Logger) (string, error) { stsSvc := sts.New(awsSession) ecrSvc := ecr.New(awsSession) // 1. Get the caller identity s.t. we can get the ECR URL which includes the // account name stsIdentityOutput, stsIdentityErr := stsSvc.GetCallerIdentity(&sts.GetCallerIdentityInput{}) if stsIdentityErr != nil { return "", errors.Wrapf(stsIdentityErr, "Attempting to get AWS caller identity") } // 2. Create the URL to which we're going to do the push localImageTagParts := strings.Split(localImageTag, ":") ecrTagValue := fmt.Sprintf("%s.dkr.ecr.%s.amazonaws.com/%s:%s", *stsIdentityOutput.Account, *awsSession.Config.Region, ecrRepoName, localImageTagParts[len(localImageTagParts)-1]) // 3. Tag the local image with the ECR tag dockerTagCmd := exec.Command("docker", "tag", localImageTag, ecrTagValue) dockerTagCmdErr := system.RunOSCommand(dockerTagCmd, logger) if dockerTagCmdErr != nil { return "", errors.Wrapf(dockerTagCmdErr, "Attempting to tag Docker image") } // 4. Push the image - if that fails attempt to reauthorize with the docker // client and try again var pushError error dockerPushCmd := exec.Command("docker", "push", ecrTagValue) pushError = system.RunOSCommand(dockerPushCmd, logger) if pushError != nil { logger.WithFields(logrus.Fields{ "Error": pushError, }).Info("ECR push failed - reauthorizing") ecrAuthTokenResult, ecrAuthTokenResultErr := ecrSvc.GetAuthorizationToken(&ecr.GetAuthorizationTokenInput{}) if ecrAuthTokenResultErr != nil { pushError = ecrAuthTokenResultErr } else { authData := ecrAuthTokenResult.AuthorizationData[0] authToken, authTokenErr := base64.StdEncoding.DecodeString(*authData.AuthorizationToken) if authTokenErr != nil { pushError = authTokenErr } else { authTokenString := string(authToken) authTokenParts := strings.Split(authTokenString, ":") dockerURL := fmt.Sprintf("https://%s.dkr.ecr.%s.amazonaws.com", *stsIdentityOutput.Account, *awsSession.Config.Region) dockerLoginCmd := exec.Command("docker", "login", "-u", authTokenParts[0], "--password-stdin", dockerURL) dockerLoginCmd.Stdout = os.Stdout dockerLoginCmd.Stdin = bytes.NewReader([]byte(fmt.Sprintf("%s\n", authTokenParts[1]))) dockerLoginCmd.Stderr = os.Stderr dockerLoginCmdErr := system.RunOSCommand(dockerLoginCmd, logger) if dockerLoginCmdErr != nil { pushError = dockerLoginCmdErr } else { // Try it again... dockerRetryPushCmd := exec.Command("docker", "push", ecrTagValue) dockerRetryPushCmdErr := system.RunOSCommand(dockerRetryPushCmd, logger) pushError = dockerRetryPushCmdErr } } } } if pushError != nil { pushError = errors.Wrapf(pushError, "Attempting to push Docker image") } return ecrTagValue, pushError }
go
func PushDockerImageToECR(localImageTag string, ecrRepoName string, awsSession *session.Session, logger *logrus.Logger) (string, error) { stsSvc := sts.New(awsSession) ecrSvc := ecr.New(awsSession) // 1. Get the caller identity s.t. we can get the ECR URL which includes the // account name stsIdentityOutput, stsIdentityErr := stsSvc.GetCallerIdentity(&sts.GetCallerIdentityInput{}) if stsIdentityErr != nil { return "", errors.Wrapf(stsIdentityErr, "Attempting to get AWS caller identity") } // 2. Create the URL to which we're going to do the push localImageTagParts := strings.Split(localImageTag, ":") ecrTagValue := fmt.Sprintf("%s.dkr.ecr.%s.amazonaws.com/%s:%s", *stsIdentityOutput.Account, *awsSession.Config.Region, ecrRepoName, localImageTagParts[len(localImageTagParts)-1]) // 3. Tag the local image with the ECR tag dockerTagCmd := exec.Command("docker", "tag", localImageTag, ecrTagValue) dockerTagCmdErr := system.RunOSCommand(dockerTagCmd, logger) if dockerTagCmdErr != nil { return "", errors.Wrapf(dockerTagCmdErr, "Attempting to tag Docker image") } // 4. Push the image - if that fails attempt to reauthorize with the docker // client and try again var pushError error dockerPushCmd := exec.Command("docker", "push", ecrTagValue) pushError = system.RunOSCommand(dockerPushCmd, logger) if pushError != nil { logger.WithFields(logrus.Fields{ "Error": pushError, }).Info("ECR push failed - reauthorizing") ecrAuthTokenResult, ecrAuthTokenResultErr := ecrSvc.GetAuthorizationToken(&ecr.GetAuthorizationTokenInput{}) if ecrAuthTokenResultErr != nil { pushError = ecrAuthTokenResultErr } else { authData := ecrAuthTokenResult.AuthorizationData[0] authToken, authTokenErr := base64.StdEncoding.DecodeString(*authData.AuthorizationToken) if authTokenErr != nil { pushError = authTokenErr } else { authTokenString := string(authToken) authTokenParts := strings.Split(authTokenString, ":") dockerURL := fmt.Sprintf("https://%s.dkr.ecr.%s.amazonaws.com", *stsIdentityOutput.Account, *awsSession.Config.Region) dockerLoginCmd := exec.Command("docker", "login", "-u", authTokenParts[0], "--password-stdin", dockerURL) dockerLoginCmd.Stdout = os.Stdout dockerLoginCmd.Stdin = bytes.NewReader([]byte(fmt.Sprintf("%s\n", authTokenParts[1]))) dockerLoginCmd.Stderr = os.Stderr dockerLoginCmdErr := system.RunOSCommand(dockerLoginCmd, logger) if dockerLoginCmdErr != nil { pushError = dockerLoginCmdErr } else { // Try it again... dockerRetryPushCmd := exec.Command("docker", "push", ecrTagValue) dockerRetryPushCmdErr := system.RunOSCommand(dockerRetryPushCmd, logger) pushError = dockerRetryPushCmdErr } } } } if pushError != nil { pushError = errors.Wrapf(pushError, "Attempting to push Docker image") } return ecrTagValue, pushError }
[ "func", "PushDockerImageToECR", "(", "localImageTag", "string", ",", "ecrRepoName", "string", ",", "awsSession", "*", "session", ".", "Session", ",", "logger", "*", "logrus", ".", "Logger", ")", "(", "string", ",", "error", ")", "{", "stsSvc", ":=", "sts", ...
// PushDockerImageToECR pushes a local Docker image to an ECR repository
[ "PushDockerImageToECR", "pushes", "a", "local", "Docker", "image", "to", "an", "ECR", "repository" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/docker/docker.go#L133-L211
1,132
mweagle/Sparta
archetype/sns.go
OnSNSEvent
func (reactorFunc SNSReactorFunc) OnSNSEvent(ctx context.Context, snsEvent awsLambdaEvents.SNSEvent) (interface{}, error) { return reactorFunc(ctx, snsEvent) }
go
func (reactorFunc SNSReactorFunc) OnSNSEvent(ctx context.Context, snsEvent awsLambdaEvents.SNSEvent) (interface{}, error) { return reactorFunc(ctx, snsEvent) }
[ "func", "(", "reactorFunc", "SNSReactorFunc", ")", "OnSNSEvent", "(", "ctx", "context", ".", "Context", ",", "snsEvent", "awsLambdaEvents", ".", "SNSEvent", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "reactorFunc", "(", "ctx", ",", ...
// OnSNSEvent satisfies the SNSReactor interface
[ "OnSNSEvent", "satisfies", "the", "SNSReactor", "interface" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/archetype/sns.go#L28-L31
1,133
mweagle/Sparta
archetype/sns.go
NewSNSReactor
func NewSNSReactor(reactor SNSReactor, snsTopic gocf.Stringable, additionalLambdaPermissions []sparta.IAMRolePrivilege) (*sparta.LambdaAWSInfo, error) { reactorLambda := func(ctx context.Context, snsEvent awsLambdaEvents.SNSEvent) (interface{}, error) { return reactor.OnSNSEvent(ctx, snsEvent) } lambdaFn, lambdaFnErr := sparta.NewAWSLambda(reactorName(reactor), reactorLambda, sparta.IAMRoleDefinition{}) if lambdaFnErr != nil { return nil, errors.Wrapf(lambdaFnErr, "attempting to create reactor") } lambdaFn.Permissions = append(lambdaFn.Permissions, sparta.SNSPermission{ BasePermission: sparta.BasePermission{ SourceArn: snsTopic, }, }) if len(additionalLambdaPermissions) != 0 { lambdaFn.RoleDefinition.Privileges = additionalLambdaPermissions } return lambdaFn, nil }
go
func NewSNSReactor(reactor SNSReactor, snsTopic gocf.Stringable, additionalLambdaPermissions []sparta.IAMRolePrivilege) (*sparta.LambdaAWSInfo, error) { reactorLambda := func(ctx context.Context, snsEvent awsLambdaEvents.SNSEvent) (interface{}, error) { return reactor.OnSNSEvent(ctx, snsEvent) } lambdaFn, lambdaFnErr := sparta.NewAWSLambda(reactorName(reactor), reactorLambda, sparta.IAMRoleDefinition{}) if lambdaFnErr != nil { return nil, errors.Wrapf(lambdaFnErr, "attempting to create reactor") } lambdaFn.Permissions = append(lambdaFn.Permissions, sparta.SNSPermission{ BasePermission: sparta.BasePermission{ SourceArn: snsTopic, }, }) if len(additionalLambdaPermissions) != 0 { lambdaFn.RoleDefinition.Privileges = additionalLambdaPermissions } return lambdaFn, nil }
[ "func", "NewSNSReactor", "(", "reactor", "SNSReactor", ",", "snsTopic", "gocf", ".", "Stringable", ",", "additionalLambdaPermissions", "[", "]", "sparta", ".", "IAMRolePrivilege", ")", "(", "*", "sparta", ".", "LambdaAWSInfo", ",", "error", ")", "{", "reactorLam...
// NewSNSReactor returns an SNS reactor lambda function
[ "NewSNSReactor", "returns", "an", "SNS", "reactor", "lambda", "function" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/archetype/sns.go#L39-L63
1,134
mweagle/Sparta
system/goversion.go
GoVersion
func GoVersion(logger *logrus.Logger) (string, error) { runtimeVersion := runtime.Version() // Get the golang version from the output: // Matts-MBP:Sparta mweagle$ go version // go version go1.8.1 darwin/amd64 golangVersionRE := regexp.MustCompile(`go(\d+\.\d+(\.\d+)?)`) matches := golangVersionRE.FindStringSubmatch(runtimeVersion) if len(matches) > 2 { return matches[1], nil } logger.WithFields(logrus.Fields{ "Output": runtimeVersion, }).Warn("Unable to find Golang version using RegExp - using current version") return runtimeVersion, nil }
go
func GoVersion(logger *logrus.Logger) (string, error) { runtimeVersion := runtime.Version() // Get the golang version from the output: // Matts-MBP:Sparta mweagle$ go version // go version go1.8.1 darwin/amd64 golangVersionRE := regexp.MustCompile(`go(\d+\.\d+(\.\d+)?)`) matches := golangVersionRE.FindStringSubmatch(runtimeVersion) if len(matches) > 2 { return matches[1], nil } logger.WithFields(logrus.Fields{ "Output": runtimeVersion, }).Warn("Unable to find Golang version using RegExp - using current version") return runtimeVersion, nil }
[ "func", "GoVersion", "(", "logger", "*", "logrus", ".", "Logger", ")", "(", "string", ",", "error", ")", "{", "runtimeVersion", ":=", "runtime", ".", "Version", "(", ")", "\n", "// Get the golang version from the output:", "// Matts-MBP:Sparta mweagle$ go version", ...
// GoVersion returns the configured go version for this system
[ "GoVersion", "returns", "the", "configured", "go", "version", "for", "this", "system" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/system/goversion.go#L50-L64
1,135
mweagle/Sparta
system/goversion.go
TemporaryFile
func TemporaryFile(scratchDir string, name string) (*os.File, error) { workingDir, err := os.Getwd() if nil != err { return nil, err } // Use a stable temporary name temporaryPath := filepath.Join(workingDir, scratchDir, name) buildDir := filepath.Dir(temporaryPath) mkdirErr := os.MkdirAll(buildDir, os.ModePerm) if nil != mkdirErr { return nil, mkdirErr } tmpFile, err := os.Create(temporaryPath) if err != nil { return nil, errors.New("Failed to create temporary file: " + err.Error()) } return tmpFile, nil }
go
func TemporaryFile(scratchDir string, name string) (*os.File, error) { workingDir, err := os.Getwd() if nil != err { return nil, err } // Use a stable temporary name temporaryPath := filepath.Join(workingDir, scratchDir, name) buildDir := filepath.Dir(temporaryPath) mkdirErr := os.MkdirAll(buildDir, os.ModePerm) if nil != mkdirErr { return nil, mkdirErr } tmpFile, err := os.Create(temporaryPath) if err != nil { return nil, errors.New("Failed to create temporary file: " + err.Error()) } return tmpFile, nil }
[ "func", "TemporaryFile", "(", "scratchDir", "string", ",", "name", "string", ")", "(", "*", "os", ".", "File", ",", "error", ")", "{", "workingDir", ",", "err", ":=", "os", ".", "Getwd", "(", ")", "\n", "if", "nil", "!=", "err", "{", "return", "nil...
// TemporaryFile creates a stable temporary filename in the current working // directory
[ "TemporaryFile", "creates", "a", "stable", "temporary", "filename", "in", "the", "current", "working", "directory" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/system/goversion.go#L257-L277
1,136
mweagle/Sparta
aws/cloudformation/resources/s3LambdaEventSourceResource.go
Update
func (command S3LambdaEventSourceResource) Update(awsSession *session.Session, event *CloudFormationLambdaEvent, logger *logrus.Logger) (map[string]interface{}, error) { return command.updateNotification(true, awsSession, event, logger) }
go
func (command S3LambdaEventSourceResource) Update(awsSession *session.Session, event *CloudFormationLambdaEvent, logger *logrus.Logger) (map[string]interface{}, error) { return command.updateNotification(true, awsSession, event, logger) }
[ "func", "(", "command", "S3LambdaEventSourceResource", ")", "Update", "(", "awsSession", "*", "session", ".", "Session", ",", "event", "*", "CloudFormationLambdaEvent", ",", "logger", "*", "logrus", ".", "Logger", ")", "(", "map", "[", "string", "]", "interfac...
// Update implements the custom resource update operation
[ "Update", "implements", "the", "custom", "resource", "update", "operation" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/cloudformation/resources/s3LambdaEventSourceResource.go#L104-L108
1,137
mweagle/Sparta
aws/cloudwatch/logs/util.go
TailWithContext
func TailWithContext(reqContext aws.Context, closeChan chan bool, awsSession *session.Session, logGroupName string, filter string, logger *logrus.Logger) <-chan *cloudwatchlogs.FilteredLogEvent { // Milliseconds... lastSeenTimestamp := time.Now().Add(0).Unix() * 1000 logger.WithField("TS", lastSeenTimestamp).Debug("Started polling") outputChannel := make(chan *cloudwatchlogs.FilteredLogEvent) tailHandler := func(res *cloudwatchlogs.FilterLogEventsOutput, lastPage bool) bool { maxTime := int64(0) for _, eachEvent := range res.Events { if maxTime < *eachEvent.Timestamp { maxTime = *eachEvent.Timestamp } logger.WithField("ID", *eachEvent.EventId).Debug("Event") outputChannel <- eachEvent } if maxTime != 0 { lastSeenTimestamp = maxTime + 1 } return !lastPage } cwlogsSvc := cloudwatchlogs.New(awsSession) tickerChan := time.NewTicker(time.Millisecond * 333).C //AWS cloudwatch logs limit is 5tx/sec go func() { for { select { case <-closeChan: logger.Debug("Exiting polling loop") return case <-tickerChan: logParam := tailParams(logGroupName, filter, lastSeenTimestamp) error := cwlogsSvc.FilterLogEventsPagesWithContext(reqContext, logParam, tailHandler) if error != nil { // Just pump the thing back through the channel... errorEvent := &cloudwatchlogs.FilteredLogEvent{ EventId: aws.String("N/A"), Message: aws.String(error.Error()), Timestamp: aws.Int64(time.Now().Unix() * 1000), } outputChannel <- errorEvent } } } }() return outputChannel }
go
func TailWithContext(reqContext aws.Context, closeChan chan bool, awsSession *session.Session, logGroupName string, filter string, logger *logrus.Logger) <-chan *cloudwatchlogs.FilteredLogEvent { // Milliseconds... lastSeenTimestamp := time.Now().Add(0).Unix() * 1000 logger.WithField("TS", lastSeenTimestamp).Debug("Started polling") outputChannel := make(chan *cloudwatchlogs.FilteredLogEvent) tailHandler := func(res *cloudwatchlogs.FilterLogEventsOutput, lastPage bool) bool { maxTime := int64(0) for _, eachEvent := range res.Events { if maxTime < *eachEvent.Timestamp { maxTime = *eachEvent.Timestamp } logger.WithField("ID", *eachEvent.EventId).Debug("Event") outputChannel <- eachEvent } if maxTime != 0 { lastSeenTimestamp = maxTime + 1 } return !lastPage } cwlogsSvc := cloudwatchlogs.New(awsSession) tickerChan := time.NewTicker(time.Millisecond * 333).C //AWS cloudwatch logs limit is 5tx/sec go func() { for { select { case <-closeChan: logger.Debug("Exiting polling loop") return case <-tickerChan: logParam := tailParams(logGroupName, filter, lastSeenTimestamp) error := cwlogsSvc.FilterLogEventsPagesWithContext(reqContext, logParam, tailHandler) if error != nil { // Just pump the thing back through the channel... errorEvent := &cloudwatchlogs.FilteredLogEvent{ EventId: aws.String("N/A"), Message: aws.String(error.Error()), Timestamp: aws.Int64(time.Now().Unix() * 1000), } outputChannel <- errorEvent } } } }() return outputChannel }
[ "func", "TailWithContext", "(", "reqContext", "aws", ".", "Context", ",", "closeChan", "chan", "bool", ",", "awsSession", "*", "session", ".", "Session", ",", "logGroupName", "string", ",", "filter", "string", ",", "logger", "*", "logrus", ".", "Logger", ")"...
// TailWithContext is a utility function that support tailing the given log stream // name using the optional filter. It returns a channel for log messages
[ "TailWithContext", "is", "a", "utility", "function", "that", "support", "tailing", "the", "given", "log", "stream", "name", "using", "the", "optional", "filter", ".", "It", "returns", "a", "channel", "for", "log", "messages" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/cloudwatch/logs/util.go#L27-L77
1,138
mweagle/Sparta
magefile.go
DocsInstallRequirements
func DocsInstallRequirements() error { mg.SerialDeps(ensureWorkDir) // Is hugo already installed? spartamage.Log("Checking for Hugo version: %s", hugoVersion) hugoOutput, hugoOutputErr := sh.Output(hugoPath, "version") if hugoOutputErr == nil && strings.Contains(hugoOutput, hugoVersion) { spartamage.Log("Hugo version %s already installed at %s", hugoVersion, hugoPath) return nil } hugoArchiveName := "" switch runtime.GOOS { case "darwin": hugoArchiveName = "macOS-64bit.tar.gz" case "linux": hugoArchiveName = "Linux-64bit.tar.gz" default: hugoArchiveName = fmt.Sprintf("UNSUPPORTED_%s", runtime.GOOS) } hugoURL := fmt.Sprintf("https://github.com/gohugoio/hugo/releases/download/v%s/hugo_%s_%s", hugoVersion, hugoVersion, hugoArchiveName) spartamage.Log("Installing Hugo from source: %s", hugoURL) outputArchive := filepath.Join(localWorkDir, "hugo.tar.gz") outputFile, outputErr := os.Create(outputArchive) if outputErr != nil { return outputErr } hugoResp, hugoRespErr := http.Get(hugoURL) if hugoRespErr != nil { return hugoRespErr } defer hugoResp.Body.Close() _, copyBytesErr := io.Copy(outputFile, hugoResp.Body) if copyBytesErr != nil { return copyBytesErr } // Great, go heads and untar it... unarchiver := archiver.NewTarGz() unarchiver.OverwriteExisting = true untarErr := unarchiver.Unarchive(outputArchive, localWorkDir) if untarErr != nil { return untarErr } versionScript := [][]string{ {hugoPath, "version"}, } return spartamage.Script(versionScript) }
go
func DocsInstallRequirements() error { mg.SerialDeps(ensureWorkDir) // Is hugo already installed? spartamage.Log("Checking for Hugo version: %s", hugoVersion) hugoOutput, hugoOutputErr := sh.Output(hugoPath, "version") if hugoOutputErr == nil && strings.Contains(hugoOutput, hugoVersion) { spartamage.Log("Hugo version %s already installed at %s", hugoVersion, hugoPath) return nil } hugoArchiveName := "" switch runtime.GOOS { case "darwin": hugoArchiveName = "macOS-64bit.tar.gz" case "linux": hugoArchiveName = "Linux-64bit.tar.gz" default: hugoArchiveName = fmt.Sprintf("UNSUPPORTED_%s", runtime.GOOS) } hugoURL := fmt.Sprintf("https://github.com/gohugoio/hugo/releases/download/v%s/hugo_%s_%s", hugoVersion, hugoVersion, hugoArchiveName) spartamage.Log("Installing Hugo from source: %s", hugoURL) outputArchive := filepath.Join(localWorkDir, "hugo.tar.gz") outputFile, outputErr := os.Create(outputArchive) if outputErr != nil { return outputErr } hugoResp, hugoRespErr := http.Get(hugoURL) if hugoRespErr != nil { return hugoRespErr } defer hugoResp.Body.Close() _, copyBytesErr := io.Copy(outputFile, hugoResp.Body) if copyBytesErr != nil { return copyBytesErr } // Great, go heads and untar it... unarchiver := archiver.NewTarGz() unarchiver.OverwriteExisting = true untarErr := unarchiver.Unarchive(outputArchive, localWorkDir) if untarErr != nil { return untarErr } versionScript := [][]string{ {hugoPath, "version"}, } return spartamage.Script(versionScript) }
[ "func", "DocsInstallRequirements", "(", ")", "error", "{", "mg", ".", "SerialDeps", "(", "ensureWorkDir", ")", "\n\n", "// Is hugo already installed?", "spartamage", ".", "Log", "(", "\"", "\"", ",", "hugoVersion", ")", "\n\n", "hugoOutput", ",", "hugoOutputErr", ...
// DocsInstallRequirements installs the required Hugo version
[ "DocsInstallRequirements", "installs", "the", "required", "Hugo", "version" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/magefile.go#L125-L180
1,139
mweagle/Sparta
magefile.go
DocsCommit
func DocsCommit() error { mg.SerialDeps(DocsBuild) commitNoMessageScript := make([][]string, 0) for _, eachPath := range hugoDocsPaths { commitNoMessageScript = append(commitNoMessageScript, []string{"git", "add", "--all", eachPath}, ) } commitNoMessageScript = append(commitNoMessageScript, []string{"git", "commit", "-m", `"Documentation updates"`}, ) return spartamage.Script(commitNoMessageScript) }
go
func DocsCommit() error { mg.SerialDeps(DocsBuild) commitNoMessageScript := make([][]string, 0) for _, eachPath := range hugoDocsPaths { commitNoMessageScript = append(commitNoMessageScript, []string{"git", "add", "--all", eachPath}, ) } commitNoMessageScript = append(commitNoMessageScript, []string{"git", "commit", "-m", `"Documentation updates"`}, ) return spartamage.Script(commitNoMessageScript) }
[ "func", "DocsCommit", "(", ")", "error", "{", "mg", ".", "SerialDeps", "(", "DocsBuild", ")", "\n\n", "commitNoMessageScript", ":=", "make", "(", "[", "]", "[", "]", "string", ",", "0", ")", "\n", "for", "_", ",", "eachPath", ":=", "range", "hugoDocsPa...
// DocsCommit builds and commits the current // documentation with an autogenerated comment
[ "DocsCommit", "builds", "and", "commits", "the", "current", "documentation", "with", "an", "autogenerated", "comment" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/magefile.go#L201-L214
1,140
mweagle/Sparta
magefile.go
InstallBuildRequirements
func InstallBuildRequirements() error { spartamage.Log("`go get` update flags (env.GO_GET_FLAG): %s", os.Getenv("GO_GET_FLAG")) requirements := []string{ "github.com/golang/dep/...", "honnef.co/go/tools/...", "golang.org/x/tools/cmd/goimports", "github.com/fzipp/gocyclo", "golang.org/x/lint/golint", "github.com/mjibson/esc", "github.com/securego/gosec/cmd/gosec/...", "github.com/alexkohler/prealloc", "github.com/client9/misspell/cmd/misspell", } for _, eachDep := range requirements { cmdErr := sh.Run("go", "get", os.Getenv("GO_GET_FLAG"), eachDep) if cmdErr != nil { return cmdErr } } return nil }
go
func InstallBuildRequirements() error { spartamage.Log("`go get` update flags (env.GO_GET_FLAG): %s", os.Getenv("GO_GET_FLAG")) requirements := []string{ "github.com/golang/dep/...", "honnef.co/go/tools/...", "golang.org/x/tools/cmd/goimports", "github.com/fzipp/gocyclo", "golang.org/x/lint/golint", "github.com/mjibson/esc", "github.com/securego/gosec/cmd/gosec/...", "github.com/alexkohler/prealloc", "github.com/client9/misspell/cmd/misspell", } for _, eachDep := range requirements { cmdErr := sh.Run("go", "get", os.Getenv("GO_GET_FLAG"), eachDep) if cmdErr != nil { return cmdErr } } return nil }
[ "func", "InstallBuildRequirements", "(", ")", "error", "{", "spartamage", ".", "Log", "(", "\"", "\"", ",", "os", ".", "Getenv", "(", "\"", "\"", ")", ")", "\n\n", "requirements", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"...
// InstallBuildRequirements installs or updates the dependent // packages that aren't referenced by the source, but are needed // to build the Sparta source
[ "InstallBuildRequirements", "installs", "or", "updates", "the", "dependent", "packages", "that", "aren", "t", "referenced", "by", "the", "source", "but", "are", "needed", "to", "build", "the", "Sparta", "source" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/magefile.go#L329-L353
1,141
mweagle/Sparta
magefile.go
EnsureSpelling
func EnsureSpelling() error { goSpelling := func() error { return goSourceApply("misspell", "-error") } mg.SerialDeps( goSpelling, EnsureMarkdownSpelling) return nil }
go
func EnsureSpelling() error { goSpelling := func() error { return goSourceApply("misspell", "-error") } mg.SerialDeps( goSpelling, EnsureMarkdownSpelling) return nil }
[ "func", "EnsureSpelling", "(", ")", "error", "{", "goSpelling", ":=", "func", "(", ")", "error", "{", "return", "goSourceApply", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "mg", ".", "SerialDeps", "(", "goSpelling", ",", "EnsureMarkdownSpell...
// EnsureSpelling ensures that there are no misspellings in the source
[ "EnsureSpelling", "ensures", "that", "there", "are", "no", "misspellings", "in", "the", "source" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/magefile.go#L371-L379
1,142
mweagle/Sparta
magefile.go
EnsureFormatted
func EnsureFormatted() error { cmd := exec.Command("goimports", "-e", "-d", ".") var stdout, stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr err := cmd.Run() if err != nil { return err } if stdout.String() != "" { if mg.Verbose() { log.Print(stdout.String()) } return errors.New("`goimports -e -d .` found import errors. Run `goimports -e -w .` to fix them") } return nil }
go
func EnsureFormatted() error { cmd := exec.Command("goimports", "-e", "-d", ".") var stdout, stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr err := cmd.Run() if err != nil { return err } if stdout.String() != "" { if mg.Verbose() { log.Print(stdout.String()) } return errors.New("`goimports -e -d .` found import errors. Run `goimports -e -w .` to fix them") } return nil }
[ "func", "EnsureFormatted", "(", ")", "error", "{", "cmd", ":=", "exec", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "var", "stdout", ",", "stderr", "bytes", ".", "Buffer", "\n", "cmd", ".", "Stdo...
// EnsureFormatted ensures that the source code is formatted with goimports
[ "EnsureFormatted", "ensures", "that", "the", "source", "code", "is", "formatted", "with", "goimports" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/magefile.go#L411-L427
1,143
mweagle/Sparta
magefile.go
EnsureStaticChecks
func EnsureStaticChecks() error { // https://staticcheck.io/ staticCheckErr := sh.Run("staticcheck", "-ignore", "github.com/mweagle/Sparta/CONSTANTS.go:*", "github.com/mweagle/Sparta/...") if staticCheckErr != nil { return staticCheckErr } // https://github.com/securego/gosec if mg.Verbose() { return sh.Run("gosec", "-exclude=G204,G505,G401", "./...") } return sh.Run("gosec", "-exclude=G204,G505,G401", "-quiet", "./...") }
go
func EnsureStaticChecks() error { // https://staticcheck.io/ staticCheckErr := sh.Run("staticcheck", "-ignore", "github.com/mweagle/Sparta/CONSTANTS.go:*", "github.com/mweagle/Sparta/...") if staticCheckErr != nil { return staticCheckErr } // https://github.com/securego/gosec if mg.Verbose() { return sh.Run("gosec", "-exclude=G204,G505,G401", "./...") } return sh.Run("gosec", "-exclude=G204,G505,G401", "-quiet", "./...") }
[ "func", "EnsureStaticChecks", "(", ")", "error", "{", "// https://staticcheck.io/", "staticCheckErr", ":=", "sh", ".", "Run", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "staticCheckErr", "!=", "nil", "{", "return...
// EnsureStaticChecks ensures that the source code passes static code checks
[ "EnsureStaticChecks", "ensures", "that", "the", "source", "code", "passes", "static", "code", "checks" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/magefile.go#L430-L449
1,144
mweagle/Sparta
magefile.go
EnsureTravisBuildEnvironment
func EnsureTravisBuildEnvironment() error { mg.SerialDeps(InstallBuildRequirements) // Super run some commands travisComands := [][]string{ {"dep", "version"}, {"dep", "ensure", "-v"}, {"rsync", "-a", "--quiet", "--remove-source-files", "./vendor/", "$GOPATH/src"}, } return spartamage.Script(travisComands) }
go
func EnsureTravisBuildEnvironment() error { mg.SerialDeps(InstallBuildRequirements) // Super run some commands travisComands := [][]string{ {"dep", "version"}, {"dep", "ensure", "-v"}, {"rsync", "-a", "--quiet", "--remove-source-files", "./vendor/", "$GOPATH/src"}, } return spartamage.Script(travisComands) }
[ "func", "EnsureTravisBuildEnvironment", "(", ")", "error", "{", "mg", ".", "SerialDeps", "(", "InstallBuildRequirements", ")", "\n\n", "// Super run some commands", "travisComands", ":=", "[", "]", "[", "]", "string", "{", "{", "\"", "\"", ",", "\"", "\"", "}"...
// EnsureTravisBuildEnvironment is the command that sets up the Travis // environment to run the build.
[ "EnsureTravisBuildEnvironment", "is", "the", "command", "that", "sets", "up", "the", "Travis", "environment", "to", "run", "the", "build", "." ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/magefile.go#L474-L484
1,145
mweagle/Sparta
magefile.go
Publish
func Publish() error { mg.SerialDeps(DocsBuild, DocsCommit, GenerateBuildInfo) describeCommands := [][]string{ {"git", "push", "origin"}, } return spartamage.Script(describeCommands) }
go
func Publish() error { mg.SerialDeps(DocsBuild, DocsCommit, GenerateBuildInfo) describeCommands := [][]string{ {"git", "push", "origin"}, } return spartamage.Script(describeCommands) }
[ "func", "Publish", "(", ")", "error", "{", "mg", ".", "SerialDeps", "(", "DocsBuild", ",", "DocsCommit", ",", "GenerateBuildInfo", ")", "\n\n", "describeCommands", ":=", "[", "]", "[", "]", "string", "{", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", ...
// Publish the latest source
[ "Publish", "the", "latest", "source" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/magefile.go#L513-L522
1,146
mweagle/Sparta
magefile.go
CompareAgainstMasterBranch
func CompareAgainstMasterBranch() error { // Get the current branch, open a browser // to the change... // The first thing we need is the `git` branch cmd := exec.Command("git", "rev-parse", "--abbrev-ref", "HEAD") var stdout, stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr err := cmd.Run() if err != nil { return err } stdOutResult := strings.TrimSpace(string(stdout.Bytes())) githubURL := fmt.Sprintf("https://github.com/mweagle/Sparta/compare/master...%s", stdOutResult) return browser.OpenURL(githubURL) }
go
func CompareAgainstMasterBranch() error { // Get the current branch, open a browser // to the change... // The first thing we need is the `git` branch cmd := exec.Command("git", "rev-parse", "--abbrev-ref", "HEAD") var stdout, stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr err := cmd.Run() if err != nil { return err } stdOutResult := strings.TrimSpace(string(stdout.Bytes())) githubURL := fmt.Sprintf("https://github.com/mweagle/Sparta/compare/master...%s", stdOutResult) return browser.OpenURL(githubURL) }
[ "func", "CompareAgainstMasterBranch", "(", ")", "error", "{", "// Get the current branch, open a browser", "// to the change...", "// The first thing we need is the `git` branch", "cmd", ":=", "exec", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",...
// CompareAgainstMasterBranch is a convenience function to show the comparisons // of the current pushed branch against the master branch
[ "CompareAgainstMasterBranch", "is", "a", "convenience", "function", "to", "show", "the", "comparisons", "of", "the", "current", "pushed", "branch", "against", "the", "master", "branch" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/magefile.go#L564-L579
1,147
mweagle/Sparta
execute.go
awsLambdaInternalName
func awsLambdaInternalName(internalFunctionName string) string { var internalNameParts []string // If this is something that implements something else, trim the // leading * internalFunctionName = strings.TrimPrefix(internalFunctionName, "*") customTypeParts := reSplitCustomType.Split(internalFunctionName, -1) if len(customTypeParts) > 1 { internalNameParts = []string{customTypeParts[len(customTypeParts)-1]} } else { internalNameParts = reSplitFunctionName.Split(internalFunctionName, -1) } return strings.Join(internalNameParts, functionNameDelimiter) }
go
func awsLambdaInternalName(internalFunctionName string) string { var internalNameParts []string // If this is something that implements something else, trim the // leading * internalFunctionName = strings.TrimPrefix(internalFunctionName, "*") customTypeParts := reSplitCustomType.Split(internalFunctionName, -1) if len(customTypeParts) > 1 { internalNameParts = []string{customTypeParts[len(customTypeParts)-1]} } else { internalNameParts = reSplitFunctionName.Split(internalFunctionName, -1) } return strings.Join(internalNameParts, functionNameDelimiter) }
[ "func", "awsLambdaInternalName", "(", "internalFunctionName", "string", ")", "string", "{", "var", "internalNameParts", "[", "]", "string", "\n\n", "// If this is something that implements something else, trim the", "// leading *", "internalFunctionName", "=", "strings", ".", ...
// awsLambdaFunctionName returns the name of the function, which // is set in the CloudFormation template that is published // into the container as `AWS_LAMBDA_FUNCTION_NAME`. Rather // than publish custom vars which are editable in the Console, // tunneling this value through allows Sparta to leverage the // built in env vars.
[ "awsLambdaFunctionName", "returns", "the", "name", "of", "the", "function", "which", "is", "set", "in", "the", "CloudFormation", "template", "that", "is", "published", "into", "the", "container", "as", "AWS_LAMBDA_FUNCTION_NAME", ".", "Rather", "than", "publish", ...
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/execute.go#L39-L53
1,148
mweagle/Sparta
sparta_main_awsbinary.go
Delete
func Delete(serviceName string, logger *logrus.Logger) error { logger.Error("Delete() not supported in AWS Lambda binary") return errors.New("Delete not supported for this binary") }
go
func Delete(serviceName string, logger *logrus.Logger) error { logger.Error("Delete() not supported in AWS Lambda binary") return errors.New("Delete not supported for this binary") }
[ "func", "Delete", "(", "serviceName", "string", ",", "logger", "*", "logrus", ".", "Logger", ")", "error", "{", "logger", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// Delete is not available in the AWS Lambda binary
[ "Delete", "is", "not", "available", "in", "the", "AWS", "Lambda", "binary" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/sparta_main_awsbinary.go#L87-L90
1,149
mweagle/Sparta
sparta_main_awsbinary.go
Provision
func Provision(noop bool, serviceName string, serviceDescription string, lambdaAWSInfos []*LambdaAWSInfo, api *API, site *S3Site, s3Bucket string, useCGO bool, inplace bool, buildID string, codePipelineTrigger string, buildTags string, linkerFlags string, writer io.Writer, workflowHooks *WorkflowHooks, logger *logrus.Logger) error { logger.Error("Provision() not supported in AWS Lambda binary") return errors.New("Provision not supported for this binary") }
go
func Provision(noop bool, serviceName string, serviceDescription string, lambdaAWSInfos []*LambdaAWSInfo, api *API, site *S3Site, s3Bucket string, useCGO bool, inplace bool, buildID string, codePipelineTrigger string, buildTags string, linkerFlags string, writer io.Writer, workflowHooks *WorkflowHooks, logger *logrus.Logger) error { logger.Error("Provision() not supported in AWS Lambda binary") return errors.New("Provision not supported for this binary") }
[ "func", "Provision", "(", "noop", "bool", ",", "serviceName", "string", ",", "serviceDescription", "string", ",", "lambdaAWSInfos", "[", "]", "*", "LambdaAWSInfo", ",", "api", "*", "API", ",", "site", "*", "S3Site", ",", "s3Bucket", "string", ",", "useCGO", ...
// Provision is not available in the AWS Lambda binary
[ "Provision", "is", "not", "available", "in", "the", "AWS", "Lambda", "binary" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/sparta_main_awsbinary.go#L93-L111
1,150
mweagle/Sparta
sparta_main_awsbinary.go
Describe
func Describe(serviceName string, serviceDescription string, lambdaAWSInfos []*LambdaAWSInfo, api *API, site *S3Site, s3BucketName string, buildTags string, linkerFlags string, outputWriter io.Writer, workflowHooks *WorkflowHooks, logger *logrus.Logger) error { logger.Error("Describe() not supported in AWS Lambda binary") return errors.New("Describe not supported for this binary") }
go
func Describe(serviceName string, serviceDescription string, lambdaAWSInfos []*LambdaAWSInfo, api *API, site *S3Site, s3BucketName string, buildTags string, linkerFlags string, outputWriter io.Writer, workflowHooks *WorkflowHooks, logger *logrus.Logger) error { logger.Error("Describe() not supported in AWS Lambda binary") return errors.New("Describe not supported for this binary") }
[ "func", "Describe", "(", "serviceName", "string", ",", "serviceDescription", "string", ",", "lambdaAWSInfos", "[", "]", "*", "LambdaAWSInfo", ",", "api", "*", "API", ",", "site", "*", "S3Site", ",", "s3BucketName", "string", ",", "buildTags", "string", ",", ...
// Describe is not available in the AWS Lambda binary
[ "Describe", "is", "not", "available", "in", "the", "AWS", "Lambda", "binary" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/sparta_main_awsbinary.go#L114-L127
1,151
mweagle/Sparta
sparta_main_awsbinary.go
Explore
func Explore(serviceName string, serviceDescription string, lambdaAWSInfos []*LambdaAWSInfo, api *API, site *S3Site, s3BucketName string, buildTags string, linkerFlags string, logger *logrus.Logger) error { return errors.New("Explore not supported for this binary") }
go
func Explore(serviceName string, serviceDescription string, lambdaAWSInfos []*LambdaAWSInfo, api *API, site *S3Site, s3BucketName string, buildTags string, linkerFlags string, logger *logrus.Logger) error { return errors.New("Explore not supported for this binary") }
[ "func", "Explore", "(", "serviceName", "string", ",", "serviceDescription", "string", ",", "lambdaAWSInfos", "[", "]", "*", "LambdaAWSInfo", ",", "api", "*", "API", ",", "site", "*", "S3Site", ",", "s3BucketName", "string", ",", "buildTags", "string", ",", "...
// Explore is an interactive command that brings up a GUI to test // lambda functions previously deployed into AWS lambda. It's not supported in the // AWS binary build
[ "Explore", "is", "an", "interactive", "command", "that", "brings", "up", "a", "GUI", "to", "test", "lambda", "functions", "previously", "deployed", "into", "AWS", "lambda", ".", "It", "s", "not", "supported", "in", "the", "AWS", "binary", "build" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/sparta_main_awsbinary.go#L132-L142
1,152
mweagle/Sparta
sparta_main_awsbinary.go
Status
func Status(serviceName string, serviceDescription string, redact bool, logger *logrus.Logger) error { return errors.New("Status not supported for this binary") }
go
func Status(serviceName string, serviceDescription string, redact bool, logger *logrus.Logger) error { return errors.New("Status not supported for this binary") }
[ "func", "Status", "(", "serviceName", "string", ",", "serviceDescription", "string", ",", "redact", "bool", ",", "logger", "*", "logrus", ".", "Logger", ")", "error", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// Status is the command that produces a simple status report for a given // stack
[ "Status", "is", "the", "command", "that", "produces", "a", "simple", "status", "report", "for", "a", "given", "stack" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/sparta_main_awsbinary.go#L156-L161
1,153
mweagle/Sparta
apigateway.go
methodResponses
func methodResponses(api *API, userResponses map[int]*Response, corsEnabled bool) *gocf.APIGatewayMethodMethodResponseList { var responses gocf.APIGatewayMethodMethodResponseList for eachHTTPStatusCode, eachResponse := range userResponses { methodResponseParams := eachResponse.Parameters if corsEnabled { for eachString, eachBool := range corsMethodResponseParams(api) { methodResponseParams[eachString] = eachBool } } // Then transform them all to strings because internet methodResponseStringParams := make(map[string]string, len(methodResponseParams)) for eachKey, eachBool := range methodResponseParams { methodResponseStringParams[eachKey] = fmt.Sprintf("%t", eachBool) } methodResponse := gocf.APIGatewayMethodMethodResponse{ StatusCode: gocf.String(strconv.Itoa(eachHTTPStatusCode)), } if len(methodResponseStringParams) != 0 { methodResponse.ResponseParameters = methodResponseStringParams } responses = append(responses, methodResponse) } return &responses }
go
func methodResponses(api *API, userResponses map[int]*Response, corsEnabled bool) *gocf.APIGatewayMethodMethodResponseList { var responses gocf.APIGatewayMethodMethodResponseList for eachHTTPStatusCode, eachResponse := range userResponses { methodResponseParams := eachResponse.Parameters if corsEnabled { for eachString, eachBool := range corsMethodResponseParams(api) { methodResponseParams[eachString] = eachBool } } // Then transform them all to strings because internet methodResponseStringParams := make(map[string]string, len(methodResponseParams)) for eachKey, eachBool := range methodResponseParams { methodResponseStringParams[eachKey] = fmt.Sprintf("%t", eachBool) } methodResponse := gocf.APIGatewayMethodMethodResponse{ StatusCode: gocf.String(strconv.Itoa(eachHTTPStatusCode)), } if len(methodResponseStringParams) != 0 { methodResponse.ResponseParameters = methodResponseStringParams } responses = append(responses, methodResponse) } return &responses }
[ "func", "methodResponses", "(", "api", "*", "API", ",", "userResponses", "map", "[", "int", "]", "*", "Response", ",", "corsEnabled", "bool", ")", "*", "gocf", ".", "APIGatewayMethodMethodResponseList", "{", "var", "responses", "gocf", ".", "APIGatewayMethodMeth...
// DefaultMethodResponses returns the default set of Method HTTPStatus->Response // pass through responses. The successfulHTTPStatusCode param is the single // 2XX response code to use for the method.
[ "DefaultMethodResponses", "returns", "the", "default", "set", "of", "Method", "HTTPStatus", "-", ">", "Response", "pass", "through", "responses", ".", "The", "successfulHTTPStatusCode", "param", "is", "the", "single", "2XX", "response", "code", "to", "use", "for",...
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/apigateway.go#L77-L101
1,154
mweagle/Sparta
apigateway.go
RestAPIURL
func (api *API) RestAPIURL() *gocf.StringExpr { return gocf.Join("", gocf.String("https://"), gocf.Ref(api.LogicalResourceName()), gocf.String(".execute-api."), gocf.Ref("AWS::Region"), gocf.String(".amazonaws.com")) }
go
func (api *API) RestAPIURL() *gocf.StringExpr { return gocf.Join("", gocf.String("https://"), gocf.Ref(api.LogicalResourceName()), gocf.String(".execute-api."), gocf.Ref("AWS::Region"), gocf.String(".amazonaws.com")) }
[ "func", "(", "api", "*", "API", ")", "RestAPIURL", "(", ")", "*", "gocf", ".", "StringExpr", "{", "return", "gocf", ".", "Join", "(", "\"", "\"", ",", "gocf", ".", "String", "(", "\"", "\"", ")", ",", "gocf", ".", "Ref", "(", "api", ".", "Logic...
// RestAPIURL returns the dynamically assigned // Rest API URL including the scheme
[ "RestAPIURL", "returns", "the", "dynamically", "assigned", "Rest", "API", "URL", "including", "the", "scheme" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/apigateway.go#L484-L491
1,155
mweagle/Sparta
apigateway.go
NewAPIGateway
func NewAPIGateway(name string, stage *Stage) *API { return &API{ name: name, stage: stage, resources: make(map[string]*Resource), CORSEnabled: false, CORSOptions: nil, } }
go
func NewAPIGateway(name string, stage *Stage) *API { return &API{ name: name, stage: stage, resources: make(map[string]*Resource), CORSEnabled: false, CORSOptions: nil, } }
[ "func", "NewAPIGateway", "(", "name", "string", ",", "stage", "*", "Stage", ")", "*", "API", "{", "return", "&", "API", "{", "name", ":", "name", ",", "stage", ":", "stage", ",", "resources", ":", "make", "(", "map", "[", "string", "]", "*", "Resou...
// NewAPIGateway returns a new API Gateway structure. If stage is defined, the API Gateway // will also be deployed as part of stack creation.
[ "NewAPIGateway", "returns", "a", "new", "API", "Gateway", "structure", ".", "If", "stage", "is", "defined", "the", "API", "Gateway", "will", "also", "be", "deployed", "as", "part", "of", "stack", "creation", "." ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/apigateway.go#L716-L724
1,156
mweagle/Sparta
apigateway.go
NewAuthorizedMethod
func (resource *Resource) NewAuthorizedMethod(httpMethod string, authorizerID gocf.Stringable, defaultHTTPStatusCode int, possibleHTTPStatusCodeResponses ...int) (*Method, error) { if authorizerID == nil { return nil, fmt.Errorf("authorizerID must not be `nil` for Authorized Method") } method, methodErr := resource.NewMethod(httpMethod, defaultHTTPStatusCode, possibleHTTPStatusCodeResponses...) if methodErr == nil { method.authorizationID = authorizerID } return method, methodErr }
go
func (resource *Resource) NewAuthorizedMethod(httpMethod string, authorizerID gocf.Stringable, defaultHTTPStatusCode int, possibleHTTPStatusCodeResponses ...int) (*Method, error) { if authorizerID == nil { return nil, fmt.Errorf("authorizerID must not be `nil` for Authorized Method") } method, methodErr := resource.NewMethod(httpMethod, defaultHTTPStatusCode, possibleHTTPStatusCodeResponses...) if methodErr == nil { method.authorizationID = authorizerID } return method, methodErr }
[ "func", "(", "resource", "*", "Resource", ")", "NewAuthorizedMethod", "(", "httpMethod", "string", ",", "authorizerID", "gocf", ".", "Stringable", ",", "defaultHTTPStatusCode", "int", ",", "possibleHTTPStatusCodeResponses", "...", "int", ")", "(", "*", "Method", "...
// NewAuthorizedMethod associates the httpMethod name and authorizationID with // the given Resource. The authorizerID param is a cloudformation.Strinable // satisfying value
[ "NewAuthorizedMethod", "associates", "the", "httpMethod", "name", "and", "authorizationID", "with", "the", "given", "Resource", ".", "The", "authorizerID", "param", "is", "a", "cloudformation", ".", "Strinable", "satisfying", "value" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/apigateway.go#L867-L881
1,157
mweagle/Sparta
aws/step/sqs.go
NewSQSTaskState
func NewSQSTaskState(stateName string, parameters SQSTaskParameters) *SQSTaskState { sns := &SQSTaskState{ BaseTask: BaseTask{ baseInnerState: baseInnerState{ name: stateName, id: rand.Int63(), }, }, parameters: parameters, } return sns }
go
func NewSQSTaskState(stateName string, parameters SQSTaskParameters) *SQSTaskState { sns := &SQSTaskState{ BaseTask: BaseTask{ baseInnerState: baseInnerState{ name: stateName, id: rand.Int63(), }, }, parameters: parameters, } return sns }
[ "func", "NewSQSTaskState", "(", "stateName", "string", ",", "parameters", "SQSTaskParameters", ")", "*", "SQSTaskState", "{", "sns", ":=", "&", "SQSTaskState", "{", "BaseTask", ":", "BaseTask", "{", "baseInnerState", ":", "baseInnerState", "{", "name", ":", "sta...
// NewSQSTaskState returns an initialized SQSTaskState
[ "NewSQSTaskState", "returns", "an", "initialized", "SQSTaskState" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/sqs.go#L36-L48
1,158
mweagle/Sparta
aws/cloudformation/resources/customResource.go
CloudFormationLambdaCustomResourceHandler
func CloudFormationLambdaCustomResourceHandler(command CustomResourceCommand, logger *logrus.Logger) interface{} { return func(ctx context.Context, event CloudFormationLambdaEvent) error { lambdaCtx, lambdaCtxOk := awsLambdaCtx.FromContext(ctx) if !lambdaCtxOk { return errors.Errorf("Failed to access AWS Lambda Context from ctx argument") } customResourceSession := awsSession(logger) var opResults map[string]interface{} var opErr error executeOperation := false // If we're in cleanup mode, then skip it... // Don't forward to the CustomAction handler iff we're in CLEANUP mode describeStacksInput := &cloudformation.DescribeStacksInput{ StackName: aws.String(event.StackID), } cfSvc := cloudformation.New(customResourceSession) describeStacksOutput, describeStacksOutputErr := cfSvc.DescribeStacks(describeStacksInput) if nil != describeStacksOutputErr { opErr = describeStacksOutputErr } else { stackDesc := describeStacksOutput.Stacks[0] if stackDesc == nil { opErr = errors.Errorf("DescribeStack failed: %s", event.StackID) } else { executeOperation = (*stackDesc.StackStatus != "UPDATE_COMPLETE_CLEANUP_IN_PROGRESS") } } logger.WithFields(logrus.Fields{ "ExecuteOperation": event.LogicalResourceID, "Stacks": fmt.Sprintf("%#+v", describeStacksOutput), "RequestType": event.RequestType, }).Debug("CustomResource Request") if opErr == nil && executeOperation { switch event.RequestType { case CreateOperation: opResults, opErr = command.Create(customResourceSession, &event, logger) case DeleteOperation: opResults, opErr = command.Delete(customResourceSession, &event, logger) case UpdateOperation: opResults, opErr = command.Update(customResourceSession, &event, logger) } } // Notify CloudFormation of the result if event.ResponseURL != "" { sendErr := SendCloudFormationResponse(lambdaCtx, &event, opResults, opErr, logger) if nil != sendErr { logger.WithFields(logrus.Fields{ "Error": sendErr.Error(), "URL": event.ResponseURL, }).Info("Failed to ACK status to CloudFormation") } else { // If the cloudformation notification was complete, then this // execution functioned properly and we can clear the Error opErr = nil } } return opErr } }
go
func CloudFormationLambdaCustomResourceHandler(command CustomResourceCommand, logger *logrus.Logger) interface{} { return func(ctx context.Context, event CloudFormationLambdaEvent) error { lambdaCtx, lambdaCtxOk := awsLambdaCtx.FromContext(ctx) if !lambdaCtxOk { return errors.Errorf("Failed to access AWS Lambda Context from ctx argument") } customResourceSession := awsSession(logger) var opResults map[string]interface{} var opErr error executeOperation := false // If we're in cleanup mode, then skip it... // Don't forward to the CustomAction handler iff we're in CLEANUP mode describeStacksInput := &cloudformation.DescribeStacksInput{ StackName: aws.String(event.StackID), } cfSvc := cloudformation.New(customResourceSession) describeStacksOutput, describeStacksOutputErr := cfSvc.DescribeStacks(describeStacksInput) if nil != describeStacksOutputErr { opErr = describeStacksOutputErr } else { stackDesc := describeStacksOutput.Stacks[0] if stackDesc == nil { opErr = errors.Errorf("DescribeStack failed: %s", event.StackID) } else { executeOperation = (*stackDesc.StackStatus != "UPDATE_COMPLETE_CLEANUP_IN_PROGRESS") } } logger.WithFields(logrus.Fields{ "ExecuteOperation": event.LogicalResourceID, "Stacks": fmt.Sprintf("%#+v", describeStacksOutput), "RequestType": event.RequestType, }).Debug("CustomResource Request") if opErr == nil && executeOperation { switch event.RequestType { case CreateOperation: opResults, opErr = command.Create(customResourceSession, &event, logger) case DeleteOperation: opResults, opErr = command.Delete(customResourceSession, &event, logger) case UpdateOperation: opResults, opErr = command.Update(customResourceSession, &event, logger) } } // Notify CloudFormation of the result if event.ResponseURL != "" { sendErr := SendCloudFormationResponse(lambdaCtx, &event, opResults, opErr, logger) if nil != sendErr { logger.WithFields(logrus.Fields{ "Error": sendErr.Error(), "URL": event.ResponseURL, }).Info("Failed to ACK status to CloudFormation") } else { // If the cloudformation notification was complete, then this // execution functioned properly and we can clear the Error opErr = nil } } return opErr } }
[ "func", "CloudFormationLambdaCustomResourceHandler", "(", "command", "CustomResourceCommand", ",", "logger", "*", "logrus", ".", "Logger", ")", "interface", "{", "}", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "event", "CloudFormationLambdaEv...
// CloudFormationLambdaCustomResourceHandler is an adapter // function that transforms an implementing CustomResourceCommand // into something that that can respond to the lambda custom // resource lifecycle
[ "CloudFormationLambdaCustomResourceHandler", "is", "an", "adapter", "function", "that", "transforms", "an", "implementing", "CustomResourceCommand", "into", "something", "that", "that", "can", "respond", "to", "the", "lambda", "custom", "resource", "lifecycle" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/cloudformation/resources/customResource.go#L290-L355
1,159
mweagle/Sparta
aws/cloudformation/resources/customResource.go
NewCustomResourceLambdaHandler
func NewCustomResourceLambdaHandler(resourceType string, logger *logrus.Logger) interface{} { // TODO - eliminate this factory stuff and just register // the custom resources as normal lambda handlers... var lambdaCmd CustomResourceCommand cfResource := customTypeProvider(resourceType) if cfResource != nil { cmd, cmdOK := cfResource.(CustomResourceCommand) if cmdOK { lambdaCmd = cmd } } if lambdaCmd == nil { return errors.Errorf("Custom resource handler not found for type: %s", resourceType) } return CloudFormationLambdaCustomResourceHandler(lambdaCmd, logger) }
go
func NewCustomResourceLambdaHandler(resourceType string, logger *logrus.Logger) interface{} { // TODO - eliminate this factory stuff and just register // the custom resources as normal lambda handlers... var lambdaCmd CustomResourceCommand cfResource := customTypeProvider(resourceType) if cfResource != nil { cmd, cmdOK := cfResource.(CustomResourceCommand) if cmdOK { lambdaCmd = cmd } } if lambdaCmd == nil { return errors.Errorf("Custom resource handler not found for type: %s", resourceType) } return CloudFormationLambdaCustomResourceHandler(lambdaCmd, logger) }
[ "func", "NewCustomResourceLambdaHandler", "(", "resourceType", "string", ",", "logger", "*", "logrus", ".", "Logger", ")", "interface", "{", "}", "{", "// TODO - eliminate this factory stuff and just register", "// the custom resources as normal lambda handlers...", "var", "lam...
// NewCustomResourceLambdaHandler returns a handler for the given // type
[ "NewCustomResourceLambdaHandler", "returns", "a", "handler", "for", "the", "given", "type" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/cloudformation/resources/customResource.go#L359-L375
1,160
mweagle/Sparta
aws/step/fargate.go
NewFargateTaskState
func NewFargateTaskState(stateName string, parameters FargateTaskParameters) *FargateTaskState { ft := &FargateTaskState{ BaseTask: BaseTask{ baseInnerState: baseInnerState{ name: stateName, id: rand.Int63(), }, }, parameters: parameters, } return ft }
go
func NewFargateTaskState(stateName string, parameters FargateTaskParameters) *FargateTaskState { ft := &FargateTaskState{ BaseTask: BaseTask{ baseInnerState: baseInnerState{ name: stateName, id: rand.Int63(), }, }, parameters: parameters, } return ft }
[ "func", "NewFargateTaskState", "(", "stateName", "string", ",", "parameters", "FargateTaskParameters", ")", "*", "FargateTaskState", "{", "ft", ":=", "&", "FargateTaskState", "{", "BaseTask", ":", "BaseTask", "{", "baseInnerState", ":", "baseInnerState", "{", "name"...
// NewFargateTaskState returns an initialized FargateTaskState
[ "NewFargateTaskState", "returns", "an", "initialized", "FargateTaskState" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/fargate.go#L44-L55
1,161
mweagle/Sparta
interceptor/xray.go
RegisterXRayInterceptor
func RegisterXRayInterceptor(handler *sparta.LambdaEventInterceptors, mode XRayInterceptorMode) *sparta.LambdaEventInterceptors { interceptor := &xrayInterceptor{ mode: mode, } if handler == nil { handler = &sparta.LambdaEventInterceptors{} } return handler.Register(interceptor) }
go
func RegisterXRayInterceptor(handler *sparta.LambdaEventInterceptors, mode XRayInterceptorMode) *sparta.LambdaEventInterceptors { interceptor := &xrayInterceptor{ mode: mode, } if handler == nil { handler = &sparta.LambdaEventInterceptors{} } return handler.Register(interceptor) }
[ "func", "RegisterXRayInterceptor", "(", "handler", "*", "sparta", ".", "LambdaEventInterceptors", ",", "mode", "XRayInterceptorMode", ")", "*", "sparta", ".", "LambdaEventInterceptors", "{", "interceptor", ":=", "&", "xrayInterceptor", "{", "mode", ":", "mode", ",",...
// RegisterXRayInterceptor handles pushing the tracing information into XRay
[ "RegisterXRayInterceptor", "handles", "pushing", "the", "tracing", "information", "into", "XRay" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/interceptor/xray.go#L119-L128
1,162
mweagle/Sparta
provision_build.go
recordDuration
func recordDuration(start time.Time, name string, ctx *workflowContext) { elapsed := time.Since(start) ctx.transaction.stepDurations = append(ctx.transaction.stepDurations, &workflowStepDuration{ name: name, duration: elapsed, }) }
go
func recordDuration(start time.Time, name string, ctx *workflowContext) { elapsed := time.Since(start) ctx.transaction.stepDurations = append(ctx.transaction.stepDurations, &workflowStepDuration{ name: name, duration: elapsed, }) }
[ "func", "recordDuration", "(", "start", "time", ".", "Time", ",", "name", "string", ",", "ctx", "*", "workflowContext", ")", "{", "elapsed", ":=", "time", ".", "Since", "(", "start", ")", "\n", "ctx", ".", "transaction", ".", "stepDurations", "=", "appen...
// recordDuration is a utility function to record how long
[ "recordDuration", "is", "a", "utility", "function", "to", "record", "how", "long" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/provision_build.go#L215-L222
1,163
mweagle/Sparta
provision_build.go
registerFileCleanupFinalizer
func (ctx *workflowContext) registerFileCleanupFinalizer(localPath string) { cleanup := func(logger *logrus.Logger) { errRemove := os.Remove(localPath) if nil != errRemove { logger.WithFields(logrus.Fields{ "Path": localPath, "Error": errRemove, }).Warn("Failed to cleanup intermediate artifact") } else { logger.WithFields(logrus.Fields{ "Path": relativePath(localPath), }).Debug("Build artifact deleted") } } ctx.registerFinalizer(cleanup) }
go
func (ctx *workflowContext) registerFileCleanupFinalizer(localPath string) { cleanup := func(logger *logrus.Logger) { errRemove := os.Remove(localPath) if nil != errRemove { logger.WithFields(logrus.Fields{ "Path": localPath, "Error": errRemove, }).Warn("Failed to cleanup intermediate artifact") } else { logger.WithFields(logrus.Fields{ "Path": relativePath(localPath), }).Debug("Build artifact deleted") } } ctx.registerFinalizer(cleanup) }
[ "func", "(", "ctx", "*", "workflowContext", ")", "registerFileCleanupFinalizer", "(", "localPath", "string", ")", "{", "cleanup", ":=", "func", "(", "logger", "*", "logrus", ".", "Logger", ")", "{", "errRemove", ":=", "os", ".", "Remove", "(", "localPath", ...
// Register a finalizer that cleans up local artifacts
[ "Register", "a", "finalizer", "that", "cleans", "up", "local", "artifacts" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/provision_build.go#L243-L258
1,164
mweagle/Sparta
provision_build.go
rollback
func (ctx *workflowContext) rollback() { defer recordDuration(time.Now(), "Rollback", ctx) // Run each cleanup function concurrently. If there's an error // all we're going to do is log it as a warning, since at this // point there's nothing to do... ctx.logger.Info("Invoking rollback functions") var wg sync.WaitGroup wg.Add(len(ctx.transaction.rollbackFunctions)) rollbackErr := callRollbackHook(ctx, &wg) if rollbackErr != nil { ctx.logger.WithFields(logrus.Fields{ "Error": rollbackErr, }).Warning("Rollback Hook failed to execute") } for _, eachCleanup := range ctx.transaction.rollbackFunctions { go func(cleanupFunc spartaS3.RollbackFunction, goLogger *logrus.Logger) { // Decrement the counter when the goroutine completes. defer wg.Done() // Fetch the URL. err := cleanupFunc(goLogger) if nil != err { ctx.logger.WithFields(logrus.Fields{ "Error": err, }).Warning("Failed to cleanup resource") } }(eachCleanup, ctx.logger) } wg.Wait() }
go
func (ctx *workflowContext) rollback() { defer recordDuration(time.Now(), "Rollback", ctx) // Run each cleanup function concurrently. If there's an error // all we're going to do is log it as a warning, since at this // point there's nothing to do... ctx.logger.Info("Invoking rollback functions") var wg sync.WaitGroup wg.Add(len(ctx.transaction.rollbackFunctions)) rollbackErr := callRollbackHook(ctx, &wg) if rollbackErr != nil { ctx.logger.WithFields(logrus.Fields{ "Error": rollbackErr, }).Warning("Rollback Hook failed to execute") } for _, eachCleanup := range ctx.transaction.rollbackFunctions { go func(cleanupFunc spartaS3.RollbackFunction, goLogger *logrus.Logger) { // Decrement the counter when the goroutine completes. defer wg.Done() // Fetch the URL. err := cleanupFunc(goLogger) if nil != err { ctx.logger.WithFields(logrus.Fields{ "Error": err, }).Warning("Failed to cleanup resource") } }(eachCleanup, ctx.logger) } wg.Wait() }
[ "func", "(", "ctx", "*", "workflowContext", ")", "rollback", "(", ")", "{", "defer", "recordDuration", "(", "time", ".", "Now", "(", ")", ",", "\"", "\"", ",", "ctx", ")", "\n\n", "// Run each cleanup function concurrently. If there's an error", "// all we're goi...
// Run any provided rollback functions
[ "Run", "any", "provided", "rollback", "functions" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/provision_build.go#L261-L290
1,165
mweagle/Sparta
provision_build.go
callRollbackHook
func callRollbackHook(ctx *workflowContext, wg *sync.WaitGroup) error { if ctx.userdata.workflowHooks == nil { return nil } rollbackHooks := ctx.userdata.workflowHooks.Rollbacks if ctx.userdata.workflowHooks.Rollback != nil { ctx.logger.Warn("DEPRECATED: Single RollbackHook superseded by RollbackHookHandler slice") rollbackHooks = append(rollbackHooks, RollbackHookFunc(ctx.userdata.workflowHooks.Rollback)) } for _, eachRollbackHook := range rollbackHooks { wg.Add(1) go func(handler RollbackHookHandler, context map[string]interface{}, serviceName string, awsSession *session.Session, noop bool, logger *logrus.Logger) { // Decrement the counter when the goroutine completes. defer wg.Done() rollbackErr := handler.Rollback(context, serviceName, awsSession, noop, logger) logger.WithFields(logrus.Fields{ "Error": rollbackErr, }).Warn("Rollback function failed to complete") }(eachRollbackHook, ctx.context.workflowHooksContext, ctx.userdata.serviceName, ctx.context.awsSession, ctx.userdata.noop, ctx.logger) } return nil }
go
func callRollbackHook(ctx *workflowContext, wg *sync.WaitGroup) error { if ctx.userdata.workflowHooks == nil { return nil } rollbackHooks := ctx.userdata.workflowHooks.Rollbacks if ctx.userdata.workflowHooks.Rollback != nil { ctx.logger.Warn("DEPRECATED: Single RollbackHook superseded by RollbackHookHandler slice") rollbackHooks = append(rollbackHooks, RollbackHookFunc(ctx.userdata.workflowHooks.Rollback)) } for _, eachRollbackHook := range rollbackHooks { wg.Add(1) go func(handler RollbackHookHandler, context map[string]interface{}, serviceName string, awsSession *session.Session, noop bool, logger *logrus.Logger) { // Decrement the counter when the goroutine completes. defer wg.Done() rollbackErr := handler.Rollback(context, serviceName, awsSession, noop, logger) logger.WithFields(logrus.Fields{ "Error": rollbackErr, }).Warn("Rollback function failed to complete") }(eachRollbackHook, ctx.context.workflowHooksContext, ctx.userdata.serviceName, ctx.context.awsSession, ctx.userdata.noop, ctx.logger) } return nil }
[ "func", "callRollbackHook", "(", "ctx", "*", "workflowContext", ",", "wg", "*", "sync", ".", "WaitGroup", ")", "error", "{", "if", "ctx", ".", "userdata", ".", "workflowHooks", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "rollbackHooks", ":=", "c...
// Encapsulate calling the rollback hooks
[ "Encapsulate", "calling", "the", "rollback", "hooks" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/provision_build.go#L308-L343
1,166
mweagle/Sparta
provision_build.go
callServiceDecoratorHook
func callServiceDecoratorHook(ctx *workflowContext) error { if ctx.userdata.workflowHooks == nil { return nil } serviceHooks := ctx.userdata.workflowHooks.ServiceDecorators if ctx.userdata.workflowHooks.ServiceDecorator != nil { ctx.logger.Warn("DEPRECATED: Single ServiceDecorator hook superseded by ServiceDecorators slice") serviceHooks = append(serviceHooks, ServiceDecoratorHookFunc(ctx.userdata.workflowHooks.ServiceDecorator)) } // If there's an API gateway definition, include the resources that provision it. // Since this export will likely // generate outputs that the s3 site needs, we'll use a temporary outputs accumulator, // pass that to the S3Site // if it's defined, and then merge it with the normal output map.- for _, eachServiceHook := range serviceHooks { hookName := runtime.FuncForPC(reflect.ValueOf(eachServiceHook).Pointer()).Name() ctx.logger.WithFields(logrus.Fields{ "ServiceDecoratorHook": hookName, "WorkflowHookContext": ctx.context.workflowHooksContext, }).Info("Calling WorkflowHook") serviceTemplate := gocf.NewTemplate() decoratorError := eachServiceHook.DecorateService(ctx.context.workflowHooksContext, ctx.userdata.serviceName, serviceTemplate, ctx.userdata.s3Bucket, codeZipKey(ctx.context.s3CodeZipURL), ctx.userdata.buildID, ctx.context.awsSession, ctx.userdata.noop, ctx.logger) if nil != decoratorError { return decoratorError } safeMergeErrs := gocc.SafeMerge(serviceTemplate, ctx.context.cfTemplate) if len(safeMergeErrs) != 0 { return errors.Errorf("Failed to merge templates: %#v", safeMergeErrs) } } return nil }
go
func callServiceDecoratorHook(ctx *workflowContext) error { if ctx.userdata.workflowHooks == nil { return nil } serviceHooks := ctx.userdata.workflowHooks.ServiceDecorators if ctx.userdata.workflowHooks.ServiceDecorator != nil { ctx.logger.Warn("DEPRECATED: Single ServiceDecorator hook superseded by ServiceDecorators slice") serviceHooks = append(serviceHooks, ServiceDecoratorHookFunc(ctx.userdata.workflowHooks.ServiceDecorator)) } // If there's an API gateway definition, include the resources that provision it. // Since this export will likely // generate outputs that the s3 site needs, we'll use a temporary outputs accumulator, // pass that to the S3Site // if it's defined, and then merge it with the normal output map.- for _, eachServiceHook := range serviceHooks { hookName := runtime.FuncForPC(reflect.ValueOf(eachServiceHook).Pointer()).Name() ctx.logger.WithFields(logrus.Fields{ "ServiceDecoratorHook": hookName, "WorkflowHookContext": ctx.context.workflowHooksContext, }).Info("Calling WorkflowHook") serviceTemplate := gocf.NewTemplate() decoratorError := eachServiceHook.DecorateService(ctx.context.workflowHooksContext, ctx.userdata.serviceName, serviceTemplate, ctx.userdata.s3Bucket, codeZipKey(ctx.context.s3CodeZipURL), ctx.userdata.buildID, ctx.context.awsSession, ctx.userdata.noop, ctx.logger) if nil != decoratorError { return decoratorError } safeMergeErrs := gocc.SafeMerge(serviceTemplate, ctx.context.cfTemplate) if len(safeMergeErrs) != 0 { return errors.Errorf("Failed to merge templates: %#v", safeMergeErrs) } } return nil }
[ "func", "callServiceDecoratorHook", "(", "ctx", "*", "workflowContext", ")", "error", "{", "if", "ctx", ".", "userdata", ".", "workflowHooks", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "serviceHooks", ":=", "ctx", ".", "userdata", ".", "workflowHoo...
// Encapsulate calling the service decorator hooks
[ "Encapsulate", "calling", "the", "service", "decorator", "hooks" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/provision_build.go#L346-L387
1,167
mweagle/Sparta
provision_build.go
callArchiveHook
func callArchiveHook(lambdaArchive *zip.Writer, ctx *workflowContext) error { if ctx.userdata.workflowHooks == nil { return nil } archiveHooks := ctx.userdata.workflowHooks.Archives if ctx.userdata.workflowHooks.Archive != nil { ctx.logger.Warn("DEPRECATED: Single ArchiveHook hook superseded by ArchiveHooks slice") archiveHooks = append(archiveHooks, ArchiveHookFunc(ctx.userdata.workflowHooks.Archive)) } for _, eachArchiveHook := range archiveHooks { // Run the hook ctx.logger.WithFields(logrus.Fields{ "WorkflowHookContext": ctx.context.workflowHooksContext, }).Info("Calling ArchiveHook") hookErr := eachArchiveHook.DecorateArchive(ctx.context.workflowHooksContext, ctx.userdata.serviceName, lambdaArchive, ctx.context.awsSession, ctx.userdata.noop, ctx.logger) if hookErr != nil { return errors.Wrapf(hookErr, "DecorateArchive returned an error") } } return nil }
go
func callArchiveHook(lambdaArchive *zip.Writer, ctx *workflowContext) error { if ctx.userdata.workflowHooks == nil { return nil } archiveHooks := ctx.userdata.workflowHooks.Archives if ctx.userdata.workflowHooks.Archive != nil { ctx.logger.Warn("DEPRECATED: Single ArchiveHook hook superseded by ArchiveHooks slice") archiveHooks = append(archiveHooks, ArchiveHookFunc(ctx.userdata.workflowHooks.Archive)) } for _, eachArchiveHook := range archiveHooks { // Run the hook ctx.logger.WithFields(logrus.Fields{ "WorkflowHookContext": ctx.context.workflowHooksContext, }).Info("Calling ArchiveHook") hookErr := eachArchiveHook.DecorateArchive(ctx.context.workflowHooksContext, ctx.userdata.serviceName, lambdaArchive, ctx.context.awsSession, ctx.userdata.noop, ctx.logger) if hookErr != nil { return errors.Wrapf(hookErr, "DecorateArchive returned an error") } } return nil }
[ "func", "callArchiveHook", "(", "lambdaArchive", "*", "zip", ".", "Writer", ",", "ctx", "*", "workflowContext", ")", "error", "{", "if", "ctx", ".", "userdata", ".", "workflowHooks", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "archiveHooks", ":=",...
// Encapsulate calling the archive hooks
[ "Encapsulate", "calling", "the", "archive", "hooks" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/provision_build.go#L390-L418
1,168
mweagle/Sparta
provision_build.go
callWorkflowHook
func callWorkflowHook(hookPhase string, hook WorkflowHook, hooks []WorkflowHookHandler, ctx *workflowContext) error { if hook != nil { ctx.logger.Warn(fmt.Sprintf("DEPRECATED: Single %s hook superseded by %ss slice", hookPhase, hookPhase)) hooks = append(hooks, WorkflowHookFunc(hook)) } for _, eachHook := range hooks { // Run the hook ctx.logger.WithFields(logrus.Fields{ "Phase": hookPhase, "WorkflowHookContext": ctx.context.workflowHooksContext, }).Info("Calling WorkflowHook") hookErr := eachHook.DecorateWorkflow(ctx.context.workflowHooksContext, ctx.userdata.serviceName, ctx.userdata.s3Bucket, ctx.userdata.buildID, ctx.context.awsSession, ctx.userdata.noop, ctx.logger) if hookErr != nil { return errors.Wrapf(hookErr, "DecorateWorkflow returned an error") } } return nil }
go
func callWorkflowHook(hookPhase string, hook WorkflowHook, hooks []WorkflowHookHandler, ctx *workflowContext) error { if hook != nil { ctx.logger.Warn(fmt.Sprintf("DEPRECATED: Single %s hook superseded by %ss slice", hookPhase, hookPhase)) hooks = append(hooks, WorkflowHookFunc(hook)) } for _, eachHook := range hooks { // Run the hook ctx.logger.WithFields(logrus.Fields{ "Phase": hookPhase, "WorkflowHookContext": ctx.context.workflowHooksContext, }).Info("Calling WorkflowHook") hookErr := eachHook.DecorateWorkflow(ctx.context.workflowHooksContext, ctx.userdata.serviceName, ctx.userdata.s3Bucket, ctx.userdata.buildID, ctx.context.awsSession, ctx.userdata.noop, ctx.logger) if hookErr != nil { return errors.Wrapf(hookErr, "DecorateWorkflow returned an error") } } return nil }
[ "func", "callWorkflowHook", "(", "hookPhase", "string", ",", "hook", "WorkflowHook", ",", "hooks", "[", "]", "WorkflowHookHandler", ",", "ctx", "*", "workflowContext", ")", "error", "{", "if", "hook", "!=", "nil", "{", "ctx", ".", "logger", ".", "Warn", "(...
// Encapsulate calling a workflow hook
[ "Encapsulate", "calling", "a", "workflow", "hook" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/provision_build.go#L421-L451
1,169
mweagle/Sparta
provision_build.go
callValidationHooks
func callValidationHooks(validationHooks []ServiceValidationHookHandler, template *gocf.Template, ctx *workflowContext) error { var marshaledTemplate []byte if len(validationHooks) != 0 { jsonBytes, jsonBytesErr := json.Marshal(template) if jsonBytesErr != nil { return errors.Wrapf(jsonBytesErr, "Failed to marshal template for validation") } marshaledTemplate = jsonBytes } for _, eachHook := range validationHooks { // Run the hook ctx.logger.WithFields(logrus.Fields{ "Phase": "Validation", "ValidationHookContext": ctx.context.workflowHooksContext, }).Info("Calling WorkflowHook") var loopTemplate gocf.Template unmarshalErr := json.Unmarshal(marshaledTemplate, &loopTemplate) if unmarshalErr != nil { return errors.Wrapf(unmarshalErr, "Failed to unmarshal read-only copy of template for Validation") } hookErr := eachHook.ValidateService(ctx.context.workflowHooksContext, ctx.userdata.serviceName, &loopTemplate, ctx.userdata.s3Bucket, codeZipKey(ctx.context.s3CodeZipURL), ctx.userdata.buildID, ctx.context.awsSession, ctx.userdata.noop, ctx.logger) if hookErr != nil { return errors.Wrapf(hookErr, "Service failed to pass validation") } } return nil }
go
func callValidationHooks(validationHooks []ServiceValidationHookHandler, template *gocf.Template, ctx *workflowContext) error { var marshaledTemplate []byte if len(validationHooks) != 0 { jsonBytes, jsonBytesErr := json.Marshal(template) if jsonBytesErr != nil { return errors.Wrapf(jsonBytesErr, "Failed to marshal template for validation") } marshaledTemplate = jsonBytes } for _, eachHook := range validationHooks { // Run the hook ctx.logger.WithFields(logrus.Fields{ "Phase": "Validation", "ValidationHookContext": ctx.context.workflowHooksContext, }).Info("Calling WorkflowHook") var loopTemplate gocf.Template unmarshalErr := json.Unmarshal(marshaledTemplate, &loopTemplate) if unmarshalErr != nil { return errors.Wrapf(unmarshalErr, "Failed to unmarshal read-only copy of template for Validation") } hookErr := eachHook.ValidateService(ctx.context.workflowHooksContext, ctx.userdata.serviceName, &loopTemplate, ctx.userdata.s3Bucket, codeZipKey(ctx.context.s3CodeZipURL), ctx.userdata.buildID, ctx.context.awsSession, ctx.userdata.noop, ctx.logger) if hookErr != nil { return errors.Wrapf(hookErr, "Service failed to pass validation") } } return nil }
[ "func", "callValidationHooks", "(", "validationHooks", "[", "]", "ServiceValidationHookHandler", ",", "template", "*", "gocf", ".", "Template", ",", "ctx", "*", "workflowContext", ")", "error", "{", "var", "marshaledTemplate", "[", "]", "byte", "\n", "if", "len"...
// Encapsulate calling the validation hooks
[ "Encapsulate", "calling", "the", "validation", "hooks" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/provision_build.go#L454-L495
1,170
mweagle/Sparta
provision_build.go
versionAwareS3KeyName
func versionAwareS3KeyName(s3DefaultKey string, s3VersioningEnabled bool, logger *logrus.Logger) (string, error) { versionKeyName := s3DefaultKey if !s3VersioningEnabled { var extension = path.Ext(s3DefaultKey) var prefixString = strings.TrimSuffix(s3DefaultKey, extension) hash := sha1.New() salt := fmt.Sprintf("%s-%d", s3DefaultKey, time.Now().UnixNano()) _, writeErr := hash.Write([]byte(salt)) if writeErr != nil { return "", errors.Wrapf(writeErr, "Failed to update hash digest") } versionKeyName = fmt.Sprintf("%s-%s%s", prefixString, hex.EncodeToString(hash.Sum(nil)), extension) logger.WithFields(logrus.Fields{ "Default": s3DefaultKey, "Extension": extension, "PrefixString": prefixString, "Unique": versionKeyName, }).Debug("Created unique S3 keyname") } return versionKeyName, nil }
go
func versionAwareS3KeyName(s3DefaultKey string, s3VersioningEnabled bool, logger *logrus.Logger) (string, error) { versionKeyName := s3DefaultKey if !s3VersioningEnabled { var extension = path.Ext(s3DefaultKey) var prefixString = strings.TrimSuffix(s3DefaultKey, extension) hash := sha1.New() salt := fmt.Sprintf("%s-%d", s3DefaultKey, time.Now().UnixNano()) _, writeErr := hash.Write([]byte(salt)) if writeErr != nil { return "", errors.Wrapf(writeErr, "Failed to update hash digest") } versionKeyName = fmt.Sprintf("%s-%s%s", prefixString, hex.EncodeToString(hash.Sum(nil)), extension) logger.WithFields(logrus.Fields{ "Default": s3DefaultKey, "Extension": extension, "PrefixString": prefixString, "Unique": versionKeyName, }).Debug("Created unique S3 keyname") } return versionKeyName, nil }
[ "func", "versionAwareS3KeyName", "(", "s3DefaultKey", "string", ",", "s3VersioningEnabled", "bool", ",", "logger", "*", "logrus", ".", "Logger", ")", "(", "string", ",", "error", ")", "{", "versionKeyName", ":=", "s3DefaultKey", "\n", "if", "!", "s3VersioningEna...
// versionAwareS3KeyName returns a keyname that provides the correct cache // invalidation semantics based on whether the target bucket // has versioning enabled
[ "versionAwareS3KeyName", "returns", "a", "keyname", "that", "provides", "the", "correct", "cache", "invalidation", "semantics", "based", "on", "whether", "the", "target", "bucket", "has", "versioning", "enabled" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/provision_build.go#L500-L525
1,171
mweagle/Sparta
provision_build.go
uploadLocalFileToS3
func uploadLocalFileToS3(localPath string, s3ObjectKey string, ctx *workflowContext) (string, error) { // If versioning is enabled, use a stable name, otherwise use a name // that's dynamically created. By default assume that the bucket is // enabled for versioning if s3ObjectKey == "" { defaultS3KeyName := fmt.Sprintf("%s/%s", ctx.userdata.serviceName, filepath.Base(localPath)) s3KeyName, s3KeyNameErr := versionAwareS3KeyName(defaultS3KeyName, ctx.context.s3BucketVersioningEnabled, ctx.logger) if nil != s3KeyNameErr { return "", errors.Wrapf(s3KeyNameErr, "Failed to create version aware S3 keyname") } s3ObjectKey = s3KeyName } s3URL := "" if ctx.userdata.noop { // Binary size filesize := int64(0) stat, statErr := os.Stat(localPath) if statErr == nil { filesize = stat.Size() } ctx.logger.WithFields(logrus.Fields{ "Bucket": ctx.userdata.s3Bucket, "Key": s3ObjectKey, "File": filepath.Base(localPath), "Size": humanize.Bytes(uint64(filesize)), }).Info(noopMessage("S3 upload")) s3URL = fmt.Sprintf("https://%s-s3.amazonaws.com/%s", ctx.userdata.s3Bucket, s3ObjectKey) } else { // Make sure we mark things for cleanup in case there's a problem ctx.registerFileCleanupFinalizer(localPath) // Then upload it uploadLocation, uploadURLErr := spartaS3.UploadLocalFileToS3(localPath, ctx.context.awsSession, ctx.userdata.s3Bucket, s3ObjectKey, ctx.logger) if nil != uploadURLErr { return "", errors.Wrapf(uploadURLErr, "Failed to upload local file to S3") } s3URL = uploadLocation ctx.registerRollback(spartaS3.CreateS3RollbackFunc(ctx.context.awsSession, uploadLocation)) } return s3URL, nil }
go
func uploadLocalFileToS3(localPath string, s3ObjectKey string, ctx *workflowContext) (string, error) { // If versioning is enabled, use a stable name, otherwise use a name // that's dynamically created. By default assume that the bucket is // enabled for versioning if s3ObjectKey == "" { defaultS3KeyName := fmt.Sprintf("%s/%s", ctx.userdata.serviceName, filepath.Base(localPath)) s3KeyName, s3KeyNameErr := versionAwareS3KeyName(defaultS3KeyName, ctx.context.s3BucketVersioningEnabled, ctx.logger) if nil != s3KeyNameErr { return "", errors.Wrapf(s3KeyNameErr, "Failed to create version aware S3 keyname") } s3ObjectKey = s3KeyName } s3URL := "" if ctx.userdata.noop { // Binary size filesize := int64(0) stat, statErr := os.Stat(localPath) if statErr == nil { filesize = stat.Size() } ctx.logger.WithFields(logrus.Fields{ "Bucket": ctx.userdata.s3Bucket, "Key": s3ObjectKey, "File": filepath.Base(localPath), "Size": humanize.Bytes(uint64(filesize)), }).Info(noopMessage("S3 upload")) s3URL = fmt.Sprintf("https://%s-s3.amazonaws.com/%s", ctx.userdata.s3Bucket, s3ObjectKey) } else { // Make sure we mark things for cleanup in case there's a problem ctx.registerFileCleanupFinalizer(localPath) // Then upload it uploadLocation, uploadURLErr := spartaS3.UploadLocalFileToS3(localPath, ctx.context.awsSession, ctx.userdata.s3Bucket, s3ObjectKey, ctx.logger) if nil != uploadURLErr { return "", errors.Wrapf(uploadURLErr, "Failed to upload local file to S3") } s3URL = uploadLocation ctx.registerRollback(spartaS3.CreateS3RollbackFunc(ctx.context.awsSession, uploadLocation)) } return s3URL, nil }
[ "func", "uploadLocalFileToS3", "(", "localPath", "string", ",", "s3ObjectKey", "string", ",", "ctx", "*", "workflowContext", ")", "(", "string", ",", "error", ")", "{", "// If versioning is enabled, use a stable name, otherwise use a name", "// that's dynamically created. By ...
// Upload a local file to S3. Returns the full S3 URL to the file that was // uploaded. If the target bucket does not have versioning enabled, // this function will automatically make a new key to ensure uniqueness
[ "Upload", "a", "local", "file", "to", "S3", ".", "Returns", "the", "full", "S3", "URL", "to", "the", "file", "that", "was", "uploaded", ".", "If", "the", "target", "bucket", "does", "not", "have", "versioning", "enabled", "this", "function", "will", "aut...
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/provision_build.go#L530-L580
1,172
mweagle/Sparta
provision_build.go
createPackageStep
func createPackageStep() workflowStep { return func(ctx *workflowContext) (workflowStep, error) { defer recordDuration(time.Now(), "Creating code bundle", ctx) // PreBuild Hook if ctx.userdata.workflowHooks != nil { preBuildErr := callWorkflowHook("PreBuild", ctx.userdata.workflowHooks.PreBuild, ctx.userdata.workflowHooks.PreBuilds, ctx) if nil != preBuildErr { return nil, preBuildErr } } sanitizedServiceName := sanitizedName(ctx.userdata.serviceName) buildErr := system.BuildGoBinary(ctx.userdata.serviceName, ctx.context.binaryName, ctx.userdata.useCGO, ctx.userdata.buildID, ctx.userdata.buildTags, ctx.userdata.linkFlags, ctx.userdata.noop, ctx.logger) if nil != buildErr { return nil, buildErr } // Cleanup the temporary binary defer func() { errRemove := os.Remove(ctx.context.binaryName) if nil != errRemove { ctx.logger.WithFields(logrus.Fields{ "File": ctx.context.binaryName, "Error": errRemove, }).Warn("Failed to delete binary") } }() // PostBuild Hook if ctx.userdata.workflowHooks != nil { postBuildErr := callWorkflowHook("PostBuild", ctx.userdata.workflowHooks.PostBuild, ctx.userdata.workflowHooks.PostBuilds, ctx) if nil != postBuildErr { return nil, postBuildErr } } tmpFile, err := system.TemporaryFile(ScratchDirectory, fmt.Sprintf("%s-code.zip", sanitizedServiceName)) if err != nil { return nil, err } // Strip the local directory in case it's in there... ctx.logger.WithFields(logrus.Fields{ "TempName": relativePath(tmpFile.Name()), }).Info("Creating code ZIP archive for upload") lambdaArchive := zip.NewWriter(tmpFile) // Archive Hook archiveErr := callArchiveHook(lambdaArchive, ctx) if nil != archiveErr { return nil, archiveErr } // Issue: https://github.com/mweagle/Sparta/issues/103. If the executable // bit isn't set, then AWS Lambda won't be able to fork the binary var fileHeaderAnnotator spartaZip.FileHeaderAnnotator if runtime.GOOS == "windows" { fileHeaderAnnotator = func(header *zip.FileHeader) (*zip.FileHeader, error) { // Make the binary executable // Ref: https://github.com/aws/aws-lambda-go/blob/master/cmd/build-lambda-zip/main.go#L51 header.CreatorVersion = 3 << 8 header.ExternalAttrs = 0777 << 16 return header, nil } } // File info for the binary executable readerErr := spartaZip.AnnotateAddToZip(lambdaArchive, ctx.context.binaryName, "", fileHeaderAnnotator, ctx.logger) if nil != readerErr { return nil, readerErr } archiveCloseErr := lambdaArchive.Close() if nil != archiveCloseErr { return nil, archiveCloseErr } tempfileCloseErr := tmpFile.Close() if nil != tempfileCloseErr { return nil, tempfileCloseErr } return createUploadStep(tmpFile.Name()), nil } }
go
func createPackageStep() workflowStep { return func(ctx *workflowContext) (workflowStep, error) { defer recordDuration(time.Now(), "Creating code bundle", ctx) // PreBuild Hook if ctx.userdata.workflowHooks != nil { preBuildErr := callWorkflowHook("PreBuild", ctx.userdata.workflowHooks.PreBuild, ctx.userdata.workflowHooks.PreBuilds, ctx) if nil != preBuildErr { return nil, preBuildErr } } sanitizedServiceName := sanitizedName(ctx.userdata.serviceName) buildErr := system.BuildGoBinary(ctx.userdata.serviceName, ctx.context.binaryName, ctx.userdata.useCGO, ctx.userdata.buildID, ctx.userdata.buildTags, ctx.userdata.linkFlags, ctx.userdata.noop, ctx.logger) if nil != buildErr { return nil, buildErr } // Cleanup the temporary binary defer func() { errRemove := os.Remove(ctx.context.binaryName) if nil != errRemove { ctx.logger.WithFields(logrus.Fields{ "File": ctx.context.binaryName, "Error": errRemove, }).Warn("Failed to delete binary") } }() // PostBuild Hook if ctx.userdata.workflowHooks != nil { postBuildErr := callWorkflowHook("PostBuild", ctx.userdata.workflowHooks.PostBuild, ctx.userdata.workflowHooks.PostBuilds, ctx) if nil != postBuildErr { return nil, postBuildErr } } tmpFile, err := system.TemporaryFile(ScratchDirectory, fmt.Sprintf("%s-code.zip", sanitizedServiceName)) if err != nil { return nil, err } // Strip the local directory in case it's in there... ctx.logger.WithFields(logrus.Fields{ "TempName": relativePath(tmpFile.Name()), }).Info("Creating code ZIP archive for upload") lambdaArchive := zip.NewWriter(tmpFile) // Archive Hook archiveErr := callArchiveHook(lambdaArchive, ctx) if nil != archiveErr { return nil, archiveErr } // Issue: https://github.com/mweagle/Sparta/issues/103. If the executable // bit isn't set, then AWS Lambda won't be able to fork the binary var fileHeaderAnnotator spartaZip.FileHeaderAnnotator if runtime.GOOS == "windows" { fileHeaderAnnotator = func(header *zip.FileHeader) (*zip.FileHeader, error) { // Make the binary executable // Ref: https://github.com/aws/aws-lambda-go/blob/master/cmd/build-lambda-zip/main.go#L51 header.CreatorVersion = 3 << 8 header.ExternalAttrs = 0777 << 16 return header, nil } } // File info for the binary executable readerErr := spartaZip.AnnotateAddToZip(lambdaArchive, ctx.context.binaryName, "", fileHeaderAnnotator, ctx.logger) if nil != readerErr { return nil, readerErr } archiveCloseErr := lambdaArchive.Close() if nil != archiveCloseErr { return nil, archiveCloseErr } tempfileCloseErr := tmpFile.Close() if nil != tempfileCloseErr { return nil, tempfileCloseErr } return createUploadStep(tmpFile.Name()), nil } }
[ "func", "createPackageStep", "(", ")", "workflowStep", "{", "return", "func", "(", "ctx", "*", "workflowContext", ")", "(", "workflowStep", ",", "error", ")", "{", "defer", "recordDuration", "(", "time", ".", "Now", "(", ")", ",", "\"", "\"", ",", "ctx",...
// Build and package the application
[ "Build", "and", "package", "the", "application" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/provision_build.go#L803-L897
1,173
mweagle/Sparta
provision_build.go
maximumStackOperationTimeout
func maximumStackOperationTimeout(template *gocf.Template, logger *logrus.Logger) time.Duration { stackOperationTimeout := 20 * time.Minute // If there is a CloudFront distributon in there then // let's give that a bit more time to settle down...In general // the initial CloudFront distribution takes ~30 minutes for _, eachResource := range template.Resources { if eachResource.Properties.CfnResourceType() == "AWS::CloudFront::Distribution" { stackOperationTimeout = 60 * time.Minute break } } logger.WithField("OperationTimeout", stackOperationTimeout).Debug("Computed operation timeout value") return stackOperationTimeout }
go
func maximumStackOperationTimeout(template *gocf.Template, logger *logrus.Logger) time.Duration { stackOperationTimeout := 20 * time.Minute // If there is a CloudFront distributon in there then // let's give that a bit more time to settle down...In general // the initial CloudFront distribution takes ~30 minutes for _, eachResource := range template.Resources { if eachResource.Properties.CfnResourceType() == "AWS::CloudFront::Distribution" { stackOperationTimeout = 60 * time.Minute break } } logger.WithField("OperationTimeout", stackOperationTimeout).Debug("Computed operation timeout value") return stackOperationTimeout }
[ "func", "maximumStackOperationTimeout", "(", "template", "*", "gocf", ".", "Template", ",", "logger", "*", "logrus", ".", "Logger", ")", "time", ".", "Duration", "{", "stackOperationTimeout", ":=", "20", "*", "time", ".", "Minute", "\n", "// If there is a CloudF...
// maximumStackOperationTimeout returns the timeout // value to use for a stack operation based on the type // of resources that it provisions. In general the timeout // is short with an exception made for CloudFront // distributions
[ "maximumStackOperationTimeout", "returns", "the", "timeout", "value", "to", "use", "for", "a", "stack", "operation", "based", "on", "the", "type", "of", "resources", "that", "it", "provisions", ".", "In", "general", "the", "timeout", "is", "short", "with", "an...
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/provision_build.go#L992-L1005
1,174
mweagle/Sparta
provision_build.go
createCodePipelineTriggerPackage
func createCodePipelineTriggerPackage(cfTemplateJSON []byte, ctx *workflowContext) (string, error) { tmpFile, err := system.TemporaryFile(ScratchDirectory, ctx.userdata.codePipelineTrigger) if err != nil { return "", errors.Wrapf(err, "Failed to create temporary file for CodePipeline") } ctx.logger.WithFields(logrus.Fields{ "PipelineName": tmpFile.Name(), }).Info("Creating pipeline archive") templateArchive := zip.NewWriter(tmpFile) ctx.logger.WithFields(logrus.Fields{ "Path": tmpFile.Name(), }).Info("Creating CodePipeline archive") // File info for the binary executable zipEntryName := "cloudformation.json" bytesWriter, bytesWriterErr := templateArchive.Create(zipEntryName) if bytesWriterErr != nil { return "", bytesWriterErr } bytesReader := bytes.NewReader(cfTemplateJSON) written, writtenErr := io.Copy(bytesWriter, bytesReader) if nil != writtenErr { return "", writtenErr } ctx.logger.WithFields(logrus.Fields{ "WrittenBytes": written, "ZipName": zipEntryName, }).Debug("Archiving file") // If there is a codePipelineEnvironments defined, then we'll need to get all the // maps, marshal them to JSON, then add the JSON to the ZIP archive. if nil != codePipelineEnvironments { for eachEnvironment, eachMap := range codePipelineEnvironments { codePipelineParameters := map[string]interface{}{ "Parameters": eachMap, } environmentJSON, environmentJSONErr := json.Marshal(codePipelineParameters) if nil != environmentJSONErr { ctx.logger.Error("Failed to Marshal CodePipeline environment: " + eachEnvironment) return "", environmentJSONErr } var envVarName = fmt.Sprintf("%s.json", eachEnvironment) // File info for the binary executable binaryWriter, binaryWriterErr := templateArchive.Create(envVarName) if binaryWriterErr != nil { return "", binaryWriterErr } _, writeErr := binaryWriter.Write(environmentJSON) if writeErr != nil { return "", writeErr } } } archiveCloseErr := templateArchive.Close() if nil != archiveCloseErr { return "", archiveCloseErr } tempfileCloseErr := tmpFile.Close() if nil != tempfileCloseErr { return "", tempfileCloseErr } // Leave it here... ctx.logger.WithFields(logrus.Fields{ "File": filepath.Base(tmpFile.Name()), }).Info("Created CodePipeline archive") // The key is the name + the pipeline name return tmpFile.Name(), nil }
go
func createCodePipelineTriggerPackage(cfTemplateJSON []byte, ctx *workflowContext) (string, error) { tmpFile, err := system.TemporaryFile(ScratchDirectory, ctx.userdata.codePipelineTrigger) if err != nil { return "", errors.Wrapf(err, "Failed to create temporary file for CodePipeline") } ctx.logger.WithFields(logrus.Fields{ "PipelineName": tmpFile.Name(), }).Info("Creating pipeline archive") templateArchive := zip.NewWriter(tmpFile) ctx.logger.WithFields(logrus.Fields{ "Path": tmpFile.Name(), }).Info("Creating CodePipeline archive") // File info for the binary executable zipEntryName := "cloudformation.json" bytesWriter, bytesWriterErr := templateArchive.Create(zipEntryName) if bytesWriterErr != nil { return "", bytesWriterErr } bytesReader := bytes.NewReader(cfTemplateJSON) written, writtenErr := io.Copy(bytesWriter, bytesReader) if nil != writtenErr { return "", writtenErr } ctx.logger.WithFields(logrus.Fields{ "WrittenBytes": written, "ZipName": zipEntryName, }).Debug("Archiving file") // If there is a codePipelineEnvironments defined, then we'll need to get all the // maps, marshal them to JSON, then add the JSON to the ZIP archive. if nil != codePipelineEnvironments { for eachEnvironment, eachMap := range codePipelineEnvironments { codePipelineParameters := map[string]interface{}{ "Parameters": eachMap, } environmentJSON, environmentJSONErr := json.Marshal(codePipelineParameters) if nil != environmentJSONErr { ctx.logger.Error("Failed to Marshal CodePipeline environment: " + eachEnvironment) return "", environmentJSONErr } var envVarName = fmt.Sprintf("%s.json", eachEnvironment) // File info for the binary executable binaryWriter, binaryWriterErr := templateArchive.Create(envVarName) if binaryWriterErr != nil { return "", binaryWriterErr } _, writeErr := binaryWriter.Write(environmentJSON) if writeErr != nil { return "", writeErr } } } archiveCloseErr := templateArchive.Close() if nil != archiveCloseErr { return "", archiveCloseErr } tempfileCloseErr := tmpFile.Close() if nil != tempfileCloseErr { return "", tempfileCloseErr } // Leave it here... ctx.logger.WithFields(logrus.Fields{ "File": filepath.Base(tmpFile.Name()), }).Info("Created CodePipeline archive") // The key is the name + the pipeline name return tmpFile.Name(), nil }
[ "func", "createCodePipelineTriggerPackage", "(", "cfTemplateJSON", "[", "]", "byte", ",", "ctx", "*", "workflowContext", ")", "(", "string", ",", "error", ")", "{", "tmpFile", ",", "err", ":=", "system", ".", "TemporaryFile", "(", "ScratchDirectory", ",", "ctx...
// createCodePipelineTriggerPackage handles marshaling the template, zipping // the config files in the package, and the
[ "createCodePipelineTriggerPackage", "handles", "marshaling", "the", "template", "zipping", "the", "config", "files", "in", "the", "package", "and", "the" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/provision_build.go#L1009-L1080
1,175
mweagle/Sparta
aws/step/step.go
marshalStateJSON
func (bis *baseInnerState) marshalStateJSON(stateType string, additionalData map[string]interface{}) ([]byte, error) { if additionalData == nil { additionalData = make(map[string]interface{}) } additionalData["Type"] = stateType if bis.next != nil { additionalData["Next"] = bis.next.Name() } if bis.comment != "" { additionalData["Comment"] = bis.comment } if bis.inputPath != "" { additionalData["InputPath"] = bis.inputPath } if bis.outputPath != "" { additionalData["OutputPath"] = bis.outputPath } if !bis.isEndStateInvalid && bis.next == nil { additionalData["End"] = true } // Output the pretty version return json.Marshal(additionalData) }
go
func (bis *baseInnerState) marshalStateJSON(stateType string, additionalData map[string]interface{}) ([]byte, error) { if additionalData == nil { additionalData = make(map[string]interface{}) } additionalData["Type"] = stateType if bis.next != nil { additionalData["Next"] = bis.next.Name() } if bis.comment != "" { additionalData["Comment"] = bis.comment } if bis.inputPath != "" { additionalData["InputPath"] = bis.inputPath } if bis.outputPath != "" { additionalData["OutputPath"] = bis.outputPath } if !bis.isEndStateInvalid && bis.next == nil { additionalData["End"] = true } // Output the pretty version return json.Marshal(additionalData) }
[ "func", "(", "bis", "*", "baseInnerState", ")", "marshalStateJSON", "(", "stateType", "string", ",", "additionalData", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "additionalData", "==", "ni...
// marshalStateJSON for subclass marshalling of state information
[ "marshalStateJSON", "for", "subclass", "marshalling", "of", "state", "information" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L542-L565
1,176
mweagle/Sparta
aws/step/step.go
NewPassState
func NewPassState(name string, resultData interface{}) *PassState { return &PassState{ baseInnerState: baseInnerState{ name: name, id: rand.Int63(), }, Result: resultData, } }
go
func NewPassState(name string, resultData interface{}) *PassState { return &PassState{ baseInnerState: baseInnerState{ name: name, id: rand.Int63(), }, Result: resultData, } }
[ "func", "NewPassState", "(", "name", "string", ",", "resultData", "interface", "{", "}", ")", "*", "PassState", "{", "return", "&", "PassState", "{", "baseInnerState", ":", "baseInnerState", "{", "name", ":", "name", ",", "id", ":", "rand", ".", "Int63", ...
// NewPassState returns a new PassState instance
[ "NewPassState", "returns", "a", "new", "PassState", "instance" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L647-L655
1,177
mweagle/Sparta
aws/step/step.go
WithDefault
func (cs *ChoiceState) WithDefault(defaultState TransitionState) *ChoiceState { cs.Default = defaultState return cs }
go
func (cs *ChoiceState) WithDefault(defaultState TransitionState) *ChoiceState { cs.Default = defaultState return cs }
[ "func", "(", "cs", "*", "ChoiceState", ")", "WithDefault", "(", "defaultState", "TransitionState", ")", "*", "ChoiceState", "{", "cs", ".", "Default", "=", "defaultState", "\n", "return", "cs", "\n", "}" ]
// WithDefault is the fluent builder for the default state
[ "WithDefault", "is", "the", "fluent", "builder", "for", "the", "default", "state" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L670-L673
1,178
mweagle/Sparta
aws/step/step.go
NewChoiceState
func NewChoiceState(choiceStateName string, choices ...ChoiceBranch) *ChoiceState { return &ChoiceState{ baseInnerState: baseInnerState{ name: choiceStateName, id: rand.Int63(), isEndStateInvalid: true, }, Choices: append([]ChoiceBranch{}, choices...), } }
go
func NewChoiceState(choiceStateName string, choices ...ChoiceBranch) *ChoiceState { return &ChoiceState{ baseInnerState: baseInnerState{ name: choiceStateName, id: rand.Int63(), isEndStateInvalid: true, }, Choices: append([]ChoiceBranch{}, choices...), } }
[ "func", "NewChoiceState", "(", "choiceStateName", "string", ",", "choices", "...", "ChoiceBranch", ")", "*", "ChoiceState", "{", "return", "&", "ChoiceState", "{", "baseInnerState", ":", "baseInnerState", "{", "name", ":", "choiceStateName", ",", "id", ":", "ran...
// NewChoiceState returns a "ChoiceState" with the supplied // information
[ "NewChoiceState", "returns", "a", "ChoiceState", "with", "the", "supplied", "information" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L708-L717
1,179
mweagle/Sparta
aws/step/step.go
WithErrors
func (tr *TaskRetry) WithErrors(errors ...StateError) *TaskRetry { if tr.ErrorEquals == nil { tr.ErrorEquals = make([]StateError, 0) } tr.ErrorEquals = append(tr.ErrorEquals, errors...) return tr }
go
func (tr *TaskRetry) WithErrors(errors ...StateError) *TaskRetry { if tr.ErrorEquals == nil { tr.ErrorEquals = make([]StateError, 0) } tr.ErrorEquals = append(tr.ErrorEquals, errors...) return tr }
[ "func", "(", "tr", "*", "TaskRetry", ")", "WithErrors", "(", "errors", "...", "StateError", ")", "*", "TaskRetry", "{", "if", "tr", ".", "ErrorEquals", "==", "nil", "{", "tr", ".", "ErrorEquals", "=", "make", "(", "[", "]", "StateError", ",", "0", ")...
// WithErrors is the fluent builder
[ "WithErrors", "is", "the", "fluent", "builder" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L733-L739
1,180
mweagle/Sparta
aws/step/step.go
WithInterval
func (tr *TaskRetry) WithInterval(interval time.Duration) *TaskRetry { tr.IntervalSeconds = interval return tr }
go
func (tr *TaskRetry) WithInterval(interval time.Duration) *TaskRetry { tr.IntervalSeconds = interval return tr }
[ "func", "(", "tr", "*", "TaskRetry", ")", "WithInterval", "(", "interval", "time", ".", "Duration", ")", "*", "TaskRetry", "{", "tr", ".", "IntervalSeconds", "=", "interval", "\n", "return", "tr", "\n", "}" ]
// WithInterval is the fluent builder
[ "WithInterval", "is", "the", "fluent", "builder" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L742-L745
1,181
mweagle/Sparta
aws/step/step.go
WithMaxAttempts
func (tr *TaskRetry) WithMaxAttempts(maxAttempts int) *TaskRetry { tr.MaxAttempts = maxAttempts return tr }
go
func (tr *TaskRetry) WithMaxAttempts(maxAttempts int) *TaskRetry { tr.MaxAttempts = maxAttempts return tr }
[ "func", "(", "tr", "*", "TaskRetry", ")", "WithMaxAttempts", "(", "maxAttempts", "int", ")", "*", "TaskRetry", "{", "tr", ".", "MaxAttempts", "=", "maxAttempts", "\n", "return", "tr", "\n", "}" ]
// WithMaxAttempts is the fluent builder
[ "WithMaxAttempts", "is", "the", "fluent", "builder" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L748-L751
1,182
mweagle/Sparta
aws/step/step.go
WithBackoffRate
func (tr *TaskRetry) WithBackoffRate(backoffRate float32) *TaskRetry { tr.BackoffRate = backoffRate return tr }
go
func (tr *TaskRetry) WithBackoffRate(backoffRate float32) *TaskRetry { tr.BackoffRate = backoffRate return tr }
[ "func", "(", "tr", "*", "TaskRetry", ")", "WithBackoffRate", "(", "backoffRate", "float32", ")", "*", "TaskRetry", "{", "tr", ".", "BackoffRate", "=", "backoffRate", "\n", "return", "tr", "\n", "}" ]
// WithBackoffRate is the fluent builder
[ "WithBackoffRate", "is", "the", "fluent", "builder" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L754-L757
1,183
mweagle/Sparta
aws/step/step.go
MarshalJSON
func (tc *TaskCatch) MarshalJSON() ([]byte, error) { catchJSON := map[string]interface{}{ "ErrorEquals": tc.errorEquals, "Next": tc.next, } return json.Marshal(catchJSON) }
go
func (tc *TaskCatch) MarshalJSON() ([]byte, error) { catchJSON := map[string]interface{}{ "ErrorEquals": tc.errorEquals, "Next": tc.next, } return json.Marshal(catchJSON) }
[ "func", "(", "tc", "*", "TaskCatch", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "catchJSON", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "tc", ".", "errorEquals", ",", "\"", "\""...
// MarshalJSON to prevent inadvertent composition
[ "MarshalJSON", "to", "prevent", "inadvertent", "composition" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L778-L784
1,184
mweagle/Sparta
aws/step/step.go
NewTaskCatch
func NewTaskCatch(nextState TransitionState, errors ...StateError) *TaskCatch { return &TaskCatch{ errorEquals: errors, next: nextState, } }
go
func NewTaskCatch(nextState TransitionState, errors ...StateError) *TaskCatch { return &TaskCatch{ errorEquals: errors, next: nextState, } }
[ "func", "NewTaskCatch", "(", "nextState", "TransitionState", ",", "errors", "...", "StateError", ")", "*", "TaskCatch", "{", "return", "&", "TaskCatch", "{", "errorEquals", ":", "errors", ",", "next", ":", "nextState", ",", "}", "\n", "}" ]
// NewTaskCatch returns a new TaskCatch instance
[ "NewTaskCatch", "returns", "a", "new", "TaskCatch", "instance" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L787-L792
1,185
mweagle/Sparta
aws/step/step.go
additionalParams
func (bt *BaseTask) additionalParams() map[string]interface{} { additionalParams := make(map[string]interface{}) if bt.TimeoutSeconds.Seconds() != 0 { additionalParams["TimeoutSeconds"] = bt.TimeoutSeconds.Seconds() } if bt.HeartbeatSeconds.Seconds() != 0 { additionalParams["HeartbeatSeconds"] = bt.HeartbeatSeconds.Seconds() } if bt.ResultPath != "" { additionalParams["ResultPath"] = bt.ResultPath } if len(bt.Retriers) != 0 { additionalParams["Retry"] = make([]map[string]interface{}, 0) } if bt.Catchers != nil { catcherMap := make([]map[string]interface{}, len(bt.Catchers)) for index, eachCatcher := range bt.Catchers { catcherMap[index] = map[string]interface{}{ "ErrorEquals": eachCatcher.errorEquals, "Next": eachCatcher.next.Name(), } } additionalParams["Catch"] = catcherMap } return additionalParams }
go
func (bt *BaseTask) additionalParams() map[string]interface{} { additionalParams := make(map[string]interface{}) if bt.TimeoutSeconds.Seconds() != 0 { additionalParams["TimeoutSeconds"] = bt.TimeoutSeconds.Seconds() } if bt.HeartbeatSeconds.Seconds() != 0 { additionalParams["HeartbeatSeconds"] = bt.HeartbeatSeconds.Seconds() } if bt.ResultPath != "" { additionalParams["ResultPath"] = bt.ResultPath } if len(bt.Retriers) != 0 { additionalParams["Retry"] = make([]map[string]interface{}, 0) } if bt.Catchers != nil { catcherMap := make([]map[string]interface{}, len(bt.Catchers)) for index, eachCatcher := range bt.Catchers { catcherMap[index] = map[string]interface{}{ "ErrorEquals": eachCatcher.errorEquals, "Next": eachCatcher.next.Name(), } } additionalParams["Catch"] = catcherMap } return additionalParams }
[ "func", "(", "bt", "*", "BaseTask", ")", "additionalParams", "(", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "additionalParams", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n\n", "if", "bt", ".", "Time...
// attributeMap returns the map of attributes necessary // for JSON serialization
[ "attributeMap", "returns", "the", "map", "of", "attributes", "necessary", "for", "JSON", "serialization" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L836-L862
1,186
mweagle/Sparta
aws/step/step.go
WithTimeout
func (bt *BaseTask) WithTimeout(timeout time.Duration) *BaseTask { bt.TimeoutSeconds = timeout return bt }
go
func (bt *BaseTask) WithTimeout(timeout time.Duration) *BaseTask { bt.TimeoutSeconds = timeout return bt }
[ "func", "(", "bt", "*", "BaseTask", ")", "WithTimeout", "(", "timeout", "time", ".", "Duration", ")", "*", "BaseTask", "{", "bt", ".", "TimeoutSeconds", "=", "timeout", "\n", "return", "bt", "\n", "}" ]
// WithTimeout is the fluent builder for BaseTask
[ "WithTimeout", "is", "the", "fluent", "builder", "for", "BaseTask" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L894-L897
1,187
mweagle/Sparta
aws/step/step.go
WithHeartbeat
func (bt *BaseTask) WithHeartbeat(pulse time.Duration) *BaseTask { bt.HeartbeatSeconds = pulse return bt }
go
func (bt *BaseTask) WithHeartbeat(pulse time.Duration) *BaseTask { bt.HeartbeatSeconds = pulse return bt }
[ "func", "(", "bt", "*", "BaseTask", ")", "WithHeartbeat", "(", "pulse", "time", ".", "Duration", ")", "*", "BaseTask", "{", "bt", ".", "HeartbeatSeconds", "=", "pulse", "\n", "return", "bt", "\n", "}" ]
// WithHeartbeat is the fluent builder for BaseTask
[ "WithHeartbeat", "is", "the", "fluent", "builder", "for", "BaseTask" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L900-L903
1,188
mweagle/Sparta
aws/step/step.go
WithRetriers
func (bt *BaseTask) WithRetriers(retries ...*TaskRetry) *BaseTask { if bt.Retriers == nil { bt.Retriers = make([]*TaskRetry, 0) } bt.Retriers = append(bt.Retriers, retries...) return bt }
go
func (bt *BaseTask) WithRetriers(retries ...*TaskRetry) *BaseTask { if bt.Retriers == nil { bt.Retriers = make([]*TaskRetry, 0) } bt.Retriers = append(bt.Retriers, retries...) return bt }
[ "func", "(", "bt", "*", "BaseTask", ")", "WithRetriers", "(", "retries", "...", "*", "TaskRetry", ")", "*", "BaseTask", "{", "if", "bt", ".", "Retriers", "==", "nil", "{", "bt", ".", "Retriers", "=", "make", "(", "[", "]", "*", "TaskRetry", ",", "0...
// WithRetriers is the fluent builder for BaseTask
[ "WithRetriers", "is", "the", "fluent", "builder", "for", "BaseTask" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L906-L912
1,189
mweagle/Sparta
aws/step/step.go
WithCatchers
func (bt *BaseTask) WithCatchers(catch ...*TaskCatch) *BaseTask { if bt.Catchers == nil { bt.Catchers = make([]*TaskCatch, 0) } bt.Catchers = append(bt.Catchers, catch...) return bt }
go
func (bt *BaseTask) WithCatchers(catch ...*TaskCatch) *BaseTask { if bt.Catchers == nil { bt.Catchers = make([]*TaskCatch, 0) } bt.Catchers = append(bt.Catchers, catch...) return bt }
[ "func", "(", "bt", "*", "BaseTask", ")", "WithCatchers", "(", "catch", "...", "*", "TaskCatch", ")", "*", "BaseTask", "{", "if", "bt", ".", "Catchers", "==", "nil", "{", "bt", ".", "Catchers", "=", "make", "(", "[", "]", "*", "TaskCatch", ",", "0",...
// WithCatchers is the fluent builder for BaseTask
[ "WithCatchers", "is", "the", "fluent", "builder", "for", "BaseTask" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L915-L921
1,190
mweagle/Sparta
aws/step/step.go
WithComment
func (bt *BaseTask) WithComment(comment string) TransitionState { bt.comment = comment return bt }
go
func (bt *BaseTask) WithComment(comment string) TransitionState { bt.comment = comment return bt }
[ "func", "(", "bt", "*", "BaseTask", ")", "WithComment", "(", "comment", "string", ")", "TransitionState", "{", "bt", ".", "comment", "=", "comment", "\n", "return", "bt", "\n", "}" ]
// WithComment returns the BaseTask comment
[ "WithComment", "returns", "the", "BaseTask", "comment" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L924-L927
1,191
mweagle/Sparta
aws/step/step.go
WithInputPath
func (bt *BaseTask) WithInputPath(inputPath string) TransitionState { bt.inputPath = inputPath return bt }
go
func (bt *BaseTask) WithInputPath(inputPath string) TransitionState { bt.inputPath = inputPath return bt }
[ "func", "(", "bt", "*", "BaseTask", ")", "WithInputPath", "(", "inputPath", "string", ")", "TransitionState", "{", "bt", ".", "inputPath", "=", "inputPath", "\n", "return", "bt", "\n", "}" ]
// WithInputPath returns the BaseTask input data selector
[ "WithInputPath", "returns", "the", "BaseTask", "input", "data", "selector" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L930-L933
1,192
mweagle/Sparta
aws/step/step.go
WithOutputPath
func (bt *BaseTask) WithOutputPath(outputPath string) TransitionState { bt.outputPath = outputPath return bt }
go
func (bt *BaseTask) WithOutputPath(outputPath string) TransitionState { bt.outputPath = outputPath return bt }
[ "func", "(", "bt", "*", "BaseTask", ")", "WithOutputPath", "(", "outputPath", "string", ")", "TransitionState", "{", "bt", ".", "outputPath", "=", "outputPath", "\n", "return", "bt", "\n", "}" ]
// WithOutputPath returns the BaseTask output data selector
[ "WithOutputPath", "returns", "the", "BaseTask", "output", "data", "selector" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L936-L939
1,193
mweagle/Sparta
aws/step/step.go
NewLambdaTaskState
func NewLambdaTaskState(stateName string, lambdaFn *sparta.LambdaAWSInfo) *LambdaTaskState { ts := &LambdaTaskState{ BaseTask: BaseTask{ baseInnerState: baseInnerState{ name: stateName, id: rand.Int63(), }, }, lambdaFn: lambdaFn, } ts.LambdaDecorator = func(serviceName string, lambdaResourceName string, lambdaResource gocf.LambdaFunction, resourceMetadata map[string]interface{}, S3Bucket string, S3Key string, buildID string, cfTemplate *gocf.Template, context map[string]interface{}, logger *logrus.Logger) error { if ts.preexistingDecorator != nil { preexistingLambdaDecoratorErr := ts.preexistingDecorator( serviceName, lambdaResourceName, lambdaResource, resourceMetadata, S3Bucket, S3Key, buildID, cfTemplate, context, logger) if preexistingLambdaDecoratorErr != nil { return preexistingLambdaDecoratorErr } } // Save the lambda name s.t. we can create the {"Ref"::"lambdaName"} entry... ts.lambdaLogicalResourceName = lambdaResourceName return nil } // Make sure this Lambda decorator is included in the list of existing decorators // If there already is a decorator, then save it... ts.preexistingDecorator = lambdaFn.Decorator ts.lambdaFn.Decorators = append(ts.lambdaFn.Decorators, sparta.TemplateDecoratorHookFunc(ts.LambdaDecorator)) return ts }
go
func NewLambdaTaskState(stateName string, lambdaFn *sparta.LambdaAWSInfo) *LambdaTaskState { ts := &LambdaTaskState{ BaseTask: BaseTask{ baseInnerState: baseInnerState{ name: stateName, id: rand.Int63(), }, }, lambdaFn: lambdaFn, } ts.LambdaDecorator = func(serviceName string, lambdaResourceName string, lambdaResource gocf.LambdaFunction, resourceMetadata map[string]interface{}, S3Bucket string, S3Key string, buildID string, cfTemplate *gocf.Template, context map[string]interface{}, logger *logrus.Logger) error { if ts.preexistingDecorator != nil { preexistingLambdaDecoratorErr := ts.preexistingDecorator( serviceName, lambdaResourceName, lambdaResource, resourceMetadata, S3Bucket, S3Key, buildID, cfTemplate, context, logger) if preexistingLambdaDecoratorErr != nil { return preexistingLambdaDecoratorErr } } // Save the lambda name s.t. we can create the {"Ref"::"lambdaName"} entry... ts.lambdaLogicalResourceName = lambdaResourceName return nil } // Make sure this Lambda decorator is included in the list of existing decorators // If there already is a decorator, then save it... ts.preexistingDecorator = lambdaFn.Decorator ts.lambdaFn.Decorators = append(ts.lambdaFn.Decorators, sparta.TemplateDecoratorHookFunc(ts.LambdaDecorator)) return ts }
[ "func", "NewLambdaTaskState", "(", "stateName", "string", ",", "lambdaFn", "*", "sparta", ".", "LambdaAWSInfo", ")", "*", "LambdaTaskState", "{", "ts", ":=", "&", "LambdaTaskState", "{", "BaseTask", ":", "BaseTask", "{", "baseInnerState", ":", "baseInnerState", ...
// NewLambdaTaskState returns a LambdaTaskState instance properly initialized
[ "NewLambdaTaskState", "returns", "a", "LambdaTaskState", "instance", "properly", "initialized" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L960-L1007
1,194
mweagle/Sparta
aws/step/step.go
NewWaitDelayState
func NewWaitDelayState(stateName string, delay time.Duration) *WaitDelay { return &WaitDelay{ baseInnerState: baseInnerState{ name: stateName, id: rand.Int63(), }, delay: delay, } }
go
func NewWaitDelayState(stateName string, delay time.Duration) *WaitDelay { return &WaitDelay{ baseInnerState: baseInnerState{ name: stateName, id: rand.Int63(), }, delay: delay, } }
[ "func", "NewWaitDelayState", "(", "stateName", "string", ",", "delay", "time", ".", "Duration", ")", "*", "WaitDelay", "{", "return", "&", "WaitDelay", "{", "baseInnerState", ":", "baseInnerState", "{", "name", ":", "stateName", ",", "id", ":", "rand", ".", ...
// NewWaitDelayState returns a new WaitDelay pointer instance
[ "NewWaitDelayState", "returns", "a", "new", "WaitDelay", "pointer", "instance" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L1072-L1080
1,195
mweagle/Sparta
aws/step/step.go
NewWaitUntilState
func NewWaitUntilState(stateName string, waitUntil time.Time) *WaitUntil { return &WaitUntil{ baseInnerState: baseInnerState{ name: stateName, id: rand.Int63(), }, Timestamp: waitUntil, } }
go
func NewWaitUntilState(stateName string, waitUntil time.Time) *WaitUntil { return &WaitUntil{ baseInnerState: baseInnerState{ name: stateName, id: rand.Int63(), }, Timestamp: waitUntil, } }
[ "func", "NewWaitUntilState", "(", "stateName", "string", ",", "waitUntil", "time", ".", "Time", ")", "*", "WaitUntil", "{", "return", "&", "WaitUntil", "{", "baseInnerState", ":", "baseInnerState", "{", "name", ":", "stateName", ",", "id", ":", "rand", ".", ...
// NewWaitUntilState returns a new WaitDelay pointer instance
[ "NewWaitUntilState", "returns", "a", "new", "WaitDelay", "pointer", "instance" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L1139-L1147
1,196
mweagle/Sparta
aws/step/step.go
NewWaitDynamicUntilState
func NewWaitDynamicUntilState(stateName string, timestampPath string) *WaitDynamicUntil { return &WaitDynamicUntil{ baseInnerState: baseInnerState{ name: stateName, id: rand.Int63(), }, TimestampPath: timestampPath, } }
go
func NewWaitDynamicUntilState(stateName string, timestampPath string) *WaitDynamicUntil { return &WaitDynamicUntil{ baseInnerState: baseInnerState{ name: stateName, id: rand.Int63(), }, TimestampPath: timestampPath, } }
[ "func", "NewWaitDynamicUntilState", "(", "stateName", "string", ",", "timestampPath", "string", ")", "*", "WaitDynamicUntil", "{", "return", "&", "WaitDynamicUntil", "{", "baseInnerState", ":", "baseInnerState", "{", "name", ":", "stateName", ",", "id", ":", "rand...
// NewWaitDynamicUntilState returns a new WaitDynamicUntil pointer instance
[ "NewWaitDynamicUntilState", "returns", "a", "new", "WaitDynamicUntil", "pointer", "instance" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L1202-L1210
1,197
mweagle/Sparta
aws/step/step.go
NewSuccessState
func NewSuccessState(name string) *SuccessState { return &SuccessState{ baseInnerState: baseInnerState{ name: name, id: rand.Int63(), isEndStateInvalid: true, }, } }
go
func NewSuccessState(name string) *SuccessState { return &SuccessState{ baseInnerState: baseInnerState{ name: name, id: rand.Int63(), isEndStateInvalid: true, }, } }
[ "func", "NewSuccessState", "(", "name", "string", ")", "*", "SuccessState", "{", "return", "&", "SuccessState", "{", "baseInnerState", ":", "baseInnerState", "{", "name", ":", "name", ",", "id", ":", "rand", ".", "Int63", "(", ")", ",", "isEndStateInvalid", ...
// NewSuccessState returns a "SuccessState" with the supplied // name
[ "NewSuccessState", "returns", "a", "SuccessState", "with", "the", "supplied", "name" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L1265-L1273
1,198
mweagle/Sparta
aws/step/step.go
MarshalJSON
func (fs *FailState) MarshalJSON() ([]byte, error) { additionalParams := make(map[string]interface{}) additionalParams["Error"] = fs.ErrorName if fs.Cause != nil { additionalParams["Cause"] = fs.Cause.Error() } return fs.marshalStateJSON("Fail", additionalParams) }
go
func (fs *FailState) MarshalJSON() ([]byte, error) { additionalParams := make(map[string]interface{}) additionalParams["Error"] = fs.ErrorName if fs.Cause != nil { additionalParams["Cause"] = fs.Cause.Error() } return fs.marshalStateJSON("Fail", additionalParams) }
[ "func", "(", "fs", "*", "FailState", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "additionalParams", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "additionalParams", "[", "\"", "\"",...
// MarshalJSON for custom marshaling
[ "MarshalJSON", "for", "custom", "marshaling" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L1316-L1323
1,199
mweagle/Sparta
aws/step/step.go
NewFailState
func NewFailState(failStateName string, errorName string, cause error) *FailState { return &FailState{ baseInnerState: baseInnerState{ name: failStateName, id: rand.Int63(), isEndStateInvalid: true, }, ErrorName: errorName, Cause: cause, } }
go
func NewFailState(failStateName string, errorName string, cause error) *FailState { return &FailState{ baseInnerState: baseInnerState{ name: failStateName, id: rand.Int63(), isEndStateInvalid: true, }, ErrorName: errorName, Cause: cause, } }
[ "func", "NewFailState", "(", "failStateName", "string", ",", "errorName", "string", ",", "cause", "error", ")", "*", "FailState", "{", "return", "&", "FailState", "{", "baseInnerState", ":", "baseInnerState", "{", "name", ":", "failStateName", ",", "id", ":", ...
// NewFailState returns a "FailState" with the supplied // information
[ "NewFailState", "returns", "a", "FailState", "with", "the", "supplied", "information" ]
a646ce10a6728e988448dc3f6f79cd3322854c61
https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L1327-L1337