id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
12,800
cloudfoundry/gosigar
sigar_darwin.go
kern_procargs
func kern_procargs(pid int, exe func(string), argv func(string), env func(string, string)) error { mib := []C.int{C.CTL_KERN, C.KERN_PROCARGS2, C.int(pid)} argmax := uintptr(C.ARG_MAX) buf := make([]byte, argmax) err := sysctl(mib, &buf[0], &argmax, nil, 0) if err != nil { return nil } bbuf := bytes.NewBuffer(buf) bbuf.Truncate(int(argmax)) var argc int32 binary.Read(bbuf, binary.LittleEndian, &argc) path, err := bbuf.ReadBytes(0) if exe != nil { exe(string(chop(path))) } // skip trailing \0's for { c, _ := bbuf.ReadByte() if c != 0 { bbuf.UnreadByte() break // start of argv[0] } } for i := 0; i < int(argc); i++ { arg, err := bbuf.ReadBytes(0) if err == io.EOF { break } if argv != nil { argv(string(chop(arg))) } } if env == nil { return nil } delim := []byte{61} // "=" for { line, err := bbuf.ReadBytes(0) if err == io.EOF || line[0] == 0 { break } pair := bytes.SplitN(chop(line), delim, 2) env(string(pair[0]), string(pair[1])) } return nil }
go
func kern_procargs(pid int, exe func(string), argv func(string), env func(string, string)) error { mib := []C.int{C.CTL_KERN, C.KERN_PROCARGS2, C.int(pid)} argmax := uintptr(C.ARG_MAX) buf := make([]byte, argmax) err := sysctl(mib, &buf[0], &argmax, nil, 0) if err != nil { return nil } bbuf := bytes.NewBuffer(buf) bbuf.Truncate(int(argmax)) var argc int32 binary.Read(bbuf, binary.LittleEndian, &argc) path, err := bbuf.ReadBytes(0) if exe != nil { exe(string(chop(path))) } // skip trailing \0's for { c, _ := bbuf.ReadByte() if c != 0 { bbuf.UnreadByte() break // start of argv[0] } } for i := 0; i < int(argc); i++ { arg, err := bbuf.ReadBytes(0) if err == io.EOF { break } if argv != nil { argv(string(chop(arg))) } } if env == nil { return nil } delim := []byte{61} // "=" for { line, err := bbuf.ReadBytes(0) if err == io.EOF || line[0] == 0 { break } pair := bytes.SplitN(chop(line), delim, 2) env(string(pair[0]), string(pair[1])) } return nil }
[ "func", "kern_procargs", "(", "pid", "int", ",", "exe", "func", "(", "string", ")", ",", "argv", "func", "(", "string", ")", ",", "env", "func", "(", "string", ",", "string", ")", ")", "error", "{", "mib", ":=", "[", "]", "C", ".", "int", "{", "C", ".", "CTL_KERN", ",", "C", ".", "KERN_PROCARGS2", ",", "C", ".", "int", "(", "pid", ")", "}", "\n", "argmax", ":=", "uintptr", "(", "C", ".", "ARG_MAX", ")", "\n", "buf", ":=", "make", "(", "[", "]", "byte", ",", "argmax", ")", "\n", "err", ":=", "sysctl", "(", "mib", ",", "&", "buf", "[", "0", "]", ",", "&", "argmax", ",", "nil", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n\n", "bbuf", ":=", "bytes", ".", "NewBuffer", "(", "buf", ")", "\n", "bbuf", ".", "Truncate", "(", "int", "(", "argmax", ")", ")", "\n\n", "var", "argc", "int32", "\n", "binary", ".", "Read", "(", "bbuf", ",", "binary", ".", "LittleEndian", ",", "&", "argc", ")", "\n\n", "path", ",", "err", ":=", "bbuf", ".", "ReadBytes", "(", "0", ")", "\n", "if", "exe", "!=", "nil", "{", "exe", "(", "string", "(", "chop", "(", "path", ")", ")", ")", "\n", "}", "\n\n", "// skip trailing \\0's", "for", "{", "c", ",", "_", ":=", "bbuf", ".", "ReadByte", "(", ")", "\n", "if", "c", "!=", "0", "{", "bbuf", ".", "UnreadByte", "(", ")", "\n", "break", "// start of argv[0]", "\n", "}", "\n", "}", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "int", "(", "argc", ")", ";", "i", "++", "{", "arg", ",", "err", ":=", "bbuf", ".", "ReadBytes", "(", "0", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "break", "\n", "}", "\n", "if", "argv", "!=", "nil", "{", "argv", "(", "string", "(", "chop", "(", "arg", ")", ")", ")", "\n", "}", "\n", "}", "\n\n", "if", "env", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "delim", ":=", "[", "]", "byte", "{", "61", "}", "// \"=\"", "\n\n", "for", "{", "line", ",", "err", ":=", "bbuf", ".", "ReadBytes", "(", "0", ")", "\n", "if", "err", "==", "io", ".", "EOF", "||", "line", "[", "0", "]", "==", "0", "{", "break", "\n", "}", "\n", "pair", ":=", "bytes", ".", "SplitN", "(", "chop", "(", "line", ")", ",", "delim", ",", "2", ")", "\n", "env", "(", "string", "(", "pair", "[", "0", "]", ")", ",", "string", "(", "pair", "[", "1", "]", ")", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// wrapper around sysctl KERN_PROCARGS2 // callbacks params are optional, // up to the caller as to which pieces of data they want
[ "wrapper", "around", "sysctl", "KERN_PROCARGS2", "callbacks", "params", "are", "optional", "up", "to", "the", "caller", "as", "to", "which", "pieces", "of", "data", "they", "want" ]
50ddd08d81d770b1e0ce2c969a46e46c73580e2a
https://github.com/cloudfoundry/gosigar/blob/50ddd08d81d770b1e0ce2c969a46e46c73580e2a/sigar_darwin.go#L320-L379
12,801
cloudfoundry/gosigar
sigar_darwin.go
sysctl
func sysctl(mib []C.int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var p0 unsafe.Pointer p0 = unsafe.Pointer(&mib[0]) _, _, e1 := syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if e1 != 0 { err = e1 } return }
go
func sysctl(mib []C.int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var p0 unsafe.Pointer p0 = unsafe.Pointer(&mib[0]) _, _, e1 := syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if e1 != 0 { err = e1 } return }
[ "func", "sysctl", "(", "mib", "[", "]", "C", ".", "int", ",", "old", "*", "byte", ",", "oldlen", "*", "uintptr", ",", "new", "*", "byte", ",", "newlen", "uintptr", ")", "(", "err", "error", ")", "{", "var", "p0", "unsafe", ".", "Pointer", "\n", "p0", "=", "unsafe", ".", "Pointer", "(", "&", "mib", "[", "0", "]", ")", "\n", "_", ",", "_", ",", "e1", ":=", "syscall", ".", "Syscall6", "(", "syscall", ".", "SYS___SYSCTL", ",", "uintptr", "(", "p0", ")", ",", "uintptr", "(", "len", "(", "mib", ")", ")", ",", "uintptr", "(", "unsafe", ".", "Pointer", "(", "old", ")", ")", ",", "uintptr", "(", "unsafe", ".", "Pointer", "(", "oldlen", ")", ")", ",", "uintptr", "(", "unsafe", ".", "Pointer", "(", "new", ")", ")", ",", "uintptr", "(", "newlen", ")", ")", "\n", "if", "e1", "!=", "0", "{", "err", "=", "e1", "\n", "}", "\n", "return", "\n", "}" ]
// XXX copied from zsyscall_darwin_amd64.go
[ "XXX", "copied", "from", "zsyscall_darwin_amd64", ".", "go" ]
50ddd08d81d770b1e0ce2c969a46e46c73580e2a
https://github.com/cloudfoundry/gosigar/blob/50ddd08d81d770b1e0ce2c969a46e46c73580e2a/sigar_darwin.go#L382-L394
12,802
cloudfoundry/gosigar
psnotify/psnotify_linux.go
createListener
func createListener() (eventListener, error) { listener := &netlinkListener{} err := listener.bind() return listener, err }
go
func createListener() (eventListener, error) { listener := &netlinkListener{} err := listener.bind() return listener, err }
[ "func", "createListener", "(", ")", "(", "eventListener", ",", "error", ")", "{", "listener", ":=", "&", "netlinkListener", "{", "}", "\n", "err", ":=", "listener", ".", "bind", "(", ")", "\n", "return", "listener", ",", "err", "\n", "}" ]
// Initialize linux implementation of the eventListener interface
[ "Initialize", "linux", "implementation", "of", "the", "eventListener", "interface" ]
50ddd08d81d770b1e0ce2c969a46e46c73580e2a
https://github.com/cloudfoundry/gosigar/blob/50ddd08d81d770b1e0ce2c969a46e46c73580e2a/psnotify/psnotify_linux.go#L91-L95
12,803
cloudfoundry/gosigar
psnotify/psnotify_linux.go
readEvents
func (w *Watcher) readEvents() { buf := make([]byte, syscall.Getpagesize()) listener, _ := w.listener.(*netlinkListener) for { if w.isDone() { return } nr, _, err := syscall.Recvfrom(listener.sock, buf, 0) if err != nil { w.Error <- err continue } if nr < syscall.NLMSG_HDRLEN { w.Error <- syscall.EINVAL continue } msgs, _ := syscall.ParseNetlinkMessage(buf[:nr]) for _, m := range msgs { if m.Header.Type == syscall.NLMSG_DONE { w.handleEvent(m.Data) } } } }
go
func (w *Watcher) readEvents() { buf := make([]byte, syscall.Getpagesize()) listener, _ := w.listener.(*netlinkListener) for { if w.isDone() { return } nr, _, err := syscall.Recvfrom(listener.sock, buf, 0) if err != nil { w.Error <- err continue } if nr < syscall.NLMSG_HDRLEN { w.Error <- syscall.EINVAL continue } msgs, _ := syscall.ParseNetlinkMessage(buf[:nr]) for _, m := range msgs { if m.Header.Type == syscall.NLMSG_DONE { w.handleEvent(m.Data) } } } }
[ "func", "(", "w", "*", "Watcher", ")", "readEvents", "(", ")", "{", "buf", ":=", "make", "(", "[", "]", "byte", ",", "syscall", ".", "Getpagesize", "(", ")", ")", "\n\n", "listener", ",", "_", ":=", "w", ".", "listener", ".", "(", "*", "netlinkListener", ")", "\n\n", "for", "{", "if", "w", ".", "isDone", "(", ")", "{", "return", "\n", "}", "\n\n", "nr", ",", "_", ",", "err", ":=", "syscall", ".", "Recvfrom", "(", "listener", ".", "sock", ",", "buf", ",", "0", ")", "\n\n", "if", "err", "!=", "nil", "{", "w", ".", "Error", "<-", "err", "\n", "continue", "\n", "}", "\n", "if", "nr", "<", "syscall", ".", "NLMSG_HDRLEN", "{", "w", ".", "Error", "<-", "syscall", ".", "EINVAL", "\n", "continue", "\n", "}", "\n\n", "msgs", ",", "_", ":=", "syscall", ".", "ParseNetlinkMessage", "(", "buf", "[", ":", "nr", "]", ")", "\n\n", "for", "_", ",", "m", ":=", "range", "msgs", "{", "if", "m", ".", "Header", ".", "Type", "==", "syscall", ".", "NLMSG_DONE", "{", "w", ".", "handleEvent", "(", "m", ".", "Data", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Read events from the netlink socket
[ "Read", "events", "from", "the", "netlink", "socket" ]
50ddd08d81d770b1e0ce2c969a46e46c73580e2a
https://github.com/cloudfoundry/gosigar/blob/50ddd08d81d770b1e0ce2c969a46e46c73580e2a/psnotify/psnotify_linux.go#L108-L137
12,804
cloudfoundry/gosigar
psnotify/psnotify_linux.go
isWatching
func (w *Watcher) isWatching(pid int, event uint32) bool { w.watchesMutex.Lock() defer w.watchesMutex.Unlock() if watch, ok := w.watches[pid]; ok { return (watch.flags & event) == event } return false }
go
func (w *Watcher) isWatching(pid int, event uint32) bool { w.watchesMutex.Lock() defer w.watchesMutex.Unlock() if watch, ok := w.watches[pid]; ok { return (watch.flags & event) == event } return false }
[ "func", "(", "w", "*", "Watcher", ")", "isWatching", "(", "pid", "int", ",", "event", "uint32", ")", "bool", "{", "w", ".", "watchesMutex", ".", "Lock", "(", ")", "\n", "defer", "w", ".", "watchesMutex", ".", "Unlock", "(", ")", "\n\n", "if", "watch", ",", "ok", ":=", "w", ".", "watches", "[", "pid", "]", ";", "ok", "{", "return", "(", "watch", ".", "flags", "&", "event", ")", "==", "event", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Internal helper to check if pid && event is being watched
[ "Internal", "helper", "to", "check", "if", "pid", "&&", "event", "is", "being", "watched" ]
50ddd08d81d770b1e0ce2c969a46e46c73580e2a
https://github.com/cloudfoundry/gosigar/blob/50ddd08d81d770b1e0ce2c969a46e46c73580e2a/psnotify/psnotify_linux.go#L140-L148
12,805
cloudfoundry/gosigar
psnotify/psnotify_linux.go
bind
func (listener *netlinkListener) bind() error { sock, err := syscall.Socket( syscall.AF_NETLINK, syscall.SOCK_DGRAM, syscall.NETLINK_CONNECTOR) if err != nil { return err } listener.sock = sock listener.addr = &syscall.SockaddrNetlink{ Family: syscall.AF_NETLINK, Groups: _CN_IDX_PROC, } err = syscall.Bind(listener.sock, listener.addr) if err != nil { return err } return listener.send(_PROC_CN_MCAST_LISTEN) }
go
func (listener *netlinkListener) bind() error { sock, err := syscall.Socket( syscall.AF_NETLINK, syscall.SOCK_DGRAM, syscall.NETLINK_CONNECTOR) if err != nil { return err } listener.sock = sock listener.addr = &syscall.SockaddrNetlink{ Family: syscall.AF_NETLINK, Groups: _CN_IDX_PROC, } err = syscall.Bind(listener.sock, listener.addr) if err != nil { return err } return listener.send(_PROC_CN_MCAST_LISTEN) }
[ "func", "(", "listener", "*", "netlinkListener", ")", "bind", "(", ")", "error", "{", "sock", ",", "err", ":=", "syscall", ".", "Socket", "(", "syscall", ".", "AF_NETLINK", ",", "syscall", ".", "SOCK_DGRAM", ",", "syscall", ".", "NETLINK_CONNECTOR", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "listener", ".", "sock", "=", "sock", "\n", "listener", ".", "addr", "=", "&", "syscall", ".", "SockaddrNetlink", "{", "Family", ":", "syscall", ".", "AF_NETLINK", ",", "Groups", ":", "_CN_IDX_PROC", ",", "}", "\n\n", "err", "=", "syscall", ".", "Bind", "(", "listener", ".", "sock", ",", "listener", ".", "addr", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "listener", ".", "send", "(", "_PROC_CN_MCAST_LISTEN", ")", "\n", "}" ]
// Bind our netlink socket and // send a listen control message to the connector driver.
[ "Bind", "our", "netlink", "socket", "and", "send", "a", "listen", "control", "message", "to", "the", "connector", "driver", "." ]
50ddd08d81d770b1e0ce2c969a46e46c73580e2a
https://github.com/cloudfoundry/gosigar/blob/50ddd08d81d770b1e0ce2c969a46e46c73580e2a/psnotify/psnotify_linux.go#L199-L222
12,806
cloudfoundry/gosigar
psnotify/psnotify_linux.go
close
func (listener *netlinkListener) close() error { err := listener.send(_PROC_CN_MCAST_IGNORE) syscall.Close(listener.sock) return err }
go
func (listener *netlinkListener) close() error { err := listener.send(_PROC_CN_MCAST_IGNORE) syscall.Close(listener.sock) return err }
[ "func", "(", "listener", "*", "netlinkListener", ")", "close", "(", ")", "error", "{", "err", ":=", "listener", ".", "send", "(", "_PROC_CN_MCAST_IGNORE", ")", "\n", "syscall", ".", "Close", "(", "listener", ".", "sock", ")", "\n", "return", "err", "\n", "}" ]
// Send an ignore control message to the connector driver // and close our netlink socket.
[ "Send", "an", "ignore", "control", "message", "to", "the", "connector", "driver", "and", "close", "our", "netlink", "socket", "." ]
50ddd08d81d770b1e0ce2c969a46e46c73580e2a
https://github.com/cloudfoundry/gosigar/blob/50ddd08d81d770b1e0ce2c969a46e46c73580e2a/psnotify/psnotify_linux.go#L226-L230
12,807
cloudfoundry/gosigar
sigar_format.go
FormatSize
func FormatSize(size uint64) string { ord := []string{"K", "M", "G", "T", "P", "E"} o := 0 buf := new(bytes.Buffer) w := bufio.NewWriter(buf) if size < 973 { fmt.Fprintf(w, "%3d ", size) w.Flush() return buf.String() } for { remain := size & 1023 size >>= 10 if size >= 973 { o++ continue } if size < 9 || (size == 9 && remain < 973) { remain = ((remain * 5) + 256) / 512 if remain >= 10 { size++ remain = 0 } fmt.Fprintf(w, "%d.%d%s", size, remain, ord[o]) break } if remain >= 512 { size++ } fmt.Fprintf(w, "%3d%s", size, ord[o]) break } w.Flush() return buf.String() }
go
func FormatSize(size uint64) string { ord := []string{"K", "M", "G", "T", "P", "E"} o := 0 buf := new(bytes.Buffer) w := bufio.NewWriter(buf) if size < 973 { fmt.Fprintf(w, "%3d ", size) w.Flush() return buf.String() } for { remain := size & 1023 size >>= 10 if size >= 973 { o++ continue } if size < 9 || (size == 9 && remain < 973) { remain = ((remain * 5) + 256) / 512 if remain >= 10 { size++ remain = 0 } fmt.Fprintf(w, "%d.%d%s", size, remain, ord[o]) break } if remain >= 512 { size++ } fmt.Fprintf(w, "%3d%s", size, ord[o]) break } w.Flush() return buf.String() }
[ "func", "FormatSize", "(", "size", "uint64", ")", "string", "{", "ord", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", "\n", "o", ":=", "0", "\n", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "w", ":=", "bufio", ".", "NewWriter", "(", "buf", ")", "\n\n", "if", "size", "<", "973", "{", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\"", ",", "size", ")", "\n", "w", ".", "Flush", "(", ")", "\n", "return", "buf", ".", "String", "(", ")", "\n", "}", "\n\n", "for", "{", "remain", ":=", "size", "&", "1023", "\n", "size", ">>=", "10", "\n\n", "if", "size", ">=", "973", "{", "o", "++", "\n", "continue", "\n", "}", "\n\n", "if", "size", "<", "9", "||", "(", "size", "==", "9", "&&", "remain", "<", "973", ")", "{", "remain", "=", "(", "(", "remain", "*", "5", ")", "+", "256", ")", "/", "512", "\n", "if", "remain", ">=", "10", "{", "size", "++", "\n", "remain", "=", "0", "\n", "}", "\n\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\"", ",", "size", ",", "remain", ",", "ord", "[", "o", "]", ")", "\n", "break", "\n", "}", "\n\n", "if", "remain", ">=", "512", "{", "size", "++", "\n", "}", "\n\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\"", ",", "size", ",", "ord", "[", "o", "]", ")", "\n", "break", "\n", "}", "\n\n", "w", ".", "Flush", "(", ")", "\n", "return", "buf", ".", "String", "(", ")", "\n", "}" ]
// Go version of apr_strfsize
[ "Go", "version", "of", "apr_strfsize" ]
50ddd08d81d770b1e0ce2c969a46e46c73580e2a
https://github.com/cloudfoundry/gosigar/blob/50ddd08d81d770b1e0ce2c969a46e46c73580e2a/sigar_format.go#L12-L54
12,808
alecthomas/participle
lexer/lexer.go
SymbolsByRune
func SymbolsByRune(def Definition) map[rune]string { out := map[rune]string{} for s, r := range def.Symbols() { out[r] = s } return out }
go
func SymbolsByRune(def Definition) map[rune]string { out := map[rune]string{} for s, r := range def.Symbols() { out[r] = s } return out }
[ "func", "SymbolsByRune", "(", "def", "Definition", ")", "map", "[", "rune", "]", "string", "{", "out", ":=", "map", "[", "rune", "]", "string", "{", "}", "\n", "for", "s", ",", "r", ":=", "range", "def", ".", "Symbols", "(", ")", "{", "out", "[", "r", "]", "=", "s", "\n", "}", "\n", "return", "out", "\n", "}" ]
// SymbolsByRune returns a map of lexer symbol names keyed by rune.
[ "SymbolsByRune", "returns", "a", "map", "of", "lexer", "symbol", "names", "keyed", "by", "rune", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/lexer/lexer.go#L42-L48
12,809
alecthomas/participle
lexer/lexer.go
NameOfReader
func NameOfReader(r interface{}) string { if nr, ok := r.(interface{ Name() string }); ok { return nr.Name() } return "" }
go
func NameOfReader(r interface{}) string { if nr, ok := r.(interface{ Name() string }); ok { return nr.Name() } return "" }
[ "func", "NameOfReader", "(", "r", "interface", "{", "}", ")", "string", "{", "if", "nr", ",", "ok", ":=", "r", ".", "(", "interface", "{", "Name", "(", ")", "string", "}", ")", ";", "ok", "{", "return", "nr", ".", "Name", "(", ")", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// NameOfReader attempts to retrieve the filename of a reader.
[ "NameOfReader", "attempts", "to", "retrieve", "the", "filename", "of", "a", "reader", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/lexer/lexer.go#L51-L56
12,810
alecthomas/participle
lexer/lexer.go
ConsumeAll
func ConsumeAll(lexer Lexer) ([]Token, error) { tokens := []Token{} for { token, err := lexer.Next() if err != nil { return nil, err } tokens = append(tokens, token) if token.Type == EOF { return tokens, nil } } }
go
func ConsumeAll(lexer Lexer) ([]Token, error) { tokens := []Token{} for { token, err := lexer.Next() if err != nil { return nil, err } tokens = append(tokens, token) if token.Type == EOF { return tokens, nil } } }
[ "func", "ConsumeAll", "(", "lexer", "Lexer", ")", "(", "[", "]", "Token", ",", "error", ")", "{", "tokens", ":=", "[", "]", "Token", "{", "}", "\n", "for", "{", "token", ",", "err", ":=", "lexer", ".", "Next", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "tokens", "=", "append", "(", "tokens", ",", "token", ")", "\n", "if", "token", ".", "Type", "==", "EOF", "{", "return", "tokens", ",", "nil", "\n", "}", "\n", "}", "\n", "}" ]
// ConsumeAll reads all tokens from a Lexer.
[ "ConsumeAll", "reads", "all", "tokens", "from", "a", "Lexer", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/lexer/lexer.go#L72-L84
12,811
alecthomas/participle
lexer/lexer.go
RuneToken
func RuneToken(r rune) Token { return Token{Type: r, Value: string(r)} }
go
func RuneToken(r rune) Token { return Token{Type: r, Value: string(r)} }
[ "func", "RuneToken", "(", "r", "rune", ")", "Token", "{", "return", "Token", "{", "Type", ":", "r", ",", "Value", ":", "string", "(", "r", ")", "}", "\n", "}" ]
// RuneToken represents a rune as a Token.
[ "RuneToken", "represents", "a", "rune", "as", "a", "Token", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/lexer/lexer.go#L116-L118
12,812
alecthomas/participle
lexer/lexer.go
MakeSymbolTable
func MakeSymbolTable(def Definition, types ...string) (map[rune]bool, error) { symbols := def.Symbols() table := map[rune]bool{} for _, symbol := range types { rn, ok := symbols[symbol] if !ok { return nil, fmt.Errorf("lexer does not support symbol %q", symbol) } table[rn] = true } return table, nil }
go
func MakeSymbolTable(def Definition, types ...string) (map[rune]bool, error) { symbols := def.Symbols() table := map[rune]bool{} for _, symbol := range types { rn, ok := symbols[symbol] if !ok { return nil, fmt.Errorf("lexer does not support symbol %q", symbol) } table[rn] = true } return table, nil }
[ "func", "MakeSymbolTable", "(", "def", "Definition", ",", "types", "...", "string", ")", "(", "map", "[", "rune", "]", "bool", ",", "error", ")", "{", "symbols", ":=", "def", ".", "Symbols", "(", ")", "\n", "table", ":=", "map", "[", "rune", "]", "bool", "{", "}", "\n", "for", "_", ",", "symbol", ":=", "range", "types", "{", "rn", ",", "ok", ":=", "symbols", "[", "symbol", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "symbol", ")", "\n", "}", "\n", "table", "[", "rn", "]", "=", "true", "\n", "}", "\n", "return", "table", ",", "nil", "\n", "}" ]
// MakeSymbolTable builds a lookup table for checking token ID existence. // // For each symbolic name in "types", the returned map will contain the corresponding token ID as a key.
[ "MakeSymbolTable", "builds", "a", "lookup", "table", "for", "checking", "token", "ID", "existence", ".", "For", "each", "symbolic", "name", "in", "types", "the", "returned", "map", "will", "contain", "the", "corresponding", "token", "ID", "as", "a", "key", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/lexer/lexer.go#L139-L150
12,813
alecthomas/participle
lexer/peek.go
Upgrade
func Upgrade(lexer Lexer) PeekingLexer { if peeking, ok := lexer.(PeekingLexer); ok { return peeking } return &lookaheadLexer{Lexer: lexer} }
go
func Upgrade(lexer Lexer) PeekingLexer { if peeking, ok := lexer.(PeekingLexer); ok { return peeking } return &lookaheadLexer{Lexer: lexer} }
[ "func", "Upgrade", "(", "lexer", "Lexer", ")", "PeekingLexer", "{", "if", "peeking", ",", "ok", ":=", "lexer", ".", "(", "PeekingLexer", ")", ";", "ok", "{", "return", "peeking", "\n", "}", "\n", "return", "&", "lookaheadLexer", "{", "Lexer", ":", "lexer", "}", "\n", "}" ]
// Upgrade a Lexer to a PeekingLexer with arbitrary lookahead.
[ "Upgrade", "a", "Lexer", "to", "a", "PeekingLexer", "with", "arbitrary", "lookahead", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/lexer/peek.go#L4-L9
12,814
alecthomas/participle
context.go
Defer
func (p *parseContext) Defer(pos lexer.Position, strct reflect.Value, field structLexerField, fieldValue []reflect.Value) { p.apply = append(p.apply, &contextFieldSet{pos, strct, field, fieldValue}) }
go
func (p *parseContext) Defer(pos lexer.Position, strct reflect.Value, field structLexerField, fieldValue []reflect.Value) { p.apply = append(p.apply, &contextFieldSet{pos, strct, field, fieldValue}) }
[ "func", "(", "p", "*", "parseContext", ")", "Defer", "(", "pos", "lexer", ".", "Position", ",", "strct", "reflect", ".", "Value", ",", "field", "structLexerField", ",", "fieldValue", "[", "]", "reflect", ".", "Value", ")", "{", "p", ".", "apply", "=", "append", "(", "p", ".", "apply", ",", "&", "contextFieldSet", "{", "pos", ",", "strct", ",", "field", ",", "fieldValue", "}", ")", "\n", "}" ]
// Defer adds a function to be applied once a branch has been picked.
[ "Defer", "adds", "a", "function", "to", "be", "applied", "once", "a", "branch", "has", "been", "picked", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/context.go#L37-L39
12,815
alecthomas/participle
context.go
Apply
func (p *parseContext) Apply() error { for _, apply := range p.apply { if err := setField(apply.pos, apply.strct, apply.field, apply.fieldValue); err != nil { return err } } p.apply = nil return nil }
go
func (p *parseContext) Apply() error { for _, apply := range p.apply { if err := setField(apply.pos, apply.strct, apply.field, apply.fieldValue); err != nil { return err } } p.apply = nil return nil }
[ "func", "(", "p", "*", "parseContext", ")", "Apply", "(", ")", "error", "{", "for", "_", ",", "apply", ":=", "range", "p", ".", "apply", "{", "if", "err", ":=", "setField", "(", "apply", ".", "pos", ",", "apply", ".", "strct", ",", "apply", ".", "field", ",", "apply", ".", "fieldValue", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "p", ".", "apply", "=", "nil", "\n", "return", "nil", "\n", "}" ]
// Apply deferred functions.
[ "Apply", "deferred", "functions", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/context.go#L42-L50
12,816
alecthomas/participle
context.go
Accept
func (p *parseContext) Accept(branch *parseContext) { p.apply = append(p.apply, branch.apply...) p.rewinder = branch.rewinder }
go
func (p *parseContext) Accept(branch *parseContext) { p.apply = append(p.apply, branch.apply...) p.rewinder = branch.rewinder }
[ "func", "(", "p", "*", "parseContext", ")", "Accept", "(", "branch", "*", "parseContext", ")", "{", "p", ".", "apply", "=", "append", "(", "p", ".", "apply", ",", "branch", ".", "apply", "...", ")", "\n", "p", ".", "rewinder", "=", "branch", ".", "rewinder", "\n", "}" ]
// Branch accepts the branch as the correct branch.
[ "Branch", "accepts", "the", "branch", "as", "the", "correct", "branch", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/context.go#L53-L56
12,817
alecthomas/participle
context.go
Branch
func (p *parseContext) Branch() *parseContext { branch := &parseContext{} *branch = *p branch.apply = nil branch.rewinder = p.rewinder.Lookahead() return branch }
go
func (p *parseContext) Branch() *parseContext { branch := &parseContext{} *branch = *p branch.apply = nil branch.rewinder = p.rewinder.Lookahead() return branch }
[ "func", "(", "p", "*", "parseContext", ")", "Branch", "(", ")", "*", "parseContext", "{", "branch", ":=", "&", "parseContext", "{", "}", "\n", "*", "branch", "=", "*", "p", "\n", "branch", ".", "apply", "=", "nil", "\n", "branch", ".", "rewinder", "=", "p", ".", "rewinder", ".", "Lookahead", "(", ")", "\n", "return", "branch", "\n", "}" ]
// Branch starts a new lookahead branch.
[ "Branch", "starts", "a", "new", "lookahead", "branch", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/context.go#L59-L65
12,818
alecthomas/participle
context.go
Stop
func (p *parseContext) Stop(branch *parseContext) bool { if branch.cursor > p.cursor+p.lookahead { p.Accept(branch) return true } return false }
go
func (p *parseContext) Stop(branch *parseContext) bool { if branch.cursor > p.cursor+p.lookahead { p.Accept(branch) return true } return false }
[ "func", "(", "p", "*", "parseContext", ")", "Stop", "(", "branch", "*", "parseContext", ")", "bool", "{", "if", "branch", ".", "cursor", ">", "p", ".", "cursor", "+", "p", ".", "lookahead", "{", "p", ".", "Accept", "(", "branch", ")", "\n", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Stop returns true if parsing should terminate after the given "branch" failed to match.
[ "Stop", "returns", "true", "if", "parsing", "should", "terminate", "after", "the", "given", "branch", "failed", "to", "match", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/context.go#L68-L74
12,819
alecthomas/participle
context.go
Lookahead
func (r *rewinder) Lookahead() *rewinder { clone := &rewinder{} *clone = *r clone.limit = clone.cursor return clone }
go
func (r *rewinder) Lookahead() *rewinder { clone := &rewinder{} *clone = *r clone.limit = clone.cursor return clone }
[ "func", "(", "r", "*", "rewinder", ")", "Lookahead", "(", ")", "*", "rewinder", "{", "clone", ":=", "&", "rewinder", "{", "}", "\n", "*", "clone", "=", "*", "r", "\n", "clone", ".", "limit", "=", "clone", ".", "cursor", "\n", "return", "clone", "\n", "}" ]
// Lookahead returns a new rewinder usable for lookahead.
[ "Lookahead", "returns", "a", "new", "rewinder", "usable", "for", "lookahead", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/context.go#L120-L125
12,820
alecthomas/participle
lexer/text_scanner.go
LexWithScanner
func LexWithScanner(r io.Reader, scan *scanner.Scanner) Lexer { return lexWithScanner(r, scan) }
go
func LexWithScanner(r io.Reader, scan *scanner.Scanner) Lexer { return lexWithScanner(r, scan) }
[ "func", "LexWithScanner", "(", "r", "io", ".", "Reader", ",", "scan", "*", "scanner", ".", "Scanner", ")", "Lexer", "{", "return", "lexWithScanner", "(", "r", ",", "scan", ")", "\n", "}" ]
// LexWithScanner creates a Lexer from a user-provided scanner.Scanner. // // Useful if you need to customise the Scanner.
[ "LexWithScanner", "creates", "a", "Lexer", "from", "a", "user", "-", "provided", "scanner", ".", "Scanner", ".", "Useful", "if", "you", "need", "to", "customise", "the", "Scanner", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/lexer/text_scanner.go#L66-L68
12,821
alecthomas/participle
map.go
Map
func Map(mapper Mapper, symbols ...string) Option { return func(p *Parser) error { p.mappers = append(p.mappers, mapperByToken{ mapper: mapper, symbols: symbols, }) return nil } }
go
func Map(mapper Mapper, symbols ...string) Option { return func(p *Parser) error { p.mappers = append(p.mappers, mapperByToken{ mapper: mapper, symbols: symbols, }) return nil } }
[ "func", "Map", "(", "mapper", "Mapper", ",", "symbols", "...", "string", ")", "Option", "{", "return", "func", "(", "p", "*", "Parser", ")", "error", "{", "p", ".", "mappers", "=", "append", "(", "p", ".", "mappers", ",", "mapperByToken", "{", "mapper", ":", "mapper", ",", "symbols", ":", "symbols", ",", "}", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Map is an Option that configures the Parser to apply a mapping function to each Token from the lexer. // // This can be useful to eg. upper-case all tokens of a certain type, or dequote strings. // // "symbols" specifies the token symbols that the Mapper will be applied to. If empty, all tokens will be mapped.
[ "Map", "is", "an", "Option", "that", "configures", "the", "Parser", "to", "apply", "a", "mapping", "function", "to", "each", "Token", "from", "the", "lexer", ".", "This", "can", "be", "useful", "to", "eg", ".", "upper", "-", "case", "all", "tokens", "of", "a", "certain", "type", "or", "dequote", "strings", ".", "symbols", "specifies", "the", "token", "symbols", "that", "the", "Mapper", "will", "be", "applied", "to", ".", "If", "empty", "all", "tokens", "will", "be", "mapped", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/map.go#L30-L38
12,822
alecthomas/participle
map.go
Upper
func Upper(types ...string) Option { return Map(func(token lexer.Token) (lexer.Token, error) { token.Value = strings.ToUpper(token.Value) return token, nil }, types...) }
go
func Upper(types ...string) Option { return Map(func(token lexer.Token) (lexer.Token, error) { token.Value = strings.ToUpper(token.Value) return token, nil }, types...) }
[ "func", "Upper", "(", "types", "...", "string", ")", "Option", "{", "return", "Map", "(", "func", "(", "token", "lexer", ".", "Token", ")", "(", "lexer", ".", "Token", ",", "error", ")", "{", "token", ".", "Value", "=", "strings", ".", "ToUpper", "(", "token", ".", "Value", ")", "\n", "return", "token", ",", "nil", "\n", "}", ",", "types", "...", ")", "\n", "}" ]
// Upper is an Option that upper-cases all tokens of the given type. Useful for case normalisation.
[ "Upper", "is", "an", "Option", "that", "upper", "-", "cases", "all", "tokens", "of", "the", "given", "type", ".", "Useful", "for", "case", "normalisation", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/map.go#L73-L78
12,823
alecthomas/participle
map.go
Elide
func Elide(types ...string) Option { return Map(func(token lexer.Token) (lexer.Token, error) { return lexer.Token{}, DropToken }, types...) }
go
func Elide(types ...string) Option { return Map(func(token lexer.Token) (lexer.Token, error) { return lexer.Token{}, DropToken }, types...) }
[ "func", "Elide", "(", "types", "...", "string", ")", "Option", "{", "return", "Map", "(", "func", "(", "token", "lexer", ".", "Token", ")", "(", "lexer", ".", "Token", ",", "error", ")", "{", "return", "lexer", ".", "Token", "{", "}", ",", "DropToken", "\n", "}", ",", "types", "...", ")", "\n", "}" ]
// Elide drops tokens of the specified types.
[ "Elide", "drops", "tokens", "of", "the", "specified", "types", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/map.go#L81-L85
12,824
alecthomas/participle
lexer/ebnf/internal/parser.go
parseTerm
func (p *parser) parseTerm() (x Expression) { pos := p.pos switch p.tok { case scanner.Ident: x = p.parseIdentifier() case scanner.String: x = p.parseRange() case '(': p.next() x = &Group{pos, p.parseExpression()} p.expect(')') case '[': p.next() x = &Option{pos, p.parseExpression()} p.expect(']') case '{': p.next() x = &Repetition{pos, p.parseExpression()} p.expect('}') } return x }
go
func (p *parser) parseTerm() (x Expression) { pos := p.pos switch p.tok { case scanner.Ident: x = p.parseIdentifier() case scanner.String: x = p.parseRange() case '(': p.next() x = &Group{pos, p.parseExpression()} p.expect(')') case '[': p.next() x = &Option{pos, p.parseExpression()} p.expect(']') case '{': p.next() x = &Repetition{pos, p.parseExpression()} p.expect('}') } return x }
[ "func", "(", "p", "*", "parser", ")", "parseTerm", "(", ")", "(", "x", "Expression", ")", "{", "pos", ":=", "p", ".", "pos", "\n\n", "switch", "p", ".", "tok", "{", "case", "scanner", ".", "Ident", ":", "x", "=", "p", ".", "parseIdentifier", "(", ")", "\n\n", "case", "scanner", ".", "String", ":", "x", "=", "p", ".", "parseRange", "(", ")", "\n\n", "case", "'('", ":", "p", ".", "next", "(", ")", "\n", "x", "=", "&", "Group", "{", "pos", ",", "p", ".", "parseExpression", "(", ")", "}", "\n", "p", ".", "expect", "(", "')'", ")", "\n\n", "case", "'['", ":", "p", ".", "next", "(", ")", "\n", "x", "=", "&", "Option", "{", "pos", ",", "p", ".", "parseExpression", "(", ")", "}", "\n", "p", ".", "expect", "(", "']'", ")", "\n\n", "case", "'{'", ":", "p", ".", "next", "(", ")", "\n", "x", "=", "&", "Repetition", "{", "pos", ",", "p", ".", "parseExpression", "(", ")", "}", "\n", "p", ".", "expect", "(", "'}'", ")", "\n", "}", "\n\n", "return", "x", "\n", "}" ]
// ParseTerm returns nil if no term was found.
[ "ParseTerm", "returns", "nil", "if", "no", "term", "was", "found", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/lexer/ebnf/internal/parser.go#L97-L124
12,825
alecthomas/participle
lexer/ebnf/internal/parser.go
Parse
func Parse(filename string, src io.Reader) (Grammar, error) { var p parser grammar := p.parse(filename, src) return grammar, p.errors.Err() }
go
func Parse(filename string, src io.Reader) (Grammar, error) { var p parser grammar := p.parse(filename, src) return grammar, p.errors.Err() }
[ "func", "Parse", "(", "filename", "string", ",", "src", "io", ".", "Reader", ")", "(", "Grammar", ",", "error", ")", "{", "var", "p", "parser", "\n", "grammar", ":=", "p", ".", "parse", "(", "filename", ",", "src", ")", "\n", "return", "grammar", ",", "p", ".", "errors", ".", "Err", "(", ")", "\n", "}" ]
// Parse parses a set of EBNF productions from source src. // It returns a set of productions. Errors are reported // for incorrect syntax and if a production is declared // more than once; the filename is used only for error // positions. //
[ "Parse", "parses", "a", "set", "of", "EBNF", "productions", "from", "source", "src", ".", "It", "returns", "a", "set", "of", "productions", ".", "Errors", "are", "reported", "for", "incorrect", "syntax", "and", "if", "a", "production", "is", "declared", "more", "than", "once", ";", "the", "filename", "is", "used", "only", "for", "error", "positions", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/lexer/ebnf/internal/parser.go#L205-L209
12,826
alecthomas/participle
lexer/ebnf/ebnf.go
optimize
func (e *ebnfLexerDefinition) optimize(expr internal.Expression) internal.Expression { switch n := expr.(type) { case internal.Alternative: // Convert alternate characters into a character set (eg. "a" | "b" | "c" | "true" becomes // set("abc") | "true"). out := make(internal.Alternative, 0, len(n)) set := "" for _, expr := range n { if t, ok := expr.(*internal.Token); ok && utf8.RuneCountInString(t.String) == 1 { set += t.String continue } // Hit a node that is not a single-character Token. Flush set? if set != "" { out = append(out, &characterSet{pos: n.Pos(), Set: set}) set = "" } out = append(out, e.optimize(expr)) } if set != "" { out = append(out, &characterSet{pos: n.Pos(), Set: set}) } return out case internal.Sequence: for i, expr := range n { n[i] = e.optimize(expr) } case *internal.Group: n.Body = e.optimize(n.Body) case *internal.Option: n.Body = e.optimize(n.Body) case *internal.Repetition: n.Body = e.optimize(n.Body) case *internal.Range: // Convert range into a set. begin, end := beginEnd(n) set := &rangeSet{ pos: n.Pos(), include: [2]rune{begin, end}, } for next := n.Exclude; next != nil; { switch n := next.(type) { case *internal.Range: begin, end := beginEnd(n) set.exclude = append(set.exclude, [2]rune{begin, end}) next = n.Exclude case *internal.Token: rn, _ := utf8.DecodeRuneInString(n.String) set.exclude = append(set.exclude, [2]rune{rn, rn}) next = nil default: panic(fmt.Sprintf("should not have encountered %T", n)) } } // Use an asciiSet if the characters are in ASCII range. return makeSet(n.Pos(), set) case *internal.Token: return &ebnfToken{pos: n.Pos(), runes: []rune(n.String)} } return expr }
go
func (e *ebnfLexerDefinition) optimize(expr internal.Expression) internal.Expression { switch n := expr.(type) { case internal.Alternative: // Convert alternate characters into a character set (eg. "a" | "b" | "c" | "true" becomes // set("abc") | "true"). out := make(internal.Alternative, 0, len(n)) set := "" for _, expr := range n { if t, ok := expr.(*internal.Token); ok && utf8.RuneCountInString(t.String) == 1 { set += t.String continue } // Hit a node that is not a single-character Token. Flush set? if set != "" { out = append(out, &characterSet{pos: n.Pos(), Set: set}) set = "" } out = append(out, e.optimize(expr)) } if set != "" { out = append(out, &characterSet{pos: n.Pos(), Set: set}) } return out case internal.Sequence: for i, expr := range n { n[i] = e.optimize(expr) } case *internal.Group: n.Body = e.optimize(n.Body) case *internal.Option: n.Body = e.optimize(n.Body) case *internal.Repetition: n.Body = e.optimize(n.Body) case *internal.Range: // Convert range into a set. begin, end := beginEnd(n) set := &rangeSet{ pos: n.Pos(), include: [2]rune{begin, end}, } for next := n.Exclude; next != nil; { switch n := next.(type) { case *internal.Range: begin, end := beginEnd(n) set.exclude = append(set.exclude, [2]rune{begin, end}) next = n.Exclude case *internal.Token: rn, _ := utf8.DecodeRuneInString(n.String) set.exclude = append(set.exclude, [2]rune{rn, rn}) next = nil default: panic(fmt.Sprintf("should not have encountered %T", n)) } } // Use an asciiSet if the characters are in ASCII range. return makeSet(n.Pos(), set) case *internal.Token: return &ebnfToken{pos: n.Pos(), runes: []rune(n.String)} } return expr }
[ "func", "(", "e", "*", "ebnfLexerDefinition", ")", "optimize", "(", "expr", "internal", ".", "Expression", ")", "internal", ".", "Expression", "{", "switch", "n", ":=", "expr", ".", "(", "type", ")", "{", "case", "internal", ".", "Alternative", ":", "// Convert alternate characters into a character set (eg. \"a\" | \"b\" | \"c\" | \"true\" becomes", "// set(\"abc\") | \"true\").", "out", ":=", "make", "(", "internal", ".", "Alternative", ",", "0", ",", "len", "(", "n", ")", ")", "\n", "set", ":=", "\"", "\"", "\n", "for", "_", ",", "expr", ":=", "range", "n", "{", "if", "t", ",", "ok", ":=", "expr", ".", "(", "*", "internal", ".", "Token", ")", ";", "ok", "&&", "utf8", ".", "RuneCountInString", "(", "t", ".", "String", ")", "==", "1", "{", "set", "+=", "t", ".", "String", "\n", "continue", "\n", "}", "\n", "// Hit a node that is not a single-character Token. Flush set?", "if", "set", "!=", "\"", "\"", "{", "out", "=", "append", "(", "out", ",", "&", "characterSet", "{", "pos", ":", "n", ".", "Pos", "(", ")", ",", "Set", ":", "set", "}", ")", "\n", "set", "=", "\"", "\"", "\n", "}", "\n", "out", "=", "append", "(", "out", ",", "e", ".", "optimize", "(", "expr", ")", ")", "\n", "}", "\n", "if", "set", "!=", "\"", "\"", "{", "out", "=", "append", "(", "out", ",", "&", "characterSet", "{", "pos", ":", "n", ".", "Pos", "(", ")", ",", "Set", ":", "set", "}", ")", "\n", "}", "\n", "return", "out", "\n\n", "case", "internal", ".", "Sequence", ":", "for", "i", ",", "expr", ":=", "range", "n", "{", "n", "[", "i", "]", "=", "e", ".", "optimize", "(", "expr", ")", "\n", "}", "\n\n", "case", "*", "internal", ".", "Group", ":", "n", ".", "Body", "=", "e", ".", "optimize", "(", "n", ".", "Body", ")", "\n\n", "case", "*", "internal", ".", "Option", ":", "n", ".", "Body", "=", "e", ".", "optimize", "(", "n", ".", "Body", ")", "\n\n", "case", "*", "internal", ".", "Repetition", ":", "n", ".", "Body", "=", "e", ".", "optimize", "(", "n", ".", "Body", ")", "\n\n", "case", "*", "internal", ".", "Range", ":", "// Convert range into a set.", "begin", ",", "end", ":=", "beginEnd", "(", "n", ")", "\n", "set", ":=", "&", "rangeSet", "{", "pos", ":", "n", ".", "Pos", "(", ")", ",", "include", ":", "[", "2", "]", "rune", "{", "begin", ",", "end", "}", ",", "}", "\n\n", "for", "next", ":=", "n", ".", "Exclude", ";", "next", "!=", "nil", ";", "{", "switch", "n", ":=", "next", ".", "(", "type", ")", "{", "case", "*", "internal", ".", "Range", ":", "begin", ",", "end", ":=", "beginEnd", "(", "n", ")", "\n", "set", ".", "exclude", "=", "append", "(", "set", ".", "exclude", ",", "[", "2", "]", "rune", "{", "begin", ",", "end", "}", ")", "\n", "next", "=", "n", ".", "Exclude", "\n", "case", "*", "internal", ".", "Token", ":", "rn", ",", "_", ":=", "utf8", ".", "DecodeRuneInString", "(", "n", ".", "String", ")", "\n", "set", ".", "exclude", "=", "append", "(", "set", ".", "exclude", ",", "[", "2", "]", "rune", "{", "rn", ",", "rn", "}", ")", "\n", "next", "=", "nil", "\n", "default", ":", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "n", ")", ")", "\n", "}", "\n", "}", "\n", "// Use an asciiSet if the characters are in ASCII range.", "return", "makeSet", "(", "n", ".", "Pos", "(", ")", ",", "set", ")", "\n\n", "case", "*", "internal", ".", "Token", ":", "return", "&", "ebnfToken", "{", "pos", ":", "n", ".", "Pos", "(", ")", ",", "runes", ":", "[", "]", "rune", "(", "n", ".", "String", ")", "}", "\n", "}", "\n", "return", "expr", "\n", "}" ]
// Apply some optimizations to the EBNF.
[ "Apply", "some", "optimizations", "to", "the", "EBNF", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/lexer/ebnf/ebnf.go#L279-L346
12,827
alecthomas/participle
lexer/ebnf/ebnf.go
validate
func validate(grammar internal.Grammar, expr internal.Expression) error { // nolint: gocyclo switch n := expr.(type) { case *internal.Production: return validate(grammar, n.Expr) case internal.Alternative: for _, e := range n { if err := validate(grammar, e); err != nil { return err } } return nil case *internal.Group: return validate(grammar, n.Body) case *internal.Name: if grammar.Index[n.String] == nil { return lexer.Errorf(lexer.Position(n.Pos()), "unknown production %q", n.String) } return nil case *internal.Option: return validate(grammar, n.Body) case *internal.Range: if utf8.RuneCountInString(n.Begin.String) != 1 { return lexer.Errorf(lexer.Position(n.Pos()), "start of range must be a single rune") } if utf8.RuneCountInString(n.End.String) != 1 { return lexer.Errorf(lexer.Position(n.Pos()), "end of range must be a single rune") } return nil case *internal.Repetition: return validate(grammar, n.Body) case internal.Sequence: for _, e := range n { if err := validate(grammar, e); err != nil { return err } } return nil case *internal.Token: return nil case nil: return nil } return lexer.Errorf(lexer.Position(expr.Pos()), "unknown EBNF expression %T", expr) }
go
func validate(grammar internal.Grammar, expr internal.Expression) error { // nolint: gocyclo switch n := expr.(type) { case *internal.Production: return validate(grammar, n.Expr) case internal.Alternative: for _, e := range n { if err := validate(grammar, e); err != nil { return err } } return nil case *internal.Group: return validate(grammar, n.Body) case *internal.Name: if grammar.Index[n.String] == nil { return lexer.Errorf(lexer.Position(n.Pos()), "unknown production %q", n.String) } return nil case *internal.Option: return validate(grammar, n.Body) case *internal.Range: if utf8.RuneCountInString(n.Begin.String) != 1 { return lexer.Errorf(lexer.Position(n.Pos()), "start of range must be a single rune") } if utf8.RuneCountInString(n.End.String) != 1 { return lexer.Errorf(lexer.Position(n.Pos()), "end of range must be a single rune") } return nil case *internal.Repetition: return validate(grammar, n.Body) case internal.Sequence: for _, e := range n { if err := validate(grammar, e); err != nil { return err } } return nil case *internal.Token: return nil case nil: return nil } return lexer.Errorf(lexer.Position(expr.Pos()), "unknown EBNF expression %T", expr) }
[ "func", "validate", "(", "grammar", "internal", ".", "Grammar", ",", "expr", "internal", ".", "Expression", ")", "error", "{", "// nolint: gocyclo", "switch", "n", ":=", "expr", ".", "(", "type", ")", "{", "case", "*", "internal", ".", "Production", ":", "return", "validate", "(", "grammar", ",", "n", ".", "Expr", ")", "\n\n", "case", "internal", ".", "Alternative", ":", "for", "_", ",", "e", ":=", "range", "n", "{", "if", "err", ":=", "validate", "(", "grammar", ",", "e", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n\n", "case", "*", "internal", ".", "Group", ":", "return", "validate", "(", "grammar", ",", "n", ".", "Body", ")", "\n\n", "case", "*", "internal", ".", "Name", ":", "if", "grammar", ".", "Index", "[", "n", ".", "String", "]", "==", "nil", "{", "return", "lexer", ".", "Errorf", "(", "lexer", ".", "Position", "(", "n", ".", "Pos", "(", ")", ")", ",", "\"", "\"", ",", "n", ".", "String", ")", "\n", "}", "\n", "return", "nil", "\n\n", "case", "*", "internal", ".", "Option", ":", "return", "validate", "(", "grammar", ",", "n", ".", "Body", ")", "\n\n", "case", "*", "internal", ".", "Range", ":", "if", "utf8", ".", "RuneCountInString", "(", "n", ".", "Begin", ".", "String", ")", "!=", "1", "{", "return", "lexer", ".", "Errorf", "(", "lexer", ".", "Position", "(", "n", ".", "Pos", "(", ")", ")", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "utf8", ".", "RuneCountInString", "(", "n", ".", "End", ".", "String", ")", "!=", "1", "{", "return", "lexer", ".", "Errorf", "(", "lexer", ".", "Position", "(", "n", ".", "Pos", "(", ")", ")", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n\n", "case", "*", "internal", ".", "Repetition", ":", "return", "validate", "(", "grammar", ",", "n", ".", "Body", ")", "\n\n", "case", "internal", ".", "Sequence", ":", "for", "_", ",", "e", ":=", "range", "n", "{", "if", "err", ":=", "validate", "(", "grammar", ",", "e", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n\n", "case", "*", "internal", ".", "Token", ":", "return", "nil", "\n\n", "case", "nil", ":", "return", "nil", "\n", "}", "\n", "return", "lexer", ".", "Errorf", "(", "lexer", ".", "Position", "(", "expr", ".", "Pos", "(", ")", ")", ",", "\"", "\"", ",", "expr", ")", "\n", "}" ]
// Validate the grammar against the lexer rules.
[ "Validate", "the", "grammar", "against", "the", "lexer", "rules", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/lexer/ebnf/ebnf.go#L361-L413
12,828
alecthomas/participle
parser.go
Lex
func (p *Parser) Lex(r io.Reader) ([]lexer.Token, error) { lex, err := p.lex.Lex(r) if err != nil { return nil, err } return lexer.ConsumeAll(lex) }
go
func (p *Parser) Lex(r io.Reader) ([]lexer.Token, error) { lex, err := p.lex.Lex(r) if err != nil { return nil, err } return lexer.ConsumeAll(lex) }
[ "func", "(", "p", "*", "Parser", ")", "Lex", "(", "r", "io", ".", "Reader", ")", "(", "[", "]", "lexer", ".", "Token", ",", "error", ")", "{", "lex", ",", "err", ":=", "p", ".", "lex", ".", "Lex", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "lexer", ".", "ConsumeAll", "(", "lex", ")", "\n", "}" ]
// Lex uses the parser's lexer to tokenise input.
[ "Lex", "uses", "the", "parser", "s", "lexer", "to", "tokenise", "input", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/parser.go#L101-L107
12,829
alecthomas/participle
options.go
Lexer
func Lexer(def lexer.Definition) Option { return func(p *Parser) error { p.lex = def return nil } }
go
func Lexer(def lexer.Definition) Option { return func(p *Parser) error { p.lex = def return nil } }
[ "func", "Lexer", "(", "def", "lexer", ".", "Definition", ")", "Option", "{", "return", "func", "(", "p", "*", "Parser", ")", "error", "{", "p", ".", "lex", "=", "def", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Lexer is an Option that sets the lexer to use with the given grammar.
[ "Lexer", "is", "an", "Option", "that", "sets", "the", "lexer", "to", "use", "with", "the", "given", "grammar", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/options.go#L11-L16
12,830
alecthomas/participle
options.go
UseLookahead
func UseLookahead(n int) Option { return func(p *Parser) error { p.useLookahead = n return nil } }
go
func UseLookahead(n int) Option { return func(p *Parser) error { p.useLookahead = n return nil } }
[ "func", "UseLookahead", "(", "n", "int", ")", "Option", "{", "return", "func", "(", "p", "*", "Parser", ")", "error", "{", "p", ".", "useLookahead", "=", "n", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// UseLookahead allows branch lookahead up to "n" tokens. // // If parsing cannot be disambiguated before "n" tokens of lookahead, parsing will fail. // // Note that increasing lookahead has a minor performance impact, but also // reduces the accuracy of error reporting.
[ "UseLookahead", "allows", "branch", "lookahead", "up", "to", "n", "tokens", ".", "If", "parsing", "cannot", "be", "disambiguated", "before", "n", "tokens", "of", "lookahead", "parsing", "will", "fail", ".", "Note", "that", "increasing", "lookahead", "has", "a", "minor", "performance", "impact", "but", "also", "reduces", "the", "accuracy", "of", "error", "reporting", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/options.go#L24-L29
12,831
alecthomas/participle
options.go
CaseInsensitive
func CaseInsensitive(tokens ...string) Option { return func(p *Parser) error { for _, token := range tokens { p.caseInsensitive[token] = true } return nil } }
go
func CaseInsensitive(tokens ...string) Option { return func(p *Parser) error { for _, token := range tokens { p.caseInsensitive[token] = true } return nil } }
[ "func", "CaseInsensitive", "(", "tokens", "...", "string", ")", "Option", "{", "return", "func", "(", "p", "*", "Parser", ")", "error", "{", "for", "_", ",", "token", ":=", "range", "tokens", "{", "p", ".", "caseInsensitive", "[", "token", "]", "=", "true", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// CaseInsensitive allows the specified token types to be matched case-insensitively.
[ "CaseInsensitive", "allows", "the", "specified", "token", "types", "to", "be", "matched", "case", "-", "insensitively", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/options.go#L32-L39
12,832
alecthomas/participle
struct.go
collectFieldIndexes
func collectFieldIndexes(s reflect.Type) (out [][]int, err error) { if s.Kind() != reflect.Struct { return nil, fmt.Errorf("expected a struct but got %q", s) } defer decorate(&err, s.String) for i := 0; i < s.NumField(); i++ { f := s.Field(i) if f.Anonymous { children, err := collectFieldIndexes(f.Type) if err != nil { return nil, err } for _, idx := range children { out = append(out, append(f.Index, idx...)) } } else if fieldLexerTag(f) != "" { out = append(out, f.Index) } } return }
go
func collectFieldIndexes(s reflect.Type) (out [][]int, err error) { if s.Kind() != reflect.Struct { return nil, fmt.Errorf("expected a struct but got %q", s) } defer decorate(&err, s.String) for i := 0; i < s.NumField(); i++ { f := s.Field(i) if f.Anonymous { children, err := collectFieldIndexes(f.Type) if err != nil { return nil, err } for _, idx := range children { out = append(out, append(f.Index, idx...)) } } else if fieldLexerTag(f) != "" { out = append(out, f.Index) } } return }
[ "func", "collectFieldIndexes", "(", "s", "reflect", ".", "Type", ")", "(", "out", "[", "]", "[", "]", "int", ",", "err", "error", ")", "{", "if", "s", ".", "Kind", "(", ")", "!=", "reflect", ".", "Struct", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "s", ")", "\n", "}", "\n", "defer", "decorate", "(", "&", "err", ",", "s", ".", "String", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "s", ".", "NumField", "(", ")", ";", "i", "++", "{", "f", ":=", "s", ".", "Field", "(", "i", ")", "\n", "if", "f", ".", "Anonymous", "{", "children", ",", "err", ":=", "collectFieldIndexes", "(", "f", ".", "Type", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "idx", ":=", "range", "children", "{", "out", "=", "append", "(", "out", ",", "append", "(", "f", ".", "Index", ",", "idx", "...", ")", ")", "\n", "}", "\n", "}", "else", "if", "fieldLexerTag", "(", "f", ")", "!=", "\"", "\"", "{", "out", "=", "append", "(", "out", ",", "f", ".", "Index", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Recursively collect flattened indices for top-level fields and embedded fields.
[ "Recursively", "collect", "flattened", "indices", "for", "top", "-", "level", "fields", "and", "embedded", "fields", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/struct.go#L106-L126
12,833
alecthomas/participle
grammar.go
parseType
func (g *generatorContext) parseType(t reflect.Type) (_ node, returnedError error) { rt := t t = indirectType(t) if n, ok := g.typeNodes[t]; ok { return n, nil } if rt.Implements(parseableType) { return &parseable{rt.Elem()}, nil } if reflect.PtrTo(rt).Implements(parseableType) { return &parseable{rt}, nil } switch t.Kind() { case reflect.Slice, reflect.Ptr: t = indirectType(t.Elem()) if t.Kind() != reflect.Struct { return nil, fmt.Errorf("expected a struct but got %T", t) } fallthrough case reflect.Struct: slexer, err := lexStruct(t) if err != nil { return nil, err } out := &strct{typ: t} g.typeNodes[t] = out // Ensure we avoid infinite recursion. if slexer.NumField() == 0 { return nil, fmt.Errorf("can not parse into empty struct %s", t) } defer decorate(&returnedError, func() string { return slexer.Field().Name }) e, err := g.parseDisjunction(slexer) if err != nil { return nil, err } if e == nil { return nil, fmt.Errorf("no grammar found in %s", t) } if token, _ := slexer.Peek(); !token.EOF() { return nil, fmt.Errorf("unexpected input %q", token.Value) } out.expr = e return out, nil } return nil, fmt.Errorf("%s should be a struct or should implement the Parseable interface", t) }
go
func (g *generatorContext) parseType(t reflect.Type) (_ node, returnedError error) { rt := t t = indirectType(t) if n, ok := g.typeNodes[t]; ok { return n, nil } if rt.Implements(parseableType) { return &parseable{rt.Elem()}, nil } if reflect.PtrTo(rt).Implements(parseableType) { return &parseable{rt}, nil } switch t.Kind() { case reflect.Slice, reflect.Ptr: t = indirectType(t.Elem()) if t.Kind() != reflect.Struct { return nil, fmt.Errorf("expected a struct but got %T", t) } fallthrough case reflect.Struct: slexer, err := lexStruct(t) if err != nil { return nil, err } out := &strct{typ: t} g.typeNodes[t] = out // Ensure we avoid infinite recursion. if slexer.NumField() == 0 { return nil, fmt.Errorf("can not parse into empty struct %s", t) } defer decorate(&returnedError, func() string { return slexer.Field().Name }) e, err := g.parseDisjunction(slexer) if err != nil { return nil, err } if e == nil { return nil, fmt.Errorf("no grammar found in %s", t) } if token, _ := slexer.Peek(); !token.EOF() { return nil, fmt.Errorf("unexpected input %q", token.Value) } out.expr = e return out, nil } return nil, fmt.Errorf("%s should be a struct or should implement the Parseable interface", t) }
[ "func", "(", "g", "*", "generatorContext", ")", "parseType", "(", "t", "reflect", ".", "Type", ")", "(", "_", "node", ",", "returnedError", "error", ")", "{", "rt", ":=", "t", "\n", "t", "=", "indirectType", "(", "t", ")", "\n", "if", "n", ",", "ok", ":=", "g", ".", "typeNodes", "[", "t", "]", ";", "ok", "{", "return", "n", ",", "nil", "\n", "}", "\n", "if", "rt", ".", "Implements", "(", "parseableType", ")", "{", "return", "&", "parseable", "{", "rt", ".", "Elem", "(", ")", "}", ",", "nil", "\n", "}", "\n", "if", "reflect", ".", "PtrTo", "(", "rt", ")", ".", "Implements", "(", "parseableType", ")", "{", "return", "&", "parseable", "{", "rt", "}", ",", "nil", "\n", "}", "\n", "switch", "t", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Slice", ",", "reflect", ".", "Ptr", ":", "t", "=", "indirectType", "(", "t", ".", "Elem", "(", ")", ")", "\n", "if", "t", ".", "Kind", "(", ")", "!=", "reflect", ".", "Struct", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "t", ")", "\n", "}", "\n", "fallthrough", "\n\n", "case", "reflect", ".", "Struct", ":", "slexer", ",", "err", ":=", "lexStruct", "(", "t", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "out", ":=", "&", "strct", "{", "typ", ":", "t", "}", "\n", "g", ".", "typeNodes", "[", "t", "]", "=", "out", "// Ensure we avoid infinite recursion.", "\n", "if", "slexer", ".", "NumField", "(", ")", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "t", ")", "\n", "}", "\n", "defer", "decorate", "(", "&", "returnedError", ",", "func", "(", ")", "string", "{", "return", "slexer", ".", "Field", "(", ")", ".", "Name", "}", ")", "\n", "e", ",", "err", ":=", "g", ".", "parseDisjunction", "(", "slexer", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "e", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "t", ")", "\n", "}", "\n", "if", "token", ",", "_", ":=", "slexer", ".", "Peek", "(", ")", ";", "!", "token", ".", "EOF", "(", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "token", ".", "Value", ")", "\n", "}", "\n", "out", ".", "expr", "=", "e", "\n", "return", "out", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "t", ")", "\n", "}" ]
// Takes a type and builds a tree of nodes out of it.
[ "Takes", "a", "type", "and", "builds", "a", "tree", "of", "nodes", "out", "of", "it", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/grammar.go#L26-L71
12,834
alecthomas/participle
grammar.go
parseLiteral
func (g *generatorContext) parseLiteral(lex *structLexer) (node, error) { // nolint: interfacer token, err := lex.Next() if err != nil { return nil, err } if token.Type != scanner.String && token.Type != scanner.RawString && token.Type != scanner.Char { return nil, fmt.Errorf("expected quoted string but got %q", token) } s := token.Value t := rune(-1) token, err = lex.Peek() if err != nil { return nil, err } if token.Value == ":" && (token.Type == scanner.Char || token.Type == ':') { _, _ = lex.Next() token, err = lex.Next() if err != nil { return nil, err } if token.Type != scanner.Ident { return nil, fmt.Errorf("expected identifier for literal type constraint but got %q", token) } var ok bool t, ok = g.Symbols()[token.Value] if !ok { return nil, fmt.Errorf("unknown token type %q in literal type constraint", token) } } return &literal{s: s, t: t, tt: g.symbolsToIDs[t]}, nil }
go
func (g *generatorContext) parseLiteral(lex *structLexer) (node, error) { // nolint: interfacer token, err := lex.Next() if err != nil { return nil, err } if token.Type != scanner.String && token.Type != scanner.RawString && token.Type != scanner.Char { return nil, fmt.Errorf("expected quoted string but got %q", token) } s := token.Value t := rune(-1) token, err = lex.Peek() if err != nil { return nil, err } if token.Value == ":" && (token.Type == scanner.Char || token.Type == ':') { _, _ = lex.Next() token, err = lex.Next() if err != nil { return nil, err } if token.Type != scanner.Ident { return nil, fmt.Errorf("expected identifier for literal type constraint but got %q", token) } var ok bool t, ok = g.Symbols()[token.Value] if !ok { return nil, fmt.Errorf("unknown token type %q in literal type constraint", token) } } return &literal{s: s, t: t, tt: g.symbolsToIDs[t]}, nil }
[ "func", "(", "g", "*", "generatorContext", ")", "parseLiteral", "(", "lex", "*", "structLexer", ")", "(", "node", ",", "error", ")", "{", "// nolint: interfacer", "token", ",", "err", ":=", "lex", ".", "Next", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "token", ".", "Type", "!=", "scanner", ".", "String", "&&", "token", ".", "Type", "!=", "scanner", ".", "RawString", "&&", "token", ".", "Type", "!=", "scanner", ".", "Char", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "token", ")", "\n", "}", "\n", "s", ":=", "token", ".", "Value", "\n", "t", ":=", "rune", "(", "-", "1", ")", "\n", "token", ",", "err", "=", "lex", ".", "Peek", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "token", ".", "Value", "==", "\"", "\"", "&&", "(", "token", ".", "Type", "==", "scanner", ".", "Char", "||", "token", ".", "Type", "==", "':'", ")", "{", "_", ",", "_", "=", "lex", ".", "Next", "(", ")", "\n", "token", ",", "err", "=", "lex", ".", "Next", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "token", ".", "Type", "!=", "scanner", ".", "Ident", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "token", ")", "\n", "}", "\n", "var", "ok", "bool", "\n", "t", ",", "ok", "=", "g", ".", "Symbols", "(", ")", "[", "token", ".", "Value", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "token", ")", "\n", "}", "\n", "}", "\n", "return", "&", "literal", "{", "s", ":", "s", ",", "t", ":", "t", ",", "tt", ":", "g", ".", "symbolsToIDs", "[", "t", "]", "}", ",", "nil", "\n", "}" ]
// A literal string. // // Note that for this to match, the tokeniser must be able to produce this string. For example, // if the tokeniser only produces individual characters but the literal is "hello", or vice versa.
[ "A", "literal", "string", ".", "Note", "that", "for", "this", "to", "match", "the", "tokeniser", "must", "be", "able", "to", "produce", "this", "string", ".", "For", "example", "if", "the", "tokeniser", "only", "produces", "individual", "characters", "but", "the", "literal", "is", "hello", "or", "vice", "versa", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/grammar.go#L287-L317
12,835
alecthomas/participle
lexer/ebnf/reader.go
Begin
func (r *tokenReader) Begin() { r.runes = r.runes[r.cursor:] r.cursor = 0 r.oldPos = r.pos }
go
func (r *tokenReader) Begin() { r.runes = r.runes[r.cursor:] r.cursor = 0 r.oldPos = r.pos }
[ "func", "(", "r", "*", "tokenReader", ")", "Begin", "(", ")", "{", "r", ".", "runes", "=", "r", ".", "runes", "[", "r", ".", "cursor", ":", "]", "\n", "r", ".", "cursor", "=", "0", "\n", "r", ".", "oldPos", "=", "r", ".", "pos", "\n", "}" ]
// Begin a new token attempt.
[ "Begin", "a", "new", "token", "attempt", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/lexer/ebnf/reader.go#L30-L34
12,836
alecthomas/participle
lexer/ebnf/reader.go
buffer
func (r *tokenReader) buffer() (rune, error) { rn, _, err := r.r.ReadRune() if err != nil { return 0, err } r.runes = append(r.runes, rn) return rn, nil }
go
func (r *tokenReader) buffer() (rune, error) { rn, _, err := r.r.ReadRune() if err != nil { return 0, err } r.runes = append(r.runes, rn) return rn, nil }
[ "func", "(", "r", "*", "tokenReader", ")", "buffer", "(", ")", "(", "rune", ",", "error", ")", "{", "rn", ",", "_", ",", "err", ":=", "r", ".", "r", ".", "ReadRune", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "r", ".", "runes", "=", "append", "(", "r", ".", "runes", ",", "rn", ")", "\n", "return", "rn", ",", "nil", "\n", "}" ]
// Buffer a rune without moving the cursor.
[ "Buffer", "a", "rune", "without", "moving", "the", "cursor", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/lexer/ebnf/reader.go#L67-L74
12,837
alecthomas/participle
_examples/basic/ast.go
Parse
func Parse(r io.Reader) (*Program, error) { program := &Program{} err := basicParser.Parse(r, program) if err != nil { return nil, err } program.init() return program, nil }
go
func Parse(r io.Reader) (*Program, error) { program := &Program{} err := basicParser.Parse(r, program) if err != nil { return nil, err } program.init() return program, nil }
[ "func", "Parse", "(", "r", "io", ".", "Reader", ")", "(", "*", "Program", ",", "error", ")", "{", "program", ":=", "&", "Program", "{", "}", "\n", "err", ":=", "basicParser", ".", "Parse", "(", "r", ",", "program", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "program", ".", "init", "(", ")", "\n", "return", "program", ",", "nil", "\n", "}" ]
// Parse a BASIC program.
[ "Parse", "a", "BASIC", "program", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/_examples/basic/ast.go#L12-L20
12,838
alecthomas/participle
nodes.go
Parse
func (r *repetition) Parse(ctx *parseContext, parent reflect.Value) (out []reflect.Value, err error) { i := 0 for ; i < MaxIterations; i++ { branch := ctx.Branch() v, err := r.node.Parse(branch, parent) out = append(out, v...) if err != nil { // Optional part failed to match. if ctx.Stop(branch) { return out, err } break } else { ctx.Accept(branch) } if v == nil { break } } if i >= MaxIterations { t, _ := ctx.Peek(0) panic(lexer.Errorf(t.Pos, "too many iterations of %s (> %d)", r, MaxIterations)) } if out == nil { out = []reflect.Value{} } return out, nil }
go
func (r *repetition) Parse(ctx *parseContext, parent reflect.Value) (out []reflect.Value, err error) { i := 0 for ; i < MaxIterations; i++ { branch := ctx.Branch() v, err := r.node.Parse(branch, parent) out = append(out, v...) if err != nil { // Optional part failed to match. if ctx.Stop(branch) { return out, err } break } else { ctx.Accept(branch) } if v == nil { break } } if i >= MaxIterations { t, _ := ctx.Peek(0) panic(lexer.Errorf(t.Pos, "too many iterations of %s (> %d)", r, MaxIterations)) } if out == nil { out = []reflect.Value{} } return out, nil }
[ "func", "(", "r", "*", "repetition", ")", "Parse", "(", "ctx", "*", "parseContext", ",", "parent", "reflect", ".", "Value", ")", "(", "out", "[", "]", "reflect", ".", "Value", ",", "err", "error", ")", "{", "i", ":=", "0", "\n", "for", ";", "i", "<", "MaxIterations", ";", "i", "++", "{", "branch", ":=", "ctx", ".", "Branch", "(", ")", "\n", "v", ",", "err", ":=", "r", ".", "node", ".", "Parse", "(", "branch", ",", "parent", ")", "\n", "out", "=", "append", "(", "out", ",", "v", "...", ")", "\n", "if", "err", "!=", "nil", "{", "// Optional part failed to match.", "if", "ctx", ".", "Stop", "(", "branch", ")", "{", "return", "out", ",", "err", "\n", "}", "\n", "break", "\n", "}", "else", "{", "ctx", ".", "Accept", "(", "branch", ")", "\n", "}", "\n", "if", "v", "==", "nil", "{", "break", "\n", "}", "\n", "}", "\n", "if", "i", ">=", "MaxIterations", "{", "t", ",", "_", ":=", "ctx", ".", "Peek", "(", "0", ")", "\n", "panic", "(", "lexer", ".", "Errorf", "(", "t", ".", "Pos", ",", "\"", "\"", ",", "r", ",", "MaxIterations", ")", ")", "\n", "}", "\n", "if", "out", "==", "nil", "{", "out", "=", "[", "]", "reflect", ".", "Value", "{", "}", "\n", "}", "\n", "return", "out", ",", "nil", "\n", "}" ]
// Parse a repetition. Once a repetition is encountered it will always match, so grammars // should ensure that branches are differentiated prior to the repetition.
[ "Parse", "a", "repetition", ".", "Once", "a", "repetition", "is", "encountered", "it", "will", "always", "match", "so", "grammars", "should", "ensure", "that", "branches", "are", "differentiated", "prior", "to", "the", "repetition", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/nodes.go#L330-L357
12,839
alecthomas/participle
nodes.go
conform
func conform(t reflect.Type, values []reflect.Value) (out []reflect.Value, err error) { for _, v := range values { for t != v.Type() && t.Kind() == reflect.Ptr && v.Kind() != reflect.Ptr { // This can occur during partial failure. if !v.CanAddr() { return } v = v.Addr() } // Already of the right kind, don't bother converting. if v.Kind() == t.Kind() { out = append(out, v) continue } kind := t.Kind() switch kind { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: n, err := strconv.ParseInt(v.String(), 0, sizeOfKind(kind)) if err != nil { return nil, fmt.Errorf("invalid integer %q: %s", v.String(), err) } v = reflect.New(t).Elem() v.SetInt(n) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: n, err := strconv.ParseUint(v.String(), 0, sizeOfKind(kind)) if err != nil { return nil, fmt.Errorf("invalid integer %q: %s", v.String(), err) } v = reflect.New(t).Elem() v.SetUint(n) case reflect.Bool: v = reflect.ValueOf(true) case reflect.Float32, reflect.Float64: n, err := strconv.ParseFloat(v.String(), sizeOfKind(kind)) if err != nil { return nil, fmt.Errorf("invalid integer %q: %s", v.String(), err) } v = reflect.New(t).Elem() v.SetFloat(n) } out = append(out, v) } return out, nil }
go
func conform(t reflect.Type, values []reflect.Value) (out []reflect.Value, err error) { for _, v := range values { for t != v.Type() && t.Kind() == reflect.Ptr && v.Kind() != reflect.Ptr { // This can occur during partial failure. if !v.CanAddr() { return } v = v.Addr() } // Already of the right kind, don't bother converting. if v.Kind() == t.Kind() { out = append(out, v) continue } kind := t.Kind() switch kind { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: n, err := strconv.ParseInt(v.String(), 0, sizeOfKind(kind)) if err != nil { return nil, fmt.Errorf("invalid integer %q: %s", v.String(), err) } v = reflect.New(t).Elem() v.SetInt(n) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: n, err := strconv.ParseUint(v.String(), 0, sizeOfKind(kind)) if err != nil { return nil, fmt.Errorf("invalid integer %q: %s", v.String(), err) } v = reflect.New(t).Elem() v.SetUint(n) case reflect.Bool: v = reflect.ValueOf(true) case reflect.Float32, reflect.Float64: n, err := strconv.ParseFloat(v.String(), sizeOfKind(kind)) if err != nil { return nil, fmt.Errorf("invalid integer %q: %s", v.String(), err) } v = reflect.New(t).Elem() v.SetFloat(n) } out = append(out, v) } return out, nil }
[ "func", "conform", "(", "t", "reflect", ".", "Type", ",", "values", "[", "]", "reflect", ".", "Value", ")", "(", "out", "[", "]", "reflect", ".", "Value", ",", "err", "error", ")", "{", "for", "_", ",", "v", ":=", "range", "values", "{", "for", "t", "!=", "v", ".", "Type", "(", ")", "&&", "t", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "&&", "v", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "{", "// This can occur during partial failure.", "if", "!", "v", ".", "CanAddr", "(", ")", "{", "return", "\n", "}", "\n", "v", "=", "v", ".", "Addr", "(", ")", "\n", "}", "\n\n", "// Already of the right kind, don't bother converting.", "if", "v", ".", "Kind", "(", ")", "==", "t", ".", "Kind", "(", ")", "{", "out", "=", "append", "(", "out", ",", "v", ")", "\n", "continue", "\n", "}", "\n\n", "kind", ":=", "t", ".", "Kind", "(", ")", "\n", "switch", "kind", "{", "case", "reflect", ".", "Int", ",", "reflect", ".", "Int8", ",", "reflect", ".", "Int16", ",", "reflect", ".", "Int32", ",", "reflect", ".", "Int64", ":", "n", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "v", ".", "String", "(", ")", ",", "0", ",", "sizeOfKind", "(", "kind", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "v", ".", "String", "(", ")", ",", "err", ")", "\n", "}", "\n", "v", "=", "reflect", ".", "New", "(", "t", ")", ".", "Elem", "(", ")", "\n", "v", ".", "SetInt", "(", "n", ")", "\n\n", "case", "reflect", ".", "Uint", ",", "reflect", ".", "Uint8", ",", "reflect", ".", "Uint16", ",", "reflect", ".", "Uint32", ",", "reflect", ".", "Uint64", ":", "n", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "v", ".", "String", "(", ")", ",", "0", ",", "sizeOfKind", "(", "kind", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "v", ".", "String", "(", ")", ",", "err", ")", "\n", "}", "\n", "v", "=", "reflect", ".", "New", "(", "t", ")", ".", "Elem", "(", ")", "\n", "v", ".", "SetUint", "(", "n", ")", "\n\n", "case", "reflect", ".", "Bool", ":", "v", "=", "reflect", ".", "ValueOf", "(", "true", ")", "\n\n", "case", "reflect", ".", "Float32", ",", "reflect", ".", "Float64", ":", "n", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "v", ".", "String", "(", ")", ",", "sizeOfKind", "(", "kind", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "v", ".", "String", "(", ")", ",", "err", ")", "\n", "}", "\n", "v", "=", "reflect", ".", "New", "(", "t", ")", ".", "Elem", "(", ")", "\n", "v", ".", "SetFloat", "(", "n", ")", "\n", "}", "\n\n", "out", "=", "append", "(", "out", ",", "v", ")", "\n", "}", "\n", "return", "out", ",", "nil", "\n", "}" ]
// Attempt to transform values to given type. // // This will dereference pointers, and attempt to parse strings into integer values, floats, etc.
[ "Attempt", "to", "transform", "values", "to", "given", "type", ".", "This", "will", "dereference", "pointers", "and", "attempt", "to", "parse", "strings", "into", "integer", "values", "floats", "etc", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/nodes.go#L392-L441
12,840
alecthomas/participle
lexer/errors.go
Errorf
func Errorf(pos Position, format string, args ...interface{}) *Error { return &Error{ Message: fmt.Sprintf(format, args...), Pos: pos, } }
go
func Errorf(pos Position, format string, args ...interface{}) *Error { return &Error{ Message: fmt.Sprintf(format, args...), Pos: pos, } }
[ "func", "Errorf", "(", "pos", "Position", ",", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "*", "Error", "{", "return", "&", "Error", "{", "Message", ":", "fmt", ".", "Sprintf", "(", "format", ",", "args", "...", ")", ",", "Pos", ":", "pos", ",", "}", "\n", "}" ]
// Errorf creats a new Error at the given position.
[ "Errorf", "creats", "a", "new", "Error", "at", "the", "given", "position", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/lexer/errors.go#L12-L17
12,841
alecthomas/participle
lexer/errors.go
Error
func (e *Error) Error() string { filename := e.Pos.Filename if filename == "" { filename = "<source>" } return fmt.Sprintf("%s:%d:%d: %s", filename, e.Pos.Line, e.Pos.Column, e.Message) }
go
func (e *Error) Error() string { filename := e.Pos.Filename if filename == "" { filename = "<source>" } return fmt.Sprintf("%s:%d:%d: %s", filename, e.Pos.Line, e.Pos.Column, e.Message) }
[ "func", "(", "e", "*", "Error", ")", "Error", "(", ")", "string", "{", "filename", ":=", "e", ".", "Pos", ".", "Filename", "\n", "if", "filename", "==", "\"", "\"", "{", "filename", "=", "\"", "\"", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "filename", ",", "e", ".", "Pos", ".", "Line", ",", "e", ".", "Pos", ".", "Column", ",", "e", ".", "Message", ")", "\n", "}" ]
// Error complies with the error interface and reports the position of an error.
[ "Error", "complies", "with", "the", "error", "interface", "and", "reports", "the", "position", "of", "an", "error", "." ]
ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6
https://github.com/alecthomas/participle/blob/ecd076c6ba6cfe3d4a18e0b0e7af160e5825d8e6/lexer/errors.go#L20-L26
12,842
fanliao/go-promise
future_factory.go
Wrap
func Wrap(value interface{}) *Future { pr := NewPromise() if e, ok := value.(error); !ok { pr.Resolve(value) } else { pr.Reject(e) } return pr.Future }
go
func Wrap(value interface{}) *Future { pr := NewPromise() if e, ok := value.(error); !ok { pr.Resolve(value) } else { pr.Reject(e) } return pr.Future }
[ "func", "Wrap", "(", "value", "interface", "{", "}", ")", "*", "Future", "{", "pr", ":=", "NewPromise", "(", ")", "\n", "if", "e", ",", "ok", ":=", "value", ".", "(", "error", ")", ";", "!", "ok", "{", "pr", ".", "Resolve", "(", "value", ")", "\n", "}", "else", "{", "pr", ".", "Reject", "(", "e", ")", "\n", "}", "\n\n", "return", "pr", ".", "Future", "\n", "}" ]
//Wrap return a Future that presents the wrapped value
[ "Wrap", "return", "a", "Future", "that", "presents", "the", "wrapped", "value" ]
1890db352a72f9e6c6219c20111355cddc795297
https://github.com/fanliao/go-promise/blob/1890db352a72f9e6c6219c20111355cddc795297/future_factory.go#L72-L81
12,843
fanliao/go-promise
future_factory.go
WhenAll
func WhenAll(acts ...interface{}) (fu *Future) { pr := NewPromise() fu = pr.Future if len(acts) == 0 { pr.Resolve([]interface{}{}) return } fs := make([]*Future, len(acts)) for i, act := range acts { fs[i] = Start(act) } fu = whenAllFuture(fs...) return }
go
func WhenAll(acts ...interface{}) (fu *Future) { pr := NewPromise() fu = pr.Future if len(acts) == 0 { pr.Resolve([]interface{}{}) return } fs := make([]*Future, len(acts)) for i, act := range acts { fs[i] = Start(act) } fu = whenAllFuture(fs...) return }
[ "func", "WhenAll", "(", "acts", "...", "interface", "{", "}", ")", "(", "fu", "*", "Future", ")", "{", "pr", ":=", "NewPromise", "(", ")", "\n", "fu", "=", "pr", ".", "Future", "\n\n", "if", "len", "(", "acts", ")", "==", "0", "{", "pr", ".", "Resolve", "(", "[", "]", "interface", "{", "}", "{", "}", ")", "\n", "return", "\n", "}", "\n\n", "fs", ":=", "make", "(", "[", "]", "*", "Future", ",", "len", "(", "acts", ")", ")", "\n", "for", "i", ",", "act", ":=", "range", "acts", "{", "fs", "[", "i", "]", "=", "Start", "(", "act", ")", "\n", "}", "\n", "fu", "=", "whenAllFuture", "(", "fs", "...", ")", "\n", "return", "\n", "}" ]
//WhenAll receives function slice and returns a Future. //If all Futures are resolved, this Future will be resolved and return results slice. //Otherwise will rejected with results slice returned by all Futures //Legit types of act are same with Start function
[ "WhenAll", "receives", "function", "slice", "and", "returns", "a", "Future", ".", "If", "all", "Futures", "are", "resolved", "this", "Future", "will", "be", "resolved", "and", "return", "results", "slice", ".", "Otherwise", "will", "rejected", "with", "results", "slice", "returned", "by", "all", "Futures", "Legit", "types", "of", "act", "are", "same", "with", "Start", "function" ]
1890db352a72f9e6c6219c20111355cddc795297
https://github.com/fanliao/go-promise/blob/1890db352a72f9e6c6219c20111355cddc795297/future_factory.go#L207-L222
12,844
fanliao/go-promise
future_factory.go
whenAllFuture
func whenAllFuture(fs ...*Future) *Future { wf := NewPromise() rs := make([]interface{}, len(fs)) if len(fs) == 0 { wf.Resolve([]interface{}{}) } else { n := int32(len(fs)) cancelOthers := func(j int) { for k, f1 := range fs { if k != j { f1.Cancel() } } } go func() { isCancelled := int32(0) for i, f := range fs { j := i f.OnSuccess(func(v interface{}) { rs[j] = v if atomic.AddInt32(&n, -1) == 0 { wf.Resolve(rs) } }).OnFailure(func(v interface{}) { if atomic.CompareAndSwapInt32(&isCancelled, 0, 1) { //try to cancel all futures cancelOthers(j) //errs := make([]error, 0, 1) //errs = append(errs, v.(error)) e := newAggregateError1("Error appears in WhenAll:", v) wf.Reject(e) } }).OnCancel(func() { if atomic.CompareAndSwapInt32(&isCancelled, 0, 1) { //try to cancel all futures cancelOthers(j) wf.Cancel() } }) } }() } return wf.Future }
go
func whenAllFuture(fs ...*Future) *Future { wf := NewPromise() rs := make([]interface{}, len(fs)) if len(fs) == 0 { wf.Resolve([]interface{}{}) } else { n := int32(len(fs)) cancelOthers := func(j int) { for k, f1 := range fs { if k != j { f1.Cancel() } } } go func() { isCancelled := int32(0) for i, f := range fs { j := i f.OnSuccess(func(v interface{}) { rs[j] = v if atomic.AddInt32(&n, -1) == 0 { wf.Resolve(rs) } }).OnFailure(func(v interface{}) { if atomic.CompareAndSwapInt32(&isCancelled, 0, 1) { //try to cancel all futures cancelOthers(j) //errs := make([]error, 0, 1) //errs = append(errs, v.(error)) e := newAggregateError1("Error appears in WhenAll:", v) wf.Reject(e) } }).OnCancel(func() { if atomic.CompareAndSwapInt32(&isCancelled, 0, 1) { //try to cancel all futures cancelOthers(j) wf.Cancel() } }) } }() } return wf.Future }
[ "func", "whenAllFuture", "(", "fs", "...", "*", "Future", ")", "*", "Future", "{", "wf", ":=", "NewPromise", "(", ")", "\n", "rs", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "len", "(", "fs", ")", ")", "\n\n", "if", "len", "(", "fs", ")", "==", "0", "{", "wf", ".", "Resolve", "(", "[", "]", "interface", "{", "}", "{", "}", ")", "\n", "}", "else", "{", "n", ":=", "int32", "(", "len", "(", "fs", ")", ")", "\n", "cancelOthers", ":=", "func", "(", "j", "int", ")", "{", "for", "k", ",", "f1", ":=", "range", "fs", "{", "if", "k", "!=", "j", "{", "f1", ".", "Cancel", "(", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "go", "func", "(", ")", "{", "isCancelled", ":=", "int32", "(", "0", ")", "\n", "for", "i", ",", "f", ":=", "range", "fs", "{", "j", ":=", "i", "\n\n", "f", ".", "OnSuccess", "(", "func", "(", "v", "interface", "{", "}", ")", "{", "rs", "[", "j", "]", "=", "v", "\n", "if", "atomic", ".", "AddInt32", "(", "&", "n", ",", "-", "1", ")", "==", "0", "{", "wf", ".", "Resolve", "(", "rs", ")", "\n", "}", "\n", "}", ")", ".", "OnFailure", "(", "func", "(", "v", "interface", "{", "}", ")", "{", "if", "atomic", ".", "CompareAndSwapInt32", "(", "&", "isCancelled", ",", "0", ",", "1", ")", "{", "//try to cancel all futures", "cancelOthers", "(", "j", ")", "\n\n", "//errs := make([]error, 0, 1)", "//errs = append(errs, v.(error))", "e", ":=", "newAggregateError1", "(", "\"", "\"", ",", "v", ")", "\n", "wf", ".", "Reject", "(", "e", ")", "\n", "}", "\n", "}", ")", ".", "OnCancel", "(", "func", "(", ")", "{", "if", "atomic", ".", "CompareAndSwapInt32", "(", "&", "isCancelled", ",", "0", ",", "1", ")", "{", "//try to cancel all futures", "cancelOthers", "(", "j", ")", "\n\n", "wf", ".", "Cancel", "(", ")", "\n", "}", "\n", "}", ")", "\n", "}", "\n", "}", "(", ")", "\n", "}", "\n\n", "return", "wf", ".", "Future", "\n", "}" ]
//WhenAll receives Futures slice and returns a Future. //If all Futures are resolved, this Future will be resolved and return results slice. //If any Future is cancelled, this Future will be cancelled. //Otherwise will rejected with results slice returned by all Futures. //Legit types of act are same with Start function
[ "WhenAll", "receives", "Futures", "slice", "and", "returns", "a", "Future", ".", "If", "all", "Futures", "are", "resolved", "this", "Future", "will", "be", "resolved", "and", "return", "results", "slice", ".", "If", "any", "Future", "is", "cancelled", "this", "Future", "will", "be", "cancelled", ".", "Otherwise", "will", "rejected", "with", "results", "slice", "returned", "by", "all", "Futures", ".", "Legit", "types", "of", "act", "are", "same", "with", "Start", "function" ]
1890db352a72f9e6c6219c20111355cddc795297
https://github.com/fanliao/go-promise/blob/1890db352a72f9e6c6219c20111355cddc795297/future_factory.go#L229-L278
12,845
fanliao/go-promise
future.go
getPipe
func (this *pipe) getPipe(isResolved bool) (func(v interface{}) *Future, *Promise) { if isResolved { return this.pipeDoneTask, this.pipePromise } else { return this.pipeFailTask, this.pipePromise } }
go
func (this *pipe) getPipe(isResolved bool) (func(v interface{}) *Future, *Promise) { if isResolved { return this.pipeDoneTask, this.pipePromise } else { return this.pipeFailTask, this.pipePromise } }
[ "func", "(", "this", "*", "pipe", ")", "getPipe", "(", "isResolved", "bool", ")", "(", "func", "(", "v", "interface", "{", "}", ")", "*", "Future", ",", "*", "Promise", ")", "{", "if", "isResolved", "{", "return", "this", ".", "pipeDoneTask", ",", "this", ".", "pipePromise", "\n", "}", "else", "{", "return", "this", ".", "pipeFailTask", ",", "this", ".", "pipePromise", "\n", "}", "\n", "}" ]
//getPipe returns piped Future task function and pipe Promise by the status of current Promise.
[ "getPipe", "returns", "piped", "Future", "task", "function", "and", "pipe", "Promise", "by", "the", "status", "of", "current", "Promise", "." ]
1890db352a72f9e6c6219c20111355cddc795297
https://github.com/fanliao/go-promise/blob/1890db352a72f9e6c6219c20111355cddc795297/future.go#L39-L45
12,846
fanliao/go-promise
future.go
IsCancelled
func (this *Future) IsCancelled() bool { val := this.loadVal() if val != nil && val.r != nil && val.r.Typ == RESULT_CANCELLED { return true } else { return false } }
go
func (this *Future) IsCancelled() bool { val := this.loadVal() if val != nil && val.r != nil && val.r.Typ == RESULT_CANCELLED { return true } else { return false } }
[ "func", "(", "this", "*", "Future", ")", "IsCancelled", "(", ")", "bool", "{", "val", ":=", "this", ".", "loadVal", "(", ")", "\n\n", "if", "val", "!=", "nil", "&&", "val", ".", "r", "!=", "nil", "&&", "val", ".", "r", ".", "Typ", "==", "RESULT_CANCELLED", "{", "return", "true", "\n", "}", "else", "{", "return", "false", "\n", "}", "\n", "}" ]
//IsCancelled returns true if the promise is cancelled, otherwise false
[ "IsCancelled", "returns", "true", "if", "the", "promise", "is", "cancelled", "otherwise", "false" ]
1890db352a72f9e6c6219c20111355cddc795297
https://github.com/fanliao/go-promise/blob/1890db352a72f9e6c6219c20111355cddc795297/future.go#L96-L104
12,847
fanliao/go-promise
future.go
SetTimeout
func (this *Future) SetTimeout(mm int) *Future { if mm == 0 { mm = 10 } else { mm = mm * 1000 * 1000 } go func() { <-time.After((time.Duration)(mm) * time.Nanosecond) this.Cancel() }() return this }
go
func (this *Future) SetTimeout(mm int) *Future { if mm == 0 { mm = 10 } else { mm = mm * 1000 * 1000 } go func() { <-time.After((time.Duration)(mm) * time.Nanosecond) this.Cancel() }() return this }
[ "func", "(", "this", "*", "Future", ")", "SetTimeout", "(", "mm", "int", ")", "*", "Future", "{", "if", "mm", "==", "0", "{", "mm", "=", "10", "\n", "}", "else", "{", "mm", "=", "mm", "*", "1000", "*", "1000", "\n", "}", "\n\n", "go", "func", "(", ")", "{", "<-", "time", ".", "After", "(", "(", "time", ".", "Duration", ")", "(", "mm", ")", "*", "time", ".", "Nanosecond", ")", "\n", "this", ".", "Cancel", "(", ")", "\n", "}", "(", ")", "\n", "return", "this", "\n", "}" ]
//SetTimeout sets the future task will be cancelled //if future is not complete before time out
[ "SetTimeout", "sets", "the", "future", "task", "will", "be", "cancelled", "if", "future", "is", "not", "complete", "before", "time", "out" ]
1890db352a72f9e6c6219c20111355cddc795297
https://github.com/fanliao/go-promise/blob/1890db352a72f9e6c6219c20111355cddc795297/future.go#L108-L120
12,848
fanliao/go-promise
future.go
GetChan
func (this *Future) GetChan() <-chan *PromiseResult { c := make(chan *PromiseResult, 1) this.OnComplete(func(v interface{}) { c <- this.loadResult() }).OnCancel(func() { c <- this.loadResult() }) return c }
go
func (this *Future) GetChan() <-chan *PromiseResult { c := make(chan *PromiseResult, 1) this.OnComplete(func(v interface{}) { c <- this.loadResult() }).OnCancel(func() { c <- this.loadResult() }) return c }
[ "func", "(", "this", "*", "Future", ")", "GetChan", "(", ")", "<-", "chan", "*", "PromiseResult", "{", "c", ":=", "make", "(", "chan", "*", "PromiseResult", ",", "1", ")", "\n", "this", ".", "OnComplete", "(", "func", "(", "v", "interface", "{", "}", ")", "{", "c", "<-", "this", ".", "loadResult", "(", ")", "\n", "}", ")", ".", "OnCancel", "(", "func", "(", ")", "{", "c", "<-", "this", ".", "loadResult", "(", ")", "\n", "}", ")", "\n", "return", "c", "\n", "}" ]
//GetChan returns a channel than can be used to receive result of Promise
[ "GetChan", "returns", "a", "channel", "than", "can", "be", "used", "to", "receive", "result", "of", "Promise" ]
1890db352a72f9e6c6219c20111355cddc795297
https://github.com/fanliao/go-promise/blob/1890db352a72f9e6c6219c20111355cddc795297/future.go#L123-L131
12,849
fanliao/go-promise
future.go
loadVal
func (this *Future) loadVal() *futureVal { r := atomic.LoadPointer(&this.val) return (*futureVal)(r) }
go
func (this *Future) loadVal() *futureVal { r := atomic.LoadPointer(&this.val) return (*futureVal)(r) }
[ "func", "(", "this", "*", "Future", ")", "loadVal", "(", ")", "*", "futureVal", "{", "r", ":=", "atomic", ".", "LoadPointer", "(", "&", "this", ".", "val", ")", "\n", "return", "(", "*", "futureVal", ")", "(", "r", ")", "\n", "}" ]
//val uses Atomic load to return state value of the Future
[ "val", "uses", "Atomic", "load", "to", "return", "state", "value", "of", "the", "Future" ]
1890db352a72f9e6c6219c20111355cddc795297
https://github.com/fanliao/go-promise/blob/1890db352a72f9e6c6219c20111355cddc795297/future.go#L294-L297
12,850
fanliao/go-promise
future.go
setResult
func (this *Future) setResult(r *PromiseResult) (e error) { //r *PromiseResult) { defer func() { if err := getError(recover()); err != nil { e = err fmt.Println("\nerror in setResult():", err) } }() e = errors.New("Cannot resolve/reject/cancel more than once") for { v := this.loadVal() if v.r != nil { return } newVal := *v newVal.r = r //Use CAS operation to ensure that the state of Promise isn't changed. //If the state is changed, must get latest state and try to call CAS again. //No ABA issue in this case because address of all objects are different. if atomic.CompareAndSwapPointer(&this.val, unsafe.Pointer(v), unsafe.Pointer(&newVal)) { //Close chEnd then all Get() and GetOrTimeout() will be unblocked close(this.final) //call callback functions and start the Promise pipeline if len(v.dones) > 0 || len(v.fails) > 0 || len(v.always) > 0 || len(v.cancels) > 0 { go func() { execCallback(r, v.dones, v.fails, v.always, v.cancels) }() } //start the pipeline if len(v.pipes) > 0 { go func() { for _, pipe := range v.pipes { pipeTask, pipePromise := pipe.getPipe(r.Typ == RESULT_SUCCESS) startPipe(r, pipeTask, pipePromise) } }() } e = nil break } } return }
go
func (this *Future) setResult(r *PromiseResult) (e error) { //r *PromiseResult) { defer func() { if err := getError(recover()); err != nil { e = err fmt.Println("\nerror in setResult():", err) } }() e = errors.New("Cannot resolve/reject/cancel more than once") for { v := this.loadVal() if v.r != nil { return } newVal := *v newVal.r = r //Use CAS operation to ensure that the state of Promise isn't changed. //If the state is changed, must get latest state and try to call CAS again. //No ABA issue in this case because address of all objects are different. if atomic.CompareAndSwapPointer(&this.val, unsafe.Pointer(v), unsafe.Pointer(&newVal)) { //Close chEnd then all Get() and GetOrTimeout() will be unblocked close(this.final) //call callback functions and start the Promise pipeline if len(v.dones) > 0 || len(v.fails) > 0 || len(v.always) > 0 || len(v.cancels) > 0 { go func() { execCallback(r, v.dones, v.fails, v.always, v.cancels) }() } //start the pipeline if len(v.pipes) > 0 { go func() { for _, pipe := range v.pipes { pipeTask, pipePromise := pipe.getPipe(r.Typ == RESULT_SUCCESS) startPipe(r, pipeTask, pipePromise) } }() } e = nil break } } return }
[ "func", "(", "this", "*", "Future", ")", "setResult", "(", "r", "*", "PromiseResult", ")", "(", "e", "error", ")", "{", "//r *PromiseResult) {", "defer", "func", "(", ")", "{", "if", "err", ":=", "getError", "(", "recover", "(", ")", ")", ";", "err", "!=", "nil", "{", "e", "=", "err", "\n", "fmt", ".", "Println", "(", "\"", "\\n", "\"", ",", "err", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "e", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n\n", "for", "{", "v", ":=", "this", ".", "loadVal", "(", ")", "\n", "if", "v", ".", "r", "!=", "nil", "{", "return", "\n", "}", "\n", "newVal", ":=", "*", "v", "\n", "newVal", ".", "r", "=", "r", "\n\n", "//Use CAS operation to ensure that the state of Promise isn't changed.", "//If the state is changed, must get latest state and try to call CAS again.", "//No ABA issue in this case because address of all objects are different.", "if", "atomic", ".", "CompareAndSwapPointer", "(", "&", "this", ".", "val", ",", "unsafe", ".", "Pointer", "(", "v", ")", ",", "unsafe", ".", "Pointer", "(", "&", "newVal", ")", ")", "{", "//Close chEnd then all Get() and GetOrTimeout() will be unblocked", "close", "(", "this", ".", "final", ")", "\n\n", "//call callback functions and start the Promise pipeline", "if", "len", "(", "v", ".", "dones", ")", ">", "0", "||", "len", "(", "v", ".", "fails", ")", ">", "0", "||", "len", "(", "v", ".", "always", ")", ">", "0", "||", "len", "(", "v", ".", "cancels", ")", ">", "0", "{", "go", "func", "(", ")", "{", "execCallback", "(", "r", ",", "v", ".", "dones", ",", "v", ".", "fails", ",", "v", ".", "always", ",", "v", ".", "cancels", ")", "\n", "}", "(", ")", "\n", "}", "\n\n", "//start the pipeline", "if", "len", "(", "v", ".", "pipes", ")", ">", "0", "{", "go", "func", "(", ")", "{", "for", "_", ",", "pipe", ":=", "range", "v", ".", "pipes", "{", "pipeTask", ",", "pipePromise", ":=", "pipe", ".", "getPipe", "(", "r", ".", "Typ", "==", "RESULT_SUCCESS", ")", "\n", "startPipe", "(", "r", ",", "pipeTask", ",", "pipePromise", ")", "\n", "}", "\n", "}", "(", ")", "\n", "}", "\n", "e", "=", "nil", "\n", "break", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
//setResult sets the value and final status of Promise, it will only be executed for once
[ "setResult", "sets", "the", "value", "and", "final", "status", "of", "Promise", "it", "will", "only", "be", "executed", "for", "once" ]
1890db352a72f9e6c6219c20111355cddc795297
https://github.com/fanliao/go-promise/blob/1890db352a72f9e6c6219c20111355cddc795297/future.go#L300-L346
12,851
fanliao/go-promise
future.go
addCallback
func (this *Future) addCallback(callback interface{}, t callbackType) { if callback == nil { return } if (t == CALLBACK_DONE) || (t == CALLBACK_FAIL) || (t == CALLBACK_ALWAYS) { if _, ok := callback.(func(v interface{})); !ok { panic(errors.New("Callback function spec must be func(v interface{})")) } } else if t == CALLBACK_CANCEL { if _, ok := callback.(func()); !ok { panic(errors.New("Callback function spec must be func()")) } } for { v := this.loadVal() r := v.r if r == nil { newVal := *v switch t { case CALLBACK_DONE: newVal.dones = append(newVal.dones, callback.(func(v interface{}))) case CALLBACK_FAIL: newVal.fails = append(newVal.fails, callback.(func(v interface{}))) case CALLBACK_ALWAYS: newVal.always = append(newVal.always, callback.(func(v interface{}))) case CALLBACK_CANCEL: newVal.cancels = append(newVal.cancels, callback.(func())) } //use CAS to ensure that the state of Future is not changed, //if the state is changed, will retry CAS operation. if atomic.CompareAndSwapPointer(&this.val, unsafe.Pointer(v), unsafe.Pointer(&newVal)) { break } } else { if (t == CALLBACK_DONE && r.Typ == RESULT_SUCCESS) || (t == CALLBACK_FAIL && r.Typ == RESULT_FAILURE) || (t == CALLBACK_ALWAYS && r.Typ != RESULT_CANCELLED) { callbackFunc := callback.(func(v interface{})) callbackFunc(r.Result) } else if t == CALLBACK_CANCEL && r.Typ == RESULT_CANCELLED { callbackFunc := callback.(func()) callbackFunc() } break } } }
go
func (this *Future) addCallback(callback interface{}, t callbackType) { if callback == nil { return } if (t == CALLBACK_DONE) || (t == CALLBACK_FAIL) || (t == CALLBACK_ALWAYS) { if _, ok := callback.(func(v interface{})); !ok { panic(errors.New("Callback function spec must be func(v interface{})")) } } else if t == CALLBACK_CANCEL { if _, ok := callback.(func()); !ok { panic(errors.New("Callback function spec must be func()")) } } for { v := this.loadVal() r := v.r if r == nil { newVal := *v switch t { case CALLBACK_DONE: newVal.dones = append(newVal.dones, callback.(func(v interface{}))) case CALLBACK_FAIL: newVal.fails = append(newVal.fails, callback.(func(v interface{}))) case CALLBACK_ALWAYS: newVal.always = append(newVal.always, callback.(func(v interface{}))) case CALLBACK_CANCEL: newVal.cancels = append(newVal.cancels, callback.(func())) } //use CAS to ensure that the state of Future is not changed, //if the state is changed, will retry CAS operation. if atomic.CompareAndSwapPointer(&this.val, unsafe.Pointer(v), unsafe.Pointer(&newVal)) { break } } else { if (t == CALLBACK_DONE && r.Typ == RESULT_SUCCESS) || (t == CALLBACK_FAIL && r.Typ == RESULT_FAILURE) || (t == CALLBACK_ALWAYS && r.Typ != RESULT_CANCELLED) { callbackFunc := callback.(func(v interface{})) callbackFunc(r.Result) } else if t == CALLBACK_CANCEL && r.Typ == RESULT_CANCELLED { callbackFunc := callback.(func()) callbackFunc() } break } } }
[ "func", "(", "this", "*", "Future", ")", "addCallback", "(", "callback", "interface", "{", "}", ",", "t", "callbackType", ")", "{", "if", "callback", "==", "nil", "{", "return", "\n", "}", "\n", "if", "(", "t", "==", "CALLBACK_DONE", ")", "||", "(", "t", "==", "CALLBACK_FAIL", ")", "||", "(", "t", "==", "CALLBACK_ALWAYS", ")", "{", "if", "_", ",", "ok", ":=", "callback", ".", "(", "func", "(", "v", "interface", "{", "}", ")", ")", ";", "!", "ok", "{", "panic", "(", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "}", "else", "if", "t", "==", "CALLBACK_CANCEL", "{", "if", "_", ",", "ok", ":=", "callback", ".", "(", "func", "(", ")", ")", ";", "!", "ok", "{", "panic", "(", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "}", "\n\n", "for", "{", "v", ":=", "this", ".", "loadVal", "(", ")", "\n", "r", ":=", "v", ".", "r", "\n", "if", "r", "==", "nil", "{", "newVal", ":=", "*", "v", "\n", "switch", "t", "{", "case", "CALLBACK_DONE", ":", "newVal", ".", "dones", "=", "append", "(", "newVal", ".", "dones", ",", "callback", ".", "(", "func", "(", "v", "interface", "{", "}", ")", ")", ")", "\n", "case", "CALLBACK_FAIL", ":", "newVal", ".", "fails", "=", "append", "(", "newVal", ".", "fails", ",", "callback", ".", "(", "func", "(", "v", "interface", "{", "}", ")", ")", ")", "\n", "case", "CALLBACK_ALWAYS", ":", "newVal", ".", "always", "=", "append", "(", "newVal", ".", "always", ",", "callback", ".", "(", "func", "(", "v", "interface", "{", "}", ")", ")", ")", "\n", "case", "CALLBACK_CANCEL", ":", "newVal", ".", "cancels", "=", "append", "(", "newVal", ".", "cancels", ",", "callback", ".", "(", "func", "(", ")", ")", ")", "\n", "}", "\n\n", "//use CAS to ensure that the state of Future is not changed,", "//if the state is changed, will retry CAS operation.", "if", "atomic", ".", "CompareAndSwapPointer", "(", "&", "this", ".", "val", ",", "unsafe", ".", "Pointer", "(", "v", ")", ",", "unsafe", ".", "Pointer", "(", "&", "newVal", ")", ")", "{", "break", "\n", "}", "\n", "}", "else", "{", "if", "(", "t", "==", "CALLBACK_DONE", "&&", "r", ".", "Typ", "==", "RESULT_SUCCESS", ")", "||", "(", "t", "==", "CALLBACK_FAIL", "&&", "r", ".", "Typ", "==", "RESULT_FAILURE", ")", "||", "(", "t", "==", "CALLBACK_ALWAYS", "&&", "r", ".", "Typ", "!=", "RESULT_CANCELLED", ")", "{", "callbackFunc", ":=", "callback", ".", "(", "func", "(", "v", "interface", "{", "}", ")", ")", "\n", "callbackFunc", "(", "r", ".", "Result", ")", "\n", "}", "else", "if", "t", "==", "CALLBACK_CANCEL", "&&", "r", ".", "Typ", "==", "RESULT_CANCELLED", "{", "callbackFunc", ":=", "callback", ".", "(", "func", "(", ")", ")", "\n", "callbackFunc", "(", ")", "\n", "}", "\n", "break", "\n", "}", "\n", "}", "\n", "}" ]
//handleOneCallback registers a callback function
[ "handleOneCallback", "registers", "a", "callback", "function" ]
1890db352a72f9e6c6219c20111355cddc795297
https://github.com/fanliao/go-promise/blob/1890db352a72f9e6c6219c20111355cddc795297/future.go#L349-L399
12,852
fanliao/go-promise
promise.go
NewPromise
func NewPromise() *Promise { val := &futureVal{ make([]func(v interface{}), 0, 8), make([]func(v interface{}), 0, 8), make([]func(v interface{}), 0, 4), make([]func(), 0, 2), make([]*pipe, 0, 4), nil, } f := &Promise{ &Future{ rand.Int(), make(chan struct{}), unsafe.Pointer(val), }, } return f }
go
func NewPromise() *Promise { val := &futureVal{ make([]func(v interface{}), 0, 8), make([]func(v interface{}), 0, 8), make([]func(v interface{}), 0, 4), make([]func(), 0, 2), make([]*pipe, 0, 4), nil, } f := &Promise{ &Future{ rand.Int(), make(chan struct{}), unsafe.Pointer(val), }, } return f }
[ "func", "NewPromise", "(", ")", "*", "Promise", "{", "val", ":=", "&", "futureVal", "{", "make", "(", "[", "]", "func", "(", "v", "interface", "{", "}", ")", ",", "0", ",", "8", ")", ",", "make", "(", "[", "]", "func", "(", "v", "interface", "{", "}", ")", ",", "0", ",", "8", ")", ",", "make", "(", "[", "]", "func", "(", "v", "interface", "{", "}", ")", ",", "0", ",", "4", ")", ",", "make", "(", "[", "]", "func", "(", ")", ",", "0", ",", "2", ")", ",", "make", "(", "[", "]", "*", "pipe", ",", "0", ",", "4", ")", ",", "nil", ",", "}", "\n", "f", ":=", "&", "Promise", "{", "&", "Future", "{", "rand", ".", "Int", "(", ")", ",", "make", "(", "chan", "struct", "{", "}", ")", ",", "unsafe", ".", "Pointer", "(", "val", ")", ",", "}", ",", "}", "\n", "return", "f", "\n", "}" ]
//NewPromise is factory function for Promise
[ "NewPromise", "is", "factory", "function", "for", "Promise" ]
1890db352a72f9e6c6219c20111355cddc795297
https://github.com/fanliao/go-promise/blob/1890db352a72f9e6c6219c20111355cddc795297/promise.go#L100-L116
12,853
mesos/mesos-go
api/v1/lib/extras/executor/eventrules/handlers_generated.go
Handle
func (r Rule) Handle(h events.Handler) Rule { return Rules{r, Handle(h)}.Eval }
go
func (r Rule) Handle(h events.Handler) Rule { return Rules{r, Handle(h)}.Eval }
[ "func", "(", "r", "Rule", ")", "Handle", "(", "h", "events", ".", "Handler", ")", "Rule", "{", "return", "Rules", "{", "r", ",", "Handle", "(", "h", ")", "}", ".", "Eval", "\n", "}" ]
// Handle returns a Rule that invokes the receiver, then the given events.Handler
[ "Handle", "returns", "a", "Rule", "that", "invokes", "the", "receiver", "then", "the", "given", "events", ".", "Handler" ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/extras/executor/eventrules/handlers_generated.go#L30-L32
12,854
mesos/mesos-go
api/v1/lib/extras/executor/eventrules/handlers_generated.go
HandleF
func (r Rule) HandleF(h events.HandlerFunc) Rule { return r.Handle(events.Handler(h)) }
go
func (r Rule) HandleF(h events.HandlerFunc) Rule { return r.Handle(events.Handler(h)) }
[ "func", "(", "r", "Rule", ")", "HandleF", "(", "h", "events", ".", "HandlerFunc", ")", "Rule", "{", "return", "r", ".", "Handle", "(", "events", ".", "Handler", "(", "h", ")", ")", "\n", "}" ]
// HandleF is the functional equivalent of Handle
[ "HandleF", "is", "the", "functional", "equivalent", "of", "Handle" ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/extras/executor/eventrules/handlers_generated.go#L35-L37
12,855
mesos/mesos-go
api/v1/lib/extras/executor/eventrules/handlers_generated.go
HandleEvent
func (r Rule) HandleEvent(ctx context.Context, e *executor.Event) (err error) { if r == nil { return nil } _, _, err = r(ctx, e, nil, ChainIdentity) return }
go
func (r Rule) HandleEvent(ctx context.Context, e *executor.Event) (err error) { if r == nil { return nil } _, _, err = r(ctx, e, nil, ChainIdentity) return }
[ "func", "(", "r", "Rule", ")", "HandleEvent", "(", "ctx", "context", ".", "Context", ",", "e", "*", "executor", ".", "Event", ")", "(", "err", "error", ")", "{", "if", "r", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "_", ",", "_", ",", "err", "=", "r", "(", "ctx", ",", "e", ",", "nil", ",", "ChainIdentity", ")", "\n", "return", "\n", "}" ]
// HandleEvent implements events.Handler for Rule
[ "HandleEvent", "implements", "events", ".", "Handler", "for", "Rule" ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/extras/executor/eventrules/handlers_generated.go#L40-L46
12,856
mesos/mesos-go
api/v1/lib/extras/executor/eventrules/handlers_generated.go
HandleEvent
func (rs Rules) HandleEvent(ctx context.Context, e *executor.Event) error { return Rule(rs.Eval).HandleEvent(ctx, e) }
go
func (rs Rules) HandleEvent(ctx context.Context, e *executor.Event) error { return Rule(rs.Eval).HandleEvent(ctx, e) }
[ "func", "(", "rs", "Rules", ")", "HandleEvent", "(", "ctx", "context", ".", "Context", ",", "e", "*", "executor", ".", "Event", ")", "error", "{", "return", "Rule", "(", "rs", ".", "Eval", ")", ".", "HandleEvent", "(", "ctx", ",", "e", ")", "\n", "}" ]
// HandleEvent implements events.Handler for Rules
[ "HandleEvent", "implements", "events", ".", "Handler", "for", "Rules" ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/extras/executor/eventrules/handlers_generated.go#L49-L51
12,857
mesos/mesos-go
api/v1/lib/extras/executor/callrules/callrules_generated.go
Error
func (es ErrorList) Error() string { switch len(es) { case 0: return msgNoErrors case 1: return es[0].Error() default: return fmt.Sprintf("%s (and %d more errors)", es[0], len(es)-1) } }
go
func (es ErrorList) Error() string { switch len(es) { case 0: return msgNoErrors case 1: return es[0].Error() default: return fmt.Sprintf("%s (and %d more errors)", es[0], len(es)-1) } }
[ "func", "(", "es", "ErrorList", ")", "Error", "(", ")", "string", "{", "switch", "len", "(", "es", ")", "{", "case", "0", ":", "return", "msgNoErrors", "\n", "case", "1", ":", "return", "es", "[", "0", "]", ".", "Error", "(", ")", "\n", "default", ":", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "es", "[", "0", "]", ",", "len", "(", "es", ")", "-", "1", ")", "\n", "}", "\n", "}" ]
// Error implements error; returns the message of the first error in the list.
[ "Error", "implements", "error", ";", "returns", "the", "message", "of", "the", "first", "error", "in", "the", "list", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/extras/executor/callrules/callrules_generated.go#L84-L93
12,858
mesos/mesos-go
api/v1/lib/extras/executor/callrules/callrules_generated.go
Error2
func Error2(a, b error) error { if a == nil { if b == nil { return nil } if list, ok := b.(ErrorList); ok { return flatten(list).Err() } return b } if b == nil { if list, ok := a.(ErrorList); ok { return flatten(list).Err() } return a } return Error(a, b) }
go
func Error2(a, b error) error { if a == nil { if b == nil { return nil } if list, ok := b.(ErrorList); ok { return flatten(list).Err() } return b } if b == nil { if list, ok := a.(ErrorList); ok { return flatten(list).Err() } return a } return Error(a, b) }
[ "func", "Error2", "(", "a", ",", "b", "error", ")", "error", "{", "if", "a", "==", "nil", "{", "if", "b", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "list", ",", "ok", ":=", "b", ".", "(", "ErrorList", ")", ";", "ok", "{", "return", "flatten", "(", "list", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "b", "\n", "}", "\n", "if", "b", "==", "nil", "{", "if", "list", ",", "ok", ":=", "a", ".", "(", "ErrorList", ")", ";", "ok", "{", "return", "flatten", "(", "list", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "a", "\n", "}", "\n", "return", "Error", "(", "a", ",", "b", ")", "\n", "}" ]
// Error2 aggregates the given error params, returning nil if both are nil. // Use Error2 to avoid the overhead of creating a slice when aggregating only 2 errors.
[ "Error2", "aggregates", "the", "given", "error", "params", "returning", "nil", "if", "both", "are", "nil", ".", "Use", "Error2", "to", "avoid", "the", "overhead", "of", "creating", "a", "slice", "when", "aggregating", "only", "2", "errors", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/extras/executor/callrules/callrules_generated.go#L97-L114
12,859
mesos/mesos-go
api/v1/lib/extras/executor/callrules/callrules_generated.go
IsErrorList
func IsErrorList(err error) bool { if err != nil { _, ok := err.(ErrorList) return ok } return false }
go
func IsErrorList(err error) bool { if err != nil { _, ok := err.(ErrorList) return ok } return false }
[ "func", "IsErrorList", "(", "err", "error", ")", "bool", "{", "if", "err", "!=", "nil", "{", "_", ",", "ok", ":=", "err", ".", "(", "ErrorList", ")", "\n", "return", "ok", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsErrorList returns true if err is a non-nil error list
[ "IsErrorList", "returns", "true", "if", "err", "is", "a", "non", "-", "nil", "error", "list" ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/extras/executor/callrules/callrules_generated.go#L129-L135
12,860
mesos/mesos-go
api/v0/detector/zoo/detect.go
MinCyclePeriod
func MinCyclePeriod(d time.Duration) detector.Option { return func(di interface{}) detector.Option { md := di.(*MasterDetector) old := md.minDetectorCyclePeriod md.minDetectorCyclePeriod = d return MinCyclePeriod(old) } }
go
func MinCyclePeriod(d time.Duration) detector.Option { return func(di interface{}) detector.Option { md := di.(*MasterDetector) old := md.minDetectorCyclePeriod md.minDetectorCyclePeriod = d return MinCyclePeriod(old) } }
[ "func", "MinCyclePeriod", "(", "d", "time", ".", "Duration", ")", "detector", ".", "Option", "{", "return", "func", "(", "di", "interface", "{", "}", ")", "detector", ".", "Option", "{", "md", ":=", "di", ".", "(", "*", "MasterDetector", ")", "\n", "old", ":=", "md", ".", "minDetectorCyclePeriod", "\n", "md", ".", "minDetectorCyclePeriod", "=", "d", "\n", "return", "MinCyclePeriod", "(", "old", ")", "\n", "}", "\n", "}" ]
// MinCyclePeriod is a functional option that determines the highest frequency of master change notifications
[ "MinCyclePeriod", "is", "a", "functional", "option", "that", "determines", "the", "highest", "frequency", "of", "master", "change", "notifications" ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v0/detector/zoo/detect.go#L76-L83
12,861
mesos/mesos-go
api/v0/detector/zoo/detect.go
NewMasterDetector
func NewMasterDetector(zkurls string, options ...detector.Option) (*MasterDetector, error) { zkHosts, zkPath, err := parseZk(zkurls) if err != nil { log.Fatalln("Failed to parse url", err) return nil, err } detector := &MasterDetector{ minDetectorCyclePeriod: defaultMinDetectorCyclePeriod, done: make(chan struct{}), cancel: func() {}, } detector.bootstrapFunc = func(client ZKInterface, _ <-chan struct{}) (ZKInterface, error) { if client == nil { return connect2(zkHosts, zkPath) } return client, nil } // apply options last so that they can override default behavior for _, opt := range options { opt(detector) } log.V(2).Infoln("Created new detector to watch", zkHosts, zkPath) return detector, nil }
go
func NewMasterDetector(zkurls string, options ...detector.Option) (*MasterDetector, error) { zkHosts, zkPath, err := parseZk(zkurls) if err != nil { log.Fatalln("Failed to parse url", err) return nil, err } detector := &MasterDetector{ minDetectorCyclePeriod: defaultMinDetectorCyclePeriod, done: make(chan struct{}), cancel: func() {}, } detector.bootstrapFunc = func(client ZKInterface, _ <-chan struct{}) (ZKInterface, error) { if client == nil { return connect2(zkHosts, zkPath) } return client, nil } // apply options last so that they can override default behavior for _, opt := range options { opt(detector) } log.V(2).Infoln("Created new detector to watch", zkHosts, zkPath) return detector, nil }
[ "func", "NewMasterDetector", "(", "zkurls", "string", ",", "options", "...", "detector", ".", "Option", ")", "(", "*", "MasterDetector", ",", "error", ")", "{", "zkHosts", ",", "zkPath", ",", "err", ":=", "parseZk", "(", "zkurls", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalln", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "detector", ":=", "&", "MasterDetector", "{", "minDetectorCyclePeriod", ":", "defaultMinDetectorCyclePeriod", ",", "done", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "cancel", ":", "func", "(", ")", "{", "}", ",", "}", "\n\n", "detector", ".", "bootstrapFunc", "=", "func", "(", "client", "ZKInterface", ",", "_", "<-", "chan", "struct", "{", "}", ")", "(", "ZKInterface", ",", "error", ")", "{", "if", "client", "==", "nil", "{", "return", "connect2", "(", "zkHosts", ",", "zkPath", ")", "\n", "}", "\n", "return", "client", ",", "nil", "\n", "}", "\n\n", "// apply options last so that they can override default behavior", "for", "_", ",", "opt", ":=", "range", "options", "{", "opt", "(", "detector", ")", "\n", "}", "\n\n", "log", ".", "V", "(", "2", ")", ".", "Infoln", "(", "\"", "\"", ",", "zkHosts", ",", "zkPath", ")", "\n", "return", "detector", ",", "nil", "\n", "}" ]
// Internal constructor function
[ "Internal", "constructor", "function" ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v0/detector/zoo/detect.go#L95-L122
12,862
mesos/mesos-go
api/v0/detector/zoo/detect.go
logPanic
func logPanic(f func()) { defer func() { if r := recover(); r != nil { log.Errorf("recovered from client panic: %v", r) } }() f() }
go
func logPanic(f func()) { defer func() { if r := recover(); r != nil { log.Errorf("recovered from client panic: %v", r) } }() f() }
[ "func", "logPanic", "(", "f", "func", "(", ")", ")", "{", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "r", ")", "\n", "}", "\n", "}", "(", ")", "\n", "f", "(", ")", "\n", "}" ]
// logPanic safely executes the given func, recovering from and logging a panic if one occurs.
[ "logPanic", "safely", "executes", "the", "given", "func", "recovering", "from", "and", "logging", "a", "panic", "if", "one", "occurs", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v0/detector/zoo/detect.go#L175-L182
12,863
mesos/mesos-go
api/v0/detector/zoo/detect.go
Detect
func (md *MasterDetector) Detect(f detector.MasterChanged) (err error) { // kickstart zk client connectivity if err := md.callBootstrap(); err != nil { log.V(3).Infoln("failed to execute bootstrap function", err.Error()) return err } if f == nil { // only ever install, at most, one ignoreChanged listener. multiple instances of it // just consume resources and generate misleading log messages. if !atomic.CompareAndSwapInt32(&md.ignoreInstalled, 0, 1) { log.V(3).Infoln("ignoreChanged listener already installed") return } f = ignoreChanged } log.V(3).Infoln("spawning detect()") go md.detect(f) return nil }
go
func (md *MasterDetector) Detect(f detector.MasterChanged) (err error) { // kickstart zk client connectivity if err := md.callBootstrap(); err != nil { log.V(3).Infoln("failed to execute bootstrap function", err.Error()) return err } if f == nil { // only ever install, at most, one ignoreChanged listener. multiple instances of it // just consume resources and generate misleading log messages. if !atomic.CompareAndSwapInt32(&md.ignoreInstalled, 0, 1) { log.V(3).Infoln("ignoreChanged listener already installed") return } f = ignoreChanged } log.V(3).Infoln("spawning detect()") go md.detect(f) return nil }
[ "func", "(", "md", "*", "MasterDetector", ")", "Detect", "(", "f", "detector", ".", "MasterChanged", ")", "(", "err", "error", ")", "{", "// kickstart zk client connectivity", "if", "err", ":=", "md", ".", "callBootstrap", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "V", "(", "3", ")", ".", "Infoln", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "err", "\n", "}", "\n\n", "if", "f", "==", "nil", "{", "// only ever install, at most, one ignoreChanged listener. multiple instances of it", "// just consume resources and generate misleading log messages.", "if", "!", "atomic", ".", "CompareAndSwapInt32", "(", "&", "md", ".", "ignoreInstalled", ",", "0", ",", "1", ")", "{", "log", ".", "V", "(", "3", ")", ".", "Infoln", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "f", "=", "ignoreChanged", "\n", "}", "\n\n", "log", ".", "V", "(", "3", ")", ".", "Infoln", "(", "\"", "\"", ")", "\n", "go", "md", ".", "detect", "(", "f", ")", "\n", "return", "nil", "\n", "}" ]
// the first call to Detect will kickstart a connection to zookeeper. a nil change listener may // be spec'd, result of which is a detector that will still listen for master changes and record // leaderhip changes internally but no listener would be notified. Detect may be called more than // once, and each time the spec'd listener will be added to the list of those receiving notifications.
[ "the", "first", "call", "to", "Detect", "will", "kickstart", "a", "connection", "to", "zookeeper", ".", "a", "nil", "change", "listener", "may", "be", "spec", "d", "result", "of", "which", "is", "a", "detector", "that", "will", "still", "listen", "for", "master", "changes", "and", "record", "leaderhip", "changes", "internally", "but", "no", "listener", "would", "be", "notified", ".", "Detect", "may", "be", "called", "more", "than", "once", "and", "each", "time", "the", "spec", "d", "listener", "will", "be", "added", "to", "the", "list", "of", "those", "receiving", "notifications", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v0/detector/zoo/detect.go#L272-L292
12,864
mesos/mesos-go
api/v1/cmd/example-scheduler/app/app.go
buildEventHandler
func buildEventHandler(state *internalState, fidStore store.Singleton) events.Handler { // disable brief logs when verbose logs are enabled (there's no sense logging twice!) logger := controller.LogEvents(nil).Unless(state.config.verbose) return eventrules.New( logAllEvents().If(state.config.verbose), eventMetrics(state.metricsAPI, time.Now, state.config.summaryMetrics), controller.LiftErrors().DropOnError(), ).Handle(events.Handlers{ scheduler.Event_FAILURE: logger.HandleF(failure), scheduler.Event_OFFERS: trackOffersReceived(state).HandleF(resourceOffers(state)), scheduler.Event_UPDATE: controller.AckStatusUpdates(state.cli).AndThen().HandleF(statusUpdate(state)), scheduler.Event_SUBSCRIBED: eventrules.New( logger, controller.TrackSubscription(fidStore, state.config.failoverTimeout), ), }.Otherwise(logger.HandleEvent)) }
go
func buildEventHandler(state *internalState, fidStore store.Singleton) events.Handler { // disable brief logs when verbose logs are enabled (there's no sense logging twice!) logger := controller.LogEvents(nil).Unless(state.config.verbose) return eventrules.New( logAllEvents().If(state.config.verbose), eventMetrics(state.metricsAPI, time.Now, state.config.summaryMetrics), controller.LiftErrors().DropOnError(), ).Handle(events.Handlers{ scheduler.Event_FAILURE: logger.HandleF(failure), scheduler.Event_OFFERS: trackOffersReceived(state).HandleF(resourceOffers(state)), scheduler.Event_UPDATE: controller.AckStatusUpdates(state.cli).AndThen().HandleF(statusUpdate(state)), scheduler.Event_SUBSCRIBED: eventrules.New( logger, controller.TrackSubscription(fidStore, state.config.failoverTimeout), ), }.Otherwise(logger.HandleEvent)) }
[ "func", "buildEventHandler", "(", "state", "*", "internalState", ",", "fidStore", "store", ".", "Singleton", ")", "events", ".", "Handler", "{", "// disable brief logs when verbose logs are enabled (there's no sense logging twice!)", "logger", ":=", "controller", ".", "LogEvents", "(", "nil", ")", ".", "Unless", "(", "state", ".", "config", ".", "verbose", ")", "\n", "return", "eventrules", ".", "New", "(", "logAllEvents", "(", ")", ".", "If", "(", "state", ".", "config", ".", "verbose", ")", ",", "eventMetrics", "(", "state", ".", "metricsAPI", ",", "time", ".", "Now", ",", "state", ".", "config", ".", "summaryMetrics", ")", ",", "controller", ".", "LiftErrors", "(", ")", ".", "DropOnError", "(", ")", ",", ")", ".", "Handle", "(", "events", ".", "Handlers", "{", "scheduler", ".", "Event_FAILURE", ":", "logger", ".", "HandleF", "(", "failure", ")", ",", "scheduler", ".", "Event_OFFERS", ":", "trackOffersReceived", "(", "state", ")", ".", "HandleF", "(", "resourceOffers", "(", "state", ")", ")", ",", "scheduler", ".", "Event_UPDATE", ":", "controller", ".", "AckStatusUpdates", "(", "state", ".", "cli", ")", ".", "AndThen", "(", ")", ".", "HandleF", "(", "statusUpdate", "(", "state", ")", ")", ",", "scheduler", ".", "Event_SUBSCRIBED", ":", "eventrules", ".", "New", "(", "logger", ",", "controller", ".", "TrackSubscription", "(", "fidStore", ",", "state", ".", "config", ".", "failoverTimeout", ")", ",", ")", ",", "}", ".", "Otherwise", "(", "logger", ".", "HandleEvent", ")", ")", "\n", "}" ]
// buildEventHandler generates and returns a handler to process events received from the subscription.
[ "buildEventHandler", "generates", "and", "returns", "a", "handler", "to", "process", "events", "received", "from", "the", "subscription", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/cmd/example-scheduler/app/app.go#L90-L106
12,865
mesos/mesos-go
api/v1/cmd/example-scheduler/app/app.go
logAllEvents
func logAllEvents() eventrules.Rule { return func(ctx context.Context, e *scheduler.Event, err error, ch eventrules.Chain) (context.Context, *scheduler.Event, error) { log.Printf("%+v\n", *e) return ch(ctx, e, err) } }
go
func logAllEvents() eventrules.Rule { return func(ctx context.Context, e *scheduler.Event, err error, ch eventrules.Chain) (context.Context, *scheduler.Event, error) { log.Printf("%+v\n", *e) return ch(ctx, e, err) } }
[ "func", "logAllEvents", "(", ")", "eventrules", ".", "Rule", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "e", "*", "scheduler", ".", "Event", ",", "err", "error", ",", "ch", "eventrules", ".", "Chain", ")", "(", "context", ".", "Context", ",", "*", "scheduler", ".", "Event", ",", "error", ")", "{", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "*", "e", ")", "\n", "return", "ch", "(", "ctx", ",", "e", ",", "err", ")", "\n", "}", "\n", "}" ]
// logAllEvents logs every observed event; this is somewhat expensive to do
[ "logAllEvents", "logs", "every", "observed", "event", ";", "this", "is", "somewhat", "expensive", "to", "do" ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/cmd/example-scheduler/app/app.go#L292-L297
12,866
mesos/mesos-go
api/v1/cmd/example-scheduler/app/app.go
eventMetrics
func eventMetrics(metricsAPI *metricsAPI, clock func() time.Time, timingMetrics bool) eventrules.Rule { timed := metricsAPI.eventReceivedLatency if !timingMetrics { timed = nil } harness := xmetrics.NewHarness(metricsAPI.eventReceivedCount, metricsAPI.eventErrorCount, timed, clock) return eventrules.Metrics(harness, nil) }
go
func eventMetrics(metricsAPI *metricsAPI, clock func() time.Time, timingMetrics bool) eventrules.Rule { timed := metricsAPI.eventReceivedLatency if !timingMetrics { timed = nil } harness := xmetrics.NewHarness(metricsAPI.eventReceivedCount, metricsAPI.eventErrorCount, timed, clock) return eventrules.Metrics(harness, nil) }
[ "func", "eventMetrics", "(", "metricsAPI", "*", "metricsAPI", ",", "clock", "func", "(", ")", "time", ".", "Time", ",", "timingMetrics", "bool", ")", "eventrules", ".", "Rule", "{", "timed", ":=", "metricsAPI", ".", "eventReceivedLatency", "\n", "if", "!", "timingMetrics", "{", "timed", "=", "nil", "\n", "}", "\n", "harness", ":=", "xmetrics", ".", "NewHarness", "(", "metricsAPI", ".", "eventReceivedCount", ",", "metricsAPI", ".", "eventErrorCount", ",", "timed", ",", "clock", ")", "\n", "return", "eventrules", ".", "Metrics", "(", "harness", ",", "nil", ")", "\n", "}" ]
// eventMetrics logs metrics for every processed API event
[ "eventMetrics", "logs", "metrics", "for", "every", "processed", "API", "event" ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/cmd/example-scheduler/app/app.go#L300-L307
12,867
mesos/mesos-go
api/v1/cmd/example-scheduler/app/app.go
callMetrics
func callMetrics(metricsAPI *metricsAPI, clock func() time.Time, timingMetrics bool) callrules.Rule { timed := metricsAPI.callLatency if !timingMetrics { timed = nil } harness := xmetrics.NewHarness(metricsAPI.callCount, metricsAPI.callErrorCount, timed, clock) return callrules.Metrics(harness, nil) }
go
func callMetrics(metricsAPI *metricsAPI, clock func() time.Time, timingMetrics bool) callrules.Rule { timed := metricsAPI.callLatency if !timingMetrics { timed = nil } harness := xmetrics.NewHarness(metricsAPI.callCount, metricsAPI.callErrorCount, timed, clock) return callrules.Metrics(harness, nil) }
[ "func", "callMetrics", "(", "metricsAPI", "*", "metricsAPI", ",", "clock", "func", "(", ")", "time", ".", "Time", ",", "timingMetrics", "bool", ")", "callrules", ".", "Rule", "{", "timed", ":=", "metricsAPI", ".", "callLatency", "\n", "if", "!", "timingMetrics", "{", "timed", "=", "nil", "\n", "}", "\n", "harness", ":=", "xmetrics", ".", "NewHarness", "(", "metricsAPI", ".", "callCount", ",", "metricsAPI", ".", "callErrorCount", ",", "timed", ",", "clock", ")", "\n", "return", "callrules", ".", "Metrics", "(", "harness", ",", "nil", ")", "\n", "}" ]
// callMetrics logs metrics for every outgoing Mesos call
[ "callMetrics", "logs", "metrics", "for", "every", "outgoing", "Mesos", "call" ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/cmd/example-scheduler/app/app.go#L310-L317
12,868
mesos/mesos-go
api/v1/cmd/example-scheduler/app/app.go
logCalls
func logCalls(messages map[scheduler.Call_Type]string) callrules.Rule { return func(ctx context.Context, c *scheduler.Call, r mesos.Response, err error, ch callrules.Chain) (context.Context, *scheduler.Call, mesos.Response, error) { if message, ok := messages[c.GetType()]; ok { log.Println(message) } return ch(ctx, c, r, err) } }
go
func logCalls(messages map[scheduler.Call_Type]string) callrules.Rule { return func(ctx context.Context, c *scheduler.Call, r mesos.Response, err error, ch callrules.Chain) (context.Context, *scheduler.Call, mesos.Response, error) { if message, ok := messages[c.GetType()]; ok { log.Println(message) } return ch(ctx, c, r, err) } }
[ "func", "logCalls", "(", "messages", "map", "[", "scheduler", ".", "Call_Type", "]", "string", ")", "callrules", ".", "Rule", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "c", "*", "scheduler", ".", "Call", ",", "r", "mesos", ".", "Response", ",", "err", "error", ",", "ch", "callrules", ".", "Chain", ")", "(", "context", ".", "Context", ",", "*", "scheduler", ".", "Call", ",", "mesos", ".", "Response", ",", "error", ")", "{", "if", "message", ",", "ok", ":=", "messages", "[", "c", ".", "GetType", "(", ")", "]", ";", "ok", "{", "log", ".", "Println", "(", "message", ")", "\n", "}", "\n", "return", "ch", "(", "ctx", ",", "c", ",", "r", ",", "err", ")", "\n", "}", "\n", "}" ]
// logCalls logs a specific message string when a particular call-type is observed
[ "logCalls", "logs", "a", "specific", "message", "string", "when", "a", "particular", "call", "-", "type", "is", "observed" ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/cmd/example-scheduler/app/app.go#L320-L327
12,869
mesos/mesos-go
api/v0/auth/sasl/authenticatee.go
makeAuthenticatee
func makeAuthenticatee(handler callback.Handler, factory transportFactory) (auth.Authenticatee, error) { ip := callback.NewInterprocess() if err := handler.Handle(ip); err != nil { return nil, err } config := &authenticateeConfig{ client: ip.Client(), handler: handler, transport: factory.makeTransport(), } return auth.AuthenticateeFunc(func(ctx context.Context, handler callback.Handler) error { ctx, auth := newAuthenticatee(ctx, config) auth.authenticate(ctx, ip.Server()) select { case <-ctx.Done(): return auth.discard(ctx) case <-auth.done: return auth.err } }), nil }
go
func makeAuthenticatee(handler callback.Handler, factory transportFactory) (auth.Authenticatee, error) { ip := callback.NewInterprocess() if err := handler.Handle(ip); err != nil { return nil, err } config := &authenticateeConfig{ client: ip.Client(), handler: handler, transport: factory.makeTransport(), } return auth.AuthenticateeFunc(func(ctx context.Context, handler callback.Handler) error { ctx, auth := newAuthenticatee(ctx, config) auth.authenticate(ctx, ip.Server()) select { case <-ctx.Done(): return auth.discard(ctx) case <-auth.done: return auth.err } }), nil }
[ "func", "makeAuthenticatee", "(", "handler", "callback", ".", "Handler", ",", "factory", "transportFactory", ")", "(", "auth", ".", "Authenticatee", ",", "error", ")", "{", "ip", ":=", "callback", ".", "NewInterprocess", "(", ")", "\n", "if", "err", ":=", "handler", ".", "Handle", "(", "ip", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "config", ":=", "&", "authenticateeConfig", "{", "client", ":", "ip", ".", "Client", "(", ")", ",", "handler", ":", "handler", ",", "transport", ":", "factory", ".", "makeTransport", "(", ")", ",", "}", "\n", "return", "auth", ".", "AuthenticateeFunc", "(", "func", "(", "ctx", "context", ".", "Context", ",", "handler", "callback", ".", "Handler", ")", "error", "{", "ctx", ",", "auth", ":=", "newAuthenticatee", "(", "ctx", ",", "config", ")", "\n", "auth", ".", "authenticate", "(", "ctx", ",", "ip", ".", "Server", "(", ")", ")", "\n\n", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "auth", ".", "discard", "(", "ctx", ")", "\n", "case", "<-", "auth", ".", "done", ":", "return", "auth", ".", "err", "\n", "}", "\n", "}", ")", ",", "nil", "\n", "}" ]
// build a new authenticatee implementation using the given callbacks and a new transport instance
[ "build", "a", "new", "authenticatee", "implementation", "using", "the", "given", "callbacks", "and", "a", "new", "transport", "instance" ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v0/auth/sasl/authenticatee.go#L111-L133
12,870
mesos/mesos-go
api/v0/auth/sasl/authenticatee.go
installHandlers
func (self *authenticateeProcess) installHandlers(ctx context.Context) error { type handlerFn func(ctx context.Context, from *upid.UPID, pbMsg proto.Message) withContext := func(f handlerFn) messenger.MessageHandler { return func(from *upid.UPID, m proto.Message) { status := (&self.status).get() if self.from != nil && !self.from.Equal(from) { self.terminate(status, statusError, UnexpectedAuthenticatorPid) } else { f(withStatus(ctx, status), from, m) } } } // Anticipate mechanisms and steps from the server handlers := []struct { f handlerFn m proto.Message }{ {self.mechanisms, &mesos.AuthenticationMechanismsMessage{}}, {self.step, &mesos.AuthenticationStepMessage{}}, {self.completed, &mesos.AuthenticationCompletedMessage{}}, {self.failed, &mesos.AuthenticationFailedMessage{}}, {self.errored, &mesos.AuthenticationErrorMessage{}}, } for _, h := range handlers { if err := self.transport.Install(withContext(h.f), h.m); err != nil { return err } } return nil }
go
func (self *authenticateeProcess) installHandlers(ctx context.Context) error { type handlerFn func(ctx context.Context, from *upid.UPID, pbMsg proto.Message) withContext := func(f handlerFn) messenger.MessageHandler { return func(from *upid.UPID, m proto.Message) { status := (&self.status).get() if self.from != nil && !self.from.Equal(from) { self.terminate(status, statusError, UnexpectedAuthenticatorPid) } else { f(withStatus(ctx, status), from, m) } } } // Anticipate mechanisms and steps from the server handlers := []struct { f handlerFn m proto.Message }{ {self.mechanisms, &mesos.AuthenticationMechanismsMessage{}}, {self.step, &mesos.AuthenticationStepMessage{}}, {self.completed, &mesos.AuthenticationCompletedMessage{}}, {self.failed, &mesos.AuthenticationFailedMessage{}}, {self.errored, &mesos.AuthenticationErrorMessage{}}, } for _, h := range handlers { if err := self.transport.Install(withContext(h.f), h.m); err != nil { return err } } return nil }
[ "func", "(", "self", "*", "authenticateeProcess", ")", "installHandlers", "(", "ctx", "context", ".", "Context", ")", "error", "{", "type", "handlerFn", "func", "(", "ctx", "context", ".", "Context", ",", "from", "*", "upid", ".", "UPID", ",", "pbMsg", "proto", ".", "Message", ")", "\n\n", "withContext", ":=", "func", "(", "f", "handlerFn", ")", "messenger", ".", "MessageHandler", "{", "return", "func", "(", "from", "*", "upid", ".", "UPID", ",", "m", "proto", ".", "Message", ")", "{", "status", ":=", "(", "&", "self", ".", "status", ")", ".", "get", "(", ")", "\n", "if", "self", ".", "from", "!=", "nil", "&&", "!", "self", ".", "from", ".", "Equal", "(", "from", ")", "{", "self", ".", "terminate", "(", "status", ",", "statusError", ",", "UnexpectedAuthenticatorPid", ")", "\n", "}", "else", "{", "f", "(", "withStatus", "(", "ctx", ",", "status", ")", ",", "from", ",", "m", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Anticipate mechanisms and steps from the server", "handlers", ":=", "[", "]", "struct", "{", "f", "handlerFn", "\n", "m", "proto", ".", "Message", "\n", "}", "{", "{", "self", ".", "mechanisms", ",", "&", "mesos", ".", "AuthenticationMechanismsMessage", "{", "}", "}", ",", "{", "self", ".", "step", ",", "&", "mesos", ".", "AuthenticationStepMessage", "{", "}", "}", ",", "{", "self", ".", "completed", ",", "&", "mesos", ".", "AuthenticationCompletedMessage", "{", "}", "}", ",", "{", "self", ".", "failed", ",", "&", "mesos", ".", "AuthenticationFailedMessage", "{", "}", "}", ",", "{", "self", ".", "errored", ",", "&", "mesos", ".", "AuthenticationErrorMessage", "{", "}", "}", ",", "}", "\n", "for", "_", ",", "h", ":=", "range", "handlers", "{", "if", "err", ":=", "self", ".", "transport", ".", "Install", "(", "withContext", "(", "h", ".", "f", ")", ",", "h", ".", "m", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// returns true when handlers are installed without error, otherwise terminates the // authentication process.
[ "returns", "true", "when", "handlers", "are", "installed", "without", "error", "otherwise", "terminates", "the", "authentication", "process", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v0/auth/sasl/authenticatee.go#L187-L219
12,871
mesos/mesos-go
api/v0/messenger/messenger.go
UPIDBindingAddress
func UPIDBindingAddress(hostname string, bindingAddress net.IP) (string, error) { upidHost := "" if bindingAddress != nil && "0.0.0.0" != bindingAddress.String() { upidHost = bindingAddress.String() } else { if hostname == "" || hostname == "0.0.0.0" { return "", fmt.Errorf("invalid hostname (%q) specified with binding address %v", hostname, bindingAddress) } ip := net.ParseIP(hostname) if ip != nil { ip = ip.To4() } if ip == nil { ips, err := net.LookupIP(hostname) if err != nil { return "", err } // try to find an ipv4 and use that for _, addr := range ips { if ip = addr.To4(); ip != nil { break } } if ip == nil { // no ipv4? best guess, just take the first addr if len(ips) > 0 { ip = ips[0] log.Warningf("failed to find an IPv4 address for '%v', best guess is '%v'", hostname, ip) } else { return "", fmt.Errorf("failed to determine IP address for host '%v'", hostname) } } } upidHost = ip.String() } return upidHost, nil }
go
func UPIDBindingAddress(hostname string, bindingAddress net.IP) (string, error) { upidHost := "" if bindingAddress != nil && "0.0.0.0" != bindingAddress.String() { upidHost = bindingAddress.String() } else { if hostname == "" || hostname == "0.0.0.0" { return "", fmt.Errorf("invalid hostname (%q) specified with binding address %v", hostname, bindingAddress) } ip := net.ParseIP(hostname) if ip != nil { ip = ip.To4() } if ip == nil { ips, err := net.LookupIP(hostname) if err != nil { return "", err } // try to find an ipv4 and use that for _, addr := range ips { if ip = addr.To4(); ip != nil { break } } if ip == nil { // no ipv4? best guess, just take the first addr if len(ips) > 0 { ip = ips[0] log.Warningf("failed to find an IPv4 address for '%v', best guess is '%v'", hostname, ip) } else { return "", fmt.Errorf("failed to determine IP address for host '%v'", hostname) } } } upidHost = ip.String() } return upidHost, nil }
[ "func", "UPIDBindingAddress", "(", "hostname", "string", ",", "bindingAddress", "net", ".", "IP", ")", "(", "string", ",", "error", ")", "{", "upidHost", ":=", "\"", "\"", "\n", "if", "bindingAddress", "!=", "nil", "&&", "\"", "\"", "!=", "bindingAddress", ".", "String", "(", ")", "{", "upidHost", "=", "bindingAddress", ".", "String", "(", ")", "\n", "}", "else", "{", "if", "hostname", "==", "\"", "\"", "||", "hostname", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hostname", ",", "bindingAddress", ")", "\n", "}", "\n", "ip", ":=", "net", ".", "ParseIP", "(", "hostname", ")", "\n", "if", "ip", "!=", "nil", "{", "ip", "=", "ip", ".", "To4", "(", ")", "\n", "}", "\n", "if", "ip", "==", "nil", "{", "ips", ",", "err", ":=", "net", ".", "LookupIP", "(", "hostname", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "// try to find an ipv4 and use that", "for", "_", ",", "addr", ":=", "range", "ips", "{", "if", "ip", "=", "addr", ".", "To4", "(", ")", ";", "ip", "!=", "nil", "{", "break", "\n", "}", "\n", "}", "\n", "if", "ip", "==", "nil", "{", "// no ipv4? best guess, just take the first addr", "if", "len", "(", "ips", ")", ">", "0", "{", "ip", "=", "ips", "[", "0", "]", "\n", "log", ".", "Warningf", "(", "\"", "\"", ",", "hostname", ",", "ip", ")", "\n", "}", "else", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hostname", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "upidHost", "=", "ip", ".", "String", "(", ")", "\n", "}", "\n", "return", "upidHost", ",", "nil", "\n", "}" ]
// UPIDBindingAddress determines the value of UPID.Host that will be used to build // a Transport. If a non-nil, non-wildcard bindingAddress is specified then it will be used // for both the UPID and Transport binding address. Otherwise hostname is resolved to an IP // address and the UPID.Host is set to that address and the bindingAddress is passed through // to the Transport.
[ "UPIDBindingAddress", "determines", "the", "value", "of", "UPID", ".", "Host", "that", "will", "be", "used", "to", "build", "a", "Transport", ".", "If", "a", "non", "-", "nil", "non", "-", "wildcard", "bindingAddress", "is", "specified", "then", "it", "will", "be", "used", "for", "both", "the", "UPID", "and", "Transport", "binding", "address", ".", "Otherwise", "hostname", "is", "resolved", "to", "an", "IP", "address", "and", "the", "UPID", ".", "Host", "is", "set", "to", "that", "address", "and", "the", "bindingAddress", "is", "passed", "through", "to", "the", "Transport", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v0/messenger/messenger.go#L105-L141
12,872
mesos/mesos-go
api/v0/messenger/messenger.go
NewHttp
func NewHttp(upid upid.UPID, opts ...httpOpt) *MesosMessenger { return NewHttpWithBindingAddress(upid, nil, opts...) }
go
func NewHttp(upid upid.UPID, opts ...httpOpt) *MesosMessenger { return NewHttpWithBindingAddress(upid, nil, opts...) }
[ "func", "NewHttp", "(", "upid", "upid", ".", "UPID", ",", "opts", "...", "httpOpt", ")", "*", "MesosMessenger", "{", "return", "NewHttpWithBindingAddress", "(", "upid", ",", "nil", ",", "opts", "...", ")", "\n", "}" ]
// NewMesosMessenger creates a new mesos messenger.
[ "NewMesosMessenger", "creates", "a", "new", "mesos", "messenger", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v0/messenger/messenger.go#L144-L146
12,873
mesos/mesos-go
api/v0/messenger/messenger.go
Send
func (m *MesosMessenger) Send(ctx context.Context, upid *upid.UPID, msg proto.Message) error { if upid == nil { panic("cannot sent a message to a nil pid") } else if *upid == m.upid { return fmt.Errorf("Send the message to self") } b, err := proto.Marshal(msg) if err != nil { return err } name := getMessageName(msg) log.V(2).Infof("Sending message %v to %v\n", name, upid) wrapped := &Message{upid, name, msg, b} d := dispatchFunc(func(rf errorHandlerFunc) { err := m.tr.Send(ctx, wrapped) err = rf(ctx, wrapped, err) if err != nil { m.reportError("send", wrapped, err) } }) select { case <-ctx.Done(): return ctx.Err() case m.sendingQueue <- d: return nil } }
go
func (m *MesosMessenger) Send(ctx context.Context, upid *upid.UPID, msg proto.Message) error { if upid == nil { panic("cannot sent a message to a nil pid") } else if *upid == m.upid { return fmt.Errorf("Send the message to self") } b, err := proto.Marshal(msg) if err != nil { return err } name := getMessageName(msg) log.V(2).Infof("Sending message %v to %v\n", name, upid) wrapped := &Message{upid, name, msg, b} d := dispatchFunc(func(rf errorHandlerFunc) { err := m.tr.Send(ctx, wrapped) err = rf(ctx, wrapped, err) if err != nil { m.reportError("send", wrapped, err) } }) select { case <-ctx.Done(): return ctx.Err() case m.sendingQueue <- d: return nil } }
[ "func", "(", "m", "*", "MesosMessenger", ")", "Send", "(", "ctx", "context", ".", "Context", ",", "upid", "*", "upid", ".", "UPID", ",", "msg", "proto", ".", "Message", ")", "error", "{", "if", "upid", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "else", "if", "*", "upid", "==", "m", ".", "upid", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "b", ",", "err", ":=", "proto", ".", "Marshal", "(", "msg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "name", ":=", "getMessageName", "(", "msg", ")", "\n", "log", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"", "\\n", "\"", ",", "name", ",", "upid", ")", "\n\n", "wrapped", ":=", "&", "Message", "{", "upid", ",", "name", ",", "msg", ",", "b", "}", "\n", "d", ":=", "dispatchFunc", "(", "func", "(", "rf", "errorHandlerFunc", ")", "{", "err", ":=", "m", ".", "tr", ".", "Send", "(", "ctx", ",", "wrapped", ")", "\n", "err", "=", "rf", "(", "ctx", ",", "wrapped", ",", "err", ")", "\n", "if", "err", "!=", "nil", "{", "m", ".", "reportError", "(", "\"", "\"", ",", "wrapped", ",", "err", ")", "\n", "}", "\n", "}", ")", "\n", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "case", "m", ".", "sendingQueue", "<-", "d", ":", "return", "nil", "\n", "}", "\n", "}" ]
// Send puts a message into the outgoing queue, waiting to be sent. // With buffered channels, this will not block under moderate throughput. // When an error is generated, the error can be communicated by placing // a message on the incoming queue to be handled upstream.
[ "Send", "puts", "a", "message", "into", "the", "outgoing", "queue", "waiting", "to", "be", "sent", ".", "With", "buffered", "channels", "this", "will", "not", "block", "under", "moderate", "throughput", ".", "When", "an", "error", "is", "generated", "the", "error", "can", "be", "communicated", "by", "placing", "a", "message", "on", "the", "incoming", "queue", "to", "be", "handled", "upstream", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v0/messenger/messenger.go#L188-L217
12,874
mesos/mesos-go
api/v0/messenger/messenger.go
Start
func (m *MesosMessenger) Start() error { m.stop = make(chan struct{}) pid, errChan := m.tr.Start() if pid == (upid.UPID{}) { err := <-errChan return fmt.Errorf("failed to start messenger: %v", err) } // the pid that we're actually bound as m.upid = pid go m.sendLoop() go m.decodeLoop() // wait for a listener error or a stop signal; either way stop the messenger // TODO(jdef) a better implementation would attempt to re-listen; need to coordinate // access to m.upid in that case. probably better off with a state machine instead of // what we have now. go func() { select { case err := <-errChan: if err != nil { //TODO(jdef) should the driver abort in this case? probably //since this messenger will never attempt to re-establish the //transport log.Errorln("transport stopped unexpectedly:", err.Error()) } err = m.Stop() if err != nil && err != errTerminal { log.Errorln("failed to stop messenger cleanly: ", err.Error()) } case <-m.stop: } }() return nil }
go
func (m *MesosMessenger) Start() error { m.stop = make(chan struct{}) pid, errChan := m.tr.Start() if pid == (upid.UPID{}) { err := <-errChan return fmt.Errorf("failed to start messenger: %v", err) } // the pid that we're actually bound as m.upid = pid go m.sendLoop() go m.decodeLoop() // wait for a listener error or a stop signal; either way stop the messenger // TODO(jdef) a better implementation would attempt to re-listen; need to coordinate // access to m.upid in that case. probably better off with a state machine instead of // what we have now. go func() { select { case err := <-errChan: if err != nil { //TODO(jdef) should the driver abort in this case? probably //since this messenger will never attempt to re-establish the //transport log.Errorln("transport stopped unexpectedly:", err.Error()) } err = m.Stop() if err != nil && err != errTerminal { log.Errorln("failed to stop messenger cleanly: ", err.Error()) } case <-m.stop: } }() return nil }
[ "func", "(", "m", "*", "MesosMessenger", ")", "Start", "(", ")", "error", "{", "m", ".", "stop", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n\n", "pid", ",", "errChan", ":=", "m", ".", "tr", ".", "Start", "(", ")", "\n", "if", "pid", "==", "(", "upid", ".", "UPID", "{", "}", ")", "{", "err", ":=", "<-", "errChan", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// the pid that we're actually bound as", "m", ".", "upid", "=", "pid", "\n\n", "go", "m", ".", "sendLoop", "(", ")", "\n", "go", "m", ".", "decodeLoop", "(", ")", "\n\n", "// wait for a listener error or a stop signal; either way stop the messenger", "// TODO(jdef) a better implementation would attempt to re-listen; need to coordinate", "// access to m.upid in that case. probably better off with a state machine instead of", "// what we have now.", "go", "func", "(", ")", "{", "select", "{", "case", "err", ":=", "<-", "errChan", ":", "if", "err", "!=", "nil", "{", "//TODO(jdef) should the driver abort in this case? probably", "//since this messenger will never attempt to re-establish the", "//transport", "log", ".", "Errorln", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "err", "=", "m", ".", "Stop", "(", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "errTerminal", "{", "log", ".", "Errorln", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "case", "<-", "m", ".", "stop", ":", "}", "\n", "}", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Start starts the messenger; expects to be called once and only once.
[ "Start", "starts", "the", "messenger", ";", "expects", "to", "be", "called", "once", "and", "only", "once", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v0/messenger/messenger.go#L246-L284
12,875
mesos/mesos-go
api/v0/messenger/messenger.go
Stop
func (m *MesosMessenger) Stop() (err error) { m.stopOnce.Do(func() { select { case <-m.stop: default: defer close(m.stop) } log.Infof("stopping messenger %v..", m.upid) //TODO(jdef) don't hardcode the graceful flag here if err2 := m.tr.Stop(true); err2 != nil && err2 != errTerminal { log.Warningf("failed to stop the transporter: %v\n", err2) err = err2 } }) return }
go
func (m *MesosMessenger) Stop() (err error) { m.stopOnce.Do(func() { select { case <-m.stop: default: defer close(m.stop) } log.Infof("stopping messenger %v..", m.upid) //TODO(jdef) don't hardcode the graceful flag here if err2 := m.tr.Stop(true); err2 != nil && err2 != errTerminal { log.Warningf("failed to stop the transporter: %v\n", err2) err = err2 } }) return }
[ "func", "(", "m", "*", "MesosMessenger", ")", "Stop", "(", ")", "(", "err", "error", ")", "{", "m", ".", "stopOnce", ".", "Do", "(", "func", "(", ")", "{", "select", "{", "case", "<-", "m", ".", "stop", ":", "default", ":", "defer", "close", "(", "m", ".", "stop", ")", "\n", "}", "\n\n", "log", ".", "Infof", "(", "\"", "\"", ",", "m", ".", "upid", ")", "\n\n", "//TODO(jdef) don't hardcode the graceful flag here", "if", "err2", ":=", "m", ".", "tr", ".", "Stop", "(", "true", ")", ";", "err2", "!=", "nil", "&&", "err2", "!=", "errTerminal", "{", "log", ".", "Warningf", "(", "\"", "\\n", "\"", ",", "err2", ")", "\n", "err", "=", "err2", "\n", "}", "\n", "}", ")", "\n", "return", "\n", "}" ]
// Stop stops the messenger and clean up all the goroutines.
[ "Stop", "stops", "the", "messenger", "and", "clean", "up", "all", "the", "goroutines", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v0/messenger/messenger.go#L287-L304
12,876
mesos/mesos-go
api/v0/messenger/messenger.go
getMessageName
func getMessageName(msg proto.Message) string { var msgName string switch msg := msg.(type) { case *scheduler.Call: msgName = "scheduler" default: msgName = fmt.Sprintf("%v.%v", "mesos.internal", reflect.TypeOf(msg).Elem().Name()) } return msgName }
go
func getMessageName(msg proto.Message) string { var msgName string switch msg := msg.(type) { case *scheduler.Call: msgName = "scheduler" default: msgName = fmt.Sprintf("%v.%v", "mesos.internal", reflect.TypeOf(msg).Elem().Name()) } return msgName }
[ "func", "getMessageName", "(", "msg", "proto", ".", "Message", ")", "string", "{", "var", "msgName", "string", "\n\n", "switch", "msg", ":=", "msg", ".", "(", "type", ")", "{", "case", "*", "scheduler", ".", "Call", ":", "msgName", "=", "\"", "\"", "\n", "default", ":", "msgName", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "msg", ")", ".", "Elem", "(", ")", ".", "Name", "(", ")", ")", "\n", "}", "\n\n", "return", "msgName", "\n", "}" ]
// getMessageName returns the name of the message in the mesos manner.
[ "getMessageName", "returns", "the", "name", "of", "the", "message", "in", "the", "mesos", "manner", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v0/messenger/messenger.go#L406-L417
12,877
mesos/mesos-go
api/v1/lib/ranges.go
NewRanges
func NewRanges(ns ...uint64) Ranges { xs := append(uint64s{}, ns...) sort.Sort(xs) rs := make(Ranges, len(xs)) for i := range xs { rs[i].Begin, rs[i].End = xs[i], xs[i] } return rs.Squash() }
go
func NewRanges(ns ...uint64) Ranges { xs := append(uint64s{}, ns...) sort.Sort(xs) rs := make(Ranges, len(xs)) for i := range xs { rs[i].Begin, rs[i].End = xs[i], xs[i] } return rs.Squash() }
[ "func", "NewRanges", "(", "ns", "...", "uint64", ")", "Ranges", "{", "xs", ":=", "append", "(", "uint64s", "{", "}", ",", "ns", "...", ")", "\n", "sort", ".", "Sort", "(", "xs", ")", "\n", "rs", ":=", "make", "(", "Ranges", ",", "len", "(", "xs", ")", ")", "\n", "for", "i", ":=", "range", "xs", "{", "rs", "[", "i", "]", ".", "Begin", ",", "rs", "[", "i", "]", ".", "End", "=", "xs", "[", "i", "]", ",", "xs", "[", "i", "]", "\n", "}", "\n", "return", "rs", ".", "Squash", "(", ")", "\n", "}" ]
// NewRanges returns squashed Ranges from the given numbers.
[ "NewRanges", "returns", "squashed", "Ranges", "from", "the", "given", "numbers", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/ranges.go#L11-L19
12,878
mesos/mesos-go
api/v1/lib/ranges.go
Size
func (rs Ranges) Size() uint64 { var sz uint64 for i := range rs { sz += 1 + (rs[i].End - rs[i].Begin) } return sz }
go
func (rs Ranges) Size() uint64 { var sz uint64 for i := range rs { sz += 1 + (rs[i].End - rs[i].Begin) } return sz }
[ "func", "(", "rs", "Ranges", ")", "Size", "(", ")", "uint64", "{", "var", "sz", "uint64", "\n", "for", "i", ":=", "range", "rs", "{", "sz", "+=", "1", "+", "(", "rs", "[", "i", "]", ".", "End", "-", "rs", "[", "i", "]", ".", "Begin", ")", "\n", "}", "\n", "return", "sz", "\n", "}" ]
// Size returns the sum of the Size of all Ranges.
[ "Size", "returns", "the", "sum", "of", "the", "Size", "of", "all", "Ranges", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/ranges.go#L67-L73
12,879
mesos/mesos-go
api/v1/lib/ranges.go
Squash
func (rs Ranges) Squash() Ranges { if len(rs) < 2 { return rs } squashed := Ranges{rs[0]} for i := 1; i < len(rs); i++ { switch max := squashed[len(squashed)-1].End; { case 1+max < rs[i].Begin: // no overlap nor continuity: push squashed = append(squashed, rs[i]) case max <= rs[i].End: // overlap or continuity: squash squashed[len(squashed)-1].End = rs[i].End } } return squashed }
go
func (rs Ranges) Squash() Ranges { if len(rs) < 2 { return rs } squashed := Ranges{rs[0]} for i := 1; i < len(rs); i++ { switch max := squashed[len(squashed)-1].End; { case 1+max < rs[i].Begin: // no overlap nor continuity: push squashed = append(squashed, rs[i]) case max <= rs[i].End: // overlap or continuity: squash squashed[len(squashed)-1].End = rs[i].End } } return squashed }
[ "func", "(", "rs", "Ranges", ")", "Squash", "(", ")", "Ranges", "{", "if", "len", "(", "rs", ")", "<", "2", "{", "return", "rs", "\n", "}", "\n", "squashed", ":=", "Ranges", "{", "rs", "[", "0", "]", "}", "\n", "for", "i", ":=", "1", ";", "i", "<", "len", "(", "rs", ")", ";", "i", "++", "{", "switch", "max", ":=", "squashed", "[", "len", "(", "squashed", ")", "-", "1", "]", ".", "End", ";", "{", "case", "1", "+", "max", "<", "rs", "[", "i", "]", ".", "Begin", ":", "// no overlap nor continuity: push", "squashed", "=", "append", "(", "squashed", ",", "rs", "[", "i", "]", ")", "\n", "case", "max", "<=", "rs", "[", "i", "]", ".", "End", ":", "// overlap or continuity: squash", "squashed", "[", "len", "(", "squashed", ")", "-", "1", "]", ".", "End", "=", "rs", "[", "i", "]", ".", "End", "\n", "}", "\n", "}", "\n", "return", "squashed", "\n", "}" ]
// Squash merges overlapping and continuous Ranges. It assumes they're pre-sorted.
[ "Squash", "merges", "overlapping", "and", "continuous", "Ranges", ".", "It", "assumes", "they", "re", "pre", "-", "sorted", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/ranges.go#L82-L96
12,880
mesos/mesos-go
api/v1/lib/ranges.go
Search
func (rs Ranges) Search(n uint64) int { for lo, hi := 0, len(rs)-1; lo <= hi; { switch m := lo + (hi-lo)/2; { case n < rs[m].Begin: hi = m - 1 case n > rs[m].End: lo = m + 1 default: return m } } return -1 }
go
func (rs Ranges) Search(n uint64) int { for lo, hi := 0, len(rs)-1; lo <= hi; { switch m := lo + (hi-lo)/2; { case n < rs[m].Begin: hi = m - 1 case n > rs[m].End: lo = m + 1 default: return m } } return -1 }
[ "func", "(", "rs", "Ranges", ")", "Search", "(", "n", "uint64", ")", "int", "{", "for", "lo", ",", "hi", ":=", "0", ",", "len", "(", "rs", ")", "-", "1", ";", "lo", "<=", "hi", ";", "{", "switch", "m", ":=", "lo", "+", "(", "hi", "-", "lo", ")", "/", "2", ";", "{", "case", "n", "<", "rs", "[", "m", "]", ".", "Begin", ":", "hi", "=", "m", "-", "1", "\n", "case", "n", ">", "rs", "[", "m", "]", ".", "End", ":", "lo", "=", "m", "+", "1", "\n", "default", ":", "return", "m", "\n", "}", "\n", "}", "\n", "return", "-", "1", "\n", "}" ]
// Search performs a binary search for n returning the index of the Range it was // found at or -1 if not found.
[ "Search", "performs", "a", "binary", "search", "for", "n", "returning", "the", "index", "of", "the", "Range", "it", "was", "found", "at", "or", "-", "1", "if", "not", "found", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/ranges.go#L100-L112
12,881
mesos/mesos-go
api/v1/lib/ranges.go
Partition
func (rs Ranges) Partition(n uint64) (Ranges, bool) { i := rs.Search(n) if i < 0 { return rs, false } pn := make(Ranges, 0, len(rs)+1) switch pn = append(pn, rs[:i]...); { case rs[i].Begin == rs[i].End: // delete case rs[i].Begin == n: // increment lower bound pn = append(pn, Value_Range{rs[i].Begin + 1, rs[i].End}) case rs[i].End == n: // decrement upper bound pn = append(pn, Value_Range{rs[i].Begin, rs[i].End - 1}) default: // split pn = append(pn, Value_Range{rs[i].Begin, n - 1}, Value_Range{n + 1, rs[i].End}) } return append(pn, rs[i+1:]...), true }
go
func (rs Ranges) Partition(n uint64) (Ranges, bool) { i := rs.Search(n) if i < 0 { return rs, false } pn := make(Ranges, 0, len(rs)+1) switch pn = append(pn, rs[:i]...); { case rs[i].Begin == rs[i].End: // delete case rs[i].Begin == n: // increment lower bound pn = append(pn, Value_Range{rs[i].Begin + 1, rs[i].End}) case rs[i].End == n: // decrement upper bound pn = append(pn, Value_Range{rs[i].Begin, rs[i].End - 1}) default: // split pn = append(pn, Value_Range{rs[i].Begin, n - 1}, Value_Range{n + 1, rs[i].End}) } return append(pn, rs[i+1:]...), true }
[ "func", "(", "rs", "Ranges", ")", "Partition", "(", "n", "uint64", ")", "(", "Ranges", ",", "bool", ")", "{", "i", ":=", "rs", ".", "Search", "(", "n", ")", "\n", "if", "i", "<", "0", "{", "return", "rs", ",", "false", "\n", "}", "\n\n", "pn", ":=", "make", "(", "Ranges", ",", "0", ",", "len", "(", "rs", ")", "+", "1", ")", "\n", "switch", "pn", "=", "append", "(", "pn", ",", "rs", "[", ":", "i", "]", "...", ")", ";", "{", "case", "rs", "[", "i", "]", ".", "Begin", "==", "rs", "[", "i", "]", ".", "End", ":", "// delete", "case", "rs", "[", "i", "]", ".", "Begin", "==", "n", ":", "// increment lower bound", "pn", "=", "append", "(", "pn", ",", "Value_Range", "{", "rs", "[", "i", "]", ".", "Begin", "+", "1", ",", "rs", "[", "i", "]", ".", "End", "}", ")", "\n", "case", "rs", "[", "i", "]", ".", "End", "==", "n", ":", "// decrement upper bound", "pn", "=", "append", "(", "pn", ",", "Value_Range", "{", "rs", "[", "i", "]", ".", "Begin", ",", "rs", "[", "i", "]", ".", "End", "-", "1", "}", ")", "\n", "default", ":", "// split", "pn", "=", "append", "(", "pn", ",", "Value_Range", "{", "rs", "[", "i", "]", ".", "Begin", ",", "n", "-", "1", "}", ",", "Value_Range", "{", "n", "+", "1", ",", "rs", "[", "i", "]", ".", "End", "}", ")", "\n", "}", "\n", "return", "append", "(", "pn", ",", "rs", "[", "i", "+", "1", ":", "]", "...", ")", ",", "true", "\n", "}" ]
// Partition partitions Ranges around n. It returns the partitioned Ranges // and a boolean indicating if n was found.
[ "Partition", "partitions", "Ranges", "around", "n", ".", "It", "returns", "the", "partitioned", "Ranges", "and", "a", "boolean", "indicating", "if", "n", "was", "found", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/ranges.go#L116-L133
12,882
mesos/mesos-go
api/v1/lib/ranges.go
Remove
func (rs Ranges) Remove(removal Value_Range) Ranges { ranges := make([]Value_Range, 0, len(rs)) for _, r := range rs { // skip if the entire range is subsumed by removal if r.Begin >= removal.Begin && r.End <= removal.End { continue } // divide if the range subsumes the removal if r.Begin < removal.Begin && r.End > removal.End { ranges = append(ranges, Value_Range{r.Begin, removal.Begin - 1}, Value_Range{removal.End + 1, r.End}, ) continue } // add the full range if there's no intersection if r.End < removal.Begin || r.Begin > removal.End { ranges = append(ranges, r) continue } // trim if the range does intersect if r.End > removal.End { ranges = append(ranges, Value_Range{removal.End + 1, r.End}) } else { if r.Begin >= removal.Begin { // should never happen panic("r.Begin >= removal.Begin") } ranges = append(ranges, Value_Range{r.Begin, removal.Begin - 1}) } } return Ranges(ranges).Squash() }
go
func (rs Ranges) Remove(removal Value_Range) Ranges { ranges := make([]Value_Range, 0, len(rs)) for _, r := range rs { // skip if the entire range is subsumed by removal if r.Begin >= removal.Begin && r.End <= removal.End { continue } // divide if the range subsumes the removal if r.Begin < removal.Begin && r.End > removal.End { ranges = append(ranges, Value_Range{r.Begin, removal.Begin - 1}, Value_Range{removal.End + 1, r.End}, ) continue } // add the full range if there's no intersection if r.End < removal.Begin || r.Begin > removal.End { ranges = append(ranges, r) continue } // trim if the range does intersect if r.End > removal.End { ranges = append(ranges, Value_Range{removal.End + 1, r.End}) } else { if r.Begin >= removal.Begin { // should never happen panic("r.Begin >= removal.Begin") } ranges = append(ranges, Value_Range{r.Begin, removal.Begin - 1}) } } return Ranges(ranges).Squash() }
[ "func", "(", "rs", "Ranges", ")", "Remove", "(", "removal", "Value_Range", ")", "Ranges", "{", "ranges", ":=", "make", "(", "[", "]", "Value_Range", ",", "0", ",", "len", "(", "rs", ")", ")", "\n", "for", "_", ",", "r", ":=", "range", "rs", "{", "// skip if the entire range is subsumed by removal", "if", "r", ".", "Begin", ">=", "removal", ".", "Begin", "&&", "r", ".", "End", "<=", "removal", ".", "End", "{", "continue", "\n", "}", "\n", "// divide if the range subsumes the removal", "if", "r", ".", "Begin", "<", "removal", ".", "Begin", "&&", "r", ".", "End", ">", "removal", ".", "End", "{", "ranges", "=", "append", "(", "ranges", ",", "Value_Range", "{", "r", ".", "Begin", ",", "removal", ".", "Begin", "-", "1", "}", ",", "Value_Range", "{", "removal", ".", "End", "+", "1", ",", "r", ".", "End", "}", ",", ")", "\n", "continue", "\n", "}", "\n", "// add the full range if there's no intersection", "if", "r", ".", "End", "<", "removal", ".", "Begin", "||", "r", ".", "Begin", ">", "removal", ".", "End", "{", "ranges", "=", "append", "(", "ranges", ",", "r", ")", "\n", "continue", "\n", "}", "\n", "// trim if the range does intersect", "if", "r", ".", "End", ">", "removal", ".", "End", "{", "ranges", "=", "append", "(", "ranges", ",", "Value_Range", "{", "removal", ".", "End", "+", "1", ",", "r", ".", "End", "}", ")", "\n", "}", "else", "{", "if", "r", ".", "Begin", ">=", "removal", ".", "Begin", "{", "// should never happen", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "ranges", "=", "append", "(", "ranges", ",", "Value_Range", "{", "r", ".", "Begin", ",", "removal", ".", "Begin", "-", "1", "}", ")", "\n", "}", "\n", "}", "\n", "return", "Ranges", "(", "ranges", ")", ".", "Squash", "(", ")", "\n", "}" ]
// Remove removes a range from already coalesced ranges. // The algorithms constructs a new vector of ranges which is then // Squash'ed into a Ranges instance.
[ "Remove", "removes", "a", "range", "from", "already", "coalesced", "ranges", ".", "The", "algorithms", "constructs", "a", "new", "vector", "of", "ranges", "which", "is", "then", "Squash", "ed", "into", "a", "Ranges", "instance", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/ranges.go#L138-L170
12,883
mesos/mesos-go
api/v1/lib/ranges.go
Compare
func (rs Ranges) Compare(right Ranges) int { x, y, result := rs.equiv(right) if result { return 0 } for _, a := range x { // make sure that this range is a subset of a range in y matched := false for _, b := range y { if a.Begin >= b.Begin && a.End <= b.End { matched = true break } } if !matched { return 1 } } return -1 }
go
func (rs Ranges) Compare(right Ranges) int { x, y, result := rs.equiv(right) if result { return 0 } for _, a := range x { // make sure that this range is a subset of a range in y matched := false for _, b := range y { if a.Begin >= b.Begin && a.End <= b.End { matched = true break } } if !matched { return 1 } } return -1 }
[ "func", "(", "rs", "Ranges", ")", "Compare", "(", "right", "Ranges", ")", "int", "{", "x", ",", "y", ",", "result", ":=", "rs", ".", "equiv", "(", "right", ")", "\n", "if", "result", "{", "return", "0", "\n", "}", "\n", "for", "_", ",", "a", ":=", "range", "x", "{", "// make sure that this range is a subset of a range in y", "matched", ":=", "false", "\n", "for", "_", ",", "b", ":=", "range", "y", "{", "if", "a", ".", "Begin", ">=", "b", ".", "Begin", "&&", "a", ".", "End", "<=", "b", ".", "End", "{", "matched", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "matched", "{", "return", "1", "\n", "}", "\n", "}", "\n", "return", "-", "1", "\n", "}" ]
// Compare assumes that both Ranges are already in sort-order. // Returns 0 if rs and right are equivalent, -1 if rs is a subset of right, or else 1
[ "Compare", "assumes", "that", "both", "Ranges", "are", "already", "in", "sort", "-", "order", ".", "Returns", "0", "if", "rs", "and", "right", "are", "equivalent", "-", "1", "if", "rs", "is", "a", "subset", "of", "right", "or", "else", "1" ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/ranges.go#L174-L193
12,884
mesos/mesos-go
api/v0/auth/interface.go
getAuthenticateeProvider
func getAuthenticateeProvider(name string) (provider Authenticatee, ok bool) { providerLock.Lock() defer providerLock.Unlock() provider, ok = authenticateeProviders[name] return }
go
func getAuthenticateeProvider(name string) (provider Authenticatee, ok bool) { providerLock.Lock() defer providerLock.Unlock() provider, ok = authenticateeProviders[name] return }
[ "func", "getAuthenticateeProvider", "(", "name", "string", ")", "(", "provider", "Authenticatee", ",", "ok", "bool", ")", "{", "providerLock", ".", "Lock", "(", ")", "\n", "defer", "providerLock", ".", "Unlock", "(", ")", "\n\n", "provider", ",", "ok", "=", "authenticateeProviders", "[", "name", "]", "\n", "return", "\n", "}" ]
// Look up an authentication provider by name, returns non-nil and true if such // a provider is found.
[ "Look", "up", "an", "authentication", "provider", "by", "name", "returns", "non", "-", "nil", "and", "true", "if", "such", "a", "provider", "is", "found", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v0/auth/interface.go#L57-L63
12,885
mesos/mesos-go
api/v1/lib/httpcli/http.go
New
func New(opts ...Opt) *Client { c := &Client{ codec: DefaultCodec, do: With(DefaultConfigOpt...), header: cloneHeaders(DefaultHeaders), errorMapper: DefaultErrorMapper, } c.buildRequestFunc = c.buildRequest c.handleResponse = c.HandleResponse c.With(opts...) return c }
go
func New(opts ...Opt) *Client { c := &Client{ codec: DefaultCodec, do: With(DefaultConfigOpt...), header: cloneHeaders(DefaultHeaders), errorMapper: DefaultErrorMapper, } c.buildRequestFunc = c.buildRequest c.handleResponse = c.HandleResponse c.With(opts...) return c }
[ "func", "New", "(", "opts", "...", "Opt", ")", "*", "Client", "{", "c", ":=", "&", "Client", "{", "codec", ":", "DefaultCodec", ",", "do", ":", "With", "(", "DefaultConfigOpt", "...", ")", ",", "header", ":", "cloneHeaders", "(", "DefaultHeaders", ")", ",", "errorMapper", ":", "DefaultErrorMapper", ",", "}", "\n", "c", ".", "buildRequestFunc", "=", "c", ".", "buildRequest", "\n", "c", ".", "handleResponse", "=", "c", ".", "HandleResponse", "\n", "c", ".", "With", "(", "opts", "...", ")", "\n", "return", "c", "\n", "}" ]
// New returns a new Client with the given Opts applied. // Callers are expected to configure the URL, Do, and Codec options prior to // invoking Do.
[ "New", "returns", "a", "new", "Client", "with", "the", "given", "Opts", "applied", ".", "Callers", "are", "expected", "to", "configure", "the", "URL", "Do", "and", "Codec", "options", "prior", "to", "invoking", "Do", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/httpcli/http.go#L104-L115
12,886
mesos/mesos-go
api/v1/lib/httpcli/http.go
Apply
func (opts RequestOpts) Apply(req *http.Request) { // apply per-request options for _, o := range opts { if o != nil { o(req) } } }
go
func (opts RequestOpts) Apply(req *http.Request) { // apply per-request options for _, o := range opts { if o != nil { o(req) } } }
[ "func", "(", "opts", "RequestOpts", ")", "Apply", "(", "req", "*", "http", ".", "Request", ")", "{", "// apply per-request options", "for", "_", ",", "o", ":=", "range", "opts", "{", "if", "o", "!=", "nil", "{", "o", "(", "req", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Apply this set of request options to the given HTTP request.
[ "Apply", "this", "set", "of", "request", "options", "to", "the", "given", "HTTP", "request", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/httpcli/http.go#L139-L146
12,887
mesos/mesos-go
api/v1/lib/httpcli/http.go
With
func (c *Client) With(opts ...Opt) Opt { return Opts(opts).Merged().Apply(c) }
go
func (c *Client) With(opts ...Opt) Opt { return Opts(opts).Merged().Apply(c) }
[ "func", "(", "c", "*", "Client", ")", "With", "(", "opts", "...", "Opt", ")", "Opt", "{", "return", "Opts", "(", "opts", ")", ".", "Merged", "(", ")", ".", "Apply", "(", "c", ")", "\n", "}" ]
// With applies the given Opts to a Client and returns itself.
[ "With", "applies", "the", "given", "Opts", "to", "a", "Client", "and", "returns", "itself", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/httpcli/http.go#L149-L151
12,888
mesos/mesos-go
api/v1/lib/httpcli/http.go
Mesos
func (c *Client) Mesos(opts ...RequestOpt) mesos.Client { return mesos.ClientFunc(func(m encoding.Marshaler) (mesos.Response, error) { return c.Do(m, opts...) }) }
go
func (c *Client) Mesos(opts ...RequestOpt) mesos.Client { return mesos.ClientFunc(func(m encoding.Marshaler) (mesos.Response, error) { return c.Do(m, opts...) }) }
[ "func", "(", "c", "*", "Client", ")", "Mesos", "(", "opts", "...", "RequestOpt", ")", "mesos", ".", "Client", "{", "return", "mesos", ".", "ClientFunc", "(", "func", "(", "m", "encoding", ".", "Marshaler", ")", "(", "mesos", ".", "Response", ",", "error", ")", "{", "return", "c", ".", "Do", "(", "m", ",", "opts", "...", ")", "\n", "}", ")", "\n", "}" ]
// Mesos returns a mesos.Client variant backed by this implementation. // Deprecated.
[ "Mesos", "returns", "a", "mesos", ".", "Client", "variant", "backed", "by", "this", "implementation", ".", "Deprecated", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/httpcli/http.go#L166-L170
12,889
mesos/mesos-go
api/v1/lib/httpcli/http.go
buildRequest
func (c *Client) buildRequest(cr client.Request, rc client.ResponseClass, opt ...RequestOpt) (*http.Request, error) { if crs, ok := cr.(client.RequestStreaming); ok { return c.buildRequestStream(crs.Marshaler, rc, opt...) } accept, err := prepareForResponse(rc, c.codec) if err != nil { return nil, err } //TODO(jdef): use a pool to allocate these (and reduce garbage)? // .. or else, use a pipe (like streaming does) to avoid the intermediate buffer? var body bytes.Buffer if err := c.codec.NewEncoder(encoding.SinkWriter(&body)).Encode(cr.Marshaler()); err != nil { return nil, err } req, err := http.NewRequest("POST", c.url, &body) if err != nil { return nil, err } helper := HTTPRequestHelper{req} return helper. withOptions(c.requestOpts, opt). withHeaders(c.header). withHeader("Content-Type", c.codec.Type.ContentType()). withHeader("Accept", c.codec.Type.ContentType()). withOptions(accept). Request, nil }
go
func (c *Client) buildRequest(cr client.Request, rc client.ResponseClass, opt ...RequestOpt) (*http.Request, error) { if crs, ok := cr.(client.RequestStreaming); ok { return c.buildRequestStream(crs.Marshaler, rc, opt...) } accept, err := prepareForResponse(rc, c.codec) if err != nil { return nil, err } //TODO(jdef): use a pool to allocate these (and reduce garbage)? // .. or else, use a pipe (like streaming does) to avoid the intermediate buffer? var body bytes.Buffer if err := c.codec.NewEncoder(encoding.SinkWriter(&body)).Encode(cr.Marshaler()); err != nil { return nil, err } req, err := http.NewRequest("POST", c.url, &body) if err != nil { return nil, err } helper := HTTPRequestHelper{req} return helper. withOptions(c.requestOpts, opt). withHeaders(c.header). withHeader("Content-Type", c.codec.Type.ContentType()). withHeader("Accept", c.codec.Type.ContentType()). withOptions(accept). Request, nil }
[ "func", "(", "c", "*", "Client", ")", "buildRequest", "(", "cr", "client", ".", "Request", ",", "rc", "client", ".", "ResponseClass", ",", "opt", "...", "RequestOpt", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "if", "crs", ",", "ok", ":=", "cr", ".", "(", "client", ".", "RequestStreaming", ")", ";", "ok", "{", "return", "c", ".", "buildRequestStream", "(", "crs", ".", "Marshaler", ",", "rc", ",", "opt", "...", ")", "\n", "}", "\n", "accept", ",", "err", ":=", "prepareForResponse", "(", "rc", ",", "c", ".", "codec", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "//TODO(jdef): use a pool to allocate these (and reduce garbage)?", "// .. or else, use a pipe (like streaming does) to avoid the intermediate buffer?", "var", "body", "bytes", ".", "Buffer", "\n", "if", "err", ":=", "c", ".", "codec", ".", "NewEncoder", "(", "encoding", ".", "SinkWriter", "(", "&", "body", ")", ")", ".", "Encode", "(", "cr", ".", "Marshaler", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "c", ".", "url", ",", "&", "body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "helper", ":=", "HTTPRequestHelper", "{", "req", "}", "\n", "return", "helper", ".", "withOptions", "(", "c", ".", "requestOpts", ",", "opt", ")", ".", "withHeaders", "(", "c", ".", "header", ")", ".", "withHeader", "(", "\"", "\"", ",", "c", ".", "codec", ".", "Type", ".", "ContentType", "(", ")", ")", ".", "withHeader", "(", "\"", "\"", ",", "c", ".", "codec", ".", "Type", ".", "ContentType", "(", ")", ")", ".", "withOptions", "(", "accept", ")", ".", "Request", ",", "nil", "\n", "}" ]
// buildRequest is a factory func that generates and returns an http.Request for the // given marshaler and request options.
[ "buildRequest", "is", "a", "factory", "func", "that", "generates", "and", "returns", "an", "http", ".", "Request", "for", "the", "given", "marshaler", "and", "request", "options", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/httpcli/http.go#L192-L221
12,890
mesos/mesos-go
api/v1/lib/httpcli/http.go
HandleResponse
func (c *Client) HandleResponse(res *http.Response, rc client.ResponseClass, err error) (mesos.Response, error) { if err != nil { if res != nil && res.Body != nil { res.Body.Close() } return nil, err } result := &Response{ Closer: res.Body, Header: res.Header, } if err = c.errorMapper(res); err != nil { return result, err } err = validateSuccessfulResponse(c.codec, res, rc) if err != nil { res.Body.Close() return nil, err } switch res.StatusCode { case http.StatusOK: debug.Log("request OK, decoding response") sf := newSourceFactory(rc, res.ContentLength > -1) if sf == nil { if rc != client.ResponseClassNoData { panic("nil Source for response that expected data") } // we don't expect any data. drain the response body and close it (compliant with golang's expectations // for http/1.1 keepalive support. defer res.Body.Close() _, err = io.Copy(ioutil.Discard, res.Body) return nil, err } result.Decoder = c.codec.NewDecoder(sf.NewSource(res.Body)) case http.StatusAccepted: debug.Log("request Accepted") // noop; no decoder for these types of calls defer res.Body.Close() _, err = io.Copy(ioutil.Discard, res.Body) return nil, err default: debug.Log("unexpected HTTP status", res.StatusCode) defer res.Body.Close() io.Copy(ioutil.Discard, res.Body) // intentionally discard any error here return nil, ProtocolError(fmt.Sprintf("unexpected mesos HTTP response code: %d", res.StatusCode)) } return result, nil }
go
func (c *Client) HandleResponse(res *http.Response, rc client.ResponseClass, err error) (mesos.Response, error) { if err != nil { if res != nil && res.Body != nil { res.Body.Close() } return nil, err } result := &Response{ Closer: res.Body, Header: res.Header, } if err = c.errorMapper(res); err != nil { return result, err } err = validateSuccessfulResponse(c.codec, res, rc) if err != nil { res.Body.Close() return nil, err } switch res.StatusCode { case http.StatusOK: debug.Log("request OK, decoding response") sf := newSourceFactory(rc, res.ContentLength > -1) if sf == nil { if rc != client.ResponseClassNoData { panic("nil Source for response that expected data") } // we don't expect any data. drain the response body and close it (compliant with golang's expectations // for http/1.1 keepalive support. defer res.Body.Close() _, err = io.Copy(ioutil.Discard, res.Body) return nil, err } result.Decoder = c.codec.NewDecoder(sf.NewSource(res.Body)) case http.StatusAccepted: debug.Log("request Accepted") // noop; no decoder for these types of calls defer res.Body.Close() _, err = io.Copy(ioutil.Discard, res.Body) return nil, err default: debug.Log("unexpected HTTP status", res.StatusCode) defer res.Body.Close() io.Copy(ioutil.Discard, res.Body) // intentionally discard any error here return nil, ProtocolError(fmt.Sprintf("unexpected mesos HTTP response code: %d", res.StatusCode)) } return result, nil }
[ "func", "(", "c", "*", "Client", ")", "HandleResponse", "(", "res", "*", "http", ".", "Response", ",", "rc", "client", ".", "ResponseClass", ",", "err", "error", ")", "(", "mesos", ".", "Response", ",", "error", ")", "{", "if", "err", "!=", "nil", "{", "if", "res", "!=", "nil", "&&", "res", ".", "Body", "!=", "nil", "{", "res", ".", "Body", ".", "Close", "(", ")", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "result", ":=", "&", "Response", "{", "Closer", ":", "res", ".", "Body", ",", "Header", ":", "res", ".", "Header", ",", "}", "\n", "if", "err", "=", "c", ".", "errorMapper", "(", "res", ")", ";", "err", "!=", "nil", "{", "return", "result", ",", "err", "\n", "}", "\n\n", "err", "=", "validateSuccessfulResponse", "(", "c", ".", "codec", ",", "res", ",", "rc", ")", "\n", "if", "err", "!=", "nil", "{", "res", ".", "Body", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "switch", "res", ".", "StatusCode", "{", "case", "http", ".", "StatusOK", ":", "debug", ".", "Log", "(", "\"", "\"", ")", "\n\n", "sf", ":=", "newSourceFactory", "(", "rc", ",", "res", ".", "ContentLength", ">", "-", "1", ")", "\n", "if", "sf", "==", "nil", "{", "if", "rc", "!=", "client", ".", "ResponseClassNoData", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "// we don't expect any data. drain the response body and close it (compliant with golang's expectations", "// for http/1.1 keepalive support.", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n", "_", ",", "err", "=", "io", ".", "Copy", "(", "ioutil", ".", "Discard", ",", "res", ".", "Body", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "result", ".", "Decoder", "=", "c", ".", "codec", ".", "NewDecoder", "(", "sf", ".", "NewSource", "(", "res", ".", "Body", ")", ")", "\n\n", "case", "http", ".", "StatusAccepted", ":", "debug", ".", "Log", "(", "\"", "\"", ")", "\n\n", "// noop; no decoder for these types of calls", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n", "_", ",", "err", "=", "io", ".", "Copy", "(", "ioutil", ".", "Discard", ",", "res", ".", "Body", ")", "\n", "return", "nil", ",", "err", "\n\n", "default", ":", "debug", ".", "Log", "(", "\"", "\"", ",", "res", ".", "StatusCode", ")", "\n\n", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n", "io", ".", "Copy", "(", "ioutil", ".", "Discard", ",", "res", ".", "Body", ")", "// intentionally discard any error here", "\n", "return", "nil", ",", "ProtocolError", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "res", ".", "StatusCode", ")", ")", "\n", "}", "\n\n", "return", "result", ",", "nil", "\n", "}" ]
// HandleResponse parses an HTTP response from a Mesos service endpoint, transforming the // raw HTTP response into a mesos.Response.
[ "HandleResponse", "parses", "an", "HTTP", "response", "from", "a", "Mesos", "service", "endpoint", "transforming", "the", "raw", "HTTP", "response", "into", "a", "mesos", ".", "Response", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/httpcli/http.go#L329-L386
12,891
mesos/mesos-go
api/v1/lib/httpcli/http.go
Do
func (c *Client) Do(m encoding.Marshaler, opt ...RequestOpt) (res mesos.Response, err error) { return c.Send(client.RequestSingleton(m), client.ResponseClassAuto, opt...) }
go
func (c *Client) Do(m encoding.Marshaler, opt ...RequestOpt) (res mesos.Response, err error) { return c.Send(client.RequestSingleton(m), client.ResponseClassAuto, opt...) }
[ "func", "(", "c", "*", "Client", ")", "Do", "(", "m", "encoding", ".", "Marshaler", ",", "opt", "...", "RequestOpt", ")", "(", "res", "mesos", ".", "Response", ",", "err", "error", ")", "{", "return", "c", ".", "Send", "(", "client", ".", "RequestSingleton", "(", "m", ")", ",", "client", ".", "ResponseClassAuto", ",", "opt", "...", ")", "\n", "}" ]
// Do is deprecated in favor of Send.
[ "Do", "is", "deprecated", "in", "favor", "of", "Send", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/httpcli/http.go#L389-L391
12,892
mesos/mesos-go
api/v1/lib/httpcli/http.go
ErrorMapper
func ErrorMapper(em ErrorMapperFunc) Opt { return func(c *Client) Opt { old := c.errorMapper c.errorMapper = em return ErrorMapper(old) } }
go
func ErrorMapper(em ErrorMapperFunc) Opt { return func(c *Client) Opt { old := c.errorMapper c.errorMapper = em return ErrorMapper(old) } }
[ "func", "ErrorMapper", "(", "em", "ErrorMapperFunc", ")", "Opt", "{", "return", "func", "(", "c", "*", "Client", ")", "Opt", "{", "old", ":=", "c", ".", "errorMapper", "\n", "c", ".", "errorMapper", "=", "em", "\n", "return", "ErrorMapper", "(", "old", ")", "\n", "}", "\n", "}" ]
// ErrorMapper returns am Opt that overrides the existing error mapping behavior of the client.
[ "ErrorMapper", "returns", "am", "Opt", "that", "overrides", "the", "existing", "error", "mapping", "behavior", "of", "the", "client", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/httpcli/http.go#L415-L421
12,893
mesos/mesos-go
api/v1/lib/httpcli/http.go
Endpoint
func Endpoint(rawurl string) Opt { return func(c *Client) Opt { old := c.url c.url = rawurl return Endpoint(old) } }
go
func Endpoint(rawurl string) Opt { return func(c *Client) Opt { old := c.url c.url = rawurl return Endpoint(old) } }
[ "func", "Endpoint", "(", "rawurl", "string", ")", "Opt", "{", "return", "func", "(", "c", "*", "Client", ")", "Opt", "{", "old", ":=", "c", ".", "url", "\n", "c", ".", "url", "=", "rawurl", "\n", "return", "Endpoint", "(", "old", ")", "\n", "}", "\n", "}" ]
// Endpoint returns an Opt that sets a Client's URL.
[ "Endpoint", "returns", "an", "Opt", "that", "sets", "a", "Client", "s", "URL", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/httpcli/http.go#L424-L430
12,894
mesos/mesos-go
api/v1/lib/httpcli/http.go
WrapDoer
func WrapDoer(f func(DoFunc) DoFunc) Opt { return func(c *Client) Opt { old := c.do c.do = f(c.do) return Do(old) } }
go
func WrapDoer(f func(DoFunc) DoFunc) Opt { return func(c *Client) Opt { old := c.do c.do = f(c.do) return Do(old) } }
[ "func", "WrapDoer", "(", "f", "func", "(", "DoFunc", ")", "DoFunc", ")", "Opt", "{", "return", "func", "(", "c", "*", "Client", ")", "Opt", "{", "old", ":=", "c", ".", "do", "\n", "c", ".", "do", "=", "f", "(", "c", ".", "do", ")", "\n", "return", "Do", "(", "old", ")", "\n", "}", "\n", "}" ]
// WrapDoer returns an Opt that decorates a Client's DoFunc
[ "WrapDoer", "returns", "an", "Opt", "that", "decorates", "a", "Client", "s", "DoFunc" ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/httpcli/http.go#L433-L439
12,895
mesos/mesos-go
api/v1/lib/httpcli/http.go
Do
func Do(do DoFunc) Opt { return func(c *Client) Opt { old := c.do c.do = do return Do(old) } }
go
func Do(do DoFunc) Opt { return func(c *Client) Opt { old := c.do c.do = do return Do(old) } }
[ "func", "Do", "(", "do", "DoFunc", ")", "Opt", "{", "return", "func", "(", "c", "*", "Client", ")", "Opt", "{", "old", ":=", "c", ".", "do", "\n", "c", ".", "do", "=", "do", "\n", "return", "Do", "(", "old", ")", "\n", "}", "\n", "}" ]
// Do returns an Opt that sets a Client's DoFunc
[ "Do", "returns", "an", "Opt", "that", "sets", "a", "Client", "s", "DoFunc" ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/httpcli/http.go#L442-L448
12,896
mesos/mesos-go
api/v1/lib/httpcli/http.go
Codec
func Codec(codec encoding.Codec) Opt { return func(c *Client) Opt { old := c.codec c.codec = codec return Codec(old) } }
go
func Codec(codec encoding.Codec) Opt { return func(c *Client) Opt { old := c.codec c.codec = codec return Codec(old) } }
[ "func", "Codec", "(", "codec", "encoding", ".", "Codec", ")", "Opt", "{", "return", "func", "(", "c", "*", "Client", ")", "Opt", "{", "old", ":=", "c", ".", "codec", "\n", "c", ".", "codec", "=", "codec", "\n", "return", "Codec", "(", "old", ")", "\n", "}", "\n", "}" ]
// Codec returns an Opt that sets a Client's Codec.
[ "Codec", "returns", "an", "Opt", "that", "sets", "a", "Client", "s", "Codec", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/httpcli/http.go#L451-L457
12,897
mesos/mesos-go
api/v1/lib/httpcli/http.go
DefaultHeader
func DefaultHeader(k, v string) Opt { return func(c *Client) Opt { old, found := c.header[k] old = append([]string{}, old...) // clone c.header.Add(k, v) return func(c *Client) Opt { if found { c.header[k] = old } else { c.header.Del(k) } return DefaultHeader(k, v) } } }
go
func DefaultHeader(k, v string) Opt { return func(c *Client) Opt { old, found := c.header[k] old = append([]string{}, old...) // clone c.header.Add(k, v) return func(c *Client) Opt { if found { c.header[k] = old } else { c.header.Del(k) } return DefaultHeader(k, v) } } }
[ "func", "DefaultHeader", "(", "k", ",", "v", "string", ")", "Opt", "{", "return", "func", "(", "c", "*", "Client", ")", "Opt", "{", "old", ",", "found", ":=", "c", ".", "header", "[", "k", "]", "\n", "old", "=", "append", "(", "[", "]", "string", "{", "}", ",", "old", "...", ")", "// clone", "\n", "c", ".", "header", ".", "Add", "(", "k", ",", "v", ")", "\n", "return", "func", "(", "c", "*", "Client", ")", "Opt", "{", "if", "found", "{", "c", ".", "header", "[", "k", "]", "=", "old", "\n", "}", "else", "{", "c", ".", "header", ".", "Del", "(", "k", ")", "\n", "}", "\n", "return", "DefaultHeader", "(", "k", ",", "v", ")", "\n", "}", "\n", "}", "\n", "}" ]
// DefaultHeader returns an Opt that adds a header to an Client's headers.
[ "DefaultHeader", "returns", "an", "Opt", "that", "adds", "a", "header", "to", "an", "Client", "s", "headers", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/httpcli/http.go#L460-L474
12,898
mesos/mesos-go
api/v1/lib/httpcli/http.go
HandleResponse
func HandleResponse(f ResponseHandler) Opt { return func(c *Client) Opt { old := c.handleResponse c.handleResponse = f return HandleResponse(old) } }
go
func HandleResponse(f ResponseHandler) Opt { return func(c *Client) Opt { old := c.handleResponse c.handleResponse = f return HandleResponse(old) } }
[ "func", "HandleResponse", "(", "f", "ResponseHandler", ")", "Opt", "{", "return", "func", "(", "c", "*", "Client", ")", "Opt", "{", "old", ":=", "c", ".", "handleResponse", "\n", "c", ".", "handleResponse", "=", "f", "\n", "return", "HandleResponse", "(", "old", ")", "\n", "}", "\n", "}" ]
// HandleResponse returns a functional config option to set the HTTP response handler of the client.
[ "HandleResponse", "returns", "a", "functional", "config", "option", "to", "set", "the", "HTTP", "response", "handler", "of", "the", "client", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/httpcli/http.go#L477-L483
12,899
mesos/mesos-go
api/v1/lib/httpcli/http.go
RequestOptions
func RequestOptions(opts ...RequestOpt) Opt { if len(opts) == 0 { return nil } return func(c *Client) Opt { old := append([]RequestOpt{}, c.requestOpts...) c.requestOpts = opts return RequestOptions(old...) } }
go
func RequestOptions(opts ...RequestOpt) Opt { if len(opts) == 0 { return nil } return func(c *Client) Opt { old := append([]RequestOpt{}, c.requestOpts...) c.requestOpts = opts return RequestOptions(old...) } }
[ "func", "RequestOptions", "(", "opts", "...", "RequestOpt", ")", "Opt", "{", "if", "len", "(", "opts", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "return", "func", "(", "c", "*", "Client", ")", "Opt", "{", "old", ":=", "append", "(", "[", "]", "RequestOpt", "{", "}", ",", "c", ".", "requestOpts", "...", ")", "\n", "c", ".", "requestOpts", "=", "opts", "\n", "return", "RequestOptions", "(", "old", "...", ")", "\n", "}", "\n", "}" ]
// RequestOptions returns an Opt that applies the given set of options to every Client request.
[ "RequestOptions", "returns", "an", "Opt", "that", "applies", "the", "given", "set", "of", "options", "to", "every", "Client", "request", "." ]
ee67238bbd943c751ec0a5dffb09af2b0182d361
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v1/lib/httpcli/http.go#L486-L495