repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
hashicorp/serf
serf/serf.go
checkQueueDepth
func (s *Serf) checkQueueDepth(name string, queue *memberlist.TransmitLimitedQueue) { for { select { case <-time.After(s.config.QueueCheckInterval): numq := queue.NumQueued() metrics.AddSample([]string{"serf", "queue", name}, float32(numq)) if numq >= s.config.QueueDepthWarning { s.logger.Printf("[WARN] serf: %s queue depth: %d", name, numq) } if max := s.getQueueMax(); numq > max { s.logger.Printf("[WARN] serf: %s queue depth (%d) exceeds limit (%d), dropping messages!", name, numq, max) queue.Prune(max) } case <-s.shutdownCh: return } } }
go
func (s *Serf) checkQueueDepth(name string, queue *memberlist.TransmitLimitedQueue) { for { select { case <-time.After(s.config.QueueCheckInterval): numq := queue.NumQueued() metrics.AddSample([]string{"serf", "queue", name}, float32(numq)) if numq >= s.config.QueueDepthWarning { s.logger.Printf("[WARN] serf: %s queue depth: %d", name, numq) } if max := s.getQueueMax(); numq > max { s.logger.Printf("[WARN] serf: %s queue depth (%d) exceeds limit (%d), dropping messages!", name, numq, max) queue.Prune(max) } case <-s.shutdownCh: return } } }
[ "func", "(", "s", "*", "Serf", ")", "checkQueueDepth", "(", "name", "string", ",", "queue", "*", "memberlist", ".", "TransmitLimitedQueue", ")", "{", "for", "{", "select", "{", "case", "<-", "time", ".", "After", "(", "s", ".", "config", ".", "QueueCheckInterval", ")", ":", "numq", ":=", "queue", ".", "NumQueued", "(", ")", "\n", "metrics", ".", "AddSample", "(", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "name", "}", ",", "float32", "(", "numq", ")", ")", "\n", "if", "numq", ">=", "s", ".", "config", ".", "QueueDepthWarning", "{", "s", ".", "logger", ".", "Printf", "(", "\"", "\"", ",", "name", ",", "numq", ")", "\n", "}", "\n", "if", "max", ":=", "s", ".", "getQueueMax", "(", ")", ";", "numq", ">", "max", "{", "s", ".", "logger", ".", "Printf", "(", "\"", "\"", ",", "name", ",", "numq", ",", "max", ")", "\n", "queue", ".", "Prune", "(", "max", ")", "\n", "}", "\n", "case", "<-", "s", ".", "shutdownCh", ":", "return", "\n", "}", "\n", "}", "\n", "}" ]
// checkQueueDepth periodically checks the size of a queue to see if // it is too large
[ "checkQueueDepth", "periodically", "checks", "the", "size", "of", "a", "queue", "to", "see", "if", "it", "is", "too", "large" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L1576-L1594
train
hashicorp/serf
serf/serf.go
removeOldMember
func removeOldMember(old []*memberState, name string) []*memberState { for i, m := range old { if m.Name == name { n := len(old) old[i], old[n-1] = old[n-1], nil return old[:n-1] } } return old }
go
func removeOldMember(old []*memberState, name string) []*memberState { for i, m := range old { if m.Name == name { n := len(old) old[i], old[n-1] = old[n-1], nil return old[:n-1] } } return old }
[ "func", "removeOldMember", "(", "old", "[", "]", "*", "memberState", ",", "name", "string", ")", "[", "]", "*", "memberState", "{", "for", "i", ",", "m", ":=", "range", "old", "{", "if", "m", ".", "Name", "==", "name", "{", "n", ":=", "len", "(", "old", ")", "\n", "old", "[", "i", "]", ",", "old", "[", "n", "-", "1", "]", "=", "old", "[", "n", "-", "1", "]", ",", "nil", "\n", "return", "old", "[", ":", "n", "-", "1", "]", "\n", "}", "\n", "}", "\n\n", "return", "old", "\n", "}" ]
// removeOldMember is used to remove an old member from a list of old // members.
[ "removeOldMember", "is", "used", "to", "remove", "an", "old", "member", "from", "a", "list", "of", "old", "members", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L1598-L1608
train
hashicorp/serf
serf/serf.go
reapIntents
func reapIntents(intents map[string]nodeIntent, now time.Time, timeout time.Duration) { for node, intent := range intents { if now.Sub(intent.WallTime) > timeout { delete(intents, node) } } }
go
func reapIntents(intents map[string]nodeIntent, now time.Time, timeout time.Duration) { for node, intent := range intents { if now.Sub(intent.WallTime) > timeout { delete(intents, node) } } }
[ "func", "reapIntents", "(", "intents", "map", "[", "string", "]", "nodeIntent", ",", "now", "time", ".", "Time", ",", "timeout", "time", ".", "Duration", ")", "{", "for", "node", ",", "intent", ":=", "range", "intents", "{", "if", "now", ".", "Sub", "(", "intent", ".", "WallTime", ")", ">", "timeout", "{", "delete", "(", "intents", ",", "node", ")", "\n", "}", "\n", "}", "\n", "}" ]
// reapIntents clears out any intents that are older than the timeout. Make sure // the memberLock is held when passing in the Serf instance's recentIntents // member.
[ "reapIntents", "clears", "out", "any", "intents", "that", "are", "older", "than", "the", "timeout", ".", "Make", "sure", "the", "memberLock", "is", "held", "when", "passing", "in", "the", "Serf", "instance", "s", "recentIntents", "member", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L1613-L1619
train
hashicorp/serf
serf/serf.go
upsertIntent
func upsertIntent(intents map[string]nodeIntent, node string, itype messageType, ltime LamportTime, stamper func() time.Time) bool { if intent, ok := intents[node]; !ok || ltime > intent.LTime { intents[node] = nodeIntent{ Type: itype, WallTime: stamper(), LTime: ltime, } return true } return false }
go
func upsertIntent(intents map[string]nodeIntent, node string, itype messageType, ltime LamportTime, stamper func() time.Time) bool { if intent, ok := intents[node]; !ok || ltime > intent.LTime { intents[node] = nodeIntent{ Type: itype, WallTime: stamper(), LTime: ltime, } return true } return false }
[ "func", "upsertIntent", "(", "intents", "map", "[", "string", "]", "nodeIntent", ",", "node", "string", ",", "itype", "messageType", ",", "ltime", "LamportTime", ",", "stamper", "func", "(", ")", "time", ".", "Time", ")", "bool", "{", "if", "intent", ",", "ok", ":=", "intents", "[", "node", "]", ";", "!", "ok", "||", "ltime", ">", "intent", ".", "LTime", "{", "intents", "[", "node", "]", "=", "nodeIntent", "{", "Type", ":", "itype", ",", "WallTime", ":", "stamper", "(", ")", ",", "LTime", ":", "ltime", ",", "}", "\n", "return", "true", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// upsertIntent will update an existing intent with the supplied Lamport time, // or create a new entry. This will return true if a new entry was added. The // stamper is used to capture the wall clock time for expiring these buffered // intents. Make sure the memberLock is held when passing in the Serf instance's // recentIntents member.
[ "upsertIntent", "will", "update", "an", "existing", "intent", "with", "the", "supplied", "Lamport", "time", "or", "create", "a", "new", "entry", ".", "This", "will", "return", "true", "if", "a", "new", "entry", "was", "added", ".", "The", "stamper", "is", "used", "to", "capture", "the", "wall", "clock", "time", "for", "expiring", "these", "buffered", "intents", ".", "Make", "sure", "the", "memberLock", "is", "held", "when", "passing", "in", "the", "Serf", "instance", "s", "recentIntents", "member", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L1626-L1638
train
hashicorp/serf
serf/serf.go
recentIntent
func recentIntent(intents map[string]nodeIntent, node string, itype messageType) (LamportTime, bool) { if intent, ok := intents[node]; ok && intent.Type == itype { return intent.LTime, true } return LamportTime(0), false }
go
func recentIntent(intents map[string]nodeIntent, node string, itype messageType) (LamportTime, bool) { if intent, ok := intents[node]; ok && intent.Type == itype { return intent.LTime, true } return LamportTime(0), false }
[ "func", "recentIntent", "(", "intents", "map", "[", "string", "]", "nodeIntent", ",", "node", "string", ",", "itype", "messageType", ")", "(", "LamportTime", ",", "bool", ")", "{", "if", "intent", ",", "ok", ":=", "intents", "[", "node", "]", ";", "ok", "&&", "intent", ".", "Type", "==", "itype", "{", "return", "intent", ".", "LTime", ",", "true", "\n", "}", "\n\n", "return", "LamportTime", "(", "0", ")", ",", "false", "\n", "}" ]
// recentIntent checks the recent intent buffer for a matching entry for a given // node, and returns the Lamport time, if an intent is present, indicated by the // returned boolean. Make sure the memberLock is held for read when passing in // the Serf instance's recentIntents member.
[ "recentIntent", "checks", "the", "recent", "intent", "buffer", "for", "a", "matching", "entry", "for", "a", "given", "node", "and", "returns", "the", "Lamport", "time", "if", "an", "intent", "is", "present", "indicated", "by", "the", "returned", "boolean", ".", "Make", "sure", "the", "memberLock", "is", "held", "for", "read", "when", "passing", "in", "the", "Serf", "instance", "s", "recentIntents", "member", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L1644-L1650
train
hashicorp/serf
serf/serf.go
handleRejoin
func (s *Serf) handleRejoin(previous []*PreviousNode) { for _, prev := range previous { // Do not attempt to join ourself if prev.Name == s.config.NodeName { continue } s.logger.Printf("[INFO] serf: Attempting re-join to previously known node: %s", prev) _, err := s.memberlist.Join([]string{prev.Addr}) if err == nil { s.logger.Printf("[INFO] serf: Re-joined to previously known node: %s", prev) return } } s.logger.Printf("[WARN] serf: Failed to re-join any previously known node") }
go
func (s *Serf) handleRejoin(previous []*PreviousNode) { for _, prev := range previous { // Do not attempt to join ourself if prev.Name == s.config.NodeName { continue } s.logger.Printf("[INFO] serf: Attempting re-join to previously known node: %s", prev) _, err := s.memberlist.Join([]string{prev.Addr}) if err == nil { s.logger.Printf("[INFO] serf: Re-joined to previously known node: %s", prev) return } } s.logger.Printf("[WARN] serf: Failed to re-join any previously known node") }
[ "func", "(", "s", "*", "Serf", ")", "handleRejoin", "(", "previous", "[", "]", "*", "PreviousNode", ")", "{", "for", "_", ",", "prev", ":=", "range", "previous", "{", "// Do not attempt to join ourself", "if", "prev", ".", "Name", "==", "s", ".", "config", ".", "NodeName", "{", "continue", "\n", "}", "\n\n", "s", ".", "logger", ".", "Printf", "(", "\"", "\"", ",", "prev", ")", "\n", "_", ",", "err", ":=", "s", ".", "memberlist", ".", "Join", "(", "[", "]", "string", "{", "prev", ".", "Addr", "}", ")", "\n", "if", "err", "==", "nil", "{", "s", ".", "logger", ".", "Printf", "(", "\"", "\"", ",", "prev", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "s", ".", "logger", ".", "Printf", "(", "\"", "\"", ")", "\n", "}" ]
// handleRejoin attempts to reconnect to previously known alive nodes
[ "handleRejoin", "attempts", "to", "reconnect", "to", "previously", "known", "alive", "nodes" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L1653-L1668
train
hashicorp/serf
serf/serf.go
encodeTags
func (s *Serf) encodeTags(tags map[string]string) []byte { // Support role-only backwards compatibility if s.ProtocolVersion() < 3 { role := tags["role"] return []byte(role) } // Use a magic byte prefix and msgpack encode the tags var buf bytes.Buffer buf.WriteByte(tagMagicByte) enc := codec.NewEncoder(&buf, &codec.MsgpackHandle{}) if err := enc.Encode(tags); err != nil { panic(fmt.Sprintf("Failed to encode tags: %v", err)) } return buf.Bytes() }
go
func (s *Serf) encodeTags(tags map[string]string) []byte { // Support role-only backwards compatibility if s.ProtocolVersion() < 3 { role := tags["role"] return []byte(role) } // Use a magic byte prefix and msgpack encode the tags var buf bytes.Buffer buf.WriteByte(tagMagicByte) enc := codec.NewEncoder(&buf, &codec.MsgpackHandle{}) if err := enc.Encode(tags); err != nil { panic(fmt.Sprintf("Failed to encode tags: %v", err)) } return buf.Bytes() }
[ "func", "(", "s", "*", "Serf", ")", "encodeTags", "(", "tags", "map", "[", "string", "]", "string", ")", "[", "]", "byte", "{", "// Support role-only backwards compatibility", "if", "s", ".", "ProtocolVersion", "(", ")", "<", "3", "{", "role", ":=", "tags", "[", "\"", "\"", "]", "\n", "return", "[", "]", "byte", "(", "role", ")", "\n", "}", "\n\n", "// Use a magic byte prefix and msgpack encode the tags", "var", "buf", "bytes", ".", "Buffer", "\n", "buf", ".", "WriteByte", "(", "tagMagicByte", ")", "\n", "enc", ":=", "codec", ".", "NewEncoder", "(", "&", "buf", ",", "&", "codec", ".", "MsgpackHandle", "{", "}", ")", "\n", "if", "err", ":=", "enc", ".", "Encode", "(", "tags", ")", ";", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n", "return", "buf", ".", "Bytes", "(", ")", "\n", "}" ]
// encodeTags is used to encode a tag map
[ "encodeTags", "is", "used", "to", "encode", "a", "tag", "map" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L1671-L1686
train
hashicorp/serf
serf/serf.go
Stats
func (s *Serf) Stats() map[string]string { toString := func(v uint64) string { return strconv.FormatUint(v, 10) } s.memberLock.RLock() members := toString(uint64(len(s.members))) failed := toString(uint64(len(s.failedMembers))) left := toString(uint64(len(s.leftMembers))) health_score := toString(uint64(s.memberlist.GetHealthScore())) s.memberLock.RUnlock() stats := map[string]string{ "members": members, "failed": failed, "left": left, "health_score": health_score, "member_time": toString(uint64(s.clock.Time())), "event_time": toString(uint64(s.eventClock.Time())), "query_time": toString(uint64(s.queryClock.Time())), "intent_queue": toString(uint64(s.broadcasts.NumQueued())), "event_queue": toString(uint64(s.eventBroadcasts.NumQueued())), "query_queue": toString(uint64(s.queryBroadcasts.NumQueued())), "encrypted": fmt.Sprintf("%v", s.EncryptionEnabled()), } if !s.config.DisableCoordinates { stats["coordinate_resets"] = toString(uint64(s.coordClient.Stats().Resets)) } return stats }
go
func (s *Serf) Stats() map[string]string { toString := func(v uint64) string { return strconv.FormatUint(v, 10) } s.memberLock.RLock() members := toString(uint64(len(s.members))) failed := toString(uint64(len(s.failedMembers))) left := toString(uint64(len(s.leftMembers))) health_score := toString(uint64(s.memberlist.GetHealthScore())) s.memberLock.RUnlock() stats := map[string]string{ "members": members, "failed": failed, "left": left, "health_score": health_score, "member_time": toString(uint64(s.clock.Time())), "event_time": toString(uint64(s.eventClock.Time())), "query_time": toString(uint64(s.queryClock.Time())), "intent_queue": toString(uint64(s.broadcasts.NumQueued())), "event_queue": toString(uint64(s.eventBroadcasts.NumQueued())), "query_queue": toString(uint64(s.queryBroadcasts.NumQueued())), "encrypted": fmt.Sprintf("%v", s.EncryptionEnabled()), } if !s.config.DisableCoordinates { stats["coordinate_resets"] = toString(uint64(s.coordClient.Stats().Resets)) } return stats }
[ "func", "(", "s", "*", "Serf", ")", "Stats", "(", ")", "map", "[", "string", "]", "string", "{", "toString", ":=", "func", "(", "v", "uint64", ")", "string", "{", "return", "strconv", ".", "FormatUint", "(", "v", ",", "10", ")", "\n", "}", "\n", "s", ".", "memberLock", ".", "RLock", "(", ")", "\n", "members", ":=", "toString", "(", "uint64", "(", "len", "(", "s", ".", "members", ")", ")", ")", "\n", "failed", ":=", "toString", "(", "uint64", "(", "len", "(", "s", ".", "failedMembers", ")", ")", ")", "\n", "left", ":=", "toString", "(", "uint64", "(", "len", "(", "s", ".", "leftMembers", ")", ")", ")", "\n", "health_score", ":=", "toString", "(", "uint64", "(", "s", ".", "memberlist", ".", "GetHealthScore", "(", ")", ")", ")", "\n\n", "s", ".", "memberLock", ".", "RUnlock", "(", ")", "\n", "stats", ":=", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "members", ",", "\"", "\"", ":", "failed", ",", "\"", "\"", ":", "left", ",", "\"", "\"", ":", "health_score", ",", "\"", "\"", ":", "toString", "(", "uint64", "(", "s", ".", "clock", ".", "Time", "(", ")", ")", ")", ",", "\"", "\"", ":", "toString", "(", "uint64", "(", "s", ".", "eventClock", ".", "Time", "(", ")", ")", ")", ",", "\"", "\"", ":", "toString", "(", "uint64", "(", "s", ".", "queryClock", ".", "Time", "(", ")", ")", ")", ",", "\"", "\"", ":", "toString", "(", "uint64", "(", "s", ".", "broadcasts", ".", "NumQueued", "(", ")", ")", ")", ",", "\"", "\"", ":", "toString", "(", "uint64", "(", "s", ".", "eventBroadcasts", ".", "NumQueued", "(", ")", ")", ")", ",", "\"", "\"", ":", "toString", "(", "uint64", "(", "s", ".", "queryBroadcasts", ".", "NumQueued", "(", ")", ")", ")", ",", "\"", "\"", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "s", ".", "EncryptionEnabled", "(", ")", ")", ",", "}", "\n", "if", "!", "s", ".", "config", ".", "DisableCoordinates", "{", "stats", "[", "\"", "\"", "]", "=", "toString", "(", "uint64", "(", "s", ".", "coordClient", ".", "Stats", "(", ")", ".", "Resets", ")", ")", "\n", "}", "\n", "return", "stats", "\n", "}" ]
// Stats is used to provide operator debugging information
[ "Stats", "is", "used", "to", "provide", "operator", "debugging", "information" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L1708-L1736
train
hashicorp/serf
serf/serf.go
writeKeyringFile
func (s *Serf) writeKeyringFile() error { if len(s.config.KeyringFile) == 0 { return nil } keyring := s.config.MemberlistConfig.Keyring keysRaw := keyring.GetKeys() keysEncoded := make([]string, len(keysRaw)) for i, key := range keysRaw { keysEncoded[i] = base64.StdEncoding.EncodeToString(key) } encodedKeys, err := json.MarshalIndent(keysEncoded, "", " ") if err != nil { return fmt.Errorf("Failed to encode keys: %s", err) } // Use 0600 for permissions because key data is sensitive if err = ioutil.WriteFile(s.config.KeyringFile, encodedKeys, 0600); err != nil { return fmt.Errorf("Failed to write keyring file: %s", err) } // Success! return nil }
go
func (s *Serf) writeKeyringFile() error { if len(s.config.KeyringFile) == 0 { return nil } keyring := s.config.MemberlistConfig.Keyring keysRaw := keyring.GetKeys() keysEncoded := make([]string, len(keysRaw)) for i, key := range keysRaw { keysEncoded[i] = base64.StdEncoding.EncodeToString(key) } encodedKeys, err := json.MarshalIndent(keysEncoded, "", " ") if err != nil { return fmt.Errorf("Failed to encode keys: %s", err) } // Use 0600 for permissions because key data is sensitive if err = ioutil.WriteFile(s.config.KeyringFile, encodedKeys, 0600); err != nil { return fmt.Errorf("Failed to write keyring file: %s", err) } // Success! return nil }
[ "func", "(", "s", "*", "Serf", ")", "writeKeyringFile", "(", ")", "error", "{", "if", "len", "(", "s", ".", "config", ".", "KeyringFile", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "keyring", ":=", "s", ".", "config", ".", "MemberlistConfig", ".", "Keyring", "\n", "keysRaw", ":=", "keyring", ".", "GetKeys", "(", ")", "\n", "keysEncoded", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "keysRaw", ")", ")", "\n\n", "for", "i", ",", "key", ":=", "range", "keysRaw", "{", "keysEncoded", "[", "i", "]", "=", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "key", ")", "\n", "}", "\n\n", "encodedKeys", ",", "err", ":=", "json", ".", "MarshalIndent", "(", "keysEncoded", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Use 0600 for permissions because key data is sensitive", "if", "err", "=", "ioutil", ".", "WriteFile", "(", "s", ".", "config", ".", "KeyringFile", ",", "encodedKeys", ",", "0600", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Success!", "return", "nil", "\n", "}" ]
// WriteKeyringFile will serialize the current keyring and save it to a file.
[ "WriteKeyringFile", "will", "serialize", "the", "current", "keyring", "and", "save", "it", "to", "a", "file", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L1739-L1764
train
hashicorp/serf
serf/serf.go
GetCoordinate
func (s *Serf) GetCoordinate() (*coordinate.Coordinate, error) { if !s.config.DisableCoordinates { return s.coordClient.GetCoordinate(), nil } return nil, fmt.Errorf("Coordinates are disabled") }
go
func (s *Serf) GetCoordinate() (*coordinate.Coordinate, error) { if !s.config.DisableCoordinates { return s.coordClient.GetCoordinate(), nil } return nil, fmt.Errorf("Coordinates are disabled") }
[ "func", "(", "s", "*", "Serf", ")", "GetCoordinate", "(", ")", "(", "*", "coordinate", ".", "Coordinate", ",", "error", ")", "{", "if", "!", "s", ".", "config", ".", "DisableCoordinates", "{", "return", "s", ".", "coordClient", ".", "GetCoordinate", "(", ")", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}" ]
// GetCoordinate returns the network coordinate of the local node.
[ "GetCoordinate", "returns", "the", "network", "coordinate", "of", "the", "local", "node", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L1767-L1773
train
hashicorp/serf
serf/serf.go
GetCachedCoordinate
func (s *Serf) GetCachedCoordinate(name string) (coord *coordinate.Coordinate, ok bool) { if !s.config.DisableCoordinates { s.coordCacheLock.RLock() defer s.coordCacheLock.RUnlock() if coord, ok = s.coordCache[name]; ok { return coord, true } return nil, false } return nil, false }
go
func (s *Serf) GetCachedCoordinate(name string) (coord *coordinate.Coordinate, ok bool) { if !s.config.DisableCoordinates { s.coordCacheLock.RLock() defer s.coordCacheLock.RUnlock() if coord, ok = s.coordCache[name]; ok { return coord, true } return nil, false } return nil, false }
[ "func", "(", "s", "*", "Serf", ")", "GetCachedCoordinate", "(", "name", "string", ")", "(", "coord", "*", "coordinate", ".", "Coordinate", ",", "ok", "bool", ")", "{", "if", "!", "s", ".", "config", ".", "DisableCoordinates", "{", "s", ".", "coordCacheLock", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "coordCacheLock", ".", "RUnlock", "(", ")", "\n", "if", "coord", ",", "ok", "=", "s", ".", "coordCache", "[", "name", "]", ";", "ok", "{", "return", "coord", ",", "true", "\n", "}", "\n\n", "return", "nil", ",", "false", "\n", "}", "\n\n", "return", "nil", ",", "false", "\n", "}" ]
// GetCachedCoordinate returns the network coordinate for the node with the given // name. This will only be valid if DisableCoordinates is set to false.
[ "GetCachedCoordinate", "returns", "the", "network", "coordinate", "for", "the", "node", "with", "the", "given", "name", ".", "This", "will", "only", "be", "valid", "if", "DisableCoordinates", "is", "set", "to", "false", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L1777-L1789
train
hashicorp/serf
serf/serf.go
NumNodes
func (s *Serf) NumNodes() (numNodes int) { s.memberLock.RLock() numNodes = len(s.members) s.memberLock.RUnlock() return numNodes }
go
func (s *Serf) NumNodes() (numNodes int) { s.memberLock.RLock() numNodes = len(s.members) s.memberLock.RUnlock() return numNodes }
[ "func", "(", "s", "*", "Serf", ")", "NumNodes", "(", ")", "(", "numNodes", "int", ")", "{", "s", ".", "memberLock", ".", "RLock", "(", ")", "\n", "numNodes", "=", "len", "(", "s", ".", "members", ")", "\n", "s", ".", "memberLock", ".", "RUnlock", "(", ")", "\n\n", "return", "numNodes", "\n", "}" ]
// NumNodes returns the number of nodes in the serf cluster, regardless of // their health or status.
[ "NumNodes", "returns", "the", "number", "of", "nodes", "in", "the", "serf", "cluster", "regardless", "of", "their", "health", "or", "status", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L1793-L1799
train
hashicorp/serf
cmd/serf/command/agent/ipc_query_response_stream.go
Stream
func (qs *queryResponseStream) Stream(resp *serf.QueryResponse) { // Setup a timer for the query ending remaining := resp.Deadline().Sub(time.Now()) done := time.After(remaining) ackCh := resp.AckCh() respCh := resp.ResponseCh() for { select { case a := <-ackCh: if err := qs.sendAck(a); err != nil { qs.logger.Printf("[ERR] agent.ipc: Failed to stream ack to %v: %v", qs.client, err) return } case r := <-respCh: if err := qs.sendResponse(r.From, r.Payload); err != nil { qs.logger.Printf("[ERR] agent.ipc: Failed to stream response to %v: %v", qs.client, err) return } case <-done: if err := qs.sendDone(); err != nil { qs.logger.Printf("[ERR] agent.ipc: Failed to stream query end to %v: %v", qs.client, err) } return } } }
go
func (qs *queryResponseStream) Stream(resp *serf.QueryResponse) { // Setup a timer for the query ending remaining := resp.Deadline().Sub(time.Now()) done := time.After(remaining) ackCh := resp.AckCh() respCh := resp.ResponseCh() for { select { case a := <-ackCh: if err := qs.sendAck(a); err != nil { qs.logger.Printf("[ERR] agent.ipc: Failed to stream ack to %v: %v", qs.client, err) return } case r := <-respCh: if err := qs.sendResponse(r.From, r.Payload); err != nil { qs.logger.Printf("[ERR] agent.ipc: Failed to stream response to %v: %v", qs.client, err) return } case <-done: if err := qs.sendDone(); err != nil { qs.logger.Printf("[ERR] agent.ipc: Failed to stream query end to %v: %v", qs.client, err) } return } } }
[ "func", "(", "qs", "*", "queryResponseStream", ")", "Stream", "(", "resp", "*", "serf", ".", "QueryResponse", ")", "{", "// Setup a timer for the query ending", "remaining", ":=", "resp", ".", "Deadline", "(", ")", ".", "Sub", "(", "time", ".", "Now", "(", ")", ")", "\n", "done", ":=", "time", ".", "After", "(", "remaining", ")", "\n\n", "ackCh", ":=", "resp", ".", "AckCh", "(", ")", "\n", "respCh", ":=", "resp", ".", "ResponseCh", "(", ")", "\n", "for", "{", "select", "{", "case", "a", ":=", "<-", "ackCh", ":", "if", "err", ":=", "qs", ".", "sendAck", "(", "a", ")", ";", "err", "!=", "nil", "{", "qs", ".", "logger", ".", "Printf", "(", "\"", "\"", ",", "qs", ".", "client", ",", "err", ")", "\n", "return", "\n", "}", "\n", "case", "r", ":=", "<-", "respCh", ":", "if", "err", ":=", "qs", ".", "sendResponse", "(", "r", ".", "From", ",", "r", ".", "Payload", ")", ";", "err", "!=", "nil", "{", "qs", ".", "logger", ".", "Printf", "(", "\"", "\"", ",", "qs", ".", "client", ",", "err", ")", "\n", "return", "\n", "}", "\n", "case", "<-", "done", ":", "if", "err", ":=", "qs", ".", "sendDone", "(", ")", ";", "err", "!=", "nil", "{", "qs", ".", "logger", ".", "Printf", "(", "\"", "\"", ",", "qs", ".", "client", ",", "err", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// Stream is a long running routine used to stream the results of a query back to a client
[ "Stream", "is", "a", "long", "running", "routine", "used", "to", "stream", "the", "results", "of", "a", "query", "back", "to", "a", "client" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/ipc_query_response_stream.go#L27-L53
train
hashicorp/serf
cmd/serf/command/agent/ipc_query_response_stream.go
sendAck
func (qs *queryResponseStream) sendAck(from string) error { header := responseHeader{ Seq: qs.seq, Error: "", } rec := queryRecord{ Type: queryRecordAck, From: from, } return qs.client.Send(&header, &rec) }
go
func (qs *queryResponseStream) sendAck(from string) error { header := responseHeader{ Seq: qs.seq, Error: "", } rec := queryRecord{ Type: queryRecordAck, From: from, } return qs.client.Send(&header, &rec) }
[ "func", "(", "qs", "*", "queryResponseStream", ")", "sendAck", "(", "from", "string", ")", "error", "{", "header", ":=", "responseHeader", "{", "Seq", ":", "qs", ".", "seq", ",", "Error", ":", "\"", "\"", ",", "}", "\n", "rec", ":=", "queryRecord", "{", "Type", ":", "queryRecordAck", ",", "From", ":", "from", ",", "}", "\n", "return", "qs", ".", "client", ".", "Send", "(", "&", "header", ",", "&", "rec", ")", "\n", "}" ]
// sendAck is used to send a single ack
[ "sendAck", "is", "used", "to", "send", "a", "single", "ack" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/ipc_query_response_stream.go#L56-L66
train
hashicorp/serf
cmd/serf/command/agent/ipc_query_response_stream.go
sendResponse
func (qs *queryResponseStream) sendResponse(from string, payload []byte) error { header := responseHeader{ Seq: qs.seq, Error: "", } rec := queryRecord{ Type: queryRecordResponse, From: from, Payload: payload, } return qs.client.Send(&header, &rec) }
go
func (qs *queryResponseStream) sendResponse(from string, payload []byte) error { header := responseHeader{ Seq: qs.seq, Error: "", } rec := queryRecord{ Type: queryRecordResponse, From: from, Payload: payload, } return qs.client.Send(&header, &rec) }
[ "func", "(", "qs", "*", "queryResponseStream", ")", "sendResponse", "(", "from", "string", ",", "payload", "[", "]", "byte", ")", "error", "{", "header", ":=", "responseHeader", "{", "Seq", ":", "qs", ".", "seq", ",", "Error", ":", "\"", "\"", ",", "}", "\n", "rec", ":=", "queryRecord", "{", "Type", ":", "queryRecordResponse", ",", "From", ":", "from", ",", "Payload", ":", "payload", ",", "}", "\n", "return", "qs", ".", "client", ".", "Send", "(", "&", "header", ",", "&", "rec", ")", "\n", "}" ]
// sendResponse is used to send a single response
[ "sendResponse", "is", "used", "to", "send", "a", "single", "response" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/ipc_query_response_stream.go#L69-L80
train
hashicorp/serf
cmd/serf/command/agent/ipc_query_response_stream.go
sendDone
func (qs *queryResponseStream) sendDone() error { header := responseHeader{ Seq: qs.seq, Error: "", } rec := queryRecord{ Type: queryRecordDone, } return qs.client.Send(&header, &rec) }
go
func (qs *queryResponseStream) sendDone() error { header := responseHeader{ Seq: qs.seq, Error: "", } rec := queryRecord{ Type: queryRecordDone, } return qs.client.Send(&header, &rec) }
[ "func", "(", "qs", "*", "queryResponseStream", ")", "sendDone", "(", ")", "error", "{", "header", ":=", "responseHeader", "{", "Seq", ":", "qs", ".", "seq", ",", "Error", ":", "\"", "\"", ",", "}", "\n", "rec", ":=", "queryRecord", "{", "Type", ":", "queryRecordDone", ",", "}", "\n", "return", "qs", ".", "client", ".", "Send", "(", "&", "header", ",", "&", "rec", ")", "\n", "}" ]
// sendDone is used to signal the end
[ "sendDone", "is", "used", "to", "signal", "the", "end" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/ipc_query_response_stream.go#L83-L92
train
hashicorp/serf
client/rpc_client.go
NewRPCClient
func NewRPCClient(addr string) (*RPCClient, error) { conf := Config{Addr: addr} return ClientFromConfig(&conf) }
go
func NewRPCClient(addr string) (*RPCClient, error) { conf := Config{Addr: addr} return ClientFromConfig(&conf) }
[ "func", "NewRPCClient", "(", "addr", "string", ")", "(", "*", "RPCClient", ",", "error", ")", "{", "conf", ":=", "Config", "{", "Addr", ":", "addr", "}", "\n", "return", "ClientFromConfig", "(", "&", "conf", ")", "\n", "}" ]
// NewRPCClient is used to create a new RPC client given the // RPC address of the Serf agent. This will return a client, // or an error if the connection could not be established. // This will use the DefaultTimeout for the client.
[ "NewRPCClient", "is", "used", "to", "create", "a", "new", "RPC", "client", "given", "the", "RPC", "address", "of", "the", "Serf", "agent", ".", "This", "will", "return", "a", "client", "or", "an", "error", "if", "the", "connection", "could", "not", "be", "established", ".", "This", "will", "use", "the", "DefaultTimeout", "for", "the", "client", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L114-L117
train
hashicorp/serf
client/rpc_client.go
ClientFromConfig
func ClientFromConfig(c *Config) (*RPCClient, error) { // Setup the defaults if c.Timeout == 0 { c.Timeout = DefaultTimeout } // Try to dial to serf conn, err := net.DialTimeout("tcp", c.Addr, c.Timeout) if err != nil { return nil, err } // Create the client client := &RPCClient{ seq: 0, timeout: c.Timeout, conn: conn.(*net.TCPConn), reader: bufio.NewReader(conn), writer: bufio.NewWriter(conn), dispatch: make(map[uint64]seqHandler), shutdownCh: make(chan struct{}), } client.dec = codec.NewDecoder(client.reader, &codec.MsgpackHandle{RawToString: true, WriteExt: true}) client.enc = codec.NewEncoder(client.writer, &codec.MsgpackHandle{RawToString: true, WriteExt: true}) go client.listen() // Do the initial handshake if err := client.handshake(); err != nil { client.Close() return nil, err } // Do the initial authentication if needed if c.AuthKey != "" { if err := client.auth(c.AuthKey); err != nil { client.Close() return nil, err } } return client, err }
go
func ClientFromConfig(c *Config) (*RPCClient, error) { // Setup the defaults if c.Timeout == 0 { c.Timeout = DefaultTimeout } // Try to dial to serf conn, err := net.DialTimeout("tcp", c.Addr, c.Timeout) if err != nil { return nil, err } // Create the client client := &RPCClient{ seq: 0, timeout: c.Timeout, conn: conn.(*net.TCPConn), reader: bufio.NewReader(conn), writer: bufio.NewWriter(conn), dispatch: make(map[uint64]seqHandler), shutdownCh: make(chan struct{}), } client.dec = codec.NewDecoder(client.reader, &codec.MsgpackHandle{RawToString: true, WriteExt: true}) client.enc = codec.NewEncoder(client.writer, &codec.MsgpackHandle{RawToString: true, WriteExt: true}) go client.listen() // Do the initial handshake if err := client.handshake(); err != nil { client.Close() return nil, err } // Do the initial authentication if needed if c.AuthKey != "" { if err := client.auth(c.AuthKey); err != nil { client.Close() return nil, err } } return client, err }
[ "func", "ClientFromConfig", "(", "c", "*", "Config", ")", "(", "*", "RPCClient", ",", "error", ")", "{", "// Setup the defaults", "if", "c", ".", "Timeout", "==", "0", "{", "c", ".", "Timeout", "=", "DefaultTimeout", "\n", "}", "\n\n", "// Try to dial to serf", "conn", ",", "err", ":=", "net", ".", "DialTimeout", "(", "\"", "\"", ",", "c", ".", "Addr", ",", "c", ".", "Timeout", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Create the client", "client", ":=", "&", "RPCClient", "{", "seq", ":", "0", ",", "timeout", ":", "c", ".", "Timeout", ",", "conn", ":", "conn", ".", "(", "*", "net", ".", "TCPConn", ")", ",", "reader", ":", "bufio", ".", "NewReader", "(", "conn", ")", ",", "writer", ":", "bufio", ".", "NewWriter", "(", "conn", ")", ",", "dispatch", ":", "make", "(", "map", "[", "uint64", "]", "seqHandler", ")", ",", "shutdownCh", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n", "client", ".", "dec", "=", "codec", ".", "NewDecoder", "(", "client", ".", "reader", ",", "&", "codec", ".", "MsgpackHandle", "{", "RawToString", ":", "true", ",", "WriteExt", ":", "true", "}", ")", "\n", "client", ".", "enc", "=", "codec", ".", "NewEncoder", "(", "client", ".", "writer", ",", "&", "codec", ".", "MsgpackHandle", "{", "RawToString", ":", "true", ",", "WriteExt", ":", "true", "}", ")", "\n", "go", "client", ".", "listen", "(", ")", "\n\n", "// Do the initial handshake", "if", "err", ":=", "client", ".", "handshake", "(", ")", ";", "err", "!=", "nil", "{", "client", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Do the initial authentication if needed", "if", "c", ".", "AuthKey", "!=", "\"", "\"", "{", "if", "err", ":=", "client", ".", "auth", "(", "c", ".", "AuthKey", ")", ";", "err", "!=", "nil", "{", "client", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "client", ",", "err", "\n", "}" ]
// ClientFromConfig is used to create a new RPC client given the // configuration object. This will return a client, or an error if // the connection could not be established.
[ "ClientFromConfig", "is", "used", "to", "create", "a", "new", "RPC", "client", "given", "the", "configuration", "object", ".", "This", "will", "return", "a", "client", "or", "an", "error", "if", "the", "connection", "could", "not", "be", "established", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L122-L165
train
hashicorp/serf
client/rpc_client.go
Close
func (c *RPCClient) Close() error { c.shutdownLock.Lock() defer c.shutdownLock.Unlock() if !c.shutdown { c.shutdown = true close(c.shutdownCh) c.deregisterAll() return c.conn.Close() } return nil }
go
func (c *RPCClient) Close() error { c.shutdownLock.Lock() defer c.shutdownLock.Unlock() if !c.shutdown { c.shutdown = true close(c.shutdownCh) c.deregisterAll() return c.conn.Close() } return nil }
[ "func", "(", "c", "*", "RPCClient", ")", "Close", "(", ")", "error", "{", "c", ".", "shutdownLock", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "shutdownLock", ".", "Unlock", "(", ")", "\n\n", "if", "!", "c", ".", "shutdown", "{", "c", ".", "shutdown", "=", "true", "\n", "close", "(", "c", ".", "shutdownCh", ")", "\n", "c", ".", "deregisterAll", "(", ")", "\n", "return", "c", ".", "conn", ".", "Close", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close is used to free any resources associated with the client
[ "Close", "is", "used", "to", "free", "any", "resources", "associated", "with", "the", "client" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L175-L186
train
hashicorp/serf
client/rpc_client.go
ForceLeave
func (c *RPCClient) ForceLeave(node string) error { header := requestHeader{ Command: forceLeaveCommand, Seq: c.getSeq(), } req := forceLeaveRequest{ Node: node, } return c.genericRPC(&header, &req, nil) }
go
func (c *RPCClient) ForceLeave(node string) error { header := requestHeader{ Command: forceLeaveCommand, Seq: c.getSeq(), } req := forceLeaveRequest{ Node: node, } return c.genericRPC(&header, &req, nil) }
[ "func", "(", "c", "*", "RPCClient", ")", "ForceLeave", "(", "node", "string", ")", "error", "{", "header", ":=", "requestHeader", "{", "Command", ":", "forceLeaveCommand", ",", "Seq", ":", "c", ".", "getSeq", "(", ")", ",", "}", "\n", "req", ":=", "forceLeaveRequest", "{", "Node", ":", "node", ",", "}", "\n", "return", "c", ".", "genericRPC", "(", "&", "header", ",", "&", "req", ",", "nil", ")", "\n", "}" ]
// ForceLeave is used to ask the agent to issue a leave command for // a given node
[ "ForceLeave", "is", "used", "to", "ask", "the", "agent", "to", "issue", "a", "leave", "command", "for", "a", "given", "node" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L190-L199
train
hashicorp/serf
client/rpc_client.go
Join
func (c *RPCClient) Join(addrs []string, replay bool) (int, error) { header := requestHeader{ Command: joinCommand, Seq: c.getSeq(), } req := joinRequest{ Existing: addrs, Replay: replay, } var resp joinResponse err := c.genericRPC(&header, &req, &resp) return int(resp.Num), err }
go
func (c *RPCClient) Join(addrs []string, replay bool) (int, error) { header := requestHeader{ Command: joinCommand, Seq: c.getSeq(), } req := joinRequest{ Existing: addrs, Replay: replay, } var resp joinResponse err := c.genericRPC(&header, &req, &resp) return int(resp.Num), err }
[ "func", "(", "c", "*", "RPCClient", ")", "Join", "(", "addrs", "[", "]", "string", ",", "replay", "bool", ")", "(", "int", ",", "error", ")", "{", "header", ":=", "requestHeader", "{", "Command", ":", "joinCommand", ",", "Seq", ":", "c", ".", "getSeq", "(", ")", ",", "}", "\n", "req", ":=", "joinRequest", "{", "Existing", ":", "addrs", ",", "Replay", ":", "replay", ",", "}", "\n", "var", "resp", "joinResponse", "\n\n", "err", ":=", "c", ".", "genericRPC", "(", "&", "header", ",", "&", "req", ",", "&", "resp", ")", "\n", "return", "int", "(", "resp", ".", "Num", ")", ",", "err", "\n", "}" ]
// Join is used to instruct the agent to attempt a join
[ "Join", "is", "used", "to", "instruct", "the", "agent", "to", "attempt", "a", "join" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L202-L215
train
hashicorp/serf
client/rpc_client.go
Members
func (c *RPCClient) Members() ([]Member, error) { header := requestHeader{ Command: membersCommand, Seq: c.getSeq(), } var resp membersResponse err := c.genericRPC(&header, nil, &resp) return resp.Members, err }
go
func (c *RPCClient) Members() ([]Member, error) { header := requestHeader{ Command: membersCommand, Seq: c.getSeq(), } var resp membersResponse err := c.genericRPC(&header, nil, &resp) return resp.Members, err }
[ "func", "(", "c", "*", "RPCClient", ")", "Members", "(", ")", "(", "[", "]", "Member", ",", "error", ")", "{", "header", ":=", "requestHeader", "{", "Command", ":", "membersCommand", ",", "Seq", ":", "c", ".", "getSeq", "(", ")", ",", "}", "\n", "var", "resp", "membersResponse", "\n\n", "err", ":=", "c", ".", "genericRPC", "(", "&", "header", ",", "nil", ",", "&", "resp", ")", "\n", "return", "resp", ".", "Members", ",", "err", "\n", "}" ]
// Members is used to fetch a list of known members
[ "Members", "is", "used", "to", "fetch", "a", "list", "of", "known", "members" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L218-L227
train
hashicorp/serf
client/rpc_client.go
MembersFiltered
func (c *RPCClient) MembersFiltered(tags map[string]string, status string, name string) ([]Member, error) { header := requestHeader{ Command: membersFilteredCommand, Seq: c.getSeq(), } req := membersFilteredRequest{ Tags: tags, Status: status, Name: name, } var resp membersResponse err := c.genericRPC(&header, &req, &resp) return resp.Members, err }
go
func (c *RPCClient) MembersFiltered(tags map[string]string, status string, name string) ([]Member, error) { header := requestHeader{ Command: membersFilteredCommand, Seq: c.getSeq(), } req := membersFilteredRequest{ Tags: tags, Status: status, Name: name, } var resp membersResponse err := c.genericRPC(&header, &req, &resp) return resp.Members, err }
[ "func", "(", "c", "*", "RPCClient", ")", "MembersFiltered", "(", "tags", "map", "[", "string", "]", "string", ",", "status", "string", ",", "name", "string", ")", "(", "[", "]", "Member", ",", "error", ")", "{", "header", ":=", "requestHeader", "{", "Command", ":", "membersFilteredCommand", ",", "Seq", ":", "c", ".", "getSeq", "(", ")", ",", "}", "\n", "req", ":=", "membersFilteredRequest", "{", "Tags", ":", "tags", ",", "Status", ":", "status", ",", "Name", ":", "name", ",", "}", "\n", "var", "resp", "membersResponse", "\n\n", "err", ":=", "c", ".", "genericRPC", "(", "&", "header", ",", "&", "req", ",", "&", "resp", ")", "\n", "return", "resp", ".", "Members", ",", "err", "\n", "}" ]
// MembersFiltered returns a subset of members
[ "MembersFiltered", "returns", "a", "subset", "of", "members" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L230-L245
train
hashicorp/serf
client/rpc_client.go
UserEvent
func (c *RPCClient) UserEvent(name string, payload []byte, coalesce bool) error { header := requestHeader{ Command: eventCommand, Seq: c.getSeq(), } req := eventRequest{ Name: name, Payload: payload, Coalesce: coalesce, } return c.genericRPC(&header, &req, nil) }
go
func (c *RPCClient) UserEvent(name string, payload []byte, coalesce bool) error { header := requestHeader{ Command: eventCommand, Seq: c.getSeq(), } req := eventRequest{ Name: name, Payload: payload, Coalesce: coalesce, } return c.genericRPC(&header, &req, nil) }
[ "func", "(", "c", "*", "RPCClient", ")", "UserEvent", "(", "name", "string", ",", "payload", "[", "]", "byte", ",", "coalesce", "bool", ")", "error", "{", "header", ":=", "requestHeader", "{", "Command", ":", "eventCommand", ",", "Seq", ":", "c", ".", "getSeq", "(", ")", ",", "}", "\n", "req", ":=", "eventRequest", "{", "Name", ":", "name", ",", "Payload", ":", "payload", ",", "Coalesce", ":", "coalesce", ",", "}", "\n", "return", "c", ".", "genericRPC", "(", "&", "header", ",", "&", "req", ",", "nil", ")", "\n", "}" ]
// UserEvent is used to trigger sending an event
[ "UserEvent", "is", "used", "to", "trigger", "sending", "an", "event" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L248-L259
train
hashicorp/serf
client/rpc_client.go
Leave
func (c *RPCClient) Leave() error { header := requestHeader{ Command: leaveCommand, Seq: c.getSeq(), } return c.genericRPC(&header, nil, nil) }
go
func (c *RPCClient) Leave() error { header := requestHeader{ Command: leaveCommand, Seq: c.getSeq(), } return c.genericRPC(&header, nil, nil) }
[ "func", "(", "c", "*", "RPCClient", ")", "Leave", "(", ")", "error", "{", "header", ":=", "requestHeader", "{", "Command", ":", "leaveCommand", ",", "Seq", ":", "c", ".", "getSeq", "(", ")", ",", "}", "\n", "return", "c", ".", "genericRPC", "(", "&", "header", ",", "nil", ",", "nil", ")", "\n", "}" ]
// Leave is used to trigger a graceful leave and shutdown of the agent
[ "Leave", "is", "used", "to", "trigger", "a", "graceful", "leave", "and", "shutdown", "of", "the", "agent" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L262-L268
train
hashicorp/serf
client/rpc_client.go
UpdateTags
func (c *RPCClient) UpdateTags(tags map[string]string, delTags []string) error { header := requestHeader{ Command: tagsCommand, Seq: c.getSeq(), } req := tagsRequest{ Tags: tags, DeleteTags: delTags, } return c.genericRPC(&header, &req, nil) }
go
func (c *RPCClient) UpdateTags(tags map[string]string, delTags []string) error { header := requestHeader{ Command: tagsCommand, Seq: c.getSeq(), } req := tagsRequest{ Tags: tags, DeleteTags: delTags, } return c.genericRPC(&header, &req, nil) }
[ "func", "(", "c", "*", "RPCClient", ")", "UpdateTags", "(", "tags", "map", "[", "string", "]", "string", ",", "delTags", "[", "]", "string", ")", "error", "{", "header", ":=", "requestHeader", "{", "Command", ":", "tagsCommand", ",", "Seq", ":", "c", ".", "getSeq", "(", ")", ",", "}", "\n", "req", ":=", "tagsRequest", "{", "Tags", ":", "tags", ",", "DeleteTags", ":", "delTags", ",", "}", "\n", "return", "c", ".", "genericRPC", "(", "&", "header", ",", "&", "req", ",", "nil", ")", "\n", "}" ]
// UpdateTags will modify the tags on a running serf agent
[ "UpdateTags", "will", "modify", "the", "tags", "on", "a", "running", "serf", "agent" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L271-L281
train
hashicorp/serf
client/rpc_client.go
Respond
func (c *RPCClient) Respond(id uint64, buf []byte) error { header := requestHeader{ Command: respondCommand, Seq: c.getSeq(), } req := respondRequest{ ID: id, Payload: buf, } return c.genericRPC(&header, &req, nil) }
go
func (c *RPCClient) Respond(id uint64, buf []byte) error { header := requestHeader{ Command: respondCommand, Seq: c.getSeq(), } req := respondRequest{ ID: id, Payload: buf, } return c.genericRPC(&header, &req, nil) }
[ "func", "(", "c", "*", "RPCClient", ")", "Respond", "(", "id", "uint64", ",", "buf", "[", "]", "byte", ")", "error", "{", "header", ":=", "requestHeader", "{", "Command", ":", "respondCommand", ",", "Seq", ":", "c", ".", "getSeq", "(", ")", ",", "}", "\n", "req", ":=", "respondRequest", "{", "ID", ":", "id", ",", "Payload", ":", "buf", ",", "}", "\n", "return", "c", ".", "genericRPC", "(", "&", "header", ",", "&", "req", ",", "nil", ")", "\n", "}" ]
// Respond allows a client to respond to a query event. The ID is the // ID of the Query to respond to, and the given payload is the response.
[ "Respond", "allows", "a", "client", "to", "respond", "to", "a", "query", "event", ".", "The", "ID", "is", "the", "ID", "of", "the", "Query", "to", "respond", "to", "and", "the", "given", "payload", "is", "the", "response", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L285-L295
train
hashicorp/serf
client/rpc_client.go
InstallKey
func (c *RPCClient) InstallKey(key string) (map[string]string, error) { header := requestHeader{ Command: installKeyCommand, Seq: c.getSeq(), } req := keyRequest{ Key: key, } resp := keyResponse{} err := c.genericRPC(&header, &req, &resp) return resp.Messages, err }
go
func (c *RPCClient) InstallKey(key string) (map[string]string, error) { header := requestHeader{ Command: installKeyCommand, Seq: c.getSeq(), } req := keyRequest{ Key: key, } resp := keyResponse{} err := c.genericRPC(&header, &req, &resp) return resp.Messages, err }
[ "func", "(", "c", "*", "RPCClient", ")", "InstallKey", "(", "key", "string", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "header", ":=", "requestHeader", "{", "Command", ":", "installKeyCommand", ",", "Seq", ":", "c", ".", "getSeq", "(", ")", ",", "}", "\n", "req", ":=", "keyRequest", "{", "Key", ":", "key", ",", "}", "\n\n", "resp", ":=", "keyResponse", "{", "}", "\n", "err", ":=", "c", ".", "genericRPC", "(", "&", "header", ",", "&", "req", ",", "&", "resp", ")", "\n\n", "return", "resp", ".", "Messages", ",", "err", "\n", "}" ]
// IntallKey installs a new encryption key onto the keyring
[ "IntallKey", "installs", "a", "new", "encryption", "key", "onto", "the", "keyring" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L298-L311
train
hashicorp/serf
client/rpc_client.go
ListKeys
func (c *RPCClient) ListKeys() (map[string]int, int, map[string]string, error) { header := requestHeader{ Command: listKeysCommand, Seq: c.getSeq(), } resp := keyResponse{} err := c.genericRPC(&header, nil, &resp) return resp.Keys, resp.NumNodes, resp.Messages, err }
go
func (c *RPCClient) ListKeys() (map[string]int, int, map[string]string, error) { header := requestHeader{ Command: listKeysCommand, Seq: c.getSeq(), } resp := keyResponse{} err := c.genericRPC(&header, nil, &resp) return resp.Keys, resp.NumNodes, resp.Messages, err }
[ "func", "(", "c", "*", "RPCClient", ")", "ListKeys", "(", ")", "(", "map", "[", "string", "]", "int", ",", "int", ",", "map", "[", "string", "]", "string", ",", "error", ")", "{", "header", ":=", "requestHeader", "{", "Command", ":", "listKeysCommand", ",", "Seq", ":", "c", ".", "getSeq", "(", ")", ",", "}", "\n\n", "resp", ":=", "keyResponse", "{", "}", "\n", "err", ":=", "c", ".", "genericRPC", "(", "&", "header", ",", "nil", ",", "&", "resp", ")", "\n\n", "return", "resp", ".", "Keys", ",", "resp", ".", "NumNodes", ",", "resp", ".", "Messages", ",", "err", "\n", "}" ]
// ListKeys returns all of the active keys on each member of the cluster
[ "ListKeys", "returns", "all", "of", "the", "active", "keys", "on", "each", "member", "of", "the", "cluster" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L346-L356
train
hashicorp/serf
client/rpc_client.go
Stats
func (c *RPCClient) Stats() (map[string]map[string]string, error) { header := requestHeader{ Command: statsCommand, Seq: c.getSeq(), } var resp map[string]map[string]string err := c.genericRPC(&header, nil, &resp) return resp, err }
go
func (c *RPCClient) Stats() (map[string]map[string]string, error) { header := requestHeader{ Command: statsCommand, Seq: c.getSeq(), } var resp map[string]map[string]string err := c.genericRPC(&header, nil, &resp) return resp, err }
[ "func", "(", "c", "*", "RPCClient", ")", "Stats", "(", ")", "(", "map", "[", "string", "]", "map", "[", "string", "]", "string", ",", "error", ")", "{", "header", ":=", "requestHeader", "{", "Command", ":", "statsCommand", ",", "Seq", ":", "c", ".", "getSeq", "(", ")", ",", "}", "\n", "var", "resp", "map", "[", "string", "]", "map", "[", "string", "]", "string", "\n\n", "err", ":=", "c", ".", "genericRPC", "(", "&", "header", ",", "nil", ",", "&", "resp", ")", "\n", "return", "resp", ",", "err", "\n", "}" ]
// Stats is used to get debugging state information
[ "Stats", "is", "used", "to", "get", "debugging", "state", "information" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L359-L368
train
hashicorp/serf
client/rpc_client.go
GetCoordinate
func (c *RPCClient) GetCoordinate(node string) (*coordinate.Coordinate, error) { header := requestHeader{ Command: getCoordinateCommand, Seq: c.getSeq(), } req := coordinateRequest{ Node: node, } var resp coordinateResponse if err := c.genericRPC(&header, &req, &resp); err != nil { return nil, err } if resp.Ok { return &resp.Coord, nil } return nil, nil }
go
func (c *RPCClient) GetCoordinate(node string) (*coordinate.Coordinate, error) { header := requestHeader{ Command: getCoordinateCommand, Seq: c.getSeq(), } req := coordinateRequest{ Node: node, } var resp coordinateResponse if err := c.genericRPC(&header, &req, &resp); err != nil { return nil, err } if resp.Ok { return &resp.Coord, nil } return nil, nil }
[ "func", "(", "c", "*", "RPCClient", ")", "GetCoordinate", "(", "node", "string", ")", "(", "*", "coordinate", ".", "Coordinate", ",", "error", ")", "{", "header", ":=", "requestHeader", "{", "Command", ":", "getCoordinateCommand", ",", "Seq", ":", "c", ".", "getSeq", "(", ")", ",", "}", "\n", "req", ":=", "coordinateRequest", "{", "Node", ":", "node", ",", "}", "\n", "var", "resp", "coordinateResponse", "\n\n", "if", "err", ":=", "c", ".", "genericRPC", "(", "&", "header", ",", "&", "req", ",", "&", "resp", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "resp", ".", "Ok", "{", "return", "&", "resp", ".", "Coord", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// GetCoordinate is used to retrieve the cached coordinate of a node.
[ "GetCoordinate", "is", "used", "to", "retrieve", "the", "cached", "coordinate", "of", "a", "node", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L371-L388
train
hashicorp/serf
client/rpc_client.go
Monitor
func (c *RPCClient) Monitor(level logutils.LogLevel, ch chan<- string) (StreamHandle, error) { // Setup the request seq := c.getSeq() header := requestHeader{ Command: monitorCommand, Seq: seq, } req := monitorRequest{ LogLevel: string(level), } // Create a monitor handler initCh := make(chan error, 1) handler := &monitorHandler{ client: c, initCh: initCh, logCh: ch, seq: seq, } c.handleSeq(seq, handler) // Send the request if err := c.send(&header, &req); err != nil { c.deregisterHandler(seq) return 0, err } // Wait for a response select { case err := <-initCh: return StreamHandle(seq), err case <-c.shutdownCh: c.deregisterHandler(seq) return 0, clientClosed } }
go
func (c *RPCClient) Monitor(level logutils.LogLevel, ch chan<- string) (StreamHandle, error) { // Setup the request seq := c.getSeq() header := requestHeader{ Command: monitorCommand, Seq: seq, } req := monitorRequest{ LogLevel: string(level), } // Create a monitor handler initCh := make(chan error, 1) handler := &monitorHandler{ client: c, initCh: initCh, logCh: ch, seq: seq, } c.handleSeq(seq, handler) // Send the request if err := c.send(&header, &req); err != nil { c.deregisterHandler(seq) return 0, err } // Wait for a response select { case err := <-initCh: return StreamHandle(seq), err case <-c.shutdownCh: c.deregisterHandler(seq) return 0, clientClosed } }
[ "func", "(", "c", "*", "RPCClient", ")", "Monitor", "(", "level", "logutils", ".", "LogLevel", ",", "ch", "chan", "<-", "string", ")", "(", "StreamHandle", ",", "error", ")", "{", "// Setup the request", "seq", ":=", "c", ".", "getSeq", "(", ")", "\n", "header", ":=", "requestHeader", "{", "Command", ":", "monitorCommand", ",", "Seq", ":", "seq", ",", "}", "\n", "req", ":=", "monitorRequest", "{", "LogLevel", ":", "string", "(", "level", ")", ",", "}", "\n\n", "// Create a monitor handler", "initCh", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "handler", ":=", "&", "monitorHandler", "{", "client", ":", "c", ",", "initCh", ":", "initCh", ",", "logCh", ":", "ch", ",", "seq", ":", "seq", ",", "}", "\n", "c", ".", "handleSeq", "(", "seq", ",", "handler", ")", "\n\n", "// Send the request", "if", "err", ":=", "c", ".", "send", "(", "&", "header", ",", "&", "req", ")", ";", "err", "!=", "nil", "{", "c", ".", "deregisterHandler", "(", "seq", ")", "\n", "return", "0", ",", "err", "\n", "}", "\n\n", "// Wait for a response", "select", "{", "case", "err", ":=", "<-", "initCh", ":", "return", "StreamHandle", "(", "seq", ")", ",", "err", "\n", "case", "<-", "c", ".", "shutdownCh", ":", "c", ".", "deregisterHandler", "(", "seq", ")", "\n", "return", "0", ",", "clientClosed", "\n", "}", "\n", "}" ]
// Monitor is used to subscribe to the logs of the agent
[ "Monitor", "is", "used", "to", "subscribe", "to", "the", "logs", "of", "the", "agent" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L435-L470
train
hashicorp/serf
client/rpc_client.go
Stream
func (c *RPCClient) Stream(filter string, ch chan<- map[string]interface{}) (StreamHandle, error) { // Setup the request seq := c.getSeq() header := requestHeader{ Command: streamCommand, Seq: seq, } req := streamRequest{ Type: filter, } // Create a monitor handler initCh := make(chan error, 1) handler := &streamHandler{ client: c, initCh: initCh, eventCh: ch, seq: seq, } c.handleSeq(seq, handler) // Send the request if err := c.send(&header, &req); err != nil { c.deregisterHandler(seq) return 0, err } // Wait for a response select { case err := <-initCh: return StreamHandle(seq), err case <-c.shutdownCh: c.deregisterHandler(seq) return 0, clientClosed } }
go
func (c *RPCClient) Stream(filter string, ch chan<- map[string]interface{}) (StreamHandle, error) { // Setup the request seq := c.getSeq() header := requestHeader{ Command: streamCommand, Seq: seq, } req := streamRequest{ Type: filter, } // Create a monitor handler initCh := make(chan error, 1) handler := &streamHandler{ client: c, initCh: initCh, eventCh: ch, seq: seq, } c.handleSeq(seq, handler) // Send the request if err := c.send(&header, &req); err != nil { c.deregisterHandler(seq) return 0, err } // Wait for a response select { case err := <-initCh: return StreamHandle(seq), err case <-c.shutdownCh: c.deregisterHandler(seq) return 0, clientClosed } }
[ "func", "(", "c", "*", "RPCClient", ")", "Stream", "(", "filter", "string", ",", "ch", "chan", "<-", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "StreamHandle", ",", "error", ")", "{", "// Setup the request", "seq", ":=", "c", ".", "getSeq", "(", ")", "\n", "header", ":=", "requestHeader", "{", "Command", ":", "streamCommand", ",", "Seq", ":", "seq", ",", "}", "\n", "req", ":=", "streamRequest", "{", "Type", ":", "filter", ",", "}", "\n\n", "// Create a monitor handler", "initCh", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "handler", ":=", "&", "streamHandler", "{", "client", ":", "c", ",", "initCh", ":", "initCh", ",", "eventCh", ":", "ch", ",", "seq", ":", "seq", ",", "}", "\n", "c", ".", "handleSeq", "(", "seq", ",", "handler", ")", "\n\n", "// Send the request", "if", "err", ":=", "c", ".", "send", "(", "&", "header", ",", "&", "req", ")", ";", "err", "!=", "nil", "{", "c", ".", "deregisterHandler", "(", "seq", ")", "\n", "return", "0", ",", "err", "\n", "}", "\n\n", "// Wait for a response", "select", "{", "case", "err", ":=", "<-", "initCh", ":", "return", "StreamHandle", "(", "seq", ")", ",", "err", "\n", "case", "<-", "c", ".", "shutdownCh", ":", "c", ".", "deregisterHandler", "(", "seq", ")", "\n", "return", "0", ",", "clientClosed", "\n", "}", "\n", "}" ]
// Stream is used to subscribe to events
[ "Stream", "is", "used", "to", "subscribe", "to", "events" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L517-L552
train
hashicorp/serf
client/rpc_client.go
Query
func (c *RPCClient) Query(params *QueryParam) error { // Setup the request seq := c.getSeq() header := requestHeader{ Command: queryCommand, Seq: seq, } req := queryRequest{ FilterNodes: params.FilterNodes, FilterTags: params.FilterTags, RequestAck: params.RequestAck, RelayFactor: params.RelayFactor, Timeout: params.Timeout, Name: params.Name, Payload: params.Payload, } // Create a query handler initCh := make(chan error, 1) handler := &queryHandler{ client: c, initCh: initCh, ackCh: params.AckCh, respCh: params.RespCh, seq: seq, } c.handleSeq(seq, handler) // Send the request if err := c.send(&header, &req); err != nil { c.deregisterHandler(seq) return err } // Wait for a response select { case err := <-initCh: return err case <-c.shutdownCh: c.deregisterHandler(seq) return clientClosed } }
go
func (c *RPCClient) Query(params *QueryParam) error { // Setup the request seq := c.getSeq() header := requestHeader{ Command: queryCommand, Seq: seq, } req := queryRequest{ FilterNodes: params.FilterNodes, FilterTags: params.FilterTags, RequestAck: params.RequestAck, RelayFactor: params.RelayFactor, Timeout: params.Timeout, Name: params.Name, Payload: params.Payload, } // Create a query handler initCh := make(chan error, 1) handler := &queryHandler{ client: c, initCh: initCh, ackCh: params.AckCh, respCh: params.RespCh, seq: seq, } c.handleSeq(seq, handler) // Send the request if err := c.send(&header, &req); err != nil { c.deregisterHandler(seq) return err } // Wait for a response select { case err := <-initCh: return err case <-c.shutdownCh: c.deregisterHandler(seq) return clientClosed } }
[ "func", "(", "c", "*", "RPCClient", ")", "Query", "(", "params", "*", "QueryParam", ")", "error", "{", "// Setup the request", "seq", ":=", "c", ".", "getSeq", "(", ")", "\n", "header", ":=", "requestHeader", "{", "Command", ":", "queryCommand", ",", "Seq", ":", "seq", ",", "}", "\n", "req", ":=", "queryRequest", "{", "FilterNodes", ":", "params", ".", "FilterNodes", ",", "FilterTags", ":", "params", ".", "FilterTags", ",", "RequestAck", ":", "params", ".", "RequestAck", ",", "RelayFactor", ":", "params", ".", "RelayFactor", ",", "Timeout", ":", "params", ".", "Timeout", ",", "Name", ":", "params", ".", "Name", ",", "Payload", ":", "params", ".", "Payload", ",", "}", "\n\n", "// Create a query handler", "initCh", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "handler", ":=", "&", "queryHandler", "{", "client", ":", "c", ",", "initCh", ":", "initCh", ",", "ackCh", ":", "params", ".", "AckCh", ",", "respCh", ":", "params", ".", "RespCh", ",", "seq", ":", "seq", ",", "}", "\n", "c", ".", "handleSeq", "(", "seq", ",", "handler", ")", "\n\n", "// Send the request", "if", "err", ":=", "c", ".", "send", "(", "&", "header", ",", "&", "req", ")", ";", "err", "!=", "nil", "{", "c", ".", "deregisterHandler", "(", "seq", ")", "\n", "return", "err", "\n", "}", "\n\n", "// Wait for a response", "select", "{", "case", "err", ":=", "<-", "initCh", ":", "return", "err", "\n", "case", "<-", "c", ".", "shutdownCh", ":", "c", ".", "deregisterHandler", "(", "seq", ")", "\n", "return", "clientClosed", "\n", "}", "\n", "}" ]
// Query initiates a new query message using the given parameters, and streams // acks and responses over the given channels. The channels will not block on // sends and should be buffered. At the end of the query, the channels will be // closed.
[ "Query", "initiates", "a", "new", "query", "message", "using", "the", "given", "parameters", "and", "streams", "acks", "and", "responses", "over", "the", "given", "channels", ".", "The", "channels", "will", "not", "block", "on", "sends", "and", "should", "be", "buffered", ".", "At", "the", "end", "of", "the", "query", "the", "channels", "will", "be", "closed", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L637-L679
train
hashicorp/serf
client/rpc_client.go
Stop
func (c *RPCClient) Stop(handle StreamHandle) error { // Deregister locally first to stop delivery c.deregisterHandler(uint64(handle)) header := requestHeader{ Command: stopCommand, Seq: c.getSeq(), } req := stopRequest{ Stop: uint64(handle), } return c.genericRPC(&header, &req, nil) }
go
func (c *RPCClient) Stop(handle StreamHandle) error { // Deregister locally first to stop delivery c.deregisterHandler(uint64(handle)) header := requestHeader{ Command: stopCommand, Seq: c.getSeq(), } req := stopRequest{ Stop: uint64(handle), } return c.genericRPC(&header, &req, nil) }
[ "func", "(", "c", "*", "RPCClient", ")", "Stop", "(", "handle", "StreamHandle", ")", "error", "{", "// Deregister locally first to stop delivery", "c", ".", "deregisterHandler", "(", "uint64", "(", "handle", ")", ")", "\n\n", "header", ":=", "requestHeader", "{", "Command", ":", "stopCommand", ",", "Seq", ":", "c", ".", "getSeq", "(", ")", ",", "}", "\n", "req", ":=", "stopRequest", "{", "Stop", ":", "uint64", "(", "handle", ")", ",", "}", "\n", "return", "c", ".", "genericRPC", "(", "&", "header", ",", "&", "req", ",", "nil", ")", "\n", "}" ]
// Stop is used to unsubscribe from logs or event streams
[ "Stop", "is", "used", "to", "unsubscribe", "from", "logs", "or", "event", "streams" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L682-L694
train
hashicorp/serf
client/rpc_client.go
handshake
func (c *RPCClient) handshake() error { header := requestHeader{ Command: handshakeCommand, Seq: c.getSeq(), } req := handshakeRequest{ Version: maxIPCVersion, } return c.genericRPC(&header, &req, nil) }
go
func (c *RPCClient) handshake() error { header := requestHeader{ Command: handshakeCommand, Seq: c.getSeq(), } req := handshakeRequest{ Version: maxIPCVersion, } return c.genericRPC(&header, &req, nil) }
[ "func", "(", "c", "*", "RPCClient", ")", "handshake", "(", ")", "error", "{", "header", ":=", "requestHeader", "{", "Command", ":", "handshakeCommand", ",", "Seq", ":", "c", ".", "getSeq", "(", ")", ",", "}", "\n", "req", ":=", "handshakeRequest", "{", "Version", ":", "maxIPCVersion", ",", "}", "\n", "return", "c", ".", "genericRPC", "(", "&", "header", ",", "&", "req", ",", "nil", ")", "\n", "}" ]
// handshake is used to perform the initial handshake on connect
[ "handshake", "is", "used", "to", "perform", "the", "initial", "handshake", "on", "connect" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L697-L706
train
hashicorp/serf
client/rpc_client.go
auth
func (c *RPCClient) auth(authKey string) error { header := requestHeader{ Command: authCommand, Seq: c.getSeq(), } req := authRequest{ AuthKey: authKey, } return c.genericRPC(&header, &req, nil) }
go
func (c *RPCClient) auth(authKey string) error { header := requestHeader{ Command: authCommand, Seq: c.getSeq(), } req := authRequest{ AuthKey: authKey, } return c.genericRPC(&header, &req, nil) }
[ "func", "(", "c", "*", "RPCClient", ")", "auth", "(", "authKey", "string", ")", "error", "{", "header", ":=", "requestHeader", "{", "Command", ":", "authCommand", ",", "Seq", ":", "c", ".", "getSeq", "(", ")", ",", "}", "\n", "req", ":=", "authRequest", "{", "AuthKey", ":", "authKey", ",", "}", "\n", "return", "c", ".", "genericRPC", "(", "&", "header", ",", "&", "req", ",", "nil", ")", "\n", "}" ]
// auth is used to perform the initial authentication on connect
[ "auth", "is", "used", "to", "perform", "the", "initial", "authentication", "on", "connect" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L709-L718
train
hashicorp/serf
client/rpc_client.go
genericRPC
func (c *RPCClient) genericRPC(header *requestHeader, req interface{}, resp interface{}) error { // Setup a response handler errCh := make(chan error, 1) handler := func(respHeader *responseHeader) { // If we get an auth error, we should not wait for a request body if respHeader.Error == authRequired { goto SEND_ERR } if resp != nil { err := c.dec.Decode(resp) if err != nil { errCh <- err return } } SEND_ERR: errCh <- strToError(respHeader.Error) } c.handleSeq(header.Seq, &seqCallback{handler: handler}) defer c.deregisterHandler(header.Seq) // Send the request if err := c.send(header, req); err != nil { return err } // Wait for a response select { case err := <-errCh: return err case <-c.shutdownCh: return clientClosed } }
go
func (c *RPCClient) genericRPC(header *requestHeader, req interface{}, resp interface{}) error { // Setup a response handler errCh := make(chan error, 1) handler := func(respHeader *responseHeader) { // If we get an auth error, we should not wait for a request body if respHeader.Error == authRequired { goto SEND_ERR } if resp != nil { err := c.dec.Decode(resp) if err != nil { errCh <- err return } } SEND_ERR: errCh <- strToError(respHeader.Error) } c.handleSeq(header.Seq, &seqCallback{handler: handler}) defer c.deregisterHandler(header.Seq) // Send the request if err := c.send(header, req); err != nil { return err } // Wait for a response select { case err := <-errCh: return err case <-c.shutdownCh: return clientClosed } }
[ "func", "(", "c", "*", "RPCClient", ")", "genericRPC", "(", "header", "*", "requestHeader", ",", "req", "interface", "{", "}", ",", "resp", "interface", "{", "}", ")", "error", "{", "// Setup a response handler", "errCh", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "handler", ":=", "func", "(", "respHeader", "*", "responseHeader", ")", "{", "// If we get an auth error, we should not wait for a request body", "if", "respHeader", ".", "Error", "==", "authRequired", "{", "goto", "SEND_ERR", "\n", "}", "\n", "if", "resp", "!=", "nil", "{", "err", ":=", "c", ".", "dec", ".", "Decode", "(", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "errCh", "<-", "err", "\n", "return", "\n", "}", "\n", "}", "\n", "SEND_ERR", ":", "errCh", "<-", "strToError", "(", "respHeader", ".", "Error", ")", "\n", "}", "\n", "c", ".", "handleSeq", "(", "header", ".", "Seq", ",", "&", "seqCallback", "{", "handler", ":", "handler", "}", ")", "\n", "defer", "c", ".", "deregisterHandler", "(", "header", ".", "Seq", ")", "\n\n", "// Send the request", "if", "err", ":=", "c", ".", "send", "(", "header", ",", "req", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Wait for a response", "select", "{", "case", "err", ":=", "<-", "errCh", ":", "return", "err", "\n", "case", "<-", "c", ".", "shutdownCh", ":", "return", "clientClosed", "\n", "}", "\n", "}" ]
// genericRPC is used to send a request and wait for an // errorSequenceResponse, potentially returning an error
[ "genericRPC", "is", "used", "to", "send", "a", "request", "and", "wait", "for", "an", "errorSequenceResponse", "potentially", "returning", "an", "error" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L722-L755
train
hashicorp/serf
client/rpc_client.go
deregisterAll
func (c *RPCClient) deregisterAll() { c.dispatchLock.Lock() defer c.dispatchLock.Unlock() for _, seqH := range c.dispatch { seqH.Cleanup() } c.dispatch = make(map[uint64]seqHandler) }
go
func (c *RPCClient) deregisterAll() { c.dispatchLock.Lock() defer c.dispatchLock.Unlock() for _, seqH := range c.dispatch { seqH.Cleanup() } c.dispatch = make(map[uint64]seqHandler) }
[ "func", "(", "c", "*", "RPCClient", ")", "deregisterAll", "(", ")", "{", "c", ".", "dispatchLock", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "dispatchLock", ".", "Unlock", "(", ")", "\n\n", "for", "_", ",", "seqH", ":=", "range", "c", ".", "dispatch", "{", "seqH", ".", "Cleanup", "(", ")", "\n", "}", "\n", "c", ".", "dispatch", "=", "make", "(", "map", "[", "uint64", "]", "seqHandler", ")", "\n", "}" ]
// deregisterAll is used to deregister all handlers
[ "deregisterAll", "is", "used", "to", "deregister", "all", "handlers" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L771-L779
train
hashicorp/serf
client/rpc_client.go
deregisterHandler
func (c *RPCClient) deregisterHandler(seq uint64) { c.dispatchLock.Lock() seqH, ok := c.dispatch[seq] delete(c.dispatch, seq) c.dispatchLock.Unlock() if ok { seqH.Cleanup() } }
go
func (c *RPCClient) deregisterHandler(seq uint64) { c.dispatchLock.Lock() seqH, ok := c.dispatch[seq] delete(c.dispatch, seq) c.dispatchLock.Unlock() if ok { seqH.Cleanup() } }
[ "func", "(", "c", "*", "RPCClient", ")", "deregisterHandler", "(", "seq", "uint64", ")", "{", "c", ".", "dispatchLock", ".", "Lock", "(", ")", "\n", "seqH", ",", "ok", ":=", "c", ".", "dispatch", "[", "seq", "]", "\n", "delete", "(", "c", ".", "dispatch", ",", "seq", ")", "\n", "c", ".", "dispatchLock", ".", "Unlock", "(", ")", "\n\n", "if", "ok", "{", "seqH", ".", "Cleanup", "(", ")", "\n", "}", "\n", "}" ]
// deregisterHandler is used to deregister a handler
[ "deregisterHandler", "is", "used", "to", "deregister", "a", "handler" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L782-L791
train
hashicorp/serf
client/rpc_client.go
handleSeq
func (c *RPCClient) handleSeq(seq uint64, handler seqHandler) { c.dispatchLock.Lock() defer c.dispatchLock.Unlock() c.dispatch[seq] = handler }
go
func (c *RPCClient) handleSeq(seq uint64, handler seqHandler) { c.dispatchLock.Lock() defer c.dispatchLock.Unlock() c.dispatch[seq] = handler }
[ "func", "(", "c", "*", "RPCClient", ")", "handleSeq", "(", "seq", "uint64", ",", "handler", "seqHandler", ")", "{", "c", ".", "dispatchLock", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "dispatchLock", ".", "Unlock", "(", ")", "\n", "c", ".", "dispatch", "[", "seq", "]", "=", "handler", "\n", "}" ]
// handleSeq is used to setup a handlerto wait on a response for // a given sequence number.
[ "handleSeq", "is", "used", "to", "setup", "a", "handlerto", "wait", "on", "a", "response", "for", "a", "given", "sequence", "number", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L795-L799
train
hashicorp/serf
client/rpc_client.go
respondSeq
func (c *RPCClient) respondSeq(seq uint64, respHeader *responseHeader) { c.dispatchLock.Lock() seqL, ok := c.dispatch[seq] c.dispatchLock.Unlock() // Get a registered listener, ignore if none if ok { seqL.Handle(respHeader) } }
go
func (c *RPCClient) respondSeq(seq uint64, respHeader *responseHeader) { c.dispatchLock.Lock() seqL, ok := c.dispatch[seq] c.dispatchLock.Unlock() // Get a registered listener, ignore if none if ok { seqL.Handle(respHeader) } }
[ "func", "(", "c", "*", "RPCClient", ")", "respondSeq", "(", "seq", "uint64", ",", "respHeader", "*", "responseHeader", ")", "{", "c", ".", "dispatchLock", ".", "Lock", "(", ")", "\n", "seqL", ",", "ok", ":=", "c", ".", "dispatch", "[", "seq", "]", "\n", "c", ".", "dispatchLock", ".", "Unlock", "(", ")", "\n\n", "// Get a registered listener, ignore if none", "if", "ok", "{", "seqL", ".", "Handle", "(", "respHeader", ")", "\n", "}", "\n", "}" ]
// respondSeq is used to respond to a given sequence number
[ "respondSeq", "is", "used", "to", "respond", "to", "a", "given", "sequence", "number" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L802-L811
train
hashicorp/serf
client/rpc_client.go
listen
func (c *RPCClient) listen() { defer c.Close() var respHeader responseHeader for { if err := c.dec.Decode(&respHeader); err != nil { if !c.shutdown { log.Printf("[ERR] agent.client: Failed to decode response header: %v", err) } break } c.respondSeq(respHeader.Seq, &respHeader) } }
go
func (c *RPCClient) listen() { defer c.Close() var respHeader responseHeader for { if err := c.dec.Decode(&respHeader); err != nil { if !c.shutdown { log.Printf("[ERR] agent.client: Failed to decode response header: %v", err) } break } c.respondSeq(respHeader.Seq, &respHeader) } }
[ "func", "(", "c", "*", "RPCClient", ")", "listen", "(", ")", "{", "defer", "c", ".", "Close", "(", ")", "\n", "var", "respHeader", "responseHeader", "\n", "for", "{", "if", "err", ":=", "c", ".", "dec", ".", "Decode", "(", "&", "respHeader", ")", ";", "err", "!=", "nil", "{", "if", "!", "c", ".", "shutdown", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "break", "\n", "}", "\n", "c", ".", "respondSeq", "(", "respHeader", ".", "Seq", ",", "&", "respHeader", ")", "\n", "}", "\n", "}" ]
// listen is used to processes data coming over the IPC channel, // and wrote it to the correct destination based on seq no
[ "listen", "is", "used", "to", "processes", "data", "coming", "over", "the", "IPC", "channel", "and", "wrote", "it", "to", "the", "correct", "destination", "based", "on", "seq", "no" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/client/rpc_client.go#L815-L827
train
hashicorp/serf
serf/config.go
Init
func (c *Config) Init() { if c.Tags == nil { c.Tags = make(map[string]string) } }
go
func (c *Config) Init() { if c.Tags == nil { c.Tags = make(map[string]string) } }
[ "func", "(", "c", "*", "Config", ")", "Init", "(", ")", "{", "if", "c", ".", "Tags", "==", "nil", "{", "c", ".", "Tags", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "}", "\n", "}" ]
// Init allocates the subdata structures
[ "Init", "allocates", "the", "subdata", "structures" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/config.go#L252-L256
train
hashicorp/serf
serf/config.go
DefaultConfig
func DefaultConfig() *Config { hostname, err := os.Hostname() if err != nil { panic(err) } return &Config{ NodeName: hostname, BroadcastTimeout: 5 * time.Second, LeavePropagateDelay: 1 * time.Second, EventBuffer: 512, QueryBuffer: 512, LogOutput: os.Stderr, ProtocolVersion: 4, ReapInterval: 15 * time.Second, RecentIntentTimeout: 5 * time.Minute, ReconnectInterval: 30 * time.Second, ReconnectTimeout: 24 * time.Hour, QueueCheckInterval: 30 * time.Second, QueueDepthWarning: 128, MaxQueueDepth: 4096, TombstoneTimeout: 24 * time.Hour, FlapTimeout: 60 * time.Second, MemberlistConfig: memberlist.DefaultLANConfig(), QueryTimeoutMult: 16, QueryResponseSizeLimit: 1024, QuerySizeLimit: 1024, EnableNameConflictResolution: true, DisableCoordinates: false, UserEventSizeLimit: 512, } }
go
func DefaultConfig() *Config { hostname, err := os.Hostname() if err != nil { panic(err) } return &Config{ NodeName: hostname, BroadcastTimeout: 5 * time.Second, LeavePropagateDelay: 1 * time.Second, EventBuffer: 512, QueryBuffer: 512, LogOutput: os.Stderr, ProtocolVersion: 4, ReapInterval: 15 * time.Second, RecentIntentTimeout: 5 * time.Minute, ReconnectInterval: 30 * time.Second, ReconnectTimeout: 24 * time.Hour, QueueCheckInterval: 30 * time.Second, QueueDepthWarning: 128, MaxQueueDepth: 4096, TombstoneTimeout: 24 * time.Hour, FlapTimeout: 60 * time.Second, MemberlistConfig: memberlist.DefaultLANConfig(), QueryTimeoutMult: 16, QueryResponseSizeLimit: 1024, QuerySizeLimit: 1024, EnableNameConflictResolution: true, DisableCoordinates: false, UserEventSizeLimit: 512, } }
[ "func", "DefaultConfig", "(", ")", "*", "Config", "{", "hostname", ",", "err", ":=", "os", ".", "Hostname", "(", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "Config", "{", "NodeName", ":", "hostname", ",", "BroadcastTimeout", ":", "5", "*", "time", ".", "Second", ",", "LeavePropagateDelay", ":", "1", "*", "time", ".", "Second", ",", "EventBuffer", ":", "512", ",", "QueryBuffer", ":", "512", ",", "LogOutput", ":", "os", ".", "Stderr", ",", "ProtocolVersion", ":", "4", ",", "ReapInterval", ":", "15", "*", "time", ".", "Second", ",", "RecentIntentTimeout", ":", "5", "*", "time", ".", "Minute", ",", "ReconnectInterval", ":", "30", "*", "time", ".", "Second", ",", "ReconnectTimeout", ":", "24", "*", "time", ".", "Hour", ",", "QueueCheckInterval", ":", "30", "*", "time", ".", "Second", ",", "QueueDepthWarning", ":", "128", ",", "MaxQueueDepth", ":", "4096", ",", "TombstoneTimeout", ":", "24", "*", "time", ".", "Hour", ",", "FlapTimeout", ":", "60", "*", "time", ".", "Second", ",", "MemberlistConfig", ":", "memberlist", ".", "DefaultLANConfig", "(", ")", ",", "QueryTimeoutMult", ":", "16", ",", "QueryResponseSizeLimit", ":", "1024", ",", "QuerySizeLimit", ":", "1024", ",", "EnableNameConflictResolution", ":", "true", ",", "DisableCoordinates", ":", "false", ",", "UserEventSizeLimit", ":", "512", ",", "}", "\n", "}" ]
// DefaultConfig returns a Config struct that contains reasonable defaults // for most of the configurations.
[ "DefaultConfig", "returns", "a", "Config", "struct", "that", "contains", "reasonable", "defaults", "for", "most", "of", "the", "configurations", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/config.go#L260-L291
train
hashicorp/serf
serf/coalesce.go
coalescedEventCh
func coalescedEventCh(outCh chan<- Event, shutdownCh <-chan struct{}, cPeriod time.Duration, qPeriod time.Duration, c coalescer) chan<- Event { inCh := make(chan Event, 1024) go coalesceLoop(inCh, outCh, shutdownCh, cPeriod, qPeriod, c) return inCh }
go
func coalescedEventCh(outCh chan<- Event, shutdownCh <-chan struct{}, cPeriod time.Duration, qPeriod time.Duration, c coalescer) chan<- Event { inCh := make(chan Event, 1024) go coalesceLoop(inCh, outCh, shutdownCh, cPeriod, qPeriod, c) return inCh }
[ "func", "coalescedEventCh", "(", "outCh", "chan", "<-", "Event", ",", "shutdownCh", "<-", "chan", "struct", "{", "}", ",", "cPeriod", "time", ".", "Duration", ",", "qPeriod", "time", ".", "Duration", ",", "c", "coalescer", ")", "chan", "<-", "Event", "{", "inCh", ":=", "make", "(", "chan", "Event", ",", "1024", ")", "\n", "go", "coalesceLoop", "(", "inCh", ",", "outCh", ",", "shutdownCh", ",", "cPeriod", ",", "qPeriod", ",", "c", ")", "\n", "return", "inCh", "\n", "}" ]
// coalescedEventCh returns an event channel where the events are coalesced // using the given coalescer.
[ "coalescedEventCh", "returns", "an", "event", "channel", "where", "the", "events", "are", "coalesced", "using", "the", "given", "coalescer", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/coalesce.go#L23-L28
train
hashicorp/serf
serf/coalesce.go
coalesceLoop
func coalesceLoop(inCh <-chan Event, outCh chan<- Event, shutdownCh <-chan struct{}, coalescePeriod time.Duration, quiescentPeriod time.Duration, c coalescer) { var quiescent <-chan time.Time var quantum <-chan time.Time shutdown := false INGEST: // Reset the timers quantum = nil quiescent = nil for { select { case e := <-inCh: // Ignore any non handled events if !c.Handle(e) { outCh <- e continue } // Start a new quantum if we need to // and restart the quiescent timer if quantum == nil { quantum = time.After(coalescePeriod) } quiescent = time.After(quiescentPeriod) // Coalesce the event c.Coalesce(e) case <-quantum: goto FLUSH case <-quiescent: goto FLUSH case <-shutdownCh: shutdown = true goto FLUSH } } FLUSH: // Flush the coalesced events c.Flush(outCh) // Restart ingestion if we are not done if !shutdown { goto INGEST } }
go
func coalesceLoop(inCh <-chan Event, outCh chan<- Event, shutdownCh <-chan struct{}, coalescePeriod time.Duration, quiescentPeriod time.Duration, c coalescer) { var quiescent <-chan time.Time var quantum <-chan time.Time shutdown := false INGEST: // Reset the timers quantum = nil quiescent = nil for { select { case e := <-inCh: // Ignore any non handled events if !c.Handle(e) { outCh <- e continue } // Start a new quantum if we need to // and restart the quiescent timer if quantum == nil { quantum = time.After(coalescePeriod) } quiescent = time.After(quiescentPeriod) // Coalesce the event c.Coalesce(e) case <-quantum: goto FLUSH case <-quiescent: goto FLUSH case <-shutdownCh: shutdown = true goto FLUSH } } FLUSH: // Flush the coalesced events c.Flush(outCh) // Restart ingestion if we are not done if !shutdown { goto INGEST } }
[ "func", "coalesceLoop", "(", "inCh", "<-", "chan", "Event", ",", "outCh", "chan", "<-", "Event", ",", "shutdownCh", "<-", "chan", "struct", "{", "}", ",", "coalescePeriod", "time", ".", "Duration", ",", "quiescentPeriod", "time", ".", "Duration", ",", "c", "coalescer", ")", "{", "var", "quiescent", "<-", "chan", "time", ".", "Time", "\n", "var", "quantum", "<-", "chan", "time", ".", "Time", "\n", "shutdown", ":=", "false", "\n\n", "INGEST", ":", "// Reset the timers", "quantum", "=", "nil", "\n", "quiescent", "=", "nil", "\n\n", "for", "{", "select", "{", "case", "e", ":=", "<-", "inCh", ":", "// Ignore any non handled events", "if", "!", "c", ".", "Handle", "(", "e", ")", "{", "outCh", "<-", "e", "\n", "continue", "\n", "}", "\n\n", "// Start a new quantum if we need to", "// and restart the quiescent timer", "if", "quantum", "==", "nil", "{", "quantum", "=", "time", ".", "After", "(", "coalescePeriod", ")", "\n", "}", "\n", "quiescent", "=", "time", ".", "After", "(", "quiescentPeriod", ")", "\n\n", "// Coalesce the event", "c", ".", "Coalesce", "(", "e", ")", "\n\n", "case", "<-", "quantum", ":", "goto", "FLUSH", "\n", "case", "<-", "quiescent", ":", "goto", "FLUSH", "\n", "case", "<-", "shutdownCh", ":", "shutdown", "=", "true", "\n", "goto", "FLUSH", "\n", "}", "\n", "}", "\n\n", "FLUSH", ":", "// Flush the coalesced events", "c", ".", "Flush", "(", "outCh", ")", "\n\n", "// Restart ingestion if we are not done", "if", "!", "shutdown", "{", "goto", "INGEST", "\n", "}", "\n", "}" ]
// coalesceLoop is a simple long-running routine that manages the high-level // flow of coalescing based on quiescence and a maximum quantum period.
[ "coalesceLoop", "is", "a", "simple", "long", "-", "running", "routine", "that", "manages", "the", "high", "-", "level", "flow", "of", "coalescing", "based", "on", "quiescence", "and", "a", "maximum", "quantum", "period", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/coalesce.go#L32-L80
train
swaggo/swag
gen/gen.go
Build
func (g *Gen) Build(config *Config) error { if _, err := os.Stat(config.SearchDir); os.IsNotExist(err) { return fmt.Errorf("dir: %s is not exist", config.SearchDir) } log.Println("Generate swagger docs....") p := swag.New() p.PropNamingStrategy = config.PropNamingStrategy p.ParseVendor = config.ParseVendor if err := p.ParseAPI(config.SearchDir, config.MainAPIFile); err != nil { return err } swagger := p.GetSwagger() b, err := json.MarshalIndent(swagger, "", " ") if err != nil { return err } os.MkdirAll(config.OutputDir, os.ModePerm) docs, err := os.Create(path.Join(config.OutputDir, "docs.go")) if err != nil { return err } defer docs.Close() swaggerJSON, err := os.Create(path.Join(config.OutputDir, "swagger.json")) if err != nil { return err } defer swaggerJSON.Close() swaggerJSON.Write(b) swaggerYAML, err := os.Create(path.Join(config.OutputDir, "swagger.yaml")) if err != nil { return err } defer swaggerYAML.Close() y, err := yaml.JSONToYAML(b) if err != nil { return errors.Wrap(err, "cannot covert json to yaml") } swaggerYAML.Write(y) if err := packageTemplate.Execute(docs, struct { Timestamp time.Time Doc string }{ Timestamp: time.Now(), Doc: "`" + string(b) + "`", }); err != nil { return err } log.Printf("create docs.go at %+v", docs.Name()) log.Printf("create swagger.json at %+v", swaggerJSON.Name()) log.Printf("create swagger.yaml at %+v", swaggerYAML.Name()) return nil }
go
func (g *Gen) Build(config *Config) error { if _, err := os.Stat(config.SearchDir); os.IsNotExist(err) { return fmt.Errorf("dir: %s is not exist", config.SearchDir) } log.Println("Generate swagger docs....") p := swag.New() p.PropNamingStrategy = config.PropNamingStrategy p.ParseVendor = config.ParseVendor if err := p.ParseAPI(config.SearchDir, config.MainAPIFile); err != nil { return err } swagger := p.GetSwagger() b, err := json.MarshalIndent(swagger, "", " ") if err != nil { return err } os.MkdirAll(config.OutputDir, os.ModePerm) docs, err := os.Create(path.Join(config.OutputDir, "docs.go")) if err != nil { return err } defer docs.Close() swaggerJSON, err := os.Create(path.Join(config.OutputDir, "swagger.json")) if err != nil { return err } defer swaggerJSON.Close() swaggerJSON.Write(b) swaggerYAML, err := os.Create(path.Join(config.OutputDir, "swagger.yaml")) if err != nil { return err } defer swaggerYAML.Close() y, err := yaml.JSONToYAML(b) if err != nil { return errors.Wrap(err, "cannot covert json to yaml") } swaggerYAML.Write(y) if err := packageTemplate.Execute(docs, struct { Timestamp time.Time Doc string }{ Timestamp: time.Now(), Doc: "`" + string(b) + "`", }); err != nil { return err } log.Printf("create docs.go at %+v", docs.Name()) log.Printf("create swagger.json at %+v", swaggerJSON.Name()) log.Printf("create swagger.yaml at %+v", swaggerYAML.Name()) return nil }
[ "func", "(", "g", "*", "Gen", ")", "Build", "(", "config", "*", "Config", ")", "error", "{", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "config", ".", "SearchDir", ")", ";", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "config", ".", "SearchDir", ")", "\n", "}", "\n\n", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "p", ":=", "swag", ".", "New", "(", ")", "\n", "p", ".", "PropNamingStrategy", "=", "config", ".", "PropNamingStrategy", "\n", "p", ".", "ParseVendor", "=", "config", ".", "ParseVendor", "\n\n", "if", "err", ":=", "p", ".", "ParseAPI", "(", "config", ".", "SearchDir", ",", "config", ".", "MainAPIFile", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "swagger", ":=", "p", ".", "GetSwagger", "(", ")", "\n\n", "b", ",", "err", ":=", "json", ".", "MarshalIndent", "(", "swagger", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "os", ".", "MkdirAll", "(", "config", ".", "OutputDir", ",", "os", ".", "ModePerm", ")", "\n", "docs", ",", "err", ":=", "os", ".", "Create", "(", "path", ".", "Join", "(", "config", ".", "OutputDir", ",", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "docs", ".", "Close", "(", ")", "\n\n", "swaggerJSON", ",", "err", ":=", "os", ".", "Create", "(", "path", ".", "Join", "(", "config", ".", "OutputDir", ",", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "defer", "swaggerJSON", ".", "Close", "(", ")", "\n", "swaggerJSON", ".", "Write", "(", "b", ")", "\n\n", "swaggerYAML", ",", "err", ":=", "os", ".", "Create", "(", "path", ".", "Join", "(", "config", ".", "OutputDir", ",", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "defer", "swaggerYAML", ".", "Close", "(", ")", "\n", "y", ",", "err", ":=", "yaml", ".", "JSONToYAML", "(", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "swaggerYAML", ".", "Write", "(", "y", ")", "\n\n", "if", "err", ":=", "packageTemplate", ".", "Execute", "(", "docs", ",", "struct", "{", "Timestamp", "time", ".", "Time", "\n", "Doc", "string", "\n", "}", "{", "Timestamp", ":", "time", ".", "Now", "(", ")", ",", "Doc", ":", "\"", "\"", "+", "string", "(", "b", ")", "+", "\"", "\"", ",", "}", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "log", ".", "Printf", "(", "\"", "\"", ",", "docs", ".", "Name", "(", ")", ")", "\n", "log", ".", "Printf", "(", "\"", "\"", ",", "swaggerJSON", ".", "Name", "(", ")", ")", "\n", "log", ".", "Printf", "(", "\"", "\"", ",", "swaggerYAML", ".", "Name", "(", ")", ")", "\n\n", "return", "nil", "\n", "}" ]
// Build builds swagger json file for gived searchDir and mainAPIFile. Returns json
[ "Build", "builds", "swagger", "json", "file", "for", "gived", "searchDir", "and", "mainAPIFile", ".", "Returns", "json" ]
2a7b9f41f0361c4bf8145a5369b01b189aaa7245
https://github.com/swaggo/swag/blob/2a7b9f41f0361c4bf8145a5369b01b189aaa7245/gen/gen.go#L45-L108
train
swaggo/swag
operation.go
ParseComment
func (operation *Operation) ParseComment(comment string, astFile *ast.File) error { commentLine := strings.TrimSpace(strings.TrimLeft(comment, "//")) if len(commentLine) == 0 { return nil } attribute := strings.Fields(commentLine)[0] lineRemainder := strings.TrimSpace(commentLine[len(attribute):]) switch strings.ToLower(attribute) { case "@description": if operation.Description == "" { operation.Description = lineRemainder } else { operation.Description += "\n" + lineRemainder } case "@summary": operation.Summary = lineRemainder case "@id": operation.ID = lineRemainder case "@tags": operation.ParseTagsComment(lineRemainder) case "@accept": if err := operation.ParseAcceptComment(lineRemainder); err != nil { return err } case "@produce": if err := operation.ParseProduceComment(lineRemainder); err != nil { return err } case "@param": if err := operation.ParseParamComment(lineRemainder, astFile); err != nil { return err } case "@success", "@failure": if err := operation.ParseResponseComment(lineRemainder, astFile); err != nil { if err := operation.ParseEmptyResponseComment(lineRemainder); err != nil { if err := operation.ParseEmptyResponseOnly(lineRemainder); err != nil { return err } } } case "@header": if err := operation.ParseResponseHeaderComment(lineRemainder, astFile); err != nil { return err } case "@router": if err := operation.ParseRouterComment(lineRemainder); err != nil { return err } case "@security": if err := operation.ParseSecurityComment(lineRemainder); err != nil { return err } } return nil }
go
func (operation *Operation) ParseComment(comment string, astFile *ast.File) error { commentLine := strings.TrimSpace(strings.TrimLeft(comment, "//")) if len(commentLine) == 0 { return nil } attribute := strings.Fields(commentLine)[0] lineRemainder := strings.TrimSpace(commentLine[len(attribute):]) switch strings.ToLower(attribute) { case "@description": if operation.Description == "" { operation.Description = lineRemainder } else { operation.Description += "\n" + lineRemainder } case "@summary": operation.Summary = lineRemainder case "@id": operation.ID = lineRemainder case "@tags": operation.ParseTagsComment(lineRemainder) case "@accept": if err := operation.ParseAcceptComment(lineRemainder); err != nil { return err } case "@produce": if err := operation.ParseProduceComment(lineRemainder); err != nil { return err } case "@param": if err := operation.ParseParamComment(lineRemainder, astFile); err != nil { return err } case "@success", "@failure": if err := operation.ParseResponseComment(lineRemainder, astFile); err != nil { if err := operation.ParseEmptyResponseComment(lineRemainder); err != nil { if err := operation.ParseEmptyResponseOnly(lineRemainder); err != nil { return err } } } case "@header": if err := operation.ParseResponseHeaderComment(lineRemainder, astFile); err != nil { return err } case "@router": if err := operation.ParseRouterComment(lineRemainder); err != nil { return err } case "@security": if err := operation.ParseSecurityComment(lineRemainder); err != nil { return err } } return nil }
[ "func", "(", "operation", "*", "Operation", ")", "ParseComment", "(", "comment", "string", ",", "astFile", "*", "ast", ".", "File", ")", "error", "{", "commentLine", ":=", "strings", ".", "TrimSpace", "(", "strings", ".", "TrimLeft", "(", "comment", ",", "\"", "\"", ")", ")", "\n", "if", "len", "(", "commentLine", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "attribute", ":=", "strings", ".", "Fields", "(", "commentLine", ")", "[", "0", "]", "\n", "lineRemainder", ":=", "strings", ".", "TrimSpace", "(", "commentLine", "[", "len", "(", "attribute", ")", ":", "]", ")", "\n", "switch", "strings", ".", "ToLower", "(", "attribute", ")", "{", "case", "\"", "\"", ":", "if", "operation", ".", "Description", "==", "\"", "\"", "{", "operation", ".", "Description", "=", "lineRemainder", "\n", "}", "else", "{", "operation", ".", "Description", "+=", "\"", "\\n", "\"", "+", "lineRemainder", "\n", "}", "\n", "case", "\"", "\"", ":", "operation", ".", "Summary", "=", "lineRemainder", "\n", "case", "\"", "\"", ":", "operation", ".", "ID", "=", "lineRemainder", "\n", "case", "\"", "\"", ":", "operation", ".", "ParseTagsComment", "(", "lineRemainder", ")", "\n", "case", "\"", "\"", ":", "if", "err", ":=", "operation", ".", "ParseAcceptComment", "(", "lineRemainder", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "\"", "\"", ":", "if", "err", ":=", "operation", ".", "ParseProduceComment", "(", "lineRemainder", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "\"", "\"", ":", "if", "err", ":=", "operation", ".", "ParseParamComment", "(", "lineRemainder", ",", "astFile", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "\"", "\"", ",", "\"", "\"", ":", "if", "err", ":=", "operation", ".", "ParseResponseComment", "(", "lineRemainder", ",", "astFile", ")", ";", "err", "!=", "nil", "{", "if", "err", ":=", "operation", ".", "ParseEmptyResponseComment", "(", "lineRemainder", ")", ";", "err", "!=", "nil", "{", "if", "err", ":=", "operation", ".", "ParseEmptyResponseOnly", "(", "lineRemainder", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "case", "\"", "\"", ":", "if", "err", ":=", "operation", ".", "ParseResponseHeaderComment", "(", "lineRemainder", ",", "astFile", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "\"", "\"", ":", "if", "err", ":=", "operation", ".", "ParseRouterComment", "(", "lineRemainder", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "\"", "\"", ":", "if", "err", ":=", "operation", ".", "ParseSecurityComment", "(", "lineRemainder", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ParseComment parses comment for given comment string and returns error if error occurs.
[ "ParseComment", "parses", "comment", "for", "given", "comment", "string", "and", "returns", "error", "if", "error", "occurs", "." ]
2a7b9f41f0361c4bf8145a5369b01b189aaa7245
https://github.com/swaggo/swag/blob/2a7b9f41f0361c4bf8145a5369b01b189aaa7245/operation.go#L59-L114
train
swaggo/swag
operation.go
ParseTagsComment
func (operation *Operation) ParseTagsComment(commentLine string) { tags := strings.Split(commentLine, ",") for _, tag := range tags { operation.Tags = append(operation.Tags, strings.TrimSpace(tag)) } }
go
func (operation *Operation) ParseTagsComment(commentLine string) { tags := strings.Split(commentLine, ",") for _, tag := range tags { operation.Tags = append(operation.Tags, strings.TrimSpace(tag)) } }
[ "func", "(", "operation", "*", "Operation", ")", "ParseTagsComment", "(", "commentLine", "string", ")", "{", "tags", ":=", "strings", ".", "Split", "(", "commentLine", ",", "\"", "\"", ")", "\n", "for", "_", ",", "tag", ":=", "range", "tags", "{", "operation", ".", "Tags", "=", "append", "(", "operation", ".", "Tags", ",", "strings", ".", "TrimSpace", "(", "tag", ")", ")", "\n", "}", "\n", "}" ]
// ParseTagsComment parses comment for given `tag` comment string.
[ "ParseTagsComment", "parses", "comment", "for", "given", "tag", "comment", "string", "." ]
2a7b9f41f0361c4bf8145a5369b01b189aaa7245
https://github.com/swaggo/swag/blob/2a7b9f41f0361c4bf8145a5369b01b189aaa7245/operation.go#L353-L358
train
swaggo/swag
operation.go
ParseAcceptComment
func (operation *Operation) ParseAcceptComment(commentLine string) error { return parseMimeTypeList(commentLine, &operation.Consumes, "%v accept type can't be accepted") }
go
func (operation *Operation) ParseAcceptComment(commentLine string) error { return parseMimeTypeList(commentLine, &operation.Consumes, "%v accept type can't be accepted") }
[ "func", "(", "operation", "*", "Operation", ")", "ParseAcceptComment", "(", "commentLine", "string", ")", "error", "{", "return", "parseMimeTypeList", "(", "commentLine", ",", "&", "operation", ".", "Consumes", ",", "\"", "\"", ")", "\n", "}" ]
// ParseAcceptComment parses comment for given `accept` comment string.
[ "ParseAcceptComment", "parses", "comment", "for", "given", "accept", "comment", "string", "." ]
2a7b9f41f0361c4bf8145a5369b01b189aaa7245
https://github.com/swaggo/swag/blob/2a7b9f41f0361c4bf8145a5369b01b189aaa7245/operation.go#L361-L363
train
swaggo/swag
operation.go
ParseProduceComment
func (operation *Operation) ParseProduceComment(commentLine string) error { return parseMimeTypeList(commentLine, &operation.Produces, "%v produce type can't be accepted") }
go
func (operation *Operation) ParseProduceComment(commentLine string) error { return parseMimeTypeList(commentLine, &operation.Produces, "%v produce type can't be accepted") }
[ "func", "(", "operation", "*", "Operation", ")", "ParseProduceComment", "(", "commentLine", "string", ")", "error", "{", "return", "parseMimeTypeList", "(", "commentLine", ",", "&", "operation", ".", "Produces", ",", "\"", "\"", ")", "\n", "}" ]
// ParseProduceComment parses comment for given `produce` comment string.
[ "ParseProduceComment", "parses", "comment", "for", "given", "produce", "comment", "string", "." ]
2a7b9f41f0361c4bf8145a5369b01b189aaa7245
https://github.com/swaggo/swag/blob/2a7b9f41f0361c4bf8145a5369b01b189aaa7245/operation.go#L366-L368
train
swaggo/swag
operation.go
ParseRouterComment
func (operation *Operation) ParseRouterComment(commentLine string) error { var matches []string if matches = routerPattern.FindStringSubmatch(commentLine); len(matches) != 3 { return fmt.Errorf("can not parse router comment \"%s\"", commentLine) } path := matches[1] httpMethod := matches[2] operation.Path = path operation.HTTPMethod = strings.ToUpper(httpMethod) return nil }
go
func (operation *Operation) ParseRouterComment(commentLine string) error { var matches []string if matches = routerPattern.FindStringSubmatch(commentLine); len(matches) != 3 { return fmt.Errorf("can not parse router comment \"%s\"", commentLine) } path := matches[1] httpMethod := matches[2] operation.Path = path operation.HTTPMethod = strings.ToUpper(httpMethod) return nil }
[ "func", "(", "operation", "*", "Operation", ")", "ParseRouterComment", "(", "commentLine", "string", ")", "error", "{", "var", "matches", "[", "]", "string", "\n\n", "if", "matches", "=", "routerPattern", ".", "FindStringSubmatch", "(", "commentLine", ")", ";", "len", "(", "matches", ")", "!=", "3", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\\\"", "\\\"", "\"", ",", "commentLine", ")", "\n", "}", "\n", "path", ":=", "matches", "[", "1", "]", "\n", "httpMethod", ":=", "matches", "[", "2", "]", "\n\n", "operation", ".", "Path", "=", "path", "\n", "operation", ".", "HTTPMethod", "=", "strings", ".", "ToUpper", "(", "httpMethod", ")", "\n\n", "return", "nil", "\n", "}" ]
// ParseRouterComment parses comment for gived `router` comment string.
[ "ParseRouterComment", "parses", "comment", "for", "gived", "router", "comment", "string", "." ]
2a7b9f41f0361c4bf8145a5369b01b189aaa7245
https://github.com/swaggo/swag/blob/2a7b9f41f0361c4bf8145a5369b01b189aaa7245/operation.go#L392-L405
train
swaggo/swag
operation.go
ParseSecurityComment
func (operation *Operation) ParseSecurityComment(commentLine string) error { securitySource := commentLine[strings.Index(commentLine, "@Security")+1:] l := strings.Index(securitySource, "[") r := strings.Index(securitySource, "]") // exists scope if !(l == -1 && r == -1) { scopes := securitySource[l+1 : r] s := []string{} for _, scope := range strings.Split(scopes, ",") { scope = strings.TrimSpace(scope) s = append(s, scope) } securityKey := securitySource[0:l] securityMap := map[string][]string{} securityMap[securityKey] = append(securityMap[securityKey], s...) operation.Security = append(operation.Security, securityMap) } else { securityKey := strings.TrimSpace(securitySource) securityMap := map[string][]string{} securityMap[securityKey] = []string{} operation.Security = append(operation.Security, securityMap) } return nil }
go
func (operation *Operation) ParseSecurityComment(commentLine string) error { securitySource := commentLine[strings.Index(commentLine, "@Security")+1:] l := strings.Index(securitySource, "[") r := strings.Index(securitySource, "]") // exists scope if !(l == -1 && r == -1) { scopes := securitySource[l+1 : r] s := []string{} for _, scope := range strings.Split(scopes, ",") { scope = strings.TrimSpace(scope) s = append(s, scope) } securityKey := securitySource[0:l] securityMap := map[string][]string{} securityMap[securityKey] = append(securityMap[securityKey], s...) operation.Security = append(operation.Security, securityMap) } else { securityKey := strings.TrimSpace(securitySource) securityMap := map[string][]string{} securityMap[securityKey] = []string{} operation.Security = append(operation.Security, securityMap) } return nil }
[ "func", "(", "operation", "*", "Operation", ")", "ParseSecurityComment", "(", "commentLine", "string", ")", "error", "{", "securitySource", ":=", "commentLine", "[", "strings", ".", "Index", "(", "commentLine", ",", "\"", "\"", ")", "+", "1", ":", "]", "\n", "l", ":=", "strings", ".", "Index", "(", "securitySource", ",", "\"", "\"", ")", "\n", "r", ":=", "strings", ".", "Index", "(", "securitySource", ",", "\"", "\"", ")", "\n", "// exists scope", "if", "!", "(", "l", "==", "-", "1", "&&", "r", "==", "-", "1", ")", "{", "scopes", ":=", "securitySource", "[", "l", "+", "1", ":", "r", "]", "\n", "s", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "scope", ":=", "range", "strings", ".", "Split", "(", "scopes", ",", "\"", "\"", ")", "{", "scope", "=", "strings", ".", "TrimSpace", "(", "scope", ")", "\n", "s", "=", "append", "(", "s", ",", "scope", ")", "\n", "}", "\n", "securityKey", ":=", "securitySource", "[", "0", ":", "l", "]", "\n", "securityMap", ":=", "map", "[", "string", "]", "[", "]", "string", "{", "}", "\n", "securityMap", "[", "securityKey", "]", "=", "append", "(", "securityMap", "[", "securityKey", "]", ",", "s", "...", ")", "\n", "operation", ".", "Security", "=", "append", "(", "operation", ".", "Security", ",", "securityMap", ")", "\n", "}", "else", "{", "securityKey", ":=", "strings", ".", "TrimSpace", "(", "securitySource", ")", "\n", "securityMap", ":=", "map", "[", "string", "]", "[", "]", "string", "{", "}", "\n", "securityMap", "[", "securityKey", "]", "=", "[", "]", "string", "{", "}", "\n", "operation", ".", "Security", "=", "append", "(", "operation", ".", "Security", ",", "securityMap", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ParseSecurityComment parses comment for gived `security` comment string.
[ "ParseSecurityComment", "parses", "comment", "for", "gived", "security", "comment", "string", "." ]
2a7b9f41f0361c4bf8145a5369b01b189aaa7245
https://github.com/swaggo/swag/blob/2a7b9f41f0361c4bf8145a5369b01b189aaa7245/operation.go#L408-L431
train
swaggo/swag
operation.go
ParseResponseComment
func (operation *Operation) ParseResponseComment(commentLine string, astFile *ast.File) error { var matches []string if matches = responsePattern.FindStringSubmatch(commentLine); len(matches) != 5 { return fmt.Errorf("can not parse response comment \"%s\"", commentLine) } response := spec.Response{} code, _ := strconv.Atoi(matches[1]) responseDescription := strings.Trim(matches[4], "\"") if responseDescription == "" { responseDescription = http.StatusText(code) } response.Description = responseDescription schemaType := strings.Trim(matches[2], "{}") refType := matches[3] if operation.parser != nil { // checking refType has existing in 'TypeDefinitions' if err := operation.registerSchemaType(refType, astFile); err != nil { return err } } // so we have to know all type in app //TODO: we might omitted schema.type if schemaType equals 'object' response.Schema = &spec.Schema{SchemaProps: spec.SchemaProps{Type: []string{schemaType}}} if schemaType == "object" { response.Schema.Ref = spec.Ref{ Ref: jsonreference.MustCreateRef("#/definitions/" + refType), } } if schemaType == "array" { refType = TransToValidSchemeType(refType) if IsPrimitiveType(refType) { response.Schema.Items = &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Type: spec.StringOrArray{refType}, }, }, } } else { response.Schema.Items = &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Ref: spec.Ref{Ref: jsonreference.MustCreateRef("#/definitions/" + refType)}, }, }, } } } if operation.Responses == nil { operation.Responses = &spec.Responses{ ResponsesProps: spec.ResponsesProps{ StatusCodeResponses: make(map[int]spec.Response), }, } } operation.Responses.StatusCodeResponses[code] = response return nil }
go
func (operation *Operation) ParseResponseComment(commentLine string, astFile *ast.File) error { var matches []string if matches = responsePattern.FindStringSubmatch(commentLine); len(matches) != 5 { return fmt.Errorf("can not parse response comment \"%s\"", commentLine) } response := spec.Response{} code, _ := strconv.Atoi(matches[1]) responseDescription := strings.Trim(matches[4], "\"") if responseDescription == "" { responseDescription = http.StatusText(code) } response.Description = responseDescription schemaType := strings.Trim(matches[2], "{}") refType := matches[3] if operation.parser != nil { // checking refType has existing in 'TypeDefinitions' if err := operation.registerSchemaType(refType, astFile); err != nil { return err } } // so we have to know all type in app //TODO: we might omitted schema.type if schemaType equals 'object' response.Schema = &spec.Schema{SchemaProps: spec.SchemaProps{Type: []string{schemaType}}} if schemaType == "object" { response.Schema.Ref = spec.Ref{ Ref: jsonreference.MustCreateRef("#/definitions/" + refType), } } if schemaType == "array" { refType = TransToValidSchemeType(refType) if IsPrimitiveType(refType) { response.Schema.Items = &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Type: spec.StringOrArray{refType}, }, }, } } else { response.Schema.Items = &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Ref: spec.Ref{Ref: jsonreference.MustCreateRef("#/definitions/" + refType)}, }, }, } } } if operation.Responses == nil { operation.Responses = &spec.Responses{ ResponsesProps: spec.ResponsesProps{ StatusCodeResponses: make(map[int]spec.Response), }, } } operation.Responses.StatusCodeResponses[code] = response return nil }
[ "func", "(", "operation", "*", "Operation", ")", "ParseResponseComment", "(", "commentLine", "string", ",", "astFile", "*", "ast", ".", "File", ")", "error", "{", "var", "matches", "[", "]", "string", "\n\n", "if", "matches", "=", "responsePattern", ".", "FindStringSubmatch", "(", "commentLine", ")", ";", "len", "(", "matches", ")", "!=", "5", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\\\"", "\\\"", "\"", ",", "commentLine", ")", "\n", "}", "\n\n", "response", ":=", "spec", ".", "Response", "{", "}", "\n\n", "code", ",", "_", ":=", "strconv", ".", "Atoi", "(", "matches", "[", "1", "]", ")", "\n\n", "responseDescription", ":=", "strings", ".", "Trim", "(", "matches", "[", "4", "]", ",", "\"", "\\\"", "\"", ")", "\n", "if", "responseDescription", "==", "\"", "\"", "{", "responseDescription", "=", "http", ".", "StatusText", "(", "code", ")", "\n", "}", "\n", "response", ".", "Description", "=", "responseDescription", "\n\n", "schemaType", ":=", "strings", ".", "Trim", "(", "matches", "[", "2", "]", ",", "\"", "\"", ")", "\n", "refType", ":=", "matches", "[", "3", "]", "\n\n", "if", "operation", ".", "parser", "!=", "nil", "{", "// checking refType has existing in 'TypeDefinitions'", "if", "err", ":=", "operation", ".", "registerSchemaType", "(", "refType", ",", "astFile", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "// so we have to know all type in app", "//TODO: we might omitted schema.type if schemaType equals 'object'", "response", ".", "Schema", "=", "&", "spec", ".", "Schema", "{", "SchemaProps", ":", "spec", ".", "SchemaProps", "{", "Type", ":", "[", "]", "string", "{", "schemaType", "}", "}", "}", "\n\n", "if", "schemaType", "==", "\"", "\"", "{", "response", ".", "Schema", ".", "Ref", "=", "spec", ".", "Ref", "{", "Ref", ":", "jsonreference", ".", "MustCreateRef", "(", "\"", "\"", "+", "refType", ")", ",", "}", "\n", "}", "\n\n", "if", "schemaType", "==", "\"", "\"", "{", "refType", "=", "TransToValidSchemeType", "(", "refType", ")", "\n", "if", "IsPrimitiveType", "(", "refType", ")", "{", "response", ".", "Schema", ".", "Items", "=", "&", "spec", ".", "SchemaOrArray", "{", "Schema", ":", "&", "spec", ".", "Schema", "{", "SchemaProps", ":", "spec", ".", "SchemaProps", "{", "Type", ":", "spec", ".", "StringOrArray", "{", "refType", "}", ",", "}", ",", "}", ",", "}", "\n", "}", "else", "{", "response", ".", "Schema", ".", "Items", "=", "&", "spec", ".", "SchemaOrArray", "{", "Schema", ":", "&", "spec", ".", "Schema", "{", "SchemaProps", ":", "spec", ".", "SchemaProps", "{", "Ref", ":", "spec", ".", "Ref", "{", "Ref", ":", "jsonreference", ".", "MustCreateRef", "(", "\"", "\"", "+", "refType", ")", "}", ",", "}", ",", "}", ",", "}", "\n", "}", "\n", "}", "\n\n", "if", "operation", ".", "Responses", "==", "nil", "{", "operation", ".", "Responses", "=", "&", "spec", ".", "Responses", "{", "ResponsesProps", ":", "spec", ".", "ResponsesProps", "{", "StatusCodeResponses", ":", "make", "(", "map", "[", "int", "]", "spec", ".", "Response", ")", ",", "}", ",", "}", "\n", "}", "\n\n", "operation", ".", "Responses", ".", "StatusCodeResponses", "[", "code", "]", "=", "response", "\n\n", "return", "nil", "\n", "}" ]
// ParseResponseComment parses comment for gived `response` comment string.
[ "ParseResponseComment", "parses", "comment", "for", "gived", "response", "comment", "string", "." ]
2a7b9f41f0361c4bf8145a5369b01b189aaa7245
https://github.com/swaggo/swag/blob/2a7b9f41f0361c4bf8145a5369b01b189aaa7245/operation.go#L491-L559
train
swaggo/swag
operation.go
ParseResponseHeaderComment
func (operation *Operation) ParseResponseHeaderComment(commentLine string, astFile *ast.File) error { var matches []string if matches = responsePattern.FindStringSubmatch(commentLine); len(matches) != 5 { return fmt.Errorf("can not parse response comment \"%s\"", commentLine) } response := spec.Response{} code, _ := strconv.Atoi(matches[1]) responseDescription := strings.Trim(matches[4], "\"") if responseDescription == "" { responseDescription = http.StatusText(code) } response.Description = responseDescription schemaType := strings.Trim(matches[2], "{}") refType := matches[3] if operation.Responses == nil { operation.Responses = &spec.Responses{ ResponsesProps: spec.ResponsesProps{ StatusCodeResponses: make(map[int]spec.Response), }, } } response, responseExist := operation.Responses.StatusCodeResponses[code] if responseExist { header := spec.Header{} header.Description = responseDescription header.Type = schemaType if response.Headers == nil { response.Headers = make(map[string]spec.Header) } response.Headers[refType] = header operation.Responses.StatusCodeResponses[code] = response } return nil }
go
func (operation *Operation) ParseResponseHeaderComment(commentLine string, astFile *ast.File) error { var matches []string if matches = responsePattern.FindStringSubmatch(commentLine); len(matches) != 5 { return fmt.Errorf("can not parse response comment \"%s\"", commentLine) } response := spec.Response{} code, _ := strconv.Atoi(matches[1]) responseDescription := strings.Trim(matches[4], "\"") if responseDescription == "" { responseDescription = http.StatusText(code) } response.Description = responseDescription schemaType := strings.Trim(matches[2], "{}") refType := matches[3] if operation.Responses == nil { operation.Responses = &spec.Responses{ ResponsesProps: spec.ResponsesProps{ StatusCodeResponses: make(map[int]spec.Response), }, } } response, responseExist := operation.Responses.StatusCodeResponses[code] if responseExist { header := spec.Header{} header.Description = responseDescription header.Type = schemaType if response.Headers == nil { response.Headers = make(map[string]spec.Header) } response.Headers[refType] = header operation.Responses.StatusCodeResponses[code] = response } return nil }
[ "func", "(", "operation", "*", "Operation", ")", "ParseResponseHeaderComment", "(", "commentLine", "string", ",", "astFile", "*", "ast", ".", "File", ")", "error", "{", "var", "matches", "[", "]", "string", "\n\n", "if", "matches", "=", "responsePattern", ".", "FindStringSubmatch", "(", "commentLine", ")", ";", "len", "(", "matches", ")", "!=", "5", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\\\"", "\\\"", "\"", ",", "commentLine", ")", "\n", "}", "\n\n", "response", ":=", "spec", ".", "Response", "{", "}", "\n\n", "code", ",", "_", ":=", "strconv", ".", "Atoi", "(", "matches", "[", "1", "]", ")", "\n\n", "responseDescription", ":=", "strings", ".", "Trim", "(", "matches", "[", "4", "]", ",", "\"", "\\\"", "\"", ")", "\n", "if", "responseDescription", "==", "\"", "\"", "{", "responseDescription", "=", "http", ".", "StatusText", "(", "code", ")", "\n", "}", "\n", "response", ".", "Description", "=", "responseDescription", "\n\n", "schemaType", ":=", "strings", ".", "Trim", "(", "matches", "[", "2", "]", ",", "\"", "\"", ")", "\n", "refType", ":=", "matches", "[", "3", "]", "\n\n", "if", "operation", ".", "Responses", "==", "nil", "{", "operation", ".", "Responses", "=", "&", "spec", ".", "Responses", "{", "ResponsesProps", ":", "spec", ".", "ResponsesProps", "{", "StatusCodeResponses", ":", "make", "(", "map", "[", "int", "]", "spec", ".", "Response", ")", ",", "}", ",", "}", "\n", "}", "\n\n", "response", ",", "responseExist", ":=", "operation", ".", "Responses", ".", "StatusCodeResponses", "[", "code", "]", "\n", "if", "responseExist", "{", "header", ":=", "spec", ".", "Header", "{", "}", "\n", "header", ".", "Description", "=", "responseDescription", "\n", "header", ".", "Type", "=", "schemaType", "\n\n", "if", "response", ".", "Headers", "==", "nil", "{", "response", ".", "Headers", "=", "make", "(", "map", "[", "string", "]", "spec", ".", "Header", ")", "\n", "}", "\n", "response", ".", "Headers", "[", "refType", "]", "=", "header", "\n\n", "operation", ".", "Responses", ".", "StatusCodeResponses", "[", "code", "]", "=", "response", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// ParseResponseHeaderComment parses comment for gived `response header` comment string.
[ "ParseResponseHeaderComment", "parses", "comment", "for", "gived", "response", "header", "comment", "string", "." ]
2a7b9f41f0361c4bf8145a5369b01b189aaa7245
https://github.com/swaggo/swag/blob/2a7b9f41f0361c4bf8145a5369b01b189aaa7245/operation.go#L562-L605
train
swaggo/swag
operation.go
createParameter
func createParameter(paramType, description, paramName, schemaType string, required bool) spec.Parameter { // //five possible parameter types. query, path, body, header, form paramProps := spec.ParamProps{ Name: paramName, Description: description, Required: required, In: paramType, } if paramType == "body" { paramProps.Schema = &spec.Schema{ SchemaProps: spec.SchemaProps{ Type: []string{schemaType}, }, } parameter := spec.Parameter{ ParamProps: paramProps, } return parameter } parameter := spec.Parameter{ ParamProps: paramProps, SimpleSchema: spec.SimpleSchema{ Type: schemaType, }, } return parameter }
go
func createParameter(paramType, description, paramName, schemaType string, required bool) spec.Parameter { // //five possible parameter types. query, path, body, header, form paramProps := spec.ParamProps{ Name: paramName, Description: description, Required: required, In: paramType, } if paramType == "body" { paramProps.Schema = &spec.Schema{ SchemaProps: spec.SchemaProps{ Type: []string{schemaType}, }, } parameter := spec.Parameter{ ParamProps: paramProps, } return parameter } parameter := spec.Parameter{ ParamProps: paramProps, SimpleSchema: spec.SimpleSchema{ Type: schemaType, }, } return parameter }
[ "func", "createParameter", "(", "paramType", ",", "description", ",", "paramName", ",", "schemaType", "string", ",", "required", "bool", ")", "spec", ".", "Parameter", "{", "// //five possible parameter types. \tquery, path, body, header, form", "paramProps", ":=", "spec", ".", "ParamProps", "{", "Name", ":", "paramName", ",", "Description", ":", "description", ",", "Required", ":", "required", ",", "In", ":", "paramType", ",", "}", "\n", "if", "paramType", "==", "\"", "\"", "{", "paramProps", ".", "Schema", "=", "&", "spec", ".", "Schema", "{", "SchemaProps", ":", "spec", ".", "SchemaProps", "{", "Type", ":", "[", "]", "string", "{", "schemaType", "}", ",", "}", ",", "}", "\n", "parameter", ":=", "spec", ".", "Parameter", "{", "ParamProps", ":", "paramProps", ",", "}", "\n", "return", "parameter", "\n", "}", "\n", "parameter", ":=", "spec", ".", "Parameter", "{", "ParamProps", ":", "paramProps", ",", "SimpleSchema", ":", "spec", ".", "SimpleSchema", "{", "Type", ":", "schemaType", ",", "}", ",", "}", "\n", "return", "parameter", "\n", "}" ]
// createParameter returns swagger spec.Parameter for gived paramType, description, paramName, schemaType, required
[ "createParameter", "returns", "swagger", "spec", ".", "Parameter", "for", "gived", "paramType", "description", "paramName", "schemaType", "required" ]
2a7b9f41f0361c4bf8145a5369b01b189aaa7245
https://github.com/swaggo/swag/blob/2a7b9f41f0361c4bf8145a5369b01b189aaa7245/operation.go#L658-L684
train
swaggo/swag
swagger.go
Register
func Register(name string, swagger Swagger) { swaggerMu.Lock() defer swaggerMu.Unlock() if swagger == nil { panic("swagger is nil") } if swag != nil { panic("Register called twice for swag: " + name) } swag = swagger }
go
func Register(name string, swagger Swagger) { swaggerMu.Lock() defer swaggerMu.Unlock() if swagger == nil { panic("swagger is nil") } if swag != nil { panic("Register called twice for swag: " + name) } swag = swagger }
[ "func", "Register", "(", "name", "string", ",", "swagger", "Swagger", ")", "{", "swaggerMu", ".", "Lock", "(", ")", "\n", "defer", "swaggerMu", ".", "Unlock", "(", ")", "\n", "if", "swagger", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "swag", "!=", "nil", "{", "panic", "(", "\"", "\"", "+", "name", ")", "\n", "}", "\n", "swag", "=", "swagger", "\n", "}" ]
// Register registers swagger for given name.
[ "Register", "registers", "swagger", "for", "given", "name", "." ]
2a7b9f41f0361c4bf8145a5369b01b189aaa7245
https://github.com/swaggo/swag/blob/2a7b9f41f0361c4bf8145a5369b01b189aaa7245/swagger.go#L22-L33
train
swaggo/swag
swagger.go
ReadDoc
func ReadDoc() (string, error) { if swag != nil { return swag.ReadDoc(), nil } return "", errors.New("not yet registered swag") }
go
func ReadDoc() (string, error) { if swag != nil { return swag.ReadDoc(), nil } return "", errors.New("not yet registered swag") }
[ "func", "ReadDoc", "(", ")", "(", "string", ",", "error", ")", "{", "if", "swag", "!=", "nil", "{", "return", "swag", ".", "ReadDoc", "(", ")", ",", "nil", "\n", "}", "\n", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// ReadDoc reads swagger document.
[ "ReadDoc", "reads", "swagger", "document", "." ]
2a7b9f41f0361c4bf8145a5369b01b189aaa7245
https://github.com/swaggo/swag/blob/2a7b9f41f0361c4bf8145a5369b01b189aaa7245/swagger.go#L36-L41
train
swaggo/swag
parser.go
New
func New() *Parser { parser := &Parser{ swagger: &spec.Swagger{ SwaggerProps: spec.SwaggerProps{ Info: &spec.Info{ InfoProps: spec.InfoProps{ Contact: &spec.ContactInfo{}, License: &spec.License{}, }, }, Paths: &spec.Paths{ Paths: make(map[string]spec.PathItem), }, Definitions: make(map[string]spec.Schema), }, }, files: make(map[string]*ast.File), TypeDefinitions: make(map[string]map[string]*ast.TypeSpec), CustomPrimitiveTypes: make(map[string]string), registerTypes: make(map[string]*ast.TypeSpec), } return parser }
go
func New() *Parser { parser := &Parser{ swagger: &spec.Swagger{ SwaggerProps: spec.SwaggerProps{ Info: &spec.Info{ InfoProps: spec.InfoProps{ Contact: &spec.ContactInfo{}, License: &spec.License{}, }, }, Paths: &spec.Paths{ Paths: make(map[string]spec.PathItem), }, Definitions: make(map[string]spec.Schema), }, }, files: make(map[string]*ast.File), TypeDefinitions: make(map[string]map[string]*ast.TypeSpec), CustomPrimitiveTypes: make(map[string]string), registerTypes: make(map[string]*ast.TypeSpec), } return parser }
[ "func", "New", "(", ")", "*", "Parser", "{", "parser", ":=", "&", "Parser", "{", "swagger", ":", "&", "spec", ".", "Swagger", "{", "SwaggerProps", ":", "spec", ".", "SwaggerProps", "{", "Info", ":", "&", "spec", ".", "Info", "{", "InfoProps", ":", "spec", ".", "InfoProps", "{", "Contact", ":", "&", "spec", ".", "ContactInfo", "{", "}", ",", "License", ":", "&", "spec", ".", "License", "{", "}", ",", "}", ",", "}", ",", "Paths", ":", "&", "spec", ".", "Paths", "{", "Paths", ":", "make", "(", "map", "[", "string", "]", "spec", ".", "PathItem", ")", ",", "}", ",", "Definitions", ":", "make", "(", "map", "[", "string", "]", "spec", ".", "Schema", ")", ",", "}", ",", "}", ",", "files", ":", "make", "(", "map", "[", "string", "]", "*", "ast", ".", "File", ")", ",", "TypeDefinitions", ":", "make", "(", "map", "[", "string", "]", "map", "[", "string", "]", "*", "ast", ".", "TypeSpec", ")", ",", "CustomPrimitiveTypes", ":", "make", "(", "map", "[", "string", "]", "string", ")", ",", "registerTypes", ":", "make", "(", "map", "[", "string", "]", "*", "ast", ".", "TypeSpec", ")", ",", "}", "\n", "return", "parser", "\n", "}" ]
// New creates a new Parser with default properties.
[ "New", "creates", "a", "new", "Parser", "with", "default", "properties", "." ]
2a7b9f41f0361c4bf8145a5369b01b189aaa7245
https://github.com/swaggo/swag/blob/2a7b9f41f0361c4bf8145a5369b01b189aaa7245/parser.go#L60-L82
train
swaggo/swag
parser.go
ParseAPI
func (parser *Parser) ParseAPI(searchDir string, mainAPIFile string) error { Println("Generate general API Info") if err := parser.getAllGoFileInfo(searchDir); err != nil { return err } parser.ParseGeneralAPIInfo(path.Join(searchDir, mainAPIFile)) for _, astFile := range parser.files { parser.ParseType(astFile) } for fileName, astFile := range parser.files { if err := parser.ParseRouterAPIInfo(fileName, astFile); err != nil { return err } } parser.ParseDefinitions() return nil }
go
func (parser *Parser) ParseAPI(searchDir string, mainAPIFile string) error { Println("Generate general API Info") if err := parser.getAllGoFileInfo(searchDir); err != nil { return err } parser.ParseGeneralAPIInfo(path.Join(searchDir, mainAPIFile)) for _, astFile := range parser.files { parser.ParseType(astFile) } for fileName, astFile := range parser.files { if err := parser.ParseRouterAPIInfo(fileName, astFile); err != nil { return err } } parser.ParseDefinitions() return nil }
[ "func", "(", "parser", "*", "Parser", ")", "ParseAPI", "(", "searchDir", "string", ",", "mainAPIFile", "string", ")", "error", "{", "Println", "(", "\"", "\"", ")", "\n", "if", "err", ":=", "parser", ".", "getAllGoFileInfo", "(", "searchDir", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "parser", ".", "ParseGeneralAPIInfo", "(", "path", ".", "Join", "(", "searchDir", ",", "mainAPIFile", ")", ")", "\n\n", "for", "_", ",", "astFile", ":=", "range", "parser", ".", "files", "{", "parser", ".", "ParseType", "(", "astFile", ")", "\n", "}", "\n\n", "for", "fileName", ",", "astFile", ":=", "range", "parser", ".", "files", "{", "if", "err", ":=", "parser", ".", "ParseRouterAPIInfo", "(", "fileName", ",", "astFile", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "parser", ".", "ParseDefinitions", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// ParseAPI parses general api info for gived searchDir and mainAPIFile
[ "ParseAPI", "parses", "general", "api", "info", "for", "gived", "searchDir", "and", "mainAPIFile" ]
2a7b9f41f0361c4bf8145a5369b01b189aaa7245
https://github.com/swaggo/swag/blob/2a7b9f41f0361c4bf8145a5369b01b189aaa7245/parser.go#L85-L105
train
swaggo/swag
parser.go
getSchemes
func getSchemes(commentLine string) []string { attribute := strings.ToLower(strings.Split(commentLine, " ")[0]) return strings.Split(strings.TrimSpace(commentLine[len(attribute):]), " ") }
go
func getSchemes(commentLine string) []string { attribute := strings.ToLower(strings.Split(commentLine, " ")[0]) return strings.Split(strings.TrimSpace(commentLine[len(attribute):]), " ") }
[ "func", "getSchemes", "(", "commentLine", "string", ")", "[", "]", "string", "{", "attribute", ":=", "strings", ".", "ToLower", "(", "strings", ".", "Split", "(", "commentLine", ",", "\"", "\"", ")", "[", "0", "]", ")", "\n", "return", "strings", ".", "Split", "(", "strings", ".", "TrimSpace", "(", "commentLine", "[", "len", "(", "attribute", ")", ":", "]", ")", ",", "\"", "\"", ")", "\n", "}" ]
// getSchemes parses swagger schemes for given commentLine
[ "getSchemes", "parses", "swagger", "schemes", "for", "given", "commentLine" ]
2a7b9f41f0361c4bf8145a5369b01b189aaa7245
https://github.com/swaggo/swag/blob/2a7b9f41f0361c4bf8145a5369b01b189aaa7245/parser.go#L381-L384
train
swaggo/swag
parser.go
ParseRouterAPIInfo
func (parser *Parser) ParseRouterAPIInfo(fileName string, astFile *ast.File) error { for _, astDescription := range astFile.Decls { switch astDeclaration := astDescription.(type) { case *ast.FuncDecl: if astDeclaration.Doc != nil && astDeclaration.Doc.List != nil { operation := NewOperation() //for per 'function' comment, create a new 'Operation' object operation.parser = parser for _, comment := range astDeclaration.Doc.List { if err := operation.ParseComment(comment.Text, astFile); err != nil { return fmt.Errorf("ParseComment error in file %s :%+v", fileName, err) } } var pathItem spec.PathItem var ok bool if pathItem, ok = parser.swagger.Paths.Paths[operation.Path]; !ok { pathItem = spec.PathItem{} } switch strings.ToUpper(operation.HTTPMethod) { case http.MethodGet: pathItem.Get = &operation.Operation case http.MethodPost: pathItem.Post = &operation.Operation case http.MethodDelete: pathItem.Delete = &operation.Operation case http.MethodPut: pathItem.Put = &operation.Operation case http.MethodPatch: pathItem.Patch = &operation.Operation case http.MethodHead: pathItem.Head = &operation.Operation case http.MethodOptions: pathItem.Options = &operation.Operation } parser.swagger.Paths.Paths[operation.Path] = pathItem } } } return nil }
go
func (parser *Parser) ParseRouterAPIInfo(fileName string, astFile *ast.File) error { for _, astDescription := range astFile.Decls { switch astDeclaration := astDescription.(type) { case *ast.FuncDecl: if astDeclaration.Doc != nil && astDeclaration.Doc.List != nil { operation := NewOperation() //for per 'function' comment, create a new 'Operation' object operation.parser = parser for _, comment := range astDeclaration.Doc.List { if err := operation.ParseComment(comment.Text, astFile); err != nil { return fmt.Errorf("ParseComment error in file %s :%+v", fileName, err) } } var pathItem spec.PathItem var ok bool if pathItem, ok = parser.swagger.Paths.Paths[operation.Path]; !ok { pathItem = spec.PathItem{} } switch strings.ToUpper(operation.HTTPMethod) { case http.MethodGet: pathItem.Get = &operation.Operation case http.MethodPost: pathItem.Post = &operation.Operation case http.MethodDelete: pathItem.Delete = &operation.Operation case http.MethodPut: pathItem.Put = &operation.Operation case http.MethodPatch: pathItem.Patch = &operation.Operation case http.MethodHead: pathItem.Head = &operation.Operation case http.MethodOptions: pathItem.Options = &operation.Operation } parser.swagger.Paths.Paths[operation.Path] = pathItem } } } return nil }
[ "func", "(", "parser", "*", "Parser", ")", "ParseRouterAPIInfo", "(", "fileName", "string", ",", "astFile", "*", "ast", ".", "File", ")", "error", "{", "for", "_", ",", "astDescription", ":=", "range", "astFile", ".", "Decls", "{", "switch", "astDeclaration", ":=", "astDescription", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "FuncDecl", ":", "if", "astDeclaration", ".", "Doc", "!=", "nil", "&&", "astDeclaration", ".", "Doc", ".", "List", "!=", "nil", "{", "operation", ":=", "NewOperation", "(", ")", "//for per 'function' comment, create a new 'Operation' object", "\n", "operation", ".", "parser", "=", "parser", "\n", "for", "_", ",", "comment", ":=", "range", "astDeclaration", ".", "Doc", ".", "List", "{", "if", "err", ":=", "operation", ".", "ParseComment", "(", "comment", ".", "Text", ",", "astFile", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "fileName", ",", "err", ")", "\n", "}", "\n", "}", "\n", "var", "pathItem", "spec", ".", "PathItem", "\n", "var", "ok", "bool", "\n\n", "if", "pathItem", ",", "ok", "=", "parser", ".", "swagger", ".", "Paths", ".", "Paths", "[", "operation", ".", "Path", "]", ";", "!", "ok", "{", "pathItem", "=", "spec", ".", "PathItem", "{", "}", "\n", "}", "\n", "switch", "strings", ".", "ToUpper", "(", "operation", ".", "HTTPMethod", ")", "{", "case", "http", ".", "MethodGet", ":", "pathItem", ".", "Get", "=", "&", "operation", ".", "Operation", "\n", "case", "http", ".", "MethodPost", ":", "pathItem", ".", "Post", "=", "&", "operation", ".", "Operation", "\n", "case", "http", ".", "MethodDelete", ":", "pathItem", ".", "Delete", "=", "&", "operation", ".", "Operation", "\n", "case", "http", ".", "MethodPut", ":", "pathItem", ".", "Put", "=", "&", "operation", ".", "Operation", "\n", "case", "http", ".", "MethodPatch", ":", "pathItem", ".", "Patch", "=", "&", "operation", ".", "Operation", "\n", "case", "http", ".", "MethodHead", ":", "pathItem", ".", "Head", "=", "&", "operation", ".", "Operation", "\n", "case", "http", ".", "MethodOptions", ":", "pathItem", ".", "Options", "=", "&", "operation", ".", "Operation", "\n", "}", "\n\n", "parser", ".", "swagger", ".", "Paths", ".", "Paths", "[", "operation", ".", "Path", "]", "=", "pathItem", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// ParseRouterAPIInfo parses router api info for given astFile
[ "ParseRouterAPIInfo", "parses", "router", "api", "info", "for", "given", "astFile" ]
2a7b9f41f0361c4bf8145a5369b01b189aaa7245
https://github.com/swaggo/swag/blob/2a7b9f41f0361c4bf8145a5369b01b189aaa7245/parser.go#L387-L428
train
swaggo/swag
parser.go
ParseType
func (parser *Parser) ParseType(astFile *ast.File) { if _, ok := parser.TypeDefinitions[astFile.Name.String()]; !ok { parser.TypeDefinitions[astFile.Name.String()] = make(map[string]*ast.TypeSpec) } for _, astDeclaration := range astFile.Decls { if generalDeclaration, ok := astDeclaration.(*ast.GenDecl); ok && generalDeclaration.Tok == token.TYPE { for _, astSpec := range generalDeclaration.Specs { if typeSpec, ok := astSpec.(*ast.TypeSpec); ok { typeName := fmt.Sprintf("%v", typeSpec.Type) // check if its a custom primitive type if IsGolangPrimitiveType(typeName) { parser.CustomPrimitiveTypes[typeSpec.Name.String()] = TransToValidSchemeType(typeName) } else { parser.TypeDefinitions[astFile.Name.String()][typeSpec.Name.String()] = typeSpec } } } } } }
go
func (parser *Parser) ParseType(astFile *ast.File) { if _, ok := parser.TypeDefinitions[astFile.Name.String()]; !ok { parser.TypeDefinitions[astFile.Name.String()] = make(map[string]*ast.TypeSpec) } for _, astDeclaration := range astFile.Decls { if generalDeclaration, ok := astDeclaration.(*ast.GenDecl); ok && generalDeclaration.Tok == token.TYPE { for _, astSpec := range generalDeclaration.Specs { if typeSpec, ok := astSpec.(*ast.TypeSpec); ok { typeName := fmt.Sprintf("%v", typeSpec.Type) // check if its a custom primitive type if IsGolangPrimitiveType(typeName) { parser.CustomPrimitiveTypes[typeSpec.Name.String()] = TransToValidSchemeType(typeName) } else { parser.TypeDefinitions[astFile.Name.String()][typeSpec.Name.String()] = typeSpec } } } } } }
[ "func", "(", "parser", "*", "Parser", ")", "ParseType", "(", "astFile", "*", "ast", ".", "File", ")", "{", "if", "_", ",", "ok", ":=", "parser", ".", "TypeDefinitions", "[", "astFile", ".", "Name", ".", "String", "(", ")", "]", ";", "!", "ok", "{", "parser", ".", "TypeDefinitions", "[", "astFile", ".", "Name", ".", "String", "(", ")", "]", "=", "make", "(", "map", "[", "string", "]", "*", "ast", ".", "TypeSpec", ")", "\n", "}", "\n\n", "for", "_", ",", "astDeclaration", ":=", "range", "astFile", ".", "Decls", "{", "if", "generalDeclaration", ",", "ok", ":=", "astDeclaration", ".", "(", "*", "ast", ".", "GenDecl", ")", ";", "ok", "&&", "generalDeclaration", ".", "Tok", "==", "token", ".", "TYPE", "{", "for", "_", ",", "astSpec", ":=", "range", "generalDeclaration", ".", "Specs", "{", "if", "typeSpec", ",", "ok", ":=", "astSpec", ".", "(", "*", "ast", ".", "TypeSpec", ")", ";", "ok", "{", "typeName", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "typeSpec", ".", "Type", ")", "\n", "// check if its a custom primitive type", "if", "IsGolangPrimitiveType", "(", "typeName", ")", "{", "parser", ".", "CustomPrimitiveTypes", "[", "typeSpec", ".", "Name", ".", "String", "(", ")", "]", "=", "TransToValidSchemeType", "(", "typeName", ")", "\n", "}", "else", "{", "parser", ".", "TypeDefinitions", "[", "astFile", ".", "Name", ".", "String", "(", ")", "]", "[", "typeSpec", ".", "Name", ".", "String", "(", ")", "]", "=", "typeSpec", "\n", "}", "\n\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// ParseType parses type info for given astFile.
[ "ParseType", "parses", "type", "info", "for", "given", "astFile", "." ]
2a7b9f41f0361c4bf8145a5369b01b189aaa7245
https://github.com/swaggo/swag/blob/2a7b9f41f0361c4bf8145a5369b01b189aaa7245/parser.go#L431-L452
train
swaggo/swag
parser.go
ParseDefinitions
func (parser *Parser) ParseDefinitions() { // sort the typeNames so that parsing definitions is deterministic typeNames := make([]string, 0, len(parser.registerTypes)) for refTypeName := range parser.registerTypes { typeNames = append(typeNames, refTypeName) } sort.Strings(typeNames) for _, refTypeName := range typeNames { typeSpec := parser.registerTypes[refTypeName] ss := strings.Split(refTypeName, ".") pkgName := ss[0] parser.structStack = nil parser.ParseDefinition(pkgName, typeSpec.Name.Name, typeSpec) } }
go
func (parser *Parser) ParseDefinitions() { // sort the typeNames so that parsing definitions is deterministic typeNames := make([]string, 0, len(parser.registerTypes)) for refTypeName := range parser.registerTypes { typeNames = append(typeNames, refTypeName) } sort.Strings(typeNames) for _, refTypeName := range typeNames { typeSpec := parser.registerTypes[refTypeName] ss := strings.Split(refTypeName, ".") pkgName := ss[0] parser.structStack = nil parser.ParseDefinition(pkgName, typeSpec.Name.Name, typeSpec) } }
[ "func", "(", "parser", "*", "Parser", ")", "ParseDefinitions", "(", ")", "{", "// sort the typeNames so that parsing definitions is deterministic", "typeNames", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "parser", ".", "registerTypes", ")", ")", "\n", "for", "refTypeName", ":=", "range", "parser", ".", "registerTypes", "{", "typeNames", "=", "append", "(", "typeNames", ",", "refTypeName", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "typeNames", ")", "\n\n", "for", "_", ",", "refTypeName", ":=", "range", "typeNames", "{", "typeSpec", ":=", "parser", ".", "registerTypes", "[", "refTypeName", "]", "\n", "ss", ":=", "strings", ".", "Split", "(", "refTypeName", ",", "\"", "\"", ")", "\n", "pkgName", ":=", "ss", "[", "0", "]", "\n", "parser", ".", "structStack", "=", "nil", "\n", "parser", ".", "ParseDefinition", "(", "pkgName", ",", "typeSpec", ".", "Name", ".", "Name", ",", "typeSpec", ")", "\n", "}", "\n", "}" ]
// ParseDefinitions parses Swagger Api definitions.
[ "ParseDefinitions", "parses", "Swagger", "Api", "definitions", "." ]
2a7b9f41f0361c4bf8145a5369b01b189aaa7245
https://github.com/swaggo/swag/blob/2a7b9f41f0361c4bf8145a5369b01b189aaa7245/parser.go#L464-L479
train
swaggo/swag
parser.go
ParseDefinition
func (parser *Parser) ParseDefinition(pkgName, typeName string, typeSpec *ast.TypeSpec) error { refTypeName := fullTypeName(pkgName, typeName) if _, isParsed := parser.swagger.Definitions[refTypeName]; isParsed { Println("Skipping '" + refTypeName + "', already parsed.") return nil } if parser.isInStructStack(refTypeName) { Println("Skipping '" + refTypeName + "', recursion detected.") return nil } parser.structStack = append(parser.structStack, refTypeName) Println("Generating " + refTypeName) schema, err := parser.parseTypeExpr(pkgName, typeName, typeSpec.Type) if err != nil { return err } parser.swagger.Definitions[refTypeName] = schema return nil }
go
func (parser *Parser) ParseDefinition(pkgName, typeName string, typeSpec *ast.TypeSpec) error { refTypeName := fullTypeName(pkgName, typeName) if _, isParsed := parser.swagger.Definitions[refTypeName]; isParsed { Println("Skipping '" + refTypeName + "', already parsed.") return nil } if parser.isInStructStack(refTypeName) { Println("Skipping '" + refTypeName + "', recursion detected.") return nil } parser.structStack = append(parser.structStack, refTypeName) Println("Generating " + refTypeName) schema, err := parser.parseTypeExpr(pkgName, typeName, typeSpec.Type) if err != nil { return err } parser.swagger.Definitions[refTypeName] = schema return nil }
[ "func", "(", "parser", "*", "Parser", ")", "ParseDefinition", "(", "pkgName", ",", "typeName", "string", ",", "typeSpec", "*", "ast", ".", "TypeSpec", ")", "error", "{", "refTypeName", ":=", "fullTypeName", "(", "pkgName", ",", "typeName", ")", "\n", "if", "_", ",", "isParsed", ":=", "parser", ".", "swagger", ".", "Definitions", "[", "refTypeName", "]", ";", "isParsed", "{", "Println", "(", "\"", "\"", "+", "refTypeName", "+", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "if", "parser", ".", "isInStructStack", "(", "refTypeName", ")", "{", "Println", "(", "\"", "\"", "+", "refTypeName", "+", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n", "parser", ".", "structStack", "=", "append", "(", "parser", ".", "structStack", ",", "refTypeName", ")", "\n\n", "Println", "(", "\"", "\"", "+", "refTypeName", ")", "\n\n", "schema", ",", "err", ":=", "parser", ".", "parseTypeExpr", "(", "pkgName", ",", "typeName", ",", "typeSpec", ".", "Type", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "parser", ".", "swagger", ".", "Definitions", "[", "refTypeName", "]", "=", "schema", "\n", "return", "nil", "\n", "}" ]
// ParseDefinition parses given type spec that corresponds to the type under // given name and package, and populates swagger schema definitions registry // with a schema for the given type
[ "ParseDefinition", "parses", "given", "type", "spec", "that", "corresponds", "to", "the", "type", "under", "given", "name", "and", "package", "and", "populates", "swagger", "schema", "definitions", "registry", "with", "a", "schema", "for", "the", "given", "type" ]
2a7b9f41f0361c4bf8145a5369b01b189aaa7245
https://github.com/swaggo/swag/blob/2a7b9f41f0361c4bf8145a5369b01b189aaa7245/parser.go#L484-L505
train
swaggo/swag
parser.go
getAllGoFileInfo
func (parser *Parser) getAllGoFileInfo(searchDir string) error { return filepath.Walk(searchDir, parser.visit) }
go
func (parser *Parser) getAllGoFileInfo(searchDir string) error { return filepath.Walk(searchDir, parser.visit) }
[ "func", "(", "parser", "*", "Parser", ")", "getAllGoFileInfo", "(", "searchDir", "string", ")", "error", "{", "return", "filepath", ".", "Walk", "(", "searchDir", ",", "parser", ".", "visit", ")", "\n", "}" ]
// GetAllGoFileInfo gets all Go source files information for given searchDir.
[ "GetAllGoFileInfo", "gets", "all", "Go", "source", "files", "information", "for", "given", "searchDir", "." ]
2a7b9f41f0361c4bf8145a5369b01b189aaa7245
https://github.com/swaggo/swag/blob/2a7b9f41f0361c4bf8145a5369b01b189aaa7245/parser.go#L1148-L1150
train
swaggo/swag
parser.go
Skip
func (parser *Parser) Skip(path string, f os.FileInfo) error { if !parser.ParseVendor { // ignore vendor if f.IsDir() && f.Name() == "vendor" { return filepath.SkipDir } } // exclude all hidden folder if f.IsDir() && len(f.Name()) > 1 && f.Name()[0] == '.' { return filepath.SkipDir } return nil }
go
func (parser *Parser) Skip(path string, f os.FileInfo) error { if !parser.ParseVendor { // ignore vendor if f.IsDir() && f.Name() == "vendor" { return filepath.SkipDir } } // exclude all hidden folder if f.IsDir() && len(f.Name()) > 1 && f.Name()[0] == '.' { return filepath.SkipDir } return nil }
[ "func", "(", "parser", "*", "Parser", ")", "Skip", "(", "path", "string", ",", "f", "os", ".", "FileInfo", ")", "error", "{", "if", "!", "parser", ".", "ParseVendor", "{", "// ignore vendor", "if", "f", ".", "IsDir", "(", ")", "&&", "f", ".", "Name", "(", ")", "==", "\"", "\"", "{", "return", "filepath", ".", "SkipDir", "\n", "}", "\n", "}", "\n\n", "// exclude all hidden folder", "if", "f", ".", "IsDir", "(", ")", "&&", "len", "(", "f", ".", "Name", "(", ")", ")", ">", "1", "&&", "f", ".", "Name", "(", ")", "[", "0", "]", "==", "'.'", "{", "return", "filepath", ".", "SkipDir", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Skip returns filepath.SkipDir error if match vendor and hidden folder
[ "Skip", "returns", "filepath", ".", "SkipDir", "error", "if", "match", "vendor", "and", "hidden", "folder" ]
2a7b9f41f0361c4bf8145a5369b01b189aaa7245
https://github.com/swaggo/swag/blob/2a7b9f41f0361c4bf8145a5369b01b189aaa7245/parser.go#L1170-L1183
train
tidwall/gjson
gjson_ngae.go
fillIndex
func fillIndex(json string, c *parseContext) { if len(c.value.Raw) > 0 && !c.calcd { jhdr := *(*reflect.StringHeader)(unsafe.Pointer(&json)) rhdr := *(*reflect.StringHeader)(unsafe.Pointer(&(c.value.Raw))) c.value.Index = int(rhdr.Data - jhdr.Data) if c.value.Index < 0 || c.value.Index >= len(json) { c.value.Index = 0 } } }
go
func fillIndex(json string, c *parseContext) { if len(c.value.Raw) > 0 && !c.calcd { jhdr := *(*reflect.StringHeader)(unsafe.Pointer(&json)) rhdr := *(*reflect.StringHeader)(unsafe.Pointer(&(c.value.Raw))) c.value.Index = int(rhdr.Data - jhdr.Data) if c.value.Index < 0 || c.value.Index >= len(json) { c.value.Index = 0 } } }
[ "func", "fillIndex", "(", "json", "string", ",", "c", "*", "parseContext", ")", "{", "if", "len", "(", "c", ".", "value", ".", "Raw", ")", ">", "0", "&&", "!", "c", ".", "calcd", "{", "jhdr", ":=", "*", "(", "*", "reflect", ".", "StringHeader", ")", "(", "unsafe", ".", "Pointer", "(", "&", "json", ")", ")", "\n", "rhdr", ":=", "*", "(", "*", "reflect", ".", "StringHeader", ")", "(", "unsafe", ".", "Pointer", "(", "&", "(", "c", ".", "value", ".", "Raw", ")", ")", ")", "\n", "c", ".", "value", ".", "Index", "=", "int", "(", "rhdr", ".", "Data", "-", "jhdr", ".", "Data", ")", "\n", "if", "c", ".", "value", ".", "Index", "<", "0", "||", "c", ".", "value", ".", "Index", ">=", "len", "(", "json", ")", "{", "c", ".", "value", ".", "Index", "=", "0", "\n", "}", "\n", "}", "\n", "}" ]
// fillIndex finds the position of Raw data and assigns it to the Index field // of the resulting value. If the position cannot be found then Index zero is // used instead.
[ "fillIndex", "finds", "the", "position", "of", "Raw", "data", "and", "assigns", "it", "to", "the", "Index", "field", "of", "the", "resulting", "value", ".", "If", "the", "position", "cannot", "be", "found", "then", "Index", "zero", "is", "used", "instead", "." ]
fb8e539484c9fb2df9f472bc0e3949a74c256f95
https://github.com/tidwall/gjson/blob/fb8e539484c9fb2df9f472bc0e3949a74c256f95/gjson_ngae.go#L60-L69
train
tidwall/gjson
gjson.go
String
func (t Type) String() string { switch t { default: return "" case Null: return "Null" case False: return "False" case Number: return "Number" case String: return "String" case True: return "True" case JSON: return "JSON" } }
go
func (t Type) String() string { switch t { default: return "" case Null: return "Null" case False: return "False" case Number: return "Number" case String: return "String" case True: return "True" case JSON: return "JSON" } }
[ "func", "(", "t", "Type", ")", "String", "(", ")", "string", "{", "switch", "t", "{", "default", ":", "return", "\"", "\"", "\n", "case", "Null", ":", "return", "\"", "\"", "\n", "case", "False", ":", "return", "\"", "\"", "\n", "case", "Number", ":", "return", "\"", "\"", "\n", "case", "String", ":", "return", "\"", "\"", "\n", "case", "True", ":", "return", "\"", "\"", "\n", "case", "JSON", ":", "return", "\"", "\"", "\n", "}", "\n", "}" ]
// String returns a string representation of the type.
[ "String", "returns", "a", "string", "representation", "of", "the", "type", "." ]
fb8e539484c9fb2df9f472bc0e3949a74c256f95
https://github.com/tidwall/gjson/blob/fb8e539484c9fb2df9f472bc0e3949a74c256f95/gjson.go#L40-L57
train
tidwall/gjson
gjson.go
String
func (t Result) String() string { switch t.Type { default: return "" case False: return "false" case Number: if len(t.Raw) == 0 { // calculated result return strconv.FormatFloat(t.Num, 'f', -1, 64) } var i int if t.Raw[0] == '-' { i++ } for ; i < len(t.Raw); i++ { if t.Raw[i] < '0' || t.Raw[i] > '9' { return strconv.FormatFloat(t.Num, 'f', -1, 64) } } return t.Raw case String: return t.Str case JSON: return t.Raw case True: return "true" } }
go
func (t Result) String() string { switch t.Type { default: return "" case False: return "false" case Number: if len(t.Raw) == 0 { // calculated result return strconv.FormatFloat(t.Num, 'f', -1, 64) } var i int if t.Raw[0] == '-' { i++ } for ; i < len(t.Raw); i++ { if t.Raw[i] < '0' || t.Raw[i] > '9' { return strconv.FormatFloat(t.Num, 'f', -1, 64) } } return t.Raw case String: return t.Str case JSON: return t.Raw case True: return "true" } }
[ "func", "(", "t", "Result", ")", "String", "(", ")", "string", "{", "switch", "t", ".", "Type", "{", "default", ":", "return", "\"", "\"", "\n", "case", "False", ":", "return", "\"", "\"", "\n", "case", "Number", ":", "if", "len", "(", "t", ".", "Raw", ")", "==", "0", "{", "// calculated result", "return", "strconv", ".", "FormatFloat", "(", "t", ".", "Num", ",", "'f'", ",", "-", "1", ",", "64", ")", "\n", "}", "\n", "var", "i", "int", "\n", "if", "t", ".", "Raw", "[", "0", "]", "==", "'-'", "{", "i", "++", "\n", "}", "\n", "for", ";", "i", "<", "len", "(", "t", ".", "Raw", ")", ";", "i", "++", "{", "if", "t", ".", "Raw", "[", "i", "]", "<", "'0'", "||", "t", ".", "Raw", "[", "i", "]", ">", "'9'", "{", "return", "strconv", ".", "FormatFloat", "(", "t", ".", "Num", ",", "'f'", ",", "-", "1", ",", "64", ")", "\n", "}", "\n", "}", "\n", "return", "t", ".", "Raw", "\n", "case", "String", ":", "return", "t", ".", "Str", "\n", "case", "JSON", ":", "return", "t", ".", "Raw", "\n", "case", "True", ":", "return", "\"", "\"", "\n", "}", "\n", "}" ]
// String returns a string representation of the value.
[ "String", "returns", "a", "string", "representation", "of", "the", "value", "." ]
fb8e539484c9fb2df9f472bc0e3949a74c256f95
https://github.com/tidwall/gjson/blob/fb8e539484c9fb2df9f472bc0e3949a74c256f95/gjson.go#L74-L102
train
tidwall/gjson
gjson.go
Bool
func (t Result) Bool() bool { switch t.Type { default: return false case True: return true case String: return t.Str != "" && t.Str != "0" && t.Str != "false" case Number: return t.Num != 0 } }
go
func (t Result) Bool() bool { switch t.Type { default: return false case True: return true case String: return t.Str != "" && t.Str != "0" && t.Str != "false" case Number: return t.Num != 0 } }
[ "func", "(", "t", "Result", ")", "Bool", "(", ")", "bool", "{", "switch", "t", ".", "Type", "{", "default", ":", "return", "false", "\n", "case", "True", ":", "return", "true", "\n", "case", "String", ":", "return", "t", ".", "Str", "!=", "\"", "\"", "&&", "t", ".", "Str", "!=", "\"", "\"", "&&", "t", ".", "Str", "!=", "\"", "\"", "\n", "case", "Number", ":", "return", "t", ".", "Num", "!=", "0", "\n", "}", "\n", "}" ]
// Bool returns an boolean representation.
[ "Bool", "returns", "an", "boolean", "representation", "." ]
fb8e539484c9fb2df9f472bc0e3949a74c256f95
https://github.com/tidwall/gjson/blob/fb8e539484c9fb2df9f472bc0e3949a74c256f95/gjson.go#L105-L116
train
tidwall/gjson
gjson.go
Int
func (t Result) Int() int64 { switch t.Type { default: return 0 case True: return 1 case String: n, _ := parseInt(t.Str) return n case Number: // try to directly convert the float64 to int64 n, ok := floatToInt(t.Num) if !ok { // now try to parse the raw string n, ok = parseInt(t.Raw) if !ok { // fallback to a standard conversion return int64(t.Num) } } return n } }
go
func (t Result) Int() int64 { switch t.Type { default: return 0 case True: return 1 case String: n, _ := parseInt(t.Str) return n case Number: // try to directly convert the float64 to int64 n, ok := floatToInt(t.Num) if !ok { // now try to parse the raw string n, ok = parseInt(t.Raw) if !ok { // fallback to a standard conversion return int64(t.Num) } } return n } }
[ "func", "(", "t", "Result", ")", "Int", "(", ")", "int64", "{", "switch", "t", ".", "Type", "{", "default", ":", "return", "0", "\n", "case", "True", ":", "return", "1", "\n", "case", "String", ":", "n", ",", "_", ":=", "parseInt", "(", "t", ".", "Str", ")", "\n", "return", "n", "\n", "case", "Number", ":", "// try to directly convert the float64 to int64", "n", ",", "ok", ":=", "floatToInt", "(", "t", ".", "Num", ")", "\n", "if", "!", "ok", "{", "// now try to parse the raw string", "n", ",", "ok", "=", "parseInt", "(", "t", ".", "Raw", ")", "\n", "if", "!", "ok", "{", "// fallback to a standard conversion", "return", "int64", "(", "t", ".", "Num", ")", "\n", "}", "\n", "}", "\n", "return", "n", "\n", "}", "\n", "}" ]
// Int returns an integer representation.
[ "Int", "returns", "an", "integer", "representation", "." ]
fb8e539484c9fb2df9f472bc0e3949a74c256f95
https://github.com/tidwall/gjson/blob/fb8e539484c9fb2df9f472bc0e3949a74c256f95/gjson.go#L119-L141
train
tidwall/gjson
gjson.go
Uint
func (t Result) Uint() uint64 { switch t.Type { default: return 0 case True: return 1 case String: n, _ := parseUint(t.Str) return n case Number: // try to directly convert the float64 to uint64 n, ok := floatToUint(t.Num) if !ok { // now try to parse the raw string n, ok = parseUint(t.Raw) if !ok { // fallback to a standard conversion return uint64(t.Num) } } return n } }
go
func (t Result) Uint() uint64 { switch t.Type { default: return 0 case True: return 1 case String: n, _ := parseUint(t.Str) return n case Number: // try to directly convert the float64 to uint64 n, ok := floatToUint(t.Num) if !ok { // now try to parse the raw string n, ok = parseUint(t.Raw) if !ok { // fallback to a standard conversion return uint64(t.Num) } } return n } }
[ "func", "(", "t", "Result", ")", "Uint", "(", ")", "uint64", "{", "switch", "t", ".", "Type", "{", "default", ":", "return", "0", "\n", "case", "True", ":", "return", "1", "\n", "case", "String", ":", "n", ",", "_", ":=", "parseUint", "(", "t", ".", "Str", ")", "\n", "return", "n", "\n", "case", "Number", ":", "// try to directly convert the float64 to uint64", "n", ",", "ok", ":=", "floatToUint", "(", "t", ".", "Num", ")", "\n", "if", "!", "ok", "{", "// now try to parse the raw string", "n", ",", "ok", "=", "parseUint", "(", "t", ".", "Raw", ")", "\n", "if", "!", "ok", "{", "// fallback to a standard conversion", "return", "uint64", "(", "t", ".", "Num", ")", "\n", "}", "\n", "}", "\n", "return", "n", "\n", "}", "\n", "}" ]
// Uint returns an unsigned integer representation.
[ "Uint", "returns", "an", "unsigned", "integer", "representation", "." ]
fb8e539484c9fb2df9f472bc0e3949a74c256f95
https://github.com/tidwall/gjson/blob/fb8e539484c9fb2df9f472bc0e3949a74c256f95/gjson.go#L144-L166
train
tidwall/gjson
gjson.go
Float
func (t Result) Float() float64 { switch t.Type { default: return 0 case True: return 1 case String: n, _ := strconv.ParseFloat(t.Str, 64) return n case Number: return t.Num } }
go
func (t Result) Float() float64 { switch t.Type { default: return 0 case True: return 1 case String: n, _ := strconv.ParseFloat(t.Str, 64) return n case Number: return t.Num } }
[ "func", "(", "t", "Result", ")", "Float", "(", ")", "float64", "{", "switch", "t", ".", "Type", "{", "default", ":", "return", "0", "\n", "case", "True", ":", "return", "1", "\n", "case", "String", ":", "n", ",", "_", ":=", "strconv", ".", "ParseFloat", "(", "t", ".", "Str", ",", "64", ")", "\n", "return", "n", "\n", "case", "Number", ":", "return", "t", ".", "Num", "\n", "}", "\n", "}" ]
// Float returns an float64 representation.
[ "Float", "returns", "an", "float64", "representation", "." ]
fb8e539484c9fb2df9f472bc0e3949a74c256f95
https://github.com/tidwall/gjson/blob/fb8e539484c9fb2df9f472bc0e3949a74c256f95/gjson.go#L169-L181
train
tidwall/gjson
gjson.go
Time
func (t Result) Time() time.Time { res, _ := time.Parse(time.RFC3339, t.String()) return res }
go
func (t Result) Time() time.Time { res, _ := time.Parse(time.RFC3339, t.String()) return res }
[ "func", "(", "t", "Result", ")", "Time", "(", ")", "time", ".", "Time", "{", "res", ",", "_", ":=", "time", ".", "Parse", "(", "time", ".", "RFC3339", ",", "t", ".", "String", "(", ")", ")", "\n", "return", "res", "\n", "}" ]
// Time returns a time.Time representation.
[ "Time", "returns", "a", "time", ".", "Time", "representation", "." ]
fb8e539484c9fb2df9f472bc0e3949a74c256f95
https://github.com/tidwall/gjson/blob/fb8e539484c9fb2df9f472bc0e3949a74c256f95/gjson.go#L184-L187
train
tidwall/gjson
gjson.go
Array
func (t Result) Array() []Result { if t.Type == Null { return []Result{} } if t.Type != JSON { return []Result{t} } r := t.arrayOrMap('[', false) return r.a }
go
func (t Result) Array() []Result { if t.Type == Null { return []Result{} } if t.Type != JSON { return []Result{t} } r := t.arrayOrMap('[', false) return r.a }
[ "func", "(", "t", "Result", ")", "Array", "(", ")", "[", "]", "Result", "{", "if", "t", ".", "Type", "==", "Null", "{", "return", "[", "]", "Result", "{", "}", "\n", "}", "\n", "if", "t", ".", "Type", "!=", "JSON", "{", "return", "[", "]", "Result", "{", "t", "}", "\n", "}", "\n", "r", ":=", "t", ".", "arrayOrMap", "(", "'['", ",", "false", ")", "\n", "return", "r", ".", "a", "\n", "}" ]
// Array returns back an array of values. // If the result represents a non-existent value, then an empty array will be returned. // If the result is not a JSON array, the return value will be an array containing one result.
[ "Array", "returns", "back", "an", "array", "of", "values", ".", "If", "the", "result", "represents", "a", "non", "-", "existent", "value", "then", "an", "empty", "array", "will", "be", "returned", ".", "If", "the", "result", "is", "not", "a", "JSON", "array", "the", "return", "value", "will", "be", "an", "array", "containing", "one", "result", "." ]
fb8e539484c9fb2df9f472bc0e3949a74c256f95
https://github.com/tidwall/gjson/blob/fb8e539484c9fb2df9f472bc0e3949a74c256f95/gjson.go#L192-L201
train
tidwall/gjson
gjson.go
IsObject
func (t Result) IsObject() bool { return t.Type == JSON && len(t.Raw) > 0 && t.Raw[0] == '{' }
go
func (t Result) IsObject() bool { return t.Type == JSON && len(t.Raw) > 0 && t.Raw[0] == '{' }
[ "func", "(", "t", "Result", ")", "IsObject", "(", ")", "bool", "{", "return", "t", ".", "Type", "==", "JSON", "&&", "len", "(", "t", ".", "Raw", ")", ">", "0", "&&", "t", ".", "Raw", "[", "0", "]", "==", "'{'", "\n", "}" ]
// IsObject returns true if the result value is a JSON object.
[ "IsObject", "returns", "true", "if", "the", "result", "value", "is", "a", "JSON", "object", "." ]
fb8e539484c9fb2df9f472bc0e3949a74c256f95
https://github.com/tidwall/gjson/blob/fb8e539484c9fb2df9f472bc0e3949a74c256f95/gjson.go#L204-L206
train
tidwall/gjson
gjson.go
IsArray
func (t Result) IsArray() bool { return t.Type == JSON && len(t.Raw) > 0 && t.Raw[0] == '[' }
go
func (t Result) IsArray() bool { return t.Type == JSON && len(t.Raw) > 0 && t.Raw[0] == '[' }
[ "func", "(", "t", "Result", ")", "IsArray", "(", ")", "bool", "{", "return", "t", ".", "Type", "==", "JSON", "&&", "len", "(", "t", ".", "Raw", ")", ">", "0", "&&", "t", ".", "Raw", "[", "0", "]", "==", "'['", "\n", "}" ]
// IsArray returns true if the result value is a JSON array.
[ "IsArray", "returns", "true", "if", "the", "result", "value", "is", "a", "JSON", "array", "." ]
fb8e539484c9fb2df9f472bc0e3949a74c256f95
https://github.com/tidwall/gjson/blob/fb8e539484c9fb2df9f472bc0e3949a74c256f95/gjson.go#L209-L211
train
tidwall/gjson
gjson.go
ForEach
func (t Result) ForEach(iterator func(key, value Result) bool) { if !t.Exists() { return } if t.Type != JSON { iterator(Result{}, t) return } json := t.Raw var keys bool var i int var key, value Result for ; i < len(json); i++ { if json[i] == '{' { i++ key.Type = String keys = true break } else if json[i] == '[' { i++ break } if json[i] > ' ' { return } } var str string var vesc bool var ok bool for ; i < len(json); i++ { if keys { if json[i] != '"' { continue } s := i i, str, vesc, ok = parseString(json, i+1) if !ok { return } if vesc { key.Str = unescape(str[1 : len(str)-1]) } else { key.Str = str[1 : len(str)-1] } key.Raw = str key.Index = s } for ; i < len(json); i++ { if json[i] <= ' ' || json[i] == ',' || json[i] == ':' { continue } break } s := i i, value, ok = parseAny(json, i, true) if !ok { return } value.Index = s if !iterator(key, value) { return } } }
go
func (t Result) ForEach(iterator func(key, value Result) bool) { if !t.Exists() { return } if t.Type != JSON { iterator(Result{}, t) return } json := t.Raw var keys bool var i int var key, value Result for ; i < len(json); i++ { if json[i] == '{' { i++ key.Type = String keys = true break } else if json[i] == '[' { i++ break } if json[i] > ' ' { return } } var str string var vesc bool var ok bool for ; i < len(json); i++ { if keys { if json[i] != '"' { continue } s := i i, str, vesc, ok = parseString(json, i+1) if !ok { return } if vesc { key.Str = unescape(str[1 : len(str)-1]) } else { key.Str = str[1 : len(str)-1] } key.Raw = str key.Index = s } for ; i < len(json); i++ { if json[i] <= ' ' || json[i] == ',' || json[i] == ':' { continue } break } s := i i, value, ok = parseAny(json, i, true) if !ok { return } value.Index = s if !iterator(key, value) { return } } }
[ "func", "(", "t", "Result", ")", "ForEach", "(", "iterator", "func", "(", "key", ",", "value", "Result", ")", "bool", ")", "{", "if", "!", "t", ".", "Exists", "(", ")", "{", "return", "\n", "}", "\n", "if", "t", ".", "Type", "!=", "JSON", "{", "iterator", "(", "Result", "{", "}", ",", "t", ")", "\n", "return", "\n", "}", "\n", "json", ":=", "t", ".", "Raw", "\n", "var", "keys", "bool", "\n", "var", "i", "int", "\n", "var", "key", ",", "value", "Result", "\n", "for", ";", "i", "<", "len", "(", "json", ")", ";", "i", "++", "{", "if", "json", "[", "i", "]", "==", "'{'", "{", "i", "++", "\n", "key", ".", "Type", "=", "String", "\n", "keys", "=", "true", "\n", "break", "\n", "}", "else", "if", "json", "[", "i", "]", "==", "'['", "{", "i", "++", "\n", "break", "\n", "}", "\n", "if", "json", "[", "i", "]", ">", "' '", "{", "return", "\n", "}", "\n", "}", "\n", "var", "str", "string", "\n", "var", "vesc", "bool", "\n", "var", "ok", "bool", "\n", "for", ";", "i", "<", "len", "(", "json", ")", ";", "i", "++", "{", "if", "keys", "{", "if", "json", "[", "i", "]", "!=", "'\"'", "{", "continue", "\n", "}", "\n", "s", ":=", "i", "\n", "i", ",", "str", ",", "vesc", ",", "ok", "=", "parseString", "(", "json", ",", "i", "+", "1", ")", "\n", "if", "!", "ok", "{", "return", "\n", "}", "\n", "if", "vesc", "{", "key", ".", "Str", "=", "unescape", "(", "str", "[", "1", ":", "len", "(", "str", ")", "-", "1", "]", ")", "\n", "}", "else", "{", "key", ".", "Str", "=", "str", "[", "1", ":", "len", "(", "str", ")", "-", "1", "]", "\n", "}", "\n", "key", ".", "Raw", "=", "str", "\n", "key", ".", "Index", "=", "s", "\n", "}", "\n", "for", ";", "i", "<", "len", "(", "json", ")", ";", "i", "++", "{", "if", "json", "[", "i", "]", "<=", "' '", "||", "json", "[", "i", "]", "==", "','", "||", "json", "[", "i", "]", "==", "':'", "{", "continue", "\n", "}", "\n", "break", "\n", "}", "\n", "s", ":=", "i", "\n", "i", ",", "value", ",", "ok", "=", "parseAny", "(", "json", ",", "i", ",", "true", ")", "\n", "if", "!", "ok", "{", "return", "\n", "}", "\n", "value", ".", "Index", "=", "s", "\n", "if", "!", "iterator", "(", "key", ",", "value", ")", "{", "return", "\n", "}", "\n", "}", "\n", "}" ]
// ForEach iterates through values. // If the result represents a non-existent value, then no values will be iterated. // If the result is an Object, the iterator will pass the key and value of each item. // If the result is an Array, the iterator will only pass the value of each item. // If the result is not a JSON array or object, the iterator will pass back one value equal to the result.
[ "ForEach", "iterates", "through", "values", ".", "If", "the", "result", "represents", "a", "non", "-", "existent", "value", "then", "no", "values", "will", "be", "iterated", ".", "If", "the", "result", "is", "an", "Object", "the", "iterator", "will", "pass", "the", "key", "and", "value", "of", "each", "item", ".", "If", "the", "result", "is", "an", "Array", "the", "iterator", "will", "only", "pass", "the", "value", "of", "each", "item", ".", "If", "the", "result", "is", "not", "a", "JSON", "array", "or", "object", "the", "iterator", "will", "pass", "back", "one", "value", "equal", "to", "the", "result", "." ]
fb8e539484c9fb2df9f472bc0e3949a74c256f95
https://github.com/tidwall/gjson/blob/fb8e539484c9fb2df9f472bc0e3949a74c256f95/gjson.go#L218-L281
train
tidwall/gjson
gjson.go
Map
func (t Result) Map() map[string]Result { if t.Type != JSON { return map[string]Result{} } r := t.arrayOrMap('{', false) return r.o }
go
func (t Result) Map() map[string]Result { if t.Type != JSON { return map[string]Result{} } r := t.arrayOrMap('{', false) return r.o }
[ "func", "(", "t", "Result", ")", "Map", "(", ")", "map", "[", "string", "]", "Result", "{", "if", "t", ".", "Type", "!=", "JSON", "{", "return", "map", "[", "string", "]", "Result", "{", "}", "\n", "}", "\n", "r", ":=", "t", ".", "arrayOrMap", "(", "'{'", ",", "false", ")", "\n", "return", "r", ".", "o", "\n", "}" ]
// Map returns back an map of values. The result should be a JSON array.
[ "Map", "returns", "back", "an", "map", "of", "values", ".", "The", "result", "should", "be", "a", "JSON", "array", "." ]
fb8e539484c9fb2df9f472bc0e3949a74c256f95
https://github.com/tidwall/gjson/blob/fb8e539484c9fb2df9f472bc0e3949a74c256f95/gjson.go#L284-L290
train
tidwall/gjson
gjson.go
Get
func (t Result) Get(path string) Result { return Get(t.Raw, path) }
go
func (t Result) Get(path string) Result { return Get(t.Raw, path) }
[ "func", "(", "t", "Result", ")", "Get", "(", "path", "string", ")", "Result", "{", "return", "Get", "(", "t", ".", "Raw", ",", "path", ")", "\n", "}" ]
// Get searches result for the specified path. // The result should be a JSON array or object.
[ "Get", "searches", "result", "for", "the", "specified", "path", ".", "The", "result", "should", "be", "a", "JSON", "array", "or", "object", "." ]
fb8e539484c9fb2df9f472bc0e3949a74c256f95
https://github.com/tidwall/gjson/blob/fb8e539484c9fb2df9f472bc0e3949a74c256f95/gjson.go#L294-L296
train
tidwall/gjson
gjson.go
Parse
func Parse(json string) Result { var value Result for i := 0; i < len(json); i++ { if json[i] == '{' || json[i] == '[' { value.Type = JSON value.Raw = json[i:] // just take the entire raw break } if json[i] <= ' ' { continue } switch json[i] { default: if (json[i] >= '0' && json[i] <= '9') || json[i] == '-' { value.Type = Number value.Raw, value.Num = tonum(json[i:]) } else { return Result{} } case 'n': value.Type = Null value.Raw = tolit(json[i:]) case 't': value.Type = True value.Raw = tolit(json[i:]) case 'f': value.Type = False value.Raw = tolit(json[i:]) case '"': value.Type = String value.Raw, value.Str = tostr(json[i:]) } break } return value }
go
func Parse(json string) Result { var value Result for i := 0; i < len(json); i++ { if json[i] == '{' || json[i] == '[' { value.Type = JSON value.Raw = json[i:] // just take the entire raw break } if json[i] <= ' ' { continue } switch json[i] { default: if (json[i] >= '0' && json[i] <= '9') || json[i] == '-' { value.Type = Number value.Raw, value.Num = tonum(json[i:]) } else { return Result{} } case 'n': value.Type = Null value.Raw = tolit(json[i:]) case 't': value.Type = True value.Raw = tolit(json[i:]) case 'f': value.Type = False value.Raw = tolit(json[i:]) case '"': value.Type = String value.Raw, value.Str = tostr(json[i:]) } break } return value }
[ "func", "Parse", "(", "json", "string", ")", "Result", "{", "var", "value", "Result", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "json", ")", ";", "i", "++", "{", "if", "json", "[", "i", "]", "==", "'{'", "||", "json", "[", "i", "]", "==", "'['", "{", "value", ".", "Type", "=", "JSON", "\n", "value", ".", "Raw", "=", "json", "[", "i", ":", "]", "// just take the entire raw", "\n", "break", "\n", "}", "\n", "if", "json", "[", "i", "]", "<=", "' '", "{", "continue", "\n", "}", "\n", "switch", "json", "[", "i", "]", "{", "default", ":", "if", "(", "json", "[", "i", "]", ">=", "'0'", "&&", "json", "[", "i", "]", "<=", "'9'", ")", "||", "json", "[", "i", "]", "==", "'-'", "{", "value", ".", "Type", "=", "Number", "\n", "value", ".", "Raw", ",", "value", ".", "Num", "=", "tonum", "(", "json", "[", "i", ":", "]", ")", "\n", "}", "else", "{", "return", "Result", "{", "}", "\n", "}", "\n", "case", "'n'", ":", "value", ".", "Type", "=", "Null", "\n", "value", ".", "Raw", "=", "tolit", "(", "json", "[", "i", ":", "]", ")", "\n", "case", "'t'", ":", "value", ".", "Type", "=", "True", "\n", "value", ".", "Raw", "=", "tolit", "(", "json", "[", "i", ":", "]", ")", "\n", "case", "'f'", ":", "value", ".", "Type", "=", "False", "\n", "value", ".", "Raw", "=", "tolit", "(", "json", "[", "i", ":", "]", ")", "\n", "case", "'\"'", ":", "value", ".", "Type", "=", "String", "\n", "value", ".", "Raw", ",", "value", ".", "Str", "=", "tostr", "(", "json", "[", "i", ":", "]", ")", "\n", "}", "\n", "break", "\n", "}", "\n", "return", "value", "\n", "}" ]
// Parse parses the json and returns a result. // // This function expects that the json is well-formed, and does not validate. // Invalid json will not panic, but it may return back unexpected results. // If you are consuming JSON from an unpredictable source then you may want to // use the Valid function first.
[ "Parse", "parses", "the", "json", "and", "returns", "a", "result", ".", "This", "function", "expects", "that", "the", "json", "is", "well", "-", "formed", "and", "does", "not", "validate", ".", "Invalid", "json", "will", "not", "panic", "but", "it", "may", "return", "back", "unexpected", "results", ".", "If", "you", "are", "consuming", "JSON", "from", "an", "unpredictable", "source", "then", "you", "may", "want", "to", "use", "the", "Valid", "function", "first", "." ]
fb8e539484c9fb2df9f472bc0e3949a74c256f95
https://github.com/tidwall/gjson/blob/fb8e539484c9fb2df9f472bc0e3949a74c256f95/gjson.go#L421-L456
train
tidwall/gjson
gjson.go
runeit
func runeit(json string) rune { n, _ := strconv.ParseUint(json[:4], 16, 64) return rune(n) }
go
func runeit(json string) rune { n, _ := strconv.ParseUint(json[:4], 16, 64) return rune(n) }
[ "func", "runeit", "(", "json", "string", ")", "rune", "{", "n", ",", "_", ":=", "strconv", ".", "ParseUint", "(", "json", "[", ":", "4", "]", ",", "16", ",", "64", ")", "\n", "return", "rune", "(", "n", ")", "\n", "}" ]
// runeit returns the rune from the the \uXXXX
[ "runeit", "returns", "the", "rune", "from", "the", "the", "\\", "uXXXX" ]
fb8e539484c9fb2df9f472bc0e3949a74c256f95
https://github.com/tidwall/gjson/blob/fb8e539484c9fb2df9f472bc0e3949a74c256f95/gjson.go#L1478-L1481
train
tidwall/gjson
gjson.go
unescape
func unescape(json string) string { //, error) { var str = make([]byte, 0, len(json)) for i := 0; i < len(json); i++ { switch { default: str = append(str, json[i]) case json[i] < ' ': return string(str) case json[i] == '\\': i++ if i >= len(json) { return string(str) } switch json[i] { default: return string(str) case '\\': str = append(str, '\\') case '/': str = append(str, '/') case 'b': str = append(str, '\b') case 'f': str = append(str, '\f') case 'n': str = append(str, '\n') case 'r': str = append(str, '\r') case 't': str = append(str, '\t') case '"': str = append(str, '"') case 'u': if i+5 > len(json) { return string(str) } r := runeit(json[i+1:]) i += 5 if utf16.IsSurrogate(r) { // need another code if len(json[i:]) >= 6 && json[i] == '\\' && json[i+1] == 'u' { // we expect it to be correct so just consume it r = utf16.DecodeRune(r, runeit(json[i+2:])) i += 6 } } // provide enough space to encode the largest utf8 possible str = append(str, 0, 0, 0, 0, 0, 0, 0, 0) n := utf8.EncodeRune(str[len(str)-8:], r) str = str[:len(str)-8+n] i-- // backtrack index by one } } } return string(str) }
go
func unescape(json string) string { //, error) { var str = make([]byte, 0, len(json)) for i := 0; i < len(json); i++ { switch { default: str = append(str, json[i]) case json[i] < ' ': return string(str) case json[i] == '\\': i++ if i >= len(json) { return string(str) } switch json[i] { default: return string(str) case '\\': str = append(str, '\\') case '/': str = append(str, '/') case 'b': str = append(str, '\b') case 'f': str = append(str, '\f') case 'n': str = append(str, '\n') case 'r': str = append(str, '\r') case 't': str = append(str, '\t') case '"': str = append(str, '"') case 'u': if i+5 > len(json) { return string(str) } r := runeit(json[i+1:]) i += 5 if utf16.IsSurrogate(r) { // need another code if len(json[i:]) >= 6 && json[i] == '\\' && json[i+1] == 'u' { // we expect it to be correct so just consume it r = utf16.DecodeRune(r, runeit(json[i+2:])) i += 6 } } // provide enough space to encode the largest utf8 possible str = append(str, 0, 0, 0, 0, 0, 0, 0, 0) n := utf8.EncodeRune(str[len(str)-8:], r) str = str[:len(str)-8+n] i-- // backtrack index by one } } } return string(str) }
[ "func", "unescape", "(", "json", "string", ")", "string", "{", "//, error) {", "var", "str", "=", "make", "(", "[", "]", "byte", ",", "0", ",", "len", "(", "json", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "json", ")", ";", "i", "++", "{", "switch", "{", "default", ":", "str", "=", "append", "(", "str", ",", "json", "[", "i", "]", ")", "\n", "case", "json", "[", "i", "]", "<", "' '", ":", "return", "string", "(", "str", ")", "\n", "case", "json", "[", "i", "]", "==", "'\\\\'", ":", "i", "++", "\n", "if", "i", ">=", "len", "(", "json", ")", "{", "return", "string", "(", "str", ")", "\n", "}", "\n", "switch", "json", "[", "i", "]", "{", "default", ":", "return", "string", "(", "str", ")", "\n", "case", "'\\\\'", ":", "str", "=", "append", "(", "str", ",", "'\\\\'", ")", "\n", "case", "'/'", ":", "str", "=", "append", "(", "str", ",", "'/'", ")", "\n", "case", "'b'", ":", "str", "=", "append", "(", "str", ",", "'\\b'", ")", "\n", "case", "'f'", ":", "str", "=", "append", "(", "str", ",", "'\\f'", ")", "\n", "case", "'n'", ":", "str", "=", "append", "(", "str", ",", "'\\n'", ")", "\n", "case", "'r'", ":", "str", "=", "append", "(", "str", ",", "'\\r'", ")", "\n", "case", "'t'", ":", "str", "=", "append", "(", "str", ",", "'\\t'", ")", "\n", "case", "'\"'", ":", "str", "=", "append", "(", "str", ",", "'\"'", ")", "\n", "case", "'u'", ":", "if", "i", "+", "5", ">", "len", "(", "json", ")", "{", "return", "string", "(", "str", ")", "\n", "}", "\n", "r", ":=", "runeit", "(", "json", "[", "i", "+", "1", ":", "]", ")", "\n", "i", "+=", "5", "\n", "if", "utf16", ".", "IsSurrogate", "(", "r", ")", "{", "// need another code", "if", "len", "(", "json", "[", "i", ":", "]", ")", ">=", "6", "&&", "json", "[", "i", "]", "==", "'\\\\'", "&&", "json", "[", "i", "+", "1", "]", "==", "'u'", "{", "// we expect it to be correct so just consume it", "r", "=", "utf16", ".", "DecodeRune", "(", "r", ",", "runeit", "(", "json", "[", "i", "+", "2", ":", "]", ")", ")", "\n", "i", "+=", "6", "\n", "}", "\n", "}", "\n", "// provide enough space to encode the largest utf8 possible", "str", "=", "append", "(", "str", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ")", "\n", "n", ":=", "utf8", ".", "EncodeRune", "(", "str", "[", "len", "(", "str", ")", "-", "8", ":", "]", ",", "r", ")", "\n", "str", "=", "str", "[", ":", "len", "(", "str", ")", "-", "8", "+", "n", "]", "\n", "i", "--", "// backtrack index by one", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "string", "(", "str", ")", "\n", "}" ]
// unescape unescapes a string
[ "unescape", "unescapes", "a", "string" ]
fb8e539484c9fb2df9f472bc0e3949a74c256f95
https://github.com/tidwall/gjson/blob/fb8e539484c9fb2df9f472bc0e3949a74c256f95/gjson.go#L1484-L1539
train
tidwall/gjson
gjson.go
GetMany
func GetMany(json string, path ...string) []Result { res := make([]Result, len(path)) for i, path := range path { res[i] = Get(json, path) } return res }
go
func GetMany(json string, path ...string) []Result { res := make([]Result, len(path)) for i, path := range path { res[i] = Get(json, path) } return res }
[ "func", "GetMany", "(", "json", "string", ",", "path", "...", "string", ")", "[", "]", "Result", "{", "res", ":=", "make", "(", "[", "]", "Result", ",", "len", "(", "path", ")", ")", "\n", "for", "i", ",", "path", ":=", "range", "path", "{", "res", "[", "i", "]", "=", "Get", "(", "json", ",", "path", ")", "\n", "}", "\n", "return", "res", "\n", "}" ]
// GetMany searches json for the multiple paths. // The return value is a Result array where the number of items // will be equal to the number of input paths.
[ "GetMany", "searches", "json", "for", "the", "multiple", "paths", ".", "The", "return", "value", "is", "a", "Result", "array", "where", "the", "number", "of", "items", "will", "be", "equal", "to", "the", "number", "of", "input", "paths", "." ]
fb8e539484c9fb2df9f472bc0e3949a74c256f95
https://github.com/tidwall/gjson/blob/fb8e539484c9fb2df9f472bc0e3949a74c256f95/gjson.go#L1674-L1680
train
tidwall/gjson
gjson.go
GetManyBytes
func GetManyBytes(json []byte, path ...string) []Result { res := make([]Result, len(path)) for i, path := range path { res[i] = GetBytes(json, path) } return res }
go
func GetManyBytes(json []byte, path ...string) []Result { res := make([]Result, len(path)) for i, path := range path { res[i] = GetBytes(json, path) } return res }
[ "func", "GetManyBytes", "(", "json", "[", "]", "byte", ",", "path", "...", "string", ")", "[", "]", "Result", "{", "res", ":=", "make", "(", "[", "]", "Result", ",", "len", "(", "path", ")", ")", "\n", "for", "i", ",", "path", ":=", "range", "path", "{", "res", "[", "i", "]", "=", "GetBytes", "(", "json", ",", "path", ")", "\n", "}", "\n", "return", "res", "\n", "}" ]
// GetManyBytes searches json for the multiple paths. // The return value is a Result array where the number of items // will be equal to the number of input paths.
[ "GetManyBytes", "searches", "json", "for", "the", "multiple", "paths", ".", "The", "return", "value", "is", "a", "Result", "array", "where", "the", "number", "of", "items", "will", "be", "equal", "to", "the", "number", "of", "input", "paths", "." ]
fb8e539484c9fb2df9f472bc0e3949a74c256f95
https://github.com/tidwall/gjson/blob/fb8e539484c9fb2df9f472bc0e3949a74c256f95/gjson.go#L1685-L1691
train
tidwall/gjson
gjson.go
execModifier
func execModifier(json, path string) (pathOut, res string, ok bool) { name := path[1:] var hasArgs bool for i := 1; i < len(path); i++ { if path[i] == ':' { pathOut = path[i+1:] name = path[1:i] hasArgs = len(pathOut) > 0 break } if !DisableChaining { if path[i] == '|' { pathOut = path[i:] name = path[1:i] break } } } if fn, ok := modifiers[name]; ok { var args string if hasArgs { var parsedArgs bool switch pathOut[0] { case '{', '[', '"': res := Parse(pathOut) if res.Exists() { _, args = parseSquash(pathOut, 0) pathOut = pathOut[len(args):] parsedArgs = true } } if !parsedArgs { idx := -1 if !DisableChaining { idx = strings.IndexByte(pathOut, '|') } if idx == -1 { args = pathOut pathOut = "" } else { args = pathOut[:idx] pathOut = pathOut[idx:] } } } return pathOut, fn(json, args), true } return pathOut, res, false }
go
func execModifier(json, path string) (pathOut, res string, ok bool) { name := path[1:] var hasArgs bool for i := 1; i < len(path); i++ { if path[i] == ':' { pathOut = path[i+1:] name = path[1:i] hasArgs = len(pathOut) > 0 break } if !DisableChaining { if path[i] == '|' { pathOut = path[i:] name = path[1:i] break } } } if fn, ok := modifiers[name]; ok { var args string if hasArgs { var parsedArgs bool switch pathOut[0] { case '{', '[', '"': res := Parse(pathOut) if res.Exists() { _, args = parseSquash(pathOut, 0) pathOut = pathOut[len(args):] parsedArgs = true } } if !parsedArgs { idx := -1 if !DisableChaining { idx = strings.IndexByte(pathOut, '|') } if idx == -1 { args = pathOut pathOut = "" } else { args = pathOut[:idx] pathOut = pathOut[idx:] } } } return pathOut, fn(json, args), true } return pathOut, res, false }
[ "func", "execModifier", "(", "json", ",", "path", "string", ")", "(", "pathOut", ",", "res", "string", ",", "ok", "bool", ")", "{", "name", ":=", "path", "[", "1", ":", "]", "\n", "var", "hasArgs", "bool", "\n", "for", "i", ":=", "1", ";", "i", "<", "len", "(", "path", ")", ";", "i", "++", "{", "if", "path", "[", "i", "]", "==", "':'", "{", "pathOut", "=", "path", "[", "i", "+", "1", ":", "]", "\n", "name", "=", "path", "[", "1", ":", "i", "]", "\n", "hasArgs", "=", "len", "(", "pathOut", ")", ">", "0", "\n", "break", "\n", "}", "\n", "if", "!", "DisableChaining", "{", "if", "path", "[", "i", "]", "==", "'|'", "{", "pathOut", "=", "path", "[", "i", ":", "]", "\n", "name", "=", "path", "[", "1", ":", "i", "]", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "fn", ",", "ok", ":=", "modifiers", "[", "name", "]", ";", "ok", "{", "var", "args", "string", "\n", "if", "hasArgs", "{", "var", "parsedArgs", "bool", "\n", "switch", "pathOut", "[", "0", "]", "{", "case", "'{'", ",", "'['", ",", "'\"'", ":", "res", ":=", "Parse", "(", "pathOut", ")", "\n", "if", "res", ".", "Exists", "(", ")", "{", "_", ",", "args", "=", "parseSquash", "(", "pathOut", ",", "0", ")", "\n", "pathOut", "=", "pathOut", "[", "len", "(", "args", ")", ":", "]", "\n", "parsedArgs", "=", "true", "\n", "}", "\n", "}", "\n", "if", "!", "parsedArgs", "{", "idx", ":=", "-", "1", "\n", "if", "!", "DisableChaining", "{", "idx", "=", "strings", ".", "IndexByte", "(", "pathOut", ",", "'|'", ")", "\n", "}", "\n", "if", "idx", "==", "-", "1", "{", "args", "=", "pathOut", "\n", "pathOut", "=", "\"", "\"", "\n", "}", "else", "{", "args", "=", "pathOut", "[", ":", "idx", "]", "\n", "pathOut", "=", "pathOut", "[", "idx", ":", "]", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "pathOut", ",", "fn", "(", "json", ",", "args", ")", ",", "true", "\n", "}", "\n", "return", "pathOut", ",", "res", ",", "false", "\n", "}" ]
// execModifier parses the path to find a matching modifier function. // then input expects that the path already starts with a '@'
[ "execModifier", "parses", "the", "path", "to", "find", "a", "matching", "modifier", "function", ".", "then", "input", "expects", "that", "the", "path", "already", "starts", "with", "a" ]
fb8e539484c9fb2df9f472bc0e3949a74c256f95
https://github.com/tidwall/gjson/blob/fb8e539484c9fb2df9f472bc0e3949a74c256f95/gjson.go#L2175-L2223
train
tidwall/gjson
gjson.go
AddModifier
func AddModifier(name string, fn func(json, arg string) string) { modifiers[name] = fn }
go
func AddModifier(name string, fn func(json, arg string) string) { modifiers[name] = fn }
[ "func", "AddModifier", "(", "name", "string", ",", "fn", "func", "(", "json", ",", "arg", "string", ")", "string", ")", "{", "modifiers", "[", "name", "]", "=", "fn", "\n", "}" ]
// AddModifier binds a custom modifier command to the GJSON syntax. // This operation is not thread safe and should be executed prior to // using all other gjson function.
[ "AddModifier", "binds", "a", "custom", "modifier", "command", "to", "the", "GJSON", "syntax", ".", "This", "operation", "is", "not", "thread", "safe", "and", "should", "be", "executed", "prior", "to", "using", "all", "other", "gjson", "function", "." ]
fb8e539484c9fb2df9f472bc0e3949a74c256f95
https://github.com/tidwall/gjson/blob/fb8e539484c9fb2df9f472bc0e3949a74c256f95/gjson.go#L2237-L2239
train
tidwall/gjson
gjson.go
ModifierExists
func ModifierExists(name string, fn func(json, arg string) string) bool { _, ok := modifiers[name] return ok }
go
func ModifierExists(name string, fn func(json, arg string) string) bool { _, ok := modifiers[name] return ok }
[ "func", "ModifierExists", "(", "name", "string", ",", "fn", "func", "(", "json", ",", "arg", "string", ")", "string", ")", "bool", "{", "_", ",", "ok", ":=", "modifiers", "[", "name", "]", "\n", "return", "ok", "\n", "}" ]
// ModifierExists returns true when the specified modifier exists.
[ "ModifierExists", "returns", "true", "when", "the", "specified", "modifier", "exists", "." ]
fb8e539484c9fb2df9f472bc0e3949a74c256f95
https://github.com/tidwall/gjson/blob/fb8e539484c9fb2df9f472bc0e3949a74c256f95/gjson.go#L2242-L2245
train
hashicorp/hcl
json/scanner/scanner.go
New
func New(src []byte) *Scanner { // even though we accept a src, we read from a io.Reader compatible type // (*bytes.Buffer). So in the future we might easily change it to streaming // read. b := bytes.NewBuffer(src) s := &Scanner{ buf: b, src: src, } // srcPosition always starts with 1 s.srcPos.Line = 1 return s }
go
func New(src []byte) *Scanner { // even though we accept a src, we read from a io.Reader compatible type // (*bytes.Buffer). So in the future we might easily change it to streaming // read. b := bytes.NewBuffer(src) s := &Scanner{ buf: b, src: src, } // srcPosition always starts with 1 s.srcPos.Line = 1 return s }
[ "func", "New", "(", "src", "[", "]", "byte", ")", "*", "Scanner", "{", "// even though we accept a src, we read from a io.Reader compatible type", "// (*bytes.Buffer). So in the future we might easily change it to streaming", "// read.", "b", ":=", "bytes", ".", "NewBuffer", "(", "src", ")", "\n", "s", ":=", "&", "Scanner", "{", "buf", ":", "b", ",", "src", ":", "src", ",", "}", "\n\n", "// srcPosition always starts with 1", "s", ".", "srcPos", ".", "Line", "=", "1", "\n", "return", "s", "\n", "}" ]
// New creates and initializes a new instance of Scanner using src as // its source content.
[ "New", "creates", "and", "initializes", "a", "new", "instance", "of", "Scanner", "using", "src", "as", "its", "source", "content", "." ]
99e2f22d1c94b272184d97dd9d252866409100ab
https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/json/scanner/scanner.go#L47-L60
train
hashicorp/hcl
json/scanner/scanner.go
unread
func (s *Scanner) unread() { if err := s.buf.UnreadRune(); err != nil { panic(err) // this is user fault, we should catch it } s.srcPos = s.prevPos // put back last position }
go
func (s *Scanner) unread() { if err := s.buf.UnreadRune(); err != nil { panic(err) // this is user fault, we should catch it } s.srcPos = s.prevPos // put back last position }
[ "func", "(", "s", "*", "Scanner", ")", "unread", "(", ")", "{", "if", "err", ":=", "s", ".", "buf", ".", "UnreadRune", "(", ")", ";", "err", "!=", "nil", "{", "panic", "(", "err", ")", "// this is user fault, we should catch it", "\n", "}", "\n", "s", ".", "srcPos", "=", "s", ".", "prevPos", "// put back last position", "\n", "}" ]
// unread unreads the previous read Rune and updates the source position
[ "unread", "unreads", "the", "previous", "read", "Rune", "and", "updates", "the", "source", "position" ]
99e2f22d1c94b272184d97dd9d252866409100ab
https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/json/scanner/scanner.go#L101-L106
train
hashicorp/hcl
json/scanner/scanner.go
peek
func (s *Scanner) peek() rune { peek, _, err := s.buf.ReadRune() if err != nil { return eof } s.buf.UnreadRune() return peek }
go
func (s *Scanner) peek() rune { peek, _, err := s.buf.ReadRune() if err != nil { return eof } s.buf.UnreadRune() return peek }
[ "func", "(", "s", "*", "Scanner", ")", "peek", "(", ")", "rune", "{", "peek", ",", "_", ",", "err", ":=", "s", ".", "buf", ".", "ReadRune", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "eof", "\n", "}", "\n\n", "s", ".", "buf", ".", "UnreadRune", "(", ")", "\n", "return", "peek", "\n", "}" ]
// peek returns the next rune without advancing the reader.
[ "peek", "returns", "the", "next", "rune", "without", "advancing", "the", "reader", "." ]
99e2f22d1c94b272184d97dd9d252866409100ab
https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/json/scanner/scanner.go#L109-L117
train
hashicorp/hcl
json/scanner/scanner.go
Scan
func (s *Scanner) Scan() token.Token { ch := s.next() // skip white space for isWhitespace(ch) { ch = s.next() } var tok token.Type // token text markings s.tokStart = s.srcPos.Offset - s.lastCharLen // token position, initial next() is moving the offset by one(size of rune // actually), though we are interested with the starting point s.tokPos.Offset = s.srcPos.Offset - s.lastCharLen if s.srcPos.Column > 0 { // common case: last character was not a '\n' s.tokPos.Line = s.srcPos.Line s.tokPos.Column = s.srcPos.Column } else { // last character was a '\n' // (we cannot be at the beginning of the source // since we have called next() at least once) s.tokPos.Line = s.srcPos.Line - 1 s.tokPos.Column = s.lastLineLen } switch { case isLetter(ch): lit := s.scanIdentifier() if lit == "true" || lit == "false" { tok = token.BOOL } else if lit == "null" { tok = token.NULL } else { s.err("illegal char") } case isDecimal(ch): tok = s.scanNumber(ch) default: switch ch { case eof: tok = token.EOF case '"': tok = token.STRING s.scanString() case '.': tok = token.PERIOD ch = s.peek() if isDecimal(ch) { tok = token.FLOAT ch = s.scanMantissa(ch) ch = s.scanExponent(ch) } case '[': tok = token.LBRACK case ']': tok = token.RBRACK case '{': tok = token.LBRACE case '}': tok = token.RBRACE case ',': tok = token.COMMA case ':': tok = token.COLON case '-': if isDecimal(s.peek()) { ch := s.next() tok = s.scanNumber(ch) } else { s.err("illegal char") } default: s.err("illegal char: " + string(ch)) } } // finish token ending s.tokEnd = s.srcPos.Offset // create token literal var tokenText string if s.tokStart >= 0 { tokenText = string(s.src[s.tokStart:s.tokEnd]) } s.tokStart = s.tokEnd // ensure idempotency of tokenText() call return token.Token{ Type: tok, Pos: s.tokPos, Text: tokenText, } }
go
func (s *Scanner) Scan() token.Token { ch := s.next() // skip white space for isWhitespace(ch) { ch = s.next() } var tok token.Type // token text markings s.tokStart = s.srcPos.Offset - s.lastCharLen // token position, initial next() is moving the offset by one(size of rune // actually), though we are interested with the starting point s.tokPos.Offset = s.srcPos.Offset - s.lastCharLen if s.srcPos.Column > 0 { // common case: last character was not a '\n' s.tokPos.Line = s.srcPos.Line s.tokPos.Column = s.srcPos.Column } else { // last character was a '\n' // (we cannot be at the beginning of the source // since we have called next() at least once) s.tokPos.Line = s.srcPos.Line - 1 s.tokPos.Column = s.lastLineLen } switch { case isLetter(ch): lit := s.scanIdentifier() if lit == "true" || lit == "false" { tok = token.BOOL } else if lit == "null" { tok = token.NULL } else { s.err("illegal char") } case isDecimal(ch): tok = s.scanNumber(ch) default: switch ch { case eof: tok = token.EOF case '"': tok = token.STRING s.scanString() case '.': tok = token.PERIOD ch = s.peek() if isDecimal(ch) { tok = token.FLOAT ch = s.scanMantissa(ch) ch = s.scanExponent(ch) } case '[': tok = token.LBRACK case ']': tok = token.RBRACK case '{': tok = token.LBRACE case '}': tok = token.RBRACE case ',': tok = token.COMMA case ':': tok = token.COLON case '-': if isDecimal(s.peek()) { ch := s.next() tok = s.scanNumber(ch) } else { s.err("illegal char") } default: s.err("illegal char: " + string(ch)) } } // finish token ending s.tokEnd = s.srcPos.Offset // create token literal var tokenText string if s.tokStart >= 0 { tokenText = string(s.src[s.tokStart:s.tokEnd]) } s.tokStart = s.tokEnd // ensure idempotency of tokenText() call return token.Token{ Type: tok, Pos: s.tokPos, Text: tokenText, } }
[ "func", "(", "s", "*", "Scanner", ")", "Scan", "(", ")", "token", ".", "Token", "{", "ch", ":=", "s", ".", "next", "(", ")", "\n\n", "// skip white space", "for", "isWhitespace", "(", "ch", ")", "{", "ch", "=", "s", ".", "next", "(", ")", "\n", "}", "\n\n", "var", "tok", "token", ".", "Type", "\n\n", "// token text markings", "s", ".", "tokStart", "=", "s", ".", "srcPos", ".", "Offset", "-", "s", ".", "lastCharLen", "\n\n", "// token position, initial next() is moving the offset by one(size of rune", "// actually), though we are interested with the starting point", "s", ".", "tokPos", ".", "Offset", "=", "s", ".", "srcPos", ".", "Offset", "-", "s", ".", "lastCharLen", "\n", "if", "s", ".", "srcPos", ".", "Column", ">", "0", "{", "// common case: last character was not a '\\n'", "s", ".", "tokPos", ".", "Line", "=", "s", ".", "srcPos", ".", "Line", "\n", "s", ".", "tokPos", ".", "Column", "=", "s", ".", "srcPos", ".", "Column", "\n", "}", "else", "{", "// last character was a '\\n'", "// (we cannot be at the beginning of the source", "// since we have called next() at least once)", "s", ".", "tokPos", ".", "Line", "=", "s", ".", "srcPos", ".", "Line", "-", "1", "\n", "s", ".", "tokPos", ".", "Column", "=", "s", ".", "lastLineLen", "\n", "}", "\n\n", "switch", "{", "case", "isLetter", "(", "ch", ")", ":", "lit", ":=", "s", ".", "scanIdentifier", "(", ")", "\n", "if", "lit", "==", "\"", "\"", "||", "lit", "==", "\"", "\"", "{", "tok", "=", "token", ".", "BOOL", "\n", "}", "else", "if", "lit", "==", "\"", "\"", "{", "tok", "=", "token", ".", "NULL", "\n", "}", "else", "{", "s", ".", "err", "(", "\"", "\"", ")", "\n", "}", "\n", "case", "isDecimal", "(", "ch", ")", ":", "tok", "=", "s", ".", "scanNumber", "(", "ch", ")", "\n", "default", ":", "switch", "ch", "{", "case", "eof", ":", "tok", "=", "token", ".", "EOF", "\n", "case", "'\"'", ":", "tok", "=", "token", ".", "STRING", "\n", "s", ".", "scanString", "(", ")", "\n", "case", "'.'", ":", "tok", "=", "token", ".", "PERIOD", "\n", "ch", "=", "s", ".", "peek", "(", ")", "\n", "if", "isDecimal", "(", "ch", ")", "{", "tok", "=", "token", ".", "FLOAT", "\n", "ch", "=", "s", ".", "scanMantissa", "(", "ch", ")", "\n", "ch", "=", "s", ".", "scanExponent", "(", "ch", ")", "\n", "}", "\n", "case", "'['", ":", "tok", "=", "token", ".", "LBRACK", "\n", "case", "']'", ":", "tok", "=", "token", ".", "RBRACK", "\n", "case", "'{'", ":", "tok", "=", "token", ".", "LBRACE", "\n", "case", "'}'", ":", "tok", "=", "token", ".", "RBRACE", "\n", "case", "','", ":", "tok", "=", "token", ".", "COMMA", "\n", "case", "':'", ":", "tok", "=", "token", ".", "COLON", "\n", "case", "'-'", ":", "if", "isDecimal", "(", "s", ".", "peek", "(", ")", ")", "{", "ch", ":=", "s", ".", "next", "(", ")", "\n", "tok", "=", "s", ".", "scanNumber", "(", "ch", ")", "\n", "}", "else", "{", "s", ".", "err", "(", "\"", "\"", ")", "\n", "}", "\n", "default", ":", "s", ".", "err", "(", "\"", "\"", "+", "string", "(", "ch", ")", ")", "\n", "}", "\n", "}", "\n\n", "// finish token ending", "s", ".", "tokEnd", "=", "s", ".", "srcPos", ".", "Offset", "\n\n", "// create token literal", "var", "tokenText", "string", "\n", "if", "s", ".", "tokStart", ">=", "0", "{", "tokenText", "=", "string", "(", "s", ".", "src", "[", "s", ".", "tokStart", ":", "s", ".", "tokEnd", "]", ")", "\n", "}", "\n", "s", ".", "tokStart", "=", "s", ".", "tokEnd", "// ensure idempotency of tokenText() call", "\n\n", "return", "token", ".", "Token", "{", "Type", ":", "tok", ",", "Pos", ":", "s", ".", "tokPos", ",", "Text", ":", "tokenText", ",", "}", "\n", "}" ]
// Scan scans the next token and returns the token.
[ "Scan", "scans", "the", "next", "token", "and", "returns", "the", "token", "." ]
99e2f22d1c94b272184d97dd9d252866409100ab
https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/json/scanner/scanner.go#L120-L214
train
hashicorp/hcl
json/scanner/scanner.go
scanMantissa
func (s *Scanner) scanMantissa(ch rune) rune { scanned := false for isDecimal(ch) { ch = s.next() scanned = true } if scanned && ch != eof { s.unread() } return ch }
go
func (s *Scanner) scanMantissa(ch rune) rune { scanned := false for isDecimal(ch) { ch = s.next() scanned = true } if scanned && ch != eof { s.unread() } return ch }
[ "func", "(", "s", "*", "Scanner", ")", "scanMantissa", "(", "ch", "rune", ")", "rune", "{", "scanned", ":=", "false", "\n", "for", "isDecimal", "(", "ch", ")", "{", "ch", "=", "s", ".", "next", "(", ")", "\n", "scanned", "=", "true", "\n", "}", "\n\n", "if", "scanned", "&&", "ch", "!=", "eof", "{", "s", ".", "unread", "(", ")", "\n", "}", "\n", "return", "ch", "\n", "}" ]
// scanMantissa scans the mantissa beginning from the rune. It returns the next // non decimal rune. It's used to determine wheter it's a fraction or exponent.
[ "scanMantissa", "scans", "the", "mantissa", "beginning", "from", "the", "rune", ".", "It", "returns", "the", "next", "non", "decimal", "rune", ".", "It", "s", "used", "to", "determine", "wheter", "it", "s", "a", "fraction", "or", "exponent", "." ]
99e2f22d1c94b272184d97dd9d252866409100ab
https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/json/scanner/scanner.go#L251-L262
train
hashicorp/hcl
json/scanner/scanner.go
scanFraction
func (s *Scanner) scanFraction(ch rune) rune { if ch == '.' { ch = s.peek() // we peek just to see if we can move forward ch = s.scanMantissa(ch) } return ch }
go
func (s *Scanner) scanFraction(ch rune) rune { if ch == '.' { ch = s.peek() // we peek just to see if we can move forward ch = s.scanMantissa(ch) } return ch }
[ "func", "(", "s", "*", "Scanner", ")", "scanFraction", "(", "ch", "rune", ")", "rune", "{", "if", "ch", "==", "'.'", "{", "ch", "=", "s", ".", "peek", "(", ")", "// we peek just to see if we can move forward", "\n", "ch", "=", "s", ".", "scanMantissa", "(", "ch", ")", "\n", "}", "\n", "return", "ch", "\n", "}" ]
// scanFraction scans the fraction after the '.' rune
[ "scanFraction", "scans", "the", "fraction", "after", "the", ".", "rune" ]
99e2f22d1c94b272184d97dd9d252866409100ab
https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/json/scanner/scanner.go#L265-L271
train
hashicorp/hcl
json/scanner/scanner.go
scanExponent
func (s *Scanner) scanExponent(ch rune) rune { if ch == 'e' || ch == 'E' { ch = s.next() if ch == '-' || ch == '+' { ch = s.next() } ch = s.scanMantissa(ch) } return ch }
go
func (s *Scanner) scanExponent(ch rune) rune { if ch == 'e' || ch == 'E' { ch = s.next() if ch == '-' || ch == '+' { ch = s.next() } ch = s.scanMantissa(ch) } return ch }
[ "func", "(", "s", "*", "Scanner", ")", "scanExponent", "(", "ch", "rune", ")", "rune", "{", "if", "ch", "==", "'e'", "||", "ch", "==", "'E'", "{", "ch", "=", "s", ".", "next", "(", ")", "\n", "if", "ch", "==", "'-'", "||", "ch", "==", "'+'", "{", "ch", "=", "s", ".", "next", "(", ")", "\n", "}", "\n", "ch", "=", "s", ".", "scanMantissa", "(", "ch", ")", "\n", "}", "\n", "return", "ch", "\n", "}" ]
// scanExponent scans the remaining parts of an exponent after the 'e' or 'E' // rune.
[ "scanExponent", "scans", "the", "remaining", "parts", "of", "an", "exponent", "after", "the", "e", "or", "E", "rune", "." ]
99e2f22d1c94b272184d97dd9d252866409100ab
https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/json/scanner/scanner.go#L275-L284
train
hashicorp/hcl
json/scanner/scanner.go
scanEscape
func (s *Scanner) scanEscape() rune { // http://en.cppreference.com/w/cpp/language/escape ch := s.next() // read character after '/' switch ch { case 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', '"': // nothing to do case '0', '1', '2', '3', '4', '5', '6', '7': // octal notation ch = s.scanDigits(ch, 8, 3) case 'x': // hexademical notation ch = s.scanDigits(s.next(), 16, 2) case 'u': // universal character name ch = s.scanDigits(s.next(), 16, 4) case 'U': // universal character name ch = s.scanDigits(s.next(), 16, 8) default: s.err("illegal char escape") } return ch }
go
func (s *Scanner) scanEscape() rune { // http://en.cppreference.com/w/cpp/language/escape ch := s.next() // read character after '/' switch ch { case 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', '"': // nothing to do case '0', '1', '2', '3', '4', '5', '6', '7': // octal notation ch = s.scanDigits(ch, 8, 3) case 'x': // hexademical notation ch = s.scanDigits(s.next(), 16, 2) case 'u': // universal character name ch = s.scanDigits(s.next(), 16, 4) case 'U': // universal character name ch = s.scanDigits(s.next(), 16, 8) default: s.err("illegal char escape") } return ch }
[ "func", "(", "s", "*", "Scanner", ")", "scanEscape", "(", ")", "rune", "{", "// http://en.cppreference.com/w/cpp/language/escape", "ch", ":=", "s", ".", "next", "(", ")", "// read character after '/'", "\n", "switch", "ch", "{", "case", "'a'", ",", "'b'", ",", "'f'", ",", "'n'", ",", "'r'", ",", "'t'", ",", "'v'", ",", "'\\\\'", ",", "'\"'", ":", "// nothing to do", "case", "'0'", ",", "'1'", ",", "'2'", ",", "'3'", ",", "'4'", ",", "'5'", ",", "'6'", ",", "'7'", ":", "// octal notation", "ch", "=", "s", ".", "scanDigits", "(", "ch", ",", "8", ",", "3", ")", "\n", "case", "'x'", ":", "// hexademical notation", "ch", "=", "s", ".", "scanDigits", "(", "s", ".", "next", "(", ")", ",", "16", ",", "2", ")", "\n", "case", "'u'", ":", "// universal character name", "ch", "=", "s", ".", "scanDigits", "(", "s", ".", "next", "(", ")", ",", "16", ",", "4", ")", "\n", "case", "'U'", ":", "// universal character name", "ch", "=", "s", ".", "scanDigits", "(", "s", ".", "next", "(", ")", ",", "16", ",", "8", ")", "\n", "default", ":", "s", ".", "err", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "ch", "\n", "}" ]
// scanEscape scans an escape sequence
[ "scanEscape", "scans", "an", "escape", "sequence" ]
99e2f22d1c94b272184d97dd9d252866409100ab
https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/json/scanner/scanner.go#L323-L345
train
hashicorp/hcl
json/scanner/scanner.go
scanIdentifier
func (s *Scanner) scanIdentifier() string { offs := s.srcPos.Offset - s.lastCharLen ch := s.next() for isLetter(ch) || isDigit(ch) || ch == '-' { ch = s.next() } if ch != eof { s.unread() // we got identifier, put back latest char } return string(s.src[offs:s.srcPos.Offset]) }
go
func (s *Scanner) scanIdentifier() string { offs := s.srcPos.Offset - s.lastCharLen ch := s.next() for isLetter(ch) || isDigit(ch) || ch == '-' { ch = s.next() } if ch != eof { s.unread() // we got identifier, put back latest char } return string(s.src[offs:s.srcPos.Offset]) }
[ "func", "(", "s", "*", "Scanner", ")", "scanIdentifier", "(", ")", "string", "{", "offs", ":=", "s", ".", "srcPos", ".", "Offset", "-", "s", ".", "lastCharLen", "\n", "ch", ":=", "s", ".", "next", "(", ")", "\n", "for", "isLetter", "(", "ch", ")", "||", "isDigit", "(", "ch", ")", "||", "ch", "==", "'-'", "{", "ch", "=", "s", ".", "next", "(", ")", "\n", "}", "\n\n", "if", "ch", "!=", "eof", "{", "s", ".", "unread", "(", ")", "// we got identifier, put back latest char", "\n", "}", "\n\n", "return", "string", "(", "s", ".", "src", "[", "offs", ":", "s", ".", "srcPos", ".", "Offset", "]", ")", "\n", "}" ]
// scanIdentifier scans an identifier and returns the literal string
[ "scanIdentifier", "scans", "an", "identifier", "and", "returns", "the", "literal", "string" ]
99e2f22d1c94b272184d97dd9d252866409100ab
https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/json/scanner/scanner.go#L364-L376
train
hashicorp/hcl
json/scanner/scanner.go
recentPosition
func (s *Scanner) recentPosition() (pos token.Pos) { pos.Offset = s.srcPos.Offset - s.lastCharLen switch { case s.srcPos.Column > 0: // common case: last character was not a '\n' pos.Line = s.srcPos.Line pos.Column = s.srcPos.Column case s.lastLineLen > 0: // last character was a '\n' // (we cannot be at the beginning of the source // since we have called next() at least once) pos.Line = s.srcPos.Line - 1 pos.Column = s.lastLineLen default: // at the beginning of the source pos.Line = 1 pos.Column = 1 } return }
go
func (s *Scanner) recentPosition() (pos token.Pos) { pos.Offset = s.srcPos.Offset - s.lastCharLen switch { case s.srcPos.Column > 0: // common case: last character was not a '\n' pos.Line = s.srcPos.Line pos.Column = s.srcPos.Column case s.lastLineLen > 0: // last character was a '\n' // (we cannot be at the beginning of the source // since we have called next() at least once) pos.Line = s.srcPos.Line - 1 pos.Column = s.lastLineLen default: // at the beginning of the source pos.Line = 1 pos.Column = 1 } return }
[ "func", "(", "s", "*", "Scanner", ")", "recentPosition", "(", ")", "(", "pos", "token", ".", "Pos", ")", "{", "pos", ".", "Offset", "=", "s", ".", "srcPos", ".", "Offset", "-", "s", ".", "lastCharLen", "\n", "switch", "{", "case", "s", ".", "srcPos", ".", "Column", ">", "0", ":", "// common case: last character was not a '\\n'", "pos", ".", "Line", "=", "s", ".", "srcPos", ".", "Line", "\n", "pos", ".", "Column", "=", "s", ".", "srcPos", ".", "Column", "\n", "case", "s", ".", "lastLineLen", ">", "0", ":", "// last character was a '\\n'", "// (we cannot be at the beginning of the source", "// since we have called next() at least once)", "pos", ".", "Line", "=", "s", ".", "srcPos", ".", "Line", "-", "1", "\n", "pos", ".", "Column", "=", "s", ".", "lastLineLen", "\n", "default", ":", "// at the beginning of the source", "pos", ".", "Line", "=", "1", "\n", "pos", ".", "Column", "=", "1", "\n", "}", "\n", "return", "\n", "}" ]
// recentPosition returns the position of the character immediately after the // character or token returned by the last call to Scan.
[ "recentPosition", "returns", "the", "position", "of", "the", "character", "immediately", "after", "the", "character", "or", "token", "returned", "by", "the", "last", "call", "to", "Scan", "." ]
99e2f22d1c94b272184d97dd9d252866409100ab
https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/json/scanner/scanner.go#L380-L399
train