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
muesli/beehive
bees/bees.go
LogFatal
func (bee *Bee) LogFatal(args ...interface{}) { a := []interface{}{"[" + bee.Name() + "]:"} for _, v := range args { a = append(a, v) } log.Panicln(a...) Log(bee.Name(), fmt.Sprintln(args...), 2) }
go
func (bee *Bee) LogFatal(args ...interface{}) { a := []interface{}{"[" + bee.Name() + "]:"} for _, v := range args { a = append(a, v) } log.Panicln(a...) Log(bee.Name(), fmt.Sprintln(args...), 2) }
[ "func", "(", "bee", "*", "Bee", ")", "LogFatal", "(", "args", "...", "interface", "{", "}", ")", "{", "a", ":=", "[", "]", "interface", "{", "}", "{", "\"[\"", "+", "bee", ".", "Name", "(", ")", "+", "\"]:\"", "}", "\n", "for", "_", ",", "v", ":=", "range", "args", "{", "a", "=", "append", "(", "a", ",", "v", ")", "\n", "}", "\n", "log", ".", "Panicln", "(", "a", "...", ")", "\n", "Log", "(", "bee", ".", "Name", "(", ")", ",", "fmt", ".", "Sprintln", "(", "args", "...", ")", ",", "2", ")", "\n", "}" ]
// LogFatal logs a fatal error
[ "LogFatal", "logs", "a", "fatal", "error" ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L359-L366
train
muesli/beehive
bees/events.go
handleEvents
func handleEvents() { for { event, ok := <-eventsIn if !ok { log.Println() log.Println("Stopped event handler!") break } bee := GetBee(event.Bee) (*bee).LogEvent() log.Println() log.Println("Event received:", event.Bee, "/", event.Name, "-", GetEventDescriptor(&event).Description) for _, v := range event.Options { log.Println("\tOptions:", v) } go func() { defer func() { if e := recover(); e != nil { log.Printf("Fatal chain event: %s %s", e, debug.Stack()) } }() execChains(&event) }() } }
go
func handleEvents() { for { event, ok := <-eventsIn if !ok { log.Println() log.Println("Stopped event handler!") break } bee := GetBee(event.Bee) (*bee).LogEvent() log.Println() log.Println("Event received:", event.Bee, "/", event.Name, "-", GetEventDescriptor(&event).Description) for _, v := range event.Options { log.Println("\tOptions:", v) } go func() { defer func() { if e := recover(); e != nil { log.Printf("Fatal chain event: %s %s", e, debug.Stack()) } }() execChains(&event) }() } }
[ "func", "handleEvents", "(", ")", "{", "for", "{", "event", ",", "ok", ":=", "<-", "eventsIn", "\n", "if", "!", "ok", "{", "log", ".", "Println", "(", ")", "\n", "log", ".", "Println", "(", "\"Stopped event handler!\"", ")", "\n", "break", "\n", "}", "\n", "bee", ":=", "GetBee", "(", "event", ".", "Bee", ")", "\n", "(", "*", "bee", ")", ".", "LogEvent", "(", ")", "\n", "log", ".", "Println", "(", ")", "\n", "log", ".", "Println", "(", "\"Event received:\"", ",", "event", ".", "Bee", ",", "\"/\"", ",", "event", ".", "Name", ",", "\"-\"", ",", "GetEventDescriptor", "(", "&", "event", ")", ".", "Description", ")", "\n", "for", "_", ",", "v", ":=", "range", "event", ".", "Options", "{", "log", ".", "Println", "(", "\"\\tOptions:\"", ",", "\\t", ")", "\n", "}", "\n", "v", "\n", "}", "\n", "}" ]
// handleEvents handles incoming events and executes matching Chains.
[ "handleEvents", "handles", "incoming", "events", "and", "executes", "matching", "Chains", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/events.go#L39-L67
train
muesli/beehive
filters/filters.go
GetFilter
func GetFilter(identifier string) *FilterInterface { filter, ok := filters[identifier] if ok { return filter } return nil }
go
func GetFilter(identifier string) *FilterInterface { filter, ok := filters[identifier] if ok { return filter } return nil }
[ "func", "GetFilter", "(", "identifier", "string", ")", "*", "FilterInterface", "{", "filter", ",", "ok", ":=", "filters", "[", "identifier", "]", "\n", "if", "ok", "{", "return", "filter", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetFilter returns a filter with a specific name
[ "GetFilter", "returns", "a", "filter", "with", "a", "specific", "name" ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/filters/filters.go#L46-L53
train
muesli/beehive
api/resources/actions/actions_response.go
AddAction
func (r *ActionResponse) AddAction(action *bees.Action) { r.actions = append(r.actions, action) r.Actions = append(r.Actions, prepareActionResponse(r.Context, action)) }
go
func (r *ActionResponse) AddAction(action *bees.Action) { r.actions = append(r.actions, action) r.Actions = append(r.Actions, prepareActionResponse(r.Context, action)) }
[ "func", "(", "r", "*", "ActionResponse", ")", "AddAction", "(", "action", "*", "bees", ".", "Action", ")", "{", "r", ".", "actions", "=", "append", "(", "r", ".", "actions", ",", "action", ")", "\n", "r", ".", "Actions", "=", "append", "(", "r", ".", "Actions", ",", "prepareActionResponse", "(", "r", ".", "Context", ",", "action", ")", ")", "\n", "}" ]
// AddAction adds a action to the response
[ "AddAction", "adds", "a", "action", "to", "the", "response" ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/api/resources/actions/actions_response.go#L53-L56
train
muesli/beehive
api/resources/logs/logs_response.go
AddLog
func (r *LogResponse) AddLog(log *bees.LogMessage) { r.logs = append(r.logs, log) r.Logs = append(r.Logs, prepareLogResponse(r.Context, log)) }
go
func (r *LogResponse) AddLog(log *bees.LogMessage) { r.logs = append(r.logs, log) r.Logs = append(r.Logs, prepareLogResponse(r.Context, log)) }
[ "func", "(", "r", "*", "LogResponse", ")", "AddLog", "(", "log", "*", "bees", ".", "LogMessage", ")", "{", "r", ".", "logs", "=", "append", "(", "r", ".", "logs", ",", "log", ")", "\n", "r", ".", "Logs", "=", "append", "(", "r", ".", "Logs", ",", "prepareLogResponse", "(", "r", ".", "Context", ",", "log", ")", ")", "\n", "}" ]
// AddLog adds a log to the response
[ "AddLog", "adds", "a", "log", "to", "the", "response" ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/api/resources/logs/logs_response.go#L56-L59
train
muesli/beehive
bees/actions.go
GetAction
func GetAction(id string) *Action { for _, a := range actions { if a.ID == id { return &a } } return nil }
go
func GetAction(id string) *Action { for _, a := range actions { if a.ID == id { return &a } } return nil }
[ "func", "GetAction", "(", "id", "string", ")", "*", "Action", "{", "for", "_", ",", "a", ":=", "range", "actions", "{", "if", "a", ".", "ID", "==", "id", "{", "return", "&", "a", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetAction returns one action with a specific ID.
[ "GetAction", "returns", "one", "action", "with", "a", "specific", "ID", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/actions.go#L51-L59
train
muesli/beehive
bees/actions.go
execAction
func execAction(action Action, opts map[string]interface{}) bool { a := Action{ Bee: action.Bee, Name: action.Name, } for _, opt := range action.Options { ph := Placeholder{ Name: opt.Name, } switch opt.Value.(type) { case string: var value bytes.Buffer tmpl, err := template.New(action.Bee + "_" + action.Name + "_" + opt.Name).Funcs(templatehelper.FuncMap).Parse(opt.Value.(string)) if err == nil { err = tmpl.Execute(&value, opts) } if err != nil { panic(err) } ph.Type = "string" ph.Value = value.String() default: ph.Type = opt.Type ph.Value = opt.Value } a.Options = append(a.Options, ph) } bee := GetBee(a.Bee) if (*bee).IsRunning() { (*bee).LogAction() log.Println("\tExecuting action:", a.Bee, "/", a.Name, "-", GetActionDescriptor(&a).Description) for _, v := range a.Options { log.Println("\t\tOptions:", v) } (*bee).Action(a) } else { log.Println("\tNot executing action on stopped bee:", a.Bee, "/", a.Name, "-", GetActionDescriptor(&a).Description) for _, v := range a.Options { log.Println("\t\tOptions:", v) } } return true }
go
func execAction(action Action, opts map[string]interface{}) bool { a := Action{ Bee: action.Bee, Name: action.Name, } for _, opt := range action.Options { ph := Placeholder{ Name: opt.Name, } switch opt.Value.(type) { case string: var value bytes.Buffer tmpl, err := template.New(action.Bee + "_" + action.Name + "_" + opt.Name).Funcs(templatehelper.FuncMap).Parse(opt.Value.(string)) if err == nil { err = tmpl.Execute(&value, opts) } if err != nil { panic(err) } ph.Type = "string" ph.Value = value.String() default: ph.Type = opt.Type ph.Value = opt.Value } a.Options = append(a.Options, ph) } bee := GetBee(a.Bee) if (*bee).IsRunning() { (*bee).LogAction() log.Println("\tExecuting action:", a.Bee, "/", a.Name, "-", GetActionDescriptor(&a).Description) for _, v := range a.Options { log.Println("\t\tOptions:", v) } (*bee).Action(a) } else { log.Println("\tNot executing action on stopped bee:", a.Bee, "/", a.Name, "-", GetActionDescriptor(&a).Description) for _, v := range a.Options { log.Println("\t\tOptions:", v) } } return true }
[ "func", "execAction", "(", "action", "Action", ",", "opts", "map", "[", "string", "]", "interface", "{", "}", ")", "bool", "{", "a", ":=", "Action", "{", "Bee", ":", "action", ".", "Bee", ",", "Name", ":", "action", ".", "Name", ",", "}", "\n", "for", "_", ",", "opt", ":=", "range", "action", ".", "Options", "{", "ph", ":=", "Placeholder", "{", "Name", ":", "opt", ".", "Name", ",", "}", "\n", "switch", "opt", ".", "Value", ".", "(", "type", ")", "{", "case", "string", ":", "var", "value", "bytes", ".", "Buffer", "\n", "tmpl", ",", "err", ":=", "template", ".", "New", "(", "action", ".", "Bee", "+", "\"_\"", "+", "action", ".", "Name", "+", "\"_\"", "+", "opt", ".", "Name", ")", ".", "Funcs", "(", "templatehelper", ".", "FuncMap", ")", ".", "Parse", "(", "opt", ".", "Value", ".", "(", "string", ")", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "tmpl", ".", "Execute", "(", "&", "value", ",", "opts", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "ph", ".", "Type", "=", "\"string\"", "\n", "ph", ".", "Value", "=", "value", ".", "String", "(", ")", "\n", "default", ":", "ph", ".", "Type", "=", "opt", ".", "Type", "\n", "ph", ".", "Value", "=", "opt", ".", "Value", "\n", "}", "\n", "a", ".", "Options", "=", "append", "(", "a", ".", "Options", ",", "ph", ")", "\n", "}", "\n", "bee", ":=", "GetBee", "(", "a", ".", "Bee", ")", "\n", "if", "(", "*", "bee", ")", ".", "IsRunning", "(", ")", "{", "(", "*", "bee", ")", ".", "LogAction", "(", ")", "\n", "log", ".", "Println", "(", "\"\\tExecuting action:\"", ",", "\\t", ",", "a", ".", "Bee", ",", "\"/\"", ",", "a", ".", "Name", ",", "\"-\"", ")", "\n", "GetActionDescriptor", "(", "&", "a", ")", ".", "Description", "\n", "for", "_", ",", "v", ":=", "range", "a", ".", "Options", "{", "log", ".", "Println", "(", "\"\\t\\tOptions:\"", ",", "\\t", ")", "\n", "}", "\n", "}", "else", "\\t", "\n", "v", "\n", "}" ]
// execAction executes an action and map its ins & outs.
[ "execAction", "executes", "an", "action", "and", "map", "its", "ins", "&", "outs", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/actions.go#L67-L118
train
muesli/beehive
api/context/context.go
NewAPIContext
func (context *APIContext) NewAPIContext() smolder.APIContext { ctx := &APIContext{ Config: context.Config, } return ctx }
go
func (context *APIContext) NewAPIContext() smolder.APIContext { ctx := &APIContext{ Config: context.Config, } return ctx }
[ "func", "(", "context", "*", "APIContext", ")", "NewAPIContext", "(", ")", "smolder", ".", "APIContext", "{", "ctx", ":=", "&", "APIContext", "{", "Config", ":", "context", ".", "Config", ",", "}", "\n", "return", "ctx", "\n", "}" ]
// NewAPIContext returns a new polly context
[ "NewAPIContext", "returns", "a", "new", "polly", "context" ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/api/context/context.go#L36-L41
train
muesli/beehive
bees/placeholders.go
SetValue
func (ph *Placeholders) SetValue(name string, _type string, value interface{}) { if ph.Value(name) == nil { p := Placeholder{ Name: name, Type: _type, Value: value, } *ph = append(*ph, p) } else { for i := 0; i < len(*ph); i++ { if (*ph)[i].Name == name { (*ph)[i].Type = _type (*ph)[i].Value = value } } } }
go
func (ph *Placeholders) SetValue(name string, _type string, value interface{}) { if ph.Value(name) == nil { p := Placeholder{ Name: name, Type: _type, Value: value, } *ph = append(*ph, p) } else { for i := 0; i < len(*ph); i++ { if (*ph)[i].Name == name { (*ph)[i].Type = _type (*ph)[i].Value = value } } } }
[ "func", "(", "ph", "*", "Placeholders", ")", "SetValue", "(", "name", "string", ",", "_type", "string", ",", "value", "interface", "{", "}", ")", "{", "if", "ph", ".", "Value", "(", "name", ")", "==", "nil", "{", "p", ":=", "Placeholder", "{", "Name", ":", "name", ",", "Type", ":", "_type", ",", "Value", ":", "value", ",", "}", "\n", "*", "ph", "=", "append", "(", "*", "ph", ",", "p", ")", "\n", "}", "else", "{", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "*", "ph", ")", ";", "i", "++", "{", "if", "(", "*", "ph", ")", "[", "i", "]", ".", "Name", "==", "name", "{", "(", "*", "ph", ")", "[", "i", "]", ".", "Type", "=", "_type", "\n", "(", "*", "ph", ")", "[", "i", "]", ".", "Value", "=", "value", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// SetValue sets a value in the Placeholder slice.
[ "SetValue", "sets", "a", "value", "in", "the", "Placeholder", "slice", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/placeholders.go#L45-L61
train
muesli/beehive
bees/placeholders.go
Value
func (ph Placeholders) Value(name string) interface{} { for _, p := range ph { if p.Name == name { return p.Value } } return nil }
go
func (ph Placeholders) Value(name string) interface{} { for _, p := range ph { if p.Name == name { return p.Value } } return nil }
[ "func", "(", "ph", "Placeholders", ")", "Value", "(", "name", "string", ")", "interface", "{", "}", "{", "for", "_", ",", "p", ":=", "range", "ph", "{", "if", "p", ".", "Name", "==", "name", "{", "return", "p", ".", "Value", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Value retrieves a value from a Placeholder slice.
[ "Value", "retrieves", "a", "value", "from", "a", "Placeholder", "slice", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/placeholders.go#L64-L72
train
muesli/beehive
bees/placeholders.go
Bind
func (ph Placeholders) Bind(name string, dst interface{}) error { v := ph.Value(name) if v == nil { return errors.New("Placeholder with name " + name + " not found") } return ConvertValue(v, dst) }
go
func (ph Placeholders) Bind(name string, dst interface{}) error { v := ph.Value(name) if v == nil { return errors.New("Placeholder with name " + name + " not found") } return ConvertValue(v, dst) }
[ "func", "(", "ph", "Placeholders", ")", "Bind", "(", "name", "string", ",", "dst", "interface", "{", "}", ")", "error", "{", "v", ":=", "ph", ".", "Value", "(", "name", ")", "\n", "if", "v", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"Placeholder with name \"", "+", "name", "+", "\" not found\"", ")", "\n", "}", "\n", "return", "ConvertValue", "(", "v", ",", "dst", ")", "\n", "}" ]
// Bind a value from a Placeholder slice.
[ "Bind", "a", "value", "from", "a", "Placeholder", "slice", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/placeholders.go#L75-L82
train
muesli/beehive
bees/descriptors.go
GetActionDescriptor
func GetActionDescriptor(action *Action) ActionDescriptor { bee := GetBee(action.Bee) if bee == nil { panic("Bee " + action.Bee + " not registered") } factory := (*GetFactory((*bee).Namespace())) for _, ac := range factory.Actions() { if ac.Name == action.Name { return ac } } return ActionDescriptor{} }
go
func GetActionDescriptor(action *Action) ActionDescriptor { bee := GetBee(action.Bee) if bee == nil { panic("Bee " + action.Bee + " not registered") } factory := (*GetFactory((*bee).Namespace())) for _, ac := range factory.Actions() { if ac.Name == action.Name { return ac } } return ActionDescriptor{} }
[ "func", "GetActionDescriptor", "(", "action", "*", "Action", ")", "ActionDescriptor", "{", "bee", ":=", "GetBee", "(", "action", ".", "Bee", ")", "\n", "if", "bee", "==", "nil", "{", "panic", "(", "\"Bee \"", "+", "action", ".", "Bee", "+", "\" not registered\"", ")", "\n", "}", "\n", "factory", ":=", "(", "*", "GetFactory", "(", "(", "*", "bee", ")", ".", "Namespace", "(", ")", ")", ")", "\n", "for", "_", ",", "ac", ":=", "range", "factory", ".", "Actions", "(", ")", "{", "if", "ac", ".", "Name", "==", "action", ".", "Name", "{", "return", "ac", "\n", "}", "\n", "}", "\n", "return", "ActionDescriptor", "{", "}", "\n", "}" ]
// GetActionDescriptor returns the ActionDescriptor matching an action.
[ "GetActionDescriptor", "returns", "the", "ActionDescriptor", "matching", "an", "action", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/descriptors.go#L65-L78
train
muesli/beehive
bees/descriptors.go
GetEventDescriptor
func GetEventDescriptor(event *Event) EventDescriptor { bee := GetBee(event.Bee) if bee == nil { panic("Bee " + event.Bee + " not registered") } factory := (*GetFactory((*bee).Namespace())) for _, ev := range factory.Events() { if ev.Name == event.Name { return ev } } return EventDescriptor{} }
go
func GetEventDescriptor(event *Event) EventDescriptor { bee := GetBee(event.Bee) if bee == nil { panic("Bee " + event.Bee + " not registered") } factory := (*GetFactory((*bee).Namespace())) for _, ev := range factory.Events() { if ev.Name == event.Name { return ev } } return EventDescriptor{} }
[ "func", "GetEventDescriptor", "(", "event", "*", "Event", ")", "EventDescriptor", "{", "bee", ":=", "GetBee", "(", "event", ".", "Bee", ")", "\n", "if", "bee", "==", "nil", "{", "panic", "(", "\"Bee \"", "+", "event", ".", "Bee", "+", "\" not registered\"", ")", "\n", "}", "\n", "factory", ":=", "(", "*", "GetFactory", "(", "(", "*", "bee", ")", ".", "Namespace", "(", ")", ")", ")", "\n", "for", "_", ",", "ev", ":=", "range", "factory", ".", "Events", "(", ")", "{", "if", "ev", ".", "Name", "==", "event", ".", "Name", "{", "return", "ev", "\n", "}", "\n", "}", "\n", "return", "EventDescriptor", "{", "}", "\n", "}" ]
// GetEventDescriptor returns the EventDescriptor matching an event.
[ "GetEventDescriptor", "returns", "the", "EventDescriptor", "matching", "an", "event", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/descriptors.go#L81-L94
train
muesli/beehive
bees/ircbee/ircbeefactory.go
States
func (factory *IrcBeeFactory) States() []bees.StateDescriptor { opts := []bees.StateDescriptor{ { Name: "connected", Description: "Whether this bee is currently connected to IRC", Type: "bool", }, { Name: "channels", Description: "Which channels this bee is currently connected to", Type: "[]string", }, } return opts }
go
func (factory *IrcBeeFactory) States() []bees.StateDescriptor { opts := []bees.StateDescriptor{ { Name: "connected", Description: "Whether this bee is currently connected to IRC", Type: "bool", }, { Name: "channels", Description: "Which channels this bee is currently connected to", Type: "[]string", }, } return opts }
[ "func", "(", "factory", "*", "IrcBeeFactory", ")", "States", "(", ")", "[", "]", "bees", ".", "StateDescriptor", "{", "opts", ":=", "[", "]", "bees", ".", "StateDescriptor", "{", "{", "Name", ":", "\"connected\"", ",", "Description", ":", "\"Whether this bee is currently connected to IRC\"", ",", "Type", ":", "\"bool\"", ",", "}", ",", "{", "Name", ":", "\"channels\"", ",", "Description", ":", "\"Which channels this bee is currently connected to\"", ",", "Type", ":", "\"[]string\"", ",", "}", ",", "}", "\n", "return", "opts", "\n", "}" ]
// States returns the state values provided by this Bee.
[ "States", "returns", "the", "state", "values", "provided", "by", "this", "Bee", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/ircbee/ircbeefactory.go#L105-L119
train
muesli/beehive
api/resources/chains/chains_response.go
AddChain
func (r *ChainResponse) AddChain(chain bees.Chain) { r.chains[chain.Name] = &chain }
go
func (r *ChainResponse) AddChain(chain bees.Chain) { r.chains[chain.Name] = &chain }
[ "func", "(", "r", "*", "ChainResponse", ")", "AddChain", "(", "chain", "bees", ".", "Chain", ")", "{", "r", ".", "chains", "[", "chain", ".", "Name", "]", "=", "&", "chain", "\n", "}" ]
// AddChain adds a chain to the response
[ "AddChain", "adds", "a", "chain", "to", "the", "response" ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/api/resources/chains/chains_response.go#L58-L60
train
muesli/beehive
bees/cronbee/cron/cronparser.go
checkValues
func (c *crontime) checkValues() { for _, sec := range c.second { if sec >= 60 || sec < 0 { log.Panicln("Cronbee: Your config seems messed up. Check the range of \"Second\".") } } for _, min := range c.second { if min >= 60 || min < 0 { log.Panicln("Cronbee: Your config seems messed up. Check the range of \"Minute\".") } } for _, hour := range c.hour { if hour >= 24 || hour < 0 { log.Panicln("Cronbee: Your config seems messed up. Check the range of \"Hour\".") } } for _, dow := range c.dow { if dow >= 7 || dow < 0 { log.Panicln("Cronbee: Your config seems messed up. Check the range of \"DayOfWeek\".") } } for _, dom := range c.dom { if dom >= 32 || dom < 1 { log.Panicln("Cronbee: Your config seems messed up. Check the range of \"DayOfMonth\".") } } for _, month := range c.month { if month >= 13 || month < 1 { log.Panicln("Cronbee: Your config seems messed up. Check the range of \"Month\".") } } }
go
func (c *crontime) checkValues() { for _, sec := range c.second { if sec >= 60 || sec < 0 { log.Panicln("Cronbee: Your config seems messed up. Check the range of \"Second\".") } } for _, min := range c.second { if min >= 60 || min < 0 { log.Panicln("Cronbee: Your config seems messed up. Check the range of \"Minute\".") } } for _, hour := range c.hour { if hour >= 24 || hour < 0 { log.Panicln("Cronbee: Your config seems messed up. Check the range of \"Hour\".") } } for _, dow := range c.dow { if dow >= 7 || dow < 0 { log.Panicln("Cronbee: Your config seems messed up. Check the range of \"DayOfWeek\".") } } for _, dom := range c.dom { if dom >= 32 || dom < 1 { log.Panicln("Cronbee: Your config seems messed up. Check the range of \"DayOfMonth\".") } } for _, month := range c.month { if month >= 13 || month < 1 { log.Panicln("Cronbee: Your config seems messed up. Check the range of \"Month\".") } } }
[ "func", "(", "c", "*", "crontime", ")", "checkValues", "(", ")", "{", "for", "_", ",", "sec", ":=", "range", "c", ".", "second", "{", "if", "sec", ">=", "60", "||", "sec", "<", "0", "{", "log", ".", "Panicln", "(", "\"Cronbee: Your config seems messed up. Check the range of \\\"Second\\\".\"", ")", "\n", "}", "\n", "}", "\n", "\\\"", "\n", "\\\"", "\n", "for", "_", ",", "min", ":=", "range", "c", ".", "second", "{", "if", "min", ">=", "60", "||", "min", "<", "0", "{", "log", ".", "Panicln", "(", "\"Cronbee: Your config seems messed up. Check the range of \\\"Minute\\\".\"", ")", "\n", "}", "\n", "}", "\n", "\\\"", "\n", "\\\"", "\n", "}" ]
// Look for obvious nonsense in the config.
[ "Look", "for", "obvious", "nonsense", "in", "the", "config", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/cronbee/cron/cronparser.go#L285-L321
train
muesli/beehive
bees/cronbee/cron/cronparser.go
valueRange
func valueRange(a, b, base int) []int { value := make([]int, absoluteOverBreakpoint(a, b, base)+1) i := 0 for ; a != b; a++ { if a == base { a = 0 } value[i] = a i++ } value[i] = a return value }
go
func valueRange(a, b, base int) []int { value := make([]int, absoluteOverBreakpoint(a, b, base)+1) i := 0 for ; a != b; a++ { if a == base { a = 0 } value[i] = a i++ } value[i] = a return value }
[ "func", "valueRange", "(", "a", ",", "b", ",", "base", "int", ")", "[", "]", "int", "{", "value", ":=", "make", "(", "[", "]", "int", ",", "absoluteOverBreakpoint", "(", "a", ",", "b", ",", "base", ")", "+", "1", ")", "\n", "i", ":=", "0", "\n", "for", ";", "a", "!=", "b", ";", "a", "++", "{", "if", "a", "==", "base", "{", "a", "=", "0", "\n", "}", "\n", "value", "[", "i", "]", "=", "a", "\n", "i", "++", "\n", "}", "\n", "value", "[", "i", "]", "=", "a", "\n", "return", "value", "\n", "}" ]
// Returns an array filled with all values between a and b considering // the base.
[ "Returns", "an", "array", "filled", "with", "all", "values", "between", "a", "and", "b", "considering", "the", "base", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/cronbee/cron/cronparser.go#L346-L358
train
muesli/beehive
bees/logs.go
NewLogMessage
func NewLogMessage(bee string, message string, messageType uint) LogMessage { return LogMessage{ ID: UUID(), Bee: bee, Message: message, MessageType: messageType, Timestamp: time.Now(), } }
go
func NewLogMessage(bee string, message string, messageType uint) LogMessage { return LogMessage{ ID: UUID(), Bee: bee, Message: message, MessageType: messageType, Timestamp: time.Now(), } }
[ "func", "NewLogMessage", "(", "bee", "string", ",", "message", "string", ",", "messageType", "uint", ")", "LogMessage", "{", "return", "LogMessage", "{", "ID", ":", "UUID", "(", ")", ",", "Bee", ":", "bee", ",", "Message", ":", "message", ",", "MessageType", ":", "messageType", ",", "Timestamp", ":", "time", ".", "Now", "(", ")", ",", "}", "\n", "}" ]
// NewLogMessage returns a newly composed LogMessage
[ "NewLogMessage", "returns", "a", "newly", "composed", "LogMessage" ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/logs.go#L52-L60
train
muesli/beehive
bees/logs.go
Log
func Log(bee string, message string, messageType uint) { logMutex.Lock() defer logMutex.Unlock() logs[bee] = append(logs[bee], NewLogMessage(bee, message, messageType)) }
go
func Log(bee string, message string, messageType uint) { logMutex.Lock() defer logMutex.Unlock() logs[bee] = append(logs[bee], NewLogMessage(bee, message, messageType)) }
[ "func", "Log", "(", "bee", "string", ",", "message", "string", ",", "messageType", "uint", ")", "{", "logMutex", ".", "Lock", "(", ")", "\n", "defer", "logMutex", ".", "Unlock", "(", ")", "\n", "logs", "[", "bee", "]", "=", "append", "(", "logs", "[", "bee", "]", ",", "NewLogMessage", "(", "bee", ",", "message", ",", "messageType", ")", ")", "\n", "}" ]
// Log adds a new LogMessage to the log
[ "Log", "adds", "a", "new", "LogMessage", "to", "the", "log" ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/logs.go#L63-L68
train
muesli/beehive
bees/logs.go
GetLogs
func GetLogs(bee string) []LogMessage { r := []LogMessage{} logMutex.RLock() for b, ls := range logs { if len(bee) == 0 || bee == b { for _, l := range ls { r = append(r, l) } } } logMutex.RUnlock() sort.Sort(LogSorter(r)) return r }
go
func GetLogs(bee string) []LogMessage { r := []LogMessage{} logMutex.RLock() for b, ls := range logs { if len(bee) == 0 || bee == b { for _, l := range ls { r = append(r, l) } } } logMutex.RUnlock() sort.Sort(LogSorter(r)) return r }
[ "func", "GetLogs", "(", "bee", "string", ")", "[", "]", "LogMessage", "{", "r", ":=", "[", "]", "LogMessage", "{", "}", "\n", "logMutex", ".", "RLock", "(", ")", "\n", "for", "b", ",", "ls", ":=", "range", "logs", "{", "if", "len", "(", "bee", ")", "==", "0", "||", "bee", "==", "b", "{", "for", "_", ",", "l", ":=", "range", "ls", "{", "r", "=", "append", "(", "r", ",", "l", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "logMutex", ".", "RUnlock", "(", ")", "\n", "sort", ".", "Sort", "(", "LogSorter", "(", "r", ")", ")", "\n", "return", "r", "\n", "}" ]
// GetLogs returns all logs for a Bee.
[ "GetLogs", "returns", "all", "logs", "for", "a", "Bee", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/logs.go#L71-L86
train
muesli/beehive
bees/ircbee/irctools/irctools.go
Colored
func Colored(val string, color string) string { // 00 white 01 black 02 blue (navy) 03 green 04 red 05 brown (maroon) // 06 purple 07 orange (olive) 08 yellow 09 light green (lime) // 10 teal (a green/blue cyan) 11 light cyan (cyan) (aqua) 12 light blue (royal) // 13 pink (light purple) (fuchsia) 14 grey 15 light grey (silver) c := "01" switch color { case "white": c = "00" case "black": c = "01" case "blue": c = "02" case "green": c = "03" case "red": c = "04" case "brown": c = "05" case "purple": c = "06" case "orange": c = "07" case "yellow": c = "08" case "lime": c = "09" case "teal": c = "10" case "cyan": c = "11" case "lightblue": c = "12" case "pink": c = "13" case "grey": c = "14" case "silver": c = "15" } return "\x03" + c + val + "\x03" }
go
func Colored(val string, color string) string { // 00 white 01 black 02 blue (navy) 03 green 04 red 05 brown (maroon) // 06 purple 07 orange (olive) 08 yellow 09 light green (lime) // 10 teal (a green/blue cyan) 11 light cyan (cyan) (aqua) 12 light blue (royal) // 13 pink (light purple) (fuchsia) 14 grey 15 light grey (silver) c := "01" switch color { case "white": c = "00" case "black": c = "01" case "blue": c = "02" case "green": c = "03" case "red": c = "04" case "brown": c = "05" case "purple": c = "06" case "orange": c = "07" case "yellow": c = "08" case "lime": c = "09" case "teal": c = "10" case "cyan": c = "11" case "lightblue": c = "12" case "pink": c = "13" case "grey": c = "14" case "silver": c = "15" } return "\x03" + c + val + "\x03" }
[ "func", "Colored", "(", "val", "string", ",", "color", "string", ")", "string", "{", "c", ":=", "\"01\"", "\n", "switch", "color", "{", "case", "\"white\"", ":", "c", "=", "\"00\"", "\n", "case", "\"black\"", ":", "c", "=", "\"01\"", "\n", "case", "\"blue\"", ":", "c", "=", "\"02\"", "\n", "case", "\"green\"", ":", "c", "=", "\"03\"", "\n", "case", "\"red\"", ":", "c", "=", "\"04\"", "\n", "case", "\"brown\"", ":", "c", "=", "\"05\"", "\n", "case", "\"purple\"", ":", "c", "=", "\"06\"", "\n", "case", "\"orange\"", ":", "c", "=", "\"07\"", "\n", "case", "\"yellow\"", ":", "c", "=", "\"08\"", "\n", "case", "\"lime\"", ":", "c", "=", "\"09\"", "\n", "case", "\"teal\"", ":", "c", "=", "\"10\"", "\n", "case", "\"cyan\"", ":", "c", "=", "\"11\"", "\n", "case", "\"lightblue\"", ":", "c", "=", "\"12\"", "\n", "case", "\"pink\"", ":", "c", "=", "\"13\"", "\n", "case", "\"grey\"", ":", "c", "=", "\"14\"", "\n", "case", "\"silver\"", ":", "c", "=", "\"15\"", "\n", "}", "\n", "return", "\"\\x03\"", "+", "\\x03", "+", "c", "+", "val", "\n", "}" ]
// Colored wraps val in color styling tags.
[ "Colored", "wraps", "val", "in", "color", "styling", "tags", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/ircbee/irctools/irctools.go#L38-L80
train
muesli/beehive
bees/options.go
Value
func (opts BeeOptions) Value(name string) interface{} { for _, opt := range opts { if opt.Name == name { return opt.Value } } return nil }
go
func (opts BeeOptions) Value(name string) interface{} { for _, opt := range opts { if opt.Name == name { return opt.Value } } return nil }
[ "func", "(", "opts", "BeeOptions", ")", "Value", "(", "name", "string", ")", "interface", "{", "}", "{", "for", "_", ",", "opt", ":=", "range", "opts", "{", "if", "opt", ".", "Name", "==", "name", "{", "return", "opt", ".", "Value", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Value retrieves a value from a BeeOptions slice.
[ "Value", "retrieves", "a", "value", "from", "a", "BeeOptions", "slice", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/options.go#L46-L54
train
muesli/beehive
bees/options.go
Bind
func (opts BeeOptions) Bind(name string, dst interface{}) error { v := opts.Value(name) if v == nil { return errors.New("Option with name " + name + " not found") } return ConvertValue(v, dst) }
go
func (opts BeeOptions) Bind(name string, dst interface{}) error { v := opts.Value(name) if v == nil { return errors.New("Option with name " + name + " not found") } return ConvertValue(v, dst) }
[ "func", "(", "opts", "BeeOptions", ")", "Bind", "(", "name", "string", ",", "dst", "interface", "{", "}", ")", "error", "{", "v", ":=", "opts", ".", "Value", "(", "name", ")", "\n", "if", "v", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"Option with name \"", "+", "name", "+", "\" not found\"", ")", "\n", "}", "\n", "return", "ConvertValue", "(", "v", ",", "dst", ")", "\n", "}" ]
// Bind a value from a BeeOptions slice.
[ "Bind", "a", "value", "from", "a", "BeeOptions", "slice", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/options.go#L57-L64
train
muesli/beehive
bees/telegrambee/telegrambee.go
getAPIKey
func getAPIKey(options *bees.BeeOptions) string { var apiKey string options.Bind("api_key", &apiKey) if strings.HasPrefix(apiKey, "file://") { buf, err := ioutil.ReadFile(strings.TrimPrefix(apiKey, "file://")) if err != nil { panic("Error reading API key file " + apiKey) } apiKey = string(buf) } if strings.HasPrefix(apiKey, "env://") { buf := strings.TrimPrefix(apiKey, "env://") apiKey = os.Getenv(string(buf)) } return strings.TrimSpace(apiKey) }
go
func getAPIKey(options *bees.BeeOptions) string { var apiKey string options.Bind("api_key", &apiKey) if strings.HasPrefix(apiKey, "file://") { buf, err := ioutil.ReadFile(strings.TrimPrefix(apiKey, "file://")) if err != nil { panic("Error reading API key file " + apiKey) } apiKey = string(buf) } if strings.HasPrefix(apiKey, "env://") { buf := strings.TrimPrefix(apiKey, "env://") apiKey = os.Getenv(string(buf)) } return strings.TrimSpace(apiKey) }
[ "func", "getAPIKey", "(", "options", "*", "bees", ".", "BeeOptions", ")", "string", "{", "var", "apiKey", "string", "\n", "options", ".", "Bind", "(", "\"api_key\"", ",", "&", "apiKey", ")", "\n", "if", "strings", ".", "HasPrefix", "(", "apiKey", ",", "\"file://\"", ")", "{", "buf", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "strings", ".", "TrimPrefix", "(", "apiKey", ",", "\"file://\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "\"Error reading API key file \"", "+", "apiKey", ")", "\n", "}", "\n", "apiKey", "=", "string", "(", "buf", ")", "\n", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "apiKey", ",", "\"env://\"", ")", "{", "buf", ":=", "strings", ".", "TrimPrefix", "(", "apiKey", ",", "\"env://\"", ")", "\n", "apiKey", "=", "os", ".", "Getenv", "(", "string", "(", "buf", ")", ")", "\n", "}", "\n", "return", "strings", ".", "TrimSpace", "(", "apiKey", ")", "\n", "}" ]
// Gets the Bot's API key from a file, the recipe config or the // TELEGRAM_API_KEY environment variable.
[ "Gets", "the", "Bot", "s", "API", "key", "from", "a", "file", "the", "recipe", "config", "or", "the", "TELEGRAM_API_KEY", "environment", "variable", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/telegrambee/telegrambee.go#L136-L154
train
muesli/beehive
bees/config.go
NewBeeConfig
func NewBeeConfig(name, class, description string, options BeeOptions) (BeeConfig, error) { if len(name) == 0 { return BeeConfig{}, errors.New("A Bee's name can't be empty") } b := GetBee(name) if b != nil { return BeeConfig{}, errors.New("A Bee with that name already exists") } f := GetFactory(class) if f == nil { return BeeConfig{}, errors.New("Invalid class specified") } return BeeConfig{ Name: name, Class: class, Description: description, Options: options, }, nil }
go
func NewBeeConfig(name, class, description string, options BeeOptions) (BeeConfig, error) { if len(name) == 0 { return BeeConfig{}, errors.New("A Bee's name can't be empty") } b := GetBee(name) if b != nil { return BeeConfig{}, errors.New("A Bee with that name already exists") } f := GetFactory(class) if f == nil { return BeeConfig{}, errors.New("Invalid class specified") } return BeeConfig{ Name: name, Class: class, Description: description, Options: options, }, nil }
[ "func", "NewBeeConfig", "(", "name", ",", "class", ",", "description", "string", ",", "options", "BeeOptions", ")", "(", "BeeConfig", ",", "error", ")", "{", "if", "len", "(", "name", ")", "==", "0", "{", "return", "BeeConfig", "{", "}", ",", "errors", ".", "New", "(", "\"A Bee's name can't be empty\"", ")", "\n", "}", "\n", "b", ":=", "GetBee", "(", "name", ")", "\n", "if", "b", "!=", "nil", "{", "return", "BeeConfig", "{", "}", ",", "errors", ".", "New", "(", "\"A Bee with that name already exists\"", ")", "\n", "}", "\n", "f", ":=", "GetFactory", "(", "class", ")", "\n", "if", "f", "==", "nil", "{", "return", "BeeConfig", "{", "}", ",", "errors", ".", "New", "(", "\"Invalid class specified\"", ")", "\n", "}", "\n", "return", "BeeConfig", "{", "Name", ":", "name", ",", "Class", ":", "class", ",", "Description", ":", "description", ",", "Options", ":", "options", ",", "}", ",", "nil", "\n", "}" ]
// NewBeeConfig validates a configuration and sets up a new BeeConfig
[ "NewBeeConfig", "validates", "a", "configuration", "and", "sets", "up", "a", "new", "BeeConfig" ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/config.go#L35-L56
train
muesli/beehive
bees/config.go
BeeConfigs
func BeeConfigs() []BeeConfig { bs := []BeeConfig{} for _, b := range bees { bs = append(bs, (*b).Config()) } return bs }
go
func BeeConfigs() []BeeConfig { bs := []BeeConfig{} for _, b := range bees { bs = append(bs, (*b).Config()) } return bs }
[ "func", "BeeConfigs", "(", ")", "[", "]", "BeeConfig", "{", "bs", ":=", "[", "]", "BeeConfig", "{", "}", "\n", "for", "_", ",", "b", ":=", "range", "bees", "{", "bs", "=", "append", "(", "bs", ",", "(", "*", "b", ")", ".", "Config", "(", ")", ")", "\n", "}", "\n", "return", "bs", "\n", "}" ]
// BeeConfigs returns configs for all Bees.
[ "BeeConfigs", "returns", "configs", "for", "all", "Bees", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/config.go#L59-L66
train
muesli/beehive
bees/filters.go
execFilter
func execFilter(filter string, opts map[string]interface{}) bool { f := *filters.GetFilter("template") log.Println("\tExecuting filter:", filter) defer func() { if e := recover(); e != nil { log.Println("Fatal filter event:", e) } }() return f.Passes(opts, filter) }
go
func execFilter(filter string, opts map[string]interface{}) bool { f := *filters.GetFilter("template") log.Println("\tExecuting filter:", filter) defer func() { if e := recover(); e != nil { log.Println("Fatal filter event:", e) } }() return f.Passes(opts, filter) }
[ "func", "execFilter", "(", "filter", "string", ",", "opts", "map", "[", "string", "]", "interface", "{", "}", ")", "bool", "{", "f", ":=", "*", "filters", ".", "GetFilter", "(", "\"template\"", ")", "\n", "log", ".", "Println", "(", "\"\\tExecuting filter:\"", ",", "\\t", ")", "\n", "filter", "\n", "defer", "func", "(", ")", "{", "if", "e", ":=", "recover", "(", ")", ";", "e", "!=", "nil", "{", "log", ".", "Println", "(", "\"Fatal filter event:\"", ",", "e", ")", "\n", "}", "\n", "}", "(", ")", "\n", "}" ]
// execFilter executes a filter. Returns whether the filter passed or not.
[ "execFilter", "executes", "a", "filter", ".", "Returns", "whether", "the", "filter", "passed", "or", "not", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/filters.go#L38-L49
train
muesli/beehive
bees/openweathermapbee/event.go
TriggerWeatherInformationEvent
func (mod *OpenweathermapBee) TriggerWeatherInformationEvent(v *owm.Weather) { weather := bees.Event{ Bee: mod.Name(), Name: "main_weather", Options: []bees.Placeholder{ { Name: "id", Type: "int", Value: v.ID, }, { Name: "main", Type: "string", Value: v.Main, }, { Name: "description", Type: "string", Value: v.Description, }, { Name: "icon", Type: "string", Value: v.Icon, }, }, } mod.evchan <- weather }
go
func (mod *OpenweathermapBee) TriggerWeatherInformationEvent(v *owm.Weather) { weather := bees.Event{ Bee: mod.Name(), Name: "main_weather", Options: []bees.Placeholder{ { Name: "id", Type: "int", Value: v.ID, }, { Name: "main", Type: "string", Value: v.Main, }, { Name: "description", Type: "string", Value: v.Description, }, { Name: "icon", Type: "string", Value: v.Icon, }, }, } mod.evchan <- weather }
[ "func", "(", "mod", "*", "OpenweathermapBee", ")", "TriggerWeatherInformationEvent", "(", "v", "*", "owm", ".", "Weather", ")", "{", "weather", ":=", "bees", ".", "Event", "{", "Bee", ":", "mod", ".", "Name", "(", ")", ",", "Name", ":", "\"main_weather\"", ",", "Options", ":", "[", "]", "bees", ".", "Placeholder", "{", "{", "Name", ":", "\"id\"", ",", "Type", ":", "\"int\"", ",", "Value", ":", "v", ".", "ID", ",", "}", ",", "{", "Name", ":", "\"main\"", ",", "Type", ":", "\"string\"", ",", "Value", ":", "v", ".", "Main", ",", "}", ",", "{", "Name", ":", "\"description\"", ",", "Type", ":", "\"string\"", ",", "Value", ":", "v", ".", "Description", ",", "}", ",", "{", "Name", ":", "\"icon\"", ",", "Type", ":", "\"string\"", ",", "Value", ":", "v", ".", "Icon", ",", "}", ",", "}", ",", "}", "\n", "mod", ".", "evchan", "<-", "weather", "\n", "}" ]
// WeatherInformationEvent triggers a weather event
[ "WeatherInformationEvent", "triggers", "a", "weather", "event" ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/openweathermapbee/event.go#L186-L214
train
muesli/beehive
filters/template/templatefilter.go
Passes
func (filter *TemplateFilter) Passes(data interface{}, value interface{}) bool { switch v := value.(type) { case string: var res bytes.Buffer if strings.Index(v, "{{test") >= 0 { v = strings.Replace(v, "{{test", "{{if", -1) v += "true{{end}}" } tmpl, err := template.New("_" + v).Funcs(templatehelper.FuncMap).Parse(v) if err == nil { err = tmpl.Execute(&res, data) } if err != nil { panic(err) } return strings.TrimSpace(res.String()) == "true" } return false }
go
func (filter *TemplateFilter) Passes(data interface{}, value interface{}) bool { switch v := value.(type) { case string: var res bytes.Buffer if strings.Index(v, "{{test") >= 0 { v = strings.Replace(v, "{{test", "{{if", -1) v += "true{{end}}" } tmpl, err := template.New("_" + v).Funcs(templatehelper.FuncMap).Parse(v) if err == nil { err = tmpl.Execute(&res, data) } if err != nil { panic(err) } return strings.TrimSpace(res.String()) == "true" } return false }
[ "func", "(", "filter", "*", "TemplateFilter", ")", "Passes", "(", "data", "interface", "{", "}", ",", "value", "interface", "{", "}", ")", "bool", "{", "switch", "v", ":=", "value", ".", "(", "type", ")", "{", "case", "string", ":", "var", "res", "bytes", ".", "Buffer", "\n", "if", "strings", ".", "Index", "(", "v", ",", "\"{{test\"", ")", ">=", "0", "{", "v", "=", "strings", ".", "Replace", "(", "v", ",", "\"{{test\"", ",", "\"{{if\"", ",", "-", "1", ")", "\n", "v", "+=", "\"true{{end}}\"", "\n", "}", "\n", "tmpl", ",", "err", ":=", "template", ".", "New", "(", "\"_\"", "+", "v", ")", ".", "Funcs", "(", "templatehelper", ".", "FuncMap", ")", ".", "Parse", "(", "v", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "tmpl", ".", "Execute", "(", "&", "res", ",", "data", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "strings", ".", "TrimSpace", "(", "res", ".", "String", "(", ")", ")", "==", "\"true\"", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Passes returns true when the Filter matched the data.
[ "Passes", "returns", "true", "when", "the", "Filter", "matched", "the", "data", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/filters/template/templatefilter.go#L48-L70
train
muesli/beehive
api/resources/hives/hives_response.go
AddHive
func (r *HiveResponse) AddHive(hive *bees.BeeFactoryInterface) { r.hives[(*hive).Name()] = hive }
go
func (r *HiveResponse) AddHive(hive *bees.BeeFactoryInterface) { r.hives[(*hive).Name()] = hive }
[ "func", "(", "r", "*", "HiveResponse", ")", "AddHive", "(", "hive", "*", "bees", ".", "BeeFactoryInterface", ")", "{", "r", ".", "hives", "[", "(", "*", "hive", ")", ".", "Name", "(", ")", "]", "=", "hive", "\n", "}" ]
// AddHive adds a hive to the response
[ "AddHive", "adds", "a", "hive", "to", "the", "response" ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/api/resources/hives/hives_response.go#L64-L66
train
muesli/beehive
api/resources/bees/bees_response.go
AddBee
func (r *BeeResponse) AddBee(bee *bees.BeeInterface) { r.bees[(*bee).Name()] = bee hive := bees.GetFactory((*bee).Namespace()) if hive == nil { panic("Hive for Bee not found") } r.hives[(*hive).Name()] = hive r.Hives = append(r.Hives, hives.PrepareHiveResponse(r.Context, hive)) }
go
func (r *BeeResponse) AddBee(bee *bees.BeeInterface) { r.bees[(*bee).Name()] = bee hive := bees.GetFactory((*bee).Namespace()) if hive == nil { panic("Hive for Bee not found") } r.hives[(*hive).Name()] = hive r.Hives = append(r.Hives, hives.PrepareHiveResponse(r.Context, hive)) }
[ "func", "(", "r", "*", "BeeResponse", ")", "AddBee", "(", "bee", "*", "bees", ".", "BeeInterface", ")", "{", "r", ".", "bees", "[", "(", "*", "bee", ")", ".", "Name", "(", ")", "]", "=", "bee", "\n", "hive", ":=", "bees", ".", "GetFactory", "(", "(", "*", "bee", ")", ".", "Namespace", "(", ")", ")", "\n", "if", "hive", "==", "nil", "{", "panic", "(", "\"Hive for Bee not found\"", ")", "\n", "}", "\n", "r", ".", "hives", "[", "(", "*", "hive", ")", ".", "Name", "(", ")", "]", "=", "hive", "\n", "r", ".", "Hives", "=", "append", "(", "r", ".", "Hives", ",", "hives", ".", "PrepareHiveResponse", "(", "r", ".", "Context", ",", "hive", ")", ")", "\n", "}" ]
// AddBee adds a bee to the response
[ "AddBee", "adds", "a", "bee", "to", "the", "response" ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/api/resources/bees/bees_response.go#L66-L76
train
muesli/beehive
api/api.go
Run
func Run() { // to see what happens in the package, uncomment the following //restful.TraceLogger(log.New(os.Stdout, "[restful] ", log.LstdFlags|log.Lshortfile)) // Setup web-service smolderConfig := smolder.APIConfig{ BaseURL: canonicalURL, PathPrefix: "v1/", } context := &context.APIContext{ Config: smolderConfig, } wsContainer := smolder.NewSmolderContainer(smolderConfig, nil, nil) wsContainer.Router(restful.CurlyRouter{}) ws := new(restful.WebService) ws.Route(ws.GET("/images/{subpath:*}").To(assetHandler)) ws.Route(ws.GET("/oauth2/{subpath:*}").To(oauth2Handler)) ws.Route(ws.GET("/{subpath:*}").To(assetHandler)) ws.Route(ws.GET("/").To(assetHandler)) wsContainer.Add(ws) func(resources ...smolder.APIResource) { for _, r := range resources { r.Register(wsContainer, smolderConfig, context) } }( &hives.HiveResource{}, &bees.BeeResource{}, &chains.ChainResource{}, &actions.ActionResource{}, &logs.LogResource{}, ) server := &http.Server{Addr: bind, Handler: wsContainer} go func() { log.Fatal(server.ListenAndServe()) }() }
go
func Run() { // to see what happens in the package, uncomment the following //restful.TraceLogger(log.New(os.Stdout, "[restful] ", log.LstdFlags|log.Lshortfile)) // Setup web-service smolderConfig := smolder.APIConfig{ BaseURL: canonicalURL, PathPrefix: "v1/", } context := &context.APIContext{ Config: smolderConfig, } wsContainer := smolder.NewSmolderContainer(smolderConfig, nil, nil) wsContainer.Router(restful.CurlyRouter{}) ws := new(restful.WebService) ws.Route(ws.GET("/images/{subpath:*}").To(assetHandler)) ws.Route(ws.GET("/oauth2/{subpath:*}").To(oauth2Handler)) ws.Route(ws.GET("/{subpath:*}").To(assetHandler)) ws.Route(ws.GET("/").To(assetHandler)) wsContainer.Add(ws) func(resources ...smolder.APIResource) { for _, r := range resources { r.Register(wsContainer, smolderConfig, context) } }( &hives.HiveResource{}, &bees.BeeResource{}, &chains.ChainResource{}, &actions.ActionResource{}, &logs.LogResource{}, ) server := &http.Server{Addr: bind, Handler: wsContainer} go func() { log.Fatal(server.ListenAndServe()) }() }
[ "func", "Run", "(", ")", "{", "smolderConfig", ":=", "smolder", ".", "APIConfig", "{", "BaseURL", ":", "canonicalURL", ",", "PathPrefix", ":", "\"v1/\"", ",", "}", "\n", "context", ":=", "&", "context", ".", "APIContext", "{", "Config", ":", "smolderConfig", ",", "}", "\n", "wsContainer", ":=", "smolder", ".", "NewSmolderContainer", "(", "smolderConfig", ",", "nil", ",", "nil", ")", "\n", "wsContainer", ".", "Router", "(", "restful", ".", "CurlyRouter", "{", "}", ")", "\n", "ws", ":=", "new", "(", "restful", ".", "WebService", ")", "\n", "ws", ".", "Route", "(", "ws", ".", "GET", "(", "\"/images/{subpath:*}\"", ")", ".", "To", "(", "assetHandler", ")", ")", "\n", "ws", ".", "Route", "(", "ws", ".", "GET", "(", "\"/oauth2/{subpath:*}\"", ")", ".", "To", "(", "oauth2Handler", ")", ")", "\n", "ws", ".", "Route", "(", "ws", ".", "GET", "(", "\"/{subpath:*}\"", ")", ".", "To", "(", "assetHandler", ")", ")", "\n", "ws", ".", "Route", "(", "ws", ".", "GET", "(", "\"/\"", ")", ".", "To", "(", "assetHandler", ")", ")", "\n", "wsContainer", ".", "Add", "(", "ws", ")", "\n", "func", "(", "resources", "...", "smolder", ".", "APIResource", ")", "{", "for", "_", ",", "r", ":=", "range", "resources", "{", "r", ".", "Register", "(", "wsContainer", ",", "smolderConfig", ",", "context", ")", "\n", "}", "\n", "}", "(", "&", "hives", ".", "HiveResource", "{", "}", ",", "&", "bees", ".", "BeeResource", "{", "}", ",", "&", "chains", ".", "ChainResource", "{", "}", ",", "&", "actions", ".", "ActionResource", "{", "}", ",", "&", "logs", ".", "LogResource", "{", "}", ",", ")", "\n", "server", ":=", "&", "http", ".", "Server", "{", "Addr", ":", "bind", ",", "Handler", ":", "wsContainer", "}", "\n", "go", "func", "(", ")", "{", "log", ".", "Fatal", "(", "server", ".", "ListenAndServe", "(", ")", ")", "\n", "}", "(", ")", "\n", "}" ]
// Run sets up the restful API container and an HTTP server go-routine
[ "Run", "sets", "up", "the", "restful", "API", "container", "and", "an", "HTTP", "server", "go", "-", "routine" ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/api/api.go#L164-L202
train
muesli/beehive
bees/cronbee/cron/crontime.go
DurationUntilNextEvent
func (c *crontime) DurationUntilNextEvent() time.Duration { return c.nextEvent().Sub(time.Now()) }
go
func (c *crontime) DurationUntilNextEvent() time.Duration { return c.nextEvent().Sub(time.Now()) }
[ "func", "(", "c", "*", "crontime", ")", "DurationUntilNextEvent", "(", ")", "time", ".", "Duration", "{", "return", "c", ".", "nextEvent", "(", ")", ".", "Sub", "(", "time", ".", "Now", "(", ")", ")", "\n", "}" ]
// Returns the time.Duration until the next event.
[ "Returns", "the", "time", ".", "Duration", "until", "the", "next", "event", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/cronbee/cron/crontime.go#L52-L54
train
muesli/beehive
bees/cronbee/cron/crontime.go
calculateEvent
func (c *crontime) calculateEvent(baseTime time.Time) time.Time { c.calculationInProgress = true defer c.setCalculationInProgress(false) baseTime = setNanoecond(baseTime, 10000) c.calculatedTime = baseTime // Ignore all Events in the Past & initial 'result' //c.calculatedTime = setNanoecond(c.calculatedTime, 10000) c.nextValidMonth(baseTime) c.nextValidDay(baseTime) c.nextValidHour(baseTime) c.nextValidMinute(baseTime) c.nextValidSecond(baseTime) log.Println("Cronbee has found a time stamp: ", c.calculatedTime) return c.calculatedTime }
go
func (c *crontime) calculateEvent(baseTime time.Time) time.Time { c.calculationInProgress = true defer c.setCalculationInProgress(false) baseTime = setNanoecond(baseTime, 10000) c.calculatedTime = baseTime // Ignore all Events in the Past & initial 'result' //c.calculatedTime = setNanoecond(c.calculatedTime, 10000) c.nextValidMonth(baseTime) c.nextValidDay(baseTime) c.nextValidHour(baseTime) c.nextValidMinute(baseTime) c.nextValidSecond(baseTime) log.Println("Cronbee has found a time stamp: ", c.calculatedTime) return c.calculatedTime }
[ "func", "(", "c", "*", "crontime", ")", "calculateEvent", "(", "baseTime", "time", ".", "Time", ")", "time", ".", "Time", "{", "c", ".", "calculationInProgress", "=", "true", "\n", "defer", "c", ".", "setCalculationInProgress", "(", "false", ")", "\n", "baseTime", "=", "setNanoecond", "(", "baseTime", ",", "10000", ")", "\n", "c", ".", "calculatedTime", "=", "baseTime", "\n", "c", ".", "nextValidMonth", "(", "baseTime", ")", "\n", "c", ".", "nextValidDay", "(", "baseTime", ")", "\n", "c", ".", "nextValidHour", "(", "baseTime", ")", "\n", "c", ".", "nextValidMinute", "(", "baseTime", ")", "\n", "c", ".", "nextValidSecond", "(", "baseTime", ")", "\n", "log", ".", "Println", "(", "\"Cronbee has found a time stamp: \"", ",", "c", ".", "calculatedTime", ")", "\n", "return", "c", ".", "calculatedTime", "\n", "}" ]
// This functions calculates the next event
[ "This", "functions", "calculates", "the", "next", "event" ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/cronbee/cron/crontime.go#L93-L106
train
muesli/beehive
bees/cronbee/cron/crontime.go
nextValidMonth
func (c *crontime) nextValidMonth(baseTime time.Time) { for _, mon := range c.month { if mon >= int(c.calculatedTime.Month()) { //log.Print("Inside Month", mon, c.calculatedTime) c.calculatedTime = setMonth(c.calculatedTime, mon) //log.Println(" :: and out", c.calculatedTime) return } } // If no result was found try it again in the following year c.calculatedTime = c.calculatedTime.AddDate(1, 0, 0) c.calculatedTime = setMonth(c.calculatedTime, c.month[0]) //log.Println("Cronbee: Month", c.calculatedTime, baseTime, c.month) c.nextValidMonth(baseTime) }
go
func (c *crontime) nextValidMonth(baseTime time.Time) { for _, mon := range c.month { if mon >= int(c.calculatedTime.Month()) { //log.Print("Inside Month", mon, c.calculatedTime) c.calculatedTime = setMonth(c.calculatedTime, mon) //log.Println(" :: and out", c.calculatedTime) return } } // If no result was found try it again in the following year c.calculatedTime = c.calculatedTime.AddDate(1, 0, 0) c.calculatedTime = setMonth(c.calculatedTime, c.month[0]) //log.Println("Cronbee: Month", c.calculatedTime, baseTime, c.month) c.nextValidMonth(baseTime) }
[ "func", "(", "c", "*", "crontime", ")", "nextValidMonth", "(", "baseTime", "time", ".", "Time", ")", "{", "for", "_", ",", "mon", ":=", "range", "c", ".", "month", "{", "if", "mon", ">=", "int", "(", "c", ".", "calculatedTime", ".", "Month", "(", ")", ")", "{", "c", ".", "calculatedTime", "=", "setMonth", "(", "c", ".", "calculatedTime", ",", "mon", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "c", ".", "calculatedTime", "=", "c", ".", "calculatedTime", ".", "AddDate", "(", "1", ",", "0", ",", "0", ")", "\n", "c", ".", "calculatedTime", "=", "setMonth", "(", "c", ".", "calculatedTime", ",", "c", ".", "month", "[", "0", "]", ")", "\n", "c", ".", "nextValidMonth", "(", "baseTime", ")", "\n", "}" ]
// Calculates the next valid Month based upon the previous results.
[ "Calculates", "the", "next", "valid", "Month", "based", "upon", "the", "previous", "results", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/cronbee/cron/crontime.go#L109-L123
train
muesli/beehive
bees/cronbee/cron/crontime.go
nextValidDay
func (c *crontime) nextValidDay(baseTime time.Time) { for _, dom := range c.dom { if dom >= c.calculatedTime.Day() { for _, dow := range c.dow { if monthHasDow(dow, dom, int(c.calculatedTime.Month()), c.calculatedTime.Year()) { c.calculatedTime = setDay(c.calculatedTime, dom) //log.Println("Cronbee: Day-INS-1:", c.calculatedTime) return } } } } /* else { for _, dow := range c.dow { if monthHasDow(dow, dom, int(c.calculatedTime.Month()), c.calculatedTime.Year()){ c.calculatedTime = setDay(c.calculatedTime, dom) log.Println("Cronbee: Day-INS-2:", c.calculatedTime) return } } }*/ // If no result was found try it again in the following month. c.calculatedTime = c.calculatedTime.AddDate(0, 1, 0) c.calculatedTime = setDay(c.calculatedTime, c.dom[0]) //log.Println("Cronbee: Day", c.calculatedTime, baseTime) c.nextValidMonth(baseTime) c.nextValidDay(baseTime) }
go
func (c *crontime) nextValidDay(baseTime time.Time) { for _, dom := range c.dom { if dom >= c.calculatedTime.Day() { for _, dow := range c.dow { if monthHasDow(dow, dom, int(c.calculatedTime.Month()), c.calculatedTime.Year()) { c.calculatedTime = setDay(c.calculatedTime, dom) //log.Println("Cronbee: Day-INS-1:", c.calculatedTime) return } } } } /* else { for _, dow := range c.dow { if monthHasDow(dow, dom, int(c.calculatedTime.Month()), c.calculatedTime.Year()){ c.calculatedTime = setDay(c.calculatedTime, dom) log.Println("Cronbee: Day-INS-2:", c.calculatedTime) return } } }*/ // If no result was found try it again in the following month. c.calculatedTime = c.calculatedTime.AddDate(0, 1, 0) c.calculatedTime = setDay(c.calculatedTime, c.dom[0]) //log.Println("Cronbee: Day", c.calculatedTime, baseTime) c.nextValidMonth(baseTime) c.nextValidDay(baseTime) }
[ "func", "(", "c", "*", "crontime", ")", "nextValidDay", "(", "baseTime", "time", ".", "Time", ")", "{", "for", "_", ",", "dom", ":=", "range", "c", ".", "dom", "{", "if", "dom", ">=", "c", ".", "calculatedTime", ".", "Day", "(", ")", "{", "for", "_", ",", "dow", ":=", "range", "c", ".", "dow", "{", "if", "monthHasDow", "(", "dow", ",", "dom", ",", "int", "(", "c", ".", "calculatedTime", ".", "Month", "(", ")", ")", ",", "c", ".", "calculatedTime", ".", "Year", "(", ")", ")", "{", "c", ".", "calculatedTime", "=", "setDay", "(", "c", ".", "calculatedTime", ",", "dom", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "c", ".", "calculatedTime", "=", "c", ".", "calculatedTime", ".", "AddDate", "(", "0", ",", "1", ",", "0", ")", "\n", "c", ".", "calculatedTime", "=", "setDay", "(", "c", ".", "calculatedTime", ",", "c", ".", "dom", "[", "0", "]", ")", "\n", "c", ".", "nextValidMonth", "(", "baseTime", ")", "\n", "c", ".", "nextValidDay", "(", "baseTime", ")", "\n", "}" ]
// Calculates the next valid Day based upon the previous results.
[ "Calculates", "the", "next", "valid", "Day", "based", "upon", "the", "previous", "results", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/cronbee/cron/crontime.go#L126-L152
train
muesli/beehive
bees/cronbee/cron/crontime.go
nextValidHour
func (c *crontime) nextValidHour(baseTime time.Time) { for _, hour := range c.hour { if c.calculatedTime.Day() == baseTime.Day() { if !hasPassed(hour, c.calculatedTime.Hour()) { c.calculatedTime = setHour(c.calculatedTime, hour) return } } else { c.calculatedTime = setHour(c.calculatedTime, hour) return } } // If no result was found try it again in the following day. c.calculatedTime = c.calculatedTime.AddDate(0, 0, 1) // <-| c.calculatedTime = setHour(c.calculatedTime, c.hour[0]) // | //log.Println("Cronbee: Hour", c.calculatedTime, baseTime) // | c.nextValidMonth(baseTime) // May trigger a new month --------| c.nextValidDay(baseTime) c.nextValidHour(baseTime) }
go
func (c *crontime) nextValidHour(baseTime time.Time) { for _, hour := range c.hour { if c.calculatedTime.Day() == baseTime.Day() { if !hasPassed(hour, c.calculatedTime.Hour()) { c.calculatedTime = setHour(c.calculatedTime, hour) return } } else { c.calculatedTime = setHour(c.calculatedTime, hour) return } } // If no result was found try it again in the following day. c.calculatedTime = c.calculatedTime.AddDate(0, 0, 1) // <-| c.calculatedTime = setHour(c.calculatedTime, c.hour[0]) // | //log.Println("Cronbee: Hour", c.calculatedTime, baseTime) // | c.nextValidMonth(baseTime) // May trigger a new month --------| c.nextValidDay(baseTime) c.nextValidHour(baseTime) }
[ "func", "(", "c", "*", "crontime", ")", "nextValidHour", "(", "baseTime", "time", ".", "Time", ")", "{", "for", "_", ",", "hour", ":=", "range", "c", ".", "hour", "{", "if", "c", ".", "calculatedTime", ".", "Day", "(", ")", "==", "baseTime", ".", "Day", "(", ")", "{", "if", "!", "hasPassed", "(", "hour", ",", "c", ".", "calculatedTime", ".", "Hour", "(", ")", ")", "{", "c", ".", "calculatedTime", "=", "setHour", "(", "c", ".", "calculatedTime", ",", "hour", ")", "\n", "return", "\n", "}", "\n", "}", "else", "{", "c", ".", "calculatedTime", "=", "setHour", "(", "c", ".", "calculatedTime", ",", "hour", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "c", ".", "calculatedTime", "=", "c", ".", "calculatedTime", ".", "AddDate", "(", "0", ",", "0", ",", "1", ")", "\n", "c", ".", "calculatedTime", "=", "setHour", "(", "c", ".", "calculatedTime", ",", "c", ".", "hour", "[", "0", "]", ")", "\n", "c", ".", "nextValidMonth", "(", "baseTime", ")", "\n", "c", ".", "nextValidDay", "(", "baseTime", ")", "\n", "c", ".", "nextValidHour", "(", "baseTime", ")", "\n", "}" ]
// Calculates the next valid Hour based upon the previous results.
[ "Calculates", "the", "next", "valid", "Hour", "based", "upon", "the", "previous", "results", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/cronbee/cron/crontime.go#L155-L174
train
muesli/beehive
bees/cronbee/cron/crontime.go
nextValidMinute
func (c *crontime) nextValidMinute(baseTime time.Time) { for _, min := range c.minute { if c.calculatedTime.Hour() == baseTime.Hour() { if !hasPassed(min, c.calculatedTime.Minute()) { c.calculatedTime = setMinute(c.calculatedTime, min) return } } else { c.calculatedTime = setMinute(c.calculatedTime, min) return } } c.calculatedTime = c.calculatedTime.Add(1 * time.Hour) c.calculatedTime = setMinute(c.calculatedTime, c.minute[0]) //log.Println("Cronbee: Minute", c.calculatedTime, baseTime) c.nextValidHour(baseTime) c.nextValidMinute(baseTime) }
go
func (c *crontime) nextValidMinute(baseTime time.Time) { for _, min := range c.minute { if c.calculatedTime.Hour() == baseTime.Hour() { if !hasPassed(min, c.calculatedTime.Minute()) { c.calculatedTime = setMinute(c.calculatedTime, min) return } } else { c.calculatedTime = setMinute(c.calculatedTime, min) return } } c.calculatedTime = c.calculatedTime.Add(1 * time.Hour) c.calculatedTime = setMinute(c.calculatedTime, c.minute[0]) //log.Println("Cronbee: Minute", c.calculatedTime, baseTime) c.nextValidHour(baseTime) c.nextValidMinute(baseTime) }
[ "func", "(", "c", "*", "crontime", ")", "nextValidMinute", "(", "baseTime", "time", ".", "Time", ")", "{", "for", "_", ",", "min", ":=", "range", "c", ".", "minute", "{", "if", "c", ".", "calculatedTime", ".", "Hour", "(", ")", "==", "baseTime", ".", "Hour", "(", ")", "{", "if", "!", "hasPassed", "(", "min", ",", "c", ".", "calculatedTime", ".", "Minute", "(", ")", ")", "{", "c", ".", "calculatedTime", "=", "setMinute", "(", "c", ".", "calculatedTime", ",", "min", ")", "\n", "return", "\n", "}", "\n", "}", "else", "{", "c", ".", "calculatedTime", "=", "setMinute", "(", "c", ".", "calculatedTime", ",", "min", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "c", ".", "calculatedTime", "=", "c", ".", "calculatedTime", ".", "Add", "(", "1", "*", "time", ".", "Hour", ")", "\n", "c", ".", "calculatedTime", "=", "setMinute", "(", "c", ".", "calculatedTime", ",", "c", ".", "minute", "[", "0", "]", ")", "\n", "c", ".", "nextValidHour", "(", "baseTime", ")", "\n", "c", ".", "nextValidMinute", "(", "baseTime", ")", "\n", "}" ]
// Calculates the next valid Minute based upon the previous results.
[ "Calculates", "the", "next", "valid", "Minute", "based", "upon", "the", "previous", "results", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/cronbee/cron/crontime.go#L177-L194
train
muesli/beehive
bees/cronbee/cron/crontime.go
nextValidSecond
func (c *crontime) nextValidSecond(baseTime time.Time) { for _, sec := range c.second { if !c.minuteHasPassed(baseTime) { // check if sec is in the past. <= prevents triggering the same event twice if sec > c.calculatedTime.Second() { c.calculatedTime = setSecond(c.calculatedTime, sec) return } } else { c.calculatedTime = setSecond(c.calculatedTime, sec) return } } c.calculatedTime = c.calculatedTime.Add(1 * time.Minute) c.calculatedTime = setSecond(c.calculatedTime, 0) //log.Println("Cronbee: Second", c.calculatedTime, baseTime) c.nextValidMinute(baseTime) c.nextValidSecond(baseTime) }
go
func (c *crontime) nextValidSecond(baseTime time.Time) { for _, sec := range c.second { if !c.minuteHasPassed(baseTime) { // check if sec is in the past. <= prevents triggering the same event twice if sec > c.calculatedTime.Second() { c.calculatedTime = setSecond(c.calculatedTime, sec) return } } else { c.calculatedTime = setSecond(c.calculatedTime, sec) return } } c.calculatedTime = c.calculatedTime.Add(1 * time.Minute) c.calculatedTime = setSecond(c.calculatedTime, 0) //log.Println("Cronbee: Second", c.calculatedTime, baseTime) c.nextValidMinute(baseTime) c.nextValidSecond(baseTime) }
[ "func", "(", "c", "*", "crontime", ")", "nextValidSecond", "(", "baseTime", "time", ".", "Time", ")", "{", "for", "_", ",", "sec", ":=", "range", "c", ".", "second", "{", "if", "!", "c", ".", "minuteHasPassed", "(", "baseTime", ")", "{", "if", "sec", ">", "c", ".", "calculatedTime", ".", "Second", "(", ")", "{", "c", ".", "calculatedTime", "=", "setSecond", "(", "c", ".", "calculatedTime", ",", "sec", ")", "\n", "return", "\n", "}", "\n", "}", "else", "{", "c", ".", "calculatedTime", "=", "setSecond", "(", "c", ".", "calculatedTime", ",", "sec", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "c", ".", "calculatedTime", "=", "c", ".", "calculatedTime", ".", "Add", "(", "1", "*", "time", ".", "Minute", ")", "\n", "c", ".", "calculatedTime", "=", "setSecond", "(", "c", ".", "calculatedTime", ",", "0", ")", "\n", "c", ".", "nextValidMinute", "(", "baseTime", ")", "\n", "c", ".", "nextValidSecond", "(", "baseTime", ")", "\n", "}" ]
// Calculates the next valid Second based upon the previous results.
[ "Calculates", "the", "next", "valid", "Second", "based", "upon", "the", "previous", "results", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/cronbee/cron/crontime.go#L197-L215
train
muesli/beehive
bees/factories.go
GetFactory
func GetFactory(identifier string) *BeeFactoryInterface { factory, ok := factories[identifier] if ok { return factory } return nil }
go
func GetFactory(identifier string) *BeeFactoryInterface { factory, ok := factories[identifier] if ok { return factory } return nil }
[ "func", "GetFactory", "(", "identifier", "string", ")", "*", "BeeFactoryInterface", "{", "factory", ",", "ok", ":=", "factories", "[", "identifier", "]", "\n", "if", "ok", "{", "return", "factory", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetFactory returns the factory with a specific name.
[ "GetFactory", "returns", "the", "factory", "with", "a", "specific", "name", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/factories.go#L118-L125
train
muesli/beehive
bees/factories.go
GetFactories
func GetFactories() []*BeeFactoryInterface { r := []*BeeFactoryInterface{} for _, factory := range factories { r = append(r, factory) } return r }
go
func GetFactories() []*BeeFactoryInterface { r := []*BeeFactoryInterface{} for _, factory := range factories { r = append(r, factory) } return r }
[ "func", "GetFactories", "(", ")", "[", "]", "*", "BeeFactoryInterface", "{", "r", ":=", "[", "]", "*", "BeeFactoryInterface", "{", "}", "\n", "for", "_", ",", "factory", ":=", "range", "factories", "{", "r", "=", "append", "(", "r", ",", "factory", ")", "\n", "}", "\n", "return", "r", "\n", "}" ]
// GetFactories returns all known bee factories.
[ "GetFactories", "returns", "all", "known", "bee", "factories", "." ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/factories.go#L128-L135
train
muesli/beehive
bees/chains.go
GetChain
func GetChain(id string) *Chain { for _, c := range chains { if c.Name == id { return &c } } return nil }
go
func GetChain(id string) *Chain { for _, c := range chains { if c.Name == id { return &c } } return nil }
[ "func", "GetChain", "(", "id", "string", ")", "*", "Chain", "{", "for", "_", ",", "c", ":=", "range", "chains", "{", "if", "c", ".", "Name", "==", "id", "{", "return", "&", "c", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetChain returns a chain with a specific id
[ "GetChain", "returns", "a", "chain", "with", "a", "specific", "id" ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/chains.go#L52-L60
train
muesli/beehive
bees/chains.go
SetChains
func SetChains(cs []Chain) { newcs := []Chain{} // migrate old chain style for _, c := range cs { for _, el := range c.Elements { if el.Action.Name != "" { el.Action.ID = UUID() c.Actions = append(c.Actions, el.Action.ID) actions = append(actions, el.Action) } if el.Filter.Name != "" { //FIXME: migrate old style filters c.Filters = append(c.Filters, el.Filter.Options.Value.(string)) } } c.Elements = []ChainElement{} newcs = append(newcs, c) } chains = newcs }
go
func SetChains(cs []Chain) { newcs := []Chain{} // migrate old chain style for _, c := range cs { for _, el := range c.Elements { if el.Action.Name != "" { el.Action.ID = UUID() c.Actions = append(c.Actions, el.Action.ID) actions = append(actions, el.Action) } if el.Filter.Name != "" { //FIXME: migrate old style filters c.Filters = append(c.Filters, el.Filter.Options.Value.(string)) } } c.Elements = []ChainElement{} newcs = append(newcs, c) } chains = newcs }
[ "func", "SetChains", "(", "cs", "[", "]", "Chain", ")", "{", "newcs", ":=", "[", "]", "Chain", "{", "}", "\n", "for", "_", ",", "c", ":=", "range", "cs", "{", "for", "_", ",", "el", ":=", "range", "c", ".", "Elements", "{", "if", "el", ".", "Action", ".", "Name", "!=", "\"\"", "{", "el", ".", "Action", ".", "ID", "=", "UUID", "(", ")", "\n", "c", ".", "Actions", "=", "append", "(", "c", ".", "Actions", ",", "el", ".", "Action", ".", "ID", ")", "\n", "actions", "=", "append", "(", "actions", ",", "el", ".", "Action", ")", "\n", "}", "\n", "if", "el", ".", "Filter", ".", "Name", "!=", "\"\"", "{", "c", ".", "Filters", "=", "append", "(", "c", ".", "Filters", ",", "el", ".", "Filter", ".", "Options", ".", "Value", ".", "(", "string", ")", ")", "\n", "}", "\n", "}", "\n", "c", ".", "Elements", "=", "[", "]", "ChainElement", "{", "}", "\n", "newcs", "=", "append", "(", "newcs", ",", "c", ")", "\n", "}", "\n", "chains", "=", "newcs", "\n", "}" ]
// SetChains sets the currently configured chains
[ "SetChains", "sets", "the", "currently", "configured", "chains" ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/chains.go#L63-L84
train
muesli/beehive
bees/chains.go
execChains
func execChains(event *Event) { for _, c := range chains { if c.Event.Name != event.Name || c.Event.Bee != event.Bee { continue } m := make(map[string]interface{}) for _, opt := range event.Options { m[opt.Name] = opt.Value } ctx.FillMap(m) failed := false log.Println("Executing chain:", c.Name, "-", c.Description) for _, el := range c.Filters { if execFilter(el, m) { log.Println("\t\tPassed filter!") } else { log.Println("\t\tDid not pass filter!") failed = true break } } if failed { continue } for _, el := range c.Actions { action := GetAction(el) if action == nil { log.Println("\t\tERROR: Unknown action referenced!") continue } execAction(*action, m) } } }
go
func execChains(event *Event) { for _, c := range chains { if c.Event.Name != event.Name || c.Event.Bee != event.Bee { continue } m := make(map[string]interface{}) for _, opt := range event.Options { m[opt.Name] = opt.Value } ctx.FillMap(m) failed := false log.Println("Executing chain:", c.Name, "-", c.Description) for _, el := range c.Filters { if execFilter(el, m) { log.Println("\t\tPassed filter!") } else { log.Println("\t\tDid not pass filter!") failed = true break } } if failed { continue } for _, el := range c.Actions { action := GetAction(el) if action == nil { log.Println("\t\tERROR: Unknown action referenced!") continue } execAction(*action, m) } } }
[ "func", "execChains", "(", "event", "*", "Event", ")", "{", "for", "_", ",", "c", ":=", "range", "chains", "{", "if", "c", ".", "Event", ".", "Name", "!=", "event", ".", "Name", "||", "c", ".", "Event", ".", "Bee", "!=", "event", ".", "Bee", "{", "continue", "\n", "}", "\n", "m", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "for", "_", ",", "opt", ":=", "range", "event", ".", "Options", "{", "m", "[", "opt", ".", "Name", "]", "=", "opt", ".", "Value", "\n", "}", "\n", "ctx", ".", "FillMap", "(", "m", ")", "\n", "failed", ":=", "false", "\n", "log", ".", "Println", "(", "\"Executing chain:\"", ",", "c", ".", "Name", ",", "\"-\"", ",", "c", ".", "Description", ")", "\n", "for", "_", ",", "el", ":=", "range", "c", ".", "Filters", "{", "if", "execFilter", "(", "el", ",", "m", ")", "{", "log", ".", "Println", "(", "\"\\t\\tPassed filter!\"", ")", "\n", "}", "else", "\\t", "\n", "}", "\n", "\\t", "\n", "{", "log", ".", "Println", "(", "\"\\t\\tDid not pass filter!\"", ")", "\n", "\\t", "\n", "\\t", "\n", "}", "\n", "}", "\n", "}" ]
// execChains executes chains for an event we received
[ "execChains", "executes", "chains", "for", "an", "event", "we", "received" ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/chains.go#L87-L123
train
muesli/beehive
app/app.go
AddFlags
func AddFlags(flags []CliFlag) { for _, flag := range flags { appflags = append(appflags, flag) } }
go
func AddFlags(flags []CliFlag) { for _, flag := range flags { appflags = append(appflags, flag) } }
[ "func", "AddFlags", "(", "flags", "[", "]", "CliFlag", ")", "{", "for", "_", ",", "flag", ":=", "range", "flags", "{", "appflags", "=", "append", "(", "appflags", ",", "flag", ")", "\n", "}", "\n", "}" ]
// AddFlags adds CliFlags to appflags
[ "AddFlags", "adds", "CliFlags", "to", "appflags" ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/app/app.go#L42-L46
train
muesli/beehive
app/app.go
Run
func Run() { for _, f := range appflags { switch f.Value.(type) { case string: flag.StringVar((f.V).(*string), f.Name, f.Value.(string), f.Desc) case bool: flag.BoolVar((f.V).(*bool), f.Name, f.Value.(bool), f.Desc) } } flag.Parse() }
go
func Run() { for _, f := range appflags { switch f.Value.(type) { case string: flag.StringVar((f.V).(*string), f.Name, f.Value.(string), f.Desc) case bool: flag.BoolVar((f.V).(*bool), f.Name, f.Value.(bool), f.Desc) } } flag.Parse() }
[ "func", "Run", "(", ")", "{", "for", "_", ",", "f", ":=", "range", "appflags", "{", "switch", "f", ".", "Value", ".", "(", "type", ")", "{", "case", "string", ":", "flag", ".", "StringVar", "(", "(", "f", ".", "V", ")", ".", "(", "*", "string", ")", ",", "f", ".", "Name", ",", "f", ".", "Value", ".", "(", "string", ")", ",", "f", ".", "Desc", ")", "\n", "case", "bool", ":", "flag", ".", "BoolVar", "(", "(", "f", ".", "V", ")", ".", "(", "*", "bool", ")", ",", "f", ".", "Name", ",", "f", ".", "Value", ".", "(", "bool", ")", ",", "f", ".", "Desc", ")", "\n", "}", "\n", "}", "\n", "flag", ".", "Parse", "(", ")", "\n", "}" ]
// Run sets up all the cli-param mappings
[ "Run", "sets", "up", "all", "the", "cli", "-", "param", "mappings" ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/app/app.go#L49-L60
train
muesli/beehive
beehive.go
loadConfig
func loadConfig() Config { config := Config{} j, err := ioutil.ReadFile(configFile) if err == nil { err = json.Unmarshal(j, &config) if err != nil { log.Fatal("Error parsing config file: ", err) } } return config }
go
func loadConfig() Config { config := Config{} j, err := ioutil.ReadFile(configFile) if err == nil { err = json.Unmarshal(j, &config) if err != nil { log.Fatal("Error parsing config file: ", err) } } return config }
[ "func", "loadConfig", "(", ")", "Config", "{", "config", ":=", "Config", "{", "}", "\n", "j", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "configFile", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "json", ".", "Unmarshal", "(", "j", ",", "&", "config", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "\"Error parsing config file: \"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "config", "\n", "}" ]
// Loads chains from config
[ "Loads", "chains", "from", "config" ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/beehive.go#L58-L70
train
muesli/beehive
beehive.go
saveConfig
func saveConfig(c Config) { j, err := json.MarshalIndent(c, "", " ") if err == nil { err = ioutil.WriteFile(configFile, j, 0644) } if err != nil { log.Fatal(err) } }
go
func saveConfig(c Config) { j, err := json.MarshalIndent(c, "", " ") if err == nil { err = ioutil.WriteFile(configFile, j, 0644) } if err != nil { log.Fatal(err) } }
[ "func", "saveConfig", "(", "c", "Config", ")", "{", "j", ",", "err", ":=", "json", ".", "MarshalIndent", "(", "c", ",", "\"\"", ",", "\" \"", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "ioutil", ".", "WriteFile", "(", "configFile", ",", "j", ",", "0644", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "}" ]
// Saves chains to config
[ "Saves", "chains", "to", "config" ]
4bfd4852e0b4bdcbc711323775cc7144ccd81b7e
https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/beehive.go#L73-L82
train
stretchr/testify
mock/mock.go
Maybe
func (c *Call) Maybe() *Call { c.lock() defer c.unlock() c.optional = true return c }
go
func (c *Call) Maybe() *Call { c.lock() defer c.unlock() c.optional = true return c }
[ "func", "(", "c", "*", "Call", ")", "Maybe", "(", ")", "*", "Call", "{", "c", ".", "lock", "(", ")", "\n", "defer", "c", ".", "unlock", "(", ")", "\n", "c", ".", "optional", "=", "true", "\n", "return", "c", "\n", "}" ]
// Maybe allows the method call to be optional. Not calling an optional method // will not cause an error while asserting expectations
[ "Maybe", "allows", "the", "method", "call", "to", "be", "optional", ".", "Not", "calling", "an", "optional", "method", "will", "not", "cause", "an", "error", "while", "asserting", "expectations" ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/mock/mock.go#L166-L171
train
stretchr/testify
mock/mock.go
fail
func (m *Mock) fail(format string, args ...interface{}) { m.mutex.Lock() defer m.mutex.Unlock() if m.test == nil { panic(fmt.Sprintf(format, args...)) } m.test.Errorf(format, args...) m.test.FailNow() }
go
func (m *Mock) fail(format string, args ...interface{}) { m.mutex.Lock() defer m.mutex.Unlock() if m.test == nil { panic(fmt.Sprintf(format, args...)) } m.test.Errorf(format, args...) m.test.FailNow() }
[ "func", "(", "m", "*", "Mock", ")", "fail", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "m", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mutex", ".", "Unlock", "(", ")", "\n", "if", "m", ".", "test", "==", "nil", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "format", ",", "args", "...", ")", ")", "\n", "}", "\n", "m", ".", "test", ".", "Errorf", "(", "format", ",", "args", "...", ")", "\n", "m", ".", "test", ".", "FailNow", "(", ")", "\n", "}" ]
// fail fails the current test with the given formatted format and args. // In case that a test was defined, it uses the test APIs for failing a test, // otherwise it uses panic.
[ "fail", "fails", "the", "current", "test", "with", "the", "given", "formatted", "format", "and", "args", ".", "In", "case", "that", "a", "test", "was", "defined", "it", "uses", "the", "test", "APIs", "for", "failing", "a", "test", "otherwise", "it", "uses", "panic", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/mock/mock.go#L231-L240
train
stretchr/testify
mock/mock.go
AssertExpectationsForObjects
func AssertExpectationsForObjects(t TestingT, testObjects ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } for _, obj := range testObjects { if m, ok := obj.(Mock); ok { t.Logf("Deprecated mock.AssertExpectationsForObjects(myMock.Mock) use mock.AssertExpectationsForObjects(myMock)") obj = &m } m := obj.(assertExpectationser) if !m.AssertExpectations(t) { t.Logf("Expectations didn't match for Mock: %+v", reflect.TypeOf(m)) return false } } return true }
go
func AssertExpectationsForObjects(t TestingT, testObjects ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } for _, obj := range testObjects { if m, ok := obj.(Mock); ok { t.Logf("Deprecated mock.AssertExpectationsForObjects(myMock.Mock) use mock.AssertExpectationsForObjects(myMock)") obj = &m } m := obj.(assertExpectationser) if !m.AssertExpectations(t) { t.Logf("Expectations didn't match for Mock: %+v", reflect.TypeOf(m)) return false } } return true }
[ "func", "AssertExpectationsForObjects", "(", "t", "TestingT", ",", "testObjects", "...", "interface", "{", "}", ")", "bool", "{", "if", "h", ",", "ok", ":=", "t", ".", "(", "tHelper", ")", ";", "ok", "{", "h", ".", "Helper", "(", ")", "\n", "}", "\n", "for", "_", ",", "obj", ":=", "range", "testObjects", "{", "if", "m", ",", "ok", ":=", "obj", ".", "(", "Mock", ")", ";", "ok", "{", "t", ".", "Logf", "(", "\"Deprecated mock.AssertExpectationsForObjects(myMock.Mock) use mock.AssertExpectationsForObjects(myMock)\"", ")", "\n", "obj", "=", "&", "m", "\n", "}", "\n", "m", ":=", "obj", ".", "(", "assertExpectationser", ")", "\n", "if", "!", "m", ".", "AssertExpectations", "(", "t", ")", "{", "t", ".", "Logf", "(", "\"Expectations didn't match for Mock: %+v\"", ",", "reflect", ".", "TypeOf", "(", "m", ")", ")", "\n", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// AssertExpectationsForObjects asserts that everything specified with On and Return // of the specified objects was in fact called as expected. // // Calls may have occurred in any order.
[ "AssertExpectationsForObjects", "asserts", "that", "everything", "specified", "with", "On", "and", "Return", "of", "the", "specified", "objects", "was", "in", "fact", "called", "as", "expected", ".", "Calls", "may", "have", "occurred", "in", "any", "order", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/mock/mock.go#L414-L430
train
stretchr/testify
mock/mock.go
AssertExpectations
func (m *Mock) AssertExpectations(t TestingT) bool { if h, ok := t.(tHelper); ok { h.Helper() } m.mutex.Lock() defer m.mutex.Unlock() var somethingMissing bool var failedExpectations int // iterate through each expectation expectedCalls := m.expectedCalls() for _, expectedCall := range expectedCalls { if !expectedCall.optional && !m.methodWasCalled(expectedCall.Method, expectedCall.Arguments) && expectedCall.totalCalls == 0 { somethingMissing = true failedExpectations++ t.Logf("FAIL:\t%s(%s)\n\t\tat: %s", expectedCall.Method, expectedCall.Arguments.String(), expectedCall.callerInfo) } else { if expectedCall.Repeatability > 0 { somethingMissing = true failedExpectations++ t.Logf("FAIL:\t%s(%s)\n\t\tat: %s", expectedCall.Method, expectedCall.Arguments.String(), expectedCall.callerInfo) } else { t.Logf("PASS:\t%s(%s)", expectedCall.Method, expectedCall.Arguments.String()) } } } if somethingMissing { t.Errorf("FAIL: %d out of %d expectation(s) were met.\n\tThe code you are testing needs to make %d more call(s).\n\tat: %s", len(expectedCalls)-failedExpectations, len(expectedCalls), failedExpectations, assert.CallerInfo()) } return !somethingMissing }
go
func (m *Mock) AssertExpectations(t TestingT) bool { if h, ok := t.(tHelper); ok { h.Helper() } m.mutex.Lock() defer m.mutex.Unlock() var somethingMissing bool var failedExpectations int // iterate through each expectation expectedCalls := m.expectedCalls() for _, expectedCall := range expectedCalls { if !expectedCall.optional && !m.methodWasCalled(expectedCall.Method, expectedCall.Arguments) && expectedCall.totalCalls == 0 { somethingMissing = true failedExpectations++ t.Logf("FAIL:\t%s(%s)\n\t\tat: %s", expectedCall.Method, expectedCall.Arguments.String(), expectedCall.callerInfo) } else { if expectedCall.Repeatability > 0 { somethingMissing = true failedExpectations++ t.Logf("FAIL:\t%s(%s)\n\t\tat: %s", expectedCall.Method, expectedCall.Arguments.String(), expectedCall.callerInfo) } else { t.Logf("PASS:\t%s(%s)", expectedCall.Method, expectedCall.Arguments.String()) } } } if somethingMissing { t.Errorf("FAIL: %d out of %d expectation(s) were met.\n\tThe code you are testing needs to make %d more call(s).\n\tat: %s", len(expectedCalls)-failedExpectations, len(expectedCalls), failedExpectations, assert.CallerInfo()) } return !somethingMissing }
[ "func", "(", "m", "*", "Mock", ")", "AssertExpectations", "(", "t", "TestingT", ")", "bool", "{", "if", "h", ",", "ok", ":=", "t", ".", "(", "tHelper", ")", ";", "ok", "{", "h", ".", "Helper", "(", ")", "\n", "}", "\n", "m", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mutex", ".", "Unlock", "(", ")", "\n", "var", "somethingMissing", "bool", "\n", "var", "failedExpectations", "int", "\n", "expectedCalls", ":=", "m", ".", "expectedCalls", "(", ")", "\n", "for", "_", ",", "expectedCall", ":=", "range", "expectedCalls", "{", "if", "!", "expectedCall", ".", "optional", "&&", "!", "m", ".", "methodWasCalled", "(", "expectedCall", ".", "Method", ",", "expectedCall", ".", "Arguments", ")", "&&", "expectedCall", ".", "totalCalls", "==", "0", "{", "somethingMissing", "=", "true", "\n", "failedExpectations", "++", "\n", "t", ".", "Logf", "(", "\"FAIL:\\t%s(%s)\\n\\t\\tat: %s\"", ",", "\\t", ",", "\\n", ",", "\\t", ")", "\n", "}", "else", "\\t", "\n", "}", "\n", "expectedCall", ".", "Method", "\n", "expectedCall", ".", "Arguments", ".", "String", "(", ")", "\n", "}" ]
// AssertExpectations asserts that everything specified with On and Return was // in fact called as expected. Calls may have occurred in any order.
[ "AssertExpectations", "asserts", "that", "everything", "specified", "with", "On", "and", "Return", "was", "in", "fact", "called", "as", "expected", ".", "Calls", "may", "have", "occurred", "in", "any", "order", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/mock/mock.go#L434-L466
train
stretchr/testify
mock/mock.go
AssertNumberOfCalls
func (m *Mock) AssertNumberOfCalls(t TestingT, methodName string, expectedCalls int) bool { if h, ok := t.(tHelper); ok { h.Helper() } m.mutex.Lock() defer m.mutex.Unlock() var actualCalls int for _, call := range m.calls() { if call.Method == methodName { actualCalls++ } } return assert.Equal(t, expectedCalls, actualCalls, fmt.Sprintf("Expected number of calls (%d) does not match the actual number of calls (%d).", expectedCalls, actualCalls)) }
go
func (m *Mock) AssertNumberOfCalls(t TestingT, methodName string, expectedCalls int) bool { if h, ok := t.(tHelper); ok { h.Helper() } m.mutex.Lock() defer m.mutex.Unlock() var actualCalls int for _, call := range m.calls() { if call.Method == methodName { actualCalls++ } } return assert.Equal(t, expectedCalls, actualCalls, fmt.Sprintf("Expected number of calls (%d) does not match the actual number of calls (%d).", expectedCalls, actualCalls)) }
[ "func", "(", "m", "*", "Mock", ")", "AssertNumberOfCalls", "(", "t", "TestingT", ",", "methodName", "string", ",", "expectedCalls", "int", ")", "bool", "{", "if", "h", ",", "ok", ":=", "t", ".", "(", "tHelper", ")", ";", "ok", "{", "h", ".", "Helper", "(", ")", "\n", "}", "\n", "m", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mutex", ".", "Unlock", "(", ")", "\n", "var", "actualCalls", "int", "\n", "for", "_", ",", "call", ":=", "range", "m", ".", "calls", "(", ")", "{", "if", "call", ".", "Method", "==", "methodName", "{", "actualCalls", "++", "\n", "}", "\n", "}", "\n", "return", "assert", ".", "Equal", "(", "t", ",", "expectedCalls", ",", "actualCalls", ",", "fmt", ".", "Sprintf", "(", "\"Expected number of calls (%d) does not match the actual number of calls (%d).\"", ",", "expectedCalls", ",", "actualCalls", ")", ")", "\n", "}" ]
// AssertNumberOfCalls asserts that the method was called expectedCalls times.
[ "AssertNumberOfCalls", "asserts", "that", "the", "method", "was", "called", "expectedCalls", "times", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/mock/mock.go#L469-L482
train
stretchr/testify
mock/mock.go
AssertCalled
func (m *Mock) AssertCalled(t TestingT, methodName string, arguments ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } m.mutex.Lock() defer m.mutex.Unlock() if !m.methodWasCalled(methodName, arguments) { var calledWithArgs []string for _, call := range m.calls() { calledWithArgs = append(calledWithArgs, fmt.Sprintf("%v", call.Arguments)) } if len(calledWithArgs) == 0 { return assert.Fail(t, "Should have called with given arguments", fmt.Sprintf("Expected %q to have been called with:\n%v\nbut no actual calls happened", methodName, arguments)) } return assert.Fail(t, "Should have called with given arguments", fmt.Sprintf("Expected %q to have been called with:\n%v\nbut actual calls were:\n %v", methodName, arguments, strings.Join(calledWithArgs, "\n"))) } return true }
go
func (m *Mock) AssertCalled(t TestingT, methodName string, arguments ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } m.mutex.Lock() defer m.mutex.Unlock() if !m.methodWasCalled(methodName, arguments) { var calledWithArgs []string for _, call := range m.calls() { calledWithArgs = append(calledWithArgs, fmt.Sprintf("%v", call.Arguments)) } if len(calledWithArgs) == 0 { return assert.Fail(t, "Should have called with given arguments", fmt.Sprintf("Expected %q to have been called with:\n%v\nbut no actual calls happened", methodName, arguments)) } return assert.Fail(t, "Should have called with given arguments", fmt.Sprintf("Expected %q to have been called with:\n%v\nbut actual calls were:\n %v", methodName, arguments, strings.Join(calledWithArgs, "\n"))) } return true }
[ "func", "(", "m", "*", "Mock", ")", "AssertCalled", "(", "t", "TestingT", ",", "methodName", "string", ",", "arguments", "...", "interface", "{", "}", ")", "bool", "{", "if", "h", ",", "ok", ":=", "t", ".", "(", "tHelper", ")", ";", "ok", "{", "h", ".", "Helper", "(", ")", "\n", "}", "\n", "m", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mutex", ".", "Unlock", "(", ")", "\n", "if", "!", "m", ".", "methodWasCalled", "(", "methodName", ",", "arguments", ")", "{", "var", "calledWithArgs", "[", "]", "string", "\n", "for", "_", ",", "call", ":=", "range", "m", ".", "calls", "(", ")", "{", "calledWithArgs", "=", "append", "(", "calledWithArgs", ",", "fmt", ".", "Sprintf", "(", "\"%v\"", ",", "call", ".", "Arguments", ")", ")", "\n", "}", "\n", "if", "len", "(", "calledWithArgs", ")", "==", "0", "{", "return", "assert", ".", "Fail", "(", "t", ",", "\"Should have called with given arguments\"", ",", "fmt", ".", "Sprintf", "(", "\"Expected %q to have been called with:\\n%v\\nbut no actual calls happened\"", ",", "\\n", ",", "\\n", ")", ")", "\n", "}", "\n", "methodName", "\n", "}", "\n", "arguments", "\n", "}" ]
// AssertCalled asserts that the method was called. // It can produce a false result when an argument is a pointer type and the underlying value changed after calling the mocked method.
[ "AssertCalled", "asserts", "that", "the", "method", "was", "called", ".", "It", "can", "produce", "a", "false", "result", "when", "an", "argument", "is", "a", "pointer", "type", "and", "the", "underlying", "value", "changed", "after", "calling", "the", "mocked", "method", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/mock/mock.go#L486-L505
train
stretchr/testify
mock/mock.go
AssertNotCalled
func (m *Mock) AssertNotCalled(t TestingT, methodName string, arguments ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } m.mutex.Lock() defer m.mutex.Unlock() if m.methodWasCalled(methodName, arguments) { return assert.Fail(t, "Should not have called with given arguments", fmt.Sprintf("Expected %q to not have been called with:\n%v\nbut actually it was.", methodName, arguments)) } return true }
go
func (m *Mock) AssertNotCalled(t TestingT, methodName string, arguments ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } m.mutex.Lock() defer m.mutex.Unlock() if m.methodWasCalled(methodName, arguments) { return assert.Fail(t, "Should not have called with given arguments", fmt.Sprintf("Expected %q to not have been called with:\n%v\nbut actually it was.", methodName, arguments)) } return true }
[ "func", "(", "m", "*", "Mock", ")", "AssertNotCalled", "(", "t", "TestingT", ",", "methodName", "string", ",", "arguments", "...", "interface", "{", "}", ")", "bool", "{", "if", "h", ",", "ok", ":=", "t", ".", "(", "tHelper", ")", ";", "ok", "{", "h", ".", "Helper", "(", ")", "\n", "}", "\n", "m", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mutex", ".", "Unlock", "(", ")", "\n", "if", "m", ".", "methodWasCalled", "(", "methodName", ",", "arguments", ")", "{", "return", "assert", ".", "Fail", "(", "t", ",", "\"Should not have called with given arguments\"", ",", "fmt", ".", "Sprintf", "(", "\"Expected %q to not have been called with:\\n%v\\nbut actually it was.\"", ",", "\\n", ",", "\\n", ")", ")", "\n", "}", "\n", "methodName", "\n", "}" ]
// AssertNotCalled asserts that the method was not called. // It can produce a false result when an argument is a pointer type and the underlying value changed after calling the mocked method.
[ "AssertNotCalled", "asserts", "that", "the", "method", "was", "not", "called", ".", "It", "can", "produce", "a", "false", "result", "when", "an", "argument", "is", "a", "pointer", "type", "and", "the", "underlying", "value", "changed", "after", "calling", "the", "mocked", "method", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/mock/mock.go#L509-L520
train
stretchr/testify
mock/mock.go
Get
func (args Arguments) Get(index int) interface{} { if index+1 > len(args) { panic(fmt.Sprintf("assert: arguments: Cannot call Get(%d) because there are %d argument(s).", index, len(args))) } return args[index] }
go
func (args Arguments) Get(index int) interface{} { if index+1 > len(args) { panic(fmt.Sprintf("assert: arguments: Cannot call Get(%d) because there are %d argument(s).", index, len(args))) } return args[index] }
[ "func", "(", "args", "Arguments", ")", "Get", "(", "index", "int", ")", "interface", "{", "}", "{", "if", "index", "+", "1", ">", "len", "(", "args", ")", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"assert: arguments: Cannot call Get(%d) because there are %d argument(s).\"", ",", "index", ",", "len", "(", "args", ")", ")", ")", "\n", "}", "\n", "return", "args", "[", "index", "]", "\n", "}" ]
// Get Returns the argument at the specified index.
[ "Get", "Returns", "the", "argument", "at", "the", "specified", "index", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/mock/mock.go#L638-L643
train
stretchr/testify
mock/mock.go
Is
func (args Arguments) Is(objects ...interface{}) bool { for i, obj := range args { if obj != objects[i] { return false } } return true }
go
func (args Arguments) Is(objects ...interface{}) bool { for i, obj := range args { if obj != objects[i] { return false } } return true }
[ "func", "(", "args", "Arguments", ")", "Is", "(", "objects", "...", "interface", "{", "}", ")", "bool", "{", "for", "i", ",", "obj", ":=", "range", "args", "{", "if", "obj", "!=", "objects", "[", "i", "]", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Is gets whether the objects match the arguments specified.
[ "Is", "gets", "whether", "the", "objects", "match", "the", "arguments", "specified", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/mock/mock.go#L646-L653
train
stretchr/testify
mock/mock.go
Diff
func (args Arguments) Diff(objects []interface{}) (string, int) { //TODO: could return string as error and nil for No difference var output = "\n" var differences int var maxArgCount = len(args) if len(objects) > maxArgCount { maxArgCount = len(objects) } for i := 0; i < maxArgCount; i++ { var actual, expected interface{} var actualFmt, expectedFmt string if len(objects) <= i { actual = "(Missing)" actualFmt = "(Missing)" } else { actual = objects[i] actualFmt = fmt.Sprintf("(%[1]T=%[1]v)", actual) } if len(args) <= i { expected = "(Missing)" expectedFmt = "(Missing)" } else { expected = args[i] expectedFmt = fmt.Sprintf("(%[1]T=%[1]v)", expected) } if matcher, ok := expected.(argumentMatcher); ok { if matcher.Matches(actual) { output = fmt.Sprintf("%s\t%d: PASS: %s matched by %s\n", output, i, actualFmt, matcher) } else { differences++ output = fmt.Sprintf("%s\t%d: FAIL: %s not matched by %s\n", output, i, actualFmt, matcher) } } else if reflect.TypeOf(expected) == reflect.TypeOf((*AnythingOfTypeArgument)(nil)).Elem() { // type checking if reflect.TypeOf(actual).Name() != string(expected.(AnythingOfTypeArgument)) && reflect.TypeOf(actual).String() != string(expected.(AnythingOfTypeArgument)) { // not match differences++ output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, expected, reflect.TypeOf(actual).Name(), actualFmt) } } else { // normal checking if assert.ObjectsAreEqual(expected, Anything) || assert.ObjectsAreEqual(actual, Anything) || assert.ObjectsAreEqual(actual, expected) { // match output = fmt.Sprintf("%s\t%d: PASS: %s == %s\n", output, i, actualFmt, expectedFmt) } else { // not match differences++ output = fmt.Sprintf("%s\t%d: FAIL: %s != %s\n", output, i, actualFmt, expectedFmt) } } } if differences == 0 { return "No differences.", differences } return output, differences }
go
func (args Arguments) Diff(objects []interface{}) (string, int) { //TODO: could return string as error and nil for No difference var output = "\n" var differences int var maxArgCount = len(args) if len(objects) > maxArgCount { maxArgCount = len(objects) } for i := 0; i < maxArgCount; i++ { var actual, expected interface{} var actualFmt, expectedFmt string if len(objects) <= i { actual = "(Missing)" actualFmt = "(Missing)" } else { actual = objects[i] actualFmt = fmt.Sprintf("(%[1]T=%[1]v)", actual) } if len(args) <= i { expected = "(Missing)" expectedFmt = "(Missing)" } else { expected = args[i] expectedFmt = fmt.Sprintf("(%[1]T=%[1]v)", expected) } if matcher, ok := expected.(argumentMatcher); ok { if matcher.Matches(actual) { output = fmt.Sprintf("%s\t%d: PASS: %s matched by %s\n", output, i, actualFmt, matcher) } else { differences++ output = fmt.Sprintf("%s\t%d: FAIL: %s not matched by %s\n", output, i, actualFmt, matcher) } } else if reflect.TypeOf(expected) == reflect.TypeOf((*AnythingOfTypeArgument)(nil)).Elem() { // type checking if reflect.TypeOf(actual).Name() != string(expected.(AnythingOfTypeArgument)) && reflect.TypeOf(actual).String() != string(expected.(AnythingOfTypeArgument)) { // not match differences++ output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, expected, reflect.TypeOf(actual).Name(), actualFmt) } } else { // normal checking if assert.ObjectsAreEqual(expected, Anything) || assert.ObjectsAreEqual(actual, Anything) || assert.ObjectsAreEqual(actual, expected) { // match output = fmt.Sprintf("%s\t%d: PASS: %s == %s\n", output, i, actualFmt, expectedFmt) } else { // not match differences++ output = fmt.Sprintf("%s\t%d: FAIL: %s != %s\n", output, i, actualFmt, expectedFmt) } } } if differences == 0 { return "No differences.", differences } return output, differences }
[ "func", "(", "args", "Arguments", ")", "Diff", "(", "objects", "[", "]", "interface", "{", "}", ")", "(", "string", ",", "int", ")", "{", "var", "output", "=", "\"\\n\"", "\n", "\\n", "\n", "var", "differences", "int", "\n", "var", "maxArgCount", "=", "len", "(", "args", ")", "\n", "if", "len", "(", "objects", ")", ">", "maxArgCount", "{", "maxArgCount", "=", "len", "(", "objects", ")", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "maxArgCount", ";", "i", "++", "{", "var", "actual", ",", "expected", "interface", "{", "}", "\n", "var", "actualFmt", ",", "expectedFmt", "string", "\n", "if", "len", "(", "objects", ")", "<=", "i", "{", "actual", "=", "\"(Missing)\"", "\n", "actualFmt", "=", "\"(Missing)\"", "\n", "}", "else", "{", "actual", "=", "objects", "[", "i", "]", "\n", "actualFmt", "=", "fmt", ".", "Sprintf", "(", "\"(%[1]T=%[1]v)\"", ",", "actual", ")", "\n", "}", "\n", "if", "len", "(", "args", ")", "<=", "i", "{", "expected", "=", "\"(Missing)\"", "\n", "expectedFmt", "=", "\"(Missing)\"", "\n", "}", "else", "{", "expected", "=", "args", "[", "i", "]", "\n", "expectedFmt", "=", "fmt", ".", "Sprintf", "(", "\"(%[1]T=%[1]v)\"", ",", "expected", ")", "\n", "}", "\n", "if", "matcher", ",", "ok", ":=", "expected", ".", "(", "argumentMatcher", ")", ";", "ok", "{", "if", "matcher", ".", "Matches", "(", "actual", ")", "{", "output", "=", "fmt", ".", "Sprintf", "(", "\"%s\\t%d: PASS: %s matched by %s\\n\"", ",", "\\t", ",", "\\n", ",", "output", ",", "i", ")", "\n", "}", "else", "actualFmt", "\n", "}", "else", "matcher", "\n", "}", "\n", "{", "differences", "++", "\n", "output", "=", "fmt", ".", "Sprintf", "(", "\"%s\\t%d: FAIL: %s not matched by %s\\n\"", ",", "\\t", ",", "\\n", ",", "output", ",", "i", ")", "\n", "}", "\n", "}" ]
// Diff gets a string describing the differences between the arguments // and the specified objects. // // Returns the diff string and number of differences found.
[ "Diff", "gets", "a", "string", "describing", "the", "differences", "between", "the", "arguments", "and", "the", "specified", "objects", ".", "Returns", "the", "diff", "string", "and", "number", "of", "differences", "found", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/mock/mock.go#L659-L728
train
stretchr/testify
mock/mock.go
Assert
func (args Arguments) Assert(t TestingT, objects ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } // get the differences diff, diffCount := args.Diff(objects) if diffCount == 0 { return true } // there are differences... report them... t.Logf(diff) t.Errorf("%sArguments do not match.", assert.CallerInfo()) return false }
go
func (args Arguments) Assert(t TestingT, objects ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } // get the differences diff, diffCount := args.Diff(objects) if diffCount == 0 { return true } // there are differences... report them... t.Logf(diff) t.Errorf("%sArguments do not match.", assert.CallerInfo()) return false }
[ "func", "(", "args", "Arguments", ")", "Assert", "(", "t", "TestingT", ",", "objects", "...", "interface", "{", "}", ")", "bool", "{", "if", "h", ",", "ok", ":=", "t", ".", "(", "tHelper", ")", ";", "ok", "{", "h", ".", "Helper", "(", ")", "\n", "}", "\n", "diff", ",", "diffCount", ":=", "args", ".", "Diff", "(", "objects", ")", "\n", "if", "diffCount", "==", "0", "{", "return", "true", "\n", "}", "\n", "t", ".", "Logf", "(", "diff", ")", "\n", "t", ".", "Errorf", "(", "\"%sArguments do not match.\"", ",", "assert", ".", "CallerInfo", "(", ")", ")", "\n", "return", "false", "\n", "}" ]
// Assert compares the arguments with the specified objects and fails if // they do not exactly match.
[ "Assert", "compares", "the", "arguments", "with", "the", "specified", "objects", "and", "fails", "if", "they", "do", "not", "exactly", "match", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/mock/mock.go#L732-L750
train
stretchr/testify
mock/mock.go
Int
func (args Arguments) Int(index int) int { var s int var ok bool if s, ok = args.Get(index).(int); !ok { panic(fmt.Sprintf("assert: arguments: Int(%d) failed because object wasn't correct type: %v", index, args.Get(index))) } return s }
go
func (args Arguments) Int(index int) int { var s int var ok bool if s, ok = args.Get(index).(int); !ok { panic(fmt.Sprintf("assert: arguments: Int(%d) failed because object wasn't correct type: %v", index, args.Get(index))) } return s }
[ "func", "(", "args", "Arguments", ")", "Int", "(", "index", "int", ")", "int", "{", "var", "s", "int", "\n", "var", "ok", "bool", "\n", "if", "s", ",", "ok", "=", "args", ".", "Get", "(", "index", ")", ".", "(", "int", ")", ";", "!", "ok", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"assert: arguments: Int(%d) failed because object wasn't correct type: %v\"", ",", "index", ",", "args", ".", "Get", "(", "index", ")", ")", ")", "\n", "}", "\n", "return", "s", "\n", "}" ]
// Int gets the argument at the specified index. Panics if there is no argument, or // if the argument is of the wrong type.
[ "Int", "gets", "the", "argument", "at", "the", "specified", "index", ".", "Panics", "if", "there", "is", "no", "argument", "or", "if", "the", "argument", "is", "of", "the", "wrong", "type", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/mock/mock.go#L783-L790
train
stretchr/testify
mock/mock.go
Error
func (args Arguments) Error(index int) error { obj := args.Get(index) var s error var ok bool if obj == nil { return nil } if s, ok = obj.(error); !ok { panic(fmt.Sprintf("assert: arguments: Error(%d) failed because object wasn't correct type: %v", index, args.Get(index))) } return s }
go
func (args Arguments) Error(index int) error { obj := args.Get(index) var s error var ok bool if obj == nil { return nil } if s, ok = obj.(error); !ok { panic(fmt.Sprintf("assert: arguments: Error(%d) failed because object wasn't correct type: %v", index, args.Get(index))) } return s }
[ "func", "(", "args", "Arguments", ")", "Error", "(", "index", "int", ")", "error", "{", "obj", ":=", "args", ".", "Get", "(", "index", ")", "\n", "var", "s", "error", "\n", "var", "ok", "bool", "\n", "if", "obj", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "s", ",", "ok", "=", "obj", ".", "(", "error", ")", ";", "!", "ok", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"assert: arguments: Error(%d) failed because object wasn't correct type: %v\"", ",", "index", ",", "args", ".", "Get", "(", "index", ")", ")", ")", "\n", "}", "\n", "return", "s", "\n", "}" ]
// Error gets the argument at the specified index. Panics if there is no argument, or // if the argument is of the wrong type.
[ "Error", "gets", "the", "argument", "at", "the", "specified", "index", ".", "Panics", "if", "there", "is", "no", "argument", "or", "if", "the", "argument", "is", "of", "the", "wrong", "type", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/mock/mock.go#L794-L805
train
stretchr/testify
require/require.go
DirExists
func DirExists(t TestingT, path string, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if assert.DirExists(t, path, msgAndArgs...) { return } t.FailNow() }
go
func DirExists(t TestingT, path string, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if assert.DirExists(t, path, msgAndArgs...) { return } t.FailNow() }
[ "func", "DirExists", "(", "t", "TestingT", ",", "path", "string", ",", "msgAndArgs", "...", "interface", "{", "}", ")", "{", "if", "h", ",", "ok", ":=", "t", ".", "(", "tHelper", ")", ";", "ok", "{", "h", ".", "Helper", "(", ")", "\n", "}", "\n", "if", "assert", ".", "DirExists", "(", "t", ",", "path", ",", "msgAndArgs", "...", ")", "{", "return", "\n", "}", "\n", "t", ".", "FailNow", "(", ")", "\n", "}" ]
// DirExists checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists.
[ "DirExists", "checks", "whether", "a", "directory", "exists", "in", "the", "given", "path", ".", "It", "also", "fails", "if", "the", "path", "is", "a", "file", "rather", "a", "directory", "or", "there", "is", "an", "error", "checking", "whether", "it", "exists", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/require/require.go#L70-L78
train
stretchr/testify
require/require.go
FailNowf
func FailNowf(t TestingT, failureMessage string, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if assert.FailNowf(t, failureMessage, msg, args...) { return } t.FailNow() }
go
func FailNowf(t TestingT, failureMessage string, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if assert.FailNowf(t, failureMessage, msg, args...) { return } t.FailNow() }
[ "func", "FailNowf", "(", "t", "TestingT", ",", "failureMessage", "string", ",", "msg", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "if", "h", ",", "ok", ":=", "t", ".", "(", "tHelper", ")", ";", "ok", "{", "h", ".", "Helper", "(", ")", "\n", "}", "\n", "if", "assert", ".", "FailNowf", "(", "t", ",", "failureMessage", ",", "msg", ",", "args", "...", ")", "{", "return", "\n", "}", "\n", "t", ".", "FailNow", "(", ")", "\n", "}" ]
// FailNowf fails test
[ "FailNowf", "fails", "test" ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/require/require.go#L322-L330
train
stretchr/testify
assert/assertion_forward.go
NotZero
func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return NotZero(a.t, i, msgAndArgs...) }
go
func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return NotZero(a.t, i, msgAndArgs...) }
[ "func", "(", "a", "*", "Assertions", ")", "NotZero", "(", "i", "interface", "{", "}", ",", "msgAndArgs", "...", "interface", "{", "}", ")", "bool", "{", "if", "h", ",", "ok", ":=", "a", ".", "t", ".", "(", "tHelper", ")", ";", "ok", "{", "h", ".", "Helper", "(", ")", "\n", "}", "\n", "return", "NotZero", "(", "a", ".", "t", ",", "i", ",", "msgAndArgs", "...", ")", "\n", "}" ]
// NotZero asserts that i is not the zero value for its type.
[ "NotZero", "asserts", "that", "i", "is", "not", "the", "zero", "value", "for", "its", "type", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertion_forward.go#L901-L906
train
stretchr/testify
assert/http_assertions.go
HTTPBody
func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string { w := httptest.NewRecorder() req, err := http.NewRequest(method, url+"?"+values.Encode(), nil) if err != nil { return "" } handler(w, req) return w.Body.String() }
go
func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string { w := httptest.NewRecorder() req, err := http.NewRequest(method, url+"?"+values.Encode(), nil) if err != nil { return "" } handler(w, req) return w.Body.String() }
[ "func", "HTTPBody", "(", "handler", "http", ".", "HandlerFunc", ",", "method", ",", "url", "string", ",", "values", "url", ".", "Values", ")", "string", "{", "w", ":=", "httptest", ".", "NewRecorder", "(", ")", "\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "method", ",", "url", "+", "\"?\"", "+", "values", ".", "Encode", "(", ")", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", "\n", "}", "\n", "handler", "(", "w", ",", "req", ")", "\n", "return", "w", ".", "Body", ".", "String", "(", ")", "\n", "}" ]
// HTTPBody is a helper that returns HTTP body of the response. It returns // empty string if building a new request fails.
[ "HTTPBody", "is", "a", "helper", "that", "returns", "HTTP", "body", "of", "the", "response", ".", "It", "returns", "empty", "string", "if", "building", "a", "new", "request", "fails", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/http_assertions.go#L95-L103
train
stretchr/testify
suite/suite.go
Require
func (suite *Suite) Require() *require.Assertions { if suite.require == nil { suite.require = require.New(suite.T()) } return suite.require }
go
func (suite *Suite) Require() *require.Assertions { if suite.require == nil { suite.require = require.New(suite.T()) } return suite.require }
[ "func", "(", "suite", "*", "Suite", ")", "Require", "(", ")", "*", "require", ".", "Assertions", "{", "if", "suite", ".", "require", "==", "nil", "{", "suite", ".", "require", "=", "require", ".", "New", "(", "suite", ".", "T", "(", ")", ")", "\n", "}", "\n", "return", "suite", ".", "require", "\n", "}" ]
// Require returns a require context for suite.
[ "Require", "returns", "a", "require", "context", "for", "suite", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/suite/suite.go#L40-L45
train
stretchr/testify
suite/suite.go
Run
func Run(t *testing.T, suite TestingSuite) { suite.SetT(t) defer failOnPanic(t) suiteSetupDone := false methodFinder := reflect.TypeOf(suite) tests := []testing.InternalTest{} for index := 0; index < methodFinder.NumMethod(); index++ { method := methodFinder.Method(index) ok, err := methodFilter(method.Name) if err != nil { fmt.Fprintf(os.Stderr, "testify: invalid regexp for -m: %s\n", err) os.Exit(1) } if !ok { continue } if !suiteSetupDone { if setupAllSuite, ok := suite.(SetupAllSuite); ok { setupAllSuite.SetupSuite() } defer func() { if tearDownAllSuite, ok := suite.(TearDownAllSuite); ok { tearDownAllSuite.TearDownSuite() } }() suiteSetupDone = true } test := testing.InternalTest{ Name: method.Name, F: func(t *testing.T) { parentT := suite.T() suite.SetT(t) defer failOnPanic(t) if setupTestSuite, ok := suite.(SetupTestSuite); ok { setupTestSuite.SetupTest() } if beforeTestSuite, ok := suite.(BeforeTest); ok { beforeTestSuite.BeforeTest(methodFinder.Elem().Name(), method.Name) } defer func() { if afterTestSuite, ok := suite.(AfterTest); ok { afterTestSuite.AfterTest(methodFinder.Elem().Name(), method.Name) } if tearDownTestSuite, ok := suite.(TearDownTestSuite); ok { tearDownTestSuite.TearDownTest() } suite.SetT(parentT) }() method.Func.Call([]reflect.Value{reflect.ValueOf(suite)}) }, } tests = append(tests, test) } runTests(t, tests) }
go
func Run(t *testing.T, suite TestingSuite) { suite.SetT(t) defer failOnPanic(t) suiteSetupDone := false methodFinder := reflect.TypeOf(suite) tests := []testing.InternalTest{} for index := 0; index < methodFinder.NumMethod(); index++ { method := methodFinder.Method(index) ok, err := methodFilter(method.Name) if err != nil { fmt.Fprintf(os.Stderr, "testify: invalid regexp for -m: %s\n", err) os.Exit(1) } if !ok { continue } if !suiteSetupDone { if setupAllSuite, ok := suite.(SetupAllSuite); ok { setupAllSuite.SetupSuite() } defer func() { if tearDownAllSuite, ok := suite.(TearDownAllSuite); ok { tearDownAllSuite.TearDownSuite() } }() suiteSetupDone = true } test := testing.InternalTest{ Name: method.Name, F: func(t *testing.T) { parentT := suite.T() suite.SetT(t) defer failOnPanic(t) if setupTestSuite, ok := suite.(SetupTestSuite); ok { setupTestSuite.SetupTest() } if beforeTestSuite, ok := suite.(BeforeTest); ok { beforeTestSuite.BeforeTest(methodFinder.Elem().Name(), method.Name) } defer func() { if afterTestSuite, ok := suite.(AfterTest); ok { afterTestSuite.AfterTest(methodFinder.Elem().Name(), method.Name) } if tearDownTestSuite, ok := suite.(TearDownTestSuite); ok { tearDownTestSuite.TearDownTest() } suite.SetT(parentT) }() method.Func.Call([]reflect.Value{reflect.ValueOf(suite)}) }, } tests = append(tests, test) } runTests(t, tests) }
[ "func", "Run", "(", "t", "*", "testing", ".", "T", ",", "suite", "TestingSuite", ")", "{", "suite", ".", "SetT", "(", "t", ")", "\n", "defer", "failOnPanic", "(", "t", ")", "\n", "suiteSetupDone", ":=", "false", "\n", "methodFinder", ":=", "reflect", ".", "TypeOf", "(", "suite", ")", "\n", "tests", ":=", "[", "]", "testing", ".", "InternalTest", "{", "}", "\n", "for", "index", ":=", "0", ";", "index", "<", "methodFinder", ".", "NumMethod", "(", ")", ";", "index", "++", "{", "method", ":=", "methodFinder", ".", "Method", "(", "index", ")", "\n", "ok", ",", "err", ":=", "methodFilter", "(", "method", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"testify: invalid regexp for -m: %s\\n\"", ",", "\\n", ")", "\n", "err", "\n", "}", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "if", "!", "suiteSetupDone", "{", "if", "setupAllSuite", ",", "ok", ":=", "suite", ".", "(", "SetupAllSuite", ")", ";", "ok", "{", "setupAllSuite", ".", "SetupSuite", "(", ")", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "tearDownAllSuite", ",", "ok", ":=", "suite", ".", "(", "TearDownAllSuite", ")", ";", "ok", "{", "tearDownAllSuite", ".", "TearDownSuite", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n", "suiteSetupDone", "=", "true", "\n", "}", "\n", "test", ":=", "testing", ".", "InternalTest", "{", "Name", ":", "method", ".", "Name", ",", "F", ":", "func", "(", "t", "*", "testing", ".", "T", ")", "{", "parentT", ":=", "suite", ".", "T", "(", ")", "\n", "suite", ".", "SetT", "(", "t", ")", "\n", "defer", "failOnPanic", "(", "t", ")", "\n", "if", "setupTestSuite", ",", "ok", ":=", "suite", ".", "(", "SetupTestSuite", ")", ";", "ok", "{", "setupTestSuite", ".", "SetupTest", "(", ")", "\n", "}", "\n", "if", "beforeTestSuite", ",", "ok", ":=", "suite", ".", "(", "BeforeTest", ")", ";", "ok", "{", "beforeTestSuite", ".", "BeforeTest", "(", "methodFinder", ".", "Elem", "(", ")", ".", "Name", "(", ")", ",", "method", ".", "Name", ")", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "afterTestSuite", ",", "ok", ":=", "suite", ".", "(", "AfterTest", ")", ";", "ok", "{", "afterTestSuite", ".", "AfterTest", "(", "methodFinder", ".", "Elem", "(", ")", ".", "Name", "(", ")", ",", "method", ".", "Name", ")", "\n", "}", "\n", "if", "tearDownTestSuite", ",", "ok", ":=", "suite", ".", "(", "TearDownTestSuite", ")", ";", "ok", "{", "tearDownTestSuite", ".", "TearDownTest", "(", ")", "\n", "}", "\n", "suite", ".", "SetT", "(", "parentT", ")", "\n", "}", "(", ")", "\n", "method", ".", "Func", ".", "Call", "(", "[", "]", "reflect", ".", "Value", "{", "reflect", ".", "ValueOf", "(", "suite", ")", "}", ")", "\n", "}", ",", "}", "\n", "}", "\n", "tests", "=", "append", "(", "tests", ",", "test", ")", "\n", "}" ]
// Run takes a testing suite and runs all of the tests attached // to it.
[ "Run", "takes", "a", "testing", "suite", "and", "runs", "all", "of", "the", "tests", "attached", "to", "it", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/suite/suite.go#L82-L139
train
stretchr/testify
suite/suite.go
methodFilter
func methodFilter(name string) (bool, error) { if ok, _ := regexp.MatchString("^Test", name); !ok { return false, nil } return regexp.MatchString(*matchMethod, name) }
go
func methodFilter(name string) (bool, error) { if ok, _ := regexp.MatchString("^Test", name); !ok { return false, nil } return regexp.MatchString(*matchMethod, name) }
[ "func", "methodFilter", "(", "name", "string", ")", "(", "bool", ",", "error", ")", "{", "if", "ok", ",", "_", ":=", "regexp", ".", "MatchString", "(", "\"^Test\"", ",", "name", ")", ";", "!", "ok", "{", "return", "false", ",", "nil", "\n", "}", "\n", "return", "regexp", ".", "MatchString", "(", "*", "matchMethod", ",", "name", ")", "\n", "}" ]
// Filtering method according to set regular expression // specified command-line argument -m
[ "Filtering", "method", "according", "to", "set", "regular", "expression", "specified", "command", "-", "line", "argument", "-", "m" ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/suite/suite.go#L157-L162
train
stretchr/testify
assert/assertion_format.go
InEpsilonf
func InEpsilonf(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return InEpsilon(t, expected, actual, epsilon, append([]interface{}{msg}, args...)...) }
go
func InEpsilonf(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return InEpsilon(t, expected, actual, epsilon, append([]interface{}{msg}, args...)...) }
[ "func", "InEpsilonf", "(", "t", "TestingT", ",", "expected", "interface", "{", "}", ",", "actual", "interface", "{", "}", ",", "epsilon", "float64", ",", "msg", "string", ",", "args", "...", "interface", "{", "}", ")", "bool", "{", "if", "h", ",", "ok", ":=", "t", ".", "(", "tHelper", ")", ";", "ok", "{", "h", ".", "Helper", "(", ")", "\n", "}", "\n", "return", "InEpsilon", "(", "t", ",", "expected", ",", "actual", ",", "epsilon", ",", "append", "(", "[", "]", "interface", "{", "}", "{", "msg", "}", ",", "args", "...", ")", "...", ")", "\n", "}" ]
// InEpsilonf asserts that expected and actual have a relative error less than epsilon
[ "InEpsilonf", "asserts", "that", "expected", "and", "actual", "have", "a", "relative", "error", "less", "than", "epsilon" ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertion_format.go#L284-L289
train
stretchr/testify
assert/assertion_format.go
NotZerof
func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotZero(t, i, append([]interface{}{msg}, args...)...) }
go
func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotZero(t, i, append([]interface{}{msg}, args...)...) }
[ "func", "NotZerof", "(", "t", "TestingT", ",", "i", "interface", "{", "}", ",", "msg", "string", ",", "args", "...", "interface", "{", "}", ")", "bool", "{", "if", "h", ",", "ok", ":=", "t", ".", "(", "tHelper", ")", ";", "ok", "{", "h", ".", "Helper", "(", ")", "\n", "}", "\n", "return", "NotZero", "(", "t", ",", "i", ",", "append", "(", "[", "]", "interface", "{", "}", "{", "msg", "}", ",", "args", "...", ")", "...", ")", "\n", "}" ]
// NotZerof asserts that i is not the zero value for its type.
[ "NotZerof", "asserts", "that", "i", "is", "not", "the", "zero", "value", "for", "its", "type", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertion_format.go#L458-L463
train
stretchr/testify
_codegen/main.go
parsePackageSource
func parsePackageSource(pkg string) (*types.Scope, *doc.Package, error) { pd, err := build.Import(pkg, ".", 0) if err != nil { return nil, nil, err } fset := token.NewFileSet() files := make(map[string]*ast.File) fileList := make([]*ast.File, len(pd.GoFiles)) for i, fname := range pd.GoFiles { src, err := ioutil.ReadFile(path.Join(pd.SrcRoot, pd.ImportPath, fname)) if err != nil { return nil, nil, err } f, err := parser.ParseFile(fset, fname, src, parser.ParseComments|parser.AllErrors) if err != nil { return nil, nil, err } files[fname] = f fileList[i] = f } cfg := types.Config{ Importer: importer.Default(), } info := types.Info{ Defs: make(map[*ast.Ident]types.Object), } tp, err := cfg.Check(pkg, fset, fileList, &info) if err != nil { return nil, nil, err } scope := tp.Scope() ap, _ := ast.NewPackage(fset, files, nil, nil) docs := doc.New(ap, pkg, 0) return scope, docs, nil }
go
func parsePackageSource(pkg string) (*types.Scope, *doc.Package, error) { pd, err := build.Import(pkg, ".", 0) if err != nil { return nil, nil, err } fset := token.NewFileSet() files := make(map[string]*ast.File) fileList := make([]*ast.File, len(pd.GoFiles)) for i, fname := range pd.GoFiles { src, err := ioutil.ReadFile(path.Join(pd.SrcRoot, pd.ImportPath, fname)) if err != nil { return nil, nil, err } f, err := parser.ParseFile(fset, fname, src, parser.ParseComments|parser.AllErrors) if err != nil { return nil, nil, err } files[fname] = f fileList[i] = f } cfg := types.Config{ Importer: importer.Default(), } info := types.Info{ Defs: make(map[*ast.Ident]types.Object), } tp, err := cfg.Check(pkg, fset, fileList, &info) if err != nil { return nil, nil, err } scope := tp.Scope() ap, _ := ast.NewPackage(fset, files, nil, nil) docs := doc.New(ap, pkg, 0) return scope, docs, nil }
[ "func", "parsePackageSource", "(", "pkg", "string", ")", "(", "*", "types", ".", "Scope", ",", "*", "doc", ".", "Package", ",", "error", ")", "{", "pd", ",", "err", ":=", "build", ".", "Import", "(", "pkg", ",", "\".\"", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "fset", ":=", "token", ".", "NewFileSet", "(", ")", "\n", "files", ":=", "make", "(", "map", "[", "string", "]", "*", "ast", ".", "File", ")", "\n", "fileList", ":=", "make", "(", "[", "]", "*", "ast", ".", "File", ",", "len", "(", "pd", ".", "GoFiles", ")", ")", "\n", "for", "i", ",", "fname", ":=", "range", "pd", ".", "GoFiles", "{", "src", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ".", "Join", "(", "pd", ".", "SrcRoot", ",", "pd", ".", "ImportPath", ",", "fname", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "f", ",", "err", ":=", "parser", ".", "ParseFile", "(", "fset", ",", "fname", ",", "src", ",", "parser", ".", "ParseComments", "|", "parser", ".", "AllErrors", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "files", "[", "fname", "]", "=", "f", "\n", "fileList", "[", "i", "]", "=", "f", "\n", "}", "\n", "cfg", ":=", "types", ".", "Config", "{", "Importer", ":", "importer", ".", "Default", "(", ")", ",", "}", "\n", "info", ":=", "types", ".", "Info", "{", "Defs", ":", "make", "(", "map", "[", "*", "ast", ".", "Ident", "]", "types", ".", "Object", ")", ",", "}", "\n", "tp", ",", "err", ":=", "cfg", ".", "Check", "(", "pkg", ",", "fset", ",", "fileList", ",", "&", "info", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "scope", ":=", "tp", ".", "Scope", "(", ")", "\n", "ap", ",", "_", ":=", "ast", ".", "NewPackage", "(", "fset", ",", "files", ",", "nil", ",", "nil", ")", "\n", "docs", ":=", "doc", ".", "New", "(", "ap", ",", "pkg", ",", "0", ")", "\n", "return", "scope", ",", "docs", ",", "nil", "\n", "}" ]
// parsePackageSource returns the types scope and the package documentation from the package
[ "parsePackageSource", "returns", "the", "types", "scope", "and", "the", "package", "documentation", "from", "the", "package" ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/_codegen/main.go#L174-L213
train
stretchr/testify
assert/assertions.go
ObjectsAreEqualValues
func ObjectsAreEqualValues(expected, actual interface{}) bool { if ObjectsAreEqual(expected, actual) { return true } actualType := reflect.TypeOf(actual) if actualType == nil { return false } expectedValue := reflect.ValueOf(expected) if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { // Attempt comparison after type conversion return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) } return false }
go
func ObjectsAreEqualValues(expected, actual interface{}) bool { if ObjectsAreEqual(expected, actual) { return true } actualType := reflect.TypeOf(actual) if actualType == nil { return false } expectedValue := reflect.ValueOf(expected) if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { // Attempt comparison after type conversion return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) } return false }
[ "func", "ObjectsAreEqualValues", "(", "expected", ",", "actual", "interface", "{", "}", ")", "bool", "{", "if", "ObjectsAreEqual", "(", "expected", ",", "actual", ")", "{", "return", "true", "\n", "}", "\n", "actualType", ":=", "reflect", ".", "TypeOf", "(", "actual", ")", "\n", "if", "actualType", "==", "nil", "{", "return", "false", "\n", "}", "\n", "expectedValue", ":=", "reflect", ".", "ValueOf", "(", "expected", ")", "\n", "if", "expectedValue", ".", "IsValid", "(", ")", "&&", "expectedValue", ".", "Type", "(", ")", ".", "ConvertibleTo", "(", "actualType", ")", "{", "return", "reflect", ".", "DeepEqual", "(", "expectedValue", ".", "Convert", "(", "actualType", ")", ".", "Interface", "(", ")", ",", "actual", ")", "\n", "}", "\n", "return", "false", "\n", "}" ]
// ObjectsAreEqualValues gets whether two objects are equal, or if their // values are equal.
[ "ObjectsAreEqualValues", "gets", "whether", "two", "objects", "are", "equal", "or", "if", "their", "values", "are", "equal", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L78-L94
train
stretchr/testify
assert/assertions.go
formatUnequalValues
func formatUnequalValues(expected, actual interface{}) (e string, a string) { if reflect.TypeOf(expected) != reflect.TypeOf(actual) { return fmt.Sprintf("%T(%#v)", expected, expected), fmt.Sprintf("%T(%#v)", actual, actual) } return fmt.Sprintf("%#v", expected), fmt.Sprintf("%#v", actual) }
go
func formatUnequalValues(expected, actual interface{}) (e string, a string) { if reflect.TypeOf(expected) != reflect.TypeOf(actual) { return fmt.Sprintf("%T(%#v)", expected, expected), fmt.Sprintf("%T(%#v)", actual, actual) } return fmt.Sprintf("%#v", expected), fmt.Sprintf("%#v", actual) }
[ "func", "formatUnequalValues", "(", "expected", ",", "actual", "interface", "{", "}", ")", "(", "e", "string", ",", "a", "string", ")", "{", "if", "reflect", ".", "TypeOf", "(", "expected", ")", "!=", "reflect", ".", "TypeOf", "(", "actual", ")", "{", "return", "fmt", ".", "Sprintf", "(", "\"%T(%#v)\"", ",", "expected", ",", "expected", ")", ",", "fmt", ".", "Sprintf", "(", "\"%T(%#v)\"", ",", "actual", ",", "actual", ")", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"%#v\"", ",", "expected", ")", ",", "fmt", ".", "Sprintf", "(", "\"%#v\"", ",", "actual", ")", "\n", "}" ]
// formatUnequalValues takes two values of arbitrary types and returns string // representations appropriate to be presented to the user. // // If the values are not of like type, the returned strings will be prefixed // with the type name, and the value will be enclosed in parenthesis similar // to a type conversion in the Go grammar.
[ "formatUnequalValues", "takes", "two", "values", "of", "arbitrary", "types", "and", "returns", "string", "representations", "appropriate", "to", "be", "presented", "to", "the", "user", ".", "If", "the", "values", "are", "not", "of", "like", "type", "the", "returned", "strings", "will", "be", "prefixed", "with", "the", "type", "name", "and", "the", "value", "will", "be", "enclosed", "in", "parenthesis", "similar", "to", "a", "type", "conversion", "in", "the", "Go", "grammar", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L390-L398
train
stretchr/testify
assert/assertions.go
containsKind
func containsKind(kinds []reflect.Kind, kind reflect.Kind) bool { for i := 0; i < len(kinds); i++ { if kind == kinds[i] { return true } } return false }
go
func containsKind(kinds []reflect.Kind, kind reflect.Kind) bool { for i := 0; i < len(kinds); i++ { if kind == kinds[i] { return true } } return false }
[ "func", "containsKind", "(", "kinds", "[", "]", "reflect", ".", "Kind", ",", "kind", "reflect", ".", "Kind", ")", "bool", "{", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "kinds", ")", ";", "i", "++", "{", "if", "kind", "==", "kinds", "[", "i", "]", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// containsKind checks if a specified kind in the slice of kinds.
[ "containsKind", "checks", "if", "a", "specified", "kind", "in", "the", "slice", "of", "kinds", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L454-L462
train
stretchr/testify
assert/assertions.go
isNil
func isNil(object interface{}) bool { if object == nil { return true } value := reflect.ValueOf(object) kind := value.Kind() isNilableKind := containsKind( []reflect.Kind{ reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice}, kind) if isNilableKind && value.IsNil() { return true } return false }
go
func isNil(object interface{}) bool { if object == nil { return true } value := reflect.ValueOf(object) kind := value.Kind() isNilableKind := containsKind( []reflect.Kind{ reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice}, kind) if isNilableKind && value.IsNil() { return true } return false }
[ "func", "isNil", "(", "object", "interface", "{", "}", ")", "bool", "{", "if", "object", "==", "nil", "{", "return", "true", "\n", "}", "\n", "value", ":=", "reflect", ".", "ValueOf", "(", "object", ")", "\n", "kind", ":=", "value", ".", "Kind", "(", ")", "\n", "isNilableKind", ":=", "containsKind", "(", "[", "]", "reflect", ".", "Kind", "{", "reflect", ".", "Chan", ",", "reflect", ".", "Func", ",", "reflect", ".", "Interface", ",", "reflect", ".", "Map", ",", "reflect", ".", "Ptr", ",", "reflect", ".", "Slice", "}", ",", "kind", ")", "\n", "if", "isNilableKind", "&&", "value", ".", "IsNil", "(", ")", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isNil checks if a specified object is nil or not, without Failing.
[ "isNil", "checks", "if", "a", "specified", "object", "is", "nil", "or", "not", "without", "Failing", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L465-L484
train
stretchr/testify
assert/assertions.go
didPanic
func didPanic(f PanicTestFunc) (bool, interface{}) { didPanic := false var message interface{} func() { defer func() { if message = recover(); message != nil { didPanic = true } }() // call the target function f() }() return didPanic, message }
go
func didPanic(f PanicTestFunc) (bool, interface{}) { didPanic := false var message interface{} func() { defer func() { if message = recover(); message != nil { didPanic = true } }() // call the target function f() }() return didPanic, message }
[ "func", "didPanic", "(", "f", "PanicTestFunc", ")", "(", "bool", ",", "interface", "{", "}", ")", "{", "didPanic", ":=", "false", "\n", "var", "message", "interface", "{", "}", "\n", "func", "(", ")", "{", "defer", "func", "(", ")", "{", "if", "message", "=", "recover", "(", ")", ";", "message", "!=", "nil", "{", "didPanic", "=", "true", "\n", "}", "\n", "}", "(", ")", "\n", "f", "(", ")", "\n", "}", "(", ")", "\n", "return", "didPanic", ",", "message", "\n", "}" ]
// didPanic returns true if the function passed to it panics. Otherwise, it returns false.
[ "didPanic", "returns", "true", "if", "the", "function", "passed", "to", "it", "panics", ".", "Otherwise", "it", "returns", "false", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L903-L922
train
stretchr/testify
assert/assertions.go
InDeltaMapValues
func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if expected == nil || actual == nil || reflect.TypeOf(actual).Kind() != reflect.Map || reflect.TypeOf(expected).Kind() != reflect.Map { return Fail(t, "Arguments must be maps", msgAndArgs...) } expectedMap := reflect.ValueOf(expected) actualMap := reflect.ValueOf(actual) if expectedMap.Len() != actualMap.Len() { return Fail(t, "Arguments must have the same number of keys", msgAndArgs...) } for _, k := range expectedMap.MapKeys() { ev := expectedMap.MapIndex(k) av := actualMap.MapIndex(k) if !ev.IsValid() { return Fail(t, fmt.Sprintf("missing key %q in expected map", k), msgAndArgs...) } if !av.IsValid() { return Fail(t, fmt.Sprintf("missing key %q in actual map", k), msgAndArgs...) } if !InDelta( t, ev.Interface(), av.Interface(), delta, msgAndArgs..., ) { return false } } return true }
go
func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if expected == nil || actual == nil || reflect.TypeOf(actual).Kind() != reflect.Map || reflect.TypeOf(expected).Kind() != reflect.Map { return Fail(t, "Arguments must be maps", msgAndArgs...) } expectedMap := reflect.ValueOf(expected) actualMap := reflect.ValueOf(actual) if expectedMap.Len() != actualMap.Len() { return Fail(t, "Arguments must have the same number of keys", msgAndArgs...) } for _, k := range expectedMap.MapKeys() { ev := expectedMap.MapIndex(k) av := actualMap.MapIndex(k) if !ev.IsValid() { return Fail(t, fmt.Sprintf("missing key %q in expected map", k), msgAndArgs...) } if !av.IsValid() { return Fail(t, fmt.Sprintf("missing key %q in actual map", k), msgAndArgs...) } if !InDelta( t, ev.Interface(), av.Interface(), delta, msgAndArgs..., ) { return false } } return true }
[ "func", "InDeltaMapValues", "(", "t", "TestingT", ",", "expected", ",", "actual", "interface", "{", "}", ",", "delta", "float64", ",", "msgAndArgs", "...", "interface", "{", "}", ")", "bool", "{", "if", "h", ",", "ok", ":=", "t", ".", "(", "tHelper", ")", ";", "ok", "{", "h", ".", "Helper", "(", ")", "\n", "}", "\n", "if", "expected", "==", "nil", "||", "actual", "==", "nil", "||", "reflect", ".", "TypeOf", "(", "actual", ")", ".", "Kind", "(", ")", "!=", "reflect", ".", "Map", "||", "reflect", ".", "TypeOf", "(", "expected", ")", ".", "Kind", "(", ")", "!=", "reflect", ".", "Map", "{", "return", "Fail", "(", "t", ",", "\"Arguments must be maps\"", ",", "msgAndArgs", "...", ")", "\n", "}", "\n", "expectedMap", ":=", "reflect", ".", "ValueOf", "(", "expected", ")", "\n", "actualMap", ":=", "reflect", ".", "ValueOf", "(", "actual", ")", "\n", "if", "expectedMap", ".", "Len", "(", ")", "!=", "actualMap", ".", "Len", "(", ")", "{", "return", "Fail", "(", "t", ",", "\"Arguments must have the same number of keys\"", ",", "msgAndArgs", "...", ")", "\n", "}", "\n", "for", "_", ",", "k", ":=", "range", "expectedMap", ".", "MapKeys", "(", ")", "{", "ev", ":=", "expectedMap", ".", "MapIndex", "(", "k", ")", "\n", "av", ":=", "actualMap", ".", "MapIndex", "(", "k", ")", "\n", "if", "!", "ev", ".", "IsValid", "(", ")", "{", "return", "Fail", "(", "t", ",", "fmt", ".", "Sprintf", "(", "\"missing key %q in expected map\"", ",", "k", ")", ",", "msgAndArgs", "...", ")", "\n", "}", "\n", "if", "!", "av", ".", "IsValid", "(", ")", "{", "return", "Fail", "(", "t", ",", "fmt", ".", "Sprintf", "(", "\"missing key %q in actual map\"", ",", "k", ")", ",", "msgAndArgs", "...", ")", "\n", "}", "\n", "if", "!", "InDelta", "(", "t", ",", "ev", ".", "Interface", "(", ")", ",", "av", ".", "Interface", "(", ")", ",", "delta", ",", "msgAndArgs", "...", ",", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.
[ "InDeltaMapValues", "is", "the", "same", "as", "InDelta", "but", "it", "compares", "all", "values", "between", "two", "maps", ".", "Both", "maps", "must", "have", "exactly", "the", "same", "keys", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L1082-L1123
train
stretchr/testify
assert/assertions.go
matchRegexp
func matchRegexp(rx interface{}, str interface{}) bool { var r *regexp.Regexp if rr, ok := rx.(*regexp.Regexp); ok { r = rr } else { r = regexp.MustCompile(fmt.Sprint(rx)) } return (r.FindStringIndex(fmt.Sprint(str)) != nil) }
go
func matchRegexp(rx interface{}, str interface{}) bool { var r *regexp.Regexp if rr, ok := rx.(*regexp.Regexp); ok { r = rr } else { r = regexp.MustCompile(fmt.Sprint(rx)) } return (r.FindStringIndex(fmt.Sprint(str)) != nil) }
[ "func", "matchRegexp", "(", "rx", "interface", "{", "}", ",", "str", "interface", "{", "}", ")", "bool", "{", "var", "r", "*", "regexp", ".", "Regexp", "\n", "if", "rr", ",", "ok", ":=", "rx", ".", "(", "*", "regexp", ".", "Regexp", ")", ";", "ok", "{", "r", "=", "rr", "\n", "}", "else", "{", "r", "=", "regexp", ".", "MustCompile", "(", "fmt", ".", "Sprint", "(", "rx", ")", ")", "\n", "}", "\n", "return", "(", "r", ".", "FindStringIndex", "(", "fmt", ".", "Sprint", "(", "str", ")", ")", "!=", "nil", ")", "\n", "}" ]
// matchRegexp return true if a specified regexp matches a string.
[ "matchRegexp", "return", "true", "if", "a", "specified", "regexp", "matches", "a", "string", "." ]
34c6fa2dc70986bccbbffcc6130f6920a924b075
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L1245-L1256
train
vmware/govmomi
object/virtual_device_list.go
SCSIControllerTypes
func SCSIControllerTypes() VirtualDeviceList { // Return a mutable list of SCSI controller types, initialized with defaults. return VirtualDeviceList([]types.BaseVirtualDevice{ &types.VirtualLsiLogicController{}, &types.VirtualBusLogicController{}, &types.ParaVirtualSCSIController{}, &types.VirtualLsiLogicSASController{}, }).Select(func(device types.BaseVirtualDevice) bool { c := device.(types.BaseVirtualSCSIController).GetVirtualSCSIController() c.SharedBus = types.VirtualSCSISharingNoSharing c.BusNumber = -1 return true }) }
go
func SCSIControllerTypes() VirtualDeviceList { // Return a mutable list of SCSI controller types, initialized with defaults. return VirtualDeviceList([]types.BaseVirtualDevice{ &types.VirtualLsiLogicController{}, &types.VirtualBusLogicController{}, &types.ParaVirtualSCSIController{}, &types.VirtualLsiLogicSASController{}, }).Select(func(device types.BaseVirtualDevice) bool { c := device.(types.BaseVirtualSCSIController).GetVirtualSCSIController() c.SharedBus = types.VirtualSCSISharingNoSharing c.BusNumber = -1 return true }) }
[ "func", "SCSIControllerTypes", "(", ")", "VirtualDeviceList", "{", "return", "VirtualDeviceList", "(", "[", "]", "types", ".", "BaseVirtualDevice", "{", "&", "types", ".", "VirtualLsiLogicController", "{", "}", ",", "&", "types", ".", "VirtualBusLogicController", "{", "}", ",", "&", "types", ".", "ParaVirtualSCSIController", "{", "}", ",", "&", "types", ".", "VirtualLsiLogicSASController", "{", "}", ",", "}", ")", ".", "Select", "(", "func", "(", "device", "types", ".", "BaseVirtualDevice", ")", "bool", "{", "c", ":=", "device", ".", "(", "types", ".", "BaseVirtualSCSIController", ")", ".", "GetVirtualSCSIController", "(", ")", "\n", "c", ".", "SharedBus", "=", "types", ".", "VirtualSCSISharingNoSharing", "\n", "c", ".", "BusNumber", "=", "-", "1", "\n", "return", "true", "\n", "}", ")", "\n", "}" ]
// SCSIControllerTypes are used for adding a new SCSI controller to a VM.
[ "SCSIControllerTypes", "are", "used", "for", "adding", "a", "new", "SCSI", "controller", "to", "a", "VM", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L44-L57
train
vmware/govmomi
object/virtual_device_list.go
EthernetCardTypes
func EthernetCardTypes() VirtualDeviceList { return VirtualDeviceList([]types.BaseVirtualDevice{ &types.VirtualE1000{}, &types.VirtualE1000e{}, &types.VirtualVmxnet2{}, &types.VirtualVmxnet3{}, &types.VirtualPCNet32{}, &types.VirtualSriovEthernetCard{}, }).Select(func(device types.BaseVirtualDevice) bool { c := device.(types.BaseVirtualEthernetCard).GetVirtualEthernetCard() c.GetVirtualDevice().Key = -1 return true }) }
go
func EthernetCardTypes() VirtualDeviceList { return VirtualDeviceList([]types.BaseVirtualDevice{ &types.VirtualE1000{}, &types.VirtualE1000e{}, &types.VirtualVmxnet2{}, &types.VirtualVmxnet3{}, &types.VirtualPCNet32{}, &types.VirtualSriovEthernetCard{}, }).Select(func(device types.BaseVirtualDevice) bool { c := device.(types.BaseVirtualEthernetCard).GetVirtualEthernetCard() c.GetVirtualDevice().Key = -1 return true }) }
[ "func", "EthernetCardTypes", "(", ")", "VirtualDeviceList", "{", "return", "VirtualDeviceList", "(", "[", "]", "types", ".", "BaseVirtualDevice", "{", "&", "types", ".", "VirtualE1000", "{", "}", ",", "&", "types", ".", "VirtualE1000e", "{", "}", ",", "&", "types", ".", "VirtualVmxnet2", "{", "}", ",", "&", "types", ".", "VirtualVmxnet3", "{", "}", ",", "&", "types", ".", "VirtualPCNet32", "{", "}", ",", "&", "types", ".", "VirtualSriovEthernetCard", "{", "}", ",", "}", ")", ".", "Select", "(", "func", "(", "device", "types", ".", "BaseVirtualDevice", ")", "bool", "{", "c", ":=", "device", ".", "(", "types", ".", "BaseVirtualEthernetCard", ")", ".", "GetVirtualEthernetCard", "(", ")", "\n", "c", ".", "GetVirtualDevice", "(", ")", ".", "Key", "=", "-", "1", "\n", "return", "true", "\n", "}", ")", "\n", "}" ]
// EthernetCardTypes are used for adding a new ethernet card to a VM.
[ "EthernetCardTypes", "are", "used", "for", "adding", "a", "new", "ethernet", "card", "to", "a", "VM", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L60-L73
train
vmware/govmomi
object/virtual_device_list.go
Select
func (l VirtualDeviceList) Select(f func(device types.BaseVirtualDevice) bool) VirtualDeviceList { var found VirtualDeviceList for _, device := range l { if f(device) { found = append(found, device) } } return found }
go
func (l VirtualDeviceList) Select(f func(device types.BaseVirtualDevice) bool) VirtualDeviceList { var found VirtualDeviceList for _, device := range l { if f(device) { found = append(found, device) } } return found }
[ "func", "(", "l", "VirtualDeviceList", ")", "Select", "(", "f", "func", "(", "device", "types", ".", "BaseVirtualDevice", ")", "bool", ")", "VirtualDeviceList", "{", "var", "found", "VirtualDeviceList", "\n", "for", "_", ",", "device", ":=", "range", "l", "{", "if", "f", "(", "device", ")", "{", "found", "=", "append", "(", "found", ",", "device", ")", "\n", "}", "\n", "}", "\n", "return", "found", "\n", "}" ]
// Select returns a new list containing all elements of the list for which the given func returns true.
[ "Select", "returns", "a", "new", "list", "containing", "all", "elements", "of", "the", "list", "for", "which", "the", "given", "func", "returns", "true", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L76-L86
train
vmware/govmomi
object/virtual_device_list.go
SelectByType
func (l VirtualDeviceList) SelectByType(deviceType types.BaseVirtualDevice) VirtualDeviceList { dtype := reflect.TypeOf(deviceType) if dtype == nil { return nil } dname := dtype.Elem().Name() return l.Select(func(device types.BaseVirtualDevice) bool { t := reflect.TypeOf(device) if t == dtype { return true } _, ok := t.Elem().FieldByName(dname) return ok }) }
go
func (l VirtualDeviceList) SelectByType(deviceType types.BaseVirtualDevice) VirtualDeviceList { dtype := reflect.TypeOf(deviceType) if dtype == nil { return nil } dname := dtype.Elem().Name() return l.Select(func(device types.BaseVirtualDevice) bool { t := reflect.TypeOf(device) if t == dtype { return true } _, ok := t.Elem().FieldByName(dname) return ok }) }
[ "func", "(", "l", "VirtualDeviceList", ")", "SelectByType", "(", "deviceType", "types", ".", "BaseVirtualDevice", ")", "VirtualDeviceList", "{", "dtype", ":=", "reflect", ".", "TypeOf", "(", "deviceType", ")", "\n", "if", "dtype", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "dname", ":=", "dtype", ".", "Elem", "(", ")", ".", "Name", "(", ")", "\n", "return", "l", ".", "Select", "(", "func", "(", "device", "types", ".", "BaseVirtualDevice", ")", "bool", "{", "t", ":=", "reflect", ".", "TypeOf", "(", "device", ")", "\n", "if", "t", "==", "dtype", "{", "return", "true", "\n", "}", "\n", "_", ",", "ok", ":=", "t", ".", "Elem", "(", ")", ".", "FieldByName", "(", "dname", ")", "\n", "return", "ok", "\n", "}", ")", "\n", "}" ]
// SelectByType returns a new list with devices that are equal to or extend the given type.
[ "SelectByType", "returns", "a", "new", "list", "with", "devices", "that", "are", "equal", "to", "or", "extend", "the", "given", "type", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L89-L107
train
vmware/govmomi
object/virtual_device_list.go
SelectByBackingInfo
func (l VirtualDeviceList) SelectByBackingInfo(backing types.BaseVirtualDeviceBackingInfo) VirtualDeviceList { t := reflect.TypeOf(backing) return l.Select(func(device types.BaseVirtualDevice) bool { db := device.GetVirtualDevice().Backing if db == nil { return false } if reflect.TypeOf(db) != t { return false } if reflect.ValueOf(backing).IsNil() { // selecting by backing type return true } switch a := db.(type) { case *types.VirtualEthernetCardNetworkBackingInfo: b := backing.(*types.VirtualEthernetCardNetworkBackingInfo) return a.DeviceName == b.DeviceName case *types.VirtualEthernetCardDistributedVirtualPortBackingInfo: b := backing.(*types.VirtualEthernetCardDistributedVirtualPortBackingInfo) return a.Port.SwitchUuid == b.Port.SwitchUuid && a.Port.PortgroupKey == b.Port.PortgroupKey case *types.VirtualDiskFlatVer2BackingInfo: b := backing.(*types.VirtualDiskFlatVer2BackingInfo) if a.Parent != nil && b.Parent != nil { return a.Parent.FileName == b.Parent.FileName } return a.FileName == b.FileName case *types.VirtualSerialPortURIBackingInfo: b := backing.(*types.VirtualSerialPortURIBackingInfo) return a.ServiceURI == b.ServiceURI case types.BaseVirtualDeviceFileBackingInfo: b := backing.(types.BaseVirtualDeviceFileBackingInfo) return a.GetVirtualDeviceFileBackingInfo().FileName == b.GetVirtualDeviceFileBackingInfo().FileName default: return false } }) }
go
func (l VirtualDeviceList) SelectByBackingInfo(backing types.BaseVirtualDeviceBackingInfo) VirtualDeviceList { t := reflect.TypeOf(backing) return l.Select(func(device types.BaseVirtualDevice) bool { db := device.GetVirtualDevice().Backing if db == nil { return false } if reflect.TypeOf(db) != t { return false } if reflect.ValueOf(backing).IsNil() { // selecting by backing type return true } switch a := db.(type) { case *types.VirtualEthernetCardNetworkBackingInfo: b := backing.(*types.VirtualEthernetCardNetworkBackingInfo) return a.DeviceName == b.DeviceName case *types.VirtualEthernetCardDistributedVirtualPortBackingInfo: b := backing.(*types.VirtualEthernetCardDistributedVirtualPortBackingInfo) return a.Port.SwitchUuid == b.Port.SwitchUuid && a.Port.PortgroupKey == b.Port.PortgroupKey case *types.VirtualDiskFlatVer2BackingInfo: b := backing.(*types.VirtualDiskFlatVer2BackingInfo) if a.Parent != nil && b.Parent != nil { return a.Parent.FileName == b.Parent.FileName } return a.FileName == b.FileName case *types.VirtualSerialPortURIBackingInfo: b := backing.(*types.VirtualSerialPortURIBackingInfo) return a.ServiceURI == b.ServiceURI case types.BaseVirtualDeviceFileBackingInfo: b := backing.(types.BaseVirtualDeviceFileBackingInfo) return a.GetVirtualDeviceFileBackingInfo().FileName == b.GetVirtualDeviceFileBackingInfo().FileName default: return false } }) }
[ "func", "(", "l", "VirtualDeviceList", ")", "SelectByBackingInfo", "(", "backing", "types", ".", "BaseVirtualDeviceBackingInfo", ")", "VirtualDeviceList", "{", "t", ":=", "reflect", ".", "TypeOf", "(", "backing", ")", "\n", "return", "l", ".", "Select", "(", "func", "(", "device", "types", ".", "BaseVirtualDevice", ")", "bool", "{", "db", ":=", "device", ".", "GetVirtualDevice", "(", ")", ".", "Backing", "\n", "if", "db", "==", "nil", "{", "return", "false", "\n", "}", "\n", "if", "reflect", ".", "TypeOf", "(", "db", ")", "!=", "t", "{", "return", "false", "\n", "}", "\n", "if", "reflect", ".", "ValueOf", "(", "backing", ")", ".", "IsNil", "(", ")", "{", "return", "true", "\n", "}", "\n", "switch", "a", ":=", "db", ".", "(", "type", ")", "{", "case", "*", "types", ".", "VirtualEthernetCardNetworkBackingInfo", ":", "b", ":=", "backing", ".", "(", "*", "types", ".", "VirtualEthernetCardNetworkBackingInfo", ")", "\n", "return", "a", ".", "DeviceName", "==", "b", ".", "DeviceName", "\n", "case", "*", "types", ".", "VirtualEthernetCardDistributedVirtualPortBackingInfo", ":", "b", ":=", "backing", ".", "(", "*", "types", ".", "VirtualEthernetCardDistributedVirtualPortBackingInfo", ")", "\n", "return", "a", ".", "Port", ".", "SwitchUuid", "==", "b", ".", "Port", ".", "SwitchUuid", "&&", "a", ".", "Port", ".", "PortgroupKey", "==", "b", ".", "Port", ".", "PortgroupKey", "\n", "case", "*", "types", ".", "VirtualDiskFlatVer2BackingInfo", ":", "b", ":=", "backing", ".", "(", "*", "types", ".", "VirtualDiskFlatVer2BackingInfo", ")", "\n", "if", "a", ".", "Parent", "!=", "nil", "&&", "b", ".", "Parent", "!=", "nil", "{", "return", "a", ".", "Parent", ".", "FileName", "==", "b", ".", "Parent", ".", "FileName", "\n", "}", "\n", "return", "a", ".", "FileName", "==", "b", ".", "FileName", "\n", "case", "*", "types", ".", "VirtualSerialPortURIBackingInfo", ":", "b", ":=", "backing", ".", "(", "*", "types", ".", "VirtualSerialPortURIBackingInfo", ")", "\n", "return", "a", ".", "ServiceURI", "==", "b", ".", "ServiceURI", "\n", "case", "types", ".", "BaseVirtualDeviceFileBackingInfo", ":", "b", ":=", "backing", ".", "(", "types", ".", "BaseVirtualDeviceFileBackingInfo", ")", "\n", "return", "a", ".", "GetVirtualDeviceFileBackingInfo", "(", ")", ".", "FileName", "==", "b", ".", "GetVirtualDeviceFileBackingInfo", "(", ")", ".", "FileName", "\n", "default", ":", "return", "false", "\n", "}", "\n", "}", ")", "\n", "}" ]
// SelectByBackingInfo returns a new list with devices matching the given backing info. // If the value of backing is nil, any device with a backing of the same type will be returned.
[ "SelectByBackingInfo", "returns", "a", "new", "list", "with", "devices", "matching", "the", "given", "backing", "info", ".", "If", "the", "value", "of", "backing", "is", "nil", "any", "device", "with", "a", "backing", "of", "the", "same", "type", "will", "be", "returned", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L111-L153
train
vmware/govmomi
object/virtual_device_list.go
Find
func (l VirtualDeviceList) Find(name string) types.BaseVirtualDevice { for _, device := range l { if l.Name(device) == name { return device } } return nil }
go
func (l VirtualDeviceList) Find(name string) types.BaseVirtualDevice { for _, device := range l { if l.Name(device) == name { return device } } return nil }
[ "func", "(", "l", "VirtualDeviceList", ")", "Find", "(", "name", "string", ")", "types", ".", "BaseVirtualDevice", "{", "for", "_", ",", "device", ":=", "range", "l", "{", "if", "l", ".", "Name", "(", "device", ")", "==", "name", "{", "return", "device", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Find returns the device matching the given name.
[ "Find", "returns", "the", "device", "matching", "the", "given", "name", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L156-L163
train
vmware/govmomi
object/virtual_device_list.go
FindByKey
func (l VirtualDeviceList) FindByKey(key int32) types.BaseVirtualDevice { for _, device := range l { if device.GetVirtualDevice().Key == key { return device } } return nil }
go
func (l VirtualDeviceList) FindByKey(key int32) types.BaseVirtualDevice { for _, device := range l { if device.GetVirtualDevice().Key == key { return device } } return nil }
[ "func", "(", "l", "VirtualDeviceList", ")", "FindByKey", "(", "key", "int32", ")", "types", ".", "BaseVirtualDevice", "{", "for", "_", ",", "device", ":=", "range", "l", "{", "if", "device", ".", "GetVirtualDevice", "(", ")", ".", "Key", "==", "key", "{", "return", "device", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// FindByKey returns the device matching the given key.
[ "FindByKey", "returns", "the", "device", "matching", "the", "given", "key", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L166-L173
train
vmware/govmomi
object/virtual_device_list.go
FindIDEController
func (l VirtualDeviceList) FindIDEController(name string) (*types.VirtualIDEController, error) { if name != "" { d := l.Find(name) if d == nil { return nil, fmt.Errorf("device '%s' not found", name) } if c, ok := d.(*types.VirtualIDEController); ok { return c, nil } return nil, fmt.Errorf("%s is not an IDE controller", name) } c := l.PickController((*types.VirtualIDEController)(nil)) if c == nil { return nil, errors.New("no available IDE controller") } return c.(*types.VirtualIDEController), nil }
go
func (l VirtualDeviceList) FindIDEController(name string) (*types.VirtualIDEController, error) { if name != "" { d := l.Find(name) if d == nil { return nil, fmt.Errorf("device '%s' not found", name) } if c, ok := d.(*types.VirtualIDEController); ok { return c, nil } return nil, fmt.Errorf("%s is not an IDE controller", name) } c := l.PickController((*types.VirtualIDEController)(nil)) if c == nil { return nil, errors.New("no available IDE controller") } return c.(*types.VirtualIDEController), nil }
[ "func", "(", "l", "VirtualDeviceList", ")", "FindIDEController", "(", "name", "string", ")", "(", "*", "types", ".", "VirtualIDEController", ",", "error", ")", "{", "if", "name", "!=", "\"\"", "{", "d", ":=", "l", ".", "Find", "(", "name", ")", "\n", "if", "d", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"device '%s' not found\"", ",", "name", ")", "\n", "}", "\n", "if", "c", ",", "ok", ":=", "d", ".", "(", "*", "types", ".", "VirtualIDEController", ")", ";", "ok", "{", "return", "c", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"%s is not an IDE controller\"", ",", "name", ")", "\n", "}", "\n", "c", ":=", "l", ".", "PickController", "(", "(", "*", "types", ".", "VirtualIDEController", ")", "(", "nil", ")", ")", "\n", "if", "c", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"no available IDE controller\"", ")", "\n", "}", "\n", "return", "c", ".", "(", "*", "types", ".", "VirtualIDEController", ")", ",", "nil", "\n", "}" ]
// FindIDEController will find the named IDE controller if given, otherwise will pick an available controller. // An error is returned if the named controller is not found or not an IDE controller. Or, if name is not // given and no available controller can be found.
[ "FindIDEController", "will", "find", "the", "named", "IDE", "controller", "if", "given", "otherwise", "will", "pick", "an", "available", "controller", ".", "An", "error", "is", "returned", "if", "the", "named", "controller", "is", "not", "found", "or", "not", "an", "IDE", "controller", ".", "Or", "if", "name", "is", "not", "given", "and", "no", "available", "controller", "can", "be", "found", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L178-L196
train
vmware/govmomi
object/virtual_device_list.go
CreateIDEController
func (l VirtualDeviceList) CreateIDEController() (types.BaseVirtualDevice, error) { ide := &types.VirtualIDEController{} ide.Key = l.NewKey() return ide, nil }
go
func (l VirtualDeviceList) CreateIDEController() (types.BaseVirtualDevice, error) { ide := &types.VirtualIDEController{} ide.Key = l.NewKey() return ide, nil }
[ "func", "(", "l", "VirtualDeviceList", ")", "CreateIDEController", "(", ")", "(", "types", ".", "BaseVirtualDevice", ",", "error", ")", "{", "ide", ":=", "&", "types", ".", "VirtualIDEController", "{", "}", "\n", "ide", ".", "Key", "=", "l", ".", "NewKey", "(", ")", "\n", "return", "ide", ",", "nil", "\n", "}" ]
// CreateIDEController creates a new IDE controller.
[ "CreateIDEController", "creates", "a", "new", "IDE", "controller", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L199-L203
train
vmware/govmomi
object/virtual_device_list.go
FindSCSIController
func (l VirtualDeviceList) FindSCSIController(name string) (*types.VirtualSCSIController, error) { if name != "" { d := l.Find(name) if d == nil { return nil, fmt.Errorf("device '%s' not found", name) } if c, ok := d.(types.BaseVirtualSCSIController); ok { return c.GetVirtualSCSIController(), nil } return nil, fmt.Errorf("%s is not an SCSI controller", name) } c := l.PickController((*types.VirtualSCSIController)(nil)) if c == nil { return nil, errors.New("no available SCSI controller") } return c.(types.BaseVirtualSCSIController).GetVirtualSCSIController(), nil }
go
func (l VirtualDeviceList) FindSCSIController(name string) (*types.VirtualSCSIController, error) { if name != "" { d := l.Find(name) if d == nil { return nil, fmt.Errorf("device '%s' not found", name) } if c, ok := d.(types.BaseVirtualSCSIController); ok { return c.GetVirtualSCSIController(), nil } return nil, fmt.Errorf("%s is not an SCSI controller", name) } c := l.PickController((*types.VirtualSCSIController)(nil)) if c == nil { return nil, errors.New("no available SCSI controller") } return c.(types.BaseVirtualSCSIController).GetVirtualSCSIController(), nil }
[ "func", "(", "l", "VirtualDeviceList", ")", "FindSCSIController", "(", "name", "string", ")", "(", "*", "types", ".", "VirtualSCSIController", ",", "error", ")", "{", "if", "name", "!=", "\"\"", "{", "d", ":=", "l", ".", "Find", "(", "name", ")", "\n", "if", "d", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"device '%s' not found\"", ",", "name", ")", "\n", "}", "\n", "if", "c", ",", "ok", ":=", "d", ".", "(", "types", ".", "BaseVirtualSCSIController", ")", ";", "ok", "{", "return", "c", ".", "GetVirtualSCSIController", "(", ")", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"%s is not an SCSI controller\"", ",", "name", ")", "\n", "}", "\n", "c", ":=", "l", ".", "PickController", "(", "(", "*", "types", ".", "VirtualSCSIController", ")", "(", "nil", ")", ")", "\n", "if", "c", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"no available SCSI controller\"", ")", "\n", "}", "\n", "return", "c", ".", "(", "types", ".", "BaseVirtualSCSIController", ")", ".", "GetVirtualSCSIController", "(", ")", ",", "nil", "\n", "}" ]
// FindSCSIController will find the named SCSI controller if given, otherwise will pick an available controller. // An error is returned if the named controller is not found or not an SCSI controller. Or, if name is not // given and no available controller can be found.
[ "FindSCSIController", "will", "find", "the", "named", "SCSI", "controller", "if", "given", "otherwise", "will", "pick", "an", "available", "controller", ".", "An", "error", "is", "returned", "if", "the", "named", "controller", "is", "not", "found", "or", "not", "an", "SCSI", "controller", ".", "Or", "if", "name", "is", "not", "given", "and", "no", "available", "controller", "can", "be", "found", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L208-L226
train
vmware/govmomi
object/virtual_device_list.go
CreateSCSIController
func (l VirtualDeviceList) CreateSCSIController(name string) (types.BaseVirtualDevice, error) { ctypes := SCSIControllerTypes() if name == "" || name == "scsi" { name = ctypes.Type(ctypes[0]) } else if name == "virtualscsi" { name = "pvscsi" // ovf VirtualSCSI mapping } found := ctypes.Select(func(device types.BaseVirtualDevice) bool { return l.Type(device) == name }) if len(found) == 0 { return nil, fmt.Errorf("unknown SCSI controller type '%s'", name) } c, ok := found[0].(types.BaseVirtualSCSIController) if !ok { return nil, fmt.Errorf("invalid SCSI controller type '%s'", name) } scsi := c.GetVirtualSCSIController() scsi.BusNumber = l.newSCSIBusNumber() scsi.Key = l.NewKey() scsi.ScsiCtlrUnitNumber = 7 return c.(types.BaseVirtualDevice), nil }
go
func (l VirtualDeviceList) CreateSCSIController(name string) (types.BaseVirtualDevice, error) { ctypes := SCSIControllerTypes() if name == "" || name == "scsi" { name = ctypes.Type(ctypes[0]) } else if name == "virtualscsi" { name = "pvscsi" // ovf VirtualSCSI mapping } found := ctypes.Select(func(device types.BaseVirtualDevice) bool { return l.Type(device) == name }) if len(found) == 0 { return nil, fmt.Errorf("unknown SCSI controller type '%s'", name) } c, ok := found[0].(types.BaseVirtualSCSIController) if !ok { return nil, fmt.Errorf("invalid SCSI controller type '%s'", name) } scsi := c.GetVirtualSCSIController() scsi.BusNumber = l.newSCSIBusNumber() scsi.Key = l.NewKey() scsi.ScsiCtlrUnitNumber = 7 return c.(types.BaseVirtualDevice), nil }
[ "func", "(", "l", "VirtualDeviceList", ")", "CreateSCSIController", "(", "name", "string", ")", "(", "types", ".", "BaseVirtualDevice", ",", "error", ")", "{", "ctypes", ":=", "SCSIControllerTypes", "(", ")", "\n", "if", "name", "==", "\"\"", "||", "name", "==", "\"scsi\"", "{", "name", "=", "ctypes", ".", "Type", "(", "ctypes", "[", "0", "]", ")", "\n", "}", "else", "if", "name", "==", "\"virtualscsi\"", "{", "name", "=", "\"pvscsi\"", "\n", "}", "\n", "found", ":=", "ctypes", ".", "Select", "(", "func", "(", "device", "types", ".", "BaseVirtualDevice", ")", "bool", "{", "return", "l", ".", "Type", "(", "device", ")", "==", "name", "\n", "}", ")", "\n", "if", "len", "(", "found", ")", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"unknown SCSI controller type '%s'\"", ",", "name", ")", "\n", "}", "\n", "c", ",", "ok", ":=", "found", "[", "0", "]", ".", "(", "types", ".", "BaseVirtualSCSIController", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"invalid SCSI controller type '%s'\"", ",", "name", ")", "\n", "}", "\n", "scsi", ":=", "c", ".", "GetVirtualSCSIController", "(", ")", "\n", "scsi", ".", "BusNumber", "=", "l", ".", "newSCSIBusNumber", "(", ")", "\n", "scsi", ".", "Key", "=", "l", ".", "NewKey", "(", ")", "\n", "scsi", ".", "ScsiCtlrUnitNumber", "=", "7", "\n", "return", "c", ".", "(", "types", ".", "BaseVirtualDevice", ")", ",", "nil", "\n", "}" ]
// CreateSCSIController creates a new SCSI controller of type name if given, otherwise defaults to lsilogic.
[ "CreateSCSIController", "creates", "a", "new", "SCSI", "controller", "of", "type", "name", "if", "given", "otherwise", "defaults", "to", "lsilogic", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L229-L256
train
vmware/govmomi
object/virtual_device_list.go
newSCSIBusNumber
func (l VirtualDeviceList) newSCSIBusNumber() int32 { var used []int for _, d := range l.SelectByType((*types.VirtualSCSIController)(nil)) { num := d.(types.BaseVirtualSCSIController).GetVirtualSCSIController().BusNumber if num >= 0 { used = append(used, int(num)) } // else caller is creating a new vm using SCSIControllerTypes } sort.Ints(used) for i, n := range scsiBusNumbers { if i == len(used) || n != used[i] { return int32(n) } } return -1 }
go
func (l VirtualDeviceList) newSCSIBusNumber() int32 { var used []int for _, d := range l.SelectByType((*types.VirtualSCSIController)(nil)) { num := d.(types.BaseVirtualSCSIController).GetVirtualSCSIController().BusNumber if num >= 0 { used = append(used, int(num)) } // else caller is creating a new vm using SCSIControllerTypes } sort.Ints(used) for i, n := range scsiBusNumbers { if i == len(used) || n != used[i] { return int32(n) } } return -1 }
[ "func", "(", "l", "VirtualDeviceList", ")", "newSCSIBusNumber", "(", ")", "int32", "{", "var", "used", "[", "]", "int", "\n", "for", "_", ",", "d", ":=", "range", "l", ".", "SelectByType", "(", "(", "*", "types", ".", "VirtualSCSIController", ")", "(", "nil", ")", ")", "{", "num", ":=", "d", ".", "(", "types", ".", "BaseVirtualSCSIController", ")", ".", "GetVirtualSCSIController", "(", ")", ".", "BusNumber", "\n", "if", "num", ">=", "0", "{", "used", "=", "append", "(", "used", ",", "int", "(", "num", ")", ")", "\n", "}", "\n", "}", "\n", "sort", ".", "Ints", "(", "used", ")", "\n", "for", "i", ",", "n", ":=", "range", "scsiBusNumbers", "{", "if", "i", "==", "len", "(", "used", ")", "||", "n", "!=", "used", "[", "i", "]", "{", "return", "int32", "(", "n", ")", "\n", "}", "\n", "}", "\n", "return", "-", "1", "\n", "}" ]
// newSCSIBusNumber returns the bus number to use for adding a new SCSI bus device. // -1 is returned if there are no bus numbers available.
[ "newSCSIBusNumber", "returns", "the", "bus", "number", "to", "use", "for", "adding", "a", "new", "SCSI", "bus", "device", ".", "-", "1", "is", "returned", "if", "there", "are", "no", "bus", "numbers", "available", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L262-L281
train
vmware/govmomi
object/virtual_device_list.go
CreateNVMEController
func (l VirtualDeviceList) CreateNVMEController() (types.BaseVirtualDevice, error) { nvme := &types.VirtualNVMEController{} nvme.BusNumber = l.newNVMEBusNumber() nvme.Key = l.NewKey() return nvme, nil }
go
func (l VirtualDeviceList) CreateNVMEController() (types.BaseVirtualDevice, error) { nvme := &types.VirtualNVMEController{} nvme.BusNumber = l.newNVMEBusNumber() nvme.Key = l.NewKey() return nvme, nil }
[ "func", "(", "l", "VirtualDeviceList", ")", "CreateNVMEController", "(", ")", "(", "types", ".", "BaseVirtualDevice", ",", "error", ")", "{", "nvme", ":=", "&", "types", ".", "VirtualNVMEController", "{", "}", "\n", "nvme", ".", "BusNumber", "=", "l", ".", "newNVMEBusNumber", "(", ")", "\n", "nvme", ".", "Key", "=", "l", ".", "NewKey", "(", ")", "\n", "return", "nvme", ",", "nil", "\n", "}" ]
// CreateNVMEController creates a new NVMWE controller.
[ "CreateNVMEController", "creates", "a", "new", "NVMWE", "controller", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L307-L313
train
vmware/govmomi
object/virtual_device_list.go
newNVMEBusNumber
func (l VirtualDeviceList) newNVMEBusNumber() int32 { var used []int for _, d := range l.SelectByType((*types.VirtualNVMEController)(nil)) { num := d.(types.BaseVirtualController).GetVirtualController().BusNumber if num >= 0 { used = append(used, int(num)) } // else caller is creating a new vm using NVMEControllerTypes } sort.Ints(used) for i, n := range nvmeBusNumbers { if i == len(used) || n != used[i] { return int32(n) } } return -1 }
go
func (l VirtualDeviceList) newNVMEBusNumber() int32 { var used []int for _, d := range l.SelectByType((*types.VirtualNVMEController)(nil)) { num := d.(types.BaseVirtualController).GetVirtualController().BusNumber if num >= 0 { used = append(used, int(num)) } // else caller is creating a new vm using NVMEControllerTypes } sort.Ints(used) for i, n := range nvmeBusNumbers { if i == len(used) || n != used[i] { return int32(n) } } return -1 }
[ "func", "(", "l", "VirtualDeviceList", ")", "newNVMEBusNumber", "(", ")", "int32", "{", "var", "used", "[", "]", "int", "\n", "for", "_", ",", "d", ":=", "range", "l", ".", "SelectByType", "(", "(", "*", "types", ".", "VirtualNVMEController", ")", "(", "nil", ")", ")", "{", "num", ":=", "d", ".", "(", "types", ".", "BaseVirtualController", ")", ".", "GetVirtualController", "(", ")", ".", "BusNumber", "\n", "if", "num", ">=", "0", "{", "used", "=", "append", "(", "used", ",", "int", "(", "num", ")", ")", "\n", "}", "\n", "}", "\n", "sort", ".", "Ints", "(", "used", ")", "\n", "for", "i", ",", "n", ":=", "range", "nvmeBusNumbers", "{", "if", "i", "==", "len", "(", "used", ")", "||", "n", "!=", "used", "[", "i", "]", "{", "return", "int32", "(", "n", ")", "\n", "}", "\n", "}", "\n", "return", "-", "1", "\n", "}" ]
// newNVMEBusNumber returns the bus number to use for adding a new NVME bus device. // -1 is returned if there are no bus numbers available.
[ "newNVMEBusNumber", "returns", "the", "bus", "number", "to", "use", "for", "adding", "a", "new", "NVME", "bus", "device", ".", "-", "1", "is", "returned", "if", "there", "are", "no", "bus", "numbers", "available", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L319-L338
train
vmware/govmomi
object/virtual_device_list.go
FindDiskController
func (l VirtualDeviceList) FindDiskController(name string) (types.BaseVirtualController, error) { switch { case name == "ide": return l.FindIDEController("") case name == "scsi" || name == "": return l.FindSCSIController("") case name == "nvme": return l.FindNVMEController("") default: if c, ok := l.Find(name).(types.BaseVirtualController); ok { return c, nil } return nil, fmt.Errorf("%s is not a valid controller", name) } }
go
func (l VirtualDeviceList) FindDiskController(name string) (types.BaseVirtualController, error) { switch { case name == "ide": return l.FindIDEController("") case name == "scsi" || name == "": return l.FindSCSIController("") case name == "nvme": return l.FindNVMEController("") default: if c, ok := l.Find(name).(types.BaseVirtualController); ok { return c, nil } return nil, fmt.Errorf("%s is not a valid controller", name) } }
[ "func", "(", "l", "VirtualDeviceList", ")", "FindDiskController", "(", "name", "string", ")", "(", "types", ".", "BaseVirtualController", ",", "error", ")", "{", "switch", "{", "case", "name", "==", "\"ide\"", ":", "return", "l", ".", "FindIDEController", "(", "\"\"", ")", "\n", "case", "name", "==", "\"scsi\"", "||", "name", "==", "\"\"", ":", "return", "l", ".", "FindSCSIController", "(", "\"\"", ")", "\n", "case", "name", "==", "\"nvme\"", ":", "return", "l", ".", "FindNVMEController", "(", "\"\"", ")", "\n", "default", ":", "if", "c", ",", "ok", ":=", "l", ".", "Find", "(", "name", ")", ".", "(", "types", ".", "BaseVirtualController", ")", ";", "ok", "{", "return", "c", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"%s is not a valid controller\"", ",", "name", ")", "\n", "}", "\n", "}" ]
// FindDiskController will find an existing ide or scsi disk controller.
[ "FindDiskController", "will", "find", "an", "existing", "ide", "or", "scsi", "disk", "controller", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L341-L355
train
vmware/govmomi
object/virtual_device_list.go
newUnitNumber
func (l VirtualDeviceList) newUnitNumber(c types.BaseVirtualController) int32 { units := make([]bool, 30) switch sc := c.(type) { case types.BaseVirtualSCSIController: // The SCSI controller sits on its own bus units[sc.GetVirtualSCSIController().ScsiCtlrUnitNumber] = true } key := c.GetVirtualController().Key for _, device := range l { d := device.GetVirtualDevice() if d.ControllerKey == key && d.UnitNumber != nil { units[int(*d.UnitNumber)] = true } } for unit, used := range units { if !used { return int32(unit) } } return -1 }
go
func (l VirtualDeviceList) newUnitNumber(c types.BaseVirtualController) int32 { units := make([]bool, 30) switch sc := c.(type) { case types.BaseVirtualSCSIController: // The SCSI controller sits on its own bus units[sc.GetVirtualSCSIController().ScsiCtlrUnitNumber] = true } key := c.GetVirtualController().Key for _, device := range l { d := device.GetVirtualDevice() if d.ControllerKey == key && d.UnitNumber != nil { units[int(*d.UnitNumber)] = true } } for unit, used := range units { if !used { return int32(unit) } } return -1 }
[ "func", "(", "l", "VirtualDeviceList", ")", "newUnitNumber", "(", "c", "types", ".", "BaseVirtualController", ")", "int32", "{", "units", ":=", "make", "(", "[", "]", "bool", ",", "30", ")", "\n", "switch", "sc", ":=", "c", ".", "(", "type", ")", "{", "case", "types", ".", "BaseVirtualSCSIController", ":", "units", "[", "sc", ".", "GetVirtualSCSIController", "(", ")", ".", "ScsiCtlrUnitNumber", "]", "=", "true", "\n", "}", "\n", "key", ":=", "c", ".", "GetVirtualController", "(", ")", ".", "Key", "\n", "for", "_", ",", "device", ":=", "range", "l", "{", "d", ":=", "device", ".", "GetVirtualDevice", "(", ")", "\n", "if", "d", ".", "ControllerKey", "==", "key", "&&", "d", ".", "UnitNumber", "!=", "nil", "{", "units", "[", "int", "(", "*", "d", ".", "UnitNumber", ")", "]", "=", "true", "\n", "}", "\n", "}", "\n", "for", "unit", ",", "used", ":=", "range", "units", "{", "if", "!", "used", "{", "return", "int32", "(", "unit", ")", "\n", "}", "\n", "}", "\n", "return", "-", "1", "\n", "}" ]
// newUnitNumber returns the unit number to use for attaching a new device to the given controller.
[ "newUnitNumber", "returns", "the", "unit", "number", "to", "use", "for", "attaching", "a", "new", "device", "to", "the", "given", "controller", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L383-L409
train
vmware/govmomi
object/virtual_device_list.go
AssignController
func (l VirtualDeviceList) AssignController(device types.BaseVirtualDevice, c types.BaseVirtualController) { d := device.GetVirtualDevice() d.ControllerKey = c.GetVirtualController().Key d.UnitNumber = new(int32) *d.UnitNumber = l.newUnitNumber(c) if d.Key == 0 { d.Key = -1 } }
go
func (l VirtualDeviceList) AssignController(device types.BaseVirtualDevice, c types.BaseVirtualController) { d := device.GetVirtualDevice() d.ControllerKey = c.GetVirtualController().Key d.UnitNumber = new(int32) *d.UnitNumber = l.newUnitNumber(c) if d.Key == 0 { d.Key = -1 } }
[ "func", "(", "l", "VirtualDeviceList", ")", "AssignController", "(", "device", "types", ".", "BaseVirtualDevice", ",", "c", "types", ".", "BaseVirtualController", ")", "{", "d", ":=", "device", ".", "GetVirtualDevice", "(", ")", "\n", "d", ".", "ControllerKey", "=", "c", ".", "GetVirtualController", "(", ")", ".", "Key", "\n", "d", ".", "UnitNumber", "=", "new", "(", "int32", ")", "\n", "*", "d", ".", "UnitNumber", "=", "l", ".", "newUnitNumber", "(", "c", ")", "\n", "if", "d", ".", "Key", "==", "0", "{", "d", ".", "Key", "=", "-", "1", "\n", "}", "\n", "}" ]
// AssignController assigns a device to a controller.
[ "AssignController", "assigns", "a", "device", "to", "a", "controller", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L430-L438
train
vmware/govmomi
object/virtual_device_list.go
CreateDisk
func (l VirtualDeviceList) CreateDisk(c types.BaseVirtualController, ds types.ManagedObjectReference, name string) *types.VirtualDisk { // If name is not specified, one will be chosen for you. // But if when given, make sure it ends in .vmdk, otherwise it will be treated as a directory. if len(name) > 0 && filepath.Ext(name) != ".vmdk" { name += ".vmdk" } device := &types.VirtualDisk{ VirtualDevice: types.VirtualDevice{ Backing: &types.VirtualDiskFlatVer2BackingInfo{ DiskMode: string(types.VirtualDiskModePersistent), ThinProvisioned: types.NewBool(true), VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{ FileName: name, Datastore: &ds, }, }, }, } l.AssignController(device, c) return device }
go
func (l VirtualDeviceList) CreateDisk(c types.BaseVirtualController, ds types.ManagedObjectReference, name string) *types.VirtualDisk { // If name is not specified, one will be chosen for you. // But if when given, make sure it ends in .vmdk, otherwise it will be treated as a directory. if len(name) > 0 && filepath.Ext(name) != ".vmdk" { name += ".vmdk" } device := &types.VirtualDisk{ VirtualDevice: types.VirtualDevice{ Backing: &types.VirtualDiskFlatVer2BackingInfo{ DiskMode: string(types.VirtualDiskModePersistent), ThinProvisioned: types.NewBool(true), VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{ FileName: name, Datastore: &ds, }, }, }, } l.AssignController(device, c) return device }
[ "func", "(", "l", "VirtualDeviceList", ")", "CreateDisk", "(", "c", "types", ".", "BaseVirtualController", ",", "ds", "types", ".", "ManagedObjectReference", ",", "name", "string", ")", "*", "types", ".", "VirtualDisk", "{", "if", "len", "(", "name", ")", ">", "0", "&&", "filepath", ".", "Ext", "(", "name", ")", "!=", "\".vmdk\"", "{", "name", "+=", "\".vmdk\"", "\n", "}", "\n", "device", ":=", "&", "types", ".", "VirtualDisk", "{", "VirtualDevice", ":", "types", ".", "VirtualDevice", "{", "Backing", ":", "&", "types", ".", "VirtualDiskFlatVer2BackingInfo", "{", "DiskMode", ":", "string", "(", "types", ".", "VirtualDiskModePersistent", ")", ",", "ThinProvisioned", ":", "types", ".", "NewBool", "(", "true", ")", ",", "VirtualDeviceFileBackingInfo", ":", "types", ".", "VirtualDeviceFileBackingInfo", "{", "FileName", ":", "name", ",", "Datastore", ":", "&", "ds", ",", "}", ",", "}", ",", "}", ",", "}", "\n", "l", ".", "AssignController", "(", "device", ",", "c", ")", "\n", "return", "device", "\n", "}" ]
// CreateDisk creates a new VirtualDisk device which can be added to a VM.
[ "CreateDisk", "creates", "a", "new", "VirtualDisk", "device", "which", "can", "be", "added", "to", "a", "VM", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L441-L463
train
vmware/govmomi
object/virtual_device_list.go
ChildDisk
func (l VirtualDeviceList) ChildDisk(parent *types.VirtualDisk) *types.VirtualDisk { disk := *parent backing := disk.Backing.(*types.VirtualDiskFlatVer2BackingInfo) p := new(DatastorePath) p.FromString(backing.FileName) p.Path = "" // Use specified disk as parent backing to a new disk. disk.Backing = &types.VirtualDiskFlatVer2BackingInfo{ VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{ FileName: p.String(), Datastore: backing.Datastore, }, Parent: backing, DiskMode: backing.DiskMode, ThinProvisioned: backing.ThinProvisioned, } return &disk }
go
func (l VirtualDeviceList) ChildDisk(parent *types.VirtualDisk) *types.VirtualDisk { disk := *parent backing := disk.Backing.(*types.VirtualDiskFlatVer2BackingInfo) p := new(DatastorePath) p.FromString(backing.FileName) p.Path = "" // Use specified disk as parent backing to a new disk. disk.Backing = &types.VirtualDiskFlatVer2BackingInfo{ VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{ FileName: p.String(), Datastore: backing.Datastore, }, Parent: backing, DiskMode: backing.DiskMode, ThinProvisioned: backing.ThinProvisioned, } return &disk }
[ "func", "(", "l", "VirtualDeviceList", ")", "ChildDisk", "(", "parent", "*", "types", ".", "VirtualDisk", ")", "*", "types", ".", "VirtualDisk", "{", "disk", ":=", "*", "parent", "\n", "backing", ":=", "disk", ".", "Backing", ".", "(", "*", "types", ".", "VirtualDiskFlatVer2BackingInfo", ")", "\n", "p", ":=", "new", "(", "DatastorePath", ")", "\n", "p", ".", "FromString", "(", "backing", ".", "FileName", ")", "\n", "p", ".", "Path", "=", "\"\"", "\n", "disk", ".", "Backing", "=", "&", "types", ".", "VirtualDiskFlatVer2BackingInfo", "{", "VirtualDeviceFileBackingInfo", ":", "types", ".", "VirtualDeviceFileBackingInfo", "{", "FileName", ":", "p", ".", "String", "(", ")", ",", "Datastore", ":", "backing", ".", "Datastore", ",", "}", ",", "Parent", ":", "backing", ",", "DiskMode", ":", "backing", ".", "DiskMode", ",", "ThinProvisioned", ":", "backing", ".", "ThinProvisioned", ",", "}", "\n", "return", "&", "disk", "\n", "}" ]
// ChildDisk creates a new VirtualDisk device, linked to the given parent disk, which can be added to a VM.
[ "ChildDisk", "creates", "a", "new", "VirtualDisk", "device", "linked", "to", "the", "given", "parent", "disk", "which", "can", "be", "added", "to", "a", "VM", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L466-L485
train
vmware/govmomi
object/virtual_device_list.go
Connect
func (l VirtualDeviceList) Connect(device types.BaseVirtualDevice) error { return l.connectivity(device, true) }
go
func (l VirtualDeviceList) Connect(device types.BaseVirtualDevice) error { return l.connectivity(device, true) }
[ "func", "(", "l", "VirtualDeviceList", ")", "Connect", "(", "device", "types", ".", "BaseVirtualDevice", ")", "error", "{", "return", "l", ".", "connectivity", "(", "device", ",", "true", ")", "\n", "}" ]
// Connect changes the device to connected, returns an error if the device is not connectable.
[ "Connect", "changes", "the", "device", "to", "connected", "returns", "an", "error", "if", "the", "device", "is", "not", "connectable", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L500-L502
train
vmware/govmomi
object/virtual_device_list.go
Disconnect
func (l VirtualDeviceList) Disconnect(device types.BaseVirtualDevice) error { return l.connectivity(device, false) }
go
func (l VirtualDeviceList) Disconnect(device types.BaseVirtualDevice) error { return l.connectivity(device, false) }
[ "func", "(", "l", "VirtualDeviceList", ")", "Disconnect", "(", "device", "types", ".", "BaseVirtualDevice", ")", "error", "{", "return", "l", ".", "connectivity", "(", "device", ",", "false", ")", "\n", "}" ]
// Disconnect changes the device to disconnected, returns an error if the device is not connectable.
[ "Disconnect", "changes", "the", "device", "to", "disconnected", "returns", "an", "error", "if", "the", "device", "is", "not", "connectable", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L505-L507
train
vmware/govmomi
object/virtual_device_list.go
FindCdrom
func (l VirtualDeviceList) FindCdrom(name string) (*types.VirtualCdrom, error) { if name != "" { d := l.Find(name) if d == nil { return nil, fmt.Errorf("device '%s' not found", name) } if c, ok := d.(*types.VirtualCdrom); ok { return c, nil } return nil, fmt.Errorf("%s is not a cdrom device", name) } c := l.SelectByType((*types.VirtualCdrom)(nil)) if len(c) == 0 { return nil, errors.New("no cdrom device found") } return c[0].(*types.VirtualCdrom), nil }
go
func (l VirtualDeviceList) FindCdrom(name string) (*types.VirtualCdrom, error) { if name != "" { d := l.Find(name) if d == nil { return nil, fmt.Errorf("device '%s' not found", name) } if c, ok := d.(*types.VirtualCdrom); ok { return c, nil } return nil, fmt.Errorf("%s is not a cdrom device", name) } c := l.SelectByType((*types.VirtualCdrom)(nil)) if len(c) == 0 { return nil, errors.New("no cdrom device found") } return c[0].(*types.VirtualCdrom), nil }
[ "func", "(", "l", "VirtualDeviceList", ")", "FindCdrom", "(", "name", "string", ")", "(", "*", "types", ".", "VirtualCdrom", ",", "error", ")", "{", "if", "name", "!=", "\"\"", "{", "d", ":=", "l", ".", "Find", "(", "name", ")", "\n", "if", "d", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"device '%s' not found\"", ",", "name", ")", "\n", "}", "\n", "if", "c", ",", "ok", ":=", "d", ".", "(", "*", "types", ".", "VirtualCdrom", ")", ";", "ok", "{", "return", "c", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"%s is not a cdrom device\"", ",", "name", ")", "\n", "}", "\n", "c", ":=", "l", ".", "SelectByType", "(", "(", "*", "types", ".", "VirtualCdrom", ")", "(", "nil", ")", ")", "\n", "if", "len", "(", "c", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"no cdrom device found\"", ")", "\n", "}", "\n", "return", "c", "[", "0", "]", ".", "(", "*", "types", ".", "VirtualCdrom", ")", ",", "nil", "\n", "}" ]
// FindCdrom finds a cdrom device with the given name, defaulting to the first cdrom device if any.
[ "FindCdrom", "finds", "a", "cdrom", "device", "with", "the", "given", "name", "defaulting", "to", "the", "first", "cdrom", "device", "if", "any", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L510-L528
train