repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
apex/apex
mock/lambdaiface.go
UpdateEventSourceMappingWithContext
func (m *MockLambdaAPI) UpdateEventSourceMappingWithContext(arg0 aws.Context, arg1 *lambda.UpdateEventSourceMappingInput, arg2 ...request.Option) (*lambda.EventSourceMappingConfiguration, error) { varargs := []interface{}{arg0, arg1} for _, a := range arg2 { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "UpdateEventSourceMappingWithContext", varargs...) ret0, _ := ret[0].(*lambda.EventSourceMappingConfiguration) ret1, _ := ret[1].(error) return ret0, ret1 }
go
func (m *MockLambdaAPI) UpdateEventSourceMappingWithContext(arg0 aws.Context, arg1 *lambda.UpdateEventSourceMappingInput, arg2 ...request.Option) (*lambda.EventSourceMappingConfiguration, error) { varargs := []interface{}{arg0, arg1} for _, a := range arg2 { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "UpdateEventSourceMappingWithContext", varargs...) ret0, _ := ret[0].(*lambda.EventSourceMappingConfiguration) ret1, _ := ret[1].(error) return ret0, ret1 }
[ "func", "(", "m", "*", "MockLambdaAPI", ")", "UpdateEventSourceMappingWithContext", "(", "arg0", "aws", ".", "Context", ",", "arg1", "*", "lambda", ".", "UpdateEventSourceMappingInput", ",", "arg2", "...", "request", ".", "Option", ")", "(", "*", "lambda", ".", "EventSourceMappingConfiguration", ",", "error", ")", "{", "varargs", ":=", "[", "]", "interface", "{", "}", "{", "arg0", ",", "arg1", "}", "\n", "for", "_", ",", "a", ":=", "range", "arg2", "{", "varargs", "=", "append", "(", "varargs", ",", "a", ")", "\n", "}", "\n", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"UpdateEventSourceMappingWithContext\"", ",", "varargs", "...", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "*", "lambda", ".", "EventSourceMappingConfiguration", ")", "\n", "ret1", ",", "_", ":=", "ret", "[", "1", "]", ".", "(", "error", ")", "\n", "return", "ret0", ",", "ret1", "\n", "}" ]
// UpdateEventSourceMappingWithContext mocks base method
[ "UpdateEventSourceMappingWithContext", "mocks", "base", "method" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/mock/lambdaiface.go#L1311-L1320
train
apex/apex
mock/lambdaiface.go
UpdateFunctionCode
func (m *MockLambdaAPI) UpdateFunctionCode(arg0 *lambda.UpdateFunctionCodeInput) (*lambda.FunctionConfiguration, error) { ret := m.ctrl.Call(m, "UpdateFunctionCode", arg0) ret0, _ := ret[0].(*lambda.FunctionConfiguration) ret1, _ := ret[1].(error) return ret0, ret1 }
go
func (m *MockLambdaAPI) UpdateFunctionCode(arg0 *lambda.UpdateFunctionCodeInput) (*lambda.FunctionConfiguration, error) { ret := m.ctrl.Call(m, "UpdateFunctionCode", arg0) ret0, _ := ret[0].(*lambda.FunctionConfiguration) ret1, _ := ret[1].(error) return ret0, ret1 }
[ "func", "(", "m", "*", "MockLambdaAPI", ")", "UpdateFunctionCode", "(", "arg0", "*", "lambda", ".", "UpdateFunctionCodeInput", ")", "(", "*", "lambda", ".", "FunctionConfiguration", ",", "error", ")", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"UpdateFunctionCode\"", ",", "arg0", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "*", "lambda", ".", "FunctionConfiguration", ")", "\n", "ret1", ",", "_", ":=", "ret", "[", "1", "]", ".", "(", "error", ")", "\n", "return", "ret0", ",", "ret1", "\n", "}" ]
// UpdateFunctionCode mocks base method
[ "UpdateFunctionCode", "mocks", "base", "method" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/mock/lambdaiface.go#L1329-L1334
train
apex/apex
mock/lambdaiface.go
UpdateFunctionCodeRequest
func (m *MockLambdaAPI) UpdateFunctionCodeRequest(arg0 *lambda.UpdateFunctionCodeInput) (*request.Request, *lambda.FunctionConfiguration) { ret := m.ctrl.Call(m, "UpdateFunctionCodeRequest", arg0) ret0, _ := ret[0].(*request.Request) ret1, _ := ret[1].(*lambda.FunctionConfiguration) return ret0, ret1 }
go
func (m *MockLambdaAPI) UpdateFunctionCodeRequest(arg0 *lambda.UpdateFunctionCodeInput) (*request.Request, *lambda.FunctionConfiguration) { ret := m.ctrl.Call(m, "UpdateFunctionCodeRequest", arg0) ret0, _ := ret[0].(*request.Request) ret1, _ := ret[1].(*lambda.FunctionConfiguration) return ret0, ret1 }
[ "func", "(", "m", "*", "MockLambdaAPI", ")", "UpdateFunctionCodeRequest", "(", "arg0", "*", "lambda", ".", "UpdateFunctionCodeInput", ")", "(", "*", "request", ".", "Request", ",", "*", "lambda", ".", "FunctionConfiguration", ")", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"UpdateFunctionCodeRequest\"", ",", "arg0", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "*", "request", ".", "Request", ")", "\n", "ret1", ",", "_", ":=", "ret", "[", "1", "]", ".", "(", "*", "lambda", ".", "FunctionConfiguration", ")", "\n", "return", "ret0", ",", "ret1", "\n", "}" ]
// UpdateFunctionCodeRequest mocks base method
[ "UpdateFunctionCodeRequest", "mocks", "base", "method" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/mock/lambdaiface.go#L1342-L1347
train
apex/apex
mock/lambdaiface.go
UpdateFunctionConfiguration
func (m *MockLambdaAPI) UpdateFunctionConfiguration(arg0 *lambda.UpdateFunctionConfigurationInput) (*lambda.FunctionConfiguration, error) { ret := m.ctrl.Call(m, "UpdateFunctionConfiguration", arg0) ret0, _ := ret[0].(*lambda.FunctionConfiguration) ret1, _ := ret[1].(error) return ret0, ret1 }
go
func (m *MockLambdaAPI) UpdateFunctionConfiguration(arg0 *lambda.UpdateFunctionConfigurationInput) (*lambda.FunctionConfiguration, error) { ret := m.ctrl.Call(m, "UpdateFunctionConfiguration", arg0) ret0, _ := ret[0].(*lambda.FunctionConfiguration) ret1, _ := ret[1].(error) return ret0, ret1 }
[ "func", "(", "m", "*", "MockLambdaAPI", ")", "UpdateFunctionConfiguration", "(", "arg0", "*", "lambda", ".", "UpdateFunctionConfigurationInput", ")", "(", "*", "lambda", ".", "FunctionConfiguration", ",", "error", ")", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"UpdateFunctionConfiguration\"", ",", "arg0", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "*", "lambda", ".", "FunctionConfiguration", ")", "\n", "ret1", ",", "_", ":=", "ret", "[", "1", "]", ".", "(", "error", ")", "\n", "return", "ret0", ",", "ret1", "\n", "}" ]
// UpdateFunctionConfiguration mocks base method
[ "UpdateFunctionConfiguration", "mocks", "base", "method" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/mock/lambdaiface.go#L1373-L1378
train
apex/apex
mock/lambdaiface.go
UpdateFunctionConfigurationRequest
func (m *MockLambdaAPI) UpdateFunctionConfigurationRequest(arg0 *lambda.UpdateFunctionConfigurationInput) (*request.Request, *lambda.FunctionConfiguration) { ret := m.ctrl.Call(m, "UpdateFunctionConfigurationRequest", arg0) ret0, _ := ret[0].(*request.Request) ret1, _ := ret[1].(*lambda.FunctionConfiguration) return ret0, ret1 }
go
func (m *MockLambdaAPI) UpdateFunctionConfigurationRequest(arg0 *lambda.UpdateFunctionConfigurationInput) (*request.Request, *lambda.FunctionConfiguration) { ret := m.ctrl.Call(m, "UpdateFunctionConfigurationRequest", arg0) ret0, _ := ret[0].(*request.Request) ret1, _ := ret[1].(*lambda.FunctionConfiguration) return ret0, ret1 }
[ "func", "(", "m", "*", "MockLambdaAPI", ")", "UpdateFunctionConfigurationRequest", "(", "arg0", "*", "lambda", ".", "UpdateFunctionConfigurationInput", ")", "(", "*", "request", ".", "Request", ",", "*", "lambda", ".", "FunctionConfiguration", ")", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"UpdateFunctionConfigurationRequest\"", ",", "arg0", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "*", "request", ".", "Request", ")", "\n", "ret1", ",", "_", ":=", "ret", "[", "1", "]", ".", "(", "*", "lambda", ".", "FunctionConfiguration", ")", "\n", "return", "ret0", ",", "ret1", "\n", "}" ]
// UpdateFunctionConfigurationRequest mocks base method
[ "UpdateFunctionConfigurationRequest", "mocks", "base", "method" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/mock/lambdaiface.go#L1386-L1391
train
apex/apex
upgrade/upgrade.go
Upgrade
func Upgrade(version string) error { term.HideCursor() defer term.ShowCursor() p := &update.Manager{ Command: "apex", Store: &github.Store{ Owner: "apex", Repo: "apex", Version: version, }, } // fetch releases releases, err := p.LatestReleases() if err != nil { return errors.Wrap(err, "fetching latest release") } // no updates if len(releases) == 0 { util.LogPad("No updates available, you're good :)") return nil } // latest r := releases[0] // find the tarball for this system a := r.FindTarball(runtime.GOOS, runtime.GOARCH) if a == nil { return errors.Errorf("failed to find a binary for %s %s", runtime.GOOS, runtime.GOARCH) } // download tarball to a tmp dir tarball, err := a.DownloadProxy(progressreader.New) if err != nil { return errors.Wrap(err, "downloading tarball") } // install it if err := p.Install(tarball); err != nil { return errors.Wrap(err, "installing") } term.ClearAll() util.LogPad("Updated %s to %s", version, r.Version) return nil }
go
func Upgrade(version string) error { term.HideCursor() defer term.ShowCursor() p := &update.Manager{ Command: "apex", Store: &github.Store{ Owner: "apex", Repo: "apex", Version: version, }, } // fetch releases releases, err := p.LatestReleases() if err != nil { return errors.Wrap(err, "fetching latest release") } // no updates if len(releases) == 0 { util.LogPad("No updates available, you're good :)") return nil } // latest r := releases[0] // find the tarball for this system a := r.FindTarball(runtime.GOOS, runtime.GOARCH) if a == nil { return errors.Errorf("failed to find a binary for %s %s", runtime.GOOS, runtime.GOARCH) } // download tarball to a tmp dir tarball, err := a.DownloadProxy(progressreader.New) if err != nil { return errors.Wrap(err, "downloading tarball") } // install it if err := p.Install(tarball); err != nil { return errors.Wrap(err, "installing") } term.ClearAll() util.LogPad("Updated %s to %s", version, r.Version) return nil }
[ "func", "Upgrade", "(", "version", "string", ")", "error", "{", "term", ".", "HideCursor", "(", ")", "\n", "defer", "term", ".", "ShowCursor", "(", ")", "\n", "p", ":=", "&", "update", ".", "Manager", "{", "Command", ":", "\"apex\"", ",", "Store", ":", "&", "github", ".", "Store", "{", "Owner", ":", "\"apex\"", ",", "Repo", ":", "\"apex\"", ",", "Version", ":", "version", ",", "}", ",", "}", "\n", "releases", ",", "err", ":=", "p", ".", "LatestReleases", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"fetching latest release\"", ")", "\n", "}", "\n", "if", "len", "(", "releases", ")", "==", "0", "{", "util", ".", "LogPad", "(", "\"No updates available, you're good :)\"", ")", "\n", "return", "nil", "\n", "}", "\n", "r", ":=", "releases", "[", "0", "]", "\n", "a", ":=", "r", ".", "FindTarball", "(", "runtime", ".", "GOOS", ",", "runtime", ".", "GOARCH", ")", "\n", "if", "a", "==", "nil", "{", "return", "errors", ".", "Errorf", "(", "\"failed to find a binary for %s %s\"", ",", "runtime", ".", "GOOS", ",", "runtime", ".", "GOARCH", ")", "\n", "}", "\n", "tarball", ",", "err", ":=", "a", ".", "DownloadProxy", "(", "progressreader", ".", "New", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"downloading tarball\"", ")", "\n", "}", "\n", "if", "err", ":=", "p", ".", "Install", "(", "tarball", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"installing\"", ")", "\n", "}", "\n", "term", ".", "ClearAll", "(", ")", "\n", "util", ".", "LogPad", "(", "\"Updated %s to %s\"", ",", "version", ",", "r", ".", "Version", ")", "\n", "return", "nil", "\n", "}" ]
// Upgrade the current `version` of apex to the latest.
[ "Upgrade", "the", "current", "version", "of", "apex", "to", "the", "latest", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/upgrade/upgrade.go#L17-L66
train
apex/apex
boot/boot.go
Boot
func (b *Bootstrapper) Boot() error { fmt.Println(logo) if b.isProject() { help("I've detected a ./project.json file, this seems to already be a project!") return nil } help("Enter the name of your project. It should be machine-friendly, as this\nis used to prefix your functions in Lambda.") b.name = prompt.StringRequired(indent(" Project name: ")) help("Enter an optional description of your project.") b.description = prompt.String(indent(" Project description: ")) fmt.Println() return b.bootVanilla() }
go
func (b *Bootstrapper) Boot() error { fmt.Println(logo) if b.isProject() { help("I've detected a ./project.json file, this seems to already be a project!") return nil } help("Enter the name of your project. It should be machine-friendly, as this\nis used to prefix your functions in Lambda.") b.name = prompt.StringRequired(indent(" Project name: ")) help("Enter an optional description of your project.") b.description = prompt.String(indent(" Project description: ")) fmt.Println() return b.bootVanilla() }
[ "func", "(", "b", "*", "Bootstrapper", ")", "Boot", "(", ")", "error", "{", "fmt", ".", "Println", "(", "logo", ")", "\n", "if", "b", ".", "isProject", "(", ")", "{", "help", "(", "\"I've detected a ./project.json file, this seems to already be a project!\"", ")", "\n", "return", "nil", "\n", "}", "\n", "help", "(", "\"Enter the name of your project. It should be machine-friendly, as this\\nis used to prefix your functions in Lambda.\"", ")", "\n", "\\n", "\n", "b", ".", "name", "=", "prompt", ".", "StringRequired", "(", "indent", "(", "\" Project name: \"", ")", ")", "\n", "help", "(", "\"Enter an optional description of your project.\"", ")", "\n", "b", ".", "description", "=", "prompt", ".", "String", "(", "indent", "(", "\" Project description: \"", ")", ")", "\n", "fmt", ".", "Println", "(", ")", "\n", "}" ]
// Boot the project.
[ "Boot", "the", "project", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/boot/boot.go#L82-L98
train
apex/apex
boot/boot.go
isProject
func (b *Bootstrapper) isProject() bool { _, err := os.Stat("project.json") return err == nil }
go
func (b *Bootstrapper) isProject() bool { _, err := os.Stat("project.json") return err == nil }
[ "func", "(", "b", "*", "Bootstrapper", ")", "isProject", "(", ")", "bool", "{", "_", ",", "err", ":=", "os", ".", "Stat", "(", "\"project.json\"", ")", "\n", "return", "err", "==", "nil", "\n", "}" ]
// check if there's a project.
[ "check", "if", "there", "s", "a", "project", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/boot/boot.go#L101-L104
train
apex/apex
boot/boot.go
bootVanilla
func (b *Bootstrapper) bootVanilla() error { iamRole, err := b.createRole() if err != nil { return err } if err := b.initProjectFiles(iamRole); err != nil { return err } fmt.Println(setupCompleteVanilla) return nil }
go
func (b *Bootstrapper) bootVanilla() error { iamRole, err := b.createRole() if err != nil { return err } if err := b.initProjectFiles(iamRole); err != nil { return err } fmt.Println(setupCompleteVanilla) return nil }
[ "func", "(", "b", "*", "Bootstrapper", ")", "bootVanilla", "(", ")", "error", "{", "iamRole", ",", "err", ":=", "b", ".", "createRole", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "b", ".", "initProjectFiles", "(", "iamRole", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "fmt", ".", "Println", "(", "setupCompleteVanilla", ")", "\n", "return", "nil", "\n", "}" ]
// Bootstrap without Terraform.
[ "Bootstrap", "without", "Terraform", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/boot/boot.go#L107-L119
train
apex/apex
boot/boot.go
createRole
func (b *Bootstrapper) createRole() (string, error) { roleName := fmt.Sprintf("%s_lambda_function", b.name) policyName := fmt.Sprintf("%s_lambda_logs", b.name) logf("creating IAM %s role", roleName) role, err := b.IAM.CreateRole(&iam.CreateRoleInput{ RoleName: &roleName, AssumeRolePolicyDocument: aws.String(iamAssumeRolePolicy), }) if err != nil { return "", fmt.Errorf("creating role: %s", err) } logf("creating IAM %s policy", policyName) policy, err := b.IAM.CreatePolicy(&iam.CreatePolicyInput{ PolicyName: &policyName, Description: aws.String("Allow lambda_function to utilize CloudWatchLogs. Created by apex(1)."), PolicyDocument: aws.String(iamLogsPolicy), }) if err != nil { return "", fmt.Errorf("creating policy: %s", err) } logf("attaching policy to lambda_function role.") _, err = b.IAM.AttachRolePolicy(&iam.AttachRolePolicyInput{ RoleName: &roleName, PolicyArn: policy.Policy.Arn, }) if err != nil { return "", fmt.Errorf("creating policy: %s", err) } return *role.Role.Arn, nil }
go
func (b *Bootstrapper) createRole() (string, error) { roleName := fmt.Sprintf("%s_lambda_function", b.name) policyName := fmt.Sprintf("%s_lambda_logs", b.name) logf("creating IAM %s role", roleName) role, err := b.IAM.CreateRole(&iam.CreateRoleInput{ RoleName: &roleName, AssumeRolePolicyDocument: aws.String(iamAssumeRolePolicy), }) if err != nil { return "", fmt.Errorf("creating role: %s", err) } logf("creating IAM %s policy", policyName) policy, err := b.IAM.CreatePolicy(&iam.CreatePolicyInput{ PolicyName: &policyName, Description: aws.String("Allow lambda_function to utilize CloudWatchLogs. Created by apex(1)."), PolicyDocument: aws.String(iamLogsPolicy), }) if err != nil { return "", fmt.Errorf("creating policy: %s", err) } logf("attaching policy to lambda_function role.") _, err = b.IAM.AttachRolePolicy(&iam.AttachRolePolicyInput{ RoleName: &roleName, PolicyArn: policy.Policy.Arn, }) if err != nil { return "", fmt.Errorf("creating policy: %s", err) } return *role.Role.Arn, nil }
[ "func", "(", "b", "*", "Bootstrapper", ")", "createRole", "(", ")", "(", "string", ",", "error", ")", "{", "roleName", ":=", "fmt", ".", "Sprintf", "(", "\"%s_lambda_function\"", ",", "b", ".", "name", ")", "\n", "policyName", ":=", "fmt", ".", "Sprintf", "(", "\"%s_lambda_logs\"", ",", "b", ".", "name", ")", "\n", "logf", "(", "\"creating IAM %s role\"", ",", "roleName", ")", "\n", "role", ",", "err", ":=", "b", ".", "IAM", ".", "CreateRole", "(", "&", "iam", ".", "CreateRoleInput", "{", "RoleName", ":", "&", "roleName", ",", "AssumeRolePolicyDocument", ":", "aws", ".", "String", "(", "iamAssumeRolePolicy", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"creating role: %s\"", ",", "err", ")", "\n", "}", "\n", "logf", "(", "\"creating IAM %s policy\"", ",", "policyName", ")", "\n", "policy", ",", "err", ":=", "b", ".", "IAM", ".", "CreatePolicy", "(", "&", "iam", ".", "CreatePolicyInput", "{", "PolicyName", ":", "&", "policyName", ",", "Description", ":", "aws", ".", "String", "(", "\"Allow lambda_function to utilize CloudWatchLogs. Created by apex(1).\"", ")", ",", "PolicyDocument", ":", "aws", ".", "String", "(", "iamLogsPolicy", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"creating policy: %s\"", ",", "err", ")", "\n", "}", "\n", "logf", "(", "\"attaching policy to lambda_function role.\"", ")", "\n", "_", ",", "err", "=", "b", ".", "IAM", ".", "AttachRolePolicy", "(", "&", "iam", ".", "AttachRolePolicyInput", "{", "RoleName", ":", "&", "roleName", ",", "PolicyArn", ":", "policy", ".", "Policy", ".", "Arn", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"creating policy: %s\"", ",", "err", ")", "\n", "}", "\n", "return", "*", "role", ".", "Role", ".", "Arn", ",", "nil", "\n", "}" ]
// Create IAM role, returning the ARN.
[ "Create", "IAM", "role", "returning", "the", "ARN", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/boot/boot.go#L122-L158
train
apex/apex
boot/boot.go
help
func help(s string) { os.Stdout.WriteString("\n") os.Stdout.WriteString(indent(s)) os.Stdout.WriteString("\n\n") }
go
func help(s string) { os.Stdout.WriteString("\n") os.Stdout.WriteString(indent(s)) os.Stdout.WriteString("\n\n") }
[ "func", "help", "(", "s", "string", ")", "{", "os", ".", "Stdout", ".", "WriteString", "(", "\"\\n\"", ")", "\n", "\\n", "\n", "os", ".", "Stdout", ".", "WriteString", "(", "indent", "(", "s", ")", ")", "\n", "}" ]
// help string output.
[ "help", "string", "output", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/boot/boot.go#L175-L179
train
apex/apex
boot/boot.go
indent
func indent(s string) (out string) { for _, l := range strings.SplitAfter(s, "\n") { out += fmt.Sprintf(" %s", l) } return }
go
func indent(s string) (out string) { for _, l := range strings.SplitAfter(s, "\n") { out += fmt.Sprintf(" %s", l) } return }
[ "func", "indent", "(", "s", "string", ")", "(", "out", "string", ")", "{", "for", "_", ",", "l", ":=", "range", "strings", ".", "SplitAfter", "(", "s", ",", "\"\\n\"", ")", "\\n", "\n", "{", "out", "+=", "fmt", ".", "Sprintf", "(", "\" %s\"", ",", "l", ")", "\n", "}", "\n", "}" ]
// indent multiline string with 2 spaces.
[ "indent", "multiline", "string", "with", "2", "spaces", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/boot/boot.go#L182-L188
train
apex/apex
boot/boot.go
logf
func logf(s string, v ...interface{}) { fmt.Printf(" \033[34m[+]\033[0m %s\n", fmt.Sprintf(s, v...)) }
go
func logf(s string, v ...interface{}) { fmt.Printf(" \033[34m[+]\033[0m %s\n", fmt.Sprintf(s, v...)) }
[ "func", "logf", "(", "s", "string", ",", "v", "...", "interface", "{", "}", ")", "{", "fmt", ".", "Printf", "(", "\" \\033[34m[+]\\033[0m %s\\n\"", ",", "\\033", ")", "\n", "}" ]
// logf outputs a log message.
[ "logf", "outputs", "a", "log", "message", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/boot/boot.go#L191-L193
train
apex/apex
logs/logs.go
wait
func (l *Logs) wait(done <-chan error) { for range l.GroupNames { if err := <-done; err != nil { l.err = err return } } }
go
func (l *Logs) wait(done <-chan error) { for range l.GroupNames { if err := <-done; err != nil { l.err = err return } } }
[ "func", "(", "l", "*", "Logs", ")", "wait", "(", "done", "<-", "chan", "error", ")", "{", "for", "range", "l", ".", "GroupNames", "{", "if", "err", ":=", "<-", "done", ";", "err", "!=", "nil", "{", "l", ".", "err", "=", "err", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// wait for each log group to complete.
[ "wait", "for", "each", "log", "group", "to", "complete", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/logs/logs.go#L56-L63
train
apex/apex
logs/logs.go
consume
func (l *Logs) consume(name string, ch chan *Event, done chan error) { log := Log{ Config: l.Config, GroupName: name, Log: log.WithField("group", name), } for event := range log.Start() { ch <- event } done <- log.Err() }
go
func (l *Logs) consume(name string, ch chan *Event, done chan error) { log := Log{ Config: l.Config, GroupName: name, Log: log.WithField("group", name), } for event := range log.Start() { ch <- event } done <- log.Err() }
[ "func", "(", "l", "*", "Logs", ")", "consume", "(", "name", "string", ",", "ch", "chan", "*", "Event", ",", "done", "chan", "error", ")", "{", "log", ":=", "Log", "{", "Config", ":", "l", ".", "Config", ",", "GroupName", ":", "name", ",", "Log", ":", "log", ".", "WithField", "(", "\"group\"", ",", "name", ")", ",", "}", "\n", "for", "event", ":=", "range", "log", ".", "Start", "(", ")", "{", "ch", "<-", "event", "\n", "}", "\n", "done", "<-", "log", ".", "Err", "(", ")", "\n", "}" ]
// consume logs for group `name`.
[ "consume", "logs", "for", "group", "name", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/logs/logs.go#L66-L78
train
apex/apex
cmd/apex/root/root.go
preRun
func preRun(c *cobra.Command, args []string) error { err := Prepare(c, args) if err != nil { return err } return Project.Open() }
go
func preRun(c *cobra.Command, args []string) error { err := Prepare(c, args) if err != nil { return err } return Project.Open() }
[ "func", "preRun", "(", "c", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "error", "{", "err", ":=", "Prepare", "(", "c", ",", "args", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "Project", ".", "Open", "(", ")", "\n", "}" ]
// preRun sets up global tasks used for most commands, some use PreRunNoop // to remove this default behaviour.
[ "preRun", "sets", "up", "global", "tasks", "used", "for", "most", "commands", "some", "use", "PreRunNoop", "to", "remove", "this", "default", "behaviour", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/root/root.go#L84-L91
train
apex/apex
utils/utils.go
Sha256
func Sha256(b []byte) string { h := sha256.New() h.Write(b) return base64.StdEncoding.EncodeToString(h.Sum(nil)) }
go
func Sha256(b []byte) string { h := sha256.New() h.Write(b) return base64.StdEncoding.EncodeToString(h.Sum(nil)) }
[ "func", "Sha256", "(", "b", "[", "]", "byte", ")", "string", "{", "h", ":=", "sha256", ".", "New", "(", ")", "\n", "h", ".", "Write", "(", "b", ")", "\n", "return", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "h", ".", "Sum", "(", "nil", ")", ")", "\n", "}" ]
// Sha256 returns a base64 encoded SHA256 hash of `b`.
[ "Sha256", "returns", "a", "base64", "encoded", "SHA256", "hash", "of", "b", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/utils/utils.go#L24-L28
train
apex/apex
utils/utils.go
LoadFiles
func LoadFiles(root string, ignoreFile []byte) (files []string, err error) { err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error { if err != nil { return err } mode := info.Mode() if !(mode.IsDir() || mode.IsRegular() || mode&os.ModeSymlink == os.ModeSymlink) { return nil } rel, err := filepath.Rel(root, path) if err != nil { return err } matched, err := gitignorer.GitIgnore(bytes.NewReader(ignoreFile), rel) if err != nil { return err } if mode.IsDir() && matched { return filepath.SkipDir } else if mode.IsDir() || matched { return nil } files = append(files, rel) return nil }) return }
go
func LoadFiles(root string, ignoreFile []byte) (files []string, err error) { err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error { if err != nil { return err } mode := info.Mode() if !(mode.IsDir() || mode.IsRegular() || mode&os.ModeSymlink == os.ModeSymlink) { return nil } rel, err := filepath.Rel(root, path) if err != nil { return err } matched, err := gitignorer.GitIgnore(bytes.NewReader(ignoreFile), rel) if err != nil { return err } if mode.IsDir() && matched { return filepath.SkipDir } else if mode.IsDir() || matched { return nil } files = append(files, rel) return nil }) return }
[ "func", "LoadFiles", "(", "root", "string", ",", "ignoreFile", "[", "]", "byte", ")", "(", "files", "[", "]", "string", ",", "err", "error", ")", "{", "err", "=", "filepath", ".", "Walk", "(", "root", ",", "func", "(", "path", "string", ",", "info", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "mode", ":=", "info", ".", "Mode", "(", ")", "\n", "if", "!", "(", "mode", ".", "IsDir", "(", ")", "||", "mode", ".", "IsRegular", "(", ")", "||", "mode", "&", "os", ".", "ModeSymlink", "==", "os", ".", "ModeSymlink", ")", "{", "return", "nil", "\n", "}", "\n", "rel", ",", "err", ":=", "filepath", ".", "Rel", "(", "root", ",", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "matched", ",", "err", ":=", "gitignorer", ".", "GitIgnore", "(", "bytes", ".", "NewReader", "(", "ignoreFile", ")", ",", "rel", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "mode", ".", "IsDir", "(", ")", "&&", "matched", "{", "return", "filepath", ".", "SkipDir", "\n", "}", "else", "if", "mode", ".", "IsDir", "(", ")", "||", "matched", "{", "return", "nil", "\n", "}", "\n", "files", "=", "append", "(", "files", ",", "rel", ")", "\n", "return", "nil", "\n", "}", ")", "\n", "return", "\n", "}" ]
// LoadFiles return filtered map of relative to 'root' file paths; // for filtering it uses shell file name pattern matching
[ "LoadFiles", "return", "filtered", "map", "of", "relative", "to", "root", "file", "paths", ";", "for", "filtering", "it", "uses", "shell", "file", "name", "pattern", "matching" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/utils/utils.go#L32-L65
train
apex/apex
utils/utils.go
ReadIgnoreFile
func ReadIgnoreFile(dir string) ([]byte, error) { path := filepath.Join(dir, ".apexignore") b, err := ioutil.ReadFile(path) if os.IsNotExist(err) { return nil, nil } if err != nil { return nil, err } return b, nil }
go
func ReadIgnoreFile(dir string) ([]byte, error) { path := filepath.Join(dir, ".apexignore") b, err := ioutil.ReadFile(path) if os.IsNotExist(err) { return nil, nil } if err != nil { return nil, err } return b, nil }
[ "func", "ReadIgnoreFile", "(", "dir", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "path", ":=", "filepath", ".", "Join", "(", "dir", ",", "\".apexignore\"", ")", "\n", "b", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "b", ",", "nil", "\n", "}" ]
// ReadIgnoreFile reads .apexignore in `dir` when present and returns a list of patterns.
[ "ReadIgnoreFile", "reads", ".", "apexignore", "in", "dir", "when", "present", "and", "returns", "a", "list", "of", "patterns", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/utils/utils.go#L94-L108
train
apex/apex
utils/utils.go
ContainsString
func ContainsString(array []string, element string) bool { for _, e := range array { if element == e { return true } } return false }
go
func ContainsString(array []string, element string) bool { for _, e := range array { if element == e { return true } } return false }
[ "func", "ContainsString", "(", "array", "[", "]", "string", ",", "element", "string", ")", "bool", "{", "for", "_", ",", "e", ":=", "range", "array", "{", "if", "element", "==", "e", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// ContainsString checks if array contains string
[ "ContainsString", "checks", "if", "array", "contains", "string" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/utils/utils.go#L111-L118
train
apex/apex
utils/utils.go
ParseEnv
func ParseEnv(env []string) (map[string]string, error) { m := make(map[string]string) for _, s := range env { parts := strings.SplitN(s, "=", 2) if len(parts) == 2 { m[parts[0]] = parts[1] } else { return nil, fmt.Errorf("environment variable %q is missing a value", parts[0]) } } return m, nil }
go
func ParseEnv(env []string) (map[string]string, error) { m := make(map[string]string) for _, s := range env { parts := strings.SplitN(s, "=", 2) if len(parts) == 2 { m[parts[0]] = parts[1] } else { return nil, fmt.Errorf("environment variable %q is missing a value", parts[0]) } } return m, nil }
[ "func", "ParseEnv", "(", "env", "[", "]", "string", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "m", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "for", "_", ",", "s", ":=", "range", "env", "{", "parts", ":=", "strings", ".", "SplitN", "(", "s", ",", "\"=\"", ",", "2", ")", "\n", "if", "len", "(", "parts", ")", "==", "2", "{", "m", "[", "parts", "[", "0", "]", "]", "=", "parts", "[", "1", "]", "\n", "}", "else", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"environment variable %q is missing a value\"", ",", "parts", "[", "0", "]", ")", "\n", "}", "\n", "}", "\n", "return", "m", ",", "nil", "\n", "}" ]
// ParseEnv accepts an `env` slice from the command-line and returns a map.
[ "ParseEnv", "accepts", "an", "env", "slice", "from", "the", "command", "-", "line", "and", "returns", "a", "map", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/utils/utils.go#L121-L134
train
apex/apex
utils/utils.go
ProfileAndRegionFromConfig
func ProfileAndRegionFromConfig(environment string) (string, string, error) { configFile := "project.json" if environment != "" { configFile = fmt.Sprintf("project.%s.json", environment) } f, err := os.Open(configFile) if err != nil { return "", "", err } defer f.Close() var v struct { Profile string `json:"profile"` Region string `json:"region"` } if err := json.NewDecoder(f).Decode(&v); err != nil { return "", "", err } return v.Profile, v.Region, nil }
go
func ProfileAndRegionFromConfig(environment string) (string, string, error) { configFile := "project.json" if environment != "" { configFile = fmt.Sprintf("project.%s.json", environment) } f, err := os.Open(configFile) if err != nil { return "", "", err } defer f.Close() var v struct { Profile string `json:"profile"` Region string `json:"region"` } if err := json.NewDecoder(f).Decode(&v); err != nil { return "", "", err } return v.Profile, v.Region, nil }
[ "func", "ProfileAndRegionFromConfig", "(", "environment", "string", ")", "(", "string", ",", "string", ",", "error", ")", "{", "configFile", ":=", "\"project.json\"", "\n", "if", "environment", "!=", "\"\"", "{", "configFile", "=", "fmt", ".", "Sprintf", "(", "\"project.%s.json\"", ",", "environment", ")", "\n", "}", "\n", "f", ",", "err", ":=", "os", ".", "Open", "(", "configFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "\"\"", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "var", "v", "struct", "{", "Profile", "string", "`json:\"profile\"`", "\n", "Region", "string", "`json:\"region\"`", "\n", "}", "\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "f", ")", ".", "Decode", "(", "&", "v", ")", ";", "err", "!=", "nil", "{", "return", "\"\"", ",", "\"\"", ",", "err", "\n", "}", "\n", "return", "v", ".", "Profile", ",", "v", ".", "Region", ",", "nil", "\n", "}" ]
// ProfileAndRegionFromConfig attempts to load the .profile setting from `environment`'s config.
[ "ProfileAndRegionFromConfig", "attempts", "to", "load", "the", ".", "profile", "setting", "from", "environment", "s", "config", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/utils/utils.go#L137-L160
train
apex/apex
utils/utils.go
AssumeRole
func AssumeRole(role string, config *aws.Config) (*aws.Config, error) { stscreds := sts.New(session.New(config)) params := &sts.AssumeRoleInput{ RoleArn: &role, RoleSessionName: aws.String("apex"), DurationSeconds: aws.Int64(1800), } res, err := stscreds.AssumeRole(params) if err != nil { return nil, err } id := *res.Credentials.AccessKeyId secret := *res.Credentials.SecretAccessKey token := *res.Credentials.SessionToken return &aws.Config{ Region: config.Region, Credentials: credentials.NewStaticCredentials(id, secret, token), }, nil }
go
func AssumeRole(role string, config *aws.Config) (*aws.Config, error) { stscreds := sts.New(session.New(config)) params := &sts.AssumeRoleInput{ RoleArn: &role, RoleSessionName: aws.String("apex"), DurationSeconds: aws.Int64(1800), } res, err := stscreds.AssumeRole(params) if err != nil { return nil, err } id := *res.Credentials.AccessKeyId secret := *res.Credentials.SecretAccessKey token := *res.Credentials.SessionToken return &aws.Config{ Region: config.Region, Credentials: credentials.NewStaticCredentials(id, secret, token), }, nil }
[ "func", "AssumeRole", "(", "role", "string", ",", "config", "*", "aws", ".", "Config", ")", "(", "*", "aws", ".", "Config", ",", "error", ")", "{", "stscreds", ":=", "sts", ".", "New", "(", "session", ".", "New", "(", "config", ")", ")", "\n", "params", ":=", "&", "sts", ".", "AssumeRoleInput", "{", "RoleArn", ":", "&", "role", ",", "RoleSessionName", ":", "aws", ".", "String", "(", "\"apex\"", ")", ",", "DurationSeconds", ":", "aws", ".", "Int64", "(", "1800", ")", ",", "}", "\n", "res", ",", "err", ":=", "stscreds", ".", "AssumeRole", "(", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "id", ":=", "*", "res", ".", "Credentials", ".", "AccessKeyId", "\n", "secret", ":=", "*", "res", ".", "Credentials", ".", "SecretAccessKey", "\n", "token", ":=", "*", "res", ".", "Credentials", ".", "SessionToken", "\n", "return", "&", "aws", ".", "Config", "{", "Region", ":", "config", ".", "Region", ",", "Credentials", ":", "credentials", ".", "NewStaticCredentials", "(", "id", ",", "secret", ",", "token", ")", ",", "}", ",", "nil", "\n", "}" ]
// AssumeRole uses STS to assume the given `role`.
[ "AssumeRole", "uses", "STS", "to", "assume", "the", "given", "role", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/utils/utils.go#L163-L185
train
apex/apex
project/project.go
Open
func (p *Project) Open() error { p.defaults() configFile := "project.json" if p.Environment != "" { configFile = fmt.Sprintf("project.%s.json", p.Environment) } f, err := os.Open(filepath.Join(p.Path, configFile)) if err != nil { return err } if err := json.NewDecoder(f).Decode(&p.Config); err != nil { return err } if p.InfraEnvironment == "" { p.InfraEnvironment = p.Config.DefaultEnvironment } if p.Role == "" { p.Role = p.readInfraRole() } if err := validator.Validate(&p.Config); err != nil { return err } t, err := template.New("nameTemplate").Parse(p.NameTemplate) if err != nil { return err } p.nameTemplate = t ignoreFile, err := utils.ReadIgnoreFile(p.Path) if err != nil { return err } p.IgnoreFile = append(p.IgnoreFile, ignoreFile...) return nil }
go
func (p *Project) Open() error { p.defaults() configFile := "project.json" if p.Environment != "" { configFile = fmt.Sprintf("project.%s.json", p.Environment) } f, err := os.Open(filepath.Join(p.Path, configFile)) if err != nil { return err } if err := json.NewDecoder(f).Decode(&p.Config); err != nil { return err } if p.InfraEnvironment == "" { p.InfraEnvironment = p.Config.DefaultEnvironment } if p.Role == "" { p.Role = p.readInfraRole() } if err := validator.Validate(&p.Config); err != nil { return err } t, err := template.New("nameTemplate").Parse(p.NameTemplate) if err != nil { return err } p.nameTemplate = t ignoreFile, err := utils.ReadIgnoreFile(p.Path) if err != nil { return err } p.IgnoreFile = append(p.IgnoreFile, ignoreFile...) return nil }
[ "func", "(", "p", "*", "Project", ")", "Open", "(", ")", "error", "{", "p", ".", "defaults", "(", ")", "\n", "configFile", ":=", "\"project.json\"", "\n", "if", "p", ".", "Environment", "!=", "\"\"", "{", "configFile", "=", "fmt", ".", "Sprintf", "(", "\"project.%s.json\"", ",", "p", ".", "Environment", ")", "\n", "}", "\n", "f", ",", "err", ":=", "os", ".", "Open", "(", "filepath", ".", "Join", "(", "p", ".", "Path", ",", "configFile", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "f", ")", ".", "Decode", "(", "&", "p", ".", "Config", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "p", ".", "InfraEnvironment", "==", "\"\"", "{", "p", ".", "InfraEnvironment", "=", "p", ".", "Config", ".", "DefaultEnvironment", "\n", "}", "\n", "if", "p", ".", "Role", "==", "\"\"", "{", "p", ".", "Role", "=", "p", ".", "readInfraRole", "(", ")", "\n", "}", "\n", "if", "err", ":=", "validator", ".", "Validate", "(", "&", "p", ".", "Config", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "t", ",", "err", ":=", "template", ".", "New", "(", "\"nameTemplate\"", ")", ".", "Parse", "(", "p", ".", "NameTemplate", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "p", ".", "nameTemplate", "=", "t", "\n", "ignoreFile", ",", "err", ":=", "utils", ".", "ReadIgnoreFile", "(", "p", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "p", ".", "IgnoreFile", "=", "append", "(", "p", ".", "IgnoreFile", ",", "ignoreFile", "...", ")", "\n", "return", "nil", "\n", "}" ]
// Open the project.json file and prime the config.
[ "Open", "the", "project", ".", "json", "file", "and", "prime", "the", "config", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L100-L142
train
apex/apex
project/project.go
DeployAndClean
func (p *Project) DeployAndClean() error { if err := p.Deploy(); err != nil { return err } return p.Clean() }
go
func (p *Project) DeployAndClean() error { if err := p.Deploy(); err != nil { return err } return p.Clean() }
[ "func", "(", "p", "*", "Project", ")", "DeployAndClean", "(", ")", "error", "{", "if", "err", ":=", "p", ".", "Deploy", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "p", ".", "Clean", "(", ")", "\n", "}" ]
// DeployAndClean deploys functions and then cleans up their build artifacts.
[ "DeployAndClean", "deploys", "functions", "and", "then", "cleans", "up", "their", "build", "artifacts", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L181-L187
train
apex/apex
project/project.go
Deploy
func (p *Project) Deploy() error { p.Log.Debugf("deploying %d functions", len(p.Functions)) sem := make(semaphore.Semaphore, p.Concurrency) errs := make(chan error) go func() { for _, fn := range p.Functions { fn := fn sem.Acquire() go func() { defer sem.Release() err := fn.Deploy() if err != nil { err = fmt.Errorf("function %s: %s", fn.Name, err) } errs <- err }() } sem.Wait() close(errs) }() for err := range errs { if err != nil { return err } } return nil }
go
func (p *Project) Deploy() error { p.Log.Debugf("deploying %d functions", len(p.Functions)) sem := make(semaphore.Semaphore, p.Concurrency) errs := make(chan error) go func() { for _, fn := range p.Functions { fn := fn sem.Acquire() go func() { defer sem.Release() err := fn.Deploy() if err != nil { err = fmt.Errorf("function %s: %s", fn.Name, err) } errs <- err }() } sem.Wait() close(errs) }() for err := range errs { if err != nil { return err } } return nil }
[ "func", "(", "p", "*", "Project", ")", "Deploy", "(", ")", "error", "{", "p", ".", "Log", ".", "Debugf", "(", "\"deploying %d functions\"", ",", "len", "(", "p", ".", "Functions", ")", ")", "\n", "sem", ":=", "make", "(", "semaphore", ".", "Semaphore", ",", "p", ".", "Concurrency", ")", "\n", "errs", ":=", "make", "(", "chan", "error", ")", "\n", "go", "func", "(", ")", "{", "for", "_", ",", "fn", ":=", "range", "p", ".", "Functions", "{", "fn", ":=", "fn", "\n", "sem", ".", "Acquire", "(", ")", "\n", "go", "func", "(", ")", "{", "defer", "sem", ".", "Release", "(", ")", "\n", "err", ":=", "fn", ".", "Deploy", "(", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"function %s: %s\"", ",", "fn", ".", "Name", ",", "err", ")", "\n", "}", "\n", "errs", "<-", "err", "\n", "}", "(", ")", "\n", "}", "\n", "sem", ".", "Wait", "(", ")", "\n", "close", "(", "errs", ")", "\n", "}", "(", ")", "\n", "for", "err", ":=", "range", "errs", "{", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Deploy functions and their configurations.
[ "Deploy", "functions", "and", "their", "configurations", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L190-L224
train
apex/apex
project/project.go
Clean
func (p *Project) Clean() error { p.Log.Debugf("cleaning %d functions", len(p.Functions)) for _, fn := range p.Functions { if err := fn.Clean(); err != nil { return fmt.Errorf("function %s: %s", fn.Name, err) } } return nil }
go
func (p *Project) Clean() error { p.Log.Debugf("cleaning %d functions", len(p.Functions)) for _, fn := range p.Functions { if err := fn.Clean(); err != nil { return fmt.Errorf("function %s: %s", fn.Name, err) } } return nil }
[ "func", "(", "p", "*", "Project", ")", "Clean", "(", ")", "error", "{", "p", ".", "Log", ".", "Debugf", "(", "\"cleaning %d functions\"", ",", "len", "(", "p", ".", "Functions", ")", ")", "\n", "for", "_", ",", "fn", ":=", "range", "p", ".", "Functions", "{", "if", "err", ":=", "fn", ".", "Clean", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"function %s: %s\"", ",", "fn", ".", "Name", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Clean up function build artifacts.
[ "Clean", "up", "function", "build", "artifacts", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L227-L237
train
apex/apex
project/project.go
Delete
func (p *Project) Delete() error { p.Log.Debugf("deleting %d functions", len(p.Functions)) for _, fn := range p.Functions { if _, err := fn.GetConfig(); err != nil { if awserr, ok := err.(awserr.Error); ok && awserr.Code() == "ResourceNotFoundException" { p.Log.Infof("function %q hasn't been deployed yet or has been deleted manually on AWS Lambda", fn.Name) continue } return fmt.Errorf("function %s: %s", fn.Name, err) } if err := fn.Delete(); err != nil { return fmt.Errorf("function %s: %s", fn.Name, err) } } return nil }
go
func (p *Project) Delete() error { p.Log.Debugf("deleting %d functions", len(p.Functions)) for _, fn := range p.Functions { if _, err := fn.GetConfig(); err != nil { if awserr, ok := err.(awserr.Error); ok && awserr.Code() == "ResourceNotFoundException" { p.Log.Infof("function %q hasn't been deployed yet or has been deleted manually on AWS Lambda", fn.Name) continue } return fmt.Errorf("function %s: %s", fn.Name, err) } if err := fn.Delete(); err != nil { return fmt.Errorf("function %s: %s", fn.Name, err) } } return nil }
[ "func", "(", "p", "*", "Project", ")", "Delete", "(", ")", "error", "{", "p", ".", "Log", ".", "Debugf", "(", "\"deleting %d functions\"", ",", "len", "(", "p", ".", "Functions", ")", ")", "\n", "for", "_", ",", "fn", ":=", "range", "p", ".", "Functions", "{", "if", "_", ",", "err", ":=", "fn", ".", "GetConfig", "(", ")", ";", "err", "!=", "nil", "{", "if", "awserr", ",", "ok", ":=", "err", ".", "(", "awserr", ".", "Error", ")", ";", "ok", "&&", "awserr", ".", "Code", "(", ")", "==", "\"ResourceNotFoundException\"", "{", "p", ".", "Log", ".", "Infof", "(", "\"function %q hasn't been deployed yet or has been deleted manually on AWS Lambda\"", ",", "fn", ".", "Name", ")", "\n", "continue", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"function %s: %s\"", ",", "fn", ".", "Name", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "fn", ".", "Delete", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"function %s: %s\"", ",", "fn", ".", "Name", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Delete functions.
[ "Delete", "functions", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L240-L258
train
apex/apex
project/project.go
RollbackVersion
func (p *Project) RollbackVersion(version string) error { p.Log.Debugf("rolling back %d functions to version %s", len(p.Functions), version) for _, fn := range p.Functions { if err := fn.RollbackVersion(version); err != nil { return fmt.Errorf("function %s: %s", fn.Name, err) } } return nil }
go
func (p *Project) RollbackVersion(version string) error { p.Log.Debugf("rolling back %d functions to version %s", len(p.Functions), version) for _, fn := range p.Functions { if err := fn.RollbackVersion(version); err != nil { return fmt.Errorf("function %s: %s", fn.Name, err) } } return nil }
[ "func", "(", "p", "*", "Project", ")", "RollbackVersion", "(", "version", "string", ")", "error", "{", "p", ".", "Log", ".", "Debugf", "(", "\"rolling back %d functions to version %s\"", ",", "len", "(", "p", ".", "Functions", ")", ",", "version", ")", "\n", "for", "_", ",", "fn", ":=", "range", "p", ".", "Functions", "{", "if", "err", ":=", "fn", ".", "RollbackVersion", "(", "version", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"function %s: %s\"", ",", "fn", ".", "Name", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// RollbackVersion project functions to the specified version.
[ "RollbackVersion", "project", "functions", "to", "the", "specified", "version", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L274-L284
train
apex/apex
project/project.go
FunctionDirNames
func (p *Project) FunctionDirNames() (list []string, err error) { dir := filepath.Join(p.Path, functionsDir) files, err := ioutil.ReadDir(dir) if err != nil { return nil, err } for _, file := range files { if file.IsDir() { list = append(list, file.Name()) } } return list, nil }
go
func (p *Project) FunctionDirNames() (list []string, err error) { dir := filepath.Join(p.Path, functionsDir) files, err := ioutil.ReadDir(dir) if err != nil { return nil, err } for _, file := range files { if file.IsDir() { list = append(list, file.Name()) } } return list, nil }
[ "func", "(", "p", "*", "Project", ")", "FunctionDirNames", "(", ")", "(", "list", "[", "]", "string", ",", "err", "error", ")", "{", "dir", ":=", "filepath", ".", "Join", "(", "p", ".", "Path", ",", "functionsDir", ")", "\n", "files", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "dir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "file", ":=", "range", "files", "{", "if", "file", ".", "IsDir", "(", ")", "{", "list", "=", "append", "(", "list", ",", "file", ".", "Name", "(", ")", ")", "\n", "}", "\n", "}", "\n", "return", "list", ",", "nil", "\n", "}" ]
// FunctionDirNames returns a list of function directory names.
[ "FunctionDirNames", "returns", "a", "list", "of", "function", "directory", "names", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L287-L302
train
apex/apex
project/project.go
LoadEnvFromFile
func (p *Project) LoadEnvFromFile(path string) error { p.Log.Debugf("load env from file %q", path) var env map[string]string f, err := os.Open(path) if err != nil { return err } defer f.Close() if err := json.NewDecoder(f).Decode(&env); err != nil { return err } for k, v := range env { p.Setenv(k, v) } return nil }
go
func (p *Project) LoadEnvFromFile(path string) error { p.Log.Debugf("load env from file %q", path) var env map[string]string f, err := os.Open(path) if err != nil { return err } defer f.Close() if err := json.NewDecoder(f).Decode(&env); err != nil { return err } for k, v := range env { p.Setenv(k, v) } return nil }
[ "func", "(", "p", "*", "Project", ")", "LoadEnvFromFile", "(", "path", "string", ")", "error", "{", "p", ".", "Log", ".", "Debugf", "(", "\"load env from file %q\"", ",", "path", ")", "\n", "var", "env", "map", "[", "string", "]", "string", "\n", "f", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "f", ")", ".", "Decode", "(", "&", "env", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "k", ",", "v", ":=", "range", "env", "{", "p", ".", "Setenv", "(", "k", ",", "v", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// LoadEnvFromFile reads `path` JSON and applies it to the environment.
[ "LoadEnvFromFile", "reads", "path", "JSON", "and", "applies", "it", "to", "the", "environment", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L305-L324
train
apex/apex
project/project.go
Setenv
func (p *Project) Setenv(name, value string) { for _, fn := range p.Functions { fn.Setenv(name, value) } }
go
func (p *Project) Setenv(name, value string) { for _, fn := range p.Functions { fn.Setenv(name, value) } }
[ "func", "(", "p", "*", "Project", ")", "Setenv", "(", "name", ",", "value", "string", ")", "{", "for", "_", ",", "fn", ":=", "range", "p", ".", "Functions", "{", "fn", ".", "Setenv", "(", "name", ",", "value", ")", "\n", "}", "\n", "}" ]
// Setenv sets environment variable `name` to `value` on every function in project.
[ "Setenv", "sets", "environment", "variable", "name", "to", "value", "on", "every", "function", "in", "project", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L327-L331
train
apex/apex
project/project.go
LoadFunctionByPath
func (p *Project) LoadFunctionByPath(name, path string) (*function.Function, error) { fn := &function.Function{ Config: function.Config{ Runtime: p.Runtime, Memory: p.Memory, Timeout: p.Timeout, Role: p.Role, Handler: p.Handler, Shim: p.Shim, Hooks: p.Hooks, Environment: copyStringMap(p.Config.Environment), RetainedVersions: p.RetainedVersions, VPC: copyVPC(p.VPC), Zip: p.Zip, }, Name: name, Path: path, Log: p.Log, IgnoreFile: p.IgnoreFile, Alias: p.Alias, } if name, err := p.name(fn); err == nil { fn.FunctionName = name } else { return nil, err } if err := fn.Open(p.Environment); err != nil { return nil, err } fn.Service = p.ServiceProvider.NewService(fn.AWSConfig()) return fn, nil }
go
func (p *Project) LoadFunctionByPath(name, path string) (*function.Function, error) { fn := &function.Function{ Config: function.Config{ Runtime: p.Runtime, Memory: p.Memory, Timeout: p.Timeout, Role: p.Role, Handler: p.Handler, Shim: p.Shim, Hooks: p.Hooks, Environment: copyStringMap(p.Config.Environment), RetainedVersions: p.RetainedVersions, VPC: copyVPC(p.VPC), Zip: p.Zip, }, Name: name, Path: path, Log: p.Log, IgnoreFile: p.IgnoreFile, Alias: p.Alias, } if name, err := p.name(fn); err == nil { fn.FunctionName = name } else { return nil, err } if err := fn.Open(p.Environment); err != nil { return nil, err } fn.Service = p.ServiceProvider.NewService(fn.AWSConfig()) return fn, nil }
[ "func", "(", "p", "*", "Project", ")", "LoadFunctionByPath", "(", "name", ",", "path", "string", ")", "(", "*", "function", ".", "Function", ",", "error", ")", "{", "fn", ":=", "&", "function", ".", "Function", "{", "Config", ":", "function", ".", "Config", "{", "Runtime", ":", "p", ".", "Runtime", ",", "Memory", ":", "p", ".", "Memory", ",", "Timeout", ":", "p", ".", "Timeout", ",", "Role", ":", "p", ".", "Role", ",", "Handler", ":", "p", ".", "Handler", ",", "Shim", ":", "p", ".", "Shim", ",", "Hooks", ":", "p", ".", "Hooks", ",", "Environment", ":", "copyStringMap", "(", "p", ".", "Config", ".", "Environment", ")", ",", "RetainedVersions", ":", "p", ".", "RetainedVersions", ",", "VPC", ":", "copyVPC", "(", "p", ".", "VPC", ")", ",", "Zip", ":", "p", ".", "Zip", ",", "}", ",", "Name", ":", "name", ",", "Path", ":", "path", ",", "Log", ":", "p", ".", "Log", ",", "IgnoreFile", ":", "p", ".", "IgnoreFile", ",", "Alias", ":", "p", ".", "Alias", ",", "}", "\n", "if", "name", ",", "err", ":=", "p", ".", "name", "(", "fn", ")", ";", "err", "==", "nil", "{", "fn", ".", "FunctionName", "=", "name", "\n", "}", "else", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "fn", ".", "Open", "(", "p", ".", "Environment", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "fn", ".", "Service", "=", "p", ".", "ServiceProvider", ".", "NewService", "(", "fn", ".", "AWSConfig", "(", ")", ")", "\n", "return", "fn", ",", "nil", "\n", "}" ]
// LoadFunctionByPath returns the function in the given directory.
[ "LoadFunctionByPath", "returns", "the", "function", "in", "the", "given", "directory", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L339-L374
train
apex/apex
project/project.go
CreateOrUpdateAlias
func (p *Project) CreateOrUpdateAlias(alias, version string) error { p.Log.Debugf("updating %d functions", len(p.Functions)) sem := make(semaphore.Semaphore, p.Concurrency) errs := make(chan error) go func() { for _, fn := range p.Functions { fn := fn sem.Acquire() go func() { defer sem.Release() version, err := fn.GetVersionFromAlias(version) if err != nil { err = fmt.Errorf("function %s: %s", fn.Name, err) } err = fn.CreateOrUpdateAlias(alias, version) if err != nil { err = fmt.Errorf("function %s: %s", fn.Name, err) } errs <- err }() } sem.Wait() close(errs) }() for err := range errs { if err != nil { return err } } return nil }
go
func (p *Project) CreateOrUpdateAlias(alias, version string) error { p.Log.Debugf("updating %d functions", len(p.Functions)) sem := make(semaphore.Semaphore, p.Concurrency) errs := make(chan error) go func() { for _, fn := range p.Functions { fn := fn sem.Acquire() go func() { defer sem.Release() version, err := fn.GetVersionFromAlias(version) if err != nil { err = fmt.Errorf("function %s: %s", fn.Name, err) } err = fn.CreateOrUpdateAlias(alias, version) if err != nil { err = fmt.Errorf("function %s: %s", fn.Name, err) } errs <- err }() } sem.Wait() close(errs) }() for err := range errs { if err != nil { return err } } return nil }
[ "func", "(", "p", "*", "Project", ")", "CreateOrUpdateAlias", "(", "alias", ",", "version", "string", ")", "error", "{", "p", ".", "Log", ".", "Debugf", "(", "\"updating %d functions\"", ",", "len", "(", "p", ".", "Functions", ")", ")", "\n", "sem", ":=", "make", "(", "semaphore", ".", "Semaphore", ",", "p", ".", "Concurrency", ")", "\n", "errs", ":=", "make", "(", "chan", "error", ")", "\n", "go", "func", "(", ")", "{", "for", "_", ",", "fn", ":=", "range", "p", ".", "Functions", "{", "fn", ":=", "fn", "\n", "sem", ".", "Acquire", "(", ")", "\n", "go", "func", "(", ")", "{", "defer", "sem", ".", "Release", "(", ")", "\n", "version", ",", "err", ":=", "fn", ".", "GetVersionFromAlias", "(", "version", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"function %s: %s\"", ",", "fn", ".", "Name", ",", "err", ")", "\n", "}", "\n", "err", "=", "fn", ".", "CreateOrUpdateAlias", "(", "alias", ",", "version", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"function %s: %s\"", ",", "fn", ".", "Name", ",", "err", ")", "\n", "}", "\n", "errs", "<-", "err", "\n", "}", "(", ")", "\n", "}", "\n", "sem", ".", "Wait", "(", ")", "\n", "close", "(", "errs", ")", "\n", "}", "(", ")", "\n", "for", "err", ":=", "range", "errs", "{", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CreateOrUpdateAlias ensures the given `alias` is available for `version`.
[ "CreateOrUpdateAlias", "ensures", "the", "given", "alias", "is", "available", "for", "version", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L377-L416
train
apex/apex
project/project.go
name
func (p *Project) name(fn *function.Function) (string, error) { data := struct { Project *Project Function *function.Function }{ Project: p, Function: fn, } name, err := render(p.nameTemplate, data) if err != nil { return "", err } return name, nil }
go
func (p *Project) name(fn *function.Function) (string, error) { data := struct { Project *Project Function *function.Function }{ Project: p, Function: fn, } name, err := render(p.nameTemplate, data) if err != nil { return "", err } return name, nil }
[ "func", "(", "p", "*", "Project", ")", "name", "(", "fn", "*", "function", ".", "Function", ")", "(", "string", ",", "error", ")", "{", "data", ":=", "struct", "{", "Project", "*", "Project", "\n", "Function", "*", "function", ".", "Function", "\n", "}", "{", "Project", ":", "p", ",", "Function", ":", "fn", ",", "}", "\n", "name", ",", "err", ":=", "render", "(", "p", ".", "nameTemplate", ",", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "return", "name", ",", "nil", "\n", "}" ]
// name returns the computed name for `fn`, using the nameTemplate.
[ "name", "returns", "the", "computed", "name", "for", "fn", "using", "the", "nameTemplate", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L419-L434
train
apex/apex
project/project.go
readInfraRole
func (p *Project) readInfraRole() string { role, err := infra.Output(p.InfraEnvironment, "lambda_function_role_id") if err != nil { p.Log.Debugf("couldn't read role from infrastructure: %s", err) return "" } return role }
go
func (p *Project) readInfraRole() string { role, err := infra.Output(p.InfraEnvironment, "lambda_function_role_id") if err != nil { p.Log.Debugf("couldn't read role from infrastructure: %s", err) return "" } return role }
[ "func", "(", "p", "*", "Project", ")", "readInfraRole", "(", ")", "string", "{", "role", ",", "err", ":=", "infra", ".", "Output", "(", "p", ".", "InfraEnvironment", ",", "\"lambda_function_role_id\"", ")", "\n", "if", "err", "!=", "nil", "{", "p", ".", "Log", ".", "Debugf", "(", "\"couldn't read role from infrastructure: %s\"", ",", "err", ")", "\n", "return", "\"\"", "\n", "}", "\n", "return", "role", "\n", "}" ]
// readInfraRole reads lambda function IAM role from infrastructure
[ "readInfraRole", "reads", "lambda", "function", "IAM", "role", "from", "infrastructure" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L437-L445
train
apex/apex
project/project.go
render
func render(t *template.Template, v interface{}) (string, error) { buf := new(bytes.Buffer) if err := t.Execute(buf, v); err != nil { return "", err } return buf.String(), nil }
go
func render(t *template.Template, v interface{}) (string, error) { buf := new(bytes.Buffer) if err := t.Execute(buf, v); err != nil { return "", err } return buf.String(), nil }
[ "func", "render", "(", "t", "*", "template", ".", "Template", ",", "v", "interface", "{", "}", ")", "(", "string", ",", "error", ")", "{", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "if", "err", ":=", "t", ".", "Execute", "(", "buf", ",", "v", ")", ";", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "return", "buf", ".", "String", "(", ")", ",", "nil", "\n", "}" ]
// render returns a string by executing template `t` against the given value `v`.
[ "render", "returns", "a", "string", "by", "executing", "template", "t", "against", "the", "given", "value", "v", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L448-L456
train
apex/apex
project/project.go
copyVPC
func copyVPC(in vpc.VPC) vpc.VPC { securityGroups := make([]string, len(in.SecurityGroups)) copy(securityGroups, in.SecurityGroups) subnets := make([]string, len(in.Subnets)) copy(subnets, in.Subnets) return vpc.VPC{ SecurityGroups: securityGroups, Subnets: subnets, } }
go
func copyVPC(in vpc.VPC) vpc.VPC { securityGroups := make([]string, len(in.SecurityGroups)) copy(securityGroups, in.SecurityGroups) subnets := make([]string, len(in.Subnets)) copy(subnets, in.Subnets) return vpc.VPC{ SecurityGroups: securityGroups, Subnets: subnets, } }
[ "func", "copyVPC", "(", "in", "vpc", ".", "VPC", ")", "vpc", ".", "VPC", "{", "securityGroups", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "in", ".", "SecurityGroups", ")", ")", "\n", "copy", "(", "securityGroups", ",", "in", ".", "SecurityGroups", ")", "\n", "subnets", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "in", ".", "Subnets", ")", ")", "\n", "copy", "(", "subnets", ",", "in", ".", "Subnets", ")", "\n", "return", "vpc", ".", "VPC", "{", "SecurityGroups", ":", "securityGroups", ",", "Subnets", ":", "subnets", ",", "}", "\n", "}" ]
// copyVPC returns a copy of `in`.
[ "copyVPC", "returns", "a", "copy", "of", "in", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L468-L478
train
apex/apex
project/project.go
matches
func matches(name string, patterns []string) (bool, error) { if len(patterns) == 0 { return true, nil } for _, pattern := range patterns { match, err := filepath.Match(pattern, name) if err != nil { return false, err } if match { return true, nil } } return false, nil }
go
func matches(name string, patterns []string) (bool, error) { if len(patterns) == 0 { return true, nil } for _, pattern := range patterns { match, err := filepath.Match(pattern, name) if err != nil { return false, err } if match { return true, nil } } return false, nil }
[ "func", "matches", "(", "name", "string", ",", "patterns", "[", "]", "string", ")", "(", "bool", ",", "error", ")", "{", "if", "len", "(", "patterns", ")", "==", "0", "{", "return", "true", ",", "nil", "\n", "}", "\n", "for", "_", ",", "pattern", ":=", "range", "patterns", "{", "match", ",", "err", ":=", "filepath", ".", "Match", "(", "pattern", ",", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "if", "match", "{", "return", "true", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "false", ",", "nil", "\n", "}" ]
// matches returns true if `name` is matched by any of the given `patterns`, // or if zero `patterns` are provided.
[ "matches", "returns", "true", "if", "name", "is", "matched", "by", "any", "of", "the", "given", "patterns", "or", "if", "zero", "patterns", "are", "provided", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L482-L499
train
apex/apex
internal/progressreader/progressreader.go
Read
func (r *reader) Read(b []byte) (int, error) { r.Do(term.ClearAll) n, err := r.ReadCloser.Read(b) r.written += n r.p.ValueInt(r.written) r.render(term.CenterLine(r.p.String())) return n, err }
go
func (r *reader) Read(b []byte) (int, error) { r.Do(term.ClearAll) n, err := r.ReadCloser.Read(b) r.written += n r.p.ValueInt(r.written) r.render(term.CenterLine(r.p.String())) return n, err }
[ "func", "(", "r", "*", "reader", ")", "Read", "(", "b", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "r", ".", "Do", "(", "term", ".", "ClearAll", ")", "\n", "n", ",", "err", ":=", "r", ".", "ReadCloser", ".", "Read", "(", "b", ")", "\n", "r", ".", "written", "+=", "n", "\n", "r", ".", "p", ".", "ValueInt", "(", "r", ".", "written", ")", "\n", "r", ".", "render", "(", "term", ".", "CenterLine", "(", "r", ".", "p", ".", "String", "(", ")", ")", ")", "\n", "return", "n", ",", "err", "\n", "}" ]
// Read implementation.
[ "Read", "implementation", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/progressreader/progressreader.go#L24-L31
train
apex/apex
internal/progressreader/progressreader.go
New
func New(size int, r io.ReadCloser) io.ReadCloser { return &reader{ ReadCloser: r, p: util.NewProgressInt(size), render: term.Renderer(), } }
go
func New(size int, r io.ReadCloser) io.ReadCloser { return &reader{ ReadCloser: r, p: util.NewProgressInt(size), render: term.Renderer(), } }
[ "func", "New", "(", "size", "int", ",", "r", "io", ".", "ReadCloser", ")", "io", ".", "ReadCloser", "{", "return", "&", "reader", "{", "ReadCloser", ":", "r", ",", "p", ":", "util", ".", "NewProgressInt", "(", "size", ")", ",", "render", ":", "term", ".", "Renderer", "(", ")", ",", "}", "\n", "}" ]
// New returns a progress bar reader.
[ "New", "returns", "a", "progress", "bar", "reader", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/progressreader/progressreader.go#L34-L40
train
apex/apex
metrics/metric.go
Collect
func (m *Metric) Collect() (a AggregatedMetrics) { for n := range m.collect(m.gen()) { value := aggregate(n.Value) switch n.Name { case "Duration": a.Duration = value case "Errors": a.Errors = value case "Invocations": a.Invocations = value case "Throttles": a.Throttles = value } } return }
go
func (m *Metric) Collect() (a AggregatedMetrics) { for n := range m.collect(m.gen()) { value := aggregate(n.Value) switch n.Name { case "Duration": a.Duration = value case "Errors": a.Errors = value case "Invocations": a.Invocations = value case "Throttles": a.Throttles = value } } return }
[ "func", "(", "m", "*", "Metric", ")", "Collect", "(", ")", "(", "a", "AggregatedMetrics", ")", "{", "for", "n", ":=", "range", "m", ".", "collect", "(", "m", ".", "gen", "(", ")", ")", "{", "value", ":=", "aggregate", "(", "n", ".", "Value", ")", "\n", "switch", "n", ".", "Name", "{", "case", "\"Duration\"", ":", "a", ".", "Duration", "=", "value", "\n", "case", "\"Errors\"", ":", "a", ".", "Errors", "=", "value", "\n", "case", "\"Invocations\"", ":", "a", ".", "Invocations", "=", "value", "\n", "case", "\"Throttles\"", ":", "a", ".", "Throttles", "=", "value", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Collect and aggregate metrics for on function.
[ "Collect", "and", "aggregate", "metrics", "for", "on", "function", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/metrics/metric.go#L21-L38
train
apex/apex
metrics/metric.go
stats
func (m *Metric) stats(name string) (*cloudwatch.GetMetricStatisticsOutput, error) { return m.Service.GetMetricStatistics(&cloudwatch.GetMetricStatisticsInput{ StartTime: &m.StartDate, EndTime: &m.EndDate, MetricName: &name, Namespace: aws.String("AWS/Lambda"), Period: aws.Int64(int64(period(m.StartDate, m.EndDate).Seconds())), Statistics: []*string{ aws.String("Sum"), }, Dimensions: []*cloudwatch.Dimension{ { Name: aws.String("FunctionName"), Value: &m.FunctionName, }, }, Unit: aws.String(unit(name)), }) }
go
func (m *Metric) stats(name string) (*cloudwatch.GetMetricStatisticsOutput, error) { return m.Service.GetMetricStatistics(&cloudwatch.GetMetricStatisticsInput{ StartTime: &m.StartDate, EndTime: &m.EndDate, MetricName: &name, Namespace: aws.String("AWS/Lambda"), Period: aws.Int64(int64(period(m.StartDate, m.EndDate).Seconds())), Statistics: []*string{ aws.String("Sum"), }, Dimensions: []*cloudwatch.Dimension{ { Name: aws.String("FunctionName"), Value: &m.FunctionName, }, }, Unit: aws.String(unit(name)), }) }
[ "func", "(", "m", "*", "Metric", ")", "stats", "(", "name", "string", ")", "(", "*", "cloudwatch", ".", "GetMetricStatisticsOutput", ",", "error", ")", "{", "return", "m", ".", "Service", ".", "GetMetricStatistics", "(", "&", "cloudwatch", ".", "GetMetricStatisticsInput", "{", "StartTime", ":", "&", "m", ".", "StartDate", ",", "EndTime", ":", "&", "m", ".", "EndDate", ",", "MetricName", ":", "&", "name", ",", "Namespace", ":", "aws", ".", "String", "(", "\"AWS/Lambda\"", ")", ",", "Period", ":", "aws", ".", "Int64", "(", "int64", "(", "period", "(", "m", ".", "StartDate", ",", "m", ".", "EndDate", ")", ".", "Seconds", "(", ")", ")", ")", ",", "Statistics", ":", "[", "]", "*", "string", "{", "aws", ".", "String", "(", "\"Sum\"", ")", ",", "}", ",", "Dimensions", ":", "[", "]", "*", "cloudwatch", ".", "Dimension", "{", "{", "Name", ":", "aws", ".", "String", "(", "\"FunctionName\"", ")", ",", "Value", ":", "&", "m", ".", "FunctionName", ",", "}", ",", "}", ",", "Unit", ":", "aws", ".", "String", "(", "unit", "(", "name", ")", ")", ",", "}", ")", "\n", "}" ]
// stats for function `name`.
[ "stats", "for", "function", "name", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/metrics/metric.go#L47-L65
train
apex/apex
metrics/metric.go
collect
func (m *Metric) collect(in <-chan string) <-chan cloudWatchMetric { var wg sync.WaitGroup out := make(chan cloudWatchMetric) for name := range in { wg.Add(1) name := name go func() { defer wg.Done() res, err := m.stats(name) if err != nil { // TODO: refactor so that errors are reported in cmd fmt.Println(err.Error()) return } out <- cloudWatchMetric{ Name: name, Value: res.Datapoints, } }() } go func() { wg.Wait() close(out) }() return out }
go
func (m *Metric) collect(in <-chan string) <-chan cloudWatchMetric { var wg sync.WaitGroup out := make(chan cloudWatchMetric) for name := range in { wg.Add(1) name := name go func() { defer wg.Done() res, err := m.stats(name) if err != nil { // TODO: refactor so that errors are reported in cmd fmt.Println(err.Error()) return } out <- cloudWatchMetric{ Name: name, Value: res.Datapoints, } }() } go func() { wg.Wait() close(out) }() return out }
[ "func", "(", "m", "*", "Metric", ")", "collect", "(", "in", "<-", "chan", "string", ")", "<-", "chan", "cloudWatchMetric", "{", "var", "wg", "sync", ".", "WaitGroup", "\n", "out", ":=", "make", "(", "chan", "cloudWatchMetric", ")", "\n", "for", "name", ":=", "range", "in", "{", "wg", ".", "Add", "(", "1", ")", "\n", "name", ":=", "name", "\n", "go", "func", "(", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "res", ",", "err", ":=", "m", ".", "stats", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Println", "(", "err", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n", "out", "<-", "cloudWatchMetric", "{", "Name", ":", "name", ",", "Value", ":", "res", ".", "Datapoints", ",", "}", "\n", "}", "(", ")", "\n", "}", "\n", "go", "func", "(", ")", "{", "wg", ".", "Wait", "(", ")", "\n", "close", "(", "out", ")", "\n", "}", "(", ")", "\n", "return", "out", "\n", "}" ]
// collect starts a new cloudwatch session and requests the key metrics.
[ "collect", "starts", "a", "new", "cloudwatch", "session", "and", "requests", "the", "key", "metrics", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/metrics/metric.go#L68-L99
train
apex/apex
metrics/metric.go
gen
func (m *Metric) gen() <-chan string { out := make(chan string, len(metricsNames)) for _, n := range metricsNames { out <- n } close(out) return out }
go
func (m *Metric) gen() <-chan string { out := make(chan string, len(metricsNames)) for _, n := range metricsNames { out <- n } close(out) return out }
[ "func", "(", "m", "*", "Metric", ")", "gen", "(", ")", "<-", "chan", "string", "{", "out", ":=", "make", "(", "chan", "string", ",", "len", "(", "metricsNames", ")", ")", "\n", "for", "_", ",", "n", ":=", "range", "metricsNames", "{", "out", "<-", "n", "\n", "}", "\n", "close", "(", "out", ")", "\n", "return", "out", "\n", "}" ]
// gen generates the key metric structs and returns a channel pipeline.
[ "gen", "generates", "the", "key", "metric", "structs", "and", "returns", "a", "channel", "pipeline", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/metrics/metric.go#L102-L109
train
apex/apex
metrics/metric.go
period
func period(start, end time.Time) time.Duration { switch n := end.Sub(start).Hours(); { case n > 24: return time.Hour * 24 default: return time.Hour } }
go
func period(start, end time.Time) time.Duration { switch n := end.Sub(start).Hours(); { case n > 24: return time.Hour * 24 default: return time.Hour } }
[ "func", "period", "(", "start", ",", "end", "time", ".", "Time", ")", "time", ".", "Duration", "{", "switch", "n", ":=", "end", ".", "Sub", "(", "start", ")", ".", "Hours", "(", ")", ";", "{", "case", "n", ">", "24", ":", "return", "time", ".", "Hour", "*", "24", "\n", "default", ":", "return", "time", ".", "Hour", "\n", "}", "\n", "}" ]
// period returns the resolution of metrics.
[ "period", "returns", "the", "resolution", "of", "metrics", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/metrics/metric.go#L112-L119
train
apex/apex
metrics/metric.go
aggregate
func aggregate(datapoints []*cloudwatch.Datapoint) int { sum := 0.0 for _, datapoint := range datapoints { sum += *datapoint.Sum } return int(sum) }
go
func aggregate(datapoints []*cloudwatch.Datapoint) int { sum := 0.0 for _, datapoint := range datapoints { sum += *datapoint.Sum } return int(sum) }
[ "func", "aggregate", "(", "datapoints", "[", "]", "*", "cloudwatch", ".", "Datapoint", ")", "int", "{", "sum", ":=", "0.0", "\n", "for", "_", ",", "datapoint", ":=", "range", "datapoints", "{", "sum", "+=", "*", "datapoint", ".", "Sum", "\n", "}", "\n", "return", "int", "(", "sum", ")", "\n", "}" ]
// aggregate accumulates the datapoints.
[ "aggregate", "accumulates", "the", "datapoints", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/metrics/metric.go#L132-L140
train
apex/apex
plugins/hooks/hooks.go
Error
func (e *HookError) Error() string { return fmt.Sprintf("%s hook: %s", e.Hook, e.Output) }
go
func (e *HookError) Error() string { return fmt.Sprintf("%s hook: %s", e.Hook, e.Output) }
[ "func", "(", "e", "*", "HookError", ")", "Error", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"%s hook: %s\"", ",", "e", ".", "Hook", ",", "e", ".", "Output", ")", "\n", "}" ]
// Error string.
[ "Error", "string", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/plugins/hooks/hooks.go#L28-L30
train
apex/apex
plugins/hooks/hooks.go
Build
func (p *Plugin) Build(fn *function.Function, zip *archive.Zip) error { return p.run("build", fn.Hooks.Build, fn) }
go
func (p *Plugin) Build(fn *function.Function, zip *archive.Zip) error { return p.run("build", fn.Hooks.Build, fn) }
[ "func", "(", "p", "*", "Plugin", ")", "Build", "(", "fn", "*", "function", ".", "Function", ",", "zip", "*", "archive", ".", "Zip", ")", "error", "{", "return", "p", ".", "run", "(", "\"build\"", ",", "fn", ".", "Hooks", ".", "Build", ",", "fn", ")", "\n", "}" ]
// Build runs the "build" hook commands.
[ "Build", "runs", "the", "build", "hook", "commands", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/plugins/hooks/hooks.go#L36-L38
train
apex/apex
plugins/hooks/hooks.go
Deploy
func (p *Plugin) Deploy(fn *function.Function) error { return p.run("deploy", fn.Hooks.Deploy, fn) }
go
func (p *Plugin) Deploy(fn *function.Function) error { return p.run("deploy", fn.Hooks.Deploy, fn) }
[ "func", "(", "p", "*", "Plugin", ")", "Deploy", "(", "fn", "*", "function", ".", "Function", ")", "error", "{", "return", "p", ".", "run", "(", "\"deploy\"", ",", "fn", ".", "Hooks", ".", "Deploy", ",", "fn", ")", "\n", "}" ]
// Deploy runs the "deploy" hook commands.
[ "Deploy", "runs", "the", "deploy", "hook", "commands", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/plugins/hooks/hooks.go#L46-L48
train
apex/apex
plugins/hooks/hooks.go
run
func (p *Plugin) run(hook, command string, fn *function.Function) error { if command == "" { return nil } fn.Log.WithFields(log.Fields{ "hook": hook, "command": command, }).Debug("hook") var cmd *exec.Cmd if runtime.GOOS == "windows" { cmd = exec.Command("cmd", "/c", command) } else { cmd = exec.Command("sh", "-c", command) } cmd.Env = os.Environ() cmd.Dir = fn.Path b, err := cmd.CombinedOutput() if err != nil { return &HookError{ Hook: hook, Command: command, Output: string(b), } } return nil }
go
func (p *Plugin) run(hook, command string, fn *function.Function) error { if command == "" { return nil } fn.Log.WithFields(log.Fields{ "hook": hook, "command": command, }).Debug("hook") var cmd *exec.Cmd if runtime.GOOS == "windows" { cmd = exec.Command("cmd", "/c", command) } else { cmd = exec.Command("sh", "-c", command) } cmd.Env = os.Environ() cmd.Dir = fn.Path b, err := cmd.CombinedOutput() if err != nil { return &HookError{ Hook: hook, Command: command, Output: string(b), } } return nil }
[ "func", "(", "p", "*", "Plugin", ")", "run", "(", "hook", ",", "command", "string", ",", "fn", "*", "function", ".", "Function", ")", "error", "{", "if", "command", "==", "\"\"", "{", "return", "nil", "\n", "}", "\n", "fn", ".", "Log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"hook\"", ":", "hook", ",", "\"command\"", ":", "command", ",", "}", ")", ".", "Debug", "(", "\"hook\"", ")", "\n", "var", "cmd", "*", "exec", ".", "Cmd", "\n", "if", "runtime", ".", "GOOS", "==", "\"windows\"", "{", "cmd", "=", "exec", ".", "Command", "(", "\"cmd\"", ",", "\"/c\"", ",", "command", ")", "\n", "}", "else", "{", "cmd", "=", "exec", ".", "Command", "(", "\"sh\"", ",", "\"-c\"", ",", "command", ")", "\n", "}", "\n", "cmd", ".", "Env", "=", "os", ".", "Environ", "(", ")", "\n", "cmd", ".", "Dir", "=", "fn", ".", "Path", "\n", "b", ",", "err", ":=", "cmd", ".", "CombinedOutput", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "HookError", "{", "Hook", ":", "hook", ",", "Command", ":", "command", ",", "Output", ":", "string", "(", "b", ")", ",", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// run a hook command.
[ "run", "a", "hook", "command", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/plugins/hooks/hooks.go#L51-L80
train
apex/apex
internal/util/util.go
ClearHeader
func ClearHeader(h http.Header) { for k := range h { if keepFields[k] { continue } h.Del(k) } }
go
func ClearHeader(h http.Header) { for k := range h { if keepFields[k] { continue } h.Del(k) } }
[ "func", "ClearHeader", "(", "h", "http", ".", "Header", ")", "{", "for", "k", ":=", "range", "h", "{", "if", "keepFields", "[", "k", "]", "{", "continue", "\n", "}", "\n", "h", ".", "Del", "(", "k", ")", "\n", "}", "\n", "}" ]
// ClearHeader removes all header fields.
[ "ClearHeader", "removes", "all", "header", "fields", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L38-L46
train
apex/apex
internal/util/util.go
ReadFileJSON
func ReadFileJSON(path string, v interface{}) error { b, err := ioutil.ReadFile(path) if err != nil { return errors.Wrap(err, "reading") } if err := json.Unmarshal(b, &v); err != nil { return errors.Wrap(err, "unmarshaling") } return nil }
go
func ReadFileJSON(path string, v interface{}) error { b, err := ioutil.ReadFile(path) if err != nil { return errors.Wrap(err, "reading") } if err := json.Unmarshal(b, &v); err != nil { return errors.Wrap(err, "unmarshaling") } return nil }
[ "func", "ReadFileJSON", "(", "path", "string", ",", "v", "interface", "{", "}", ")", "error", "{", "b", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"reading\"", ")", "\n", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "b", ",", "&", "v", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"unmarshaling\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ReadFileJSON reads json from the given path.
[ "ReadFileJSON", "reads", "json", "from", "the", "given", "path", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L64-L75
train
apex/apex
internal/util/util.go
Camelcase
func Camelcase(s string, v ...interface{}) string { return name.CamelCase(fmt.Sprintf(s, v...), true) }
go
func Camelcase(s string, v ...interface{}) string { return name.CamelCase(fmt.Sprintf(s, v...), true) }
[ "func", "Camelcase", "(", "s", "string", ",", "v", "...", "interface", "{", "}", ")", "string", "{", "return", "name", ".", "CamelCase", "(", "fmt", ".", "Sprintf", "(", "s", ",", "v", "...", ")", ",", "true", ")", "\n", "}" ]
// Camelcase string with optional args.
[ "Camelcase", "string", "with", "optional", "args", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L78-L80
train
apex/apex
internal/util/util.go
NewInlineProgressInt
func NewInlineProgressInt(total int) *progress.Bar { b := progress.NewInt(total) b.Template(`{{.Bar}} {{.Percent | printf "%0.0f"}}% {{.Text}}`) b.Width = 20 b.StartDelimiter = colors.Gray("|") b.EndDelimiter = colors.Gray("|") b.Filled = colors.Purple("█") b.Empty = colors.Gray(" ") return b }
go
func NewInlineProgressInt(total int) *progress.Bar { b := progress.NewInt(total) b.Template(`{{.Bar}} {{.Percent | printf "%0.0f"}}% {{.Text}}`) b.Width = 20 b.StartDelimiter = colors.Gray("|") b.EndDelimiter = colors.Gray("|") b.Filled = colors.Purple("█") b.Empty = colors.Gray(" ") return b }
[ "func", "NewInlineProgressInt", "(", "total", "int", ")", "*", "progress", ".", "Bar", "{", "b", ":=", "progress", ".", "NewInt", "(", "total", ")", "\n", "b", ".", "Template", "(", "`{{.Bar}} {{.Percent | printf \"%0.0f\"}}% {{.Text}}`", ")", "\n", "b", ".", "Width", "=", "20", "\n", "b", ".", "StartDelimiter", "=", "colors", ".", "Gray", "(", "\"|\"", ")", "\n", "b", ".", "EndDelimiter", "=", "colors", ".", "Gray", "(", "\"|\"", ")", "\n", "b", ".", "Filled", "=", "colors", ".", "Purple", "(", "\"█\")", ")", "\n", "b", ".", "Empty", "=", "colors", ".", "Gray", "(", "\" \"", ")", "\n", "return", "b", "\n", "}" ]
// NewInlineProgressInt with the given total.
[ "NewInlineProgressInt", "with", "the", "given", "total", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L95-L104
train
apex/apex
internal/util/util.go
Fatal
func Fatal(err error) { fmt.Fprintf(os.Stderr, "\n %s %s\n\n", colors.Red("Error:"), err) os.Exit(1) }
go
func Fatal(err error) { fmt.Fprintf(os.Stderr, "\n %s %s\n\n", colors.Red("Error:"), err) os.Exit(1) }
[ "func", "Fatal", "(", "err", "error", ")", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"\\n %s %s\\n\\n\"", ",", "\\n", ",", "\\n", ")", "\n", "\\n", "\n", "}" ]
// Fatal error.
[ "Fatal", "error", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L115-L118
train
apex/apex
internal/util/util.go
IsJSON
func IsJSON(s string) bool { return len(s) > 1 && s[0] == '{' && s[len(s)-1] == '}' }
go
func IsJSON(s string) bool { return len(s) > 1 && s[0] == '{' && s[len(s)-1] == '}' }
[ "func", "IsJSON", "(", "s", "string", ")", "bool", "{", "return", "len", "(", "s", ")", ">", "1", "&&", "s", "[", "0", "]", "==", "'{'", "&&", "s", "[", "len", "(", "s", ")", "-", "1", "]", "==", "'}'", "\n", "}" ]
// IsJSON returns true if the string looks like json.
[ "IsJSON", "returns", "true", "if", "the", "string", "looks", "like", "json", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L121-L123
train
apex/apex
internal/util/util.go
IsNotFound
func IsNotFound(err error) bool { switch { case err == nil: return false case strings.Contains(err.Error(), "does not exist"): return true case strings.Contains(err.Error(), "not found"): return true default: return false } }
go
func IsNotFound(err error) bool { switch { case err == nil: return false case strings.Contains(err.Error(), "does not exist"): return true case strings.Contains(err.Error(), "not found"): return true default: return false } }
[ "func", "IsNotFound", "(", "err", "error", ")", "bool", "{", "switch", "{", "case", "err", "==", "nil", ":", "return", "false", "\n", "case", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"does not exist\"", ")", ":", "return", "true", "\n", "case", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"not found\"", ")", ":", "return", "true", "\n", "default", ":", "return", "false", "\n", "}", "\n", "}" ]
// IsNotFound returns true if err is not nil and represents a missing resource.
[ "IsNotFound", "returns", "true", "if", "err", "is", "not", "nil", "and", "represents", "a", "missing", "resource", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L131-L142
train
apex/apex
internal/util/util.go
Env
func Env(m map[string]string) (env []string) { for k, v := range m { env = append(env, fmt.Sprintf("%s=%s", k, v)) } return }
go
func Env(m map[string]string) (env []string) { for k, v := range m { env = append(env, fmt.Sprintf("%s=%s", k, v)) } return }
[ "func", "Env", "(", "m", "map", "[", "string", "]", "string", ")", "(", "env", "[", "]", "string", ")", "{", "for", "k", ",", "v", ":=", "range", "m", "{", "env", "=", "append", "(", "env", ",", "fmt", ".", "Sprintf", "(", "\"%s=%s\"", ",", "k", ",", "v", ")", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Env returns a slice from environment variable map.
[ "Env", "returns", "a", "slice", "from", "environment", "variable", "map", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L157-L162
train
apex/apex
internal/util/util.go
PrefixLines
func PrefixLines(s string, prefix string) string { lines := strings.Split(s, "\n") for i, l := range lines { lines[i] = prefix + l } return strings.Join(lines, "\n") }
go
func PrefixLines(s string, prefix string) string { lines := strings.Split(s, "\n") for i, l := range lines { lines[i] = prefix + l } return strings.Join(lines, "\n") }
[ "func", "PrefixLines", "(", "s", "string", ",", "prefix", "string", ")", "string", "{", "lines", ":=", "strings", ".", "Split", "(", "s", ",", "\"\\n\"", ")", "\n", "\\n", "\n", "for", "i", ",", "l", ":=", "range", "lines", "{", "lines", "[", "i", "]", "=", "prefix", "+", "l", "\n", "}", "\n", "}" ]
// PrefixLines prefixes the lines in s with prefix.
[ "PrefixLines", "prefixes", "the", "lines", "in", "s", "with", "prefix", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L165-L171
train
apex/apex
internal/util/util.go
WaitForListen
func WaitForListen(u *url.URL, timeout time.Duration) error { timedout := time.After(timeout) b := backoff.Backoff{ Min: 100 * time.Millisecond, Max: time.Second, Factor: 1.5, } for { select { case <-timedout: return errors.Errorf("timed out after %s", timeout) case <-time.After(b.Duration()): if IsListening(u) { return nil } } } }
go
func WaitForListen(u *url.URL, timeout time.Duration) error { timedout := time.After(timeout) b := backoff.Backoff{ Min: 100 * time.Millisecond, Max: time.Second, Factor: 1.5, } for { select { case <-timedout: return errors.Errorf("timed out after %s", timeout) case <-time.After(b.Duration()): if IsListening(u) { return nil } } } }
[ "func", "WaitForListen", "(", "u", "*", "url", ".", "URL", ",", "timeout", "time", ".", "Duration", ")", "error", "{", "timedout", ":=", "time", ".", "After", "(", "timeout", ")", "\n", "b", ":=", "backoff", ".", "Backoff", "{", "Min", ":", "100", "*", "time", ".", "Millisecond", ",", "Max", ":", "time", ".", "Second", ",", "Factor", ":", "1.5", ",", "}", "\n", "for", "{", "select", "{", "case", "<-", "timedout", ":", "return", "errors", ".", "Errorf", "(", "\"timed out after %s\"", ",", "timeout", ")", "\n", "case", "<-", "time", ".", "After", "(", "b", ".", "Duration", "(", ")", ")", ":", "if", "IsListening", "(", "u", ")", "{", "return", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// WaitForListen blocks until `u` is listening with timeout.
[ "WaitForListen", "blocks", "until", "u", "is", "listening", "with", "timeout", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L179-L198
train
apex/apex
internal/util/util.go
IsListening
func IsListening(u *url.URL) bool { conn, err := net.Dial("tcp", u.Host) if err != nil { return false } conn.Close() return true }
go
func IsListening(u *url.URL) bool { conn, err := net.Dial("tcp", u.Host) if err != nil { return false } conn.Close() return true }
[ "func", "IsListening", "(", "u", "*", "url", ".", "URL", ")", "bool", "{", "conn", ",", "err", ":=", "net", ".", "Dial", "(", "\"tcp\"", ",", "u", ".", "Host", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "conn", ".", "Close", "(", ")", "\n", "return", "true", "\n", "}" ]
// IsListening returns true if there's a server listening on `u`.
[ "IsListening", "returns", "true", "if", "there", "s", "a", "server", "listening", "on", "u", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L201-L209
train
apex/apex
internal/util/util.go
ExitStatus
func ExitStatus(cmd *exec.Cmd, err error) string { ps := cmd.ProcessState if e, ok := err.(*exec.ExitError); ok { ps = e.ProcessState } if ps != nil { s, ok := ps.Sys().(syscall.WaitStatus) if ok { return fmt.Sprintf("%d", s.ExitStatus()) } } return "?" }
go
func ExitStatus(cmd *exec.Cmd, err error) string { ps := cmd.ProcessState if e, ok := err.(*exec.ExitError); ok { ps = e.ProcessState } if ps != nil { s, ok := ps.Sys().(syscall.WaitStatus) if ok { return fmt.Sprintf("%d", s.ExitStatus()) } } return "?" }
[ "func", "ExitStatus", "(", "cmd", "*", "exec", ".", "Cmd", ",", "err", "error", ")", "string", "{", "ps", ":=", "cmd", ".", "ProcessState", "\n", "if", "e", ",", "ok", ":=", "err", ".", "(", "*", "exec", ".", "ExitError", ")", ";", "ok", "{", "ps", "=", "e", ".", "ProcessState", "\n", "}", "\n", "if", "ps", "!=", "nil", "{", "s", ",", "ok", ":=", "ps", ".", "Sys", "(", ")", ".", "(", "syscall", ".", "WaitStatus", ")", "\n", "if", "ok", "{", "return", "fmt", ".", "Sprintf", "(", "\"%d\"", ",", "s", ".", "ExitStatus", "(", ")", ")", "\n", "}", "\n", "}", "\n", "return", "\"?\"", "\n", "}" ]
// ExitStatus returns the exit status of cmd.
[ "ExitStatus", "returns", "the", "exit", "status", "of", "cmd", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L212-L227
train
apex/apex
internal/util/util.go
Log
func Log(msg string, v ...interface{}) { fmt.Printf(" %s\n", colors.Purple(fmt.Sprintf(msg, v...))) }
go
func Log(msg string, v ...interface{}) { fmt.Printf(" %s\n", colors.Purple(fmt.Sprintf(msg, v...))) }
[ "func", "Log", "(", "msg", "string", ",", "v", "...", "interface", "{", "}", ")", "{", "fmt", ".", "Printf", "(", "\" %s\\n\"", ",", "\\n", ")", "\n", "}" ]
// Log outputs a log message.
[ "Log", "outputs", "a", "log", "message", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L252-L254
train
apex/apex
internal/util/util.go
LogClear
func LogClear(msg string, v ...interface{}) { term.MoveUp(1) term.ClearLine() fmt.Printf("\r %s\n", colors.Purple(fmt.Sprintf(msg, v...))) }
go
func LogClear(msg string, v ...interface{}) { term.MoveUp(1) term.ClearLine() fmt.Printf("\r %s\n", colors.Purple(fmt.Sprintf(msg, v...))) }
[ "func", "LogClear", "(", "msg", "string", ",", "v", "...", "interface", "{", "}", ")", "{", "term", ".", "MoveUp", "(", "1", ")", "\n", "term", ".", "ClearLine", "(", ")", "\n", "fmt", ".", "Printf", "(", "\"\\r %s\\n\"", ",", "\\r", ")", "\n", "}" ]
// LogClear clears the line and outputs a log message.
[ "LogClear", "clears", "the", "line", "and", "outputs", "a", "log", "message", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L257-L261
train
apex/apex
internal/util/util.go
LogTitle
func LogTitle(msg string, v ...interface{}) { fmt.Printf("\n \x1b[1m%s\x1b[m\n\n", fmt.Sprintf(msg, v...)) }
go
func LogTitle(msg string, v ...interface{}) { fmt.Printf("\n \x1b[1m%s\x1b[m\n\n", fmt.Sprintf(msg, v...)) }
[ "func", "LogTitle", "(", "msg", "string", ",", "v", "...", "interface", "{", "}", ")", "{", "fmt", ".", "Printf", "(", "\"\\n \\x1b[1m%s\\x1b[m\\n\\n\"", ",", "\\n", ")", "\n", "}" ]
// LogTitle outputs a log title.
[ "LogTitle", "outputs", "a", "log", "title", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L264-L266
train
apex/apex
internal/util/util.go
LogName
func LogName(name, msg string, v ...interface{}) { fmt.Printf(" %s %s\n", colors.Purple(name+":"), fmt.Sprintf(msg, v...)) }
go
func LogName(name, msg string, v ...interface{}) { fmt.Printf(" %s %s\n", colors.Purple(name+":"), fmt.Sprintf(msg, v...)) }
[ "func", "LogName", "(", "name", ",", "msg", "string", ",", "v", "...", "interface", "{", "}", ")", "{", "fmt", ".", "Printf", "(", "\" %s %s\\n\"", ",", "\\n", ",", "colors", ".", "Purple", "(", "name", "+", "\":\"", ")", ")", "\n", "}" ]
// LogName outputs a log message with name.
[ "LogName", "outputs", "a", "log", "message", "with", "name", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L269-L271
train
apex/apex
internal/util/util.go
LogListItem
func LogListItem(msg string, v ...interface{}) { fmt.Printf(" • %s\n", fmt.Sprintf(msg, v...)) }
go
func LogListItem(msg string, v ...interface{}) { fmt.Printf(" • %s\n", fmt.Sprintf(msg, v...)) }
[ "func", "LogListItem", "(", "msg", "string", ",", "v", "...", "interface", "{", "}", ")", "{", "fmt", ".", "Printf", "(", "\" • %s\\n\", ", "\",", " ", ")", "\n", "}" ]
// LogListItem outputs a list item.
[ "LogListItem", "outputs", "a", "list", "item", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L274-L276
train
apex/apex
internal/util/util.go
ToFloat
func ToFloat(v interface{}) float64 { switch n := v.(type) { case int: return float64(n) case int8: return float64(n) case int16: return float64(n) case int32: return float64(n) case int64: return float64(n) case uint: return float64(n) case uint8: return float64(n) case uint16: return float64(n) case uint32: return float64(n) case uint64: return float64(n) case float32: return float64(n) case float64: return n default: return math.NaN() } }
go
func ToFloat(v interface{}) float64 { switch n := v.(type) { case int: return float64(n) case int8: return float64(n) case int16: return float64(n) case int32: return float64(n) case int64: return float64(n) case uint: return float64(n) case uint8: return float64(n) case uint16: return float64(n) case uint32: return float64(n) case uint64: return float64(n) case float32: return float64(n) case float64: return n default: return math.NaN() } }
[ "func", "ToFloat", "(", "v", "interface", "{", "}", ")", "float64", "{", "switch", "n", ":=", "v", ".", "(", "type", ")", "{", "case", "int", ":", "return", "float64", "(", "n", ")", "\n", "case", "int8", ":", "return", "float64", "(", "n", ")", "\n", "case", "int16", ":", "return", "float64", "(", "n", ")", "\n", "case", "int32", ":", "return", "float64", "(", "n", ")", "\n", "case", "int64", ":", "return", "float64", "(", "n", ")", "\n", "case", "uint", ":", "return", "float64", "(", "n", ")", "\n", "case", "uint8", ":", "return", "float64", "(", "n", ")", "\n", "case", "uint16", ":", "return", "float64", "(", "n", ")", "\n", "case", "uint32", ":", "return", "float64", "(", "n", ")", "\n", "case", "uint64", ":", "return", "float64", "(", "n", ")", "\n", "case", "float32", ":", "return", "float64", "(", "n", ")", "\n", "case", "float64", ":", "return", "n", "\n", "default", ":", "return", "math", ".", "NaN", "(", ")", "\n", "}", "\n", "}" ]
// ToFloat returns a float or NaN.
[ "ToFloat", "returns", "a", "float", "or", "NaN", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L279-L308
train
apex/apex
internal/util/util.go
MillisecondsSince
func MillisecondsSince(t time.Time) int { return int(time.Since(t) / time.Millisecond) }
go
func MillisecondsSince(t time.Time) int { return int(time.Since(t) / time.Millisecond) }
[ "func", "MillisecondsSince", "(", "t", "time", ".", "Time", ")", "int", "{", "return", "int", "(", "time", ".", "Since", "(", "t", ")", "/", "time", ".", "Millisecond", ")", "\n", "}" ]
// MillisecondsSince returns the duration as milliseconds relative to time t.
[ "MillisecondsSince", "returns", "the", "duration", "as", "milliseconds", "relative", "to", "time", "t", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L316-L318
train
apex/apex
internal/util/util.go
ParseDuration
func ParseDuration(s string) (d time.Duration, err error) { r := strings.NewReader(s) switch { case strings.HasSuffix(s, "d"): var v float64 _, err = fmt.Fscanf(r, "%fd", &v) d = time.Duration(v * float64(24*time.Hour)) case strings.HasSuffix(s, "w"): var v float64 _, err = fmt.Fscanf(r, "%fw", &v) d = time.Duration(v * float64(24*time.Hour*7)) case strings.HasSuffix(s, "mo"): var v float64 _, err = fmt.Fscanf(r, "%fmo", &v) d = time.Duration(v * float64(30*24*time.Hour)) case strings.HasSuffix(s, "M"): var v float64 _, err = fmt.Fscanf(r, "%fM", &v) d = time.Duration(v * float64(30*24*time.Hour)) default: d, err = time.ParseDuration(s) } return }
go
func ParseDuration(s string) (d time.Duration, err error) { r := strings.NewReader(s) switch { case strings.HasSuffix(s, "d"): var v float64 _, err = fmt.Fscanf(r, "%fd", &v) d = time.Duration(v * float64(24*time.Hour)) case strings.HasSuffix(s, "w"): var v float64 _, err = fmt.Fscanf(r, "%fw", &v) d = time.Duration(v * float64(24*time.Hour*7)) case strings.HasSuffix(s, "mo"): var v float64 _, err = fmt.Fscanf(r, "%fmo", &v) d = time.Duration(v * float64(30*24*time.Hour)) case strings.HasSuffix(s, "M"): var v float64 _, err = fmt.Fscanf(r, "%fM", &v) d = time.Duration(v * float64(30*24*time.Hour)) default: d, err = time.ParseDuration(s) } return }
[ "func", "ParseDuration", "(", "s", "string", ")", "(", "d", "time", ".", "Duration", ",", "err", "error", ")", "{", "r", ":=", "strings", ".", "NewReader", "(", "s", ")", "\n", "switch", "{", "case", "strings", ".", "HasSuffix", "(", "s", ",", "\"d\"", ")", ":", "var", "v", "float64", "\n", "_", ",", "err", "=", "fmt", ".", "Fscanf", "(", "r", ",", "\"%fd\"", ",", "&", "v", ")", "\n", "d", "=", "time", ".", "Duration", "(", "v", "*", "float64", "(", "24", "*", "time", ".", "Hour", ")", ")", "\n", "case", "strings", ".", "HasSuffix", "(", "s", ",", "\"w\"", ")", ":", "var", "v", "float64", "\n", "_", ",", "err", "=", "fmt", ".", "Fscanf", "(", "r", ",", "\"%fw\"", ",", "&", "v", ")", "\n", "d", "=", "time", ".", "Duration", "(", "v", "*", "float64", "(", "24", "*", "time", ".", "Hour", "*", "7", ")", ")", "\n", "case", "strings", ".", "HasSuffix", "(", "s", ",", "\"mo\"", ")", ":", "var", "v", "float64", "\n", "_", ",", "err", "=", "fmt", ".", "Fscanf", "(", "r", ",", "\"%fmo\"", ",", "&", "v", ")", "\n", "d", "=", "time", ".", "Duration", "(", "v", "*", "float64", "(", "30", "*", "24", "*", "time", ".", "Hour", ")", ")", "\n", "case", "strings", ".", "HasSuffix", "(", "s", ",", "\"M\"", ")", ":", "var", "v", "float64", "\n", "_", ",", "err", "=", "fmt", ".", "Fscanf", "(", "r", ",", "\"%fM\"", ",", "&", "v", ")", "\n", "d", "=", "time", ".", "Duration", "(", "v", "*", "float64", "(", "30", "*", "24", "*", "time", ".", "Hour", ")", ")", "\n", "default", ":", "d", ",", "err", "=", "time", ".", "ParseDuration", "(", "s", ")", "\n", "}", "\n", "return", "\n", "}" ]
// ParseDuration string with day and month approximation support.
[ "ParseDuration", "string", "with", "day", "and", "month", "approximation", "support", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L321-L346
train
apex/apex
internal/util/util.go
ParseSections
func ParseSections(r io.Reader) (sections []string, err error) { s := bufio.NewScanner(r) for s.Scan() { t := s.Text() if strings.HasPrefix(t, "[") { sections = append(sections, strings.Trim(t, "[]")) } } err = s.Err() return }
go
func ParseSections(r io.Reader) (sections []string, err error) { s := bufio.NewScanner(r) for s.Scan() { t := s.Text() if strings.HasPrefix(t, "[") { sections = append(sections, strings.Trim(t, "[]")) } } err = s.Err() return }
[ "func", "ParseSections", "(", "r", "io", ".", "Reader", ")", "(", "sections", "[", "]", "string", ",", "err", "error", ")", "{", "s", ":=", "bufio", ".", "NewScanner", "(", "r", ")", "\n", "for", "s", ".", "Scan", "(", ")", "{", "t", ":=", "s", ".", "Text", "(", ")", "\n", "if", "strings", ".", "HasPrefix", "(", "t", ",", "\"[\"", ")", "{", "sections", "=", "append", "(", "sections", ",", "strings", ".", "Trim", "(", "t", ",", "\"[]\"", ")", ")", "\n", "}", "\n", "}", "\n", "err", "=", "s", ".", "Err", "(", ")", "\n", "return", "\n", "}" ]
// ParseSections returns INI style sections from r.
[ "ParseSections", "returns", "INI", "style", "sections", "from", "r", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L368-L381
train
apex/apex
cost/cost.go
Cost
func Cost(requests, ms, memory int) float64 { return RequestCost(requests) + DurationCost(ms, memory) }
go
func Cost(requests, ms, memory int) float64 { return RequestCost(requests) + DurationCost(ms, memory) }
[ "func", "Cost", "(", "requests", ",", "ms", ",", "memory", "int", ")", "float64", "{", "return", "RequestCost", "(", "requests", ")", "+", "DurationCost", "(", "ms", ",", "memory", ")", "\n", "}" ]
// Cost returns the total cost.
[ "Cost", "returns", "the", "total", "cost", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cost/cost.go#L50-L52
train
apex/apex
infra/tfvars.go
functionVars
func (p *Proxy) functionVars() (args []string) { args = append(args, "-var") args = append(args, fmt.Sprintf("aws_region=%s", p.Region)) args = append(args, "-var") args = append(args, fmt.Sprintf("apex_environment=%s", p.Environment)) if p.Role != "" { args = append(args, "-var") args = append(args, fmt.Sprintf("apex_function_role=%s", p.Role)) } // GetConfig is slow, so store the results and then use the configurations as needed var relations []ConfigRelation for _, fn := range p.Functions { config, err := fn.GetConfig() if err != nil { log.Debugf("can't fetch function config: %s", err.Error()) continue } var relation ConfigRelation relation.Function = fn relation.Configuration = config.Configuration relations = append(relations, relation) } args = append(args, getFunctionArnVars(relations)...) args = append(args, getFunctionNameVars(relations)...) args = append(args, getFunctionArns(relations)...) args = append(args, getFunctionNames(relations)...) return args }
go
func (p *Proxy) functionVars() (args []string) { args = append(args, "-var") args = append(args, fmt.Sprintf("aws_region=%s", p.Region)) args = append(args, "-var") args = append(args, fmt.Sprintf("apex_environment=%s", p.Environment)) if p.Role != "" { args = append(args, "-var") args = append(args, fmt.Sprintf("apex_function_role=%s", p.Role)) } // GetConfig is slow, so store the results and then use the configurations as needed var relations []ConfigRelation for _, fn := range p.Functions { config, err := fn.GetConfig() if err != nil { log.Debugf("can't fetch function config: %s", err.Error()) continue } var relation ConfigRelation relation.Function = fn relation.Configuration = config.Configuration relations = append(relations, relation) } args = append(args, getFunctionArnVars(relations)...) args = append(args, getFunctionNameVars(relations)...) args = append(args, getFunctionArns(relations)...) args = append(args, getFunctionNames(relations)...) return args }
[ "func", "(", "p", "*", "Proxy", ")", "functionVars", "(", ")", "(", "args", "[", "]", "string", ")", "{", "args", "=", "append", "(", "args", ",", "\"-var\"", ")", "\n", "args", "=", "append", "(", "args", ",", "fmt", ".", "Sprintf", "(", "\"aws_region=%s\"", ",", "p", ".", "Region", ")", ")", "\n", "args", "=", "append", "(", "args", ",", "\"-var\"", ")", "\n", "args", "=", "append", "(", "args", ",", "fmt", ".", "Sprintf", "(", "\"apex_environment=%s\"", ",", "p", ".", "Environment", ")", ")", "\n", "if", "p", ".", "Role", "!=", "\"\"", "{", "args", "=", "append", "(", "args", ",", "\"-var\"", ")", "\n", "args", "=", "append", "(", "args", ",", "fmt", ".", "Sprintf", "(", "\"apex_function_role=%s\"", ",", "p", ".", "Role", ")", ")", "\n", "}", "\n", "var", "relations", "[", "]", "ConfigRelation", "\n", "for", "_", ",", "fn", ":=", "range", "p", ".", "Functions", "{", "config", ",", "err", ":=", "fn", ".", "GetConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Debugf", "(", "\"can't fetch function config: %s\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "continue", "\n", "}", "\n", "var", "relation", "ConfigRelation", "\n", "relation", ".", "Function", "=", "fn", "\n", "relation", ".", "Configuration", "=", "config", ".", "Configuration", "\n", "relations", "=", "append", "(", "relations", ",", "relation", ")", "\n", "}", "\n", "args", "=", "append", "(", "args", ",", "getFunctionArnVars", "(", "relations", ")", "...", ")", "\n", "args", "=", "append", "(", "args", ",", "getFunctionNameVars", "(", "relations", ")", "...", ")", "\n", "args", "=", "append", "(", "args", ",", "getFunctionArns", "(", "relations", ")", "...", ")", "\n", "args", "=", "append", "(", "args", ",", "getFunctionNames", "(", "relations", ")", "...", ")", "\n", "return", "args", "\n", "}" ]
// functionVars returns the function variables as terraform -var arguments.
[ "functionVars", "returns", "the", "function", "variables", "as", "terraform", "-", "var", "arguments", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/infra/tfvars.go#L19-L53
train
apex/apex
infra/tfvars.go
getFunctionArnVars
func getFunctionArnVars(relations []ConfigRelation) (args []string) { log.Debugf("Generating the tfvar apex_function_FUNCTION") for _, rel := range relations { args = append(args, "-var") args = append(args, fmt.Sprintf("apex_function_%s=%s", rel.Function.Name, *rel.Configuration.FunctionArn)) } return args }
go
func getFunctionArnVars(relations []ConfigRelation) (args []string) { log.Debugf("Generating the tfvar apex_function_FUNCTION") for _, rel := range relations { args = append(args, "-var") args = append(args, fmt.Sprintf("apex_function_%s=%s", rel.Function.Name, *rel.Configuration.FunctionArn)) } return args }
[ "func", "getFunctionArnVars", "(", "relations", "[", "]", "ConfigRelation", ")", "(", "args", "[", "]", "string", ")", "{", "log", ".", "Debugf", "(", "\"Generating the tfvar apex_function_FUNCTION\"", ")", "\n", "for", "_", ",", "rel", ":=", "range", "relations", "{", "args", "=", "append", "(", "args", ",", "\"-var\"", ")", "\n", "args", "=", "append", "(", "args", ",", "fmt", ".", "Sprintf", "(", "\"apex_function_%s=%s\"", ",", "rel", ".", "Function", ".", "Name", ",", "*", "rel", ".", "Configuration", ".", "FunctionArn", ")", ")", "\n", "}", "\n", "return", "args", "\n", "}" ]
// Generate a series of variables apex_function_FUNCTION that contains the arn of the functions // This function is being phased out in favour of apex_function_arns
[ "Generate", "a", "series", "of", "variables", "apex_function_FUNCTION", "that", "contains", "the", "arn", "of", "the", "functions", "This", "function", "is", "being", "phased", "out", "in", "favour", "of", "apex_function_arns" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/infra/tfvars.go#L57-L64
train
apex/apex
infra/tfvars.go
getFunctionArns
func getFunctionArns(relations []ConfigRelation) (args []string) { log.Debugf("Generating the tfvar apex_function_arns") var arns []string for _, rel := range relations { arns = append(arns, fmt.Sprintf("%s = %q", rel.Function.Name, *rel.Configuration.FunctionArn)) } args = append(args, "-var") args = append(args, fmt.Sprintf("apex_function_arns={ %s }", strings.Join(arns, ", "))) return args }
go
func getFunctionArns(relations []ConfigRelation) (args []string) { log.Debugf("Generating the tfvar apex_function_arns") var arns []string for _, rel := range relations { arns = append(arns, fmt.Sprintf("%s = %q", rel.Function.Name, *rel.Configuration.FunctionArn)) } args = append(args, "-var") args = append(args, fmt.Sprintf("apex_function_arns={ %s }", strings.Join(arns, ", "))) return args }
[ "func", "getFunctionArns", "(", "relations", "[", "]", "ConfigRelation", ")", "(", "args", "[", "]", "string", ")", "{", "log", ".", "Debugf", "(", "\"Generating the tfvar apex_function_arns\"", ")", "\n", "var", "arns", "[", "]", "string", "\n", "for", "_", ",", "rel", ":=", "range", "relations", "{", "arns", "=", "append", "(", "arns", ",", "fmt", ".", "Sprintf", "(", "\"%s = %q\"", ",", "rel", ".", "Function", ".", "Name", ",", "*", "rel", ".", "Configuration", ".", "FunctionArn", ")", ")", "\n", "}", "\n", "args", "=", "append", "(", "args", ",", "\"-var\"", ")", "\n", "args", "=", "append", "(", "args", ",", "fmt", ".", "Sprintf", "(", "\"apex_function_arns={ %s }\"", ",", "strings", ".", "Join", "(", "arns", ",", "\", \"", ")", ")", ")", "\n", "return", "args", "\n", "}" ]
// Generates a map that has the function's name as a key and the arn of the function as a value
[ "Generates", "a", "map", "that", "has", "the", "function", "s", "name", "as", "a", "key", "and", "the", "arn", "of", "the", "function", "as", "a", "value" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/infra/tfvars.go#L78-L87
train
apex/apex
infra/tfvars.go
getFunctionNames
func getFunctionNames(relations []ConfigRelation) (args []string) { log.Debugf("Generating the tfvar apex_function_names") var names []string for _, rel := range relations { names = append(names, fmt.Sprintf("%s = %q", rel.Function.Name, rel.Function.FunctionName)) } args = append(args, "-var") args = append(args, fmt.Sprintf("apex_function_names={ %s }", strings.Join(names, ", "))) return args }
go
func getFunctionNames(relations []ConfigRelation) (args []string) { log.Debugf("Generating the tfvar apex_function_names") var names []string for _, rel := range relations { names = append(names, fmt.Sprintf("%s = %q", rel.Function.Name, rel.Function.FunctionName)) } args = append(args, "-var") args = append(args, fmt.Sprintf("apex_function_names={ %s }", strings.Join(names, ", "))) return args }
[ "func", "getFunctionNames", "(", "relations", "[", "]", "ConfigRelation", ")", "(", "args", "[", "]", "string", ")", "{", "log", ".", "Debugf", "(", "\"Generating the tfvar apex_function_names\"", ")", "\n", "var", "names", "[", "]", "string", "\n", "for", "_", ",", "rel", ":=", "range", "relations", "{", "names", "=", "append", "(", "names", ",", "fmt", ".", "Sprintf", "(", "\"%s = %q\"", ",", "rel", ".", "Function", ".", "Name", ",", "rel", ".", "Function", ".", "FunctionName", ")", ")", "\n", "}", "\n", "args", "=", "append", "(", "args", ",", "\"-var\"", ")", "\n", "args", "=", "append", "(", "args", ",", "fmt", ".", "Sprintf", "(", "\"apex_function_names={ %s }\"", ",", "strings", ".", "Join", "(", "names", ",", "\", \"", ")", ")", ")", "\n", "return", "args", "\n", "}" ]
// Generates a map that has the function's name as a key and the full name of the function as a value
[ "Generates", "a", "map", "that", "has", "the", "function", "s", "name", "as", "a", "key", "and", "the", "full", "name", "of", "the", "function", "as", "a", "value" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/infra/tfvars.go#L90-L99
train
apex/apex
exec/exec.go
Run
func (p *Proxy) Run(command string, args ...string) error { log.WithFields(log.Fields{ "command": command, "args": args, }).Debug("exec") cmd := exec.Command(command, args...) cmd.Env = append(os.Environ(), p.functionEnvVars()...) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Dir = p.Dir return cmd.Run() }
go
func (p *Proxy) Run(command string, args ...string) error { log.WithFields(log.Fields{ "command": command, "args": args, }).Debug("exec") cmd := exec.Command(command, args...) cmd.Env = append(os.Environ(), p.functionEnvVars()...) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Dir = p.Dir return cmd.Run() }
[ "func", "(", "p", "*", "Proxy", ")", "Run", "(", "command", "string", ",", "args", "...", "string", ")", "error", "{", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"command\"", ":", "command", ",", "\"args\"", ":", "args", ",", "}", ")", ".", "Debug", "(", "\"exec\"", ")", "\n", "cmd", ":=", "exec", ".", "Command", "(", "command", ",", "args", "...", ")", "\n", "cmd", ".", "Env", "=", "append", "(", "os", ".", "Environ", "(", ")", ",", "p", ".", "functionEnvVars", "(", ")", "...", ")", "\n", "cmd", ".", "Stdin", "=", "os", ".", "Stdin", "\n", "cmd", ".", "Stdout", "=", "os", ".", "Stdout", "\n", "cmd", ".", "Stderr", "=", "os", ".", "Stderr", "\n", "cmd", ".", "Dir", "=", "p", ".", "Dir", "\n", "return", "cmd", ".", "Run", "(", ")", "\n", "}" ]
// Run command in specified directory.
[ "Run", "command", "in", "specified", "directory", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/exec/exec.go#L23-L37
train
apex/apex
metrics/metrics.go
Collect
func (m *Metrics) Collect() (a map[string]AggregatedMetrics) { a = make(map[string]AggregatedMetrics) for _, fnName := range m.FunctionNames { metric := Metric{ Config: m.Config, FunctionName: fnName, } a[fnName] = metric.Collect() } return }
go
func (m *Metrics) Collect() (a map[string]AggregatedMetrics) { a = make(map[string]AggregatedMetrics) for _, fnName := range m.FunctionNames { metric := Metric{ Config: m.Config, FunctionName: fnName, } a[fnName] = metric.Collect() } return }
[ "func", "(", "m", "*", "Metrics", ")", "Collect", "(", ")", "(", "a", "map", "[", "string", "]", "AggregatedMetrics", ")", "{", "a", "=", "make", "(", "map", "[", "string", "]", "AggregatedMetrics", ")", "\n", "for", "_", ",", "fnName", ":=", "range", "m", ".", "FunctionNames", "{", "metric", ":=", "Metric", "{", "Config", ":", "m", ".", "Config", ",", "FunctionName", ":", "fnName", ",", "}", "\n", "a", "[", "fnName", "]", "=", "metric", ".", "Collect", "(", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Collect and aggregate metrics for multiple functions.
[ "Collect", "and", "aggregate", "metrics", "for", "multiple", "functions", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/metrics/metrics.go#L33-L46
train
apex/apex
cmd/apex/autocomplete/autocomplete.go
find
func find(name string) *cobra.Command { for _, cmd := range root.Command.Commands() { if cmd.Name() == name { return cmd } } return nil }
go
func find(name string) *cobra.Command { for _, cmd := range root.Command.Commands() { if cmd.Name() == name { return cmd } } return nil }
[ "func", "find", "(", "name", "string", ")", "*", "cobra", ".", "Command", "{", "for", "_", ",", "cmd", ":=", "range", "root", ".", "Command", ".", "Commands", "(", ")", "{", "if", "cmd", ".", "Name", "(", ")", "==", "name", "{", "return", "cmd", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// find command by `name`.
[ "find", "command", "by", "name", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/autocomplete/autocomplete.go#L73-L80
train
apex/apex
cmd/apex/autocomplete/autocomplete.go
rootCommands
func rootCommands() { for _, cmd := range root.Command.Commands() { if !cmd.Hidden { fmt.Printf("%s ", cmd.Name()) } } }
go
func rootCommands() { for _, cmd := range root.Command.Commands() { if !cmd.Hidden { fmt.Printf("%s ", cmd.Name()) } } }
[ "func", "rootCommands", "(", ")", "{", "for", "_", ",", "cmd", ":=", "range", "root", ".", "Command", ".", "Commands", "(", ")", "{", "if", "!", "cmd", ".", "Hidden", "{", "fmt", ".", "Printf", "(", "\"%s \"", ",", "cmd", ".", "Name", "(", ")", ")", "\n", "}", "\n", "}", "\n", "}" ]
// output root commands.
[ "output", "root", "commands", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/autocomplete/autocomplete.go#L83-L89
train
apex/apex
cmd/apex/autocomplete/autocomplete.go
flags
func flags(cmd *cobra.Command) { cmd.Flags().VisitAll(func(f *flag.Flag) { if !f.Hidden { fmt.Printf("--%s ", f.Name) } }) }
go
func flags(cmd *cobra.Command) { cmd.Flags().VisitAll(func(f *flag.Flag) { if !f.Hidden { fmt.Printf("--%s ", f.Name) } }) }
[ "func", "flags", "(", "cmd", "*", "cobra", ".", "Command", ")", "{", "cmd", ".", "Flags", "(", ")", ".", "VisitAll", "(", "func", "(", "f", "*", "flag", ".", "Flag", ")", "{", "if", "!", "f", ".", "Hidden", "{", "fmt", ".", "Printf", "(", "\"--%s \"", ",", "f", ".", "Name", ")", "\n", "}", "\n", "}", ")", "\n", "}" ]
// output flags.
[ "output", "flags", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/autocomplete/autocomplete.go#L92-L98
train
apex/apex
plugins/inference/inference.go
Open
func (p *Plugin) Open(fn *function.Function) error { if fn.Runtime != "" { return nil } fn.Log.Debug("inferring runtime") for name, runtime := range p.Files { if _, err := os.Stat(filepath.Join(fn.Path, name)); err == nil { fn.Log.WithField("runtime", runtime).Debug("inferred runtime") fn.Runtime = runtime return nil } } return nil }
go
func (p *Plugin) Open(fn *function.Function) error { if fn.Runtime != "" { return nil } fn.Log.Debug("inferring runtime") for name, runtime := range p.Files { if _, err := os.Stat(filepath.Join(fn.Path, name)); err == nil { fn.Log.WithField("runtime", runtime).Debug("inferred runtime") fn.Runtime = runtime return nil } } return nil }
[ "func", "(", "p", "*", "Plugin", ")", "Open", "(", "fn", "*", "function", ".", "Function", ")", "error", "{", "if", "fn", ".", "Runtime", "!=", "\"\"", "{", "return", "nil", "\n", "}", "\n", "fn", ".", "Log", ".", "Debug", "(", "\"inferring runtime\"", ")", "\n", "for", "name", ",", "runtime", ":=", "range", "p", ".", "Files", "{", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "filepath", ".", "Join", "(", "fn", ".", "Path", ",", "name", ")", ")", ";", "err", "==", "nil", "{", "fn", ".", "Log", ".", "WithField", "(", "\"runtime\"", ",", "runtime", ")", ".", "Debug", "(", "\"inferred runtime\"", ")", "\n", "fn", ".", "Runtime", "=", "runtime", "\n", "return", "nil", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Open checks for files in the function directory to infer its runtime.
[ "Open", "checks", "for", "files", "in", "the", "function", "directory", "to", "infer", "its", "runtime", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/plugins/inference/inference.go#L35-L51
train
apex/apex
service/provider.go
NewProvider
func NewProvider(session *session.Session, dryRun bool) Provideriface { return &Provider{ Session: session, DryRun: dryRun, } }
go
func NewProvider(session *session.Session, dryRun bool) Provideriface { return &Provider{ Session: session, DryRun: dryRun, } }
[ "func", "NewProvider", "(", "session", "*", "session", ".", "Session", ",", "dryRun", "bool", ")", "Provideriface", "{", "return", "&", "Provider", "{", "Session", ":", "session", ",", "DryRun", ":", "dryRun", ",", "}", "\n", "}" ]
// NewProvider with session and dry run
[ "NewProvider", "with", "session", "and", "dry", "run" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/service/provider.go#L24-L29
train
apex/apex
service/provider.go
NewService
func (p *Provider) NewService(cfg *aws.Config) lambdaiface.LambdaAPI { if p.DryRun { return dryrun.New(p.Session) } else if cfg != nil { return lambda.New(p.Session, cfg) } else { return lambda.New(p.Session) } }
go
func (p *Provider) NewService(cfg *aws.Config) lambdaiface.LambdaAPI { if p.DryRun { return dryrun.New(p.Session) } else if cfg != nil { return lambda.New(p.Session, cfg) } else { return lambda.New(p.Session) } }
[ "func", "(", "p", "*", "Provider", ")", "NewService", "(", "cfg", "*", "aws", ".", "Config", ")", "lambdaiface", ".", "LambdaAPI", "{", "if", "p", ".", "DryRun", "{", "return", "dryrun", ".", "New", "(", "p", ".", "Session", ")", "\n", "}", "else", "if", "cfg", "!=", "nil", "{", "return", "lambda", ".", "New", "(", "p", ".", "Session", ",", "cfg", ")", "\n", "}", "else", "{", "return", "lambda", ".", "New", "(", "p", ".", "Session", ")", "\n", "}", "\n", "}" ]
// NewService returns Lambda service with AWS config
[ "NewService", "returns", "Lambda", "service", "with", "AWS", "config" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/service/provider.go#L32-L40
train
apex/apex
plugins/shim/shim.go
Build
func (p *Plugin) Build(fn *function.Function, zip *archive.Zip) error { if fn.Shim { fn.Log.Debug("add shim") if err := zip.AddBytes("index.js", shim.MustAsset("index.js")); err != nil { return err } if err := zip.AddBytes("byline.js", shim.MustAsset("byline.js")); err != nil { return err } } return nil }
go
func (p *Plugin) Build(fn *function.Function, zip *archive.Zip) error { if fn.Shim { fn.Log.Debug("add shim") if err := zip.AddBytes("index.js", shim.MustAsset("index.js")); err != nil { return err } if err := zip.AddBytes("byline.js", shim.MustAsset("byline.js")); err != nil { return err } } return nil }
[ "func", "(", "p", "*", "Plugin", ")", "Build", "(", "fn", "*", "function", ".", "Function", ",", "zip", "*", "archive", ".", "Zip", ")", "error", "{", "if", "fn", ".", "Shim", "{", "fn", ".", "Log", ".", "Debug", "(", "\"add shim\"", ")", "\n", "if", "err", ":=", "zip", ".", "AddBytes", "(", "\"index.js\"", ",", "shim", ".", "MustAsset", "(", "\"index.js\"", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "zip", ".", "AddBytes", "(", "\"byline.js\"", ",", "shim", ".", "MustAsset", "(", "\"byline.js\"", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Build adds the nodejs shim files.
[ "Build", "adds", "the", "nodejs", "shim", "files", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/plugins/shim/shim.go#L19-L33
train
apex/apex
cmd/apex/list/list.go
outputTFvars
func outputTFvars() { for _, fn := range root.Project.Functions { config, err := fn.GetConfig() if err != nil { log.Debugf("can't fetch function config: %s", err.Error()) continue } fmt.Printf("apex_function_%s=%q\n", fn.Name, *config.Configuration.FunctionArn) } }
go
func outputTFvars() { for _, fn := range root.Project.Functions { config, err := fn.GetConfig() if err != nil { log.Debugf("can't fetch function config: %s", err.Error()) continue } fmt.Printf("apex_function_%s=%q\n", fn.Name, *config.Configuration.FunctionArn) } }
[ "func", "outputTFvars", "(", ")", "{", "for", "_", ",", "fn", ":=", "range", "root", ".", "Project", ".", "Functions", "{", "config", ",", "err", ":=", "fn", ".", "GetConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Debugf", "(", "\"can't fetch function config: %s\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "continue", "\n", "}", "\n", "fmt", ".", "Printf", "(", "\"apex_function_%s=%q\\n\"", ",", "\\n", ",", "fn", ".", "Name", ")", "\n", "}", "\n", "}" ]
// outputTFvars format.
[ "outputTFvars", "format", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/list/list.go#L61-L71
train
apex/apex
cmd/apex/list/list.go
outputList
func outputList() { fmt.Println() for _, fn := range root.Project.Functions { awsFn, err := fn.GetConfigCurrent() if awserr, ok := err.(awserr.Error); ok && awserr.Code() == "ResourceNotFoundException" { fmt.Printf(" \033[%dm%s\033[0m (not deployed) \n", colors.Blue, fn.Name) } else { fmt.Printf(" \033[%dm%s\033[0m\n", colors.Blue, fn.Name) } if fn.Description != "" { fmt.Printf(" description: %v\n", fn.Description) } fmt.Printf(" runtime: %v\n", fn.Runtime) fmt.Printf(" memory: %vmb\n", fn.Memory) fmt.Printf(" timeout: %vs\n", fn.Timeout) fmt.Printf(" role: %v\n", fn.Role) fmt.Printf(" handler: %v\n", fn.Handler) if awsFn != nil && awsFn.Configuration != nil && awsFn.Configuration.FunctionArn != nil { fmt.Printf(" arn: %v\n", *awsFn.Configuration.FunctionArn) } if err != nil { fmt.Println() continue // ignore } aliaslist, err := fn.GetAliases() if err != nil { continue } var aliases string for index, alias := range aliaslist.Aliases { if index > 0 { aliases += ", " } aliases += fmt.Sprintf("%s@v%s", *alias.Name, *alias.FunctionVersion) } if aliases == "" { aliases = "<none>" } fmt.Printf(" aliases: %s\n", aliases) fmt.Println() } }
go
func outputList() { fmt.Println() for _, fn := range root.Project.Functions { awsFn, err := fn.GetConfigCurrent() if awserr, ok := err.(awserr.Error); ok && awserr.Code() == "ResourceNotFoundException" { fmt.Printf(" \033[%dm%s\033[0m (not deployed) \n", colors.Blue, fn.Name) } else { fmt.Printf(" \033[%dm%s\033[0m\n", colors.Blue, fn.Name) } if fn.Description != "" { fmt.Printf(" description: %v\n", fn.Description) } fmt.Printf(" runtime: %v\n", fn.Runtime) fmt.Printf(" memory: %vmb\n", fn.Memory) fmt.Printf(" timeout: %vs\n", fn.Timeout) fmt.Printf(" role: %v\n", fn.Role) fmt.Printf(" handler: %v\n", fn.Handler) if awsFn != nil && awsFn.Configuration != nil && awsFn.Configuration.FunctionArn != nil { fmt.Printf(" arn: %v\n", *awsFn.Configuration.FunctionArn) } if err != nil { fmt.Println() continue // ignore } aliaslist, err := fn.GetAliases() if err != nil { continue } var aliases string for index, alias := range aliaslist.Aliases { if index > 0 { aliases += ", " } aliases += fmt.Sprintf("%s@v%s", *alias.Name, *alias.FunctionVersion) } if aliases == "" { aliases = "<none>" } fmt.Printf(" aliases: %s\n", aliases) fmt.Println() } }
[ "func", "outputList", "(", ")", "{", "fmt", ".", "Println", "(", ")", "\n", "for", "_", ",", "fn", ":=", "range", "root", ".", "Project", ".", "Functions", "{", "awsFn", ",", "err", ":=", "fn", ".", "GetConfigCurrent", "(", ")", "\n", "if", "awserr", ",", "ok", ":=", "err", ".", "(", "awserr", ".", "Error", ")", ";", "ok", "&&", "awserr", ".", "Code", "(", ")", "==", "\"ResourceNotFoundException\"", "{", "fmt", ".", "Printf", "(", "\" \\033[%dm%s\\033[0m (not deployed) \\n\"", ",", "\\033", ",", "\\033", ")", "\n", "}", "else", "\\n", "\n", "colors", ".", "Blue", "\n", "fn", ".", "Name", "\n", "{", "fmt", ".", "Printf", "(", "\" \\033[%dm%s\\033[0m\\n\"", ",", "\\033", ",", "\\033", ")", "\n", "}", "\n", "\\n", "\n", "colors", ".", "Blue", "\n", "fn", ".", "Name", "\n", "if", "fn", ".", "Description", "!=", "\"\"", "{", "fmt", ".", "Printf", "(", "\" description: %v\\n\"", ",", "\\n", ")", "\n", "}", "\n", "fn", ".", "Description", "\n", "fmt", ".", "Printf", "(", "\" runtime: %v\\n\"", ",", "\\n", ")", "\n", "fn", ".", "Runtime", "\n", "fmt", ".", "Printf", "(", "\" memory: %vmb\\n\"", ",", "\\n", ")", "\n", "fn", ".", "Memory", "\n", "fmt", ".", "Printf", "(", "\" timeout: %vs\\n\"", ",", "\\n", ")", "\n", "fn", ".", "Timeout", "\n", "fmt", ".", "Printf", "(", "\" role: %v\\n\"", ",", "\\n", ")", "\n", "}", "\n", "}" ]
// outputList format.
[ "outputList", "format", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/list/list.go#L74-L120
train
xtaci/kcp-go
fec.go
freeRange
func (dec *fecDecoder) freeRange(first, n int, q []fecPacket) []fecPacket { for i := first; i < first+n; i++ { // recycle buffer xmitBuf.Put([]byte(q[i])) } if first == 0 && n < len(q)/2 { return q[n:] } copy(q[first:], q[first+n:]) return q[:len(q)-n] }
go
func (dec *fecDecoder) freeRange(first, n int, q []fecPacket) []fecPacket { for i := first; i < first+n; i++ { // recycle buffer xmitBuf.Put([]byte(q[i])) } if first == 0 && n < len(q)/2 { return q[n:] } copy(q[first:], q[first+n:]) return q[:len(q)-n] }
[ "func", "(", "dec", "*", "fecDecoder", ")", "freeRange", "(", "first", ",", "n", "int", ",", "q", "[", "]", "fecPacket", ")", "[", "]", "fecPacket", "{", "for", "i", ":=", "first", ";", "i", "<", "first", "+", "n", ";", "i", "++", "{", "xmitBuf", ".", "Put", "(", "[", "]", "byte", "(", "q", "[", "i", "]", ")", ")", "\n", "}", "\n", "if", "first", "==", "0", "&&", "n", "<", "len", "(", "q", ")", "/", "2", "{", "return", "q", "[", "n", ":", "]", "\n", "}", "\n", "copy", "(", "q", "[", "first", ":", "]", ",", "q", "[", "first", "+", "n", ":", "]", ")", "\n", "return", "q", "[", ":", "len", "(", "q", ")", "-", "n", "]", "\n", "}" ]
// free a range of fecPacket
[ "free", "a", "range", "of", "fecPacket" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/fec.go#L178-L188
train
xtaci/kcp-go
readloop_linux.go
readLoop
func (s *UDPSession) readLoop() { addr, _ := net.ResolveUDPAddr("udp", s.conn.LocalAddr().String()) if addr.IP.To4() != nil { s.readLoopIPv4() } else { s.readLoopIPv6() } }
go
func (s *UDPSession) readLoop() { addr, _ := net.ResolveUDPAddr("udp", s.conn.LocalAddr().String()) if addr.IP.To4() != nil { s.readLoopIPv4() } else { s.readLoopIPv6() } }
[ "func", "(", "s", "*", "UDPSession", ")", "readLoop", "(", ")", "{", "addr", ",", "_", ":=", "net", ".", "ResolveUDPAddr", "(", "\"udp\"", ",", "s", ".", "conn", ".", "LocalAddr", "(", ")", ".", "String", "(", ")", ")", "\n", "if", "addr", ".", "IP", ".", "To4", "(", ")", "!=", "nil", "{", "s", ".", "readLoopIPv4", "(", ")", "\n", "}", "else", "{", "s", ".", "readLoopIPv6", "(", ")", "\n", "}", "\n", "}" ]
// the read loop for a client session
[ "the", "read", "loop", "for", "a", "client", "session" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/readloop_linux.go#L19-L26
train
xtaci/kcp-go
readloop_linux.go
monitor
func (l *Listener) monitor() { addr, _ := net.ResolveUDPAddr("udp", l.conn.LocalAddr().String()) if addr.IP.To4() != nil { l.monitorIPv4() } else { l.monitorIPv6() } }
go
func (l *Listener) monitor() { addr, _ := net.ResolveUDPAddr("udp", l.conn.LocalAddr().String()) if addr.IP.To4() != nil { l.monitorIPv4() } else { l.monitorIPv6() } }
[ "func", "(", "l", "*", "Listener", ")", "monitor", "(", ")", "{", "addr", ",", "_", ":=", "net", ".", "ResolveUDPAddr", "(", "\"udp\"", ",", "l", ".", "conn", ".", "LocalAddr", "(", ")", ".", "String", "(", ")", ")", "\n", "if", "addr", ".", "IP", ".", "To4", "(", ")", "!=", "nil", "{", "l", ".", "monitorIPv4", "(", ")", "\n", "}", "else", "{", "l", ".", "monitorIPv6", "(", ")", "\n", "}", "\n", "}" ]
// monitor incoming data for all connections of server
[ "monitor", "incoming", "data", "for", "all", "connections", "of", "server" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/readloop_linux.go#L100-L107
train
xtaci/kcp-go
kcp.go
encode
func (seg *segment) encode(ptr []byte) []byte { ptr = ikcp_encode32u(ptr, seg.conv) ptr = ikcp_encode8u(ptr, seg.cmd) ptr = ikcp_encode8u(ptr, seg.frg) ptr = ikcp_encode16u(ptr, seg.wnd) ptr = ikcp_encode32u(ptr, seg.ts) ptr = ikcp_encode32u(ptr, seg.sn) ptr = ikcp_encode32u(ptr, seg.una) ptr = ikcp_encode32u(ptr, uint32(len(seg.data))) atomic.AddUint64(&DefaultSnmp.OutSegs, 1) return ptr }
go
func (seg *segment) encode(ptr []byte) []byte { ptr = ikcp_encode32u(ptr, seg.conv) ptr = ikcp_encode8u(ptr, seg.cmd) ptr = ikcp_encode8u(ptr, seg.frg) ptr = ikcp_encode16u(ptr, seg.wnd) ptr = ikcp_encode32u(ptr, seg.ts) ptr = ikcp_encode32u(ptr, seg.sn) ptr = ikcp_encode32u(ptr, seg.una) ptr = ikcp_encode32u(ptr, uint32(len(seg.data))) atomic.AddUint64(&DefaultSnmp.OutSegs, 1) return ptr }
[ "func", "(", "seg", "*", "segment", ")", "encode", "(", "ptr", "[", "]", "byte", ")", "[", "]", "byte", "{", "ptr", "=", "ikcp_encode32u", "(", "ptr", ",", "seg", ".", "conv", ")", "\n", "ptr", "=", "ikcp_encode8u", "(", "ptr", ",", "seg", ".", "cmd", ")", "\n", "ptr", "=", "ikcp_encode8u", "(", "ptr", ",", "seg", ".", "frg", ")", "\n", "ptr", "=", "ikcp_encode16u", "(", "ptr", ",", "seg", ".", "wnd", ")", "\n", "ptr", "=", "ikcp_encode32u", "(", "ptr", ",", "seg", ".", "ts", ")", "\n", "ptr", "=", "ikcp_encode32u", "(", "ptr", ",", "seg", ".", "sn", ")", "\n", "ptr", "=", "ikcp_encode32u", "(", "ptr", ",", "seg", ".", "una", ")", "\n", "ptr", "=", "ikcp_encode32u", "(", "ptr", ",", "uint32", "(", "len", "(", "seg", ".", "data", ")", ")", ")", "\n", "atomic", ".", "AddUint64", "(", "&", "DefaultSnmp", ".", "OutSegs", ",", "1", ")", "\n", "return", "ptr", "\n", "}" ]
// encode a segment into buffer
[ "encode", "a", "segment", "into", "buffer" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L112-L123
train
xtaci/kcp-go
kcp.go
NewKCP
func NewKCP(conv uint32, output output_callback) *KCP { kcp := new(KCP) kcp.conv = conv kcp.snd_wnd = IKCP_WND_SND kcp.rcv_wnd = IKCP_WND_RCV kcp.rmt_wnd = IKCP_WND_RCV kcp.mtu = IKCP_MTU_DEF kcp.mss = kcp.mtu - IKCP_OVERHEAD kcp.buffer = make([]byte, kcp.mtu) kcp.rx_rto = IKCP_RTO_DEF kcp.rx_minrto = IKCP_RTO_MIN kcp.interval = IKCP_INTERVAL kcp.ts_flush = IKCP_INTERVAL kcp.ssthresh = IKCP_THRESH_INIT kcp.dead_link = IKCP_DEADLINK kcp.output = output return kcp }
go
func NewKCP(conv uint32, output output_callback) *KCP { kcp := new(KCP) kcp.conv = conv kcp.snd_wnd = IKCP_WND_SND kcp.rcv_wnd = IKCP_WND_RCV kcp.rmt_wnd = IKCP_WND_RCV kcp.mtu = IKCP_MTU_DEF kcp.mss = kcp.mtu - IKCP_OVERHEAD kcp.buffer = make([]byte, kcp.mtu) kcp.rx_rto = IKCP_RTO_DEF kcp.rx_minrto = IKCP_RTO_MIN kcp.interval = IKCP_INTERVAL kcp.ts_flush = IKCP_INTERVAL kcp.ssthresh = IKCP_THRESH_INIT kcp.dead_link = IKCP_DEADLINK kcp.output = output return kcp }
[ "func", "NewKCP", "(", "conv", "uint32", ",", "output", "output_callback", ")", "*", "KCP", "{", "kcp", ":=", "new", "(", "KCP", ")", "\n", "kcp", ".", "conv", "=", "conv", "\n", "kcp", ".", "snd_wnd", "=", "IKCP_WND_SND", "\n", "kcp", ".", "rcv_wnd", "=", "IKCP_WND_RCV", "\n", "kcp", ".", "rmt_wnd", "=", "IKCP_WND_RCV", "\n", "kcp", ".", "mtu", "=", "IKCP_MTU_DEF", "\n", "kcp", ".", "mss", "=", "kcp", ".", "mtu", "-", "IKCP_OVERHEAD", "\n", "kcp", ".", "buffer", "=", "make", "(", "[", "]", "byte", ",", "kcp", ".", "mtu", ")", "\n", "kcp", ".", "rx_rto", "=", "IKCP_RTO_DEF", "\n", "kcp", ".", "rx_minrto", "=", "IKCP_RTO_MIN", "\n", "kcp", ".", "interval", "=", "IKCP_INTERVAL", "\n", "kcp", ".", "ts_flush", "=", "IKCP_INTERVAL", "\n", "kcp", ".", "ssthresh", "=", "IKCP_THRESH_INIT", "\n", "kcp", ".", "dead_link", "=", "IKCP_DEADLINK", "\n", "kcp", ".", "output", "=", "output", "\n", "return", "kcp", "\n", "}" ]
// NewKCP create a new kcp control object, 'conv' must equal in two endpoint // from the same connection.
[ "NewKCP", "create", "a", "new", "kcp", "control", "object", "conv", "must", "equal", "in", "two", "endpoint", "from", "the", "same", "connection", "." ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L160-L177
train
xtaci/kcp-go
kcp.go
newSegment
func (kcp *KCP) newSegment(size int) (seg segment) { seg.data = xmitBuf.Get().([]byte)[:size] return }
go
func (kcp *KCP) newSegment(size int) (seg segment) { seg.data = xmitBuf.Get().([]byte)[:size] return }
[ "func", "(", "kcp", "*", "KCP", ")", "newSegment", "(", "size", "int", ")", "(", "seg", "segment", ")", "{", "seg", ".", "data", "=", "xmitBuf", ".", "Get", "(", ")", ".", "(", "[", "]", "byte", ")", "[", ":", "size", "]", "\n", "return", "\n", "}" ]
// newSegment creates a KCP segment
[ "newSegment", "creates", "a", "KCP", "segment" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L180-L183
train
xtaci/kcp-go
kcp.go
delSegment
func (kcp *KCP) delSegment(seg *segment) { if seg.data != nil { xmitBuf.Put(seg.data) seg.data = nil } }
go
func (kcp *KCP) delSegment(seg *segment) { if seg.data != nil { xmitBuf.Put(seg.data) seg.data = nil } }
[ "func", "(", "kcp", "*", "KCP", ")", "delSegment", "(", "seg", "*", "segment", ")", "{", "if", "seg", ".", "data", "!=", "nil", "{", "xmitBuf", ".", "Put", "(", "seg", ".", "data", ")", "\n", "seg", ".", "data", "=", "nil", "\n", "}", "\n", "}" ]
// delSegment recycles a KCP segment
[ "delSegment", "recycles", "a", "KCP", "segment" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L186-L191
train
xtaci/kcp-go
kcp.go
ReserveBytes
func (kcp *KCP) ReserveBytes(n int) bool { if n >= int(kcp.mtu-IKCP_OVERHEAD) || n < 0 { return false } kcp.reserved = n kcp.mss = kcp.mtu - IKCP_OVERHEAD - uint32(n) return true }
go
func (kcp *KCP) ReserveBytes(n int) bool { if n >= int(kcp.mtu-IKCP_OVERHEAD) || n < 0 { return false } kcp.reserved = n kcp.mss = kcp.mtu - IKCP_OVERHEAD - uint32(n) return true }
[ "func", "(", "kcp", "*", "KCP", ")", "ReserveBytes", "(", "n", "int", ")", "bool", "{", "if", "n", ">=", "int", "(", "kcp", ".", "mtu", "-", "IKCP_OVERHEAD", ")", "||", "n", "<", "0", "{", "return", "false", "\n", "}", "\n", "kcp", ".", "reserved", "=", "n", "\n", "kcp", ".", "mss", "=", "kcp", ".", "mtu", "-", "IKCP_OVERHEAD", "-", "uint32", "(", "n", ")", "\n", "return", "true", "\n", "}" ]
// ReserveBytes keeps n bytes untouched from the beginning of the buffer // the output_callback function should be aware of this // return false if n >= mss
[ "ReserveBytes", "keeps", "n", "bytes", "untouched", "from", "the", "beginning", "of", "the", "buffer", "the", "output_callback", "function", "should", "be", "aware", "of", "this", "return", "false", "if", "n", ">", "=", "mss" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L196-L203
train
xtaci/kcp-go
kcp.go
PeekSize
func (kcp *KCP) PeekSize() (length int) { if len(kcp.rcv_queue) == 0 { return -1 } seg := &kcp.rcv_queue[0] if seg.frg == 0 { return len(seg.data) } if len(kcp.rcv_queue) < int(seg.frg+1) { return -1 } for k := range kcp.rcv_queue { seg := &kcp.rcv_queue[k] length += len(seg.data) if seg.frg == 0 { break } } return }
go
func (kcp *KCP) PeekSize() (length int) { if len(kcp.rcv_queue) == 0 { return -1 } seg := &kcp.rcv_queue[0] if seg.frg == 0 { return len(seg.data) } if len(kcp.rcv_queue) < int(seg.frg+1) { return -1 } for k := range kcp.rcv_queue { seg := &kcp.rcv_queue[k] length += len(seg.data) if seg.frg == 0 { break } } return }
[ "func", "(", "kcp", "*", "KCP", ")", "PeekSize", "(", ")", "(", "length", "int", ")", "{", "if", "len", "(", "kcp", ".", "rcv_queue", ")", "==", "0", "{", "return", "-", "1", "\n", "}", "\n", "seg", ":=", "&", "kcp", ".", "rcv_queue", "[", "0", "]", "\n", "if", "seg", ".", "frg", "==", "0", "{", "return", "len", "(", "seg", ".", "data", ")", "\n", "}", "\n", "if", "len", "(", "kcp", ".", "rcv_queue", ")", "<", "int", "(", "seg", ".", "frg", "+", "1", ")", "{", "return", "-", "1", "\n", "}", "\n", "for", "k", ":=", "range", "kcp", ".", "rcv_queue", "{", "seg", ":=", "&", "kcp", ".", "rcv_queue", "[", "k", "]", "\n", "length", "+=", "len", "(", "seg", ".", "data", ")", "\n", "if", "seg", ".", "frg", "==", "0", "{", "break", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// PeekSize checks the size of next message in the recv queue
[ "PeekSize", "checks", "the", "size", "of", "next", "message", "in", "the", "recv", "queue" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L206-L228
train
xtaci/kcp-go
kcp.go
parse_data
func (kcp *KCP) parse_data(newseg segment) bool { sn := newseg.sn if _itimediff(sn, kcp.rcv_nxt+kcp.rcv_wnd) >= 0 || _itimediff(sn, kcp.rcv_nxt) < 0 { return true } n := len(kcp.rcv_buf) - 1 insert_idx := 0 repeat := false for i := n; i >= 0; i-- { seg := &kcp.rcv_buf[i] if seg.sn == sn { repeat = true break } if _itimediff(sn, seg.sn) > 0 { insert_idx = i + 1 break } } if !repeat { // replicate the content if it's new dataCopy := xmitBuf.Get().([]byte)[:len(newseg.data)] copy(dataCopy, newseg.data) newseg.data = dataCopy if insert_idx == n+1 { kcp.rcv_buf = append(kcp.rcv_buf, newseg) } else { kcp.rcv_buf = append(kcp.rcv_buf, segment{}) copy(kcp.rcv_buf[insert_idx+1:], kcp.rcv_buf[insert_idx:]) kcp.rcv_buf[insert_idx] = newseg } } // move available data from rcv_buf -> rcv_queue count := 0 for k := range kcp.rcv_buf { seg := &kcp.rcv_buf[k] if seg.sn == kcp.rcv_nxt && len(kcp.rcv_queue) < int(kcp.rcv_wnd) { kcp.rcv_nxt++ count++ } else { break } } if count > 0 { kcp.rcv_queue = append(kcp.rcv_queue, kcp.rcv_buf[:count]...) kcp.rcv_buf = kcp.remove_front(kcp.rcv_buf, count) } return repeat }
go
func (kcp *KCP) parse_data(newseg segment) bool { sn := newseg.sn if _itimediff(sn, kcp.rcv_nxt+kcp.rcv_wnd) >= 0 || _itimediff(sn, kcp.rcv_nxt) < 0 { return true } n := len(kcp.rcv_buf) - 1 insert_idx := 0 repeat := false for i := n; i >= 0; i-- { seg := &kcp.rcv_buf[i] if seg.sn == sn { repeat = true break } if _itimediff(sn, seg.sn) > 0 { insert_idx = i + 1 break } } if !repeat { // replicate the content if it's new dataCopy := xmitBuf.Get().([]byte)[:len(newseg.data)] copy(dataCopy, newseg.data) newseg.data = dataCopy if insert_idx == n+1 { kcp.rcv_buf = append(kcp.rcv_buf, newseg) } else { kcp.rcv_buf = append(kcp.rcv_buf, segment{}) copy(kcp.rcv_buf[insert_idx+1:], kcp.rcv_buf[insert_idx:]) kcp.rcv_buf[insert_idx] = newseg } } // move available data from rcv_buf -> rcv_queue count := 0 for k := range kcp.rcv_buf { seg := &kcp.rcv_buf[k] if seg.sn == kcp.rcv_nxt && len(kcp.rcv_queue) < int(kcp.rcv_wnd) { kcp.rcv_nxt++ count++ } else { break } } if count > 0 { kcp.rcv_queue = append(kcp.rcv_queue, kcp.rcv_buf[:count]...) kcp.rcv_buf = kcp.remove_front(kcp.rcv_buf, count) } return repeat }
[ "func", "(", "kcp", "*", "KCP", ")", "parse_data", "(", "newseg", "segment", ")", "bool", "{", "sn", ":=", "newseg", ".", "sn", "\n", "if", "_itimediff", "(", "sn", ",", "kcp", ".", "rcv_nxt", "+", "kcp", ".", "rcv_wnd", ")", ">=", "0", "||", "_itimediff", "(", "sn", ",", "kcp", ".", "rcv_nxt", ")", "<", "0", "{", "return", "true", "\n", "}", "\n", "n", ":=", "len", "(", "kcp", ".", "rcv_buf", ")", "-", "1", "\n", "insert_idx", ":=", "0", "\n", "repeat", ":=", "false", "\n", "for", "i", ":=", "n", ";", "i", ">=", "0", ";", "i", "--", "{", "seg", ":=", "&", "kcp", ".", "rcv_buf", "[", "i", "]", "\n", "if", "seg", ".", "sn", "==", "sn", "{", "repeat", "=", "true", "\n", "break", "\n", "}", "\n", "if", "_itimediff", "(", "sn", ",", "seg", ".", "sn", ")", ">", "0", "{", "insert_idx", "=", "i", "+", "1", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "repeat", "{", "dataCopy", ":=", "xmitBuf", ".", "Get", "(", ")", ".", "(", "[", "]", "byte", ")", "[", ":", "len", "(", "newseg", ".", "data", ")", "]", "\n", "copy", "(", "dataCopy", ",", "newseg", ".", "data", ")", "\n", "newseg", ".", "data", "=", "dataCopy", "\n", "if", "insert_idx", "==", "n", "+", "1", "{", "kcp", ".", "rcv_buf", "=", "append", "(", "kcp", ".", "rcv_buf", ",", "newseg", ")", "\n", "}", "else", "{", "kcp", ".", "rcv_buf", "=", "append", "(", "kcp", ".", "rcv_buf", ",", "segment", "{", "}", ")", "\n", "copy", "(", "kcp", ".", "rcv_buf", "[", "insert_idx", "+", "1", ":", "]", ",", "kcp", ".", "rcv_buf", "[", "insert_idx", ":", "]", ")", "\n", "kcp", ".", "rcv_buf", "[", "insert_idx", "]", "=", "newseg", "\n", "}", "\n", "}", "\n", "count", ":=", "0", "\n", "for", "k", ":=", "range", "kcp", ".", "rcv_buf", "{", "seg", ":=", "&", "kcp", ".", "rcv_buf", "[", "k", "]", "\n", "if", "seg", ".", "sn", "==", "kcp", ".", "rcv_nxt", "&&", "len", "(", "kcp", ".", "rcv_queue", ")", "<", "int", "(", "kcp", ".", "rcv_wnd", ")", "{", "kcp", ".", "rcv_nxt", "++", "\n", "count", "++", "\n", "}", "else", "{", "break", "\n", "}", "\n", "}", "\n", "if", "count", ">", "0", "{", "kcp", ".", "rcv_queue", "=", "append", "(", "kcp", ".", "rcv_queue", ",", "kcp", ".", "rcv_buf", "[", ":", "count", "]", "...", ")", "\n", "kcp", ".", "rcv_buf", "=", "kcp", ".", "remove_front", "(", "kcp", ".", "rcv_buf", ",", "count", ")", "\n", "}", "\n", "return", "repeat", "\n", "}" ]
// returns true if data has repeated
[ "returns", "true", "if", "data", "has", "repeated" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L453-L507
train
xtaci/kcp-go
kcp.go
SetMtu
func (kcp *KCP) SetMtu(mtu int) int { if mtu < 50 || mtu < IKCP_OVERHEAD { return -1 } if kcp.reserved >= int(kcp.mtu-IKCP_OVERHEAD) || kcp.reserved < 0 { return -1 } buffer := make([]byte, mtu) if buffer == nil { return -2 } kcp.mtu = uint32(mtu) kcp.mss = kcp.mtu - IKCP_OVERHEAD - uint32(kcp.reserved) kcp.buffer = buffer return 0 }
go
func (kcp *KCP) SetMtu(mtu int) int { if mtu < 50 || mtu < IKCP_OVERHEAD { return -1 } if kcp.reserved >= int(kcp.mtu-IKCP_OVERHEAD) || kcp.reserved < 0 { return -1 } buffer := make([]byte, mtu) if buffer == nil { return -2 } kcp.mtu = uint32(mtu) kcp.mss = kcp.mtu - IKCP_OVERHEAD - uint32(kcp.reserved) kcp.buffer = buffer return 0 }
[ "func", "(", "kcp", "*", "KCP", ")", "SetMtu", "(", "mtu", "int", ")", "int", "{", "if", "mtu", "<", "50", "||", "mtu", "<", "IKCP_OVERHEAD", "{", "return", "-", "1", "\n", "}", "\n", "if", "kcp", ".", "reserved", ">=", "int", "(", "kcp", ".", "mtu", "-", "IKCP_OVERHEAD", ")", "||", "kcp", ".", "reserved", "<", "0", "{", "return", "-", "1", "\n", "}", "\n", "buffer", ":=", "make", "(", "[", "]", "byte", ",", "mtu", ")", "\n", "if", "buffer", "==", "nil", "{", "return", "-", "2", "\n", "}", "\n", "kcp", ".", "mtu", "=", "uint32", "(", "mtu", ")", "\n", "kcp", ".", "mss", "=", "kcp", ".", "mtu", "-", "IKCP_OVERHEAD", "-", "uint32", "(", "kcp", ".", "reserved", ")", "\n", "kcp", ".", "buffer", "=", "buffer", "\n", "return", "0", "\n", "}" ]
// SetMtu changes MTU size, default is 1400
[ "SetMtu", "changes", "MTU", "size", "default", "is", "1400" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L957-L973
train
xtaci/kcp-go
kcp.go
WaitSnd
func (kcp *KCP) WaitSnd() int { return len(kcp.snd_buf) + len(kcp.snd_queue) }
go
func (kcp *KCP) WaitSnd() int { return len(kcp.snd_buf) + len(kcp.snd_queue) }
[ "func", "(", "kcp", "*", "KCP", ")", "WaitSnd", "(", ")", "int", "{", "return", "len", "(", "kcp", ".", "snd_buf", ")", "+", "len", "(", "kcp", ".", "snd_queue", ")", "\n", "}" ]
// WaitSnd gets how many packet is waiting to be sent
[ "WaitSnd", "gets", "how", "many", "packet", "is", "waiting", "to", "be", "sent" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L1019-L1021
train